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
12,000
Microsoft/fast-dna
build/clean.js
cleanPath
function cleanPath(cleanPath) { const removePath = path.resolve(process.cwd(), cleanPath) rimraf(removePath, () => { console.log(removePath, "cleaned"); }); }
javascript
function cleanPath(cleanPath) { const removePath = path.resolve(process.cwd(), cleanPath) rimraf(removePath, () => { console.log(removePath, "cleaned"); }); }
[ "function", "cleanPath", "(", "cleanPath", ")", "{", "const", "removePath", "=", "path", ".", "resolve", "(", "process", ".", "cwd", "(", ")", ",", "cleanPath", ")", "rimraf", "(", "removePath", ",", "(", ")", "=>", "{", "console", ".", "log", "(", "removePath", ",", "\"cleaned\"", ")", ";", "}", ")", ";", "}" ]
Function to remove a given path
[ "Function", "to", "remove", "a", "given", "path" ]
807a3ad3252ef8685da95e57490f5015287b0566
https://github.com/Microsoft/fast-dna/blob/807a3ad3252ef8685da95e57490f5015287b0566/build/clean.js#L17-L22
12,001
Microsoft/fast-dna
build/copy-schemas.js
copySchemaFiles
function copySchemaFiles() { const resolvedSrcSchemaPaths = path.resolve(rootDir, srcSchemaPaths); glob(resolvedSrcSchemaPaths, void(0), function(error, files) { files.forEach((filePath) => { const destSchemaPath = filePath.replace(/(\bsrc\b)(?!.*\1)/, destDir); fs.copyFileSync(filePath, destSchemaPath); }); }); }
javascript
function copySchemaFiles() { const resolvedSrcSchemaPaths = path.resolve(rootDir, srcSchemaPaths); glob(resolvedSrcSchemaPaths, void(0), function(error, files) { files.forEach((filePath) => { const destSchemaPath = filePath.replace(/(\bsrc\b)(?!.*\1)/, destDir); fs.copyFileSync(filePath, destSchemaPath); }); }); }
[ "function", "copySchemaFiles", "(", ")", "{", "const", "resolvedSrcSchemaPaths", "=", "path", ".", "resolve", "(", "rootDir", ",", "srcSchemaPaths", ")", ";", "glob", "(", "resolvedSrcSchemaPaths", ",", "void", "(", "0", ")", ",", "function", "(", "error", ",", "files", ")", "{", "files", ".", "forEach", "(", "(", "filePath", ")", "=>", "{", "const", "destSchemaPath", "=", "filePath", ".", "replace", "(", "/", "(\\bsrc\\b)(?!.*\\1)", "/", ",", "destDir", ")", ";", "fs", ".", "copyFileSync", "(", "filePath", ",", "destSchemaPath", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Function to copy schema files to their dist folder
[ "Function", "to", "copy", "schema", "files", "to", "their", "dist", "folder" ]
807a3ad3252ef8685da95e57490f5015287b0566
https://github.com/Microsoft/fast-dna/blob/807a3ad3252ef8685da95e57490f5015287b0566/build/copy-schemas.js#L16-L25
12,002
weareoutman/clockpicker
gulpfile.js
js
function js(prefix) { gulp.src('src/clockpicker.js') .pipe(rename({ prefix: prefix + '-' })) .pipe(replace(versionRegExp, version)) .pipe(gulp.dest('dist')) .pipe(uglify({ preserveComments: 'some' })) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('dist')); }
javascript
function js(prefix) { gulp.src('src/clockpicker.js') .pipe(rename({ prefix: prefix + '-' })) .pipe(replace(versionRegExp, version)) .pipe(gulp.dest('dist')) .pipe(uglify({ preserveComments: 'some' })) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('dist')); }
[ "function", "js", "(", "prefix", ")", "{", "gulp", ".", "src", "(", "'src/clockpicker.js'", ")", ".", "pipe", "(", "rename", "(", "{", "prefix", ":", "prefix", "+", "'-'", "}", ")", ")", ".", "pipe", "(", "replace", "(", "versionRegExp", ",", "version", ")", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "'dist'", ")", ")", ".", "pipe", "(", "uglify", "(", "{", "preserveComments", ":", "'some'", "}", ")", ")", ".", "pipe", "(", "rename", "(", "{", "suffix", ":", "'.min'", "}", ")", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "'dist'", ")", ")", ";", "}" ]
Rename and uglify scripts
[ "Rename", "and", "uglify", "scripts" ]
e6ac014b3c167281ac37cf122ab19b6967d8fae4
https://github.com/weareoutman/clockpicker/blob/e6ac014b3c167281ac37cf122ab19b6967d8fae4/gulpfile.js#L13-L27
12,003
weareoutman/clockpicker
gulpfile.js
css
function css(prefix) { var stream; if (prefix === 'bootstrap') { stream = gulp.src('src/clockpicker.css'); } else { // Concat with some styles picked from bootstrap stream = gulp.src(['src/standalone.css', 'src/clockpicker.css']) .pipe(concat('clockpicker.css')); } stream.pipe(rename({ prefix: prefix + '-' })) .pipe(replace(versionRegExp, version)) .pipe(gulp.dest('dist')) .pipe(minifyCSS({ keepSpecialComments: 1 })) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('dist')); }
javascript
function css(prefix) { var stream; if (prefix === 'bootstrap') { stream = gulp.src('src/clockpicker.css'); } else { // Concat with some styles picked from bootstrap stream = gulp.src(['src/standalone.css', 'src/clockpicker.css']) .pipe(concat('clockpicker.css')); } stream.pipe(rename({ prefix: prefix + '-' })) .pipe(replace(versionRegExp, version)) .pipe(gulp.dest('dist')) .pipe(minifyCSS({ keepSpecialComments: 1 })) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('dist')); }
[ "function", "css", "(", "prefix", ")", "{", "var", "stream", ";", "if", "(", "prefix", "===", "'bootstrap'", ")", "{", "stream", "=", "gulp", ".", "src", "(", "'src/clockpicker.css'", ")", ";", "}", "else", "{", "// Concat with some styles picked from bootstrap", "stream", "=", "gulp", ".", "src", "(", "[", "'src/standalone.css'", ",", "'src/clockpicker.css'", "]", ")", ".", "pipe", "(", "concat", "(", "'clockpicker.css'", ")", ")", ";", "}", "stream", ".", "pipe", "(", "rename", "(", "{", "prefix", ":", "prefix", "+", "'-'", "}", ")", ")", ".", "pipe", "(", "replace", "(", "versionRegExp", ",", "version", ")", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "'dist'", ")", ")", ".", "pipe", "(", "minifyCSS", "(", "{", "keepSpecialComments", ":", "1", "}", ")", ")", ".", "pipe", "(", "rename", "(", "{", "suffix", ":", "'.min'", "}", ")", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "'dist'", ")", ")", ";", "}" ]
Rename, concat and minify stylesheets
[ "Rename", "concat", "and", "minify", "stylesheets" ]
e6ac014b3c167281ac37cf122ab19b6967d8fae4
https://github.com/weareoutman/clockpicker/blob/e6ac014b3c167281ac37cf122ab19b6967d8fae4/gulpfile.js#L30-L51
12,004
tangrams/tangram
src/leaflet_layer.js
function (layer, targetCenter, targetZoom) { map._stop(); var startZoom = map._zoom; targetCenter = L.latLng(targetCenter); targetZoom = targetZoom === undefined ? startZoom : targetZoom; targetZoom = Math.min(targetZoom, map.getMaxZoom()); // don't go past max zoom var start = Date.now(), duration = 75; function frame() { var t = (Date.now() - start) / duration; if (t <= 1) { // reuse internal flyTo frame to ensure these animations are canceled like others map._flyToFrame = L.Util.requestAnimFrame(frame, map); setZoomAroundNoMoveEnd(layer, targetCenter, startZoom + (targetZoom - startZoom) * t); } else { setZoomAroundNoMoveEnd(layer, targetCenter, targetZoom) ._moveEnd(true); } } map._moveStart(true); frame.call(map); return map; }
javascript
function (layer, targetCenter, targetZoom) { map._stop(); var startZoom = map._zoom; targetCenter = L.latLng(targetCenter); targetZoom = targetZoom === undefined ? startZoom : targetZoom; targetZoom = Math.min(targetZoom, map.getMaxZoom()); // don't go past max zoom var start = Date.now(), duration = 75; function frame() { var t = (Date.now() - start) / duration; if (t <= 1) { // reuse internal flyTo frame to ensure these animations are canceled like others map._flyToFrame = L.Util.requestAnimFrame(frame, map); setZoomAroundNoMoveEnd(layer, targetCenter, startZoom + (targetZoom - startZoom) * t); } else { setZoomAroundNoMoveEnd(layer, targetCenter, targetZoom) ._moveEnd(true); } } map._moveStart(true); frame.call(map); return map; }
[ "function", "(", "layer", ",", "targetCenter", ",", "targetZoom", ")", "{", "map", ".", "_stop", "(", ")", ";", "var", "startZoom", "=", "map", ".", "_zoom", ";", "targetCenter", "=", "L", ".", "latLng", "(", "targetCenter", ")", ";", "targetZoom", "=", "targetZoom", "===", "undefined", "?", "startZoom", ":", "targetZoom", ";", "targetZoom", "=", "Math", ".", "min", "(", "targetZoom", ",", "map", ".", "getMaxZoom", "(", ")", ")", ";", "// don't go past max zoom", "var", "start", "=", "Date", ".", "now", "(", ")", ",", "duration", "=", "75", ";", "function", "frame", "(", ")", "{", "var", "t", "=", "(", "Date", ".", "now", "(", ")", "-", "start", ")", "/", "duration", ";", "if", "(", "t", "<=", "1", ")", "{", "// reuse internal flyTo frame to ensure these animations are canceled like others", "map", ".", "_flyToFrame", "=", "L", ".", "Util", ".", "requestAnimFrame", "(", "frame", ",", "map", ")", ";", "setZoomAroundNoMoveEnd", "(", "layer", ",", "targetCenter", ",", "startZoom", "+", "(", "targetZoom", "-", "startZoom", ")", "*", "t", ")", ";", "}", "else", "{", "setZoomAroundNoMoveEnd", "(", "layer", ",", "targetCenter", ",", "targetZoom", ")", ".", "_moveEnd", "(", "true", ")", ";", "}", "}", "map", ".", "_moveStart", "(", "true", ")", ";", "frame", ".", "call", "(", "map", ")", ";", "return", "map", ";", "}" ]
Simplified version of Leaflet's flyTo, for short animations zooming around a point
[ "Simplified", "version", "of", "Leaflet", "s", "flyTo", "for", "short", "animations", "zooming", "around", "a", "point" ]
e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11
https://github.com/tangrams/tangram/blob/e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11/src/leaflet_layer.js#L314-L343
12,005
tangrams/tangram
src/tile/tile.js
addDebugLayers
function addDebugLayers (node, tree) { for (let layer in node) { let counts = node[layer]; addLayerDebugEntry(tree, layer, counts.features, counts.geoms, counts.styles, counts.base); if (counts.layers) { tree[layer].layers = tree[layer].layers || {}; addDebugLayers(counts.layers, tree[layer].layers); // process child layers } } }
javascript
function addDebugLayers (node, tree) { for (let layer in node) { let counts = node[layer]; addLayerDebugEntry(tree, layer, counts.features, counts.geoms, counts.styles, counts.base); if (counts.layers) { tree[layer].layers = tree[layer].layers || {}; addDebugLayers(counts.layers, tree[layer].layers); // process child layers } } }
[ "function", "addDebugLayers", "(", "node", ",", "tree", ")", "{", "for", "(", "let", "layer", "in", "node", ")", "{", "let", "counts", "=", "node", "[", "layer", "]", ";", "addLayerDebugEntry", "(", "tree", ",", "layer", ",", "counts", ".", "features", ",", "counts", ".", "geoms", ",", "counts", ".", "styles", ",", "counts", ".", "base", ")", ";", "if", "(", "counts", ".", "layers", ")", "{", "tree", "[", "layer", "]", ".", "layers", "=", "tree", "[", "layer", "]", ".", "layers", "||", "{", "}", ";", "addDebugLayers", "(", "counts", ".", "layers", ",", "tree", "[", "layer", "]", ".", "layers", ")", ";", "// process child layers", "}", "}", "}" ]
build debug stats layer tree
[ "build", "debug", "stats", "layer", "tree" ]
e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11
https://github.com/tangrams/tangram/blob/e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11/src/tile/tile.js#L631-L640
12,006
tangrams/tangram
src/tile/tile_manager.js
meshSetString
function meshSetString (tiles) { return JSON.stringify( Object.entries(tiles).map(([,t]) => { return Object.entries(t.meshes).map(([,s]) => { return s.map(m => m.created_at); }); }) ); }
javascript
function meshSetString (tiles) { return JSON.stringify( Object.entries(tiles).map(([,t]) => { return Object.entries(t.meshes).map(([,s]) => { return s.map(m => m.created_at); }); }) ); }
[ "function", "meshSetString", "(", "tiles", ")", "{", "return", "JSON", ".", "stringify", "(", "Object", ".", "entries", "(", "tiles", ")", ".", "map", "(", "(", "[", ",", "t", "]", ")", "=>", "{", "return", "Object", ".", "entries", "(", "t", ".", "meshes", ")", ".", "map", "(", "(", "[", ",", "s", "]", ")", "=>", "{", "return", "s", ".", "map", "(", "m", "=>", "m", ".", "created_at", ")", ";", "}", ")", ";", "}", ")", ")", ";", "}" ]
Create a string representing the current set of meshes for a given set of tiles, based on their created timestamp. Used to determine when tiles should be re-collided.
[ "Create", "a", "string", "representing", "the", "current", "set", "of", "meshes", "for", "a", "given", "set", "of", "tiles", "based", "on", "their", "created", "timestamp", ".", "Used", "to", "determine", "when", "tiles", "should", "be", "re", "-", "collided", "." ]
e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11
https://github.com/tangrams/tangram/blob/e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11/src/tile/tile_manager.js#L462-L470
12,007
tangrams/tangram
src/sources/geojson.js
getCentroidFeatureForPolygon
function getCentroidFeatureForPolygon (coordinates, properties, newProperties) { let centroid = Geo.centroid(coordinates); if (!centroid) { return; } // clone properties and mixix newProperties let centroid_properties = {}; Object.assign(centroid_properties, properties, newProperties); return { type: 'Feature', properties: centroid_properties, geometry: { type: 'Point', coordinates: centroid } }; }
javascript
function getCentroidFeatureForPolygon (coordinates, properties, newProperties) { let centroid = Geo.centroid(coordinates); if (!centroid) { return; } // clone properties and mixix newProperties let centroid_properties = {}; Object.assign(centroid_properties, properties, newProperties); return { type: 'Feature', properties: centroid_properties, geometry: { type: 'Point', coordinates: centroid } }; }
[ "function", "getCentroidFeatureForPolygon", "(", "coordinates", ",", "properties", ",", "newProperties", ")", "{", "let", "centroid", "=", "Geo", ".", "centroid", "(", "coordinates", ")", ";", "if", "(", "!", "centroid", ")", "{", "return", ";", "}", "// clone properties and mixix newProperties", "let", "centroid_properties", "=", "{", "}", ";", "Object", ".", "assign", "(", "centroid_properties", ",", "properties", ",", "newProperties", ")", ";", "return", "{", "type", ":", "'Feature'", ",", "properties", ":", "centroid_properties", ",", "geometry", ":", "{", "type", ":", "'Point'", ",", "coordinates", ":", "centroid", "}", "}", ";", "}" ]
Helper function to create centroid point feature from polygon coordinates and provided feature meta-data
[ "Helper", "function", "to", "create", "centroid", "point", "feature", "from", "polygon", "coordinates", "and", "provided", "feature", "meta", "-", "data" ]
e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11
https://github.com/tangrams/tangram/blob/e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11/src/sources/geojson.js#L255-L273
12,008
tangrams/tangram
src/scene/scene_loader.js
flattenProperties
function flattenProperties (obj, prefix = null, globals = {}) { prefix = prefix ? (prefix + '.') : 'global.'; for (const p in obj) { const key = prefix + p; const val = obj[p]; globals[key] = val; if (typeof val === 'object' && !Array.isArray(val)) { flattenProperties(val, key, globals); } } return globals; }
javascript
function flattenProperties (obj, prefix = null, globals = {}) { prefix = prefix ? (prefix + '.') : 'global.'; for (const p in obj) { const key = prefix + p; const val = obj[p]; globals[key] = val; if (typeof val === 'object' && !Array.isArray(val)) { flattenProperties(val, key, globals); } } return globals; }
[ "function", "flattenProperties", "(", "obj", ",", "prefix", "=", "null", ",", "globals", "=", "{", "}", ")", "{", "prefix", "=", "prefix", "?", "(", "prefix", "+", "'.'", ")", ":", "'global.'", ";", "for", "(", "const", "p", "in", "obj", ")", "{", "const", "key", "=", "prefix", "+", "p", ";", "const", "val", "=", "obj", "[", "p", "]", ";", "globals", "[", "key", "]", "=", "val", ";", "if", "(", "typeof", "val", "===", "'object'", "&&", "!", "Array", ".", "isArray", "(", "val", ")", ")", "{", "flattenProperties", "(", "val", ",", "key", ",", "globals", ")", ";", "}", "}", "return", "globals", ";", "}" ]
Flatten nested properties for simpler string look-ups
[ "Flatten", "nested", "properties", "for", "simpler", "string", "look", "-", "ups" ]
e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11
https://github.com/tangrams/tangram/blob/e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11/src/scene/scene_loader.js#L388-L401
12,009
tangrams/tangram
demos/lib/keymaster.js
compareArray
function compareArray(a1, a2) { if (a1.length != a2.length) return false; for (var i = 0; i < a1.length; i++) { if (a1[i] !== a2[i]) return false; } return true; }
javascript
function compareArray(a1, a2) { if (a1.length != a2.length) return false; for (var i = 0; i < a1.length; i++) { if (a1[i] !== a2[i]) return false; } return true; }
[ "function", "compareArray", "(", "a1", ",", "a2", ")", "{", "if", "(", "a1", ".", "length", "!=", "a2", ".", "length", ")", "return", "false", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "a1", ".", "length", ";", "i", "++", ")", "{", "if", "(", "a1", "[", "i", "]", "!==", "a2", "[", "i", "]", ")", "return", "false", ";", "}", "return", "true", ";", "}" ]
for comparing mods before unassignment
[ "for", "comparing", "mods", "before", "unassignment" ]
e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11
https://github.com/tangrams/tangram/blob/e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11/demos/lib/keymaster.js#L47-L53
12,010
tangrams/tangram
demos/lib/keymaster.js
unbindKey
function unbindKey(key, scope) { var multipleKeys, keys, mods = [], i, j, obj; multipleKeys = getKeys(key); for (j = 0; j < multipleKeys.length; j++) { keys = multipleKeys[j].split('+'); if (keys.length > 1) { mods = getMods(keys); key = keys[keys.length - 1]; } key = code(key); if (scope === undefined) { scope = getScope(); } if (!_handlers[key]) { return; } for (i = 0; i < _handlers[key].length; i++) { obj = _handlers[key][i]; // only clear handlers if correct scope and mods match if (obj.scope === scope && compareArray(obj.mods, mods)) { _handlers[key][i] = {}; } } } }
javascript
function unbindKey(key, scope) { var multipleKeys, keys, mods = [], i, j, obj; multipleKeys = getKeys(key); for (j = 0; j < multipleKeys.length; j++) { keys = multipleKeys[j].split('+'); if (keys.length > 1) { mods = getMods(keys); key = keys[keys.length - 1]; } key = code(key); if (scope === undefined) { scope = getScope(); } if (!_handlers[key]) { return; } for (i = 0; i < _handlers[key].length; i++) { obj = _handlers[key][i]; // only clear handlers if correct scope and mods match if (obj.scope === scope && compareArray(obj.mods, mods)) { _handlers[key][i] = {}; } } } }
[ "function", "unbindKey", "(", "key", ",", "scope", ")", "{", "var", "multipleKeys", ",", "keys", ",", "mods", "=", "[", "]", ",", "i", ",", "j", ",", "obj", ";", "multipleKeys", "=", "getKeys", "(", "key", ")", ";", "for", "(", "j", "=", "0", ";", "j", "<", "multipleKeys", ".", "length", ";", "j", "++", ")", "{", "keys", "=", "multipleKeys", "[", "j", "]", ".", "split", "(", "'+'", ")", ";", "if", "(", "keys", ".", "length", ">", "1", ")", "{", "mods", "=", "getMods", "(", "keys", ")", ";", "key", "=", "keys", "[", "keys", ".", "length", "-", "1", "]", ";", "}", "key", "=", "code", "(", "key", ")", ";", "if", "(", "scope", "===", "undefined", ")", "{", "scope", "=", "getScope", "(", ")", ";", "}", "if", "(", "!", "_handlers", "[", "key", "]", ")", "{", "return", ";", "}", "for", "(", "i", "=", "0", ";", "i", "<", "_handlers", "[", "key", "]", ".", "length", ";", "i", "++", ")", "{", "obj", "=", "_handlers", "[", "key", "]", "[", "i", "]", ";", "// only clear handlers if correct scope and mods match", "if", "(", "obj", ".", "scope", "===", "scope", "&&", "compareArray", "(", "obj", ".", "mods", ",", "mods", ")", ")", "{", "_handlers", "[", "key", "]", "[", "i", "]", "=", "{", "}", ";", "}", "}", "}", "}" ]
unbind all handlers for given key in current scope
[ "unbind", "all", "handlers", "for", "given", "key", "in", "current", "scope" ]
e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11
https://github.com/tangrams/tangram/blob/e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11/demos/lib/keymaster.js#L167-L198
12,011
tangrams/tangram
demos/lib/keymaster.js
deleteScope
function deleteScope(scope){ var key, handlers, i; for (key in _handlers) { handlers = _handlers[key]; for (i = 0; i < handlers.length; ) { if (handlers[i].scope === scope) handlers.splice(i, 1); else i++; } } }
javascript
function deleteScope(scope){ var key, handlers, i; for (key in _handlers) { handlers = _handlers[key]; for (i = 0; i < handlers.length; ) { if (handlers[i].scope === scope) handlers.splice(i, 1); else i++; } } }
[ "function", "deleteScope", "(", "scope", ")", "{", "var", "key", ",", "handlers", ",", "i", ";", "for", "(", "key", "in", "_handlers", ")", "{", "handlers", "=", "_handlers", "[", "key", "]", ";", "for", "(", "i", "=", "0", ";", "i", "<", "handlers", ".", "length", ";", ")", "{", "if", "(", "handlers", "[", "i", "]", ".", "scope", "===", "scope", ")", "handlers", ".", "splice", "(", "i", ",", "1", ")", ";", "else", "i", "++", ";", "}", "}", "}" ]
delete all handlers for a given scope
[ "delete", "all", "handlers", "for", "a", "given", "scope" ]
e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11
https://github.com/tangrams/tangram/blob/e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11/demos/lib/keymaster.js#L227-L237
12,012
tangrams/tangram
demos/lib/keymaster.js
getKeys
function getKeys(key) { var keys; key = key.replace(/\s/g, ''); keys = key.split(','); if ((keys[keys.length - 1]) == '') { keys[keys.length - 2] += ','; } return keys; }
javascript
function getKeys(key) { var keys; key = key.replace(/\s/g, ''); keys = key.split(','); if ((keys[keys.length - 1]) == '') { keys[keys.length - 2] += ','; } return keys; }
[ "function", "getKeys", "(", "key", ")", "{", "var", "keys", ";", "key", "=", "key", ".", "replace", "(", "/", "\\s", "/", "g", ",", "''", ")", ";", "keys", "=", "key", ".", "split", "(", "','", ")", ";", "if", "(", "(", "keys", "[", "keys", ".", "length", "-", "1", "]", ")", "==", "''", ")", "{", "keys", "[", "keys", ".", "length", "-", "2", "]", "+=", "','", ";", "}", "return", "keys", ";", "}" ]
abstract key logic for assign and unassign
[ "abstract", "key", "logic", "for", "assign", "and", "unassign" ]
e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11
https://github.com/tangrams/tangram/blob/e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11/demos/lib/keymaster.js#L240-L248
12,013
tangrams/tangram
demos/lib/keymaster.js
getMods
function getMods(key) { var mods = key.slice(0, key.length - 1); for (var mi = 0; mi < mods.length; mi++) mods[mi] = _MODIFIERS[mods[mi]]; return mods; }
javascript
function getMods(key) { var mods = key.slice(0, key.length - 1); for (var mi = 0; mi < mods.length; mi++) mods[mi] = _MODIFIERS[mods[mi]]; return mods; }
[ "function", "getMods", "(", "key", ")", "{", "var", "mods", "=", "key", ".", "slice", "(", "0", ",", "key", ".", "length", "-", "1", ")", ";", "for", "(", "var", "mi", "=", "0", ";", "mi", "<", "mods", ".", "length", ";", "mi", "++", ")", "mods", "[", "mi", "]", "=", "_MODIFIERS", "[", "mods", "[", "mi", "]", "]", ";", "return", "mods", ";", "}" ]
abstract mods logic for assign and unassign
[ "abstract", "mods", "logic", "for", "assign", "and", "unassign" ]
e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11
https://github.com/tangrams/tangram/blob/e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11/demos/lib/keymaster.js#L251-L256
12,014
tangrams/tangram
src/utils/worker_broker.js
freeTransferables
function freeTransferables(transferables) { if (!Array.isArray(transferables)) { return; } transferables.filter(t => t.parent && t.property).forEach(t => delete t.parent[t.property]); }
javascript
function freeTransferables(transferables) { if (!Array.isArray(transferables)) { return; } transferables.filter(t => t.parent && t.property).forEach(t => delete t.parent[t.property]); }
[ "function", "freeTransferables", "(", "transferables", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "transferables", ")", ")", "{", "return", ";", "}", "transferables", ".", "filter", "(", "t", "=>", "t", ".", "parent", "&&", "t", ".", "property", ")", ".", "forEach", "(", "t", "=>", "delete", "t", ".", "parent", "[", "t", ".", "property", "]", ")", ";", "}" ]
Remove neutered transferables from parent objects, as they should no longer be accessed after transfer
[ "Remove", "neutered", "transferables", "from", "parent", "objects", "as", "they", "should", "no", "longer", "be", "accessed", "after", "transfer" ]
e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11
https://github.com/tangrams/tangram/blob/e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11/src/utils/worker_broker.js#L500-L505
12,015
tangrams/tangram
demos/main.js
onHover
function onHover (selection) { var feature = selection.feature; if (feature) { if (selection.changed) { var info; if (scene.introspection) { info = getFeaturePropsHTML(feature); } else { var name = feature.properties.name || feature.properties.kind || (Object.keys(feature.properties).length+' properties'); name = '<b>'+name+'</b>'; name += '<br>(click for details)'; name = '<span class="labelInner">' + name + '</span>'; info = name; } if (info) { tooltip.setContent(info); } } layer.openTooltip(selection.leaflet_event.latlng); } else { layer.closeTooltip(); } }
javascript
function onHover (selection) { var feature = selection.feature; if (feature) { if (selection.changed) { var info; if (scene.introspection) { info = getFeaturePropsHTML(feature); } else { var name = feature.properties.name || feature.properties.kind || (Object.keys(feature.properties).length+' properties'); name = '<b>'+name+'</b>'; name += '<br>(click for details)'; name = '<span class="labelInner">' + name + '</span>'; info = name; } if (info) { tooltip.setContent(info); } } layer.openTooltip(selection.leaflet_event.latlng); } else { layer.closeTooltip(); } }
[ "function", "onHover", "(", "selection", ")", "{", "var", "feature", "=", "selection", ".", "feature", ";", "if", "(", "feature", ")", "{", "if", "(", "selection", ".", "changed", ")", "{", "var", "info", ";", "if", "(", "scene", ".", "introspection", ")", "{", "info", "=", "getFeaturePropsHTML", "(", "feature", ")", ";", "}", "else", "{", "var", "name", "=", "feature", ".", "properties", ".", "name", "||", "feature", ".", "properties", ".", "kind", "||", "(", "Object", ".", "keys", "(", "feature", ".", "properties", ")", ".", "length", "+", "' properties'", ")", ";", "name", "=", "'<b>'", "+", "name", "+", "'</b>'", ";", "name", "+=", "'<br>(click for details)'", ";", "name", "=", "'<span class=\"labelInner\">'", "+", "name", "+", "'</span>'", ";", "info", "=", "name", ";", "}", "if", "(", "info", ")", "{", "tooltip", ".", "setContent", "(", "info", ")", ";", "}", "}", "layer", ".", "openTooltip", "(", "selection", ".", "leaflet_event", ".", "latlng", ")", ";", "}", "else", "{", "layer", ".", "closeTooltip", "(", ")", ";", "}", "}" ]
close tooltip when zooming
[ "close", "tooltip", "when", "zooming" ]
e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11
https://github.com/tangrams/tangram/blob/e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11/demos/main.js#L82-L108
12,016
tangrams/tangram
demos/main.js
getFeaturePropsHTML
function getFeaturePropsHTML (feature) { var props = ['name', 'kind', 'kind_detail', 'id']; // show these properties first if available Object.keys(feature.properties) // show rest of proeprties alphabetized .sort() .forEach(function(p) { if (props.indexOf(p) === -1) { props.push(p); } }); var info = '<div class="featureTable">'; props.forEach(function(p) { if (feature.properties[p]) { info += '<div class="featureRow"><div class="featureCell"><b>' + p + '</b></div>' + '<div class="featureCell">' + feature.properties[p] + '</div></div>'; } }); info += '<div class="featureRow"><div class="featureCell"><b>scene layers</b></div>' + '<div class="featureCell">' + feature.layers.join('<br>') + '</div></div>'; info += '</div>'; return info; }
javascript
function getFeaturePropsHTML (feature) { var props = ['name', 'kind', 'kind_detail', 'id']; // show these properties first if available Object.keys(feature.properties) // show rest of proeprties alphabetized .sort() .forEach(function(p) { if (props.indexOf(p) === -1) { props.push(p); } }); var info = '<div class="featureTable">'; props.forEach(function(p) { if (feature.properties[p]) { info += '<div class="featureRow"><div class="featureCell"><b>' + p + '</b></div>' + '<div class="featureCell">' + feature.properties[p] + '</div></div>'; } }); info += '<div class="featureRow"><div class="featureCell"><b>scene layers</b></div>' + '<div class="featureCell">' + feature.layers.join('<br>') + '</div></div>'; info += '</div>'; return info; }
[ "function", "getFeaturePropsHTML", "(", "feature", ")", "{", "var", "props", "=", "[", "'name'", ",", "'kind'", ",", "'kind_detail'", ",", "'id'", "]", ";", "// show these properties first if available", "Object", ".", "keys", "(", "feature", ".", "properties", ")", "// show rest of proeprties alphabetized", ".", "sort", "(", ")", ".", "forEach", "(", "function", "(", "p", ")", "{", "if", "(", "props", ".", "indexOf", "(", "p", ")", "===", "-", "1", ")", "{", "props", ".", "push", "(", "p", ")", ";", "}", "}", ")", ";", "var", "info", "=", "'<div class=\"featureTable\">'", ";", "props", ".", "forEach", "(", "function", "(", "p", ")", "{", "if", "(", "feature", ".", "properties", "[", "p", "]", ")", "{", "info", "+=", "'<div class=\"featureRow\"><div class=\"featureCell\"><b>'", "+", "p", "+", "'</b></div>'", "+", "'<div class=\"featureCell\">'", "+", "feature", ".", "properties", "[", "p", "]", "+", "'</div></div>'", ";", "}", "}", ")", ";", "info", "+=", "'<div class=\"featureRow\"><div class=\"featureCell\"><b>scene layers</b></div>'", "+", "'<div class=\"featureCell\">'", "+", "feature", ".", "layers", ".", "join", "(", "'<br>'", ")", "+", "'</div></div>'", ";", "info", "+=", "'</div>'", ";", "return", "info", ";", "}" ]
Get an HTML fragment with feature properties
[ "Get", "an", "HTML", "fragment", "with", "feature", "properties" ]
e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11
https://github.com/tangrams/tangram/blob/e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11/demos/main.js#L136-L157
12,017
tangrams/tangram
src/builders/polylines.js
getNextNonBoundarySegment
function getNextNonBoundarySegment (line, startIndex, tolerance) { var endIndex = startIndex; while (line[endIndex + 1] && outsideTile(line[endIndex], line[endIndex + 1], tolerance)) { endIndex++; } // If there is a line segment remaining that is within the tile, push it to the lines array return (line.length - endIndex >= 2) ? line.slice(endIndex) : false; }
javascript
function getNextNonBoundarySegment (line, startIndex, tolerance) { var endIndex = startIndex; while (line[endIndex + 1] && outsideTile(line[endIndex], line[endIndex + 1], tolerance)) { endIndex++; } // If there is a line segment remaining that is within the tile, push it to the lines array return (line.length - endIndex >= 2) ? line.slice(endIndex) : false; }
[ "function", "getNextNonBoundarySegment", "(", "line", ",", "startIndex", ",", "tolerance", ")", "{", "var", "endIndex", "=", "startIndex", ";", "while", "(", "line", "[", "endIndex", "+", "1", "]", "&&", "outsideTile", "(", "line", "[", "endIndex", "]", ",", "line", "[", "endIndex", "+", "1", "]", ",", "tolerance", ")", ")", "{", "endIndex", "++", ";", "}", "// If there is a line segment remaining that is within the tile, push it to the lines array", "return", "(", "line", ".", "length", "-", "endIndex", ">=", "2", ")", "?", "line", ".", "slice", "(", "endIndex", ")", ":", "false", ";", "}" ]
Iterate through line from startIndex to find a segment not on a tile boundary, if any.
[ "Iterate", "through", "line", "from", "startIndex", "to", "find", "a", "segment", "not", "on", "a", "tile", "boundary", "if", "any", "." ]
e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11
https://github.com/tangrams/tangram/blob/e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11/src/builders/polylines.js#L264-L272
12,018
tangrams/tangram
src/builders/polylines.js
endPolygon
function endPolygon(coordCurr, normPrev, normNext, join_type, v, context) { // If polygon ends on a tile boundary, don't add a join if (isCoordOutsideTile(coordCurr)) { addVertex(coordCurr, normPrev, normPrev, 1, v, context, 1); addVertex(coordCurr, normPrev, normPrev, 0, v, context, -1); indexPairs(1, context); } else { // If polygon ends within a tile, add Miter or no joint (join added on startPolygon) var miterVec = createMiterVec(normPrev, normNext); if (join_type === JOIN_TYPE.miter && Vector.lengthSq(miterVec) > context.miter_len_sq) { join_type = JOIN_TYPE.bevel; // switch to bevel } if (join_type === JOIN_TYPE.miter) { addVertex(coordCurr, miterVec, normPrev, 1, v, context, 1); addVertex(coordCurr, miterVec, normPrev, 0, v, context, -1); indexPairs(1, context); } else { addVertex(coordCurr, normPrev, normPrev, 1, v, context, 1); addVertex(coordCurr, normPrev, normPrev, 0, v, context, -1); indexPairs(1, context); } } }
javascript
function endPolygon(coordCurr, normPrev, normNext, join_type, v, context) { // If polygon ends on a tile boundary, don't add a join if (isCoordOutsideTile(coordCurr)) { addVertex(coordCurr, normPrev, normPrev, 1, v, context, 1); addVertex(coordCurr, normPrev, normPrev, 0, v, context, -1); indexPairs(1, context); } else { // If polygon ends within a tile, add Miter or no joint (join added on startPolygon) var miterVec = createMiterVec(normPrev, normNext); if (join_type === JOIN_TYPE.miter && Vector.lengthSq(miterVec) > context.miter_len_sq) { join_type = JOIN_TYPE.bevel; // switch to bevel } if (join_type === JOIN_TYPE.miter) { addVertex(coordCurr, miterVec, normPrev, 1, v, context, 1); addVertex(coordCurr, miterVec, normPrev, 0, v, context, -1); indexPairs(1, context); } else { addVertex(coordCurr, normPrev, normPrev, 1, v, context, 1); addVertex(coordCurr, normPrev, normPrev, 0, v, context, -1); indexPairs(1, context); } } }
[ "function", "endPolygon", "(", "coordCurr", ",", "normPrev", ",", "normNext", ",", "join_type", ",", "v", ",", "context", ")", "{", "// If polygon ends on a tile boundary, don't add a join", "if", "(", "isCoordOutsideTile", "(", "coordCurr", ")", ")", "{", "addVertex", "(", "coordCurr", ",", "normPrev", ",", "normPrev", ",", "1", ",", "v", ",", "context", ",", "1", ")", ";", "addVertex", "(", "coordCurr", ",", "normPrev", ",", "normPrev", ",", "0", ",", "v", ",", "context", ",", "-", "1", ")", ";", "indexPairs", "(", "1", ",", "context", ")", ";", "}", "else", "{", "// If polygon ends within a tile, add Miter or no joint (join added on startPolygon)", "var", "miterVec", "=", "createMiterVec", "(", "normPrev", ",", "normNext", ")", ";", "if", "(", "join_type", "===", "JOIN_TYPE", ".", "miter", "&&", "Vector", ".", "lengthSq", "(", "miterVec", ")", ">", "context", ".", "miter_len_sq", ")", "{", "join_type", "=", "JOIN_TYPE", ".", "bevel", ";", "// switch to bevel", "}", "if", "(", "join_type", "===", "JOIN_TYPE", ".", "miter", ")", "{", "addVertex", "(", "coordCurr", ",", "miterVec", ",", "normPrev", ",", "1", ",", "v", ",", "context", ",", "1", ")", ";", "addVertex", "(", "coordCurr", ",", "miterVec", ",", "normPrev", ",", "0", ",", "v", ",", "context", ",", "-", "1", ")", ";", "indexPairs", "(", "1", ",", "context", ")", ";", "}", "else", "{", "addVertex", "(", "coordCurr", ",", "normPrev", ",", "normPrev", ",", "1", ",", "v", ",", "context", ",", "1", ")", ";", "addVertex", "(", "coordCurr", ",", "normPrev", ",", "normPrev", ",", "0", ",", "v", ",", "context", ",", "-", "1", ")", ";", "indexPairs", "(", "1", ",", "context", ")", ";", "}", "}", "}" ]
End a polygon appropriately
[ "End", "a", "polygon", "appropriately" ]
e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11
https://github.com/tangrams/tangram/blob/e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11/src/builders/polylines.js#L294-L320
12,019
tangrams/tangram
src/builders/polylines.js
addMiter
function addMiter (v, coordCurr, normPrev, normNext, miter_len_sq, isBeginning, context) { var miterVec = createMiterVec(normPrev, normNext); // Miter limit: if miter join is too sharp, convert to bevel instead if (Vector.lengthSq(miterVec) > miter_len_sq) { addJoin(JOIN_TYPE.bevel, v, coordCurr, normPrev, normNext, isBeginning, context); } else { addVertex(coordCurr, miterVec, miterVec, 1, v, context, 1); addVertex(coordCurr, miterVec, miterVec, 0, v, context, -1); if (!isBeginning) { indexPairs(1, context); } } }
javascript
function addMiter (v, coordCurr, normPrev, normNext, miter_len_sq, isBeginning, context) { var miterVec = createMiterVec(normPrev, normNext); // Miter limit: if miter join is too sharp, convert to bevel instead if (Vector.lengthSq(miterVec) > miter_len_sq) { addJoin(JOIN_TYPE.bevel, v, coordCurr, normPrev, normNext, isBeginning, context); } else { addVertex(coordCurr, miterVec, miterVec, 1, v, context, 1); addVertex(coordCurr, miterVec, miterVec, 0, v, context, -1); if (!isBeginning) { indexPairs(1, context); } } }
[ "function", "addMiter", "(", "v", ",", "coordCurr", ",", "normPrev", ",", "normNext", ",", "miter_len_sq", ",", "isBeginning", ",", "context", ")", "{", "var", "miterVec", "=", "createMiterVec", "(", "normPrev", ",", "normNext", ")", ";", "// Miter limit: if miter join is too sharp, convert to bevel instead", "if", "(", "Vector", ".", "lengthSq", "(", "miterVec", ")", ">", "miter_len_sq", ")", "{", "addJoin", "(", "JOIN_TYPE", ".", "bevel", ",", "v", ",", "coordCurr", ",", "normPrev", ",", "normNext", ",", "isBeginning", ",", "context", ")", ";", "}", "else", "{", "addVertex", "(", "coordCurr", ",", "miterVec", ",", "miterVec", ",", "1", ",", "v", ",", "context", ",", "1", ")", ";", "addVertex", "(", "coordCurr", ",", "miterVec", ",", "miterVec", ",", "0", ",", "v", ",", "context", ",", "-", "1", ")", ";", "if", "(", "!", "isBeginning", ")", "{", "indexPairs", "(", "1", ",", "context", ")", ";", "}", "}", "}" ]
Add a miter vector or a join if the miter is too sharp
[ "Add", "a", "miter", "vector", "or", "a", "join", "if", "the", "miter", "is", "too", "sharp" ]
e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11
https://github.com/tangrams/tangram/blob/e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11/src/builders/polylines.js#L329-L343
12,020
tangrams/tangram
src/builders/polylines.js
addJoin
function addJoin(join_type, v, coordCurr, normPrev, normNext, isBeginning, context) { var miterVec = createMiterVec(normPrev, normNext); var isClockwise = (normNext[0] * normPrev[1] - normNext[1] * normPrev[0] > 0); if (context.texcoord_index != null) { zero_v[1] = v; one_v[1] = v; } if (isClockwise){ addVertex(coordCurr, miterVec, miterVec, 1, v, context, 1); addVertex(coordCurr, normPrev, miterVec, 0, v, context, -1); if (!isBeginning) { indexPairs(1, context); } addFan(coordCurr, // extrusion vector of first vertex Vector.neg(normPrev), // controls extrude distance of pivot vertex miterVec, // extrusion vector of last vertex Vector.neg(normNext), // line normal (unused here) miterVec, // uv coordinates zero_v, one_v, zero_v, false, (join_type === JOIN_TYPE.bevel), context ); addVertex(coordCurr, miterVec, miterVec, 1, v, context, 1); addVertex(coordCurr, normNext, miterVec, 0, v, context, -1); } else { addVertex(coordCurr, normPrev, miterVec, 1, v, context, 1); addVertex(coordCurr, miterVec, miterVec, 0, v, context, -1); if (!isBeginning) { indexPairs(1, context); } addFan(coordCurr, // extrusion vector of first vertex normPrev, // extrusion vector of pivot vertex Vector.neg(miterVec), // extrusion vector of last vertex normNext, // line normal for offset miterVec, // uv coordinates one_v, zero_v, one_v, false, (join_type === JOIN_TYPE.bevel), context ); addVertex(coordCurr, normNext, miterVec, 1, v, context, 1); addVertex(coordCurr, miterVec, miterVec, 0, v, context, -1); } }
javascript
function addJoin(join_type, v, coordCurr, normPrev, normNext, isBeginning, context) { var miterVec = createMiterVec(normPrev, normNext); var isClockwise = (normNext[0] * normPrev[1] - normNext[1] * normPrev[0] > 0); if (context.texcoord_index != null) { zero_v[1] = v; one_v[1] = v; } if (isClockwise){ addVertex(coordCurr, miterVec, miterVec, 1, v, context, 1); addVertex(coordCurr, normPrev, miterVec, 0, v, context, -1); if (!isBeginning) { indexPairs(1, context); } addFan(coordCurr, // extrusion vector of first vertex Vector.neg(normPrev), // controls extrude distance of pivot vertex miterVec, // extrusion vector of last vertex Vector.neg(normNext), // line normal (unused here) miterVec, // uv coordinates zero_v, one_v, zero_v, false, (join_type === JOIN_TYPE.bevel), context ); addVertex(coordCurr, miterVec, miterVec, 1, v, context, 1); addVertex(coordCurr, normNext, miterVec, 0, v, context, -1); } else { addVertex(coordCurr, normPrev, miterVec, 1, v, context, 1); addVertex(coordCurr, miterVec, miterVec, 0, v, context, -1); if (!isBeginning) { indexPairs(1, context); } addFan(coordCurr, // extrusion vector of first vertex normPrev, // extrusion vector of pivot vertex Vector.neg(miterVec), // extrusion vector of last vertex normNext, // line normal for offset miterVec, // uv coordinates one_v, zero_v, one_v, false, (join_type === JOIN_TYPE.bevel), context ); addVertex(coordCurr, normNext, miterVec, 1, v, context, 1); addVertex(coordCurr, miterVec, miterVec, 0, v, context, -1); } }
[ "function", "addJoin", "(", "join_type", ",", "v", ",", "coordCurr", ",", "normPrev", ",", "normNext", ",", "isBeginning", ",", "context", ")", "{", "var", "miterVec", "=", "createMiterVec", "(", "normPrev", ",", "normNext", ")", ";", "var", "isClockwise", "=", "(", "normNext", "[", "0", "]", "*", "normPrev", "[", "1", "]", "-", "normNext", "[", "1", "]", "*", "normPrev", "[", "0", "]", ">", "0", ")", ";", "if", "(", "context", ".", "texcoord_index", "!=", "null", ")", "{", "zero_v", "[", "1", "]", "=", "v", ";", "one_v", "[", "1", "]", "=", "v", ";", "}", "if", "(", "isClockwise", ")", "{", "addVertex", "(", "coordCurr", ",", "miterVec", ",", "miterVec", ",", "1", ",", "v", ",", "context", ",", "1", ")", ";", "addVertex", "(", "coordCurr", ",", "normPrev", ",", "miterVec", ",", "0", ",", "v", ",", "context", ",", "-", "1", ")", ";", "if", "(", "!", "isBeginning", ")", "{", "indexPairs", "(", "1", ",", "context", ")", ";", "}", "addFan", "(", "coordCurr", ",", "// extrusion vector of first vertex", "Vector", ".", "neg", "(", "normPrev", ")", ",", "// controls extrude distance of pivot vertex", "miterVec", ",", "// extrusion vector of last vertex", "Vector", ".", "neg", "(", "normNext", ")", ",", "// line normal (unused here)", "miterVec", ",", "// uv coordinates", "zero_v", ",", "one_v", ",", "zero_v", ",", "false", ",", "(", "join_type", "===", "JOIN_TYPE", ".", "bevel", ")", ",", "context", ")", ";", "addVertex", "(", "coordCurr", ",", "miterVec", ",", "miterVec", ",", "1", ",", "v", ",", "context", ",", "1", ")", ";", "addVertex", "(", "coordCurr", ",", "normNext", ",", "miterVec", ",", "0", ",", "v", ",", "context", ",", "-", "1", ")", ";", "}", "else", "{", "addVertex", "(", "coordCurr", ",", "normPrev", ",", "miterVec", ",", "1", ",", "v", ",", "context", ",", "1", ")", ";", "addVertex", "(", "coordCurr", ",", "miterVec", ",", "miterVec", ",", "0", ",", "v", ",", "context", ",", "-", "1", ")", ";", "if", "(", "!", "isBeginning", ")", "{", "indexPairs", "(", "1", ",", "context", ")", ";", "}", "addFan", "(", "coordCurr", ",", "// extrusion vector of first vertex", "normPrev", ",", "// extrusion vector of pivot vertex", "Vector", ".", "neg", "(", "miterVec", ")", ",", "// extrusion vector of last vertex", "normNext", ",", "// line normal for offset", "miterVec", ",", "// uv coordinates", "one_v", ",", "zero_v", ",", "one_v", ",", "false", ",", "(", "join_type", "===", "JOIN_TYPE", ".", "bevel", ")", ",", "context", ")", ";", "addVertex", "(", "coordCurr", ",", "normNext", ",", "miterVec", ",", "1", ",", "v", ",", "context", ",", "1", ")", ";", "addVertex", "(", "coordCurr", ",", "miterVec", ",", "miterVec", ",", "0", ",", "v", ",", "context", ",", "-", "1", ")", ";", "}", "}" ]
Add a bevel or round join
[ "Add", "a", "bevel", "or", "round", "join" ]
e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11
https://github.com/tangrams/tangram/blob/e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11/src/builders/polylines.js#L346-L404
12,021
tangrams/tangram
src/builders/polylines.js
indexPairs
function indexPairs(num_pairs, context){ var vertex_elements = context.vertex_data.vertex_elements; var num_vertices = context.vertex_data.vertex_count; var offset = num_vertices - 2 * num_pairs - 2; for (var i = 0; i < num_pairs; i++){ vertex_elements.push(offset + 2 * i + 2); vertex_elements.push(offset + 2 * i + 1); vertex_elements.push(offset + 2 * i + 0); vertex_elements.push(offset + 2 * i + 2); vertex_elements.push(offset + 2 * i + 3); vertex_elements.push(offset + 2 * i + 1); context.geom_count += 2; } }
javascript
function indexPairs(num_pairs, context){ var vertex_elements = context.vertex_data.vertex_elements; var num_vertices = context.vertex_data.vertex_count; var offset = num_vertices - 2 * num_pairs - 2; for (var i = 0; i < num_pairs; i++){ vertex_elements.push(offset + 2 * i + 2); vertex_elements.push(offset + 2 * i + 1); vertex_elements.push(offset + 2 * i + 0); vertex_elements.push(offset + 2 * i + 2); vertex_elements.push(offset + 2 * i + 3); vertex_elements.push(offset + 2 * i + 1); context.geom_count += 2; } }
[ "function", "indexPairs", "(", "num_pairs", ",", "context", ")", "{", "var", "vertex_elements", "=", "context", ".", "vertex_data", ".", "vertex_elements", ";", "var", "num_vertices", "=", "context", ".", "vertex_data", ".", "vertex_count", ";", "var", "offset", "=", "num_vertices", "-", "2", "*", "num_pairs", "-", "2", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "num_pairs", ";", "i", "++", ")", "{", "vertex_elements", ".", "push", "(", "offset", "+", "2", "*", "i", "+", "2", ")", ";", "vertex_elements", ".", "push", "(", "offset", "+", "2", "*", "i", "+", "1", ")", ";", "vertex_elements", ".", "push", "(", "offset", "+", "2", "*", "i", "+", "0", ")", ";", "vertex_elements", ".", "push", "(", "offset", "+", "2", "*", "i", "+", "2", ")", ";", "vertex_elements", ".", "push", "(", "offset", "+", "2", "*", "i", "+", "3", ")", ";", "vertex_elements", ".", "push", "(", "offset", "+", "2", "*", "i", "+", "1", ")", ";", "context", ".", "geom_count", "+=", "2", ";", "}", "}" ]
Add indices to vertex_elements
[ "Add", "indices", "to", "vertex_elements" ]
e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11
https://github.com/tangrams/tangram/blob/e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11/src/builders/polylines.js#L407-L421
12,022
tangrams/tangram
src/builders/polylines.js
addCap
function addCap (coord, v, normal, type, isBeginning, context) { var neg_normal = Vector.neg(normal); var has_texcoord = (context.texcoord_index != null); switch (type){ case CAP_TYPE.square: var tangent; // first vertex on the lineString if (isBeginning){ tangent = [normal[1], -normal[0]]; addVertex(coord, Vector.add(normal, tangent), normal, 1, v, context, 1); addVertex(coord, Vector.add(neg_normal, tangent), normal, 0, v, context, 1); if (has_texcoord) { // Add length of square cap to texture coordinate v += 0.5 * context.texcoord_width * context.v_scale; } addVertex(coord, normal, normal, 1, v, context, 1); addVertex(coord, neg_normal, normal, 0, v, context, 1); } // last vertex on the lineString else { tangent = [-normal[1], normal[0]]; addVertex(coord, normal, normal, 1, v, context, 1); addVertex(coord, neg_normal, normal, 0, v, context, 1); if (has_texcoord) { // Add length of square cap to texture coordinate v += 0.5 * context.texcoord_width * context.v_scale; } addVertex(coord, Vector.add(normal, tangent), normal, 1, v, context, 1); addVertex(coord, Vector.add(neg_normal, tangent), normal, 0, v, context, 1); } indexPairs(1, context); break; case CAP_TYPE.round: // default for end cap, beginning cap will overwrite below (this way we're always passing a non-null value, // even if texture coords are disabled) var uvA = zero_v, uvB = one_v, uvC = mid_v; var nA, nB; // first vertex on the lineString if (isBeginning) { nA = normal; nB = neg_normal; if (has_texcoord){ v += 0.5 * context.texcoord_width * context.v_scale; uvA = one_v, uvB = zero_v, uvC = mid_v; // update cap UV order } } // last vertex on the lineString - flip the direction of the cap else { nA = neg_normal; nB = normal; } if (has_texcoord) { zero_v[1] = v, one_v[1] = v, mid_v[1] = v; // update cap UV values } addFan(coord, nA, zero_vec2, nB, // extrusion normal normal, // line normal, for offsets uvA, uvC, uvB, // texture coords (ignored if disabled) true, false, context ); break; case CAP_TYPE.butt: return; } }
javascript
function addCap (coord, v, normal, type, isBeginning, context) { var neg_normal = Vector.neg(normal); var has_texcoord = (context.texcoord_index != null); switch (type){ case CAP_TYPE.square: var tangent; // first vertex on the lineString if (isBeginning){ tangent = [normal[1], -normal[0]]; addVertex(coord, Vector.add(normal, tangent), normal, 1, v, context, 1); addVertex(coord, Vector.add(neg_normal, tangent), normal, 0, v, context, 1); if (has_texcoord) { // Add length of square cap to texture coordinate v += 0.5 * context.texcoord_width * context.v_scale; } addVertex(coord, normal, normal, 1, v, context, 1); addVertex(coord, neg_normal, normal, 0, v, context, 1); } // last vertex on the lineString else { tangent = [-normal[1], normal[0]]; addVertex(coord, normal, normal, 1, v, context, 1); addVertex(coord, neg_normal, normal, 0, v, context, 1); if (has_texcoord) { // Add length of square cap to texture coordinate v += 0.5 * context.texcoord_width * context.v_scale; } addVertex(coord, Vector.add(normal, tangent), normal, 1, v, context, 1); addVertex(coord, Vector.add(neg_normal, tangent), normal, 0, v, context, 1); } indexPairs(1, context); break; case CAP_TYPE.round: // default for end cap, beginning cap will overwrite below (this way we're always passing a non-null value, // even if texture coords are disabled) var uvA = zero_v, uvB = one_v, uvC = mid_v; var nA, nB; // first vertex on the lineString if (isBeginning) { nA = normal; nB = neg_normal; if (has_texcoord){ v += 0.5 * context.texcoord_width * context.v_scale; uvA = one_v, uvB = zero_v, uvC = mid_v; // update cap UV order } } // last vertex on the lineString - flip the direction of the cap else { nA = neg_normal; nB = normal; } if (has_texcoord) { zero_v[1] = v, one_v[1] = v, mid_v[1] = v; // update cap UV values } addFan(coord, nA, zero_vec2, nB, // extrusion normal normal, // line normal, for offsets uvA, uvC, uvB, // texture coords (ignored if disabled) true, false, context ); break; case CAP_TYPE.butt: return; } }
[ "function", "addCap", "(", "coord", ",", "v", ",", "normal", ",", "type", ",", "isBeginning", ",", "context", ")", "{", "var", "neg_normal", "=", "Vector", ".", "neg", "(", "normal", ")", ";", "var", "has_texcoord", "=", "(", "context", ".", "texcoord_index", "!=", "null", ")", ";", "switch", "(", "type", ")", "{", "case", "CAP_TYPE", ".", "square", ":", "var", "tangent", ";", "// first vertex on the lineString", "if", "(", "isBeginning", ")", "{", "tangent", "=", "[", "normal", "[", "1", "]", ",", "-", "normal", "[", "0", "]", "]", ";", "addVertex", "(", "coord", ",", "Vector", ".", "add", "(", "normal", ",", "tangent", ")", ",", "normal", ",", "1", ",", "v", ",", "context", ",", "1", ")", ";", "addVertex", "(", "coord", ",", "Vector", ".", "add", "(", "neg_normal", ",", "tangent", ")", ",", "normal", ",", "0", ",", "v", ",", "context", ",", "1", ")", ";", "if", "(", "has_texcoord", ")", "{", "// Add length of square cap to texture coordinate", "v", "+=", "0.5", "*", "context", ".", "texcoord_width", "*", "context", ".", "v_scale", ";", "}", "addVertex", "(", "coord", ",", "normal", ",", "normal", ",", "1", ",", "v", ",", "context", ",", "1", ")", ";", "addVertex", "(", "coord", ",", "neg_normal", ",", "normal", ",", "0", ",", "v", ",", "context", ",", "1", ")", ";", "}", "// last vertex on the lineString", "else", "{", "tangent", "=", "[", "-", "normal", "[", "1", "]", ",", "normal", "[", "0", "]", "]", ";", "addVertex", "(", "coord", ",", "normal", ",", "normal", ",", "1", ",", "v", ",", "context", ",", "1", ")", ";", "addVertex", "(", "coord", ",", "neg_normal", ",", "normal", ",", "0", ",", "v", ",", "context", ",", "1", ")", ";", "if", "(", "has_texcoord", ")", "{", "// Add length of square cap to texture coordinate", "v", "+=", "0.5", "*", "context", ".", "texcoord_width", "*", "context", ".", "v_scale", ";", "}", "addVertex", "(", "coord", ",", "Vector", ".", "add", "(", "normal", ",", "tangent", ")", ",", "normal", ",", "1", ",", "v", ",", "context", ",", "1", ")", ";", "addVertex", "(", "coord", ",", "Vector", ".", "add", "(", "neg_normal", ",", "tangent", ")", ",", "normal", ",", "0", ",", "v", ",", "context", ",", "1", ")", ";", "}", "indexPairs", "(", "1", ",", "context", ")", ";", "break", ";", "case", "CAP_TYPE", ".", "round", ":", "// default for end cap, beginning cap will overwrite below (this way we're always passing a non-null value,", "// even if texture coords are disabled)", "var", "uvA", "=", "zero_v", ",", "uvB", "=", "one_v", ",", "uvC", "=", "mid_v", ";", "var", "nA", ",", "nB", ";", "// first vertex on the lineString", "if", "(", "isBeginning", ")", "{", "nA", "=", "normal", ";", "nB", "=", "neg_normal", ";", "if", "(", "has_texcoord", ")", "{", "v", "+=", "0.5", "*", "context", ".", "texcoord_width", "*", "context", ".", "v_scale", ";", "uvA", "=", "one_v", ",", "uvB", "=", "zero_v", ",", "uvC", "=", "mid_v", ";", "// update cap UV order", "}", "}", "// last vertex on the lineString - flip the direction of the cap", "else", "{", "nA", "=", "neg_normal", ";", "nB", "=", "normal", ";", "}", "if", "(", "has_texcoord", ")", "{", "zero_v", "[", "1", "]", "=", "v", ",", "one_v", "[", "1", "]", "=", "v", ",", "mid_v", "[", "1", "]", "=", "v", ";", "// update cap UV values", "}", "addFan", "(", "coord", ",", "nA", ",", "zero_vec2", ",", "nB", ",", "// extrusion normal", "normal", ",", "// line normal, for offsets", "uvA", ",", "uvC", ",", "uvB", ",", "// texture coords (ignored if disabled)", "true", ",", "false", ",", "context", ")", ";", "break", ";", "case", "CAP_TYPE", ".", "butt", ":", "return", ";", "}", "}" ]
Function to add the vertices needed for line caps, because to re-use the buffers they need to be at the end
[ "Function", "to", "add", "the", "vertices", "needed", "for", "line", "caps", "because", "to", "re", "-", "use", "the", "buffers", "they", "need", "to", "be", "at", "the", "end" ]
e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11
https://github.com/tangrams/tangram/blob/e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11/src/builders/polylines.js#L551-L629
12,023
tangrams/tangram
src/builders/polylines.js
trianglesPerArc
function trianglesPerArc (angle, width) { if (angle < 0) { angle = -angle; } var numTriangles = (width > 2 * MIN_FAN_WIDTH) ? Math.log2(width / MIN_FAN_WIDTH) : 1; return Math.ceil(angle / Math.PI * numTriangles); }
javascript
function trianglesPerArc (angle, width) { if (angle < 0) { angle = -angle; } var numTriangles = (width > 2 * MIN_FAN_WIDTH) ? Math.log2(width / MIN_FAN_WIDTH) : 1; return Math.ceil(angle / Math.PI * numTriangles); }
[ "function", "trianglesPerArc", "(", "angle", ",", "width", ")", "{", "if", "(", "angle", "<", "0", ")", "{", "angle", "=", "-", "angle", ";", "}", "var", "numTriangles", "=", "(", "width", ">", "2", "*", "MIN_FAN_WIDTH", ")", "?", "Math", ".", "log2", "(", "width", "/", "MIN_FAN_WIDTH", ")", ":", "1", ";", "return", "Math", ".", "ceil", "(", "angle", "/", "Math", ".", "PI", "*", "numTriangles", ")", ";", "}" ]
Calculate number of triangles for a fan given an angle and line width
[ "Calculate", "number", "of", "triangles", "for", "a", "fan", "given", "an", "angle", "and", "line", "width" ]
e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11
https://github.com/tangrams/tangram/blob/e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11/src/builders/polylines.js#L632-L639
12,024
tangrams/tangram
src/builders/polylines.js
permuteLine
function permuteLine(line, startIndex){ var newLine = []; for (let i = 0; i < line.length; i++){ var index = (i + startIndex) % line.length; // skip the first (repeated) index if (index !== 0) { newLine.push(line[index]); } } newLine.push(newLine[0]); return newLine; }
javascript
function permuteLine(line, startIndex){ var newLine = []; for (let i = 0; i < line.length; i++){ var index = (i + startIndex) % line.length; // skip the first (repeated) index if (index !== 0) { newLine.push(line[index]); } } newLine.push(newLine[0]); return newLine; }
[ "function", "permuteLine", "(", "line", ",", "startIndex", ")", "{", "var", "newLine", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "line", ".", "length", ";", "i", "++", ")", "{", "var", "index", "=", "(", "i", "+", "startIndex", ")", "%", "line", ".", "length", ";", "// skip the first (repeated) index", "if", "(", "index", "!==", "0", ")", "{", "newLine", ".", "push", "(", "line", "[", "index", "]", ")", ";", "}", "}", "newLine", ".", "push", "(", "newLine", "[", "0", "]", ")", ";", "return", "newLine", ";", "}" ]
Cyclically permute closed line starting at an index
[ "Cyclically", "permute", "closed", "line", "starting", "at", "an", "index" ]
e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11
https://github.com/tangrams/tangram/blob/e1368e3784f143cfdbecbf5a0b0fdaa4b430ed11/src/builders/polylines.js#L642-L653
12,025
expressjs/serve-static
index.js
collapseLeadingSlashes
function collapseLeadingSlashes (str) { for (var i = 0; i < str.length; i++) { if (str.charCodeAt(i) !== 0x2f /* / */) { break } } return i > 1 ? '/' + str.substr(i) : str }
javascript
function collapseLeadingSlashes (str) { for (var i = 0; i < str.length; i++) { if (str.charCodeAt(i) !== 0x2f /* / */) { break } } return i > 1 ? '/' + str.substr(i) : str }
[ "function", "collapseLeadingSlashes", "(", "str", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "str", ".", "length", ";", "i", "++", ")", "{", "if", "(", "str", ".", "charCodeAt", "(", "i", ")", "!==", "0x2f", "/* / */", ")", "{", "break", "}", "}", "return", "i", ">", "1", "?", "'/'", "+", "str", ".", "substr", "(", "i", ")", ":", "str", "}" ]
Collapse all leading slashes into a single slash @private
[ "Collapse", "all", "leading", "slashes", "into", "a", "single", "slash" ]
a8918403e423da80993ecafdec5709d75e06e6c2
https://github.com/expressjs/serve-static/blob/a8918403e423da80993ecafdec5709d75e06e6c2/index.js#L133-L143
12,026
expressjs/serve-static
index.js
createRedirectDirectoryListener
function createRedirectDirectoryListener () { return function redirect (res) { if (this.hasTrailingSlash()) { this.error(404) return } // get original URL var originalUrl = parseUrl.original(this.req) // append trailing slash originalUrl.path = null originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + '/') // reformat the URL var loc = encodeUrl(url.format(originalUrl)) var doc = createHtmlDocument('Redirecting', 'Redirecting to <a href="' + escapeHtml(loc) + '">' + escapeHtml(loc) + '</a>') // send redirect response res.statusCode = 301 res.setHeader('Content-Type', 'text/html; charset=UTF-8') res.setHeader('Content-Length', Buffer.byteLength(doc)) res.setHeader('Content-Security-Policy', "default-src 'self'") res.setHeader('X-Content-Type-Options', 'nosniff') res.setHeader('Location', loc) res.end(doc) } }
javascript
function createRedirectDirectoryListener () { return function redirect (res) { if (this.hasTrailingSlash()) { this.error(404) return } // get original URL var originalUrl = parseUrl.original(this.req) // append trailing slash originalUrl.path = null originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + '/') // reformat the URL var loc = encodeUrl(url.format(originalUrl)) var doc = createHtmlDocument('Redirecting', 'Redirecting to <a href="' + escapeHtml(loc) + '">' + escapeHtml(loc) + '</a>') // send redirect response res.statusCode = 301 res.setHeader('Content-Type', 'text/html; charset=UTF-8') res.setHeader('Content-Length', Buffer.byteLength(doc)) res.setHeader('Content-Security-Policy', "default-src 'self'") res.setHeader('X-Content-Type-Options', 'nosniff') res.setHeader('Location', loc) res.end(doc) } }
[ "function", "createRedirectDirectoryListener", "(", ")", "{", "return", "function", "redirect", "(", "res", ")", "{", "if", "(", "this", ".", "hasTrailingSlash", "(", ")", ")", "{", "this", ".", "error", "(", "404", ")", "return", "}", "// get original URL", "var", "originalUrl", "=", "parseUrl", ".", "original", "(", "this", ".", "req", ")", "// append trailing slash", "originalUrl", ".", "path", "=", "null", "originalUrl", ".", "pathname", "=", "collapseLeadingSlashes", "(", "originalUrl", ".", "pathname", "+", "'/'", ")", "// reformat the URL", "var", "loc", "=", "encodeUrl", "(", "url", ".", "format", "(", "originalUrl", ")", ")", "var", "doc", "=", "createHtmlDocument", "(", "'Redirecting'", ",", "'Redirecting to <a href=\"'", "+", "escapeHtml", "(", "loc", ")", "+", "'\">'", "+", "escapeHtml", "(", "loc", ")", "+", "'</a>'", ")", "// send redirect response", "res", ".", "statusCode", "=", "301", "res", ".", "setHeader", "(", "'Content-Type'", ",", "'text/html; charset=UTF-8'", ")", "res", ".", "setHeader", "(", "'Content-Length'", ",", "Buffer", ".", "byteLength", "(", "doc", ")", ")", "res", ".", "setHeader", "(", "'Content-Security-Policy'", ",", "\"default-src 'self'\"", ")", "res", ".", "setHeader", "(", "'X-Content-Type-Options'", ",", "'nosniff'", ")", "res", ".", "setHeader", "(", "'Location'", ",", "loc", ")", "res", ".", "end", "(", "doc", ")", "}", "}" ]
Create a directory listener that performs a redirect. @private
[ "Create", "a", "directory", "listener", "that", "performs", "a", "redirect", "." ]
a8918403e423da80993ecafdec5709d75e06e6c2
https://github.com/expressjs/serve-static/blob/a8918403e423da80993ecafdec5709d75e06e6c2/index.js#L182-L210
12,027
ModelDepot/tfjs-yolo-tiny
src/index.js
yolo
async function yolo( input, model, { classProbThreshold = DEFAULT_CLASS_PROB_THRESHOLD, iouThreshold = DEFAULT_IOU_THRESHOLD, filterBoxesThreshold = DEFAULT_FILTER_BOXES_THRESHOLD, yoloAnchors = YOLO_ANCHORS, maxBoxes = DEFAULT_MAX_BOXES, width: widthPx = DEFAULT_INPUT_DIM, height: heightPx = DEFAULT_INPUT_DIM, numClasses = 80, classNames = class_names, } = {}, ) { const outs = tf.tidy(() => { // Keep as one var to dispose easier const activation = model.predict(input); const [box_xy, box_wh, box_confidence, box_class_probs ] = yolo_head(activation, yoloAnchors, numClasses); const all_boxes = yolo_boxes_to_corners(box_xy, box_wh); let [boxes, scores, classes] = yolo_filter_boxes( all_boxes, box_confidence, box_class_probs, filterBoxesThreshold); // If all boxes have been filtered out if (boxes == null) { return null; } const width = tf.scalar(widthPx); const height = tf.scalar(heightPx); const image_dims = tf.stack([height, width, height, width]).reshape([1,4]); boxes = tf.mul(boxes, image_dims); return [boxes, scores, classes]; }); if (outs === null) { return []; } const [boxes, scores, classes] = outs; const indices = await tf.image.nonMaxSuppressionAsync(boxes, scores, maxBoxes, iouThreshold) // Pick out data that wasn't filtered out by NMS and put them into // CPU land to pass back to consumer const classes_indx_arr = await classes.gather(indices).data(); const keep_scores = await scores.gather(indices).data(); const boxes_arr = await boxes.gather(indices).data(); tf.dispose(outs); indices.dispose(); const results = []; classes_indx_arr.forEach((class_indx, i) => { const classProb = keep_scores[i]; if (classProb < classProbThreshold) { return; } const className = classNames[class_indx]; let [top, left, bottom, right] = [ boxes_arr[4 * i], boxes_arr[4 * i + 1], boxes_arr[4 * i + 2], boxes_arr[4 * i + 3], ]; top = Math.max(0, top); left = Math.max(0, left); bottom = Math.min(heightPx, bottom); right = Math.min(widthPx, right); const resultObj = { className, classProb, bottom, top, left, right, }; results.push(resultObj); }); return results; }
javascript
async function yolo( input, model, { classProbThreshold = DEFAULT_CLASS_PROB_THRESHOLD, iouThreshold = DEFAULT_IOU_THRESHOLD, filterBoxesThreshold = DEFAULT_FILTER_BOXES_THRESHOLD, yoloAnchors = YOLO_ANCHORS, maxBoxes = DEFAULT_MAX_BOXES, width: widthPx = DEFAULT_INPUT_DIM, height: heightPx = DEFAULT_INPUT_DIM, numClasses = 80, classNames = class_names, } = {}, ) { const outs = tf.tidy(() => { // Keep as one var to dispose easier const activation = model.predict(input); const [box_xy, box_wh, box_confidence, box_class_probs ] = yolo_head(activation, yoloAnchors, numClasses); const all_boxes = yolo_boxes_to_corners(box_xy, box_wh); let [boxes, scores, classes] = yolo_filter_boxes( all_boxes, box_confidence, box_class_probs, filterBoxesThreshold); // If all boxes have been filtered out if (boxes == null) { return null; } const width = tf.scalar(widthPx); const height = tf.scalar(heightPx); const image_dims = tf.stack([height, width, height, width]).reshape([1,4]); boxes = tf.mul(boxes, image_dims); return [boxes, scores, classes]; }); if (outs === null) { return []; } const [boxes, scores, classes] = outs; const indices = await tf.image.nonMaxSuppressionAsync(boxes, scores, maxBoxes, iouThreshold) // Pick out data that wasn't filtered out by NMS and put them into // CPU land to pass back to consumer const classes_indx_arr = await classes.gather(indices).data(); const keep_scores = await scores.gather(indices).data(); const boxes_arr = await boxes.gather(indices).data(); tf.dispose(outs); indices.dispose(); const results = []; classes_indx_arr.forEach((class_indx, i) => { const classProb = keep_scores[i]; if (classProb < classProbThreshold) { return; } const className = classNames[class_indx]; let [top, left, bottom, right] = [ boxes_arr[4 * i], boxes_arr[4 * i + 1], boxes_arr[4 * i + 2], boxes_arr[4 * i + 3], ]; top = Math.max(0, top); left = Math.max(0, left); bottom = Math.min(heightPx, bottom); right = Math.min(widthPx, right); const resultObj = { className, classProb, bottom, top, left, right, }; results.push(resultObj); }); return results; }
[ "async", "function", "yolo", "(", "input", ",", "model", ",", "{", "classProbThreshold", "=", "DEFAULT_CLASS_PROB_THRESHOLD", ",", "iouThreshold", "=", "DEFAULT_IOU_THRESHOLD", ",", "filterBoxesThreshold", "=", "DEFAULT_FILTER_BOXES_THRESHOLD", ",", "yoloAnchors", "=", "YOLO_ANCHORS", ",", "maxBoxes", "=", "DEFAULT_MAX_BOXES", ",", "width", ":", "widthPx", "=", "DEFAULT_INPUT_DIM", ",", "height", ":", "heightPx", "=", "DEFAULT_INPUT_DIM", ",", "numClasses", "=", "80", ",", "classNames", "=", "class_names", ",", "}", "=", "{", "}", ",", ")", "{", "const", "outs", "=", "tf", ".", "tidy", "(", "(", ")", "=>", "{", "// Keep as one var to dispose easier", "const", "activation", "=", "model", ".", "predict", "(", "input", ")", ";", "const", "[", "box_xy", ",", "box_wh", ",", "box_confidence", ",", "box_class_probs", "]", "=", "yolo_head", "(", "activation", ",", "yoloAnchors", ",", "numClasses", ")", ";", "const", "all_boxes", "=", "yolo_boxes_to_corners", "(", "box_xy", ",", "box_wh", ")", ";", "let", "[", "boxes", ",", "scores", ",", "classes", "]", "=", "yolo_filter_boxes", "(", "all_boxes", ",", "box_confidence", ",", "box_class_probs", ",", "filterBoxesThreshold", ")", ";", "// If all boxes have been filtered out", "if", "(", "boxes", "==", "null", ")", "{", "return", "null", ";", "}", "const", "width", "=", "tf", ".", "scalar", "(", "widthPx", ")", ";", "const", "height", "=", "tf", ".", "scalar", "(", "heightPx", ")", ";", "const", "image_dims", "=", "tf", ".", "stack", "(", "[", "height", ",", "width", ",", "height", ",", "width", "]", ")", ".", "reshape", "(", "[", "1", ",", "4", "]", ")", ";", "boxes", "=", "tf", ".", "mul", "(", "boxes", ",", "image_dims", ")", ";", "return", "[", "boxes", ",", "scores", ",", "classes", "]", ";", "}", ")", ";", "if", "(", "outs", "===", "null", ")", "{", "return", "[", "]", ";", "}", "const", "[", "boxes", ",", "scores", ",", "classes", "]", "=", "outs", ";", "const", "indices", "=", "await", "tf", ".", "image", ".", "nonMaxSuppressionAsync", "(", "boxes", ",", "scores", ",", "maxBoxes", ",", "iouThreshold", ")", "// Pick out data that wasn't filtered out by NMS and put them into", "// CPU land to pass back to consumer", "const", "classes_indx_arr", "=", "await", "classes", ".", "gather", "(", "indices", ")", ".", "data", "(", ")", ";", "const", "keep_scores", "=", "await", "scores", ".", "gather", "(", "indices", ")", ".", "data", "(", ")", ";", "const", "boxes_arr", "=", "await", "boxes", ".", "gather", "(", "indices", ")", ".", "data", "(", ")", ";", "tf", ".", "dispose", "(", "outs", ")", ";", "indices", ".", "dispose", "(", ")", ";", "const", "results", "=", "[", "]", ";", "classes_indx_arr", ".", "forEach", "(", "(", "class_indx", ",", "i", ")", "=>", "{", "const", "classProb", "=", "keep_scores", "[", "i", "]", ";", "if", "(", "classProb", "<", "classProbThreshold", ")", "{", "return", ";", "}", "const", "className", "=", "classNames", "[", "class_indx", "]", ";", "let", "[", "top", ",", "left", ",", "bottom", ",", "right", "]", "=", "[", "boxes_arr", "[", "4", "*", "i", "]", ",", "boxes_arr", "[", "4", "*", "i", "+", "1", "]", ",", "boxes_arr", "[", "4", "*", "i", "+", "2", "]", ",", "boxes_arr", "[", "4", "*", "i", "+", "3", "]", ",", "]", ";", "top", "=", "Math", ".", "max", "(", "0", ",", "top", ")", ";", "left", "=", "Math", ".", "max", "(", "0", ",", "left", ")", ";", "bottom", "=", "Math", ".", "min", "(", "heightPx", ",", "bottom", ")", ";", "right", "=", "Math", ".", "min", "(", "widthPx", ",", "right", ")", ";", "const", "resultObj", "=", "{", "className", ",", "classProb", ",", "bottom", ",", "top", ",", "left", ",", "right", ",", "}", ";", "results", ".", "push", "(", "resultObj", ")", ";", "}", ")", ";", "return", "results", ";", "}" ]
Given an input image and model, outputs bounding boxes of detected objects with class labels and class probabilities. @param {tf.Tensor} input Expected shape (1, 416, 416, 3) Tensor representing input image (RGB 416x416) @param {tf.Model} model Tiny YOLO model to use @param {Object} [options] Override options for customized models or performance @param {Number} [options.classProbThreshold=0.4] Filter out classes below a certain threshold @param {Number} [options.iouThreshold=0.4] Filter out boxes that have an IoU greater than this threadhold (refer to tf.image.nonMaxSuppression) @param {Number} [options.filterBoxesThreshold=0.01] Threshold to filter out box confidence * class confidence @param {Number} [options.maxBoxes=2048] Number of max boxes to return, refer to tf.image.nonMaxSuppression. Note: The model itself can only return so many boxes. @param {tf.Tensor} [options.yoloAnchors=See src/postprocessing.js] (Advanced) Yolo Anchor Boxes, only needed if retraining on a new dataset @param {Number} [options.width=416] (Advanced) If your model's input width is not 416, only if you're using a custom model @param {Number} [options.height=416] (Advanced) If your model's input height is not 416, only if you're using a custom model @param {Number} [options.numClasses=80] (Advanced) If your model has a different number of classes, only if you're using a custom model @param {Array<String>} [options.classNames=See src/coco_classes.js] (Advanced) If your model has non-MSCOCO class names, only if you're using a custom model @returns {Array<Object>} An array of found objects with `className`, `classProb`, `bottom`, `top`, `left`, `right`. Positions are in pixel values. `classProb` ranges from 0 to 1. `className` is derived from `options.classNames`.
[ "Given", "an", "input", "image", "and", "model", "outputs", "bounding", "boxes", "of", "detected", "objects", "with", "class", "labels", "and", "class", "probabilities", "." ]
bfd5562aca0c832553d0f02244cf0d92f20de5c8
https://github.com/ModelDepot/tfjs-yolo-tiny/blob/bfd5562aca0c832553d0f02244cf0d92f20de5c8/src/index.js#L57-L149
12,028
jamhall/s3rver
lib/middleware/website.js
redirect
function redirect(url) { // unset headers const { res } = this; res .getHeaderNames() .filter(name => !name.match(/^access-control-|vary|x-amz-/i)) .forEach(name => res.removeHeader(name)); this.set("Location", url); // status if (!statuses.redirect[this.status]) this.status = 302; if (this.status === 302) { const redirect = new S3Error("Found", "Resource Found"); redirect.description = "302 Moved Temporarily"; this.body = redirect.toHTML(); this.type = "text/html"; } else { this.body = ""; this.type = ""; } }
javascript
function redirect(url) { // unset headers const { res } = this; res .getHeaderNames() .filter(name => !name.match(/^access-control-|vary|x-amz-/i)) .forEach(name => res.removeHeader(name)); this.set("Location", url); // status if (!statuses.redirect[this.status]) this.status = 302; if (this.status === 302) { const redirect = new S3Error("Found", "Resource Found"); redirect.description = "302 Moved Temporarily"; this.body = redirect.toHTML(); this.type = "text/html"; } else { this.body = ""; this.type = ""; } }
[ "function", "redirect", "(", "url", ")", "{", "// unset headers", "const", "{", "res", "}", "=", "this", ";", "res", ".", "getHeaderNames", "(", ")", ".", "filter", "(", "name", "=>", "!", "name", ".", "match", "(", "/", "^access-control-|vary|x-amz-", "/", "i", ")", ")", ".", "forEach", "(", "name", "=>", "res", ".", "removeHeader", "(", "name", ")", ")", ";", "this", ".", "set", "(", "\"Location\"", ",", "url", ")", ";", "// status", "if", "(", "!", "statuses", ".", "redirect", "[", "this", ".", "status", "]", ")", "this", ".", "status", "=", "302", ";", "if", "(", "this", ".", "status", "===", "302", ")", "{", "const", "redirect", "=", "new", "S3Error", "(", "\"Found\"", ",", "\"Resource Found\"", ")", ";", "redirect", ".", "description", "=", "\"302 Moved Temporarily\"", ";", "this", ".", "body", "=", "redirect", ".", "toHTML", "(", ")", ";", "this", ".", "type", "=", "\"text/html\"", ";", "}", "else", "{", "this", ".", "body", "=", "\"\"", ";", "this", ".", "type", "=", "\"\"", ";", "}", "}" ]
Overrides Koa's redirect behavior with one more closely matching S3 @param {string} url
[ "Overrides", "Koa", "s", "redirect", "behavior", "with", "one", "more", "closely", "matching", "S3" ]
9d24058ecb0abfc49781f2f2cb7389ab5f6b09c7
https://github.com/jamhall/s3rver/blob/9d24058ecb0abfc49781f2f2cb7389ab5f6b09c7/lib/middleware/website.js#L126-L148
12,029
jamhall/s3rver
lib/middleware/website.js
onerror
async function onerror(err) { // don't do anything if there is no error. // this allows you to pass `this.onerror` // to node-style callbacks. if (null == err) return; if (!(err instanceof Error)) err = new Error(format("non-error thrown: %j", err)); let headerSent = false; if (this.headerSent || !this.writable) { headerSent = err.headerSent = true; } // delegate this.app.emit("error", err, this); // nothing we can do here other // than delegate to the app-level // handler and log. if (headerSent) { return; } const { res } = this; if (!(err instanceof S3Error)) { err = S3Error.fromError(err); } // first unset all headers res .getHeaderNames() .filter(name => !name.match(/^access-control-|vary|x-amz-/i)) .forEach(name => res.removeHeader(name)); // (the presence of x-amz-error-* headers needs additional research) // this.set(err.headers); // force text/html this.type = "text/html"; if (!err.description) err.description = `${err.status} ${statuses[err.status]}`; // respond const { website } = this.state; if ( err.code !== "NoSuchBucket" && err.code !== "UnsupportedQuery" && website.errorDocumentKey ) { // attempt to serve error document const object = await this.store.getObject( this.params.bucket, website.errorDocumentKey ); if (object) { const objectRedirectLocation = object.metadata["x-amz-website-redirect-location"]; if (objectRedirectLocation) { object.content.destroy(); this.status = 301; this.redirect(objectRedirectLocation); res.end(this.body); } else { this.type = object.metadata["content-type"]; this.length = object.size; object.content.pipe(res); } return; } this.logger.error( "Custom Error Document not found: " + website.errorDocumentKey ); const errorDocumentErr = new S3Error( "NoSuchKey", "The specified key does not exist.", { Key: website.errorDocumentKey } ); errorDocumentErr.description = "An Error Occurred While Attempting to Retrieve a Custom Error Document"; err.errors.push(errorDocumentErr); } const msg = err.toHTML(); this.status = err.status; this.length = Buffer.byteLength(msg); res.end(msg); }
javascript
async function onerror(err) { // don't do anything if there is no error. // this allows you to pass `this.onerror` // to node-style callbacks. if (null == err) return; if (!(err instanceof Error)) err = new Error(format("non-error thrown: %j", err)); let headerSent = false; if (this.headerSent || !this.writable) { headerSent = err.headerSent = true; } // delegate this.app.emit("error", err, this); // nothing we can do here other // than delegate to the app-level // handler and log. if (headerSent) { return; } const { res } = this; if (!(err instanceof S3Error)) { err = S3Error.fromError(err); } // first unset all headers res .getHeaderNames() .filter(name => !name.match(/^access-control-|vary|x-amz-/i)) .forEach(name => res.removeHeader(name)); // (the presence of x-amz-error-* headers needs additional research) // this.set(err.headers); // force text/html this.type = "text/html"; if (!err.description) err.description = `${err.status} ${statuses[err.status]}`; // respond const { website } = this.state; if ( err.code !== "NoSuchBucket" && err.code !== "UnsupportedQuery" && website.errorDocumentKey ) { // attempt to serve error document const object = await this.store.getObject( this.params.bucket, website.errorDocumentKey ); if (object) { const objectRedirectLocation = object.metadata["x-amz-website-redirect-location"]; if (objectRedirectLocation) { object.content.destroy(); this.status = 301; this.redirect(objectRedirectLocation); res.end(this.body); } else { this.type = object.metadata["content-type"]; this.length = object.size; object.content.pipe(res); } return; } this.logger.error( "Custom Error Document not found: " + website.errorDocumentKey ); const errorDocumentErr = new S3Error( "NoSuchKey", "The specified key does not exist.", { Key: website.errorDocumentKey } ); errorDocumentErr.description = "An Error Occurred While Attempting to Retrieve a Custom Error Document"; err.errors.push(errorDocumentErr); } const msg = err.toHTML(); this.status = err.status; this.length = Buffer.byteLength(msg); res.end(msg); }
[ "async", "function", "onerror", "(", "err", ")", "{", "// don't do anything if there is no error.", "// this allows you to pass `this.onerror`", "// to node-style callbacks.", "if", "(", "null", "==", "err", ")", "return", ";", "if", "(", "!", "(", "err", "instanceof", "Error", ")", ")", "err", "=", "new", "Error", "(", "format", "(", "\"non-error thrown: %j\"", ",", "err", ")", ")", ";", "let", "headerSent", "=", "false", ";", "if", "(", "this", ".", "headerSent", "||", "!", "this", ".", "writable", ")", "{", "headerSent", "=", "err", ".", "headerSent", "=", "true", ";", "}", "// delegate", "this", ".", "app", ".", "emit", "(", "\"error\"", ",", "err", ",", "this", ")", ";", "// nothing we can do here other", "// than delegate to the app-level", "// handler and log.", "if", "(", "headerSent", ")", "{", "return", ";", "}", "const", "{", "res", "}", "=", "this", ";", "if", "(", "!", "(", "err", "instanceof", "S3Error", ")", ")", "{", "err", "=", "S3Error", ".", "fromError", "(", "err", ")", ";", "}", "// first unset all headers", "res", ".", "getHeaderNames", "(", ")", ".", "filter", "(", "name", "=>", "!", "name", ".", "match", "(", "/", "^access-control-|vary|x-amz-", "/", "i", ")", ")", ".", "forEach", "(", "name", "=>", "res", ".", "removeHeader", "(", "name", ")", ")", ";", "// (the presence of x-amz-error-* headers needs additional research)", "// this.set(err.headers);", "// force text/html", "this", ".", "type", "=", "\"text/html\"", ";", "if", "(", "!", "err", ".", "description", ")", "err", ".", "description", "=", "`", "${", "err", ".", "status", "}", "${", "statuses", "[", "err", ".", "status", "]", "}", "`", ";", "// respond", "const", "{", "website", "}", "=", "this", ".", "state", ";", "if", "(", "err", ".", "code", "!==", "\"NoSuchBucket\"", "&&", "err", ".", "code", "!==", "\"UnsupportedQuery\"", "&&", "website", ".", "errorDocumentKey", ")", "{", "// attempt to serve error document", "const", "object", "=", "await", "this", ".", "store", ".", "getObject", "(", "this", ".", "params", ".", "bucket", ",", "website", ".", "errorDocumentKey", ")", ";", "if", "(", "object", ")", "{", "const", "objectRedirectLocation", "=", "object", ".", "metadata", "[", "\"x-amz-website-redirect-location\"", "]", ";", "if", "(", "objectRedirectLocation", ")", "{", "object", ".", "content", ".", "destroy", "(", ")", ";", "this", ".", "status", "=", "301", ";", "this", ".", "redirect", "(", "objectRedirectLocation", ")", ";", "res", ".", "end", "(", "this", ".", "body", ")", ";", "}", "else", "{", "this", ".", "type", "=", "object", ".", "metadata", "[", "\"content-type\"", "]", ";", "this", ".", "length", "=", "object", ".", "size", ";", "object", ".", "content", ".", "pipe", "(", "res", ")", ";", "}", "return", ";", "}", "this", ".", "logger", ".", "error", "(", "\"Custom Error Document not found: \"", "+", "website", ".", "errorDocumentKey", ")", ";", "const", "errorDocumentErr", "=", "new", "S3Error", "(", "\"NoSuchKey\"", ",", "\"The specified key does not exist.\"", ",", "{", "Key", ":", "website", ".", "errorDocumentKey", "}", ")", ";", "errorDocumentErr", ".", "description", "=", "\"An Error Occurred While Attempting to Retrieve a Custom Error Document\"", ";", "err", ".", "errors", ".", "push", "(", "errorDocumentErr", ")", ";", "}", "const", "msg", "=", "err", ".", "toHTML", "(", ")", ";", "this", ".", "status", "=", "err", ".", "status", ";", "this", ".", "length", "=", "Buffer", ".", "byteLength", "(", "msg", ")", ";", "res", ".", "end", "(", "msg", ")", ";", "}" ]
Koa context.onerror handler modified to write a HTML-formatted response body @param {Error} err
[ "Koa", "context", ".", "onerror", "handler", "modified", "to", "write", "a", "HTML", "-", "formatted", "response", "body" ]
9d24058ecb0abfc49781f2f2cb7389ab5f6b09c7
https://github.com/jamhall/s3rver/blob/9d24058ecb0abfc49781f2f2cb7389ab5f6b09c7/lib/middleware/website.js#L154-L243
12,030
jamhall/s3rver
lib/middleware/authentication.js
getStringToSign
function getStringToSign(canonicalRequest) { return [ canonicalRequest.method, canonicalRequest.contentMD5, canonicalRequest.contentType, canonicalRequest.timestamp, ...canonicalRequest.amzHeaders, canonicalRequest.querystring ? `${canonicalRequest.uri}?${canonicalRequest.querystring}` : canonicalRequest.uri ].join("\n"); }
javascript
function getStringToSign(canonicalRequest) { return [ canonicalRequest.method, canonicalRequest.contentMD5, canonicalRequest.contentType, canonicalRequest.timestamp, ...canonicalRequest.amzHeaders, canonicalRequest.querystring ? `${canonicalRequest.uri}?${canonicalRequest.querystring}` : canonicalRequest.uri ].join("\n"); }
[ "function", "getStringToSign", "(", "canonicalRequest", ")", "{", "return", "[", "canonicalRequest", ".", "method", ",", "canonicalRequest", ".", "contentMD5", ",", "canonicalRequest", ".", "contentType", ",", "canonicalRequest", ".", "timestamp", ",", "...", "canonicalRequest", ".", "amzHeaders", ",", "canonicalRequest", ".", "querystring", "?", "`", "${", "canonicalRequest", ".", "uri", "}", "${", "canonicalRequest", ".", "querystring", "}", "`", ":", "canonicalRequest", ".", "uri", "]", ".", "join", "(", "\"\\n\"", ")", ";", "}" ]
Generates a string to be signed for the specified signature version. (currently only generates strings for V2 signing) @param {*} canonicalRequest
[ "Generates", "a", "string", "to", "be", "signed", "for", "the", "specified", "signature", "version", "." ]
9d24058ecb0abfc49781f2f2cb7389ab5f6b09c7
https://github.com/jamhall/s3rver/blob/9d24058ecb0abfc49781f2f2cb7389ab5f6b09c7/lib/middleware/authentication.js#L453-L464
12,031
jamhall/s3rver
lib/middleware/authentication.js
calculateSignature
function calculateSignature(stringToSign, signingKey, algorithm) { const signature = createHmac(algorithm, signingKey); signature.update(stringToSign, "utf8"); return signature.digest("base64"); }
javascript
function calculateSignature(stringToSign, signingKey, algorithm) { const signature = createHmac(algorithm, signingKey); signature.update(stringToSign, "utf8"); return signature.digest("base64"); }
[ "function", "calculateSignature", "(", "stringToSign", ",", "signingKey", ",", "algorithm", ")", "{", "const", "signature", "=", "createHmac", "(", "algorithm", ",", "signingKey", ")", ";", "signature", ".", "update", "(", "stringToSign", ",", "\"utf8\"", ")", ";", "return", "signature", ".", "digest", "(", "\"base64\"", ")", ";", "}" ]
Performs the calculation of an authentication code for a string using the specified key and algorithm. @param {String} stringToSign the string representation of a canonical request @param {String} signingKey a secret access key for V2 signing, or a signing key for V4 signing @param {String} algorithm should be one of "sha1" or "sha256"
[ "Performs", "the", "calculation", "of", "an", "authentication", "code", "for", "a", "string", "using", "the", "specified", "key", "and", "algorithm", "." ]
9d24058ecb0abfc49781f2f2cb7389ab5f6b09c7
https://github.com/jamhall/s3rver/blob/9d24058ecb0abfc49781f2f2cb7389ab5f6b09c7/lib/middleware/authentication.js#L474-L478
12,032
jamhall/s3rver
lib/s3rver.js
onerror
function onerror(err) { // don't do anything if there is no error. // this allows you to pass `this.onerror` // to node-style callbacks. if (null == err) return; if (!(err instanceof Error)) err = new Error(format("non-error thrown: %j", err)); let headerSent = false; if (this.headerSent || !this.writable) { headerSent = err.headerSent = true; } // delegate this.app.emit("error", err, this); // nothing we can do here other // than delegate to the app-level // handler and log. if (headerSent) { return; } const { res } = this; if (!(err instanceof S3Error)) { err = S3Error.fromError(err); } // first unset all headers res .getHeaderNames() .filter(name => !name.match(/^access-control-|vary|x-amz-/i)) .forEach(name => res.removeHeader(name)); // (the presence of x-amz-error-* headers needs additional research) // this.set(err.headers); // force application/xml this.type = "application/xml"; // respond const msg = err.toXML(); this.status = err.status; this.length = Buffer.byteLength(msg); res.end(msg); }
javascript
function onerror(err) { // don't do anything if there is no error. // this allows you to pass `this.onerror` // to node-style callbacks. if (null == err) return; if (!(err instanceof Error)) err = new Error(format("non-error thrown: %j", err)); let headerSent = false; if (this.headerSent || !this.writable) { headerSent = err.headerSent = true; } // delegate this.app.emit("error", err, this); // nothing we can do here other // than delegate to the app-level // handler and log. if (headerSent) { return; } const { res } = this; if (!(err instanceof S3Error)) { err = S3Error.fromError(err); } // first unset all headers res .getHeaderNames() .filter(name => !name.match(/^access-control-|vary|x-amz-/i)) .forEach(name => res.removeHeader(name)); // (the presence of x-amz-error-* headers needs additional research) // this.set(err.headers); // force application/xml this.type = "application/xml"; // respond const msg = err.toXML(); this.status = err.status; this.length = Buffer.byteLength(msg); res.end(msg); }
[ "function", "onerror", "(", "err", ")", "{", "// don't do anything if there is no error.", "// this allows you to pass `this.onerror`", "// to node-style callbacks.", "if", "(", "null", "==", "err", ")", "return", ";", "if", "(", "!", "(", "err", "instanceof", "Error", ")", ")", "err", "=", "new", "Error", "(", "format", "(", "\"non-error thrown: %j\"", ",", "err", ")", ")", ";", "let", "headerSent", "=", "false", ";", "if", "(", "this", ".", "headerSent", "||", "!", "this", ".", "writable", ")", "{", "headerSent", "=", "err", ".", "headerSent", "=", "true", ";", "}", "// delegate", "this", ".", "app", ".", "emit", "(", "\"error\"", ",", "err", ",", "this", ")", ";", "// nothing we can do here other", "// than delegate to the app-level", "// handler and log.", "if", "(", "headerSent", ")", "{", "return", ";", "}", "const", "{", "res", "}", "=", "this", ";", "if", "(", "!", "(", "err", "instanceof", "S3Error", ")", ")", "{", "err", "=", "S3Error", ".", "fromError", "(", "err", ")", ";", "}", "// first unset all headers", "res", ".", "getHeaderNames", "(", ")", ".", "filter", "(", "name", "=>", "!", "name", ".", "match", "(", "/", "^access-control-|vary|x-amz-", "/", "i", ")", ")", ".", "forEach", "(", "name", "=>", "res", ".", "removeHeader", "(", "name", ")", ")", ";", "// (the presence of x-amz-error-* headers needs additional research)", "// this.set(err.headers);", "// force application/xml", "this", ".", "type", "=", "\"application/xml\"", ";", "// respond", "const", "msg", "=", "err", ".", "toXML", "(", ")", ";", "this", ".", "status", "=", "err", ".", "status", ";", "this", ".", "length", "=", "Buffer", ".", "byteLength", "(", "msg", ")", ";", "res", ".", "end", "(", "msg", ")", ";", "}" ]
Koa context.onerror handler modified to write a XML-formatted response body @param {Error} err
[ "Koa", "context", ".", "onerror", "handler", "modified", "to", "write", "a", "XML", "-", "formatted", "response", "body" ]
9d24058ecb0abfc49781f2f2cb7389ab5f6b09c7
https://github.com/jamhall/s3rver/blob/9d24058ecb0abfc49781f2f2cb7389ab5f6b09c7/lib/s3rver.js#L209-L256
12,033
MONEI/Shopify-api-node
index.js
Shopify
function Shopify(options) { if (!(this instanceof Shopify)) return new Shopify(options); if ( !options || !options.shopName || !options.accessToken && (!options.apiKey || !options.password) || options.accessToken && (options.apiKey || options.password) ) { throw new Error('Missing or invalid options'); } EventEmitter.call(this); this.options = defaults(options, { timeout: 60000 }); // // API call limits, updated with each request. // this.callLimits = { remaining: undefined, current: undefined, max: undefined }; this.baseUrl = { auth: !options.accessToken && `${options.apiKey}:${options.password}`, hostname: !options.shopName.endsWith('.myshopify.com') ? `${options.shopName}.myshopify.com` : options.shopName, protocol: 'https:' }; if (options.autoLimit) { const conf = transform(options.autoLimit, (result, value, key) => { if (key === 'calls') key = 'limit'; result[key] = value; }, { bucketSize: 35 }); this.request = stopcock(this.request, conf); } }
javascript
function Shopify(options) { if (!(this instanceof Shopify)) return new Shopify(options); if ( !options || !options.shopName || !options.accessToken && (!options.apiKey || !options.password) || options.accessToken && (options.apiKey || options.password) ) { throw new Error('Missing or invalid options'); } EventEmitter.call(this); this.options = defaults(options, { timeout: 60000 }); // // API call limits, updated with each request. // this.callLimits = { remaining: undefined, current: undefined, max: undefined }; this.baseUrl = { auth: !options.accessToken && `${options.apiKey}:${options.password}`, hostname: !options.shopName.endsWith('.myshopify.com') ? `${options.shopName}.myshopify.com` : options.shopName, protocol: 'https:' }; if (options.autoLimit) { const conf = transform(options.autoLimit, (result, value, key) => { if (key === 'calls') key = 'limit'; result[key] = value; }, { bucketSize: 35 }); this.request = stopcock(this.request, conf); } }
[ "function", "Shopify", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Shopify", ")", ")", "return", "new", "Shopify", "(", "options", ")", ";", "if", "(", "!", "options", "||", "!", "options", ".", "shopName", "||", "!", "options", ".", "accessToken", "&&", "(", "!", "options", ".", "apiKey", "||", "!", "options", ".", "password", ")", "||", "options", ".", "accessToken", "&&", "(", "options", ".", "apiKey", "||", "options", ".", "password", ")", ")", "{", "throw", "new", "Error", "(", "'Missing or invalid options'", ")", ";", "}", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "options", "=", "defaults", "(", "options", ",", "{", "timeout", ":", "60000", "}", ")", ";", "//", "// API call limits, updated with each request.", "//", "this", ".", "callLimits", "=", "{", "remaining", ":", "undefined", ",", "current", ":", "undefined", ",", "max", ":", "undefined", "}", ";", "this", ".", "baseUrl", "=", "{", "auth", ":", "!", "options", ".", "accessToken", "&&", "`", "${", "options", ".", "apiKey", "}", "${", "options", ".", "password", "}", "`", ",", "hostname", ":", "!", "options", ".", "shopName", ".", "endsWith", "(", "'.myshopify.com'", ")", "?", "`", "${", "options", ".", "shopName", "}", "`", ":", "options", ".", "shopName", ",", "protocol", ":", "'https:'", "}", ";", "if", "(", "options", ".", "autoLimit", ")", "{", "const", "conf", "=", "transform", "(", "options", ".", "autoLimit", ",", "(", "result", ",", "value", ",", "key", ")", "=>", "{", "if", "(", "key", "===", "'calls'", ")", "key", "=", "'limit'", ";", "result", "[", "key", "]", "=", "value", ";", "}", ",", "{", "bucketSize", ":", "35", "}", ")", ";", "this", ".", "request", "=", "stopcock", "(", "this", ".", "request", ",", "conf", ")", ";", "}", "}" ]
Creates a Shopify instance. @param {Object} options Configuration options @param {String} options.shopName The name of the shop @param {String} options.apiKey The API Key @param {String} options.password The private app password @param {String} options.accessToken The persistent OAuth public app token @param {Boolean|Object} [options.autoLimit] Limits the request rate @param {Number} [options.timeout] The request timeout @constructor @public
[ "Creates", "a", "Shopify", "instance", "." ]
a7bd0d41a9a47478e32ab46546977982092cc960
https://github.com/MONEI/Shopify-api-node/blob/a7bd0d41a9a47478e32ab46546977982092cc960/index.js#L28-L67
12,034
prescottprue/redux-firestore
src/reducers/listenersReducer.js
listenersById
function listenersById(state = {}, { type, path, payload }) { switch (type) { case actionTypes.SET_LISTENER: return { ...state, [payload.name]: { name: payload.name, path, }, }; case actionTypes.UNSET_LISTENER: return omit(state, [payload.name]); default: return state; } }
javascript
function listenersById(state = {}, { type, path, payload }) { switch (type) { case actionTypes.SET_LISTENER: return { ...state, [payload.name]: { name: payload.name, path, }, }; case actionTypes.UNSET_LISTENER: return omit(state, [payload.name]); default: return state; } }
[ "function", "listenersById", "(", "state", "=", "{", "}", ",", "{", "type", ",", "path", ",", "payload", "}", ")", "{", "switch", "(", "type", ")", "{", "case", "actionTypes", ".", "SET_LISTENER", ":", "return", "{", "...", "state", ",", "[", "payload", ".", "name", "]", ":", "{", "name", ":", "payload", ".", "name", ",", "path", ",", "}", ",", "}", ";", "case", "actionTypes", ".", "UNSET_LISTENER", ":", "return", "omit", "(", "state", ",", "[", "payload", ".", "name", "]", ")", ";", "default", ":", "return", "state", ";", "}", "}" ]
Reducer for listeners ids. Changed by `SET_LISTENER` and `UNSET_LISTENER` actions. @param {Object} [state={}] - Current listenersById redux state @param {Object} action - Object containing the action that was dispatched @param {String} action.type - Type of action that was dispatched @return {Object} listenersById state after reduction (used in listeners) @private
[ "Reducer", "for", "listeners", "ids", ".", "Changed", "by", "SET_LISTENER", "and", "UNSET_LISTENER", "actions", "." ]
cd9eb5c580e9e69886d4f1df1929c45adbe6081f
https://github.com/prescottprue/redux-firestore/blob/cd9eb5c580e9e69886d4f1df1929c45adbe6081f/src/reducers/listenersReducer.js#L14-L29
12,035
prescottprue/redux-firestore
src/reducers/listenersReducer.js
allListeners
function allListeners(state = [], { type, payload }) { switch (type) { case actionTypes.SET_LISTENER: return [...state, payload.name]; case actionTypes.UNSET_LISTENER: return state.filter(name => name !== payload.name); default: return state; } }
javascript
function allListeners(state = [], { type, payload }) { switch (type) { case actionTypes.SET_LISTENER: return [...state, payload.name]; case actionTypes.UNSET_LISTENER: return state.filter(name => name !== payload.name); default: return state; } }
[ "function", "allListeners", "(", "state", "=", "[", "]", ",", "{", "type", ",", "payload", "}", ")", "{", "switch", "(", "type", ")", "{", "case", "actionTypes", ".", "SET_LISTENER", ":", "return", "[", "...", "state", ",", "payload", ".", "name", "]", ";", "case", "actionTypes", ".", "UNSET_LISTENER", ":", "return", "state", ".", "filter", "(", "name", "=>", "name", "!==", "payload", ".", "name", ")", ";", "default", ":", "return", "state", ";", "}", "}" ]
Reducer for listeners state. Changed by `ERROR` and `LOGOUT` actions. @param {Object} [state=[]] - Current authError redux state @param {Object} action - Object containing the action that was dispatched @param {String} action.type - Type of action that was dispatched @return {Object} allListeners state after reduction (used in listeners) @private
[ "Reducer", "for", "listeners", "state", ".", "Changed", "by", "ERROR", "and", "LOGOUT", "actions", "." ]
cd9eb5c580e9e69886d4f1df1929c45adbe6081f
https://github.com/prescottprue/redux-firestore/blob/cd9eb5c580e9e69886d4f1df1929c45adbe6081f/src/reducers/listenersReducer.js#L39-L48
12,036
prescottprue/redux-firestore
src/reducers/orderedReducer.js
addDoc
function addDoc(array = [], action) { const { meta, payload } = action; if (!meta.subcollections || meta.storeAs) { return [ ...array.slice(0, payload.ordered.newIndex), { id: meta.doc, ...payload.data }, ...array.slice(payload.ordered.newIndex), ]; } // Add doc to subcollection by modifying the existing doc at this level return modifyDoc(array, action); }
javascript
function addDoc(array = [], action) { const { meta, payload } = action; if (!meta.subcollections || meta.storeAs) { return [ ...array.slice(0, payload.ordered.newIndex), { id: meta.doc, ...payload.data }, ...array.slice(payload.ordered.newIndex), ]; } // Add doc to subcollection by modifying the existing doc at this level return modifyDoc(array, action); }
[ "function", "addDoc", "(", "array", "=", "[", "]", ",", "action", ")", "{", "const", "{", "meta", ",", "payload", "}", "=", "action", ";", "if", "(", "!", "meta", ".", "subcollections", "||", "meta", ".", "storeAs", ")", "{", "return", "[", "...", "array", ".", "slice", "(", "0", ",", "payload", ".", "ordered", ".", "newIndex", ")", ",", "{", "id", ":", "meta", ".", "doc", ",", "...", "payload", ".", "data", "}", ",", "...", "array", ".", "slice", "(", "payload", ".", "ordered", ".", "newIndex", ")", ",", "]", ";", "}", "// Add doc to subcollection by modifying the existing doc at this level", "return", "modifyDoc", "(", "array", ",", "action", ")", ";", "}" ]
Case reducer for adding a document to a collection or subcollection. @param {Array} [array=[]] - Redux state of current collection @param {Object} action - The action that was dispatched @return {Array} State with document modified
[ "Case", "reducer", "for", "adding", "a", "document", "to", "a", "collection", "or", "subcollection", "." ]
cd9eb5c580e9e69886d4f1df1929c45adbe6081f
https://github.com/prescottprue/redux-firestore/blob/cd9eb5c580e9e69886d4f1df1929c45adbe6081f/src/reducers/orderedReducer.js#L58-L70
12,037
prescottprue/redux-firestore
src/reducers/orderedReducer.js
removeDoc
function removeDoc(array, action) { // Update is at doc level (not subcollection level) if (!action.meta.subcollections || action.meta.storeAs) { // Remove doc from collection array return reject(array, { id: action.meta.doc }); // returns a new array } // Update is at subcollection level const subcollectionSetting = action.meta.subcollections[0]; // Meta does not contain doc, remove whole subcollection if (!subcollectionSetting.doc) { return updateItemInArray( array, action.meta.doc, item => omit(item, [subcollectionSetting.collection]), // omit creates a new object ); } // Meta contains doc setting, remove doc from subcollection return updateItemInArray(array, action.meta.doc, item => { const subcollectionVal = get(item, subcollectionSetting.collection, []); // Subcollection exists within doc, update item within subcollection if (subcollectionVal.length) { return { ...item, [subcollectionSetting.collection]: reject(array, { id: subcollectionSetting.doc, }), }; } // Item does not contain subcollection return item; }); }
javascript
function removeDoc(array, action) { // Update is at doc level (not subcollection level) if (!action.meta.subcollections || action.meta.storeAs) { // Remove doc from collection array return reject(array, { id: action.meta.doc }); // returns a new array } // Update is at subcollection level const subcollectionSetting = action.meta.subcollections[0]; // Meta does not contain doc, remove whole subcollection if (!subcollectionSetting.doc) { return updateItemInArray( array, action.meta.doc, item => omit(item, [subcollectionSetting.collection]), // omit creates a new object ); } // Meta contains doc setting, remove doc from subcollection return updateItemInArray(array, action.meta.doc, item => { const subcollectionVal = get(item, subcollectionSetting.collection, []); // Subcollection exists within doc, update item within subcollection if (subcollectionVal.length) { return { ...item, [subcollectionSetting.collection]: reject(array, { id: subcollectionSetting.doc, }), }; } // Item does not contain subcollection return item; }); }
[ "function", "removeDoc", "(", "array", ",", "action", ")", "{", "// Update is at doc level (not subcollection level)", "if", "(", "!", "action", ".", "meta", ".", "subcollections", "||", "action", ".", "meta", ".", "storeAs", ")", "{", "// Remove doc from collection array", "return", "reject", "(", "array", ",", "{", "id", ":", "action", ".", "meta", ".", "doc", "}", ")", ";", "// returns a new array", "}", "// Update is at subcollection level", "const", "subcollectionSetting", "=", "action", ".", "meta", ".", "subcollections", "[", "0", "]", ";", "// Meta does not contain doc, remove whole subcollection", "if", "(", "!", "subcollectionSetting", ".", "doc", ")", "{", "return", "updateItemInArray", "(", "array", ",", "action", ".", "meta", ".", "doc", ",", "item", "=>", "omit", "(", "item", ",", "[", "subcollectionSetting", ".", "collection", "]", ")", ",", "// omit creates a new object", ")", ";", "}", "// Meta contains doc setting, remove doc from subcollection", "return", "updateItemInArray", "(", "array", ",", "action", ".", "meta", ".", "doc", ",", "item", "=>", "{", "const", "subcollectionVal", "=", "get", "(", "item", ",", "subcollectionSetting", ".", "collection", ",", "[", "]", ")", ";", "// Subcollection exists within doc, update item within subcollection", "if", "(", "subcollectionVal", ".", "length", ")", "{", "return", "{", "...", "item", ",", "[", "subcollectionSetting", ".", "collection", "]", ":", "reject", "(", "array", ",", "{", "id", ":", "subcollectionSetting", ".", "doc", ",", "}", ")", ",", "}", ";", "}", "// Item does not contain subcollection", "return", "item", ";", "}", ")", ";", "}" ]
Case reducer for adding a document to a collection. @param {Array} array - Redux state of current collection @param {Object} action - The action that was dispatched @return {Array} State with document modified
[ "Case", "reducer", "for", "adding", "a", "document", "to", "a", "collection", "." ]
cd9eb5c580e9e69886d4f1df1929c45adbe6081f
https://github.com/prescottprue/redux-firestore/blob/cd9eb5c580e9e69886d4f1df1929c45adbe6081f/src/reducers/orderedReducer.js#L78-L111
12,038
prescottprue/redux-firestore
src/utils/query.js
arrayToStr
function arrayToStr(key, value) { if (isString(value) || isNumber(value)) return `${key}=${value}`; if (isString(value[0])) return `${key}=${value.join(':')}`; if (value && value.toString) return `${key}=${value.toString()}`; return value.map(val => arrayToStr(key, val)); }
javascript
function arrayToStr(key, value) { if (isString(value) || isNumber(value)) return `${key}=${value}`; if (isString(value[0])) return `${key}=${value.join(':')}`; if (value && value.toString) return `${key}=${value.toString()}`; return value.map(val => arrayToStr(key, val)); }
[ "function", "arrayToStr", "(", "key", ",", "value", ")", "{", "if", "(", "isString", "(", "value", ")", "||", "isNumber", "(", "value", ")", ")", "return", "`", "${", "key", "}", "${", "value", "}", "`", ";", "if", "(", "isString", "(", "value", "[", "0", "]", ")", ")", "return", "`", "${", "key", "}", "${", "value", ".", "join", "(", "':'", ")", "}", "`", ";", "if", "(", "value", "&&", "value", ".", "toString", ")", "return", "`", "${", "key", "}", "${", "value", ".", "toString", "(", ")", "}", "`", ";", "return", "value", ".", "map", "(", "val", "=>", "arrayToStr", "(", "key", ",", "val", ")", ")", ";", "}" ]
Convert where parameter into a string notation for use in query name @param {String} key - Key to use @param {Array} value - Where config array @return {String} String representing where settings for use in query name
[ "Convert", "where", "parameter", "into", "a", "string", "notation", "for", "use", "in", "query", "name" ]
cd9eb5c580e9e69886d4f1df1929c45adbe6081f
https://github.com/prescottprue/redux-firestore/blob/cd9eb5c580e9e69886d4f1df1929c45adbe6081f/src/utils/query.js#L151-L157
12,039
prescottprue/redux-firestore
src/utils/query.js
pickQueryParams
function pickQueryParams(obj) { return [ 'where', 'orderBy', 'limit', 'startAfter', 'startAt', 'endAt', 'endBefore', ].reduce((acc, key) => (obj[key] ? { ...acc, [key]: obj[key] } : acc), {}); }
javascript
function pickQueryParams(obj) { return [ 'where', 'orderBy', 'limit', 'startAfter', 'startAt', 'endAt', 'endBefore', ].reduce((acc, key) => (obj[key] ? { ...acc, [key]: obj[key] } : acc), {}); }
[ "function", "pickQueryParams", "(", "obj", ")", "{", "return", "[", "'where'", ",", "'orderBy'", ",", "'limit'", ",", "'startAfter'", ",", "'startAt'", ",", "'endAt'", ",", "'endBefore'", ",", "]", ".", "reduce", "(", "(", "acc", ",", "key", ")", "=>", "(", "obj", "[", "key", "]", "?", "{", "...", "acc", ",", "[", "key", "]", ":", "obj", "[", "key", "]", "}", ":", "acc", ")", ",", "{", "}", ")", ";", "}" ]
Pcik query params from object @param {Object} obj - Object from which to pick query params @return {Object}
[ "Pcik", "query", "params", "from", "object" ]
cd9eb5c580e9e69886d4f1df1929c45adbe6081f
https://github.com/prescottprue/redux-firestore/blob/cd9eb5c580e9e69886d4f1df1929c45adbe6081f/src/utils/query.js#L164-L174
12,040
prescottprue/redux-firestore
src/utils/query.js
docChangeEvent
function docChangeEvent(change, originalMeta = {}) { const meta = { ...cloneDeep(originalMeta), path: change.doc.ref.path }; if (originalMeta.subcollections && !originalMeta.storeAs) { meta.subcollections[0] = { ...meta.subcollections[0], doc: change.doc.id }; } else { meta.doc = change.doc.id; } return { type: changeTypeToEventType[change.type] || actionTypes.DOCUMENT_MODIFIED, meta, payload: { data: change.doc.data(), ordered: { oldIndex: change.oldIndex, newIndex: change.newIndex }, }, }; }
javascript
function docChangeEvent(change, originalMeta = {}) { const meta = { ...cloneDeep(originalMeta), path: change.doc.ref.path }; if (originalMeta.subcollections && !originalMeta.storeAs) { meta.subcollections[0] = { ...meta.subcollections[0], doc: change.doc.id }; } else { meta.doc = change.doc.id; } return { type: changeTypeToEventType[change.type] || actionTypes.DOCUMENT_MODIFIED, meta, payload: { data: change.doc.data(), ordered: { oldIndex: change.oldIndex, newIndex: change.newIndex }, }, }; }
[ "function", "docChangeEvent", "(", "change", ",", "originalMeta", "=", "{", "}", ")", "{", "const", "meta", "=", "{", "...", "cloneDeep", "(", "originalMeta", ")", ",", "path", ":", "change", ".", "doc", ".", "ref", ".", "path", "}", ";", "if", "(", "originalMeta", ".", "subcollections", "&&", "!", "originalMeta", ".", "storeAs", ")", "{", "meta", ".", "subcollections", "[", "0", "]", "=", "{", "...", "meta", ".", "subcollections", "[", "0", "]", ",", "doc", ":", "change", ".", "doc", ".", "id", "}", ";", "}", "else", "{", "meta", ".", "doc", "=", "change", ".", "doc", ".", "id", ";", "}", "return", "{", "type", ":", "changeTypeToEventType", "[", "change", ".", "type", "]", "||", "actionTypes", ".", "DOCUMENT_MODIFIED", ",", "meta", ",", "payload", ":", "{", "data", ":", "change", ".", "doc", ".", "data", "(", ")", ",", "ordered", ":", "{", "oldIndex", ":", "change", ".", "oldIndex", ",", "newIndex", ":", "change", ".", "newIndex", "}", ",", "}", ",", "}", ";", "}" ]
Action creator for document change event. Used to create action objects to be passed to dispatch. @param {Object} change - Document change object from Firebase callback @param {Object} [originalMeta={}] - Original meta data of action @return {Object} [description]
[ "Action", "creator", "for", "document", "change", "event", ".", "Used", "to", "create", "action", "objects", "to", "be", "passed", "to", "dispatch", "." ]
cd9eb5c580e9e69886d4f1df1929c45adbe6081f
https://github.com/prescottprue/redux-firestore/blob/cd9eb5c580e9e69886d4f1df1929c45adbe6081f/src/utils/query.js#L630-L645
12,041
prescottprue/redux-firestore
src/utils/actions.js
createWithFirebaseAndDispatch
function createWithFirebaseAndDispatch(firebase, dispatch) { return func => (...args) => func.apply(firebase, [firebase, dispatch, ...args]); }
javascript
function createWithFirebaseAndDispatch(firebase, dispatch) { return func => (...args) => func.apply(firebase, [firebase, dispatch, ...args]); }
[ "function", "createWithFirebaseAndDispatch", "(", "firebase", ",", "dispatch", ")", "{", "return", "func", "=>", "(", "...", "args", ")", "=>", "func", ".", "apply", "(", "firebase", ",", "[", "firebase", ",", "dispatch", ",", "...", "args", "]", ")", ";", "}" ]
Function that builds a factory that passes firebase and dispatch as first two arguments. @param {Object} firebase - Internal firebase instance @param {Function} dispatch - Redux's dispatch function @return {Function} A wrapper that accepts a function to wrap with firebase and dispatch.
[ "Function", "that", "builds", "a", "factory", "that", "passes", "firebase", "and", "dispatch", "as", "first", "two", "arguments", "." ]
cd9eb5c580e9e69886d4f1df1929c45adbe6081f
https://github.com/prescottprue/redux-firestore/blob/cd9eb5c580e9e69886d4f1df1929c45adbe6081f/src/utils/actions.js#L76-L79
12,042
prettymuchbryce/easystarjs
src/easystar.js
function (diffX, diffY) { if (diffX === 0 && diffY === -1) return EasyStar.TOP else if (diffX === 1 && diffY === -1) return EasyStar.TOP_RIGHT else if (diffX === 1 && diffY === 0) return EasyStar.RIGHT else if (diffX === 1 && diffY === 1) return EasyStar.BOTTOM_RIGHT else if (diffX === 0 && diffY === 1) return EasyStar.BOTTOM else if (diffX === -1 && diffY === 1) return EasyStar.BOTTOM_LEFT else if (diffX === -1 && diffY === 0) return EasyStar.LEFT else if (diffX === -1 && diffY === -1) return EasyStar.TOP_LEFT throw new Error('These differences are not valid: ' + diffX + ', ' + diffY) }
javascript
function (diffX, diffY) { if (diffX === 0 && diffY === -1) return EasyStar.TOP else if (diffX === 1 && diffY === -1) return EasyStar.TOP_RIGHT else if (diffX === 1 && diffY === 0) return EasyStar.RIGHT else if (diffX === 1 && diffY === 1) return EasyStar.BOTTOM_RIGHT else if (diffX === 0 && diffY === 1) return EasyStar.BOTTOM else if (diffX === -1 && diffY === 1) return EasyStar.BOTTOM_LEFT else if (diffX === -1 && diffY === 0) return EasyStar.LEFT else if (diffX === -1 && diffY === -1) return EasyStar.TOP_LEFT throw new Error('These differences are not valid: ' + diffX + ', ' + diffY) }
[ "function", "(", "diffX", ",", "diffY", ")", "{", "if", "(", "diffX", "===", "0", "&&", "diffY", "===", "-", "1", ")", "return", "EasyStar", ".", "TOP", "else", "if", "(", "diffX", "===", "1", "&&", "diffY", "===", "-", "1", ")", "return", "EasyStar", ".", "TOP_RIGHT", "else", "if", "(", "diffX", "===", "1", "&&", "diffY", "===", "0", ")", "return", "EasyStar", ".", "RIGHT", "else", "if", "(", "diffX", "===", "1", "&&", "diffY", "===", "1", ")", "return", "EasyStar", ".", "BOTTOM_RIGHT", "else", "if", "(", "diffX", "===", "0", "&&", "diffY", "===", "1", ")", "return", "EasyStar", ".", "BOTTOM", "else", "if", "(", "diffX", "===", "-", "1", "&&", "diffY", "===", "1", ")", "return", "EasyStar", ".", "BOTTOM_LEFT", "else", "if", "(", "diffX", "===", "-", "1", "&&", "diffY", "===", "0", ")", "return", "EasyStar", ".", "LEFT", "else", "if", "(", "diffX", "===", "-", "1", "&&", "diffY", "===", "-", "1", ")", "return", "EasyStar", ".", "TOP_LEFT", "throw", "new", "Error", "(", "'These differences are not valid: '", "+", "diffX", "+", "', '", "+", "diffY", ")", "}" ]
-1, -1 | 0, -1 | 1, -1 -1, 0 | SOURCE | 1, 0 -1, 1 | 0, 1 | 1, 1
[ "-", "1", "-", "1", "|", "0", "-", "1", "|", "1", "-", "1", "-", "1", "0", "|", "SOURCE", "|", "1", "0", "-", "1", "1", "|", "0", "1", "|", "1", "1" ]
293ad9d5c71c6135ba18ac876c39663f5a357031
https://github.com/prettymuchbryce/easystarjs/blob/293ad9d5c71c6135ba18ac876c39663f5a357031/src/easystar.js#L495-L505
12,043
be-fe/iSlider
build/iSlider.plugin.zoompic.js
getTouches
function getTouches(touches) { return Array.prototype.slice.call(touches).map(function (touch) { return { left: touch.pageX, top: touch.pageY }; }); }
javascript
function getTouches(touches) { return Array.prototype.slice.call(touches).map(function (touch) { return { left: touch.pageX, top: touch.pageY }; }); }
[ "function", "getTouches", "(", "touches", ")", "{", "return", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "touches", ")", ".", "map", "(", "function", "(", "touch", ")", "{", "return", "{", "left", ":", "touch", ".", "pageX", ",", "top", ":", "touch", ".", "pageY", "}", ";", "}", ")", ";", "}" ]
Get touch pointer @param touches @returns {Array}
[ "Get", "touch", "pointer" ]
4c6c0044f6ce30fa3b36da910f82ecce9b2e249c
https://github.com/be-fe/iSlider/blob/4c6c0044f6ce30fa3b36da910f82ecce9b2e249c/build/iSlider.plugin.zoompic.js#L104-L111
12,044
be-fe/iSlider
build/iSlider.plugin.zoompic.js
getComputedTranslate
function getComputedTranslate(obj) { var result = { translateX: 0, translateY: 0, translateZ: 0, scaleX: 1, scaleY: 1, offsetX: 0, offsetY: 0 }; var offsetX = 0, offsetY = 0; if (!global.getComputedStyle || !obj) return result; var style = global.getComputedStyle(obj), transform, origin; transform = style.webkitTransform || style.mozTransform; origin = style.webkitTransformOrigin || style.mozTransformOrigin; var par = origin.match(/(.*)px\s+(.*)px/); if (par.length > 1) { offsetX = par[1] - 0; offsetY = par[2] - 0; } if (transform === 'none') return result; var mat3d = transform.match(/^matrix3d\((.+)\)$/); var mat2d = transform.match(/^matrix\((.+)\)$/); var str; if (mat3d) { str = mat3d[1].split(', '); result = { translateX: str[12] - 0, translateY: str[13] - 0, translateZ: str[14] - 0, offsetX: offsetX - 0, offsetY: offsetY - 0, scaleX: str[0] - 0, scaleY: str[5] - 0, scaleZ: str[10] - 0 }; } else if (mat2d) { str = mat2d[1].split(', '); result = { translateX: str[4] - 0, translateY: str[5] - 0, offsetX: offsetX - 0, offsetY: offsetY - 0, scaleX: str[0] - 0, scaleY: str[3] - 0 }; } return result; }
javascript
function getComputedTranslate(obj) { var result = { translateX: 0, translateY: 0, translateZ: 0, scaleX: 1, scaleY: 1, offsetX: 0, offsetY: 0 }; var offsetX = 0, offsetY = 0; if (!global.getComputedStyle || !obj) return result; var style = global.getComputedStyle(obj), transform, origin; transform = style.webkitTransform || style.mozTransform; origin = style.webkitTransformOrigin || style.mozTransformOrigin; var par = origin.match(/(.*)px\s+(.*)px/); if (par.length > 1) { offsetX = par[1] - 0; offsetY = par[2] - 0; } if (transform === 'none') return result; var mat3d = transform.match(/^matrix3d\((.+)\)$/); var mat2d = transform.match(/^matrix\((.+)\)$/); var str; if (mat3d) { str = mat3d[1].split(', '); result = { translateX: str[12] - 0, translateY: str[13] - 0, translateZ: str[14] - 0, offsetX: offsetX - 0, offsetY: offsetY - 0, scaleX: str[0] - 0, scaleY: str[5] - 0, scaleZ: str[10] - 0 }; } else if (mat2d) { str = mat2d[1].split(', '); result = { translateX: str[4] - 0, translateY: str[5] - 0, offsetX: offsetX - 0, offsetY: offsetY - 0, scaleX: str[0] - 0, scaleY: str[3] - 0 }; } return result; }
[ "function", "getComputedTranslate", "(", "obj", ")", "{", "var", "result", "=", "{", "translateX", ":", "0", ",", "translateY", ":", "0", ",", "translateZ", ":", "0", ",", "scaleX", ":", "1", ",", "scaleY", ":", "1", ",", "offsetX", ":", "0", ",", "offsetY", ":", "0", "}", ";", "var", "offsetX", "=", "0", ",", "offsetY", "=", "0", ";", "if", "(", "!", "global", ".", "getComputedStyle", "||", "!", "obj", ")", "return", "result", ";", "var", "style", "=", "global", ".", "getComputedStyle", "(", "obj", ")", ",", "transform", ",", "origin", ";", "transform", "=", "style", ".", "webkitTransform", "||", "style", ".", "mozTransform", ";", "origin", "=", "style", ".", "webkitTransformOrigin", "||", "style", ".", "mozTransformOrigin", ";", "var", "par", "=", "origin", ".", "match", "(", "/", "(.*)px\\s+(.*)px", "/", ")", ";", "if", "(", "par", ".", "length", ">", "1", ")", "{", "offsetX", "=", "par", "[", "1", "]", "-", "0", ";", "offsetY", "=", "par", "[", "2", "]", "-", "0", ";", "}", "if", "(", "transform", "===", "'none'", ")", "return", "result", ";", "var", "mat3d", "=", "transform", ".", "match", "(", "/", "^matrix3d\\((.+)\\)$", "/", ")", ";", "var", "mat2d", "=", "transform", ".", "match", "(", "/", "^matrix\\((.+)\\)$", "/", ")", ";", "var", "str", ";", "if", "(", "mat3d", ")", "{", "str", "=", "mat3d", "[", "1", "]", ".", "split", "(", "', '", ")", ";", "result", "=", "{", "translateX", ":", "str", "[", "12", "]", "-", "0", ",", "translateY", ":", "str", "[", "13", "]", "-", "0", ",", "translateZ", ":", "str", "[", "14", "]", "-", "0", ",", "offsetX", ":", "offsetX", "-", "0", ",", "offsetY", ":", "offsetY", "-", "0", ",", "scaleX", ":", "str", "[", "0", "]", "-", "0", ",", "scaleY", ":", "str", "[", "5", "]", "-", "0", ",", "scaleZ", ":", "str", "[", "10", "]", "-", "0", "}", ";", "}", "else", "if", "(", "mat2d", ")", "{", "str", "=", "mat2d", "[", "1", "]", ".", "split", "(", "', '", ")", ";", "result", "=", "{", "translateX", ":", "str", "[", "4", "]", "-", "0", ",", "translateY", ":", "str", "[", "5", "]", "-", "0", ",", "offsetX", ":", "offsetX", "-", "0", ",", "offsetY", ":", "offsetY", "-", "0", ",", "scaleX", ":", "str", "[", "0", "]", "-", "0", ",", "scaleY", ":", "str", "[", "3", "]", "-", "0", "}", ";", "}", "return", "result", ";", "}" ]
Get computed translate @param obj @returns {{translateX: number, translateY: number, translateZ: number, scaleX: number, scaleY: number, offsetX: number, offsetY: number}}
[ "Get", "computed", "translate" ]
4c6c0044f6ce30fa3b36da910f82ecce9b2e249c
https://github.com/be-fe/iSlider/blob/4c6c0044f6ce30fa3b36da910f82ecce9b2e249c/build/iSlider.plugin.zoompic.js#L130-L178
12,045
be-fe/iSlider
build/iSlider.plugin.zoompic.js
startHandler
function startHandler(evt) { startHandlerOriginal.call(this, evt); // must be a picture, only one picture!! var node = this.els[1].querySelector('img:first-child'); var device = this.deviceEvents; if (device.hasTouch && node !== null) { IN_SCALE_MODE = true; var transform = getComputedTranslate(node); startTouches = getTouches(evt.targetTouches); startX = transform.translateX - 0; startY = transform.translateY - 0; currentScale = transform.scaleX; zoomNode = node; var pos = getPosition(node); if (evt.targetTouches.length == 2) { lastTouchStart = null; var touches = evt.touches; var touchCenter = getCenter({ x: touches[0].pageX, y: touches[0].pageY }, { x: touches[1].pageX, y: touches[1].pageY }); node.style.webkitTransformOrigin = generateTransformOrigin(touchCenter.x - pos.left, touchCenter.y - pos.top); } else if (evt.targetTouches.length === 1) { var time = (new Date()).getTime(); gesture = 0; if (time - lastTouchStart < 300) { evt.preventDefault(); gesture = 3; } lastTouchStart = time; } } }
javascript
function startHandler(evt) { startHandlerOriginal.call(this, evt); // must be a picture, only one picture!! var node = this.els[1].querySelector('img:first-child'); var device = this.deviceEvents; if (device.hasTouch && node !== null) { IN_SCALE_MODE = true; var transform = getComputedTranslate(node); startTouches = getTouches(evt.targetTouches); startX = transform.translateX - 0; startY = transform.translateY - 0; currentScale = transform.scaleX; zoomNode = node; var pos = getPosition(node); if (evt.targetTouches.length == 2) { lastTouchStart = null; var touches = evt.touches; var touchCenter = getCenter({ x: touches[0].pageX, y: touches[0].pageY }, { x: touches[1].pageX, y: touches[1].pageY }); node.style.webkitTransformOrigin = generateTransformOrigin(touchCenter.x - pos.left, touchCenter.y - pos.top); } else if (evt.targetTouches.length === 1) { var time = (new Date()).getTime(); gesture = 0; if (time - lastTouchStart < 300) { evt.preventDefault(); gesture = 3; } lastTouchStart = time; } } }
[ "function", "startHandler", "(", "evt", ")", "{", "startHandlerOriginal", ".", "call", "(", "this", ",", "evt", ")", ";", "// must be a picture, only one picture!!", "var", "node", "=", "this", ".", "els", "[", "1", "]", ".", "querySelector", "(", "'img:first-child'", ")", ";", "var", "device", "=", "this", ".", "deviceEvents", ";", "if", "(", "device", ".", "hasTouch", "&&", "node", "!==", "null", ")", "{", "IN_SCALE_MODE", "=", "true", ";", "var", "transform", "=", "getComputedTranslate", "(", "node", ")", ";", "startTouches", "=", "getTouches", "(", "evt", ".", "targetTouches", ")", ";", "startX", "=", "transform", ".", "translateX", "-", "0", ";", "startY", "=", "transform", ".", "translateY", "-", "0", ";", "currentScale", "=", "transform", ".", "scaleX", ";", "zoomNode", "=", "node", ";", "var", "pos", "=", "getPosition", "(", "node", ")", ";", "if", "(", "evt", ".", "targetTouches", ".", "length", "==", "2", ")", "{", "lastTouchStart", "=", "null", ";", "var", "touches", "=", "evt", ".", "touches", ";", "var", "touchCenter", "=", "getCenter", "(", "{", "x", ":", "touches", "[", "0", "]", ".", "pageX", ",", "y", ":", "touches", "[", "0", "]", ".", "pageY", "}", ",", "{", "x", ":", "touches", "[", "1", "]", ".", "pageX", ",", "y", ":", "touches", "[", "1", "]", ".", "pageY", "}", ")", ";", "node", ".", "style", ".", "webkitTransformOrigin", "=", "generateTransformOrigin", "(", "touchCenter", ".", "x", "-", "pos", ".", "left", ",", "touchCenter", ".", "y", "-", "pos", ".", "top", ")", ";", "}", "else", "if", "(", "evt", ".", "targetTouches", ".", "length", "===", "1", ")", "{", "var", "time", "=", "(", "new", "Date", "(", ")", ")", ".", "getTime", "(", ")", ";", "gesture", "=", "0", ";", "if", "(", "time", "-", "lastTouchStart", "<", "300", ")", "{", "evt", ".", "preventDefault", "(", ")", ";", "gesture", "=", "3", ";", "}", "lastTouchStart", "=", "time", ";", "}", "}", "}" ]
Start event handle @param {object} evt
[ "Start", "event", "handle" ]
4c6c0044f6ce30fa3b36da910f82ecce9b2e249c
https://github.com/be-fe/iSlider/blob/4c6c0044f6ce30fa3b36da910f82ecce9b2e249c/build/iSlider.plugin.zoompic.js#L206-L241
12,046
be-fe/iSlider
build/iSlider.plugin.zoompic.js
moveHandler
function moveHandler(evt) { if (IN_SCALE_MODE) { var result = 0; var node = zoomNode; var device = this.deviceEvents; if (device.hasTouch) { if (evt.targetTouches.length === 2) { node.style.webkitTransitionDuration = '0'; evt.preventDefault(); scaleImage(evt); result = 2; } else if (evt.targetTouches.length === 1 && currentScale > 1) { node.style.webkitTransitionDuration = '0'; evt.preventDefault(); moveImage.call(this, evt); result = 1; } gesture = result; if (result > 0) { return; } } } moveHandlerOriginal.call(this, evt); }
javascript
function moveHandler(evt) { if (IN_SCALE_MODE) { var result = 0; var node = zoomNode; var device = this.deviceEvents; if (device.hasTouch) { if (evt.targetTouches.length === 2) { node.style.webkitTransitionDuration = '0'; evt.preventDefault(); scaleImage(evt); result = 2; } else if (evt.targetTouches.length === 1 && currentScale > 1) { node.style.webkitTransitionDuration = '0'; evt.preventDefault(); moveImage.call(this, evt); result = 1; } gesture = result; if (result > 0) { return; } } } moveHandlerOriginal.call(this, evt); }
[ "function", "moveHandler", "(", "evt", ")", "{", "if", "(", "IN_SCALE_MODE", ")", "{", "var", "result", "=", "0", ";", "var", "node", "=", "zoomNode", ";", "var", "device", "=", "this", ".", "deviceEvents", ";", "if", "(", "device", ".", "hasTouch", ")", "{", "if", "(", "evt", ".", "targetTouches", ".", "length", "===", "2", ")", "{", "node", ".", "style", ".", "webkitTransitionDuration", "=", "'0'", ";", "evt", ".", "preventDefault", "(", ")", ";", "scaleImage", "(", "evt", ")", ";", "result", "=", "2", ";", "}", "else", "if", "(", "evt", ".", "targetTouches", ".", "length", "===", "1", "&&", "currentScale", ">", "1", ")", "{", "node", ".", "style", ".", "webkitTransitionDuration", "=", "'0'", ";", "evt", ".", "preventDefault", "(", ")", ";", "moveImage", ".", "call", "(", "this", ",", "evt", ")", ";", "result", "=", "1", ";", "}", "gesture", "=", "result", ";", "if", "(", "result", ">", "0", ")", "{", "return", ";", "}", "}", "}", "moveHandlerOriginal", ".", "call", "(", "this", ",", "evt", ")", ";", "}" ]
Move event handle @param {object} evt @returns {number}
[ "Move", "event", "handle" ]
4c6c0044f6ce30fa3b36da910f82ecce9b2e249c
https://github.com/be-fe/iSlider/blob/4c6c0044f6ce30fa3b36da910f82ecce9b2e249c/build/iSlider.plugin.zoompic.js#L248-L273
12,047
be-fe/iSlider
build/iSlider.plugin.zoompic.js
handleDoubleTap
function handleDoubleTap(evt) { var zoomFactor = zoomFactor || 2; var node = zoomNode; var pos = getPosition(node); currentScale = currentScale == 1 ? zoomFactor : 1; node.style.webkitTransform = generateTranslate(0, 0, 0, currentScale); if (currentScale != 1) node.style.webkitTransformOrigin = generateTransformOrigin(evt.touches[0].pageX - pos.left, evt.touches[0].pageY - pos.top); }
javascript
function handleDoubleTap(evt) { var zoomFactor = zoomFactor || 2; var node = zoomNode; var pos = getPosition(node); currentScale = currentScale == 1 ? zoomFactor : 1; node.style.webkitTransform = generateTranslate(0, 0, 0, currentScale); if (currentScale != 1) node.style.webkitTransformOrigin = generateTransformOrigin(evt.touches[0].pageX - pos.left, evt.touches[0].pageY - pos.top); }
[ "function", "handleDoubleTap", "(", "evt", ")", "{", "var", "zoomFactor", "=", "zoomFactor", "||", "2", ";", "var", "node", "=", "zoomNode", ";", "var", "pos", "=", "getPosition", "(", "node", ")", ";", "currentScale", "=", "currentScale", "==", "1", "?", "zoomFactor", ":", "1", ";", "node", ".", "style", ".", "webkitTransform", "=", "generateTranslate", "(", "0", ",", "0", ",", "0", ",", "currentScale", ")", ";", "if", "(", "currentScale", "!=", "1", ")", "node", ".", "style", ".", "webkitTransformOrigin", "=", "generateTransformOrigin", "(", "evt", ".", "touches", "[", "0", "]", ".", "pageX", "-", "pos", ".", "left", ",", "evt", ".", "touches", "[", "0", "]", ".", "pageY", "-", "pos", ".", "top", ")", ";", "}" ]
Double tao handle @param {object} evt
[ "Double", "tao", "handle" ]
4c6c0044f6ce30fa3b36da910f82ecce9b2e249c
https://github.com/be-fe/iSlider/blob/4c6c0044f6ce30fa3b36da910f82ecce9b2e249c/build/iSlider.plugin.zoompic.js#L279-L286
12,048
be-fe/iSlider
build/iSlider.plugin.zoompic.js
endHandler
function endHandler(evt) { if (IN_SCALE_MODE) { var result = 0; if (gesture === 2) {//双手指 resetImage(evt); result = 2; } else if (gesture == 1) {//放大拖拽 resetImage(evt); result = 1; } else if (gesture === 3) {//双击 handleDoubleTap(evt); resetImage(evt); IN_SCALE_MODE = false; } if (result > 0) { return; } } endHandlerOriginal.call(this, evt); }
javascript
function endHandler(evt) { if (IN_SCALE_MODE) { var result = 0; if (gesture === 2) {//双手指 resetImage(evt); result = 2; } else if (gesture == 1) {//放大拖拽 resetImage(evt); result = 1; } else if (gesture === 3) {//双击 handleDoubleTap(evt); resetImage(evt); IN_SCALE_MODE = false; } if (result > 0) { return; } } endHandlerOriginal.call(this, evt); }
[ "function", "endHandler", "(", "evt", ")", "{", "if", "(", "IN_SCALE_MODE", ")", "{", "var", "result", "=", "0", ";", "if", "(", "gesture", "===", "2", ")", "{", "//双手指", "resetImage", "(", "evt", ")", ";", "result", "=", "2", ";", "}", "else", "if", "(", "gesture", "==", "1", ")", "{", "//放大拖拽", "resetImage", "(", "evt", ")", ";", "result", "=", "1", ";", "}", "else", "if", "(", "gesture", "===", "3", ")", "{", "//双击", "handleDoubleTap", "(", "evt", ")", ";", "resetImage", "(", "evt", ")", ";", "IN_SCALE_MODE", "=", "false", ";", "}", "if", "(", "result", ">", "0", ")", "{", "return", ";", "}", "}", "endHandlerOriginal", ".", "call", "(", "this", ",", "evt", ")", ";", "}" ]
End event handle @param evt
[ "End", "event", "handle" ]
4c6c0044f6ce30fa3b36da910f82ecce9b2e249c
https://github.com/be-fe/iSlider/blob/4c6c0044f6ce30fa3b36da910f82ecce9b2e249c/build/iSlider.plugin.zoompic.js#L304-L324
12,049
be-fe/iSlider
build/iSlider.plugin.zoompic.js
valueInViewScope
function valueInViewScope(node, value, tag) { var min, max; var pos = getPosition(node); viewScope = { start: {left: pos.left, top: pos.top}, end: {left: pos.left + node.clientWidth, top: pos.top + node.clientHeight} }; var str = tag == 1 ? 'left' : 'top'; min = viewScope.start[str]; max = viewScope.end[str]; return (value >= min && value <= max); }
javascript
function valueInViewScope(node, value, tag) { var min, max; var pos = getPosition(node); viewScope = { start: {left: pos.left, top: pos.top}, end: {left: pos.left + node.clientWidth, top: pos.top + node.clientHeight} }; var str = tag == 1 ? 'left' : 'top'; min = viewScope.start[str]; max = viewScope.end[str]; return (value >= min && value <= max); }
[ "function", "valueInViewScope", "(", "node", ",", "value", ",", "tag", ")", "{", "var", "min", ",", "max", ";", "var", "pos", "=", "getPosition", "(", "node", ")", ";", "viewScope", "=", "{", "start", ":", "{", "left", ":", "pos", ".", "left", ",", "top", ":", "pos", ".", "top", "}", ",", "end", ":", "{", "left", ":", "pos", ".", "left", "+", "node", ".", "clientWidth", ",", "top", ":", "pos", ".", "top", "+", "node", ".", "clientHeight", "}", "}", ";", "var", "str", "=", "tag", "==", "1", "?", "'left'", ":", "'top'", ";", "min", "=", "viewScope", ".", "start", "[", "str", "]", ";", "max", "=", "viewScope", ".", "end", "[", "str", "]", ";", "return", "(", "value", ">=", "min", "&&", "value", "<=", "max", ")", ";", "}" ]
Check target is in range @param node @param value @param tag @returns {boolean}
[ "Check", "target", "is", "in", "range" ]
4c6c0044f6ce30fa3b36da910f82ecce9b2e249c
https://github.com/be-fe/iSlider/blob/4c6c0044f6ce30fa3b36da910f82ecce9b2e249c/build/iSlider.plugin.zoompic.js#L367-L378
12,050
be-fe/iSlider
build/iSlider.js
_A
function _A(a) { return Array.prototype.slice.apply(a, Array.prototype.slice.call(arguments, 1)); }
javascript
function _A(a) { return Array.prototype.slice.apply(a, Array.prototype.slice.call(arguments, 1)); }
[ "function", "_A", "(", "a", ")", "{", "return", "Array", ".", "prototype", ".", "slice", ".", "apply", "(", "a", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ")", ";", "}" ]
Parse arguments to array @param {Arguments} a @param {Number|null} start @param {Number|null} end @returns {Array}
[ "Parse", "arguments", "to", "array" ]
4c6c0044f6ce30fa3b36da910f82ecce9b2e249c
https://github.com/be-fe/iSlider/blob/4c6c0044f6ce30fa3b36da910f82ecce9b2e249c/build/iSlider.js#L113-L115
12,051
GitbookIO/nuts
lib/utils/platforms.js
detectPlatform
function detectPlatform(platform) { var name = platform.toLowerCase(); var prefix = "", suffix = ""; // Detect NuGet/Squirrel.Windows files if (name == 'releases' || hasSuffix(name, '.nupkg')) return platforms.WINDOWS_32; // Detect prefix: osx, widnows or linux if (_.contains(name, 'win') || hasSuffix(name, '.exe')) prefix = platforms.WINDOWS; if (_.contains(name, 'linux') || _.contains(name, 'ubuntu') || hasSuffix(name, '.deb') || hasSuffix(name, '.rpm') || hasSuffix(name, '.tgz') || hasSuffix(name, '.tar.gz')) { if (_.contains(name, 'linux_deb') || hasSuffix(name, '.deb')) { prefix = platforms.LINUX_DEB; } else if (_.contains(name, 'linux_rpm') || hasSuffix(name, '.rpm')) { prefix = platforms.LINUX_RPM; } else if (_.contains(name, 'linux') || hasSuffix(name, '.tgz') || hasSuffix(name, '.tar.gz')) { prefix = platforms.LINUX; } } if (_.contains(name, 'mac') || _.contains(name, 'osx') || name.indexOf('darwin') >= 0 || hasSuffix(name, '.dmg')) prefix = platforms.OSX; // Detect suffix: 32 or 64 if (_.contains(name, '32') || _.contains(name, 'ia32') || _.contains(name, 'i386')) suffix = '32'; if (_.contains(name, '64') || _.contains(name, 'x64') || _.contains(name, 'amd64')) suffix = '64'; suffix = suffix || (prefix == platforms.OSX? '64' : '32'); return _.compact([prefix, suffix]).join('_'); }
javascript
function detectPlatform(platform) { var name = platform.toLowerCase(); var prefix = "", suffix = ""; // Detect NuGet/Squirrel.Windows files if (name == 'releases' || hasSuffix(name, '.nupkg')) return platforms.WINDOWS_32; // Detect prefix: osx, widnows or linux if (_.contains(name, 'win') || hasSuffix(name, '.exe')) prefix = platforms.WINDOWS; if (_.contains(name, 'linux') || _.contains(name, 'ubuntu') || hasSuffix(name, '.deb') || hasSuffix(name, '.rpm') || hasSuffix(name, '.tgz') || hasSuffix(name, '.tar.gz')) { if (_.contains(name, 'linux_deb') || hasSuffix(name, '.deb')) { prefix = platforms.LINUX_DEB; } else if (_.contains(name, 'linux_rpm') || hasSuffix(name, '.rpm')) { prefix = platforms.LINUX_RPM; } else if (_.contains(name, 'linux') || hasSuffix(name, '.tgz') || hasSuffix(name, '.tar.gz')) { prefix = platforms.LINUX; } } if (_.contains(name, 'mac') || _.contains(name, 'osx') || name.indexOf('darwin') >= 0 || hasSuffix(name, '.dmg')) prefix = platforms.OSX; // Detect suffix: 32 or 64 if (_.contains(name, '32') || _.contains(name, 'ia32') || _.contains(name, 'i386')) suffix = '32'; if (_.contains(name, '64') || _.contains(name, 'x64') || _.contains(name, 'amd64')) suffix = '64'; suffix = suffix || (prefix == platforms.OSX? '64' : '32'); return _.compact([prefix, suffix]).join('_'); }
[ "function", "detectPlatform", "(", "platform", ")", "{", "var", "name", "=", "platform", ".", "toLowerCase", "(", ")", ";", "var", "prefix", "=", "\"\"", ",", "suffix", "=", "\"\"", ";", "// Detect NuGet/Squirrel.Windows files", "if", "(", "name", "==", "'releases'", "||", "hasSuffix", "(", "name", ",", "'.nupkg'", ")", ")", "return", "platforms", ".", "WINDOWS_32", ";", "// Detect prefix: osx, widnows or linux", "if", "(", "_", ".", "contains", "(", "name", ",", "'win'", ")", "||", "hasSuffix", "(", "name", ",", "'.exe'", ")", ")", "prefix", "=", "platforms", ".", "WINDOWS", ";", "if", "(", "_", ".", "contains", "(", "name", ",", "'linux'", ")", "||", "_", ".", "contains", "(", "name", ",", "'ubuntu'", ")", "||", "hasSuffix", "(", "name", ",", "'.deb'", ")", "||", "hasSuffix", "(", "name", ",", "'.rpm'", ")", "||", "hasSuffix", "(", "name", ",", "'.tgz'", ")", "||", "hasSuffix", "(", "name", ",", "'.tar.gz'", ")", ")", "{", "if", "(", "_", ".", "contains", "(", "name", ",", "'linux_deb'", ")", "||", "hasSuffix", "(", "name", ",", "'.deb'", ")", ")", "{", "prefix", "=", "platforms", ".", "LINUX_DEB", ";", "}", "else", "if", "(", "_", ".", "contains", "(", "name", ",", "'linux_rpm'", ")", "||", "hasSuffix", "(", "name", ",", "'.rpm'", ")", ")", "{", "prefix", "=", "platforms", ".", "LINUX_RPM", ";", "}", "else", "if", "(", "_", ".", "contains", "(", "name", ",", "'linux'", ")", "||", "hasSuffix", "(", "name", ",", "'.tgz'", ")", "||", "hasSuffix", "(", "name", ",", "'.tar.gz'", ")", ")", "{", "prefix", "=", "platforms", ".", "LINUX", ";", "}", "}", "if", "(", "_", ".", "contains", "(", "name", ",", "'mac'", ")", "||", "_", ".", "contains", "(", "name", ",", "'osx'", ")", "||", "name", ".", "indexOf", "(", "'darwin'", ")", ">=", "0", "||", "hasSuffix", "(", "name", ",", "'.dmg'", ")", ")", "prefix", "=", "platforms", ".", "OSX", ";", "// Detect suffix: 32 or 64", "if", "(", "_", ".", "contains", "(", "name", ",", "'32'", ")", "||", "_", ".", "contains", "(", "name", ",", "'ia32'", ")", "||", "_", ".", "contains", "(", "name", ",", "'i386'", ")", ")", "suffix", "=", "'32'", ";", "if", "(", "_", ".", "contains", "(", "name", ",", "'64'", ")", "||", "_", ".", "contains", "(", "name", ",", "'x64'", ")", "||", "_", ".", "contains", "(", "name", ",", "'amd64'", ")", ")", "suffix", "=", "'64'", ";", "suffix", "=", "suffix", "||", "(", "prefix", "==", "platforms", ".", "OSX", "?", "'64'", ":", "'32'", ")", ";", "return", "_", ".", "compact", "(", "[", "prefix", ",", "suffix", "]", ")", ".", "join", "(", "'_'", ")", ";", "}" ]
Detect and normalize the platform name
[ "Detect", "and", "normalize", "the", "platform", "name" ]
52c91a66c9269e3dac754c276c10333a966f545f
https://github.com/GitbookIO/nuts/blob/52c91a66c9269e3dac754c276c10333a966f545f/lib/utils/platforms.js#L30-L72
12,052
GitbookIO/nuts
lib/utils/platforms.js
satisfiesPlatform
function satisfiesPlatform(platform, list) { if (_.contains(list, platform)) return true; // By default, user 32bits version if (_.contains(list+'_32', platform)) return true; return false; }
javascript
function satisfiesPlatform(platform, list) { if (_.contains(list, platform)) return true; // By default, user 32bits version if (_.contains(list+'_32', platform)) return true; return false; }
[ "function", "satisfiesPlatform", "(", "platform", ",", "list", ")", "{", "if", "(", "_", ".", "contains", "(", "list", ",", "platform", ")", ")", "return", "true", ";", "// By default, user 32bits version", "if", "(", "_", ".", "contains", "(", "list", "+", "'_32'", ",", "platform", ")", ")", "return", "true", ";", "return", "false", ";", "}" ]
Satisfies a platform
[ "Satisfies", "a", "platform" ]
52c91a66c9269e3dac754c276c10333a966f545f
https://github.com/GitbookIO/nuts/blob/52c91a66c9269e3dac754c276c10333a966f545f/lib/utils/platforms.js#L79-L86
12,053
GitbookIO/nuts
lib/utils/platforms.js
resolveForVersion
function resolveForVersion(version, platformID, opts) { opts = _.defaults(opts || {}, { // Order for filetype filePreference: ['.exe', '.dmg', '.deb', '.rpm', '.tgz', '.tar.gz', '.zip', '.nupkg'], wanted: null }); // Prepare file prefs if (opts.wanted) opts.filePreference = _.uniq([opts.wanted].concat(opts.filePreference)); // Normalize platform id platformID = detectPlatform(platformID); return _.chain(version.platforms) .filter(function(pl) { return pl.type.indexOf(platformID) === 0; }) .sort(function(p1, p2) { var result = 0; // Compare by arhcitecture ("osx_64" > "osx") if (p1.type.length > p2.type.length) result = -1; else if (p2.type.length > p1.type.length) result = 1; // Order by file type if samee architecture if (result == 0) { var ext1 = path.extname(p1.filename); var ext2 = path.extname(p2.filename); var pos1 = _.indexOf(opts.filePreference, ext1); var pos2 = _.indexOf(opts.filePreference, ext2); pos1 = pos1 == -1? opts.filePreference.length : pos1; pos2 = pos2 == -1? opts.filePreference.length : pos2; if (pos1 < pos2) result = -1; else if (pos2 < pos1) result = 1; } return result; }) .first() .value() }
javascript
function resolveForVersion(version, platformID, opts) { opts = _.defaults(opts || {}, { // Order for filetype filePreference: ['.exe', '.dmg', '.deb', '.rpm', '.tgz', '.tar.gz', '.zip', '.nupkg'], wanted: null }); // Prepare file prefs if (opts.wanted) opts.filePreference = _.uniq([opts.wanted].concat(opts.filePreference)); // Normalize platform id platformID = detectPlatform(platformID); return _.chain(version.platforms) .filter(function(pl) { return pl.type.indexOf(platformID) === 0; }) .sort(function(p1, p2) { var result = 0; // Compare by arhcitecture ("osx_64" > "osx") if (p1.type.length > p2.type.length) result = -1; else if (p2.type.length > p1.type.length) result = 1; // Order by file type if samee architecture if (result == 0) { var ext1 = path.extname(p1.filename); var ext2 = path.extname(p2.filename); var pos1 = _.indexOf(opts.filePreference, ext1); var pos2 = _.indexOf(opts.filePreference, ext2); pos1 = pos1 == -1? opts.filePreference.length : pos1; pos2 = pos2 == -1? opts.filePreference.length : pos2; if (pos1 < pos2) result = -1; else if (pos2 < pos1) result = 1; } return result; }) .first() .value() }
[ "function", "resolveForVersion", "(", "version", ",", "platformID", ",", "opts", ")", "{", "opts", "=", "_", ".", "defaults", "(", "opts", "||", "{", "}", ",", "{", "// Order for filetype", "filePreference", ":", "[", "'.exe'", ",", "'.dmg'", ",", "'.deb'", ",", "'.rpm'", ",", "'.tgz'", ",", "'.tar.gz'", ",", "'.zip'", ",", "'.nupkg'", "]", ",", "wanted", ":", "null", "}", ")", ";", "// Prepare file prefs", "if", "(", "opts", ".", "wanted", ")", "opts", ".", "filePreference", "=", "_", ".", "uniq", "(", "[", "opts", ".", "wanted", "]", ".", "concat", "(", "opts", ".", "filePreference", ")", ")", ";", "// Normalize platform id", "platformID", "=", "detectPlatform", "(", "platformID", ")", ";", "return", "_", ".", "chain", "(", "version", ".", "platforms", ")", ".", "filter", "(", "function", "(", "pl", ")", "{", "return", "pl", ".", "type", ".", "indexOf", "(", "platformID", ")", "===", "0", ";", "}", ")", ".", "sort", "(", "function", "(", "p1", ",", "p2", ")", "{", "var", "result", "=", "0", ";", "// Compare by arhcitecture (\"osx_64\" > \"osx\")", "if", "(", "p1", ".", "type", ".", "length", ">", "p2", ".", "type", ".", "length", ")", "result", "=", "-", "1", ";", "else", "if", "(", "p2", ".", "type", ".", "length", ">", "p1", ".", "type", ".", "length", ")", "result", "=", "1", ";", "// Order by file type if samee architecture", "if", "(", "result", "==", "0", ")", "{", "var", "ext1", "=", "path", ".", "extname", "(", "p1", ".", "filename", ")", ";", "var", "ext2", "=", "path", ".", "extname", "(", "p2", ".", "filename", ")", ";", "var", "pos1", "=", "_", ".", "indexOf", "(", "opts", ".", "filePreference", ",", "ext1", ")", ";", "var", "pos2", "=", "_", ".", "indexOf", "(", "opts", ".", "filePreference", ",", "ext2", ")", ";", "pos1", "=", "pos1", "==", "-", "1", "?", "opts", ".", "filePreference", ".", "length", ":", "pos1", ";", "pos2", "=", "pos2", "==", "-", "1", "?", "opts", ".", "filePreference", ".", "length", ":", "pos2", ";", "if", "(", "pos1", "<", "pos2", ")", "result", "=", "-", "1", ";", "else", "if", "(", "pos2", "<", "pos1", ")", "result", "=", "1", ";", "}", "return", "result", ";", "}", ")", ".", "first", "(", ")", ".", "value", "(", ")", "}" ]
Resolve a platform for a version
[ "Resolve", "a", "platform", "for", "a", "version" ]
52c91a66c9269e3dac754c276c10333a966f545f
https://github.com/GitbookIO/nuts/blob/52c91a66c9269e3dac754c276c10333a966f545f/lib/utils/platforms.js#L89-L130
12,054
GitbookIO/nuts
lib/utils/notes.js
mergeForVersions
function mergeForVersions(versions, opts) { opts = _.defaults(opts || {}, { includeTag: true }); return _.chain(versions) .reduce(function(prev, version) { if (!version.notes) return prev; // Include tag as title if (opts.includeTag) { prev = prev + '## ' + version.tag + '\n'; } // Include notes prev = prev + version.notes + '\n'; // New lines if (opts.includeTag) { prev = prev + '\n'; } return prev; }, '') .value(); }
javascript
function mergeForVersions(versions, opts) { opts = _.defaults(opts || {}, { includeTag: true }); return _.chain(versions) .reduce(function(prev, version) { if (!version.notes) return prev; // Include tag as title if (opts.includeTag) { prev = prev + '## ' + version.tag + '\n'; } // Include notes prev = prev + version.notes + '\n'; // New lines if (opts.includeTag) { prev = prev + '\n'; } return prev; }, '') .value(); }
[ "function", "mergeForVersions", "(", "versions", ",", "opts", ")", "{", "opts", "=", "_", ".", "defaults", "(", "opts", "||", "{", "}", ",", "{", "includeTag", ":", "true", "}", ")", ";", "return", "_", ".", "chain", "(", "versions", ")", ".", "reduce", "(", "function", "(", "prev", ",", "version", ")", "{", "if", "(", "!", "version", ".", "notes", ")", "return", "prev", ";", "// Include tag as title", "if", "(", "opts", ".", "includeTag", ")", "{", "prev", "=", "prev", "+", "'## '", "+", "version", ".", "tag", "+", "'\\n'", ";", "}", "// Include notes", "prev", "=", "prev", "+", "version", ".", "notes", "+", "'\\n'", ";", "// New lines", "if", "(", "opts", ".", "includeTag", ")", "{", "prev", "=", "prev", "+", "'\\n'", ";", "}", "return", "prev", ";", "}", ",", "''", ")", ".", "value", "(", ")", ";", "}" ]
Merge release notes for a list of versions
[ "Merge", "release", "notes", "for", "a", "list", "of", "versions" ]
52c91a66c9269e3dac754c276c10333a966f545f
https://github.com/GitbookIO/nuts/blob/52c91a66c9269e3dac754c276c10333a966f545f/lib/utils/notes.js#L4-L29
12,055
GitbookIO/nuts
lib/utils/win-releases.js
hashPrerelease
function hashPrerelease(s) { if (_.isString(s[0])) { return (_.indexOf(CHANNELS, s[0]) + 1) * CHANNEL_MAGINITUDE + (s[1] || 0); } else { return s[0]; } }
javascript
function hashPrerelease(s) { if (_.isString(s[0])) { return (_.indexOf(CHANNELS, s[0]) + 1) * CHANNEL_MAGINITUDE + (s[1] || 0); } else { return s[0]; } }
[ "function", "hashPrerelease", "(", "s", ")", "{", "if", "(", "_", ".", "isString", "(", "s", "[", "0", "]", ")", ")", "{", "return", "(", "_", ".", "indexOf", "(", "CHANNELS", ",", "s", "[", "0", "]", ")", "+", "1", ")", "*", "CHANNEL_MAGINITUDE", "+", "(", "s", "[", "1", "]", "||", "0", ")", ";", "}", "else", "{", "return", "s", "[", "0", "]", ";", "}", "}" ]
Hash a prerelease
[ "Hash", "a", "prerelease" ]
52c91a66c9269e3dac754c276c10333a966f545f
https://github.com/GitbookIO/nuts/blob/52c91a66c9269e3dac754c276c10333a966f545f/lib/utils/win-releases.js#L16-L22
12,056
GitbookIO/nuts
lib/utils/win-releases.js
normVersion
function normVersion(tag) { var parts = new semver.SemVer(tag); var prerelease = ""; if (parts.prerelease && parts.prerelease.length > 0) { prerelease = hashPrerelease(parts.prerelease); } return [ parts.major, parts.minor, parts.patch ].join('.') + (prerelease? '.'+prerelease : ''); }
javascript
function normVersion(tag) { var parts = new semver.SemVer(tag); var prerelease = ""; if (parts.prerelease && parts.prerelease.length > 0) { prerelease = hashPrerelease(parts.prerelease); } return [ parts.major, parts.minor, parts.patch ].join('.') + (prerelease? '.'+prerelease : ''); }
[ "function", "normVersion", "(", "tag", ")", "{", "var", "parts", "=", "new", "semver", ".", "SemVer", "(", "tag", ")", ";", "var", "prerelease", "=", "\"\"", ";", "if", "(", "parts", ".", "prerelease", "&&", "parts", ".", "prerelease", ".", "length", ">", "0", ")", "{", "prerelease", "=", "hashPrerelease", "(", "parts", ".", "prerelease", ")", ";", "}", "return", "[", "parts", ".", "major", ",", "parts", ".", "minor", ",", "parts", ".", "patch", "]", ".", "join", "(", "'.'", ")", "+", "(", "prerelease", "?", "'.'", "+", "prerelease", ":", "''", ")", ";", "}" ]
Map a semver version to a windows version
[ "Map", "a", "semver", "version", "to", "a", "windows", "version" ]
52c91a66c9269e3dac754c276c10333a966f545f
https://github.com/GitbookIO/nuts/blob/52c91a66c9269e3dac754c276c10333a966f545f/lib/utils/win-releases.js#L25-L38
12,057
GitbookIO/nuts
lib/utils/win-releases.js
toSemver
function toSemver(tag) { var parts = tag.split('.'); var version = parts.slice(0, 3).join('.'); var prerelease = Number(parts[3]); // semver == windows version if (!prerelease) return version; var channelId = Math.floor(prerelease/CHANNEL_MAGINITUDE); var channel = CHANNELS[channelId - 1]; var count = prerelease - (channelId*CHANNEL_MAGINITUDE); return version + '-' + channel + '.' + count }
javascript
function toSemver(tag) { var parts = tag.split('.'); var version = parts.slice(0, 3).join('.'); var prerelease = Number(parts[3]); // semver == windows version if (!prerelease) return version; var channelId = Math.floor(prerelease/CHANNEL_MAGINITUDE); var channel = CHANNELS[channelId - 1]; var count = prerelease - (channelId*CHANNEL_MAGINITUDE); return version + '-' + channel + '.' + count }
[ "function", "toSemver", "(", "tag", ")", "{", "var", "parts", "=", "tag", ".", "split", "(", "'.'", ")", ";", "var", "version", "=", "parts", ".", "slice", "(", "0", ",", "3", ")", ".", "join", "(", "'.'", ")", ";", "var", "prerelease", "=", "Number", "(", "parts", "[", "3", "]", ")", ";", "// semver == windows version", "if", "(", "!", "prerelease", ")", "return", "version", ";", "var", "channelId", "=", "Math", ".", "floor", "(", "prerelease", "/", "CHANNEL_MAGINITUDE", ")", ";", "var", "channel", "=", "CHANNELS", "[", "channelId", "-", "1", "]", ";", "var", "count", "=", "prerelease", "-", "(", "channelId", "*", "CHANNEL_MAGINITUDE", ")", ";", "return", "version", "+", "'-'", "+", "channel", "+", "'.'", "+", "count", "}" ]
Map a windows version to a semver
[ "Map", "a", "windows", "version", "to", "a", "semver" ]
52c91a66c9269e3dac754c276c10333a966f545f
https://github.com/GitbookIO/nuts/blob/52c91a66c9269e3dac754c276c10333a966f545f/lib/utils/win-releases.js#L41-L54
12,058
GitbookIO/nuts
lib/utils/win-releases.js
generateRELEASES
function generateRELEASES(entries) { return _.map(entries, function(entry) { var filename = entry.filename; if (!filename) { filename = [ entry.app, entry.version, entry.isDelta? 'delta.nupkg' : 'full.nupkg' ].join('-'); } return [ entry.sha, filename, entry.size ].join(' '); }) .join('\n'); }
javascript
function generateRELEASES(entries) { return _.map(entries, function(entry) { var filename = entry.filename; if (!filename) { filename = [ entry.app, entry.version, entry.isDelta? 'delta.nupkg' : 'full.nupkg' ].join('-'); } return [ entry.sha, filename, entry.size ].join(' '); }) .join('\n'); }
[ "function", "generateRELEASES", "(", "entries", ")", "{", "return", "_", ".", "map", "(", "entries", ",", "function", "(", "entry", ")", "{", "var", "filename", "=", "entry", ".", "filename", ";", "if", "(", "!", "filename", ")", "{", "filename", "=", "[", "entry", ".", "app", ",", "entry", ".", "version", ",", "entry", ".", "isDelta", "?", "'delta.nupkg'", ":", "'full.nupkg'", "]", ".", "join", "(", "'-'", ")", ";", "}", "return", "[", "entry", ".", "sha", ",", "filename", ",", "entry", ".", "size", "]", ".", "join", "(", "' '", ")", ";", "}", ")", ".", "join", "(", "'\\n'", ")", ";", "}" ]
Generate a RELEASES file
[ "Generate", "a", "RELEASES", "file" ]
52c91a66c9269e3dac754c276c10333a966f545f
https://github.com/GitbookIO/nuts/blob/52c91a66c9269e3dac754c276c10333a966f545f/lib/utils/win-releases.js#L98-L117
12,059
GitbookIO/nuts
lib/versions.js
normalizeVersion
function normalizeVersion(release) { // Ignore draft if (release.draft) return null; var downloadCount = 0; var releasePlatforms = _.chain(release.assets) .map(function(asset) { var platform = platforms.detect(asset.name); if (!platform) return null; downloadCount = downloadCount + asset.download_count; return { id: String(asset.id), type: platform, filename: asset.name, size: asset.size, content_type: asset.content_type, raw: asset }; }) .compact() .value(); return { tag: normalizeTag(release.tag_name).split('-')[0], channel: extractChannel(release.tag_name), notes: release.body || "", published_at: new Date(release.published_at), platforms: releasePlatforms }; }
javascript
function normalizeVersion(release) { // Ignore draft if (release.draft) return null; var downloadCount = 0; var releasePlatforms = _.chain(release.assets) .map(function(asset) { var platform = platforms.detect(asset.name); if (!platform) return null; downloadCount = downloadCount + asset.download_count; return { id: String(asset.id), type: platform, filename: asset.name, size: asset.size, content_type: asset.content_type, raw: asset }; }) .compact() .value(); return { tag: normalizeTag(release.tag_name).split('-')[0], channel: extractChannel(release.tag_name), notes: release.body || "", published_at: new Date(release.published_at), platforms: releasePlatforms }; }
[ "function", "normalizeVersion", "(", "release", ")", "{", "// Ignore draft", "if", "(", "release", ".", "draft", ")", "return", "null", ";", "var", "downloadCount", "=", "0", ";", "var", "releasePlatforms", "=", "_", ".", "chain", "(", "release", ".", "assets", ")", ".", "map", "(", "function", "(", "asset", ")", "{", "var", "platform", "=", "platforms", ".", "detect", "(", "asset", ".", "name", ")", ";", "if", "(", "!", "platform", ")", "return", "null", ";", "downloadCount", "=", "downloadCount", "+", "asset", ".", "download_count", ";", "return", "{", "id", ":", "String", "(", "asset", ".", "id", ")", ",", "type", ":", "platform", ",", "filename", ":", "asset", ".", "name", ",", "size", ":", "asset", ".", "size", ",", "content_type", ":", "asset", ".", "content_type", ",", "raw", ":", "asset", "}", ";", "}", ")", ".", "compact", "(", ")", ".", "value", "(", ")", ";", "return", "{", "tag", ":", "normalizeTag", "(", "release", ".", "tag_name", ")", ".", "split", "(", "'-'", ")", "[", "0", "]", ",", "channel", ":", "extractChannel", "(", "release", ".", "tag_name", ")", ",", "notes", ":", "release", ".", "body", "||", "\"\"", ",", "published_at", ":", "new", "Date", "(", "release", ".", "published_at", ")", ",", "platforms", ":", "releasePlatforms", "}", ";", "}" ]
Normalize a release to a version
[ "Normalize", "a", "release", "to", "a", "version" ]
52c91a66c9269e3dac754c276c10333a966f545f
https://github.com/GitbookIO/nuts/blob/52c91a66c9269e3dac754c276c10333a966f545f/lib/versions.js#L22-L52
12,060
GitbookIO/nuts
lib/versions.js
compareVersions
function compareVersions(v1, v2) { if (semver.gt(v1.tag, v2.tag)) { return -1; } if (semver.lt(v1.tag, v2.tag)) { return 1; } return 0; }
javascript
function compareVersions(v1, v2) { if (semver.gt(v1.tag, v2.tag)) { return -1; } if (semver.lt(v1.tag, v2.tag)) { return 1; } return 0; }
[ "function", "compareVersions", "(", "v1", ",", "v2", ")", "{", "if", "(", "semver", ".", "gt", "(", "v1", ".", "tag", ",", "v2", ".", "tag", ")", ")", "{", "return", "-", "1", ";", "}", "if", "(", "semver", ".", "lt", "(", "v1", ".", "tag", ",", "v2", ".", "tag", ")", ")", "{", "return", "1", ";", "}", "return", "0", ";", "}" ]
Compare two version
[ "Compare", "two", "version" ]
52c91a66c9269e3dac754c276c10333a966f545f
https://github.com/GitbookIO/nuts/blob/52c91a66c9269e3dac754c276c10333a966f545f/lib/versions.js#L55-L63
12,061
getsentry/sentry-cli
js/helper.js
execute
function execute(args, live, silent) { const env = Object.assign({}, process.env); return new Promise((resolve, reject) => { if (live === true) { const pid = childProcess.spawn(getPath(), args, { env, stdio: ['inherit', silent ? 'pipe' : 'inherit', 'inherit'], }); pid.on('exit', () => { resolve(); }); } else { childProcess.execFile(getPath(), args, { env }, (err, stdout) => { if (err) { reject(err); } else { resolve(stdout); } }); } }); }
javascript
function execute(args, live, silent) { const env = Object.assign({}, process.env); return new Promise((resolve, reject) => { if (live === true) { const pid = childProcess.spawn(getPath(), args, { env, stdio: ['inherit', silent ? 'pipe' : 'inherit', 'inherit'], }); pid.on('exit', () => { resolve(); }); } else { childProcess.execFile(getPath(), args, { env }, (err, stdout) => { if (err) { reject(err); } else { resolve(stdout); } }); } }); }
[ "function", "execute", "(", "args", ",", "live", ",", "silent", ")", "{", "const", "env", "=", "Object", ".", "assign", "(", "{", "}", ",", "process", ".", "env", ")", ";", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "live", "===", "true", ")", "{", "const", "pid", "=", "childProcess", ".", "spawn", "(", "getPath", "(", ")", ",", "args", ",", "{", "env", ",", "stdio", ":", "[", "'inherit'", ",", "silent", "?", "'pipe'", ":", "'inherit'", ",", "'inherit'", "]", ",", "}", ")", ";", "pid", ".", "on", "(", "'exit'", ",", "(", ")", "=>", "{", "resolve", "(", ")", ";", "}", ")", ";", "}", "else", "{", "childProcess", ".", "execFile", "(", "getPath", "(", ")", ",", "args", ",", "{", "env", "}", ",", "(", "err", ",", "stdout", ")", "=>", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "else", "{", "resolve", "(", "stdout", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "}" ]
Runs `sentry-cli` with the given command line arguments. Use {@link prepareCommand} to specify the command and add arguments for command- specific options. For top-level options, use {@link serializeOptions} directly. The returned promise resolves with the standard output of the command invocation including all newlines. In order to parse this output, be sure to trim the output first. If the command failed to execute, the Promise rejects with the error returned by the CLI. This error includes a `code` property with the process exit status. @example const output = await execute(['--version']); expect(output.trim()).toBe('sentry-cli x.y.z'); @param {string[]} args Command line arguments passed to `sentry-cli`. @param {boolean} live We inherit stdio to display `sentry-cli` output directly. @param {boolean} silent Disable stdout for silents build (CI/Webpack Stats, ...) @returns {Promise.<string>} A promise that resolves to the standard output.
[ "Runs", "sentry", "-", "cli", "with", "the", "given", "command", "line", "arguments", "." ]
96ada912dbf9264fa0f19b4bddbc2f6dacccabef
https://github.com/getsentry/sentry-cli/blob/96ada912dbf9264fa0f19b4bddbc2f6dacccabef/js/helper.js#L133-L154
12,062
mourner/suncalc
suncalc.js
getSetJ
function getSetJ(h, lw, phi, dec, n, M, L) { var w = hourAngle(h, phi, dec), a = approxTransit(w, lw, n); return solarTransitJ(a, M, L); }
javascript
function getSetJ(h, lw, phi, dec, n, M, L) { var w = hourAngle(h, phi, dec), a = approxTransit(w, lw, n); return solarTransitJ(a, M, L); }
[ "function", "getSetJ", "(", "h", ",", "lw", ",", "phi", ",", "dec", ",", "n", ",", "M", ",", "L", ")", "{", "var", "w", "=", "hourAngle", "(", "h", ",", "phi", ",", "dec", ")", ",", "a", "=", "approxTransit", "(", "w", ",", "lw", ",", "n", ")", ";", "return", "solarTransitJ", "(", "a", ",", "M", ",", "L", ")", ";", "}" ]
returns set time for the given sun altitude
[ "returns", "set", "time", "for", "the", "given", "sun", "altitude" ]
00372d06b4c4a802afb3aef754d04cba7262905b
https://github.com/mourner/suncalc/blob/00372d06b4c4a802afb3aef754d04cba7262905b/suncalc.js#L130-L135
12,063
TahaSh/vue-paginate
src/components/PaginateLinks.js
getLimitedLinksMetadata
function getLimitedLinksMetadata (limitedLinks) { return limitedLinks.map((link, index) => { if (link === ELLIPSES && limitedLinks[index - 1] === 0) { return 'left-ellipses' } else if (link === ELLIPSES && limitedLinks[index - 1] !== 0) { return 'right-ellipses' } return link }) }
javascript
function getLimitedLinksMetadata (limitedLinks) { return limitedLinks.map((link, index) => { if (link === ELLIPSES && limitedLinks[index - 1] === 0) { return 'left-ellipses' } else if (link === ELLIPSES && limitedLinks[index - 1] !== 0) { return 'right-ellipses' } return link }) }
[ "function", "getLimitedLinksMetadata", "(", "limitedLinks", ")", "{", "return", "limitedLinks", ".", "map", "(", "(", "link", ",", "index", ")", "=>", "{", "if", "(", "link", "===", "ELLIPSES", "&&", "limitedLinks", "[", "index", "-", "1", "]", "===", "0", ")", "{", "return", "'left-ellipses'", "}", "else", "if", "(", "link", "===", "ELLIPSES", "&&", "limitedLinks", "[", "index", "-", "1", "]", "!==", "0", ")", "{", "return", "'right-ellipses'", "}", "return", "link", "}", ")", "}" ]
Mainly used here to check whether the displayed ellipses is for showing previous or next links
[ "Mainly", "used", "here", "to", "check", "whether", "the", "displayed", "ellipses", "is", "for", "showing", "previous", "or", "next", "links" ]
fcff039e90c9e3be5fbc091a47bf67d467fc3cd1
https://github.com/TahaSh/vue-paginate/blob/fcff039e90c9e3be5fbc091a47bf67d467fc3cd1/src/components/PaginateLinks.js#L314-L323
12,064
ractivejs/ractive
src/view/RepeatedFragment.js
findDelegate
function findDelegate(start) { let frag = start; let delegate, el; out: while (frag) { // find next element el = 0; while (!el && frag) { if (frag.owner.type === ELEMENT) el = frag.owner; if (frag.owner.ractive && frag.owner.ractive.delegate === false) break out; frag = frag.parent || frag.componentParent; } if (el.delegate === false) break out; delegate = el.delegate || el; // find next repeated fragment while (frag) { if (frag.iterations) break; if (frag.owner.ractive && frag.owner.ractive.delegate === false) break out; frag = frag.parent || frag.componentParent; } } return delegate; }
javascript
function findDelegate(start) { let frag = start; let delegate, el; out: while (frag) { // find next element el = 0; while (!el && frag) { if (frag.owner.type === ELEMENT) el = frag.owner; if (frag.owner.ractive && frag.owner.ractive.delegate === false) break out; frag = frag.parent || frag.componentParent; } if (el.delegate === false) break out; delegate = el.delegate || el; // find next repeated fragment while (frag) { if (frag.iterations) break; if (frag.owner.ractive && frag.owner.ractive.delegate === false) break out; frag = frag.parent || frag.componentParent; } } return delegate; }
[ "function", "findDelegate", "(", "start", ")", "{", "let", "frag", "=", "start", ";", "let", "delegate", ",", "el", ";", "out", ":", "while", "(", "frag", ")", "{", "// find next element", "el", "=", "0", ";", "while", "(", "!", "el", "&&", "frag", ")", "{", "if", "(", "frag", ".", "owner", ".", "type", "===", "ELEMENT", ")", "el", "=", "frag", ".", "owner", ";", "if", "(", "frag", ".", "owner", ".", "ractive", "&&", "frag", ".", "owner", ".", "ractive", ".", "delegate", "===", "false", ")", "break", "out", ";", "frag", "=", "frag", ".", "parent", "||", "frag", ".", "componentParent", ";", "}", "if", "(", "el", ".", "delegate", "===", "false", ")", "break", "out", ";", "delegate", "=", "el", ".", "delegate", "||", "el", ";", "// find next repeated fragment", "while", "(", "frag", ")", "{", "if", "(", "frag", ".", "iterations", ")", "break", ";", "if", "(", "frag", ".", "owner", ".", "ractive", "&&", "frag", ".", "owner", ".", "ractive", ".", "delegate", "===", "false", ")", "break", "out", ";", "frag", "=", "frag", ".", "parent", "||", "frag", ".", "componentParent", ";", "}", "}", "return", "delegate", ";", "}" ]
find the topmost delegate
[ "find", "the", "topmost", "delegate" ]
421f1feb95b6d572e41eb379da7cfd0ea5c5a4ce
https://github.com/ractivejs/ractive/blob/421f1feb95b6d572e41eb379da7cfd0ea5c5a4ce/src/view/RepeatedFragment.js#L521-L546
12,065
ractivejs/ractive
src/events/fireEvent.js
variants
function variants(name, initial) { const map = initial ? initStars : bubbleStars; if (map[name]) return map[name]; const parts = name.split('.'); const result = []; let base = false; // initial events the implicit namespace of 'this' if (initial) { parts.unshift('this'); base = true; } // use max - 1 bits as a bitmap to pick a part or a * // need to skip the full star case if the namespace is synthetic const max = Math.pow(2, parts.length) - (initial ? 1 : 0); for (let i = 0; i < max; i++) { const join = []; for (let j = 0; j < parts.length; j++) { join.push(1 & (i >> j) ? '*' : parts[j]); } result.unshift(join.join('.')); } if (base) { // include non-this-namespaced versions if (parts.length > 2) { result.push.apply(result, variants(name, false)); } else { result.push('*'); result.push(name); } } map[name] = result; return result; }
javascript
function variants(name, initial) { const map = initial ? initStars : bubbleStars; if (map[name]) return map[name]; const parts = name.split('.'); const result = []; let base = false; // initial events the implicit namespace of 'this' if (initial) { parts.unshift('this'); base = true; } // use max - 1 bits as a bitmap to pick a part or a * // need to skip the full star case if the namespace is synthetic const max = Math.pow(2, parts.length) - (initial ? 1 : 0); for (let i = 0; i < max; i++) { const join = []; for (let j = 0; j < parts.length; j++) { join.push(1 & (i >> j) ? '*' : parts[j]); } result.unshift(join.join('.')); } if (base) { // include non-this-namespaced versions if (parts.length > 2) { result.push.apply(result, variants(name, false)); } else { result.push('*'); result.push(name); } } map[name] = result; return result; }
[ "function", "variants", "(", "name", ",", "initial", ")", "{", "const", "map", "=", "initial", "?", "initStars", ":", "bubbleStars", ";", "if", "(", "map", "[", "name", "]", ")", "return", "map", "[", "name", "]", ";", "const", "parts", "=", "name", ".", "split", "(", "'.'", ")", ";", "const", "result", "=", "[", "]", ";", "let", "base", "=", "false", ";", "// initial events the implicit namespace of 'this'", "if", "(", "initial", ")", "{", "parts", ".", "unshift", "(", "'this'", ")", ";", "base", "=", "true", ";", "}", "// use max - 1 bits as a bitmap to pick a part or a *", "// need to skip the full star case if the namespace is synthetic", "const", "max", "=", "Math", ".", "pow", "(", "2", ",", "parts", ".", "length", ")", "-", "(", "initial", "?", "1", ":", "0", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "max", ";", "i", "++", ")", "{", "const", "join", "=", "[", "]", ";", "for", "(", "let", "j", "=", "0", ";", "j", "<", "parts", ".", "length", ";", "j", "++", ")", "{", "join", ".", "push", "(", "1", "&", "(", "i", ">>", "j", ")", "?", "'*'", ":", "parts", "[", "j", "]", ")", ";", "}", "result", ".", "unshift", "(", "join", ".", "join", "(", "'.'", ")", ")", ";", "}", "if", "(", "base", ")", "{", "// include non-this-namespaced versions", "if", "(", "parts", ".", "length", ">", "2", ")", "{", "result", ".", "push", ".", "apply", "(", "result", ",", "variants", "(", "name", ",", "false", ")", ")", ";", "}", "else", "{", "result", ".", "push", "(", "'*'", ")", ";", "result", ".", "push", "(", "name", ")", ";", "}", "}", "map", "[", "name", "]", "=", "result", ";", "return", "result", ";", "}" ]
cartesian product of name parts and stars adjusted appropriately for special cases
[ "cartesian", "product", "of", "name", "parts", "and", "stars", "adjusted", "appropriately", "for", "special", "cases" ]
421f1feb95b6d572e41eb379da7cfd0ea5c5a4ce
https://github.com/ractivejs/ractive/blob/421f1feb95b6d572e41eb379da7cfd0ea5c5a4ce/src/events/fireEvent.js#L8-L45
12,066
ractivejs/ractive
gobblefile.js
transpile
function transpile(src, options) { return buble.transform(src, { target: { ie: 9 }, transforms: { modules: false } }); }
javascript
function transpile(src, options) { return buble.transform(src, { target: { ie: 9 }, transforms: { modules: false } }); }
[ "function", "transpile", "(", "src", ",", "options", ")", "{", "return", "buble", ".", "transform", "(", "src", ",", "{", "target", ":", "{", "ie", ":", "9", "}", ",", "transforms", ":", "{", "modules", ":", "false", "}", "}", ")", ";", "}" ]
Essentially gobble-buble but takes out the middleman. eslint-disable-next-line no-unused-vars
[ "Essentially", "gobble", "-", "buble", "but", "takes", "out", "the", "middleman", ".", "eslint", "-", "disable", "-", "next", "-", "line", "no", "-", "unused", "-", "vars" ]
421f1feb95b6d572e41eb379da7cfd0ea5c5a4ce
https://github.com/ractivejs/ractive/blob/421f1feb95b6d572e41eb379da7cfd0ea5c5a4ce/gobblefile.js#L203-L208
12,067
ractivejs/ractive
gobblefile.js
replacePlaceholders
function replacePlaceholders(src, options) { return Object.keys(placeholders).reduce((out, placeholder) => { return out.replace(new RegExp(`${placeholder}`, 'g'), placeholders[placeholder]); }, src); }
javascript
function replacePlaceholders(src, options) { return Object.keys(placeholders).reduce((out, placeholder) => { return out.replace(new RegExp(`${placeholder}`, 'g'), placeholders[placeholder]); }, src); }
[ "function", "replacePlaceholders", "(", "src", ",", "options", ")", "{", "return", "Object", ".", "keys", "(", "placeholders", ")", ".", "reduce", "(", "(", "out", ",", "placeholder", ")", "=>", "{", "return", "out", ".", "replace", "(", "new", "RegExp", "(", "`", "${", "placeholder", "}", "`", ",", "'g'", ")", ",", "placeholders", "[", "placeholder", "]", ")", ";", "}", ",", "src", ")", ";", "}" ]
Looks for placeholders in the code and replaces them. eslint-disable-next-line no-unused-vars
[ "Looks", "for", "placeholders", "in", "the", "code", "and", "replaces", "them", ".", "eslint", "-", "disable", "-", "next", "-", "line", "no", "-", "unused", "-", "vars" ]
421f1feb95b6d572e41eb379da7cfd0ea5c5a4ce
https://github.com/ractivejs/ractive/blob/421f1feb95b6d572e41eb379da7cfd0ea5c5a4ce/gobblefile.js#L223-L227
12,068
facebook/fbjs
packages/fbjs/src/unicode/UnicodeHangulKorean.js
decomposeSyllable
function decomposeSyllable(codePoint) { const sylSIndex = codePoint - SBASE; const sylTIndex = sylSIndex % TCOUNT; return String.fromCharCode(LBASE + sylSIndex / NCOUNT) + String.fromCharCode(VBASE + (sylSIndex % NCOUNT) / TCOUNT) + ((sylTIndex > 0) ? String.fromCharCode(TBASE + sylTIndex) : ''); }
javascript
function decomposeSyllable(codePoint) { const sylSIndex = codePoint - SBASE; const sylTIndex = sylSIndex % TCOUNT; return String.fromCharCode(LBASE + sylSIndex / NCOUNT) + String.fromCharCode(VBASE + (sylSIndex % NCOUNT) / TCOUNT) + ((sylTIndex > 0) ? String.fromCharCode(TBASE + sylTIndex) : ''); }
[ "function", "decomposeSyllable", "(", "codePoint", ")", "{", "const", "sylSIndex", "=", "codePoint", "-", "SBASE", ";", "const", "sylTIndex", "=", "sylSIndex", "%", "TCOUNT", ";", "return", "String", ".", "fromCharCode", "(", "LBASE", "+", "sylSIndex", "/", "NCOUNT", ")", "+", "String", ".", "fromCharCode", "(", "VBASE", "+", "(", "sylSIndex", "%", "NCOUNT", ")", "/", "TCOUNT", ")", "+", "(", "(", "sylTIndex", ">", "0", ")", "?", "String", ".", "fromCharCode", "(", "TBASE", "+", "sylTIndex", ")", ":", "''", ")", ";", "}" ]
Maps one Hangul Syllable code-point to the equivalent Hangul Conjoining Jamo characters, as defined in UnicodeData.txt. @param {number} codePoint One Unicode character @output {string}
[ "Maps", "one", "Hangul", "Syllable", "code", "-", "point", "to", "the", "equivalent", "Hangul", "Conjoining", "Jamo", "characters", "as", "defined", "in", "UnicodeData", ".", "txt", "." ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/fbjs/src/unicode/UnicodeHangulKorean.js#L119-L125
12,069
facebook/fbjs
packages/fbjs/src/functional/groupArray.js
groupArray
function groupArray(array, fn) { var ret = {}; for (var ii = 0; ii < array.length; ii++) { var result = fn.call(array, array[ii], ii); if (!ret[result]) { ret[result] = []; } ret[result].push(array[ii]); } return ret; }
javascript
function groupArray(array, fn) { var ret = {}; for (var ii = 0; ii < array.length; ii++) { var result = fn.call(array, array[ii], ii); if (!ret[result]) { ret[result] = []; } ret[result].push(array[ii]); } return ret; }
[ "function", "groupArray", "(", "array", ",", "fn", ")", "{", "var", "ret", "=", "{", "}", ";", "for", "(", "var", "ii", "=", "0", ";", "ii", "<", "array", ".", "length", ";", "ii", "++", ")", "{", "var", "result", "=", "fn", ".", "call", "(", "array", ",", "array", "[", "ii", "]", ",", "ii", ")", ";", "if", "(", "!", "ret", "[", "result", "]", ")", "{", "ret", "[", "result", "]", "=", "[", "]", ";", "}", "ret", "[", "result", "]", ".", "push", "(", "array", "[", "ii", "]", ")", ";", "}", "return", "ret", ";", "}" ]
Groups all items in the array using the specified function. An object will be returned where the keys are the group names, and the values are arrays of all the items in that group. @param {array} array @param {function} fn Should return a string with a group name @return {object} items grouped using fn
[ "Groups", "all", "items", "in", "the", "array", "using", "the", "specified", "function", ".", "An", "object", "will", "be", "returned", "where", "the", "keys", "are", "the", "group", "names", "and", "the", "values", "are", "arrays", "of", "all", "the", "items", "in", "that", "group", "." ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/fbjs/src/functional/groupArray.js#L22-L32
12,070
facebook/fbjs
packages/fbjs/src/useragent/UserAgent.js
compare
function compare(name, version, query, normalizer) { // check for exact match with no version if (name === query) { return true; } // check for non-matching names if (!query.startsWith(name)) { return false; } // full comparison with version let range = query.slice(name.length); if (version) { range = normalizer ? normalizer(range) : range; return VersionRange.contains(range, version); } return false; }
javascript
function compare(name, version, query, normalizer) { // check for exact match with no version if (name === query) { return true; } // check for non-matching names if (!query.startsWith(name)) { return false; } // full comparison with version let range = query.slice(name.length); if (version) { range = normalizer ? normalizer(range) : range; return VersionRange.contains(range, version); } return false; }
[ "function", "compare", "(", "name", ",", "version", ",", "query", ",", "normalizer", ")", "{", "// check for exact match with no version", "if", "(", "name", "===", "query", ")", "{", "return", "true", ";", "}", "// check for non-matching names", "if", "(", "!", "query", ".", "startsWith", "(", "name", ")", ")", "{", "return", "false", ";", "}", "// full comparison with version", "let", "range", "=", "query", ".", "slice", "(", "name", ".", "length", ")", ";", "if", "(", "version", ")", "{", "range", "=", "normalizer", "?", "normalizer", "(", "range", ")", ":", "range", ";", "return", "VersionRange", ".", "contains", "(", "range", ",", "version", ")", ";", "}", "return", "false", ";", "}" ]
Checks to see whether `name` and `version` satisfy `query`. @param {string} name Name of the browser, device, engine or platform @param {?string} version Version of the browser, engine or platform @param {string} query Query of form "Name [range expression]" @param {?function} normalizer Optional pre-processor for range expression @return {boolean}
[ "Checks", "to", "see", "whether", "name", "and", "version", "satisfy", "query", "." ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/fbjs/src/useragent/UserAgent.js#L27-L46
12,071
facebook/fbjs
packages/fbjs/src/core/dom/getElementPosition.js
getElementPosition
function getElementPosition(element) { const rect = getElementRect(element); return { x: rect.left, y: rect.top, width: rect.right - rect.left, height: rect.bottom - rect.top }; }
javascript
function getElementPosition(element) { const rect = getElementRect(element); return { x: rect.left, y: rect.top, width: rect.right - rect.left, height: rect.bottom - rect.top }; }
[ "function", "getElementPosition", "(", "element", ")", "{", "const", "rect", "=", "getElementRect", "(", "element", ")", ";", "return", "{", "x", ":", "rect", ".", "left", ",", "y", ":", "rect", ".", "top", ",", "width", ":", "rect", ".", "right", "-", "rect", ".", "left", ",", "height", ":", "rect", ".", "bottom", "-", "rect", ".", "top", "}", ";", "}" ]
Gets an element's position in pixels relative to the viewport. The returned object represents the position of the element's top left corner. @param {DOMElement} element @return {object}
[ "Gets", "an", "element", "s", "position", "in", "pixels", "relative", "to", "the", "viewport", ".", "The", "returned", "object", "represents", "the", "position", "of", "the", "element", "s", "top", "left", "corner", "." ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/fbjs/src/core/dom/getElementPosition.js#L20-L28
12,072
facebook/fbjs
packages/fbjs/src/useragent/VersionRange.js
checkOrExpression
function checkOrExpression(range, version) { const expressions = range.split(orRegex); if (expressions.length > 1) { return expressions.some(range => VersionRange.contains(range, version)); } else { range = expressions[0].trim(); return checkRangeExpression(range, version); } }
javascript
function checkOrExpression(range, version) { const expressions = range.split(orRegex); if (expressions.length > 1) { return expressions.some(range => VersionRange.contains(range, version)); } else { range = expressions[0].trim(); return checkRangeExpression(range, version); } }
[ "function", "checkOrExpression", "(", "range", ",", "version", ")", "{", "const", "expressions", "=", "range", ".", "split", "(", "orRegex", ")", ";", "if", "(", "expressions", ".", "length", ">", "1", ")", "{", "return", "expressions", ".", "some", "(", "range", "=>", "VersionRange", ".", "contains", "(", "range", ",", "version", ")", ")", ";", "}", "else", "{", "range", "=", "expressions", "[", "0", "]", ".", "trim", "(", ")", ";", "return", "checkRangeExpression", "(", "range", ",", "version", ")", ";", "}", "}" ]
Splits input `range` on "||" and returns true if any subrange matches `version`. @param {string} range @param {string} version @returns {boolean}
[ "Splits", "input", "range", "on", "||", "and", "returns", "true", "if", "any", "subrange", "matches", "version", "." ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/fbjs/src/useragent/VersionRange.js#L28-L37
12,073
facebook/fbjs
packages/fbjs/src/useragent/VersionRange.js
zeroPad
function zeroPad(array, length) { for (let i = array.length; i < length; i++) { array[i] = '0'; } }
javascript
function zeroPad(array, length) { for (let i = array.length; i < length; i++) { array[i] = '0'; } }
[ "function", "zeroPad", "(", "array", ",", "length", ")", "{", "for", "(", "let", "i", "=", "array", ".", "length", ";", "i", "<", "length", ";", "i", "++", ")", "{", "array", "[", "i", "]", "=", "'0'", ";", "}", "}" ]
Zero-pads array `array` until it is at least `length` long. @param {array} array @param {number} length
[ "Zero", "-", "pads", "array", "array", "until", "it", "is", "at", "least", "length", "long", "." ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/fbjs/src/useragent/VersionRange.js#L237-L241
12,074
facebook/fbjs
packages/fbjs/src/useragent/VersionRange.js
compare
function compare(a, b) { invariant(typeof a === typeof b, '"a" and "b" must be of the same type'); if (a > b) { return 1; } else if (a < b) { return -1; } else { return 0; } }
javascript
function compare(a, b) { invariant(typeof a === typeof b, '"a" and "b" must be of the same type'); if (a > b) { return 1; } else if (a < b) { return -1; } else { return 0; } }
[ "function", "compare", "(", "a", ",", "b", ")", "{", "invariant", "(", "typeof", "a", "===", "typeof", "b", ",", "'\"a\" and \"b\" must be of the same type'", ")", ";", "if", "(", "a", ">", "b", ")", "{", "return", "1", ";", "}", "else", "if", "(", "a", "<", "b", ")", "{", "return", "-", "1", ";", "}", "else", "{", "return", "0", ";", "}", "}" ]
Returns the ordering of `a` and `b`. @param {string|number} a @param {string|number} b @returns {number} -1, 0 or 1 to indicate whether `a` is less than, equal to, or greater than `b`, respectively
[ "Returns", "the", "ordering", "of", "a", "and", "b", "." ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/fbjs/src/useragent/VersionRange.js#L313-L323
12,075
facebook/fbjs
packages/fbjs/src/useragent/VersionRange.js
compareComponents
function compareComponents(a, b) { const [aNormalized, bNormalized] = normalizeVersions(a, b); for (let i = 0; i < bNormalized.length; i++) { const result = compareNumeric(aNormalized[i], bNormalized[i]); if (result) { return result; } } return 0; }
javascript
function compareComponents(a, b) { const [aNormalized, bNormalized] = normalizeVersions(a, b); for (let i = 0; i < bNormalized.length; i++) { const result = compareNumeric(aNormalized[i], bNormalized[i]); if (result) { return result; } } return 0; }
[ "function", "compareComponents", "(", "a", ",", "b", ")", "{", "const", "[", "aNormalized", ",", "bNormalized", "]", "=", "normalizeVersions", "(", "a", ",", "b", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "bNormalized", ".", "length", ";", "i", "++", ")", "{", "const", "result", "=", "compareNumeric", "(", "aNormalized", "[", "i", "]", ",", "bNormalized", "[", "i", "]", ")", ";", "if", "(", "result", ")", "{", "return", "result", ";", "}", "}", "return", "0", ";", "}" ]
Compares arrays of version components. @param {array<string>} a @param {array<string>} b @returns {number} -1, 0 or 1 to indicate whether `a` is less than, equal to, or greater than `b`, respectively
[ "Compares", "arrays", "of", "version", "components", "." ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/fbjs/src/useragent/VersionRange.js#L333-L344
12,076
facebook/fbjs
packages/fbjs/src/unicode/UnicodeCJK.js
hiraganaToKatakana
function hiraganaToKatakana(str) { if (!hasKana(str)) { return str; } return str.split('').map(charCodeToKatakana).join(''); }
javascript
function hiraganaToKatakana(str) { if (!hasKana(str)) { return str; } return str.split('').map(charCodeToKatakana).join(''); }
[ "function", "hiraganaToKatakana", "(", "str", ")", "{", "if", "(", "!", "hasKana", "(", "str", ")", ")", "{", "return", "str", ";", "}", "return", "str", ".", "split", "(", "''", ")", ".", "map", "(", "charCodeToKatakana", ")", ".", "join", "(", "''", ")", ";", "}" ]
Replace any Hiragana character with the matching Katakana @param {string} str @output {string}
[ "Replace", "any", "Hiragana", "character", "with", "the", "matching", "Katakana" ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/fbjs/src/unicode/UnicodeCJK.js#L145-L150
12,077
facebook/fbjs
packages/fbjs/src/unicode/UnicodeCJK.js
isKanaWithTrailingLatin
function isKanaWithTrailingLatin(str) { REGEX_IS_KANA_WITH_TRAILING_LATIN = REGEX_IS_KANA_WITH_TRAILING_LATIN || new RegExp('^' + '[' + R_KANA + ']+' + '[' + R_LATIN + ']' + '$'); return REGEX_IS_KANA_WITH_TRAILING_LATIN.test(str); }
javascript
function isKanaWithTrailingLatin(str) { REGEX_IS_KANA_WITH_TRAILING_LATIN = REGEX_IS_KANA_WITH_TRAILING_LATIN || new RegExp('^' + '[' + R_KANA + ']+' + '[' + R_LATIN + ']' + '$'); return REGEX_IS_KANA_WITH_TRAILING_LATIN.test(str); }
[ "function", "isKanaWithTrailingLatin", "(", "str", ")", "{", "REGEX_IS_KANA_WITH_TRAILING_LATIN", "=", "REGEX_IS_KANA_WITH_TRAILING_LATIN", "||", "new", "RegExp", "(", "'^'", "+", "'['", "+", "R_KANA", "+", "']+'", "+", "'['", "+", "R_LATIN", "+", "']'", "+", "'$'", ")", ";", "return", "REGEX_IS_KANA_WITH_TRAILING_LATIN", ".", "test", "(", "str", ")", ";", "}" ]
Whether the string is exactly a sequence of Kana characters followed by one Latin character. @param {string} str @output {string}
[ "Whether", "the", "string", "is", "exactly", "a", "sequence", "of", "Kana", "characters", "followed", "by", "one", "Latin", "character", "." ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/fbjs/src/unicode/UnicodeCJK.js#L160-L164
12,078
facebook/fbjs
packages/fbjs/src/core/dom/getDocumentScrollElement.js
getDocumentScrollElement
function getDocumentScrollElement(doc) { doc = doc || document; if (doc.scrollingElement) { return doc.scrollingElement; } return !isWebkit && doc.compatMode === 'CSS1Compat' ? doc.documentElement : doc.body; }
javascript
function getDocumentScrollElement(doc) { doc = doc || document; if (doc.scrollingElement) { return doc.scrollingElement; } return !isWebkit && doc.compatMode === 'CSS1Compat' ? doc.documentElement : doc.body; }
[ "function", "getDocumentScrollElement", "(", "doc", ")", "{", "doc", "=", "doc", "||", "document", ";", "if", "(", "doc", ".", "scrollingElement", ")", "{", "return", "doc", ".", "scrollingElement", ";", "}", "return", "!", "isWebkit", "&&", "doc", ".", "compatMode", "===", "'CSS1Compat'", "?", "doc", ".", "documentElement", ":", "doc", ".", "body", ";", "}" ]
Gets the element with the document scroll properties such as `scrollLeft` and `scrollHeight`. This may differ across different browsers. NOTE: The return value can be null if the DOM is not yet ready. @param {?DOMDocument} doc Defaults to current document. @return {?DOMElement}
[ "Gets", "the", "element", "with", "the", "document", "scroll", "properties", "such", "as", "scrollLeft", "and", "scrollHeight", ".", "This", "may", "differ", "across", "different", "browsers", "." ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/fbjs/src/core/dom/getDocumentScrollElement.js#L26-L34
12,079
facebook/fbjs
packages/fbjs/src/__forks__/warning.js
printWarning
function printWarning(format, ...args) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, () => args[argIndex++]); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }
javascript
function printWarning(format, ...args) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, () => args[argIndex++]); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }
[ "function", "printWarning", "(", "format", ",", "...", "args", ")", "{", "var", "argIndex", "=", "0", ";", "var", "message", "=", "'Warning: '", "+", "format", ".", "replace", "(", "/", "%s", "/", "g", ",", "(", ")", "=>", "args", "[", "argIndex", "++", "]", ")", ";", "if", "(", "typeof", "console", "!==", "'undefined'", ")", "{", "console", ".", "error", "(", "message", ")", ";", "}", "try", "{", "// --- Welcome to debugging React ---", "// This error was thrown as a convenience so that you can use this stack", "// to find the callsite that caused this warning to fire.", "throw", "new", "Error", "(", "message", ")", ";", "}", "catch", "(", "x", ")", "{", "}", "}" ]
Similar to invariant but only logs a warning if the condition is not met. This can be used to log issues in development environments in critical paths. Removing the logging code for production environments will keep the same logic and follow the same code paths.
[ "Similar", "to", "invariant", "but", "only", "logs", "a", "warning", "if", "the", "condition", "is", "not", "met", ".", "This", "can", "be", "used", "to", "log", "issues", "in", "development", "environments", "in", "critical", "paths", ".", "Removing", "the", "logging", "code", "for", "production", "environments", "will", "keep", "the", "same", "logic", "and", "follow", "the", "same", "code", "paths", "." ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/fbjs/src/__forks__/warning.js#L22-L34
12,080
facebook/fbjs
packages/fbjs/src/functional/concatAllArray.js
concatAllArray
function concatAllArray(array) { var ret = []; for (var ii = 0; ii < array.length; ii++) { var value = array[ii]; if (Array.isArray(value)) { push.apply(ret, value); } else if (value != null) { throw new TypeError( 'concatAllArray: All items in the array must be an array or null, ' + 'got "' + value + '" at index "' + ii + '" instead' ); } } return ret; }
javascript
function concatAllArray(array) { var ret = []; for (var ii = 0; ii < array.length; ii++) { var value = array[ii]; if (Array.isArray(value)) { push.apply(ret, value); } else if (value != null) { throw new TypeError( 'concatAllArray: All items in the array must be an array or null, ' + 'got "' + value + '" at index "' + ii + '" instead' ); } } return ret; }
[ "function", "concatAllArray", "(", "array", ")", "{", "var", "ret", "=", "[", "]", ";", "for", "(", "var", "ii", "=", "0", ";", "ii", "<", "array", ".", "length", ";", "ii", "++", ")", "{", "var", "value", "=", "array", "[", "ii", "]", ";", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "push", ".", "apply", "(", "ret", ",", "value", ")", ";", "}", "else", "if", "(", "value", "!=", "null", ")", "{", "throw", "new", "TypeError", "(", "'concatAllArray: All items in the array must be an array or null, '", "+", "'got \"'", "+", "value", "+", "'\" at index \"'", "+", "ii", "+", "'\" instead'", ")", ";", "}", "}", "return", "ret", ";", "}" ]
Concats an array of arrays into a single flat array. @param {array} array @return {array}
[ "Concats", "an", "array", "of", "arrays", "into", "a", "single", "flat", "array", "." ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/fbjs/src/functional/concatAllArray.js#L19-L33
12,081
facebook/fbjs
packages/fbjs/src/core/CSSCore.js
function(element, className) { invariant( !/\s/.test(className), 'CSSCore.addClass takes only a single class name. "%s" contains ' + 'multiple classes.', className ); if (className) { if (element.classList) { element.classList.add(className); } else if (!CSSCore.hasClass(element, className)) { element.className = element.className + ' ' + className; } } return element; }
javascript
function(element, className) { invariant( !/\s/.test(className), 'CSSCore.addClass takes only a single class name. "%s" contains ' + 'multiple classes.', className ); if (className) { if (element.classList) { element.classList.add(className); } else if (!CSSCore.hasClass(element, className)) { element.className = element.className + ' ' + className; } } return element; }
[ "function", "(", "element", ",", "className", ")", "{", "invariant", "(", "!", "/", "\\s", "/", ".", "test", "(", "className", ")", ",", "'CSSCore.addClass takes only a single class name. \"%s\" contains '", "+", "'multiple classes.'", ",", "className", ")", ";", "if", "(", "className", ")", "{", "if", "(", "element", ".", "classList", ")", "{", "element", ".", "classList", ".", "add", "(", "className", ")", ";", "}", "else", "if", "(", "!", "CSSCore", ".", "hasClass", "(", "element", ",", "className", ")", ")", "{", "element", ".", "className", "=", "element", ".", "className", "+", "' '", "+", "className", ";", "}", "}", "return", "element", ";", "}" ]
Adds the class passed in to the element if it doesn't already have it. @param {DOMElement} element the element to set the class on @param {string} className the CSS className @return {DOMElement} the element passed in
[ "Adds", "the", "class", "passed", "in", "to", "the", "element", "if", "it", "doesn", "t", "already", "have", "it", "." ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/fbjs/src/core/CSSCore.js#L41-L56
12,082
facebook/fbjs
packages/fbjs/src/core/CSSCore.js
function(element, className) { invariant( !/\s/.test(className), 'CSSCore.removeClass takes only a single class name. "%s" contains ' + 'multiple classes.', className ); if (className) { if (element.classList) { element.classList.remove(className); } else if (CSSCore.hasClass(element, className)) { element.className = element.className .replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1') .replace(/\s+/g, ' ') // multiple spaces to one .replace(/^\s*|\s*$/g, ''); // trim the ends } } return element; }
javascript
function(element, className) { invariant( !/\s/.test(className), 'CSSCore.removeClass takes only a single class name. "%s" contains ' + 'multiple classes.', className ); if (className) { if (element.classList) { element.classList.remove(className); } else if (CSSCore.hasClass(element, className)) { element.className = element.className .replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1') .replace(/\s+/g, ' ') // multiple spaces to one .replace(/^\s*|\s*$/g, ''); // trim the ends } } return element; }
[ "function", "(", "element", ",", "className", ")", "{", "invariant", "(", "!", "/", "\\s", "/", ".", "test", "(", "className", ")", ",", "'CSSCore.removeClass takes only a single class name. \"%s\" contains '", "+", "'multiple classes.'", ",", "className", ")", ";", "if", "(", "className", ")", "{", "if", "(", "element", ".", "classList", ")", "{", "element", ".", "classList", ".", "remove", "(", "className", ")", ";", "}", "else", "if", "(", "CSSCore", ".", "hasClass", "(", "element", ",", "className", ")", ")", "{", "element", ".", "className", "=", "element", ".", "className", ".", "replace", "(", "new", "RegExp", "(", "'(^|\\\\s)'", "+", "className", "+", "'(?:\\\\s|$)'", ",", "'g'", ")", ",", "'$1'", ")", ".", "replace", "(", "/", "\\s+", "/", "g", ",", "' '", ")", "// multiple spaces to one", ".", "replace", "(", "/", "^\\s*|\\s*$", "/", "g", ",", "''", ")", ";", "// trim the ends", "}", "}", "return", "element", ";", "}" ]
Removes the class passed in from the element @param {DOMElement} element the element to set the class on @param {string} className the CSS className @return {DOMElement} the element passed in
[ "Removes", "the", "class", "passed", "in", "from", "the", "element" ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/fbjs/src/core/CSSCore.js#L65-L83
12,083
facebook/fbjs
packages/fbjs/src/core/CSSCore.js
function(element, className, bool) { return (bool ? CSSCore.addClass : CSSCore.removeClass)(element, className); }
javascript
function(element, className, bool) { return (bool ? CSSCore.addClass : CSSCore.removeClass)(element, className); }
[ "function", "(", "element", ",", "className", ",", "bool", ")", "{", "return", "(", "bool", "?", "CSSCore", ".", "addClass", ":", "CSSCore", ".", "removeClass", ")", "(", "element", ",", "className", ")", ";", "}" ]
Helper to add or remove a class from an element based on a condition. @param {DOMElement} element the element to set the class on @param {string} className the CSS className @param {*} bool condition to whether to add or remove the class @return {DOMElement} the element passed in
[ "Helper", "to", "add", "or", "remove", "a", "class", "from", "an", "element", "based", "on", "a", "condition", "." ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/fbjs/src/core/CSSCore.js#L93-L95
12,084
facebook/fbjs
packages/fbjs/src/core/createArrayFromMixed.js
createArrayFromMixed
function createArrayFromMixed(obj) { if (!hasArrayNature(obj)) { return [obj]; } else if (Array.isArray(obj)) { return obj.slice(); } else { return toArray(obj); } }
javascript
function createArrayFromMixed(obj) { if (!hasArrayNature(obj)) { return [obj]; } else if (Array.isArray(obj)) { return obj.slice(); } else { return toArray(obj); } }
[ "function", "createArrayFromMixed", "(", "obj", ")", "{", "if", "(", "!", "hasArrayNature", "(", "obj", ")", ")", "{", "return", "[", "obj", "]", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "obj", ")", ")", "{", "return", "obj", ".", "slice", "(", ")", ";", "}", "else", "{", "return", "toArray", "(", "obj", ")", ";", "}", "}" ]
Ensure that the argument is an array by wrapping it in an array if it is not. Creates a copy of the argument if it is already an array. This is mostly useful idiomatically: var createArrayFromMixed = require('createArrayFromMixed'); function takesOneOrMoreThings(things) { things = createArrayFromMixed(things); ... } This allows you to treat `things' as an array, but accept scalars in the API. If you need to convert an array-like object, like `arguments`, into an array use toArray instead. @param {*} obj @return {array}
[ "Ensure", "that", "the", "argument", "is", "an", "array", "by", "wrapping", "it", "in", "an", "array", "if", "it", "is", "not", ".", "Creates", "a", "copy", "of", "the", "argument", "if", "it", "is", "already", "an", "array", "." ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/fbjs/src/core/createArrayFromMixed.js#L130-L138
12,085
facebook/fbjs
packages/fbjs/src/core/dom/getElementRect.js
getElementRect
function getElementRect(elem) { const docElem = elem.ownerDocument.documentElement; // FF 2, Safari 3 and Opera 9.5- do not support getBoundingClientRect(). // IE9- will throw if the element is not in the document. if (!('getBoundingClientRect' in elem) || !containsNode(docElem, elem)) { return { left: 0, right: 0, top: 0, bottom: 0 }; } // Subtracts clientTop/Left because IE8- added a 2px border to the // <html> element (see http://fburl.com/1493213). IE 7 in // Quicksmode does not report clientLeft/clientTop so there // will be an unaccounted offset of 2px when in quirksmode const rect = elem.getBoundingClientRect(); return { left: Math.round(rect.left) - docElem.clientLeft, right: Math.round(rect.right) - docElem.clientLeft, top: Math.round(rect.top) - docElem.clientTop, bottom: Math.round(rect.bottom) - docElem.clientTop }; }
javascript
function getElementRect(elem) { const docElem = elem.ownerDocument.documentElement; // FF 2, Safari 3 and Opera 9.5- do not support getBoundingClientRect(). // IE9- will throw if the element is not in the document. if (!('getBoundingClientRect' in elem) || !containsNode(docElem, elem)) { return { left: 0, right: 0, top: 0, bottom: 0 }; } // Subtracts clientTop/Left because IE8- added a 2px border to the // <html> element (see http://fburl.com/1493213). IE 7 in // Quicksmode does not report clientLeft/clientTop so there // will be an unaccounted offset of 2px when in quirksmode const rect = elem.getBoundingClientRect(); return { left: Math.round(rect.left) - docElem.clientLeft, right: Math.round(rect.right) - docElem.clientLeft, top: Math.round(rect.top) - docElem.clientTop, bottom: Math.round(rect.bottom) - docElem.clientTop }; }
[ "function", "getElementRect", "(", "elem", ")", "{", "const", "docElem", "=", "elem", ".", "ownerDocument", ".", "documentElement", ";", "// FF 2, Safari 3 and Opera 9.5- do not support getBoundingClientRect().", "// IE9- will throw if the element is not in the document.", "if", "(", "!", "(", "'getBoundingClientRect'", "in", "elem", ")", "||", "!", "containsNode", "(", "docElem", ",", "elem", ")", ")", "{", "return", "{", "left", ":", "0", ",", "right", ":", "0", ",", "top", ":", "0", ",", "bottom", ":", "0", "}", ";", "}", "// Subtracts clientTop/Left because IE8- added a 2px border to the", "// <html> element (see http://fburl.com/1493213). IE 7 in", "// Quicksmode does not report clientLeft/clientTop so there", "// will be an unaccounted offset of 2px when in quirksmode", "const", "rect", "=", "elem", ".", "getBoundingClientRect", "(", ")", ";", "return", "{", "left", ":", "Math", ".", "round", "(", "rect", ".", "left", ")", "-", "docElem", ".", "clientLeft", ",", "right", ":", "Math", ".", "round", "(", "rect", ".", "right", ")", "-", "docElem", ".", "clientLeft", ",", "top", ":", "Math", ".", "round", "(", "rect", ".", "top", ")", "-", "docElem", ".", "clientTop", ",", "bottom", ":", "Math", ".", "round", "(", "rect", ".", "bottom", ")", "-", "docElem", ".", "clientTop", "}", ";", "}" ]
Gets an element's bounding rect in pixels relative to the viewport. @param {DOMElement} elem @return {object}
[ "Gets", "an", "element", "s", "bounding", "rect", "in", "pixels", "relative", "to", "the", "viewport", "." ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/fbjs/src/core/dom/getElementRect.js#L19-L45
12,086
facebook/fbjs
packages/fbjs/src/__forks__/Style.js
function(node) { if (!node) { return null; } var ownerDocument = node.ownerDocument; while (node && node !== ownerDocument.body) { if (_isNodeScrollable(node, 'overflow') || _isNodeScrollable(node, 'overflowY') || _isNodeScrollable(node, 'overflowX')) { return node; } node = node.parentNode; } return ownerDocument.defaultView || ownerDocument.parentWindow; }
javascript
function(node) { if (!node) { return null; } var ownerDocument = node.ownerDocument; while (node && node !== ownerDocument.body) { if (_isNodeScrollable(node, 'overflow') || _isNodeScrollable(node, 'overflowY') || _isNodeScrollable(node, 'overflowX')) { return node; } node = node.parentNode; } return ownerDocument.defaultView || ownerDocument.parentWindow; }
[ "function", "(", "node", ")", "{", "if", "(", "!", "node", ")", "{", "return", "null", ";", "}", "var", "ownerDocument", "=", "node", ".", "ownerDocument", ";", "while", "(", "node", "&&", "node", "!==", "ownerDocument", ".", "body", ")", "{", "if", "(", "_isNodeScrollable", "(", "node", ",", "'overflow'", ")", "||", "_isNodeScrollable", "(", "node", ",", "'overflowY'", ")", "||", "_isNodeScrollable", "(", "node", ",", "'overflowX'", ")", ")", "{", "return", "node", ";", "}", "node", "=", "node", ".", "parentNode", ";", "}", "return", "ownerDocument", ".", "defaultView", "||", "ownerDocument", ".", "parentWindow", ";", "}" ]
Determines the nearest ancestor of a node that is scrollable. NOTE: This can be expensive if used repeatedly or on a node nested deeply. @param {?DOMNode} node Node from which to start searching. @return {?DOMWindow|DOMElement} Scroll parent of the supplied node.
[ "Determines", "the", "nearest", "ancestor", "of", "a", "node", "that", "is", "scrollable", "." ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/fbjs/src/__forks__/Style.js#L45-L59
12,087
facebook/fbjs
packages/babel-preset-fbjs/plugins/rewrite-modules.js
mapModule
function mapModule(state, module) { var moduleMap = state.opts.map || {}; if (moduleMap.hasOwnProperty(module)) { return moduleMap[module]; } // Jest understands the haste module system, so leave modules intact. if (process.env.NODE_ENV !== 'test') { var modulePrefix = state.opts.prefix; if (modulePrefix == null) { modulePrefix = './'; } return modulePrefix + module; } return null; }
javascript
function mapModule(state, module) { var moduleMap = state.opts.map || {}; if (moduleMap.hasOwnProperty(module)) { return moduleMap[module]; } // Jest understands the haste module system, so leave modules intact. if (process.env.NODE_ENV !== 'test') { var modulePrefix = state.opts.prefix; if (modulePrefix == null) { modulePrefix = './'; } return modulePrefix + module; } return null; }
[ "function", "mapModule", "(", "state", ",", "module", ")", "{", "var", "moduleMap", "=", "state", ".", "opts", ".", "map", "||", "{", "}", ";", "if", "(", "moduleMap", ".", "hasOwnProperty", "(", "module", ")", ")", "{", "return", "moduleMap", "[", "module", "]", ";", "}", "// Jest understands the haste module system, so leave modules intact.", "if", "(", "process", ".", "env", ".", "NODE_ENV", "!==", "'test'", ")", "{", "var", "modulePrefix", "=", "state", ".", "opts", ".", "prefix", ";", "if", "(", "modulePrefix", "==", "null", ")", "{", "modulePrefix", "=", "'./'", ";", "}", "return", "modulePrefix", "+", "module", ";", "}", "return", "null", ";", "}" ]
Rewrites module string literals according to the `map` and `prefix` options. This allows other npm packages to be published and used directly without being a part of the same build.
[ "Rewrites", "module", "string", "literals", "according", "to", "the", "map", "and", "prefix", "options", ".", "This", "allows", "other", "npm", "packages", "to", "be", "published", "and", "used", "directly", "without", "being", "a", "part", "of", "the", "same", "build", "." ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/babel-preset-fbjs/plugins/rewrite-modules.js#L15-L29
12,088
facebook/fbjs
packages/babel-preset-fbjs/plugins/rewrite-modules.js
transformTypeImport
function transformTypeImport(path, state) { var source = path.get('source'); if (source.type === 'StringLiteral') { var module = mapModule(state, source.node.value); if (module) { source.replaceWith(t.stringLiteral(module)); } } }
javascript
function transformTypeImport(path, state) { var source = path.get('source'); if (source.type === 'StringLiteral') { var module = mapModule(state, source.node.value); if (module) { source.replaceWith(t.stringLiteral(module)); } } }
[ "function", "transformTypeImport", "(", "path", ",", "state", ")", "{", "var", "source", "=", "path", ".", "get", "(", "'source'", ")", ";", "if", "(", "source", ".", "type", "===", "'StringLiteral'", ")", "{", "var", "module", "=", "mapModule", "(", "state", ",", "source", ".", "node", ".", "value", ")", ";", "if", "(", "module", ")", "{", "source", ".", "replaceWith", "(", "t", ".", "stringLiteral", "(", "module", ")", ")", ";", "}", "}", "}" ]
Transforms `import type Bar from 'foo'`
[ "Transforms", "import", "type", "Bar", "from", "foo" ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/babel-preset-fbjs/plugins/rewrite-modules.js#L79-L87
12,089
facebook/fbjs
packages/fbjs/src/unicode/UnicodeUtilsExtra.js
phpEscape
function phpEscape(s) { var result = '"'; for (let cp of UnicodeUtils.getCodePoints(s)) { let special = specialEscape[cp]; if (special !== undefined) { result += special; } else if (cp >= 0x20 && cp <= 0x7e) { result += String.fromCodePoint(cp); } else if (cp <= 0xFFFF) { result += '\\u{' + zeroPaddedHex(cp, 4) + '}'; } else { result += '\\u{' + zeroPaddedHex(cp, 6) + '}'; } } result += '"'; return result; }
javascript
function phpEscape(s) { var result = '"'; for (let cp of UnicodeUtils.getCodePoints(s)) { let special = specialEscape[cp]; if (special !== undefined) { result += special; } else if (cp >= 0x20 && cp <= 0x7e) { result += String.fromCodePoint(cp); } else if (cp <= 0xFFFF) { result += '\\u{' + zeroPaddedHex(cp, 4) + '}'; } else { result += '\\u{' + zeroPaddedHex(cp, 6) + '}'; } } result += '"'; return result; }
[ "function", "phpEscape", "(", "s", ")", "{", "var", "result", "=", "'\"'", ";", "for", "(", "let", "cp", "of", "UnicodeUtils", ".", "getCodePoints", "(", "s", ")", ")", "{", "let", "special", "=", "specialEscape", "[", "cp", "]", ";", "if", "(", "special", "!==", "undefined", ")", "{", "result", "+=", "special", ";", "}", "else", "if", "(", "cp", ">=", "0x20", "&&", "cp", "<=", "0x7e", ")", "{", "result", "+=", "String", ".", "fromCodePoint", "(", "cp", ")", ";", "}", "else", "if", "(", "cp", "<=", "0xFFFF", ")", "{", "result", "+=", "'\\\\u{'", "+", "zeroPaddedHex", "(", "cp", ",", "4", ")", "+", "'}'", ";", "}", "else", "{", "result", "+=", "'\\\\u{'", "+", "zeroPaddedHex", "(", "cp", ",", "6", ")", "+", "'}'", ";", "}", "}", "result", "+=", "'\"'", ";", "return", "result", ";", "}" ]
Returns a double-quoted PHP string with all non-printable and non-US-ASCII sequences escaped. @param {string} str Valid Unicode string @return {string} Double-quoted string with Unicode sequences escaped
[ "Returns", "a", "double", "-", "quoted", "PHP", "string", "with", "all", "non", "-", "printable", "and", "non", "-", "US", "-", "ASCII", "sequences", "escaped", "." ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/fbjs/src/unicode/UnicodeUtilsExtra.js#L81-L97
12,090
facebook/fbjs
packages/fbjs/src/unicode/UnicodeUtilsExtra.js
jsEscape
function jsEscape(s) { var result = '"'; for (var i = 0; i < s.length; i++) { let cp = s.charCodeAt(i); let special = specialEscape[cp]; if (special !== undefined) { result += special; } else if (cp >= 0x20 && cp <= 0x7e) { result += String.fromCodePoint(cp); } else { result += '\\u' + zeroPaddedHex(cp, 4); } } result += '"'; return result; }
javascript
function jsEscape(s) { var result = '"'; for (var i = 0; i < s.length; i++) { let cp = s.charCodeAt(i); let special = specialEscape[cp]; if (special !== undefined) { result += special; } else if (cp >= 0x20 && cp <= 0x7e) { result += String.fromCodePoint(cp); } else { result += '\\u' + zeroPaddedHex(cp, 4); } } result += '"'; return result; }
[ "function", "jsEscape", "(", "s", ")", "{", "var", "result", "=", "'\"'", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "s", ".", "length", ";", "i", "++", ")", "{", "let", "cp", "=", "s", ".", "charCodeAt", "(", "i", ")", ";", "let", "special", "=", "specialEscape", "[", "cp", "]", ";", "if", "(", "special", "!==", "undefined", ")", "{", "result", "+=", "special", ";", "}", "else", "if", "(", "cp", ">=", "0x20", "&&", "cp", "<=", "0x7e", ")", "{", "result", "+=", "String", ".", "fromCodePoint", "(", "cp", ")", ";", "}", "else", "{", "result", "+=", "'\\\\u'", "+", "zeroPaddedHex", "(", "cp", ",", "4", ")", ";", "}", "}", "result", "+=", "'\"'", ";", "return", "result", ";", "}" ]
Returns a double-quoted Java or JavaScript string with all non-printable and non-US-ASCII sequences escaped. @param {string} str Valid Unicode string @return {string} Double-quoted string with Unicode sequences escaped
[ "Returns", "a", "double", "-", "quoted", "Java", "or", "JavaScript", "string", "with", "all", "non", "-", "printable", "and", "non", "-", "US", "-", "ASCII", "sequences", "escaped", "." ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/fbjs/src/unicode/UnicodeUtilsExtra.js#L106-L121
12,091
facebook/fbjs
packages/fbjs/src/__forks__/UserAgentData.js
getBrowserVersion
function getBrowserVersion(version) { if (!version) { return { major: '', minor: '', }; } var parts = version.split('.'); return { major: parts[0], minor: parts[1], }; }
javascript
function getBrowserVersion(version) { if (!version) { return { major: '', minor: '', }; } var parts = version.split('.'); return { major: parts[0], minor: parts[1], }; }
[ "function", "getBrowserVersion", "(", "version", ")", "{", "if", "(", "!", "version", ")", "{", "return", "{", "major", ":", "''", ",", "minor", ":", "''", ",", "}", ";", "}", "var", "parts", "=", "version", ".", "split", "(", "'.'", ")", ";", "return", "{", "major", ":", "parts", "[", "0", "]", ",", "minor", ":", "parts", "[", "1", "]", ",", "}", ";", "}" ]
Get the version number in parts. This is very naive. We actually get major version as a part of UAParser already, which is generally good enough, but let's get the minor just in case.
[ "Get", "the", "version", "number", "in", "parts", ".", "This", "is", "very", "naive", ".", "We", "actually", "get", "major", "version", "as", "a", "part", "of", "UAParser", "already", "which", "is", "generally", "good", "enough", "but", "let", "s", "get", "the", "minor", "just", "in", "case", "." ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/fbjs/src/__forks__/UserAgentData.js#L43-L55
12,092
facebook/fbjs
packages/fbjs/src/unicode/UnicodeUtils.js
getCodePoints
function getCodePoints(str) { const codePoints = []; for (let pos = 0; pos < str.length; pos += getUTF16Length(str, pos)) { codePoints.push(str.codePointAt(pos)); } return codePoints; }
javascript
function getCodePoints(str) { const codePoints = []; for (let pos = 0; pos < str.length; pos += getUTF16Length(str, pos)) { codePoints.push(str.codePointAt(pos)); } return codePoints; }
[ "function", "getCodePoints", "(", "str", ")", "{", "const", "codePoints", "=", "[", "]", ";", "for", "(", "let", "pos", "=", "0", ";", "pos", "<", "str", ".", "length", ";", "pos", "+=", "getUTF16Length", "(", "str", ",", "pos", ")", ")", "{", "codePoints", ".", "push", "(", "str", ".", "codePointAt", "(", "pos", ")", ")", ";", "}", "return", "codePoints", ";", "}" ]
Get a list of Unicode code-points from a String @param {string} str Valid Unicode string @return {array<number>} A list of code-points in [0..0x10FFFF]
[ "Get", "a", "list", "of", "Unicode", "code", "-", "points", "from", "a", "String" ]
f2493c0188263fd40d2e456e7567fbee3752fbbf
https://github.com/facebook/fbjs/blob/f2493c0188263fd40d2e456e7567fbee3752fbbf/packages/fbjs/src/unicode/UnicodeUtils.js#L202-L208
12,093
apigee-127/swagger-tools
lib/specs.js
function (version) { var that = this; var createValidators = function (spec, validatorsMap) { return _.reduce(validatorsMap, function (result, schemas, schemaName) { result[schemaName] = helpers.createJsonValidator(schemas); return result; }, {}); }; var fixSchemaId = function (schemaName) { // Swagger 1.2 schema files use one id but use a different id when referencing schema files. We also use the schema // file name to reference the schema in ZSchema. To fix this so that the JSON Schema validator works properly, we // need to set the id to be the name of the schema file. var fixed = _.cloneDeep(that.schemas[schemaName]); fixed.id = schemaName; return fixed; }; var primitives = ['string', 'number', 'boolean', 'integer', 'array']; switch (version) { case '1.2': this.docsUrl = 'https://github.com/swagger-api/swagger-spec/blob/master/versions/1.2.md'; this.primitives = _.union(primitives, ['void', 'File']); this.schemasUrl = 'https://github.com/swagger-api/swagger-spec/tree/master/schemas/v1.2'; // Here explicitly to allow browserify to work this.schemas = { 'apiDeclaration.json': require('../schemas/1.2/apiDeclaration.json'), 'authorizationObject.json': require('../schemas/1.2/authorizationObject.json'), 'dataType.json': require('../schemas/1.2/dataType.json'), 'dataTypeBase.json': require('../schemas/1.2/dataTypeBase.json'), 'infoObject.json': require('../schemas/1.2/infoObject.json'), 'modelsObject.json': require('../schemas/1.2/modelsObject.json'), 'oauth2GrantType.json': require('../schemas/1.2/oauth2GrantType.json'), 'operationObject.json': require('../schemas/1.2/operationObject.json'), 'parameterObject.json': require('../schemas/1.2/parameterObject.json'), 'resourceListing.json': require('../schemas/1.2/resourceListing.json'), 'resourceObject.json': require('../schemas/1.2/resourceObject.json') }; this.validators = createValidators(this, { 'apiDeclaration.json': _.map([ 'dataTypeBase.json', 'modelsObject.json', 'oauth2GrantType.json', 'authorizationObject.json', 'parameterObject.json', 'operationObject.json', 'apiDeclaration.json' ], fixSchemaId), 'resourceListing.json': _.map([ 'resourceObject.json', 'infoObject.json', 'oauth2GrantType.json', 'authorizationObject.json', 'resourceListing.json' ], fixSchemaId) }); break; case '2.0': this.docsUrl = 'https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md'; this.primitives = _.union(primitives, ['file']); this.schemasUrl = 'https://github.com/swagger-api/swagger-spec/tree/master/schemas/v2.0'; // Here explicitly to allow browserify to work this.schemas = { 'schema.json': require('../schemas/2.0/schema.json') }; this.validators = createValidators(this, { 'schema.json': [fixSchemaId('schema.json')] }); break; default: throw new Error(version + ' is an unsupported Swagger specification version'); } this.version = version; }
javascript
function (version) { var that = this; var createValidators = function (spec, validatorsMap) { return _.reduce(validatorsMap, function (result, schemas, schemaName) { result[schemaName] = helpers.createJsonValidator(schemas); return result; }, {}); }; var fixSchemaId = function (schemaName) { // Swagger 1.2 schema files use one id but use a different id when referencing schema files. We also use the schema // file name to reference the schema in ZSchema. To fix this so that the JSON Schema validator works properly, we // need to set the id to be the name of the schema file. var fixed = _.cloneDeep(that.schemas[schemaName]); fixed.id = schemaName; return fixed; }; var primitives = ['string', 'number', 'boolean', 'integer', 'array']; switch (version) { case '1.2': this.docsUrl = 'https://github.com/swagger-api/swagger-spec/blob/master/versions/1.2.md'; this.primitives = _.union(primitives, ['void', 'File']); this.schemasUrl = 'https://github.com/swagger-api/swagger-spec/tree/master/schemas/v1.2'; // Here explicitly to allow browserify to work this.schemas = { 'apiDeclaration.json': require('../schemas/1.2/apiDeclaration.json'), 'authorizationObject.json': require('../schemas/1.2/authorizationObject.json'), 'dataType.json': require('../schemas/1.2/dataType.json'), 'dataTypeBase.json': require('../schemas/1.2/dataTypeBase.json'), 'infoObject.json': require('../schemas/1.2/infoObject.json'), 'modelsObject.json': require('../schemas/1.2/modelsObject.json'), 'oauth2GrantType.json': require('../schemas/1.2/oauth2GrantType.json'), 'operationObject.json': require('../schemas/1.2/operationObject.json'), 'parameterObject.json': require('../schemas/1.2/parameterObject.json'), 'resourceListing.json': require('../schemas/1.2/resourceListing.json'), 'resourceObject.json': require('../schemas/1.2/resourceObject.json') }; this.validators = createValidators(this, { 'apiDeclaration.json': _.map([ 'dataTypeBase.json', 'modelsObject.json', 'oauth2GrantType.json', 'authorizationObject.json', 'parameterObject.json', 'operationObject.json', 'apiDeclaration.json' ], fixSchemaId), 'resourceListing.json': _.map([ 'resourceObject.json', 'infoObject.json', 'oauth2GrantType.json', 'authorizationObject.json', 'resourceListing.json' ], fixSchemaId) }); break; case '2.0': this.docsUrl = 'https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md'; this.primitives = _.union(primitives, ['file']); this.schemasUrl = 'https://github.com/swagger-api/swagger-spec/tree/master/schemas/v2.0'; // Here explicitly to allow browserify to work this.schemas = { 'schema.json': require('../schemas/2.0/schema.json') }; this.validators = createValidators(this, { 'schema.json': [fixSchemaId('schema.json')] }); break; default: throw new Error(version + ' is an unsupported Swagger specification version'); } this.version = version; }
[ "function", "(", "version", ")", "{", "var", "that", "=", "this", ";", "var", "createValidators", "=", "function", "(", "spec", ",", "validatorsMap", ")", "{", "return", "_", ".", "reduce", "(", "validatorsMap", ",", "function", "(", "result", ",", "schemas", ",", "schemaName", ")", "{", "result", "[", "schemaName", "]", "=", "helpers", ".", "createJsonValidator", "(", "schemas", ")", ";", "return", "result", ";", "}", ",", "{", "}", ")", ";", "}", ";", "var", "fixSchemaId", "=", "function", "(", "schemaName", ")", "{", "// Swagger 1.2 schema files use one id but use a different id when referencing schema files. We also use the schema", "// file name to reference the schema in ZSchema. To fix this so that the JSON Schema validator works properly, we", "// need to set the id to be the name of the schema file.", "var", "fixed", "=", "_", ".", "cloneDeep", "(", "that", ".", "schemas", "[", "schemaName", "]", ")", ";", "fixed", ".", "id", "=", "schemaName", ";", "return", "fixed", ";", "}", ";", "var", "primitives", "=", "[", "'string'", ",", "'number'", ",", "'boolean'", ",", "'integer'", ",", "'array'", "]", ";", "switch", "(", "version", ")", "{", "case", "'1.2'", ":", "this", ".", "docsUrl", "=", "'https://github.com/swagger-api/swagger-spec/blob/master/versions/1.2.md'", ";", "this", ".", "primitives", "=", "_", ".", "union", "(", "primitives", ",", "[", "'void'", ",", "'File'", "]", ")", ";", "this", ".", "schemasUrl", "=", "'https://github.com/swagger-api/swagger-spec/tree/master/schemas/v1.2'", ";", "// Here explicitly to allow browserify to work", "this", ".", "schemas", "=", "{", "'apiDeclaration.json'", ":", "require", "(", "'../schemas/1.2/apiDeclaration.json'", ")", ",", "'authorizationObject.json'", ":", "require", "(", "'../schemas/1.2/authorizationObject.json'", ")", ",", "'dataType.json'", ":", "require", "(", "'../schemas/1.2/dataType.json'", ")", ",", "'dataTypeBase.json'", ":", "require", "(", "'../schemas/1.2/dataTypeBase.json'", ")", ",", "'infoObject.json'", ":", "require", "(", "'../schemas/1.2/infoObject.json'", ")", ",", "'modelsObject.json'", ":", "require", "(", "'../schemas/1.2/modelsObject.json'", ")", ",", "'oauth2GrantType.json'", ":", "require", "(", "'../schemas/1.2/oauth2GrantType.json'", ")", ",", "'operationObject.json'", ":", "require", "(", "'../schemas/1.2/operationObject.json'", ")", ",", "'parameterObject.json'", ":", "require", "(", "'../schemas/1.2/parameterObject.json'", ")", ",", "'resourceListing.json'", ":", "require", "(", "'../schemas/1.2/resourceListing.json'", ")", ",", "'resourceObject.json'", ":", "require", "(", "'../schemas/1.2/resourceObject.json'", ")", "}", ";", "this", ".", "validators", "=", "createValidators", "(", "this", ",", "{", "'apiDeclaration.json'", ":", "_", ".", "map", "(", "[", "'dataTypeBase.json'", ",", "'modelsObject.json'", ",", "'oauth2GrantType.json'", ",", "'authorizationObject.json'", ",", "'parameterObject.json'", ",", "'operationObject.json'", ",", "'apiDeclaration.json'", "]", ",", "fixSchemaId", ")", ",", "'resourceListing.json'", ":", "_", ".", "map", "(", "[", "'resourceObject.json'", ",", "'infoObject.json'", ",", "'oauth2GrantType.json'", ",", "'authorizationObject.json'", ",", "'resourceListing.json'", "]", ",", "fixSchemaId", ")", "}", ")", ";", "break", ";", "case", "'2.0'", ":", "this", ".", "docsUrl", "=", "'https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md'", ";", "this", ".", "primitives", "=", "_", ".", "union", "(", "primitives", ",", "[", "'file'", "]", ")", ";", "this", ".", "schemasUrl", "=", "'https://github.com/swagger-api/swagger-spec/tree/master/schemas/v2.0'", ";", "// Here explicitly to allow browserify to work", "this", ".", "schemas", "=", "{", "'schema.json'", ":", "require", "(", "'../schemas/2.0/schema.json'", ")", "}", ";", "this", ".", "validators", "=", "createValidators", "(", "this", ",", "{", "'schema.json'", ":", "[", "fixSchemaId", "(", "'schema.json'", ")", "]", "}", ")", ";", "break", ";", "default", ":", "throw", "new", "Error", "(", "version", "+", "' is an unsupported Swagger specification version'", ")", ";", "}", "this", ".", "version", "=", "version", ";", "}" ]
Creates a new Swagger specification object. @param {string} version - The Swagger version @constructor
[ "Creates", "a", "new", "Swagger", "specification", "object", "." ]
12f4c55cfc50f34a149b5f2e74fadab0452a1517
https://github.com/apigee-127/swagger-tools/blob/12f4c55cfc50f34a149b5f2e74fadab0452a1517/lib/specs.js#L1073-L1157
12,094
expressjs/csurf
index.js
csurf
function csurf (options) { var opts = options || {} // get cookie options var cookie = getCookieOptions(opts.cookie) // get session options var sessionKey = opts.sessionKey || 'session' // get value getter var value = opts.value || defaultValue // token repo var tokens = new Tokens(opts) // ignored methods var ignoreMethods = opts.ignoreMethods === undefined ? ['GET', 'HEAD', 'OPTIONS'] : opts.ignoreMethods if (!Array.isArray(ignoreMethods)) { throw new TypeError('option ignoreMethods must be an array') } // generate lookup var ignoreMethod = getIgnoredMethods(ignoreMethods) return function csrf (req, res, next) { // validate the configuration against request if (!verifyConfiguration(req, sessionKey, cookie)) { return next(new Error('misconfigured csrf')) } // get the secret from the request var secret = getSecret(req, sessionKey, cookie) var token // lazy-load token getter req.csrfToken = function csrfToken () { var sec = !cookie ? getSecret(req, sessionKey, cookie) : secret // use cached token if secret has not changed if (token && sec === secret) { return token } // generate & set new secret if (sec === undefined) { sec = tokens.secretSync() setSecret(req, res, sessionKey, sec, cookie) } // update changed secret secret = sec // create new token token = tokens.create(secret) return token } // generate & set secret if (!secret) { secret = tokens.secretSync() setSecret(req, res, sessionKey, secret, cookie) } // verify the incoming token if (!ignoreMethod[req.method] && !tokens.verify(secret, value(req))) { return next(createError(403, 'invalid csrf token', { code: 'EBADCSRFTOKEN' })) } next() } }
javascript
function csurf (options) { var opts = options || {} // get cookie options var cookie = getCookieOptions(opts.cookie) // get session options var sessionKey = opts.sessionKey || 'session' // get value getter var value = opts.value || defaultValue // token repo var tokens = new Tokens(opts) // ignored methods var ignoreMethods = opts.ignoreMethods === undefined ? ['GET', 'HEAD', 'OPTIONS'] : opts.ignoreMethods if (!Array.isArray(ignoreMethods)) { throw new TypeError('option ignoreMethods must be an array') } // generate lookup var ignoreMethod = getIgnoredMethods(ignoreMethods) return function csrf (req, res, next) { // validate the configuration against request if (!verifyConfiguration(req, sessionKey, cookie)) { return next(new Error('misconfigured csrf')) } // get the secret from the request var secret = getSecret(req, sessionKey, cookie) var token // lazy-load token getter req.csrfToken = function csrfToken () { var sec = !cookie ? getSecret(req, sessionKey, cookie) : secret // use cached token if secret has not changed if (token && sec === secret) { return token } // generate & set new secret if (sec === undefined) { sec = tokens.secretSync() setSecret(req, res, sessionKey, sec, cookie) } // update changed secret secret = sec // create new token token = tokens.create(secret) return token } // generate & set secret if (!secret) { secret = tokens.secretSync() setSecret(req, res, sessionKey, secret, cookie) } // verify the incoming token if (!ignoreMethod[req.method] && !tokens.verify(secret, value(req))) { return next(createError(403, 'invalid csrf token', { code: 'EBADCSRFTOKEN' })) } next() } }
[ "function", "csurf", "(", "options", ")", "{", "var", "opts", "=", "options", "||", "{", "}", "// get cookie options", "var", "cookie", "=", "getCookieOptions", "(", "opts", ".", "cookie", ")", "// get session options", "var", "sessionKey", "=", "opts", ".", "sessionKey", "||", "'session'", "// get value getter", "var", "value", "=", "opts", ".", "value", "||", "defaultValue", "// token repo", "var", "tokens", "=", "new", "Tokens", "(", "opts", ")", "// ignored methods", "var", "ignoreMethods", "=", "opts", ".", "ignoreMethods", "===", "undefined", "?", "[", "'GET'", ",", "'HEAD'", ",", "'OPTIONS'", "]", ":", "opts", ".", "ignoreMethods", "if", "(", "!", "Array", ".", "isArray", "(", "ignoreMethods", ")", ")", "{", "throw", "new", "TypeError", "(", "'option ignoreMethods must be an array'", ")", "}", "// generate lookup", "var", "ignoreMethod", "=", "getIgnoredMethods", "(", "ignoreMethods", ")", "return", "function", "csrf", "(", "req", ",", "res", ",", "next", ")", "{", "// validate the configuration against request", "if", "(", "!", "verifyConfiguration", "(", "req", ",", "sessionKey", ",", "cookie", ")", ")", "{", "return", "next", "(", "new", "Error", "(", "'misconfigured csrf'", ")", ")", "}", "// get the secret from the request", "var", "secret", "=", "getSecret", "(", "req", ",", "sessionKey", ",", "cookie", ")", "var", "token", "// lazy-load token getter", "req", ".", "csrfToken", "=", "function", "csrfToken", "(", ")", "{", "var", "sec", "=", "!", "cookie", "?", "getSecret", "(", "req", ",", "sessionKey", ",", "cookie", ")", ":", "secret", "// use cached token if secret has not changed", "if", "(", "token", "&&", "sec", "===", "secret", ")", "{", "return", "token", "}", "// generate & set new secret", "if", "(", "sec", "===", "undefined", ")", "{", "sec", "=", "tokens", ".", "secretSync", "(", ")", "setSecret", "(", "req", ",", "res", ",", "sessionKey", ",", "sec", ",", "cookie", ")", "}", "// update changed secret", "secret", "=", "sec", "// create new token", "token", "=", "tokens", ".", "create", "(", "secret", ")", "return", "token", "}", "// generate & set secret", "if", "(", "!", "secret", ")", "{", "secret", "=", "tokens", ".", "secretSync", "(", ")", "setSecret", "(", "req", ",", "res", ",", "sessionKey", ",", "secret", ",", "cookie", ")", "}", "// verify the incoming token", "if", "(", "!", "ignoreMethod", "[", "req", ".", "method", "]", "&&", "!", "tokens", ".", "verify", "(", "secret", ",", "value", "(", "req", ")", ")", ")", "{", "return", "next", "(", "createError", "(", "403", ",", "'invalid csrf token'", ",", "{", "code", ":", "'EBADCSRFTOKEN'", "}", ")", ")", "}", "next", "(", ")", "}", "}" ]
CSRF protection middleware. This middleware adds a `req.csrfToken()` function to make a token which should be added to requests which mutate state, within a hidden form field, query-string etc. This token is validated against the visitor's session. @param {Object} options @return {Function} middleware @public
[ "CSRF", "protection", "middleware", "." ]
248112a42f36fc9a84a71b0f5d383a1e03813f54
https://github.com/expressjs/csurf/blob/248112a42f36fc9a84a71b0f5d383a1e03813f54/index.js#L41-L119
12,095
expressjs/csurf
index.js
defaultValue
function defaultValue (req) { return (req.body && req.body._csrf) || (req.query && req.query._csrf) || (req.headers['csrf-token']) || (req.headers['xsrf-token']) || (req.headers['x-csrf-token']) || (req.headers['x-xsrf-token']) }
javascript
function defaultValue (req) { return (req.body && req.body._csrf) || (req.query && req.query._csrf) || (req.headers['csrf-token']) || (req.headers['xsrf-token']) || (req.headers['x-csrf-token']) || (req.headers['x-xsrf-token']) }
[ "function", "defaultValue", "(", "req", ")", "{", "return", "(", "req", ".", "body", "&&", "req", ".", "body", ".", "_csrf", ")", "||", "(", "req", ".", "query", "&&", "req", ".", "query", ".", "_csrf", ")", "||", "(", "req", ".", "headers", "[", "'csrf-token'", "]", ")", "||", "(", "req", ".", "headers", "[", "'xsrf-token'", "]", ")", "||", "(", "req", ".", "headers", "[", "'x-csrf-token'", "]", ")", "||", "(", "req", ".", "headers", "[", "'x-xsrf-token'", "]", ")", "}" ]
Default value function, checking the `req.body` and `req.query` for the CSRF token. @param {IncomingMessage} req @return {String} @api private
[ "Default", "value", "function", "checking", "the", "req", ".", "body", "and", "req", ".", "query", "for", "the", "CSRF", "token", "." ]
248112a42f36fc9a84a71b0f5d383a1e03813f54
https://github.com/expressjs/csurf/blob/248112a42f36fc9a84a71b0f5d383a1e03813f54/index.js#L130-L137
12,096
expressjs/csurf
index.js
getCookieOptions
function getCookieOptions (options) { if (options !== true && typeof options !== 'object') { return undefined } var opts = Object.create(null) // defaults opts.key = '_csrf' opts.path = '/' if (options && typeof options === 'object') { for (var prop in options) { var val = options[prop] if (val !== undefined) { opts[prop] = val } } } return opts }
javascript
function getCookieOptions (options) { if (options !== true && typeof options !== 'object') { return undefined } var opts = Object.create(null) // defaults opts.key = '_csrf' opts.path = '/' if (options && typeof options === 'object') { for (var prop in options) { var val = options[prop] if (val !== undefined) { opts[prop] = val } } } return opts }
[ "function", "getCookieOptions", "(", "options", ")", "{", "if", "(", "options", "!==", "true", "&&", "typeof", "options", "!==", "'object'", ")", "{", "return", "undefined", "}", "var", "opts", "=", "Object", ".", "create", "(", "null", ")", "// defaults", "opts", ".", "key", "=", "'_csrf'", "opts", ".", "path", "=", "'/'", "if", "(", "options", "&&", "typeof", "options", "===", "'object'", ")", "{", "for", "(", "var", "prop", "in", "options", ")", "{", "var", "val", "=", "options", "[", "prop", "]", "if", "(", "val", "!==", "undefined", ")", "{", "opts", "[", "prop", "]", "=", "val", "}", "}", "}", "return", "opts", "}" ]
Get options for cookie. @param {boolean|object} [options] @returns {object} @api private
[ "Get", "options", "for", "cookie", "." ]
248112a42f36fc9a84a71b0f5d383a1e03813f54
https://github.com/expressjs/csurf/blob/248112a42f36fc9a84a71b0f5d383a1e03813f54/index.js#L147-L169
12,097
expressjs/csurf
index.js
getIgnoredMethods
function getIgnoredMethods (methods) { var obj = Object.create(null) for (var i = 0; i < methods.length; i++) { var method = methods[i].toUpperCase() obj[method] = true } return obj }
javascript
function getIgnoredMethods (methods) { var obj = Object.create(null) for (var i = 0; i < methods.length; i++) { var method = methods[i].toUpperCase() obj[method] = true } return obj }
[ "function", "getIgnoredMethods", "(", "methods", ")", "{", "var", "obj", "=", "Object", ".", "create", "(", "null", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "methods", ".", "length", ";", "i", "++", ")", "{", "var", "method", "=", "methods", "[", "i", "]", ".", "toUpperCase", "(", ")", "obj", "[", "method", "]", "=", "true", "}", "return", "obj", "}" ]
Get a lookup of ignored methods. @param {array} methods @returns {object} @api private
[ "Get", "a", "lookup", "of", "ignored", "methods", "." ]
248112a42f36fc9a84a71b0f5d383a1e03813f54
https://github.com/expressjs/csurf/blob/248112a42f36fc9a84a71b0f5d383a1e03813f54/index.js#L179-L188
12,098
expressjs/csurf
index.js
getSecret
function getSecret (req, sessionKey, cookie) { // get the bag & key var bag = getSecretBag(req, sessionKey, cookie) var key = cookie ? cookie.key : 'csrfSecret' if (!bag) { throw new Error('misconfigured csrf') } // return secret from bag return bag[key] }
javascript
function getSecret (req, sessionKey, cookie) { // get the bag & key var bag = getSecretBag(req, sessionKey, cookie) var key = cookie ? cookie.key : 'csrfSecret' if (!bag) { throw new Error('misconfigured csrf') } // return secret from bag return bag[key] }
[ "function", "getSecret", "(", "req", ",", "sessionKey", ",", "cookie", ")", "{", "// get the bag & key", "var", "bag", "=", "getSecretBag", "(", "req", ",", "sessionKey", ",", "cookie", ")", "var", "key", "=", "cookie", "?", "cookie", ".", "key", ":", "'csrfSecret'", "if", "(", "!", "bag", ")", "{", "throw", "new", "Error", "(", "'misconfigured csrf'", ")", "}", "// return secret from bag", "return", "bag", "[", "key", "]", "}" ]
Get the token secret from the request. @param {IncomingMessage} req @param {String} sessionKey @param {Object} [cookie] @api private
[ "Get", "the", "token", "secret", "from", "the", "request", "." ]
248112a42f36fc9a84a71b0f5d383a1e03813f54
https://github.com/expressjs/csurf/blob/248112a42f36fc9a84a71b0f5d383a1e03813f54/index.js#L199-L210
12,099
expressjs/csurf
index.js
getSecretBag
function getSecretBag (req, sessionKey, cookie) { if (cookie) { // get secret from cookie var cookieKey = cookie.signed ? 'signedCookies' : 'cookies' return req[cookieKey] } else { // get secret from session return req[sessionKey] } }
javascript
function getSecretBag (req, sessionKey, cookie) { if (cookie) { // get secret from cookie var cookieKey = cookie.signed ? 'signedCookies' : 'cookies' return req[cookieKey] } else { // get secret from session return req[sessionKey] } }
[ "function", "getSecretBag", "(", "req", ",", "sessionKey", ",", "cookie", ")", "{", "if", "(", "cookie", ")", "{", "// get secret from cookie", "var", "cookieKey", "=", "cookie", ".", "signed", "?", "'signedCookies'", ":", "'cookies'", "return", "req", "[", "cookieKey", "]", "}", "else", "{", "// get secret from session", "return", "req", "[", "sessionKey", "]", "}", "}" ]
Get the token secret bag from the request. @param {IncomingMessage} req @param {String} sessionKey @param {Object} [cookie] @api private
[ "Get", "the", "token", "secret", "bag", "from", "the", "request", "." ]
248112a42f36fc9a84a71b0f5d383a1e03813f54
https://github.com/expressjs/csurf/blob/248112a42f36fc9a84a71b0f5d383a1e03813f54/index.js#L221-L233