id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
31,900
cmap/morpheus.js
js/jquery.event.drag-2.3.0.js
function( elem, dd ){ var offset = (elem && elem.ownerDocument) ? $( elem )[ dd.relative ? "position" : "offset" ]() || { top:0, left:0 } : { top: 0, left: 0 }; return { drag: elem, callback: new drag.callback(), droppable: [], offset: offset }; }
javascript
function( elem, dd ){ var offset = (elem && elem.ownerDocument) ? $( elem )[ dd.relative ? "position" : "offset" ]() || { top:0, left:0 } : { top: 0, left: 0 }; return { drag: elem, callback: new drag.callback(), droppable: [], offset: offset }; }
[ "function", "(", "elem", ",", "dd", ")", "{", "var", "offset", "=", "(", "elem", "&&", "elem", ".", "ownerDocument", ")", "?", "$", "(", "elem", ")", "[", "dd", ".", "relative", "?", "\"position\"", ":", "\"offset\"", "]", "(", ")", "||", "{", "t...
returns an interaction object
[ "returns", "an", "interaction", "object" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/jquery.event.drag-2.3.0.js#L162-L172
31,901
cmap/morpheus.js
js/jquery.event.drag-2.3.0.js
function( event, type, dd, x, elem ){ // not configured if ( !dd ) return; // remember the original event and type var orig = { event:event.originalEvent, type:event.type }, // is the event drag related or drog related? mode = type.indexOf("drop") ? "drag" : "drop", // iteration vars result, i = x || 0, ia, $elems, callback, len = !isNaN( x ) ? x : dd.interactions.length; // modify the event type event.type = type; // protects originalEvent from side-effects var noop = function(){}; event.originalEvent = new jQuery.Event(orig.event, { preventDefault: noop, stopPropagation: noop, stopImmediatePropagation: noop }); // initialize the results dd.results = []; // handle each interacted element do if ( ia = dd.interactions[ i ] ){ // validate the interaction if ( type !== "dragend" && ia.cancelled ) continue; // set the dragdrop properties on the event object callback = drag.properties( event, dd, ia ); // prepare for more results ia.results = []; // handle each element $( elem || ia[ mode ] || dd.droppable ).each(function( p, subject ){ // identify drag or drop targets individually callback.target = subject; // force propagtion of the custom event event.isPropagationStopped = function(){ return false; }; // handle the event result = subject ? $event.dispatch.call( subject, event, callback ) : null; // stop the drag interaction for this element if ( result === false ){ if ( mode == "drag" ){ ia.cancelled = true; dd.propagates -= 1; } if ( type == "drop" ){ ia[ mode ][p] = null; } } // assign any dropinit elements else if ( type == "dropinit" ) ia.droppable.push( drag.element( result ) || subject ); // accept a returned proxy element if ( type == "dragstart" ) ia.proxy = $( drag.element( result ) || ia.drag )[0]; // remember this result ia.results.push( result ); // forget the event result, for recycling delete event.result; // break on cancelled handler if ( type !== "dropinit" ) return result; }); // flatten the results dd.results[ i ] = drag.flatten( ia.results ); // accept a set of valid drop targets if ( type == "dropinit" ) ia.droppable = drag.flatten( ia.droppable ); // locate drop targets if ( type == "dragstart" && !ia.cancelled ) callback.update(); } while ( ++i < len ) // restore the original event & type event.type = orig.type; event.originalEvent = orig.event; // return all handler results return drag.flatten( dd.results ); }
javascript
function( event, type, dd, x, elem ){ // not configured if ( !dd ) return; // remember the original event and type var orig = { event:event.originalEvent, type:event.type }, // is the event drag related or drog related? mode = type.indexOf("drop") ? "drag" : "drop", // iteration vars result, i = x || 0, ia, $elems, callback, len = !isNaN( x ) ? x : dd.interactions.length; // modify the event type event.type = type; // protects originalEvent from side-effects var noop = function(){}; event.originalEvent = new jQuery.Event(orig.event, { preventDefault: noop, stopPropagation: noop, stopImmediatePropagation: noop }); // initialize the results dd.results = []; // handle each interacted element do if ( ia = dd.interactions[ i ] ){ // validate the interaction if ( type !== "dragend" && ia.cancelled ) continue; // set the dragdrop properties on the event object callback = drag.properties( event, dd, ia ); // prepare for more results ia.results = []; // handle each element $( elem || ia[ mode ] || dd.droppable ).each(function( p, subject ){ // identify drag or drop targets individually callback.target = subject; // force propagtion of the custom event event.isPropagationStopped = function(){ return false; }; // handle the event result = subject ? $event.dispatch.call( subject, event, callback ) : null; // stop the drag interaction for this element if ( result === false ){ if ( mode == "drag" ){ ia.cancelled = true; dd.propagates -= 1; } if ( type == "drop" ){ ia[ mode ][p] = null; } } // assign any dropinit elements else if ( type == "dropinit" ) ia.droppable.push( drag.element( result ) || subject ); // accept a returned proxy element if ( type == "dragstart" ) ia.proxy = $( drag.element( result ) || ia.drag )[0]; // remember this result ia.results.push( result ); // forget the event result, for recycling delete event.result; // break on cancelled handler if ( type !== "dropinit" ) return result; }); // flatten the results dd.results[ i ] = drag.flatten( ia.results ); // accept a set of valid drop targets if ( type == "dropinit" ) ia.droppable = drag.flatten( ia.droppable ); // locate drop targets if ( type == "dragstart" && !ia.cancelled ) callback.update(); } while ( ++i < len ) // restore the original event & type event.type = orig.type; event.originalEvent = orig.event; // return all handler results return drag.flatten( dd.results ); }
[ "function", "(", "event", ",", "type", ",", "dd", ",", "x", ",", "elem", ")", "{", "// not configured", "if", "(", "!", "dd", ")", "return", ";", "// remember the original event and type", "var", "orig", "=", "{", "event", ":", "event", ".", "originalEvent...
re-use event object for custom events
[ "re", "-", "use", "event", "object", "for", "custom", "events" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/jquery.event.drag-2.3.0.js#L229-L307
31,902
cmap/morpheus.js
js/jquery.event.drag-2.3.0.js
function( arr ){ return $.map( arr, function( member ){ return member && member.jquery ? $.makeArray( member ) : member && member.length ? drag.flatten( member ) : member; }); }
javascript
function( arr ){ return $.map( arr, function( member ){ return member && member.jquery ? $.makeArray( member ) : member && member.length ? drag.flatten( member ) : member; }); }
[ "function", "(", "arr", ")", "{", "return", "$", ".", "map", "(", "arr", ",", "function", "(", "member", ")", "{", "return", "member", "&&", "member", ".", "jquery", "?", "$", ".", "makeArray", "(", "member", ")", ":", "member", "&&", "member", "."...
flatten nested jquery objects and arrays into a single dimension array
[ "flatten", "nested", "jquery", "objects", "and", "arrays", "into", "a", "single", "dimension", "array" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/jquery.event.drag-2.3.0.js#L340-L345
31,903
cmap/morpheus.js
js/tsne.js
function (n) { if (typeof(n) === 'undefined' || isNaN(n)) { return []; } if (typeof ArrayBuffer === 'undefined') { // lacking browser support var arr = new Array(n); for (var i = 0; i < n; i++) { arr[i] = 0; } return arr; } else { return new Float64Array(n); // typed arrays are faster } }
javascript
function (n) { if (typeof(n) === 'undefined' || isNaN(n)) { return []; } if (typeof ArrayBuffer === 'undefined') { // lacking browser support var arr = new Array(n); for (var i = 0; i < n; i++) { arr[i] = 0; } return arr; } else { return new Float64Array(n); // typed arrays are faster } }
[ "function", "(", "n", ")", "{", "if", "(", "typeof", "(", "n", ")", "===", "'undefined'", "||", "isNaN", "(", "n", ")", ")", "{", "return", "[", "]", ";", "}", "if", "(", "typeof", "ArrayBuffer", "===", "'undefined'", ")", "{", "// lacking browser su...
utilitity that creates contiguous vector of zeros of size n
[ "utilitity", "that", "creates", "contiguous", "vector", "of", "zeros", "of", "size", "n" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/tsne.js#L45-L59
31,904
cmap/morpheus.js
js/tsne.js
function (n, d, s) { var uses = typeof s !== 'undefined'; var x = []; for (var i = 0; i < n; i++) { var xhere = []; for (var j = 0; j < d; j++) { if (uses) { xhere.push(s); } else { xhere.push(randn(0.0, 1e-4)); } } x.push(xhere); } return x; }
javascript
function (n, d, s) { var uses = typeof s !== 'undefined'; var x = []; for (var i = 0; i < n; i++) { var xhere = []; for (var j = 0; j < d; j++) { if (uses) { xhere.push(s); } else { xhere.push(randn(0.0, 1e-4)); } } x.push(xhere); } return x; }
[ "function", "(", "n", ",", "d", ",", "s", ")", "{", "var", "uses", "=", "typeof", "s", "!==", "'undefined'", ";", "var", "x", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "var", "xher...
utility that returns 2d array filled with random numbers or with value s, if provided
[ "utility", "that", "returns", "2d", "array", "filled", "with", "random", "numbers", "or", "with", "value", "s", "if", "provided" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/tsne.js#L63-L78
31,905
cmap/morpheus.js
js/tsne.js
function (x1, x2) { var D = x1.length; var d = 0; for (var i = 0; i < D; i++) { var x1i = x1[i]; var x2i = x2[i]; d += (x1i - x2i) * (x1i - x2i); } return d; }
javascript
function (x1, x2) { var D = x1.length; var d = 0; for (var i = 0; i < D; i++) { var x1i = x1[i]; var x2i = x2[i]; d += (x1i - x2i) * (x1i - x2i); } return d; }
[ "function", "(", "x1", ",", "x2", ")", "{", "var", "D", "=", "x1", ".", "length", ";", "var", "d", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "D", ";", "i", "++", ")", "{", "var", "x1i", "=", "x1", "[", "i", "]", ...
compute L2 distance between two vectors
[ "compute", "L2", "distance", "between", "two", "vectors" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/tsne.js#L81-L90
31,906
cmap/morpheus.js
js/tsne.js
function (X) { var N = X.length; var dist = zeros(N * N); // allocate contiguous array for (var i = 0; i < N; i++) { for (var j = i + 1; j < N; j++) { var d = L2(X[i], X[j]); dist[i * N + j] = d; dist[j * N + i] = d; } } return dist; }
javascript
function (X) { var N = X.length; var dist = zeros(N * N); // allocate contiguous array for (var i = 0; i < N; i++) { for (var j = i + 1; j < N; j++) { var d = L2(X[i], X[j]); dist[i * N + j] = d; dist[j * N + i] = d; } } return dist; }
[ "function", "(", "X", ")", "{", "var", "N", "=", "X", ".", "length", ";", "var", "dist", "=", "zeros", "(", "N", "*", "N", ")", ";", "// allocate contiguous array", "for", "(", "var", "i", "=", "0", ";", "i", "<", "N", ";", "i", "++", ")", "{...
compute pairwise distance in all vectors in X
[ "compute", "pairwise", "distance", "in", "all", "vectors", "in", "X" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/tsne.js#L93-L104
31,907
cmap/morpheus.js
js/tsne.js
function (X) { var N = X.length; var D = X[0].length; assert(N > 0, " X is empty? You must have some data!"); assert(D > 0, " X[0] is empty? Where is the data?"); var dists = xtod(X); // convert X to distances using gaussian kernel this.P = d2p(dists, this.perplexity, 1e-4); // attach to object this.N = N; // back up the size of the dataset this.initSolution(); // refresh this }
javascript
function (X) { var N = X.length; var D = X[0].length; assert(N > 0, " X is empty? You must have some data!"); assert(D > 0, " X[0] is empty? Where is the data?"); var dists = xtod(X); // convert X to distances using gaussian kernel this.P = d2p(dists, this.perplexity, 1e-4); // attach to object this.N = N; // back up the size of the dataset this.initSolution(); // refresh this }
[ "function", "(", "X", ")", "{", "var", "N", "=", "X", ".", "length", ";", "var", "D", "=", "X", "[", "0", "]", ".", "length", ";", "assert", "(", "N", ">", "0", ",", "\" X is empty? You must have some data!\"", ")", ";", "assert", "(", "D", ">", ...
this function takes a set of high-dimensional points and creates matrix P from them using gaussian kernel
[ "this", "function", "takes", "a", "set", "of", "high", "-", "dimensional", "points", "and", "creates", "matrix", "P", "from", "them", "using", "gaussian", "kernel" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/tsne.js#L217-L226
31,908
cmap/morpheus.js
js/tsne.js
function (D) { var N = D.length; assert(N > 0, " X is empty? You must have some data!"); // convert D to a (fast) typed array version var dists = zeros(N * N); // allocate contiguous array for (var i = 0; i < N; i++) { for (var j = i + 1; j < N; j++) { var d = D[i][j]; dists[i * N + j] = d; dists[j * N + i] = d; } } this.P = d2p(dists, this.perplexity, 1e-4); this.N = N; this.initSolution(); // refresh this }
javascript
function (D) { var N = D.length; assert(N > 0, " X is empty? You must have some data!"); // convert D to a (fast) typed array version var dists = zeros(N * N); // allocate contiguous array for (var i = 0; i < N; i++) { for (var j = i + 1; j < N; j++) { var d = D[i][j]; dists[i * N + j] = d; dists[j * N + i] = d; } } this.P = d2p(dists, this.perplexity, 1e-4); this.N = N; this.initSolution(); // refresh this }
[ "function", "(", "D", ")", "{", "var", "N", "=", "D", ".", "length", ";", "assert", "(", "N", ">", "0", ",", "\" X is empty? You must have some data!\"", ")", ";", "// convert D to a (fast) typed array version", "var", "dists", "=", "zeros", "(", "N", "*", "...
this function takes a given distance matrix and creates matrix P from them. D is assumed to be provided as a list of lists, and should be symmetric
[ "this", "function", "takes", "a", "given", "distance", "matrix", "and", "creates", "matrix", "P", "from", "them", ".", "D", "is", "assumed", "to", "be", "provided", "as", "a", "list", "of", "lists", "and", "should", "be", "symmetric" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/tsne.js#L231-L246
31,909
cmap/morpheus.js
js/tsne.js
function () { this.iter += 1; var N = this.N; var cg = this.costGrad(this.Y); // evaluate gradient var cost = cg.cost; var grad = cg.grad; // perform gradient step var ymean = zeros(this.dim); for (var i = 0; i < N; i++) { for (var d = 0; d < this.dim; d++) { var gid = grad[i][d]; var sid = this.ystep[i][d]; var gainid = this.gains[i][d]; // compute gain update var newgain = sign(gid) === sign(sid) ? gainid * 0.8 : gainid + 0.2; if (newgain < 0.01) newgain = 0.01; // clamp this.gains[i][d] = newgain; // store for next turn // compute momentum step direction var momval = this.iter < 250 ? 0.5 : 0.8; var newsid = momval * sid - this.epsilon * newgain * grad[i][d]; this.ystep[i][d] = newsid; // remember the step we took // step! this.Y[i][d] += newsid; ymean[d] += this.Y[i][d]; // accumulate mean so that we can center later } } // reproject Y to be zero mean for (var i = 0; i < N; i++) { for (var d = 0; d < this.dim; d++) { this.Y[i][d] -= ymean[d] / N; } } //if(this.iter%100===0) console.log('iter ' + this.iter + ', cost: ' + cost); return cost; // return current cost }
javascript
function () { this.iter += 1; var N = this.N; var cg = this.costGrad(this.Y); // evaluate gradient var cost = cg.cost; var grad = cg.grad; // perform gradient step var ymean = zeros(this.dim); for (var i = 0; i < N; i++) { for (var d = 0; d < this.dim; d++) { var gid = grad[i][d]; var sid = this.ystep[i][d]; var gainid = this.gains[i][d]; // compute gain update var newgain = sign(gid) === sign(sid) ? gainid * 0.8 : gainid + 0.2; if (newgain < 0.01) newgain = 0.01; // clamp this.gains[i][d] = newgain; // store for next turn // compute momentum step direction var momval = this.iter < 250 ? 0.5 : 0.8; var newsid = momval * sid - this.epsilon * newgain * grad[i][d]; this.ystep[i][d] = newsid; // remember the step we took // step! this.Y[i][d] += newsid; ymean[d] += this.Y[i][d]; // accumulate mean so that we can center later } } // reproject Y to be zero mean for (var i = 0; i < N; i++) { for (var d = 0; d < this.dim; d++) { this.Y[i][d] -= ymean[d] / N; } } //if(this.iter%100===0) console.log('iter ' + this.iter + ', cost: ' + cost); return cost; // return current cost }
[ "function", "(", ")", "{", "this", ".", "iter", "+=", "1", ";", "var", "N", "=", "this", ".", "N", ";", "var", "cg", "=", "this", ".", "costGrad", "(", "this", ".", "Y", ")", ";", "// evaluate gradient", "var", "cost", "=", "cg", ".", "cost", "...
perform a single step of optimization to improve the embedding
[ "perform", "a", "single", "step", "of", "optimization", "to", "improve", "the", "embedding" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/tsne.js#L263-L305
31,910
cmap/morpheus.js
js/tsne.js
function (Y) { var N = this.N; var dim = this.dim; // dim of output space var P = this.P; var pmul = this.iter < 100 ? 4 : 1; // trick that helps with local optima // compute current Q distribution, unnormalized first var Qu = zeros(N * N); var qsum = 0.0; for (var i = 0; i < N; i++) { for (var j = i + 1; j < N; j++) { var dsum = 0.0; for (var d = 0; d < dim; d++) { var dhere = Y[i][d] - Y[j][d]; dsum += dhere * dhere; } var qu = 1.0 / (1.0 + dsum); // Student t-distribution Qu[i * N + j] = qu; Qu[j * N + i] = qu; qsum += 2 * qu; } } // normalize Q distribution to sum to 1 var NN = N * N; var Q = zeros(NN); for (var q = 0; q < NN; q++) { Q[q] = Math.max(Qu[q] / qsum, 1e-100); } var cost = 0.0; var grad = []; for (var i = 0; i < N; i++) { var gsum = new Array(dim); // init grad for point i for (var d = 0; d < dim; d++) { gsum[d] = 0.0; } for (var j = 0; j < N; j++) { cost += -P[i * N + j] * Math.log(Q[i * N + j]); // accumulate cost (the non-constant portion at least...) var premult = 4 * (pmul * P[i * N + j] - Q[i * N + j]) * Qu[i * N + j]; for (var d = 0; d < dim; d++) { gsum[d] += premult * (Y[i][d] - Y[j][d]); } } grad.push(gsum); } return { cost: cost, grad: grad }; }
javascript
function (Y) { var N = this.N; var dim = this.dim; // dim of output space var P = this.P; var pmul = this.iter < 100 ? 4 : 1; // trick that helps with local optima // compute current Q distribution, unnormalized first var Qu = zeros(N * N); var qsum = 0.0; for (var i = 0; i < N; i++) { for (var j = i + 1; j < N; j++) { var dsum = 0.0; for (var d = 0; d < dim; d++) { var dhere = Y[i][d] - Y[j][d]; dsum += dhere * dhere; } var qu = 1.0 / (1.0 + dsum); // Student t-distribution Qu[i * N + j] = qu; Qu[j * N + i] = qu; qsum += 2 * qu; } } // normalize Q distribution to sum to 1 var NN = N * N; var Q = zeros(NN); for (var q = 0; q < NN; q++) { Q[q] = Math.max(Qu[q] / qsum, 1e-100); } var cost = 0.0; var grad = []; for (var i = 0; i < N; i++) { var gsum = new Array(dim); // init grad for point i for (var d = 0; d < dim; d++) { gsum[d] = 0.0; } for (var j = 0; j < N; j++) { cost += -P[i * N + j] * Math.log(Q[i * N + j]); // accumulate cost (the non-constant portion at least...) var premult = 4 * (pmul * P[i * N + j] - Q[i * N + j]) * Qu[i * N + j]; for (var d = 0; d < dim; d++) { gsum[d] += premult * (Y[i][d] - Y[j][d]); } } grad.push(gsum); } return { cost: cost, grad: grad }; }
[ "function", "(", "Y", ")", "{", "var", "N", "=", "this", ".", "N", ";", "var", "dim", "=", "this", ".", "dim", ";", "// dim of output space", "var", "P", "=", "this", ".", "P", ";", "var", "pmul", "=", "this", ".", "iter", "<", "100", "?", "4",...
return cost and gradient, given an arrangement
[ "return", "cost", "and", "gradient", "given", "an", "arrangement" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/tsne.js#L336-L387
31,911
forbesmyester/SyncIt
makeAsync.js
function() { var args = Array.prototype.slice.call(arguments); args.unshift(null); var Factory = classFunc.bind.apply( classFunc, args ); this._inst = new Factory(); }
javascript
function() { var args = Array.prototype.slice.call(arguments); args.unshift(null); var Factory = classFunc.bind.apply( classFunc, args ); this._inst = new Factory(); }
[ "function", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "args", ".", "unshift", "(", "null", ")", ";", "var", "Factory", "=", "classFunc", ".", "bind", ".", "apply", "(", "cla...
This will create the constructor
[ "This", "will", "create", "the", "constructor" ]
f1e8e7eda7552b11f083a779e01c4fab5f073167
https://github.com/forbesmyester/SyncIt/blob/f1e8e7eda7552b11f083a779e01c4fab5f073167/makeAsync.js#L40-L48
31,912
rtc-io/rtc-screenshare
electron.js
simpleSelector
function simpleSelector(sources, callback) { var options = crel('select', { style: 'margin: 0.5rem' }, sources.map(function(source) { return crel('option', {id: source.id, value: source.id}, source.name); })); var selector = crel('div', { style: 'position: absolute; padding: 1rem; z-index: 999999; background: #ffffff; width: 100%; font-family: \'Lucida Sans Unicode\', \'Lucida Grande\', sans-serif; box-shadow: 0px 2px 4px #dddddd;' }, crel('label', { style: 'margin: 0.5rem' }, 'Share screen:'), options, crel('span', { style: 'margin: 0.5rem; display: inline-block' }, button('Share', function() { close(); var selected = sources.filter(function(source) { return source && source.id === options.value; })[0]; return callback(null, options.value, { title: selected.name }); }), button('Cancel', close) ) ); function button(text, fn) { var button = crel('button', { style: 'background: #555555; color: #ffffff; padding: 0.5rem 1rem; margin: 0rem 0.2rem;' }, text); button.addEventListener('click', fn); return button; } function close() { document.body.removeChild(selector); } document.body.appendChild(selector); }
javascript
function simpleSelector(sources, callback) { var options = crel('select', { style: 'margin: 0.5rem' }, sources.map(function(source) { return crel('option', {id: source.id, value: source.id}, source.name); })); var selector = crel('div', { style: 'position: absolute; padding: 1rem; z-index: 999999; background: #ffffff; width: 100%; font-family: \'Lucida Sans Unicode\', \'Lucida Grande\', sans-serif; box-shadow: 0px 2px 4px #dddddd;' }, crel('label', { style: 'margin: 0.5rem' }, 'Share screen:'), options, crel('span', { style: 'margin: 0.5rem; display: inline-block' }, button('Share', function() { close(); var selected = sources.filter(function(source) { return source && source.id === options.value; })[0]; return callback(null, options.value, { title: selected.name }); }), button('Cancel', close) ) ); function button(text, fn) { var button = crel('button', { style: 'background: #555555; color: #ffffff; padding: 0.5rem 1rem; margin: 0rem 0.2rem;' }, text); button.addEventListener('click', fn); return button; } function close() { document.body.removeChild(selector); } document.body.appendChild(selector); }
[ "function", "simpleSelector", "(", "sources", ",", "callback", ")", "{", "var", "options", "=", "crel", "(", "'select'", ",", "{", "style", ":", "'margin: 0.5rem'", "}", ",", "sources", ".", "map", "(", "function", "(", "source", ")", "{", "return", "cre...
This is just a simple default screen selector implementation
[ "This", "is", "just", "a", "simple", "default", "screen", "selector", "implementation" ]
0a160e73031a8b0f43111c22f48db6dbde3be305
https://github.com/rtc-io/rtc-screenshare/blob/0a160e73031a8b0f43111c22f48db6dbde3be305/electron.js#L84-L123
31,913
InvokIT/js-untar
src/untar.js
untar
function untar(arrayBuffer) { if (!(arrayBuffer instanceof ArrayBuffer)) { throw new TypeError("arrayBuffer is not an instance of ArrayBuffer."); } if (!global.Worker) { throw new Error("Worker implementation is not available in this environment."); } return new ProgressivePromise(function(resolve, reject, progress) { var worker = new Worker(workerScriptUri); var files = []; worker.onerror = function(err) { reject(err); }; worker.onmessage = function(message) { message = message.data; switch (message.type) { case "log": console[message.data.level]("Worker: " + message.data.msg); break; case "extract": var file = decorateExtractedFile(message.data); files.push(file); progress(file); break; case "complete": worker.terminate(); resolve(files); break; case "error": //console.log("error message"); worker.terminate(); reject(new Error(message.data.message)); break; default: worker.terminate(); reject(new Error("Unknown message from worker: " + message.type)); break; } }; //console.info("Sending arraybuffer to worker for extraction."); worker.postMessage({ type: "extract", buffer: arrayBuffer }, [arrayBuffer]); }); }
javascript
function untar(arrayBuffer) { if (!(arrayBuffer instanceof ArrayBuffer)) { throw new TypeError("arrayBuffer is not an instance of ArrayBuffer."); } if (!global.Worker) { throw new Error("Worker implementation is not available in this environment."); } return new ProgressivePromise(function(resolve, reject, progress) { var worker = new Worker(workerScriptUri); var files = []; worker.onerror = function(err) { reject(err); }; worker.onmessage = function(message) { message = message.data; switch (message.type) { case "log": console[message.data.level]("Worker: " + message.data.msg); break; case "extract": var file = decorateExtractedFile(message.data); files.push(file); progress(file); break; case "complete": worker.terminate(); resolve(files); break; case "error": //console.log("error message"); worker.terminate(); reject(new Error(message.data.message)); break; default: worker.terminate(); reject(new Error("Unknown message from worker: " + message.type)); break; } }; //console.info("Sending arraybuffer to worker for extraction."); worker.postMessage({ type: "extract", buffer: arrayBuffer }, [arrayBuffer]); }); }
[ "function", "untar", "(", "arrayBuffer", ")", "{", "if", "(", "!", "(", "arrayBuffer", "instanceof", "ArrayBuffer", ")", ")", "{", "throw", "new", "TypeError", "(", "\"arrayBuffer is not an instance of ArrayBuffer.\"", ")", ";", "}", "if", "(", "!", "global", ...
Returns a ProgressivePromise.
[ "Returns", "a", "ProgressivePromise", "." ]
49e639cf82e8d58dccb3458cbd08768afee8b41c
https://github.com/InvokIT/js-untar/blob/49e639cf82e8d58dccb3458cbd08768afee8b41c/src/untar.js#L12-L61
31,914
sidorares/hot-module-replacement
index.js
collectDependencies
function collectDependencies(module) { let paths = []; function pathsToAcceptingModules(path, root) { const requiredMe = parents[root.filename]; if (module.hot._selfAccepted) { paths.push(path.concat(root.filename)); return; } if (module.hot._selfDeclined) { return; } for (let next in requiredMe) { let parentHotRuntime = requiredMe[next].hot; if (parentHotRuntime._acceptedDependencies[root.filename]) { paths.push(path.concat(root.filename)); continue; } if (parentHotRuntime._declinedDependencies[root.filename]) { continue; } pathsToAcceptingModules(path.concat(root.filename), requiredMe[next]); } } pathsToAcceptingModules([], module); return paths; }
javascript
function collectDependencies(module) { let paths = []; function pathsToAcceptingModules(path, root) { const requiredMe = parents[root.filename]; if (module.hot._selfAccepted) { paths.push(path.concat(root.filename)); return; } if (module.hot._selfDeclined) { return; } for (let next in requiredMe) { let parentHotRuntime = requiredMe[next].hot; if (parentHotRuntime._acceptedDependencies[root.filename]) { paths.push(path.concat(root.filename)); continue; } if (parentHotRuntime._declinedDependencies[root.filename]) { continue; } pathsToAcceptingModules(path.concat(root.filename), requiredMe[next]); } } pathsToAcceptingModules([], module); return paths; }
[ "function", "collectDependencies", "(", "module", ")", "{", "let", "paths", "=", "[", "]", ";", "function", "pathsToAcceptingModules", "(", "path", ",", "root", ")", "{", "const", "requiredMe", "=", "parents", "[", "root", ".", "filename", "]", ";", "if", ...
module is changed, which dependency needs to be reloaded?
[ "module", "is", "changed", "which", "dependency", "needs", "to", "be", "reloaded?" ]
2af226b9e8fd1ce75b40b96c0920f053e92db450
https://github.com/sidorares/hot-module-replacement/blob/2af226b9e8fd1ce75b40b96c0920f053e92db450/index.js#L22-L47
31,915
dstreet/dependsOn
src/dependency.js
getFieldState
function getFieldState($ele) { var val = $ele.val() // If dependency is a radio group, then filter by `:checked` if ($ele.attr('type') === 'radio') { val = $ele.filter(':checked').val() } return { value: val, checked: $ele.is(':checked'), disabled: $ele.is(':disabled'), selected: $ele.is(':selected') } }
javascript
function getFieldState($ele) { var val = $ele.val() // If dependency is a radio group, then filter by `:checked` if ($ele.attr('type') === 'radio') { val = $ele.filter(':checked').val() } return { value: val, checked: $ele.is(':checked'), disabled: $ele.is(':disabled'), selected: $ele.is(':selected') } }
[ "function", "getFieldState", "(", "$ele", ")", "{", "var", "val", "=", "$ele", ".", "val", "(", ")", "// If dependency is a radio group, then filter by `:checked`", "if", "(", "$ele", ".", "attr", "(", "'type'", ")", "===", "'radio'", ")", "{", "val", "=", "...
Get the current state of a field @param {jQuery} $ele The element @return {Object} @private
[ "Get", "the", "current", "state", "of", "a", "field" ]
a40100652aa6a6f7748bf3cd761578b34b82d547
https://github.com/dstreet/dependsOn/blob/a40100652aa6a6f7748bf3cd761578b34b82d547/src/dependency.js#L311-L325
31,916
smsapi/smsapi-javascript-client
lib/smsapi.js
SMSAPI
function SMSAPI(options) { options = options || {}; if (options.proxy) this.proxy(options.proxy); else this.proxy(new ProxyHttp({ server: options.server })); var moduleOptions = { proxy: this.proxy() }; // init authentication if (options.oauth) { // overwrite authentication object this.authentication = new AuthenticationOAuth( _.extend({}, moduleOptions, options.oauth) ); this.proxy().setAuth(this.authentication); } else { this.authentication = new AuthenticationSimple(moduleOptions); } // init modules this.points = new Points(moduleOptions); this.profile = new Profile(moduleOptions); this.sender = new Sender(moduleOptions); this.message = new Message(moduleOptions); this.hlr = new Hlr(moduleOptions); this.user = new User(moduleOptions); this.template = new Template(moduleOptions); this.push = new Push(moduleOptions); this.contacts = new Contacts(moduleOptions); /** * @deprecated * @type {Phonebook} */ this.phonebook = new Phonebook(moduleOptions); this.proxy().setAuth(this.authentication); }
javascript
function SMSAPI(options) { options = options || {}; if (options.proxy) this.proxy(options.proxy); else this.proxy(new ProxyHttp({ server: options.server })); var moduleOptions = { proxy: this.proxy() }; // init authentication if (options.oauth) { // overwrite authentication object this.authentication = new AuthenticationOAuth( _.extend({}, moduleOptions, options.oauth) ); this.proxy().setAuth(this.authentication); } else { this.authentication = new AuthenticationSimple(moduleOptions); } // init modules this.points = new Points(moduleOptions); this.profile = new Profile(moduleOptions); this.sender = new Sender(moduleOptions); this.message = new Message(moduleOptions); this.hlr = new Hlr(moduleOptions); this.user = new User(moduleOptions); this.template = new Template(moduleOptions); this.push = new Push(moduleOptions); this.contacts = new Contacts(moduleOptions); /** * @deprecated * @type {Phonebook} */ this.phonebook = new Phonebook(moduleOptions); this.proxy().setAuth(this.authentication); }
[ "function", "SMSAPI", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "if", "(", "options", ".", "proxy", ")", "this", ".", "proxy", "(", "options", ".", "proxy", ")", ";", "else", "this", ".", "proxy", "(", "new", "ProxyH...
SMSAPI main class @param {Object} [options] @param {String} [options.server] url to the server @param {Object} [options.oauth] if provided will use oauth, simple auth otherwise @param {String} options.oauth.clientId @param {String} options.oauth.clientSecret @param {String} [options.oauth.grantType] @param {String} [options.oauth.scope] @param {ProxyAbstract} [options.proxy] custom proxy that implements ProxyAbstract @constructor
[ "SMSAPI", "main", "class" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/smsapi.js#L28-L74
31,917
smsapi/smsapi-javascript-client
lib/authentication-oauth.js
AuthenticationOAuth
function AuthenticationOAuth(options) { AuthenticationAbstract.call(this, options); options = options || {}; this._token = { access: options.accessToken || null }; }
javascript
function AuthenticationOAuth(options) { AuthenticationAbstract.call(this, options); options = options || {}; this._token = { access: options.accessToken || null }; }
[ "function", "AuthenticationOAuth", "(", "options", ")", "{", "AuthenticationAbstract", ".", "call", "(", "this", ",", "options", ")", ";", "options", "=", "options", "||", "{", "}", ";", "this", ".", "_token", "=", "{", "access", ":", "options", ".", "ac...
use oauth for authentication @param {Object} options @param {String} options.accessToken @extends AuthenticationAbstract @constructor
[ "use", "oauth", "for", "authentication" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/authentication-oauth.js#L12-L18
31,918
smsapi/smsapi-javascript-client
lib/contacts-groups-permissions-get.js
ContactsGroupsPermissionsGet
function ContactsGroupsPermissionsGet(options, groupId, username) { ActionAbstract.call(this, options); this._groupId = groupId; this._username = username; }
javascript
function ContactsGroupsPermissionsGet(options, groupId, username) { ActionAbstract.call(this, options); this._groupId = groupId; this._username = username; }
[ "function", "ContactsGroupsPermissionsGet", "(", "options", ",", "groupId", ",", "username", ")", "{", "ActionAbstract", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_groupId", "=", "groupId", ";", "this", ".", "_username", "=", "usernam...
get group permissions for user @see http://dev.smsapi.pl/#!/contacts%2Fgroups/get_0 @param {Object} options @param {String} groupId @param {String} username @extends ActionAbstract @constructor
[ "get", "group", "permissions", "for", "user" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/contacts-groups-permissions-get.js#L13-L17
31,919
smsapi/smsapi-javascript-client
lib/contacts-groups-assignments-get.js
ContactsGroupsAssignmentsGet
function ContactsGroupsAssignmentsGet(options, contactId, groupId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
javascript
function ContactsGroupsAssignmentsGet(options, contactId, groupId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
[ "function", "ContactsGroupsAssignmentsGet", "(", "options", ",", "contactId", ",", "groupId", ")", "{", "ActionAbstract", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_groupId", "=", "groupId", ";", "this", ".", "_contactId", "=", "conta...
get group related to contact @see http://dev.smsapi.pl/#!/contacts/getGroup_0 @param {Object} options @param {String} contactId @param {String} groupId @extends ActionAbstract @constructor
[ "get", "group", "related", "to", "contact" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/contacts-groups-assignments-get.js#L13-L17
31,920
smsapi/smsapi-javascript-client
lib/contacts-groups-assignments-delete.js
ContactsGroupsAssignmentsDelete
function ContactsGroupsAssignmentsDelete(options, contactId, groupId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
javascript
function ContactsGroupsAssignmentsDelete(options, contactId, groupId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
[ "function", "ContactsGroupsAssignmentsDelete", "(", "options", ",", "contactId", ",", "groupId", ")", "{", "ActionAbstract", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_groupId", "=", "groupId", ";", "this", ".", "_contactId", "=", "co...
unpin contact from group @see http://dev.smsapi.pl/#!/contacts/unpinContactGroup @param {Object} options @param {String} contactId @param {String} groupId @extends ActionAbstract @constructor
[ "unpin", "contact", "from", "group" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/contacts-groups-assignments-delete.js#L13-L17
31,921
smsapi/smsapi-javascript-client
lib/contacts-groups-members-get.js
ContactsGroupsMembersGet
function ContactsGroupsMembersGet(options, groupId, contactId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
javascript
function ContactsGroupsMembersGet(options, groupId, contactId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
[ "function", "ContactsGroupsMembersGet", "(", "options", ",", "groupId", ",", "contactId", ")", "{", "ActionAbstract", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_groupId", "=", "groupId", ";", "this", ".", "_contactId", "=", "contactId...
check whether contact is in group @see http://dev.smsapi.pl/#!/contacts%2Fgroups/contactsGet @param {Object} options @param {String} groupId @param {String} contactId @extends ActionAbstract @constructor
[ "check", "whether", "contact", "is", "in", "group" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/contacts-groups-members-get.js#L13-L17
31,922
smsapi/smsapi-javascript-client
lib/contacts-groups-members-delete.js
ContactsGroupsMembersDelete
function ContactsGroupsMembersDelete(options, groupId, contactId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
javascript
function ContactsGroupsMembersDelete(options, groupId, contactId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
[ "function", "ContactsGroupsMembersDelete", "(", "options", ",", "groupId", ",", "contactId", ")", "{", "ActionAbstract", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_groupId", "=", "groupId", ";", "this", ".", "_contactId", "=", "contac...
unpin contact from the group @see http://dev.smsapi.pl/#!/contacts%2Fgroups/contactsDelete @param {Object} options @param {String} groupId @param {String} contactId @extends ActionAbstract @constructor
[ "unpin", "contact", "from", "the", "group" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/contacts-groups-members-delete.js#L13-L17
31,923
smsapi/smsapi-javascript-client
lib/contacts-groups-assignments-add.js
ContactsGroupsAssignmentsAdd
function ContactsGroupsAssignmentsAdd(options, contactId, groupId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
javascript
function ContactsGroupsAssignmentsAdd(options, contactId, groupId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
[ "function", "ContactsGroupsAssignmentsAdd", "(", "options", ",", "contactId", ",", "groupId", ")", "{", "ActionAbstract", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_groupId", "=", "groupId", ";", "this", ".", "_contactId", "=", "conta...
Assign contact to group @see http://dev.smsapi.pl/#!/contacts/assignGroup @param {Object} options @param {String} contactId @param {String} groupId @extends ActionAbstract @constructor
[ "Assign", "contact", "to", "group" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/contacts-groups-assignments-add.js#L13-L17
31,924
smsapi/smsapi-javascript-client
lib/contacts-groups-members-add.js
ContactsGroupsMembersAdd
function ContactsGroupsMembersAdd(options, groupId, contactId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
javascript
function ContactsGroupsMembersAdd(options, groupId, contactId) { ActionAbstract.call(this, options); this._groupId = groupId; this._contactId = contactId; }
[ "function", "ContactsGroupsMembersAdd", "(", "options", ",", "groupId", ",", "contactId", ")", "{", "ActionAbstract", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_groupId", "=", "groupId", ";", "this", ".", "_contactId", "=", "contactId...
pin contact to the group @see http://dev.smsapi.pl/#!/contacts%2Fgroups/contactsPut @param {Object} options @param {String} groupId @param {String} contactId @extends ActionAbstract @constructor
[ "pin", "contact", "to", "the", "group" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/contacts-groups-members-add.js#L13-L17
31,925
smsapi/smsapi-javascript-client
lib/contacts-groups-permissions-delete.js
ContactsGroupsPermissionsDelete
function ContactsGroupsPermissionsDelete(options, groupId, username) { ActionAbstract.call(this, options); this._groupId = groupId; this._username = username; }
javascript
function ContactsGroupsPermissionsDelete(options, groupId, username) { ActionAbstract.call(this, options); this._groupId = groupId; this._username = username; }
[ "function", "ContactsGroupsPermissionsDelete", "(", "options", ",", "groupId", ",", "username", ")", "{", "ActionAbstract", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_groupId", "=", "groupId", ";", "this", ".", "_username", "=", "user...
delete group permissions for user @see http://dev.smsapi.pl/#!/contacts%2Fgroups/delete_0 @param {Object} options @param {String} groupId @param {String} username @extends ActionAbstract @constructor
[ "delete", "group", "permissions", "for", "user" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/contacts-groups-permissions-delete.js#L13-L17
31,926
smsapi/smsapi-javascript-client
lib/proxy-http.js
ProxyHttp
function ProxyHttp(options) { ProxyAbstract.call(this, options); this._server = options.server || 'https://api.smsapi.pl/'; this._auth = options.auth || null; }
javascript
function ProxyHttp(options) { ProxyAbstract.call(this, options); this._server = options.server || 'https://api.smsapi.pl/'; this._auth = options.auth || null; }
[ "function", "ProxyHttp", "(", "options", ")", "{", "ProxyAbstract", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_server", "=", "options", ".", "server", "||", "'https://api.smsapi.pl/'", ";", "this", ".", "_auth", "=", "options", ".",...
proxy for http server @param {Object} [options] @param {String} [options.server] url to the server @param {AuthenticationAbstract} [options.auth] authentication object
[ "proxy", "for", "http", "server" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/proxy-http.js#L10-L14
31,927
smsapi/smsapi-javascript-client
lib/request.js
Request
function Request(options) { options = options || {}; this._server = options.server || ''; this._path = options.path || ''; this._json = options.json || false; this._data = options.data || {}; this._auth = options.auth || null; this._file = options.file || null; this._method = options.method || 'post'; }
javascript
function Request(options) { options = options || {}; this._server = options.server || ''; this._path = options.path || ''; this._json = options.json || false; this._data = options.data || {}; this._auth = options.auth || null; this._file = options.file || null; this._method = options.method || 'post'; }
[ "function", "Request", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "_server", "=", "options", ".", "server", "||", "''", ";", "this", ".", "_path", "=", "options", ".", "path", "||", "''", ";", "this", "."...
single request to the server @param {Object} [options] @param {String} [options.server] @param {String} [options.path] @param {Boolean} [options.json] @param {Object} [options.data] @param {AuthenticationAbstract} [options.auth] @param {String} [options.file]
[ "single", "request", "to", "the", "server" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/request.js#L16-L25
31,928
smsapi/smsapi-javascript-client
lib/contacts-groups-permissions-add.js
ContactsGroupsPermissionsAdd
function ContactsGroupsPermissionsAdd(options, groupId, username) { ActionAbstract.call(this, options); this._groupId = groupId; this._username = username; }
javascript
function ContactsGroupsPermissionsAdd(options, groupId, username) { ActionAbstract.call(this, options); this._groupId = groupId; this._username = username; }
[ "function", "ContactsGroupsPermissionsAdd", "(", "options", ",", "groupId", ",", "username", ")", "{", "ActionAbstract", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_groupId", "=", "groupId", ";", "this", ".", "_username", "=", "usernam...
add permissions for the user @see http://dev.smsapi.pl/#!/contacts%2Fgroups/edit_0 @param {Object} options @param {String} groupId @param {String} username @extends ActionAbstract @constructor
[ "add", "permissions", "for", "the", "user" ]
fe181a00e02fa4df874e02782e2e3813ab541803
https://github.com/smsapi/smsapi-javascript-client/blob/fe181a00e02fa4df874e02782e2e3813ab541803/lib/contacts-groups-permissions-add.js#L13-L17
31,929
amuramoto/messenger-node
lib/client/messages/message-creative/index.js
createMessageCreative
function createMessageCreative (message) { return new Promise (async (resolve, reject) => { if (!message) { reject('Valid message object required'); } let request_options = { 'api_version': 'v2.11', 'path': '/me/message_creatives', 'payload': { 'messages': [util.parseMessageProps(message)] } }; try { let response = await this.sendGraphRequest(request_options); resolve(response); } catch (e) { reject(e); } }); }
javascript
function createMessageCreative (message) { return new Promise (async (resolve, reject) => { if (!message) { reject('Valid message object required'); } let request_options = { 'api_version': 'v2.11', 'path': '/me/message_creatives', 'payload': { 'messages': [util.parseMessageProps(message)] } }; try { let response = await this.sendGraphRequest(request_options); resolve(response); } catch (e) { reject(e); } }); }
[ "function", "createMessageCreative", "(", "message", ")", "{", "return", "new", "Promise", "(", "async", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "!", "message", ")", "{", "reject", "(", "'Valid message object required'", ")", ";", "}", "l...
Creates a new message creative. @param {Object} message An object that describes the message to send. @return {Promise<Object>} The API response @memberof Client# @example <caption>Text Message</caption> let message = {'text': 'my text message'}; Client.createMessageCreative(message) .then(res => { console.log(res); // {"message_creative_id": "953434576932424"} }); @example <caption>Template Message</caption> let message = { template_type: 'generic', elements: [ { 'title':'This is a generic template', 'subtitle':'Plus a subtitle!', 'image_url':'https://www.example.com/dog.jpg', 'buttons':[ { 'type':'postback', 'title':'Postback Button', 'payload':'postback_payload' }, { 'type': 'web_url', 'title': 'URL Button', 'url': 'https://www.example.com/' } ] } ] }; Client.createMessageCreative(message) .then(res => { console.log(res); // {"message_creative_id": "953434576932424"} });
[ "Creates", "a", "new", "message", "creative", "." ]
d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4
https://github.com/amuramoto/messenger-node/blob/d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4/lib/client/messages/message-creative/index.js#L45-L66
31,930
amuramoto/messenger-node
lib/client/messages/custom-labels/index.js
createCustomLabel
function createCustomLabel (name) { return new Promise (async (resolve, reject) => { if (!name) { reject('name required'); } let options = { 'payload': {'name': name} }; try { let response = await this.callCustomLabelsApi(options); resolve(response); } catch (e) { reject(e); } }); }
javascript
function createCustomLabel (name) { return new Promise (async (resolve, reject) => { if (!name) { reject('name required'); } let options = { 'payload': {'name': name} }; try { let response = await this.callCustomLabelsApi(options); resolve(response); } catch (e) { reject(e); } }); }
[ "function", "createCustomLabel", "(", "name", ")", "{", "return", "new", "Promise", "(", "async", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "!", "name", ")", "{", "reject", "(", "'name required'", ")", ";", "}", "let", "options", "=", ...
Creates a new custom label. @param {String} name The name of the custom label. @return {Promise<Object>} The API response @memberof Client# @example Client.createCustomLabel('my_custom_label') .then(res => { console.log(res); // {"id": "9485676932424"} });
[ "Creates", "a", "new", "custom", "label", "." ]
d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4
https://github.com/amuramoto/messenger-node/blob/d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4/lib/client/messages/custom-labels/index.js#L23-L38
31,931
amuramoto/messenger-node
lib/client/messages/custom-labels/index.js
getAllCustomLabels
function getAllCustomLabels () { return new Promise (async (resolve, reject) => { let options = { 'qs': {'fields': 'id,name'} }; try { let response = await this.callCustomLabelsApi(options); resolve(response); } catch (e) { reject(e); } }); }
javascript
function getAllCustomLabels () { return new Promise (async (resolve, reject) => { let options = { 'qs': {'fields': 'id,name'} }; try { let response = await this.callCustomLabelsApi(options); resolve(response); } catch (e) { reject(e); } }); }
[ "function", "getAllCustomLabels", "(", ")", "{", "return", "new", "Promise", "(", "async", "(", "resolve", ",", "reject", ")", "=>", "{", "let", "options", "=", "{", "'qs'", ":", "{", "'fields'", ":", "'id,name'", "}", "}", ";", "try", "{", "let", "r...
Retrieves the list of all custom labels. @return {Promise<Object>} The API response @memberof Client# @example let field = ['name', 'id']; //optional Client.getAllCustomLabels(fields) .then(res => { console.log(res); // { // "data": [ // { "name": "myLabel", "id": "1001200005003"}, // { "name": "myOtherLabel", "id": "1001200005002"} // ], // "paging": { // "cursors": { // "before": "QVFIUmx1WTBpMGpJWXprYzVYaVhabW55dVpyc", // "after": "QVFIUmItNkpTbjVzakxFWGRydzdaVUFNNnNPaU" // } // } // } });
[ "Retrieves", "the", "list", "of", "all", "custom", "labels", "." ]
d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4
https://github.com/amuramoto/messenger-node/blob/d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4/lib/client/messages/custom-labels/index.js#L138-L151
31,932
amuramoto/messenger-node
lib/client/messages/custom-labels/index.js
deleteCustomLabel
function deleteCustomLabel (label_id) { return new Promise (async (resolve, reject) => { if (!label_id) { reject('label_id required'); return; } let options = { 'method': 'DELETE', 'path': '/' + label_id }; try { let response = await this.callCustomLabelsApi(options); resolve(response); } catch (e) { reject(e); } }); }
javascript
function deleteCustomLabel (label_id) { return new Promise (async (resolve, reject) => { if (!label_id) { reject('label_id required'); return; } let options = { 'method': 'DELETE', 'path': '/' + label_id }; try { let response = await this.callCustomLabelsApi(options); resolve(response); } catch (e) { reject(e); } }); }
[ "function", "deleteCustomLabel", "(", "label_id", ")", "{", "return", "new", "Promise", "(", "async", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "!", "label_id", ")", "{", "reject", "(", "'label_id required'", ")", ";", "return", ";", "}",...
Deletes a custom label. @param {Integer} label_id The ID of the custom label to delete. @return {Promise<Object>} The API response @memberof Client# @example Client.deleteCustomLabel(094730967209673) .then(res => { console.log(res); // {"success": true} });
[ "Deletes", "a", "custom", "label", "." ]
d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4
https://github.com/amuramoto/messenger-node/blob/d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4/lib/client/messages/custom-labels/index.js#L164-L182
31,933
amuramoto/messenger-node
lib/client/messages/custom-labels/index.js
addPsidtoCustomLabel
function addPsidtoCustomLabel (psid, label_id) { return new Promise (async (resolve, reject) => { if (!psid || !label_id) { reject('PSID and label_id required'); return; } let options = { 'path': `/${label_id}/label`, 'payload': {'user': psid} }; try { let response = await this.callCustomLabelsApi(options); resolve(response); } catch (e) { reject(e); } }); }
javascript
function addPsidtoCustomLabel (psid, label_id) { return new Promise (async (resolve, reject) => { if (!psid || !label_id) { reject('PSID and label_id required'); return; } let options = { 'path': `/${label_id}/label`, 'payload': {'user': psid} }; try { let response = await this.callCustomLabelsApi(options); resolve(response); } catch (e) { reject(e); } }); }
[ "function", "addPsidtoCustomLabel", "(", "psid", ",", "label_id", ")", "{", "return", "new", "Promise", "(", "async", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "!", "psid", "||", "!", "label_id", ")", "{", "reject", "(", "'PSID and label_...
Associates a user's PSID to a custom label. @param {Integer} psid PSID of the user to associate with the custom label. @param {Integer} label_id The ID of a custom label. Created with {@link #createcustomlabel|createCustomLabel()}. @return {Promise<Object>} The API response @memberof Client# @example let psid = 49670354734069743, custom_label_id = 0957209720496743; Client.addPsidtoCustomLabel(psid, custom_label_id) .then(res => { console.log(res); // {"success": true} });
[ "Associates", "a", "user", "s", "PSID", "to", "a", "custom", "label", "." ]
d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4
https://github.com/amuramoto/messenger-node/blob/d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4/lib/client/messages/custom-labels/index.js#L198-L215
31,934
amuramoto/messenger-node
lib/client/index.js
Client
function Client (options) { let GraphRequest = new graphRequest(options); Object.assign( this, GraphRequest, new messages(GraphRequest), new messengerProfile(GraphRequest), new person(GraphRequest), new messengerCode(GraphRequest), new messagingInsights(GraphRequest), new attachment(GraphRequest), new nlp(GraphRequest), new handoverProtocol(GraphRequest) ); }
javascript
function Client (options) { let GraphRequest = new graphRequest(options); Object.assign( this, GraphRequest, new messages(GraphRequest), new messengerProfile(GraphRequest), new person(GraphRequest), new messengerCode(GraphRequest), new messagingInsights(GraphRequest), new attachment(GraphRequest), new nlp(GraphRequest), new handoverProtocol(GraphRequest) ); }
[ "function", "Client", "(", "options", ")", "{", "let", "GraphRequest", "=", "new", "graphRequest", "(", "options", ")", ";", "Object", ".", "assign", "(", "this", ",", "GraphRequest", ",", "new", "messages", "(", "GraphRequest", ")", ",", "new", "messenger...
Creates an instance of `Client`, used for sending requests to the Messenger Platform APIs. @constructor @class Client @param {Object} options An object that contains the configuration settings for the `Client`. @param {String} options.page_token A valid Page-scoped access token. @param {String} options.app_token _Optional._ A valid app-scoped access token. Required for ID Matching. @param {String} options.graph_api_version _Optional._ The version of the Graph API to target for all API requests. Defaults to latest. Must be in the format `v2.11`. @returns {Client} @example const Messenger = require('messenger-node'); let options = { 'page_token': 'sd0we98h248n2g40gh4g80h32', 'app_token': 'ih908wh084ggh423940hg934g358h0358hg3', //optional 'api_version': 'v2.9' //optional } const Client = new Messenger.Client(options);
[ "Creates", "an", "instance", "of", "Client", "used", "for", "sending", "requests", "to", "the", "Messenger", "Platform", "APIs", "." ]
d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4
https://github.com/amuramoto/messenger-node/blob/d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4/lib/client/index.js#L29-L45
31,935
amuramoto/messenger-node
lib/client/messages/broadcast/index.js
startBroadcastReachEstimation
function startBroadcastReachEstimation (custom_label_id) { return new Promise (async (resolve, reject) => { let options = { 'custom_label_id': custom_label_id || true }; try { let response = await this.callBroadcastApi(options); resolve(response); } catch (e) { reject(e); } }); }
javascript
function startBroadcastReachEstimation (custom_label_id) { return new Promise (async (resolve, reject) => { let options = { 'custom_label_id': custom_label_id || true }; try { let response = await this.callBroadcastApi(options); resolve(response); } catch (e) { reject(e); } }); }
[ "function", "startBroadcastReachEstimation", "(", "custom_label_id", ")", "{", "return", "new", "Promise", "(", "async", "(", "resolve", ",", "reject", ")", "=>", "{", "let", "options", "=", "{", "'custom_label_id'", ":", "custom_label_id", "||", "true", "}", ...
Start a reach estimation for the number of people that will be reached by a broadcast to all users or to users associated with a custom label. @param {Integer} custom_label_id _Optional._ The ID of a custom label targeted by the broadcast. Created by calling {@link #createcustomlabel|Client.createCustomLabel()}. @return {Promise<Object>} The API Response @memberof Client# @example let custom_label_id = 3467390467035645 //optional Client.startBroadcastReachEstimation(custom_label_id) .then(res => { console.log(res); // {"reach_estimation_id": "9485676932424"} });
[ "Start", "a", "reach", "estimation", "for", "the", "number", "of", "people", "that", "will", "be", "reached", "by", "a", "broadcast", "to", "all", "users", "or", "to", "users", "associated", "with", "a", "custom", "label", "." ]
d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4
https://github.com/amuramoto/messenger-node/blob/d6cee1bedeea0ce7a675edbdb0bee6f0f50f44d4/lib/client/messages/broadcast/index.js#L57-L69
31,936
cdiggins/myna-parser
tools/myna_markdown_to_html.js
startTag
function startTag(tag, attr) { let attrStr = ""; if (attr) { attrStr = " " + Object.keys(attr).map(function(k) { return k + ' = "' + attr[k] + '"'; }).join(" "); } return "<" + tag + attrStr + ">"; }
javascript
function startTag(tag, attr) { let attrStr = ""; if (attr) { attrStr = " " + Object.keys(attr).map(function(k) { return k + ' = "' + attr[k] + '"'; }).join(" "); } return "<" + tag + attrStr + ">"; }
[ "function", "startTag", "(", "tag", ",", "attr", ")", "{", "let", "attrStr", "=", "\"\"", ";", "if", "(", "attr", ")", "{", "attrStr", "=", "\" \"", "+", "Object", ".", "keys", "(", "attr", ")", ".", "map", "(", "function", "(", "k", ")", "{", ...
Returns the HTML for a start tag
[ "Returns", "the", "HTML", "for", "a", "start", "tag" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/tools/myna_markdown_to_html.js#L7-L15
31,937
cdiggins/myna-parser
tools/myna_markdown_to_html.js
mdAstToHtml
function mdAstToHtml(ast, lines) { if (lines == undefined) lines = []; // Adds each element of the array as markdown function addArray(ast) { for (let child of ast) mdAstToHtml(child, lines); return lines; } // Adds tagged content function addTag(tag, ast, newLine) { lines.push(startTag(tag)); if (ast instanceof Array) addArray(ast); else mdAstToHtml(ast, lines); lines.push(endTag(tag)); if (newLine) lines.push('\r\n'); return lines; } function addLink(url, astOrText) { lines.push(startTag('a', { href:url })); if (astOrText) { if (astOrText.children) addArray(astOrText.children); else lines.push(astOrText); } lines.push(endTag('a')) ; return lines; } function addImg(url) { lines.push(startTag('img', { src:url })); lines.push(endTag('img')) ; return lines; } switch (ast.name) { case "heading": { let headingLevel = ast.children[0]; let restOfLine = ast.children[1]; let h = headingLevel.allText.length; switch (h) { case 1: return addTag("h1", restOfLine, true); case 2: return addTag("h2", restOfLine, true); case 3: return addTag("h3", restOfLine, true); case 4: return addTag("h4", restOfLine, true); case 5: return addTag("h5", restOfLine, true); case 6: return addTag("h6", restOfLine, true); default: throw "Heading level must be from 1 to 6" } } case "paragraph": return addTag("p", ast.children, true); case "unorderedList": return addTag("ul", ast.children, true); case "orderedList": return addTag("ol", ast.children, true); case "unorderedListItem": return addTag("li", ast.children, true); case "orderedListItem": return addTag("li", ast.children, true); case "inlineUrl": return addLink(ast.allText, ast.allText); case "bold": return addTag("b", ast.children); case "italic": return addTag("i", ast.children); case "code": return addTag("code", ast.children); case "codeBlock": return addTag("pre", ast.children); case "quote": return addTag("blockquote", ast.children, true); case "link": return addLink(ast.children[1].allText, ast.children[0]); case "image": return addImg(ast.children[0]); default: if (ast.isLeaf) lines.push(ast.allText); else ast.children.forEach(function(c) { mdAstToHtml(c, lines); }); } return lines; }
javascript
function mdAstToHtml(ast, lines) { if (lines == undefined) lines = []; // Adds each element of the array as markdown function addArray(ast) { for (let child of ast) mdAstToHtml(child, lines); return lines; } // Adds tagged content function addTag(tag, ast, newLine) { lines.push(startTag(tag)); if (ast instanceof Array) addArray(ast); else mdAstToHtml(ast, lines); lines.push(endTag(tag)); if (newLine) lines.push('\r\n'); return lines; } function addLink(url, astOrText) { lines.push(startTag('a', { href:url })); if (astOrText) { if (astOrText.children) addArray(astOrText.children); else lines.push(astOrText); } lines.push(endTag('a')) ; return lines; } function addImg(url) { lines.push(startTag('img', { src:url })); lines.push(endTag('img')) ; return lines; } switch (ast.name) { case "heading": { let headingLevel = ast.children[0]; let restOfLine = ast.children[1]; let h = headingLevel.allText.length; switch (h) { case 1: return addTag("h1", restOfLine, true); case 2: return addTag("h2", restOfLine, true); case 3: return addTag("h3", restOfLine, true); case 4: return addTag("h4", restOfLine, true); case 5: return addTag("h5", restOfLine, true); case 6: return addTag("h6", restOfLine, true); default: throw "Heading level must be from 1 to 6" } } case "paragraph": return addTag("p", ast.children, true); case "unorderedList": return addTag("ul", ast.children, true); case "orderedList": return addTag("ol", ast.children, true); case "unorderedListItem": return addTag("li", ast.children, true); case "orderedListItem": return addTag("li", ast.children, true); case "inlineUrl": return addLink(ast.allText, ast.allText); case "bold": return addTag("b", ast.children); case "italic": return addTag("i", ast.children); case "code": return addTag("code", ast.children); case "codeBlock": return addTag("pre", ast.children); case "quote": return addTag("blockquote", ast.children, true); case "link": return addLink(ast.children[1].allText, ast.children[0]); case "image": return addImg(ast.children[0]); default: if (ast.isLeaf) lines.push(ast.allText); else ast.children.forEach(function(c) { mdAstToHtml(c, lines); }); } return lines; }
[ "function", "mdAstToHtml", "(", "ast", ",", "lines", ")", "{", "if", "(", "lines", "==", "undefined", ")", "lines", "=", "[", "]", ";", "// Adds each element of the array as markdown ", "function", "addArray", "(", "ast", ")", "{", "for", "(", "let", "child"...
Returns HTML from a MarkDown AST
[ "Returns", "HTML", "from", "a", "MarkDown", "AST" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/tools/myna_markdown_to_html.js#L23-L117
31,938
cdiggins/myna-parser
tools/myna_markdown_to_html.js
addTag
function addTag(tag, ast, newLine) { lines.push(startTag(tag)); if (ast instanceof Array) addArray(ast); else mdAstToHtml(ast, lines); lines.push(endTag(tag)); if (newLine) lines.push('\r\n'); return lines; }
javascript
function addTag(tag, ast, newLine) { lines.push(startTag(tag)); if (ast instanceof Array) addArray(ast); else mdAstToHtml(ast, lines); lines.push(endTag(tag)); if (newLine) lines.push('\r\n'); return lines; }
[ "function", "addTag", "(", "tag", ",", "ast", ",", "newLine", ")", "{", "lines", ".", "push", "(", "startTag", "(", "tag", ")", ")", ";", "if", "(", "ast", "instanceof", "Array", ")", "addArray", "(", "ast", ")", ";", "else", "mdAstToHtml", "(", "a...
Adds tagged content
[ "Adds", "tagged", "content" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/tools/myna_markdown_to_html.js#L35-L45
31,939
cdiggins/myna-parser
tools/myna_markdown_to_html.js
mdToHtml
function mdToHtml(input) { let rule = myna.allRules['markdown.document']; let ast = myna.parse(rule, input); return mdAstToHtml(ast, []).join(""); }
javascript
function mdToHtml(input) { let rule = myna.allRules['markdown.document']; let ast = myna.parse(rule, input); return mdAstToHtml(ast, []).join(""); }
[ "function", "mdToHtml", "(", "input", ")", "{", "let", "rule", "=", "myna", ".", "allRules", "[", "'markdown.document'", "]", ";", "let", "ast", "=", "myna", ".", "parse", "(", "rule", ",", "input", ")", ";", "return", "mdAstToHtml", "(", "ast", ",", ...
Converts Markdown text to HTML
[ "Converts", "Markdown", "text", "to", "HTML" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/tools/myna_markdown_to_html.js#L120-L124
31,940
cdiggins/myna-parser
myna.js
function () { var r = this.cloneImplementation(); if (typeof (r) !== typeof (this)) throw new Error("Error in implementation of cloneImplementation: not returning object of correct type"); r.name = this.name; r.grammarName = this.grammarName; r._createAstNode = this._createAstNode; return r; }
javascript
function () { var r = this.cloneImplementation(); if (typeof (r) !== typeof (this)) throw new Error("Error in implementation of cloneImplementation: not returning object of correct type"); r.name = this.name; r.grammarName = this.grammarName; r._createAstNode = this._createAstNode; return r; }
[ "function", "(", ")", "{", "var", "r", "=", "this", ".", "cloneImplementation", "(", ")", ";", "if", "(", "typeof", "(", "r", ")", "!==", "typeof", "(", "this", ")", ")", "throw", "new", "Error", "(", "\"Error in implementation of cloneImplementation: not re...
Returns a copy of this rule with all fields copied.
[ "Returns", "a", "copy", "of", "this", "rule", "with", "all", "fields", "copied", "." ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L298-L306
31,941
cdiggins/myna-parser
myna.js
function () { if (this.min == 0 && this.max == 1) return this.firstChild.toString() + "?"; if (this.min == 0 && this.max == Infinity) return this.firstChild.toString() + "*"; if (this.min == 1 && this.max == Infinity) return this.firstChild.toString() + "+"; return this.firstChild.toString() + "{" + this.min + "," + this.max + "}"; }
javascript
function () { if (this.min == 0 && this.max == 1) return this.firstChild.toString() + "?"; if (this.min == 0 && this.max == Infinity) return this.firstChild.toString() + "*"; if (this.min == 1 && this.max == Infinity) return this.firstChild.toString() + "+"; return this.firstChild.toString() + "{" + this.min + "," + this.max + "}"; }
[ "function", "(", ")", "{", "if", "(", "this", ".", "min", "==", "0", "&&", "this", ".", "max", "==", "1", ")", "return", "this", ".", "firstChild", ".", "toString", "(", ")", "+", "\"?\"", ";", "if", "(", "this", ".", "min", "==", "0", "&&", ...
Used for creating a human readable definition of the grammar.
[ "Used", "for", "creating", "a", "human", "readable", "definition", "of", "the", "grammar", "." ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L654-L662
31,942
cdiggins/myna-parser
myna.js
seq
function seq() { var rules = []; for (var _i = 0; _i < arguments.length; _i++) { rules[_i - 0] = arguments[_i]; } var rs = rules.map(RuleTypeToRule); if (rs.length == 0) throw new Error("At least one rule is expected when calling `seq`"); if (rs.length == 1) return rs[0]; var rule1 = rs[0]; var rule2 = seq.apply(void 0, rs.slice(1)); if (rule1.nonAdvancing && rule2 instanceof Advance) return new AdvanceIf(rule1); else return new Sequence(rule1, rule2); }
javascript
function seq() { var rules = []; for (var _i = 0; _i < arguments.length; _i++) { rules[_i - 0] = arguments[_i]; } var rs = rules.map(RuleTypeToRule); if (rs.length == 0) throw new Error("At least one rule is expected when calling `seq`"); if (rs.length == 1) return rs[0]; var rule1 = rs[0]; var rule2 = seq.apply(void 0, rs.slice(1)); if (rule1.nonAdvancing && rule2 instanceof Advance) return new AdvanceIf(rule1); else return new Sequence(rule1, rule2); }
[ "function", "seq", "(", ")", "{", "var", "rules", "=", "[", "]", ";", "for", "(", "var", "_i", "=", "0", ";", "_i", "<", "arguments", ".", "length", ";", "_i", "++", ")", "{", "rules", "[", "_i", "-", "0", "]", "=", "arguments", "[", "_i", ...
Creates a rule that matches a series of rules in order, and succeeds if they all do
[ "Creates", "a", "rule", "that", "matches", "a", "series", "of", "rules", "in", "order", "and", "succeeds", "if", "they", "all", "do" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L1012-L1028
31,943
cdiggins/myna-parser
myna.js
quantified
function quantified(rule, min, max) { if (min === void 0) { min = 0; } if (max === void 0) { max = Infinity; } if (min === 0 && max === 1) return new Optional(RuleTypeToRule(rule)); else return new Quantified(RuleTypeToRule(rule), min, max); }
javascript
function quantified(rule, min, max) { if (min === void 0) { min = 0; } if (max === void 0) { max = Infinity; } if (min === 0 && max === 1) return new Optional(RuleTypeToRule(rule)); else return new Quantified(RuleTypeToRule(rule), min, max); }
[ "function", "quantified", "(", "rule", ",", "min", ",", "max", ")", "{", "if", "(", "min", "===", "void", "0", ")", "{", "min", "=", "0", ";", "}", "if", "(", "max", "===", "void", "0", ")", "{", "max", "=", "Infinity", ";", "}", "if", "(", ...
Attempts to apply a rule between min and max number of times inclusive. If the maximum is set to Infinity, it will attempt to match as many times as it can, but throw an exception if the parser does not advance
[ "Attempts", "to", "apply", "a", "rule", "between", "min", "and", "max", "number", "of", "times", "inclusive", ".", "If", "the", "maximum", "is", "set", "to", "Infinity", "it", "will", "attempt", "to", "match", "as", "many", "times", "as", "it", "can", ...
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L1063-L1070
31,944
cdiggins/myna-parser
myna.js
log
function log(msg) { if (msg === void 0) { msg = ""; } return action(function (p) { console.log(msg); }).setType("log"); }
javascript
function log(msg) { if (msg === void 0) { msg = ""; } return action(function (p) { console.log(msg); }).setType("log"); }
[ "function", "log", "(", "msg", ")", "{", "if", "(", "msg", "===", "void", "0", ")", "{", "msg", "=", "\"\"", ";", "}", "return", "action", "(", "function", "(", "p", ")", "{", "console", ".", "log", "(", "msg", ")", ";", "}", ")", ".", "setTy...
Logs a message as an action
[ "Logs", "a", "message", "as", "an", "action" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L1147-L1150
31,945
cdiggins/myna-parser
myna.js
guardedSeq
function guardedSeq(condition) { var rules = []; for (var _i = 1; _i < arguments.length; _i++) { rules[_i - 1] = arguments[_i]; } return seq(condition, seq.apply(void 0, rules.map(function (r) { return assert(r); }))).setType("guardedSeq"); }
javascript
function guardedSeq(condition) { var rules = []; for (var _i = 1; _i < arguments.length; _i++) { rules[_i - 1] = arguments[_i]; } return seq(condition, seq.apply(void 0, rules.map(function (r) { return assert(r); }))).setType("guardedSeq"); }
[ "function", "guardedSeq", "(", "condition", ")", "{", "var", "rules", "=", "[", "]", ";", "for", "(", "var", "_i", "=", "1", ";", "_i", "<", "arguments", ".", "length", ";", "_i", "++", ")", "{", "rules", "[", "_i", "-", "1", "]", "=", "argumen...
If first part of a guarded sequence passes then each subsequent rule must pass as well otherwise an exception occurs. This helps create parsers that fail fast, and thus provide better feedback for badly formed input.
[ "If", "first", "part", "of", "a", "guarded", "sequence", "passes", "then", "each", "subsequent", "rule", "must", "pass", "as", "well", "otherwise", "an", "exception", "occurs", ".", "This", "helps", "create", "parsers", "that", "fail", "fast", "and", "thus",...
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L1167-L1173
31,946
cdiggins/myna-parser
myna.js
keywords
function keywords() { var words = []; for (var _i = 0; _i < arguments.length; _i++) { words[_i - 0] = arguments[_i]; } return choice.apply(void 0, words.map(keyword)); }
javascript
function keywords() { var words = []; for (var _i = 0; _i < arguments.length; _i++) { words[_i - 0] = arguments[_i]; } return choice.apply(void 0, words.map(keyword)); }
[ "function", "keywords", "(", ")", "{", "var", "words", "=", "[", "]", ";", "for", "(", "var", "_i", "=", "0", ";", "_i", "<", "arguments", ".", "length", ";", "_i", "++", ")", "{", "words", "[", "_i", "-", "0", "]", "=", "arguments", "[", "_i...
Chooses one of a a list of identifiers
[ "Chooses", "one", "of", "a", "a", "list", "of", "identifiers" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L1206-L1212
31,947
cdiggins/myna-parser
myna.js
parse
function parse(r, s) { var p = new ParseState(s, 0, []); if (!(r instanceof AstRule)) r = r.ast; if (!r.parser(p)) return null; return p && p.nodes ? p.nodes[0] : null; }
javascript
function parse(r, s) { var p = new ParseState(s, 0, []); if (!(r instanceof AstRule)) r = r.ast; if (!r.parser(p)) return null; return p && p.nodes ? p.nodes[0] : null; }
[ "function", "parse", "(", "r", ",", "s", ")", "{", "var", "p", "=", "new", "ParseState", "(", "s", ",", "0", ",", "[", "]", ")", ";", "if", "(", "!", "(", "r", "instanceof", "AstRule", ")", ")", "r", "=", "r", ".", "ast", ";", "if", "(", ...
Returns the root node of the abstract syntax tree created by parsing the rule.
[ "Returns", "the", "root", "node", "of", "the", "abstract", "syntax", "tree", "created", "by", "parsing", "the", "rule", "." ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L1272-L1279
31,948
cdiggins/myna-parser
myna.js
allGrammarRules
function allGrammarRules() { return Object.keys(Myna.allRules).sort().map(function (k) { return Myna.allRules[k]; }); }
javascript
function allGrammarRules() { return Object.keys(Myna.allRules).sort().map(function (k) { return Myna.allRules[k]; }); }
[ "function", "allGrammarRules", "(", ")", "{", "return", "Object", ".", "keys", "(", "Myna", ".", "allRules", ")", ".", "sort", "(", ")", ".", "map", "(", "function", "(", "k", ")", "{", "return", "Myna", ".", "allRules", "[", "k", "]", ";", "}", ...
Returns all rules as an array sorted by name.
[ "Returns", "all", "rules", "as", "an", "array", "sorted", "by", "name", "." ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L1296-L1298
31,949
cdiggins/myna-parser
myna.js
grammarToString
function grammarToString(grammarName) { return grammarRules(grammarName).map(function (r) { return r.fullName + " <- " + r.definition; }).join('\n'); }
javascript
function grammarToString(grammarName) { return grammarRules(grammarName).map(function (r) { return r.fullName + " <- " + r.definition; }).join('\n'); }
[ "function", "grammarToString", "(", "grammarName", ")", "{", "return", "grammarRules", "(", "grammarName", ")", ".", "map", "(", "function", "(", "r", ")", "{", "return", "r", ".", "fullName", "+", "\" <- \"", "+", "r", ".", "definition", ";", "}", ")", ...
Creates a string representation of a grammar
[ "Creates", "a", "string", "representation", "of", "a", "grammar" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L1306-L1308
31,950
cdiggins/myna-parser
myna.js
astSchemaToString
function astSchemaToString(grammarName) { return grammarAstRules(grammarName).map(function (r) { return r.name + " <- " + r.astRuleDefn(); }).join('\n'); }
javascript
function astSchemaToString(grammarName) { return grammarAstRules(grammarName).map(function (r) { return r.name + " <- " + r.astRuleDefn(); }).join('\n'); }
[ "function", "astSchemaToString", "(", "grammarName", ")", "{", "return", "grammarAstRules", "(", "grammarName", ")", ".", "map", "(", "function", "(", "r", ")", "{", "return", "r", ".", "name", "+", "\" <- \"", "+", "r", ".", "astRuleDefn", "(", ")", ";"...
Creates a string representation of the AST schema generated by parsing the grammar
[ "Creates", "a", "string", "representation", "of", "the", "AST", "schema", "generated", "by", "parsing", "the", "grammar" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L1311-L1313
31,951
cdiggins/myna-parser
myna.js
registerGrammar
function registerGrammar(grammarName, grammar, defaultRule) { for (var k in grammar) { if (grammar[k] instanceof Rule) { var rule = grammar[k]; rule.setName(grammarName, k); Myna.allRules[rule.fullName] = rule; } } Myna.grammars[grammarName] = grammar; if (defaultRule) { Myna.parsers[grammarName] = function (text) { return parse(defaultRule, text); }; } return grammar; }
javascript
function registerGrammar(grammarName, grammar, defaultRule) { for (var k in grammar) { if (grammar[k] instanceof Rule) { var rule = grammar[k]; rule.setName(grammarName, k); Myna.allRules[rule.fullName] = rule; } } Myna.grammars[grammarName] = grammar; if (defaultRule) { Myna.parsers[grammarName] = function (text) { return parse(defaultRule, text); }; } return grammar; }
[ "function", "registerGrammar", "(", "grammarName", ",", "grammar", ",", "defaultRule", ")", "{", "for", "(", "var", "k", "in", "grammar", ")", "{", "if", "(", "grammar", "[", "k", "]", "instanceof", "Rule", ")", "{", "var", "rule", "=", "grammar", "[",...
Initializes and register a grammar object and all of the rules. Sets names for all of the rules from the name of the field it is associated with combined with the name of the grammar. Each rule is stored in Myna.rules and each grammar is stored in Myna.grammars.
[ "Initializes", "and", "register", "a", "grammar", "object", "and", "all", "of", "the", "rules", ".", "Sets", "names", "for", "all", "of", "the", "rules", "from", "the", "name", "of", "the", "field", "it", "is", "associated", "with", "combined", "with", "...
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L1318-L1331
31,952
cdiggins/myna-parser
myna.js
RuleTypeToRule
function RuleTypeToRule(rule) { if (rule instanceof Rule) return rule; if (typeof (rule) === "string") return text(rule); if (typeof (rule) === "boolean") return rule ? Myna.truePredicate : Myna.falsePredicate; throw new Error("Invalid rule type: " + rule); }
javascript
function RuleTypeToRule(rule) { if (rule instanceof Rule) return rule; if (typeof (rule) === "string") return text(rule); if (typeof (rule) === "boolean") return rule ? Myna.truePredicate : Myna.falsePredicate; throw new Error("Invalid rule type: " + rule); }
[ "function", "RuleTypeToRule", "(", "rule", ")", "{", "if", "(", "rule", "instanceof", "Rule", ")", "return", "rule", ";", "if", "(", "typeof", "(", "rule", ")", "===", "\"string\"", ")", "return", "text", "(", "rule", ")", ";", "if", "(", "typeof", "...
Given a RuleType returns an instance of a Rule.
[ "Given", "a", "RuleType", "returns", "an", "instance", "of", "a", "Rule", "." ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/myna.js#L1342-L1350
31,953
cdiggins/myna-parser
grammars/grammar_arithmetic.js
CreateArithmeticGrammar
function CreateArithmeticGrammar(myna) { // Setup a shorthand for the Myna parsing library object let m = myna; // Construct a grammar let g = new function() { // These are helper rules, they do not create nodes in the parse tree. this.fraction = m.seq(".", m.digit.zeroOrMore); this.plusOrMinus = m.char("+-"); this.exponent = m.seq(m.char("eE"), this.plusOrMinus.opt, m.digits); this.comma = m.text(",").ws; // Using a lazy evaluation rule to allow recursive rule definitions let _this = this; this.expr = m.delay(function() { return _this.sum; }); // The following rules create nodes in the abstract syntax tree this.number = m.seq(m.integer, this.fraction.opt, this.exponent.opt).ast; this.parenExpr = m.parenthesized(this.expr.ws).ast; this.leafExpr = m.choice(this.parenExpr, this.number.ws); this.prefixOp = this.plusOrMinus.ast; this.prefixExpr = m.seq(this.prefixOp.ws.zeroOrMore, this.leafExpr).ast; this.divExpr = m.seq(m.char("/").ws, this.prefixExpr).ast; this.mulExpr = m.seq(m.char("*").ws, this.prefixExpr).ast; this.product = m.seq(this.prefixExpr.ws, this.mulExpr.or(this.divExpr).zeroOrMore).ast; this.subExpr = m.seq(m.char("-").ws, this.product).ast; this.addExpr = m.seq(m.char("+").ws, this.product).ast; this.sum = m.seq(this.product, this.addExpr.or(this.subExpr).zeroOrMore).ast; }; // Register the grammar, providing a name and the default parse rule return myna.registerGrammar("arithmetic", g, g.expr); }
javascript
function CreateArithmeticGrammar(myna) { // Setup a shorthand for the Myna parsing library object let m = myna; // Construct a grammar let g = new function() { // These are helper rules, they do not create nodes in the parse tree. this.fraction = m.seq(".", m.digit.zeroOrMore); this.plusOrMinus = m.char("+-"); this.exponent = m.seq(m.char("eE"), this.plusOrMinus.opt, m.digits); this.comma = m.text(",").ws; // Using a lazy evaluation rule to allow recursive rule definitions let _this = this; this.expr = m.delay(function() { return _this.sum; }); // The following rules create nodes in the abstract syntax tree this.number = m.seq(m.integer, this.fraction.opt, this.exponent.opt).ast; this.parenExpr = m.parenthesized(this.expr.ws).ast; this.leafExpr = m.choice(this.parenExpr, this.number.ws); this.prefixOp = this.plusOrMinus.ast; this.prefixExpr = m.seq(this.prefixOp.ws.zeroOrMore, this.leafExpr).ast; this.divExpr = m.seq(m.char("/").ws, this.prefixExpr).ast; this.mulExpr = m.seq(m.char("*").ws, this.prefixExpr).ast; this.product = m.seq(this.prefixExpr.ws, this.mulExpr.or(this.divExpr).zeroOrMore).ast; this.subExpr = m.seq(m.char("-").ws, this.product).ast; this.addExpr = m.seq(m.char("+").ws, this.product).ast; this.sum = m.seq(this.product, this.addExpr.or(this.subExpr).zeroOrMore).ast; }; // Register the grammar, providing a name and the default parse rule return myna.registerGrammar("arithmetic", g, g.expr); }
[ "function", "CreateArithmeticGrammar", "(", "myna", ")", "{", "// Setup a shorthand for the Myna parsing library object", "let", "m", "=", "myna", ";", "// Construct a grammar ", "let", "g", "=", "new", "function", "(", ")", "{", "// These are helper rules, they do not crea...
Defines a grammar for basic arithmetic
[ "Defines", "a", "grammar", "for", "basic", "arithmetic" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/grammars/grammar_arithmetic.js#L4-L38
31,954
cdiggins/myna-parser
tools/myna_mustache_expander.js
mergeObjects
function mergeObjects(a, b) { var r = { }; for (var k in a) r[k] = a[k]; for (var k in b) r[k] = b[k]; return r; }
javascript
function mergeObjects(a, b) { var r = { }; for (var k in a) r[k] = a[k]; for (var k in b) r[k] = b[k]; return r; }
[ "function", "mergeObjects", "(", "a", ",", "b", ")", "{", "var", "r", "=", "{", "}", ";", "for", "(", "var", "k", "in", "a", ")", "r", "[", "k", "]", "=", "a", "[", "k", "]", ";", "for", "(", "var", "k", "in", "b", ")", "r", "[", "k", ...
Creates a new object containing the properties of the first object and the second object. If any value has the same key in both values, the second object overrides the first.
[ "Creates", "a", "new", "object", "containing", "the", "properties", "of", "the", "first", "object", "and", "the", "second", "object", ".", "If", "any", "value", "has", "the", "same", "key", "in", "both", "values", "the", "second", "object", "overrides", "t...
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/tools/myna_mustache_expander.js#L25-L32
31,955
cdiggins/myna-parser
tools/myna_mustache_expander.js
expandAst
function expandAst(ast, data, lines) { if (lines == undefined) lines = []; // If there is a child "key" get the value associated with it. let keyNode = ast.child("key"); let key = keyNode ? keyNode.allText : ""; let val = data ? (key in data ? data[key] : "") : ""; // Functions are not supported if (typeof(val) == 'function') throw new Exception('Functions are not supported'); switch (ast.rule.name) { case "document": case "sectionContent": ast.children.forEach(function(c) { expandAst(c, data, lines); }); return lines; case "comment": return lines; case "plainText": lines.push(ast.allText); return lines; case "section": let content = ast.child("sectionContent"); if (typeof val === "boolean" || typeof val === "number" || typeof val === "string") { if (val) expandAst(content, data, lines); } else if (val instanceof Array) { for (let x of val) expandAst(content, mergeObjects(data, x), lines); } else { expandAst(content, mergeObjects(data, val), lines); } return lines; case "invertedSection": if (!val || ((val instanceof Array) && val.length == 0)) expandAst(ast.child("sectionContent"), data, lines); return lines; case "escapedVar": if (val) lines.push( expand(escapeHtmlChars(String(val)), data)); return lines; case "unescapedVar": if (val) lines.push( expand(String(val), data)); return lines; } throw "Unrecognized AST node " + ast.rule.name; }
javascript
function expandAst(ast, data, lines) { if (lines == undefined) lines = []; // If there is a child "key" get the value associated with it. let keyNode = ast.child("key"); let key = keyNode ? keyNode.allText : ""; let val = data ? (key in data ? data[key] : "") : ""; // Functions are not supported if (typeof(val) == 'function') throw new Exception('Functions are not supported'); switch (ast.rule.name) { case "document": case "sectionContent": ast.children.forEach(function(c) { expandAst(c, data, lines); }); return lines; case "comment": return lines; case "plainText": lines.push(ast.allText); return lines; case "section": let content = ast.child("sectionContent"); if (typeof val === "boolean" || typeof val === "number" || typeof val === "string") { if (val) expandAst(content, data, lines); } else if (val instanceof Array) { for (let x of val) expandAst(content, mergeObjects(data, x), lines); } else { expandAst(content, mergeObjects(data, val), lines); } return lines; case "invertedSection": if (!val || ((val instanceof Array) && val.length == 0)) expandAst(ast.child("sectionContent"), data, lines); return lines; case "escapedVar": if (val) lines.push( expand(escapeHtmlChars(String(val)), data)); return lines; case "unescapedVar": if (val) lines.push( expand(String(val), data)); return lines; } throw "Unrecognized AST node " + ast.rule.name; }
[ "function", "expandAst", "(", "ast", ",", "data", ",", "lines", ")", "{", "if", "(", "lines", "==", "undefined", ")", "lines", "=", "[", "]", ";", "// If there is a child \"key\" get the value associated with it. ", "let", "keyNode", "=", "ast", ".", "child", ...
Given an AST node, a data object, and an optional array of string, converts the nodes expanding the reserved characters.
[ "Given", "an", "AST", "node", "a", "data", "object", "and", "an", "optional", "array", "of", "string", "converts", "the", "nodes", "expanding", "the", "reserved", "characters", "." ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/tools/myna_mustache_expander.js#L36-L98
31,956
cdiggins/myna-parser
tools/myna_mustache_expander.js
expand
function expand(template, data) { if (template.indexOf("{{") >= 0) { let ast = myna.parsers.mustache(template); let lines = expandAst(ast, data); return lines.join(""); } else { return template; } }
javascript
function expand(template, data) { if (template.indexOf("{{") >= 0) { let ast = myna.parsers.mustache(template); let lines = expandAst(ast, data); return lines.join(""); } else { return template; } }
[ "function", "expand", "(", "template", ",", "data", ")", "{", "if", "(", "template", ".", "indexOf", "(", "\"{{\"", ")", ">=", "0", ")", "{", "let", "ast", "=", "myna", ".", "parsers", ".", "mustache", "(", "template", ")", ";", "let", "lines", "="...
Expands text containing CTemplate delimiters "{{" using the data object
[ "Expands", "text", "containing", "CTemplate", "delimiters", "{{", "using", "the", "data", "object" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/tools/myna_mustache_expander.js#L101-L110
31,957
cdiggins/myna-parser
tools/myna_escape_html_chars.js
escapeHtmlChars
function escapeHtmlChars(text) { let ast = myna.parsers.html_reserved_chars(text); if (!ast.children) return ""; return ast.children.map(astNodeToHtmlText).join(''); }
javascript
function escapeHtmlChars(text) { let ast = myna.parsers.html_reserved_chars(text); if (!ast.children) return ""; return ast.children.map(astNodeToHtmlText).join(''); }
[ "function", "escapeHtmlChars", "(", "text", ")", "{", "let", "ast", "=", "myna", ".", "parsers", ".", "html_reserved_chars", "(", "text", ")", ";", "if", "(", "!", "ast", ".", "children", ")", "return", "\"\"", ";", "return", "ast", ".", "children", "....
Returns a string, replacing all of the reserved characters with entities
[ "Returns", "a", "string", "replacing", "all", "of", "the", "reserved", "characters", "with", "entities" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/tools/myna_escape_html_chars.js#L37-L43
31,958
cdiggins/myna-parser
grammars/grammar_pithy.js
guardedSeq
function guardedSeq() { var args = Array.prototype.slice.call(arguments, 1).map(function(r) { return m.seq(m.assert(r), _this.ws); }); return m.seq(arguments[0], _this.ws, m.seq.apply(m, args)); }
javascript
function guardedSeq() { var args = Array.prototype.slice.call(arguments, 1).map(function(r) { return m.seq(m.assert(r), _this.ws); }); return m.seq(arguments[0], _this.ws, m.seq.apply(m, args)); }
[ "function", "guardedSeq", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ".", "map", "(", "function", "(", "r", ")", "{", "return", "m", ".", "seq", "(", "m", ".", "assert...
If the first rule argument passes, all subsequent rules must pass or an assert will throw
[ "If", "the", "first", "rule", "argument", "passes", "all", "subsequent", "rules", "must", "pass", "or", "an", "assert", "will", "throw" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/grammars/grammar_pithy.js#L42-L45
31,959
cdiggins/myna-parser
grammars/grammar_pithy.js
commaList
function commaList(r, trailing = true) { var result = r.then(guardedSeq(_this.comma, r).zeroOrMore); if (trailing) return result.then(_this.comma.opt); else return result; }
javascript
function commaList(r, trailing = true) { var result = r.then(guardedSeq(_this.comma, r).zeroOrMore); if (trailing) return result.then(_this.comma.opt); else return result; }
[ "function", "commaList", "(", "r", ",", "trailing", "=", "true", ")", "{", "var", "result", "=", "r", ".", "then", "(", "guardedSeq", "(", "_this", ".", "comma", ",", "r", ")", ".", "zeroOrMore", ")", ";", "if", "(", "trailing", ")", "return", "res...
Comma delimited list with a trailing comma
[ "Comma", "delimited", "list", "with", "a", "trailing", "comma" ]
24e07fe107e3814b412d537aca365142844514ec
https://github.com/cdiggins/myna-parser/blob/24e07fe107e3814b412d537aca365142844514ec/grammars/grammar_pithy.js#L48-L52
31,960
twolfson/layout
lib/layout.js
Layout
function Layout(algorithmName, options) { // Save the algorithmName as our algorithm (assume function) var algorithm = algorithmName || 'top-down'; // If the algorithm is a string, look it up if (typeof algorithm === 'string') { algorithm = algorithms[algorithmName]; // Assert that the algorithm was found assert(algorithm, 'Sorry, the \'' + algorithmName +'\' algorithm could not be loaded.'); } // Create a new PackingSmith with our algorithm and return var retSmith = new PackingSmith(algorithm, options); return retSmith; }
javascript
function Layout(algorithmName, options) { // Save the algorithmName as our algorithm (assume function) var algorithm = algorithmName || 'top-down'; // If the algorithm is a string, look it up if (typeof algorithm === 'string') { algorithm = algorithms[algorithmName]; // Assert that the algorithm was found assert(algorithm, 'Sorry, the \'' + algorithmName +'\' algorithm could not be loaded.'); } // Create a new PackingSmith with our algorithm and return var retSmith = new PackingSmith(algorithm, options); return retSmith; }
[ "function", "Layout", "(", "algorithmName", ",", "options", ")", "{", "// Save the algorithmName as our algorithm (assume function)", "var", "algorithm", "=", "algorithmName", "||", "'top-down'", ";", "// If the algorithm is a string, look it up", "if", "(", "typeof", "algori...
Layout adds items in an algorithmic fashion @constructor @param {String|Object} [algorithm="top-down"] Name of algorithm or custom algorithm to use @param {Mixed} [options] Options to provide for the algorithm
[ "Layout", "adds", "items", "in", "an", "algorithmic", "fashion" ]
eaf4c254dee37afbde0eec2c82b343869c6049db
https://github.com/twolfson/layout/blob/eaf4c254dee37afbde0eec2c82b343869c6049db/lib/layout.js#L12-L27
31,961
doowb/github-content
index.js
GithubContent
function GithubContent(options) { if (!(this instanceof GithubContent)) { return new GithubContent(options); } // setup our specific options var opts = extend({branch: 'master'}, options); opts.json = false; opts.apiurl = 'https://raw.githubusercontent.com'; GithubBase.call(this, opts); this.options = extend({}, opts, this.options); }
javascript
function GithubContent(options) { if (!(this instanceof GithubContent)) { return new GithubContent(options); } // setup our specific options var opts = extend({branch: 'master'}, options); opts.json = false; opts.apiurl = 'https://raw.githubusercontent.com'; GithubBase.call(this, opts); this.options = extend({}, opts, this.options); }
[ "function", "GithubContent", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "GithubContent", ")", ")", "{", "return", "new", "GithubContent", "(", "options", ")", ";", "}", "// setup our specific options", "var", "opts", "=", "extend", ...
Create an instance of GithubContent to setup downloading of files. ```js var options = { owner: 'doowb', repo: 'github-content', branch: 'master' // defaults to master }; var gc = new GithubContent(options); ``` @param {Object} `options` Options to set on instance. Additional options passed to [github-base] @param {String} `options.owner` Set the owner to be used for each file. @param {String} `options.repo` Set the repository to be used for each file. @param {String} `options.branch` Set the branch to be used for each file. Defaults to `master` @api public
[ "Create", "an", "instance", "of", "GithubContent", "to", "setup", "downloading", "of", "files", "." ]
1348f808083d14dde4f986ff9f93ee543183e1d3
https://github.com/doowb/github-content/blob/1348f808083d14dde4f986ff9f93ee543183e1d3/index.js#L33-L44
31,962
twolfson/layout
lib/smiths/packing.smith.js
function () { // Grab the items var items = this.items; // Find the most negative x and y var minX = Infinity, minY = Infinity; items.forEach(function (item) { var coords = item; minX = Math.min(minX, coords.x); minY = Math.min(minY, coords.y); }); // Offset each item by -minX, -minY; effectively resetting to 0, 0 items.forEach(function (item) { var coords = item; coords.x -= minX; coords.y -= minY; }); }
javascript
function () { // Grab the items var items = this.items; // Find the most negative x and y var minX = Infinity, minY = Infinity; items.forEach(function (item) { var coords = item; minX = Math.min(minX, coords.x); minY = Math.min(minY, coords.y); }); // Offset each item by -minX, -minY; effectively resetting to 0, 0 items.forEach(function (item) { var coords = item; coords.x -= minX; coords.y -= minY; }); }
[ "function", "(", ")", "{", "// Grab the items", "var", "items", "=", "this", ".", "items", ";", "// Find the most negative x and y", "var", "minX", "=", "Infinity", ",", "minY", "=", "Infinity", ";", "items", ".", "forEach", "(", "function", "(", "item", ")"...
Method to normalize coordinates to 0, 0 This is bad to do mid-addition since it messes up the algorithm
[ "Method", "to", "normalize", "coordinates", "to", "0", "0", "This", "is", "bad", "to", "do", "mid", "-", "addition", "since", "it", "messes", "up", "the", "algorithm" ]
eaf4c254dee37afbde0eec2c82b343869c6049db
https://github.com/twolfson/layout/blob/eaf4c254dee37afbde0eec2c82b343869c6049db/lib/smiths/packing.smith.js#L24-L43
31,963
giapnguyen74/nextql
samples/mongoose/index.js
normalizeFields
function normalizeFields(fields) { const _fields = {}; Object.keys(fields).forEach(k => { if (fields[k].constructor == Object && !fields[k].type) { _fields[k] = normalizeFields(fields[k]); } else { _fields[k] = 1; } }); return _fields; }
javascript
function normalizeFields(fields) { const _fields = {}; Object.keys(fields).forEach(k => { if (fields[k].constructor == Object && !fields[k].type) { _fields[k] = normalizeFields(fields[k]); } else { _fields[k] = 1; } }); return _fields; }
[ "function", "normalizeFields", "(", "fields", ")", "{", "const", "_fields", "=", "{", "}", ";", "Object", ".", "keys", "(", "fields", ")", ".", "forEach", "(", "k", "=>", "{", "if", "(", "fields", "[", "k", "]", ".", "constructor", "==", "Object", ...
Simply convert mongoose schema to nextql fields
[ "Simply", "convert", "mongoose", "schema", "to", "nextql", "fields" ]
92c7b908fe3abadd1a5a3b85ae470c5e6208ad4e
https://github.com/giapnguyen74/nextql/blob/92c7b908fe3abadd1a5a3b85ae470c5e6208ad4e/samples/mongoose/index.js#L4-L14
31,964
giapnguyen74/nextql
src/resolvers.js
resolve_type_define
function resolve_type_define(nextql, fieldValue, fieldDefine, fieldPath) { let fd = fieldDefine; // First phrase resolve fieldDefine is auto or function into final fieldDefine if (fd === 1) { if (isPrimitive(fieldValue)) { return "*"; } else { fd = nextql.resolveType(fieldValue); nextql.afterResolveTypeHooks.forEach( hook => (fd = hook(fieldValue) || fd) ); } } if (typeof fd == "function") { fd = fieldDefine(fieldValue); } // Second phrase resolve fieldDefine is explicit into fieldModel name; if (fd == undefined) { return new NextQLError( "Cannot resolve model: " + JSON.stringify(fieldDefine), { path: fieldPath } ); } // InlineModel if (fd.constructor && fd.constructor == Object) { return new InlineModel(fd); } // ScalarModel if (fd === "*") { return "*"; } // NamedModel const model = nextql.model(fd); if (!model) { return new NextQLError("Model not found: " + fd, { path: fieldPath }); } return model; }
javascript
function resolve_type_define(nextql, fieldValue, fieldDefine, fieldPath) { let fd = fieldDefine; // First phrase resolve fieldDefine is auto or function into final fieldDefine if (fd === 1) { if (isPrimitive(fieldValue)) { return "*"; } else { fd = nextql.resolveType(fieldValue); nextql.afterResolveTypeHooks.forEach( hook => (fd = hook(fieldValue) || fd) ); } } if (typeof fd == "function") { fd = fieldDefine(fieldValue); } // Second phrase resolve fieldDefine is explicit into fieldModel name; if (fd == undefined) { return new NextQLError( "Cannot resolve model: " + JSON.stringify(fieldDefine), { path: fieldPath } ); } // InlineModel if (fd.constructor && fd.constructor == Object) { return new InlineModel(fd); } // ScalarModel if (fd === "*") { return "*"; } // NamedModel const model = nextql.model(fd); if (!model) { return new NextQLError("Model not found: " + fd, { path: fieldPath }); } return model; }
[ "function", "resolve_type_define", "(", "nextql", ",", "fieldValue", ",", "fieldDefine", ",", "fieldPath", ")", "{", "let", "fd", "=", "fieldDefine", ";", "// First phrase resolve fieldDefine is auto or function into final fieldDefine", "if", "(", "fd", "===", "1", ")",...
Give field value and field define, resolve field model or error field path provided for log @param {*} nextql @param {string} path @param {*} value @param {*} typeDef @return {*} model
[ "Give", "field", "value", "and", "field", "define", "resolve", "field", "model", "or", "error", "field", "path", "provided", "for", "log" ]
92c7b908fe3abadd1a5a3b85ae470c5e6208ad4e
https://github.com/giapnguyen74/nextql/blob/92c7b908fe3abadd1a5a3b85ae470c5e6208ad4e/src/resolvers.js#L36-L81
31,965
giapnguyen74/nextql
src/resolvers.js
resolve_scalar_value
function resolve_scalar_value(nextql, value, valueQuery, info) { if (value == undefined) { set(info.result, info.path, null); return Promise.resolve(); } if (valueQuery !== 1) { const keylen = Object.keys(valueQuery).length; const queryAsObject = valueQuery.$params ? keylen > 1 : keylen > 0; if (queryAsObject) { return Promise.reject( new NextQLError("Cannot query scalar as object", info) ); } } if (isPrimitive(value)) { set(info.result, info.path, value); return Promise.resolve(); } // non-primitive value as scalar, not good solution yet try { set(info.result, info.path, JSON.parse(JSON.stringify(value))); return Promise.resolve(); } catch (e) { return Promise.reject( new NextQLError("Cannot serialize return value", info) ); } }
javascript
function resolve_scalar_value(nextql, value, valueQuery, info) { if (value == undefined) { set(info.result, info.path, null); return Promise.resolve(); } if (valueQuery !== 1) { const keylen = Object.keys(valueQuery).length; const queryAsObject = valueQuery.$params ? keylen > 1 : keylen > 0; if (queryAsObject) { return Promise.reject( new NextQLError("Cannot query scalar as object", info) ); } } if (isPrimitive(value)) { set(info.result, info.path, value); return Promise.resolve(); } // non-primitive value as scalar, not good solution yet try { set(info.result, info.path, JSON.parse(JSON.stringify(value))); return Promise.resolve(); } catch (e) { return Promise.reject( new NextQLError("Cannot serialize return value", info) ); } }
[ "function", "resolve_scalar_value", "(", "nextql", ",", "value", ",", "valueQuery", ",", "info", ")", "{", "if", "(", "value", "==", "undefined", ")", "{", "set", "(", "info", ".", "result", ",", "info", ".", "path", ",", "null", ")", ";", "return", ...
Given value and valueQuery; resolve value as a scalar @param {*} nextql @param {*} value @param {*} valueQuery @param {*} info
[ "Given", "value", "and", "valueQuery", ";", "resolve", "value", "as", "a", "scalar" ]
92c7b908fe3abadd1a5a3b85ae470c5e6208ad4e
https://github.com/giapnguyen74/nextql/blob/92c7b908fe3abadd1a5a3b85ae470c5e6208ad4e/src/resolvers.js#L90-L120
31,966
giapnguyen74/nextql
src/resolvers.js
execute_conditional
function execute_conditional( nextql, value, valueModel, conditional, query, info, context ) { let model; const modelName = valueModel.check( value, conditional, query.$params, context, info ); if (modelName instanceof Error) { return Promise.reject(modelName); } if (modelName === true) { model = valueModel; } if (typeof modelName == "string" && modelName != "*") { model = nextql.model(modelName); } if (!model) return Promise.resolve(); return resolve_object_value(nextql, value, model, query, info, context); }
javascript
function execute_conditional( nextql, value, valueModel, conditional, query, info, context ) { let model; const modelName = valueModel.check( value, conditional, query.$params, context, info ); if (modelName instanceof Error) { return Promise.reject(modelName); } if (modelName === true) { model = valueModel; } if (typeof modelName == "string" && modelName != "*") { model = nextql.model(modelName); } if (!model) return Promise.resolve(); return resolve_object_value(nextql, value, model, query, info, context); }
[ "function", "execute_conditional", "(", "nextql", ",", "value", ",", "valueModel", ",", "conditional", ",", "query", ",", "info", ",", "context", ")", "{", "let", "model", ";", "const", "modelName", "=", "valueModel", ".", "check", "(", "value", ",", "cond...
Given value, valueModel and conditional path; call conditional function and process result @param {*} nextql @param {*} value @param {*} valueModel @param {*} conditionalQuery @param {*} info @param {*} context
[ "Given", "value", "valueModel", "and", "conditional", "path", ";", "call", "conditional", "function", "and", "process", "result" ]
92c7b908fe3abadd1a5a3b85ae470c5e6208ad4e
https://github.com/giapnguyen74/nextql/blob/92c7b908fe3abadd1a5a3b85ae470c5e6208ad4e/src/resolvers.js#L131-L165
31,967
giapnguyen74/nextql
src/resolvers.js
resolve_object_value
function resolve_object_value( nextql, value, valueModel, valueQuery, info, context ) { if (value == undefined) { set(info.result, info.path, null); return Promise.resolve(); } if (isPrimitive(value)) { return Promise.reject( new NextQLError("Cannot query scalar as " + valueModel.name, info) ); } return Promise.all( Object.keys(valueQuery).map(path => { if (path == "$params") return; const fieldName = path.split(nextql.aliasSeparator, 1)[0]; //Conditional query? if (fieldName[0] === "?") { return execute_conditional( nextql, value, valueModel, fieldName, valueQuery[path], info, context ); } const newInfo = info_append_path(info, path); return valueModel .get( value, fieldName, valueQuery[path].$params, context, newInfo ) .then(fieldValue => { let fieldDef; if (valueModel.computed[fieldName]) { fieldDef = valueModel.fields[fieldName] || 1; } else { fieldDef = valueModel.fields[fieldName]; } return resolve_value( nextql, fieldValue, fieldDef, valueQuery[path], newInfo, context ); }); }) ); }
javascript
function resolve_object_value( nextql, value, valueModel, valueQuery, info, context ) { if (value == undefined) { set(info.result, info.path, null); return Promise.resolve(); } if (isPrimitive(value)) { return Promise.reject( new NextQLError("Cannot query scalar as " + valueModel.name, info) ); } return Promise.all( Object.keys(valueQuery).map(path => { if (path == "$params") return; const fieldName = path.split(nextql.aliasSeparator, 1)[0]; //Conditional query? if (fieldName[0] === "?") { return execute_conditional( nextql, value, valueModel, fieldName, valueQuery[path], info, context ); } const newInfo = info_append_path(info, path); return valueModel .get( value, fieldName, valueQuery[path].$params, context, newInfo ) .then(fieldValue => { let fieldDef; if (valueModel.computed[fieldName]) { fieldDef = valueModel.fields[fieldName] || 1; } else { fieldDef = valueModel.fields[fieldName]; } return resolve_value( nextql, fieldValue, fieldDef, valueQuery[path], newInfo, context ); }); }) ); }
[ "function", "resolve_object_value", "(", "nextql", ",", "value", ",", "valueModel", ",", "valueQuery", ",", "info", ",", "context", ")", "{", "if", "(", "value", "==", "undefined", ")", "{", "set", "(", "info", ".", "result", ",", "info", ".", "path", ...
Given value, valueModel, valueQuery; recursive resolve field value @param {*} nextql @param {*} value @param {*} valueModel @param {*} valueQuery @param {*} info @param {*} context
[ "Given", "value", "valueModel", "valueQuery", ";", "recursive", "resolve", "field", "value" ]
92c7b908fe3abadd1a5a3b85ae470c5e6208ad4e
https://github.com/giapnguyen74/nextql/blob/92c7b908fe3abadd1a5a3b85ae470c5e6208ad4e/src/resolvers.js#L176-L241
31,968
frapontillo/node-rdp
lib/rdp-file.js
buildRdpFile
function buildRdpFile(config) { var deferred = Q.defer(); var fileContent = getRdpFileContent(config); var fileName = path.normalize(os.tmpdir() + '/' + sanitize(config.address) + '.rdp'); Q.nfcall(fs.writeFile, fileName, fileContent) .then(function() { deferred.resolve(fileName); }) .fail(deferred.reject); return deferred.promise; }
javascript
function buildRdpFile(config) { var deferred = Q.defer(); var fileContent = getRdpFileContent(config); var fileName = path.normalize(os.tmpdir() + '/' + sanitize(config.address) + '.rdp'); Q.nfcall(fs.writeFile, fileName, fileContent) .then(function() { deferred.resolve(fileName); }) .fail(deferred.reject); return deferred.promise; }
[ "function", "buildRdpFile", "(", "config", ")", "{", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "var", "fileContent", "=", "getRdpFileContent", "(", "config", ")", ";", "var", "fileName", "=", "path", ".", "normalize", "(", "os", ".", "t...
Returns a promise that will be resolved as soon as the file is created. @param config @returns {promise|*|Q.promise}
[ "Returns", "a", "promise", "that", "will", "be", "resolved", "as", "soon", "as", "the", "file", "is", "created", "." ]
0d4e0acb15923aab29a86ee42c84af6bef8c50c1
https://github.com/frapontillo/node-rdp/blob/0d4e0acb15923aab29a86ee42c84af6bef8c50c1/lib/rdp-file.js#L202-L212
31,969
gchudnov/inkjet
build/lib/magic.js
magic
function magic(buf, cb) { setTimeout(() => { const sampleLength = 24; const sample = buf.slice(0, sampleLength).toString('hex'); // lookup data const found = Object.keys(_magicDb2.default).find(it => { return sample.indexOf(it) != -1; }); if (found) { cb(null, _magicDb2.default[found]); } else { cb(new Error('Magic number not found')); } }, 0); }
javascript
function magic(buf, cb) { setTimeout(() => { const sampleLength = 24; const sample = buf.slice(0, sampleLength).toString('hex'); // lookup data const found = Object.keys(_magicDb2.default).find(it => { return sample.indexOf(it) != -1; }); if (found) { cb(null, _magicDb2.default[found]); } else { cb(new Error('Magic number not found')); } }, 0); }
[ "function", "magic", "(", "buf", ",", "cb", ")", "{", "setTimeout", "(", "(", ")", "=>", "{", "const", "sampleLength", "=", "24", ";", "const", "sample", "=", "buf", ".", "slice", "(", "0", ",", "sampleLength", ")", ".", "toString", "(", "'hex'", "...
Lookup the magic number in magic-number DB @param {Buffer} buf Data buffer @param {function} cb Callback to invoke on completion
[ "Lookup", "the", "magic", "number", "in", "magic", "-", "number", "DB" ]
7ee7e1a67562e083c60be93864fad86d1ac8eb30
https://github.com/gchudnov/inkjet/blob/7ee7e1a67562e083c60be93864fad86d1ac8eb30/build/lib/magic.js#L19-L34
31,970
gchudnov/inkjet
build/lib/encode.js
encode
function encode(buf, options, cb) { try { const imageData = { data: buf, width: options.width, height: options.height }; const data = (0, _encoder2.default)(imageData, options.quality); cb(null, data); } catch (err) { cb(err); } }
javascript
function encode(buf, options, cb) { try { const imageData = { data: buf, width: options.width, height: options.height }; const data = (0, _encoder2.default)(imageData, options.quality); cb(null, data); } catch (err) { cb(err); } }
[ "function", "encode", "(", "buf", ",", "options", ",", "cb", ")", "{", "try", "{", "const", "imageData", "=", "{", "data", ":", "buf", ",", "width", ":", "options", ".", "width", ",", "height", ":", "options", ".", "height", "}", ";", "const", "dat...
Encode the data to JPEG format @param buf Buffer|Uint8Array @param options Object { width: number, height: number, quality: number } @param cb Callback to invoke on completion @callback { width: number, height: number, data: Uint8Array }
[ "Encode", "the", "data", "to", "JPEG", "format" ]
7ee7e1a67562e083c60be93864fad86d1ac8eb30
https://github.com/gchudnov/inkjet/blob/7ee7e1a67562e083c60be93864fad86d1ac8eb30/build/lib/encode.js#L23-L35
31,971
gchudnov/inkjet
build/lib/buffer-utils.js
toBuffer
function toBuffer(buf) { if (buf instanceof ArrayBuffer) { return arrayBufferToBuffer(buf); } else if (Buffer.isBuffer(buf)) { return buf; } else if (buf instanceof Uint8Array) { return new Buffer(buf); } else { return buf; // type unknown, trust the user } }
javascript
function toBuffer(buf) { if (buf instanceof ArrayBuffer) { return arrayBufferToBuffer(buf); } else if (Buffer.isBuffer(buf)) { return buf; } else if (buf instanceof Uint8Array) { return new Buffer(buf); } else { return buf; // type unknown, trust the user } }
[ "function", "toBuffer", "(", "buf", ")", "{", "if", "(", "buf", "instanceof", "ArrayBuffer", ")", "{", "return", "arrayBufferToBuffer", "(", "buf", ")", ";", "}", "else", "if", "(", "Buffer", ".", "isBuffer", "(", "buf", ")", ")", "{", "return", "buf",...
Converts the buffer to Buffer @param {Buffer|ArrayBuffer|Uint8Array} buf Input buffer @returns {Buffer}
[ "Converts", "the", "buffer", "to", "Buffer" ]
7ee7e1a67562e083c60be93864fad86d1ac8eb30
https://github.com/gchudnov/inkjet/blob/7ee7e1a67562e083c60be93864fad86d1ac8eb30/build/lib/buffer-utils.js#L18-L28
31,972
gchudnov/inkjet
build/lib/buffer-utils.js
toArrayBuffer
function toArrayBuffer(buf) { if (buf instanceof ArrayBuffer) { return buf; } else if (Buffer.isBuffer(buf)) { return bufferToArrayBuffer(buf); } else if (buf instanceof Uint8Array) { return bufferToArrayBuffer(buf); } else { return buf; // type unknown, trust the user } }
javascript
function toArrayBuffer(buf) { if (buf instanceof ArrayBuffer) { return buf; } else if (Buffer.isBuffer(buf)) { return bufferToArrayBuffer(buf); } else if (buf instanceof Uint8Array) { return bufferToArrayBuffer(buf); } else { return buf; // type unknown, trust the user } }
[ "function", "toArrayBuffer", "(", "buf", ")", "{", "if", "(", "buf", "instanceof", "ArrayBuffer", ")", "{", "return", "buf", ";", "}", "else", "if", "(", "Buffer", ".", "isBuffer", "(", "buf", ")", ")", "{", "return", "bufferToArrayBuffer", "(", "buf", ...
Converts any buffer to ArrayBuffer @param {Buffer|ArrayBuffer|Uint8Array} buf Input buffer @returns {ArrayBuffer}
[ "Converts", "any", "buffer", "to", "ArrayBuffer" ]
7ee7e1a67562e083c60be93864fad86d1ac8eb30
https://github.com/gchudnov/inkjet/blob/7ee7e1a67562e083c60be93864fad86d1ac8eb30/build/lib/buffer-utils.js#L35-L45
31,973
gchudnov/inkjet
build/lib/buffer-utils.js
toUint8Array
function toUint8Array(buf) { if (buf instanceof Uint8Array) { return buf; } else if (buf instanceof ArrayBuffer) { return new Uint8Array(buf); } else if (Buffer.isBuffer(buf)) { return new Uint8Array(buf); } else { return buf; // type unknown, trust the user } }
javascript
function toUint8Array(buf) { if (buf instanceof Uint8Array) { return buf; } else if (buf instanceof ArrayBuffer) { return new Uint8Array(buf); } else if (Buffer.isBuffer(buf)) { return new Uint8Array(buf); } else { return buf; // type unknown, trust the user } }
[ "function", "toUint8Array", "(", "buf", ")", "{", "if", "(", "buf", "instanceof", "Uint8Array", ")", "{", "return", "buf", ";", "}", "else", "if", "(", "buf", "instanceof", "ArrayBuffer", ")", "{", "return", "new", "Uint8Array", "(", "buf", ")", ";", "...
Converts any buffer to Uint8Array @param {Buffer|ArrayBuffer|Uint8Array} buf Input buffer @returns {Uint8Array}
[ "Converts", "any", "buffer", "to", "Uint8Array" ]
7ee7e1a67562e083c60be93864fad86d1ac8eb30
https://github.com/gchudnov/inkjet/blob/7ee7e1a67562e083c60be93864fad86d1ac8eb30/build/lib/buffer-utils.js#L52-L62
31,974
gchudnov/inkjet
build/lib/buffer-utils.js
bufferToArrayBuffer
function bufferToArrayBuffer(buf) { const arr = new ArrayBuffer(buf.length); const view = new Uint8Array(arr); for (let i = 0; i < buf.length; ++i) { view[i] = buf[i]; } return arr; }
javascript
function bufferToArrayBuffer(buf) { const arr = new ArrayBuffer(buf.length); const view = new Uint8Array(arr); for (let i = 0; i < buf.length; ++i) { view[i] = buf[i]; } return arr; }
[ "function", "bufferToArrayBuffer", "(", "buf", ")", "{", "const", "arr", "=", "new", "ArrayBuffer", "(", "buf", ".", "length", ")", ";", "const", "view", "=", "new", "Uint8Array", "(", "arr", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<...
Buffer -> ArrayBuffer @param {Buffer|Uint8Array} buf @returns {ArrayBuffer}
[ "Buffer", "-", ">", "ArrayBuffer" ]
7ee7e1a67562e083c60be93864fad86d1ac8eb30
https://github.com/gchudnov/inkjet/blob/7ee7e1a67562e083c60be93864fad86d1ac8eb30/build/lib/buffer-utils.js#L86-L93
31,975
gchudnov/inkjet
build/lib/decode.js
decode
function decode(buf, options, cb) { function getData(j, width, height) { const dest = { width: width, height: height, data: new Uint8Array(width * height * 4) }; j.copyToImageData(dest); return dest.data; } try { const j = new _jpg.JpegImage(); j.parse(buf); const width = options.width || j.width; const height = options.height || j.height; const data = getData(j, width, height); const result = { width: width, height: height, data: data }; cb(null, result); } catch (err) { if (typeof err === 'string') { // jpg.js throws 'string' values, convert to an Error err = new Error(err); } cb(err); } }
javascript
function decode(buf, options, cb) { function getData(j, width, height) { const dest = { width: width, height: height, data: new Uint8Array(width * height * 4) }; j.copyToImageData(dest); return dest.data; } try { const j = new _jpg.JpegImage(); j.parse(buf); const width = options.width || j.width; const height = options.height || j.height; const data = getData(j, width, height); const result = { width: width, height: height, data: data }; cb(null, result); } catch (err) { if (typeof err === 'string') { // jpg.js throws 'string' values, convert to an Error err = new Error(err); } cb(err); } }
[ "function", "decode", "(", "buf", ",", "options", ",", "cb", ")", "{", "function", "getData", "(", "j", ",", "width", ",", "height", ")", "{", "const", "dest", "=", "{", "width", ":", "width", ",", "height", ":", "height", ",", "data", ":", "new", ...
Decode the JPEG data @param buf Uint8Array @param options Object { width: number, height: number } @param cb Callback to invoke on completion @callback { width: number, height: number, data: Uint8Array }
[ "Decode", "the", "JPEG", "data" ]
7ee7e1a67562e083c60be93864fad86d1ac8eb30
https://github.com/gchudnov/inkjet/blob/7ee7e1a67562e083c60be93864fad86d1ac8eb30/build/lib/decode.js#L19-L52
31,976
gchudnov/inkjet
build/lib/exif.js
exif
function exif(buf, options, cb) { try { const exif = new _ExifReader.ExifReader(); exif.load(buf); // The MakerNote tag can be really large. Remove it to lower memory usage. if (!options.hasOwnProperty('hasMakerNote') || !options.hasMakerNote) { exif.deleteTag('MakerNote'); } const metadata = exif.getAllTags(); cb(null, metadata); } catch (err) { if (err.message === 'No Exif data') { cb(null, {}); } else { cb(err); } } }
javascript
function exif(buf, options, cb) { try { const exif = new _ExifReader.ExifReader(); exif.load(buf); // The MakerNote tag can be really large. Remove it to lower memory usage. if (!options.hasOwnProperty('hasMakerNote') || !options.hasMakerNote) { exif.deleteTag('MakerNote'); } const metadata = exif.getAllTags(); cb(null, metadata); } catch (err) { if (err.message === 'No Exif data') { cb(null, {}); } else { cb(err); } } }
[ "function", "exif", "(", "buf", ",", "options", ",", "cb", ")", "{", "try", "{", "const", "exif", "=", "new", "_ExifReader", ".", "ExifReader", "(", ")", ";", "exif", ".", "load", "(", "buf", ")", ";", "// The MakerNote tag can be really large. Remove it to ...
Read EXIF data from the provided buffer @param buf ArrayBuffer @param options Object { hasMakerNote: true|false } @param cb Callback to invoke on completion @callback Object { name: value, ... }
[ "Read", "EXIF", "data", "from", "the", "provided", "buffer" ]
7ee7e1a67562e083c60be93864fad86d1ac8eb30
https://github.com/gchudnov/inkjet/blob/7ee7e1a67562e083c60be93864fad86d1ac8eb30/build/lib/exif.js#L19-L39
31,977
gchudnov/inkjet
build/lib/info.js
info
function info(buf, cb) { setTimeout(() => { const info = (0, _imageinfo2.default)(buf); if (!info) { cb(new Error('Cannot get image info')); } else { cb(null, { type: info.type, mimeType: info.mimeType, extension: info.format.toLowerCase(), width: info.width, height: info.height }); } }, 0); }
javascript
function info(buf, cb) { setTimeout(() => { const info = (0, _imageinfo2.default)(buf); if (!info) { cb(new Error('Cannot get image info')); } else { cb(null, { type: info.type, mimeType: info.mimeType, extension: info.format.toLowerCase(), width: info.width, height: info.height }); } }, 0); }
[ "function", "info", "(", "buf", ",", "cb", ")", "{", "setTimeout", "(", "(", ")", "=>", "{", "const", "info", "=", "(", "0", ",", "_imageinfo2", ".", "default", ")", "(", "buf", ")", ";", "if", "(", "!", "info", ")", "{", "cb", "(", "new", "E...
Get image information @param {Buffer} buf Image or image part that contains image parameters @param {function} cb Callback to invoke on completion
[ "Get", "image", "information" ]
7ee7e1a67562e083c60be93864fad86d1ac8eb30
https://github.com/gchudnov/inkjet/blob/7ee7e1a67562e083c60be93864fad86d1ac8eb30/build/lib/info.js#L19-L34
31,978
hdnpt/geartrack
src/malaysiaPosTracker.js
obtainInfo
function obtainInfo(action, id, cb) { request.post({ url: action, form: { trackingNo03: id }, timeout: 20000 }, function (error, response, body) { if (error || response.statusCode != 200) { cb(utils.errorDown()) return } // Not found if (body.indexOf('Please insert the correct Tracking Number.') != -1) { cb(utils.errorNoData()) return } let entity = null try { entity = createMalaysiaPosEntity(body) } catch (error) { return cb(utils.errorParser(id, error.message)) } cb(null, entity) }) }
javascript
function obtainInfo(action, id, cb) { request.post({ url: action, form: { trackingNo03: id }, timeout: 20000 }, function (error, response, body) { if (error || response.statusCode != 200) { cb(utils.errorDown()) return } // Not found if (body.indexOf('Please insert the correct Tracking Number.') != -1) { cb(utils.errorNoData()) return } let entity = null try { entity = createMalaysiaPosEntity(body) } catch (error) { return cb(utils.errorParser(id, error.message)) } cb(null, entity) }) }
[ "function", "obtainInfo", "(", "action", ",", "id", ",", "cb", ")", "{", "request", ".", "post", "(", "{", "url", ":", "action", ",", "form", ":", "{", "trackingNo03", ":", "id", "}", ",", "timeout", ":", "20000", "}", ",", "function", "(", "error"...
Get info from malaysiaPos page @param action @param id @param postalcode @param cb
[ "Get", "info", "from", "malaysiaPos", "page" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/malaysiaPosTracker.js#L35-L63
31,979
hdnpt/geartrack
src/malaysiaPosTracker.js
createMalaysiaPosEntity
function createMalaysiaPosEntity(html) { let $ = parser.load(html) let id = $('#trackingNo03').get(0).children[0].data.trim() let init = html.indexOf("var strTD") init = html.indexOf('"', init + 1) let fin = html.indexOf('"', init + 1) let strTD = html.substring(init, fin) $ = parser.load(strTD) let trs = $('#tbDetails tbody tr') let states = utils.tableParser( trs, { 'date': { 'idx': 0, 'mandatory': true, 'parser': elem => { return moment.tz(elem, 'DD MMM YYYY HH:mm:ss', 'en', zone).format() } }, 'state': {'idx': 1, 'mandatory': true}, 'area': {'idx': 2} }, elem => { // On Maintenance there is a row with a td colspan=4, we want to skip it if(elem.children[0].attribs && elem.children[0].attribs.colspan && elem.children[0].attribs.colspan == 4) { return false } return true }) return new MalaysiaInfo({ id: id, state: states[0].state, states: states }) }
javascript
function createMalaysiaPosEntity(html) { let $ = parser.load(html) let id = $('#trackingNo03').get(0).children[0].data.trim() let init = html.indexOf("var strTD") init = html.indexOf('"', init + 1) let fin = html.indexOf('"', init + 1) let strTD = html.substring(init, fin) $ = parser.load(strTD) let trs = $('#tbDetails tbody tr') let states = utils.tableParser( trs, { 'date': { 'idx': 0, 'mandatory': true, 'parser': elem => { return moment.tz(elem, 'DD MMM YYYY HH:mm:ss', 'en', zone).format() } }, 'state': {'idx': 1, 'mandatory': true}, 'area': {'idx': 2} }, elem => { // On Maintenance there is a row with a td colspan=4, we want to skip it if(elem.children[0].attribs && elem.children[0].attribs.colspan && elem.children[0].attribs.colspan == 4) { return false } return true }) return new MalaysiaInfo({ id: id, state: states[0].state, states: states }) }
[ "function", "createMalaysiaPosEntity", "(", "html", ")", "{", "let", "$", "=", "parser", ".", "load", "(", "html", ")", "let", "id", "=", "$", "(", "'#trackingNo03'", ")", ".", "get", "(", "0", ")", ".", "children", "[", "0", "]", ".", "data", ".",...
Create malaysiaPos entity from html @param html
[ "Create", "malaysiaPos", "entity", "from", "html" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/malaysiaPosTracker.js#L69-L108
31,980
hdnpt/geartrack
src/cttTracker.js
createCttEntity
function createCttEntity(id, html, cb) { let state = null let messages = [] try { html = htmlBeautify(html) let $ = parser.load(html) let table = $('table.full-width tr').get(1).children.filter(e => e.type == 'tag') let dayAndHours = table[2].children[0].data.trim() + ' ' + table[3].children[0].data.trim() state = { date: moment.tz(dayAndHours, "YYYY/MM/DD HH:mm", zone).format() } if(table[4].children.length == 0) { state['status'] = 'Sem estado' } else { if(table[4].children[0].data) { state['status'] = table[4].children[0].data.trim() } else { state['status'] = table[4].children[0].children[0].data.trim() } } let details = $('#details_0').find('tr') let day = "" let dayUnformated = "" let message = {} for(let i = 0; i < details.length; i++) { let tr = details.get(i) if(tr.children.length >= 8){ let idxsum = 0 if(tr.children.length >= 9) { day = tr.children[0].children[0].data.trim() dayUnformated = day.split(',')[1].trim() day = moment.tz(dayUnformated, "DD MMMM YYYY", 'pt', zone).format() message = { day: day, status: [] } messages.push(message) idxsum = 1 } let hours = tr.children[0+idxsum].children[0].data.trim() let time = moment.tz(dayUnformated + ' ' + hours, "DD MMMM YYYY HH:mm", 'pt', zone).format() let add = { time: time, status: tr.children[2+idxsum].children[0].data.trim(), local: tr.children[6+idxsum].children[0].data.trim() } message.status.push(add) } } } catch (error) { return cb(error) } cb(null, new CttInfo(id, state, messages)) }
javascript
function createCttEntity(id, html, cb) { let state = null let messages = [] try { html = htmlBeautify(html) let $ = parser.load(html) let table = $('table.full-width tr').get(1).children.filter(e => e.type == 'tag') let dayAndHours = table[2].children[0].data.trim() + ' ' + table[3].children[0].data.trim() state = { date: moment.tz(dayAndHours, "YYYY/MM/DD HH:mm", zone).format() } if(table[4].children.length == 0) { state['status'] = 'Sem estado' } else { if(table[4].children[0].data) { state['status'] = table[4].children[0].data.trim() } else { state['status'] = table[4].children[0].children[0].data.trim() } } let details = $('#details_0').find('tr') let day = "" let dayUnformated = "" let message = {} for(let i = 0; i < details.length; i++) { let tr = details.get(i) if(tr.children.length >= 8){ let idxsum = 0 if(tr.children.length >= 9) { day = tr.children[0].children[0].data.trim() dayUnformated = day.split(',')[1].trim() day = moment.tz(dayUnformated, "DD MMMM YYYY", 'pt', zone).format() message = { day: day, status: [] } messages.push(message) idxsum = 1 } let hours = tr.children[0+idxsum].children[0].data.trim() let time = moment.tz(dayUnformated + ' ' + hours, "DD MMMM YYYY HH:mm", 'pt', zone).format() let add = { time: time, status: tr.children[2+idxsum].children[0].data.trim(), local: tr.children[6+idxsum].children[0].data.trim() } message.status.push(add) } } } catch (error) { return cb(error) } cb(null, new CttInfo(id, state, messages)) }
[ "function", "createCttEntity", "(", "id", ",", "html", ",", "cb", ")", "{", "let", "state", "=", "null", "let", "messages", "=", "[", "]", "try", "{", "html", "=", "htmlBeautify", "(", "html", ")", "let", "$", "=", "parser", ".", "load", "(", "html...
Create ctt entity from html @param id @param html @param cb
[ "Create", "ctt", "entity", "from", "html" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/cttTracker.js#L75-L140
31,981
hdnpt/geartrack
src/pitneybowesTracker.js
obtainInfo
function obtainInfo(id, action, cb) { request.get({ url: action, timeout: 20000, strictSSL: false }, function (error, response, body) { if (error || response.statusCode != 200) { cb(utils.errorDown()) return } // Not found if (body.indexOf('errorMessage') != -1) { cb(utils.errorNoData()) return } let entity = null try { entity = createParcelTrackerEntity(body) } catch (error) { return cb(utils.errorParser(id, error.message)) } if(entity != null) cb(null, entity) }) }
javascript
function obtainInfo(id, action, cb) { request.get({ url: action, timeout: 20000, strictSSL: false }, function (error, response, body) { if (error || response.statusCode != 200) { cb(utils.errorDown()) return } // Not found if (body.indexOf('errorMessage') != -1) { cb(utils.errorNoData()) return } let entity = null try { entity = createParcelTrackerEntity(body) } catch (error) { return cb(utils.errorParser(id, error.message)) } if(entity != null) cb(null, entity) }) }
[ "function", "obtainInfo", "(", "id", ",", "action", ",", "cb", ")", "{", "request", ".", "get", "(", "{", "url", ":", "action", ",", "timeout", ":", "20000", ",", "strictSSL", ":", "false", "}", ",", "function", "(", "error", ",", "response", ",", ...
Get info from parcel tracker request @param action @param id @param cb
[ "Get", "info", "from", "parcel", "tracker", "request" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/pitneybowesTracker.js#L30-L56
31,982
hdnpt/geartrack
src/pitneybowesTracker.js
createParcelTrackerEntity
function createParcelTrackerEntity(body) { const data = JSON.parse(body) const states = [] data.scanHistory.scanDetails.forEach((elem) => { const state = { state : elem.eventDescription, date : elem.eventDate + "T" + elem.eventTime } if(elem.eventLocation && elem.eventLocation.country && elem.eventLocation.countyOrRegion && elem.eventLocation.city){ state.area = elem.eventLocation.country + " - " + elem.eventLocation.countyOrRegion + " - " + elem.eventLocation.city } states.push(state) }) return new ParcelTrackerInfo({ attempts: 1, id: data.packageIdentifier, state: data.currentStatus.eventDescription, carrier: data.carrier, origin: data.senderLocation.country + " - " + data.senderLocation.countyOrRegion + " - " + data.senderLocation.city, destiny: data.destinationLocation.country + " - " + data.destinationLocation.countyOrRegion + " - " + data.destinationLocation.city, states: states }) }
javascript
function createParcelTrackerEntity(body) { const data = JSON.parse(body) const states = [] data.scanHistory.scanDetails.forEach((elem) => { const state = { state : elem.eventDescription, date : elem.eventDate + "T" + elem.eventTime } if(elem.eventLocation && elem.eventLocation.country && elem.eventLocation.countyOrRegion && elem.eventLocation.city){ state.area = elem.eventLocation.country + " - " + elem.eventLocation.countyOrRegion + " - " + elem.eventLocation.city } states.push(state) }) return new ParcelTrackerInfo({ attempts: 1, id: data.packageIdentifier, state: data.currentStatus.eventDescription, carrier: data.carrier, origin: data.senderLocation.country + " - " + data.senderLocation.countyOrRegion + " - " + data.senderLocation.city, destiny: data.destinationLocation.country + " - " + data.destinationLocation.countyOrRegion + " - " + data.destinationLocation.city, states: states }) }
[ "function", "createParcelTrackerEntity", "(", "body", ")", "{", "const", "data", "=", "JSON", ".", "parse", "(", "body", ")", "const", "states", "=", "[", "]", "data", ".", "scanHistory", ".", "scanDetails", ".", "forEach", "(", "(", "elem", ")", "=>", ...
Create parcel tracker entity from html @param html
[ "Create", "parcel", "tracker", "entity", "from", "html" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/pitneybowesTracker.js#L62-L95
31,983
hdnpt/geartrack
src/utils.js
function (type, error = null, id = null) { type = type.toUpperCase() let errors = { 'NO_DATA': 'No info for that id yet. Or maybe the data provided was wrong.', 'BUSY': 'The server providing the info is busy right now. Try again.', 'UNAVAILABLE': 'The server providing the info is unavailable right now. Try again later.', 'EMPTY': 'The provider server was parsed correctly, but has no data to show. Try Again later.', 'DOWN': 'The provider server is currently down. Try Again later.', 'PARSER': 'Something went wrong when parsing the provider website.', 'ACTION_REQUIRED': 'That tracker requires an aditional step in their website.' } let message = error != null ? error : errors[type] message = id != null ? message + ' ID:' + id : message return new Error(type + ' - ' + message) }
javascript
function (type, error = null, id = null) { type = type.toUpperCase() let errors = { 'NO_DATA': 'No info for that id yet. Or maybe the data provided was wrong.', 'BUSY': 'The server providing the info is busy right now. Try again.', 'UNAVAILABLE': 'The server providing the info is unavailable right now. Try again later.', 'EMPTY': 'The provider server was parsed correctly, but has no data to show. Try Again later.', 'DOWN': 'The provider server is currently down. Try Again later.', 'PARSER': 'Something went wrong when parsing the provider website.', 'ACTION_REQUIRED': 'That tracker requires an aditional step in their website.' } let message = error != null ? error : errors[type] message = id != null ? message + ' ID:' + id : message return new Error(type + ' - ' + message) }
[ "function", "(", "type", ",", "error", "=", "null", ",", "id", "=", "null", ")", "{", "type", "=", "type", ".", "toUpperCase", "(", ")", "let", "errors", "=", "{", "'NO_DATA'", ":", "'No info for that id yet. Or maybe the data provided was wrong.'", ",", "'BUS...
Get the Error message by Type @param type @param error Error message @returns {Error}
[ "Get", "the", "Error", "message", "by", "Type" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/utils.js#L10-L25
31,984
hdnpt/geartrack
src/correosESTracker.js
createCorreosEsEntity
function createCorreosEsEntity(id, html) { let $ = parser.load(html) let table2 = $('#Table2').get(0); let states = [] const fields = ['date', 'info'] if (table2.children.length === 0 || (table2.children[1] !== undefined && table2.children[1].data !== undefined && table2.children[1].data.trim() === 'fin tabla descripciones')) return null; table2.children.forEach(function (elem) { if (elem.attribs !== undefined && elem.attribs.class.trim() === 'txtCabeceraTabla') { let state = {} elem.children.forEach(function (_child) { if (_child.attribs !== undefined && _child.attribs.class !== undefined) { let _class = _child.attribs.class.trim() if (_class === 'txtDescripcionTabla') { state['date'] = moment.tz(_child.children[0].data.trim(), "DD/MM/YYYY", zone).format() } else if (_class === 'txtContenidoTabla' || _class === 'txtContenidoTablaOff') { state['state'] = _child.children[1].children[0].data.trim() if (_child.children[1].attribs !== undefined && _child.children[1].attribs !== undefined && _child.children[1].attribs.title) { state['title'] = _child.children[1].attribs.title.trim() } } } }) if (Object.keys(state).length > 0) { states.push(state) } } }) return new CorreosESInfo({ 'id': id, 'state': states[states.length - 1].state, 'states': states.reverse() }) }
javascript
function createCorreosEsEntity(id, html) { let $ = parser.load(html) let table2 = $('#Table2').get(0); let states = [] const fields = ['date', 'info'] if (table2.children.length === 0 || (table2.children[1] !== undefined && table2.children[1].data !== undefined && table2.children[1].data.trim() === 'fin tabla descripciones')) return null; table2.children.forEach(function (elem) { if (elem.attribs !== undefined && elem.attribs.class.trim() === 'txtCabeceraTabla') { let state = {} elem.children.forEach(function (_child) { if (_child.attribs !== undefined && _child.attribs.class !== undefined) { let _class = _child.attribs.class.trim() if (_class === 'txtDescripcionTabla') { state['date'] = moment.tz(_child.children[0].data.trim(), "DD/MM/YYYY", zone).format() } else if (_class === 'txtContenidoTabla' || _class === 'txtContenidoTablaOff') { state['state'] = _child.children[1].children[0].data.trim() if (_child.children[1].attribs !== undefined && _child.children[1].attribs !== undefined && _child.children[1].attribs.title) { state['title'] = _child.children[1].attribs.title.trim() } } } }) if (Object.keys(state).length > 0) { states.push(state) } } }) return new CorreosESInfo({ 'id': id, 'state': states[states.length - 1].state, 'states': states.reverse() }) }
[ "function", "createCorreosEsEntity", "(", "id", ",", "html", ")", "{", "let", "$", "=", "parser", ".", "load", "(", "html", ")", "let", "table2", "=", "$", "(", "'#Table2'", ")", ".", "get", "(", "0", ")", ";", "let", "states", "=", "[", "]", "co...
Create correos.es entity from html @param html
[ "Create", "correos", ".", "es", "entity", "from", "html" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/correosESTracker.js#L59-L103
31,985
hdnpt/geartrack
src/cjahTracker.js
createCjahEntity
function createCjahEntity(id, html, cb) { let entity = null try { let $ = parser.load(html) let trs = $('table tbody tr') // Not found if (!trs || trs.length === 0) { cb(utils.errorNoData()) return } let states = utils.tableParser( trs, { 'id': { 'idx': 1, 'mandatory': true }, 'date': {'idx': 3, 'mandatory': true, 'parser': elem => { return moment.tz( elem, 'DD/MM/YYYY h:mm:ssa', 'en', zone).format()}}, 'state': { 'idx': 5, 'mandatory': true } }, elem => true) entity = new CjahInfo({ id: states[0].id, state: states[0].state, states: states }) } catch (error) { return cb(utils.errorParser(id, error.message)) } cb(null, entity) }
javascript
function createCjahEntity(id, html, cb) { let entity = null try { let $ = parser.load(html) let trs = $('table tbody tr') // Not found if (!trs || trs.length === 0) { cb(utils.errorNoData()) return } let states = utils.tableParser( trs, { 'id': { 'idx': 1, 'mandatory': true }, 'date': {'idx': 3, 'mandatory': true, 'parser': elem => { return moment.tz( elem, 'DD/MM/YYYY h:mm:ssa', 'en', zone).format()}}, 'state': { 'idx': 5, 'mandatory': true } }, elem => true) entity = new CjahInfo({ id: states[0].id, state: states[0].state, states: states }) } catch (error) { return cb(utils.errorParser(id, error.message)) } cb(null, entity) }
[ "function", "createCjahEntity", "(", "id", ",", "html", ",", "cb", ")", "{", "let", "entity", "=", "null", "try", "{", "let", "$", "=", "parser", ".", "load", "(", "html", ")", "let", "trs", "=", "$", "(", "'table tbody tr'", ")", "// Not found", "if...
Create cjah entity from html @param id @param html @param cb
[ "Create", "cjah", "entity", "from", "html" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/cjahTracker.js#L44-L75
31,986
hdnpt/geartrack
src/singpostTracker.js
createSingpostEntity
function createSingpostEntity(id, html) { let $ = parser.load(html) let date = [] $('span.tacking-date').each(function (i, elem) { date.push($(this).text().trim()) }) let status = [] $('div.tacking-status').each(function (i, elem) { status.push($(this).text().trim()) }) let messages = [] for(let i = 0; i < date.length; i++) { messages.push({ date: moment.tz(date[i], "DD-MM-YYYY", zone).format(), state: status[i].replace(/ \(Country.+\)/ig, "").trim() // remove '(Country: PT)' }) } return new SingpostInfo(id, messages) }
javascript
function createSingpostEntity(id, html) { let $ = parser.load(html) let date = [] $('span.tacking-date').each(function (i, elem) { date.push($(this).text().trim()) }) let status = [] $('div.tacking-status').each(function (i, elem) { status.push($(this).text().trim()) }) let messages = [] for(let i = 0; i < date.length; i++) { messages.push({ date: moment.tz(date[i], "DD-MM-YYYY", zone).format(), state: status[i].replace(/ \(Country.+\)/ig, "").trim() // remove '(Country: PT)' }) } return new SingpostInfo(id, messages) }
[ "function", "createSingpostEntity", "(", "id", ",", "html", ")", "{", "let", "$", "=", "parser", ".", "load", "(", "html", ")", "let", "date", "=", "[", "]", "$", "(", "'span.tacking-date'", ")", ".", "each", "(", "function", "(", "i", ",", "elem", ...
Create singpost entity from html @param id @param html
[ "Create", "singpost", "entity", "from", "html" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/singpostTracker.js#L66-L88
31,987
hdnpt/geartrack
src/panasiaTracker.js
createPanasiaEntity
function createPanasiaEntity(html, id) { let $ = parser.load(html) let td11 = $('.one-parcel .td11').contents() let orderNumber = td11[1].data let product = td11[3].data let td22 = $('.one-parcel .td22').contents() let trackingNumber = td22[1].data let country = utils.removeChineseChars(td22[3].data).trim() let td33 = $('.one-parcel .td33').contents() let dates = [] for(let i = 1; i < td33.length; ++i) { let date = td33[i].children[1].data dates.push(moment.tz(date, "YYYY-MM-DD HH:mm:ss", zone).format()) } let td44 = $('.one-parcel .td44').contents() let states = [] for(let i = 0; i < td44.length; ++i) { let s = td44[i].children[0].data states.push(s.replace(',', ', ').replace('En tr?nsito', 'En transito')) } let finalStates = [] for(let i = 0; i < dates.length; ++i) { finalStates.push({ state: states[i], date: dates[i] }) } return new PanasiaInfo({ orderNumber: orderNumber, product: product, id: id, country: country, states: finalStates.sort((a, b) => { let dateA = moment(a.date), dateB = moment(b.date) return dateA < dateB }) }) }
javascript
function createPanasiaEntity(html, id) { let $ = parser.load(html) let td11 = $('.one-parcel .td11').contents() let orderNumber = td11[1].data let product = td11[3].data let td22 = $('.one-parcel .td22').contents() let trackingNumber = td22[1].data let country = utils.removeChineseChars(td22[3].data).trim() let td33 = $('.one-parcel .td33').contents() let dates = [] for(let i = 1; i < td33.length; ++i) { let date = td33[i].children[1].data dates.push(moment.tz(date, "YYYY-MM-DD HH:mm:ss", zone).format()) } let td44 = $('.one-parcel .td44').contents() let states = [] for(let i = 0; i < td44.length; ++i) { let s = td44[i].children[0].data states.push(s.replace(',', ', ').replace('En tr?nsito', 'En transito')) } let finalStates = [] for(let i = 0; i < dates.length; ++i) { finalStates.push({ state: states[i], date: dates[i] }) } return new PanasiaInfo({ orderNumber: orderNumber, product: product, id: id, country: country, states: finalStates.sort((a, b) => { let dateA = moment(a.date), dateB = moment(b.date) return dateA < dateB }) }) }
[ "function", "createPanasiaEntity", "(", "html", ",", "id", ")", "{", "let", "$", "=", "parser", ".", "load", "(", "html", ")", "let", "td11", "=", "$", "(", "'.one-parcel .td11'", ")", ".", "contents", "(", ")", "let", "orderNumber", "=", "td11", "[", ...
Create panasia entity from html @param html @param id
[ "Create", "panasia", "entity", "from", "html" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/panasiaTracker.js#L53-L101
31,988
hdnpt/geartrack
src/cainiaoTracker.js
createCainiaoEntity
function createCainiaoEntity(id, json) { let section = json.data[0].section3 || json.data[0].section2; let msgs = section.detailList.map(m => { return { state: fixStateName(m.desc), date: moment.tz(m.time, "YYYY-MM-DD HH:mm:ss", zone).format() } }) let destinyId = json.data[0].section2.mailNo || null return new CainiaoInfo(id, msgs, destinyId) }
javascript
function createCainiaoEntity(id, json) { let section = json.data[0].section3 || json.data[0].section2; let msgs = section.detailList.map(m => { return { state: fixStateName(m.desc), date: moment.tz(m.time, "YYYY-MM-DD HH:mm:ss", zone).format() } }) let destinyId = json.data[0].section2.mailNo || null return new CainiaoInfo(id, msgs, destinyId) }
[ "function", "createCainiaoEntity", "(", "id", ",", "json", ")", "{", "let", "section", "=", "json", ".", "data", "[", "0", "]", ".", "section3", "||", "json", ".", "data", "[", "0", "]", ".", "section2", ";", "let", "msgs", "=", "section", ".", "de...
Create cainiao entity from html @param id @param json
[ "Create", "cainiao", "entity", "from", "html" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/cainiaoTracker.js#L68-L81
31,989
hdnpt/geartrack
src/expresso24Tracker.js
createExpressoEntity
function createExpressoEntity(html) { let $ = parser.load(html) let data = [] $('table span').each(function (i, elem) { if(i >= 10 ) data.push($(this).text().trim().replace(/\s\s+/g, ' ')) }) return new ExpressoInfo({ 'guide': data[0], 'origin': data[1], 'date': moment.tz(data[2], "YYYY-MM-DD", zone).format(), 'status': data[3], 'weight': data[4], 'parcels': data[5], 'receiver_name': data[6], 'address': parseAddress(data[7]), 'refund': data[8], 'ref': data[9], }) }
javascript
function createExpressoEntity(html) { let $ = parser.load(html) let data = [] $('table span').each(function (i, elem) { if(i >= 10 ) data.push($(this).text().trim().replace(/\s\s+/g, ' ')) }) return new ExpressoInfo({ 'guide': data[0], 'origin': data[1], 'date': moment.tz(data[2], "YYYY-MM-DD", zone).format(), 'status': data[3], 'weight': data[4], 'parcels': data[5], 'receiver_name': data[6], 'address': parseAddress(data[7]), 'refund': data[8], 'ref': data[9], }) }
[ "function", "createExpressoEntity", "(", "html", ")", "{", "let", "$", "=", "parser", ".", "load", "(", "html", ")", "let", "data", "=", "[", "]", "$", "(", "'table span'", ")", ".", "each", "(", "function", "(", "i", ",", "elem", ")", "{", "if", ...
Create expresso entity from html @param html
[ "Create", "expresso", "entity", "from", "html" ]
e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba
https://github.com/hdnpt/geartrack/blob/e69c81f0084d7a5c60c63dcb2ca6a9e8dad5e0ba/src/expresso24Tracker.js#L59-L80
31,990
amqp/node-red-contrib-rhea
rhea/rhea.js
amqpEndpointNode
function amqpEndpointNode(n) { RED.nodes.createNode(this, n); // save node parameters this.host = n.host; this.port = n.port; this.username = n.username; this.password = n.password; this.container_id = n.container_id; this.rejectUnauthorized = n.rejectUnauthorized; this.usetls = n.usetls; if (this.usetls && n.tls) { this.tls = RED.nodes.getNode(n.tls) } // build options for connection var options = { host: this.host, port: this.port}; if (this.username) { options.username = this.username; } if (this.password) { options.password = this.password; } if (this.container_id) { options.container_id = this.container_id; } else { options.container_id = "node-red-rhea-" + container.generate_uuid(); } if (this.usetls && n.tls) { options.transport = 'tls'; if (this.tls.credentials.cadata) { options.ca = this.tls.credentials.cadata } } options.rejectUnauthorized = this.rejectUnauthorized; var node = this; this.connected = false; this.connecting = false; /** * Exposed function for connecting to the remote AMQP container * creating an AMQP connection object * * @param callback function called when the connection is established */ this.connect = function(callback) { // AMQP connection not established, trying to do that if (!node.connected && !node.connecting) { node.connecting = true; node.connection = container.connect(options); node.connection.on('connection_error', function(context) { node.connecting = false; node.connected = false; var error = context.connection.get_error(); node.error(error); }); node.connection.on('connection_open', function(context) { node.connecting = false; node.connected = true; callback(context.connection); }); node.connection.on('disconnected', function(context) { node.connected = false; }); // AMQP connection already established } else { callback(node.connection); } } }
javascript
function amqpEndpointNode(n) { RED.nodes.createNode(this, n); // save node parameters this.host = n.host; this.port = n.port; this.username = n.username; this.password = n.password; this.container_id = n.container_id; this.rejectUnauthorized = n.rejectUnauthorized; this.usetls = n.usetls; if (this.usetls && n.tls) { this.tls = RED.nodes.getNode(n.tls) } // build options for connection var options = { host: this.host, port: this.port}; if (this.username) { options.username = this.username; } if (this.password) { options.password = this.password; } if (this.container_id) { options.container_id = this.container_id; } else { options.container_id = "node-red-rhea-" + container.generate_uuid(); } if (this.usetls && n.tls) { options.transport = 'tls'; if (this.tls.credentials.cadata) { options.ca = this.tls.credentials.cadata } } options.rejectUnauthorized = this.rejectUnauthorized; var node = this; this.connected = false; this.connecting = false; /** * Exposed function for connecting to the remote AMQP container * creating an AMQP connection object * * @param callback function called when the connection is established */ this.connect = function(callback) { // AMQP connection not established, trying to do that if (!node.connected && !node.connecting) { node.connecting = true; node.connection = container.connect(options); node.connection.on('connection_error', function(context) { node.connecting = false; node.connected = false; var error = context.connection.get_error(); node.error(error); }); node.connection.on('connection_open', function(context) { node.connecting = false; node.connected = true; callback(context.connection); }); node.connection.on('disconnected', function(context) { node.connected = false; }); // AMQP connection already established } else { callback(node.connection); } } }
[ "function", "amqpEndpointNode", "(", "n", ")", "{", "RED", ".", "nodes", ".", "createNode", "(", "this", ",", "n", ")", ";", "// save node parameters", "this", ".", "host", "=", "n", ".", "host", ";", "this", ".", "port", "=", "n", ".", "port", ";", ...
Node for configuring an AMQP endpoint
[ "Node", "for", "configuring", "an", "AMQP", "endpoint" ]
69eebcdc494571030b222afeec98d8f947355a91
https://github.com/amqp/node-red-contrib-rhea/blob/69eebcdc494571030b222afeec98d8f947355a91/rhea/rhea.js#L24-L112
31,991
amqp/node-red-contrib-rhea
rhea/rhea.js
amqpSenderNode
function amqpSenderNode(config) { RED.nodes.createNode(this, config); // get endpoint configuration this.endpoint = RED.nodes.getNode(config.endpoint); // get all other configuration this.address = config.address; this.autosettle = config.autosettle; this.dynamic = config.dynamic; this.sndsettlemode = config.sndsettlemode; this.rcvsettlemode = config.rcvsettlemode; this.durable = config.durable; this.expirypolicy = config.expirypolicy; var node = this; // node not yet connected this.status({ fill: 'red', shape: 'dot', text: 'disconnected' }); if (node.endpoint) { node.endpoint.connect(function(connection) { setup(connection); }); /** * Node setup for creating sender link * * @param connection Connection instance */ function setup(connection) { node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); // build sender options based on node configuration var options = { target: { address: node.address, dynamic: node.dynamic, durable: node.durable, expiry_policy: node.expirypolicy }, autosettle: node.autosettle, snd_settle_mode: node.sndsettlemode, rcv_settle_mode: node.rcvsettlemode }; node.sender = node.connection.open_sender(options); node.sender.on('accepted', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.sender.on('released', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.sender.on('rejected', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { // enough credits to send if (node.sender.sendable()) { node.sender.send(msg.payload); } }); node.on('close', function() { if (node.sender != null) node.sender.detach(); node.connection.close(); }); } } }
javascript
function amqpSenderNode(config) { RED.nodes.createNode(this, config); // get endpoint configuration this.endpoint = RED.nodes.getNode(config.endpoint); // get all other configuration this.address = config.address; this.autosettle = config.autosettle; this.dynamic = config.dynamic; this.sndsettlemode = config.sndsettlemode; this.rcvsettlemode = config.rcvsettlemode; this.durable = config.durable; this.expirypolicy = config.expirypolicy; var node = this; // node not yet connected this.status({ fill: 'red', shape: 'dot', text: 'disconnected' }); if (node.endpoint) { node.endpoint.connect(function(connection) { setup(connection); }); /** * Node setup for creating sender link * * @param connection Connection instance */ function setup(connection) { node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); // build sender options based on node configuration var options = { target: { address: node.address, dynamic: node.dynamic, durable: node.durable, expiry_policy: node.expirypolicy }, autosettle: node.autosettle, snd_settle_mode: node.sndsettlemode, rcv_settle_mode: node.rcvsettlemode }; node.sender = node.connection.open_sender(options); node.sender.on('accepted', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.sender.on('released', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.sender.on('rejected', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { // enough credits to send if (node.sender.sendable()) { node.sender.send(msg.payload); } }); node.on('close', function() { if (node.sender != null) node.sender.detach(); node.connection.close(); }); } } }
[ "function", "amqpSenderNode", "(", "config", ")", "{", "RED", ".", "nodes", ".", "createNode", "(", "this", ",", "config", ")", ";", "// get endpoint configuration", "this", ".", "endpoint", "=", "RED", ".", "nodes", ".", "getNode", "(", "config", ".", "en...
Node for AMQP sender
[ "Node", "for", "AMQP", "sender" ]
69eebcdc494571030b222afeec98d8f947355a91
https://github.com/amqp/node-red-contrib-rhea/blob/69eebcdc494571030b222afeec98d8f947355a91/rhea/rhea.js#L119-L205
31,992
amqp/node-red-contrib-rhea
rhea/rhea.js
setup
function setup(connection) { node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); // build sender options based on node configuration var options = { target: { address: node.address, dynamic: node.dynamic, durable: node.durable, expiry_policy: node.expirypolicy }, autosettle: node.autosettle, snd_settle_mode: node.sndsettlemode, rcv_settle_mode: node.rcvsettlemode }; node.sender = node.connection.open_sender(options); node.sender.on('accepted', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.sender.on('released', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.sender.on('rejected', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { // enough credits to send if (node.sender.sendable()) { node.sender.send(msg.payload); } }); node.on('close', function() { if (node.sender != null) node.sender.detach(); node.connection.close(); }); }
javascript
function setup(connection) { node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); // build sender options based on node configuration var options = { target: { address: node.address, dynamic: node.dynamic, durable: node.durable, expiry_policy: node.expirypolicy }, autosettle: node.autosettle, snd_settle_mode: node.sndsettlemode, rcv_settle_mode: node.rcvsettlemode }; node.sender = node.connection.open_sender(options); node.sender.on('accepted', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.sender.on('released', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.sender.on('rejected', function(context) { var msg = outDelivery(node, context.delivery); node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { // enough credits to send if (node.sender.sendable()) { node.sender.send(msg.payload); } }); node.on('close', function() { if (node.sender != null) node.sender.detach(); node.connection.close(); }); }
[ "function", "setup", "(", "connection", ")", "{", "node", ".", "connection", "=", "connection", ";", "// node connected", "node", ".", "status", "(", "{", "fill", ":", "'green'", ",", "shape", ":", "'dot'", ",", "text", ":", "'connected'", "}", ")", ";",...
Node setup for creating sender link @param connection Connection instance
[ "Node", "setup", "for", "creating", "sender", "link" ]
69eebcdc494571030b222afeec98d8f947355a91
https://github.com/amqp/node-red-contrib-rhea/blob/69eebcdc494571030b222afeec98d8f947355a91/rhea/rhea.js#L149-L202
31,993
amqp/node-red-contrib-rhea
rhea/rhea.js
amqpReceiverNode
function amqpReceiverNode(config) { RED.nodes.createNode(this, config); // get endpoint configuration this.endpoint = RED.nodes.getNode(config.endpoint); // get all other configuration this.address = config.address; this.autoaccept = config.autoaccept; this.creditwindow = config.creditwindow; this.dynamic = config.dynamic; this.sndsettlemode = config.sndsettlemode; this.rcvsettlemode = config.rcvsettlemode; this.durable = config.durable; this.expirypolicy = config.expirypolicy; if (this.dynamic) this.address = undefined; var node = this; // node not yet connected this.status({ fill: 'red', shape: 'dot', text: 'disconnected' }); if (this.endpoint) { node.endpoint.connect(function(connection) { setup(connection); }); /** * Node setup for creating receiver link * * @param connection Connection instance */ function setup(connection) { node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); // build receiver options based on node configuration var options = { source: { address: node.address, dynamic: node.dynamic, durable: node.durable, expiry_policy: node.expirypolicy }, credit_window: node.creditwindow, autoaccept: node.autoaccept, snd_settle_mode: node.sndsettlemode, rcv_settle_mode: node.rcvsettlemode }; node.receiver = node.connection.open_receiver(options); node.receiver.on('message', function(context) { var msg = { payload: context.message, delivery: context.delivery }; node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { if (msg.credit) { node.receiver.flow(msg.credit); } }); node.on('close', function() { if (node.receiver != null) node.receiver.detach(); node.connection.close(); }); } } }
javascript
function amqpReceiverNode(config) { RED.nodes.createNode(this, config); // get endpoint configuration this.endpoint = RED.nodes.getNode(config.endpoint); // get all other configuration this.address = config.address; this.autoaccept = config.autoaccept; this.creditwindow = config.creditwindow; this.dynamic = config.dynamic; this.sndsettlemode = config.sndsettlemode; this.rcvsettlemode = config.rcvsettlemode; this.durable = config.durable; this.expirypolicy = config.expirypolicy; if (this.dynamic) this.address = undefined; var node = this; // node not yet connected this.status({ fill: 'red', shape: 'dot', text: 'disconnected' }); if (this.endpoint) { node.endpoint.connect(function(connection) { setup(connection); }); /** * Node setup for creating receiver link * * @param connection Connection instance */ function setup(connection) { node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); // build receiver options based on node configuration var options = { source: { address: node.address, dynamic: node.dynamic, durable: node.durable, expiry_policy: node.expirypolicy }, credit_window: node.creditwindow, autoaccept: node.autoaccept, snd_settle_mode: node.sndsettlemode, rcv_settle_mode: node.rcvsettlemode }; node.receiver = node.connection.open_receiver(options); node.receiver.on('message', function(context) { var msg = { payload: context.message, delivery: context.delivery }; node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { if (msg.credit) { node.receiver.flow(msg.credit); } }); node.on('close', function() { if (node.receiver != null) node.receiver.detach(); node.connection.close(); }); } } }
[ "function", "amqpReceiverNode", "(", "config", ")", "{", "RED", ".", "nodes", ".", "createNode", "(", "this", ",", "config", ")", ";", "// get endpoint configuration", "this", ".", "endpoint", "=", "RED", ".", "nodes", ".", "getNode", "(", "config", ".", "...
Node for AMQP receiver
[ "Node", "for", "AMQP", "receiver" ]
69eebcdc494571030b222afeec98d8f947355a91
https://github.com/amqp/node-red-contrib-rhea/blob/69eebcdc494571030b222afeec98d8f947355a91/rhea/rhea.js#L220-L304
31,994
amqp/node-red-contrib-rhea
rhea/rhea.js
setup
function setup(connection) { node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); // build receiver options based on node configuration var options = { source: { address: node.address, dynamic: node.dynamic, durable: node.durable, expiry_policy: node.expirypolicy }, credit_window: node.creditwindow, autoaccept: node.autoaccept, snd_settle_mode: node.sndsettlemode, rcv_settle_mode: node.rcvsettlemode }; node.receiver = node.connection.open_receiver(options); node.receiver.on('message', function(context) { var msg = { payload: context.message, delivery: context.delivery }; node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { if (msg.credit) { node.receiver.flow(msg.credit); } }); node.on('close', function() { if (node.receiver != null) node.receiver.detach(); node.connection.close(); }); }
javascript
function setup(connection) { node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); // build receiver options based on node configuration var options = { source: { address: node.address, dynamic: node.dynamic, durable: node.durable, expiry_policy: node.expirypolicy }, credit_window: node.creditwindow, autoaccept: node.autoaccept, snd_settle_mode: node.sndsettlemode, rcv_settle_mode: node.rcvsettlemode }; node.receiver = node.connection.open_receiver(options); node.receiver.on('message', function(context) { var msg = { payload: context.message, delivery: context.delivery }; node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { if (msg.credit) { node.receiver.flow(msg.credit); } }); node.on('close', function() { if (node.receiver != null) node.receiver.detach(); node.connection.close(); }); }
[ "function", "setup", "(", "connection", ")", "{", "node", ".", "connection", "=", "connection", ";", "// node connected", "node", ".", "status", "(", "{", "fill", ":", "'green'", ",", "shape", ":", "'dot'", ",", "text", ":", "'connected'", "}", ")", ";",...
Node setup for creating receiver link @param connection Connection instance
[ "Node", "setup", "for", "creating", "receiver", "link" ]
69eebcdc494571030b222afeec98d8f947355a91
https://github.com/amqp/node-red-contrib-rhea/blob/69eebcdc494571030b222afeec98d8f947355a91/rhea/rhea.js#L254-L301
31,995
amqp/node-red-contrib-rhea
rhea/rhea.js
amqpRequesterNode
function amqpRequesterNode(config) { RED.nodes.createNode(this, config); //var container = rhea.create_container(); // get endpoint configuration this.endpoint = RED.nodes.getNode(config.endpoint); // get all other configuration this.address = config.address; var node = this; // node not yet connected this.status({ fill: 'red', shape: 'dot', text: 'disconnected' }); if (this.endpoint) { node.endpoint.connect(function(connection) { setup(connection); }); /** * Node setup for creating sender link for sending the request * and the dynamic receiver for receiving reply * * @param connection Connection instance */ function setup(connection) { node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); // build sender options based on node configuration var sender_options = { target: { address: node.address } }; node.sender = node.connection.open_sender(sender_options); node.sender.on('accepted', function(context) { var msg = outDelivery(node, context.delivery); node.send([msg, ]); }); node.sender.on('released', function(context) { var msg = outDelivery(node, context.delivery); node.send([msg, ]); }); node.sender.on('rejected', function(context) { var msg = outDelivery(node, context.delivery); node.send([msg, ]); }); // build receiver options var receiver_options = { source: { dynamic: true } }; node.receiver = node.connection.open_receiver(receiver_options); node.receiver.on('message', function(context) { var msg = { payload: context.message, delivery: context.delivery }; node.send([ ,msg]); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { // enough credits to send if (node.sender.sendable()) { if (node.receiver.source.address) { node.sender.send({ reply_to: node.receiver.source.address, body: msg.payload.body }); } } }); node.on('close', function() { if (node.sender != null) node.sender.detach(); if (node.receiver != null) node.receiver.detach(); node.connection.close(); }) } } }
javascript
function amqpRequesterNode(config) { RED.nodes.createNode(this, config); //var container = rhea.create_container(); // get endpoint configuration this.endpoint = RED.nodes.getNode(config.endpoint); // get all other configuration this.address = config.address; var node = this; // node not yet connected this.status({ fill: 'red', shape: 'dot', text: 'disconnected' }); if (this.endpoint) { node.endpoint.connect(function(connection) { setup(connection); }); /** * Node setup for creating sender link for sending the request * and the dynamic receiver for receiving reply * * @param connection Connection instance */ function setup(connection) { node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); // build sender options based on node configuration var sender_options = { target: { address: node.address } }; node.sender = node.connection.open_sender(sender_options); node.sender.on('accepted', function(context) { var msg = outDelivery(node, context.delivery); node.send([msg, ]); }); node.sender.on('released', function(context) { var msg = outDelivery(node, context.delivery); node.send([msg, ]); }); node.sender.on('rejected', function(context) { var msg = outDelivery(node, context.delivery); node.send([msg, ]); }); // build receiver options var receiver_options = { source: { dynamic: true } }; node.receiver = node.connection.open_receiver(receiver_options); node.receiver.on('message', function(context) { var msg = { payload: context.message, delivery: context.delivery }; node.send([ ,msg]); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { // enough credits to send if (node.sender.sendable()) { if (node.receiver.source.address) { node.sender.send({ reply_to: node.receiver.source.address, body: msg.payload.body }); } } }); node.on('close', function() { if (node.sender != null) node.sender.detach(); if (node.receiver != null) node.receiver.detach(); node.connection.close(); }) } } }
[ "function", "amqpRequesterNode", "(", "config", ")", "{", "RED", ".", "nodes", ".", "createNode", "(", "this", ",", "config", ")", ";", "//var container = rhea.create_container();", "// get endpoint configuration", "this", ".", "endpoint", "=", "RED", ".", "nodes", ...
Node for AMQP requester
[ "Node", "for", "AMQP", "requester" ]
69eebcdc494571030b222afeec98d8f947355a91
https://github.com/amqp/node-red-contrib-rhea/blob/69eebcdc494571030b222afeec98d8f947355a91/rhea/rhea.js#L311-L410
31,996
amqp/node-red-contrib-rhea
rhea/rhea.js
amqpResponderNode
function amqpResponderNode(config) { RED.nodes.createNode(this, config); // get endpoint configuration this.endpoint = RED.nodes.getNode(config.endpoint); // get all other configuration this.address = config.address; var node = this; // node not yet connected this.status({ fill: 'red', shape: 'dot', text: 'disconnected' }); if (this.endpoint) { node.endpoint.connect(function(connection) { setup(connection); }); /** * Node setup for creating receiver link for receiving the request * and the sender for sending reply * * @param connection Connection instance */ function setup(connection) { var request = undefined; var reply_to = undefined; var response = undefined; node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); node.sender = node.connection.open_sender({ target: {} }); // build receiver options var receiver_options = { source: { address: node.address } }; node.receiver = node.connection.open_receiver(receiver_options); node.receiver.on('message', function(context) { // save request and reply_to address on AMQP message received request = context.message; reply_to = request.reply_to; // provides the request and delivery as node output var msg = { payload: context.message, delivery: context.delivery }; node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { // enough credits to send if (node.sender.sendable()) { if (reply_to) { // fill the response with the provided one as input response = msg.payload; response.to = reply_to; node.sender.send(response); } } }); node.on('close', function() { if (node.sender != null) node.sender.detach(); if (node.receiver != null) node.receiver.detach(); node.connection.close(); }) } } }
javascript
function amqpResponderNode(config) { RED.nodes.createNode(this, config); // get endpoint configuration this.endpoint = RED.nodes.getNode(config.endpoint); // get all other configuration this.address = config.address; var node = this; // node not yet connected this.status({ fill: 'red', shape: 'dot', text: 'disconnected' }); if (this.endpoint) { node.endpoint.connect(function(connection) { setup(connection); }); /** * Node setup for creating receiver link for receiving the request * and the sender for sending reply * * @param connection Connection instance */ function setup(connection) { var request = undefined; var reply_to = undefined; var response = undefined; node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); node.sender = node.connection.open_sender({ target: {} }); // build receiver options var receiver_options = { source: { address: node.address } }; node.receiver = node.connection.open_receiver(receiver_options); node.receiver.on('message', function(context) { // save request and reply_to address on AMQP message received request = context.message; reply_to = request.reply_to; // provides the request and delivery as node output var msg = { payload: context.message, delivery: context.delivery }; node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { // enough credits to send if (node.sender.sendable()) { if (reply_to) { // fill the response with the provided one as input response = msg.payload; response.to = reply_to; node.sender.send(response); } } }); node.on('close', function() { if (node.sender != null) node.sender.detach(); if (node.receiver != null) node.receiver.detach(); node.connection.close(); }) } } }
[ "function", "amqpResponderNode", "(", "config", ")", "{", "RED", ".", "nodes", ".", "createNode", "(", "this", ",", "config", ")", ";", "// get endpoint configuration", "this", ".", "endpoint", "=", "RED", ".", "nodes", ".", "getNode", "(", "config", ".", ...
Node for AMQP responder
[ "Node", "for", "AMQP", "responder" ]
69eebcdc494571030b222afeec98d8f947355a91
https://github.com/amqp/node-red-contrib-rhea/blob/69eebcdc494571030b222afeec98d8f947355a91/rhea/rhea.js#L417-L508
31,997
amqp/node-red-contrib-rhea
rhea/rhea.js
setup
function setup(connection) { var request = undefined; var reply_to = undefined; var response = undefined; node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); node.sender = node.connection.open_sender({ target: {} }); // build receiver options var receiver_options = { source: { address: node.address } }; node.receiver = node.connection.open_receiver(receiver_options); node.receiver.on('message', function(context) { // save request and reply_to address on AMQP message received request = context.message; reply_to = request.reply_to; // provides the request and delivery as node output var msg = { payload: context.message, delivery: context.delivery }; node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { // enough credits to send if (node.sender.sendable()) { if (reply_to) { // fill the response with the provided one as input response = msg.payload; response.to = reply_to; node.sender.send(response); } } }); node.on('close', function() { if (node.sender != null) node.sender.detach(); if (node.receiver != null) node.receiver.detach(); node.connection.close(); }) }
javascript
function setup(connection) { var request = undefined; var reply_to = undefined; var response = undefined; node.connection = connection; // node connected node.status({ fill: 'green', shape: 'dot', text: 'connected' }); node.sender = node.connection.open_sender({ target: {} }); // build receiver options var receiver_options = { source: { address: node.address } }; node.receiver = node.connection.open_receiver(receiver_options); node.receiver.on('message', function(context) { // save request and reply_to address on AMQP message received request = context.message; reply_to = request.reply_to; // provides the request and delivery as node output var msg = { payload: context.message, delivery: context.delivery }; node.send(msg); }); node.connection.on('disconnected', function(context) { // node disconnected node.status({fill: 'red', shape: 'dot', text: 'disconnected' }); }); node.on('input', function(msg) { // enough credits to send if (node.sender.sendable()) { if (reply_to) { // fill the response with the provided one as input response = msg.payload; response.to = reply_to; node.sender.send(response); } } }); node.on('close', function() { if (node.sender != null) node.sender.detach(); if (node.receiver != null) node.receiver.detach(); node.connection.close(); }) }
[ "function", "setup", "(", "connection", ")", "{", "var", "request", "=", "undefined", ";", "var", "reply_to", "=", "undefined", ";", "var", "response", "=", "undefined", ";", "node", ".", "connection", "=", "connection", ";", "// node connected", "node", "."...
Node setup for creating receiver link for receiving the request and the sender for sending reply @param connection Connection instance
[ "Node", "setup", "for", "creating", "receiver", "link", "for", "receiving", "the", "request", "and", "the", "sender", "for", "sending", "reply" ]
69eebcdc494571030b222afeec98d8f947355a91
https://github.com/amqp/node-red-contrib-rhea/blob/69eebcdc494571030b222afeec98d8f947355a91/rhea/rhea.js#L442-L505
31,998
hegemonic/requizzle
lib/requizzle.js
isNativeModule
function isNativeModule(targetPath, parentModule) { const lookupPaths = Module._resolveLookupPaths(targetPath, parentModule, true); /* istanbul ignore next */ return lookupPaths === null || (lookupPaths.length === 2 && lookupPaths[1].length === 0 && lookupPaths[0] === targetPath); }
javascript
function isNativeModule(targetPath, parentModule) { const lookupPaths = Module._resolveLookupPaths(targetPath, parentModule, true); /* istanbul ignore next */ return lookupPaths === null || (lookupPaths.length === 2 && lookupPaths[1].length === 0 && lookupPaths[0] === targetPath); }
[ "function", "isNativeModule", "(", "targetPath", ",", "parentModule", ")", "{", "const", "lookupPaths", "=", "Module", ".", "_resolveLookupPaths", "(", "targetPath", ",", "parentModule", ",", "true", ")", ";", "/* istanbul ignore next */", "return", "lookupPaths", "...
Function that returns text to swizzle into the module. @typedef module:lib/requizzle~wrapperFunction @type {function} @param {string} targetPath - The path to the target module. @param {string} parentModulePath - The path to the module that is requiring the target module. @return {string} The text to insert before or after the module's source code. Options for the wrappers that will be swizzled into the target module. @typedef module:lib/requizzle~options @type {Object} @property {Object=} options.extras - Functions that generate text to swizzle into the target module. @property {module:lib/requizzle~wrapperFunction} options.extras.after - Function that returns text to insert after the module's source code. @property {module:lib/requizzle~wrapperFunction} options.extras.before - Function that returns text to insert before the module's source code. @property {(Array.<string>|string)} options.requirePaths - Additional paths to search when resolving module paths in the target module.
[ "Function", "that", "returns", "text", "to", "swizzle", "into", "the", "module", "." ]
3193e1bed6fdfe69fbde99496da6ed383a160680
https://github.com/hegemonic/requizzle/blob/3193e1bed6fdfe69fbde99496da6ed383a160680/lib/requizzle.js#L38-L46
31,999
oxyno-zeta/react-editable-json-tree
src/utils/objectTypes.js
isComponentWillChange
function isComponentWillChange(oldValue, newValue) { const oldType = getObjectType(oldValue); const newType = getObjectType(newValue); return ((oldType === 'Function' || newType === 'Function') && newType !== oldType); }
javascript
function isComponentWillChange(oldValue, newValue) { const oldType = getObjectType(oldValue); const newType = getObjectType(newValue); return ((oldType === 'Function' || newType === 'Function') && newType !== oldType); }
[ "function", "isComponentWillChange", "(", "oldValue", ",", "newValue", ")", "{", "const", "oldType", "=", "getObjectType", "(", "oldValue", ")", ";", "const", "newType", "=", "getObjectType", "(", "newValue", ")", ";", "return", "(", "(", "oldType", "===", "...
Is Component will change ? @param oldValue {*} old value @param newValue {*} new value @returns {boolean} result
[ "Is", "Component", "will", "change", "?" ]
7f322b28c4da44098bc34cfd89b59308e26b20eb
https://github.com/oxyno-zeta/react-editable-json-tree/blob/7f322b28c4da44098bc34cfd89b59308e26b20eb/src/utils/objectTypes.js#L40-L44