repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
gmac/sass-thematic
lib/thematic.js
function() { if (typeof this.varsData !== 'string') { if (!this.varsFile) throw 'No theme variables file specified.'; this.varsFile = path.resolve(this.cwd, this.varsFile); this.varsData = fs.readFileSync(this.varsFile, 'utf-8'); } }
javascript
function() { if (typeof this.varsData !== 'string') { if (!this.varsFile) throw 'No theme variables file specified.'; this.varsFile = path.resolve(this.cwd, this.varsFile); this.varsData = fs.readFileSync(this.varsFile, 'utf-8'); } }
[ "function", "(", ")", "{", "if", "(", "typeof", "this", ".", "varsData", "!==", "'string'", ")", "{", "if", "(", "!", "this", ".", "varsFile", ")", "throw", "'No theme variables file specified.'", ";", "this", ".", "varsFile", "=", "path", ".", "resolve", "(", "this", ".", "cwd", ",", "this", ".", "varsFile", ")", ";", "this", ".", "varsData", "=", "fs", ".", "readFileSync", "(", "this", ".", "varsFile", ",", "'utf-8'", ")", ";", "}", "}" ]
Loads theme variables into the thematic instance.
[ "Loads", "theme", "variables", "into", "the", "thematic", "instance", "." ]
a887c15b98ec2c45452340a9bc26c5321add034a
https://github.com/gmac/sass-thematic/blob/a887c15b98ec2c45452340a9bc26c5321add034a/lib/thematic.js#L170-L176
train
gmac/sass-thematic
lib/thematic.js
function(source) { if (typeof source === 'object') { this.ast = source; } else if (typeof source === 'string') { // JSON source: if (isJSON(source)) { this.ast = JSON.parse(source); } // Sass source: else { this.ast = gonzales.parse(source, {syntax: 'scss'}); } } else { throw 'Source could not be loaded.'; } return this.resetMapping(); }
javascript
function(source) { if (typeof source === 'object') { this.ast = source; } else if (typeof source === 'string') { // JSON source: if (isJSON(source)) { this.ast = JSON.parse(source); } // Sass source: else { this.ast = gonzales.parse(source, {syntax: 'scss'}); } } else { throw 'Source could not be loaded.'; } return this.resetMapping(); }
[ "function", "(", "source", ")", "{", "if", "(", "typeof", "source", "===", "'object'", ")", "{", "this", ".", "ast", "=", "source", ";", "}", "else", "if", "(", "typeof", "source", "===", "'string'", ")", "{", "if", "(", "isJSON", "(", "source", ")", ")", "{", "this", ".", "ast", "=", "JSON", ".", "parse", "(", "source", ")", ";", "}", "else", "{", "this", ".", "ast", "=", "gonzales", ".", "parse", "(", "source", ",", "{", "syntax", ":", "'scss'", "}", ")", ";", "}", "}", "else", "{", "throw", "'Source could not be loaded.'", ";", "}", "return", "this", ".", "resetMapping", "(", ")", ";", "}" ]
Loads a source file into the renderer. @param {String|Object} source AST, JSON string, or Sass string. @returns {SassThematic} self reference.
[ "Loads", "a", "source", "file", "into", "the", "renderer", "." ]
a887c15b98ec2c45452340a9bc26c5321add034a
https://github.com/gmac/sass-thematic/blob/a887c15b98ec2c45452340a9bc26c5321add034a/lib/thematic.js#L201-L220
train
gmac/sass-thematic
lib/thematic.js
function(opts) { var opts = opts || {}; this._template = !!(opts.hasOwnProperty('template') ? opts.template : this.template); this._treeRemoval = !!(opts.hasOwnProperty('treeRemoval') ? opts.treeRemoval : this.treeRemoval); this._varsRemoval = !!(opts.hasOwnProperty('varsRemoval') ? opts.varsRemoval : this.varsRemoval); this._parseNode(this.ast); return this; }
javascript
function(opts) { var opts = opts || {}; this._template = !!(opts.hasOwnProperty('template') ? opts.template : this.template); this._treeRemoval = !!(opts.hasOwnProperty('treeRemoval') ? opts.treeRemoval : this.treeRemoval); this._varsRemoval = !!(opts.hasOwnProperty('varsRemoval') ? opts.varsRemoval : this.varsRemoval); this._parseNode(this.ast); return this; }
[ "function", "(", "opts", ")", "{", "var", "opts", "=", "opts", "||", "{", "}", ";", "this", ".", "_template", "=", "!", "!", "(", "opts", ".", "hasOwnProperty", "(", "'template'", ")", "?", "opts", ".", "template", ":", "this", ".", "template", ")", ";", "this", ".", "_treeRemoval", "=", "!", "!", "(", "opts", ".", "hasOwnProperty", "(", "'treeRemoval'", ")", "?", "opts", ".", "treeRemoval", ":", "this", ".", "treeRemoval", ")", ";", "this", ".", "_varsRemoval", "=", "!", "!", "(", "opts", ".", "hasOwnProperty", "(", "'varsRemoval'", ")", "?", "opts", ".", "varsRemoval", ":", "this", ".", "varsRemoval", ")", ";", "this", ".", "_parseNode", "(", "this", ".", "ast", ")", ";", "return", "this", ";", "}" ]
Parses the Thematic AST instance. All non-themed rules and declarations will be eliminated by default. @param {Object} options for parsing: - disableTreeRemoval: true to prevent destructive tree pruning. - disableVarsRemoval: true to prevent destructive variables removal. - template: true for template parsing. @returns {SassThematic} self reference.
[ "Parses", "the", "Thematic", "AST", "instance", ".", "All", "non", "-", "themed", "rules", "and", "declarations", "will", "be", "eliminated", "by", "default", "." ]
a887c15b98ec2c45452340a9bc26c5321add034a
https://github.com/gmac/sass-thematic/blob/a887c15b98ec2c45452340a9bc26c5321add034a/lib/thematic.js#L244-L251
train
gmac/sass-thematic
lib/thematic.js
function(parent) { function error(usage) { return new Error('Template theme fields are not permitted '+ usage +':\n>>> '+ Node.toString(parent)); } // Check for arguments implementation: if (parent.type === NodeType.ARGUMENTS) { throw error('as arguments'); } // Check for interpolations implementation: if (parent.type === NodeType.INTERPOLATION) { throw error('in interpolations'); } // Check for operations implementation: for (var i=0; i < parent.content.length; i++) { if (NodeType.OPERATOR.test(parent.content[i].type)) { throw error('in operations'); } } }
javascript
function(parent) { function error(usage) { return new Error('Template theme fields are not permitted '+ usage +':\n>>> '+ Node.toString(parent)); } // Check for arguments implementation: if (parent.type === NodeType.ARGUMENTS) { throw error('as arguments'); } // Check for interpolations implementation: if (parent.type === NodeType.INTERPOLATION) { throw error('in interpolations'); } // Check for operations implementation: for (var i=0; i < parent.content.length; i++) { if (NodeType.OPERATOR.test(parent.content[i].type)) { throw error('in operations'); } } }
[ "function", "(", "parent", ")", "{", "function", "error", "(", "usage", ")", "{", "return", "new", "Error", "(", "'Template theme fields are not permitted '", "+", "usage", "+", "':\\n>>> '", "+", "\\n", ")", ";", "}", "Node", ".", "toString", "(", "parent", ")", "if", "(", "parent", ".", "type", "===", "NodeType", ".", "ARGUMENTS", ")", "{", "throw", "error", "(", "'as arguments'", ")", ";", "}", "if", "(", "parent", ".", "type", "===", "NodeType", ".", "INTERPOLATION", ")", "{", "throw", "error", "(", "'in interpolations'", ")", ";", "}", "}" ]
Validates the usage context for a template field. Template fields are post-processed values, therefore may not be used in preprocessed functions, operations, or interpolations. @private
[ "Validates", "the", "usage", "context", "for", "a", "template", "field", ".", "Template", "fields", "are", "post", "-", "processed", "values", "therefore", "may", "not", "be", "used", "in", "preprocessed", "functions", "operations", "or", "interpolations", "." ]
a887c15b98ec2c45452340a9bc26c5321add034a
https://github.com/gmac/sass-thematic/blob/a887c15b98ec2c45452340a9bc26c5321add034a/lib/thematic.js#L425-L446
train
gmac/sass-thematic
lib/thematic.js
function(field) { if (this.vars.hasOwnProperty(field)) { if (!this.usage.hasOwnProperty(field)) { this.usage[field] = 0; } this.usage[field]++; } }
javascript
function(field) { if (this.vars.hasOwnProperty(field)) { if (!this.usage.hasOwnProperty(field)) { this.usage[field] = 0; } this.usage[field]++; } }
[ "function", "(", "field", ")", "{", "if", "(", "this", ".", "vars", ".", "hasOwnProperty", "(", "field", ")", ")", "{", "if", "(", "!", "this", ".", "usage", ".", "hasOwnProperty", "(", "field", ")", ")", "{", "this", ".", "usage", "[", "field", "]", "=", "0", ";", "}", "this", ".", "usage", "[", "field", "]", "++", ";", "}", "}" ]
Tracks field names used within the source, and keeps a running tally of their use count. @param {String} name of field to report on.
[ "Tracks", "field", "names", "used", "within", "the", "source", "and", "keeps", "a", "running", "tally", "of", "their", "use", "count", "." ]
a887c15b98ec2c45452340a9bc26c5321add034a
https://github.com/gmac/sass-thematic/blob/a887c15b98ec2c45452340a9bc26c5321add034a/lib/thematic.js#L453-L460
train
gmac/sass-thematic
lib/thematic.js
function(field) { if (this._template) { var match = field.match(this.fieldRegex); return match && this.vars.hasOwnProperty(match[1]); } return false; }
javascript
function(field) { if (this._template) { var match = field.match(this.fieldRegex); return match && this.vars.hasOwnProperty(match[1]); } return false; }
[ "function", "(", "field", ")", "{", "if", "(", "this", ".", "_template", ")", "{", "var", "match", "=", "field", ".", "match", "(", "this", ".", "fieldRegex", ")", ";", "return", "match", "&&", "this", ".", "vars", ".", "hasOwnProperty", "(", "match", "[", "1", "]", ")", ";", "}", "return", "false", ";", "}" ]
Validates the formatting of a template field, and checks for its name in the vars mapping table.
[ "Validates", "the", "formatting", "of", "a", "template", "field", "and", "checks", "for", "its", "name", "in", "the", "vars", "mapping", "table", "." ]
a887c15b98ec2c45452340a9bc26c5321add034a
https://github.com/gmac/sass-thematic/blob/a887c15b98ec2c45452340a9bc26c5321add034a/lib/thematic.js#L466-L472
train
gmac/sass-thematic
lib/thematic.js
function(opts, done) { if (typeof opts !== 'object') { done = opts; opts = null; } validateCallback(done); this.parse(opts); this.renderCSS(done); return this; }
javascript
function(opts, done) { if (typeof opts !== 'object') { done = opts; opts = null; } validateCallback(done); this.parse(opts); this.renderCSS(done); return this; }
[ "function", "(", "opts", ",", "done", ")", "{", "if", "(", "typeof", "opts", "!==", "'object'", ")", "{", "done", "=", "opts", ";", "opts", "=", "null", ";", "}", "validateCallback", "(", "done", ")", ";", "this", ".", "parse", "(", "opts", ")", ";", "this", ".", "renderCSS", "(", "done", ")", ";", "return", "this", ";", "}" ]
Renders flat CSS from pruned theme source. @param {Function} callback function to run on completion. @returns {SassThematic} self reference.
[ "Renders", "flat", "CSS", "from", "pruned", "theme", "source", "." ]
a887c15b98ec2c45452340a9bc26c5321add034a
https://github.com/gmac/sass-thematic/blob/a887c15b98ec2c45452340a9bc26c5321add034a/lib/thematic.js#L479-L488
train
gmac/sass-thematic
lib/thematic.js
function(done) { var isSync = (typeof done !== 'function'); var sass = require('node-sass'); var opts = this.sassCSSOptions(); if (isSync) { try { return sass.renderSync(opts).css.toString(); } catch (err) { throw formatSassError(err, opts.data); } } sass.render(opts, function(err, result) { if (err) return done(formatSassError(err, opts.data)); done(null, result.css.toString()); }); }
javascript
function(done) { var isSync = (typeof done !== 'function'); var sass = require('node-sass'); var opts = this.sassCSSOptions(); if (isSync) { try { return sass.renderSync(opts).css.toString(); } catch (err) { throw formatSassError(err, opts.data); } } sass.render(opts, function(err, result) { if (err) return done(formatSassError(err, opts.data)); done(null, result.css.toString()); }); }
[ "function", "(", "done", ")", "{", "var", "isSync", "=", "(", "typeof", "done", "!==", "'function'", ")", ";", "var", "sass", "=", "require", "(", "'node-sass'", ")", ";", "var", "opts", "=", "this", ".", "sassCSSOptions", "(", ")", ";", "if", "(", "isSync", ")", "{", "try", "{", "return", "sass", ".", "renderSync", "(", "opts", ")", ".", "css", ".", "toString", "(", ")", ";", "}", "catch", "(", "err", ")", "{", "throw", "formatSassError", "(", "err", ",", "opts", ".", "data", ")", ";", "}", "}", "sass", ".", "render", "(", "opts", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "return", "done", "(", "formatSassError", "(", "err", ",", "opts", ".", "data", ")", ")", ";", "done", "(", "null", ",", "result", ".", "css", ".", "toString", "(", ")", ")", ";", "}", ")", ";", "}" ]
Low-level implementation of CSS rendering. @param {Function} callback for asynchronous rendering. @returns {String|undefined} rendered CSS string (sync) or undefined (async). @private
[ "Low", "-", "level", "implementation", "of", "CSS", "rendering", "." ]
a887c15b98ec2c45452340a9bc26c5321add034a
https://github.com/gmac/sass-thematic/blob/a887c15b98ec2c45452340a9bc26c5321add034a/lib/thematic.js#L521-L538
train
gmac/sass-thematic
lib/thematic.js
function(opts, done) { if (typeof opts !== 'object') { done = opts; opts = {}; } validateCallback(done); opts.template = true; this.parse(opts); this.renderTemplate(done); return this; }
javascript
function(opts, done) { if (typeof opts !== 'object') { done = opts; opts = {}; } validateCallback(done); opts.template = true; this.parse(opts); this.renderTemplate(done); return this; }
[ "function", "(", "opts", ",", "done", ")", "{", "if", "(", "typeof", "opts", "!==", "'object'", ")", "{", "done", "=", "opts", ";", "opts", "=", "{", "}", ";", "}", "validateCallback", "(", "done", ")", ";", "opts", ".", "template", "=", "true", ";", "this", ".", "parse", "(", "opts", ")", ";", "this", ".", "renderTemplate", "(", "done", ")", ";", "return", "this", ";", "}" ]
Renders a flat CSS template with interpolation fields. @param {Function} callback function to run on completion. @returns {SassThematic} self reference.
[ "Renders", "a", "flat", "CSS", "template", "with", "interpolation", "fields", "." ]
a887c15b98ec2c45452340a9bc26c5321add034a
https://github.com/gmac/sass-thematic/blob/a887c15b98ec2c45452340a9bc26c5321add034a/lib/thematic.js#L545-L555
train
gmac/sass-thematic
lib/thematic.js
function(done) { var isSync = (typeof done !== 'function'); var sass = require('node-sass'); var opts = this.sassTemplateOptions(); var self = this; if (isSync) { try { var result = sass.renderSync(opts); return this.fieldIdentifiersToInterpolations(result.css.toString()); } catch (err) { throw formatSassError(err, opts.data); } } sass.render(opts, function(err, result) { if (err) return done(formatSassError(err, opts.data)); done(null, self.fieldIdentifiersToInterpolations(result.css.toString())); }); }
javascript
function(done) { var isSync = (typeof done !== 'function'); var sass = require('node-sass'); var opts = this.sassTemplateOptions(); var self = this; if (isSync) { try { var result = sass.renderSync(opts); return this.fieldIdentifiersToInterpolations(result.css.toString()); } catch (err) { throw formatSassError(err, opts.data); } } sass.render(opts, function(err, result) { if (err) return done(formatSassError(err, opts.data)); done(null, self.fieldIdentifiersToInterpolations(result.css.toString())); }); }
[ "function", "(", "done", ")", "{", "var", "isSync", "=", "(", "typeof", "done", "!==", "'function'", ")", ";", "var", "sass", "=", "require", "(", "'node-sass'", ")", ";", "var", "opts", "=", "this", ".", "sassTemplateOptions", "(", ")", ";", "var", "self", "=", "this", ";", "if", "(", "isSync", ")", "{", "try", "{", "var", "result", "=", "sass", ".", "renderSync", "(", "opts", ")", ";", "return", "this", ".", "fieldIdentifiersToInterpolations", "(", "result", ".", "css", ".", "toString", "(", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "throw", "formatSassError", "(", "err", ",", "opts", ".", "data", ")", ";", "}", "}", "sass", ".", "render", "(", "opts", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "return", "done", "(", "formatSassError", "(", "err", ",", "opts", ".", "data", ")", ")", ";", "done", "(", "null", ",", "self", ".", "fieldIdentifiersToInterpolations", "(", "result", ".", "css", ".", "toString", "(", ")", ")", ")", ";", "}", ")", ";", "}" ]
Low-level implementation of template rendering. @param {Function} callback for asynchronous rendering. @returns {String|undefined} rendered template string (sync) or undefined (async). @private
[ "Low", "-", "level", "implementation", "of", "template", "rendering", "." ]
a887c15b98ec2c45452340a9bc26c5321add034a
https://github.com/gmac/sass-thematic/blob/a887c15b98ec2c45452340a9bc26c5321add034a/lib/thematic.js#L590-L609
train
gmac/sass-thematic
lib/thematic.js
function(sass) { var match; while ((match = this.fieldRegexAll.exec(sass)) !== null) { if (this.vars.hasOwnProperty(match[1])) { this._addFieldUsage(match[1]); } } return this; }
javascript
function(sass) { var match; while ((match = this.fieldRegexAll.exec(sass)) !== null) { if (this.vars.hasOwnProperty(match[1])) { this._addFieldUsage(match[1]); } } return this; }
[ "function", "(", "sass", ")", "{", "var", "match", ";", "while", "(", "(", "match", "=", "this", ".", "fieldRegexAll", ".", "exec", "(", "sass", ")", ")", "!==", "null", ")", "{", "if", "(", "this", ".", "vars", ".", "hasOwnProperty", "(", "match", "[", "1", "]", ")", ")", "{", "this", ".", "_addFieldUsage", "(", "match", "[", "1", "]", ")", ";", "}", "}", "return", "this", ";", "}" ]
Counts the usage of all field identifiers in the source text. Field counts are reported into the parser's usage table. @param {String} sass string to count field usage in.
[ "Counts", "the", "usage", "of", "all", "field", "identifiers", "in", "the", "source", "text", ".", "Field", "counts", "are", "reported", "into", "the", "parser", "s", "usage", "table", "." ]
a887c15b98ec2c45452340a9bc26c5321add034a
https://github.com/gmac/sass-thematic/blob/a887c15b98ec2c45452340a9bc26c5321add034a/lib/thematic.js#L616-L624
train
gmac/sass-thematic
lib/thematic.js
formatSassError
function formatSassError(err, data) { // Generate three-line preview around the error: var preview = data.split('\n'); preview = preview.slice(Math.max(0, err.line-2), Math.min(err.line+1, preview.length-1)); preview = preview.map(function(src) { return '>>> '+ src }); preview.unshift(err.message); var error = new Error('Error rendering theme Sass:\n'+ preview.join('\n')); error.line = err.line || null; error.column = err.column || null; return error; }
javascript
function formatSassError(err, data) { // Generate three-line preview around the error: var preview = data.split('\n'); preview = preview.slice(Math.max(0, err.line-2), Math.min(err.line+1, preview.length-1)); preview = preview.map(function(src) { return '>>> '+ src }); preview.unshift(err.message); var error = new Error('Error rendering theme Sass:\n'+ preview.join('\n')); error.line = err.line || null; error.column = err.column || null; return error; }
[ "function", "formatSassError", "(", "err", ",", "data", ")", "{", "var", "preview", "=", "data", ".", "split", "(", "'\\n'", ")", ";", "\\n", "preview", "=", "preview", ".", "slice", "(", "Math", ".", "max", "(", "0", ",", "err", ".", "line", "-", "2", ")", ",", "Math", ".", "min", "(", "err", ".", "line", "+", "1", ",", "preview", ".", "length", "-", "1", ")", ")", ";", "preview", "=", "preview", ".", "map", "(", "function", "(", "src", ")", "{", "return", "'>>> '", "+", "src", "}", ")", ";", "preview", ".", "unshift", "(", "err", ".", "message", ")", ";", "var", "error", "=", "new", "Error", "(", "'Error rendering theme Sass:\\n'", "+", "\\n", ")", ";", "preview", ".", "join", "(", "'\\n'", ")", "\\n", "}" ]
Format Sass error for better contextual reporting.
[ "Format", "Sass", "error", "for", "better", "contextual", "reporting", "." ]
a887c15b98ec2c45452340a9bc26c5321add034a
https://github.com/gmac/sass-thematic/blob/a887c15b98ec2c45452340a9bc26c5321add034a/lib/thematic.js#L710-L721
train
gmac/sass-thematic
lib/ast.js
function(base) { for (var i=1; i < arguments.length; i++) { var ext = arguments[i]; for (var key in ext) { if (ext.hasOwnProperty(key)) base[key] = ext[key]; } } return base; }
javascript
function(base) { for (var i=1; i < arguments.length; i++) { var ext = arguments[i]; for (var key in ext) { if (ext.hasOwnProperty(key)) base[key] = ext[key]; } } return base; }
[ "function", "(", "base", ")", "{", "for", "(", "var", "i", "=", "1", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "{", "var", "ext", "=", "arguments", "[", "i", "]", ";", "for", "(", "var", "key", "in", "ext", ")", "{", "if", "(", "ext", ".", "hasOwnProperty", "(", "key", ")", ")", "base", "[", "key", "]", "=", "ext", "[", "key", "]", ";", "}", "}", "return", "base", ";", "}" ]
Merge properties from one or more objects onto a base object. @param {Object} base object to receive merged properties. @param {...Object} mixin objects to extend onto base.
[ "Merge", "properties", "from", "one", "or", "more", "objects", "onto", "a", "base", "object", "." ]
a887c15b98ec2c45452340a9bc26c5321add034a
https://github.com/gmac/sass-thematic/blob/a887c15b98ec2c45452340a9bc26c5321add034a/lib/ast.js#L16-L24
train
gmac/sass-thematic
lib/ast.js
function(opts) { return this.extend(gonzales.createNode({ type: 'stylesheet', syntax: 'scss', content: [], start: {line: 1, column: 1}, end: {line: 1, column: 1} }), opts || {}); }
javascript
function(opts) { return this.extend(gonzales.createNode({ type: 'stylesheet', syntax: 'scss', content: [], start: {line: 1, column: 1}, end: {line: 1, column: 1} }), opts || {}); }
[ "function", "(", "opts", ")", "{", "return", "this", ".", "extend", "(", "gonzales", ".", "createNode", "(", "{", "type", ":", "'stylesheet'", ",", "syntax", ":", "'scss'", ",", "content", ":", "[", "]", ",", "start", ":", "{", "line", ":", "1", ",", "column", ":", "1", "}", ",", "end", ":", "{", "line", ":", "1", ",", "column", ":", "1", "}", "}", ")", ",", "opts", "||", "{", "}", ")", ";", "}" ]
Creates a new empty Gonzales stylesheet node. @param {Object} options to extend onto the new node.
[ "Creates", "a", "new", "empty", "Gonzales", "stylesheet", "node", "." ]
a887c15b98ec2c45452340a9bc26c5321add034a
https://github.com/gmac/sass-thematic/blob/a887c15b98ec2c45452340a9bc26c5321add034a/lib/ast.js#L30-L38
train
gmac/sass-thematic
lib/ast.js
function(parentFile, importedFile) { if (parentFile.includedFiles.indexOf(importedFile.file) < 0) { // Add imported file reference: parentFile.includedFiles.push(importedFile.file); // Add all of imported file's imports: for (var i=0; i < importedFile.includedFiles.length; i++) { var includeFile = importedFile.includedFiles[i]; if (parentFile.includedFiles.indexOf(includeFile) < 0) { parentFile.includedFiles.push(includeFile); } } } }
javascript
function(parentFile, importedFile) { if (parentFile.includedFiles.indexOf(importedFile.file) < 0) { // Add imported file reference: parentFile.includedFiles.push(importedFile.file); // Add all of imported file's imports: for (var i=0; i < importedFile.includedFiles.length; i++) { var includeFile = importedFile.includedFiles[i]; if (parentFile.includedFiles.indexOf(includeFile) < 0) { parentFile.includedFiles.push(includeFile); } } } }
[ "function", "(", "parentFile", ",", "importedFile", ")", "{", "if", "(", "parentFile", ".", "includedFiles", ".", "indexOf", "(", "importedFile", ".", "file", ")", "<", "0", ")", "{", "parentFile", ".", "includedFiles", ".", "push", "(", "importedFile", ".", "file", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "importedFile", ".", "includedFiles", ".", "length", ";", "i", "++", ")", "{", "var", "includeFile", "=", "importedFile", ".", "includedFiles", "[", "i", "]", ";", "if", "(", "parentFile", ".", "includedFiles", ".", "indexOf", "(", "includeFile", ")", "<", "0", ")", "{", "parentFile", ".", "includedFiles", ".", "push", "(", "includeFile", ")", ";", "}", "}", "}", "}" ]
Maps included files from an import onto its parent.
[ "Maps", "included", "files", "from", "an", "import", "onto", "its", "parent", "." ]
a887c15b98ec2c45452340a9bc26c5321add034a
https://github.com/gmac/sass-thematic/blob/a887c15b98ec2c45452340a9bc26c5321add034a/lib/ast.js#L56-L69
train
gmac/sass-thematic
lib/ast.js
function(file) { if (!AST.cache) { return; } else if (typeof file === 'string') { if (!AST.cache[file]) AST.cache[file] = null; } else if (file.isParsed() && !file.timestamp) { file.timestamp = Date.now(); AST.cache[file.file] = file; } }
javascript
function(file) { if (!AST.cache) { return; } else if (typeof file === 'string') { if (!AST.cache[file]) AST.cache[file] = null; } else if (file.isParsed() && !file.timestamp) { file.timestamp = Date.now(); AST.cache[file.file] = file; } }
[ "function", "(", "file", ")", "{", "if", "(", "!", "AST", ".", "cache", ")", "{", "return", ";", "}", "else", "if", "(", "typeof", "file", "===", "'string'", ")", "{", "if", "(", "!", "AST", ".", "cache", "[", "file", "]", ")", "AST", ".", "cache", "[", "file", "]", "=", "null", ";", "}", "else", "if", "(", "file", ".", "isParsed", "(", ")", "&&", "!", "file", ".", "timestamp", ")", "{", "file", ".", "timestamp", "=", "Date", ".", "now", "(", ")", ";", "AST", ".", "cache", "[", "file", ".", "file", "]", "=", "file", ";", "}", "}" ]
Writes a file into the cache of parsed files. File paths may be submitted to expand the file graph, even if we don't have a valid file yet to fill the node.
[ "Writes", "a", "file", "into", "the", "cache", "of", "parsed", "files", ".", "File", "paths", "may", "be", "submitted", "to", "expand", "the", "file", "graph", "even", "if", "we", "don", "t", "have", "a", "valid", "file", "yet", "to", "fill", "the", "node", "." ]
a887c15b98ec2c45452340a9bc26c5321add034a
https://github.com/gmac/sass-thematic/blob/a887c15b98ec2c45452340a9bc26c5321add034a/lib/ast.js#L76-L87
train
gmac/sass-thematic
lib/ast.js
Importer
function Importer(opts) { var self = this; opts = opts || {}; EventEmitter.call(this); this.cwd = opts.cwd ? path.resolve(opts.cwd) : process.cwd(); this.file = opts.file ? path.resolve(opts.cwd, opts.file) : this.cwd; this.data = opts.data; this.includePaths = opts.includePaths || []; // Map all include paths to configured working directory: this.includePaths = this.includePaths.map(function(includePath) { return path.resolve(self.cwd, includePath); }); }
javascript
function Importer(opts) { var self = this; opts = opts || {}; EventEmitter.call(this); this.cwd = opts.cwd ? path.resolve(opts.cwd) : process.cwd(); this.file = opts.file ? path.resolve(opts.cwd, opts.file) : this.cwd; this.data = opts.data; this.includePaths = opts.includePaths || []; // Map all include paths to configured working directory: this.includePaths = this.includePaths.map(function(includePath) { return path.resolve(self.cwd, includePath); }); }
[ "function", "Importer", "(", "opts", ")", "{", "var", "self", "=", "this", ";", "opts", "=", "opts", "||", "{", "}", ";", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "cwd", "=", "opts", ".", "cwd", "?", "path", ".", "resolve", "(", "opts", ".", "cwd", ")", ":", "process", ".", "cwd", "(", ")", ";", "this", ".", "file", "=", "opts", ".", "file", "?", "path", ".", "resolve", "(", "opts", ".", "cwd", ",", "opts", ".", "file", ")", ":", "this", ".", "cwd", ";", "this", ".", "data", "=", "opts", ".", "data", ";", "this", ".", "includePaths", "=", "opts", ".", "includePaths", "||", "[", "]", ";", "this", ".", "includePaths", "=", "this", ".", "includePaths", ".", "map", "(", "function", "(", "includePath", ")", "{", "return", "path", ".", "resolve", "(", "self", ".", "cwd", ",", "includePath", ")", ";", "}", ")", ";", "}" ]
File Importer Primary engine for managing and resolving file imports. Manages options and serves as a central cache for resolved files. Also the primary event bus for messaging file import actions.
[ "File", "Importer", "Primary", "engine", "for", "managing", "and", "resolving", "file", "imports", ".", "Manages", "options", "and", "serves", "as", "a", "central", "cache", "for", "resolved", "files", ".", "Also", "the", "primary", "event", "bus", "for", "messaging", "file", "import", "actions", "." ]
a887c15b98ec2c45452340a9bc26c5321add034a
https://github.com/gmac/sass-thematic/blob/a887c15b98ec2c45452340a9bc26c5321add034a/lib/ast.js#L97-L110
train
gmac/sass-thematic
lib/ast.js
function(done) { this.async = true; var self = this; function finish(err, file) { var hasCallback = (typeof done === 'function'); if (err && !hasCallback) return self.emit('error', err); if (err) return done(err); done(null, file); } if (this.data) { this.createFile(this.file, this.uri, this.file, this.data, finish).parse(finish); } else { this.resolve(this.file, this.cwd, function(err, file) { if (err) return finish(err); file.parse(finish); }); } return this; }
javascript
function(done) { this.async = true; var self = this; function finish(err, file) { var hasCallback = (typeof done === 'function'); if (err && !hasCallback) return self.emit('error', err); if (err) return done(err); done(null, file); } if (this.data) { this.createFile(this.file, this.uri, this.file, this.data, finish).parse(finish); } else { this.resolve(this.file, this.cwd, function(err, file) { if (err) return finish(err); file.parse(finish); }); } return this; }
[ "function", "(", "done", ")", "{", "this", ".", "async", "=", "true", ";", "var", "self", "=", "this", ";", "function", "finish", "(", "err", ",", "file", ")", "{", "var", "hasCallback", "=", "(", "typeof", "done", "===", "'function'", ")", ";", "if", "(", "err", "&&", "!", "hasCallback", ")", "return", "self", ".", "emit", "(", "'error'", ",", "err", ")", ";", "if", "(", "err", ")", "return", "done", "(", "err", ")", ";", "done", "(", "null", ",", "file", ")", ";", "}", "if", "(", "this", ".", "data", ")", "{", "this", ".", "createFile", "(", "this", ".", "file", ",", "this", ".", "uri", ",", "this", ".", "file", ",", "this", ".", "data", ",", "finish", ")", ".", "parse", "(", "finish", ")", ";", "}", "else", "{", "this", ".", "resolve", "(", "this", ".", "file", ",", "this", ".", "cwd", ",", "function", "(", "err", ",", "file", ")", "{", "if", "(", "err", ")", "return", "finish", "(", "err", ")", ";", "file", ".", "parse", "(", "finish", ")", ";", "}", ")", ";", "}", "return", "this", ";", "}" ]
Runs the importer config asynchronously.
[ "Runs", "the", "importer", "config", "asynchronously", "." ]
a887c15b98ec2c45452340a9bc26c5321add034a
https://github.com/gmac/sass-thematic/blob/a887c15b98ec2c45452340a9bc26c5321add034a/lib/ast.js#L119-L140
train
gmac/sass-thematic
lib/ast.js
function() { this.async = false; var file; if (this.data) { file = this.createFile(this.file, this.uri, this.file, this.data); } else { file = this.resolveSync(this.file, this.cwd); } return file.parse(); }
javascript
function() { this.async = false; var file; if (this.data) { file = this.createFile(this.file, this.uri, this.file, this.data); } else { file = this.resolveSync(this.file, this.cwd); } return file.parse(); }
[ "function", "(", ")", "{", "this", ".", "async", "=", "false", ";", "var", "file", ";", "if", "(", "this", ".", "data", ")", "{", "file", "=", "this", ".", "createFile", "(", "this", ".", "file", ",", "this", ".", "uri", ",", "this", ".", "file", ",", "this", ".", "data", ")", ";", "}", "else", "{", "file", "=", "this", ".", "resolveSync", "(", "this", ".", "file", ",", "this", ".", "cwd", ")", ";", "}", "return", "file", ".", "parse", "(", ")", ";", "}" ]
Runs the importer config synchronously.
[ "Runs", "the", "importer", "config", "synchronously", "." ]
a887c15b98ec2c45452340a9bc26c5321add034a
https://github.com/gmac/sass-thematic/blob/a887c15b98ec2c45452340a9bc26c5321add034a/lib/ast.js#L145-L156
train
gmac/sass-thematic
lib/ast.js
File
function File(filepath, data, importer) { this.file = filepath; this.data = data; this.importer = importer; this.includedFiles = []; this._cb = []; _.cacheFile(filepath); }
javascript
function File(filepath, data, importer) { this.file = filepath; this.data = data; this.importer = importer; this.includedFiles = []; this._cb = []; _.cacheFile(filepath); }
[ "function", "File", "(", "filepath", ",", "data", ",", "importer", ")", "{", "this", ".", "file", "=", "filepath", ";", "this", ".", "data", "=", "data", ";", "this", ".", "importer", "=", "importer", ";", "this", ".", "includedFiles", "=", "[", "]", ";", "this", ".", "_cb", "=", "[", "]", ";", "_", ".", "cacheFile", "(", "filepath", ")", ";", "}" ]
File Handler for parsing loaded file data into an AST. Parsing resolves import statements, thus may request additional files.
[ "File", "Handler", "for", "parsing", "loaded", "file", "data", "into", "an", "AST", ".", "Parsing", "resolves", "import", "statements", "thus", "may", "request", "additional", "files", "." ]
a887c15b98ec2c45452340a9bc26c5321add034a
https://github.com/gmac/sass-thematic/blob/a887c15b98ec2c45452340a9bc26c5321add034a/lib/ast.js#L267-L274
train
roofstock/ember-cli-data-export
vendor/xlsx-0.10.8.js
sectorify
function sectorify(file, ssz) { var nsectors = Math.ceil(file.length/ssz)-1; var sectors = new Array(nsectors); for(var i=1; i < nsectors; ++i) sectors[i-1] = file.slice(i*ssz,(i+1)*ssz); sectors[nsectors-1] = file.slice(nsectors*ssz); return sectors; }
javascript
function sectorify(file, ssz) { var nsectors = Math.ceil(file.length/ssz)-1; var sectors = new Array(nsectors); for(var i=1; i < nsectors; ++i) sectors[i-1] = file.slice(i*ssz,(i+1)*ssz); sectors[nsectors-1] = file.slice(nsectors*ssz); return sectors; }
[ "function", "sectorify", "(", "file", ",", "ssz", ")", "{", "var", "nsectors", "=", "Math", ".", "ceil", "(", "file", ".", "length", "/", "ssz", ")", "-", "1", ";", "var", "sectors", "=", "new", "Array", "(", "nsectors", ")", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "nsectors", ";", "++", "i", ")", "sectors", "[", "i", "-", "1", "]", "=", "file", ".", "slice", "(", "i", "*", "ssz", ",", "(", "i", "+", "1", ")", "*", "ssz", ")", ";", "sectors", "[", "nsectors", "-", "1", "]", "=", "file", ".", "slice", "(", "nsectors", "*", "ssz", ")", ";", "return", "sectors", ";", "}" ]
Break the file up into sectors
[ "Break", "the", "file", "up", "into", "sectors" ]
93eda5cf4e40092e69fb702acdfc51ef82bac4c4
https://github.com/roofstock/ember-cli-data-export/blob/93eda5cf4e40092e69fb702acdfc51ef82bac4c4/vendor/xlsx-0.10.8.js#L1154-L1160
train
respectTheCode/node-caspar-cg
lib/xml2json.js
makePath
function makePath(object, path, index) { index = index || 0; var obj; if (path.length > index + 1) { obj = object[path[index]]; // we always want the last object in an array if (_.isArray(obj)) obj = _.last(obj); makePath(obj, path, index + 1); } else { obj = object[path[index]]; if (!obj) { // object doesn't exist yet so make it object[path[index]] = {}; } else { if (!_.isArray(obj)) { // object isn't an array yet so make an array with the object as the first element object[path[index]] = [obj]; } // append the new object object[path[index]].push({}); } } }
javascript
function makePath(object, path, index) { index = index || 0; var obj; if (path.length > index + 1) { obj = object[path[index]]; // we always want the last object in an array if (_.isArray(obj)) obj = _.last(obj); makePath(obj, path, index + 1); } else { obj = object[path[index]]; if (!obj) { // object doesn't exist yet so make it object[path[index]] = {}; } else { if (!_.isArray(obj)) { // object isn't an array yet so make an array with the object as the first element object[path[index]] = [obj]; } // append the new object object[path[index]].push({}); } } }
[ "function", "makePath", "(", "object", ",", "path", ",", "index", ")", "{", "index", "=", "index", "||", "0", ";", "var", "obj", ";", "if", "(", "path", ".", "length", ">", "index", "+", "1", ")", "{", "obj", "=", "object", "[", "path", "[", "index", "]", "]", ";", "if", "(", "_", ".", "isArray", "(", "obj", ")", ")", "obj", "=", "_", ".", "last", "(", "obj", ")", ";", "makePath", "(", "obj", ",", "path", ",", "index", "+", "1", ")", ";", "}", "else", "{", "obj", "=", "object", "[", "path", "[", "index", "]", "]", ";", "if", "(", "!", "obj", ")", "{", "object", "[", "path", "[", "index", "]", "]", "=", "{", "}", ";", "}", "else", "{", "if", "(", "!", "_", ".", "isArray", "(", "obj", ")", ")", "{", "object", "[", "path", "[", "index", "]", "]", "=", "[", "obj", "]", ";", "}", "object", "[", "path", "[", "index", "]", "]", ".", "push", "(", "{", "}", ")", ";", "}", "}", "}" ]
helper function to prepare a path for values this will convert a node into an array if it already exists
[ "helper", "function", "to", "prepare", "a", "path", "for", "values", "this", "will", "convert", "a", "node", "into", "an", "array", "if", "it", "already", "exists" ]
8b71bf587b1c44d65f24030c75bd4763ad5d038f
https://github.com/respectTheCode/node-caspar-cg/blob/8b71bf587b1c44d65f24030c75bd4763ad5d038f/lib/xml2json.js#L18-L45
train
respectTheCode/node-caspar-cg
lib/xml2json.js
setValueForPath
function setValueForPath(object, path, value, index) { index = index || 0; if (path.length > index + 1) { var obj = object[path[index]]; // we always want the last object in an array if (_.isArray(obj)) obj = _.last(obj); setValueForPath(obj, path, value, index + 1); } else { // found the object so set its value object[path[index]] = value; } }
javascript
function setValueForPath(object, path, value, index) { index = index || 0; if (path.length > index + 1) { var obj = object[path[index]]; // we always want the last object in an array if (_.isArray(obj)) obj = _.last(obj); setValueForPath(obj, path, value, index + 1); } else { // found the object so set its value object[path[index]] = value; } }
[ "function", "setValueForPath", "(", "object", ",", "path", ",", "value", ",", "index", ")", "{", "index", "=", "index", "||", "0", ";", "if", "(", "path", ".", "length", ">", "index", "+", "1", ")", "{", "var", "obj", "=", "object", "[", "path", "[", "index", "]", "]", ";", "if", "(", "_", ".", "isArray", "(", "obj", ")", ")", "obj", "=", "_", ".", "last", "(", "obj", ")", ";", "setValueForPath", "(", "obj", ",", "path", ",", "value", ",", "index", "+", "1", ")", ";", "}", "else", "{", "object", "[", "path", "[", "index", "]", "]", "=", "value", ";", "}", "}" ]
helper function to set the value of a path
[ "helper", "function", "to", "set", "the", "value", "of", "a", "path" ]
8b71bf587b1c44d65f24030c75bd4763ad5d038f
https://github.com/respectTheCode/node-caspar-cg/blob/8b71bf587b1c44d65f24030c75bd4763ad5d038f/lib/xml2json.js#L48-L62
train
kesla/sort-json
app/overwrite.js
overwriteFile
function overwriteFile(path, options) { let fileContent = null; let newData = null; try { fileContent = fs.readFileSync(path, 'utf8'); newData = visit(JSON.parse(fileContent), options); } catch (e) { console.error('Failed to retrieve json object from file'); throw e; } let indent; if (options && options.indentSize) { indent = options.indentSize; } else { indent = detectIndent(fileContent).indent || DEFAULT_INDENT_SIZE; } const newLine = detectNewline(fileContent) || '\n'; let newFileContent = JSON.stringify(newData, null, indent); if (!(options && options.noFinalNewLine)) { // Append a new line at EOF newFileContent += '\n'; } if (newLine !== '\n') { newFileContent = newFileContent.replace(/\n/g, newLine); } fs.writeFileSync(path, newFileContent, 'utf8'); return newData; }
javascript
function overwriteFile(path, options) { let fileContent = null; let newData = null; try { fileContent = fs.readFileSync(path, 'utf8'); newData = visit(JSON.parse(fileContent), options); } catch (e) { console.error('Failed to retrieve json object from file'); throw e; } let indent; if (options && options.indentSize) { indent = options.indentSize; } else { indent = detectIndent(fileContent).indent || DEFAULT_INDENT_SIZE; } const newLine = detectNewline(fileContent) || '\n'; let newFileContent = JSON.stringify(newData, null, indent); if (!(options && options.noFinalNewLine)) { // Append a new line at EOF newFileContent += '\n'; } if (newLine !== '\n') { newFileContent = newFileContent.replace(/\n/g, newLine); } fs.writeFileSync(path, newFileContent, 'utf8'); return newData; }
[ "function", "overwriteFile", "(", "path", ",", "options", ")", "{", "let", "fileContent", "=", "null", ";", "let", "newData", "=", "null", ";", "try", "{", "fileContent", "=", "fs", ".", "readFileSync", "(", "path", ",", "'utf8'", ")", ";", "newData", "=", "visit", "(", "JSON", ".", "parse", "(", "fileContent", ")", ",", "options", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "error", "(", "'Failed to retrieve json object from file'", ")", ";", "throw", "e", ";", "}", "let", "indent", ";", "if", "(", "options", "&&", "options", ".", "indentSize", ")", "{", "indent", "=", "options", ".", "indentSize", ";", "}", "else", "{", "indent", "=", "detectIndent", "(", "fileContent", ")", ".", "indent", "||", "DEFAULT_INDENT_SIZE", ";", "}", "const", "newLine", "=", "detectNewline", "(", "fileContent", ")", "||", "'\\n'", ";", "\\n", "let", "newFileContent", "=", "JSON", ".", "stringify", "(", "newData", ",", "null", ",", "indent", ")", ";", "if", "(", "!", "(", "options", "&&", "options", ".", "noFinalNewLine", ")", ")", "{", "newFileContent", "+=", "'\\n'", ";", "}", "\\n", "if", "(", "newLine", "!==", "'\\n'", ")", "\\n", "}" ]
Overwrite file with sorted json @param {String} path - absolutePath @param {Object} [options = {}] - optional params @returns {*}
[ "Overwrite", "file", "with", "sorted", "json" ]
81648138ac8edcf0c1967445e6c6f5cefa434bf4
https://github.com/kesla/sort-json/blob/81648138ac8edcf0c1967445e6c6f5cefa434bf4/app/overwrite.js#L15-L49
train
kesla/sort-json
app/overwrite.js
overwrite
function overwrite(absolutePaths, options) { const paths = Array.isArray(absolutePaths) ? absolutePaths : [absolutePaths]; const results = paths.map(path => overwriteFile(path, options)); return results.length > 1 ? results : results[0]; }
javascript
function overwrite(absolutePaths, options) { const paths = Array.isArray(absolutePaths) ? absolutePaths : [absolutePaths]; const results = paths.map(path => overwriteFile(path, options)); return results.length > 1 ? results : results[0]; }
[ "function", "overwrite", "(", "absolutePaths", ",", "options", ")", "{", "const", "paths", "=", "Array", ".", "isArray", "(", "absolutePaths", ")", "?", "absolutePaths", ":", "[", "absolutePaths", "]", ";", "const", "results", "=", "paths", ".", "map", "(", "path", "=>", "overwriteFile", "(", "path", ",", "options", ")", ")", ";", "return", "results", ".", "length", ">", "1", "?", "results", ":", "results", "[", "0", "]", ";", "}" ]
Sorts the files json with the visit function and then overwrites the file with sorted json @see visit @param {String|Array} absolutePaths - String: Absolute path to json file to sort and overwrite Array: Absolute paths to json files to sort and overwrite @param {Object} [options = {}] - Optional parameters object, see visit for details @returns {*} - Whatever is returned by visit
[ "Sorts", "the", "files", "json", "with", "the", "visit", "function", "and", "then", "overwrites", "the", "file", "with", "sorted", "json" ]
81648138ac8edcf0c1967445e6c6f5cefa434bf4
https://github.com/kesla/sort-json/blob/81648138ac8edcf0c1967445e6c6f5cefa434bf4/app/overwrite.js#L59-L63
train
kesla/sort-json
app/visit.js
visit
function visit(old, options) { const sortOptions = options || {}; const ignoreCase = sortOptions.ignoreCase || false; const reverse = sortOptions.reverse || false; const depth = sortOptions.depth || Infinity; const level = sortOptions.level || 1; const processing = level <= depth; if (typeof (old) !== 'object' || old === null) { return old; } const copy = Array.isArray(old) ? [] : {}; let keys = Object.keys(old); if (processing) { keys = ignoreCase ? keys.sort((left, right) => left.toLowerCase().localeCompare(right.toLowerCase())) : keys.sort(); } if (reverse) { keys = keys.reverse(); } keys.forEach((key) => { const subSortOptions = Object.assign({}, sortOptions); subSortOptions.level = level + 1; copy[key] = visit(old[key], subSortOptions); }); return copy; }
javascript
function visit(old, options) { const sortOptions = options || {}; const ignoreCase = sortOptions.ignoreCase || false; const reverse = sortOptions.reverse || false; const depth = sortOptions.depth || Infinity; const level = sortOptions.level || 1; const processing = level <= depth; if (typeof (old) !== 'object' || old === null) { return old; } const copy = Array.isArray(old) ? [] : {}; let keys = Object.keys(old); if (processing) { keys = ignoreCase ? keys.sort((left, right) => left.toLowerCase().localeCompare(right.toLowerCase())) : keys.sort(); } if (reverse) { keys = keys.reverse(); } keys.forEach((key) => { const subSortOptions = Object.assign({}, sortOptions); subSortOptions.level = level + 1; copy[key] = visit(old[key], subSortOptions); }); return copy; }
[ "function", "visit", "(", "old", ",", "options", ")", "{", "const", "sortOptions", "=", "options", "||", "{", "}", ";", "const", "ignoreCase", "=", "sortOptions", ".", "ignoreCase", "||", "false", ";", "const", "reverse", "=", "sortOptions", ".", "reverse", "||", "false", ";", "const", "depth", "=", "sortOptions", ".", "depth", "||", "Infinity", ";", "const", "level", "=", "sortOptions", ".", "level", "||", "1", ";", "const", "processing", "=", "level", "<=", "depth", ";", "if", "(", "typeof", "(", "old", ")", "!==", "'object'", "||", "old", "===", "null", ")", "{", "return", "old", ";", "}", "const", "copy", "=", "Array", ".", "isArray", "(", "old", ")", "?", "[", "]", ":", "{", "}", ";", "let", "keys", "=", "Object", ".", "keys", "(", "old", ")", ";", "if", "(", "processing", ")", "{", "keys", "=", "ignoreCase", "?", "keys", ".", "sort", "(", "(", "left", ",", "right", ")", "=>", "left", ".", "toLowerCase", "(", ")", ".", "localeCompare", "(", "right", ".", "toLowerCase", "(", ")", ")", ")", ":", "keys", ".", "sort", "(", ")", ";", "}", "if", "(", "reverse", ")", "{", "keys", "=", "keys", ".", "reverse", "(", ")", ";", "}", "keys", ".", "forEach", "(", "(", "key", ")", "=>", "{", "const", "subSortOptions", "=", "Object", ".", "assign", "(", "{", "}", ",", "sortOptions", ")", ";", "subSortOptions", ".", "level", "=", "level", "+", "1", ";", "copy", "[", "key", "]", "=", "visit", "(", "old", "[", "key", "]", ",", "subSortOptions", ")", ";", "}", ")", ";", "return", "copy", ";", "}" ]
Sorts the keys on objects @param {*} old - An object to sort the keys of, if not object just returns whatever was given @param {Object} [sortOptions = {}] - optional parameters @param [options.reverse = false] - When sorting keys, converts all keys to lowercase so that capitalization doesn't interfere with sort order @param [options.ignoreCase = false] - When sorting keys, converts all keys to @param [options.depth = Infinity] - Depth's level sorting keys on a multidimensional object @returns {*} - Object with sorted keys, if old wasn't an object returns whatever was passed
[ "Sorts", "the", "keys", "on", "objects" ]
81648138ac8edcf0c1967445e6c6f5cefa434bf4
https://github.com/kesla/sort-json/blob/81648138ac8edcf0c1967445e6c6f5cefa434bf4/app/visit.js#L14-L46
train
jsreport/jsreport-sample-template
samples/Orders/orders-script/content.js
fetchOrders
function fetchOrders() { return new Promise((resolve, reject) => { https.get('https://services.odata.org/V4/Northwind/Northwind.svc/Orders', (result) => { var str = ''; result.on('data', (b) => str += b); result.on('error', reject); result.on('end', () => resolve(JSON.parse(str).value)); }); }) }
javascript
function fetchOrders() { return new Promise((resolve, reject) => { https.get('https://services.odata.org/V4/Northwind/Northwind.svc/Orders', (result) => { var str = ''; result.on('data', (b) => str += b); result.on('error', reject); result.on('end', () => resolve(JSON.parse(str).value)); }); }) }
[ "function", "fetchOrders", "(", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "https", ".", "get", "(", "'https://services.odata.org/V4/Northwind/Northwind.svc/Orders'", ",", "(", "result", ")", "=>", "{", "var", "str", "=", "''", ";", "result", ".", "on", "(", "'data'", ",", "(", "b", ")", "=>", "str", "+=", "b", ")", ";", "result", ".", "on", "(", "'error'", ",", "reject", ")", ";", "result", ".", "on", "(", "'end'", ",", "(", ")", "=>", "resolve", "(", "JSON", ".", "parse", "(", "str", ")", ".", "value", ")", ")", ";", "}", ")", ";", "}", ")", "}" ]
call remote http rest api
[ "call", "remote", "http", "rest", "api" ]
54973fcd2cbbb69549015c324a3bea615612e4a3
https://github.com/jsreport/jsreport-sample-template/blob/54973fcd2cbbb69549015c324a3bea615612e4a3/samples/Orders/orders-script/content.js#L5-L15
train
jsreport/jsreport-sample-template
samples/Orders/orders-script/content.js
prepareDataSource
async function prepareDataSource() { const orders = await fetchOrders() const ordersByShipCountry = orders.reduce((a, v) => { a[v.ShipCountry] = a[v.ShipCountry] || [] a[v.ShipCountry].push(v) return a }, {}) return Object.keys(ordersByShipCountry).map((country) => { const ordersInCountry = ordersByShipCountry[country] const accumulated = {} ordersInCountry.forEach((o) => { o.OrderDate = new Date(o.OrderDate); const key = o.OrderDate.getFullYear() + '/' + (o.OrderDate.getMonth() + 1); accumulated[key] = accumulated[key] || { value: 0, orderDate: o.OrderDate }; accumulated[key].value++; }); return { rows: ordersInCountry, country, accumulated } }).slice(0, 2) }
javascript
async function prepareDataSource() { const orders = await fetchOrders() const ordersByShipCountry = orders.reduce((a, v) => { a[v.ShipCountry] = a[v.ShipCountry] || [] a[v.ShipCountry].push(v) return a }, {}) return Object.keys(ordersByShipCountry).map((country) => { const ordersInCountry = ordersByShipCountry[country] const accumulated = {} ordersInCountry.forEach((o) => { o.OrderDate = new Date(o.OrderDate); const key = o.OrderDate.getFullYear() + '/' + (o.OrderDate.getMonth() + 1); accumulated[key] = accumulated[key] || { value: 0, orderDate: o.OrderDate }; accumulated[key].value++; }); return { rows: ordersInCountry, country, accumulated } }).slice(0, 2) }
[ "async", "function", "prepareDataSource", "(", ")", "{", "const", "orders", "=", "await", "fetchOrders", "(", ")", "const", "ordersByShipCountry", "=", "orders", ".", "reduce", "(", "(", "a", ",", "v", ")", "=>", "{", "a", "[", "v", ".", "ShipCountry", "]", "=", "a", "[", "v", ".", "ShipCountry", "]", "||", "[", "]", "a", "[", "v", ".", "ShipCountry", "]", ".", "push", "(", "v", ")", "return", "a", "}", ",", "{", "}", ")", "return", "Object", ".", "keys", "(", "ordersByShipCountry", ")", ".", "map", "(", "(", "country", ")", "=>", "{", "const", "ordersInCountry", "=", "ordersByShipCountry", "[", "country", "]", "const", "accumulated", "=", "{", "}", "ordersInCountry", ".", "forEach", "(", "(", "o", ")", "=>", "{", "o", ".", "OrderDate", "=", "new", "Date", "(", "o", ".", "OrderDate", ")", ";", "const", "key", "=", "o", ".", "OrderDate", ".", "getFullYear", "(", ")", "+", "'/'", "+", "(", "o", ".", "OrderDate", ".", "getMonth", "(", ")", "+", "1", ")", ";", "accumulated", "[", "key", "]", "=", "accumulated", "[", "key", "]", "||", "{", "value", ":", "0", ",", "orderDate", ":", "o", ".", "OrderDate", "}", ";", "accumulated", "[", "key", "]", ".", "value", "++", ";", "}", ")", ";", "return", "{", "rows", ":", "ordersInCountry", ",", "country", ",", "accumulated", "}", "}", ")", ".", "slice", "(", "0", ",", "2", ")", "}" ]
group the data for report
[ "group", "the", "data", "for", "report" ]
54973fcd2cbbb69549015c324a3bea615612e4a3
https://github.com/jsreport/jsreport-sample-template/blob/54973fcd2cbbb69549015c324a3bea615612e4a3/samples/Orders/orders-script/content.js#L18-L48
train
dhershman1/tap-junit
src/serialize.js
buildFailureParams
function buildFailureParams (test) { const opts = test.error.operator ? { type: test.error.operator, message: test.raw } : { message: test.raw } if (test.error.raw && test.error.stack) { return [ opts, ` --- ${test.error.raw} ${test.error.stack} --- ` ] } return [opts] }
javascript
function buildFailureParams (test) { const opts = test.error.operator ? { type: test.error.operator, message: test.raw } : { message: test.raw } if (test.error.raw && test.error.stack) { return [ opts, ` --- ${test.error.raw} ${test.error.stack} --- ` ] } return [opts] }
[ "function", "buildFailureParams", "(", "test", ")", "{", "const", "opts", "=", "test", ".", "error", ".", "operator", "?", "{", "type", ":", "test", ".", "error", ".", "operator", ",", "message", ":", "test", ".", "raw", "}", ":", "{", "message", ":", "test", ".", "raw", "}", "if", "(", "test", ".", "error", ".", "raw", "&&", "test", ".", "error", ".", "stack", ")", "{", "return", "[", "opts", ",", "`", "${", "test", ".", "error", ".", "raw", "}", "${", "test", ".", "error", ".", "stack", "}", "`", "]", "}", "return", "[", "opts", "]", "}" ]
Gathers information from the test object to build out the proper arguments for creating the failure element @function @private @param {Object} test The primary test results object @returns {Array} An array with the proper arguments to use
[ "Gathers", "information", "from", "the", "test", "object", "to", "build", "out", "the", "proper", "arguments", "for", "creating", "the", "failure", "element" ]
07efbf9125f1bfe69e70208ac149abc1fd3625b2
https://github.com/dhershman1/tap-junit/blob/07efbf9125f1bfe69e70208ac149abc1fd3625b2/src/serialize.js#L11-L29
train
reg-viz/x-img-diff-js
demo/wasm-util.js
fetchAndInstantiate
function fetchAndInstantiate(url, importObject) { return fetch(url).then(response => response.arrayBuffer() ).then(bytes => WebAssembly.instantiate(bytes, importObject) ).then(results => results.instance ); }
javascript
function fetchAndInstantiate(url, importObject) { return fetch(url).then(response => response.arrayBuffer() ).then(bytes => WebAssembly.instantiate(bytes, importObject) ).then(results => results.instance ); }
[ "function", "fetchAndInstantiate", "(", "url", ",", "importObject", ")", "{", "return", "fetch", "(", "url", ")", ".", "then", "(", "response", "=>", "response", ".", "arrayBuffer", "(", ")", ")", ".", "then", "(", "bytes", "=>", "WebAssembly", ".", "instantiate", "(", "bytes", ",", "importObject", ")", ")", ".", "then", "(", "results", "=>", "results", ".", "instance", ")", ";", "}" ]
This library function fetches the wasm module at 'url', instantiates it with the given 'importObject', and returns the instantiated object instance
[ "This", "library", "function", "fetches", "the", "wasm", "module", "at", "url", "instantiates", "it", "with", "the", "given", "importObject", "and", "returns", "the", "instantiated", "object", "instance" ]
e46c52beaae58fb5fcbe4ee95c89f2c070c3f1f9
https://github.com/reg-viz/x-img-diff-js/blob/e46c52beaae58fb5fcbe4ee95c89f2c070c3f1f9/demo/wasm-util.js#L6-L14
train
reg-viz/x-img-diff-js
demo/wasm-util.js
openDatabase
function openDatabase() { return new Promise((resolve, reject) => { var request = indexedDB.open(dbName, dbVersion); request.onerror = reject.bind(null, 'Error opening wasm cache database'); request.onsuccess = () => { resolve(request.result) }; request.onupgradeneeded = event => { var db = request.result; if (db.objectStoreNames.contains(storeName)) { console.log(`Clearing out version ${event.oldVersion} wasm cache`); db.deleteObjectStore(storeName); } console.log(`Creating version ${event.newVersion} wasm cache`); db.createObjectStore(storeName) }; }); }
javascript
function openDatabase() { return new Promise((resolve, reject) => { var request = indexedDB.open(dbName, dbVersion); request.onerror = reject.bind(null, 'Error opening wasm cache database'); request.onsuccess = () => { resolve(request.result) }; request.onupgradeneeded = event => { var db = request.result; if (db.objectStoreNames.contains(storeName)) { console.log(`Clearing out version ${event.oldVersion} wasm cache`); db.deleteObjectStore(storeName); } console.log(`Creating version ${event.newVersion} wasm cache`); db.createObjectStore(storeName) }; }); }
[ "function", "openDatabase", "(", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "var", "request", "=", "indexedDB", ".", "open", "(", "dbName", ",", "dbVersion", ")", ";", "request", ".", "onerror", "=", "reject", ".", "bind", "(", "null", ",", "'Error opening wasm cache database'", ")", ";", "request", ".", "onsuccess", "=", "(", ")", "=>", "{", "resolve", "(", "request", ".", "result", ")", "}", ";", "request", ".", "onupgradeneeded", "=", "event", "=>", "{", "var", "db", "=", "request", ".", "result", ";", "if", "(", "db", ".", "objectStoreNames", ".", "contains", "(", "storeName", ")", ")", "{", "console", ".", "log", "(", "`", "${", "event", ".", "oldVersion", "}", "`", ")", ";", "db", ".", "deleteObjectStore", "(", "storeName", ")", ";", "}", "console", ".", "log", "(", "`", "${", "event", ".", "newVersion", "}", "`", ")", ";", "db", ".", "createObjectStore", "(", "storeName", ")", "}", ";", "}", ")", ";", "}" ]
This helper function Promise-ifies the operation of opening an IndexedDB database and clearing out the cache when the version changes.
[ "This", "helper", "function", "Promise", "-", "ifies", "the", "operation", "of", "opening", "an", "IndexedDB", "database", "and", "clearing", "out", "the", "cache", "when", "the", "version", "changes", "." ]
e46c52beaae58fb5fcbe4ee95c89f2c070c3f1f9
https://github.com/reg-viz/x-img-diff-js/blob/e46c52beaae58fb5fcbe4ee95c89f2c070c3f1f9/demo/wasm-util.js#L31-L46
train
reg-viz/x-img-diff-js
demo/wasm-util.js
lookupInDatabase
function lookupInDatabase(db) { return new Promise((resolve, reject) => { var store = db.transaction([storeName]).objectStore(storeName); var request = store.get(url); request.onerror = reject.bind(null, `Error getting wasm module ${url}`); request.onsuccess = event => { if (request.result) resolve(request.result); else reject(`Module ${url} was not found in wasm cache`); } }); }
javascript
function lookupInDatabase(db) { return new Promise((resolve, reject) => { var store = db.transaction([storeName]).objectStore(storeName); var request = store.get(url); request.onerror = reject.bind(null, `Error getting wasm module ${url}`); request.onsuccess = event => { if (request.result) resolve(request.result); else reject(`Module ${url} was not found in wasm cache`); } }); }
[ "function", "lookupInDatabase", "(", "db", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "var", "store", "=", "db", ".", "transaction", "(", "[", "storeName", "]", ")", ".", "objectStore", "(", "storeName", ")", ";", "var", "request", "=", "store", ".", "get", "(", "url", ")", ";", "request", ".", "onerror", "=", "reject", ".", "bind", "(", "null", ",", "`", "${", "url", "}", "`", ")", ";", "request", ".", "onsuccess", "=", "event", "=>", "{", "if", "(", "request", ".", "result", ")", "resolve", "(", "request", ".", "result", ")", ";", "else", "reject", "(", "`", "${", "url", "}", "`", ")", ";", "}", "}", ")", ";", "}" ]
This helper function Promise-ifies the operation of looking up 'url' in the given IDBDatabase.
[ "This", "helper", "function", "Promise", "-", "ifies", "the", "operation", "of", "looking", "up", "url", "in", "the", "given", "IDBDatabase", "." ]
e46c52beaae58fb5fcbe4ee95c89f2c070c3f1f9
https://github.com/reg-viz/x-img-diff-js/blob/e46c52beaae58fb5fcbe4ee95c89f2c070c3f1f9/demo/wasm-util.js#L50-L62
train
reg-viz/x-img-diff-js
demo/wasm-util.js
storeInDatabase
function storeInDatabase(db, module) { var store = db.transaction([storeName], 'readwrite').objectStore(storeName); try { var request = store.put(module, url); request.onerror = err => { console.log(`Failed to store in wasm cache: ${err}`) }; request.onsuccess = err => { console.log(`Successfully stored ${url} in wasm cache`) }; } catch (e) { console.warn('An error was thrown... in storing wasm cache...'); console.warn(e); } }
javascript
function storeInDatabase(db, module) { var store = db.transaction([storeName], 'readwrite').objectStore(storeName); try { var request = store.put(module, url); request.onerror = err => { console.log(`Failed to store in wasm cache: ${err}`) }; request.onsuccess = err => { console.log(`Successfully stored ${url} in wasm cache`) }; } catch (e) { console.warn('An error was thrown... in storing wasm cache...'); console.warn(e); } }
[ "function", "storeInDatabase", "(", "db", ",", "module", ")", "{", "var", "store", "=", "db", ".", "transaction", "(", "[", "storeName", "]", ",", "'readwrite'", ")", ".", "objectStore", "(", "storeName", ")", ";", "try", "{", "var", "request", "=", "store", ".", "put", "(", "module", ",", "url", ")", ";", "request", ".", "onerror", "=", "err", "=>", "{", "console", ".", "log", "(", "`", "${", "err", "}", "`", ")", "}", ";", "request", ".", "onsuccess", "=", "err", "=>", "{", "console", ".", "log", "(", "`", "${", "url", "}", "`", ")", "}", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "warn", "(", "'An error was thrown... in storing wasm cache...'", ")", ";", "console", ".", "warn", "(", "e", ")", ";", "}", "}" ]
This helper function fires off an async operation to store the given wasm Module in the given IDBDatabase.
[ "This", "helper", "function", "fires", "off", "an", "async", "operation", "to", "store", "the", "given", "wasm", "Module", "in", "the", "given", "IDBDatabase", "." ]
e46c52beaae58fb5fcbe4ee95c89f2c070c3f1f9
https://github.com/reg-viz/x-img-diff-js/blob/e46c52beaae58fb5fcbe4ee95c89f2c070c3f1f9/demo/wasm-util.js#L66-L76
train
reg-viz/x-img-diff-js
demo/wasm-util.js
fetchAndInstantiate
function fetchAndInstantiate() { return fetch(url).then(response => response.arrayBuffer() ).then(buffer => WebAssembly.instantiate(buffer, importObject) ) }
javascript
function fetchAndInstantiate() { return fetch(url).then(response => response.arrayBuffer() ).then(buffer => WebAssembly.instantiate(buffer, importObject) ) }
[ "function", "fetchAndInstantiate", "(", ")", "{", "return", "fetch", "(", "url", ")", ".", "then", "(", "response", "=>", "response", ".", "arrayBuffer", "(", ")", ")", ".", "then", "(", "buffer", "=>", "WebAssembly", ".", "instantiate", "(", "buffer", ",", "importObject", ")", ")", "}" ]
This helper function fetches 'url', compiles it into a Module, instantiates the Module with the given import object.
[ "This", "helper", "function", "fetches", "url", "compiles", "it", "into", "a", "Module", "instantiates", "the", "Module", "with", "the", "given", "import", "object", "." ]
e46c52beaae58fb5fcbe4ee95c89f2c070c3f1f9
https://github.com/reg-viz/x-img-diff-js/blob/e46c52beaae58fb5fcbe4ee95c89f2c070c3f1f9/demo/wasm-util.js#L80-L86
train
aheckmann/mpromise
lib/promise.js
Promise
function Promise(back) { this.emitter = new EventEmitter(); this.emitted = {}; this.ended = false; if ('function' == typeof back) this.onResolve(back); }
javascript
function Promise(back) { this.emitter = new EventEmitter(); this.emitted = {}; this.ended = false; if ('function' == typeof back) this.onResolve(back); }
[ "function", "Promise", "(", "back", ")", "{", "this", ".", "emitter", "=", "new", "EventEmitter", "(", ")", ";", "this", ".", "emitted", "=", "{", "}", ";", "this", ".", "ended", "=", "false", ";", "if", "(", "'function'", "==", "typeof", "back", ")", "this", ".", "onResolve", "(", "back", ")", ";", "}" ]
Promise constructor. _NOTE: The success and failure event names can be overridden by setting `Promise.SUCCESS` and `Promise.FAILURE` respectively._ @param {Function} back a function that accepts `fn(err, ...){}` as signature @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter @event `reject`: Emits when the promise is rejected (event name may be overridden) @event `fulfill`: Emits when the promise is fulfilled (event name may be overridden) @api public
[ "Promise", "constructor", "." ]
c6a3e3bc5e9205f699a5388aa88659529cb9b56b
https://github.com/aheckmann/mpromise/blob/c6a3e3bc5e9205f699a5388aa88659529cb9b56b/lib/promise.js#L25-L31
train
mercadolibre/tiny.js
modules/pointerEvents.js
function (root) { var current = root.prototype ? root.prototype.addEventListener : root.addEventListener; var customAddEventListener = function (name, func, capture) { // Branch when a PointerXXX is used if (supportedEventsNames.indexOf(name) !== -1) { setTouchAware(this, name, true); } if (current === undefined) { this.attachEvent('on' + getMouseEquivalentEventName(name), func); } else { current.call(this, name, func, capture); } }; if (root.prototype) { root.prototype.addEventListener = customAddEventListener; } else { root.addEventListener = customAddEventListener; } }
javascript
function (root) { var current = root.prototype ? root.prototype.addEventListener : root.addEventListener; var customAddEventListener = function (name, func, capture) { // Branch when a PointerXXX is used if (supportedEventsNames.indexOf(name) !== -1) { setTouchAware(this, name, true); } if (current === undefined) { this.attachEvent('on' + getMouseEquivalentEventName(name), func); } else { current.call(this, name, func, capture); } }; if (root.prototype) { root.prototype.addEventListener = customAddEventListener; } else { root.addEventListener = customAddEventListener; } }
[ "function", "(", "root", ")", "{", "var", "current", "=", "root", ".", "prototype", "?", "root", ".", "prototype", ".", "addEventListener", ":", "root", ".", "addEventListener", ";", "var", "customAddEventListener", "=", "function", "(", "name", ",", "func", ",", "capture", ")", "{", "if", "(", "supportedEventsNames", ".", "indexOf", "(", "name", ")", "!==", "-", "1", ")", "{", "setTouchAware", "(", "this", ",", "name", ",", "true", ")", ";", "}", "if", "(", "current", "===", "undefined", ")", "{", "this", ".", "attachEvent", "(", "'on'", "+", "getMouseEquivalentEventName", "(", "name", ")", ",", "func", ")", ";", "}", "else", "{", "current", ".", "call", "(", "this", ",", "name", ",", "func", ",", "capture", ")", ";", "}", "}", ";", "if", "(", "root", ".", "prototype", ")", "{", "root", ".", "prototype", ".", "addEventListener", "=", "customAddEventListener", ";", "}", "else", "{", "root", ".", "addEventListener", "=", "customAddEventListener", ";", "}", "}" ]
Intercept addEventListener calls by changing the prototype
[ "Intercept", "addEventListener", "calls", "by", "changing", "the", "prototype" ]
10fad8be21abdbec23642be77ad64f449711a40d
https://github.com/mercadolibre/tiny.js/blob/10fad8be21abdbec23642be77ad64f449711a40d/modules/pointerEvents.js#L320-L341
train
mercadolibre/tiny.js
modules/pointerEvents.js
function (root) { var current = root.prototype ? root.prototype.removeEventListener : root.removeEventListener; var customRemoveEventListener = function (name, func, capture) { // Release when a PointerXXX is used if (supportedEventsNames.indexOf(name) !== -1) { setTouchAware(this, name, false); } if (current === undefined) { this.detachEvent(getMouseEquivalentEventName(name), func); } else { current.call(this, name, func, capture); } }; if (root.prototype) { root.prototype.removeEventListener = customRemoveEventListener; } else { root.removeEventListener = customRemoveEventListener; } }
javascript
function (root) { var current = root.prototype ? root.prototype.removeEventListener : root.removeEventListener; var customRemoveEventListener = function (name, func, capture) { // Release when a PointerXXX is used if (supportedEventsNames.indexOf(name) !== -1) { setTouchAware(this, name, false); } if (current === undefined) { this.detachEvent(getMouseEquivalentEventName(name), func); } else { current.call(this, name, func, capture); } }; if (root.prototype) { root.prototype.removeEventListener = customRemoveEventListener; } else { root.removeEventListener = customRemoveEventListener; } }
[ "function", "(", "root", ")", "{", "var", "current", "=", "root", ".", "prototype", "?", "root", ".", "prototype", ".", "removeEventListener", ":", "root", ".", "removeEventListener", ";", "var", "customRemoveEventListener", "=", "function", "(", "name", ",", "func", ",", "capture", ")", "{", "if", "(", "supportedEventsNames", ".", "indexOf", "(", "name", ")", "!==", "-", "1", ")", "{", "setTouchAware", "(", "this", ",", "name", ",", "false", ")", ";", "}", "if", "(", "current", "===", "undefined", ")", "{", "this", ".", "detachEvent", "(", "getMouseEquivalentEventName", "(", "name", ")", ",", "func", ")", ";", "}", "else", "{", "current", ".", "call", "(", "this", ",", "name", ",", "func", ",", "capture", ")", ";", "}", "}", ";", "if", "(", "root", ".", "prototype", ")", "{", "root", ".", "prototype", ".", "removeEventListener", "=", "customRemoveEventListener", ";", "}", "else", "{", "root", ".", "removeEventListener", "=", "customRemoveEventListener", ";", "}", "}" ]
Intercept removeEventListener calls by changing the prototype
[ "Intercept", "removeEventListener", "calls", "by", "changing", "the", "prototype" ]
10fad8be21abdbec23642be77ad64f449711a40d
https://github.com/mercadolibre/tiny.js/blob/10fad8be21abdbec23642be77ad64f449711a40d/modules/pointerEvents.js#L344-L364
train
mercadolibre/tiny.js
modules/pointerEvents.js
pointerDown
function pointerDown(e) { // don't register an activePointer if more than one touch is active. var singleFinger = e.pointerType === POINTER_TYPE_MOUSE || e.pointerType === POINTER_TYPE_PEN || (e.pointerType === POINTER_TYPE_TOUCH && e.isPrimary); if (!isScrolling && singleFinger) { activePointer = { id: e.pointerId, clientX: e.clientX, clientY: e.clientY, x: (e.x || e.pageX), y: (e.y || e.pageY), type: e.pointerType }; } }
javascript
function pointerDown(e) { // don't register an activePointer if more than one touch is active. var singleFinger = e.pointerType === POINTER_TYPE_MOUSE || e.pointerType === POINTER_TYPE_PEN || (e.pointerType === POINTER_TYPE_TOUCH && e.isPrimary); if (!isScrolling && singleFinger) { activePointer = { id: e.pointerId, clientX: e.clientX, clientY: e.clientY, x: (e.x || e.pageX), y: (e.y || e.pageY), type: e.pointerType }; } }
[ "function", "pointerDown", "(", "e", ")", "{", "var", "singleFinger", "=", "e", ".", "pointerType", "===", "POINTER_TYPE_MOUSE", "||", "e", ".", "pointerType", "===", "POINTER_TYPE_PEN", "||", "(", "e", ".", "pointerType", "===", "POINTER_TYPE_TOUCH", "&&", "e", ".", "isPrimary", ")", ";", "if", "(", "!", "isScrolling", "&&", "singleFinger", ")", "{", "activePointer", "=", "{", "id", ":", "e", ".", "pointerId", ",", "clientX", ":", "e", ".", "clientX", ",", "clientY", ":", "e", ".", "clientY", ",", "x", ":", "(", "e", ".", "x", "||", "e", ".", "pageX", ")", ",", "y", ":", "(", "e", ".", "y", "||", "e", ".", "pageY", ")", ",", "type", ":", "e", ".", "pointerType", "}", ";", "}", "}" ]
Handles the 'pointerdown' event from pointerEvents polyfill or native PointerEvents when supported. @private @param {MouseEvent|PointerEvent} e Event.
[ "Handles", "the", "pointerdown", "event", "from", "pointerEvents", "polyfill", "or", "native", "PointerEvents", "when", "supported", "." ]
10fad8be21abdbec23642be77ad64f449711a40d
https://github.com/mercadolibre/tiny.js/blob/10fad8be21abdbec23642be77ad64f449711a40d/modules/pointerEvents.js#L681-L697
train
mercadolibre/tiny.js
modules/pointerEvents.js
pointerUp
function pointerUp(e) { // Does our event is the same as the activePointer set by pointerdown? if (activePointer && activePointer.id === e.pointerId) { // Have we moved too much? if (Math.abs(activePointer.x - (e.x || e.pageX)) < 5 && Math.abs(activePointer.y - (e.y || e.pageY)) < 5) { // Have we scrolled too much? if (!isScrolling || (Math.abs(sDistX - window.pageXOffset) < 5 && Math.abs(sDistY - window.pageYOffset) < 5)) { makePointertapEvent(e); } } } activePointer = null; }
javascript
function pointerUp(e) { // Does our event is the same as the activePointer set by pointerdown? if (activePointer && activePointer.id === e.pointerId) { // Have we moved too much? if (Math.abs(activePointer.x - (e.x || e.pageX)) < 5 && Math.abs(activePointer.y - (e.y || e.pageY)) < 5) { // Have we scrolled too much? if (!isScrolling || (Math.abs(sDistX - window.pageXOffset) < 5 && Math.abs(sDistY - window.pageYOffset) < 5)) { makePointertapEvent(e); } } } activePointer = null; }
[ "function", "pointerUp", "(", "e", ")", "{", "if", "(", "activePointer", "&&", "activePointer", ".", "id", "===", "e", ".", "pointerId", ")", "{", "if", "(", "Math", ".", "abs", "(", "activePointer", ".", "x", "-", "(", "e", ".", "x", "||", "e", ".", "pageX", ")", ")", "<", "5", "&&", "Math", ".", "abs", "(", "activePointer", ".", "y", "-", "(", "e", ".", "y", "||", "e", ".", "pageY", ")", ")", "<", "5", ")", "{", "if", "(", "!", "isScrolling", "||", "(", "Math", ".", "abs", "(", "sDistX", "-", "window", ".", "pageXOffset", ")", "<", "5", "&&", "Math", ".", "abs", "(", "sDistY", "-", "window", ".", "pageYOffset", ")", "<", "5", ")", ")", "{", "makePointertapEvent", "(", "e", ")", ";", "}", "}", "}", "activePointer", "=", "null", ";", "}" ]
Handles the 'pointerup' event from pointerEvents polyfill or native PointerEvents when supported. @private @param {MouseEvent|PointerEvent} e Event.
[ "Handles", "the", "pointerup", "event", "from", "pointerEvents", "polyfill", "or", "native", "PointerEvents", "when", "supported", "." ]
10fad8be21abdbec23642be77ad64f449711a40d
https://github.com/mercadolibre/tiny.js/blob/10fad8be21abdbec23642be77ad64f449711a40d/modules/pointerEvents.js#L715-L730
train
mercadolibre/tiny.js
modules/pointerEvents.js
makePointertapEvent
function makePointertapEvent(sourceEvent) { var evt = document.createEvent('MouseEvents'); var newTarget = document.elementFromPoint(sourceEvent.clientX, sourceEvent.clientY); // According to the MDN docs if the specified point is outside the visible bounds of the document // or either coordinate is negative, the result is null if (!newTarget) { return null; } // TODO: Replace 'initMouseEvent' with 'new MouseEvent' evt.initMouseEvent('pointertap', true, true, window, 1, sourceEvent.screenX, sourceEvent.screenY, sourceEvent.clientX, sourceEvent.clientY, sourceEvent.ctrlKey, sourceEvent.altKey, sourceEvent.shiftKey, sourceEvent.metaKey, sourceEvent.button, newTarget); evt.maskedEvent = sourceEvent; newTarget.dispatchEvent(evt); return evt; }
javascript
function makePointertapEvent(sourceEvent) { var evt = document.createEvent('MouseEvents'); var newTarget = document.elementFromPoint(sourceEvent.clientX, sourceEvent.clientY); // According to the MDN docs if the specified point is outside the visible bounds of the document // or either coordinate is negative, the result is null if (!newTarget) { return null; } // TODO: Replace 'initMouseEvent' with 'new MouseEvent' evt.initMouseEvent('pointertap', true, true, window, 1, sourceEvent.screenX, sourceEvent.screenY, sourceEvent.clientX, sourceEvent.clientY, sourceEvent.ctrlKey, sourceEvent.altKey, sourceEvent.shiftKey, sourceEvent.metaKey, sourceEvent.button, newTarget); evt.maskedEvent = sourceEvent; newTarget.dispatchEvent(evt); return evt; }
[ "function", "makePointertapEvent", "(", "sourceEvent", ")", "{", "var", "evt", "=", "document", ".", "createEvent", "(", "'MouseEvents'", ")", ";", "var", "newTarget", "=", "document", ".", "elementFromPoint", "(", "sourceEvent", ".", "clientX", ",", "sourceEvent", ".", "clientY", ")", ";", "if", "(", "!", "newTarget", ")", "{", "return", "null", ";", "}", "evt", ".", "initMouseEvent", "(", "'pointertap'", ",", "true", ",", "true", ",", "window", ",", "1", ",", "sourceEvent", ".", "screenX", ",", "sourceEvent", ".", "screenY", ",", "sourceEvent", ".", "clientX", ",", "sourceEvent", ".", "clientY", ",", "sourceEvent", ".", "ctrlKey", ",", "sourceEvent", ".", "altKey", ",", "sourceEvent", ".", "shiftKey", ",", "sourceEvent", ".", "metaKey", ",", "sourceEvent", ".", "button", ",", "newTarget", ")", ";", "evt", ".", "maskedEvent", "=", "sourceEvent", ";", "newTarget", ".", "dispatchEvent", "(", "evt", ")", ";", "return", "evt", ";", "}" ]
Creates the pointertap event that is not part of standard. @private @param {MouseEvent|PointerEvent} sourceEvent An event to use as a base for pointertap.
[ "Creates", "the", "pointertap", "event", "that", "is", "not", "part", "of", "standard", "." ]
10fad8be21abdbec23642be77ad64f449711a40d
https://github.com/mercadolibre/tiny.js/blob/10fad8be21abdbec23642be77ad64f449711a40d/modules/pointerEvents.js#L738-L757
train
apparatus/Kafkaesque
lib/kafkaesque.js
function() { _cbt = require('./cbt')(); _options = options || {}; // apply defaults // the min bytes of an incoming reply _options.minBytes = _options.minBytes || 1; // the max bytes of an incoming reply _options.maxBytes = _options.maxBytes || 1024 * 1024; // the group the client will join when using `.connect()` _options.group = _options.group || 'kafkaesqueGroup'; // the clientID when connecting to kafka _options.clientId = _options.clientId || 'kafkaesque' + Math.floor(Math.random() * 100000000); // the array of brokers _options.brokers = _options.brokers || [{host: 'localhost', port: 9092}]; // the amount of time it should take for this clients session within the group // to timeout _options.sessionTimeout = _options.sessionTimeout || 6000; // the amount of time to take to emit a heartbeat msg _options.heartbeat = _options.heartbeat || 2500; // the default amount of time that the kafka broker shoudl wait to send // a reply to a fetch request if the fetch reply is smaller than the minBytes _options.maxWait = _options.maxWait || 5000; _brokers = {}; _topics = {}; _groupMemberId = ''; _groupGeneration = 0; _.each(_options.brokers, function(broker) { broker = { host: broker.host, port: broker.port, maxBytes: _options.maxBytes, minBytes: _options.minBytes, clientId: _options.clientId }; _brokers[_makeBrokerKey(broker)] = api(broker); }); _metaBroker = _brokers[_makeBrokerKey(_options.brokers[0])]; }
javascript
function() { _cbt = require('./cbt')(); _options = options || {}; // apply defaults // the min bytes of an incoming reply _options.minBytes = _options.minBytes || 1; // the max bytes of an incoming reply _options.maxBytes = _options.maxBytes || 1024 * 1024; // the group the client will join when using `.connect()` _options.group = _options.group || 'kafkaesqueGroup'; // the clientID when connecting to kafka _options.clientId = _options.clientId || 'kafkaesque' + Math.floor(Math.random() * 100000000); // the array of brokers _options.brokers = _options.brokers || [{host: 'localhost', port: 9092}]; // the amount of time it should take for this clients session within the group // to timeout _options.sessionTimeout = _options.sessionTimeout || 6000; // the amount of time to take to emit a heartbeat msg _options.heartbeat = _options.heartbeat || 2500; // the default amount of time that the kafka broker shoudl wait to send // a reply to a fetch request if the fetch reply is smaller than the minBytes _options.maxWait = _options.maxWait || 5000; _brokers = {}; _topics = {}; _groupMemberId = ''; _groupGeneration = 0; _.each(_options.brokers, function(broker) { broker = { host: broker.host, port: broker.port, maxBytes: _options.maxBytes, minBytes: _options.minBytes, clientId: _options.clientId }; _brokers[_makeBrokerKey(broker)] = api(broker); }); _metaBroker = _brokers[_makeBrokerKey(_options.brokers[0])]; }
[ "function", "(", ")", "{", "_cbt", "=", "require", "(", "'./cbt'", ")", "(", ")", ";", "_options", "=", "options", "||", "{", "}", ";", "_options", ".", "minBytes", "=", "_options", ".", "minBytes", "||", "1", ";", "_options", ".", "maxBytes", "=", "_options", ".", "maxBytes", "||", "1024", "*", "1024", ";", "_options", ".", "group", "=", "_options", ".", "group", "||", "'kafkaesqueGroup'", ";", "_options", ".", "clientId", "=", "_options", ".", "clientId", "||", "'kafkaesque'", "+", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "100000000", ")", ";", "_options", ".", "brokers", "=", "_options", ".", "brokers", "||", "[", "{", "host", ":", "'localhost'", ",", "port", ":", "9092", "}", "]", ";", "_options", ".", "sessionTimeout", "=", "_options", ".", "sessionTimeout", "||", "6000", ";", "_options", ".", "heartbeat", "=", "_options", ".", "heartbeat", "||", "2500", ";", "_options", ".", "maxWait", "=", "_options", ".", "maxWait", "||", "5000", ";", "_brokers", "=", "{", "}", ";", "_topics", "=", "{", "}", ";", "_groupMemberId", "=", "''", ";", "_groupGeneration", "=", "0", ";", "_", ".", "each", "(", "_options", ".", "brokers", ",", "function", "(", "broker", ")", "{", "broker", "=", "{", "host", ":", "broker", ".", "host", ",", "port", ":", "broker", ".", "port", ",", "maxBytes", ":", "_options", ".", "maxBytes", ",", "minBytes", ":", "_options", ".", "minBytes", ",", "clientId", ":", "_options", ".", "clientId", "}", ";", "_brokers", "[", "_makeBrokerKey", "(", "broker", ")", "]", "=", "api", "(", "broker", ")", ";", "}", ")", ";", "_metaBroker", "=", "_brokers", "[", "_makeBrokerKey", "(", "_options", ".", "brokers", "[", "0", "]", ")", "]", ";", "}" ]
construct the kafka clients
[ "construct", "the", "kafka", "clients" ]
fa9a63f1f711e86bfc776d58ea44d91a8fb4a50b
https://github.com/apparatus/Kafkaesque/blob/fa9a63f1f711e86bfc776d58ea44d91a8fb4a50b/lib/kafkaesque.js#L310-L358
train
apparatus/Kafkaesque
lib/kafkaesque.js
function (cb) { _metaBroker.tearUp(function (err) { if (!err) { _metaBroker.connected = true; } cb(err); }); }
javascript
function (cb) { _metaBroker.tearUp(function (err) { if (!err) { _metaBroker.connected = true; } cb(err); }); }
[ "function", "(", "cb", ")", "{", "_metaBroker", ".", "tearUp", "(", "function", "(", "err", ")", "{", "if", "(", "!", "err", ")", "{", "_metaBroker", ".", "connected", "=", "true", ";", "}", "cb", "(", "err", ")", ";", "}", ")", ";", "}" ]
connect this kafkaesque instance to the meta broker
[ "connect", "this", "kafkaesque", "instance", "to", "the", "meta", "broker" ]
fa9a63f1f711e86bfc776d58ea44d91a8fb4a50b
https://github.com/apparatus/Kafkaesque/blob/fa9a63f1f711e86bfc776d58ea44d91a8fb4a50b/lib/kafkaesque.js#L406-L413
train
apparatus/Kafkaesque
lib/kafkaesque.js
function(params, cb) { cb = cb || _noop; assert(params.topic); _metaBroker.metadata([params.topic], function(err, cluster) { cluster.topics.forEach(function(topic) { _partitions[topic.topicName] = topic.partitions; }); cb(err, cluster); }); }
javascript
function(params, cb) { cb = cb || _noop; assert(params.topic); _metaBroker.metadata([params.topic], function(err, cluster) { cluster.topics.forEach(function(topic) { _partitions[topic.topicName] = topic.partitions; }); cb(err, cluster); }); }
[ "function", "(", "params", ",", "cb", ")", "{", "cb", "=", "cb", "||", "_noop", ";", "assert", "(", "params", ".", "topic", ")", ";", "_metaBroker", ".", "metadata", "(", "[", "params", ".", "topic", "]", ",", "function", "(", "err", ",", "cluster", ")", "{", "cluster", ".", "topics", ".", "forEach", "(", "function", "(", "topic", ")", "{", "_partitions", "[", "topic", ".", "topicName", "]", "=", "topic", ".", "partitions", ";", "}", ")", ";", "cb", "(", "err", ",", "cluster", ")", ";", "}", ")", ";", "}" ]
make a metadata request to the kafka cluster params: topic - the topic name, required
[ "make", "a", "metadata", "request", "to", "the", "kafka", "cluster" ]
fa9a63f1f711e86bfc776d58ea44d91a8fb4a50b
https://github.com/apparatus/Kafkaesque/blob/fa9a63f1f711e86bfc776d58ea44d91a8fb4a50b/lib/kafkaesque.js#L495-L506
train
apparatus/Kafkaesque
lib/kafkaesque.js
function() { if (_polling) { _closing = true; setTimeout(function() { if( _closing) { _.each(_brokers, function(broker) { broker.tearDown(); }); } }, _options.maxWait); } else { _.each(_brokers, function(broker) { broker.tearDown(); }); } }
javascript
function() { if (_polling) { _closing = true; setTimeout(function() { if( _closing) { _.each(_brokers, function(broker) { broker.tearDown(); }); } }, _options.maxWait); } else { _.each(_brokers, function(broker) { broker.tearDown(); }); } }
[ "function", "(", ")", "{", "if", "(", "_polling", ")", "{", "_closing", "=", "true", ";", "setTimeout", "(", "function", "(", ")", "{", "if", "(", "_closing", ")", "{", "_", ".", "each", "(", "_brokers", ",", "function", "(", "broker", ")", "{", "broker", ".", "tearDown", "(", ")", ";", "}", ")", ";", "}", "}", ",", "_options", ".", "maxWait", ")", ";", "}", "else", "{", "_", ".", "each", "(", "_brokers", ",", "function", "(", "broker", ")", "{", "broker", ".", "tearDown", "(", ")", ";", "}", ")", ";", "}", "}" ]
end all polls and teardown all connections to kafka
[ "end", "all", "polls", "and", "teardown", "all", "connections", "to", "kafka" ]
fa9a63f1f711e86bfc776d58ea44d91a8fb4a50b
https://github.com/apparatus/Kafkaesque/blob/fa9a63f1f711e86bfc776d58ea44d91a8fb4a50b/lib/kafkaesque.js#L771-L787
train
mercadolibre/tiny.js
modules/cookies.js
set
function set(key, value, options) { options = typeof options ==='object' ? options : { expires: options }; let expires = options.expires != null ? options.expires : defaults.expires; if (typeof expires === 'string' && expires !== '') { expires = new Date(expires); } else if (typeof expires === 'number') { expires = new Date(+new Date + (1000 * day * expires)); } if (expires && 'toGMTString' in expires) { expires = ';expires=' + expires.toGMTString(); } let path = ';path=' + (options.path || defaults.path); let domain = options.domain || defaults.domain; domain = domain ? ';domain=' + domain : ''; let secure = options.secure || defaults.secure ? ';secure' : ''; if (typeof value == 'object') { if (Array.isArray(value) || isPlainObject(value)) { value = JSON.stringify(value); } else { value = ''; } } document.cookie = encodeCookie(key) + '=' + encodeCookie(value) + expires + path + domain + secure; }
javascript
function set(key, value, options) { options = typeof options ==='object' ? options : { expires: options }; let expires = options.expires != null ? options.expires : defaults.expires; if (typeof expires === 'string' && expires !== '') { expires = new Date(expires); } else if (typeof expires === 'number') { expires = new Date(+new Date + (1000 * day * expires)); } if (expires && 'toGMTString' in expires) { expires = ';expires=' + expires.toGMTString(); } let path = ';path=' + (options.path || defaults.path); let domain = options.domain || defaults.domain; domain = domain ? ';domain=' + domain : ''; let secure = options.secure || defaults.secure ? ';secure' : ''; if (typeof value == 'object') { if (Array.isArray(value) || isPlainObject(value)) { value = JSON.stringify(value); } else { value = ''; } } document.cookie = encodeCookie(key) + '=' + encodeCookie(value) + expires + path + domain + secure; }
[ "function", "set", "(", "key", ",", "value", ",", "options", ")", "{", "options", "=", "typeof", "options", "===", "'object'", "?", "options", ":", "{", "expires", ":", "options", "}", ";", "let", "expires", "=", "options", ".", "expires", "!=", "null", "?", "options", ".", "expires", ":", "defaults", ".", "expires", ";", "if", "(", "typeof", "expires", "===", "'string'", "&&", "expires", "!==", "''", ")", "{", "expires", "=", "new", "Date", "(", "expires", ")", ";", "}", "else", "if", "(", "typeof", "expires", "===", "'number'", ")", "{", "expires", "=", "new", "Date", "(", "+", "new", "Date", "+", "(", "1000", "*", "day", "*", "expires", ")", ")", ";", "}", "if", "(", "expires", "&&", "'toGMTString'", "in", "expires", ")", "{", "expires", "=", "';expires='", "+", "expires", ".", "toGMTString", "(", ")", ";", "}", "let", "path", "=", "';path='", "+", "(", "options", ".", "path", "||", "defaults", ".", "path", ")", ";", "let", "domain", "=", "options", ".", "domain", "||", "defaults", ".", "domain", ";", "domain", "=", "domain", "?", "';domain='", "+", "domain", ":", "''", ";", "let", "secure", "=", "options", ".", "secure", "||", "defaults", ".", "secure", "?", "';secure'", ":", "''", ";", "if", "(", "typeof", "value", "==", "'object'", ")", "{", "if", "(", "Array", ".", "isArray", "(", "value", ")", "||", "isPlainObject", "(", "value", ")", ")", "{", "value", "=", "JSON", ".", "stringify", "(", "value", ")", ";", "}", "else", "{", "value", "=", "''", ";", "}", "}", "document", ".", "cookie", "=", "encodeCookie", "(", "key", ")", "+", "'='", "+", "encodeCookie", "(", "value", ")", "+", "expires", "+", "path", "+", "domain", "+", "secure", ";", "}" ]
Then `key` contains an object with keys and values for cookies, `value` contains the options object.
[ "Then", "key", "contains", "an", "object", "with", "keys", "and", "values", "for", "cookies", "value", "contains", "the", "options", "object", "." ]
10fad8be21abdbec23642be77ad64f449711a40d
https://github.com/mercadolibre/tiny.js/blob/10fad8be21abdbec23642be77ad64f449711a40d/modules/cookies.js#L35-L66
train
apparatus/Kafkaesque
lib/api.js
function(topics, cb) { var correlationId = _cbt.put(metaResponse(cb)); var msg = envelope(meta.encode() .correlation(correlationId) .client(_options.clientId) .topics(topics) .end()); sendMsg(msg, correlationId, cb); }
javascript
function(topics, cb) { var correlationId = _cbt.put(metaResponse(cb)); var msg = envelope(meta.encode() .correlation(correlationId) .client(_options.clientId) .topics(topics) .end()); sendMsg(msg, correlationId, cb); }
[ "function", "(", "topics", ",", "cb", ")", "{", "var", "correlationId", "=", "_cbt", ".", "put", "(", "metaResponse", "(", "cb", ")", ")", ";", "var", "msg", "=", "envelope", "(", "meta", ".", "encode", "(", ")", ".", "correlation", "(", "correlationId", ")", ".", "client", "(", "_options", ".", "clientId", ")", ".", "topics", "(", "topics", ")", ".", "end", "(", ")", ")", ";", "sendMsg", "(", "msg", ",", "correlationId", ",", "cb", ")", ";", "}" ]
write a metadata request to kafka, storing the callback. topics: array of topics to retreive information on cb: callback
[ "write", "a", "metadata", "request", "to", "kafka", "storing", "the", "callback", "." ]
fa9a63f1f711e86bfc776d58ea44d91a8fb4a50b
https://github.com/apparatus/Kafkaesque/blob/fa9a63f1f711e86bfc776d58ea44d91a8fb4a50b/lib/api.js#L81-L89
train
apparatus/Kafkaesque
lib/api.js
function(params, messages, cb) { var correlationId = _cbt.put(prodResponse(cb)); var msg = envelope(prod.encode() .correlation(correlationId) .client(_options.clientId) .timeout() .topic(params.topic) .partition(params.partition) .messages(messages) .end()); sendMsg(msg, correlationId, cb); }
javascript
function(params, messages, cb) { var correlationId = _cbt.put(prodResponse(cb)); var msg = envelope(prod.encode() .correlation(correlationId) .client(_options.clientId) .timeout() .topic(params.topic) .partition(params.partition) .messages(messages) .end()); sendMsg(msg, correlationId, cb); }
[ "function", "(", "params", ",", "messages", ",", "cb", ")", "{", "var", "correlationId", "=", "_cbt", ".", "put", "(", "prodResponse", "(", "cb", ")", ")", ";", "var", "msg", "=", "envelope", "(", "prod", ".", "encode", "(", ")", ".", "correlation", "(", "correlationId", ")", ".", "client", "(", "_options", ".", "clientId", ")", ".", "timeout", "(", ")", ".", "topic", "(", "params", ".", "topic", ")", ".", "partition", "(", "params", ".", "partition", ")", ".", "messages", "(", "messages", ")", ".", "end", "(", ")", ")", ";", "sendMsg", "(", "msg", ",", "correlationId", ",", "cb", ")", ";", "}" ]
write a produce request to kafka params: topic: the topic to write to partition: the partition to write to messages: an array of messages to write to kafkia, messages may be - a string - an array of string - an array of objects of the form {key: ..., value: ...} if key value pairs exist the key will be written to kafka for reference purposes otherwise a null key will be used
[ "write", "a", "produce", "request", "to", "kafka" ]
fa9a63f1f711e86bfc776d58ea44d91a8fb4a50b
https://github.com/apparatus/Kafkaesque/blob/fa9a63f1f711e86bfc776d58ea44d91a8fb4a50b/lib/api.js#L107-L118
train
apparatus/Kafkaesque
lib/api.js
function(params, cb) { var correlationId = _cbt.put(fetchResponse(cb)); var msg = envelope(fech.encode() .correlation(correlationId) .client(_options.clientId) .maxWait(params.maxWait) .minBytes(params.minBytes) .topic(params.topic) .partition(params.partition) .offset(params.offset) .maxBytes(_options.maxBytes) .end()); sendMsg(msg, correlationId, cb); }
javascript
function(params, cb) { var correlationId = _cbt.put(fetchResponse(cb)); var msg = envelope(fech.encode() .correlation(correlationId) .client(_options.clientId) .maxWait(params.maxWait) .minBytes(params.minBytes) .topic(params.topic) .partition(params.partition) .offset(params.offset) .maxBytes(_options.maxBytes) .end()); sendMsg(msg, correlationId, cb); }
[ "function", "(", "params", ",", "cb", ")", "{", "var", "correlationId", "=", "_cbt", ".", "put", "(", "fetchResponse", "(", "cb", ")", ")", ";", "var", "msg", "=", "envelope", "(", "fech", ".", "encode", "(", ")", ".", "correlation", "(", "correlationId", ")", ".", "client", "(", "_options", ".", "clientId", ")", ".", "maxWait", "(", "params", ".", "maxWait", ")", ".", "minBytes", "(", "params", ".", "minBytes", ")", ".", "topic", "(", "params", ".", "topic", ")", ".", "partition", "(", "params", ".", "partition", ")", ".", "offset", "(", "params", ".", "offset", ")", ".", "maxBytes", "(", "_options", ".", "maxBytes", ")", ".", "end", "(", ")", ")", ";", "sendMsg", "(", "msg", ",", "correlationId", ",", "cb", ")", ";", "}" ]
write a fetch request to kafka params: topic: the topic to write to partition: the partition to write to offset: the offset to fetch from maxWait: the maximum wait time in ms minBytes: the minimum number of bytes that should be available before a response is sent
[ "write", "a", "fetch", "request", "to", "kafka" ]
fa9a63f1f711e86bfc776d58ea44d91a8fb4a50b
https://github.com/apparatus/Kafkaesque/blob/fa9a63f1f711e86bfc776d58ea44d91a8fb4a50b/lib/api.js#L132-L145
train
apparatus/Kafkaesque
lib/api.js
function(params, cb) { var correlationId = _cbt.put(offsetResponse(cb)); var msg = envelope(off.encode() .correlation(correlationId) .client(_options.clientId) .replica() .topic(params.topic) .partition(params.partition) .timestamp() .maxOffsets() .end()); sendMsg(msg, correlationId, cb); }
javascript
function(params, cb) { var correlationId = _cbt.put(offsetResponse(cb)); var msg = envelope(off.encode() .correlation(correlationId) .client(_options.clientId) .replica() .topic(params.topic) .partition(params.partition) .timestamp() .maxOffsets() .end()); sendMsg(msg, correlationId, cb); }
[ "function", "(", "params", ",", "cb", ")", "{", "var", "correlationId", "=", "_cbt", ".", "put", "(", "offsetResponse", "(", "cb", ")", ")", ";", "var", "msg", "=", "envelope", "(", "off", ".", "encode", "(", ")", ".", "correlation", "(", "correlationId", ")", ".", "client", "(", "_options", ".", "clientId", ")", ".", "replica", "(", ")", ".", "topic", "(", "params", ".", "topic", ")", ".", "partition", "(", "params", ".", "partition", ")", ".", "timestamp", "(", ")", ".", "maxOffsets", "(", ")", ".", "end", "(", ")", ")", ";", "sendMsg", "(", "msg", ",", "correlationId", ",", "cb", ")", ";", "}" ]
request the latest offset from kafka i.e. the OLD offset api, not commit / fetch
[ "request", "the", "latest", "offset", "from", "kafka" ]
fa9a63f1f711e86bfc776d58ea44d91a8fb4a50b
https://github.com/apparatus/Kafkaesque/blob/fa9a63f1f711e86bfc776d58ea44d91a8fb4a50b/lib/api.js#L154-L166
train
apparatus/Kafkaesque
lib/api.js
function(params, cb) { var correlationId = _cbt.put(offFetchResponse(cb)); var msg = envelope(offFetch.encode(params.fetchFromCoordinator ? 1 : 0) .correlation(correlationId) .client(_options.clientId) .group(params.group) .topic(params.topic) .partition(params.partition) .end()); sendMsg(msg, correlationId, cb); }
javascript
function(params, cb) { var correlationId = _cbt.put(offFetchResponse(cb)); var msg = envelope(offFetch.encode(params.fetchFromCoordinator ? 1 : 0) .correlation(correlationId) .client(_options.clientId) .group(params.group) .topic(params.topic) .partition(params.partition) .end()); sendMsg(msg, correlationId, cb); }
[ "function", "(", "params", ",", "cb", ")", "{", "var", "correlationId", "=", "_cbt", ".", "put", "(", "offFetchResponse", "(", "cb", ")", ")", ";", "var", "msg", "=", "envelope", "(", "offFetch", ".", "encode", "(", "params", ".", "fetchFromCoordinator", "?", "1", ":", "0", ")", ".", "correlation", "(", "correlationId", ")", ".", "client", "(", "_options", ".", "clientId", ")", ".", "group", "(", "params", ".", "group", ")", ".", "topic", "(", "params", ".", "topic", ")", ".", "partition", "(", "params", ".", "partition", ")", ".", "end", "(", ")", ")", ";", "sendMsg", "(", "msg", ",", "correlationId", ",", "cb", ")", ";", "}" ]
write an offset request to kafka params: group: the consumer group id topic: the topic to commit on partition: the partition to commit on
[ "write", "an", "offset", "request", "to", "kafka" ]
fa9a63f1f711e86bfc776d58ea44d91a8fb4a50b
https://github.com/apparatus/Kafkaesque/blob/fa9a63f1f711e86bfc776d58ea44d91a8fb4a50b/lib/api.js#L177-L187
train
apparatus/Kafkaesque
lib/api.js
function(params, cb) { var correlationId = _cbt.put(offCommitResponse(cb)); var msg = envelope(offCommit.encode() .correlation(correlationId) .client(_options.clientId) .group(params.group) .topic(params.topic) .partition(params.partition) .offset(params.offset) // .when(params.when) //disabled in api ver1 .meta(params.meta) .end()); sendMsg(msg, correlationId, cb); }
javascript
function(params, cb) { var correlationId = _cbt.put(offCommitResponse(cb)); var msg = envelope(offCommit.encode() .correlation(correlationId) .client(_options.clientId) .group(params.group) .topic(params.topic) .partition(params.partition) .offset(params.offset) // .when(params.when) //disabled in api ver1 .meta(params.meta) .end()); sendMsg(msg, correlationId, cb); }
[ "function", "(", "params", ",", "cb", ")", "{", "var", "correlationId", "=", "_cbt", ".", "put", "(", "offCommitResponse", "(", "cb", ")", ")", ";", "var", "msg", "=", "envelope", "(", "offCommit", ".", "encode", "(", ")", ".", "correlation", "(", "correlationId", ")", ".", "client", "(", "_options", ".", "clientId", ")", ".", "group", "(", "params", ".", "group", ")", ".", "topic", "(", "params", ".", "topic", ")", ".", "partition", "(", "params", ".", "partition", ")", ".", "offset", "(", "params", ".", "offset", ")", ".", "meta", "(", "params", ".", "meta", ")", ".", "end", "(", ")", ")", ";", "sendMsg", "(", "msg", ",", "correlationId", ",", "cb", ")", ";", "}" ]
write a commit request to kafka params: group: the consumer group id topic: the topic to commit on partition: the partition to commit on offset: the offset to commit
[ "write", "a", "commit", "request", "to", "kafka" ]
fa9a63f1f711e86bfc776d58ea44d91a8fb4a50b
https://github.com/apparatus/Kafkaesque/blob/fa9a63f1f711e86bfc776d58ea44d91a8fb4a50b/lib/api.js#L199-L213
train
apparatus/Kafkaesque
lib/api.js
function(cb) { // return early if already connected if (_socket) { return cb(null, {host: _options.host, port: _options.port}); } _socket = net.createConnection(_options.port, _options.host); _socket.on('connect', function() { if (cb) { cb(null, {host: _options.host, port: _options.port}); } }); _socket.on('data', function(buf) { var res; var rblock; var decoder; if (!_rcvBuf) { _rcvBuf = kb(); } _rcvBuf.append(buf); res = response.decodeHead(_rcvBuf.get()); // console.log(res) // buffer can have more than one msg... // don't want to drop msgs while (_rcvBuf.length() > 0 && _rcvBuf.length() >= res.size + 4) { decoder = _cbt.remove(res.correlation); rblock = decoder.decode(_rcvBuf.get(), res); _rcvBuf.slice(res.size + 4); if (_rcvBuf.length() > 0) { res = response.decodeHead(_rcvBuf.get()); } decoder.callback(rblock.err, rblock.result); } }); _socket.on('end', function() {}); _socket.on('timeout', function(){ console.log('socket timeout'); }); _socket.on('drain', function(){}); _socket.on('error', function(err){ console.log('SOCKET ERROR: ' + err); }); _socket.on('close', function(){}); }
javascript
function(cb) { // return early if already connected if (_socket) { return cb(null, {host: _options.host, port: _options.port}); } _socket = net.createConnection(_options.port, _options.host); _socket.on('connect', function() { if (cb) { cb(null, {host: _options.host, port: _options.port}); } }); _socket.on('data', function(buf) { var res; var rblock; var decoder; if (!_rcvBuf) { _rcvBuf = kb(); } _rcvBuf.append(buf); res = response.decodeHead(_rcvBuf.get()); // console.log(res) // buffer can have more than one msg... // don't want to drop msgs while (_rcvBuf.length() > 0 && _rcvBuf.length() >= res.size + 4) { decoder = _cbt.remove(res.correlation); rblock = decoder.decode(_rcvBuf.get(), res); _rcvBuf.slice(res.size + 4); if (_rcvBuf.length() > 0) { res = response.decodeHead(_rcvBuf.get()); } decoder.callback(rblock.err, rblock.result); } }); _socket.on('end', function() {}); _socket.on('timeout', function(){ console.log('socket timeout'); }); _socket.on('drain', function(){}); _socket.on('error', function(err){ console.log('SOCKET ERROR: ' + err); }); _socket.on('close', function(){}); }
[ "function", "(", "cb", ")", "{", "if", "(", "_socket", ")", "{", "return", "cb", "(", "null", ",", "{", "host", ":", "_options", ".", "host", ",", "port", ":", "_options", ".", "port", "}", ")", ";", "}", "_socket", "=", "net", ".", "createConnection", "(", "_options", ".", "port", ",", "_options", ".", "host", ")", ";", "_socket", ".", "on", "(", "'connect'", ",", "function", "(", ")", "{", "if", "(", "cb", ")", "{", "cb", "(", "null", ",", "{", "host", ":", "_options", ".", "host", ",", "port", ":", "_options", ".", "port", "}", ")", ";", "}", "}", ")", ";", "_socket", ".", "on", "(", "'data'", ",", "function", "(", "buf", ")", "{", "var", "res", ";", "var", "rblock", ";", "var", "decoder", ";", "if", "(", "!", "_rcvBuf", ")", "{", "_rcvBuf", "=", "kb", "(", ")", ";", "}", "_rcvBuf", ".", "append", "(", "buf", ")", ";", "res", "=", "response", ".", "decodeHead", "(", "_rcvBuf", ".", "get", "(", ")", ")", ";", "while", "(", "_rcvBuf", ".", "length", "(", ")", ">", "0", "&&", "_rcvBuf", ".", "length", "(", ")", ">=", "res", ".", "size", "+", "4", ")", "{", "decoder", "=", "_cbt", ".", "remove", "(", "res", ".", "correlation", ")", ";", "rblock", "=", "decoder", ".", "decode", "(", "_rcvBuf", ".", "get", "(", ")", ",", "res", ")", ";", "_rcvBuf", ".", "slice", "(", "res", ".", "size", "+", "4", ")", ";", "if", "(", "_rcvBuf", ".", "length", "(", ")", ">", "0", ")", "{", "res", "=", "response", ".", "decodeHead", "(", "_rcvBuf", ".", "get", "(", ")", ")", ";", "}", "decoder", ".", "callback", "(", "rblock", ".", "err", ",", "rblock", ".", "result", ")", ";", "}", "}", ")", ";", "_socket", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "}", ")", ";", "_socket", ".", "on", "(", "'timeout'", ",", "function", "(", ")", "{", "console", ".", "log", "(", "'socket timeout'", ")", ";", "}", ")", ";", "_socket", ".", "on", "(", "'drain'", ",", "function", "(", ")", "{", "}", ")", ";", "_socket", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "console", ".", "log", "(", "'SOCKET ERROR: '", "+", "err", ")", ";", "}", ")", ";", "_socket", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "}", ")", ";", "}" ]
tearup the connection to kafka
[ "tearup", "the", "connection", "to", "kafka" ]
fa9a63f1f711e86bfc776d58ea44d91a8fb4a50b
https://github.com/apparatus/Kafkaesque/blob/fa9a63f1f711e86bfc776d58ea44d91a8fb4a50b/lib/api.js#L364-L419
train
mercadolibre/tiny.js
modules/support.js
animationEnd
function animationEnd() { let el = document.createElement('tiny'); let animEndEventNames = { WebkitAnimation : 'webkitAnimationEnd', MozAnimation : 'animationend', OAnimation : 'oAnimationEnd oanimationend', animation : 'animationend' }; for (let name in animEndEventNames) { if (animEndEventNames.hasOwnProperty(name) && el.style[name] !== undefined) { return { end: animEndEventNames[name] }; } } return false; }
javascript
function animationEnd() { let el = document.createElement('tiny'); let animEndEventNames = { WebkitAnimation : 'webkitAnimationEnd', MozAnimation : 'animationend', OAnimation : 'oAnimationEnd oanimationend', animation : 'animationend' }; for (let name in animEndEventNames) { if (animEndEventNames.hasOwnProperty(name) && el.style[name] !== undefined) { return { end: animEndEventNames[name] }; } } return false; }
[ "function", "animationEnd", "(", ")", "{", "let", "el", "=", "document", ".", "createElement", "(", "'tiny'", ")", ";", "let", "animEndEventNames", "=", "{", "WebkitAnimation", ":", "'webkitAnimationEnd'", ",", "MozAnimation", ":", "'animationend'", ",", "OAnimation", ":", "'oAnimationEnd oanimationend'", ",", "animation", ":", "'animationend'", "}", ";", "for", "(", "let", "name", "in", "animEndEventNames", ")", "{", "if", "(", "animEndEventNames", ".", "hasOwnProperty", "(", "name", ")", "&&", "el", ".", "style", "[", "name", "]", "!==", "undefined", ")", "{", "return", "{", "end", ":", "animEndEventNames", "[", "name", "]", "}", ";", "}", "}", "return", "false", ";", "}" ]
Checks for the CSS Animations support @function @private
[ "Checks", "for", "the", "CSS", "Animations", "support" ]
10fad8be21abdbec23642be77ad64f449711a40d
https://github.com/mercadolibre/tiny.js/blob/10fad8be21abdbec23642be77ad64f449711a40d/modules/support.js#L94-L113
train
mercadolibre/tiny.js
modules/offset.js
getFixedParent
function getFixedParent (el) { let currentParent = el.offsetParent, parent; while (parent === undefined) { if (currentParent === null) { parent = null; break; } if (css(currentParent, 'position') !== 'fixed') { currentParent = currentParent.offsetParent; } else { parent = currentParent; } } return parent; }
javascript
function getFixedParent (el) { let currentParent = el.offsetParent, parent; while (parent === undefined) { if (currentParent === null) { parent = null; break; } if (css(currentParent, 'position') !== 'fixed') { currentParent = currentParent.offsetParent; } else { parent = currentParent; } } return parent; }
[ "function", "getFixedParent", "(", "el", ")", "{", "let", "currentParent", "=", "el", ".", "offsetParent", ",", "parent", ";", "while", "(", "parent", "===", "undefined", ")", "{", "if", "(", "currentParent", "===", "null", ")", "{", "parent", "=", "null", ";", "break", ";", "}", "if", "(", "css", "(", "currentParent", ",", "'position'", ")", "!==", "'fixed'", ")", "{", "currentParent", "=", "currentParent", ".", "offsetParent", ";", "}", "else", "{", "parent", "=", "currentParent", ";", "}", "}", "return", "parent", ";", "}" ]
Get the current parentNode with the 'fixed' position. @private @param {HTMLElement} el A given HTMLElement. @returns {HTMLElement}
[ "Get", "the", "current", "parentNode", "with", "the", "fixed", "position", "." ]
10fad8be21abdbec23642be77ad64f449711a40d
https://github.com/mercadolibre/tiny.js/blob/10fad8be21abdbec23642be77ad64f449711a40d/modules/offset.js#L38-L57
train
gangachris/ng-validators
src/helpers.js
function (name, value, options) { if (options) { return validator[name](value, options) ? null : (_a = {}, _a[name] = { valid: false }, _a); } return validator[name](value) ? null : (_b = {}, _b[name] = { valid: false }, _b); var _a, _b; }
javascript
function (name, value, options) { if (options) { return validator[name](value, options) ? null : (_a = {}, _a[name] = { valid: false }, _a); } return validator[name](value) ? null : (_b = {}, _b[name] = { valid: false }, _b); var _a, _b; }
[ "function", "(", "name", ",", "value", ",", "options", ")", "{", "if", "(", "options", ")", "{", "return", "validator", "[", "name", "]", "(", "value", ",", "options", ")", "?", "null", ":", "(", "_a", "=", "{", "}", ",", "_a", "[", "name", "]", "=", "{", "valid", ":", "false", "}", ",", "_a", ")", ";", "}", "return", "validator", "[", "name", "]", "(", "value", ")", "?", "null", ":", "(", "_b", "=", "{", "}", ",", "_b", "[", "name", "]", "=", "{", "valid", ":", "false", "}", ",", "_b", ")", ";", "var", "_a", ",", "_b", ";", "}" ]
Wrapper for calling validator js functions @param {any} name name of the validator to be called e.g isEmail @param {any} value value passed from the abstract control @param {any} options optional parameters @returns
[ "Wrapper", "for", "calling", "validator", "js", "functions" ]
00bee20fbe26bc59cc4182f7971ecbda8e491dca
https://github.com/gangachris/ng-validators/blob/00bee20fbe26bc59cc4182f7971ecbda8e491dca/src/helpers.js#L12-L26
train
gangachris/ng-validators
src/helpers.js
getParamValidator
function getParamValidator(name) { return function (options) { return function (c) { return getValidator(name, c.value != null ? c.value : '', options); }; }; }
javascript
function getParamValidator(name) { return function (options) { return function (c) { return getValidator(name, c.value != null ? c.value : '', options); }; }; }
[ "function", "getParamValidator", "(", "name", ")", "{", "return", "function", "(", "options", ")", "{", "return", "function", "(", "c", ")", "{", "return", "getValidator", "(", "name", ",", "c", ".", "value", "!=", "null", "?", "c", ".", "value", ":", "''", ",", "options", ")", ";", "}", ";", "}", ";", "}" ]
Gets the validators with parameter. Parameters are optional since some validators do not require them @export @param {string} name name of the validator @returns angular form validator @export @param {string} name @returns
[ "Gets", "the", "validators", "with", "parameter", ".", "Parameters", "are", "optional", "since", "some", "validators", "do", "not", "require", "them" ]
00bee20fbe26bc59cc4182f7971ecbda8e491dca
https://github.com/gangachris/ng-validators/blob/00bee20fbe26bc59cc4182f7971ecbda8e491dca/src/helpers.js#L42-L48
train
AlgoTrader/betfair-sports-api
lib/emulator_market.js
placeBets
function placeBets() { // check input bets list var error; for ( var i = 0; i < req.request.bets.length; ++i) { var desc = req.request.bets[i]; error = checkPlaceBetItem(self, desc); // console.log('EMU bet', desc, "error", error); if (error) break; } // It is very strange, but Betfair returns 'OK' // when bet size or price is invalid res.response.errorCode = 'OK'; res.response.betResults = []; if (error) { // Prepare response, no bets placed for ( var i = 0; i < req.request.bets.length; ++i) { var resItem = { averagePriceMatched : '0.0', betId : '0', resultCode : error, sizeMatched : '0.0', success : 'false' }; res.response.betResults.push(resItem); } cb(null, res); return; } // Create bets var betIds = []; for ( var i = 0; i < req.request.bets.length; ++i) { var desc = req.request.bets[i]; var bet = new EmulatorBet(desc.marketId, desc.selectionId, desc.betType, desc.price, desc.size); betIds.push(bet.betId); self.bets[bet.betId] = bet; } // Try to match bets using price matching var bets = betIds.map(function(id) { return self.bets[id]; }); matchBetsUsingPrices(self, bets); // Prepare response for ( var id in betIds) { var betId = betIds[id]; var bet = self.bets[betId]; var resItem = { averagePriceMatched : bet.averageMatchedPrice(), betId : bet.betId, resultCode : 'OK', sizeMatched : bet.matchedSize(), success : 'true' }; res.response.betResults.push(resItem); } // placeBets was OK cb(null, res); }
javascript
function placeBets() { // check input bets list var error; for ( var i = 0; i < req.request.bets.length; ++i) { var desc = req.request.bets[i]; error = checkPlaceBetItem(self, desc); // console.log('EMU bet', desc, "error", error); if (error) break; } // It is very strange, but Betfair returns 'OK' // when bet size or price is invalid res.response.errorCode = 'OK'; res.response.betResults = []; if (error) { // Prepare response, no bets placed for ( var i = 0; i < req.request.bets.length; ++i) { var resItem = { averagePriceMatched : '0.0', betId : '0', resultCode : error, sizeMatched : '0.0', success : 'false' }; res.response.betResults.push(resItem); } cb(null, res); return; } // Create bets var betIds = []; for ( var i = 0; i < req.request.bets.length; ++i) { var desc = req.request.bets[i]; var bet = new EmulatorBet(desc.marketId, desc.selectionId, desc.betType, desc.price, desc.size); betIds.push(bet.betId); self.bets[bet.betId] = bet; } // Try to match bets using price matching var bets = betIds.map(function(id) { return self.bets[id]; }); matchBetsUsingPrices(self, bets); // Prepare response for ( var id in betIds) { var betId = betIds[id]; var bet = self.bets[betId]; var resItem = { averagePriceMatched : bet.averageMatchedPrice(), betId : bet.betId, resultCode : 'OK', sizeMatched : bet.matchedSize(), success : 'true' }; res.response.betResults.push(resItem); } // placeBets was OK cb(null, res); }
[ "function", "placeBets", "(", ")", "{", "var", "error", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "req", ".", "request", ".", "bets", ".", "length", ";", "++", "i", ")", "{", "var", "desc", "=", "req", ".", "request", ".", "bets", "[", "i", "]", ";", "error", "=", "checkPlaceBetItem", "(", "self", ",", "desc", ")", ";", "if", "(", "error", ")", "break", ";", "}", "res", ".", "response", ".", "errorCode", "=", "'OK'", ";", "res", ".", "response", ".", "betResults", "=", "[", "]", ";", "if", "(", "error", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "req", ".", "request", ".", "bets", ".", "length", ";", "++", "i", ")", "{", "var", "resItem", "=", "{", "averagePriceMatched", ":", "'0.0'", ",", "betId", ":", "'0'", ",", "resultCode", ":", "error", ",", "sizeMatched", ":", "'0.0'", ",", "success", ":", "'false'", "}", ";", "res", ".", "response", ".", "betResults", ".", "push", "(", "resItem", ")", ";", "}", "cb", "(", "null", ",", "res", ")", ";", "return", ";", "}", "var", "betIds", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "req", ".", "request", ".", "bets", ".", "length", ";", "++", "i", ")", "{", "var", "desc", "=", "req", ".", "request", ".", "bets", "[", "i", "]", ";", "var", "bet", "=", "new", "EmulatorBet", "(", "desc", ".", "marketId", ",", "desc", ".", "selectionId", ",", "desc", ".", "betType", ",", "desc", ".", "price", ",", "desc", ".", "size", ")", ";", "betIds", ".", "push", "(", "bet", ".", "betId", ")", ";", "self", ".", "bets", "[", "bet", ".", "betId", "]", "=", "bet", ";", "}", "var", "bets", "=", "betIds", ".", "map", "(", "function", "(", "id", ")", "{", "return", "self", ".", "bets", "[", "id", "]", ";", "}", ")", ";", "matchBetsUsingPrices", "(", "self", ",", "bets", ")", ";", "for", "(", "var", "id", "in", "betIds", ")", "{", "var", "betId", "=", "betIds", "[", "id", "]", ";", "var", "bet", "=", "self", ".", "bets", "[", "betId", "]", ";", "var", "resItem", "=", "{", "averagePriceMatched", ":", "bet", ".", "averageMatchedPrice", "(", ")", ",", "betId", ":", "bet", ".", "betId", ",", "resultCode", ":", "'OK'", ",", "sizeMatched", ":", "bet", ".", "matchedSize", "(", ")", ",", "success", ":", "'true'", "}", ";", "res", ".", "response", ".", "betResults", ".", "push", "(", "resItem", ")", ";", "}", "cb", "(", "null", ",", "res", ")", ";", "}" ]
place bets, the function is delayed to simulate slow network
[ "place", "bets", "the", "function", "is", "delayed", "to", "simulate", "slow", "network" ]
196093a9711b268e9f8b1892e71c1aa070492747
https://github.com/AlgoTrader/betfair-sports-api/blob/196093a9711b268e9f8b1892e71c1aa070492747/lib/emulator_market.js#L375-L439
train
AlgoTrader/betfair-sports-api
lib/emulator_market.js
cancelBets
function cancelBets() { // check request bets list var error; for ( var i = 0; i < req.request.bets.length; ++i) { var desc = req.request.bets[i]; error = checkCancelBetItem(self, desc); // console.log('EMU bet', desc, "error", error); if (error) break; } if (error) { res.response.errorCode = 'MARKET_IDS_DONT_MATCH'; cb(null, res); return; } // cancel bets res.response.errorCode = 'OK'; res.response.betResults = []; for ( var i = 0; i < req.request.bets.length; ++i) { var betId = req.request.bets[i].betId; console.log('EMU: cancel id=', betId); var bet = self.bets[betId]; // do cancel work var result = bet.cancel(); var resItem = { betId : bet.betId, resultCode : result.code, sizeCancelled : result.sizeCancelled, sizeMatched : result.sizeMatched, success : result.success }; res.response.betResults.push(resItem); } // cancelBets was OK cb(null, res); }
javascript
function cancelBets() { // check request bets list var error; for ( var i = 0; i < req.request.bets.length; ++i) { var desc = req.request.bets[i]; error = checkCancelBetItem(self, desc); // console.log('EMU bet', desc, "error", error); if (error) break; } if (error) { res.response.errorCode = 'MARKET_IDS_DONT_MATCH'; cb(null, res); return; } // cancel bets res.response.errorCode = 'OK'; res.response.betResults = []; for ( var i = 0; i < req.request.bets.length; ++i) { var betId = req.request.bets[i].betId; console.log('EMU: cancel id=', betId); var bet = self.bets[betId]; // do cancel work var result = bet.cancel(); var resItem = { betId : bet.betId, resultCode : result.code, sizeCancelled : result.sizeCancelled, sizeMatched : result.sizeMatched, success : result.success }; res.response.betResults.push(resItem); } // cancelBets was OK cb(null, res); }
[ "function", "cancelBets", "(", ")", "{", "var", "error", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "req", ".", "request", ".", "bets", ".", "length", ";", "++", "i", ")", "{", "var", "desc", "=", "req", ".", "request", ".", "bets", "[", "i", "]", ";", "error", "=", "checkCancelBetItem", "(", "self", ",", "desc", ")", ";", "if", "(", "error", ")", "break", ";", "}", "if", "(", "error", ")", "{", "res", ".", "response", ".", "errorCode", "=", "'MARKET_IDS_DONT_MATCH'", ";", "cb", "(", "null", ",", "res", ")", ";", "return", ";", "}", "res", ".", "response", ".", "errorCode", "=", "'OK'", ";", "res", ".", "response", ".", "betResults", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "req", ".", "request", ".", "bets", ".", "length", ";", "++", "i", ")", "{", "var", "betId", "=", "req", ".", "request", ".", "bets", "[", "i", "]", ".", "betId", ";", "console", ".", "log", "(", "'EMU: cancel id='", ",", "betId", ")", ";", "var", "bet", "=", "self", ".", "bets", "[", "betId", "]", ";", "var", "result", "=", "bet", ".", "cancel", "(", ")", ";", "var", "resItem", "=", "{", "betId", ":", "bet", ".", "betId", ",", "resultCode", ":", "result", ".", "code", ",", "sizeCancelled", ":", "result", ".", "sizeCancelled", ",", "sizeMatched", ":", "result", ".", "sizeMatched", ",", "success", ":", "result", ".", "success", "}", ";", "res", ".", "response", ".", "betResults", ".", "push", "(", "resItem", ")", ";", "}", "cb", "(", "null", ",", "res", ")", ";", "}" ]
cancel bets, the function is delayed to simulate slow network
[ "cancel", "bets", "the", "function", "is", "delayed", "to", "simulate", "slow", "network" ]
196093a9711b268e9f8b1892e71c1aa070492747
https://github.com/AlgoTrader/betfair-sports-api/blob/196093a9711b268e9f8b1892e71c1aa070492747/lib/emulator_market.js#L471-L511
train
AlgoTrader/betfair-sports-api
lib/emulator_market.js
checkPlaceBetItem
function checkPlaceBetItem(self, desc) { if (desc.asianLineId !== '0' || desc.betCategoryType !== 'E') return 'UNKNOWN_ERROR'; if (desc.betPersistenceType !== 'NONE' && desc.betPersistenceType !== 'IP') return 'INVALID_PERSISTENCE'; if (desc.betType !== 'B' && desc.betType !== 'L') return 'INVALID_BET_TYPE'; if (desc.bspLiability !== '0') return 'BSP_BETTING_NOT_ALLOWED'; var price = betfairPrice.newBetfairPrice(desc.price); if (Math.abs(price.size - 1 * desc.price) > 0.0001) return 'INVALID_PRICE'; if (!self.players[desc.selectionId]) return 'SELECTION_REMOVED'; if (1 * desc.size < minimumBetSize || 1 * desc.size > maximumBetSize) return 'INVALID_SIZE'; // no checks failed, then bet is OK return null; }
javascript
function checkPlaceBetItem(self, desc) { if (desc.asianLineId !== '0' || desc.betCategoryType !== 'E') return 'UNKNOWN_ERROR'; if (desc.betPersistenceType !== 'NONE' && desc.betPersistenceType !== 'IP') return 'INVALID_PERSISTENCE'; if (desc.betType !== 'B' && desc.betType !== 'L') return 'INVALID_BET_TYPE'; if (desc.bspLiability !== '0') return 'BSP_BETTING_NOT_ALLOWED'; var price = betfairPrice.newBetfairPrice(desc.price); if (Math.abs(price.size - 1 * desc.price) > 0.0001) return 'INVALID_PRICE'; if (!self.players[desc.selectionId]) return 'SELECTION_REMOVED'; if (1 * desc.size < minimumBetSize || 1 * desc.size > maximumBetSize) return 'INVALID_SIZE'; // no checks failed, then bet is OK return null; }
[ "function", "checkPlaceBetItem", "(", "self", ",", "desc", ")", "{", "if", "(", "desc", ".", "asianLineId", "!==", "'0'", "||", "desc", ".", "betCategoryType", "!==", "'E'", ")", "return", "'UNKNOWN_ERROR'", ";", "if", "(", "desc", ".", "betPersistenceType", "!==", "'NONE'", "&&", "desc", ".", "betPersistenceType", "!==", "'IP'", ")", "return", "'INVALID_PERSISTENCE'", ";", "if", "(", "desc", ".", "betType", "!==", "'B'", "&&", "desc", ".", "betType", "!==", "'L'", ")", "return", "'INVALID_BET_TYPE'", ";", "if", "(", "desc", ".", "bspLiability", "!==", "'0'", ")", "return", "'BSP_BETTING_NOT_ALLOWED'", ";", "var", "price", "=", "betfairPrice", ".", "newBetfairPrice", "(", "desc", ".", "price", ")", ";", "if", "(", "Math", ".", "abs", "(", "price", ".", "size", "-", "1", "*", "desc", ".", "price", ")", ">", "0.0001", ")", "return", "'INVALID_PRICE'", ";", "if", "(", "!", "self", ".", "players", "[", "desc", ".", "selectionId", "]", ")", "return", "'SELECTION_REMOVED'", ";", "if", "(", "1", "*", "desc", ".", "size", "<", "minimumBetSize", "||", "1", "*", "desc", ".", "size", ">", "maximumBetSize", ")", "return", "'INVALID_SIZE'", ";", "return", "null", ";", "}" ]
Check a single bet item from placeBets bets list
[ "Check", "a", "single", "bet", "item", "from", "placeBets", "bets", "list" ]
196093a9711b268e9f8b1892e71c1aa070492747
https://github.com/AlgoTrader/betfair-sports-api/blob/196093a9711b268e9f8b1892e71c1aa070492747/lib/emulator_market.js#L519-L544
train
mattbornski/libphonenumber
lib/closure/goog/net/streams/jsonstreamparser.js
skipWhitespace
function skipWhitespace() { while (i < input.length) { if (isWhitespace(input[i])) { i++; parser.pos_++; continue; } break; } }
javascript
function skipWhitespace() { while (i < input.length) { if (isWhitespace(input[i])) { i++; parser.pos_++; continue; } break; } }
[ "function", "skipWhitespace", "(", ")", "{", "while", "(", "i", "<", "input", ".", "length", ")", "{", "if", "(", "isWhitespace", "(", "input", "[", "i", "]", ")", ")", "{", "i", "++", ";", "parser", ".", "pos_", "++", ";", "continue", ";", "}", "break", ";", "}", "}" ]
Skip as many whitespaces as possible, and increments current index of stream to next available char.
[ "Skip", "as", "many", "whitespaces", "as", "possible", "and", "increments", "current", "index", "of", "stream", "to", "next", "available", "char", "." ]
8e5b827ca1a9ddd0d5e7722436ec987897e85bda
https://github.com/mattbornski/libphonenumber/blob/8e5b827ca1a9ddd0d5e7722436ec987897e85bda/lib/closure/goog/net/streams/jsonstreamparser.js#L287-L296
train
yahoo/context-parser
src/context-parser.js
DisableIEConditionalComments
function DisableIEConditionalComments(state, i){ if (state === htmlState.STATE_COMMENT && this.input[i] === ']' && this.input[i+1] === '>') { // for lazy conversion this._convertString2Array(); this.input.splice(i + 1, 0, ' '); this.inputLen++; } }
javascript
function DisableIEConditionalComments(state, i){ if (state === htmlState.STATE_COMMENT && this.input[i] === ']' && this.input[i+1] === '>') { // for lazy conversion this._convertString2Array(); this.input.splice(i + 1, 0, ' '); this.inputLen++; } }
[ "function", "DisableIEConditionalComments", "(", "state", ",", "i", ")", "{", "if", "(", "state", "===", "htmlState", ".", "STATE_COMMENT", "&&", "this", ".", "input", "[", "i", "]", "===", "']'", "&&", "this", ".", "input", "[", "i", "+", "1", "]", "===", "'>'", ")", "{", "this", ".", "_convertString2Array", "(", ")", ";", "this", ".", "input", ".", "splice", "(", "i", "+", "1", ",", "0", ",", "' '", ")", ";", "this", ".", "inputLen", "++", ";", "}", "}" ]
remove IE conditional comments
[ "remove", "IE", "conditional", "comments" ]
6ad21fdcf242b2c2f6eb70281bbf6425a05122c1
https://github.com/yahoo/context-parser/blob/6ad21fdcf242b2c2f6eb70281bbf6425a05122c1/src/context-parser.js#L967-L975
train
appscot/sails-orientdb
lib/associations.js
function (collectionIdentity) { if (!collectionIdentity) return; var schema = connectionObject.collections[collectionIdentity].attributes; if(!schema) return 'id'; var key; for(key in schema){ if(schema[key].primaryKey) return key; } return 'id'; }
javascript
function (collectionIdentity) { if (!collectionIdentity) return; var schema = connectionObject.collections[collectionIdentity].attributes; if(!schema) return 'id'; var key; for(key in schema){ if(schema[key].primaryKey) return key; } return 'id'; }
[ "function", "(", "collectionIdentity", ")", "{", "if", "(", "!", "collectionIdentity", ")", "return", ";", "var", "schema", "=", "connectionObject", ".", "collections", "[", "collectionIdentity", "]", ".", "attributes", ";", "if", "(", "!", "schema", ")", "return", "'id'", ";", "var", "key", ";", "for", "(", "key", "in", "schema", ")", "{", "if", "(", "schema", "[", "key", "]", ".", "primaryKey", ")", "return", "key", ";", "}", "return", "'id'", ";", "}" ]
Look up the name of the primary key field for the collection with the specified identity. @param {String} collectionIdentity @return {String}
[ "Look", "up", "the", "name", "of", "the", "primary", "key", "field", "for", "the", "collection", "with", "the", "specified", "identity", "." ]
2a902f08b097a813c45ccb0e23835a29611e979e
https://github.com/appscot/sails-orientdb/blob/2a902f08b097a813c45ccb0e23835a29611e979e/lib/associations.js#L336-L349
train
eggjs/egg-jsonp
app/extend/application.js
securityAssert
function securityAssert(ctx) { // all disabled. don't need check if (!csrfEnable && !validateReferrer) return; // pass referrer check const referrer = ctx.get('referrer'); if (validateReferrer && validateReferrer(referrer)) return; if (csrfEnable && validateCsrf(ctx)) return; const err = new Error('jsonp request security validate failed'); err.referrer = referrer; err.status = 403; throw err; }
javascript
function securityAssert(ctx) { // all disabled. don't need check if (!csrfEnable && !validateReferrer) return; // pass referrer check const referrer = ctx.get('referrer'); if (validateReferrer && validateReferrer(referrer)) return; if (csrfEnable && validateCsrf(ctx)) return; const err = new Error('jsonp request security validate failed'); err.referrer = referrer; err.status = 403; throw err; }
[ "function", "securityAssert", "(", "ctx", ")", "{", "if", "(", "!", "csrfEnable", "&&", "!", "validateReferrer", ")", "return", ";", "const", "referrer", "=", "ctx", ".", "get", "(", "'referrer'", ")", ";", "if", "(", "validateReferrer", "&&", "validateReferrer", "(", "referrer", ")", ")", "return", ";", "if", "(", "csrfEnable", "&&", "validateCsrf", "(", "ctx", ")", ")", "return", ";", "const", "err", "=", "new", "Error", "(", "'jsonp request security validate failed'", ")", ";", "err", ".", "referrer", "=", "referrer", ";", "err", ".", "status", "=", "403", ";", "throw", "err", ";", "}" ]
jsonp request security check, pass if 1. hit referrer white list 2. or pass csrf check 3. both check are disabled @param {Context} ctx request context
[ "jsonp", "request", "security", "check", "pass", "if" ]
f19c6436be1b3a71127b342ad07dbb1bac861efe
https://github.com/eggjs/egg-jsonp/blob/f19c6436be1b3a71127b342ad07dbb1bac861efe/app/extend/application.js#L38-L51
train
appscot/sails-orientdb
lib/adapter.js
function(conn, cb) { log.debug('teardown:', conn); /* istanbul ignore if: standard waterline-adapter code */ if ( typeof conn == 'function') { cb = conn; conn = null; } /* istanbul ignore if: standard waterline-adapter code */ if (!conn) { connections = {}; return cb(); } /* istanbul ignore if: standard waterline-adapter code */ if (!connections[conn]) return cb(); delete connections[conn]; cb(); }
javascript
function(conn, cb) { log.debug('teardown:', conn); /* istanbul ignore if: standard waterline-adapter code */ if ( typeof conn == 'function') { cb = conn; conn = null; } /* istanbul ignore if: standard waterline-adapter code */ if (!conn) { connections = {}; return cb(); } /* istanbul ignore if: standard waterline-adapter code */ if (!connections[conn]) return cb(); delete connections[conn]; cb(); }
[ "function", "(", "conn", ",", "cb", ")", "{", "log", ".", "debug", "(", "'teardown:'", ",", "conn", ")", ";", "if", "(", "typeof", "conn", "==", "'function'", ")", "{", "cb", "=", "conn", ";", "conn", "=", "null", ";", "}", "if", "(", "!", "conn", ")", "{", "connections", "=", "{", "}", ";", "return", "cb", "(", ")", ";", "}", "if", "(", "!", "connections", "[", "conn", "]", ")", "return", "cb", "(", ")", ";", "delete", "connections", "[", "conn", "]", ";", "cb", "(", ")", ";", "}" ]
Teardown a Connection Fired when a model is unregistered, typically when the server is killed. Useful for tearing-down remaining open connections, etc. @param {Function} cb [description] @return {[type]} [description]
[ "Teardown", "a", "Connection" ]
2a902f08b097a813c45ccb0e23835a29611e979e
https://github.com/appscot/sails-orientdb/blob/2a902f08b097a813c45ccb0e23835a29611e979e/lib/adapter.js#L187-L204
train
appscot/sails-orientdb
lib/adapter.js
function(connection, collection, object, cb) { utils.removeCircularReferences(object); if (cb) { cb(object); } return object; }
javascript
function(connection, collection, object, cb) { utils.removeCircularReferences(object); if (cb) { cb(object); } return object; }
[ "function", "(", "connection", ",", "collection", ",", "object", ",", "cb", ")", "{", "utils", ".", "removeCircularReferences", "(", "object", ")", ";", "if", "(", "cb", ")", "{", "cb", "(", "object", ")", ";", "}", "return", "object", ";", "}" ]
Remove Circular References Replaces circular references with `id` when one is available, otherwise it replaces the object with string '[Circular]' @param {Object} connection @param {Object} collection @param {Object} object @param {Object} cb
[ "Remove", "Circular", "References" ]
2a902f08b097a813c45ccb0e23835a29611e979e
https://github.com/appscot/sails-orientdb/blob/2a902f08b097a813c45ccb0e23835a29611e979e/lib/adapter.js#L463-L469
train
zorkow/speech-rule-engine
resources/www/scripts/explorer.js
function(node, highlighter) { this.div.classList.add('MJX_LiveRegion_Show'); var rect = node.getBoundingClientRect(); var bot = rect.bottom + 10 + window.pageYOffset; var left = rect.left + window.pageXOffset; this.div.style.top = bot + 'px'; this.div.style.left = left + 'px'; var color = highlighter.colorString(); this.inner.style.backgroundColor = color.background; this.inner.style.color = color.foreground; }
javascript
function(node, highlighter) { this.div.classList.add('MJX_LiveRegion_Show'); var rect = node.getBoundingClientRect(); var bot = rect.bottom + 10 + window.pageYOffset; var left = rect.left + window.pageXOffset; this.div.style.top = bot + 'px'; this.div.style.left = left + 'px'; var color = highlighter.colorString(); this.inner.style.backgroundColor = color.background; this.inner.style.color = color.foreground; }
[ "function", "(", "node", ",", "highlighter", ")", "{", "this", ".", "div", ".", "classList", ".", "add", "(", "'MJX_LiveRegion_Show'", ")", ";", "var", "rect", "=", "node", ".", "getBoundingClientRect", "(", ")", ";", "var", "bot", "=", "rect", ".", "bottom", "+", "10", "+", "window", ".", "pageYOffset", ";", "var", "left", "=", "rect", ".", "left", "+", "window", ".", "pageXOffset", ";", "this", ".", "div", ".", "style", ".", "top", "=", "bot", "+", "'px'", ";", "this", ".", "div", ".", "style", ".", "left", "=", "left", "+", "'px'", ";", "var", "color", "=", "highlighter", ".", "colorString", "(", ")", ";", "this", ".", "inner", ".", "style", ".", "backgroundColor", "=", "color", ".", "background", ";", "this", ".", "inner", ".", "style", ".", "color", "=", "color", ".", "foreground", ";", "}" ]
Shows the live region as a subtitle of a node.
[ "Shows", "the", "live", "region", "as", "a", "subtitle", "of", "a", "node", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/explorer.js#L184-L194
train
zorkow/speech-rule-engine
resources/www/scripts/explorer.js
function(type) { var element = MathJax.HTML.Element( 'div', {className: 'MJX_LiveRegion'}); element.setAttribute('aria-live', type); return element; }
javascript
function(type) { var element = MathJax.HTML.Element( 'div', {className: 'MJX_LiveRegion'}); element.setAttribute('aria-live', type); return element; }
[ "function", "(", "type", ")", "{", "var", "element", "=", "MathJax", ".", "HTML", ".", "Element", "(", "'div'", ",", "{", "className", ":", "'MJX_LiveRegion'", "}", ")", ";", "element", ".", "setAttribute", "(", "'aria-live'", ",", "type", ")", ";", "return", "element", ";", "}" ]
Creates a live region with a particular type.
[ "Creates", "a", "live", "region", "with", "a", "particular", "type", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/explorer.js#L239-L244
train
zorkow/speech-rule-engine
resources/www/scripts/explorer.js
function() { if (!Assistive.getOption('speech')) return; LiveRegion.announced = true; MathJax.Ajax.Styles(LiveRegion.styles); var div = LiveRegion.Create('polite'); document.body.appendChild(div); LiveRegion.Update(div, LiveRegion.ANNOUNCE); setTimeout(function() {document.body.removeChild(div);}, 1000); }
javascript
function() { if (!Assistive.getOption('speech')) return; LiveRegion.announced = true; MathJax.Ajax.Styles(LiveRegion.styles); var div = LiveRegion.Create('polite'); document.body.appendChild(div); LiveRegion.Update(div, LiveRegion.ANNOUNCE); setTimeout(function() {document.body.removeChild(div);}, 1000); }
[ "function", "(", ")", "{", "if", "(", "!", "Assistive", ".", "getOption", "(", "'speech'", ")", ")", "return", ";", "LiveRegion", ".", "announced", "=", "true", ";", "MathJax", ".", "Ajax", ".", "Styles", "(", "LiveRegion", ".", "styles", ")", ";", "var", "div", "=", "LiveRegion", ".", "Create", "(", "'polite'", ")", ";", "document", ".", "body", ".", "appendChild", "(", "div", ")", ";", "LiveRegion", ".", "Update", "(", "div", ",", "LiveRegion", ".", "ANNOUNCE", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "document", ".", "body", ".", "removeChild", "(", "div", ")", ";", "}", ",", "1000", ")", ";", "}" ]
Speaks the announce string.
[ "Speaks", "the", "announce", "string", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/explorer.js#L259-L267
train
zorkow/speech-rule-engine
resources/www/scripts/explorer.js
function(msg) { if (!Assistive.hook) return; var script = document.getElementById(msg[1]); if (script && script.id) { var jax = MathJax.Hub.getJaxFor(script.id); if (jax && jax.enriched) { Explorer.StateChange(script.id, jax); Explorer.liveRegion.Add(); Explorer.AddEvent(script); } } }
javascript
function(msg) { if (!Assistive.hook) return; var script = document.getElementById(msg[1]); if (script && script.id) { var jax = MathJax.Hub.getJaxFor(script.id); if (jax && jax.enriched) { Explorer.StateChange(script.id, jax); Explorer.liveRegion.Add(); Explorer.AddEvent(script); } } }
[ "function", "(", "msg", ")", "{", "if", "(", "!", "Assistive", ".", "hook", ")", "return", ";", "var", "script", "=", "document", ".", "getElementById", "(", "msg", "[", "1", "]", ")", ";", "if", "(", "script", "&&", "script", ".", "id", ")", "{", "var", "jax", "=", "MathJax", ".", "Hub", ".", "getJaxFor", "(", "script", ".", "id", ")", ";", "if", "(", "jax", "&&", "jax", ".", "enriched", ")", "{", "Explorer", ".", "StateChange", "(", "script", ".", "id", ",", "jax", ")", ";", "Explorer", ".", "liveRegion", ".", "Add", "(", ")", ";", "Explorer", ".", "AddEvent", "(", "script", ")", ";", "}", "}", "}" ]
Registers new Maths and adds a key event if it is enriched.
[ "Registers", "new", "Maths", "and", "adds", "a", "key", "event", "if", "it", "is", "enriched", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/explorer.js#L297-L308
train
zorkow/speech-rule-engine
resources/www/scripts/explorer.js
function(jax) { Explorer.RemoveHook(); Explorer.hook = MathJax.Hub.Register.MessageHook( 'End Math', function(message) { var newid = message[1].id + '-Frame'; var math = document.getElementById(newid); if (jax && newid === Explorer.expanded) { Explorer.ActivateWalker(math, jax); math.focus(); Explorer.expanded = false; } }); }
javascript
function(jax) { Explorer.RemoveHook(); Explorer.hook = MathJax.Hub.Register.MessageHook( 'End Math', function(message) { var newid = message[1].id + '-Frame'; var math = document.getElementById(newid); if (jax && newid === Explorer.expanded) { Explorer.ActivateWalker(math, jax); math.focus(); Explorer.expanded = false; } }); }
[ "function", "(", "jax", ")", "{", "Explorer", ".", "RemoveHook", "(", ")", ";", "Explorer", ".", "hook", "=", "MathJax", ".", "Hub", ".", "Register", ".", "MessageHook", "(", "'End Math'", ",", "function", "(", "message", ")", "{", "var", "newid", "=", "message", "[", "1", "]", ".", "id", "+", "'-Frame'", ";", "var", "math", "=", "document", ".", "getElementById", "(", "newid", ")", ";", "if", "(", "jax", "&&", "newid", "===", "Explorer", ".", "expanded", ")", "{", "Explorer", ".", "ActivateWalker", "(", "math", ",", "jax", ")", ";", "math", ".", "focus", "(", ")", ";", "Explorer", ".", "expanded", "=", "false", ";", "}", "}", ")", ";", "}" ]
Add hook to run at End Math to restart walking on an expansion element.
[ "Add", "hook", "to", "run", "at", "End", "Math", "to", "restart", "walking", "on", "an", "expansion", "element", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/explorer.js#L328-L340
train
zorkow/speech-rule-engine
resources/www/scripts/explorer.js
function() { if (Explorer.hook) { MathJax.Hub.UnRegister.MessageHook(Explorer.hook); Explorer.hook = null; } }
javascript
function() { if (Explorer.hook) { MathJax.Hub.UnRegister.MessageHook(Explorer.hook); Explorer.hook = null; } }
[ "function", "(", ")", "{", "if", "(", "Explorer", ".", "hook", ")", "{", "MathJax", ".", "Hub", ".", "UnRegister", ".", "MessageHook", "(", "Explorer", ".", "hook", ")", ";", "Explorer", ".", "hook", "=", "null", ";", "}", "}" ]
Remove and unregister the explorer hook.
[ "Remove", "and", "unregister", "the", "explorer", "hook", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/explorer.js#L344-L349
train
zorkow/speech-rule-engine
resources/www/scripts/explorer.js
function(script) { var id = script.id + '-Frame'; var sibling = script.previousSibling; if (!sibling) return; var math = sibling.id !== id ? sibling.firstElementChild : sibling; Explorer.AddAria(math); Explorer.AddMouseEvents(math); if (math.className === 'MathJax_MathML') { math = math.firstElementChild; } if (!math) return; math.onkeydown = Explorer.Keydown; Explorer.Flame(math); math.addEventListener( Explorer.focusinEvent, function(event) { if (!Assistive.hook) return; if (!LiveRegion.announced) LiveRegion.Announce(); }); math.addEventListener( Explorer.focusoutEvent, function(event) { if (!Assistive.hook) return; // A fix for Edge. if (Explorer.ignoreFocusOut) { Explorer.ignoreFocusOut = false; if (Explorer.walker.moved === 'enter') { event.target.focus(); return; } } if (Explorer.walker) Explorer.DeactivateWalker(); }); // if (Assistive.getOption('speech')) { Explorer.AddSpeech(math); } // }
javascript
function(script) { var id = script.id + '-Frame'; var sibling = script.previousSibling; if (!sibling) return; var math = sibling.id !== id ? sibling.firstElementChild : sibling; Explorer.AddAria(math); Explorer.AddMouseEvents(math); if (math.className === 'MathJax_MathML') { math = math.firstElementChild; } if (!math) return; math.onkeydown = Explorer.Keydown; Explorer.Flame(math); math.addEventListener( Explorer.focusinEvent, function(event) { if (!Assistive.hook) return; if (!LiveRegion.announced) LiveRegion.Announce(); }); math.addEventListener( Explorer.focusoutEvent, function(event) { if (!Assistive.hook) return; // A fix for Edge. if (Explorer.ignoreFocusOut) { Explorer.ignoreFocusOut = false; if (Explorer.walker.moved === 'enter') { event.target.focus(); return; } } if (Explorer.walker) Explorer.DeactivateWalker(); }); // if (Assistive.getOption('speech')) { Explorer.AddSpeech(math); } // }
[ "function", "(", "script", ")", "{", "var", "id", "=", "script", ".", "id", "+", "'-Frame'", ";", "var", "sibling", "=", "script", ".", "previousSibling", ";", "if", "(", "!", "sibling", ")", "return", ";", "var", "math", "=", "sibling", ".", "id", "!==", "id", "?", "sibling", ".", "firstElementChild", ":", "sibling", ";", "Explorer", ".", "AddAria", "(", "math", ")", ";", "Explorer", ".", "AddMouseEvents", "(", "math", ")", ";", "if", "(", "math", ".", "className", "===", "'MathJax_MathML'", ")", "{", "math", "=", "math", ".", "firstElementChild", ";", "}", "if", "(", "!", "math", ")", "return", ";", "math", ".", "onkeydown", "=", "Explorer", ".", "Keydown", ";", "Explorer", ".", "Flame", "(", "math", ")", ";", "math", ".", "addEventListener", "(", "Explorer", ".", "focusinEvent", ",", "function", "(", "event", ")", "{", "if", "(", "!", "Assistive", ".", "hook", ")", "return", ";", "if", "(", "!", "LiveRegion", ".", "announced", ")", "LiveRegion", ".", "Announce", "(", ")", ";", "}", ")", ";", "math", ".", "addEventListener", "(", "Explorer", ".", "focusoutEvent", ",", "function", "(", "event", ")", "{", "if", "(", "!", "Assistive", ".", "hook", ")", "return", ";", "if", "(", "Explorer", ".", "ignoreFocusOut", ")", "{", "Explorer", ".", "ignoreFocusOut", "=", "false", ";", "if", "(", "Explorer", ".", "walker", ".", "moved", "===", "'enter'", ")", "{", "event", ".", "target", ".", "focus", "(", ")", ";", "return", ";", "}", "}", "if", "(", "Explorer", ".", "walker", ")", "Explorer", ".", "DeactivateWalker", "(", ")", ";", "}", ")", ";", "if", "(", "Assistive", ".", "getOption", "(", "'speech'", ")", ")", "{", "Explorer", ".", "AddSpeech", "(", "math", ")", ";", "}", "}" ]
Adds a key event to an enriched jax.
[ "Adds", "a", "key", "event", "to", "an", "enriched", "jax", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/explorer.js#L359-L397
train
zorkow/speech-rule-engine
resources/www/scripts/explorer.js
function(math) { var id = math.id; var jax = MathJax.Hub.getJaxFor(id); var mathml = jax.root.toMathML(); if (!math.getAttribute('haslabel')) { Explorer.AddMathLabel(mathml, id); } if (math.getAttribute('hasspeech')) return; switch (Assistive.getOption('generation')) { case 'eager': Explorer.AddSpeechEager(mathml, id); break; case 'mixed': var complexity = math.querySelectorAll('[data-semantic-complexity]'); if (complexity.length >= Assistive.eagerComplexity) { Explorer.AddSpeechEager(mathml, id); } break; case 'lazy': default: break; } }
javascript
function(math) { var id = math.id; var jax = MathJax.Hub.getJaxFor(id); var mathml = jax.root.toMathML(); if (!math.getAttribute('haslabel')) { Explorer.AddMathLabel(mathml, id); } if (math.getAttribute('hasspeech')) return; switch (Assistive.getOption('generation')) { case 'eager': Explorer.AddSpeechEager(mathml, id); break; case 'mixed': var complexity = math.querySelectorAll('[data-semantic-complexity]'); if (complexity.length >= Assistive.eagerComplexity) { Explorer.AddSpeechEager(mathml, id); } break; case 'lazy': default: break; } }
[ "function", "(", "math", ")", "{", "var", "id", "=", "math", ".", "id", ";", "var", "jax", "=", "MathJax", ".", "Hub", ".", "getJaxFor", "(", "id", ")", ";", "var", "mathml", "=", "jax", ".", "root", ".", "toMathML", "(", ")", ";", "if", "(", "!", "math", ".", "getAttribute", "(", "'haslabel'", ")", ")", "{", "Explorer", ".", "AddMathLabel", "(", "mathml", ",", "id", ")", ";", "}", "if", "(", "math", ".", "getAttribute", "(", "'hasspeech'", ")", ")", "return", ";", "switch", "(", "Assistive", ".", "getOption", "(", "'generation'", ")", ")", "{", "case", "'eager'", ":", "Explorer", ".", "AddSpeechEager", "(", "mathml", ",", "id", ")", ";", "break", ";", "case", "'mixed'", ":", "var", "complexity", "=", "math", ".", "querySelectorAll", "(", "'[data-semantic-complexity]'", ")", ";", "if", "(", "complexity", ".", "length", ">=", "Assistive", ".", "eagerComplexity", ")", "{", "Explorer", ".", "AddSpeechEager", "(", "mathml", ",", "id", ")", ";", "}", "break", ";", "case", "'lazy'", ":", "default", ":", "break", ";", "}", "}" ]
Add speech output.
[ "Add", "speech", "output", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/explorer.js#L401-L423
train
zorkow/speech-rule-engine
resources/www/scripts/explorer.js
function(mathml, id) { Explorer.MakeSpeechTask( mathml, id, sre.TreeSpeechGenerator, function(math, speech) {math.setAttribute('hasspeech', 'true');}, 5); }
javascript
function(mathml, id) { Explorer.MakeSpeechTask( mathml, id, sre.TreeSpeechGenerator, function(math, speech) {math.setAttribute('hasspeech', 'true');}, 5); }
[ "function", "(", "mathml", ",", "id", ")", "{", "Explorer", ".", "MakeSpeechTask", "(", "mathml", ",", "id", ",", "sre", ".", "TreeSpeechGenerator", ",", "function", "(", "math", ",", "speech", ")", "{", "math", ".", "setAttribute", "(", "'hasspeech'", ",", "'true'", ")", ";", "}", ",", "5", ")", ";", "}" ]
Adds speech strings to the node using a web worker.
[ "Adds", "speech", "strings", "to", "the", "node", "using", "a", "web", "worker", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/explorer.js#L434-L438
train
zorkow/speech-rule-engine
resources/www/scripts/explorer.js
function(mathml, id) { Explorer.MakeSpeechTask( mathml, id, sre.SummarySpeechGenerator, function(math, speech) { math.setAttribute('haslabel', 'true'); math.setAttribute('aria-label', speech);}, 5); }
javascript
function(mathml, id) { Explorer.MakeSpeechTask( mathml, id, sre.SummarySpeechGenerator, function(math, speech) { math.setAttribute('haslabel', 'true'); math.setAttribute('aria-label', speech);}, 5); }
[ "function", "(", "mathml", ",", "id", ")", "{", "Explorer", ".", "MakeSpeechTask", "(", "mathml", ",", "id", ",", "sre", ".", "SummarySpeechGenerator", ",", "function", "(", "math", ",", "speech", ")", "{", "math", ".", "setAttribute", "(", "'haslabel'", ",", "'true'", ")", ";", "math", ".", "setAttribute", "(", "'aria-label'", ",", "speech", ")", ";", "}", ",", "5", ")", ";", "}" ]
Attaches the Math expression as an aria label.
[ "Attaches", "the", "Math", "expression", "as", "an", "aria", "label", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/explorer.js#L442-L449
train
zorkow/speech-rule-engine
resources/www/scripts/explorer.js
function(mathml, id, constructor, onSpeech, time) { var messageID = Explorer.AddMessage(); setTimeout(function() { var speechGenerator = new constructor(); var math = document.getElementById(id); var dummy = new sre.DummyWalker( math, speechGenerator, Explorer.highlighter, mathml); var speech = dummy.speech(); if (speech) { onSpeech(math, speech); } Explorer.RemoveMessage(messageID); }, time); }
javascript
function(mathml, id, constructor, onSpeech, time) { var messageID = Explorer.AddMessage(); setTimeout(function() { var speechGenerator = new constructor(); var math = document.getElementById(id); var dummy = new sre.DummyWalker( math, speechGenerator, Explorer.highlighter, mathml); var speech = dummy.speech(); if (speech) { onSpeech(math, speech); } Explorer.RemoveMessage(messageID); }, time); }
[ "function", "(", "mathml", ",", "id", ",", "constructor", ",", "onSpeech", ",", "time", ")", "{", "var", "messageID", "=", "Explorer", ".", "AddMessage", "(", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "var", "speechGenerator", "=", "new", "constructor", "(", ")", ";", "var", "math", "=", "document", ".", "getElementById", "(", "id", ")", ";", "var", "dummy", "=", "new", "sre", ".", "DummyWalker", "(", "math", ",", "speechGenerator", ",", "Explorer", ".", "highlighter", ",", "mathml", ")", ";", "var", "speech", "=", "dummy", ".", "speech", "(", ")", ";", "if", "(", "speech", ")", "{", "onSpeech", "(", "math", ",", "speech", ")", ";", "}", "Explorer", ".", "RemoveMessage", "(", "messageID", ")", ";", "}", ",", "time", ")", ";", "}" ]
The actual speech task generator.
[ "The", "actual", "speech", "task", "generator", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/explorer.js#L453-L466
train
zorkow/speech-rule-engine
resources/www/scripts/explorer.js
function(event) { if (event.keyCode === KEY.ESCAPE) { if (!Explorer.walker) return; Explorer.RemoveHook(); Explorer.DeactivateWalker(); FALSE(event); return; } // If walker is active we redirect there. if (Explorer.walker && Explorer.walker.isActive()) { if (typeof(Explorer.walker.modifier) !== 'undefined') { Explorer.walker.modifier = event.shiftKey; } var move = Explorer.walker.move(event.keyCode); if (move === null) return; if (move) { if (Explorer.walker.moved === 'expand') { Explorer.expanded = Explorer.walker.node.id; // This sometimes blurs in Edge and sometimes it does not. if (MathJax.Hub.Browser.isEdge) { Explorer.ignoreFocusOut = true; Explorer.DeactivateWalker(); return; } // This does not blur in FF, IE. if (MathJax.Hub.Browser.isFirefox || MathJax.Hub.Browser.isMSIE) { Explorer.DeactivateWalker(); return; } } Explorer.liveRegion.Update(Explorer.walker.speech()); Explorer.Highlight(); } else { Explorer.PlayEarcon(); } FALSE(event); return; } var math = event.target; if (event.keyCode === KEY.SPACE) { if (event.shiftKey && Assistive.hook) { var jax = MathJax.Hub.getJaxFor(math); Explorer.ActivateWalker(math, jax); Explorer.AddHook(jax); } else { MathJax.Extension.MathEvents.Event.ContextMenu(event, math); } FALSE(event); return; } }
javascript
function(event) { if (event.keyCode === KEY.ESCAPE) { if (!Explorer.walker) return; Explorer.RemoveHook(); Explorer.DeactivateWalker(); FALSE(event); return; } // If walker is active we redirect there. if (Explorer.walker && Explorer.walker.isActive()) { if (typeof(Explorer.walker.modifier) !== 'undefined') { Explorer.walker.modifier = event.shiftKey; } var move = Explorer.walker.move(event.keyCode); if (move === null) return; if (move) { if (Explorer.walker.moved === 'expand') { Explorer.expanded = Explorer.walker.node.id; // This sometimes blurs in Edge and sometimes it does not. if (MathJax.Hub.Browser.isEdge) { Explorer.ignoreFocusOut = true; Explorer.DeactivateWalker(); return; } // This does not blur in FF, IE. if (MathJax.Hub.Browser.isFirefox || MathJax.Hub.Browser.isMSIE) { Explorer.DeactivateWalker(); return; } } Explorer.liveRegion.Update(Explorer.walker.speech()); Explorer.Highlight(); } else { Explorer.PlayEarcon(); } FALSE(event); return; } var math = event.target; if (event.keyCode === KEY.SPACE) { if (event.shiftKey && Assistive.hook) { var jax = MathJax.Hub.getJaxFor(math); Explorer.ActivateWalker(math, jax); Explorer.AddHook(jax); } else { MathJax.Extension.MathEvents.Event.ContextMenu(event, math); } FALSE(event); return; } }
[ "function", "(", "event", ")", "{", "if", "(", "event", ".", "keyCode", "===", "KEY", ".", "ESCAPE", ")", "{", "if", "(", "!", "Explorer", ".", "walker", ")", "return", ";", "Explorer", ".", "RemoveHook", "(", ")", ";", "Explorer", ".", "DeactivateWalker", "(", ")", ";", "FALSE", "(", "event", ")", ";", "return", ";", "}", "if", "(", "Explorer", ".", "walker", "&&", "Explorer", ".", "walker", ".", "isActive", "(", ")", ")", "{", "if", "(", "typeof", "(", "Explorer", ".", "walker", ".", "modifier", ")", "!==", "'undefined'", ")", "{", "Explorer", ".", "walker", ".", "modifier", "=", "event", ".", "shiftKey", ";", "}", "var", "move", "=", "Explorer", ".", "walker", ".", "move", "(", "event", ".", "keyCode", ")", ";", "if", "(", "move", "===", "null", ")", "return", ";", "if", "(", "move", ")", "{", "if", "(", "Explorer", ".", "walker", ".", "moved", "===", "'expand'", ")", "{", "Explorer", ".", "expanded", "=", "Explorer", ".", "walker", ".", "node", ".", "id", ";", "if", "(", "MathJax", ".", "Hub", ".", "Browser", ".", "isEdge", ")", "{", "Explorer", ".", "ignoreFocusOut", "=", "true", ";", "Explorer", ".", "DeactivateWalker", "(", ")", ";", "return", ";", "}", "if", "(", "MathJax", ".", "Hub", ".", "Browser", ".", "isFirefox", "||", "MathJax", ".", "Hub", ".", "Browser", ".", "isMSIE", ")", "{", "Explorer", ".", "DeactivateWalker", "(", ")", ";", "return", ";", "}", "}", "Explorer", ".", "liveRegion", ".", "Update", "(", "Explorer", ".", "walker", ".", "speech", "(", ")", ")", ";", "Explorer", ".", "Highlight", "(", ")", ";", "}", "else", "{", "Explorer", ".", "PlayEarcon", "(", ")", ";", "}", "FALSE", "(", "event", ")", ";", "return", ";", "}", "var", "math", "=", "event", ".", "target", ";", "if", "(", "event", ".", "keyCode", "===", "KEY", ".", "SPACE", ")", "{", "if", "(", "event", ".", "shiftKey", "&&", "Assistive", ".", "hook", ")", "{", "var", "jax", "=", "MathJax", ".", "Hub", ".", "getJaxFor", "(", "math", ")", ";", "Explorer", ".", "ActivateWalker", "(", "math", ",", "jax", ")", ";", "Explorer", ".", "AddHook", "(", "jax", ")", ";", "}", "else", "{", "MathJax", ".", "Extension", ".", "MathEvents", ".", "Event", ".", "ContextMenu", "(", "event", ",", "math", ")", ";", "}", "FALSE", "(", "event", ")", ";", "return", ";", "}", "}" ]
Event execution on keydown. Subsumes the same method of MathEvents.
[ "Event", "execution", "on", "keydown", ".", "Subsumes", "the", "same", "method", "of", "MathEvents", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/explorer.js#L470-L520
train
zorkow/speech-rule-engine
resources/www/scripts/explorer.js
function(node) { sre.HighlighterFactory.addEvents( node, {'mouseover': Explorer.MouseOver, 'mouseout': Explorer.MouseOut}, {renderer: MathJax.Hub.outputJax['jax/mml'][0].id, browser: MathJax.Hub.Browser.name} ); }
javascript
function(node) { sre.HighlighterFactory.addEvents( node, {'mouseover': Explorer.MouseOver, 'mouseout': Explorer.MouseOut}, {renderer: MathJax.Hub.outputJax['jax/mml'][0].id, browser: MathJax.Hub.Browser.name} ); }
[ "function", "(", "node", ")", "{", "sre", ".", "HighlighterFactory", ".", "addEvents", "(", "node", ",", "{", "'mouseover'", ":", "Explorer", ".", "MouseOver", ",", "'mouseout'", ":", "Explorer", ".", "MouseOut", "}", ",", "{", "renderer", ":", "MathJax", ".", "Hub", ".", "outputJax", "[", "'jax/mml'", "]", "[", "0", "]", ".", "id", ",", "browser", ":", "MathJax", ".", "Hub", ".", "Browser", ".", "name", "}", ")", ";", "}" ]
Adds mouse events to maction items in an enriched jax.
[ "Adds", "mouse", "events", "to", "maction", "items", "in", "an", "enriched", "jax", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/explorer.js#L532-L540
train
zorkow/speech-rule-engine
resources/www/scripts/explorer.js
function() { Explorer.liveRegion.Clear(); Explorer.liveRegion.Hide(); Explorer.Unhighlight(); Explorer.currentHighlight = null; Explorer.walker.deactivate(); Explorer.walker = null; }
javascript
function() { Explorer.liveRegion.Clear(); Explorer.liveRegion.Hide(); Explorer.Unhighlight(); Explorer.currentHighlight = null; Explorer.walker.deactivate(); Explorer.walker = null; }
[ "function", "(", ")", "{", "Explorer", ".", "liveRegion", ".", "Clear", "(", ")", ";", "Explorer", ".", "liveRegion", ".", "Hide", "(", ")", ";", "Explorer", ".", "Unhighlight", "(", ")", ";", "Explorer", ".", "currentHighlight", "=", "null", ";", "Explorer", ".", "walker", ".", "deactivate", "(", ")", ";", "Explorer", ".", "walker", "=", "null", ";", "}" ]
Deactivates the walker.
[ "Deactivates", "the", "walker", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/explorer.js#L618-L625
train
zorkow/speech-rule-engine
resources/www/scripts/explorer.js
function() { Explorer.Reset(); var speechItems = ['Subtitles', 'Generation']; speechItems.forEach( function(x) { var item = MathJax.Menu.menu.FindId('Accessibility', x); if (item) { item.disabled = !item.disabled; }}); Explorer.Regenerate(); }
javascript
function() { Explorer.Reset(); var speechItems = ['Subtitles', 'Generation']; speechItems.forEach( function(x) { var item = MathJax.Menu.menu.FindId('Accessibility', x); if (item) { item.disabled = !item.disabled; }}); Explorer.Regenerate(); }
[ "function", "(", ")", "{", "Explorer", ".", "Reset", "(", ")", ";", "var", "speechItems", "=", "[", "'Subtitles'", ",", "'Generation'", "]", ";", "speechItems", ".", "forEach", "(", "function", "(", "x", ")", "{", "var", "item", "=", "MathJax", ".", "Menu", ".", "menu", ".", "FindId", "(", "'Accessibility'", ",", "x", ")", ";", "if", "(", "item", ")", "{", "item", ".", "disabled", "=", "!", "item", ".", "disabled", ";", "}", "}", ")", ";", "Explorer", ".", "Regenerate", "(", ")", ";", "}" ]
Toggle speech output.
[ "Toggle", "speech", "output", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/explorer.js#L652-L662
train
zorkow/speech-rule-engine
resources/www/scripts/explorer.js
function() { for (var i = 0, all = MathJax.Hub.getAllJax(), jax; jax = all[i]; i++) { var math = document.getElementById(jax.inputID + '-Frame'); if (math) { math.removeAttribute('hasSpeech'); Explorer.AddSpeech(math); } } }
javascript
function() { for (var i = 0, all = MathJax.Hub.getAllJax(), jax; jax = all[i]; i++) { var math = document.getElementById(jax.inputID + '-Frame'); if (math) { math.removeAttribute('hasSpeech'); Explorer.AddSpeech(math); } } }
[ "function", "(", ")", "{", "for", "(", "var", "i", "=", "0", ",", "all", "=", "MathJax", ".", "Hub", ".", "getAllJax", "(", ")", ",", "jax", ";", "jax", "=", "all", "[", "i", "]", ";", "i", "++", ")", "{", "var", "math", "=", "document", ".", "getElementById", "(", "jax", ".", "inputID", "+", "'-Frame'", ")", ";", "if", "(", "math", ")", "{", "math", ".", "removeAttribute", "(", "'hasSpeech'", ")", ";", "Explorer", ".", "AddSpeech", "(", "math", ")", ";", "}", "}", "}" ]
Regenerates speech.
[ "Regenerates", "speech", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/explorer.js#L666-L674
train
zorkow/speech-rule-engine
resources/www/scripts/semantic-enrich.js
function (jax,id,script) { delete jax.enriched; if (this.config.disabled) return; try { this.running = true; var mml = sre.Enrich.semanticMathmlSync(jax.root.toMathML()); jax.root = MathJax.InputJax.MathML.Parse.prototype.MakeMML(mml); jax.root.inputID = script.id; jax.enriched = true; this.running = false; } catch (err) { this.running = false; throw err; } }
javascript
function (jax,id,script) { delete jax.enriched; if (this.config.disabled) return; try { this.running = true; var mml = sre.Enrich.semanticMathmlSync(jax.root.toMathML()); jax.root = MathJax.InputJax.MathML.Parse.prototype.MakeMML(mml); jax.root.inputID = script.id; jax.enriched = true; this.running = false; } catch (err) { this.running = false; throw err; } }
[ "function", "(", "jax", ",", "id", ",", "script", ")", "{", "delete", "jax", ".", "enriched", ";", "if", "(", "this", ".", "config", ".", "disabled", ")", "return", ";", "try", "{", "this", ".", "running", "=", "true", ";", "var", "mml", "=", "sre", ".", "Enrich", ".", "semanticMathmlSync", "(", "jax", ".", "root", ".", "toMathML", "(", ")", ")", ";", "jax", ".", "root", "=", "MathJax", ".", "InputJax", ".", "MathML", ".", "Parse", ".", "prototype", ".", "MakeMML", "(", "mml", ")", ";", "jax", ".", "root", ".", "inputID", "=", "script", ".", "id", ";", "jax", ".", "enriched", "=", "true", ";", "this", ".", "running", "=", "false", ";", "}", "catch", "(", "err", ")", "{", "this", ".", "running", "=", "false", ";", "throw", "err", ";", "}", "}" ]
If we are not disabled, Get the enriched MathML and parse it into the jax root. Mark the jax as enriched.
[ "If", "we", "are", "not", "disabled", "Get", "the", "enriched", "MathML", "and", "parse", "it", "into", "the", "jax", "root", ".", "Mark", "the", "jax", "as", "enriched", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/semantic-enrich.js#L52-L66
train
zorkow/speech-rule-engine
resources/www/scripts/semantic-enrich.js
function (update,menu) { this.config.disabled = false; if (update) MathJax.Hub.Queue(["Reprocess",MathJax.Hub]); }
javascript
function (update,menu) { this.config.disabled = false; if (update) MathJax.Hub.Queue(["Reprocess",MathJax.Hub]); }
[ "function", "(", "update", ",", "menu", ")", "{", "this", ".", "config", ".", "disabled", "=", "false", ";", "if", "(", "update", ")", "MathJax", ".", "Hub", ".", "Queue", "(", "[", "\"Reprocess\"", ",", "MathJax", ".", "Hub", "]", ")", ";", "}" ]
Functions to enable and disabled enrichment.
[ "Functions", "to", "enable", "and", "disabled", "enrichment", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/semantic-enrich.js#L70-L73
train
zorkow/speech-rule-engine
resources/www/scripts/accessibility-menu.js
function() { var items = Array(this.modules.length); for (var i = 0, module; module = this.modules[i]; i++) items[i] = module.placeHolder; var menu = MENU.FindId('Accessibility'); if (menu) { items.unshift(ITEM.RULE()); menu.submenu.items.push.apply(menu.submenu.items,items); } else { var renderer = (MENU.FindId("Settings","Renderer")||{}).submenu; if (renderer) { // move AssitiveMML and InTabOrder from Renderer to Accessibility menu items.unshift(ITEM.RULE()); items.unshift(renderer.items.pop()); items.unshift(renderer.items.pop()); } items.unshift("Accessibility"); var menu = ITEM.SUBMENU.apply(ITEM.SUBMENU,items); var locale = MENU.IndexOfId('Locale'); if (locale) { MENU.items.splice(locale,0,menu); } else { MENU.items.push(ITEM.RULE(), menu); } } }
javascript
function() { var items = Array(this.modules.length); for (var i = 0, module; module = this.modules[i]; i++) items[i] = module.placeHolder; var menu = MENU.FindId('Accessibility'); if (menu) { items.unshift(ITEM.RULE()); menu.submenu.items.push.apply(menu.submenu.items,items); } else { var renderer = (MENU.FindId("Settings","Renderer")||{}).submenu; if (renderer) { // move AssitiveMML and InTabOrder from Renderer to Accessibility menu items.unshift(ITEM.RULE()); items.unshift(renderer.items.pop()); items.unshift(renderer.items.pop()); } items.unshift("Accessibility"); var menu = ITEM.SUBMENU.apply(ITEM.SUBMENU,items); var locale = MENU.IndexOfId('Locale'); if (locale) { MENU.items.splice(locale,0,menu); } else { MENU.items.push(ITEM.RULE(), menu); } } }
[ "function", "(", ")", "{", "var", "items", "=", "Array", "(", "this", ".", "modules", ".", "length", ")", ";", "for", "(", "var", "i", "=", "0", ",", "module", ";", "module", "=", "this", ".", "modules", "[", "i", "]", ";", "i", "++", ")", "items", "[", "i", "]", "=", "module", ".", "placeHolder", ";", "var", "menu", "=", "MENU", ".", "FindId", "(", "'Accessibility'", ")", ";", "if", "(", "menu", ")", "{", "items", ".", "unshift", "(", "ITEM", ".", "RULE", "(", ")", ")", ";", "menu", ".", "submenu", ".", "items", ".", "push", ".", "apply", "(", "menu", ".", "submenu", ".", "items", ",", "items", ")", ";", "}", "else", "{", "var", "renderer", "=", "(", "MENU", ".", "FindId", "(", "\"Settings\"", ",", "\"Renderer\"", ")", "||", "{", "}", ")", ".", "submenu", ";", "if", "(", "renderer", ")", "{", "items", ".", "unshift", "(", "ITEM", ".", "RULE", "(", ")", ")", ";", "items", ".", "unshift", "(", "renderer", ".", "items", ".", "pop", "(", ")", ")", ";", "items", ".", "unshift", "(", "renderer", ".", "items", ".", "pop", "(", ")", ")", ";", "}", "items", ".", "unshift", "(", "\"Accessibility\"", ")", ";", "var", "menu", "=", "ITEM", ".", "SUBMENU", ".", "apply", "(", "ITEM", ".", "SUBMENU", ",", "items", ")", ";", "var", "locale", "=", "MENU", ".", "IndexOfId", "(", "'Locale'", ")", ";", "if", "(", "locale", ")", "{", "MENU", ".", "items", ".", "splice", "(", "locale", ",", "0", ",", "menu", ")", ";", "}", "else", "{", "MENU", ".", "items", ".", "push", "(", "ITEM", ".", "RULE", "(", ")", ",", "menu", ")", ";", "}", "}", "}" ]
Attaches the menu items;
[ "Attaches", "the", "menu", "items", ";" ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/accessibility-menu.js#L67-L91
train
rofrischmann/react-look
scripts/preparePackages.js
copyLICENSE
function copyLICENSE(pkg) { fs.copy(__dirname + '/../LICENSE', __dirname + '/../packages/' + pkg + '/LICENSE', err => { errorOnFail(err) console.log('LICENSE was successfully copied into the ' + pkg + ' package.') }) }
javascript
function copyLICENSE(pkg) { fs.copy(__dirname + '/../LICENSE', __dirname + '/../packages/' + pkg + '/LICENSE', err => { errorOnFail(err) console.log('LICENSE was successfully copied into the ' + pkg + ' package.') }) }
[ "function", "copyLICENSE", "(", "pkg", ")", "{", "fs", ".", "copy", "(", "__dirname", "+", "'/../LICENSE'", ",", "__dirname", "+", "'/../packages/'", "+", "pkg", "+", "'/LICENSE'", ",", "err", "=>", "{", "errorOnFail", "(", "err", ")", "console", ".", "log", "(", "'LICENSE was successfully copied into the '", "+", "pkg", "+", "' package.'", ")", "}", ")", "}" ]
Copies LICENSE into a pgk subfolder
[ "Copies", "LICENSE", "into", "a", "pgk", "subfolder" ]
bcc01653328e6298ae46af14c91958874e8baf92
https://github.com/rofrischmann/react-look/blob/bcc01653328e6298ae46af14c91958874e8baf92/scripts/preparePackages.js#L17-L22
train
rofrischmann/react-look
scripts/preparePackages.js
updateVersion
function updateVersion(pkg) { fs.readFile(__dirname + '/../package.json', 'utf8', (err, data) => { errorOnFail(err) const globalVersion = JSON.parse(data).version fs.readFile(__dirname + '/../packages/' + pkg + '/package.json', (err, data) => { errorOnFail(err) const packageJSON = JSON.parse(data) packageJSON.version = globalVersion // Update react-look-core dependency version if (pkg !== 'react-look-core') { packageJSON.dependencies['react-look-core'] = '^' + globalVersion } // Update react-look dependency version if (pkg === 'react-look-test-utils') { packageJSON.peerDependencies['react-look'] = '^' + globalVersion } const newPackageJSON = JSON.stringify(packageJSON, null, 4) fs.writeFile(__dirname + '/../packages/' + pkg + '/package.json', newPackageJSON, err => { errorOnFail(err) console.log('Successfully updated ' + pkg + ' version and react-look-core dependency version to ' + globalVersion + '.') }) }) }) }
javascript
function updateVersion(pkg) { fs.readFile(__dirname + '/../package.json', 'utf8', (err, data) => { errorOnFail(err) const globalVersion = JSON.parse(data).version fs.readFile(__dirname + '/../packages/' + pkg + '/package.json', (err, data) => { errorOnFail(err) const packageJSON = JSON.parse(data) packageJSON.version = globalVersion // Update react-look-core dependency version if (pkg !== 'react-look-core') { packageJSON.dependencies['react-look-core'] = '^' + globalVersion } // Update react-look dependency version if (pkg === 'react-look-test-utils') { packageJSON.peerDependencies['react-look'] = '^' + globalVersion } const newPackageJSON = JSON.stringify(packageJSON, null, 4) fs.writeFile(__dirname + '/../packages/' + pkg + '/package.json', newPackageJSON, err => { errorOnFail(err) console.log('Successfully updated ' + pkg + ' version and react-look-core dependency version to ' + globalVersion + '.') }) }) }) }
[ "function", "updateVersion", "(", "pkg", ")", "{", "fs", ".", "readFile", "(", "__dirname", "+", "'/../package.json'", ",", "'utf8'", ",", "(", "err", ",", "data", ")", "=>", "{", "errorOnFail", "(", "err", ")", "const", "globalVersion", "=", "JSON", ".", "parse", "(", "data", ")", ".", "version", "fs", ".", "readFile", "(", "__dirname", "+", "'/../packages/'", "+", "pkg", "+", "'/package.json'", ",", "(", "err", ",", "data", ")", "=>", "{", "errorOnFail", "(", "err", ")", "const", "packageJSON", "=", "JSON", ".", "parse", "(", "data", ")", "packageJSON", ".", "version", "=", "globalVersion", "if", "(", "pkg", "!==", "'react-look-core'", ")", "{", "packageJSON", ".", "dependencies", "[", "'react-look-core'", "]", "=", "'^'", "+", "globalVersion", "}", "if", "(", "pkg", "===", "'react-look-test-utils'", ")", "{", "packageJSON", ".", "peerDependencies", "[", "'react-look'", "]", "=", "'^'", "+", "globalVersion", "}", "const", "newPackageJSON", "=", "JSON", ".", "stringify", "(", "packageJSON", ",", "null", ",", "4", ")", "fs", ".", "writeFile", "(", "__dirname", "+", "'/../packages/'", "+", "pkg", "+", "'/package.json'", ",", "newPackageJSON", ",", "err", "=>", "{", "errorOnFail", "(", "err", ")", "console", ".", "log", "(", "'Successfully updated '", "+", "pkg", "+", "' version and react-look-core dependency version to '", "+", "globalVersion", "+", "'.'", ")", "}", ")", "}", ")", "}", ")", "}" ]
Updates the package.json version of a given pkg with the global package.json version
[ "Updates", "the", "package", ".", "json", "version", "of", "a", "given", "pkg", "with", "the", "global", "package", ".", "json", "version" ]
bcc01653328e6298ae46af14c91958874e8baf92
https://github.com/rofrischmann/react-look/blob/bcc01653328e6298ae46af14c91958874e8baf92/scripts/preparePackages.js#L26-L55
train
zorkow/speech-rule-engine
src/semantic_tree/semantic_node.js
function(tag, nodes) { var xmlNodes = nodes.map(function(x) {return x.xml(xml, opt_brief);}); var tagNode = xml.createElementNS('', tag); for (var i = 0, child; child = xmlNodes[i]; i++) { tagNode.appendChild(child); } return tagNode; }
javascript
function(tag, nodes) { var xmlNodes = nodes.map(function(x) {return x.xml(xml, opt_brief);}); var tagNode = xml.createElementNS('', tag); for (var i = 0, child; child = xmlNodes[i]; i++) { tagNode.appendChild(child); } return tagNode; }
[ "function", "(", "tag", ",", "nodes", ")", "{", "var", "xmlNodes", "=", "nodes", ".", "map", "(", "function", "(", "x", ")", "{", "return", "x", ".", "xml", "(", "xml", ",", "opt_brief", ")", ";", "}", ")", ";", "var", "tagNode", "=", "xml", ".", "createElementNS", "(", "''", ",", "tag", ")", ";", "for", "(", "var", "i", "=", "0", ",", "child", ";", "child", "=", "xmlNodes", "[", "i", "]", ";", "i", "++", ")", "{", "tagNode", ".", "appendChild", "(", "child", ")", ";", "}", "return", "tagNode", ";", "}" ]
Translates a list of nodes into XML representation. @param {string} tag Name of the enclosing tag. @param {!Array.<!sre.SemanticNode>} nodes A list of nodes. @return {Node} An XML representation of the node list.
[ "Translates", "a", "list", "of", "nodes", "into", "XML", "representation", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/src/semantic_tree/semantic_node.js#L144-L151
train
zorkow/speech-rule-engine
resources/www/scripts/auto-collapse.js
function (element) { if (this.config.disabled) return; this.GetContainerWidths(element); var jax = HUB.getAllJax(element); var state = {collapse: [], jax: jax, m: jax.length, i: 0, changed:false}; return this.collapseState(state); }
javascript
function (element) { if (this.config.disabled) return; this.GetContainerWidths(element); var jax = HUB.getAllJax(element); var state = {collapse: [], jax: jax, m: jax.length, i: 0, changed:false}; return this.collapseState(state); }
[ "function", "(", "element", ")", "{", "if", "(", "this", ".", "config", ".", "disabled", ")", "return", ";", "this", ".", "GetContainerWidths", "(", "element", ")", ";", "var", "jax", "=", "HUB", ".", "getAllJax", "(", "element", ")", ";", "var", "state", "=", "{", "collapse", ":", "[", "]", ",", "jax", ":", "jax", ",", "m", ":", "jax", ".", "length", ",", "i", ":", "0", ",", "changed", ":", "false", "}", ";", "return", "this", ".", "collapseState", "(", "state", ")", ";", "}" ]
Find math that is too wide and collapse it.
[ "Find", "math", "that", "is", "too", "wide", "and", "collapse", "it", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/auto-collapse.js#L158-L164
train
zorkow/speech-rule-engine
resources/www/scripts/auto-collapse.js
function (SRE,state) { var w = SRE.width, m = w, M = 1000000; for (var j = SRE.action.length-1; j >= 0; j--) { var action = SRE.action[j], selection = action.selection; if (w > SRE.cwidth) { action.selection = 1; m = action.SREwidth; M = w; } else { action.selection = 2; } w = action.SREwidth; if (SRE.DOMupdate) { document.getElementById(action.id).setAttribute("selection",action.selection); } else if (action.selection !== selection) { state.changed = true; } } SRE.m = m; SRE.M = M; }
javascript
function (SRE,state) { var w = SRE.width, m = w, M = 1000000; for (var j = SRE.action.length-1; j >= 0; j--) { var action = SRE.action[j], selection = action.selection; if (w > SRE.cwidth) { action.selection = 1; m = action.SREwidth; M = w; } else { action.selection = 2; } w = action.SREwidth; if (SRE.DOMupdate) { document.getElementById(action.id).setAttribute("selection",action.selection); } else if (action.selection !== selection) { state.changed = true; } } SRE.m = m; SRE.M = M; }
[ "function", "(", "SRE", ",", "state", ")", "{", "var", "w", "=", "SRE", ".", "width", ",", "m", "=", "w", ",", "M", "=", "1000000", ";", "for", "(", "var", "j", "=", "SRE", ".", "action", ".", "length", "-", "1", ";", "j", ">=", "0", ";", "j", "--", ")", "{", "var", "action", "=", "SRE", ".", "action", "[", "j", "]", ",", "selection", "=", "action", ".", "selection", ";", "if", "(", "w", ">", "SRE", ".", "cwidth", ")", "{", "action", ".", "selection", "=", "1", ";", "m", "=", "action", ".", "SREwidth", ";", "M", "=", "w", ";", "}", "else", "{", "action", ".", "selection", "=", "2", ";", "}", "w", "=", "action", ".", "SREwidth", ";", "if", "(", "SRE", ".", "DOMupdate", ")", "{", "document", ".", "getElementById", "(", "action", ".", "id", ")", ".", "setAttribute", "(", "\"selection\"", ",", "action", ".", "selection", ")", ";", "}", "else", "if", "(", "action", ".", "selection", "!==", "selection", ")", "{", "state", ".", "changed", "=", "true", ";", "}", "}", "SRE", ".", "m", "=", "m", ";", "SRE", ".", "M", "=", "M", ";", "}" ]
Find the actions that need to be collapsed to acheive the correct width, and retain the sizes that would cause the equation to be expanded or collapsed further.
[ "Find", "the", "actions", "that", "need", "to", "be", "collapsed", "to", "acheive", "the", "correct", "width", "and", "retain", "the", "sizes", "that", "would", "cause", "the", "equation", "to", "be", "expanded", "or", "collapsed", "further", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/auto-collapse.js#L189-L207
train
zorkow/speech-rule-engine
resources/www/scripts/auto-collapse.js
function (jax,state) { if (!jax.root.SRE.actionWidths) { MathJax.OutputJax[jax.outputJax].getMetrics(jax); try {this.computeActionWidths(jax)} catch (err) { if (!err.restart) throw err; return MathJax.Callback.After(["collapseState",this,state],err.restart); } state.changed = true; } return null; }
javascript
function (jax,state) { if (!jax.root.SRE.actionWidths) { MathJax.OutputJax[jax.outputJax].getMetrics(jax); try {this.computeActionWidths(jax)} catch (err) { if (!err.restart) throw err; return MathJax.Callback.After(["collapseState",this,state],err.restart); } state.changed = true; } return null; }
[ "function", "(", "jax", ",", "state", ")", "{", "if", "(", "!", "jax", ".", "root", ".", "SRE", ".", "actionWidths", ")", "{", "MathJax", ".", "OutputJax", "[", "jax", ".", "outputJax", "]", ".", "getMetrics", "(", "jax", ")", ";", "try", "{", "this", ".", "computeActionWidths", "(", "jax", ")", "}", "catch", "(", "err", ")", "{", "if", "(", "!", "err", ".", "restart", ")", "throw", "err", ";", "return", "MathJax", ".", "Callback", ".", "After", "(", "[", "\"collapseState\"", ",", "this", ",", "state", "]", ",", "err", ".", "restart", ")", ";", "}", "state", ".", "changed", "=", "true", ";", "}", "return", "null", ";", "}" ]
Get the widths of the different collapsings, trapping any restarts, and restarting the process when the event has occurred.
[ "Get", "the", "widths", "of", "the", "different", "collapsings", "trapping", "any", "restarts", "and", "restarting", "the", "process", "when", "the", "event", "has", "occurred", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/auto-collapse.js#L214-L224
train
zorkow/speech-rule-engine
resources/www/scripts/auto-collapse.js
function (jax) { var SRE = jax.root.SRE, actions = SRE.action, j, state = {}; SRE.width = jax.sreGetRootWidth(state); for (j = actions.length-1; j >= 0; j--) actions[j].selection = 2; for (j = actions.length-1; j >= 0; j--) { var action = actions[j]; if (action.SREwidth == null) { action.selection = 1; action.SREwidth = jax.sreGetActionWidth(state,action); } } SRE.actionWidths = true; }
javascript
function (jax) { var SRE = jax.root.SRE, actions = SRE.action, j, state = {}; SRE.width = jax.sreGetRootWidth(state); for (j = actions.length-1; j >= 0; j--) actions[j].selection = 2; for (j = actions.length-1; j >= 0; j--) { var action = actions[j]; if (action.SREwidth == null) { action.selection = 1; action.SREwidth = jax.sreGetActionWidth(state,action); } } SRE.actionWidths = true; }
[ "function", "(", "jax", ")", "{", "var", "SRE", "=", "jax", ".", "root", ".", "SRE", ",", "actions", "=", "SRE", ".", "action", ",", "j", ",", "state", "=", "{", "}", ";", "SRE", ".", "width", "=", "jax", ".", "sreGetRootWidth", "(", "state", ")", ";", "for", "(", "j", "=", "actions", ".", "length", "-", "1", ";", "j", ">=", "0", ";", "j", "--", ")", "actions", "[", "j", "]", ".", "selection", "=", "2", ";", "for", "(", "j", "=", "actions", ".", "length", "-", "1", ";", "j", ">=", "0", ";", "j", "--", ")", "{", "var", "action", "=", "actions", "[", "j", "]", ";", "if", "(", "action", ".", "SREwidth", "==", "null", ")", "{", "action", ".", "selection", "=", "1", ";", "action", ".", "SREwidth", "=", "jax", ".", "sreGetActionWidth", "(", "state", ",", "action", ")", ";", "}", "}", "SRE", ".", "actionWidths", "=", "true", ";", "}" ]
Compute the action widths by collapsing each maction, and recording the width of the complete equation.
[ "Compute", "the", "action", "widths", "by", "collapsing", "each", "maction", "and", "recording", "the", "width", "of", "the", "complete", "equation", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/auto-collapse.js#L229-L241
train
zorkow/speech-rule-engine
resources/www/scripts/collapsible.js
function (mml,id) { var child = this.FindChild(mml,id); return (child ? child.data.join("") : "?"); }
javascript
function (mml,id) { var child = this.FindChild(mml,id); return (child ? child.data.join("") : "?"); }
[ "function", "(", "mml", ",", "id", ")", "{", "var", "child", "=", "this", ".", "FindChild", "(", "mml", ",", "id", ")", ";", "return", "(", "child", "?", "child", ".", "data", ".", "join", "(", "\"\"", ")", ":", "\"?\"", ")", ";", "}" ]
Locate child node and return its text
[ "Locate", "child", "node", "and", "return", "its", "text" ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/collapsible.js#L303-L306
train
zorkow/speech-rule-engine
resources/www/scripts/collapsible.js
function (mml) { this.UncollapseChild(mml,1); if (mml.complexity > this.COLLAPSE.fenced) { if (mml.attr["data-semantic-role"] === "leftright") { var marker = mml.data[0].data.join("") + mml.data[mml.data.length-1].data.join(""); mml = this.MakeAction(this.Marker(marker),mml); } } return mml; }
javascript
function (mml) { this.UncollapseChild(mml,1); if (mml.complexity > this.COLLAPSE.fenced) { if (mml.attr["data-semantic-role"] === "leftright") { var marker = mml.data[0].data.join("") + mml.data[mml.data.length-1].data.join(""); mml = this.MakeAction(this.Marker(marker),mml); } } return mml; }
[ "function", "(", "mml", ")", "{", "this", ".", "UncollapseChild", "(", "mml", ",", "1", ")", ";", "if", "(", "mml", ".", "complexity", ">", "this", ".", "COLLAPSE", ".", "fenced", ")", "{", "if", "(", "mml", ".", "attr", "[", "\"data-semantic-role\"", "]", "===", "\"leftright\"", ")", "{", "var", "marker", "=", "mml", ".", "data", "[", "0", "]", ".", "data", ".", "join", "(", "\"\"", ")", "+", "mml", ".", "data", "[", "mml", ".", "data", ".", "length", "-", "1", "]", ".", "data", ".", "join", "(", "\"\"", ")", ";", "mml", "=", "this", ".", "MakeAction", "(", "this", ".", "Marker", "(", "marker", ")", ",", "mml", ")", ";", "}", "}", "return", "mml", ";", "}" ]
For fenced elements, if the contents are collapsed, collapse the fence instead.
[ "For", "fenced", "elements", "if", "the", "contents", "are", "collapsed", "collapse", "the", "fence", "instead", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/collapsible.js#L336-L345
train
zorkow/speech-rule-engine
resources/www/scripts/collapsible.js
function (mml) { this.UncollapseChild(mml,0); if (mml.complexity > this.COLLAPSE.sqrt) mml = this.MakeAction(this.Marker(this.MARKER.sqrt),mml); return mml; }
javascript
function (mml) { this.UncollapseChild(mml,0); if (mml.complexity > this.COLLAPSE.sqrt) mml = this.MakeAction(this.Marker(this.MARKER.sqrt),mml); return mml; }
[ "function", "(", "mml", ")", "{", "this", ".", "UncollapseChild", "(", "mml", ",", "0", ")", ";", "if", "(", "mml", ".", "complexity", ">", "this", ".", "COLLAPSE", ".", "sqrt", ")", "mml", "=", "this", ".", "MakeAction", "(", "this", ".", "Marker", "(", "this", ".", "MARKER", ".", "sqrt", ")", ",", "mml", ")", ";", "return", "mml", ";", "}" ]
For sqrt elements, if the contents are collapsed, collapse the sqrt instead.
[ "For", "sqrt", "elements", "if", "the", "contents", "are", "collapsed", "collapse", "the", "sqrt", "instead", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/collapsible.js#L364-L369
train
zorkow/speech-rule-engine
resources/www/scripts/collapsible.js
function (mml) { if (this.SplitAttribute(mml,"children").length === 1) { var child = (mml.data.length === 1 && mml.data[0].inferred ? mml.data[0] : mml); if (child.data[0] && child.data[0].collapsible) { // // Move menclose into the maction element // var maction = child.data[0]; child.SetData(0,maction.data[1]); maction.SetData(1,mml); mml = maction; } } return mml; }
javascript
function (mml) { if (this.SplitAttribute(mml,"children").length === 1) { var child = (mml.data.length === 1 && mml.data[0].inferred ? mml.data[0] : mml); if (child.data[0] && child.data[0].collapsible) { // // Move menclose into the maction element // var maction = child.data[0]; child.SetData(0,maction.data[1]); maction.SetData(1,mml); mml = maction; } } return mml; }
[ "function", "(", "mml", ")", "{", "if", "(", "this", ".", "SplitAttribute", "(", "mml", ",", "\"children\"", ")", ".", "length", "===", "1", ")", "{", "var", "child", "=", "(", "mml", ".", "data", ".", "length", "===", "1", "&&", "mml", ".", "data", "[", "0", "]", ".", "inferred", "?", "mml", ".", "data", "[", "0", "]", ":", "mml", ")", ";", "if", "(", "child", ".", "data", "[", "0", "]", "&&", "child", ".", "data", "[", "0", "]", ".", "collapsible", ")", "{", "var", "maction", "=", "child", ".", "data", "[", "0", "]", ";", "child", ".", "SetData", "(", "0", ",", "maction", ".", "data", "[", "1", "]", ")", ";", "maction", ".", "SetData", "(", "1", ",", "mml", ")", ";", "mml", "=", "maction", ";", "}", "}", "return", "mml", ";", "}" ]
For enclose, include enclosure in collapsed child, if any
[ "For", "enclose", "include", "enclosure", "in", "collapsed", "child", "if", "any" ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/collapsible.js#L380-L394
train
zorkow/speech-rule-engine
resources/www/scripts/collapsible.js
function (mml) { if (mml.complexity > this.COLLAPSE.bigop || mml.data[0].type !== "mo") { var id = this.SplitAttribute(mml,"content").pop(); var op = Collapsible.FindChildText(mml,id); mml = this.MakeAction(this.Marker(op),mml); } return mml; }
javascript
function (mml) { if (mml.complexity > this.COLLAPSE.bigop || mml.data[0].type !== "mo") { var id = this.SplitAttribute(mml,"content").pop(); var op = Collapsible.FindChildText(mml,id); mml = this.MakeAction(this.Marker(op),mml); } return mml; }
[ "function", "(", "mml", ")", "{", "if", "(", "mml", ".", "complexity", ">", "this", ".", "COLLAPSE", ".", "bigop", "||", "mml", ".", "data", "[", "0", "]", ".", "type", "!==", "\"mo\"", ")", "{", "var", "id", "=", "this", ".", "SplitAttribute", "(", "mml", ",", "\"content\"", ")", ".", "pop", "(", ")", ";", "var", "op", "=", "Collapsible", ".", "FindChildText", "(", "mml", ",", "id", ")", ";", "mml", "=", "this", ".", "MakeAction", "(", "this", ".", "Marker", "(", "op", ")", ",", "mml", ")", ";", "}", "return", "mml", ";", "}" ]
For bigops, get the character to use from the largeop at its core.
[ "For", "bigops", "get", "the", "character", "to", "use", "from", "the", "largeop", "at", "its", "core", "." ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/collapsible.js#L399-L406
train
zorkow/speech-rule-engine
resources/www/scripts/collapsible.js
function (mml) { if (mml.complexity > this.COLLAPSE.relseq) { var content = this.SplitAttribute(mml,"content"); var marker = Collapsible.FindChildText(mml,content[0]); if (content.length > 1) marker += "\u22EF"; mml = this.MakeAction(this.Marker(marker),mml); } return mml; }
javascript
function (mml) { if (mml.complexity > this.COLLAPSE.relseq) { var content = this.SplitAttribute(mml,"content"); var marker = Collapsible.FindChildText(mml,content[0]); if (content.length > 1) marker += "\u22EF"; mml = this.MakeAction(this.Marker(marker),mml); } return mml; }
[ "function", "(", "mml", ")", "{", "if", "(", "mml", ".", "complexity", ">", "this", ".", "COLLAPSE", ".", "relseq", ")", "{", "var", "content", "=", "this", ".", "SplitAttribute", "(", "mml", ",", "\"content\"", ")", ";", "var", "marker", "=", "Collapsible", ".", "FindChildText", "(", "mml", ",", "content", "[", "0", "]", ")", ";", "if", "(", "content", ".", "length", ">", "1", ")", "marker", "+=", "\"\\u22EF\"", ";", "\\u22EF", "}", "mml", "=", "this", ".", "MakeAction", "(", "this", ".", "Marker", "(", "marker", ")", ",", "mml", ")", ";", "}" ]
For multirel and relseq, use proper symbol
[ "For", "multirel", "and", "relseq", "use", "proper", "symbol" ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/collapsible.js#L419-L427
train
zorkow/speech-rule-engine
resources/www/scripts/collapsible.js
function (mml) { this.UncollapseChild(mml,0,2); if (mml.complexity > this.COLLAPSE.superscript) mml = this.MakeAction(this.Marker(this.MARKER.superscript),mml); return mml; }
javascript
function (mml) { this.UncollapseChild(mml,0,2); if (mml.complexity > this.COLLAPSE.superscript) mml = this.MakeAction(this.Marker(this.MARKER.superscript),mml); return mml; }
[ "function", "(", "mml", ")", "{", "this", ".", "UncollapseChild", "(", "mml", ",", "0", ",", "2", ")", ";", "if", "(", "mml", ".", "complexity", ">", "this", ".", "COLLAPSE", ".", "superscript", ")", "mml", "=", "this", ".", "MakeAction", "(", "this", ".", "Marker", "(", "this", ".", "MARKER", ".", "superscript", ")", ",", "mml", ")", ";", "return", "mml", ";", "}" ]
Include super- and subscripts into a collapsed base
[ "Include", "super", "-", "and", "subscripts", "into", "a", "collapsed", "base" ]
d4d9dc9c6b4144897b60a90177d116e9d3777d71
https://github.com/zorkow/speech-rule-engine/blob/d4d9dc9c6b4144897b60a90177d116e9d3777d71/resources/www/scripts/collapsible.js#L440-L445
train
Runnable/ponos
examples/basic-worker.js
basicWorker
function basicWorker (job) { return Promise.try(() => { const tid = getNamespace('ponos').get('tid') if (!job.message) { throw new WorkerStopError('message is required', { tid: tid }) } console.log(`hello world: ${job.message}. tid: ${tid}`) }) }
javascript
function basicWorker (job) { return Promise.try(() => { const tid = getNamespace('ponos').get('tid') if (!job.message) { throw new WorkerStopError('message is required', { tid: tid }) } console.log(`hello world: ${job.message}. tid: ${tid}`) }) }
[ "function", "basicWorker", "(", "job", ")", "{", "return", "Promise", ".", "try", "(", "(", ")", "=>", "{", "const", "tid", "=", "getNamespace", "(", "'ponos'", ")", ".", "get", "(", "'tid'", ")", "if", "(", "!", "job", ".", "message", ")", "{", "throw", "new", "WorkerStopError", "(", "'message is required'", ",", "{", "tid", ":", "tid", "}", ")", "}", "console", ".", "log", "(", "`", "${", "job", ".", "message", "}", "${", "tid", "}", "`", ")", "}", ")", "}" ]
A simple worker that will publish a message to a queue. @param {object} job Object describing the job. @param {string} job.queue Queue on which the message will be published. @returns {promise} Resolved when the message is put on the queue.
[ "A", "simple", "worker", "that", "will", "publish", "a", "message", "to", "a", "queue", "." ]
af60007557fb5164b4d49e995e2c294927f67df1
https://github.com/Runnable/ponos/blob/af60007557fb5164b4d49e995e2c294927f67df1/examples/basic-worker.js#L15-L23
train
moay/afterglow
vendor/videojs/plugins/Youtube.js
function(){ var uri = 'https://img.youtube.com/vi/' + this.url.videoId + '/maxresdefault.jpg'; try { var image = new Image(); image.onload = function(){ // Onload may still be called if YouTube returns the 120x90 error thumbnail if('naturalHeight' in image){ if (image.naturalHeight <= 90 || image.naturalWidth <= 120) { return; } } else if(image.height <= 90 || image.width <= 120) { return; } this.poster_ = uri; this.trigger('posterchange'); }.bind(this); image.onerror = function(){}; image.src = uri; } catch(e){} }
javascript
function(){ var uri = 'https://img.youtube.com/vi/' + this.url.videoId + '/maxresdefault.jpg'; try { var image = new Image(); image.onload = function(){ // Onload may still be called if YouTube returns the 120x90 error thumbnail if('naturalHeight' in image){ if (image.naturalHeight <= 90 || image.naturalWidth <= 120) { return; } } else if(image.height <= 90 || image.width <= 120) { return; } this.poster_ = uri; this.trigger('posterchange'); }.bind(this); image.onerror = function(){}; image.src = uri; } catch(e){} }
[ "function", "(", ")", "{", "var", "uri", "=", "'https://img.youtube.com/vi/'", "+", "this", ".", "url", ".", "videoId", "+", "'/maxresdefault.jpg'", ";", "try", "{", "var", "image", "=", "new", "Image", "(", ")", ";", "image", ".", "onload", "=", "function", "(", ")", "{", "if", "(", "'naturalHeight'", "in", "image", ")", "{", "if", "(", "image", ".", "naturalHeight", "<=", "90", "||", "image", ".", "naturalWidth", "<=", "120", ")", "{", "return", ";", "}", "}", "else", "if", "(", "image", ".", "height", "<=", "90", "||", "image", ".", "width", "<=", "120", ")", "{", "return", ";", "}", "this", ".", "poster_", "=", "uri", ";", "this", ".", "trigger", "(", "'posterchange'", ")", ";", "}", ".", "bind", "(", "this", ")", ";", "image", ".", "onerror", "=", "function", "(", ")", "{", "}", ";", "image", ".", "src", "=", "uri", ";", "}", "catch", "(", "e", ")", "{", "}", "}" ]
Tries to get the highest resolution thumbnail available for the video
[ "Tries", "to", "get", "the", "highest", "resolution", "thumbnail", "available", "for", "the", "video" ]
a7fbc889a18188147fcd8418c5d3bb801608b9a7
https://github.com/moay/afterglow/blob/a7fbc889a18188147fcd8418c5d3bb801608b9a7/vendor/videojs/plugins/Youtube.js#L628-L650
train