repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
karlkfi/ngindox
lib/util.js
routeTypes
function routeTypes(routeMap) { var typeSet = {}; var keys = Object.keys(routeMap); for (var i = 0, len = keys.length; i < len; i++) { var route = routeMap[keys[i]]; var type = routeType(route); typeSet[type] = true; } // Use RouteTypeFields ordering var typeList = []; var fields = Object.keys(RouteTypeFields); for (var i = 0, len = fields.length; i < len; i++) { var type = RouteTypeFields[fields[i]]; if (typeSet[type]) { typeList.push(type) } } return typeList; }
javascript
function routeTypes(routeMap) { var typeSet = {}; var keys = Object.keys(routeMap); for (var i = 0, len = keys.length; i < len; i++) { var route = routeMap[keys[i]]; var type = routeType(route); typeSet[type] = true; } // Use RouteTypeFields ordering var typeList = []; var fields = Object.keys(RouteTypeFields); for (var i = 0, len = fields.length; i < len; i++) { var type = RouteTypeFields[fields[i]]; if (typeSet[type]) { typeList.push(type) } } return typeList; }
[ "function", "routeTypes", "(", "routeMap", ")", "{", "var", "typeSet", "=", "{", "}", ";", "var", "keys", "=", "Object", ".", "keys", "(", "routeMap", ")", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "keys", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "route", "=", "routeMap", "[", "keys", "[", "i", "]", "]", ";", "var", "type", "=", "routeType", "(", "route", ")", ";", "typeSet", "[", "type", "]", "=", "true", ";", "}", "var", "typeList", "=", "[", "]", ";", "var", "fields", "=", "Object", ".", "keys", "(", "RouteTypeFields", ")", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "fields", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "type", "=", "RouteTypeFields", "[", "fields", "[", "i", "]", "]", ";", "if", "(", "typeSet", "[", "type", "]", ")", "{", "typeList", ".", "push", "(", "type", ")", "}", "}", "return", "typeList", ";", "}" ]
Get a list of route types found in the provided route map, in canonical order
[ "Get", "a", "list", "of", "route", "types", "found", "in", "the", "provided", "route", "map", "in", "canonical", "order" ]
2c0e8a682d7bde9e5d73a853f45bf1460f4664e9
https://github.com/karlkfi/ngindox/blob/2c0e8a682d7bde9e5d73a853f45bf1460f4664e9/lib/util.js#L64-L85
train
shobhitsinghal624/passport-google-authcode
lib/passport-google-authcode/strategy.js
GoogleAuthCodeStrategy
function GoogleAuthCodeStrategy(options, verify) { options = options || {}; options.authorizationURL = options.authorizationURL || 'https://accounts.google.com/o/oauth2/v2/auth'; options.tokenURL = options.tokenURL || 'https://www.googleapis.com/oauth2/v4/token'; this._passReqToCallback = options.passReqToCallback; OAuth2Strategy.call(this, options, verify); this.name = 'google-authcode'; }
javascript
function GoogleAuthCodeStrategy(options, verify) { options = options || {}; options.authorizationURL = options.authorizationURL || 'https://accounts.google.com/o/oauth2/v2/auth'; options.tokenURL = options.tokenURL || 'https://www.googleapis.com/oauth2/v4/token'; this._passReqToCallback = options.passReqToCallback; OAuth2Strategy.call(this, options, verify); this.name = 'google-authcode'; }
[ "function", "GoogleAuthCodeStrategy", "(", "options", ",", "verify", ")", "{", "options", "=", "options", "||", "{", "}", ";", "options", ".", "authorizationURL", "=", "options", ".", "authorizationURL", "||", "'https://accounts.google.com/o/oauth2/v2/auth'", ";", "options", ".", "tokenURL", "=", "options", ".", "tokenURL", "||", "'https://www.googleapis.com/oauth2/v4/token'", ";", "this", ".", "_passReqToCallback", "=", "options", ".", "passReqToCallback", ";", "OAuth2Strategy", ".", "call", "(", "this", ",", "options", ",", "verify", ")", ";", "this", ".", "name", "=", "'google-authcode'", ";", "}" ]
`GoogleAuthCodeStrategy` constructor. The Google authentication strategy authenticates requests by delegating to Google using the OAuth 2.0 protocol. Applications must supply a `verify` callback which accepts an `accessToken`, `refreshToken` and service-specific `profile`, and then calls the `done` callback supplying a `user`, which should be set to `false` if the credentials are not valid. If an exception occured, `err` should be set. Options: - `clientID` your Google application's client id - `clientSecret` your Google application's client secret Examples: passport.use(new GoogleAuthCodeStrategy({ clientID: '123-456-789', clientSecret: 'shhh-its-a-secret' }, function(accessToken, refreshToken, profile, done) { User.findOrCreate(..., function (err, user) { done(err, user); }); } )); @param {Object} options @param {Function} verify @api public
[ "GoogleAuthCodeStrategy", "constructor", "." ]
427d5c6290cf9d4568af869935f496f25f62dd6e
https://github.com/shobhitsinghal624/passport-google-authcode/blob/427d5c6290cf9d4568af869935f496f25f62dd6e/lib/passport-google-authcode/strategy.js#L41-L50
train
Spectre/spectre
lib/query.js
isValidDate
function isValidDate(date) { if (moment.isMoment(date)) { return date.isValid(); } else { return moment(date).isValid(); } }
javascript
function isValidDate(date) { if (moment.isMoment(date)) { return date.isValid(); } else { return moment(date).isValid(); } }
[ "function", "isValidDate", "(", "date", ")", "{", "if", "(", "moment", ".", "isMoment", "(", "date", ")", ")", "{", "return", "date", ".", "isValid", "(", ")", ";", "}", "else", "{", "return", "moment", "(", "date", ")", ".", "isValid", "(", ")", ";", "}", "}" ]
Validates a date @param date @returns {boolean}
[ "Validates", "a", "date" ]
5ff2227cd31116699a6a23a9e8c057ad3b729a1c
https://github.com/Spectre/spectre/blob/5ff2227cd31116699a6a23a9e8c057ad3b729a1c/lib/query.js#L10-L16
train
Spectre/spectre
lib/query.js
isValidQuery
function isValidQuery(definition) { var requiredKeys = [ 'event_name', 'resource_type', 'tracker_id' ]; return _.all(requiredKeys, function(key) { return _.has(definition, key); }); }
javascript
function isValidQuery(definition) { var requiredKeys = [ 'event_name', 'resource_type', 'tracker_id' ]; return _.all(requiredKeys, function(key) { return _.has(definition, key); }); }
[ "function", "isValidQuery", "(", "definition", ")", "{", "var", "requiredKeys", "=", "[", "'event_name'", ",", "'resource_type'", ",", "'tracker_id'", "]", ";", "return", "_", ".", "all", "(", "requiredKeys", ",", "function", "(", "key", ")", "{", "return", "_", ".", "has", "(", "definition", ",", "key", ")", ";", "}", ")", ";", "}" ]
Checks for required keys to execute a query @param {definition} Query definition @returns {boolean}
[ "Checks", "for", "required", "keys", "to", "execute", "a", "query" ]
5ff2227cd31116699a6a23a9e8c057ad3b729a1c
https://github.com/Spectre/spectre/blob/5ff2227cd31116699a6a23a9e8c057ad3b729a1c/lib/query.js#L24-L34
train
maxkfranz/weaver
documentation/api/weaver.js-1.0.0-pre/weaver.js
function( fn ){ var req; var fnName; if( $$.is.object(fn) && fn.fn ){ // manual fn req = fnAs( fn.fn, fn.name ); fnName = fn.name; fn = fn.fn; } else if( $$.is.fn(fn) ){ // auto fn req = fn.toString(); fnName = fn.name; } else if( $$.is.string(fn) ){ // stringified fn req = fn; } else if( $$.is.object(fn) ){ // plain object if( fn.proto ){ req = ''; } else { req = fn.name + ' = {};'; } fnName = fn.name; fn = fn.obj; } req += '\n'; var protoreq = function( val, subname ){ if( val.prototype ){ var protoNonempty = false; for( var prop in val.prototype ){ protoNonempty = true; break; }; if( protoNonempty ){ req += fnAsRequire( { name: subname, obj: val, proto: true }, val ); } } }; // pull in prototype if( fn.prototype && fnName != null ){ for( var name in fn.prototype ){ var protoStr = ''; var val = fn.prototype[ name ]; var valStr = stringifyFieldVal( val ); var subname = fnName + '.prototype.' + name; protoStr += subname + ' = ' + valStr + ';\n'; if( protoStr ){ req += protoStr; } protoreq( val, subname ); // subobject with prototype } } // pull in properties for obj/fns if( !$$.is.string(fn) ){ for( var name in fn ){ var propsStr = ''; if( fn.hasOwnProperty(name) ){ var val = fn[ name ]; var valStr = stringifyFieldVal( val ); var subname = fnName + '["' + name + '"]'; propsStr += subname + ' = ' + valStr + ';\n'; } if( propsStr ){ req += propsStr; } protoreq( val, subname ); // subobject with prototype } } return req; }
javascript
function( fn ){ var req; var fnName; if( $$.is.object(fn) && fn.fn ){ // manual fn req = fnAs( fn.fn, fn.name ); fnName = fn.name; fn = fn.fn; } else if( $$.is.fn(fn) ){ // auto fn req = fn.toString(); fnName = fn.name; } else if( $$.is.string(fn) ){ // stringified fn req = fn; } else if( $$.is.object(fn) ){ // plain object if( fn.proto ){ req = ''; } else { req = fn.name + ' = {};'; } fnName = fn.name; fn = fn.obj; } req += '\n'; var protoreq = function( val, subname ){ if( val.prototype ){ var protoNonempty = false; for( var prop in val.prototype ){ protoNonempty = true; break; }; if( protoNonempty ){ req += fnAsRequire( { name: subname, obj: val, proto: true }, val ); } } }; // pull in prototype if( fn.prototype && fnName != null ){ for( var name in fn.prototype ){ var protoStr = ''; var val = fn.prototype[ name ]; var valStr = stringifyFieldVal( val ); var subname = fnName + '.prototype.' + name; protoStr += subname + ' = ' + valStr + ';\n'; if( protoStr ){ req += protoStr; } protoreq( val, subname ); // subobject with prototype } } // pull in properties for obj/fns if( !$$.is.string(fn) ){ for( var name in fn ){ var propsStr = ''; if( fn.hasOwnProperty(name) ){ var val = fn[ name ]; var valStr = stringifyFieldVal( val ); var subname = fnName + '["' + name + '"]'; propsStr += subname + ' = ' + valStr + ';\n'; } if( propsStr ){ req += propsStr; } protoreq( val, subname ); // subobject with prototype } } return req; }
[ "function", "(", "fn", ")", "{", "var", "req", ";", "var", "fnName", ";", "if", "(", "$$", ".", "is", ".", "object", "(", "fn", ")", "&&", "fn", ".", "fn", ")", "{", "req", "=", "fnAs", "(", "fn", ".", "fn", ",", "fn", ".", "name", ")", ";", "fnName", "=", "fn", ".", "name", ";", "fn", "=", "fn", ".", "fn", ";", "}", "else", "if", "(", "$$", ".", "is", ".", "fn", "(", "fn", ")", ")", "{", "req", "=", "fn", ".", "toString", "(", ")", ";", "fnName", "=", "fn", ".", "name", ";", "}", "else", "if", "(", "$$", ".", "is", ".", "string", "(", "fn", ")", ")", "{", "req", "=", "fn", ";", "}", "else", "if", "(", "$$", ".", "is", ".", "object", "(", "fn", ")", ")", "{", "if", "(", "fn", ".", "proto", ")", "{", "req", "=", "''", ";", "}", "else", "{", "req", "=", "fn", ".", "name", "+", "' = {};'", ";", "}", "fnName", "=", "fn", ".", "name", ";", "fn", "=", "fn", ".", "obj", ";", "}", "req", "+=", "'\\n'", ";", "\\n", "var", "protoreq", "=", "function", "(", "val", ",", "subname", ")", "{", "if", "(", "val", ".", "prototype", ")", "{", "var", "protoNonempty", "=", "false", ";", "for", "(", "var", "prop", "in", "val", ".", "prototype", ")", "{", "protoNonempty", "=", "true", ";", "break", ";", "}", ";", "if", "(", "protoNonempty", ")", "{", "req", "+=", "fnAsRequire", "(", "{", "name", ":", "subname", ",", "obj", ":", "val", ",", "proto", ":", "true", "}", ",", "val", ")", ";", "}", "}", "}", ";", "if", "(", "fn", ".", "prototype", "&&", "fnName", "!=", "null", ")", "{", "for", "(", "var", "name", "in", "fn", ".", "prototype", ")", "{", "var", "protoStr", "=", "''", ";", "var", "val", "=", "fn", ".", "prototype", "[", "name", "]", ";", "var", "valStr", "=", "stringifyFieldVal", "(", "val", ")", ";", "var", "subname", "=", "fnName", "+", "'.prototype.'", "+", "name", ";", "protoStr", "+=", "subname", "+", "' = '", "+", "valStr", "+", "';\\n'", ";", "\\n", "if", "(", "protoStr", ")", "{", "req", "+=", "protoStr", ";", "}", "}", "}", "protoreq", "(", "val", ",", "subname", ")", ";", "}" ]
allows for requires with prototypes and subobjs etc
[ "allows", "for", "requires", "with", "prototypes", "and", "subobjs", "etc" ]
bac2535114420379005acdfe2dad06331de88496
https://github.com/maxkfranz/weaver/blob/bac2535114420379005acdfe2dad06331de88496/documentation/api/weaver.js-1.0.0-pre/weaver.js#L949-L1031
train
maxkfranz/weaver
documentation/api/weaver.js-1.0.0-pre/weaver.js
function( m ){ var _p = this._private; if( _p.webworker ){ _p.webworker.postMessage( m ); } if( _p.child ){ _p.child.send( m ); } return this; // chaining }
javascript
function( m ){ var _p = this._private; if( _p.webworker ){ _p.webworker.postMessage( m ); } if( _p.child ){ _p.child.send( m ); } return this; // chaining }
[ "function", "(", "m", ")", "{", "var", "_p", "=", "this", ".", "_private", ";", "if", "(", "_p", ".", "webworker", ")", "{", "_p", ".", "webworker", ".", "postMessage", "(", "m", ")", ";", "}", "if", "(", "_p", ".", "child", ")", "{", "_p", ".", "child", ".", "send", "(", "m", ")", ";", "}", "return", "this", ";", "}" ]
send the thread a message
[ "send", "the", "thread", "a", "message" ]
bac2535114420379005acdfe2dad06331de88496
https://github.com/maxkfranz/weaver/blob/bac2535114420379005acdfe2dad06331de88496/documentation/api/weaver.js-1.0.0-pre/weaver.js#L1206-L1218
train
maxkfranz/weaver
documentation/api/weaver.js-1.0.0-pre/weaver.js
function( fn, as ){ for( var i = 0; i < this.length; i++ ){ var thread = this[i]; thread.require( fn, as ); } return this; }
javascript
function( fn, as ){ for( var i = 0; i < this.length; i++ ){ var thread = this[i]; thread.require( fn, as ); } return this; }
[ "function", "(", "fn", ",", "as", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "length", ";", "i", "++", ")", "{", "var", "thread", "=", "this", "[", "i", "]", ";", "thread", ".", "require", "(", "fn", ",", "as", ")", ";", "}", "return", "this", ";", "}" ]
require fn in all threads
[ "require", "fn", "in", "all", "threads" ]
bac2535114420379005acdfe2dad06331de88496
https://github.com/maxkfranz/weaver/blob/bac2535114420379005acdfe2dad06331de88496/documentation/api/weaver.js-1.0.0-pre/weaver.js#L1346-L1354
train
maxkfranz/weaver
documentation/api/weaver.js-1.0.0-pre/weaver.js
function( fn ){ var pass = this._private.pass.shift(); return this.random().pass( pass ).run( fn ); }
javascript
function( fn ){ var pass = this._private.pass.shift(); return this.random().pass( pass ).run( fn ); }
[ "function", "(", "fn", ")", "{", "var", "pass", "=", "this", ".", "_private", ".", "pass", ".", "shift", "(", ")", ";", "return", "this", ".", "random", "(", ")", ".", "pass", "(", "pass", ")", ".", "run", "(", "fn", ")", ";", "}" ]
run on random thread
[ "run", "on", "random", "thread" ]
bac2535114420379005acdfe2dad06331de88496
https://github.com/maxkfranz/weaver/blob/bac2535114420379005acdfe2dad06331de88496/documentation/api/weaver.js-1.0.0-pre/weaver.js#L1365-L1369
train
maxkfranz/weaver
documentation/api/weaver.js-1.0.0-pre/weaver.js
function( m ){ for( var i = 0; i < this.length; i++ ){ var thread = this[i]; thread.message( m ); } return this; // chaining }
javascript
function( m ){ for( var i = 0; i < this.length; i++ ){ var thread = this[i]; thread.message( m ); } return this; // chaining }
[ "function", "(", "m", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "length", ";", "i", "++", ")", "{", "var", "thread", "=", "this", "[", "i", "]", ";", "thread", ".", "message", "(", "m", ")", ";", "}", "return", "this", ";", "}" ]
send all threads a message
[ "send", "all", "threads", "a", "message" ]
bac2535114420379005acdfe2dad06331de88496
https://github.com/maxkfranz/weaver/blob/bac2535114420379005acdfe2dad06331de88496/documentation/api/weaver.js-1.0.0-pre/weaver.js#L1377-L1385
train
maxkfranz/weaver
documentation/api/weaver.js-1.0.0-pre/weaver.js
function( fn ){ var self = this; var _p = self._private; var subsize = self.spreadSize(); // number of pass eles to handle in each thread var pass = _p.pass.shift().concat([]); // keep a copy var runPs = []; for( var i = 0; i < this.length; i++ ){ var thread = this[i]; var slice = pass.splice( 0, subsize ); var runP = thread.pass( slice ).run( fn ); runPs.push( runP ); var doneEarly = pass.length === 0; if( doneEarly ){ break; } } return $$.Promise.all( runPs ).then(function( thens ){ var postpass = new Array(); var p = 0; // fill postpass with the total result joined from all threads for( var i = 0; i < thens.length; i++ ){ var then = thens[i]; // array result from thread i for( var j = 0; j < then.length; j++ ){ var t = then[j]; // array element postpass[ p++ ] = t; } } return postpass; }); }
javascript
function( fn ){ var self = this; var _p = self._private; var subsize = self.spreadSize(); // number of pass eles to handle in each thread var pass = _p.pass.shift().concat([]); // keep a copy var runPs = []; for( var i = 0; i < this.length; i++ ){ var thread = this[i]; var slice = pass.splice( 0, subsize ); var runP = thread.pass( slice ).run( fn ); runPs.push( runP ); var doneEarly = pass.length === 0; if( doneEarly ){ break; } } return $$.Promise.all( runPs ).then(function( thens ){ var postpass = new Array(); var p = 0; // fill postpass with the total result joined from all threads for( var i = 0; i < thens.length; i++ ){ var then = thens[i]; // array result from thread i for( var j = 0; j < then.length; j++ ){ var t = then[j]; // array element postpass[ p++ ] = t; } } return postpass; }); }
[ "function", "(", "fn", ")", "{", "var", "self", "=", "this", ";", "var", "_p", "=", "self", ".", "_private", ";", "var", "subsize", "=", "self", ".", "spreadSize", "(", ")", ";", "var", "pass", "=", "_p", ".", "pass", ".", "shift", "(", ")", ".", "concat", "(", "[", "]", ")", ";", "var", "runPs", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "length", ";", "i", "++", ")", "{", "var", "thread", "=", "this", "[", "i", "]", ";", "var", "slice", "=", "pass", ".", "splice", "(", "0", ",", "subsize", ")", ";", "var", "runP", "=", "thread", ".", "pass", "(", "slice", ")", ".", "run", "(", "fn", ")", ";", "runPs", ".", "push", "(", "runP", ")", ";", "var", "doneEarly", "=", "pass", ".", "length", "===", "0", ";", "if", "(", "doneEarly", ")", "{", "break", ";", "}", "}", "return", "$$", ".", "Promise", ".", "all", "(", "runPs", ")", ".", "then", "(", "function", "(", "thens", ")", "{", "var", "postpass", "=", "new", "Array", "(", ")", ";", "var", "p", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "thens", ".", "length", ";", "i", "++", ")", "{", "var", "then", "=", "thens", "[", "i", "]", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "then", ".", "length", ";", "j", "++", ")", "{", "var", "t", "=", "then", "[", "j", "]", ";", "postpass", "[", "p", "++", "]", "=", "t", ";", "}", "}", "return", "postpass", ";", "}", ")", ";", "}" ]
split the data into slices to spread the data equally among threads
[ "split", "the", "data", "into", "slices", "to", "spread", "the", "data", "equally", "among", "threads" ]
bac2535114420379005acdfe2dad06331de88496
https://github.com/maxkfranz/weaver/blob/bac2535114420379005acdfe2dad06331de88496/documentation/api/weaver.js-1.0.0-pre/weaver.js#L1420-L1456
train
maxkfranz/weaver
documentation/api/weaver.js-1.0.0-pre/weaver.js
function( cmp ){ var self = this; var P = this._private.pass[0].length; var subsize = this.spreadSize(); var N = this.length; cmp = cmp || function( a, b ){ // default comparison function if( a < b ){ return -1; } else if( a > b ){ return 1; } return 0; }; self.require( cmp, '_$_$_cmp' ); return self.spread(function( split ){ // sort each split normally var sortedSplit = split.sort( _$_$_cmp ); resolve( sortedSplit ); }).then(function( joined ){ // do all the merging in the main thread to minimise data transfer // TODO could do merging in separate threads but would incur add'l cost of data transfer // for each level of the merge var merge = function( i, j, max ){ // don't overflow array j = Math.min( j, P ); max = Math.min( max, P ); // left and right sides of merge var l = i; var r = j; var sorted = []; for( var k = l; k < max; k++ ){ var eleI = joined[i]; var eleJ = joined[j]; if( i < r && ( j >= max || cmp(eleI, eleJ) <= 0 ) ){ sorted.push( eleI ); i++; } else { sorted.push( eleJ ); j++; } } // in the array proper, put the sorted values for( var k = 0; k < sorted.length; k++ ){ // kth sorted item var index = l + k; joined[ index ] = sorted[k]; } }; for( var splitL = subsize; splitL < P; splitL *= 2 ){ // merge until array is "split" as 1 for( var i = 0; i < P; i += 2*splitL ){ merge( i, i + splitL, i + 2*splitL ); } } return joined; }); }
javascript
function( cmp ){ var self = this; var P = this._private.pass[0].length; var subsize = this.spreadSize(); var N = this.length; cmp = cmp || function( a, b ){ // default comparison function if( a < b ){ return -1; } else if( a > b ){ return 1; } return 0; }; self.require( cmp, '_$_$_cmp' ); return self.spread(function( split ){ // sort each split normally var sortedSplit = split.sort( _$_$_cmp ); resolve( sortedSplit ); }).then(function( joined ){ // do all the merging in the main thread to minimise data transfer // TODO could do merging in separate threads but would incur add'l cost of data transfer // for each level of the merge var merge = function( i, j, max ){ // don't overflow array j = Math.min( j, P ); max = Math.min( max, P ); // left and right sides of merge var l = i; var r = j; var sorted = []; for( var k = l; k < max; k++ ){ var eleI = joined[i]; var eleJ = joined[j]; if( i < r && ( j >= max || cmp(eleI, eleJ) <= 0 ) ){ sorted.push( eleI ); i++; } else { sorted.push( eleJ ); j++; } } // in the array proper, put the sorted values for( var k = 0; k < sorted.length; k++ ){ // kth sorted item var index = l + k; joined[ index ] = sorted[k]; } }; for( var splitL = subsize; splitL < P; splitL *= 2 ){ // merge until array is "split" as 1 for( var i = 0; i < P; i += 2*splitL ){ merge( i, i + splitL, i + 2*splitL ); } } return joined; }); }
[ "function", "(", "cmp", ")", "{", "var", "self", "=", "this", ";", "var", "P", "=", "this", ".", "_private", ".", "pass", "[", "0", "]", ".", "length", ";", "var", "subsize", "=", "this", ".", "spreadSize", "(", ")", ";", "var", "N", "=", "this", ".", "length", ";", "cmp", "=", "cmp", "||", "function", "(", "a", ",", "b", ")", "{", "if", "(", "a", "<", "b", ")", "{", "return", "-", "1", ";", "}", "else", "if", "(", "a", ">", "b", ")", "{", "return", "1", ";", "}", "return", "0", ";", "}", ";", "self", ".", "require", "(", "cmp", ",", "'_$_$_cmp'", ")", ";", "return", "self", ".", "spread", "(", "function", "(", "split", ")", "{", "var", "sortedSplit", "=", "split", ".", "sort", "(", "_$_$_cmp", ")", ";", "resolve", "(", "sortedSplit", ")", ";", "}", ")", ".", "then", "(", "function", "(", "joined", ")", "{", "var", "merge", "=", "function", "(", "i", ",", "j", ",", "max", ")", "{", "j", "=", "Math", ".", "min", "(", "j", ",", "P", ")", ";", "max", "=", "Math", ".", "min", "(", "max", ",", "P", ")", ";", "var", "l", "=", "i", ";", "var", "r", "=", "j", ";", "var", "sorted", "=", "[", "]", ";", "for", "(", "var", "k", "=", "l", ";", "k", "<", "max", ";", "k", "++", ")", "{", "var", "eleI", "=", "joined", "[", "i", "]", ";", "var", "eleJ", "=", "joined", "[", "j", "]", ";", "if", "(", "i", "<", "r", "&&", "(", "j", ">=", "max", "||", "cmp", "(", "eleI", ",", "eleJ", ")", "<=", "0", ")", ")", "{", "sorted", ".", "push", "(", "eleI", ")", ";", "i", "++", ";", "}", "else", "{", "sorted", ".", "push", "(", "eleJ", ")", ";", "j", "++", ";", "}", "}", "for", "(", "var", "k", "=", "0", ";", "k", "<", "sorted", ".", "length", ";", "k", "++", ")", "{", "var", "index", "=", "l", "+", "k", ";", "joined", "[", "index", "]", "=", "sorted", "[", "k", "]", ";", "}", "}", ";", "for", "(", "var", "splitL", "=", "subsize", ";", "splitL", "<", "P", ";", "splitL", "*=", "2", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "P", ";", "i", "+=", "2", "*", "splitL", ")", "{", "merge", "(", "i", ",", "i", "+", "splitL", ",", "i", "+", "2", "*", "splitL", ")", ";", "}", "}", "return", "joined", ";", "}", ")", ";", "}" ]
sorts the passed array using a divide and conquer strategy
[ "sorts", "the", "passed", "array", "using", "a", "divide", "and", "conquer", "strategy" ]
bac2535114420379005acdfe2dad06331de88496
https://github.com/maxkfranz/weaver/blob/bac2535114420379005acdfe2dad06331de88496/documentation/api/weaver.js-1.0.0-pre/weaver.js#L1511-L1583
train
yoshuawuyts/from2-string
index.js
fromString
function fromString (string) { assert.equal(typeof string, 'string') return from(function (size, next) { if (string.length <= 0) return this.push(null) const chunk = string.slice(0, size) string = string.slice(size) next(null, chunk) }) }
javascript
function fromString (string) { assert.equal(typeof string, 'string') return from(function (size, next) { if (string.length <= 0) return this.push(null) const chunk = string.slice(0, size) string = string.slice(size) next(null, chunk) }) }
[ "function", "fromString", "(", "string", ")", "{", "assert", ".", "equal", "(", "typeof", "string", ",", "'string'", ")", "return", "from", "(", "function", "(", "size", ",", "next", ")", "{", "if", "(", "string", ".", "length", "<=", "0", ")", "return", "this", ".", "push", "(", "null", ")", "const", "chunk", "=", "string", ".", "slice", "(", "0", ",", "size", ")", "string", "=", "string", ".", "slice", "(", "size", ")", "next", "(", "null", ",", "chunk", ")", "}", ")", "}" ]
create a stream from a string str -> stream
[ "create", "a", "stream", "from", "a", "string", "str", "-", ">", "stream" ]
5bf57ae03db720566538e799eecc0eeb5df0dd39
https://github.com/yoshuawuyts/from2-string/blob/5bf57ae03db720566538e799eecc0eeb5df0dd39/index.js#L8-L19
train
koopjs/geohub
lib/repo.js
repoSha
function repoSha (options, callback) { var user = options.user var repo = options.repo var path = options.path || null var branch = options.branch || 'master' var token = options.token || null if (!user || !repo || !path) { return callback(new Error('must specify user, repo, path')) } var url = '/repos/' + user + '/' + repo + '/contents/' + path request({ url: url, qs: { access_token: token, ref: branch } }, function (err, json) { if (err) return callback(err) if (json.message) return callback(new Error(json.message)) if (json.sha) return callback(null, json.sha) callback(new Error('could not get sha for ' + url)) }) }
javascript
function repoSha (options, callback) { var user = options.user var repo = options.repo var path = options.path || null var branch = options.branch || 'master' var token = options.token || null if (!user || !repo || !path) { return callback(new Error('must specify user, repo, path')) } var url = '/repos/' + user + '/' + repo + '/contents/' + path request({ url: url, qs: { access_token: token, ref: branch } }, function (err, json) { if (err) return callback(err) if (json.message) return callback(new Error(json.message)) if (json.sha) return callback(null, json.sha) callback(new Error('could not get sha for ' + url)) }) }
[ "function", "repoSha", "(", "options", ",", "callback", ")", "{", "var", "user", "=", "options", ".", "user", "var", "repo", "=", "options", ".", "repo", "var", "path", "=", "options", ".", "path", "||", "null", "var", "branch", "=", "options", ".", "branch", "||", "'master'", "var", "token", "=", "options", ".", "token", "||", "null", "if", "(", "!", "user", "||", "!", "repo", "||", "!", "path", ")", "{", "return", "callback", "(", "new", "Error", "(", "'must specify user, repo, path'", ")", ")", "}", "var", "url", "=", "'/repos/'", "+", "user", "+", "'/'", "+", "repo", "+", "'/contents/'", "+", "path", "request", "(", "{", "url", ":", "url", ",", "qs", ":", "{", "access_token", ":", "token", ",", "ref", ":", "branch", "}", "}", ",", "function", "(", "err", ",", "json", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", "if", "(", "json", ".", "message", ")", "return", "callback", "(", "new", "Error", "(", "json", ".", "message", ")", ")", "if", "(", "json", ".", "sha", ")", "return", "callback", "(", "null", ",", "json", ".", "sha", ")", "callback", "(", "new", "Error", "(", "'could not get sha for '", "+", "url", ")", ")", "}", ")", "}" ]
get the SHA of a file in a github repository @param {object} options - user, repo, path (optional), branch (optional), token (optional) @param {Function} callback - err, sha
[ "get", "the", "SHA", "of", "a", "file", "in", "a", "github", "repository" ]
d58c12daba4b33edc0b70333d440572f9c39e6db
https://github.com/koopjs/geohub/blob/d58c12daba4b33edc0b70333d440572f9c39e6db/lib/repo.js#L150-L175
train
Vestorly/ember-cli-deploy-versioning
index.js
setVersioningContext
function setVersioningContext(context, key, value) { const { versioning } = context; versioning[key] = value; if (key === 'previous') { process.env.EMBER_DEPLOY_PREVIOUS_VERSION = value; } if (key === 'current') { process.env.EMBER_DEPLOY_CURRENT_VERSION = value; } return { versioning }; }
javascript
function setVersioningContext(context, key, value) { const { versioning } = context; versioning[key] = value; if (key === 'previous') { process.env.EMBER_DEPLOY_PREVIOUS_VERSION = value; } if (key === 'current') { process.env.EMBER_DEPLOY_CURRENT_VERSION = value; } return { versioning }; }
[ "function", "setVersioningContext", "(", "context", ",", "key", ",", "value", ")", "{", "const", "{", "versioning", "}", "=", "context", ";", "versioning", "[", "key", "]", "=", "value", ";", "if", "(", "key", "===", "'previous'", ")", "{", "process", ".", "env", ".", "EMBER_DEPLOY_PREVIOUS_VERSION", "=", "value", ";", "}", "if", "(", "key", "===", "'current'", ")", "{", "process", ".", "env", ".", "EMBER_DEPLOY_CURRENT_VERSION", "=", "value", ";", "}", "return", "{", "versioning", "}", ";", "}" ]
Assigns values to the `context.versioning` object. @property setVersioningContext @param {Object} context @param {String} key @param {Mixed} value @private
[ "Assigns", "values", "to", "the", "context", ".", "versioning", "object", "." ]
031941e99d9110b688088d378050bac59d4643a3
https://github.com/Vestorly/ember-cli-deploy-versioning/blob/031941e99d9110b688088d378050bac59d4643a3/index.js#L312-L326
train
gabrielcsapo/woof
util.js
flatten
function flatten (flags, allowShorthand, allowExtendedShorthand) { let map = {} Object.keys(flags).forEach((k) => { const { alias, type, validate } = flags[k] let value = { name: k } if (type) value.type = type if (validate) value.validate = validate // include the name as value that can be invoked // also include the shorthands if allowed map[k] = value if (allowShorthand) map[`-${k}`] = value if (allowExtendedShorthand) map[`--${k}`] = value // If the alias is a string we don't need to map anything if (typeof alias === 'string') { if (allowShorthand) map[`-${alias}`] = value if (allowExtendedShorthand) map[`--${alias}`] = value map[alias] = value // the default alias is included } // If the alias is an array, we should map over the values and set them if (Array.isArray(alias)) { alias.forEach((a) => { if (allowShorthand) map[`-${a}`] = value if (allowExtendedShorthand) map[`--${a}`] = value // the default alias is included map[a] = value }) } }) return map }
javascript
function flatten (flags, allowShorthand, allowExtendedShorthand) { let map = {} Object.keys(flags).forEach((k) => { const { alias, type, validate } = flags[k] let value = { name: k } if (type) value.type = type if (validate) value.validate = validate // include the name as value that can be invoked // also include the shorthands if allowed map[k] = value if (allowShorthand) map[`-${k}`] = value if (allowExtendedShorthand) map[`--${k}`] = value // If the alias is a string we don't need to map anything if (typeof alias === 'string') { if (allowShorthand) map[`-${alias}`] = value if (allowExtendedShorthand) map[`--${alias}`] = value map[alias] = value // the default alias is included } // If the alias is an array, we should map over the values and set them if (Array.isArray(alias)) { alias.forEach((a) => { if (allowShorthand) map[`-${a}`] = value if (allowExtendedShorthand) map[`--${a}`] = value // the default alias is included map[a] = value }) } }) return map }
[ "function", "flatten", "(", "flags", ",", "allowShorthand", ",", "allowExtendedShorthand", ")", "{", "let", "map", "=", "{", "}", "Object", ".", "keys", "(", "flags", ")", ".", "forEach", "(", "(", "k", ")", "=>", "{", "const", "{", "alias", ",", "type", ",", "validate", "}", "=", "flags", "[", "k", "]", "let", "value", "=", "{", "name", ":", "k", "}", "if", "(", "type", ")", "value", ".", "type", "=", "type", "if", "(", "validate", ")", "value", ".", "validate", "=", "validate", "map", "[", "k", "]", "=", "value", "if", "(", "allowShorthand", ")", "map", "[", "`", "${", "k", "}", "`", "]", "=", "value", "if", "(", "allowExtendedShorthand", ")", "map", "[", "`", "${", "k", "}", "`", "]", "=", "value", "if", "(", "typeof", "alias", "===", "'string'", ")", "{", "if", "(", "allowShorthand", ")", "map", "[", "`", "${", "alias", "}", "`", "]", "=", "value", "if", "(", "allowExtendedShorthand", ")", "map", "[", "`", "${", "alias", "}", "`", "]", "=", "value", "map", "[", "alias", "]", "=", "value", "}", "if", "(", "Array", ".", "isArray", "(", "alias", ")", ")", "{", "alias", ".", "forEach", "(", "(", "a", ")", "=>", "{", "if", "(", "allowShorthand", ")", "map", "[", "`", "${", "a", "}", "`", "]", "=", "value", "if", "(", "allowExtendedShorthand", ")", "map", "[", "`", "${", "a", "}", "`", "]", "=", "value", "map", "[", "a", "]", "=", "value", "}", ")", "}", "}", ")", "return", "map", "}" ]
turns alias keys into a map @method flatten @param {Array<Object>} flags - keys defined by the user that need to be mapped @param {Boolean} allowShorthand - allows the option to use short hand syntax such as - before the arg @param {Boolean} allowExtendedShorthand - allows the option to use short hand syntax such as -- before the arg @return {Object} - hashmap of mapped keys
[ "turns", "alias", "keys", "into", "a", "map" ]
599f73cf8c767e758210b625483140192d91017b
https://github.com/gabrielcsapo/woof/blob/599f73cf8c767e758210b625483140192d91017b/util.js#L40-L73
train
CreaturePhil/origindb
src/index.js
db
function db(objectName) { if (_.isBoolean(save.hasLoaded)) deasync.loopWhile(() => !save.hasLoaded); if (!_.has(objects, objectName)) objects[objectName] = {}; return createMethods(objects[objectName], save.bind(null, objectName)); }
javascript
function db(objectName) { if (_.isBoolean(save.hasLoaded)) deasync.loopWhile(() => !save.hasLoaded); if (!_.has(objects, objectName)) objects[objectName] = {}; return createMethods(objects[objectName], save.bind(null, objectName)); }
[ "function", "db", "(", "objectName", ")", "{", "if", "(", "_", ".", "isBoolean", "(", "save", ".", "hasLoaded", ")", ")", "deasync", ".", "loopWhile", "(", "(", ")", "=>", "!", "save", ".", "hasLoaded", ")", ";", "if", "(", "!", "_", ".", "has", "(", "objects", ",", "objectName", ")", ")", "objects", "[", "objectName", "]", "=", "{", "}", ";", "return", "createMethods", "(", "objects", "[", "objectName", "]", ",", "save", ".", "bind", "(", "null", ",", "objectName", ")", ")", ";", "}" ]
The database instance. @param {string} objectName @param {Object} methods
[ "The", "database", "instance", "." ]
7b919211c0cfdba8f8737c0cf09f81aa276df9dc
https://github.com/CreaturePhil/origindb/blob/7b919211c0cfdba8f8737c0cf09f81aa276df9dc/src/index.js#L47-L51
train
JCloudYu/beson
deserialize.esm.js
__deserializeBoolean
function __deserializeBoolean(type, start, options) { let end = start; let data = type === DATA_TYPE.TRUE; return { anchor: end, value: data }; }
javascript
function __deserializeBoolean(type, start, options) { let end = start; let data = type === DATA_TYPE.TRUE; return { anchor: end, value: data }; }
[ "function", "__deserializeBoolean", "(", "type", ",", "start", ",", "options", ")", "{", "let", "end", "=", "start", ";", "let", "data", "=", "type", "===", "DATA_TYPE", ".", "TRUE", ";", "return", "{", "anchor", ":", "end", ",", "value", ":", "data", "}", ";", "}" ]
Deserialize boolean data @param {string} type @param {number} start - byteOffset @param {DeserializeOptions} options @returns {{anchor: number, value: boolean}} anchor: byteOffset @private
[ "Deserialize", "boolean", "data" ]
de9f1f6be59599feb1a5e70085b42b0382600d0b
https://github.com/JCloudYu/beson/blob/de9f1f6be59599feb1a5e70085b42b0382600d0b/deserialize.esm.js#L258-L262
train
JCloudYu/beson
deserialize.esm.js
__deserializeInt8
function __deserializeInt8(buffer, start, options) { let end = start + 1; let dataView = new DataView(buffer); let data = dataView.getInt8(start); return { anchor: end, value:options.use_native_types ? data : Int8.from(data) }; }
javascript
function __deserializeInt8(buffer, start, options) { let end = start + 1; let dataView = new DataView(buffer); let data = dataView.getInt8(start); return { anchor: end, value:options.use_native_types ? data : Int8.from(data) }; }
[ "function", "__deserializeInt8", "(", "buffer", ",", "start", ",", "options", ")", "{", "let", "end", "=", "start", "+", "1", ";", "let", "dataView", "=", "new", "DataView", "(", "buffer", ")", ";", "let", "data", "=", "dataView", ".", "getInt8", "(", "start", ")", ";", "return", "{", "anchor", ":", "end", ",", "value", ":", "options", ".", "use_native_types", "?", "data", ":", "Int8", ".", "from", "(", "data", ")", "}", ";", "}" ]
Deserialize Int8 data @param {ArrayBuffer} buffer @param {number} start - byteOffset @param {DeserializeOptions} options @returns {{anchor: number, value: Number|Int8}} anchor: byteOffset @private
[ "Deserialize", "Int8", "data" ]
de9f1f6be59599feb1a5e70085b42b0382600d0b
https://github.com/JCloudYu/beson/blob/de9f1f6be59599feb1a5e70085b42b0382600d0b/deserialize.esm.js#L272-L277
train
JCloudYu/beson
deserialize.esm.js
__deserializeInt16
function __deserializeInt16(buffer, start, options) { let end = start + 2; let dataView = new DataView(buffer); let data = dataView.getInt16(start, true); return { anchor: end, value:options.use_native_types ? data : Int16.from(data) }; }
javascript
function __deserializeInt16(buffer, start, options) { let end = start + 2; let dataView = new DataView(buffer); let data = dataView.getInt16(start, true); return { anchor: end, value:options.use_native_types ? data : Int16.from(data) }; }
[ "function", "__deserializeInt16", "(", "buffer", ",", "start", ",", "options", ")", "{", "let", "end", "=", "start", "+", "2", ";", "let", "dataView", "=", "new", "DataView", "(", "buffer", ")", ";", "let", "data", "=", "dataView", ".", "getInt16", "(", "start", ",", "true", ")", ";", "return", "{", "anchor", ":", "end", ",", "value", ":", "options", ".", "use_native_types", "?", "data", ":", "Int16", ".", "from", "(", "data", ")", "}", ";", "}" ]
Deserialize Int16 data @param {ArrayBuffer} buffer @param {number} start - byteOffset @param {DeserializeOptions} options @returns {{anchor: number, value: Number|Int16}} anchor: byteOffset @private
[ "Deserialize", "Int16", "data" ]
de9f1f6be59599feb1a5e70085b42b0382600d0b
https://github.com/JCloudYu/beson/blob/de9f1f6be59599feb1a5e70085b42b0382600d0b/deserialize.esm.js#L287-L292
train
JCloudYu/beson
deserialize.esm.js
__deserializeInt32
function __deserializeInt32(buffer, start, options) { let end = start + 4; let dataView = new DataView(buffer); let data = dataView.getInt32(start, true); return { anchor: end, value:options.use_native_types ? data : Int32.from(data) }; }
javascript
function __deserializeInt32(buffer, start, options) { let end = start + 4; let dataView = new DataView(buffer); let data = dataView.getInt32(start, true); return { anchor: end, value:options.use_native_types ? data : Int32.from(data) }; }
[ "function", "__deserializeInt32", "(", "buffer", ",", "start", ",", "options", ")", "{", "let", "end", "=", "start", "+", "4", ";", "let", "dataView", "=", "new", "DataView", "(", "buffer", ")", ";", "let", "data", "=", "dataView", ".", "getInt32", "(", "start", ",", "true", ")", ";", "return", "{", "anchor", ":", "end", ",", "value", ":", "options", ".", "use_native_types", "?", "data", ":", "Int32", ".", "from", "(", "data", ")", "}", ";", "}" ]
Deserialize Int32 data @param {ArrayBuffer} buffer @param {number} start - byteOffset @param {DeserializeOptions} options @returns {{anchor: number, value:number|Int32}} anchor: byteOffset @private
[ "Deserialize", "Int32", "data" ]
de9f1f6be59599feb1a5e70085b42b0382600d0b
https://github.com/JCloudYu/beson/blob/de9f1f6be59599feb1a5e70085b42b0382600d0b/deserialize.esm.js#L302-L307
train
JCloudYu/beson
deserialize.esm.js
__deserializeInt64
function __deserializeInt64(buffer, start, options) { let step = 4; let length = 2; let end = start + (step * length); let dataView = new DataView(buffer); let dataArray = []; for (let i = start; i < end; i += step) { dataArray.push(dataView.getUint32(i, true)); } let data = new Int64(new Uint32Array(dataArray)); return { anchor: end, value: data }; }
javascript
function __deserializeInt64(buffer, start, options) { let step = 4; let length = 2; let end = start + (step * length); let dataView = new DataView(buffer); let dataArray = []; for (let i = start; i < end; i += step) { dataArray.push(dataView.getUint32(i, true)); } let data = new Int64(new Uint32Array(dataArray)); return { anchor: end, value: data }; }
[ "function", "__deserializeInt64", "(", "buffer", ",", "start", ",", "options", ")", "{", "let", "step", "=", "4", ";", "let", "length", "=", "2", ";", "let", "end", "=", "start", "+", "(", "step", "*", "length", ")", ";", "let", "dataView", "=", "new", "DataView", "(", "buffer", ")", ";", "let", "dataArray", "=", "[", "]", ";", "for", "(", "let", "i", "=", "start", ";", "i", "<", "end", ";", "i", "+=", "step", ")", "{", "dataArray", ".", "push", "(", "dataView", ".", "getUint32", "(", "i", ",", "true", ")", ")", ";", "}", "let", "data", "=", "new", "Int64", "(", "new", "Uint32Array", "(", "dataArray", ")", ")", ";", "return", "{", "anchor", ":", "end", ",", "value", ":", "data", "}", ";", "}" ]
Deserialize Int64 data @param {ArrayBuffer} buffer @param {number} start - byteOffset @param {DeserializeOptions} options @returns {{anchor: number, value: Int64}} anchor: byteOffset @private
[ "Deserialize", "Int64", "data" ]
de9f1f6be59599feb1a5e70085b42b0382600d0b
https://github.com/JCloudYu/beson/blob/de9f1f6be59599feb1a5e70085b42b0382600d0b/deserialize.esm.js#L317-L328
train
JCloudYu/beson
deserialize.esm.js
__deserializeIntVar
function __deserializeIntVar(buffer, start, options) { const dataBuff = new Uint8Array(buffer); if ( dataBuff[start] > 127 ) { throw new Error( "Cannot support IntVar whose size is greater than 127 bytes" ); } let index = 0, data_size = dataBuff[start], end = start + 1; const result_buffer = new Uint8Array(data_size); while( data_size-- > 0 ) { result_buffer[index] = dataBuff[end]; index++; end++; } let data = new IntVar(result_buffer); return { anchor: end, value: data }; }
javascript
function __deserializeIntVar(buffer, start, options) { const dataBuff = new Uint8Array(buffer); if ( dataBuff[start] > 127 ) { throw new Error( "Cannot support IntVar whose size is greater than 127 bytes" ); } let index = 0, data_size = dataBuff[start], end = start + 1; const result_buffer = new Uint8Array(data_size); while( data_size-- > 0 ) { result_buffer[index] = dataBuff[end]; index++; end++; } let data = new IntVar(result_buffer); return { anchor: end, value: data }; }
[ "function", "__deserializeIntVar", "(", "buffer", ",", "start", ",", "options", ")", "{", "const", "dataBuff", "=", "new", "Uint8Array", "(", "buffer", ")", ";", "if", "(", "dataBuff", "[", "start", "]", ">", "127", ")", "{", "throw", "new", "Error", "(", "\"Cannot support IntVar whose size is greater than 127 bytes\"", ")", ";", "}", "let", "index", "=", "0", ",", "data_size", "=", "dataBuff", "[", "start", "]", ",", "end", "=", "start", "+", "1", ";", "const", "result_buffer", "=", "new", "Uint8Array", "(", "data_size", ")", ";", "while", "(", "data_size", "--", ">", "0", ")", "{", "result_buffer", "[", "index", "]", "=", "dataBuff", "[", "end", "]", ";", "index", "++", ";", "end", "++", ";", "}", "let", "data", "=", "new", "IntVar", "(", "result_buffer", ")", ";", "return", "{", "anchor", ":", "end", ",", "value", ":", "data", "}", ";", "}" ]
Deserialize IntVar data @param {ArrayBuffer} buffer @param {number} start - byteOffset @param {DeserializeOptions} options @returns {{anchor: number, value: IntVar}} anchor: byteOffset @private
[ "Deserialize", "IntVar", "data" ]
de9f1f6be59599feb1a5e70085b42b0382600d0b
https://github.com/JCloudYu/beson/blob/de9f1f6be59599feb1a5e70085b42b0382600d0b/deserialize.esm.js#L401-L419
train
JCloudYu/beson
deserialize.esm.js
__deserializeUInt8
function __deserializeUInt8(buffer, start, options) { let end = start + 1; let dataView = new DataView(buffer); let data = dataView.getUint8(start); return { anchor: end, value:options.use_native_types ? data : UInt8.from(data) }; }
javascript
function __deserializeUInt8(buffer, start, options) { let end = start + 1; let dataView = new DataView(buffer); let data = dataView.getUint8(start); return { anchor: end, value:options.use_native_types ? data : UInt8.from(data) }; }
[ "function", "__deserializeUInt8", "(", "buffer", ",", "start", ",", "options", ")", "{", "let", "end", "=", "start", "+", "1", ";", "let", "dataView", "=", "new", "DataView", "(", "buffer", ")", ";", "let", "data", "=", "dataView", ".", "getUint8", "(", "start", ")", ";", "return", "{", "anchor", ":", "end", ",", "value", ":", "options", ".", "use_native_types", "?", "data", ":", "UInt8", ".", "from", "(", "data", ")", "}", ";", "}" ]
Deserialize UInt8 data @param {ArrayBuffer} buffer @param {number} start - byteOffset @param {DeserializeOptions} options @returns {{anchor: number, value: Number|UInt8}} anchor: byteOffset @private
[ "Deserialize", "UInt8", "data" ]
de9f1f6be59599feb1a5e70085b42b0382600d0b
https://github.com/JCloudYu/beson/blob/de9f1f6be59599feb1a5e70085b42b0382600d0b/deserialize.esm.js#L429-L434
train
JCloudYu/beson
deserialize.esm.js
__deserializeUInt16
function __deserializeUInt16(buffer, start, options) { let end = start + 2; let dataView = new DataView(buffer); let data = dataView.getUint16(start, true); return { anchor: end, value:options.use_native_types ? data : UInt16.from(data) }; }
javascript
function __deserializeUInt16(buffer, start, options) { let end = start + 2; let dataView = new DataView(buffer); let data = dataView.getUint16(start, true); return { anchor: end, value:options.use_native_types ? data : UInt16.from(data) }; }
[ "function", "__deserializeUInt16", "(", "buffer", ",", "start", ",", "options", ")", "{", "let", "end", "=", "start", "+", "2", ";", "let", "dataView", "=", "new", "DataView", "(", "buffer", ")", ";", "let", "data", "=", "dataView", ".", "getUint16", "(", "start", ",", "true", ")", ";", "return", "{", "anchor", ":", "end", ",", "value", ":", "options", ".", "use_native_types", "?", "data", ":", "UInt16", ".", "from", "(", "data", ")", "}", ";", "}" ]
Deserialize UInt16 data @param {ArrayBuffer} buffer @param {number} start - byteOffset @param {DeserializeOptions} options @returns {{anchor: number, value: Number|UInt16}} anchor: byteOffset @private
[ "Deserialize", "UInt16", "data" ]
de9f1f6be59599feb1a5e70085b42b0382600d0b
https://github.com/JCloudYu/beson/blob/de9f1f6be59599feb1a5e70085b42b0382600d0b/deserialize.esm.js#L444-L449
train
JCloudYu/beson
deserialize.esm.js
__deserializeUInt32
function __deserializeUInt32(buffer, start, options) { let end = start + 4; let dataView = new DataView(buffer); let data = dataView.getUint32(start, true); return { anchor: end, value:options.use_native_types ? data : UInt32.from(data) }; }
javascript
function __deserializeUInt32(buffer, start, options) { let end = start + 4; let dataView = new DataView(buffer); let data = dataView.getUint32(start, true); return { anchor: end, value:options.use_native_types ? data : UInt32.from(data) }; }
[ "function", "__deserializeUInt32", "(", "buffer", ",", "start", ",", "options", ")", "{", "let", "end", "=", "start", "+", "4", ";", "let", "dataView", "=", "new", "DataView", "(", "buffer", ")", ";", "let", "data", "=", "dataView", ".", "getUint32", "(", "start", ",", "true", ")", ";", "return", "{", "anchor", ":", "end", ",", "value", ":", "options", ".", "use_native_types", "?", "data", ":", "UInt32", ".", "from", "(", "data", ")", "}", ";", "}" ]
Deserialize UInt32 data @param {ArrayBuffer} buffer @param {number} start - byteOffset @param {DeserializeOptions} options @returns {{anchor: number, value:number|UInt32}} anchor: byteOffset @private
[ "Deserialize", "UInt32", "data" ]
de9f1f6be59599feb1a5e70085b42b0382600d0b
https://github.com/JCloudYu/beson/blob/de9f1f6be59599feb1a5e70085b42b0382600d0b/deserialize.esm.js#L459-L464
train
JCloudYu/beson
deserialize.esm.js
__deserializeUIntVar
function __deserializeUIntVar(buffer, start, options) { const dataBuff = new Uint8Array(buffer); if ( dataBuff[start] > 127 ) { throw new Error( "Cannot support UIntVar whose size is greater than 127 bytes" ); } let index = 0, data_size = dataBuff[start], end = start + 1; const result_buffer = new Uint8Array(data_size); while( data_size-- > 0 ) { result_buffer[index] = dataBuff[end]; index++; end++; } let data = new UIntVar(result_buffer); return { anchor: end, value: data }; }
javascript
function __deserializeUIntVar(buffer, start, options) { const dataBuff = new Uint8Array(buffer); if ( dataBuff[start] > 127 ) { throw new Error( "Cannot support UIntVar whose size is greater than 127 bytes" ); } let index = 0, data_size = dataBuff[start], end = start + 1; const result_buffer = new Uint8Array(data_size); while( data_size-- > 0 ) { result_buffer[index] = dataBuff[end]; index++; end++; } let data = new UIntVar(result_buffer); return { anchor: end, value: data }; }
[ "function", "__deserializeUIntVar", "(", "buffer", ",", "start", ",", "options", ")", "{", "const", "dataBuff", "=", "new", "Uint8Array", "(", "buffer", ")", ";", "if", "(", "dataBuff", "[", "start", "]", ">", "127", ")", "{", "throw", "new", "Error", "(", "\"Cannot support UIntVar whose size is greater than 127 bytes\"", ")", ";", "}", "let", "index", "=", "0", ",", "data_size", "=", "dataBuff", "[", "start", "]", ",", "end", "=", "start", "+", "1", ";", "const", "result_buffer", "=", "new", "Uint8Array", "(", "data_size", ")", ";", "while", "(", "data_size", "--", ">", "0", ")", "{", "result_buffer", "[", "index", "]", "=", "dataBuff", "[", "end", "]", ";", "index", "++", ";", "end", "++", ";", "}", "let", "data", "=", "new", "UIntVar", "(", "result_buffer", ")", ";", "return", "{", "anchor", ":", "end", ",", "value", ":", "data", "}", ";", "}" ]
Deserialize UIntVar data @param {ArrayBuffer} buffer @param {number} start - byteOffset @param {DeserializeOptions} options @returns {{anchor: number, value: UIntVar}} anchor: byteOffset @private
[ "Deserialize", "UIntVar", "data" ]
de9f1f6be59599feb1a5e70085b42b0382600d0b
https://github.com/JCloudYu/beson/blob/de9f1f6be59599feb1a5e70085b42b0382600d0b/deserialize.esm.js#L558-L576
train
JCloudYu/beson
deserialize.esm.js
__deserializeFloat32
function __deserializeFloat32(buffer, start, options) { let end = start + 4; let dataView = new DataView(buffer); let data = dataView.getFloat32(start, true); return { anchor: end, value: data }; }
javascript
function __deserializeFloat32(buffer, start, options) { let end = start + 4; let dataView = new DataView(buffer); let data = dataView.getFloat32(start, true); return { anchor: end, value: data }; }
[ "function", "__deserializeFloat32", "(", "buffer", ",", "start", ",", "options", ")", "{", "let", "end", "=", "start", "+", "4", ";", "let", "dataView", "=", "new", "DataView", "(", "buffer", ")", ";", "let", "data", "=", "dataView", ".", "getFloat32", "(", "start", ",", "true", ")", ";", "return", "{", "anchor", ":", "end", ",", "value", ":", "data", "}", ";", "}" ]
Deserialize float data @param {ArrayBuffer} buffer @param {number} start - byteOffset @param {DeserializeOptions} options @returns {{anchor: number, value: number}} anchor: byteOffset, value: double @private
[ "Deserialize", "float", "data" ]
de9f1f6be59599feb1a5e70085b42b0382600d0b
https://github.com/JCloudYu/beson/blob/de9f1f6be59599feb1a5e70085b42b0382600d0b/deserialize.esm.js#L586-L591
train
JCloudYu/beson
deserialize.esm.js
__deserializeFloat64
function __deserializeFloat64(buffer, start, options) { let end = start + 8; let dataView = new DataView(buffer); let data = dataView.getFloat64(start, true); return { anchor: end, value: data }; }
javascript
function __deserializeFloat64(buffer, start, options) { let end = start + 8; let dataView = new DataView(buffer); let data = dataView.getFloat64(start, true); return { anchor: end, value: data }; }
[ "function", "__deserializeFloat64", "(", "buffer", ",", "start", ",", "options", ")", "{", "let", "end", "=", "start", "+", "8", ";", "let", "dataView", "=", "new", "DataView", "(", "buffer", ")", ";", "let", "data", "=", "dataView", ".", "getFloat64", "(", "start", ",", "true", ")", ";", "return", "{", "anchor", ":", "end", ",", "value", ":", "data", "}", ";", "}" ]
Deserialize double data @param {ArrayBuffer} buffer @param {number} start - byteOffset @param {DeserializeOptions} options @returns {{anchor: number, value: number}} anchor: byteOffset, value: double @private
[ "Deserialize", "double", "data" ]
de9f1f6be59599feb1a5e70085b42b0382600d0b
https://github.com/JCloudYu/beson/blob/de9f1f6be59599feb1a5e70085b42b0382600d0b/deserialize.esm.js#L601-L606
train
JCloudYu/beson
deserialize.esm.js
__deserializeArray
function __deserializeArray(buffer, start, options) { let dataView = new DataView(buffer); let length = dataView.getUint32(start, true); start += 4; let end = start + length; let data = []; while (start < end) { let subType, subData; ({ anchor: start, value: subType } = __deserializeType(buffer, start, options)); ({ anchor: start, value: subData } = __deserializeData(subType, buffer, start, options)); data.push(subData); } return { anchor: end, value: data }; }
javascript
function __deserializeArray(buffer, start, options) { let dataView = new DataView(buffer); let length = dataView.getUint32(start, true); start += 4; let end = start + length; let data = []; while (start < end) { let subType, subData; ({ anchor: start, value: subType } = __deserializeType(buffer, start, options)); ({ anchor: start, value: subData } = __deserializeData(subType, buffer, start, options)); data.push(subData); } return { anchor: end, value: data }; }
[ "function", "__deserializeArray", "(", "buffer", ",", "start", ",", "options", ")", "{", "let", "dataView", "=", "new", "DataView", "(", "buffer", ")", ";", "let", "length", "=", "dataView", ".", "getUint32", "(", "start", ",", "true", ")", ";", "start", "+=", "4", ";", "let", "end", "=", "start", "+", "length", ";", "let", "data", "=", "[", "]", ";", "while", "(", "start", "<", "end", ")", "{", "let", "subType", ",", "subData", ";", "(", "{", "anchor", ":", "start", ",", "value", ":", "subType", "}", "=", "__deserializeType", "(", "buffer", ",", "start", ",", "options", ")", ")", ";", "(", "{", "anchor", ":", "start", ",", "value", ":", "subData", "}", "=", "__deserializeData", "(", "subType", ",", "buffer", ",", "start", ",", "options", ")", ")", ";", "data", ".", "push", "(", "subData", ")", ";", "}", "return", "{", "anchor", ":", "end", ",", "value", ":", "data", "}", ";", "}" ]
Deserialize array data @param {ArrayBuffer} buffer @param {number} start - byteOffset @param {DeserializeOptions} options @returns {{anchor: number, value: *[]}} anchor: byteOffset @private
[ "Deserialize", "array", "data" ]
de9f1f6be59599feb1a5e70085b42b0382600d0b
https://github.com/JCloudYu/beson/blob/de9f1f6be59599feb1a5e70085b42b0382600d0b/deserialize.esm.js#L660-L673
train
JCloudYu/beson
deserialize.esm.js
__deserializeObject
function __deserializeObject(buffer, start, options) { let dataView = new DataView(buffer); let length = dataView.getUint32(start, true); start += 4; let end = start + length; let data = {}; while (start < end) { let subType, subKey, subData; ({ anchor: start, value: subType } = __deserializeType(buffer, start, options)); ({ anchor: start, value: subKey } = __deserializeShortString(buffer, start, options)); ({ anchor: start, value: subData } = __deserializeData(subType, buffer, start, options)); data[subKey] = subData; } return { anchor: end, value: data }; }
javascript
function __deserializeObject(buffer, start, options) { let dataView = new DataView(buffer); let length = dataView.getUint32(start, true); start += 4; let end = start + length; let data = {}; while (start < end) { let subType, subKey, subData; ({ anchor: start, value: subType } = __deserializeType(buffer, start, options)); ({ anchor: start, value: subKey } = __deserializeShortString(buffer, start, options)); ({ anchor: start, value: subData } = __deserializeData(subType, buffer, start, options)); data[subKey] = subData; } return { anchor: end, value: data }; }
[ "function", "__deserializeObject", "(", "buffer", ",", "start", ",", "options", ")", "{", "let", "dataView", "=", "new", "DataView", "(", "buffer", ")", ";", "let", "length", "=", "dataView", ".", "getUint32", "(", "start", ",", "true", ")", ";", "start", "+=", "4", ";", "let", "end", "=", "start", "+", "length", ";", "let", "data", "=", "{", "}", ";", "while", "(", "start", "<", "end", ")", "{", "let", "subType", ",", "subKey", ",", "subData", ";", "(", "{", "anchor", ":", "start", ",", "value", ":", "subType", "}", "=", "__deserializeType", "(", "buffer", ",", "start", ",", "options", ")", ")", ";", "(", "{", "anchor", ":", "start", ",", "value", ":", "subKey", "}", "=", "__deserializeShortString", "(", "buffer", ",", "start", ",", "options", ")", ")", ";", "(", "{", "anchor", ":", "start", ",", "value", ":", "subData", "}", "=", "__deserializeData", "(", "subType", ",", "buffer", ",", "start", ",", "options", ")", ")", ";", "data", "[", "subKey", "]", "=", "subData", ";", "}", "return", "{", "anchor", ":", "end", ",", "value", ":", "data", "}", ";", "}" ]
Deserialize object data @param {ArrayBuffer} buffer @param {number} start - byteOffset @param {DeserializeOptions} options @returns {{anchor: number, value: {}}} anchor: byteOffset @private
[ "Deserialize", "object", "data" ]
de9f1f6be59599feb1a5e70085b42b0382600d0b
https://github.com/JCloudYu/beson/blob/de9f1f6be59599feb1a5e70085b42b0382600d0b/deserialize.esm.js#L712-L726
train
JCloudYu/beson
deserialize.esm.js
__deserializeDate
function __deserializeDate(buffer, start, options) { let end = start + 8; let dataView = new DataView(buffer); let data = new Date(dataView.getFloat64(start, true)); return { anchor: end, value: data }; }
javascript
function __deserializeDate(buffer, start, options) { let end = start + 8; let dataView = new DataView(buffer); let data = new Date(dataView.getFloat64(start, true)); return { anchor: end, value: data }; }
[ "function", "__deserializeDate", "(", "buffer", ",", "start", ",", "options", ")", "{", "let", "end", "=", "start", "+", "8", ";", "let", "dataView", "=", "new", "DataView", "(", "buffer", ")", ";", "let", "data", "=", "new", "Date", "(", "dataView", ".", "getFloat64", "(", "start", ",", "true", ")", ")", ";", "return", "{", "anchor", ":", "end", ",", "value", ":", "data", "}", ";", "}" ]
Deserialize date data @param {ArrayBuffer} buffer @param {number} start - byteOffset @param {DeserializeOptions} options @returns {{anchor: number, value: Date}} anchor: byteOffset @private
[ "Deserialize", "date", "data" ]
de9f1f6be59599feb1a5e70085b42b0382600d0b
https://github.com/JCloudYu/beson/blob/de9f1f6be59599feb1a5e70085b42b0382600d0b/deserialize.esm.js#L766-L771
train
JCloudYu/beson
deserialize.esm.js
__deserializeObjectId
function __deserializeObjectId(buffer, start, options) { let step = 1; let length = 12; let end = start + length; let dataView = new DataView(buffer); let dataArray = []; for (let i = start; i < end; i += step) { dataArray.push(dataView.getUint8(i)); } let data = new ObjectId(Uint8Array.from(dataArray).buffer); return { anchor: end, value: data }; }
javascript
function __deserializeObjectId(buffer, start, options) { let step = 1; let length = 12; let end = start + length; let dataView = new DataView(buffer); let dataArray = []; for (let i = start; i < end; i += step) { dataArray.push(dataView.getUint8(i)); } let data = new ObjectId(Uint8Array.from(dataArray).buffer); return { anchor: end, value: data }; }
[ "function", "__deserializeObjectId", "(", "buffer", ",", "start", ",", "options", ")", "{", "let", "step", "=", "1", ";", "let", "length", "=", "12", ";", "let", "end", "=", "start", "+", "length", ";", "let", "dataView", "=", "new", "DataView", "(", "buffer", ")", ";", "let", "dataArray", "=", "[", "]", ";", "for", "(", "let", "i", "=", "start", ";", "i", "<", "end", ";", "i", "+=", "step", ")", "{", "dataArray", ".", "push", "(", "dataView", ".", "getUint8", "(", "i", ")", ")", ";", "}", "let", "data", "=", "new", "ObjectId", "(", "Uint8Array", ".", "from", "(", "dataArray", ")", ".", "buffer", ")", ";", "return", "{", "anchor", ":", "end", ",", "value", ":", "data", "}", ";", "}" ]
Deserialize ObjectId data @param {ArrayBuffer} buffer @param {number} start - byteOffset @param {DeserializeOptions} options @returns {{anchor: number, value: ObjectId}} anchor: byteOffset @private
[ "Deserialize", "ObjectId", "data" ]
de9f1f6be59599feb1a5e70085b42b0382600d0b
https://github.com/JCloudYu/beson/blob/de9f1f6be59599feb1a5e70085b42b0382600d0b/deserialize.esm.js#L781-L792
train
JCloudYu/beson
deserialize.esm.js
__deserializeArrayBuffer
function __deserializeArrayBuffer(buffer, start, options) { let end = start + 4; let [length] = new Uint32Array(buffer.slice(start, end)); end = end + length; return {anchor:end, value:buffer.slice(start+4, end)}; }
javascript
function __deserializeArrayBuffer(buffer, start, options) { let end = start + 4; let [length] = new Uint32Array(buffer.slice(start, end)); end = end + length; return {anchor:end, value:buffer.slice(start+4, end)}; }
[ "function", "__deserializeArrayBuffer", "(", "buffer", ",", "start", ",", "options", ")", "{", "let", "end", "=", "start", "+", "4", ";", "let", "[", "length", "]", "=", "new", "Uint32Array", "(", "buffer", ".", "slice", "(", "start", ",", "end", ")", ")", ";", "end", "=", "end", "+", "length", ";", "return", "{", "anchor", ":", "end", ",", "value", ":", "buffer", ".", "slice", "(", "start", "+", "4", ",", "end", ")", "}", ";", "}" ]
Deserialize ArrayBuffer object @param {ArrayBuffer} buffer @param {Number} start @returns {{anchor:Number, value:ArrayBuffer}} @param {DeserializeOptions} options @private
[ "Deserialize", "ArrayBuffer", "object" ]
de9f1f6be59599feb1a5e70085b42b0382600d0b
https://github.com/JCloudYu/beson/blob/de9f1f6be59599feb1a5e70085b42b0382600d0b/deserialize.esm.js#L802-L808
train
jabney/regex-replace-loader
index.js
getRegex
function getRegex(regex, flags) { var result = typeOf(regex) === 'String' ? new RegExp(regex, flags || '') : regex if (typeOf(result) !== 'RegExp') { throw new Error( NAME + ': option "regex" must be a string or a RegExp object') } return result }
javascript
function getRegex(regex, flags) { var result = typeOf(regex) === 'String' ? new RegExp(regex, flags || '') : regex if (typeOf(result) !== 'RegExp') { throw new Error( NAME + ': option "regex" must be a string or a RegExp object') } return result }
[ "function", "getRegex", "(", "regex", ",", "flags", ")", "{", "var", "result", "=", "typeOf", "(", "regex", ")", "===", "'String'", "?", "new", "RegExp", "(", "regex", ",", "flags", "||", "''", ")", ":", "regex", "if", "(", "typeOf", "(", "result", ")", "!==", "'RegExp'", ")", "{", "throw", "new", "Error", "(", "NAME", "+", "': option \"regex\" must be a string or a RegExp object'", ")", "}", "return", "result", "}" ]
Transform regex into a RegExp if it isn't one already. @param {any} regex @param {string} flags @returns {RegExp}
[ "Transform", "regex", "into", "a", "RegExp", "if", "it", "isn", "t", "one", "already", "." ]
02bd4a780a39223b682ead55312306e32f7a7755
https://github.com/jabney/regex-replace-loader/blob/02bd4a780a39223b682ead55312306e32f7a7755/index.js#L67-L78
train
jabney/regex-replace-loader
index.js
getMatchFn
function getMatchFn(valueFn) { return function () { var len = arguments.length // Create a RegExp match object. var match = Array.prototype.slice.call(arguments, 0, -2) .reduce(function (map, g, i) { map[i] = g return map }, {index: arguments[len - 2], input: arguments[len - 1]}) // Call the original function. return valueFn(match) } }
javascript
function getMatchFn(valueFn) { return function () { var len = arguments.length // Create a RegExp match object. var match = Array.prototype.slice.call(arguments, 0, -2) .reduce(function (map, g, i) { map[i] = g return map }, {index: arguments[len - 2], input: arguments[len - 1]}) // Call the original function. return valueFn(match) } }
[ "function", "getMatchFn", "(", "valueFn", ")", "{", "return", "function", "(", ")", "{", "var", "len", "=", "arguments", ".", "length", "var", "match", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ",", "-", "2", ")", ".", "reduce", "(", "function", "(", "map", ",", "g", ",", "i", ")", "{", "map", "[", "i", "]", "=", "g", "return", "map", "}", ",", "{", "index", ":", "arguments", "[", "len", "-", "2", "]", ",", "input", ":", "arguments", "[", "len", "-", "1", "]", "}", ")", "return", "valueFn", "(", "match", ")", "}", "}" ]
Return a function for use with string.replace that converts that function's arguments into a RegExpMatchArray and calls the value function. @param {(match: RegExpMatchArray) => string} valueFn @returns {(m: string, ...args: string[], i: number, s: string) => string}
[ "Return", "a", "function", "for", "use", "with", "string", ".", "replace", "that", "converts", "that", "function", "s", "arguments", "into", "a", "RegExpMatchArray", "and", "calls", "the", "value", "function", "." ]
02bd4a780a39223b682ead55312306e32f7a7755
https://github.com/jabney/regex-replace-loader/blob/02bd4a780a39223b682ead55312306e32f7a7755/index.js#L108-L120
train
jabney/regex-replace-loader
index.js
replace
function replace(regex, source, options) { var valueOrFn = getValueOrMatchFn(options.value) source.replace(regex, function () { return '' }) return source.replace(regex, valueOrFn) }
javascript
function replace(regex, source, options) { var valueOrFn = getValueOrMatchFn(options.value) source.replace(regex, function () { return '' }) return source.replace(regex, valueOrFn) }
[ "function", "replace", "(", "regex", ",", "source", ",", "options", ")", "{", "var", "valueOrFn", "=", "getValueOrMatchFn", "(", "options", ".", "value", ")", "source", ".", "replace", "(", "regex", ",", "function", "(", ")", "{", "return", "''", "}", ")", "return", "source", ".", "replace", "(", "regex", ",", "valueOrFn", ")", "}" ]
Execute a replace operation and return the modified source. @param {RegExp} regex @param {string} source @param {LoaderOptions} options @returns {string}
[ "Execute", "a", "replace", "operation", "and", "return", "the", "modified", "source", "." ]
02bd4a780a39223b682ead55312306e32f7a7755
https://github.com/jabney/regex-replace-loader/blob/02bd4a780a39223b682ead55312306e32f7a7755/index.js#L130-L134
train
dvhb/webpack
scripts/getConfig.js
validateDependency
function validateDependency(packageJson, dependency) { const version = findDependency(dependency.package, packageJson); if (!version) { return; } let major; try { major = semverUtils.parseRange(version)[0].major; } catch (exception) { console.log('DvhbWebpack: cannot parse ' + dependency.name + ' version which is "' + version + '".'); console.log('DvhbWebpack might not work properly. Please report this issue at ' + consts.BUGS_URL); console.log(); } if (major < dependency.from) { throw new DvhbWebpackError('DvhbWebpack: ' + dependency.name + ' ' + dependency.from + ' is required, ' + 'you are using version ' + major + '.'); } else if (major > dependency.to) { console.log('DvhbWebpack: ' + dependency.name + ' is supported up to version ' + dependency.to + ', ' + 'you are using version ' + major + '.'); console.log('DvhbWebpack might not work properly, report bugs at ' + consts.BUGS_URL); console.log(); } }
javascript
function validateDependency(packageJson, dependency) { const version = findDependency(dependency.package, packageJson); if (!version) { return; } let major; try { major = semverUtils.parseRange(version)[0].major; } catch (exception) { console.log('DvhbWebpack: cannot parse ' + dependency.name + ' version which is "' + version + '".'); console.log('DvhbWebpack might not work properly. Please report this issue at ' + consts.BUGS_URL); console.log(); } if (major < dependency.from) { throw new DvhbWebpackError('DvhbWebpack: ' + dependency.name + ' ' + dependency.from + ' is required, ' + 'you are using version ' + major + '.'); } else if (major > dependency.to) { console.log('DvhbWebpack: ' + dependency.name + ' is supported up to version ' + dependency.to + ', ' + 'you are using version ' + major + '.'); console.log('DvhbWebpack might not work properly, report bugs at ' + consts.BUGS_URL); console.log(); } }
[ "function", "validateDependency", "(", "packageJson", ",", "dependency", ")", "{", "const", "version", "=", "findDependency", "(", "dependency", ".", "package", ",", "packageJson", ")", ";", "if", "(", "!", "version", ")", "{", "return", ";", "}", "let", "major", ";", "try", "{", "major", "=", "semverUtils", ".", "parseRange", "(", "version", ")", "[", "0", "]", ".", "major", ";", "}", "catch", "(", "exception", ")", "{", "console", ".", "log", "(", "'DvhbWebpack: cannot parse '", "+", "dependency", ".", "name", "+", "' version which is \"'", "+", "version", "+", "'\".'", ")", ";", "console", ".", "log", "(", "'DvhbWebpack might not work properly. Please report this issue at '", "+", "consts", ".", "BUGS_URL", ")", ";", "console", ".", "log", "(", ")", ";", "}", "if", "(", "major", "<", "dependency", ".", "from", ")", "{", "throw", "new", "DvhbWebpackError", "(", "'DvhbWebpack: '", "+", "dependency", ".", "name", "+", "' '", "+", "dependency", ".", "from", "+", "' is required, '", "+", "'you are using version '", "+", "major", "+", "'.'", ")", ";", "}", "else", "if", "(", "major", ">", "dependency", ".", "to", ")", "{", "console", ".", "log", "(", "'DvhbWebpack: '", "+", "dependency", ".", "name", "+", "' is supported up to version '", "+", "dependency", ".", "to", "+", "', '", "+", "'you are using version '", "+", "major", "+", "'.'", ")", ";", "console", ".", "log", "(", "'DvhbWebpack might not work properly, report bugs at '", "+", "consts", ".", "BUGS_URL", ")", ";", "console", ".", "log", "(", ")", ";", "}", "}" ]
Check versions of a project dependency. @param {Object} packageJson package.json. @param {Object} dependency Dependency details.
[ "Check", "versions", "of", "a", "project", "dependency", "." ]
1097f6c44f2d8da631e4df9ec0a01db23dbb352f
https://github.com/dvhb/webpack/blob/1097f6c44f2d8da631e4df9ec0a01db23dbb352f/scripts/getConfig.js#L205-L231
train
karlkfi/ngindox
lib/nginx-transformer.js
toRouteMap
function toRouteMap(routeList) { var routeMap = {}; for (var i = 0, len = routeList.length; i < len; i++) { var route = routeList[i]; routeMap[route['path']] = route; } return routeMap; }
javascript
function toRouteMap(routeList) { var routeMap = {}; for (var i = 0, len = routeList.length; i < len; i++) { var route = routeList[i]; routeMap[route['path']] = route; } return routeMap; }
[ "function", "toRouteMap", "(", "routeList", ")", "{", "var", "routeMap", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "routeList", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "route", "=", "routeList", "[", "i", "]", ";", "routeMap", "[", "route", "[", "'path'", "]", "]", "=", "route", ";", "}", "return", "routeMap", ";", "}" ]
Transforms route list into a map of routes indexed by path.
[ "Transforms", "route", "list", "into", "a", "map", "of", "routes", "indexed", "by", "path", "." ]
2c0e8a682d7bde9e5d73a853f45bf1460f4664e9
https://github.com/karlkfi/ngindox/blob/2c0e8a682d7bde9e5d73a853f45bf1460f4664e9/lib/nginx-transformer.js#L197-L204
train
hash-bang/Monoxide
index.js
function() { var doc = this; var newDoc = {}; _.forEach(this, function(v, k) { if (doc.hasOwnProperty(k) && !_.startsWith(k, '$')) newDoc[k] = _.clone(v); }); return newDoc; }
javascript
function() { var doc = this; var newDoc = {}; _.forEach(this, function(v, k) { if (doc.hasOwnProperty(k) && !_.startsWith(k, '$')) newDoc[k] = _.clone(v); }); return newDoc; }
[ "function", "(", ")", "{", "var", "doc", "=", "this", ";", "var", "newDoc", "=", "{", "}", ";", "_", ".", "forEach", "(", "this", ",", "function", "(", "v", ",", "k", ")", "{", "if", "(", "doc", ".", "hasOwnProperty", "(", "k", ")", "&&", "!", "_", ".", "startsWith", "(", "k", ",", "'$'", ")", ")", "newDoc", "[", "k", "]", "=", "_", ".", "clone", "(", "v", ")", ";", "}", ")", ";", "return", "newDoc", ";", "}" ]
Transform a MonoxideDocument into a plain JavaScript object @return {Object} Plain JavaScript object with all special properties and other gunk removed
[ "Transform", "a", "MonoxideDocument", "into", "a", "plain", "JavaScript", "object" ]
76b1cf33c8e5b6e36801daa31bde9b422601c3a6
https://github.com/hash-bang/Monoxide/blob/76b1cf33c8e5b6e36801daa31bde9b422601c3a6/index.js#L2026-L2034
train
hash-bang/Monoxide
index.js
function() { var doc = this; var outDoc = doc.toObject(); // Rely on the toObject() syntax to strip out rubbish doc.getOIDs().forEach(function(node) { switch (node.fkType) { case 'objectId': var oidLeaf = _.get(doc, node.docPath); if (_.isUndefined(oidLeaf)) return; // Ignore undefined if (!o.utilities.isObjectID(oidLeaf)) { if (_.has(oidLeaf, '_id')) { // Already populated? _.set(outDoc, node.docPath, o.utilities.objectID(oidLeaf._id)); } else { // Convert to an OID _.set(outDoc, node.docPath, o.utilities.objectID(oidLeaf)); } } break; case 'objectIdArray': var oidLeaf = _.get(doc, node.schemaPath); _.set(outDoc, node.schemaPath, oidLeaf.map(function(leaf) { return o.utilities.isObjectID(leaf) ? leaf : o.utilities.objectID(leaf); })); break; default: return; // Ignore unsupported OID types } }); return outDoc; }
javascript
function() { var doc = this; var outDoc = doc.toObject(); // Rely on the toObject() syntax to strip out rubbish doc.getOIDs().forEach(function(node) { switch (node.fkType) { case 'objectId': var oidLeaf = _.get(doc, node.docPath); if (_.isUndefined(oidLeaf)) return; // Ignore undefined if (!o.utilities.isObjectID(oidLeaf)) { if (_.has(oidLeaf, '_id')) { // Already populated? _.set(outDoc, node.docPath, o.utilities.objectID(oidLeaf._id)); } else { // Convert to an OID _.set(outDoc, node.docPath, o.utilities.objectID(oidLeaf)); } } break; case 'objectIdArray': var oidLeaf = _.get(doc, node.schemaPath); _.set(outDoc, node.schemaPath, oidLeaf.map(function(leaf) { return o.utilities.isObjectID(leaf) ? leaf : o.utilities.objectID(leaf); })); break; default: return; // Ignore unsupported OID types } }); return outDoc; }
[ "function", "(", ")", "{", "var", "doc", "=", "this", ";", "var", "outDoc", "=", "doc", ".", "toObject", "(", ")", ";", "doc", ".", "getOIDs", "(", ")", ".", "forEach", "(", "function", "(", "node", ")", "{", "switch", "(", "node", ".", "fkType", ")", "{", "case", "'objectId'", ":", "var", "oidLeaf", "=", "_", ".", "get", "(", "doc", ",", "node", ".", "docPath", ")", ";", "if", "(", "_", ".", "isUndefined", "(", "oidLeaf", ")", ")", "return", ";", "if", "(", "!", "o", ".", "utilities", ".", "isObjectID", "(", "oidLeaf", ")", ")", "{", "if", "(", "_", ".", "has", "(", "oidLeaf", ",", "'_id'", ")", ")", "{", "_", ".", "set", "(", "outDoc", ",", "node", ".", "docPath", ",", "o", ".", "utilities", ".", "objectID", "(", "oidLeaf", ".", "_id", ")", ")", ";", "}", "else", "{", "_", ".", "set", "(", "outDoc", ",", "node", ".", "docPath", ",", "o", ".", "utilities", ".", "objectID", "(", "oidLeaf", ")", ")", ";", "}", "}", "break", ";", "case", "'objectIdArray'", ":", "var", "oidLeaf", "=", "_", ".", "get", "(", "doc", ",", "node", ".", "schemaPath", ")", ";", "_", ".", "set", "(", "outDoc", ",", "node", ".", "schemaPath", ",", "oidLeaf", ".", "map", "(", "function", "(", "leaf", ")", "{", "return", "o", ".", "utilities", ".", "isObjectID", "(", "leaf", ")", "?", "leaf", ":", "o", ".", "utilities", ".", "objectID", "(", "leaf", ")", ";", "}", ")", ")", ";", "break", ";", "default", ":", "return", ";", "}", "}", ")", ";", "return", "outDoc", ";", "}" ]
Transform a MonoxideDocument into a Mongo object This function transforms all OID strings back into their Mongo equivalent @return {Object} Plain JavaScript object with all special properties and other gunk removed
[ "Transform", "a", "MonoxideDocument", "into", "a", "Mongo", "object", "This", "function", "transforms", "all", "OID", "strings", "back", "into", "their", "Mongo", "equivalent" ]
76b1cf33c8e5b6e36801daa31bde9b422601c3a6
https://github.com/hash-bang/Monoxide/blob/76b1cf33c8e5b6e36801daa31bde9b422601c3a6/index.js#L2041-L2071
train
hash-bang/Monoxide
index.js
function() { var doc = this; var stack = []; _.forEach(model.$oids, function(fkType, schemaPath) { if (fkType.type == 'subDocument') return; // Skip sub-documents (as they are stored against the parent anyway) stack = stack.concat(doc.getNodesBySchemaPath(schemaPath) .map(function(node) { node.fkType = fkType.type; return node; }) ); }); return stack; }
javascript
function() { var doc = this; var stack = []; _.forEach(model.$oids, function(fkType, schemaPath) { if (fkType.type == 'subDocument') return; // Skip sub-documents (as they are stored against the parent anyway) stack = stack.concat(doc.getNodesBySchemaPath(schemaPath) .map(function(node) { node.fkType = fkType.type; return node; }) ); }); return stack; }
[ "function", "(", ")", "{", "var", "doc", "=", "this", ";", "var", "stack", "=", "[", "]", ";", "_", ".", "forEach", "(", "model", ".", "$oids", ",", "function", "(", "fkType", ",", "schemaPath", ")", "{", "if", "(", "fkType", ".", "type", "==", "'subDocument'", ")", "return", ";", "stack", "=", "stack", ".", "concat", "(", "doc", ".", "getNodesBySchemaPath", "(", "schemaPath", ")", ".", "map", "(", "function", "(", "node", ")", "{", "node", ".", "fkType", "=", "fkType", ".", "type", ";", "return", "node", ";", "}", ")", ")", ";", "}", ")", ";", "return", "stack", ";", "}" ]
Return an array of all OID leaf nodes within the document This function combines the behaviour of monoxide.utilities.extractFKs with monoxide.monoxideDocument.getNodesBySchemaPath) @return {array} An array of all leaf nodes
[ "Return", "an", "array", "of", "all", "OID", "leaf", "nodes", "within", "the", "document", "This", "function", "combines", "the", "behaviour", "of", "monoxide", ".", "utilities", ".", "extractFKs", "with", "monoxide", ".", "monoxideDocument", ".", "getNodesBySchemaPath", ")" ]
76b1cf33c8e5b6e36801daa31bde9b422601c3a6
https://github.com/hash-bang/Monoxide/blob/76b1cf33c8e5b6e36801daa31bde9b422601c3a6/index.js#L2275-L2290
train
MathiasPaumgarten/grunt-shared-config
tasks/shared-config.js
generateJS
function generateJS( data ) { var preparedData = prepareValues( data ); var content = JSON.stringify( preparedData, null, options.indention ); var output = outputPattern.js.replace( "{{name}}", options.name ).replace( "{{vars}}", content ); return options.singlequote ? output.replace( /"/g, "'" ) : output; }
javascript
function generateJS( data ) { var preparedData = prepareValues( data ); var content = JSON.stringify( preparedData, null, options.indention ); var output = outputPattern.js.replace( "{{name}}", options.name ).replace( "{{vars}}", content ); return options.singlequote ? output.replace( /"/g, "'" ) : output; }
[ "function", "generateJS", "(", "data", ")", "{", "var", "preparedData", "=", "prepareValues", "(", "data", ")", ";", "var", "content", "=", "JSON", ".", "stringify", "(", "preparedData", ",", "null", ",", "options", ".", "indention", ")", ";", "var", "output", "=", "outputPattern", ".", "js", ".", "replace", "(", "\"{{name}}\"", ",", "options", ".", "name", ")", ".", "replace", "(", "\"{{vars}}\"", ",", "content", ")", ";", "return", "options", ".", "singlequote", "?", "output", ".", "replace", "(", "/", "\"", "/", "g", ",", "\"'\"", ")", ":", "output", ";", "}" ]
Generate JavaScript files
[ "Generate", "JavaScript", "files" ]
ff5ab985bcecc138e3b4a1bf91da77785a65bc64
https://github.com/MathiasPaumgarten/grunt-shared-config/blob/ff5ab985bcecc138e3b4a1bf91da77785a65bc64/tasks/shared-config.js#L267-L273
train
ircanywhere/irc-factory
examples/persistent.js
createClient
function createClient() { rpc.emit('createClient', 'test', { nick : 'simpleircbot', user : 'testuser', server : 'localhost', realname: 'realbot', port: 6667, secure: false, retryCount: 2, retryWait: 3000 }); }
javascript
function createClient() { rpc.emit('createClient', 'test', { nick : 'simpleircbot', user : 'testuser', server : 'localhost', realname: 'realbot', port: 6667, secure: false, retryCount: 2, retryWait: 3000 }); }
[ "function", "createClient", "(", ")", "{", "rpc", ".", "emit", "(", "'createClient'", ",", "'test'", ",", "{", "nick", ":", "'simpleircbot'", ",", "user", ":", "'testuser'", ",", "server", ":", "'localhost'", ",", "realname", ":", "'realbot'", ",", "port", ":", "6667", ",", "secure", ":", "false", ",", "retryCount", ":", "2", ",", "retryWait", ":", "3000", "}", ")", ";", "}" ]
handle incoming events, we don't use an event emitter because of the fact we want queueing.
[ "handle", "incoming", "events", "we", "don", "t", "use", "an", "event", "emitter", "because", "of", "the", "fact", "we", "want", "queueing", "." ]
6a7f739bda7fe3a6c6201edce2fab64699c17167
https://github.com/ircanywhere/irc-factory/blob/6a7f739bda7fe3a6c6201edce2fab64699c17167/examples/persistent.js#L34-L45
train
tilgovi/simple-xpath-position
src/xpath.js
nodePosition
function nodePosition(node) { let name = node.nodeName let position = 1 while ((node = node.previousSibling)) { if (node.nodeName === name) position += 1 } return position }
javascript
function nodePosition(node) { let name = node.nodeName let position = 1 while ((node = node.previousSibling)) { if (node.nodeName === name) position += 1 } return position }
[ "function", "nodePosition", "(", "node", ")", "{", "let", "name", "=", "node", ".", "nodeName", "let", "position", "=", "1", "while", "(", "(", "node", "=", "node", ".", "previousSibling", ")", ")", "{", "if", "(", "node", ".", "nodeName", "===", "name", ")", "position", "+=", "1", "}", "return", "position", "}" ]
Get the ordinal position of this node among its siblings of the same name.
[ "Get", "the", "ordinal", "position", "of", "this", "node", "among", "its", "siblings", "of", "the", "same", "name", "." ]
6001d1d213d99da5c64782aa6a9fdfca11b7ef74
https://github.com/tilgovi/simple-xpath-position/blob/6001d1d213d99da5c64782aa6a9fdfca11b7ef74/src/xpath.js#L94-L101
train
tilgovi/simple-xpath-position
src/xpath.js
resolve
function resolve(path, root, resolver) { try { // Add a default value to each path part lacking a prefix. let nspath = path.replace(/\/(?!\.)([^\/:\(]+)(?=\/|$)/g, '/_default_:$1') return platformResolve(nspath, root, resolver) } catch (err) { return fallbackResolve(path, root) } }
javascript
function resolve(path, root, resolver) { try { // Add a default value to each path part lacking a prefix. let nspath = path.replace(/\/(?!\.)([^\/:\(]+)(?=\/|$)/g, '/_default_:$1') return platformResolve(nspath, root, resolver) } catch (err) { return fallbackResolve(path, root) } }
[ "function", "resolve", "(", "path", ",", "root", ",", "resolver", ")", "{", "try", "{", "let", "nspath", "=", "path", ".", "replace", "(", "/", "\\/(?!\\.)([^\\/:\\(]+)(?=\\/|$)", "/", "g", ",", "'/_default_:$1'", ")", "return", "platformResolve", "(", "nspath", ",", "root", ",", "resolver", ")", "}", "catch", "(", "err", ")", "{", "return", "fallbackResolve", "(", "path", ",", "root", ")", "}", "}" ]
Find a single node with XPath `path`
[ "Find", "a", "single", "node", "with", "XPath", "path" ]
6001d1d213d99da5c64782aa6a9fdfca11b7ef74
https://github.com/tilgovi/simple-xpath-position/blob/6001d1d213d99da5c64782aa6a9fdfca11b7ef74/src/xpath.js#L105-L113
train
tilgovi/simple-xpath-position
src/xpath.js
fallbackResolve
function fallbackResolve(path, root) { let steps = path.split("/") let node = root while (node) { let step = steps.shift() if (step === undefined) break if (step === '.') continue let [name, position] = step.split(/[\[\]]/) name = name.replace('_default_:', '') position = position ? parseInt(position) : 1 node = findChild(node, name, position) } return node }
javascript
function fallbackResolve(path, root) { let steps = path.split("/") let node = root while (node) { let step = steps.shift() if (step === undefined) break if (step === '.') continue let [name, position] = step.split(/[\[\]]/) name = name.replace('_default_:', '') position = position ? parseInt(position) : 1 node = findChild(node, name, position) } return node }
[ "function", "fallbackResolve", "(", "path", ",", "root", ")", "{", "let", "steps", "=", "path", ".", "split", "(", "\"/\"", ")", "let", "node", "=", "root", "while", "(", "node", ")", "{", "let", "step", "=", "steps", ".", "shift", "(", ")", "if", "(", "step", "===", "undefined", ")", "break", "if", "(", "step", "===", "'.'", ")", "continue", "let", "[", "name", ",", "position", "]", "=", "step", ".", "split", "(", "/", "[\\[\\]]", "/", ")", "name", "=", "name", ".", "replace", "(", "'_default_:'", ",", "''", ")", "position", "=", "position", "?", "parseInt", "(", "position", ")", ":", "1", "node", "=", "findChild", "(", "node", ",", "name", ",", "position", ")", "}", "return", "node", "}" ]
Find a single node with XPath `path` using the simple, built-in evaluator.
[ "Find", "a", "single", "node", "with", "XPath", "path", "using", "the", "simple", "built", "-", "in", "evaluator", "." ]
6001d1d213d99da5c64782aa6a9fdfca11b7ef74
https://github.com/tilgovi/simple-xpath-position/blob/6001d1d213d99da5c64782aa6a9fdfca11b7ef74/src/xpath.js#L117-L130
train
tilgovi/simple-xpath-position
src/xpath.js
platformResolve
function platformResolve(path, root, resolver) { let document = getDocument(root) let r = document.evaluate(path, root, resolver, FIRST_ORDERED_NODE_TYPE, null) return r.singleNodeValue }
javascript
function platformResolve(path, root, resolver) { let document = getDocument(root) let r = document.evaluate(path, root, resolver, FIRST_ORDERED_NODE_TYPE, null) return r.singleNodeValue }
[ "function", "platformResolve", "(", "path", ",", "root", ",", "resolver", ")", "{", "let", "document", "=", "getDocument", "(", "root", ")", "let", "r", "=", "document", ".", "evaluate", "(", "path", ",", "root", ",", "resolver", ",", "FIRST_ORDERED_NODE_TYPE", ",", "null", ")", "return", "r", ".", "singleNodeValue", "}" ]
Find a single node with XPath `path` using `document.evaluate`.
[ "Find", "a", "single", "node", "with", "XPath", "path", "using", "document", ".", "evaluate", "." ]
6001d1d213d99da5c64782aa6a9fdfca11b7ef74
https://github.com/tilgovi/simple-xpath-position/blob/6001d1d213d99da5c64782aa6a9fdfca11b7ef74/src/xpath.js#L134-L138
train
tilgovi/simple-xpath-position
src/xpath.js
findChild
function findChild(node, name, position) { for (node = node.firstChild ; node ; node = node.nextSibling) { if (nodeName(node) === name && --position === 0) break } return node }
javascript
function findChild(node, name, position) { for (node = node.firstChild ; node ; node = node.nextSibling) { if (nodeName(node) === name && --position === 0) break } return node }
[ "function", "findChild", "(", "node", ",", "name", ",", "position", ")", "{", "for", "(", "node", "=", "node", ".", "firstChild", ";", "node", ";", "node", "=", "node", ".", "nextSibling", ")", "{", "if", "(", "nodeName", "(", "node", ")", "===", "name", "&&", "--", "position", "===", "0", ")", "break", "}", "return", "node", "}" ]
Find the child of the given node by name and ordinal position.
[ "Find", "the", "child", "of", "the", "given", "node", "by", "name", "and", "ordinal", "position", "." ]
6001d1d213d99da5c64782aa6a9fdfca11b7ef74
https://github.com/tilgovi/simple-xpath-position/blob/6001d1d213d99da5c64782aa6a9fdfca11b7ef74/src/xpath.js#L142-L147
train
silas/hapi-bunyan
lib/index.js
logEvent
function logEvent(ctx, data, request) { if (!data) return; var obj = {}; var msg = ''; if (ctx.includeTags && Array.isArray(data.tags)) { obj.tags = ctx.joinTags ? data.tags.join(ctx.joinTags) : data.tags; } if (request) obj.req_id = request.id; if (data instanceof Error) { ctx.log.child(obj)[ctx.level](data); return; } var type = typeof data.data; if (type === 'string') { msg = data.data; } else if (ctx.includeData && data.data !== undefined) { if (ctx.mergeData && type === 'object' && !Array.isArray(data.data)) { lodash.assign(obj, data.data); if (obj.id === obj.req_id) delete obj.id; } else { obj.data = data.data; } } else if (ctx.skipUndefined) { return; } ctx.log[ctx.level](obj, msg); }
javascript
function logEvent(ctx, data, request) { if (!data) return; var obj = {}; var msg = ''; if (ctx.includeTags && Array.isArray(data.tags)) { obj.tags = ctx.joinTags ? data.tags.join(ctx.joinTags) : data.tags; } if (request) obj.req_id = request.id; if (data instanceof Error) { ctx.log.child(obj)[ctx.level](data); return; } var type = typeof data.data; if (type === 'string') { msg = data.data; } else if (ctx.includeData && data.data !== undefined) { if (ctx.mergeData && type === 'object' && !Array.isArray(data.data)) { lodash.assign(obj, data.data); if (obj.id === obj.req_id) delete obj.id; } else { obj.data = data.data; } } else if (ctx.skipUndefined) { return; } ctx.log[ctx.level](obj, msg); }
[ "function", "logEvent", "(", "ctx", ",", "data", ",", "request", ")", "{", "if", "(", "!", "data", ")", "return", ";", "var", "obj", "=", "{", "}", ";", "var", "msg", "=", "''", ";", "if", "(", "ctx", ".", "includeTags", "&&", "Array", ".", "isArray", "(", "data", ".", "tags", ")", ")", "{", "obj", ".", "tags", "=", "ctx", ".", "joinTags", "?", "data", ".", "tags", ".", "join", "(", "ctx", ".", "joinTags", ")", ":", "data", ".", "tags", ";", "}", "if", "(", "request", ")", "obj", ".", "req_id", "=", "request", ".", "id", ";", "if", "(", "data", "instanceof", "Error", ")", "{", "ctx", ".", "log", ".", "child", "(", "obj", ")", "[", "ctx", ".", "level", "]", "(", "data", ")", ";", "return", ";", "}", "var", "type", "=", "typeof", "data", ".", "data", ";", "if", "(", "type", "===", "'string'", ")", "{", "msg", "=", "data", ".", "data", ";", "}", "else", "if", "(", "ctx", ".", "includeData", "&&", "data", ".", "data", "!==", "undefined", ")", "{", "if", "(", "ctx", ".", "mergeData", "&&", "type", "===", "'object'", "&&", "!", "Array", ".", "isArray", "(", "data", ".", "data", ")", ")", "{", "lodash", ".", "assign", "(", "obj", ",", "data", ".", "data", ")", ";", "if", "(", "obj", ".", "id", "===", "obj", ".", "req_id", ")", "delete", "obj", ".", "id", ";", "}", "else", "{", "obj", ".", "data", "=", "data", ".", "data", ";", "}", "}", "else", "if", "(", "ctx", ".", "skipUndefined", ")", "{", "return", ";", "}", "ctx", ".", "log", "[", "ctx", ".", "level", "]", "(", "obj", ",", "msg", ")", ";", "}" ]
Event logger.
[ "Event", "logger", "." ]
6f49b9ca431522a8448930f0df28d726afccda37
https://github.com/silas/hapi-bunyan/blob/6f49b9ca431522a8448930f0df28d726afccda37/lib/index.js#L19-L53
train
JCloudYu/beson
serialize.esm.js
__serializeIntVar
function __serializeIntVar(data) { if ( data.size > 127 ) { throw new Error( "Cannot support IntVar whose size is greater than 127 bytes" ); } const size = new Uint8Array([data.size]); return [size.buffer, data.toBytes().buffer]; }
javascript
function __serializeIntVar(data) { if ( data.size > 127 ) { throw new Error( "Cannot support IntVar whose size is greater than 127 bytes" ); } const size = new Uint8Array([data.size]); return [size.buffer, data.toBytes().buffer]; }
[ "function", "__serializeIntVar", "(", "data", ")", "{", "if", "(", "data", ".", "size", ">", "127", ")", "{", "throw", "new", "Error", "(", "\"Cannot support IntVar whose size is greater than 127 bytes\"", ")", ";", "}", "const", "size", "=", "new", "Uint8Array", "(", "[", "data", ".", "size", "]", ")", ";", "return", "[", "size", ".", "buffer", ",", "data", ".", "toBytes", "(", ")", ".", "buffer", "]", ";", "}" ]
Serialize IntVar data @param {IntVar} data @returns {ArrayBuffer[]} @private
[ "Serialize", "IntVar", "data" ]
de9f1f6be59599feb1a5e70085b42b0382600d0b
https://github.com/JCloudYu/beson/blob/de9f1f6be59599feb1a5e70085b42b0382600d0b/serialize.esm.js#L381-L388
train
JCloudYu/beson
serialize.esm.js
__serializeUIntVar
function __serializeUIntVar(data) { if ( data.size > 127 ) { throw new Error( "Cannot support UIntVar whose size is greater than 127 bytes" ); } const size = new Uint8Array([data.size]); return [size.buffer, data.toBytes().buffer]; }
javascript
function __serializeUIntVar(data) { if ( data.size > 127 ) { throw new Error( "Cannot support UIntVar whose size is greater than 127 bytes" ); } const size = new Uint8Array([data.size]); return [size.buffer, data.toBytes().buffer]; }
[ "function", "__serializeUIntVar", "(", "data", ")", "{", "if", "(", "data", ".", "size", ">", "127", ")", "{", "throw", "new", "Error", "(", "\"Cannot support UIntVar whose size is greater than 127 bytes\"", ")", ";", "}", "const", "size", "=", "new", "Uint8Array", "(", "[", "data", ".", "size", "]", ")", ";", "return", "[", "size", ".", "buffer", ",", "data", ".", "toBytes", "(", ")", ".", "buffer", "]", ";", "}" ]
Serialize UIntVar data @param {UIntVar} data @returns {ArrayBuffer[]} @private
[ "Serialize", "UIntVar", "data" ]
de9f1f6be59599feb1a5e70085b42b0382600d0b
https://github.com/JCloudYu/beson/blob/de9f1f6be59599feb1a5e70085b42b0382600d0b/serialize.esm.js#L436-L443
train
JCloudYu/beson
serialize.esm.js
__serializeArray
function __serializeArray(data, options=DEFAULT_OPTIONS) { let dataBuffers = []; // ignore undefined value for (let key in data) { let subData = data[key]; let subType = __getType(subData, options); let subTypeBuffer = __serializeType(subType); let subDataBuffers = __serializeData(subType, subData, options); dataBuffers.push(subTypeBuffer, ...subDataBuffers); } let length = __getLengthByArrayBuffers(dataBuffers); let lengthData = new Uint32Array([length]); return [lengthData.buffer, ...dataBuffers]; }
javascript
function __serializeArray(data, options=DEFAULT_OPTIONS) { let dataBuffers = []; // ignore undefined value for (let key in data) { let subData = data[key]; let subType = __getType(subData, options); let subTypeBuffer = __serializeType(subType); let subDataBuffers = __serializeData(subType, subData, options); dataBuffers.push(subTypeBuffer, ...subDataBuffers); } let length = __getLengthByArrayBuffers(dataBuffers); let lengthData = new Uint32Array([length]); return [lengthData.buffer, ...dataBuffers]; }
[ "function", "__serializeArray", "(", "data", ",", "options", "=", "DEFAULT_OPTIONS", ")", "{", "let", "dataBuffers", "=", "[", "]", ";", "for", "(", "let", "key", "in", "data", ")", "{", "let", "subData", "=", "data", "[", "key", "]", ";", "let", "subType", "=", "__getType", "(", "subData", ",", "options", ")", ";", "let", "subTypeBuffer", "=", "__serializeType", "(", "subType", ")", ";", "let", "subDataBuffers", "=", "__serializeData", "(", "subType", ",", "subData", ",", "options", ")", ";", "dataBuffers", ".", "push", "(", "subTypeBuffer", ",", "...", "subDataBuffers", ")", ";", "}", "let", "length", "=", "__getLengthByArrayBuffers", "(", "dataBuffers", ")", ";", "let", "lengthData", "=", "new", "Uint32Array", "(", "[", "length", "]", ")", ";", "return", "[", "lengthData", ".", "buffer", ",", "...", "dataBuffers", "]", ";", "}" ]
Serialize array data @param {*[]} data @param {Object} options @param {boolean} options.sort_key @param {boolean} options.streaming_array @param {boolean} options.streaming_object @returns {ArrayBuffer[]} @private
[ "Serialize", "array", "data" ]
de9f1f6be59599feb1a5e70085b42b0382600d0b
https://github.com/JCloudYu/beson/blob/de9f1f6be59599feb1a5e70085b42b0382600d0b/serialize.esm.js#L492-L505
train
JCloudYu/beson
serialize.esm.js
__serializeObject
function __serializeObject(data, options=DEFAULT_OPTIONS) { let dataBuffers = []; let allKeys = (options.sort_key === true) ? Object.keys(data).sort() : Object.keys(data); // ignore undefined value for (let key of allKeys) { let subData = data[key]; if (subData === undefined) continue; let subType = __getType(subData, options); let subTypeBuffer = __serializeType(subType); let keyBuffers = __serializeShortString(key); let subDataBuffers = __serializeData(subType, subData, options); dataBuffers.push(subTypeBuffer, ...keyBuffers, ...subDataBuffers); } let length = __getLengthByArrayBuffers(dataBuffers); let lengthData = new Uint32Array([length]); return [lengthData.buffer, ...dataBuffers]; }
javascript
function __serializeObject(data, options=DEFAULT_OPTIONS) { let dataBuffers = []; let allKeys = (options.sort_key === true) ? Object.keys(data).sort() : Object.keys(data); // ignore undefined value for (let key of allKeys) { let subData = data[key]; if (subData === undefined) continue; let subType = __getType(subData, options); let subTypeBuffer = __serializeType(subType); let keyBuffers = __serializeShortString(key); let subDataBuffers = __serializeData(subType, subData, options); dataBuffers.push(subTypeBuffer, ...keyBuffers, ...subDataBuffers); } let length = __getLengthByArrayBuffers(dataBuffers); let lengthData = new Uint32Array([length]); return [lengthData.buffer, ...dataBuffers]; }
[ "function", "__serializeObject", "(", "data", ",", "options", "=", "DEFAULT_OPTIONS", ")", "{", "let", "dataBuffers", "=", "[", "]", ";", "let", "allKeys", "=", "(", "options", ".", "sort_key", "===", "true", ")", "?", "Object", ".", "keys", "(", "data", ")", ".", "sort", "(", ")", ":", "Object", ".", "keys", "(", "data", ")", ";", "for", "(", "let", "key", "of", "allKeys", ")", "{", "let", "subData", "=", "data", "[", "key", "]", ";", "if", "(", "subData", "===", "undefined", ")", "continue", ";", "let", "subType", "=", "__getType", "(", "subData", ",", "options", ")", ";", "let", "subTypeBuffer", "=", "__serializeType", "(", "subType", ")", ";", "let", "keyBuffers", "=", "__serializeShortString", "(", "key", ")", ";", "let", "subDataBuffers", "=", "__serializeData", "(", "subType", ",", "subData", ",", "options", ")", ";", "dataBuffers", ".", "push", "(", "subTypeBuffer", ",", "...", "keyBuffers", ",", "...", "subDataBuffers", ")", ";", "}", "let", "length", "=", "__getLengthByArrayBuffers", "(", "dataBuffers", ")", ";", "let", "lengthData", "=", "new", "Uint32Array", "(", "[", "length", "]", ")", ";", "return", "[", "lengthData", ".", "buffer", ",", "...", "dataBuffers", "]", ";", "}" ]
Serialize object data @param {Object} data @param {Object} options @param {boolean} options.sort_key @param {boolean} options.streaming_array @param {boolean} options.streaming_object @returns {ArrayBuffer[]} @private
[ "Serialize", "object", "data" ]
de9f1f6be59599feb1a5e70085b42b0382600d0b
https://github.com/JCloudYu/beson/blob/de9f1f6be59599feb1a5e70085b42b0382600d0b/serialize.esm.js#L540-L557
train
JCloudYu/beson
serialize.esm.js
__serializeArrayBuffer
function __serializeArrayBuffer(data) { let length = data.byteLength; let lengthData = new Uint32Array([length]); return [lengthData.buffer, data]; }
javascript
function __serializeArrayBuffer(data) { let length = data.byteLength; let lengthData = new Uint32Array([length]); return [lengthData.buffer, data]; }
[ "function", "__serializeArrayBuffer", "(", "data", ")", "{", "let", "length", "=", "data", ".", "byteLength", ";", "let", "lengthData", "=", "new", "Uint32Array", "(", "[", "length", "]", ")", ";", "return", "[", "lengthData", ".", "buffer", ",", "data", "]", ";", "}" ]
Serialize ArrayBuffer Object @param {ArrayBuffer} data @returns {ArrayBuffer[]} @private
[ "Serialize", "ArrayBuffer", "Object" ]
de9f1f6be59599feb1a5e70085b42b0382600d0b
https://github.com/JCloudYu/beson/blob/de9f1f6be59599feb1a5e70085b42b0382600d0b/serialize.esm.js#L613-L617
train
maxkfranz/weaver
documentation/js/Markdown.Editor.js
function (newMode, noSave) { if (mode != newMode) { mode = newMode; if (!noSave) { saveState(); } } if (!uaSniffed.isIE || mode != "moving") { timer = setTimeout(refreshState, 1); } else { inputStateObj = null; } }
javascript
function (newMode, noSave) { if (mode != newMode) { mode = newMode; if (!noSave) { saveState(); } } if (!uaSniffed.isIE || mode != "moving") { timer = setTimeout(refreshState, 1); } else { inputStateObj = null; } }
[ "function", "(", "newMode", ",", "noSave", ")", "{", "if", "(", "mode", "!=", "newMode", ")", "{", "mode", "=", "newMode", ";", "if", "(", "!", "noSave", ")", "{", "saveState", "(", ")", ";", "}", "}", "if", "(", "!", "uaSniffed", ".", "isIE", "||", "mode", "!=", "\"moving\"", ")", "{", "timer", "=", "setTimeout", "(", "refreshState", ",", "1", ")", ";", "}", "else", "{", "inputStateObj", "=", "null", ";", "}", "}" ]
Set the mode for later logic steps.
[ "Set", "the", "mode", "for", "later", "logic", "steps", "." ]
bac2535114420379005acdfe2dad06331de88496
https://github.com/maxkfranz/weaver/blob/bac2535114420379005acdfe2dad06331de88496/documentation/js/Markdown.Editor.js#L411-L425
train
maxkfranz/weaver
documentation/js/Markdown.Editor.js
function () { var currState = inputStateObj || new TextareaState(panels); if (!currState) { return false; } if (mode == "moving") { if (!lastState) { lastState = currState; } return; } if (lastState) { if (undoStack[stackPtr - 1].text != lastState.text) { undoStack[stackPtr++] = lastState; } lastState = null; } undoStack[stackPtr++] = currState; undoStack[stackPtr + 1] = null; if (callback) { callback(); } }
javascript
function () { var currState = inputStateObj || new TextareaState(panels); if (!currState) { return false; } if (mode == "moving") { if (!lastState) { lastState = currState; } return; } if (lastState) { if (undoStack[stackPtr - 1].text != lastState.text) { undoStack[stackPtr++] = lastState; } lastState = null; } undoStack[stackPtr++] = currState; undoStack[stackPtr + 1] = null; if (callback) { callback(); } }
[ "function", "(", ")", "{", "var", "currState", "=", "inputStateObj", "||", "new", "TextareaState", "(", "panels", ")", ";", "if", "(", "!", "currState", ")", "{", "return", "false", ";", "}", "if", "(", "mode", "==", "\"moving\"", ")", "{", "if", "(", "!", "lastState", ")", "{", "lastState", "=", "currState", ";", "}", "return", ";", "}", "if", "(", "lastState", ")", "{", "if", "(", "undoStack", "[", "stackPtr", "-", "1", "]", ".", "text", "!=", "lastState", ".", "text", ")", "{", "undoStack", "[", "stackPtr", "++", "]", "=", "lastState", ";", "}", "lastState", "=", "null", ";", "}", "undoStack", "[", "stackPtr", "++", "]", "=", "currState", ";", "undoStack", "[", "stackPtr", "+", "1", "]", "=", "null", ";", "if", "(", "callback", ")", "{", "callback", "(", ")", ";", "}", "}" ]
Push the input area state to the stack.
[ "Push", "the", "input", "area", "state", "to", "the", "stack", "." ]
bac2535114420379005acdfe2dad06331de88496
https://github.com/maxkfranz/weaver/blob/bac2535114420379005acdfe2dad06331de88496/documentation/js/Markdown.Editor.js#L491-L514
train
maxkfranz/weaver
documentation/js/Markdown.Editor.js
function (event) { if (!event.ctrlKey && !event.metaKey) { var keyCode = event.keyCode; if ((keyCode >= 33 && keyCode <= 40) || (keyCode >= 63232 && keyCode <= 63235)) { // 33 - 40: page up/dn and arrow keys // 63232 - 63235: page up/dn and arrow keys on safari setMode("moving"); } else if (keyCode == 8 || keyCode == 46 || keyCode == 127) { // 8: backspace // 46: delete // 127: delete setMode("deleting"); } else if (keyCode == 13) { // 13: Enter setMode("newlines"); } else if (keyCode == 27) { // 27: escape setMode("escape"); } else if ((keyCode < 16 || keyCode > 20) && keyCode != 91) { // 16-20 are shift, etc. // 91: left window key // I think this might be a little messed up since there are // a lot of nonprinting keys above 20. setMode("typing"); } } }
javascript
function (event) { if (!event.ctrlKey && !event.metaKey) { var keyCode = event.keyCode; if ((keyCode >= 33 && keyCode <= 40) || (keyCode >= 63232 && keyCode <= 63235)) { // 33 - 40: page up/dn and arrow keys // 63232 - 63235: page up/dn and arrow keys on safari setMode("moving"); } else if (keyCode == 8 || keyCode == 46 || keyCode == 127) { // 8: backspace // 46: delete // 127: delete setMode("deleting"); } else if (keyCode == 13) { // 13: Enter setMode("newlines"); } else if (keyCode == 27) { // 27: escape setMode("escape"); } else if ((keyCode < 16 || keyCode > 20) && keyCode != 91) { // 16-20 are shift, etc. // 91: left window key // I think this might be a little messed up since there are // a lot of nonprinting keys above 20. setMode("typing"); } } }
[ "function", "(", "event", ")", "{", "if", "(", "!", "event", ".", "ctrlKey", "&&", "!", "event", ".", "metaKey", ")", "{", "var", "keyCode", "=", "event", ".", "keyCode", ";", "if", "(", "(", "keyCode", ">=", "33", "&&", "keyCode", "<=", "40", ")", "||", "(", "keyCode", ">=", "63232", "&&", "keyCode", "<=", "63235", ")", ")", "{", "setMode", "(", "\"moving\"", ")", ";", "}", "else", "if", "(", "keyCode", "==", "8", "||", "keyCode", "==", "46", "||", "keyCode", "==", "127", ")", "{", "setMode", "(", "\"deleting\"", ")", ";", "}", "else", "if", "(", "keyCode", "==", "13", ")", "{", "setMode", "(", "\"newlines\"", ")", ";", "}", "else", "if", "(", "keyCode", "==", "27", ")", "{", "setMode", "(", "\"escape\"", ")", ";", "}", "else", "if", "(", "(", "keyCode", "<", "16", "||", "keyCode", ">", "20", ")", "&&", "keyCode", "!=", "91", ")", "{", "setMode", "(", "\"typing\"", ")", ";", "}", "}", "}" ]
Set the mode depending on what is going on in the input area.
[ "Set", "the", "mode", "depending", "on", "what", "is", "going", "on", "in", "the", "input", "area", "." ]
bac2535114420379005acdfe2dad06331de88496
https://github.com/maxkfranz/weaver/blob/bac2535114420379005acdfe2dad06331de88496/documentation/js/Markdown.Editor.js#L557-L590
train
maxkfranz/weaver
documentation/js/Markdown.Editor.js
function (inputElem, listener) { util.addEvent(inputElem, "input", listener); inputElem.onpaste = listener; inputElem.ondrop = listener; util.addEvent(inputElem, "keypress", listener); util.addEvent(inputElem, "keydown", listener); }
javascript
function (inputElem, listener) { util.addEvent(inputElem, "input", listener); inputElem.onpaste = listener; inputElem.ondrop = listener; util.addEvent(inputElem, "keypress", listener); util.addEvent(inputElem, "keydown", listener); }
[ "function", "(", "inputElem", ",", "listener", ")", "{", "util", ".", "addEvent", "(", "inputElem", ",", "\"input\"", ",", "listener", ")", ";", "inputElem", ".", "onpaste", "=", "listener", ";", "inputElem", ".", "ondrop", "=", "listener", ";", "util", ".", "addEvent", "(", "inputElem", ",", "\"keypress\"", ",", "listener", ")", ";", "util", ".", "addEvent", "(", "inputElem", ",", "\"keydown\"", ",", "listener", ")", ";", "}" ]
The other legal value is "manual" Adds event listeners to elements
[ "The", "other", "legal", "value", "is", "manual", "Adds", "event", "listeners", "to", "elements" ]
bac2535114420379005acdfe2dad06331de88496
https://github.com/maxkfranz/weaver/blob/bac2535114420379005acdfe2dad06331de88496/documentation/js/Markdown.Editor.js#L782-L790
train
maxkfranz/weaver
documentation/js/Markdown.Editor.js
function () { if (timeout) { clearTimeout(timeout); timeout = undefined; } if (startType !== "manual") { var delay = 0; if (startType === "delayed") { delay = elapsedTime; } if (delay > maxDelay) { delay = maxDelay; } timeout = setTimeout(makePreviewHtml, delay); } }
javascript
function () { if (timeout) { clearTimeout(timeout); timeout = undefined; } if (startType !== "manual") { var delay = 0; if (startType === "delayed") { delay = elapsedTime; } if (delay > maxDelay) { delay = maxDelay; } timeout = setTimeout(makePreviewHtml, delay); } }
[ "function", "(", ")", "{", "if", "(", "timeout", ")", "{", "clearTimeout", "(", "timeout", ")", ";", "timeout", "=", "undefined", ";", "}", "if", "(", "startType", "!==", "\"manual\"", ")", "{", "var", "delay", "=", "0", ";", "if", "(", "startType", "===", "\"delayed\"", ")", "{", "delay", "=", "elapsedTime", ";", "}", "if", "(", "delay", ">", "maxDelay", ")", "{", "delay", "=", "maxDelay", ";", "}", "timeout", "=", "setTimeout", "(", "makePreviewHtml", ",", "delay", ")", ";", "}", "}" ]
setTimeout is already used. Used as an event listener.
[ "setTimeout", "is", "already", "used", ".", "Used", "as", "an", "event", "listener", "." ]
bac2535114420379005acdfe2dad06331de88496
https://github.com/maxkfranz/weaver/blob/bac2535114420379005acdfe2dad06331de88496/documentation/js/Markdown.Editor.js#L840-L860
train
maxkfranz/weaver
documentation/js/Markdown.Editor.js
function (isCancel) { util.removeEvent(doc.body, "keydown", checkEscape); var text = input.value; if (isCancel) { text = null; } else { // Fixes common pasting errors. text = text.replace(/^http:\/\/(https?|ftp):\/\//, '$1://'); if (!/^(?:https?|ftp):\/\//.test(text)) text = 'http://' + text; } dialog.parentNode.removeChild(dialog); callback(text); return false; }
javascript
function (isCancel) { util.removeEvent(doc.body, "keydown", checkEscape); var text = input.value; if (isCancel) { text = null; } else { // Fixes common pasting errors. text = text.replace(/^http:\/\/(https?|ftp):\/\//, '$1://'); if (!/^(?:https?|ftp):\/\//.test(text)) text = 'http://' + text; } dialog.parentNode.removeChild(dialog); callback(text); return false; }
[ "function", "(", "isCancel", ")", "{", "util", ".", "removeEvent", "(", "doc", ".", "body", ",", "\"keydown\"", ",", "checkEscape", ")", ";", "var", "text", "=", "input", ".", "value", ";", "if", "(", "isCancel", ")", "{", "text", "=", "null", ";", "}", "else", "{", "text", "=", "text", ".", "replace", "(", "/", "^http:\\/\\/(https?|ftp):\\/\\/", "/", ",", "'$1://'", ")", ";", "if", "(", "!", "/", "^(?:https?|ftp):\\/\\/", "/", ".", "test", "(", "text", ")", ")", "text", "=", "'http://'", "+", "text", ";", "}", "dialog", ".", "parentNode", ".", "removeChild", "(", "dialog", ")", ";", "callback", "(", "text", ")", ";", "return", "false", ";", "}" ]
Dismisses the hyperlink input box. isCancel is true if we don't care about the input text. isCancel is false if we are going to keep the text.
[ "Dismisses", "the", "hyperlink", "input", "box", ".", "isCancel", "is", "true", "if", "we", "don", "t", "care", "about", "the", "input", "text", ".", "isCancel", "is", "false", "if", "we", "are", "going", "to", "keep", "the", "text", "." ]
bac2535114420379005acdfe2dad06331de88496
https://github.com/maxkfranz/weaver/blob/bac2535114420379005acdfe2dad06331de88496/documentation/js/Markdown.Editor.js#L1038-L1056
train
lechu1985/basic-mouse-event-polyfill-phantomjs
index.js
function (eventType, params) { params = params || { bubbles: false, cancelable: false, ctrlKey: false, altKey: false, shiftKey: false, metaKey: false }; var mouseEvent = document.createEvent('MouseEvent'); mouseEvent.initMouseEvent(eventType, params.bubbles, params.cancelable, window, 0, 0, 0, 0, 0, params.ctrlKey, params.altKey, params.shiftKey, params.metaKey, 0, null); return mouseEvent; }
javascript
function (eventType, params) { params = params || { bubbles: false, cancelable: false, ctrlKey: false, altKey: false, shiftKey: false, metaKey: false }; var mouseEvent = document.createEvent('MouseEvent'); mouseEvent.initMouseEvent(eventType, params.bubbles, params.cancelable, window, 0, 0, 0, 0, 0, params.ctrlKey, params.altKey, params.shiftKey, params.metaKey, 0, null); return mouseEvent; }
[ "function", "(", "eventType", ",", "params", ")", "{", "params", "=", "params", "||", "{", "bubbles", ":", "false", ",", "cancelable", ":", "false", ",", "ctrlKey", ":", "false", ",", "altKey", ":", "false", ",", "shiftKey", ":", "false", ",", "metaKey", ":", "false", "}", ";", "var", "mouseEvent", "=", "document", ".", "createEvent", "(", "'MouseEvent'", ")", ";", "mouseEvent", ".", "initMouseEvent", "(", "eventType", ",", "params", ".", "bubbles", ",", "params", ".", "cancelable", ",", "window", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "params", ".", "ctrlKey", ",", "params", ".", "altKey", ",", "params", ".", "shiftKey", ",", "params", ".", "metaKey", ",", "0", ",", "null", ")", ";", "return", "mouseEvent", ";", "}" ]
Polyfills DOM4 MouseEvent
[ "Polyfills", "DOM4", "MouseEvent" ]
235ff99c81fc8950803eebb87ba15a2b8ceaa571
https://github.com/lechu1985/basic-mouse-event-polyfill-phantomjs/blob/235ff99c81fc8950803eebb87ba15a2b8ceaa571/index.js#L11-L24
train
eGavr/toc-md
lib/index.js
function (source, opts, cb) { var callback, options; if (arguments.length === 2) { options = defaults(); callback = opts; } else { options = defaults(opts); callback = cb; } try { source = api.clean(source); callback(null, api.insert(source, getToc(source, options))); } catch (err) { callback(err, null); } }
javascript
function (source, opts, cb) { var callback, options; if (arguments.length === 2) { options = defaults(); callback = opts; } else { options = defaults(opts); callback = cb; } try { source = api.clean(source); callback(null, api.insert(source, getToc(source, options))); } catch (err) { callback(err, null); } }
[ "function", "(", "source", ",", "opts", ",", "cb", ")", "{", "var", "callback", ",", "options", ";", "if", "(", "arguments", ".", "length", "===", "2", ")", "{", "options", "=", "defaults", "(", ")", ";", "callback", "=", "opts", ";", "}", "else", "{", "options", "=", "defaults", "(", "opts", ")", ";", "callback", "=", "cb", ";", "}", "try", "{", "source", "=", "api", ".", "clean", "(", "source", ")", ";", "callback", "(", "null", ",", "api", ".", "insert", "(", "source", ",", "getToc", "(", "source", ",", "options", ")", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "callback", "(", "err", ",", "null", ")", ";", "}", "}" ]
Inserts a TOC object into a source @param {String} source @param {Object} [opts] @param {Number} [opts.maxDepth] @param {Char} [opts.bullet] @param {Function} cb
[ "Inserts", "a", "TOC", "object", "into", "a", "source" ]
debdf98d7c1035eeec2a25350c5ab2263c2cd89e
https://github.com/eGavr/toc-md/blob/debdf98d7c1035eeec2a25350c5ab2263c2cd89e/lib/index.js#L14-L32
train
jeremyworboys/node-kit
lib/node-kit.js
Kit
function Kit(str, variables, forbiddenPaths) { this._variables = variables || {}; this._forbiddenPaths = forbiddenPaths || []; // Import file if (fs.existsSync(str)) { this.fileContents = fs.readFileSync(str).toString(); this.filename = path.basename(str); this._fileDir = path.dirname(str); if (this._forbiddenPaths.indexOf(str) !== -1) { throw new Error('Error: infinite import loop detected. (e.g. File A imports File B, which imports File A.) You must fix this before the file can be compiled.'); } this._forbiddenPaths.push(str); } // Anonymous string else { this.fileContents = str.toString(); this.filename = '<anonymous>'; this._fileDir = ''; } }
javascript
function Kit(str, variables, forbiddenPaths) { this._variables = variables || {}; this._forbiddenPaths = forbiddenPaths || []; // Import file if (fs.existsSync(str)) { this.fileContents = fs.readFileSync(str).toString(); this.filename = path.basename(str); this._fileDir = path.dirname(str); if (this._forbiddenPaths.indexOf(str) !== -1) { throw new Error('Error: infinite import loop detected. (e.g. File A imports File B, which imports File A.) You must fix this before the file can be compiled.'); } this._forbiddenPaths.push(str); } // Anonymous string else { this.fileContents = str.toString(); this.filename = '<anonymous>'; this._fileDir = ''; } }
[ "function", "Kit", "(", "str", ",", "variables", ",", "forbiddenPaths", ")", "{", "this", ".", "_variables", "=", "variables", "||", "{", "}", ";", "this", ".", "_forbiddenPaths", "=", "forbiddenPaths", "||", "[", "]", ";", "if", "(", "fs", ".", "existsSync", "(", "str", ")", ")", "{", "this", ".", "fileContents", "=", "fs", ".", "readFileSync", "(", "str", ")", ".", "toString", "(", ")", ";", "this", ".", "filename", "=", "path", ".", "basename", "(", "str", ")", ";", "this", ".", "_fileDir", "=", "path", ".", "dirname", "(", "str", ")", ";", "if", "(", "this", ".", "_forbiddenPaths", ".", "indexOf", "(", "str", ")", "!==", "-", "1", ")", "{", "throw", "new", "Error", "(", "'Error: infinite import loop detected. (e.g. File A imports File B, which imports File A.) You must fix this before the file can be compiled.'", ")", ";", "}", "this", ".", "_forbiddenPaths", ".", "push", "(", "str", ")", ";", "}", "else", "{", "this", ".", "fileContents", "=", "str", ".", "toString", "(", ")", ";", "this", ".", "filename", "=", "'<anonymous>'", ";", "this", ".", "_fileDir", "=", "''", ";", "}", "}" ]
Create a new Kit object @param {string} str @param {Object} variables @param {Array<string>} forbiddenPaths
[ "Create", "a", "new", "Kit", "object" ]
3b26db2aedb218bade1fd32a51f604d8215657f1
https://github.com/jeremyworboys/node-kit/blob/3b26db2aedb218bade1fd32a51f604d8215657f1/lib/node-kit.js#L28-L50
train
maxkfranz/weaver
documentation/js/Markdown.Converter.js
encodeProblemUrlChars
function encodeProblemUrlChars(url) { if (!url) return ""; var len = url.length; return url.replace(_problemUrlChars, function (match, offset) { if (match == "~D") // escape for dollar return "%24"; if (match == ":") { if (offset == len - 1 || /[0-9\/]/.test(url.charAt(offset + 1))) return ":" } return "%" + match.charCodeAt(0).toString(16); }); }
javascript
function encodeProblemUrlChars(url) { if (!url) return ""; var len = url.length; return url.replace(_problemUrlChars, function (match, offset) { if (match == "~D") // escape for dollar return "%24"; if (match == ":") { if (offset == len - 1 || /[0-9\/]/.test(url.charAt(offset + 1))) return ":" } return "%" + match.charCodeAt(0).toString(16); }); }
[ "function", "encodeProblemUrlChars", "(", "url", ")", "{", "if", "(", "!", "url", ")", "return", "\"\"", ";", "var", "len", "=", "url", ".", "length", ";", "return", "url", ".", "replace", "(", "_problemUrlChars", ",", "function", "(", "match", ",", "offset", ")", "{", "if", "(", "match", "==", "\"~D\"", ")", "return", "\"%24\"", ";", "if", "(", "match", "==", "\":\"", ")", "{", "if", "(", "offset", "==", "len", "-", "1", "||", "/", "[0-9\\/]", "/", ".", "test", "(", "url", ".", "charAt", "(", "offset", "+", "1", ")", ")", ")", "return", "\":\"", "}", "return", "\"%\"", "+", "match", ".", "charCodeAt", "(", "0", ")", ".", "toString", "(", "16", ")", ";", "}", ")", ";", "}" ]
hex-encodes some unusual "problem" chars in URLs to avoid URL detection problems
[ "hex", "-", "encodes", "some", "unusual", "problem", "chars", "in", "URLs", "to", "avoid", "URL", "detection", "problems" ]
bac2535114420379005acdfe2dad06331de88496
https://github.com/maxkfranz/weaver/blob/bac2535114420379005acdfe2dad06331de88496/documentation/js/Markdown.Converter.js#L1291-L1306
train
fortunejs/fortune-indexeddb
lib/index.js
reducer
function reducer (type, records) { return reduce(records, function (hash, record) { record = outputRecord.call(self, type, msgpack.decode(record)) hash[record[primaryKey]] = record return hash }, {}) }
javascript
function reducer (type, records) { return reduce(records, function (hash, record) { record = outputRecord.call(self, type, msgpack.decode(record)) hash[record[primaryKey]] = record return hash }, {}) }
[ "function", "reducer", "(", "type", ",", "records", ")", "{", "return", "reduce", "(", "records", ",", "function", "(", "hash", ",", "record", ")", "{", "record", "=", "outputRecord", ".", "call", "(", "self", ",", "type", ",", "msgpack", ".", "decode", "(", "record", ")", ")", "hash", "[", "record", "[", "primaryKey", "]", "]", "=", "record", "return", "hash", "}", ",", "{", "}", ")", "}" ]
Populating memory database with results from IndexedDB.
[ "Populating", "memory", "database", "with", "results", "from", "IndexedDB", "." ]
d3409a86e6eea88d0fca22b4d4674b1120ad74d9
https://github.com/fortunejs/fortune-indexeddb/blob/d3409a86e6eea88d0fca22b4d4674b1120ad74d9/lib/index.js#L126-L132
train
tobilg/marathon-event-bus-client
examples/example.js
function (name, data) { console.log("Custom handler for " + name); // Send information of the "deployment_info" event to an external service (here: Just an echo service) request("https://echo.getpostman.com/get?name=" + name + "&startTime=" + data.timestamp, function (error, response, body) { body = JSON.parse(body); if (!error && response.statusCode == 200) { console.log("Here's the data we have just sent to the echo service:"); console.log("--------------------"); console.log(JSON.stringify(body.args)); // Show the sent data console.log("--------------------"); } }); }
javascript
function (name, data) { console.log("Custom handler for " + name); // Send information of the "deployment_info" event to an external service (here: Just an echo service) request("https://echo.getpostman.com/get?name=" + name + "&startTime=" + data.timestamp, function (error, response, body) { body = JSON.parse(body); if (!error && response.statusCode == 200) { console.log("Here's the data we have just sent to the echo service:"); console.log("--------------------"); console.log(JSON.stringify(body.args)); // Show the sent data console.log("--------------------"); } }); }
[ "function", "(", "name", ",", "data", ")", "{", "console", ".", "log", "(", "\"Custom handler for \"", "+", "name", ")", ";", "request", "(", "\"https://echo.getpostman.com/get?name=\"", "+", "name", "+", "\"&startTime=\"", "+", "data", ".", "timestamp", ",", "function", "(", "error", ",", "response", ",", "body", ")", "{", "body", "=", "JSON", ".", "parse", "(", "body", ")", ";", "if", "(", "!", "error", "&&", "response", ".", "statusCode", "==", "200", ")", "{", "console", ".", "log", "(", "\"Here's the data we have just sent to the echo service:\"", ")", ";", "console", ".", "log", "(", "\"--------------------\"", ")", ";", "console", ".", "log", "(", "JSON", ".", "stringify", "(", "body", ".", "args", ")", ")", ";", "console", ".", "log", "(", "\"--------------------\"", ")", ";", "}", "}", ")", ";", "}" ]
Specify the custom event handlers
[ "Specify", "the", "custom", "event", "handlers" ]
fc9b6851815d365ad2ab140cc47b328571ee9396
https://github.com/tobilg/marathon-event-bus-client/blob/fc9b6851815d365ad2ab140cc47b328571ee9396/examples/example.js#L26-L38
train
chip-js/fragments-js
src/compile.js
compile
function compile(fragments, template) { var walker = document.createTreeWalker(template, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT); var bindings = [], currentNode, parentNode, previousNode; // Reset first node to ensure it isn't a fragment walker.nextNode(); walker.previousNode(); // find bindings for each node do { currentNode = walker.currentNode; parentNode = currentNode.parentNode; bindings.push.apply(bindings, getBindingsForNode(fragments, currentNode, template)); if (currentNode.parentNode !== parentNode) { // currentNode was removed and made a template walker.currentNode = previousNode || walker.root; } else { previousNode = currentNode; } } while (walker.nextNode()); return bindings; }
javascript
function compile(fragments, template) { var walker = document.createTreeWalker(template, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT); var bindings = [], currentNode, parentNode, previousNode; // Reset first node to ensure it isn't a fragment walker.nextNode(); walker.previousNode(); // find bindings for each node do { currentNode = walker.currentNode; parentNode = currentNode.parentNode; bindings.push.apply(bindings, getBindingsForNode(fragments, currentNode, template)); if (currentNode.parentNode !== parentNode) { // currentNode was removed and made a template walker.currentNode = previousNode || walker.root; } else { previousNode = currentNode; } } while (walker.nextNode()); return bindings; }
[ "function", "compile", "(", "fragments", ",", "template", ")", "{", "var", "walker", "=", "document", ".", "createTreeWalker", "(", "template", ",", "NodeFilter", ".", "SHOW_ELEMENT", "|", "NodeFilter", ".", "SHOW_TEXT", ")", ";", "var", "bindings", "=", "[", "]", ",", "currentNode", ",", "parentNode", ",", "previousNode", ";", "walker", ".", "nextNode", "(", ")", ";", "walker", ".", "previousNode", "(", ")", ";", "do", "{", "currentNode", "=", "walker", ".", "currentNode", ";", "parentNode", "=", "currentNode", ".", "parentNode", ";", "bindings", ".", "push", ".", "apply", "(", "bindings", ",", "getBindingsForNode", "(", "fragments", ",", "currentNode", ",", "template", ")", ")", ";", "if", "(", "currentNode", ".", "parentNode", "!==", "parentNode", ")", "{", "walker", ".", "currentNode", "=", "previousNode", "||", "walker", ".", "root", ";", "}", "else", "{", "previousNode", "=", "currentNode", ";", "}", "}", "while", "(", "walker", ".", "nextNode", "(", ")", ")", ";", "return", "bindings", ";", "}" ]
Walks the template DOM replacing any bindings and caching bindings onto the template object.
[ "Walks", "the", "template", "DOM", "replacing", "any", "bindings", "and", "caching", "bindings", "onto", "the", "template", "object", "." ]
5d613ea42c3823423efb01fce4ffef80c7f5ce0f
https://github.com/chip-js/fragments-js/blob/5d613ea42c3823423efb01fce4ffef80c7f5ce0f/src/compile.js#L6-L29
train
chip-js/fragments-js
src/compile.js
splitTextNode
function splitTextNode(fragments, node) { if (!node.processed) { node.processed = true; var regex = fragments.binders.text._expr; var content = node.nodeValue; if (content.match(regex)) { var match, lastIndex = 0, parts = [], fragment = document.createDocumentFragment(); while ((match = regex.exec(content))) { parts.push(content.slice(lastIndex, regex.lastIndex - match[0].length)); parts.push(match[0]); lastIndex = regex.lastIndex; } parts.push(content.slice(lastIndex)); parts = parts.filter(notEmpty); node.nodeValue = parts[0]; for (var i = 1; i < parts.length; i++) { var newTextNode = document.createTextNode(parts[i]); newTextNode.processed = true; fragment.appendChild(newTextNode); } node.parentNode.insertBefore(fragment, node.nextSibling); } } }
javascript
function splitTextNode(fragments, node) { if (!node.processed) { node.processed = true; var regex = fragments.binders.text._expr; var content = node.nodeValue; if (content.match(regex)) { var match, lastIndex = 0, parts = [], fragment = document.createDocumentFragment(); while ((match = regex.exec(content))) { parts.push(content.slice(lastIndex, regex.lastIndex - match[0].length)); parts.push(match[0]); lastIndex = regex.lastIndex; } parts.push(content.slice(lastIndex)); parts = parts.filter(notEmpty); node.nodeValue = parts[0]; for (var i = 1; i < parts.length; i++) { var newTextNode = document.createTextNode(parts[i]); newTextNode.processed = true; fragment.appendChild(newTextNode); } node.parentNode.insertBefore(fragment, node.nextSibling); } } }
[ "function", "splitTextNode", "(", "fragments", ",", "node", ")", "{", "if", "(", "!", "node", ".", "processed", ")", "{", "node", ".", "processed", "=", "true", ";", "var", "regex", "=", "fragments", ".", "binders", ".", "text", ".", "_expr", ";", "var", "content", "=", "node", ".", "nodeValue", ";", "if", "(", "content", ".", "match", "(", "regex", ")", ")", "{", "var", "match", ",", "lastIndex", "=", "0", ",", "parts", "=", "[", "]", ",", "fragment", "=", "document", ".", "createDocumentFragment", "(", ")", ";", "while", "(", "(", "match", "=", "regex", ".", "exec", "(", "content", ")", ")", ")", "{", "parts", ".", "push", "(", "content", ".", "slice", "(", "lastIndex", ",", "regex", ".", "lastIndex", "-", "match", "[", "0", "]", ".", "length", ")", ")", ";", "parts", ".", "push", "(", "match", "[", "0", "]", ")", ";", "lastIndex", "=", "regex", ".", "lastIndex", ";", "}", "parts", ".", "push", "(", "content", ".", "slice", "(", "lastIndex", ")", ")", ";", "parts", "=", "parts", ".", "filter", "(", "notEmpty", ")", ";", "node", ".", "nodeValue", "=", "parts", "[", "0", "]", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "parts", ".", "length", ";", "i", "++", ")", "{", "var", "newTextNode", "=", "document", ".", "createTextNode", "(", "parts", "[", "i", "]", ")", ";", "newTextNode", ".", "processed", "=", "true", ";", "fragment", ".", "appendChild", "(", "newTextNode", ")", ";", "}", "node", ".", "parentNode", ".", "insertBefore", "(", "fragment", ",", "node", ".", "nextSibling", ")", ";", "}", "}", "}" ]
Splits text nodes with expressions in them so they can be bound individually, has parentNode passed in since it may be a document fragment which appears as null on node.parentNode.
[ "Splits", "text", "nodes", "with", "expressions", "in", "them", "so", "they", "can", "be", "bound", "individually", "has", "parentNode", "passed", "in", "since", "it", "may", "be", "a", "document", "fragment", "which", "appears", "as", "null", "on", "node", ".", "parentNode", "." ]
5d613ea42c3823423efb01fce4ffef80c7f5ce0f
https://github.com/chip-js/fragments-js/blob/5d613ea42c3823423efb01fce4ffef80c7f5ce0f/src/compile.js#L137-L161
train
utopiaio/Ethiopic-Calendar
index.js
ethCopticToJDN
function ethCopticToJDN(year, month, day, era) { return (era + 365) + 365 * (year - 1) + Math.floor(year / 4) + 30 * month + day - 31; }
javascript
function ethCopticToJDN(year, month, day, era) { return (era + 365) + 365 * (year - 1) + Math.floor(year / 4) + 30 * month + day - 31; }
[ "function", "ethCopticToJDN", "(", "year", ",", "month", ",", "day", ",", "era", ")", "{", "return", "(", "era", "+", "365", ")", "+", "365", "*", "(", "year", "-", "1", ")", "+", "Math", ".", "floor", "(", "year", "/", "4", ")", "+", "30", "*", "month", "+", "day", "-", "31", ";", "}" ]
Computes the Julian day number of the given Coptic or Ethiopic date. This method assumes that the JDN epoch offset has been set. This method is called by copticToGregorian and ethiopicToGregorian which will set the jdn offset context. @param {Number} year year in the Ethiopic calendar @param {Number} month month in the Ethiopic calendar @param {Number} day date in the Ethiopic calendar @param {Number} era [description] @return {Number} The Julian Day Number (JDN)
[ "Computes", "the", "Julian", "day", "number", "of", "the", "given", "Coptic", "or", "Ethiopic", "date", ".", "This", "method", "assumes", "that", "the", "JDN", "epoch", "offset", "has", "been", "set", ".", "This", "method", "is", "called", "by", "copticToGregorian", "and", "ethiopicToGregorian", "which", "will", "set", "the", "jdn", "offset", "context", "." ]
c4e15243fd792f57ecb1a85685ecaf8b4c781ee4
https://github.com/utopiaio/Ethiopic-Calendar/blob/c4e15243fd792f57ecb1a85685ecaf8b4c781ee4/index.js#L42-L44
train
utopiaio/Ethiopic-Calendar
index.js
jdnToGregorian
function jdnToGregorian(jdn, JD_OFFSET = JD_EPOCH_OFFSET_GREGORIAN, leapYear = isGregorianLeap) { const nMonths = 12; const monthDays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; const r2000 = mod((jdn - JD_OFFSET), 730485); const r400 = mod((jdn - JD_OFFSET), 146097); const r100 = mod(r400, 36524); const r4 = mod(r100, 1461); let n = mod(r4, 365) + 365 * Math.floor(r4 / 1460); const s = Math.floor(r4 / 1095); const aprime = 400 * Math.floor((jdn - JD_OFFSET) / 146097) + 100 * Math.floor(r400 / 36524) + 4 * Math.floor(r100 / 1461) + Math.floor(r4 / 365) - Math.floor(r4 / 1460) - Math.floor(r2000 / 730484); const year = aprime + 1; const t = Math.floor((364 + s - n) / 306); let month = t * (Math.floor(n / 31) + 1) + (1 - t) * (Math.floor((5 * (n - s) + 13) / 153) + 1); n += 1 - Math.floor(r2000 / 730484); let day = n; if ((r100 === 0) && (n === 0) && (r400 !== 0)) { month = 12; day = 31; } else { monthDays[2] = (leapYear(year)) ? 29 : 28; for (let i = 1; i <= nMonths; i += 1) { if (n <= monthDays[i]) { day = n; break; } n -= monthDays[i]; } } return { year, month, day }; }
javascript
function jdnToGregorian(jdn, JD_OFFSET = JD_EPOCH_OFFSET_GREGORIAN, leapYear = isGregorianLeap) { const nMonths = 12; const monthDays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; const r2000 = mod((jdn - JD_OFFSET), 730485); const r400 = mod((jdn - JD_OFFSET), 146097); const r100 = mod(r400, 36524); const r4 = mod(r100, 1461); let n = mod(r4, 365) + 365 * Math.floor(r4 / 1460); const s = Math.floor(r4 / 1095); const aprime = 400 * Math.floor((jdn - JD_OFFSET) / 146097) + 100 * Math.floor(r400 / 36524) + 4 * Math.floor(r100 / 1461) + Math.floor(r4 / 365) - Math.floor(r4 / 1460) - Math.floor(r2000 / 730484); const year = aprime + 1; const t = Math.floor((364 + s - n) / 306); let month = t * (Math.floor(n / 31) + 1) + (1 - t) * (Math.floor((5 * (n - s) + 13) / 153) + 1); n += 1 - Math.floor(r2000 / 730484); let day = n; if ((r100 === 0) && (n === 0) && (r400 !== 0)) { month = 12; day = 31; } else { monthDays[2] = (leapYear(year)) ? 29 : 28; for (let i = 1; i <= nMonths; i += 1) { if (n <= monthDays[i]) { day = n; break; } n -= monthDays[i]; } } return { year, month, day }; }
[ "function", "jdnToGregorian", "(", "jdn", ",", "JD_OFFSET", "=", "JD_EPOCH_OFFSET_GREGORIAN", ",", "leapYear", "=", "isGregorianLeap", ")", "{", "const", "nMonths", "=", "12", ";", "const", "monthDays", "=", "[", "0", ",", "31", ",", "28", ",", "31", ",", "30", ",", "31", ",", "30", ",", "31", ",", "31", ",", "30", ",", "31", ",", "30", ",", "31", "]", ";", "const", "r2000", "=", "mod", "(", "(", "jdn", "-", "JD_OFFSET", ")", ",", "730485", ")", ";", "const", "r400", "=", "mod", "(", "(", "jdn", "-", "JD_OFFSET", ")", ",", "146097", ")", ";", "const", "r100", "=", "mod", "(", "r400", ",", "36524", ")", ";", "const", "r4", "=", "mod", "(", "r100", ",", "1461", ")", ";", "let", "n", "=", "mod", "(", "r4", ",", "365", ")", "+", "365", "*", "Math", ".", "floor", "(", "r4", "/", "1460", ")", ";", "const", "s", "=", "Math", ".", "floor", "(", "r4", "/", "1095", ")", ";", "const", "aprime", "=", "400", "*", "Math", ".", "floor", "(", "(", "jdn", "-", "JD_OFFSET", ")", "/", "146097", ")", "+", "100", "*", "Math", ".", "floor", "(", "r400", "/", "36524", ")", "+", "4", "*", "Math", ".", "floor", "(", "r100", "/", "1461", ")", "+", "Math", ".", "floor", "(", "r4", "/", "365", ")", "-", "Math", ".", "floor", "(", "r4", "/", "1460", ")", "-", "Math", ".", "floor", "(", "r2000", "/", "730484", ")", ";", "const", "year", "=", "aprime", "+", "1", ";", "const", "t", "=", "Math", ".", "floor", "(", "(", "364", "+", "s", "-", "n", ")", "/", "306", ")", ";", "let", "month", "=", "t", "*", "(", "Math", ".", "floor", "(", "n", "/", "31", ")", "+", "1", ")", "+", "(", "1", "-", "t", ")", "*", "(", "Math", ".", "floor", "(", "(", "5", "*", "(", "n", "-", "s", ")", "+", "13", ")", "/", "153", ")", "+", "1", ")", ";", "n", "+=", "1", "-", "Math", ".", "floor", "(", "r2000", "/", "730484", ")", ";", "let", "day", "=", "n", ";", "if", "(", "(", "r100", "===", "0", ")", "&&", "(", "n", "===", "0", ")", "&&", "(", "r400", "!==", "0", ")", ")", "{", "month", "=", "12", ";", "day", "=", "31", ";", "}", "else", "{", "monthDays", "[", "2", "]", "=", "(", "leapYear", "(", "year", ")", ")", "?", "29", ":", "28", ";", "for", "(", "let", "i", "=", "1", ";", "i", "<=", "nMonths", ";", "i", "+=", "1", ")", "{", "if", "(", "n", "<=", "monthDays", "[", "i", "]", ")", "{", "day", "=", "n", ";", "break", ";", "}", "n", "-=", "monthDays", "[", "i", "]", ";", "}", "}", "return", "{", "year", ",", "month", ",", "day", "}", ";", "}" ]
converts JDN to Gregorian @param {Number} jdn @param {Number} JD_OFFSET @param {Function} leapYear @return {Number}
[ "converts", "JDN", "to", "Gregorian" ]
c4e15243fd792f57ecb1a85685ecaf8b4c781ee4
https://github.com/utopiaio/Ethiopic-Calendar/blob/c4e15243fd792f57ecb1a85685ecaf8b4c781ee4/index.js#L54-L94
train
utopiaio/Ethiopic-Calendar
index.js
guessEra
function guessEra(jdn, JD_AM = JD_EPOCH_OFFSET_AMETE_MIHRET, JD_AA = JD_EPOCH_OFFSET_AMETE_ALEM) { return (jdn >= (JD_AM + 365)) ? JD_AM : JD_AA; }
javascript
function guessEra(jdn, JD_AM = JD_EPOCH_OFFSET_AMETE_MIHRET, JD_AA = JD_EPOCH_OFFSET_AMETE_ALEM) { return (jdn >= (JD_AM + 365)) ? JD_AM : JD_AA; }
[ "function", "guessEra", "(", "jdn", ",", "JD_AM", "=", "JD_EPOCH_OFFSET_AMETE_MIHRET", ",", "JD_AA", "=", "JD_EPOCH_OFFSET_AMETE_ALEM", ")", "{", "return", "(", "jdn", ">=", "(", "JD_AM", "+", "365", ")", ")", "?", "JD_AM", ":", "JD_AA", ";", "}" ]
guesses ERA from JDN @param {Number} jdn @return {Number}
[ "guesses", "ERA", "from", "JDN" ]
c4e15243fd792f57ecb1a85685ecaf8b4c781ee4
https://github.com/utopiaio/Ethiopic-Calendar/blob/c4e15243fd792f57ecb1a85685ecaf8b4c781ee4/index.js#L102-L104
train
utopiaio/Ethiopic-Calendar
index.js
gregorianToJDN
function gregorianToJDN(year = 1, month = 1, day = 1, JD_OFFSET = JD_EPOCH_OFFSET_GREGORIAN) { const s = Math.floor(year / 4) - Math.floor((year - 1) / 4) - Math.floor(year / 100) + Math.floor((year - 1) / 100) + Math.floor(year / 400) - Math.floor((year - 1) / 400); const t = Math.floor((14 - month) / 12); const n = 31 * t * (month - 1) + (1 - t) * (59 + s + 30 * (month - 3) + Math.floor((3 * month - 7) / 5)) + day - 1; const j = JD_OFFSET + 365 * (year - 1) + Math.floor((year - 1) / 4) - Math.floor((year - 1) / 100) + Math.floor((year - 1) / 400) + n; return j; }
javascript
function gregorianToJDN(year = 1, month = 1, day = 1, JD_OFFSET = JD_EPOCH_OFFSET_GREGORIAN) { const s = Math.floor(year / 4) - Math.floor((year - 1) / 4) - Math.floor(year / 100) + Math.floor((year - 1) / 100) + Math.floor(year / 400) - Math.floor((year - 1) / 400); const t = Math.floor((14 - month) / 12); const n = 31 * t * (month - 1) + (1 - t) * (59 + s + 30 * (month - 3) + Math.floor((3 * month - 7) / 5)) + day - 1; const j = JD_OFFSET + 365 * (year - 1) + Math.floor((year - 1) / 4) - Math.floor((year - 1) / 100) + Math.floor((year - 1) / 400) + n; return j; }
[ "function", "gregorianToJDN", "(", "year", "=", "1", ",", "month", "=", "1", ",", "day", "=", "1", ",", "JD_OFFSET", "=", "JD_EPOCH_OFFSET_GREGORIAN", ")", "{", "const", "s", "=", "Math", ".", "floor", "(", "year", "/", "4", ")", "-", "Math", ".", "floor", "(", "(", "year", "-", "1", ")", "/", "4", ")", "-", "Math", ".", "floor", "(", "year", "/", "100", ")", "+", "Math", ".", "floor", "(", "(", "year", "-", "1", ")", "/", "100", ")", "+", "Math", ".", "floor", "(", "year", "/", "400", ")", "-", "Math", ".", "floor", "(", "(", "year", "-", "1", ")", "/", "400", ")", ";", "const", "t", "=", "Math", ".", "floor", "(", "(", "14", "-", "month", ")", "/", "12", ")", ";", "const", "n", "=", "31", "*", "t", "*", "(", "month", "-", "1", ")", "+", "(", "1", "-", "t", ")", "*", "(", "59", "+", "s", "+", "30", "*", "(", "month", "-", "3", ")", "+", "Math", ".", "floor", "(", "(", "3", "*", "month", "-", "7", ")", "/", "5", ")", ")", "+", "day", "-", "1", ";", "const", "j", "=", "JD_OFFSET", "+", "365", "*", "(", "year", "-", "1", ")", "+", "Math", ".", "floor", "(", "(", "year", "-", "1", ")", "/", "4", ")", "-", "Math", ".", "floor", "(", "(", "year", "-", "1", ")", "/", "100", ")", "+", "Math", ".", "floor", "(", "(", "year", "-", "1", ")", "/", "400", ")", "+", "n", ";", "return", "j", ";", "}" ]
given year, month and day of Gregorian returns JDN @param {Number} year @param {Number} month @param {Number} day @param {Number} JD_OFFSET @return {Number}
[ "given", "year", "month", "and", "day", "of", "Gregorian", "returns", "JDN" ]
c4e15243fd792f57ecb1a85685ecaf8b4c781ee4
https://github.com/utopiaio/Ethiopic-Calendar/blob/c4e15243fd792f57ecb1a85685ecaf8b4c781ee4/index.js#L115-L134
train
utopiaio/Ethiopic-Calendar
index.js
jdnToEthiopic
function jdnToEthiopic(jdn, era = JD_EPOCH_OFFSET_AMETE_MIHRET) { const r = mod((jdn - era), 1461); const n = mod(r, 365) + 365 * Math.floor(r / 1460); const year = 4 * Math.floor((jdn - era) / 1461) + Math.floor(r / 365) - Math.floor(r / 1460); const month = Math.floor(n / 30) + 1; const day = mod(n, 30) + 1; return { year, month, day }; }
javascript
function jdnToEthiopic(jdn, era = JD_EPOCH_OFFSET_AMETE_MIHRET) { const r = mod((jdn - era), 1461); const n = mod(r, 365) + 365 * Math.floor(r / 1460); const year = 4 * Math.floor((jdn - era) / 1461) + Math.floor(r / 365) - Math.floor(r / 1460); const month = Math.floor(n / 30) + 1; const day = mod(n, 30) + 1; return { year, month, day }; }
[ "function", "jdnToEthiopic", "(", "jdn", ",", "era", "=", "JD_EPOCH_OFFSET_AMETE_MIHRET", ")", "{", "const", "r", "=", "mod", "(", "(", "jdn", "-", "era", ")", ",", "1461", ")", ";", "const", "n", "=", "mod", "(", "r", ",", "365", ")", "+", "365", "*", "Math", ".", "floor", "(", "r", "/", "1460", ")", ";", "const", "year", "=", "4", "*", "Math", ".", "floor", "(", "(", "jdn", "-", "era", ")", "/", "1461", ")", "+", "Math", ".", "floor", "(", "r", "/", "365", ")", "-", "Math", ".", "floor", "(", "r", "/", "1460", ")", ";", "const", "month", "=", "Math", ".", "floor", "(", "n", "/", "30", ")", "+", "1", ";", "const", "day", "=", "mod", "(", "n", ",", "30", ")", "+", "1", ";", "return", "{", "year", ",", "month", ",", "day", "}", ";", "}" ]
given a JDN and an era returns the Ethiopic equivalent @param {Number} jdn @param {Number} era @return {Object} { year, month, day }
[ "given", "a", "JDN", "and", "an", "era", "returns", "the", "Ethiopic", "equivalent" ]
c4e15243fd792f57ecb1a85685ecaf8b4c781ee4
https://github.com/utopiaio/Ethiopic-Calendar/blob/c4e15243fd792f57ecb1a85685ecaf8b4c781ee4/index.js#L143-L152
train
chip-js/fragments-js
src/fragments.js
Fragments
function Fragments(options) { if (!options || !options.observations) { throw new TypeError('Must provide an observations instance to Fragments in options.'); } this.compiling = false; this.observations = options.observations; this.globals = options.observations.globals; this.formatters = options.observations.formatters; this.animations = {}; this.animateAttribute = 'animate'; this.binders = { element: { _wildcards: [] }, attribute: { _wildcards: [], _expr: /{{\s*(.*?)\s*}}(?!})/g, _delimitersOnlyInDefault: false }, text: { _wildcards: [], _expr: /{{\s*(.*?)\s*}}(?!})/g } }; // Text binder for text nodes with expressions in them this.registerText('__default__', registerTextDefault); function registerTextDefault(value) { this.element.textContent = (value != null) ? value : ''; } // Text binder for text nodes with expressions in them to be converted to HTML this.registerText('{*}', function(value) { if (this.content) { this.content.remove(); this.content = null; } if (typeof value === 'string' && value || value instanceof Node) { this.content = View.makeInstanceOf(toFragment(value)); this.element.parentNode.insertBefore(this.content, this.element.nextSibling); } }); // Catchall attribute binder for regular attributes with expressions in them this.registerAttribute('__default__', function(value) { if (value != null) { this.element.setAttribute(this.name, value); } else { this.element.removeAttribute(this.name); } }); this.addOptions(options); }
javascript
function Fragments(options) { if (!options || !options.observations) { throw new TypeError('Must provide an observations instance to Fragments in options.'); } this.compiling = false; this.observations = options.observations; this.globals = options.observations.globals; this.formatters = options.observations.formatters; this.animations = {}; this.animateAttribute = 'animate'; this.binders = { element: { _wildcards: [] }, attribute: { _wildcards: [], _expr: /{{\s*(.*?)\s*}}(?!})/g, _delimitersOnlyInDefault: false }, text: { _wildcards: [], _expr: /{{\s*(.*?)\s*}}(?!})/g } }; // Text binder for text nodes with expressions in them this.registerText('__default__', registerTextDefault); function registerTextDefault(value) { this.element.textContent = (value != null) ? value : ''; } // Text binder for text nodes with expressions in them to be converted to HTML this.registerText('{*}', function(value) { if (this.content) { this.content.remove(); this.content = null; } if (typeof value === 'string' && value || value instanceof Node) { this.content = View.makeInstanceOf(toFragment(value)); this.element.parentNode.insertBefore(this.content, this.element.nextSibling); } }); // Catchall attribute binder for regular attributes with expressions in them this.registerAttribute('__default__', function(value) { if (value != null) { this.element.setAttribute(this.name, value); } else { this.element.removeAttribute(this.name); } }); this.addOptions(options); }
[ "function", "Fragments", "(", "options", ")", "{", "if", "(", "!", "options", "||", "!", "options", ".", "observations", ")", "{", "throw", "new", "TypeError", "(", "'Must provide an observations instance to Fragments in options.'", ")", ";", "}", "this", ".", "compiling", "=", "false", ";", "this", ".", "observations", "=", "options", ".", "observations", ";", "this", ".", "globals", "=", "options", ".", "observations", ".", "globals", ";", "this", ".", "formatters", "=", "options", ".", "observations", ".", "formatters", ";", "this", ".", "animations", "=", "{", "}", ";", "this", ".", "animateAttribute", "=", "'animate'", ";", "this", ".", "binders", "=", "{", "element", ":", "{", "_wildcards", ":", "[", "]", "}", ",", "attribute", ":", "{", "_wildcards", ":", "[", "]", ",", "_expr", ":", "/", "{{\\s*(.*?)\\s*}}(?!})", "/", "g", ",", "_delimitersOnlyInDefault", ":", "false", "}", ",", "text", ":", "{", "_wildcards", ":", "[", "]", ",", "_expr", ":", "/", "{{\\s*(.*?)\\s*}}(?!})", "/", "g", "}", "}", ";", "this", ".", "registerText", "(", "'__default__'", ",", "registerTextDefault", ")", ";", "function", "registerTextDefault", "(", "value", ")", "{", "this", ".", "element", ".", "textContent", "=", "(", "value", "!=", "null", ")", "?", "value", ":", "''", ";", "}", "this", ".", "registerText", "(", "'{*}'", ",", "function", "(", "value", ")", "{", "if", "(", "this", ".", "content", ")", "{", "this", ".", "content", ".", "remove", "(", ")", ";", "this", ".", "content", "=", "null", ";", "}", "if", "(", "typeof", "value", "===", "'string'", "&&", "value", "||", "value", "instanceof", "Node", ")", "{", "this", ".", "content", "=", "View", ".", "makeInstanceOf", "(", "toFragment", "(", "value", ")", ")", ";", "this", ".", "element", ".", "parentNode", ".", "insertBefore", "(", "this", ".", "content", ",", "this", ".", "element", ".", "nextSibling", ")", ";", "}", "}", ")", ";", "this", ".", "registerAttribute", "(", "'__default__'", ",", "function", "(", "value", ")", "{", "if", "(", "value", "!=", "null", ")", "{", "this", ".", "element", ".", "setAttribute", "(", "this", ".", "name", ",", "value", ")", ";", "}", "else", "{", "this", ".", "element", ".", "removeAttribute", "(", "this", ".", "name", ")", ";", "}", "}", ")", ";", "this", ".", "addOptions", "(", "options", ")", ";", "}" ]
A Fragments object serves as a registry for binders and formatters @param {Observations} observations An instance of Observations for tracking changes to the data
[ "A", "Fragments", "object", "serves", "as", "a", "registry", "for", "binders", "and", "formatters" ]
5d613ea42c3823423efb01fce4ffef80c7f5ce0f
https://github.com/chip-js/fragments-js/blob/5d613ea42c3823423efb01fce4ffef80c7f5ce0f/src/fragments.js#L18-L66
train
chip-js/fragments-js
src/fragments.js
function(html) { if (!html) { throw new TypeError('Invalid html, cannot create a template from: ' + html); } var fragment = toFragment(html); if (fragment.childNodes.length === 0) { throw new Error('Cannot create a template from ' + html + ' because it is empty.'); } var template = Template.makeInstanceOf(fragment); this.compileTemplate(template); return template; }
javascript
function(html) { if (!html) { throw new TypeError('Invalid html, cannot create a template from: ' + html); } var fragment = toFragment(html); if (fragment.childNodes.length === 0) { throw new Error('Cannot create a template from ' + html + ' because it is empty.'); } var template = Template.makeInstanceOf(fragment); this.compileTemplate(template); return template; }
[ "function", "(", "html", ")", "{", "if", "(", "!", "html", ")", "{", "throw", "new", "TypeError", "(", "'Invalid html, cannot create a template from: '", "+", "html", ")", ";", "}", "var", "fragment", "=", "toFragment", "(", "html", ")", ";", "if", "(", "fragment", ".", "childNodes", ".", "length", "===", "0", ")", "{", "throw", "new", "Error", "(", "'Cannot create a template from '", "+", "html", "+", "' because it is empty.'", ")", ";", "}", "var", "template", "=", "Template", ".", "makeInstanceOf", "(", "fragment", ")", ";", "this", ".", "compileTemplate", "(", "template", ")", ";", "return", "template", ";", "}" ]
Takes an HTML string, an element, an array of elements, or a document fragment, and compiles it into a template. Instances may then be created and bound to a given context. @param {String|NodeList|HTMLCollection|HTMLTemplateElement|HTMLScriptElement|Node} html A Template can be created from many different types of objects. Any of these will be converted into a document fragment for the template to clone. Nodes and elements passed in will be removed from the DOM.
[ "Takes", "an", "HTML", "string", "an", "element", "an", "array", "of", "elements", "or", "a", "document", "fragment", "and", "compiles", "it", "into", "a", "template", ".", "Instances", "may", "then", "be", "created", "and", "bound", "to", "a", "given", "context", "." ]
5d613ea42c3823423efb01fce4ffef80c7f5ce0f
https://github.com/chip-js/fragments-js/blob/5d613ea42c3823423efb01fce4ffef80c7f5ce0f/src/fragments.js#L85-L96
train
chip-js/fragments-js
src/fragments.js
function(template) { if (template && !template.compiled) { // Set compiling flag on fragments, but don't turn it false until the outermost template is done var lastCompilingValue = this.compiling; this.compiling = true; // Set this before compiling so we don't get into infinite loops if there is template recursion template.compiled = true; template.bindings = compile(this, template); this.compiling = lastCompilingValue; } return template; }
javascript
function(template) { if (template && !template.compiled) { // Set compiling flag on fragments, but don't turn it false until the outermost template is done var lastCompilingValue = this.compiling; this.compiling = true; // Set this before compiling so we don't get into infinite loops if there is template recursion template.compiled = true; template.bindings = compile(this, template); this.compiling = lastCompilingValue; } return template; }
[ "function", "(", "template", ")", "{", "if", "(", "template", "&&", "!", "template", ".", "compiled", ")", "{", "var", "lastCompilingValue", "=", "this", ".", "compiling", ";", "this", ".", "compiling", "=", "true", ";", "template", ".", "compiled", "=", "true", ";", "template", ".", "bindings", "=", "compile", "(", "this", ",", "template", ")", ";", "this", ".", "compiling", "=", "lastCompilingValue", ";", "}", "return", "template", ";", "}" ]
Takes a template instance and pre-compiles it @param {Template} template A template @return {Template} The template
[ "Takes", "a", "template", "instance", "and", "pre", "-", "compiles", "it" ]
5d613ea42c3823423efb01fce4ffef80c7f5ce0f
https://github.com/chip-js/fragments-js/blob/5d613ea42c3823423efb01fce4ffef80c7f5ce0f/src/fragments.js#L104-L115
train
chip-js/fragments-js
src/fragments.js
function(element) { if (!element.bindings) { element.bindings = compile(this, element); View.makeInstanceOf(element); } return element; }
javascript
function(element) { if (!element.bindings) { element.bindings = compile(this, element); View.makeInstanceOf(element); } return element; }
[ "function", "(", "element", ")", "{", "if", "(", "!", "element", ".", "bindings", ")", "{", "element", ".", "bindings", "=", "compile", "(", "this", ",", "element", ")", ";", "View", ".", "makeInstanceOf", "(", "element", ")", ";", "}", "return", "element", ";", "}" ]
Compiles bindings on an element.
[ "Compiles", "bindings", "on", "an", "element", "." ]
5d613ea42c3823423efb01fce4ffef80c7f5ce0f
https://github.com/chip-js/fragments-js/blob/5d613ea42c3823423efb01fce4ffef80c7f5ce0f/src/fragments.js#L121-L128
train
chip-js/fragments-js
src/fragments.js
function(context, expr, callback, callbackContext) { if (typeof context === 'string') { callbackContext = callback; callback = expr; expr = context; context = null; } var observer = this.observations.createObserver(expr, callback, callbackContext); if (context) { observer.bind(context, true); } return observer; }
javascript
function(context, expr, callback, callbackContext) { if (typeof context === 'string') { callbackContext = callback; callback = expr; expr = context; context = null; } var observer = this.observations.createObserver(expr, callback, callbackContext); if (context) { observer.bind(context, true); } return observer; }
[ "function", "(", "context", ",", "expr", ",", "callback", ",", "callbackContext", ")", "{", "if", "(", "typeof", "context", "===", "'string'", ")", "{", "callbackContext", "=", "callback", ";", "callback", "=", "expr", ";", "expr", "=", "context", ";", "context", "=", "null", ";", "}", "var", "observer", "=", "this", ".", "observations", ".", "createObserver", "(", "expr", ",", "callback", ",", "callbackContext", ")", ";", "if", "(", "context", ")", "{", "observer", ".", "bind", "(", "context", ",", "true", ")", ";", "}", "return", "observer", ";", "}" ]
Observes an expression within a given context, calling the callback when it changes and returning the observer.
[ "Observes", "an", "expression", "within", "a", "given", "context", "calling", "the", "callback", "when", "it", "changes", "and", "returning", "the", "observer", "." ]
5d613ea42c3823423efb01fce4ffef80c7f5ce0f
https://github.com/chip-js/fragments-js/blob/5d613ea42c3823423efb01fce4ffef80c7f5ce0f/src/fragments.js#L149-L161
train
koggdal/matrixmath
Matrix.js
removeColumn
function removeColumn(values, col, colsPerRow) { var n = 0; for (var i = 0, l = values.length; i < l; i++) { if (i % colsPerRow !== col) values[n++] = values[i]; } values.length = n; }
javascript
function removeColumn(values, col, colsPerRow) { var n = 0; for (var i = 0, l = values.length; i < l; i++) { if (i % colsPerRow !== col) values[n++] = values[i]; } values.length = n; }
[ "function", "removeColumn", "(", "values", ",", "col", ",", "colsPerRow", ")", "{", "var", "n", "=", "0", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "values", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "if", "(", "i", "%", "colsPerRow", "!==", "col", ")", "values", "[", "n", "++", "]", "=", "values", "[", "i", "]", ";", "}", "values", ".", "length", "=", "n", ";", "}" ]
Remove a column from the values array. @param {Array} values Array of values. @param {number} col Index of the column. @param {number} colsPerRow Number of columns per row. @private
[ "Remove", "a", "column", "from", "the", "values", "array", "." ]
4bbc721be90149964bc80221f3afccc1c5f91953
https://github.com/koggdal/matrixmath/blob/4bbc721be90149964bc80221f3afccc1c5f91953/Matrix.js#L839-L845
train
koggdal/matrixmath
Matrix.js
toArray
function toArray(matrix, array) { for (var i = 0, l = matrix.length; i < l; i++) { array[i] = matrix[i]; } return array; }
javascript
function toArray(matrix, array) { for (var i = 0, l = matrix.length; i < l; i++) { array[i] = matrix[i]; } return array; }
[ "function", "toArray", "(", "matrix", ",", "array", ")", "{", "for", "(", "var", "i", "=", "0", ",", "l", "=", "matrix", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "array", "[", "i", "]", "=", "matrix", "[", "i", "]", ";", "}", "return", "array", ";", "}" ]
Convert a matrix to an array with the values. @param {Matrix} matrix The matrix instance. @param {Array} array The array to use. @return {Array} The array. @private
[ "Convert", "a", "matrix", "to", "an", "array", "with", "the", "values", "." ]
4bbc721be90149964bc80221f3afccc1c5f91953
https://github.com/koggdal/matrixmath/blob/4bbc721be90149964bc80221f3afccc1c5f91953/Matrix.js#L857-L863
train
koggdal/matrixmath
Matrix.js
getData
function getData(matrix, array) { toArray(matrix, array); array.rows = matrix.rows; array.cols = matrix.cols; return array; }
javascript
function getData(matrix, array) { toArray(matrix, array); array.rows = matrix.rows; array.cols = matrix.cols; return array; }
[ "function", "getData", "(", "matrix", ",", "array", ")", "{", "toArray", "(", "matrix", ",", "array", ")", ";", "array", ".", "rows", "=", "matrix", ".", "rows", ";", "array", ".", "cols", "=", "matrix", ".", "cols", ";", "return", "array", ";", "}" ]
Get the matrix data as an array with properties for rows and cols. @param {Matrix} matrix The matrix instance. @param {Array} array The array to use. @return {Array} The array. @private
[ "Get", "the", "matrix", "data", "as", "an", "array", "with", "properties", "for", "rows", "and", "cols", "." ]
4bbc721be90149964bc80221f3afccc1c5f91953
https://github.com/koggdal/matrixmath/blob/4bbc721be90149964bc80221f3afccc1c5f91953/Matrix.js#L875-L882
train
tadam313/sheet-db
src/api/v3/index.js
getOperation
function getOperation(opType) { var opname = Object.keys(APISPEC.operations) .filter(function(operation) { return operation === opType; }); if (!opname.length) { throw new ReferenceError('Operation is not supported'); } // avoid mutation return util._extend({}, APISPEC.operations[opname[0]]); }
javascript
function getOperation(opType) { var opname = Object.keys(APISPEC.operations) .filter(function(operation) { return operation === opType; }); if (!opname.length) { throw new ReferenceError('Operation is not supported'); } // avoid mutation return util._extend({}, APISPEC.operations[opname[0]]); }
[ "function", "getOperation", "(", "opType", ")", "{", "var", "opname", "=", "Object", ".", "keys", "(", "APISPEC", ".", "operations", ")", ".", "filter", "(", "function", "(", "operation", ")", "{", "return", "operation", "===", "opType", ";", "}", ")", ";", "if", "(", "!", "opname", ".", "length", ")", "{", "throw", "new", "ReferenceError", "(", "'Operation is not supported'", ")", ";", "}", "return", "util", ".", "_extend", "(", "{", "}", ",", "APISPEC", ".", "operations", "[", "opname", "[", "0", "]", "]", ")", ";", "}" ]
Retrieves te operation description @param opType @returns {*}
[ "Retrieves", "te", "operation", "description" ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/index.js#L76-L88
train
tadam313/sheet-db
src/api/v3/index.js
getOperationContext
function getOperationContext(opType, options) { var operation = getOperation(opType); options = options || {}; options.visibility = !options.token ? 'public' : 'private'; options.apiRoot = APISPEC.root; operation.headers = operation.headers || {}; operation.headers['GData-Version'] = Number(APISPEC.version).toFixed(1); if (options.token) { operation.headers['Authorization'] = 'Bearer ' + options.token; delete options.token; } operation.url = tpl(operation.url, options); operation.body = options.body; operation.strictSSL = false; return operation; }
javascript
function getOperationContext(opType, options) { var operation = getOperation(opType); options = options || {}; options.visibility = !options.token ? 'public' : 'private'; options.apiRoot = APISPEC.root; operation.headers = operation.headers || {}; operation.headers['GData-Version'] = Number(APISPEC.version).toFixed(1); if (options.token) { operation.headers['Authorization'] = 'Bearer ' + options.token; delete options.token; } operation.url = tpl(operation.url, options); operation.body = options.body; operation.strictSSL = false; return operation; }
[ "function", "getOperationContext", "(", "opType", ",", "options", ")", "{", "var", "operation", "=", "getOperation", "(", "opType", ")", ";", "options", "=", "options", "||", "{", "}", ";", "options", ".", "visibility", "=", "!", "options", ".", "token", "?", "'public'", ":", "'private'", ";", "options", ".", "apiRoot", "=", "APISPEC", ".", "root", ";", "operation", ".", "headers", "=", "operation", ".", "headers", "||", "{", "}", ";", "operation", ".", "headers", "[", "'GData-Version'", "]", "=", "Number", "(", "APISPEC", ".", "version", ")", ".", "toFixed", "(", "1", ")", ";", "if", "(", "options", ".", "token", ")", "{", "operation", ".", "headers", "[", "'Authorization'", "]", "=", "'Bearer '", "+", "options", ".", "token", ";", "delete", "options", ".", "token", ";", "}", "operation", ".", "url", "=", "tpl", "(", "operation", ".", "url", ",", "options", ")", ";", "operation", ".", "body", "=", "options", ".", "body", ";", "operation", ".", "strictSSL", "=", "false", ";", "return", "operation", ";", "}" ]
Retrieves the operation context for the given type @param opType @param options @returns {*}
[ "Retrieves", "the", "operation", "context", "for", "the", "given", "type" ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/index.js#L97-L119
train
mikolalysenko/clean-pslg
clean-pslg.js
boundRat
function boundRat (r) { var f = ratToFloat(r) return [ nextafter(f, -Infinity), nextafter(f, Infinity) ] }
javascript
function boundRat (r) { var f = ratToFloat(r) return [ nextafter(f, -Infinity), nextafter(f, Infinity) ] }
[ "function", "boundRat", "(", "r", ")", "{", "var", "f", "=", "ratToFloat", "(", "r", ")", "return", "[", "nextafter", "(", "f", ",", "-", "Infinity", ")", ",", "nextafter", "(", "f", ",", "Infinity", ")", "]", "}" ]
Bounds on a rational number when rounded to a float
[ "Bounds", "on", "a", "rational", "number", "when", "rounded", "to", "a", "float" ]
c20e801e036bf2c8ebca6ea6c6631aa64fc334c7
https://github.com/mikolalysenko/clean-pslg/blob/c20e801e036bf2c8ebca6ea6c6631aa64fc334c7/clean-pslg.js#L17-L23
train
mikolalysenko/clean-pslg
clean-pslg.js
boundEdges
function boundEdges (points, edges) { var bounds = new Array(edges.length) for (var i = 0; i < edges.length; ++i) { var e = edges[i] var a = points[e[0]] var b = points[e[1]] bounds[i] = [ nextafter(Math.min(a[0], b[0]), -Infinity), nextafter(Math.min(a[1], b[1]), -Infinity), nextafter(Math.max(a[0], b[0]), Infinity), nextafter(Math.max(a[1], b[1]), Infinity) ] } return bounds }
javascript
function boundEdges (points, edges) { var bounds = new Array(edges.length) for (var i = 0; i < edges.length; ++i) { var e = edges[i] var a = points[e[0]] var b = points[e[1]] bounds[i] = [ nextafter(Math.min(a[0], b[0]), -Infinity), nextafter(Math.min(a[1], b[1]), -Infinity), nextafter(Math.max(a[0], b[0]), Infinity), nextafter(Math.max(a[1], b[1]), Infinity) ] } return bounds }
[ "function", "boundEdges", "(", "points", ",", "edges", ")", "{", "var", "bounds", "=", "new", "Array", "(", "edges", ".", "length", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "edges", ".", "length", ";", "++", "i", ")", "{", "var", "e", "=", "edges", "[", "i", "]", "var", "a", "=", "points", "[", "e", "[", "0", "]", "]", "var", "b", "=", "points", "[", "e", "[", "1", "]", "]", "bounds", "[", "i", "]", "=", "[", "nextafter", "(", "Math", ".", "min", "(", "a", "[", "0", "]", ",", "b", "[", "0", "]", ")", ",", "-", "Infinity", ")", ",", "nextafter", "(", "Math", ".", "min", "(", "a", "[", "1", "]", ",", "b", "[", "1", "]", ")", ",", "-", "Infinity", ")", ",", "nextafter", "(", "Math", ".", "max", "(", "a", "[", "0", "]", ",", "b", "[", "0", "]", ")", ",", "Infinity", ")", ",", "nextafter", "(", "Math", ".", "max", "(", "a", "[", "1", "]", ",", "b", "[", "1", "]", ")", ",", "Infinity", ")", "]", "}", "return", "bounds", "}" ]
Convert a list of edges in a pslg to bounding boxes
[ "Convert", "a", "list", "of", "edges", "in", "a", "pslg", "to", "bounding", "boxes" ]
c20e801e036bf2c8ebca6ea6c6631aa64fc334c7
https://github.com/mikolalysenko/clean-pslg/blob/c20e801e036bf2c8ebca6ea6c6631aa64fc334c7/clean-pslg.js#L26-L40
train
mikolalysenko/clean-pslg
clean-pslg.js
boundPoints
function boundPoints (points) { var bounds = new Array(points.length) for (var i = 0; i < points.length; ++i) { var p = points[i] bounds[i] = [ nextafter(p[0], -Infinity), nextafter(p[1], -Infinity), nextafter(p[0], Infinity), nextafter(p[1], Infinity) ] } return bounds }
javascript
function boundPoints (points) { var bounds = new Array(points.length) for (var i = 0; i < points.length; ++i) { var p = points[i] bounds[i] = [ nextafter(p[0], -Infinity), nextafter(p[1], -Infinity), nextafter(p[0], Infinity), nextafter(p[1], Infinity) ] } return bounds }
[ "function", "boundPoints", "(", "points", ")", "{", "var", "bounds", "=", "new", "Array", "(", "points", ".", "length", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "points", ".", "length", ";", "++", "i", ")", "{", "var", "p", "=", "points", "[", "i", "]", "bounds", "[", "i", "]", "=", "[", "nextafter", "(", "p", "[", "0", "]", ",", "-", "Infinity", ")", ",", "nextafter", "(", "p", "[", "1", "]", ",", "-", "Infinity", ")", ",", "nextafter", "(", "p", "[", "0", "]", ",", "Infinity", ")", ",", "nextafter", "(", "p", "[", "1", "]", ",", "Infinity", ")", "]", "}", "return", "bounds", "}" ]
Convert a list of points into bounding boxes by duplicating coords
[ "Convert", "a", "list", "of", "points", "into", "bounding", "boxes", "by", "duplicating", "coords" ]
c20e801e036bf2c8ebca6ea6c6631aa64fc334c7
https://github.com/mikolalysenko/clean-pslg/blob/c20e801e036bf2c8ebca6ea6c6631aa64fc334c7/clean-pslg.js#L43-L55
train
mikolalysenko/clean-pslg
clean-pslg.js
dedupPoints
function dedupPoints (floatPoints, ratPoints, floatBounds) { var numPoints = ratPoints.length var uf = new UnionFind(numPoints) // Compute rational bounds var bounds = [] for (var i = 0; i < ratPoints.length; ++i) { var p = ratPoints[i] var xb = boundRat(p[0]) var yb = boundRat(p[1]) bounds.push([ nextafter(xb[0], -Infinity), nextafter(yb[0], -Infinity), nextafter(xb[1], Infinity), nextafter(yb[1], Infinity) ]) } // Link all points with over lapping boxes boxIntersect(bounds, function (i, j) { uf.link(i, j) }) // Do 1 pass over points to combine points in label sets var noDupes = true var labels = new Array(numPoints) for (var i = 0; i < numPoints; ++i) { var j = uf.find(i) if (j !== i) { // Clear no-dupes flag, zero out label noDupes = false // Make each point the top-left point from its cell floatPoints[j] = [ Math.min(floatPoints[i][0], floatPoints[j][0]), Math.min(floatPoints[i][1], floatPoints[j][1]) ] } } // If no duplicates, return null to signal termination if (noDupes) { return null } var ptr = 0 for (var i = 0; i < numPoints; ++i) { var j = uf.find(i) if (j === i) { labels[i] = ptr floatPoints[ptr++] = floatPoints[i] } else { labels[i] = -1 } } floatPoints.length = ptr // Do a second pass to fix up missing labels for (var i = 0; i < numPoints; ++i) { if (labels[i] < 0) { labels[i] = labels[uf.find(i)] } } // Return resulting union-find data structure return labels }
javascript
function dedupPoints (floatPoints, ratPoints, floatBounds) { var numPoints = ratPoints.length var uf = new UnionFind(numPoints) // Compute rational bounds var bounds = [] for (var i = 0; i < ratPoints.length; ++i) { var p = ratPoints[i] var xb = boundRat(p[0]) var yb = boundRat(p[1]) bounds.push([ nextafter(xb[0], -Infinity), nextafter(yb[0], -Infinity), nextafter(xb[1], Infinity), nextafter(yb[1], Infinity) ]) } // Link all points with over lapping boxes boxIntersect(bounds, function (i, j) { uf.link(i, j) }) // Do 1 pass over points to combine points in label sets var noDupes = true var labels = new Array(numPoints) for (var i = 0; i < numPoints; ++i) { var j = uf.find(i) if (j !== i) { // Clear no-dupes flag, zero out label noDupes = false // Make each point the top-left point from its cell floatPoints[j] = [ Math.min(floatPoints[i][0], floatPoints[j][0]), Math.min(floatPoints[i][1], floatPoints[j][1]) ] } } // If no duplicates, return null to signal termination if (noDupes) { return null } var ptr = 0 for (var i = 0; i < numPoints; ++i) { var j = uf.find(i) if (j === i) { labels[i] = ptr floatPoints[ptr++] = floatPoints[i] } else { labels[i] = -1 } } floatPoints.length = ptr // Do a second pass to fix up missing labels for (var i = 0; i < numPoints; ++i) { if (labels[i] < 0) { labels[i] = labels[uf.find(i)] } } // Return resulting union-find data structure return labels }
[ "function", "dedupPoints", "(", "floatPoints", ",", "ratPoints", ",", "floatBounds", ")", "{", "var", "numPoints", "=", "ratPoints", ".", "length", "var", "uf", "=", "new", "UnionFind", "(", "numPoints", ")", "var", "bounds", "=", "[", "]", "for", "(", "var", "i", "=", "0", ";", "i", "<", "ratPoints", ".", "length", ";", "++", "i", ")", "{", "var", "p", "=", "ratPoints", "[", "i", "]", "var", "xb", "=", "boundRat", "(", "p", "[", "0", "]", ")", "var", "yb", "=", "boundRat", "(", "p", "[", "1", "]", ")", "bounds", ".", "push", "(", "[", "nextafter", "(", "xb", "[", "0", "]", ",", "-", "Infinity", ")", ",", "nextafter", "(", "yb", "[", "0", "]", ",", "-", "Infinity", ")", ",", "nextafter", "(", "xb", "[", "1", "]", ",", "Infinity", ")", ",", "nextafter", "(", "yb", "[", "1", "]", ",", "Infinity", ")", "]", ")", "}", "boxIntersect", "(", "bounds", ",", "function", "(", "i", ",", "j", ")", "{", "uf", ".", "link", "(", "i", ",", "j", ")", "}", ")", "var", "noDupes", "=", "true", "var", "labels", "=", "new", "Array", "(", "numPoints", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numPoints", ";", "++", "i", ")", "{", "var", "j", "=", "uf", ".", "find", "(", "i", ")", "if", "(", "j", "!==", "i", ")", "{", "noDupes", "=", "false", "floatPoints", "[", "j", "]", "=", "[", "Math", ".", "min", "(", "floatPoints", "[", "i", "]", "[", "0", "]", ",", "floatPoints", "[", "j", "]", "[", "0", "]", ")", ",", "Math", ".", "min", "(", "floatPoints", "[", "i", "]", "[", "1", "]", ",", "floatPoints", "[", "j", "]", "[", "1", "]", ")", "]", "}", "}", "if", "(", "noDupes", ")", "{", "return", "null", "}", "var", "ptr", "=", "0", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numPoints", ";", "++", "i", ")", "{", "var", "j", "=", "uf", ".", "find", "(", "i", ")", "if", "(", "j", "===", "i", ")", "{", "labels", "[", "i", "]", "=", "ptr", "floatPoints", "[", "ptr", "++", "]", "=", "floatPoints", "[", "i", "]", "}", "else", "{", "labels", "[", "i", "]", "=", "-", "1", "}", "}", "floatPoints", ".", "length", "=", "ptr", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numPoints", ";", "++", "i", ")", "{", "if", "(", "labels", "[", "i", "]", "<", "0", ")", "{", "labels", "[", "i", "]", "=", "labels", "[", "uf", ".", "find", "(", "i", ")", "]", "}", "}", "return", "labels", "}" ]
Merge overlapping points
[ "Merge", "overlapping", "points" ]
c20e801e036bf2c8ebca6ea6c6631aa64fc334c7
https://github.com/mikolalysenko/clean-pslg/blob/c20e801e036bf2c8ebca6ea6c6631aa64fc334c7/clean-pslg.js#L191-L257
train
mikolalysenko/clean-pslg
clean-pslg.js
dedupEdges
function dedupEdges (edges, labels, useColor) { if (edges.length === 0) { return } if (labels) { for (var i = 0; i < edges.length; ++i) { var e = edges[i] var a = labels[e[0]] var b = labels[e[1]] e[0] = Math.min(a, b) e[1] = Math.max(a, b) } } else { for (var i = 0; i < edges.length; ++i) { var e = edges[i] var a = e[0] var b = e[1] e[0] = Math.min(a, b) e[1] = Math.max(a, b) } } if (useColor) { edges.sort(compareLex3) } else { edges.sort(compareLex2) } var ptr = 1 for (var i = 1; i < edges.length; ++i) { var prev = edges[i - 1] var next = edges[i] if (next[0] === prev[0] && next[1] === prev[1] && (!useColor || next[2] === prev[2])) { continue } edges[ptr++] = next } edges.length = ptr }
javascript
function dedupEdges (edges, labels, useColor) { if (edges.length === 0) { return } if (labels) { for (var i = 0; i < edges.length; ++i) { var e = edges[i] var a = labels[e[0]] var b = labels[e[1]] e[0] = Math.min(a, b) e[1] = Math.max(a, b) } } else { for (var i = 0; i < edges.length; ++i) { var e = edges[i] var a = e[0] var b = e[1] e[0] = Math.min(a, b) e[1] = Math.max(a, b) } } if (useColor) { edges.sort(compareLex3) } else { edges.sort(compareLex2) } var ptr = 1 for (var i = 1; i < edges.length; ++i) { var prev = edges[i - 1] var next = edges[i] if (next[0] === prev[0] && next[1] === prev[1] && (!useColor || next[2] === prev[2])) { continue } edges[ptr++] = next } edges.length = ptr }
[ "function", "dedupEdges", "(", "edges", ",", "labels", ",", "useColor", ")", "{", "if", "(", "edges", ".", "length", "===", "0", ")", "{", "return", "}", "if", "(", "labels", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "edges", ".", "length", ";", "++", "i", ")", "{", "var", "e", "=", "edges", "[", "i", "]", "var", "a", "=", "labels", "[", "e", "[", "0", "]", "]", "var", "b", "=", "labels", "[", "e", "[", "1", "]", "]", "e", "[", "0", "]", "=", "Math", ".", "min", "(", "a", ",", "b", ")", "e", "[", "1", "]", "=", "Math", ".", "max", "(", "a", ",", "b", ")", "}", "}", "else", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "edges", ".", "length", ";", "++", "i", ")", "{", "var", "e", "=", "edges", "[", "i", "]", "var", "a", "=", "e", "[", "0", "]", "var", "b", "=", "e", "[", "1", "]", "e", "[", "0", "]", "=", "Math", ".", "min", "(", "a", ",", "b", ")", "e", "[", "1", "]", "=", "Math", ".", "max", "(", "a", ",", "b", ")", "}", "}", "if", "(", "useColor", ")", "{", "edges", ".", "sort", "(", "compareLex3", ")", "}", "else", "{", "edges", ".", "sort", "(", "compareLex2", ")", "}", "var", "ptr", "=", "1", "for", "(", "var", "i", "=", "1", ";", "i", "<", "edges", ".", "length", ";", "++", "i", ")", "{", "var", "prev", "=", "edges", "[", "i", "-", "1", "]", "var", "next", "=", "edges", "[", "i", "]", "if", "(", "next", "[", "0", "]", "===", "prev", "[", "0", "]", "&&", "next", "[", "1", "]", "===", "prev", "[", "1", "]", "&&", "(", "!", "useColor", "||", "next", "[", "2", "]", "===", "prev", "[", "2", "]", ")", ")", "{", "continue", "}", "edges", "[", "ptr", "++", "]", "=", "next", "}", "edges", ".", "length", "=", "ptr", "}" ]
Remove duplicate edge labels
[ "Remove", "duplicate", "edge", "labels" ]
c20e801e036bf2c8ebca6ea6c6631aa64fc334c7
https://github.com/mikolalysenko/clean-pslg/blob/c20e801e036bf2c8ebca6ea6c6631aa64fc334c7/clean-pslg.js#L274-L311
train
mikolalysenko/clean-pslg
clean-pslg.js
snapRound
function snapRound (points, edges, useColor) { // 1. find edge crossings var edgeBounds = boundEdges(points, edges) var crossings = getCrossings(points, edges, edgeBounds) // 2. find t-junctions var vertBounds = boundPoints(points) var tjunctions = getTJunctions(points, edges, edgeBounds, vertBounds) // 3. cut edges, construct rational points var ratPoints = cutEdges(points, edges, crossings, tjunctions, useColor) // 4. dedupe verts var labels = dedupPoints(points, ratPoints, vertBounds) // 5. dedupe edges dedupEdges(edges, labels, useColor) // 6. check termination if (!labels) { return (crossings.length > 0 || tjunctions.length > 0) } // More iterations necessary return true }
javascript
function snapRound (points, edges, useColor) { // 1. find edge crossings var edgeBounds = boundEdges(points, edges) var crossings = getCrossings(points, edges, edgeBounds) // 2. find t-junctions var vertBounds = boundPoints(points) var tjunctions = getTJunctions(points, edges, edgeBounds, vertBounds) // 3. cut edges, construct rational points var ratPoints = cutEdges(points, edges, crossings, tjunctions, useColor) // 4. dedupe verts var labels = dedupPoints(points, ratPoints, vertBounds) // 5. dedupe edges dedupEdges(edges, labels, useColor) // 6. check termination if (!labels) { return (crossings.length > 0 || tjunctions.length > 0) } // More iterations necessary return true }
[ "function", "snapRound", "(", "points", ",", "edges", ",", "useColor", ")", "{", "var", "edgeBounds", "=", "boundEdges", "(", "points", ",", "edges", ")", "var", "crossings", "=", "getCrossings", "(", "points", ",", "edges", ",", "edgeBounds", ")", "var", "vertBounds", "=", "boundPoints", "(", "points", ")", "var", "tjunctions", "=", "getTJunctions", "(", "points", ",", "edges", ",", "edgeBounds", ",", "vertBounds", ")", "var", "ratPoints", "=", "cutEdges", "(", "points", ",", "edges", ",", "crossings", ",", "tjunctions", ",", "useColor", ")", "var", "labels", "=", "dedupPoints", "(", "points", ",", "ratPoints", ",", "vertBounds", ")", "dedupEdges", "(", "edges", ",", "labels", ",", "useColor", ")", "if", "(", "!", "labels", ")", "{", "return", "(", "crossings", ".", "length", ">", "0", "||", "tjunctions", ".", "length", ">", "0", ")", "}", "return", "true", "}" ]
Repeat until convergence
[ "Repeat", "until", "convergence" ]
c20e801e036bf2c8ebca6ea6c6631aa64fc334c7
https://github.com/mikolalysenko/clean-pslg/blob/c20e801e036bf2c8ebca6ea6c6631aa64fc334c7/clean-pslg.js#L320-L345
train
mikolalysenko/clean-pslg
clean-pslg.js
cleanPSLG
function cleanPSLG (points, edges, colors) { // If using colors, augment edges with color data var prevEdges if (colors) { prevEdges = edges var augEdges = new Array(edges.length) for (var i = 0; i < edges.length; ++i) { var e = edges[i] augEdges[i] = [e[0], e[1], colors[i]] } edges = augEdges } // First round: remove duplicate edges and points var modified = preRound(points, edges, !!colors) // Run snap rounding until convergence while (snapRound(points, edges, !!colors)) { modified = true } // Strip color tags if (!!colors && modified) { prevEdges.length = 0 colors.length = 0 for (var i = 0; i < edges.length; ++i) { var e = edges[i] prevEdges.push([e[0], e[1]]) colors.push(e[2]) } } return modified }
javascript
function cleanPSLG (points, edges, colors) { // If using colors, augment edges with color data var prevEdges if (colors) { prevEdges = edges var augEdges = new Array(edges.length) for (var i = 0; i < edges.length; ++i) { var e = edges[i] augEdges[i] = [e[0], e[1], colors[i]] } edges = augEdges } // First round: remove duplicate edges and points var modified = preRound(points, edges, !!colors) // Run snap rounding until convergence while (snapRound(points, edges, !!colors)) { modified = true } // Strip color tags if (!!colors && modified) { prevEdges.length = 0 colors.length = 0 for (var i = 0; i < edges.length; ++i) { var e = edges[i] prevEdges.push([e[0], e[1]]) colors.push(e[2]) } } return modified }
[ "function", "cleanPSLG", "(", "points", ",", "edges", ",", "colors", ")", "{", "var", "prevEdges", "if", "(", "colors", ")", "{", "prevEdges", "=", "edges", "var", "augEdges", "=", "new", "Array", "(", "edges", ".", "length", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "edges", ".", "length", ";", "++", "i", ")", "{", "var", "e", "=", "edges", "[", "i", "]", "augEdges", "[", "i", "]", "=", "[", "e", "[", "0", "]", ",", "e", "[", "1", "]", ",", "colors", "[", "i", "]", "]", "}", "edges", "=", "augEdges", "}", "var", "modified", "=", "preRound", "(", "points", ",", "edges", ",", "!", "!", "colors", ")", "while", "(", "snapRound", "(", "points", ",", "edges", ",", "!", "!", "colors", ")", ")", "{", "modified", "=", "true", "}", "if", "(", "!", "!", "colors", "&&", "modified", ")", "{", "prevEdges", ".", "length", "=", "0", "colors", ".", "length", "=", "0", "for", "(", "var", "i", "=", "0", ";", "i", "<", "edges", ".", "length", ";", "++", "i", ")", "{", "var", "e", "=", "edges", "[", "i", "]", "prevEdges", ".", "push", "(", "[", "e", "[", "0", "]", ",", "e", "[", "1", "]", "]", ")", "colors", ".", "push", "(", "e", "[", "2", "]", ")", "}", "}", "return", "modified", "}" ]
Main loop, runs PSLG clean up until completion
[ "Main", "loop", "runs", "PSLG", "clean", "up", "until", "completion" ]
c20e801e036bf2c8ebca6ea6c6631aa64fc334c7
https://github.com/mikolalysenko/clean-pslg/blob/c20e801e036bf2c8ebca6ea6c6631aa64fc334c7/clean-pslg.js#L348-L381
train
reapp/reapp-kit
src/lib/theme.js
convertRawTheme
function convertRawTheme(theme) { if (!Array.isArray(theme.constants)) { return { constants: Object.keys(theme.constants).map(key => theme.constants[key]), styles: [].concat(theme.styles), animations: [].concat(theme.animations) } } else return theme; }
javascript
function convertRawTheme(theme) { if (!Array.isArray(theme.constants)) { return { constants: Object.keys(theme.constants).map(key => theme.constants[key]), styles: [].concat(theme.styles), animations: [].concat(theme.animations) } } else return theme; }
[ "function", "convertRawTheme", "(", "theme", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "theme", ".", "constants", ")", ")", "{", "return", "{", "constants", ":", "Object", ".", "keys", "(", "theme", ".", "constants", ")", ".", "map", "(", "key", "=>", "theme", ".", "constants", "[", "key", "]", ")", ",", "styles", ":", "[", "]", ".", "concat", "(", "theme", ".", "styles", ")", ",", "animations", ":", "[", "]", ".", "concat", "(", "theme", ".", "animations", ")", "}", "}", "else", "return", "theme", ";", "}" ]
user may not want to configure a whole theme and just pass in the theme we give them wholesale, lets convert it
[ "user", "may", "not", "want", "to", "configure", "a", "whole", "theme", "and", "just", "pass", "in", "the", "theme", "we", "give", "them", "wholesale", "lets", "convert", "it" ]
10557c6b808542f52bb421e23efb2b58dff567ed
https://github.com/reapp/reapp-kit/blob/10557c6b808542f52bb421e23efb2b58dff567ed/src/lib/theme.js#L20-L30
train
jonschlinkert/expand-object
index.js
expand
function expand(str, opts) { opts = opts || {}; if (typeof str !== 'string') { throw new TypeError('expand-object expects a string.'); } if (!/[.|:=]/.test(str) && /,/.test(str)) { return toArray(str); } var m; if ((m = /(\w+[:=]\w+\.)+/.exec(str)) && !/[|,+]/.test(str)) { var val = m[0].split(':').join('.'); str = val + str.slice(m[0].length); } var arr = splitString(str, '|'); var len = arr.length, i = -1; var res = {}; if (isArrayLike(str) && arr.length === 1) { return expandArrayObj(str, opts); } while (++i < len) { var val = arr[i]; // test for `https://foo` if (/\w:\/\/\w/.test(val)) { res[val] = ''; continue; } var re = /^((?:\w+)\.(?:\w+))[:.]((?:\w+,)+)+((?:\w+):(?:\w+))/; var m = re.exec(val); if (m && m[1] && m[2] && m[3]) { var arrVal = m[2]; arrVal = arrVal.replace(/,$/, ''); var prop = arrVal.split(','); prop = prop.concat(toObject(m[3])); res = set(res, m[1], prop); } else if (!/[.,\|:=]/.test(val)) { res[val] = opts.toBoolean ? true : ''; } else { res = expandObject(res, val, opts); } } return res; }
javascript
function expand(str, opts) { opts = opts || {}; if (typeof str !== 'string') { throw new TypeError('expand-object expects a string.'); } if (!/[.|:=]/.test(str) && /,/.test(str)) { return toArray(str); } var m; if ((m = /(\w+[:=]\w+\.)+/.exec(str)) && !/[|,+]/.test(str)) { var val = m[0].split(':').join('.'); str = val + str.slice(m[0].length); } var arr = splitString(str, '|'); var len = arr.length, i = -1; var res = {}; if (isArrayLike(str) && arr.length === 1) { return expandArrayObj(str, opts); } while (++i < len) { var val = arr[i]; // test for `https://foo` if (/\w:\/\/\w/.test(val)) { res[val] = ''; continue; } var re = /^((?:\w+)\.(?:\w+))[:.]((?:\w+,)+)+((?:\w+):(?:\w+))/; var m = re.exec(val); if (m && m[1] && m[2] && m[3]) { var arrVal = m[2]; arrVal = arrVal.replace(/,$/, ''); var prop = arrVal.split(','); prop = prop.concat(toObject(m[3])); res = set(res, m[1], prop); } else if (!/[.,\|:=]/.test(val)) { res[val] = opts.toBoolean ? true : ''; } else { res = expandObject(res, val, opts); } } return res; }
[ "function", "expand", "(", "str", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "if", "(", "typeof", "str", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'expand-object expects a string.'", ")", ";", "}", "if", "(", "!", "/", "[.|:=]", "/", ".", "test", "(", "str", ")", "&&", "/", ",", "/", ".", "test", "(", "str", ")", ")", "{", "return", "toArray", "(", "str", ")", ";", "}", "var", "m", ";", "if", "(", "(", "m", "=", "/", "(\\w+[:=]\\w+\\.)+", "/", ".", "exec", "(", "str", ")", ")", "&&", "!", "/", "[|,+]", "/", ".", "test", "(", "str", ")", ")", "{", "var", "val", "=", "m", "[", "0", "]", ".", "split", "(", "':'", ")", ".", "join", "(", "'.'", ")", ";", "str", "=", "val", "+", "str", ".", "slice", "(", "m", "[", "0", "]", ".", "length", ")", ";", "}", "var", "arr", "=", "splitString", "(", "str", ",", "'|'", ")", ";", "var", "len", "=", "arr", ".", "length", ",", "i", "=", "-", "1", ";", "var", "res", "=", "{", "}", ";", "if", "(", "isArrayLike", "(", "str", ")", "&&", "arr", ".", "length", "===", "1", ")", "{", "return", "expandArrayObj", "(", "str", ",", "opts", ")", ";", "}", "while", "(", "++", "i", "<", "len", ")", "{", "var", "val", "=", "arr", "[", "i", "]", ";", "if", "(", "/", "\\w:\\/\\/\\w", "/", ".", "test", "(", "val", ")", ")", "{", "res", "[", "val", "]", "=", "''", ";", "continue", ";", "}", "var", "re", "=", "/", "^((?:\\w+)\\.(?:\\w+))[:.]((?:\\w+,)+)+((?:\\w+):(?:\\w+))", "/", ";", "var", "m", "=", "re", ".", "exec", "(", "val", ")", ";", "if", "(", "m", "&&", "m", "[", "1", "]", "&&", "m", "[", "2", "]", "&&", "m", "[", "3", "]", ")", "{", "var", "arrVal", "=", "m", "[", "2", "]", ";", "arrVal", "=", "arrVal", ".", "replace", "(", "/", ",$", "/", ",", "''", ")", ";", "var", "prop", "=", "arrVal", ".", "split", "(", "','", ")", ";", "prop", "=", "prop", ".", "concat", "(", "toObject", "(", "m", "[", "3", "]", ")", ")", ";", "res", "=", "set", "(", "res", ",", "m", "[", "1", "]", ",", "prop", ")", ";", "}", "else", "if", "(", "!", "/", "[.,\\|:=]", "/", ".", "test", "(", "val", ")", ")", "{", "res", "[", "val", "]", "=", "opts", ".", "toBoolean", "?", "true", ":", "''", ";", "}", "else", "{", "res", "=", "expandObject", "(", "res", ",", "val", ",", "opts", ")", ";", "}", "}", "return", "res", ";", "}" ]
Expand the given string into an object. @param {String} `str` @return {Object}
[ "Expand", "the", "given", "string", "into", "an", "object", "." ]
98abd15d44d167d8c40f77bfcf01022b1d631c93
https://github.com/jonschlinkert/expand-object/blob/98abd15d44d167d8c40f77bfcf01022b1d631c93/index.js#L13-L61
train
socialshares/buttons
src/socialshares.js
getService
function getService (classList) { let service Object.keys(services).forEach(key => { if (classList.contains('socialshares-' + key)) { service = services[key] service.name = key } }) return service }
javascript
function getService (classList) { let service Object.keys(services).forEach(key => { if (classList.contains('socialshares-' + key)) { service = services[key] service.name = key } }) return service }
[ "function", "getService", "(", "classList", ")", "{", "let", "service", "Object", ".", "keys", "(", "services", ")", ".", "forEach", "(", "key", "=>", "{", "if", "(", "classList", ".", "contains", "(", "'socialshares-'", "+", "key", ")", ")", "{", "service", "=", "services", "[", "key", "]", "service", ".", "name", "=", "key", "}", "}", ")", "return", "service", "}" ]
Identifies the service based on the button's class and returns the metadata for that service.
[ "Identifies", "the", "service", "based", "on", "the", "button", "s", "class", "and", "returns", "the", "metadata", "for", "that", "service", "." ]
f0d47c7b8dfb6d9e994d266f199a936ced7c0f28
https://github.com/socialshares/buttons/blob/f0d47c7b8dfb6d9e994d266f199a936ced7c0f28/src/socialshares.js#L37-L48
train
socialshares/buttons
src/socialshares.js
openDialog
function openDialog (url) { const width = socialshares.config.dialog.width const height = socialshares.config.dialog.height // Center the popup const top = (window.screen.height / 2 - height / 2) const left = (window.screen.width / 2 - width / 2) window.open(url, 'Share', `width=${width},height=${height},top=${top},left=${left},menubar=no,toolbar=no,resizable=yes,scrollbars=yes`) }
javascript
function openDialog (url) { const width = socialshares.config.dialog.width const height = socialshares.config.dialog.height // Center the popup const top = (window.screen.height / 2 - height / 2) const left = (window.screen.width / 2 - width / 2) window.open(url, 'Share', `width=${width},height=${height},top=${top},left=${left},menubar=no,toolbar=no,resizable=yes,scrollbars=yes`) }
[ "function", "openDialog", "(", "url", ")", "{", "const", "width", "=", "socialshares", ".", "config", ".", "dialog", ".", "width", "const", "height", "=", "socialshares", ".", "config", ".", "dialog", ".", "height", "const", "top", "=", "(", "window", ".", "screen", ".", "height", "/", "2", "-", "height", "/", "2", ")", "const", "left", "=", "(", "window", ".", "screen", ".", "width", "/", "2", "-", "width", "/", "2", ")", "window", ".", "open", "(", "url", ",", "'Share'", ",", "`", "${", "width", "}", "${", "height", "}", "${", "top", "}", "${", "left", "}", "`", ")", "}" ]
Popup window helper
[ "Popup", "window", "helper" ]
f0d47c7b8dfb6d9e994d266f199a936ced7c0f28
https://github.com/socialshares/buttons/blob/f0d47c7b8dfb6d9e994d266f199a936ced7c0f28/src/socialshares.js#L57-L66
train
tadam313/sheet-db
src/rest_client.js
fetchData
async function fetchData(key, transformation, cacheMiss) { // TODO: needs better caching logic var data = cache.get(key); if (data) { return data; } try { data = transformation(await cacheMiss()); } catch (err) { throw new Error('The response contains invalid data'); } cache.put(key, data); return data; }
javascript
async function fetchData(key, transformation, cacheMiss) { // TODO: needs better caching logic var data = cache.get(key); if (data) { return data; } try { data = transformation(await cacheMiss()); } catch (err) { throw new Error('The response contains invalid data'); } cache.put(key, data); return data; }
[ "async", "function", "fetchData", "(", "key", ",", "transformation", ",", "cacheMiss", ")", "{", "var", "data", "=", "cache", ".", "get", "(", "key", ")", ";", "if", "(", "data", ")", "{", "return", "data", ";", "}", "try", "{", "data", "=", "transformation", "(", "await", "cacheMiss", "(", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "throw", "new", "Error", "(", "'The response contains invalid data'", ")", ";", "}", "cache", ".", "put", "(", "key", ",", "data", ")", ";", "return", "data", ";", "}" ]
Tries to fetch the response from the cache and provides fallback if not found @param {string} key - Key of the data in the cache @param {function} transformation - Transformation of the data @param {function} cacheMiss - Handler in case of the data is not found in the cache @returns {*}
[ "Tries", "to", "fetch", "the", "response", "from", "the", "cache", "and", "provides", "fallback", "if", "not", "found" ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/rest_client.js#L46-L63
train
tadam313/sheet-db
src/rest_client.js
querySheetInfo
async function querySheetInfo(sheetId) { var key = util.createIdentifier('sheet_info', sheetId); return await fetchData(key, api.converter.sheetInfoResponse, () => executeRequest('sheet_info', {sheetId: sheetId}) ); }
javascript
async function querySheetInfo(sheetId) { var key = util.createIdentifier('sheet_info', sheetId); return await fetchData(key, api.converter.sheetInfoResponse, () => executeRequest('sheet_info', {sheetId: sheetId}) ); }
[ "async", "function", "querySheetInfo", "(", "sheetId", ")", "{", "var", "key", "=", "util", ".", "createIdentifier", "(", "'sheet_info'", ",", "sheetId", ")", ";", "return", "await", "fetchData", "(", "key", ",", "api", ".", "converter", ".", "sheetInfoResponse", ",", "(", ")", "=>", "executeRequest", "(", "'sheet_info'", ",", "{", "sheetId", ":", "sheetId", "}", ")", ")", ";", "}" ]
Queries the specific sheet info. @param {string} sheetId
[ "Queries", "the", "specific", "sheet", "info", "." ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/rest_client.js#L79-L85
train
tadam313/sheet-db
src/rest_client.js
createWorksheet
async function createWorksheet(sheetId, worksheetTitle, options) { options = Object.assign({ title: worksheetTitle }, options); let payload = api.converter.createWorksheetRequest(options); let response = await executeRequest('create_worksheet', { body: payload, sheetId: sheetId }); cache.clear(); // converts worksheetData to model return api.converter.workSheetInfoResponse(response); }
javascript
async function createWorksheet(sheetId, worksheetTitle, options) { options = Object.assign({ title: worksheetTitle }, options); let payload = api.converter.createWorksheetRequest(options); let response = await executeRequest('create_worksheet', { body: payload, sheetId: sheetId }); cache.clear(); // converts worksheetData to model return api.converter.workSheetInfoResponse(response); }
[ "async", "function", "createWorksheet", "(", "sheetId", ",", "worksheetTitle", ",", "options", ")", "{", "options", "=", "Object", ".", "assign", "(", "{", "title", ":", "worksheetTitle", "}", ",", "options", ")", ";", "let", "payload", "=", "api", ".", "converter", ".", "createWorksheetRequest", "(", "options", ")", ";", "let", "response", "=", "await", "executeRequest", "(", "'create_worksheet'", ",", "{", "body", ":", "payload", ",", "sheetId", ":", "sheetId", "}", ")", ";", "cache", ".", "clear", "(", ")", ";", "return", "api", ".", "converter", ".", "workSheetInfoResponse", "(", "response", ")", ";", "}" ]
Creates the specific worksheet @param {string} sheetId ID of the sheet @param {string} worksheetTitle name of the worksheet to be created @param {object} options
[ "Creates", "the", "specific", "worksheet" ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/rest_client.js#L94-L107
train
tadam313/sheet-db
src/rest_client.js
dropWorksheet
async function dropWorksheet(sheetId, worksheetId) { let response = await executeRequest('drop_worksheet', { sheetId: sheetId, worksheetId: worksheetId }); cache.clear(); return response; }
javascript
async function dropWorksheet(sheetId, worksheetId) { let response = await executeRequest('drop_worksheet', { sheetId: sheetId, worksheetId: worksheetId }); cache.clear(); return response; }
[ "async", "function", "dropWorksheet", "(", "sheetId", ",", "worksheetId", ")", "{", "let", "response", "=", "await", "executeRequest", "(", "'drop_worksheet'", ",", "{", "sheetId", ":", "sheetId", ",", "worksheetId", ":", "worksheetId", "}", ")", ";", "cache", ".", "clear", "(", ")", ";", "return", "response", ";", "}" ]
Drops the specific worksheet @param {string} sheetId @param {string} worksheetId
[ "Drops", "the", "specific", "worksheet" ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/rest_client.js#L115-L123
train
tadam313/sheet-db
src/rest_client.js
insertEntries
async function insertEntries(worksheetInfo, entries, options) { let response; let insertEntry = (entry) => { var payload = Object.assign({ body: api.converter.createEntryRequest(entry) }, worksheetInfo ); return executeRequest('create_entry', payload); }; if (options.ordered) { for (let entry of entries) { response = await insertEntry(entry); } } else { response = await Promise.all(entries.map(entry => insertEntry(entry))); } cache.clear(); return response; }
javascript
async function insertEntries(worksheetInfo, entries, options) { let response; let insertEntry = (entry) => { var payload = Object.assign({ body: api.converter.createEntryRequest(entry) }, worksheetInfo ); return executeRequest('create_entry', payload); }; if (options.ordered) { for (let entry of entries) { response = await insertEntry(entry); } } else { response = await Promise.all(entries.map(entry => insertEntry(entry))); } cache.clear(); return response; }
[ "async", "function", "insertEntries", "(", "worksheetInfo", ",", "entries", ",", "options", ")", "{", "let", "response", ";", "let", "insertEntry", "=", "(", "entry", ")", "=>", "{", "var", "payload", "=", "Object", ".", "assign", "(", "{", "body", ":", "api", ".", "converter", ".", "createEntryRequest", "(", "entry", ")", "}", ",", "worksheetInfo", ")", ";", "return", "executeRequest", "(", "'create_entry'", ",", "payload", ")", ";", "}", ";", "if", "(", "options", ".", "ordered", ")", "{", "for", "(", "let", "entry", "of", "entries", ")", "{", "response", "=", "await", "insertEntry", "(", "entry", ")", ";", "}", "}", "else", "{", "response", "=", "await", "Promise", ".", "all", "(", "entries", ".", "map", "(", "entry", "=>", "insertEntry", "(", "entry", ")", ")", ")", ";", "}", "cache", ".", "clear", "(", ")", ";", "return", "response", ";", "}" ]
Creates the specific entry @param {string} worksheetInfo @param {array} entries @param {object} options
[ "Creates", "the", "specific", "entry" ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/rest_client.js#L132-L154
train
tadam313/sheet-db
src/rest_client.js
updateEntries
async function updateEntries(worksheetInfo, entries) { let requests = entries.map(entry => { var payload = Object.assign({ body: api.converter.updateEntryRequest(entry), entityId: entry._id }, worksheetInfo ); return executeRequest('update_entry', payload); }); let response = Promise.all(requests); cache.clear(); return response; }
javascript
async function updateEntries(worksheetInfo, entries) { let requests = entries.map(entry => { var payload = Object.assign({ body: api.converter.updateEntryRequest(entry), entityId: entry._id }, worksheetInfo ); return executeRequest('update_entry', payload); }); let response = Promise.all(requests); cache.clear(); return response; }
[ "async", "function", "updateEntries", "(", "worksheetInfo", ",", "entries", ")", "{", "let", "requests", "=", "entries", ".", "map", "(", "entry", "=>", "{", "var", "payload", "=", "Object", ".", "assign", "(", "{", "body", ":", "api", ".", "converter", ".", "updateEntryRequest", "(", "entry", ")", ",", "entityId", ":", "entry", ".", "_id", "}", ",", "worksheetInfo", ")", ";", "return", "executeRequest", "(", "'update_entry'", ",", "payload", ")", ";", "}", ")", ";", "let", "response", "=", "Promise", ".", "all", "(", "requests", ")", ";", "cache", ".", "clear", "(", ")", ";", "return", "response", ";", "}" ]
Update the specified entries @param {object} worksheetInfo SheetID and worksheetID @param {array} entries
[ "Update", "the", "specified", "entries" ]
2ca1b85b8a6086a327d65b98b68b543fade84848
https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/rest_client.js#L162-L178
train