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
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
vibhor1997a/nodejs-open-file-explorer
lib/linux.js
openExplorerinLinux
function openExplorerinLinux(path, callback) { path = path || '/'; let p = spawn('xdg-open', [path]); p.on('error', (err) => { p.kill(); return callback(err); }); }
javascript
function openExplorerinLinux(path, callback) { path = path || '/'; let p = spawn('xdg-open', [path]); p.on('error', (err) => { p.kill(); return callback(err); }); }
[ "function", "openExplorerinLinux", "(", "path", ",", "callback", ")", "{", "path", "=", "path", "||", "'/'", ";", "let", "p", "=", "spawn", "(", "'xdg-open'", ",", "[", "path", "]", ")", ";", "p", ".", "on", "(", "'error'", ",", "(", "err", ")", "=>", "{", "p", ".", "kill", "(", ")", ";", "return", "callback", "(", "err", ")", ";", "}", ")", ";", "}" ]
Opens the Explorer and executes the callback function in ubuntu like os @param {string} path The path string to be opened in the explorer @param {Function} callback Callback function to which error is passed if some error occurs
[ "Opens", "the", "Explorer", "and", "executes", "the", "callback", "function", "in", "ubuntu", "like", "os" ]
ea86151dfb85251be2f07dbbaa73eb4dce36ddb8
https://github.com/vibhor1997a/nodejs-open-file-explorer/blob/ea86151dfb85251be2f07dbbaa73eb4dce36ddb8/lib/linux.js#L8-L15
train
vibhor1997a/nodejs-open-file-explorer
index.js
openExplorer
function openExplorer(path, callback) { if (osType == 'Windows_NT') { openExplorerinWindows(path, callback); } else if (osType == 'Darwin') { openExplorerinMac(path, callback); } else { openExplorerinLinux(path, callback); } }
javascript
function openExplorer(path, callback) { if (osType == 'Windows_NT') { openExplorerinWindows(path, callback); } else if (osType == 'Darwin') { openExplorerinMac(path, callback); } else { openExplorerinLinux(path, callback); } }
[ "function", "openExplorer", "(", "path", ",", "callback", ")", "{", "if", "(", "osType", "==", "'Windows_NT'", ")", "{", "openExplorerinWindows", "(", "path", ",", "callback", ")", ";", "}", "else", "if", "(", "osType", "==", "'Darwin'", ")", "{", "openExplorerinMac", "(", "path", ",", "callback", ")", ";", "}", "else", "{", "openExplorerinLinux", "(", "path", ",", "callback", ")", ";", "}", "}" ]
Opens the Explorer and executes the callback function @param {string} path The path string to be opened in the explorer @param {Function} callback Callback function to which error is passed if some error occurs
[ "Opens", "the", "Explorer", "and", "executes", "the", "callback", "function" ]
ea86151dfb85251be2f07dbbaa73eb4dce36ddb8
https://github.com/vibhor1997a/nodejs-open-file-explorer/blob/ea86151dfb85251be2f07dbbaa73eb4dce36ddb8/index.js#L12-L22
train
vibhor1997a/nodejs-open-file-explorer
lib/mac.js
openExplorerinMac
function openExplorerinMac(path, callback) { path = path || '/'; let p = spawn('open', [path]); p.on('error', (err) => { p.kill(); return callback(err); }); }
javascript
function openExplorerinMac(path, callback) { path = path || '/'; let p = spawn('open', [path]); p.on('error', (err) => { p.kill(); return callback(err); }); }
[ "function", "openExplorerinMac", "(", "path", ",", "callback", ")", "{", "path", "=", "path", "||", "'/'", ";", "let", "p", "=", "spawn", "(", "'open'", ",", "[", "path", "]", ")", ";", "p", ".", "on", "(", "'error'", ",", "(", "err", ")", "=>", "{", "p", ".", "kill", "(", ")", ";", "return", "callback", "(", "err", ")", ";", "}", ")", ";", "}" ]
Opens the Explorer and executes the callback function in osX @param {string} path The path string to be opened in the explorer @param {Function} callback Callback function to which error is passed if some error occurs
[ "Opens", "the", "Explorer", "and", "executes", "the", "callback", "function", "in", "osX" ]
ea86151dfb85251be2f07dbbaa73eb4dce36ddb8
https://github.com/vibhor1997a/nodejs-open-file-explorer/blob/ea86151dfb85251be2f07dbbaa73eb4dce36ddb8/lib/mac.js#L8-L15
train
vibhor1997a/nodejs-open-file-explorer
lib/win.js
openExplorerinWindows
function openExplorerinWindows(path, callback) { path = path || '='; let p = spawn('explorer', [path]); p.on('error', (err) => { p.kill(); return callback(err); }); }
javascript
function openExplorerinWindows(path, callback) { path = path || '='; let p = spawn('explorer', [path]); p.on('error', (err) => { p.kill(); return callback(err); }); }
[ "function", "openExplorerinWindows", "(", "path", ",", "callback", ")", "{", "path", "=", "path", "||", "'='", ";", "let", "p", "=", "spawn", "(", "'explorer'", ",", "[", "path", "]", ")", ";", "p", ".", "on", "(", "'error'", ",", "(", "err", ")", "=>", "{", "p", ".", "kill", "(", ")", ";", "return", "callback", "(", "err", ")", ";", "}", ")", ";", "}" ]
Opens the Explorer and executes the callback function in windows os @param {string} path The path string to be opened in the explorer @param {Function} callback Callback function to which error is passed if some error occurs
[ "Opens", "the", "Explorer", "and", "executes", "the", "callback", "function", "in", "windows", "os" ]
ea86151dfb85251be2f07dbbaa73eb4dce36ddb8
https://github.com/vibhor1997a/nodejs-open-file-explorer/blob/ea86151dfb85251be2f07dbbaa73eb4dce36ddb8/lib/win.js#L8-L15
train
johnwebbcole/jscad-utils
dist/index.js
function(p1, p2) { var r = { c: 90, A: Math.abs(p2.x - p1.x), B: Math.abs(p2.y - p1.y) }; var brad = Math.atan2(r.B, r.A); r.b = this.toDegrees(brad); // r.C = Math.sqrt(Math.pow(r.B, 2) + Math.pow(r.A, 2)); r.C = r.B / Math.sin(brad); r.a = 90 - r.b; return r; }
javascript
function(p1, p2) { var r = { c: 90, A: Math.abs(p2.x - p1.x), B: Math.abs(p2.y - p1.y) }; var brad = Math.atan2(r.B, r.A); r.b = this.toDegrees(brad); // r.C = Math.sqrt(Math.pow(r.B, 2) + Math.pow(r.A, 2)); r.C = r.B / Math.sin(brad); r.a = 90 - r.b; return r; }
[ "function", "(", "p1", ",", "p2", ")", "{", "var", "r", "=", "{", "c", ":", "90", ",", "A", ":", "Math", ".", "abs", "(", "p2", ".", "x", "-", "p1", ".", "x", ")", ",", "B", ":", "Math", ".", "abs", "(", "p2", ".", "y", "-", "p1", ".", "y", ")", "}", ";", "var", "brad", "=", "Math", ".", "atan2", "(", "r", ".", "B", ",", "r", ".", "A", ")", ";", "r", ".", "b", "=", "this", ".", "toDegrees", "(", "brad", ")", ";", "r", ".", "C", "=", "r", ".", "B", "/", "Math", ".", "sin", "(", "brad", ")", ";", "r", ".", "a", "=", "90", "-", "r", ".", "b", ";", "return", "r", ";", "}" ]
Solve a 90 degree triangle from two points. @param {Number} p1.x Point 1 x coordinate @param {Number} p1.y Point 1 y coordinate @param {Number} p2.x Point 2 x coordinate @param {Number} p2.y Point 2 y coordinate @return {Object} A triangle object {A,B,C,a,b,c}
[ "Solve", "a", "90", "degree", "triangle", "from", "two", "points", "." ]
7c52e446aa5c001ccbb0a867a69b160da20a13e7
https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L36-L49
train
johnwebbcole/jscad-utils
dist/index.js
function(r) { r = Object.assign(r, { C: 90 }); r.A = r.A || 90 - r.B; r.B = r.B || 90 - r.A; var arad = toRadians(r.A); // sinA = a/c // a = c * sinA // tanA = a/b // a = b * tanA r.a = r.a || (r.c ? r.c * Math.sin(arad) : r.b * Math.tan(arad)); // sinA = a/c r.c = r.c || r.a / Math.sin(arad); // tanA = a/b r.b = r.b || r.a / Math.tan(arad); return r; }
javascript
function(r) { r = Object.assign(r, { C: 90 }); r.A = r.A || 90 - r.B; r.B = r.B || 90 - r.A; var arad = toRadians(r.A); // sinA = a/c // a = c * sinA // tanA = a/b // a = b * tanA r.a = r.a || (r.c ? r.c * Math.sin(arad) : r.b * Math.tan(arad)); // sinA = a/c r.c = r.c || r.a / Math.sin(arad); // tanA = a/b r.b = r.b || r.a / Math.tan(arad); return r; }
[ "function", "(", "r", ")", "{", "r", "=", "Object", ".", "assign", "(", "r", ",", "{", "C", ":", "90", "}", ")", ";", "r", ".", "A", "=", "r", ".", "A", "||", "90", "-", "r", ".", "B", ";", "r", ".", "B", "=", "r", ".", "B", "||", "90", "-", "r", ".", "A", ";", "var", "arad", "=", "toRadians", "(", "r", ".", "A", ")", ";", "r", ".", "a", "=", "r", ".", "a", "||", "(", "r", ".", "c", "?", "r", ".", "c", "*", "Math", ".", "sin", "(", "arad", ")", ":", "r", ".", "b", "*", "Math", ".", "tan", "(", "arad", ")", ")", ";", "r", ".", "c", "=", "r", ".", "c", "||", "r", ".", "a", "/", "Math", ".", "sin", "(", "arad", ")", ";", "r", ".", "b", "=", "r", ".", "b", "||", "r", ".", "a", "/", "Math", ".", "tan", "(", "arad", ")", ";", "return", "r", ";", "}" ]
Solve a partial triangle object. Angles are in degrees. Angle `C` is set to 90 degrees. @param {Number} r.a Length of side `a` @param {Number} r.A Angle `A` in degrees @param {Number} r.b Length of side `b` @param {Number} r.B Angle `B` in degrees @param {Number} r.c Length of side `c` @return {Object} A solved triangle object {A,B,C,a,b,c}
[ "Solve", "a", "partial", "triangle", "object", ".", "Angles", "are", "in", "degrees", ".", "Angle", "C", "is", "set", "to", "90", "degrees", "." ]
7c52e446aa5c001ccbb0a867a69b160da20a13e7
https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L61-L84
train
johnwebbcole/jscad-utils
dist/index.js
function(object) { return Array.isArray(object) ? object : [object.x, object.y, object.z]; }
javascript
function(object) { return Array.isArray(object) ? object : [object.x, object.y, object.z]; }
[ "function", "(", "object", ")", "{", "return", "Array", ".", "isArray", "(", "object", ")", "?", "object", ":", "[", "object", ".", "x", ",", "object", ".", "y", ",", "object", ".", "z", "]", ";", "}" ]
Converts an object with x, y, and z properties into an array, or an array if passed an array. @param {Object|Array} object
[ "Converts", "an", "object", "with", "x", "y", "and", "z", "properties", "into", "an", "array", "or", "an", "array", "if", "passed", "an", "array", "." ]
7c52e446aa5c001ccbb0a867a69b160da20a13e7
https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L132-L134
train
johnwebbcole/jscad-utils
dist/index.js
function(desired, nozzel = NOZZEL_SIZE, nozzie = 0) { return (Math.floor(desired / nozzel) + nozzie) * nozzel; }
javascript
function(desired, nozzel = NOZZEL_SIZE, nozzie = 0) { return (Math.floor(desired / nozzel) + nozzie) * nozzel; }
[ "function", "(", "desired", ",", "nozzel", "=", "NOZZEL_SIZE", ",", "nozzie", "=", "0", ")", "{", "return", "(", "Math", ".", "floor", "(", "desired", "/", "nozzel", ")", "+", "nozzie", ")", "*", "nozzel", ";", "}" ]
Return the largest number that is a multiple of the nozzel size. @param {Number} desired Desired value @param {Number} [nozzel=NOZZEL_SIZE] Nozel size, defaults to `NOZZEL_SIZE` @param {Number} [nozzie=0] Number of nozzel sizes to add to the value @return {Number} Multiple of nozzel size
[ "Return", "the", "largest", "number", "that", "is", "a", "multiple", "of", "the", "nozzel", "size", "." ]
7c52e446aa5c001ccbb0a867a69b160da20a13e7
https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L194-L196
train
johnwebbcole/jscad-utils
dist/index.js
function(desired, nozzel = NOZZEL_SIZE, nozzie = 0) { return (Math.ceil(desired / nozzel) + nozzie) * nozzel; }
javascript
function(desired, nozzel = NOZZEL_SIZE, nozzie = 0) { return (Math.ceil(desired / nozzel) + nozzie) * nozzel; }
[ "function", "(", "desired", ",", "nozzel", "=", "NOZZEL_SIZE", ",", "nozzie", "=", "0", ")", "{", "return", "(", "Math", ".", "ceil", "(", "desired", "/", "nozzel", ")", "+", "nozzie", ")", "*", "nozzel", ";", "}" ]
Returns the largest number that is a multipel of the nozzel size, just over the desired value. @param {Number} desired Desired value @param {Number} [nozzel=NOZZEL_SIZE] Nozel size, defaults to `NOZZEL_SIZE` @param {Number} [nozzie=0] Number of nozzel sizes to add to the value @return {Number} Multiple of nozzel size
[ "Returns", "the", "largest", "number", "that", "is", "a", "multipel", "of", "the", "nozzel", "size", "just", "over", "the", "desired", "value", "." ]
7c52e446aa5c001ccbb0a867a69b160da20a13e7
https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L205-L207
train
johnwebbcole/jscad-utils
dist/index.js
function(msg, o) { echo( msg, JSON.stringify(o.getBounds()), JSON.stringify(this.size(o.getBounds())) ); }
javascript
function(msg, o) { echo( msg, JSON.stringify(o.getBounds()), JSON.stringify(this.size(o.getBounds())) ); }
[ "function", "(", "msg", ",", "o", ")", "{", "echo", "(", "msg", ",", "JSON", ".", "stringify", "(", "o", ".", "getBounds", "(", ")", ")", ",", "JSON", ".", "stringify", "(", "this", ".", "size", "(", "o", ".", "getBounds", "(", ")", ")", ")", ")", ";", "}" ]
Print a message and CSG object bounds and size to the conosle. @param {String} msg Message to print @param {CSG} o A CSG object to print the bounds and size of.
[ "Print", "a", "message", "and", "CSG", "object", "bounds", "and", "size", "to", "the", "conosle", "." ]
7c52e446aa5c001ccbb0a867a69b160da20a13e7
https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L263-L269
train
johnwebbcole/jscad-utils
dist/index.js
function(object, segments, axis) { var size = object.size()[axis]; var width = size / segments; var result = []; for (var i = width; i < size; i += width) { result.push(i); } return result; }
javascript
function(object, segments, axis) { var size = object.size()[axis]; var width = size / segments; var result = []; for (var i = width; i < size; i += width) { result.push(i); } return result; }
[ "function", "(", "object", ",", "segments", ",", "axis", ")", "{", "var", "size", "=", "object", ".", "size", "(", ")", "[", "axis", "]", ";", "var", "width", "=", "size", "/", "segments", ";", "var", "result", "=", "[", "]", ";", "for", "(", "var", "i", "=", "width", ";", "i", "<", "size", ";", "i", "+=", "width", ")", "{", "result", ".", "push", "(", "i", ")", ";", "}", "return", "result", ";", "}" ]
Returns an array of positions along an object on a given axis. @param {CSG} object The object to calculate the segments on. @param {number} segments The number of segments to create. @param {string} axis Axis to create the sgements on. @return {Array} An array of segment positions.
[ "Returns", "an", "array", "of", "positions", "along", "an", "object", "on", "a", "given", "axis", "." ]
7c52e446aa5c001ccbb0a867a69b160da20a13e7
https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L366-L374
train
johnwebbcole/jscad-utils
dist/index.js
size
function size(o) { var bbox = o.getBounds ? o.getBounds() : o; var foo = bbox[1].minus(bbox[0]); return foo; }
javascript
function size(o) { var bbox = o.getBounds ? o.getBounds() : o; var foo = bbox[1].minus(bbox[0]); return foo; }
[ "function", "size", "(", "o", ")", "{", "var", "bbox", "=", "o", ".", "getBounds", "?", "o", ".", "getBounds", "(", ")", ":", "o", ";", "var", "foo", "=", "bbox", "[", "1", "]", ".", "minus", "(", "bbox", "[", "0", "]", ")", ";", "return", "foo", ";", "}" ]
Returns a `Vector3D` with the size of the object. @param {CSG} o A `CSG` like object or an array of `CSG.Vector3D` objects (the result of getBounds()). @return {CSG.Vector3D} Vector3d with the size of the object
[ "Returns", "a", "Vector3D", "with", "the", "size", "of", "the", "object", "." ]
7c52e446aa5c001ccbb0a867a69b160da20a13e7
https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L475-L480
train
johnwebbcole/jscad-utils
dist/index.js
fit
function fit(object, x, y, z, keep_aspect_ratio) { var a; if (Array.isArray(x)) { a = x; keep_aspect_ratio = y; x = a[0]; y = a[1]; z = a[2]; } else { a = [x, y, z]; } // var c = util.centroid(object); var size = this.size(object.getBounds()); function scale(size, value) { if (value == 0) return 1; return value / size; } var s = [scale(size.x, x), scale(size.y, y), scale(size.z, z)]; var min = util.array.min(s); return util.centerWith( object.scale( s.map(function(d, i) { if (a[i] === 0) return 1; // don't scale when value is zero return keep_aspect_ratio ? min : d; }) ), "xyz", object ); }
javascript
function fit(object, x, y, z, keep_aspect_ratio) { var a; if (Array.isArray(x)) { a = x; keep_aspect_ratio = y; x = a[0]; y = a[1]; z = a[2]; } else { a = [x, y, z]; } // var c = util.centroid(object); var size = this.size(object.getBounds()); function scale(size, value) { if (value == 0) return 1; return value / size; } var s = [scale(size.x, x), scale(size.y, y), scale(size.z, z)]; var min = util.array.min(s); return util.centerWith( object.scale( s.map(function(d, i) { if (a[i] === 0) return 1; // don't scale when value is zero return keep_aspect_ratio ? min : d; }) ), "xyz", object ); }
[ "function", "fit", "(", "object", ",", "x", ",", "y", ",", "z", ",", "keep_aspect_ratio", ")", "{", "var", "a", ";", "if", "(", "Array", ".", "isArray", "(", "x", ")", ")", "{", "a", "=", "x", ";", "keep_aspect_ratio", "=", "y", ";", "x", "=", "a", "[", "0", "]", ";", "y", "=", "a", "[", "1", "]", ";", "z", "=", "a", "[", "2", "]", ";", "}", "else", "{", "a", "=", "[", "x", ",", "y", ",", "z", "]", ";", "}", "var", "size", "=", "this", ".", "size", "(", "object", ".", "getBounds", "(", ")", ")", ";", "function", "scale", "(", "size", ",", "value", ")", "{", "if", "(", "value", "==", "0", ")", "return", "1", ";", "return", "value", "/", "size", ";", "}", "var", "s", "=", "[", "scale", "(", "size", ".", "x", ",", "x", ")", ",", "scale", "(", "size", ".", "y", ",", "y", ")", ",", "scale", "(", "size", ".", "z", ",", "z", ")", "]", ";", "var", "min", "=", "util", ".", "array", ".", "min", "(", "s", ")", ";", "return", "util", ".", "centerWith", "(", "object", ".", "scale", "(", "s", ".", "map", "(", "function", "(", "d", ",", "i", ")", "{", "if", "(", "a", "[", "i", "]", "===", "0", ")", "return", "1", ";", "return", "keep_aspect_ratio", "?", "min", ":", "d", ";", "}", ")", ")", ",", "\"xyz\"", ",", "object", ")", ";", "}" ]
Fit an object inside a bounding box. Often used with text labels. @param {CSG} object [description] @param {number | array} x [description] @param {number} y [description] @param {number} z [description] @param {boolean} keep_aspect_ratio [description] @return {CSG} [description]
[ "Fit", "an", "object", "inside", "a", "bounding", "box", ".", "Often", "used", "with", "text", "labels", "." ]
7c52e446aa5c001ccbb0a867a69b160da20a13e7
https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L557-L589
train
johnwebbcole/jscad-utils
dist/index.js
flush
function flush(moveobj, withobj, axis, mside, wside) { return moveobj.translate( util.calcFlush(moveobj, withobj, axis, mside, wside) ); }
javascript
function flush(moveobj, withobj, axis, mside, wside) { return moveobj.translate( util.calcFlush(moveobj, withobj, axis, mside, wside) ); }
[ "function", "flush", "(", "moveobj", ",", "withobj", ",", "axis", ",", "mside", ",", "wside", ")", "{", "return", "moveobj", ".", "translate", "(", "util", ".", "calcFlush", "(", "moveobj", ",", "withobj", ",", "axis", ",", "mside", ",", "wside", ")", ")", ";", "}" ]
Moves an object flush with another object @param {CSG} moveobj Object to move @param {CSG} withobj Object to make flush with @param {String} axis Which axis: 'x', 'y', 'z' @param {Number} mside 0 or 1 @param {Number} wside 0 or 1 @return {CSG} [description]
[ "Moves", "an", "object", "flush", "with", "another", "object" ]
7c52e446aa5c001ccbb0a867a69b160da20a13e7
https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L702-L706
train
johnwebbcole/jscad-utils
dist/index.js
getDelta
function getDelta(size, bounds, axis, offset, nonzero) { if (!util.isEmpty(offset) && nonzero) { if (Math.abs(offset) < 1e-4) { offset = 1e-4 * (util.isNegative(offset) ? -1 : 1); } } // if the offset is negative, then it's an offset from // the positive side of the axis var dist = util.isNegative(offset) ? (offset = size[axis] + offset) : offset; return util.axisApply(axis, function(i, a) { return bounds[0][a] + (util.isEmpty(dist) ? size[axis] / 2 : dist); }); }
javascript
function getDelta(size, bounds, axis, offset, nonzero) { if (!util.isEmpty(offset) && nonzero) { if (Math.abs(offset) < 1e-4) { offset = 1e-4 * (util.isNegative(offset) ? -1 : 1); } } // if the offset is negative, then it's an offset from // the positive side of the axis var dist = util.isNegative(offset) ? (offset = size[axis] + offset) : offset; return util.axisApply(axis, function(i, a) { return bounds[0][a] + (util.isEmpty(dist) ? size[axis] / 2 : dist); }); }
[ "function", "getDelta", "(", "size", ",", "bounds", ",", "axis", ",", "offset", ",", "nonzero", ")", "{", "if", "(", "!", "util", ".", "isEmpty", "(", "offset", ")", "&&", "nonzero", ")", "{", "if", "(", "Math", ".", "abs", "(", "offset", ")", "<", "1e-4", ")", "{", "offset", "=", "1e-4", "*", "(", "util", ".", "isNegative", "(", "offset", ")", "?", "-", "1", ":", "1", ")", ";", "}", "}", "var", "dist", "=", "util", ".", "isNegative", "(", "offset", ")", "?", "(", "offset", "=", "size", "[", "axis", "]", "+", "offset", ")", ":", "offset", ";", "return", "util", ".", "axisApply", "(", "axis", ",", "function", "(", "i", ",", "a", ")", "{", "return", "bounds", "[", "0", "]", "[", "a", "]", "+", "(", "util", ".", "isEmpty", "(", "dist", ")", "?", "size", "[", "axis", "]", "/", "2", ":", "dist", ")", ";", "}", ")", ";", "}" ]
Given an size, bounds and an axis, a Point along the axis will be returned. If no `offset` is given, then the midway point on the axis is returned. When the `offset` is positive, a point `offset` from the mininum axis is returned. When the `offset` is negative, the `offset` is subtracted from the axis maximum. @param {Size} size Size array of the object @param {Bounds} bounds Bounds of the object @param {String} axis Axis to find the point on @param {Number} offset Offset from either end @param {Boolean} nonzero When true, no offset values under 1e-4 are allowed. @return {Point} The point along the axis.
[ "Given", "an", "size", "bounds", "and", "an", "axis", "a", "Point", "along", "the", "axis", "will", "be", "returned", ".", "If", "no", "offset", "is", "given", "then", "the", "midway", "point", "on", "the", "axis", "is", "returned", ".", "When", "the", "offset", "is", "positive", "a", "point", "offset", "from", "the", "mininum", "axis", "is", "returned", ".", "When", "the", "offset", "is", "negative", "the", "offset", "is", "subtracted", "from", "the", "axis", "maximum", "." ]
7c52e446aa5c001ccbb0a867a69b160da20a13e7
https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L801-L813
train
johnwebbcole/jscad-utils
dist/index.js
bisect
function bisect( object, axis, offset, angle, rotateaxis, rotateoffset, options ) { options = util.defaults(options, { addRotationCenter: false }); angle = angle || 0; var info = util.normalVector(axis); var bounds = object.getBounds(); var size = util.size(object); rotateaxis = rotateaxis || { x: "y", y: "x", z: "x" }[axis]; // function getDelta(axis, offset) { // // if the offset is negative, then it's an offset from // // the positive side of the axis // var dist = util.isNegative(offset) ? offset = size[axis] + offset : offset; // return util.axisApply(axis, function (i, a) { // return bounds[0][a] + (util.isEmpty(dist) ? size[axis] / 2 : dist); // }); // } var cutDelta = options.cutDelta || util.getDelta(size, bounds, axis, offset); var rotateOffsetAxis = { xy: "z", yz: "x", xz: "y" }[[axis, rotateaxis].sort().join("")]; var centroid = object.centroid(); var rotateDelta = util.getDelta(size, bounds, rotateOffsetAxis, rotateoffset); var rotationCenter = options.rotationCenter || new CSG$1.Vector3D( util.axisApply("xyz", function(i, a) { if (a == axis) return cutDelta[i]; if (a == rotateOffsetAxis) return rotateDelta[i]; return centroid[a]; }) ); var rotationAxis = util.rotationAxes[rotateaxis]; var cutplane = CSG$1.OrthoNormalBasis.GetCartesian( info.orthoNormalCartesian[0], info.orthoNormalCartesian[1] ) .translate(cutDelta) .rotate(rotationCenter, rotationAxis, angle); var g = util.group("negative,positive", [ object.cutByPlane(cutplane.plane).color("red"), object.cutByPlane(cutplane.plane.flipped()).color("blue") ]); if (options.addRotationCenter) g.add( util.unitAxis(size.length() + 10, 0.5, rotationCenter), "rotationCenter" ); return g; }
javascript
function bisect( object, axis, offset, angle, rotateaxis, rotateoffset, options ) { options = util.defaults(options, { addRotationCenter: false }); angle = angle || 0; var info = util.normalVector(axis); var bounds = object.getBounds(); var size = util.size(object); rotateaxis = rotateaxis || { x: "y", y: "x", z: "x" }[axis]; // function getDelta(axis, offset) { // // if the offset is negative, then it's an offset from // // the positive side of the axis // var dist = util.isNegative(offset) ? offset = size[axis] + offset : offset; // return util.axisApply(axis, function (i, a) { // return bounds[0][a] + (util.isEmpty(dist) ? size[axis] / 2 : dist); // }); // } var cutDelta = options.cutDelta || util.getDelta(size, bounds, axis, offset); var rotateOffsetAxis = { xy: "z", yz: "x", xz: "y" }[[axis, rotateaxis].sort().join("")]; var centroid = object.centroid(); var rotateDelta = util.getDelta(size, bounds, rotateOffsetAxis, rotateoffset); var rotationCenter = options.rotationCenter || new CSG$1.Vector3D( util.axisApply("xyz", function(i, a) { if (a == axis) return cutDelta[i]; if (a == rotateOffsetAxis) return rotateDelta[i]; return centroid[a]; }) ); var rotationAxis = util.rotationAxes[rotateaxis]; var cutplane = CSG$1.OrthoNormalBasis.GetCartesian( info.orthoNormalCartesian[0], info.orthoNormalCartesian[1] ) .translate(cutDelta) .rotate(rotationCenter, rotationAxis, angle); var g = util.group("negative,positive", [ object.cutByPlane(cutplane.plane).color("red"), object.cutByPlane(cutplane.plane.flipped()).color("blue") ]); if (options.addRotationCenter) g.add( util.unitAxis(size.length() + 10, 0.5, rotationCenter), "rotationCenter" ); return g; }
[ "function", "bisect", "(", "object", ",", "axis", ",", "offset", ",", "angle", ",", "rotateaxis", ",", "rotateoffset", ",", "options", ")", "{", "options", "=", "util", ".", "defaults", "(", "options", ",", "{", "addRotationCenter", ":", "false", "}", ")", ";", "angle", "=", "angle", "||", "0", ";", "var", "info", "=", "util", ".", "normalVector", "(", "axis", ")", ";", "var", "bounds", "=", "object", ".", "getBounds", "(", ")", ";", "var", "size", "=", "util", ".", "size", "(", "object", ")", ";", "rotateaxis", "=", "rotateaxis", "||", "{", "x", ":", "\"y\"", ",", "y", ":", "\"x\"", ",", "z", ":", "\"x\"", "}", "[", "axis", "]", ";", "var", "cutDelta", "=", "options", ".", "cutDelta", "||", "util", ".", "getDelta", "(", "size", ",", "bounds", ",", "axis", ",", "offset", ")", ";", "var", "rotateOffsetAxis", "=", "{", "xy", ":", "\"z\"", ",", "yz", ":", "\"x\"", ",", "xz", ":", "\"y\"", "}", "[", "[", "axis", ",", "rotateaxis", "]", ".", "sort", "(", ")", ".", "join", "(", "\"\"", ")", "]", ";", "var", "centroid", "=", "object", ".", "centroid", "(", ")", ";", "var", "rotateDelta", "=", "util", ".", "getDelta", "(", "size", ",", "bounds", ",", "rotateOffsetAxis", ",", "rotateoffset", ")", ";", "var", "rotationCenter", "=", "options", ".", "rotationCenter", "||", "new", "CSG$1", ".", "Vector3D", "(", "util", ".", "axisApply", "(", "\"xyz\"", ",", "function", "(", "i", ",", "a", ")", "{", "if", "(", "a", "==", "axis", ")", "return", "cutDelta", "[", "i", "]", ";", "if", "(", "a", "==", "rotateOffsetAxis", ")", "return", "rotateDelta", "[", "i", "]", ";", "return", "centroid", "[", "a", "]", ";", "}", ")", ")", ";", "var", "rotationAxis", "=", "util", ".", "rotationAxes", "[", "rotateaxis", "]", ";", "var", "cutplane", "=", "CSG$1", ".", "OrthoNormalBasis", ".", "GetCartesian", "(", "info", ".", "orthoNormalCartesian", "[", "0", "]", ",", "info", ".", "orthoNormalCartesian", "[", "1", "]", ")", ".", "translate", "(", "cutDelta", ")", ".", "rotate", "(", "rotationCenter", ",", "rotationAxis", ",", "angle", ")", ";", "var", "g", "=", "util", ".", "group", "(", "\"negative,positive\"", ",", "[", "object", ".", "cutByPlane", "(", "cutplane", ".", "plane", ")", ".", "color", "(", "\"red\"", ")", ",", "object", ".", "cutByPlane", "(", "cutplane", ".", "plane", ".", "flipped", "(", ")", ")", ".", "color", "(", "\"blue\"", ")", "]", ")", ";", "if", "(", "options", ".", "addRotationCenter", ")", "g", ".", "add", "(", "util", ".", "unitAxis", "(", "size", ".", "length", "(", ")", "+", "10", ",", "0.5", ",", "rotationCenter", ")", ",", "\"rotationCenter\"", ")", ";", "return", "g", ";", "}" ]
Cut an object into two pieces, along a given axis. The offset allows you to move the cut plane along the cut axis. For example, a 10mm cube with an offset of 2, will create a 2mm side and an 8mm side. Negative offsets operate off of the larger side of the axes. In the previous example, an offset of -2 creates a 8mm side and a 2mm side. You can angle the cut plane and poistion the rotation point. ![bisect example](jsdoc2md/bisect.png) @param {CSG} object object to bisect @param {string} axis axis to cut along @param {number} offset offset to cut at @param {number} angle angle to rotate the cut plane to @return {object} Returns a group object with a parts object.
[ "Cut", "an", "object", "into", "two", "pieces", "along", "a", "given", "axis", ".", "The", "offset", "allows", "you", "to", "move", "the", "cut", "plane", "along", "the", "cut", "axis", ".", "For", "example", "a", "10mm", "cube", "with", "an", "offset", "of", "2", "will", "create", "a", "2mm", "side", "and", "an", "8mm", "side", "." ]
7c52e446aa5c001ccbb0a867a69b160da20a13e7
https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L831-L904
train
johnwebbcole/jscad-utils
dist/index.js
stretch
function stretch(object, axis, distance, offset) { var normal = { x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] }; var bounds = object.getBounds(); var size = util.size(object); var cutDelta = util.getDelta(size, bounds, axis, offset, true); // console.log('stretch.cutDelta', cutDelta, normal[axis]); return object.stretchAtPlane(normal[axis], cutDelta, distance); }
javascript
function stretch(object, axis, distance, offset) { var normal = { x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] }; var bounds = object.getBounds(); var size = util.size(object); var cutDelta = util.getDelta(size, bounds, axis, offset, true); // console.log('stretch.cutDelta', cutDelta, normal[axis]); return object.stretchAtPlane(normal[axis], cutDelta, distance); }
[ "function", "stretch", "(", "object", ",", "axis", ",", "distance", ",", "offset", ")", "{", "var", "normal", "=", "{", "x", ":", "[", "1", ",", "0", ",", "0", "]", ",", "y", ":", "[", "0", ",", "1", ",", "0", "]", ",", "z", ":", "[", "0", ",", "0", ",", "1", "]", "}", ";", "var", "bounds", "=", "object", ".", "getBounds", "(", ")", ";", "var", "size", "=", "util", ".", "size", "(", "object", ")", ";", "var", "cutDelta", "=", "util", ".", "getDelta", "(", "size", ",", "bounds", ",", "axis", ",", "offset", ",", "true", ")", ";", "return", "object", ".", "stretchAtPlane", "(", "normal", "[", "axis", "]", ",", "cutDelta", ",", "distance", ")", ";", "}" ]
Wraps the `stretchAtPlane` call using the same logic as `bisect`. @param {CSG} object Object to stretch @param {String} axis Axis to streatch along @param {Number} distance Distance to stretch @param {Number} offset Offset along the axis to cut the object @return {CSG} The stretched object.
[ "Wraps", "the", "stretchAtPlane", "call", "using", "the", "same", "logic", "as", "bisect", "." ]
7c52e446aa5c001ccbb0a867a69b160da20a13e7
https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L915-L926
train
johnwebbcole/jscad-utils
dist/index.js
poly2solid
function poly2solid(top, bottom, height) { if (top.sides.length == 0) { // empty! return new CSG$1(); } // var offsetVector = CSG.parseOptionAs3DVector(options, "offset", [0, 0, 10]); var offsetVector = CSG$1.Vector3D.Create(0, 0, height); var normalVector = CSG$1.Vector3D.Create(0, 1, 0); var polygons = []; // bottom and top polygons = polygons.concat( bottom._toPlanePolygons({ translation: [0, 0, 0], normalVector: normalVector, flipped: !(offsetVector.z < 0) }) ); polygons = polygons.concat( top._toPlanePolygons({ translation: offsetVector, normalVector: normalVector, flipped: offsetVector.z < 0 }) ); // walls var c1 = new CSG$1.Connector( offsetVector.times(0), [0, 0, offsetVector.z], normalVector ); var c2 = new CSG$1.Connector( offsetVector, [0, 0, offsetVector.z], normalVector ); polygons = polygons.concat( bottom._toWallPolygons({ cag: top, toConnector1: c1, toConnector2: c2 }) ); // } return CSG$1.fromPolygons(polygons); }
javascript
function poly2solid(top, bottom, height) { if (top.sides.length == 0) { // empty! return new CSG$1(); } // var offsetVector = CSG.parseOptionAs3DVector(options, "offset", [0, 0, 10]); var offsetVector = CSG$1.Vector3D.Create(0, 0, height); var normalVector = CSG$1.Vector3D.Create(0, 1, 0); var polygons = []; // bottom and top polygons = polygons.concat( bottom._toPlanePolygons({ translation: [0, 0, 0], normalVector: normalVector, flipped: !(offsetVector.z < 0) }) ); polygons = polygons.concat( top._toPlanePolygons({ translation: offsetVector, normalVector: normalVector, flipped: offsetVector.z < 0 }) ); // walls var c1 = new CSG$1.Connector( offsetVector.times(0), [0, 0, offsetVector.z], normalVector ); var c2 = new CSG$1.Connector( offsetVector, [0, 0, offsetVector.z], normalVector ); polygons = polygons.concat( bottom._toWallPolygons({ cag: top, toConnector1: c1, toConnector2: c2 }) ); // } return CSG$1.fromPolygons(polygons); }
[ "function", "poly2solid", "(", "top", ",", "bottom", ",", "height", ")", "{", "if", "(", "top", ".", "sides", ".", "length", "==", "0", ")", "{", "return", "new", "CSG$1", "(", ")", ";", "}", "var", "offsetVector", "=", "CSG$1", ".", "Vector3D", ".", "Create", "(", "0", ",", "0", ",", "height", ")", ";", "var", "normalVector", "=", "CSG$1", ".", "Vector3D", ".", "Create", "(", "0", ",", "1", ",", "0", ")", ";", "var", "polygons", "=", "[", "]", ";", "polygons", "=", "polygons", ".", "concat", "(", "bottom", ".", "_toPlanePolygons", "(", "{", "translation", ":", "[", "0", ",", "0", ",", "0", "]", ",", "normalVector", ":", "normalVector", ",", "flipped", ":", "!", "(", "offsetVector", ".", "z", "<", "0", ")", "}", ")", ")", ";", "polygons", "=", "polygons", ".", "concat", "(", "top", ".", "_toPlanePolygons", "(", "{", "translation", ":", "offsetVector", ",", "normalVector", ":", "normalVector", ",", "flipped", ":", "offsetVector", ".", "z", "<", "0", "}", ")", ")", ";", "var", "c1", "=", "new", "CSG$1", ".", "Connector", "(", "offsetVector", ".", "times", "(", "0", ")", ",", "[", "0", ",", "0", ",", "offsetVector", ".", "z", "]", ",", "normalVector", ")", ";", "var", "c2", "=", "new", "CSG$1", ".", "Connector", "(", "offsetVector", ",", "[", "0", ",", "0", ",", "offsetVector", ".", "z", "]", ",", "normalVector", ")", ";", "polygons", "=", "polygons", ".", "concat", "(", "bottom", ".", "_toWallPolygons", "(", "{", "cag", ":", "top", ",", "toConnector1", ":", "c1", ",", "toConnector2", ":", "c2", "}", ")", ")", ";", "return", "CSG$1", ".", "fromPolygons", "(", "polygons", ")", ";", "}" ]
Takes two CSG polygons and createds a solid of `height`. Similar to `CSG.extrude`, excdept you can resize either polygon. @param {CAG} top Top polygon @param {CAG} bottom Bottom polygon @param {number} height heigth of solid @return {CSG} generated solid
[ "Takes", "two", "CSG", "polygons", "and", "createds", "a", "solid", "of", "height", ".", "Similar", "to", "CSG", ".", "extrude", "excdept", "you", "can", "resize", "either", "polygon", "." ]
7c52e446aa5c001ccbb0a867a69b160da20a13e7
https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L937-L983
train
johnwebbcole/jscad-utils
dist/index.js
Hexagon
function Hexagon(diameter, height) { var radius = diameter / 2; var sqrt3 = Math.sqrt(3) / 2; var hex = CAG.fromPoints([ [radius, 0], [radius / 2, radius * sqrt3], [-radius / 2, radius * sqrt3], [-radius, 0], [-radius / 2, -radius * sqrt3], [radius / 2, -radius * sqrt3] ]); return hex.extrude({ offset: [0, 0, height] }); }
javascript
function Hexagon(diameter, height) { var radius = diameter / 2; var sqrt3 = Math.sqrt(3) / 2; var hex = CAG.fromPoints([ [radius, 0], [radius / 2, radius * sqrt3], [-radius / 2, radius * sqrt3], [-radius, 0], [-radius / 2, -radius * sqrt3], [radius / 2, -radius * sqrt3] ]); return hex.extrude({ offset: [0, 0, height] }); }
[ "function", "Hexagon", "(", "diameter", ",", "height", ")", "{", "var", "radius", "=", "diameter", "/", "2", ";", "var", "sqrt3", "=", "Math", ".", "sqrt", "(", "3", ")", "/", "2", ";", "var", "hex", "=", "CAG", ".", "fromPoints", "(", "[", "[", "radius", ",", "0", "]", ",", "[", "radius", "/", "2", ",", "radius", "*", "sqrt3", "]", ",", "[", "-", "radius", "/", "2", ",", "radius", "*", "sqrt3", "]", ",", "[", "-", "radius", ",", "0", "]", ",", "[", "-", "radius", "/", "2", ",", "-", "radius", "*", "sqrt3", "]", ",", "[", "radius", "/", "2", ",", "-", "radius", "*", "sqrt3", "]", "]", ")", ";", "return", "hex", ".", "extrude", "(", "{", "offset", ":", "[", "0", ",", "0", ",", "height", "]", "}", ")", ";", "}" ]
Crate a hexagon. @param {number} diameter Outside diameter of the hexagon @param {number} height height of the hexagon
[ "Crate", "a", "hexagon", "." ]
7c52e446aa5c001ccbb0a867a69b160da20a13e7
https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L1848-L1863
train
johnwebbcole/jscad-utils
dist/index.js
Tube
function Tube( outsideDiameter, insideDiameter, height, outsideOptions, insideOptions ) { return Parts.Cylinder(outsideDiameter, height, outsideOptions).subtract( Parts.Cylinder(insideDiameter, height, insideOptions || outsideOptions) ); }
javascript
function Tube( outsideDiameter, insideDiameter, height, outsideOptions, insideOptions ) { return Parts.Cylinder(outsideDiameter, height, outsideOptions).subtract( Parts.Cylinder(insideDiameter, height, insideOptions || outsideOptions) ); }
[ "function", "Tube", "(", "outsideDiameter", ",", "insideDiameter", ",", "height", ",", "outsideOptions", ",", "insideOptions", ")", "{", "return", "Parts", ".", "Cylinder", "(", "outsideDiameter", ",", "height", ",", "outsideOptions", ")", ".", "subtract", "(", "Parts", ".", "Cylinder", "(", "insideDiameter", ",", "height", ",", "insideOptions", "||", "outsideOptions", ")", ")", ";", "}" ]
Create a tube @param {Number} outsideDiameter Outside diameter of the tube @param {Number} insideDiameter Inside diameter of the tube @param {Number} height Height of the tube @param {Object} outsideOptions Options passed to the outside cylinder @param {Object} insideOptions Options passed to the inside cylinder @returns {CSG} A CSG Tube
[ "Create", "a", "tube" ]
7c52e446aa5c001ccbb0a867a69b160da20a13e7
https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L1887-L1897
train
johnwebbcole/jscad-utils
dist/index.js
function( headDiameter, headLength, diameter, length, clearLength, options ) { var head = Parts.Hexagon(headDiameter, headLength); var thread = Parts.Cylinder(diameter, length); if (clearLength) { var headClearSpace = Parts.Hexagon(headDiameter, clearLength); } return Parts.Hardware.Screw(head, thread, headClearSpace, options); }
javascript
function( headDiameter, headLength, diameter, length, clearLength, options ) { var head = Parts.Hexagon(headDiameter, headLength); var thread = Parts.Cylinder(diameter, length); if (clearLength) { var headClearSpace = Parts.Hexagon(headDiameter, clearLength); } return Parts.Hardware.Screw(head, thread, headClearSpace, options); }
[ "function", "(", "headDiameter", ",", "headLength", ",", "diameter", ",", "length", ",", "clearLength", ",", "options", ")", "{", "var", "head", "=", "Parts", ".", "Hexagon", "(", "headDiameter", ",", "headLength", ")", ";", "var", "thread", "=", "Parts", ".", "Cylinder", "(", "diameter", ",", "length", ")", ";", "if", "(", "clearLength", ")", "{", "var", "headClearSpace", "=", "Parts", ".", "Hexagon", "(", "headDiameter", ",", "clearLength", ")", ";", "}", "return", "Parts", ".", "Hardware", ".", "Screw", "(", "head", ",", "thread", ",", "headClearSpace", ",", "options", ")", ";", "}" ]
Creates a `Group` object with a Hex Head Screw. @param {number} headDiameter Diameter of the head of the screw @param {number} headLength Length of the head @param {number} diameter Diameter of the threaded shaft @param {number} length Length of the threaded shaft @param {number} clearLength Length of the clearance section of the head. @param {object} options Screw options include orientation and clerance scale.
[ "Creates", "a", "Group", "object", "with", "a", "Hex", "Head", "Screw", "." ]
7c52e446aa5c001ccbb0a867a69b160da20a13e7
https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L1986-L2002
train
Clarence-pan/format-webpack-stats-errors-warnings
src/format-webpack-stats-errors-warnings.js
_formatErrorsWarnings
function _formatErrorsWarnings(level, list, projectRoot){ return list.map(x => { let file, line, col, endLine, endCol, message try{ // resolve the relative path let fullFilePath = data_get(x, 'module.resource') file = fullFilePath && projectRoot ? path.relative(projectRoot, fullFilePath) : '' // file = file.replace(/[\\//]/g, '/') line = data_get(x, 'error.error.loc.line') || 0 col = data_get(x, 'error.error.loc.column') || 0 // only need first line of message let fullMessage = (x.message + '').trim() let crPos = fullMessage.indexOf("\n") if (crPos >= 0){ message = fullMessage.substring(0, crPos) } else { message = fullMessage } if (!line){ let linesColsInfo let m if (x.name === 'ModuleNotFoundError' && (m = fullMessage.match(MODULE_NOT_FOUND_ERR_MSG_PATTERN))){ linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[1]) } else if (fullMessage.indexOf('component lists rendered with v-for should have explicit keys') > 0 && (m = fullMessage.match(/([a-zA-Z-_]+)\s+(v-for=['"].*?['"])/))){ linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[2], {after: m[1]}) } else if (m = fullMessage.match(/export ['"](\S+?)['"] was not found/)){ linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[1], {after: 'import'}) } else if (m = fullMessage.match(/Error compiling template:((?:.|[\r\n])*)- Component template/m)){ linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[1].trim()) message = fullMessage.replace(/\n/g, ' ') } if (linesColsInfo){ line = linesColsInfo.line || 0 col = linesColsInfo.col || 0 endLine = linesColsInfo.endLine endCol = linesColsInfo.endCol } } let endLinesCols = (endLine || endCol) ? ('~' + (endLine || '') + (endLine ? ',' : '') + (endCol || '0')) : '' return `!>${level}: ${file}:${line},${col}${endLinesCols}: ${message || '@see output window'}` } catch (e){ console.warn(e) return '' } }).join("\n") }
javascript
function _formatErrorsWarnings(level, list, projectRoot){ return list.map(x => { let file, line, col, endLine, endCol, message try{ // resolve the relative path let fullFilePath = data_get(x, 'module.resource') file = fullFilePath && projectRoot ? path.relative(projectRoot, fullFilePath) : '' // file = file.replace(/[\\//]/g, '/') line = data_get(x, 'error.error.loc.line') || 0 col = data_get(x, 'error.error.loc.column') || 0 // only need first line of message let fullMessage = (x.message + '').trim() let crPos = fullMessage.indexOf("\n") if (crPos >= 0){ message = fullMessage.substring(0, crPos) } else { message = fullMessage } if (!line){ let linesColsInfo let m if (x.name === 'ModuleNotFoundError' && (m = fullMessage.match(MODULE_NOT_FOUND_ERR_MSG_PATTERN))){ linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[1]) } else if (fullMessage.indexOf('component lists rendered with v-for should have explicit keys') > 0 && (m = fullMessage.match(/([a-zA-Z-_]+)\s+(v-for=['"].*?['"])/))){ linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[2], {after: m[1]}) } else if (m = fullMessage.match(/export ['"](\S+?)['"] was not found/)){ linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[1], {after: 'import'}) } else if (m = fullMessage.match(/Error compiling template:((?:.|[\r\n])*)- Component template/m)){ linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[1].trim()) message = fullMessage.replace(/\n/g, ' ') } if (linesColsInfo){ line = linesColsInfo.line || 0 col = linesColsInfo.col || 0 endLine = linesColsInfo.endLine endCol = linesColsInfo.endCol } } let endLinesCols = (endLine || endCol) ? ('~' + (endLine || '') + (endLine ? ',' : '') + (endCol || '0')) : '' return `!>${level}: ${file}:${line},${col}${endLinesCols}: ${message || '@see output window'}` } catch (e){ console.warn(e) return '' } }).join("\n") }
[ "function", "_formatErrorsWarnings", "(", "level", ",", "list", ",", "projectRoot", ")", "{", "return", "list", ".", "map", "(", "x", "=>", "{", "let", "file", ",", "line", ",", "col", ",", "endLine", ",", "endCol", ",", "message", "try", "{", "let", "fullFilePath", "=", "data_get", "(", "x", ",", "'module.resource'", ")", "file", "=", "fullFilePath", "&&", "projectRoot", "?", "path", ".", "relative", "(", "projectRoot", ",", "fullFilePath", ")", ":", "''", "line", "=", "data_get", "(", "x", ",", "'error.error.loc.line'", ")", "||", "0", "col", "=", "data_get", "(", "x", ",", "'error.error.loc.column'", ")", "||", "0", "let", "fullMessage", "=", "(", "x", ".", "message", "+", "''", ")", ".", "trim", "(", ")", "let", "crPos", "=", "fullMessage", ".", "indexOf", "(", "\"\\n\"", ")", "\\n", "if", "(", "crPos", ">=", "0", ")", "{", "message", "=", "fullMessage", ".", "substring", "(", "0", ",", "crPos", ")", "}", "else", "{", "message", "=", "fullMessage", "}", "if", "(", "!", "line", ")", "{", "let", "linesColsInfo", "let", "m", "if", "(", "x", ".", "name", "===", "'ModuleNotFoundError'", "&&", "(", "m", "=", "fullMessage", ".", "match", "(", "MODULE_NOT_FOUND_ERR_MSG_PATTERN", ")", ")", ")", "{", "linesColsInfo", "=", "_resolveLineColNumInFile", "(", "fullFilePath", ",", "m", "[", "1", "]", ")", "}", "else", "if", "(", "fullMessage", ".", "indexOf", "(", "'component lists rendered with v-for should have explicit keys'", ")", ">", "0", "&&", "(", "m", "=", "fullMessage", ".", "match", "(", "/", "([a-zA-Z-_]+)\\s+(v-for=['\"].*?['\"])", "/", ")", ")", ")", "{", "linesColsInfo", "=", "_resolveLineColNumInFile", "(", "fullFilePath", ",", "m", "[", "2", "]", ",", "{", "after", ":", "m", "[", "1", "]", "}", ")", "}", "else", "if", "(", "m", "=", "fullMessage", ".", "match", "(", "/", "export ['\"](\\S+?)['\"] was not found", "/", ")", ")", "{", "linesColsInfo", "=", "_resolveLineColNumInFile", "(", "fullFilePath", ",", "m", "[", "1", "]", ",", "{", "after", ":", "'import'", "}", ")", "}", "else", "if", "(", "m", "=", "fullMessage", ".", "match", "(", "/", "Error compiling template:((?:.|[\\r\\n])*)- Component template", "/", "m", ")", ")", "{", "linesColsInfo", "=", "_resolveLineColNumInFile", "(", "fullFilePath", ",", "m", "[", "1", "]", ".", "trim", "(", ")", ")", "message", "=", "fullMessage", ".", "replace", "(", "/", "\\n", "/", "g", ",", "' '", ")", "}", "if", "(", "linesColsInfo", ")", "{", "line", "=", "linesColsInfo", ".", "line", "||", "0", "col", "=", "linesColsInfo", ".", "col", "||", "0", "endLine", "=", "linesColsInfo", ".", "endLine", "endCol", "=", "linesColsInfo", ".", "endCol", "}", "}", "let", "endLinesCols", "=", "(", "endLine", "||", "endCol", ")", "?", "(", "'~'", "+", "(", "endLine", "||", "''", ")", "+", "(", "endLine", "?", "','", ":", "''", ")", "+", "(", "endCol", "||", "'0'", ")", ")", ":", "''", "}", "return", "`", "${", "level", "}", "${", "file", "}", "${", "line", "}", "${", "col", "}", "${", "endLinesCols", "}", "${", "message", "||", "'@see output window'", "}", "`", "}", ")", ".", "catch", "(", "e", ")", "{", "console", ".", "warn", "(", "e", ")", "return", "''", "}", "join", "}" ]
Format errors or warnings @param {string} level @param {Array<Error>} list @param {String|null} projectRoot
[ "Format", "errors", "or", "warnings" ]
35211ed18023e9e060d56f1227ae7483ac40fc23
https://github.com/Clarence-pan/format-webpack-stats-errors-warnings/blob/35211ed18023e9e060d56f1227ae7483ac40fc23/src/format-webpack-stats-errors-warnings.js#L30-L83
train
Clarence-pan/format-webpack-stats-errors-warnings
src/format-webpack-stats-errors-warnings.js
_resolveLineColNumInFile
function _resolveLineColNumInFile(file, message, options={}){ if (!message){ return {line: 0, col: 0} } let fileContent = fs.readFileSync(file, 'utf8') let beyondPos = 0 switch (typeof options.after){ case 'string': beyondPos = fileContent.indexOf(options.after) break case 'number': beyondPos = options.after break default: break } let pos = fileContent.indexOf(message, beyondPos >= 0 ? beyondPos : 0) if (pos <= 0){ return {line: 0, col: 0} } let lineNum = 1 let linePos = 0 for (let i = 0; i < pos; i++){ if (fileContent.charCodeAt(i) === 10){ // 10: "\n" lineNum++ linePos = i } } return {line: lineNum, col: pos - linePos, endCol: pos - linePos + message.length} }
javascript
function _resolveLineColNumInFile(file, message, options={}){ if (!message){ return {line: 0, col: 0} } let fileContent = fs.readFileSync(file, 'utf8') let beyondPos = 0 switch (typeof options.after){ case 'string': beyondPos = fileContent.indexOf(options.after) break case 'number': beyondPos = options.after break default: break } let pos = fileContent.indexOf(message, beyondPos >= 0 ? beyondPos : 0) if (pos <= 0){ return {line: 0, col: 0} } let lineNum = 1 let linePos = 0 for (let i = 0; i < pos; i++){ if (fileContent.charCodeAt(i) === 10){ // 10: "\n" lineNum++ linePos = i } } return {line: lineNum, col: pos - linePos, endCol: pos - linePos + message.length} }
[ "function", "_resolveLineColNumInFile", "(", "file", ",", "message", ",", "options", "=", "{", "}", ")", "{", "if", "(", "!", "message", ")", "{", "return", "{", "line", ":", "0", ",", "col", ":", "0", "}", "}", "let", "fileContent", "=", "fs", ".", "readFileSync", "(", "file", ",", "'utf8'", ")", "let", "beyondPos", "=", "0", "switch", "(", "typeof", "options", ".", "after", ")", "{", "case", "'string'", ":", "beyondPos", "=", "fileContent", ".", "indexOf", "(", "options", ".", "after", ")", "break", "case", "'number'", ":", "beyondPos", "=", "options", ".", "after", "break", "default", ":", "break", "}", "let", "pos", "=", "fileContent", ".", "indexOf", "(", "message", ",", "beyondPos", ">=", "0", "?", "beyondPos", ":", "0", ")", "if", "(", "pos", "<=", "0", ")", "{", "return", "{", "line", ":", "0", ",", "col", ":", "0", "}", "}", "let", "lineNum", "=", "1", "let", "linePos", "=", "0", "for", "(", "let", "i", "=", "0", ";", "i", "<", "pos", ";", "i", "++", ")", "{", "if", "(", "fileContent", ".", "charCodeAt", "(", "i", ")", "===", "10", ")", "{", "lineNum", "++", "linePos", "=", "i", "}", "}", "return", "{", "line", ":", "lineNum", ",", "col", ":", "pos", "-", "linePos", ",", "endCol", ":", "pos", "-", "linePos", "+", "message", ".", "length", "}", "}" ]
Resolve the line num of a message in a file
[ "Resolve", "the", "line", "num", "of", "a", "message", "in", "a", "file" ]
35211ed18023e9e060d56f1227ae7483ac40fc23
https://github.com/Clarence-pan/format-webpack-stats-errors-warnings/blob/35211ed18023e9e060d56f1227ae7483ac40fc23/src/format-webpack-stats-errors-warnings.js#L88-L123
train
Mogztter/opal-node-compiler
src/opal-builder.js
qpdecode
function qpdecode(callback) { return function(data) { var string = callback(data); return string .replace(/[\t\x20]$/gm, '') .replace(/=(?:\r\n?|\n|$)/g, '') .replace(/=([a-fA-F0-9]{2})/g, function($0, $1) { var codePoint = parseInt($1, 16); return String.fromCharCode(codePoint); }); } }
javascript
function qpdecode(callback) { return function(data) { var string = callback(data); return string .replace(/[\t\x20]$/gm, '') .replace(/=(?:\r\n?|\n|$)/g, '') .replace(/=([a-fA-F0-9]{2})/g, function($0, $1) { var codePoint = parseInt($1, 16); return String.fromCharCode(codePoint); }); } }
[ "function", "qpdecode", "(", "callback", ")", "{", "return", "function", "(", "data", ")", "{", "var", "string", "=", "callback", "(", "data", ")", ";", "return", "string", ".", "replace", "(", "/", "[\\t\\x20]$", "/", "gm", ",", "''", ")", ".", "replace", "(", "/", "=(?:\\r\\n?|\\n|$)", "/", "g", ",", "''", ")", ".", "replace", "(", "/", "=([a-fA-F0-9]{2})", "/", "g", ",", "function", "(", "$0", ",", "$1", ")", "{", "var", "codePoint", "=", "parseInt", "(", "$1", ",", "16", ")", ";", "return", "String", ".", "fromCharCode", "(", "codePoint", ")", ";", "}", ")", ";", "}", "}" ]
quoted-printable decode
[ "quoted", "-", "printable", "decode" ]
9eae6daef84f9ebfeb9b1ac50fc04455622cc22c
https://github.com/Mogztter/opal-node-compiler/blob/9eae6daef84f9ebfeb9b1ac50fc04455622cc22c/src/opal-builder.js#L33378-L33390
train
saebekassebil/piu
lib/name.js
order
function order(type, name) { if (type === '' || type === 'M') return name; if (type === 'm') return type + name; if (type === 'aug') return name + '#5'; if (type === 'm#5') return 'm' + name + '#5'; if (type === 'dim') return name === 'b7' ? 'dim7' : 'm' + name + 'b5'; if (type === 'Mb5') return name + 'b5'; else return name + type; }
javascript
function order(type, name) { if (type === '' || type === 'M') return name; if (type === 'm') return type + name; if (type === 'aug') return name + '#5'; if (type === 'm#5') return 'm' + name + '#5'; if (type === 'dim') return name === 'b7' ? 'dim7' : 'm' + name + 'b5'; if (type === 'Mb5') return name + 'b5'; else return name + type; }
[ "function", "order", "(", "type", ",", "name", ")", "{", "if", "(", "type", "===", "''", "||", "type", "===", "'M'", ")", "return", "name", ";", "if", "(", "type", "===", "'m'", ")", "return", "type", "+", "name", ";", "if", "(", "type", "===", "'aug'", ")", "return", "name", "+", "'#5'", ";", "if", "(", "type", "===", "'m#5'", ")", "return", "'m'", "+", "name", "+", "'#5'", ";", "if", "(", "type", "===", "'dim'", ")", "return", "name", "===", "'b7'", "?", "'dim7'", ":", "'m'", "+", "name", "+", "'b5'", ";", "if", "(", "type", "===", "'Mb5'", ")", "return", "name", "+", "'b5'", ";", "else", "return", "name", "+", "type", ";", "}" ]
Return chord type and extensions in the correct order
[ "Return", "chord", "type", "and", "extensions", "in", "the", "correct", "order" ]
e3aca0c4f5e0556a5e36e233801b8e8e34aa89db
https://github.com/saebekassebil/piu/blob/e3aca0c4f5e0556a5e36e233801b8e8e34aa89db/lib/name.js#L11-L19
train
Yomguithereal/obliterator
combinations.js
indicesToItems
function indicesToItems(target, items, indices, r) { for (var i = 0; i < r; i++) target[i] = items[indices[i]]; }
javascript
function indicesToItems(target, items, indices, r) { for (var i = 0; i < r; i++) target[i] = items[indices[i]]; }
[ "function", "indicesToItems", "(", "target", ",", "items", ",", "indices", ",", "r", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "r", ";", "i", "++", ")", "target", "[", "i", "]", "=", "items", "[", "indices", "[", "i", "]", "]", ";", "}" ]
Helper mapping indices to items.
[ "Helper", "mapping", "indices", "to", "items", "." ]
e28692aadd3c1c8be686c5c4b4d7bb988924a97a
https://github.com/Yomguithereal/obliterator/blob/e28692aadd3c1c8be686c5c4b4d7bb988924a97a/combinations.js#L12-L15
train
Yomguithereal/obliterator
split.js
makeGlobal
function makeGlobal(pattern) { var flags = 'g'; if (pattern.multiline) flags += 'm'; if (pattern.ignoreCase) flags += 'i'; if (pattern.sticky) flags += 'y'; if (pattern.unicode) flags += 'u'; return new RegExp(pattern.source, flags); }
javascript
function makeGlobal(pattern) { var flags = 'g'; if (pattern.multiline) flags += 'm'; if (pattern.ignoreCase) flags += 'i'; if (pattern.sticky) flags += 'y'; if (pattern.unicode) flags += 'u'; return new RegExp(pattern.source, flags); }
[ "function", "makeGlobal", "(", "pattern", ")", "{", "var", "flags", "=", "'g'", ";", "if", "(", "pattern", ".", "multiline", ")", "flags", "+=", "'m'", ";", "if", "(", "pattern", ".", "ignoreCase", ")", "flags", "+=", "'i'", ";", "if", "(", "pattern", ".", "sticky", ")", "flags", "+=", "'y'", ";", "if", "(", "pattern", ".", "unicode", ")", "flags", "+=", "'u'", ";", "return", "new", "RegExp", "(", "pattern", ".", "source", ",", "flags", ")", ";", "}" ]
Function used to make the given pattern global. @param {RegExp} pattern - Regular expression to make global. @return {RegExp}
[ "Function", "used", "to", "make", "the", "given", "pattern", "global", "." ]
e28692aadd3c1c8be686c5c4b4d7bb988924a97a
https://github.com/Yomguithereal/obliterator/blob/e28692aadd3c1c8be686c5c4b4d7bb988924a97a/split.js#L15-L24
train
Yomguithereal/obliterator
foreach.js
forEach
function forEach(iterable, callback) { var iterator, k, i, l, s; if (!iterable) throw new Error('obliterator/forEach: invalid iterable.'); if (typeof callback !== 'function') throw new Error('obliterator/forEach: expecting a callback.'); // The target is an array or a string or function arguments if ( Array.isArray(iterable) || (ARRAY_BUFFER_SUPPORT && ArrayBuffer.isView(iterable)) || typeof iterable === 'string' || iterable.toString() === '[object Arguments]' ) { for (i = 0, l = iterable.length; i < l; i++) callback(iterable[i], i); return; } // The target has a #.forEach method if (typeof iterable.forEach === 'function') { iterable.forEach(callback); return; } // The target is iterable if ( SYMBOL_SUPPORT && Symbol.iterator in iterable && typeof iterable.next !== 'function' ) { iterable = iterable[Symbol.iterator](); } // The target is an iterator if (typeof iterable.next === 'function') { iterator = iterable; i = 0; while ((s = iterator.next(), s.done !== true)) { callback(s.value, i); i++; } return; } // The target is a plain object for (k in iterable) { if (iterable.hasOwnProperty(k)) { callback(iterable[k], k); } } return; }
javascript
function forEach(iterable, callback) { var iterator, k, i, l, s; if (!iterable) throw new Error('obliterator/forEach: invalid iterable.'); if (typeof callback !== 'function') throw new Error('obliterator/forEach: expecting a callback.'); // The target is an array or a string or function arguments if ( Array.isArray(iterable) || (ARRAY_BUFFER_SUPPORT && ArrayBuffer.isView(iterable)) || typeof iterable === 'string' || iterable.toString() === '[object Arguments]' ) { for (i = 0, l = iterable.length; i < l; i++) callback(iterable[i], i); return; } // The target has a #.forEach method if (typeof iterable.forEach === 'function') { iterable.forEach(callback); return; } // The target is iterable if ( SYMBOL_SUPPORT && Symbol.iterator in iterable && typeof iterable.next !== 'function' ) { iterable = iterable[Symbol.iterator](); } // The target is an iterator if (typeof iterable.next === 'function') { iterator = iterable; i = 0; while ((s = iterator.next(), s.done !== true)) { callback(s.value, i); i++; } return; } // The target is a plain object for (k in iterable) { if (iterable.hasOwnProperty(k)) { callback(iterable[k], k); } } return; }
[ "function", "forEach", "(", "iterable", ",", "callback", ")", "{", "var", "iterator", ",", "k", ",", "i", ",", "l", ",", "s", ";", "if", "(", "!", "iterable", ")", "throw", "new", "Error", "(", "'obliterator/forEach: invalid iterable.'", ")", ";", "if", "(", "typeof", "callback", "!==", "'function'", ")", "throw", "new", "Error", "(", "'obliterator/forEach: expecting a callback.'", ")", ";", "if", "(", "Array", ".", "isArray", "(", "iterable", ")", "||", "(", "ARRAY_BUFFER_SUPPORT", "&&", "ArrayBuffer", ".", "isView", "(", "iterable", ")", ")", "||", "typeof", "iterable", "===", "'string'", "||", "iterable", ".", "toString", "(", ")", "===", "'[object Arguments]'", ")", "{", "for", "(", "i", "=", "0", ",", "l", "=", "iterable", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "callback", "(", "iterable", "[", "i", "]", ",", "i", ")", ";", "return", ";", "}", "if", "(", "typeof", "iterable", ".", "forEach", "===", "'function'", ")", "{", "iterable", ".", "forEach", "(", "callback", ")", ";", "return", ";", "}", "if", "(", "SYMBOL_SUPPORT", "&&", "Symbol", ".", "iterator", "in", "iterable", "&&", "typeof", "iterable", ".", "next", "!==", "'function'", ")", "{", "iterable", "=", "iterable", "[", "Symbol", ".", "iterator", "]", "(", ")", ";", "}", "if", "(", "typeof", "iterable", ".", "next", "===", "'function'", ")", "{", "iterator", "=", "iterable", ";", "i", "=", "0", ";", "while", "(", "(", "s", "=", "iterator", ".", "next", "(", ")", ",", "s", ".", "done", "!==", "true", ")", ")", "{", "callback", "(", "s", ".", "value", ",", "i", ")", ";", "i", "++", ";", "}", "return", ";", "}", "for", "(", "k", "in", "iterable", ")", "{", "if", "(", "iterable", ".", "hasOwnProperty", "(", "k", ")", ")", "{", "callback", "(", "iterable", "[", "k", "]", ",", "k", ")", ";", "}", "}", "return", ";", "}" ]
Function able to iterate over almost any iterable JS value. @param {any} iterable - Iterable value. @param {function} callback - Callback function.
[ "Function", "able", "to", "iterate", "over", "almost", "any", "iterable", "JS", "value", "." ]
e28692aadd3c1c8be686c5c4b4d7bb988924a97a
https://github.com/Yomguithereal/obliterator/blob/e28692aadd3c1c8be686c5c4b4d7bb988924a97a/foreach.js#L20-L77
train
thlorenz/docme
lib/init-tmp-dir.js
initTmpDir
function initTmpDir (dirname, cb) { var dir = path.join(os.tmpDir(), dirname); rmrf(dir, function (err) { if (err) return cb(err); mkdir(dir, function (err) { if (err) return cb(err); cb(null, dir); }); }); }
javascript
function initTmpDir (dirname, cb) { var dir = path.join(os.tmpDir(), dirname); rmrf(dir, function (err) { if (err) return cb(err); mkdir(dir, function (err) { if (err) return cb(err); cb(null, dir); }); }); }
[ "function", "initTmpDir", "(", "dirname", ",", "cb", ")", "{", "var", "dir", "=", "path", ".", "join", "(", "os", ".", "tmpDir", "(", ")", ",", "dirname", ")", ";", "rmrf", "(", "dir", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "mkdir", "(", "dir", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "cb", "(", "null", ",", "dir", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Initializes a tmp dir into which to place intermediate files @name initTmpDir @private @function @param {String} dirname @param {Function(Error, String)} cb called back with the full path to the initialized tmp dir
[ "Initializes", "a", "tmp", "dir", "into", "which", "to", "place", "intermediate", "files" ]
4dcd56a961dfe0393653c1d3f7d6744584199e79
https://github.com/thlorenz/docme/blob/4dcd56a961dfe0393653c1d3f7d6744584199e79/lib/init-tmp-dir.js#L19-L29
train
kengz/lomath
chart/plot.js
p
function p() { // global promise object to wait for all plot options to be completed before writing this.promises = []; // global array for options to plot this.optArray = []; // simple plot this.plot = function(seriesArr, title, yLabel, xLabel) { // console.log("plotting") var defer = q.defer(); this.promises.push(defer.promise); title = title || false; yLabel = yLabel || false; xLabel = xLabel || false; var opt = _.cloneDeep(tmpOpt), set = _.set.bind(null, opt); set('series', seriesArr); set('title.text', title); set('yAxis.title.text', yLabel); set('xAxis.title.text', xLabel); // setTimeout(function() {}, 2000); this.optArray.push(opt); defer.resolve(); return opt; }; // advance plot = specify your own highcharts options this.advPlot = function(opt) { var defer = q.defer(); this.promises.push(defer.promise); this.optArray.push(opt); defer.resolve(); return opt; }; // write highchart options to json for rendering // if autosave is true, charts will save on view this.write = function(autosave) { var defer = q.defer(); for (var i = 0; i < this.optArray.length; i++) { _.set(this.optArray[i], 'chart.renderTo', 'hchart' + i); _.set(this.optArray[i], 'autosave', autosave); } fs.writeFile(__dirname + '/src/options.json', JSON.stringify(this.optArray), defer.resolve); return defer.promise; }; // serialize optArray and write to this.serialize = function(autosave) { var defer = q.defer(); q.all(this.promises) .then(this.write(autosave)) .then(defer.resolve()); return defer.promise; }; // finally, render after all plots specified // if autosave is true, charts will save on view this.render = function(autosave) { var gulpplot = require(__dirname + '/../gulpfile.js').gulpplot; this.serialize(autosave) .then(gulpplot) }; this.dynrender = function() { this.serialize() // .then(dyngulpplot) }; }
javascript
function p() { // global promise object to wait for all plot options to be completed before writing this.promises = []; // global array for options to plot this.optArray = []; // simple plot this.plot = function(seriesArr, title, yLabel, xLabel) { // console.log("plotting") var defer = q.defer(); this.promises.push(defer.promise); title = title || false; yLabel = yLabel || false; xLabel = xLabel || false; var opt = _.cloneDeep(tmpOpt), set = _.set.bind(null, opt); set('series', seriesArr); set('title.text', title); set('yAxis.title.text', yLabel); set('xAxis.title.text', xLabel); // setTimeout(function() {}, 2000); this.optArray.push(opt); defer.resolve(); return opt; }; // advance plot = specify your own highcharts options this.advPlot = function(opt) { var defer = q.defer(); this.promises.push(defer.promise); this.optArray.push(opt); defer.resolve(); return opt; }; // write highchart options to json for rendering // if autosave is true, charts will save on view this.write = function(autosave) { var defer = q.defer(); for (var i = 0; i < this.optArray.length; i++) { _.set(this.optArray[i], 'chart.renderTo', 'hchart' + i); _.set(this.optArray[i], 'autosave', autosave); } fs.writeFile(__dirname + '/src/options.json', JSON.stringify(this.optArray), defer.resolve); return defer.promise; }; // serialize optArray and write to this.serialize = function(autosave) { var defer = q.defer(); q.all(this.promises) .then(this.write(autosave)) .then(defer.resolve()); return defer.promise; }; // finally, render after all plots specified // if autosave is true, charts will save on view this.render = function(autosave) { var gulpplot = require(__dirname + '/../gulpfile.js').gulpplot; this.serialize(autosave) .then(gulpplot) }; this.dynrender = function() { this.serialize() // .then(dyngulpplot) }; }
[ "function", "p", "(", ")", "{", "this", ".", "promises", "=", "[", "]", ";", "this", ".", "optArray", "=", "[", "]", ";", "this", ".", "plot", "=", "function", "(", "seriesArr", ",", "title", ",", "yLabel", ",", "xLabel", ")", "{", "var", "defer", "=", "q", ".", "defer", "(", ")", ";", "this", ".", "promises", ".", "push", "(", "defer", ".", "promise", ")", ";", "title", "=", "title", "||", "false", ";", "yLabel", "=", "yLabel", "||", "false", ";", "xLabel", "=", "xLabel", "||", "false", ";", "var", "opt", "=", "_", ".", "cloneDeep", "(", "tmpOpt", ")", ",", "set", "=", "_", ".", "set", ".", "bind", "(", "null", ",", "opt", ")", ";", "set", "(", "'series'", ",", "seriesArr", ")", ";", "set", "(", "'title.text'", ",", "title", ")", ";", "set", "(", "'yAxis.title.text'", ",", "yLabel", ")", ";", "set", "(", "'xAxis.title.text'", ",", "xLabel", ")", ";", "this", ".", "optArray", ".", "push", "(", "opt", ")", ";", "defer", ".", "resolve", "(", ")", ";", "return", "opt", ";", "}", ";", "this", ".", "advPlot", "=", "function", "(", "opt", ")", "{", "var", "defer", "=", "q", ".", "defer", "(", ")", ";", "this", ".", "promises", ".", "push", "(", "defer", ".", "promise", ")", ";", "this", ".", "optArray", ".", "push", "(", "opt", ")", ";", "defer", ".", "resolve", "(", ")", ";", "return", "opt", ";", "}", ";", "this", ".", "write", "=", "function", "(", "autosave", ")", "{", "var", "defer", "=", "q", ".", "defer", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "optArray", ".", "length", ";", "i", "++", ")", "{", "_", ".", "set", "(", "this", ".", "optArray", "[", "i", "]", ",", "'chart.renderTo'", ",", "'hchart'", "+", "i", ")", ";", "_", ".", "set", "(", "this", ".", "optArray", "[", "i", "]", ",", "'autosave'", ",", "autosave", ")", ";", "}", "fs", ".", "writeFile", "(", "__dirname", "+", "'/src/options.json'", ",", "JSON", ".", "stringify", "(", "this", ".", "optArray", ")", ",", "defer", ".", "resolve", ")", ";", "return", "defer", ".", "promise", ";", "}", ";", "this", ".", "serialize", "=", "function", "(", "autosave", ")", "{", "var", "defer", "=", "q", ".", "defer", "(", ")", ";", "q", ".", "all", "(", "this", ".", "promises", ")", ".", "then", "(", "this", ".", "write", "(", "autosave", ")", ")", ".", "then", "(", "defer", ".", "resolve", "(", ")", ")", ";", "return", "defer", ".", "promise", ";", "}", ";", "this", ".", "render", "=", "function", "(", "autosave", ")", "{", "var", "gulpplot", "=", "require", "(", "__dirname", "+", "'/../gulpfile.js'", ")", ".", "gulpplot", ";", "this", ".", "serialize", "(", "autosave", ")", ".", "then", "(", "gulpplot", ")", "}", ";", "this", ".", "dynrender", "=", "function", "(", ")", "{", "this", ".", "serialize", "(", ")", "}", ";", "}" ]
definition of plot package, uses highcharts
[ "definition", "of", "plot", "package", "uses", "highcharts" ]
6b0454843816da515e8c30b8e0eb571899e6b085
https://github.com/kengz/lomath/blob/6b0454843816da515e8c30b8e0eb571899e6b085/chart/plot.js#L18-L96
train
kengz/lomath
chart/src/js/render.js
localExport
function localExport(opt) { var ind = _.reGet(/\d/)(opt.chart.renderTo); _.assign(opt, { 'exporting': { 'buttons': { 'contextButton': { 'y': -10, 'menuItems': [{ 'text': 'Save as PNG', onclick: function() { this.createCanvas(opt.title, 'png', ind); }, 'separator': false }, { 'text': 'Save as JPEG', onclick: function() { this.createCanvas(opt.title, 'jpeg', ind); }, 'separator': false }] } } } }) return opt; }
javascript
function localExport(opt) { var ind = _.reGet(/\d/)(opt.chart.renderTo); _.assign(opt, { 'exporting': { 'buttons': { 'contextButton': { 'y': -10, 'menuItems': [{ 'text': 'Save as PNG', onclick: function() { this.createCanvas(opt.title, 'png', ind); }, 'separator': false }, { 'text': 'Save as JPEG', onclick: function() { this.createCanvas(opt.title, 'jpeg', ind); }, 'separator': false }] } } } }) return opt; }
[ "function", "localExport", "(", "opt", ")", "{", "var", "ind", "=", "_", ".", "reGet", "(", "/", "\\d", "/", ")", "(", "opt", ".", "chart", ".", "renderTo", ")", ";", "_", ".", "assign", "(", "opt", ",", "{", "'exporting'", ":", "{", "'buttons'", ":", "{", "'contextButton'", ":", "{", "'y'", ":", "-", "10", ",", "'menuItems'", ":", "[", "{", "'text'", ":", "'Save as PNG'", ",", "onclick", ":", "function", "(", ")", "{", "this", ".", "createCanvas", "(", "opt", ".", "title", ",", "'png'", ",", "ind", ")", ";", "}", ",", "'separator'", ":", "false", "}", ",", "{", "'text'", ":", "'Save as JPEG'", ",", "onclick", ":", "function", "(", ")", "{", "this", ".", "createCanvas", "(", "opt", ".", "title", ",", "'jpeg'", ",", "ind", ")", ";", "}", ",", "'separator'", ":", "false", "}", "]", "}", "}", "}", "}", ")", "return", "opt", ";", "}" ]
extending exporting properties for local save
[ "extending", "exporting", "properties", "for", "local", "save" ]
6b0454843816da515e8c30b8e0eb571899e6b085
https://github.com/kengz/lomath/blob/6b0454843816da515e8c30b8e0eb571899e6b085/chart/src/js/render.js#L34-L59
train
thlorenz/docme
index.js
docme
function docme(readme, args, jsdocargs, cb) { args = args || {}; jsdocargs = jsdocargs || []; log.level = args.loglevel || 'info'; var projectRoot = args.projectRoot || process.cwd() , projectName = path.basename(projectRoot) resolveReadme(readme, function (err, fullPath) { if (err) return cb(err); log.info('docme', 'Updating API in "%s" with current jsdocs', readme); update(projectRoot, projectName, jsdocargs, fullPath, cb); }); }
javascript
function docme(readme, args, jsdocargs, cb) { args = args || {}; jsdocargs = jsdocargs || []; log.level = args.loglevel || 'info'; var projectRoot = args.projectRoot || process.cwd() , projectName = path.basename(projectRoot) resolveReadme(readme, function (err, fullPath) { if (err) return cb(err); log.info('docme', 'Updating API in "%s" with current jsdocs', readme); update(projectRoot, projectName, jsdocargs, fullPath, cb); }); }
[ "function", "docme", "(", "readme", ",", "args", ",", "jsdocargs", ",", "cb", ")", "{", "args", "=", "args", "||", "{", "}", ";", "jsdocargs", "=", "jsdocargs", "||", "[", "]", ";", "log", ".", "level", "=", "args", ".", "loglevel", "||", "'info'", ";", "var", "projectRoot", "=", "args", ".", "projectRoot", "||", "process", ".", "cwd", "(", ")", ",", "projectName", "=", "path", ".", "basename", "(", "projectRoot", ")", "resolveReadme", "(", "readme", ",", "function", "(", "err", ",", "fullPath", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "log", ".", "info", "(", "'docme'", ",", "'Updating API in \"%s\" with current jsdocs'", ",", "readme", ")", ";", "update", "(", "projectRoot", ",", "projectName", ",", "jsdocargs", ",", "fullPath", ",", "cb", ")", ";", "}", ")", ";", "}" ]
Generates jsdocs for non-private members of the project in the current folder. It then updates the given README with the githubified version of the generated API docs. @name docme @function @param {String} readme path to readme in which the API docs should be updated @param {Array.<String>} args consumed by docme @param {String=} args.loglevel (info) level at which to log: silly|verbose|info|warn|error|silent @param {Array.<String>} jsdocargs consumed by jsdoc @param {Function(Error)} cb called back when docme finished updating the README
[ "Generates", "jsdocs", "for", "non", "-", "private", "members", "of", "the", "project", "in", "the", "current", "folder", ".", "It", "then", "updates", "the", "given", "README", "with", "the", "githubified", "version", "of", "the", "generated", "API", "docs", "." ]
4dcd56a961dfe0393653c1d3f7d6744584199e79
https://github.com/thlorenz/docme/blob/4dcd56a961dfe0393653c1d3f7d6744584199e79/index.js#L66-L80
train
hiddentao/sjv
index.js
function(schema) { if (!schema) { throw new Error('Schema is empty'); } this._defaultLimitTypes = [String,Boolean,Number,Date,Array,Object] this.schema = schema; }
javascript
function(schema) { if (!schema) { throw new Error('Schema is empty'); } this._defaultLimitTypes = [String,Boolean,Number,Date,Array,Object] this.schema = schema; }
[ "function", "(", "schema", ")", "{", "if", "(", "!", "schema", ")", "{", "throw", "new", "Error", "(", "'Schema is empty'", ")", ";", "}", "this", ".", "_defaultLimitTypes", "=", "[", "String", ",", "Boolean", ",", "Number", ",", "Date", ",", "Array", ",", "Object", "]", "this", ".", "schema", "=", "schema", ";", "}" ]
A schema.
[ "A", "schema", "." ]
e09f30baab43aaf1864dcdea2d6096c5bdd6550d
https://github.com/hiddentao/sjv/blob/e09f30baab43aaf1864dcdea2d6096c5bdd6550d/index.js#L13-L20
train
boggan/unrar.js
lib/Unrar.js
unrar
function unrar(arrayBuffer) { RarEventMgr.emitStart(); var bstream = new BitStream(arrayBuffer, false /* rtl */ ); var header = new RarVolumeHeader(bstream); if (header.crc == 0x6152 && header.headType == 0x72 && header.flags.value == 0x1A21 && header.headSize == 7) { RarEventMgr.emitInfo("Found RAR signature"); var mhead = new RarVolumeHeader(bstream); if (mhead.headType != RarUtils.VOLUME_TYPES.MAIN_HEAD) { RarEventMgr.emitError("Error! RAR did not include a MAIN_HEAD header"); } else { var localFiles = [], localFile = null; do { try { localFile = new RarLocalFile(bstream); RarEventMgr.emitInfo("RAR localFile isValid=" + localFile.isValid + ", volume packSize=" + localFile.header.packSize); if (localFile && localFile.isValid && localFile.header.packSize > 0) { RarUtils.PROGRESS.totalUncompressedBytesInArchive += localFile.header.unpackedSize; localFiles.push(localFile); } else if (localFile.header.packSize == 0 && localFile.header.unpackedSize == 0) { localFile.isValid = true; } } catch (err) { break; } RarEventMgr.emitInfo("bstream" + bstream.bytePtr + "/" + bstream.bytes.length); } while (localFile.isValid); RarUtils.PROGRESS.totalFilesInArchive = localFiles.length; // now we have all console.information but things are unpacked // TODO: unpack localFiles = localFiles.sort(function(a, b) { var aname = a.filename; var bname = b.filename; return aname > bname ? 1 : -1; }); RarEventMgr.emitInfo(localFiles.map(function(a) { return a.filename }).join(', ')); for (var i = 0; i < localFiles.length; ++i) { var localfile = localFiles[i]; RarEventMgr.emitInfo("Local file: ", localfile.filename); // update progress RarUtils.PROGRESS.currentFilename = localfile.header.filename; RarUtils.PROGRESS.currentBytesUnarchivedInFile = 0; // actually do the unzipping localfile.unrar(); if (localfile.isValid) { // notify extract event with file RarEventMgr.emitExtract(localfile); RarEventMgr.emitProgress(RarUtils.PROGRESS); } } RarEventMgr.emitProgress(RarUtils.PROGRESS); } } else { RarEventMgr.emitError("Invalid RAR file"); } RarEventMgr.emitFinish(localFiles); return localFiles; }
javascript
function unrar(arrayBuffer) { RarEventMgr.emitStart(); var bstream = new BitStream(arrayBuffer, false /* rtl */ ); var header = new RarVolumeHeader(bstream); if (header.crc == 0x6152 && header.headType == 0x72 && header.flags.value == 0x1A21 && header.headSize == 7) { RarEventMgr.emitInfo("Found RAR signature"); var mhead = new RarVolumeHeader(bstream); if (mhead.headType != RarUtils.VOLUME_TYPES.MAIN_HEAD) { RarEventMgr.emitError("Error! RAR did not include a MAIN_HEAD header"); } else { var localFiles = [], localFile = null; do { try { localFile = new RarLocalFile(bstream); RarEventMgr.emitInfo("RAR localFile isValid=" + localFile.isValid + ", volume packSize=" + localFile.header.packSize); if (localFile && localFile.isValid && localFile.header.packSize > 0) { RarUtils.PROGRESS.totalUncompressedBytesInArchive += localFile.header.unpackedSize; localFiles.push(localFile); } else if (localFile.header.packSize == 0 && localFile.header.unpackedSize == 0) { localFile.isValid = true; } } catch (err) { break; } RarEventMgr.emitInfo("bstream" + bstream.bytePtr + "/" + bstream.bytes.length); } while (localFile.isValid); RarUtils.PROGRESS.totalFilesInArchive = localFiles.length; // now we have all console.information but things are unpacked // TODO: unpack localFiles = localFiles.sort(function(a, b) { var aname = a.filename; var bname = b.filename; return aname > bname ? 1 : -1; }); RarEventMgr.emitInfo(localFiles.map(function(a) { return a.filename }).join(', ')); for (var i = 0; i < localFiles.length; ++i) { var localfile = localFiles[i]; RarEventMgr.emitInfo("Local file: ", localfile.filename); // update progress RarUtils.PROGRESS.currentFilename = localfile.header.filename; RarUtils.PROGRESS.currentBytesUnarchivedInFile = 0; // actually do the unzipping localfile.unrar(); if (localfile.isValid) { // notify extract event with file RarEventMgr.emitExtract(localfile); RarEventMgr.emitProgress(RarUtils.PROGRESS); } } RarEventMgr.emitProgress(RarUtils.PROGRESS); } } else { RarEventMgr.emitError("Invalid RAR file"); } RarEventMgr.emitFinish(localFiles); return localFiles; }
[ "function", "unrar", "(", "arrayBuffer", ")", "{", "RarEventMgr", ".", "emitStart", "(", ")", ";", "var", "bstream", "=", "new", "BitStream", "(", "arrayBuffer", ",", "false", ")", ";", "var", "header", "=", "new", "RarVolumeHeader", "(", "bstream", ")", ";", "if", "(", "header", ".", "crc", "==", "0x6152", "&&", "header", ".", "headType", "==", "0x72", "&&", "header", ".", "flags", ".", "value", "==", "0x1A21", "&&", "header", ".", "headSize", "==", "7", ")", "{", "RarEventMgr", ".", "emitInfo", "(", "\"Found RAR signature\"", ")", ";", "var", "mhead", "=", "new", "RarVolumeHeader", "(", "bstream", ")", ";", "if", "(", "mhead", ".", "headType", "!=", "RarUtils", ".", "VOLUME_TYPES", ".", "MAIN_HEAD", ")", "{", "RarEventMgr", ".", "emitError", "(", "\"Error! RAR did not include a MAIN_HEAD header\"", ")", ";", "}", "else", "{", "var", "localFiles", "=", "[", "]", ",", "localFile", "=", "null", ";", "do", "{", "try", "{", "localFile", "=", "new", "RarLocalFile", "(", "bstream", ")", ";", "RarEventMgr", ".", "emitInfo", "(", "\"RAR localFile isValid=\"", "+", "localFile", ".", "isValid", "+", "\", volume packSize=\"", "+", "localFile", ".", "header", ".", "packSize", ")", ";", "if", "(", "localFile", "&&", "localFile", ".", "isValid", "&&", "localFile", ".", "header", ".", "packSize", ">", "0", ")", "{", "RarUtils", ".", "PROGRESS", ".", "totalUncompressedBytesInArchive", "+=", "localFile", ".", "header", ".", "unpackedSize", ";", "localFiles", ".", "push", "(", "localFile", ")", ";", "}", "else", "if", "(", "localFile", ".", "header", ".", "packSize", "==", "0", "&&", "localFile", ".", "header", ".", "unpackedSize", "==", "0", ")", "{", "localFile", ".", "isValid", "=", "true", ";", "}", "}", "catch", "(", "err", ")", "{", "break", ";", "}", "RarEventMgr", ".", "emitInfo", "(", "\"bstream\"", "+", "bstream", ".", "bytePtr", "+", "\"/\"", "+", "bstream", ".", "bytes", ".", "length", ")", ";", "}", "while", "(", "localFile", ".", "isValid", ")", ";", "RarUtils", ".", "PROGRESS", ".", "totalFilesInArchive", "=", "localFiles", ".", "length", ";", "localFiles", "=", "localFiles", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "var", "aname", "=", "a", ".", "filename", ";", "var", "bname", "=", "b", ".", "filename", ";", "return", "aname", ">", "bname", "?", "1", ":", "-", "1", ";", "}", ")", ";", "RarEventMgr", ".", "emitInfo", "(", "localFiles", ".", "map", "(", "function", "(", "a", ")", "{", "return", "a", ".", "filename", "}", ")", ".", "join", "(", "', '", ")", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "localFiles", ".", "length", ";", "++", "i", ")", "{", "var", "localfile", "=", "localFiles", "[", "i", "]", ";", "RarEventMgr", ".", "emitInfo", "(", "\"Local file: \"", ",", "localfile", ".", "filename", ")", ";", "RarUtils", ".", "PROGRESS", ".", "currentFilename", "=", "localfile", ".", "header", ".", "filename", ";", "RarUtils", ".", "PROGRESS", ".", "currentBytesUnarchivedInFile", "=", "0", ";", "localfile", ".", "unrar", "(", ")", ";", "if", "(", "localfile", ".", "isValid", ")", "{", "RarEventMgr", ".", "emitExtract", "(", "localfile", ")", ";", "RarEventMgr", ".", "emitProgress", "(", "RarUtils", ".", "PROGRESS", ")", ";", "}", "}", "RarEventMgr", ".", "emitProgress", "(", "RarUtils", ".", "PROGRESS", ")", ";", "}", "}", "else", "{", "RarEventMgr", ".", "emitError", "(", "\"Invalid RAR file\"", ")", ";", "}", "RarEventMgr", ".", "emitFinish", "(", "localFiles", ")", ";", "return", "localFiles", ";", "}" ]
make sure we flush all tracking variables
[ "make", "sure", "we", "flush", "all", "tracking", "variables" ]
88f56ee9ef9d133a24119b8f6e456b8f55a294d4
https://github.com/boggan/unrar.js/blob/88f56ee9ef9d133a24119b8f6e456b8f55a294d4/lib/Unrar.js#L40-L115
train
boggan/unrar.js
lib/BitStream.js
BitStream
function BitStream(ab, rtl, opt_offset, opt_length) { // if (!ab || !ab.toString || ab.toString() !== "[object ArrayBuffer]") { // throw "Error! BitArray constructed with an invalid ArrayBuffer object"; // } var offset = opt_offset || 0; var length = opt_length || ab.byteLength; this.bytes = new Uint8Array(ab, offset, length); this.bytePtr = 0; // tracks which byte we are on this.bitPtr = 0; // tracks which bit we are on (can have values 0 through 7) this.peekBits = rtl ? this.peekBits_rtl : this.peekBits_ltr; }
javascript
function BitStream(ab, rtl, opt_offset, opt_length) { // if (!ab || !ab.toString || ab.toString() !== "[object ArrayBuffer]") { // throw "Error! BitArray constructed with an invalid ArrayBuffer object"; // } var offset = opt_offset || 0; var length = opt_length || ab.byteLength; this.bytes = new Uint8Array(ab, offset, length); this.bytePtr = 0; // tracks which byte we are on this.bitPtr = 0; // tracks which bit we are on (can have values 0 through 7) this.peekBits = rtl ? this.peekBits_rtl : this.peekBits_ltr; }
[ "function", "BitStream", "(", "ab", ",", "rtl", ",", "opt_offset", ",", "opt_length", ")", "{", "var", "offset", "=", "opt_offset", "||", "0", ";", "var", "length", "=", "opt_length", "||", "ab", ".", "byteLength", ";", "this", ".", "bytes", "=", "new", "Uint8Array", "(", "ab", ",", "offset", ",", "length", ")", ";", "this", ".", "bytePtr", "=", "0", ";", "this", ".", "bitPtr", "=", "0", ";", "this", ".", "peekBits", "=", "rtl", "?", "this", ".", "peekBits_rtl", ":", "this", ".", "peekBits_ltr", ";", "}" ]
This bit stream peeks and consumes bits out of a binary stream. @param {ArrayBuffer} ab An ArrayBuffer object or a Uint8Array. @param {boolean} rtl Whether the stream reads bits from the byte starting from bit 7 to 0 (true) or bit 0 to 7 (false). @param {Number} opt_offset The offset into the ArrayBuffer @param {Number} opt_length The length of this BitStream
[ "This", "bit", "stream", "peeks", "and", "consumes", "bits", "out", "of", "a", "binary", "stream", "." ]
88f56ee9ef9d133a24119b8f6e456b8f55a294d4
https://github.com/boggan/unrar.js/blob/88f56ee9ef9d133a24119b8f6e456b8f55a294d4/lib/BitStream.js#L14-L25
train
senecajs/seneca-web
web.js
mapRoutes
function mapRoutes(msg, done) { var seneca = this var adapter = msg.adapter || locals.adapter var context = msg.context || locals.context var options = msg.options || locals.options var routes = Mapper(msg.routes) var auth = msg.auth || locals.auth // Call the adaptor with the mapped routes, context to apply them to // and instance of seneca and the provided consumer callback. adapter.call(seneca, options, context, auth, routes, done) }
javascript
function mapRoutes(msg, done) { var seneca = this var adapter = msg.adapter || locals.adapter var context = msg.context || locals.context var options = msg.options || locals.options var routes = Mapper(msg.routes) var auth = msg.auth || locals.auth // Call the adaptor with the mapped routes, context to apply them to // and instance of seneca and the provided consumer callback. adapter.call(seneca, options, context, auth, routes, done) }
[ "function", "mapRoutes", "(", "msg", ",", "done", ")", "{", "var", "seneca", "=", "this", "var", "adapter", "=", "msg", ".", "adapter", "||", "locals", ".", "adapter", "var", "context", "=", "msg", ".", "context", "||", "locals", ".", "context", "var", "options", "=", "msg", ".", "options", "||", "locals", ".", "options", "var", "routes", "=", "Mapper", "(", "msg", ".", "routes", ")", "var", "auth", "=", "msg", ".", "auth", "||", "locals", ".", "auth", "adapter", ".", "call", "(", "seneca", ",", "options", ",", "context", ",", "auth", ",", "routes", ",", "done", ")", "}" ]
Creates a route-map and passes it to a given adapter. The msg can optionally contain a custom adapter or context for once off routing.
[ "Creates", "a", "route", "-", "map", "and", "passes", "it", "to", "a", "given", "adapter", ".", "The", "msg", "can", "optionally", "contain", "a", "custom", "adapter", "or", "context", "for", "once", "off", "routing", "." ]
e990cc8f8fcfa70b984ffe0aa7aab57a64e8c6cb
https://github.com/senecajs/seneca-web/blob/e990cc8f8fcfa70b984ffe0aa7aab57a64e8c6cb/web.js#L58-L69
train
senecajs/seneca-web
web.js
setServer
function setServer(msg, done) { var seneca = this var context = msg.context || locals.context var adapter = msg.adapter || locals.adapter var options = msg.options || locals.options var auth = msg.auth || locals.auth var routes = msg.routes // If the adapter is a string, we look up the // adapters collection in opts.adapters. if (!_.isFunction(adapter)) { return done(new Error('Provide a function as adapter')) } // either replaced or the same. Regardless // this sets what is called by mapRoutes. locals = { context: context, adapter: adapter, auth: auth, options: options } // If we have routes in the msg map them and // let the matter handle the callback if (routes) { mapRoutes.call(seneca, { routes: routes }, done) } else { // no routes to process, let the // caller know everything went ok. done(null, { ok: true }) } }
javascript
function setServer(msg, done) { var seneca = this var context = msg.context || locals.context var adapter = msg.adapter || locals.adapter var options = msg.options || locals.options var auth = msg.auth || locals.auth var routes = msg.routes // If the adapter is a string, we look up the // adapters collection in opts.adapters. if (!_.isFunction(adapter)) { return done(new Error('Provide a function as adapter')) } // either replaced or the same. Regardless // this sets what is called by mapRoutes. locals = { context: context, adapter: adapter, auth: auth, options: options } // If we have routes in the msg map them and // let the matter handle the callback if (routes) { mapRoutes.call(seneca, { routes: routes }, done) } else { // no routes to process, let the // caller know everything went ok. done(null, { ok: true }) } }
[ "function", "setServer", "(", "msg", ",", "done", ")", "{", "var", "seneca", "=", "this", "var", "context", "=", "msg", ".", "context", "||", "locals", ".", "context", "var", "adapter", "=", "msg", ".", "adapter", "||", "locals", ".", "adapter", "var", "options", "=", "msg", ".", "options", "||", "locals", ".", "options", "var", "auth", "=", "msg", ".", "auth", "||", "locals", ".", "auth", "var", "routes", "=", "msg", ".", "routes", "if", "(", "!", "_", ".", "isFunction", "(", "adapter", ")", ")", "{", "return", "done", "(", "new", "Error", "(", "'Provide a function as adapter'", ")", ")", "}", "locals", "=", "{", "context", ":", "context", ",", "adapter", ":", "adapter", ",", "auth", ":", "auth", ",", "options", ":", "options", "}", "if", "(", "routes", ")", "{", "mapRoutes", ".", "call", "(", "seneca", ",", "{", "routes", ":", "routes", "}", ",", "done", ")", "}", "else", "{", "done", "(", "null", ",", "{", "ok", ":", "true", "}", ")", "}", "}" ]
Sets the 'default' server context. Any call to mapRoutes will use this server as it's context if none is provided. This is the server returned by getServer.
[ "Sets", "the", "default", "server", "context", ".", "Any", "call", "to", "mapRoutes", "will", "use", "this", "server", "as", "it", "s", "context", "if", "none", "is", "provided", ".", "This", "is", "the", "server", "returned", "by", "getServer", "." ]
e990cc8f8fcfa70b984ffe0aa7aab57a64e8c6cb
https://github.com/senecajs/seneca-web/blob/e990cc8f8fcfa70b984ffe0aa7aab57a64e8c6cb/web.js#L73-L105
train
sidorares/nodejs-mysql-native
lib/mysql-native/command.js
cmd
function cmd(handlers) { this.fieldindex = 0; this.state = "start"; this.stmt = "" this.params = [] // mixin all handlers for (var h in handlers) { this[h] = handlers[h]; } // save command name to display in debug output this.command_name = cmd.caller.command_name; this.args = Array.prototype.slice.call(cmd.caller.arguments); }
javascript
function cmd(handlers) { this.fieldindex = 0; this.state = "start"; this.stmt = "" this.params = [] // mixin all handlers for (var h in handlers) { this[h] = handlers[h]; } // save command name to display in debug output this.command_name = cmd.caller.command_name; this.args = Array.prototype.slice.call(cmd.caller.arguments); }
[ "function", "cmd", "(", "handlers", ")", "{", "this", ".", "fieldindex", "=", "0", ";", "this", ".", "state", "=", "\"start\"", ";", "this", ".", "stmt", "=", "\"\"", "this", ".", "params", "=", "[", "]", "for", "(", "var", "h", "in", "handlers", ")", "{", "this", "[", "h", "]", "=", "handlers", "[", "h", "]", ";", "}", "this", ".", "command_name", "=", "cmd", ".", "caller", ".", "command_name", ";", "this", ".", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "cmd", ".", "caller", ".", "arguments", ")", ";", "}" ]
base for all commands initialises EventEmitter and implemets state mashine
[ "base", "for", "all", "commands", "initialises", "EventEmitter", "and", "implemets", "state", "mashine" ]
a7bb1356c8722b99e75e1eecf0af960fdc3c56c3
https://github.com/sidorares/nodejs-mysql-native/blob/a7bb1356c8722b99e75e1eecf0af960fdc3c56c3/lib/mysql-native/command.js#L8-L23
train
thaliproject/Thali_CordovaPlugin
thali/install/cordova-hooks/ios/before_plugin_install.js
updateJXcoreExtensionImport
function updateJXcoreExtensionImport(context) { var cordovaUtil = context.requireCordovaModule('cordova-lib/src/cordova/util'); var ConfigParser = context.requireCordovaModule('cordova-lib').configparser; var projectRoot = cordovaUtil.isCordova(); var xml = cordovaUtil.projectConfig(projectRoot); var cfg = new ConfigParser(xml); var Q = context.requireCordovaModule('q'); var deferred = new Q.defer(); var jxcoreExtensionPath = path.join( context.opts.plugin.dir, 'src', 'ios', 'JXcoreExtension.m'); try { console.log('Updating JXcoreExtension.m'); var oldContent = fs.readFileSync(jxcoreExtensionPath, 'utf8'); var newContent = oldContent.replace('%PROJECT_NAME%', cfg.name()); fs.writeFileSync(jxcoreExtensionPath, newContent, 'utf8'); deferred.resolve(); } catch (error) { console.log('Failed updating of JXcoreExtension.m'); deferred.reject(error); } return deferred.promise; }
javascript
function updateJXcoreExtensionImport(context) { var cordovaUtil = context.requireCordovaModule('cordova-lib/src/cordova/util'); var ConfigParser = context.requireCordovaModule('cordova-lib').configparser; var projectRoot = cordovaUtil.isCordova(); var xml = cordovaUtil.projectConfig(projectRoot); var cfg = new ConfigParser(xml); var Q = context.requireCordovaModule('q'); var deferred = new Q.defer(); var jxcoreExtensionPath = path.join( context.opts.plugin.dir, 'src', 'ios', 'JXcoreExtension.m'); try { console.log('Updating JXcoreExtension.m'); var oldContent = fs.readFileSync(jxcoreExtensionPath, 'utf8'); var newContent = oldContent.replace('%PROJECT_NAME%', cfg.name()); fs.writeFileSync(jxcoreExtensionPath, newContent, 'utf8'); deferred.resolve(); } catch (error) { console.log('Failed updating of JXcoreExtension.m'); deferred.reject(error); } return deferred.promise; }
[ "function", "updateJXcoreExtensionImport", "(", "context", ")", "{", "var", "cordovaUtil", "=", "context", ".", "requireCordovaModule", "(", "'cordova-lib/src/cordova/util'", ")", ";", "var", "ConfigParser", "=", "context", ".", "requireCordovaModule", "(", "'cordova-lib'", ")", ".", "configparser", ";", "var", "projectRoot", "=", "cordovaUtil", ".", "isCordova", "(", ")", ";", "var", "xml", "=", "cordovaUtil", ".", "projectConfig", "(", "projectRoot", ")", ";", "var", "cfg", "=", "new", "ConfigParser", "(", "xml", ")", ";", "var", "Q", "=", "context", ".", "requireCordovaModule", "(", "'q'", ")", ";", "var", "deferred", "=", "new", "Q", ".", "defer", "(", ")", ";", "var", "jxcoreExtensionPath", "=", "path", ".", "join", "(", "context", ".", "opts", ".", "plugin", ".", "dir", ",", "'src'", ",", "'ios'", ",", "'JXcoreExtension.m'", ")", ";", "try", "{", "console", ".", "log", "(", "'Updating JXcoreExtension.m'", ")", ";", "var", "oldContent", "=", "fs", ".", "readFileSync", "(", "jxcoreExtensionPath", ",", "'utf8'", ")", ";", "var", "newContent", "=", "oldContent", ".", "replace", "(", "'%PROJECT_NAME%'", ",", "cfg", ".", "name", "(", ")", ")", ";", "fs", ".", "writeFileSync", "(", "jxcoreExtensionPath", ",", "newContent", ",", "'utf8'", ")", ";", "deferred", ".", "resolve", "(", ")", ";", "}", "catch", "(", "error", ")", "{", "console", ".", "log", "(", "'Failed updating of JXcoreExtension.m'", ")", ";", "deferred", ".", "reject", "(", "error", ")", ";", "}", "return", "deferred", ".", "promise", ";", "}" ]
Replaces PROJECT_NAME pattern with actual Cordova's project name
[ "Replaces", "PROJECT_NAME", "pattern", "with", "actual", "Cordova", "s", "project", "name" ]
0496da88a125a871d2ebff39359fbbf8ba01fd8f
https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/install/cordova-hooks/ios/before_plugin_install.js#L13-L41
train
thaliproject/Thali_CordovaPlugin
thali/NextGeneration/thaliMobileNativeWrapper.js
function (methodName, callback) { Mobile(methodName).registerToNative(callback); Mobile('didRegisterToNative').callNative(methodName, function () { logger.debug('Method %s registered to native', methodName); }); }
javascript
function (methodName, callback) { Mobile(methodName).registerToNative(callback); Mobile('didRegisterToNative').callNative(methodName, function () { logger.debug('Method %s registered to native', methodName); }); }
[ "function", "(", "methodName", ",", "callback", ")", "{", "Mobile", "(", "methodName", ")", ".", "registerToNative", "(", "callback", ")", ";", "Mobile", "(", "'didRegisterToNative'", ")", ".", "callNative", "(", "methodName", ",", "function", "(", ")", "{", "logger", ".", "debug", "(", "'Method %s registered to native'", ",", "methodName", ")", ";", "}", ")", ";", "}" ]
Function to register a method to the native side and inform that the registration was done.
[ "Function", "to", "register", "a", "method", "to", "the", "native", "side", "and", "inform", "that", "the", "registration", "was", "done", "." ]
0496da88a125a871d2ebff39359fbbf8ba01fd8f
https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/NextGeneration/thaliMobileNativeWrapper.js#L1224-L1229
train
thaliproject/Thali_CordovaPlugin
thali/NextGeneration/replication/utilities.js
compareBufferArrays
function compareBufferArrays(buffArray1, buffArray2) { assert(Array.isArray(buffArray1), 'We only accept arrays.'); assert(Array.isArray(buffArray2), 'We only accept arrays.'); if (buffArray1.length !== buffArray2.length) { return false; } for (var i = 0; i < buffArray1.length; ++i) { var buff1 = buffArray1[i]; assert(Buffer.isBuffer(buff1), 'Only buffers allowed in 1'); var buff2 = buffArray2[i]; assert(Buffer.isBuffer(buff2), 'Only buffers allowed in 2'); if (Buffer.compare(buff1, buff2) !== 0) { return false; } } return true; }
javascript
function compareBufferArrays(buffArray1, buffArray2) { assert(Array.isArray(buffArray1), 'We only accept arrays.'); assert(Array.isArray(buffArray2), 'We only accept arrays.'); if (buffArray1.length !== buffArray2.length) { return false; } for (var i = 0; i < buffArray1.length; ++i) { var buff1 = buffArray1[i]; assert(Buffer.isBuffer(buff1), 'Only buffers allowed in 1'); var buff2 = buffArray2[i]; assert(Buffer.isBuffer(buff2), 'Only buffers allowed in 2'); if (Buffer.compare(buff1, buff2) !== 0) { return false; } } return true; }
[ "function", "compareBufferArrays", "(", "buffArray1", ",", "buffArray2", ")", "{", "assert", "(", "Array", ".", "isArray", "(", "buffArray1", ")", ",", "'We only accept arrays.'", ")", ";", "assert", "(", "Array", ".", "isArray", "(", "buffArray2", ")", ",", "'We only accept arrays.'", ")", ";", "if", "(", "buffArray1", ".", "length", "!==", "buffArray2", ".", "length", ")", "{", "return", "false", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "buffArray1", ".", "length", ";", "++", "i", ")", "{", "var", "buff1", "=", "buffArray1", "[", "i", "]", ";", "assert", "(", "Buffer", ".", "isBuffer", "(", "buff1", ")", ",", "'Only buffers allowed in 1'", ")", ";", "var", "buff2", "=", "buffArray2", "[", "i", "]", ";", "assert", "(", "Buffer", ".", "isBuffer", "(", "buff2", ")", ",", "'Only buffers allowed in 2'", ")", ";", "if", "(", "Buffer", ".", "compare", "(", "buff1", ",", "buff2", ")", "!==", "0", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Compares if two buffer arrays contain the same buffers in the same order. @param {Buffer[]} buffArray1 @param {Buffer[]} buffArray2 @returns {boolean}
[ "Compares", "if", "two", "buffer", "arrays", "contain", "the", "same", "buffers", "in", "the", "same", "order", "." ]
0496da88a125a871d2ebff39359fbbf8ba01fd8f
https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/NextGeneration/replication/utilities.js#L11-L27
train
thaliproject/Thali_CordovaPlugin
thali/NextGeneration/mux/createPeerListener.js
closeOldestServer
function closeOldestServer() { var oldest = null; Object.keys(self._peerServers).forEach(function (k) { if (oldest == null) { oldest = k; } else { if (self._peerServers[k].lastActive < self._peerServers[oldest].lastActive) { oldest = k; } } }); if (oldest) { closeServer(self, self._peerServers[oldest], null, false); } }
javascript
function closeOldestServer() { var oldest = null; Object.keys(self._peerServers).forEach(function (k) { if (oldest == null) { oldest = k; } else { if (self._peerServers[k].lastActive < self._peerServers[oldest].lastActive) { oldest = k; } } }); if (oldest) { closeServer(self, self._peerServers[oldest], null, false); } }
[ "function", "closeOldestServer", "(", ")", "{", "var", "oldest", "=", "null", ";", "Object", ".", "keys", "(", "self", ".", "_peerServers", ")", ".", "forEach", "(", "function", "(", "k", ")", "{", "if", "(", "oldest", "==", "null", ")", "{", "oldest", "=", "k", ";", "}", "else", "{", "if", "(", "self", ".", "_peerServers", "[", "k", "]", ".", "lastActive", "<", "self", ".", "_peerServers", "[", "oldest", "]", ".", "lastActive", ")", "{", "oldest", "=", "k", ";", "}", "}", "}", ")", ";", "if", "(", "oldest", ")", "{", "closeServer", "(", "self", ",", "self", ".", "_peerServers", "[", "oldest", "]", ",", "null", ",", "false", ")", ";", "}", "}" ]
This is the server that will listen for connection coming from the application
[ "This", "is", "the", "server", "that", "will", "listen", "for", "connection", "coming", "from", "the", "application" ]
0496da88a125a871d2ebff39359fbbf8ba01fd8f
https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/NextGeneration/mux/createPeerListener.js#L466-L482
train
thaliproject/Thali_CordovaPlugin
thali/install/install.js
httpRequestPromise
function httpRequestPromise(method, urlObject) { if (method !== 'GET' && method !== 'HEAD') { return Promise.reject(new Error('We only support GET or HEAD requests')); } return new Promise(function (resolve, reject) { var httpsRequestOptions = { host: urlObject.host, method: method, path: urlObject.path }; var req = https.request(httpsRequestOptions, function (res) { if (res.statusCode !== 200) { reject(new Error('Did not get 200 for ' + urlObject.href + ', instead got ' + res.statusCode)); return; } resolve(res); }) .on('error', function (e) { reject(new Error('Got error on ' + urlObject.href + ' - ' + e)); }); req.end(); }); }
javascript
function httpRequestPromise(method, urlObject) { if (method !== 'GET' && method !== 'HEAD') { return Promise.reject(new Error('We only support GET or HEAD requests')); } return new Promise(function (resolve, reject) { var httpsRequestOptions = { host: urlObject.host, method: method, path: urlObject.path }; var req = https.request(httpsRequestOptions, function (res) { if (res.statusCode !== 200) { reject(new Error('Did not get 200 for ' + urlObject.href + ', instead got ' + res.statusCode)); return; } resolve(res); }) .on('error', function (e) { reject(new Error('Got error on ' + urlObject.href + ' - ' + e)); }); req.end(); }); }
[ "function", "httpRequestPromise", "(", "method", ",", "urlObject", ")", "{", "if", "(", "method", "!==", "'GET'", "&&", "method", "!==", "'HEAD'", ")", "{", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "'We only support GET or HEAD requests'", ")", ")", ";", "}", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "httpsRequestOptions", "=", "{", "host", ":", "urlObject", ".", "host", ",", "method", ":", "method", ",", "path", ":", "urlObject", ".", "path", "}", ";", "var", "req", "=", "https", ".", "request", "(", "httpsRequestOptions", ",", "function", "(", "res", ")", "{", "if", "(", "res", ".", "statusCode", "!==", "200", ")", "{", "reject", "(", "new", "Error", "(", "'Did not get 200 for '", "+", "urlObject", ".", "href", "+", "', instead got '", "+", "res", ".", "statusCode", ")", ")", ";", "return", ";", "}", "resolve", "(", "res", ")", ";", "}", ")", ".", "on", "(", "'error'", ",", "function", "(", "e", ")", "{", "reject", "(", "new", "Error", "(", "'Got error on '", "+", "urlObject", ".", "href", "+", "' - '", "+", "e", ")", ")", ";", "}", ")", ";", "req", ".", "end", "(", ")", ";", "}", ")", ";", "}" ]
Unfortunately the obvious library, request-promise, doesn't handle streams well so it would take the multi-megabyte ZIP response file and turn it into an in-memory string. So we use this instead.
[ "Unfortunately", "the", "obvious", "library", "request", "-", "promise", "doesn", "t", "handle", "streams", "well", "so", "it", "would", "take", "the", "multi", "-", "megabyte", "ZIP", "response", "file", "and", "turn", "it", "into", "an", "in", "-", "memory", "string", ".", "So", "we", "use", "this", "instead", "." ]
0496da88a125a871d2ebff39359fbbf8ba01fd8f
https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/install/install.js#L26-L53
train
thaliproject/Thali_CordovaPlugin
thali/install/install.js
getReleaseConfig
function getReleaseConfig() { var configFileName = path.join(__dirname, '..', 'package.json'); return fs.readFileAsync(configFileName, 'utf-8') .then(function (data) { var conf; try { conf = JSON.parse(data); if (conf && conf.thaliInstall) { return conf.thaliInstall; } return Promise.reject('Configuration error!'); } catch (err) { return Promise.reject(new Error(err)); } }); }
javascript
function getReleaseConfig() { var configFileName = path.join(__dirname, '..', 'package.json'); return fs.readFileAsync(configFileName, 'utf-8') .then(function (data) { var conf; try { conf = JSON.parse(data); if (conf && conf.thaliInstall) { return conf.thaliInstall; } return Promise.reject('Configuration error!'); } catch (err) { return Promise.reject(new Error(err)); } }); }
[ "function", "getReleaseConfig", "(", ")", "{", "var", "configFileName", "=", "path", ".", "join", "(", "__dirname", ",", "'..'", ",", "'package.json'", ")", ";", "return", "fs", ".", "readFileAsync", "(", "configFileName", ",", "'utf-8'", ")", ".", "then", "(", "function", "(", "data", ")", "{", "var", "conf", ";", "try", "{", "conf", "=", "JSON", ".", "parse", "(", "data", ")", ";", "if", "(", "conf", "&&", "conf", ".", "thaliInstall", ")", "{", "return", "conf", ".", "thaliInstall", ";", "}", "return", "Promise", ".", "reject", "(", "'Configuration error!'", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "err", ")", ")", ";", "}", "}", ")", ";", "}" ]
This method is used to retrieve the release configuration data stored in the releaseConfig.json. @returns {Promise} Returns release config
[ "This", "method", "is", "used", "to", "retrieve", "the", "release", "configuration", "data", "stored", "in", "the", "releaseConfig", ".", "json", "." ]
0496da88a125a871d2ebff39359fbbf8ba01fd8f
https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/install/install.js#L79-L96
train
thaliproject/Thali_CordovaPlugin
thali/install/install.js
doGitHubEtagsMatch
function doGitHubEtagsMatch(projectName, depotName, branchName, directoryToInstallIn) { return getEtagFromEtagFile(depotName, branchName, directoryToInstallIn) .then(function (etagFromFile) { if (!etagFromFile) { return false; } return httpRequestPromise('HEAD', getGitHubZipUrlObject(projectName, depotName, branchName)) .then(function (res) { var etagFromHeadRequest = returnEtagFromResponse(res); return etagFromFile === etagFromHeadRequest; }); }); }
javascript
function doGitHubEtagsMatch(projectName, depotName, branchName, directoryToInstallIn) { return getEtagFromEtagFile(depotName, branchName, directoryToInstallIn) .then(function (etagFromFile) { if (!etagFromFile) { return false; } return httpRequestPromise('HEAD', getGitHubZipUrlObject(projectName, depotName, branchName)) .then(function (res) { var etagFromHeadRequest = returnEtagFromResponse(res); return etagFromFile === etagFromHeadRequest; }); }); }
[ "function", "doGitHubEtagsMatch", "(", "projectName", ",", "depotName", ",", "branchName", ",", "directoryToInstallIn", ")", "{", "return", "getEtagFromEtagFile", "(", "depotName", ",", "branchName", ",", "directoryToInstallIn", ")", ".", "then", "(", "function", "(", "etagFromFile", ")", "{", "if", "(", "!", "etagFromFile", ")", "{", "return", "false", ";", "}", "return", "httpRequestPromise", "(", "'HEAD'", ",", "getGitHubZipUrlObject", "(", "projectName", ",", "depotName", ",", "branchName", ")", ")", ".", "then", "(", "function", "(", "res", ")", "{", "var", "etagFromHeadRequest", "=", "returnEtagFromResponse", "(", "res", ")", ";", "return", "etagFromFile", "===", "etagFromHeadRequest", ";", "}", ")", ";", "}", ")", ";", "}" ]
This method is a hack because I'm having trouble getting GitHub to respect if-none-match headers. So instead I'm doing a HEAD request and manually checking if the etags match. @param {string} projectName The project name @param {string} depotName The depot name @param {string} branchName The branch name @param {string} directoryToInstallIn The directory to install in @returns {boolean} Do the etags match?
[ "This", "method", "is", "a", "hack", "because", "I", "m", "having", "trouble", "getting", "GitHub", "to", "respect", "if", "-", "none", "-", "match", "headers", ".", "So", "instead", "I", "m", "doing", "a", "HEAD", "request", "and", "manually", "checking", "if", "the", "etags", "match", "." ]
0496da88a125a871d2ebff39359fbbf8ba01fd8f
https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/install/install.js#L137-L152
train
thaliproject/Thali_CordovaPlugin
thali/install/install.js
copyDevelopmentThaliCordovaPluginToProject
function copyDevelopmentThaliCordovaPluginToProject(appRootDirectory, thaliDontCheckIn, depotName, branchName) { var targetDirectory = createUnzippedDirectoryPath(depotName, branchName, thaliDontCheckIn); var sourceDirectory = path.join( appRootDirectory, '..', 'Thali_CordovaPlugin'); return new Promise(function (resolve, reject) { fs.remove(targetDirectory, function (err) { if (err) { reject(new Error('copyDevelopmentThaliCordovaPluginToProject remove ' + 'failed with ' + err)); return; } console.log('Copying files from ' + sourceDirectory + ' to ' + targetDirectory); fs.copy(sourceDirectory, targetDirectory, function (err) { if (err) { reject( new Error('copyDevelopmentThaliCordovaPluginToProject failed with' + err)); return; } resolve(createGitHubZipResponse(depotName, branchName, thaliDontCheckIn, true)); }); }); }); }
javascript
function copyDevelopmentThaliCordovaPluginToProject(appRootDirectory, thaliDontCheckIn, depotName, branchName) { var targetDirectory = createUnzippedDirectoryPath(depotName, branchName, thaliDontCheckIn); var sourceDirectory = path.join( appRootDirectory, '..', 'Thali_CordovaPlugin'); return new Promise(function (resolve, reject) { fs.remove(targetDirectory, function (err) { if (err) { reject(new Error('copyDevelopmentThaliCordovaPluginToProject remove ' + 'failed with ' + err)); return; } console.log('Copying files from ' + sourceDirectory + ' to ' + targetDirectory); fs.copy(sourceDirectory, targetDirectory, function (err) { if (err) { reject( new Error('copyDevelopmentThaliCordovaPluginToProject failed with' + err)); return; } resolve(createGitHubZipResponse(depotName, branchName, thaliDontCheckIn, true)); }); }); }); }
[ "function", "copyDevelopmentThaliCordovaPluginToProject", "(", "appRootDirectory", ",", "thaliDontCheckIn", ",", "depotName", ",", "branchName", ")", "{", "var", "targetDirectory", "=", "createUnzippedDirectoryPath", "(", "depotName", ",", "branchName", ",", "thaliDontCheckIn", ")", ";", "var", "sourceDirectory", "=", "path", ".", "join", "(", "appRootDirectory", ",", "'..'", ",", "'Thali_CordovaPlugin'", ")", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "fs", ".", "remove", "(", "targetDirectory", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "reject", "(", "new", "Error", "(", "'copyDevelopmentThaliCordovaPluginToProject remove '", "+", "'failed with '", "+", "err", ")", ")", ";", "return", ";", "}", "console", ".", "log", "(", "'Copying files from '", "+", "sourceDirectory", "+", "' to '", "+", "targetDirectory", ")", ";", "fs", ".", "copy", "(", "sourceDirectory", ",", "targetDirectory", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "reject", "(", "new", "Error", "(", "'copyDevelopmentThaliCordovaPluginToProject failed with'", "+", "err", ")", ")", ";", "return", ";", "}", "resolve", "(", "createGitHubZipResponse", "(", "depotName", ",", "branchName", ",", "thaliDontCheckIn", ",", "true", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
This will copy the contents of a Thali_CordovaPlugin local depot to the right directory in the current Cordova project so it will be installed. This is used for local development only. @param {string} appRootDirectory @param {string} thaliDontCheckIn @param {string} depotName @param {string} branchName @returns {Promise<Object|Error>}
[ "This", "will", "copy", "the", "contents", "of", "a", "Thali_CordovaPlugin", "local", "depot", "to", "the", "right", "directory", "in", "the", "current", "Cordova", "project", "so", "it", "will", "be", "installed", ".", "This", "is", "used", "for", "local", "development", "only", "." ]
0496da88a125a871d2ebff39359fbbf8ba01fd8f
https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/install/install.js#L245-L275
train
thaliproject/Thali_CordovaPlugin
thali/install/validateBuildEnvironment.js
checkVersion
function checkVersion(objectName, versionNumber) { const desiredVersion = versionNumber ? versionNumber : versions[objectName]; const commandAndResult = commandsAndResults[objectName]; if (!commandAndResult) { return Promise.reject( new Error('Unrecognized objectName in commandsAndResults')); } if (!desiredVersion) { return Promise.reject(new Error('Unrecognized objectName in versions')); } if (commandAndResult.platform && !commandAndResult.platform.includes(os.platform())) { return Promise.reject(new Error('Requested object is not supported on ' + 'this platform')); } if (typeof commandAndResult.versionCheck === 'function') { return promiseTry(commandAndResult.versionCheck) .catch(() => Promise.reject(new Error('Version Check failed on ' + objectName))) .then((versionCheckResult) => commandAndResult.versionValidate(versionCheckResult, desiredVersion)) .then(() => Promise.resolve(true)) .catch(() => Promise.reject( new Error('Version not installed of ' + objectName))); } return execAndCheck(commandAndResult.versionCheck, commandAndResult.checkStdErr, desiredVersion, commandAndResult.versionValidate); }
javascript
function checkVersion(objectName, versionNumber) { const desiredVersion = versionNumber ? versionNumber : versions[objectName]; const commandAndResult = commandsAndResults[objectName]; if (!commandAndResult) { return Promise.reject( new Error('Unrecognized objectName in commandsAndResults')); } if (!desiredVersion) { return Promise.reject(new Error('Unrecognized objectName in versions')); } if (commandAndResult.platform && !commandAndResult.platform.includes(os.platform())) { return Promise.reject(new Error('Requested object is not supported on ' + 'this platform')); } if (typeof commandAndResult.versionCheck === 'function') { return promiseTry(commandAndResult.versionCheck) .catch(() => Promise.reject(new Error('Version Check failed on ' + objectName))) .then((versionCheckResult) => commandAndResult.versionValidate(versionCheckResult, desiredVersion)) .then(() => Promise.resolve(true)) .catch(() => Promise.reject( new Error('Version not installed of ' + objectName))); } return execAndCheck(commandAndResult.versionCheck, commandAndResult.checkStdErr, desiredVersion, commandAndResult.versionValidate); }
[ "function", "checkVersion", "(", "objectName", ",", "versionNumber", ")", "{", "const", "desiredVersion", "=", "versionNumber", "?", "versionNumber", ":", "versions", "[", "objectName", "]", ";", "const", "commandAndResult", "=", "commandsAndResults", "[", "objectName", "]", ";", "if", "(", "!", "commandAndResult", ")", "{", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "'Unrecognized objectName in commandsAndResults'", ")", ")", ";", "}", "if", "(", "!", "desiredVersion", ")", "{", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "'Unrecognized objectName in versions'", ")", ")", ";", "}", "if", "(", "commandAndResult", ".", "platform", "&&", "!", "commandAndResult", ".", "platform", ".", "includes", "(", "os", ".", "platform", "(", ")", ")", ")", "{", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "'Requested object is not supported on '", "+", "'this platform'", ")", ")", ";", "}", "if", "(", "typeof", "commandAndResult", ".", "versionCheck", "===", "'function'", ")", "{", "return", "promiseTry", "(", "commandAndResult", ".", "versionCheck", ")", ".", "catch", "(", "(", ")", "=>", "Promise", ".", "reject", "(", "new", "Error", "(", "'Version Check failed on '", "+", "objectName", ")", ")", ")", ".", "then", "(", "(", "versionCheckResult", ")", "=>", "commandAndResult", ".", "versionValidate", "(", "versionCheckResult", ",", "desiredVersion", ")", ")", ".", "then", "(", "(", ")", "=>", "Promise", ".", "resolve", "(", "true", ")", ")", ".", "catch", "(", "(", ")", "=>", "Promise", ".", "reject", "(", "new", "Error", "(", "'Version not installed of '", "+", "objectName", ")", ")", ")", ";", "}", "return", "execAndCheck", "(", "commandAndResult", ".", "versionCheck", ",", "commandAndResult", ".", "checkStdErr", ",", "desiredVersion", ",", "commandAndResult", ".", "versionValidate", ")", ";", "}" ]
Checks if the named object is installed with the named version, if any. If versionNumber isn't given then we default to checking the versions global object. @param {string} objectName Name of the object to validate @param {string} [versionNumber] An optional string specifying the desired version. If omitted we will check the versions structure. @returns {Promise<Error|boolean>} If the desired object is found at the desired version then a resolve will be returned set to true. Otherwise an error will be returned specifying what went wrong.
[ "Checks", "if", "the", "named", "object", "is", "installed", "with", "the", "named", "version", "if", "any", ".", "If", "versionNumber", "isn", "t", "given", "then", "we", "default", "to", "checking", "the", "versions", "global", "object", "." ]
0496da88a125a871d2ebff39359fbbf8ba01fd8f
https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/install/validateBuildEnvironment.js#L266-L296
train
thaliproject/Thali_CordovaPlugin
thali/install/SSDPReplacer/hook.js
findFirstFile
function findFirstFile (name, rootDir) { return new Promise(function (resolve, reject) { var resultPath; function end() { if (resultPath) { resolve(resultPath); } else { reject(new Error( format('file is not found, name: \'%s\'', name) )); } } var finder = findit(rootDir) .on('file', function (path) { // We can receive here 'path': 'a/b/my-file', 'a/b/bad-my-file', // 'my-file', 'bad-my-file'. // Both 'a/b/my-file' and 'my-file' should be valid. if (path === name || endsWith(path, '/' + name)) { resultPath = path; finder.stop(); } }) .on('error', function (error) { reject(new Error(error)); }) .on('stop', end) .on('end', end); }) .catch(function (error) { console.error( 'finder failed, error: \'%s\', stack: \'%s\'', error.toString(), error.stack ); return Promise.reject(error); }); }
javascript
function findFirstFile (name, rootDir) { return new Promise(function (resolve, reject) { var resultPath; function end() { if (resultPath) { resolve(resultPath); } else { reject(new Error( format('file is not found, name: \'%s\'', name) )); } } var finder = findit(rootDir) .on('file', function (path) { // We can receive here 'path': 'a/b/my-file', 'a/b/bad-my-file', // 'my-file', 'bad-my-file'. // Both 'a/b/my-file' and 'my-file' should be valid. if (path === name || endsWith(path, '/' + name)) { resultPath = path; finder.stop(); } }) .on('error', function (error) { reject(new Error(error)); }) .on('stop', end) .on('end', end); }) .catch(function (error) { console.error( 'finder failed, error: \'%s\', stack: \'%s\'', error.toString(), error.stack ); return Promise.reject(error); }); }
[ "function", "findFirstFile", "(", "name", ",", "rootDir", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "resultPath", ";", "function", "end", "(", ")", "{", "if", "(", "resultPath", ")", "{", "resolve", "(", "resultPath", ")", ";", "}", "else", "{", "reject", "(", "new", "Error", "(", "format", "(", "'file is not found, name: \\'%s\\''", ",", "\\'", ")", ")", ")", ";", "}", "}", "\\'", "}", ")", ".", "name", "var", "finder", "=", "findit", "(", "rootDir", ")", ".", "on", "(", "'file'", ",", "function", "(", "path", ")", "{", "if", "(", "path", "===", "name", "||", "endsWith", "(", "path", ",", "'/'", "+", "name", ")", ")", "{", "resultPath", "=", "path", ";", "finder", ".", "stop", "(", ")", ";", "}", "}", ")", ".", "on", "(", "'error'", ",", "function", "(", "error", ")", "{", "reject", "(", "new", "Error", "(", "error", ")", ")", ";", "}", ")", ".", "on", "(", "'stop'", ",", "end", ")", ".", "on", "(", "'end'", ",", "end", ")", ";", ";", "}" ]
We want to find the first path that ends with 'name'.
[ "We", "want", "to", "find", "the", "first", "path", "that", "ends", "with", "name", "." ]
0496da88a125a871d2ebff39359fbbf8ba01fd8f
https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/install/SSDPReplacer/hook.js#L28-L65
train
thaliproject/Thali_CordovaPlugin
thali/NextGeneration/identityExchange/connectionTable.js
ConnectionTable
function ConnectionTable(thaliReplicationManager) { EventEmitter.call(this); var self = this; this.thaliReplicationManager = thaliReplicationManager; this.connectionTable = {}; this.connectionSuccessListener = function (successObject) { self.connectionTable[successObject.peerIdentifier] = { muxPort: successObject.muxPort, time: Date.now() }; self.emit(successObject.peerIdentifier, self.connectionTable[successObject.peerIdentifier]); }; thaliReplicationManager.on(ThaliReplicationManager.events.CONNECTION_SUCCESS, this.connectionSuccessListener); }
javascript
function ConnectionTable(thaliReplicationManager) { EventEmitter.call(this); var self = this; this.thaliReplicationManager = thaliReplicationManager; this.connectionTable = {}; this.connectionSuccessListener = function (successObject) { self.connectionTable[successObject.peerIdentifier] = { muxPort: successObject.muxPort, time: Date.now() }; self.emit(successObject.peerIdentifier, self.connectionTable[successObject.peerIdentifier]); }; thaliReplicationManager.on(ThaliReplicationManager.events.CONNECTION_SUCCESS, this.connectionSuccessListener); }
[ "function", "ConnectionTable", "(", "thaliReplicationManager", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "var", "self", "=", "this", ";", "this", ".", "thaliReplicationManager", "=", "thaliReplicationManager", ";", "this", ".", "connectionTable", "=", "{", "}", ";", "this", ".", "connectionSuccessListener", "=", "function", "(", "successObject", ")", "{", "self", ".", "connectionTable", "[", "successObject", ".", "peerIdentifier", "]", "=", "{", "muxPort", ":", "successObject", ".", "muxPort", ",", "time", ":", "Date", ".", "now", "(", ")", "}", ";", "self", ".", "emit", "(", "successObject", ".", "peerIdentifier", ",", "self", ".", "connectionTable", "[", "successObject", ".", "peerIdentifier", "]", ")", ";", "}", ";", "thaliReplicationManager", ".", "on", "(", "ThaliReplicationManager", ".", "events", ".", "CONNECTION_SUCCESS", ",", "this", ".", "connectionSuccessListener", ")", ";", "}" ]
A temporary hack to collect connectionSuccess events. Once we put in ACLs we won't need this hack anymore. @param thaliReplicationManager @constructor
[ "A", "temporary", "hack", "to", "collect", "connectionSuccess", "events", ".", "Once", "we", "put", "in", "ACLs", "we", "won", "t", "need", "this", "hack", "anymore", "." ]
0496da88a125a871d2ebff39359fbbf8ba01fd8f
https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/NextGeneration/identityExchange/connectionTable.js#L43-L57
train
thaliproject/Thali_CordovaPlugin
thali/NextGeneration/thaliMobile.js
start
function start (router, pskIdToSecret, networkType) { if (thaliMobileStates.started === true) { return Promise.reject(new Error('Call Stop!')); } thaliMobileStates.started = true; thaliMobileStates.networkType = networkType || global.NETWORK_TYPE || thaliMobileStates.networkType; return getWifiOrNativeMethodByNetworkType('start', thaliMobileStates.networkType)(router, pskIdToSecret) .then(function (result) { if (result.wifiResult === null && result.nativeResult === null) { return result; } return Promise.reject(result); }); }
javascript
function start (router, pskIdToSecret, networkType) { if (thaliMobileStates.started === true) { return Promise.reject(new Error('Call Stop!')); } thaliMobileStates.started = true; thaliMobileStates.networkType = networkType || global.NETWORK_TYPE || thaliMobileStates.networkType; return getWifiOrNativeMethodByNetworkType('start', thaliMobileStates.networkType)(router, pskIdToSecret) .then(function (result) { if (result.wifiResult === null && result.nativeResult === null) { return result; } return Promise.reject(result); }); }
[ "function", "start", "(", "router", ",", "pskIdToSecret", ",", "networkType", ")", "{", "if", "(", "thaliMobileStates", ".", "started", "===", "true", ")", "{", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "'Call Stop!'", ")", ")", ";", "}", "thaliMobileStates", ".", "started", "=", "true", ";", "thaliMobileStates", ".", "networkType", "=", "networkType", "||", "global", ".", "NETWORK_TYPE", "||", "thaliMobileStates", ".", "networkType", ";", "return", "getWifiOrNativeMethodByNetworkType", "(", "'start'", ",", "thaliMobileStates", ".", "networkType", ")", "(", "router", ",", "pskIdToSecret", ")", ".", "then", "(", "function", "(", "result", ")", "{", "if", "(", "result", ".", "wifiResult", "===", "null", "&&", "result", ".", "nativeResult", "===", "null", ")", "{", "return", "result", ";", "}", "return", "Promise", ".", "reject", "(", "result", ")", ";", "}", ")", ";", "}" ]
This object is our generic status wrapper that lets us return information about both WiFi and Native. @public @typedef {Object} combinedResult @property {?Error} wifiResult @property {?Error} nativeResult
[ "This", "object", "is", "our", "generic", "status", "wrapper", "that", "lets", "us", "return", "information", "about", "both", "WiFi", "and", "Native", "." ]
0496da88a125a871d2ebff39359fbbf8ba01fd8f
https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/NextGeneration/thaliMobile.js#L182-L198
train
thaliproject/Thali_CordovaPlugin
thali/install/cordova-hooks/android/after_plugin_install.js
function (appRoot) { var filePath = path.join(appRoot, 'platforms/android/src/io/jxcore/node/JXcoreExtension.java'); var content = fs.readFileSync(filePath, 'utf-8'); content = content.replace('lifeCycleMonitor.start();', 'lifeCycleMonitor.start();\n\t\tRegisterExecuteUT.Register();'); content = content.replace('package io.jxcore.node;', 'package io.jxcore.node;\nimport com.test.thalitest.RegisterExecuteUT;'); fs.writeFileSync(filePath, content, 'utf-8'); }
javascript
function (appRoot) { var filePath = path.join(appRoot, 'platforms/android/src/io/jxcore/node/JXcoreExtension.java'); var content = fs.readFileSync(filePath, 'utf-8'); content = content.replace('lifeCycleMonitor.start();', 'lifeCycleMonitor.start();\n\t\tRegisterExecuteUT.Register();'); content = content.replace('package io.jxcore.node;', 'package io.jxcore.node;\nimport com.test.thalitest.RegisterExecuteUT;'); fs.writeFileSync(filePath, content, 'utf-8'); }
[ "function", "(", "appRoot", ")", "{", "var", "filePath", "=", "path", ".", "join", "(", "appRoot", ",", "'platforms/android/src/io/jxcore/node/JXcoreExtension.java'", ")", ";", "var", "content", "=", "fs", ".", "readFileSync", "(", "filePath", ",", "'utf-8'", ")", ";", "content", "=", "content", ".", "replace", "(", "'lifeCycleMonitor.start();'", ",", "'lifeCycleMonitor.start();\\n\\t\\tRegisterExecuteUT.Register();'", ")", ";", "\\n", "\\t", "}" ]
Updates JXcoreExtension with a method which is used to register the native UT executor. We are doing it because we don't want to mess our production code with our test code so we create a function that dynamically adds method executing tests only when we are actually testing. @param {Object} appRoot
[ "Updates", "JXcoreExtension", "with", "a", "method", "which", "is", "used", "to", "register", "the", "native", "UT", "executor", ".", "We", "are", "doing", "it", "because", "we", "don", "t", "want", "to", "mess", "our", "production", "code", "with", "our", "test", "code", "so", "we", "create", "a", "function", "that", "dynamically", "adds", "method", "executing", "tests", "only", "when", "we", "are", "actually", "testing", "." ]
0496da88a125a871d2ebff39359fbbf8ba01fd8f
https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/install/cordova-hooks/android/after_plugin_install.js#L178-L188
train
thaliproject/Thali_CordovaPlugin
thali/NextGeneration/security/hkdf.js
HKDF
function HKDF(hashAlg, salt, ikm) { if (!(this instanceof HKDF)) { return new HKDF(hashAlg, salt, ikm); } this.hashAlg = hashAlg; // create the hash alg to see if it exists and get its length var hash = crypto.createHash(this.hashAlg); this.hashLength = hash.digest().length; this.salt = salt || zeros(this.hashLength); this.ikm = ikm; // now we compute the PRK var hmac = crypto.createHmac(this.hashAlg, this.salt); hmac.update(this.ikm); this.prk = hmac.digest(); }
javascript
function HKDF(hashAlg, salt, ikm) { if (!(this instanceof HKDF)) { return new HKDF(hashAlg, salt, ikm); } this.hashAlg = hashAlg; // create the hash alg to see if it exists and get its length var hash = crypto.createHash(this.hashAlg); this.hashLength = hash.digest().length; this.salt = salt || zeros(this.hashLength); this.ikm = ikm; // now we compute the PRK var hmac = crypto.createHmac(this.hashAlg, this.salt); hmac.update(this.ikm); this.prk = hmac.digest(); }
[ "function", "HKDF", "(", "hashAlg", ",", "salt", ",", "ikm", ")", "{", "if", "(", "!", "(", "this", "instanceof", "HKDF", ")", ")", "{", "return", "new", "HKDF", "(", "hashAlg", ",", "salt", ",", "ikm", ")", ";", "}", "this", ".", "hashAlg", "=", "hashAlg", ";", "var", "hash", "=", "crypto", ".", "createHash", "(", "this", ".", "hashAlg", ")", ";", "this", ".", "hashLength", "=", "hash", ".", "digest", "(", ")", ".", "length", ";", "this", ".", "salt", "=", "salt", "||", "zeros", "(", "this", ".", "hashLength", ")", ";", "this", ".", "ikm", "=", "ikm", ";", "var", "hmac", "=", "crypto", ".", "createHmac", "(", "this", ".", "hashAlg", ",", "this", ".", "salt", ")", ";", "hmac", ".", "update", "(", "this", ".", "ikm", ")", ";", "this", ".", "prk", "=", "hmac", ".", "digest", "(", ")", ";", "}" ]
ikm is initial keying material
[ "ikm", "is", "initial", "keying", "material" ]
0496da88a125a871d2ebff39359fbbf8ba01fd8f
https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/NextGeneration/security/hkdf.js#L32-L48
train
thaliproject/Thali_CordovaPlugin
thali/NextGeneration/notification/thaliNotificationBeacons.js
createPublicKeyHash
function createPublicKeyHash (ecdhPublicKey) { return crypto.createHash(module.exports.SHA256) .update(ecdhPublicKey) .digest() .slice(0, 16); }
javascript
function createPublicKeyHash (ecdhPublicKey) { return crypto.createHash(module.exports.SHA256) .update(ecdhPublicKey) .digest() .slice(0, 16); }
[ "function", "createPublicKeyHash", "(", "ecdhPublicKey", ")", "{", "return", "crypto", ".", "createHash", "(", "module", ".", "exports", ".", "SHA256", ")", ".", "update", "(", "ecdhPublicKey", ")", ".", "digest", "(", ")", ".", "slice", "(", "0", ",", "16", ")", ";", "}" ]
Creates a 16 byte hash of a public key. We choose 16 bytes as large enough to prevent accidentally collisions but small enough not to eat up excess space in a beacon. @param {Buffer} ecdhPublicKey The buffer representing the ECDH's public key. @returns {Buffer}
[ "Creates", "a", "16", "byte", "hash", "of", "a", "public", "key", "." ]
0496da88a125a871d2ebff39359fbbf8ba01fd8f
https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/NextGeneration/notification/thaliNotificationBeacons.js#L121-L126
train
thaliproject/Thali_CordovaPlugin
thali/NextGeneration/notification/thaliNotificationBeacons.js
generatePreambleAndBeacons
function generatePreambleAndBeacons (publicKeysToNotify, ecdhForLocalDevice, millisecondsUntilExpiration) { if (publicKeysToNotify == null) { throw new Error('publicKeysToNotify cannot be null'); } if (ecdhForLocalDevice == null) { throw new Error('ecdhForLocalDevice cannot be null'); } if (millisecondsUntilExpiration <= 0 || millisecondsUntilExpiration > module.exports.ONE_DAY) { throw new Error('millisecondsUntilExpiration must be > 0 & < ' + module.exports.ONE_DAY); } if (publicKeysToNotify.length === 0) { return null; } var beacons = []; var ke = crypto.createECDH(thaliConfig.BEACON_CURVE); // Generate preamble var pubKe = ke.generateKeys(); // We fuzz the expiration by adding on a random number that fits in // an unsigned 8 bit integer. var expiration = Date.now() + millisecondsUntilExpiration + crypto.randomBytes(1).readUInt8(0); var expirationLong = Long.fromNumber(expiration); var expirationBuffer = new Buffer(module.exports.LONG_SIZE); expirationBuffer.writeInt32BE(expirationLong.high, 0); expirationBuffer.writeInt32BE(expirationLong.low, 4); beacons.push(Buffer.concat([pubKe, expirationBuffer])); // UnencryptedKeyId = SHA256(Kx.public().encode()).first(16) var unencryptedKeyId = createPublicKeyHash(ecdhForLocalDevice.getPublicKey()); publicKeysToNotify.forEach(function (pubKy) { // Sxy = ECDH(Kx.private(), PubKy) var sxy = ecdhForLocalDevice.computeSecret(pubKy); // HKxy = HKDF(SHA256, Sxy, Expiration, 32) var hkxy = HKDF(module.exports.SHA256, sxy, expirationBuffer) .derive('', module.exports.SHA256_HMAC_KEY_SIZE); // BeaconHmac = HMAC(SHA256, HKxy, Expiration).first(16) var beaconHmac = crypto.createHmac(module.exports.SHA256, hkxy) .update(expirationBuffer) .digest() .slice(0, module.exports.TRUNCATED_HASH_SIZE); // Sey = ECDH(Ke.private(), PubKy) var sey = ke.computeSecret(pubKy); // hkey = HKDF(SHA256, Sey, Expiration, 16) var hkey = HKDF(module.exports.SHA256, sey, expirationBuffer) .derive('', module.exports.AES_128_KEY_SIZE); // beacons.append(AESEncrypt(GCM, HKey, 0, 128, UnencryptedKeyId) + // BeaconHmac) var aes = crypto.createCipher(module.exports.GCM, hkey); beacons.push(Buffer.concat([ Buffer.concat([aes.update(unencryptedKeyId), aes.final()]), beaconHmac ])); }); return Buffer.concat(beacons); }
javascript
function generatePreambleAndBeacons (publicKeysToNotify, ecdhForLocalDevice, millisecondsUntilExpiration) { if (publicKeysToNotify == null) { throw new Error('publicKeysToNotify cannot be null'); } if (ecdhForLocalDevice == null) { throw new Error('ecdhForLocalDevice cannot be null'); } if (millisecondsUntilExpiration <= 0 || millisecondsUntilExpiration > module.exports.ONE_DAY) { throw new Error('millisecondsUntilExpiration must be > 0 & < ' + module.exports.ONE_DAY); } if (publicKeysToNotify.length === 0) { return null; } var beacons = []; var ke = crypto.createECDH(thaliConfig.BEACON_CURVE); // Generate preamble var pubKe = ke.generateKeys(); // We fuzz the expiration by adding on a random number that fits in // an unsigned 8 bit integer. var expiration = Date.now() + millisecondsUntilExpiration + crypto.randomBytes(1).readUInt8(0); var expirationLong = Long.fromNumber(expiration); var expirationBuffer = new Buffer(module.exports.LONG_SIZE); expirationBuffer.writeInt32BE(expirationLong.high, 0); expirationBuffer.writeInt32BE(expirationLong.low, 4); beacons.push(Buffer.concat([pubKe, expirationBuffer])); // UnencryptedKeyId = SHA256(Kx.public().encode()).first(16) var unencryptedKeyId = createPublicKeyHash(ecdhForLocalDevice.getPublicKey()); publicKeysToNotify.forEach(function (pubKy) { // Sxy = ECDH(Kx.private(), PubKy) var sxy = ecdhForLocalDevice.computeSecret(pubKy); // HKxy = HKDF(SHA256, Sxy, Expiration, 32) var hkxy = HKDF(module.exports.SHA256, sxy, expirationBuffer) .derive('', module.exports.SHA256_HMAC_KEY_SIZE); // BeaconHmac = HMAC(SHA256, HKxy, Expiration).first(16) var beaconHmac = crypto.createHmac(module.exports.SHA256, hkxy) .update(expirationBuffer) .digest() .slice(0, module.exports.TRUNCATED_HASH_SIZE); // Sey = ECDH(Ke.private(), PubKy) var sey = ke.computeSecret(pubKy); // hkey = HKDF(SHA256, Sey, Expiration, 16) var hkey = HKDF(module.exports.SHA256, sey, expirationBuffer) .derive('', module.exports.AES_128_KEY_SIZE); // beacons.append(AESEncrypt(GCM, HKey, 0, 128, UnencryptedKeyId) + // BeaconHmac) var aes = crypto.createCipher(module.exports.GCM, hkey); beacons.push(Buffer.concat([ Buffer.concat([aes.update(unencryptedKeyId), aes.final()]), beaconHmac ])); }); return Buffer.concat(beacons); }
[ "function", "generatePreambleAndBeacons", "(", "publicKeysToNotify", ",", "ecdhForLocalDevice", ",", "millisecondsUntilExpiration", ")", "{", "if", "(", "publicKeysToNotify", "==", "null", ")", "{", "throw", "new", "Error", "(", "'publicKeysToNotify cannot be null'", ")", ";", "}", "if", "(", "ecdhForLocalDevice", "==", "null", ")", "{", "throw", "new", "Error", "(", "'ecdhForLocalDevice cannot be null'", ")", ";", "}", "if", "(", "millisecondsUntilExpiration", "<=", "0", "||", "millisecondsUntilExpiration", ">", "module", ".", "exports", ".", "ONE_DAY", ")", "{", "throw", "new", "Error", "(", "'millisecondsUntilExpiration must be > 0 & < '", "+", "module", ".", "exports", ".", "ONE_DAY", ")", ";", "}", "if", "(", "publicKeysToNotify", ".", "length", "===", "0", ")", "{", "return", "null", ";", "}", "var", "beacons", "=", "[", "]", ";", "var", "ke", "=", "crypto", ".", "createECDH", "(", "thaliConfig", ".", "BEACON_CURVE", ")", ";", "var", "pubKe", "=", "ke", ".", "generateKeys", "(", ")", ";", "var", "expiration", "=", "Date", ".", "now", "(", ")", "+", "millisecondsUntilExpiration", "+", "crypto", ".", "randomBytes", "(", "1", ")", ".", "readUInt8", "(", "0", ")", ";", "var", "expirationLong", "=", "Long", ".", "fromNumber", "(", "expiration", ")", ";", "var", "expirationBuffer", "=", "new", "Buffer", "(", "module", ".", "exports", ".", "LONG_SIZE", ")", ";", "expirationBuffer", ".", "writeInt32BE", "(", "expirationLong", ".", "high", ",", "0", ")", ";", "expirationBuffer", ".", "writeInt32BE", "(", "expirationLong", ".", "low", ",", "4", ")", ";", "beacons", ".", "push", "(", "Buffer", ".", "concat", "(", "[", "pubKe", ",", "expirationBuffer", "]", ")", ")", ";", "var", "unencryptedKeyId", "=", "createPublicKeyHash", "(", "ecdhForLocalDevice", ".", "getPublicKey", "(", ")", ")", ";", "publicKeysToNotify", ".", "forEach", "(", "function", "(", "pubKy", ")", "{", "var", "sxy", "=", "ecdhForLocalDevice", ".", "computeSecret", "(", "pubKy", ")", ";", "var", "hkxy", "=", "HKDF", "(", "module", ".", "exports", ".", "SHA256", ",", "sxy", ",", "expirationBuffer", ")", ".", "derive", "(", "''", ",", "module", ".", "exports", ".", "SHA256_HMAC_KEY_SIZE", ")", ";", "var", "beaconHmac", "=", "crypto", ".", "createHmac", "(", "module", ".", "exports", ".", "SHA256", ",", "hkxy", ")", ".", "update", "(", "expirationBuffer", ")", ".", "digest", "(", ")", ".", "slice", "(", "0", ",", "module", ".", "exports", ".", "TRUNCATED_HASH_SIZE", ")", ";", "var", "sey", "=", "ke", ".", "computeSecret", "(", "pubKy", ")", ";", "var", "hkey", "=", "HKDF", "(", "module", ".", "exports", ".", "SHA256", ",", "sey", ",", "expirationBuffer", ")", ".", "derive", "(", "''", ",", "module", ".", "exports", ".", "AES_128_KEY_SIZE", ")", ";", "var", "aes", "=", "crypto", ".", "createCipher", "(", "module", ".", "exports", ".", "GCM", ",", "hkey", ")", ";", "beacons", ".", "push", "(", "Buffer", ".", "concat", "(", "[", "Buffer", ".", "concat", "(", "[", "aes", ".", "update", "(", "unencryptedKeyId", ")", ",", "aes", ".", "final", "(", ")", "]", ")", ",", "beaconHmac", "]", ")", ")", ";", "}", ")", ";", "return", "Buffer", ".", "concat", "(", "beacons", ")", ";", "}" ]
This function will generate a buffer containing the notification preamble and beacons for the given set of public keys using the supplied private key and set to the specified seconds until expiration. @param {Buffer[]} publicKeysToNotify - An array of buffers holding ECDH public keys. @param {ECDH} ecdhForLocalDevice - A Crypto.ECDH object initialized with the local device's public and private keys @param {number} millisecondsUntilExpiration - The number of milliseconds into the future after which the beacons should expire. Note that this value will be fuzzed as previously described. @returns {?Buffer} - A buffer containing the serialized preamble and beacons or null if there are no beacons to generate
[ "This", "function", "will", "generate", "a", "buffer", "containing", "the", "notification", "preamble", "and", "beacons", "for", "the", "given", "set", "of", "public", "keys", "using", "the", "supplied", "private", "key", "and", "set", "to", "the", "specified", "seconds", "until", "expiration", "." ]
0496da88a125a871d2ebff39359fbbf8ba01fd8f
https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/NextGeneration/notification/thaliNotificationBeacons.js#L144-L216
train
thaliproject/Thali_CordovaPlugin
thali/NextGeneration/notification/thaliNotificationBeacons.js
generatePskSecret
function generatePskSecret(ecdhForLocalDevice, remotePeerPublicKey, pskIdentityField) { var sxy = ecdhForLocalDevice.computeSecret(remotePeerPublicKey); return HKDF(module.exports.SHA256, sxy, pskIdentityField) .derive('', module.exports.AES_256_KEY_SIZE); }
javascript
function generatePskSecret(ecdhForLocalDevice, remotePeerPublicKey, pskIdentityField) { var sxy = ecdhForLocalDevice.computeSecret(remotePeerPublicKey); return HKDF(module.exports.SHA256, sxy, pskIdentityField) .derive('', module.exports.AES_256_KEY_SIZE); }
[ "function", "generatePskSecret", "(", "ecdhForLocalDevice", ",", "remotePeerPublicKey", ",", "pskIdentityField", ")", "{", "var", "sxy", "=", "ecdhForLocalDevice", ".", "computeSecret", "(", "remotePeerPublicKey", ")", ";", "return", "HKDF", "(", "module", ".", "exports", ".", "SHA256", ",", "sxy", ",", "pskIdentityField", ")", ".", "derive", "(", "''", ",", "module", ".", "exports", ".", "AES_256_KEY_SIZE", ")", ";", "}" ]
Generates a PSK secret between the local device and a remote peer. @param {ECDH} ecdhForLocalDevice @param {Buffer} remotePeerPublicKey @param {string} pskIdentityField @returns {Buffer}
[ "Generates", "a", "PSK", "secret", "between", "the", "local", "device", "and", "a", "remote", "peer", "." ]
0496da88a125a871d2ebff39359fbbf8ba01fd8f
https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/NextGeneration/notification/thaliNotificationBeacons.js#L406-L411
train
thaliproject/Thali_CordovaPlugin
thali/NextGeneration/notification/thaliNotificationBeacons.js
generatePskSecrets
function generatePskSecrets(publicKeysToNotify, ecdhForLocalDevice, beaconStreamWithPreAmble) { var preAmbleSizeInBytes = module.exports.PUBLIC_KEY_SIZE + module.exports.EXPIRATION_SIZE; var preAmble = beaconStreamWithPreAmble.slice(0, preAmbleSizeInBytes); var beaconStreamNoPreAmble = beaconStreamWithPreAmble.slice(preAmbleSizeInBytes); var beacons = []; for (var i = 0; i < beaconStreamNoPreAmble.length; i += module.exports.BEACON_SIZE) { beacons.push( beaconStreamNoPreAmble.slice(i, i + module.exports.BEACON_SIZE)); } assert(beacons.length === publicKeysToNotify.length, 'We should have the' + 'same number of beacons as public keys to notify'); var pskMap = {}; for (i = 0; i < publicKeysToNotify.length; ++i) { var pskIdentityField = generatePskIdentityField(preAmble, beacons[i]); var pskSecret = generatePskSecret(ecdhForLocalDevice, publicKeysToNotify[i], pskIdentityField); pskMap[pskIdentityField] = { publicKey: publicKeysToNotify[i], pskSecret: pskSecret }; } return pskMap; }
javascript
function generatePskSecrets(publicKeysToNotify, ecdhForLocalDevice, beaconStreamWithPreAmble) { var preAmbleSizeInBytes = module.exports.PUBLIC_KEY_SIZE + module.exports.EXPIRATION_SIZE; var preAmble = beaconStreamWithPreAmble.slice(0, preAmbleSizeInBytes); var beaconStreamNoPreAmble = beaconStreamWithPreAmble.slice(preAmbleSizeInBytes); var beacons = []; for (var i = 0; i < beaconStreamNoPreAmble.length; i += module.exports.BEACON_SIZE) { beacons.push( beaconStreamNoPreAmble.slice(i, i + module.exports.BEACON_SIZE)); } assert(beacons.length === publicKeysToNotify.length, 'We should have the' + 'same number of beacons as public keys to notify'); var pskMap = {}; for (i = 0; i < publicKeysToNotify.length; ++i) { var pskIdentityField = generatePskIdentityField(preAmble, beacons[i]); var pskSecret = generatePskSecret(ecdhForLocalDevice, publicKeysToNotify[i], pskIdentityField); pskMap[pskIdentityField] = { publicKey: publicKeysToNotify[i], pskSecret: pskSecret }; } return pskMap; }
[ "function", "generatePskSecrets", "(", "publicKeysToNotify", ",", "ecdhForLocalDevice", ",", "beaconStreamWithPreAmble", ")", "{", "var", "preAmbleSizeInBytes", "=", "module", ".", "exports", ".", "PUBLIC_KEY_SIZE", "+", "module", ".", "exports", ".", "EXPIRATION_SIZE", ";", "var", "preAmble", "=", "beaconStreamWithPreAmble", ".", "slice", "(", "0", ",", "preAmbleSizeInBytes", ")", ";", "var", "beaconStreamNoPreAmble", "=", "beaconStreamWithPreAmble", ".", "slice", "(", "preAmbleSizeInBytes", ")", ";", "var", "beacons", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "beaconStreamNoPreAmble", ".", "length", ";", "i", "+=", "module", ".", "exports", ".", "BEACON_SIZE", ")", "{", "beacons", ".", "push", "(", "beaconStreamNoPreAmble", ".", "slice", "(", "i", ",", "i", "+", "module", ".", "exports", ".", "BEACON_SIZE", ")", ")", ";", "}", "assert", "(", "beacons", ".", "length", "===", "publicKeysToNotify", ".", "length", ",", "'We should have the'", "+", "'same number of beacons as public keys to notify'", ")", ";", "var", "pskMap", "=", "{", "}", ";", "for", "(", "i", "=", "0", ";", "i", "<", "publicKeysToNotify", ".", "length", ";", "++", "i", ")", "{", "var", "pskIdentityField", "=", "generatePskIdentityField", "(", "preAmble", ",", "beacons", "[", "i", "]", ")", ";", "var", "pskSecret", "=", "generatePskSecret", "(", "ecdhForLocalDevice", ",", "publicKeysToNotify", "[", "i", "]", ",", "pskIdentityField", ")", ";", "pskMap", "[", "pskIdentityField", "]", "=", "{", "publicKey", ":", "publicKeysToNotify", "[", "i", "]", ",", "pskSecret", ":", "pskSecret", "}", ";", "}", "return", "pskMap", ";", "}" ]
A dictionary whose key is the identity string sent over TLS and whose value is a keyAndSecret specifying what publicKey this identity is associated with and what secret it needs to provide. @public @typedef {Object.<string, keyAndSecret>} pskMap This function takes a list of public keys and the device's ECDH private key along with a beacon stream with preamble that was generated using those public keys. The function requires that the beacon values in the beacon stream MUST be in the same order as the keys listed in the publicKeysToNotify array. The code will then generate Sxy as given in http://thaliproject.org/PresenceProtocolBindings/#transferring-from-notification-beacon-to-tls and then feed that to HKDF using the the PSKIdentity value which is defined in the above as the pre-amble plus the individual beacon value for the associated public key. This means we have to parse the beacon stream to pull out the preamble along with the specific associated beacon and then combine them together into a single buffer that is then base64'd using the URL safe base64 scheme. This is then fed to HKDF as defined in the link above which produces the value that will be used as the secret. This function will then wrap up all of this into a dictionary whose key is the base64 url safe'd pre-amble + beacon value and who value is the secret along with the associated publicKey. @param {Buffer[]} publicKeysToNotify - An array of buffers holding ECDH public keys. @param {ECDH} ecdhForLocalDevice - A Crypto.ECDH object initialized with the local device's public and private keys @param {Buffer} beaconStreamWithPreAmble - A buffer stream containing the preamble and beacons @returns {pskMap|Error}
[ "A", "dictionary", "whose", "key", "is", "the", "identity", "string", "sent", "over", "TLS", "and", "whose", "value", "is", "a", "keyAndSecret", "specifying", "what", "publicKey", "this", "identity", "is", "associated", "with", "and", "what", "secret", "it", "needs", "to", "provide", "." ]
0496da88a125a871d2ebff39359fbbf8ba01fd8f
https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/NextGeneration/notification/thaliNotificationBeacons.js#L461-L492
train
thaliproject/Thali_CordovaPlugin
thali/NextGeneration/thaliPeerPool/thaliPeerAction.js
PeerAction
function PeerAction (peerIdentifier, connectionType, actionType, pskIdentity, pskKey) { EventEmitter.call(this); this._peerIdentifier = peerIdentifier; this._connectionType = connectionType; this._actionType = actionType; this._pskIdentity = pskIdentity; this._pskKey = pskKey; this._actionState = PeerAction.actionState.CREATED; this._id = peerActionCounter; ++peerActionCounter; }
javascript
function PeerAction (peerIdentifier, connectionType, actionType, pskIdentity, pskKey) { EventEmitter.call(this); this._peerIdentifier = peerIdentifier; this._connectionType = connectionType; this._actionType = actionType; this._pskIdentity = pskIdentity; this._pskKey = pskKey; this._actionState = PeerAction.actionState.CREATED; this._id = peerActionCounter; ++peerActionCounter; }
[ "function", "PeerAction", "(", "peerIdentifier", ",", "connectionType", ",", "actionType", ",", "pskIdentity", ",", "pskKey", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "_peerIdentifier", "=", "peerIdentifier", ";", "this", ".", "_connectionType", "=", "connectionType", ";", "this", ".", "_actionType", "=", "actionType", ";", "this", ".", "_pskIdentity", "=", "pskIdentity", ";", "this", ".", "_pskKey", "=", "pskKey", ";", "this", ".", "_actionState", "=", "PeerAction", ".", "actionState", ".", "CREATED", ";", "this", ".", "_id", "=", "peerActionCounter", ";", "++", "peerActionCounter", ";", "}" ]
This event is emitted synchronously when action state is changed to KILLED. @event killed @public An action that has been given to the pool to manage. When an action is created its state MUST be CREATED. BugBug: In a sane world we would have limits on how long an action can run and we would even set up those limits as a config item. But for now we let each action own the stage for as long as it would like. @public @interface PeerAction @constructor @fires event:killed @fires event:started @param {string} peerIdentifier @param {module:ThaliMobileNativeWrapper.connectionTypes} connectionType @param {string} actionType @param {string} pskIdentity @param {Buffer} pskKey
[ "This", "event", "is", "emitted", "synchronously", "when", "action", "state", "is", "changed", "to", "KILLED", "." ]
0496da88a125a871d2ebff39359fbbf8ba01fd8f
https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/NextGeneration/thaliPeerPool/thaliPeerAction.js#L55-L67
train
PeculiarVentures/xadesjs
examples/html/src/helper.js
BrowserInfo
function BrowserInfo() { var res = { name: "", version: "" }; var userAgent = self.navigator.userAgent; var reg; if (reg = /edge\/([\d\.]+)/i.exec(userAgent)) { res.name = Browser.Edge; res.version = reg[1]; } else if (/msie/i.test(userAgent)) { res.name = Browser.IE; res.version = /msie ([\d\.]+)/i.exec(userAgent)[1]; } else if (/Trident/i.test(userAgent)) { res.name = Browser.IE; res.version = /rv:([\d\.]+)/i.exec(userAgent)[1]; } else if (/chrome/i.test(userAgent)) { res.name = Browser.Chrome; res.version = /chrome\/([\d\.]+)/i.exec(userAgent)[1]; } else if (/safari/i.test(userAgent)) { res.name = Browser.Safari; res.version = /([\d\.]+) safari/i.exec(userAgent)[1]; } else if (/firefox/i.test(userAgent)) { res.name = Browser.Firefox; res.version = /firefox\/([\d\.]+)/i.exec(userAgent)[1]; } return res; }
javascript
function BrowserInfo() { var res = { name: "", version: "" }; var userAgent = self.navigator.userAgent; var reg; if (reg = /edge\/([\d\.]+)/i.exec(userAgent)) { res.name = Browser.Edge; res.version = reg[1]; } else if (/msie/i.test(userAgent)) { res.name = Browser.IE; res.version = /msie ([\d\.]+)/i.exec(userAgent)[1]; } else if (/Trident/i.test(userAgent)) { res.name = Browser.IE; res.version = /rv:([\d\.]+)/i.exec(userAgent)[1]; } else if (/chrome/i.test(userAgent)) { res.name = Browser.Chrome; res.version = /chrome\/([\d\.]+)/i.exec(userAgent)[1]; } else if (/safari/i.test(userAgent)) { res.name = Browser.Safari; res.version = /([\d\.]+) safari/i.exec(userAgent)[1]; } else if (/firefox/i.test(userAgent)) { res.name = Browser.Firefox; res.version = /firefox\/([\d\.]+)/i.exec(userAgent)[1]; } return res; }
[ "function", "BrowserInfo", "(", ")", "{", "var", "res", "=", "{", "name", ":", "\"\"", ",", "version", ":", "\"\"", "}", ";", "var", "userAgent", "=", "self", ".", "navigator", ".", "userAgent", ";", "var", "reg", ";", "if", "(", "reg", "=", "/", "edge\\/([\\d\\.]+)", "/", "i", ".", "exec", "(", "userAgent", ")", ")", "{", "res", ".", "name", "=", "Browser", ".", "Edge", ";", "res", ".", "version", "=", "reg", "[", "1", "]", ";", "}", "else", "if", "(", "/", "msie", "/", "i", ".", "test", "(", "userAgent", ")", ")", "{", "res", ".", "name", "=", "Browser", ".", "IE", ";", "res", ".", "version", "=", "/", "msie ([\\d\\.]+)", "/", "i", ".", "exec", "(", "userAgent", ")", "[", "1", "]", ";", "}", "else", "if", "(", "/", "Trident", "/", "i", ".", "test", "(", "userAgent", ")", ")", "{", "res", ".", "name", "=", "Browser", ".", "IE", ";", "res", ".", "version", "=", "/", "rv:([\\d\\.]+)", "/", "i", ".", "exec", "(", "userAgent", ")", "[", "1", "]", ";", "}", "else", "if", "(", "/", "chrome", "/", "i", ".", "test", "(", "userAgent", ")", ")", "{", "res", ".", "name", "=", "Browser", ".", "Chrome", ";", "res", ".", "version", "=", "/", "chrome\\/([\\d\\.]+)", "/", "i", ".", "exec", "(", "userAgent", ")", "[", "1", "]", ";", "}", "else", "if", "(", "/", "safari", "/", "i", ".", "test", "(", "userAgent", ")", ")", "{", "res", ".", "name", "=", "Browser", ".", "Safari", ";", "res", ".", "version", "=", "/", "([\\d\\.]+) safari", "/", "i", ".", "exec", "(", "userAgent", ")", "[", "1", "]", ";", "}", "else", "if", "(", "/", "firefox", "/", "i", ".", "test", "(", "userAgent", ")", ")", "{", "res", ".", "name", "=", "Browser", ".", "Firefox", ";", "res", ".", "version", "=", "/", "firefox\\/([\\d\\.]+)", "/", "i", ".", "exec", "(", "userAgent", ")", "[", "1", "]", ";", "}", "return", "res", ";", "}" ]
Returns info about browser
[ "Returns", "info", "about", "browser" ]
c35e3895868bdcfb52e2b29685efc50c877cd1f1
https://github.com/PeculiarVentures/xadesjs/blob/c35e3895868bdcfb52e2b29685efc50c877cd1f1/examples/html/src/helper.js#L11-L43
train
freeCodeCamp/curriculum
unpack.js
createUnpackedBundle
function createUnpackedBundle() { fs.mkdirp(unpackedDir, err => { if (err && err.code !== 'EEXIST') { console.log(err); throw err; } let unpackedFile = path.join(__dirname, 'unpacked.js'); let b = browserify(unpackedFile).bundle(); b.on('error', console.error); let unpackedBundleFile = path.join(unpackedDir, 'unpacked-bundle.js'); const bundleFileStream = fs.createWriteStream(unpackedBundleFile); bundleFileStream.on('finish', () => { console.log('Wrote bundled JS into ' + unpackedBundleFile); }); bundleFileStream.on('pipe', () => { console.log('Writing bundled JS...'); }); bundleFileStream.on('error', console.error); b.pipe(bundleFileStream); // bundleFileStream.end(); // do not do this prematurely! }); }
javascript
function createUnpackedBundle() { fs.mkdirp(unpackedDir, err => { if (err && err.code !== 'EEXIST') { console.log(err); throw err; } let unpackedFile = path.join(__dirname, 'unpacked.js'); let b = browserify(unpackedFile).bundle(); b.on('error', console.error); let unpackedBundleFile = path.join(unpackedDir, 'unpacked-bundle.js'); const bundleFileStream = fs.createWriteStream(unpackedBundleFile); bundleFileStream.on('finish', () => { console.log('Wrote bundled JS into ' + unpackedBundleFile); }); bundleFileStream.on('pipe', () => { console.log('Writing bundled JS...'); }); bundleFileStream.on('error', console.error); b.pipe(bundleFileStream); // bundleFileStream.end(); // do not do this prematurely! }); }
[ "function", "createUnpackedBundle", "(", ")", "{", "fs", ".", "mkdirp", "(", "unpackedDir", ",", "err", "=>", "{", "if", "(", "err", "&&", "err", ".", "code", "!==", "'EEXIST'", ")", "{", "console", ".", "log", "(", "err", ")", ";", "throw", "err", ";", "}", "let", "unpackedFile", "=", "path", ".", "join", "(", "__dirname", ",", "'unpacked.js'", ")", ";", "let", "b", "=", "browserify", "(", "unpackedFile", ")", ".", "bundle", "(", ")", ";", "b", ".", "on", "(", "'error'", ",", "console", ".", "error", ")", ";", "let", "unpackedBundleFile", "=", "path", ".", "join", "(", "unpackedDir", ",", "'unpacked-bundle.js'", ")", ";", "const", "bundleFileStream", "=", "fs", ".", "createWriteStream", "(", "unpackedBundleFile", ")", ";", "bundleFileStream", ".", "on", "(", "'finish'", ",", "(", ")", "=>", "{", "console", ".", "log", "(", "'Wrote bundled JS into '", "+", "unpackedBundleFile", ")", ";", "}", ")", ";", "bundleFileStream", ".", "on", "(", "'pipe'", ",", "(", ")", "=>", "{", "console", ".", "log", "(", "'Writing bundled JS...'", ")", ";", "}", ")", ";", "bundleFileStream", ".", "on", "(", "'error'", ",", "console", ".", "error", ")", ";", "b", ".", "pipe", "(", "bundleFileStream", ")", ";", "}", ")", ";", "}" ]
bundle up the test-running JS
[ "bundle", "up", "the", "test", "-", "running", "JS" ]
9c5686cbb700fb7c1443aee81592096f3c61b944
https://github.com/freeCodeCamp/curriculum/blob/9c5686cbb700fb7c1443aee81592096f3c61b944/unpack.js#L20-L42
train
jorgebay/node-cassandra-cql
lib/types.js
function (query, params, stringifier) { if (!query || !query.length || !params) { return query; } if (!stringifier) { stringifier = function (a) {return a.toString()}; } var parts = []; var isLiteral = false; var lastIndex = 0; var paramsCounter = 0; for (var i = 0; i < query.length; i++) { var char = query.charAt(i); if (char === "'" && query.charAt(i-1) !== '\\') { //opening or closing quotes in a literal value of the query isLiteral = !isLiteral; } if (!isLiteral && char === '?') { //is a placeholder parts.push(query.substring(lastIndex, i)); parts.push(stringifier(params[paramsCounter++])); lastIndex = i+1; } } parts.push(query.substring(lastIndex)); return parts.join(''); }
javascript
function (query, params, stringifier) { if (!query || !query.length || !params) { return query; } if (!stringifier) { stringifier = function (a) {return a.toString()}; } var parts = []; var isLiteral = false; var lastIndex = 0; var paramsCounter = 0; for (var i = 0; i < query.length; i++) { var char = query.charAt(i); if (char === "'" && query.charAt(i-1) !== '\\') { //opening or closing quotes in a literal value of the query isLiteral = !isLiteral; } if (!isLiteral && char === '?') { //is a placeholder parts.push(query.substring(lastIndex, i)); parts.push(stringifier(params[paramsCounter++])); lastIndex = i+1; } } parts.push(query.substring(lastIndex)); return parts.join(''); }
[ "function", "(", "query", ",", "params", ",", "stringifier", ")", "{", "if", "(", "!", "query", "||", "!", "query", ".", "length", "||", "!", "params", ")", "{", "return", "query", ";", "}", "if", "(", "!", "stringifier", ")", "{", "stringifier", "=", "function", "(", "a", ")", "{", "return", "a", ".", "toString", "(", ")", "}", ";", "}", "var", "parts", "=", "[", "]", ";", "var", "isLiteral", "=", "false", ";", "var", "lastIndex", "=", "0", ";", "var", "paramsCounter", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "query", ".", "length", ";", "i", "++", ")", "{", "var", "char", "=", "query", ".", "charAt", "(", "i", ")", ";", "if", "(", "char", "===", "\"'\"", "&&", "query", ".", "charAt", "(", "i", "-", "1", ")", "!==", "'\\\\'", ")", "\\\\", "{", "isLiteral", "=", "!", "isLiteral", ";", "}", "}", "if", "(", "!", "isLiteral", "&&", "char", "===", "'?'", ")", "{", "parts", ".", "push", "(", "query", ".", "substring", "(", "lastIndex", ",", "i", ")", ")", ";", "parts", ".", "push", "(", "stringifier", "(", "params", "[", "paramsCounter", "++", "]", ")", ")", ";", "lastIndex", "=", "i", "+", "1", ";", "}", "parts", ".", "push", "(", "query", ".", "substring", "(", "lastIndex", ")", ")", ";", "}" ]
Replaced the query place holders with the stringified value @param {String} query @param {Array} params @param {Function} stringifier
[ "Replaced", "the", "query", "place", "holders", "with", "the", "stringified", "value" ]
2136de4cdde4219f9b4ba754a8f0c043077a83f2
https://github.com/jorgebay/node-cassandra-cql/blob/2136de4cdde4219f9b4ba754a8f0c043077a83f2/lib/types.js#L105-L131
train
jorgebay/node-cassandra-cql
lib/types.js
FrameHeader
function FrameHeader(values) { if (values) { if (values instanceof Buffer) { this.fromBuffer(values); } else { for (var prop in values) { this[prop] = values[prop]; } } } }
javascript
function FrameHeader(values) { if (values) { if (values instanceof Buffer) { this.fromBuffer(values); } else { for (var prop in values) { this[prop] = values[prop]; } } } }
[ "function", "FrameHeader", "(", "values", ")", "{", "if", "(", "values", ")", "{", "if", "(", "values", "instanceof", "Buffer", ")", "{", "this", ".", "fromBuffer", "(", "values", ")", ";", "}", "else", "{", "for", "(", "var", "prop", "in", "values", ")", "{", "this", "[", "prop", "]", "=", "values", "[", "prop", "]", ";", "}", "}", "}", "}" ]
classes Represents a frame header that could be used to read from a Buffer or to write to a Buffer
[ "classes", "Represents", "a", "frame", "header", "that", "could", "be", "used", "to", "read", "from", "a", "Buffer", "or", "to", "write", "to", "a", "Buffer" ]
2136de4cdde4219f9b4ba754a8f0c043077a83f2
https://github.com/jorgebay/node-cassandra-cql/blob/2136de4cdde4219f9b4ba754a8f0c043077a83f2/lib/types.js#L187-L198
train
jorgebay/node-cassandra-cql
lib/types.js
QueueWhile
function QueueWhile(test, delayRetry) { this.queue = async.queue(function (task, queueCallback) { async.whilst( test, function(cb) { //Retry in a while if (delayRetry) { setTimeout(cb, delayRetry); } else { setImmediate(cb); } }, function() { queueCallback(null, null); } ); }, 1); }
javascript
function QueueWhile(test, delayRetry) { this.queue = async.queue(function (task, queueCallback) { async.whilst( test, function(cb) { //Retry in a while if (delayRetry) { setTimeout(cb, delayRetry); } else { setImmediate(cb); } }, function() { queueCallback(null, null); } ); }, 1); }
[ "function", "QueueWhile", "(", "test", ",", "delayRetry", ")", "{", "this", ".", "queue", "=", "async", ".", "queue", "(", "function", "(", "task", ",", "queueCallback", ")", "{", "async", ".", "whilst", "(", "test", ",", "function", "(", "cb", ")", "{", "if", "(", "delayRetry", ")", "{", "setTimeout", "(", "cb", ",", "delayRetry", ")", ";", "}", "else", "{", "setImmediate", "(", "cb", ")", ";", "}", "}", ",", "function", "(", ")", "{", "queueCallback", "(", "null", ",", "null", ")", ";", "}", ")", ";", "}", ",", "1", ")", ";", "}" ]
Queues callbacks while the condition tests true. Similar behaviour as async.whilst.
[ "Queues", "callbacks", "while", "the", "condition", "tests", "true", ".", "Similar", "behaviour", "as", "async", ".", "whilst", "." ]
2136de4cdde4219f9b4ba754a8f0c043077a83f2
https://github.com/jorgebay/node-cassandra-cql/blob/2136de4cdde4219f9b4ba754a8f0c043077a83f2/lib/types.js#L277-L295
train
jorgebay/node-cassandra-cql
lib/types.js
DriverError
function DriverError (message, constructor) { if (constructor) { Error.captureStackTrace(this, constructor); this.name = constructor.name; } this.message = message || 'Error'; this.info = 'Cassandra Driver Error'; }
javascript
function DriverError (message, constructor) { if (constructor) { Error.captureStackTrace(this, constructor); this.name = constructor.name; } this.message = message || 'Error'; this.info = 'Cassandra Driver Error'; }
[ "function", "DriverError", "(", "message", ",", "constructor", ")", "{", "if", "(", "constructor", ")", "{", "Error", ".", "captureStackTrace", "(", "this", ",", "constructor", ")", ";", "this", ".", "name", "=", "constructor", ".", "name", ";", "}", "this", ".", "message", "=", "message", "||", "'Error'", ";", "this", ".", "info", "=", "'Cassandra Driver Error'", ";", "}" ]
error classes Base Error
[ "error", "classes", "Base", "Error" ]
2136de4cdde4219f9b4ba754a8f0c043077a83f2
https://github.com/jorgebay/node-cassandra-cql/blob/2136de4cdde4219f9b4ba754a8f0c043077a83f2/lib/types.js#L356-L363
train
jorgebay/node-cassandra-cql
lib/utils.js
copyBuffer
function copyBuffer(buf) { var targetBuffer = new Buffer(buf.length); buf.copy(targetBuffer); return targetBuffer; }
javascript
function copyBuffer(buf) { var targetBuffer = new Buffer(buf.length); buf.copy(targetBuffer); return targetBuffer; }
[ "function", "copyBuffer", "(", "buf", ")", "{", "var", "targetBuffer", "=", "new", "Buffer", "(", "buf", ".", "length", ")", ";", "buf", ".", "copy", "(", "targetBuffer", ")", ";", "return", "targetBuffer", ";", "}" ]
Creates a copy of a buffer
[ "Creates", "a", "copy", "of", "a", "buffer" ]
2136de4cdde4219f9b4ba754a8f0c043077a83f2
https://github.com/jorgebay/node-cassandra-cql/blob/2136de4cdde4219f9b4ba754a8f0c043077a83f2/lib/utils.js#L5-L9
train
jorgebay/node-cassandra-cql
lib/utils.js
totalLength
function totalLength (arr) { if (!arr) { return 0; } var total = 0; arr.forEach(function (item) { var length = item.length; length = length ? length : 0; total += length; }); return total; }
javascript
function totalLength (arr) { if (!arr) { return 0; } var total = 0; arr.forEach(function (item) { var length = item.length; length = length ? length : 0; total += length; }); return total; }
[ "function", "totalLength", "(", "arr", ")", "{", "if", "(", "!", "arr", ")", "{", "return", "0", ";", "}", "var", "total", "=", "0", ";", "arr", ".", "forEach", "(", "function", "(", "item", ")", "{", "var", "length", "=", "item", ".", "length", ";", "length", "=", "length", "?", "length", ":", "0", ";", "total", "+=", "length", ";", "}", ")", ";", "return", "total", ";", "}" ]
Gets the sum of the length of the items of an array
[ "Gets", "the", "sum", "of", "the", "length", "of", "the", "items", "of", "an", "array" ]
2136de4cdde4219f9b4ba754a8f0c043077a83f2
https://github.com/jorgebay/node-cassandra-cql/blob/2136de4cdde4219f9b4ba754a8f0c043077a83f2/lib/utils.js#L22-L33
train
jorgebay/node-cassandra-cql
index.js
Client
function Client(options) { events.EventEmitter.call(this); //Unlimited amount of listeners for internal event queues by default this.setMaxListeners(0); this.options = utils.extend({}, optionsDefault, options); //current connection index this.connectionIndex = 0; //current connection index for prepared queries this.prepareConnectionIndex = 0; this.preparedQueries = {}; this._createPool(); }
javascript
function Client(options) { events.EventEmitter.call(this); //Unlimited amount of listeners for internal event queues by default this.setMaxListeners(0); this.options = utils.extend({}, optionsDefault, options); //current connection index this.connectionIndex = 0; //current connection index for prepared queries this.prepareConnectionIndex = 0; this.preparedQueries = {}; this._createPool(); }
[ "function", "Client", "(", "options", ")", "{", "events", ".", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "setMaxListeners", "(", "0", ")", ";", "this", ".", "options", "=", "utils", ".", "extend", "(", "{", "}", ",", "optionsDefault", ",", "options", ")", ";", "this", ".", "connectionIndex", "=", "0", ";", "this", ".", "prepareConnectionIndex", "=", "0", ";", "this", ".", "preparedQueries", "=", "{", "}", ";", "this", ".", "_createPool", "(", ")", ";", "}" ]
Represents a pool of connection to multiple hosts
[ "Represents", "a", "pool", "of", "connection", "to", "multiple", "hosts" ]
2136de4cdde4219f9b4ba754a8f0c043077a83f2
https://github.com/jorgebay/node-cassandra-cql/blob/2136de4cdde4219f9b4ba754a8f0c043077a83f2/index.js#L24-L36
train
jorgebay/node-cassandra-cql
lib/writers.js
BatchWriter
function BatchWriter(queries, consistency, options) { this.queries = queries; options = utils.extend({atomic: true}, options); this.type = options.atomic ? 0 : 1; this.type = options.counter ? 2 : this.type; this.consistency = consistency; this.streamId = null; if (consistency === null || typeof consistency === 'undefined') { this.consistency = types.consistencies.getDefault(); } }
javascript
function BatchWriter(queries, consistency, options) { this.queries = queries; options = utils.extend({atomic: true}, options); this.type = options.atomic ? 0 : 1; this.type = options.counter ? 2 : this.type; this.consistency = consistency; this.streamId = null; if (consistency === null || typeof consistency === 'undefined') { this.consistency = types.consistencies.getDefault(); } }
[ "function", "BatchWriter", "(", "queries", ",", "consistency", ",", "options", ")", "{", "this", ".", "queries", "=", "queries", ";", "options", "=", "utils", ".", "extend", "(", "{", "atomic", ":", "true", "}", ",", "options", ")", ";", "this", ".", "type", "=", "options", ".", "atomic", "?", "0", ":", "1", ";", "this", ".", "type", "=", "options", ".", "counter", "?", "2", ":", "this", ".", "type", ";", "this", ".", "consistency", "=", "consistency", ";", "this", ".", "streamId", "=", "null", ";", "if", "(", "consistency", "===", "null", "||", "typeof", "consistency", "===", "'undefined'", ")", "{", "this", ".", "consistency", "=", "types", ".", "consistencies", ".", "getDefault", "(", ")", ";", "}", "}" ]
Writes a batch request @param {Array} queries Array of objects with the properties query and params @constructor
[ "Writes", "a", "batch", "request" ]
2136de4cdde4219f9b4ba754a8f0c043077a83f2
https://github.com/jorgebay/node-cassandra-cql/blob/2136de4cdde4219f9b4ba754a8f0c043077a83f2/lib/writers.js#L266-L276
train
silvermine/videojs-quality-selector
src/js/components/QualitySelector.js
function(source) { var src = (source ? source.src : undefined); if (this.selectedSrc !== src) { this.selectedSrc = src; this.update(); } }
javascript
function(source) { var src = (source ? source.src : undefined); if (this.selectedSrc !== src) { this.selectedSrc = src; this.update(); } }
[ "function", "(", "source", ")", "{", "var", "src", "=", "(", "source", "?", "source", ".", "src", ":", "undefined", ")", ";", "if", "(", "this", ".", "selectedSrc", "!==", "src", ")", "{", "this", ".", "selectedSrc", "=", "src", ";", "this", ".", "update", "(", ")", ";", "}", "}" ]
Updates the source that is selected in the menu @param source {object} player source to display as selected
[ "Updates", "the", "source", "that", "is", "selected", "in", "the", "menu" ]
57ab38e9118c6a4661835fe9fa38c2ee03efebb2
https://github.com/silvermine/videojs-quality-selector/blob/57ab38e9118c6a4661835fe9fa38c2ee03efebb2/src/js/components/QualitySelector.js#L57-L64
train
Hypercubed/svgsaver
lib/svgsaver.js
cloneSvg
function cloneSvg(src, attrs, styles) { var clonedSvg = src.cloneNode(true); domWalk(src, clonedSvg, function (src, tgt) { if (tgt.style) { (0, _computedStyles2['default'])(src, tgt.style, styles); } }, function (src, tgt) { if (tgt.style && tgt.parentNode) { cleanStyle(tgt); } if (tgt.attributes) { cleanAttrs(tgt, attrs, styles); } }); return clonedSvg; }
javascript
function cloneSvg(src, attrs, styles) { var clonedSvg = src.cloneNode(true); domWalk(src, clonedSvg, function (src, tgt) { if (tgt.style) { (0, _computedStyles2['default'])(src, tgt.style, styles); } }, function (src, tgt) { if (tgt.style && tgt.parentNode) { cleanStyle(tgt); } if (tgt.attributes) { cleanAttrs(tgt, attrs, styles); } }); return clonedSvg; }
[ "function", "cloneSvg", "(", "src", ",", "attrs", ",", "styles", ")", "{", "var", "clonedSvg", "=", "src", ".", "cloneNode", "(", "true", ")", ";", "domWalk", "(", "src", ",", "clonedSvg", ",", "function", "(", "src", ",", "tgt", ")", "{", "if", "(", "tgt", ".", "style", ")", "{", "(", "0", ",", "_computedStyles2", "[", "'default'", "]", ")", "(", "src", ",", "tgt", ".", "style", ",", "styles", ")", ";", "}", "}", ",", "function", "(", "src", ",", "tgt", ")", "{", "if", "(", "tgt", ".", "style", "&&", "tgt", ".", "parentNode", ")", "{", "cleanStyle", "(", "tgt", ")", ";", "}", "if", "(", "tgt", ".", "attributes", ")", "{", "cleanAttrs", "(", "tgt", ",", "attrs", ",", "styles", ")", ";", "}", "}", ")", ";", "return", "clonedSvg", ";", "}" ]
Clones an SVGElement, copies approprate atttributes and styles.
[ "Clones", "an", "SVGElement", "copies", "approprate", "atttributes", "and", "styles", "." ]
aa4a9f270629acdba35cd1b4fea57122c7dba45f
https://github.com/Hypercubed/svgsaver/blob/aa4a9f270629acdba35cd1b4fea57122c7dba45f/lib/svgsaver.js#L163-L180
train
Hypercubed/svgsaver
src/clonesvg.js
cleanAttrs
function cleanAttrs (el, attrs, styles) { // attrs === false - remove all, attrs === true - allow all if (attrs === true) { return; } Array.prototype.slice.call(el.attributes) .forEach(function (attr) { // remove if it is not style nor on attrs whitelist // keeping attributes that are also styles because attributes override if (attr.specified) { if (attrs === '' || attrs === false || (isUndefined(styles[attr.name]) && attrs.indexOf(attr.name) < 0)) { el.removeAttribute(attr.name); } } }); }
javascript
function cleanAttrs (el, attrs, styles) { // attrs === false - remove all, attrs === true - allow all if (attrs === true) { return; } Array.prototype.slice.call(el.attributes) .forEach(function (attr) { // remove if it is not style nor on attrs whitelist // keeping attributes that are also styles because attributes override if (attr.specified) { if (attrs === '' || attrs === false || (isUndefined(styles[attr.name]) && attrs.indexOf(attr.name) < 0)) { el.removeAttribute(attr.name); } } }); }
[ "function", "cleanAttrs", "(", "el", ",", "attrs", ",", "styles", ")", "{", "if", "(", "attrs", "===", "true", ")", "{", "return", ";", "}", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "el", ".", "attributes", ")", ".", "forEach", "(", "function", "(", "attr", ")", "{", "if", "(", "attr", ".", "specified", ")", "{", "if", "(", "attrs", "===", "''", "||", "attrs", "===", "false", "||", "(", "isUndefined", "(", "styles", "[", "attr", ".", "name", "]", ")", "&&", "attrs", ".", "indexOf", "(", "attr", ".", "name", ")", "<", "0", ")", ")", "{", "el", ".", "removeAttribute", "(", "attr", ".", "name", ")", ";", "}", "}", "}", ")", ";", "}" ]
Removes attributes that are not valid for SVGs
[ "Removes", "attributes", "that", "are", "not", "valid", "for", "SVGs" ]
aa4a9f270629acdba35cd1b4fea57122c7dba45f
https://github.com/Hypercubed/svgsaver/blob/aa4a9f270629acdba35cd1b4fea57122c7dba45f/src/clonesvg.js#L7-L20
train
custom-select/custom-select
src/index.js
setFocusedElement
function setFocusedElement(cstOption) { if (focusedElement) { focusedElement.classList.remove(builderParams.hasFocusClass); } if (typeof cstOption !== 'undefined') { focusedElement = cstOption; focusedElement.classList.add(builderParams.hasFocusClass); // Offset update: checks if the focused element is in the visible part of the panelClass // if not dispatches a custom event if (isOpen) { if (cstOption.offsetTop < cstOption.offsetParent.scrollTop || cstOption.offsetTop > (cstOption.offsetParent.scrollTop + cstOption.offsetParent.clientHeight) - cstOption.clientHeight) { cstOption.dispatchEvent(new CustomEvent('custom-select:focus-outside-panel', { bubbles: true })); } } } else { focusedElement = undefined; } }
javascript
function setFocusedElement(cstOption) { if (focusedElement) { focusedElement.classList.remove(builderParams.hasFocusClass); } if (typeof cstOption !== 'undefined') { focusedElement = cstOption; focusedElement.classList.add(builderParams.hasFocusClass); // Offset update: checks if the focused element is in the visible part of the panelClass // if not dispatches a custom event if (isOpen) { if (cstOption.offsetTop < cstOption.offsetParent.scrollTop || cstOption.offsetTop > (cstOption.offsetParent.scrollTop + cstOption.offsetParent.clientHeight) - cstOption.clientHeight) { cstOption.dispatchEvent(new CustomEvent('custom-select:focus-outside-panel', { bubbles: true })); } } } else { focusedElement = undefined; } }
[ "function", "setFocusedElement", "(", "cstOption", ")", "{", "if", "(", "focusedElement", ")", "{", "focusedElement", ".", "classList", ".", "remove", "(", "builderParams", ".", "hasFocusClass", ")", ";", "}", "if", "(", "typeof", "cstOption", "!==", "'undefined'", ")", "{", "focusedElement", "=", "cstOption", ";", "focusedElement", ".", "classList", ".", "add", "(", "builderParams", ".", "hasFocusClass", ")", ";", "if", "(", "isOpen", ")", "{", "if", "(", "cstOption", ".", "offsetTop", "<", "cstOption", ".", "offsetParent", ".", "scrollTop", "||", "cstOption", ".", "offsetTop", ">", "(", "cstOption", ".", "offsetParent", ".", "scrollTop", "+", "cstOption", ".", "offsetParent", ".", "clientHeight", ")", "-", "cstOption", ".", "clientHeight", ")", "{", "cstOption", ".", "dispatchEvent", "(", "new", "CustomEvent", "(", "'custom-select:focus-outside-panel'", ",", "{", "bubbles", ":", "true", "}", ")", ")", ";", "}", "}", "}", "else", "{", "focusedElement", "=", "undefined", ";", "}", "}" ]
Inner Functions Sets the focused element with the neccessary classes substitutions
[ "Inner", "Functions", "Sets", "the", "focused", "element", "with", "the", "neccessary", "classes", "substitutions" ]
388f40c79355eb38fea64dfc7834970edf020cb4
https://github.com/custom-select/custom-select/blob/388f40c79355eb38fea64dfc7834970edf020cb4/src/index.js#L47-L67
train
Azure/azure-mobile-apps-js-client
sdk/src/Platform/cordova/storeHelper.js
validateTableDefinition
function validateTableDefinition(tableDefinition) { // Do basic table name validation and leave the rest to the store Validate.notNull(tableDefinition, 'tableDefinition'); Validate.isObject(tableDefinition, 'tableDefinition'); Validate.isString(tableDefinition.name, 'tableDefinition.name'); Validate.notNullOrEmpty(tableDefinition.name, 'tableDefinition.name'); // Validate the specified column types and check for duplicate columns var columnDefinitions = tableDefinition.columnDefinitions, definedColumns = {}; Validate.isObject(columnDefinitions); Validate.notNull(columnDefinitions); for (var columnName in columnDefinitions) { Validate.isString(columnDefinitions[columnName], 'columnType'); Validate.notNullOrEmpty(columnDefinitions[columnName], 'columnType'); if (definedColumns[columnName.toLowerCase()]) { throw new Error('Duplicate definition for column ' + columnName + '" in table "' + tableDefinition.name + '"'); } definedColumns[columnName.toLowerCase()] = true; } }
javascript
function validateTableDefinition(tableDefinition) { // Do basic table name validation and leave the rest to the store Validate.notNull(tableDefinition, 'tableDefinition'); Validate.isObject(tableDefinition, 'tableDefinition'); Validate.isString(tableDefinition.name, 'tableDefinition.name'); Validate.notNullOrEmpty(tableDefinition.name, 'tableDefinition.name'); // Validate the specified column types and check for duplicate columns var columnDefinitions = tableDefinition.columnDefinitions, definedColumns = {}; Validate.isObject(columnDefinitions); Validate.notNull(columnDefinitions); for (var columnName in columnDefinitions) { Validate.isString(columnDefinitions[columnName], 'columnType'); Validate.notNullOrEmpty(columnDefinitions[columnName], 'columnType'); if (definedColumns[columnName.toLowerCase()]) { throw new Error('Duplicate definition for column ' + columnName + '" in table "' + tableDefinition.name + '"'); } definedColumns[columnName.toLowerCase()] = true; } }
[ "function", "validateTableDefinition", "(", "tableDefinition", ")", "{", "Validate", ".", "notNull", "(", "tableDefinition", ",", "'tableDefinition'", ")", ";", "Validate", ".", "isObject", "(", "tableDefinition", ",", "'tableDefinition'", ")", ";", "Validate", ".", "isString", "(", "tableDefinition", ".", "name", ",", "'tableDefinition.name'", ")", ";", "Validate", ".", "notNullOrEmpty", "(", "tableDefinition", ".", "name", ",", "'tableDefinition.name'", ")", ";", "var", "columnDefinitions", "=", "tableDefinition", ".", "columnDefinitions", ",", "definedColumns", "=", "{", "}", ";", "Validate", ".", "isObject", "(", "columnDefinitions", ")", ";", "Validate", ".", "notNull", "(", "columnDefinitions", ")", ";", "for", "(", "var", "columnName", "in", "columnDefinitions", ")", "{", "Validate", ".", "isString", "(", "columnDefinitions", "[", "columnName", "]", ",", "'columnType'", ")", ";", "Validate", ".", "notNullOrEmpty", "(", "columnDefinitions", "[", "columnName", "]", ",", "'columnType'", ")", ";", "if", "(", "definedColumns", "[", "columnName", ".", "toLowerCase", "(", ")", "]", ")", "{", "throw", "new", "Error", "(", "'Duplicate definition for column '", "+", "columnName", "+", "'\" in table \"'", "+", "tableDefinition", ".", "name", "+", "'\"'", ")", ";", "}", "definedColumns", "[", "columnName", ".", "toLowerCase", "(", ")", "]", "=", "true", ";", "}", "}" ]
Validates the table definition @private
[ "Validates", "the", "table", "definition" ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/storeHelper.js#L17-L43
train
Azure/azure-mobile-apps-js-client
sdk/src/Platform/cordova/storeHelper.js
addTableDefinition
function addTableDefinition(tableDefinitions, tableDefinition) { Validate.isObject(tableDefinitions); Validate.notNull(tableDefinitions); validateTableDefinition(tableDefinition); tableDefinitions[tableDefinition.name.toLowerCase()] = tableDefinition; }
javascript
function addTableDefinition(tableDefinitions, tableDefinition) { Validate.isObject(tableDefinitions); Validate.notNull(tableDefinitions); validateTableDefinition(tableDefinition); tableDefinitions[tableDefinition.name.toLowerCase()] = tableDefinition; }
[ "function", "addTableDefinition", "(", "tableDefinitions", ",", "tableDefinition", ")", "{", "Validate", ".", "isObject", "(", "tableDefinitions", ")", ";", "Validate", ".", "notNull", "(", "tableDefinitions", ")", ";", "validateTableDefinition", "(", "tableDefinition", ")", ";", "tableDefinitions", "[", "tableDefinition", ".", "name", ".", "toLowerCase", "(", ")", "]", "=", "tableDefinition", ";", "}" ]
Adds a tableDefinition to the tableDefinitions object @private
[ "Adds", "a", "tableDefinition", "to", "the", "tableDefinitions", "object" ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/storeHelper.js#L49-L55
train
Azure/azure-mobile-apps-js-client
sdk/src/Platform/cordova/storeHelper.js
getTableDefinition
function getTableDefinition(tableDefinitions, tableName) { Validate.isObject(tableDefinitions); Validate.notNull(tableDefinitions); Validate.isString(tableName); Validate.notNullOrEmpty(tableName); return tableDefinitions[tableName.toLowerCase()]; }
javascript
function getTableDefinition(tableDefinitions, tableName) { Validate.isObject(tableDefinitions); Validate.notNull(tableDefinitions); Validate.isString(tableName); Validate.notNullOrEmpty(tableName); return tableDefinitions[tableName.toLowerCase()]; }
[ "function", "getTableDefinition", "(", "tableDefinitions", ",", "tableName", ")", "{", "Validate", ".", "isObject", "(", "tableDefinitions", ")", ";", "Validate", ".", "notNull", "(", "tableDefinitions", ")", ";", "Validate", ".", "isString", "(", "tableName", ")", ";", "Validate", ".", "notNullOrEmpty", "(", "tableName", ")", ";", "return", "tableDefinitions", "[", "tableName", ".", "toLowerCase", "(", ")", "]", ";", "}" ]
Gets the table definition for the specified table name from the tableDefinitions object @private
[ "Gets", "the", "table", "definition", "for", "the", "specified", "table", "name", "from", "the", "tableDefinitions", "object" ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/storeHelper.js#L61-L68
train
Azure/azure-mobile-apps-js-client
sdk/src/Platform/cordova/storeHelper.js
getColumnType
function getColumnType(columnDefinitions, columnName) { Validate.isObject(columnDefinitions); Validate.notNull(columnDefinitions); Validate.isString(columnName); Validate.notNullOrEmpty(columnName); for (var column in columnDefinitions) { if (column.toLowerCase() === columnName.toLowerCase()) { return columnDefinitions[column]; } } }
javascript
function getColumnType(columnDefinitions, columnName) { Validate.isObject(columnDefinitions); Validate.notNull(columnDefinitions); Validate.isString(columnName); Validate.notNullOrEmpty(columnName); for (var column in columnDefinitions) { if (column.toLowerCase() === columnName.toLowerCase()) { return columnDefinitions[column]; } } }
[ "function", "getColumnType", "(", "columnDefinitions", ",", "columnName", ")", "{", "Validate", ".", "isObject", "(", "columnDefinitions", ")", ";", "Validate", ".", "notNull", "(", "columnDefinitions", ")", ";", "Validate", ".", "isString", "(", "columnName", ")", ";", "Validate", ".", "notNullOrEmpty", "(", "columnName", ")", ";", "for", "(", "var", "column", "in", "columnDefinitions", ")", "{", "if", "(", "column", ".", "toLowerCase", "(", ")", "===", "columnName", ".", "toLowerCase", "(", ")", ")", "{", "return", "columnDefinitions", "[", "column", "]", ";", "}", "}", "}" ]
Gets the type of the specified column @private
[ "Gets", "the", "type", "of", "the", "specified", "column" ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/storeHelper.js#L74-L85
train
Azure/azure-mobile-apps-js-client
sdk/src/Platform/cordova/storeHelper.js
getColumnName
function getColumnName(columnDefinitions, property) { Validate.isObject(columnDefinitions); Validate.notNull(columnDefinitions); Validate.isString(property); Validate.notNullOrEmpty(property); for (var column in columnDefinitions) { if (column.toLowerCase() === property.toLowerCase()) { return column; } } return property; // If no definition found for property, simply returns the column name as is }
javascript
function getColumnName(columnDefinitions, property) { Validate.isObject(columnDefinitions); Validate.notNull(columnDefinitions); Validate.isString(property); Validate.notNullOrEmpty(property); for (var column in columnDefinitions) { if (column.toLowerCase() === property.toLowerCase()) { return column; } } return property; // If no definition found for property, simply returns the column name as is }
[ "function", "getColumnName", "(", "columnDefinitions", ",", "property", ")", "{", "Validate", ".", "isObject", "(", "columnDefinitions", ")", ";", "Validate", ".", "notNull", "(", "columnDefinitions", ")", ";", "Validate", ".", "isString", "(", "property", ")", ";", "Validate", ".", "notNullOrEmpty", "(", "property", ")", ";", "for", "(", "var", "column", "in", "columnDefinitions", ")", "{", "if", "(", "column", ".", "toLowerCase", "(", ")", "===", "property", ".", "toLowerCase", "(", ")", ")", "{", "return", "column", ";", "}", "}", "return", "property", ";", "}" ]
Returns the column name in the column definitions that matches the specified property @private
[ "Returns", "the", "column", "name", "in", "the", "column", "definitions", "that", "matches", "the", "specified", "property" ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/storeHelper.js#L91-L104
train
Azure/azure-mobile-apps-js-client
sdk/src/Platform/cordova/storeHelper.js
getId
function getId(record) { Validate.isObject(record); Validate.notNull(record); for (var property in record) { if (property.toLowerCase() === idPropertyName.toLowerCase()) { return record[property]; } } }
javascript
function getId(record) { Validate.isObject(record); Validate.notNull(record); for (var property in record) { if (property.toLowerCase() === idPropertyName.toLowerCase()) { return record[property]; } } }
[ "function", "getId", "(", "record", ")", "{", "Validate", ".", "isObject", "(", "record", ")", ";", "Validate", ".", "notNull", "(", "record", ")", ";", "for", "(", "var", "property", "in", "record", ")", "{", "if", "(", "property", ".", "toLowerCase", "(", ")", "===", "idPropertyName", ".", "toLowerCase", "(", ")", ")", "{", "return", "record", "[", "property", "]", ";", "}", "}", "}" ]
Returns the Id property value OR undefined if none exists @private
[ "Returns", "the", "Id", "property", "value", "OR", "undefined", "if", "none", "exists" ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/storeHelper.js#L110-L119
train
Azure/azure-mobile-apps-js-client
sdk/src/Platform/cordova/storeHelper.js
isId
function isId(property) { Validate.isString(property); Validate.notNullOrEmpty(property); return property.toLowerCase() === idPropertyName.toLowerCase(); }
javascript
function isId(property) { Validate.isString(property); Validate.notNullOrEmpty(property); return property.toLowerCase() === idPropertyName.toLowerCase(); }
[ "function", "isId", "(", "property", ")", "{", "Validate", ".", "isString", "(", "property", ")", ";", "Validate", ".", "notNullOrEmpty", "(", "property", ")", ";", "return", "property", ".", "toLowerCase", "(", ")", "===", "idPropertyName", ".", "toLowerCase", "(", ")", ";", "}" ]
Checks if property is an ID property. @private
[ "Checks", "if", "property", "is", "an", "ID", "property", "." ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/storeHelper.js#L125-L130
train
Azure/azure-mobile-apps-js-client
sdk/src/sync/MobileServiceSyncContext.js
upsertWithLogging
function upsertWithLogging(tableName, instance, action, shouldOverwrite) { Validate.isString(tableName, 'tableName'); Validate.notNullOrEmpty(tableName, 'tableName'); Validate.notNull(instance, 'instance'); Validate.isValidId(instance.id, 'instance.id'); if (!store) { throw new Error('MobileServiceSyncContext not initialized'); } return store.lookup(tableName, instance.id, true /* suppressRecordNotFoundError */).then(function(existingRecord) { if (existingRecord && !shouldOverwrite) { throw new Error('Record with id ' + existingRecord.id + ' already exists in the table ' + tableName); } }).then(function() { return operationTableManager.getLoggingOperation(tableName, action, instance); }).then(function(loggingOperation) { return store.executeBatch([ { action: 'upsert', tableName: tableName, data: instance }, loggingOperation ]); }).then(function() { return instance; }); }
javascript
function upsertWithLogging(tableName, instance, action, shouldOverwrite) { Validate.isString(tableName, 'tableName'); Validate.notNullOrEmpty(tableName, 'tableName'); Validate.notNull(instance, 'instance'); Validate.isValidId(instance.id, 'instance.id'); if (!store) { throw new Error('MobileServiceSyncContext not initialized'); } return store.lookup(tableName, instance.id, true /* suppressRecordNotFoundError */).then(function(existingRecord) { if (existingRecord && !shouldOverwrite) { throw new Error('Record with id ' + existingRecord.id + ' already exists in the table ' + tableName); } }).then(function() { return operationTableManager.getLoggingOperation(tableName, action, instance); }).then(function(loggingOperation) { return store.executeBatch([ { action: 'upsert', tableName: tableName, data: instance }, loggingOperation ]); }).then(function() { return instance; }); }
[ "function", "upsertWithLogging", "(", "tableName", ",", "instance", ",", "action", ",", "shouldOverwrite", ")", "{", "Validate", ".", "isString", "(", "tableName", ",", "'tableName'", ")", ";", "Validate", ".", "notNullOrEmpty", "(", "tableName", ",", "'tableName'", ")", ";", "Validate", ".", "notNull", "(", "instance", ",", "'instance'", ")", ";", "Validate", ".", "isValidId", "(", "instance", ".", "id", ",", "'instance.id'", ")", ";", "if", "(", "!", "store", ")", "{", "throw", "new", "Error", "(", "'MobileServiceSyncContext not initialized'", ")", ";", "}", "return", "store", ".", "lookup", "(", "tableName", ",", "instance", ".", "id", ",", "true", ")", ".", "then", "(", "function", "(", "existingRecord", ")", "{", "if", "(", "existingRecord", "&&", "!", "shouldOverwrite", ")", "{", "throw", "new", "Error", "(", "'Record with id '", "+", "existingRecord", ".", "id", "+", "' already exists in the table '", "+", "tableName", ")", ";", "}", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "operationTableManager", ".", "getLoggingOperation", "(", "tableName", ",", "action", ",", "instance", ")", ";", "}", ")", ".", "then", "(", "function", "(", "loggingOperation", ")", "{", "return", "store", ".", "executeBatch", "(", "[", "{", "action", ":", "'upsert'", ",", "tableName", ":", "tableName", ",", "data", ":", "instance", "}", ",", "loggingOperation", "]", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "instance", ";", "}", ")", ";", "}" ]
Performs upsert and logs the action in the operation table Validates parameters. Callers can skip validation
[ "Performs", "upsert", "and", "logs", "the", "action", "in", "the", "operation", "table", "Validates", "parameters", ".", "Callers", "can", "skip", "validation" ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/sync/MobileServiceSyncContext.js#L332-L361
train
Azure/azure-mobile-apps-js-client
sdk/src/Platform/cordova/sqliteSerializer.js
getSqliteType
function getSqliteType (columnType) { var sqliteType; switch (columnType) { case ColumnType.Object: case ColumnType.Array: case ColumnType.String: case ColumnType.Text: sqliteType = "TEXT"; break; case ColumnType.Integer: case ColumnType.Int: case ColumnType.Boolean: case ColumnType.Bool: case ColumnType.Date: sqliteType = "INTEGER"; break; case ColumnType.Real: case ColumnType.Float: sqliteType = "REAL"; break; default: throw new Error('Column type ' + columnType + ' is not supported'); } return sqliteType; }
javascript
function getSqliteType (columnType) { var sqliteType; switch (columnType) { case ColumnType.Object: case ColumnType.Array: case ColumnType.String: case ColumnType.Text: sqliteType = "TEXT"; break; case ColumnType.Integer: case ColumnType.Int: case ColumnType.Boolean: case ColumnType.Bool: case ColumnType.Date: sqliteType = "INTEGER"; break; case ColumnType.Real: case ColumnType.Float: sqliteType = "REAL"; break; default: throw new Error('Column type ' + columnType + ' is not supported'); } return sqliteType; }
[ "function", "getSqliteType", "(", "columnType", ")", "{", "var", "sqliteType", ";", "switch", "(", "columnType", ")", "{", "case", "ColumnType", ".", "Object", ":", "case", "ColumnType", ".", "Array", ":", "case", "ColumnType", ".", "String", ":", "case", "ColumnType", ".", "Text", ":", "sqliteType", "=", "\"TEXT\"", ";", "break", ";", "case", "ColumnType", ".", "Integer", ":", "case", "ColumnType", ".", "Int", ":", "case", "ColumnType", ".", "Boolean", ":", "case", "ColumnType", ".", "Bool", ":", "case", "ColumnType", ".", "Date", ":", "sqliteType", "=", "\"INTEGER\"", ";", "break", ";", "case", "ColumnType", ".", "Real", ":", "case", "ColumnType", ".", "Float", ":", "sqliteType", "=", "\"REAL\"", ";", "break", ";", "default", ":", "throw", "new", "Error", "(", "'Column type '", "+", "columnType", "+", "' is not supported'", ")", ";", "}", "return", "sqliteType", ";", "}" ]
Gets the SQLite type that matches the specified ColumnType. @private @param columnType - The type of values that will be stored in the SQLite table @throw Will throw an error if columnType is not supported
[ "Gets", "the", "SQLite", "type", "that", "matches", "the", "specified", "ColumnType", "." ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/sqliteSerializer.js#L26-L52
train
Azure/azure-mobile-apps-js-client
sdk/src/Platform/cordova/sqliteSerializer.js
serialize
function serialize (value, columnDefinitions) { var serializedValue = {}; try { Validate.notNull(columnDefinitions, 'columnDefinitions'); Validate.isObject(columnDefinitions); Validate.notNull(value); Validate.isObject(value); for (var property in value) { var columnType = storeHelper.getColumnType(columnDefinitions, property); // Skip properties that don't match any column in the table if (!_.isNull(columnType)) { serializedValue[property] = serializeMember(value[property], columnType); } } } catch (error) { throw new verror.VError(error, 'Failed to serialize value ' + JSON.stringify(value) + '. Column definitions: ' + JSON.stringify(columnDefinitions)); } return serializedValue; }
javascript
function serialize (value, columnDefinitions) { var serializedValue = {}; try { Validate.notNull(columnDefinitions, 'columnDefinitions'); Validate.isObject(columnDefinitions); Validate.notNull(value); Validate.isObject(value); for (var property in value) { var columnType = storeHelper.getColumnType(columnDefinitions, property); // Skip properties that don't match any column in the table if (!_.isNull(columnType)) { serializedValue[property] = serializeMember(value[property], columnType); } } } catch (error) { throw new verror.VError(error, 'Failed to serialize value ' + JSON.stringify(value) + '. Column definitions: ' + JSON.stringify(columnDefinitions)); } return serializedValue; }
[ "function", "serialize", "(", "value", ",", "columnDefinitions", ")", "{", "var", "serializedValue", "=", "{", "}", ";", "try", "{", "Validate", ".", "notNull", "(", "columnDefinitions", ",", "'columnDefinitions'", ")", ";", "Validate", ".", "isObject", "(", "columnDefinitions", ")", ";", "Validate", ".", "notNull", "(", "value", ")", ";", "Validate", ".", "isObject", "(", "value", ")", ";", "for", "(", "var", "property", "in", "value", ")", "{", "var", "columnType", "=", "storeHelper", ".", "getColumnType", "(", "columnDefinitions", ",", "property", ")", ";", "if", "(", "!", "_", ".", "isNull", "(", "columnType", ")", ")", "{", "serializedValue", "[", "property", "]", "=", "serializeMember", "(", "value", "[", "property", "]", ",", "columnType", ")", ";", "}", "}", "}", "catch", "(", "error", ")", "{", "throw", "new", "verror", ".", "VError", "(", "error", ",", "'Failed to serialize value '", "+", "JSON", ".", "stringify", "(", "value", ")", "+", "'. Column definitions: '", "+", "JSON", ".", "stringify", "(", "columnDefinitions", ")", ")", ";", "}", "return", "serializedValue", ";", "}" ]
Serializes an object into an object that can be stored in a SQLite table, as defined by columnDefinitions. @private
[ "Serializes", "an", "object", "into", "an", "object", "that", "can", "be", "stored", "in", "a", "SQLite", "table", "as", "defined", "by", "columnDefinitions", "." ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/sqliteSerializer.js#L145-L170
train
Azure/azure-mobile-apps-js-client
sdk/src/Platform/cordova/sqliteSerializer.js
deserialize
function deserialize (value, columnDefinitions) { var deserializedValue = {}; try { Validate.notNull(columnDefinitions, 'columnDefinitions'); Validate.isObject(columnDefinitions); Validate.notNull(value); Validate.isObject(value); for (var property in value) { var columnName = storeHelper.getColumnName(columnDefinitions, property); // this helps us deserialize with proper case for the property name deserializedValue[columnName] = deserializeMember(value[property], storeHelper.getColumnType(columnDefinitions, property)); } } catch (error) { throw new verror.VError(error, 'Failed to deserialize value ' + JSON.stringify(value) + '. Column definitions: ' + JSON.stringify(columnDefinitions)); } return deserializedValue; }
javascript
function deserialize (value, columnDefinitions) { var deserializedValue = {}; try { Validate.notNull(columnDefinitions, 'columnDefinitions'); Validate.isObject(columnDefinitions); Validate.notNull(value); Validate.isObject(value); for (var property in value) { var columnName = storeHelper.getColumnName(columnDefinitions, property); // this helps us deserialize with proper case for the property name deserializedValue[columnName] = deserializeMember(value[property], storeHelper.getColumnType(columnDefinitions, property)); } } catch (error) { throw new verror.VError(error, 'Failed to deserialize value ' + JSON.stringify(value) + '. Column definitions: ' + JSON.stringify(columnDefinitions)); } return deserializedValue; }
[ "function", "deserialize", "(", "value", ",", "columnDefinitions", ")", "{", "var", "deserializedValue", "=", "{", "}", ";", "try", "{", "Validate", ".", "notNull", "(", "columnDefinitions", ",", "'columnDefinitions'", ")", ";", "Validate", ".", "isObject", "(", "columnDefinitions", ")", ";", "Validate", ".", "notNull", "(", "value", ")", ";", "Validate", ".", "isObject", "(", "value", ")", ";", "for", "(", "var", "property", "in", "value", ")", "{", "var", "columnName", "=", "storeHelper", ".", "getColumnName", "(", "columnDefinitions", ",", "property", ")", ";", "deserializedValue", "[", "columnName", "]", "=", "deserializeMember", "(", "value", "[", "property", "]", ",", "storeHelper", ".", "getColumnType", "(", "columnDefinitions", ",", "property", ")", ")", ";", "}", "}", "catch", "(", "error", ")", "{", "throw", "new", "verror", ".", "VError", "(", "error", ",", "'Failed to deserialize value '", "+", "JSON", ".", "stringify", "(", "value", ")", "+", "'. Column definitions: '", "+", "JSON", ".", "stringify", "(", "columnDefinitions", ")", ")", ";", "}", "return", "deserializedValue", ";", "}" ]
Deserializes a row read from a SQLite table into a Javascript object, as defined by columnDefinitions. @private
[ "Deserializes", "a", "row", "read", "from", "a", "SQLite", "table", "into", "a", "Javascript", "object", "as", "defined", "by", "columnDefinitions", "." ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/sqliteSerializer.js#L176-L197
train
Azure/azure-mobile-apps-js-client
sdk/src/Platform/cordova/sqliteSerializer.js
serializeMember
function serializeMember(value, columnType) { // Start by checking if the specified column type is valid if (!isColumnTypeValid(columnType)) { throw new Error('Column type ' + columnType + ' is not supported'); } // Now check if the specified value can be stored in a column of type columnType if (!isJSValueCompatibleWithColumnType(value, columnType)) { throw new Error('Converting value ' + JSON.stringify(value) + ' of type ' + typeof value + ' to type ' + columnType + ' is not supported.'); } // If we are here, it means we are good to proceed with serialization var sqliteType = getSqliteType(columnType), serializedValue; switch (sqliteType) { case "TEXT": serializedValue = typeConverter.convertToText(value); break; case "INTEGER": serializedValue = typeConverter.convertToInteger(value); break; case "REAL": serializedValue = typeConverter.convertToReal(value); break; default: throw new Error('Column type ' + columnType + ' is not supported'); } return serializedValue; }
javascript
function serializeMember(value, columnType) { // Start by checking if the specified column type is valid if (!isColumnTypeValid(columnType)) { throw new Error('Column type ' + columnType + ' is not supported'); } // Now check if the specified value can be stored in a column of type columnType if (!isJSValueCompatibleWithColumnType(value, columnType)) { throw new Error('Converting value ' + JSON.stringify(value) + ' of type ' + typeof value + ' to type ' + columnType + ' is not supported.'); } // If we are here, it means we are good to proceed with serialization var sqliteType = getSqliteType(columnType), serializedValue; switch (sqliteType) { case "TEXT": serializedValue = typeConverter.convertToText(value); break; case "INTEGER": serializedValue = typeConverter.convertToInteger(value); break; case "REAL": serializedValue = typeConverter.convertToReal(value); break; default: throw new Error('Column type ' + columnType + ' is not supported'); } return serializedValue; }
[ "function", "serializeMember", "(", "value", ",", "columnType", ")", "{", "if", "(", "!", "isColumnTypeValid", "(", "columnType", ")", ")", "{", "throw", "new", "Error", "(", "'Column type '", "+", "columnType", "+", "' is not supported'", ")", ";", "}", "if", "(", "!", "isJSValueCompatibleWithColumnType", "(", "value", ",", "columnType", ")", ")", "{", "throw", "new", "Error", "(", "'Converting value '", "+", "JSON", ".", "stringify", "(", "value", ")", "+", "' of type '", "+", "typeof", "value", "+", "' to type '", "+", "columnType", "+", "' is not supported.'", ")", ";", "}", "var", "sqliteType", "=", "getSqliteType", "(", "columnType", ")", ",", "serializedValue", ";", "switch", "(", "sqliteType", ")", "{", "case", "\"TEXT\"", ":", "serializedValue", "=", "typeConverter", ".", "convertToText", "(", "value", ")", ";", "break", ";", "case", "\"INTEGER\"", ":", "serializedValue", "=", "typeConverter", ".", "convertToInteger", "(", "value", ")", ";", "break", ";", "case", "\"REAL\"", ":", "serializedValue", "=", "typeConverter", ".", "convertToReal", "(", "value", ")", ";", "break", ";", "default", ":", "throw", "new", "Error", "(", "'Column type '", "+", "columnType", "+", "' is not supported'", ")", ";", "}", "return", "serializedValue", ";", "}" ]
Serializes a property of an object into a value which can be stored in a SQLite column of type columnType. @private
[ "Serializes", "a", "property", "of", "an", "object", "into", "a", "value", "which", "can", "be", "stored", "in", "a", "SQLite", "column", "of", "type", "columnType", "." ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/sqliteSerializer.js#L203-L235
train
Azure/azure-mobile-apps-js-client
sdk/src/Platform/cordova/sqliteSerializer.js
deserializeMember
function deserializeMember(value, columnType) { // Handle this special case first. // Simply return 'value' if a corresponding columnType is not defined. if (!columnType) { return value; } // Start by checking if the specified column type is valid. if (!isColumnTypeValid(columnType)) { throw new Error('Column type ' + columnType + ' is not supported'); } // Now check if the specified value can be stored in a column of type columnType. if (!isSqliteValueCompatibleWithColumnType(value, columnType)) { throw new Error('Converting value ' + JSON.stringify(value) + ' of type ' + typeof value + ' to type ' + columnType + ' is not supported.'); } // If we are here, it means we are good to proceed with deserialization var deserializedValue, error; switch (columnType) { case ColumnType.Object: deserializedValue = typeConverter.convertToObject(value); break; case ColumnType.Array: deserializedValue = typeConverter.convertToArray(value); break; case ColumnType.String: case ColumnType.Text: deserializedValue = typeConverter.convertToText(value); break; case ColumnType.Integer: case ColumnType.Int: deserializedValue = typeConverter.convertToInteger(value); break; case ColumnType.Boolean: case ColumnType.Bool: deserializedValue = typeConverter.convertToBoolean(value); break; case ColumnType.Date: deserializedValue = typeConverter.convertToDate(value); break; case ColumnType.Real: case ColumnType.Float: deserializedValue = typeConverter.convertToReal(value); break; default: throw new Error(_.format(Platform.getResourceString("sqliteSerializer_UnsupportedColumnType"), columnType)); } return deserializedValue; }
javascript
function deserializeMember(value, columnType) { // Handle this special case first. // Simply return 'value' if a corresponding columnType is not defined. if (!columnType) { return value; } // Start by checking if the specified column type is valid. if (!isColumnTypeValid(columnType)) { throw new Error('Column type ' + columnType + ' is not supported'); } // Now check if the specified value can be stored in a column of type columnType. if (!isSqliteValueCompatibleWithColumnType(value, columnType)) { throw new Error('Converting value ' + JSON.stringify(value) + ' of type ' + typeof value + ' to type ' + columnType + ' is not supported.'); } // If we are here, it means we are good to proceed with deserialization var deserializedValue, error; switch (columnType) { case ColumnType.Object: deserializedValue = typeConverter.convertToObject(value); break; case ColumnType.Array: deserializedValue = typeConverter.convertToArray(value); break; case ColumnType.String: case ColumnType.Text: deserializedValue = typeConverter.convertToText(value); break; case ColumnType.Integer: case ColumnType.Int: deserializedValue = typeConverter.convertToInteger(value); break; case ColumnType.Boolean: case ColumnType.Bool: deserializedValue = typeConverter.convertToBoolean(value); break; case ColumnType.Date: deserializedValue = typeConverter.convertToDate(value); break; case ColumnType.Real: case ColumnType.Float: deserializedValue = typeConverter.convertToReal(value); break; default: throw new Error(_.format(Platform.getResourceString("sqliteSerializer_UnsupportedColumnType"), columnType)); } return deserializedValue; }
[ "function", "deserializeMember", "(", "value", ",", "columnType", ")", "{", "if", "(", "!", "columnType", ")", "{", "return", "value", ";", "}", "if", "(", "!", "isColumnTypeValid", "(", "columnType", ")", ")", "{", "throw", "new", "Error", "(", "'Column type '", "+", "columnType", "+", "' is not supported'", ")", ";", "}", "if", "(", "!", "isSqliteValueCompatibleWithColumnType", "(", "value", ",", "columnType", ")", ")", "{", "throw", "new", "Error", "(", "'Converting value '", "+", "JSON", ".", "stringify", "(", "value", ")", "+", "' of type '", "+", "typeof", "value", "+", "' to type '", "+", "columnType", "+", "' is not supported.'", ")", ";", "}", "var", "deserializedValue", ",", "error", ";", "switch", "(", "columnType", ")", "{", "case", "ColumnType", ".", "Object", ":", "deserializedValue", "=", "typeConverter", ".", "convertToObject", "(", "value", ")", ";", "break", ";", "case", "ColumnType", ".", "Array", ":", "deserializedValue", "=", "typeConverter", ".", "convertToArray", "(", "value", ")", ";", "break", ";", "case", "ColumnType", ".", "String", ":", "case", "ColumnType", ".", "Text", ":", "deserializedValue", "=", "typeConverter", ".", "convertToText", "(", "value", ")", ";", "break", ";", "case", "ColumnType", ".", "Integer", ":", "case", "ColumnType", ".", "Int", ":", "deserializedValue", "=", "typeConverter", ".", "convertToInteger", "(", "value", ")", ";", "break", ";", "case", "ColumnType", ".", "Boolean", ":", "case", "ColumnType", ".", "Bool", ":", "deserializedValue", "=", "typeConverter", ".", "convertToBoolean", "(", "value", ")", ";", "break", ";", "case", "ColumnType", ".", "Date", ":", "deserializedValue", "=", "typeConverter", ".", "convertToDate", "(", "value", ")", ";", "break", ";", "case", "ColumnType", ".", "Real", ":", "case", "ColumnType", ".", "Float", ":", "deserializedValue", "=", "typeConverter", ".", "convertToReal", "(", "value", ")", ";", "break", ";", "default", ":", "throw", "new", "Error", "(", "_", ".", "format", "(", "Platform", ".", "getResourceString", "(", "\"sqliteSerializer_UnsupportedColumnType\"", ")", ",", "columnType", ")", ")", ";", "}", "return", "deserializedValue", ";", "}" ]
Deserializes a property of an object read from SQLite into a value of type columnType
[ "Deserializes", "a", "property", "of", "an", "object", "read", "from", "SQLite", "into", "a", "value", "of", "type", "columnType" ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/sqliteSerializer.js#L238-L292
train
Azure/azure-mobile-apps-js-client
sdk/src/Platform/cordova/sqliteSerializer.js
serializeValue
function serializeValue(value) { var type; if ( _.isNull(value) ) { type = ColumnType.Object; } else if ( _.isNumber(value) ) { type = ColumnType.Real; } else if ( _.isDate(value) ) { type = ColumnType.Date; } else if ( _.isBool(value) ) { type = ColumnType.Boolean; } else if ( _.isString(value) ) { type = ColumnType.String; } else if ( _.isArray(value) ) { type = ColumnType.Array; } else if ( _.isObject(value) ) { type = ColumnType.Object; } else { type = ColumnType.Object; } return serializeMember(value, type); }
javascript
function serializeValue(value) { var type; if ( _.isNull(value) ) { type = ColumnType.Object; } else if ( _.isNumber(value) ) { type = ColumnType.Real; } else if ( _.isDate(value) ) { type = ColumnType.Date; } else if ( _.isBool(value) ) { type = ColumnType.Boolean; } else if ( _.isString(value) ) { type = ColumnType.String; } else if ( _.isArray(value) ) { type = ColumnType.Array; } else if ( _.isObject(value) ) { type = ColumnType.Object; } else { type = ColumnType.Object; } return serializeMember(value, type); }
[ "function", "serializeValue", "(", "value", ")", "{", "var", "type", ";", "if", "(", "_", ".", "isNull", "(", "value", ")", ")", "{", "type", "=", "ColumnType", ".", "Object", ";", "}", "else", "if", "(", "_", ".", "isNumber", "(", "value", ")", ")", "{", "type", "=", "ColumnType", ".", "Real", ";", "}", "else", "if", "(", "_", ".", "isDate", "(", "value", ")", ")", "{", "type", "=", "ColumnType", ".", "Date", ";", "}", "else", "if", "(", "_", ".", "isBool", "(", "value", ")", ")", "{", "type", "=", "ColumnType", ".", "Boolean", ";", "}", "else", "if", "(", "_", ".", "isString", "(", "value", ")", ")", "{", "type", "=", "ColumnType", ".", "String", ";", "}", "else", "if", "(", "_", ".", "isArray", "(", "value", ")", ")", "{", "type", "=", "ColumnType", ".", "Array", ";", "}", "else", "if", "(", "_", ".", "isObject", "(", "value", ")", ")", "{", "type", "=", "ColumnType", ".", "Object", ";", "}", "else", "{", "type", "=", "ColumnType", ".", "Object", ";", "}", "return", "serializeMember", "(", "value", ",", "type", ")", ";", "}" ]
Serializes a JS value to its equivalent that will be stored in the store. This method is useful while querying to convert values to their store representations. @private
[ "Serializes", "a", "JS", "value", "to", "its", "equivalent", "that", "will", "be", "stored", "in", "the", "store", ".", "This", "method", "is", "useful", "while", "querying", "to", "convert", "values", "to", "their", "store", "representations", "." ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/sqliteSerializer.js#L299-L321
train
Azure/azure-mobile-apps-js-client
sdk/src/Utilities/taskRunner.js
run
function run(task) { return Platform.async(function(callback) { // parameter validation Validate.isFunction(task); Validate.isFunction(callback); // Add the task to the queue of pending tasks and trigger task processing queue.push({ task: task, callback: callback }); processTask(); })(); }
javascript
function run(task) { return Platform.async(function(callback) { // parameter validation Validate.isFunction(task); Validate.isFunction(callback); // Add the task to the queue of pending tasks and trigger task processing queue.push({ task: task, callback: callback }); processTask(); })(); }
[ "function", "run", "(", "task", ")", "{", "return", "Platform", ".", "async", "(", "function", "(", "callback", ")", "{", "Validate", ".", "isFunction", "(", "task", ")", ";", "Validate", ".", "isFunction", "(", "callback", ")", ";", "queue", ".", "push", "(", "{", "task", ":", "task", ",", "callback", ":", "callback", "}", ")", ";", "processTask", "(", ")", ";", "}", ")", "(", ")", ";", "}" ]
Runs the specified task asynchronously after all the earlier tasks have completed @param task Function / task to be executed. The task can either be a synchronous function or can return a promise. @returns A promise that is resolved with the value returned by the task. If the task fails the promise is rejected.
[ "Runs", "the", "specified", "task", "asynchronously", "after", "all", "the", "earlier", "tasks", "have", "completed" ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Utilities/taskRunner.js#L27-L40
train
Azure/azure-mobile-apps-js-client
sdk/src/Utilities/taskRunner.js
processTask
function processTask() { setTimeout(function() { if (isBusy || queue.length === 0) { return; } isBusy = true; var next = queue.shift(), result, error; Platform.async(function(callback) { // Start a promise chain callback(); })().then(function() { return next.task(); // Run the task }).then(function(res) { // task completed successfully isBusy = false; processTask(); next.callback(null, res); // resolve the promise returned by the run function }, function(err) { // task failed isBusy = false; processTask(); next.callback(err); // reject the promise returned by the run function }); }, 0); }
javascript
function processTask() { setTimeout(function() { if (isBusy || queue.length === 0) { return; } isBusy = true; var next = queue.shift(), result, error; Platform.async(function(callback) { // Start a promise chain callback(); })().then(function() { return next.task(); // Run the task }).then(function(res) { // task completed successfully isBusy = false; processTask(); next.callback(null, res); // resolve the promise returned by the run function }, function(err) { // task failed isBusy = false; processTask(); next.callback(err); // reject the promise returned by the run function }); }, 0); }
[ "function", "processTask", "(", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "if", "(", "isBusy", "||", "queue", ".", "length", "===", "0", ")", "{", "return", ";", "}", "isBusy", "=", "true", ";", "var", "next", "=", "queue", ".", "shift", "(", ")", ",", "result", ",", "error", ";", "Platform", ".", "async", "(", "function", "(", "callback", ")", "{", "callback", "(", ")", ";", "}", ")", "(", ")", ".", "then", "(", "function", "(", ")", "{", "return", "next", ".", "task", "(", ")", ";", "}", ")", ".", "then", "(", "function", "(", "res", ")", "{", "isBusy", "=", "false", ";", "processTask", "(", ")", ";", "next", ".", "callback", "(", "null", ",", "res", ")", ";", "}", ",", "function", "(", "err", ")", "{", "isBusy", "=", "false", ";", "processTask", "(", ")", ";", "next", ".", "callback", "(", "err", ")", ";", "}", ")", ";", "}", ",", "0", ")", ";", "}" ]
Asynchronously executes the first pending task
[ "Asynchronously", "executes", "the", "first", "pending", "task" ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Utilities/taskRunner.js#L45-L71
train
Azure/azure-mobile-apps-js-client
sdk/src/sync/pull.js
initialize
function initialize () { return pullTaskRunner.run(function() { return store.defineTable({ name: pulltimeTableName, columnDefinitions: { id: 'string', // column for storing queryId tableName: 'string', // column for storing table name value: 'date' // column for storing lastKnownUpdatedAt } }); }); }
javascript
function initialize () { return pullTaskRunner.run(function() { return store.defineTable({ name: pulltimeTableName, columnDefinitions: { id: 'string', // column for storing queryId tableName: 'string', // column for storing table name value: 'date' // column for storing lastKnownUpdatedAt } }); }); }
[ "function", "initialize", "(", ")", "{", "return", "pullTaskRunner", ".", "run", "(", "function", "(", ")", "{", "return", "store", ".", "defineTable", "(", "{", "name", ":", "pulltimeTableName", ",", "columnDefinitions", ":", "{", "id", ":", "'string'", ",", "tableName", ":", "'string'", ",", "value", ":", "'date'", "}", "}", ")", ";", "}", ")", ";", "}" ]
Creates and initializes the table used to store the state for performing incremental pull
[ "Creates", "and", "initializes", "the", "table", "used", "to", "store", "the", "state", "for", "performing", "incremental", "pull" ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/sync/pull.js#L42-L53
train
Azure/azure-mobile-apps-js-client
sdk/src/sync/pull.js
pull
function pull(query, queryId, settings) { //TODO: support pullQueryId //TODO: page size should be configurable return pullTaskRunner.run(function() { validateQuery(query, 'query'); Validate.isString(queryId, 'queryId'); // non-null string or null - both are valid Validate.isObject(settings, 'settings'); settings = settings || {}; if (_.isNull(settings.pageSize)) { pageSize = defaultPageSize; } else if (_.isInteger(settings.pageSize) && settings.pageSize > 0) { pageSize = settings.pageSize; } else { throw new Error('Page size must be a positive integer. Page size ' + settings.pageSize + ' is invalid.'); } // Make a copy of the query as we will be modifying it tablePullQuery = copyQuery(query); mobileServiceTable = client.getTable(tablePullQuery.getComponents().table); mobileServiceTable._features = queryId ? [constants.features.OfflineSync, constants.features.IncrementalPull] : [constants.features.OfflineSync]; pullQueryId = queryId; // Set up the query for initiating a pull and then pull all pages return setupQuery().then(function() { return pullAllPages(); }); }); }
javascript
function pull(query, queryId, settings) { //TODO: support pullQueryId //TODO: page size should be configurable return pullTaskRunner.run(function() { validateQuery(query, 'query'); Validate.isString(queryId, 'queryId'); // non-null string or null - both are valid Validate.isObject(settings, 'settings'); settings = settings || {}; if (_.isNull(settings.pageSize)) { pageSize = defaultPageSize; } else if (_.isInteger(settings.pageSize) && settings.pageSize > 0) { pageSize = settings.pageSize; } else { throw new Error('Page size must be a positive integer. Page size ' + settings.pageSize + ' is invalid.'); } // Make a copy of the query as we will be modifying it tablePullQuery = copyQuery(query); mobileServiceTable = client.getTable(tablePullQuery.getComponents().table); mobileServiceTable._features = queryId ? [constants.features.OfflineSync, constants.features.IncrementalPull] : [constants.features.OfflineSync]; pullQueryId = queryId; // Set up the query for initiating a pull and then pull all pages return setupQuery().then(function() { return pullAllPages(); }); }); }
[ "function", "pull", "(", "query", ",", "queryId", ",", "settings", ")", "{", "return", "pullTaskRunner", ".", "run", "(", "function", "(", ")", "{", "validateQuery", "(", "query", ",", "'query'", ")", ";", "Validate", ".", "isString", "(", "queryId", ",", "'queryId'", ")", ";", "Validate", ".", "isObject", "(", "settings", ",", "'settings'", ")", ";", "settings", "=", "settings", "||", "{", "}", ";", "if", "(", "_", ".", "isNull", "(", "settings", ".", "pageSize", ")", ")", "{", "pageSize", "=", "defaultPageSize", ";", "}", "else", "if", "(", "_", ".", "isInteger", "(", "settings", ".", "pageSize", ")", "&&", "settings", ".", "pageSize", ">", "0", ")", "{", "pageSize", "=", "settings", ".", "pageSize", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Page size must be a positive integer. Page size '", "+", "settings", ".", "pageSize", "+", "' is invalid.'", ")", ";", "}", "tablePullQuery", "=", "copyQuery", "(", "query", ")", ";", "mobileServiceTable", "=", "client", ".", "getTable", "(", "tablePullQuery", ".", "getComponents", "(", ")", ".", "table", ")", ";", "mobileServiceTable", ".", "_features", "=", "queryId", "?", "[", "constants", ".", "features", ".", "OfflineSync", ",", "constants", ".", "features", ".", "IncrementalPull", "]", ":", "[", "constants", ".", "features", ".", "OfflineSync", "]", ";", "pullQueryId", "=", "queryId", ";", "return", "setupQuery", "(", ")", ".", "then", "(", "function", "(", ")", "{", "return", "pullAllPages", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Pulls changes from the server tables into the local store. @param query Query specifying which records to pull @param pullQueryId A unique string ID for an incremental pull query OR null for a vanilla pull query. @param [settings] An object that defines the various pull settings - currently only pageSize @returns A promise that is fulfilled when all records are pulled OR is rejected if the pull fails or is cancelled.
[ "Pulls", "changes", "from", "the", "server", "tables", "into", "the", "local", "store", "." ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/sync/pull.js#L64-L94
train
Azure/azure-mobile-apps-js-client
sdk/src/sync/pull.js
pullAllPages
function pullAllPages() { // 1. Pull one page // 2. Check if Pull is complete // 3. If it is complete, go to 5. If not, update the query to fetch the next page. // 4. Go to 1 // 5. DONE return pullPage().then(function(pulledRecords) { if (!isPullComplete(pulledRecords)) { // update query and continue pulling the remaining pages return updateQueryForNextPage(pulledRecords).then(function() { return pullAllPages(); }); } }); }
javascript
function pullAllPages() { // 1. Pull one page // 2. Check if Pull is complete // 3. If it is complete, go to 5. If not, update the query to fetch the next page. // 4. Go to 1 // 5. DONE return pullPage().then(function(pulledRecords) { if (!isPullComplete(pulledRecords)) { // update query and continue pulling the remaining pages return updateQueryForNextPage(pulledRecords).then(function() { return pullAllPages(); }); } }); }
[ "function", "pullAllPages", "(", ")", "{", "return", "pullPage", "(", ")", ".", "then", "(", "function", "(", "pulledRecords", ")", "{", "if", "(", "!", "isPullComplete", "(", "pulledRecords", ")", ")", "{", "return", "updateQueryForNextPage", "(", "pulledRecords", ")", ".", "then", "(", "function", "(", ")", "{", "return", "pullAllPages", "(", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
Pulls all pages from the server table, one page at a time.
[ "Pulls", "all", "pages", "from", "the", "server", "table", "one", "page", "at", "a", "time", "." ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/sync/pull.js#L104-L118
train
Azure/azure-mobile-apps-js-client
sdk/src/sync/pull.js
pullPage
function pullPage() { // Define appropriate parameter to enable fetching of deleted records from the server. // Assumption is that soft delete is enabled on the server table. var params = {}; params[tableConstants.includeDeletedFlag] = true; var pulledRecords; // azure-query-js does not support datatimeoffset // As a temporary workaround, convert the query to an odata string and replace datetime' with datetimeoffset'. var queryString = pagePullQuery.toOData(); var tableName = pagePullQuery.getComponents().table; queryString = queryString.replace(new RegExp('^/' + tableName), '').replace("datetime'", "datetimeoffset'"); return mobileServiceTable.read(queryString, params).then(function(result) { pulledRecords = result || []; var chain = Platform.async(function(callback) { callback(); })(); // Process all records in the page for (var i = 0; i < pulledRecords.length; i++) { chain = processPulledRecord(chain, tableName, pulledRecords[i]); } return chain; }).then(function(pulled) { return onPagePulled(); }).then(function() { return pulledRecords; }); }
javascript
function pullPage() { // Define appropriate parameter to enable fetching of deleted records from the server. // Assumption is that soft delete is enabled on the server table. var params = {}; params[tableConstants.includeDeletedFlag] = true; var pulledRecords; // azure-query-js does not support datatimeoffset // As a temporary workaround, convert the query to an odata string and replace datetime' with datetimeoffset'. var queryString = pagePullQuery.toOData(); var tableName = pagePullQuery.getComponents().table; queryString = queryString.replace(new RegExp('^/' + tableName), '').replace("datetime'", "datetimeoffset'"); return mobileServiceTable.read(queryString, params).then(function(result) { pulledRecords = result || []; var chain = Platform.async(function(callback) { callback(); })(); // Process all records in the page for (var i = 0; i < pulledRecords.length; i++) { chain = processPulledRecord(chain, tableName, pulledRecords[i]); } return chain; }).then(function(pulled) { return onPagePulled(); }).then(function() { return pulledRecords; }); }
[ "function", "pullPage", "(", ")", "{", "var", "params", "=", "{", "}", ";", "params", "[", "tableConstants", ".", "includeDeletedFlag", "]", "=", "true", ";", "var", "pulledRecords", ";", "var", "queryString", "=", "pagePullQuery", ".", "toOData", "(", ")", ";", "var", "tableName", "=", "pagePullQuery", ".", "getComponents", "(", ")", ".", "table", ";", "queryString", "=", "queryString", ".", "replace", "(", "new", "RegExp", "(", "'^/'", "+", "tableName", ")", ",", "''", ")", ".", "replace", "(", "\"datetime'\"", ",", "\"datetimeoffset'\"", ")", ";", "return", "mobileServiceTable", ".", "read", "(", "queryString", ",", "params", ")", ".", "then", "(", "function", "(", "result", ")", "{", "pulledRecords", "=", "result", "||", "[", "]", ";", "var", "chain", "=", "Platform", ".", "async", "(", "function", "(", "callback", ")", "{", "callback", "(", ")", ";", "}", ")", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "pulledRecords", ".", "length", ";", "i", "++", ")", "{", "chain", "=", "processPulledRecord", "(", "chain", ",", "tableName", ",", "pulledRecords", "[", "i", "]", ")", ";", "}", "return", "chain", ";", "}", ")", ".", "then", "(", "function", "(", "pulled", ")", "{", "return", "onPagePulled", "(", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "pulledRecords", ";", "}", ")", ";", "}" ]
Pull the page as described by the query
[ "Pull", "the", "page", "as", "described", "by", "the", "query" ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/sync/pull.js#L129-L162
train
Azure/azure-mobile-apps-js-client
sdk/src/sync/pull.js
updateQueryForNextPage
function updateQueryForNextPage(pulledRecords) { return Platform.async(function(callback) { callback(); })().then(function() { if (!pulledRecords) { throw new Error('Something is wrong. pulledRecords cannot be null at this point'); } var lastRecord = pulledRecords[ pulledRecords.length - 1]; if (!lastRecord) { throw new Error('Something is wrong. Possibly invalid response from the server. lastRecord cannot be null!'); } var lastRecordTime = lastRecord[tableConstants.sysProps.updatedAtColumnName]; if (!_.isDate(lastRecordTime)) { throw new Error('Property ' + tableConstants.sysProps.updatedAtColumnName + ' of the last record should be a valid date'); } if (lastRecordTime.getTime() === lastKnownUpdatedAt.getTime()) { pagePullQuery.skip(pagePullQuery.getComponents().skip + pulledRecords.length); } else { buildQueryFromLastKnownUpdateAt(lastRecordTime); } }); }
javascript
function updateQueryForNextPage(pulledRecords) { return Platform.async(function(callback) { callback(); })().then(function() { if (!pulledRecords) { throw new Error('Something is wrong. pulledRecords cannot be null at this point'); } var lastRecord = pulledRecords[ pulledRecords.length - 1]; if (!lastRecord) { throw new Error('Something is wrong. Possibly invalid response from the server. lastRecord cannot be null!'); } var lastRecordTime = lastRecord[tableConstants.sysProps.updatedAtColumnName]; if (!_.isDate(lastRecordTime)) { throw new Error('Property ' + tableConstants.sysProps.updatedAtColumnName + ' of the last record should be a valid date'); } if (lastRecordTime.getTime() === lastKnownUpdatedAt.getTime()) { pagePullQuery.skip(pagePullQuery.getComponents().skip + pulledRecords.length); } else { buildQueryFromLastKnownUpdateAt(lastRecordTime); } }); }
[ "function", "updateQueryForNextPage", "(", "pulledRecords", ")", "{", "return", "Platform", ".", "async", "(", "function", "(", "callback", ")", "{", "callback", "(", ")", ";", "}", ")", "(", ")", ".", "then", "(", "function", "(", ")", "{", "if", "(", "!", "pulledRecords", ")", "{", "throw", "new", "Error", "(", "'Something is wrong. pulledRecords cannot be null at this point'", ")", ";", "}", "var", "lastRecord", "=", "pulledRecords", "[", "pulledRecords", ".", "length", "-", "1", "]", ";", "if", "(", "!", "lastRecord", ")", "{", "throw", "new", "Error", "(", "'Something is wrong. Possibly invalid response from the server. lastRecord cannot be null!'", ")", ";", "}", "var", "lastRecordTime", "=", "lastRecord", "[", "tableConstants", ".", "sysProps", ".", "updatedAtColumnName", "]", ";", "if", "(", "!", "_", ".", "isDate", "(", "lastRecordTime", ")", ")", "{", "throw", "new", "Error", "(", "'Property '", "+", "tableConstants", ".", "sysProps", ".", "updatedAtColumnName", "+", "' of the last record should be a valid date'", ")", ";", "}", "if", "(", "lastRecordTime", ".", "getTime", "(", ")", "===", "lastKnownUpdatedAt", ".", "getTime", "(", ")", ")", "{", "pagePullQuery", ".", "skip", "(", "pagePullQuery", ".", "getComponents", "(", ")", ".", "skip", "+", "pulledRecords", ".", "length", ")", ";", "}", "else", "{", "buildQueryFromLastKnownUpdateAt", "(", "lastRecordTime", ")", ";", "}", "}", ")", ";", "}" ]
update the query to pull the next page
[ "update", "the", "query", "to", "pull", "the", "next", "page" ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/sync/pull.js#L217-L244
train
Azure/azure-mobile-apps-js-client
sdk/src/sync/pull.js
buildQueryFromLastKnownUpdateAt
function buildQueryFromLastKnownUpdateAt(updatedAt) { lastKnownUpdatedAt = updatedAt; // Make a copy of the table query and tweak it to fetch the next first page pagePullQuery = copyQuery(tablePullQuery); pagePullQuery = pagePullQuery.where(function(lastKnownUpdatedAt) { // Ideally we would have liked to set this[tableConstants.sysProps.updatedAtColumnName] // but this isn't supported return this.updatedAt >= lastKnownUpdatedAt; }, lastKnownUpdatedAt); pagePullQuery.orderBy(tableConstants.sysProps.updatedAtColumnName); pagePullQuery.take(pageSize); }
javascript
function buildQueryFromLastKnownUpdateAt(updatedAt) { lastKnownUpdatedAt = updatedAt; // Make a copy of the table query and tweak it to fetch the next first page pagePullQuery = copyQuery(tablePullQuery); pagePullQuery = pagePullQuery.where(function(lastKnownUpdatedAt) { // Ideally we would have liked to set this[tableConstants.sysProps.updatedAtColumnName] // but this isn't supported return this.updatedAt >= lastKnownUpdatedAt; }, lastKnownUpdatedAt); pagePullQuery.orderBy(tableConstants.sysProps.updatedAtColumnName); pagePullQuery.take(pageSize); }
[ "function", "buildQueryFromLastKnownUpdateAt", "(", "updatedAt", ")", "{", "lastKnownUpdatedAt", "=", "updatedAt", ";", "pagePullQuery", "=", "copyQuery", "(", "tablePullQuery", ")", ";", "pagePullQuery", "=", "pagePullQuery", ".", "where", "(", "function", "(", "lastKnownUpdatedAt", ")", "{", "return", "this", ".", "updatedAt", ">=", "lastKnownUpdatedAt", ";", "}", ",", "lastKnownUpdatedAt", ")", ";", "pagePullQuery", ".", "orderBy", "(", "tableConstants", ".", "sysProps", ".", "updatedAtColumnName", ")", ";", "pagePullQuery", ".", "take", "(", "pageSize", ")", ";", "}" ]
Builds a query to fetch one page Records with updatedAt values >= updatedAt will be fetched
[ "Builds", "a", "query", "to", "fetch", "one", "page", "Records", "with", "updatedAt", "values", ">", "=", "updatedAt", "will", "be", "fetched" ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/sync/pull.js#L248-L262
train
Azure/azure-mobile-apps-js-client
sdk/src/sync/pull.js
onPagePulled
function onPagePulled() { // For incremental pull, make a note of the lastKnownUpdatedAt in the store if (pullQueryId) { return store.upsert(pulltimeTableName, { id: pullQueryId, tableName: pagePullQuery.getComponents().table, value: lastKnownUpdatedAt }); } }
javascript
function onPagePulled() { // For incremental pull, make a note of the lastKnownUpdatedAt in the store if (pullQueryId) { return store.upsert(pulltimeTableName, { id: pullQueryId, tableName: pagePullQuery.getComponents().table, value: lastKnownUpdatedAt }); } }
[ "function", "onPagePulled", "(", ")", "{", "if", "(", "pullQueryId", ")", "{", "return", "store", ".", "upsert", "(", "pulltimeTableName", ",", "{", "id", ":", "pullQueryId", ",", "tableName", ":", "pagePullQuery", ".", "getComponents", "(", ")", ".", "table", ",", "value", ":", "lastKnownUpdatedAt", "}", ")", ";", "}", "}" ]
Called after a page is pulled and processed
[ "Called", "after", "a", "page", "is", "pulled", "and", "processed" ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/sync/pull.js#L265-L275
train
Azure/azure-mobile-apps-js-client
sdk/src/sync/pull.js
validateQuery
function validateQuery(query) { Validate.isObject(query); Validate.notNull(query); var components = query.getComponents(); for (var i in components.ordering) { throw new Error('orderBy and orderByDescending clauses are not supported in the pull query'); } if (components.skip) { throw new Error('skip is not supported in the pull query'); } if (components.take) { throw new Error('take is not supported in the pull query'); } if (components.selections && components.selections.length !== 0) { throw new Error('select is not supported in the pull query'); } if (components.includeTotalCount) { throw new Error('includeTotalCount is not supported in the pull query'); } }
javascript
function validateQuery(query) { Validate.isObject(query); Validate.notNull(query); var components = query.getComponents(); for (var i in components.ordering) { throw new Error('orderBy and orderByDescending clauses are not supported in the pull query'); } if (components.skip) { throw new Error('skip is not supported in the pull query'); } if (components.take) { throw new Error('take is not supported in the pull query'); } if (components.selections && components.selections.length !== 0) { throw new Error('select is not supported in the pull query'); } if (components.includeTotalCount) { throw new Error('includeTotalCount is not supported in the pull query'); } }
[ "function", "validateQuery", "(", "query", ")", "{", "Validate", ".", "isObject", "(", "query", ")", ";", "Validate", ".", "notNull", "(", "query", ")", ";", "var", "components", "=", "query", ".", "getComponents", "(", ")", ";", "for", "(", "var", "i", "in", "components", ".", "ordering", ")", "{", "throw", "new", "Error", "(", "'orderBy and orderByDescending clauses are not supported in the pull query'", ")", ";", "}", "if", "(", "components", ".", "skip", ")", "{", "throw", "new", "Error", "(", "'skip is not supported in the pull query'", ")", ";", "}", "if", "(", "components", ".", "take", ")", "{", "throw", "new", "Error", "(", "'take is not supported in the pull query'", ")", ";", "}", "if", "(", "components", ".", "selections", "&&", "components", ".", "selections", ".", "length", "!==", "0", ")", "{", "throw", "new", "Error", "(", "'select is not supported in the pull query'", ")", ";", "}", "if", "(", "components", ".", "includeTotalCount", ")", "{", "throw", "new", "Error", "(", "'includeTotalCount is not supported in the pull query'", ")", ";", "}", "}" ]
Not all query operations are allowed while pulling. This function validates that the query does not perform unsupported operations.
[ "Not", "all", "query", "operations", "are", "allowed", "while", "pulling", ".", "This", "function", "validates", "that", "the", "query", "does", "not", "perform", "unsupported", "operations", "." ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/sync/pull.js#L279-L304
train
Azure/azure-mobile-apps-js-client
sdk/src/sync/pull.js
copyQuery
function copyQuery(query) { var components = query.getComponents(); var queryCopy = new Query(components.table); queryCopy.setComponents(components); return queryCopy; }
javascript
function copyQuery(query) { var components = query.getComponents(); var queryCopy = new Query(components.table); queryCopy.setComponents(components); return queryCopy; }
[ "function", "copyQuery", "(", "query", ")", "{", "var", "components", "=", "query", ".", "getComponents", "(", ")", ";", "var", "queryCopy", "=", "new", "Query", "(", "components", ".", "table", ")", ";", "queryCopy", ".", "setComponents", "(", "components", ")", ";", "return", "queryCopy", ";", "}" ]
Makes a copy of the QueryJS object
[ "Makes", "a", "copy", "of", "the", "QueryJS", "object" ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/sync/pull.js#L307-L313
train
Azure/azure-mobile-apps-js-client
sdk/src/sync/purge.js
purge
function purge(query, forcePurge) { return storeTaskRunner.run(function() { Validate.isObject(query, 'query'); Validate.notNull(query, 'query'); if (!_.isNull(forcePurge)) { Validate.isBool(forcePurge, 'forcePurge'); } // Query for pending operations associated with this table var operationQuery = new Query(tableConstants.operationTableName) .where(function(tableName) { return this.tableName === tableName; }, query.getComponents().table); // Query to search for the incremental sync state associated with this table var incrementalSyncStateQuery = new Query(tableConstants.pulltimeTableName) .where(function(tableName) { return this.tableName === tableName; }, query.getComponents().table); // 1. In case of force purge, simply remove operation table entries for the table being purged // Else, ensure no records exists in the operation table for the table being purged. // 2. Delete pull state for all incremental queries associated with this table // 3. Delete the records from the table as specified by 'query' // // TODO: All store operations performed while purging should be part of a single transaction // Note: An incremental pull after a purge should fetch purged records again. If we run 3 before 2, // we might end up in a state where 3 is complete but 2 has failed. In such a case subsequent incremental pull // will not re-fetch purged records. Hence, it is important to run 2 before 3. // There still exists a possibility of pending operations being deleted while force purging and the subsequent // operations failing which is tracked by the above TODO. return Platform.async(function(callback) { callback(); })().then(function() { if (forcePurge) { return store.del(operationQuery); } else { return store.read(operationQuery).then(function(operations) { if (operations.length > 0) { throw new Error('Cannot purge the table as it contains pending operations'); } }); } }).then(function() { return store.del(incrementalSyncStateQuery); }).then(function() { return store.del(query); }); }); }
javascript
function purge(query, forcePurge) { return storeTaskRunner.run(function() { Validate.isObject(query, 'query'); Validate.notNull(query, 'query'); if (!_.isNull(forcePurge)) { Validate.isBool(forcePurge, 'forcePurge'); } // Query for pending operations associated with this table var operationQuery = new Query(tableConstants.operationTableName) .where(function(tableName) { return this.tableName === tableName; }, query.getComponents().table); // Query to search for the incremental sync state associated with this table var incrementalSyncStateQuery = new Query(tableConstants.pulltimeTableName) .where(function(tableName) { return this.tableName === tableName; }, query.getComponents().table); // 1. In case of force purge, simply remove operation table entries for the table being purged // Else, ensure no records exists in the operation table for the table being purged. // 2. Delete pull state for all incremental queries associated with this table // 3. Delete the records from the table as specified by 'query' // // TODO: All store operations performed while purging should be part of a single transaction // Note: An incremental pull after a purge should fetch purged records again. If we run 3 before 2, // we might end up in a state where 3 is complete but 2 has failed. In such a case subsequent incremental pull // will not re-fetch purged records. Hence, it is important to run 2 before 3. // There still exists a possibility of pending operations being deleted while force purging and the subsequent // operations failing which is tracked by the above TODO. return Platform.async(function(callback) { callback(); })().then(function() { if (forcePurge) { return store.del(operationQuery); } else { return store.read(operationQuery).then(function(operations) { if (operations.length > 0) { throw new Error('Cannot purge the table as it contains pending operations'); } }); } }).then(function() { return store.del(incrementalSyncStateQuery); }).then(function() { return store.del(query); }); }); }
[ "function", "purge", "(", "query", ",", "forcePurge", ")", "{", "return", "storeTaskRunner", ".", "run", "(", "function", "(", ")", "{", "Validate", ".", "isObject", "(", "query", ",", "'query'", ")", ";", "Validate", ".", "notNull", "(", "query", ",", "'query'", ")", ";", "if", "(", "!", "_", ".", "isNull", "(", "forcePurge", ")", ")", "{", "Validate", ".", "isBool", "(", "forcePurge", ",", "'forcePurge'", ")", ";", "}", "var", "operationQuery", "=", "new", "Query", "(", "tableConstants", ".", "operationTableName", ")", ".", "where", "(", "function", "(", "tableName", ")", "{", "return", "this", ".", "tableName", "===", "tableName", ";", "}", ",", "query", ".", "getComponents", "(", ")", ".", "table", ")", ";", "var", "incrementalSyncStateQuery", "=", "new", "Query", "(", "tableConstants", ".", "pulltimeTableName", ")", ".", "where", "(", "function", "(", "tableName", ")", "{", "return", "this", ".", "tableName", "===", "tableName", ";", "}", ",", "query", ".", "getComponents", "(", ")", ".", "table", ")", ";", "return", "Platform", ".", "async", "(", "function", "(", "callback", ")", "{", "callback", "(", ")", ";", "}", ")", "(", ")", ".", "then", "(", "function", "(", ")", "{", "if", "(", "forcePurge", ")", "{", "return", "store", ".", "del", "(", "operationQuery", ")", ";", "}", "else", "{", "return", "store", ".", "read", "(", "operationQuery", ")", ".", "then", "(", "function", "(", "operations", ")", "{", "if", "(", "operations", ".", "length", ">", "0", ")", "{", "throw", "new", "Error", "(", "'Cannot purge the table as it contains pending operations'", ")", ";", "}", "}", ")", ";", "}", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "store", ".", "del", "(", "incrementalSyncStateQuery", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "store", ".", "del", "(", "query", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Purges data, pending operations and incremental sync state associated with a local table A regular purge, would fail if there are any pending operations for the table being purged. A forced purge will proceed even if pending operations for the table being purged exist in the operation table. In addition, it will also delete the table's pending operations. @param query Query object that specifies what records are to be purged @param [forcePurge] An optional boolean, which if set to true, will perform a forced purge. @returns A promise that is fulfilled when purge is complete OR is rejected if it fails.
[ "Purges", "data", "pending", "operations", "and", "incremental", "sync", "state", "associated", "with", "a", "local", "table", "A", "regular", "purge", "would", "fail", "if", "there", "are", "any", "pending", "operations", "for", "the", "table", "being", "purged", ".", "A", "forced", "purge", "will", "proceed", "even", "if", "pending", "operations", "for", "the", "table", "being", "purged", "exist", "in", "the", "operation", "table", ".", "In", "addition", "it", "will", "also", "delete", "the", "table", "s", "pending", "operations", "." ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/sync/purge.js#L35-L84
train
Azure/azure-mobile-apps-js-client
sdk/src/sync/operations.js
lockOperation
function lockOperation(id) { return runner.run(function() { // Locking a locked operation should have no effect if (lockedOperationId === id) { return; } if (!lockedOperationId) { lockedOperationId = id; return; } throw new Error('Only one operation can be locked at a time'); }); }
javascript
function lockOperation(id) { return runner.run(function() { // Locking a locked operation should have no effect if (lockedOperationId === id) { return; } if (!lockedOperationId) { lockedOperationId = id; return; } throw new Error('Only one operation can be locked at a time'); }); }
[ "function", "lockOperation", "(", "id", ")", "{", "return", "runner", ".", "run", "(", "function", "(", ")", "{", "if", "(", "lockedOperationId", "===", "id", ")", "{", "return", ";", "}", "if", "(", "!", "lockedOperationId", ")", "{", "lockedOperationId", "=", "id", ";", "return", ";", "}", "throw", "new", "Error", "(", "'Only one operation can be locked at a time'", ")", ";", "}", ")", ";", "}" ]
Locks the operation with the specified id. TODO: Lock state and the value of the locked operation should be persisted. That way we can handle the following scenario: insert -> initiate push -> connection failure after item inserted in server table -> client crashes or cancels push -> client app starts again -> delete -> condense. In the above scenario if we condense insert and delete into nothing, we end up not deleting the item we sent to server. And if we do not condense, insert will have no corresponding data in the table to send to the server while pushing as the record would have been deleted.
[ "Locks", "the", "operation", "with", "the", "specified", "id", "." ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/sync/operations.js#L86-L100
train
Azure/azure-mobile-apps-js-client
sdk/src/sync/operations.js
getCondenseAction
function getCondenseAction(pendingOperation, newAction) { var pendingAction = pendingOperation.action, condenseAction; if (pendingAction === 'insert' && newAction === 'update') { condenseAction = 'nop'; } else if (pendingAction === 'insert' && newAction === 'delete') { condenseAction = 'remove'; } else if (pendingAction === 'update' && newAction === 'update') { condenseAction = 'nop'; } else if (pendingAction === 'update' && newAction === 'delete') { condenseAction = 'modify'; } else if (pendingAction === 'delete' && newAction === 'delete') { condenseAction = 'nop'; } else if (pendingAction === 'delete') { throw new Error('Operation ' + newAction + ' not supported as a DELETE operation is pending'); //TODO: Limitation on all client SDKs } else { throw new Error('Condense not supported when pending action is ' + pendingAction + ' and new action is ' + newAction); } if (isLocked(pendingOperation)) { condenseAction = 'add'; } return condenseAction; }
javascript
function getCondenseAction(pendingOperation, newAction) { var pendingAction = pendingOperation.action, condenseAction; if (pendingAction === 'insert' && newAction === 'update') { condenseAction = 'nop'; } else if (pendingAction === 'insert' && newAction === 'delete') { condenseAction = 'remove'; } else if (pendingAction === 'update' && newAction === 'update') { condenseAction = 'nop'; } else if (pendingAction === 'update' && newAction === 'delete') { condenseAction = 'modify'; } else if (pendingAction === 'delete' && newAction === 'delete') { condenseAction = 'nop'; } else if (pendingAction === 'delete') { throw new Error('Operation ' + newAction + ' not supported as a DELETE operation is pending'); //TODO: Limitation on all client SDKs } else { throw new Error('Condense not supported when pending action is ' + pendingAction + ' and new action is ' + newAction); } if (isLocked(pendingOperation)) { condenseAction = 'add'; } return condenseAction; }
[ "function", "getCondenseAction", "(", "pendingOperation", ",", "newAction", ")", "{", "var", "pendingAction", "=", "pendingOperation", ".", "action", ",", "condenseAction", ";", "if", "(", "pendingAction", "===", "'insert'", "&&", "newAction", "===", "'update'", ")", "{", "condenseAction", "=", "'nop'", ";", "}", "else", "if", "(", "pendingAction", "===", "'insert'", "&&", "newAction", "===", "'delete'", ")", "{", "condenseAction", "=", "'remove'", ";", "}", "else", "if", "(", "pendingAction", "===", "'update'", "&&", "newAction", "===", "'update'", ")", "{", "condenseAction", "=", "'nop'", ";", "}", "else", "if", "(", "pendingAction", "===", "'update'", "&&", "newAction", "===", "'delete'", ")", "{", "condenseAction", "=", "'modify'", ";", "}", "else", "if", "(", "pendingAction", "===", "'delete'", "&&", "newAction", "===", "'delete'", ")", "{", "condenseAction", "=", "'nop'", ";", "}", "else", "if", "(", "pendingAction", "===", "'delete'", ")", "{", "throw", "new", "Error", "(", "'Operation '", "+", "newAction", "+", "' not supported as a DELETE operation is pending'", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Condense not supported when pending action is '", "+", "pendingAction", "+", "' and new action is '", "+", "newAction", ")", ";", "}", "if", "(", "isLocked", "(", "pendingOperation", ")", ")", "{", "condenseAction", "=", "'add'", ";", "}", "return", "condenseAction", ";", "}" ]
Determines how to condense the new action into the pending operation @returns 'nop' - if no action is needed 'remove' - if the pending operation should be removed 'modify' - if the pending action should be modified to be the new action 'add' - if a new operation should be added
[ "Determines", "how", "to", "condense", "the", "new", "action", "into", "the", "pending", "operation" ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/sync/operations.js#L289-L314
train
Azure/azure-mobile-apps-js-client
sdk/src/sync/operations.js
getOperationForInsertingLog
function getOperationForInsertingLog(tableName, action, item) { return api.getMetadata(tableName, action, item).then(function(metadata) { return { tableName: operationTableName, action: 'upsert', data: { id: ++maxId, tableName: tableName, action: action, itemId: item[idPropertyName], metadata: metadata } }; }); }
javascript
function getOperationForInsertingLog(tableName, action, item) { return api.getMetadata(tableName, action, item).then(function(metadata) { return { tableName: operationTableName, action: 'upsert', data: { id: ++maxId, tableName: tableName, action: action, itemId: item[idPropertyName], metadata: metadata } }; }); }
[ "function", "getOperationForInsertingLog", "(", "tableName", ",", "action", ",", "item", ")", "{", "return", "api", ".", "getMetadata", "(", "tableName", ",", "action", ",", "item", ")", ".", "then", "(", "function", "(", "metadata", ")", "{", "return", "{", "tableName", ":", "operationTableName", ",", "action", ":", "'upsert'", ",", "data", ":", "{", "id", ":", "++", "maxId", ",", "tableName", ":", "tableName", ",", "action", ":", "action", ",", "itemId", ":", "item", "[", "idPropertyName", "]", ",", "metadata", ":", "metadata", "}", "}", ";", "}", ")", ";", "}" ]
Gets the operation that will insert a new record in the operation table.
[ "Gets", "the", "operation", "that", "will", "insert", "a", "new", "record", "in", "the", "operation", "table", "." ]
bd4f9ba795527fbb95eca0f4ab53eb798934beba
https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/sync/operations.js#L319-L333
train