id
int32
0
58k
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
10,300
ecomfe/echarts-gl
src/util/ZRTextureAtlasSurface.js
function (el, spriteWidth, spriteHeight) { // TODO, inner text, shadow var rect = el.getBoundingRect(); var scaleX = spriteWidth / rect.width; var scaleY = spriteHeight / rect.height; el.position = [-rect.x * scaleX, -rect.y * scaleY]; el.scale = [scaleX, scaleY]; el.update(); }
javascript
function (el, spriteWidth, spriteHeight) { // TODO, inner text, shadow var rect = el.getBoundingRect(); var scaleX = spriteWidth / rect.width; var scaleY = spriteHeight / rect.height; el.position = [-rect.x * scaleX, -rect.y * scaleY]; el.scale = [scaleX, scaleY]; el.update(); }
[ "function", "(", "el", ",", "spriteWidth", ",", "spriteHeight", ")", "{", "// TODO, inner text, shadow", "var", "rect", "=", "el", ".", "getBoundingRect", "(", ")", ";", "var", "scaleX", "=", "spriteWidth", "/", "rect", ".", "width", ";", "var", "scaleY", "=", "spriteHeight", "/", "rect", ".", "height", ";", "el", ".", "position", "=", "[", "-", "rect", ".", "x", "*", "scaleX", ",", "-", "rect", ".", "y", "*", "scaleY", "]", ";", "el", ".", "scale", "=", "[", "scaleX", ",", "scaleY", "]", ";", "el", ".", "update", "(", ")", ";", "}" ]
Fit element size by correct its position and scaling @param {module:zrender/graphic/Displayable} el @param {number} spriteWidth @param {number} spriteHeight
[ "Fit", "element", "size", "by", "correct", "its", "position", "and", "scaling" ]
b59058e1b58d682fbbc602c084a86708b350f703
https://github.com/ecomfe/echarts-gl/blob/b59058e1b58d682fbbc602c084a86708b350f703/src/util/ZRTextureAtlasSurface.js#L149-L158
10,301
ecomfe/echarts-gl
src/util/ZRTextureAtlasSurface.js
function () { for (var i = 0; i < this._textureAtlasNodes.length; i++) { this._textureAtlasNodes[i].clear(); } this._currentNodeIdx = 0; this._zr.clear(); this._coords = {}; }
javascript
function () { for (var i = 0; i < this._textureAtlasNodes.length; i++) { this._textureAtlasNodes[i].clear(); } this._currentNodeIdx = 0; this._zr.clear(); this._coords = {}; }
[ "function", "(", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "_textureAtlasNodes", ".", "length", ";", "i", "++", ")", "{", "this", ".", "_textureAtlasNodes", "[", "i", "]", ".", "clear", "(", ")", ";", "}", "this", ".", "_currentNodeIdx", "=", "0", ";", "this", ".", "_zr", ".", "clear", "(", ")", ";", "this", ".", "_coords", "=", "{", "}", ";", "}" ]
Clear the texture atlas
[ "Clear", "the", "texture", "atlas" ]
b59058e1b58d682fbbc602c084a86708b350f703
https://github.com/ecomfe/echarts-gl/blob/b59058e1b58d682fbbc602c084a86708b350f703/src/util/ZRTextureAtlasSurface.js#L229-L239
10,302
ecomfe/echarts-gl
src/util/ZRTextureAtlasSurface.js
function () { var dpr = this._dpr; return [this._nodeWidth / this._canvas.width * dpr, this._nodeHeight / this._canvas.height * dpr]; }
javascript
function () { var dpr = this._dpr; return [this._nodeWidth / this._canvas.width * dpr, this._nodeHeight / this._canvas.height * dpr]; }
[ "function", "(", ")", "{", "var", "dpr", "=", "this", ".", "_dpr", ";", "return", "[", "this", ".", "_nodeWidth", "/", "this", ".", "_canvas", ".", "width", "*", "dpr", ",", "this", ".", "_nodeHeight", "/", "this", ".", "_canvas", ".", "height", "*", "dpr", "]", ";", "}" ]
Get coord scale after texture atlas is expanded. @return {Array.<number>}
[ "Get", "coord", "scale", "after", "texture", "atlas", "is", "expanded", "." ]
b59058e1b58d682fbbc602c084a86708b350f703
https://github.com/ecomfe/echarts-gl/blob/b59058e1b58d682fbbc602c084a86708b350f703/src/util/ZRTextureAtlasSurface.js#L345-L348
10,303
ecomfe/echarts-gl
src/component/common/Geo3DBuilder.js
function (idx) { var polygons = this._triangulationResults[idx - this._startIndex]; var sideVertexCount = 0; var sideTriangleCount = 0; for (var i = 0; i < polygons.length; i++) { sideVertexCount += polygons[i].points.length / 3; sideTriangleCount += polygons[i].indices.length / 3; } var vertexCount = sideVertexCount * 2 + sideVertexCount * 4; var triangleCount = sideTriangleCount * 2 + sideVertexCount * 2; return { vertexCount: vertexCount, triangleCount: triangleCount }; }
javascript
function (idx) { var polygons = this._triangulationResults[idx - this._startIndex]; var sideVertexCount = 0; var sideTriangleCount = 0; for (var i = 0; i < polygons.length; i++) { sideVertexCount += polygons[i].points.length / 3; sideTriangleCount += polygons[i].indices.length / 3; } var vertexCount = sideVertexCount * 2 + sideVertexCount * 4; var triangleCount = sideTriangleCount * 2 + sideVertexCount * 2; return { vertexCount: vertexCount, triangleCount: triangleCount }; }
[ "function", "(", "idx", ")", "{", "var", "polygons", "=", "this", ".", "_triangulationResults", "[", "idx", "-", "this", ".", "_startIndex", "]", ";", "var", "sideVertexCount", "=", "0", ";", "var", "sideTriangleCount", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "polygons", ".", "length", ";", "i", "++", ")", "{", "sideVertexCount", "+=", "polygons", "[", "i", "]", ".", "points", ".", "length", "/", "3", ";", "sideTriangleCount", "+=", "polygons", "[", "i", "]", ".", "indices", ".", "length", "/", "3", ";", "}", "var", "vertexCount", "=", "sideVertexCount", "*", "2", "+", "sideVertexCount", "*", "4", ";", "var", "triangleCount", "=", "sideTriangleCount", "*", "2", "+", "sideVertexCount", "*", "2", ";", "return", "{", "vertexCount", ":", "vertexCount", ",", "triangleCount", ":", "triangleCount", "}", ";", "}" ]
Get region vertex and triangle count
[ "Get", "region", "vertex", "and", "triangle", "count" ]
b59058e1b58d682fbbc602c084a86708b350f703
https://github.com/ecomfe/echarts-gl/blob/b59058e1b58d682fbbc602c084a86708b350f703/src/component/common/Geo3DBuilder.js#L472-L491
10,304
mde/ejs
lib/ejs.js
getIncludePath
function getIncludePath(path, options) { var includePath; var filePath; var views = options.views; // Abs path if (path.charAt(0) == '/') { includePath = exports.resolveInclude(path.replace(/^\/*/,''), options.root || '/', true); } // Relative paths else { // Look relative to a passed filename first if (options.filename) { filePath = exports.resolveInclude(path, options.filename); if (fs.existsSync(filePath)) { includePath = filePath; } } // Then look in any views directories if (!includePath) { if (Array.isArray(views) && views.some(function (v) { filePath = exports.resolveInclude(path, v, true); return fs.existsSync(filePath); })) { includePath = filePath; } } if (!includePath) { throw new Error('Could not find the include file "' + options.escapeFunction(path) + '"'); } } return includePath; }
javascript
function getIncludePath(path, options) { var includePath; var filePath; var views = options.views; // Abs path if (path.charAt(0) == '/') { includePath = exports.resolveInclude(path.replace(/^\/*/,''), options.root || '/', true); } // Relative paths else { // Look relative to a passed filename first if (options.filename) { filePath = exports.resolveInclude(path, options.filename); if (fs.existsSync(filePath)) { includePath = filePath; } } // Then look in any views directories if (!includePath) { if (Array.isArray(views) && views.some(function (v) { filePath = exports.resolveInclude(path, v, true); return fs.existsSync(filePath); })) { includePath = filePath; } } if (!includePath) { throw new Error('Could not find the include file "' + options.escapeFunction(path) + '"'); } } return includePath; }
[ "function", "getIncludePath", "(", "path", ",", "options", ")", "{", "var", "includePath", ";", "var", "filePath", ";", "var", "views", "=", "options", ".", "views", ";", "// Abs path", "if", "(", "path", ".", "charAt", "(", "0", ")", "==", "'/'", ")", "{", "includePath", "=", "exports", ".", "resolveInclude", "(", "path", ".", "replace", "(", "/", "^\\/*", "/", ",", "''", ")", ",", "options", ".", "root", "||", "'/'", ",", "true", ")", ";", "}", "// Relative paths", "else", "{", "// Look relative to a passed filename first", "if", "(", "options", ".", "filename", ")", "{", "filePath", "=", "exports", ".", "resolveInclude", "(", "path", ",", "options", ".", "filename", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "filePath", ")", ")", "{", "includePath", "=", "filePath", ";", "}", "}", "// Then look in any views directories", "if", "(", "!", "includePath", ")", "{", "if", "(", "Array", ".", "isArray", "(", "views", ")", "&&", "views", ".", "some", "(", "function", "(", "v", ")", "{", "filePath", "=", "exports", ".", "resolveInclude", "(", "path", ",", "v", ",", "true", ")", ";", "return", "fs", ".", "existsSync", "(", "filePath", ")", ";", "}", ")", ")", "{", "includePath", "=", "filePath", ";", "}", "}", "if", "(", "!", "includePath", ")", "{", "throw", "new", "Error", "(", "'Could not find the include file \"'", "+", "options", ".", "escapeFunction", "(", "path", ")", "+", "'\"'", ")", ";", "}", "}", "return", "includePath", ";", "}" ]
Get the path to the included file by Options @param {String} path specified path @param {Options} options compilation options @return {String}
[ "Get", "the", "path", "to", "the", "included", "file", "by", "Options" ]
f2c77d78d2bbd4c61e8d6fcf3df38ab528a6bdac
https://github.com/mde/ejs/blob/f2c77d78d2bbd4c61e8d6fcf3df38ab528a6bdac/lib/ejs.js#L136-L169
10,305
mde/ejs
lib/ejs.js
rethrow
function rethrow(err, str, flnm, lineno, esc){ var lines = str.split('\n'); var start = Math.max(lineno - 3, 0); var end = Math.min(lines.length, lineno + 3); var filename = esc(flnm); // eslint-disable-line // Error context var context = lines.slice(start, end).map(function (line, i){ var curr = i + start + 1; return (curr == lineno ? ' >> ' : ' ') + curr + '| ' + line; }).join('\n'); // Alter exception message err.path = filename; err.message = (filename || 'ejs') + ':' + lineno + '\n' + context + '\n\n' + err.message; throw err; }
javascript
function rethrow(err, str, flnm, lineno, esc){ var lines = str.split('\n'); var start = Math.max(lineno - 3, 0); var end = Math.min(lines.length, lineno + 3); var filename = esc(flnm); // eslint-disable-line // Error context var context = lines.slice(start, end).map(function (line, i){ var curr = i + start + 1; return (curr == lineno ? ' >> ' : ' ') + curr + '| ' + line; }).join('\n'); // Alter exception message err.path = filename; err.message = (filename || 'ejs') + ':' + lineno + '\n' + context + '\n\n' + err.message; throw err; }
[ "function", "rethrow", "(", "err", ",", "str", ",", "flnm", ",", "lineno", ",", "esc", ")", "{", "var", "lines", "=", "str", ".", "split", "(", "'\\n'", ")", ";", "var", "start", "=", "Math", ".", "max", "(", "lineno", "-", "3", ",", "0", ")", ";", "var", "end", "=", "Math", ".", "min", "(", "lines", ".", "length", ",", "lineno", "+", "3", ")", ";", "var", "filename", "=", "esc", "(", "flnm", ")", ";", "// eslint-disable-line", "// Error context", "var", "context", "=", "lines", ".", "slice", "(", "start", ",", "end", ")", ".", "map", "(", "function", "(", "line", ",", "i", ")", "{", "var", "curr", "=", "i", "+", "start", "+", "1", ";", "return", "(", "curr", "==", "lineno", "?", "' >> '", ":", "' '", ")", "+", "curr", "+", "'| '", "+", "line", ";", "}", ")", ".", "join", "(", "'\\n'", ")", ";", "// Alter exception message", "err", ".", "path", "=", "filename", ";", "err", ".", "message", "=", "(", "filename", "||", "'ejs'", ")", "+", "':'", "+", "lineno", "+", "'\\n'", "+", "context", "+", "'\\n\\n'", "+", "err", ".", "message", ";", "throw", "err", ";", "}" ]
Re-throw the given `err` in context to the `str` of ejs, `filename`, and `lineno`. @implements RethrowCallback @memberof module:ejs-internal @param {Error} err Error object @param {String} str EJS source @param {String} filename file name of the EJS file @param {String} lineno line number of the error @static
[ "Re", "-", "throw", "the", "given", "err", "in", "context", "to", "the", "str", "of", "ejs", "filename", "and", "lineno", "." ]
f2c77d78d2bbd4c61e8d6fcf3df38ab528a6bdac
https://github.com/mde/ejs/blob/f2c77d78d2bbd4c61e8d6fcf3df38ab528a6bdac/lib/ejs.js#L333-L355
10,306
jossmac/react-images
lib/Lightbox.js
normalizeSourceSet
function normalizeSourceSet(data) { var sourceSet = data.srcSet || data.srcset; if (Array.isArray(sourceSet)) { return sourceSet.join(); } return sourceSet; }
javascript
function normalizeSourceSet(data) { var sourceSet = data.srcSet || data.srcset; if (Array.isArray(sourceSet)) { return sourceSet.join(); } return sourceSet; }
[ "function", "normalizeSourceSet", "(", "data", ")", "{", "var", "sourceSet", "=", "data", ".", "srcSet", "||", "data", ".", "srcset", ";", "if", "(", "Array", ".", "isArray", "(", "sourceSet", ")", ")", "{", "return", "sourceSet", ".", "join", "(", ")", ";", "}", "return", "sourceSet", ";", "}" ]
consumers sometimes provide incorrect type or casing
[ "consumers", "sometimes", "provide", "incorrect", "type", "or", "casing" ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/lib/Lightbox.js#L76-L84
10,307
jossmac/react-images
examples/dist/common.js
generateCSS
function generateCSS(selector, styleTypes, stringHandlers, useImportant) { var merged = styleTypes.reduce(_util.recursiveMerge); var declarations = {}; var mediaQueries = {}; var pseudoStyles = {}; Object.keys(merged).forEach(function (key) { if (key[0] === ':') { pseudoStyles[key] = merged[key]; } else if (key[0] === '@') { mediaQueries[key] = merged[key]; } else { declarations[key] = merged[key]; } }); return generateCSSRuleset(selector, declarations, stringHandlers, useImportant) + Object.keys(pseudoStyles).map(function (pseudoSelector) { return generateCSSRuleset(selector + pseudoSelector, pseudoStyles[pseudoSelector], stringHandlers, useImportant); }).join("") + Object.keys(mediaQueries).map(function (mediaQuery) { var ruleset = generateCSS(selector, [mediaQueries[mediaQuery]], stringHandlers, useImportant); return mediaQuery + '{' + ruleset + '}'; }).join(""); }
javascript
function generateCSS(selector, styleTypes, stringHandlers, useImportant) { var merged = styleTypes.reduce(_util.recursiveMerge); var declarations = {}; var mediaQueries = {}; var pseudoStyles = {}; Object.keys(merged).forEach(function (key) { if (key[0] === ':') { pseudoStyles[key] = merged[key]; } else if (key[0] === '@') { mediaQueries[key] = merged[key]; } else { declarations[key] = merged[key]; } }); return generateCSSRuleset(selector, declarations, stringHandlers, useImportant) + Object.keys(pseudoStyles).map(function (pseudoSelector) { return generateCSSRuleset(selector + pseudoSelector, pseudoStyles[pseudoSelector], stringHandlers, useImportant); }).join("") + Object.keys(mediaQueries).map(function (mediaQuery) { var ruleset = generateCSS(selector, [mediaQueries[mediaQuery]], stringHandlers, useImportant); return mediaQuery + '{' + ruleset + '}'; }).join(""); }
[ "function", "generateCSS", "(", "selector", ",", "styleTypes", ",", "stringHandlers", ",", "useImportant", ")", "{", "var", "merged", "=", "styleTypes", ".", "reduce", "(", "_util", ".", "recursiveMerge", ")", ";", "var", "declarations", "=", "{", "}", ";", "var", "mediaQueries", "=", "{", "}", ";", "var", "pseudoStyles", "=", "{", "}", ";", "Object", ".", "keys", "(", "merged", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "key", "[", "0", "]", "===", "':'", ")", "{", "pseudoStyles", "[", "key", "]", "=", "merged", "[", "key", "]", ";", "}", "else", "if", "(", "key", "[", "0", "]", "===", "'@'", ")", "{", "mediaQueries", "[", "key", "]", "=", "merged", "[", "key", "]", ";", "}", "else", "{", "declarations", "[", "key", "]", "=", "merged", "[", "key", "]", ";", "}", "}", ")", ";", "return", "generateCSSRuleset", "(", "selector", ",", "declarations", ",", "stringHandlers", ",", "useImportant", ")", "+", "Object", ".", "keys", "(", "pseudoStyles", ")", ".", "map", "(", "function", "(", "pseudoSelector", ")", "{", "return", "generateCSSRuleset", "(", "selector", "+", "pseudoSelector", ",", "pseudoStyles", "[", "pseudoSelector", "]", ",", "stringHandlers", ",", "useImportant", ")", ";", "}", ")", ".", "join", "(", "\"\"", ")", "+", "Object", ".", "keys", "(", "mediaQueries", ")", ".", "map", "(", "function", "(", "mediaQuery", ")", "{", "var", "ruleset", "=", "generateCSS", "(", "selector", ",", "[", "mediaQueries", "[", "mediaQuery", "]", "]", ",", "stringHandlers", ",", "useImportant", ")", ";", "return", "mediaQuery", "+", "'{'", "+", "ruleset", "+", "'}'", ";", "}", ")", ".", "join", "(", "\"\"", ")", ";", "}" ]
Generate CSS for a selector and some styles. This function handles the media queries, pseudo selectors, and descendant styles that can be used in aphrodite styles. @param {string} selector: A base CSS selector for the styles to be generated with. @param {Object} styleTypes: A list of properties of the return type of StyleSheet.create, e.g. [styles.red, styles.blue]. @param stringHandlers: See `generateCSSRuleset` @param useImportant: See `generateCSSRuleset` To actually generate the CSS special-construct-less styles are passed to `generateCSSRuleset`. For instance, a call to generateCSSInner(".foo", { color: "red", "@media screen": { height: 20, ":hover": { backgroundColor: "black" } }, ":active": { fontWeight: "bold", ">>bar": { _names: { "foo_bar": true }, height: 10, } } }); will make 5 calls to `generateCSSRuleset`: generateCSSRuleset(".foo", { color: "red" }, ...) generateCSSRuleset(".foo:active", { fontWeight: "bold" }, ...) generateCSSRuleset(".foo:active .foo_bar", { height: 10 }, ...) // These 2 will be wrapped in @media screen {} generateCSSRuleset(".foo", { height: 20 }, ...) generateCSSRuleset(".foo:hover", { backgroundColor: "black" }, ...)
[ "Generate", "CSS", "for", "a", "selector", "and", "some", "styles", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L62-L85
10,308
jossmac/react-images
examples/dist/common.js
generateCSSRuleset
function generateCSSRuleset(selector, declarations, stringHandlers, useImportant) { var handledDeclarations = runStringHandlers(declarations, stringHandlers); var prefixedDeclarations = (0, _inlineStylePrefixerStatic2['default'])(handledDeclarations); var prefixedRules = (0, _util.flatten)((0, _util.objectToPairs)(prefixedDeclarations).map(function (_ref) { var _ref2 = _slicedToArray(_ref, 2); var key = _ref2[0]; var value = _ref2[1]; if (Array.isArray(value)) { var _ret = (function () { // inline-style-prefix-all returns an array when there should be // multiple rules, we will flatten to single rules var prefixedValues = []; var unprefixedValues = []; value.forEach(function (v) { if (v.indexOf('-') === 0) { prefixedValues.push(v); } else { unprefixedValues.push(v); } }); prefixedValues.sort(); unprefixedValues.sort(); return { v: prefixedValues.concat(unprefixedValues).map(function (v) { return [key, v]; }) }; })(); if (typeof _ret === 'object') return _ret.v; } return [[key, value]]; })); var rules = prefixedRules.map(function (_ref3) { var _ref32 = _slicedToArray(_ref3, 2); var key = _ref32[0]; var value = _ref32[1]; var stringValue = (0, _util.stringifyValue)(key, value); var ret = (0, _util.kebabifyStyleName)(key) + ':' + stringValue + ';'; return useImportant === false ? ret : (0, _util.importantify)(ret); }).join(""); if (rules) { return selector + '{' + rules + '}'; } else { return ""; } }
javascript
function generateCSSRuleset(selector, declarations, stringHandlers, useImportant) { var handledDeclarations = runStringHandlers(declarations, stringHandlers); var prefixedDeclarations = (0, _inlineStylePrefixerStatic2['default'])(handledDeclarations); var prefixedRules = (0, _util.flatten)((0, _util.objectToPairs)(prefixedDeclarations).map(function (_ref) { var _ref2 = _slicedToArray(_ref, 2); var key = _ref2[0]; var value = _ref2[1]; if (Array.isArray(value)) { var _ret = (function () { // inline-style-prefix-all returns an array when there should be // multiple rules, we will flatten to single rules var prefixedValues = []; var unprefixedValues = []; value.forEach(function (v) { if (v.indexOf('-') === 0) { prefixedValues.push(v); } else { unprefixedValues.push(v); } }); prefixedValues.sort(); unprefixedValues.sort(); return { v: prefixedValues.concat(unprefixedValues).map(function (v) { return [key, v]; }) }; })(); if (typeof _ret === 'object') return _ret.v; } return [[key, value]]; })); var rules = prefixedRules.map(function (_ref3) { var _ref32 = _slicedToArray(_ref3, 2); var key = _ref32[0]; var value = _ref32[1]; var stringValue = (0, _util.stringifyValue)(key, value); var ret = (0, _util.kebabifyStyleName)(key) + ':' + stringValue + ';'; return useImportant === false ? ret : (0, _util.importantify)(ret); }).join(""); if (rules) { return selector + '{' + rules + '}'; } else { return ""; } }
[ "function", "generateCSSRuleset", "(", "selector", ",", "declarations", ",", "stringHandlers", ",", "useImportant", ")", "{", "var", "handledDeclarations", "=", "runStringHandlers", "(", "declarations", ",", "stringHandlers", ")", ";", "var", "prefixedDeclarations", "=", "(", "0", ",", "_inlineStylePrefixerStatic2", "[", "'default'", "]", ")", "(", "handledDeclarations", ")", ";", "var", "prefixedRules", "=", "(", "0", ",", "_util", ".", "flatten", ")", "(", "(", "0", ",", "_util", ".", "objectToPairs", ")", "(", "prefixedDeclarations", ")", ".", "map", "(", "function", "(", "_ref", ")", "{", "var", "_ref2", "=", "_slicedToArray", "(", "_ref", ",", "2", ")", ";", "var", "key", "=", "_ref2", "[", "0", "]", ";", "var", "value", "=", "_ref2", "[", "1", "]", ";", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "var", "_ret", "=", "(", "function", "(", ")", "{", "// inline-style-prefix-all returns an array when there should be", "// multiple rules, we will flatten to single rules", "var", "prefixedValues", "=", "[", "]", ";", "var", "unprefixedValues", "=", "[", "]", ";", "value", ".", "forEach", "(", "function", "(", "v", ")", "{", "if", "(", "v", ".", "indexOf", "(", "'-'", ")", "===", "0", ")", "{", "prefixedValues", ".", "push", "(", "v", ")", ";", "}", "else", "{", "unprefixedValues", ".", "push", "(", "v", ")", ";", "}", "}", ")", ";", "prefixedValues", ".", "sort", "(", ")", ";", "unprefixedValues", ".", "sort", "(", ")", ";", "return", "{", "v", ":", "prefixedValues", ".", "concat", "(", "unprefixedValues", ")", ".", "map", "(", "function", "(", "v", ")", "{", "return", "[", "key", ",", "v", "]", ";", "}", ")", "}", ";", "}", ")", "(", ")", ";", "if", "(", "typeof", "_ret", "===", "'object'", ")", "return", "_ret", ".", "v", ";", "}", "return", "[", "[", "key", ",", "value", "]", "]", ";", "}", ")", ")", ";", "var", "rules", "=", "prefixedRules", ".", "map", "(", "function", "(", "_ref3", ")", "{", "var", "_ref32", "=", "_slicedToArray", "(", "_ref3", ",", "2", ")", ";", "var", "key", "=", "_ref32", "[", "0", "]", ";", "var", "value", "=", "_ref32", "[", "1", "]", ";", "var", "stringValue", "=", "(", "0", ",", "_util", ".", "stringifyValue", ")", "(", "key", ",", "value", ")", ";", "var", "ret", "=", "(", "0", ",", "_util", ".", "kebabifyStyleName", ")", "(", "key", ")", "+", "':'", "+", "stringValue", "+", "';'", ";", "return", "useImportant", "===", "false", "?", "ret", ":", "(", "0", ",", "_util", ".", "importantify", ")", "(", "ret", ")", ";", "}", ")", ".", "join", "(", "\"\"", ")", ";", "if", "(", "rules", ")", "{", "return", "selector", "+", "'{'", "+", "rules", "+", "'}'", ";", "}", "else", "{", "return", "\"\"", ";", "}", "}" ]
Generate a CSS ruleset with the selector and containing the declarations. This function assumes that the given declarations don't contain any special children (such as media queries, pseudo-selectors, or descendant styles). Note that this method does not deal with nesting used for e.g. psuedo-selectors or media queries. That responsibility is left to the `generateCSS` function. @param {string} selector: the selector associated with the ruleset @param {Object} declarations: a map from camelCased CSS property name to CSS property value. @param {Object.<string, function>} stringHandlers: a map from camelCased CSS property name to a function which will map the given value to the value that is output. @param {bool} useImportant: A boolean saying whether to append "!important" to each of the CSS declarations. @returns {string} A string of raw CSS. Examples: generateCSSRuleset(".blah", { color: "red" }) -> ".blah{color: red !important;}" generateCSSRuleset(".blah", { color: "red" }, {}, false) -> ".blah{color: red}" generateCSSRuleset(".blah", { color: "red" }, {color: c => c.toUpperCase}) -> ".blah{color: RED}" generateCSSRuleset(".blah:hover", { color: "red" }) -> ".blah:hover{color: red}"
[ "Generate", "a", "CSS", "ruleset", "with", "the", "selector", "and", "containing", "the", "declarations", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L141-L199
10,309
jossmac/react-images
examples/dist/common.js
fontFamily
function fontFamily(val) { if (Array.isArray(val)) { return val.map(fontFamily).join(","); } else if (typeof val === "object") { injectStyleOnce(val.fontFamily, "@font-face", [val], false); return '"' + val.fontFamily + '"'; } else { return val; } }
javascript
function fontFamily(val) { if (Array.isArray(val)) { return val.map(fontFamily).join(","); } else if (typeof val === "object") { injectStyleOnce(val.fontFamily, "@font-face", [val], false); return '"' + val.fontFamily + '"'; } else { return val; } }
[ "function", "fontFamily", "(", "val", ")", "{", "if", "(", "Array", ".", "isArray", "(", "val", ")", ")", "{", "return", "val", ".", "map", "(", "fontFamily", ")", ".", "join", "(", "\",\"", ")", ";", "}", "else", "if", "(", "typeof", "val", "===", "\"object\"", ")", "{", "injectStyleOnce", "(", "val", ".", "fontFamily", ",", "\"@font-face\"", ",", "[", "val", "]", ",", "false", ")", ";", "return", "'\"'", "+", "val", ".", "fontFamily", "+", "'\"'", ";", "}", "else", "{", "return", "val", ";", "}", "}" ]
With fontFamily we look for objects that are passed in and interpret them as @font-face rules that we need to inject. The value of fontFamily can either be a string (as normal), an object (a single font face), or an array of objects and strings.
[ "With", "fontFamily", "we", "look", "for", "objects", "that", "are", "passed", "in", "and", "interpret", "them", "as" ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L261-L270
10,310
jossmac/react-images
examples/dist/common.js
animationName
function animationName(val) { if (typeof val !== "object") { return val; } // Generate a unique name based on the hash of the object. We can't // just use the hash because the name can't start with a number. // TODO(emily): this probably makes debugging hard, allow a custom // name? var name = 'keyframe_' + (0, _util.hashObject)(val); // Since keyframes need 3 layers of nesting, we use `generateCSS` to // build the inner layers and wrap it in `@keyframes` ourselves. var finalVal = '@keyframes ' + name + '{'; Object.keys(val).forEach(function (key) { finalVal += (0, _generate.generateCSS)(key, [val[key]], stringHandlers, false); }); finalVal += '}'; injectGeneratedCSSOnce(name, finalVal); return name; }
javascript
function animationName(val) { if (typeof val !== "object") { return val; } // Generate a unique name based on the hash of the object. We can't // just use the hash because the name can't start with a number. // TODO(emily): this probably makes debugging hard, allow a custom // name? var name = 'keyframe_' + (0, _util.hashObject)(val); // Since keyframes need 3 layers of nesting, we use `generateCSS` to // build the inner layers and wrap it in `@keyframes` ourselves. var finalVal = '@keyframes ' + name + '{'; Object.keys(val).forEach(function (key) { finalVal += (0, _generate.generateCSS)(key, [val[key]], stringHandlers, false); }); finalVal += '}'; injectGeneratedCSSOnce(name, finalVal); return name; }
[ "function", "animationName", "(", "val", ")", "{", "if", "(", "typeof", "val", "!==", "\"object\"", ")", "{", "return", "val", ";", "}", "// Generate a unique name based on the hash of the object. We can't", "// just use the hash because the name can't start with a number.", "// TODO(emily): this probably makes debugging hard, allow a custom", "// name?", "var", "name", "=", "'keyframe_'", "+", "(", "0", ",", "_util", ".", "hashObject", ")", "(", "val", ")", ";", "// Since keyframes need 3 layers of nesting, we use `generateCSS` to", "// build the inner layers and wrap it in `@keyframes` ourselves.", "var", "finalVal", "=", "'@keyframes '", "+", "name", "+", "'{'", ";", "Object", ".", "keys", "(", "val", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "finalVal", "+=", "(", "0", ",", "_generate", ".", "generateCSS", ")", "(", "key", ",", "[", "val", "[", "key", "]", "]", ",", "stringHandlers", ",", "false", ")", ";", "}", ")", ";", "finalVal", "+=", "'}'", ";", "injectGeneratedCSSOnce", "(", "name", ",", "finalVal", ")", ";", "return", "name", ";", "}" ]
With animationName we look for an object that contains keyframes and inject them as an `@keyframes` block, returning a uniquely generated name. The keyframes object should look like animationName: { from: { left: 0, top: 0, }, '50%': { left: 15, top: 5, }, to: { left: 20, top: 20, } } TODO(emily): `stringHandlers` doesn't let us rename the key, so I have to use `animationName` here. Improve that so we can call this `animation` instead of `animationName`.
[ "With", "animationName", "we", "look", "for", "an", "object", "that", "contains", "keyframes", "and", "inject", "them", "as", "an" ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L292-L314
10,311
jossmac/react-images
examples/dist/common.js
injectAndGetClassName
function injectAndGetClassName(useImportant, styleDefinitions) { // Filter out falsy values from the input, to allow for // `css(a, test && c)` var validDefinitions = styleDefinitions.filter(function (def) { return def; }); // Break if there aren't any valid styles. if (validDefinitions.length === 0) { return ""; } var className = validDefinitions.map(function (s) { return s._name; }).join("-o_O-"); injectStyleOnce(className, '.' + className, validDefinitions.map(function (d) { return d._definition; }), useImportant); return className; }
javascript
function injectAndGetClassName(useImportant, styleDefinitions) { // Filter out falsy values from the input, to allow for // `css(a, test && c)` var validDefinitions = styleDefinitions.filter(function (def) { return def; }); // Break if there aren't any valid styles. if (validDefinitions.length === 0) { return ""; } var className = validDefinitions.map(function (s) { return s._name; }).join("-o_O-"); injectStyleOnce(className, '.' + className, validDefinitions.map(function (d) { return d._definition; }), useImportant); return className; }
[ "function", "injectAndGetClassName", "(", "useImportant", ",", "styleDefinitions", ")", "{", "// Filter out falsy values from the input, to allow for", "// `css(a, test && c)`", "var", "validDefinitions", "=", "styleDefinitions", ".", "filter", "(", "function", "(", "def", ")", "{", "return", "def", ";", "}", ")", ";", "// Break if there aren't any valid styles.", "if", "(", "validDefinitions", ".", "length", "===", "0", ")", "{", "return", "\"\"", ";", "}", "var", "className", "=", "validDefinitions", ".", "map", "(", "function", "(", "s", ")", "{", "return", "s", ".", "_name", ";", "}", ")", ".", "join", "(", "\"-o_O-\"", ")", ";", "injectStyleOnce", "(", "className", ",", "'.'", "+", "className", ",", "validDefinitions", ".", "map", "(", "function", "(", "d", ")", "{", "return", "d", ".", "_definition", ";", "}", ")", ",", "useImportant", ")", ";", "return", "className", ";", "}" ]
Inject styles associated with the passed style definition objects, and return an associated CSS class name. @param {boolean} useImportant If true, will append !important to generated CSS output. e.g. {color: red} -> "color: red !important". @param {Object[]} styleDefinitions style definition objects as returned as properties of the return value of StyleSheet.create().
[ "Inject", "styles", "associated", "with", "the", "passed", "style", "definition", "objects", "and", "return", "an", "associated", "CSS", "class", "name", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L411-L431
10,312
jossmac/react-images
examples/dist/common.js
murmurhash2_32_gc
function murmurhash2_32_gc(str) { var l = str.length; var h = l; var i = 0; var k = undefined; while (l >= 4) { k = str.charCodeAt(i) & 0xff | (str.charCodeAt(++i) & 0xff) << 8 | (str.charCodeAt(++i) & 0xff) << 16 | (str.charCodeAt(++i) & 0xff) << 24; k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16); k ^= k >>> 24; k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16); h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16) ^ k; l -= 4; ++i; } switch (l) { case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16; case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8; case 1: h ^= str.charCodeAt(i) & 0xff; h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16); } h ^= h >>> 13; h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16); h ^= h >>> 15; return (h >>> 0).toString(36); }
javascript
function murmurhash2_32_gc(str) { var l = str.length; var h = l; var i = 0; var k = undefined; while (l >= 4) { k = str.charCodeAt(i) & 0xff | (str.charCodeAt(++i) & 0xff) << 8 | (str.charCodeAt(++i) & 0xff) << 16 | (str.charCodeAt(++i) & 0xff) << 24; k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16); k ^= k >>> 24; k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16); h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16) ^ k; l -= 4; ++i; } switch (l) { case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16; case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8; case 1: h ^= str.charCodeAt(i) & 0xff; h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16); } h ^= h >>> 13; h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16); h ^= h >>> 15; return (h >>> 0).toString(36); }
[ "function", "murmurhash2_32_gc", "(", "str", ")", "{", "var", "l", "=", "str", ".", "length", ";", "var", "h", "=", "l", ";", "var", "i", "=", "0", ";", "var", "k", "=", "undefined", ";", "while", "(", "l", ">=", "4", ")", "{", "k", "=", "str", ".", "charCodeAt", "(", "i", ")", "&", "0xff", "|", "(", "str", ".", "charCodeAt", "(", "++", "i", ")", "&", "0xff", ")", "<<", "8", "|", "(", "str", ".", "charCodeAt", "(", "++", "i", ")", "&", "0xff", ")", "<<", "16", "|", "(", "str", ".", "charCodeAt", "(", "++", "i", ")", "&", "0xff", ")", "<<", "24", ";", "k", "=", "(", "k", "&", "0xffff", ")", "*", "0x5bd1e995", "+", "(", "(", "(", "k", ">>>", "16", ")", "*", "0x5bd1e995", "&", "0xffff", ")", "<<", "16", ")", ";", "k", "^=", "k", ">>>", "24", ";", "k", "=", "(", "k", "&", "0xffff", ")", "*", "0x5bd1e995", "+", "(", "(", "(", "k", ">>>", "16", ")", "*", "0x5bd1e995", "&", "0xffff", ")", "<<", "16", ")", ";", "h", "=", "(", "h", "&", "0xffff", ")", "*", "0x5bd1e995", "+", "(", "(", "(", "h", ">>>", "16", ")", "*", "0x5bd1e995", "&", "0xffff", ")", "<<", "16", ")", "^", "k", ";", "l", "-=", "4", ";", "++", "i", ";", "}", "switch", "(", "l", ")", "{", "case", "3", ":", "h", "^=", "(", "str", ".", "charCodeAt", "(", "i", "+", "2", ")", "&", "0xff", ")", "<<", "16", ";", "case", "2", ":", "h", "^=", "(", "str", ".", "charCodeAt", "(", "i", "+", "1", ")", "&", "0xff", ")", "<<", "8", ";", "case", "1", ":", "h", "^=", "str", ".", "charCodeAt", "(", "i", ")", "&", "0xff", ";", "h", "=", "(", "h", "&", "0xffff", ")", "*", "0x5bd1e995", "+", "(", "(", "(", "h", ">>>", "16", ")", "*", "0x5bd1e995", "&", "0xffff", ")", "<<", "16", ")", ";", "}", "h", "^=", "h", ">>>", "13", ";", "h", "=", "(", "h", "&", "0xffff", ")", "*", "0x5bd1e995", "+", "(", "(", "(", "h", ">>>", "16", ")", "*", "0x5bd1e995", "&", "0xffff", ")", "<<", "16", ")", ";", "h", "^=", "h", ">>>", "15", ";", "return", "(", "h", ">>>", "0", ")", ".", "toString", "(", "36", ")", ";", "}" ]
JS Implementation of MurmurHash2 @author <a href="mailto:gary.court@gmail.com">Gary Court</a> @see http://github.com/garycourt/murmurhash-js @author <a href="mailto:aappleby@gmail.com">Austin Appleby</a> @see http://sites.google.com/site/murmurhash/ @param {string} str ASCII only @return {string} Base 36 encoded hash result
[ "JS", "Implementation", "of", "MurmurHash2" ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L608-L642
10,313
jossmac/react-images
examples/dist/common.js
flush
function flush() { while (index < queue.length) { var currentIndex = index; // Advance the index before calling the task. This ensures that we will // begin flushing on the next task the task throws an error. index = index + 1; queue[currentIndex].call(); // Prevent leaking memory for long chains of recursive calls to `asap`. // If we call `asap` within tasks scheduled by `asap`, the queue will // grow, but to avoid an O(n) walk for every task we execute, we don't // shift tasks off the queue after they have been executed. // Instead, we periodically shift 1024 tasks off the queue. if (index > capacity) { // Manually shift all values starting at the index back to the // beginning of the queue. for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) { queue[scan] = queue[scan + index]; } queue.length -= index; index = 0; } } queue.length = 0; index = 0; flushing = false; }
javascript
function flush() { while (index < queue.length) { var currentIndex = index; // Advance the index before calling the task. This ensures that we will // begin flushing on the next task the task throws an error. index = index + 1; queue[currentIndex].call(); // Prevent leaking memory for long chains of recursive calls to `asap`. // If we call `asap` within tasks scheduled by `asap`, the queue will // grow, but to avoid an O(n) walk for every task we execute, we don't // shift tasks off the queue after they have been executed. // Instead, we periodically shift 1024 tasks off the queue. if (index > capacity) { // Manually shift all values starting at the index back to the // beginning of the queue. for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) { queue[scan] = queue[scan + index]; } queue.length -= index; index = 0; } } queue.length = 0; index = 0; flushing = false; }
[ "function", "flush", "(", ")", "{", "while", "(", "index", "<", "queue", ".", "length", ")", "{", "var", "currentIndex", "=", "index", ";", "// Advance the index before calling the task. This ensures that we will", "// begin flushing on the next task the task throws an error.", "index", "=", "index", "+", "1", ";", "queue", "[", "currentIndex", "]", ".", "call", "(", ")", ";", "// Prevent leaking memory for long chains of recursive calls to `asap`.", "// If we call `asap` within tasks scheduled by `asap`, the queue will", "// grow, but to avoid an O(n) walk for every task we execute, we don't", "// shift tasks off the queue after they have been executed.", "// Instead, we periodically shift 1024 tasks off the queue.", "if", "(", "index", ">", "capacity", ")", "{", "// Manually shift all values starting at the index back to the", "// beginning of the queue.", "for", "(", "var", "scan", "=", "0", ",", "newLength", "=", "queue", ".", "length", "-", "index", ";", "scan", "<", "newLength", ";", "scan", "++", ")", "{", "queue", "[", "scan", "]", "=", "queue", "[", "scan", "+", "index", "]", ";", "}", "queue", ".", "length", "-=", "index", ";", "index", "=", "0", ";", "}", "}", "queue", ".", "length", "=", "0", ";", "index", "=", "0", ";", "flushing", "=", "false", ";", "}" ]
The flush function processes all tasks that have been scheduled with `rawAsap` unless and until one of those tasks throws an exception. If a task throws an exception, `flush` ensures that its state will remain consistent and will resume where it left off when called again. However, `flush` does not make any arrangements to be called again if an exception is thrown.
[ "The", "flush", "function", "processes", "all", "tasks", "that", "have", "been", "scheduled", "with", "rawAsap", "unless", "and", "until", "one", "of", "those", "tasks", "throws", "an", "exception", ".", "If", "a", "task", "throws", "an", "exception", "flush", "ensures", "that", "its", "state", "will", "remain", "consistent", "and", "will", "resume", "where", "it", "left", "off", "when", "called", "again", ".", "However", "flush", "does", "not", "make", "any", "arrangements", "to", "be", "called", "again", "if", "an", "exception", "is", "thrown", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L782-L807
10,314
jossmac/react-images
examples/dist/common.js
makeRequestCallFromMutationObserver
function makeRequestCallFromMutationObserver(callback) { var toggle = 1; var observer = new BrowserMutationObserver(callback); var node = document.createTextNode(""); observer.observe(node, {characterData: true}); return function requestCall() { toggle = -toggle; node.data = toggle; }; }
javascript
function makeRequestCallFromMutationObserver(callback) { var toggle = 1; var observer = new BrowserMutationObserver(callback); var node = document.createTextNode(""); observer.observe(node, {characterData: true}); return function requestCall() { toggle = -toggle; node.data = toggle; }; }
[ "function", "makeRequestCallFromMutationObserver", "(", "callback", ")", "{", "var", "toggle", "=", "1", ";", "var", "observer", "=", "new", "BrowserMutationObserver", "(", "callback", ")", ";", "var", "node", "=", "document", ".", "createTextNode", "(", "\"\"", ")", ";", "observer", ".", "observe", "(", "node", ",", "{", "characterData", ":", "true", "}", ")", ";", "return", "function", "requestCall", "(", ")", "{", "toggle", "=", "-", "toggle", ";", "node", ".", "data", "=", "toggle", ";", "}", ";", "}" ]
To request a high priority event, we induce a mutation observer by toggling the text of a text node between "1" and "-1".
[ "To", "request", "a", "high", "priority", "event", "we", "induce", "a", "mutation", "observer", "by", "toggling", "the", "text", "of", "a", "text", "node", "between", "1", "and", "-", "1", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L876-L885
10,315
jossmac/react-images
examples/dist/common.js
makeRequestCallFromTimer
function makeRequestCallFromTimer(callback) { return function requestCall() { // We dispatch a timeout with a specified delay of 0 for engines that // can reliably accommodate that request. This will usually be snapped // to a 4 milisecond delay, but once we're flushing, there's no delay // between events. var timeoutHandle = setTimeout(handleTimer, 0); // However, since this timer gets frequently dropped in Firefox // workers, we enlist an interval handle that will try to fire // an event 20 times per second until it succeeds. var intervalHandle = setInterval(handleTimer, 50); function handleTimer() { // Whichever timer succeeds will cancel both timers and // execute the callback. clearTimeout(timeoutHandle); clearInterval(intervalHandle); callback(); } }; }
javascript
function makeRequestCallFromTimer(callback) { return function requestCall() { // We dispatch a timeout with a specified delay of 0 for engines that // can reliably accommodate that request. This will usually be snapped // to a 4 milisecond delay, but once we're flushing, there's no delay // between events. var timeoutHandle = setTimeout(handleTimer, 0); // However, since this timer gets frequently dropped in Firefox // workers, we enlist an interval handle that will try to fire // an event 20 times per second until it succeeds. var intervalHandle = setInterval(handleTimer, 50); function handleTimer() { // Whichever timer succeeds will cancel both timers and // execute the callback. clearTimeout(timeoutHandle); clearInterval(intervalHandle); callback(); } }; }
[ "function", "makeRequestCallFromTimer", "(", "callback", ")", "{", "return", "function", "requestCall", "(", ")", "{", "// We dispatch a timeout with a specified delay of 0 for engines that", "// can reliably accommodate that request. This will usually be snapped", "// to a 4 milisecond delay, but once we're flushing, there's no delay", "// between events.", "var", "timeoutHandle", "=", "setTimeout", "(", "handleTimer", ",", "0", ")", ";", "// However, since this timer gets frequently dropped in Firefox", "// workers, we enlist an interval handle that will try to fire", "// an event 20 times per second until it succeeds.", "var", "intervalHandle", "=", "setInterval", "(", "handleTimer", ",", "50", ")", ";", "function", "handleTimer", "(", ")", "{", "// Whichever timer succeeds will cancel both timers and", "// execute the callback.", "clearTimeout", "(", "timeoutHandle", ")", ";", "clearInterval", "(", "intervalHandle", ")", ";", "callback", "(", ")", ";", "}", "}", ";", "}" ]
`setTimeout` does not call the passed callback if the delay is less than approximately 7 in web workers in Firefox 8 through 18, and sometimes not even then.
[ "setTimeout", "does", "not", "call", "the", "passed", "callback", "if", "the", "delay", "is", "less", "than", "approximately", "7", "in", "web", "workers", "in", "Firefox", "8", "through", "18", "and", "sometimes", "not", "even", "then", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L927-L947
10,316
jossmac/react-images
examples/dist/common.js
createMergedResultFunction
function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } var c = {}; mergeIntoWithNoDuplicateKeys(c, a); mergeIntoWithNoDuplicateKeys(c, b); return c; }; }
javascript
function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } var c = {}; mergeIntoWithNoDuplicateKeys(c, a); mergeIntoWithNoDuplicateKeys(c, b); return c; }; }
[ "function", "createMergedResultFunction", "(", "one", ",", "two", ")", "{", "return", "function", "mergedResult", "(", ")", "{", "var", "a", "=", "one", ".", "apply", "(", "this", ",", "arguments", ")", ";", "var", "b", "=", "two", ".", "apply", "(", "this", ",", "arguments", ")", ";", "if", "(", "a", "==", "null", ")", "{", "return", "b", ";", "}", "else", "if", "(", "b", "==", "null", ")", "{", "return", "a", ";", "}", "var", "c", "=", "{", "}", ";", "mergeIntoWithNoDuplicateKeys", "(", "c", ",", "a", ")", ";", "mergeIntoWithNoDuplicateKeys", "(", "c", ",", "b", ")", ";", "return", "c", ";", "}", ";", "}" ]
Creates a function that invokes two functions and merges their return values. @param {function} one Function to invoke first. @param {function} two Function to invoke second. @return {function} Function that invokes the two argument functions. @private
[ "Creates", "a", "function", "that", "invokes", "two", "functions", "and", "merges", "their", "return", "values", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L1575-L1589
10,317
jossmac/react-images
examples/dist/common.js
createChainedFunction
function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; }
javascript
function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; }
[ "function", "createChainedFunction", "(", "one", ",", "two", ")", "{", "return", "function", "chainedFunction", "(", ")", "{", "one", ".", "apply", "(", "this", ",", "arguments", ")", ";", "two", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", ";", "}" ]
Creates a function that invokes two functions and ignores their return vales. @param {function} one Function to invoke first. @param {function} two Function to invoke second. @return {function} Function that invokes the two argument functions. @private
[ "Creates", "a", "function", "that", "invokes", "two", "functions", "and", "ignores", "their", "return", "vales", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L1599-L1604
10,318
jossmac/react-images
examples/dist/common.js
prefixAll
function prefixAll(styles) { Object.keys(styles).forEach(function (property) { var value = styles[property]; if (value instanceof Object && !Array.isArray(value)) { // recurse through nested style objects styles[property] = prefixAll(value); } else { Object.keys(_prefixProps2.default).forEach(function (prefix) { var properties = _prefixProps2.default[prefix]; // add prefixes if needed if (properties[property]) { styles[prefix + (0, _capitalizeString2.default)(property)] = value; } }); } }); Object.keys(styles).forEach(function (property) { [].concat(styles[property]).forEach(function (value, index) { // resolve every special plugins plugins.forEach(function (plugin) { return assignStyles(styles, plugin(property, value)); }); }); }); return (0, _sortPrefixedStyle2.default)(styles); }
javascript
function prefixAll(styles) { Object.keys(styles).forEach(function (property) { var value = styles[property]; if (value instanceof Object && !Array.isArray(value)) { // recurse through nested style objects styles[property] = prefixAll(value); } else { Object.keys(_prefixProps2.default).forEach(function (prefix) { var properties = _prefixProps2.default[prefix]; // add prefixes if needed if (properties[property]) { styles[prefix + (0, _capitalizeString2.default)(property)] = value; } }); } }); Object.keys(styles).forEach(function (property) { [].concat(styles[property]).forEach(function (value, index) { // resolve every special plugins plugins.forEach(function (plugin) { return assignStyles(styles, plugin(property, value)); }); }); }); return (0, _sortPrefixedStyle2.default)(styles); }
[ "function", "prefixAll", "(", "styles", ")", "{", "Object", ".", "keys", "(", "styles", ")", ".", "forEach", "(", "function", "(", "property", ")", "{", "var", "value", "=", "styles", "[", "property", "]", ";", "if", "(", "value", "instanceof", "Object", "&&", "!", "Array", ".", "isArray", "(", "value", ")", ")", "{", "// recurse through nested style objects", "styles", "[", "property", "]", "=", "prefixAll", "(", "value", ")", ";", "}", "else", "{", "Object", ".", "keys", "(", "_prefixProps2", ".", "default", ")", ".", "forEach", "(", "function", "(", "prefix", ")", "{", "var", "properties", "=", "_prefixProps2", ".", "default", "[", "prefix", "]", ";", "// add prefixes if needed", "if", "(", "properties", "[", "property", "]", ")", "{", "styles", "[", "prefix", "+", "(", "0", ",", "_capitalizeString2", ".", "default", ")", "(", "property", ")", "]", "=", "value", ";", "}", "}", ")", ";", "}", "}", ")", ";", "Object", ".", "keys", "(", "styles", ")", ".", "forEach", "(", "function", "(", "property", ")", "{", "[", "]", ".", "concat", "(", "styles", "[", "property", "]", ")", ".", "forEach", "(", "function", "(", "value", ",", "index", ")", "{", "// resolve every special plugins", "plugins", ".", "forEach", "(", "function", "(", "plugin", ")", "{", "return", "assignStyles", "(", "styles", ",", "plugin", "(", "property", ",", "value", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "return", "(", "0", ",", "_sortPrefixedStyle2", ".", "default", ")", "(", "styles", ")", ";", "}" ]
Returns a prefixed version of the style object using all vendor prefixes @param {Object} styles - Style object that gets prefixed properties added @returns {Object} - Style object with prefixed properties and values
[ "Returns", "a", "prefixed", "version", "of", "the", "style", "object", "using", "all", "vendor", "prefixes" ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L2673-L2700
10,319
jossmac/react-images
examples/dist/common.js
function (name, value) { if (DOMProperty.isReservedProp(name)) { return false; } if ((name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) { return false; } if (value === null) { return true; } switch (typeof value) { case 'boolean': return DOMProperty.shouldAttributeAcceptBooleanValue(name); case 'undefined': case 'number': case 'string': case 'object': return true; default: // function, symbol return false; } }
javascript
function (name, value) { if (DOMProperty.isReservedProp(name)) { return false; } if ((name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) { return false; } if (value === null) { return true; } switch (typeof value) { case 'boolean': return DOMProperty.shouldAttributeAcceptBooleanValue(name); case 'undefined': case 'number': case 'string': case 'object': return true; default: // function, symbol return false; } }
[ "function", "(", "name", ",", "value", ")", "{", "if", "(", "DOMProperty", ".", "isReservedProp", "(", "name", ")", ")", "{", "return", "false", ";", "}", "if", "(", "(", "name", "[", "0", "]", "===", "'o'", "||", "name", "[", "0", "]", "===", "'O'", ")", "&&", "(", "name", "[", "1", "]", "===", "'n'", "||", "name", "[", "1", "]", "===", "'N'", ")", ")", "{", "return", "false", ";", "}", "if", "(", "value", "===", "null", ")", "{", "return", "true", ";", "}", "switch", "(", "typeof", "value", ")", "{", "case", "'boolean'", ":", "return", "DOMProperty", ".", "shouldAttributeAcceptBooleanValue", "(", "name", ")", ";", "case", "'undefined'", ":", "case", "'number'", ":", "case", "'string'", ":", "case", "'object'", ":", "return", "true", ";", "default", ":", "// function, symbol", "return", "false", ";", "}", "}" ]
Checks whether a property name is a writeable attribute. @method
[ "Checks", "whether", "a", "property", "name", "is", "a", "writeable", "attribute", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L4383-L4405
10,320
jossmac/react-images
examples/dist/common.js
getTopLevelCallbackBookKeeping
function getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst) { if (callbackBookkeepingPool.length) { var instance = callbackBookkeepingPool.pop(); instance.topLevelType = topLevelType; instance.nativeEvent = nativeEvent; instance.targetInst = targetInst; return instance; } return { topLevelType: topLevelType, nativeEvent: nativeEvent, targetInst: targetInst, ancestors: [] }; }
javascript
function getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst) { if (callbackBookkeepingPool.length) { var instance = callbackBookkeepingPool.pop(); instance.topLevelType = topLevelType; instance.nativeEvent = nativeEvent; instance.targetInst = targetInst; return instance; } return { topLevelType: topLevelType, nativeEvent: nativeEvent, targetInst: targetInst, ancestors: [] }; }
[ "function", "getTopLevelCallbackBookKeeping", "(", "topLevelType", ",", "nativeEvent", ",", "targetInst", ")", "{", "if", "(", "callbackBookkeepingPool", ".", "length", ")", "{", "var", "instance", "=", "callbackBookkeepingPool", ".", "pop", "(", ")", ";", "instance", ".", "topLevelType", "=", "topLevelType", ";", "instance", ".", "nativeEvent", "=", "nativeEvent", ";", "instance", ".", "targetInst", "=", "targetInst", ";", "return", "instance", ";", "}", "return", "{", "topLevelType", ":", "topLevelType", ",", "nativeEvent", ":", "nativeEvent", ",", "targetInst", ":", "targetInst", ",", "ancestors", ":", "[", "]", "}", ";", "}" ]
Used to store ancestor hierarchy in top level callback
[ "Used", "to", "store", "ancestor", "hierarchy", "in", "top", "level", "callback" ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L5691-L5705
10,321
jossmac/react-images
examples/dist/common.js
getVendorPrefixedEventName
function getVendorPrefixedEventName(eventName) { if (prefixedEventNames[eventName]) { return prefixedEventNames[eventName]; } else if (!vendorPrefixes[eventName]) { return eventName; } var prefixMap = vendorPrefixes[eventName]; for (var styleProp in prefixMap) { if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) { return prefixedEventNames[eventName] = prefixMap[styleProp]; } } return ''; }
javascript
function getVendorPrefixedEventName(eventName) { if (prefixedEventNames[eventName]) { return prefixedEventNames[eventName]; } else if (!vendorPrefixes[eventName]) { return eventName; } var prefixMap = vendorPrefixes[eventName]; for (var styleProp in prefixMap) { if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) { return prefixedEventNames[eventName] = prefixMap[styleProp]; } } return ''; }
[ "function", "getVendorPrefixedEventName", "(", "eventName", ")", "{", "if", "(", "prefixedEventNames", "[", "eventName", "]", ")", "{", "return", "prefixedEventNames", "[", "eventName", "]", ";", "}", "else", "if", "(", "!", "vendorPrefixes", "[", "eventName", "]", ")", "{", "return", "eventName", ";", "}", "var", "prefixMap", "=", "vendorPrefixes", "[", "eventName", "]", ";", "for", "(", "var", "styleProp", "in", "prefixMap", ")", "{", "if", "(", "prefixMap", ".", "hasOwnProperty", "(", "styleProp", ")", "&&", "styleProp", "in", "style", ")", "{", "return", "prefixedEventNames", "[", "eventName", "]", "=", "prefixMap", "[", "styleProp", "]", ";", "}", "}", "return", "''", ";", "}" ]
Attempts to determine the correct vendor prefixed event name. @param {string} eventName @returns {string}
[ "Attempts", "to", "determine", "the", "correct", "vendor", "prefixed", "event", "name", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L6220-L6236
10,322
jossmac/react-images
examples/dist/common.js
function (styles) { { var serialized = ''; var delimiter = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = styles[styleName]; if (styleValue != null) { var isCustomProperty = styleName.indexOf('--') === 0; serialized += delimiter + hyphenateStyleName$1(styleName) + ':'; serialized += dangerousStyleValue_1(styleName, styleValue, isCustomProperty); delimiter = ';'; } } return serialized || null; } }
javascript
function (styles) { { var serialized = ''; var delimiter = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = styles[styleName]; if (styleValue != null) { var isCustomProperty = styleName.indexOf('--') === 0; serialized += delimiter + hyphenateStyleName$1(styleName) + ':'; serialized += dangerousStyleValue_1(styleName, styleValue, isCustomProperty); delimiter = ';'; } } return serialized || null; } }
[ "function", "(", "styles", ")", "{", "{", "var", "serialized", "=", "''", ";", "var", "delimiter", "=", "''", ";", "for", "(", "var", "styleName", "in", "styles", ")", "{", "if", "(", "!", "styles", ".", "hasOwnProperty", "(", "styleName", ")", ")", "{", "continue", ";", "}", "var", "styleValue", "=", "styles", "[", "styleName", "]", ";", "if", "(", "styleValue", "!=", "null", ")", "{", "var", "isCustomProperty", "=", "styleName", ".", "indexOf", "(", "'--'", ")", "===", "0", ";", "serialized", "+=", "delimiter", "+", "hyphenateStyleName$1", "(", "styleName", ")", "+", "':'", ";", "serialized", "+=", "dangerousStyleValue_1", "(", "styleName", ",", "styleValue", ",", "isCustomProperty", ")", ";", "delimiter", "=", "';'", ";", "}", "}", "return", "serialized", "||", "null", ";", "}", "}" ]
This creates a string that is expected to be equivalent to the style attribute generated by server-side rendering. It by-passes warnings and security checks so it's not safe to use this value for anything other than comparison. It is only used in DEV for SSR validation.
[ "This", "creates", "a", "string", "that", "is", "expected", "to", "be", "equivalent", "to", "the", "style", "attribute", "generated", "by", "server", "-", "side", "rendering", ".", "It", "by", "-", "passes", "warnings", "and", "security", "checks", "so", "it", "s", "not", "safe", "to", "use", "this", "value", "for", "anything", "other", "than", "comparison", ".", "It", "is", "only", "used", "in", "DEV", "for", "SSR", "validation", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L6967-L6986
10,323
jossmac/react-images
examples/dist/common.js
function (node, name, expected) { { var propertyInfo = DOMProperty_1.getPropertyInfo(name); if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod || propertyInfo.mustUseProperty) { return node[propertyInfo.propertyName]; } else { var attributeName = propertyInfo.attributeName; var stringValue = null; if (propertyInfo.hasOverloadedBooleanValue) { if (node.hasAttribute(attributeName)) { var value = node.getAttribute(attributeName); if (value === '') { return true; } if (shouldIgnoreValue(propertyInfo, expected)) { return value; } if (value === '' + expected) { return expected; } return value; } } else if (node.hasAttribute(attributeName)) { if (shouldIgnoreValue(propertyInfo, expected)) { // We had an attribute but shouldn't have had one, so read it // for the error message. return node.getAttribute(attributeName); } if (propertyInfo.hasBooleanValue) { // If this was a boolean, it doesn't matter what the value is // the fact that we have it is the same as the expected. return expected; } // Even if this property uses a namespace we use getAttribute // because we assume its namespaced name is the same as our config. // To use getAttributeNS we need the local name which we don't have // in our config atm. stringValue = node.getAttribute(attributeName); } if (shouldIgnoreValue(propertyInfo, expected)) { return stringValue === null ? expected : stringValue; } else if (stringValue === '' + expected) { return expected; } else { return stringValue; } } } } }
javascript
function (node, name, expected) { { var propertyInfo = DOMProperty_1.getPropertyInfo(name); if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod || propertyInfo.mustUseProperty) { return node[propertyInfo.propertyName]; } else { var attributeName = propertyInfo.attributeName; var stringValue = null; if (propertyInfo.hasOverloadedBooleanValue) { if (node.hasAttribute(attributeName)) { var value = node.getAttribute(attributeName); if (value === '') { return true; } if (shouldIgnoreValue(propertyInfo, expected)) { return value; } if (value === '' + expected) { return expected; } return value; } } else if (node.hasAttribute(attributeName)) { if (shouldIgnoreValue(propertyInfo, expected)) { // We had an attribute but shouldn't have had one, so read it // for the error message. return node.getAttribute(attributeName); } if (propertyInfo.hasBooleanValue) { // If this was a boolean, it doesn't matter what the value is // the fact that we have it is the same as the expected. return expected; } // Even if this property uses a namespace we use getAttribute // because we assume its namespaced name is the same as our config. // To use getAttributeNS we need the local name which we don't have // in our config atm. stringValue = node.getAttribute(attributeName); } if (shouldIgnoreValue(propertyInfo, expected)) { return stringValue === null ? expected : stringValue; } else if (stringValue === '' + expected) { return expected; } else { return stringValue; } } } } }
[ "function", "(", "node", ",", "name", ",", "expected", ")", "{", "{", "var", "propertyInfo", "=", "DOMProperty_1", ".", "getPropertyInfo", "(", "name", ")", ";", "if", "(", "propertyInfo", ")", "{", "var", "mutationMethod", "=", "propertyInfo", ".", "mutationMethod", ";", "if", "(", "mutationMethod", "||", "propertyInfo", ".", "mustUseProperty", ")", "{", "return", "node", "[", "propertyInfo", ".", "propertyName", "]", ";", "}", "else", "{", "var", "attributeName", "=", "propertyInfo", ".", "attributeName", ";", "var", "stringValue", "=", "null", ";", "if", "(", "propertyInfo", ".", "hasOverloadedBooleanValue", ")", "{", "if", "(", "node", ".", "hasAttribute", "(", "attributeName", ")", ")", "{", "var", "value", "=", "node", ".", "getAttribute", "(", "attributeName", ")", ";", "if", "(", "value", "===", "''", ")", "{", "return", "true", ";", "}", "if", "(", "shouldIgnoreValue", "(", "propertyInfo", ",", "expected", ")", ")", "{", "return", "value", ";", "}", "if", "(", "value", "===", "''", "+", "expected", ")", "{", "return", "expected", ";", "}", "return", "value", ";", "}", "}", "else", "if", "(", "node", ".", "hasAttribute", "(", "attributeName", ")", ")", "{", "if", "(", "shouldIgnoreValue", "(", "propertyInfo", ",", "expected", ")", ")", "{", "// We had an attribute but shouldn't have had one, so read it", "// for the error message.", "return", "node", ".", "getAttribute", "(", "attributeName", ")", ";", "}", "if", "(", "propertyInfo", ".", "hasBooleanValue", ")", "{", "// If this was a boolean, it doesn't matter what the value is", "// the fact that we have it is the same as the expected.", "return", "expected", ";", "}", "// Even if this property uses a namespace we use getAttribute", "// because we assume its namespaced name is the same as our config.", "// To use getAttributeNS we need the local name which we don't have", "// in our config atm.", "stringValue", "=", "node", ".", "getAttribute", "(", "attributeName", ")", ";", "}", "if", "(", "shouldIgnoreValue", "(", "propertyInfo", ",", "expected", ")", ")", "{", "return", "stringValue", "===", "null", "?", "expected", ":", "stringValue", ";", "}", "else", "if", "(", "stringValue", "===", "''", "+", "expected", ")", "{", "return", "expected", ";", "}", "else", "{", "return", "stringValue", ";", "}", "}", "}", "}", "}" ]
Get the value for a property on a node. Only used in DEV for SSR validation. The "expected" argument is used as a hint of what the expected value is. Some properties have multiple equivalent values.
[ "Get", "the", "value", "for", "a", "property", "on", "a", "node", ".", "Only", "used", "in", "DEV", "for", "SSR", "validation", ".", "The", "expected", "argument", "is", "used", "as", "a", "hint", "of", "what", "the", "expected", "value", "is", ".", "Some", "properties", "have", "multiple", "equivalent", "values", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L7505-L7559
10,324
jossmac/react-images
examples/dist/common.js
function (node, name, expected) { { if (!isAttributeNameSafe(name)) { return; } if (!node.hasAttribute(name)) { return expected === undefined ? undefined : null; } var value = node.getAttribute(name); if (value === '' + expected) { return expected; } return value; } }
javascript
function (node, name, expected) { { if (!isAttributeNameSafe(name)) { return; } if (!node.hasAttribute(name)) { return expected === undefined ? undefined : null; } var value = node.getAttribute(name); if (value === '' + expected) { return expected; } return value; } }
[ "function", "(", "node", ",", "name", ",", "expected", ")", "{", "{", "if", "(", "!", "isAttributeNameSafe", "(", "name", ")", ")", "{", "return", ";", "}", "if", "(", "!", "node", ".", "hasAttribute", "(", "name", ")", ")", "{", "return", "expected", "===", "undefined", "?", "undefined", ":", "null", ";", "}", "var", "value", "=", "node", ".", "getAttribute", "(", "name", ")", ";", "if", "(", "value", "===", "''", "+", "expected", ")", "{", "return", "expected", ";", "}", "return", "value", ";", "}", "}" ]
Get the value for a attribute on a node. Only used in DEV for SSR validation. The third argument is used as a hint of what the expected value is. Some attributes have multiple equivalent values.
[ "Get", "the", "value", "for", "a", "attribute", "on", "a", "node", ".", "Only", "used", "in", "DEV", "for", "SSR", "validation", ".", "The", "third", "argument", "is", "used", "as", "a", "hint", "of", "what", "the", "expected", "value", "is", ".", "Some", "attributes", "have", "multiple", "equivalent", "values", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L7566-L7580
10,325
jossmac/react-images
examples/dist/common.js
function (parent, html) { if (!testDocument) { testDocument = document.implementation.createHTMLDocument(); } var testElement = parent.namespaceURI === HTML_NAMESPACE$1 ? testDocument.createElement(parent.tagName) : testDocument.createElementNS(parent.namespaceURI, parent.tagName); testElement.innerHTML = html; return testElement.innerHTML; }
javascript
function (parent, html) { if (!testDocument) { testDocument = document.implementation.createHTMLDocument(); } var testElement = parent.namespaceURI === HTML_NAMESPACE$1 ? testDocument.createElement(parent.tagName) : testDocument.createElementNS(parent.namespaceURI, parent.tagName); testElement.innerHTML = html; return testElement.innerHTML; }
[ "function", "(", "parent", ",", "html", ")", "{", "if", "(", "!", "testDocument", ")", "{", "testDocument", "=", "document", ".", "implementation", ".", "createHTMLDocument", "(", ")", ";", "}", "var", "testElement", "=", "parent", ".", "namespaceURI", "===", "HTML_NAMESPACE$1", "?", "testDocument", ".", "createElement", "(", "parent", ".", "tagName", ")", ":", "testDocument", ".", "createElementNS", "(", "parent", ".", "namespaceURI", ",", "parent", ".", "tagName", ")", ";", "testElement", ".", "innerHTML", "=", "html", ";", "return", "testElement", ".", "innerHTML", ";", "}" ]
Parse the HTML and read it back to normalize the HTML string so that it can be used for comparison.
[ "Parse", "the", "HTML", "and", "read", "it", "back", "to", "normalize", "the", "HTML", "string", "so", "that", "it", "can", "be", "used", "for", "comparison", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L9822-L9829
10,326
jossmac/react-images
examples/dist/common.js
findInsertionPosition
function findInsertionPosition(queue, update) { var priorityLevel = update.priorityLevel; var insertAfter = null; var insertBefore = null; if (queue.last !== null && comparePriority(queue.last.priorityLevel, priorityLevel) <= 0) { // Fast path for the common case where the update should be inserted at // the end of the queue. insertAfter = queue.last; } else { insertBefore = queue.first; while (insertBefore !== null && comparePriority(insertBefore.priorityLevel, priorityLevel) <= 0) { insertAfter = insertBefore; insertBefore = insertBefore.next; } } return insertAfter; }
javascript
function findInsertionPosition(queue, update) { var priorityLevel = update.priorityLevel; var insertAfter = null; var insertBefore = null; if (queue.last !== null && comparePriority(queue.last.priorityLevel, priorityLevel) <= 0) { // Fast path for the common case where the update should be inserted at // the end of the queue. insertAfter = queue.last; } else { insertBefore = queue.first; while (insertBefore !== null && comparePriority(insertBefore.priorityLevel, priorityLevel) <= 0) { insertAfter = insertBefore; insertBefore = insertBefore.next; } } return insertAfter; }
[ "function", "findInsertionPosition", "(", "queue", ",", "update", ")", "{", "var", "priorityLevel", "=", "update", ".", "priorityLevel", ";", "var", "insertAfter", "=", "null", ";", "var", "insertBefore", "=", "null", ";", "if", "(", "queue", ".", "last", "!==", "null", "&&", "comparePriority", "(", "queue", ".", "last", ".", "priorityLevel", ",", "priorityLevel", ")", "<=", "0", ")", "{", "// Fast path for the common case where the update should be inserted at", "// the end of the queue.", "insertAfter", "=", "queue", ".", "last", ";", "}", "else", "{", "insertBefore", "=", "queue", ".", "first", ";", "while", "(", "insertBefore", "!==", "null", "&&", "comparePriority", "(", "insertBefore", ".", "priorityLevel", ",", "priorityLevel", ")", "<=", "0", ")", "{", "insertAfter", "=", "insertBefore", ";", "insertBefore", "=", "insertBefore", ".", "next", ";", "}", "}", "return", "insertAfter", ";", "}" ]
Returns the update after which the incoming update should be inserted into the queue, or null if it should be inserted at beginning.
[ "Returns", "the", "update", "after", "which", "the", "incoming", "update", "should", "be", "inserted", "into", "the", "queue", "or", "null", "if", "it", "should", "be", "inserted", "at", "beginning", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L10873-L10889
10,327
jossmac/react-images
examples/dist/common.js
function (fn) { !(showDialog === defaultShowDialog) ? invariant(false, 'The custom dialog was already injected.') : void 0; !(typeof fn === 'function') ? invariant(false, 'Injected showDialog() must be a function.') : void 0; showDialog = fn; }
javascript
function (fn) { !(showDialog === defaultShowDialog) ? invariant(false, 'The custom dialog was already injected.') : void 0; !(typeof fn === 'function') ? invariant(false, 'Injected showDialog() must be a function.') : void 0; showDialog = fn; }
[ "function", "(", "fn", ")", "{", "!", "(", "showDialog", "===", "defaultShowDialog", ")", "?", "invariant", "(", "false", ",", "'The custom dialog was already injected.'", ")", ":", "void", "0", ";", "!", "(", "typeof", "fn", "===", "'function'", ")", "?", "invariant", "(", "false", ",", "'Injected showDialog() must be a function.'", ")", ":", "void", "0", ";", "showDialog", "=", "fn", ";", "}" ]
Display custom dialog for lifecycle errors. Return false to prevent default behavior of logging to console.error.
[ "Display", "custom", "dialog", "for", "lifecycle", "errors", ".", "Return", "false", "to", "prevent", "default", "behavior", "of", "logging", "to", "console", ".", "error", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L12254-L12258
10,328
jossmac/react-images
examples/dist/common.js
safelyCallComponentWillUnmount
function safelyCallComponentWillUnmount(current, instance) { { invokeGuardedCallback$2(null, callComponentWillUnmountWithTimerInDev, null, current, instance); if (hasCaughtError$1()) { var unmountError = clearCaughtError$1(); captureError(current, unmountError); } } }
javascript
function safelyCallComponentWillUnmount(current, instance) { { invokeGuardedCallback$2(null, callComponentWillUnmountWithTimerInDev, null, current, instance); if (hasCaughtError$1()) { var unmountError = clearCaughtError$1(); captureError(current, unmountError); } } }
[ "function", "safelyCallComponentWillUnmount", "(", "current", ",", "instance", ")", "{", "{", "invokeGuardedCallback$2", "(", "null", ",", "callComponentWillUnmountWithTimerInDev", ",", "null", ",", "current", ",", "instance", ")", ";", "if", "(", "hasCaughtError$1", "(", ")", ")", "{", "var", "unmountError", "=", "clearCaughtError$1", "(", ")", ";", "captureError", "(", "current", ",", "unmountError", ")", ";", "}", "}", "}" ]
Capture errors so they don't interrupt unmounting.
[ "Capture", "errors", "so", "they", "don", "t", "interrupt", "unmounting", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L15063-L15071
10,329
jossmac/react-images
examples/dist/common.js
resetNextUnitOfWork
function resetNextUnitOfWork() { // Clear out roots with no more work on them, or if they have uncaught errors while (nextScheduledRoot !== null && nextScheduledRoot.current.pendingWorkPriority === NoWork$2) { // Unschedule this root. nextScheduledRoot.isScheduled = false; // Read the next pointer now. // We need to clear it in case this root gets scheduled again later. var next = nextScheduledRoot.nextScheduledRoot; nextScheduledRoot.nextScheduledRoot = null; // Exit if we cleared all the roots and there's no work to do. if (nextScheduledRoot === lastScheduledRoot) { nextScheduledRoot = null; lastScheduledRoot = null; nextPriorityLevel = NoWork$2; return null; } // Continue with the next root. // If there's no work on it, it will get unscheduled too. nextScheduledRoot = next; } var root = nextScheduledRoot; var highestPriorityRoot = null; var highestPriorityLevel = NoWork$2; while (root !== null) { if (root.current.pendingWorkPriority !== NoWork$2 && (highestPriorityLevel === NoWork$2 || highestPriorityLevel > root.current.pendingWorkPriority)) { highestPriorityLevel = root.current.pendingWorkPriority; highestPriorityRoot = root; } // We didn't find anything to do in this root, so let's try the next one. root = root.nextScheduledRoot; } if (highestPriorityRoot !== null) { nextPriorityLevel = highestPriorityLevel; // Before we start any new work, let's make sure that we have a fresh // stack to work from. // TODO: This call is buried a bit too deep. It would be nice to have // a single point which happens right before any new work and // unfortunately this is it. resetContextStack(); nextUnitOfWork = createWorkInProgress$1(highestPriorityRoot.current, highestPriorityLevel); if (highestPriorityRoot !== nextRenderedTree) { // We've switched trees. Reset the nested update counter. nestedUpdateCount = 0; nextRenderedTree = highestPriorityRoot; } return; } nextPriorityLevel = NoWork$2; nextUnitOfWork = null; nextRenderedTree = null; return; }
javascript
function resetNextUnitOfWork() { // Clear out roots with no more work on them, or if they have uncaught errors while (nextScheduledRoot !== null && nextScheduledRoot.current.pendingWorkPriority === NoWork$2) { // Unschedule this root. nextScheduledRoot.isScheduled = false; // Read the next pointer now. // We need to clear it in case this root gets scheduled again later. var next = nextScheduledRoot.nextScheduledRoot; nextScheduledRoot.nextScheduledRoot = null; // Exit if we cleared all the roots and there's no work to do. if (nextScheduledRoot === lastScheduledRoot) { nextScheduledRoot = null; lastScheduledRoot = null; nextPriorityLevel = NoWork$2; return null; } // Continue with the next root. // If there's no work on it, it will get unscheduled too. nextScheduledRoot = next; } var root = nextScheduledRoot; var highestPriorityRoot = null; var highestPriorityLevel = NoWork$2; while (root !== null) { if (root.current.pendingWorkPriority !== NoWork$2 && (highestPriorityLevel === NoWork$2 || highestPriorityLevel > root.current.pendingWorkPriority)) { highestPriorityLevel = root.current.pendingWorkPriority; highestPriorityRoot = root; } // We didn't find anything to do in this root, so let's try the next one. root = root.nextScheduledRoot; } if (highestPriorityRoot !== null) { nextPriorityLevel = highestPriorityLevel; // Before we start any new work, let's make sure that we have a fresh // stack to work from. // TODO: This call is buried a bit too deep. It would be nice to have // a single point which happens right before any new work and // unfortunately this is it. resetContextStack(); nextUnitOfWork = createWorkInProgress$1(highestPriorityRoot.current, highestPriorityLevel); if (highestPriorityRoot !== nextRenderedTree) { // We've switched trees. Reset the nested update counter. nestedUpdateCount = 0; nextRenderedTree = highestPriorityRoot; } return; } nextPriorityLevel = NoWork$2; nextUnitOfWork = null; nextRenderedTree = null; return; }
[ "function", "resetNextUnitOfWork", "(", ")", "{", "// Clear out roots with no more work on them, or if they have uncaught errors", "while", "(", "nextScheduledRoot", "!==", "null", "&&", "nextScheduledRoot", ".", "current", ".", "pendingWorkPriority", "===", "NoWork$2", ")", "{", "// Unschedule this root.", "nextScheduledRoot", ".", "isScheduled", "=", "false", ";", "// Read the next pointer now.", "// We need to clear it in case this root gets scheduled again later.", "var", "next", "=", "nextScheduledRoot", ".", "nextScheduledRoot", ";", "nextScheduledRoot", ".", "nextScheduledRoot", "=", "null", ";", "// Exit if we cleared all the roots and there's no work to do.", "if", "(", "nextScheduledRoot", "===", "lastScheduledRoot", ")", "{", "nextScheduledRoot", "=", "null", ";", "lastScheduledRoot", "=", "null", ";", "nextPriorityLevel", "=", "NoWork$2", ";", "return", "null", ";", "}", "// Continue with the next root.", "// If there's no work on it, it will get unscheduled too.", "nextScheduledRoot", "=", "next", ";", "}", "var", "root", "=", "nextScheduledRoot", ";", "var", "highestPriorityRoot", "=", "null", ";", "var", "highestPriorityLevel", "=", "NoWork$2", ";", "while", "(", "root", "!==", "null", ")", "{", "if", "(", "root", ".", "current", ".", "pendingWorkPriority", "!==", "NoWork$2", "&&", "(", "highestPriorityLevel", "===", "NoWork$2", "||", "highestPriorityLevel", ">", "root", ".", "current", ".", "pendingWorkPriority", ")", ")", "{", "highestPriorityLevel", "=", "root", ".", "current", ".", "pendingWorkPriority", ";", "highestPriorityRoot", "=", "root", ";", "}", "// We didn't find anything to do in this root, so let's try the next one.", "root", "=", "root", ".", "nextScheduledRoot", ";", "}", "if", "(", "highestPriorityRoot", "!==", "null", ")", "{", "nextPriorityLevel", "=", "highestPriorityLevel", ";", "// Before we start any new work, let's make sure that we have a fresh", "// stack to work from.", "// TODO: This call is buried a bit too deep. It would be nice to have", "// a single point which happens right before any new work and", "// unfortunately this is it.", "resetContextStack", "(", ")", ";", "nextUnitOfWork", "=", "createWorkInProgress$1", "(", "highestPriorityRoot", ".", "current", ",", "highestPriorityLevel", ")", ";", "if", "(", "highestPriorityRoot", "!==", "nextRenderedTree", ")", "{", "// We've switched trees. Reset the nested update counter.", "nestedUpdateCount", "=", "0", ";", "nextRenderedTree", "=", "highestPriorityRoot", ";", "}", "return", ";", "}", "nextPriorityLevel", "=", "NoWork$2", ";", "nextUnitOfWork", "=", "null", ";", "nextRenderedTree", "=", "null", ";", "return", ";", "}" ]
resetNextUnitOfWork mutates the current priority context. It is reset after after the workLoop exits, so never call resetNextUnitOfWork from outside the work loop.
[ "resetNextUnitOfWork", "mutates", "the", "current", "priority", "context", ".", "It", "is", "reset", "after", "after", "the", "workLoop", "exits", "so", "never", "call", "resetNextUnitOfWork", "from", "outside", "the", "work", "loop", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L16097-L16151
10,330
jossmac/react-images
examples/dist/common.js
getSiblingNode
function getSiblingNode(node) { while (node) { if (node.nextSibling) { return node.nextSibling; } node = node.parentNode; } }
javascript
function getSiblingNode(node) { while (node) { if (node.nextSibling) { return node.nextSibling; } node = node.parentNode; } }
[ "function", "getSiblingNode", "(", "node", ")", "{", "while", "(", "node", ")", "{", "if", "(", "node", ".", "nextSibling", ")", "{", "return", "node", ".", "nextSibling", ";", "}", "node", "=", "node", ".", "parentNode", ";", "}", "}" ]
Get the next sibling within a container. This will walk up the DOM if a node's siblings have been exhausted. @param {DOMElement|DOMTextNode} node @return {?DOMElement|DOMTextNode}
[ "Get", "the", "next", "sibling", "within", "a", "container", ".", "This", "will", "walk", "up", "the", "DOM", "if", "a", "node", "s", "siblings", "have", "been", "exhausted", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L17430-L17437
10,331
jossmac/react-images
examples/dist/common.js
getNodeForCharacterOffset
function getNodeForCharacterOffset(root, offset) { var node = getLeafNode(root); var nodeStart = 0; var nodeEnd = 0; while (node) { if (node.nodeType === TEXT_NODE$3) { nodeEnd = nodeStart + node.textContent.length; if (nodeStart <= offset && nodeEnd >= offset) { return { node: node, offset: offset - nodeStart }; } nodeStart = nodeEnd; } node = getLeafNode(getSiblingNode(node)); } }
javascript
function getNodeForCharacterOffset(root, offset) { var node = getLeafNode(root); var nodeStart = 0; var nodeEnd = 0; while (node) { if (node.nodeType === TEXT_NODE$3) { nodeEnd = nodeStart + node.textContent.length; if (nodeStart <= offset && nodeEnd >= offset) { return { node: node, offset: offset - nodeStart }; } nodeStart = nodeEnd; } node = getLeafNode(getSiblingNode(node)); } }
[ "function", "getNodeForCharacterOffset", "(", "root", ",", "offset", ")", "{", "var", "node", "=", "getLeafNode", "(", "root", ")", ";", "var", "nodeStart", "=", "0", ";", "var", "nodeEnd", "=", "0", ";", "while", "(", "node", ")", "{", "if", "(", "node", ".", "nodeType", "===", "TEXT_NODE$3", ")", "{", "nodeEnd", "=", "nodeStart", "+", "node", ".", "textContent", ".", "length", ";", "if", "(", "nodeStart", "<=", "offset", "&&", "nodeEnd", ">=", "offset", ")", "{", "return", "{", "node", ":", "node", ",", "offset", ":", "offset", "-", "nodeStart", "}", ";", "}", "nodeStart", "=", "nodeEnd", ";", "}", "node", "=", "getLeafNode", "(", "getSiblingNode", "(", "node", ")", ")", ";", "}", "}" ]
Get object describing the nodes which contain characters at offset. @param {DOMElement|DOMTextNode} root @param {number} offset @return {?object}
[ "Get", "object", "describing", "the", "nodes", "which", "contain", "characters", "at", "offset", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L17446-L17467
10,332
jossmac/react-images
examples/dist/common.js
traverseEnterLeave
function traverseEnterLeave(from, to, fn, argFrom, argTo) { var common = from && to ? getLowestCommonAncestor(from, to) : null; var pathFrom = []; while (from && from !== common) { pathFrom.push(from); from = getParent(from); } var pathTo = []; while (to && to !== common) { pathTo.push(to); to = getParent(to); } var i; for (i = 0; i < pathFrom.length; i++) { fn(pathFrom[i], 'bubbled', argFrom); } for (i = pathTo.length; i-- > 0;) { fn(pathTo[i], 'captured', argTo); } }
javascript
function traverseEnterLeave(from, to, fn, argFrom, argTo) { var common = from && to ? getLowestCommonAncestor(from, to) : null; var pathFrom = []; while (from && from !== common) { pathFrom.push(from); from = getParent(from); } var pathTo = []; while (to && to !== common) { pathTo.push(to); to = getParent(to); } var i; for (i = 0; i < pathFrom.length; i++) { fn(pathFrom[i], 'bubbled', argFrom); } for (i = pathTo.length; i-- > 0;) { fn(pathTo[i], 'captured', argTo); } }
[ "function", "traverseEnterLeave", "(", "from", ",", "to", ",", "fn", ",", "argFrom", ",", "argTo", ")", "{", "var", "common", "=", "from", "&&", "to", "?", "getLowestCommonAncestor", "(", "from", ",", "to", ")", ":", "null", ";", "var", "pathFrom", "=", "[", "]", ";", "while", "(", "from", "&&", "from", "!==", "common", ")", "{", "pathFrom", ".", "push", "(", "from", ")", ";", "from", "=", "getParent", "(", "from", ")", ";", "}", "var", "pathTo", "=", "[", "]", ";", "while", "(", "to", "&&", "to", "!==", "common", ")", "{", "pathTo", ".", "push", "(", "to", ")", ";", "to", "=", "getParent", "(", "to", ")", ";", "}", "var", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "pathFrom", ".", "length", ";", "i", "++", ")", "{", "fn", "(", "pathFrom", "[", "i", "]", ",", "'bubbled'", ",", "argFrom", ")", ";", "}", "for", "(", "i", "=", "pathTo", ".", "length", ";", "i", "--", ">", "0", ";", ")", "{", "fn", "(", "pathTo", "[", "i", "]", ",", "'captured'", ",", "argTo", ")", ";", "}", "}" ]
Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that should would receive a `mouseEnter` or `mouseLeave` event. Does not invoke the callback on the nearest common ancestor because nothing "entered" or "left" that element.
[ "Traverses", "the", "ID", "hierarchy", "and", "invokes", "the", "supplied", "cb", "on", "any", "IDs", "that", "should", "would", "receive", "a", "mouseEnter", "or", "mouseLeave", "event", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L18365-L18384
10,333
jossmac/react-images
examples/dist/common.js
listenerAtPhase
function listenerAtPhase(inst, event, propagationPhase) { var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(inst, registrationName); }
javascript
function listenerAtPhase(inst, event, propagationPhase) { var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(inst, registrationName); }
[ "function", "listenerAtPhase", "(", "inst", ",", "event", ",", "propagationPhase", ")", "{", "var", "registrationName", "=", "event", ".", "dispatchConfig", ".", "phasedRegistrationNames", "[", "propagationPhase", "]", ";", "return", "getListener", "(", "inst", ",", "registrationName", ")", ";", "}" ]
Some event types have a notion of different registration names for different "phases" of propagation. This finds listeners by a given phase.
[ "Some", "event", "types", "have", "a", "notion", "of", "different", "registration", "names", "for", "different", "phases", "of", "propagation", ".", "This", "finds", "listeners", "by", "a", "given", "phase", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L18404-L18407
10,334
jossmac/react-images
examples/dist/common.js
accumulateDirectDispatchesSingle
function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event._targetInst, null, event); } }
javascript
function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event._targetInst, null, event); } }
[ "function", "accumulateDirectDispatchesSingle", "(", "event", ")", "{", "if", "(", "event", "&&", "event", ".", "dispatchConfig", ".", "registrationName", ")", "{", "accumulateDispatches", "(", "event", ".", "_targetInst", ",", "null", ",", "event", ")", ";", "}", "}" ]
Accumulates dispatches on an `SyntheticEvent`, but only for the `dispatchMarker`. @param {SyntheticEvent} event
[ "Accumulates", "dispatches", "on", "an", "SyntheticEvent", "but", "only", "for", "the", "dispatchMarker", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L18471-L18475
10,335
jossmac/react-images
examples/dist/common.js
isPresto
function isPresto() { var opera = window.opera; return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12; }
javascript
function isPresto() { var opera = window.opera; return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12; }
[ "function", "isPresto", "(", ")", "{", "var", "opera", "=", "window", ".", "opera", ";", "return", "typeof", "opera", "===", "'object'", "&&", "typeof", "opera", ".", "version", "===", "'function'", "&&", "parseInt", "(", "opera", ".", "version", "(", ")", ",", "10", ")", "<=", "12", ";", "}" ]
Opera <= 12 includes TextEvent in window, but does not fire text input events. Rely on keypress instead.
[ "Opera", "<", "=", "12", "includes", "TextEvent", "in", "window", "but", "does", "not", "fire", "text", "input", "events", ".", "Rely", "on", "keypress", "instead", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L18926-L18929
10,336
jossmac/react-images
examples/dist/common.js
isFallbackCompositionEnd
function isFallbackCompositionEnd(topLevelType, nativeEvent) { switch (topLevelType) { case 'topKeyUp': // Command keys insert or clear IME input. return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; case 'topKeyDown': // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return nativeEvent.keyCode !== START_KEYCODE; case 'topKeyPress': case 'topMouseDown': case 'topBlur': // Events are not possible without cancelling IME. return true; default: return false; } }
javascript
function isFallbackCompositionEnd(topLevelType, nativeEvent) { switch (topLevelType) { case 'topKeyUp': // Command keys insert or clear IME input. return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; case 'topKeyDown': // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return nativeEvent.keyCode !== START_KEYCODE; case 'topKeyPress': case 'topMouseDown': case 'topBlur': // Events are not possible without cancelling IME. return true; default: return false; } }
[ "function", "isFallbackCompositionEnd", "(", "topLevelType", ",", "nativeEvent", ")", "{", "switch", "(", "topLevelType", ")", "{", "case", "'topKeyUp'", ":", "// Command keys insert or clear IME input.", "return", "END_KEYCODES", ".", "indexOf", "(", "nativeEvent", ".", "keyCode", ")", "!==", "-", "1", ";", "case", "'topKeyDown'", ":", "// Expect IME keyCode on each keydown. If we get any other", "// code we must have exited earlier.", "return", "nativeEvent", ".", "keyCode", "!==", "START_KEYCODE", ";", "case", "'topKeyPress'", ":", "case", "'topMouseDown'", ":", "case", "'topBlur'", ":", "// Events are not possible without cancelling IME.", "return", "true", ";", "default", ":", "return", "false", ";", "}", "}" ]
Does our fallback mode think that this event is the end of composition? @param {string} topLevelType @param {object} nativeEvent @return {boolean}
[ "Does", "our", "fallback", "mode", "think", "that", "this", "event", "is", "the", "end", "of", "composition?" ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L19016-L19033
10,337
jossmac/react-images
examples/dist/common.js
extractBeforeInputEvent
function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var chars; if (canUseTextInputEvent) { chars = getNativeBeforeInputChars(topLevelType, nativeEvent); } else { chars = getFallbackBeforeInputChars(topLevelType, nativeEvent); } // If no characters are being inserted, no BeforeInput event should // be fired. if (!chars) { return null; } var event = SyntheticInputEvent_1.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget); event.data = chars; EventPropagators_1.accumulateTwoPhaseDispatches(event); return event; }
javascript
function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var chars; if (canUseTextInputEvent) { chars = getNativeBeforeInputChars(topLevelType, nativeEvent); } else { chars = getFallbackBeforeInputChars(topLevelType, nativeEvent); } // If no characters are being inserted, no BeforeInput event should // be fired. if (!chars) { return null; } var event = SyntheticInputEvent_1.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget); event.data = chars; EventPropagators_1.accumulateTwoPhaseDispatches(event); return event; }
[ "function", "extractBeforeInputEvent", "(", "topLevelType", ",", "targetInst", ",", "nativeEvent", ",", "nativeEventTarget", ")", "{", "var", "chars", ";", "if", "(", "canUseTextInputEvent", ")", "{", "chars", "=", "getNativeBeforeInputChars", "(", "topLevelType", ",", "nativeEvent", ")", ";", "}", "else", "{", "chars", "=", "getFallbackBeforeInputChars", "(", "topLevelType", ",", "nativeEvent", ")", ";", "}", "// If no characters are being inserted, no BeforeInput event should", "// be fired.", "if", "(", "!", "chars", ")", "{", "return", "null", ";", "}", "var", "event", "=", "SyntheticInputEvent_1", ".", "getPooled", "(", "eventTypes", ".", "beforeInput", ",", "targetInst", ",", "nativeEvent", ",", "nativeEventTarget", ")", ";", "event", ".", "data", "=", "chars", ";", "EventPropagators_1", ".", "accumulateTwoPhaseDispatches", "(", "event", ")", ";", "return", "event", ";", "}" ]
Extract a SyntheticInputEvent for `beforeInput`, based on either native `textInput` or fallback behavior. @return {?object} A SyntheticInputEvent.
[ "Extract", "a", "SyntheticInputEvent", "for", "beforeInput", "based", "on", "either", "native", "textInput", "or", "fallback", "behavior", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L19228-L19248
10,338
jossmac/react-images
examples/dist/common.js
modifierStateGetter
function modifierStateGetter(keyArg) { var syntheticEvent = this; var nativeEvent = syntheticEvent.nativeEvent; if (nativeEvent.getModifierState) { return nativeEvent.getModifierState(keyArg); } var keyProp = modifierKeyToProp[keyArg]; return keyProp ? !!nativeEvent[keyProp] : false; }
javascript
function modifierStateGetter(keyArg) { var syntheticEvent = this; var nativeEvent = syntheticEvent.nativeEvent; if (nativeEvent.getModifierState) { return nativeEvent.getModifierState(keyArg); } var keyProp = modifierKeyToProp[keyArg]; return keyProp ? !!nativeEvent[keyProp] : false; }
[ "function", "modifierStateGetter", "(", "keyArg", ")", "{", "var", "syntheticEvent", "=", "this", ";", "var", "nativeEvent", "=", "syntheticEvent", ".", "nativeEvent", ";", "if", "(", "nativeEvent", ".", "getModifierState", ")", "{", "return", "nativeEvent", ".", "getModifierState", "(", "keyArg", ")", ";", "}", "var", "keyProp", "=", "modifierKeyToProp", "[", "keyArg", "]", ";", "return", "keyProp", "?", "!", "!", "nativeEvent", "[", "keyProp", "]", ":", "false", ";", "}" ]
IE8 does not implement getModifierState so we simply map it to the only modifier keys exposed by the event itself, does not support Lock-keys. Currently, all major browsers except Chrome seems to support Lock-keys.
[ "IE8", "does", "not", "implement", "getModifierState", "so", "we", "simply", "map", "it", "to", "the", "only", "modifier", "keys", "exposed", "by", "the", "event", "itself", "does", "not", "support", "Lock", "-", "keys", ".", "Currently", "all", "major", "browsers", "except", "Chrome", "seems", "to", "support", "Lock", "-", "keys", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L19662-L19670
10,339
jossmac/react-images
examples/dist/common.js
isValidContainer
function isValidContainer(node) { return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || node.nodeType === COMMENT_NODE && node.nodeValue === ' react-mount-point-unstable ')); }
javascript
function isValidContainer(node) { return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || node.nodeType === COMMENT_NODE && node.nodeValue === ' react-mount-point-unstable ')); }
[ "function", "isValidContainer", "(", "node", ")", "{", "return", "!", "!", "(", "node", "&&", "(", "node", ".", "nodeType", "===", "ELEMENT_NODE", "||", "node", ".", "nodeType", "===", "DOCUMENT_NODE", "||", "node", ".", "nodeType", "===", "DOCUMENT_FRAGMENT_NODE", "||", "node", ".", "nodeType", "===", "COMMENT_NODE", "&&", "node", ".", "nodeValue", "===", "' react-mount-point-unstable '", ")", ")", ";", "}" ]
True if the supplied DOM node is a valid node element. @param {?DOMElement} node The candidate DOM node. @return {boolean} True if the DOM is a valid DOM node. @internal
[ "True", "if", "the", "supplied", "DOM", "node", "is", "a", "valid", "node", "element", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L20758-L20760
10,340
jossmac/react-images
examples/dist/common.js
finish
function finish(e) { if (e && e.target !== node) { return; } clearTimeout(timer); if (removeListeners) removeListeners(); (0, _removeClass2.default)(node, className); (0, _removeClass2.default)(node, activeClassName); if (removeListeners) removeListeners(); // Usually this optional callback is used for informing an owner of // a leave animation and telling it to remove the child. if (finishCallback) { finishCallback(); } }
javascript
function finish(e) { if (e && e.target !== node) { return; } clearTimeout(timer); if (removeListeners) removeListeners(); (0, _removeClass2.default)(node, className); (0, _removeClass2.default)(node, activeClassName); if (removeListeners) removeListeners(); // Usually this optional callback is used for informing an owner of // a leave animation and telling it to remove the child. if (finishCallback) { finishCallback(); } }
[ "function", "finish", "(", "e", ")", "{", "if", "(", "e", "&&", "e", ".", "target", "!==", "node", ")", "{", "return", ";", "}", "clearTimeout", "(", "timer", ")", ";", "if", "(", "removeListeners", ")", "removeListeners", "(", ")", ";", "(", "0", ",", "_removeClass2", ".", "default", ")", "(", "node", ",", "className", ")", ";", "(", "0", ",", "_removeClass2", ".", "default", ")", "(", "node", ",", "activeClassName", ")", ";", "if", "(", "removeListeners", ")", "removeListeners", "(", ")", ";", "// Usually this optional callback is used for informing an owner of", "// a leave animation and telling it to remove the child.", "if", "(", "finishCallback", ")", "{", "finishCallback", "(", ")", ";", "}", "}" ]
Clean-up the animation after the specified delay
[ "Clean", "-", "up", "the", "animation", "after", "the", "specified", "delay" ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L22303-L22321
10,341
jossmac/react-images
examples/dist/common.js
getChildMapping
function getChildMapping(children) { if (!children) { return children; } var result = {}; _react.Children.map(children, function (child) { return child; }).forEach(function (child) { result[child.key] = child; }); return result; }
javascript
function getChildMapping(children) { if (!children) { return children; } var result = {}; _react.Children.map(children, function (child) { return child; }).forEach(function (child) { result[child.key] = child; }); return result; }
[ "function", "getChildMapping", "(", "children", ")", "{", "if", "(", "!", "children", ")", "{", "return", "children", ";", "}", "var", "result", "=", "{", "}", ";", "_react", ".", "Children", ".", "map", "(", "children", ",", "function", "(", "child", ")", "{", "return", "child", ";", "}", ")", ".", "forEach", "(", "function", "(", "child", ")", "{", "result", "[", "child", ".", "key", "]", "=", "child", ";", "}", ")", ";", "return", "result", ";", "}" ]
Given `this.props.children`, return an object mapping key to child. @param {*} children `this.props.children` @return {object} Mapping of key to child
[ "Given", "this", ".", "props", ".", "children", "return", "an", "object", "mapping", "key", "to", "child", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L22672-L22683
10,342
jossmac/react-images
examples/dist/common.js
escape
function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { '=': '=0', ':': '=2' }; var escapedString = ('' + key).replace(escapeRegex, function (match) { return escaperLookup[match]; }); return '$' + escapedString; }
javascript
function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { '=': '=0', ':': '=2' }; var escapedString = ('' + key).replace(escapeRegex, function (match) { return escaperLookup[match]; }); return '$' + escapedString; }
[ "function", "escape", "(", "key", ")", "{", "var", "escapeRegex", "=", "/", "[=:]", "/", "g", ";", "var", "escaperLookup", "=", "{", "'='", ":", "'=0'", ",", "':'", ":", "'=2'", "}", ";", "var", "escapedString", "=", "(", "''", "+", "key", ")", ".", "replace", "(", "escapeRegex", ",", "function", "(", "match", ")", "{", "return", "escaperLookup", "[", "match", "]", ";", "}", ")", ";", "return", "'$'", "+", "escapedString", ";", "}" ]
Escape and wrap key so it is safe to use as a reactid @param {string} key to be escaped. @return {string} the escaped key.
[ "Escape", "and", "wrap", "key", "so", "it", "is", "safe", "to", "use", "as", "a", "reactid" ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L23509-L23520
10,343
jossmac/react-images
examples/dist/common.js
getComponentKey
function getComponentKey(component, index) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (typeof component === 'object' && component !== null && component.key != null) { // Explicit key return escape(component.key); } // Implicit key determined by the index in the set return index.toString(36); }
javascript
function getComponentKey(component, index) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (typeof component === 'object' && component !== null && component.key != null) { // Explicit key return escape(component.key); } // Implicit key determined by the index in the set return index.toString(36); }
[ "function", "getComponentKey", "(", "component", ",", "index", ")", "{", "// Do some typechecking here since we call this blindly. We want to ensure", "// that we don't block potential future ES APIs.", "if", "(", "typeof", "component", "===", "'object'", "&&", "component", "!==", "null", "&&", "component", ".", "key", "!=", "null", ")", "{", "// Explicit key", "return", "escape", "(", "component", ".", "key", ")", ";", "}", "// Implicit key determined by the index in the set", "return", "index", ".", "toString", "(", "36", ")", ";", "}" ]
Generate a key string that identifies a component within a set. @param {*} component A component that could contain a manual key. @param {number} index Index that is used if a manual key is not provided. @return {string}
[ "Generate", "a", "key", "string", "that", "identifies", "a", "component", "within", "a", "set", "." ]
c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3
https://github.com/jossmac/react-images/blob/c6d9c2b9b92cc02e8fb9bfd5c0550d53aa4a14e3/examples/dist/common.js#L23668-L23677
10,344
zhoushengmufc/iosselect
demo/ajax/zepto.js
triggerGlobal
function triggerGlobal(settings, context, eventName, data) { if (settings.global) return triggerAndReturn(context || document, eventName, data); }
javascript
function triggerGlobal(settings, context, eventName, data) { if (settings.global) return triggerAndReturn(context || document, eventName, data); }
[ "function", "triggerGlobal", "(", "settings", ",", "context", ",", "eventName", ",", "data", ")", "{", "if", "(", "settings", ".", "global", ")", "return", "triggerAndReturn", "(", "context", "||", "document", ",", "eventName", ",", "data", ")", ";", "}" ]
trigger an Ajax "global" event
[ "trigger", "an", "Ajax", "global", "event" ]
e32b1614e9c1c1417d16bfb5e47ba543d6d64f0f
https://github.com/zhoushengmufc/iosselect/blob/e32b1614e9c1c1417d16bfb5e47ba543d6d64f0f/demo/ajax/zepto.js#L1386-L1389
10,345
zhoushengmufc/iosselect
demo/ajax/zepto.js
ajaxBeforeSend
function ajaxBeforeSend(xhr, settings) { var context = settings.context; if (settings.beforeSend.call(context, xhr, settings) === false || triggerGlobal(settings, context, 'ajaxBeforeSend', [ xhr, settings ]) === false) return false; triggerGlobal(settings, context, 'ajaxSend', [ xhr, settings ]); }
javascript
function ajaxBeforeSend(xhr, settings) { var context = settings.context; if (settings.beforeSend.call(context, xhr, settings) === false || triggerGlobal(settings, context, 'ajaxBeforeSend', [ xhr, settings ]) === false) return false; triggerGlobal(settings, context, 'ajaxSend', [ xhr, settings ]); }
[ "function", "ajaxBeforeSend", "(", "xhr", ",", "settings", ")", "{", "var", "context", "=", "settings", ".", "context", ";", "if", "(", "settings", ".", "beforeSend", ".", "call", "(", "context", ",", "xhr", ",", "settings", ")", "===", "false", "||", "triggerGlobal", "(", "settings", ",", "context", ",", "'ajaxBeforeSend'", ",", "[", "xhr", ",", "settings", "]", ")", "===", "false", ")", "return", "false", ";", "triggerGlobal", "(", "settings", ",", "context", ",", "'ajaxSend'", ",", "[", "xhr", ",", "settings", "]", ")", ";", "}" ]
triggers an extra global event "ajaxBeforeSend" that's like "ajaxSend" but cancelable
[ "triggers", "an", "extra", "global", "event", "ajaxBeforeSend", "that", "s", "like", "ajaxSend", "but", "cancelable" ]
e32b1614e9c1c1417d16bfb5e47ba543d6d64f0f
https://github.com/zhoushengmufc/iosselect/blob/e32b1614e9c1c1417d16bfb5e47ba543d6d64f0f/demo/ajax/zepto.js#L1404-L1416
10,346
minirefresh/minirefresh
examples/scroll-nested/libs/swipe/js/swiper.jquery.js
function (e) { if (e.targetTouches.length < 2) return 1; var x1 = e.targetTouches[0].pageX, y1 = e.targetTouches[0].pageY, x2 = e.targetTouches[1].pageX, y2 = e.targetTouches[1].pageY; var distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); return distance; }
javascript
function (e) { if (e.targetTouches.length < 2) return 1; var x1 = e.targetTouches[0].pageX, y1 = e.targetTouches[0].pageY, x2 = e.targetTouches[1].pageX, y2 = e.targetTouches[1].pageY; var distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); return distance; }
[ "function", "(", "e", ")", "{", "if", "(", "e", ".", "targetTouches", ".", "length", "<", "2", ")", "return", "1", ";", "var", "x1", "=", "e", ".", "targetTouches", "[", "0", "]", ".", "pageX", ",", "y1", "=", "e", ".", "targetTouches", "[", "0", "]", ".", "pageY", ",", "x2", "=", "e", ".", "targetTouches", "[", "1", "]", ".", "pageX", ",", "y2", "=", "e", ".", "targetTouches", "[", "1", "]", ".", "pageY", ";", "var", "distance", "=", "Math", ".", "sqrt", "(", "Math", ".", "pow", "(", "x2", "-", "x1", ",", "2", ")", "+", "Math", ".", "pow", "(", "y2", "-", "y1", ",", "2", ")", ")", ";", "return", "distance", ";", "}" ]
Calc Scale From Multi-touches
[ "Calc", "Scale", "From", "Multi", "-", "touches" ]
8c74d46b4e7e7b22ae4807032887b9e5e3391d8a
https://github.com/minirefresh/minirefresh/blob/8c74d46b4e7e7b22ae4807032887b9e5e3391d8a/examples/scroll-nested/libs/swipe/js/swiper.jquery.js#L3834-L3842
10,347
watson-developer-cloud/node-sdk
examples/assistant_tone_analyzer_integration/tone_detection.js
invokeToneAsync
function invokeToneAsync(assistantPayload, toneAnalyzer) { return new Promise(function(resolve, reject) { toneAnalyzer.tone({ text: assistantPayload.input.text }, function(error, data) { if (error) { reject(error); } else { resolve(data); } }); }); }
javascript
function invokeToneAsync(assistantPayload, toneAnalyzer) { return new Promise(function(resolve, reject) { toneAnalyzer.tone({ text: assistantPayload.input.text }, function(error, data) { if (error) { reject(error); } else { resolve(data); } }); }); }
[ "function", "invokeToneAsync", "(", "assistantPayload", ",", "toneAnalyzer", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "toneAnalyzer", ".", "tone", "(", "{", "text", ":", "assistantPayload", ".", "input", ".", "text", "}", ",", "function", "(", "error", ",", "data", ")", "{", "if", "(", "error", ")", "{", "reject", "(", "error", ")", ";", "}", "else", "{", "resolve", "(", "data", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
invokeToneAsync is an asynchronous function that calls the Tone Analyzer service and returns a Promise @param assistantPayload json object returned by the Watson Assistant Service @param toneAnalyzer an instance of the Watson Tone Analyzer service @return a Promise for the result of calling the toneAnalyzer with the assistantPayload (which contains the user's input text)
[ "invokeToneAsync", "is", "an", "asynchronous", "function", "that", "calls", "the", "Tone", "Analyzer", "service", "and", "returns", "a", "Promise" ]
f97aa72e3edec655a2d40fae64560d709a56e9c7
https://github.com/watson-developer-cloud/node-sdk/blob/f97aa72e3edec655a2d40fae64560d709a56e9c7/examples/assistant_tone_analyzer_integration/tone_detection.js#L36-L46
10,348
watson-developer-cloud/node-sdk
examples/assistant_tone_analyzer_integration/tone_detection.js
updateTone
function updateTone(user, tones, maintainHistory) { var maxScore = 0.0; var primaryTone = null; var primaryToneScore = null; tones.forEach(function(tone) { if (tone.score > maxScore) { maxScore = tone.score; primaryTone = tone.tone_name.toLowerCase(); primaryToneScore = tone.score; } }); // update user tone user.tone.current = primaryTone; if (maintainHistory) { if (typeof user.tone.history === 'undefined') { user.tone.history = []; } user.tone.history.push({ tone_name: primaryTone, score: primaryToneScore, }); } }
javascript
function updateTone(user, tones, maintainHistory) { var maxScore = 0.0; var primaryTone = null; var primaryToneScore = null; tones.forEach(function(tone) { if (tone.score > maxScore) { maxScore = tone.score; primaryTone = tone.tone_name.toLowerCase(); primaryToneScore = tone.score; } }); // update user tone user.tone.current = primaryTone; if (maintainHistory) { if (typeof user.tone.history === 'undefined') { user.tone.history = []; } user.tone.history.push({ tone_name: primaryTone, score: primaryToneScore, }); } }
[ "function", "updateTone", "(", "user", ",", "tones", ",", "maintainHistory", ")", "{", "var", "maxScore", "=", "0.0", ";", "var", "primaryTone", "=", "null", ";", "var", "primaryToneScore", "=", "null", ";", "tones", ".", "forEach", "(", "function", "(", "tone", ")", "{", "if", "(", "tone", ".", "score", ">", "maxScore", ")", "{", "maxScore", "=", "tone", ".", "score", ";", "primaryTone", "=", "tone", ".", "tone_name", ".", "toLowerCase", "(", ")", ";", "primaryToneScore", "=", "tone", ".", "score", ";", "}", "}", ")", ";", "// update user tone", "user", ".", "tone", ".", "current", "=", "primaryTone", ";", "if", "(", "maintainHistory", ")", "{", "if", "(", "typeof", "user", ".", "tone", ".", "history", "===", "'undefined'", ")", "{", "user", ".", "tone", ".", "history", "=", "[", "]", ";", "}", "user", ".", "tone", ".", "history", ".", "push", "(", "{", "tone_name", ":", "primaryTone", ",", "score", ":", "primaryToneScore", ",", "}", ")", ";", "}", "}" ]
updateTone updates the user tone with the primary tone - the tone with the largest score @param user a json object representing user information (tone) to be used in conversing with the assistant Service @param tones an array containing the document-level tones in the payload returned by the Tone Analyzer
[ "updateTone", "updates", "the", "user", "tone", "with", "the", "primary", "tone", "-", "the", "tone", "with", "the", "largest", "score" ]
f97aa72e3edec655a2d40fae64560d709a56e9c7
https://github.com/watson-developer-cloud/node-sdk/blob/f97aa72e3edec655a2d40fae64560d709a56e9c7/examples/assistant_tone_analyzer_integration/tone_detection.js#L99-L124
10,349
watson-developer-cloud/node-sdk
examples/speech_to_text.v1.js
onEvent
function onEvent(name, event) { console.log(name, JSON.stringify(event, null, 2)); }
javascript
function onEvent(name, event) { console.log(name, JSON.stringify(event, null, 2)); }
[ "function", "onEvent", "(", "name", ",", "event", ")", "{", "console", ".", "log", "(", "name", ",", "JSON", ".", "stringify", "(", "event", ",", "null", ",", "2", ")", ")", ";", "}" ]
Displays events on the console.
[ "Displays", "events", "on", "the", "console", "." ]
f97aa72e3edec655a2d40fae64560d709a56e9c7
https://github.com/watson-developer-cloud/node-sdk/blob/f97aa72e3edec655a2d40fae64560d709a56e9c7/examples/speech_to_text.v1.js#L45-L47
10,350
nodegit/nodegit
examples/walk-history-for-file.js
compileHistory
function compileHistory(resultingArrayOfCommits) { var lastSha; if (historyCommits.length > 0) { lastSha = historyCommits[historyCommits.length - 1].commit.sha(); if ( resultingArrayOfCommits.length == 1 && resultingArrayOfCommits[0].commit.sha() == lastSha ) { return; } } resultingArrayOfCommits.forEach(function(entry) { historyCommits.push(entry); }); lastSha = historyCommits[historyCommits.length - 1].commit.sha(); walker = repo.createRevWalk(); walker.push(lastSha); walker.sorting(nodegit.Revwalk.SORT.TIME); return walker.fileHistoryWalk(historyFile, 500) .then(compileHistory); }
javascript
function compileHistory(resultingArrayOfCommits) { var lastSha; if (historyCommits.length > 0) { lastSha = historyCommits[historyCommits.length - 1].commit.sha(); if ( resultingArrayOfCommits.length == 1 && resultingArrayOfCommits[0].commit.sha() == lastSha ) { return; } } resultingArrayOfCommits.forEach(function(entry) { historyCommits.push(entry); }); lastSha = historyCommits[historyCommits.length - 1].commit.sha(); walker = repo.createRevWalk(); walker.push(lastSha); walker.sorting(nodegit.Revwalk.SORT.TIME); return walker.fileHistoryWalk(historyFile, 500) .then(compileHistory); }
[ "function", "compileHistory", "(", "resultingArrayOfCommits", ")", "{", "var", "lastSha", ";", "if", "(", "historyCommits", ".", "length", ">", "0", ")", "{", "lastSha", "=", "historyCommits", "[", "historyCommits", ".", "length", "-", "1", "]", ".", "commit", ".", "sha", "(", ")", ";", "if", "(", "resultingArrayOfCommits", ".", "length", "==", "1", "&&", "resultingArrayOfCommits", "[", "0", "]", ".", "commit", ".", "sha", "(", ")", "==", "lastSha", ")", "{", "return", ";", "}", "}", "resultingArrayOfCommits", ".", "forEach", "(", "function", "(", "entry", ")", "{", "historyCommits", ".", "push", "(", "entry", ")", ";", "}", ")", ";", "lastSha", "=", "historyCommits", "[", "historyCommits", ".", "length", "-", "1", "]", ".", "commit", ".", "sha", "(", ")", ";", "walker", "=", "repo", ".", "createRevWalk", "(", ")", ";", "walker", ".", "push", "(", "lastSha", ")", ";", "walker", ".", "sorting", "(", "nodegit", ".", "Revwalk", ".", "SORT", ".", "TIME", ")", ";", "return", "walker", ".", "fileHistoryWalk", "(", "historyFile", ",", "500", ")", ".", "then", "(", "compileHistory", ")", ";", "}" ]
This code walks the history of the master branch and prints results that look very similar to calling `git log` from the command line
[ "This", "code", "walks", "the", "history", "of", "the", "master", "branch", "and", "prints", "results", "that", "look", "very", "similar", "to", "calling", "git", "log", "from", "the", "command", "line" ]
764146ca8054cd2839685c423bc2e5ba727165e9
https://github.com/nodegit/nodegit/blob/764146ca8054cd2839685c423bc2e5ba727165e9/examples/walk-history-for-file.js#L12-L36
10,351
nodegit/nodegit
examples/general.js
walk
function walk() { return revWalk.next().then(function(oid) { if (!oid) { return; } return repo.getCommit(oid).then(function(commit) { console.log("Commit:", commit.toString()); return walk(); }); }); }
javascript
function walk() { return revWalk.next().then(function(oid) { if (!oid) { return; } return repo.getCommit(oid).then(function(commit) { console.log("Commit:", commit.toString()); return walk(); }); }); }
[ "function", "walk", "(", ")", "{", "return", "revWalk", ".", "next", "(", ")", ".", "then", "(", "function", "(", "oid", ")", "{", "if", "(", "!", "oid", ")", "{", "return", ";", "}", "return", "repo", ".", "getCommit", "(", "oid", ")", ".", "then", "(", "function", "(", "commit", ")", "{", "console", ".", "log", "(", "\"Commit:\"", ",", "commit", ".", "toString", "(", ")", ")", ";", "return", "walk", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Now that we have the starting point pushed onto the walker, we start asking for ancestors. It will return them in the sorting order we asked for as commit oids. We can then lookup and parse the commited pointed at by the returned OID; note that this operation is specially fast since the raw contents of the commit object will be cached in memory
[ "Now", "that", "we", "have", "the", "starting", "point", "pushed", "onto", "the", "walker", "we", "start", "asking", "for", "ancestors", ".", "It", "will", "return", "them", "in", "the", "sorting", "order", "we", "asked", "for", "as", "commit", "oids", ".", "We", "can", "then", "lookup", "and", "parse", "the", "commited", "pointed", "at", "by", "the", "returned", "OID", ";", "note", "that", "this", "operation", "is", "specially", "fast", "since", "the", "raw", "contents", "of", "the", "commit", "object", "will", "be", "cached", "in", "memory" ]
764146ca8054cd2839685c423bc2e5ba727165e9
https://github.com/nodegit/nodegit/blob/764146ca8054cd2839685c423bc2e5ba727165e9/examples/general.js#L301-L312
10,352
nodegit/nodegit
lib/repository.js
performRebase
function performRebase( repository, rebase, signature, beforeNextFn, beforeFinishFn ) { var beforeNextFnResult; /* In the case of FF merges and a beforeFinishFn, this will fail * when looking for 'rewritten' so we need to handle that case. */ function readRebaseMetadataFile(fileName, continueOnError) { return fse.readFile( path.join(repository.path(), "rebase-merge", fileName), { encoding: "utf8" } ) .then(fp.trim) .catch(function(err) { if (continueOnError) { return null; } throw err; }); } function calcHeadName(input) { return input.replace(/refs\/heads\/(.*)/, "$1"); } function getPromise() { return rebase.next() .then(function() { return repository.refreshIndex(); }) .then(function(index) { if (index.hasConflicts()) { throw index; } return rebase.commit(null, signature); }) .then(function() { return performRebase( repository, rebase, signature, beforeNextFn, beforeFinishFn ); }) .catch(function(error) { if (error && error.errno === NodeGit.Error.CODE.ITEROVER) { const calcRewritten = fp.cond([ [fp.isEmpty, fp.constant(null)], [fp.stubTrue, fp.flow([ fp.split("\n"), fp.map(fp.split(" ")) ])] ]); const beforeFinishFnPromise = !beforeFinishFn ? Promise.resolve() : Promise.all([ readRebaseMetadataFile("onto_name"), readRebaseMetadataFile("onto"), readRebaseMetadataFile("head-name").then(calcHeadName), readRebaseMetadataFile("orig-head"), readRebaseMetadataFile("rewritten", true).then(calcRewritten) ]) .then(function([ ontoName, ontoSha, originalHeadName, originalHeadSha, rewritten ]) { return beforeFinishFn({ ontoName, ontoSha, originalHeadName, originalHeadSha, rebase, rewritten }); }); return beforeFinishFnPromise .then(function() { return rebase.finish(signature); }); } else { throw error; } }); } if(beforeNextFn) { beforeNextFnResult = beforeNextFn(rebase); // if beforeNextFn returns a promise, chain the promise return Promise.resolve(beforeNextFnResult) .then(getPromise); } return getPromise(); }
javascript
function performRebase( repository, rebase, signature, beforeNextFn, beforeFinishFn ) { var beforeNextFnResult; /* In the case of FF merges and a beforeFinishFn, this will fail * when looking for 'rewritten' so we need to handle that case. */ function readRebaseMetadataFile(fileName, continueOnError) { return fse.readFile( path.join(repository.path(), "rebase-merge", fileName), { encoding: "utf8" } ) .then(fp.trim) .catch(function(err) { if (continueOnError) { return null; } throw err; }); } function calcHeadName(input) { return input.replace(/refs\/heads\/(.*)/, "$1"); } function getPromise() { return rebase.next() .then(function() { return repository.refreshIndex(); }) .then(function(index) { if (index.hasConflicts()) { throw index; } return rebase.commit(null, signature); }) .then(function() { return performRebase( repository, rebase, signature, beforeNextFn, beforeFinishFn ); }) .catch(function(error) { if (error && error.errno === NodeGit.Error.CODE.ITEROVER) { const calcRewritten = fp.cond([ [fp.isEmpty, fp.constant(null)], [fp.stubTrue, fp.flow([ fp.split("\n"), fp.map(fp.split(" ")) ])] ]); const beforeFinishFnPromise = !beforeFinishFn ? Promise.resolve() : Promise.all([ readRebaseMetadataFile("onto_name"), readRebaseMetadataFile("onto"), readRebaseMetadataFile("head-name").then(calcHeadName), readRebaseMetadataFile("orig-head"), readRebaseMetadataFile("rewritten", true).then(calcRewritten) ]) .then(function([ ontoName, ontoSha, originalHeadName, originalHeadSha, rewritten ]) { return beforeFinishFn({ ontoName, ontoSha, originalHeadName, originalHeadSha, rebase, rewritten }); }); return beforeFinishFnPromise .then(function() { return rebase.finish(signature); }); } else { throw error; } }); } if(beforeNextFn) { beforeNextFnResult = beforeNextFn(rebase); // if beforeNextFn returns a promise, chain the promise return Promise.resolve(beforeNextFnResult) .then(getPromise); } return getPromise(); }
[ "function", "performRebase", "(", "repository", ",", "rebase", ",", "signature", ",", "beforeNextFn", ",", "beforeFinishFn", ")", "{", "var", "beforeNextFnResult", ";", "/* In the case of FF merges and a beforeFinishFn, this will fail\n * when looking for 'rewritten' so we need to handle that case.\n */", "function", "readRebaseMetadataFile", "(", "fileName", ",", "continueOnError", ")", "{", "return", "fse", ".", "readFile", "(", "path", ".", "join", "(", "repository", ".", "path", "(", ")", ",", "\"rebase-merge\"", ",", "fileName", ")", ",", "{", "encoding", ":", "\"utf8\"", "}", ")", ".", "then", "(", "fp", ".", "trim", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "if", "(", "continueOnError", ")", "{", "return", "null", ";", "}", "throw", "err", ";", "}", ")", ";", "}", "function", "calcHeadName", "(", "input", ")", "{", "return", "input", ".", "replace", "(", "/", "refs\\/heads\\/(.*)", "/", ",", "\"$1\"", ")", ";", "}", "function", "getPromise", "(", ")", "{", "return", "rebase", ".", "next", "(", ")", ".", "then", "(", "function", "(", ")", "{", "return", "repository", ".", "refreshIndex", "(", ")", ";", "}", ")", ".", "then", "(", "function", "(", "index", ")", "{", "if", "(", "index", ".", "hasConflicts", "(", ")", ")", "{", "throw", "index", ";", "}", "return", "rebase", ".", "commit", "(", "null", ",", "signature", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "performRebase", "(", "repository", ",", "rebase", ",", "signature", ",", "beforeNextFn", ",", "beforeFinishFn", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "error", ")", "{", "if", "(", "error", "&&", "error", ".", "errno", "===", "NodeGit", ".", "Error", ".", "CODE", ".", "ITEROVER", ")", "{", "const", "calcRewritten", "=", "fp", ".", "cond", "(", "[", "[", "fp", ".", "isEmpty", ",", "fp", ".", "constant", "(", "null", ")", "]", ",", "[", "fp", ".", "stubTrue", ",", "fp", ".", "flow", "(", "[", "fp", ".", "split", "(", "\"\\n\"", ")", ",", "fp", ".", "map", "(", "fp", ".", "split", "(", "\" \"", ")", ")", "]", ")", "]", "]", ")", ";", "const", "beforeFinishFnPromise", "=", "!", "beforeFinishFn", "?", "Promise", ".", "resolve", "(", ")", ":", "Promise", ".", "all", "(", "[", "readRebaseMetadataFile", "(", "\"onto_name\"", ")", ",", "readRebaseMetadataFile", "(", "\"onto\"", ")", ",", "readRebaseMetadataFile", "(", "\"head-name\"", ")", ".", "then", "(", "calcHeadName", ")", ",", "readRebaseMetadataFile", "(", "\"orig-head\"", ")", ",", "readRebaseMetadataFile", "(", "\"rewritten\"", ",", "true", ")", ".", "then", "(", "calcRewritten", ")", "]", ")", ".", "then", "(", "function", "(", "[", "ontoName", ",", "ontoSha", ",", "originalHeadName", ",", "originalHeadSha", ",", "rewritten", "]", ")", "{", "return", "beforeFinishFn", "(", "{", "ontoName", ",", "ontoSha", ",", "originalHeadName", ",", "originalHeadSha", ",", "rebase", ",", "rewritten", "}", ")", ";", "}", ")", ";", "return", "beforeFinishFnPromise", ".", "then", "(", "function", "(", ")", "{", "return", "rebase", ".", "finish", "(", "signature", ")", ";", "}", ")", ";", "}", "else", "{", "throw", "error", ";", "}", "}", ")", ";", "}", "if", "(", "beforeNextFn", ")", "{", "beforeNextFnResult", "=", "beforeNextFn", "(", "rebase", ")", ";", "// if beforeNextFn returns a promise, chain the promise", "return", "Promise", ".", "resolve", "(", "beforeNextFnResult", ")", ".", "then", "(", "getPromise", ")", ";", "}", "return", "getPromise", "(", ")", ";", "}" ]
Goes through a rebase's rebase operations and commits them if there are no merge conflicts @param {Repository} repository The repository that the rebase is being performed in @param {Rebase} rebase The current rebase being performed @param {Signature} signature Identity of the one performing the rebase @param {Function} beforeNextFn Callback to be called before each invocation of next(). If the callback returns a promise, the next() will be called when the promise resolves. @param {Function} beforeFinishFn Callback called before the invocation of finish(). If the callback returns a promise, finish() will be called when the promise resolves. This callback will be provided a detailed overview of the rebase @return {Int|Index} An error code for an unsuccesful rebase or an index for a rebase with conflicts
[ "Goes", "through", "a", "rebase", "s", "rebase", "operations", "and", "commits", "them", "if", "there", "are", "no", "merge", "conflicts" ]
764146ca8054cd2839685c423bc2e5ba727165e9
https://github.com/nodegit/nodegit/blob/764146ca8054cd2839685c423bc2e5ba727165e9/lib/repository.js#L213-L319
10,353
nodegit/nodegit
lib/repository.js
lastHunkStagedPromise
function lastHunkStagedPromise(result) { return NodeGit.Diff.indexToWorkdir(repo, index, { flags: NodeGit.Diff.OPTION.SHOW_UNTRACKED_CONTENT | NodeGit.Diff.OPTION.RECURSE_UNTRACKED_DIRS | (additionalDiffOptions || 0) }) .then(function(diff) { return diff.patches(); }) .then(function(patches) { var pathPatch = patches.filter(function(patch) { return patch.newFile().path() === filePath; }); var emptyPatch = false; if (pathPatch.length > 0) { // No hunks, unchanged file mode, and no type changes. emptyPatch = pathPatch[0].size() === 0 && pathPatch[0].oldFile().mode() === pathPatch[0].newFile().mode() && !pathPatch[0].isTypeChange(); } if (emptyPatch) { return index.addByPath(filePath) .then(function() { return index.write(); }); } return result; }); }
javascript
function lastHunkStagedPromise(result) { return NodeGit.Diff.indexToWorkdir(repo, index, { flags: NodeGit.Diff.OPTION.SHOW_UNTRACKED_CONTENT | NodeGit.Diff.OPTION.RECURSE_UNTRACKED_DIRS | (additionalDiffOptions || 0) }) .then(function(diff) { return diff.patches(); }) .then(function(patches) { var pathPatch = patches.filter(function(patch) { return patch.newFile().path() === filePath; }); var emptyPatch = false; if (pathPatch.length > 0) { // No hunks, unchanged file mode, and no type changes. emptyPatch = pathPatch[0].size() === 0 && pathPatch[0].oldFile().mode() === pathPatch[0].newFile().mode() && !pathPatch[0].isTypeChange(); } if (emptyPatch) { return index.addByPath(filePath) .then(function() { return index.write(); }); } return result; }); }
[ "function", "lastHunkStagedPromise", "(", "result", ")", "{", "return", "NodeGit", ".", "Diff", ".", "indexToWorkdir", "(", "repo", ",", "index", ",", "{", "flags", ":", "NodeGit", ".", "Diff", ".", "OPTION", ".", "SHOW_UNTRACKED_CONTENT", "|", "NodeGit", ".", "Diff", ".", "OPTION", ".", "RECURSE_UNTRACKED_DIRS", "|", "(", "additionalDiffOptions", "||", "0", ")", "}", ")", ".", "then", "(", "function", "(", "diff", ")", "{", "return", "diff", ".", "patches", "(", ")", ";", "}", ")", ".", "then", "(", "function", "(", "patches", ")", "{", "var", "pathPatch", "=", "patches", ".", "filter", "(", "function", "(", "patch", ")", "{", "return", "patch", ".", "newFile", "(", ")", ".", "path", "(", ")", "===", "filePath", ";", "}", ")", ";", "var", "emptyPatch", "=", "false", ";", "if", "(", "pathPatch", ".", "length", ">", "0", ")", "{", "// No hunks, unchanged file mode, and no type changes.", "emptyPatch", "=", "pathPatch", "[", "0", "]", ".", "size", "(", ")", "===", "0", "&&", "pathPatch", "[", "0", "]", ".", "oldFile", "(", ")", ".", "mode", "(", ")", "===", "pathPatch", "[", "0", "]", ".", "newFile", "(", ")", ".", "mode", "(", ")", "&&", "!", "pathPatch", "[", "0", "]", ".", "isTypeChange", "(", ")", ";", "}", "if", "(", "emptyPatch", ")", "{", "return", "index", ".", "addByPath", "(", "filePath", ")", ".", "then", "(", "function", "(", ")", "{", "return", "index", ".", "write", "(", ")", ";", "}", ")", ";", "}", "return", "result", ";", "}", ")", ";", "}" ]
The following chain checks if there is a patch with no hunks left for the file, and no filemode changes were done on the file. It is then safe to stage the entire file so the file doesn't show as having unstaged changes in `git status`. Also, check if there are no type changes.
[ "The", "following", "chain", "checks", "if", "there", "is", "a", "patch", "with", "no", "hunks", "left", "for", "the", "file", "and", "no", "filemode", "changes", "were", "done", "on", "the", "file", ".", "It", "is", "then", "safe", "to", "stage", "the", "entire", "file", "so", "the", "file", "doesn", "t", "show", "as", "having", "unstaged", "changes", "in", "git", "status", ".", "Also", "check", "if", "there", "are", "no", "type", "changes", "." ]
764146ca8054cd2839685c423bc2e5ba727165e9
https://github.com/nodegit/nodegit/blob/764146ca8054cd2839685c423bc2e5ba727165e9/lib/repository.js#L1995-L2025
10,354
nodegit/nodegit
lib/utils/lookup_wrapper.js
lookupWrapper
function lookupWrapper(objectType, lookupFunction) { lookupFunction = lookupFunction || objectType.lookup; return function(repo, id, callback) { if (id instanceof objectType) { return Promise.resolve(id).then(function(obj) { obj.repo = repo; if (typeof callback === "function") { callback(null, obj); } return obj; }, callback); } return lookupFunction(repo, id).then(function(obj) { obj.repo = repo; if (typeof callback === "function") { callback(null, obj); } return obj; }, callback); }; }
javascript
function lookupWrapper(objectType, lookupFunction) { lookupFunction = lookupFunction || objectType.lookup; return function(repo, id, callback) { if (id instanceof objectType) { return Promise.resolve(id).then(function(obj) { obj.repo = repo; if (typeof callback === "function") { callback(null, obj); } return obj; }, callback); } return lookupFunction(repo, id).then(function(obj) { obj.repo = repo; if (typeof callback === "function") { callback(null, obj); } return obj; }, callback); }; }
[ "function", "lookupWrapper", "(", "objectType", ",", "lookupFunction", ")", "{", "lookupFunction", "=", "lookupFunction", "||", "objectType", ".", "lookup", ";", "return", "function", "(", "repo", ",", "id", ",", "callback", ")", "{", "if", "(", "id", "instanceof", "objectType", ")", "{", "return", "Promise", ".", "resolve", "(", "id", ")", ".", "then", "(", "function", "(", "obj", ")", "{", "obj", ".", "repo", "=", "repo", ";", "if", "(", "typeof", "callback", "===", "\"function\"", ")", "{", "callback", "(", "null", ",", "obj", ")", ";", "}", "return", "obj", ";", "}", ",", "callback", ")", ";", "}", "return", "lookupFunction", "(", "repo", ",", "id", ")", ".", "then", "(", "function", "(", "obj", ")", "{", "obj", ".", "repo", "=", "repo", ";", "if", "(", "typeof", "callback", "===", "\"function\"", ")", "{", "callback", "(", "null", ",", "obj", ")", ";", "}", "return", "obj", ";", "}", ",", "callback", ")", ";", "}", ";", "}" ]
Wraps a method so that you can pass in either a string, OID or the object itself and you will always get back a promise that resolves to the object. @param {Object} objectType The object type that you're expecting to receive. @param {Function} lookupFunction The function to do the lookup for the object. Defaults to `objectType.lookup`. @return {Function}
[ "Wraps", "a", "method", "so", "that", "you", "can", "pass", "in", "either", "a", "string", "OID", "or", "the", "object", "itself", "and", "you", "will", "always", "get", "back", "a", "promise", "that", "resolves", "to", "the", "object", "." ]
764146ca8054cd2839685c423bc2e5ba727165e9
https://github.com/nodegit/nodegit/blob/764146ca8054cd2839685c423bc2e5ba727165e9/lib/utils/lookup_wrapper.js#L11-L37
10,355
Leaflet/Leaflet.draw
docs/examples/libs/leaflet.snap.js
computeBuffer
function computeBuffer() { this._buffer = map.layerPointToLatLng(new L.Point(0,0)).lat - map.layerPointToLatLng(new L.Point(this.options.snapDistance, 0)).lat; }
javascript
function computeBuffer() { this._buffer = map.layerPointToLatLng(new L.Point(0,0)).lat - map.layerPointToLatLng(new L.Point(this.options.snapDistance, 0)).lat; }
[ "function", "computeBuffer", "(", ")", "{", "this", ".", "_buffer", "=", "map", ".", "layerPointToLatLng", "(", "new", "L", ".", "Point", "(", "0", ",", "0", ")", ")", ".", "lat", "-", "map", ".", "layerPointToLatLng", "(", "new", "L", ".", "Point", "(", "this", ".", "options", ".", "snapDistance", ",", "0", ")", ")", ".", "lat", ";", "}" ]
Convert snap distance in pixels into buffer in degres, for searching around mouse It changes at each zoom change.
[ "Convert", "snap", "distance", "in", "pixels", "into", "buffer", "in", "degres", "for", "searching", "around", "mouse", "It", "changes", "at", "each", "zoom", "change", "." ]
d5dd11781c2e07f9e719308e504fe579000edf54
https://github.com/Leaflet/Leaflet.draw/blob/d5dd11781c2e07f9e719308e504fe579000edf54/docs/examples/libs/leaflet.snap.js#L32-L35
10,356
Leaflet/Leaflet.draw
docs/examples/libs/Leaflet.draw.drag-src.js
function(matrix) { var skew = this._skew; if (!skew) { skew = this._createElement('skew'); this._container.appendChild(skew); skew.style.behavior = 'url(#default#VML)'; this._skew = skew; } // handle skew/translate separately, cause it's broken var mt = matrix[0].toFixed(8) + " " + matrix[1].toFixed(8) + " " + matrix[2].toFixed(8) + " " + matrix[3].toFixed(8) + " 0 0"; var offset = Math.floor(matrix[4]).toFixed() + ", " + Math.floor(matrix[5]).toFixed() + ""; var s = this._container.style; var l = parseFloat(s.left); var t = parseFloat(s.top); var w = parseFloat(s.width); var h = parseFloat(s.height); if (isNaN(l)) l = 0; if (isNaN(t)) t = 0; if (isNaN(w) || !w) w = 1; if (isNaN(h) || !h) h = 1; var origin = (-l / w - 0.5).toFixed(8) + " " + (-t / h - 0.5).toFixed(8); skew.on = "f"; skew.matrix = mt; skew.origin = origin; skew.offset = offset; skew.on = true; }
javascript
function(matrix) { var skew = this._skew; if (!skew) { skew = this._createElement('skew'); this._container.appendChild(skew); skew.style.behavior = 'url(#default#VML)'; this._skew = skew; } // handle skew/translate separately, cause it's broken var mt = matrix[0].toFixed(8) + " " + matrix[1].toFixed(8) + " " + matrix[2].toFixed(8) + " " + matrix[3].toFixed(8) + " 0 0"; var offset = Math.floor(matrix[4]).toFixed() + ", " + Math.floor(matrix[5]).toFixed() + ""; var s = this._container.style; var l = parseFloat(s.left); var t = parseFloat(s.top); var w = parseFloat(s.width); var h = parseFloat(s.height); if (isNaN(l)) l = 0; if (isNaN(t)) t = 0; if (isNaN(w) || !w) w = 1; if (isNaN(h) || !h) h = 1; var origin = (-l / w - 0.5).toFixed(8) + " " + (-t / h - 0.5).toFixed(8); skew.on = "f"; skew.matrix = mt; skew.origin = origin; skew.offset = offset; skew.on = true; }
[ "function", "(", "matrix", ")", "{", "var", "skew", "=", "this", ".", "_skew", ";", "if", "(", "!", "skew", ")", "{", "skew", "=", "this", ".", "_createElement", "(", "'skew'", ")", ";", "this", ".", "_container", ".", "appendChild", "(", "skew", ")", ";", "skew", ".", "style", ".", "behavior", "=", "'url(#default#VML)'", ";", "this", ".", "_skew", "=", "skew", ";", "}", "// handle skew/translate separately, cause it's broken", "var", "mt", "=", "matrix", "[", "0", "]", ".", "toFixed", "(", "8", ")", "+", "\" \"", "+", "matrix", "[", "1", "]", ".", "toFixed", "(", "8", ")", "+", "\" \"", "+", "matrix", "[", "2", "]", ".", "toFixed", "(", "8", ")", "+", "\" \"", "+", "matrix", "[", "3", "]", ".", "toFixed", "(", "8", ")", "+", "\" 0 0\"", ";", "var", "offset", "=", "Math", ".", "floor", "(", "matrix", "[", "4", "]", ")", ".", "toFixed", "(", ")", "+", "\", \"", "+", "Math", ".", "floor", "(", "matrix", "[", "5", "]", ")", ".", "toFixed", "(", ")", "+", "\"\"", ";", "var", "s", "=", "this", ".", "_container", ".", "style", ";", "var", "l", "=", "parseFloat", "(", "s", ".", "left", ")", ";", "var", "t", "=", "parseFloat", "(", "s", ".", "top", ")", ";", "var", "w", "=", "parseFloat", "(", "s", ".", "width", ")", ";", "var", "h", "=", "parseFloat", "(", "s", ".", "height", ")", ";", "if", "(", "isNaN", "(", "l", ")", ")", "l", "=", "0", ";", "if", "(", "isNaN", "(", "t", ")", ")", "t", "=", "0", ";", "if", "(", "isNaN", "(", "w", ")", "||", "!", "w", ")", "w", "=", "1", ";", "if", "(", "isNaN", "(", "h", ")", "||", "!", "h", ")", "h", "=", "1", ";", "var", "origin", "=", "(", "-", "l", "/", "w", "-", "0.5", ")", ".", "toFixed", "(", "8", ")", "+", "\" \"", "+", "(", "-", "t", "/", "h", "-", "0.5", ")", ".", "toFixed", "(", "8", ")", ";", "skew", ".", "on", "=", "\"f\"", ";", "skew", ".", "matrix", "=", "mt", ";", "skew", ".", "origin", "=", "origin", ";", "skew", ".", "offset", "=", "offset", ";", "skew", ".", "on", "=", "true", ";", "}" ]
Applies matrix transformation to VML @param {Array.<Number>} matrix
[ "Applies", "matrix", "transformation", "to", "VML" ]
d5dd11781c2e07f9e719308e504fe579000edf54
https://github.com/Leaflet/Leaflet.draw/blob/d5dd11781c2e07f9e719308e504fe579000edf54/docs/examples/libs/Leaflet.draw.drag-src.js#L51-L85
10,357
Leaflet/Leaflet.draw
docs/examples/libs/Leaflet.draw.drag-src.js
function(e) { if ((this.dragging && this.dragging.moved()) || (this._map.dragging && this._map.dragging.moved())) { return; } this._fireMouseEvent(e); }
javascript
function(e) { if ((this.dragging && this.dragging.moved()) || (this._map.dragging && this._map.dragging.moved())) { return; } this._fireMouseEvent(e); }
[ "function", "(", "e", ")", "{", "if", "(", "(", "this", ".", "dragging", "&&", "this", ".", "dragging", ".", "moved", "(", ")", ")", "||", "(", "this", ".", "_map", ".", "dragging", "&&", "this", ".", "_map", ".", "dragging", ".", "moved", "(", ")", ")", ")", "{", "return", ";", "}", "this", ".", "_fireMouseEvent", "(", "e", ")", ";", "}" ]
Check if the feature was dragged, that'll supress the click event on mouseup. That fixes popups for example @param {MouseEvent} e
[ "Check", "if", "the", "feature", "was", "dragged", "that", "ll", "supress", "the", "click", "event", "on", "mouseup", ".", "That", "fixes", "popups", "for", "example" ]
d5dd11781c2e07f9e719308e504fe579000edf54
https://github.com/Leaflet/Leaflet.draw/blob/d5dd11781c2e07f9e719308e504fe579000edf54/docs/examples/libs/Leaflet.draw.drag-src.js#L99-L106
10,358
Leaflet/Leaflet.draw
docs/examples/libs/Leaflet.draw.drag-src.js
function(matrix) { var path = this._path; var i, len, latlng; var px = L.point(matrix[4], matrix[5]); var crs = path._map.options.crs; var transformation = crs.transformation; var scale = crs.scale(path._map.getZoom()); var projection = crs.projection; var diff = transformation.untransform(px, scale) .subtract(transformation.untransform(L.point(0, 0), scale)); // console.time('transform'); // all shifts are in-place if (path._point) { // L.Circle path._latlng = projection.unproject( projection.project(path._latlng)._add(diff)); path._point._add(px); } else if (path._originalPoints) { // everything else for (i = 0, len = path._originalPoints.length; i < len; i++) { latlng = path._latlngs[i]; path._latlngs[i] = projection .unproject(projection.project(latlng)._add(diff)); path._originalPoints[i]._add(px); } } // holes operations if (path._holes) { for (i = 0, len = path._holes.length; i < len; i++) { for (var j = 0, len2 = path._holes[i].length; j < len2; j++) { latlng = path._holes[i][j]; path._holes[i][j] = projection .unproject(projection.project(latlng)._add(diff)); path._holePoints[i][j]._add(px); } } } // console.timeEnd('transform'); path._updatePath(); }
javascript
function(matrix) { var path = this._path; var i, len, latlng; var px = L.point(matrix[4], matrix[5]); var crs = path._map.options.crs; var transformation = crs.transformation; var scale = crs.scale(path._map.getZoom()); var projection = crs.projection; var diff = transformation.untransform(px, scale) .subtract(transformation.untransform(L.point(0, 0), scale)); // console.time('transform'); // all shifts are in-place if (path._point) { // L.Circle path._latlng = projection.unproject( projection.project(path._latlng)._add(diff)); path._point._add(px); } else if (path._originalPoints) { // everything else for (i = 0, len = path._originalPoints.length; i < len; i++) { latlng = path._latlngs[i]; path._latlngs[i] = projection .unproject(projection.project(latlng)._add(diff)); path._originalPoints[i]._add(px); } } // holes operations if (path._holes) { for (i = 0, len = path._holes.length; i < len; i++) { for (var j = 0, len2 = path._holes[i].length; j < len2; j++) { latlng = path._holes[i][j]; path._holes[i][j] = projection .unproject(projection.project(latlng)._add(diff)); path._holePoints[i][j]._add(px); } } } // console.timeEnd('transform'); path._updatePath(); }
[ "function", "(", "matrix", ")", "{", "var", "path", "=", "this", ".", "_path", ";", "var", "i", ",", "len", ",", "latlng", ";", "var", "px", "=", "L", ".", "point", "(", "matrix", "[", "4", "]", ",", "matrix", "[", "5", "]", ")", ";", "var", "crs", "=", "path", ".", "_map", ".", "options", ".", "crs", ";", "var", "transformation", "=", "crs", ".", "transformation", ";", "var", "scale", "=", "crs", ".", "scale", "(", "path", ".", "_map", ".", "getZoom", "(", ")", ")", ";", "var", "projection", "=", "crs", ".", "projection", ";", "var", "diff", "=", "transformation", ".", "untransform", "(", "px", ",", "scale", ")", ".", "subtract", "(", "transformation", ".", "untransform", "(", "L", ".", "point", "(", "0", ",", "0", ")", ",", "scale", ")", ")", ";", "// console.time('transform');", "// all shifts are in-place", "if", "(", "path", ".", "_point", ")", "{", "// L.Circle", "path", ".", "_latlng", "=", "projection", ".", "unproject", "(", "projection", ".", "project", "(", "path", ".", "_latlng", ")", ".", "_add", "(", "diff", ")", ")", ";", "path", ".", "_point", ".", "_add", "(", "px", ")", ";", "}", "else", "if", "(", "path", ".", "_originalPoints", ")", "{", "// everything else", "for", "(", "i", "=", "0", ",", "len", "=", "path", ".", "_originalPoints", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "latlng", "=", "path", ".", "_latlngs", "[", "i", "]", ";", "path", ".", "_latlngs", "[", "i", "]", "=", "projection", ".", "unproject", "(", "projection", ".", "project", "(", "latlng", ")", ".", "_add", "(", "diff", ")", ")", ";", "path", ".", "_originalPoints", "[", "i", "]", ".", "_add", "(", "px", ")", ";", "}", "}", "// holes operations", "if", "(", "path", ".", "_holes", ")", "{", "for", "(", "i", "=", "0", ",", "len", "=", "path", ".", "_holes", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "0", ",", "len2", "=", "path", ".", "_holes", "[", "i", "]", ".", "length", ";", "j", "<", "len2", ";", "j", "++", ")", "{", "latlng", "=", "path", ".", "_holes", "[", "i", "]", "[", "j", "]", ";", "path", ".", "_holes", "[", "i", "]", "[", "j", "]", "=", "projection", ".", "unproject", "(", "projection", ".", "project", "(", "latlng", ")", ".", "_add", "(", "diff", ")", ")", ";", "path", ".", "_holePoints", "[", "i", "]", "[", "j", "]", ".", "_add", "(", "px", ")", ";", "}", "}", "}", "// console.timeEnd('transform');", "path", ".", "_updatePath", "(", ")", ";", "}" ]
Applies transformation, does it in one sweep for performance, so don't be surprised about the code repetition. [ x ] [ a b tx ] [ x ] [ a * x + b * y + tx ] [ y ] = [ c d ty ] [ y ] = [ c * x + d * y + ty ] @param {Array.<Number>} matrix
[ "Applies", "transformation", "does", "it", "in", "one", "sweep", "for", "performance", "so", "don", "t", "be", "surprised", "about", "the", "code", "repetition", "." ]
d5dd11781c2e07f9e719308e504fe579000edf54
https://github.com/Leaflet/Leaflet.draw/blob/d5dd11781c2e07f9e719308e504fe579000edf54/docs/examples/libs/Leaflet.draw.drag-src.js#L251-L296
10,359
Leaflet/Leaflet.draw
docs/examples/libs/Leaflet.draw.drag-src.js
function(evt) { var poly = this._shape || this._poly; var marker = evt.target; poly.fire('mousedown', L.Util.extend(evt, { containerPoint: L.DomUtil.getPosition(marker._icon) .add(poly._map._getMapPanePos()) })); }
javascript
function(evt) { var poly = this._shape || this._poly; var marker = evt.target; poly.fire('mousedown', L.Util.extend(evt, { containerPoint: L.DomUtil.getPosition(marker._icon) .add(poly._map._getMapPanePos()) })); }
[ "function", "(", "evt", ")", "{", "var", "poly", "=", "this", ".", "_shape", "||", "this", ".", "_poly", ";", "var", "marker", "=", "evt", ".", "target", ";", "poly", ".", "fire", "(", "'mousedown'", ",", "L", ".", "Util", ".", "extend", "(", "evt", ",", "{", "containerPoint", ":", "L", ".", "DomUtil", ".", "getPosition", "(", "marker", ".", "_icon", ")", ".", "add", "(", "poly", ".", "_map", ".", "_getMapPanePos", "(", ")", ")", "}", ")", ")", ";", "}" ]
Start dragging through the marker @param {L.MouseEvent} evt
[ "Start", "dragging", "through", "the", "marker" ]
d5dd11781c2e07f9e719308e504fe579000edf54
https://github.com/Leaflet/Leaflet.draw/blob/d5dd11781c2e07f9e719308e504fe579000edf54/docs/examples/libs/Leaflet.draw.drag-src.js#L745-L752
10,360
Leaflet/Leaflet.draw
docs/examples-0.7.x/libs/leaflet-src.js
function (obj) { // (LatLng) or (LatLngBounds) if (!obj) { return this; } var latLng = L.latLng(obj); if (latLng !== null) { obj = latLng; } else { obj = L.latLngBounds(obj); } if (obj instanceof L.LatLng) { if (!this._southWest && !this._northEast) { this._southWest = new L.LatLng(obj.lat, obj.lng); this._northEast = new L.LatLng(obj.lat, obj.lng); } else { this._southWest.lat = Math.min(obj.lat, this._southWest.lat); this._southWest.lng = Math.min(obj.lng, this._southWest.lng); this._northEast.lat = Math.max(obj.lat, this._northEast.lat); this._northEast.lng = Math.max(obj.lng, this._northEast.lng); } } else if (obj instanceof L.LatLngBounds) { this.extend(obj._southWest); this.extend(obj._northEast); } return this; }
javascript
function (obj) { // (LatLng) or (LatLngBounds) if (!obj) { return this; } var latLng = L.latLng(obj); if (latLng !== null) { obj = latLng; } else { obj = L.latLngBounds(obj); } if (obj instanceof L.LatLng) { if (!this._southWest && !this._northEast) { this._southWest = new L.LatLng(obj.lat, obj.lng); this._northEast = new L.LatLng(obj.lat, obj.lng); } else { this._southWest.lat = Math.min(obj.lat, this._southWest.lat); this._southWest.lng = Math.min(obj.lng, this._southWest.lng); this._northEast.lat = Math.max(obj.lat, this._northEast.lat); this._northEast.lng = Math.max(obj.lng, this._northEast.lng); } } else if (obj instanceof L.LatLngBounds) { this.extend(obj._southWest); this.extend(obj._northEast); } return this; }
[ "function", "(", "obj", ")", "{", "// (LatLng) or (LatLngBounds)", "if", "(", "!", "obj", ")", "{", "return", "this", ";", "}", "var", "latLng", "=", "L", ".", "latLng", "(", "obj", ")", ";", "if", "(", "latLng", "!==", "null", ")", "{", "obj", "=", "latLng", ";", "}", "else", "{", "obj", "=", "L", ".", "latLngBounds", "(", "obj", ")", ";", "}", "if", "(", "obj", "instanceof", "L", ".", "LatLng", ")", "{", "if", "(", "!", "this", ".", "_southWest", "&&", "!", "this", ".", "_northEast", ")", "{", "this", ".", "_southWest", "=", "new", "L", ".", "LatLng", "(", "obj", ".", "lat", ",", "obj", ".", "lng", ")", ";", "this", ".", "_northEast", "=", "new", "L", ".", "LatLng", "(", "obj", ".", "lat", ",", "obj", ".", "lng", ")", ";", "}", "else", "{", "this", ".", "_southWest", ".", "lat", "=", "Math", ".", "min", "(", "obj", ".", "lat", ",", "this", ".", "_southWest", ".", "lat", ")", ";", "this", ".", "_southWest", ".", "lng", "=", "Math", ".", "min", "(", "obj", ".", "lng", ",", "this", ".", "_southWest", ".", "lng", ")", ";", "this", ".", "_northEast", ".", "lat", "=", "Math", ".", "max", "(", "obj", ".", "lat", ",", "this", ".", "_northEast", ".", "lat", ")", ";", "this", ".", "_northEast", ".", "lng", "=", "Math", ".", "max", "(", "obj", ".", "lng", ",", "this", ".", "_northEast", ".", "lng", ")", ";", "}", "}", "else", "if", "(", "obj", "instanceof", "L", ".", "LatLngBounds", ")", "{", "this", ".", "extend", "(", "obj", ".", "_southWest", ")", ";", "this", ".", "extend", "(", "obj", ".", "_northEast", ")", ";", "}", "return", "this", ";", "}" ]
extend the bounds to contain the given point or bounds
[ "extend", "the", "bounds", "to", "contain", "the", "given", "point", "or", "bounds" ]
d5dd11781c2e07f9e719308e504fe579000edf54
https://github.com/Leaflet/Leaflet.draw/blob/d5dd11781c2e07f9e719308e504fe579000edf54/docs/examples-0.7.x/libs/leaflet-src.js#L1261-L1287
10,361
Leaflet/Leaflet.draw
docs/examples-0.7.x/libs/leaflet-src.js
function (center, zoom) { zoom = zoom === undefined ? this.getZoom() : zoom; this._resetView(L.latLng(center), this._limitZoom(zoom)); return this; }
javascript
function (center, zoom) { zoom = zoom === undefined ? this.getZoom() : zoom; this._resetView(L.latLng(center), this._limitZoom(zoom)); return this; }
[ "function", "(", "center", ",", "zoom", ")", "{", "zoom", "=", "zoom", "===", "undefined", "?", "this", ".", "getZoom", "(", ")", ":", "zoom", ";", "this", ".", "_resetView", "(", "L", ".", "latLng", "(", "center", ")", ",", "this", ".", "_limitZoom", "(", "zoom", ")", ")", ";", "return", "this", ";", "}" ]
public methods that modify map state replaced by animation-powered implementation in Map.PanAnimation.js
[ "public", "methods", "that", "modify", "map", "state", "replaced", "by", "animation", "-", "powered", "implementation", "in", "Map", ".", "PanAnimation", ".", "js" ]
d5dd11781c2e07f9e719308e504fe579000edf54
https://github.com/Leaflet/Leaflet.draw/blob/d5dd11781c2e07f9e719308e504fe579000edf54/docs/examples-0.7.x/libs/leaflet-src.js#L1594-L1598
10,362
Leaflet/Leaflet.draw
docs/examples-0.7.x/libs/leaflet-src.js
function (offset, bounds) { if (!bounds) { return offset; } var viewBounds = this.getPixelBounds(), newBounds = new L.Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset)); return offset.add(this._getBoundsOffset(newBounds, bounds)); }
javascript
function (offset, bounds) { if (!bounds) { return offset; } var viewBounds = this.getPixelBounds(), newBounds = new L.Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset)); return offset.add(this._getBoundsOffset(newBounds, bounds)); }
[ "function", "(", "offset", ",", "bounds", ")", "{", "if", "(", "!", "bounds", ")", "{", "return", "offset", ";", "}", "var", "viewBounds", "=", "this", ".", "getPixelBounds", "(", ")", ",", "newBounds", "=", "new", "L", ".", "Bounds", "(", "viewBounds", ".", "min", ".", "add", "(", "offset", ")", ",", "viewBounds", ".", "max", ".", "add", "(", "offset", ")", ")", ";", "return", "offset", ".", "add", "(", "this", ".", "_getBoundsOffset", "(", "newBounds", ",", "bounds", ")", ")", ";", "}" ]
adjust offset for view to get inside bounds
[ "adjust", "offset", "for", "view", "to", "get", "inside", "bounds" ]
d5dd11781c2e07f9e719308e504fe579000edf54
https://github.com/Leaflet/Leaflet.draw/blob/d5dd11781c2e07f9e719308e504fe579000edf54/docs/examples-0.7.x/libs/leaflet-src.js#L2310-L2317
10,363
Leaflet/Leaflet.draw
docs/examples-0.7.x/libs/leaflet-src.js
function (points, sqTolerance) { var reducedPoints = [points[0]]; for (var i = 1, prev = 0, len = points.length; i < len; i++) { if (this._sqDist(points[i], points[prev]) > sqTolerance) { reducedPoints.push(points[i]); prev = i; } } if (prev < len - 1) { reducedPoints.push(points[len - 1]); } return reducedPoints; }
javascript
function (points, sqTolerance) { var reducedPoints = [points[0]]; for (var i = 1, prev = 0, len = points.length; i < len; i++) { if (this._sqDist(points[i], points[prev]) > sqTolerance) { reducedPoints.push(points[i]); prev = i; } } if (prev < len - 1) { reducedPoints.push(points[len - 1]); } return reducedPoints; }
[ "function", "(", "points", ",", "sqTolerance", ")", "{", "var", "reducedPoints", "=", "[", "points", "[", "0", "]", "]", ";", "for", "(", "var", "i", "=", "1", ",", "prev", "=", "0", ",", "len", "=", "points", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "this", ".", "_sqDist", "(", "points", "[", "i", "]", ",", "points", "[", "prev", "]", ")", ">", "sqTolerance", ")", "{", "reducedPoints", ".", "push", "(", "points", "[", "i", "]", ")", ";", "prev", "=", "i", ";", "}", "}", "if", "(", "prev", "<", "len", "-", "1", ")", "{", "reducedPoints", ".", "push", "(", "points", "[", "len", "-", "1", "]", ")", ";", "}", "return", "reducedPoints", ";", "}" ]
reduce points that are too close to each other to a single point
[ "reduce", "points", "that", "are", "too", "close", "to", "each", "other", "to", "a", "single", "point" ]
d5dd11781c2e07f9e719308e504fe579000edf54
https://github.com/Leaflet/Leaflet.draw/blob/d5dd11781c2e07f9e719308e504fe579000edf54/docs/examples-0.7.x/libs/leaflet-src.js#L5324-L5337
10,364
Leaflet/Leaflet.draw
docs/examples-0.7.x/libs/leaflet-src.js
function (a, b, bounds, useLastCode) { var codeA = useLastCode ? this._lastCode : this._getBitCode(a, bounds), codeB = this._getBitCode(b, bounds), codeOut, p, newCode; // save 2nd code to avoid calculating it on the next segment this._lastCode = codeB; while (true) { // if a,b is inside the clip window (trivial accept) if (!(codeA | codeB)) { return [a, b]; // if a,b is outside the clip window (trivial reject) } else if (codeA & codeB) { return false; // other cases } else { codeOut = codeA || codeB; p = this._getEdgeIntersection(a, b, codeOut, bounds); newCode = this._getBitCode(p, bounds); if (codeOut === codeA) { a = p; codeA = newCode; } else { b = p; codeB = newCode; } } } }
javascript
function (a, b, bounds, useLastCode) { var codeA = useLastCode ? this._lastCode : this._getBitCode(a, bounds), codeB = this._getBitCode(b, bounds), codeOut, p, newCode; // save 2nd code to avoid calculating it on the next segment this._lastCode = codeB; while (true) { // if a,b is inside the clip window (trivial accept) if (!(codeA | codeB)) { return [a, b]; // if a,b is outside the clip window (trivial reject) } else if (codeA & codeB) { return false; // other cases } else { codeOut = codeA || codeB; p = this._getEdgeIntersection(a, b, codeOut, bounds); newCode = this._getBitCode(p, bounds); if (codeOut === codeA) { a = p; codeA = newCode; } else { b = p; codeB = newCode; } } } }
[ "function", "(", "a", ",", "b", ",", "bounds", ",", "useLastCode", ")", "{", "var", "codeA", "=", "useLastCode", "?", "this", ".", "_lastCode", ":", "this", ".", "_getBitCode", "(", "a", ",", "bounds", ")", ",", "codeB", "=", "this", ".", "_getBitCode", "(", "b", ",", "bounds", ")", ",", "codeOut", ",", "p", ",", "newCode", ";", "// save 2nd code to avoid calculating it on the next segment", "this", ".", "_lastCode", "=", "codeB", ";", "while", "(", "true", ")", "{", "// if a,b is inside the clip window (trivial accept)", "if", "(", "!", "(", "codeA", "|", "codeB", ")", ")", "{", "return", "[", "a", ",", "b", "]", ";", "// if a,b is outside the clip window (trivial reject)", "}", "else", "if", "(", "codeA", "&", "codeB", ")", "{", "return", "false", ";", "// other cases", "}", "else", "{", "codeOut", "=", "codeA", "||", "codeB", ";", "p", "=", "this", ".", "_getEdgeIntersection", "(", "a", ",", "b", ",", "codeOut", ",", "bounds", ")", ";", "newCode", "=", "this", ".", "_getBitCode", "(", "p", ",", "bounds", ")", ";", "if", "(", "codeOut", "===", "codeA", ")", "{", "a", "=", "p", ";", "codeA", "=", "newCode", ";", "}", "else", "{", "b", "=", "p", ";", "codeB", "=", "newCode", ";", "}", "}", "}", "}" ]
Cohen-Sutherland line clipping algorithm. Used to avoid rendering parts of a polyline that are not currently visible.
[ "Cohen", "-", "Sutherland", "line", "clipping", "algorithm", ".", "Used", "to", "avoid", "rendering", "parts", "of", "a", "polyline", "that", "are", "not", "currently", "visible", "." ]
d5dd11781c2e07f9e719308e504fe579000edf54
https://github.com/Leaflet/Leaflet.draw/blob/d5dd11781c2e07f9e719308e504fe579000edf54/docs/examples-0.7.x/libs/leaflet-src.js#L5342-L5373
10,365
Leaflet/Leaflet.draw
docs/examples-0.7.x/libs/leaflet-src.js
function (p, p1, p2, sqDist) { var x = p1.x, y = p1.y, dx = p2.x - x, dy = p2.y - y, dot = dx * dx + dy * dy, t; if (dot > 0) { t = ((p.x - x) * dx + (p.y - y) * dy) / dot; if (t > 1) { x = p2.x; y = p2.y; } else if (t > 0) { x += dx * t; y += dy * t; } } dx = p.x - x; dy = p.y - y; return sqDist ? dx * dx + dy * dy : new L.Point(x, y); }
javascript
function (p, p1, p2, sqDist) { var x = p1.x, y = p1.y, dx = p2.x - x, dy = p2.y - y, dot = dx * dx + dy * dy, t; if (dot > 0) { t = ((p.x - x) * dx + (p.y - y) * dy) / dot; if (t > 1) { x = p2.x; y = p2.y; } else if (t > 0) { x += dx * t; y += dy * t; } } dx = p.x - x; dy = p.y - y; return sqDist ? dx * dx + dy * dy : new L.Point(x, y); }
[ "function", "(", "p", ",", "p1", ",", "p2", ",", "sqDist", ")", "{", "var", "x", "=", "p1", ".", "x", ",", "y", "=", "p1", ".", "y", ",", "dx", "=", "p2", ".", "x", "-", "x", ",", "dy", "=", "p2", ".", "y", "-", "y", ",", "dot", "=", "dx", "*", "dx", "+", "dy", "*", "dy", ",", "t", ";", "if", "(", "dot", ">", "0", ")", "{", "t", "=", "(", "(", "p", ".", "x", "-", "x", ")", "*", "dx", "+", "(", "p", ".", "y", "-", "y", ")", "*", "dy", ")", "/", "dot", ";", "if", "(", "t", ">", "1", ")", "{", "x", "=", "p2", ".", "x", ";", "y", "=", "p2", ".", "y", ";", "}", "else", "if", "(", "t", ">", "0", ")", "{", "x", "+=", "dx", "*", "t", ";", "y", "+=", "dy", "*", "t", ";", "}", "}", "dx", "=", "p", ".", "x", "-", "x", ";", "dy", "=", "p", ".", "y", "-", "y", ";", "return", "sqDist", "?", "dx", "*", "dx", "+", "dy", "*", "dy", ":", "new", "L", ".", "Point", "(", "x", ",", "y", ")", ";", "}" ]
return closest point on segment or distance to that point
[ "return", "closest", "point", "on", "segment", "or", "distance", "to", "that", "point" ]
d5dd11781c2e07f9e719308e504fe579000edf54
https://github.com/Leaflet/Leaflet.draw/blob/d5dd11781c2e07f9e719308e504fe579000edf54/docs/examples-0.7.x/libs/leaflet-src.js#L5417-L5441
10,366
Leaflet/Leaflet.draw
build/build.js
bundleFiles
function bundleFiles(files, copy, version) { var node = new SourceNode(null, null, null, ''); node.add(new SourceNode(null, null, null, copy + '(function (window, document, undefined) {')); for (var i = 0, len = files.length; i < len; i++) { var contents = fs.readFileSync(files[i], 'utf8'); if (files[i] === 'src/Leaflet.draw.js') { contents = contents.replace( new RegExp('drawVersion = \'.*\''), 'drawVersion = ' + JSON.stringify(version) ); } var lines = contents.split('\n'); var lineCount = lines.length; var fileNode = new SourceNode(null, null, null, ''); fileNode.setSourceContent(files[i], contents); for (var j = 0; j < lineCount; j++) { fileNode.add(new SourceNode(j + 1, 0, files[i], lines[j] + '\n')); } node.add(fileNode); node.add(new SourceNode(null, null, null, '\n\n')); } node.add(new SourceNode(null, null, null, '}(window, document));')); var bundle = node.toStringWithSourceMap(); return { src: bundle.code, srcmap: bundle.map.toString() }; }
javascript
function bundleFiles(files, copy, version) { var node = new SourceNode(null, null, null, ''); node.add(new SourceNode(null, null, null, copy + '(function (window, document, undefined) {')); for (var i = 0, len = files.length; i < len; i++) { var contents = fs.readFileSync(files[i], 'utf8'); if (files[i] === 'src/Leaflet.draw.js') { contents = contents.replace( new RegExp('drawVersion = \'.*\''), 'drawVersion = ' + JSON.stringify(version) ); } var lines = contents.split('\n'); var lineCount = lines.length; var fileNode = new SourceNode(null, null, null, ''); fileNode.setSourceContent(files[i], contents); for (var j = 0; j < lineCount; j++) { fileNode.add(new SourceNode(j + 1, 0, files[i], lines[j] + '\n')); } node.add(fileNode); node.add(new SourceNode(null, null, null, '\n\n')); } node.add(new SourceNode(null, null, null, '}(window, document));')); var bundle = node.toStringWithSourceMap(); return { src: bundle.code, srcmap: bundle.map.toString() }; }
[ "function", "bundleFiles", "(", "files", ",", "copy", ",", "version", ")", "{", "var", "node", "=", "new", "SourceNode", "(", "null", ",", "null", ",", "null", ",", "''", ")", ";", "node", ".", "add", "(", "new", "SourceNode", "(", "null", ",", "null", ",", "null", ",", "copy", "+", "'(function (window, document, undefined) {'", ")", ")", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "files", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "contents", "=", "fs", ".", "readFileSync", "(", "files", "[", "i", "]", ",", "'utf8'", ")", ";", "if", "(", "files", "[", "i", "]", "===", "'src/Leaflet.draw.js'", ")", "{", "contents", "=", "contents", ".", "replace", "(", "new", "RegExp", "(", "'drawVersion = \\'.*\\''", ")", ",", "'drawVersion = '", "+", "JSON", ".", "stringify", "(", "version", ")", ")", ";", "}", "var", "lines", "=", "contents", ".", "split", "(", "'\\n'", ")", ";", "var", "lineCount", "=", "lines", ".", "length", ";", "var", "fileNode", "=", "new", "SourceNode", "(", "null", ",", "null", ",", "null", ",", "''", ")", ";", "fileNode", ".", "setSourceContent", "(", "files", "[", "i", "]", ",", "contents", ")", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "lineCount", ";", "j", "++", ")", "{", "fileNode", ".", "add", "(", "new", "SourceNode", "(", "j", "+", "1", ",", "0", ",", "files", "[", "i", "]", ",", "lines", "[", "j", "]", "+", "'\\n'", ")", ")", ";", "}", "node", ".", "add", "(", "fileNode", ")", ";", "node", ".", "add", "(", "new", "SourceNode", "(", "null", ",", "null", ",", "null", ",", "'\\n\\n'", ")", ")", ";", "}", "node", ".", "add", "(", "new", "SourceNode", "(", "null", ",", "null", ",", "null", ",", "'}(window, document));'", ")", ")", ";", "var", "bundle", "=", "node", ".", "toStringWithSourceMap", "(", ")", ";", "return", "{", "src", ":", "bundle", ".", "code", ",", "srcmap", ":", "bundle", ".", "map", ".", "toString", "(", ")", "}", ";", "}" ]
Concatenate the files while building up a sourcemap for the concatenation, and replace the line defining L.version with the string prepared in the jakefile
[ "Concatenate", "the", "files", "while", "building", "up", "a", "sourcemap", "for", "the", "concatenation", "and", "replace", "the", "line", "defining", "L", ".", "version", "with", "the", "string", "prepared", "in", "the", "jakefile" ]
d5dd11781c2e07f9e719308e504fe579000edf54
https://github.com/Leaflet/Leaflet.draw/blob/d5dd11781c2e07f9e719308e504fe579000edf54/build/build.js#L76-L112
10,367
Leaflet/Leaflet.draw
Jakefile.js
calculateVersion
function calculateVersion(officialRelease, callback) { var version = require('./package.json').version; if (officialRelease) { callback(version); } else { git.short(function (str) { callback(version + '+' + str); }); } }
javascript
function calculateVersion(officialRelease, callback) { var version = require('./package.json').version; if (officialRelease) { callback(version); } else { git.short(function (str) { callback(version + '+' + str); }); } }
[ "function", "calculateVersion", "(", "officialRelease", ",", "callback", ")", "{", "var", "version", "=", "require", "(", "'./package.json'", ")", ".", "version", ";", "if", "(", "officialRelease", ")", "{", "callback", "(", "version", ")", ";", "}", "else", "{", "git", ".", "short", "(", "function", "(", "str", ")", "{", "callback", "(", "version", "+", "'+'", "+", "str", ")", ";", "}", ")", ";", "}", "}" ]
Returns the version string in package.json, plus a semver build metadata if this is not an official release
[ "Returns", "the", "version", "string", "in", "package", ".", "json", "plus", "a", "semver", "build", "metadata", "if", "this", "is", "not", "an", "official", "release" ]
d5dd11781c2e07f9e719308e504fe579000edf54
https://github.com/Leaflet/Leaflet.draw/blob/d5dd11781c2e07f9e719308e504fe579000edf54/Jakefile.js#L32-L42
10,368
Leaflet/Leaflet.draw
docs/examples/libs/spectrum.js
bind
function bind(func, obj) { var slice = Array.prototype.slice; var args = slice.call(arguments, 2); return function () { return func.apply(obj, args.concat(slice.call(arguments))); }; }
javascript
function bind(func, obj) { var slice = Array.prototype.slice; var args = slice.call(arguments, 2); return function () { return func.apply(obj, args.concat(slice.call(arguments))); }; }
[ "function", "bind", "(", "func", ",", "obj", ")", "{", "var", "slice", "=", "Array", ".", "prototype", ".", "slice", ";", "var", "args", "=", "slice", ".", "call", "(", "arguments", ",", "2", ")", ";", "return", "function", "(", ")", "{", "return", "func", ".", "apply", "(", "obj", ",", "args", ".", "concat", "(", "slice", ".", "call", "(", "arguments", ")", ")", ")", ";", "}", ";", "}" ]
Create a function bound to a given object Thanks to underscore.js
[ "Create", "a", "function", "bound", "to", "a", "given", "object", "Thanks", "to", "underscore", ".", "js" ]
d5dd11781c2e07f9e719308e504fe579000edf54
https://github.com/Leaflet/Leaflet.draw/blob/d5dd11781c2e07f9e719308e504fe579000edf54/docs/examples/libs/spectrum.js#L941-L947
10,369
hyperledger/fabric-sdk-node
fabric-ca-client/lib/helper.js
parseURL
function parseURL(url) { const endpoint = {}; const purl = urlParser.parse(url, true); if (purl.protocol && purl.protocol.startsWith('http')) { endpoint.protocol = purl.protocol.slice(0, -1); if (purl.hostname) { endpoint.hostname = purl.hostname; if (purl.port) { endpoint.port = parseInt(purl.port); } } else { throw new Error('InvalidURL: missing hostname.'); } } else { throw new Error('InvalidURL: url must start with http or https.'); } return endpoint; }
javascript
function parseURL(url) { const endpoint = {}; const purl = urlParser.parse(url, true); if (purl.protocol && purl.protocol.startsWith('http')) { endpoint.protocol = purl.protocol.slice(0, -1); if (purl.hostname) { endpoint.hostname = purl.hostname; if (purl.port) { endpoint.port = parseInt(purl.port); } } else { throw new Error('InvalidURL: missing hostname.'); } } else { throw new Error('InvalidURL: url must start with http or https.'); } return endpoint; }
[ "function", "parseURL", "(", "url", ")", "{", "const", "endpoint", "=", "{", "}", ";", "const", "purl", "=", "urlParser", ".", "parse", "(", "url", ",", "true", ")", ";", "if", "(", "purl", ".", "protocol", "&&", "purl", ".", "protocol", ".", "startsWith", "(", "'http'", ")", ")", "{", "endpoint", ".", "protocol", "=", "purl", ".", "protocol", ".", "slice", "(", "0", ",", "-", "1", ")", ";", "if", "(", "purl", ".", "hostname", ")", "{", "endpoint", ".", "hostname", "=", "purl", ".", "hostname", ";", "if", "(", "purl", ".", "port", ")", "{", "endpoint", ".", "port", "=", "parseInt", "(", "purl", ".", "port", ")", ";", "}", "}", "else", "{", "throw", "new", "Error", "(", "'InvalidURL: missing hostname.'", ")", ";", "}", "}", "else", "{", "throw", "new", "Error", "(", "'InvalidURL: url must start with http or https.'", ")", ";", "}", "return", "endpoint", ";", "}" ]
Utility function which parses an HTTP URL into its component parts @param {string} url HTTP or HTTPS url including protocol, host and port @returns {HTTPEndpoint} @throws InvalidURL for malformed URLs @ignore
[ "Utility", "function", "which", "parses", "an", "HTTP", "URL", "into", "its", "component", "parts" ]
4f62e201624c1e9a14d548808d3524aa93573cd5
https://github.com/hyperledger/fabric-sdk-node/blob/4f62e201624c1e9a14d548808d3524aa93573cd5/fabric-ca-client/lib/helper.js#L56-L80
10,370
hyperledger/fabric-sdk-node
fabric-client/lib/impl/CryptoSuite_ECDSA_AES.js
makeRealPem
function makeRealPem(pem) { let result = null; if (typeof pem === 'string') { result = pem.replace(/-----BEGIN -----/, '-----BEGIN CERTIFICATE-----'); result = result.replace(/-----END -----/, '-----END CERTIFICATE-----'); result = result.replace(/-----([^-]+) ECDSA ([^-]+)-----([^-]*)-----([^-]+) ECDSA ([^-]+)-----/, '-----$1 EC $2-----$3-----$4 EC $5-----'); } return result; }
javascript
function makeRealPem(pem) { let result = null; if (typeof pem === 'string') { result = pem.replace(/-----BEGIN -----/, '-----BEGIN CERTIFICATE-----'); result = result.replace(/-----END -----/, '-----END CERTIFICATE-----'); result = result.replace(/-----([^-]+) ECDSA ([^-]+)-----([^-]*)-----([^-]+) ECDSA ([^-]+)-----/, '-----$1 EC $2-----$3-----$4 EC $5-----'); } return result; }
[ "function", "makeRealPem", "(", "pem", ")", "{", "let", "result", "=", "null", ";", "if", "(", "typeof", "pem", "===", "'string'", ")", "{", "result", "=", "pem", ".", "replace", "(", "/", "-----BEGIN -----", "/", ",", "'-----BEGIN CERTIFICATE-----'", ")", ";", "result", "=", "result", ".", "replace", "(", "/", "-----END -----", "/", ",", "'-----END CERTIFICATE-----'", ")", ";", "result", "=", "result", ".", "replace", "(", "/", "-----([^-]+) ECDSA ([^-]+)-----([^-]*)-----([^-]+) ECDSA ([^-]+)-----", "/", ",", "'-----$1 EC $2-----$3-----$4 EC $5-----'", ")", ";", "}", "return", "result", ";", "}" ]
Utilitly method to make sure the start and end markers are correct
[ "Utilitly", "method", "to", "make", "sure", "the", "start", "and", "end", "markers", "are", "correct" ]
4f62e201624c1e9a14d548808d3524aa93573cd5
https://github.com/hyperledger/fabric-sdk-node/blob/4f62e201624c1e9a14d548808d3524aa93573cd5/fabric-client/lib/impl/CryptoSuite_ECDSA_AES.js#L343-L351
10,371
hyperledger/fabric-sdk-node
fabric-network/lib/contract.js
verifyTransactionName
function verifyTransactionName(name) { if (typeof name !== 'string' || name.length === 0) { const msg = util.format('Transaction name must be a non-empty string: %j', name); logger.error('verifyTransactionName:', msg); throw new Error(msg); } }
javascript
function verifyTransactionName(name) { if (typeof name !== 'string' || name.length === 0) { const msg = util.format('Transaction name must be a non-empty string: %j', name); logger.error('verifyTransactionName:', msg); throw new Error(msg); } }
[ "function", "verifyTransactionName", "(", "name", ")", "{", "if", "(", "typeof", "name", "!==", "'string'", "||", "name", ".", "length", "===", "0", ")", "{", "const", "msg", "=", "util", ".", "format", "(", "'Transaction name must be a non-empty string: %j'", ",", "name", ")", ";", "logger", ".", "error", "(", "'verifyTransactionName:'", ",", "msg", ")", ";", "throw", "new", "Error", "(", "msg", ")", ";", "}", "}" ]
Ensure transaction name is a non-empty string. @private @param {*} name Transaction name. @throws {Error} if the name is invalid.
[ "Ensure", "transaction", "name", "is", "a", "non", "-", "empty", "string", "." ]
4f62e201624c1e9a14d548808d3524aa93573cd5
https://github.com/hyperledger/fabric-sdk-node/blob/4f62e201624c1e9a14d548808d3524aa93573cd5/fabric-network/lib/contract.js#L21-L27
10,372
hyperledger/fabric-sdk-node
fabric-network/lib/contract.js
verifyNamespace
function verifyNamespace(namespace) { if (namespace && typeof namespace !== 'string') { const msg = util.format('Namespace must be a non-empty string: %j', namespace); logger.error('verifyNamespace:', msg); throw new Error(msg); } }
javascript
function verifyNamespace(namespace) { if (namespace && typeof namespace !== 'string') { const msg = util.format('Namespace must be a non-empty string: %j', namespace); logger.error('verifyNamespace:', msg); throw new Error(msg); } }
[ "function", "verifyNamespace", "(", "namespace", ")", "{", "if", "(", "namespace", "&&", "typeof", "namespace", "!==", "'string'", ")", "{", "const", "msg", "=", "util", ".", "format", "(", "'Namespace must be a non-empty string: %j'", ",", "namespace", ")", ";", "logger", ".", "error", "(", "'verifyNamespace:'", ",", "msg", ")", ";", "throw", "new", "Error", "(", "msg", ")", ";", "}", "}" ]
Ensure that, if a namespace is defined, it is a non-empty string @private @param {*} namespace Transaction namespace. @throws {Error} if the namespace is invalid.
[ "Ensure", "that", "if", "a", "namespace", "is", "defined", "it", "is", "a", "non", "-", "empty", "string" ]
4f62e201624c1e9a14d548808d3524aa93573cd5
https://github.com/hyperledger/fabric-sdk-node/blob/4f62e201624c1e9a14d548808d3524aa93573cd5/fabric-network/lib/contract.js#L35-L41
10,373
hyperledger/fabric-sdk-node
fabric-network/lib/transaction.js
verifyArguments
function verifyArguments(args) { const isInvalid = args.some((arg) => typeof arg !== 'string'); if (isInvalid) { const argsString = args.map((arg) => util.format('%j', arg)).join(', '); const msg = util.format('Transaction arguments must be strings: %s', argsString); logger.error('verifyArguments:', msg); throw new Error(msg); } }
javascript
function verifyArguments(args) { const isInvalid = args.some((arg) => typeof arg !== 'string'); if (isInvalid) { const argsString = args.map((arg) => util.format('%j', arg)).join(', '); const msg = util.format('Transaction arguments must be strings: %s', argsString); logger.error('verifyArguments:', msg); throw new Error(msg); } }
[ "function", "verifyArguments", "(", "args", ")", "{", "const", "isInvalid", "=", "args", ".", "some", "(", "(", "arg", ")", "=>", "typeof", "arg", "!==", "'string'", ")", ";", "if", "(", "isInvalid", ")", "{", "const", "argsString", "=", "args", ".", "map", "(", "(", "arg", ")", "=>", "util", ".", "format", "(", "'%j'", ",", "arg", ")", ")", ".", "join", "(", "', '", ")", ";", "const", "msg", "=", "util", ".", "format", "(", "'Transaction arguments must be strings: %s'", ",", "argsString", ")", ";", "logger", ".", "error", "(", "'verifyArguments:'", ",", "msg", ")", ";", "throw", "new", "Error", "(", "msg", ")", ";", "}", "}" ]
Ensure supplied transaction arguments are not strings. @private @static @param {Array} args transaction arguments. @throws {Error} if any arguments are invalid.
[ "Ensure", "supplied", "transaction", "arguments", "are", "not", "strings", "." ]
4f62e201624c1e9a14d548808d3524aa93573cd5
https://github.com/hyperledger/fabric-sdk-node/blob/4f62e201624c1e9a14d548808d3524aa93573cd5/fabric-network/lib/transaction.js#L27-L35
10,374
hyperledger/fabric-sdk-node
fabric-client/lib/Client.js
_stringToSignature
function _stringToSignature(string_signatures) { const signatures = []; for (let signature of string_signatures) { // check for properties rather than object type if (signature && signature.signature_header && signature.signature) { logger.debug('_stringToSignature - signature is protobuf'); } else { logger.debug('_stringToSignature - signature is string'); const signature_bytes = Buffer.from(signature, 'hex'); signature = _configtxProto.ConfigSignature.decode(signature_bytes); } signatures.push(signature); } return signatures; }
javascript
function _stringToSignature(string_signatures) { const signatures = []; for (let signature of string_signatures) { // check for properties rather than object type if (signature && signature.signature_header && signature.signature) { logger.debug('_stringToSignature - signature is protobuf'); } else { logger.debug('_stringToSignature - signature is string'); const signature_bytes = Buffer.from(signature, 'hex'); signature = _configtxProto.ConfigSignature.decode(signature_bytes); } signatures.push(signature); } return signatures; }
[ "function", "_stringToSignature", "(", "string_signatures", ")", "{", "const", "signatures", "=", "[", "]", ";", "for", "(", "let", "signature", "of", "string_signatures", ")", "{", "// check for properties rather than object type", "if", "(", "signature", "&&", "signature", ".", "signature_header", "&&", "signature", ".", "signature", ")", "{", "logger", ".", "debug", "(", "'_stringToSignature - signature is protobuf'", ")", ";", "}", "else", "{", "logger", ".", "debug", "(", "'_stringToSignature - signature is string'", ")", ";", "const", "signature_bytes", "=", "Buffer", ".", "from", "(", "signature", ",", "'hex'", ")", ";", "signature", "=", "_configtxProto", ".", "ConfigSignature", ".", "decode", "(", "signature_bytes", ")", ";", "}", "signatures", ".", "push", "(", "signature", ")", ";", "}", "return", "signatures", ";", "}" ]
internal utility method to check and convert any strings to protobuf signatures
[ "internal", "utility", "method", "to", "check", "and", "convert", "any", "strings", "to", "protobuf", "signatures" ]
4f62e201624c1e9a14d548808d3524aa93573cd5
https://github.com/hyperledger/fabric-sdk-node/blob/4f62e201624c1e9a14d548808d3524aa93573cd5/fabric-client/lib/Client.js#L1868-L1883
10,375
hyperledger/fabric-sdk-node
fabric-client/lib/Client.js
_getNetworkConfig
function _getNetworkConfig(loadConfig, client) { let network_config = null; let network_data = null; let network_config_loc = null; if (typeof loadConfig === 'string') { network_config_loc = path.resolve(loadConfig); logger.debug('%s - looking at absolute path of ==>%s<==', '_getNetworkConfig', network_config_loc); const file_data = fs.readFileSync(network_config_loc); const file_ext = path.extname(network_config_loc); // maybe the file is yaml else has to be JSON if ((/(yml|yaml)$/i).test(file_ext)) { network_data = yaml.safeLoad(file_data); } else { network_data = JSON.parse(file_data); } } else { network_data = loadConfig; } try { if (!network_data) { throw new Error('missing configuration data'); } if (!network_data.version) { throw new Error('"version" is missing'); } const parsing = Client.getConfigSetting('network-config-schema'); if (!parsing) { throw new Error('missing "network-config-schema" configuration setting'); } const pieces = network_data.version.toString().split('.'); const version = pieces[0] + '.' + pieces[1]; if (!parsing[version]) { throw new Error('common connection profile has an unknown "version"'); } const NetworkConfig = require(parsing[version]); network_config = new NetworkConfig(network_data, client, network_config_loc); } catch (error) { throw new Error(util.format('Invalid common connection profile due to %s', error.message)); } return network_config; }
javascript
function _getNetworkConfig(loadConfig, client) { let network_config = null; let network_data = null; let network_config_loc = null; if (typeof loadConfig === 'string') { network_config_loc = path.resolve(loadConfig); logger.debug('%s - looking at absolute path of ==>%s<==', '_getNetworkConfig', network_config_loc); const file_data = fs.readFileSync(network_config_loc); const file_ext = path.extname(network_config_loc); // maybe the file is yaml else has to be JSON if ((/(yml|yaml)$/i).test(file_ext)) { network_data = yaml.safeLoad(file_data); } else { network_data = JSON.parse(file_data); } } else { network_data = loadConfig; } try { if (!network_data) { throw new Error('missing configuration data'); } if (!network_data.version) { throw new Error('"version" is missing'); } const parsing = Client.getConfigSetting('network-config-schema'); if (!parsing) { throw new Error('missing "network-config-schema" configuration setting'); } const pieces = network_data.version.toString().split('.'); const version = pieces[0] + '.' + pieces[1]; if (!parsing[version]) { throw new Error('common connection profile has an unknown "version"'); } const NetworkConfig = require(parsing[version]); network_config = new NetworkConfig(network_data, client, network_config_loc); } catch (error) { throw new Error(util.format('Invalid common connection profile due to %s', error.message)); } return network_config; }
[ "function", "_getNetworkConfig", "(", "loadConfig", ",", "client", ")", "{", "let", "network_config", "=", "null", ";", "let", "network_data", "=", "null", ";", "let", "network_config_loc", "=", "null", ";", "if", "(", "typeof", "loadConfig", "===", "'string'", ")", "{", "network_config_loc", "=", "path", ".", "resolve", "(", "loadConfig", ")", ";", "logger", ".", "debug", "(", "'%s - looking at absolute path of ==>%s<=='", ",", "'_getNetworkConfig'", ",", "network_config_loc", ")", ";", "const", "file_data", "=", "fs", ".", "readFileSync", "(", "network_config_loc", ")", ";", "const", "file_ext", "=", "path", ".", "extname", "(", "network_config_loc", ")", ";", "// maybe the file is yaml else has to be JSON", "if", "(", "(", "/", "(yml|yaml)$", "/", "i", ")", ".", "test", "(", "file_ext", ")", ")", "{", "network_data", "=", "yaml", ".", "safeLoad", "(", "file_data", ")", ";", "}", "else", "{", "network_data", "=", "JSON", ".", "parse", "(", "file_data", ")", ";", "}", "}", "else", "{", "network_data", "=", "loadConfig", ";", "}", "try", "{", "if", "(", "!", "network_data", ")", "{", "throw", "new", "Error", "(", "'missing configuration data'", ")", ";", "}", "if", "(", "!", "network_data", ".", "version", ")", "{", "throw", "new", "Error", "(", "'\"version\" is missing'", ")", ";", "}", "const", "parsing", "=", "Client", ".", "getConfigSetting", "(", "'network-config-schema'", ")", ";", "if", "(", "!", "parsing", ")", "{", "throw", "new", "Error", "(", "'missing \"network-config-schema\" configuration setting'", ")", ";", "}", "const", "pieces", "=", "network_data", ".", "version", ".", "toString", "(", ")", ".", "split", "(", "'.'", ")", ";", "const", "version", "=", "pieces", "[", "0", "]", "+", "'.'", "+", "pieces", "[", "1", "]", ";", "if", "(", "!", "parsing", "[", "version", "]", ")", "{", "throw", "new", "Error", "(", "'common connection profile has an unknown \"version\"'", ")", ";", "}", "const", "NetworkConfig", "=", "require", "(", "parsing", "[", "version", "]", ")", ";", "network_config", "=", "new", "NetworkConfig", "(", "network_data", ",", "client", ",", "network_config_loc", ")", ";", "}", "catch", "(", "error", ")", "{", "throw", "new", "Error", "(", "util", ".", "format", "(", "'Invalid common connection profile due to %s'", ",", "error", ".", "message", ")", ")", ";", "}", "return", "network_config", ";", "}" ]
internal utility method to get a NetworkConfig
[ "internal", "utility", "method", "to", "get", "a", "NetworkConfig" ]
4f62e201624c1e9a14d548808d3524aa93573cd5
https://github.com/hyperledger/fabric-sdk-node/blob/4f62e201624c1e9a14d548808d3524aa93573cd5/fabric-client/lib/Client.js#L1886-L1928
10,376
hyperledger/fabric-sdk-node
fabric-client/lib/Channel.js
_getProposalResponseResults
function _getProposalResponseResults(proposal_response) { if (!proposal_response.payload) { throw new Error('Parameter must be a ProposalResponse Object'); } const payload = _responseProto.ProposalResponsePayload.decode(proposal_response.payload); const extension = _proposalProto.ChaincodeAction.decode(payload.extension); // TODO should we check the status of this action logger.debug('_getWriteSet - chaincode action status:%s message:%s', extension.response.status, extension.response.message); // return a buffer object which has an equals method return extension.results.toBuffer(); }
javascript
function _getProposalResponseResults(proposal_response) { if (!proposal_response.payload) { throw new Error('Parameter must be a ProposalResponse Object'); } const payload = _responseProto.ProposalResponsePayload.decode(proposal_response.payload); const extension = _proposalProto.ChaincodeAction.decode(payload.extension); // TODO should we check the status of this action logger.debug('_getWriteSet - chaincode action status:%s message:%s', extension.response.status, extension.response.message); // return a buffer object which has an equals method return extension.results.toBuffer(); }
[ "function", "_getProposalResponseResults", "(", "proposal_response", ")", "{", "if", "(", "!", "proposal_response", ".", "payload", ")", "{", "throw", "new", "Error", "(", "'Parameter must be a ProposalResponse Object'", ")", ";", "}", "const", "payload", "=", "_responseProto", ".", "ProposalResponsePayload", ".", "decode", "(", "proposal_response", ".", "payload", ")", ";", "const", "extension", "=", "_proposalProto", ".", "ChaincodeAction", ".", "decode", "(", "payload", ".", "extension", ")", ";", "// TODO should we check the status of this action", "logger", ".", "debug", "(", "'_getWriteSet - chaincode action status:%s message:%s'", ",", "extension", ".", "response", ".", "status", ",", "extension", ".", "response", ".", "message", ")", ";", "// return a buffer object which has an equals method", "return", "extension", ".", "results", ".", "toBuffer", "(", ")", ";", "}" ]
internal utility method to decode and get the write set from a proposal response
[ "internal", "utility", "method", "to", "decode", "and", "get", "the", "write", "set", "from", "a", "proposal", "response" ]
4f62e201624c1e9a14d548808d3524aa93573cd5
https://github.com/hyperledger/fabric-sdk-node/blob/4f62e201624c1e9a14d548808d3524aa93573cd5/fabric-client/lib/Channel.js#L3624-L3634
10,377
sidorares/node-mysql2
lib/helpers.js
printDebugWithCode
function printDebugWithCode(msg, code) { // eslint-disable-next-line no-console console.log(`\n\n${msg}:\n`); // eslint-disable-next-line no-console console.log(`${highlightFn(code)}\n`); }
javascript
function printDebugWithCode(msg, code) { // eslint-disable-next-line no-console console.log(`\n\n${msg}:\n`); // eslint-disable-next-line no-console console.log(`${highlightFn(code)}\n`); }
[ "function", "printDebugWithCode", "(", "msg", ",", "code", ")", "{", "// eslint-disable-next-line no-console", "console", ".", "log", "(", "`", "\\n", "\\n", "${", "msg", "}", "\\n", "`", ")", ";", "// eslint-disable-next-line no-console", "console", ".", "log", "(", "`", "${", "highlightFn", "(", "code", ")", "}", "\\n", "`", ")", ";", "}" ]
Prints debug message with code frame, will try to use `cardinal` if available.
[ "Prints", "debug", "message", "with", "code", "frame", "will", "try", "to", "use", "cardinal", "if", "available", "." ]
0b8ab90df2fdf7ade2961b588c7413428e9fd9f4
https://github.com/sidorares/node-mysql2/blob/0b8ab90df2fdf7ade2961b588c7413428e9fd9f4/lib/helpers.js#L43-L48
10,378
521dimensions/amplitudejs
dist/visualizations/michaelbromley.js
Polygon
function Polygon( sides, x, y, tileSize, ctx, num, analyser, streamData, tiles, fgRotation ){ this.analyser = analyser; this.sides = sides; this.tileSize = tileSize; this.ctx = ctx; this.tiles = tiles; this.fgRotation = fgRotation; /* The number of the tile, starting at 0 */ this.num = num; /* The highest colour value, which then fades out */ this.high = 0; /* Increase this value to fade out faster. */ this.decay = this.num > 42 ? 1.5 : 2; /* For highlighted stroke effect figure out the x and y coordinates of the center of the polygon based on the 60 degree XY axis coordinates passed in */ this.highlight = 0; var step = Math.round(Math.cos(Math.PI/6)*tileSize*2); this.y = Math.round(step * Math.sin(Math.PI/3) * -y ); this.x = Math.round(x * step + y * step/2 ); /* Calculate the vertices of the polygon */ this.vertices = []; for (var i = 1; i <= this.sides;i += 1) { x = this.x + this.tileSize * Math.cos(i * 2 * Math.PI / this.sides + Math.PI/6); y = this.y + this.tileSize * Math.sin(i * 2 * Math.PI / this.sides + Math.PI/6); this.vertices.push([x, y]); } this.streamData = streamData; }
javascript
function Polygon( sides, x, y, tileSize, ctx, num, analyser, streamData, tiles, fgRotation ){ this.analyser = analyser; this.sides = sides; this.tileSize = tileSize; this.ctx = ctx; this.tiles = tiles; this.fgRotation = fgRotation; /* The number of the tile, starting at 0 */ this.num = num; /* The highest colour value, which then fades out */ this.high = 0; /* Increase this value to fade out faster. */ this.decay = this.num > 42 ? 1.5 : 2; /* For highlighted stroke effect figure out the x and y coordinates of the center of the polygon based on the 60 degree XY axis coordinates passed in */ this.highlight = 0; var step = Math.round(Math.cos(Math.PI/6)*tileSize*2); this.y = Math.round(step * Math.sin(Math.PI/3) * -y ); this.x = Math.round(x * step + y * step/2 ); /* Calculate the vertices of the polygon */ this.vertices = []; for (var i = 1; i <= this.sides;i += 1) { x = this.x + this.tileSize * Math.cos(i * 2 * Math.PI / this.sides + Math.PI/6); y = this.y + this.tileSize * Math.sin(i * 2 * Math.PI / this.sides + Math.PI/6); this.vertices.push([x, y]); } this.streamData = streamData; }
[ "function", "Polygon", "(", "sides", ",", "x", ",", "y", ",", "tileSize", ",", "ctx", ",", "num", ",", "analyser", ",", "streamData", ",", "tiles", ",", "fgRotation", ")", "{", "this", ".", "analyser", "=", "analyser", ";", "this", ".", "sides", "=", "sides", ";", "this", ".", "tileSize", "=", "tileSize", ";", "this", ".", "ctx", "=", "ctx", ";", "this", ".", "tiles", "=", "tiles", ";", "this", ".", "fgRotation", "=", "fgRotation", ";", "/*\n\t\tThe number of the tile, starting at 0\n\t*/", "this", ".", "num", "=", "num", ";", "/*\n\t\tThe highest colour value, which then fades out\n\t*/", "this", ".", "high", "=", "0", ";", "/*\n\t\tIncrease this value to fade out faster.\n\t*/", "this", ".", "decay", "=", "this", ".", "num", ">", "42", "?", "1.5", ":", "2", ";", "/* For highlighted stroke effect\n\t\tfigure out the x and y coordinates of the center of the polygon based on the\n\t\t60 degree XY axis coordinates passed in\n\t*/", "this", ".", "highlight", "=", "0", ";", "var", "step", "=", "Math", ".", "round", "(", "Math", ".", "cos", "(", "Math", ".", "PI", "/", "6", ")", "*", "tileSize", "*", "2", ")", ";", "this", ".", "y", "=", "Math", ".", "round", "(", "step", "*", "Math", ".", "sin", "(", "Math", ".", "PI", "/", "3", ")", "*", "-", "y", ")", ";", "this", ".", "x", "=", "Math", ".", "round", "(", "x", "*", "step", "+", "y", "*", "step", "/", "2", ")", ";", "/*\n\t\tCalculate the vertices of the polygon\n\t*/", "this", ".", "vertices", "=", "[", "]", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<=", "this", ".", "sides", ";", "i", "+=", "1", ")", "{", "x", "=", "this", ".", "x", "+", "this", ".", "tileSize", "*", "Math", ".", "cos", "(", "i", "*", "2", "*", "Math", ".", "PI", "/", "this", ".", "sides", "+", "Math", ".", "PI", "/", "6", ")", ";", "y", "=", "this", ".", "y", "+", "this", ".", "tileSize", "*", "Math", ".", "sin", "(", "i", "*", "2", "*", "Math", ".", "PI", "/", "this", ".", "sides", "+", "Math", ".", "PI", "/", "6", ")", ";", "this", ".", "vertices", ".", "push", "(", "[", "x", ",", "y", "]", ")", ";", "}", "this", ".", "streamData", "=", "streamData", ";", "}" ]
Defines the polygon object. @param {number} sides @param {number} x @param {number} y @param {number} tileSize @param {context} ctx @param {number} num @param {Uint8Array} streamData @param {array} tiles @param {integer} fgRotation
[ "Defines", "the", "polygon", "object", "." ]
86eea632f251ebaeb04b3c9ee9c84470d912f298
https://github.com/521dimensions/amplitudejs/blob/86eea632f251ebaeb04b3c9ee9c84470d912f298/dist/visualizations/michaelbromley.js#L432-L475
10,379
521dimensions/amplitudejs
dist/visualizations/michaelbromley.js
Star
function Star( x, y, starSize, ctx, fgCanvas, analyser, streamData ){ this.x = x; this.y = y; this.angle = Math.atan( Math.abs(y) / Math.abs(x) ); this.starSize = starSize; this.ctx = ctx; this.high = 0; this.fgCanvas = fgCanvas; this.analyser = analyser; this.streamData = streamData; }
javascript
function Star( x, y, starSize, ctx, fgCanvas, analyser, streamData ){ this.x = x; this.y = y; this.angle = Math.atan( Math.abs(y) / Math.abs(x) ); this.starSize = starSize; this.ctx = ctx; this.high = 0; this.fgCanvas = fgCanvas; this.analyser = analyser; this.streamData = streamData; }
[ "function", "Star", "(", "x", ",", "y", ",", "starSize", ",", "ctx", ",", "fgCanvas", ",", "analyser", ",", "streamData", ")", "{", "this", ".", "x", "=", "x", ";", "this", ".", "y", "=", "y", ";", "this", ".", "angle", "=", "Math", ".", "atan", "(", "Math", ".", "abs", "(", "y", ")", "/", "Math", ".", "abs", "(", "x", ")", ")", ";", "this", ".", "starSize", "=", "starSize", ";", "this", ".", "ctx", "=", "ctx", ";", "this", ".", "high", "=", "0", ";", "this", ".", "fgCanvas", "=", "fgCanvas", ";", "this", ".", "analyser", "=", "analyser", ";", "this", ".", "streamData", "=", "streamData", ";", "}" ]
Define the star object @param {number} x @param {number} y @param {number} starSize @param {context} ctx @param {canvas} fgCanvas @param {analyser} analyser @param {Uint8Array} streamData
[ "Define", "the", "star", "object" ]
86eea632f251ebaeb04b3c9ee9c84470d912f298
https://github.com/521dimensions/amplitudejs/blob/86eea632f251ebaeb04b3c9ee9c84470d912f298/dist/visualizations/michaelbromley.js#L661-L671
10,380
jsbin/jsbin
public/js/vendor/codemirror3/mode/smarty/smarty.js
function(stream, state) { if (stream.match(settings.leftDelimiter, true)) { if (stream.eat("*")) { return helpers.chain(stream, state, parsers.inBlock("comment", "*" + settings.rightDelimiter)); } else { // Smarty 3 allows { and } surrounded by whitespace to NOT slip into Smarty mode state.depth++; var isEol = stream.eol(); var isFollowedByWhitespace = /\s/.test(stream.peek()); if (settings.smartyVersion === 3 && settings.leftDelimiter === "{" && (isEol || isFollowedByWhitespace)) { state.depth--; return null; } else { state.tokenize = parsers.smarty; last = "startTag"; return "tag"; } } } else { stream.next(); return null; } }
javascript
function(stream, state) { if (stream.match(settings.leftDelimiter, true)) { if (stream.eat("*")) { return helpers.chain(stream, state, parsers.inBlock("comment", "*" + settings.rightDelimiter)); } else { // Smarty 3 allows { and } surrounded by whitespace to NOT slip into Smarty mode state.depth++; var isEol = stream.eol(); var isFollowedByWhitespace = /\s/.test(stream.peek()); if (settings.smartyVersion === 3 && settings.leftDelimiter === "{" && (isEol || isFollowedByWhitespace)) { state.depth--; return null; } else { state.tokenize = parsers.smarty; last = "startTag"; return "tag"; } } } else { stream.next(); return null; } }
[ "function", "(", "stream", ",", "state", ")", "{", "if", "(", "stream", ".", "match", "(", "settings", ".", "leftDelimiter", ",", "true", ")", ")", "{", "if", "(", "stream", ".", "eat", "(", "\"*\"", ")", ")", "{", "return", "helpers", ".", "chain", "(", "stream", ",", "state", ",", "parsers", ".", "inBlock", "(", "\"comment\"", ",", "\"*\"", "+", "settings", ".", "rightDelimiter", ")", ")", ";", "}", "else", "{", "// Smarty 3 allows { and } surrounded by whitespace to NOT slip into Smarty mode", "state", ".", "depth", "++", ";", "var", "isEol", "=", "stream", ".", "eol", "(", ")", ";", "var", "isFollowedByWhitespace", "=", "/", "\\s", "/", ".", "test", "(", "stream", ".", "peek", "(", ")", ")", ";", "if", "(", "settings", ".", "smartyVersion", "===", "3", "&&", "settings", ".", "leftDelimiter", "===", "\"{\"", "&&", "(", "isEol", "||", "isFollowedByWhitespace", ")", ")", "{", "state", ".", "depth", "--", ";", "return", "null", ";", "}", "else", "{", "state", ".", "tokenize", "=", "parsers", ".", "smarty", ";", "last", "=", "\"startTag\"", ";", "return", "\"tag\"", ";", "}", "}", "}", "else", "{", "stream", ".", "next", "(", ")", ";", "return", "null", ";", "}", "}" ]
the main tokenizer
[ "the", "main", "tokenizer" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/codemirror3/mode/smarty/smarty.js#L47-L69
10,381
jsbin/jsbin
public/js/render/edit.js
jsbinShowEdit
function jsbinShowEdit(options) { 'use strict'; if (window.location.hash === '#noedit') {return;} var moveTimer, over, doc = document, aEL = 'addEventListener', path = options.root + window.location.pathname, style = doc.createElement('link'), btn = doc.createElement('a'); // Add button: btn.id = 'edit-with-js-bin'; btn.href = path + (path.slice(-1) === '/' ? '' : '/') + 'edit'; btn.innerHTML = 'Edit in JS Bin <img src="' + options['static'] + '/images/favicon.png" width="16" height="16">'; doc.documentElement.appendChild(btn); // Style button: style.setAttribute('rel', 'stylesheet'); style.setAttribute('href', options['static'] + '/css/edit.css'); doc.documentElement.appendChild(style); // show / hide button: btn.onmouseover = btn.onmouseout = function() { over = !over; (over ? show : hide)(); }; function show() { clearTimeout(moveTimer); btn.style.top = '0'; moveTimer = setTimeout(hide, 2000); } function hide() { if (!over) { btn.style.top = '-60px'; } } show(); if (aEL in doc) {doc[aEL]('mousemove', show, false);} else {doc.attachEvent('mousemove', show);} }
javascript
function jsbinShowEdit(options) { 'use strict'; if (window.location.hash === '#noedit') {return;} var moveTimer, over, doc = document, aEL = 'addEventListener', path = options.root + window.location.pathname, style = doc.createElement('link'), btn = doc.createElement('a'); // Add button: btn.id = 'edit-with-js-bin'; btn.href = path + (path.slice(-1) === '/' ? '' : '/') + 'edit'; btn.innerHTML = 'Edit in JS Bin <img src="' + options['static'] + '/images/favicon.png" width="16" height="16">'; doc.documentElement.appendChild(btn); // Style button: style.setAttribute('rel', 'stylesheet'); style.setAttribute('href', options['static'] + '/css/edit.css'); doc.documentElement.appendChild(style); // show / hide button: btn.onmouseover = btn.onmouseout = function() { over = !over; (over ? show : hide)(); }; function show() { clearTimeout(moveTimer); btn.style.top = '0'; moveTimer = setTimeout(hide, 2000); } function hide() { if (!over) { btn.style.top = '-60px'; } } show(); if (aEL in doc) {doc[aEL]('mousemove', show, false);} else {doc.attachEvent('mousemove', show);} }
[ "function", "jsbinShowEdit", "(", "options", ")", "{", "'use strict'", ";", "if", "(", "window", ".", "location", ".", "hash", "===", "'#noedit'", ")", "{", "return", ";", "}", "var", "moveTimer", ",", "over", ",", "doc", "=", "document", ",", "aEL", "=", "'addEventListener'", ",", "path", "=", "options", ".", "root", "+", "window", ".", "location", ".", "pathname", ",", "style", "=", "doc", ".", "createElement", "(", "'link'", ")", ",", "btn", "=", "doc", ".", "createElement", "(", "'a'", ")", ";", "// Add button:", "btn", ".", "id", "=", "'edit-with-js-bin'", ";", "btn", ".", "href", "=", "path", "+", "(", "path", ".", "slice", "(", "-", "1", ")", "===", "'/'", "?", "''", ":", "'/'", ")", "+", "'edit'", ";", "btn", ".", "innerHTML", "=", "'Edit in JS Bin <img src=\"'", "+", "options", "[", "'static'", "]", "+", "'/images/favicon.png\" width=\"16\" height=\"16\">'", ";", "doc", ".", "documentElement", ".", "appendChild", "(", "btn", ")", ";", "// Style button:", "style", ".", "setAttribute", "(", "'rel'", ",", "'stylesheet'", ")", ";", "style", ".", "setAttribute", "(", "'href'", ",", "options", "[", "'static'", "]", "+", "'/css/edit.css'", ")", ";", "doc", ".", "documentElement", ".", "appendChild", "(", "style", ")", ";", "// show / hide button:", "btn", ".", "onmouseover", "=", "btn", ".", "onmouseout", "=", "function", "(", ")", "{", "over", "=", "!", "over", ";", "(", "over", "?", "show", ":", "hide", ")", "(", ")", ";", "}", ";", "function", "show", "(", ")", "{", "clearTimeout", "(", "moveTimer", ")", ";", "btn", ".", "style", ".", "top", "=", "'0'", ";", "moveTimer", "=", "setTimeout", "(", "hide", ",", "2000", ")", ";", "}", "function", "hide", "(", ")", "{", "if", "(", "!", "over", ")", "{", "btn", ".", "style", ".", "top", "=", "'-60px'", ";", "}", "}", "show", "(", ")", ";", "if", "(", "aEL", "in", "doc", ")", "{", "doc", "[", "aEL", "]", "(", "'mousemove'", ",", "show", ",", "false", ")", ";", "}", "else", "{", "doc", ".", "attachEvent", "(", "'mousemove'", ",", "show", ")", ";", "}", "}" ]
"Edit in JS Bin" button setup
[ "Edit", "in", "JS", "Bin", "button", "setup" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/render/edit.js#L2-L44
10,382
jsbin/jsbin
public/js/vendor/codemirror3/mode/haskell/haskell.js
normal
function normal(source, setState) { if (source.eatWhile(whiteCharRE)) { return null; } var ch = source.next(); if (specialRE.test(ch)) { if (ch == '{' && source.eat('-')) { var t = "comment"; if (source.eat('#')) { t = "meta"; } return switchState(source, setState, ncomment(t, 1)); } return null; } if (ch == '\'') { if (source.eat('\\')) { source.next(); // should handle other escapes here } else { source.next(); } if (source.eat('\'')) { return "string"; } return "error"; } if (ch == '"') { return switchState(source, setState, stringLiteral); } if (largeRE.test(ch)) { source.eatWhile(idRE); if (source.eat('.')) { return "qualifier"; } return "variable-2"; } if (smallRE.test(ch)) { source.eatWhile(idRE); return "variable"; } if (digitRE.test(ch)) { if (ch == '0') { if (source.eat(/[xX]/)) { source.eatWhile(hexitRE); // should require at least 1 return "integer"; } if (source.eat(/[oO]/)) { source.eatWhile(octitRE); // should require at least 1 return "number"; } } source.eatWhile(digitRE); var t = "number"; if (source.match(/^\.\d+/)) { t = "number"; } if (source.eat(/[eE]/)) { t = "number"; source.eat(/[-+]/); source.eatWhile(digitRE); // should require at least 1 } return t; } if (ch == "." && source.eat(".")) return "keyword"; if (symbolRE.test(ch)) { if (ch == '-' && source.eat(/-/)) { source.eatWhile(/-/); if (!source.eat(symbolRE)) { source.skipToEnd(); return "comment"; } } var t = "variable"; if (ch == ':') { t = "variable-2"; } source.eatWhile(symbolRE); return t; } return "error"; }
javascript
function normal(source, setState) { if (source.eatWhile(whiteCharRE)) { return null; } var ch = source.next(); if (specialRE.test(ch)) { if (ch == '{' && source.eat('-')) { var t = "comment"; if (source.eat('#')) { t = "meta"; } return switchState(source, setState, ncomment(t, 1)); } return null; } if (ch == '\'') { if (source.eat('\\')) { source.next(); // should handle other escapes here } else { source.next(); } if (source.eat('\'')) { return "string"; } return "error"; } if (ch == '"') { return switchState(source, setState, stringLiteral); } if (largeRE.test(ch)) { source.eatWhile(idRE); if (source.eat('.')) { return "qualifier"; } return "variable-2"; } if (smallRE.test(ch)) { source.eatWhile(idRE); return "variable"; } if (digitRE.test(ch)) { if (ch == '0') { if (source.eat(/[xX]/)) { source.eatWhile(hexitRE); // should require at least 1 return "integer"; } if (source.eat(/[oO]/)) { source.eatWhile(octitRE); // should require at least 1 return "number"; } } source.eatWhile(digitRE); var t = "number"; if (source.match(/^\.\d+/)) { t = "number"; } if (source.eat(/[eE]/)) { t = "number"; source.eat(/[-+]/); source.eatWhile(digitRE); // should require at least 1 } return t; } if (ch == "." && source.eat(".")) return "keyword"; if (symbolRE.test(ch)) { if (ch == '-' && source.eat(/-/)) { source.eatWhile(/-/); if (!source.eat(symbolRE)) { source.skipToEnd(); return "comment"; } } var t = "variable"; if (ch == ':') { t = "variable-2"; } source.eatWhile(symbolRE); return t; } return "error"; }
[ "function", "normal", "(", "source", ",", "setState", ")", "{", "if", "(", "source", ".", "eatWhile", "(", "whiteCharRE", ")", ")", "{", "return", "null", ";", "}", "var", "ch", "=", "source", ".", "next", "(", ")", ";", "if", "(", "specialRE", ".", "test", "(", "ch", ")", ")", "{", "if", "(", "ch", "==", "'{'", "&&", "source", ".", "eat", "(", "'-'", ")", ")", "{", "var", "t", "=", "\"comment\"", ";", "if", "(", "source", ".", "eat", "(", "'#'", ")", ")", "{", "t", "=", "\"meta\"", ";", "}", "return", "switchState", "(", "source", ",", "setState", ",", "ncomment", "(", "t", ",", "1", ")", ")", ";", "}", "return", "null", ";", "}", "if", "(", "ch", "==", "'\\''", ")", "{", "if", "(", "source", ".", "eat", "(", "'\\\\'", ")", ")", "{", "source", ".", "next", "(", ")", ";", "// should handle other escapes here", "}", "else", "{", "source", ".", "next", "(", ")", ";", "}", "if", "(", "source", ".", "eat", "(", "'\\''", ")", ")", "{", "return", "\"string\"", ";", "}", "return", "\"error\"", ";", "}", "if", "(", "ch", "==", "'\"'", ")", "{", "return", "switchState", "(", "source", ",", "setState", ",", "stringLiteral", ")", ";", "}", "if", "(", "largeRE", ".", "test", "(", "ch", ")", ")", "{", "source", ".", "eatWhile", "(", "idRE", ")", ";", "if", "(", "source", ".", "eat", "(", "'.'", ")", ")", "{", "return", "\"qualifier\"", ";", "}", "return", "\"variable-2\"", ";", "}", "if", "(", "smallRE", ".", "test", "(", "ch", ")", ")", "{", "source", ".", "eatWhile", "(", "idRE", ")", ";", "return", "\"variable\"", ";", "}", "if", "(", "digitRE", ".", "test", "(", "ch", ")", ")", "{", "if", "(", "ch", "==", "'0'", ")", "{", "if", "(", "source", ".", "eat", "(", "/", "[xX]", "/", ")", ")", "{", "source", ".", "eatWhile", "(", "hexitRE", ")", ";", "// should require at least 1", "return", "\"integer\"", ";", "}", "if", "(", "source", ".", "eat", "(", "/", "[oO]", "/", ")", ")", "{", "source", ".", "eatWhile", "(", "octitRE", ")", ";", "// should require at least 1", "return", "\"number\"", ";", "}", "}", "source", ".", "eatWhile", "(", "digitRE", ")", ";", "var", "t", "=", "\"number\"", ";", "if", "(", "source", ".", "match", "(", "/", "^\\.\\d+", "/", ")", ")", "{", "t", "=", "\"number\"", ";", "}", "if", "(", "source", ".", "eat", "(", "/", "[eE]", "/", ")", ")", "{", "t", "=", "\"number\"", ";", "source", ".", "eat", "(", "/", "[-+]", "/", ")", ";", "source", ".", "eatWhile", "(", "digitRE", ")", ";", "// should require at least 1", "}", "return", "t", ";", "}", "if", "(", "ch", "==", "\".\"", "&&", "source", ".", "eat", "(", "\".\"", ")", ")", "return", "\"keyword\"", ";", "if", "(", "symbolRE", ".", "test", "(", "ch", ")", ")", "{", "if", "(", "ch", "==", "'-'", "&&", "source", ".", "eat", "(", "/", "-", "/", ")", ")", "{", "source", ".", "eatWhile", "(", "/", "-", "/", ")", ";", "if", "(", "!", "source", ".", "eat", "(", "symbolRE", ")", ")", "{", "source", ".", "skipToEnd", "(", ")", ";", "return", "\"comment\"", ";", "}", "}", "var", "t", "=", "\"variable\"", ";", "if", "(", "ch", "==", "':'", ")", "{", "t", "=", "\"variable-2\"", ";", "}", "source", ".", "eatWhile", "(", "symbolRE", ")", ";", "return", "t", ";", "}", "return", "\"error\"", ";", "}" ]
newlines are handled in tokenizer
[ "newlines", "are", "handled", "in", "tokenizer" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/codemirror3/mode/haskell/haskell.js#L19-L110
10,383
jsbin/jsbin
lib/handlers/error.js
function (err, req, res, next) { err = this.coerceError(err); if (err instanceof errors.NotFound && req.accepts('html')) { if (err instanceof errors.BinNotFound) { if (req.editor) { return (new BinHandler(this.sandbox)).notFound(req, res, next); } } return this.renderErrorPage('error', err, req, res); } else if (err instanceof errors.HTTPError) { // return this.renderError(err, req, res); return this.renderErrorPage(err.status, err, req, res); } if (err) { // console.error(err.stack); } next(err); }
javascript
function (err, req, res, next) { err = this.coerceError(err); if (err instanceof errors.NotFound && req.accepts('html')) { if (err instanceof errors.BinNotFound) { if (req.editor) { return (new BinHandler(this.sandbox)).notFound(req, res, next); } } return this.renderErrorPage('error', err, req, res); } else if (err instanceof errors.HTTPError) { // return this.renderError(err, req, res); return this.renderErrorPage(err.status, err, req, res); } if (err) { // console.error(err.stack); } next(err); }
[ "function", "(", "err", ",", "req", ",", "res", ",", "next", ")", "{", "err", "=", "this", ".", "coerceError", "(", "err", ")", ";", "if", "(", "err", "instanceof", "errors", ".", "NotFound", "&&", "req", ".", "accepts", "(", "'html'", ")", ")", "{", "if", "(", "err", "instanceof", "errors", ".", "BinNotFound", ")", "{", "if", "(", "req", ".", "editor", ")", "{", "return", "(", "new", "BinHandler", "(", "this", ".", "sandbox", ")", ")", ".", "notFound", "(", "req", ",", "res", ",", "next", ")", ";", "}", "}", "return", "this", ".", "renderErrorPage", "(", "'error'", ",", "err", ",", "req", ",", "res", ")", ";", "}", "else", "if", "(", "err", "instanceof", "errors", ".", "HTTPError", ")", "{", "// return this.renderError(err, req, res);", "return", "this", ".", "renderErrorPage", "(", "err", ".", "status", ",", "err", ",", "req", ",", "res", ")", ";", "}", "if", "(", "err", ")", "{", "// console.error(err.stack);", "}", "next", "(", "err", ")", ";", "}" ]
Handles all types of HTTPError and ensures that the correct type of response is returned depending on the type of content requested. So if you're expecting JSON you should get JSON.
[ "Handles", "all", "types", "of", "HTTPError", "and", "ensures", "that", "the", "correct", "type", "of", "response", "is", "returned", "depending", "on", "the", "type", "of", "content", "requested", ".", "So", "if", "you", "re", "expecting", "JSON", "you", "should", "get", "JSON", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/lib/handlers/error.js#L24-L45
10,384
jsbin/jsbin
lib/handlers/error.js
function (req, res) { var error = new errors.NotFound('Page Does Not Exist'); if (req.accepts('html') && (req.url.indexOf('/api/') !== 0)) { this.renderErrorPage('404', error, req, res); } else { this.renderError(error, req, res); } }
javascript
function (req, res) { var error = new errors.NotFound('Page Does Not Exist'); if (req.accepts('html') && (req.url.indexOf('/api/') !== 0)) { this.renderErrorPage('404', error, req, res); } else { this.renderError(error, req, res); } }
[ "function", "(", "req", ",", "res", ")", "{", "var", "error", "=", "new", "errors", ".", "NotFound", "(", "'Page Does Not Exist'", ")", ";", "if", "(", "req", ".", "accepts", "(", "'html'", ")", "&&", "(", "req", ".", "url", ".", "indexOf", "(", "'/api/'", ")", "!==", "0", ")", ")", "{", "this", ".", "renderErrorPage", "(", "'404'", ",", "error", ",", "req", ",", "res", ")", ";", "}", "else", "{", "this", ".", "renderError", "(", "error", ",", "req", ",", "res", ")", ";", "}", "}" ]
Fall through handler for when no routes match.
[ "Fall", "through", "handler", "for", "when", "no", "routes", "match", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/lib/handlers/error.js#L48-L55
10,385
jsbin/jsbin
lib/handlers/error.js
function (err, req, res) { console.error('uncaughtError', req.method + ' ' + req.url); this.sendErrorReport(err, req); if (req.accepts('html')) { this.renderErrorPage('error', err, req, res); } else { var error = new errors.HTTPError(500, 'Internal Server Error'); this.renderError(error, req, res); } }
javascript
function (err, req, res) { console.error('uncaughtError', req.method + ' ' + req.url); this.sendErrorReport(err, req); if (req.accepts('html')) { this.renderErrorPage('error', err, req, res); } else { var error = new errors.HTTPError(500, 'Internal Server Error'); this.renderError(error, req, res); } }
[ "function", "(", "err", ",", "req", ",", "res", ")", "{", "console", ".", "error", "(", "'uncaughtError'", ",", "req", ".", "method", "+", "' '", "+", "req", ".", "url", ")", ";", "this", ".", "sendErrorReport", "(", "err", ",", "req", ")", ";", "if", "(", "req", ".", "accepts", "(", "'html'", ")", ")", "{", "this", ".", "renderErrorPage", "(", "'error'", ",", "err", ",", "req", ",", "res", ")", ";", "}", "else", "{", "var", "error", "=", "new", "errors", ".", "HTTPError", "(", "500", ",", "'Internal Server Error'", ")", ";", "this", ".", "renderError", "(", "error", ",", "req", ",", "res", ")", ";", "}", "}" ]
Displays a friendly 500 page in production if requesting html otherwise returns an appropriate format.
[ "Displays", "a", "friendly", "500", "page", "in", "production", "if", "requesting", "html", "otherwise", "returns", "an", "appropriate", "format", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/lib/handlers/error.js#L59-L69
10,386
jsbin/jsbin
lib/handlers/error.js
function (err) { var status = typeof err === 'number' ? err : err.status; if (!(err instanceof errors.HTTPError) && status) { return errors.create(status, err.message); } return err; }
javascript
function (err) { var status = typeof err === 'number' ? err : err.status; if (!(err instanceof errors.HTTPError) && status) { return errors.create(status, err.message); } return err; }
[ "function", "(", "err", ")", "{", "var", "status", "=", "typeof", "err", "===", "'number'", "?", "err", ":", "err", ".", "status", ";", "if", "(", "!", "(", "err", "instanceof", "errors", ".", "HTTPError", ")", "&&", "status", ")", "{", "return", "errors", ".", "create", "(", "status", ",", "err", ".", "message", ")", ";", "}", "return", "err", ";", "}" ]
Checks to see if the error has a status property and if so converts it into an instance of HTTPError. Just returns this original error if no status is found.
[ "Checks", "to", "see", "if", "the", "error", "has", "a", "status", "property", "and", "if", "so", "converts", "it", "into", "an", "instance", "of", "HTTPError", ".", "Just", "returns", "this", "original", "error", "if", "no", "status", "is", "found", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/lib/handlers/error.js#L157-L164
10,387
jsbin/jsbin
public/js/chrome/share.js
formData
function formData(form) { var length = form.length; var data = {}; var value; var el; var type; var name; var append = function (data, name, value) { if (data[name] === undefined) { data[name] = value; } else { if (typeof data[name] === 'string') { data[name] = [data[name]]; } data[name].push(value); } }; for (var i = 0; i < length; i++) { el = form[i]; value = el.value; type = el.type; name = el.name; if (type === 'radio') { if (el.checked) { append(data, name, value); } } else if (type === 'checkbox') { if (data[name] === undefined) { data[name] = []; } if (el.checked) { append(data, name, value); } } else { append(data, name, value); } } return data; }
javascript
function formData(form) { var length = form.length; var data = {}; var value; var el; var type; var name; var append = function (data, name, value) { if (data[name] === undefined) { data[name] = value; } else { if (typeof data[name] === 'string') { data[name] = [data[name]]; } data[name].push(value); } }; for (var i = 0; i < length; i++) { el = form[i]; value = el.value; type = el.type; name = el.name; if (type === 'radio') { if (el.checked) { append(data, name, value); } } else if (type === 'checkbox') { if (data[name] === undefined) { data[name] = []; } if (el.checked) { append(data, name, value); } } else { append(data, name, value); } } return data; }
[ "function", "formData", "(", "form", ")", "{", "var", "length", "=", "form", ".", "length", ";", "var", "data", "=", "{", "}", ";", "var", "value", ";", "var", "el", ";", "var", "type", ";", "var", "name", ";", "var", "append", "=", "function", "(", "data", ",", "name", ",", "value", ")", "{", "if", "(", "data", "[", "name", "]", "===", "undefined", ")", "{", "data", "[", "name", "]", "=", "value", ";", "}", "else", "{", "if", "(", "typeof", "data", "[", "name", "]", "===", "'string'", ")", "{", "data", "[", "name", "]", "=", "[", "data", "[", "name", "]", "]", ";", "}", "data", "[", "name", "]", ".", "push", "(", "value", ")", ";", "}", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "el", "=", "form", "[", "i", "]", ";", "value", "=", "el", ".", "value", ";", "type", "=", "el", ".", "type", ";", "name", "=", "el", ".", "name", ";", "if", "(", "type", "===", "'radio'", ")", "{", "if", "(", "el", ".", "checked", ")", "{", "append", "(", "data", ",", "name", ",", "value", ")", ";", "}", "}", "else", "if", "(", "type", "===", "'checkbox'", ")", "{", "if", "(", "data", "[", "name", "]", "===", "undefined", ")", "{", "data", "[", "name", "]", "=", "[", "]", ";", "}", "if", "(", "el", ".", "checked", ")", "{", "append", "(", "data", ",", "name", ",", "value", ")", ";", "}", "}", "else", "{", "append", "(", "data", ",", "name", ",", "value", ")", ";", "}", "}", "return", "data", ";", "}" ]
get an object representation of a form's state
[ "get", "an", "object", "representation", "of", "a", "form", "s", "state" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/chrome/share.js#L79-L121
10,388
jsbin/jsbin
public/js/vendor/codemirror3/mode/haml/haml.js
function() { var htmlState = htmlMode.startState(); var rubyState = rubyMode.startState(); return { htmlState: htmlState, rubyState: rubyState, indented: 0, previousToken: { style: null, indented: 0}, tokenize: html }; }
javascript
function() { var htmlState = htmlMode.startState(); var rubyState = rubyMode.startState(); return { htmlState: htmlState, rubyState: rubyState, indented: 0, previousToken: { style: null, indented: 0}, tokenize: html }; }
[ "function", "(", ")", "{", "var", "htmlState", "=", "htmlMode", ".", "startState", "(", ")", ";", "var", "rubyState", "=", "rubyMode", ".", "startState", "(", ")", ";", "return", "{", "htmlState", ":", "htmlState", ",", "rubyState", ":", "rubyState", ",", "indented", ":", "0", ",", "previousToken", ":", "{", "style", ":", "null", ",", "indented", ":", "0", "}", ",", "tokenize", ":", "html", "}", ";", "}" ]
default to html mode
[ "default", "to", "html", "mode" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/codemirror3/mode/haml/haml.js#L88-L98
10,389
jsbin/jsbin
public/js/vendor/codemirror3/mode/htmlembedded/htmlembedded.js
htmlDispatch
function htmlDispatch(stream, state) { if (stream.match(scriptStartRegex, false)) { state.token=scriptingDispatch; return scriptingMode.token(stream, state.scriptState); } else return htmlMixedMode.token(stream, state.htmlState); }
javascript
function htmlDispatch(stream, state) { if (stream.match(scriptStartRegex, false)) { state.token=scriptingDispatch; return scriptingMode.token(stream, state.scriptState); } else return htmlMixedMode.token(stream, state.htmlState); }
[ "function", "htmlDispatch", "(", "stream", ",", "state", ")", "{", "if", "(", "stream", ".", "match", "(", "scriptStartRegex", ",", "false", ")", ")", "{", "state", ".", "token", "=", "scriptingDispatch", ";", "return", "scriptingMode", ".", "token", "(", "stream", ",", "state", ".", "scriptState", ")", ";", "}", "else", "return", "htmlMixedMode", ".", "token", "(", "stream", ",", "state", ".", "htmlState", ")", ";", "}" ]
tokenizer when in html mode
[ "tokenizer", "when", "in", "html", "mode" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/codemirror3/mode/htmlembedded/htmlembedded.js#L11-L18
10,390
jsbin/jsbin
public/js/vendor/codemirror3/keymap/vim.js
function(cm, key) { var command; var vim = maybeInitVimState(cm); var macroModeState = vimGlobalState.macroModeState; if (macroModeState.enteredMacroMode) { if (key == 'q') { actions.exitMacroRecordMode(); vim.inputState = new InputState(); return; } } if (key == '<Esc>') { // Clear input state and get back to normal mode. vim.inputState = new InputState(); if (vim.visualMode) { exitVisualMode(cm); } return; } // Enter visual mode when the mouse selects text. if (!vim.visualMode && !cursorEqual(cm.getCursor('head'), cm.getCursor('anchor'))) { vim.visualMode = true; vim.visualLine = false; CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"}); cm.on('mousedown', exitVisualMode); } if (key != '0' || (key == '0' && vim.inputState.getRepeat() === 0)) { // Have to special case 0 since it's both a motion and a number. command = commandDispatcher.matchCommand(key, defaultKeymap, vim); } if (!command) { if (isNumber(key)) { // Increment count unless count is 0 and key is 0. vim.inputState.pushRepeatDigit(key); } return; } if (command.type == 'keyToKey') { // TODO: prevent infinite recursion. for (var i = 0; i < command.toKeys.length; i++) { this.handleKey(cm, command.toKeys[i]); } } else { if (macroModeState.enteredMacroMode) { logKey(macroModeState, key); } commandDispatcher.processCommand(cm, vim, command); } }
javascript
function(cm, key) { var command; var vim = maybeInitVimState(cm); var macroModeState = vimGlobalState.macroModeState; if (macroModeState.enteredMacroMode) { if (key == 'q') { actions.exitMacroRecordMode(); vim.inputState = new InputState(); return; } } if (key == '<Esc>') { // Clear input state and get back to normal mode. vim.inputState = new InputState(); if (vim.visualMode) { exitVisualMode(cm); } return; } // Enter visual mode when the mouse selects text. if (!vim.visualMode && !cursorEqual(cm.getCursor('head'), cm.getCursor('anchor'))) { vim.visualMode = true; vim.visualLine = false; CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"}); cm.on('mousedown', exitVisualMode); } if (key != '0' || (key == '0' && vim.inputState.getRepeat() === 0)) { // Have to special case 0 since it's both a motion and a number. command = commandDispatcher.matchCommand(key, defaultKeymap, vim); } if (!command) { if (isNumber(key)) { // Increment count unless count is 0 and key is 0. vim.inputState.pushRepeatDigit(key); } return; } if (command.type == 'keyToKey') { // TODO: prevent infinite recursion. for (var i = 0; i < command.toKeys.length; i++) { this.handleKey(cm, command.toKeys[i]); } } else { if (macroModeState.enteredMacroMode) { logKey(macroModeState, key); } commandDispatcher.processCommand(cm, vim, command); } }
[ "function", "(", "cm", ",", "key", ")", "{", "var", "command", ";", "var", "vim", "=", "maybeInitVimState", "(", "cm", ")", ";", "var", "macroModeState", "=", "vimGlobalState", ".", "macroModeState", ";", "if", "(", "macroModeState", ".", "enteredMacroMode", ")", "{", "if", "(", "key", "==", "'q'", ")", "{", "actions", ".", "exitMacroRecordMode", "(", ")", ";", "vim", ".", "inputState", "=", "new", "InputState", "(", ")", ";", "return", ";", "}", "}", "if", "(", "key", "==", "'<Esc>'", ")", "{", "// Clear input state and get back to normal mode.", "vim", ".", "inputState", "=", "new", "InputState", "(", ")", ";", "if", "(", "vim", ".", "visualMode", ")", "{", "exitVisualMode", "(", "cm", ")", ";", "}", "return", ";", "}", "// Enter visual mode when the mouse selects text.", "if", "(", "!", "vim", ".", "visualMode", "&&", "!", "cursorEqual", "(", "cm", ".", "getCursor", "(", "'head'", ")", ",", "cm", ".", "getCursor", "(", "'anchor'", ")", ")", ")", "{", "vim", ".", "visualMode", "=", "true", ";", "vim", ".", "visualLine", "=", "false", ";", "CodeMirror", ".", "signal", "(", "cm", ",", "\"vim-mode-change\"", ",", "{", "mode", ":", "\"visual\"", "}", ")", ";", "cm", ".", "on", "(", "'mousedown'", ",", "exitVisualMode", ")", ";", "}", "if", "(", "key", "!=", "'0'", "||", "(", "key", "==", "'0'", "&&", "vim", ".", "inputState", ".", "getRepeat", "(", ")", "===", "0", ")", ")", "{", "// Have to special case 0 since it's both a motion and a number.", "command", "=", "commandDispatcher", ".", "matchCommand", "(", "key", ",", "defaultKeymap", ",", "vim", ")", ";", "}", "if", "(", "!", "command", ")", "{", "if", "(", "isNumber", "(", "key", ")", ")", "{", "// Increment count unless count is 0 and key is 0.", "vim", ".", "inputState", ".", "pushRepeatDigit", "(", "key", ")", ";", "}", "return", ";", "}", "if", "(", "command", ".", "type", "==", "'keyToKey'", ")", "{", "// TODO: prevent infinite recursion.", "for", "(", "var", "i", "=", "0", ";", "i", "<", "command", ".", "toKeys", ".", "length", ";", "i", "++", ")", "{", "this", ".", "handleKey", "(", "cm", ",", "command", ".", "toKeys", "[", "i", "]", ")", ";", "}", "}", "else", "{", "if", "(", "macroModeState", ".", "enteredMacroMode", ")", "{", "logKey", "(", "macroModeState", ",", "key", ")", ";", "}", "commandDispatcher", ".", "processCommand", "(", "cm", ",", "vim", ",", "command", ")", ";", "}", "}" ]
This is the outermost function called by CodeMirror, after keys have been mapped to their Vim equivalents.
[ "This", "is", "the", "outermost", "function", "called", "by", "CodeMirror", "after", "keys", "have", "been", "mapped", "to", "their", "Vim", "equivalents", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/codemirror3/keymap/vim.js#L588-L637
10,391
jsbin/jsbin
public/js/vendor/codemirror3/keymap/vim.js
InputState
function InputState() { this.prefixRepeat = []; this.motionRepeat = []; this.operator = null; this.operatorArgs = null; this.motion = null; this.motionArgs = null; this.keyBuffer = []; // For matching multi-key commands. this.registerName = null; // Defaults to the unamed register. }
javascript
function InputState() { this.prefixRepeat = []; this.motionRepeat = []; this.operator = null; this.operatorArgs = null; this.motion = null; this.motionArgs = null; this.keyBuffer = []; // For matching multi-key commands. this.registerName = null; // Defaults to the unamed register. }
[ "function", "InputState", "(", ")", "{", "this", ".", "prefixRepeat", "=", "[", "]", ";", "this", ".", "motionRepeat", "=", "[", "]", ";", "this", ".", "operator", "=", "null", ";", "this", ".", "operatorArgs", "=", "null", ";", "this", ".", "motion", "=", "null", ";", "this", ".", "motionArgs", "=", "null", ";", "this", ".", "keyBuffer", "=", "[", "]", ";", "// For matching multi-key commands.", "this", ".", "registerName", "=", "null", ";", "// Defaults to the unamed register.", "}" ]
Represents the current input state.
[ "Represents", "the", "current", "input", "state", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/codemirror3/keymap/vim.js#L644-L654
10,392
jsbin/jsbin
public/js/vendor/codemirror3/keymap/vim.js
function(name) { if (!this.isValidRegister(name)) { return this.unamedRegister; } name = name.toLowerCase(); if (!this.registers[name]) { this.registers[name] = new Register(); } return this.registers[name]; }
javascript
function(name) { if (!this.isValidRegister(name)) { return this.unamedRegister; } name = name.toLowerCase(); if (!this.registers[name]) { this.registers[name] = new Register(); } return this.registers[name]; }
[ "function", "(", "name", ")", "{", "if", "(", "!", "this", ".", "isValidRegister", "(", "name", ")", ")", "{", "return", "this", ".", "unamedRegister", ";", "}", "name", "=", "name", ".", "toLowerCase", "(", ")", ";", "if", "(", "!", "this", ".", "registers", "[", "name", "]", ")", "{", "this", ".", "registers", "[", "name", "]", "=", "new", "Register", "(", ")", ";", "}", "return", "this", ".", "registers", "[", "name", "]", ";", "}" ]
Gets the register named @name. If one of @name doesn't already exist, create it. If @name is invalid, return the unamedRegister.
[ "Gets", "the", "register", "named" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/codemirror3/keymap/vim.js#L776-L785
10,393
jsbin/jsbin
public/js/vendor/codemirror3/keymap/vim.js
getFullyMatchedCommandOrNull
function getFullyMatchedCommandOrNull(command) { if (keys.length < command.keys.length) { // Matches part of a multi-key command. Buffer and wait for next // stroke. inputState.keyBuffer.push(key); return null; } else { if (command.keys[keys.length - 1] == 'character') { inputState.selectedCharacter = selectedCharacter; } // Clear the buffer since a full match was found. inputState.keyBuffer = []; return command; } }
javascript
function getFullyMatchedCommandOrNull(command) { if (keys.length < command.keys.length) { // Matches part of a multi-key command. Buffer and wait for next // stroke. inputState.keyBuffer.push(key); return null; } else { if (command.keys[keys.length - 1] == 'character') { inputState.selectedCharacter = selectedCharacter; } // Clear the buffer since a full match was found. inputState.keyBuffer = []; return command; } }
[ "function", "getFullyMatchedCommandOrNull", "(", "command", ")", "{", "if", "(", "keys", ".", "length", "<", "command", ".", "keys", ".", "length", ")", "{", "// Matches part of a multi-key command. Buffer and wait for next", "// stroke.", "inputState", ".", "keyBuffer", ".", "push", "(", "key", ")", ";", "return", "null", ";", "}", "else", "{", "if", "(", "command", ".", "keys", "[", "keys", ".", "length", "-", "1", "]", "==", "'character'", ")", "{", "inputState", ".", "selectedCharacter", "=", "selectedCharacter", ";", "}", "// Clear the buffer since a full match was found.", "inputState", ".", "keyBuffer", "=", "[", "]", ";", "return", "command", ";", "}", "}" ]
Returns the command if it is a full match, or null if not.
[ "Returns", "the", "command", "if", "it", "is", "a", "full", "match", "or", "null", "if", "not", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/codemirror3/keymap/vim.js#L834-L848
10,394
jsbin/jsbin
public/js/vendor/codemirror3/keymap/vim.js
function(cm, operatorArgs, _vim, curStart, curEnd) { // If the ending line is past the last line, inclusive, instead of // including the trailing \n, include the \n before the starting line if (operatorArgs.linewise && curEnd.line > cm.lastLine() && curStart.line > cm.firstLine()) { curStart.line--; curStart.ch = lineLength(cm, curStart.line); } vimGlobalState.registerController.pushText( operatorArgs.registerName, 'delete', cm.getRange(curStart, curEnd), operatorArgs.linewise); cm.replaceRange('', curStart, curEnd); if (operatorArgs.linewise) { cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm)); } else { cm.setCursor(curStart); } }
javascript
function(cm, operatorArgs, _vim, curStart, curEnd) { // If the ending line is past the last line, inclusive, instead of // including the trailing \n, include the \n before the starting line if (operatorArgs.linewise && curEnd.line > cm.lastLine() && curStart.line > cm.firstLine()) { curStart.line--; curStart.ch = lineLength(cm, curStart.line); } vimGlobalState.registerController.pushText( operatorArgs.registerName, 'delete', cm.getRange(curStart, curEnd), operatorArgs.linewise); cm.replaceRange('', curStart, curEnd); if (operatorArgs.linewise) { cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm)); } else { cm.setCursor(curStart); } }
[ "function", "(", "cm", ",", "operatorArgs", ",", "_vim", ",", "curStart", ",", "curEnd", ")", "{", "// If the ending line is past the last line, inclusive, instead of", "// including the trailing \\n, include the \\n before the starting line", "if", "(", "operatorArgs", ".", "linewise", "&&", "curEnd", ".", "line", ">", "cm", ".", "lastLine", "(", ")", "&&", "curStart", ".", "line", ">", "cm", ".", "firstLine", "(", ")", ")", "{", "curStart", ".", "line", "--", ";", "curStart", ".", "ch", "=", "lineLength", "(", "cm", ",", "curStart", ".", "line", ")", ";", "}", "vimGlobalState", ".", "registerController", ".", "pushText", "(", "operatorArgs", ".", "registerName", ",", "'delete'", ",", "cm", ".", "getRange", "(", "curStart", ",", "curEnd", ")", ",", "operatorArgs", ".", "linewise", ")", ";", "cm", ".", "replaceRange", "(", "''", ",", "curStart", ",", "curEnd", ")", ";", "if", "(", "operatorArgs", ".", "linewise", ")", "{", "cm", ".", "setCursor", "(", "motions", ".", "moveToFirstNonWhiteSpaceCharacter", "(", "cm", ")", ")", ";", "}", "else", "{", "cm", ".", "setCursor", "(", "curStart", ")", ";", "}", "}" ]
delete is a javascript keyword.
[ "delete", "is", "a", "javascript", "keyword", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/codemirror3/keymap/vim.js#L1595-L1612
10,395
jsbin/jsbin
public/js/vendor/codemirror3/keymap/vim.js
isInRange
function isInRange(pos, start, end) { if (typeof pos != 'number') { // Assume it is a cursor position. Get the line number. pos = pos.line; } if (start instanceof Array) { return inArray(pos, start); } else { if (end) { return (pos >= start && pos <= end); } else { return pos == start; } } }
javascript
function isInRange(pos, start, end) { if (typeof pos != 'number') { // Assume it is a cursor position. Get the line number. pos = pos.line; } if (start instanceof Array) { return inArray(pos, start); } else { if (end) { return (pos >= start && pos <= end); } else { return pos == start; } } }
[ "function", "isInRange", "(", "pos", ",", "start", ",", "end", ")", "{", "if", "(", "typeof", "pos", "!=", "'number'", ")", "{", "// Assume it is a cursor position. Get the line number.", "pos", "=", "pos", ".", "line", ";", "}", "if", "(", "start", "instanceof", "Array", ")", "{", "return", "inArray", "(", "pos", ",", "start", ")", ";", "}", "else", "{", "if", "(", "end", ")", "{", "return", "(", "pos", ">=", "start", "&&", "pos", "<=", "end", ")", ";", "}", "else", "{", "return", "pos", "==", "start", ";", "}", "}", "}" ]
Check if pos is in the specified range, INCLUSIVE. Range can be specified with 1 or 2 arguments. If the first range argument is an array, treat it as an array of line numbers. Match pos against any of the lines. If the first range argument is a number, if there is only 1 range argument, check if pos has the same line number if there are 2 range arguments, then check if pos is in between the two range arguments.
[ "Check", "if", "pos", "is", "in", "the", "specified", "range", "INCLUSIVE", ".", "Range", "can", "be", "specified", "with", "1", "or", "2", "arguments", ".", "If", "the", "first", "range", "argument", "is", "an", "array", "treat", "it", "as", "an", "array", "of", "line", "numbers", ".", "Match", "pos", "against", "any", "of", "the", "lines", ".", "If", "the", "first", "range", "argument", "is", "a", "number", "if", "there", "is", "only", "1", "range", "argument", "check", "if", "pos", "has", "the", "same", "line", "number", "if", "there", "are", "2", "range", "arguments", "then", "check", "if", "pos", "is", "in", "between", "the", "two", "range", "arguments", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/codemirror3/keymap/vim.js#L2936-L2950
10,396
jsbin/jsbin
public/js/vendor/codemirror3/keymap/vim.js
buildVimKeyMap
function buildVimKeyMap() { /** * Handle the raw key event from CodeMirror. Translate the * Shift + key modifier to the resulting letter, while preserving other * modifers. */ // TODO: Figure out a way to catch capslock. function cmKeyToVimKey(key, modifier) { var vimKey = key; if (isUpperCase(vimKey)) { // Convert to lower case if shift is not the modifier since the key // we get from CodeMirror is always upper case. if (modifier == 'Shift') { modifier = null; } else { vimKey = vimKey.toLowerCase(); } } if (modifier) { // Vim will parse modifier+key combination as a single key. vimKey = modifier.charAt(0) + '-' + vimKey; } var specialKey = ({Enter:'CR',Backspace:'BS',Delete:'Del'})[vimKey]; vimKey = specialKey ? specialKey : vimKey; vimKey = vimKey.length > 1 ? '<'+ vimKey + '>' : vimKey; return vimKey; } // Closure to bind CodeMirror, key, modifier. function keyMapper(vimKey) { return function(cm) { CodeMirror.Vim.handleKey(cm, vimKey); }; } var cmToVimKeymap = { 'nofallthrough': true, 'style': 'fat-cursor' }; function bindKeys(keys, modifier) { for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (!modifier && inArray(key, specialSymbols)) { // Wrap special symbols with '' because that's how CodeMirror binds // them. key = "'" + key + "'"; } var vimKey = cmKeyToVimKey(keys[i], modifier); var cmKey = modifier ? modifier + '-' + key : key; cmToVimKeymap[cmKey] = keyMapper(vimKey); } } bindKeys(upperCaseAlphabet); bindKeys(upperCaseAlphabet, 'Shift'); bindKeys(upperCaseAlphabet, 'Ctrl'); bindKeys(specialSymbols); bindKeys(specialSymbols, 'Ctrl'); bindKeys(numbers); bindKeys(numbers, 'Ctrl'); bindKeys(specialKeys); bindKeys(specialKeys, 'Ctrl'); return cmToVimKeymap; }
javascript
function buildVimKeyMap() { /** * Handle the raw key event from CodeMirror. Translate the * Shift + key modifier to the resulting letter, while preserving other * modifers. */ // TODO: Figure out a way to catch capslock. function cmKeyToVimKey(key, modifier) { var vimKey = key; if (isUpperCase(vimKey)) { // Convert to lower case if shift is not the modifier since the key // we get from CodeMirror is always upper case. if (modifier == 'Shift') { modifier = null; } else { vimKey = vimKey.toLowerCase(); } } if (modifier) { // Vim will parse modifier+key combination as a single key. vimKey = modifier.charAt(0) + '-' + vimKey; } var specialKey = ({Enter:'CR',Backspace:'BS',Delete:'Del'})[vimKey]; vimKey = specialKey ? specialKey : vimKey; vimKey = vimKey.length > 1 ? '<'+ vimKey + '>' : vimKey; return vimKey; } // Closure to bind CodeMirror, key, modifier. function keyMapper(vimKey) { return function(cm) { CodeMirror.Vim.handleKey(cm, vimKey); }; } var cmToVimKeymap = { 'nofallthrough': true, 'style': 'fat-cursor' }; function bindKeys(keys, modifier) { for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (!modifier && inArray(key, specialSymbols)) { // Wrap special symbols with '' because that's how CodeMirror binds // them. key = "'" + key + "'"; } var vimKey = cmKeyToVimKey(keys[i], modifier); var cmKey = modifier ? modifier + '-' + key : key; cmToVimKeymap[cmKey] = keyMapper(vimKey); } } bindKeys(upperCaseAlphabet); bindKeys(upperCaseAlphabet, 'Shift'); bindKeys(upperCaseAlphabet, 'Ctrl'); bindKeys(specialSymbols); bindKeys(specialSymbols, 'Ctrl'); bindKeys(numbers); bindKeys(numbers, 'Ctrl'); bindKeys(specialKeys); bindKeys(specialKeys, 'Ctrl'); return cmToVimKeymap; }
[ "function", "buildVimKeyMap", "(", ")", "{", "/**\n * Handle the raw key event from CodeMirror. Translate the\n * Shift + key modifier to the resulting letter, while preserving other\n * modifers.\n */", "// TODO: Figure out a way to catch capslock.", "function", "cmKeyToVimKey", "(", "key", ",", "modifier", ")", "{", "var", "vimKey", "=", "key", ";", "if", "(", "isUpperCase", "(", "vimKey", ")", ")", "{", "// Convert to lower case if shift is not the modifier since the key", "// we get from CodeMirror is always upper case.", "if", "(", "modifier", "==", "'Shift'", ")", "{", "modifier", "=", "null", ";", "}", "else", "{", "vimKey", "=", "vimKey", ".", "toLowerCase", "(", ")", ";", "}", "}", "if", "(", "modifier", ")", "{", "// Vim will parse modifier+key combination as a single key.", "vimKey", "=", "modifier", ".", "charAt", "(", "0", ")", "+", "'-'", "+", "vimKey", ";", "}", "var", "specialKey", "=", "(", "{", "Enter", ":", "'CR'", ",", "Backspace", ":", "'BS'", ",", "Delete", ":", "'Del'", "}", ")", "[", "vimKey", "]", ";", "vimKey", "=", "specialKey", "?", "specialKey", ":", "vimKey", ";", "vimKey", "=", "vimKey", ".", "length", ">", "1", "?", "'<'", "+", "vimKey", "+", "'>'", ":", "vimKey", ";", "return", "vimKey", ";", "}", "// Closure to bind CodeMirror, key, modifier.", "function", "keyMapper", "(", "vimKey", ")", "{", "return", "function", "(", "cm", ")", "{", "CodeMirror", ".", "Vim", ".", "handleKey", "(", "cm", ",", "vimKey", ")", ";", "}", ";", "}", "var", "cmToVimKeymap", "=", "{", "'nofallthrough'", ":", "true", ",", "'style'", ":", "'fat-cursor'", "}", ";", "function", "bindKeys", "(", "keys", ",", "modifier", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "var", "key", "=", "keys", "[", "i", "]", ";", "if", "(", "!", "modifier", "&&", "inArray", "(", "key", ",", "specialSymbols", ")", ")", "{", "// Wrap special symbols with '' because that's how CodeMirror binds", "// them.", "key", "=", "\"'\"", "+", "key", "+", "\"'\"", ";", "}", "var", "vimKey", "=", "cmKeyToVimKey", "(", "keys", "[", "i", "]", ",", "modifier", ")", ";", "var", "cmKey", "=", "modifier", "?", "modifier", "+", "'-'", "+", "key", ":", "key", ";", "cmToVimKeymap", "[", "cmKey", "]", "=", "keyMapper", "(", "vimKey", ")", ";", "}", "}", "bindKeys", "(", "upperCaseAlphabet", ")", ";", "bindKeys", "(", "upperCaseAlphabet", ",", "'Shift'", ")", ";", "bindKeys", "(", "upperCaseAlphabet", ",", "'Ctrl'", ")", ";", "bindKeys", "(", "specialSymbols", ")", ";", "bindKeys", "(", "specialSymbols", ",", "'Ctrl'", ")", ";", "bindKeys", "(", "numbers", ")", ";", "bindKeys", "(", "numbers", ",", "'Ctrl'", ")", ";", "bindKeys", "(", "specialKeys", ")", ";", "bindKeys", "(", "specialKeys", ",", "'Ctrl'", ")", ";", "return", "cmToVimKeymap", ";", "}" ]
Register Vim with CodeMirror
[ "Register", "Vim", "with", "CodeMirror" ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/codemirror3/keymap/vim.js#L3492-L3555
10,397
jsbin/jsbin
public/js/vendor/codemirror3/keymap/vim.js
onChange
function onChange(_cm, changeObj) { var macroModeState = vimGlobalState.macroModeState; var lastChange = macroModeState.lastInsertModeChanges; while (changeObj) { lastChange.expectCursorActivityForChange = true; if (changeObj.origin == '+input' || changeObj.origin == 'paste' || changeObj.origin === undefined /* only in testing */) { var text = changeObj.text.join('\n'); lastChange.changes.push(text); } // Change objects may be chained with next. changeObj = changeObj.next; } }
javascript
function onChange(_cm, changeObj) { var macroModeState = vimGlobalState.macroModeState; var lastChange = macroModeState.lastInsertModeChanges; while (changeObj) { lastChange.expectCursorActivityForChange = true; if (changeObj.origin == '+input' || changeObj.origin == 'paste' || changeObj.origin === undefined /* only in testing */) { var text = changeObj.text.join('\n'); lastChange.changes.push(text); } // Change objects may be chained with next. changeObj = changeObj.next; } }
[ "function", "onChange", "(", "_cm", ",", "changeObj", ")", "{", "var", "macroModeState", "=", "vimGlobalState", ".", "macroModeState", ";", "var", "lastChange", "=", "macroModeState", ".", "lastInsertModeChanges", ";", "while", "(", "changeObj", ")", "{", "lastChange", ".", "expectCursorActivityForChange", "=", "true", ";", "if", "(", "changeObj", ".", "origin", "==", "'+input'", "||", "changeObj", ".", "origin", "==", "'paste'", "||", "changeObj", ".", "origin", "===", "undefined", "/* only in testing */", ")", "{", "var", "text", "=", "changeObj", ".", "text", ".", "join", "(", "'\\n'", ")", ";", "lastChange", ".", "changes", ".", "push", "(", "text", ")", ";", "}", "// Change objects may be chained with next.", "changeObj", "=", "changeObj", ".", "next", ";", "}", "}" ]
Listens for changes made in insert mode. Should only be active in insert mode.
[ "Listens", "for", "changes", "made", "in", "insert", "mode", ".", "Should", "only", "be", "active", "in", "insert", "mode", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/codemirror3/keymap/vim.js#L3647-L3660
10,398
jsbin/jsbin
public/js/vendor/codemirror3/keymap/vim.js
onCursorActivity
function onCursorActivity() { var macroModeState = vimGlobalState.macroModeState; var lastChange = macroModeState.lastInsertModeChanges; if (lastChange.expectCursorActivityForChange) { lastChange.expectCursorActivityForChange = false; } else { // Cursor moved outside the context of an edit. Reset the change. lastChange.changes = []; } }
javascript
function onCursorActivity() { var macroModeState = vimGlobalState.macroModeState; var lastChange = macroModeState.lastInsertModeChanges; if (lastChange.expectCursorActivityForChange) { lastChange.expectCursorActivityForChange = false; } else { // Cursor moved outside the context of an edit. Reset the change. lastChange.changes = []; } }
[ "function", "onCursorActivity", "(", ")", "{", "var", "macroModeState", "=", "vimGlobalState", ".", "macroModeState", ";", "var", "lastChange", "=", "macroModeState", ".", "lastInsertModeChanges", ";", "if", "(", "lastChange", ".", "expectCursorActivityForChange", ")", "{", "lastChange", ".", "expectCursorActivityForChange", "=", "false", ";", "}", "else", "{", "// Cursor moved outside the context of an edit. Reset the change.", "lastChange", ".", "changes", "=", "[", "]", ";", "}", "}" ]
Listens for any kind of cursor activity on CodeMirror. - For tracking cursor activity in insert mode. - Should only be active in insert mode.
[ "Listens", "for", "any", "kind", "of", "cursor", "activity", "on", "CodeMirror", ".", "-", "For", "tracking", "cursor", "activity", "in", "insert", "mode", ".", "-", "Should", "only", "be", "active", "in", "insert", "mode", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/codemirror3/keymap/vim.js#L3667-L3676
10,399
jsbin/jsbin
public/js/vendor/codemirror3/keymap/vim.js
onKeyEventTargetKeyDown
function onKeyEventTargetKeyDown(e) { var macroModeState = vimGlobalState.macroModeState; var lastChange = macroModeState.lastInsertModeChanges; var keyName = CodeMirror.keyName(e); function onKeyFound() { lastChange.changes.push(new InsertModeKey(keyName)); return true; } if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) { CodeMirror.lookupKey(keyName, ['vim-insert'], onKeyFound); } }
javascript
function onKeyEventTargetKeyDown(e) { var macroModeState = vimGlobalState.macroModeState; var lastChange = macroModeState.lastInsertModeChanges; var keyName = CodeMirror.keyName(e); function onKeyFound() { lastChange.changes.push(new InsertModeKey(keyName)); return true; } if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) { CodeMirror.lookupKey(keyName, ['vim-insert'], onKeyFound); } }
[ "function", "onKeyEventTargetKeyDown", "(", "e", ")", "{", "var", "macroModeState", "=", "vimGlobalState", ".", "macroModeState", ";", "var", "lastChange", "=", "macroModeState", ".", "lastInsertModeChanges", ";", "var", "keyName", "=", "CodeMirror", ".", "keyName", "(", "e", ")", ";", "function", "onKeyFound", "(", ")", "{", "lastChange", ".", "changes", ".", "push", "(", "new", "InsertModeKey", "(", "keyName", ")", ")", ";", "return", "true", ";", "}", "if", "(", "keyName", ".", "indexOf", "(", "'Delete'", ")", "!=", "-", "1", "||", "keyName", ".", "indexOf", "(", "'Backspace'", ")", "!=", "-", "1", ")", "{", "CodeMirror", ".", "lookupKey", "(", "keyName", ",", "[", "'vim-insert'", "]", ",", "onKeyFound", ")", ";", "}", "}" ]
Handles raw key down events from the text area. - Should only be active in insert mode. - For recording deletes in insert mode.
[ "Handles", "raw", "key", "down", "events", "from", "the", "text", "area", ".", "-", "Should", "only", "be", "active", "in", "insert", "mode", ".", "-", "For", "recording", "deletes", "in", "insert", "mode", "." ]
d962c36fff71104acad98ac07629c1331704d420
https://github.com/jsbin/jsbin/blob/d962c36fff71104acad98ac07629c1331704d420/public/js/vendor/codemirror3/keymap/vim.js#L3688-L3699