code stringlengths 2 1.05M |
|---|
'use strict';
module.exports = function(grunt) {
// Load all grunt tasks
require('load-grunt-tasks')(grunt);
// Project configuration.
grunt.initConfig({
jshint: {
js: {
src: ['Gruntfile.js', 'tasks/*.js']
},
options: {
reporterOutput: "",
jshintrc: '.jshintrc'
}
},
watch: {
js: {
files: '<%= jshint.js.src %>',
tasks: ['jshint:js', 'jsbeautifier']
}
},
jsbeautifier: {
files: '<%= jshint.js.src %>',
options: {
js: {
braceStyle: 'collapse',
breakChainedMethods: false,
e4x: false,
evalCode: false,
indentChar: ' ',
indentLevel: 0,
indentSize: 4,
indentWithTabs: false,
jslintHappy: false,
keepArrayIndentation: false,
keepFunctionIndentation: false,
maxPreserveNewlines: 10,
preserveNewlines: true,
spaceBeforeConditional: true,
spaceInParen: false,
unescapeStrings: false,
wrapLineLength: 0
}
}
}
});
// By default, lint and run all tests.
grunt.registerTask('default', ['jshint', 'jsbeautifier']);
};
|
var lexer = require('../lib/lexer.js');
TokenType = lexer.TokenType;
exports['get null if empty string'] = function (test) {
var lxr = lexer.createLexer('');
test.strictEqual(lxr.nextToken(), null);
}
exports['get null if blank string'] = function (test) {
var lxr = lexer.createLexer(' ');
test.strictEqual(lxr.nextToken(), null);
}
exports['get null if empty lines'] = function (test) {
var lxr = lexer.createLexer(' \n \n');
test.strictEqual(lxr.nextToken(), null);
}
exports['get null if empty lines with carriage return'] = function (test) {
var lxr = lexer.createLexer(' \r\n \n');
test.strictEqual(lxr.nextToken(), null);
}
exports['get indent and integer'] = function (test) {
var lxr = lexer.createLexer('123');
var token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Indent);
test.equal(token.value, 0);
token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Integer);
test.equal(token.value, '123');
test.strictEqual(lxr.nextToken(), null);
};
exports['get indent and real'] = function (test) {
var lxr = lexer.createLexer('123.45');
var token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Indent);
test.equal(token.value, 0);
token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Real);
test.equal(token.value, '123.45');
test.strictEqual(lxr.nextToken(), null);
};
exports['get indent and name'] = function (test) {
var lxr = lexer.createLexer('name');
var token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Indent);
test.equal(token.value, 0);
token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Name);
test.equal(token.value, 'name');
test.strictEqual(lxr.nextToken(), null);
};
exports['get indent and two names'] = function (test) {
var lxr = lexer.createLexer('foo bar');
var token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Indent);
test.equal(token.value, 0);
token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Name);
test.equal(token.value, 'foo');
token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Name);
test.equal(token.value, 'bar');
test.strictEqual(lxr.nextToken(), null);
};
exports['get indent two spaces and name'] = function (test) {
var lxr = lexer.createLexer(' name');
var token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Indent);
test.equal(token.value, 2);
token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Name);
test.equal(token.value, 'name');
test.strictEqual(lxr.nextToken(), null);
};
exports['get string'] = function (test) {
var lxr = lexer.createLexer('"foo"');
var token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Indent);
test.equal(token.value, 0);
token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.String);
test.equal(token.value, 'foo');
test.strictEqual(lxr.nextToken(), null);
};
exports['get indent two spaces and name skipping empty lines'] = function (test) {
var lxr = lexer.createLexer(' \r\n\n name');
var token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Indent);
test.equal(token.value, 2);
token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Name);
test.equal(token.value, 'name');
test.strictEqual(lxr.nextToken(), null);
};
exports['get parenthesis as punctuation'] = function (test) {
var lxr = lexer.createLexer('()');
var token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Indent);
test.equal(token.value, 0);
token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Punctuation);
test.equal(token.value, '(');
token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Punctuation);
test.equal(token.value, ')');
test.strictEqual(lxr.nextToken(), null);
};
exports['get colons as punctuation'] = function (test) {
var lxr = lexer.createLexer(':');
var token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Indent);
test.equal(token.value, 0);
token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Punctuation);
test.equal(token.value, ':');
test.strictEqual(lxr.nextToken(), null);
};
exports['get equal as operator'] = function (test) {
var lxr = lexer.createLexer('=');
var token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Indent);
test.equal(token.value, 0);
token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Operator);
test.equal(token.value, '=');
test.strictEqual(lxr.nextToken(), null);
};
exports['get plus as operator'] = function (test) {
var lxr = lexer.createLexer('+');
var token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Indent);
test.equal(token.value, 0);
token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Operator);
test.equal(token.value, '+');
test.strictEqual(lxr.nextToken(), null);
};
exports['get comparison operators'] = function (test) {
var operators = ['==', '!=', '<', '<=', '>', '>='];
var lxr = lexer.createLexer(operators.join(' '));
lxr.nextToken();
for (var k = 0; k < operators.length; k++) {
var token = lxr.nextToken();
test.ok(token);
test.equal(token.type, TokenType.Operator);
test.equal(token.value, operators[k]);
}
test.strictEqual(lxr.nextToken(), null);
};
|
/**
* Tests for the parser/tokenizer
*/
"use strict";
var JSHINT = require('../../src/jshint.js').JSHINT;
var fs = require('fs');
var TestRun = require("../helpers/testhelper").setup.testRun;
var path = require("path");
exports.unsafe = function (test) {
var code = [
"var a\u000a = 'Here is a unsafe character';",
];
TestRun(test)
.addError(1, "This character may get silently deleted by one or more browsers.")
.test(code, {es3: true});
test.done();
};
exports.other = function (test) {
var code = [
"\\",
"!",
];
TestRun(test)
.addError(1, "Unexpected '\\'.")
.addError(2, "Unexpected early end of program.")
.addError(2, "Expected an identifier and instead saw '(end)'.")
.addError(2, "Unrecoverable syntax error. (100% scanned).")
.test(code, {es3: true});
// GH-818
TestRun(test)
.addError(1, "Expected an identifier and instead saw ')'.")
.addError(1, "Unrecoverable syntax error. (100% scanned).")
.test("if (product < ) {}", {es3: true});
test.done();
};
exports.confusingOps = function (test) {
var code = [
"var a = 3 - -3;",
"var b = 3 + +3;",
"a = a - --a;",
"a = b + ++b;",
"a = a-- - 3;", // this is not confusing?!
"a = a++ + 3;", // this is not confusing?!
];
var run = TestRun(test)
.addError(1, "Confusing minuses.")
.addError(2, "Confusing plusses.")
.addError(3, "Confusing minuses.")
.addError(4, "Confusing plusses.");
run.test(code, {es3: true});
run.test(code, {}); // es5
run.test(code, {esnext: true});
run.test(code, {moz: true});
test.done();
};
exports.plusplus = function (test) {
var run;
var code = [
"var a = ++[2];",
"var b = --(2);",
];
run = TestRun(test)
.addError(1, "Unexpected use of '++'.")
.addError(2, "Unexpected use of '--'.");
run.test(code, { plusplus: true, es3: true });
run.test(code, { plusplus: true }); // es5
run.test(code, { plusplus: true, esnext: true });
run.test(code, { plusplus: true, moz: true });
run = TestRun(test)
.addError(2, "Bad operand.");
run.test(code, { plusplus: false, es3: true });
run.test(code, { plusplus: false }); // es5
run.test(code, { plusplus: false, esnext: true });
run.test(code, { plusplus: false, moz: true });
test.done();
};
exports.assignment = function (test) {
var code = [
"function test() {",
"arguments.length = 2;",
"arguments[0] = 3;",
"}",
"function test2() {",
"\"use strict\";",
"arguments.length = 2;",
"arguments[0] = 3;",
"}",
"a() = 2;",
];
var run = TestRun(test)
.addError(2, "Bad assignment.")
.addError(3, "Bad assignment.")
.addError(10, "Bad assignment.")
.addError(10, "Expected an assignment or function call and instead saw an expression.")
.addError(10, "Missing semicolon.");
run.test(code, { plusplus: true, es3: true });
run.test(code, { plusplus: true }); // es5
run.test(code, { plusplus: true, esnext: true });
run.test(code, { plusplus: true, moz: true });
test.done();
};
exports.relations = function (test) {
var code = [
"var a = 2 === NaN;",
"var b = NaN == 2;",
"var c = !2 < 3;",
"var c = 2 < !3;",
"var d = (!'x' in obj);",
"var e = (!a === b);",
"var f = (a === !'hi');",
"var g = (!2 === 1);",
"var h = (![1, 2, 3] === []);",
];
var run = TestRun(test)
.addError(1, "Use the isNaN function to compare with NaN.")
.addError(2, "Use the isNaN function to compare with NaN.")
.addError(3, "Confusing use of '!'.", {character : 9})
.addError(4, "Confusing use of '!'.", {character : 13})
.addError(5, "Confusing use of '!'.", {character : 10})
.addError(6, "Confusing use of '!'.", {character : 10})
.addError(7, "Confusing use of '!'.", {character : 16})
.addError(8, "Confusing use of '!'.", {character : 10})
.addError(9, "Confusing use of '!'.", {character : 10});
run.test(code, {es3: true});
run.test(code, {}); // es5
run.test(code, {esnext: true});
run.test(code, {moz: true});
test.done();
};
exports.options = function (test) {
var code = [
"/*member a*/",
"/*members b*/",
"var x; x.a.b.c();",
"/*jshint ++ */",
"/*jslint indent: 0 */",
"/*jslint indent: -2 */",
"/*jslint indent: 100.4 */",
"/*jslint maxlen: 200.4 */",
"/*jslint maxerr: 300.4 */",
"/*jslint maxerr: 0 */",
"/*jslint maxerr: 20 */",
"/*member c:true */",
"/*jshint d:no */",
"/*global xxx*/",
"xxx = 2;",
];
var run = TestRun(test)
.addError(3, "Unexpected /*member 'c'.")
.addError(4, "Bad option: '++'.")
.addError(5, "Expected a small integer or 'false' and instead saw '0'.")
.addError(6, "Expected a small integer or 'false' and instead saw '-2'.")
.addError(7, "Expected a small integer or 'false' and instead saw '100.4'.")
.addError(8, "Expected a small integer or 'false' and instead saw '200.4'.")
.addError(9, "Expected a small integer or 'false' and instead saw '300.4'.")
.addError(10, "Expected a small integer or 'false' and instead saw '0'.")
.addError(13, "Bad option: 'd'.")
.addError(15, "Read only.");
run.test(code, {es3: true});
run.test(code, {}); // es5
run.test(code, {esnext: true});
run.test(code, {moz: true});
TestRun(test).test(fs.readFileSync(__dirname + "/fixtures/gh988.js", "utf8"));
test.done();
};
exports.shebang = function (test) {
var code = [
"#!test",
"var a = 'xxx';",
"#!test"
];
var run = TestRun(test)
.addError(3, "Expected an identifier and instead saw '#'.")
.addError(3, "Expected an operator and instead saw '!'.")
.addError(3, "Expected an assignment or function call and instead saw an expression.")
.addError(3, "Missing semicolon.");
run.test(code, {es3: true});
run.test(code, {}); // es5
run.test(code, {esnext: true});
run.test(code, {moz: true});
test.done();
};
exports.shebangImpliesNode = function (test) {
var code = [
"#!usr/bin/env node",
"require('module');",
];
TestRun(test).test(code);
test.done();
};
exports.numbers = function (test) {
/*jshint maxlen: 300*/
var code = [
"var a = 10e307;",
"var b = 10e308;",
"var c = 0.03 + 0.3 + 3.0 + 30.00;",
"var d = 03;",
"var e = .3;",
"var f = 0xAAg;",
"var g = 0033;",
"var h = 3.;",
"var i = 3.7.toString();",
"var j = 1e-10;" // GH-821
];
TestRun(test)
.addError(2, "Bad number '10e308'.")
.addError(5, "A leading decimal point can be confused with a dot: '.3'.")
.addError(6, "Unexpected '0'.")
.addError(7, "Expected an identifier and instead saw 'var'.")
.addError(7, "Missing semicolon.")
.addError(7, "Don't use extra leading zeros '0033'.")
.addError(8, "A trailing decimal point can be confused with a dot: '3.'.")
.addError(9, "A dot following a number can be confused with a decimal point.")
.test(code, {es3: true});
// Octals are prohibited in strict mode.
TestRun(test)
.addError(3, "Octal literals are not allowed in strict mode.")
.test([
"(function () {",
"'use strict';",
"return 045;",
"}());"
]);
// GitHub #751 - an expression containing a number with a leading decimal point should be parsed in its entirety
TestRun(test)
.addError(1, "A leading decimal point can be confused with a dot: '.3'.")
.addError(2, "A leading decimal point can be confused with a dot: '.3'.")
.test([
"var a = .3 + 1;",
"var b = 1 + .3;",
]);
test.done();
};
exports.comments = function (test) {
var code = [
"/*",
"/* nested */",
"*/",
"/* unclosed ...",
];
var run = TestRun(test)
.addError(3, "Unbegun comment.")
.addError(4, "Unclosed comment.");
run.test(code, {es3: true});
run.test(code, {}); // es5
run.test(code, {esnext: true});
run.test(code, {moz: true});
var src = "/* this is a comment /* with nested slash-start */";
TestRun(test).test(src);
TestRun(test).test(fs.readFileSync(__dirname + "/fixtures/gruntComment.js", "utf8"));
test.done();
};
exports.regexp = function (test) {
var code = [
"var a1 = /\\\x1f/;",
"var a2 = /[\\\x1f]/;",
"var b1 = /\\</;", // only \< is unexpected?!
"var b2 = /[\\<]/;", // only \< is unexpected?!
"var c = /(?(a)b)/;",
"var d = /)[--aa-b-cde-]/;",
"var e = /[]/;",
"var f = /[^]/;",
"var g = /[a^[]/;",
// FIXME: Firefox doesn't handle [a-\\s] well.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=813249
"", // "var h = /[a-\\s-\\w-\\d\\x10-\\x20--]/;",
"var i = /[/-a1-/]/;",
"var j = /[a-<<-3]./;",
"var k = /]}/;",
"var l = /?(*)(+)({)/;",
"var m = /a{b}b{2,c}c{3,2}d{4,?}x{30,40}/;",
"var n = /a??b+?c*?d{3,4}? a?b+c*d{3,4}/;",
"var o = /a\\/* [a-^-22-]/;",
"var p = /(?:(?=a|(?!b)))/;",
"var q = /=;/;",
"var r = /(/;",
"var s = /(((/;",
"var t = /x/* 2;",
"var u = /x/;",
"var v = /dsdg;",
"var w = v + /s/;",
"var x = w - /s/;",
"var y = typeof /[a-z]/;" // GH-657
];
var run = TestRun(test)
.addError(1, "This character may get silently deleted by one or more browsers.")
.addError(1, "Unexpected control character in regular expression.")
.addError(2, "This character may get silently deleted by one or more browsers.")
.addError(2, "Unexpected control character in regular expression.")
.addError(3, "Unexpected escaped character '<' in regular expression.")
.addError(4, "Unexpected escaped character '<' in regular expression.")
.addError(5, "Invalid regular expression.")
.addError(6, "Invalid regular expression.")
.addError(11, "Invalid regular expression.")
.addError(12, "Invalid regular expression.")
.addError(14, "Invalid regular expression.")
.addError(15, "Invalid regular expression.")
.addError(17, "Invalid regular expression.")
.addError(20, "Invalid regular expression.")
.addError(21, "Invalid regular expression.")
.addError(24, "Unclosed regular expression.")
.addError(24, "Unrecoverable syntax error. (88% scanned).");
run.test(code, {es3: true});
run.test(code, {}); // es5
run.test(code, {esnext: true});
run.test(code, {moz: true});
TestRun(test).test("var y = Math.sqrt(16) / 180;", {es3: true});
TestRun(test).test("var y = Math.sqrt(16) / 180;", {}); // es5
TestRun(test).test("var y = Math.sqrt(16) / 180;", {esnext: true});
TestRun(test).test("var y = Math.sqrt(16) / 180;", {moz: true});
// GH-803
TestRun(test).test("var x = [1]; var y = x[0] / 180;", {es3: true});
TestRun(test).test("var x = [1]; var y = x[0] / 180;", {}); // es5
TestRun(test).test("var x = [1]; var y = x[0] / 180;", {esnext: true});
TestRun(test).test("var x = [1]; var y = x[0] / 180;", {moz: true});
test.done();
};
exports.testRegexRegressions = function (test) {
// GH-536
TestRun(test).test("str /= 5;", {es3: true}, { str: true });
TestRun(test).test("str /= 5;", {}, { str: true }); // es5
TestRun(test).test("str /= 5;", {esnext: true}, { str: true });
TestRun(test).test("str /= 5;", {moz: true}, { str: true });
TestRun(test).test("str = str.replace(/=/g, '');", {es3: true}, { str: true });
TestRun(test).test("str = str.replace(/=/g, '');", {}, { str: true }); // es5
TestRun(test).test("str = str.replace(/=/g, '');", {esnext: true}, { str: true });
TestRun(test).test("str = str.replace(/=/g, '');", {moz: true}, { str: true });
TestRun(test).test("str = str.replace(/=abc/g, '');", {es3: true}, { str: true });
TestRun(test).test("str = str.replace(/=abc/g, '');", {}, { str: true }); // es5
TestRun(test).test("str = str.replace(/=abc/g, '');", {esnext: true}, { str: true });
TestRun(test).test("str = str.replace(/=abc/g, '');", {moz: true}, { str: true });
// GH-538
TestRun(test).test("var exp = /function(.*){/gi;", {es3: true});
TestRun(test).test("var exp = /function(.*){/gi;", {}); // es5
TestRun(test).test("var exp = /function(.*){/gi;", {esnext: true});
TestRun(test).test("var exp = /function(.*){/gi;", {moz: true});
test.done();
};
exports.strings = function (test) {
var code = [
"var a = '\u0012\\r';",
"var b = \'\\g\';",
"var c = '\\u0022\\u0070\\u005C';",
"var e = '\\x6b..\\x6e';",
"var f = 'ax"
];
var run = TestRun(test)
.addError(1, "Control character in string: <non-printable>.", {character: 10})
.addError(1, "This character may get silently deleted by one or more browsers.")
.addError(2, "Bad or unnecessary escaping.")
.addError(5, "Unclosed string.")
.addError(5, "Missing semicolon.");
run.test(code, {es3: true});
run.test(code, {}); // es5
run.test(code, {esnext: true});
run.test(code, {moz: true});
test.done();
};
exports.ownProperty = function (test) {
var code = [
"var obj = { hasOwnProperty: false };",
"obj.hasOwnProperty = true;",
"obj['hasOwnProperty'] = true;",
"function test() { var hasOwnProperty = {}.hasOwnProperty; }"
];
var run = TestRun(test)
.addError(1, "'hasOwnProperty' is a really bad name.")
.addError(2, "'hasOwnProperty' is a really bad name.")
.addError(3, "'hasOwnProperty' is a really bad name.")
.addError(3, "['hasOwnProperty'] is better written in dot notation.");
run.test(code, {es3: true});
run.test(code, {}); // es5
run.test(code, {esnext: true});
run.test(code, {moz: true});
test.done();
};
exports.jsonMode = function (test) {
var code = [
'{',
' a: 2,',
' \'b\': "hallo\\"\\v\\x12\\\'world",',
' "c\\"\\v\\x12": \'4\',',
' "d": "4\\',
' ",',
' "e": 0x332,',
' "x": 0',
'}',
];
var run = TestRun(test)
.addError(2, "Expected a string and instead saw a.")
.addError(3, "Strings must use doublequote.")
.addError(3, "Avoid \\v.")
.addError(3, "Avoid \\x-.")
.addError(3, "Avoid \\'.")
.addError(4, "Avoid \\v.")
.addError(4, "Avoid \\x-.")
.addError(4, "Strings must use doublequote.")
.addError(5, "Avoid EOL escaping.")
.addError(7, "Avoid 0x-.");
run.test(code, {multistr: true, es3: true});
run.test(code, {multistr: true}); // es5
run.test(code, {multistr: true, esnext: true});
run.test(code, {multistr: true, moz: true});
test.done();
};
exports.comma = function (test) {
var src = fs.readFileSync(__dirname + "/fixtures/comma.js", "utf8");
TestRun(test)
.addError(2, "Expected an assignment or function call and instead saw an expression.")
.addError(15, "Expected an assignment or function call and instead saw an expression.")
.addError(15, "Missing semicolon.")
.addError(20, "Expected an assignment or function call and instead saw an expression.")
.addError(30, "Expected an assignment or function call and instead saw an expression.")
.addError(35, "Expected an assignment or function call and instead saw an expression.")
.addError(35, "Missing semicolon.")
.addError(36, "Unexpected 'if'.")
.addError(43, "Expected an assignment or function call and instead saw an expression.")
.addError(43, "Missing semicolon.")
.addError(44, "Unexpected '}'.")
.test(src, {es3: true});
// Regression test (GH-56)
TestRun(test)
.addError(4, "Expected an assignment or function call and instead saw an expression.")
.test(fs.readFileSync(__dirname + "/fixtures/gh56.js", "utf8"));
// Regression test (GH-363)
TestRun(test)
.addError(1, "Extra comma. (it breaks older versions of IE)")
.test("var f = [1,];", {es3: true});
test.done();
};
exports.withStatement = function (test) {
var src = fs.readFileSync(__dirname + "/fixtures/with.js", "utf8");
var run;
run = TestRun(test)
.addError(5, "Don't use 'with'.")
.addError(13, "'with' is not allowed in strict mode.");
run.test(src, {es3: true});
run.test(src); // es5
run.test(src, {esnext: true});
run.test(src, {moz: true});
run = TestRun(test)
.addError(13, "'with' is not allowed in strict mode.");
run.test(src, {withstmt: true, es3: true});
run.test(src, {withstmt: true}); // es5
run.test(src, {withstmt: true, esnext: true});
run.test(src, {withstmt: true, moz: true});
test.done();
};
exports.blocks = function (test) {
var src = fs.readFileSync(__dirname + "/fixtures/blocks.js", "utf8");
var run = TestRun(test)
.addError(29, "Unmatched \'{\'.")
.addError(31, "Unmatched \'{\'.");
run.test(src, {es3: true});
run.test(src, {}); // es5
run.test(src, {esnext: true});
run.test(src, {moz: true});
test.done();
};
exports.functionCharacterLocation = function (test) {
var i;
var src = fs.readFileSync(__dirname + "/fixtures/nestedFunctions.js", "utf8");
var locations = JSON.parse(
fs.readFileSync(
__dirname + "/fixtures/nestedFunctions-locations.js", "utf8"
)
);
JSHINT(src);
var report = JSHINT.data().functions;
test.equal(locations.length, report.length);
for (i = 0; i < locations.length; i += 1) {
test.equal(locations[i].name, report[i].name);
test.equal(locations[i].line, report[i].line);
test.equal(locations[i].character, report[i].character);
test.equal(locations[i].last, report[i].last);
test.equal(locations[i].lastcharacter, report[i].lastcharacter);
}
test.done();
};
exports.exported = function (test) {
var src = fs.readFileSync(__dirname + "/fixtures/exported.js", "utf8");
var run = TestRun(test)
.addError(5, "'unused' is defined but never used.")
.addError(6, "'isDog' is defined but never used.")
.addError(13, "'unusedDeclaration' is defined but never used.")
.addError(14, "'unusedExpression' is defined but never used.")
.addError(17, "'cannotBeExported' is defined but never used.");
run.test(src, {es3: true, unused: true });
run.test(src, {unused: true }); // es5
run.test(src, {esnext: true, unused: true });
run.test(src, {moz: true, unused: true });
run = TestRun(test)
.addError(1, "'unused' is defined but never used.")
.test("var unused = 1; var used = 2;", {exported: ["used"], unused: true});
test.done();
};
exports.testIdentifiers = function (test) {
var src = fs.readFileSync(__dirname + "/fixtures/identifiers.js", "utf8");
TestRun(test).test(src, {es3: true});
var run = TestRun(test)
.addError(1, "'ascii' is defined but never used.")
.addError(2, "'num1' is defined but never used.")
.addError(3, "'lifé' is defined but never used.")
.addError(4, "'π' is defined but never used.")
.addError(5, "'привет' is defined but never used.")
.addError(6, "'\\u1d44' is defined but never used.")
.addError(7, "'encoded\\u1d44' is defined but never used.")
.addError(8, "'\\uFF38' is defined but never used.")
.addError(9, "'\\uFF58' is defined but never used.")
.addError(10, "'\\u1FBC' is defined but never used.")
.addError(11, "'\\uFF70' is defined but never used.")
.addError(12, "'\\u4DB3' is defined but never used.")
.addError(13, "'\\u97CA' is defined but never used.")
.addError(14, "'\\uD7A1' is defined but never used.")
.addError(15, "'\\uFFDA' is defined but never used.")
.addError(16, "'\\uA6ED' is defined but never used.")
.addError(17, "'\\u0024' is defined but never used.")
.addError(18, "'\\u005F' is defined but never used.")
.addError(19, "'\\u0024\\uFF38' is defined but never used.")
.addError(20, "'\\u0024\\uFF58' is defined but never used.")
.addError(21, "'\\u0024\\u1FBC' is defined but never used.")
.addError(22, "'\\u0024\\uFF70' is defined but never used.")
.addError(23, "'\\u0024\\u4DB3' is defined but never used.")
.addError(24, "'\\u0024\\u97CA' is defined but never used.")
.addError(25, "'\\u0024\\uD7A1' is defined but never used.")
.addError(26, "'\\u0024\\uFFDA' is defined but never used.")
.addError(27, "'\\u0024\\uA6ED' is defined but never used.")
.addError(28, "'\\u0024\\uFE24' is defined but never used.")
.addError(29, "'\\u0024\\uABE9' is defined but never used.")
.addError(30, "'\\u0024\\uFF17' is defined but never used.")
.addError(31, "'\\u0024\\uFE4E' is defined but never used.")
.addError(32, "'\\u0024\\u200C' is defined but never used.")
.addError(33, "'\\u0024\\u200D' is defined but never used.")
.addError(34, "'\\u0024\\u0024' is defined but never used.")
.addError(35, "'\\u0024\\u005F' is defined but never used.");
run.test(src, {es3: true, unused: true });
run.test(src, {unused: true }); // es5
run.test(src, {esnext: true, unused: true });
run.test(src, {moz: true, unused: true });
test.done();
};
exports["regression for GH-878"] = function (test) {
var src = fs.readFileSync(__dirname + "/fixtures/gh878.js", "utf8");
TestRun(test).test(src, {es3: true});
test.done();
};
exports["regression for GH-910"] = function (test) {
var src = "(function () { if (true) { foo.bar + } })();";
TestRun(test)
.addError(1, "Expected an identifier and instead saw '}'.")
.addError(1, "Expected an assignment or function call and instead saw an expression.")
.addError(1, "Missing semicolon.")
.addError(1, "Expected an identifier and instead saw ')'.")
.addError(1, "Expected an operator and instead saw '('.")
.addError(1, "Unmatched '{'.")
.addError(1, "Unmatched '('.")
.addError(1, "Expected an assignment or function call and instead saw an expression.")
.addError(1, "Missing semicolon.")
.test(src, { es3: true, nonew: true });
test.done();
};
exports.testHtml = function (test) {
var html = "<html><body>Hello World</body></html>";
TestRun(test)
.addError(1, "Expected an identifier and instead saw '<'.")
.addError(1, "Expected an assignment or function call and instead saw an expression.")
.addError(1, "Missing semicolon.")
.addError(1, "Expected an identifier and instead saw '<'.")
.addError(1, "Unrecoverable syntax error. (100% scanned).")
.test(html, {});
test.done();
};
exports["test: destructuring var in function scope"] = function (test) {
var code = [
"function foobar() {",
" var [ a, b, c ] = [ 1, 2, 3 ];",
" var [ a ] = [ 1 ];",
" var [ a ] = [ z ];",
" var [ h, w ] = [ 'hello', 'world' ]; ",
" var [ o ] = [ { o : 1 } ];",
" var [ a, [ [ [ b ], c ], d ] ] = [ 1, [ [ [ 2 ], 3], 4 ] ];",
" var { foo : bar } = { foo : 1 };",
" var [ a, { foo : bar } ] = [ 2, { foo : 1 } ];",
" var [ 1 ] = [ a ];",
" var [ a, b; c ] = [ 1, 2, 3 ];",
" var [ a, b, c ] = [ 1, 2; 3 ];",
"}"
];
TestRun(test)
.addError(1, "'foobar' is defined but never used.")
.addError(3, "'a' is already defined.")
.addError(4, "'a' is already defined.")
.addError(7, "'a' is already defined.")
.addError(7, "'b' is already defined.")
.addError(7, "'c' is already defined.")
.addError(9, "'a' is already defined.")
.addError(9, "'bar' is already defined.")
.addError(10, "Expected an identifier and instead saw '1'.")
.addError(10, "Expected ',' and instead saw '1'.")
.addError(10, "Expected an identifier and instead saw ']'.")
.addError(11, "Expected ',' and instead saw ';'.")
.addError(11, "'a' is already defined.")
.addError(11, "'b' is already defined.")
.addError(11, "'c' is already defined.")
.addError(12, "'a' is already defined.")
.addError(12, "'b' is already defined.")
.addError(12, "'c' is already defined.")
.addError(12, "Expected ']' to match '[' from line 12 and instead saw ';'.")
.addError(12, "Missing semicolon.")
.addError(12, "Expected an assignment or function call and instead saw an expression.")
.addError(12, "Missing semicolon.")
.addError(12, "Expected an identifier and instead saw ']'.")
.addError(12, "Expected an assignment or function call and instead saw an expression.")
.addError(4, "'z' is not defined.")
.addError(12, "'a' is defined but never used.")
.addError(12, "'b' is defined but never used.")
.addError(12, "'c' is defined but never used.")
.addError(5, "'h' is defined but never used.")
.addError(5, "'w' is defined but never used.")
.addError(6, "'o' is defined but never used.")
.addError(7, "'d' is defined but never used.")
.addError(9, "'bar' is defined but never used.")
.test(code, {esnext: true, unused: true, undef: true});
test.done();
};
exports["test: destructuring var as moz"] = function (test) {
var code = [
"var [ a, b, c ] = [ 1, 2, 3 ];",
"var [ a ] = [ 1 ];",
"var [ a ] = [ z ];",
"var [ h, w ] = [ 'hello', 'world' ]; ",
"var [ o ] = [ { o : 1 } ];",
"var [ a, [ [ [ b ], c ], d ] ] = [ 1, [ [ [ 2 ], 3], 4 ] ];",
"var { foo : bar } = { foo : 1 };",
"var [ a, { foo : bar } ] = [ 2, { foo : 1 } ];",
];
TestRun(test)
.addError(3, "'z' is not defined.")
.addError(8, "'a' is defined but never used.")
.addError(6, "'b' is defined but never used.")
.addError(6, "'c' is defined but never used.")
.addError(4, "'h' is defined but never used.")
.addError(4, "'w' is defined but never used.")
.addError(5, "'o' is defined but never used.")
.addError(6, "'d' is defined but never used.")
.addError(8, "'bar' is defined but never used.")
.test(code, {moz: true, unused: true, undef: true});
test.done();
};
exports["test: destructuring var as esnext"] = function (test) {
var code = [
"var [ a, b, c ] = [ 1, 2, 3 ];",
"var [ a ] = [ 1 ];",
"var [ a ] = [ z ];",
"var [ h, w ] = [ 'hello', 'world' ]; ",
"var [ o ] = [ { o : 1 } ];",
"var [ a, [ [ [ b ], c ], d ] ] = [ 1, [ [ [ 2 ], 3], 4 ] ];",
"var { foo : bar } = { foo : 1 };",
"var [ a, { foo : bar } ] = [ 2, { foo : 1 } ];",
];
TestRun(test)
.addError(3, "'z' is not defined.")
.addError(8, "'a' is defined but never used.")
.addError(6, "'b' is defined but never used.")
.addError(6, "'c' is defined but never used.")
.addError(4, "'h' is defined but never used.")
.addError(4, "'w' is defined but never used.")
.addError(5, "'o' is defined but never used.")
.addError(6, "'d' is defined but never used.")
.addError(8, "'bar' is defined but never used.")
.test(code, {esnext: true, unused: true, undef: true});
test.done();
};
exports["test: destructuring var as es5"] = function (test) {
var code = [
"var [ a, b, c ] = [ 1, 2, 3 ];",
"var [ a ] = [ 1 ];",
"var [ a ] = [ z ];",
"var [ h, w ] = [ 'hello', 'world' ]; ",
"var [ o ] = [ { o : 1 } ];",
"var [ a, [ [ [ b ], c ], d ] ] = [ 1, [ [ [ 2 ], 3], 4 ] ];",
"var { foo : bar } = { foo : 1 };",
"var [ a, { foo : bar } ] = [ 2, { foo : 1 } ];",
];
TestRun(test)
.addError(1, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(2, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(4, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(7, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(8, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(8, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'z' is not defined.")
.addError(8, "'a' is defined but never used.")
.addError(6, "'b' is defined but never used.")
.addError(6, "'c' is defined but never used.")
.addError(4, "'h' is defined but never used.")
.addError(4, "'w' is defined but never used.")
.addError(5, "'o' is defined but never used.")
.addError(6, "'d' is defined but never used.")
.addError(8, "'bar' is defined but never used.")
.test(code, {unused: true, undef: true}); // es5
test.done();
};
exports["test: destructuring var as legacy JS"] = function (test) {
var code = [
"var [ a, b, c ] = [ 1, 2, 3 ];",
"var [ a ] = [ 1 ];",
"var [ a ] = [ z ];",
"var [ h, w ] = [ 'hello', 'world' ]; ",
"var [ o ] = [ { o : 1 } ];",
"var [ a, [ [ [ b ], c ], d ] ] = [ 1, [ [ [ 2 ], 3], 4 ] ];",
"var { foo : bar } = { foo : 1 };",
"var [ a, { foo : bar } ] = [ 2, { foo : 1 } ];",
];
TestRun(test)
.addError(1, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(2, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(4, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(7, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(8, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(8, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'z' is not defined.")
.addError(8, "'a' is defined but never used.")
.addError(6, "'b' is defined but never used.")
.addError(6, "'c' is defined but never used.")
.addError(4, "'h' is defined but never used.")
.addError(4, "'w' is defined but never used.")
.addError(5, "'o' is defined but never used.")
.addError(6, "'d' is defined but never used.")
.addError(8, "'bar' is defined but never used.")
.test(code, {es3: true, unused: true, undef: true});
test.done();
};
exports["test: destructuring var errors"] = function (test) {
var code = [
"var [ a, b, c ] = [ 1, 2, 3 ];",
"var [ a ] = [ 1 ];",
"var [ a ] = [ z ];",
"var [ h, w ] = [ 'hello', 'world' ]; ",
"var [ o ] = [ { o : 1 } ];",
"var [ a, [ [ [ b ], c ], d ] ] = [ 1, [ [ [ 2 ], 3], 4 ] ];",
"var { foo : bar } = { foo : 1 };",
"var [ a, { foo : bar } ] = [ 2, { foo : 1 } ];",
"var [ 1 ] = [ a ];",
"var [ a, b; c ] = [ 1, 2, 3 ];",
"var [ a, b, c ] = [ 1, 2; 3 ];"
];
TestRun(test)
.addError(9, "Expected an identifier and instead saw '1'.")
.addError(9, "Expected ',' and instead saw '1'.")
.addError(9, "Expected an identifier and instead saw ']'.")
.addError(10, "Expected ',' and instead saw ';'.")
.addError(11, "Expected ']' to match '[' from line 11 and instead saw ';'.")
.addError(11, "Missing semicolon.")
.addError(11, "Expected an assignment or function call and instead saw an expression.")
.addError(11, "Missing semicolon.")
.addError(11, "Expected an identifier and instead saw ']'.")
.addError(11, "Expected an assignment or function call and instead saw an expression.")
.addError(3, "'z' is not defined.")
.addError(11, "'a' is defined but never used.")
.addError(11, "'b' is defined but never used.")
.addError(11, "'c' is defined but never used.")
.addError(4, "'h' is defined but never used.")
.addError(4, "'w' is defined but never used.")
.addError(5, "'o' is defined but never used.")
.addError(6, "'d' is defined but never used.")
.addError(8, "'bar' is defined but never used.")
.test(code, {esnext: true, unused: true, undef: true});
test.done();
};
exports["test: destructuring const as moz"] = function (test) {
var code = [
"const [ a, b, c ] = [ 1, 2, 3 ];",
"const [ d ] = [ 1 ];",
"const [ e ] = [ z ];",
"const [ hel, wor ] = [ 'hello', 'world' ]; ",
"const [ o ] = [ { o : 1 } ];",
"const [ f, [ [ [ g ], h ], i ] ] = [ 1, [ [ [ 2 ], 3], 4 ] ];",
"const { foo : bar } = { foo : 1 };",
"const [ j, { foo : foobar } ] = [ 2, { foo : 1 } ];",
"const [ aa, bb ] = yield func();"
];
TestRun(test)
.addError(1, "'a' is defined but never used.")
.addError(1, "'b' is defined but never used.")
.addError(1, "'c' is defined but never used.")
.addError(2, "'d' is defined but never used.")
.addError(3, "'e' is defined but never used.")
.addError(4, "'hel' is defined but never used.")
.addError(4, "'wor' is defined but never used.")
.addError(5, "'o' is defined but never used.")
.addError(6, "'f' is defined but never used.")
.addError(6, "'g' is defined but never used.")
.addError(6, "'h' is defined but never used.")
.addError(6, "'i' is defined but never used.")
.addError(7, "'bar' is defined but never used.")
.addError(8, "'j' is defined but never used.")
.addError(8, "'foobar' is defined but never used.")
.addError(9, "'aa' is defined but never used.")
.addError(9, "'bb' is defined but never used.")
.addError(3, "'z' is not defined.")
.addError(9, "'func' is not defined.")
.test(code, {moz: true, unused: true, undef: true});
test.done();
};
exports["test: destructuring const as esnext"] = function (test) {
var code = [
"const [ a, b, c ] = [ 1, 2, 3 ];",
"const [ d ] = [ 1 ];",
"const [ e ] = [ z ];",
"const [ hel, wor ] = [ 'hello', 'world' ]; ",
"const [ o ] = [ { o : 1 } ];",
"const [ f, [ [ [ g ], h ], i ] ] = [ 1, [ [ [ 2 ], 3], 4 ] ];",
"const { foo : bar } = { foo : 1 };",
"const [ j, { foo : foobar } ] = [ 2, { foo : 1 } ];",
];
TestRun(test)
.addError(1, "'a' is defined but never used.")
.addError(1, "'b' is defined but never used.")
.addError(1, "'c' is defined but never used.")
.addError(2, "'d' is defined but never used.")
.addError(3, "'e' is defined but never used.")
.addError(4, "'hel' is defined but never used.")
.addError(4, "'wor' is defined but never used.")
.addError(5, "'o' is defined but never used.")
.addError(6, "'f' is defined but never used.")
.addError(6, "'g' is defined but never used.")
.addError(6, "'h' is defined but never used.")
.addError(6, "'i' is defined but never used.")
.addError(7, "'bar' is defined but never used.")
.addError(8, "'j' is defined but never used.")
.addError(8, "'foobar' is defined but never used.")
.addError(3, "'z' is not defined.")
.test(code, {esnext: true, unused: true, undef: true});
test.done();
};
exports["test: destructuring const as es5"] = function (test) {
var code = [
"const [ a, b, c ] = [ 1, 2, 3 ];",
"const [ d ] = [ 1 ];",
"const [ e ] = [ z ];",
"const [ hel, wor ] = [ 'hello', 'world' ]; ",
"const [ o ] = [ { o : 1 } ];",
"const [ f, [ [ [ g ], h ], i ] ] = [ 1, [ [ [ 2 ], 3], 4 ] ];",
"const { foo : bar } = { foo : 1 };",
"const [ j, { foo : foobar } ] = [ 2, { foo : 1 } ];",
];
TestRun(test)
.addError(1, "'const' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(1, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(2, "'const' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(2, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'const' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(4, "'const' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(4, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'const' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'const' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(7, "'const' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(7, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(8, "'const' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(8, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(8, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(1, "'a' is defined but never used.")
.addError(1, "'b' is defined but never used.")
.addError(1, "'c' is defined but never used.")
.addError(2, "'d' is defined but never used.")
.addError(3, "'e' is defined but never used.")
.addError(4, "'hel' is defined but never used.")
.addError(4, "'wor' is defined but never used.")
.addError(5, "'o' is defined but never used.")
.addError(6, "'f' is defined but never used.")
.addError(6, "'g' is defined but never used.")
.addError(6, "'h' is defined but never used.")
.addError(6, "'i' is defined but never used.")
.addError(7, "'bar' is defined but never used.")
.addError(8, "'j' is defined but never used.")
.addError(8, "'foobar' is defined but never used.")
.addError(3, "'z' is not defined.")
.test(code, {unused: true, undef: true}); // es5
test.done();
};
exports["test: destructuring const as legacy JS"] = function (test) {
var code = [
"const [ a, b, c ] = [ 1, 2, 3 ];",
"const [ d ] = [ 1 ];",
"const [ e ] = [ z ];",
"const [ hel, wor ] = [ 'hello', 'world' ]; ",
"const [ o ] = [ { o : 1 } ];",
"const [ f, [ [ [ g ], h ], i ] ] = [ 1, [ [ [ 2 ], 3], 4 ] ];",
"const { foo : bar } = { foo : 1 };",
"const [ j, { foo : foobar } ] = [ 2, { foo : 1 } ];",
];
TestRun(test)
.addError(1, "'const' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(1, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(2, "'const' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(2, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'const' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(4, "'const' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(4, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'const' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'const' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(7, "'const' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(7, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(8, "'const' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(8, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(8, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(1, "'a' is defined but never used.")
.addError(1, "'b' is defined but never used.")
.addError(1, "'c' is defined but never used.")
.addError(2, "'d' is defined but never used.")
.addError(3, "'e' is defined but never used.")
.addError(4, "'hel' is defined but never used.")
.addError(4, "'wor' is defined but never used.")
.addError(5, "'o' is defined but never used.")
.addError(6, "'f' is defined but never used.")
.addError(6, "'g' is defined but never used.")
.addError(6, "'h' is defined but never used.")
.addError(6, "'i' is defined but never used.")
.addError(7, "'bar' is defined but never used.")
.addError(8, "'j' is defined but never used.")
.addError(8, "'foobar' is defined but never used.")
.addError(3, "'z' is not defined.")
.test(code, {es3: true, unused: true, undef: true});
test.done();
};
exports["test: destructuring const errors"] = function (test) {
var code = [
"const [ a, b, c ] = [ 1, 2, 3 ];",
"const [ a, b, c ] = [ 1, 2, 3 ];",
"const [ 1 ] = [ a ];",
"const [ k, l; m ] = [ 1, 2, 3 ];",
"const [ n, o, p ] = [ 1, 2; 3 ];"
];
TestRun(test)
.addError(2, "'b' is defined but never used.")
.addError(2, "'c' is defined but never used.")
.addError(4, "'k' is defined but never used.")
.addError(4, "'l' is defined but never used.")
.addError(4, "'m' is defined but never used.")
.addError(5, "'n' is defined but never used.")
.addError(5, "'o' is defined but never used.")
.addError(5, "'p' is defined but never used.")
.addError(2, "const 'a' has already been declared.")
.addError(2, "const 'b' has already been declared.")
.addError(2, "const 'c' has already been declared.")
.addError(3, "Expected an identifier and instead saw '1'.")
.addError(3, "Expected ',' and instead saw '1'.")
.addError(3, "Expected an identifier and instead saw ']'.")
.addError(4, "Expected ',' and instead saw ';'.")
.addError(5, "Expected ']' to match '[' from line 5 and instead saw ';'.")
.addError(5, "Missing semicolon.")
.addError(5, "Expected an assignment or function call and instead saw an expression.")
.addError(5, "Missing semicolon.")
.addError(5, "Expected an identifier and instead saw ']'.")
.addError(5, "Expected an assignment or function call and instead saw an expression.")
.addError(5, "Missing semicolon.")
.test(code, {es3: true, esnext: true, unused: true, undef: true});
test.done();
};
exports["test: destructuring globals as moz"] = function (test) {
var code = [
"var a, b, c, d, h, w, o;",
"[ a, b, c ] = [ 1, 2, 3 ];",
"[ a ] = [ 1 ];",
"[ a ] = [ z ];",
"[ h, w ] = [ 'hello', 'world' ]; ",
"[ o ] = [ { o : 1 } ];",
"[ a, [ [ [ b ], c ], d ] ] = [ 1, [ [ [ 2 ], 3], 4 ] ];",
"[ a, { foo : b } ] = [ 2, { foo : 1 } ];",
];
TestRun(test)
.addError(4, "'z' is not defined.")
.test(code, {moz: true, unused: true, undef: true});
test.done();
};
exports["test: destructuring globals as esnext"] = function (test) {
var code = [
"var a, b, c, d, h, w, o;",
"[ a, b, c ] = [ 1, 2, 3 ];",
"[ a ] = [ 1 ];",
"[ a ] = [ z ];",
"[ h, w ] = [ 'hello', 'world' ]; ",
"[ o ] = [ { o : 1 } ];",
"[ a, [ [ [ b ], c ], d ] ] = [ 1, [ [ [ 2 ], 3], 4 ] ];",
"[ a, { foo : b } ] = [ 2, { foo : 1 } ];",
];
TestRun(test)
.addError(4, "'z' is not defined.")
.test(code, {esnext: true, unused: true, undef: true});
test.done();
};
exports["test: destructuring globals as es5"] = function (test) {
var code = [
"var a, b, c, d, h, w, o;",
"[ a, b, c ] = [ 1, 2, 3 ];",
"[ a ] = [ 1 ];",
"[ a ] = [ z ];",
"[ h, w ] = [ 'hello', 'world' ]; ",
"[ o ] = [ { o : 1 } ];",
"[ a, [ [ [ b ], c ], d ] ] = [ 1, [ [ [ 2 ], 3], 4 ] ];",
"[ a, { foo : b } ] = [ 2, { foo : 1 } ];",
];
TestRun(test)
.addError(4, "'z' is not defined.")
.addError(2, "'destructuring assignment' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'destructuring assignment' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(4, "'destructuring assignment' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'destructuring assignment' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'destructuring assignment' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(7, "'destructuring assignment' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(8, "'destructuring assignment' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(code, {unused: true, undef: true}); // es5
test.done();
};
exports["test: destructuring globals as legacy JS"] = function (test) {
var code = [
"var a, b, c, d, h, w, o;",
"[ a, b, c ] = [ 1, 2, 3 ];",
"[ a ] = [ 1 ];",
"[ a ] = [ z ];",
"[ h, w ] = [ 'hello', 'world' ]; ",
"[ o ] = [ { o : 1 } ];",
"[ a, [ [ [ b ], c ], d ] ] = [ 1, [ [ [ 2 ], 3], 4 ] ];",
"[ a, { foo : b } ] = [ 2, { foo : 1 } ];",
];
TestRun(test)
.addError(4, "'z' is not defined.")
.addError(2, "'destructuring assignment' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'destructuring assignment' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(4, "'destructuring assignment' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'destructuring assignment' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'destructuring assignment' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(7, "'destructuring assignment' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(8, "'destructuring assignment' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(code, {es3: true, unused: true, undef: true});
test.done();
};
exports["test: destructuring globals with syntax error"] = function (test) {
var code = [
"var a, b, c;",
"[ a ] = [ z ];",
"[ 1 ] = [ a ];",
"[ a, b; c ] = [ 1, 2, 3 ];",
"[ a, b, c ] = [ 1, 2; 3 ];"
];
TestRun(test)
.addError(4, "Expected ']' to match '[' from line 4 and instead saw ';'.")
.addError(4, "Expected an assignment or function call and instead saw an expression.")
.addError(4, "Missing semicolon.")
.addError(4, "Expected an assignment or function call and instead saw an expression.")
.addError(4, "Missing semicolon.")
.addError(4, "Expected an identifier and instead saw ']'.")
.addError(4, "Expected an operator and instead saw '='.")
.addError(4, "Expected an operator and instead saw '['.")
.addError(4, "Expected an assignment or function call and instead saw an expression.")
.addError(4, "Missing semicolon.")
.addError(4, "Expected an assignment or function call and instead saw an expression.")
.addError(4, "Expected an assignment or function call and instead saw an expression.")
.addError(4, "Missing semicolon.")
.addError(4, "Expected an identifier and instead saw ']'.")
.addError(4, "Expected an assignment or function call and instead saw an expression.")
.addError(5, "Expected ']' to match '[' from line 5 and instead saw ';'.")
.addError(5, "Missing semicolon.")
.addError(5, "Expected an assignment or function call and instead saw an expression.")
.addError(5, "Missing semicolon.")
.addError(5, "Expected an identifier and instead saw ']'.")
.addError(5, "Expected an assignment or function call and instead saw an expression.")
.addError(2, "'z' is not defined.")
.test(code, {esnext: true, unused: true, undef: true});
test.done();
};
exports["test: destructuring assign of empty values as moz"] = function (test) {
var code = [
"var [ a ] = [ 1, 2 ];",
"var [ c, d ] = [ 1 ];",
"var [ e, , f ] = [ 3, , 4 ];"
];
TestRun(test)
.addError(1, "'a' is defined but never used.")
.addError(2, "'c' is defined but never used.")
.addError(2, "'d' is defined but never used.")
.addError(3, "'e' is defined but never used.")
.addError(3, "'f' is defined but never used.")
.test(code, {moz: true, unused: true, undef: true, laxcomma: true});
test.done();
};
exports["test: destructuring assign of empty values as esnext"] = function (test) {
var code = [
"var [ a ] = [ 1, 2 ];",
"var [ c, d ] = [ 1 ];",
"var [ e, , f ] = [ 3, , 4 ];"
];
TestRun(test)
.addError(1, "'a' is defined but never used.")
.addError(2, "'c' is defined but never used.")
.addError(2, "'d' is defined but never used.")
.addError(3, "'e' is defined but never used.")
.addError(3, "'f' is defined but never used.")
.test(code, {esnext: true, unused: true, undef: true});
test.done();
};
exports["test: destructuring assign of empty values as es5"] = function (test) {
var code = [
"var [ a ] = [ 1, 2 ];",
"var [ c, d ] = [ 1 ];",
"var [ e, , f ] = [ 3, , 4 ];"
];
TestRun(test)
.addError(1, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(1, "'a' is defined but never used.")
.addError(2, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(2, "'c' is defined but never used.")
.addError(2, "'d' is defined but never used.")
.addError(3, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'e' is defined but never used.")
.addError(3, "'f' is defined but never used.")
.test(code, {unused: true, undef: true}); // es5
test.done();
};
exports["test: destructuring assign of empty values as JS legacy"] = function (test) {
var code = [
"var [ a ] = [ 1, 2 ];",
"var [ c, d ] = [ 1 ];",
"var [ e, , f ] = [ 3, , 4 ];"
];
TestRun(test)
.addError(1, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(1, "'a' is defined but never used.")
.addError(2, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(2, "'c' is defined but never used.")
.addError(2, "'d' is defined but never used.")
.addError(3, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'e' is defined but never used.")
.addError(3, "'f' is defined but never used.")
.addError(3, "Extra comma. (it breaks older versions of IE)")
.test(code, {es3: true, unused: true, undef: true});
test.done();
};
exports["test: array element assignment inside array"] = function (test) {
var code = [
"var a1 = {};",
"var a2 = [function f() {a1[0] = 1;}];",
];
TestRun(test)
.test(code);
test.done();
};
exports["test: let statement as moz"] = function (test) {
var code = [
"let x = 1;",
"{",
" let y = 3 ;",
" {",
" let z = 2;",
" print(x + ' ' + y + ' ' + z);",
" }",
" print(x + ' ' + y);",
"}",
"print(x);"
];
TestRun(test)
.test(code, {moz: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: let statement as esnext"] = function (test) {
var code = [
"let x = 1;",
"{",
" let y = 3 ;",
" {",
" let z = 2;",
" print(x + ' ' + y + ' ' + z);",
" }",
" print(x + ' ' + y);",
"}",
"print(x);"
];
TestRun(test)
.test(code, {esnext: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: let statement as es5"] = function (test) {
var code = [
"let x = 1;",
"{",
" let y = 3 ;",
" {",
" let z = 2;",
" print(x + ' ' + y + ' ' + z);",
" }",
" print(x + ' ' + y);",
"}",
"print(x);"
];
TestRun(test)
.addError(1, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(code, {unused: true, undef: true, predef: ["print"]}); // es5
test.done();
};
exports["test: let statement as legacy JS"] = function (test) {
var code = [
"let x = 1;",
"{",
" let y = 3 ;",
" {",
" let z = 2;",
" print(x + ' ' + y + ' ' + z);",
" }",
" print(x + ' ' + y);",
"}",
"print(x);"
];
TestRun(test)
.addError(1, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(code, {es3: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: let statement out of scope as moz"] = function (test) {
var code = [
"let x = 1;",
"{",
" let y = 3 ;",
" {",
" let z = 2;",
" }",
" print(z);",
"}",
"print(y);",
];
TestRun(test)
.addError(1, "'x' is defined but never used.")
.addError(5, "'z' is defined but never used.")
.addError(3, "'y' is defined but never used.")
.addError(7, "'z' is not defined.")
.addError(9, "'y' is not defined.")
.test(code, {moz: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: let statement out of scope as esnext"] = function (test) {
var code = [
"let x = 1;",
"{",
" let y = 3 ;",
" {",
" let z = 2;",
" }",
" print(z);",
"}",
"print(y);",
];
TestRun(test)
.addError(1, "'x' is defined but never used.")
.addError(5, "'z' is defined but never used.")
.addError(3, "'y' is defined but never used.")
.addError(7, "'z' is not defined.")
.addError(9, "'y' is not defined.")
.test(code, {esnext: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: let statement out of scope as es5"] = function (test) {
var code = [
"let x = 1;",
"{",
" let y = 3 ;",
" {",
" let z = 2;",
" }",
" print(z);",
"}",
"print(y);",
];
TestRun(test)
.addError(1, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(1, "'x' is defined but never used.")
.addError(5, "'z' is defined but never used.")
.addError(3, "'y' is defined but never used.")
.addError(7, "'z' is not defined.")
.addError(9, "'y' is not defined.")
.test(code, {unused: true, undef: true, predef: ["print"]}); // es5
test.done();
};
exports["test: let statement out of scope as legacy JS"] = function (test) {
var code = [
"let x = 1;",
"{",
" let y = 3 ;",
" {",
" let z = 2;",
" }",
" print(z);",
"}",
"print(y);",
];
TestRun(test)
.addError(1, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(1, "'x' is defined but never used.")
.addError(5, "'z' is defined but never used.")
.addError(3, "'y' is defined but never used.")
.addError(7, "'z' is not defined.")
.addError(9, "'y' is not defined.")
.test(code, {es3: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: let statement in functions as moz"] = function (test) {
var code = [
"let x = 1;",
"function foo() {",
" let y = 3 ;",
" function bar() {",
" let z = 2;",
" print(x);",
" print(z);",
" }",
" print(y);",
" bar();",
"}",
"foo();"
];
TestRun(test)
.test(code, {moz: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: let statement in functions as esnext"] = function (test) {
var code = [
"let x = 1;",
"function foo() {",
" let y = 3 ;",
" function bar() {",
" let z = 2;",
" print(x);",
" print(z);",
" }",
" print(y);",
" bar();",
"}",
"foo();"
];
TestRun(test)
.test(code, {esnext: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: let statement in functions as es5"] = function (test) {
var code = [
"let x = 1;",
"function foo() {",
" let y = 3 ;",
" function bar() {",
" let z = 2;",
" print(x);",
" print(z);",
" }",
" print(y);",
" bar();",
"}",
"foo();"
];
TestRun(test)
.addError(1, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(code, {unused: true, undef: true, predef: ["print"]}); // es5
test.done();
};
exports["test: let statement in functions as legacy JS"] = function (test) {
var code = [
"let x = 1;",
"function foo() {",
" let y = 3 ;",
" function bar() {",
" let z = 2;",
" print(x);",
" print(z);",
" }",
" print(y);",
" bar();",
"}",
"foo();"
];
TestRun(test)
.addError(1, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(code, {es3: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: let statement not in scope as moz"] = function (test) {
var code = [
"let x = 1;",
"function foo() {",
" let y = 3 ;",
" let bar = function () {",
" print(x);",
" let z = 2;",
" };",
" print(z);",
"}",
"print(y);",
"bar();",
"foo();",
];
TestRun(test)
.addError(6, "'z' is defined but never used.")
.addError(3, "'y' is defined but never used.")
.addError(4, "'bar' is defined but never used.")
.addError(8, "'z' is not defined.")
.addError(10, "'y' is not defined.")
.addError(11, "'bar' is not defined.")
.test(code, {moz: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: let statement not in scope as esnext"] = function (test) {
var code = [
"let x = 1;",
"function foo() {",
" let y = 3 ;",
" let bar = function () {",
" print(x);",
" let z = 2;",
" };",
" print(z);",
"}",
"print(y);",
"bar();",
"foo();",
];
TestRun(test)
.addError(6, "'z' is defined but never used.")
.addError(3, "'y' is defined but never used.")
.addError(4, "'bar' is defined but never used.")
.addError(8, "'z' is not defined.")
.addError(10, "'y' is not defined.")
.addError(11, "'bar' is not defined.")
.test(code, {esnext: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: let statement not in scope as es5"] = function (test) {
var code = [
"let x = 1;",
"function foo() {",
" let y = 3 ;",
" let bar = function () {",
" print(x);",
" let z = 2;",
" };",
" print(z);",
"}",
"print(y);",
"bar();",
"foo();",
];
TestRun(test)
.addError(1, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(4, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'z' is defined but never used.")
.addError(3, "'y' is defined but never used.")
.addError(4, "'bar' is defined but never used.")
.addError(8, "'z' is not defined.")
.addError(10, "'y' is not defined.")
.addError(11, "'bar' is not defined.")
.test(code, {unused: true, undef: true, predef: ["print"]}); // es5
test.done();
};
exports["test: let statement not in scope as legacy JS"] = function (test) {
var code = [
"let x = 1;",
"function foo() {",
" let y = 3 ;",
" let bar = function () {",
" print(x);",
" let z = 2;",
" };",
" print(z);",
"}",
"print(y);",
"bar();",
"foo();",
];
TestRun(test)
.addError(1, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(4, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'z' is defined but never used.")
.addError(3, "'y' is defined but never used.")
.addError(4, "'bar' is defined but never used.")
.addError(8, "'z' is not defined.")
.addError(10, "'y' is not defined.")
.addError(11, "'bar' is not defined.")
.test(code, {es3: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: let statement in for loop as moz"] = function (test) {
var code = [
"var obj={foo: 'bar', bar: 'foo'};",
"for ( let [n, v] in Iterator(obj) ) {",
" print('Name: ' + n + ', Value: ' + v);",
"}",
"for (let i in [1, 2, 3, 4]) {",
" print(i);",
"}",
"for (let i in [1, 2, 3, 4]) {",
" print(i);",
"}",
"for (let i = 0; i<15; ++i) {",
" print(i);",
"}",
"for (let i=i ; i < 10 ; i++ ) {",
"print(i);",
"}"
];
TestRun(test)
.test(code, {moz: true, unused: true, undef: true, predef: ["print", "Iterator"]});
test.done();
};
exports["test: let statement in for loop as esnext"] = function (test) {
var code = [
"var obj={foo: 'bar', bar: 'foo'};",
"for ( let [n, v] in Iterator(obj) ) {",
" print('Name: ' + n + ', Value: ' + v);",
"}",
"for (let i in [1, 2, 3, 4]) {",
" print(i);",
"}",
"for (let i in [1, 2, 3, 4]) {",
" print(i);",
"}",
"for (let i = 0; i<15; ++i) {",
" print(i);",
"}",
"for (let i=i ; i < 10 ; i++ ) {",
"print(i);",
"}"
];
TestRun(test)
.test(code, {esnext: true, unused: true, undef: true, predef: ["print", "Iterator"]});
test.done();
};
exports["test: let statement in for loop as es5"] = function (test) {
var code = [
"var obj={foo: 'bar', bar: 'foo'};",
"for ( let [n, v] in Iterator(obj) ) {",
" print('Name: ' + n + ', Value: ' + v);",
"}",
"for (let i in [1, 2, 3, 4]) {",
" print(i);",
"}",
"for (let i in [1, 2, 3, 4]) {",
" print(i);",
"}",
"for (let i = 0; i<15; ++i) {",
" print(i);",
"}",
"for (let i=i ; i < 10 ; i++ ) {",
"print(i);",
"}"
];
TestRun(test)
.addError(2, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(2, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(8, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(11, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(14, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(code, {unused: true, undef: true, predef: ["print", "Iterator"]}); // es5
test.done();
};
exports["test: let statement in for loop as legacy JS"] = function (test) {
var code = [
"var obj={foo: 'bar', bar: 'foo'};",
"for ( let [n, v] in Iterator(obj) ) {",
" print('Name: ' + n + ', Value: ' + v);",
"}",
"for (let i in [1, 2, 3, 4]) {",
" print(i);",
"}",
"for (let i in [1, 2, 3, 4]) {",
" print(i);",
"}",
"for (let i = 0; i<15; ++i) {",
" print(i);",
"}",
"for (let i=i ; i < 10 ; i++ ) {",
"print(i);",
"}"
];
TestRun(test)
.addError(2, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(2, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(8, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(11, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(14, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(code, {es3: true, unused: true, undef: true, predef: ["print", "Iterator"]});
test.done();
};
exports["test: let statement in destructured for loop as moz"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"var people = [",
"{",
" name: 'Mike Smith',",
" family: {",
" mother: 'Jane Smith',",
" father: 'Harry Smith',",
" sister: 'Samantha Smith'",
" },",
" age: 35",
"},",
"{",
" name: 'Tom Jones',",
" family: {",
" mother: 'Norah Jones',",
" father: 'Richard Jones',",
" brother: 'Howard Jones'",
" },",
" age: 25",
"}",
"];",
"for (let {name: n, family: { father: f } } in people) {",
"print('Name: ' + n + ', Father: ' + f);",
"}"
];
TestRun(test)
.test(code, {moz: true, unused: true,
undef: true, predef: ["print"]});
test.done();
};
exports["test: let statement in destructured for loop as esnext"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"var people = [",
"{",
" name: 'Mike Smith',",
" family: {",
" mother: 'Jane Smith',",
" father: 'Harry Smith',",
" sister: 'Samantha Smith'",
" },",
" age: 35",
"},",
"{",
" name: 'Tom Jones',",
" family: {",
" mother: 'Norah Jones',",
" father: 'Richard Jones',",
" brother: 'Howard Jones'",
" },",
" age: 25",
"}",
"];",
"for (let {name: n, family: { father: f } } in people) {",
"print('Name: ' + n + ', Father: ' + f);",
"}"
];
TestRun(test)
.test(code, {esnext: true, unused: true,
undef: true, predef: ["print"]});
test.done();
};
exports["test: let statement in destructured for loop as es5"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"var people = [",
"{",
" name: 'Mike Smith',",
" family: {",
" mother: 'Jane Smith',",
" father: 'Harry Smith',",
" sister: 'Samantha Smith'",
" },",
" age: 35",
"},",
"{",
" name: 'Tom Jones',",
" family: {",
" mother: 'Norah Jones',",
" father: 'Richard Jones',",
" brother: 'Howard Jones'",
" },",
" age: 25",
"}",
"];",
"for (let {name: n, family: { father: f } } in people) {",
"print('Name: ' + n + ', Father: ' + f);",
"}"
];
TestRun(test)
.addError(21, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(21, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(code, {unused: true, undef: true, predef: ["print"]}); // es5
test.done();
};
exports["test: let statement in destructured for loop as legacy JS"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"var people = [",
"{",
" name: 'Mike Smith',",
" family: {",
" mother: 'Jane Smith',",
" father: 'Harry Smith',",
" sister: 'Samantha Smith'",
" },",
" age: 35",
"},",
"{",
" name: 'Tom Jones',",
" family: {",
" mother: 'Norah Jones',",
" father: 'Richard Jones',",
" brother: 'Howard Jones'",
" },",
" age: 25",
"}",
"];",
"for (let {name: n, family: { father: f } } in people) {",
"print('Name: ' + n + ', Father: ' + f);",
"}"
];
TestRun(test)
.addError(21, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(21, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(code, {es3: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: let statement (as seen in jetpack)"] = function (test) {
// Example taken from jetpack/addons sdk library from Mozilla project
var code = [
"const { Cc, Ci } = require('chrome');",
"// add a text/unicode flavor (html converted to plain text)",
"let (str = Cc['@mozilla.org/supports-string;1'].",
" createInstance(Ci.nsISupportsString),",
" converter = Cc['@mozilla.org/feed-textconstruct;1'].",
" createInstance(Ci.nsIFeedTextConstruct))",
"{",
"converter.type = 'html';",
"converter.text = options.data;",
"str.data = converter.plainText();",
"xferable.addDataFlavor('text/unicode');",
"xferable.setTransferData('text/unicode', str, str.data.length * 2);",
"}"
];
TestRun(test)
.test(code, {moz: true, unused: true, undef: true,
predef: ["require", "xferable", "options"]});
test.done();
};
exports["test: let statement (as seen in jetpack) as esnext"] = function (test) {
// Example taken from jetpack/addons sdk library from Mozilla project
var code = [
"const { Cc, Ci } = require('chrome');",
"// add a text/unicode flavor (html converted to plain text)",
"let (str = Cc['@mozilla.org/supports-string;1'].",
" createInstance(Ci.nsISupportsString),",
" converter = Cc['@mozilla.org/feed-textconstruct;1'].",
" createInstance(Ci.nsIFeedTextConstruct))",
"{",
"converter.type = 'html';",
"converter.text = options.data;",
"str.data = converter.plainText();",
"xferable.addDataFlavor('text/unicode');",
"xferable.setTransferData('text/unicode', str, str.data.length * 2);",
"}"
];
TestRun(test)
.addError(3, "'let block' is only available in Mozilla JavaScript extensions (use moz option).")
.test(code, {esnext: true, unused: true, undef: true,
predef: ["require", "xferable", "options"]});
test.done();
};
exports["test: let statement (as seen in jetpack) as es5"] = function (test) {
// Example taken from jetpack/addons sdk library from Mozilla project
var code = [
"const { Cc, Ci } = require('chrome');",
"// add a text/unicode flavor (html converted to plain text)",
"let (str = Cc['@mozilla.org/supports-string;1'].",
" createInstance(Ci.nsISupportsString),",
" converter = Cc['@mozilla.org/feed-textconstruct;1'].",
" createInstance(Ci.nsIFeedTextConstruct))",
"{",
"converter.type = 'html';",
"converter.text = options.data;",
"str.data = converter.plainText();",
"xferable.addDataFlavor('text/unicode');",
"xferable.setTransferData('text/unicode', str, str.data.length * 2);",
"}"
];
TestRun(test)
.addError(1, "'const' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(1, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'let block' is only available in Mozilla JavaScript extensions (use moz option).")
.test(code, {unused: true, undef: true,
predef: ["require", "xferable", "options"]}); // es5
test.done();
};
exports["test: let statement (as seen in jetpack) as legacy JS"] = function (test) {
// Example taken from jetpack/addons sdk library from Mozilla project
var code = [
"const { Cc, Ci } = require('chrome');",
"// add a text/unicode flavor (html converted to plain text)",
"let (str = Cc['@mozilla.org/supports-string;1'].",
" createInstance(Ci.nsISupportsString),",
" converter = Cc['@mozilla.org/feed-textconstruct;1'].",
" createInstance(Ci.nsIFeedTextConstruct))",
"{",
"converter.type = 'html';",
"converter.text = options.data;",
"str.data = converter.plainText();",
"xferable.addDataFlavor('text/unicode');",
"xferable.setTransferData('text/unicode', str, str.data.length * 2);",
"}"
];
TestRun(test)
.addError(1, "'const' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(1, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'let block' is only available in Mozilla JavaScript extensions (use moz option).")
.test(code, {es3: true, unused: true, undef: true,
predef: ["require", "xferable", "options"]});
test.done();
};
exports["test: let block and let expression"] = function (test) {
// Example taken from jetpack/addons sdk library from Mozilla project
var code = [
"let (x=1, y=2, z=3)",
"{",
" let(t=4) print(x, y, z, t);",
" print(let(u=4) u,x);",
"}"
];
TestRun(test)
.test(code, {moz: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: let block and let expression as esnext"] = function (test) {
// Example taken from jetpack/addons sdk library from Mozilla project
var code = [
"let (x=1, y=2, z=3)",
"{",
" let(t=4) print(x, y, z, t);",
" print(let(u=4) u,x);",
"}"
];
TestRun(test)
.addError(1, "'let block' is only available in Mozilla JavaScript extensions (use moz option).")
.addError(3, "'let block' is only available in Mozilla JavaScript extensions (use moz option).")
.addError(4, "'let expressions' is only available in Mozilla JavaScript extensions " +
"(use moz option).")
.test(code, {esnext: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: let block and let expression as es5"] = function (test) {
// Example taken from jetpack/addons sdk library from Mozilla project
var code = [
"let (x=1, y=2, z=3)",
"{",
" let(t=4) print(x, y, z, t);",
" print(let(u=4) u,x);",
"}"
];
TestRun(test)
.addError(1, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(1, "'let block' is only available in Mozilla JavaScript extensions (use moz option).")
.addError(3, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'let block' is only available in Mozilla JavaScript extensions (use moz option).")
.addError(4, "'let expressions' is only available in Mozilla JavaScript extensions " +
"(use moz option).")
.addError(4, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(code, {unused: true, undef: true, predef: ["print"]}); // es5
test.done();
};
exports["test: let block and let expression as legacy JS"] = function (test) {
// Example taken from jetpack/addons sdk library from Mozilla project
var code = [
"let (x=1, y=2, z=3)",
"{",
" let(t=4) print(x, y, z, t);",
" print(let(u=4) u,x);",
"}"
];
TestRun(test)
.addError(1, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(1, "'let block' is only available in Mozilla JavaScript extensions (use moz option).")
.addError(3, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'let block' is only available in Mozilla JavaScript extensions (use moz option).")
.addError(4, "'let expressions' is only available in Mozilla JavaScript extensions " +
"(use moz option).")
.addError(4, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(code, {es3: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["make sure let variables are not treated as globals"] = function (test) {
// This is a regression test for GH-1362
var code = [
"function sup() {",
"if (true) {",
"let closed = 1;",
"closed = 2;",
"}",
"if (true) {",
"if (true) {",
"let closed = 1;",
"closed = 2;",
"}",
"}",
"}"
];
TestRun(test).test(code, { esnext: true, browser: true });
test.done();
};
exports["make sure var variables can shadow let variables"] = function (test) {
// This is a regression test for GH-1394
var code = [
"let a = 1;",
"let b = 2;",
"var c = 3;",
"function sup(a) {",
"var b = 4;",
"let c = 5;",
"let d = 6;",
"if (false) {",
"var d = 7;",
"}",
"return b + c + a + d;",
"}",
"sup();"
];
TestRun(test)
.addError(1, "'a' is defined but never used.")
.addError(2, "'b' is defined but never used.")
.addError(3, "'c' is defined but never used.")
.addError(7, "'d' is defined but never used.")
.test(code, { esnext: true, unused: true, undef: true, funcscope: true });
test.done();
};
exports["test destructuring function as moz"] = function (test) {
// Example from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"function userId({id}) {",
" return id;",
"}",
"function whois({displayName: displayName, fullName: {firstName: name}}) {",
" print(displayName + ' is ' + name);",
"}",
"var user = {id: 42, displayName: 'jdoe', fullName: {firstName: 'John', lastName: 'Doe'}};",
"print('userId: ' + userId(user));",
"whois(user);"
];
TestRun(test)
.test(code, {moz: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test destructuring function as esnext"] = function (test) {
// Example from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"function userId({id}) {",
" return id;",
"}",
"function whois({displayName: displayName, fullName: {firstName: name}}) {",
" print(displayName + ' is ' + name);",
"}",
"var user = {id: 42, displayName: 'jdoe', fullName: {firstName: 'John', lastName: 'Doe'}};",
"print('userId: ' + userId(user));",
"whois(user);"
];
TestRun(test)
.test(code, {esnext: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test destructuring function as es5"] = function (test) {
// Example from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"function userId({id}) {",
" return id;",
"}",
"function whois({displayName: displayName, fullName: {firstName: name}}) {",
" print(displayName + ' is ' + name);",
"}",
"var user = {id: 42, displayName: 'jdoe', fullName: {firstName: 'John', lastName: 'Doe'}};",
"print('userId: ' + userId(user));",
"whois(user);"
];
TestRun(test)
.addError(1, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(4, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(4, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(code, {unused: true, undef: true, predef: ["print"]}); // es5
test.done();
};
exports["test destructuring function as legacy JS"] = function (test) {
// Example from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"function userId({id}) {",
" return id;",
"}",
"function whois({displayName: displayName, fullName: {firstName: name}}) {",
" print(displayName + ' is ' + name);",
"}",
"var user = {id: 42, displayName: 'jdoe', fullName: {firstName: 'John', lastName: 'Doe'}};",
"print('userId: ' + userId(user));",
"whois(user);"
];
TestRun(test)
.addError(1, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(4, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(4, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(code, {es3: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: invalid for each"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"for each (let i = 0; i<15; ++i) {",
" print(i);",
"}"
];
TestRun(test)
.addError(1, "Invalid for each loop.")
.test(code, {moz: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: invalid for each as esnext"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"for each (let i = 0; i<15; ++i) {",
" print(i);",
"}"
];
TestRun(test)
.addError(1, "Invalid for each loop.")
.addError(1, "'for each' is only available in Mozilla JavaScript extensions (use moz option).")
.test(code, {esnext: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: invalid for each as ES5"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"for each (let i = 0; i<15; ++i) {",
" print(i);",
"}"
];
TestRun(test)
.addError(1, "Invalid for each loop.")
.addError(1, "'for each' is only available in Mozilla JavaScript extensions (use moz option).")
.addError(1, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(code, {unused: true, undef: true, predef: ["print"]}); // es5
test.done();
};
exports["test: invalid for each as legacy JS"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"for each (let i = 0; i<15; ++i) {",
" print(i);",
"}"
];
TestRun(test)
.addError(1, "Invalid for each loop.")
.addError(1, "'for each' is only available in Mozilla JavaScript extensions (use moz option).")
.addError(1, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(code, {es3: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: esnext generator"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"function* fib() {",
" var i = 0, j = 1;",
" while (true) {",
" yield i;",
" [i, j] = [j, i + j];",
" }",
"}",
"var g = fib();",
"for (var i = 0; i < 10; i++)",
" print(g.next());"
];
TestRun(test)
.test(code, {esnext: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: esnext generator as moz extension"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"function* fib() {",
" var i = 0, j = 1;",
" while (true) {",
" yield i;",
" [i, j] = [j, i + j];",
" }",
"}",
"var g = fib();",
"for (var i = 0; i < 10; i++)",
" print(g.next());"
];
TestRun(test)
.addError(1, "'function*' is only available in ES6 (use esnext option).")
.test(code, {moz: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: esnext generator as es5"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"function* fib() {",
" var i = 0, j = 1;",
" while (true) {",
" yield i;",
" [i, j] = [j, i + j];",
" }",
"}",
"var g = fib();",
"for (var i = 0; i < 10; i++)",
" print(g.next());"
];
TestRun(test)
.addError(1, "'function*' is only available in ES6 (use esnext option).")
.addError(4, "'yield' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'destructuring assignment' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(code, {unused: true, undef: true, predef: ["print"]}); // es5
test.done();
};
exports["test: esnext generator as legacy JS"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"function* fib() {",
" var i = 0, j = 1;",
" while (true) {",
" yield i;",
" [i, j] = [j, i + j];",
" }",
"}",
"var g = fib();",
"for (var i = 0; i < 10; i++)",
" print(g.next());"
];
TestRun(test)
.addError(1, "'function*' is only available in ES6 (use esnext option).")
.addError(4, "'yield' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'destructuring assignment' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(code, {es3: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: esnext generator without yield"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"function* fib() {",
" var i = 0, j = 1;",
" while (true) {",
" [i, j] = [j, i + j];",
" return i;",
" }",
"}",
"var g = fib();",
"for (let i = 0; i < 10; i++)",
" print(g.next());"
];
TestRun(test)
.addError(7, "A generator function shall contain a yield statement.")
.test(code, {esnext: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: esnext generator without yield and check turned off"] = function (test) {
var code = [
"function* emptyGenerator() {}",
"emptyGenerator();"
];
TestRun(test)
.test(code, {esnext: true, noyield: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: mozilla generator"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"function fib() {",
" var i = 0, j = 1;",
" while (true) {",
" yield i;",
" [i, j] = [j, i + j];",
" }",
"}",
"var g = fib();",
"for (let i = 0; i < 10; i++)",
" print(g.next());"
];
TestRun(test)
.test(code, {moz: true, unused: true, undef: true, predef: ["print", "Iterator"]});
test.done();
};
exports["test: mozilla generator as esnext"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"function fib() {",
" var i = 0, j = 1;",
" while (true) {",
" yield i;",
" [i, j] = [j, i + j];",
" }",
"}",
"var g = fib();",
"for (let i = 0; i < 10; i++)",
" print(g.next());"
];
TestRun(test)
.addError(4,
"A yield statement shall be within a generator function (with syntax: `function*`)")
.test(code, {esnext: true, unused: true, undef: true, predef: ["print", "Iterator"]});
test.done();
};
exports["test: yield statement within try-catch"] = function (test) {
// see issue: https://github.com/jshint/jshint/issues/1505
var code = [
"function* fib() {",
" try {",
" yield 1;",
" } catch (err) {",
" yield err;",
" }",
"}",
"var g = fib();",
"for (let i = 0; i < 10; i++)",
" print(g.next());"
];
TestRun(test)
.test(code, {esnext: true, unused: true, undef: true, predef: ["print", "Iterator"]});
test.done();
};
exports["test: mozilla generator as es5"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"function fib() {",
" var i = 0, j = 1;",
" while (true) {",
" yield i;",
" [i, j] = [j, i + j];",
" }",
"}",
"var g = fib();",
"for (let i = 0; i < 10; i++)",
" print(g.next());"
];
TestRun(test)
.addError(4, "'yield' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'destructuring assignment' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(9, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(code, {unused: true, undef: true, predef: ["print", "Iterator"]}); // es5
test.done();
};
exports["test: mozilla generator as legacy JS"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"function fib() {",
" var i = 0, j = 1;",
" while (true) {",
" yield i;",
" [i, j] = [j, i + j];",
" }",
"}",
"var g = fib();",
"for (let i = 0; i < 10; i++)",
" print(g.next());"
];
TestRun(test)
.addError(4, "'yield' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'destructuring assignment' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(9, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(code, {es3: true, unused: true, undef: true, predef: ["print", "Iterator"]});
test.done();
};
exports["test: array comprehension"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"function *range(begin, end) {",
" for (let i = begin; i < end; ++i) {",
" yield i;",
" }",
"}",
"var ten_squares = [for (i of range(0, 10)) i * i];",
"var evens = [for (i of range(0, 21)) if (i % 2 === 0) i];",
"print('squares:', ten_squares);",
"print('evens:', evens);"
];
TestRun(test)
.test(code, {esnext: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: moz-style array comprehension"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"function range(begin, end) {",
" for (let i = begin; i < end; ++i) {",
" yield i;",
" }",
"}",
"var ten_squares = [i * i for each (i in range(0, 10))];",
"var evens = [i for each (i in range(0, 21)) if (i % 2 === 0)];",
"print('squares:', ten_squares);",
"print('evens:', evens);"
];
TestRun(test)
.test(code, {moz: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: array comprehension with for..of"] = function (test) {
// example adapted from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"function *range(begin, end) {",
" for (let i = begin; i < end; ++i) {",
" yield i;",
" }",
"}",
"var ten_squares = [for (i of range(0, 10)) i * i];",
"var evens = [for (i of range(0, 21)) if (i % 2 === 0) i];",
"print('squares:', ten_squares);",
"print('evens:', evens);"
];
TestRun(test)
.test(code, {esnext: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: moz-style array comprehension with for..of"] = function (test) {
// example adapted from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"function range(begin, end) {",
" for (let i = begin; i < end; ++i) {",
" yield i;",
" }",
"}",
"var ten_squares = [i * i for (i of range(0, 10))];",
"var evens = [i for (i of range(0, 21)) if (i % 2 === 0)];",
"print('squares:', ten_squares);",
"print('evens:', evens);"
];
TestRun(test)
.test(code, {moz: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: array comprehension with unused variables"] = function (test) {
var code = [
"var ret = [for (i of unknown) i];",
"print('ret:', ret);",
];
TestRun(test)
.addError(1, "'unknown' is not defined.")
.test(code, {esnext: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: moz-style array comprehension with unused variables"] = function (test) {
var code = [
"var ret = [i for (i of unknown)];",
"print('ret:', ret);",
];
TestRun(test)
.addError(1, "'unknown' is not defined.")
.test(code, {moz: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: moz-style array comprehension as esnext"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"function range(begin, end) {",
" for (let i = begin; i < end; ++i) {",
" yield i;",
" }",
"}",
"var ten_squares = [i * i for each (i in range(0, 10))];",
"var evens = [i for each (i in range(0, 21)) if (i % 2 === 0)];",
"print('squares:', ten_squares);",
"print('evens:', evens);"
];
TestRun(test)
.addError(3, "A yield statement shall be within a generator function (with syntax: " +
"`function*`)")
.addError(6, "Expected 'for' and instead saw 'i'.")
.addError(6, "'for each' is only available in Mozilla JavaScript extensions (use moz option).")
.addError(7, "Expected 'for' and instead saw 'i'.")
.addError(7, "'for each' is only available in Mozilla JavaScript extensions (use moz option).")
.test(code, {esnext: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: array comprehension as es5"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"function *range(begin, end) {",
" for (let i = begin; i < end; ++i) {",
" yield i;",
" }",
"}",
"var ten_squares = [for (i of range(0, 10)) i * i];",
"var evens = [for (i of range(0, 21)) if (i % 2 === 0) i];",
"print('squares:', ten_squares);",
"print('evens:', evens);"
];
TestRun(test)
.addError(1, "'function*' is only available in ES6 (use esnext option).")
.addError(2, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'yield' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.addError(7, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.test(code, {unused: true, undef: true, predef: ["print"]}); // es5
test.done();
};
exports["test: moz-style array comprehension as es5"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"function range(begin, end) {",
" for (let i = begin; i < end; ++i) {",
" yield i;",
" }",
"}",
"var ten_squares = [i * i for each (i in range(0, 10))];",
"var evens = [i for each (i in range(0, 21)) if (i % 2 === 0)];",
"print('squares:', ten_squares);",
"print('evens:', evens);"
];
TestRun(test)
.addError(2, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'yield' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.addError(6, "Expected 'for' and instead saw 'i'.")
.addError(6, "'for each' is only available in Mozilla JavaScript extensions (use moz option).")
.addError(7, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.addError(7, "Expected 'for' and instead saw 'i'.")
.addError(7, "'for each' is only available in Mozilla JavaScript extensions (use moz option).")
.test(code, {unused: true, undef: true, predef: ["print"]}); // es5
test.done();
};
exports["test: array comprehension as legacy JS"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"function range(begin, end) {",
" for (let i = begin; i < end; ++i) {",
" yield i;",
" }",
"}",
"var ten_squares = [for (i of range(0, 10)) i * i];",
"var evens = [for (i of range(0, 21)) if (i % 2 === 0) i];",
"print('squares:', ten_squares);",
"print('evens:', evens);"
];
TestRun(test)
.addError(2, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'yield' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.addError(7, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.test(code, {es3: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: moz-style array comprehension as legacy JS"] = function (test) {
// example taken from https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7
var code = [
"function range(begin, end) {",
" for (let i = begin; i < end; ++i) {",
" yield i;",
" }",
"}",
"var ten_squares = [i * i for each (i in range(0, 10))];",
"var evens = [i for each (i in range(0, 21)) if (i % 2 === 0)];",
"print('squares:', ten_squares);",
"print('evens:', evens);"
];
TestRun(test)
.addError(2, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'yield' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.addError(6, "Expected 'for' and instead saw 'i'.")
.addError(6, "'for each' is only available in Mozilla JavaScript extensions (use moz option).")
.addError(7, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.addError(7, "Expected 'for' and instead saw 'i'.")
.addError(7, "'for each' is only available in Mozilla JavaScript extensions (use moz option).")
.test(code, {es3: true, unused: true, undef: true, predef: ["print"]});
test.done();
};
exports['test: array comprehension with dest array at global scope'] = function (test) {
var code = [
"[for ([i, j] of [[0,0], [1,1], [2,2]]) [i, j] ];",
"var destarray_comparray_1 = [for ([i, j] of [[0,0], [1,1], [2,2]]) [i, [j, j] ]];",
"var destarray_comparray_2 = [for ([i, j] of [[0,0], [1,1], [2,2]]) [i, {i: [i, j]} ]];",
];
TestRun(test)
.test(code, {esnext: true, undef: true, predef: ["print"]});
test.done();
};
exports['test: moz-style array comprehension with dest array at global scope'] = function (test) {
var code = [
"[ [i, j] for each ([i, j] in [[0,0], [1,1], [2,2]])];",
"var destarray_comparray_1 = [ [i, [j, j] ] for each ([i, j] in [[0,0], [1,1], [2,2]])];",
"var destarray_comparray_2 = [ [i, {i: [i, j]} ] for each ([i, j] in [[0,0], [1,1], [2,2]])];",
];
TestRun(test)
.test(code, {moz: true, undef: true, predef: ["print"]});
test.done();
};
exports['test: moz-style array comprehension with dest array at global scope as esnext'] = function (test) {
var code = [
"[ [i, j] for each ([i, j] in [[0,0], [1,1], [2,2]])];",
"var destarray_comparray_1 = [ [i, [j, j] ] for each ([i, j] in [[0,0], [1,1], [2,2]])];",
"var destarray_comparray_2 = [ [i, {i: [i, j]} ] for each ([i, j] in [[0,0], [1,1], [2,2]])];",
];
TestRun(test)
.addError(1, "Expected 'for' and instead saw '['.")
.addError(1, "'for each' is only available in Mozilla JavaScript extensions (use moz option).")
.addError(2, "Expected 'for' and instead saw '['.")
.addError(2, "'for each' is only available in Mozilla JavaScript extensions (use moz option).")
.addError(3, "Expected 'for' and instead saw '['.")
.addError(3, "'for each' is only available in Mozilla JavaScript extensions (use moz option).")
.test(code, {esnext: true, undef: true, predef: ["print"]});
test.done();
};
exports['test: array comprehension with dest array at global scope as es5'] = function (test) {
var code = [
"[for ([i, j] of [[0,0], [1,1], [2,2]]) [i, j] ];",
"var destarray_comparray_1 = [for ([i, j] of [[0,0], [1,1], [2,2]]) [i, [j, j] ] ];",
"var destarray_comparray_2 = [for ([i, j] of [[0,0], [1,1], [2,2]]) [i, {i: [i, j]} ] ];",
];
TestRun(test)
.addError(1, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.addError(2, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.addError(3, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.test(code, {undef: true, predef: ["print"]}); // es5
test.done();
};
exports['test: moz-style array comprehension with dest array at global scope as es5'] = function (test) {
var code = [
"[ [i, j] for each ([i, j] in [[0,0], [1,1], [2,2]])];",
"var destarray_comparray_1 = [ [i, [j, j] ] for each ([i, j] in [[0,0], [1,1], [2,2]])];",
"var destarray_comparray_2 = [ [i, {i: [i, j]} ] for each ([i, j] in [[0,0], [1,1], [2,2]])];",
];
TestRun(test)
.addError(1, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.addError(1, "Expected 'for' and instead saw '['.")
.addError(1, "'for each' is only available in Mozilla JavaScript extensions (use moz option).")
.addError(2, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.addError(2, "Expected 'for' and instead saw '['.")
.addError(2, "'for each' is only available in Mozilla JavaScript extensions (use moz option).")
.addError(3, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.addError(3, "Expected 'for' and instead saw '['.")
.addError(3, "'for each' is only available in Mozilla JavaScript extensions (use moz option).")
.test(code, {undef: true, predef: ["print"]}); // es5
test.done();
};
exports['test: array comprehension with dest array at global scope as JS legacy'] = function (test) {
var code = [
"[for ([i, j] of [[0,0], [1,1], [2,2]]) [i, j] ];",
"var destarray_comparray_1 = [for ([i, j] of [[0,0], [1,1], [2,2]]) [i, [j, j] ] ];",
"var destarray_comparray_2 = [for ([i, j] of [[0,0], [1,1], [2,2]]) [i, {i: [i, j]} ] ];",
];
TestRun(test)
.addError(1, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.addError(2, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.addError(3, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.test(code, {es3: true, undef: true, predef: ["print"]});
test.done();
};
exports['test: moz-style array comprehension with dest array at global scope as JS legacy'] = function (test) {
var code = [
"[ [i, j] for each ([i, j] in [[0,0], [1,1], [2,2]])];",
"var destarray_comparray_1 = [ [i, [j, j] ] for each ([i, j] in [[0,0], [1,1], [2,2]])];",
"var destarray_comparray_2 = [ [i, {i: [i, j]} ] for each ([i, j] in [[0,0], [1,1], [2,2]])];",
];
TestRun(test)
.addError(1, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.addError(1, "Expected 'for' and instead saw '['.")
.addError(1, "'for each' is only available in Mozilla JavaScript extensions (use moz option).")
.addError(2, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.addError(2, "Expected 'for' and instead saw '['.")
.addError(2, "'for each' is only available in Mozilla JavaScript extensions (use moz option).")
.addError(3, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.addError(3, "Expected 'for' and instead saw '['.")
.addError(3, "'for each' is only available in Mozilla JavaScript extensions (use moz option).")
.test(code, {es3: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: array comprehension imbrication with dest array"] = function (test) {
var code = [
"[for ([i, j] of [for ([a, b] of [[2,2], [3,4]]) [a, b] ]) [i, j] ];"
];
TestRun(test)
.test(code, {esnext: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: moz-style array comprehension imbrication with dest array"] = function (test) {
var code = [
"[ [i, j] for ([i, j] in [[a, b] for each ([a, b] in [[2,2], [3,4]])]) ];"
];
TestRun(test)
.test(code, {moz: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: moz-style array comprehension imbrication with dest array using for..of"] = function (test) {
var code = [
"[ [i, j] for ([i, j] of [[a, b] for ([a, b] of [[2,2], [3,4]])]) ];"
];
TestRun(test)
.test(code, {moz: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: moz-style array comprehension imbrication with dest array as esnext"] = function (test) {
var code = [
"[ [i, j] for each ([i, j] in [[a, b] for each ([a, b] in [[2,2], [3,4]])]) ];"
];
TestRun(test)
.addError(1, "Expected 'for' and instead saw '['.")
.addError(1, "'for each' is only available in Mozilla JavaScript extensions (use moz option).")
.test(code, {esnext: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: array comprehension imbrication with dest array as es5"] = function (test) {
var code = [
"[for ([i, j] of [for ([a, b] of [[2,2], [3,4]]) [a, b] ]) [i, j] ];"
];
TestRun(test)
.addError(1, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.addError(1, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.test(code, {undef: true, predef: ["print"]}); // es5
test.done();
};
exports["test: moz-style array comprehension imbrication with dest array as es5"] = function (test) {
var code = [
"[for ([i, j] of [for ([a, b] of [[2,2], [3,4]]) [a, b] ]) [i, j] ];"
];
TestRun(test)
.addError(1, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.addError(1, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.test(code, {undef: true, predef: ["print"]}); // es5
test.done();
};
exports["test: array comprehension imbrication with dest array as legacy JS"] = function (test) {
var code = [
"[ [i, j] for each ([i, j] in [[a, b] for each ([a, b] in [[2,2], [3,4]])]) ];"
];
TestRun(test)
.addError(1, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.addError(1, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.addError(1, "Expected 'for' and instead saw '['.")
.addError(1, "Expected 'for' and instead saw '['.")
.addError(1, "'for each' is only available in Mozilla JavaScript extensions (use moz option).")
.test(code, {es3: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: moz-style array comprehension imbrication with dest array as legacy JS"] = function (test) {
var code = [
"[ [i, j] for each ([i, j] in [[a, b] for each ([a, b] in [[2,2], [3,4]])]) ];"
];
TestRun(test)
.addError(1, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.addError(1, "'array comprehension' is only available in ES6 " +
"(use esnext option).")
.addError(1, "Expected 'for' and instead saw '['.")
.addError(1, "Expected 'for' and instead saw '['.")
.addError(1, "'for each' is only available in Mozilla JavaScript extensions (use moz option).")
.test(code, {es3: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: no false positive array comprehension"] = function (test) {
var code = [
"var foo = []; for (let i in [1,2,3]) { print(i); }"
];
TestRun(test)
.test(code, {moz: true, undef: true, predef: ["print"]});
test.done();
};
exports["try catch filters"] = function (test) {
var code = [
"try {",
" throw {name: 'foo', message: 'bar'};",
"}",
"catch (e if e.name === 'foo') {",
" print (e.message);",
"}"
];
TestRun(test)
.test(code, {moz: true, undef: true, predef: ["print"]});
test.done();
};
exports["try catch filters as esnext"] = function (test) {
var code = [
"try {",
" throw {name: 'foo', message: 'bar'};",
"}",
"catch (e if e.name === 'foo') {",
" print (e.message);",
"}"
];
TestRun(test)
.addError(4, "'catch filter' is only available in Mozilla JavaScript extensions " +
"(use moz option).")
.test(code, {esnext: true, undef: true, predef: ["print"]});
test.done();
};
exports["try catch filters as es5"] = function (test) {
var code = [
"try {",
" throw {name: 'foo', message: 'bar'};",
"}",
"catch (e if e.name === 'foo') {",
" print (e.message);",
"}"
];
TestRun(test)
.addError(4, "'catch filter' is only available in Mozilla JavaScript extensions " +
"(use moz option).")
.test(code, {undef: true, predef: ["print"]}); // es5
test.done();
};
exports["try catch filters as legacy JS"] = function (test) {
var code = [
"try {",
" throw {name: 'foo', message: 'bar'};",
"}",
"catch (e if e.name === 'foo') {",
" print (e.message);",
"}"
];
TestRun(test)
.addError(4, "'catch filter' is only available in Mozilla JavaScript extensions " +
"(use moz option).")
.test(code, {es3: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: function closure expression"] = function (test) {
var code = [
"let (arr = [1,2,3]) {",
" arr.every(function (o) o instanceof Object);",
"}"
];
TestRun(test)
.test(code, {es3: true, moz: true, undef: true});
test.done();
};
exports["test: function closure expression as esnext"] = function (test) {
var code = [
"var arr = [1,2,3];",
"arr.every(function (o) o instanceof Object);",
];
TestRun(test)
.addError(2, "'function closure expressions' is only available in Mozilla JavaScript " +
"extensions (use moz option).")
.test(code, {esnext: true, undef: true});
test.done();
};
exports["test: function closure expression as es5"] = function (test) {
var code = [
"var arr = [1,2,3];",
"arr.every(function (o) o instanceof Object);",
];
TestRun(test)
.addError(2, "'function closure expressions' is only available in Mozilla JavaScript " +
"extensions (use moz option).")
.test(code, {undef: true}); // es5
test.done();
};
exports["test: function closure expression as legacy JS"] = function (test) {
var code = [
"var arr = [1,2,3];",
"arr.every(function (o) o instanceof Object);",
];
TestRun(test)
.addError(2, "'function closure expressions' is only available in Mozilla JavaScript " +
"extensions (use moz option).")
.test(code, {es3: true, undef: true});
test.done();
};
exports["test: for of as esnext"] = function (test) {
var code = [
"for (let x of [1,2,3,4]) {",
" print(x);",
"}",
"for (let x of [1,2,3,4]) print(x);"
];
TestRun(test)
.test(code, {esnext: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: for of as es5"] = function (test) {
var code = [
"for (let x of [1,2,3,4]) {",
" print(x);",
"}",
"for (let x of [1,2,3,4]) print(x);"
];
TestRun(test)
.addError(1, "'for of' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(1, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(4, "'for of' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(4, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(code, {undef: true, predef: ["print"]}); // es5
test.done();
};
exports["test: for of as legacy JS"] = function (test) {
var code = [
"for (let x of [1,2,3,4]) {",
" print(x);",
"}",
"for (let x of [1,2,3,4]) print(x);"
];
TestRun(test)
.addError(1, "'for of' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(1, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(4, "'for of' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(4, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(code, {undef: true, predef: ["print"]}); // es5
test.done();
};
exports["test: try multi-catch for moz extensions"] = function (test) {
var code = [
"try {",
" print('X');",
"} catch (err) {",
" print(err);",
"} catch (err) {",
" print(err);",
"} finally {",
" print('Z');",
"}"
];
TestRun(test)
.test(code, {moz: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: try multi-catch as esnext"] = function (test) {
var code = [
"try {",
" print('X');",
"} catch (err) {",
" print(err);",
"} catch (err) {",
" print(err);",
"} finally {",
" print('Z');",
"}"
];
TestRun(test)
.addError(5, "'multiple catch blocks' is only available in Mozilla JavaScript extensions " +
"(use moz option).")
.test(code, {esnext: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: try multi-catch as es5"] = function (test) {
var code = [
"try {",
" print('X');",
"} catch (err) {",
" print(err);",
"} catch (err) {",
" print(err);",
"} finally {",
" print('Z');",
"}"
];
TestRun(test)
.addError(5, "'multiple catch blocks' is only available in Mozilla JavaScript extensions " +
"(use moz option).")
.test(code, {undef: true, predef: ["print"]}); // es5
test.done();
};
exports["test: try multi-catch as legacy JS"] = function (test) {
var code = [
"try {",
" print('X');",
"} catch (err) {",
" print(err);",
"} catch (err) {",
" print(err);",
"} finally {",
" print('Z');",
"}"
];
TestRun(test)
.addError(5, "'multiple catch blocks' is only available in Mozilla JavaScript extensions " +
"(use moz option).")
.test(code, {es3: true, undef: true, predef: ["print"]});
test.done();
};
exports["test: no let not directly within a block"] = function (test) {
var code = [
"if (true) let x = 1;",
"function foo() {",
" if (true)",
" let x = 1;",
"}",
"if (true) let (x = 1) print(x);",
"for (let x = 0; x < 42; ++x) let a = 1;",
"for (let x in [1, 2, 3, 4] ) let a = 1;",
"for (let x of [1, 2, 3, 4] ) let a = 1;",
"while (true) let a = 1;",
"if (false) let a = 1; else if (true) let a = 1; else let a = 2;"
];
TestRun(test)
.addError(1, "Let declaration not directly within block.")
.addError(4, "Let declaration not directly within block.")
.addError(7, "Let declaration not directly within block.")
.addError(8, "Let declaration not directly within block.")
.addError(9, "Let declaration not directly within block.")
.addError(10, "Let declaration not directly within block.")
.addError(11, "Let declaration not directly within block.")
.addError(11, "Let declaration not directly within block.")
.addError(11, "Let declaration not directly within block.")
.test(code, {moz: true, predef: ["print"]});
test.done();
};
exports["regression test for crash from GH-964"] = function (test) {
var code = [
"function test(a, b) {",
" return a[b] || a[b] = new A();",
"}"
];
TestRun(test)
.addError(2, "Bad assignment.")
.addError(2, "Expected an operator and instead saw 'new'.")
.addError(2, "Missing semicolon.")
.test(code);
test.done();
};
exports["automatic comma insertion GH-950"] = function (test) {
var code = [
"var a = b",
"instanceof c;",
"var a = { b: 'X' }",
"delete a.b",
"var y = true",
" && true && false;",
"function test() {",
" return",
" { a: 1 }",
"}",
];
var run = TestRun(test)
.addError(2, "Bad line breaking before 'instanceof'.")
.addError(6, "Bad line breaking before '&&'.")
.addError(8, "Line breaking error 'return'.")
.addError(9, "Label 'a' on 1 statement.")
.addError(9, "Expected an assignment or function call and instead saw an expression.");
run.test(code, {es3: true, asi: true});
run.test(code, {asi: true}); // es5
run.test(code, {esnext: true, asi: true});
run.test(code, {moz: true, asi: true});
run = TestRun(test)
.addError(2, "Bad line breaking before 'instanceof'.")
.addError(3, "Missing semicolon.")
.addError(4, "Missing semicolon.")
.addError(6, "Bad line breaking before '&&'.")
.addError(8, "Line breaking error 'return'.")
.addError(8, "Missing semicolon.")
.addError(9, "Label 'a' on 1 statement.")
.addError(9, "Expected an assignment or function call and instead saw an expression.")
.addError(9, "Missing semicolon.");
run.test(code, {es3: true, asi: false});
run.test(code, {asi: false}); // es5
run.test(code, {esnext: true, asi: false});
run.test(code, {moz: true, asi: false});
test.done();
};
exports["fat arrows support"] = function (test) {
var code = [
"let empty = () => {};",
"let identity = x => x;",
"let square = x => x * x;",
"let key_maker = val => ({key: val});",
"let odds = evens.map(v => v + 1);",
"let fives = []; nats.forEach(v => { if (v % 5 === 0) fives.push(v); });",
"let block = (x,y, { z: t }) => {",
" print(x,y,z);",
" print(j, t);",
"};",
// using lexical this
"const obj = {",
" method: function () {",
" return () => this;",
" }",
"};",
];
var run = TestRun(test)
.addError(5, "'evens' is not defined.")
.addError(6, "'nats' is not defined.")
.addError(8, "'print' is not defined.")
.addError(9, "'print' is not defined.")
.addError(9, "'j' is not defined.")
.addError(8, "'z' is not defined.");
run.test(code, { undef: true, esnext: true });
run.test(code, { undef: true, moz: true });
run = TestRun(test)
.addError(1, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(1, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(2, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(2, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(3, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(4, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(4, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(7, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(7, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(7, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(11, "'const' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(13, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).");
run.test(code); // es5
run.test(code, {es3: true});
test.done();
};
exports["concise methods support"] = function (test) {
var code = [
"var foobar = {",
" foo () {",
" return 'foo';",
" },",
" *bar () {",
" yield 'bar';",
" }",
"};"
];
var run = TestRun(test);
run.test(code, {esnext: true});
run.test(code, {moz: true});
run = TestRun(test)
.addError(2, "'concise methods' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'generator functions' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'concise methods' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'yield' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).");
run.test(code); // es5
run.test(code, {es3: true});
test.done();
};
exports["concise methods support for 'get' and 'set' function names"] = function (test) {
var code = [
"var a = [1, 2, 3, 4, 5];",
"var strange = {",
" get (i) {",
" return a[i];",
" },",
" set () {",
" a.forEach(function(v, i, l) { l[i] = v++; });",
" }",
"};"
];
TestRun(test).test(code, {esnext: true});
test.done();
};
exports["concise methods support for 'get' without 'set'"] = function (test) {
var code = [
"var a = [1, 2, 3, 4, 5];",
"var strange = {",
" get () {",
" return a;",
" }",
"};"
];
TestRun(test).test(code, {esnext: true});
test.done();
};
exports["concise methods support for 'set' without 'get'"] = function (test) {
var code = [
"var a = [1, 2, 3, 4, 5];",
"var strange = {",
" set (v) {",
" a = v;",
" }",
"};"
];
TestRun(test).test(code, {esnext: true});
test.done();
};
exports["spread rest operator support"] = function (test) {
var code = [
// spread operator
"function foo(a, b, c) {",
" console.log(a, b, c); ",
"}",
"var args = [ 0, 1, 2 ];",
"foo(...args);",
// spread operator
"let initial = [ 1, 2, 3, 4, 5 ];",
"let extended = [ ...initial, 6, 7, 8, 9 ];",
// rest operator
"(function foo(i, j, ...args) {",
" return args;",
"}());",
// rest operator on a fat arrow function
"let bar = (...args) => args;"
];
var run = TestRun(test);
run.test(code, {esnext: true});
run.test(code, {moz: true});
run = TestRun(test)
.addError(5, "'spread/rest operator' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(7, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(7, "'spread/rest operator' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(8, "'spread/rest operator' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(11, "'let' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(11, "'spread/rest operator' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(11, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(11, "'spread/rest operator' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).");
test.done();
};
exports["test for GH-1010"] = function (test) {
var code = [
"var x = 20, y, z; if(x < 30) y=7, z=2; else y=5;"
];
var run = TestRun(test);
run.test(code, {expr: true, es3: true});
run.test(code, {expr: true}); // es5
run.test(code, {expr: true, esnext: true});
run.test(code, {expr: true, moz: true});
test.done();
};
exports.classes = function (test) {
var cdecl = "// cdecl";
var cexpr = "// cexpr";
var cdeclAssn = "// cdeclAssn";
var cexprAssn = "// cexprAssn";
var code = [
"var Bar;",
// class declarations
cdecl,
"class Foo0 {}",
"class Foo1 extends Bar {}",
"class protected {",
" constructor(package) {}",
"}",
"class Foo3 extends interface {",
" constructor() {}",
"}",
"class Foo4 extends Bar {",
" constructor() {",
" super();",
" }",
"}",
"class Foo5 {",
" constructor() {",
" }",
" static create() {",
" }",
"}",
"class Foo6 extends Bar {",
" constructor() {",
" super();",
" }",
" static create() {",
" }",
"}",
// class expressions
cexpr,
"var Foo7 = class {};",
"let Foo8 = class extends Bar {};",
"var static = class protected {",
" constructor(package) {}",
"};",
"var Foo10 = class extends interface {",
" constructor() {}",
"};",
"var Foo11 = class extends Bar {",
" constructor() {",
" super();",
" }",
"};",
"var Foo12 = class {",
" constructor() {",
" }",
" static create() {",
" }",
"};",
"let Foo13 = class extends Bar {",
" constructor() {",
" super();",
" }",
" static create() {",
" }",
"};",
// mark these as used
"void (Foo1, Foo3, Foo4, Foo5, Foo6);",
"void (Foo8, Foo10, Foo11, Foo12, Foo13);",
// class declarations: extends AssignmentExpression
cdeclAssn,
"class Foo14 extends Bar[42] {}",
"class Foo15 extends { a: function() { return 42; } } {}",
"class Foo16 extends class Foo15 extends Bar {} {}",
"class Foo17 extends Foo15 = class Foo16 extends Bar {} {}",
"class Foo18 extends function () {} {}",
"class Foo19 extends class extends function () {} {} {}",
"class Foo20 extends Foo18 = class extends Foo17 = function () {} {} {}",
// class expressions: extends AssignmentExpression
cexprAssn,
"let Foo21 = class extends Bar[42] {};",
"let Foo22 = class extends { a() { return 42; } } {};",
"let Foo23 = class extends class Foo15 extends Bar {} {};",
"let Foo24 = class extends Foo15 = class Foo16 extends Bar {} {};",
"let Foo25 = class extends function () {} {};",
"let Foo26 = class extends class extends function () {} {} {};",
"let Foo27 = class extends Foo18 = class extends Foo17 = function () {} {} {};",
// mark these as used
"void (Foo14, Foo15, Foo16, Foo17, Foo18, Foo19, Foo20);",
"void (Foo21, Foo22, Foo23, Foo24, Foo25, Foo26, Foo27);"
];
cdecl = code.indexOf(cdecl) + 1;
cexpr = code.indexOf(cexpr) + 1;
cdeclAssn = code.indexOf(cdeclAssn) + 1;
cexprAssn = code.indexOf(cexprAssn) + 1;
var run = TestRun(test)
.addError(cdecl + 4, "Expected an identifier and instead saw 'package' (a reserved word).")
.addError(cexpr + 4, "Expected an identifier and instead saw 'package' (a reserved word).");
run.test(code, {esnext: true});
run.test(code, {moz: true});
run
.addError(cdecl + 1, "'Foo0' is defined but never used.")
.addError(cdecl + 3, "Expected an identifier and instead saw 'protected' (a reserved word).")
.addError(cdecl + 3, "'protected' is defined but never used.")
.addError(cdecl + 4, "'package' is defined but never used.");
run
.addError(cexpr + 1, "'Foo7' is defined but never used.")
.addError(cexpr + 3, "Expected an identifier and instead saw 'static' (a reserved word).")
.addError(cexpr + 3, "'static' is defined but never used.")
.addError(cexpr + 3, "Expected an identifier and instead saw 'protected' (a reserved word).")
.addError(cexpr + 4, "'package' is defined but never used.");
code[0] = "'use strict';" + code[0];
run.test(code, {unused: true, globalstrict: true, esnext: true});
run.test(code, {unused: true, globalstrict: true, moz: true});
test.done();
};
exports["class and method naming"] = function (test) {
var code = [
"class eval {}",
"class arguments {}",
"class C {",
" get constructor() {}",
" set constructor(x) {}",
" prototype() {}",
"}"
];
var run = TestRun(test)
.addError(1, "Expected an identifier and instead saw 'eval' (a reserved word).")
.addError(2, "Expected an identifier and instead saw 'arguments' (a reserved word).")
.addError(4, "A class getter method cannot be named 'constructor'.")
.addError(5, "A class setter method cannot be named 'constructor'.")
.addError(7, "A class method cannot be named 'prototype'.");
run.test(code, {esnext: true});
test.done();
};
exports["test for GH-1018"] = function (test) {
var code = [
"if (a = 42) {}",
"else if (a = 42) {}",
"while (a = 42) {}",
"for (a = 42; a = 42; a += 42) {}",
"do {} while (a = 42);",
"switch (a = 42) {}"
];
var run = TestRun(test);
run.test(code, {boss: true});
for (var i = 0; i < code.length; i++) {
run.addError(i + 1, "Expected a conditional expression and instead saw an assignment.");
}
run.test(code);
test.done();
};
exports["test warnings for assignments in conditionals"] = function (test) {
var code = [
"if (a = b) { }",
"if ((a = b)) { }",
"if (a = b, a) { }",
"if (a = b, b = c) { }",
"if ((a = b, b = c)) { }",
"if (a = b, (b = c)) { }"
];
var run = TestRun(test)
.addError(1, "Expected a conditional expression and instead saw an assignment.")
.addError(4, "Expected a conditional expression and instead saw an assignment.");
run.test(code); // es5
test.done();
};
exports["test for GH-1089"] = function (test) {
var code = [
"function foo() {",
" 'use strict';",
" Object.defineProperty(foo, 'property', {",
" get: function() foo,",
" set: function(value) {},",
" enumerable: true",
" });",
"}",
"foo;"
];
var run = TestRun(test)
.addError(9, "Expected an assignment or function call and instead saw an expression.");
run.test(code, {moz: true});
run
.addError(4, "'function closure expressions' is only available in Mozilla JavaScript " +
"extensions (use moz option).");
run.test(code);
test.done();
};
exports["test for GH-1103"] = function (test) {
var code = [ "var ohnoes = 42;" ];
var run = TestRun(test);
var patch = true;
JSHINT.addModule(function (linter) {
if (!patch) {
return;
}
patch = false;
var ohnoes = "oh noes";
Array.prototype.ohnoes = function () {
linter.warn("E024", { line: 1, char: 1, data: [ ohnoes += "!" ] });
};
});
run.test(code);
test.done();
delete Array.prototype.ohnoes;
};
exports["test for GH-1105"] = function (test) {
var code = [
"while (true) {",
" if (true) { break }",
"}"
];
var run = TestRun(test)
.addError(2, "Missing semicolon.");
run.test(code);
test.done();
};
exports["test for crash with invalid condition"] = function (test) {
var code = [
"do {} while ();",
"do {} while (,);",
"do {} while (a,);",
"do {} while (,b);",
"do {} while (());",
"do {} while ((,));",
"do {} while ((a,));",
"do {} while ((,b));"
];
// As long as jshint doesn't crash, it doesn't matter what these errors
// are. Feel free to adjust these if they don't match the output.
var run = TestRun(test)
.addError(1, "Expected an identifier and instead saw ')'.")
.addError(1, "Expected ')' to match '(' from line 1 and instead saw ';'.")
.addError(2, "Expected an identifier and instead saw ','.")
.addError(3, "Unexpected ')'.")
.addError(4, "Expected an identifier and instead saw ','.")
.addError(4, "Expected ')' to match '(' from line 4 and instead saw 'b'.")
.addError(4, "Expected an identifier and instead saw ')'.")
.addError(6, "Expected an identifier and instead saw ','.")
.addError(7, "Unexpected ')'.")
.addError(7, "Expected an identifier and instead saw ')'.")
.addError(7, "Expected ')' to match '(' from line 7 and instead saw ';'.")
.addError(8, "Expected an identifier and instead saw ','.")
.addError(8, "Expected ')' to match '(' from line 8 and instead saw 'b'.")
.addError(8, "Expected an identifier and instead saw ')'.");
run.test(code, {asi: true, expr: true});
test.done();
};
exports["test 'yield' in compound expressions."] = function (test) {
var code = fs.readFileSync(path.join(__dirname, "./fixtures/yield-expressions.js"), "utf8");
var run = TestRun(test)
.addError(22, "Did you mean to return a conditional instead of an assignment?")
.addError(31, "Did you mean to return a conditional instead of an assignment?");
run.test(code, {maxerr: 1000, expr: true, esnext: true});
// These are line-column pairs for the Mozilla paren errors.
var needparen = [
// comma
[ 5, 5], [ 6, 8], [ 7, 5], [11, 5], [12, 8], [13, 5],
// yield in yield
[18, 11], [19, 17], [19, 11], [20, 11], [20, 5], [21, 11], [21, 5], [21, 26], [22, 22],
[23, 22], [23, 11], [27, 11], [28, 17], [28, 11], [29, 11], [29, 5], [30, 11], [30, 5],
[30, 24], [31, 22], [32, 11], [32, 20],
// infix
[51, 10], [53, 10], [54, 16], [57, 10], [58, 5], [59, 10], [60, 5], [60, 14],
// prefix
[64, 6], [65, 7], [66, 6], [67, 7], [70, 6], [71, 7],
// ternary
[77, 5], [78, 5], [78, 13], [79, 5], [79, 13], [79, 41], [82, 5], [83, 5], [83, 13],
[84, 5], [84, 13], [84, 37]
];
needparen.forEach(function (lc) {
run.addError(lc[0], "Mozilla requires the yield expression to be parenthesized here.",
{character: lc[1]});
});
run
.addError(1, "'function*' is only available in ES6 (use esnext option).")
.addError(74, "'function*' is only available in ES6 (use esnext option).");
run.test(code, {maxerr: 1000, expr: true, moz: true});
test.done();
};
exports["test for GH-387"] = function (test) {
var code = [
"var foo = a",
"delete foo.a;"
];
var run = TestRun(test)
.addError(1, "Missing semicolon.");
run.test(code); // es5
test.done();
};
exports["test for line breaks with 'yield'"] = function (test) {
var code = [
"function* F() {",
" a = b + (yield",
" c",
" );",
" d = yield",
" + e;",
" f = (yield",
" , g);",
" h = yield",
" ? i : j;",
" k = l ? yield",
" : m;",
" n = o ? p : yield",
" + r;",
"}"
];
var run = TestRun(test)
.addError(3, "Bad line breaking before 'c'.")
.addError(6, "Bad line breaking before '+'.")
.addError(8, "Comma warnings can be turned off with 'laxcomma'.")
.addError(7, "Bad line breaking before ','.")
.addError(10, "Bad line breaking before '?'.")
.addError(14, "Bad line breaking before '+'.");
run.test(code, {esnext: true});
// Mozilla assumes the statement has ended if there is a line break
// following a `yield`. This naturally causes havoc with the subsequent
// parse.
//
// Note: there is one exception to the line-breaking rule:
// ```js
// a ? yield
// : b;
// ```
run = TestRun(test)
.addError(1, "'function*' is only available in ES6 (use esnext option).")
.addError(3, "Expected ')' to match '(' from line 2 and instead saw 'c'.")
.addError(4, "Expected an identifier and instead saw ')'.")
.addError(4, "Expected an assignment or function call and instead saw an expression.")
.addError(6, "Expected an assignment or function call and instead saw an expression.")
.addError(8, "Comma warnings can be turned off with 'laxcomma'.")
.addError(7, "Bad line breaking before ','.")
.addError(10, "Expected an identifier and instead saw '?'.")
.addError(10, "Expected an assignment or function call and instead saw an expression.")
.addError(10, "Label 'i' on j statement.")
.addError(10, "Expected an assignment or function call and instead saw an expression.")
.addError(14, "Expected an assignment or function call and instead saw an expression.");
run.test(code, {moz: true, asi: true});
run
.addError(2, "Line breaking error 'yield'.")
.addError(3, "Missing semicolon.")
.addError(5, "Line breaking error 'yield'.")
.addError(5, "Missing semicolon.")
.addError(7, "Line breaking error 'yield'.")
.addError(9, "Line breaking error 'yield'.")
.addError(9, "Missing semicolon.")
.addError(10, "Missing semicolon.")
.addError(11, "Line breaking error 'yield'.")
.addError(13, "Line breaking error 'yield'.")
.addError(13, "Missing semicolon.");
run.test(code, {moz: true});
test.done();
};
exports["regression for GH-1227"] = function (test) {
var src = fs.readFileSync(__dirname + "/fixtures/gh1227.js", "utf8");
TestRun(test)
.addError(14, "Unreachable 'return' after 'return'.")
.test(src);
test.done();
};
exports["test for 'break' in switch case + curly braces"] = function (test) {
var code = [
"switch (foo) {",
" case 1: { break; }",
" case 2: { return; }",
" case 3: { throw 'Error'; }",
" case 11: {",
" while (true) {",
" break;",
" }",
" }",
" default: break;",
"}"
];
// No error for case 1, 2, 3.
var run = TestRun(test)
.addError(9, "Expected a 'break' statement before 'default'.")
.test(code);
test.done();
};
exports["test for 'break' in switch case in loop + curly braces"] = function (test) {
var code = [
"while (true) {",
" switch (foo) {",
" case 1: { break; }",
" case 2: { return; }",
" case 3: { throw 'Error'; }",
" case 4: { continue; }",
" case 11: {",
" while (true) {",
" break;",
" }",
" }",
" default: break;",
" }",
"}"
];
// No error for case 1, 2, 3, 4.
var run = TestRun(test)
.addError(11, "Expected a 'break' statement before 'default'.")
.test(code);
test.done();
};
exports["allow expression with a comma in switch case condition"] = function (test) {
var code = [
"switch (false) {",
" case x = 1, y = x: { break; }",
"}"
]
var run = TestRun(test).test(code);
test.done();
};
exports["/*jshint ignore */ should be a good option and only accept start, end or line as values"] = function (test) {
var code = [
"/*jshint ignore:start*/",
"/*jshint ignore:end*/",
"/*jshint ignore:line*/",
"/*jshint ignore:badvalue*/"
];
TestRun(test)
.addError(4, "Bad option value.")
.test(code);
test.done();
};
exports["/*jshint ignore */ should allow the linter to skip blocked-out lines to continue finding errors in the rest of the code"] = function (test) {
var code = fs.readFileSync(__dirname + "/fixtures/gh826.js", "utf8");
TestRun(test)
.addError(33, "Use '===' to compare with '0'.")
.test(code);
test.done();
};
exports["/*jshint ignore */ should be detected even with leading and/or trailing whitespace"] = function (test) {
var code = [
" /*jshint ignore:start */", // leading whitespace
" if (true) { alert('sup') }", // should be ignored
" /*jshint ignore:end */ ", // leading and trailing whitespace
" if (true) { alert('sup') }", // should not be ignored
" /*jshint ignore:start */ ", // leading and trailing whitespace
" if (true) { alert('sup') }", // should be ignored
" /*jshint ignore:end */ " // leading and trailing whitespace
];
TestRun(test)
.addError(4, "Missing semicolon.")
.test(code);
test.done();
};
exports["should be able to ignore a single line with a trailing comment: // jshint:ignore"] = function (test) {
var code = fs.readFileSync(__dirname + "/fixtures/gh870.js", "utf8");
TestRun(test).test(code, { unused: true });
test.done();
};
exports["regression test for GH-1431"] = function (test) {
// The code is invalid but it should not crash JSHint.
TestRun(test)
.addError(1, "Use '!==' to compare with 'null'.")
.addError(1, "Expected ';' and instead saw ')'.")
.addError(1, "Expected ')' and instead saw ';'.")
.addError(1, "Expected an identifier and instead saw ';'.")
.addError(1, "Expected ')' to match '(' from line 1 and instead saw 'i'.")
.addError(1, "Expected an identifier and instead saw ')'.")
.test("for (i=0; (arr[i])!=null); i++);");
test.done();
};
exports["jshint ignore:start/end should be detected using single line comments"] = function (test) {
var code = [
"// jshint ignore:start",
"var a;",
"// jshint ignore:end",
"var b;"
];
TestRun(test)
.addError(4, "'b' is defined but never used.")
.test(code, { unused: true });
test.done();
};
exports["test destructuring function parameters as es5"] = function (test) {
var src = fs.readFileSync(__dirname + "/fixtures/destparam.js", "utf8");
TestRun(test)
.addError(4, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(4, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(7, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(7, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(7, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(7, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(10, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(10, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(11, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(11, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(14, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(14, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(15, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(15, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(16, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(16, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(16, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(17, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(17, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(18, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(18, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(21, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(21, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(21, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(22, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(22, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(22, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(23, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(23, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(23, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(24, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(24, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(24, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(27, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(27, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(27, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(28, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(28, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(28, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(29, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(29, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(29, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(30, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(30, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(30, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(31, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(31, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(31, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(src, {unused: true, undef: true, maxerr: 100});
test.done();
};
exports["test destructuring function parameters as legacy JS"] = function (test) {
var src = fs.readFileSync(__dirname + "/fixtures/destparam.js", "utf8");
TestRun(test)
.addError(4, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(4, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(5, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(6, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(7, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(7, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(7, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(7, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(10, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(10, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(11, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(11, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(14, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(14, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(15, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(15, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(16, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(16, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(16, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(17, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(17, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(18, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(18, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(21, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(21, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(21, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(22, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(22, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(22, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(23, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(23, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(23, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(24, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(24, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(24, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(27, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(27, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(27, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(28, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(28, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(28, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(29, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(29, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(29, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(30, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(30, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(30, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(31, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(31, "'destructuring expression' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.addError(31, "'arrow function syntax (=>)' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).")
.test(src, {es3: true, unused: true, undef: true, maxerr: 100});
test.done();
};
exports["test for parentheses in odd-numbered token"] = function (test) {
var code = [
"let f, b;",
"let a = x => ({ f: f(x) });",
"b = x => x;"
];
TestRun(test)
.test(code, {esnext: true});
test.done();
};
exports["regression crash from GH-1573"] = function (test) {
TestRun(test)
.addError(1, "Expected an identifier and instead saw 'var'.")
.addError(1, "Expected ']' to match '[' from line 1 and instead saw 'foo'.")
.addError(1, "Expected an identifier and instead saw ']'.")
.addError(1, "Expected an assignment or function call and instead saw an expression.")
.addError(1, "Missing semicolon.")
.test("[var foo = 1;]");
test.done();
};
exports["make sure we don't throw errors on removed options"] = function (test) {
TestRun(test).test("a();", { nomen: true, onevar: true, passfail: true, white: true });
test.done();
};
|
// THIS TEST WAS GENERATED AUTOMATICALLY ON Wed Dec 07 2016 14:07:23 GMT+0200 (EET)
'use strict';
import chai from 'chai';
import Handler from '../../../../../backend/src/account/unlink-user/Handler';
import Kernel from '../../../node_modules/deep-framework/node_modules/deep-kernel';
import KernelFactory from '../../common/KernelFactory';
// @todo: Add more advanced tests
suite('Handlers', () => {
let handler, kernelInstance;
test('Class Handler exists in deep-account-adapter-accounts-unlink-user module', () => {
chai.expect(Handler).to.be.an('function');
});
test('Load Kernel by using Kernel.load()', (done) => {
let callback = (backendKernel) => {
kernelInstance = backendKernel;
chai.assert.instanceOf(
backendKernel, Kernel, 'backendKernel is an instance of Kernel'
);
// complete the async
done();
};
KernelFactory.create(callback);
});
test('Check Handler constructor', () => {
handler = new Handler(kernelInstance);
chai.expect(handler).to.be.an.instanceof(Handler);
});
test('Check handle method exists', () => {
chai.expect(handler.handle).to.be.an('function');
});
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:233cff7b258425a580ac5c2ed140679e7c1c2b1444dce9fa317178e860c82422
size 3193
|
var passport = require('passport');
module.exports = {
login: function(req, res) {
var auth = passport.authenticate('local', function(err, user) {
var errorsMessage = '';
if(err) {
errorsMessage += 'Could not fetch user';
}
if (!user) {
errorsMessage += 'Incorrect login data';
}
if(errorsMessage.length > 0){
res.render('home', {
loginErrors: errorsMessage
});
return;
}
req.logIn(user, function(err) {
if (err) return next(err);
res.redirect('/home');
});
res.end();
});
auth(req, res);
},
logout: function(req, res, next) {
req.logout();
res.redirect('/home');
},
isAuthenticated: function(req, res, next) {
if (!req.isAuthenticated()) {
res.status(403);
res.redirect('/unauthorized');
res.end();
}
else {
next();
}
},
isInRole: function(role) {
return function(req, res, next) {
if (req.isAuthenticated() && req.user.roles.indexOf(role) > -1) {
next();
}
else {
res.redirect('/unauthorized');
res.end();
}
}
}
}; |
var searchData=
[
['toplevel',['TOPLEVEL',['../classEnsamZ.html#ad705bf3f945fd15280c825a6595e0af0ae8920199c1c8e6078d7f9e58a9fd5e75',1,'EnsamZ::TOPLEVEL()'],['../classMacroEnsamZ.html#aa2646d12de2e04f0b00f1acf9656cd42aa4792641feef81b203912f1811035950',1,'MacroEnsamZ::TOPLEVEL()']]]
];
|
/**
* Sinon-jQuery
*
* Sinon matcher for matching jQuery collections.
*
* Copyright (c) Jadu
*
* Released under the MIT license
* https://github.com/jadu/sinon-jquery/blob/master/LICENSE.txt
*/
'use strict';
import _ from 'lodash';
import $ from 'jquery';
import Matcher from '../src/Matcher';
const expect = require('chai').expect;
const sinon = require('sinon');
require('./harness');
describe('Matcher', function () {
beforeEach(function () {
this.$collection = $('<div></div>');
this.func = sinon.spy();
this.stubSinon = {
match: sinon.spy(sinon.match.bind(sinon))
};
this.matcher = new Matcher(this.stubSinon, $);
});
describe('match()', function () {
_.each(['My description', 'Your description'], function (description) {
it('should pass the specified description through to Sinon when "' + description + '"', function () {
this.matcher.match($('div'), description);
expect(this.stubSinon.match).to.have.been.calledWith(sinon.match.any, description);
});
});
describe('when comparing jQuery collection with element to another collection with element', function () {
it('should match when the two arguments are the same jQuery collection object', function () {
this.func(this.$collection);
expect(this.func).to.have.been.calledWith(this.matcher.match(this.$collection));
});
it('should match when the two arguments are different jQuery collection objects with the same element', function () {
this.func($(this.$collection[0]));
expect(this.func).to.have.been.calledWith(this.matcher.match(this.$collection));
});
it('should not match when the two arguments are jQuery collection objects with different elements', function () {
this.func($('<div></div>'));
expect(this.func).not.to.have.been.calledWith(this.matcher.match(this.$collection));
});
});
describe('when comparing an element against a tag selector', function () {
it('should match when the element has the correct tag name', function () {
this.func($('<section></section>'));
expect(this.func).to.have.been.calledWith(this.matcher.match('section'));
});
it('should not match when the element has another tag name', function () {
this.func($('<section></section>'));
expect(this.func).not.to.have.been.calledWith(this.matcher.match('div'));
});
});
});
});
|
/*!
* Bootstrap v3.3.7 (http://getbootstrap.com)
* Copyright 2011-2017 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
/*!
* Generated using the Bootstrap Customizer (https://getbootstrap.com/customize/?id=46beb5de394549d86024dec05739246e)
* Config saved to config.json and https://gist.github.com/46beb5de394549d86024dec05739246e
*/
if (typeof jQuery === 'undefined') {
throw new Error('Bootstrap\'s JavaScript requires jQuery')
}
+function ($) {
'use strict';
var version = $.fn.jquery.split(' ')[0].split('.')
if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] > 3)) {
throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4')
}
}(jQuery);
/* ========================================================================
* Bootstrap: alert.js v3.3.7
* http://getbootstrap.com/javascript/#alerts
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function (el) {
$(el).on('click', dismiss, this.close)
}
Alert.VERSION = '3.3.7'
Alert.TRANSITION_DURATION = 150
Alert.prototype.close = function (e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector === '#' ? [] : selector)
if (e) e.preventDefault()
if (!$parent.length) {
$parent = $this.closest('.alert')
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
// detach from parent, fire event then clean up data
$parent.detach().trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one('bsTransitionEnd', removeElement)
.emulateTransitionEnd(Alert.TRANSITION_DURATION) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data) $this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.alert
$.fn.alert = Plugin
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function () {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
/* ========================================================================
* Bootstrap: button.js v3.3.7
* http://getbootstrap.com/javascript/#buttons
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// BUTTON PUBLIC CLASS DEFINITION
// ==============================
var Button = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Button.DEFAULTS, options)
this.isLoading = false
}
Button.VERSION = '3.3.7'
Button.DEFAULTS = {
loadingText: 'loading...'
}
Button.prototype.setState = function (state) {
var d = 'disabled'
var $el = this.$element
var val = $el.is('input') ? 'val' : 'html'
var data = $el.data()
state += 'Text'
if (data.resetText == null) $el.data('resetText', $el[val]())
// push to event loop to allow forms to submit
setTimeout($.proxy(function () {
$el[val](data[state] == null ? this.options[state] : data[state])
if (state == 'loadingText') {
this.isLoading = true
$el.addClass(d).attr(d, d).prop(d, true)
} else if (this.isLoading) {
this.isLoading = false
$el.removeClass(d).removeAttr(d).prop(d, false)
}
}, this), 0)
}
Button.prototype.toggle = function () {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked')) changed = false
$parent.find('.active').removeClass('active')
this.$element.addClass('active')
} else if ($input.prop('type') == 'checkbox') {
if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false
this.$element.toggleClass('active')
}
$input.prop('checked', this.$element.hasClass('active'))
if (changed) $input.trigger('change')
} else {
this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
this.$element.toggleClass('active')
}
}
// BUTTON PLUGIN DEFINITION
// ========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.button')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
var old = $.fn.button
$.fn.button = Plugin
$.fn.button.Constructor = Button
// BUTTON NO CONFLICT
// ==================
$.fn.button.noConflict = function () {
$.fn.button = old
return this
}
// BUTTON DATA-API
// ===============
$(document)
.on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
var $btn = $(e.target).closest('.btn')
Plugin.call($btn, 'toggle')
if (!($(e.target).is('input[type="radio"], input[type="checkbox"]'))) {
// Prevent double click on radios, and the double selections (so cancellation) on checkboxes
e.preventDefault()
// The target component still receive the focus
if ($btn.is('input,button')) $btn.trigger('focus')
else $btn.find('input:visible,button:visible').first().trigger('focus')
}
})
.on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) {
$(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type))
})
}(jQuery);
/* ========================================================================
* Bootstrap: carousel.js v3.3.7
* http://getbootstrap.com/javascript/#carousel
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CAROUSEL CLASS DEFINITION
// =========================
var Carousel = function (element, options) {
this.$element = $(element)
this.$indicators = this.$element.find('.carousel-indicators')
this.options = options
this.paused = null
this.sliding = null
this.interval = null
this.$active = null
this.$items = null
this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this))
this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element
.on('mouseenter.bs.carousel', $.proxy(this.pause, this))
.on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
}
Carousel.VERSION = '3.3.7'
Carousel.TRANSITION_DURATION = 600
Carousel.DEFAULTS = {
interval: 5000,
pause: 'hover',
wrap: true,
keyboard: true
}
Carousel.prototype.keydown = function (e) {
if (/input|textarea/i.test(e.target.tagName)) return
switch (e.which) {
case 37: this.prev(); break
case 39: this.next(); break
default: return
}
e.preventDefault()
}
Carousel.prototype.cycle = function (e) {
e || (this.paused = false)
this.interval && clearInterval(this.interval)
this.options.interval
&& !this.paused
&& (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
return this
}
Carousel.prototype.getItemIndex = function (item) {
this.$items = item.parent().children('.item')
return this.$items.index(item || this.$active)
}
Carousel.prototype.getItemForDirection = function (direction, active) {
var activeIndex = this.getItemIndex(active)
var willWrap = (direction == 'prev' && activeIndex === 0)
|| (direction == 'next' && activeIndex == (this.$items.length - 1))
if (willWrap && !this.options.wrap) return active
var delta = direction == 'prev' ? -1 : 1
var itemIndex = (activeIndex + delta) % this.$items.length
return this.$items.eq(itemIndex)
}
Carousel.prototype.to = function (pos) {
var that = this
var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))
if (pos > (this.$items.length - 1) || pos < 0) return
if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid"
if (activeIndex == pos) return this.pause().cycle()
return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos))
}
Carousel.prototype.pause = function (e) {
e || (this.paused = true)
if (this.$element.find('.next, .prev').length && $.support.transition) {
this.$element.trigger($.support.transition.end)
this.cycle(true)
}
this.interval = clearInterval(this.interval)
return this
}
Carousel.prototype.next = function () {
if (this.sliding) return
return this.slide('next')
}
Carousel.prototype.prev = function () {
if (this.sliding) return
return this.slide('prev')
}
Carousel.prototype.slide = function (type, next) {
var $active = this.$element.find('.item.active')
var $next = next || this.getItemForDirection(type, $active)
var isCycling = this.interval
var direction = type == 'next' ? 'left' : 'right'
var that = this
if ($next.hasClass('active')) return (this.sliding = false)
var relatedTarget = $next[0]
var slideEvent = $.Event('slide.bs.carousel', {
relatedTarget: relatedTarget,
direction: direction
})
this.$element.trigger(slideEvent)
if (slideEvent.isDefaultPrevented()) return
this.sliding = true
isCycling && this.pause()
if (this.$indicators.length) {
this.$indicators.find('.active').removeClass('active')
var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
$nextIndicator && $nextIndicator.addClass('active')
}
var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid"
if ($.support.transition && this.$element.hasClass('slide')) {
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
$active
.one('bsTransitionEnd', function () {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function () {
that.$element.trigger(slidEvent)
}, 0)
})
.emulateTransitionEnd(Carousel.TRANSITION_DURATION)
} else {
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger(slidEvent)
}
isCycling && this.cycle()
return this
}
// CAROUSEL PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.carousel')
var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
var action = typeof option == 'string' ? option : options.slide
if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (action) data[action]()
else if (options.interval) data.pause().cycle()
})
}
var old = $.fn.carousel
$.fn.carousel = Plugin
$.fn.carousel.Constructor = Carousel
// CAROUSEL NO CONFLICT
// ====================
$.fn.carousel.noConflict = function () {
$.fn.carousel = old
return this
}
// CAROUSEL DATA-API
// =================
var clickHandler = function (e) {
var href
var $this = $(this)
var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
if (!$target.hasClass('carousel')) return
var options = $.extend({}, $target.data(), $this.data())
var slideIndex = $this.attr('data-slide-to')
if (slideIndex) options.interval = false
Plugin.call($target, options)
if (slideIndex) {
$target.data('bs.carousel').to(slideIndex)
}
e.preventDefault()
}
$(document)
.on('click.bs.carousel.data-api', '[data-slide]', clickHandler)
.on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler)
$(window).on('load', function () {
$('[data-ride="carousel"]').each(function () {
var $carousel = $(this)
Plugin.call($carousel, $carousel.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: dropdown.js v3.3.7
* http://getbootstrap.com/javascript/#dropdowns
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// DROPDOWN CLASS DEFINITION
// =========================
var backdrop = '.dropdown-backdrop'
var toggle = '[data-toggle="dropdown"]'
var Dropdown = function (element) {
$(element).on('click.bs.dropdown', this.toggle)
}
Dropdown.VERSION = '3.3.7'
function getParent($this) {
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = selector && $(selector)
return $parent && $parent.length ? $parent : $this.parent()
}
function clearMenus(e) {
if (e && e.which === 3) return
$(backdrop).remove()
$(toggle).each(function () {
var $this = $(this)
var $parent = getParent($this)
var relatedTarget = { relatedTarget: this }
if (!$parent.hasClass('open')) return
if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return
$parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this.attr('aria-expanded', 'false')
$parent.removeClass('open').trigger($.Event('hidden.bs.dropdown', relatedTarget))
})
}
Dropdown.prototype.toggle = function (e) {
var $this = $(this)
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
clearMenus()
if (!isActive) {
if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
// if mobile we use a backdrop because click events don't delegate
$(document.createElement('div'))
.addClass('dropdown-backdrop')
.insertAfter($(this))
.on('click', clearMenus)
}
var relatedTarget = { relatedTarget: this }
$parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this
.trigger('focus')
.attr('aria-expanded', 'true')
$parent
.toggleClass('open')
.trigger($.Event('shown.bs.dropdown', relatedTarget))
}
return false
}
Dropdown.prototype.keydown = function (e) {
if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return
var $this = $(this)
e.preventDefault()
e.stopPropagation()
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
if (!isActive && e.which != 27 || isActive && e.which == 27) {
if (e.which == 27) $parent.find(toggle).trigger('focus')
return $this.trigger('click')
}
var desc = ' li:not(.disabled):visible a'
var $items = $parent.find('.dropdown-menu' + desc)
if (!$items.length) return
var index = $items.index(e.target)
if (e.which == 38 && index > 0) index-- // up
if (e.which == 40 && index < $items.length - 1) index++ // down
if (!~index) index = 0
$items.eq(index).trigger('focus')
}
// DROPDOWN PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.dropdown')
if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.dropdown
$.fn.dropdown = Plugin
$.fn.dropdown.Constructor = Dropdown
// DROPDOWN NO CONFLICT
// ====================
$.fn.dropdown.noConflict = function () {
$.fn.dropdown = old
return this
}
// APPLY TO STANDARD DROPDOWN ELEMENTS
// ===================================
$(document)
.on('click.bs.dropdown.data-api', clearMenus)
.on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
.on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
.on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown)
.on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown)
}(jQuery);
/* ========================================================================
* Bootstrap: modal.js v3.3.7
* http://getbootstrap.com/javascript/#modals
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// MODAL CLASS DEFINITION
// ======================
var Modal = function (element, options) {
this.options = options
this.$body = $(document.body)
this.$element = $(element)
this.$dialog = this.$element.find('.modal-dialog')
this.$backdrop = null
this.isShown = null
this.originalBodyPad = null
this.scrollbarWidth = 0
this.ignoreBackdropClick = false
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function () {
this.$element.trigger('loaded.bs.modal')
}, this))
}
}
Modal.VERSION = '3.3.7'
Modal.TRANSITION_DURATION = 300
Modal.BACKDROP_TRANSITION_DURATION = 150
Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
show: true
}
Modal.prototype.toggle = function (_relatedTarget) {
return this.isShown ? this.hide() : this.show(_relatedTarget)
}
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.checkScrollbar()
this.setScrollbar()
this.$body.addClass('modal-open')
this.escape()
this.resize()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.$dialog.on('mousedown.dismiss.bs.modal', function () {
that.$element.one('mouseup.dismiss.bs.modal', function (e) {
if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true
})
})
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(that.$body) // don't move modals dom position
}
that.$element
.show()
.scrollTop(0)
that.adjustDialog()
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element.addClass('in')
that.enforceFocus()
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$dialog // wait for modal to slide in
.one('bsTransitionEnd', function () {
that.$element.trigger('focus').trigger(e)
})
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
that.$element.trigger('focus').trigger(e)
})
}
Modal.prototype.hide = function (e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
this.resize()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.off('click.dismiss.bs.modal')
.off('mouseup.dismiss.bs.modal')
this.$dialog.off('mousedown.dismiss.bs.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one('bsTransitionEnd', $.proxy(this.hideModal, this))
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
this.hideModal()
}
Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (document !== e.target &&
this.$element[0] !== e.target &&
!this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}
Modal.prototype.escape = function () {
if (this.isShown && this.options.keyboard) {
this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keydown.dismiss.bs.modal')
}
}
Modal.prototype.resize = function () {
if (this.isShown) {
$(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
} else {
$(window).off('resize.bs.modal')
}
}
Modal.prototype.hideModal = function () {
var that = this
this.$element.hide()
this.backdrop(function () {
that.$body.removeClass('modal-open')
that.resetAdjustments()
that.resetScrollbar()
that.$element.trigger('hidden.bs.modal')
})
}
Modal.prototype.removeBackdrop = function () {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}
Modal.prototype.backdrop = function (callback) {
var that = this
var animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $(document.createElement('div'))
.addClass('modal-backdrop ' + animate)
.appendTo(this.$body)
this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
if (this.ignoreBackdropClick) {
this.ignoreBackdropClick = false
return
}
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static'
? this.$element[0].focus()
: this.hide()
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ?
this.$backdrop
.one('bsTransitionEnd', callback)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
var callbackRemove = function () {
that.removeBackdrop()
callback && callback()
}
$.support.transition && this.$element.hasClass('fade') ?
this.$backdrop
.one('bsTransitionEnd', callbackRemove)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callbackRemove()
} else if (callback) {
callback()
}
}
// these following methods are used to handle overflowing modals
Modal.prototype.handleUpdate = function () {
this.adjustDialog()
}
Modal.prototype.adjustDialog = function () {
var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight
this.$element.css({
paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
})
}
Modal.prototype.resetAdjustments = function () {
this.$element.css({
paddingLeft: '',
paddingRight: ''
})
}
Modal.prototype.checkScrollbar = function () {
var fullWindowWidth = window.innerWidth
if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8
var documentElementRect = document.documentElement.getBoundingClientRect()
fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left)
}
this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth
this.scrollbarWidth = this.measureScrollbar()
}
Modal.prototype.setScrollbar = function () {
var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
this.originalBodyPad = document.body.style.paddingRight || ''
if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
}
Modal.prototype.resetScrollbar = function () {
this.$body.css('padding-right', this.originalBodyPad)
}
Modal.prototype.measureScrollbar = function () { // thx walsh
var scrollDiv = document.createElement('div')
scrollDiv.className = 'modal-scrollbar-measure'
this.$body.append(scrollDiv)
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
this.$body[0].removeChild(scrollDiv)
return scrollbarWidth
}
// MODAL PLUGIN DEFINITION
// =======================
function Plugin(option, _relatedTarget) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget)
else if (options.show) data.show(_relatedTarget)
})
}
var old = $.fn.modal
$.fn.modal = Plugin
$.fn.modal.Constructor = Modal
// MODAL NO CONFLICT
// =================
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
// MODAL DATA-API
// ==============
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
if ($this.is('a')) e.preventDefault()
$target.one('show.bs.modal', function (showEvent) {
if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
$target.one('hidden.bs.modal', function () {
$this.is(':visible') && $this.trigger('focus')
})
})
Plugin.call($target, option, this)
})
}(jQuery);
/* ========================================================================
* Bootstrap: tooltip.js v3.3.7
* http://getbootstrap.com/javascript/#tooltip
* Inspired by the original jQuery.tipsy by Jason Frame
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TOOLTIP PUBLIC CLASS DEFINITION
// ===============================
var Tooltip = function (element, options) {
this.type = null
this.options = null
this.enabled = null
this.timeout = null
this.hoverState = null
this.$element = null
this.inState = null
this.init('tooltip', element, options)
}
Tooltip.VERSION = '3.3.7'
Tooltip.TRANSITION_DURATION = 150
Tooltip.DEFAULTS = {
animation: true,
placement: 'top',
selector: false,
template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
container: false,
viewport: {
selector: 'body',
padding: 0
}
}
Tooltip.prototype.init = function (type, element, options) {
this.enabled = true
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
this.$viewport = this.options.viewport && $($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport))
this.inState = { click: false, hover: false, focus: false }
if (this.$element[0] instanceof document.constructor && !this.options.selector) {
throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!')
}
var triggers = this.options.trigger.split(' ')
for (var i = triggers.length; i--;) {
var trigger = triggers[i]
if (trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (trigger != 'manual') {
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'
var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
}
}
this.options.selector ?
(this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
this.fixTitle()
}
Tooltip.prototype.getDefaults = function () {
return Tooltip.DEFAULTS
}
Tooltip.prototype.getOptions = function (options) {
options = $.extend({}, this.getDefaults(), this.$element.data(), options)
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay,
hide: options.delay
}
}
return options
}
Tooltip.prototype.getDelegateOptions = function () {
var options = {}
var defaults = this.getDefaults()
this._options && $.each(this._options, function (key, value) {
if (defaults[key] != value) options[key] = value
})
return options
}
Tooltip.prototype.enter = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
if (obj instanceof $.Event) {
self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true
}
if (self.tip().hasClass('in') || self.hoverState == 'in') {
self.hoverState = 'in'
return
}
clearTimeout(self.timeout)
self.hoverState = 'in'
if (!self.options.delay || !self.options.delay.show) return self.show()
self.timeout = setTimeout(function () {
if (self.hoverState == 'in') self.show()
}, self.options.delay.show)
}
Tooltip.prototype.isInStateTrue = function () {
for (var key in this.inState) {
if (this.inState[key]) return true
}
return false
}
Tooltip.prototype.leave = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
if (obj instanceof $.Event) {
self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false
}
if (self.isInStateTrue()) return
clearTimeout(self.timeout)
self.hoverState = 'out'
if (!self.options.delay || !self.options.delay.hide) return self.hide()
self.timeout = setTimeout(function () {
if (self.hoverState == 'out') self.hide()
}, self.options.delay.hide)
}
Tooltip.prototype.show = function () {
var e = $.Event('show.bs.' + this.type)
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])
if (e.isDefaultPrevented() || !inDom) return
var that = this
var $tip = this.tip()
var tipId = this.getUID(this.type)
this.setContent()
$tip.attr('id', tipId)
this.$element.attr('aria-describedby', tipId)
if (this.options.animation) $tip.addClass('fade')
var placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement
var autoToken = /\s?auto?\s?/i
var autoPlace = autoToken.test(placement)
if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
$tip
.detach()
.css({ top: 0, left: 0, display: 'block' })
.addClass(placement)
.data('bs.' + this.type, this)
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
this.$element.trigger('inserted.bs.' + this.type)
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (autoPlace) {
var orgPlacement = placement
var viewportDim = this.getPosition(this.$viewport)
placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top' :
placement == 'top' && pos.top - actualHeight < viewportDim.top ? 'bottom' :
placement == 'right' && pos.right + actualWidth > viewportDim.width ? 'left' :
placement == 'left' && pos.left - actualWidth < viewportDim.left ? 'right' :
placement
$tip
.removeClass(orgPlacement)
.addClass(placement)
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
var complete = function () {
var prevHoverState = that.hoverState
that.$element.trigger('shown.bs.' + that.type)
that.hoverState = null
if (prevHoverState == 'out') that.leave(that)
}
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
}
}
Tooltip.prototype.applyPlacement = function (offset, placement) {
var $tip = this.tip()
var width = $tip[0].offsetWidth
var height = $tip[0].offsetHeight
// manually read margins because getBoundingClientRect includes difference
var marginTop = parseInt($tip.css('margin-top'), 10)
var marginLeft = parseInt($tip.css('margin-left'), 10)
// we must check for NaN for ie 8/9
if (isNaN(marginTop)) marginTop = 0
if (isNaN(marginLeft)) marginLeft = 0
offset.top += marginTop
offset.left += marginLeft
// $.fn.offset doesn't round pixel values
// so we use setOffset directly with our own function B-0
$.offset.setOffset($tip[0], $.extend({
using: function (props) {
$tip.css({
top: Math.round(props.top),
left: Math.round(props.left)
})
}
}, offset), 0)
$tip.addClass('in')
// check to see if placing tip in new offset caused the tip to resize itself
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (placement == 'top' && actualHeight != height) {
offset.top = offset.top + height - actualHeight
}
var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)
if (delta.left) offset.left += delta.left
else offset.top += delta.top
var isVertical = /top|bottom/.test(placement)
var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight'
$tip.offset(offset)
this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical)
}
Tooltip.prototype.replaceArrow = function (delta, dimension, isVertical) {
this.arrow()
.css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%')
.css(isVertical ? 'top' : 'left', '')
}
Tooltip.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
}
Tooltip.prototype.hide = function (callback) {
var that = this
var $tip = $(this.$tip)
var e = $.Event('hide.bs.' + this.type)
function complete() {
if (that.hoverState != 'in') $tip.detach()
if (that.$element) { // TODO: Check whether guarding this code with this `if` is really necessary.
that.$element
.removeAttr('aria-describedby')
.trigger('hidden.bs.' + that.type)
}
callback && callback()
}
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$tip.removeClass('in')
$.support.transition && $tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
this.hoverState = null
return this
}
Tooltip.prototype.fixTitle = function () {
var $e = this.$element
if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') {
$e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
}
}
Tooltip.prototype.hasContent = function () {
return this.getTitle()
}
Tooltip.prototype.getPosition = function ($element) {
$element = $element || this.$element
var el = $element[0]
var isBody = el.tagName == 'BODY'
var elRect = el.getBoundingClientRect()
if (elRect.width == null) {
// width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093
elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top })
}
var isSvg = window.SVGElement && el instanceof window.SVGElement
// Avoid using $.offset() on SVGs since it gives incorrect results in jQuery 3.
// See https://github.com/twbs/bootstrap/issues/20280
var elOffset = isBody ? { top: 0, left: 0 } : (isSvg ? null : $element.offset())
var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }
var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null
return $.extend({}, elRect, scroll, outerDims, elOffset)
}
Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
/* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
}
Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
var delta = { top: 0, left: 0 }
if (!this.$viewport) return delta
var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
var viewportDimensions = this.getPosition(this.$viewport)
if (/right|left/.test(placement)) {
var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll
var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
if (topEdgeOffset < viewportDimensions.top) { // top overflow
delta.top = viewportDimensions.top - topEdgeOffset
} else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
}
} else {
var leftEdgeOffset = pos.left - viewportPadding
var rightEdgeOffset = pos.left + viewportPadding + actualWidth
if (leftEdgeOffset < viewportDimensions.left) { // left overflow
delta.left = viewportDimensions.left - leftEdgeOffset
} else if (rightEdgeOffset > viewportDimensions.right) { // right overflow
delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
}
}
return delta
}
Tooltip.prototype.getTitle = function () {
var title
var $e = this.$element
var o = this.options
title = $e.attr('data-original-title')
|| (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
}
Tooltip.prototype.getUID = function (prefix) {
do prefix += ~~(Math.random() * 1000000)
while (document.getElementById(prefix))
return prefix
}
Tooltip.prototype.tip = function () {
if (!this.$tip) {
this.$tip = $(this.options.template)
if (this.$tip.length != 1) {
throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!')
}
}
return this.$tip
}
Tooltip.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
}
Tooltip.prototype.enable = function () {
this.enabled = true
}
Tooltip.prototype.disable = function () {
this.enabled = false
}
Tooltip.prototype.toggleEnabled = function () {
this.enabled = !this.enabled
}
Tooltip.prototype.toggle = function (e) {
var self = this
if (e) {
self = $(e.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(e.currentTarget, this.getDelegateOptions())
$(e.currentTarget).data('bs.' + this.type, self)
}
}
if (e) {
self.inState.click = !self.inState.click
if (self.isInStateTrue()) self.enter(self)
else self.leave(self)
} else {
self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
}
}
Tooltip.prototype.destroy = function () {
var that = this
clearTimeout(this.timeout)
this.hide(function () {
that.$element.off('.' + that.type).removeData('bs.' + that.type)
if (that.$tip) {
that.$tip.detach()
}
that.$tip = null
that.$arrow = null
that.$viewport = null
that.$element = null
})
}
// TOOLTIP PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data && /destroy|hide/.test(option)) return
if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tooltip
$.fn.tooltip = Plugin
$.fn.tooltip.Constructor = Tooltip
// TOOLTIP NO CONFLICT
// ===================
$.fn.tooltip.noConflict = function () {
$.fn.tooltip = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: popover.js v3.3.7
* http://getbootstrap.com/javascript/#popovers
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// POPOVER PUBLIC CLASS DEFINITION
// ===============================
var Popover = function (element, options) {
this.init('popover', element, options)
}
if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
Popover.VERSION = '3.3.7'
Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
// NOTE: POPOVER EXTENDS tooltip.js
// ================================
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
Popover.prototype.constructor = Popover
Popover.prototype.getDefaults = function () {
return Popover.DEFAULTS
}
Popover.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
var content = this.getContent()
$tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
$tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events
this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
](content)
$tip.removeClass('fade top bottom left right in')
// IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
// this manually by checking the contents.
if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
}
Popover.prototype.hasContent = function () {
return this.getTitle() || this.getContent()
}
Popover.prototype.getContent = function () {
var $e = this.$element
var o = this.options
return $e.attr('data-content')
|| (typeof o.content == 'function' ?
o.content.call($e[0]) :
o.content)
}
Popover.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
}
// POPOVER PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.popover')
var options = typeof option == 'object' && option
if (!data && /destroy|hide/.test(option)) return
if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.popover
$.fn.popover = Plugin
$.fn.popover.Constructor = Popover
// POPOVER NO CONFLICT
// ===================
$.fn.popover.noConflict = function () {
$.fn.popover = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: tab.js v3.3.7
* http://getbootstrap.com/javascript/#tabs
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TAB CLASS DEFINITION
// ====================
var Tab = function (element) {
// jscs:disable requireDollarBeforejQueryAssignment
this.element = $(element)
// jscs:enable requireDollarBeforejQueryAssignment
}
Tab.VERSION = '3.3.7'
Tab.TRANSITION_DURATION = 150
Tab.prototype.show = function () {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
if ($this.parent('li').hasClass('active')) return
var $previous = $ul.find('.active:last a')
var hideEvent = $.Event('hide.bs.tab', {
relatedTarget: $this[0]
})
var showEvent = $.Event('show.bs.tab', {
relatedTarget: $previous[0]
})
$previous.trigger(hideEvent)
$this.trigger(showEvent)
if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return
var $target = $(selector)
this.activate($this.closest('li'), $ul)
this.activate($target, $target.parent(), function () {
$previous.trigger({
type: 'hidden.bs.tab',
relatedTarget: $this[0]
})
$this.trigger({
type: 'shown.bs.tab',
relatedTarget: $previous[0]
})
})
}
Tab.prototype.activate = function (element, container, callback) {
var $active = container.find('> .active')
var transition = callback
&& $.support.transition
&& ($active.length && $active.hasClass('fade') || !!container.find('> .fade').length)
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', false)
element
.addClass('active')
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu').length) {
element
.closest('li.dropdown')
.addClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
}
callback && callback()
}
$active.length && transition ?
$active
.one('bsTransitionEnd', next)
.emulateTransitionEnd(Tab.TRANSITION_DURATION) :
next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data) $this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tab
$.fn.tab = Plugin
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function () {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
var clickHandler = function (e) {
e.preventDefault()
Plugin.call($(this), 'show')
}
$(document)
.on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler)
.on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler)
}(jQuery);
/* ========================================================================
* Bootstrap: affix.js v3.3.7
* http://getbootstrap.com/javascript/#affix
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// AFFIX CLASS DEFINITION
// ======================
var Affix = function (element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$target = $(this.options.target)
.on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
this.$element = $(element)
this.affixed = null
this.unpin = null
this.pinnedOffset = null
this.checkPosition()
}
Affix.VERSION = '3.3.7'
Affix.RESET = 'affix affix-top affix-bottom'
Affix.DEFAULTS = {
offset: 0,
target: window
}
Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) {
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
var targetHeight = this.$target.height()
if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false
if (this.affixed == 'bottom') {
if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
}
var initializing = this.affixed == null
var colliderTop = initializing ? scrollTop : position.top
var colliderHeight = initializing ? targetHeight : height
if (offsetTop != null && scrollTop <= offsetTop) return 'top'
if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'
return false
}
Affix.prototype.getPinnedOffset = function () {
if (this.pinnedOffset) return this.pinnedOffset
this.$element.removeClass(Affix.RESET).addClass('affix')
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
return (this.pinnedOffset = position.top - scrollTop)
}
Affix.prototype.checkPositionWithEventLoop = function () {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function () {
if (!this.$element.is(':visible')) return
var height = this.$element.height()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
var scrollHeight = Math.max($(document).height(), $(document.body).height())
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element)
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)
if (this.affixed != affix) {
if (this.unpin != null) this.$element.css('top', '')
var affixType = 'affix' + (affix ? '-' + affix : '')
var e = $.Event(affixType + '.bs.affix')
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
this.affixed = affix
this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
this.$element
.removeClass(Affix.RESET)
.addClass(affixType)
.trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
}
if (affix == 'bottom') {
this.$element.offset({
top: scrollHeight - height - offsetBottom
})
}
}
// AFFIX PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.affix
$.fn.affix = Plugin
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
// =================
$.fn.affix.noConflict = function () {
$.fn.affix = old
return this
}
// AFFIX DATA-API
// ==============
$(window).on('load', function () {
$('[data-spy="affix"]').each(function () {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom
if (data.offsetTop != null) data.offset.top = data.offsetTop
Plugin.call($spy, data)
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: collapse.js v3.3.7
* http://getbootstrap.com/javascript/#collapse
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
/* jshint latedef: false */
+function ($) {
'use strict';
// COLLAPSE PUBLIC CLASS DEFINITION
// ================================
var Collapse = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Collapse.DEFAULTS, options)
this.$trigger = $('[data-toggle="collapse"][href="#' + element.id + '"],' +
'[data-toggle="collapse"][data-target="#' + element.id + '"]')
this.transitioning = null
if (this.options.parent) {
this.$parent = this.getParent()
} else {
this.addAriaAndCollapsedClass(this.$element, this.$trigger)
}
if (this.options.toggle) this.toggle()
}
Collapse.VERSION = '3.3.7'
Collapse.TRANSITION_DURATION = 350
Collapse.DEFAULTS = {
toggle: true
}
Collapse.prototype.dimension = function () {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
Collapse.prototype.show = function () {
if (this.transitioning || this.$element.hasClass('in')) return
var activesData
var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing')
if (actives && actives.length) {
activesData = actives.data('bs.collapse')
if (activesData && activesData.transitioning) return
}
var startEvent = $.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
if (actives && actives.length) {
Plugin.call(actives, 'hide')
activesData || actives.data('bs.collapse', null)
}
var dimension = this.dimension()
this.$element
.removeClass('collapse')
.addClass('collapsing')[dimension](0)
.attr('aria-expanded', true)
this.$trigger
.removeClass('collapsed')
.attr('aria-expanded', true)
this.transitioning = 1
var complete = function () {
this.$element
.removeClass('collapsing')
.addClass('collapse in')[dimension]('')
this.transitioning = 0
this.$element
.trigger('shown.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
var scrollSize = $.camelCase(['scroll', dimension].join('-'))
this.$element
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])
}
Collapse.prototype.hide = function () {
if (this.transitioning || !this.$element.hasClass('in')) return
var startEvent = $.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var dimension = this.dimension()
this.$element[dimension](this.$element[dimension]())[0].offsetHeight
this.$element
.addClass('collapsing')
.removeClass('collapse in')
.attr('aria-expanded', false)
this.$trigger
.addClass('collapsed')
.attr('aria-expanded', false)
this.transitioning = 1
var complete = function () {
this.transitioning = 0
this.$element
.removeClass('collapsing')
.addClass('collapse')
.trigger('hidden.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
this.$element
[dimension](0)
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)
}
Collapse.prototype.toggle = function () {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
Collapse.prototype.getParent = function () {
return $(this.options.parent)
.find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]')
.each($.proxy(function (i, element) {
var $element = $(element)
this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element)
}, this))
.end()
}
Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) {
var isOpen = $element.hasClass('in')
$element.attr('aria-expanded', isOpen)
$trigger
.toggleClass('collapsed', !isOpen)
.attr('aria-expanded', isOpen)
}
function getTargetFromTrigger($trigger) {
var href
var target = $trigger.attr('data-target')
|| (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7
return $(target)
}
// COLLAPSE PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.collapse')
var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false
if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.collapse
$.fn.collapse = Plugin
$.fn.collapse.Constructor = Collapse
// COLLAPSE NO CONFLICT
// ====================
$.fn.collapse.noConflict = function () {
$.fn.collapse = old
return this
}
// COLLAPSE DATA-API
// =================
$(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) {
var $this = $(this)
if (!$this.attr('data-target')) e.preventDefault()
var $target = getTargetFromTrigger($this)
var data = $target.data('bs.collapse')
var option = data ? 'toggle' : $this.data()
Plugin.call($target, option)
})
}(jQuery);
/* ========================================================================
* Bootstrap: scrollspy.js v3.3.7
* http://getbootstrap.com/javascript/#scrollspy
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// SCROLLSPY CLASS DEFINITION
// ==========================
function ScrollSpy(element, options) {
this.$body = $(document.body)
this.$scrollElement = $(element).is(document.body) ? $(window) : $(element)
this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
this.selector = (this.options.target || '') + ' .nav li > a'
this.offsets = []
this.targets = []
this.activeTarget = null
this.scrollHeight = 0
this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this))
this.refresh()
this.process()
}
ScrollSpy.VERSION = '3.3.7'
ScrollSpy.DEFAULTS = {
offset: 10
}
ScrollSpy.prototype.getScrollHeight = function () {
return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
}
ScrollSpy.prototype.refresh = function () {
var that = this
var offsetMethod = 'offset'
var offsetBase = 0
this.offsets = []
this.targets = []
this.scrollHeight = this.getScrollHeight()
if (!$.isWindow(this.$scrollElement[0])) {
offsetMethod = 'position'
offsetBase = this.$scrollElement.scrollTop()
}
this.$body
.find(this.selector)
.map(function () {
var $el = $(this)
var href = $el.data('target') || $el.attr('href')
var $href = /^#./.test(href) && $(href)
return ($href
&& $href.length
&& $href.is(':visible')
&& [[$href[offsetMethod]().top + offsetBase, href]]) || null
})
.sort(function (a, b) { return a[0] - b[0] })
.each(function () {
that.offsets.push(this[0])
that.targets.push(this[1])
})
}
ScrollSpy.prototype.process = function () {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
var scrollHeight = this.getScrollHeight()
var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height()
var offsets = this.offsets
var targets = this.targets
var activeTarget = this.activeTarget
var i
if (this.scrollHeight != scrollHeight) {
this.refresh()
}
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
}
if (activeTarget && scrollTop < offsets[0]) {
this.activeTarget = null
return this.clear()
}
for (i = offsets.length; i--;) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (offsets[i + 1] === undefined || scrollTop < offsets[i + 1])
&& this.activate(targets[i])
}
}
ScrollSpy.prototype.activate = function (target) {
this.activeTarget = target
this.clear()
var selector = this.selector +
'[data-target="' + target + '"],' +
this.selector + '[href="' + target + '"]'
var active = $(selector)
.parents('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active
.closest('li.dropdown')
.addClass('active')
}
active.trigger('activate.bs.scrollspy')
}
ScrollSpy.prototype.clear = function () {
$(this.selector)
.parentsUntil(this.options.target, '.active')
.removeClass('active')
}
// SCROLLSPY PLUGIN DEFINITION
// ===========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.scrollspy')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.scrollspy
$.fn.scrollspy = Plugin
$.fn.scrollspy.Constructor = ScrollSpy
// SCROLLSPY NO CONFLICT
// =====================
$.fn.scrollspy.noConflict = function () {
$.fn.scrollspy = old
return this
}
// SCROLLSPY DATA-API
// ==================
$(window).on('load.bs.scrollspy.data-api', function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this)
Plugin.call($spy, $spy.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: transition.js v3.3.7
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
WebkitTransition : 'webkitTransitionEnd',
MozTransition : 'transitionend',
OTransition : 'oTransitionEnd otransitionend',
transition : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false
var $el = this
$(this).one('bsTransitionEnd', function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
$(function () {
$.support.transition = transitionEnd()
if (!$.support.transition) return
$.event.special.bsTransitionEnd = {
bindType: $.support.transition.end,
delegateType: $.support.transition.end,
handle: function (e) {
if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
}
}
})
}(jQuery);
|
/**
* Copyright 2013 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var Auth2Client = require('./oauth2client.js');
var util = require('util');
/**
* Google Compute Engine metadata server token endpoint.
* @private
*/
Compute.GOOGLE_OAUTH2_TOKEN_URL_ =
'http://metadata/computeMetadata/v1beta1/instance/service-accounts/default/token';
/**
* Google Compute Engine service account credentials.
*
* Retrieve access token from the metadata server.
* See: https://developers.google.com/compute/docs/authentication
* @constructor@constructor
*/
function Compute() {
Compute.super_.call(this);
}
/**
* Inherit from Auth2Client.
*/
util.inherits(Compute, Auth2Client);
/**
* Get the initial access token from compute metadata server.
* @param {function=} opt_callback Optional callback.
*/
Compute.prototype.authorize = function(opt_callback) {
var that = this;
that.refreshToken_(null, function(err, result) {
if (!err) {
that.credentials = result;
that.credentials.refresh_token = 'compute-placeholder';
}
opt_callback && opt_callback(err, result);
});
};
/**
* Refreshes the access token.
* @param {object=} ignored_
* @param {function=} opt_callback Optional callback.
* @private
*/
Compute.prototype.refreshToken_ = function(ignored_, opt_callback) {
var uri = this.opts.tokenUrl || Compute.GOOGLE_OAUTH2_TOKEN_URL_;
// request for new token
this.transporter.request({
method: 'GET',
uri: uri,
json: true
}, opt_callback);
};
/**
* Export Compute.
*/
module.exports = Compute;
|
var gulp = require("gulp");
var browserSync = require('browser-sync');
var less = require("gulp-less");
var plumber = require("gulp-plumber");
var notify = require("gulp-notify");
var cleanCSS = require("gulp-clean-css");
var minifyJs = require("gulp-minify");
var rename = require("gulp-rename");
gulp.task("move", function () {
return gulp.src(
['./bower_components/marked/**/*marked*js',
'./bower_components/highlightjs/**/*highlight*js',
'./bower_components/highlightjs/**/*css',
'./bower_components/jquery/dist/**/*js',
'./bower_components/font-awesome/css/**/*css',
'./bower_components/font-awesome/fonts/*',
'./bower_components/FileSaver.js/**/*FileSaver*js',
'./bower_components/js-beautify/js/lib/*beautify*js',
'./bower_components/loaders.css/*load*css',
'./bower_components/emojify.js/dist/css/**/*css',
'./bower_components/emojify.js/dist/js/**/*js',
'./bower_components/remodal/dist/**/*css',
'./bower_components/remodal/dist/**/*js',
'./bower_components/bower-webfontloader/**/*webfont*js',
'./bower_components/snap.svg/dist/**/*snap*js',
'./bower_components/underscore/**/*underscore*js',
'./bower_components/js-sequence-diagrams/dist/**/*sequence-diagram*js',
'./bower_components/js-sequence-diagrams/dist/**/*sequence-diagram*css',
'./bower_components/js-sequence-diagrams/dist/**/*sequence-diagram*map',
'./bower_components/magic-check/**/*magic-check*css',
'./bower_components/echarts/dist/**/*js',
'./bower_components/echarts/theme/**/*js',
'./bower_components/sweetalert/dist/**/*',
'./bower_components/fancybox/source/**/*',
'./bower_components/fancybox/lib/**/*'
],
{
base: './bower_components'
}
).pipe(gulp.dest('assets/lib'))
});
gulp.task("lib", function() {
return gulp.src(
['assets/lib/highlightjs/**/*',
'assets/lib/prism/**/*',
'assets/lib/bower-webfontloader/**/*',
'assets/lib/js-sequence-diagrams/**/*',
'assets/lib/magic-check/**/*',
],
{
base: './assets'
}
).pipe(gulp.dest("dist"));
});
gulp.task('browserSync', function () {
browserSync({
server: {
baseDir: '.'
},
port: 81
})
});
gulp.task('less', function () {
gulp.src("src/**/*.less", {base: "src/less"})
.pipe(plumber({errorHandler: notify.onError("Error: <%=error.message%>")}))
.pipe(less())
.pipe(gulp.dest("assets/css/"))
.pipe(browserSync.reload({
stream: true
}));
});
gulp.task('minify-css', function() {
return gulp.src('assets/css/*.css')
.pipe(cleanCSS({compatibility: 'ie8'}))
.pipe(rename({
suffix: '.min'
}))
.pipe(gulp.dest('dist/css'));
});
gulp.task('copy-css', function() {
return gulp.src('assets/css/*.css')
.pipe(gulp.dest('dist/css'));
});
gulp.task('minify-js', function() {
gulp.src('src/js/*.js')
.pipe(minifyJs({
ext:{
src:'.js',
min:'.min.js'
},
exclude: ['tasks'],
ignoreFiles: ['.combo.js', '-min.js']
})).pipe(gulp.dest('dist/js'));
gulp.src('assets/lib/echarts/theme/*.js')
.pipe(minifyJs({
ext:{
src:'.js',
min:'.min.js'
},
exclude: ['tasks'],
ignoreFiles: ['.combo.js', '-min.js']
})).pipe(gulp.dest('dist/js/echarts-theme/'));
});
gulp.task("compress", ['minify-css', 'copy-css', 'minify-js']);
gulp.task("watch", function () {
gulp.watch("src/**/*.less", ["less"]);
gulp.watch("./**/*.html", browserSync.reload);
gulp.watch("src/**/*.js", browserSync.reload);
gulp.watch("assets/**/*.css", browserSync.reload);
});
gulp.task('default', ['browserSync', 'watch', 'less']); |
import React from 'react'
import { storiesOf } from '@storybook/react'
import {
FileUploadIllustration,
LoginIllustration,
SearchIllustration,
SearchNoResultIllustration,
} from 'fyndiq-illustrations'
const h2 = {
color: '#666',
fontSize: '15px',
padding: '8px 10px',
background: '#EEE',
fontFamily: 'monospace',
}
storiesOf('Illustrations', module)
.addWithInfo('search', () => (
<div>
<h2 style={h2}><SearchIllustration /></h2>
<SearchIllustration />
<h2 style={h2}><SearchNoResultIllustration /></h2>
<SearchNoResultIllustration />
</div>
))
.addWithInfo('login', () => (
<div>
<h2 style={h2}><LoginIllustration /></h2>
<LoginIllustration />
</div>
))
.addWithInfo('file', () => (
<div>
<h2 style={h2}><FileUploadIllustration /></h2>
<FileUploadIllustration />
</div>
))
|
/**
* Test
*
* @module :: Model
* @description :: A short summary of how this model works and what it represents.
*
*/
module.exports = {
attributes: {
/* e.g.
nickname: 'string'
*/
}
};
|
'use strict'
/**
* The partitioning mode used by the tessellator to derive the number and spacing of segments used to subdivide a corresponding edge.
* @typedef {Object} MTLTessellationPartitionMode
* @property {number} pow2 -
* @property {number} integer -
* @property {number} fractionalOdd -
* @property {number} fractionalEven -
* @see https://developer.apple.com/documentation/metal/mtltessellationpartitionmode
*/
const MTLTessellationPartitionMode = {
pow2: 0,
integer: 1,
fractionalOdd: 2,
fractionalEven: 3
}
export default MTLTessellationPartitionMode
|
define(['dispatcher', 'slider/slider.store'], function(dispatcher, store) {
"use strict";
var items = {}
var idName = 'slider-arrow-id-';
var idNum = 1;
var _handleChange = function() {
var storeData = store.getData();
var checkItem = function(item) {
var id;
var itemData;
id = item.sliders[0];
if (!storeData.items.hasOwnProperty(id)) return;
itemData = storeData.items[id];
if (!item.hidden && item.slide === 'prev' && itemData.index === 0) {
item.hidden = true;
item.element.classList.add('hidden');
} else if (item.hidden && item.slide === 'prev' && itemData.index !== 0) {
item.hidden = false;
item.element.classList.remove('hidden');
}
if (!item.hidden && item.slide === 'next' && itemData.index === itemData.total) {
item.hidden = true;
item.element.classList.add('hidden');
} else if (item.hidden && item.slide === 'next' && itemData.index !== itemData.total) {
item.hidden = false;
item.element.classList.remove('hidden');
}
}
for (var id in items) {
if (items.hasOwnProperty(id)) {
checkItem(items[id]);
}
}
}
var _add = function(items, element) {
var id = element.getAttribute('data-id');
var sliderString = element.getAttribute('data-sliders');
var sliders;
var slide = element.getAttribute('data-slide');
if (!id) {
id = idName + idNum;
idNum++;
}
if (!sliderString) {
console.warn('data-sliders attribute is missing');
return;
}
if (!slide) {
console.warn('data-slide attribute is missing');
return;
}
sliders = sliderString.split('||');
element.addEventListener('click', function() {
for (var i = sliders.length - 1; i >= 0; i--) {
dispatcher.dispatch({
type: 'slider-change-' + slide,
id: sliders[i]
});
}
}, false);
items[id] = {
id: id,
sliders: sliders,
slide: slide,
hidden: false,
element: element
}
}
var _remove = function(items, item) {
delete items[item.id];
}
var _handleMutate = function() {
var elements;
var check = function(items, element) {
var found = false;
for (var id in items) {
if (items.hasOwnProperty(id)) {
if (items[id].element === element) {
found = true;
break;
}
}
}
if (!found) {
_add(items, element);
}
}
var backCheck = function(items, elements, item) {
var element = item.element;
var found = false;
for (var i = 0; i < elements.length; i++) {
if (elements[i] === item.element) {
found = true;
break;
}
}
if (!found) {
_remove(items, item);
}
}
elements = document.getElementsByClassName('view-slider-arrow');
for (var i = 0; i < elements.length; i++) {
check(items, elements[i]);
}
for (var id in items) {
if (items.hasOwnProperty(id)) {
backCheck(items, elements, items[id]);
}
}
}
var init = function() {
_handleMutate();
_handleChange();
store.eventEmitter.subscribe(_handleChange);
dispatcher.subscribe(function(e) {
if (e.type === 'mutate') {
setTimeout(function() {
_handleMutate();
_handleChange();
}, 0);
}
});
}
return {
init: init
}
}); |
const extend = require('deep-extend')
function addCraftCofig (files = {}, context) {
// If Craft
if (context.props.projectusage === 'craft' || context.props.projectusage === 'craftCB') {
extend(files.pkg, {
'dist': {
'dist': 'dist/',
'base': 'dist/public/',
'markup': 'dist/craft/',
'templates': 'dist/craft/templates',
'assets': 'dist/public/assets/',
'browserSyncDir': 'dist/public/',
'css': 'dist/public/assets/css/',
'js': 'dist/public/assets/js/',
'fonts': 'dist/public/assets/fonts/',
'cssimg': 'dist/public/assets/img/',
'bitmaps': 'dist/public/assets/img/bitmaps/',
'vectors': 'dist/public/assets/img/svgfiles/',
'contentimage': 'dist/public/images/',
'webpackassets': 'assets/',
'webpackcssassets': 'assets/css/',
'webpackpublic': 'dist/public/'
},
'src': {
'plugins': 'src/craftplugins/',
'templates': 'src/structure/templates/'
},
'minify': {
'purgeCSS': [
'src/structure/templates/**/*.{html,twig}',
'src/js/**/*.vue'
]
}
})
}
if (context.props.projectusage === 'craftCB') {
extend(files.pkg, {
'cssabove': {
'width': '1200',
'height': '1024',
'minify': true,
'inline': false,
'url': context.props.credentialdomain !== 'undefined' ? `http://${context.props.credentialdomain}` : 'http://',
'cssfile': context.props.projectcssfilename + '.css',
'include': [
'.plj .c-progressLoader',
'.plj .c-progressLoader--complete .c-progressLoader',
'.plj .o-area__wrapper',
'.plj .is-livepreview .o-area__wrapper',
'.plj .c-progressLoader__loader',
'.plj .c-progressLoader__loader.c-progressLoader--bar--complete'
],
'ignore': [
'@font-face'
],
'sites': [
{
'url': '',
'template': 'index'
},
{
'url': '/blog/hello-world',
'template': 'general/entry'
},
{
'url': '/blog',
'template': 'general/index'
},
{
'url': '/404',
'template': '404'
}
]
}
})
}
if (context.props.projectcraft3 === true) {
extend(files.pkg, {
'dist': {
'base': 'dist/web/',
'markup': 'dist/',
'templates': 'dist/templates',
'assets': 'dist/web/assets/',
'browserSyncDir': 'dist/web/',
'css': 'dist/web/assets/css/',
'js': 'dist/web/assets/js/',
'fonts': 'dist/web/assets/fonts/',
'cssimg': 'dist/web/assets/img/',
'bitmaps': 'dist/web/assets/img/bitmaps/',
'vectors': 'dist/web/assets/img/svgfiles/',
'contentimage': 'dist/web/images/',
'webpackassets': 'assets/',
'webpackcssassets': 'assets/css/',
'webpackpublic': 'dist/web/'
},
'src': {
'plugins': 'src/craftplugins/',
'templates': 'src/structure/templates/'
},
'minify': {
'purgeCSS': [
'src/structure/templates/**/*.{html,twig}',
'src/js/**/*.vue'
]
}
})
}
}
module.exports = addCraftCofig
|
version https://git-lfs.github.com/spec/v1
oid sha256:39c0b016eca99eb576761ac4b8e06966887e87d1d0e80f7b0e87b05a23671a8f
size 183077
|
'use strict';
module.exports = function (grunt) {
grunt.config('jshint', {
options: {
jshintrc: '.jshintrc'
},
src: ['gruntfile.js', 'grunt/**/*.js', 'src/**/*.js', 'demo/**/*.js']
});
grunt.config('jscs', {
options: {
config: '.jscs.json'
},
src: ['gruntfile.js', 'grunt/**/*.js', 'src/**/*.js', 'demo/**/*.js']
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-jscs');
};
|
'use strict';
var _ = require('lodash'),
async = require('async'),
moment = require('moment'),
cheerio = require('cheerio'),
request = require('request'),
url = require('url'),
util = require('util'),
searchQueue,
onComplete,
requests = require('./requests');
searchQueue = async.queue(doRequest, 3);
searchQueue.drain = function() {
requests.onComplete(onComplete);
};
/**
* Accept the options for a search & initialise search queue
* For each
*/
module.exports = function(options, callback) {
onComplete = callback;
startRequests(options);
};
function doRequest(options, callback) {
var uri = options.searchURI;
request({
strictSSL: false,
uri: uri
}, function(err, response, body) {
if (err) {
return callback(err);
}
parseBody(_.assign({}, options, {
body: body
}), callback);
});
}
function parseBody(options, callback) {
var body = options.body,
uri = options.searchURI,
$ = cheerio.load(body),
next = $('.pagination .next_page').attr('href'),
requestLinks = $('.request_listing .head a');
if (next) {
searchQueue.push(_.assign({}, options, {
searchURI: options.site + next
}));
}
console.log('%s links from %s', requestLinks.length, uri);
_.each(requestLinks, function(link) {
var uri = url.parse($(link).attr('href'));
delete uri.hash;
requests.queueRequest(_.assign({}, options, {
requestURI: url.format(uri) + '.json'
}));
});
callback();
}
function startRequests(options) {
var from = options.from || moment().subtract(10, 'years'),
to = options.to || moment(),
uri,
start,
end;
from = moment(from).startOf('month');
options.from = from.clone();
to = moment(to).startOf('month');
options.to = to.clone();
while (from < to) {
start = from.clone().startOf('month').format('YYYY-MM-DD');
end = from.clone().endOf('month').format('YYYY-MM-DD');
uri = util.format('%s/list/all?query=&request_date_after=%s&request_date_before=%s&commit=Search', options.site, start, end);
searchQueue.push(_.assign({}, options, {
searchURI: uri
}));
from.add(1, 'month');
}
}
|
import ListFormController from 'ember-flexberry/controllers/list-form';
export default ListFormController.extend({
/**
Name of related edit form route.
@property editFormRoute
@type String
@default 'ember-flexberry-dummy-suggestion-type-edit'
*/
editFormRoute: 'ember-flexberry-dummy-suggestion-type-edit'
});
|
var config = require('../config').otp;
var superagent = require('superagent');
/**
* Expose `get`
*/
module.exports.get = function(opts, callback) {
superagent
.get(config.host + ':' + config.port + config.path + opts.url)
.set(opts.headers || {})
.end(function(err, res) {
if (err || res.error || !res.ok) {
console.log(err || res.error || res.text);
callback(err || res.error || res.text);
} else {
callback(null, res.body);
}
});
};
|
// Design Basic Game Solo Challenge
// This is a solo challenge
// Your mission description:
// Overall mission: Become the Kami
// Goals: Collect Items from other people by winning a guessing game.
// Characters: honored_one, sunglasses guy, forest bear, magic flower fairy
// Objects: sunglasses, table, flower magic
// Functions: battle function, add life function.
// Pseudocode
//DEF OBJECTS for characters in the game.
//assign FALSE VALUES for main character.
//assign TRUE VALUES for enemies.
//DEF VAR energy to keep track of life.
//DEF FUNCTION for life status that subtracts the energy and outputs if the person is dead. If they are dead quit the game.
//DEF FUNCTION for battle that takes an ARGUMENT
//have battel function return a random number.
//Compare player answer with random number. If the answer are the same then set the object for hero to true and enemy to false.
//ELSE run the life function.
//Create a story with ALERT, CONFIRM, and PROMPT to send to the function. End the game if the player dies or quits.
// Initial Code
//Must be run in the browser.
var honored_one = {
sunglasses: false,
table: false,
flower_magic: false,
}
var sunglasses_guy = {
sunglasses: true,
}
var forest_bear = {
table: true,
}
var magic_flower_fairy = {
flower_magic: true,
}
var energy = 10;
function death_clock(){
energy = energy - 1;
alert("You have " + energy + " units left on your death clock...");
if(energy === 0){
throw new Error(alert("You are dead."));
}else {
battle(current);
}
}
function battle(enemy){
var decision = prompt("The enemy is challenging you to a dual of evens and odds. What is he holding behind his back? 1 or 2?");
var num = Math.floor(Math.random() * (2 - 1 + 1)) + 1;
if(decision == num){
for(var keys in honored_one){
if(keys == Object.keys(enemy)){
honored_one[keys] = true;
for(var keys in enemy){
enemy[keys] = false;
}
}
}
}else {
death_clock();
}
}
alert("Welcome, most honored one. You have been chosen by the Overlords to have your skills tested.");
alert("You will go on a semi-dangerous mission where you will need to collect three special/awesome/magical items that will give you the power of the Kami!");
var choice = confirm("Will you go on this mission?");
if(choice == true){
alert("Amazing! Lets get to it.");
alert("The Overlords are now transporting you to Sunglasses City. We need to find the one they call \"Sunglasses Guy.\"");
alert("*thinking to yourself* \"geewiz, there sure are a lot of people with sunglasses here\" \n\n ヽ(⌐■_■)ノ♪♬ \n\n (■Д■*) \n\n ⊂(▀¯▀⊂)");
alert("There he is!!!! The angry looking man right over there! \n\n ( ▀ 益 ▀ )");
var b_choice = confirm("Will you battle for the sunglasses?");
if (b_choice == true){
var current = sunglasses_guy;
battle(sunglasses_guy);
}else{
throw new Error(alert("You are dead."));
}
alert("Great Job! You now have the sunglasses! \n\n...but Sunglesses Guy sure looks mad... \n\n ٩(╬ʘ益ʘ╬)۶");
alert("Hold On!, the Overlords are going to transport you to the Forest of Bears where you must find the \"Great Forest Bear\"! You must battle the Great Forest Bear to win his prized table.");
alert("*thinking to yourself* \"man, these bears all look the same...\" \n\n ʕ·ᴥ·ʔ ʕ·ᴥ·ʔ ʕ·ᴥ·ʔ ʕ·ᴥ·ʔ");
alert("Wait, over there! The one that is slightly bigger than the others. That is the Great Forest Bear! \n\n ʕ •ᴥ•ʔ");
var c_choice = confirm("Will you battle for the table?");
if (c_choice == true){
var current = forest_bear;
battle(forest_bear);
}else{
throw new Error(alert("You are dead."));
}
alert("Amazing work! Great Forest Bear is giving you his table. \n\n ʕノ•ᴥ•ʔノ ︵ ┻━┻")
alert("The Overlords are now going to transport you to the Flower Power Garden. You must find the \"Magic Flower Fairy\" and convince it to give you its flower magic.");
alert("*thinking to yourself* \"there are like a lot of magic fairy things here...\" \n\n 炎炎炎炎☆┣o(・ω・ ) \n\n ᕦ( ✿ ⊙ ͜ʖ ⊙ ✿ )━炎炎炎炎炎炎炎炎 \n\n (∩`-´)⊃━☆゚.*・。゚");
alert("Hang on a second, I think it's the one shooting flowers from its wand! \n\n (∩ᄑ_ᄑ)⊃━✿✿✿✿✿✿");
var d_choice = confirm("Will you try to get the flower magic?");
if (d_choice == true){
var current = magic_flower_fairy;
battle(magic_flower_fairy);
}else{
throw new Error(alert("You are dead."));
}
alert("Once again you win! Look at the flower fairy's sad face! \n\n (∩ᄑ_ᄑ)⊃━");
alert("Wait, it cant be....");
alert("Yes! That makes all three special/awesome/magical items yours! \n\n ⌐■-■ \n\n ┻━┻ \n\n ✿✿✿✿✿✿");
alert("Congratulations! You are now the all powerful Kami...(though, slightly less powerful than the Overlords)...but the peasants bow to your glory! \n\n _| ̄|○ ԅ(≖‿≖ԅ) ○| ̄|_");
}else {
throw new Error(alert("You are not welcome here!"));
}
console.log(honored_one);
console.log(sunglasses_guy);
console.log(forest_bear);
console.log(magic_flower_fairy);
// Refactored Code
var honored_one = {
sunglasses: false,
table: false,
flower_magic: false,
}
var enemy = {
sunglasses: true,
table: true,
flower_magic: true,
}
var energy = 10;
function death_clock(){
energy = energy - 1;
alert("You have " + energy + " units left on your death clock...");
if(energy === 0){
throw new Error(alert("You are dead."));
}else {
battle(enemy);
}
}
function battle(enemy){
var decision = prompt("The enemy is challenging you to a dual of evens and odds. What is he holding behind his back? 1 or 2?");
var num = Math.floor(Math.random() * (2 - 1 + 1)) + 1;
if(decision == num){
for(var keys in honored_one){
if(keys == Object.keys(enemy)){
honored_one[keys] = true;
for(var keys in enemy){
enemy[keys] = false;
}
}
}
}else {
death_clock();
}
}
alert("Welcome, most honored one. You have been chosen by the Overlords to have your skills tested.");
alert("You will go on a semi-dangerous mission where you will need to collect three special/awesome/magical items that will give you the power of the Kami!");
var choice = confirm("Will you go on this mission?");
if(choice == true){
alert("Amazing! Lets get to it.");
alert("The Overlords are now transporting you to Sunglasses City. We need to find the one they call \"Sunglasses Guy.\"");
alert("*thinking to yourself* \"geewiz, there sure are a lot of people with sunglasses here\" \n\n ヽ(⌐■_■)ノ♪♬ \n\n (■Д■*) \n\n ⊂(▀¯▀⊂)");
alert("There he is!!!! The angry looking man right over there! \n\n ( ▀ 益 ▀ )");
var choice = confirm("Will you battle for the sunglasses?");
if (choice == true){
battle(enemy);
}else{
throw new Error(alert("You are dead."));
}
alert("Great Job! You now have the sunglasses! \n\n...but Sunglesses Guy sure looks mad... \n\n ٩(╬ʘ益ʘ╬)۶");
alert("Hold On!, the Overlords are going to transport you to the Forest of Bears where you must find the \"Great Forest Bear\"! You must battle the Great Forest Bear to win his prized table.");
alert("*thinking to yourself* \"man, these bears all look the same...\" \n\n ʕ·ᴥ·ʔ ʕ·ᴥ·ʔ ʕ·ᴥ·ʔ ʕ·ᴥ·ʔ");
alert("Wait, over there! The one that is slightly bigger than the others. That is the Great Forest Bear! \n\n ʕ •ᴥ•ʔ");
var choice = confirm("Will you battle for the table?");
if (choice == true){
battle(enemy);
}else{
throw new Error(alert("You are dead."));
}
alert("Amazing work! Great Forest Bear is giving you his table. \n\n ʕノ•ᴥ•ʔノ ︵ ┻━┻")
alert("The Overlords are now going to transport you to the Flower Power Garden. You must find the \"Magic Flower Fairy\" and convince it to give you its flower magic.");
alert("*thinking to yourself* \"there are like a lot of magic fairy things here...\" \n\n 炎炎炎炎☆┣o(・ω・ ) \n\n ᕦ( ✿ ⊙ ͜ʖ ⊙ ✿ )━炎炎炎炎炎炎炎炎 \n\n (∩`-´)⊃━☆゚.*・。゚");
alert("Hang on a second, I think it's the one shooting flowers from its wand! \n\n (∩ᄑ_ᄑ)⊃━✿✿✿✿✿✿");
var choice = confirm("Will you try to get the flower magic?");
if (choice == true){
battle(enemy);
}else{
throw new Error(alert("You are dead."));
}
alert("Once again you win! Look at the flower fairy's sad face! \n\n (∩ᄑ_ᄑ)⊃━");
alert("Wait, it cant be....");
alert("Yes! That makes all three special/awesome/magical items yours! \n\n ⌐■-■ \n\n ┻━┻ \n\n ✿✿✿✿✿✿");
alert("Congratulations! You are now the all powerful Kami...(though, slightly less powerful than the Overlords)...but the peasants bow to your glory! \n\n _| ̄|○ ԅ(≖‿≖ԅ) ○| ̄|_");
}else {
throw new Error(alert("You are not welcome here!"));
}
// Reflection
/*
-What was the most difficult part of this challenge?
At first I really wasn't sure what I even wanted to do, I wasn't sure if my game would be complicated enough
to satisfy the criteria. Other than that, I had a really hard time with my battle() function. I wasn't useing the
correct syntax to target an element and change its value. I was using dot notation and then [" "] brackets with
quotes but what I need were brackets without the quotes.
-What did you learn about creating objects and functions that interact with one another?
It's really hard to manipulate objects in JS. When going through the game and deciding what to do, I think I came
to the conclusion that it would be easier in my case to have arrays instead. Once I got it working, it seems to
do well.
-Did you learn about any new built-in methods you could use in your refactored solution?
If so, what were they and how do they work?
I learned a lot about the for in loop in JS. It's great for going through objects.
-How can you access and manipulate properties of objects?
You can loop through them and target them with some kind of camparison operator.
You can also target them directly if you know what key you want to change.
*/
|
'use strict'
import './Stylesheets'
import Elm from './Main'
let container = document.getElementById('container')
var counter = Elm.Main.embed(container, { path: '/' })
window.onpopstate = event => {
counter.ports.path.send(window.location.hash.split('#')[1])
}
counter.ports.pushPath.subscribe(path => {
window.history.pushState({}, '', window.location.pathname + '#' + path)
counter.ports.path.send(window.location.hash.split('#')[1])
})
|
/** @jsx jsx */
import { Editor } from 'slate'
import { jsx } from '../../..'
export const run = editor => {
Editor.delete(editor, { unit: 'character', distance: 3 })
}
export const input = (
<editor>
<block>
<cursor />
word
</block>
</editor>
)
export const output = (
<editor>
<block>
<cursor />d
</block>
</editor>
)
|
// Don't commit this file to your public repos. This config is for first-run
//
exports.creds = {
returnURL: 'http://localhost:3000/auth/openid/return',
identityMetadata: 'https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration', // For using Microsoft you should never need to change this.
clientID: '02efe21f-6d15-4026-8872-9fcd7d789602', //this POC
clientSecret: 'VO474u6v5or+S4h=', //this POC
//clientID: '01d83438-0130-472a-a1db-28fffee476f9', //silverrockweb
//clientSecret: 'B3|$[N<-(b.0219T', //silverrockweb
skipUserProfile: true, // for AzureAD should be set to true.
responseType: 'id_token', // for login only flows use id_token. For accessing resources use `id_token code`
responseMode: 'form_post', // For login only flows we should have token passed back to us in a POST
//scope: ['email', 'profile'] // additional scopes you may wish to pass
tenantName: 'argoadb2ctest.onmicrosoft.com'
};
|
'use strict'
var mongoose = require('mongoose');
let q = require('q');
let EventModel = require('../model/eventModel');
let FavoriteModel = require('../model/favoriteModel');
class FavoriteDAO {
findUser(req) {
var defer = q.defer();
let eventos = [];
FavoriteModel.find({ userId: req.decoded.id })
.then(result => {
result.map(event => {
EventModel
.findById({
_id: event._doc.eventId
}).then(event => {
return eventos.push(event);
}).then(() => {
defer.resolve(eventos);
})
})
})
return defer.promise;
}
findCompany(req) {
var defer = q.defer();
FavoriteModel.find({
companyId: req.decoded.id
}).then(favorite => {
defer.resolve(favorite._doc);
});
return defer.promise;
}
findPlace(req) {
var defer = q.defer();
FavoriteModel.find({
userId: req.decoded.id
}).then(favorite => {
defer.resolve(favorite);
});
return defer.promise;
}
persist(req) {
const { body } = req;
var defer = q.defer();
FavoriteModel.find({ userId: req.decoded.id })
.then((result) => {
console.log(result);
if (result[0].eventId === body.eventId) {
FavoriteModel
.update({
userId: req.decoded.id
},
{
$set: {
checkIn: body.check,
favorite: body.favorite,
}
}).then((result) => defer.resolve(result));
}
else {
let saveFavorite = new FavoriteModel({
companyId: body.companyId,
eventId: body.eventId,
favorite: body.favorite,
checkIn: body.check,
userId: req.decoded.id,
});
saveFavorite
.save()
.then((result) => {
defer.resolve(result);
})
.catch((err) => {
defer.reject(err);
});
}
});
return defer.promise;
}
}
module.exports = new FavoriteDAO(); |
import assert from 'assert'
import {PrivateKey, PublicKey} from 'shared/ecc'
import {encode, decode} from 'shared/chain/memo'
import {serverApiRecordEvent} from 'app/utils/ServerApiClient'
export const browserTests = {}
export default function runTests() {
let rpt = ''
let pass = true
function it(name, fn) {
console.log('Testing', name)
rpt += 'Testing ' + name + '\n'
try {
fn()
} catch(error) {
console.error(error)
pass = false
rpt += error.stack + '\n\n'
serverApiRecordEvent('client_error', error)
}
}
let private_key, public_key, encodedMemo
const wif = '5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw'
const pubkey = 'GLS8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA'
const _memo = "#memo";
it('create private key', () => {
private_key = PrivateKey.fromSeed('1')
assert.equal(private_key.toWif(), wif)
})
it('supports WIF format', () => {
assert.deepEqual(PrivateKey.fromWif(wif), private_key)
})
it('finds public from private key', () => {
public_key = private_key.toPublicKey()
assert.equal(public_key.toString(), pubkey, 'Public key did not match')
})
it('parses public key', () => {
assert(PublicKey.fromString(public_key.toString()))
})
it('encrypts memo', () => {
encodedMemo = encode(private_key, public_key, _memo)
console.log(encodedMemo)
assert(encodedMemo)
})
it('decripts memo', () => {
const dec = decode(private_key, encodedMemo)
console.log(dec);
console.log(_memo);
if(dec !== '#memo') {
console.error('Decoded memo did not match (memo encryption is unavailable)')
browserTests.memo_encryption = false
}
// TODO: FIX! assert.equal(dec, _memo, 'decoded memo did not match original');
})
if(!pass) return rpt
}
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require twitter/bootstrap
//= require jquery.shapeshift/core/jquery.shapeshift.min
//= require home
//= require_tree .
|
import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
import { Link } from 'react-router';
import {LinkContainer} from 'react-router-bootstrap';
import { Grid, Row, Glyphicon, Col, Button} from 'react-bootstrap';
import * as CHK from "../../../const/ChkConst.js"
export default class GRChecks extends Component {
static propTypes = {
GenR: PropTypes.object.isRequired
};
constructor(props) {
super(props);
this.state = {
loading: false
};
}
toggle() {
this.setState({loading: !this.state.loading});
}
render() {
var isSuccess = true;
const chk ={backgroundColor: 'black' , color: 'green',border: '1px solid blue', padding: '10px 30px 10px 10px' };
const chk1 ={backgroundColor: 'black' , color: 'green',border: '1px solid blue', };
var check0Button,check1Button,check2Button,check3Button;
switch (this.props.GenR.chk0) {
case CHK.SUCCESS:
check0Button =
<Row style={chk} >
<Col xs={10}>Previous Session Check</Col>
<Col xs={2}><Button bsStyle="success"><Glyphicon glyph="ok" /></Button></Col>
</Row>
break;
case CHK.FAILURE:
check0Button =
<Row style={chk} >
<Col xs={10}>Previous Session Check</Col>
<Col xs={2}><Button bsStyle="danger"><Glyphicon glyph="remove" /></Button></Col>
</Row>;
break;
default:
check0Button =
<Row style={chk} >
<Col xs={10}>Previous Session Check</Col>
<Col xs={2}><Button bsStyle="info"><Glyphicon glyph="time" /></Button></Col>
</Row>;
break;
}
switch (this.props.GenR.chk1) {
case CHK.SUCCESS:
check1Button =
<Row style={chk} >
<Col xs={10}>Receiver Limit Check</Col>
<Col xs={2}><Button bsStyle="success"><Glyphicon glyph="ok" /></Button></Col>
</Row>
break;
case CHK.FAILURE:
check1Button =
<Row style={chk} >
<Col xs={10}>Receiver Limit Check</Col>
<Col xs={2}><Button bsStyle="danger"><Glyphicon glyph="remove" /></Button></Col>
</Row>;
break;
default:
check1Button =
<Row style={chk} >
<Col xs={10}>Receiver Limit Check</Col>
<Col xs={2}><Button bsStyle="info"><Glyphicon glyph="time" /></Button></Col>
</Row>;
break;
}
switch (this.props.GenR.chk2) {
case CHK.SUCCESS:
check2Button =
<Row style={chk} >
<Col xs={10}>Preparing Receivers</Col>
<Col xs={2}><Button bsStyle="success"><Glyphicon glyph="ok" /></Button></Col>
</Row>
break;
case CHK.FAILURE:
check2Button =
<Row style={chk} >
<Col xs={10}>Preparing Receivers</Col>
<Col xs={2}><Button bsStyle="danger"><Glyphicon glyph="remove" /></Button></Col>
</Row>;
break;
default:
check2Button =
<Row style={chk} >
<Col xs={10}>Preparing Receivers</Col>
<Col xs={2}><Button bsStyle="info"><Glyphicon glyph="time" /></Button></Col>
</Row>;
break;
}
switch (this.props.GenR.chk3) {
case CHK.SUCCESS:
check3Button =
<Row style={chk} >
<Col xs={10}>Update Made2Manage</Col>
<Col xs={2}><Button bsStyle="success"><Glyphicon glyph="ok" /></Button></Col>
</Row>
break;
case CHK.FAILURE:
check3Button =
<Row style={chk} >
<Col xs={10}>Update Made2Manage</Col>
<Col xs={2}><Button bsStyle="danger"><Glyphicon glyph="remove" /></Button></Col>
</Row>;
break;
default:
check3Button =
<Row style={chk} >
<Col xs={10}>Update Made2Manage</Col>
<Col xs={2}><Button bsStyle="info"><Glyphicon glyph="time" /></Button></Col>
</Row>;
break;
}
const jbk ={backgroundColor: 'black' };
return (
<div>
<Row >
<Col xs={11}>
{check0Button}
</Col>
</Row>
<Row >
<Col xs={11}>
{check1Button}
</Col>
</Row>
<Row >
<Col xs={11}>
{check2Button}
</Col>
</Row>
<Row >
<Col xs={11}>
{check3Button}
</Col>
</Row>
</div>
);
}
}
|
/**
* @copyright Maichong Software Ltd. 2016 http://maichong.it
* @date 2016-02-22
* @author Liang <liang@maichong.it>
*/
'use strict';
const alaska = require('alaska');
const numeral = require('numeral');
class NumberField extends alaska.Field {
init() {
let field = this;
this.underscoreMethod('format', function (format) {
if (format) {
return numeral(this.get(field.path)).format(format);
}
return this.get(field.path);
});
}
createFilter(filter) {
let value;
if (typeof filter === 'object') {
value = filter.value;
} else if (typeof filter === 'number' || typeof filter === 'string') {
value = filter;
}
if (value !== undefined) {
value = parseFloat(value);
return isNaN(value) ? undefined : value;
}
//区间
let bt;
if (filter instanceof Array) {
bt = filter;
} else if (filter.$bt && filter.$bt instanceof Array) {
bt = filter.$bt;
} else if (filter.bt && filter.bt instanceof Array) {
bt = filter.bt;
}
if (bt && bt.length === 2) {
let start = parseFloat(bt[0]);
let end = parseFloat(bt[1]);
if (isNaN(start) || isNaN(end)) return;
return { $gte: start, $lte: end };
}
//比较
['gt', 'gte', 'lt', 'lte'].forEach((key) => {
let val = filter[key] || filter['$' + key];
if (val === undefined) return;
val = parseFloat(val);
if (isNaN(val)) return;
if (!value) {
value = {};
}
value['$' + key] = val;
});
if (value) {
return value;
}
}
}
NumberField.views = {
cell: {
name: 'NumberFieldCell',
path: __dirname + '/lib/cell.js'
},
view: {
name: 'NumberFieldView',
path: __dirname + '/lib/view.js'
},
filter: {
name: 'NumberFieldFilter',
path: __dirname + '/lib/filter.js'
}
};
NumberField.plain = Number;
NumberField.options = ['min', 'max'];
NumberField.viewOptions = ['min', 'max', 'format', 'addonBefore', 'addonAfter', 'placeholder'];
module.exports = NumberField;
|
module.exports = {
options: {
host: '127.0.0.1'
},
test: {
port: 8765,
runInBackground: true
},
demo: {
port: 8000
}
};
|
var $ = require('jquery')
$("#plastic-injection").click(function() {
window.location='/plastics'
})
$("#laser-cutting").click(function() {
window.location='/laser'
})
$("#prototype").click(function() {
window.location='/prototype'
})
$("#3d-printing").click(function() {
window.location='/3Dprint'
})
$("#packaging").click(function() {
window.location='/packaging'
})
$("#design-services").click(function() {
window.location='/design'
})
$("#electronics").click(function() {
window.location='/electronics'
})
$("#clear-filters").click(function() {
window.location='/'
})
|
$(document).ready(function(){
$("#marge-link").css("top", "-50px");
$("#marge").hover(function(){
//console.log("Hovered");
$("#marge-link").animate({
top: '0px'})
}, function(){
//console.log("Not Hovered");
$("#marge-link").animate({
top: '-50px'})
});
$("#sanz-link").css("top", "-50px");
$("#sanz").hover(function(){
$("#sanz-link").animate({
top: '0px'})
}, function(){
$("#sanz-link").animate({
top: '-50px'})
});
});
|
/**
* BSA.Dialogs - Object dialog functions
*
* This object allows:
* - output ProgressBar
* - output messages
*
* JavaScript
*
* @author Sergii Beskorovainyi <bsa2657@yandex.ru>
* @license MIT <http://www.opensource.org/licenses/mit-license.php>
* @link https://github.com/bsa-git/zf-myblog/
*/
BSA.Dialogs = {
timeout: 0, // The time period of data update
intervalID: null,
createOverlay: function(){
if(! $('overlay-modal')){
var overlay = '<div id="overlay-modal" class="overlay-dialog" style="position: absolute; top: 0px; left: 0px; z-index: 100; width: 100%; opacity: 0.6000000238418579; height: 6297px; "></div>';
var body = $$('body')[0];
body.insert({
top: overlay
});
}
},
createIFrame: function(params){
var body = $$('body')[0];
//var iFrame = $$('iframe')[0];
var iFrame = $('zend-progress-iframe');
//---------------------------
if(! iFrame){
// Создадим элемент 'iframe' для управления клиентом
// со стороны сервера и вставим его в страницу
if(params.type == 'ZendProgress'){
iFrame = new Element('iframe', {id: 'zend-progress-iframe', src: lb.getMsg('urlBase') + params.iframe_src});
body.insert({
top: iFrame
});
}
}
},
createDialogContainer: function(params){
var dialog_container = '';
var dialogWidth = 0;
var dialogHeight = 0;
var body = $$('body')[0];
//---------------------------
if(! $('modal-dialog-message')){
// Создадим контейнер диалога и вставим его в страницу
if(params.width && params.height){
// Создадим шаблон
dialog_container = '<div id="modal-dialog-message" class="dialog-content" style="width:#{width}px;height:#{height}px"></div>';
var template = new Template(dialog_container);
var show = {
width: params.width,
height: params.height
};
// Получим шаблон с данными
dialog_container = template.evaluate(show);
}else{
dialog_container = '<div id="modal-dialog-message" class="dialog-content"></div>';
}
// Вставим элемент в страницу
body.insert({
top: dialog_container
});
// Получим размер документа
var dimensions = document.viewport.getDimensions();//{ width: 776, height: 580 }
// Установим диалог на середине окна
var dialog = $('modal-dialog-message');
if(params.width && params.height){
dialogWidth = params.width;
dialogHeight = params.height;
}else{
var layout = new Element.Layout(dialog);
dialogWidth = layout.get('width');
dialogHeight = layout.get('height');
}
var dialogLeft = Math.floor((dimensions.width - dialogWidth)/2);
var dialogTop = Math.floor((dimensions.height - dialogHeight)/2);
dialog.setStyle({
left: dialogLeft + 'px',
top: dialogTop + 'px'
});
}
},
openDialogInfo : function(params)
{
var self = this;
//-------------------------
// Установим таймаут
self.timeout = 0;
// Создадим диалог и оверлей
this.createDialogContainer(params);
this.createOverlay();
// Получим содержимое для диалога
var template = this.getTemplateFor_DialogInfo(params);
var showData = this.getDataTemplateFor_DialogInfo(params);
var content = template.evaluate(showData);
// Установим содержание диалога
this.setInfoMessage(content);
// Создадим элемент - 'iFrame'
if(params.type == 'ZendProgress'){
this.createIFrame(params);
return;
}
// Определим переодическую функцию для обновления данных
this.intervalID = window.setInterval(function() {
self.timeout++;
// Получим содержимое для диалога
showData = self.getDataTemplateFor_DialogInfo(params);
content = template.evaluate(showData);
// Обновим содержание диалога
self.setInfoMessage(content);
}.bind(self), 1000);
},
setInfoMessage: function(message) {
if($('modal-dialog-message')){
$('modal-dialog-message').update(message);
}
},
closeDialogInfo : function(event)
{
if($('overlay-modal')){
$('overlay-modal').remove();
}
if($('modal-dialog-message')){
$('modal-dialog-message').remove();
}
if($('zend-progress-iframe')){
$('zend-progress-iframe').remove();
}
if(this.intervalID){
clearInterval(this.intervalID);
}
},
getTemplateFor_DialogInfo : function(params)
{
var msg = '';
var strTemplate = '';
var strMsg = '';
var strProgress = '';
var strCancel = '';
//-------------------------
switch(params.type) {
case 'ZendProgress': // Диалог ожидания окончания операции сервера c помощью Zend_Progress
case 'WaiteServerAction': // Диалог ожидания окончания операции сервера
// Созадание шаблона
strMsg = '<h3>#{msg}</h3>';
// Создадим шаблон сообщения в DialogInfo
// Особенность! Если эксплоер = Хром, то картинки не вызываются
// поэтому делаем анализ и уходим от изображений...
strProgress = '<div id="progress-bar">' +
'<div class="pg-progressbar">' +
'<div class="pg-progress" id="pg-percent" style="width: #{width}%">' +
'<div class="pg-progressstyle" '+ (Prototype.Browser.WebKit? 'style="background: #0782C1"':'') + ' ></div>' +
'<div class="pg-invertedtext" id="pg-text-1">#{text1}</div>' +
'</div>' +
'<div class="pg-text" id="pg-text-2">#{text2}</div>' +
'</div>' +
'</div>' +
'<div id="progressBar"><div id="progressDone"></div></div>';
if(params.cancel){
strCancel = '<br /><br /><br />'+
'<div id="cancel-dialog-info">'+
'<a href="#{url_cancel}">'+
(Prototype.Browser.WebKit? '#{cancel}':'<img src="#{url_image}" alt title="#{cancel}" />') +
'</a>'+
'</div>';
}
strTemplate = strMsg + strProgress + strCancel;
break;
default: // Если все остальное не подходит...
break; // Здесь останавливаемся
}
return new Template(strTemplate);
},
getDataTemplateFor_DialogInfo : function(params)
{
var msg = '';
var min = 0;
var sec = 0;
var timeProgress = '';
var show = null;
//-----------------
switch(params.type) {
case 'ZendProgress': // Диалог ожидания окончания операции сервера c помощью Zend_Progress
case 'WaiteServerAction': // Диалог ожидания окончания операции сервера
// Определим сообщение
if(params.msg){
msg = params.msg;
}else{
msg = lb.getMsg('msgIsPreparingReport');
}
// Создадим обьект с данными
show = {
msg: msg,
url_cancel: lb.getMsg('urlRes') + params.url_cancel,
url_image: lb.getMsg('urlRes') + '/images/system/stop-error.png',
cancel: lb.getMsg('msgCancel'),
width: this.timeout,
text1: '',
text2: ''
};
// Установим данные
if(this.timeout > 0){
if(this.timeout >= 60){
min = Math.floor(this.timeout/60);
sec = this.timeout%60;
if(sec == 0){
timeProgress = min + ' ' + lb.getMsg('msgMinutes') + ' ';
}else{
timeProgress = min + ' ' + lb.getMsg('msgMinutes') + ' ' + sec + ' ' + lb.getMsg('msgSeconds') + ' ';
}
}else{
timeProgress = this.timeout + ' сек.';
}
// Обновим время в обьекте данных
show.width = ((this.timeout % 10)+1)*10;
show.text1 = timeProgress;
show.text2 = timeProgress;
}
break;
default:
break;
}
return show;
},
Zend_ProgressBar_Update: function(data){
document.getElementById('pg-percent').style.width = data.percent + '%';
document.getElementById('pg-text-1').innerHTML = data.text;
document.getElementById('pg-text-2').innerHTML = data.text;
},
Zend_ProgressBar_Finish: function()
{
document.getElementById('pg-percent').style.width = '100%';
document.getElementById('pg-text-1').innerHTML = 'Demo done';
document.getElementById('pg-text-2').innerHTML = 'Demo done';
this.closeDialogInfo();
}
}
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M8 5h8v14H8z" opacity=".3" /><path d="M19 7h2v10h-2zm3 2h2v6h-2zM0 9h2v6H0zm16.5-6h-9C6.67 3 6 3.67 6 4.5v15c0 .83.67 1.5 1.5 1.5h9c.83 0 1.5-.67 1.5-1.5v-15c0-.83-.67-1.5-1.5-1.5zM16 19H8V5h8v14zM3 7h2v10H3z" /></React.Fragment>
, 'VibrationTwoTone');
|
(function() {
'use strict';
var controller = function($scope, $attrs, ramlParserWrapper) {
$scope.ramlConsole = this;
if ($attrs.hasOwnProperty('withRootDocumentation')) {
this.withRootDocumentation = true;
}
if ($scope.src) {
ramlParserWrapper.load($scope.src);
}
this.keychain = {};
};
controller.prototype.gotoView = function(view) {
this.view = view;
};
controller.prototype.tryItEnabled = function() {
return !!(this.api && this.api.baseUri);
};
controller.prototype.showRootDocumentation = function() {
return this.withRootDocumentation && this.api && this.api.documentation && this.api.documentation.length > 0;
};
RAML.Controllers.RAMLConsole = controller;
})();
|
var voices = new Array();
var synthContext = null;
var isMobile = false; // we have to disable the convolver on mobile for performance reasons.
function frequencyFromNoteNumber( note ) {
return 440 * Math.pow(2,(note-69)/12);
}
function noteOn( note, velocity ) {
//clog(' note on '+note+' '+velocity);
$('notenum').value = note;
$('noteval').value = velocity;
//light a controller LED:
light(note,'red');
}
function noteOff( note ) {
//clog('note off '+note);
$('notenum').value = note;
$('noteval').value = 0;
//light a controller LED:
light(note,'off');
}
function $(id) {
return document.getElementById(id);
}
// 'value' is normalized to 0..1.
function controller( number, value ) {
//clog('cc '+number+' '+value);
$('ccnum').value = number;
$('ccval').value = value;
//send back to controller to update LEDs
ring(number,value);
}
var currentPitchWheel = 0.0;
// 'value' is normalized to [-1,1]
function pitchWheel( value ) {
var i;
currentPitchWheel = value;
clog('pitchwheel '+value);
}
//highest note in default settings for each controller:
var maxnote = {'Base':67,'Alias8':15,'CNTRLR':59,'OhmRGB':87,'Ohm64':64};
function lights_rnd(){
var colors = ['r','g','b','c','m','y','k']; //translation is in var color in midi.js
var max = maxnote[product]; //'product' is determined in midi.js when port is selected
for(var i=0;i<=max;i++){
var randi = Math.floor(Math.random()*7);
var choice = colors[randi];
light(i,choice);
}
}
function lights_off(){
var max = maxnote[product]; //'product' is determined in midi.js when port is selected
for(var i=0;i<=max;i++){
light(i,'off');
}
}
//This is merely a placeholder, since this 'synth' doesn't actually produce sound. But it's good groundwork!
function initAudio() {
window.AudioContext = window.AudioContext || window.webkitAudioContext;
try {
synthContext = new AudioContext();
}
catch(e) {
alert('The Web Audio API is apparently not supported in this browser.');
}
//window.addEventListener('keydown', keyDown, false);
//window.addEventListener('keyup', keyUp, false);
//setupSynthUI();
isMobile = (navigator.userAgent.indexOf('Android')!=-1)||(navigator.userAgent.indexOf('iPad')!=-1)||(navigator.userAgent.indexOf('iPhone')!=-1);
}
window.onload=initAudio;
|
'use strict';
const request = require('request');
const EventEmitter = require('events').EventEmitter;
class AuthService extends EventEmitter {
constructor(appId, appSecret, options) {
super();
this._appId = appId;
this._appSecret = appSecret;
options = options || {};
this._token = null;
this._validUntil = new Date(0);
this._renewingToken = false;
this._renewBeforeExpiration = options.renewBeforeExpiration || 600;
this._scope = options.scope || 'https://graph.microsoft.com/.default';
this._oAuthUrl = options.oauthUrl || 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
}
getToken(callback) {
if (new Date() < this._validUntil) {
return callback(null, this._token);
} else {
if (this._renewingToken) {
this.once('token', callback);
} else {
this._renewingToken = true;
this._renewToken((err, data) => {
this._setNewToken(err, data, callback);
});
}
}
}
_renewToken(callback) {
const content = {
client_id: this._appId,
client_secret: this._appSecret,
grant_type: 'client_credentials',
scope: this._scope
};
request.post(this._oAuthUrl, {
form: content
}, (err, response, body) => {
if (err) {
return callback(err);
}
if (response.statusCode !== 200) {
return callback(new Error(`Received error ${response.statusCode}: ${response.statusMessage}.`));
}
callback(null, body);
});
}
_setNewToken(err, data, callback) {
this._renewingToken = false;
if (err) {
this.emit('token', err);
return callback(err);
}
const response = JSON.parse(data);
this._token = response.access_token;
const now = new Date();
this._validUntil = new Date(now.getTime() + (response.expires_in - this._renewBeforeExpiration) * 1000);
this.emit('token', null, this._token);
callback(null, this._token);
}
}
module.exports = AuthService; |
Type.registerNamespace("SitefinityWebApp.WidgetDesigners.Display");
SitefinityWebApp.WidgetDesigners.Display.DisplayDesigner = function (element) {
/* Initialize Message fields */
this._message = null;
/* Calls the base constructor */
SitefinityWebApp.WidgetDesigners.Display.DisplayDesigner.initializeBase(this, [element]);
}
SitefinityWebApp.WidgetDesigners.Display.DisplayDesigner.prototype = {
/* --------------------------------- set up and tear down --------------------------------- */
initialize: function () {
/* Here you can attach to events or do other initialization */
SitefinityWebApp.WidgetDesigners.Display.DisplayDesigner.callBaseMethod(this, 'initialize');
},
dispose: function () {
/* this is the place to unbind/dispose the event handlers created in the initialize method */
SitefinityWebApp.WidgetDesigners.Display.DisplayDesigner.callBaseMethod(this, 'dispose');
},
/* --------------------------------- public methods ---------------------------------- */
findElement: function (id) {
var result = jQuery(this.get_element()).find("#" + id).get(0);
return result;
},
/* Called when the designer window gets opened and here is place to "bind" your designer to the control properties */
refreshUI: function () {
var controlData = this._propertyEditor.get_control().Settings; /* JavaScript clone of your control - all the control properties will be properties of the controlData too */
/* RefreshUI Message */
jQuery(this.get_message()).val(controlData.Message);
},
/* Called when the "Save" button is clicked. Here you can transfer the settings from the designer to the control */
applyChanges: function () {
var controlData = this._propertyEditor.get_control().Settings;
/* ApplyChanges Message */
controlData.Message = jQuery(this.get_message()).val();
},
/* --------------------------------- event handlers ---------------------------------- */
/* --------------------------------- private methods --------------------------------- */
/* --------------------------------- properties -------------------------------------- */
/* Message properties */
get_message: function () { return this._message; },
set_message: function (value) { this._message = value; }
}
SitefinityWebApp.WidgetDesigners.Display.DisplayDesigner.registerClass('SitefinityWebApp.WidgetDesigners.Display.DisplayDesigner', Telerik.Sitefinity.Web.UI.ControlDesign.ControlDesignerBase);
|
const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow
require('electron-context-menu')({
prepend: (params, browserWindow) => [{
label: 'Rainbow',
// only show it when right-clicking images
visible: params.mediaType === 'image'
}],
showInspectElement: true
});
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({ width: 900, height: 600 })
// and load the index.html of the app.
mainWindow.loadURL(`file://${__dirname}/app/index.html`)
// Open the DevTools.
//mainWindow.webContents.openDevTools()
// Emitted when the window is closed.
mainWindow.on('closed', function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null
})
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow()
}
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
|
const types = {
'SHOW_TOP_BAR': 'SHOW_TOP_BAR',
'HIDE_TOP_BAR': 'HIDE_TOP_BAR',
'SHOW_FOOT_BAR': 'SHOW_FOOT_BAR',
'HIDE_FOOT_BAR': 'HIDE_FOOT_BAR'
}
const state = {
showTop: true,
showFoot: true
}
const mutations = {
[types.SHOW_FOOT_BAR] ({showTop}) {
state.showTop = true
},
[types.HIDE_TOP_BAR] ({showTop}) {
state.showTop = false
},
[types.SHOW_FOOT_BAR] ({showFoot}) {
state.showFoot = true
},
[types.HIDE_FOOT_BAR] ({showFoot}) {
state.showFoot = false
}
}
const actions = {
showTop ({commit}) {
commit(types.SHOW_TOP_BAR)
},
hideTop ({commit}) {
commit(types.HIDE_TOP_BAR)
},
showFoot ({commit}) {
commit(types.SHOW_FOOT_BAR)
},
hideFoot ({commit}) {
commit(types.HIDE_FOOT_BAR)
}
}
const getters = {}
export default {
state,
mutations,
actions,
getters
}
|
/**
* Created by Strawmanbobi
* 2016-12-05
*/
var app = require('../irext_console.js');
var navigationService = require('../services/navigation_service.js');
app.post('/irext/nav/nav_to_url', navigationService.navToURL); |
import React from 'react';
import {Container, Row, Col, Card} from '../../src/Grid';
import styles from './ExampleGrid.scss';
export default () =>
<div data-hook="card-example" className={styles.exampleContainer}>
<Container>
<Row>
<Card>
<Card.Header title="Grid Row - RTL support">
Row RTL support
</Card.Header>
<Card.Content>
<Row rtl>
<Col span={4}>
אחת
</Col>
<Col span={4}>
שתיים
</Col>
<Col span={4}>
שלוש
</Col>
</Row>
</Card.Content>
</Card>
</Row>
</Container>
</div>;
|
/* eslint no-bitwise: 0 */
/**
* Volume of Interest Lookup Table Function
*
* @typedef {Function} VOILUTFunction
*
* @param {Number} modalityLutValue
* @returns {Number} transformed value
*/
/**
*
* @param {Number} windowWidth Window Width
* @param {Number} windowCenter Window Center
* @returns {VOILUTFunction} VOI LUT mapping function
*/
function generateLinearVOILUT (windowWidth, windowCenter) {
return function (modalityLutValue) {
return ((modalityLutValue - windowCenter) / windowWidth + 0.5) * 255.0;
};
}
/**
* Generate a non-linear volume of interest lookup table
*
* @param {LUT} voiLUT Volume of Interest Lookup Table Object
*
* @returns {VOILUTFunction} VOI LUT mapping function
*/
function generateNonLinearVOILUT (voiLUT) {
// We don't trust the voiLUT.numBitsPerEntry, mainly thanks to Agfa!
const bitsPerEntry = Math.max(...voiLUT.lut).toString(2).length;
const shift = bitsPerEntry - 8;
const minValue = voiLUT.lut[0] >> shift;
const maxValue = voiLUT.lut[voiLUT.lut.length - 1] >> shift;
const maxValueMapped = voiLUT.firstValueMapped + voiLUT.lut.length - 1;
return function (modalityLutValue) {
if (modalityLutValue < voiLUT.firstValueMapped) {
return minValue;
} else if (modalityLutValue >= maxValueMapped) {
return maxValue;
}
return voiLUT.lut[modalityLutValue - voiLUT.firstValueMapped] >> shift;
};
}
/**
* Retrieve a VOI LUT mapping function given the current windowing settings
* and the VOI LUT for the image
*
* @param {Number} windowWidth Window Width
* @param {Number} windowCenter Window Center
* @param {LUT} [voiLUT] Volume of Interest Lookup Table Object
*
* @return {VOILUTFunction} VOI LUT mapping function
*/
export default function (windowWidth, windowCenter, voiLUT) {
if (voiLUT) {
return generateNonLinearVOILUT(voiLUT);
}
return generateLinearVOILUT(windowWidth, windowCenter);
}
|
require('./harness');
var recvCount = 0;
var body = "hello world";
connection.addListener('ready', function () {
puts("connected to " + connection.serverProperties.product);
//var e = connection.exchange('node-ack-fanout', {type: 'fanout'});
var e = connection.exchange();
var q = connection.queue('node-123ack-queue');
q.bind(e, 'ackmessage.*');
q.subscribe({ ack: true }, function (json) {
recvCount++;
puts('Got message ' + JSON.stringify(json));
if (recvCount == 1) {
puts('Got message 1.. waiting');
assert.equal('A', json.name);
setTimeout(function () {
puts('shift!');
q.shift();
}, 1000);
} else if (recvCount == 2) {
puts('got message 2');
assert.equal('B', json.name);
puts('closing connection');
connection.end();
} else {
throw new Error('Too many message!');
}
})
.addCallback(function () {
puts("publishing 2 json messages");
e.publish('ackmessage.json1', { name: 'A' });
e.publish('ackmessage.json2', { name: 'B' });
});
});
process.addListener('exit', function () {
assert.equal(2, recvCount);
});
|
var assert = require('assert');
var Readable = require('stream').Readable;
var u = require('util');
var express = require('express');
var router = express.Router();
var jsdom = require('jsdom');
var debug = require('debug')('scraper');
u.inherits(Scraper, Readable);
function Scraper(opts, doc, sel, pgSel, endWhen) {
Readable.call(this, opts);
try {
this._doc = doc;
this._sel = sel;
this._paginationNode = doc.querySelector(pgSel);
this._endWhen = endWhen;
this._clickEvent = doc.createEvent('MouseEvents');
this._clickEvent.initEvent('click', true, true);
debug('Pagination el: %s', this._paginationNode.outerHTML);
}
catch (e) {
this._error = true;
this._errorMsg = e.message;
}
}
Scraper.prototype._read = function() {
var iterable;
if (this._error) {
this.push(this._errorMsg);
this.push(null);
}
iterable = this._doc.querySelectorAll(this._sel);
if (iterable.length) {
debug('pushing html');
this.push(htmlpl0x(iterable));
assert(this._doc.querySelectorAll(this._sel).length === 0, 'iterable still contains elements');
this._paginationNode.dispatchEvent(this._clickEvent);
}
if (isPaginationDone(this._doc, this._endWhen)) {
iterable = this._doc.querySelectorAll(this._sel);
this.push(htmlpl0x(iterable));
this.push(null);
}
};
function isPaginationDone(doc, endWhen) {
var key = Object.keys(endWhen.condition)[0];
var val = endWhen.condition[key];
var el = doc.querySelector(endWhen.selector);
var doneFlag = false;
debug('End selector: %s', endWhen.selector);
debug('End condition type: %s', endWhen.type);
debug('End condition key: %s', key);
debug('End condition expected value: %s', val);
switch (endWhen.type) {
case 'css':
debug('End condition current value: %s', el.style[key]);
doneFlag = el.style[key] === val;
break;
case 'text':
debug('End condition current value: %s', el.textContent.trim());
doneFlag = el.textContent.trim() === val;
break;
}
debug('End condition met? ', doneFlag);
return doneFlag;
}
function htmlpl0x(iterable) {
var store = [];
assert(iterable.length > 0, 'Empty iterable coming into htmlpl0x');
for (var i = 0; i < iterable.length; i++) {
var el = iterable[i];
debug('currentHTML: %s', el.outerHTML);
store.push(el.outerHTML);
el.parentNode.removeChild(el);
}
debug('store: ', store);
return JSON.stringify(store);
}
/* Did someone say, HTML?! */
router.post('/', function(req, res, next) {
var url = decodeURI(req.param('url'));
var selector = decodeURIComponent(req.param('selector'));
var paginationSelector = decodeURIComponent(req.param('pgSel'));
var paginationType = decodeURIComponent(req.param('pgType')); //ajax or href
var endWhen = JSON.parse(decodeURIComponent(req.param('endWhen')));
//---------------------------------
//endWhen structure:
// {
// selector: <jQuery like selector>,
// type: <'css' or 'text'>,
// endWhen: { key: val }
// }
//Example:
//{
// selector: 'span.d-s.L5.r0',
// type: 'css',
// condition: { display: 'none' }
// }
//---------------------------------
debug('url: %s', url);
debug('selector: %s', selector);
debug('paginationSelector: %s', paginationSelector);
debug('endWhen: %s', JSON.stringify(endWhen));
jsdom.env({
url: url,
features: {
FetchExternalResources: ['script'],
ProcessExternalResources: ['script'],
MutationEvents: '2.0'
},
done: function(err, window) {
if (err) next(err);
var doc = window.document;
new Scraper({
highWaterMark: 128 * 1024
}, doc, selector, paginationSelector, endWhen).pipe(res);
}
});
});
module.exports = router;
|
var searchData=
[
['state',['State',['../class_dao_net_1_1_dao_access.html#a097058769337d1e5557cad4b4a0a320b',1,'DaoNet::DaoAccess']]],
['statecode',['StateCode',['../class_dao_net_1_1_r_p_cresponse.html#af2073f6381ce9ba9cd3cc717a29a3b81',1,'DaoNet::RPCresponse']]]
];
|
import { hashHistory } from 'react-router';
export const redirectTo = path => hashHistory.push(path);
|
'use strict';
const Jii = require('../../index');
const Article = require('../models/Article');
const Pagination = require('../../data/Pagination');
const Collection = require('../../base/Collection');
const InvalidParamException = require('../../exceptions/InvalidParamException');
const ChangeEvent = require('../../data/ChangeEvent');
const Query = require('../../data/Query');
const UnitTest = require('../../base/UnitTest');
require('../bootstrap');
class DataProviderTest extends UnitTest {
fetchTest(test) {
var fetchCount = 0;
var collection = new Collection(null, {
modelClass: Article
});
test.strictEqual(collection.isFetched(), false);
var dataProvider = collection.createDataProvider({
query: pagination => {
fetchCount++;
return new Promise(resolve => {
resolve({
totalCount: 14,
models: this._generateData(pagination.getPage() * 10, pagination.getPage() === 0 ? 10 : 14)
});
});
},
pagination: {
pageSize: 10
}
});
test.strictEqual(collection.isFetched(), false);
test.strictEqual(dataProvider.isFetched(), false);
test.strictEqual(fetchCount, 0);
dataProvider.fetch().then(() => {
test.strictEqual(collection.isFetched(), true);
test.strictEqual(dataProvider.isFetched(), true);
test.strictEqual(fetchCount, 1);
test.strictEqual(collection.length, 10);
test.strictEqual(dataProvider.length, 10);
// Fetch new page
dataProvider.getPagination().setPage(1);
return dataProvider.fetch();
}).then(() => {
test.strictEqual(collection.length, 14);
test.strictEqual(dataProvider.length, 4);
test.strictEqual(fetchCount, 2);
// Check no fetch previous page
dataProvider.getPagination().setPage(0);
return dataProvider.fetch();
}).then(() => {
test.strictEqual(dataProvider.length, 10);
test.strictEqual(fetchCount, 2);
// Check no fetch end page (where length < pageSize)
dataProvider.getPagination().setPage(1);
return dataProvider.fetch();
}).then(() => {
test.strictEqual(dataProvider.length, 4);
test.strictEqual(fetchCount, 2);
// Remove from parent and fetch
collection.remove({
id: 'id5'
});
test.strictEqual(dataProvider.length, 4);
dataProvider.getPagination().setPage(0);
return dataProvider.fetch();
}).then(() => {
test.strictEqual(dataProvider.length, 10);
test.strictEqual(fetchCount, 3);
// Update page size
dataProvider.getPagination().setPageSize(5);
test.strictEqual(dataProvider.getPagination().getPageCount(), 3);
test.strictEqual(dataProvider.length, 5);
// Set page 2, check no fetch
dataProvider.getPagination().setPage(2);
return dataProvider.fetch();
}).then(() => {
test.strictEqual(dataProvider.length, 4);
test.strictEqual(fetchCount, 3);
dataProvider.getPagination().mode = Pagination.MODE_LOAD_MORE;
dataProvider.refreshFilter();
test.strictEqual(dataProvider.length, 14);
dataProvider.getPagination().setPage(0);
test.strictEqual(dataProvider.length, 5);
test.done();
});
}
_generateData(from, to) {
var data = [];
for (var i = from; i < to; i++) {
data.push({
id: 'id' + i,
title: 'test' + i
});
}
return data;
}
}
module.exports = new DataProviderTest().exports(); |
// Thunk convertion
// ES5
function Thunk(fn) {
return function() {
var args = Array.prototype.slice.apply(arguments);
return function(callback) {
args.push(callback);
return fn.apply(this, args);
};
};
}
function f(num, callback) {
callback(num);
}
let log = console.log;
let ft = Thunk(f);
ft(2)(log); |
import PostAdapter from 'ember-tumblr/adapters/tumblr-post';
export default PostAdapter.extend({
blogUrl: 'jordanhawker.tumblr.com',
apiKey: 'djHwrb13Yd636cWzgzjRms29YwoB3fmHp0VXG4mB9GEAxcB6MX'
});
|
'use strict';
// Define the `topBar` module
angular.module('topBar', []); |
//BUG: unselect needs to be triggered when events are dragged+dropped
function SelectionManager() {
var t = this;
// exports
t.select = select;
t.unselect = unselect;
t.reportSelection = reportSelection;
t.daySelectionMousedown = daySelectionMousedown;
// imports
var opt = t.opt;
var trigger = t.trigger;
var defaultSelectionEnd = t.defaultSelectionEnd;
var renderSelection = t.renderSelection;
var clearSelection = t.clearSelection;
// locals
var selected = false;
// unselectAuto
if (opt('selectable') && opt('unselectAuto')) {
$(document).mousedown(function(ev) {
var ignore = opt('unselectCancel');
if (ignore) {
if ($(ev.target).parents(ignore).length) { // could be optimized to stop after first match
return;
}
}
unselect(ev);
});
}
function select(startDate, endDate, allDay) {
unselect();
if (!endDate) {
endDate = defaultSelectionEnd(startDate, allDay);
}
renderSelection(startDate, endDate, allDay);
reportSelection(startDate, endDate, allDay);
}
function unselect(ev) {
if (selected) {
selected = false;
clearSelection();
trigger('unselect', null, ev);
}
}
function reportSelection(startDate, endDate, allDay, ev, resource) {
selected = true;
trigger('select', null, startDate, endDate, allDay, ev, resource);
}
function daySelectionMousedown(ev) { // not really a generic manager method, oh well
var cellToDate = t.cellToDate;
var getIsCellAllDay = t.getIsCellAllDay;
var hoverListener = t.getHoverListener();
var reportDayClick = t.reportDayClick; // this is hacky and sort of weird
if (ev.which == 1 && opt('selectable')) { // which==1 means left mouse button
unselect(ev);
var _mousedownElement = this;
var dates;
hoverListener.start(function(cell, origCell) { // TODO: maybe put cellToDate/getIsCellAllDay info in cell
clearSelection();
if (cell && getIsCellAllDay(cell)) {
dates = [ cellToDate(origCell), cellToDate(cell) ].sort(dateCompare);
renderSelection(dates[0], dates[1], true);
}else{
dates = null;
}
}, ev);
$(document).one('mouseup', function(ev) {
hoverListener.stop();
if (dates) {
if (+dates[0] == +dates[1]) {
reportDayClick(dates[0], true, ev);
}
reportSelection(dates[0], dates[1], true, ev);
}
});
}
}
}
|
// npm install -g gulp
// npm install --save-dev gulp
// npm install --save-dev gulp-uglify
// npm install --save-dev gulp-concat
// npm install --save-dev gulp-rename
// npm install --save-dev gulp-clean
// npm install --save-dev gulp-typescript
// npm install --save-dev gulp-sourcemaps
// npm install --save-dev gulp-imagemin
//npm install --save-dev gulp-ruby-sass
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var imagemin = require('gulp-imagemin');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var clean = require('gulp-clean');
var sass = require('gulp-sass');
var tsFiles = 'app/**/*.ts';
var jsFiles = "dist/app";
var staticJSDestination = "dist/public/libs";
var imagesDestination = "dist/public/images";
var cssDestination = "dist/public/css";
const typescript = require('gulp-typescript');
const tscConfig = require('./tsconfig.json');
gulp.task('abc', ['copy']);
gulp.task('scripts', function () {
return gulp.src(jsFiles)
.pipe(concat('build.js'))
.pipe(gulp.dest('dist/lib'))
.pipe(rename('build.min.js'))
.pipe(uglify())
.pipe(gulp.dest('dist/lib'));
});
gulp.task('clean', function () {
gulp.src('dist', { read: false })
.pipe(clean());
});
gulp.task('copy', ['clean'], function () {
gulp.src(tsFiles)
.pipe(gulp.dest(jsFiles));
});
// TypeScript compile
gulp.task('compile',
['clean',
'assets',
//'libs'
], function () {
return gulp
.src('app/**/*.ts')
.pipe(typescript(tscConfig.compilerOptions))
.pipe(gulp.dest('dist/app'));
});
gulp.task('assets', function () {
return gulp.src(['app/**/*',
'node_modules/**/*',
'index.html',
'systemjs.config.js',
'systemjs-angular-loader.js',
'tsconfig.json',
'!app/**/*.ts',
'public/**/*'
],
{ base: './' })
.pipe(gulp.dest('dist'))
});
// copy dependencies
gulp.task('libs', function () {
return gulp.src([
'node_modules/core-js/client/shim.min.js',
'node_modules/zone.js/dist/zone.js',
'node_modules/reflect-metadata/Reflect.js',
'node_modules/systemjs/dist/system.src.js'
])
.pipe(gulp.dest('dist/lib'))
});
gulp.task('compress', function () {
return gulp.src('public/images/**.*')
.pipe(imagemin({
progressive: true
}))
.pipe(gulp.dest('public/images/'))
});
gulp.task('sass', function () {
return gulp.src('public/scss/**/*.scss')
.pipe(sass.sync().on('error', sass.logError))
.pipe(gulp.dest('public/css/'));
});
gulp.task('sass:watch', function () {
gulp.watch('public/scss/**/*.scss', ['sass']);
});
gulp.task('build', ['compile']);
gulp.task('default', ['build']);
|
/**
* Created by Florin Chelaru ( florin [dot] chelaru [at] gmail [dot] com )
* Date: 2/8/2016
* Time: 1:39 PM
*/
goog.require('ngb.d.MultiselectList');
goog.exportSymbol('ngb.d.MultiselectList', ngb.d.MultiselectList);
goog.exportProperty(ngb.d.MultiselectList.prototype, 'link', ngb.d.MultiselectList.prototype.link);
goog.exportProperty(ngb.d.MultiselectList.prototype, 'isSelected', ngb.d.MultiselectList.prototype.isSelected);
goog.exportProperty(ngb.d.MultiselectList.prototype, 'select', ngb.d.MultiselectList.prototype.select);
goog.exportProperty(ngb.d.MultiselectList.prototype, 'clearSelection', ngb.d.MultiselectList.prototype.clearSelection);
|
'use strict';
module.exports = {
db: 'mongodb://heroku_7w00n9dr:67g9498qm2c41qjo9egtl4qtoo@ds047571.mlab.com:47571/heroku_7w00n9dr',
debug: true,
logging: {
format: 'tiny'
},
// aggregate: 'whatever that is not false, because boolean false value turns aggregation off', //false
aggregate: false,
mongoose: {
debug: false
},
hostname: 'http://localhost:3000',
app: {
name: 'MEAN - A Modern Stack - Development'
},
strategies: {
local: {
enabled: true
},
landingPage: '/',
facebook: {
clientID: 'DEFAULT_APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/api/auth/facebook/callback',
enabled: false
},
twitter: {
clientID: 'DEFAULT_CONSUMER_KEY',
clientSecret: 'CONSUMER_SECRET',
callbackURL: 'http://localhost:3000/api/auth/twitter/callback',
enabled: false
},
github: {
clientID: 'DEFAULT_APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/api/auth/github/callback',
enabled: false
},
google: {
clientID: 'DEFAULT_APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/api/auth/google/callback',
enabled: false
},
linkedin: {
clientID: 'DEFAULT_API_KEY',
clientSecret: 'SECRET_KEY',
callbackURL: 'http://localhost:3000/api/auth/linkedin/callback',
enabled: false
}
},
emailFrom: 'SENDER EMAIL ADDRESS', // sender address like ABC <abc@example.com>
mailer: {
service: 'SERVICE_PROVIDER', // Gmail, SMTP
auth: {
user: 'EMAIL_ID',
pass: 'PASSWORD'
}
},
secret: 'SOME_TOKEN_SECRET'
};
|
export const USERS = '/api/users.json';
export const SESSION = '/api/session.json';
|
"use babel";
import {SwiftSourceKitGrammar} from "./grammar"
export default {
activate: () => {
console.log(new SwiftSourceKitGrammar(atom.grammars));
atom.grammars.addGrammar(new SwiftSourceKitGrammar(atom.grammars))
}
}
|
define(['./common_enhance',
'./tbtools',
'./item_ed_dialog',
'domReady!'], function (comnEnh,
tbtools,
itEdDlg,
document) {
return {
activate: function(partial_text_id) {
comnEnh.remClass('toolb_pan','toolb_pressed');
comnEnh.remClass('toolb_zoomin','toolb_pressed');
comnEnh.remClass('toolb_zoomout','toolb_pressed');
comnEnh.remClass('toolb_addvector','toolb_pressed');
comnEnh.remClass('toolb_addtext','toolb_pressed');
comnEnh.remClass('toolb_addhtml','toolb_pressed');
comnEnh.remClass('toolb_addimage','toolb_pressed');
comnEnh.addClass('toolb_'+partial_text_id,'toolb_pressed');
},
prepare: function(canvas) {
comnEnh.registerEvent(
document.getElementById('toolb'),
'mousedown',
function(event){
tbtools.dragStart(event, 'toolb');
});
comnEnh.registerEvent(
document.getElementById('toolb_pan'),
'click',
function(event){
canvas.setMouseMode('pan');
});
comnEnh.registerEvent(
document.getElementById('toolb_zoomin'),
'click',
function(event){
canvas.setMouseMode('zoomin');
});
comnEnh.registerEvent(
document.getElementById('toolb_zoomout'),
'click',
function(event){
canvas.setMouseMode('zoomout');
});
comnEnh.registerEvent(
document.getElementById('toolb_addvector'),
'click',
function(event){
canvas.setMouseMode('addvector');
comnEnh.remClass('itemeditor','hidden');
itEdDlg.activateTab('vector');
});
comnEnh.registerEvent(
document.getElementById('toolb_addtext'),
'click',
function(event){
canvas.setMouseMode('addtext');
comnEnh.remClass('itemeditor','hidden');
itEdDlg.activateTab('text');
});
comnEnh.registerEvent(
document.getElementById('toolb_addhtml'),
'click',
function(event){
canvas.setMouseMode('addhtml');
comnEnh.remClass('itemeditor','hidden');
itEdDlg.activateTab('html');
});
comnEnh.registerEvent(
document.getElementById('toolb_addimage'),
'click',
function(event){
canvas.setMouseMode('addimage');
comnEnh.remClass('itemeditor','hidden');
itEdDlg.activateTab('image');
});
}
};
});
|
"use strict";
const expect = require('chai').expect;
const hoodiecrow = require("hoodiecrow-imap");
const DEBUG_HOODIECROW = false;
const MESSAGES = [{
raw: "Subject: hello 1\r\n\r\nWorld 1!",
internaldate: "14-Sep-2013 21:22:28 -0300"
}, {
raw: "Subject: hello 2\r\n\r\nWorld 2!",
flags: ["\\Seen"],
internaldate: "15-Sep-2013 21:22:28 -0300"
}, {
raw: "Subject: hello 3\r\n\r\nWorld 3!"
}, {
raw: "From: sender name <sender@example.com>\r\n" +
"To: Receiver name <receiver@example.com>\r\n" +
"Subject: hello 4\r\n" +
"Message-Id: <abcde>\r\n" +
"Date: Fri, 13 Sep 2013 15:01:00 +0300\r\n" +
"\r\n" +
"World 4!"
}, {
raw: "Subject: hello 5\r\n\r\nWorld 5!"
}, {
raw: "Subject: hello 6\r\n\r\nWorld 6!"
}];
const server = hoodiecrow({
plugins: ["ID", "STARTTLS" /*, "LOGINDISABLED"*/ , "SASL-IR", "AUTH-PLAIN", "NAMESPACE", "IDLE", "ENABLE", "CONDSTORE", "XTOYBIRD", "LITERALPLUS", "UNSELECT", "SPECIAL-USE", "CREATE-SPECIAL-USE"],
id: {
name: "hoodiecrow",
version: "0.1"
},
systemFlags: ['\\Foo', '\\Bar', '\\Baz', '\\Deleted', '\\Seen'],
storage: {
"INBOX": {
messages: MESSAGES,
},
"": {
"separator": "/",
"folders": {
"[Gmail]": {
"flags": ["\\Noselect"],
"folders": {
"Drafts": {
"special-use": "\\Drafts"
},
}
}
}
}
},
debug: DEBUG_HOODIECROW,
});
const PORT = 3333;
const USER = 'testuser';
const PASS = 'testpass';
const imap = require('../integrations/manual/imap').create({
host: 'localhost',
port: PORT,
user: USER,
password: PASS,
tls: false,
});
describe("IMAP", () => {
before(done => {
server.listen(PORT, function() {
done();
});
});
after(() => {
server.close();
})
it('should list boxes', () => {
return imap.getBoxes().then(boxes => {
expect(boxes).to.deep.equal([{
id: 'INBOX',
delimiter: '/',
attributes: ['\\HasNoChildren'],
}, {
id: '[Gmail]',
delimiter: '/',
attributes: ['\\Noselect', '\\HasChildren'],
children: [{
id: 'Drafts',
delimiter: '/',
attributes: ['\\HasNoChildren', '\\Drafts'],
}]
}]);
})
});
it('should fetch messages', () => {
const expected = [{
body: MESSAGES[0].raw,
attributes: {
date: '2013-09-15T00:22:28.000Z',
flags: [],
uid: 1,
modseq: '1'
}
}, {
body: MESSAGES[1].raw,
attributes: {
date: '2013-09-16T00:22:28.000Z',
flags: ['\\Seen'],
uid: 2,
modseq: '2'
}
}]
return imap.fetch({messages: '1:2', isSequence: true})
.then(messages => {
expect(messages).to.deep.equal(expected);
})
.then(_ => imap.fetch({messages: ['1', '2'], isSequence: true}))
.then(messages => {
expect(messages).to.deep.equal(expected);
})
});
it('should search messages', () => {
return imap.search({query: {flags: ['SEEN']}})
.then(messages => {
expect(messages.length).to.equal(1);
expect(messages[0].body).to.equal(MESSAGES[1].raw);
expect(messages[0].attributes).to.deep.equal({
date: '2013-09-16T00:22:28.000Z',
flags: ['\\Seen'],
uid: 2,
modseq: '2'
});
})
});
it('should append message', () => {
let formattedMessage = null;
return imap.buildMessage({
from: 'me@me.com',
to: 'you@you.com',
subject: 'Subject',
body: 'hello!',
})
.then(message => {
formattedMessage = message;
return imap.append({message})
})
.then(result => expect(result).to.equal("Success"))
.then(_ => imap.fetch({messages: '7'}))
.then(messages => {
expect(messages.length).to.equal(1);
expect(messages[0].body).to.equal(formattedMessage);
})
})
it('should manipulate boxes', () => {
return Promise.resolve()
.then(_ => imap.addBox({box: 'Junk'}))
.then(_ => imap.getBoxes())
.then(boxes => {
expect(boxes.length).to.equal(3);
expect(boxes[2]).to.deep.equal({
id: 'Junk',
delimiter: '/',
attributes: ['\\HasNoChildren'],
})
})
.then(_ => imap.renameBox({oldName: 'Junk', newName: 'Junky'}))
.then(_ => imap.getBoxes())
.then(boxes => {
expect(boxes.length).to.equal(3);
expect(boxes[2]).to.deep.equal({
id: 'Junky',
delimiter: '/',
attributes: ['\\HasNoChildren'],
})
})
.then(_ => imap.deleteBox({box: 'Junky'}))
.then(_ => imap.getBoxes())
.then(boxes => {
expect(boxes.length).to.equal(2);
})
});
it('should manipulate subscriptions', () => {
return Promise.resolve()
.then(_ => imap.getSubscribedBoxes())
.then(boxes => {
expect(boxes.length).to.equal(2);
expect(boxes[0].id).to.equal('INBOX');
expect(boxes[1].id).to.equal('[Gmail]');
expect(boxes[1].children.length).to.equal(1);
expect(boxes[1].children[0].id).to.equal('Drafts');
})
.then(_ => imap.unsubscribe({box: '[Gmail]/Drafts'}))
.then(result => expect(result).to.equal("Success"))
.then(_ => imap.getSubscribedBoxes())
.then(boxes => {
expect(boxes.length).to.equal(2);
expect(boxes[1].children).to.equal(undefined);
})
.then(_ => imap.subscribe({box: '[Gmail]/Drafts'}))
.then(_ => imap.getSubscribedBoxes())
.then(boxes => {
expect(boxes.length).to.equal(2);
expect(boxes[0].id).to.equal('INBOX');
expect(boxes[1].id).to.equal('[Gmail]');
expect(boxes[1].children.length).to.equal(1);
expect(boxes[1].children[0].id).to.equal('Drafts');
})
})
it('should manipulate messages', () => {
return Promise.resolve()
.then(_ => imap.copy({messages: '1', destinationBox: '[Gmail]/Drafts'}))
.then(result => expect(result).to.equal("Success"))
.then(_ => imap.fetch({box: 'INBOX', messages: '1', isSequence: true}))
.then(messages => {
expect(messages.length).to.equal(1);
expect(messages[0].body).to.equal(MESSAGES[0].raw);
expect(messages[0].attributes.uid).to.equal(1);
})
.then(_ => imap.fetch({box: '[Gmail]/Drafts', messages: '1', isSequence: true}))
.then(messages => {
expect(messages.length).to.equal(1);
expect(messages[0].body).to.equal(MESSAGES[0].raw);
})
.then(_ => imap.move({messages: '1', destinationBox: '[Gmail]/Drafts'}))
.then(result => expect(result).to.equal("Success"))
.then(_ => imap.fetch({box: 'INBOX', messages: '1', isSequence: true}))
.then(messages => {
expect(messages.length).to.equal(1);
expect(messages[0].body).to.equal(MESSAGES[1].raw);
})
.then(_ => imap.fetch({box: '[Gmail]/Drafts', messages: '1'}))
.then(messages => {
expect(messages.length).to.equal(1);
expect(messages[0].body).to.equal(MESSAGES[0].raw);
expect(messages[0].attributes.uid).to.equal(1);
})
});
it('should manipulate flags', () => {
return Promise.resolve()
.then(_ => imap.addFlags({messages: '1', isSequence: true, flags: ['Foo']}))
.then(result => expect(result).to.equal("Success"))
.then(_ => imap.fetch({messages: '1', isSequence: true}))
.then(messages => {
expect(messages.length).to.equal(1);
expect(messages[0].attributes.flags).to.deep.equal(['\\Seen', '\\Foo']);
})
.then(_ => imap.setFlags({messages: '1', isSequence: true, flags: ['Bar', 'Baz']}))
.then(result => expect(result).to.equal("Success"))
.then(_ => imap.fetch({messages: '1', isSequence: true}))
.then(messages => {
expect(messages.length).to.equal(1);
expect(messages[0].attributes.flags).to.deep.equal(['\\Bar', '\\Baz']);
})
.then(_ => imap.deleteFlags({messages: '1', isSequence: true, flags: ['\\Baz']}))
.then(result => expect(result).to.equal('Success'))
.then(_ => imap.fetch({messages: '1', isSequence: true}))
.then(messages => {
expect(messages.length).to.equal(1);
expect(messages[0].attributes.flags).to.deep.equal(['\\Bar']);
})
})
it('should manipulate keywords', () => {
return Promise.resolve()
.then(_ => imap.addKeywords({messages: '1', isSequence: true, keywords: ['Foo']}))
.then(result => expect(result).to.equal("Success"))
.then(_ => imap.search({query: {keyword: 'Foo'}}))
.then(messages => {
expect(messages.length).to.equal(1);
})
.then(_ => imap.setKeywords({messages: '1', isSequence: true, keywords: ['Bar', 'Baz']}))
.then(result => expect(result).to.equal("Success"))
.then(_ => imap.search({query: {keyword: 'Baz'}}))
.then(messages => {
expect(messages.length).to.equal(1);
})
.then(_ => imap.deleteKeywords({messages: '1', isSequence: true, keywords: ['Baz']}))
.then(result => expect(result).to.equal('Success'))
.then(_ => imap.search({query: {keyword: 'Baz'}}))
.then(messages => {
expect(messages.length).to.equal(0);
})
})
})
|
import {expect} from 'chai';
import {parseBoolean, removePrefix} from '../../../src/server/common/string';
describe('server/common/string', () => {
it('parses boolean', () => {
expect(parseBoolean('foo')).to.be.true;
expect(parseBoolean('true')).to.be.true;
expect(parseBoolean('1')).to.be.true;
expect(parseBoolean('false')).to.be.false;
expect(parseBoolean('0')).to.be.false;
expect(parseBoolean('')).to.be.false;
expect(parseBoolean()).to.be.false;
});
it('removes prefix', () => {
expect(removePrefix('foobar', 'bar')).to.equal('foobar');
expect(removePrefix('foobar', 'foo')).to.equal('bar');
expect(removePrefix('foobar', 'Foo')).to.equal('foobar');
expect(removePrefix('foobar', 'Foo', true)).to.equal('bar');
});
});
|
require("./scraper")("semesters.json", null, true); |
#!/usr/bin/env node
var fs = require('fs'),
compressor = require('node-minify');
new compressor.minify({
type: 'gcc',
fileIn: 'playbook.js',
fileOut: 'playbook.min.js',
callback: function (err) {
if (err) {
console.log(err);
} else {
console.log("JS minified successfully.");
}
}
});
|
module.exports = { prefix: 'fas', iconName: 'mobile-android', icon: [320, 512, [], "f3ce", "M272 0H48C21.5 0 0 21.5 0 48v416c0 26.5 21.5 48 48 48h224c26.5 0 48-21.5 48-48V48c0-26.5-21.5-48-48-48zm-64 452c0 6.6-5.4 12-12 12h-72c-6.6 0-12-5.4-12-12v-8c0-6.6 5.4-12 12-12h72c6.6 0 12 5.4 12 12v8z"] }; |
import * as types from '../../constants/actionTypes';
import initialState from '../../reducers/initialState';
export default function (state = initialState.foods, action) {
switch (action.type) {
case types.RETRIEVE_CATEGORIES_SUCCESS:
return {
...state,
categories: action.categories
};
case types.ADD_TO_CARDS_SUCCESS:
return {
...state,
cards: action.cards
};
case types.RETRIEVE_NOWPLAYING_FOODS_SUCCESS:
return {
...state,
nowPlayingFoods: action.nowPlayingFoods
};
case types.RETRIEVE_FOODS_SEARCH_RESULT_SUCCESS:
return {
...state,
searchResults: action.searchResults
};
default:
return state;
}
}
|
'use strict';
/* Controllers */
var phonecatControllers = angular.module('phonecatControllers', []);
phonecatControllers.controller('PhoneListCtrl', ['$scope', 'Phone',
function($scope, Phone) {
$scope.phones = Phone.query();
$scope.orderProp = 'age';
}]);
phonecatControllers.controller('PhoneDetailCtrl', ['$scope', '$routeParams', 'Phone',
function($scope, $routeParams, Phone) {
$scope.phone = Phone.get({phoneId: $routeParams.phoneId}, function(phone) {
$scope.mainImageUrl = phone.images[0];
});
$scope.setImage = function(imageUrl) {
$scope.mainImageUrl = imageUrl;
};
}]);
phonecatControllers.controller('cartCtrl', function($scope, localStorageService) {
$scope.checkStorage = function(){
if(localStorageService.isSupported) {
var storageType = localStorageService.getStorageType();
$scope.cartDetails = [
{
"sessionId" :"",
"cartId": "",
"items": [
{
"itemId":"",
"itemName":"",
"quantity":"",
"itemDescription":"",
"price":""
},
{
"itemId":"",
"itemName":"",
"quantity":"",
"itemDescription":"",
"price":""
}
],
"userDetails":{
"userId":"1",
"userEmail": "test@avon.com",
"contactNo": "9876431135"
}
}
];
localStorageService.set('cartDetails',$scope.cartDetails);
console.log(storageType);
}else{
alert('Not Supported Localstorage');
}
};
});
|
// This returns the pid of the server process, and is the default server for "spawnServer".
// It's most useful for verifying a connection to the server.
const http = require('http');
const minimist = require('minimist');
const parsedArgs = minimist(process.argv);
const port = parsedArgs.port || process.env.SERVER_PORT || 3000;
const startSignal = parsedArgs.start_signal || `Server listening on: http://localhost:${port}`;
const signalStream = parsedArgs.signal_stream || 'stdout';
const server = http.createServer((req, res) => res.end(`${process.pid}`));
server.listen(port, () =>
// eslint-disable-next-line no-console
console[signalStream === 'stderr' ? 'error' : 'log'](startSignal)
);
|
/*
* ComposedQL
* For the full copyright and license information, please view the LICENSE.txt file.
*/
/* jslint node: true */
'use strict';
module.exports = require('./lib/composedql'); |
/* global angular */
(function(angular) {
angular.module('hrAngularYoutube')
.directive('playerTotalTime', function() {
return {
restrict: 'EA',
require: '^youtubePlayer',
link: function(scope, elm, attrs,youtubePlayerCtrl) {
youtubePlayerCtrl.getPlayer().then(function(player){
elm.html(player.getHumanReadableDuration());
});
}
};
});
})(angular);
|
import EditableField from './EditableField'
import { EditableFieldComposite } from './EditableFieldComposite'
export default EditableField
export { EditableFieldComposite }
|
const env = process.env;
exports.kibanaUser = {
username: env.TEST_KIBANA_USER || 'elastic',
password: env.TEST_KIBANA_PASS || 'changeme'
};
exports.kibanaServer = {
username: env.TEST_KIBANA_SERVER_USER || 'kibana',
password: env.TEST_KIBANA_SERVER_PASS || 'changeme'
};
exports.admin = {
username: env.TEST_ES_USER || 'elastic',
password: env.TEST_ES_PASS || 'changeme'
};
|
module.exports = [
{
type: 'item',
icon: 'fa fa-dashboard',
name: 'Dashboard',
router: {
name: 'Dashboard'
}
},
{
type: 'item',
icon: 'fa fa-users',
name: 'Teams',
badge: {
type: 'Integer',
data: 3
},
router: {
name: 'Teams'
}
},
{
type: 'item',
icon: 'fa fa-file-text',
name: 'Projects',
badge: {
type: 'Integer',
data: 4
},
router: {
name: 'Projects'
}
},
{
type: 'item',
icon: 'fa fa-calendar-o',
name: 'Calendar',
router: {
name: 'Calendar'
}
},
{
type: 'item',
icon: 'fa fa-inr',
name: 'Invoices',
router: {
name: 'Invoice'
}
},
{
type: 'item',
icon: 'fa fa-user',
name: 'Profile',
router: {
name: 'Profile'
}
}
]
|
app.directive('modalDialog', [
"settings",
"SessionService",
"$location",
function(
settings,
SessionService,
$location
) {
return {
templateUrl: settings.widgets + 'modal/dialog.html',
replace: true,
transclude: true,
scope: {
show: '='
},
link: function(scope, element, attrs) {
scope.dialogStyle = {};
if (attrs.width)
scope.dialogStyle.width = attrs.width;
if (attrs.height)
scope.dialogStyle.height = attrs.height;
scope.hideModal = function() {
scope.show = false;
console.log("hideModal körs");
};
}//end link
};
}
]); |
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(790);
/***/ }),
/***/ 3:
/***/ (function(module, exports) {
module.exports = function() { throw new Error("define cannot be used indirect"); };
/***/ }),
/***/ 582:
/***/ (function(module, exports) {
module.exports = require("./kendo.data");
/***/ }),
/***/ 599:
/***/ (function(module, exports) {
module.exports = require("./kendo.userevents");
/***/ }),
/***/ 776:
/***/ (function(module, exports) {
module.exports = require("./kendo.mobile.button");
/***/ }),
/***/ 790:
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function(f, define){
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [ __webpack_require__(582), __webpack_require__(599), __webpack_require__(776) ], __WEBPACK_AMD_DEFINE_FACTORY__ = (f), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
})(function(){
var __meta__ = { // jshint ignore:line
id: "mobile.listview",
name: "ListView",
category: "mobile",
description: "The Kendo Mobile ListView widget is used to display flat or grouped list of items.",
depends: [ "data", "userevents", "mobile.button" ]
};
(function($, undefined) {
var kendo = window.kendo,
Node = window.Node,
mobile = kendo.mobile,
ui = mobile.ui,
outerHeight = kendo._outerHeight,
DataSource = kendo.data.DataSource,
Widget = ui.DataBoundWidget,
ITEM_SELECTOR = ".km-list > li, > li:not(.km-group-container)",
HIGHLIGHT_SELECTOR = ".km-listview-link, .km-listview-label",
ICON_SELECTOR = "[" + kendo.attr("icon") + "]",
proxy = $.proxy,
attrValue = kendo.attrValue,
GROUP_CLASS = "km-group-title",
ACTIVE_CLASS = "km-state-active",
GROUP_WRAPPER = '<div class="' + GROUP_CLASS + '"><div class="km-text"></div></div>',
GROUP_TEMPLATE = kendo.template('<li><div class="' + GROUP_CLASS + '"><div class="km-text">#= this.headerTemplate(data) #</div></div><ul>#= kendo.render(this.template, data.items)#</ul></li>'),
WRAPPER = '<div class="km-listview-wrapper" />',
SEARCH_TEMPLATE = kendo.template('<form class="km-filter-form"><div class="km-filter-wrap"><input type="search" placeholder="#=placeholder#"/><a href="\\#" class="km-filter-reset" title="Clear"><span class="km-icon km-clear"></span><span class="km-text">Clear</span></a></div></form>'),
NS = ".kendoMobileListView",
STYLED = "styled",
DATABOUND = "dataBound",
DATABINDING = "dataBinding",
ITEM_CHANGE = "itemChange",
CLICK = "click",
CHANGE = "change",
PROGRESS = "progress",
FUNCTION = "function",
whitespaceRegExp = /^\s+$/,
buttonRegExp = /button/;
function whitespace() {
return this.nodeType === Node.TEXT_NODE && this.nodeValue.match(whitespaceRegExp);
}
function addIcon(item, icon) {
if (icon && !item[0].querySelector(".km-icon")) {
item.prepend('<span class="km-icon km-' + icon + '"/>');
}
}
function enhanceItem(item) {
addIcon(item, attrValue(item, "icon"));
addIcon(item, attrValue(item.children(ICON_SELECTOR), "icon"));
}
function enhanceLinkItem(item) {
var parent = item.parent(),
itemAndDetailButtons = item.add(parent.children(kendo.roleSelector("detailbutton"))),
otherNodes = parent.contents().not(itemAndDetailButtons).not(whitespace);
if (otherNodes.length) {
return;
}
item.addClass("km-listview-link")
.attr(kendo.attr("role"), "listview-link");
addIcon(item, attrValue(parent, "icon"));
addIcon(item, attrValue(item, "icon"));
}
function enhanceCheckBoxItem(label) {
if (!label[0].querySelector("input[type=checkbox],input[type=radio]")) {
return;
}
var item = label.parent();
if (item.contents().not(label).not(function() { return this.nodeType == 3; })[0]) {
return;
}
label.addClass("km-listview-label");
label.children("[type=checkbox],[type=radio]").addClass("km-widget km-icon km-check");
}
function putAt(element, top) {
$(element).css('transform', 'translate3d(0px, ' + top + 'px, 0px)');
}
var HeaderFixer = kendo.Class.extend({
init: function(listView) {
var scroller = listView.scroller();
if (!scroller) {
return;
}
this.options = listView.options;
this.element = listView.element;
this.scroller = listView.scroller();
this._shouldFixHeaders();
var headerFixer = this;
var cacheHeaders = function() {
headerFixer._cacheHeaders();
};
listView.bind("resize", cacheHeaders);
listView.bind(STYLED, cacheHeaders);
listView.bind(DATABOUND, cacheHeaders);
this._scrollHandler = function(e) {
headerFixer._fixHeader(e);
};
scroller.bind("scroll", this._scrollHandler);
},
destroy: function() {
var that = this;
if (that.scroller) {
that.scroller.unbind("scroll", that._scrollHandler);
}
},
_fixHeader: function(e) {
if (!this.fixedHeaders) {
return;
}
var i = 0,
scroller = this.scroller,
headers = this.headers,
scrollTop = e.scrollTop,
headerPair,
offset,
header;
do {
headerPair = headers[i++];
if (!headerPair) {
header = $("<div />");
break;
}
offset = headerPair.offset;
header = headerPair.header;
} while (offset + 1 > scrollTop);
if (this.currentHeader != i) {
scroller.fixedContainer.html(header.clone());
this.currentHeader = i;
}
},
_shouldFixHeaders: function() {
this.fixedHeaders = this.options.type === "group" && this.options.fixedHeaders;
},
_cacheHeaders: function() {
this._shouldFixHeaders();
if (!this.fixedHeaders) {
return;
}
var headers = [], offset = this.scroller.scrollTop;
this.element.find("." + GROUP_CLASS).each(function(_, header) {
header = $(header);
headers.unshift({
offset: header.position().top + offset,
header: header
});
});
this.headers = headers;
this._fixHeader({ scrollTop: offset });
}
});
var DEFAULT_PULL_PARAMETERS = function() {
return { page: 1 };
};
var RefreshHandler = kendo.Class.extend({
init: function(listView) {
var handler = this,
options = listView.options,
scroller = listView.scroller(),
pullParameters = options.pullParameters || DEFAULT_PULL_PARAMETERS;
this.listView = listView;
this.scroller = scroller;
listView.bind("_dataSource", function(e) {
handler.setDataSource(e.dataSource);
});
scroller.setOptions({
pullToRefresh: true,
pull: function() {
if (!handler._pulled) {
handler._pulled = true;
handler.dataSource.read(pullParameters.call(listView, handler._first));
}
},
messages: {
pullTemplate: options.messages.pullTemplate,
releaseTemplate: options.messages.releaseTemplate,
refreshTemplate: options.messages.refreshTemplate
}
});
},
setDataSource: function(dataSource) {
var handler = this;
this._first = dataSource.view()[0];
this.dataSource = dataSource;
dataSource.bind("change", function() {
handler._change();
});
dataSource.bind("error", function() {
handler._change();
});
},
_change: function() {
var scroller = this.scroller,
dataSource = this.dataSource;
if (this._pulled) {
scroller.pullHandled();
}
if (this._pulled || !this._first) {
var view = dataSource.view();
if (view[0]) {
this._first = view[0];
}
}
this._pulled = false;
}
});
var VirtualList = kendo.Observable.extend({
init: function(options) {
var list = this;
kendo.Observable.fn.init.call(list);
list.buffer = options.buffer;
list.height = options.height;
list.item = options.item;
list.items = [];
list.footer = options.footer;
list.buffer.bind("reset", function() {
list.refresh();
});
},
refresh: function() {
var buffer = this.buffer,
items = this.items,
endReached = false;
while(items.length) {
items.pop().destroy();
}
this.offset = buffer.offset;
var itemConstructor = this.item,
prevItem,
item;
for (var idx = 0; idx < buffer.viewSize; idx ++) {
if (idx === buffer.total()) {
endReached = true;
break;
}
item = itemConstructor(this.content(this.offset + items.length));
item.below(prevItem);
prevItem = item;
items.push(item);
}
this.itemCount = items.length;
this.trigger("reset");
this._resize();
if (endReached) {
this.trigger("endReached");
}
},
totalHeight: function() {
if (!this.items[0]) {
return 0;
}
var list = this,
items = list.items,
top = items[0].top,
bottom = items[items.length - 1].bottom,
averageItemHeight = (bottom - top) / list.itemCount,
remainingItemsCount = list.buffer.length - list.offset - list.itemCount;
return (this.footer ? this.footer.height : 0) + bottom + remainingItemsCount * averageItemHeight;
},
batchUpdate: function(top) {
var height = this.height(),
items = this.items,
item,
initialOffset = this.offset;
if (!items[0]) {
return;
}
if (this.lastDirection) { // scrolling up
while(items[items.length - 1].bottom > top + height * 2) {
if (this.offset === 0) {
break;
}
this.offset --;
item = items.pop();
item.update(this.content(this.offset));
item.above(items[0]);
items.unshift(item);
}
} else { // scrolling down
while (items[0].top < top - height) {
var nextIndex = this.offset + this.itemCount; // here, it should be offset + 1 + itemCount - 1.
if (nextIndex === this.buffer.total()) {
this.trigger("endReached");
break;
}
if (nextIndex === this.buffer.length) {
break;
}
item = items.shift();
item.update(this.content(this.offset + this.itemCount));
item.below(items[items.length - 1]);
items.push(item);
this.offset ++;
}
}
if (initialOffset !== this.offset) {
this._resize();
}
},
update: function(top) {
var list = this,
items = this.items,
item,
firstItem,
lastItem,
height = this.height(),
itemCount = this.itemCount,
padding = height / 2,
up = (this.lastTop || 0) > top,
topBorder = top - padding,
bottomBorder = top + height + padding;
if (!items[0]) {
return;
}
this.lastTop = top;
this.lastDirection = up;
if (up) { // scrolling up
if (items[0].top > topBorder && // needs reorder
items[items.length - 1].bottom > bottomBorder + padding && // enough padding below
this.offset > 0 // we are not at the top
)
{
this.offset --;
item = items.pop();
firstItem = items[0];
item.update(this.content(this.offset));
items.unshift(item);
item.above(firstItem);
list._resize();
}
} else { // scrolling down
if (
items[items.length - 1].bottom < bottomBorder && // needs reorder
items[0].top < topBorder - padding // enough padding above
)
{
var nextIndex = this.offset + itemCount; // here, it should be offset + 1 + itemCount - 1.
if (nextIndex === this.buffer.total()) {
this.trigger("endReached");
} else if (nextIndex !== this.buffer.length) {
item = items.shift();
lastItem = items[items.length - 1];
items.push(item);
item.update(this.content(this.offset + this.itemCount));
list.offset ++;
item.below(lastItem);
list._resize();
}
}
}
},
content: function(index) {
return this.buffer.at(index);
},
destroy: function() {
this.unbind();
},
_resize: function() {
var items = this.items,
top = 0,
bottom = 0,
firstItem = items[0],
lastItem = items[items.length - 1];
if (firstItem) {
top = firstItem.top;
bottom = lastItem.bottom;
}
this.trigger("resize", { top: top, bottom: bottom });
if (this.footer) {
this.footer.below(lastItem);
}
}
});
// export for testing purposes
kendo.mobile.ui.VirtualList = VirtualList;
var VirtualListViewItem = kendo.Class.extend({
init: function(listView, dataItem) {
var element = listView.append([dataItem], true)[0],
height = element.offsetHeight;
$.extend(this, {
top: 0,
element: element,
listView: listView,
height: height,
bottom: height
});
},
update: function(dataItem) {
this.element = this.listView.setDataItem(this.element, dataItem);
},
above: function(item) {
if (item) {
this.height = this.element.offsetHeight;
this.top = item.top - this.height;
this.bottom = item.top;
putAt(this.element, this.top);
}
},
below: function(item) {
if (item) {
this.height = this.element.offsetHeight;
this.top = item.bottom;
this.bottom = this.top + this.height;
putAt(this.element, this.top);
}
},
destroy: function() {
kendo.destroy(this.element);
$(this.element).remove();
}
});
var LOAD_ICON = '<div><span class="km-icon"></span><span class="km-loading-left"></span><span class="km-loading-right"></span></div>';
var VirtualListViewLoadingIndicator = kendo.Class.extend({
init: function(listView) {
this.element = $('<li class="km-load-more km-scroller-refresh" style="display: none"></li>').appendTo(listView.element);
this._loadIcon = $(LOAD_ICON).appendTo(this.element);
},
enable: function() {
this.element.show();
this.height = outerHeight(this.element, true);
},
disable: function() {
this.element.hide();
this.height = 0;
},
below: function(item) {
if (item) {
this.top = item.bottom;
this.bottom = this.height + this.top;
putAt(this.element, this.top);
}
}
});
var VirtualListViewPressToLoadMore = VirtualListViewLoadingIndicator.extend({
init: function(listView, buffer) {
this._loadIcon = $(LOAD_ICON).hide();
this._loadButton = $('<a class="km-load">' + listView.options.messages.loadMoreText + '</a>').hide();
this.element = $('<li class="km-load-more" style="display: none"></li>').append(this._loadIcon).append(this._loadButton).appendTo(listView.element);
var loadMore = this;
this._loadButton.kendoMobileButton().data("kendoMobileButton").bind("click", function() {
loadMore._hideShowButton();
buffer.next();
});
buffer.bind("resize", function() {
loadMore._showLoadButton();
});
this.height = outerHeight(this.element, true);
this.disable();
},
_hideShowButton: function() {
this._loadButton.hide();
this.element.addClass("km-scroller-refresh");
this._loadIcon.css('display', 'block');
},
_showLoadButton: function() {
this._loadButton.show();
this.element.removeClass("km-scroller-refresh");
this._loadIcon.hide();
}
});
var VirtualListViewItemBinder = kendo.Class.extend({
init: function(listView) {
var binder = this;
this.chromeHeight = outerHeight(listView.wrapper.children().not(listView.element));
this.listView = listView;
this.scroller = listView.scroller();
this.options = listView.options;
listView.bind("_dataSource", function(e) {
binder.setDataSource(e.dataSource, e.empty);
});
listView.bind("resize", function() {
if (!binder.list.items.length) {
return;
}
binder.scroller.reset();
binder.buffer.range(0);
binder.list.refresh();
});
this.scroller.makeVirtual();
this._scroll = function(e) {
binder.list.update(e.scrollTop);
};
this.scroller.bind('scroll', this._scroll);
this._scrollEnd = function(e) {
binder.list.batchUpdate(e.scrollTop);
};
this.scroller.bind('scrollEnd', this._scrollEnd);
},
destroy: function() {
this.list.unbind();
this.buffer.unbind();
this.scroller.unbind('scroll', this._scroll);
this.scroller.unbind('scrollEnd', this._scrollEnd);
},
setDataSource: function(dataSource, empty) {
var binder = this,
options = this.options,
listView = this.listView,
scroller = listView.scroller(),
pressToLoadMore = options.loadMore,
pageSize,
buffer,
footer;
this.dataSource = dataSource;
pageSize = dataSource.pageSize() || options.virtualViewSize;
if (!pageSize && !empty) {
throw new Error("the DataSource does not have page size configured. Page Size setting is mandatory for the mobile listview virtual scrolling to work as expected.");
}
if (this.buffer) {
this.buffer.destroy();
}
buffer = new kendo.data.Buffer(dataSource, Math.floor(pageSize / 2), pressToLoadMore);
if (pressToLoadMore) {
footer = new VirtualListViewPressToLoadMore(listView, buffer);
} else {
footer = new VirtualListViewLoadingIndicator(listView);
}
if (this.list) {
this.list.destroy();
}
var list = new VirtualList({
buffer: buffer,
footer: footer,
item: function(dataItem) { return new VirtualListViewItem(listView, dataItem); },
height: function() { return scroller.height(); }
});
list.bind("resize", function() {
binder.updateScrollerSize();
listView.updateSize();
});
list.bind("reset", function() {
binder.footer.enable();
});
list.bind("endReached", function() {
footer.disable();
binder.updateScrollerSize();
});
buffer.bind("expand", function() {
list.lastDirection = false; // expand down
list.batchUpdate(scroller.scrollTop);
});
$.extend(this, {
buffer: buffer,
scroller: scroller,
list: list,
footer: footer
});
},
updateScrollerSize: function() {
this.scroller.virtualSize(0, this.list.totalHeight() + this.chromeHeight);
},
refresh: function() {
this.list.refresh();
},
reset: function() {
this.buffer.range(0);
this.list.refresh();
}
});
var ListViewItemBinder = kendo.Class.extend({
init: function(listView) {
var binder = this;
this.listView = listView;
this.options = listView.options;
var itemBinder = this;
this._refreshHandler = function(e) {
itemBinder.refresh(e);
};
this._progressHandler = function() {
listView.showLoading();
};
listView.bind("_dataSource", function(e) {
binder.setDataSource(e.dataSource);
});
},
destroy: function() {
this._unbindDataSource();
},
reset: function() { },
refresh: function(e) {
var action = e && e.action,
dataItems = e && e.items,
listView = this.listView,
dataSource = this.dataSource,
prependOnRefresh = this.options.appendOnRefresh,
view = dataSource.view(),
groups = dataSource.group(),
groupedMode = groups && groups[0],
item;
if (action === "itemchange") {
if(!listView._hasBindingTarget()) {
item = listView.findByDataItem(dataItems)[0];
if (item) {
listView.setDataItem(item, dataItems[0]);
}
}
return;
}
var removedItems, addedItems, addedDataItems;
var adding = (action === "add" && !groupedMode) || (prependOnRefresh && !listView._filter);
var removing = action === "remove" && !groupedMode;
if (adding) {
// no need to unbind anything
removedItems = [];
} else if (removing) {
// unbind the items about to be removed;
removedItems = listView.findByDataItem(dataItems);
}
if (listView.trigger(DATABINDING, { action: action || "rebind", items: dataItems, removedItems: removedItems, index: e && e.index })) {
if (this._shouldShowLoading()) {
listView.hideLoading();
}
return;
}
if (action === "add" && !groupedMode) {
var index = view.indexOf(dataItems[0]);
if (index > -1) {
addedItems = listView.insertAt(dataItems, index);
addedDataItems = dataItems;
}
} else if (action === "remove" && !groupedMode) {
addedItems = [];
listView.remove(dataItems);
} else if (groupedMode) {
listView.replaceGrouped(view);
}
else if (prependOnRefresh && !listView._filter) {
addedItems = listView.prepend(view);
addedDataItems = view;
}
else {
listView.replace(view);
}
if (this._shouldShowLoading()) {
listView.hideLoading();
}
listView.trigger(DATABOUND, { ns: ui, addedItems: addedItems, addedDataItems: addedDataItems });
},
setDataSource: function(dataSource) {
if (this.dataSource) {
this._unbindDataSource();
}
this.dataSource = dataSource;
dataSource.bind(CHANGE, this._refreshHandler);
if (this._shouldShowLoading()) {
this.dataSource.bind(PROGRESS, this._progressHandler);
}
},
_unbindDataSource: function() {
this.dataSource.unbind(CHANGE, this._refreshHandler).unbind(PROGRESS, this._progressHandler);
},
_shouldShowLoading: function() {
var options = this.options;
return !options.pullToRefresh && !options.loadMore && !options.endlessScroll;
}
});
var ListViewFilter = kendo.Class.extend({
init: function(listView) {
var filter = this,
filterable = listView.options.filterable,
events = "change paste",
that = this;
this.listView = listView;
this.options = filterable;
listView.element.before(SEARCH_TEMPLATE({ placeholder: filterable.placeholder || "Search..." }));
if (filterable.autoFilter !== false) {
events += " keyup";
}
this.element = listView.wrapper.find(".km-search-form");
this.searchInput = listView.wrapper.find("input[type=search]")
.closest("form").on("submit" + NS, function(e) {
e.preventDefault();
})
.end()
.on("focus" + NS, function() {
filter._oldFilter = filter.searchInput.val();
})
.on(events.split(" ").join(NS + " ") + NS, proxy(this._filterChange, this));
this.clearButton = listView.wrapper.find(".km-filter-reset")
.on(CLICK, proxy(this, "_clearFilter"))
.hide();
this._dataSourceChange = $.proxy(this._refreshInput, this);
listView.bind("_dataSource", function(e) {
e.dataSource.bind("change", that._dataSourceChange);
});
},
_refreshInput: function() {
var appliedFilters = this.listView.dataSource.filter();
var searchInput = this.listView._filter.searchInput;
if (!appliedFilters || appliedFilters.filters[0].field !== this.listView.options.filterable.field) {
searchInput.val("");
} else {
searchInput.val(appliedFilters.filters[0].value);
}
},
_search: function(expr) {
this._filter = true;
this.clearButton[expr ? "show" : "hide"]();
this.listView.dataSource.filter(expr);
},
_filterChange: function(e) {
var filter = this;
if (e.type == "paste" && this.options.autoFilter !== false) {
setTimeout(function() {
filter._applyFilter();
}, 1);
} else {
this._applyFilter();
}
},
_applyFilter: function() {
var options = this.options,
value = this.searchInput.val(),
expr = value.length ? {
field: options.field,
operator: options.operator || "startswith",
ignoreCase: options.ignoreCase,
value: value
} : null;
if (value === this._oldFilter) {
return;
}
this._oldFilter = value;
this._search(expr);
},
_clearFilter: function(e) {
this.searchInput.val("");
this._search(null);
e.preventDefault();
}
});
var ListView = Widget.extend({
init: function(element, options) {
var listView = this;
Widget.fn.init.call(this, element, options);
element = this.element;
options = this.options;
// support for legacy typo in configuration options: scrollTreshold -> scrollThreshold.
if (options.scrollTreshold) {
options.scrollThreshold = options.scrollTreshold;
}
element
.on("down", HIGHLIGHT_SELECTOR, "_highlight")
.on("move up cancel", HIGHLIGHT_SELECTOR, "_dim");
this._userEvents = new kendo.UserEvents(element, {
fastTap: true,
filter: ITEM_SELECTOR,
allowSelection: true,
tap: function(e) {
listView._click(e);
}
});
// HACK!!! to negate the ms touch action from the user events.
element.css("-ms-touch-action", "auto");
element.wrap(WRAPPER);
this.wrapper = this.element.parent();
this._headerFixer = new HeaderFixer(this);
this._itemsCache = {};
this._templates();
this.virtual = options.endlessScroll || options.loadMore;
this._style();
if (this.options.$angular && (this.virtual || this.options.pullToRefresh)) {
setTimeout($.proxy(this, "_start"));
} else {
this._start();
}
},
_start: function() {
var options = this.options;
if (this.options.filterable) {
this._filter = new ListViewFilter(this);
}
if (this.virtual) {
this._itemBinder = new VirtualListViewItemBinder(this);
} else {
this._itemBinder = new ListViewItemBinder(this);
}
if (this.options.pullToRefresh) {
this._pullToRefreshHandler = new RefreshHandler(this);
}
this.setDataSource(options.dataSource);
this._enhanceItems(this.items());
kendo.notify(this, ui);
},
events: [
CLICK,
DATABINDING,
DATABOUND,
ITEM_CHANGE
],
options: {
name: "ListView",
style: "",
type: "flat",
autoBind: true,
fixedHeaders: false,
template: "#:data#",
headerTemplate: '<span class="km-text">#:value#</span>',
appendOnRefresh: false,
loadMore: false,
endlessScroll: false,
scrollThreshold: 30,
pullToRefresh: false,
messages: {
loadMoreText: "Press to load more",
pullTemplate: "Pull to refresh",
releaseTemplate: "Release to refresh",
refreshTemplate: "Refreshing"
},
pullOffset: 140,
filterable: false,
virtualViewSize: null
},
refresh: function() {
this._itemBinder.refresh();
},
reset: function() {
this._itemBinder.reset();
},
setDataSource: function(dataSource) {
// the listView should have a ready datasource for MVVM to function properly. But an empty datasource should not empty the element
var emptyDataSource = !dataSource;
this.dataSource = DataSource.create(dataSource);
this.trigger("_dataSource", { dataSource: this.dataSource, empty: emptyDataSource });
if (this.options.autoBind && !emptyDataSource) {
this.items().remove();
this.dataSource.fetch();
}
},
destroy: function() {
Widget.fn.destroy.call(this);
kendo.destroy(this.element);
this._userEvents.destroy();
if (this._itemBinder) {
this._itemBinder.destroy();
}
if(this._headerFixer) {
this._headerFixer.destroy();
}
this.element.unwrap();
delete this.element;
delete this.wrapper;
delete this._userEvents;
},
items: function() {
if (this.options.type === "group") {
return this.element.find(".km-list").children();
} else {
return this.element.children().not('.km-load-more');
}
},
scroller: function() {
if (!this._scrollerInstance) {
this._scrollerInstance = this.element.closest(".km-scroll-wrapper").data("kendoMobileScroller");
}
return this._scrollerInstance;
},
showLoading: function() {
var view = this.view();
if (view && view.loader) {
view.loader.show();
}
},
hideLoading: function() {
var view = this.view();
if (view && view.loader) {
view.loader.hide();
}
},
insertAt: function(dataItems, index, triggerChange) {
var listView = this;
return listView._renderItems(dataItems, function(items) {
if (index === 0) {
listView.element.prepend(items);
}
else if (index === -1) {
listView.element.append(items);
} else {
listView.items().eq(index - 1).after(items);
}
if (triggerChange) {
for (var i = 0; i < items.length; i ++) {
listView.trigger(ITEM_CHANGE, { item: items.eq(i), data: dataItems[i], ns: ui });
}
}
});
},
append: function(dataItems, triggerChange) {
return this.insertAt(dataItems, -1, triggerChange);
},
prepend: function(dataItems, triggerChange) {
return this.insertAt(dataItems, 0, triggerChange);
},
replace: function(dataItems) {
this.options.type = "flat";
this._angularItems("cleanup");
kendo.destroy(this.element.children());
this.element.empty();
this._userEvents.cancel();
this._style();
return this.insertAt(dataItems, 0);
},
replaceGrouped: function(groups) {
this.options.type = "group";
this._angularItems("cleanup");
this.element.empty();
var items = $(kendo.render(this.groupTemplate, groups));
this._enhanceItems(items.children("ul").children("li"));
this.element.append(items);
mobile.init(items);
this._style();
this._angularItems("compile");
},
remove: function(dataItems) {
var items = this.findByDataItem(dataItems);
this.angular("cleanup", function(){
return { elements: items };
});
kendo.destroy(items);
items.remove();
},
findByDataItem: function(dataItems) {
var selectors = [];
for (var idx = 0, length = dataItems.length; idx < length; idx ++) {
selectors[idx] = "[data-" + kendo.ns + "uid=" + dataItems[idx].uid + "]";
}
return this.element.find(selectors.join(","));
},
// item is a DOM element, not jQuery object.
setDataItem: function(item, dataItem) {
var listView = this,
replaceItem = function(items) {
var newItem = $(items[0]);
kendo.destroy(item);
listView.angular("cleanup", function(){ return { elements: [ $(item) ] }; });
$(item).replaceWith(newItem);
listView.trigger(ITEM_CHANGE, { item: newItem, data: dataItem, ns: ui });
};
return this._renderItems([dataItem], replaceItem)[0];
},
updateSize: function() {
this._size = this.getSize();
},
_renderItems: function(dataItems, callback) {
var items = $(kendo.render(this.template, dataItems));
callback(items);
this.angular("compile", function() {
return {
elements: items,
data: dataItems.map(function(data){
return { dataItem: data };
})
};
});
mobile.init(items);
this._enhanceItems(items);
return items;
},
_dim: function(e) {
this._toggle(e, false);
},
_highlight: function(e) {
this._toggle(e, true);
},
_toggle: function(e, highlight) {
if (e.which > 1) {
return;
}
var clicked = $(e.currentTarget),
item = clicked.parent(),
role = attrValue(clicked, "role") || "",
plainItem = (!role.match(buttonRegExp)),
prevented = e.isDefaultPrevented();
if (plainItem) {
item.toggleClass(ACTIVE_CLASS, highlight && !prevented);
}
},
_templates: function() {
var template = this.options.template,
headerTemplate = this.options.headerTemplate,
dataIDAttribute = ' data-uid="#=arguments[0].uid || ""#"',
templateProxy = {},
groupTemplateProxy = {};
if (typeof template === FUNCTION) {
templateProxy.template = template;
template = "#=this.template(data)#";
}
this.template = proxy(kendo.template("<li" + dataIDAttribute + ">" + template + "</li>"), templateProxy);
groupTemplateProxy.template = this.template;
if (typeof headerTemplate === FUNCTION) {
groupTemplateProxy._headerTemplate = headerTemplate;
headerTemplate = "#=this._headerTemplate(data)#";
}
groupTemplateProxy.headerTemplate = kendo.template(headerTemplate);
this.groupTemplate = proxy(GROUP_TEMPLATE, groupTemplateProxy);
},
_click: function(e) {
if (e.event.which > 1 || e.event.isDefaultPrevented()) {
return;
}
var dataItem,
item = e.target,
target = $(e.event.target),
buttonElement = target.closest(kendo.roleSelector("button", "detailbutton", "backbutton")),
button = kendo.widgetInstance(buttonElement, ui),
id = item.attr(kendo.attr("uid"));
if (id) {
dataItem = this.dataSource.getByUid(id);
}
if (this.trigger(CLICK, {target: target, item: item, dataItem: dataItem, button: button})) {
e.preventDefault();
}
},
_styleGroups: function() {
var rootItems = this.element.children();
rootItems.children("ul").addClass("km-list");
rootItems.each(function() {
var li = $(this),
groupHeader = li.contents().first();
li.addClass("km-group-container");
if (!groupHeader.is("ul") && !groupHeader.is("div." + GROUP_CLASS)) {
groupHeader.wrap(GROUP_WRAPPER);
}
});
},
_style: function() {
var options = this.options,
grouped = options.type === "group",
element = this.element,
inset = options.style === "inset";
element.addClass("km-listview")
.toggleClass("km-list", !grouped)
.toggleClass("km-virtual-list", this.virtual)
.toggleClass("km-listinset", !grouped && inset)
.toggleClass("km-listgroup", grouped && !inset)
.toggleClass("km-listgroupinset", grouped && inset);
if (!element.parents(".km-listview")[0]) {
element.closest(".km-content").toggleClass("km-insetcontent", inset); // iOS has white background when the list is not inset.
}
if (grouped) {
this._styleGroups();
}
this.trigger(STYLED);
},
_enhanceItems: function(items) {
items.each(function() {
var item = $(this),
child,
enhanced = false;
item.children().each(function() {
child = $(this);
if (child.is("a")) {
enhanceLinkItem(child);
enhanced = true;
} else if (child.is("label")) {
enhanceCheckBoxItem(child);
enhanced = true;
}
});
if (!enhanced) {
enhanceItem(item);
}
});
}
});
ui.plugin(ListView);
})(window.kendo.jQuery);
return window.kendo;
}, __webpack_require__(3));
/***/ })
/******/ }); |
(function (ns) {
'use strict';
ns.controllers.ActivityController = function () {
return {
system: undefined,
init: function(){
this.system.mapHandler('Config:init', 'activityView', 'configHandler');
}
};
};
}(chalk)); |
nile.typeref.resolve = function(env)
{
return env.getTypedef(this.name) || this;
};
nile.vardecl.resolve = function(env)
{
var type_ = this.type.resolve(env);
var this_ = nile.vardecl(this.name, type_);
return env.addVardecl(this_);
};
nile.vardecl.resolveWithType = function(env, type)
{
var type_ = this.type.prototype.constructor == nile.anytype ?
type : this.type.resolve(env);
var this_ = nile.vardecl(this.name, type_);
return env.addVardecl(this_);
};
nile.tuplepat.resolveWithType = function(env, type)
{
var types = type.innerTypes();
var elements_ = this.elements.map(function(e, i) {
return e.resolveWithType(env, types[i]);
});
return nile.tuplepat(elements_);
};
nile.numexpr.resolve = function(env)
{
var value_ = this.value == "∞" ? Infinity : parseFloat(this.value);
return nile.numexpr(value_);
};
nile.recfieldexpr.resolve = function(env)
{
var record_ = this.record.resolve(env);
var field_ = record_.getType().getFieldIndex(this.field);
return nile.recfieldexpr(record_, field_);
};
nile.opexpr.resolve = function(env)
{
this.arg = (this.arg instanceof Array) ? nile.tupleexpr(this.arg) : this.arg;
if (this.isChainedRelational())
return this.unchainRelational().resolve(env);
var arg_ = this.arg.resolve(env);
var op_ = env.getOpdef(this.op, this.fixity, arg_.getType());
return nile.opexpr(op_, this.fixity, arg_);
};
nile.varexpr.resolve = function(env)
{
var var_ = env.getVardecl(this.var);
if (!var_) {
try { var this_ = this.splitVars(); }
catch(e) { throw "Variable: " + this.var + " undeclared"; }
return this_.resolve(env);
}
return nile.varexpr(var_);
};
nile.vardef.resolve = function(env)
{
var rvalue_ = this.rvalue.resolve(env);
var lvalue_ = this.lvalue.resolveWithType(env, rvalue_.getType());
return nile.vardef(lvalue_, rvalue_);
};
nile.typedef.resolve = function(env)
{
env.pushScope();
var type_ = this.type.resolve(env);
env.popScope();
var this_ = nile.typedef(this.name, type_);
return env.addTypedef(this_);
};
nile.opsig.resolve = function(env)
{
var param_ = this.param.resolve(env);
var type_ = this.type.resolve(env);
return nile.opsig(this.name, this.fixity, param_, type_);
};
nile.opdef.resolve = function(env)
{
env.pushScope();
var sig_ = this.sig.resolve(env);
var paramType = sig_.param.getType();
var this_ = this.body ? nile.opdef(sig_, this.body.resolve(env)) :
nile.builtin.env.getOpdef(sig_.name, sig_.fixity, paramType);
// what if builtin opdef has different return value?
env.popScope();
return env.addOpdef(this_);
};
nile.ifstmt.resolve = function(env)
{
var condition_ = this.condition.resolve(env);
env.pushScope();
var tblock_ = this.tblock.resolve(env);
env.popScope();
env.pushScope();
var fblock_ = this.fblock.resolve(env);
env.popScope();
return nile.ifstmt(condition_, tblock_, fblock_);
};
nile.processinst.resolve = function(env)
{
// Resolve processdef at interpretation time (for incremental compiling).
var arg_ = this.arg.resolve(env);
return nile.processinst(this.processdef, arg_);
};
nile.processsig.resolve = function(env)
{
var param_ = this.param.resolve(env);
var type_ = this.type.resolve(env);
var this_ = nile.processsig(this.name, param_, type_);
env.addProcessdef(nile.processdef(this_, null, null, null));
return this_;
};
nile.processbody.resolveWithType = function(env, type)
{
var forpat_ = this.forpat.resolveWithType(env, type);
var block_ = this.block.resolve(env);
return nile.processbody(forpat_, block_);
};
nile.processdef.resolve = function(env)
{
env.pushScope();
var sig_ = this.sig.resolve(env);
var this_;
if (this.prologue.isEmpty() && !this.body) {
this_ = nile.builtin.env.getProcessdef(sig_.name);
// check that the process sigs match?
}
else {
var prologue_ = this.prologue.resolve(env);
var intype = sig_.getType().getIntype();
env.pushScope();
var body_ = this.body ? this.body.resolveWithType(env, intype) :
nile.builtin.env.getProcessdef("PassThrough").body;
env.popScope();
var epilogue_ = this.epilogue.resolve(env);
this_ = nile.processdef(sig_, prologue_, body_, epilogue_);
}
env.popScope();
env.addProcessdef(this_);
return this_;
};
// Wrap resolve and resolveWithType methods to set the sourceCodeRange on the result
for (objName in nile) {
var obj = nile[objName];
var resolve = obj["resolve"];
var resolveWithType = obj["resolveWithType"];
if (resolve) {
obj["resolve"] = resolve.wrap(function(previous, env) {
var range = this.sourceCodeRange;
var result = previous(env);
if (result && result["resolve"])
result.sourceCodeRange = range;
return result;
});
}
if (resolveWithType) {
obj["resolveWithType"] = resolveWithType.wrap(function(previous, env, type) {
var range = this.sourceCodeRange;
var result = previous(env, type);
if (result && result["resolve"])
result.sourceCodeRange = range;
return result;
});
}
}
|
var barelog__device__mem__manager_8h =
[
[ "barelog_device_mem_manager_t", "structbarelog__device__mem__manager__t.html", "structbarelog__device__mem__manager__t" ],
[ "BARELOG_DEBUG", "barelog__device__mem__manager_8h.html#af7df0739b5e31f131926969c00d0ed27", null ],
[ "barelog_debug_log", "barelog__device__mem__manager_8h.html#ae41a0e6ea107251288d2e0ca4de4c81e", null ],
[ "device_mem_manager_clean", "barelog__device__mem__manager_8h.html#a162936ac3b0025695807a714049e69ce", null ],
[ "device_mem_manager_clean_buffer", "barelog__device__mem__manager_8h.html#aa8aaa019e14ff7168ef1583f2cefbace", null ],
[ "device_mem_manager_clean_memory", "barelog__device__mem__manager_8h.html#a0fa6e5c257acb2c1f33bb0dd40acc64f", null ],
[ "device_mem_manager_flush", "barelog__device__mem__manager_8h.html#a9e7e5cddb1c6b846435ec7aaf8caa30e", null ],
[ "device_mem_manager_flush_buffer", "barelog__device__mem__manager_8h.html#ad37b960a3bfc77a5a6549cc84d1c783b", null ],
[ "device_mem_manager_init", "barelog__device__mem__manager_8h.html#a83f4e8c498c12b53d513f31d04629050", null ],
[ "device_mem_manager_is_buffer_full", "barelog__device__mem__manager_8h.html#a59cc512d952adbc5d520c3681d7ca33a", null ],
[ "device_mem_manager_write_buffer", "barelog__device__mem__manager_8h.html#a1a783d861b1c4fb27cea2bf65f53e9ad", null ]
]; |
describe('when weekends option is set', function() {
it('should show sat and sun if true', function() {
initCalendar({
weekends: true
})
var sun = $('.fc-day-header.fc-sun')[0]
var sat = $('.fc-day-header.fc-sun')[0]
expect(sun).toBeDefined()
expect(sat).toBeDefined()
})
it('should not show sat and sun if false', function() {
initCalendar({
weekends: false
})
var sun = $('.fc-day-header.fc-sun')[0]
var sat = $('.fc-day-header.fc-sun')[0]
expect(sun).not.toBeDefined()
expect(sat).not.toBeDefined()
})
})
|
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('/kit-sectionable', 'Integration | Component | kit sectionable', {
integration: true
});
test('it renders', function(assert) {
assert.expect(2);
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
this.render(hbs`{{kit-sectionable}}`);
assert.equal(this.$().text().trim(), '');
// Template block usage:
this.render(hbs`
{{#kit-sectionable}}
template block text
{{/kit-sectionable}}
`);
assert.equal(this.$().text().trim(), 'template block text');
});
|
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { PropTypes, Component } from 'react';
import classNames from 'classnames';
import styles from './Navigation.css';
import withStyles from '../../decorators/withStyles';
import Link from '../Link';
@withStyles(styles)
class Navigation extends Component {
static propTypes = {
className: PropTypes.string,
};
render() {
return (
<div className={classNames(this.props.className, 'Navigation')} role="navigation">
<a className="Navigation-link" href="/scores" onClick={Link.handleClick}>Scores</a>
<a className="Navigation-link" href="/contact" onClick={Link.handleClick}>Contact</a>
<span className="Navigation-spacer"> | </span>
<a className="Navigation-link" href="/login" onClick={Link.handleClick}>Log in</a>
<span className="Navigation-spacer">or</span>
<a className="Navigation-link Navigation-link--highlight" href="/register" onClick={Link.handleClick}>Sign up</a>
</div>
);
}
}
export default Navigation;
|
import React, { Component } from 'react';
import NotificationSystem from 'react-notification-system';
class Notifications extends Component {
showNotification(position) {
this.notificationSystem.addNotification({
message: 'Welcome to Crystal Dashboard - a beautiful React dashboard for everyone.',
level: 'success',
autoDismiss: 0,
position
});
}
render() {
return (
<div className="content">
<div className="container-fluid">
<div className="card">
<div className="header">
<h4>Notifications</h4>
</div>
<div className="content">
<div className="places-buttons">
<div className="row">
<div className="col-md-6 col-md-offset-3 text-center">
<h5>Notifications Places
<p className="category">Click to view notifications</p>
</h5>
</div>
</div>
<div className="row">
<div className="col-md-2 col-md-offset-3">
<button className="btn btn-default btn-block" onClick={() => this.showNotification('tl')}>Top Left</button>
</div>
<div className="col-md-2">
<button className="btn btn-default btn-block" onClick={() => this.showNotification('tc')}>Top Center</button>
</div>
<div className="col-md-2">
<button className="btn btn-default btn-block" onClick={() => this.showNotification('tr')}>Top Right</button>
</div>
</div>
<div className="row">
<div className="col-md-2 col-md-offset-3">
<button className="btn btn-default btn-block" onClick={() => this.showNotification('bl')}>Bottom Left</button>
</div>
<div className="col-md-2">
<button className="btn btn-default btn-block" onClick={() => this.showNotification('bc')}>Bottom Center</button>
</div>
<div className="col-md-2">
<button className="btn btn-default btn-block" onClick={() => this.showNotification('br')}>Bottom Right</button>
</div>
</div>
</div>
<NotificationSystem
ref={ref => this.notificationSystem = ref} />
</div>
</div>
</div>
</div>
);
}
}
export default Notifications; |
dc.ui.TemplateFieldListing = Backbone.View.extend({
events: {
'click .delete': 'deleteField'
},
initialize: function() {
_.bindAll(this, 'deleteField');
this.model.on('destroy', this.deleteView, this);
},
render: function(options) {
this.$el.html(JST['template/template_field_listing']({
field_name: this.model.get('field_name')
}));
return this;
},
deleteView: function(options) {
this.remove();
this.$el = $();
},
//Actual delete of template
deleteField: function(template) {
this.model.destroy();
this.trigger('destroy', this);
return true;
}
}) |
var packageData = require('./package.json');
// expose the API to the world
module.exports.createServer = require('./lib/server.js');
module.exports.createSimpleServer = require('./lib/simpleserver.js');
module.exports.connect = require('./lib/client.js');
module.exports.createClientPool = require('./lib/pool.js');
module.exports.version = packageData.version;
|
var G = {
'delayInit': [],
'opts': {},
};
/*******************************************************************************
* Switcher panel
******************************************************************************/
(function () {
var list = document.getElementById('list');
function generateButton(tab, idx) {
var button = document.createElement('button');
button.id = 'tab-' + idx;
button.tab = tab;
list.appendChild(button);
}
function handleFaviconLoadfailure(event) {
event.target.offsetParent.className += ' not-found';
event.target.remove();
}
function generateFavIcon(button, iconInfo) {
var favIcon = document.createElement('div');
favIcon.className = 'fav-icon';
if (typeof iconInfo === 'object') {
var img = document.createElement('img');
img.className = iconInfo.type;
img.src = iconInfo.data;
img.addEventListener("error", handleFaviconLoadfailure);
favIcon.appendChild(img);
} else {
favIcon.className += ' not-found';
}
button.appendChild(favIcon);
}
window.Switcher = {
loadFavIcons: function (favIcons) {
var buttons = list.childNodes;
for (var i = 0; i < buttons.length; i++) {
generateFavIcon(buttons[i], favIcons[buttons[i].tab.favIconUrl]);
}
},
generate: function (tabs) {
for (var i = 0; i < tabs.length; i++) {
generateButton(tabs[i], i);
};
},
};
})();
/*******************************************************************************
* Handle Keyboard events
******************************************************************************/
// Watch for the mod release
window.addEventListener('keyup', function (e) {
if (!e[G.opts.mod]) {
window.close();
}
});
window.addEventListener('keydown', function (e) {
console.log('keydown', e);
});
/*******************************************************************************
* Handle Click events
******************************************************************************/
G.delayInit.push(function () {
window.addEventListener('click', function (e) {
var elem = e.target;
if (elem.tagName !== "BUTTON") {
elem = elem.offsetParent;
if (elem.tagName !== "BUTTON") { return; }
}
var idx = elem.dataset.index;
setActive(idx);
openActiveTab();
});
});
chrome.runtime.sendMessage({ type: 'loadSwitcher' }, function (info) {
G.opts = info.opts;
G.currentTab = info.currentTab;
Switcher.generate(info.tabs);
});
G.delayInit.push(function () {
chrome.runtime.sendMessage({ type: 'loadFavIcons' }, Switcher.loadFavIcons);
});
/*******************************************************************************
* Init
******************************************************************************/
// To make the popup open faster, i delayed part of the initilisation.
setTimeout(function() {
for (var i = 0; i < G.delayInit.length; i++) {
G.delayInit[i]();
}
}, 75);
|
/**
* Created by way on 16/8/29.
* knife 引入模块
* 可添加扩充、覆盖 k模块的功能
*/
const $ = require('./knife');
['width', 'height'].forEach(function (dimension) {
var Dimension = dimension.replace(/./, function (m) {
return m[0].toUpperCase();
});
$.fn['outer' + Dimension] = function (margin) {
var elem = this;
if (elem) {
var size = elem[dimension]();
var sides = {
'width': ['left', 'right'],
'height': ['top', 'bottom']
};
sides[dimension].forEach(function (side) {
if (margin) size += parseInt(elem.css('margin-' + side), 10);
});
return size;
} else {
return null;
}
};
});
/*
$.fn.data = function(key, value) {
var tmpData = $(this).dataset();
if (!key) {
return tmpData;
}
// value may be 0, false, null
if (typeof value === 'undefined') {
// Get value
var dataVal = tmpData[key],
__eD = this[0].__eleData;
//if (dataVal !== undefined) {
if (__eD && (key in __eD)) {
return __eD[key];
} else {
return dataVal;
}
} else {
// Set value,uniformly set in extra ```__eleData```
for (var i = 0; i < this.length; i++) {
var el = this[i];
// delete multiple data in dataset
if (key in tmpData) delete el.dataset[key];
if (!el.__eleData) el.__eleData = {};
el.__eleData[key] = value;
}
return this;
}
};
*/
// 获取scroller对象
$.fn.getScroller = function(content) {
// 以前默认只能有一个无限滚动,因此infinitescroll都是加在content上,现在允许里面有多个,因此要判断父元素是否有content
content = content.hasClass('content') ? content : content.parents('.content');
if (content) {
return $(content).data('scroller');
} else {
return $('.content.javascript-scroll').data('scroller');
}
};
$.fn.scrollTop = function (value) {
if (!this.length) return
var hasScrollTop = 'scrollTop' in this[0]
if (value === undefined) return hasScrollTop ? this[0].scrollTop : this[0].pageYOffset
return this.each(hasScrollTop ?
function () {
this.scrollTop = value
} :
function () {
this.scrollTo(this.scrollX, value)
})
}
export default $; |
import RestClient from './restClient';
export default class AjaxClient extends RestClient {
getConfig(method, data, cookie) {
const config = {
credentials: this.getCredentialsConfig(this.baseUrl),
method,
headers: {
'Content-Type': 'application/json'
}
};
if (cookie) {
config.headers.Cookie = cookie;
}
if (data) {
config.body = JSON.stringify(data);
}
return config;
}
getCredentialsConfig(baseUrl) {
const includePrefix =
baseUrl.includes('http://') || baseUrl.includes('https://');
return includePrefix ? 'include' : 'same-origin';
}
}
|
const uuid = require('uuid/v4')
const zmq = require('zeromq')
const events = require('events')
const Handle = function (id, callback) {
this.id = id
this.callback = callback
}
Handle.prototype = Object.create(events.EventEmitter.prototype)
/**
* A client submits tasks to a broker.
*/
const Client = function (options = {}) {
this._message = this._message.bind(this)
this.options = options
this.handles = {}
this._connect()
}
Object.assign(Client.prototype, {
/**
* Closes the connection to the broker.
*/
close () { this.socket.close() },
/**
* Submits a task with the given name and data.
*/
submitTask (name, data, callback) {
const handle = this._addHandle(uuid(), callback)
const payload = JSON.stringify({ id: handle.id, request: name, data })
this.socket.send([Buffer.alloc(0), payload])
return handle
},
_connect () {
const endpoint = this.options.router || 'ipc:///tmp/bokeh-router'
this.socket = zmq.socket('dealer')
this.socket.on('message', this._message)
this.socket.connect(endpoint)
},
_message (...args) {
const adjustedLength = Math.max(args.length, 1)
const payload = args[adjustedLength - 1]
const task = JSON.parse(payload)
switch (task.response) {
case 'submitted':
this._submitted(task)
break
case 'completed':
this._completed(task)
break
case 'failed':
this._failed(task)
break
default:
throw new Error(`Unknown response '${task.response}'`)
}
},
_submitted (task) {
const handle = this._getHandle(task.id)
handle.emit('submit')
},
_completed (task) {
const handle = this._getHandle(task.id)
if (typeof handle.callback === 'function') {
handle.callback(null, task.data)
}
handle.emit('complete', task.data)
this._removeHandle(handle)
},
_failed (task) {
const handle = this._getHandle(task.id)
if (typeof handle.callback === 'function') {
handle.callback(task.data)
}
if (handle.listeners('error').length !== 0) { handle.emit('error', task.data) }
this._removeHandle(handle)
},
_getHandle (id) { return this.handles[id] },
_addHandle (id, callback) {
const handle = new Handle(id, callback)
this.handles[id] = handle
return handle
},
_removeHandle (handle) {
delete this.handles[handle.id]
}
})
module.exports = Client
|
import React, {Component} from "react";
import PropTypes from 'prop-types';
export default class Col extends Component{
static propTypes = {
children: PropTypes.any,
sizes: PropTypes.string
};
static defaultProps = {
children: null,
sizes: ''
};
render(){
const {children, sizes} = this.props;
return <div className={['col', sizes].join(' ')}>{children}</div>;
}
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:e425c02659d08eeb06a69b5b4b0e595d829102fec22d40755a277fc708130ee2
size 66495
|
var helper = require('./support/helper')
var assert = require('core-assert')
module.exports = function (cb) {
helper.run('safe/fixtures/nested-test.js#sub', function (er, result, log) {
assert.equal(result, true)
log.assert(
'TAP version 13',
'1..2',
'ok 1 - "sub test2" - test #1 in `safe/fixtures/nested-test.js`',
'ok 2 - "sub test3" - test #2 in `safe/fixtures/nested-test.js`'
)
// Make sure all the hooks ran as expected
assert.deepEqual(global.__results, [
'A', // top beforeAll
'D', // sub beforeAll
'B', // top beforeEach
'E', // sub beforeEach
'F', // "sub test 2"
'H', // sub afterEach
'J', // top afterEach
'B', // top beforeEach
'E', // sub beforeEach
'G', // "sub test 3"
'H', // sub afterEach
'J', // top afterEach
'I', // sub afterAll
'K' // top afterAll
])
delete global.__results
cb(er)
})
}
|
import React from 'react';
// eslint-disable-next-line
import PresenceStatusIcon from 'ringcentral-widgets/components/PresenceStatusIcon';
const props = {};
props.userStatus = 'Available';
/**
* A example of `PresenceStatusIcon`
*/
const PresenceStatusIconDemo = () => (
<PresenceStatusIcon
{...props}
/>
);
export default PresenceStatusIconDemo;
|
/*
* ------------------------------------------
* 超链接执行命令封装实现文件
* @version 1.0
* @author genify(caijf@corp.netease.com)
* ------------------------------------------
*/
/** util/editor/command/link */
NEJ.define([
'base/global',
'base/klass',
'util/editor/command/card',
'ui/editor/command/link'
],function(NEJ,_k,_t0,_i0,_p,_o,_f,_r){
var _pro;
/**
* 超链接执行命令封装
*
* @class module:util/editor/command/link._$$Link
* @extends module:util/editor/command/card._$$CardCommand
* @param {Object} options - 可选配置参数
*/
_p._$$Link = _k._$klass();
_pro = _p._$$Link._$extend(_t0._$$CardCommand);
/*
* 命令名称
*
* @const {String} module:util/editor/command/link._$$Link.command
*/
_p._$$Link.command = 'link';
/**
* 卡片内容变化回调,子类实现具体业务逻辑
*
* @protected
* @method module:util/editor/command/link._$$Link#__onChange
* @param {Object} _link - 链接地址对象
* @property {String} name - 链接名称
* @property {String} href - 链接地址
* @return {Void}
*/
_pro.__onChange = function(_link){
if(!_link)
return;
var _text = (_link.name != '') ? _link.name : _link.href;
this.__editor._$execCommand('inserthtml','<a target="_blank" href="'
+ _link.href + '">'+ _text +'</a>');
this.__editor._$focus();
};
/**
* 显示卡片,一般子类重写
*
* @protected
* @method module:util/editor/command/link._$$Link#__doShowCard
* @return {Void}
*/
_pro.__doShowCard = function(){
this.__fopt.name = this.__editor._$getSelectText();
this.__linkCard = this.__onShowCard();
this.__linkCard._$show();
this.__linkCard._$doFocus();
};
/**
* 子类实现显示具体卡片
*
* @protected
* @method module:util/editor/command/link._$$Link#__onShowCard
* @return {Void}
*/
_pro.__onShowCard = function(){
return _i0._$$LinkCard._$allocate({
draggable: true,
destroyable: true,
maskclazz: 'm-mask',
name: this.__fopt.name,
title: '添加超链接',
onchange: this.__onChange._$bind(this),
onErrorLink: this.__onError._$bind(this)
});
};
/**
* 链接错误提示
*
* @protected
* @method module:util/editor/command/link._$$Link#__onError
* @param {Object} type - 错误类型
* @return {Void}
*/
_pro.__onError = function(){
this.__linkCard.__showErrorTips('请输入合法的链接地址(http://或https://)');
};
// regist command implemention
_p._$$Link._$regist();
if (CMPT){
NEJ.copy(NEJ.P('nej.ut.cmd'),_p);
}
return _p;
}); |
// This defines the output rate, with unit of RF/t. Must be float-point number, i.e. has decimals.
var gen_level = 40.0;
var Opcodes = org.objectweb.asm.Opcodes;
var methodGenLevelGetter = node.methods.stream().filter(function (m){
return m.name.equals("genLevel");
}).findFirst().orElseThrow(function (){
return new java.lang.Error();
});
methodGenLevelGetter.instructions.clear();
methodGenLevelGetter.visitLdcInsn(gen_level);
methodGenLevelGetter.visitInsn(Opcodes.DRETURN);
methodGenLevelGetter.visitEnd();
node.visitEnd();
|
import chai from 'chai';
import dirty from 'dirty-chai';
import sinonChai from 'sinon-chai';
import sinon from 'sinon';
import DependenciesManager from '../../lib/dependenciesManager';
chai.use(sinonChai);
chai.use(dirty);
const { describe, it } = global;
const { expect } = chai;
describe('dependenciesManager', () => {
describe('#mergeDependencies', () => {
it('should merge dependencies', () => {
const instance = new DependenciesManager({}, { testDep: '1.0.0', testDep2: '2.1.2' });
const stub1 = sinon.stub(instance, 'validateDependenciesVersions');
stub1.returns(true);
const stub2 = sinon.stub(instance, 'detectDuplicatedDependencies');
instance.mergeDependencies('test', { testDep3: '1.2.3', testDep4: '2.4.3' });
expect(instance.getDependencies()).be.deep.equal(
{
testDep: '1.0.0',
testDep2: '2.1.2',
testDep3: '1.2.3',
testDep4: '2.4.3'
}
);
stub1.restore();
stub2.restore();
});
});
describe('#validateDependenciesVersions', () => {
it('should validate git/github', () => {
const instance = new DependenciesManager({});
const failRegex = /git or github link must have a commit hash/;
expect(() => instance.validateDependenciesVersions('test', {
dep: 'git+ssh://user@hostname:project.git'
})).to.throw(failRegex);
expect(() => instance.validateDependenciesVersions('test', {
dep: 'user/someproject'
})).to.throw(failRegex);
expect(() => instance.validateDependenciesVersions('test', {
dep: 'user/someproject#1234566'
})).to.not.throw(failRegex);
expect(() => instance.validateDependenciesVersions('test', {
dep: 'git+ssh://user@hostname:project.git#1234566'
})).to.not.throw(failRegex);
});
it('should warn on file/local', () => {
const instance = new DependenciesManager({});
const warnStub = sinon.stub(instance.log, 'warn');
const warningMatch = /using dependencies from local paths is permitted/;
instance.validateDependenciesVersions('test', {
dep: '../some/path',
dep2: 'file://path'
});
expect(warnStub.firstCall).to.be.calledWithMatch(warningMatch);
expect(warnStub).to.be.calledOnce();
});
it('should validate semver', () => {
const instance = new DependenciesManager({});
const failRegex = /semver ranges are forbidden, please specify exact version/;
const testVersions = [
'1.0.0 - 2.9999.9999',
'>=1.0.2 <2.1.2',
'>1.0.2 <=2.3.4',
'<1.0.0 || >=2.3.1 <2.4.5 || >=2.5.2 <3.0.0',
'~1.2',
'~1.2.3',
'2.x',
'3.3.x',
'',
'*'
];
testVersions.forEach((version) => {
expect(() => instance.validateDependenciesVersions('test', {
dep: version
})).to.throw(failRegex);
});
expect(() => instance.validateDependenciesVersions('test', {
dep: '2.3.1'
})).to.not.throw(failRegex);
});
});
const testDependencies = {
module1: '../foo/bar',
module2: '~/foo/bar',
module3: './foo/bar',
module4: '/foo/bar',
module5: 'foo/bar',
module6: 'git://github.com',
module7: 'http://asdf.com/asdf.tar.gz',
module8: 'file:../dyl',
module9: '2.0.1'
};
describe('#getLocalDependencies', () => {
it('should return only local dependencies', () => {
const instance = new DependenciesManager({});
instance.dependencies = Object.assign({}, testDependencies);
const localDeps = instance.getLocalDependencies();
const depsKeys = Object
.keys(localDeps)
.map(dep => parseInt(dep.substr(dep.length - 1), 10));
expect(depsKeys).to.be.eql([1, 2, 3, 4, 8]);
});
});
describe('#getRemoteDependencies', () => {
it('should return only remote dependencies', () => {
const instance = new DependenciesManager({});
instance.dependencies = Object.assign({}, testDependencies);
const localDeps = instance.getRemoteDependencies();
const depsKeys = Object
.keys(localDeps)
.map(dep => parseInt(dep.substr(dep.length - 1), 10));
expect(depsKeys).to.be.eql([5, 6, 7, 9]);
});
});
describe('#detectDependencyType', () => {
it('should detect local path', () => {
const instance = new DependenciesManager({});
let files = [
'../foo/bar',
'~/foo/bar',
'./foo/bar',
'/foo/bar',
'foo/bar',
'git://github.com',
'http://asdf.com/asdf.tar.gz',
'file:../dyl',
'2.0.1'
];
files = files.map(filePath => instance.detectDependencyVersionType(filePath));
expect(files.slice(0, 4)).to.be.eql(new Array(4).fill('local'));
expect(files.slice(4)).to.not.include('local');
});
it('should detect git links', () => {
const instance = new DependenciesManager({});
let files = [
'git://github.com/user/project.git#commit-ish',
'git+ssh://user@hostname:project.git#commit-ish',
'git+ssh://user@hostname/project.git#commit-ish',
'git+http://user@hostname/project/blah.git#commit-ish',
'git+https://user@hostname/project/blah.git#commit-ish',
'../foo/bar',
'/foo/bar',
'foo/bar',
'http://asdf.com/asdf.tar.gz',
'file:../dyl',
'2.0.1'
];
files = files.map(filePath => instance.detectDependencyVersionType(filePath));
expect(files.slice(0, 5)).to.be.eql(new Array(5).fill('git'));
expect(files.slice(5)).to.not.include('git');
});
it('should detect github link', () => {
const instance = new DependenciesManager({});
let files = [
'visionmedia/express',
'visionmedia/mocha#4727d357ea',
'git://github.com/user/project.git#commit-ish',
'../foo/bar',
'/foo/bar',
'http://asdf.com/asdf.tar.gz',
'file:../dyl',
'2.0.1'
];
files = files.map(filePath => instance.detectDependencyVersionType(filePath));
expect(files.slice(0, 2)).to.be.eql(new Array(2).fill('github'));
expect(files.slice(2)).to.not.include('github');
});
it('should detect github link', () => {
const instance = new DependenciesManager({});
let files = [
'http://asdf.com/asdf.tar.gz',
'https://asdf.com/asdf.tar.gz',
'visionmedia/express',
'git://github.com/user/project.git#commit-ish',
'../foo/bar',
'/foo/bar',
'file:../dyl',
'2.0.1'
];
files = files.map(filePath => instance.detectDependencyVersionType(filePath));
expect(files.slice(0, 2)).to.be.eql(new Array(2).fill('http'));
expect(files.slice(2)).to.not.include('http');
});
it('should detect file protocol', () => {
const instance = new DependenciesManager({});
let files = [
'file:../dyl',
'http://asdf.com/asdf.tar.gz',
'visionmedia/express',
'git://github.com/user/project.git#commit-ish',
'../foo/bar',
'/foo/bar',
'2.0.1'
];
files = files.map(filePath => instance.detectDependencyVersionType(filePath));
expect(files.slice(0, 1)).to.be.eql(new Array(1).fill('file'));
expect(files.slice(1)).to.not.include('file');
});
it('should detect version or tag', () => {
const instance = new DependenciesManager({});
let files = [
'1.0.0 - 2.9999.9999',
'>=1.0.2 <2.1.2',
'>1.0.2 <=2.3.4',
'2.0.1',
'<1.0.0 || >=2.3.1 <2.4.5 || >=2.5.2 <3.0.0',
'~1.2',
'~1.2.3',
'2.x',
'3.3.x',
'latest',
'next',
'file:../dyl',
'http://asdf.com/asdf.tar.gz',
'visionmedia/express',
'git://github.com/user/project.git#commit-ish',
'../foo/bar',
'/foo/bar',
];
files = files.map(filePath => instance.detectDependencyVersionType(filePath));
expect(files.slice(0, 11)).to.be.eql(new Array(11).fill('version'));
expect(files.slice(11)).to.not.include('version');
});
});
});
|
var angularApiAdapter = angular.module('angularApiAdapter', []); |
angular.module('mnBusy',[])
.factory('busyTrackerFactory',['$timeout','$q',
function($timeout,$q) {
return function() {
var tracker = {};
tracker.delayPromise = null;
tracker.durationPromise = null;
tracker.processingPromise = null;
tracker.busyPromise = null;
tracker.reset = function(options) {
// prepare tracked promises
var promises = [];
angular.forEach(options.promises,function(promise) {
// skip invalid values
if (!promise || typeof promise.then === 'undefined') {
return;
}
// skipp already tracked promises
if (promises.indexOf(promise) !== -1) {
return;
}
promises.push(promise);
});
// nothing to track => no need to wait
if (promises.length === 0) {
return;
}
// start all delays
options.delay = options.delay || 0;
tracker.delayPromise = $timeout(function() {},parseInt(options.delay,10));
tracker.delayPromise.then(
function() {
// delay timer expired
tracker.delayPromise = null;
options.minDuration = options.minDuration || 0;
tracker.durationPromise = $timeout(
function() {
// minDuration timer expired
tracker.durationPromise = null;
},parseInt(options.minDuration,10));
// start busy promise
tracker.busyPromise =
$q.all([tracker.durationPromise,tracker.processingPromise]).then(
function() {
// busy promise expired
tracker.busyPromise = null;
if (options.onReady) {
options.onReady();
}
}
);
},
function() {
// delay timer was canceled
tracker.delayPromise = null;
if (options.onReady) {
options.onReady();
}
}
);
// track all promises at once
tracker.processingPromise =
$q.all(promises).then(
function() {
// progress promise expired => process it
progressExpired();
},
function() {
// progress promise was canceled => process it
progressExpired();
}
);
function progressExpired() {
tracker.processingPromise = null;
if ( tracker.delayPromise !== null) {
// processing finioshed before delay is over => cancel delay and go on
$timeout.cancel(tracker.delayPromise);
}
}
};
tracker.isBusy = function() {
return tracker.delayPromise === null &&
tracker.busyPromise !== null;
};
tracker.isActive = function() {
return tracker.delayPromise !== null ||
tracker.busyPromise !== null;
};
return tracker;
};
}
])
.directive('busyTracker',['$injector','busyTrackerFactory',
function($injector,busyTrackerFactory){
var config;
function buildConfig(attrs){
// start with empty config
var config = {};
// add global defaults
var busyDefaultsName = 'busyDefaults';
if ($injector.has(busyDefaultsName)){
angular.extend(config,$injector.get(busyDefaultsName));
}
// add instance configs
var busyConfigAttr = attrs['busyConfig'];
if (busyConfigAttr){
var busyConfigValueName = busyDefaultsName+
busyConfigAttr.charAt(0).toUpperCase()+busyConfigAttr.slice(1);
if($injector.has(busyConfigValueName)){
angular.extend(config,$injector.get(busyConfigValueName));
}
}
return config;
}
return {
restrict: 'A',
scope: true,
transclude: true,
templateUrl: function(tElement,tAttrs){
config = buildConfig(tAttrs);
return config.templateUrl;
},
link: function(scope,element,attrs) {
// expose the tracker,config to template and children
scope.$tracker = busyTrackerFactory();
scope.$tracker.config = config;
// watch the promises for change
scope.$watchCollection(attrs['busyTracker'],function(promises) {
// normalize to array of promises
if (!angular.isArray(promises)) {
promises = [promises];
}
// start tracker if not already running
// skip reseting when some promise expires and is removed
// specially handle the case when last promise is removed but
// trackes has just expred and is marked inactive
if (!scope.$tracker.isActive() && promises.length > 0) {
scope.$tracker.reset({
promises: promises,
delay: config.delay,
minDuration: config.minDuration,
onReady: function() {
var busyReadyExp = attrs['busyReady'];
if (busyReadyExp) {
scope.$parent.$eval(busyReadyExp);
}
}
});
}
},true);
// watch params for change
var busyParams = attrs['busyParams'];
if (busyParams) {
scope.$watchCollection(busyParams,function(params) {
scope.$tracker.params = params;
},true);
}
}
};
}
])
.value('busyDefaults',{
delay: 200,
minDuration: 500
})
.value('busyDefaultsButton',{
templateUrl:'mnBusy/button.html'
})
.value('busyDefaultsOverlay',{
templateUrl:'mnBusy/overlay.html'
});
|
define(['jquery', 'storage'], function($, Storage) {
var App = Class.extend({
init: function() {
this.currentPage = 1;
this.blinkInterval = null;
this.previousState = null;
this.isParchmentReady = true;
this.ready = false;
this.storage = new Storage();
this.watchNameInputInterval = setInterval(this.toggleButton.bind(this), 100);
this.$playButton = $('.play'),
this.$playDiv = $('.play div');
},
setGame: function(game) {
this.game = game;
this.isMobile = this.game.renderer.mobile;
this.isTablet = this.game.renderer.tablet;
this.isDesktop = !(this.isMobile || this.isTablet);
this.supportsWorkers = !!window.Worker;
this.ready = true;
},
center: function() {
window.scrollTo(0, 1);
},
canStartGame: function() {
if(this.isDesktop) {
return (this.game && this.game.map && this.game.map.isLoaded);
} else {
return this.game;
}
},
tryStartingGame: function(username, starting_callback) {
var self = this,
$play = this.$playButton;
if(username !== '') {
if(!this.ready || !this.canStartGame()) {
if(!this.isMobile) {
// on desktop and tablets, add a spinner to the play button
$play.addClass('loading');
}
this.$playDiv.unbind('click');
var watchCanStart = setInterval(function() {
log.debug("waiting...");
if(self.canStartGame()) {
setTimeout(function() {
if(!self.isMobile) {
$play.removeClass('loading');
}
}, 1500);
clearInterval(watchCanStart);
self.startGame(username, starting_callback);
}
}, 100);
} else {
this.$playDiv.unbind('click');
this.startGame(username, starting_callback);
}
}
},
startGame: function(username, starting_callback) {
var self = this;
if(starting_callback) {
starting_callback();
}
this.hideIntro(function() {
if(!self.isDesktop) {
// On mobile and tablet we load the map after the player has clicked
// on the PLAY button instead of loading it in a web worker.
self.game.loadMap();
}
self.start(username);
});
},
start: function(username) {
var self = this,
firstTimePlaying = !self.storage.hasAlreadyPlayed();
if(username && !this.game.started) {
var optionsSet = false;
var config = this.config;
if (!config.env) {
log.error("invalid config.env");
// stop
}
log.debug(`Starting game with ${config.env} config.`);
this.game.setServerOptions(config.url, username);
this.center();
this.game.run(function() {
$('body').addClass('started');
if(firstTimePlaying) {
self.toggleInstructions();
}
});
}
},
setMouseCoordinates: function(event) {
var gamePos = $('#container').offset(),
scale = this.game.renderer.getScaleFactor(),
width = this.game.renderer.getWidth(),
height = this.game.renderer.getHeight(),
mouse = this.game.mouse;
mouse.x = event.pageX - gamePos.left - (this.isMobile ? 0 : 5 * scale);
mouse.y = event.pageY - gamePos.top - (this.isMobile ? 0 : 7 * scale);
if(mouse.x <= 0) {
mouse.x = 0;
} else if(mouse.x >= width) {
mouse.x = width - 1;
}
if(mouse.y <= 0) {
mouse.y = 0;
} else if(mouse.y >= height) {
mouse.y = height - 1;
}
},
initHealthBar: function() {
var scale = this.game.renderer.getScaleFactor(),
healthMaxWidth = $("#healthbar").width() - (12 * scale);
this.game.onPlayerHealthChange(function(hp, maxHp) {
var barWidth = Math.round((healthMaxWidth / maxHp) * (hp > 0 ? hp : 0));
$("#hitpoints").css('width', barWidth + "px");
});
this.game.onPlayerHurt(this.blinkHealthBar.bind(this));
},
blinkHealthBar: function() {
var $hitpoints = $('#hitpoints');
$hitpoints.addClass('white');
setTimeout(function() {
$hitpoints.removeClass('white');
}, 500)
},
toggleButton: function() {
var name = $('#parchment input').val(),
$play = $('#createcharacter .play');
if(name && name.length > 0) {
$play.removeClass('disabled');
$('#character').removeClass('disabled');
} else {
$play.addClass('disabled');
$('#character').addClass('disabled');
}
},
hideIntro: function(hidden_callback) {
clearInterval(this.watchNameInputInterval);
$('body').removeClass('intro');
setTimeout(function() {
$('body').addClass('game');
hidden_callback();
}, 1000);
},
showChat: function() {
if(this.game.started) {
$('#chatbox').addClass('active');
$('#chatinput').focus();
$('#chatbutton').addClass('active');
}
},
hideChat: function() {
if(this.game.started) {
$('#chatbox').removeClass('active');
$('#chatinput').blur();
$('#chatbutton').removeClass('active');
}
},
toggleInstructions: function() {
if($('#achievements').hasClass('active')) {
this.toggleAchievements();
$('#achievementsbutton').removeClass('active');
}
$('#instructions').toggleClass('active');
},
toggleAchievements: function() {
if($('#instructions').hasClass('active')) {
this.toggleInstructions();
$('#helpbutton').removeClass('active');
}
this.resetPage();
$('#achievements').toggleClass('active');
},
resetPage: function() {
var self = this,
$achievements = $('#achievements');
if($achievements.hasClass('active')) {
$achievements.bind(TRANSITIONEND, function() {
$achievements.removeClass('page' + self.currentPage).addClass('page1');
self.currentPage = 1;
$achievements.unbind(TRANSITIONEND);
});
}
},
initEquipmentIcons: function() {
var scale = this.game.renderer.getScaleFactor();
var getIconPath = function(spriteName) {
return 'img/'+ scale +'/item-' + spriteName + '.png';
},
weapon = this.game.player.getWeaponName(),
armor = this.game.player.getSpriteName(),
weaponPath = getIconPath(weapon),
armorPath = getIconPath(armor);
$('#weapon').css('background-image', 'url("' + weaponPath + '")');
if(armor !== 'firefox') {
$('#armor').css('background-image', 'url("' + armorPath + '")');
}
},
hideWindows: function() {
if($('#achievements').hasClass('active')) {
this.toggleAchievements();
$('#achievementsbutton').removeClass('active');
}
if($('#instructions').hasClass('active')) {
this.toggleInstructions();
$('#helpbutton').removeClass('active');
}
if($('body').hasClass('credits')) {
this.closeInGameCredits();
}
if($('body').hasClass('about')) {
this.closeInGameAbout();
}
},
showAchievementNotification: function(id, name) {
var $notif = $('#achievement-notification'),
$name = $notif.find('.name'),
$button = $('#achievementsbutton');
$notif.removeClass().addClass('active achievement' + id);
$name.text(name);
if(this.game.storage.getAchievementCount() === 1) {
this.blinkInterval = setInterval(function() {
$button.toggleClass('blink');
}, 500);
}
setTimeout(function() {
$notif.removeClass('active');
$button.removeClass('blink');
}, 5000);
},
displayUnlockedAchievement: function(id) {
var $achievement = $('#achievements li.achievement' + id);
var achievement = this.game.getAchievementById(id);
if(achievement && achievement.hidden) {
this.setAchievementData($achievement, achievement.name, achievement.desc);
}
$achievement.addClass('unlocked');
},
unlockAchievement: function(id, name) {
this.showAchievementNotification(id, name);
this.displayUnlockedAchievement(id);
var nb = parseInt($('#unlocked-achievements').text());
$('#unlocked-achievements').text(nb + 1);
},
initAchievementList: function(achievements) {
var self = this,
$lists = $('#lists'),
$page = $('#page-tmpl'),
$achievement = $('#achievement-tmpl'),
page = 0,
count = 0,
$p = null;
_.each(achievements, function(achievement) {
count++;
var $a = $achievement.clone();
$a.removeAttr('id');
$a.addClass('achievement'+count);
if(!achievement.hidden) {
self.setAchievementData($a, achievement.name, achievement.desc);
}
$a.find('.twitter').attr('href', 'http://twitter.com/share?url=http%3A%2F%2Fbrowserquest.mozilla.org&text=I%20unlocked%20the%20%27'+ achievement.name +'%27%20achievement%20on%20Mozilla%27s%20%23BrowserQuest%21&related=glecollinet:Creators%20of%20BrowserQuest%2Cwhatthefranck');
$a.show();
$a.find('a').click(function() {
var url = $(this).attr('href');
self.openPopup('twitter', url);
return false;
});
if((count - 1) % 4 === 0) {
page++;
$p = $page.clone();
$p.attr('id', 'page'+page);
$p.show();
$lists.append($p);
}
$p.append($a);
});
$('#total-achievements').text($('#achievements').find('li').length);
},
initUnlockedAchievements: function(ids) {
var self = this;
_.each(ids, function(id) {
self.displayUnlockedAchievement(id);
});
$('#unlocked-achievements').text(ids.length);
},
setAchievementData: function($el, name, desc) {
$el.find('.achievement-name').html(name);
$el.find('.achievement-description').html(desc);
},
toggleCredits: function() {
var currentState = $('#parchment').attr('class');
if(this.game.started) {
$('#parchment').removeClass().addClass('credits');
$('body').toggleClass('credits');
if(!this.game.player) {
$('body').toggleClass('death');
}
if($('body').hasClass('about')) {
this.closeInGameAbout();
$('#helpbutton').removeClass('active');
}
} else {
if(currentState !== 'animate') {
if(currentState === 'credits') {
this.animateParchment(currentState, this.previousState);
} else {
this.animateParchment(currentState, 'credits');
this.previousState = currentState;
}
}
}
},
toggleAbout: function() {
var currentState = $('#parchment').attr('class');
if(this.game.started) {
$('#parchment').removeClass().addClass('about');
$('body').toggleClass('about');
if(!this.game.player) {
$('body').toggleClass('death');
}
if($('body').hasClass('credits')) {
this.closeInGameCredits();
}
} else {
if(currentState !== 'animate') {
if(currentState === 'about') {
if(localStorage && localStorage.data) {
this.animateParchment(currentState, 'loadcharacter');
} else {
this.animateParchment(currentState, 'createcharacter');
}
} else {
this.animateParchment(currentState, 'about');
this.previousState = currentState;
}
}
}
},
closeInGameCredits: function() {
$('body').removeClass('credits');
$('#parchment').removeClass('credits');
if(!this.game.player) {
$('body').addClass('death');
}
},
closeInGameAbout: function() {
$('body').removeClass('about');
$('#parchment').removeClass('about');
if(!this.game.player) {
$('body').addClass('death');
}
$('#helpbutton').removeClass('active');
},
togglePopulationInfo: function() {
$('#population').toggleClass('visible');
},
openPopup: function(type, url) {
var h = $(window).height(),
w = $(window).width(),
popupHeight,
popupWidth,
top,
left;
switch(type) {
case 'twitter':
popupHeight = 450;
popupWidth = 550;
break;
case 'facebook':
popupHeight = 400;
popupWidth = 580;
break;
}
top = (h / 2) - (popupHeight / 2);
left = (w / 2) - (popupWidth / 2);
newwindow = window.open(url,'name','height=' + popupHeight + ',width=' + popupWidth + ',top=' + top + ',left=' + left);
if (window.focus) {newwindow.focus()}
},
animateParchment: function(origin, destination) {
var self = this,
$parchment = $('#parchment'),
duration = 1;
if(this.isMobile) {
$parchment.removeClass(origin).addClass(destination);
} else {
if(this.isParchmentReady) {
if(this.isTablet) {
duration = 0;
}
this.isParchmentReady = !this.isParchmentReady;
$parchment.toggleClass('animate');
$parchment.removeClass(origin);
setTimeout(function() {
$('#parchment').toggleClass('animate');
$parchment.addClass(destination);
}, duration * 1000);
setTimeout(function() {
self.isParchmentReady = !self.isParchmentReady;
}, duration * 1000);
}
}
},
animateMessages: function() {
var $messages = $('#notifications div');
$messages.addClass('top');
},
resetMessagesPosition: function() {
var message = $('#message2').text();
$('#notifications div').removeClass('top');
$('#message2').text('');
$('#message1').text(message);
},
showMessage: function(message) {
var $wrapper = $('#notifications div'),
$message = $('#notifications #message2');
this.animateMessages();
$message.text(message);
if(this.messageTimer) {
this.resetMessageTimer();
}
this.messageTimer = setTimeout(function() {
$wrapper.addClass('top');
}, 5000);
},
resetMessageTimer: function() {
clearTimeout(this.messageTimer);
},
resizeUi: function() {
if(this.game) {
if(this.game.started) {
this.game.resize();
this.initHealthBar();
this.game.updateBars();
} else {
var newScale = this.game.renderer.getScaleFactor();
this.game.renderer.rescale(newScale);
}
}
}
});
return App;
}); |
var config = {
viewfolder: 'views',
extension: 'html',
container: '#content',
view:'home',
};
|
import template from './letters-list.html';
import appSettings from '../../app.settings';
class Controller {
/** @ngInject */
constructor(AllRestService) {
AllRestService.getAll()
.then(all => {
this.mailbox = all.mailboxes.find(mailbox => mailbox._id === this.mailboxId);
this.letters = all.letters.filter(letter => letter.mailbox === this.mailbox._id)
.map(letter => {
letter.user = all.users.find(user => user.email === letter.to);
return letter;
})
})
}
}
export default {
bindings: {
mailboxId: '<'
},
templateUrl: template,
controller: Controller
}
|
var fs = require('fs');
var path = require('path');
function rmdir(dstPath) {
var files = [];
if (fs.existsSync(dstPath)) {
files = fs.readdirSync(dstPath);
files.forEach(function(file, index) {
var curPath = path.join(dstPath, file);
if(fs.statSync(curPath).isDirectory()) {
rmdir(curPath);
}
else {
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(dstPath);
}
}
module.exports = rmdir; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.