code
stringlengths
2
1.05M
'use strict'; const metasync = {}; module.exports = metasync; metasync.DataCollector = function( expected, // number of collect() calls expected timeout // collect timeout (optional) ) { this.expected = expected; this.timeout = timeout; this.count = 0; this.data = {}; this.errs = []; this.events = { error: null, timeout: null, done: null }; const collector = this; if (this.timeout) { this.timer = setTimeout(() => { const err = new Error('DataCollector timeout'); collector.emit('timeout', err, collector.data); }, timeout); } }; metasync.DataCollector.prototype.collect = function( // Push data to collector key, // key in result data data // value or error instance ) { this.count++; if (data instanceof Error) { this.errs[key] = data; this.emit('error', data, key); } else { this.data[key] = data; } if (this.expected === this.count) { if (this.timer) clearTimeout(this.timer); const errs = this.errs.length ? this.errs : null; this.emit('done', errs, this.data); } }; metasync.DataCollector.prototype.on = function( // DataCollector events: eventName, callback // on('error', function(err, key)) // on('timeout', function(err, data)) // on('done', function(errs, data)) // errs - hash of errors // data - hash of sucessfully received adta ) { if (eventName in this.events) { this.events[eventName] = callback; } }; metasync.DataCollector.prototype.emit = function( // Emit DataCollector events eventName, err, data ) { const event = this.events[eventName]; if (event) event(err, data); }; metasync.KeyCollector = function( // Key Collector keys, // array of keys, example: ['config', 'users', 'cities'] timeout // collect timeout (optional) ) { this.isDone = false; this.keys = keys; this.expected = keys.length; this.count = 0; this.timeout = timeout; this.data = {}; this.errs = []; this.events = { error: null, timeout: null, done: null }; const collector = this; if (this.timeout) { this.timer = setTimeout(() => { const err = new Error('KeyCollector timeout'); collector.emit('timeout', err, collector.data); }, timeout); } }; metasync.KeyCollector.prototype.collect = function( key, data ) { if (this.keys.includes(key)) { this.count++; if (data instanceof Error) { this.errs[key] = data; this.emit('error', data, key); } else { this.data[key] = data; } if (this.expected === this.count) { if (this.timer) clearTimeout(this.timer); const errs = this.errs.length ? this.errs : null; this.emit('done', errs, this.data); } } }; metasync.KeyCollector.prototype.stop = function() { }; metasync.KeyCollector.prototype.pause = function() { }; metasync.KeyCollector.prototype.resume = function() { }; metasync.KeyCollector.prototype.on = function( // KeyCollector events: eventName, callback // on('error', function(err, key)) // on('timeout', function(err, data)) // on('done', function(errs, data)) // on('pause', function()) // on('resume', function()) ) { if (eventName in this.events) { this.events[eventName] = callback; } }; metasync.KeyCollector.prototype.emit = function( // Emit DataCollector events eventName, err, data ) { const event = this.events[eventName]; if (event) event(err, data); };
/** * @fileoverview Tests for eslint object. * @author Nicholas C. Zakas */ /* globals window */ "use strict"; //------------------------------------------------------------------------------ // Helper //------------------------------------------------------------------------------ /** * To make sure this works in both browsers and Node.js * @param {string} name Name of the module to require * @param {Object} windowName name of the window * @returns {Object} Required object * @private */ function compatRequire(name, windowName) { if (typeof window === "object") { return window[windowName || name]; } if (typeof require === "function") { return require(name); } throw new Error(`Cannot find object '${name}'.`); } //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const assert = compatRequire("chai").assert, sinon = compatRequire("sinon"), path = compatRequire("path"), Linter = compatRequire("../../lib/linter", "eslint"); //------------------------------------------------------------------------------ // Constants //------------------------------------------------------------------------------ const TEST_CODE = "var answer = 6 * 7;", BROKEN_TEST_CODE = "var;"; //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ /** * Get variables in the current scope * @param {Object} scope current scope * @param {string} name name of the variable to look for * @returns {ASTNode|null} The variable object * @private */ function getVariable(scope, name) { return scope.variables.find(v => v.name === name) || null; } //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ describe("Linter", () => { const filename = "filename.js"; let sandbox, linter; beforeEach(() => { linter = new Linter(); sandbox = sinon.sandbox.create(); }); afterEach(() => { sandbox.verifyAndRestore(); }); describe("Static Members", () => { describe("version", () => { it("should return same version as instance property", () => { assert.strictEqual(Linter.version, linter.version); }); }); }); describe("when using events", () => { const code = TEST_CODE; it("an error should be thrown when an error occurs inside of an event handler", () => { const config = { rules: { checker: "error" } }; linter.defineRule("checker", () => ({ Program() { throw new Error("Intentional error."); } })); assert.throws(() => { linter.verify(code, config, filename); }, "Intentional error."); }); it("does not call rule listeners with a `this` value", () => { const spy = sandbox.spy(); linter.defineRule("checker", () => ({ Program: spy })); linter.verify("foo", { rules: { checker: "error" } }); assert(spy.calledOnce); assert.strictEqual(spy.firstCall.thisValue, void 0); }); it("does not allow listeners to use special EventEmitter values", () => { const spy = sandbox.spy(); linter.defineRule("checker", () => ({ newListener: spy })); linter.verify("foo", { rules: { checker: "error", "no-undef": "error" } }); assert(spy.notCalled); }); it("has all the `parent` properties on nodes when the rule listeners are created", () => { const spy = sandbox.spy(context => { const ast = context.getSourceCode().ast; assert.strictEqual(ast.body[0].parent, ast); assert.strictEqual(ast.body[0].expression.parent, ast.body[0]); assert.strictEqual(ast.body[0].expression.left.parent, ast.body[0].expression); assert.strictEqual(ast.body[0].expression.right.parent, ast.body[0].expression); return {}; }); linter.defineRule("checker", spy); linter.verify("foo + bar", { rules: { checker: "error" } }); assert(spy.calledOnce); }); }); describe("context.getSourceLines()", () => { it("should get proper lines when using \\n as a line break", () => { const code = "a;\nb;"; const spy = sandbox.spy(context => { assert.deepStrictEqual(context.getSourceLines(), ["a;", "b;"]); return {}; }); linter.defineRule("checker", spy); linter.verify(code, { rules: { checker: "error" } }); assert(spy.calledOnce); }); it("should get proper lines when using \\r\\n as a line break", () => { const code = "a;\r\nb;"; const spy = sandbox.spy(context => { assert.deepStrictEqual(context.getSourceLines(), ["a;", "b;"]); return {}; }); linter.defineRule("checker", spy); linter.verify(code, { rules: { checker: "error" } }); assert(spy.calledOnce); }); it("should get proper lines when using \\r as a line break", () => { const code = "a;\rb;"; const spy = sandbox.spy(context => { assert.deepStrictEqual(context.getSourceLines(), ["a;", "b;"]); return {}; }); linter.defineRule("checker", spy); linter.verify(code, { rules: { checker: "error" } }); assert(spy.calledOnce); }); it("should get proper lines when using \\u2028 as a line break", () => { const code = "a;\u2028b;"; const spy = sandbox.spy(context => { assert.deepStrictEqual(context.getSourceLines(), ["a;", "b;"]); return {}; }); linter.defineRule("checker", spy); linter.verify(code, { rules: { checker: "error" } }); assert(spy.calledOnce); }); it("should get proper lines when using \\u2029 as a line break", () => { const code = "a;\u2029b;"; const spy = sandbox.spy(context => { assert.deepStrictEqual(context.getSourceLines(), ["a;", "b;"]); return {}; }); linter.defineRule("checker", spy); linter.verify(code, { rules: { checker: "error" } }); assert(spy.calledOnce); }); }); describe("getSourceCode()", () => { const code = TEST_CODE; it("should retrieve SourceCode object after reset", () => { linter.verify(code, {}, filename, true); const sourceCode = linter.getSourceCode(); assert.isObject(sourceCode); assert.strictEqual(sourceCode.text, code); assert.isObject(sourceCode.ast); }); it("should retrieve SourceCode object without reset", () => { linter.verify(code, {}, filename); const sourceCode = linter.getSourceCode(); assert.isObject(sourceCode); assert.strictEqual(sourceCode.text, code); assert.isObject(sourceCode.ast); }); }); describe("context.getSource()", () => { const code = TEST_CODE; it("should retrieve all text when used without parameters", () => { const config = { rules: { checker: "error" } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { assert.strictEqual(context.getSource(), TEST_CODE); }); return { Program: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); it("should retrieve all text for root node", () => { const config = { rules: { checker: "error" } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(node => { assert.strictEqual(context.getSource(node), TEST_CODE); }); return { Program: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); it("should clamp to valid range when retrieving characters before start of source", () => { const config = { rules: { checker: "error" } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(node => { assert.strictEqual(context.getSource(node, 2, 0), TEST_CODE); }); return { Program: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); it("should retrieve all text for binary expression", () => { const config = { rules: { checker: "error" } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(node => { assert.strictEqual(context.getSource(node), "6 * 7"); }); return { BinaryExpression: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); it("should retrieve all text plus two characters before for binary expression", () => { const config = { rules: { checker: "error" } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(node => { assert.strictEqual(context.getSource(node, 2), "= 6 * 7"); }); return { BinaryExpression: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); it("should retrieve all text plus one character after for binary expression", () => { const config = { rules: { checker: "error" } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(node => { assert.strictEqual(context.getSource(node, 0, 1), "6 * 7;"); }); return { BinaryExpression: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); it("should retrieve all text plus two characters before and one character after for binary expression", () => { const config = { rules: { checker: "error" } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(node => { assert.strictEqual(context.getSource(node, 2, 1), "= 6 * 7;"); }); return { BinaryExpression: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); }); describe("when calling context.getAncestors", () => { const code = TEST_CODE; it("should retrieve all ancestors when used", () => { const config = { rules: { checker: "error" } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const ancestors = context.getAncestors(); assert.strictEqual(ancestors.length, 3); }); return { BinaryExpression: spy }; }); linter.verify(code, config, filename, true); assert(spy && spy.calledOnce); }); it("should retrieve empty ancestors for root node", () => { const config = { rules: { checker: "error" } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const ancestors = context.getAncestors(); assert.strictEqual(ancestors.length, 0); }); return { Program: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); }); describe("when calling context.getNodeByRangeIndex", () => { const code = TEST_CODE; it("should retrieve a node starting at the given index", () => { const config = { rules: { checker: "error" } }; const spy = sandbox.spy(context => { assert.strictEqual(context.getNodeByRangeIndex(4).type, "Identifier"); return {}; }); linter.defineRule("checker", spy); linter.verify(code, config); assert(spy.calledOnce); }); it("should retrieve a node containing the given index", () => { const config = { rules: { checker: "error" } }; const spy = sandbox.spy(context => { assert.strictEqual(context.getNodeByRangeIndex(6).type, "Identifier"); return {}; }); linter.defineRule("checker", spy); linter.verify(code, config); assert(spy.calledOnce); }); it("should retrieve a node that is exactly the given index", () => { const config = { rules: { checker: "error" } }; const spy = sandbox.spy(context => { const node = context.getNodeByRangeIndex(13); assert.strictEqual(node.type, "Literal"); assert.strictEqual(node.value, 6); return {}; }); linter.defineRule("checker", spy); linter.verify(code, config); assert(spy.calledOnce); }); it("should retrieve a node ending with the given index", () => { const config = { rules: { checker: "error" } }; const spy = sandbox.spy(context => { assert.strictEqual(context.getNodeByRangeIndex(9).type, "Identifier"); return {}; }); linter.defineRule("checker", spy); linter.verify(code, config); assert(spy.calledOnce); }); it("should retrieve the deepest node containing the given index", () => { const config = { rules: { checker: "error" } }; const spy = sandbox.spy(context => { const node1 = context.getNodeByRangeIndex(14); assert.strictEqual(node1.type, "BinaryExpression"); const node2 = context.getNodeByRangeIndex(3); assert.strictEqual(node2.type, "VariableDeclaration"); return {}; }); linter.defineRule("checker", spy); linter.verify(code, config); assert(spy.calledOnce); }); it("should return null if the index is outside the range of any node", () => { const config = { rules: { checker: "error" } }; const spy = sandbox.spy(context => { const node1 = context.getNodeByRangeIndex(-1); assert.isNull(node1); const node2 = context.getNodeByRangeIndex(-99); assert.isNull(node2); return {}; }); linter.defineRule("checker", spy); linter.verify(code, config); assert(spy.calledOnce); }); }); describe("when calling context.getScope", () => { const code = "function foo() { q: for(;;) { break q; } } function bar () { var q = t; } var baz = (() => { return 1; });"; it("should retrieve the global scope correctly from a Program", () => { const config = { rules: { checker: "error" }, parserOptions: { ecmaVersion: 6 } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(); assert.strictEqual(scope.type, "global"); }); return { Program: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); it("should retrieve the function scope correctly from a FunctionDeclaration", () => { const config = { rules: { checker: "error" }, parserOptions: { ecmaVersion: 6 } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(); assert.strictEqual(scope.type, "function"); }); return { FunctionDeclaration: spy }; }); linter.verify(code, config); assert(spy && spy.calledTwice); }); it("should retrieve the function scope correctly from a LabeledStatement", () => { const config = { rules: { checker: "error" }, parserOptions: { ecmaVersion: 6 } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(); assert.strictEqual(scope.type, "function"); assert.strictEqual(scope.block.id.name, "foo"); }); return { LabeledStatement: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); it("should retrieve the function scope correctly from within an ArrowFunctionExpression", () => { const config = { rules: { checker: "error" }, parserOptions: { ecmaVersion: 6 } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(); assert.strictEqual(scope.type, "function"); assert.strictEqual(scope.block.type, "ArrowFunctionExpression"); }); return { ReturnStatement: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); it("should retrieve the function scope correctly from within an SwitchStatement", () => { const config = { rules: { checker: "error" }, parserOptions: { ecmaVersion: 6 } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(); assert.strictEqual(scope.type, "switch"); assert.strictEqual(scope.block.type, "SwitchStatement"); }); return { SwitchStatement: spy }; }); linter.verify("switch(foo){ case 'a': var b = 'foo'; }", config); assert(spy && spy.calledOnce); }); it("should retrieve the function scope correctly from within a BlockStatement", () => { const config = { rules: { checker: "error" }, parserOptions: { ecmaVersion: 6 } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(); assert.strictEqual(scope.type, "block"); assert.strictEqual(scope.block.type, "BlockStatement"); }); return { BlockStatement: spy }; }); linter.verify("var x; {let y = 1}", config); assert(spy && spy.calledOnce); }); it("should retrieve the function scope correctly from within a nested block statement", () => { const config = { rules: { checker: "error" }, parserOptions: { ecmaVersion: 6 } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(); assert.strictEqual(scope.type, "block"); assert.strictEqual(scope.block.type, "BlockStatement"); }); return { BlockStatement: spy }; }); linter.verify("if (true) { let x = 1 }", config); assert(spy && spy.calledOnce); }); it("should retrieve the function scope correctly from within a FunctionDeclaration", () => { const config = { rules: { checker: "error" }, parserOptions: { ecmaVersion: 6 } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(); assert.strictEqual(scope.type, "function"); assert.strictEqual(scope.block.type, "FunctionDeclaration"); }); return { FunctionDeclaration: spy }; }); linter.verify("function foo() {}", config); assert(spy && spy.calledOnce); }); it("should retrieve the function scope correctly from within a FunctionExpression", () => { const config = { rules: { checker: "error" }, parserOptions: { ecmaVersion: 6 } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(); assert.strictEqual(scope.type, "function"); assert.strictEqual(scope.block.type, "FunctionExpression"); }); return { FunctionExpression: spy }; }); linter.verify("(function foo() {})();", config); assert(spy && spy.calledOnce); }); it("should retrieve the catch scope correctly from within a CatchClause", () => { const config = { rules: { checker: "error" }, parserOptions: { ecmaVersion: 6 } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(); assert.strictEqual(scope.type, "catch"); assert.strictEqual(scope.block.type, "CatchClause"); }); return { CatchClause: spy }; }); linter.verify("try {} catch (err) {}", config); assert(spy && spy.calledOnce); }); it("should retrieve module scope correctly from an ES6 module", () => { const config = { rules: { checker: "error" }, parserOptions: { sourceType: "module" } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(); assert.strictEqual(scope.type, "module"); }); return { AssignmentExpression: spy }; }); linter.verify("var foo = {}; foo.bar = 1;", config); assert(spy && spy.calledOnce); }); it("should retrieve function scope correctly when globalReturn is true", () => { const config = { rules: { checker: "error" }, parserOptions: { ecmaFeatures: { globalReturn: true } } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(); assert.strictEqual(scope.type, "function"); }); return { AssignmentExpression: spy }; }); linter.verify("var foo = {}; foo.bar = 1;", config); assert(spy && spy.calledOnce); }); }); describe("marking variables as used", () => { it("should mark variables in current scope as used", () => { const code = "var a = 1, b = 2;"; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { assert.isTrue(context.markVariableAsUsed("a")); const scope = context.getScope(); assert.isTrue(getVariable(scope, "a").eslintUsed); assert.notOk(getVariable(scope, "b").eslintUsed); }); return { "Program:exit": spy }; }); linter.verify(code, { rules: { checker: "error" } }); assert(spy && spy.calledOnce); }); it("should mark variables in function args as used", () => { const code = "function abc(a, b) { return 1; }"; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { assert.isTrue(context.markVariableAsUsed("a")); const scope = context.getScope(); assert.isTrue(getVariable(scope, "a").eslintUsed); assert.notOk(getVariable(scope, "b").eslintUsed); }); return { ReturnStatement: spy }; }); linter.verify(code, { rules: { checker: "error" } }); assert(spy && spy.calledOnce); }); it("should mark variables in higher scopes as used", () => { const code = "var a, b; function abc() { return 1; }"; let returnSpy, exitSpy; linter.defineRule("checker", context => { returnSpy = sandbox.spy(() => { assert.isTrue(context.markVariableAsUsed("a")); }); exitSpy = sandbox.spy(() => { const scope = context.getScope(); assert.isTrue(getVariable(scope, "a").eslintUsed); assert.notOk(getVariable(scope, "b").eslintUsed); }); return { ReturnStatement: returnSpy, "Program:exit": exitSpy }; }); linter.verify(code, { rules: { checker: "error" } }); assert(returnSpy && returnSpy.calledOnce); assert(exitSpy && exitSpy.calledOnce); }); it("should mark variables in Node.js environment as used", () => { const code = "var a = 1, b = 2;"; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const globalScope = context.getScope(), childScope = globalScope.childScopes[0]; assert.isTrue(context.markVariableAsUsed("a")); assert.isTrue(getVariable(childScope, "a").eslintUsed); assert.isUndefined(getVariable(childScope, "b").eslintUsed); }); return { "Program:exit": spy }; }); linter.verify(code, { rules: { checker: "error" }, env: { node: true } }); assert(spy && spy.calledOnce); }); it("should mark variables in modules as used", () => { const code = "var a = 1, b = 2;"; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const globalScope = context.getScope(), childScope = globalScope.childScopes[0]; assert.isTrue(context.markVariableAsUsed("a")); assert.isTrue(getVariable(childScope, "a").eslintUsed); assert.isUndefined(getVariable(childScope, "b").eslintUsed); }); return { "Program:exit": spy }; }); linter.verify(code, { rules: { checker: "error" }, parserOptions: { sourceType: "module" } }, filename, true); assert(spy && spy.calledOnce); }); it("should return false if the given variable is not found", () => { const code = "var a = 1, b = 2;"; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { assert.isFalse(context.markVariableAsUsed("c")); }); return { "Program:exit": spy }; }); linter.verify(code, { rules: { checker: "error" } }); assert(spy && spy.calledOnce); }); }); describe("when evaluating code", () => { const code = TEST_CODE; it("events for each node type should fire", () => { const config = { rules: { checker: "error" } }; // spies for various AST node types const spyLiteral = sinon.spy(), spyVariableDeclarator = sinon.spy(), spyVariableDeclaration = sinon.spy(), spyIdentifier = sinon.spy(), spyBinaryExpression = sinon.spy(); linter.defineRule("checker", () => ({ Literal: spyLiteral, VariableDeclarator: spyVariableDeclarator, VariableDeclaration: spyVariableDeclaration, Identifier: spyIdentifier, BinaryExpression: spyBinaryExpression })); const messages = linter.verify(code, config, filename, true); assert.strictEqual(messages.length, 0); sinon.assert.calledOnce(spyVariableDeclaration); sinon.assert.calledOnce(spyVariableDeclarator); sinon.assert.calledOnce(spyIdentifier); sinon.assert.calledTwice(spyLiteral); sinon.assert.calledOnce(spyBinaryExpression); }); it("should throw an error if a rule reports a problem without a message", () => { linter.defineRule("invalid-report", context => ({ Program(node) { context.report({ node }); } })); assert.throws( () => linter.verify("foo", { rules: { "invalid-report": "error" } }), TypeError, "Missing `message` property in report() call; add a message that describes the linting problem." ); }); }); describe("when config has shared settings for rules", () => { const code = "test-rule"; it("should pass settings to all rules", () => { linter.defineRule(code, context => ({ Literal(node) { context.report(node, context.settings.info); } })); const config = { rules: {}, settings: { info: "Hello" } }; config.rules[code] = 1; const messages = linter.verify("0", config, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].message, "Hello"); }); it("should not have any settings if they were not passed in", () => { linter.defineRule(code, context => ({ Literal(node) { if (Object.getOwnPropertyNames(context.settings).length !== 0) { context.report(node, "Settings should be empty"); } } })); const config = { rules: {} }; config.rules[code] = 1; const messages = linter.verify("0", config, filename); assert.strictEqual(messages.length, 0); }); }); describe("when config has parseOptions", () => { it("should pass ecmaFeatures to all rules when provided on config", () => { const parserOptions = { ecmaFeatures: { jsx: true, globalReturn: true } }; linter.defineRule("test-rule", sandbox.mock().withArgs( sinon.match({ parserOptions }) ).returns({})); const config = { rules: { "test-rule": 2 }, parserOptions }; linter.verify("0", config, filename); }); it("should pass parserOptions to all rules when default parserOptions is used", () => { const parserOptions = {}; linter.defineRule("test-rule", sandbox.mock().withArgs( sinon.match({ parserOptions }) ).returns({})); const config = { rules: { "test-rule": 2 } }; linter.verify("0", config, filename); }); }); describe("when a custom parser is defined using defineParser", () => { it("should be able to define a custom parser", () => { const parser = { parseForESLint: function parse(code, options) { return { ast: require("espree").parse(code, options), services: { test: { getMessage() { return "Hi!"; } } } }; } }; linter.defineParser("test-parser", parser); const config = { rules: {}, parser: "test-parser" }; const messages = linter.verify("0", config, filename); assert.strictEqual(messages.length, 0); }); }); describe("when config has parser", () => { // custom parser unsupported in browser, only test in Node if (typeof window === "undefined") { it("should pass parser as parserPath to all rules when provided on config", () => { const alternateParser = "esprima"; linter.defineRule("test-rule", sandbox.mock().withArgs( sinon.match({ parserPath: alternateParser }) ).returns({})); const config = { rules: { "test-rule": 2 }, parser: alternateParser }; linter.verify("0", config, filename); }); it("should use parseForESLint() in custom parser when custom parser is specified", () => { const alternateParser = path.resolve(__dirname, "../fixtures/parsers/enhanced-parser.js"); const config = { rules: {}, parser: alternateParser }; const messages = linter.verify("0", config, filename); assert.strictEqual(messages.length, 0); }); it("should expose parser services when using parseForESLint() and services are specified", () => { const alternateParser = path.resolve(__dirname, "../fixtures/parsers/enhanced-parser.js"); linter.defineRule("test-service-rule", context => ({ Literal(node) { context.report({ node, message: context.parserServices.test.getMessage() }); } })); const config = { rules: { "test-service-rule": 2 }, parser: alternateParser }; const messages = linter.verify("0", config, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].message, "Hi!"); }); it("should use the same parserServices if source code object is reused", () => { const parser = path.resolve(__dirname, "../fixtures/parsers/enhanced-parser.js"); linter.defineRule("test-service-rule", context => ({ Literal(node) { context.report({ node, message: context.parserServices.test.getMessage() }); } })); const config = { rules: { "test-service-rule": 2 }, parser }; const messages = linter.verify("0", config, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].message, "Hi!"); const messages2 = linter.verify(linter.getSourceCode(), config, filename); assert.strictEqual(messages2.length, 1); assert.strictEqual(messages2[0].message, "Hi!"); }); } it("should pass parser as parserPath to all rules when default parser is used", () => { linter.defineRule("test-rule", sandbox.mock().withArgs( sinon.match({ parserPath: "espree" }) ).returns({})); const config = { rules: { "test-rule": 2 } }; linter.verify("0", config, filename); }); }); describe("when passing in configuration values for rules", () => { const code = "var answer = 6 * 7"; it("should be configurable by only setting the integer value", () => { const rule = "semi", config = { rules: {} }; config.rules[rule] = 1; const messages = linter.verify(code, config, filename, true); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, rule); }); it("should be configurable by only setting the string value", () => { const rule = "semi", config = { rules: {} }; config.rules[rule] = "warn"; const messages = linter.verify(code, config, filename, true); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].severity, 1); assert.strictEqual(messages[0].ruleId, rule); }); it("should be configurable by passing in values as an array", () => { const rule = "semi", config = { rules: {} }; config.rules[rule] = [1]; const messages = linter.verify(code, config, filename, true); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, rule); }); it("should be configurable by passing in string value as an array", () => { const rule = "semi", config = { rules: {} }; config.rules[rule] = ["warn"]; const messages = linter.verify(code, config, filename, true); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].severity, 1); assert.strictEqual(messages[0].ruleId, rule); }); it("should not be configurable by setting other value", () => { const rule = "semi", config = { rules: {} }; config.rules[rule] = "1"; const messages = linter.verify(code, config, filename, true); assert.strictEqual(messages.length, 0); }); it("should process empty config", () => { const config = {}; const messages = linter.verify(code, config, filename, true); assert.strictEqual(messages.length, 0); }); }); describe("when evaluating code containing /*global */ and /*globals */ blocks", () => { const code = "/*global a b:true c:false*/ function foo() {} /*globals d:true*/"; it("variables should be available in global scope", () => { const config = { rules: { checker: "error" } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(); const a = getVariable(scope, "a"), b = getVariable(scope, "b"), c = getVariable(scope, "c"), d = getVariable(scope, "d"); assert.strictEqual(a.name, "a"); assert.strictEqual(a.writeable, false); assert.strictEqual(b.name, "b"); assert.strictEqual(b.writeable, true); assert.strictEqual(c.name, "c"); assert.strictEqual(c.writeable, false); assert.strictEqual(d.name, "d"); assert.strictEqual(d.writeable, true); }); return { Program: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); }); describe("when evaluating code containing a /*global */ block with sloppy whitespace", () => { const code = "/* global a b : true c: false*/"; it("variables should be available in global scope", () => { const config = { rules: { checker: "error" } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(), a = getVariable(scope, "a"), b = getVariable(scope, "b"), c = getVariable(scope, "c"); assert.strictEqual(a.name, "a"); assert.strictEqual(a.writeable, false); assert.strictEqual(b.name, "b"); assert.strictEqual(b.writeable, true); assert.strictEqual(c.name, "c"); assert.strictEqual(c.writeable, false); }); return { Program: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); }); describe("when evaluating code containing /*eslint-env */ block", () => { it("variables should be available in global scope", () => { const code = "/*eslint-env node*/ function f() {} /*eslint-env browser, foo*/"; const config = { rules: { checker: "error" } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(), exports = getVariable(scope, "exports"), window = getVariable(scope, "window"); assert.strictEqual(exports.writeable, true); assert.strictEqual(window.writeable, false); }); return { Program: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); }); describe("when evaluating code containing /*eslint-env */ block with sloppy whitespace", () => { const code = "/* eslint-env ,, node , no-browser ,, */"; it("variables should be available in global scope", () => { const config = { rules: { checker: "error" } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(), exports = getVariable(scope, "exports"), window = getVariable(scope, "window"); assert.strictEqual(exports.writeable, true); assert.strictEqual(window, null); }); return { Program: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); }); describe("when evaluating code containing /*exported */ block", () => { it("we should behave nicely when no matching variable is found", () => { const code = "/* exported horse */"; const config = { rules: {} }; linter.verify(code, config, filename, true); }); it("variables should be exported", () => { const code = "/* exported horse */\n\nvar horse = 'circus'"; const config = { rules: { checker: "error" } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(), horse = getVariable(scope, "horse"); assert.strictEqual(horse.eslintUsed, true); }); return { Program: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); it("undefined variables should not be exported", () => { const code = "/* exported horse */\n\nhorse = 'circus'"; const config = { rules: { checker: "error" } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(), horse = getVariable(scope, "horse"); assert.strictEqual(horse, null); }); return { Program: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); it("variables should be exported in strict mode", () => { const code = "/* exported horse */\n'use strict';\nvar horse = 'circus'"; const config = { rules: { checker: "error" } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(), horse = getVariable(scope, "horse"); assert.strictEqual(horse.eslintUsed, true); }); return { Program: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); it("variables should not be exported in the es6 module environment", () => { const code = "/* exported horse */\nvar horse = 'circus'"; const config = { rules: { checker: "error" }, parserOptions: { sourceType: "module" } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(), horse = getVariable(scope, "horse"); assert.strictEqual(horse, null); // there is no global scope at all }); return { Program: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); it("variables should not be exported when in the node environment", () => { const code = "/* exported horse */\nvar horse = 'circus'"; const config = { rules: { checker: "error" }, env: { node: true } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(), horse = getVariable(scope, "horse"); assert.strictEqual(horse, null); // there is no global scope at all }); return { Program: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); }); describe("when evaluating code containing a line comment", () => { const code = "//global a \n function f() {}"; it("should not introduce a global variable", () => { const config = { rules: { checker: "error" } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(); assert.strictEqual(getVariable(scope, "a"), null); }); return { Program: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); }); describe("when evaluating code containing normal block comments", () => { const code = "/**/ /*a*/ /*b:true*/ /*foo c:false*/"; it("should not introduce a global variable", () => { const config = { rules: { checker: "error" } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(); assert.strictEqual(getVariable(scope, "a"), null); assert.strictEqual(getVariable(scope, "b"), null); assert.strictEqual(getVariable(scope, "foo"), null); assert.strictEqual(getVariable(scope, "c"), null); }); return { Program: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); }); describe("when evaluating any code", () => { const code = "x"; it("builtin global variables should be available in the global scope", () => { const config = { rules: { checker: "error" } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(); assert.notStrictEqual(getVariable(scope, "Object"), null); assert.notStrictEqual(getVariable(scope, "Array"), null); assert.notStrictEqual(getVariable(scope, "undefined"), null); }); return { Program: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); it("ES6 global variables should not be available by default", () => { const config = { rules: { checker: "error" } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(); assert.strictEqual(getVariable(scope, "Promise"), null); assert.strictEqual(getVariable(scope, "Symbol"), null); assert.strictEqual(getVariable(scope, "WeakMap"), null); }); return { Program: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); it("ES6 global variables should be available in the es6 environment", () => { const config = { rules: { checker: "error" }, env: { es6: true } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(() => { const scope = context.getScope(); assert.notStrictEqual(getVariable(scope, "Promise"), null); assert.notStrictEqual(getVariable(scope, "Symbol"), null); assert.notStrictEqual(getVariable(scope, "WeakMap"), null); }); return { Program: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); }); describe("at any time", () => { const code = "new-rule"; it("can add a rule dynamically", () => { linter.defineRule(code, context => ({ Literal(node) { context.report(node, "message"); } })); const config = { rules: {} }; config.rules[code] = 1; const messages = linter.verify("0", config, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, code); assert.strictEqual(messages[0].nodeType, "Literal"); }); }); describe("at any time", () => { const code = ["new-rule-0", "new-rule-1"]; it("can add multiple rules dynamically", () => { const config = { rules: {} }; const newRules = {}; code.forEach(item => { config.rules[item] = 1; newRules[item] = function(context) { return { Literal(node) { context.report(node, "message"); } }; }; }); linter.defineRules(newRules); const messages = linter.verify("0", config, filename); assert.strictEqual(messages.length, code.length); code.forEach(item => { assert.ok(messages.some(message => message.ruleId === item)); }); messages.forEach(message => { assert.strictEqual(message.nodeType, "Literal"); }); }); }); describe("at any time", () => { const code = "filename-rule"; it("has access to the filename", () => { linter.defineRule(code, context => ({ Literal(node) { context.report(node, context.getFilename()); } })); const config = { rules: {} }; config.rules[code] = 1; const messages = linter.verify("0", config, filename); assert.strictEqual(messages[0].message, filename); }); it("defaults filename to '<input>'", () => { linter.defineRule(code, context => ({ Literal(node) { context.report(node, context.getFilename()); } })); const config = { rules: {} }; config.rules[code] = 1; const messages = linter.verify("0", config); assert.strictEqual(messages[0].message, "<input>"); }); }); describe("when evaluating code with comments to enable rules", () => { it("should report a violation", () => { const code = "/*eslint no-alert:1*/ alert('test');"; const config = { rules: {} }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, "no-alert"); assert.strictEqual(messages[0].message, "Unexpected alert."); assert.include(messages[0].nodeType, "CallExpression"); }); it("rules should not change initial config", () => { const config = { rules: { strict: 2 } }; const codeA = "/*eslint strict: 0*/ function bar() { return 2; }"; const codeB = "function foo() { return 1; }"; let messages = linter.verify(codeA, config, filename, false); assert.strictEqual(messages.length, 0); messages = linter.verify(codeB, config, filename, false); assert.strictEqual(messages.length, 1); }); it("rules should not change initial config", () => { const config = { rules: { quotes: [2, "double"] } }; const codeA = "/*eslint quotes: 0*/ function bar() { return '2'; }"; const codeB = "function foo() { return '1'; }"; let messages = linter.verify(codeA, config, filename, false); assert.strictEqual(messages.length, 0); messages = linter.verify(codeB, config, filename, false); assert.strictEqual(messages.length, 1); }); it("rules should not change initial config", () => { const config = { rules: { quotes: [2, "double"] } }; const codeA = "/*eslint quotes: [0, \"single\"]*/ function bar() { return '2'; }"; const codeB = "function foo() { return '1'; }"; let messages = linter.verify(codeA, config, filename, false); assert.strictEqual(messages.length, 0); messages = linter.verify(codeB, config, filename, false); assert.strictEqual(messages.length, 1); }); it("rules should not change initial config", () => { const config = { rules: { "no-unused-vars": [2, { vars: "all" }] } }; const codeA = "/*eslint no-unused-vars: [0, {\"vars\": \"local\"}]*/ var a = 44;"; const codeB = "var b = 55;"; let messages = linter.verify(codeA, config, filename, false); assert.strictEqual(messages.length, 0); messages = linter.verify(codeB, config, filename, false); assert.strictEqual(messages.length, 1); }); }); describe("when evaluating code with invalid comments to enable rules", () => { it("should report a violation when the config is not a valid rule configuration", () => { assert.deepStrictEqual( linter.verify("/*eslint no-alert:true*/ alert('test');", {}), [ { severity: 2, ruleId: "no-alert", message: "Configuration for rule \"no-alert\" is invalid:\n\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed 'true').\n", line: 1, column: 1, endLine: 1, endColumn: 25, nodeType: null } ] ); }); it("should report a violation when the config violates a rule's schema", () => { assert.deepStrictEqual( linter.verify("/* eslint no-alert: [error, {nonExistentPropertyName: true}]*/", {}), [ { severity: 2, ruleId: "no-alert", message: "Configuration for rule \"no-alert\" is invalid:\n\tValue [{\"nonExistentPropertyName\":true}] should NOT have more than 0 items.\n", line: 1, column: 1, endLine: 1, endColumn: 63, nodeType: null } ] ); }); }); describe("when evaluating code with comments to disable rules", () => { const code = "/*eslint no-alert:0*/ alert('test');"; it("should not report a violation", () => { const config = { rules: { "no-alert": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); }); describe("when evaluating code with comments to enable multiple rules", () => { const code = "/*eslint no-alert:1 no-console:1*/ alert('test'); console.log('test');"; it("should report a violation", () => { const config = { rules: {} }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 2); assert.strictEqual(messages[0].ruleId, "no-alert"); assert.strictEqual(messages[0].message, "Unexpected alert."); assert.include(messages[0].nodeType, "CallExpression"); assert.strictEqual(messages[1].ruleId, "no-console"); }); }); describe("when evaluating code with comments to enable and disable multiple rules", () => { const code = "/*eslint no-alert:1 no-console:0*/ alert('test'); console.log('test');"; it("should report a violation", () => { const config = { rules: { "no-console": 1, "no-alert": 0 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, "no-alert"); assert.strictEqual(messages[0].message, "Unexpected alert."); assert.include(messages[0].nodeType, "CallExpression"); }); }); describe("when evaluating code with comments to disable and enable configurable rule as part of plugin", () => { beforeEach(() => { linter.defineRule("test-plugin/test-rule", context => ({ Literal(node) { if (node.value === "trigger violation") { context.report(node, "Reporting violation."); } } })); }); it("should not report a violation when inline comment enables plugin rule and there's no violation", () => { const config = { rules: {} }; const code = "/*eslint test-plugin/test-rule: 2*/ var a = \"no violation\";"; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); it("should not report a violation when inline comment disables plugin rule", () => { const code = "/*eslint test-plugin/test-rule:0*/ var a = \"trigger violation\""; const config = { rules: { "test-plugin/test-rule": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); it("should report a violation when the report is right before the comment", () => { const code = " /* eslint-disable */ "; linter.defineRule("checker", context => ({ Program() { context.report({ loc: { line: 1, column: 0 }, message: "foo" }); } })); const problems = linter.verify(code, { rules: { checker: "error" } }); assert.strictEqual(problems.length, 1); assert.strictEqual(problems[0].message, "foo"); }); it("should not report a violation when the report is right at the start of the comment", () => { const code = " /* eslint-disable */ "; linter.defineRule("checker", context => ({ Program() { context.report({ loc: { line: 1, column: 1 }, message: "foo" }); } })); const problems = linter.verify(code, { rules: { checker: "error" } }); assert.strictEqual(problems.length, 0); }); it("rules should not change initial config", () => { const config = { rules: { "test-plugin/test-rule": 2 } }; const codeA = "/*eslint test-plugin/test-rule: 0*/ var a = \"trigger violation\";"; const codeB = "var a = \"trigger violation\";"; let messages = linter.verify(codeA, config, filename, false); assert.strictEqual(messages.length, 0); messages = linter.verify(codeB, config, filename, false); assert.strictEqual(messages.length, 1); }); }); describe("when evaluating code with comments to enable and disable all reporting", () => { it("should report a violation", () => { const code = [ "/*eslint-disable */", "alert('test');", "/*eslint-enable */", "alert('test');" ].join("\n"); const config = { rules: { "no-alert": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, "no-alert"); assert.strictEqual(messages[0].message, "Unexpected alert."); assert.include(messages[0].nodeType, "CallExpression"); assert.strictEqual(messages[0].line, 4); }); it("should not report a violation", () => { const code = [ "/*eslint-disable */", "alert('test');", "alert('test');" ].join("\n"); const config = { rules: { "no-alert": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); it("should not report a violation", () => { const code = [ " alert('test1');/*eslint-disable */\n", "alert('test');", " alert('test');\n", "/*eslint-enable */alert('test2');" ].join(""); const config = { rules: { "no-alert": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 2); assert.strictEqual(messages[0].column, 21); assert.strictEqual(messages[1].column, 19); }); it("should report a violation", () => { const code = [ "/*eslint-disable */", "alert('test');", "/*eslint-disable */", "alert('test');", "/*eslint-enable*/", "alert('test');", "/*eslint-enable*/" ].join("\n"); const config = { rules: { "no-alert": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 1); }); it("should not report a violation", () => { const code = [ "/*eslint-disable */", "(function(){ var b = 44;})()", "/*eslint-enable */;any();" ].join("\n"); const config = { rules: { "no-unused-vars": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); it("should not report a violation", () => { const code = [ "(function(){ /*eslint-disable */ var b = 44;})()", "/*eslint-enable */;any();" ].join("\n"); const config = { rules: { "no-unused-vars": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); }); describe("when evaluating code with comments to ignore reporting on specific rules on a specific line", () => { describe("eslint-disable-line", () => { it("should report a violation", () => { const code = [ "alert('test'); // eslint-disable-line no-alert", "console.log('test');" // here ].join("\n"); const config = { rules: { "no-alert": 1, "no-console": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, "no-console"); }); it("should report a violation", () => { const code = [ "alert('test'); // eslint-disable-line no-alert", "console.log('test'); // eslint-disable-line no-console", "alert('test');" // here ].join("\n"); const config = { rules: { "no-alert": 1, "no-console": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, "no-alert"); }); it("should report a violation if eslint-disable-line in a block comment is not on a single line", () => { const code = [ "/* eslint-disable-line", "*", "*/ console.log('test');" // here ].join("\n"); const config = { rules: { "no-console": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 2); assert.strictEqual(messages[1].ruleId, "no-console"); }); it("should not disable rule and add an extra report if eslint-disable-line in a block comment is not on a single line", () => { const code = [ "alert('test'); /* eslint-disable-line ", "no-alert */" ].join("\n"); const config = { rules: { "no-alert": 1 } }; const messages = linter.verify(code, config); assert.deepStrictEqual(messages, [ { ruleId: "no-alert", severity: 1, line: 1, column: 1, endLine: 1, endColumn: 14, message: "Unexpected alert.", messageId: "unexpected", nodeType: "CallExpression" }, { ruleId: null, severity: 2, message: "eslint-disable-line comment should not span multiple lines.", line: 1, column: 16, endLine: 2, endColumn: 12, nodeType: null } ]); }); it("should not report a violation for eslint-disable-line in block comment", () => { const code = [ "alert('test'); // eslint-disable-line no-alert", "alert('test'); /*eslint-disable-line no-alert*/" ].join("\n"); const config = { rules: { "no-alert": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); it("should not report a violation", () => { const code = [ "alert('test'); // eslint-disable-line no-alert", "console.log('test'); // eslint-disable-line no-console" ].join("\n"); const config = { rules: { "no-alert": 1, "no-console": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); it("should not report a violation", () => { const code = [ "alert('test') // eslint-disable-line no-alert, quotes, semi", "console.log('test'); // eslint-disable-line" ].join("\n"); const config = { rules: { "no-alert": 1, quotes: [1, "double"], semi: [1, "always"], "no-console": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); it("should not report a violation", () => { const code = [ "alert('test') /* eslint-disable-line no-alert, quotes, semi */", "console.log('test'); /* eslint-disable-line */" ].join("\n"); const config = { rules: { "no-alert": 1, quotes: [1, "double"], semi: [1, "always"], "no-console": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); it("should ignore violations of multiple rules when specified in mixed comments", () => { const code = [ " alert(\"test\"); /* eslint-disable-line no-alert */ // eslint-disable-line quotes" ].join("\n"); const config = { rules: { "no-alert": 1, quotes: [1, "single"] } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); }); describe("eslint-disable-next-line", () => { it("should ignore violation of specified rule on next line", () => { const code = [ "// eslint-disable-next-line no-alert", "alert('test');", "console.log('test');" ].join("\n"); const config = { rules: { "no-alert": 1, "no-console": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, "no-console"); }); it("should ignore violation of specified rule if eslint-disable-next-line is a block comment", () => { const code = [ "/* eslint-disable-next-line no-alert */", "alert('test');", "console.log('test');" ].join("\n"); const config = { rules: { "no-alert": 1, "no-console": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, "no-console"); }); it("should ignore violation of specified rule if eslint-disable-next-line is a block comment", () => { const code = [ "/* eslint-disable-next-line no-alert */", "alert('test');" ].join("\n"); const config = { rules: { "no-alert": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); it("should not ignore violation if block comment is not on a single line", () => { const code = [ "/* eslint-disable-next-line", "no-alert */alert('test');" ].join("\n"); const config = { rules: { "no-alert": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 2); assert.strictEqual(messages[1].ruleId, "no-alert"); }); it("should ignore violations only of specified rule", () => { const code = [ "// eslint-disable-next-line no-console", "alert('test');", "console.log('test');" ].join("\n"); const config = { rules: { "no-alert": 1, "no-console": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 2); assert.strictEqual(messages[0].ruleId, "no-alert"); assert.strictEqual(messages[1].ruleId, "no-console"); }); it("should ignore violations of multiple rules when specified", () => { const code = [ "// eslint-disable-next-line no-alert, quotes", "alert(\"test\");", "console.log('test');" ].join("\n"); const config = { rules: { "no-alert": 1, quotes: [1, "single"], "no-console": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, "no-console"); }); it("should ignore violations of multiple rules when specified in mixed comments", () => { const code = [ "/* eslint-disable-next-line no-alert */ // eslint-disable-next-line quotes", "alert(\"test\");" ].join("\n"); const config = { rules: { "no-alert": 1, quotes: [1, "single"] } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); it("should ignore violations of only the specified rule on next line", () => { const code = [ "// eslint-disable-next-line quotes", "alert(\"test\");", "console.log('test');" ].join("\n"); const config = { rules: { "no-alert": 1, quotes: [1, "single"], "no-console": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 2); assert.strictEqual(messages[0].ruleId, "no-alert"); assert.strictEqual(messages[1].ruleId, "no-console"); }); it("should ignore violations of specified rule on next line only", () => { const code = [ "alert('test');", "// eslint-disable-next-line no-alert", "alert('test');", "console.log('test');" ].join("\n"); const config = { rules: { "no-alert": 1, "no-console": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 2); assert.strictEqual(messages[0].ruleId, "no-alert"); assert.strictEqual(messages[1].ruleId, "no-console"); }); it("should ignore all rule violations on next line if none specified", () => { const code = [ "// eslint-disable-next-line", "alert(\"test\");", "console.log('test')" ].join("\n"); const config = { rules: { semi: [1, "never"], quotes: [1, "single"], "no-alert": 1, "no-console": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, "no-console"); }); it("should ignore violations if eslint-disable-next-line is a block comment", () => { const code = [ "alert('test');", "/* eslint-disable-next-line no-alert */", "alert('test');", "console.log('test');" ].join("\n"); const config = { rules: { "no-alert": 1, "no-console": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 2); assert.strictEqual(messages[0].ruleId, "no-alert"); assert.strictEqual(messages[1].ruleId, "no-console"); }); it("should report a violation", () => { const code = [ "/* eslint-disable-next-line", "*", "*/", "console.log('test');" // here ].join("\n"); const config = { rules: { "no-alert": 1, "no-console": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 2); assert.strictEqual(messages[1].ruleId, "no-console"); }); it("should not ignore violations if comment is of the type Shebang", () => { const code = [ "#! eslint-disable-next-line no-alert", "alert('test');", "console.log('test');" ].join("\n"); const config = { rules: { "no-alert": 1, "no-console": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 2); assert.strictEqual(messages[0].ruleId, "no-alert"); assert.strictEqual(messages[1].ruleId, "no-console"); }); }); }); describe("when evaluating code with comments to enable and disable reporting of specific rules", () => { it("should report a violation", () => { const code = [ "/*eslint-disable no-alert */", "alert('test');", "console.log('test');" // here ].join("\n"); const config = { rules: { "no-alert": 1, "no-console": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, "no-console"); }); it("should report no violation", () => { const code = [ "/*eslint-disable no-unused-vars */", "var foo; // eslint-disable-line no-unused-vars", "var bar;", "/* eslint-enable no-unused-vars */" // here ].join("\n"); const config = { rules: { "no-unused-vars": 2 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); it("should report no violation", () => { const code = [ "var foo1; // eslint-disable-line no-unused-vars", "var foo2; // eslint-disable-line no-unused-vars", "var foo3; // eslint-disable-line no-unused-vars", "var foo4; // eslint-disable-line no-unused-vars", "var foo5; // eslint-disable-line no-unused-vars" ].join("\n"); const config = { rules: { "no-unused-vars": 2 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); it("should report no violation", () => { const code = [ "/* eslint-disable quotes */", "console.log(\"foo\");", "/* eslint-enable quotes */" ].join("\n"); const config = { rules: { quotes: 2 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); it("should report a violation", () => { const code = [ "/*eslint-disable no-alert, no-console */", "alert('test');", "console.log('test');", "/*eslint-enable*/", "alert('test');", // here "console.log('test');" // here ].join("\n"); const config = { rules: { "no-alert": 1, "no-console": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 2); assert.strictEqual(messages[0].ruleId, "no-alert"); assert.strictEqual(messages[0].line, 5); assert.strictEqual(messages[1].ruleId, "no-console"); assert.strictEqual(messages[1].line, 6); }); it("should report a violation", () => { const code = [ "/*eslint-disable no-alert */", "alert('test');", "console.log('test');", "/*eslint-enable no-console */", "alert('test');" // here ].join("\n"); const config = { rules: { "no-alert": 1, "no-console": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, "no-console"); }); it("should report a violation", () => { const code = [ "/*eslint-disable no-alert, no-console */", "alert('test');", "console.log('test');", "/*eslint-enable no-alert*/", "alert('test');", // here "console.log('test');" ].join("\n"); const config = { rules: { "no-alert": 1, "no-console": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, "no-alert"); assert.strictEqual(messages[0].line, 5); }); it("should report a violation", () => { const code = [ "/*eslint-disable no-alert */", "/*eslint-disable no-console */", "alert('test');", "console.log('test');", "/*eslint-enable */", "alert('test');", // here "console.log('test');", // here "/*eslint-enable */", "alert('test');", // here "console.log('test');", // here "/*eslint-enable*/" ].join("\n"); const config = { rules: { "no-alert": 1, "no-console": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 4); assert.strictEqual(messages[0].ruleId, "no-alert"); assert.strictEqual(messages[0].line, 6); assert.strictEqual(messages[1].ruleId, "no-console"); assert.strictEqual(messages[1].line, 7); assert.strictEqual(messages[2].ruleId, "no-alert"); assert.strictEqual(messages[2].line, 9); assert.strictEqual(messages[3].ruleId, "no-console"); assert.strictEqual(messages[3].line, 10); }); it("should report a violation", () => { const code = [ "/*eslint-disable no-alert, no-console */", "alert('test');", "console.log('test');", "/*eslint-enable no-alert */", "alert('test');", // here "console.log('test');", "/*eslint-enable no-console */", "alert('test');", // here "console.log('test');", // here "/*eslint-enable no-console */" ].join("\n"); const config = { rules: { "no-alert": 1, "no-console": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 3); assert.strictEqual(messages[0].ruleId, "no-alert"); assert.strictEqual(messages[0].line, 5); assert.strictEqual(messages[1].ruleId, "no-alert"); assert.strictEqual(messages[1].line, 8); assert.strictEqual(messages[2].ruleId, "no-console"); assert.strictEqual(messages[2].line, 9); }); it("should report a violation when severity is warn", () => { const code = [ "/*eslint-disable no-alert, no-console */", "alert('test');", "console.log('test');", "/*eslint-enable no-alert */", "alert('test');", // here "console.log('test');", "/*eslint-enable no-console */", "alert('test');", // here "console.log('test');", // here "/*eslint-enable no-console */" ].join("\n"); const config = { rules: { "no-alert": "warn", "no-console": "warn" } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 3); assert.strictEqual(messages[0].ruleId, "no-alert"); assert.strictEqual(messages[0].line, 5); assert.strictEqual(messages[1].ruleId, "no-alert"); assert.strictEqual(messages[1].line, 8); assert.strictEqual(messages[2].ruleId, "no-console"); assert.strictEqual(messages[2].line, 9); }); }); describe("when evaluating code with comments to enable and disable multiple comma separated rules", () => { const code = "/*eslint no-alert:1, no-console:0*/ alert('test'); console.log('test');"; it("should report a violation", () => { const config = { rules: { "no-console": 1, "no-alert": 0 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, "no-alert"); assert.strictEqual(messages[0].message, "Unexpected alert."); assert.include(messages[0].nodeType, "CallExpression"); }); }); describe("when evaluating code with comments to enable configurable rule", () => { const code = "/*eslint quotes:[2, \"double\"]*/ alert('test');"; it("should report a violation", () => { const config = { rules: { quotes: [2, "single"] } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, "quotes"); assert.strictEqual(messages[0].message, "Strings must use doublequote."); assert.include(messages[0].nodeType, "Literal"); }); }); describe("when evaluating code with comments to enable configurable rule using string severity", () => { const code = "/*eslint quotes:[\"error\", \"double\"]*/ alert('test');"; it("should report a violation", () => { const config = { rules: { quotes: [2, "single"] } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, "quotes"); assert.strictEqual(messages[0].message, "Strings must use doublequote."); assert.include(messages[0].nodeType, "Literal"); }); }); describe("when evaluating code with incorrectly formatted comments to disable rule", () => { it("should report a violation", () => { const code = "/*eslint no-alert:'1'*/ alert('test');"; const config = { rules: { "no-alert": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 2); /* * Incorrectly formatted comment threw error; * message from caught exception * may differ amongst UAs, so verifying * first part only as defined in the * parseJsonConfig function in lib/eslint.js */ assert.match(messages[0].message, /^Failed to parse JSON from ' "no-alert":'1'':/); assert.strictEqual(messages[0].line, 1); assert.strictEqual(messages[0].column, 1); assert.strictEqual(messages[1].ruleId, "no-alert"); assert.strictEqual(messages[1].message, "Unexpected alert."); assert.include(messages[1].nodeType, "CallExpression"); }); it("should report a violation", () => { const code = "/*eslint no-alert:abc*/ alert('test');"; const config = { rules: { "no-alert": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 2); /* * Incorrectly formatted comment threw error; * message from caught exception * may differ amongst UAs, so verifying * first part only as defined in the * parseJsonConfig function in lib/eslint.js */ assert.match(messages[0].message, /^Failed to parse JSON from ' "no-alert":abc':/); assert.strictEqual(messages[0].line, 1); assert.strictEqual(messages[0].column, 1); assert.strictEqual(messages[1].ruleId, "no-alert"); assert.strictEqual(messages[1].message, "Unexpected alert."); assert.include(messages[1].nodeType, "CallExpression"); }); it("should report a violation", () => { const code = "/*eslint no-alert:0 2*/ alert('test');"; const config = { rules: { "no-alert": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 2); /* * Incorrectly formatted comment threw error; * message from caught exception * may differ amongst UAs, so verifying * first part only as defined in the * parseJsonConfig function in lib/eslint.js */ assert.match(messages[0].message, /^Failed to parse JSON from ' "no-alert":0 2':/); assert.strictEqual(messages[0].line, 1); assert.strictEqual(messages[0].column, 1); assert.strictEqual(messages[1].ruleId, "no-alert"); assert.strictEqual(messages[1].message, "Unexpected alert."); assert.include(messages[1].nodeType, "CallExpression"); }); }); describe("when evaluating code with comments which have colon in its value", () => { const code = "/* eslint max-len: [2, 100, 2, {ignoreUrls: true, ignorePattern: \"data:image\\/|\\s*require\\s*\\(|^\\s*loader\\.lazy|-\\*-\"}] */\nalert('test');"; it("should not parse errors, should report a violation", () => { const messages = linter.verify(code, {}, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, "max-len"); assert.strictEqual(messages[0].message, "Line 1 exceeds the maximum line length of 100."); assert.include(messages[0].nodeType, "Program"); }); }); describe("when evaluating a file with a shebang", () => { const code = "#!bin/program\n\nvar foo;;"; it("should preserve line numbers", () => { const config = { rules: { "no-extra-semi": 1 } }; const messages = linter.verify(code, config); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, "no-extra-semi"); assert.strictEqual(messages[0].nodeType, "EmptyStatement"); assert.strictEqual(messages[0].line, 3); }); it("should have a comment with the shebang in it", () => { const config = { rules: { checker: "error" } }; const spy = sandbox.spy(context => { const comments = context.getAllComments(); assert.strictEqual(comments.length, 1); assert.strictEqual(comments[0].type, "Shebang"); return {}; }); linter.defineRule("checker", spy); linter.verify(code, config); assert(spy.calledOnce); }); }); describe("when evaluating broken code", () => { const code = BROKEN_TEST_CODE; it("should report a violation with a useful parse error prefix", () => { const messages = linter.verify(code); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].severity, 2); assert.isNull(messages[0].ruleId); assert.strictEqual(messages[0].line, 1); assert.strictEqual(messages[0].column, 4); assert.isTrue(messages[0].fatal); assert.match(messages[0].message, /^Parsing error:/); }); it("should report source code where the issue is present", () => { const inValidCode = [ "var x = 20;", "if (x ==4 {", " x++;", "}" ]; const messages = linter.verify(inValidCode.join("\n")); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].severity, 2); assert.isTrue(messages[0].fatal); assert.match(messages[0].message, /^Parsing error:/); }); }); describe("when using an invalid (undefined) rule", () => { linter = new Linter(); const code = TEST_CODE; const results = linter.verify(code, { rules: { foobar: 2 } }); const result = results[0]; const warningResult = linter.verify(code, { rules: { foobar: 1 } })[0]; const arrayOptionResults = linter.verify(code, { rules: { foobar: [2, "always"] } }); const objectOptionResults = linter.verify(code, { rules: { foobar: [1, { bar: false }] } }); const resultsMultiple = linter.verify(code, { rules: { foobar: 2, barfoo: 1 } }); it("should add a stub rule", () => { assert.isNotNull(result); assert.isArray(results); assert.isObject(result); assert.property(result, "ruleId"); assert.strictEqual(result.ruleId, "foobar"); }); it("should report that the rule does not exist", () => { assert.property(result, "message"); assert.strictEqual(result.message, "Definition for rule 'foobar' was not found"); }); it("should report at the correct severity", () => { assert.property(result, "severity"); assert.strictEqual(result.severity, 2); assert.strictEqual(warningResult.severity, 1); }); it("should accept any valid rule configuration", () => { assert.isObject(arrayOptionResults[0]); assert.isObject(objectOptionResults[0]); }); it("should report multiple missing rules", () => { assert.isArray(resultsMultiple); assert.deepStrictEqual( resultsMultiple[1], { ruleId: "barfoo", message: "Definition for rule 'barfoo' was not found", line: 1, column: 1, severity: 1, nodeType: null } ); }); }); describe("when using a rule which has been replaced", () => { const code = TEST_CODE; const results = linter.verify(code, { rules: { "no-comma-dangle": 2 } }); it("should report the new rule", () => { assert.strictEqual(results[0].ruleId, "no-comma-dangle"); assert.strictEqual(results[0].message, "Rule 'no-comma-dangle' was removed and replaced by: comma-dangle"); }); }); describe("when calling getRules", () => { it("should return all loaded rules", () => { const rules = linter.getRules(); assert.isAbove(rules.size, 230); assert.isObject(rules.get("no-alert")); }); }); describe("when calling version", () => { it("should return current version number", () => { const version = linter.version; assert.isString(version); assert.isTrue(parseInt(version[0], 10) >= 3); }); }); describe("when evaluating an empty string", () => { it("runs rules", () => { linter.defineRule("no-programs", context => ({ Program(node) { context.report({ node, message: "No programs allowed." }); } })); assert.strictEqual( linter.verify("", { rules: { "no-programs": "error" } }).length, 1 ); }); }); describe("when evaluating code without comments to environment", () => { it("should report a violation when using typed array", () => { const code = "var array = new Uint8Array();"; const config = { rules: { "no-undef": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 1); }); it("should report a violation when using Promise", () => { const code = "new Promise();"; const config = { rules: { "no-undef": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 1); }); }); describe("when evaluating code with comments to environment", () => { it("should not support legacy config", () => { const code = "/*jshint mocha:true */ describe();"; const config = { rules: { "no-undef": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, "no-undef"); assert.strictEqual(messages[0].nodeType, "Identifier"); assert.strictEqual(messages[0].line, 1); }); it("should not report a violation", () => { const code = "/*eslint-env es6 */ new Promise();"; const config = { rules: { "no-undef": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); it("should not report a violation", () => { const code = "/*eslint-env mocha,node */ require();describe();"; const config = { rules: { "no-undef": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); it("should not report a violation", () => { const code = "/*eslint-env mocha */ suite();test();"; const config = { rules: { "no-undef": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); it("should not report a violation", () => { const code = "/*eslint-env amd */ define();require();"; const config = { rules: { "no-undef": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); it("should not report a violation", () => { const code = "/*eslint-env jasmine */ expect();spyOn();"; const config = { rules: { "no-undef": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); it("should not report a violation", () => { const code = "/*globals require: true */ /*eslint-env node */ require = 1;"; const config = { rules: { "no-undef": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); it("should not report a violation", () => { const code = "/*eslint-env node */ process.exit();"; const config = { rules: {} }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); it("should not report a violation", () => { const code = "/*eslint no-process-exit: 0 */ /*eslint-env node */ process.exit();"; const config = { rules: { "no-undef": 1 } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 0); }); }); describe("when evaluating code with comments to change config when allowInlineConfig is enabled", () => { it("should report a violation for disabling rules", () => { const code = [ "alert('test'); // eslint-disable-line no-alert" ].join("\n"); const config = { rules: { "no-alert": 1 } }; const messages = linter.verify(code, config, { filename, allowInlineConfig: false }); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, "no-alert"); }); it("should report a violation for global variable declarations", () => { const code = [ "/* global foo */" ].join("\n"); const config = { rules: { test: 2 } }; let ok = false; linter.defineRules({ test(context) { return { Program() { const scope = context.getScope(); const sourceCode = context.getSourceCode(); const comments = sourceCode.getAllComments(); assert.strictEqual(1, comments.length); const foo = getVariable(scope, "foo"); assert.notOk(foo); ok = true; } }; } }); linter.verify(code, config, { allowInlineConfig: false }); assert(ok); }); it("should report a violation for eslint-disable", () => { const code = [ "/* eslint-disable */", "alert('test');" ].join("\n"); const config = { rules: { "no-alert": 1 } }; const messages = linter.verify(code, config, { filename, allowInlineConfig: false }); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, "no-alert"); }); it("should not report a violation for rule changes", () => { const code = [ "/*eslint no-alert:2*/", "alert('test');" ].join("\n"); const config = { rules: { "no-alert": 0 } }; const messages = linter.verify(code, config, { filename, allowInlineConfig: false }); assert.strictEqual(messages.length, 0); }); it("should report a violation for disable-line", () => { const code = [ "alert('test'); // eslint-disable-line" ].join("\n"); const config = { rules: { "no-alert": 2 } }; const messages = linter.verify(code, config, { filename, allowInlineConfig: false }); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].ruleId, "no-alert"); }); it("should report a violation for env changes", () => { const code = [ "/*eslint-env browser*/" ].join("\n"); const config = { rules: { test: 2 } }; let ok = false; linter.defineRules({ test(context) { return { Program() { const scope = context.getScope(); const sourceCode = context.getSourceCode(); const comments = sourceCode.getAllComments(); assert.strictEqual(1, comments.length); const windowVar = getVariable(scope, "window"); assert.notOk(windowVar.eslintExplicitGlobal); ok = true; } }; } }); linter.verify(code, config, { allowInlineConfig: false }); assert(ok); }); }); describe("reportUnusedDisable option", () => { it("reports problems for unused eslint-disable comments", () => { assert.deepStrictEqual( linter.verify("/* eslint-disable */", {}, { reportUnusedDisableDirectives: true }), [ { ruleId: null, message: "Unused eslint-disable directive (no problems were reported).", line: 1, column: 1, severity: 2, nodeType: null } ] ); }); }); describe("when evaluating code with comments to change config when allowInlineConfig is disabled", () => { it("should not report a violation", () => { const code = [ "alert('test'); // eslint-disable-line no-alert" ].join("\n"); const config = { rules: { "no-alert": 1 } }; const messages = linter.verify(code, config, { filename, allowInlineConfig: true }); assert.strictEqual(messages.length, 0); }); }); describe("when evaluating code with hashbang", () => { it("should comment hashbang without breaking offset", () => { const code = "#!/usr/bin/env node\n'123';"; const config = { rules: { checker: "error" } }; let spy; linter.defineRule("checker", context => { spy = sandbox.spy(node => { assert.strictEqual(context.getSource(node), "'123';"); }); return { ExpressionStatement: spy }; }); linter.verify(code, config); assert(spy && spy.calledOnce); }); }); describe("verify()", () => { describe("filenames", () => { it("should allow filename to be passed on options object", () => { const filenameChecker = sandbox.spy(context => { assert.strictEqual(context.getFilename(), "foo.js"); return {}; }); linter.defineRule("checker", filenameChecker); linter.defineRule("checker", filenameChecker); linter.verify("foo;", { rules: { checker: "error" } }, { filename: "foo.js" }); assert(filenameChecker.calledOnce); }); it("should allow filename to be passed as third argument", () => { const filenameChecker = sandbox.spy(context => { assert.strictEqual(context.getFilename(), "bar.js"); return {}; }); linter.defineRule("checker", filenameChecker); linter.verify("foo;", { rules: { checker: "error" } }, "bar.js"); assert(filenameChecker.calledOnce); }); it("should default filename to <input> when options object doesn't have filename", () => { const filenameChecker = sandbox.spy(context => { assert.strictEqual(context.getFilename(), "<input>"); return {}; }); linter.defineRule("checker", filenameChecker); linter.verify("foo;", { rules: { checker: "error" } }, {}); assert(filenameChecker.calledOnce); }); it("should default filename to <input> when only two arguments are passed", () => { const filenameChecker = sandbox.spy(context => { assert.strictEqual(context.getFilename(), "<input>"); return {}; }); linter.defineRule("checker", filenameChecker); linter.verify("foo;", { rules: { checker: "error" } }); assert(filenameChecker.calledOnce); }); }); it("should report warnings in order by line and column when called", () => { const code = "foo()\n alert('test')"; const config = { rules: { "no-mixed-spaces-and-tabs": 1, "eol-last": 1, semi: [1, "always"] } }; const messages = linter.verify(code, config, filename); assert.strictEqual(messages.length, 3); assert.strictEqual(messages[0].line, 1); assert.strictEqual(messages[0].column, 6); assert.strictEqual(messages[1].line, 2); assert.strictEqual(messages[1].column, 18); assert.strictEqual(messages[2].line, 2); assert.strictEqual(messages[2].column, 18); }); describe("ecmaVersion", () => { describe("it should properly parse let declaration when", () => { it("the ECMAScript version number is 6", () => { const messages = linter.verify("let x = 5;", { parserOptions: { ecmaVersion: 6 } }); assert.strictEqual(messages.length, 0); }); it("the ECMAScript version number is 2015", () => { const messages = linter.verify("let x = 5;", { parserOptions: { ecmaVersion: 2015 } }); assert.strictEqual(messages.length, 0); }); }); it("should fail to parse exponentiation operator when the ECMAScript version number is 2015", () => { const messages = linter.verify("x ** y;", { parserOptions: { ecmaVersion: 2015 } }); assert.strictEqual(messages.length, 1); }); describe("should properly parse exponentiation operator when", () => { it("the ECMAScript version number is 7", () => { const messages = linter.verify("x ** y;", { parserOptions: { ecmaVersion: 7 } }); assert.strictEqual(messages.length, 0); }); it("the ECMAScript version number is 2016", () => { const messages = linter.verify("x ** y;", { parserOptions: { ecmaVersion: 2016 } }); assert.strictEqual(messages.length, 0); }); }); }); it("should properly parse object spread when ecmaVersion is 2018", () => { const messages = linter.verify("var x = { ...y };", { parserOptions: { ecmaVersion: 2018 } }, filename); assert.strictEqual(messages.length, 0); }); it("should properly parse global return when passed ecmaFeatures", () => { const messages = linter.verify("return;", { parserOptions: { ecmaFeatures: { globalReturn: true } } }, filename); assert.strictEqual(messages.length, 0); }); it("should properly parse global return when in Node.js environment", () => { const messages = linter.verify("return;", { env: { node: true } }, filename); assert.strictEqual(messages.length, 0); }); it("should not parse global return when in Node.js environment with globalReturn explicitly off", () => { const messages = linter.verify("return;", { env: { node: true }, parserOptions: { ecmaFeatures: { globalReturn: false } } }, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].message, "Parsing error: 'return' outside of function"); }); it("should not parse global return when Node.js environment is false", () => { const messages = linter.verify("return;", {}, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].message, "Parsing error: 'return' outside of function"); }); it("should properly parse sloppy-mode code when impliedStrict is false", () => { const messages = linter.verify("var private;", {}, filename); assert.strictEqual(messages.length, 0); }); it("should not parse sloppy-mode code when impliedStrict is true", () => { const messages = linter.verify("var private;", { parserOptions: { ecmaFeatures: { impliedStrict: true } } }, filename); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].message, "Parsing error: The keyword 'private' is reserved"); }); it("should properly parse valid code when impliedStrict is true", () => { const messages = linter.verify("var foo;", { parserOptions: { ecmaFeatures: { impliedStrict: true } } }, filename); assert.strictEqual(messages.length, 0); }); it("should properly parse JSX when passed ecmaFeatures", () => { const messages = linter.verify("var x = <div/>;", { parserOptions: { ecmaFeatures: { jsx: true } } }, filename); assert.strictEqual(messages.length, 0); }); it("should report an error when JSX code is encountered and JSX is not enabled", () => { const code = "var myDivElement = <div className=\"foo\" />;"; const messages = linter.verify(code, {}, "filename"); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].line, 1); assert.strictEqual(messages[0].column, 20); assert.strictEqual(messages[0].message, "Parsing error: Unexpected token <"); }); it("should not report an error when JSX code is encountered and JSX is enabled", () => { const code = "var myDivElement = <div className=\"foo\" />;"; const messages = linter.verify(code, { parserOptions: { ecmaFeatures: { jsx: true } } }, "filename"); assert.strictEqual(messages.length, 0); }); it("should not report an error when JSX code contains a spread operator and JSX is enabled", () => { const code = "var myDivElement = <div {...this.props} />;"; const messages = linter.verify(code, { parserOptions: { ecmaVersion: 6, ecmaFeatures: { jsx: true } } }, "filename"); assert.strictEqual(messages.length, 0); }); it("should be able to use es6 features if there is a comment which has \"eslint-env es6\"", () => { const code = [ "/* eslint-env es6 */", "var arrow = () => 0;", "var binary = 0b1010;", "{ let a = 0; const b = 1; }", "class A {}", "function defaultParams(a = 0) {}", "var {a = 1, b = 2} = {};", "for (var a of []) {}", "function* generator() { yield 0; }", "var computed = {[a]: 0};", "var duplicate = {dup: 0, dup: 1};", "var method = {foo() {}};", "var property = {a, b};", "var octal = 0o755;", "var u = /^.$/u.test('𠮷');", "var y = /hello/y.test('hello');", "function restParam(a, ...rest) {}", "class B { superInFunc() { super.foo(); } }", "var template = `hello, ${a}`;", "var unicode = '\\u{20BB7}';" ].join("\n"); const messages = linter.verify(code, null, "eslint-env es6"); assert.strictEqual(messages.length, 0); }); it("should be able to return in global if there is a comment which has \"eslint-env node\"", () => { const messages = linter.verify("/* eslint-env node */ return;", null, "eslint-env node"); assert.strictEqual(messages.length, 0); }); it("should attach a \"/*global\" comment node to declared variables", () => { const code = "/* global foo */\n/* global bar, baz */"; let ok = false; linter.defineRules({ test(context) { return { Program() { const scope = context.getScope(); const sourceCode = context.getSourceCode(); const comments = sourceCode.getAllComments(); assert.strictEqual(2, comments.length); const foo = getVariable(scope, "foo"); assert.strictEqual(true, foo.eslintExplicitGlobal); assert.strictEqual(comments[0], foo.eslintExplicitGlobalComment); const bar = getVariable(scope, "bar"); assert.strictEqual(true, bar.eslintExplicitGlobal); assert.strictEqual(comments[1], bar.eslintExplicitGlobalComment); const baz = getVariable(scope, "baz"); assert.strictEqual(true, baz.eslintExplicitGlobal); assert.strictEqual(comments[1], baz.eslintExplicitGlobalComment); ok = true; } }; } }); linter.verify(code, { rules: { test: 2 } }); assert(ok); }); it("should not crash when we reuse the SourceCode object", () => { linter.verify("function render() { return <div className='test'>{hello}</div> }", { parserOptions: { ecmaVersion: 6, ecmaFeatures: { jsx: true } } }); linter.verify(linter.getSourceCode(), { parserOptions: { ecmaVersion: 6, ecmaFeatures: { jsx: true } } }); }); it("should reuse the SourceCode object", () => { let ast1 = null, ast2 = null; linter.defineRule("save-ast1", () => ({ Program(node) { ast1 = node; } })); linter.defineRule("save-ast2", () => ({ Program(node) { ast2 = node; } })); linter.verify("function render() { return <div className='test'>{hello}</div> }", { parserOptions: { ecmaVersion: 6, ecmaFeatures: { jsx: true } }, rules: { "save-ast1": 2 } }); linter.verify(linter.getSourceCode(), { parserOptions: { ecmaVersion: 6, ecmaFeatures: { jsx: true } }, rules: { "save-ast2": 2 } }); assert(ast1 !== null); assert(ast2 !== null); assert(ast1 === ast2); }); it("should allow 'await' as a property name in modules", () => { const result = linter.verify( "obj.await", { parserOptions: { ecmaVersion: 6, sourceType: "module" } } ); assert(result.length === 0); }); it("should not modify config object passed as argument", () => { const config = {}; Object.freeze(config); linter.verify("var", config); }); it("should pass 'id' to rule contexts with the rule id", () => { const spy = sandbox.spy(context => { assert.strictEqual(context.id, "foo-bar-baz"); return {}; }); linter.defineRule("foo-bar-baz", spy); linter.verify("x", { rules: { "foo-bar-baz": "error" } }); assert(spy.calledOnce); }); it("should parse ES2018 code for backward compatibility if 'parserOptions.ecmaFeatures.experimentalObjectRestSpread' is given.", () => { const messages = linter.verify( "async function* f() { let {a, ...rest} = { a, ...obj }; }", { parserOptions: { ecmaFeatures: { experimentalObjectRestSpread: true } } } ); assert(messages.length === 0); }); }); describe("context.getScope()", () => { /** * Get the scope on the node `astSelector` specified. * @param {string} code The source code to verify. * @param {string} astSelector The AST selector to get scope. * @param {number} [ecmaVersion=5] The ECMAScript version. * @returns {{node: ASTNode, scope: escope.Scope}} Gotten scope. */ function getScope(code, astSelector, ecmaVersion = 5) { let node, scope; linter.defineRule("get-scope", context => ({ [astSelector](node0) { node = node0; scope = context.getScope(); } })); linter.verify( code, { parserOptions: { ecmaVersion }, rules: { "get-scope": 2 } } ); return { node, scope }; } it("should return 'function' scope on FunctionDeclaration (ES5)", () => { const { node, scope } = getScope("function f() {}", "FunctionDeclaration"); assert.strictEqual(scope.type, "function"); assert.strictEqual(scope.block, node); }); it("should return 'function' scope on FunctionExpression (ES5)", () => { const { node, scope } = getScope("!function f() {}", "FunctionExpression"); assert.strictEqual(scope.type, "function"); assert.strictEqual(scope.block, node); }); it("should return 'function' scope on the body of FunctionDeclaration (ES5)", () => { const { node, scope } = getScope("function f() {}", "BlockStatement"); assert.strictEqual(scope.type, "function"); assert.strictEqual(scope.block, node.parent); }); it("should return 'function' scope on the body of FunctionDeclaration (ES2015)", () => { const { node, scope } = getScope("function f() {}", "BlockStatement", 2015); assert.strictEqual(scope.type, "function"); assert.strictEqual(scope.block, node.parent); }); it("should return 'function' scope on BlockStatement in functions (ES5)", () => { const { node, scope } = getScope("function f() { { var b; } }", "BlockStatement > BlockStatement"); assert.strictEqual(scope.type, "function"); assert.strictEqual(scope.block, node.parent.parent); assert.deepStrictEqual(scope.variables.map(v => v.name), ["arguments", "b"]); }); it("should return 'block' scope on BlockStatement in functions (ES2015)", () => { const { node, scope } = getScope("function f() { { let a; var b; } }", "BlockStatement > BlockStatement", 2015); assert.strictEqual(scope.type, "block"); assert.strictEqual(scope.upper.type, "function"); assert.strictEqual(scope.block, node); assert.deepStrictEqual(scope.variables.map(v => v.name), ["a"]); assert.deepStrictEqual(scope.variableScope.variables.map(v => v.name), ["arguments", "b"]); }); it("should return 'block' scope on nested BlockStatement in functions (ES2015)", () => { const { node, scope } = getScope("function f() { { let a; { let b; var c; } } }", "BlockStatement > BlockStatement > BlockStatement", 2015); assert.strictEqual(scope.type, "block"); assert.strictEqual(scope.upper.type, "block"); assert.strictEqual(scope.upper.upper.type, "function"); assert.strictEqual(scope.block, node); assert.deepStrictEqual(scope.variables.map(v => v.name), ["b"]); assert.deepStrictEqual(scope.upper.variables.map(v => v.name), ["a"]); assert.deepStrictEqual(scope.variableScope.variables.map(v => v.name), ["arguments", "c"]); }); it("should return 'function' scope on SwitchStatement in functions (ES5)", () => { const { node, scope } = getScope("function f() { switch (a) { case 0: var b; } }", "SwitchStatement"); assert.strictEqual(scope.type, "function"); assert.strictEqual(scope.block, node.parent.parent); assert.deepStrictEqual(scope.variables.map(v => v.name), ["arguments", "b"]); }); it("should return 'switch' scope on SwitchStatement in functions (ES2015)", () => { const { node, scope } = getScope("function f() { switch (a) { case 0: let b; } }", "SwitchStatement", 2015); assert.strictEqual(scope.type, "switch"); assert.strictEqual(scope.block, node); assert.deepStrictEqual(scope.variables.map(v => v.name), ["b"]); }); it("should return 'function' scope on SwitchCase in functions (ES5)", () => { const { node, scope } = getScope("function f() { switch (a) { case 0: var b; } }", "SwitchCase"); assert.strictEqual(scope.type, "function"); assert.strictEqual(scope.block, node.parent.parent.parent); assert.deepStrictEqual(scope.variables.map(v => v.name), ["arguments", "b"]); }); it("should return 'switch' scope on SwitchCase in functions (ES2015)", () => { const { node, scope } = getScope("function f() { switch (a) { case 0: let b; } }", "SwitchCase", 2015); assert.strictEqual(scope.type, "switch"); assert.strictEqual(scope.block, node.parent); assert.deepStrictEqual(scope.variables.map(v => v.name), ["b"]); }); it("should return 'catch' scope on CatchClause in functions (ES5)", () => { const { node, scope } = getScope("function f() { try {} catch (e) { var a; } }", "CatchClause"); assert.strictEqual(scope.type, "catch"); assert.strictEqual(scope.block, node); assert.deepStrictEqual(scope.variables.map(v => v.name), ["e"]); }); it("should return 'catch' scope on CatchClause in functions (ES2015)", () => { const { node, scope } = getScope("function f() { try {} catch (e) { let a; } }", "CatchClause", 2015); assert.strictEqual(scope.type, "catch"); assert.strictEqual(scope.block, node); assert.deepStrictEqual(scope.variables.map(v => v.name), ["e"]); }); it("should return 'catch' scope on the block of CatchClause in functions (ES5)", () => { const { node, scope } = getScope("function f() { try {} catch (e) { var a; } }", "CatchClause > BlockStatement"); assert.strictEqual(scope.type, "catch"); assert.strictEqual(scope.block, node.parent); assert.deepStrictEqual(scope.variables.map(v => v.name), ["e"]); }); it("should return 'block' scope on the block of CatchClause in functions (ES2015)", () => { const { node, scope } = getScope("function f() { try {} catch (e) { let a; } }", "CatchClause > BlockStatement", 2015); assert.strictEqual(scope.type, "block"); assert.strictEqual(scope.block, node); assert.deepStrictEqual(scope.variables.map(v => v.name), ["a"]); }); it("should return 'function' scope on ForStatement in functions (ES5)", () => { const { node, scope } = getScope("function f() { for (var i = 0; i < 10; ++i) {} }", "ForStatement"); assert.strictEqual(scope.type, "function"); assert.strictEqual(scope.block, node.parent.parent); assert.deepStrictEqual(scope.variables.map(v => v.name), ["arguments", "i"]); }); it("should return 'for' scope on ForStatement in functions (ES2015)", () => { const { node, scope } = getScope("function f() { for (let i = 0; i < 10; ++i) {} }", "ForStatement", 2015); assert.strictEqual(scope.type, "for"); assert.strictEqual(scope.block, node); assert.deepStrictEqual(scope.variables.map(v => v.name), ["i"]); }); it("should return 'function' scope on the block body of ForStatement in functions (ES5)", () => { const { node, scope } = getScope("function f() { for (var i = 0; i < 10; ++i) {} }", "ForStatement > BlockStatement"); assert.strictEqual(scope.type, "function"); assert.strictEqual(scope.block, node.parent.parent.parent); assert.deepStrictEqual(scope.variables.map(v => v.name), ["arguments", "i"]); }); it("should return 'block' scope on the block body of ForStatement in functions (ES2015)", () => { const { node, scope } = getScope("function f() { for (let i = 0; i < 10; ++i) {} }", "ForStatement > BlockStatement", 2015); assert.strictEqual(scope.type, "block"); assert.strictEqual(scope.upper.type, "for"); assert.strictEqual(scope.block, node); assert.deepStrictEqual(scope.variables.map(v => v.name), []); assert.deepStrictEqual(scope.upper.variables.map(v => v.name), ["i"]); }); it("should return 'function' scope on ForInStatement in functions (ES5)", () => { const { node, scope } = getScope("function f() { for (var key in obj) {} }", "ForInStatement"); assert.strictEqual(scope.type, "function"); assert.strictEqual(scope.block, node.parent.parent); assert.deepStrictEqual(scope.variables.map(v => v.name), ["arguments", "key"]); }); it("should return 'for' scope on ForInStatement in functions (ES2015)", () => { const { node, scope } = getScope("function f() { for (let key in obj) {} }", "ForInStatement", 2015); assert.strictEqual(scope.type, "for"); assert.strictEqual(scope.block, node); assert.deepStrictEqual(scope.variables.map(v => v.name), ["key"]); }); it("should return 'function' scope on the block body of ForInStatement in functions (ES5)", () => { const { node, scope } = getScope("function f() { for (var key in obj) {} }", "ForInStatement > BlockStatement"); assert.strictEqual(scope.type, "function"); assert.strictEqual(scope.block, node.parent.parent.parent); assert.deepStrictEqual(scope.variables.map(v => v.name), ["arguments", "key"]); }); it("should return 'block' scope on the block body of ForInStatement in functions (ES2015)", () => { const { node, scope } = getScope("function f() { for (let key in obj) {} }", "ForInStatement > BlockStatement", 2015); assert.strictEqual(scope.type, "block"); assert.strictEqual(scope.upper.type, "for"); assert.strictEqual(scope.block, node); assert.deepStrictEqual(scope.variables.map(v => v.name), []); assert.deepStrictEqual(scope.upper.variables.map(v => v.name), ["key"]); }); it("should return 'for' scope on ForOfStatement in functions (ES2015)", () => { const { node, scope } = getScope("function f() { for (let x of xs) {} }", "ForOfStatement", 2015); assert.strictEqual(scope.type, "for"); assert.strictEqual(scope.block, node); assert.deepStrictEqual(scope.variables.map(v => v.name), ["x"]); }); it("should return 'block' scope on the block body of ForOfStatement in functions (ES2015)", () => { const { node, scope } = getScope("function f() { for (let x of xs) {} }", "ForOfStatement > BlockStatement", 2015); assert.strictEqual(scope.type, "block"); assert.strictEqual(scope.upper.type, "for"); assert.strictEqual(scope.block, node); assert.deepStrictEqual(scope.variables.map(v => v.name), []); assert.deepStrictEqual(scope.upper.variables.map(v => v.name), ["x"]); }); it("should shadow the same name variable by the iteration variable.", () => { const { node, scope } = getScope("let x; for (let x of x) {}", "ForOfStatement", 2015); assert.strictEqual(scope.type, "for"); assert.strictEqual(scope.upper.type, "global"); assert.strictEqual(scope.block, node); assert.strictEqual(scope.upper.variables[0].references.length, 0); assert.strictEqual(scope.references[0].identifier, node.left.declarations[0].id); assert.strictEqual(scope.references[1].identifier, node.right); assert.strictEqual(scope.references[1].resolved, scope.variables[0]); }); }); describe("Variables and references", () => { const code = [ "a;", "function foo() { b; }", "Object;", "foo;", "var c;", "c;", "/* global d */", "d;", "e;", "f;" ].join("\n"); let scope = null; beforeEach(() => { let ok = false; linter.defineRules({ test(context) { return { Program() { scope = context.getScope(); ok = true; } }; } }); linter.verify(code, { rules: { test: 2 }, globals: { e: true, f: false } }); assert(ok); }); afterEach(() => { scope = null; }); it("Scope#through should contain references of undefined variables", () => { assert.strictEqual(scope.through.length, 2); assert.strictEqual(scope.through[0].identifier.name, "a"); assert.strictEqual(scope.through[0].identifier.loc.start.line, 1); assert.strictEqual(scope.through[0].resolved, null); assert.strictEqual(scope.through[1].identifier.name, "b"); assert.strictEqual(scope.through[1].identifier.loc.start.line, 2); assert.strictEqual(scope.through[1].resolved, null); }); it("Scope#variables should contain global variables", () => { assert(scope.variables.some(v => v.name === "Object")); assert(scope.variables.some(v => v.name === "foo")); assert(scope.variables.some(v => v.name === "c")); assert(scope.variables.some(v => v.name === "d")); assert(scope.variables.some(v => v.name === "e")); assert(scope.variables.some(v => v.name === "f")); }); it("Scope#set should contain global variables", () => { assert(scope.set.get("Object")); assert(scope.set.get("foo")); assert(scope.set.get("c")); assert(scope.set.get("d")); assert(scope.set.get("e")); assert(scope.set.get("f")); }); it("Variables#references should contain their references", () => { assert.strictEqual(scope.set.get("Object").references.length, 1); assert.strictEqual(scope.set.get("Object").references[0].identifier.name, "Object"); assert.strictEqual(scope.set.get("Object").references[0].identifier.loc.start.line, 3); assert.strictEqual(scope.set.get("Object").references[0].resolved, scope.set.get("Object")); assert.strictEqual(scope.set.get("foo").references.length, 1); assert.strictEqual(scope.set.get("foo").references[0].identifier.name, "foo"); assert.strictEqual(scope.set.get("foo").references[0].identifier.loc.start.line, 4); assert.strictEqual(scope.set.get("foo").references[0].resolved, scope.set.get("foo")); assert.strictEqual(scope.set.get("c").references.length, 1); assert.strictEqual(scope.set.get("c").references[0].identifier.name, "c"); assert.strictEqual(scope.set.get("c").references[0].identifier.loc.start.line, 6); assert.strictEqual(scope.set.get("c").references[0].resolved, scope.set.get("c")); assert.strictEqual(scope.set.get("d").references.length, 1); assert.strictEqual(scope.set.get("d").references[0].identifier.name, "d"); assert.strictEqual(scope.set.get("d").references[0].identifier.loc.start.line, 8); assert.strictEqual(scope.set.get("d").references[0].resolved, scope.set.get("d")); assert.strictEqual(scope.set.get("e").references.length, 1); assert.strictEqual(scope.set.get("e").references[0].identifier.name, "e"); assert.strictEqual(scope.set.get("e").references[0].identifier.loc.start.line, 9); assert.strictEqual(scope.set.get("e").references[0].resolved, scope.set.get("e")); assert.strictEqual(scope.set.get("f").references.length, 1); assert.strictEqual(scope.set.get("f").references[0].identifier.name, "f"); assert.strictEqual(scope.set.get("f").references[0].identifier.loc.start.line, 10); assert.strictEqual(scope.set.get("f").references[0].resolved, scope.set.get("f")); }); it("Reference#resolved should be their variable", () => { assert.strictEqual(scope.set.get("Object").references[0].resolved, scope.set.get("Object")); assert.strictEqual(scope.set.get("foo").references[0].resolved, scope.set.get("foo")); assert.strictEqual(scope.set.get("c").references[0].resolved, scope.set.get("c")); assert.strictEqual(scope.set.get("d").references[0].resolved, scope.set.get("d")); assert.strictEqual(scope.set.get("e").references[0].resolved, scope.set.get("e")); assert.strictEqual(scope.set.get("f").references[0].resolved, scope.set.get("f")); }); }); describe("context.getDeclaredVariables(node)", () => { /** * Assert `context.getDeclaredVariables(node)` is valid. * @param {string} code - A code to check. * @param {string} type - A type string of ASTNode. This method checks variables on the node of the type. * @param {Array<Array<string>>} expectedNamesList - An array of expected variable names. The expected variable names is an array of string. * @returns {void} */ function verify(code, type, expectedNamesList) { linter.defineRules({ test(context) { /** * Assert `context.getDeclaredVariables(node)` is empty. * @param {ASTNode} node - A node to check. * @returns {void} */ function checkEmpty(node) { assert.strictEqual(0, context.getDeclaredVariables(node).length); } const rule = { Program: checkEmpty, EmptyStatement: checkEmpty, BlockStatement: checkEmpty, ExpressionStatement: checkEmpty, LabeledStatement: checkEmpty, BreakStatement: checkEmpty, ContinueStatement: checkEmpty, WithStatement: checkEmpty, SwitchStatement: checkEmpty, ReturnStatement: checkEmpty, ThrowStatement: checkEmpty, TryStatement: checkEmpty, WhileStatement: checkEmpty, DoWhileStatement: checkEmpty, ForStatement: checkEmpty, ForInStatement: checkEmpty, DebuggerStatement: checkEmpty, ThisExpression: checkEmpty, ArrayExpression: checkEmpty, ObjectExpression: checkEmpty, Property: checkEmpty, SequenceExpression: checkEmpty, UnaryExpression: checkEmpty, BinaryExpression: checkEmpty, AssignmentExpression: checkEmpty, UpdateExpression: checkEmpty, LogicalExpression: checkEmpty, ConditionalExpression: checkEmpty, CallExpression: checkEmpty, NewExpression: checkEmpty, MemberExpression: checkEmpty, SwitchCase: checkEmpty, Identifier: checkEmpty, Literal: checkEmpty, ForOfStatement: checkEmpty, ArrowFunctionExpression: checkEmpty, YieldExpression: checkEmpty, TemplateLiteral: checkEmpty, TaggedTemplateExpression: checkEmpty, TemplateElement: checkEmpty, ObjectPattern: checkEmpty, ArrayPattern: checkEmpty, RestElement: checkEmpty, AssignmentPattern: checkEmpty, ClassBody: checkEmpty, MethodDefinition: checkEmpty, MetaProperty: checkEmpty }; rule[type] = function(node) { const expectedNames = expectedNamesList.shift(); const variables = context.getDeclaredVariables(node); assert(Array.isArray(expectedNames)); assert(Array.isArray(variables)); assert.strictEqual(expectedNames.length, variables.length); for (let i = variables.length - 1; i >= 0; i--) { assert.strictEqual(expectedNames[i], variables[i].name); } }; return rule; } }); linter.verify(code, { rules: { test: 2 }, parserOptions: { ecmaVersion: 6, sourceType: "module" } }); // Check all expected names are asserted. assert.strictEqual(0, expectedNamesList.length); } it("VariableDeclaration", () => { const code = "\n var {a, x: [b], y: {c = 0}} = foo;\n let {d, x: [e], y: {f = 0}} = foo;\n const {g, x: [h], y: {i = 0}} = foo, {j, k = function(z) { let l; }} = bar;\n "; const namesList = [ ["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i", "j", "k"], ["l"] ]; verify(code, "VariableDeclaration", namesList); }); it("VariableDeclaration (on for-in/of loop)", () => { // TDZ scope is created here, so tests to exclude those. const code = "\n for (var {a, x: [b], y: {c = 0}} in foo) {\n let g;\n }\n for (let {d, x: [e], y: {f = 0}} of foo) {\n let h;\n }\n "; const namesList = [ ["a", "b", "c"], ["g"], ["d", "e", "f"], ["h"] ]; verify(code, "VariableDeclaration", namesList); }); it("VariableDeclarator", () => { // TDZ scope is created here, so tests to exclude those. const code = "\n var {a, x: [b], y: {c = 0}} = foo;\n let {d, x: [e], y: {f = 0}} = foo;\n const {g, x: [h], y: {i = 0}} = foo, {j, k = function(z) { let l; }} = bar;\n "; const namesList = [ ["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"], ["j", "k"], ["l"] ]; verify(code, "VariableDeclarator", namesList); }); it("FunctionDeclaration", () => { const code = "\n function foo({a, x: [b], y: {c = 0}}, [d, e]) {\n let z;\n }\n function bar({f, x: [g], y: {h = 0}}, [i, j = function(q) { let w; }]) {\n let z;\n }\n "; const namesList = [ ["foo", "a", "b", "c", "d", "e"], ["bar", "f", "g", "h", "i", "j"] ]; verify(code, "FunctionDeclaration", namesList); }); it("FunctionExpression", () => { const code = "\n (function foo({a, x: [b], y: {c = 0}}, [d, e]) {\n let z;\n });\n (function bar({f, x: [g], y: {h = 0}}, [i, j = function(q) { let w; }]) {\n let z;\n });\n "; const namesList = [ ["foo", "a", "b", "c", "d", "e"], ["bar", "f", "g", "h", "i", "j"], ["q"] ]; verify(code, "FunctionExpression", namesList); }); it("ArrowFunctionExpression", () => { const code = "\n (({a, x: [b], y: {c = 0}}, [d, e]) => {\n let z;\n });\n (({f, x: [g], y: {h = 0}}, [i, j]) => {\n let z;\n });\n "; const namesList = [ ["a", "b", "c", "d", "e"], ["f", "g", "h", "i", "j"] ]; verify(code, "ArrowFunctionExpression", namesList); }); it("ClassDeclaration", () => { const code = "\n class A { foo(x) { let y; } }\n class B { foo(x) { let y; } }\n "; const namesList = [ ["A", "A"], // outer scope's and inner scope's. ["B", "B"] ]; verify(code, "ClassDeclaration", namesList); }); it("ClassExpression", () => { const code = "\n (class A { foo(x) { let y; } });\n (class B { foo(x) { let y; } });\n "; const namesList = [ ["A"], ["B"] ]; verify(code, "ClassExpression", namesList); }); it("CatchClause", () => { const code = "\n try {} catch ({a, b}) {\n let x;\n try {} catch ({c, d}) {\n let y;\n }\n }\n "; const namesList = [ ["a", "b"], ["c", "d"] ]; verify(code, "CatchClause", namesList); }); it("ImportDeclaration", () => { const code = "\n import \"aaa\";\n import * as a from \"bbb\";\n import b, {c, x as d} from \"ccc\";\n "; const namesList = [ [], ["a"], ["b", "c", "d"] ]; verify(code, "ImportDeclaration", namesList); }); it("ImportSpecifier", () => { const code = "\n import \"aaa\";\n import * as a from \"bbb\";\n import b, {c, x as d} from \"ccc\";\n "; const namesList = [ ["c"], ["d"] ]; verify(code, "ImportSpecifier", namesList); }); it("ImportDefaultSpecifier", () => { const code = "\n import \"aaa\";\n import * as a from \"bbb\";\n import b, {c, x as d} from \"ccc\";\n "; const namesList = [ ["b"] ]; verify(code, "ImportDefaultSpecifier", namesList); }); it("ImportNamespaceSpecifier", () => { const code = "\n import \"aaa\";\n import * as a from \"bbb\";\n import b, {c, x as d} from \"ccc\";\n "; const namesList = [ ["a"] ]; verify(code, "ImportNamespaceSpecifier", namesList); }); }); describe("mutability", () => { let linter1 = null; let linter2 = null; beforeEach(() => { linter1 = new Linter(); linter2 = new Linter(); }); describe("rules", () => { it("with no changes, same rules are loaded", () => { assert.sameDeepMembers(Array.from(linter1.getRules().keys()), Array.from(linter2.getRules().keys())); }); it("loading rule in one doesnt change the other", () => { linter1.defineRule("mock-rule", () => ({})); assert.isTrue(linter1.getRules().has("mock-rule"), "mock rule is present"); assert.isFalse(linter2.getRules().has("mock-rule"), "mock rule is not present"); }); }); describe("environments", () => { it("with no changes same env are loaded", () => { assert.sameDeepMembers([linter1.environments.getAll()], [linter2.environments.getAll()]); }); it("defining env in one doesnt change the other", () => { linter1.environments.define("mock-env", true); assert.isTrue(linter1.environments.get("mock-env"), "mock env is present"); assert.isNull(linter2.environments.get("mock-env"), "mock env is not present"); }); }); }); describe("processors", () => { beforeEach(() => { // A rule that always reports the AST with a message equal to the source text linter.defineRule("report-original-text", context => ({ Program(ast) { context.report({ node: ast, message: context.getSourceCode().text }); } })); }); describe("preprocessors", () => { it("should apply a preprocessor to the code, and lint each code sample separately", () => { const code = "foo bar baz"; const problems = linter.verify( code, { rules: { "report-original-text": "error" } }, { // Apply a preprocessor that splits the source text into spaces and lints each word individually preprocess(input) { assert.strictEqual(input, code); assert.strictEqual(arguments.length, 1); return input.split(" "); } } ); assert.strictEqual(problems.length, 3); assert.deepStrictEqual(problems.map(problem => problem.message), ["foo", "bar", "baz"]); }); }); describe("postprocessors", () => { it("should apply a postprocessor to the reported messages", () => { const code = "foo bar baz"; const problems = linter.verify( code, { rules: { "report-original-text": "error" } }, { preprocess: input => input.split(" "), /* * Apply a postprocessor that updates the locations of the reported problems * to make sure they correspond to the locations in the original text. */ postprocess(problemLists) { assert.strictEqual(problemLists.length, 3); assert.strictEqual(arguments.length, 1); problemLists.forEach(problemList => assert.strictEqual(problemList.length, 1)); return problemLists.reduce( (combinedList, problemList, index) => combinedList.concat( problemList.map( problem => Object.assign( {}, problem, { message: problem.message.toUpperCase(), column: problem.column + index * 4 } ) ) ), [] ); } } ); assert.strictEqual(problems.length, 3); assert.deepStrictEqual(problems.map(problem => problem.message), ["FOO", "BAR", "BAZ"]); assert.deepStrictEqual(problems.map(problem => problem.column), [1, 5, 9]); }); it("should use postprocessed problem ranges when applying autofixes", () => { const code = "foo bar baz"; linter.defineRule("capitalize-identifiers", context => ({ Identifier(node) { if (node.name !== node.name.toUpperCase()) { context.report({ node, message: "Capitalize this identifier", fix: fixer => fixer.replaceText(node, node.name.toUpperCase()) }); } } })); const fixResult = linter.verifyAndFix( code, { rules: { "capitalize-identifiers": "error" } }, { /* * Apply a postprocessor that updates the locations of autofixes * to make sure they correspond to locations in the original text. */ preprocess: input => input.split(" "), postprocess(problemLists) { return problemLists.reduce( (combinedProblems, problemList, blockIndex) => combinedProblems.concat( problemList.map(problem => Object.assign(problem, { fix: { text: problem.fix.text, range: problem.fix.range.map( rangeIndex => rangeIndex + blockIndex * 4 ) } })) ), [] ); } } ); assert.strictEqual(fixResult.fixed, true); assert.strictEqual(fixResult.messages.length, 0); assert.strictEqual(fixResult.output, "FOO BAR BAZ"); }); }); }); describe("verifyAndFix", () => { it("Fixes the code", () => { const messages = linter.verifyAndFix("var a", { rules: { semi: 2 } }, { filename: "test.js" }); assert.strictEqual(messages.output, "var a;", "Fixes were applied correctly"); assert.isTrue(messages.fixed); }); it("does not require a third argument", () => { const fixResult = linter.verifyAndFix("var a", { rules: { semi: 2 } }); assert.deepStrictEqual(fixResult, { fixed: true, messages: [], output: "var a;" }); }); it("does not apply autofixes when fix argument is `false`", () => { const fixResult = linter.verifyAndFix("var a", { rules: { semi: 2 } }, { fix: false }); assert.strictEqual(fixResult.fixed, false); }); it("stops fixing after 10 passes", () => { linter.defineRule("add-spaces", context => ({ Program(node) { context.report({ node, message: "Add a space before this node.", fix: fixer => fixer.insertTextBefore(node, " ") }); } })); const fixResult = linter.verifyAndFix("a", { rules: { "add-spaces": "error" } }); assert.strictEqual(fixResult.fixed, true); assert.strictEqual(fixResult.output, `${" ".repeat(10)}a`); assert.strictEqual(fixResult.messages.length, 1); }); it("should throw an error if fix is passed but meta has no `fixable` property", () => { linter.defineRule("test-rule", { meta: { docs: {}, schema: [] }, create: context => ({ Program(node) { context.report(node, "hello world", {}, () => ({ range: [1, 1], text: "" })); } }) }); assert.throws(() => { linter.verify("0", { rules: { "test-rule": "error" } }); }, /Fixable rules should export a `meta\.fixable` property.$/); }); it("should not throw an error if fix is passed and there is no metadata", () => { linter.defineRule("test-rule", { create: context => ({ Program(node) { context.report(node, "hello world", {}, () => ({ range: [1, 1], text: "" })); } }) }); linter.verify("0", { rules: { "test-rule": "error" } }); }); }); describe("Edge cases", () => { it("should properly parse import statements when sourceType is module", () => { const code = "import foo from 'foo';"; const messages = linter.verify(code, { parserOptions: { sourceType: "module" } }); assert.strictEqual(messages.length, 0); }); it("should properly parse import all statements when sourceType is module", () => { const code = "import * as foo from 'foo';"; const messages = linter.verify(code, { parserOptions: { sourceType: "module" } }); assert.strictEqual(messages.length, 0); }); it("should properly parse default export statements when sourceType is module", () => { const code = "export default function initialize() {}"; const messages = linter.verify(code, { parserOptions: { sourceType: "module" } }); assert.strictEqual(messages.length, 0); }); it("should not crash when invalid parentheses syntax is encountered", () => { linter.verify("left = (aSize.width/2) - ()"); }); it("should not crash when let is used inside of switch case", () => { linter.verify("switch(foo) { case 1: let bar=2; }", { parserOptions: { ecmaVersion: 6 } }); }); it("should not crash when parsing destructured assignment", () => { linter.verify("var { a='a' } = {};", { parserOptions: { ecmaVersion: 6 } }); }); it("should report syntax error when a keyword exists in object property shorthand", () => { const messages = linter.verify("let a = {this}", { parserOptions: { ecmaVersion: 6 } }); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].fatal, true); }); it("should not rewrite env setting in core (https://github.com/eslint/eslint/issues/4814)", () => { /* * This test focuses on the instance of https://github.com/eslint/eslint/blob/v2.0.0-alpha-2/conf/environments.js#L26-L28 * This `verify()` takes the instance and runs https://github.com/eslint/eslint/blob/v2.0.0-alpha-2/lib/eslint.js#L416 */ linter.defineRule("test", () => ({})); linter.verify("var a = 0;", { env: { node: true }, parserOptions: { sourceType: "module" }, rules: { test: 2 } }); // This `verify()` takes the instance and tests that the instance was not modified. let ok = false; linter.defineRule("test", context => { assert( context.parserOptions.ecmaFeatures.globalReturn, "`ecmaFeatures.globalReturn` of the node environment should not be modified." ); ok = true; return {}; }); linter.verify("var a = 0;", { env: { node: true }, rules: { test: 2 } }); assert(ok); }); }); // only test in Node.js, not browser if (typeof window === "undefined") { const escope = require("eslint-scope"); const vk = require("eslint-visitor-keys"); describe("Custom parser", () => { const parserFixtures = path.join(__dirname, "../fixtures/parsers"), errorPrefix = "Parsing error: "; it("should have file path passed to it", () => { const code = "/* this is code */"; const parser = path.join(parserFixtures, "stub-parser.js"); const parseSpy = sinon.spy(require(parser), "parse"); linter.verify(code, { parser }, filename, true); sinon.assert.calledWithMatch(parseSpy, "", { filePath: filename }); }); it("should not report an error when JSX code contains a spread operator and JSX is enabled", () => { const code = "var myDivElement = <div {...this.props} />;"; const messages = linter.verify(code, { parser: "esprima", parserOptions: { jsx: true } }, "filename"); assert.strictEqual(messages.length, 0); }); it("should return an error when the custom parser can't be found", () => { const code = "var myDivElement = <div {...this.props} />;"; const messages = linter.verify(code, { parser: "esprima-xyz" }, "filename"); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].severity, 2); assert.strictEqual(messages[0].message, "Cannot find module 'esprima-xyz'"); }); it("should not throw or report errors when the custom parser returns unrecognized operators (https://github.com/eslint/eslint/issues/10475)", () => { const code = "null %% 'foo'"; const parser = path.join(parserFixtures, "unknown-operators", "unknown-logical-operator.js"); // This shouldn't throw const messages = linter.verify(code, { parser }, filename, true); assert.strictEqual(messages.length, 0); }); it("should not throw or report errors when the custom parser returns nested unrecognized operators (https://github.com/eslint/eslint/issues/10560)", () => { const code = "foo && bar %% baz"; const parser = path.join(parserFixtures, "unknown-operators", "unknown-logical-operator-nested.js"); // This shouldn't throw const messages = linter.verify(code, { parser }, filename, true); assert.strictEqual(messages.length, 0); }); it("should strip leading line: prefix from parser error", () => { const parser = path.join(parserFixtures, "line-error.js"); const messages = linter.verify(";", { parser }, "filename"); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].severity, 2); assert.strictEqual(messages[0].message, errorPrefix + require(parser).expectedError); }); it("should not modify a parser error message without a leading line: prefix", () => { const parser = path.join(parserFixtures, "no-line-error.js"); const messages = linter.verify(";", { parser }, "filename"); assert.strictEqual(messages.length, 1); assert.strictEqual(messages[0].severity, 2); assert.strictEqual(messages[0].message, errorPrefix + require(parser).expectedError); }); describe("if a parser provides 'visitorKeys'", () => { let types = []; let scopeAnalyzeStub = null; let sourceCode = null; beforeEach(() => { scopeAnalyzeStub = sandbox.spy(escope, "analyze"); const parser = path.join(parserFixtures, "enhanced-parser2.js"); types = []; linter.defineRule("collect-node-types", () => ({ "*"(node) { types.push(node.type); } })); linter.verify("@foo class A {}", { parser, rules: { "collect-node-types": "error" } }); sourceCode = linter.getSourceCode(); }); it("Traverser should use the visitorKeys (so 'types' includes 'Decorator')", () => { assert.deepStrictEqual( types, ["Program", "ClassDeclaration", "Decorator", "Identifier", "Identifier", "ClassBody"] ); }); it("eslint-scope should use the visitorKeys (so 'childVisitorKeys.ClassDeclaration' includes 'experimentalDecorators')", () => { assert(scopeAnalyzeStub.calledOnce); assert.deepStrictEqual( scopeAnalyzeStub.firstCall.args[1].childVisitorKeys.ClassDeclaration, vk.unionWith({ ClassDeclaration: ["experimentalDecorators"] }).ClassDeclaration ); }); it("should use the same visitorKeys if the source code object is reused", () => { const types2 = []; linter.defineRule("collect-node-types", () => ({ "*"(node) { types2.push(node.type); } })); linter.verify(sourceCode, { rules: { "collect-node-types": "error" } }); assert.deepStrictEqual( types2, ["Program", "ClassDeclaration", "Decorator", "Identifier", "Identifier", "ClassBody"] ); }); }); describe("if a parser provides 'scope'", () => { let scopeAnalyzeStub = null; let scope = null; let sourceCode = null; beforeEach(() => { scopeAnalyzeStub = sandbox.spy(escope, "analyze"); const parser = path.join(parserFixtures, "enhanced-parser3.js"); linter.defineRule("save-scope1", context => ({ Program() { scope = context.getScope(); } })); linter.verify("@foo class A {}", { parser, rules: { "save-scope1": 2 } }); sourceCode = linter.getSourceCode(); }); it("should not use eslint-scope analyzer", () => { assert(scopeAnalyzeStub.notCalled); }); it("should use the scope (so the global scope has the reference of '@foo')", () => { assert.strictEqual(scope.references.length, 1); assert.deepStrictEqual( scope.references[0].identifier.name, "foo" ); }); it("should use the same scope if the source code object is reused", () => { let scope2 = null; linter.defineRule("save-scope2", context => ({ Program() { scope2 = context.getScope(); } })); linter.verify(sourceCode, { rules: { "save-scope2": 2 } }, "test.js"); assert(scope2 !== null); assert(scope2 === scope); }); }); it("should not pass any default parserOptions to the parser", () => { const parser = path.join(parserFixtures, "throws-with-options.js"); const messages = linter.verify(";", { parser }, "filename"); assert.strictEqual(messages.length, 0); }); }); } });
/* globals Sammy, generalController, userController, toastr */ (function () { const app = Sammy(function () { this.before({}, () => generalController.updateHeader()); this.get('#/', sammy => sammy.redirect('#/home')); this.get('#/home', generalController.loadHome); this.get('#/user/sign-in', generalController.loadSignInPage); this.get('#/user/sign-up', generalController.loadSignUpPage); // User Controllers this.put('#/user/sign-in', userController.signIn); this.post('#/user/sign-up', userController.signUp); this.get('#/user/sign-out', userController.signOut); this.get('#/user/my-cookie', userController.loadHourlyCookiePage); this.post('#/cookie/reshare/:id', userController.reshareCookie); this.post('#/cookie/:type/:id', userController.rateCookie); }); $(function () { app.run('#/'); // Update rating dynamically $('#content').on('click', '.btn-like, .btn-dislike', (ev) => { let isLoggedIn = localStorage.getItem('authKey') ? true : false; if (!isLoggedIn) { toastr.error('You must be logged in to rate a cookie'); return; } let $target = $(ev.target); let splitHtml = $target.html().split(':'); let rateType = splitHtml[0].trim(); let currentRating = splitHtml[1].trim(); $target.html(`${rateType}: ${+currentRating + 1}`); }) }); } ());
var callbacks = []; var cors = require('cors'); module.exports = function(router) { var events = {}; router.post('/', cors(), function(req, res) { notify(req.body); res.json(["OKAY", 200]); }); events.registerCallback = function(callback) { callbacks.push(callback); } return events; } function notify(data) { callbacks.forEach(function(element, index, array) { element(data); }); }
import { compute } from './hamming'; describe('Hamming', () => { test('empty strands', () => { expect(compute('', '')).toEqual(0); }); xtest('single letter identical strands', () => { expect(compute('A', 'A')).toEqual(0); }); xtest('single letter different strands', () => { expect(compute('G', 'T')).toEqual(1); }); xtest('long identical strands', () => { expect(compute('GGACTGAAATCTG', 'GGACTGAAATCTG')).toEqual(0); }); xtest('long different strands', () => { expect(compute('GGACGGATTCTG', 'AGGACGGATTCT')).toEqual(9); }); xtest('disallow first strand longer', () => { expect(() => compute('AATG', 'AAA')).toThrow( new Error('left and right strands must be of equal length'), ); }); xtest('disallow second strand longer', () => { expect(() => compute('ATA', 'AGTG')).toThrow( new Error('left and right strands must be of equal length'), ); }); xtest('disallow left empty strand', () => { expect(() => compute('', 'G')).toThrow( new Error('left strand must not be empty'), ); }); xtest('disallow right empty strand', () => { expect(() => compute('G', '')).toThrow( new Error('right strand must not be empty'), ); }); });
/** * Bootstrap. * * @module imageCacheHoc */ 'use strict'; import imageCacheHoc from './lib/imageCacheHoc'; import FileSystemFactory, { FileSystem } from './lib/FileSystem'; export default imageCacheHoc; export { FileSystemFactory, FileSystem }; // Allow access to FS logic for advanced users.
if ($.writeln !== void 0) { var console = { log: function(obj) { $.writeln(obj); } }; } else { var console = window.console; } console.log($.os); try { console.log(app.name + ' ' + app.build); } catch (e) { console.log(app.name + ' ' + app.version); } //console.log(app.name + ' ' + app.build || app.version); console.log('Javascript version ' + $.version); require('./test/String/trim.js') require('./test/Array/every.js') require('./test/Array/filter.js') require('./test/Array/forEach.js') require('./test/Array/indexOf.js') require('./test/Array/isArray.js') require('./test/Array/lastIndexOf.js') require('./test/Array/map.js') require('./test/Array/reduce.js') require('./test/Array/reduceRight.js') require('./test/Array/some.js') require('./test/Function/bind.js') require('./test/Object/create.js'); require('./test/Object/defineProperties.js'); require('./test/Object/defineProperty.js'); require('./test/Object/freeze.js'); require('./test/Object/getOwnPropertyDescriptor.js'); require('./test/Object/getOwnPropertyNames.js'); require('./test/Object/getPrototypeOf.js'); require('./test/Object/isExtensible.js'); require('./test/Object/isFrozen.js'); require('./test/Object/isSealed.js'); require('./test/Object/keys.js'); require('./test/Object/preventExtensions.js'); require('./test/Object/seal.js');
// Created by Josh Hunt // joshhunt180@gmail.com // v1.4.0 tinymce.PluginManager.add('fontawesome', function (editor, url) { webApplicationIcons = [ ['adjust'], ['anchor'], ['archive'], ['area-chart'], ['arrows'], ['arrows-h'], ['arrows-v'], ['asterisk'], ['at'], ['automobile'], ['ban'], ['bank'], ['bar-chart'], ['bar-chart-o'], ['barcode'], ['bars'], ['bed'], ['beer'], ['bell'], ['bell-o'], ['bell-slash'], ['bell-slash-o'], ['bicycle'], ['binoculars'], ['birthday-cake'], ['bolt'], ['bomb'], ['book'], ['bookmark'], ['bookmark-o'], ['briefcase'], ['bug'], ['building'], ['building-o'], ['bullhorn'], ['bullseye'], ['bus'], ['cab'], ['calculator'], ['calendar'], ['calendar-o'], ['camera'], ['camera-retro'], ['car'], ['caret-square-o-down'], ['caret-square-o-left'], ['caret-square-o-right'], ['caret-square-o-up'], ['cart-arrow-down'], ['cart-plus'], ['cc'], ['certificate'], ['check'], ['check-circle'], ['check-circle-o'], ['check-square'], ['check-square-o'], ['child'], ['circle'], ['circle-o'], ['circle-o-notch'], ['circle-thin'], ['clock-o'], ['close'], ['cloud'], ['cloud-download'], ['cloud-upload'], ['code'], ['code-fork'], ['coffee'], ['cog'], ['cogs'], ['comment'], ['comment-o'], ['comments'], ['comments-o'], ['compass'], ['copyright'], ['credit-card'], ['crop'], ['crosshairs'], ['cube'], ['cubes'], ['cutlery'], ['dashboard'], ['database'], ['desktop'], ['diamond'], ['dot-circle-o'], ['download'], ['edit'], ['ellipsis-h'], ['ellipsis-v'], ['envelope'], ['envelope-o'], ['envelope-square'], ['eraser'], ['exchange'], ['exclamation'], ['exclamation-circle'], ['exclamation-triangle'], ['external-link'], ['external-link-square'], ['eye'], ['eye-slash'], ['eyedropper'], ['fax'], ['female'], ['fighter-jet'], ['file-archive-o'], ['file-audio-o'], ['file-code-o'], ['file-excel-o'], ['file-image-o'], ['file-movie-o'], ['file-pdf-o'], ['file-photo-o'], ['file-picture-o'], ['file-powerpoint-o'], ['file-sound-o'], ['file-video-o'], ['file-word-o'], ['file-zip-o'], ['film'], ['filter'], ['fire'], ['fire-extinguisher'], ['flag'], ['flag-checkered'], ['flag-o'], ['flash'], ['flask'], ['folder'], ['folder-o'], ['folder-open'], ['folder-open-o'], ['frown-o'], ['futbol-o'], ['gamepad'], ['gavel'], ['gear'], ['gears'], ['genderless'], ['gift'], ['glass'], ['globe'], ['graduation-cap'], ['group'], ['hdd-o'], ['headphones'], ['heart'], ['heart-o'], ['heartbeat'], ['history'], ['home'], ['hotel'], ['image'], ['inbox'], ['info'], ['info-circle'], ['institution'], ['key'], ['keyboard-o'], ['language'], ['laptop'], ['leaf'], ['legal'], ['lemon-o'], ['level-down'], ['level-up'], ['life-bouy'], ['life-buoy'], ['life-ring'], ['life-saver'], ['lightbulb-o'], ['line-chart'], ['location-arrow'], ['lock'], ['magic'], ['magnet'], ['mail-forward'], ['mail-reply'], ['mail-reply-all'], ['male'], ['map-marker'], ['meh-o'], ['microphone'], ['microphone-slash'], ['minus'], ['minus-circle'], ['minus-square'], ['minus-square-o'], ['mobile'], ['mobile-phone'], ['money'], ['moon-o'], ['mortar-board'], ['motorcycle'], ['music'], ['navicon'], ['newspaper-o'], ['paint-brush'], ['paper-plane'], ['paper-plane-o'], ['paw'], ['pencil'], ['pencil-square'], ['pencil-square-o'], ['phone'], ['phone-square'], ['photo'], ['picture-o'], ['pie-chart'], ['plane'], ['plug'], ['plus'], ['plus-circle'], ['plus-square'], ['plus-square-o'], ['power-off'], ['print'], ['puzzle-piece'], ['qrcode'], ['question'], ['question-circle'], ['quote-left'], ['quote-right'], ['random'], ['recycle'], ['refresh'], ['remove'], ['reorder'], ['reply'], ['reply-all'], ['retweet'], ['road'], ['rocket'], ['rss'], ['rss-square'], ['search'], ['search-minus'], ['search-plus'], ['send'], ['send-o'], ['server'], ['share'], ['share-alt'], ['share-alt-square'], ['share-square'], ['share-square-o'], ['shield'], ['ship'], ['shopping-cart'], ['sign-in'], ['sign-out'], ['signal'], ['sitemap'], ['sliders'], ['smile-o'], ['soccer-ball-o'], ['sort'], ['sort-alpha-asc'], ['sort-alpha-desc'], ['sort-amount-asc'], ['sort-amount-desc'], ['sort-asc'], ['sort-desc'], ['sort-down'], ['sort-numeric-asc'], ['sort-numeric-desc'], ['sort-up'], ['space-shuttle'], ['spinner'], ['spoon'], ['square'], ['square-o'], ['star'], ['star-half'], ['star-half-empty'], ['star-half-full'], ['star-half-o'], ['star-o'], ['street-view'], ['suitcase'], ['sun-o'], ['support'], ['tablet'], ['tachometer'], ['tag'], ['tags'], ['tasks'], ['taxi'], ['terminal'], ['thumb-tack'], ['thumbs-down'], ['thumbs-o-down'], ['thumbs-o-up'], ['thumbs-up'], ['ticket'], ['times'], ['times-circle'], ['times-circle-o'], ['tint'], ['toggle-down'], ['toggle-left'], ['toggle-off'], ['toggle-on'], ['toggle-right'], ['toggle-up'], ['trash'], ['trash-o'], ['tree'], ['trophy'], ['truck'], ['tty'], ['umbrella'], ['university'], ['unlock'], ['unlock-alt'], ['unsorted'], ['upload'], ['user'], ['user-plus'], ['user-secret'], ['user-times'], ['users'], ['video-camera'], ['volume-down'], ['volume-off'], ['volume-up'], ['warning'], ['wheelchair'], ['wifi'], ['wrench'] ] brandIcons = [ ['adn'], ['android'], ['angellist'], ['apple'], ['behance'], ['behance-square'], ['bitbucket'], ['bitbucket-square'], ['bitcoin'], ['btc'], ['buysellads'], ['cc-amex'], ['cc-discover'], ['cc-mastercard'], ['cc-paypal'], ['cc-stripe'], ['cc-visa'], ['codepen'], ['connectdevelop'], ['css3'], ['dashcube'], ['delicious'], ['deviantart'], ['digg'], ['dribbble'], ['dropbox'], ['drupal'], ['empire'], ['facebook'], ['facebook-f'], ['facebook-official'], ['facebook-square'], ['flickr'], ['forumbee'], ['foursquare'], ['ge'], ['git'], ['git-square'], ['github'], ['github-alt'], ['github-square'], ['gittip'], ['google'], ['google-plus'], ['google-plus-square'], ['google-wallet'], ['gratipay'], ['hacker-news'], ['html5'], ['instagram'], ['ioxhost'], ['joomla'], ['jsfiddle'], ['lastfm'], ['lastfm-square'], ['leanpub'], ['linkedin'], ['linkedin-square'], ['linux'], ['maxcdn'], ['meanpath'], ['medium'], ['openid'], ['pagelines'], ['paypal'], ['pied-piper'], ['pied-piper-alt'], ['pinterest'], ['pinterest-p'], ['pinterest-square'], ['qq'], ['ra'], ['rebel'], ['reddit'], ['reddit-square'], ['renren'], ['sellsy'], ['share-alt'], ['share-alt-square'], ['shirtsinbulk'], ['simplybuilt'], ['skyatlas'], ['skype'], ['slack'], ['slideshare'], ['soundcloud'], ['spotify'], ['stack-exchange'], ['stack-overflow'], ['steam'], ['steam-square'], ['stumbleupon'], ['stumbleupon-circle'], ['tencent-weibo'], ['trello'], ['tumblr'], ['tumblr-square'], ['twitch'], ['twitter'], ['twitter-square'], ['viacoin'], ['vimeo-square'], ['vine'], ['vk'], ['wechat'], ['weibo'], ['weixin'], ['whatsapp'], ['windows'], ['wordpress'], ['xing'], ['xing-square'], ['yahoo'], ['yelp'], ['youtube'], ['youtube-play'], ['youtube-square'] ] directionalIcons = [ ['angle-double-down'], ['angle-double-left'], ['angle-double-right'], ['angle-double-up'], ['angle-down'], ['angle-left'], ['angle-right'], ['angle-up'], ['arrow-circle-down'], ['arrow-circle-left'], ['arrow-circle-o-down'], ['arrow-circle-o-left'], ['arrow-circle-o-right'], ['arrow-circle-o-up'], ['arrow-circle-right'], ['arrow-circle-up'], ['arrow-down'], ['arrow-left'], ['arrow-right'], ['arrow-up'], ['arrows'], ['arrows-alt'], ['arrows-h'], ['arrows-v'], ['caret-down'], ['caret-left'], ['caret-right'], ['caret-square-o-down'], ['caret-square-o-left'], ['caret-square-o-right'], ['caret-square-o-up'], ['caret-up'], ['chevron-circle-down'], ['chevron-circle-left'], ['chevron-circle-right'], ['chevron-circle-up'], ['chevron-down'], ['chevron-left'], ['chevron-right'], ['chevron-up'], ['hand-o-down'], ['hand-o-left'], ['hand-o-right'], ['hand-o-up'], ['long-arrow-down'], ['long-arrow-left'], ['long-arrow-right'], ['long-arrow-up'], ['toggle-down'], ['toggle-left'], ['toggle-right'], ['toggle-up'] ] textEditorIcons = [ ['align-center'], ['align-justify'], ['align-left'], ['align-right'], ['bold'], ['chain'], ['chain-broken'], ['clipboard'], ['columns'], ['copy'], ['cut'], ['dedent'], ['eraser'], ['file'], ['file-o'], ['file-text'], ['file-text-o'], ['files-o'], ['floppy-o'], ['font'], ['header'], ['indent'], ['italic'], ['link'], ['list'], ['list-alt'], ['list-ol'], ['list-ul'], ['outdent'], ['paperclip'], ['paragraph'], ['paste'], ['repeat'], ['rotate-left'], ['rotate-right'], ['save'], ['scissors'], ['strikethrough'], ['subscript'], ['superscript'], ['table'], ['text-height'], ['text-width'], ['th'], ['th-large'], ['th-list'], ['underline'], ['undo'], ['unlink'] ] videoPlayerIcons = [ ['arrows-alt'], ['backward'], ['compress'], ['eject'], ['expand'], ['fast-backward'], ['fast-forward'], ['forward'], ['pause'], ['play'], ['play-circle'], ['play-circle-o'], ['step-backward'], ['step-forward'], ['stop'], ['youtube-play'] ] transportationIcons = [ ['ambulance'], ['automobile'], ['bicycle'], ['bus'], ['cab'], ['car'], ['fighter-jet'], ['motorcycle'], ['plane'], ['rocket'], ['ship'], ['space-shuttle'], ['subway'], ['taxi'], ['train'], ['truck'], ['wheelchair'] ] fileTypeIcons = [ ['file'], ['file-archive-o'], ['file-audio-o'], ['file-code-o'], ['file-excel-o'], ['file-image-o'], ['file-movie-o'], ['file-o'], ['file-pdf-o'], ['file-photo-o'], ['file-picture-o'], ['file-powerpoint-o'], ['file-sound-o'], ['file-text'], ['file-text-o'], ['file-video-o'], ['file-word-o'], ['file-zip-o'] ] genderIcons = [ ['circle-thin'], ['genderless'], ['mars'], ['mars-double'], ['mars-stroke'], ['mars-stroke-h'], ['mars-stroke-v'], ['mercury'], ['neuter'], ['transgender'], ['transgender-alt'], ['venus'], ['venus-double'], ['venus-mars'] ] formControlIcons = [ ['check-square'], ['check-square-o'], ['circle'], ['circle-o'], ['dot-circle-o'], ['minus-square'], ['minus-square-o'], ['plus-square'], ['plus-square-o'], ['square'], ['square-o'] ] currencyIcons = [ ['bitcoin'], ['btc'], ['cny'], ['dollar'], ['eur'], ['euro'], ['gbp'], ['ils'], ['inr'], ['jpy'], ['krw'], ['money'], ['rmb'], ['rouble'], ['rub'], ['ruble'], ['rupee'], ['shekel'], ['sheqel'], ['try'], ['turkish-lira'], ['usd'], ['won'], ['yen'] ] medicalIcons = [ ['ambulance'], ['h-square'], ['heart'], ['heart-o'], ['heartbeat'], ['hospital-o'], ['medkit'], ['plus-square'], ['stethoscope'], ['user-md'], ['wheelchair'] ] paymentIcons = [ ['cc-amex'], ['cc-discover'], ['cc-mastercard'], ['cc-paypal'], ['cc-stripe'], ['cc-visa'], ['credit-card'], ['google-wallet'], ['paypal'] ] spinnerIcons = [ ['circle-o-notch'], ['cog'], ['gear'], ['refresh'], ['spinner'] ] chartIcons = [ ['area-chart'], ['bar-chart'], ['bar-chart-o'], ['line-chart'], ['pie-chart'] ] function showDialog() { var win; var hideAccordion = 0; function groupHtml(iconGroup, iconTitle) { var gridHtml; if (hideAccordion == 0) { gridHtml = '<div class="mce-fontawesome-panel-accordion"><div class="mce-fontawesome-panel-title">' + iconTitle + '</div>'; gridHtml += '<div class="mce-fontawesome-panel-table" style="height: auto;"><table role="presentation" cellspacing="0"><tbody>'; hideAccordion = 1; } else { gridHtml = '<div class="mce-fontawesome-panel-accordion mce-fontawesome-panel-accordion-hide"><div class="mce-fontawesome-panel-title">' + iconTitle + '</div>'; gridHtml += '<div class="mce-fontawesome-panel-table"><table role="presentation" cellspacing="0"><tbody>'; } var width = 23; for (y = 0; y < (iconGroup.length / width); y++) { gridHtml += '<tr>'; for (x = 0; x < width; x++) { if (iconGroup[y * width + x]) { if (iconTitle == "Spinner") { gridHtml += '<td><i class="fa fa-spin fa-' + iconGroup[y * width + x] + '"> </i></td>'; } else { gridHtml += '<td><i class="fa fa-' + iconGroup[y * width + x] + '"> </i></td>'; } } } gridHtml += '</tr>'; } gridHtml += '</tbody></table></div></div>'; return gridHtml; } var panelHtml = groupHtml(webApplicationIcons, "Web Application") + groupHtml(fileTypeIcons, "File Type") + groupHtml(spinnerIcons, "Spinner") + groupHtml(formControlIcons, "Form Control") + groupHtml(currencyIcons, "Currency") + groupHtml(textEditorIcons, "Text Editor") + groupHtml(directionalIcons, "Directional") + groupHtml(videoPlayerIcons, "Video Player") + groupHtml(brandIcons, "Brand") + groupHtml(medicalIcons, "Medical") + groupHtml(transportationIcons, "Transportation") + groupHtml(genderIcons, "Gender") + groupHtml(paymentIcons, "Payment") + groupHtml(chartIcons, "Chart"); win = editor.windowManager.open({ autoScroll: true, width: 670, height: 500, title: "Icons", spacing: 20, padding: 10, classes: 'fontawesome-panel', items: [ { type: 'container', html: panelHtml, onclick: function (e) { var target = e.target; if (target.nodeName == 'I') { editor.execCommand('mceInsertContent', false, target.outerHTML + " "); win.close(); } }, }, { type: 'label', text: ' ' } ], buttons: [{ text: "Close", onclick: function () { win.close(); } }] }); // Accordion var accordionItems = new Array(); var divs = document.getElementsByTagName('div'); for (var i = 0; i < divs.length; i++) { if (divs[i].className == 'mce-fontawesome-panel-accordion' || divs[i].className == 'mce-fontawesome-panel-accordion mce-fontawesome-panel-accordion-hide') { accordionItems.push(divs[i]) } } // Assign onclick events to the accordion item headings for (var i = 0; i < accordionItems.length; i++) { var accordionTitle = getFirstChildWithTagName(accordionItems[i], 'DIV'); accordionTitle.onclick = toggleItem; } var firstDiv = accordionItems[0].getElementsByTagName('div')[1]; var firstDivHeight = firstDiv.offsetHeight; firstDiv.style.height = firstDivHeight + 'px'; function toggleItem() { var itemClass = this.parentNode.className; // Hide all items for (var i = 0; i < accordionItems.length; i++) { accordionItems[i].className = 'mce-fontawesome-panel-accordion mce-fontawesome-panel-accordion-hide'; accordionItems[i].getElementsByTagName('div')[1].style.height = "0"; } // Show this item if it was previously hidden if (itemClass == 'mce-fontawesome-panel-accordion mce-fontawesome-panel-accordion-hide') { var accordionItemContent = this; do accordionItemContent = accordionItemContent.nextSibling; while(accordionItemContent && accordionItemContent.nodeType !== 1); accordionItemContent.style.height = "auto"; var divHeight = accordionItemContent.offsetHeight; accordionItemContent.style.height = ""; this.parentNode.className = 'mce-fontawesome-panel-accordion'; var that = this; window.setTimeout(function () { accordionItemContent.style.height = divHeight + 'px'; }, 50); } } function getFirstChildWithTagName( element, tagName) { for (var i = 0; i < element.childNodes.length; i++) { if (element.childNodes[i].nodeName == tagName) { return element.childNodes[i]; } } } } editor.on('init', function() { csslink = editor.dom.create('link', { rel: 'stylesheet', href: url + '/css/fontawesome.min.css' }); document.getElementsByTagName('head')[0].appendChild(csslink); }); editor.addButton('fontawesome', { icon: 'flag', text: 'Ikoner', tooltip: 'Ikoner', onclick: showDialog }); editor.addMenuItem('fontawesome', { icon: 'flag', text: 'Ikoner', onclick: showDialog, context: 'insert' }); });
import { useEffect } from 'react'; import { usePluginReducer } from '@wq/react'; export default function MapIdentify() { const [{ instance: map, overlays }, { setHighlight }] = usePluginReducer( 'map' ); useEffect(() => { if (!map || map._alreadyConfiguredHandlers) { return; } map._alreadyConfiguredHandlers = true; overlays.forEach(overlay => { getIdentifyLayers(overlay).forEach(layer => { map.on('mouseenter', layer, onMouseEnter); map.on('mouseleave', layer, onMouseLeave); map.on('click', layer, evt => updateHighlight(evt, overlay)); }); }); function onMouseEnter() { map.getCanvas().style.cursor = 'pointer'; } function onMouseLeave() { map.getCanvas().style.cursor = ''; } function updateHighlight(evt, overlay) { const features = evt.features.map(feature => { feature.popup = overlay.popup; return feature; }); setHighlight({ type: 'FeatureCollection', features }); } }, [map, setHighlight]); return null; } function getIdentifyLayers(overlay) { if (overlay.identifyLayers) { return overlay.identifyLayers; } if (!overlay.popup) { return []; } if (overlay.type === 'geojson') { return ['symbol', 'line', 'fill', 'fill-extrusion', 'circle'].map( type => `${overlay.name}-${type}` ); } else if (overlay.type === 'vector-tile') { return ((overlay.style || {}).layers || []).map(layer => layer.id); } else { return []; } }
const express = require('express'); const path = require('path'); const cookieParser = require('cookie-parser'); const bodyParser = require('body-parser'); const session = require('express-session'); const passport = require('passport'); module.exports = (app, config) => { app.set('views', path.join(config.rootFolder, '/views')); app.set('view engine', 'hbs'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); app.use(cookieParser()); app.use(session({secret: 's3cr3t5tr1ng', resave: false, saveUninitialized: false})); app.use(passport.initialize()); app.use(passport.session()); app.use((req, res, next) => { if (req.user) { res.locals.user = req.user; } next(); }); app.use(express.static(path.join(config.rootFolder, 'public'))); };
module.exports = function(config) { config.set({ basePath: '', frameworks: ['jasmine'], reporters: ['progress'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Firefox'], singleRun: true }); };
const INITIAL_STATE = { loggedIn: false }; export function appReducer(state = INITIAL_STATE, action) { console.log("state " + JSON.stringify(state) + " action " + JSON.stringify(action)) return state; }
/** * Created by Admin on 11/21/15. */ var express = require('express'); var app = express(); var port = process.env.PORT || 3000; var mongoose = require('mongoose'); var passport = require('passport'); var flash = require('connect-flash'); var morgan = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var session = require('express-session'); var configDB = require('./configs/database.js'); mongoose.connect(configDB.url); app.use(morgan('dev')); app.use(cookieParser()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); app.set('view engine', 'ejs'); app.use(session({secret: 'ilovemywifebrunaevangelista'})); app.use(passport.initialize()); app.use(passport.session()); app.use(flash()); require('./app/routes.js')(app, passport); app.listen(port); console.log('Running server on port: %s', port);
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var DomainService = (function () { function DomainService(eventStore) { this._aggregateRoots = []; this._eventStore = eventStore; } DomainService.prototype.getAggregateRoot = function (c, callback, id) { var self = this; var similarAggregateRoots = self._aggregateRoots.filter(function (ar) { return ar.ID === id; }); if (similarAggregateRoots.length == 0) { var newAggregateRoot = new c(id); newAggregateRoot.attachEventStore(self._eventStore); // replay all actions for this Aggregate Root in the action store self._eventStore.getEventsForID(id, function (actions) { actions.forEach(function (action) { return newAggregateRoot.applyEvent(action); }); }); self._aggregateRoots.push(newAggregateRoot); callback(newAggregateRoot); return; } callback(similarAggregateRoots[0]); }; DomainService.prototype.applyEventToAllAggregates = function (event) { this._aggregateRoots.forEach(function (ar) { ar.applyEvent(event); }); }; DomainService.prototype.clearAggregateRoots = function () { this._aggregateRoots = []; }; return DomainService; }()); exports.DomainService = DomainService; //# sourceMappingURL=domainservice.js.map
module.exports = function (grunt) { // load plugins [ 'grunt-cafe-mocha', 'grunt-contrib-jshint' ].forEach(function (task) { grunt.loadNpmTasks(task); }); // configure plugins grunt.initConfig({ jshint: { app: ['app.js','settings.js', 'controllers/**/*.js', 'models/**/*.js', 'routes/**/*.js'], tests: ['Gruntfile.js', 'tests/**/*.js'] }, cafemocha: { all: {src: 'tests/tests-*.js', options: {ui: 'tdd'}} } }); // register tasks grunt.registerTask('default', ['jshint', 'cafemocha']); };
"use strict"; // 穴 Hole.prototype = new createjs.Container(); function Hole() { createjs.Container.call(this); this.width = 480; this.height = 502; this.holeH = 80; var hole = new createjs.Shape(); this.addChild(hole); hole.graphics.beginFill('black').drawEllipse(0, -this.holeH/2, this.width, this.holeH); } // 穴にもぐらを入れる Hole.prototype.addSakura = function() { var sakura = this.sakura = new Sakura(); this.addChild(sakura); sakura.y = 0; // もぐら絵の下端を穴に沿って切り抜く sakura.mask = new createjs.Shape(); sakura.mask.graphics .rect(-100, -sakura.height, sakura.width+100, sakura.height) .drawEllipse(0, -this.holeH/2, this.width, this.holeH); // もぐらを叩いた var hole = this; sakura.on('click', function(e) { hole.poka(function() { setTimeout(function() { hole.removeSakura(); hole.nyoki(); }, 1000); }); }); } // もぐらを取り除く Hole.prototype.removeSakura = function() { this.removeChild(this.sakura); delete this.sakura; } // ニョキ Hole.prototype.nyoki = function() { if (this.sakura) return; // すでにいたらやめる this.addSakura(); this.sakura.y = this.sakura.height; createjs.Tween.get(this.sakura) .to({y: 80}, 1000, createjs.Ease.backOut); } // ポカ Hole.prototype.poka = function(callback) { if (!callback) callback = function(){} var s = this.sakura; createjs.Tween.removeTweens(s); createjs.Tween.get(s) .to({scaleX: 1.2, scaleY: 0.8}, 180, createjs.Ease.sineOut) .to({scaleX: 0.8, scaleY: 1.1, y: s.height*1.1}, 120, createjs.Ease.sineIn) .to({scaleX: 1, scaleY: 1}) .call(callback); } // もぐら function Sakura() { var ids = IMAGE_IDS; var url = 'http://125.6.169.35/idolmaster/image_sp/card/quest/'+ ids[Math.floor(Math.random()*ids.length)] + '.png'; var bmp = new createjs.Bitmap(url); bmp.width = 480; bmp.height = 502; // ピクセルを取れないので適当な当たり判定 bmp.hitArea = new createjs.Shape(); bmp.hitArea.graphics.beginFill('black').rect(40, 100, 400, 402); // まんなか下端が中心 bmp.x = bmp.width/2; bmp.regX = bmp.width/2; bmp.regY = bmp.height; return bmp; } function Game(canvas) { var stage = new createjs.Stage(canvas); createjs.Touch.enable(stage); var holes = this.holes = []; var positions = [ {x: 40, y: 240}, {x: 360, y: 240}, {x: 200, y: 360}, {x: 40, y: 480}, {x: 360, y: 480}, ]; this.holes = positions.map(function(p) { var hole = new Hole(); holes.push(hole); stage.addChild(hole); hole.x = p.x; hole.y = p.y; hole.scaleX = hole.scaleY = 0.5; hole.nyoki(); return hole; }); return stage; } function main() { var canvas = document.getElementById('canvas'); canvas.addEventListener('selectstart', function(e) {e.preventDefault()}, false); var game = window.game = new Game(canvas); createjs.Ticker.addEventListener('tick', function() { game.update(); }); } main();
/* Project Name: Spine Admin Version: 1.6.0 Author: BharaniGuru R */var handleBootstrapWizards=function(){"use strict";$("#wizard").bwizard()};var FormWizard=function(){"use strict";return{init:function(){handleBootstrapWizards()}}}()
export default function filterTodos(todos, tagId) { if (tagId === -1) { return todos; } else { return todos.filter((todo) => todo.tag_ids.includes(tagId)); } };
// All symbols in the Inscriptional Parthian block as per Unicode v6.3.0: [ '\uD802\uDF40', '\uD802\uDF41', '\uD802\uDF42', '\uD802\uDF43', '\uD802\uDF44', '\uD802\uDF45', '\uD802\uDF46', '\uD802\uDF47', '\uD802\uDF48', '\uD802\uDF49', '\uD802\uDF4A', '\uD802\uDF4B', '\uD802\uDF4C', '\uD802\uDF4D', '\uD802\uDF4E', '\uD802\uDF4F', '\uD802\uDF50', '\uD802\uDF51', '\uD802\uDF52', '\uD802\uDF53', '\uD802\uDF54', '\uD802\uDF55', '\uD802\uDF56', '\uD802\uDF57', '\uD802\uDF58', '\uD802\uDF59', '\uD802\uDF5A', '\uD802\uDF5B', '\uD802\uDF5C', '\uD802\uDF5D', '\uD802\uDF5E', '\uD802\uDF5F' ];
exports.verify = function (data, field_names) { for (var i = 0; i < field_names.length; i++) { if (!data[field_names[i]]) { throw exports.error(400, field_names[i] + " not optional"); } } return true; } exports.error = function (code, message) { var e = new Error(message); e.code = code; return e; }; exports.db_error = function () { return exports.error("server_error", "Something horrible has happened with our database!"); } exports.vote_already_exists = function () { return exports.error(430, "A vote with this name already exists."); }; exports.candidate_already_exists = function () { return exports.error(430, "A candidate with this name already exists in this vote"); } exports.valid_candidate = function (fn) { if (Array.isArray(fn)) { if (fn.length > 1) return true; else return false; } else { console.log("************ valid_candidate false"); return false; } }; // HTTP 状态码 430 资源已存在
const _ = require('lodash'); const multiDB = require('mongoose-multi-connect'); module.exports = () => function (hook) { const locationGroup = _.get(hook, 'params.locationGroup'); this.getModel = multiDB.getByPostfix(locationGroup); return hook; };
'use strict'; describe('Controller: MainCtrl', function () { // load the controller's module beforeEach(module('centercareApp')); var MainCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); MainCtrl = $controller('MainCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings.length).toBe(3); }); });
'use strict'; // Modules require('should'); // Subject var subject = require('../lib/index.js'); describe('Module', function () { describe('.in_array()', function () { it('should return false when value is not in array', function () { var fn = subject.in_array(['abc', 16]); fn('def').should.equal(false); fn(8).should.equal(false); }); it('should return true when value is in array', function () { var fn = subject.in_array(['abc', 16]); fn('abc').should.equal(true); fn(16).should.equal(true); }); }); describe('.is_string()', function () { it('should return false when value not a string', function () { subject.is_string(123).should.equal(false); }); it('should return true when value is a literal string', function () { subject.is_string('literal').should.equal(true); }); it('should return true when value is a String object', function () { subject.is_string(new String('string-object')).should.equal(true); }); }); describe('.is_integer()', function () { it('should return true for a true number integer', function () { subject.is_integer(12).should.equal(true); subject.is_integer(120354).should.equal(true); subject.is_integer(2231).should.equal(true); }); it('should return false for a string integer', function () { subject.is_integer('12').should.equal(false); subject.is_integer('120354').should.equal(false); subject.is_integer('2231').should.equal(false); }); it('should return false for a number decimal', function () { subject.is_integer(1.12).should.equal(false); subject.is_integer(1.120354).should.equal(false); subject.is_integer(1.2231).should.equal(false); }); it('should return false for a string decimal', function () { subject.is_integer('1.12').should.equal(false); subject.is_integer('1.120354').should.equal(false); subject.is_integer('1.2231').should.equal(false); }); }); describe('.is_empty_object()', function () { it('should return true for an empty object literal', function () { subject.is_empty_object({}).should.equal(true); }); it('should return false for an object with one key', function () { subject.is_empty_object({ key : 'value' }).should.equal(false); }); it('should return false for an object with multiple keys', function () { subject.is_empty_object({ key1 : 'one', key2 : 'two' }).should.equal(false); }); }); describe('.string_to_boolean()', function () { it('should convert truthy values to true', function () { subject.string_to_boolean('true').should.equal(true); subject.string_to_boolean(true).should.equal(true); subject.string_to_boolean('1').should.equal(true); subject.string_to_boolean(1).should.equal(true); subject.string_to_boolean('yes').should.equal(true); }); it('should convert falsy values to false', function () { subject.string_to_boolean('false').should.equal(false); subject.string_to_boolean(false).should.equal(false); subject.string_to_boolean('0').should.equal(false); subject.string_to_boolean(0).should.equal(false); subject.string_to_boolean('no').should.equal(false); subject.string_to_boolean('null').should.equal(false); subject.string_to_boolean(null).should.equal(false); subject.string_to_boolean(undefined).should.equal(false); }); it('should handle bad input', function () { subject.string_to_boolean('notabool').should.equal(false); subject.string_to_boolean(134832).should.equal(false); }); }); describe('.string_to_integer()', function () { it('should convert a string to a base 10 integer', function () { subject.string_to_integer('102').should.equal(102); }); }); describe('.get_timestamp()', function () { it('should provide a valid UNIX timestamp in seconds', function () { var timestamp = subject.get_timestamp(); timestamp.should.be.type('number'); timestamp.toString().should.have.length(10); }); }); describe('.get_timestamp_ms()', function () { it('should provide a valid UNIX timestamp in milliseconds', function () { var timestamp = subject.get_timestamp_ms(); timestamp.should.be.type('number'); timestamp.toString().should.have.length(13); }); }); describe('.uuid_random()', function () { it('should provide a UUID', function () { subject.uuid_random().should.be.type('string').with.length(32); }); }); describe('.uuid()', function () { it('should provide a UUID', function () { subject.uuid().should.be.type('string').with.length(32); }); }); describe('.url_decode()', function () { it('should remove spaces from a string and nothing more (yet)', function () { subject.url_decode('hello%20there').should.be.type('string').and.equal('hello there'); subject.url_decode('super%20long%20sentence%20with%20spaces%20and%20stuff') .should.be.type('string').and.equal('super long sentence with spaces and stuff'); }); }); describe('.md5()', function () { // Use this terminal script to test: // Linux : echo -n "my-input" | md5sum // Mac OS X : echo -n "my-input" | md5 it('should MD5 hash "hello"', function () { subject.md5('hello').should.be.type('string').and.equal('5d41402abc4b2a76b9719d911017c592'); }); it('should MD5 hash "goodbye"', function () { subject.md5('goodbye').should.be.type('string').and.equal('69faab6268350295550de7d587bc323d'); }); it('should MD5 hash "hello" with salt correctly', function () { subject.md5('hello', 'salt').should.be.type('string').and.equal('baddf52697306303627b97b2721e964a'); }); it('should MD5 hash "goodbye" with salt correctly', function () { subject.md5('goodbye', 'salt').should.be.type('string').and.equal('4a81d497c14a768055a4d49196689d9e'); }); }); });
const storage = require('electron-json-storage'); module.exports = { getZoomFactor: function(callback) { this.get('zoom_factor', (data) => { let zoom_factor = data; if (!zoom_factor) { zoom_factor = 1; } callback(zoom_factor); }); }, setZoomFactor: function(data) { this.set('zoom_factor', data); }, getToken: function(callback) { this.get("token", callback); }, setToken: function(data) { this.set("token", data); }, get: function(name, callback) { storage.get(name, function(error, data) { if (error) throw error; if (Object.keys(data).length) { console.info(`${name}: ${data[name]}`); } callback(data[name]); }); }, set: function(name, data) { let param = {}; param[name] = data; storage.set(name, param, function(error) { if (error) throw error; }); } }
const isDeclaration = (node, parent) => { if ( (node.type === 'Identifier') && ( (parent.type === 'VariableDeclarator' && parent.id.name === node.name) || (parent.type === 'SequenceExpression' && undefined !== parent.expressions.find(x => x.name === node.name)) || (parent.type === 'FunctionDeclaration' && parent.id.name === node.name) || (parent.type === 'FunctionDeclaration' && undefined !== parent.params.find(x => x.name === node.name)) || (parent.type === 'MemberExpression' && parent.object.name === node.name && parent.object.start === node.start && -1 === ['apply', 'call'].indexOf(parent.property.name)) || (parent.type === 'ImportSpecifier' && parent.local.name === node.name) || (parent.type === 'ImportDefaultSpecifier' && parent.local.name === node.name) || (parent.type === 'ImportNamespaceSpecifier' && parent.local.name === node.name) | (parent.type === 'ExportSpecifier' && parent.exported.name === node.name) || (parent.type === 'ExportSpecifier' && parent.local.name === node.name) ) ) { return true } else { return false } } export default isDeclaration
// import { Meteor } from 'meteor/meteor'; // // import Nodes from '/imports/api/nodes/collection'; // // if (Nodes.find({ enabled: true }).count() < 1) { // // if no nodes, create them // Meteor.call('nodes:imagesUpdate'); // } else { // const latestNightlies = Nodes.find({ enabled: true, nightly: true }, { sort: { version: -1 } }).fetch(); // if (latestNightlies.length) { // const latestNightly = latestNightlies[0]; // const date = latestNightly.date; // const now = new Date(); // // if latest nightly was created more than 48h ago, create it again // if ((((+now) - (+date)) / 1000 / 60 / 60) > 48) { // Meteor.call('nodes:imagesUpdate'); // } // } // }
import alt from '../alt'; import WebAPI from '../utils/WebAPI'; import logError from '../utils/logError'; class UserFlowActions { constructor() { this.generateActions( 'formValueChange', 'signupSuccess', 'signupError', 'loginSuccess', 'loginError', 'logoutSuccess' ); } signup(signupData) { WebAPI .signup(signupData.email, signupData.password) .then((user) => { this.actions.signupSuccess(user); signupData.onSuccess(); }, (error) => { this.actions.signupError(error); }) .catch(logError); } login(loginData) { WebAPI .login(loginData.email, loginData.password) .then((user) => { this.actions.loginSuccess(user); loginData.onSuccess(); }, (error) => { this.actions.loginError(error); }) .catch(logError); } logout(callback) { WebAPI .logout() .then(() => { this.actions.logoutSuccess(); callback(); }) .catch(logError); } } export default alt.createActions(UserFlowActions);
// J.Whelan // This class wraps the 'mplayer' command line process - make sure it exists on the server var spawn = require('child_process').spawn , events = require('events') , os = require('os') , path = require('path') // , util = require('util') , _ = require('underscore') , fifojs = require('fifojs') , fs = require('fs') , logger = require('../../../shared/logging/Logger').getLogger('server') , MusicPlayerInterface = require('./IMusicPlayer') , STATUS = MusicPlayerInterface.STATUS ; var MPlayerSlave = function() { MusicPlayerInterface.call(this); events.EventEmitter.call(this); }; // util.inherits(MPlayerSlave, MusicPlayerInterface); // util.inherits(MPlayerSlave, events.EventEmitter); _(MPlayerSlave.prototype).extend(events.EventEmitter.prototype, MusicPlayerInterface.prototype); MPlayerSlave.prototype.audioStream = null; MPlayerSlave.prototype.getAudioFileInputStream = function() { return this.audioStream; }; MPlayerSlave.prototype.setAudioFileInputStream = function(stream) { this.audioStream = stream; }; MPlayerSlave.prototype.start = function (cmdLineOptions, flags) { var args = []; var slaveOptions = { // "slave" : "", // NOTE: causes issues when files are streamed via STDIN // "idle" : "", // "quiet" : "", "really-quiet" : "", "input" : "nodefault-bindings:conf=/dev/null:file=" + this.cmdFifoPath, "noconfig" : "all", "cache" : "512" // in KB }; var defFlags = { "stream" : false }; var options = _.defaults(slaveOptions, cmdLineOptions); flags = _.defaults({}, flags, defFlags); for(var prop in options) { if (options.hasOwnProperty(prop)){ args.unshift('-'+prop, options[prop] ); } } if (flags.stream) { // allow file to be streamed in args.push("-"); } // create the stream that control input can be fed into this.cmdFifoPath = createFifo(); this.cmdStream = fs.createWriteStream(this.cmdFifoPath, { flags: 'a+' }); // this.child = spawn('mplayer', args, {stdio: ['pipe', 'ignore', 'ignore']}); this.child = spawn('mplayer', args); this.child.on('exit', function (code, sig) { if (code !== null && sig === null) { var _this = this; // close the mplayer command strema this.cmdStream.end(function() { // attempt to cleanup FIFO file fs.unlinkSync(_this.cmdFifoPath); }); this.emit('done'); logger.debug("Slave instance has been killed."); } }.bind(this)); // mplayer stdin will be used to stream audio in this.setAudioFileInputStream(this.child.stdin); var _this = this; logger.warn('Are we detecting data passing through to mplayer?'); this.getAudioFileInputStream() .on("pipe", function(src) { logger.debug("Stream has STARTED piping into the MPlayerSlave"); logger.debug("Detect File Playing?"); _this.setStatus(STATUS.PLAYING); }) .on("unpipe", function(src) { logger.debug("Stream has STOPPED piping into the MPlayerSlave"); }); // pipe mplayer output to stdout this.child.stdout.pipe(process.stdout); this.child.stderr.pipe(process.stderr); logger.info('Slave instance started...'); logger.info('Command FIFO at: ' + this.cmdFifoPath); this.setStatus(STATUS.STOPPED); return this; }; MPlayerSlave.prototype.sendCommand = function(commandStr) { if (this.child != null) { this.cmdStream.write(commandStr + "\n"); logger.debug('Sent the following command(s) to mplayer: \n' + commandStr); } }; MPlayerSlave.prototype.play = function() { this.setStatus(STATUS.PLAYING); this.sendCommand('play'); }; MPlayerSlave.prototype.playFile = function(filepath) { this.setStatus(STATUS.PLAYING); this.sendCommand("loadfile '" + filepath +"'"); }; MPlayerSlave.prototype.pause = function() { if (this.getStatus === STATUS.PLAYING) { this.sendCommand('pause'); } }; MPlayerSlave.prototype.pauseToggle = function() { var curStatus = this.getStatus(); if (curStatus === STATUS.PLAYING) { this.setStatus(STATUS.PAUSED); } else if (curStatus === STATUS.PAUSED) { this.setStatus(STATUS.PLAYING); } else { this.setStatus(STATUS.UNKNOWN); } this.sendCommand("pause"); }; MPlayerSlave.prototype.stop = function() { this.setStatus(STATUS.STOPPED); this.sendCommand("stop"); }; MPlayerSlave.prototype.volumeAdjust = MPlayerSlave.prototype.volumeRelative = function(value) { this.sendCommand("volume " + value); }; MPlayerSlave.prototype.volume = MPlayerSlave.prototype.volumeAbsolute = function(value) { this.sendCommand("volume " + value + " 1"); }; MPlayerSlave.prototype.mute = function() { this.sendCommand("mute"); }; // this method was a test -- it would need a little more // work to extract output from the child process /* MPlayerSlave.prototype.logTrackTitle = function() { this.sendCommand("get_meta_title"); }; */ MPlayerSlave.prototype.close = MPlayerSlave.prototype.end = MPlayerSlave.prototype.kill = function () { /* this.getAudioFileInputStream().end(); this.child.stdout.pipe(process.stdout); this.child.stderr.pipe(process.stderr); */ this.setStatus(STATUS.STOPPED); this.sendCommand("quit 0"); // give it a couple seconds and check // if we need to forcefully kill the process var _this = this; setTimeout(function() { if(_this.child){ _this.child.kill('SIGTERM'); } }, 3000); }; /* MPlayerSlave.prototype.pause = function () { if (this.stopped) return; if(this.child){ this.child.kill('SIGSTOP'); } this.emit('pause'); }; MPlayerSlave.prototype.resume = function () { if (this.stopped) return this.play(); if(this.child){ this.child.kill('SIGCONT'); } this.emit('resume'); }; */ function createFifo() { var uniqueExtension = (Math.random()+"").substring(1), fifoPath = path.join(os.tmpdir(), 'mp_cmd_pipe' + uniqueExtension ); fifojs.mkfifo(fifoPath, 0777); return fifoPath; } module.exports = MPlayerSlave;
function euler485() { // Good luck! return true } euler485()
var data = JSON.stringify({ "codigoProduto": "119", "tipoConsumidor": "F", "documentoConsumidor": "42924057191", "cepOrigem": "14401-360", "codigoEstacaoConsultante": "123" }); var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.addEventListener("readystatechange", function () { if (this.readyState === 4) { console.log(this.responseText); } }); xhr.open("POST", "http://186.249.34.34/api/consulta"); xhr.setRequestHeader("content-type", "application/json"); xhr.setRequestHeader("authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJjb25zdWx0YUBlbnRlcnBsdWcuY29tLmJyIiwiZXhwIjoxNDcwODU3ODQwfQ.g7E2ABhES7yQXoIfpBTv30yDjal07EEI9i9Tu-d1Jjksxpv1UseaZpbjfqeNKF3pi_-xeX5ihN2EITPg184oaA"); xhr.setRequestHeader("cache-control", "no-cache"); xhr.send(data);
var moment = require("../../moment"); /************************************************** Vietnamese *************************************************/ exports["lang:vi"] = { setUp : function (cb) { moment.lang('vi'); cb(); }, tearDown : function (cb) { moment.lang('en'); cb(); }, "parse" : function (test) { test.expect(96); var i, tests = 'tháng 1,Th01_tháng 2,Th02_tháng 3,Th03_tháng 4,Th04_tháng 5,Th05_tháng 6,Th06_tháng 7,Th07_tháng 8,Th08_tháng 9,Th09_tháng 10,Th10_tháng 11,Th11_tháng 12,Th12'.split("_"); function equalTest(input, mmm, i) { test.equal(moment(input, mmm).month(), i, input + ' should be month ' + i); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(','); equalTest(tests[i][0], '[tháng] M', i); equalTest(tests[i][1], '[Th]M', i); equalTest(tests[i][0], '[tháng] MM', i); equalTest(tests[i][1], '[Th]MM', i); equalTest(tests[i][0].toLocaleLowerCase(), '[THÁNG] M', i); equalTest(tests[i][1].toLocaleLowerCase(), '[TH]M', i); equalTest(tests[i][0].toLocaleUpperCase(), '[THÁNG] MM', i); equalTest(tests[i][1].toLocaleUpperCase(), '[TH]MM', i); } test.done(); }, "format" : function (test) { test.expect(22); var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'chủ nhật, tháng 2 14 2010, 3:25:50 pm'], ['ddd, hA', 'CN, 3PM'], ['M Mo MM MMMM MMM', '2 2 02 tháng 2 Th02'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 chủ nhật CN CN'], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '6 6 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[ngày thứ] DDDo [của năm]', 'ngày thứ 45 của năm'], ['L', '14/02/2010'], ['LL', '14 tháng 2 năm 2010'], ['LLL', '14 tháng 2 năm 2010 15:25'], ['LLLL', 'chủ nhật, 14 tháng 2 năm 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 Th02 2010'], ['lll', '14 Th02 2010 15:25'], ['llll', 'CN, 14 Th02 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { test.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } test.done(); }, "format ordinal" : function (test) { test.expect(31); test.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); test.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); test.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); test.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); test.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); test.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); test.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); test.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); test.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); test.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); test.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); test.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); test.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); test.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); test.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); test.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); test.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); test.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); test.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); test.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); test.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); test.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); test.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); test.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); test.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); test.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); test.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); test.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); test.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); test.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); test.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); test.done(); }, "format month" : function (test) { test.expect(12); var i, expected = 'tháng 1,Th01_tháng 2,Th02_tháng 3,Th03_tháng 4,Th04_tháng 5,Th05_tháng 6,Th06_tháng 7,Th07_tháng 8,Th08_tháng 9,Th09_tháng 10,Th10_tháng 11,Th11_tháng 12,Th12'.split("_"); for (i = 0; i < expected.length; i++) { test.equal(moment([2011, i, 1]).format('MMMM,MMM'), expected[i], expected[i]); } test.done(); }, "format week" : function (test) { test.expect(7); var i, expected = 'chủ nhật CN CN_thứ hai T2 T2_thứ ba T3 T3_thứ tư T4 T4_thứ năm T5 T5_thứ sáu T6 T6_thứ bảy T7 T7'.split("_"); for (i = 0; i < expected.length; i++) { test.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } test.done(); }, "from" : function (test) { test.expect(30); var start = moment([2007, 1, 28]); test.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), "vài giây", "44 seconds = a few seconds"); test.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), "một phút", "45 seconds = a minute"); test.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), "một phút", "89 seconds = a minute"); test.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), "2 phút", "90 seconds = 2 minutes"); test.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), "44 phút", "44 minutes = 44 minutes"); test.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), "một giờ", "45 minutes = an hour"); test.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), "một giờ", "89 minutes = an hour"); test.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), "2 giờ", "90 minutes = 2 hours"); test.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), "5 giờ", "5 hours = 5 hours"); test.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), "21 giờ", "21 hours = 21 hours"); test.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), "một ngày", "22 hours = a day"); test.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), "một ngày", "35 hours = a day"); test.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), "2 ngày", "36 hours = 2 days"); test.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), "một ngày", "1 day = a day"); test.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), "5 ngày", "5 days = 5 days"); test.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), "25 ngày", "25 days = 25 days"); test.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), "một tháng", "26 days = a month"); test.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), "một tháng", "30 days = a month"); test.equal(start.from(moment([2007, 1, 28]).add({d: 45}), true), "một tháng", "45 days = a month"); test.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), "2 tháng", "46 days = 2 months"); test.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), "2 tháng", "75 days = 2 months"); test.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), "3 tháng", "76 days = 3 months"); test.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), "một tháng", "1 month = a month"); test.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), "5 tháng", "5 months = 5 months"); test.equal(start.from(moment([2007, 1, 28]).add({d: 344}), true), "11 tháng", "344 days = 11 months"); test.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), "một năm", "345 days = a year"); test.equal(start.from(moment([2007, 1, 28]).add({d: 547}), true), "một năm", "547 days = a year"); test.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), "2 năm", "548 days = 2 years"); test.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), "một năm", "1 year = a year"); test.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), "5 năm", "5 years = 5 years"); test.done(); }, "suffix" : function (test) { test.expect(2); test.equal(moment(30000).from(0), "vài giây tới", "prefix"); test.equal(moment(0).from(30000), "vài giây trước", "suffix"); test.done(); }, "now from now" : function (test) { test.expect(1); test.equal(moment().fromNow(), "vài giây trước", "now from now should display as in the past"); test.done(); }, "fromNow" : function (test) { test.expect(2); test.equal(moment().add({s: 30}).fromNow(), "vài giây tới", "in a few seconds"); test.equal(moment().add({d: 5}).fromNow(), "5 ngày tới", "in 5 days"); test.done(); }, "calendar day" : function (test) { test.expect(6); var a = moment().hours(2).minutes(0).seconds(0); test.equal(moment(a).calendar(), "Hôm nay lúc 02:00", "today at the same time"); test.equal(moment(a).add({ m: 25 }).calendar(), "Hôm nay lúc 02:25", "Now plus 25 min"); test.equal(moment(a).add({ h: 1 }).calendar(), "Hôm nay lúc 03:00", "Now plus 1 hour"); test.equal(moment(a).add({ d: 1 }).calendar(), "Ngày mai lúc 02:00", "tomorrow at the same time"); test.equal(moment(a).subtract({ h: 1 }).calendar(), "Hôm nay lúc 01:00", "Now minus 1 hour"); test.equal(moment(a).subtract({ d: 1 }).calendar(), "Hôm qua lúc 02:00", "yesterday at the same time"); test.done(); }, "calendar next week" : function (test) { test.expect(15); var i, m; for (i = 2; i < 7; i++) { m = moment().add({ d: i }); test.equal(m.calendar(), m.format('dddd [tuần tới lúc] LT'), "Today + " + i + " days current time"); m.hours(0).minutes(0).seconds(0).milliseconds(0); test.equal(m.calendar(), m.format('dddd [tuần tới lúc] LT'), "Today + " + i + " days beginning of day"); m.hours(23).minutes(59).seconds(59).milliseconds(999); test.equal(m.calendar(), m.format('dddd [tuần tới lúc] LT'), "Today + " + i + " days end of day"); } test.done(); }, "calendar last week" : function (test) { test.expect(15); var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({ d: i }); test.equal(m.calendar(), m.format('dddd [tuần rồi lúc] LT'), "Today - " + i + " days current time"); m.hours(0).minutes(0).seconds(0).milliseconds(0); test.equal(m.calendar(), m.format('dddd [tuần rồi lúc] LT'), "Today - " + i + " days beginning of day"); m.hours(23).minutes(59).seconds(59).milliseconds(999); test.equal(m.calendar(), m.format('dddd [tuần rồi lúc] LT'), "Today - " + i + " days end of day"); } test.done(); }, "calendar all else" : function (test) { test.expect(4); var weeksAgo = moment().subtract({ w: 1 }), weeksFromNow = moment().add({ w: 1 }); test.equal(weeksAgo.calendar(), weeksAgo.format('L'), "1 week ago"); test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), "in 1 week"); weeksAgo = moment().subtract({ w: 2 }); weeksFromNow = moment().add({ w: 2 }); test.equal(weeksAgo.calendar(), weeksAgo.format('L'), "2 weeks ago"); test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), "in 2 weeks"); test.done(); }, // Monday is the first day of the week. // The week that contains Jan 4th is the first week of the year. "weeks year starting sunday" : function (test) { test.expect(5); test.equal(moment([2012, 0, 1]).week(), 52, "Jan 1 2012 should be week 52"); test.equal(moment([2012, 0, 2]).week(), 1, "Jan 2 2012 should be week 1"); test.equal(moment([2012, 0, 8]).week(), 1, "Jan 8 2012 should be week 1"); test.equal(moment([2012, 0, 9]).week(), 2, "Jan 9 2012 should be week 2"); test.equal(moment([2012, 0, 15]).week(), 2, "Jan 15 2012 should be week 2"); test.done(); }, "weeks year starting monday" : function (test) { test.expect(5); test.equal(moment([2007, 0, 1]).week(), 1, "Jan 1 2007 should be week 1"); test.equal(moment([2007, 0, 7]).week(), 1, "Jan 7 2007 should be week 1"); test.equal(moment([2007, 0, 8]).week(), 2, "Jan 8 2007 should be week 2"); test.equal(moment([2007, 0, 14]).week(), 2, "Jan 14 2007 should be week 2"); test.equal(moment([2007, 0, 15]).week(), 3, "Jan 15 2007 should be week 3"); test.done(); }, "weeks year starting tuesday" : function (test) { test.expect(6); test.equal(moment([2007, 11, 31]).week(), 1, "Dec 31 2007 should be week 1"); test.equal(moment([2008, 0, 1]).week(), 1, "Jan 1 2008 should be week 1"); test.equal(moment([2008, 0, 6]).week(), 1, "Jan 6 2008 should be week 1"); test.equal(moment([2008, 0, 7]).week(), 2, "Jan 7 2008 should be week 2"); test.equal(moment([2008, 0, 13]).week(), 2, "Jan 13 2008 should be week 2"); test.equal(moment([2008, 0, 14]).week(), 3, "Jan 14 2008 should be week 3"); test.done(); }, "weeks year starting wednesday" : function (test) { test.expect(6); test.equal(moment([2002, 11, 30]).week(), 1, "Dec 30 2002 should be week 1"); test.equal(moment([2003, 0, 1]).week(), 1, "Jan 1 2003 should be week 1"); test.equal(moment([2003, 0, 5]).week(), 1, "Jan 5 2003 should be week 1"); test.equal(moment([2003, 0, 6]).week(), 2, "Jan 6 2003 should be week 2"); test.equal(moment([2003, 0, 12]).week(), 2, "Jan 12 2003 should be week 2"); test.equal(moment([2003, 0, 13]).week(), 3, "Jan 13 2003 should be week 3"); test.done(); }, "weeks year starting thursday" : function (test) { test.expect(6); test.equal(moment([2008, 11, 29]).week(), 1, "Dec 29 2008 should be week 1"); test.equal(moment([2009, 0, 1]).week(), 1, "Jan 1 2009 should be week 1"); test.equal(moment([2009, 0, 4]).week(), 1, "Jan 4 2009 should be week 1"); test.equal(moment([2009, 0, 5]).week(), 2, "Jan 5 2009 should be week 2"); test.equal(moment([2009, 0, 11]).week(), 2, "Jan 11 2009 should be week 2"); test.equal(moment([2009, 0, 13]).week(), 3, "Jan 12 2009 should be week 3"); test.done(); }, "weeks year starting friday" : function (test) { test.expect(6); test.equal(moment([2009, 11, 28]).week(), 53, "Dec 28 2009 should be week 53"); test.equal(moment([2010, 0, 1]).week(), 53, "Jan 1 2010 should be week 53"); test.equal(moment([2010, 0, 3]).week(), 53, "Jan 3 2010 should be week 53"); test.equal(moment([2010, 0, 4]).week(), 1, "Jan 4 2010 should be week 1"); test.equal(moment([2010, 0, 10]).week(), 1, "Jan 10 2010 should be week 1"); test.equal(moment([2010, 0, 11]).week(), 2, "Jan 11 2010 should be week 2"); test.done(); }, "weeks year starting saturday" : function (test) { test.expect(6); test.equal(moment([2010, 11, 27]).week(), 52, "Dec 27 2010 should be week 52"); test.equal(moment([2011, 0, 1]).week(), 52, "Jan 1 2011 should be week 52"); test.equal(moment([2011, 0, 2]).week(), 52, "Jan 2 2011 should be week 52"); test.equal(moment([2011, 0, 3]).week(), 1, "Jan 3 2011 should be week 1"); test.equal(moment([2011, 0, 9]).week(), 1, "Jan 9 2011 should be week 1"); test.equal(moment([2011, 0, 10]).week(), 2, "Jan 10 2011 should be week 2"); test.done(); }, "weeks year starting sunday formatted" : function (test) { test.expect(5); test.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52', "Jan 1 2012 should be week 52"); test.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1', "Jan 2 2012 should be week 1"); test.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1', "Jan 8 2012 should be week 1"); test.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2', "Jan 9 2012 should be week 2"); test.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2', "Jan 15 2012 should be week 2"); test.done(); }, "returns the name of the language" : function (test) { if (typeof module !== 'undefined' && module.exports) { test.equal(require('../../lang/vi'), 'vi', "module should export vi"); } test.done(); } };
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Footer.css'; import Link from '../Link'; class Footer extends React.Component { render() { return ( <div className={s.root}> <div className={s.container}> <span className={s.text}> 4505 Spicewood Springs Road Suite 100, Austin, Texas 78759 <span className={s.spacer}> | </span> <a href="tel:512-345-3955">(512)&nbsp;345-3955</a> <span className={s.spacer}> | </span> <a href="mailto:druesink@earthlink.net">druesink@earthlink.net</a> </span> <br /><br /> <span className={s.text}>© {new Date().getFullYear()} Donna McCoy Ruesink, D.D.S.</span> </div> </div> ); } } export default withStyles(s)(Footer);
const fs = require('fs'); const oneLineLog = require('single-line-log').stdout; // const axios = require('./axios'); // const { modes } = require('./constants'); const { simplifyMods, trimModsForRankings, files, // parallelRun, // delay, writeFileSync, } = require('./utils'); // const apikey = JSON.parse(fs.readFileSync('./config.json')).apikey; // const getUrl = (userId, modeId) => // `https://osu.ppy.sh/api/get_user?k=${apikey}&u=${userId}&type=id&m=${modeId}`; // const fetchUser = (userId, modeId, retryCount = 0) => { // if (retryCount > 3) { // return Promise.reject(new Error('Too many retries')); // } // retryCount && oneLineLog(`Retry #${retryCount}`); // return axios.get(getUrl(userId, modeId)).catch(err => { // console.log('Error:', err.message); // return delay(5000).then(() => fetchUser(userId, modeId, retryCount + 1)); // }); // }; // const fetchUserRank = ({ userId, modeId }) => { // return fetchUser(userId, modeId) // .then(({ data }) => { // return data[0].pp_rank; // }) // .catch(error => { // console.log('\x1b[33m%s\x1b[0m', error.message); // }); // }; module.exports = mode => { console.log('3. CALCULATING RANKINGS'); let players = JSON.parse(fs.readFileSync(files.userIdsList(mode))); players.sort((a, b) => b.pp - a.pp); // to get rank # players.forEach((pl, index) => { pl.rank1 = index + 1; }); const scores = JSON.parse(fs.readFileSync(files.userMapsList(mode))); const updateDatePerUser = JSON.parse(fs.readFileSync(files.userMapsDates(mode))); const mapsData = JSON.parse(fs.readFileSync(files.mapsDetailedList(mode))); console.log('Calculating overweightness for every map'); // Calculate maximum and average Overweightness let maxOW = 0; let sum = 0; let count = 0; const mapsDataWithAdjValue = mapsData .map(item => { const x = +item.x / Math.pow(item.adj || 1, 0.65) / Math.pow(+item.h || 1, 0.35); maxOW = maxOW < x ? x : maxOW; if (x > 0.00005) { sum += x; count++; } return { ...item, x, }; }) .sort((a, b) => b.x - a.x); const averageOW = sum / count; console.log('Max OW:', maxOW, 'Avg OW:', averageOW); console.log('Creating a maps dictionary'); const mapsDictionary = mapsDataWithAdjValue.reduce((dict, map) => { if (dict[map.b]) { dict[map.b].push(map); } else { dict[map.b] = [map]; } return dict; }, {}); const getFarmValue = (player, index, array) => { const playerScores = scores[player.id]; if (playerScores) { index % 100 === 0 && oneLineLog(`// Getting values for player #${index}/${array.length} - ${player.name}`); // no scores - no player in rankings let newScores = []; playerScores.forEach(scoreString => { const scoreArray = scoreString.split('_'); const score = { b: scoreArray[0], m: scoreArray[1], pp: scoreArray[2], }; const allMaps = mapsDictionary[score.b]; const nomodOrDtMaps = allMaps.filter(map => map.m == trimModsForRankings(score.m)); if (allMaps.length) { const thisMap = allMaps.find(map => map.m == simplifyMods(score.m)); const thisMapX = thisMap ? thisMap.x : 0; const maxLocal = allMaps.reduce((acc, map) => (acc > map.x ? acc : map.x), 0); const maxLocalNomodOrDt = nomodOrDtMaps.reduce( (acc, map) => (acc > map.x ? acc : map.x), 0 ); const adjustedX = (maxLocal + maxLocalNomodOrDt + 3 * thisMapX) / 5; const adjust = adjustedX > averageOW ? Math.sqrt((adjustedX - averageOW) / (maxOW - averageOW)) : Math.sqrt(adjustedX / averageOW) - 1; let pp = score.pp; pp *= 1 - adjust * (adjustedX > averageOW ? 0.2 : 0.125); newScores.push({ n: `${allMaps[0].art} - ${allMaps[0].t} [${allMaps[0].v}]`, // map name m: score.m, // mods number b: allMaps[0].b, // beatmap id p1: Math.round(score.pp), // previous PP p2: Math.round(pp), // new PP }); } else { console.log(); console.log(player.name, '- not found any maps -', score); newScores.push({ n: score.b, // map name m: score.m, // mods number b: score.b, // beatmap id p1: Math.round(score.pp), // previous PP p2: Math.round(score.pp), // new PP }); } }); newScores = newScores.sort((a, b) => b.p2 - a.p2); const ppDiff = newScores.reduce((ppDiffSum, score) => ppDiffSum + score.p2 - score.p1, 0); const minuteUpdated = updateDatePerUser[player.id]; return { n: player.name, id: player.id, ppDiff, minuteUpdated, s: newScores.slice(0, 50), // list of recalculated scores - only keep top 50 now! }; } }; const rankings = players.map(getFarmValue).filter(a => a && a.s && a.s.length); // filter out no scores players writeFileSync(files.dataRankings(mode), JSON.stringify(rankings)); console.log(); console.log('Finished calculating rankings!'); /* return parallelRun({ items: rankings, job: player => { return fetchUserRank({ userId: player.id, modeId: mode.id }) .then(rank => { oneLineLog( `Fetched #${rank} for (${rankings.indexOf(player)}/${rankings.length}) - ${player.n}` ); player.rank1 = rank; }) .catch(e => { console.log(); console.log(`Couldnt get rank for ${player.n}`); console.log(e.message); }); }, }).then(() => { rankings = rankings.filter(player => player.rank1); rankings = rankings.sort((a, b) => a.rank1 - b.rank1); writeFileSync(files.dataRankings(mode), JSON.stringify(rankings)); console.log(); console.log('Finished calculating rankings!'); }); */ }; // module.exports(modes.osu);
(function (lib, img, cjs) { var p; // shortcut to reference prototypes // library properties: lib.properties = { width: 400, height: 300, fps: 30, color: "#FFFFFF", manifest: [] }; // stage content: (lib.assets_html5 = function() { this.initialize(); }).prototype = p = new cjs.Container(); p.nominalBounds = new cjs.Rectangle(199,150,401,300); // symbols: (lib.polygon_vertex = function() { this.initialize(); // レイヤー 1 this.shape = new cjs.Shape(); this.shape.graphics.f("#66CC00").s().p("AgNAOQgFgGAAgIQAAgHAFgGQAGgFAHAAQAIAAAGAFQAFAGAAAHQAAAIgFAGQgGAFgIAAQgHAAgGgFg"); this.addChild(this.shape); }).prototype = p = new cjs.Container(); p.nominalBounds = new cjs.Rectangle(-2,-2,4,4); (lib.circle = function() { this.initialize(); // レイヤー 1 this.shape = new cjs.Shape(); this.shape.graphics.f("#FF6600").s().p("AgiAjQgPgPAAgUQAAgUAPgOQAPgPATAAQAUAAAPAPQAPAOAAAUQAAAUgPAPQgPAPgUAAQgTAAgPgPg"); this.addChild(this.shape); }).prototype = p = new cjs.Container(); p.nominalBounds = new cjs.Rectangle(-5,-5,10,10); (lib.box = function() { this.initialize(); // レイヤー 1 this.shape = new cjs.Shape(); this.shape.graphics.f("#3399FF").s().p("AgIAJIAAgRIARAAIAAARg"); this.addChild(this.shape); }).prototype = p = new cjs.Container(); p.nominalBounds = new cjs.Rectangle(-1,-1,2,2); (lib.samplecircleSampleCircle = function() { this.initialize(); // this.ball = new lib.circle(); this.ball.setTransform(135,121,3,3); // anonymous this.instance = new lib.circle(); this.instance.setTransform(83,39); this.instance_1 = new lib.circle(); this.instance_1.setTransform(258,72,4.6,4.6); this.addChild(this.instance_1,this.instance,this.ball); }).prototype = p = new cjs.Container(); p.nominalBounds = new cjs.Rectangle(78,34,203,102); (lib.sampleboxSampleBox = function() { this.initialize(); // this.floor = new lib.box(); this.floor.setTransform(52,125,13,29.995,-55.7); // anonymous this.instance = new lib.box(); this.instance.setTransform(323,100,5,82.489,62.5); this.instance_1 = new lib.box(); this.instance_1.setTransform(200,5,200.018,4.999); this.instance_2 = new lib.box(); this.instance_2.setTransform(200,295,200.018,4.999); this.instance_3 = new lib.box(); this.instance_3.setTransform(395,150,5,149.979); this.instance_4 = new lib.box(); this.instance_4.setTransform(4,150,5,149.979); this.addChild(this.instance_4,this.instance_3,this.instance_2,this.instance_1,this.instance,this.floor); }).prototype = p = new cjs.Container(); p.nominalBounds = new cjs.Rectangle(-1,0,401,300); (lib._1 = function() { this.initialize(); // レイヤー 1 this.p6 = new lib.polygon_vertex(); this.p6.setTransform(20.5,42.5); this.p5 = new lib.polygon_vertex(); this.p5.setTransform(75.5,58); this.p4 = new lib.polygon_vertex(); this.p4.setTransform(100.5,18); this.p3 = new lib.polygon_vertex(); this.p3.setTransform(92.5,-25); this.p2 = new lib.polygon_vertex(); this.p2.setTransform(58,-54); this.p1 = new lib.polygon_vertex(); this.p1.setTransform(26,-44); this.p0 = new lib.polygon_vertex(); this.addChild(this.p0,this.p1,this.p2,this.p3,this.p4,this.p5,this.p6); }).prototype = p = new cjs.Container(); p.nominalBounds = new cjs.Rectangle(-2,-56,104.5,116); (lib._0 = function() { this.initialize(); // レイヤー 1 this.p3 = new lib.polygon_vertex(); this.p3.setTransform(0,16); this.p2 = new lib.polygon_vertex(); this.p2.setTransform(72,12); this.p1 = new lib.polygon_vertex(); this.p1.setTransform(72,0); this.p0 = new lib.polygon_vertex(); this.addChild(this.p0,this.p1,this.p2,this.p3); }).prototype = p = new cjs.Container(); p.nominalBounds = new cjs.Rectangle(-2,-2,76,20); (lib.samplepolygonSamplePolygon = function() { this.initialize(); // this.flipper = new lib._0(); this.flipper.setTransform(47,213); // anonymous this.instance = new lib._1(); this.instance.setTransform(239,213); this.addChild(this.instance,this.flipper); }).prototype = p = new cjs.Container(); p.nominalBounds = new cjs.Rectangle(45,157,296.5,116); })(lib = lib||{}, images = images||{}, createjs = createjs||{}); var lib, images, createjs;
var app = playground({ smoothing: false, create: function(){ this.loadAtlases("map", "characters", "ui"); this.loadSounds("enemy1", "enemy2", "enemy3", "hurt1", "hurt2", "hurt3", "step1", "step2", "step3", "love1", "love2", "love3" ); }, ready: function(){ this.setState(Engine.Map); }, });
require("globals"); require("./zone-js/dist/zone-nativescript"); require("reflect-metadata"); require("./polyfills/array"); require("./polyfills/console"); var common_1 = require("@angular/common"); var renderer_1 = require("./renderer"); var detached_loader_1 = require("./common/detached-loader"); var dialogs_1 = require("./directives/dialogs"); var core_1 = require("@angular/core"); var platform_providers_1 = require("./platform-providers"); var directives_1 = require("./directives"); function errorHandlerFactory() { return new core_1.ErrorHandler(true); } exports.errorHandlerFactory = errorHandlerFactory; ; var NativeScriptModule = (function () { function NativeScriptModule() { } NativeScriptModule = __decorate([ core_1.NgModule({ declarations: [ detached_loader_1.DetachedLoader, dialogs_1.ModalDialogHost ].concat(directives_1.NS_DIRECTIVES), providers: [ { provide: core_1.ErrorHandler, useFactory: errorHandlerFactory }, platform_providers_1.defaultFrameProvider, platform_providers_1.defaultPageProvider, platform_providers_1.defaultDeviceProvider, renderer_1.NativeScriptRootRenderer, { provide: core_1.RootRenderer, useClass: renderer_1.NativeScriptRootRenderer }, renderer_1.NativeScriptRenderer, { provide: core_1.Renderer, useClass: renderer_1.NativeScriptRenderer }, dialogs_1.ModalDialogService ], entryComponents: [ detached_loader_1.DetachedLoader, ], imports: [ common_1.CommonModule, core_1.ApplicationModule, ], exports: [ common_1.CommonModule, core_1.ApplicationModule, detached_loader_1.DetachedLoader, dialogs_1.ModalDialogHost ].concat(directives_1.NS_DIRECTIVES), schemas: [core_1.NO_ERRORS_SCHEMA] }), __metadata('design:paramtypes', []) ], NativeScriptModule); return NativeScriptModule; }()); exports.NativeScriptModule = NativeScriptModule; //# sourceMappingURL=nativescript.module.js.map
import Transformer from '../components/_transformer.js'; import SegmentForm from '../components/SegmentForm.vue'; window.remplib = typeof(remplib) === 'undefined' ? {} : window.remplib; (function() { 'use strict'; remplib.segmentForm = { bind: (el, segment) => { return new Vue({ el: el, render: h => h(SegmentForm, { props: Transformer.transformKeys(segment) }), }); } } })();
import cjs from 'rollup-plugin-commonjs'; import babel from 'rollup-plugin-babel'; import replace from 'rollup-plugin-replace'; import uglify from 'rollup-plugin-uglify'; import resolve from 'rollup-plugin-node-resolve'; export default { entry: './src/ReactNoUnmountHide.js', format: 'umd', moduleName: 'ReactNoUnmountHide', dest: './dist/ReactNoUnmountHide.js', plugins: [ babel({ exclude: 'node_modules/**' }), cjs({ exclude: 'node_modules/process-es6/**', include: [ 'node_modules/fbjs/**', 'node_modules/object-assign/**', 'node_modules/react/**', 'node_modules/react-dom/**' ] }), replace({ 'process.env.NODE_ENV': JSON.stringify('production') }), resolve({ browser: true, main: true }), uglify() ], sourceMap: true, external: ['react', 'react-dom'], globals: { 'react': 'React', 'react-dom': 'ReactDOM' } };
(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})(function(a){a.registerHelper("lint","coffeescript",function(b){var c=[];if(!window.coffeelint)return window.console&&window.console.error("Error: window.coffeelint not defined, CodeMirror CoffeeScript linting cannot run."),c;try{var f=coffeelint.lint(b);for(b=0;b<f.length;b++){var e=f[b],g=e.lineNumber;c.push({from:a.Pos(g- 1,0),to:a.Pos(g,0),severity:e.level,message:e.message})}}catch(d){c.push({from:a.Pos(d.location.first_line,0),to:a.Pos(d.location.last_line,d.location.last_column),severity:"error",message:d.message})}return c})});
/* eslint-env node */ /* eslint-disable no-sync */ 'use strict'; var fs = require('fs'); var path = require('path'); var template = require('lodash/template'); var pTemplate = template(fs.readFileSync(path.resolve(__dirname, '../templates/p'), 'utf8')); var thenTemplate = template(fs.readFileSync(path.resolve(__dirname, '../templates/then'), 'utf8')); var allRaceTemplate = template(fs.readFileSync(path.resolve(__dirname, '../templates/allRace'), 'utf8')); var getIndentation = function (level) { var indentation = ''; for (var i = 0; i < level; i += 1) { indentation += ' '; } return indentation; }; // Increase every line of `code` after the first by `levels` of indentation. var indentCode = function (code, levels) { return code.replace(new RegExp('\\n', 'g'), '\n' + getIndentation(levels)); }; // Decrease every line of `code` after the first by `levels` of indentation. var dedentCode = function (code, levels) { return code.replace(new RegExp('\\n' + getIndentation(levels), 'g'), '\n'); }; // Determine flags to set on the program template and return generated code. var build = function (options) { options = options || {}; var task = options.task || 'setTimeout'; var globals = options.globals || (options.task ? [] : ['setTimeout']); var exposeCatch = Boolean(options.catch); var exposeResolve = Boolean(options.resolve); var exposeReject = Boolean(options.reject); var exposeAll = Boolean(options.all); var exposeRace = Boolean(options.race); var includeCatch = exposeCatch; var includeReject = exposeReject; var includeAll = exposeAll; var includeRace = exposeRace; var includeResolve = exposeResolve || includeAll || includeRace; var referenceResolve = includeAll || includeRace; var ie = Boolean(options.ie); var catchKey = ie ? '\'catch\'' : 'catch'; var catchKeyComment = ie ? ' // Quotes for old IE' : ''; var node = Boolean(options.node); // Also wrap IE because it has named function expression bugs. var wrap = (includeResolve || includeReject || includeAll || includeRace || ie) && !node; // Use a named function expression to maintain a reference to `p` regardless // of global variable tampering. var nfe = !wrap && !node; var envs = options.envs || []; if (node) { envs.push('node'); } var envSettings = envs.length > 0 ? '/* eslint-env ' + envs.join(',') + ' */\n' : ''; var globalSettings = globals.length > 0 ? '/* global ' + globals.join(',') + ' */\n' : ''; var then = thenTemplate(); var allRace = allRaceTemplate({ includeAll: includeAll, includeRace: includeRace, includeBoth: includeAll && includeRace }); var all; var race; if (includeAll && includeRace) { allRace = indentCode(allRace, 1); all = 'allRace(1)'; race = 'allRace(0)'; } else { all = allRace; race = allRace; } var code = pTemplate({ indentCode: indentCode, envSettings: envSettings, globalSettings: globalSettings, then: then, allRace: allRace, all: all, race: race, task: task, exposeCatch: exposeCatch, exposeResolve: exposeResolve, exposeReject: exposeReject, exposeAll: exposeAll, exposeRace: exposeRace, includeCatch: includeCatch, includeResolve: includeResolve, includeReject: includeReject, includeAll: includeAll, includeRace: includeRace, referenceResolve: referenceResolve, wrap: wrap, nfe: nfe, ie: ie, node: node, catchKey: catchKey, catchKeyComment: catchKeyComment }); if (!wrap) { code = dedentCode(code, 1); } return code; }; module.exports = build;
let bookController = (config) => { let post = (req, res) => { if (req.body.author) { res.status(400); res.send('Title is required'); } else { res.status(201); res.send({__id: 'book_id', name: 'book1', author:'auth'}); } }; let list = (req,res) => { res.status(200).json([{name: 'book1', author: 'auth'},{name: 'book2', author: 'auth2'}]); }; let getById = (req,res)=> { res.status(200).json(req.book); }; let updateById = (req,res)=> { for (let k in req.body) { if (req.book.hasOwnProperty(k)) { req.book[k] = req.body[k]; } } res.json(req.book); }; let updateAllById = (req,res)=> { res.json({name: 'book1', author: 'auth'}); }; let deleteById = (req, res)=> { res.status(204); }; return { post:post, list:list, getById:getById, updateById:updateById, updateAllById:updateAllById, deleteById:deleteById }; }; module.exports = bookController;
var config = require('../config'); module.exports.task = function(gulp, plugins, paths) { gulp.src(paths.app.assets) .pipe(gulp.dest(config.destDir + "/assets")) .pipe(plugins.connect.reload()); };
var Http = require('http'); var Https = require('https'); var Inherits = require('util').inherits; var Rx = require('rx'); var HttpObservable = function HttpObservable (options) { this.options = options; Rx.ObservableBase.call(this); }; Inherits(HttpObservable, Rx.ObservableBase); HttpObservable.prototype.subscribeCore = function(observer) { var options = this.options || {}; var Client = (options.protocol === 'https:') ? Https : Http; var req = Client.request(options, function(res) { //Send the status and message first. observer.onNext({statusCode: res.statusCode, statusMessage: res.statusMessage}); //Send http response headers observer.onNext(res.headers); res.on('data', function(chunk) { //Send data observer.onNext(chunk); }); res.on('end', function() { observer.onCompleted(); }); }); req.on('error', function(e) { observer.onError(e); }); if (options.postData) { req.write(options.postData); } req.end(); }; module.exports = HttpObservable;
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.16/esri/copyright.txt for details. //>>built define({widgetLabel:"Curseur de plage d\u2019histogramme"});
module.exports = require('edenjs').extend(function() { /* Require -------------------------------*/ /* Constants -------------------------------*/ /* Public Properties -------------------------------*/ /* Protected Properties -------------------------------*/ this._controller = null; /* Private Properties -------------------------------*/ /* Magic -------------------------------*/ this.___construct = function(controller) { this._controller = controller; }; /* Public Methods -------------------------------*/ this.response = function(request, response) { //if no ID if(!request.variables[0]) { //setup an error this.Controller().trigger('file-detail-error', 'No ID set', request, response); return; } var search = this.Controller() .package('file') .search() .addFilter('file_id = ?', request.variables[0]) .getRow(this._results.bind(this.Controller(), request, response)); return this; }; /* Protected Methods -------------------------------*/ this._results = function(request, response, error, data) { //if there are errors if(error || data === null) { //setup an error response.state = 404; response.message = 'File not found'; //trigger that a response has been made this.trigger('file-response', request, response); return; } //then prepare the package this.File(data.file_path).getContent(function(error, content) { response.message = content.toString('base64'); response.encoding = 'base64'; response.headers['Content-Type'] = data.file_mime; //response.headers['Content-Length'] = response.message.length //trigger that a response has been made this.trigger('file-response', request, response);; }.bind(this)); }; /* Private Methods -------------------------------*/ }).singleton();
/* eslint-disable no-tabs */ import Plugin from '@ckeditor/ckeditor5-core/src/plugin'; import ClickObserver from '@ckeditor/ckeditor5-engine/src/view/observer/clickobserver'; import ContextualBalloon from '@ckeditor/ckeditor5-ui/src/panel/balloon/contextualballoon'; import clickOutsideHandler from '@ckeditor/ckeditor5-ui/src/bindings/clickoutsidehandler'; import uid from '@ckeditor/ckeditor5-utils/src/uid'; import global from '@ckeditor/ckeditor5-utils/src/dom/global'; import ButtonView from '@ckeditor/ckeditor5-ui/src/button/buttonview'; import MainFormView from './ui/mainformview'; // Need math commands from there import MathEditing from './mathediting'; import { defaultConfig, getSelectedMathModelWidget, resizeInputElement } from './utils'; import mathIcon from './math.svg'; const mathKeystroke = 'Ctrl+4'; const mathDisplayKeystroke = 'Ctrl+M'; export default class MathUI extends Plugin { static get requires() { return [ ContextualBalloon, MathEditing ]; } static get pluginName() { return 'MathUI'; } init() { const editor = this.editor; editor.editing.view.addObserver( ClickObserver ); this._previewUid = `math-preview-${ uid() }`; this.formView = this._createFormView(); this._balloon = editor.plugins.get( ContextualBalloon ); this._createToolbarMathButton(); this._enableUserBalloonInteractions(); } destroy() { super.destroy(); this.formView.destroy(); // Destroy preview element const prewviewEl = global.document.getElementById( this._previewUid ); if ( prewviewEl ) { prewviewEl.parentNode.removeChild( prewviewEl ); } } _showUI() { const editor = this.editor; const mathCommand = editor.commands.get( 'math' ); if ( !mathCommand.isEnabled ) { return; } // When we press Ctrl+4 and have text-selected, initialize the mathCommand // (and corresponding menu) with the selected text const selection = editor.model.document.selection; const range = selection.getFirstRange(); const selectedItems = range.getItems(); const concatenatedSelection = Array.from( selectedItems ).map( item => item.data ? item.data : '' ).join( '' ); if ( concatenatedSelection && concatenatedSelection.length ) { mathCommand.value = concatenatedSelection; } this._addFormView(); this._balloon.showStack( 'main' ); } _createFormView() { const editor = this.editor; const mathCommand = editor.commands.get( 'math' ); const mathConfig = Object.assign( defaultConfig, this.editor.config.get( 'math' ) ); const formView = new MainFormView( editor.locale, mathConfig.engine, mathConfig.enablePreview, this._previewUid ); formView.mathInputView.bind( 'value' ).to( mathCommand, 'value' ); // Form elements should be read-only when corresponding commands are disabled. formView.mathInputView.bind( 'isReadOnly' ).to( mathCommand, 'isEnabled', value => !value ); // Listen to submit button click this.listenTo( formView, 'submit', () => { editor.execute( 'math', formView.equation, mathCommand.display, mathConfig.outputType, mathConfig.forceOutputType ); this._closeFormView(); } ); // Listen to cancel button click this.listenTo( formView, 'cancel', () => { this._closeFormView(); } ); // Close plugin ui, if esc is pressed (while ui is focused) formView.keystrokes.set( 'esc', ( data, cancel ) => { this.formView.fire( 'submit' ); this._closeFormView(); } ); // Close plugin ui, if Tab is pressed (while ui is focused) formView.keystrokes.set( 'tab', ( data, cancel ) => { this.formView.fire( 'submit' ); this._closeFormView(); }, { priority: 'high' } ); formView.keystrokes.set( 'Enter', ( data, cancel ) => { this.formView.fire( 'submit' ); this._closeFormView(); }); this.listenTo( formView, 'updatedMath', () => { this._balloon.updatePosition( this._getBalloonPositionData() ); } ); return formView; } _addFormView() { if ( this._isFormInPanel ) { return; } const editor = this.editor; const mathCommand = editor.commands.get( 'math' ); this._balloon.add( { view: this.formView, position: this._getBalloonPositionData(), balloonClassName: 'ck-math-balloon' } ); if ( this._balloon.visibleView === this.formView ) { this.formView.mathInputView.select(); } this.formView.equation = mathCommand.value || ''; // After updating the equation, make sure to resize the input element if ( this.formView.mathInputView.element ) { resizeInputElement( this.formView.mathInputView.element ); } } _hideUI() { if ( !this._isFormInPanel ) { return; } const editor = this.editor; this.stopListening( editor.ui, 'update' ); this.stopListening( this._balloon, 'change:visibleView' ); editor.editing.view.focus(); // Remove form first because it's on top of the stack. this._removeFormView(); } _closeFormView() { const mathCommand = this.editor.commands.get( 'math' ); if ( mathCommand.value !== undefined ) { this._removeFormView(); } else { this._hideUI(); } } _removeFormView() { if ( this._isFormInPanel ) { this._balloon.remove( this.formView ); // Hide preview element const prewviewEl = global.document.getElementById( this._previewUid ); if ( prewviewEl ) { prewviewEl.style.visibility = 'hidden'; } this.editor.editing.view.focus(); } } _getBalloonPositionData() { const view = this.editor.editing.view; const viewDocument = view.document; const target = view.domConverter.viewRangeToDom( viewDocument.selection.getFirstRange() ); return { target }; } _createToolbarMathButton() { const editor = this.editor; const mathCommand = editor.commands.get( 'math' ); const t = editor.t; // Handle the `Ctrl+4` keystroke and show the panel. editor.keystrokes.set( mathKeystroke, ( keyEvtData, cancel ) => { cancel(); if ( mathCommand.isEnabled ) { this._showUI(); } } ); // Handle the `Ctrl+M` keystroke and show the panel. editor.keystrokes.set( mathDisplayKeystroke, ( keyEvtData, cancel ) => { // Prevent focusing the search bar in FF and opening new tab in Edge. #153, #154. cancel(); if ( mathCommand.isEnabled ) { mathCommand.display = true; this._showUI(); } } ); this.editor.ui.componentFactory.add( 'math', locale => { const button = new ButtonView( locale ); button.isEnabled = true; button.label = t( 'Insert math' ); button.icon = mathIcon; button.keystroke = mathKeystroke; button.tooltip = true; button.isToggleable = true; button.bind( 'isEnabled' ).to( mathCommand, 'isEnabled' ); this.listenTo( button, 'execute', () => this._showUI() ); return button; } ); this.editor.ui.componentFactory.add( 'mathDisplay', locale => { const button = new ButtonView( locale ); button.isEnabled = true; button.label = t( 'Insert display math block' ); button.icon = mathIcon; button.keystroke = mathDisplayKeystroke; button.tooltip = true; button.isToggleable = true; button.bind( 'isEnabled' ).to( mathCommand, 'isEnabled' ); this.listenTo( button, 'execute', () => { mathCommand.display = true; this._showUI(); } ); return button; } ); } _getSelectedLaTeXElement() { const selection = this.editor.model.document.selection; return getSelectedMathModelWidget( selection ); } _enableUserBalloonInteractions() { const viewDocument = this.editor.editing.view.document; // Handle click on view document and show panel when selection is placed inside the latex element this.listenTo( viewDocument, 'click', () => { const selectedElement = this._getSelectedLaTeXElement(); if ( selectedElement ) { // Then show panel but keep focus inside editor editable. this._showUI(); } } ); // Close on click outside of balloon panel element. clickOutsideHandler( { emitter: this.formView, activator: () => this._isFormInPanel, contextElements: [ this._balloon.view.element ], callback: () => this.formView.fire( 'submit' ) } ); } get _isUIVisible() { const visibleView = this._balloon.visibleView; return visibleView == this.formView; } get _isFormInPanel() { return this._balloon.hasView( this.formView ); } }
var http = require('http'); var app = require('./app'); var config = require('./config'); var server = module.exports = http.createServer(app); server.listen(config.http_port, config.http_ip, function(){ var address = server.address(); console.log('HTTP server listening on %s:%d', address.address, address.port); });
import { getTotal, getCartProducts } from './index' describe('selectors', () => { describe('getTotal', () => { it('should return price total', () => { const state = { cart: { addedIds: [ 1, 2, 3 ], quantityById: { 1: 4, 2: 2, 3: 1 } }, products: { byId: { 1: { id: 1, price: 1.99 }, 2: { id: 1, price: 4.99 }, 3: { id: 1, price: 9.99 } } } } expect(getTotal(state)).toBe('27.93') }) }) describe('getCartProducts', () => { it('should return products with quantity', () => { const state = { cart: { addedIds: [ 1, 2, 3 ], quantityById: { 1: 4, 2: 2, 3: 1 } }, products: { byId: { 1: { id: 1, price: 1.99 }, 2: { id: 1, price: 4.99 }, 3: { id: 1, price: 9.99 } } } } expect(getCartProducts(state)).toEqual([ { id: 1, price: 1.99, quantity: 4 }, { id: 1, price: 4.99, quantity: 2 }, { id: 1, price: 9.99, quantity: 1 } ]) }) }) })
'use strict'; var express = require('express'); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); /* init */ var Mesa = require('./lib/mesa'); var Jugador = require('./lib/jugador'); var mesas = new Map(); var jugadores = new Map(); // contenido estatico app.use(express.static('client')); app.get('/', function(req, res){ res.sendfile('./client/index.html'); }); /* sockets */ io.on('connection', function(socket){ // eventos socket.on('acceder', function(nombre){ // si esta libre if(!jugadores.has(nombre)){ // guardamos el nombre en el socket socket.nombre = nombre; // guardamos el jugador jugadores.set(nombre, new Jugador(io, socket, nombre)); // avisamos de nombre correcto io.to(socket.id).emit('acceder', true); console.log('Usuario Conectado -> ' + jugadores.size); // si esta ocupado }else{ //avisamos de nombre incorrecto io.to(socket.id).emit('acceder', false); } }); socket.on('disconnect', function(){ if(!jugadores.has(socket.nombre)) return; /* borramos el jugador de la mesa*/ var mesa = jugadores.get (socket.nombre).mesa; if(mesa != null){ mesa.deleteJugador (socket.nombre); } /* borramos el jugador de la lista */ jugadores.delete(socket.nombre); console.log('Usuario Desconectado -> ' + jugadores.size); }); socket.on('getMesas', function () { mesas.forEach( function(mesa, i) { io.to(socket.id).emit('setMesa', { id : i, tipo : mesa.tipo, jugadores : mesa.getJugadores () }); } ); }); socket.on('setAsiento', function (mesa) { /* mesa: { id, posicion } */ /* si añadimos el jugador */ if(mesas.get(mesa.id).addJugador (jugadores.get(socket.nombre), mesa.posicion)){ /* avisamos a todos que el asiento a sido ocupado */ io.emit('setAsiento', { id: mesa.id, posicion: mesa.posicion, jugador: jugadores.get(socket.nombre).nombre }); } }); }); http.listen(3000, function(){ for (var i = 0; i < 10; i++) { mesas.set(i, new Mesa(io, 0)); } console.log('listening on *:3000'); });
'use strict'; /* Resources */ var ptResources = angular.module('partytube.resources', ['ngResource']); ptResources.factory('YTSearchResult', ['$resource', function($resource){ var defaults = { maxResults: '10' }; return $resource('https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&q=:q&maxResults=:maxResults&pageToken=:pageToken&key=AIzaSyAjYBy_o8ahk-ckWEzDIMCqIqdaswwPRAs', defaults); }]);
var db = require('../db'); var async = require('async'); function ManageUserService() {} ManageUserService.prototype.getUserData = function(userId, cb) { async.waterfall([ function(callback) { db.getAdminUserById(userId, function(err, user) { if (err) { callback(err, null); } else { callback(null, user); } }); } ], function(err, result) { cb(null, result); }); }; ManageUserService.prototype.updateUser = function(data, cb) { db.updateUser(data, function(err, result) { if (err) { cb(err, null); } else { cb(null, result); } }); }; ManageUserService.prototype.createUser = function(data, cb) { db.createUser(data, function(err, result) { if (err) { cb(err, null); } else { cb(null, result); } }); }; ManageUserService.prototype.getUsers = function(cb) { db.getUsers(function(err, result) { if (err) { cb(err, null); } else { cb(null, result); } }); }; ManageUserService.prototype.removeUser = function(user, cb) { db.removeUser(user, function(err, result) { if (err) { cb(err, null); } else { cb(null, result); } }); }; module.exports = new ManageUserService();
function foo() { var a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 2; return function () { function a() {} }(); }
import splitExampleCode from '../splitExampleCode'; describe('splitExampleCode', () => { test('basic example', () => { const result = splitExampleCode(`var a = 1; React.createElement('i', null, a);`); expect(result).toEqual({ head: 'var a = 1', example: `var a = 1; return (React.createElement('i', null, a));`, }); }); test('initialState', () => { const result = splitExampleCode(`initialState = {a: 1}; React.createElement('i', null, state.a);`); expect(result).toEqual({ head: 'initialState = {a: 1}', example: `initialState = {a: 1}; return (React.createElement('i', null, state.a));`, }); }); test('JSX not only in the last expression', () => { const result = splitExampleCode(`function Wrapper(ref) { var children = ref.children; return React.createElement('div', {id: 'foo'}, children); } ;React.createElement(Wrapper, null, React.createElement(Wrapper, null, React.createElement(Icon, {name: "plus"})), React.createElement(Wrapper, null, React.createElement(Icon, {name: "clip"})) )`); expect(result).toEqual({ example: `function Wrapper(ref) { var children = ref.children; return React.createElement('div', {id: 'foo'}, children); } ; return (React.createElement(Wrapper, null, React.createElement(Wrapper, null, React.createElement(Icon, {name: "plus"})), React.createElement(Wrapper, null, React.createElement(Icon, {name: "clip"})) ));`, head: `function Wrapper(ref) { var children = ref.children; return React.createElement('div', {id: 'foo'}, children); } `, }); }); test('single expression', () => { const result = splitExampleCode('pizza'); expect(result).toEqual({ head: '', example: `; return (pizza);`, }); }); test('empty string', () => { const result = splitExampleCode(''); expect(result).toEqual({ head: '', example: '', }); }); test('comment', () => { const result = splitExampleCode('/* ~ */'); expect(result).toEqual({ head: '', example: '/* ~ */', }); }); test('error', () => { const result = splitExampleCode('?'); expect(result).toEqual({ head: '', example: '?', }); }); });
import names from './names'; import paths from './paths'; import pkg from '../../package.json'; export default { names, paths, pkg }
import React from 'react'; import EntypoIcon from '../EntypoIcon'; const iconClass = 'entypo-svgicon entypo--Popup'; let EntypoPopup = (props) => ( <EntypoIcon propClass={iconClass} {...props}> <path d="M16,2H7.979C6.88,2,6,2.88,6,3.98V12c0,1.1,0.9,2,2,2h8c1.1,0,2-0.9,2-2V4C18,2.9,17.1,2,16,2z M16,12H8V4h8V12z M4,10H2v6c0,1.1,0.9,2,2,2h6v-2H4V10z"/> </EntypoIcon> ); export default EntypoPopup;
import { call } from 'redux-saga/effects'; import dbModule from '../../src/sagas/dbModule'; import { eventTypes } from '../../src/constants'; import { mockSnapshot, mockRef, mockDatabaseContext } from './dbMocks'; import { mockCall, mockCallsCount } from '../testUtils'; describe('database', () => { let ref; let context; beforeEach(() => { ref = mockRef(); context = mockDatabaseContext(ref); }); afterEach(() => { expect.hasAssertions(); }); describe('once(path, eventType, options = null)', () => { it('null for query and asArray', () => { const path = '/path'; const eventType = eventTypes.VALUE; const val = { key1: { data: 'data1' }, key2: { data: 'data2' } }; const snapshot = mockSnapshot(val); const gen = dbModule.once.call(context, path, eventType); expect(gen.next().value).toEqual(call([ref, ref.once], eventType)); expect(gen.next(snapshot)).toEqual({ done: true, value: val }); }); it('asArray = true', () => { const path = '/path'; const eventType = eventTypes.VALUE; const val = { key1: { data: 'data1' }, key2: { data: 'data2' } }; const expected = [ { key: 'key1', key1: { data: 'data1' } }, { key: 'key2', key2: { data: 'data2' } }, ]; const snapshot = mockSnapshot(val); const gen = dbModule.once.call(context, path, eventType, { asArray: true }); expect(gen.next().value).toEqual(call([ref, ref.once], eventType)); expect(gen.next(snapshot)).toEqual({ done: true, value: expected }); }); }); describe('push(path, data)', () => { it('works', () => { const path = '/path'; const data = 'testdata'; const result = 'result'; const gen = dbModule.push.call(context, path, data); expect(gen.next().value).toEqual(call([ref, ref.push], data)); expect(gen.next(result)).toEqual({ done: true, value: result }); }); }); describe('update(path, values)', () => { it('works', () => { const path = '/path'; const values = { test: 'test' }; const gen = dbModule.update.call(context, path, values); expect(gen.next().value).toEqual(call([ref, ref.update], values)); expect(gen.next()).toEqual({ done: true, value: undefined }); }); }); describe('set(path, value)', () => { it('works', () => { const path = '/path'; const value = { test1: 'aaa', test2: 'bbb' }; const gen = dbModule.set.call(context, path, value); expect(gen.next().value).toEqual(call([ref, ref.set], value)); expect(gen.next()).toEqual({ done: true, value: undefined }); }); }); describe('remove(path)', () => { it('works', () => { const path = '/path'; const gen = dbModule.remove.call(context, path); expect(gen.next().value).toEqual(call([ref, ref.remove])); expect(gen.next()).toEqual({ done: true, value: undefined }); }); }); describe('createOnEventChannel(path, eventType)', () => { it('value for eventType', () => { const path = '/path'; const eventType = eventTypes.VALUE; dbModule.createOnEventChannel.call(context, path, eventType); expect(mockCallsCount(ref.on)).toBe(1); // The function was called exactly once expect(mockCall(ref.on)[0]).toBe(eventType); }); it('child_added for eventType', () => { const path = '/path'; const eventType = eventTypes.CHILD_ADDED; dbModule.createOnEventChannel.call(context, path, eventType); expect(mockCallsCount(ref.on)).toBe(1); // The function was called exactly once expect(mockCall(ref.on)[0]).toBe(eventType); }); it('child_changed for eventType', () => { const path = '/path'; const eventType = eventTypes.CHILD_CHANGED; dbModule.createOnEventChannel.call(context, path, eventType); expect(mockCallsCount(ref.on)).toBe(1); // The function was called exactly once expect(mockCall(ref.on)[0]).toBe(eventType); }); it('child_moved for eventType', () => { const path = '/path'; const eventType = eventTypes.CHILD_MOVED; dbModule.createOnEventChannel.call(context, path, eventType); expect(mockCallsCount(ref.on)).toBe(1); // The function was called exactly once expect(mockCall(ref.on)[0]).toBe(eventType); }); it('child_removed for eventType', () => { const path = '/path'; const eventType = eventTypes.CHILD_REMOVED; dbModule.createOnEventChannel.call(context, path, eventType); expect(mockCallsCount(ref.on)).toBe(1); // The function was called exactly once expect(mockCall(ref.on)[0]).toBe(eventType); }); it('unknown eventType -> throws error', () => { const path = '/path'; const eventType = 'UNKNOWN_EVENT'; expect(() => { dbModule.createOnEventChannel.call(context, path, eventType); }).toThrow(); }); }); describe('on(path, eventType, actionCreator, options = null)', () => { it('works', () => { const path = '/path'; const actionCreator = jest.fn(); const gen = dbModule.on.call(context, path, eventTypes.VALUE, actionCreator, null); expect(gen.next().value).toEqual(call(context.database.createOnEventChannel, path, eventTypes.VALUE, null)); }); }); });
var test = require('tape') var createMesh = require('../') var createContext = require('webgl-context') var snoop = require('gl-buffer-snoop') test('should create array buffer', function (t) { var gl = createContext() snoop(gl) var mesh = createMesh(gl) t.equal(mesh.attributes.length, 0, 'no attributes') mesh.attribute('position', [ [2, 3, 4], [4, 2, 1] ]) t.equal(mesh.attributes[0].name, 'position', 'gets name') t.equal(mesh.attributes[0].size, 3, 'default size 3') t.equal(mesh.attributes[0].usage, gl.STATIC_DRAW, 'default static draw') var gpuData = gl.getBufferData(mesh.attributes[0].buffer.handle) t.deepEqual(new Float32Array(gpuData.buffer), new Float32Array([2, 3, 4, 4, 2, 1]), 'saves buffer to GPU') mesh.attribute('position', [], { usage: gl.DYNAMIC_DRAW, size: 2 }) t.equal(mesh.attributes[0].usage, gl.DYNAMIC_DRAW, 'changes usage') t.equal(mesh.attributes[0].size, 2, 'changes size') gpuData = gl.getBufferData(mesh.attributes[0].buffer.handle) t.deepEqual(new Float32Array(gpuData.buffer), new Float32Array([]), 'saves buffer to GPU') mesh.attribute('position', [ [3, 2, 1], [4, 3, 5] ]) t.equal(mesh.attributes[0].usage, gl.DYNAMIC_DRAW, 'maintains usage') t.equal(mesh.attributes[0].size, 2, 'maintains size') gpuData = gl.getBufferData(mesh.attributes[0].buffer.handle) t.deepEqual(new Float32Array(gpuData.buffer), new Float32Array([3, 2, 1, 4, 3, 5]), 'saves buffer to GPU') t.end() })
var Fragment = require('./fragment') , Attribute = require('./attribute') , Template = require('./template') , utils = require('./utils') var Element = module.exports = function(/*tag, attrs, id, template, context[, args...]*/) { var args = Array.prototype.slice.call(arguments) this.tag = args.shift() var attrs = args.shift() this.id = args.shift() this.template = args.shift() this.context = args.shift() this.args = args.length === 1 && Array.isArray(args[0]) ? args[0] : args this.children = [] this._element = null this.attrs = {} this.silent = false for(var key in attrs) { if (key.toLowerCase() === 'id') continue var val = attrs[key] if (typeof val === 'function') { var template = new Template(val, this.template.argNames) val = new Attribute(utils.requestContext.nextFragmentId++, template, this.context) utils.requestContext.fragments[val.id] = val } this.attrs[key] = val } } utils.inherits(Element, Fragment) require('implode').register('Element', Element, Fragment.prototype.$contract.concat(['tag'])) Object.defineProperties(Element.prototype, { element: { get: function() { if (!this._element) { this._element = document.getElementById('fragment' + this.id.toString()) } return this._element } }, startNode: { get: function() { return this.element } }, endNode: { get: function() { return this.element } }, class: { get: function() { var className = this.attrs.class if (className === undefined) return '' if (typeof className === 'function') return className.apply(this.context, (this.args || [])) return className } } }) Element.prototype.refresh = function(force) { if (utils.isServer) return if (force !== true) { if (Fragment.queue.indexOf(this) === -1) { Fragment.queue.push(this) setTimeout(Fragment.refresh) } return } utils.debug('[Element] #%s refreshing', this.id) var that = this // delete Contents this.deleteContents() this.element.innerHTML = this.render() // traverse the Fragment to assign the start and end // comments to their corresponding fragments utils.aquireFragments(this.element, window.app.fragments) } Element.prototype.wrap = function(content) { var ret = '' ret += '<' + this.tag + ' id="fragment' + this.id + '"' for (var attr in this.attrs) { val = this.attrs[attr] val.args = this.args if (val instanceof Attribute) { ret += 'data-bind-' + attr + '="' + val.id + '" ' ret += attr + '="' + val.render() + '"' } else { ret += ' ' + attr + '="' + val +'"' } } ret += '>' ret += content ret += '</' + this.tag + '>' return ret } Element.prototype.insertBefore = function(anchor) { this._element = document.createElement(this.tag) this._element.id = 'fragment' + this.id for (var attr in this.attrs) { val = this.attrs[attr] val.args = this.args if (val instanceof Attribute) { this._element.setAttribute('data-bind-' + attr, val.id) this._element.setAttribute(attr, val.render()) val.attribute = this._element.attributes[attr] } else { this._element.setAttribute(attr, val) } } anchor.parentNode.insertBefore(this._element, anchor) this.refresh() } Element.prototype.moveBetween = function(before, after) { before.parentNode.insertBefore(this.element, before) } Element.prototype.deleteContents = function() { // emit delete event to get child fragments to delete themselfs this.emit('deleteContents') this.element.innerHTML = '' } Element.prototype.dispose = function() { this.emit('delete') this.removeAllListeners() this.element.parentNode.removeChild(this.element) delete this.element // remove from fragments registry delete window.app.fragments[this.id] // remove from queue if ((index = Fragment.queue.indexOf(this)) > -1) { Fragment.queue.splice(index, 1) } } delete Element.prototype.append delete Element.prototype.move delete Element.prototype.insert
import React, { Component } from "react" import Layout from "../components/layout" import Container from "../components/container" import PageWithPluginSearchBar from "../components/page-with-plugin-searchbar" import { Link } from "gatsby" import logo from "../monogram.svg" import { rhythm, options } from "../utils/typography" import presets, { colors } from "../utils/presets" class Plugins extends Component { render() { return ( <Layout location={this.props.location}> <PageWithPluginSearchBar isPluginsIndex location={this.props.location}> <Container css={{ alignItems: `center`, display: `flex`, minHeight: `calc(100vh - (${presets.headerHeight} + ${ presets.bannerHeight } - 1px))`, }} > <div css={{ display: `flex`, flexDirection: `column`, }} > <img src={logo} css={{ display: `inline-block`, height: rhythm(5.2), width: rhythm(5.2), marginLeft: `auto`, marginRight: `auto`, }} alt="" /> <h1 css={{ fontSize: rhythm(1), marginTop: rhythm(1 / 4), marginLeft: rhythm(1), marginRight: rhythm(1), textAlign: `center`, }} > Welcome to the Gatsby Plugin Library! </h1> <p css={{ color: colors.gray.calm, marginLeft: rhythm(3), marginRight: rhythm(3), fontSize: rhythm(3 / 4), fontFamily: options.headerFontFamily.join(`,`), textAlign: `center`, }} > Please use the search bar to find plugins that will make your blazing-fast site even more awesome. If you'd like to create your own plugin, see the {` `} <Link to="/docs/plugin-authoring/">Plugin Authoring</Link> page in the docs! </p> </div> </Container> </PageWithPluginSearchBar> </Layout> ) } } export default Plugins
/* Author: */ (function (CMS) { CMS.Supports = { // CMS.Supports.touch touch: 'ontouchstart' in document.documentElement || (window.DocumentTouch && document instanceof DocumentTouch ? true : false), touch2: "onorientationchange" in window && "ontouchstart" in window ? true : false, // CMS.Supports.isAndroidNativeBrowser isAndroidNativeBrowser: (function () { var ua = navigator.userAgent.toLowerCase(); return ua.indexOf('android') !== -1 && ua.indexOf('mobile') !== -1 && ua.indexOf('chrome') === -1; })(), // CMS.Supports.viewportW() viewportW: function () { var a = document.documentElement.clientWidth, b = window.innerWidth; return a < b ? b : a; }, // CMS.Supports.viewportH() viewportH: function () { var a = document.documentElement.clientHeight, b = window.innerHeight; return a < b ? b : a; } }; })(window.CMS = window.CMS || {});
export Counter from './Counter/Counter' export BooksForm from './Books/Form' export BooksSearchStatus from './Books/SearchStatus' export BooksList from './Books/List'
import Civ5Save from '../Civ5Save'; const path = require('path'); const TEST_SAVEGAME_V10017 = path.join(__dirname, 'resources', '1.0.0.17.Civ5Save'); const TEST_SAVEGAME_V101135 = path.join(__dirname, 'resources', '1.0.1.135.Civ5Save'); const TEST_SAVEGAME_V101221 = path.join(__dirname, 'resources', '1.0.1.221.Civ5Save'); const TEST_SAVEGAME_V10213 = path.join(__dirname, 'resources', '1.0.2.13.Civ5Save'); const TEST_SAVEGAME_V103279 = path.join(__dirname, 'resources', '1.0.3.279.Civ5Save'); const TEST_SAVEGAME_BROKEN = path.join(__dirname, 'resources', 'broken.Civ5Save'); const NEW_ALWAYS_PEACE = true; const NEW_ALWAYS_WAR = true; const NEW_COMPLETE_KILLS = false; const NEW_CULTURAL_VICTORY = false; const NEW_DIPLOMATIC_VICTORY = true; const NEW_DOMINATION_VICTORY = true; const NEW_LOCK_MODS = true; const NEW_MAX_TURNS = 123; const NEW_NEW_RANDOM_SEED = true; const NEW_NO_BARBARIANS = false; const NEW_NO_CHANGING_WAR_OR_PEACE = true; const NEW_NO_CITY_RAZING = false; const NEW_NO_CULTURE_OVERVIEW_UI = true; const NEW_NO_ESPIONAGE = false; const NEW_NO_HAPPINESS = true; const NEW_NO_POLICIES = true; const NEW_NO_RELIGION = false; const NEW_NO_SCIENCE = true; const NEW_NO_WORLD_CONGRESS = true; const NEW_ONE_CITY_CHALLENGE = false; const NEW_PITBOSS = false; const NEW_POLICY_SAVING = false; const NEW_PRIVATE_GAME = false; const NEW_PROMOTION_SAVING = false; const NEW_RAGING_BARBARIANS = false; const NEW_RANDOM_PERSONALITIES = false; const NEW_SCIENCE_VICTORY = false; const NEW_TIME_VICTORY = true; const NEW_TURN_TIMER_ENABLED = false; const NEW_TURN_TIMER_VALUE = 321; const NEW_TURN_MODE = Civ5Save.TURN_MODES.SIMULTANEOUS; let savegame10017; let savegame101135; let savegame101221; let savegame10213; let savegame103279; function getFileBlob(url) { return new Promise(function (resolve, reject) { let xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.responseType = 'blob'; xhr.addEventListener('load', function() { resolve(xhr.response); }); xhr.addEventListener('error', function() { reject(xhr.statusText); }); xhr.send(); }); } test('Create new Civ5Save instances from file', async () => { let fileBlob = await getFileBlob(TEST_SAVEGAME_V10017); savegame10017 = await Civ5Save.fromFile(fileBlob); fileBlob = await getFileBlob(TEST_SAVEGAME_V101135); savegame101135 = await Civ5Save.fromFile(fileBlob); fileBlob = await getFileBlob(TEST_SAVEGAME_V101221); savegame101221 = await Civ5Save.fromFile(fileBlob); fileBlob = await getFileBlob(TEST_SAVEGAME_V10213); savegame10213 = await Civ5Save.fromFile(fileBlob); fileBlob = await getFileBlob(TEST_SAVEGAME_V103279); savegame103279 = await Civ5Save.fromFile(fileBlob); }, 20000); test('Get game build', () => { expect(savegame10017.gameBuild).toBe('201080'); expect(savegame101135.gameBuild).toBe('210752'); expect(savegame101221.gameBuild).toBe('218015'); expect(savegame10213.gameBuild).toBe('341540'); expect(savegame103279.gameBuild).toBe('403694'); }); test('Get game version', () => { expect(savegame10017.gameVersion).not.toBeDefined(); expect(savegame101135.gameVersion).not.toBeDefined(); expect(savegame101221.gameVersion).not.toBeDefined(); expect(savegame10213.gameVersion).toBe('1.0.2.13 (341540)'); expect(savegame103279.gameVersion).toBe('1.0.3.279(130961)'); }); test('Get current turn', () => { expect(savegame10017.currentTurn).toBe(19); expect(savegame101135.currentTurn).toBe(176); expect(savegame101221.currentTurn).toBe(52); expect(savegame10213.currentTurn).toBe(12); expect(savegame103279.currentTurn).toBe(264); }); test('Get game mode', () => { expect(savegame10017.gameMode).not.toBeDefined(); expect(savegame101135.gameMode).not.toBeDefined(); expect(savegame101221.gameMode).not.toBeDefined(); expect(savegame10213.gameMode).toBe(Civ5Save.GAME_MODES.SINGLE); expect(savegame103279.gameMode).toBe(Civ5Save.GAME_MODES.MULTI); }); test('Get difficulty', () => { expect(savegame10017.difficulty).toBe('Chieftain'); expect(savegame101135.difficulty).toBe('Warlord'); expect(savegame101221.difficulty).toBe('Prince'); expect(savegame10213.difficulty).toBe('Immortal'); expect(savegame103279.difficulty).toBe('Settler'); }); test('Get starting era', () => { expect(savegame10017.startingEra).toBe('Ancient'); expect(savegame101135.startingEra).toBe('Ancient'); expect(savegame101221.startingEra).toBe('Medieval'); expect(savegame10213.startingEra).toBe('Ancient'); expect(savegame103279.startingEra).toBe('Future'); }); test('Get current era', () => { expect(savegame10017.currentEra).toBe('Ancient'); expect(savegame101135.currentEra).toBe('Ancient'); expect(savegame101221.currentEra).toBe('Renaissance'); expect(savegame10213.currentEra).toBe('Ancient'); expect(savegame103279.currentEra).toBe('Future'); }); test('Get game pace', () => { expect(savegame10017.gamePace).toBe('Standard'); expect(savegame101135.gamePace).toBe('Marathon'); expect(savegame101221.gamePace).toBe('Quick'); expect(savegame10213.gamePace).toBe('Standard'); expect(savegame103279.gamePace).toBe('Quick'); }); test('Get map size', () => { expect(savegame10017.mapSize).toBe('Small'); expect(savegame101135.mapSize).toBe('Huge'); expect(savegame101221.mapSize).toBe('Standard'); expect(savegame10213.mapSize).toBe('Standard'); expect(savegame103279.mapSize).toBe('Duel'); }); test('Get map file', () => { expect(savegame10017.mapFile).toBe('Continents'); expect(savegame101135.mapFile).toBe('Pangaea'); expect(savegame101221.mapFile).toBe('NewWorld Scenario MapScript'); expect(savegame10213.mapFile).toBe('Pangaea'); expect(savegame103279.mapFile).toBe('Earth Duel'); }); test('Get enabled DLC', () => { expect(savegame10017.enabledDLC).toEqual([]); expect(savegame101135.enabledDLC).toEqual([ 'Babylon', 'Upgrade 1', 'Mongolia' ]); expect(savegame101221.enabledDLC).toEqual([ 'Spain and Inca', 'Polynesia', 'Babylon', 'Upgrade 1', 'Mongolia' ]); expect(savegame10213.enabledDLC).toEqual([ 'Mongolia', 'Spain and Inca', 'Polynesia', 'Denmark', 'Korea', 'Ancient Wonders', 'Babylon', 'Expansion - Gods and Kings', 'Upgrade 1' ]); expect(savegame103279.enabledDLC).toEqual([ 'Mongolia', 'Spain and Inca', 'Polynesia', 'Denmark', 'Korea', 'Ancient Wonders', 'Civilization 5 Complete', 'Babylon', 'DLC_SP_Maps', 'DLC_SP_Maps_2', 'DLC_SP_Maps_3', 'Expansion - Gods and Kings', 'Expansion - Brave New World', 'Upgrade 1' ]); }); test('Get enabled Mods', () => { expect(savegame10017.enabledMods).toEqual([]); expect(savegame101135.enabledMods).toEqual([]); expect(savegame101221.enabledMods).toEqual([ 'Conquest of the New World', ]); expect(savegame10213.enabledMods).toEqual([]); expect(savegame103279.enabledMods).toEqual([]); }); test('Get players', () => { expect(savegame10017.players).toEqual([ { civilization: 'Persia', status: Civ5Save.PLAYER_STATUSES.HUMAN }, { civilization: undefined, status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: undefined, status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: undefined, status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: undefined, status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: undefined, status: Civ5Save.PLAYER_STATUSES.AI }, ]); expect(savegame101135.players).toEqual([ { civilization: 'Arabia', status: Civ5Save.PLAYER_STATUSES.HUMAN }, { civilization: undefined, status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: undefined, status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: undefined, status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: undefined, status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: undefined, status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: undefined, status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: undefined, status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: undefined, status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: undefined, status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: undefined, status: Civ5Save.PLAYER_STATUSES.DEAD }, { civilization: undefined, status: Civ5Save.PLAYER_STATUSES.DEAD }, ]); expect(savegame101221.players).toEqual([ { civilization: 'France', status: Civ5Save.PLAYER_STATUSES.HUMAN }, { civilization: undefined, status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: undefined, status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: undefined, status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: undefined, status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: undefined, status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: undefined, status: Civ5Save.PLAYER_STATUSES.DEAD }, { civilization: undefined, status: Civ5Save.PLAYER_STATUSES.DEAD }, ]); expect(savegame10213.players).toEqual([ { civilization: 'Spain', status: Civ5Save.PLAYER_STATUSES.HUMAN }, { civilization: 'Ottoman', status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: 'Greece', status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: 'Egypt', status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: 'Byzantium', status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: 'Austria', status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: 'Songhai', status: Civ5Save.PLAYER_STATUSES.AI }, { civilization: 'Ethiopia', status: Civ5Save.PLAYER_STATUSES.AI }, ]); expect(savegame103279.players).toEqual([ { civilization: 'Denmark', status: Civ5Save.PLAYER_STATUSES.HUMAN }, { civilization: 'Austria', status: Civ5Save.PLAYER_STATUSES.AI }, ]); }); test('Get always peace', () => { expect(savegame10017.alwaysPeace).toBe(false); expect(savegame101135.alwaysPeace).toBe(false); expect(savegame101221.alwaysPeace).toBe(false); expect(savegame10213.alwaysPeace).toBe(false); expect(savegame103279.alwaysPeace).toBe(false); }); test('Set always peace', async () => { savegame10017.alwaysPeace = NEW_ALWAYS_PEACE; savegame101135.alwaysPeace = NEW_ALWAYS_PEACE; savegame101221.alwaysPeace = NEW_ALWAYS_PEACE; savegame10213.alwaysPeace = NEW_ALWAYS_PEACE; savegame103279.alwaysPeace = NEW_ALWAYS_PEACE; expect(savegame10017.alwaysPeace).toBe(NEW_ALWAYS_PEACE); expect(savegame101135.alwaysPeace).toBe(NEW_ALWAYS_PEACE); expect(savegame101221.alwaysPeace).toBe(NEW_ALWAYS_PEACE); expect(savegame10213.alwaysPeace).toBe(NEW_ALWAYS_PEACE); expect(savegame103279.alwaysPeace).toBe(NEW_ALWAYS_PEACE); }); test('Get always war', () => { expect(savegame10017.alwaysWar).toBe(false); expect(savegame101135.alwaysWar).toBe(false); expect(savegame101221.alwaysWar).toBe(false); expect(savegame10213.alwaysWar).toBe(false); expect(savegame103279.alwaysWar).toBe(false); }); test('Set always war', async () => { savegame10017.alwaysWar = NEW_ALWAYS_WAR; savegame101135.alwaysWar = NEW_ALWAYS_WAR; savegame101221.alwaysWar = NEW_ALWAYS_WAR; savegame10213.alwaysWar = NEW_ALWAYS_WAR; savegame103279.alwaysWar = NEW_ALWAYS_WAR; expect(savegame10017.alwaysWar).toBe(NEW_ALWAYS_WAR); expect(savegame101135.alwaysWar).toBe(NEW_ALWAYS_WAR); expect(savegame101221.alwaysWar).toBe(NEW_ALWAYS_WAR); expect(savegame10213.alwaysWar).toBe(NEW_ALWAYS_WAR); expect(savegame103279.alwaysWar).toBe(NEW_ALWAYS_WAR); }); test('Get complete kills', () => { expect(savegame10017.completeKills).toBe(false); expect(savegame101135.completeKills).toBe(false); expect(savegame101221.completeKills).toBe(false); expect(savegame10213.completeKills).toBe(false); expect(savegame103279.completeKills).toBe(true); }); test('Set complete kills', async () => { savegame10017.completeKills = NEW_COMPLETE_KILLS; savegame101135.completeKills = NEW_COMPLETE_KILLS; savegame101221.completeKills = NEW_COMPLETE_KILLS; savegame10213.completeKills = NEW_COMPLETE_KILLS; savegame103279.completeKills = NEW_COMPLETE_KILLS; expect(savegame10017.completeKills).toBe(NEW_COMPLETE_KILLS); expect(savegame101135.completeKills).toBe(NEW_COMPLETE_KILLS); expect(savegame101221.completeKills).toBe(NEW_COMPLETE_KILLS); expect(savegame10213.completeKills).toBe(NEW_COMPLETE_KILLS); expect(savegame103279.completeKills).toBe(NEW_COMPLETE_KILLS); }); test('Get lock mods', () => { expect(savegame10017.lockMods).toBe(false); expect(savegame101135.lockMods).toBe(false); expect(savegame101221.lockMods).toBe(false); expect(savegame10213.lockMods).toBe(false); expect(savegame103279.lockMods).toBe(false); }); test('Set lock mods', async () => { savegame10017.lockMods = NEW_LOCK_MODS; savegame101135.lockMods = NEW_LOCK_MODS; savegame101221.lockMods = NEW_LOCK_MODS; savegame10213.lockMods = NEW_LOCK_MODS; savegame103279.lockMods = NEW_LOCK_MODS; expect(savegame10017.lockMods).toBe(NEW_LOCK_MODS); expect(savegame101135.lockMods).toBe(NEW_LOCK_MODS); expect(savegame101221.lockMods).toBe(NEW_LOCK_MODS); expect(savegame10213.lockMods).toBe(NEW_LOCK_MODS); expect(savegame103279.lockMods).toBe(NEW_LOCK_MODS); }); test('Get new random seed', () => { expect(savegame10017.newRandomSeed).toBe(false); expect(savegame101135.newRandomSeed).toBe(false); expect(savegame101221.newRandomSeed).toBe(false); expect(savegame10213.newRandomSeed).toBe(false); expect(savegame103279.newRandomSeed).toBe(false); }); test('Set new random seed', async () => { savegame10017.newRandomSeed = NEW_NEW_RANDOM_SEED; savegame101135.newRandomSeed = NEW_NEW_RANDOM_SEED; savegame101221.newRandomSeed = NEW_NEW_RANDOM_SEED; savegame10213.newRandomSeed = NEW_NEW_RANDOM_SEED; savegame103279.newRandomSeed = NEW_NEW_RANDOM_SEED; expect(savegame10017.newRandomSeed).toBe(NEW_NEW_RANDOM_SEED); expect(savegame101135.newRandomSeed).toBe(NEW_NEW_RANDOM_SEED); expect(savegame101221.newRandomSeed).toBe(NEW_NEW_RANDOM_SEED); expect(savegame10213.newRandomSeed).toBe(NEW_NEW_RANDOM_SEED); expect(savegame103279.newRandomSeed).toBe(NEW_NEW_RANDOM_SEED); }); test('Get no barbarians', () => { expect(savegame10017.noBarbarians).toBe(false); expect(savegame101135.noBarbarians).toBe(false); expect(savegame101221.noBarbarians).toBe(false); expect(savegame10213.noBarbarians).toBe(false); expect(savegame103279.noBarbarians).toBe(true); }); test('Set no barbarians', async () => { savegame10017.noBarbarians = NEW_NO_BARBARIANS; savegame101135.noBarbarians = NEW_NO_BARBARIANS; savegame101221.noBarbarians = NEW_NO_BARBARIANS; savegame10213.noBarbarians = NEW_NO_BARBARIANS; savegame103279.noBarbarians = NEW_NO_BARBARIANS; expect(savegame10017.noBarbarians).toBe(NEW_NO_BARBARIANS); expect(savegame101135.noBarbarians).toBe(NEW_NO_BARBARIANS); expect(savegame101221.noBarbarians).toBe(NEW_NO_BARBARIANS); expect(savegame10213.noBarbarians).toBe(NEW_NO_BARBARIANS); expect(savegame103279.noBarbarians).toBe(NEW_NO_BARBARIANS); }); test('Get no changing war or peace', () => { expect(savegame10017.noChangingWarPeace).toBe(false); expect(savegame101135.noChangingWarPeace).toBe(false); expect(savegame101221.noChangingWarPeace).toBe(false); expect(savegame10213.noChangingWarPeace).toBe(false); expect(savegame103279.noChangingWarPeace).toBe(false); }); test('Set no changing war or peace', async () => { savegame10017.noChangingWarPeace = NEW_NO_CHANGING_WAR_OR_PEACE; savegame101135.noChangingWarPeace = NEW_NO_CHANGING_WAR_OR_PEACE; savegame101221.noChangingWarPeace = NEW_NO_CHANGING_WAR_OR_PEACE; savegame10213.noChangingWarPeace = NEW_NO_CHANGING_WAR_OR_PEACE; savegame103279.noChangingWarPeace = NEW_NO_CHANGING_WAR_OR_PEACE; expect(savegame10017.noChangingWarPeace).toBe(NEW_NO_CHANGING_WAR_OR_PEACE); expect(savegame101135.noChangingWarPeace).toBe(NEW_NO_CHANGING_WAR_OR_PEACE); expect(savegame101221.noChangingWarPeace).toBe(NEW_NO_CHANGING_WAR_OR_PEACE); expect(savegame10213.noChangingWarPeace).toBe(NEW_NO_CHANGING_WAR_OR_PEACE); expect(savegame103279.noChangingWarPeace).toBe(NEW_NO_CHANGING_WAR_OR_PEACE); }); test('Get no city razing', () => { expect(savegame10017.noCityRazing).toBe(false); expect(savegame101135.noCityRazing).toBe(false); expect(savegame101221.noCityRazing).toBe(false); expect(savegame10213.noCityRazing).toBe(false); expect(savegame103279.noCityRazing).toBe(true); }); test('Set no city razing', async () => { savegame10017.noCityRazing = NEW_NO_CITY_RAZING; savegame101135.noCityRazing = NEW_NO_CITY_RAZING; savegame101221.noCityRazing = NEW_NO_CITY_RAZING; savegame10213.noCityRazing = NEW_NO_CITY_RAZING; savegame103279.noCityRazing = NEW_NO_CITY_RAZING; expect(savegame10017.noCityRazing).toBe(NEW_NO_CITY_RAZING); expect(savegame101135.noCityRazing).toBe(NEW_NO_CITY_RAZING); expect(savegame101221.noCityRazing).toBe(NEW_NO_CITY_RAZING); expect(savegame10213.noCityRazing).toBe(NEW_NO_CITY_RAZING); expect(savegame103279.noCityRazing).toBe(NEW_NO_CITY_RAZING); }); test('Get no culture overview UI', () => { expect(savegame10017.noCultureOverviewUI).toBe(false); expect(savegame101135.noCultureOverviewUI).toBe(false); expect(savegame101221.noCultureOverviewUI).toBe(false); expect(savegame10213.noCultureOverviewUI).toBe(false); expect(savegame103279.noCultureOverviewUI).toBe(false); }); test('Set no culture overview UI', async () => { savegame10017.noCultureOverviewUI = NEW_NO_CULTURE_OVERVIEW_UI; savegame101135.noCultureOverviewUI = NEW_NO_CULTURE_OVERVIEW_UI; savegame101221.noCultureOverviewUI = NEW_NO_CULTURE_OVERVIEW_UI; savegame10213.noCultureOverviewUI = NEW_NO_CULTURE_OVERVIEW_UI; savegame103279.noCultureOverviewUI = NEW_NO_CULTURE_OVERVIEW_UI; expect(savegame10017.noCultureOverviewUI).toBe(NEW_NO_CULTURE_OVERVIEW_UI); expect(savegame101135.noCultureOverviewUI).toBe(NEW_NO_CULTURE_OVERVIEW_UI); expect(savegame101221.noCultureOverviewUI).toBe(NEW_NO_CULTURE_OVERVIEW_UI); expect(savegame10213.noCultureOverviewUI).toBe(NEW_NO_CULTURE_OVERVIEW_UI); expect(savegame103279.noCultureOverviewUI).toBe(NEW_NO_CULTURE_OVERVIEW_UI); }); test('Get no espionage', () => { expect(savegame10017.noEspionage).toBe(false); expect(savegame101135.noEspionage).toBe(false); expect(savegame101221.noEspionage).toBe(false); expect(savegame10213.noEspionage).toBe(false); expect(savegame103279.noEspionage).toBe(true); }); test('Set no espionage', async () => { savegame10017.noEspionage = NEW_NO_ESPIONAGE; savegame101135.noEspionage = NEW_NO_ESPIONAGE; savegame101221.noEspionage = NEW_NO_ESPIONAGE; savegame10213.noEspionage = NEW_NO_ESPIONAGE; savegame103279.noEspionage = NEW_NO_ESPIONAGE; expect(savegame10017.noEspionage).toBe(NEW_NO_ESPIONAGE); expect(savegame101135.noEspionage).toBe(NEW_NO_ESPIONAGE); expect(savegame101221.noEspionage).toBe(NEW_NO_ESPIONAGE); expect(savegame10213.noEspionage).toBe(NEW_NO_ESPIONAGE); expect(savegame103279.noEspionage).toBe(NEW_NO_ESPIONAGE); }); test('Get no happiness', () => { expect(savegame10017.noHappiness).toBe(false); expect(savegame101135.noHappiness).toBe(false); expect(savegame101221.noHappiness).toBe(false); expect(savegame10213.noHappiness).toBe(false); expect(savegame103279.noHappiness).toBe(false); }); test('Set no happiness', async () => { savegame10017.noHappiness = NEW_NO_HAPPINESS; savegame101135.noHappiness = NEW_NO_HAPPINESS; savegame101221.noHappiness = NEW_NO_HAPPINESS; savegame10213.noHappiness = NEW_NO_HAPPINESS; savegame103279.noHappiness = NEW_NO_HAPPINESS; expect(savegame10017.noHappiness).toBe(NEW_NO_HAPPINESS); expect(savegame101135.noHappiness).toBe(NEW_NO_HAPPINESS); expect(savegame101221.noHappiness).toBe(NEW_NO_HAPPINESS); expect(savegame10213.noHappiness).toBe(NEW_NO_HAPPINESS); expect(savegame103279.noHappiness).toBe(NEW_NO_HAPPINESS); }); test('Get no policies', () => { expect(savegame10017.noPolicies).toBe(false); expect(savegame101135.noPolicies).toBe(false); expect(savegame101221.noPolicies).toBe(false); expect(savegame10213.noPolicies).toBe(false); expect(savegame103279.noPolicies).toBe(false); }); test('Set no policies', async () => { savegame10017.noPolicies = NEW_NO_POLICIES; savegame101135.noPolicies = NEW_NO_POLICIES; savegame101221.noPolicies = NEW_NO_POLICIES; savegame10213.noPolicies = NEW_NO_POLICIES; savegame103279.noPolicies = NEW_NO_POLICIES; expect(savegame10017.noPolicies).toBe(NEW_NO_POLICIES); expect(savegame101135.noPolicies).toBe(NEW_NO_POLICIES); expect(savegame101221.noPolicies).toBe(NEW_NO_POLICIES); expect(savegame10213.noPolicies).toBe(NEW_NO_POLICIES); expect(savegame103279.noPolicies).toBe(NEW_NO_POLICIES); }); test('Get no religion', () => { expect(savegame10017.noReligion).toBe(false); expect(savegame101135.noReligion).toBe(false); expect(savegame101221.noReligion).toBe(false); expect(savegame10213.noReligion).toBe(false); expect(savegame103279.noReligion).toBe(true); }); test('Set no religion', async () => { savegame10017.noReligion = NEW_NO_RELIGION; savegame101135.noReligion = NEW_NO_RELIGION; savegame101221.noReligion = NEW_NO_RELIGION; savegame10213.noReligion = NEW_NO_RELIGION; savegame103279.noReligion = NEW_NO_RELIGION; expect(savegame10017.noReligion).toBe(NEW_NO_RELIGION); expect(savegame101135.noReligion).toBe(NEW_NO_RELIGION); expect(savegame101221.noReligion).toBe(NEW_NO_RELIGION); expect(savegame10213.noReligion).toBe(NEW_NO_RELIGION); expect(savegame103279.noReligion).toBe(NEW_NO_RELIGION); }); test('Get no science', () => { expect(savegame10017.noScience).toBe(false); expect(savegame101135.noScience).toBe(false); expect(savegame101221.noScience).toBe(false); expect(savegame10213.noScience).toBe(false); expect(savegame103279.noScience).toBe(false); }); test('Set no science', async () => { savegame10017.noScience = NEW_NO_SCIENCE; savegame101135.noScience = NEW_NO_SCIENCE; savegame101221.noScience = NEW_NO_SCIENCE; savegame10213.noScience = NEW_NO_SCIENCE; savegame103279.noScience = NEW_NO_SCIENCE; expect(savegame10017.noScience).toBe(NEW_NO_SCIENCE); expect(savegame101135.noScience).toBe(NEW_NO_SCIENCE); expect(savegame101221.noScience).toBe(NEW_NO_SCIENCE); expect(savegame10213.noScience).toBe(NEW_NO_SCIENCE); expect(savegame103279.noScience).toBe(NEW_NO_SCIENCE); }); test('Get no world congress', () => { expect(savegame10017.noWorldCongress).toBe(false); expect(savegame101135.noWorldCongress).toBe(false); expect(savegame101221.noWorldCongress).toBe(false); expect(savegame10213.noWorldCongress).toBe(false); expect(savegame103279.noWorldCongress).toBe(false); }); test('Set no world congress', async () => { savegame10017.noWorldCongress = NEW_NO_WORLD_CONGRESS; savegame101135.noWorldCongress = NEW_NO_WORLD_CONGRESS; savegame101221.noWorldCongress = NEW_NO_WORLD_CONGRESS; savegame10213.noWorldCongress = NEW_NO_WORLD_CONGRESS; savegame103279.noWorldCongress = NEW_NO_WORLD_CONGRESS; expect(savegame10017.noWorldCongress).toBe(NEW_NO_WORLD_CONGRESS); expect(savegame101135.noWorldCongress).toBe(NEW_NO_WORLD_CONGRESS); expect(savegame101221.noWorldCongress).toBe(NEW_NO_WORLD_CONGRESS); expect(savegame10213.noWorldCongress).toBe(NEW_NO_WORLD_CONGRESS); expect(savegame103279.noWorldCongress).toBe(NEW_NO_WORLD_CONGRESS); }); test('Get one city challenge', () => { expect(savegame10017.oneCityChallenge).toBe(false); expect(savegame101135.oneCityChallenge).toBe(false); expect(savegame101221.oneCityChallenge).toBe(false); expect(savegame10213.oneCityChallenge).toBe(false); expect(savegame103279.oneCityChallenge).toBe(true); }); test('Set one city challenge', async () => { savegame10017.oneCityChallenge = NEW_ONE_CITY_CHALLENGE; savegame101135.oneCityChallenge = NEW_ONE_CITY_CHALLENGE; savegame101221.oneCityChallenge = NEW_ONE_CITY_CHALLENGE; savegame10213.oneCityChallenge = NEW_ONE_CITY_CHALLENGE; savegame103279.oneCityChallenge = NEW_ONE_CITY_CHALLENGE; expect(savegame10017.oneCityChallenge).toBe(NEW_ONE_CITY_CHALLENGE); expect(savegame101135.oneCityChallenge).toBe(NEW_ONE_CITY_CHALLENGE); expect(savegame101221.oneCityChallenge).toBe(NEW_ONE_CITY_CHALLENGE); expect(savegame10213.oneCityChallenge).toBe(NEW_ONE_CITY_CHALLENGE); expect(savegame103279.oneCityChallenge).toBe(NEW_ONE_CITY_CHALLENGE); }); test('Get pitboss', () => { expect(savegame10017.pitboss).toBe(false); expect(savegame101135.pitboss).toBe(false); expect(savegame101221.pitboss).toBe(false); expect(savegame10213.pitboss).toBe(false); expect(savegame103279.pitboss).toBe(true); }); test('Set pitboss', async () => { savegame10017.pitboss = NEW_PITBOSS; savegame101135.pitboss = NEW_PITBOSS; savegame101221.pitboss = NEW_PITBOSS; savegame10213.pitboss = NEW_PITBOSS; savegame103279.pitboss = NEW_PITBOSS; expect(savegame10017.pitboss).toBe(NEW_PITBOSS); expect(savegame101135.pitboss).toBe(NEW_PITBOSS); expect(savegame101221.pitboss).toBe(NEW_PITBOSS); expect(savegame10213.pitboss).toBe(NEW_PITBOSS); expect(savegame103279.pitboss).toBe(NEW_PITBOSS); }); test('Get policy saving', () => { expect(savegame10017.policySaving).toBe(false); expect(savegame101135.policySaving).toBe(false); expect(savegame101221.policySaving).toBe(false); expect(savegame10213.policySaving).toBe(false); expect(savegame103279.policySaving).toBe(true); }); test('Set policy saving', async () => { savegame10017.policySaving = NEW_POLICY_SAVING; savegame101135.policySaving = NEW_POLICY_SAVING; savegame101221.policySaving = NEW_POLICY_SAVING; savegame10213.policySaving = NEW_POLICY_SAVING; savegame103279.policySaving = NEW_POLICY_SAVING; expect(savegame10017.policySaving).toBe(NEW_POLICY_SAVING); expect(savegame101135.policySaving).toBe(NEW_POLICY_SAVING); expect(savegame101221.policySaving).toBe(NEW_POLICY_SAVING); expect(savegame10213.policySaving).toBe(NEW_POLICY_SAVING); expect(savegame103279.policySaving).toBe(NEW_POLICY_SAVING); }); test('Get promotion saving', () => { expect(savegame10017.promotionSaving).toBe(false); expect(savegame101135.promotionSaving).toBe(false); expect(savegame101221.promotionSaving).toBe(false); expect(savegame10213.promotionSaving).toBe(false); expect(savegame103279.promotionSaving).toBe(true); }); test('Set promotion saving', async () => { savegame10017.promotionSaving = NEW_PROMOTION_SAVING; savegame101135.promotionSaving = NEW_PROMOTION_SAVING; savegame101221.promotionSaving = NEW_PROMOTION_SAVING; savegame10213.promotionSaving = NEW_PROMOTION_SAVING; savegame103279.promotionSaving = NEW_PROMOTION_SAVING; expect(savegame10017.promotionSaving).toBe(NEW_PROMOTION_SAVING); expect(savegame101135.promotionSaving).toBe(NEW_PROMOTION_SAVING); expect(savegame101221.promotionSaving).toBe(NEW_PROMOTION_SAVING); expect(savegame10213.promotionSaving).toBe(NEW_PROMOTION_SAVING); expect(savegame103279.promotionSaving).toBe(NEW_PROMOTION_SAVING); }); test('Get raging barbarians', () => { expect(savegame10017.ragingBarbarians).toBe(false); expect(savegame101135.ragingBarbarians).toBe(false); expect(savegame101221.ragingBarbarians).toBe(false); expect(savegame10213.ragingBarbarians).toBe(false); expect(savegame103279.ragingBarbarians).toBe(true); }); test('Set raging barbarians', async () => { savegame10017.ragingBarbarians = NEW_RAGING_BARBARIANS; savegame101135.ragingBarbarians = NEW_RAGING_BARBARIANS; savegame101221.ragingBarbarians = NEW_RAGING_BARBARIANS; savegame10213.ragingBarbarians = NEW_RAGING_BARBARIANS; savegame103279.ragingBarbarians = NEW_RAGING_BARBARIANS; expect(savegame10017.ragingBarbarians).toBe(NEW_RAGING_BARBARIANS); expect(savegame101135.ragingBarbarians).toBe(NEW_RAGING_BARBARIANS); expect(savegame101221.ragingBarbarians).toBe(NEW_RAGING_BARBARIANS); expect(savegame10213.ragingBarbarians).toBe(NEW_RAGING_BARBARIANS); expect(savegame103279.ragingBarbarians).toBe(NEW_RAGING_BARBARIANS); }); test('Get random personalities', () => { expect(savegame10017.randomPersonalities).toBe(false); expect(savegame101135.randomPersonalities).toBe(false); expect(savegame101221.randomPersonalities).toBe(false); expect(savegame10213.randomPersonalities).toBe(false); expect(savegame103279.randomPersonalities).toBe(true); }); test('Set random personalities', async () => { savegame10017.randomPersonalities = NEW_RANDOM_PERSONALITIES; savegame101135.randomPersonalities = NEW_RANDOM_PERSONALITIES; savegame101221.randomPersonalities = NEW_RANDOM_PERSONALITIES; savegame10213.randomPersonalities = NEW_RANDOM_PERSONALITIES; savegame103279.randomPersonalities = NEW_RANDOM_PERSONALITIES; expect(savegame10017.randomPersonalities).toBe(NEW_RANDOM_PERSONALITIES); expect(savegame101135.randomPersonalities).toBe(NEW_RANDOM_PERSONALITIES); expect(savegame101221.randomPersonalities).toBe(NEW_RANDOM_PERSONALITIES); expect(savegame10213.randomPersonalities).toBe(NEW_RANDOM_PERSONALITIES); expect(savegame103279.randomPersonalities).toBe(NEW_RANDOM_PERSONALITIES); }); test('Get turn timer enabled', () => { expect(savegame10017.turnTimerEnabled).toBe(false); expect(savegame101135.turnTimerEnabled).toBe(false); expect(savegame101221.turnTimerEnabled).toBe(false); expect(savegame10213.turnTimerEnabled).toBe(false); expect(savegame103279.turnTimerEnabled).toBe(true); }); test('Set turn timer enabled', async () => { savegame10017.turnTimerEnabled = NEW_TURN_TIMER_ENABLED; savegame101135.turnTimerEnabled = NEW_TURN_TIMER_ENABLED; savegame101221.turnTimerEnabled = NEW_TURN_TIMER_ENABLED; savegame10213.turnTimerEnabled = NEW_TURN_TIMER_ENABLED; savegame103279.turnTimerEnabled = NEW_TURN_TIMER_ENABLED; expect(savegame10017.turnTimerEnabled).toBe(NEW_TURN_TIMER_ENABLED); expect(savegame101135.turnTimerEnabled).toBe(NEW_TURN_TIMER_ENABLED); expect(savegame101221.turnTimerEnabled).toBe(NEW_TURN_TIMER_ENABLED); expect(savegame10213.turnTimerEnabled).toBe(NEW_TURN_TIMER_ENABLED); expect(savegame103279.turnTimerEnabled).toBe(NEW_TURN_TIMER_ENABLED); }); test('Get turn mode', () => { expect(savegame10017.turnMode).toBe(Civ5Save.TURN_MODES.SEQUENTIAL); expect(savegame101135.turnMode).toBe(Civ5Save.TURN_MODES.SEQUENTIAL); expect(savegame101221.turnMode).toBe(Civ5Save.TURN_MODES.SEQUENTIAL); expect(savegame10213.turnMode).toBe(Civ5Save.TURN_MODES.SEQUENTIAL); expect(savegame103279.turnMode).toBe(Civ5Save.TURN_MODES.HYBRID); }); test('Set turn mode', async () => { savegame10017.turnMode = Civ5Save.TURN_MODES.HYBRID; savegame101135.turnMode = Civ5Save.TURN_MODES.SIMULTANEOUS; savegame101221.turnMode = Civ5Save.TURN_MODES.SEQUENTIAL; savegame10213.turnMode = NEW_TURN_MODE; savegame103279.turnMode = NEW_TURN_MODE; expect(savegame10017.turnMode).toBe(Civ5Save.TURN_MODES.HYBRID); expect(savegame101135.turnMode).toBe(Civ5Save.TURN_MODES.SIMULTANEOUS); expect(savegame101221.turnMode).toBe(Civ5Save.TURN_MODES.SEQUENTIAL); expect(savegame10213.turnMode).toBe(NEW_TURN_MODE); expect(savegame103279.turnMode).toBe(NEW_TURN_MODE); }); test('Get max turns', () => { expect(savegame10017.maxTurns).toBe(500); expect(savegame101135.maxTurns).toBe(1500); expect(savegame101221.maxTurns).toBe(100); expect(savegame10213.maxTurns).toBe(500); expect(savegame103279.maxTurns).toBe(0); }); test('Set max turns', () => { savegame10017.maxTurns = NEW_MAX_TURNS; savegame101135.maxTurns = NEW_MAX_TURNS; savegame101221.maxTurns = NEW_MAX_TURNS; savegame10213.maxTurns = NEW_MAX_TURNS; savegame103279.maxTurns = NEW_MAX_TURNS; expect(savegame10017.maxTurns).toBe(NEW_MAX_TURNS); expect(savegame101135.maxTurns).toBe(NEW_MAX_TURNS); expect(savegame101221.maxTurns).toBe(NEW_MAX_TURNS); expect(savegame10213.maxTurns).toBe(NEW_MAX_TURNS); expect(savegame103279.maxTurns).toBe(NEW_MAX_TURNS); }); test('Get turn timer length', () => { expect(savegame10017.turnTimerLength).toBe(0); expect(savegame101135.turnTimerLength).toBe(0); expect(savegame101221.turnTimerLength).toBe(0); expect(savegame10213.turnTimerLength).toBe(0); expect(savegame103279.turnTimerLength).toBe(123); }); test('Set turn timer length', () => { savegame10017.turnTimerLength = NEW_TURN_TIMER_VALUE; savegame101135.turnTimerLength = NEW_TURN_TIMER_VALUE; savegame101221.turnTimerLength = NEW_TURN_TIMER_VALUE; savegame10213.turnTimerLength = NEW_TURN_TIMER_VALUE; savegame103279.turnTimerLength = NEW_TURN_TIMER_VALUE; expect(savegame10017.turnTimerLength).toBe(NEW_TURN_TIMER_VALUE); expect(savegame101135.turnTimerLength).toBe(NEW_TURN_TIMER_VALUE); expect(savegame101221.turnTimerLength).toBe(NEW_TURN_TIMER_VALUE); expect(savegame10213.turnTimerLength).toBe(NEW_TURN_TIMER_VALUE); expect(savegame103279.turnTimerLength).toBe(NEW_TURN_TIMER_VALUE); }); test('Get private game', () => { expect(savegame10017.privateGame).not.toBeDefined(); expect(savegame101135.privateGame).not.toBeDefined(); expect(savegame101221.privateGame).not.toBeDefined(); expect(savegame10213.privateGame).toBe(false); expect(savegame103279.privateGame).toBe(true); }); test('Set private game', () => { savegame10213.privateGame = NEW_PRIVATE_GAME; savegame103279.privateGame = NEW_PRIVATE_GAME; expect(savegame10213.privateGame).toBe(NEW_PRIVATE_GAME); expect(savegame103279.privateGame).toBe(NEW_PRIVATE_GAME); }); test('Get time victory', () => { expect(savegame10017.timeVictory).toBe(true); expect(savegame101135.timeVictory).toBe(true); expect(savegame101221.timeVictory).toBe(true); expect(savegame10213.timeVictory).toBe(true); expect(savegame103279.timeVictory).toBe(false); }); test('Set time victory', () => { savegame10017.timeVictory = NEW_TIME_VICTORY; savegame101135.timeVictory = NEW_TIME_VICTORY; savegame101221.timeVictory = NEW_TIME_VICTORY; savegame10213.timeVictory = NEW_TIME_VICTORY; savegame103279.timeVictory = NEW_TIME_VICTORY; expect(savegame10017.timeVictory).toBe(NEW_TIME_VICTORY); expect(savegame101135.timeVictory).toBe(NEW_TIME_VICTORY); expect(savegame101221.timeVictory).toBe(NEW_TIME_VICTORY); expect(savegame10213.timeVictory).toBe(NEW_TIME_VICTORY); expect(savegame103279.timeVictory).toBe(NEW_TIME_VICTORY); }); test('Get science victory', () => { expect(savegame10017.scienceVictory).toBe(true); expect(savegame101135.scienceVictory).toBe(true); expect(savegame101221.scienceVictory).toBe(false); expect(savegame10213.scienceVictory).toBe(true); expect(savegame103279.scienceVictory).toBe(true); }); test('Set science victory', () => { savegame10017.scienceVictory = NEW_SCIENCE_VICTORY; savegame101135.scienceVictory = NEW_SCIENCE_VICTORY; savegame101221.scienceVictory = NEW_SCIENCE_VICTORY; savegame10213.scienceVictory = NEW_SCIENCE_VICTORY; savegame103279.scienceVictory = NEW_SCIENCE_VICTORY; expect(savegame101221.scienceVictory).toBe(NEW_SCIENCE_VICTORY); expect(savegame10017.scienceVictory).toBe(NEW_SCIENCE_VICTORY); expect(savegame101135.scienceVictory).toBe(NEW_SCIENCE_VICTORY); expect(savegame10213.scienceVictory).toBe(NEW_SCIENCE_VICTORY); expect(savegame103279.scienceVictory).toBe(NEW_SCIENCE_VICTORY); }); test('Get domination victory', () => { expect(savegame10017.dominationVictory).toBe(true); expect(savegame101135.dominationVictory).toBe(true); expect(savegame101221.dominationVictory).toBe(false); expect(savegame10213.dominationVictory).toBe(true); expect(savegame103279.dominationVictory).toBe(false); }); test('Set domination victory', () => { savegame10017.dominationVictory = NEW_DOMINATION_VICTORY; savegame101135.dominationVictory = NEW_DOMINATION_VICTORY; savegame101221.dominationVictory = NEW_DOMINATION_VICTORY; savegame10213.dominationVictory = NEW_DOMINATION_VICTORY; savegame103279.dominationVictory = NEW_DOMINATION_VICTORY; expect(savegame10017.dominationVictory).toBe(NEW_DOMINATION_VICTORY); expect(savegame101135.dominationVictory).toBe(NEW_DOMINATION_VICTORY); expect(savegame101221.dominationVictory).toBe(NEW_DOMINATION_VICTORY); expect(savegame10213.dominationVictory).toBe(NEW_DOMINATION_VICTORY); expect(savegame103279.dominationVictory).toBe(NEW_DOMINATION_VICTORY); }); test('Get cultural victory', () => { expect(savegame10017.culturalVictory).toBe(true); expect(savegame101135.culturalVictory).toBe(true); expect(savegame101221.culturalVictory).toBe(false); expect(savegame10213.culturalVictory).toBe(true); expect(savegame103279.culturalVictory).toBe(true); }); test('Set cultural victory', () => { savegame10017.culturalVictory = NEW_CULTURAL_VICTORY; savegame101135.culturalVictory = NEW_CULTURAL_VICTORY; savegame101221.culturalVictory = NEW_CULTURAL_VICTORY; savegame10213.culturalVictory = NEW_CULTURAL_VICTORY; savegame103279.culturalVictory = NEW_CULTURAL_VICTORY; expect(savegame10017.culturalVictory).toBe(NEW_CULTURAL_VICTORY); expect(savegame101135.culturalVictory).toBe(NEW_CULTURAL_VICTORY); expect(savegame101221.culturalVictory).toBe(NEW_CULTURAL_VICTORY); expect(savegame10213.culturalVictory).toBe(NEW_CULTURAL_VICTORY); expect(savegame103279.culturalVictory).toBe(NEW_CULTURAL_VICTORY); }); test('Get diplomatic victory', () => { expect(savegame10017.diplomaticVictory).toBe(true); expect(savegame101135.diplomaticVictory).toBe(true); expect(savegame101221.diplomaticVictory).toBe(false); expect(savegame10213.diplomaticVictory).toBe(true); expect(savegame103279.diplomaticVictory).toBe(false); }); test('Set diplomatic victory', () => { savegame10017.diplomaticVictory = NEW_DIPLOMATIC_VICTORY; savegame101135.diplomaticVictory = NEW_DIPLOMATIC_VICTORY; savegame101221.diplomaticVictory = NEW_DIPLOMATIC_VICTORY; savegame10213.diplomaticVictory = NEW_DIPLOMATIC_VICTORY; savegame103279.diplomaticVictory = NEW_DIPLOMATIC_VICTORY; expect(savegame10017.diplomaticVictory).toBe(NEW_DIPLOMATIC_VICTORY); expect(savegame101135.diplomaticVictory).toBe(NEW_DIPLOMATIC_VICTORY); expect(savegame101221.diplomaticVictory).toBe(NEW_DIPLOMATIC_VICTORY); expect(savegame10213.diplomaticVictory).toBe(NEW_DIPLOMATIC_VICTORY); expect(savegame103279.diplomaticVictory).toBe(NEW_DIPLOMATIC_VICTORY); }); test('Save to blob', async () => { let newSavegameFile = savegame103279.toBlob(); let newSavegame = await Civ5Save.fromFile(newSavegameFile); expect(newSavegame.alwaysPeace).toBe(NEW_ALWAYS_PEACE); expect(newSavegame.alwaysWar).toBe(NEW_ALWAYS_WAR); expect(newSavegame.completeKills).toBe(NEW_COMPLETE_KILLS); expect(newSavegame.culturalVictory).toBe(NEW_CULTURAL_VICTORY); expect(newSavegame.diplomaticVictory).toBe(NEW_DIPLOMATIC_VICTORY); expect(newSavegame.dominationVictory).toBe(NEW_DOMINATION_VICTORY); expect(newSavegame.lockMods).toBe(NEW_LOCK_MODS); expect(newSavegame.maxTurns).toBe(NEW_MAX_TURNS); expect(newSavegame.newRandomSeed).toBe(NEW_NEW_RANDOM_SEED); expect(newSavegame.noBarbarians).toBe(NEW_NO_BARBARIANS); expect(newSavegame.noChangingWarPeace).toBe(NEW_NO_CHANGING_WAR_OR_PEACE); expect(newSavegame.noCityRazing).toBe(NEW_NO_CITY_RAZING); expect(newSavegame.noCultureOverviewUI).toBe(NEW_NO_CULTURE_OVERVIEW_UI); expect(newSavegame.noEspionage).toBe(NEW_NO_ESPIONAGE); expect(newSavegame.noHappiness).toBe(NEW_NO_HAPPINESS); expect(newSavegame.noPolicies).toBe(NEW_NO_POLICIES); expect(newSavegame.noReligion).toBe(NEW_NO_RELIGION); expect(newSavegame.noScience).toBe(NEW_NO_SCIENCE); expect(newSavegame.noWorldCongress).toBe(NEW_NO_WORLD_CONGRESS); expect(newSavegame.oneCityChallenge).toBe(NEW_ONE_CITY_CHALLENGE); expect(newSavegame.pitboss).toBe(NEW_PITBOSS); expect(newSavegame.policySaving).toBe(NEW_POLICY_SAVING); expect(newSavegame.privateGame).toBe(NEW_PRIVATE_GAME); expect(newSavegame.promotionSaving).toBe(NEW_PROMOTION_SAVING); expect(newSavegame.ragingBarbarians).toBe(NEW_RAGING_BARBARIANS); expect(newSavegame.randomPersonalities).toBe(NEW_RANDOM_PERSONALITIES); expect(newSavegame.scienceVictory).toBe(NEW_SCIENCE_VICTORY); expect(newSavegame.timeVictory).toBe(NEW_TIME_VICTORY); expect(newSavegame.turnTimerEnabled).toBe(NEW_TURN_TIMER_ENABLED); expect(newSavegame.turnTimerLength).toBe(NEW_TURN_TIMER_VALUE); expect(newSavegame.turnMode).toBe(NEW_TURN_MODE); }); test('Open broken save game', async () => { let fileBlob = await getFileBlob(TEST_SAVEGAME_BROKEN); await expect(Civ5Save.fromFile(fileBlob)).rejects.toBeDefined(); }); // https://github.com/bmaupin/civ5save-editor/issues/3 test('Test issue 3 (section19SkipSavePath)', async () => { let fileBlob = await getFileBlob(path.join(__dirname, 'resources', 'issue3.Civ5Save')); let savegame = await Civ5Save.fromFile(fileBlob); expect(savegame.maxTurns).toBe(330); }); // https://github.com/bmaupin/civ5save-editor/issues/4 test('Test issue 4 (gameBuild)', async () => { let fileBlob = await getFileBlob(path.join(__dirname, 'resources', 'issue4.Civ5Save')); let savegame = await Civ5Save.fromFile(fileBlob); expect(savegame.gameBuild).toBe('403694'); expect(savegame.maxTurns).toBe(500); }); // https://github.com/bmaupin/civ5save-editor/issues/6 test('Test issue 6', async () => { let fileBlob = await getFileBlob(path.join(__dirname, 'resources', 'issue6.Civ5Save')); let savegame = await Civ5Save.fromFile(fileBlob); expect(savegame.maxTurns).toBe(0); }); // https://github.com/bmaupin/civ5save-editor/issues/8 test('Test issue 8', async () => { let fileBlob = await getFileBlob(path.join(__dirname, 'resources', 'issue8.Civ5Save')); let savegame = await Civ5Save.fromFile(fileBlob); expect(savegame.enabledMods).toEqual([ '(1) Community Patch', '(2) Community Balance Overhaul', '(3) City-State Diplomacy Mod for CBP', '(4) C4DF - CBP', '(5) More Luxuries - CBO Edition (5-14b)', ]); expect(savegame.timeVictory).toBe(true); expect(savegame.noWorldCongress).toBe(false); }); // https://github.com/bmaupin/civ5save-editor/issues/15 test('Test issue 15', async () => { let fileBlob = await getFileBlob(path.join(__dirname, 'resources', 'issue15.Civ5Save')); let savegame = await Civ5Save.fromFile(fileBlob); expect(savegame.gameVersion).toBe('1.0.3.279 (180925)'); expect(savegame.gameBuild).toBe('403694'); expect(savegame.maxTurns).toBe(330); });
cordova.define("com.hpit.mobile.plugin.emailSender.EmailSenderPlugin", function(require, exports, module) {var exec = require('cordova/exec'); function EmailSenderPlugin(){ } EmailSenderPlugin.prototype.send = function(recipients, subject, text, successCallback, failureCallback){ exec(successCallback, failureCallback, "EmailSenderPlugin", "send", [recipients, subject, text]); } module.exports = new EmailSenderPlugin(); });
$(window).load(function() { $('img').click(function(){ $('img').hide(); }) $('p').click(function(){ $('img').show(); }) $('.changeName').click(function(){ $('.changeName').text('nicki'); }) });
const prettier = require('./.prettierrc.js'); const error = 2; const warn = 1; const ignore = 0; module.exports = { root: true, extends: ['eslint-config-airbnb', 'plugin:jest/recommended', 'prettier'], plugins: ['prettier', 'jest', 'react', 'json'], parser: 'babel-eslint', parserOptions: { sourceType: 'module', }, env: { es6: true, node: true, 'jest/globals': true, }, rules: { strict: [error, 'never'], 'prettier/prettier': [warn, prettier], quotes: [warn, 'single', { avoidEscape: true }], 'class-methods-use-this': ignore, 'arrow-parens': [warn, 'as-needed'], 'space-before-function-paren': ignore, 'import/no-unresolved': warn, 'import/extensions': [ // because of highlight.js and fuse.js warn, { js: 'never', json: 'always', }, ], 'import/no-extraneous-dependencies': [ error, { devDependencies: [ 'examples/**', '**/example/**', '*.js', '**/*.test.js', '**/scripts/*.js', '**/stories/*.js', '**/__tests__/*.js', 'src/**', ], peerDependencies: true, }, ], 'import/prefer-default-export': ignore, 'react/prop-types': ignore, 'react/jsx-wrap-multilines': ignore, 'react/jsx-indent': ignore, 'react/jsx-indent-props': ignore, 'react/jsx-closing-bracket-location': ignore, 'react/jsx-uses-react': error, 'react/jsx-uses-vars': error, 'react/react-in-jsx-scope': error, 'react/jsx-filename-extension': [ warn, { extensions: ['.js', '.jsx'], }, ], 'jsx-a11y/accessible-emoji': ignore, 'jsx-a11y/href-no-hash': ignore, 'jsx-a11y/label-has-for': ignore, 'jsx-a11y/anchor-is-valid': ['warn', { aspects: ['invalidHref'] }], 'react/no-unescaped-entities': ignore, }, };
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi" ], "MONTH": [ "janvier", "f\u00e9vrier", "mars", "avril", "mai", "juin", "juillet", "ao\u00fbt", "septembre", "octobre", "novembre", "d\u00e9cembre" ], "SHORTDAY": [ "dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam." ], "SHORTMONTH": [ "janv.", "f\u00e9vr.", "mars", "avr.", "mai", "juin", "juil.", "ao\u00fbt", "sept.", "oct.", "nov.", "d\u00e9c." ], "fullDate": "EEEE d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y HH:mm:ss", "mediumDate": "d MMM y", "mediumTime": "HH:mm:ss", "short": "dd/MM/yy HH:mm", "shortDate": "dd/MM/yy", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u20ac", "DECIMAL_SEP": ",", "GROUP_SEP": "\u00a0", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "(", "negSuf": "\u00a0\u00a4)", "posPre": "", "posSuf": "\u00a0\u00a4" } ] }, "id": "fr-re", "pluralCat": function (n) { if (n >= 0 && n <= 2 && n != 2) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
var scotchTape = require('scotch-tape'); var TChannel = require('tchannel'); var server = new TChannel(); var client = new TChannel(); var serverChan = server.makeSubChannel({ serviceName: 'server-original' }); // normal response serverChan.register('func1', function onReq(req, res, arg2, arg3) { // console.log('func1 responding with a small delay', { // arg2: arg2.toString(), // arg3: arg3.toString() // }); setTimeout(function onTimeout() { res.headers.as = 'raw'; res.sendOk('result', 'indeed it did'); }, Math.random() * 1000); }); // error response serverChan.register('func2', function onReq2(req, res) { res.headers.as = 'raw'; res.sendNotOk(null, 'it failed'); }); // error serverChan.register('func3', function onReq2(req, res) { res.headers.as = 'raw'; res.sendError(404, 'failed'); }); var test = scotchTape(); test('TChannel Integration', function run(it) { server.listen(24040, '127.0.0.1', function onListen() { var clientChan = client.makeSubChannel({ serviceName: 'server-original', peers: [server.hostPort], requestDefaults: { hasNoParent: true, headers: { as: 'raw', cn: 'example-client' } } }); it('should handle ok', function should(t) { var clientRequest = clientChan.request({ serviceName: 'server-original', timeout: 1500 }); clientRequest .send('func1', 'arg 1', 'arg 2', function callback(err, res, arg2, arg3) { t.equal(res.ok, true); finish(); t.end(); }) }); it('should handle not ok', function should(t) { var clientRequest = clientChan.request({ serviceName: 'server-original' }); clientRequest .send('func2', 'arg 1', 'arg 2', function callback(err, res, arg2, arg3) { t.equal(res.ok, false); finish(); t.end(); }); }); it('should handle error', function should(t) { var clientRequest = clientChan.request({ serviceName: 'server-original' }); clientRequest .send('func3', 'arg 1', 'arg 2', function callback(err, res, arg2, arg3) { t.ok(err); finish(); t.end(); }); }); }); }); var counter = 3; function finish(err) { if (err) { throw err; } if (--counter === 0) { server.close(); client.close(); } }
if ( eQuery.fn.width ) { module("dimensions", { teardown: moduleTeardown }); var pass = function( val ) { return val; }; var fn = function( val ) { return function(){ return val; }; }; /* ======== local reference ======= pass and fn can be used to test passing functions to setters See testWidth below for an example pass( value ); This function returns whatever value is passed in fn( value ); Returns a function that returns the value */ var testWidth = function( val ) { expect(9); var €div = eQuery("#nothiddendiv"); €div.width( val(30) ); equal(€div.width(), 30, "Test set to 30 correctly"); €div.hide(); equal(€div.width(), 30, "Test hidden div"); €div.show(); €div.width( val(-1) ); // handle negative numbers by setting to 0 #11604 equal(€div.width(), 0, "Test negative width normalized to 0"); €div.css("padding", "20px"); equal(€div.width(), 0, "Test padding specified with pixels"); €div.css("border", "2px solid #fff"); equal(€div.width(), 0, "Test border specified with pixels"); €div.css({ "display": "", "border": "", "padding": "" }); eQuery("#nothiddendivchild").css({ "width": 20, "padding": "3px", "border": "2px solid #fff" }); equal(eQuery("#nothiddendivchild").width(), 20, "Test child width with border and padding"); eQuery("#nothiddendiv, #nothiddendivchild").css({ "border": "", "padding": "", "width": "" }); var blah = eQuery("blah"); equal( blah.width( val(10) ), blah, "Make sure that setting a width on an empty set returns the set." ); equal( blah.width(), null, "Make sure 'null' is returned on an empty set"); equal( eQuery(window).width(), document.documentElement.clientWidth, "Window width is equal to width reported by window/document." ); eQuery._removeData( €div[0], "olddisplay" ); }; test("width()", function() { testWidth( pass ); }); test("width(Function)", function() { testWidth( fn ); }); test("width(Function(args))", function() { expect( 2 ); var €div = eQuery("#nothiddendiv"); €div.width( 30 ).width(function(i, width) { equal( width, 30, "Make sure previous value is corrrect." ); return width + 1; }); equal( €div.width(), 31, "Make sure value was modified correctly." ); }); var testHeight = function( val ) { expect(9); var €div = eQuery("#nothiddendiv"); €div.height( val(30) ); equal(€div.height(), 30, "Test set to 30 correctly"); €div.hide(); equal(€div.height(), 30, "Test hidden div"); €div.show(); €div.height( val(-1) ); // handle negative numbers by setting to 0 #11604 equal(€div.height(), 0, "Test negative height normalized to 0"); €div.css("padding", "20px"); equal(€div.height(), 0, "Test padding specified with pixels"); €div.css("border", "2px solid #fff"); equal(€div.height(), 0, "Test border specified with pixels"); €div.css({ "display": "", "border": "", "padding": "", "height": "1px" }); eQuery("#nothiddendivchild").css({ "height": 20, "padding": "3px", "border": "2px solid #fff" }); equal(eQuery("#nothiddendivchild").height(), 20, "Test child height with border and padding"); eQuery("#nothiddendiv, #nothiddendivchild").css({ "border": "", "padding": "", "height": "" }); var blah = eQuery("blah"); equal( blah.height( val(10) ), blah, "Make sure that setting a height on an empty set returns the set." ); equal( blah.height(), null, "Make sure 'null' is returned on an empty set"); equal( eQuery(window).height(), document.documentElement.clientHeight, "Window width is equal to width reported by window/document." ); eQuery._removeData( €div[0], "olddisplay" ); }; test("height()", function() { testHeight( pass ); }); test("height(Function)", function() { testHeight( fn ); }); test("height(Function(args))", function() { expect( 2 ); var €div = eQuery("#nothiddendiv"); €div.height( 30 ).height(function(i, height) { equal( height, 30, "Make sure previous value is corrrect." ); return height + 1; }); equal( €div.height(), 31, "Make sure value was modified correctly." ); }); test("innerWidth()", function() { expect(6); var winWidth = eQuery( window ).width(), docWidth = eQuery( document ).width(); equal(eQuery(window).innerWidth(), winWidth, "Test on window"); equal(eQuery(document).innerWidth(), docWidth, "Test on document"); var €div = eQuery("#nothiddendiv"); // set styles €div.css({ "margin": 10, "border": "2px solid #fff", "width": 30 }); equal(€div.innerWidth(), 30, "Test with margin and border"); €div.css("padding", "20px"); equal(€div.innerWidth(), 70, "Test with margin, border and padding"); €div.hide(); equal(€div.innerWidth(), 70, "Test hidden div"); // reset styles €div.css({ "display": "", "border": "", "padding": "", "width": "", "height": "" }); var div = eQuery( "<div>" ); // Temporarily require 0 for backwards compat - should be auto equal( div.innerWidth(), 0, "Make sure that disconnected nodes are handled." ); div.remove(); eQuery._removeData( €div[0], "olddisplay" ); }); test("innerHeight()", function() { expect(6); var winHeight = eQuery( window ).height(), docHeight = eQuery( document ).height(); equal(eQuery(window).innerHeight(), winHeight, "Test on window"); equal(eQuery(document).innerHeight(), docHeight, "Test on document"); var €div = eQuery("#nothiddendiv"); // set styles €div.css({ "margin": 10, "border": "2px solid #fff", "height": 30 }); equal(€div.innerHeight(), 30, "Test with margin and border"); €div.css("padding", "20px"); equal(€div.innerHeight(), 70, "Test with margin, border and padding"); €div.hide(); equal(€div.innerHeight(), 70, "Test hidden div"); // reset styles €div.css({ "display": "", "border": "", "padding": "", "width": "", "height": "" }); var div = eQuery( "<div>" ); // Temporarily require 0 for backwards compat - should be auto equal( div.innerHeight(), 0, "Make sure that disconnected nodes are handled." ); div.remove(); eQuery._removeData( €div[0], "olddisplay" ); }); test("outerWidth()", function() { expect(11); var winWidth = eQuery( window ).width(), docWidth = eQuery( document ).width(); equal( eQuery( window ).outerWidth(), winWidth, "Test on window without margin option" ); equal( eQuery( window ).outerWidth( true ), winWidth, "Test on window with margin option" ); equal( eQuery( document ).outerWidth(), docWidth, "Test on document without margin option" ); equal( eQuery( document ).outerWidth( true ), docWidth, "Test on document with margin option" ); var €div = eQuery("#nothiddendiv"); €div.css("width", 30); equal(€div.outerWidth(), 30, "Test with only width set"); €div.css("padding", "20px"); equal(€div.outerWidth(), 70, "Test with padding"); €div.css("border", "2px solid #fff"); equal(€div.outerWidth(), 74, "Test with padding and border"); €div.css("margin", "10px"); equal(€div.outerWidth(), 74, "Test with padding, border and margin without margin option"); €div.css("position", "absolute"); equal(€div.outerWidth(true), 94, "Test with padding, border and margin with margin option"); €div.hide(); equal(€div.outerWidth(true), 94, "Test hidden div with padding, border and margin with margin option"); // reset styles €div.css({ "position": "", "display": "", "border": "", "padding": "", "width": "", "height": "" }); var div = eQuery( "<div>" ); // Temporarily require 0 for backwards compat - should be auto equal( div.outerWidth(), 0, "Make sure that disconnected nodes are handled." ); div.remove(); eQuery._removeData( €div[0], "olddisplay" ); }); test("child of a hidden elem (or unconnected node) has accurate inner/outer/Width()/Height() see #9441 #9300", function() { expect(16); // setup html var €divNormal = eQuery("<div>").css({ "width": "100px", "height": "100px", "border": "10px solid white", "padding": "2px", "margin": "3px" }), €divChild = €divNormal.clone(), €divUnconnected = €divNormal.clone(), €divHiddenParent = eQuery("<div>").css( "display", "none" ).append( €divChild ).appendTo("body"); €divNormal.appendTo("body"); // tests that child div of a hidden div works the same as a normal div equal( €divChild.width(), €divNormal.width(), "child of a hidden element width() is wrong see #9441" ); equal( €divChild.innerWidth(), €divNormal.innerWidth(), "child of a hidden element innerWidth() is wrong see #9441" ); equal( €divChild.outerWidth(), €divNormal.outerWidth(), "child of a hidden element outerWidth() is wrong see #9441" ); equal( €divChild.outerWidth(true), €divNormal.outerWidth( true ), "child of a hidden element outerWidth( true ) is wrong see #9300" ); equal( €divChild.height(), €divNormal.height(), "child of a hidden element height() is wrong see #9441" ); equal( €divChild.innerHeight(), €divNormal.innerHeight(), "child of a hidden element innerHeight() is wrong see #9441" ); equal( €divChild.outerHeight(), €divNormal.outerHeight(), "child of a hidden element outerHeight() is wrong see #9441" ); equal( €divChild.outerHeight(true), €divNormal.outerHeight( true ), "child of a hidden element outerHeight( true ) is wrong see #9300" ); // tests that child div of an unconnected div works the same as a normal div equal( €divUnconnected.width(), €divNormal.width(), "unconnected element width() is wrong see #9441" ); equal( €divUnconnected.innerWidth(), €divNormal.innerWidth(), "unconnected element innerWidth() is wrong see #9441" ); equal( €divUnconnected.outerWidth(), €divNormal.outerWidth(), "unconnected element outerWidth() is wrong see #9441" ); equal( €divUnconnected.outerWidth(true), €divNormal.outerWidth( true ), "unconnected element outerWidth( true ) is wrong see #9300" ); equal( €divUnconnected.height(), €divNormal.height(), "unconnected element height() is wrong see #9441" ); equal( €divUnconnected.innerHeight(), €divNormal.innerHeight(), "unconnected element innerHeight() is wrong see #9441" ); equal( €divUnconnected.outerHeight(), €divNormal.outerHeight(), "unconnected element outerHeight() is wrong see #9441" ); equal( €divUnconnected.outerHeight(true), €divNormal.outerHeight( true ), "unconnected element outerHeight( true ) is wrong see #9300" ); // teardown html €divHiddenParent.remove(); €divNormal.remove(); }); test("getting dimensions shouldnt modify runtimeStyle see #9233", function() { expect( 1 ); var €div = eQuery( "<div>" ).appendTo( "#qunit-fixture" ), div = €div.get( 0 ), runtimeStyle = div.runtimeStyle; if ( runtimeStyle ) { div.runtimeStyle.marginLeft = "12em"; div.runtimeStyle.left = "11em"; } €div.outerWidth( true ); if ( runtimeStyle ) { equal( div.runtimeStyle.left, "11em", "getting dimensions modifies runtimeStyle, see #9233" ); } else { ok( true, "this browser doesnt support runtimeStyle, see #9233" ); } €div.remove(); }); test( "table dimensions", 2, function() { var table = eQuery("<table><colgroup><col/><col/></colgroup><tbody><tr><td></td><td>a</td></tr><tr><td></td><td>a</td></tr></tbody></table>").appendTo("#qunit-fixture"), tdElem = table.find("tr:eq(0) td:eq(0)"), colElem = table.find("col:eq(1)").width( 300 ); table.find("td").css({ "margin": 0, "padding": 0 }); equal( tdElem.width(), tdElem.width(), "width() doesn't alter dimension values of empty cells, see #11293" ); equal( colElem.width(), 300, "col elements have width(), see #12243" ); }); test("box-sizing:border-box child of a hidden elem (or unconnected node) has accurate inner/outer/Width()/Height() see #10413", function() { expect(16); // setup html var €divNormal = eQuery("<div>").css({ "boxSizing": "border-box", "width": "100px", "height": "100px", "border": "10px solid white", "padding": "2px", "margin": "3px" }), €divChild = €divNormal.clone(), €divUnconnected = €divNormal.clone(), €divHiddenParent = eQuery("<div>").css( "display", "none" ).append( €divChild ).appendTo("body"); €divNormal.appendTo("body"); // tests that child div of a hidden div works the same as a normal div equal( €divChild.width(), €divNormal.width(), "child of a hidden element width() is wrong see #10413" ); equal( €divChild.innerWidth(), €divNormal.innerWidth(), "child of a hidden element innerWidth() is wrong see #10413" ); equal( €divChild.outerWidth(), €divNormal.outerWidth(), "child of a hidden element outerWidth() is wrong see #10413" ); equal( €divChild.outerWidth(true), €divNormal.outerWidth( true ), "child of a hidden element outerWidth( true ) is wrong see #10413" ); equal( €divChild.height(), €divNormal.height(), "child of a hidden element height() is wrong see #10413" ); equal( €divChild.innerHeight(), €divNormal.innerHeight(), "child of a hidden element innerHeight() is wrong see #10413" ); equal( €divChild.outerHeight(), €divNormal.outerHeight(), "child of a hidden element outerHeight() is wrong see #10413" ); equal( €divChild.outerHeight(true), €divNormal.outerHeight( true ), "child of a hidden element outerHeight( true ) is wrong see #10413" ); // tests that child div of an unconnected div works the same as a normal div equal( €divUnconnected.width(), €divNormal.width(), "unconnected element width() is wrong see #10413" ); equal( €divUnconnected.innerWidth(), €divNormal.innerWidth(), "unconnected element innerWidth() is wrong see #10413" ); equal( €divUnconnected.outerWidth(), €divNormal.outerWidth(), "unconnected element outerWidth() is wrong see #10413" ); equal( €divUnconnected.outerWidth(true), €divNormal.outerWidth( true ), "unconnected element outerWidth( true ) is wrong see #10413" ); equal( €divUnconnected.height(), €divNormal.height(), "unconnected element height() is wrong see #10413" ); equal( €divUnconnected.innerHeight(), €divNormal.innerHeight(), "unconnected element innerHeight() is wrong see #10413" ); equal( €divUnconnected.outerHeight(), €divNormal.outerHeight(), "unconnected element outerHeight() is wrong see #10413" ); equal( €divUnconnected.outerHeight(true), €divNormal.outerHeight( true ), "unconnected element outerHeight( true ) is wrong see #10413" ); // teardown html €divHiddenParent.remove(); €divNormal.remove(); }); test("outerHeight()", function() { expect(11); var winHeight = eQuery( window ).height(), docHeight = eQuery( document ).height(); equal( eQuery( window ).outerHeight(), winHeight, "Test on window without margin option" ); equal( eQuery( window ).outerHeight( true ), winHeight, "Test on window with margin option" ); equal( eQuery( document ).outerHeight(), docHeight, "Test on document without margin option" ); equal( eQuery( document ).outerHeight( true ), docHeight, "Test on document with margin option" ); var €div = eQuery("#nothiddendiv"); €div.css("height", 30); equal(€div.outerHeight(), 30, "Test with only width set"); €div.css("padding", "20px"); equal(€div.outerHeight(), 70, "Test with padding"); €div.css("border", "2px solid #fff"); equal(€div.outerHeight(), 74, "Test with padding and border"); €div.css("margin", "10px"); equal(€div.outerHeight(), 74, "Test with padding, border and margin without margin option"); equal(€div.outerHeight(true), 94, "Test with padding, border and margin with margin option"); €div.hide(); equal(€div.outerHeight(true), 94, "Test hidden div with padding, border and margin with margin option"); // reset styles €div.css({ "display": "", "border": "", "padding": "", "width": "", "height": "" }); var div = eQuery( "<div>" ); // Temporarily require 0 for backwards compat - should be auto equal( div.outerHeight(), 0, "Make sure that disconnected nodes are handled." ); div.remove(); eQuery._removeData( €div[0], "olddisplay" ); }); test("passing undefined is a setter #5571", function() { expect(4); equal(eQuery("#nothiddendiv").height(30).height(undefined).height(), 30, ".height(undefined) is chainable (#5571)"); equal(eQuery("#nothiddendiv").height(30).innerHeight(undefined).height(), 30, ".innerHeight(undefined) is chainable (#5571)"); equal(eQuery("#nothiddendiv").height(30).outerHeight(undefined).height(), 30, ".outerHeight(undefined) is chainable (#5571)"); equal(eQuery("#nothiddendiv").width(30).width(undefined).width(), 30, ".width(undefined) is chainable (#5571)"); }); test( "getters on non elements should return null", function() { expect( 8 ); var nonElem = eQuery("notAnElement"); strictEqual( nonElem.width(), null, ".width() is not null (#12283)" ); strictEqual( nonElem.innerWidth(), null, ".innerWidth() is not null (#12283)" ); strictEqual( nonElem.outerWidth(), null, ".outerWidth() is not null (#12283)" ); strictEqual( nonElem.outerWidth( true ), null, ".outerWidth(true) is not null (#12283)" ); strictEqual( nonElem.height(), null, ".height() is not null (#12283)" ); strictEqual( nonElem.innerHeight(), null, ".innerHeight() is not null (#12283)" ); strictEqual( nonElem.outerHeight(), null, ".outerHeight() is not null (#12283)" ); strictEqual( nonElem.outerHeight( true ), null, ".outerHeight(true) is not null (#12283)" ); }); test("setters with and without box-sizing:border-box", function(){ expect(20); var el_bb = eQuery("<div style='width:114px;height:114px;margin:5px;padding:3px;border:4px solid white;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box;'>test</div>").appendTo("#qunit-fixture"), el = eQuery("<div style='width:100px;height:100px;margin:5px;padding:3px;border:4px solid white;'>test</div>").appendTo("#qunit-fixture"), expected = 100; equal( el_bb.width( 101 ).width(), expected + 1, "test border-box width(int) by roundtripping" ); equal( el_bb.innerWidth( 108 ).width(), expected + 2, "test border-box innerWidth(int) by roundtripping" ); equal( el_bb.outerWidth( 117 ).width(), expected + 3, "test border-box outerWidth(int) by roundtripping" ); equal( el_bb.outerWidth( 118, false ).width(), expected + 4, "test border-box outerWidth(int, false) by roundtripping" ); equal( el_bb.outerWidth( 129, true ).width(), expected + 5, "test border-box innerWidth(int, true) by roundtripping" ); equal( el_bb.height( 101 ).height(), expected + 1, "test border-box height(int) by roundtripping" ); equal( el_bb.innerHeight( 108 ).height(), expected + 2, "test border-box innerHeight(int) by roundtripping" ); equal( el_bb.outerHeight( 117 ).height(), expected + 3, "test border-box outerHeight(int) by roundtripping" ); equal( el_bb.outerHeight( 118, false ).height(), expected + 4, "test border-box outerHeight(int, false) by roundtripping" ); equal( el_bb.outerHeight( 129, true ).height(), expected + 5, "test border-box innerHeight(int, true) by roundtripping" ); equal( el.width( 101 ).width(), expected + 1, "test border-box width(int) by roundtripping" ); equal( el.innerWidth( 108 ).width(), expected + 2, "test border-box innerWidth(int) by roundtripping" ); equal( el.outerWidth( 117 ).width(), expected + 3, "test border-box outerWidth(int) by roundtripping" ); equal( el.outerWidth( 118, false ).width(), expected + 4, "test border-box outerWidth(int, false) by roundtripping" ); equal( el.outerWidth( 129, true ).width(), expected + 5, "test border-box innerWidth(int, true) by roundtripping" ); equal( el.height( 101 ).height(), expected + 1, "test border-box height(int) by roundtripping" ); equal( el.innerHeight( 108 ).height(), expected + 2, "test border-box innerHeight(int) by roundtripping" ); equal( el.outerHeight( 117 ).height(), expected + 3, "test border-box outerHeight(int) by roundtripping" ); equal( el.outerHeight( 118, false ).height(), expected + 4, "test border-box outerHeight(int, false) by roundtripping" ); equal( el.outerHeight( 129, true ).height(), expected + 5, "test border-box innerHeight(int, true) by roundtripping" ); }); testIframe( "dimensions/documentSmall", "window vs. small document", function( eQuery, window, document ) { // this test is practically tautological, but there is a bug in IE8 // with no simple workaround, so this test exposes the bug and works around it if ( document.body.offsetWidth >= document.documentElement.offsetWidth ) { expect( 2 ); equal( eQuery( document ).height(), eQuery( window ).height(), "document height matches window height" ); equal( eQuery( document ).width(), eQuery( window ).width(), "document width matches window width" ); } else { // all tests should have at least one assertion expect( 1 ); ok( true, "skipping test (conditions not satisfied)" ); } }); testIframe( "dimensions/documentLarge", "window vs. large document", function( eQuery, window, document ) { expect(2); ok( eQuery( document ).height() > eQuery( window ).height(), "document height is larger than window height" ); ok( eQuery( document ).width() > eQuery( window ).width(), "document width is larger than window width" ); }); }
/** * Created by Vicky on 6/9/2017. */ function getBill(input) { let purchases = []; let price = 0; for(let i=0; i<input.length; i+=2){ purchases.push(input[i]); price += Number(input[i+1]); } console.log(`You purchased ${purchases.join(', ')} for a total sum of ${price}`); }
self.__precacheManifest = [ { "revision": "0db62ce630b66cc38127", "url": "static/js/app.5b3cf63c.chunk.js" }, { "revision": "968dd11ad1a0a4cf3e70", "url": "static/js/runtime~app.57f5bbf7.js" }, { "revision": "060a0afd215144e7b7cb", "url": "static/js/2.b68e9907.chunk.js" }, { "revision": "a78e4b51bf5dd2e05c7453e1b5194d45", "url": "static/media/icon.a78e4b51.png" }, { "revision": "6165c9d7a2e729ba57b23dd93add5366", "url": "static/media/back-icon-mask.6165c9d7.png" }, { "revision": "7a7bc7ead25db795e58b336f04d2624c", "url": "favicon.ico" }, { "revision": "48c7ed4e7da9792af288a60d7242d615", "url": "expo-service-worker.js" }, { "revision": "d0c694b562b2208635f250762cd7fc79", "url": "serve.json" }, { "revision": "939c5b5a66b790a0d0ee43c180cbbe1c", "url": "manifest.json" }, { "revision": "3e3a90f2b3e255edd2df8c9e8b14e98e", "url": "index.html" }, { "revision": "7e58407cb31f65b195e69c72f53b58f6", "url": "static/js/runtime~app.57f5bbf7.js.gz" }, { "revision": "16709f23227d220b53e235a942bf292c", "url": "expo-service-worker.js.gz" }, { "revision": "98d2b7605d92932770ecf838dab3e4f2", "url": "static/js/app.5b3cf63c.chunk.js.gz" }, { "revision": "e6ab4a5b00d9524c47eb1ea8e9d914a8", "url": "static/js/2.b68e9907.chunk.js.gz" } ];
var searchData= [ ['adddiscriminators',['AddDiscriminators',['../PassSequence_8h.html#a0133cfbd4caf7074a0e24c6958e40cf5a6697a940304ba73825979a1f45258d14',1,'PassSequence.h']]], ['aggressive',['Aggressive',['../PassSequence_8h.html#a43f71430e3b7055e1ce934fd6fba4c28a227598607ef691b05c9eb1ea73a06a2f',1,'PassSequence.h']]], ['aggressivedce',['AggressiveDCE',['../PassSequence_8h.html#a0133cfbd4caf7074a0e24c6958e40cf5a28a8ba97dd8730b3b3243562d2173819',1,'PassSequence.h']]], ['alignmentfromassumptions',['AlignmentFromAssumptions',['../PassSequence_8h.html#a0133cfbd4caf7074a0e24c6958e40cf5aa2596c509790d24bfc5127b1ee650824',1,'PassSequence.h']]] ];
const debug = require('debug')('choo-cli:utils') const store = require('mem-fs').create() const xfs = require('mem-fs-editor').create(store) const { kebabCase, camelCase } = require('lodash') const { parse } = require('espree') const exec = require('./exec') const path = require('path') const once = require('ramda').once const walkBack = require('walk-back') const chalk = require('chalk') const delim = (require('os').platform() === 'win32') ? '\\' : '/' const message = msg => console.log(msg) const cwd = process.cwd() const resolvePath = path.resolve const newProjectPath = (projectName) => (dir) => resolvePath(cwd, projectName, dir || '') const findConfig = once(() => walkBack(process.cwd(), 'choo.yaml')) const findRootPath = once(() => { if (process.env.PROJECT_PATH) { return process.env.PROJECT_PATH } else { if (findConfig()) { return findConfig().split(delim).slice(0, -1).join(delim) } else { throw new Error('cannot find choo.yaml from ' + cwd) } } }) const destinationPath = (dir) => resolvePath(findRootPath(), dir || '') const npmInstall = process.env.NODE_ENV === 'test' ? () => { } : () => process.nextTick(() => { exec('npm', ['install', '-s'], { cwd: destinationPath() }) }) const yarnInstall = process.env.NODE_ENV === 'test' ? () => { } : () => process.nextTick(() => { exec('yarn', ['install'], { cwd: destinationPath() }) }) const install = (method) => method === 'yarn' ? yarnInstall : npmInstall const generate = (templatePath, category, props) => { const extName = path.extname(templatePath) const fileName = `${kebabCase(props.name)}${extName}` const targetPath = resolvePath(findRootPath(), props.path || category) const dest = destinationPath(`${targetPath}/${fileName}`) xfs.copyTpl(`${templatePath}`, dest, props) debug('generate', {templatePath, category, props}) xfs.commit(() => { message(`${chalk.green.bold('generate')} ${chalk.white.bold(dest)}`) }) } const isFuncNameValid = (name) => { try { parse(`function ${camelCase(name)} () {}`) return true } catch (e) { console.warn(e) return false } } module.exports = { xfs, cwd, message, generate, npmInstall, yarnInstall, install, findConfig, findRootPath, newProjectPath, isFuncNameValid, destinationPath }
define([ 'app' ], function( app ) { 'use strict'; var Router = Backbone.Router.extend({ editDevice: function(model) { console.log('edit', model.toJSON()); } }); return Router; });
var findEmbeded= require('./findEmbeded'); var ObjectID= require('mongodb').ObjectID; module.exports= function (modelName,obj,embeded,embedParentId) { var db = require( '../db' ).getDb(); if(!embedParentId) { throw {err:"Embeded Parent ID required"}; } obj= obj.map(function (val) { val._id= new ObjectID(); return val; }); var createObj={}; createObj[modelName]={}; createObj[modelName]['$each']=obj; return db.collection(embeded) .updateMany( { _id : embedParentId }, { $push : createObj } ) .then(function () { return obj; }); }
var chai = require('chai') var assert = chai.assert; var sinon = require('sinon'); var Ball = require("../lib/ball") var Club = require("../lib/club") describe('Checking ball direction', function(){ it("goes in the right direction", function(){ var clubX = 1 var clubY = 1 var ballX = 5 var ballY = 5 var ball = new Ball({x: ballX, y: ballY, radius: 6}) var club = new Club(0, ball, clubX, clubY); var slopeDeets = club.clubToBallSlope({x: clubX, y: clubY}); assert(slopeDeets.bothSlope > 0, 'the slope is ' + slopeDeets.bothSlope); assert(ball.xSpeed > 0, 'xSpeed less than zero') }) it("direction reverts to positive after stop", sinon.test(function(){ var clubX = 1 var clubY = 1 var ballX = 5 var ballY = 5 var ball = new Ball({x: ballX, y: ballY, radius: 6}) var club = new Club(0, ball, clubX, clubY); ball.xSpeed = -.01 ball.ySpeed = -.01 sinon.stub(ball, "collisionCheck"); ball.move() // at the end of the move function the ball should encounter stopCheck which should flip direction back to positive assert(ball.xSpeed > 0, "ball x speed less than 0") assert(ball.ySpeed > 0, "ball y speed less than 0") })) })
export const db = state => state.db.db export const api = state => state.api.api export const settings = state => state.settings.settings export const notifications = state => state.notification.bucket export const routes = state => state.router.links
import {Home} from './containers' import React from 'react' import {render} from 'react-dom' let a = 10; const fn = ()=> {}; render(<Home />,gitdocument.querySelector('#app'));
version https://git-lfs.github.com/spec/v1 oid sha256:b37dd247efcfc559121d953db8b1c665c120b98f3eb53a6a2ff5da75fb90479e size 524
describe('ICMS Próprio', function(){ require('./helper.js').cookies(); beforeEach(function(){ browser.get(browser.params.BASE_CALC_URL + 'calculoicms'); element(by.id('btnProprio')).click(); }) describe('Testes Relacionados a comportamentos do modal', function(){ it('Verifica se o nome do modal é correspondente com o seu cálculo.', function(){ browser.sleep(1000); expect($('.modal-header').$('.modal-title').getText()).toEqual("ICMS Próprio"); }) it('Verifica se ao clicar no x dentro do modal, o mesmo irá se fechar!', function(){ browser.sleep(1000); element(by.id('xIcmsProprio')).click(); browser.sleep(1000); expect(element(by.id('icmsProprioModal')).isDisplayed()).toBe(false); }) it('Verifica se ao apertar Esc, o modal irá se fechar.', function(){ browser.sleep(1000); browser.actions().sendKeys(protractor.Key.ESCAPE).perform(); browser.sleep(1000); expect(element(by.id('icmsProprioModal')).isDisplayed()).toBe(false); }) it('Verifica se ao clicar fora do modal, o mesmo irá se fechar', function(){ browser.sleep(1000); browser.actions().mouseMove(element(by.id('idContato'))).click().perform(); browser.sleep(1000); expect(element(by.id('icmsProprioModal')).isDisplayed()).toBe(false); }) }) describe('Testes Relacionados a validação dos inputs e buttons dentro do modal', function(){ it('Informa um valor no campo Base Cálculo e verifica se irá ser exibido a mensagem de valor inválido.', function(){ browser.sleep(1000); element(by.id('baseIcmsProprio')).sendKeys(101); expect(element(by.id('spanBaseIcmsProprio')).isDisplayed()).toBe(false); element(by.id('baseIcmsProprio')).clear().sendKeys(1); expect(element(by.id('spanBaseIcmsProprio')).isDisplayed()).toBe(false); element(by.id('baseIcmsProprio')).clear().sendKeys(0); expect(element(by.id('spanBaseIcmsProprio')).isDisplayed()).toBe(true); element(by.id('baseIcmsProprio')).clear().sendKeys(-1); expect(element(by.id('spanBaseIcmsProprio')).isDisplayed()).toBe(true); }) it('Informa um valor no campo alíquota ICMS e verifica se irá ser exibido a mensagem de valor inválido.', function(){ browser.sleep(1000); element(by.id('aliqIcmsProprio')).sendKeys(101); expect(element(by.id('spanAliqIcmsProprio')).isDisplayed()).toBe(true); element(by.id('aliqIcmsProprio')).clear().sendKeys(100); expect(element(by.id('spanAliqIcmsProprio')).isDisplayed()).toBe(false); element(by.id('aliqIcmsProprio')).clear().sendKeys(1); expect(element(by.id('spanAliqIcmsProprio')).isDisplayed()).toBe(false); element(by.id('aliqIcmsProprio')).clear().sendKeys(0); expect(element(by.id('spanAliqIcmsProprio')).isDisplayed()).toBe(true); element(by.id('aliqIcmsProprio')).clear().sendKeys(-1); expect(element(by.id('spanAliqIcmsProprio')).isDisplayed()).toBe(true); }) it('Verifica se o botão de calcular estará habilitado ou não dependendo das condições do modal passadas.', function(){ browser.sleep(1000); element(by.id('baseIcmsProprio')).clear().sendKeys(1); element(by.id('aliqIcmsProprio')).clear().sendKeys(1); expect(element(by.id('btnIcmsProprio')).isEnabled()).toBe(true); element(by.id('baseIcmsProprio')).clear().sendKeys(1); element(by.id('aliqIcmsProprio')).clear(); expect(element(by.id('btnIcmsProprio')).isEnabled()).toBe(false); element(by.id('baseIcmsProprio')).clear(); element(by.id('aliqIcmsProprio')).clear().sendKeys(1); expect(element(by.id('btnIcmsProprio')).isEnabled()).toBe(false); }) it('Verifica se o valor padrão do resultado está pré-definido corretamente com o valor zerado em reais.', function(){ browser.sleep(1000); expect(element(by.id('resultIcmsProprio')).getText()).toEqual("R$0,00"); }) }) describe('Testes relacionados a validação dos cálculos feitos.', function(){ it('Realiza um cálculo com base 100 e alíquota 10 e verifica se o resultado exibido será o correto.', function(){ browser.sleep(1000); element(by.id('baseIcmsProprio')).sendKeys(100); element(by.id('aliqIcmsProprio')).clear().sendKeys(10); element(by.id('btnIcmsProprio')).click(); var _resultado = element(by.id('resultIcmsProprio')).getText(); expect(_resultado).toEqual("R$10,00"); }) }) describe('Testes relacionados ao panel de descriminação do cálculo.', function(){ it('Verifica se ao clicar no ícone de pergunta, o panel com a discriminação do cálculo irá ser mostrado.', function(){ browser.sleep(1000); element(by.id('discrimIcmsProprio')).click(); browser.sleep(1000); expect(element(by.id('discriminacao')).isDisplayed()).toBe(true); }) it('Verifica se o valor que estão nos inputs estão batendo com os valores dentro da discriminação.', function(){ browser.sleep(1000); element(by.id('baseIcmsProprio')).clear().sendKeys(100); element(by.id('aliqIcmsProprio')).clear().sendKeys(10); element(by.id('btnIcmsProprio')).click(); browser.sleep(1000); element(by.id('discrimIcmsProprio')).click(); browser.sleep(1000); expect(element(by.binding('ctrlIcmsProprio.valoresIcmsProprio.base')).getText()).toContain("R$100,000"); expect(element(by.binding('ctrlIcmsProprio.valoresIcmsProprio.aliquota')).getText()).toContain("10"); expect(element(by.binding('ctrlIcmsProprio.valoresIcmsProprio.valorDiscriminacao')).getText()).toContain("R$10,000"); }) it('Verifica se a forma de fechar a discriminação do cálculo usando o x ou clicando novamente no ícone de pergunta estão funcionando', function(){ browser.sleep(1000); element(by.id('discrimIcmsProprio')).click(); browser.sleep(1000); $('#icmsProprioModal #discriminacao .close').click(); browser.sleep(1000); expect(element(by.id('discriminacao')).isDisplayed()).toBe(false); browser.sleep(1000); element(by.id('discrimIcmsProprio')).click(); browser.sleep(1000); element(by.id('discrimIcmsProprio')).click(); browser.sleep(1000); expect(element(by.id('discriminacao')).isDisplayed()).toBe(false); }) }) describe('Testes relacionados aos buttons que ficam no final do modal.', function(){ it('Verifica se o botão de limpar está funcionando corretamente.', function(){ browser.sleep(1000); element(by.id('baseIcmsProprio')).clear().sendKeys(1); element(by.id('aliqIcmsProprio')).clear().sendKeys(1); element(by.id('btnLimparIcmsProprio')).click(); expect(element(by.id('baseIcmsProprio')).getText()).toBe(''); expect(element(by.id('aliqIcmsProprio')).getText()).toBe(''); }) it('Verifica se o botão de fechar que fica no final da janela está funcionando corretamente', function(){ browser.sleep(1000); element(by.id('btnFecharModalIcmsProprio')).click(); browser.sleep(1000); expect(element(by.id('discriminacao')).isDisplayed()).toBe(false); }) }) })
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import babel from 'rollup-plugin-babel'; import uglify from 'rollup-plugin-uglify'; export default { input: 'src/jdlx-scraper.js', output: { file: 'dist/jdlx-scraper.js', format: 'umd', name: 'jdlx-scraper' }, plugins: [ babel({ exclude: 'node_modules/**', plugins: ["external-helpers"] }) ], watch: { include: 'src/**' } };
//Autogenerated by ../../build_app.js import audit_event from 'ember-fhir-adapter/serializers/audit-event'; export default audit_event;
'use strict'; // Parse the specified blob and pass an object of metadata to the // metadataCallback, or invoke the errorCallback with an error message. function parseAudioMetadata(blob, metadataCallback, errorCallback) { var filename = blob.name; // If blob.name exists, it should be an audio file from system // otherwise it should be an audio blob that probably from network/process // we can still parse it but we don't need to care about the filename if (filename) { // If the file is in the DCIM/ directory and has a .3gp extension // then it is a video, not a music file and we ignore it if (filename.slice(0, 5) === 'DCIM/' && filename.slice(-4).toLowerCase() === '.3gp') { errorCallback('skipping 3gp video file'); return; } // If the file has a .m4v extension then it is almost certainly a video. // Device Storage should not even return these files to us: // see https://bugzilla.mozilla.org/show_bug.cgi?id=826024 if (filename.slice(-4).toLowerCase() === '.m4v') { errorCallback('skipping m4v video file'); return; } } // If the file is too small to be a music file then ignore it if (blob.size < 128) { errorCallback('file is empty or too small'); return; } // These are the property names we use in the returned metadata object var TITLE = 'title'; var ARTIST = 'artist'; var ALBUM = 'album'; var TRACKNUM = 'tracknum'; var IMAGE = 'picture'; // These two properties are for playlist functionalities // not originally metadata from the files var RATED = 'rated'; var PLAYED = 'played'; // Map id3v2 tag ids to metadata property names var ID3V2TAGS = { TIT2: TITLE, TT2: TITLE, TPE1: ARTIST, TP1: ARTIST, TALB: ALBUM, TAL: ALBUM, TRCK: TRACKNUM, TRK: TRACKNUM, APIC: IMAGE, PIC: IMAGE }; // Map ogg tagnames to metadata property names var OGGTAGS = { title: TITLE, artist: ARTIST, album: ALBUM, tracknumber: TRACKNUM }; // Map MP4 atom names to metadata property names var MP4TAGS = { '\xa9alb': ALBUM, '\xa9art': ARTIST, '\xa9ART': ARTIST, 'aART': ARTIST, '\xa9nam': TITLE, 'trkn': TRACKNUM, 'covr': IMAGE }; // These are 'ftyp' values that we recognize // See http://www.mp4ra.org/filetype.html // Also see gecko code in /toolkit/components/mediasniffer/nsMediaSniffer.cpp // Gaia will accept the supported compatible brands in gecko as well var MP4Types = { 'M4A ' : true, // iTunes audio. Note space in property name. 'M4B ' : true, // iTunes audio book. Note space. 'mp41' : true, // MP4 version 1 'mp42' : true, // MP4 version 2 'isom' : true, // ISO base media file format, version 1 'iso2' : true // ISO base media file format, version 2 }; // MP4 and 3GP containers both use ISO base media file format. // Also see what audio codecs/formats are supported in 3GPP specification. // Format information: // https://en.wikipedia.org/wiki/ISO_base_media_file_format // http://tools.ietf.org/html/rfc6381 // http://www.3gpp.org/ftp/Specs/html-info/26244.htm // var MP4Codecs = { 'mp4a' : true, // MPEG-4 audio 'samr' : true, // AMR narrow-band speech 'sawb' : true, // AMR wide-band speech 'sawp' : true // Extended AMR wide-band audio }; // Start off with some default metadata var metadata = {}; metadata[ARTIST] = metadata[ALBUM] = metadata[TITLE] = ''; metadata[RATED] = metadata[PLAYED] = 0; // If the blob has a name, use that as a default title in case // we can't find one in the file if (filename) { var p1 = filename.lastIndexOf('/'); var p2 = filename.lastIndexOf('.'); if (p2 === -1) p2 = filename.length; metadata[TITLE] = filename.substring(p1 + 1, p2); } // Read the start of the file, figure out what kind it is, and call // the appropriate parser. Start off with an 64kb chunk of data. // If the metadata is in that initial chunk we won't have to read again. var headersize = Math.min(64 * 1024, blob.size); BlobView.get(blob, 0, headersize, function(header, error) { if (error) { errorCallback(error); return; } try { var magic = header.getASCIIText(0, 12); if (magic.substring(0, 9) === 'LOCKED 1 ') { handleLockedFile(blob); return; } if (magic.substring(0, 3) === 'ID3') { // parse ID3v2 tags in an MP3 file parseID3v2Metadata(header); } else if (magic.substring(0, 4) === 'OggS') { // parse metadata from an Ogg Vorbis file parseOggMetadata(header); } else if (magic.substring(4, 8) === 'ftyp') { // This is an MP4 file if (checkMP4Type(header, MP4Types)) { // It is a type of MP4 file that we support parseMP4Metadata(header); } else { // The MP4 file might be a video or it might be some // kind of audio that we don't support. We used to treat // files like these as unknown files and see (in the code below) // whether the <audio> tag could play them. But we never parsed // metadata from them, so even if playable, we didn't have a title. // And, the <audio> tag was treating videos as playable. errorCallback('Unknown MP4 file type'); } } else if ((header.getUint16(0, false) & 0xFFFE) === 0xFFFA) { // If this looks like an MP3 file, then look for ID3v1 metadata // tags at the end of the file. But even if there is no metadata // treat this as a playable file. BlobView.get(blob, blob.size - 128, 128, function(footer, error) { if (error) { errorCallback(error); return; } try { var magic = footer.getASCIIText(0, 3); if (magic === 'TAG') { // It is an MP3 file with ID3v1 tags parseID3v1Metadata(footer); } else { // It is an MP3 file with no metadata. We return the default // metadata object that just contains the filename as the title metadataCallback(metadata); } } catch (e) { errorCallback(e); } }); } else { // This is some kind of file that we don't know about. // Let's see if we can play it. var player = new Audio(); player.mozAudioChannelType = 'content'; var canplay = blob.type && player.canPlayType(blob.type); if (canplay === 'probably') { metadataCallback(metadata); } else { var url = URL.createObjectURL(blob); player.src = url; player.onerror = function() { URL.revokeObjectURL(url); player.removeAttribute('src'); player.load(); errorCallback('Unplayable music file'); }; player.oncanplay = function() { URL.revokeObjectURL(url); player.removeAttribute('src'); player.load(); metadataCallback(metadata); }; } } } catch (e) { console.error('parseAudioMetadata:', e, e.stack); errorCallback(e); } }); // // Parse ID3v1 metadata from the 128 bytes footer at the end of a file. // Metadata includes title, artist, album and possibly the track number. // Year, comment and genre are ignored. // // Format information: // http://www.id3.org/ID3v1 // http://en.wikipedia.org/wiki/ID3 // function parseID3v1Metadata(footer) { var title = footer.getASCIIText(3, 30); var artist = footer.getASCIIText(33, 30); var album = footer.getASCIIText(63, 30); var p = title.indexOf('\0'); if (p !== -1) title = title.substring(0, p); p = artist.indexOf('\0'); if (p !== -1) artist = artist.substring(0, p); p = album.indexOf('\0'); if (p !== -1) album = album.substring(0, p); metadata[TITLE] = title || undefined; metadata[ARTIST] = artist || undefined; metadata[ALBUM] = album || undefined; var b1 = footer.getUint8(125); var b2 = footer.getUint8(126); if (b1 === 0 && b2 !== 0) metadata[TRACKNUM] = b2; metadataCallback(metadata); } // // Format information: // http://www.id3.org/id3v2.3.0 // http://phoxis.org/2010/05/08/what-are-id3-tags-all-about/ // https://github.com/aadsm/JavaScript-ID3-Reader/ // function parseID3v2Metadata(header) { // First three bytes are "ID3" or we wouldn't be here header.index = 3; var id3version = header.readUnsignedByte(); if (id3version > 4) { console.warn('mp3 file with unknown metadata version'); metadataCallback(metadata); return; } var id3revision = header.readUnsignedByte(); var id3flags = header.readUnsignedByte(); var needs_unsynchronization = ((id3flags & 0x80) !== 0); var has_extended_header = ((id3flags & 0x40) !== 0); var length = header.readID3Uint28BE(); // XXX // For now, we just punt if unsynchronization is required. // That's what the old metadata parser did, too. // I don't think it is very common in mp3 files today. if (needs_unsynchronization) { console.warn('mp3 file uses unsynchronization. Can\'t read metadata'); metadataCallback(metadata); return; } // Get the entire ID3 data block and pass it to parseID3() // May be async, or sync, depending on whether we read enough // bytes when we read the header header.getMore(header.index, length, parseID3); function parseID3(id3) { // skip the extended header, if there is one if (has_extended_header) { id3.advance(id3.readUnsignedInt()); } // Now we have a series of frames, each of which is one ID3 tag while (id3.index < id3.byteLength) { var tagid, tagsize, tagflags; // If there is a null byte here, then we've found padding // and we're done if (id3.getUint8(id3.index) === 0) break; switch (id3version) { case 2: tagid = id3.readASCIIText(3); tagsize = id3.readUint24(); tagflags = 0; break; case 3: tagid = id3.readASCIIText(4); tagsize = id3.readUnsignedInt(); tagflags = id3.readUnsignedShort(); break; case 4: tagid = id3.readASCIIText(4); tagsize = id3.readID3Uint28BE(); tagflags = id3.readUnsignedShort(); break; } var nexttag = id3.index + tagsize; var tagname = ID3V2TAGS[tagid]; // Skip tags we don't care about if (!tagname) { id3.index = nexttag; continue; } // Skip compressed, encrypted, grouped, or synchronized tags that // we can't decode if ((tagflags & 0xFF) !== 0) { console.warn('Skipping', tagid, 'tag with flags', tagflags); id3.index = nexttag; continue; } // Wrap it in try so we don't crash the whole thing on one bad tag try { // Now get the tag value var tagvalue = null; switch (tagid) { case 'TIT2': case 'TT2': case 'TPE1': case 'TP1': case 'TALB': case 'TAL': tagvalue = readText(id3, tagsize); break; case 'TRCK': case 'TRK': tagvalue = parseInt(readText(id3, tagsize)); break; case 'APIC': case 'PIC': tagvalue = readPic(id3, tagsize, tagid); break; } if (tagvalue !== null) metadata[tagname] = tagvalue; } catch (e) { console.warn('Error parsing mp3 metadata tag', tagid, ':', e); } // Make sure we're at the start of the next tag before continuing id3.index = nexttag; } handleCoverArt(metadata); } function readPic(view, size, id) { var start = view.index; var encoding = view.readUnsignedByte(); var mimetype; // mimetype is different for old PIC tags and new APIC tags if (id === 'PIC') { mimetype = view.readASCIIText(3); if (mimetype === 'JPG') mimetype = 'image/jpeg'; else if (mimetype === 'PNG') mimetype = 'image/png'; } else { mimetype = view.readNullTerminatedLatin1Text(size - 1); } // We ignore these next two fields var kind = view.readUnsignedByte(); var desc = readText(view, size - (view.index - start), encoding); var picstart = view.sliceOffset + view.viewOffset + view.index; var piclength = size - (view.index - start); // Now return an object that specifies where to pull the image from // The properties of this object can be passed to blob.slice() return { start: picstart, end: picstart + piclength, type: mimetype }; } function readText(view, size, encoding) { if (encoding === undefined) { encoding = view.readUnsignedByte(); size = size - 1; } switch (encoding) { case 0: return view.readNullTerminatedLatin1Text(size); case 1: return view.readNullTerminatedUTF16Text(size, undefined); case 2: return view.readNullTerminatedUTF16Text(size, false); case 3: return view.readNullTerminatedUTF8Text(size); default: throw Error('unknown text encoding'); } } } // // Format information: // http://en.wikipedia.org/wiki/Ogg // http://xiph.org/vorbis/doc/Vorbis_I_spec.html // http://www.xiph.org/vorbis/doc/v-comment.html // http://wiki.xiph.org/VorbisComment // http://tools.ietf.org/html/draft-ietf-codec-oggopus-00 // function parseOggMetadata(header) { function sum(x, y) { return x + y; } // for Array.reduce() below // Ogg metadata is in the second header packet. We need to read // the first packet to find the start of the second. var p1_num_segments = header.getUint8(26); var p1_segment_lengths = header.getUnsignedByteArray(27, p1_num_segments); var p1_length = Array.reduce(p1_segment_lengths, sum, 0); var p2_header = 27 + p1_num_segments + p1_length; var p2_num_segments = header.getUint8(p2_header + 26); var p2_segment_lengths = header.getUnsignedByteArray(p2_header + 27, p2_num_segments); var p2_length = Array.reduce(p2_segment_lengths, sum, 0); var p2_offset = p2_header + 27 + p2_num_segments; // Now go fetch page 2 header.getMore(p2_offset, p2_length, function(page, error) { if (error) { errorCallback(error); return; } // Look for a comment packet from a supported codec var first_byte = page.readByte(); var valid = false; switch (first_byte) { case 3: valid = page.readASCIIText(6) === 'vorbis'; break; case 79: valid = page.readASCIIText(7) === 'pusTags'; break; } if (!valid) { errorCallback('malformed ogg comment packet'); return; } var vendor_string_length = page.readUnsignedInt(true); page.advance(vendor_string_length); // skip libvorbis vendor string var num_comments = page.readUnsignedInt(true); // |metadata| already has some of its values filled in (namely the title // field). To make sure we overwrite the pre-filled metadata, but also // append any repeated fields from the file, we keep track of the fields // we've seen in the file separately. var seen_fields = {}; for (var i = 0; i < num_comments; i++) { if (page.remaining() < 4) { // 4 bytes for comment-length variable // TODO: handle metadata that uses multiple pages break; } var comment_length = page.readUnsignedInt(true); if (comment_length > page.remaining()) { // TODO: handle metadata that uses multiple pages break; } var comment = page.readUTF8Text(comment_length); var equal = comment.indexOf('='); if (equal !== -1) { var tag = comment.substring(0, equal).toLowerCase().replace(' ', ''); var propname = OGGTAGS[tag]; if (propname) { // Do we care about this tag? var value = comment.substring(equal + 1); if (seen_fields.hasOwnProperty(propname)) { // If we already have a value, append this new one. metadata[propname] += ' ' + value; } else { // Otherwise, just save the single value. metadata[propname] = value; seen_fields[propname] = true; } } // XXX // How do we do album art in ogg? // http://wiki.xiph.org/VorbisComment // http://flac.sourceforge.net/format.html#metadata_block_picture } } // We've read all the comments, so call the callback handleCoverArt(metadata); }); } // MP4 files use 'ftyp' to identify the type of encoding. // 'ftyp' information // http://www.ftyps.com/what.html function checkMP4Type(header, types) { // The major brand is the four bytes right after 'ftyp'. var majorbrand = header.getASCIIText(8, 4); if (majorbrand in types) { return true; } else { // Check the rest part for the compatible brands, // they are every four bytes after the version of major brand. // Usually there are two optional compatible brands, // but arbitrary number of other compatible brands are also acceptable, // so we will check all the compatible brands until the header ends. var index = 16; var size = header.getUint32(0); while (index < size) { var compatiblebrand = header.getASCIIText(index, 4); index += 4; if (compatiblebrand in types) return true; } return false; } } // // XXX: Need a special case for the track number atom? // // https://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap1/qtff1.html // http://en.wikipedia.org/wiki/MPEG-4_Part_14 // http://atomicparsley.sourceforge.net/mpeg-4files.html // function parseMP4Metadata(header) { // // XXX // I think I could probably restructure this somehow. The atoms or "boxes" // we're reading and parsing here for a tree that I need to traverse. // Maybe nextBox() and firstChildBox() functions would be helpful. // Or even make these methods of BlobView? Not sure if it is worth // the time to refactor, though... See also the approach in // shared/js/get_video_rotation.js // findMoovAtom(header); function findMoovAtom(atom) { try { var offset = atom.sliceOffset + atom.viewOffset; // position in blob var size = atom.readUnsignedInt(); var type = atom.readASCIIText(4); if (size === 0) { // A size of 0 means the rest of the file size = atom.blob.size - offset; } else if (size === 1) { // A size of 1 means the size is in bytes 8-15 size = atom.readUnsignedInt() * 4294967296 + atom.readUnsignedInt(); } if (type === 'moov') { // Get the full contents of this atom atom.getMore(offset, size, function(moov) { try { parseMoovAtom(moov, size); handleCoverArt(metadata); return; } catch (e) { errorCallback(e); } }); } else { // Otherwise, get the start of the next atom and recurse // to continue the search for the moov atom. // If we're reached the end of the blob without finding // anything, just call the metadata callback with no metadata if (offset + size + 16 <= atom.blob.size) { atom.getMore(offset + size, 16, findMoovAtom); } else { metadataCallback(metadata); } } } catch (e) { errorCallback(e); } } // Once we've found the moov atom, here's what we do with it. // This function, and the ones that follow are all synchronous. // We've read the entire moov atom, so we've got all the bytes // we need and don't have to do an async read again. function parseMoovAtom(data, end) { data.advance(8); // skip the size and type of this atom // Find the udta and trak atoms within the moov atom // There will only be one udta atom, but there may be multiple trak // atoms. In that case, this is probably a movie file and we'll reject // it when we find a track that is not an mp4 audio codec. while (data.index < end) { var size = data.readUnsignedInt(); var type = data.readASCIIText(4); var nextindex = data.index + size - 8; if (type === 'udta') { // Metadata is inside here parseUdtaAtom(data, end); data.index = nextindex; } else if (type === 'trak') { // We find the audio format inside here data.advance(-8); // skip back to beginning var mdia = findChildAtom(data, 'mdia'); if (mdia) { var minf = findChildAtom(mdia, 'minf'); if (minf) { var vmhd = searchChildAtom(minf, 'vmhd'); if (vmhd) throw 'Found video track in MP4 container'; var smhd = searchChildAtom(minf, 'smhd'); if (smhd) { var stbl = findChildAtom(minf, 'stbl'); if (stbl) { var stsd = findChildAtom(stbl, 'stsd'); if (stsd) { stsd.advance(20); var codec = stsd.readASCIIText(4); if (!(codec in MP4Codecs)) { throw 'Unsupported format in MP4 container: ' + codec; } } } } } } else { // There is no enough information for us to identify the MP4 throw 'Not enough metadata in MP4 container!'; } data.index = nextindex; } else { data.advance(size - 8); } } } function findChildAtom(data, atom) { var start = data.index; var length = data.readUnsignedInt(); data.advance(4); while (data.index < start + length) { var size = data.readUnsignedInt(); var type = data.readASCIIText(4); if (type === atom) { data.advance(-8); return data; } else { data.advance(size - 8); } } return null; // not found } // This function searches the child atom just like findChildAtom(). // But the internal pointer/index will be reset to the start // after the searching finishes. function searchChildAtom(data, atom) { var start = data.index; var target = findChildAtom(data, atom); data.index = start; return target; } function parseUdtaAtom(data, end) { // Find the meta atom within the udta atom while (data.index < end) { var size = data.readUnsignedInt(); var type = data.readASCIIText(4); if (type === 'meta') { parseMetaAtom(data, data.index + size - 8); data.index = end; return; } else { data.advance(size - 8); } } } function parseMetaAtom(data, end) { // The meta atom apparently has a slightly different structure. // Have to skip flag bytes before reading children atoms data.advance(4); // Find the ilst atom within the meta atom while (data.index < end) { var size = data.readUnsignedInt(); var type = data.readASCIIText(4); if (type === 'ilst') { parseIlstAtom(data, data.index + size - 8); data.index = end; return; } else { data.advance(size - 8); } } } function parseIlstAtom(data, end) { // Now read all child atoms of ilst, looking for metadata // we care about while (data.index < end) { var size = data.readUnsignedInt(); var type = data.readASCIIText(4); var next = data.index + size - 8; var tagname = MP4TAGS[type]; if (tagname) { try { var value = getMetadataValue(data, next, type); metadata[tagname] = value; } catch (e) { console.warn('skipping', type, ':', e); } } data.index = next; } } // Find the data atom and return its value or throw an error // We handle UTF-8 strings, numbers, and blobs function getMetadataValue(data, end, tagtype) { // Loop until we find a data atom while (data.index < end) { var size = data.readUnsignedInt(); var type = data.readASCIIText(4); if (type !== 'data') { data.advance(size - 8); continue; } // We've found the data atom. // Return its (first) value or throw an error. var datatype = data.readUnsignedInt() & 0xFFFFFF; data.advance(4); // Ignore locale var datasize = size - 16; // the rest of the atom is the value // Special case for track number if (tagtype === 'trkn') { data.advance(2); return data.readUnsignedShort(); } switch (datatype) { case 1: // utf8 text return data.readUTF8Text(datasize); case 13: // jpeg return { start: data.sliceOffset + data.viewOffset + data.index, end: data.sliceOffset + data.viewOffset + data.index + datasize, type: 'image/jpeg' }; case 14: // png return { start: data.sliceOffset + data.viewOffset + data.index, end: data.sliceOffset + data.viewOffset + data.index + datasize, type: 'image/png' }; default: throw Error('unexpected type in data atom'); } } throw Error('no data atom found'); } } // Before we call the metadataCallback, we create a thumbnail // for the song, if there is not already one cached. In the normal // (cache hit) case, this happens synchronously. function handleCoverArt(metadata) { var fileinfo = { name: blob.name, blob: blob, metadata: metadata }; // We call getThumbnailURL here even though we don't need the url yet. // We do it here to force the thumbnail to be cached now while // we know there is just going to be one file at a time. getThumbnailURL(fileinfo, function(url) { metadataCallback(metadata); }); } function handleLockedFile(locked) { ForwardLock.getKey(function(secret) { ForwardLock.unlockBlob(secret, locked, callback, errorCallback); function callback(unlocked, unlockedMetadata) { // Now that we have the unlocked content of the locked file, // convert it back to a blob and recurse to parse the metadata. // When we're done, add metadata to indicate that this is locked // content (so it isn't shared) and to specify the vendor that // locked it. parseAudioMetadata(unlocked, function(metadata) { metadata.locked = true; if (unlockedMetadata.vendor) metadata.vendor = unlockedMetadata.vendor; if (!metadata[TITLE]) metadata[TITLE] = unlockedMetadata.name; metadataCallback(metadata); }, errorCallback); } }); } } // When we generate our own thumbnails, aim for this size var THUMBNAIL_WIDTH = 300; var THUMBNAIL_HEIGHT = 300; var offscreenImage = new Image(); var thumbnailCache = {}; // maps keys to blob urls // Get a thumbnail image for the specified song (reading from the // cache if possible and storing to the cache if necessary) and pass a // blob URL for it it to the specified callback. fileinfo is an object // with metadata from the MediaDB. function getThumbnailURL(fileinfo, callback) { function cacheThumbnail(key, blob, url) { asyncStorage.setItem(key, blob); thumbnailCache[key] = url; } var metadata = fileinfo.metadata; // If the file doesn't have an embedded image, just pass null if (!metadata.picture) { callback(null); return; } // We cache thumbnails based on the song artist, album, and image size. // If there is no album name, we use the directory name instead. var key = 'thumbnail'; var album = metadata.album; var artist = metadata.artist; var size = metadata.picture.end - metadata.picture.start; if (album || artist) { key = 'thumbnail.' + album + '.' + artist + '.' + size; } else { key = 'thumbnail.' + (fileinfo.name || fileinfo.blob.name); } // If we have the thumbnail url locally, just call the callback var url = thumbnailCache[key]; if (url) { callback(url); return; } // Otherwise, see if we've saved a blob in asyncStorage asyncStorage.getItem(key, function(blob) { if (blob) { // If we get a blob, save the URL locally and return the url. var url = URL.createObjectURL(blob); thumbnailCache[key] = url; callback(url); return; } else { // Otherwise, create the thumbnail image createAndCacheThumbnail(); } }); function createAndCacheThumbnail() { if (fileinfo.blob) { // this can happen for the open activity getImage(fileinfo.blob); } else { // this is the normal case musicdb.getFile(fileinfo.name, function(file) { getImage(file); }); } function getImage(file) { // Get the embedded image from the music file var embedded = file.slice(metadata.picture.start, metadata.picture.end, metadata.picture.type); // Convert to a blob url var embeddedURL = URL.createObjectURL(embedded); // Load it into an image element offscreenImage.src = embeddedURL; offscreenImage.onerror = function() { URL.revokeObjectURL(embeddedURL); offscreenImage.removeAttribute('src'); // Something went wrong reading the embedded image. // Return a default one instead console.warn('Album cover art failed to load', file.name); callback(null); }; offscreenImage.onload = function() { // We've loaded the image, now copy it to a canvas var canvas = document.createElement('canvas'); canvas.width = THUMBNAIL_WIDTH; canvas.height = THUMBNAIL_HEIGHT; var context = canvas.getContext('2d'); var scalex = canvas.width / offscreenImage.width; var scaley = canvas.height / offscreenImage.height; // Take the larger of the two scales: we crop the image to the thumbnail var scale = Math.max(scalex, scaley); // If the image was already thumbnail size, it is its own thumbnail if (scale >= 1) { offscreenImage.removeAttribute('src'); cacheThumbnail(key, embedded, embeddedURL); callback(embeddedURL); return; } // Calculate the region of the image that will be copied to the // canvas to create the thumbnail var w = Math.round(THUMBNAIL_WIDTH / scale); var h = Math.round(THUMBNAIL_HEIGHT / scale); var x = Math.round((offscreenImage.width - w) / 2); var y = Math.round((offscreenImage.height - h) / 2); // Draw that region of the image into the canvas, scaling it down context.drawImage(offscreenImage, x, y, w, h, 0, 0, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT); // We're done with the image now offscreenImage.removeAttribute('src'); URL.revokeObjectURL(embeddedURL); canvas.toBlob(function(blob) { var url = URL.createObjectURL(blob); cacheThumbnail(key, blob, url); callback(url); }, 'image/jpeg'); }; } } }
'use strict'; const SetsBuilder = require('gemini-core').SetsBuilder; const DEFAULT_DIR = require('../package').name; exports.reveal = (sets, opts) => { return SetsBuilder .create(sets, {defaultDir: DEFAULT_DIR}) .useSets(opts.sets) .useFiles(opts.paths) .useBrowsers(opts.browsers) .build(process.cwd()) .then((setCollection) => setCollection.groupByBrowser()); };
app.factory('Rule', function () { var Rule = function (properties) { this.name = null; this.detection = 'CONTAINS'; this.url_fragment = null; this.tab = { title: null, icon: null, pinned: false, protected: false, unique: false, muted: false, title_matcher: null, url_matcher: null }; angular.extend(this, properties); }; Rule.prototype.setModel = function (obj) { angular.extend(this, obj); }; return Rule; });
/** * * You can modify and use this source freely * only for the development of application related Live2D. * * (c) Live2D Inc. All rights reserved. */ var MatrixStack = function () { }; MatrixStack.matrixStack = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]; MatrixStack.depth = 0; MatrixStack.currentMatrix = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]; MatrixStack.tmp = new Array(16); MatrixStack.reset = function () { this.depth = 0; } MatrixStack.loadIdentity = function () { for (var i = 0; i < 16; i++) { this.currentMatrix[i] = (i % 5 == 0) ? 1 : 0; } } MatrixStack.push = function () { var offset = this.depth * 16; var nextOffset = (this.depth + 1) * 16; if (this.matrixStack.length < nextOffset + 16) { this.matrixStack.length = nextOffset + 16; } for (var i = 0; i < 16; i++) { this.matrixStack[nextOffset + i] = this.currentMatrix[i]; } this.depth++; } MatrixStack.pop = function () { this.depth--; if (this.depth < 0) { myError("Invalid matrix stack."); this.depth = 0; } var offset = this.depth * 16; for (var i = 0; i < 16; i++) { this.currentMatrix[i] = this.matrixStack[offset + i]; } } MatrixStack.getMatrix = function () { return this.currentMatrix; } MatrixStack.multMatrix = function (matNew) { var i, j, k; for (i = 0; i < 16; i++) { this.tmp[i] = 0; } for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { for (k = 0; k < 4; k++) { this.tmp[i + j * 4] += this.currentMatrix[i + k * 4] * matNew[k + j * 4]; } } } for (i = 0; i < 16; i++) { this.currentMatrix[i] = this.tmp[i]; } }
const quilt = require('@quilt/quilt'); let infrastructure = require('../../config/infrastructure.js'); let deployment = quilt.createDeployment(); deployment.deploy(infrastructure); let containers = new quilt.Service('containers', new quilt.Container('google/pause').replicate(infrastructure.nWorker)); deployment.deploy(containers);
// Copyright 2013 The Obvious Corporation. /** * @fileoverview Helpers made available via require('phantomjs') once package is * installed. */ var fs = require('fs') var path = require('path') /** * Where the phantom binary can be found. * @type {string} */ try { var location = require('./location') exports.path = path.resolve(__dirname, location.location) exports.platform = location.platform exports.arch = location.arch } catch(e) { // Must be running inside install script. exports.path = null } /** * The version of phantomjs installed by this package. * @type {number} */ exports.version = '1.9.8' /** * Returns a clean path that helps avoid `which` finding bin files installed * by NPM for this repo. * @param {string} path * @return {string} */ exports.cleanPath = function (path) { return path .replace(/:[^:]*node_modules[^:]*/g, '') .replace(/(^|:)\.\/bin(\:|$)/g, ':') .replace(/^:+/, '') .replace(/:+$/, '') } // Make sure the binary is executable. For some reason doing this inside // install does not work correctly, likely due to some NPM step. if (exports.path) { try { // avoid touching the binary if it's already got the correct permissions var st = fs.statSync(exports.path); var mode = st.mode | parseInt("0555", 8); if (mode !== st.mode) { fs.chmodSync(exports.path, mode); } } catch (e) { // Just ignore error if we don't have permission. // We did our best. Likely because phantomjs was already installed. } }
/** * Angular Module relying on Apache Cordova Contacts Plugin (cordova plugin add org.apache.cordova.contacts). */ var cordovaContactsModule = angular.module('cordovaContactsModule', []); // Constants /** * Constants service used in the whole module. */ cordovaContactsModule.constant('cordovaContactsConstants', { apiVersion: '1.0.0', cordovaVersion: '>=3.4.0' }); // Services /** * Main service relying on Apache Cordova Contacts Plugin. */ cordovaContactsModule.factory('cordovaContactsService', ['$rootScope', '$log', 'cordovaContactsConstants', function ($rootScope, $log, cordovaContactsConstants) { return { /** * Return the current API version. */ apiVersion: function () { $log.debug('cordovaContactsService.apiVersion.'); return cordovaContactsConstants.apiVersion; }, /** * Return the cordova API version. */ cordovaVersion: function () { $log.debug('cordovaContactsService.cordovaVersion.'); return cordovaContactsConstants.cordovaVersion; }, /** * Check the Contacts plugin availability. * @returns {boolean} */ checkContactsAvailability: function () { $log.debug('cordovaContactsService.checkContactsAvailability.'); if (!navigator.contacts) { $log.warn('Contacts API is not available.'); return false; } return true; }, /** * The navigator.contacts.create method is synchronous, and returns a new Contact object. * For more information: https://github.com/apache/cordova-plugin-contacts/blob/dev/doc/index.md#navigatorcontactscreate */ create: function (contactInfo) { $log.debug('cordovaContactsService.create.'); // Checking API availability if (!this.checkContactsAvailability()) { return null; } // API call return navigator.contacts.create(contactInfo); }, /** * The navigator.contacts.find method executes asynchronously, querying the device contacts database and returning an array of Contact objects. * For more information: https://github.com/apache/cordova-plugin-contacts/blob/dev/doc/index.md#navigatorcontactsfind */ find: function (fields, successCallback, errorCallback, options) { $log.debug('cordovaContactsService.find.'); // Checking API availability if (!this.checkContactsAvailability()) { return; } // API call navigator.contacts.find( fields, function (contacts) { $rootScope.$apply(successCallback(contacts)); }, function (error) { $rootScope.$apply(errorCallback(error)); }, options ); }, /** * Saves a new contact to the device contacts database, or updates an existing contact if a contact with the same id already exists. * For more information: https://github.com/apache/cordova-plugin-contacts/blob/dev/doc/index.md#contact */ save: function (contact, successCallback, errorCallback) { $log.debug('cordovaContactsService.save.'); // Checking API availability if (!this.checkContactsAvailability()) { return; } // API call contact.save( function (contact) { $rootScope.$apply(successCallback(contact)); }, function (error) { $rootScope.$apply(errorCallback(error)); } ); }, /** * Removes the contact from the device contacts database, otherwise executes an error callback with a ContactError object. * For more information: https://github.com/apache/cordova-plugin-contacts/blob/dev/doc/index.md#contact */ remove: function (contact, successCallback, errorCallback) { $log.debug('cordovaContactsService.remove.'); // Checking API availability if (!this.checkContactsAvailability()) { return; } // API call contact.remove( function () { $rootScope.$apply(successCallback()); }, function (error) { $rootScope.$apply(errorCallback(error)); } ); }, /** * Returns a new Contact object that is a deep copy of the calling object, with the id property set to null. * For more information: https://github.com/apache/cordova-plugin-contacts/blob/dev/doc/index.md#contact */ clone: function (contact) { $log.debug('cordovaContactsService.clone.'); // Checking API availability if (!this.checkContactsAvailability()) { return null; } // API call return contact.clone(); } }; }]);
/** * Include files into other files, optional base64 encoding. * * @link https://github.com/Sjeiti/grunt-include-file * ----------------------------------------------------------------------------- * * Configured to include pregenerated absalign classes in the Javascript * polyfill. * */ module.exports = { dist: { cwd: 'src/', src: ['absalign.js'], dest: 'dist/' } };
import { expect } from 'chai' import { shallow, render, mount } from 'enzyme' import React from 'react' import Header from '../../src/components/Header' describe('Header', () => { it('should render a Header', () => { const wrapper = shallow(React.createElement(Header)) expect(wrapper.find('header')).to.have.length(1) expect(wrapper.find('h1')).to.have.length(1) }) })
// http://css-tricks.com/snippets/javascript/htmlentities-for-javascript/ /* function htmlEntities(str) { return String(str) .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;'); } function createCodeNode(codeStr) { var node, code; node = document.createElement('pre'); code = document.createElement('code'); // TODO: Detect language node.setAttribute('class', 'pttr-section-code, language-html'); code.innerHTML = codeStr; node.appendChild(code); return node; } var previews = document.querySelectorAll('.show-code .pttr-section-preview'); for (var i = 0; i < previews.length; i++) { var codeStr = htmlEntities(previews[i].innerHTML); var node = createCodeNode(codeStr); previews[i].parentNode.appendChild(node); } */ // Do da highlighting //Prism.highlightAll();
import React, { Component } from 'react'; import PropTypes from 'prop-types'; class ConusStations extends Component { static propTypes = { onModal: PropTypes.func.isRequired }; render() { const { onModal } = this.props; return ( <div className="c-conus-stations"> <button className="c-new-button -light -transparent -compressed -fullwidth" type="button" onClick={onModal} > View threshold exceedance </button> </div> ); } } export default ConusStations;
import Predicate from './Predicate'; import Template from '../server/Template'; export default class NeqPredicate extends Predicate { constructor(opts) { const {lh, rh} = opts; super(opts); this._lh = new Template(lh); this._rh = new Template(rh); } test(data) { const lh = this._lh.render(data), rh = this._rh.render(data); return lh != rh; } }
var webpack = require('webpack'); var path = require('path'); module.exports = { entry: './index.js', output: { path: path.join(__dirname, 'dist'), filename: 'waterwheel.js' }, plugins: [ new webpack.optimize.UglifyJsPlugin({ sourceMap: false, compress: { warnings: false } }) ], module: { loaders: [ { test: /\.js?$/, exclude: /node_modules/, loaders: ['babel?cacheDirectory&presets[]=es2015'] }, { test: /\.json?$/, loader: 'json' } ] } };
module.exports = function (sails) { /** * Module dependencies. */ var util = require( '../../util' ); /** * Global access to middleware * (useful as helpers) */ sails._mixinLocals = _mixinLocals; sails._mixinResError = _mixinResError; sails._mixinServerMetadata = _mixinServerMetadata; sails._mixinReqQualifiers = _mixinReqQualifiers; /** * Extend middleware req/res for this route w/ new methods / qualifiers. */ return { /** * Bind req/res syntactic sugar before apply any app-level routes */ initialize: function (cb) { var self = this; sails.on('router:before', function () { sails.router.bind('/*', function addSugarMethods (req, res, next) { _mixinLocals(req,res); _mixinResError(req,res); _mixinServerMetadata(req,res); // Only apply HTTP middleware if it makes sense // (i.e. if this is an HTTP request) if (req.protocol === 'http' || req.protocol === 'https') { _mixinReqQualifiers(req,res); } next(); }); self.ready = true; }); // Logic to inject before running each middleware sails.on('router:route', function (requestState) { var req = requestState.req; var res = requestState.res; var next = requestState.next; mixinSugar(req,res); }); cb(); } }; /** * Always share some basic metadata with views * * @param {Request} req * @param {Response} res * @api private */ function _mixinLocals (req,res) { res.locals({ _ : util, util : util, session : req.session, title : sails.config.appName + (req.param('action') ? (' | ' + util.str.capitalize(req.param('action'))) : ''), req : req, res : res, sails : sails }); } /** * Override the behavior of res.error to better handle errors * * @param {Request} req * @param {Response} res * @api private */ function _mixinResError (req,res) { res.error = function respondWithError (err, statusCode) { // Argument defaults err = err || 'Unexpected error occurred.'; statusCode = statusCode || 500; if (err instanceof Error) { var msg = sails.config.environment === 'development' ? err.stack : err.toString(); return res.send(msg, statusCode); } if (util.isObject(err)) { return res.json(err, statusCode); } return res.send(err, statusCode); }; } /** * Some syntactic sugar * req.params.all(); * (this is applied per-route, not per request) * * @param {Request} req * @param {Response} res * @api private */ function mixinSugar (req,res) { // Make sure `id` is omitted if it's undefined // (since action blueprint routes name an optional :id) if ( typeof req.param('id') === 'undefined' ) { delete req.params.id; } // Combines parameters from the query string, and encoded request body // to compose a monolithic object of named parameters, irrespective of source var queryParams = util.clone(req.query) || {}; var bodyParams = util.clone(req.body) || {}; var allParams = util.extend({}, queryParams, bodyParams); // Mixin route params util.each(Object.keys(req.params), function (paramName) { allParams[paramName] = req.params[paramName]; }); // Define a new non-enuerable function: req.params.all() // (but only if an `:all` route parameter doesn't exist) if (!req.params.all) { Object.defineProperty(req.params, 'all', { value: function getAllParams () { return allParams; } }); } // TODO: make req.params() do the same thing as req.params.all() ?? } /** * Mix in convenience flags about this request * * @param {Request} req * @param {Response} res * @api private */ function _mixinReqQualifiers (req,res) { var accept = req.get('Accept') || ''; // Flag indicating whether HTML was explicitly mentioned in the Accepts header req.explicitlyAcceptsHTML = (accept.indexOf('html') !== -1); // Flag indicating whether a request would like to receive a JSON response req.wantsJSON = req.xhr; req.wantsJSON = req.wantsJSON || !req.explicitlyAcceptsHTML; req.wantsJSON = req.wantsJSON || ( req.is('json') && req.get('Accept') ); // Legacy support for Sails 0.8.x req.isAjax = req.xhr; req.isJson = req.header('content-type') === 'application/json'; req.acceptJson = req.header('Accept') === 'application/json'; req.isJsony = req.isJson || req.acceptJson; } /** * Host, port, etc. * * @param {Request} req * @param {Response} res * @api private */ function _mixinServerMetadata (req,res) { // Access to server port, if available req.port = req.port; // Add access to full base url for convenience req.baseUrl = req.protocol + '://' + req.host + (req.port == 80 || req.port == 443 ? '' : ':' + req.port); // Legacy support for Sails 0.8.x req.rawHost = req.host; req.rootUrl = req.baseUrl; req.baseurl = req.baseUrl; } };
(function() { serviceAreas.map = { mapobj: null, div: "map_canvas", init: function() { var mapOptions = { center: new google.maps.LatLng(37.775, -122.4183333), zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP }; serviceAreas.map.mapobj = new google.maps.Map(document.getElementById( serviceAreas.map.div), mapOptions); } }; $(document).ready(function() { serviceAreas.map.init(); }); })();
import React, { Component } from 'react'; import { CSSTransitionGroup } from 'react-transition-group'; import animation from '../actions/animations'; class Sidebar extends Component { constructor(props){ super(props); this.runSidebarTransition = this.runSidebarTransition.bind(this); } componentDidMount(){ if(this.props.animate === true ) { this.runSidebarTransition(); } else if (this.props.appLocation === "/about" || this.props.appLocation === "/project/:projectURL") { this.runSidebarTransition(); } } runSidebarTransition(){ animation.transitionSidebar(this.sidebarBackgroundColor, this.sidebarBackgroundMain); } render() { const { project } = this.props; const isMobile = document.body.classList.contains('isMobile'); const sidebarFadeInMobile = isMobile === true && this.props.appLocation === "/project/:projectURL" ? true : false; return ( <CSSTransitionGroup transitionName="change-view" transitionAppear={sidebarFadeInMobile} transitionAppearTimeout={1000} transitionEnter={false} transitionLeave={false} className={(isMobile === false ? null : 'project-transition-target') + ' transition-group-block flex-col flex-one-fourth flex-vertical-one-fourth flex-tablet-full'} > <div className={ (isMobile === false ? null : 'isMobile') + " navigation-sidebar " + ( project !== null ? project[0].projectURL : '') }> <div className="flex-row full-height middle-xs center-flex sidebar-inner"> <CSSTransitionGroup transitionName="heading" transitionAppear={true} transitionAppearTimeout={2000} transitionEnterTimeout={1000} transitionLeaveTimeout={3000} > <Heading heading={this.props.heading} projectName={project !== null ? project[0].projectName : null} /> </CSSTransitionGroup> </div> <div className="sidebar-background"> <div ref={ (div) => { this.sidebarBackgroundColor = div; } } style={ project !== null ? { backgroundColor: project[0].projectColor } : { backgroundColor: '#e8eaef' } } className="background-piece background-piece-left-color"></div> <div ref={ (div) => { this.sidebarBackgroundMain = div; } } className="background-piece background-piece-left-main"></div> </div> </div> </CSSTransitionGroup> ); } } export default Sidebar; function Heading(props){ const heading = props.heading; const projectName = props.projectName; if(heading === 'home'){ return <div className="name"> <h2> <span>G</span> <span>a</span> <span>b</span> <span>r</span> <span>i</span> <span>e</span> <span>l</span> <span>&nbsp;</span> <span>Z</span> <span>a</span> <span>r</span> <span>a</span> <span>t</span> <span>e</span> </h2> <span className="sub-head">Front-End Developer</span> </div> } else if (heading === 'about') { return <div className="name"> <h2> <span>G</span> <span>a</span> <span>b</span> <span>r</span> <span>i</span> <span>e</span> <span>l</span> <span>&nbsp;</span> <span>Z</span> <span>a</span> <span>r</span> <span>a</span> <span>t</span> <span>e</span> </h2> </div> } else { return <div className="name"> <h2> { projectName } </h2> </div> } }
/* $(document).ready(function(){ //add scroll effect to the menu navbar var navbarFixedTop = $("#header-menu"); navbarFixedTop.css('background-color', 'rgba(0,0,0,0.75)'); var transparency = 0; $(window).scroll(function() { if ($(document).scrollTop() > 70) { transparency = ($(document).scrollTop()/$(window).height())+0.75; navbarFixedTop.css('background-color', 'rgba(0,0,0,'+transparency+')'); } else { navbarFixedTop.css('background-color', 'rgba(0,0,0,0.75)'); } }); });*/ var menuopen=0; var what = (/(iPhone|iPod|iPad).*AppleWebKit/i.test(navigator.userAgent)) ? 'touchstart' : 'click'; $(document).ready(function () { $('header:has(.headerbg)').css('height','100%'); $("#"+getElementIdForScrollAdjust()).scrollTop(-250); $(document).on(what, '#butnavbar', function (e) { if(menuopen==0){ $('#upnavbar').show(); $( "#navbar" ).show().animate({left: "40px"}, 200, function() {});menuopen=1; } else if(menuopen==1){ $( "#navbar" ).animate({left: "300px"}, 200, function() {$('#upnavbar').hide();});menuopen=0; } }); showCookieConsent(); $(".cc-btn").click(function () { var ccVal; if ($(this).hasClass("cc-btn-positive")) { ccVal = "1"; } else { ccVal = "0"; } createCookie("usr_cc", ccVal, 4745); $(".cookie-consent").slideUp("fast"); }); }); function showCookieConsent() { var usrCc = readCookie("usr_cc"); if (!usrCc) { $(".cookie-consent").slideDown("slow"); } } function getElementIdForScrollAdjust() { var url = document.location; console.log(url); var blockElementId = url.hash.substring(url.hash.indexOf("#")+1); console.log(blockElementId); return blockElementId; }
name = "denseSteelPlate"; addToCreative[0] = true; creativeTab = "materials"; maxStack = 64; textureFile[0] = "denseSteelPlate.png";
/* * grunt-xmlpoke * https://github.com/bdukes/grunt-xmlpoke * * Copyright (c) 2014 Brian Dukes * Licensed under the MIT license. */ 'use strict'; module.exports = function (grunt) { // Project configuration. grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'tasks/*.js', '<%= nodeunit.tests %>' ], options: { jshintrc: '.jshintrc' } }, // Before generating any new files, remove any previously-created files. clean: { tests: ['tmp'] }, // Configuration to be run (and then tested). xmlpoke: { options : { failIfMissing: true }, missing_src: { options: { xpath: '/x', value: 'y' }, files: { 'tmp/missing.xml': 'test/fixtures/missing.xml' } }, /*invalid_src: { options: { xpath: '/x', value: 'y' }, files: { 'tmp/invalid.xml': 'test/fixtures/invalid.xml' } },*/ testing_attribute: { options: { xpath: '/data/@test-value', value: 'UPDATE' }, files: { 'tmp/testing_attribute.xml': 'test/fixtures/testing.xml' } }, testing_element_text: { options: { xpath: '/data', value: 'UPDATED information' }, files: { 'tmp/testing_element_text.xml': 'test/fixtures/testing.xml' } }, testing_element_encoded_text: { options: { xpath: '/data', value: '<child>UPDATED information</child>' }, files: { 'tmp/testing_element_encoded_text.xml': 'test/fixtures/testing.xml' } }, testing_element: { options: { xpath: '/data', value: '<child>UPDATED information</child>', valueType: 'element' }, files: { 'tmp/testing_element.xml': 'test/fixtures/testing.xml' } }, testing_element_append: { options: { replacements: [{ xpath: '/data', value: '<child>UPDATED information</child>', valueType: 'element' }, { xpath: '/data', value: '<child>UPDATED information appended</child>', valueType: 'append' }] }, files: { 'tmp/testing_element_append.xml': 'test/fixtures/testing.xml' } }, testing_element_without: { options: { xpath: '/data/without', valueType: 'remove', }, files: { 'tmp/element_without.xml': 'test/fixtures/children.xml' } }, numbers_elements: { options: { xpath: '//Number', value: '90' }, files: { 'tmp/numbers_elements.xml': 'test/fixtures/numbers.xml' } }, numbers_no_match: { options: { xpath: '//Numbering', value: '999', failIfMissing: false }, files: { 'tmp/numbers_no_match.xml': 'test/fixtures/numbers.xml' } }, default_value_is_empty: { options: { xpath: '/x/@y' }, files: { 'tmp/default_value_is_empty.xml': 'test/fixtures/simple.xml' } }, multiple_xpath_queries: { options: { xpath: ['/x/@y','/x'], value: '111' }, files: { 'tmp/multiple_xpath_queries.xml': 'test/fixtures/simple.xml' } }, multiple_replacements: { options: { replacements: [{ xpath: '/x/@y', value: '111' }, { xpath: '/x', value: 'M' }] }, files: { 'tmp/multiple_replacements.xml': 'test/fixtures/simple.xml' } }, value_as_function: { options: { xpath: '/x/@y', value: function(){ return 'value from a function'; } }, files: { 'tmp/value_as_function.xml': 'test/fixtures/simple.xml' } }, value_as_function_with_callback: { options: { xpath: '/data/@test-value', value: function(node){ return node.value.toUpperCase(); } }, files: { 'tmp/value_as_function_with_callback.xml': 'test/fixtures/testing.xml' } }, value_as_raw_xml: { options: { namespaces: { 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#' }, xpath: '//rdf:Description', valueType: 'element', value: '\r\n<Number>1</Number><Number>2</Number><Number>3</Number>' }, files: { 'tmp/value_as_raw_xml.xml': 'test/fixtures/namespaces.xml' } }, namespaces: { dest: 'tmp/namespaces.xml', src: 'test/fixtures/namespaces.xml', options: { namespaces: { 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'em': 'http://www.mozilla.org/2004/em-rdf#' }, xpath: '/rdf:RDF/rdf:Description/em:version', value: '1.2.4' } }, default_namespace_attribute: { dest: 'tmp/config.xml', src: 'test/fixtures/config.xml', options: { namespaces: { 'w': 'http://www.w3.org/ns/widgets', 'cdv': 'http://cordova.apache.org/ns/1.0' }, replacements: [{ xpath: '/w:widget/@version', value: '0.2.1' },{ xpath: '/w:widget/w:author', value: 'Someone Else' },{ xpath: '/w:widget/w:author/@email', value: 'someone.else@example.com' },{ xpath: '/w:widget/cdv:custom-cordova-thing', value: 'new value' }] } }, declaration: { dest: 'tmp/declaration.xml', src: 'test/fixtures/declaration.xml', options: { xpath: '/widget/title', value: 'New Title' } }, append_to_sap: { dest: 'tmp/append_to_sap.xml', src: 'test/fixtures/sap.xml', options: { namespaces: { 'm': 'sap.m', 'l': 'sap.ui.layout', 'f': 'sap.ui.layout.form', 'core': 'sap.ui.core', }, valueType: 'append', xpath: '//m:Select[@id="mySelect"][core:Item]', value: '<core:Item key="sov" text="Sovanta Theme"/>', }, }, }, // Unit tests. nodeunit: { tests: ['test/*_test.js'] } }); // Actually load this plugin's task(s). grunt.loadTasks('tasks'); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); // Whenever the "test" task is run, first clean the "tmp" dir, then run this // plugin's task(s), then test the result. grunt.registerTask('test', ['clean', 'xmlpoke', 'nodeunit']); // By default, lint and run all tests. grunt.registerTask('default', ['jshint', 'test']); };