id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
55,600
peteromano/jetrunner
lib/util.js
function() { var obj = arguments[0], args = Array.prototype.slice.call(arguments, 1); function copy(destination, source) { for (var property in source) { if (source[property] && source[property].constructor && source[property].constructor === Object) { destination[property] = destination[property] || {}; copy(destination[property], source[property]); } else { destination[property] = source[property]; } } return destination; } for(var i in args) { copy(obj, args[i]); } return obj; }
javascript
function() { var obj = arguments[0], args = Array.prototype.slice.call(arguments, 1); function copy(destination, source) { for (var property in source) { if (source[property] && source[property].constructor && source[property].constructor === Object) { destination[property] = destination[property] || {}; copy(destination[property], source[property]); } else { destination[property] = source[property]; } } return destination; } for(var i in args) { copy(obj, args[i]); } return obj; }
[ "function", "(", ")", "{", "var", "obj", "=", "arguments", "[", "0", "]", ",", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "function", "copy", "(", "destination", ",", "source", ")", "{", "for", "(", "var", "property", "in", "source", ")", "{", "if", "(", "source", "[", "property", "]", "&&", "source", "[", "property", "]", ".", "constructor", "&&", "source", "[", "property", "]", ".", "constructor", "===", "Object", ")", "{", "destination", "[", "property", "]", "=", "destination", "[", "property", "]", "||", "{", "}", ";", "copy", "(", "destination", "[", "property", "]", ",", "source", "[", "property", "]", ")", ";", "}", "else", "{", "destination", "[", "property", "]", "=", "source", "[", "property", "]", ";", "}", "}", "return", "destination", ";", "}", "for", "(", "var", "i", "in", "args", ")", "{", "copy", "(", "obj", ",", "args", "[", "i", "]", ")", ";", "}", "return", "obj", ";", "}" ]
Recursively merge objects together
[ "Recursively", "merge", "objects", "together" ]
1882e0ee83d31fe1c799b42848c8c1357a62c995
https://github.com/peteromano/jetrunner/blob/1882e0ee83d31fe1c799b42848c8c1357a62c995/lib/util.js#L10-L31
55,601
peteromano/jetrunner
lib/util.js
function(proto) { function F() {} this.merge(F.prototype, proto || {}, (function() { var Events = function() {}; Events.prototype = EventEmitter.prototype; return new Events(); })()); return new F(); }
javascript
function(proto) { function F() {} this.merge(F.prototype, proto || {}, (function() { var Events = function() {}; Events.prototype = EventEmitter.prototype; return new Events(); })()); return new F(); }
[ "function", "(", "proto", ")", "{", "function", "F", "(", ")", "{", "}", "this", ".", "merge", "(", "F", ".", "prototype", ",", "proto", "||", "{", "}", ",", "(", "function", "(", ")", "{", "var", "Events", "=", "function", "(", ")", "{", "}", ";", "Events", ".", "prototype", "=", "EventEmitter", ".", "prototype", ";", "return", "new", "Events", "(", ")", ";", "}", ")", "(", ")", ")", ";", "return", "new", "F", "(", ")", ";", "}" ]
Factory for extending from EventEmitter @param {Object} proto Class definition
[ "Factory", "for", "extending", "from", "EventEmitter" ]
1882e0ee83d31fe1c799b42848c8c1357a62c995
https://github.com/peteromano/jetrunner/blob/1882e0ee83d31fe1c799b42848c8c1357a62c995/lib/util.js#L38-L46
55,602
TheRoSS/jsfilter
lib/common.js
splitByDot
function splitByDot(str) { var result = []; var s = ""; for (var i = 0; i < str.length; i++) { if (str[i] == "\\" && str[i+1] == ".") { i++; s += "."; continue; } if (str[i] == ".") { result.push(s); s = ""; continue; } s += str[i]; } if (s) { result.push(s); } return result; }
javascript
function splitByDot(str) { var result = []; var s = ""; for (var i = 0; i < str.length; i++) { if (str[i] == "\\" && str[i+1] == ".") { i++; s += "."; continue; } if (str[i] == ".") { result.push(s); s = ""; continue; } s += str[i]; } if (s) { result.push(s); } return result; }
[ "function", "splitByDot", "(", "str", ")", "{", "var", "result", "=", "[", "]", ";", "var", "s", "=", "\"\"", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "str", ".", "length", ";", "i", "++", ")", "{", "if", "(", "str", "[", "i", "]", "==", "\"\\\\\"", "&&", "str", "[", "i", "+", "1", "]", "==", "\".\"", ")", "{", "i", "++", ";", "s", "+=", "\".\"", ";", "continue", ";", "}", "if", "(", "str", "[", "i", "]", "==", "\".\"", ")", "{", "result", ".", "push", "(", "s", ")", ";", "s", "=", "\"\"", ";", "continue", ";", "}", "s", "+=", "str", "[", "i", "]", ";", "}", "if", "(", "s", ")", "{", "result", ".", "push", "(", "s", ")", ";", "}", "return", "result", ";", "}" ]
Splits dot notation selector by its components Escaped dots are ignored @param {string} str @returns {Array.<string>}
[ "Splits", "dot", "notation", "selector", "by", "its", "components", "Escaped", "dots", "are", "ignored" ]
e06e689e7ad175eb1479645c9b4e38fadc385cf5
https://github.com/TheRoSS/jsfilter/blob/e06e689e7ad175eb1479645c9b4e38fadc385cf5/lib/common.js#L35-L60
55,603
TheRoSS/jsfilter
lib/common.js
normilizeSquareBrackets
function normilizeSquareBrackets(str) { var m; while ((m = reSqrBrackets.exec(str))) { var header = m[1] ? m[1] + '.' : ''; var body = m[2].replace(/\./g, "\\."); var footer = m[3] || ''; str = header + body + footer; } return str; }
javascript
function normilizeSquareBrackets(str) { var m; while ((m = reSqrBrackets.exec(str))) { var header = m[1] ? m[1] + '.' : ''; var body = m[2].replace(/\./g, "\\."); var footer = m[3] || ''; str = header + body + footer; } return str; }
[ "function", "normilizeSquareBrackets", "(", "str", ")", "{", "var", "m", ";", "while", "(", "(", "m", "=", "reSqrBrackets", ".", "exec", "(", "str", ")", ")", ")", "{", "var", "header", "=", "m", "[", "1", "]", "?", "m", "[", "1", "]", "+", "'.'", ":", "''", ";", "var", "body", "=", "m", "[", "2", "]", ".", "replace", "(", "/", "\\.", "/", "g", ",", "\"\\\\.\"", ")", ";", "var", "footer", "=", "m", "[", "3", "]", "||", "''", ";", "str", "=", "header", "+", "body", "+", "footer", ";", "}", "return", "str", ";", "}" ]
Replaces square brackets notation by escaped dot notation @param {string} str @returns {string}
[ "Replaces", "square", "brackets", "notation", "by", "escaped", "dot", "notation" ]
e06e689e7ad175eb1479645c9b4e38fadc385cf5
https://github.com/TheRoSS/jsfilter/blob/e06e689e7ad175eb1479645c9b4e38fadc385cf5/lib/common.js#L69-L80
55,604
sydneystockholm/blog.md
lib/loaders/array.js
ArrayLoader
function ArrayLoader(posts) { var self = this; posts.forEach(function (post, index) { if (!('id' in post)) { post.id = index; } }); process.nextTick(function () { self.emit('load', posts); }); }
javascript
function ArrayLoader(posts) { var self = this; posts.forEach(function (post, index) { if (!('id' in post)) { post.id = index; } }); process.nextTick(function () { self.emit('load', posts); }); }
[ "function", "ArrayLoader", "(", "posts", ")", "{", "var", "self", "=", "this", ";", "posts", ".", "forEach", "(", "function", "(", "post", ",", "index", ")", "{", "if", "(", "!", "(", "'id'", "in", "post", ")", ")", "{", "post", ".", "id", "=", "index", ";", "}", "}", ")", ";", "process", ".", "nextTick", "(", "function", "(", ")", "{", "self", ".", "emit", "(", "'load'", ",", "posts", ")", ";", "}", ")", ";", "}" ]
Create a new array loader. @param {Array} posts
[ "Create", "a", "new", "array", "loader", "." ]
0b145fa1620cbe8b7296eb242241ee93223db9f9
https://github.com/sydneystockholm/blog.md/blob/0b145fa1620cbe8b7296eb242241ee93223db9f9/lib/loaders/array.js#L10-L20
55,605
eventEmitter/ee-mysql-schema
lib/StaticModel.js
function( options ){ options = options || {}; options.$db = cOptions.db; options.$dbName = cOptions.database; options.$model = cOptions.model; return new cOptions.cls( options ); }
javascript
function( options ){ options = options || {}; options.$db = cOptions.db; options.$dbName = cOptions.database; options.$model = cOptions.model; return new cOptions.cls( options ); }
[ "function", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "options", ".", "$db", "=", "cOptions", ".", "db", ";", "options", ".", "$dbName", "=", "cOptions", ".", "database", ";", "options", ".", "$model", "=", "cOptions", ".", "model", ";", "return", "new", "cOptions", ".", "cls", "(", "options", ")", ";", "}" ]
create a constructor proxy
[ "create", "a", "constructor", "proxy" ]
521d9e008233360d9a4bb8b9af45c10f079cd41c
https://github.com/eventEmitter/ee-mysql-schema/blob/521d9e008233360d9a4bb8b9af45c10f079cd41c/lib/StaticModel.js#L414-L422
55,606
Tictrac/grunt-i18n-linter
tasks/i18n_linter.js
report
function report(items, heading) { grunt.log.subhead(heading); if (items.length > 0) { grunt.log.error(grunt.log.wordlist(items, {separator: '\n'})); } else { grunt.log.ok(); } }
javascript
function report(items, heading) { grunt.log.subhead(heading); if (items.length > 0) { grunt.log.error(grunt.log.wordlist(items, {separator: '\n'})); } else { grunt.log.ok(); } }
[ "function", "report", "(", "items", ",", "heading", ")", "{", "grunt", ".", "log", ".", "subhead", "(", "heading", ")", ";", "if", "(", "items", ".", "length", ">", "0", ")", "{", "grunt", ".", "log", ".", "error", "(", "grunt", ".", "log", ".", "wordlist", "(", "items", ",", "{", "separator", ":", "'\\n'", "}", ")", ")", ";", "}", "else", "{", "grunt", ".", "log", ".", "ok", "(", ")", ";", "}", "}" ]
Report the status of items @param {Array} items If empty its successful @param {String} success Success message @param {String} error Error message
[ "Report", "the", "status", "of", "items" ]
7a64e19ece1cf974beb29f85ec15dec17a39c45f
https://github.com/Tictrac/grunt-i18n-linter/blob/7a64e19ece1cf974beb29f85ec15dec17a39c45f/tasks/i18n_linter.js#L35-L42
55,607
melvincarvalho/rdf-shell
lib/obj.js
obj
function obj(argv, callback) { var uri = argv[2]; if (argv[3]) { util.put(argv[2], '<> <> """' + argv[3] + '""" .', function(err, callback){ if (err) { console.error(err); } else { console.log('put value : ' + argv[3]); } }); } else { var wss = 'wss://' + uri.split('/')[2] + '/'; var s = new ws(wss, { origin: 'http://websocket.org' }); s.on('open', function open() { s.send('sub ' + uri); }); s.on('close', function close() { console.log('disconnected'); }); s.on('message', function message(data, flags) { var a = data.split(' '); if (a.length && a[0] === 'pub') { util.getAll(a[1], function(err, res) { if (err) { callback(err); } else { callback(null, res[res.length-1].object.value); } }); } }); } }
javascript
function obj(argv, callback) { var uri = argv[2]; if (argv[3]) { util.put(argv[2], '<> <> """' + argv[3] + '""" .', function(err, callback){ if (err) { console.error(err); } else { console.log('put value : ' + argv[3]); } }); } else { var wss = 'wss://' + uri.split('/')[2] + '/'; var s = new ws(wss, { origin: 'http://websocket.org' }); s.on('open', function open() { s.send('sub ' + uri); }); s.on('close', function close() { console.log('disconnected'); }); s.on('message', function message(data, flags) { var a = data.split(' '); if (a.length && a[0] === 'pub') { util.getAll(a[1], function(err, res) { if (err) { callback(err); } else { callback(null, res[res.length-1].object.value); } }); } }); } }
[ "function", "obj", "(", "argv", ",", "callback", ")", "{", "var", "uri", "=", "argv", "[", "2", "]", ";", "if", "(", "argv", "[", "3", "]", ")", "{", "util", ".", "put", "(", "argv", "[", "2", "]", ",", "'<> <> \"\"\"'", "+", "argv", "[", "3", "]", "+", "'\"\"\" .'", ",", "function", "(", "err", ",", "callback", ")", "{", "if", "(", "err", ")", "{", "console", ".", "error", "(", "err", ")", ";", "}", "else", "{", "console", ".", "log", "(", "'put value : '", "+", "argv", "[", "3", "]", ")", ";", "}", "}", ")", ";", "}", "else", "{", "var", "wss", "=", "'wss://'", "+", "uri", ".", "split", "(", "'/'", ")", "[", "2", "]", "+", "'/'", ";", "var", "s", "=", "new", "ws", "(", "wss", ",", "{", "origin", ":", "'http://websocket.org'", "}", ")", ";", "s", ".", "on", "(", "'open'", ",", "function", "open", "(", ")", "{", "s", ".", "send", "(", "'sub '", "+", "uri", ")", ";", "}", ")", ";", "s", ".", "on", "(", "'close'", ",", "function", "close", "(", ")", "{", "console", ".", "log", "(", "'disconnected'", ")", ";", "}", ")", ";", "s", ".", "on", "(", "'message'", ",", "function", "message", "(", "data", ",", "flags", ")", "{", "var", "a", "=", "data", ".", "split", "(", "' '", ")", ";", "if", "(", "a", ".", "length", "&&", "a", "[", "0", "]", "===", "'pub'", ")", "{", "util", ".", "getAll", "(", "a", "[", "1", "]", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "}", "else", "{", "callback", "(", "null", ",", "res", "[", "res", ".", "length", "-", "1", "]", ".", "object", ".", "value", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "}", "}" ]
obj gets list of files for a given container @param {String} argv[2] url @callback {bin~cb} callback
[ "obj", "gets", "list", "of", "files", "for", "a", "given", "container" ]
bf2015f6f333855e69a18ce3ec9e917bbddfb425
https://github.com/melvincarvalho/rdf-shell/blob/bf2015f6f333855e69a18ce3ec9e917bbddfb425/lib/obj.js#L13-L52
55,608
melvincarvalho/rdf-shell
lib/obj.js
bin
function bin(argv) { obj(argv, function(err, res) { if (err) { console.log(err); } else { console.log(res); } }); }
javascript
function bin(argv) { obj(argv, function(err, res) { if (err) { console.log(err); } else { console.log(res); } }); }
[ "function", "bin", "(", "argv", ")", "{", "obj", "(", "argv", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "{", "console", ".", "log", "(", "err", ")", ";", "}", "else", "{", "console", ".", "log", "(", "res", ")", ";", "}", "}", ")", ";", "}" ]
obj as a command @param {String} argv[2] login @callback {bin~cb} callback
[ "obj", "as", "a", "command" ]
bf2015f6f333855e69a18ce3ec9e917bbddfb425
https://github.com/melvincarvalho/rdf-shell/blob/bf2015f6f333855e69a18ce3ec9e917bbddfb425/lib/obj.js#L61-L69
55,609
hitchyjs/odem
lib/model/compiler.js
validateAttributes
function validateAttributes( modelName, attributes = {}, errors = [] ) { if ( !attributes || typeof attributes !== "object" || Array.isArray( attributes ) ) { throw new TypeError( "definition of attributes must be object" ); } const names = Object.keys( attributes ); const handlers = {}; for ( let i = 0, length = names.length; i < length; i++ ) { const name = names[i]; const attribute = attributes[name]; if ( !attribute.type ) { attribute.type = "string"; } const type = Types.selectByName( attribute.type ); if ( !type ) { throw new TypeError( `invalid attribute type "${attribute.type}" in attribute "${name}" of model "${modelName}"` ); } if ( type.checkDefinition( attribute, errors ) ) { handlers[name] = type; } } return handlers; }
javascript
function validateAttributes( modelName, attributes = {}, errors = [] ) { if ( !attributes || typeof attributes !== "object" || Array.isArray( attributes ) ) { throw new TypeError( "definition of attributes must be object" ); } const names = Object.keys( attributes ); const handlers = {}; for ( let i = 0, length = names.length; i < length; i++ ) { const name = names[i]; const attribute = attributes[name]; if ( !attribute.type ) { attribute.type = "string"; } const type = Types.selectByName( attribute.type ); if ( !type ) { throw new TypeError( `invalid attribute type "${attribute.type}" in attribute "${name}" of model "${modelName}"` ); } if ( type.checkDefinition( attribute, errors ) ) { handlers[name] = type; } } return handlers; }
[ "function", "validateAttributes", "(", "modelName", ",", "attributes", "=", "{", "}", ",", "errors", "=", "[", "]", ")", "{", "if", "(", "!", "attributes", "||", "typeof", "attributes", "!==", "\"object\"", "||", "Array", ".", "isArray", "(", "attributes", ")", ")", "{", "throw", "new", "TypeError", "(", "\"definition of attributes must be object\"", ")", ";", "}", "const", "names", "=", "Object", ".", "keys", "(", "attributes", ")", ";", "const", "handlers", "=", "{", "}", ";", "for", "(", "let", "i", "=", "0", ",", "length", "=", "names", ".", "length", ";", "i", "<", "length", ";", "i", "++", ")", "{", "const", "name", "=", "names", "[", "i", "]", ";", "const", "attribute", "=", "attributes", "[", "name", "]", ";", "if", "(", "!", "attribute", ".", "type", ")", "{", "attribute", ".", "type", "=", "\"string\"", ";", "}", "const", "type", "=", "Types", ".", "selectByName", "(", "attribute", ".", "type", ")", ";", "if", "(", "!", "type", ")", "{", "throw", "new", "TypeError", "(", "`", "${", "attribute", ".", "type", "}", "${", "name", "}", "${", "modelName", "}", "`", ")", ";", "}", "if", "(", "type", ".", "checkDefinition", "(", "attribute", ",", "errors", ")", ")", "{", "handlers", "[", "name", "]", "=", "type", ";", "}", "}", "return", "handlers", ";", "}" ]
Basically validates provided definitions of attributes. @note Qualification of attributes' definitions are applied to provided object and thus alter the provided set of definitions, too. @param {string} modelName name of model definition of attributes is used for @param {object<string,object>} attributes definition of attributes, might be adjusted on return @param {Error[]} errors collector of processing errors @returns {object<string,ModelType>} provided set of attribute definitions incl. optional qualifications @throws TypeError on encountering severe issues with provided definition
[ "Basically", "validates", "provided", "definitions", "of", "attributes", "." ]
28f3dc31cc3314f9109d2cac1f5f7e20dad6521b
https://github.com/hitchyjs/odem/blob/28f3dc31cc3314f9109d2cac1f5f7e20dad6521b/lib/model/compiler.js#L291-L318
55,610
hitchyjs/odem
lib/model/compiler.js
compileCoercionMap
function compileCoercionMap( attributes ) { if ( !attributes || typeof attributes !== "object" || Array.isArray( attributes ) ) { throw new TypeError( "definition of attributes must be object" ); } const coercions = {}; const attributeNames = Object.keys( attributes ); for ( let ai = 0, aLength = attributeNames.length; ai < aLength; ai++ ) { const attributeName = attributeNames[ai]; const attribute = attributes[attributeName]; ( function( name, handler, definition ) { coercions[name] = value => handler.coerce( value, definition ); } )( attributeName, Types.selectByName( attribute.type ), attribute ); } return coercions; }
javascript
function compileCoercionMap( attributes ) { if ( !attributes || typeof attributes !== "object" || Array.isArray( attributes ) ) { throw new TypeError( "definition of attributes must be object" ); } const coercions = {}; const attributeNames = Object.keys( attributes ); for ( let ai = 0, aLength = attributeNames.length; ai < aLength; ai++ ) { const attributeName = attributeNames[ai]; const attribute = attributes[attributeName]; ( function( name, handler, definition ) { coercions[name] = value => handler.coerce( value, definition ); } )( attributeName, Types.selectByName( attribute.type ), attribute ); } return coercions; }
[ "function", "compileCoercionMap", "(", "attributes", ")", "{", "if", "(", "!", "attributes", "||", "typeof", "attributes", "!==", "\"object\"", "||", "Array", ".", "isArray", "(", "attributes", ")", ")", "{", "throw", "new", "TypeError", "(", "\"definition of attributes must be object\"", ")", ";", "}", "const", "coercions", "=", "{", "}", ";", "const", "attributeNames", "=", "Object", ".", "keys", "(", "attributes", ")", ";", "for", "(", "let", "ai", "=", "0", ",", "aLength", "=", "attributeNames", ".", "length", ";", "ai", "<", "aLength", ";", "ai", "++", ")", "{", "const", "attributeName", "=", "attributeNames", "[", "ai", "]", ";", "const", "attribute", "=", "attributes", "[", "attributeName", "]", ";", "(", "function", "(", "name", ",", "handler", ",", "definition", ")", "{", "coercions", "[", "name", "]", "=", "value", "=>", "handler", ".", "coerce", "(", "value", ",", "definition", ")", ";", "}", ")", "(", "attributeName", ",", "Types", ".", "selectByName", "(", "attribute", ".", "type", ")", ",", "attribute", ")", ";", "}", "return", "coercions", ";", "}" ]
Compiles coercion handlers per attribute of model. @param {object<string,object>} attributes definition of essential attributes @returns {object<string,function(*,object):*>} map of attributes' names into either attribute's coercion handler
[ "Compiles", "coercion", "handlers", "per", "attribute", "of", "model", "." ]
28f3dc31cc3314f9109d2cac1f5f7e20dad6521b
https://github.com/hitchyjs/odem/blob/28f3dc31cc3314f9109d2cac1f5f7e20dad6521b/lib/model/compiler.js#L326-L344
55,611
hitchyjs/odem
lib/model/compiler.js
compileCoercion
function compileCoercion( attributes ) { if ( !attributes || typeof attributes !== "object" || Array.isArray( attributes ) ) { throw new TypeError( "definition of attributes must be object" ); } const attributeNames = Object.keys( attributes ); const numAttributes = attributeNames.length; const coercion = []; for ( let ai = 0; ai < numAttributes; ai++ ) { const attributeName = attributeNames[ai]; const attribute = attributes[attributeName]; const handler = Types.selectByName( attribute.type ); const { args, body } = extractBody( handler.coerce ); if ( args.length < 2 ) { throw new TypeError( `coerce() of ModelType for handling ${attribute.type} values must accept two arguments` ); } coercion[ai] = ` { let ${args[0]} = __props["${attributeName}"]; const ${args[1]} = __attrs["${attributeName}"]; { ${body.replace( ptnTrailingReturn, ( all, term ) => `__props["${attributeName}"] = ${term.trim()};` )} } } `; } // eslint-disable-next-line no-new-func return new Function( ` const __attrs = this.constructor.schema.attributes; const __props = this.properties; ${coercion.join( "" )} ` ); }
javascript
function compileCoercion( attributes ) { if ( !attributes || typeof attributes !== "object" || Array.isArray( attributes ) ) { throw new TypeError( "definition of attributes must be object" ); } const attributeNames = Object.keys( attributes ); const numAttributes = attributeNames.length; const coercion = []; for ( let ai = 0; ai < numAttributes; ai++ ) { const attributeName = attributeNames[ai]; const attribute = attributes[attributeName]; const handler = Types.selectByName( attribute.type ); const { args, body } = extractBody( handler.coerce ); if ( args.length < 2 ) { throw new TypeError( `coerce() of ModelType for handling ${attribute.type} values must accept two arguments` ); } coercion[ai] = ` { let ${args[0]} = __props["${attributeName}"]; const ${args[1]} = __attrs["${attributeName}"]; { ${body.replace( ptnTrailingReturn, ( all, term ) => `__props["${attributeName}"] = ${term.trim()};` )} } } `; } // eslint-disable-next-line no-new-func return new Function( ` const __attrs = this.constructor.schema.attributes; const __props = this.properties; ${coercion.join( "" )} ` ); }
[ "function", "compileCoercion", "(", "attributes", ")", "{", "if", "(", "!", "attributes", "||", "typeof", "attributes", "!==", "\"object\"", "||", "Array", ".", "isArray", "(", "attributes", ")", ")", "{", "throw", "new", "TypeError", "(", "\"definition of attributes must be object\"", ")", ";", "}", "const", "attributeNames", "=", "Object", ".", "keys", "(", "attributes", ")", ";", "const", "numAttributes", "=", "attributeNames", ".", "length", ";", "const", "coercion", "=", "[", "]", ";", "for", "(", "let", "ai", "=", "0", ";", "ai", "<", "numAttributes", ";", "ai", "++", ")", "{", "const", "attributeName", "=", "attributeNames", "[", "ai", "]", ";", "const", "attribute", "=", "attributes", "[", "attributeName", "]", ";", "const", "handler", "=", "Types", ".", "selectByName", "(", "attribute", ".", "type", ")", ";", "const", "{", "args", ",", "body", "}", "=", "extractBody", "(", "handler", ".", "coerce", ")", ";", "if", "(", "args", ".", "length", "<", "2", ")", "{", "throw", "new", "TypeError", "(", "`", "${", "attribute", ".", "type", "}", "`", ")", ";", "}", "coercion", "[", "ai", "]", "=", "`", "${", "args", "[", "0", "]", "}", "${", "attributeName", "}", "${", "args", "[", "1", "]", "}", "${", "attributeName", "}", "${", "body", ".", "replace", "(", "ptnTrailingReturn", ",", "(", "all", ",", "term", ")", "=>", "`", "${", "attributeName", "}", "${", "term", ".", "trim", "(", ")", "}", "`", ")", "}", "`", ";", "}", "// eslint-disable-next-line no-new-func", "return", "new", "Function", "(", "`", "${", "coercion", ".", "join", "(", "\"\"", ")", "}", "`", ")", ";", "}" ]
Creates function coercing all attributes. @param {object<string,object>} attributes definition of essential attributes @returns {function()} concatenated implementation of all defined attributes' coercion handlers
[ "Creates", "function", "coercing", "all", "attributes", "." ]
28f3dc31cc3314f9109d2cac1f5f7e20dad6521b
https://github.com/hitchyjs/odem/blob/28f3dc31cc3314f9109d2cac1f5f7e20dad6521b/lib/model/compiler.js#L352-L391
55,612
hitchyjs/odem
lib/model/compiler.js
compileValidator
function compileValidator( attributes ) { if ( !attributes || typeof attributes !== "object" || Array.isArray( attributes ) ) { throw new TypeError( "definition of attributes must be object" ); } const attributeNames = Object.keys( attributes ); const numAttributes = attributeNames.length; const validation = []; for ( let ai = 0; ai < numAttributes; ai++ ) { const attributeName = attributeNames[ai]; const attribute = attributes[attributeName]; const handler = Types.selectByName( attribute.type ); const { args, body } = extractBody( handler.isValid ); if ( args.length < 4 ) { throw new TypeError( `isValid() of ModelType for handling ${attribute.type} values must accept four arguments` ); } validation[ai] = ` { const ${args[0]} = "${attributeName}"; let ${args[1]} = __props["${attributeName}"]; const ${args[2]} = __attrs["${attributeName}"]; const ${args[3]} = __errors; { ${body} } } `; } // eslint-disable-next-line no-new-func return new Function( ` const __attrs = this.constructor.schema.attributes; const __props = this.properties; const __errors = []; ${validation.join( "" )} return __errors; ` ); }
javascript
function compileValidator( attributes ) { if ( !attributes || typeof attributes !== "object" || Array.isArray( attributes ) ) { throw new TypeError( "definition of attributes must be object" ); } const attributeNames = Object.keys( attributes ); const numAttributes = attributeNames.length; const validation = []; for ( let ai = 0; ai < numAttributes; ai++ ) { const attributeName = attributeNames[ai]; const attribute = attributes[attributeName]; const handler = Types.selectByName( attribute.type ); const { args, body } = extractBody( handler.isValid ); if ( args.length < 4 ) { throw new TypeError( `isValid() of ModelType for handling ${attribute.type} values must accept four arguments` ); } validation[ai] = ` { const ${args[0]} = "${attributeName}"; let ${args[1]} = __props["${attributeName}"]; const ${args[2]} = __attrs["${attributeName}"]; const ${args[3]} = __errors; { ${body} } } `; } // eslint-disable-next-line no-new-func return new Function( ` const __attrs = this.constructor.schema.attributes; const __props = this.properties; const __errors = []; ${validation.join( "" )} return __errors; ` ); }
[ "function", "compileValidator", "(", "attributes", ")", "{", "if", "(", "!", "attributes", "||", "typeof", "attributes", "!==", "\"object\"", "||", "Array", ".", "isArray", "(", "attributes", ")", ")", "{", "throw", "new", "TypeError", "(", "\"definition of attributes must be object\"", ")", ";", "}", "const", "attributeNames", "=", "Object", ".", "keys", "(", "attributes", ")", ";", "const", "numAttributes", "=", "attributeNames", ".", "length", ";", "const", "validation", "=", "[", "]", ";", "for", "(", "let", "ai", "=", "0", ";", "ai", "<", "numAttributes", ";", "ai", "++", ")", "{", "const", "attributeName", "=", "attributeNames", "[", "ai", "]", ";", "const", "attribute", "=", "attributes", "[", "attributeName", "]", ";", "const", "handler", "=", "Types", ".", "selectByName", "(", "attribute", ".", "type", ")", ";", "const", "{", "args", ",", "body", "}", "=", "extractBody", "(", "handler", ".", "isValid", ")", ";", "if", "(", "args", ".", "length", "<", "4", ")", "{", "throw", "new", "TypeError", "(", "`", "${", "attribute", ".", "type", "}", "`", ")", ";", "}", "validation", "[", "ai", "]", "=", "`", "${", "args", "[", "0", "]", "}", "${", "attributeName", "}", "${", "args", "[", "1", "]", "}", "${", "attributeName", "}", "${", "args", "[", "2", "]", "}", "${", "attributeName", "}", "${", "args", "[", "3", "]", "}", "${", "body", "}", "`", ";", "}", "// eslint-disable-next-line no-new-func", "return", "new", "Function", "(", "`", "${", "validation", ".", "join", "(", "\"\"", ")", "}", "`", ")", ";", "}" ]
Creates validator function assessing all defined attributes of a model. @param {object<string,object>} attributes definition of essential attributes @returns {function():Error[]} concatenated implementation of all defined attributes' validation handlers
[ "Creates", "validator", "function", "assessing", "all", "defined", "attributes", "of", "a", "model", "." ]
28f3dc31cc3314f9109d2cac1f5f7e20dad6521b
https://github.com/hitchyjs/odem/blob/28f3dc31cc3314f9109d2cac1f5f7e20dad6521b/lib/model/compiler.js#L399-L443
55,613
hitchyjs/odem
lib/model/compiler.js
compileDeserializer
function compileDeserializer( attributes ) { if ( !attributes || typeof attributes !== "object" || Array.isArray( attributes ) ) { throw new TypeError( "definition of attributes must be object" ); } const attributeNames = Object.keys( attributes ); const numAttributes = attributeNames.length; const deserialization = new Array( 2 * numAttributes ); let write = 0; for ( let ai = 0; ai < numAttributes; ai++ ) { const attributeName = attributeNames[ai]; const attribute = attributes[attributeName]; const handler = Types.selectByName( attribute.type ); let sourceName; // append deserialize() method of current attribute's type handler { const { args, body } = extractBody( handler.deserialize ); if ( args.length < 1 ) { throw new TypeError( `deserialize() of ModelType for handling ${attribute.type} values must accept one argument` ); } if ( body.replace( ptnTrailingReturn, "" ).trim().length ) { sourceName = "$$d"; deserialization[write++] = ` { let ${args[0]} = $$s["${attributeName}"]; { ${body.replace( ptnTrailingReturn, ( all, term ) => `$$d["${attributeName}"] = ${term.trim()};` )} } } `; } else { sourceName = "$$s"; } } // append coerce() method of current attribute's type handler { const { args, body } = extractBody( handler.coerce ); if ( args.length < 2 ) { throw new TypeError( `coerce() of ModelType for handling ${attribute.type} values must accept two arguments` ); } deserialization[write++] = ` { let ${args[0]} = ${sourceName}["${attributeName}"]; const ${args[1]} = $$attrs["${attributeName}"]; { ${body.replace( ptnTrailingReturn, ( all, term ) => `$$d["${attributeName}"] = ${term.trim()};` )} } } `; } } deserialization.splice( write ); // eslint-disable-next-line no-new-func return new Function( "$$input", "$$attrs", ` if ( !$$attrs || typeof $$attrs !== "object" ) { throw new TypeError( "missing definition of attributes required for deserialization" ); } const $$s = $$input && typeof $$input === "object" ? $$input : {}; const $$d = {}; ${deserialization.join( "" )} return $$d; ` ); }
javascript
function compileDeserializer( attributes ) { if ( !attributes || typeof attributes !== "object" || Array.isArray( attributes ) ) { throw new TypeError( "definition of attributes must be object" ); } const attributeNames = Object.keys( attributes ); const numAttributes = attributeNames.length; const deserialization = new Array( 2 * numAttributes ); let write = 0; for ( let ai = 0; ai < numAttributes; ai++ ) { const attributeName = attributeNames[ai]; const attribute = attributes[attributeName]; const handler = Types.selectByName( attribute.type ); let sourceName; // append deserialize() method of current attribute's type handler { const { args, body } = extractBody( handler.deserialize ); if ( args.length < 1 ) { throw new TypeError( `deserialize() of ModelType for handling ${attribute.type} values must accept one argument` ); } if ( body.replace( ptnTrailingReturn, "" ).trim().length ) { sourceName = "$$d"; deserialization[write++] = ` { let ${args[0]} = $$s["${attributeName}"]; { ${body.replace( ptnTrailingReturn, ( all, term ) => `$$d["${attributeName}"] = ${term.trim()};` )} } } `; } else { sourceName = "$$s"; } } // append coerce() method of current attribute's type handler { const { args, body } = extractBody( handler.coerce ); if ( args.length < 2 ) { throw new TypeError( `coerce() of ModelType for handling ${attribute.type} values must accept two arguments` ); } deserialization[write++] = ` { let ${args[0]} = ${sourceName}["${attributeName}"]; const ${args[1]} = $$attrs["${attributeName}"]; { ${body.replace( ptnTrailingReturn, ( all, term ) => `$$d["${attributeName}"] = ${term.trim()};` )} } } `; } } deserialization.splice( write ); // eslint-disable-next-line no-new-func return new Function( "$$input", "$$attrs", ` if ( !$$attrs || typeof $$attrs !== "object" ) { throw new TypeError( "missing definition of attributes required for deserialization" ); } const $$s = $$input && typeof $$input === "object" ? $$input : {}; const $$d = {}; ${deserialization.join( "" )} return $$d; ` ); }
[ "function", "compileDeserializer", "(", "attributes", ")", "{", "if", "(", "!", "attributes", "||", "typeof", "attributes", "!==", "\"object\"", "||", "Array", ".", "isArray", "(", "attributes", ")", ")", "{", "throw", "new", "TypeError", "(", "\"definition of attributes must be object\"", ")", ";", "}", "const", "attributeNames", "=", "Object", ".", "keys", "(", "attributes", ")", ";", "const", "numAttributes", "=", "attributeNames", ".", "length", ";", "const", "deserialization", "=", "new", "Array", "(", "2", "*", "numAttributes", ")", ";", "let", "write", "=", "0", ";", "for", "(", "let", "ai", "=", "0", ";", "ai", "<", "numAttributes", ";", "ai", "++", ")", "{", "const", "attributeName", "=", "attributeNames", "[", "ai", "]", ";", "const", "attribute", "=", "attributes", "[", "attributeName", "]", ";", "const", "handler", "=", "Types", ".", "selectByName", "(", "attribute", ".", "type", ")", ";", "let", "sourceName", ";", "// append deserialize() method of current attribute's type handler", "{", "const", "{", "args", ",", "body", "}", "=", "extractBody", "(", "handler", ".", "deserialize", ")", ";", "if", "(", "args", ".", "length", "<", "1", ")", "{", "throw", "new", "TypeError", "(", "`", "${", "attribute", ".", "type", "}", "`", ")", ";", "}", "if", "(", "body", ".", "replace", "(", "ptnTrailingReturn", ",", "\"\"", ")", ".", "trim", "(", ")", ".", "length", ")", "{", "sourceName", "=", "\"$$d\"", ";", "deserialization", "[", "write", "++", "]", "=", "`", "${", "args", "[", "0", "]", "}", "${", "attributeName", "}", "${", "body", ".", "replace", "(", "ptnTrailingReturn", ",", "(", "all", ",", "term", ")", "=>", "`", "${", "attributeName", "}", "${", "term", ".", "trim", "(", ")", "}", "`", ")", "}", "`", ";", "}", "else", "{", "sourceName", "=", "\"$$s\"", ";", "}", "}", "// append coerce() method of current attribute's type handler", "{", "const", "{", "args", ",", "body", "}", "=", "extractBody", "(", "handler", ".", "coerce", ")", ";", "if", "(", "args", ".", "length", "<", "2", ")", "{", "throw", "new", "TypeError", "(", "`", "${", "attribute", ".", "type", "}", "`", ")", ";", "}", "deserialization", "[", "write", "++", "]", "=", "`", "${", "args", "[", "0", "]", "}", "${", "sourceName", "}", "${", "attributeName", "}", "${", "args", "[", "1", "]", "}", "${", "attributeName", "}", "${", "body", ".", "replace", "(", "ptnTrailingReturn", ",", "(", "all", ",", "term", ")", "=>", "`", "${", "attributeName", "}", "${", "term", ".", "trim", "(", ")", "}", "`", ")", "}", "`", ";", "}", "}", "deserialization", ".", "splice", "(", "write", ")", ";", "// eslint-disable-next-line no-new-func", "return", "new", "Function", "(", "\"$$input\"", ",", "\"$$attrs\"", ",", "`", "${", "deserialization", ".", "join", "(", "\"\"", ")", "}", "`", ")", ";", "}" ]
Creates function de-serializing and coercing all attributes in a provided record. This method is creating function resulting from concatenating methods `deserialize()` and `coerce()` of every attribute's type handler. @param {object<string,object>} attributes definition of essential attributes @returns {function(object):object} function mapping some provided record into record of de-serialized attribute values
[ "Creates", "function", "de", "-", "serializing", "and", "coercing", "all", "attributes", "in", "a", "provided", "record", "." ]
28f3dc31cc3314f9109d2cac1f5f7e20dad6521b
https://github.com/hitchyjs/odem/blob/28f3dc31cc3314f9109d2cac1f5f7e20dad6521b/lib/model/compiler.js#L503-L578
55,614
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/language/plugin.js
function( editor ) { var elementPath = editor.elementPath(), activePath = elementPath && elementPath.elements, pathMember, ret; // IE8: upon initialization if there is no path elementPath() returns null. if ( elementPath ) { for ( var i = 0; i < activePath.length; i++ ) { pathMember = activePath[ i ]; if ( !ret && pathMember.getName() == 'span' && pathMember.hasAttribute( 'dir' ) && pathMember.hasAttribute( 'lang' ) ) ret = pathMember; } } return ret; }
javascript
function( editor ) { var elementPath = editor.elementPath(), activePath = elementPath && elementPath.elements, pathMember, ret; // IE8: upon initialization if there is no path elementPath() returns null. if ( elementPath ) { for ( var i = 0; i < activePath.length; i++ ) { pathMember = activePath[ i ]; if ( !ret && pathMember.getName() == 'span' && pathMember.hasAttribute( 'dir' ) && pathMember.hasAttribute( 'lang' ) ) ret = pathMember; } } return ret; }
[ "function", "(", "editor", ")", "{", "var", "elementPath", "=", "editor", ".", "elementPath", "(", ")", ",", "activePath", "=", "elementPath", "&&", "elementPath", ".", "elements", ",", "pathMember", ",", "ret", ";", "// IE8: upon initialization if there is no path elementPath() returns null.\r", "if", "(", "elementPath", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "activePath", ".", "length", ";", "i", "++", ")", "{", "pathMember", "=", "activePath", "[", "i", "]", ";", "if", "(", "!", "ret", "&&", "pathMember", ".", "getName", "(", ")", "==", "'span'", "&&", "pathMember", ".", "hasAttribute", "(", "'dir'", ")", "&&", "pathMember", ".", "hasAttribute", "(", "'lang'", ")", ")", "ret", "=", "pathMember", ";", "}", "}", "return", "ret", ";", "}" ]
Gets the first language element for the current editor selection. @param {CKEDITOR.editor} editor @returns {CKEDITOR.dom.element} The language element, if any.
[ "Gets", "the", "first", "language", "element", "for", "the", "current", "editor", "selection", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/language/plugin.js#L127-L143
55,615
palanik/restpress
index.js
function(actionName) { self[actionName] = function() { var args = arguments; self._stack.push({action : actionName, args : args}); return self; }; }
javascript
function(actionName) { self[actionName] = function() { var args = arguments; self._stack.push({action : actionName, args : args}); return self; }; }
[ "function", "(", "actionName", ")", "{", "self", "[", "actionName", "]", "=", "function", "(", ")", "{", "var", "args", "=", "arguments", ";", "self", ".", "_stack", ".", "push", "(", "{", "action", ":", "actionName", ",", "args", ":", "args", "}", ")", ";", "return", "self", ";", "}", ";", "}" ]
Kick the can down the road for app to pick it up later
[ "Kick", "the", "can", "down", "the", "road", "for", "app", "to", "pick", "it", "up", "later" ]
4c01cc95f36f383ce47a0f80f0c2129a5f4b055c
https://github.com/palanik/restpress/blob/4c01cc95f36f383ce47a0f80f0c2129a5f4b055c/index.js#L96-L102
55,616
palanik/restpress
index.js
function(actionName, action, resourcePath) { // prefix function to set rest values var identify = function(req, res, next) { res.set('XX-Powered-By', 'Restpress'); req.resource = self; req.actionName = actionName; req.action = action; next(); }; self[actionName] = function() { if (identify) { // insert identify as second argument // This is to be done only once [].unshift.call(arguments, identify); identify = null; } // insert actionPath as first argument [].unshift.call(arguments, resourcePath + action.route); // Hack for restify where 'delete' method is 'del' var appMethod = action.method; if (appMethod == 'delete' && typeof self.app[appMethod] !== 'function' && typeof self.app['del'] === 'function') { appMethod = 'del'; } // Call express app VERB function self.app[appMethod].apply(self.app, arguments); // return this for chaining return self; }; }
javascript
function(actionName, action, resourcePath) { // prefix function to set rest values var identify = function(req, res, next) { res.set('XX-Powered-By', 'Restpress'); req.resource = self; req.actionName = actionName; req.action = action; next(); }; self[actionName] = function() { if (identify) { // insert identify as second argument // This is to be done only once [].unshift.call(arguments, identify); identify = null; } // insert actionPath as first argument [].unshift.call(arguments, resourcePath + action.route); // Hack for restify where 'delete' method is 'del' var appMethod = action.method; if (appMethod == 'delete' && typeof self.app[appMethod] !== 'function' && typeof self.app['del'] === 'function') { appMethod = 'del'; } // Call express app VERB function self.app[appMethod].apply(self.app, arguments); // return this for chaining return self; }; }
[ "function", "(", "actionName", ",", "action", ",", "resourcePath", ")", "{", "// prefix function to set rest values", "var", "identify", "=", "function", "(", "req", ",", "res", ",", "next", ")", "{", "res", ".", "set", "(", "'XX-Powered-By'", ",", "'Restpress'", ")", ";", "req", ".", "resource", "=", "self", ";", "req", ".", "actionName", "=", "actionName", ";", "req", ".", "action", "=", "action", ";", "next", "(", ")", ";", "}", ";", "self", "[", "actionName", "]", "=", "function", "(", ")", "{", "if", "(", "identify", ")", "{", "// insert identify as second argument", "// This is to be done only once", "[", "]", ".", "unshift", ".", "call", "(", "arguments", ",", "identify", ")", ";", "identify", "=", "null", ";", "}", "// insert actionPath as first argument", "[", "]", ".", "unshift", ".", "call", "(", "arguments", ",", "resourcePath", "+", "action", ".", "route", ")", ";", "// Hack for restify where 'delete' method is 'del'", "var", "appMethod", "=", "action", ".", "method", ";", "if", "(", "appMethod", "==", "'delete'", "&&", "typeof", "self", ".", "app", "[", "appMethod", "]", "!==", "'function'", "&&", "typeof", "self", ".", "app", "[", "'del'", "]", "===", "'function'", ")", "{", "appMethod", "=", "'del'", ";", "}", "// Call express app VERB function", "self", ".", "app", "[", "appMethod", "]", ".", "apply", "(", "self", ".", "app", ",", "arguments", ")", ";", "// return this for chaining", "return", "self", ";", "}", ";", "}" ]
Re-Create methods working via app for known actions
[ "Re", "-", "Create", "methods", "working", "via", "app", "for", "known", "actions" ]
4c01cc95f36f383ce47a0f80f0c2129a5f4b055c
https://github.com/palanik/restpress/blob/4c01cc95f36f383ce47a0f80f0c2129a5f4b055c/index.js#L161-L196
55,617
palanik/restpress
index.js
function(req, res, next) { res.set('XX-Powered-By', 'Restpress'); req.resource = self; req.actionName = actionName; req.action = action; next(); }
javascript
function(req, res, next) { res.set('XX-Powered-By', 'Restpress'); req.resource = self; req.actionName = actionName; req.action = action; next(); }
[ "function", "(", "req", ",", "res", ",", "next", ")", "{", "res", ".", "set", "(", "'XX-Powered-By'", ",", "'Restpress'", ")", ";", "req", ".", "resource", "=", "self", ";", "req", ".", "actionName", "=", "actionName", ";", "req", ".", "action", "=", "action", ";", "next", "(", ")", ";", "}" ]
prefix function to set rest values
[ "prefix", "function", "to", "set", "rest", "values" ]
4c01cc95f36f383ce47a0f80f0c2129a5f4b055c
https://github.com/palanik/restpress/blob/4c01cc95f36f383ce47a0f80f0c2129a5f4b055c/index.js#L163-L169
55,618
christophercrouzet/pillr
lib/components/source.js
populateStack
function populateStack(stack, rootPath, files, callback) { stack.unshift(...files .filter(file => file.stats.isDirectory()) .map(file => path.join(rootPath, file.path))); async.nextTick(callback, null, files); }
javascript
function populateStack(stack, rootPath, files, callback) { stack.unshift(...files .filter(file => file.stats.isDirectory()) .map(file => path.join(rootPath, file.path))); async.nextTick(callback, null, files); }
[ "function", "populateStack", "(", "stack", ",", "rootPath", ",", "files", ",", "callback", ")", "{", "stack", ".", "unshift", "(", "...", "files", ".", "filter", "(", "file", "=>", "file", ".", "stats", ".", "isDirectory", "(", ")", ")", ".", "map", "(", "file", "=>", "path", ".", "join", "(", "rootPath", ",", "file", ".", "path", ")", ")", ")", ";", "async", ".", "nextTick", "(", "callback", ",", "null", ",", "files", ")", ";", "}" ]
Add subdirectories to the given stack.
[ "Add", "subdirectories", "to", "the", "given", "stack", "." ]
411ccd344a03478776c4e8d2e2f9bdc45dc8ee45
https://github.com/christophercrouzet/pillr/blob/411ccd344a03478776c4e8d2e2f9bdc45dc8ee45/lib/components/source.js#L11-L16
55,619
christophercrouzet/pillr
lib/components/source.js
processStackItem
function processStackItem(out, stack, rootPath, userFilter, readMode) { // Initialize a new file object. const initFile = (dirPath) => { return (fileName, callback) => { const filePath = path.join(dirPath, fileName); fs.stat(filePath, (error, stats) => { async.nextTick(callback, error, { path: path.relative(rootPath, filePath), stats, }); }); }; }; // Filter supported files. const filterSupported = () => { return (file, callback) => { const keep = file.stats.isFile() || file.stats.isDirectory(); async.nextTick(callback, null, keep); }; }; // Filter output files. const filterOutput = () => { return (file, callback) => { const keep = file.stats.isFile() && userFilter(file); async.nextTick(callback, null, keep); }; }; // Read a file's data. const readData = () => { return (file, callback) => { const filePath = path.join(rootPath, file.path); read(filePath, readMode, (error, data) => { async.nextTick(callback, error, Object.assign({}, file, { data })); }); }; }; return (callback) => { const dirPath = stack.shift(); async.waterfall([ cb => fs.readdir(dirPath, cb), (fileNames, cb) => async.map(fileNames, initFile(dirPath), cb), (files, cb) => async.filter(files, filterSupported(), cb), (files, cb) => populateStack(stack, rootPath, files, cb), (files, cb) => async.filter(files, filterOutput(), cb), (files, cb) => async.map(files, readData(), cb), ], (error, result) => { if (error) { async.nextTick(callback, error); return; } out.push(...result); async.nextTick(callback, null); }); }; }
javascript
function processStackItem(out, stack, rootPath, userFilter, readMode) { // Initialize a new file object. const initFile = (dirPath) => { return (fileName, callback) => { const filePath = path.join(dirPath, fileName); fs.stat(filePath, (error, stats) => { async.nextTick(callback, error, { path: path.relative(rootPath, filePath), stats, }); }); }; }; // Filter supported files. const filterSupported = () => { return (file, callback) => { const keep = file.stats.isFile() || file.stats.isDirectory(); async.nextTick(callback, null, keep); }; }; // Filter output files. const filterOutput = () => { return (file, callback) => { const keep = file.stats.isFile() && userFilter(file); async.nextTick(callback, null, keep); }; }; // Read a file's data. const readData = () => { return (file, callback) => { const filePath = path.join(rootPath, file.path); read(filePath, readMode, (error, data) => { async.nextTick(callback, error, Object.assign({}, file, { data })); }); }; }; return (callback) => { const dirPath = stack.shift(); async.waterfall([ cb => fs.readdir(dirPath, cb), (fileNames, cb) => async.map(fileNames, initFile(dirPath), cb), (files, cb) => async.filter(files, filterSupported(), cb), (files, cb) => populateStack(stack, rootPath, files, cb), (files, cb) => async.filter(files, filterOutput(), cb), (files, cb) => async.map(files, readData(), cb), ], (error, result) => { if (error) { async.nextTick(callback, error); return; } out.push(...result); async.nextTick(callback, null); }); }; }
[ "function", "processStackItem", "(", "out", ",", "stack", ",", "rootPath", ",", "userFilter", ",", "readMode", ")", "{", "// Initialize a new file object.", "const", "initFile", "=", "(", "dirPath", ")", "=>", "{", "return", "(", "fileName", ",", "callback", ")", "=>", "{", "const", "filePath", "=", "path", ".", "join", "(", "dirPath", ",", "fileName", ")", ";", "fs", ".", "stat", "(", "filePath", ",", "(", "error", ",", "stats", ")", "=>", "{", "async", ".", "nextTick", "(", "callback", ",", "error", ",", "{", "path", ":", "path", ".", "relative", "(", "rootPath", ",", "filePath", ")", ",", "stats", ",", "}", ")", ";", "}", ")", ";", "}", ";", "}", ";", "// Filter supported files.", "const", "filterSupported", "=", "(", ")", "=>", "{", "return", "(", "file", ",", "callback", ")", "=>", "{", "const", "keep", "=", "file", ".", "stats", ".", "isFile", "(", ")", "||", "file", ".", "stats", ".", "isDirectory", "(", ")", ";", "async", ".", "nextTick", "(", "callback", ",", "null", ",", "keep", ")", ";", "}", ";", "}", ";", "// Filter output files.", "const", "filterOutput", "=", "(", ")", "=>", "{", "return", "(", "file", ",", "callback", ")", "=>", "{", "const", "keep", "=", "file", ".", "stats", ".", "isFile", "(", ")", "&&", "userFilter", "(", "file", ")", ";", "async", ".", "nextTick", "(", "callback", ",", "null", ",", "keep", ")", ";", "}", ";", "}", ";", "// Read a file's data.", "const", "readData", "=", "(", ")", "=>", "{", "return", "(", "file", ",", "callback", ")", "=>", "{", "const", "filePath", "=", "path", ".", "join", "(", "rootPath", ",", "file", ".", "path", ")", ";", "read", "(", "filePath", ",", "readMode", ",", "(", "error", ",", "data", ")", "=>", "{", "async", ".", "nextTick", "(", "callback", ",", "error", ",", "Object", ".", "assign", "(", "{", "}", ",", "file", ",", "{", "data", "}", ")", ")", ";", "}", ")", ";", "}", ";", "}", ";", "return", "(", "callback", ")", "=>", "{", "const", "dirPath", "=", "stack", ".", "shift", "(", ")", ";", "async", ".", "waterfall", "(", "[", "cb", "=>", "fs", ".", "readdir", "(", "dirPath", ",", "cb", ")", ",", "(", "fileNames", ",", "cb", ")", "=>", "async", ".", "map", "(", "fileNames", ",", "initFile", "(", "dirPath", ")", ",", "cb", ")", ",", "(", "files", ",", "cb", ")", "=>", "async", ".", "filter", "(", "files", ",", "filterSupported", "(", ")", ",", "cb", ")", ",", "(", "files", ",", "cb", ")", "=>", "populateStack", "(", "stack", ",", "rootPath", ",", "files", ",", "cb", ")", ",", "(", "files", ",", "cb", ")", "=>", "async", ".", "filter", "(", "files", ",", "filterOutput", "(", ")", ",", "cb", ")", ",", "(", "files", ",", "cb", ")", "=>", "async", ".", "map", "(", "files", ",", "readData", "(", ")", ",", "cb", ")", ",", "]", ",", "(", "error", ",", "result", ")", "=>", "{", "if", "(", "error", ")", "{", "async", ".", "nextTick", "(", "callback", ",", "error", ")", ";", "return", ";", "}", "out", ".", "push", "(", "...", "result", ")", ";", "async", ".", "nextTick", "(", "callback", ",", "null", ")", ";", "}", ")", ";", "}", ";", "}" ]
Process a single stack item.
[ "Process", "a", "single", "stack", "item", "." ]
411ccd344a03478776c4e8d2e2f9bdc45dc8ee45
https://github.com/christophercrouzet/pillr/blob/411ccd344a03478776c4e8d2e2f9bdc45dc8ee45/lib/components/source.js#L20-L79
55,620
jkroso/string-tween
index.js
tween
function tween(a, b){ var string = [] var keys = [] var from = [] var to = [] var cursor = 0 var m while (m = number.exec(b)) { if (m.index > cursor) string.push(b.slice(cursor, m.index)) to.push(Number(m[0])) keys.push(string.length) string.push(null) cursor = number.lastIndex } if (cursor < b.length) string.push(b.slice(cursor)) while (m = number.exec(a)) from.push(Number(m[0])) return function frame(n){ var i = keys.length while (i--) string[keys[i]] = from[i] + (to[i] - from[i]) * n return string.join('') } }
javascript
function tween(a, b){ var string = [] var keys = [] var from = [] var to = [] var cursor = 0 var m while (m = number.exec(b)) { if (m.index > cursor) string.push(b.slice(cursor, m.index)) to.push(Number(m[0])) keys.push(string.length) string.push(null) cursor = number.lastIndex } if (cursor < b.length) string.push(b.slice(cursor)) while (m = number.exec(a)) from.push(Number(m[0])) return function frame(n){ var i = keys.length while (i--) string[keys[i]] = from[i] + (to[i] - from[i]) * n return string.join('') } }
[ "function", "tween", "(", "a", ",", "b", ")", "{", "var", "string", "=", "[", "]", "var", "keys", "=", "[", "]", "var", "from", "=", "[", "]", "var", "to", "=", "[", "]", "var", "cursor", "=", "0", "var", "m", "while", "(", "m", "=", "number", ".", "exec", "(", "b", ")", ")", "{", "if", "(", "m", ".", "index", ">", "cursor", ")", "string", ".", "push", "(", "b", ".", "slice", "(", "cursor", ",", "m", ".", "index", ")", ")", "to", ".", "push", "(", "Number", "(", "m", "[", "0", "]", ")", ")", "keys", ".", "push", "(", "string", ".", "length", ")", "string", ".", "push", "(", "null", ")", "cursor", "=", "number", ".", "lastIndex", "}", "if", "(", "cursor", "<", "b", ".", "length", ")", "string", ".", "push", "(", "b", ".", "slice", "(", "cursor", ")", ")", "while", "(", "m", "=", "number", ".", "exec", "(", "a", ")", ")", "from", ".", "push", "(", "Number", "(", "m", "[", "0", "]", ")", ")", "return", "function", "frame", "(", "n", ")", "{", "var", "i", "=", "keys", ".", "length", "while", "(", "i", "--", ")", "string", "[", "keys", "[", "i", "]", "]", "=", "from", "[", "i", "]", "+", "(", "to", "[", "i", "]", "-", "from", "[", "i", "]", ")", "*", "n", "return", "string", ".", "join", "(", "''", ")", "}", "}" ]
create a tween generator from `a` to `b` @param {String} a @param {String} b @return {Function}
[ "create", "a", "tween", "generator", "from", "a", "to", "b" ]
8a74c87659f58ea4b6e152997e309bd7e57ed2a4
https://github.com/jkroso/string-tween/blob/8a74c87659f58ea4b6e152997e309bd7e57ed2a4/index.js#L19-L43
55,621
Biyaheroes/bh-mj-issue
dependency-mjml.support.js
safeEndingTags
function safeEndingTags(content) { var MJElements = [].concat(WHITELISTED_GLOBAL_TAG); (0, _forEach2.default)(_extends({}, _MJMLElementsCollection2.default, _MJMLHead2.default), function (element, name) { var tagName = element.tagName || name; MJElements.push(tagName); }); var safeContent = (0, _parseAttributes2.default)(MJElements, content.replace(/\$/g, '&#36;')); (0, _concat2.default)(_MJMLElementsCollection.endingTags, _MJMLHead.endingTags).forEach(function (tag) { safeContent = safeContent.replace(regexTag(tag), _dom2.default.replaceContentByCdata(tag)); }); return safeContent; }
javascript
function safeEndingTags(content) { var MJElements = [].concat(WHITELISTED_GLOBAL_TAG); (0, _forEach2.default)(_extends({}, _MJMLElementsCollection2.default, _MJMLHead2.default), function (element, name) { var tagName = element.tagName || name; MJElements.push(tagName); }); var safeContent = (0, _parseAttributes2.default)(MJElements, content.replace(/\$/g, '&#36;')); (0, _concat2.default)(_MJMLElementsCollection.endingTags, _MJMLHead.endingTags).forEach(function (tag) { safeContent = safeContent.replace(regexTag(tag), _dom2.default.replaceContentByCdata(tag)); }); return safeContent; }
[ "function", "safeEndingTags", "(", "content", ")", "{", "var", "MJElements", "=", "[", "]", ".", "concat", "(", "WHITELISTED_GLOBAL_TAG", ")", ";", "(", "0", ",", "_forEach2", ".", "default", ")", "(", "_extends", "(", "{", "}", ",", "_MJMLElementsCollection2", ".", "default", ",", "_MJMLHead2", ".", "default", ")", ",", "function", "(", "element", ",", "name", ")", "{", "var", "tagName", "=", "element", ".", "tagName", "||", "name", ";", "MJElements", ".", "push", "(", "tagName", ")", ";", "}", ")", ";", "var", "safeContent", "=", "(", "0", ",", "_parseAttributes2", ".", "default", ")", "(", "MJElements", ",", "content", ".", "replace", "(", "/", "\\$", "/", "g", ",", "'&#36;'", ")", ")", ";", "(", "0", ",", "_concat2", ".", "default", ")", "(", "_MJMLElementsCollection", ".", "endingTags", ",", "_MJMLHead", ".", "endingTags", ")", ".", "forEach", "(", "function", "(", "tag", ")", "{", "safeContent", "=", "safeContent", ".", "replace", "(", "regexTag", "(", "tag", ")", ",", "_dom2", ".", "default", ".", "replaceContentByCdata", "(", "tag", ")", ")", ";", "}", ")", ";", "return", "safeContent", ";", "}" ]
Avoid htmlparser to parse ending tags
[ "Avoid", "htmlparser", "to", "parse", "ending", "tags" ]
878be949e0a142139e75f579bdaed2cb43511008
https://github.com/Biyaheroes/bh-mj-issue/blob/878be949e0a142139e75f579bdaed2cb43511008/dependency-mjml.support.js#L623-L639
55,622
Biyaheroes/bh-mj-issue
dependency-mjml.support.js
mjmlElementParser
function mjmlElementParser(elem, content) { if (!elem) { throw new _Error.NullElementError('Null element found in mjmlElementParser'); } var findLine = content.substr(0, elem.startIndex).match(/\n/g); var lineNumber = findLine ? findLine.length + 1 : 1; var tagName = elem.tagName.toLowerCase(); var attributes = (0, _mapValues2.default)(_dom2.default.getAttributes(elem), function (val) { return decodeURIComponent(val); }); var element = { tagName: tagName, attributes: attributes, lineNumber: lineNumber }; if (_MJMLElementsCollection.endingTags.indexOf(tagName) !== -1) { var $local = _dom2.default.parseXML(elem); element.content = (0, _removeCDATA2.default)($local(tagName).html().trim()); } else { var children = _dom2.default.getChildren(elem); element.children = children ? (0, _compact2.default)((0, _filter2.default)(children, function (child) { return child.tagName; }).map(function (child) { return mjmlElementParser(child, content); })) : []; } return element; }
javascript
function mjmlElementParser(elem, content) { if (!elem) { throw new _Error.NullElementError('Null element found in mjmlElementParser'); } var findLine = content.substr(0, elem.startIndex).match(/\n/g); var lineNumber = findLine ? findLine.length + 1 : 1; var tagName = elem.tagName.toLowerCase(); var attributes = (0, _mapValues2.default)(_dom2.default.getAttributes(elem), function (val) { return decodeURIComponent(val); }); var element = { tagName: tagName, attributes: attributes, lineNumber: lineNumber }; if (_MJMLElementsCollection.endingTags.indexOf(tagName) !== -1) { var $local = _dom2.default.parseXML(elem); element.content = (0, _removeCDATA2.default)($local(tagName).html().trim()); } else { var children = _dom2.default.getChildren(elem); element.children = children ? (0, _compact2.default)((0, _filter2.default)(children, function (child) { return child.tagName; }).map(function (child) { return mjmlElementParser(child, content); })) : []; } return element; }
[ "function", "mjmlElementParser", "(", "elem", ",", "content", ")", "{", "if", "(", "!", "elem", ")", "{", "throw", "new", "_Error", ".", "NullElementError", "(", "'Null element found in mjmlElementParser'", ")", ";", "}", "var", "findLine", "=", "content", ".", "substr", "(", "0", ",", "elem", ".", "startIndex", ")", ".", "match", "(", "/", "\\n", "/", "g", ")", ";", "var", "lineNumber", "=", "findLine", "?", "findLine", ".", "length", "+", "1", ":", "1", ";", "var", "tagName", "=", "elem", ".", "tagName", ".", "toLowerCase", "(", ")", ";", "var", "attributes", "=", "(", "0", ",", "_mapValues2", ".", "default", ")", "(", "_dom2", ".", "default", ".", "getAttributes", "(", "elem", ")", ",", "function", "(", "val", ")", "{", "return", "decodeURIComponent", "(", "val", ")", ";", "}", ")", ";", "var", "element", "=", "{", "tagName", ":", "tagName", ",", "attributes", ":", "attributes", ",", "lineNumber", ":", "lineNumber", "}", ";", "if", "(", "_MJMLElementsCollection", ".", "endingTags", ".", "indexOf", "(", "tagName", ")", "!==", "-", "1", ")", "{", "var", "$local", "=", "_dom2", ".", "default", ".", "parseXML", "(", "elem", ")", ";", "element", ".", "content", "=", "(", "0", ",", "_removeCDATA2", ".", "default", ")", "(", "$local", "(", "tagName", ")", ".", "html", "(", ")", ".", "trim", "(", ")", ")", ";", "}", "else", "{", "var", "children", "=", "_dom2", ".", "default", ".", "getChildren", "(", "elem", ")", ";", "element", ".", "children", "=", "children", "?", "(", "0", ",", "_compact2", ".", "default", ")", "(", "(", "0", ",", "_filter2", ".", "default", ")", "(", "children", ",", "function", "(", "child", ")", "{", "return", "child", ".", "tagName", ";", "}", ")", ".", "map", "(", "function", "(", "child", ")", "{", "return", "mjmlElementParser", "(", "child", ",", "content", ")", ";", "}", ")", ")", ":", "[", "]", ";", "}", "return", "element", ";", "}" ]
converts MJML body into a JSON representation
[ "converts", "MJML", "body", "into", "a", "JSON", "representation" ]
878be949e0a142139e75f579bdaed2cb43511008
https://github.com/Biyaheroes/bh-mj-issue/blob/878be949e0a142139e75f579bdaed2cb43511008/dependency-mjml.support.js#L644-L671
55,623
ForbesLindesay-Unmaintained/sauce-test
lib/run-browser-stack.js
runSauceLabs
function runSauceLabs(location, remote, options) { var capabilities = options.capabilities; if (remote === 'browserstack') { var user = options.username || process.env.BROWSER_STACK_USERNAME; var key = options.accessKey || process.env.BROWSER_STACK_ACCESS_KEY; if (!user || !key) { return Promise.reject(new Error('You must provide `username` and `accessKey` as options ' + 'or set "BROWSER_STACK_USERNAME" and "BROWSER_STACK_ACCESS_KEY" in your ' + 'environment variables.')); } remote = 'http://hub-cloud.browserstack.com/wd/hub'; capabilities = function (platform) { var result = {}; Object.keys(options.capabilities || {}).forEach(function (key) { result[key] = options.capabilities[key]; }); Object.keys(platform).forEach(function (key) { result[key] = platform[key]; }); result['browserstack.user'] = user; result['browserstack.key'] = key; return result; }; } return (options.platforms ? Promise.resolve(options.platforms) : getPlatforms({ filterPlatforms: options.filterPlatforms, choosePlatforms: options.choosePlatforms })).then(function (platforms) { return runBrowsers(location, remote, { name: options.name, parallel: options.parallel || 3, platforms: platforms, throttle: options.throttle, capabilities: capabilities, debug: options.debug, httpDebug: options.httpDebug, jobInfo: options.jobInfo, allowExceptions: options.allowExceptions, testComplete: options.testComplete, testPassed: options.testPassed, bail: options.bail, timeout: options.timeout, onStart: options.onStart, onQueue: options.onQueue, onResult: options.onResult, onBrowserResults: options.onBrowserResults }); }); }
javascript
function runSauceLabs(location, remote, options) { var capabilities = options.capabilities; if (remote === 'browserstack') { var user = options.username || process.env.BROWSER_STACK_USERNAME; var key = options.accessKey || process.env.BROWSER_STACK_ACCESS_KEY; if (!user || !key) { return Promise.reject(new Error('You must provide `username` and `accessKey` as options ' + 'or set "BROWSER_STACK_USERNAME" and "BROWSER_STACK_ACCESS_KEY" in your ' + 'environment variables.')); } remote = 'http://hub-cloud.browserstack.com/wd/hub'; capabilities = function (platform) { var result = {}; Object.keys(options.capabilities || {}).forEach(function (key) { result[key] = options.capabilities[key]; }); Object.keys(platform).forEach(function (key) { result[key] = platform[key]; }); result['browserstack.user'] = user; result['browserstack.key'] = key; return result; }; } return (options.platforms ? Promise.resolve(options.platforms) : getPlatforms({ filterPlatforms: options.filterPlatforms, choosePlatforms: options.choosePlatforms })).then(function (platforms) { return runBrowsers(location, remote, { name: options.name, parallel: options.parallel || 3, platforms: platforms, throttle: options.throttle, capabilities: capabilities, debug: options.debug, httpDebug: options.httpDebug, jobInfo: options.jobInfo, allowExceptions: options.allowExceptions, testComplete: options.testComplete, testPassed: options.testPassed, bail: options.bail, timeout: options.timeout, onStart: options.onStart, onQueue: options.onQueue, onResult: options.onResult, onBrowserResults: options.onBrowserResults }); }); }
[ "function", "runSauceLabs", "(", "location", ",", "remote", ",", "options", ")", "{", "var", "capabilities", "=", "options", ".", "capabilities", ";", "if", "(", "remote", "===", "'browserstack'", ")", "{", "var", "user", "=", "options", ".", "username", "||", "process", ".", "env", ".", "BROWSER_STACK_USERNAME", ";", "var", "key", "=", "options", ".", "accessKey", "||", "process", ".", "env", ".", "BROWSER_STACK_ACCESS_KEY", ";", "if", "(", "!", "user", "||", "!", "key", ")", "{", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "'You must provide `username` and `accessKey` as options '", "+", "'or set \"BROWSER_STACK_USERNAME\" and \"BROWSER_STACK_ACCESS_KEY\" in your '", "+", "'environment variables.'", ")", ")", ";", "}", "remote", "=", "'http://hub-cloud.browserstack.com/wd/hub'", ";", "capabilities", "=", "function", "(", "platform", ")", "{", "var", "result", "=", "{", "}", ";", "Object", ".", "keys", "(", "options", ".", "capabilities", "||", "{", "}", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "result", "[", "key", "]", "=", "options", ".", "capabilities", "[", "key", "]", ";", "}", ")", ";", "Object", ".", "keys", "(", "platform", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "result", "[", "key", "]", "=", "platform", "[", "key", "]", ";", "}", ")", ";", "result", "[", "'browserstack.user'", "]", "=", "user", ";", "result", "[", "'browserstack.key'", "]", "=", "key", ";", "return", "result", ";", "}", ";", "}", "return", "(", "options", ".", "platforms", "?", "Promise", ".", "resolve", "(", "options", ".", "platforms", ")", ":", "getPlatforms", "(", "{", "filterPlatforms", ":", "options", ".", "filterPlatforms", ",", "choosePlatforms", ":", "options", ".", "choosePlatforms", "}", ")", ")", ".", "then", "(", "function", "(", "platforms", ")", "{", "return", "runBrowsers", "(", "location", ",", "remote", ",", "{", "name", ":", "options", ".", "name", ",", "parallel", ":", "options", ".", "parallel", "||", "3", ",", "platforms", ":", "platforms", ",", "throttle", ":", "options", ".", "throttle", ",", "capabilities", ":", "capabilities", ",", "debug", ":", "options", ".", "debug", ",", "httpDebug", ":", "options", ".", "httpDebug", ",", "jobInfo", ":", "options", ".", "jobInfo", ",", "allowExceptions", ":", "options", ".", "allowExceptions", ",", "testComplete", ":", "options", ".", "testComplete", ",", "testPassed", ":", "options", ".", "testPassed", ",", "bail", ":", "options", ".", "bail", ",", "timeout", ":", "options", ".", "timeout", ",", "onStart", ":", "options", ".", "onStart", ",", "onQueue", ":", "options", ".", "onQueue", ",", "onResult", ":", "options", ".", "onResult", ",", "onBrowserResults", ":", "options", ".", "onBrowserResults", "}", ")", ";", "}", ")", ";", "}" ]
Run a test in a collection of browsers on sauce labs @option {String} username @option {String} accessKey @option {Function} filterPlatforms @option {Function} choosePlatforms @option {Number} parallel @option {PlatformsInput} platforms @option {Function} throttle - overrides `parallel` @option {Object} capabilities @option {Boolean} debug @option {Object|Function} jobInfo @option {Boolean} allowExceptions @option {String|Function} testComplete @option {String|Function} testPassed @option {Boolean} bail @option {String} timeout @option {Function.<Result>} onResult @option {Function.<String,Array.<Result>>} onBrowserResults ```js { "chrome": [{ "passed": true, "duration": "3000", ...Platform }, ...], ... } ``` @param {Location} location @param {Object} remote @param {Options} options @returns {Promise}
[ "Run", "a", "test", "in", "a", "collection", "of", "browsers", "on", "sauce", "labs" ]
7c671b3321dc63aefc00c1c8d49e943ead2e7f5e
https://github.com/ForbesLindesay-Unmaintained/sauce-test/blob/7c671b3321dc63aefc00c1c8d49e943ead2e7f5e/lib/run-browser-stack.js#L41-L89
55,624
eventEmitter/ee-mysql
dep/node-buffalo/lib/mongo.js
writeHeader
function writeHeader(buffer, offset, size, opCode) { offset = binary.writeInt(buffer, offset, size) offset = binary.writeInt(buffer, offset, 0) offset = binary.writeInt(buffer, offset, 0) offset = binary.writeInt(buffer, offset, opCode) return offset }
javascript
function writeHeader(buffer, offset, size, opCode) { offset = binary.writeInt(buffer, offset, size) offset = binary.writeInt(buffer, offset, 0) offset = binary.writeInt(buffer, offset, 0) offset = binary.writeInt(buffer, offset, opCode) return offset }
[ "function", "writeHeader", "(", "buffer", ",", "offset", ",", "size", ",", "opCode", ")", "{", "offset", "=", "binary", ".", "writeInt", "(", "buffer", ",", "offset", ",", "size", ")", "offset", "=", "binary", ".", "writeInt", "(", "buffer", ",", "offset", ",", "0", ")", "offset", "=", "binary", ".", "writeInt", "(", "buffer", ",", "offset", ",", "0", ")", "offset", "=", "binary", ".", "writeInt", "(", "buffer", ",", "offset", ",", "opCode", ")", "return", "offset", "}" ]
header int32 size int32 request id int32 0 int32 op code command
[ "header", "int32", "size", "int32", "request", "id", "int32", "0", "int32", "op", "code", "command" ]
9797bff09a21157fb1dddb68275b01f282a184af
https://github.com/eventEmitter/ee-mysql/blob/9797bff09a21157fb1dddb68275b01f282a184af/dep/node-buffalo/lib/mongo.js#L57-L63
55,625
leozdgao/lgutil
src/dom/position.js
function (elem, offsetParent) { var offset, parentOffset if (window.jQuery) { if (!offsetParent) { return window.jQuery(elem).position() } offset = window.jQuery(elem).offset() parentOffset = window.jQuery(offsetParent).offset() // Get element offset relative to offsetParent return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left } } parentOffset = { top: 0, left: 0 } // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent if (window.getComputedStyle(elem).position === 'fixed' ) { // We assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect() } else { if (!offsetParent) { // Get *real* offsetParent offsetParent = position.offsetParent(elem) } // Get correct offsets offset = offsetFunc(elem) if (offsetParent.nodeName !== 'HTML') { parentOffset = offsetFunc(offsetParent) } // Add offsetParent borders parentOffset.top += parseInt(window.getComputedStyle(offsetParent).borderTopWidth, 10) parentOffset.left += parseInt(window.getComputedStyle(offsetParent).borderLeftWidth, 10) } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - parseInt(window.getComputedStyle(elem).marginTop, 10), left: offset.left - parentOffset.left - parseInt(window.getComputedStyle(elem).marginLeft, 10) } }
javascript
function (elem, offsetParent) { var offset, parentOffset if (window.jQuery) { if (!offsetParent) { return window.jQuery(elem).position() } offset = window.jQuery(elem).offset() parentOffset = window.jQuery(offsetParent).offset() // Get element offset relative to offsetParent return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left } } parentOffset = { top: 0, left: 0 } // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent if (window.getComputedStyle(elem).position === 'fixed' ) { // We assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect() } else { if (!offsetParent) { // Get *real* offsetParent offsetParent = position.offsetParent(elem) } // Get correct offsets offset = offsetFunc(elem) if (offsetParent.nodeName !== 'HTML') { parentOffset = offsetFunc(offsetParent) } // Add offsetParent borders parentOffset.top += parseInt(window.getComputedStyle(offsetParent).borderTopWidth, 10) parentOffset.left += parseInt(window.getComputedStyle(offsetParent).borderLeftWidth, 10) } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - parseInt(window.getComputedStyle(elem).marginTop, 10), left: offset.left - parentOffset.left - parseInt(window.getComputedStyle(elem).marginLeft, 10) } }
[ "function", "(", "elem", ",", "offsetParent", ")", "{", "var", "offset", ",", "parentOffset", "if", "(", "window", ".", "jQuery", ")", "{", "if", "(", "!", "offsetParent", ")", "{", "return", "window", ".", "jQuery", "(", "elem", ")", ".", "position", "(", ")", "}", "offset", "=", "window", ".", "jQuery", "(", "elem", ")", ".", "offset", "(", ")", "parentOffset", "=", "window", ".", "jQuery", "(", "offsetParent", ")", ".", "offset", "(", ")", "// Get element offset relative to offsetParent", "return", "{", "top", ":", "offset", ".", "top", "-", "parentOffset", ".", "top", ",", "left", ":", "offset", ".", "left", "-", "parentOffset", ".", "left", "}", "}", "parentOffset", "=", "{", "top", ":", "0", ",", "left", ":", "0", "}", "// Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent", "if", "(", "window", ".", "getComputedStyle", "(", "elem", ")", ".", "position", "===", "'fixed'", ")", "{", "// We assume that getBoundingClientRect is available when computed position is fixed", "offset", "=", "elem", ".", "getBoundingClientRect", "(", ")", "}", "else", "{", "if", "(", "!", "offsetParent", ")", "{", "// Get *real* offsetParent", "offsetParent", "=", "position", ".", "offsetParent", "(", "elem", ")", "}", "// Get correct offsets", "offset", "=", "offsetFunc", "(", "elem", ")", "if", "(", "offsetParent", ".", "nodeName", "!==", "'HTML'", ")", "{", "parentOffset", "=", "offsetFunc", "(", "offsetParent", ")", "}", "// Add offsetParent borders", "parentOffset", ".", "top", "+=", "parseInt", "(", "window", ".", "getComputedStyle", "(", "offsetParent", ")", ".", "borderTopWidth", ",", "10", ")", "parentOffset", ".", "left", "+=", "parseInt", "(", "window", ".", "getComputedStyle", "(", "offsetParent", ")", ".", "borderLeftWidth", ",", "10", ")", "}", "// Subtract parent offsets and element margins", "return", "{", "top", ":", "offset", ".", "top", "-", "parentOffset", ".", "top", "-", "parseInt", "(", "window", ".", "getComputedStyle", "(", "elem", ")", ".", "marginTop", ",", "10", ")", ",", "left", ":", "offset", ".", "left", "-", "parentOffset", ".", "left", "-", "parseInt", "(", "window", ".", "getComputedStyle", "(", "elem", ")", ".", "marginLeft", ",", "10", ")", "}", "}" ]
Get elements position @param {HTMLElement} elem @param {HTMLElement?} offsetParent @returns {{top: number, left: number}}
[ "Get", "elements", "position" ]
e9c71106fecb97fd8094f82663fe0a3aa13ae22b
https://github.com/leozdgao/lgutil/blob/e9c71106fecb97fd8094f82663fe0a3aa13ae22b/src/dom/position.js#L10-L57
55,626
Zhouzi/gulp-bucket
index.js
Definition
function Definition (factoryName, factory) { var configDefaults = {} var deps = [] return { /** * Calls the factory for each arguments and returns * the list of tasks that just got created. * * @params {Object} * @returns {Array} */ add: function add () { var configs = _(arguments).toArray().flatten(true).value() if (configs.length === 0) { // by adding an empty object // we'll create a task that has no alias // that's useful for Definition that are not // really tasks creators (e.g the help task) configs = [{}] } var addedTasks = _(configs) .map(function (config) { return _.assign({}, configDefaults, config) }) .map(function (config) { var taskName = name(factoryName, config.alias) var deps = _(factory(config, options())).flatten(true).filter(_.identity).value() var fn = _.isFunction(_.last(deps)) ? deps.pop() : _.noop gulp.task(taskName, deps, fn) return taskName }) .run() if (gulp.tasks[factoryName] == null || gulp.tasks[factoryName].$root) { gulp.task(factoryName, deps.concat(tasks(factoryName + ':'))) gulp.tasks[factoryName].$root = true } return addedTasks }, /** * Sets the factory's default config. * * @param {Object} config * @returns {{add: add, defaults: defaults, before: before}} */ defaults: function defaults (config) { configDefaults = config return this }, /** * Getter/setter that add tasks to run before any factory's task. * * @returns {*} */ before: function before () { if (arguments.length) { deps = arguments[0] return this } return deps } } }
javascript
function Definition (factoryName, factory) { var configDefaults = {} var deps = [] return { /** * Calls the factory for each arguments and returns * the list of tasks that just got created. * * @params {Object} * @returns {Array} */ add: function add () { var configs = _(arguments).toArray().flatten(true).value() if (configs.length === 0) { // by adding an empty object // we'll create a task that has no alias // that's useful for Definition that are not // really tasks creators (e.g the help task) configs = [{}] } var addedTasks = _(configs) .map(function (config) { return _.assign({}, configDefaults, config) }) .map(function (config) { var taskName = name(factoryName, config.alias) var deps = _(factory(config, options())).flatten(true).filter(_.identity).value() var fn = _.isFunction(_.last(deps)) ? deps.pop() : _.noop gulp.task(taskName, deps, fn) return taskName }) .run() if (gulp.tasks[factoryName] == null || gulp.tasks[factoryName].$root) { gulp.task(factoryName, deps.concat(tasks(factoryName + ':'))) gulp.tasks[factoryName].$root = true } return addedTasks }, /** * Sets the factory's default config. * * @param {Object} config * @returns {{add: add, defaults: defaults, before: before}} */ defaults: function defaults (config) { configDefaults = config return this }, /** * Getter/setter that add tasks to run before any factory's task. * * @returns {*} */ before: function before () { if (arguments.length) { deps = arguments[0] return this } return deps } } }
[ "function", "Definition", "(", "factoryName", ",", "factory", ")", "{", "var", "configDefaults", "=", "{", "}", "var", "deps", "=", "[", "]", "return", "{", "/**\n * Calls the factory for each arguments and returns\n * the list of tasks that just got created.\n *\n * @params {Object}\n * @returns {Array}\n */", "add", ":", "function", "add", "(", ")", "{", "var", "configs", "=", "_", "(", "arguments", ")", ".", "toArray", "(", ")", ".", "flatten", "(", "true", ")", ".", "value", "(", ")", "if", "(", "configs", ".", "length", "===", "0", ")", "{", "// by adding an empty object", "// we'll create a task that has no alias", "// that's useful for Definition that are not", "// really tasks creators (e.g the help task)", "configs", "=", "[", "{", "}", "]", "}", "var", "addedTasks", "=", "_", "(", "configs", ")", ".", "map", "(", "function", "(", "config", ")", "{", "return", "_", ".", "assign", "(", "{", "}", ",", "configDefaults", ",", "config", ")", "}", ")", ".", "map", "(", "function", "(", "config", ")", "{", "var", "taskName", "=", "name", "(", "factoryName", ",", "config", ".", "alias", ")", "var", "deps", "=", "_", "(", "factory", "(", "config", ",", "options", "(", ")", ")", ")", ".", "flatten", "(", "true", ")", ".", "filter", "(", "_", ".", "identity", ")", ".", "value", "(", ")", "var", "fn", "=", "_", ".", "isFunction", "(", "_", ".", "last", "(", "deps", ")", ")", "?", "deps", ".", "pop", "(", ")", ":", "_", ".", "noop", "gulp", ".", "task", "(", "taskName", ",", "deps", ",", "fn", ")", "return", "taskName", "}", ")", ".", "run", "(", ")", "if", "(", "gulp", ".", "tasks", "[", "factoryName", "]", "==", "null", "||", "gulp", ".", "tasks", "[", "factoryName", "]", ".", "$root", ")", "{", "gulp", ".", "task", "(", "factoryName", ",", "deps", ".", "concat", "(", "tasks", "(", "factoryName", "+", "':'", ")", ")", ")", "gulp", ".", "tasks", "[", "factoryName", "]", ".", "$root", "=", "true", "}", "return", "addedTasks", "}", ",", "/**\n * Sets the factory's default config.\n *\n * @param {Object} config\n * @returns {{add: add, defaults: defaults, before: before}}\n */", "defaults", ":", "function", "defaults", "(", "config", ")", "{", "configDefaults", "=", "config", "return", "this", "}", ",", "/**\n * Getter/setter that add tasks to run before any factory's task.\n *\n * @returns {*}\n */", "before", ":", "function", "before", "(", ")", "{", "if", "(", "arguments", ".", "length", ")", "{", "deps", "=", "arguments", "[", "0", "]", "return", "this", "}", "return", "deps", "}", "}", "}" ]
Return a Definition object that's used to create tasks from a given factory. @param {String} factoryName @param {Function} factory @returns {{add: add, defaults: defaults}}
[ "Return", "a", "Definition", "object", "that", "s", "used", "to", "create", "tasks", "from", "a", "given", "factory", "." ]
b0e9a77607be62d993e473b72eaf5952562b9656
https://github.com/Zhouzi/gulp-bucket/blob/b0e9a77607be62d993e473b72eaf5952562b9656/index.js#L15-L85
55,627
Zhouzi/gulp-bucket
index.js
main
function main () { var taskList = _(arguments).toArray().flatten(true).value() gulp.task('default', taskList) return this }
javascript
function main () { var taskList = _(arguments).toArray().flatten(true).value() gulp.task('default', taskList) return this }
[ "function", "main", "(", ")", "{", "var", "taskList", "=", "_", "(", "arguments", ")", ".", "toArray", "(", ")", ".", "flatten", "(", "true", ")", ".", "value", "(", ")", "gulp", ".", "task", "(", "'default'", ",", "taskList", ")", "return", "this", "}" ]
Create gulp's default task that runs every tasks passed as arguments. @params array of strings @returns {bucket}
[ "Create", "gulp", "s", "default", "task", "that", "runs", "every", "tasks", "passed", "as", "arguments", "." ]
b0e9a77607be62d993e473b72eaf5952562b9656
https://github.com/Zhouzi/gulp-bucket/blob/b0e9a77607be62d993e473b72eaf5952562b9656/index.js#L112-L116
55,628
Zhouzi/gulp-bucket
index.js
tasks
function tasks (taskName) { var taskList = _.keys(gulp.tasks) if (taskName == null) { return taskList } return _.filter(taskList, function (task) { return _.startsWith(task, taskName) }) }
javascript
function tasks (taskName) { var taskList = _.keys(gulp.tasks) if (taskName == null) { return taskList } return _.filter(taskList, function (task) { return _.startsWith(task, taskName) }) }
[ "function", "tasks", "(", "taskName", ")", "{", "var", "taskList", "=", "_", ".", "keys", "(", "gulp", ".", "tasks", ")", "if", "(", "taskName", "==", "null", ")", "{", "return", "taskList", "}", "return", "_", ".", "filter", "(", "taskList", ",", "function", "(", "task", ")", "{", "return", "_", ".", "startsWith", "(", "task", ",", "taskName", ")", "}", ")", "}" ]
Returns every gulp tasks with a name that starts by taskName if provided, otherwise returns all existing tasks. @param {String} [taskName] @returns {Array}
[ "Returns", "every", "gulp", "tasks", "with", "a", "name", "that", "starts", "by", "taskName", "if", "provided", "otherwise", "returns", "all", "existing", "tasks", "." ]
b0e9a77607be62d993e473b72eaf5952562b9656
https://github.com/Zhouzi/gulp-bucket/blob/b0e9a77607be62d993e473b72eaf5952562b9656/index.js#L143-L153
55,629
PrinceNebulon/github-api-promise
src/repositories/releases.js
function() { var deferred = Q.defer(); try { request .get(getRepoUrl('releases')) .set('Authorization', 'token ' + config.token) .then(function(res) { logRequestSuccess(res); deferred.resolve(res.body); }, function(err) { logRequestError(err); deferred.reject(err.message); }); } catch(err) { console.log(err); deferred.reject(err.message); } return deferred.promise; }
javascript
function() { var deferred = Q.defer(); try { request .get(getRepoUrl('releases')) .set('Authorization', 'token ' + config.token) .then(function(res) { logRequestSuccess(res); deferred.resolve(res.body); }, function(err) { logRequestError(err); deferred.reject(err.message); }); } catch(err) { console.log(err); deferred.reject(err.message); } return deferred.promise; }
[ "function", "(", ")", "{", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "try", "{", "request", ".", "get", "(", "getRepoUrl", "(", "'releases'", ")", ")", ".", "set", "(", "'Authorization'", ",", "'token '", "+", "config", ".", "token", ")", ".", "then", "(", "function", "(", "res", ")", "{", "logRequestSuccess", "(", "res", ")", ";", "deferred", ".", "resolve", "(", "res", ".", "body", ")", ";", "}", ",", "function", "(", "err", ")", "{", "logRequestError", "(", "err", ")", ";", "deferred", ".", "reject", "(", "err", ".", "message", ")", ";", "}", ")", ";", "}", "catch", "(", "err", ")", "{", "console", ".", "log", "(", "err", ")", ";", "deferred", ".", "reject", "(", "err", ".", "message", ")", ";", "}", "return", "deferred", ".", "promise", ";", "}" ]
This returns a list of releases, which does not include regular Git tags that have not been associated with a release. To get a list of Git tags, use the Repository Tags API. Information about published releases are available to everyone. Only users with push access will receive listings for draft releases. @return {JSON} A list of release data
[ "This", "returns", "a", "list", "of", "releases", "which", "does", "not", "include", "regular", "Git", "tags", "that", "have", "not", "been", "associated", "with", "a", "release", ".", "To", "get", "a", "list", "of", "Git", "tags", "use", "the", "Repository", "Tags", "API", ".", "Information", "about", "published", "releases", "are", "available", "to", "everyone", ".", "Only", "users", "with", "push", "access", "will", "receive", "listings", "for", "draft", "releases", "." ]
990cb2cce19b53f54d9243002fde47428f24e7cc
https://github.com/PrinceNebulon/github-api-promise/blob/990cb2cce19b53f54d9243002fde47428f24e7cc/src/repositories/releases.js#L44-L65
55,630
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/elementpath.js
function( query, excludeRoot, fromTop ) { var evaluator; if ( typeof query == 'string' ) evaluator = function( node ) { return node.getName() == query; }; if ( query instanceof CKEDITOR.dom.element ) evaluator = function( node ) { return node.equals( query ); }; else if ( CKEDITOR.tools.isArray( query ) ) evaluator = function( node ) { return CKEDITOR.tools.indexOf( query, node.getName() ) > -1; }; else if ( typeof query == 'function' ) evaluator = query; else if ( typeof query == 'object' ) evaluator = function( node ) { return node.getName() in query; }; var elements = this.elements, length = elements.length; excludeRoot && length--; if ( fromTop ) { elements = Array.prototype.slice.call( elements, 0 ); elements.reverse(); } for ( var i = 0; i < length; i++ ) { if ( evaluator( elements[ i ] ) ) return elements[ i ]; } return null; }
javascript
function( query, excludeRoot, fromTop ) { var evaluator; if ( typeof query == 'string' ) evaluator = function( node ) { return node.getName() == query; }; if ( query instanceof CKEDITOR.dom.element ) evaluator = function( node ) { return node.equals( query ); }; else if ( CKEDITOR.tools.isArray( query ) ) evaluator = function( node ) { return CKEDITOR.tools.indexOf( query, node.getName() ) > -1; }; else if ( typeof query == 'function' ) evaluator = query; else if ( typeof query == 'object' ) evaluator = function( node ) { return node.getName() in query; }; var elements = this.elements, length = elements.length; excludeRoot && length--; if ( fromTop ) { elements = Array.prototype.slice.call( elements, 0 ); elements.reverse(); } for ( var i = 0; i < length; i++ ) { if ( evaluator( elements[ i ] ) ) return elements[ i ]; } return null; }
[ "function", "(", "query", ",", "excludeRoot", ",", "fromTop", ")", "{", "var", "evaluator", ";", "if", "(", "typeof", "query", "==", "'string'", ")", "evaluator", "=", "function", "(", "node", ")", "{", "return", "node", ".", "getName", "(", ")", "==", "query", ";", "}", ";", "if", "(", "query", "instanceof", "CKEDITOR", ".", "dom", ".", "element", ")", "evaluator", "=", "function", "(", "node", ")", "{", "return", "node", ".", "equals", "(", "query", ")", ";", "}", ";", "else", "if", "(", "CKEDITOR", ".", "tools", ".", "isArray", "(", "query", ")", ")", "evaluator", "=", "function", "(", "node", ")", "{", "return", "CKEDITOR", ".", "tools", ".", "indexOf", "(", "query", ",", "node", ".", "getName", "(", ")", ")", ">", "-", "1", ";", "}", ";", "else", "if", "(", "typeof", "query", "==", "'function'", ")", "evaluator", "=", "query", ";", "else", "if", "(", "typeof", "query", "==", "'object'", ")", "evaluator", "=", "function", "(", "node", ")", "{", "return", "node", ".", "getName", "(", ")", "in", "query", ";", "}", ";", "var", "elements", "=", "this", ".", "elements", ",", "length", "=", "elements", ".", "length", ";", "excludeRoot", "&&", "length", "--", ";", "if", "(", "fromTop", ")", "{", "elements", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "elements", ",", "0", ")", ";", "elements", ".", "reverse", "(", ")", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "if", "(", "evaluator", "(", "elements", "[", "i", "]", ")", ")", "return", "elements", "[", "i", "]", ";", "}", "return", "null", ";", "}" ]
Search the path elements that meets the specified criteria. @param {String/Array/Function/Object/CKEDITOR.dom.element} query The criteria that can be either a tag name, list (array and object) of tag names, element or an node evaluator function. @param {Boolean} [excludeRoot] Not taking path root element into consideration. @param {Boolean} [fromTop] Search start from the topmost element instead of bottom. @returns {CKEDITOR.dom.element} The first matched dom element or `null`.
[ "Search", "the", "path", "elements", "that", "meets", "the", "specified", "criteria", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/elementpath.js#L183-L219
55,631
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/elementpath.js
function( tag ) { var holder; // Check for block context. if ( tag in CKEDITOR.dtd.$block ) { // Indeterminate elements which are not subjected to be splitted or surrounded must be checked first. var inter = this.contains( CKEDITOR.dtd.$intermediate ); holder = inter || ( this.root.equals( this.block ) && this.block ) || this.blockLimit; return !!holder.getDtd()[ tag ]; } return true; }
javascript
function( tag ) { var holder; // Check for block context. if ( tag in CKEDITOR.dtd.$block ) { // Indeterminate elements which are not subjected to be splitted or surrounded must be checked first. var inter = this.contains( CKEDITOR.dtd.$intermediate ); holder = inter || ( this.root.equals( this.block ) && this.block ) || this.blockLimit; return !!holder.getDtd()[ tag ]; } return true; }
[ "function", "(", "tag", ")", "{", "var", "holder", ";", "// Check for block context.", "if", "(", "tag", "in", "CKEDITOR", ".", "dtd", ".", "$block", ")", "{", "// Indeterminate elements which are not subjected to be splitted or surrounded must be checked first.", "var", "inter", "=", "this", ".", "contains", "(", "CKEDITOR", ".", "dtd", ".", "$intermediate", ")", ";", "holder", "=", "inter", "||", "(", "this", ".", "root", ".", "equals", "(", "this", ".", "block", ")", "&&", "this", ".", "block", ")", "||", "this", ".", "blockLimit", ";", "return", "!", "!", "holder", ".", "getDtd", "(", ")", "[", "tag", "]", ";", "}", "return", "true", ";", "}" ]
Check whether the elements path is the proper context for the specified tag name in the DTD. @param {String} tag The tag name. @returns {Boolean}
[ "Check", "whether", "the", "elements", "path", "is", "the", "proper", "context", "for", "the", "specified", "tag", "name", "in", "the", "DTD", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/elementpath.js#L228-L240
55,632
doowb/session-cache
index.js
isActive
function isActive() { try { var key = '___session is active___'; return session.get(key) || session.set(key, true); } catch (err) { return false; } }
javascript
function isActive() { try { var key = '___session is active___'; return session.get(key) || session.set(key, true); } catch (err) { return false; } }
[ "function", "isActive", "(", ")", "{", "try", "{", "var", "key", "=", "'___session is active___'", ";", "return", "session", ".", "get", "(", "key", ")", "||", "session", ".", "set", "(", "key", ",", "true", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "false", ";", "}", "}" ]
Set a heuristic for determining if the session is actually active. @return {Boolean} Returns `true` if session is active @api private
[ "Set", "a", "heuristic", "for", "determining", "if", "the", "session", "is", "actually", "active", "." ]
5f8c686a8f93c30c4e703158814a625f4b4a9dbf
https://github.com/doowb/session-cache/blob/5f8c686a8f93c30c4e703158814a625f4b4a9dbf/index.js#L50-L57
55,633
skerit/alchemy-debugbar
assets/scripts/debugbar/core.js
function (event) { event.preventDefault(); if (!currentElement) { return; } var newHeight = currentElement.data('startHeight') + (event.pageY - currentElement.data('startY')); currentElement.parent().height(newHeight); }
javascript
function (event) { event.preventDefault(); if (!currentElement) { return; } var newHeight = currentElement.data('startHeight') + (event.pageY - currentElement.data('startY')); currentElement.parent().height(newHeight); }
[ "function", "(", "event", ")", "{", "event", ".", "preventDefault", "(", ")", ";", "if", "(", "!", "currentElement", ")", "{", "return", ";", "}", "var", "newHeight", "=", "currentElement", ".", "data", "(", "'startHeight'", ")", "+", "(", "event", ".", "pageY", "-", "currentElement", ".", "data", "(", "'startY'", ")", ")", ";", "currentElement", ".", "parent", "(", ")", ".", "height", "(", "newHeight", ")", ";", "}" ]
Use the elements startHeight stored Event.pageY and current Event.pageY to resize the panel.
[ "Use", "the", "elements", "startHeight", "stored", "Event", ".", "pageY", "and", "current", "Event", ".", "pageY", "to", "resize", "the", "panel", "." ]
af0e34906646f43b0fe915c9a9a11e3f7bc27a87
https://github.com/skerit/alchemy-debugbar/blob/af0e34906646f43b0fe915c9a9a11e3f7bc27a87/assets/scripts/debugbar/core.js#L304-L311
55,634
isuttell/throttled
middleware.js
assign
function assign() { var result = {}; var args = Array.prototype.slice.call(arguments); for(var i = 0; i < args.length; i++) { var obj = args[i]; if(typeof obj !== 'object') { continue; } for(var key in obj) { if(obj.hasOwnProperty(key)) { result[key] = obj[key]; } } obj = void 0; } return result; }
javascript
function assign() { var result = {}; var args = Array.prototype.slice.call(arguments); for(var i = 0; i < args.length; i++) { var obj = args[i]; if(typeof obj !== 'object') { continue; } for(var key in obj) { if(obj.hasOwnProperty(key)) { result[key] = obj[key]; } } obj = void 0; } return result; }
[ "function", "assign", "(", ")", "{", "var", "result", "=", "{", "}", ";", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "args", ".", "length", ";", "i", "++", ")", "{", "var", "obj", "=", "args", "[", "i", "]", ";", "if", "(", "typeof", "obj", "!==", "'object'", ")", "{", "continue", ";", "}", "for", "(", "var", "key", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "result", "[", "key", "]", "=", "obj", "[", "key", "]", ";", "}", "}", "obj", "=", "void", "0", ";", "}", "return", "result", ";", "}" ]
Merge multiple obects together @param {Object...} @return {Object}
[ "Merge", "multiple", "obects", "together" ]
80634416f0c487bebe64133b0064f29834bcc16a
https://github.com/isuttell/throttled/blob/80634416f0c487bebe64133b0064f29834bcc16a/middleware.js#L41-L57
55,635
isuttell/throttled
middleware.js
function(err, results) { if(options.headers) { // Set some headers so we can track what's going on var headers = { 'X-Throttled': results.throttled, 'X-Throttle-Remaining': Math.max(options.limit - results.count, 0) }; if (results.expiresAt) { headers['X-Throttle-Reset'] = results.expiresAt; } res.set(headers); } if (err) { // Unknown error next(err); return; } else if (results.throttled) { if(logger) { // Log it logger.warn( '%s - ResponseThrottled for %s seconds - %s requests exceeded %s within %s seconds', ip, options.ban, results.count, options.limit, options.period); } // Let the client know this is forbidden res.status(403); // Create a human readable error var banLength = moment.duration(options.ban, 'seconds').humanize(); next('Warning: Too many requests. You have been throttled for ' + banLength + '. ' + 'Try again ' + moment(results.expiresAt).fromNow()); return; } else { // All is good next(); return; } }
javascript
function(err, results) { if(options.headers) { // Set some headers so we can track what's going on var headers = { 'X-Throttled': results.throttled, 'X-Throttle-Remaining': Math.max(options.limit - results.count, 0) }; if (results.expiresAt) { headers['X-Throttle-Reset'] = results.expiresAt; } res.set(headers); } if (err) { // Unknown error next(err); return; } else if (results.throttled) { if(logger) { // Log it logger.warn( '%s - ResponseThrottled for %s seconds - %s requests exceeded %s within %s seconds', ip, options.ban, results.count, options.limit, options.period); } // Let the client know this is forbidden res.status(403); // Create a human readable error var banLength = moment.duration(options.ban, 'seconds').humanize(); next('Warning: Too many requests. You have been throttled for ' + banLength + '. ' + 'Try again ' + moment(results.expiresAt).fromNow()); return; } else { // All is good next(); return; } }
[ "function", "(", "err", ",", "results", ")", "{", "if", "(", "options", ".", "headers", ")", "{", "// Set some headers so we can track what's going on", "var", "headers", "=", "{", "'X-Throttled'", ":", "results", ".", "throttled", ",", "'X-Throttle-Remaining'", ":", "Math", ".", "max", "(", "options", ".", "limit", "-", "results", ".", "count", ",", "0", ")", "}", ";", "if", "(", "results", ".", "expiresAt", ")", "{", "headers", "[", "'X-Throttle-Reset'", "]", "=", "results", ".", "expiresAt", ";", "}", "res", ".", "set", "(", "headers", ")", ";", "}", "if", "(", "err", ")", "{", "// Unknown error", "next", "(", "err", ")", ";", "return", ";", "}", "else", "if", "(", "results", ".", "throttled", ")", "{", "if", "(", "logger", ")", "{", "// Log it", "logger", ".", "warn", "(", "'%s - ResponseThrottled for %s seconds - %s requests exceeded %s within %s seconds'", ",", "ip", ",", "options", ".", "ban", ",", "results", ".", "count", ",", "options", ".", "limit", ",", "options", ".", "period", ")", ";", "}", "// Let the client know this is forbidden", "res", ".", "status", "(", "403", ")", ";", "// Create a human readable error", "var", "banLength", "=", "moment", ".", "duration", "(", "options", ".", "ban", ",", "'seconds'", ")", ".", "humanize", "(", ")", ";", "next", "(", "'Warning: Too many requests. You have been throttled for '", "+", "banLength", "+", "'. '", "+", "'Try again '", "+", "moment", "(", "results", ".", "expiresAt", ")", ".", "fromNow", "(", ")", ")", ";", "return", ";", "}", "else", "{", "// All is good", "next", "(", ")", ";", "return", ";", "}", "}" ]
Now do something with all of this information @param {Error} err @param {Object} results
[ "Now", "do", "something", "with", "all", "of", "this", "information" ]
80634416f0c487bebe64133b0064f29834bcc16a
https://github.com/isuttell/throttled/blob/80634416f0c487bebe64133b0064f29834bcc16a/middleware.js#L186-L230
55,636
Qwerios/madlib-settings
lib/settings.js
function(key, data) { var currentData; currentData = settings[key]; if ((currentData != null) && _.isObject(currentData)) { settings[key] = _.extend(data, settings[key]); } else if (currentData == null) { settings[key] = data; } }
javascript
function(key, data) { var currentData; currentData = settings[key]; if ((currentData != null) && _.isObject(currentData)) { settings[key] = _.extend(data, settings[key]); } else if (currentData == null) { settings[key] = data; } }
[ "function", "(", "key", ",", "data", ")", "{", "var", "currentData", ";", "currentData", "=", "settings", "[", "key", "]", ";", "if", "(", "(", "currentData", "!=", "null", ")", "&&", "_", ".", "isObject", "(", "currentData", ")", ")", "{", "settings", "[", "key", "]", "=", "_", ".", "extend", "(", "data", ",", "settings", "[", "key", "]", ")", ";", "}", "else", "if", "(", "currentData", "==", "null", ")", "{", "settings", "[", "key", "]", "=", "data", ";", "}", "}" ]
Used to initially set a setttings value. Convenient for settings defaults that wont overwrite already set actual values @function init @param {String} key The setting name @param {Mixed} data The setting value @return None
[ "Used", "to", "initially", "set", "a", "setttings", "value", ".", "Convenient", "for", "settings", "defaults", "that", "wont", "overwrite", "already", "set", "actual", "values" ]
078283c18d07e42a5f19a7fa4fcca92f59ee4c29
https://github.com/Qwerios/madlib-settings/blob/078283c18d07e42a5f19a7fa4fcca92f59ee4c29/lib/settings.js#L32-L40
55,637
Qwerios/madlib-settings
lib/settings.js
function(key, data) { var currentData; currentData = settings[key] || {}; settings[key] = _.extend(currentData, data); }
javascript
function(key, data) { var currentData; currentData = settings[key] || {}; settings[key] = _.extend(currentData, data); }
[ "function", "(", "key", ",", "data", ")", "{", "var", "currentData", ";", "currentData", "=", "settings", "[", "key", "]", "||", "{", "}", ";", "settings", "[", "key", "]", "=", "_", ".", "extend", "(", "currentData", ",", "data", ")", ";", "}" ]
Merge a setting using underscore's extend. Only useful if the setting is an object @function merge @param {String} key The setting name @param {Mixed} data The setting value @return None
[ "Merge", "a", "setting", "using", "underscore", "s", "extend", ".", "Only", "useful", "if", "the", "setting", "is", "an", "object" ]
078283c18d07e42a5f19a7fa4fcca92f59ee4c29
https://github.com/Qwerios/madlib-settings/blob/078283c18d07e42a5f19a7fa4fcca92f59ee4c29/lib/settings.js#L108-L112
55,638
crobinson42/error-shelter
errorShelter.js
function (err) { var storage = getStorage(); if (storage && storage.errors) { storage.errors.push(err); return localStorage.setItem([config.nameSpace], JSON.stringify(storage)); } }
javascript
function (err) { var storage = getStorage(); if (storage && storage.errors) { storage.errors.push(err); return localStorage.setItem([config.nameSpace], JSON.stringify(storage)); } }
[ "function", "(", "err", ")", "{", "var", "storage", "=", "getStorage", "(", ")", ";", "if", "(", "storage", "&&", "storage", ".", "errors", ")", "{", "storage", ".", "errors", ".", "push", "(", "err", ")", ";", "return", "localStorage", ".", "setItem", "(", "[", "config", ".", "nameSpace", "]", ",", "JSON", ".", "stringify", "(", "storage", ")", ")", ";", "}", "}" ]
JSON.stringify the object and put back in localStorage
[ "JSON", ".", "stringify", "the", "object", "and", "put", "back", "in", "localStorage" ]
dcdda9b3a802c53baa957bd15a3f657c3ef222d8
https://github.com/crobinson42/error-shelter/blob/dcdda9b3a802c53baa957bd15a3f657c3ef222d8/errorShelter.js#L52-L58
55,639
AndreasMadsen/piccolo
lib/build/dependencies.js
searchArray
function searchArray(list, value) { var index = list.indexOf(value); if (index === -1) return false; return value; }
javascript
function searchArray(list, value) { var index = list.indexOf(value); if (index === -1) return false; return value; }
[ "function", "searchArray", "(", "list", ",", "value", ")", "{", "var", "index", "=", "list", ".", "indexOf", "(", "value", ")", ";", "if", "(", "index", "===", "-", "1", ")", "return", "false", ";", "return", "value", ";", "}" ]
search array and return the search argument or false if not found
[ "search", "array", "and", "return", "the", "search", "argument", "or", "false", "if", "not", "found" ]
ef43f5634c564eef0d21a4a6aa103b2f1e3baa3d
https://github.com/AndreasMadsen/piccolo/blob/ef43f5634c564eef0d21a4a6aa103b2f1e3baa3d/lib/build/dependencies.js#L117-L122
55,640
AndreasMadsen/piccolo
lib/build/dependencies.js
searchBase
function searchBase(base) { var basename = path.resolve(base, modulename); // return no path var filename = searchArray(dirMap, basename); if (filename) return filename; // return .js path filename = searchArray(dirMap, basename + '.js'); if (filename) return filename; // return .json path filename = searchArray(dirMap, basename + '.json'); if (filename) return filename; // if input was an path, do search more if (isPath) return false; // resolve and return /package.json path if (packageMap[basename]) { return packageMap[basename]; } return searchArray(dirMap, basename + '/index.js'); }
javascript
function searchBase(base) { var basename = path.resolve(base, modulename); // return no path var filename = searchArray(dirMap, basename); if (filename) return filename; // return .js path filename = searchArray(dirMap, basename + '.js'); if (filename) return filename; // return .json path filename = searchArray(dirMap, basename + '.json'); if (filename) return filename; // if input was an path, do search more if (isPath) return false; // resolve and return /package.json path if (packageMap[basename]) { return packageMap[basename]; } return searchArray(dirMap, basename + '/index.js'); }
[ "function", "searchBase", "(", "base", ")", "{", "var", "basename", "=", "path", ".", "resolve", "(", "base", ",", "modulename", ")", ";", "// return no path", "var", "filename", "=", "searchArray", "(", "dirMap", ",", "basename", ")", ";", "if", "(", "filename", ")", "return", "filename", ";", "// return .js path", "filename", "=", "searchArray", "(", "dirMap", ",", "basename", "+", "'.js'", ")", ";", "if", "(", "filename", ")", "return", "filename", ";", "// return .json path", "filename", "=", "searchArray", "(", "dirMap", ",", "basename", "+", "'.json'", ")", ";", "if", "(", "filename", ")", "return", "filename", ";", "// if input was an path, do search more", "if", "(", "isPath", ")", "return", "false", ";", "// resolve and return /package.json path", "if", "(", "packageMap", "[", "basename", "]", ")", "{", "return", "packageMap", "[", "basename", "]", ";", "}", "return", "searchArray", "(", "dirMap", ",", "basename", "+", "'/index.js'", ")", ";", "}" ]
search each query
[ "search", "each", "query" ]
ef43f5634c564eef0d21a4a6aa103b2f1e3baa3d
https://github.com/AndreasMadsen/piccolo/blob/ef43f5634c564eef0d21a4a6aa103b2f1e3baa3d/lib/build/dependencies.js#L163-L187
55,641
AndreasMadsen/piccolo
lib/build/dependencies.js
buildPackage
function buildPackage(callback) { var dirMap = self.build.dirMap, i = dirMap.length, filepath, pkgName = '/package.json', pkgLength = pkgName.length, list = []; // search dirmap for package.json while(i--) { filepath = dirMap[i]; if (filepath.slice(filepath.length - pkgLength, filepath.length) === pkgName) { list.push(filepath); } } function resolvePackage(filepath, callback) { var dirname = filepath.slice(0, filepath.length - pkgLength); var fullpath = path.resolve(self.piccolo.get('modules'), './' + filepath); var response = { key: dirname }; fs.readFile(fullpath, 'utf8', function (error, content) { if (error) return callback(error, null); // remove BOM content = removeBOM(content); // use index if filepath is empty var filepath; if (content === '') { filepath = path.resolve(dirname, 'index.js'); } // read JSON file var result; try { result = JSON.parse(content); } catch (e) { return callback(e, null); } if (result.main) { filepath = path.resolve(dirname, result.main); } else { filepath = path.resolve(dirname, './index.js'); } // check that file exist var fullpath = path.resolve(self.piccolo.get('modules'), './' + filepath); fs.exists(fullpath, function (exist) { response.value = exist ? filepath : false; callback(null, response); }); }); } // read all package.json files and resolve the filepath async.map(list, resolvePackage, function (error, list) { if (error) return callback(error, null); var final = {}; list.forEach(function (obj) { final[obj.key] = obj.value; }); // save resolved packageMap self.build.packageMap = final; callback(null, null); }); }
javascript
function buildPackage(callback) { var dirMap = self.build.dirMap, i = dirMap.length, filepath, pkgName = '/package.json', pkgLength = pkgName.length, list = []; // search dirmap for package.json while(i--) { filepath = dirMap[i]; if (filepath.slice(filepath.length - pkgLength, filepath.length) === pkgName) { list.push(filepath); } } function resolvePackage(filepath, callback) { var dirname = filepath.slice(0, filepath.length - pkgLength); var fullpath = path.resolve(self.piccolo.get('modules'), './' + filepath); var response = { key: dirname }; fs.readFile(fullpath, 'utf8', function (error, content) { if (error) return callback(error, null); // remove BOM content = removeBOM(content); // use index if filepath is empty var filepath; if (content === '') { filepath = path.resolve(dirname, 'index.js'); } // read JSON file var result; try { result = JSON.parse(content); } catch (e) { return callback(e, null); } if (result.main) { filepath = path.resolve(dirname, result.main); } else { filepath = path.resolve(dirname, './index.js'); } // check that file exist var fullpath = path.resolve(self.piccolo.get('modules'), './' + filepath); fs.exists(fullpath, function (exist) { response.value = exist ? filepath : false; callback(null, response); }); }); } // read all package.json files and resolve the filepath async.map(list, resolvePackage, function (error, list) { if (error) return callback(error, null); var final = {}; list.forEach(function (obj) { final[obj.key] = obj.value; }); // save resolved packageMap self.build.packageMap = final; callback(null, null); }); }
[ "function", "buildPackage", "(", "callback", ")", "{", "var", "dirMap", "=", "self", ".", "build", ".", "dirMap", ",", "i", "=", "dirMap", ".", "length", ",", "filepath", ",", "pkgName", "=", "'/package.json'", ",", "pkgLength", "=", "pkgName", ".", "length", ",", "list", "=", "[", "]", ";", "// search dirmap for package.json", "while", "(", "i", "--", ")", "{", "filepath", "=", "dirMap", "[", "i", "]", ";", "if", "(", "filepath", ".", "slice", "(", "filepath", ".", "length", "-", "pkgLength", ",", "filepath", ".", "length", ")", "===", "pkgName", ")", "{", "list", ".", "push", "(", "filepath", ")", ";", "}", "}", "function", "resolvePackage", "(", "filepath", ",", "callback", ")", "{", "var", "dirname", "=", "filepath", ".", "slice", "(", "0", ",", "filepath", ".", "length", "-", "pkgLength", ")", ";", "var", "fullpath", "=", "path", ".", "resolve", "(", "self", ".", "piccolo", ".", "get", "(", "'modules'", ")", ",", "'./'", "+", "filepath", ")", ";", "var", "response", "=", "{", "key", ":", "dirname", "}", ";", "fs", ".", "readFile", "(", "fullpath", ",", "'utf8'", ",", "function", "(", "error", ",", "content", ")", "{", "if", "(", "error", ")", "return", "callback", "(", "error", ",", "null", ")", ";", "// remove BOM", "content", "=", "removeBOM", "(", "content", ")", ";", "// use index if filepath is empty", "var", "filepath", ";", "if", "(", "content", "===", "''", ")", "{", "filepath", "=", "path", ".", "resolve", "(", "dirname", ",", "'index.js'", ")", ";", "}", "// read JSON file", "var", "result", ";", "try", "{", "result", "=", "JSON", ".", "parse", "(", "content", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "callback", "(", "e", ",", "null", ")", ";", "}", "if", "(", "result", ".", "main", ")", "{", "filepath", "=", "path", ".", "resolve", "(", "dirname", ",", "result", ".", "main", ")", ";", "}", "else", "{", "filepath", "=", "path", ".", "resolve", "(", "dirname", ",", "'./index.js'", ")", ";", "}", "// check that file exist", "var", "fullpath", "=", "path", ".", "resolve", "(", "self", ".", "piccolo", ".", "get", "(", "'modules'", ")", ",", "'./'", "+", "filepath", ")", ";", "fs", ".", "exists", "(", "fullpath", ",", "function", "(", "exist", ")", "{", "response", ".", "value", "=", "exist", "?", "filepath", ":", "false", ";", "callback", "(", "null", ",", "response", ")", ";", "}", ")", ";", "}", ")", ";", "}", "// read all package.json files and resolve the filepath", "async", ".", "map", "(", "list", ",", "resolvePackage", ",", "function", "(", "error", ",", "list", ")", "{", "if", "(", "error", ")", "return", "callback", "(", "error", ",", "null", ")", ";", "var", "final", "=", "{", "}", ";", "list", ".", "forEach", "(", "function", "(", "obj", ")", "{", "final", "[", "obj", ".", "key", "]", "=", "obj", ".", "value", ";", "}", ")", ";", "// save resolved packageMap", "self", ".", "build", ".", "packageMap", "=", "final", ";", "callback", "(", "null", ",", "null", ")", ";", "}", ")", ";", "}" ]
scan and resolve all packages
[ "scan", "and", "resolve", "all", "packages" ]
ef43f5634c564eef0d21a4a6aa103b2f1e3baa3d
https://github.com/AndreasMadsen/piccolo/blob/ef43f5634c564eef0d21a4a6aa103b2f1e3baa3d/lib/build/dependencies.js#L235-L306
55,642
AndreasMadsen/piccolo
lib/build/dependencies.js
buildMap
function buildMap() { var dependencies = self.build.dependencies = {}; var cacheTime = self.cache.stats; var buildTime = self.build.mtime; Object.keys(cacheTime).forEach(function (filepath) { buildTime[filepath] = cacheTime[filepath].getTime(); }); // deep resolve all dependencies self.build.dirMap.forEach(function (filename) { var list = []; // the result array will be filled by his function deepResolve(self, filename, list); // dry result array var result = dependencies[filename] = []; var i = list.length; while(i--) { if (result.indexOf(list[i]) === -1) { result.push(list[i]); } } }); }
javascript
function buildMap() { var dependencies = self.build.dependencies = {}; var cacheTime = self.cache.stats; var buildTime = self.build.mtime; Object.keys(cacheTime).forEach(function (filepath) { buildTime[filepath] = cacheTime[filepath].getTime(); }); // deep resolve all dependencies self.build.dirMap.forEach(function (filename) { var list = []; // the result array will be filled by his function deepResolve(self, filename, list); // dry result array var result = dependencies[filename] = []; var i = list.length; while(i--) { if (result.indexOf(list[i]) === -1) { result.push(list[i]); } } }); }
[ "function", "buildMap", "(", ")", "{", "var", "dependencies", "=", "self", ".", "build", ".", "dependencies", "=", "{", "}", ";", "var", "cacheTime", "=", "self", ".", "cache", ".", "stats", ";", "var", "buildTime", "=", "self", ".", "build", ".", "mtime", ";", "Object", ".", "keys", "(", "cacheTime", ")", ".", "forEach", "(", "function", "(", "filepath", ")", "{", "buildTime", "[", "filepath", "]", "=", "cacheTime", "[", "filepath", "]", ".", "getTime", "(", ")", ";", "}", ")", ";", "// deep resolve all dependencies", "self", ".", "build", ".", "dirMap", ".", "forEach", "(", "function", "(", "filename", ")", "{", "var", "list", "=", "[", "]", ";", "// the result array will be filled by his function", "deepResolve", "(", "self", ",", "filename", ",", "list", ")", ";", "// dry result array", "var", "result", "=", "dependencies", "[", "filename", "]", "=", "[", "]", ";", "var", "i", "=", "list", ".", "length", ";", "while", "(", "i", "--", ")", "{", "if", "(", "result", ".", "indexOf", "(", "list", "[", "i", "]", ")", "===", "-", "1", ")", "{", "result", ".", "push", "(", "list", "[", "i", "]", ")", ";", "}", "}", "}", ")", ";", "}" ]
rebuild dependency tree
[ "rebuild", "dependency", "tree" ]
ef43f5634c564eef0d21a4a6aa103b2f1e3baa3d
https://github.com/AndreasMadsen/piccolo/blob/ef43f5634c564eef0d21a4a6aa103b2f1e3baa3d/lib/build/dependencies.js#L309-L334
55,643
mgesmundo/authorify-client
lib/class/Handshake.js
function() { var cert = this.keychain.getCertPem(); if (!cert) { throw new CError('missing certificate').log(); } var tmp = this.getDate() + '::' + cert + '::' + SECRET_CLIENT; var hmac = forge.hmac.create(); hmac.start('sha256', SECRET); hmac.update(tmp); return hmac.digest().toHex(); }
javascript
function() { var cert = this.keychain.getCertPem(); if (!cert) { throw new CError('missing certificate').log(); } var tmp = this.getDate() + '::' + cert + '::' + SECRET_CLIENT; var hmac = forge.hmac.create(); hmac.start('sha256', SECRET); hmac.update(tmp); return hmac.digest().toHex(); }
[ "function", "(", ")", "{", "var", "cert", "=", "this", ".", "keychain", ".", "getCertPem", "(", ")", ";", "if", "(", "!", "cert", ")", "{", "throw", "new", "CError", "(", "'missing certificate'", ")", ".", "log", "(", ")", ";", "}", "var", "tmp", "=", "this", ".", "getDate", "(", ")", "+", "'::'", "+", "cert", "+", "'::'", "+", "SECRET_CLIENT", ";", "var", "hmac", "=", "forge", ".", "hmac", ".", "create", "(", ")", ";", "hmac", ".", "start", "(", "'sha256'", ",", "SECRET", ")", ";", "hmac", ".", "update", "(", "tmp", ")", ";", "return", "hmac", ".", "digest", "(", ")", ".", "toHex", "(", ")", ";", "}" ]
Generate a valid token @returns {String} The token
[ "Generate", "a", "valid", "token" ]
39fb57db897eaa49b76444ff62bbc0ccedc7ee16
https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/lib/class/Handshake.js#L60-L70
55,644
mgesmundo/authorify-client
lib/class/Handshake.js
function() { if (this.getMode() !== mode) { throw new CError('unexpected mode').log(); } var cert; try { cert = this.keychain.getCertPem(); } catch (e) { throw new CError({ body: { code: 'ImATeapot', message: 'missing certificate', cause: e } }).log('body'); } if (!cert) { throw new CError('missing certificate').log(); } var out = { mode: this.getMode(), cert: cert }; if (this.getSid()) { out.sid = this.getSid(); } return out; }
javascript
function() { if (this.getMode() !== mode) { throw new CError('unexpected mode').log(); } var cert; try { cert = this.keychain.getCertPem(); } catch (e) { throw new CError({ body: { code: 'ImATeapot', message: 'missing certificate', cause: e } }).log('body'); } if (!cert) { throw new CError('missing certificate').log(); } var out = { mode: this.getMode(), cert: cert }; if (this.getSid()) { out.sid = this.getSid(); } return out; }
[ "function", "(", ")", "{", "if", "(", "this", ".", "getMode", "(", ")", "!==", "mode", ")", "{", "throw", "new", "CError", "(", "'unexpected mode'", ")", ".", "log", "(", ")", ";", "}", "var", "cert", ";", "try", "{", "cert", "=", "this", ".", "keychain", ".", "getCertPem", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "new", "CError", "(", "{", "body", ":", "{", "code", ":", "'ImATeapot'", ",", "message", ":", "'missing certificate'", ",", "cause", ":", "e", "}", "}", ")", ".", "log", "(", "'body'", ")", ";", "}", "if", "(", "!", "cert", ")", "{", "throw", "new", "CError", "(", "'missing certificate'", ")", ".", "log", "(", ")", ";", "}", "var", "out", "=", "{", "mode", ":", "this", ".", "getMode", "(", ")", ",", "cert", ":", "cert", "}", ";", "if", "(", "this", ".", "getSid", "(", ")", ")", "{", "out", ".", "sid", "=", "this", ".", "getSid", "(", ")", ";", "}", "return", "out", ";", "}" ]
Get the payload property of the header @return {Object} The payload property of the header
[ "Get", "the", "payload", "property", "of", "the", "header" ]
39fb57db897eaa49b76444ff62bbc0ccedc7ee16
https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/lib/class/Handshake.js#L76-L103
55,645
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/htmldataprocessor.js
blockFilter
function blockFilter( isOutput, fillEmptyBlock ) { return function( block ) { // DO NOT apply the filler if it's a fragment node. if ( block.type == CKEDITOR.NODE_DOCUMENT_FRAGMENT ) return; cleanBogus( block ); var shouldFillBlock = typeof fillEmptyBlock == 'function' ? fillEmptyBlock( block ) : fillEmptyBlock; if ( shouldFillBlock !== false && isEmptyBlockNeedFiller( block ) ) { block.add( createFiller( isOutput ) ); } }; }
javascript
function blockFilter( isOutput, fillEmptyBlock ) { return function( block ) { // DO NOT apply the filler if it's a fragment node. if ( block.type == CKEDITOR.NODE_DOCUMENT_FRAGMENT ) return; cleanBogus( block ); var shouldFillBlock = typeof fillEmptyBlock == 'function' ? fillEmptyBlock( block ) : fillEmptyBlock; if ( shouldFillBlock !== false && isEmptyBlockNeedFiller( block ) ) { block.add( createFiller( isOutput ) ); } }; }
[ "function", "blockFilter", "(", "isOutput", ",", "fillEmptyBlock", ")", "{", "return", "function", "(", "block", ")", "{", "// DO NOT apply the filler if it's a fragment node.", "if", "(", "block", ".", "type", "==", "CKEDITOR", ".", "NODE_DOCUMENT_FRAGMENT", ")", "return", ";", "cleanBogus", "(", "block", ")", ";", "var", "shouldFillBlock", "=", "typeof", "fillEmptyBlock", "==", "'function'", "?", "fillEmptyBlock", "(", "block", ")", ":", "fillEmptyBlock", ";", "if", "(", "shouldFillBlock", "!==", "false", "&&", "isEmptyBlockNeedFiller", "(", "block", ")", ")", "{", "block", ".", "add", "(", "createFiller", "(", "isOutput", ")", ")", ";", "}", "}", ";", "}" ]
This text block filter, remove any bogus and create the filler on demand.
[ "This", "text", "block", "filter", "remove", "any", "bogus", "and", "create", "the", "filler", "on", "demand", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/htmldataprocessor.js#L308-L323
55,646
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/htmldataprocessor.js
brFilter
function brFilter( isOutput ) { return function( br ) { // DO NOT apply the filer if parent's a fragment node. if ( br.parent.type == CKEDITOR.NODE_DOCUMENT_FRAGMENT ) return; var attrs = br.attributes; // Dismiss BRs that are either bogus or eol marker. if ( 'data-cke-bogus' in attrs || 'data-cke-eol' in attrs ) { delete attrs [ 'data-cke-bogus' ]; return; } // Judge the tail line-break BR, and to insert bogus after it. var next = getNext( br ), previous = getPrevious( br ); if ( !next && isBlockBoundary( br.parent ) ) append( br.parent, createFiller( isOutput ) ); else if ( isBlockBoundary( next ) && previous && !isBlockBoundary( previous ) ) createFiller( isOutput ).insertBefore( next ); }; }
javascript
function brFilter( isOutput ) { return function( br ) { // DO NOT apply the filer if parent's a fragment node. if ( br.parent.type == CKEDITOR.NODE_DOCUMENT_FRAGMENT ) return; var attrs = br.attributes; // Dismiss BRs that are either bogus or eol marker. if ( 'data-cke-bogus' in attrs || 'data-cke-eol' in attrs ) { delete attrs [ 'data-cke-bogus' ]; return; } // Judge the tail line-break BR, and to insert bogus after it. var next = getNext( br ), previous = getPrevious( br ); if ( !next && isBlockBoundary( br.parent ) ) append( br.parent, createFiller( isOutput ) ); else if ( isBlockBoundary( next ) && previous && !isBlockBoundary( previous ) ) createFiller( isOutput ).insertBefore( next ); }; }
[ "function", "brFilter", "(", "isOutput", ")", "{", "return", "function", "(", "br", ")", "{", "// DO NOT apply the filer if parent's a fragment node.", "if", "(", "br", ".", "parent", ".", "type", "==", "CKEDITOR", ".", "NODE_DOCUMENT_FRAGMENT", ")", "return", ";", "var", "attrs", "=", "br", ".", "attributes", ";", "// Dismiss BRs that are either bogus or eol marker.", "if", "(", "'data-cke-bogus'", "in", "attrs", "||", "'data-cke-eol'", "in", "attrs", ")", "{", "delete", "attrs", "[", "'data-cke-bogus'", "]", ";", "return", ";", "}", "// Judge the tail line-break BR, and to insert bogus after it.", "var", "next", "=", "getNext", "(", "br", ")", ",", "previous", "=", "getPrevious", "(", "br", ")", ";", "if", "(", "!", "next", "&&", "isBlockBoundary", "(", "br", ".", "parent", ")", ")", "append", "(", "br", ".", "parent", ",", "createFiller", "(", "isOutput", ")", ")", ";", "else", "if", "(", "isBlockBoundary", "(", "next", ")", "&&", "previous", "&&", "!", "isBlockBoundary", "(", "previous", ")", ")", "createFiller", "(", "isOutput", ")", ".", "insertBefore", "(", "next", ")", ";", "}", ";", "}" ]
Append a filler right after the last line-break BR, found at the end of block.
[ "Append", "a", "filler", "right", "after", "the", "last", "line", "-", "break", "BR", "found", "at", "the", "end", "of", "block", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/htmldataprocessor.js#L326-L347
55,647
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/htmldataprocessor.js
maybeBogus
function maybeBogus( node, atBlockEnd ) { // BR that's not from IE<11 DOM, except for a EOL marker. if ( !( isOutput && !CKEDITOR.env.needsBrFiller ) && node.type == CKEDITOR.NODE_ELEMENT && node.name == 'br' && !node.attributes[ 'data-cke-eol' ] ) { return true; } var match; // NBSP, possibly. if ( node.type == CKEDITOR.NODE_TEXT && ( match = node.value.match( tailNbspRegex ) ) ) { // We need to separate tail NBSP out of a text node, for later removal. if ( match.index ) { ( new CKEDITOR.htmlParser.text( node.value.substring( 0, match.index ) ) ).insertBefore( node ); node.value = match[ 0 ]; } // From IE<11 DOM, at the end of a text block, or before block boundary. if ( !CKEDITOR.env.needsBrFiller && isOutput && ( !atBlockEnd || node.parent.name in textBlockTags ) ) return true; // From the output. if ( !isOutput ) { var previous = node.previous; // Following a line-break at the end of block. if ( previous && previous.name == 'br' ) return true; // Or a single NBSP between two blocks. if ( !previous || isBlockBoundary( previous ) ) return true; } } return false; }
javascript
function maybeBogus( node, atBlockEnd ) { // BR that's not from IE<11 DOM, except for a EOL marker. if ( !( isOutput && !CKEDITOR.env.needsBrFiller ) && node.type == CKEDITOR.NODE_ELEMENT && node.name == 'br' && !node.attributes[ 'data-cke-eol' ] ) { return true; } var match; // NBSP, possibly. if ( node.type == CKEDITOR.NODE_TEXT && ( match = node.value.match( tailNbspRegex ) ) ) { // We need to separate tail NBSP out of a text node, for later removal. if ( match.index ) { ( new CKEDITOR.htmlParser.text( node.value.substring( 0, match.index ) ) ).insertBefore( node ); node.value = match[ 0 ]; } // From IE<11 DOM, at the end of a text block, or before block boundary. if ( !CKEDITOR.env.needsBrFiller && isOutput && ( !atBlockEnd || node.parent.name in textBlockTags ) ) return true; // From the output. if ( !isOutput ) { var previous = node.previous; // Following a line-break at the end of block. if ( previous && previous.name == 'br' ) return true; // Or a single NBSP between two blocks. if ( !previous || isBlockBoundary( previous ) ) return true; } } return false; }
[ "function", "maybeBogus", "(", "node", ",", "atBlockEnd", ")", "{", "// BR that's not from IE<11 DOM, except for a EOL marker.", "if", "(", "!", "(", "isOutput", "&&", "!", "CKEDITOR", ".", "env", ".", "needsBrFiller", ")", "&&", "node", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", "&&", "node", ".", "name", "==", "'br'", "&&", "!", "node", ".", "attributes", "[", "'data-cke-eol'", "]", ")", "{", "return", "true", ";", "}", "var", "match", ";", "// NBSP, possibly.", "if", "(", "node", ".", "type", "==", "CKEDITOR", ".", "NODE_TEXT", "&&", "(", "match", "=", "node", ".", "value", ".", "match", "(", "tailNbspRegex", ")", ")", ")", "{", "// We need to separate tail NBSP out of a text node, for later removal.", "if", "(", "match", ".", "index", ")", "{", "(", "new", "CKEDITOR", ".", "htmlParser", ".", "text", "(", "node", ".", "value", ".", "substring", "(", "0", ",", "match", ".", "index", ")", ")", ")", ".", "insertBefore", "(", "node", ")", ";", "node", ".", "value", "=", "match", "[", "0", "]", ";", "}", "// From IE<11 DOM, at the end of a text block, or before block boundary.", "if", "(", "!", "CKEDITOR", ".", "env", ".", "needsBrFiller", "&&", "isOutput", "&&", "(", "!", "atBlockEnd", "||", "node", ".", "parent", ".", "name", "in", "textBlockTags", ")", ")", "return", "true", ";", "// From the output.", "if", "(", "!", "isOutput", ")", "{", "var", "previous", "=", "node", ".", "previous", ";", "// Following a line-break at the end of block.", "if", "(", "previous", "&&", "previous", ".", "name", "==", "'br'", ")", "return", "true", ";", "// Or a single NBSP between two blocks.", "if", "(", "!", "previous", "||", "isBlockBoundary", "(", "previous", ")", ")", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Determinate whether this node is potentially a bogus node.
[ "Determinate", "whether", "this", "node", "is", "potentially", "a", "bogus", "node", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/htmldataprocessor.js#L350-L388
55,648
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/htmldataprocessor.js
cleanBogus
function cleanBogus( block ) { var bogus = []; var last = getLast( block ), node, previous; if ( last ) { // Check for bogus at the end of this block. // e.g. <p>foo<br /></p> maybeBogus( last, 1 ) && bogus.push( last ); while ( last ) { // Check for bogus at the end of any pseudo block contained. if ( isBlockBoundary( last ) && ( node = getPrevious( last ) ) && maybeBogus( node ) ) { // Bogus must have inline proceeding, instead single BR between two blocks, // is considered as filler, e.g. <hr /><br /><hr /> if ( ( previous = getPrevious( node ) ) && !isBlockBoundary( previous ) ) bogus.push( node ); // Convert the filler into appropriate form. else { createFiller( isOutput ).insertAfter( node ); node.remove(); } } last = last.previous; } } // Now remove all bogus collected from above. for ( var i = 0 ; i < bogus.length ; i++ ) bogus[ i ].remove(); }
javascript
function cleanBogus( block ) { var bogus = []; var last = getLast( block ), node, previous; if ( last ) { // Check for bogus at the end of this block. // e.g. <p>foo<br /></p> maybeBogus( last, 1 ) && bogus.push( last ); while ( last ) { // Check for bogus at the end of any pseudo block contained. if ( isBlockBoundary( last ) && ( node = getPrevious( last ) ) && maybeBogus( node ) ) { // Bogus must have inline proceeding, instead single BR between two blocks, // is considered as filler, e.g. <hr /><br /><hr /> if ( ( previous = getPrevious( node ) ) && !isBlockBoundary( previous ) ) bogus.push( node ); // Convert the filler into appropriate form. else { createFiller( isOutput ).insertAfter( node ); node.remove(); } } last = last.previous; } } // Now remove all bogus collected from above. for ( var i = 0 ; i < bogus.length ; i++ ) bogus[ i ].remove(); }
[ "function", "cleanBogus", "(", "block", ")", "{", "var", "bogus", "=", "[", "]", ";", "var", "last", "=", "getLast", "(", "block", ")", ",", "node", ",", "previous", ";", "if", "(", "last", ")", "{", "// Check for bogus at the end of this block.", "// e.g. <p>foo<br /></p>", "maybeBogus", "(", "last", ",", "1", ")", "&&", "bogus", ".", "push", "(", "last", ")", ";", "while", "(", "last", ")", "{", "// Check for bogus at the end of any pseudo block contained.", "if", "(", "isBlockBoundary", "(", "last", ")", "&&", "(", "node", "=", "getPrevious", "(", "last", ")", ")", "&&", "maybeBogus", "(", "node", ")", ")", "{", "// Bogus must have inline proceeding, instead single BR between two blocks,", "// is considered as filler, e.g. <hr /><br /><hr />", "if", "(", "(", "previous", "=", "getPrevious", "(", "node", ")", ")", "&&", "!", "isBlockBoundary", "(", "previous", ")", ")", "bogus", ".", "push", "(", "node", ")", ";", "// Convert the filler into appropriate form.", "else", "{", "createFiller", "(", "isOutput", ")", ".", "insertAfter", "(", "node", ")", ";", "node", ".", "remove", "(", ")", ";", "}", "}", "last", "=", "last", ".", "previous", ";", "}", "}", "// Now remove all bogus collected from above.", "for", "(", "var", "i", "=", "0", ";", "i", "<", "bogus", ".", "length", ";", "i", "++", ")", "bogus", "[", "i", "]", ".", "remove", "(", ")", ";", "}" ]
Removes all bogus inside of this block, and to convert fillers into the proper form.
[ "Removes", "all", "bogus", "inside", "of", "this", "block", "and", "to", "convert", "fillers", "into", "the", "proper", "form", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/htmldataprocessor.js#L391-L421
55,649
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/htmldataprocessor.js
isEmptyBlockNeedFiller
function isEmptyBlockNeedFiller( block ) { // DO NOT fill empty editable in IE<11. if ( !isOutput && !CKEDITOR.env.needsBrFiller && block.type == CKEDITOR.NODE_DOCUMENT_FRAGMENT ) return false; // 1. For IE version >=8, empty blocks are displayed correctly themself in wysiwiyg; // 2. For the rest, at least table cell and list item need no filler space. (#6248) if ( !isOutput && !CKEDITOR.env.needsBrFiller && ( document.documentMode > 7 || block.name in CKEDITOR.dtd.tr || block.name in CKEDITOR.dtd.$listItem ) ) { return false; } var last = getLast( block ); return !last || block.name == 'form' && last.name == 'input' ; }
javascript
function isEmptyBlockNeedFiller( block ) { // DO NOT fill empty editable in IE<11. if ( !isOutput && !CKEDITOR.env.needsBrFiller && block.type == CKEDITOR.NODE_DOCUMENT_FRAGMENT ) return false; // 1. For IE version >=8, empty blocks are displayed correctly themself in wysiwiyg; // 2. For the rest, at least table cell and list item need no filler space. (#6248) if ( !isOutput && !CKEDITOR.env.needsBrFiller && ( document.documentMode > 7 || block.name in CKEDITOR.dtd.tr || block.name in CKEDITOR.dtd.$listItem ) ) { return false; } var last = getLast( block ); return !last || block.name == 'form' && last.name == 'input' ; }
[ "function", "isEmptyBlockNeedFiller", "(", "block", ")", "{", "// DO NOT fill empty editable in IE<11.", "if", "(", "!", "isOutput", "&&", "!", "CKEDITOR", ".", "env", ".", "needsBrFiller", "&&", "block", ".", "type", "==", "CKEDITOR", ".", "NODE_DOCUMENT_FRAGMENT", ")", "return", "false", ";", "// 1. For IE version >=8, empty blocks are displayed correctly themself in wysiwiyg;", "// 2. For the rest, at least table cell and list item need no filler space. (#6248)", "if", "(", "!", "isOutput", "&&", "!", "CKEDITOR", ".", "env", ".", "needsBrFiller", "&&", "(", "document", ".", "documentMode", ">", "7", "||", "block", ".", "name", "in", "CKEDITOR", ".", "dtd", ".", "tr", "||", "block", ".", "name", "in", "CKEDITOR", ".", "dtd", ".", "$listItem", ")", ")", "{", "return", "false", ";", "}", "var", "last", "=", "getLast", "(", "block", ")", ";", "return", "!", "last", "||", "block", ".", "name", "==", "'form'", "&&", "last", ".", "name", "==", "'input'", ";", "}" ]
Judge whether it's an empty block that requires a filler node.
[ "Judge", "whether", "it", "s", "an", "empty", "block", "that", "requires", "a", "filler", "node", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/htmldataprocessor.js#L424-L441
55,650
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/htmldataprocessor.js
isEmpty
function isEmpty( node ) { return node.type == CKEDITOR.NODE_TEXT && !CKEDITOR.tools.trim( node.value ) || node.type == CKEDITOR.NODE_ELEMENT && node.attributes[ 'data-cke-bookmark' ]; }
javascript
function isEmpty( node ) { return node.type == CKEDITOR.NODE_TEXT && !CKEDITOR.tools.trim( node.value ) || node.type == CKEDITOR.NODE_ELEMENT && node.attributes[ 'data-cke-bookmark' ]; }
[ "function", "isEmpty", "(", "node", ")", "{", "return", "node", ".", "type", "==", "CKEDITOR", ".", "NODE_TEXT", "&&", "!", "CKEDITOR", ".", "tools", ".", "trim", "(", "node", ".", "value", ")", "||", "node", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", "&&", "node", ".", "attributes", "[", "'data-cke-bookmark'", "]", ";", "}" ]
Judge whether the node is an ghost node to be ignored, when traversing.
[ "Judge", "whether", "the", "node", "is", "an", "ghost", "node", "to", "be", "ignored", "when", "traversing", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/htmldataprocessor.js#L494-L499
55,651
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/htmldataprocessor.js
isBlockBoundary
function isBlockBoundary( node ) { return node && ( node.type == CKEDITOR.NODE_ELEMENT && node.name in blockLikeTags || node.type == CKEDITOR.NODE_DOCUMENT_FRAGMENT ); }
javascript
function isBlockBoundary( node ) { return node && ( node.type == CKEDITOR.NODE_ELEMENT && node.name in blockLikeTags || node.type == CKEDITOR.NODE_DOCUMENT_FRAGMENT ); }
[ "function", "isBlockBoundary", "(", "node", ")", "{", "return", "node", "&&", "(", "node", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", "&&", "node", ".", "name", "in", "blockLikeTags", "||", "node", ".", "type", "==", "CKEDITOR", ".", "NODE_DOCUMENT_FRAGMENT", ")", ";", "}" ]
Judge whether the node is a block-like element.
[ "Judge", "whether", "the", "node", "is", "a", "block", "-", "like", "element", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/htmldataprocessor.js#L502-L506
55,652
stefanmintert/ep_xmlexport
PadProcessor.js
function(regex, text){ var nextIndex = 0; var result = []; var execResult; while ((execResult = regex.exec(text))!== null) { result.push({ start: execResult.index, matchLength: execResult[0].length}); } return { next: function(){ return nextIndex < result.length ? result[nextIndex++] : null; } }; }
javascript
function(regex, text){ var nextIndex = 0; var result = []; var execResult; while ((execResult = regex.exec(text))!== null) { result.push({ start: execResult.index, matchLength: execResult[0].length}); } return { next: function(){ return nextIndex < result.length ? result[nextIndex++] : null; } }; }
[ "function", "(", "regex", ",", "text", ")", "{", "var", "nextIndex", "=", "0", ";", "var", "result", "=", "[", "]", ";", "var", "execResult", ";", "while", "(", "(", "execResult", "=", "regex", ".", "exec", "(", "text", ")", ")", "!==", "null", ")", "{", "result", ".", "push", "(", "{", "start", ":", "execResult", ".", "index", ",", "matchLength", ":", "execResult", "[", "0", "]", ".", "length", "}", ")", ";", "}", "return", "{", "next", ":", "function", "(", ")", "{", "return", "nextIndex", "<", "result", ".", "length", "?", "result", "[", "nextIndex", "++", "]", ":", "null", ";", "}", "}", ";", "}" ]
this is a convenience regex matcher that iterates through the matches and returns each start index and length @param {RegExp} regex @param {String} text
[ "this", "is", "a", "convenience", "regex", "matcher", "that", "iterates", "through", "the", "matches", "and", "returns", "each", "start", "index", "and", "length" ]
c46a742b66bc048453ebe26c7b3fbd710ae8f7c4
https://github.com/stefanmintert/ep_xmlexport/blob/c46a742b66bc048453ebe26c7b3fbd710ae8f7c4/PadProcessor.js#L31-L49
55,653
TyphosLabs/api-gateway-errors
index.js
lambdaError
function lambdaError(fn, settings){ var log = (settings && settings.log === false ? false : true); var map = (settings && settings.map ? settings.map : undefined); var exclude = (settings && settings.exclude ? settings.exclude : undefined); return (event, context, callback) => { fn(event, context, (err, result) => { if(err){ if(log){ console.error(Errors.stack(err)); } if(typeof err !== 'object'){ console.error('Error must be an object:', err); err = new InvalidErrorValue(err); } return callback(Errors.json(err, false, map, exclude)); } return callback(null, result); }); }; }
javascript
function lambdaError(fn, settings){ var log = (settings && settings.log === false ? false : true); var map = (settings && settings.map ? settings.map : undefined); var exclude = (settings && settings.exclude ? settings.exclude : undefined); return (event, context, callback) => { fn(event, context, (err, result) => { if(err){ if(log){ console.error(Errors.stack(err)); } if(typeof err !== 'object'){ console.error('Error must be an object:', err); err = new InvalidErrorValue(err); } return callback(Errors.json(err, false, map, exclude)); } return callback(null, result); }); }; }
[ "function", "lambdaError", "(", "fn", ",", "settings", ")", "{", "var", "log", "=", "(", "settings", "&&", "settings", ".", "log", "===", "false", "?", "false", ":", "true", ")", ";", "var", "map", "=", "(", "settings", "&&", "settings", ".", "map", "?", "settings", ".", "map", ":", "undefined", ")", ";", "var", "exclude", "=", "(", "settings", "&&", "settings", ".", "exclude", "?", "settings", ".", "exclude", ":", "undefined", ")", ";", "return", "(", "event", ",", "context", ",", "callback", ")", "=>", "{", "fn", "(", "event", ",", "context", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "err", ")", "{", "if", "(", "log", ")", "{", "console", ".", "error", "(", "Errors", ".", "stack", "(", "err", ")", ")", ";", "}", "if", "(", "typeof", "err", "!==", "'object'", ")", "{", "console", ".", "error", "(", "'Error must be an object:'", ",", "err", ")", ";", "err", "=", "new", "InvalidErrorValue", "(", "err", ")", ";", "}", "return", "callback", "(", "Errors", ".", "json", "(", "err", ",", "false", ",", "map", ",", "exclude", ")", ")", ";", "}", "return", "callback", "(", "null", ",", "result", ")", ";", "}", ")", ";", "}", ";", "}" ]
Wrap all API Gateway lambda handlers with this function. @param {Function} fn - AWS lambda handler function to wrap. @param {Object} setting - @param {boolean} setting.log - Whether or not to log errors to console. @returns {Function}
[ "Wrap", "all", "API", "Gateway", "lambda", "handlers", "with", "this", "function", "." ]
82bf92c7e7402d4f4e311ad47cc7652efdf863b7
https://github.com/TyphosLabs/api-gateway-errors/blob/82bf92c7e7402d4f4e311ad47cc7652efdf863b7/index.js#L24-L47
55,654
ugate/pulses
lib/platelets.js
asyncd
function asyncd(pw, evts, fname, args) { var es = Array.isArray(evts) ? evts : [evts]; for (var i = 0; i < es.length; i++) { if (es[i]) { defer(asyncCb.bind(es[i])); } } function asyncCb() { var argsp = args && args.length ? [this] : null; if (argsp) { argsp.push.apply(argsp, args); pw[fname].apply(pw, argsp); } else pw[fname](this); } return pw; }
javascript
function asyncd(pw, evts, fname, args) { var es = Array.isArray(evts) ? evts : [evts]; for (var i = 0; i < es.length; i++) { if (es[i]) { defer(asyncCb.bind(es[i])); } } function asyncCb() { var argsp = args && args.length ? [this] : null; if (argsp) { argsp.push.apply(argsp, args); pw[fname].apply(pw, argsp); } else pw[fname](this); } return pw; }
[ "function", "asyncd", "(", "pw", ",", "evts", ",", "fname", ",", "args", ")", "{", "var", "es", "=", "Array", ".", "isArray", "(", "evts", ")", "?", "evts", ":", "[", "evts", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "es", ".", "length", ";", "i", "++", ")", "{", "if", "(", "es", "[", "i", "]", ")", "{", "defer", "(", "asyncCb", ".", "bind", "(", "es", "[", "i", "]", ")", ")", ";", "}", "}", "function", "asyncCb", "(", ")", "{", "var", "argsp", "=", "args", "&&", "args", ".", "length", "?", "[", "this", "]", ":", "null", ";", "if", "(", "argsp", ")", "{", "argsp", ".", "push", ".", "apply", "(", "argsp", ",", "args", ")", ";", "pw", "[", "fname", "]", ".", "apply", "(", "pw", ",", "argsp", ")", ";", "}", "else", "pw", "[", "fname", "]", "(", "this", ")", ";", "}", "return", "pw", ";", "}" ]
Executes one or more events an asynchronously @arg {PulseEmitter} pw the pulse emitter @arg {(String | Array)} evts the event or array of events @arg {String} fname the function name to execute on the pulse emitter @arg {*[]} args the arguments to pass into the pulse emitter function @returns {PulseEmitter} the pulse emitter
[ "Executes", "one", "or", "more", "events", "an", "asynchronously" ]
214b186e1b72bed9c99c0a7903c70de4eca3c259
https://github.com/ugate/pulses/blob/214b186e1b72bed9c99c0a7903c70de4eca3c259/lib/platelets.js#L25-L40
55,655
ugate/pulses
lib/platelets.js
defer
function defer(cb) { if (!defer.nextLoop) { var ntv = typeof setImmediate === 'function'; defer.nextLoop = ntv ? setImmediate : function setImmediateShim(cb) { if (defer.obj) { if (!defer.cbs.length) { defer.obj.setAttribute('cnt', 'inc'); } defer.cbs.push(cb); } else { setTimeout(cb, 0); } }; if (!ntv && typeof MutationObserver === 'object' && typeof document === 'object') { defer.cbs = []; defer.obj = document.createElement('div'); defer.ob = new MutationObserver(function mutations() { for (var cbl = defer.cbs.slice(), i = defer.cbs.length = 0, l = cbl.length; i < l; i++) { cbl[i](); } }).observe(defer.obj, { attributes: true }); } } return defer.nextLoop.call(null, cb); }
javascript
function defer(cb) { if (!defer.nextLoop) { var ntv = typeof setImmediate === 'function'; defer.nextLoop = ntv ? setImmediate : function setImmediateShim(cb) { if (defer.obj) { if (!defer.cbs.length) { defer.obj.setAttribute('cnt', 'inc'); } defer.cbs.push(cb); } else { setTimeout(cb, 0); } }; if (!ntv && typeof MutationObserver === 'object' && typeof document === 'object') { defer.cbs = []; defer.obj = document.createElement('div'); defer.ob = new MutationObserver(function mutations() { for (var cbl = defer.cbs.slice(), i = defer.cbs.length = 0, l = cbl.length; i < l; i++) { cbl[i](); } }).observe(defer.obj, { attributes: true }); } } return defer.nextLoop.call(null, cb); }
[ "function", "defer", "(", "cb", ")", "{", "if", "(", "!", "defer", ".", "nextLoop", ")", "{", "var", "ntv", "=", "typeof", "setImmediate", "===", "'function'", ";", "defer", ".", "nextLoop", "=", "ntv", "?", "setImmediate", ":", "function", "setImmediateShim", "(", "cb", ")", "{", "if", "(", "defer", ".", "obj", ")", "{", "if", "(", "!", "defer", ".", "cbs", ".", "length", ")", "{", "defer", ".", "obj", ".", "setAttribute", "(", "'cnt'", ",", "'inc'", ")", ";", "}", "defer", ".", "cbs", ".", "push", "(", "cb", ")", ";", "}", "else", "{", "setTimeout", "(", "cb", ",", "0", ")", ";", "}", "}", ";", "if", "(", "!", "ntv", "&&", "typeof", "MutationObserver", "===", "'object'", "&&", "typeof", "document", "===", "'object'", ")", "{", "defer", ".", "cbs", "=", "[", "]", ";", "defer", ".", "obj", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "defer", ".", "ob", "=", "new", "MutationObserver", "(", "function", "mutations", "(", ")", "{", "for", "(", "var", "cbl", "=", "defer", ".", "cbs", ".", "slice", "(", ")", ",", "i", "=", "defer", ".", "cbs", ".", "length", "=", "0", ",", "l", "=", "cbl", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "cbl", "[", "i", "]", "(", ")", ";", "}", "}", ")", ".", "observe", "(", "defer", ".", "obj", ",", "{", "attributes", ":", "true", "}", ")", ";", "}", "}", "return", "defer", ".", "nextLoop", ".", "call", "(", "null", ",", "cb", ")", ";", "}" ]
Defers a function's execution to the next iteration in the event loop @arg {function} cb the callback function @returns {Object} the callback's return value
[ "Defers", "a", "function", "s", "execution", "to", "the", "next", "iteration", "in", "the", "event", "loop" ]
214b186e1b72bed9c99c0a7903c70de4eca3c259
https://github.com/ugate/pulses/blob/214b186e1b72bed9c99c0a7903c70de4eca3c259/lib/platelets.js#L48-L72
55,656
ugate/pulses
lib/platelets.js
merge
function merge(dest, src, ctyp, nou, non) { if (!src || typeof src !== 'object') return dest; var keys = Object.keys(src); var i = keys.length, dt; while (i--) { if (isNaN(keys[i]) && src.hasOwnProperty(keys[i]) && (!nou || (nou && typeof src[keys[i]] !== 'undefined')) && (!non || (non && src[keys[i]] !== null))) { if (ctyp && dest[keys[i]] != null && (dt = typeof dest[keys[i]]) !== 'undefined' && dt !== typeof src[keys[i]]) { continue; } dest[keys[i]] = src[keys[i]]; } } return dest; }
javascript
function merge(dest, src, ctyp, nou, non) { if (!src || typeof src !== 'object') return dest; var keys = Object.keys(src); var i = keys.length, dt; while (i--) { if (isNaN(keys[i]) && src.hasOwnProperty(keys[i]) && (!nou || (nou && typeof src[keys[i]] !== 'undefined')) && (!non || (non && src[keys[i]] !== null))) { if (ctyp && dest[keys[i]] != null && (dt = typeof dest[keys[i]]) !== 'undefined' && dt !== typeof src[keys[i]]) { continue; } dest[keys[i]] = src[keys[i]]; } } return dest; }
[ "function", "merge", "(", "dest", ",", "src", ",", "ctyp", ",", "nou", ",", "non", ")", "{", "if", "(", "!", "src", "||", "typeof", "src", "!==", "'object'", ")", "return", "dest", ";", "var", "keys", "=", "Object", ".", "keys", "(", "src", ")", ";", "var", "i", "=", "keys", ".", "length", ",", "dt", ";", "while", "(", "i", "--", ")", "{", "if", "(", "isNaN", "(", "keys", "[", "i", "]", ")", "&&", "src", ".", "hasOwnProperty", "(", "keys", "[", "i", "]", ")", "&&", "(", "!", "nou", "||", "(", "nou", "&&", "typeof", "src", "[", "keys", "[", "i", "]", "]", "!==", "'undefined'", ")", ")", "&&", "(", "!", "non", "||", "(", "non", "&&", "src", "[", "keys", "[", "i", "]", "]", "!==", "null", ")", ")", ")", "{", "if", "(", "ctyp", "&&", "dest", "[", "keys", "[", "i", "]", "]", "!=", "null", "&&", "(", "dt", "=", "typeof", "dest", "[", "keys", "[", "i", "]", "]", ")", "!==", "'undefined'", "&&", "dt", "!==", "typeof", "src", "[", "keys", "[", "i", "]", "]", ")", "{", "continue", ";", "}", "dest", "[", "keys", "[", "i", "]", "]", "=", "src", "[", "keys", "[", "i", "]", "]", ";", "}", "}", "return", "dest", ";", "}" ]
Merges an object with the properties of another object @arg {Object} dest the destination object where the properties will be added @arg {Object} src the source object that will be used for adding new properties to the destination @arg {Boolean} ctyp flag that ensures that source values are constrained to the same type as the destination values when present @arg {Boolean} nou flag that prevents merge of undefined values @arg {Boolean} non flag that prevents merge of null values @returns {Object} the destination object
[ "Merges", "an", "object", "with", "the", "properties", "of", "another", "object" ]
214b186e1b72bed9c99c0a7903c70de4eca3c259
https://github.com/ugate/pulses/blob/214b186e1b72bed9c99c0a7903c70de4eca3c259/lib/platelets.js#L113-L128
55,657
ugate/pulses
lib/platelets.js
props
function props(dest, pds, src, isrc, ndflt, nm, nmsrc) { var asrt = nm && src; if (asrt) assert.ok(dest, 'no ' + nm); var i = pds.length; while (i--) { if (asrt) prop(dest, pds[i], src, isrc, ndflt, nm, nmsrc); else prop(dest, pds[i], src, isrc, ndflt); } return dest; }
javascript
function props(dest, pds, src, isrc, ndflt, nm, nmsrc) { var asrt = nm && src; if (asrt) assert.ok(dest, 'no ' + nm); var i = pds.length; while (i--) { if (asrt) prop(dest, pds[i], src, isrc, ndflt, nm, nmsrc); else prop(dest, pds[i], src, isrc, ndflt); } return dest; }
[ "function", "props", "(", "dest", ",", "pds", ",", "src", ",", "isrc", ",", "ndflt", ",", "nm", ",", "nmsrc", ")", "{", "var", "asrt", "=", "nm", "&&", "src", ";", "if", "(", "asrt", ")", "assert", ".", "ok", "(", "dest", ",", "'no '", "+", "nm", ")", ";", "var", "i", "=", "pds", ".", "length", ";", "while", "(", "i", "--", ")", "{", "if", "(", "asrt", ")", "prop", "(", "dest", ",", "pds", "[", "i", "]", ",", "src", ",", "isrc", ",", "ndflt", ",", "nm", ",", "nmsrc", ")", ";", "else", "prop", "(", "dest", ",", "pds", "[", "i", "]", ",", "src", ",", "isrc", ",", "ndflt", ")", ";", "}", "return", "dest", ";", "}" ]
Assigns property values on a destination object or asserts that the destination object properties are within the defined boundaries when a source object is passed along with its name @arg {Object} dest the object to assign properties to or assert properties for @arg {Object[]} pds property definition objects that determine which properties will be assigned or asserted @arg {String} pds[].n the name of the property that will be assigned or asserted @arg {*} [pds[].d] a default value that will be used when there is no property defined on the source object (assignment only) @arg {Boolean} [pds[].i] true to inherit value from the passed source object (assignment only) @arg {Number} [pds[].l] when the property is a number, the lowest acceptable numeric value for the property (assignment only) @arg {Number} [pds[].h] when the property is a number, the highest acceptable numeric value for the property (assignment only) @arg {Object[]} [pd.r] a range of valid values that the property value will be restricted to (assignment only) @arg {*} [pd.c] a reference object that will be used to constrain the destination property to (uses typeof and Array.isArray- assignment only) @arg {Object} [src] source object that will be used for default property values or when assertion will be used for equallity @arg {Boolean} [isrc] true to always inherit from the source object properties when the value is not undefined, regardless of property definition (assignment only) @arg {String} [nm] a name used for the object (assertion only) @arg {String} [nmsrc] a name used for the source object (assertion only) @returns {Object} the passed object
[ "Assigns", "property", "values", "on", "a", "destination", "object", "or", "asserts", "that", "the", "destination", "object", "properties", "are", "within", "the", "defined", "boundaries", "when", "a", "source", "object", "is", "passed", "along", "with", "its", "name" ]
214b186e1b72bed9c99c0a7903c70de4eca3c259
https://github.com/ugate/pulses/blob/214b186e1b72bed9c99c0a7903c70de4eca3c259/lib/platelets.js#L148-L157
55,658
ugate/pulses
lib/platelets.js
prop
function prop(dest, pd, src, isrc, ndflt, nm, nmsrc) { if (nm && src) { assert.strictEqual(dest[pd.n], src[pd.n], (nm ? nm + '.' : '') + pd.n + ': ' + dest[pd.n] + ' !== ' + (nmsrc ? nmsrc + '.' : '') + pd.n + ': ' + src[pd.n]); } else { var dtyp = (dest && typeof dest[pd.n]) || '', vtyp, v, useObj = pd.v && Array.isArray(pd.v); if (dtyp === 'undefined') v = (src && (isrc || pd.i) && (!useObj || typeof src[pd.n] === 'object') ? src[pd.n] : null) || (ndflt ? undefined : pd.d); else if (!useObj && dtyp === 'number') v = typeof pd.l === 'number' && dest[pd.n] < pd.l ? pd.l : typeof pd.h === 'number' && dest[pd.n] > pd.h ? pd.h : undefined; else if (useObj && dtyp === 'object') v = props(dest[pd.n], pd.v, src[pd.n], isrc, ndflt, nm, nmsrc); if ((vtyp = typeof v) !== 'undefined' && (!pd.r || !!~pd.r.indexOf(v))) { if (!pd.c || (vtyp === typeof pd.c && Array.isArray(pd.c) === Array.isArray(v))) dest[pd.n] = v; } } return dest; }
javascript
function prop(dest, pd, src, isrc, ndflt, nm, nmsrc) { if (nm && src) { assert.strictEqual(dest[pd.n], src[pd.n], (nm ? nm + '.' : '') + pd.n + ': ' + dest[pd.n] + ' !== ' + (nmsrc ? nmsrc + '.' : '') + pd.n + ': ' + src[pd.n]); } else { var dtyp = (dest && typeof dest[pd.n]) || '', vtyp, v, useObj = pd.v && Array.isArray(pd.v); if (dtyp === 'undefined') v = (src && (isrc || pd.i) && (!useObj || typeof src[pd.n] === 'object') ? src[pd.n] : null) || (ndflt ? undefined : pd.d); else if (!useObj && dtyp === 'number') v = typeof pd.l === 'number' && dest[pd.n] < pd.l ? pd.l : typeof pd.h === 'number' && dest[pd.n] > pd.h ? pd.h : undefined; else if (useObj && dtyp === 'object') v = props(dest[pd.n], pd.v, src[pd.n], isrc, ndflt, nm, nmsrc); if ((vtyp = typeof v) !== 'undefined' && (!pd.r || !!~pd.r.indexOf(v))) { if (!pd.c || (vtyp === typeof pd.c && Array.isArray(pd.c) === Array.isArray(v))) dest[pd.n] = v; } } return dest; }
[ "function", "prop", "(", "dest", ",", "pd", ",", "src", ",", "isrc", ",", "ndflt", ",", "nm", ",", "nmsrc", ")", "{", "if", "(", "nm", "&&", "src", ")", "{", "assert", ".", "strictEqual", "(", "dest", "[", "pd", ".", "n", "]", ",", "src", "[", "pd", ".", "n", "]", ",", "(", "nm", "?", "nm", "+", "'.'", ":", "''", ")", "+", "pd", ".", "n", "+", "': '", "+", "dest", "[", "pd", ".", "n", "]", "+", "' !== '", "+", "(", "nmsrc", "?", "nmsrc", "+", "'.'", ":", "''", ")", "+", "pd", ".", "n", "+", "': '", "+", "src", "[", "pd", ".", "n", "]", ")", ";", "}", "else", "{", "var", "dtyp", "=", "(", "dest", "&&", "typeof", "dest", "[", "pd", ".", "n", "]", ")", "||", "''", ",", "vtyp", ",", "v", ",", "useObj", "=", "pd", ".", "v", "&&", "Array", ".", "isArray", "(", "pd", ".", "v", ")", ";", "if", "(", "dtyp", "===", "'undefined'", ")", "v", "=", "(", "src", "&&", "(", "isrc", "||", "pd", ".", "i", ")", "&&", "(", "!", "useObj", "||", "typeof", "src", "[", "pd", ".", "n", "]", "===", "'object'", ")", "?", "src", "[", "pd", ".", "n", "]", ":", "null", ")", "||", "(", "ndflt", "?", "undefined", ":", "pd", ".", "d", ")", ";", "else", "if", "(", "!", "useObj", "&&", "dtyp", "===", "'number'", ")", "v", "=", "typeof", "pd", ".", "l", "===", "'number'", "&&", "dest", "[", "pd", ".", "n", "]", "<", "pd", ".", "l", "?", "pd", ".", "l", ":", "typeof", "pd", ".", "h", "===", "'number'", "&&", "dest", "[", "pd", ".", "n", "]", ">", "pd", ".", "h", "?", "pd", ".", "h", ":", "undefined", ";", "else", "if", "(", "useObj", "&&", "dtyp", "===", "'object'", ")", "v", "=", "props", "(", "dest", "[", "pd", ".", "n", "]", ",", "pd", ".", "v", ",", "src", "[", "pd", ".", "n", "]", ",", "isrc", ",", "ndflt", ",", "nm", ",", "nmsrc", ")", ";", "if", "(", "(", "vtyp", "=", "typeof", "v", ")", "!==", "'undefined'", "&&", "(", "!", "pd", ".", "r", "||", "!", "!", "~", "pd", ".", "r", ".", "indexOf", "(", "v", ")", ")", ")", "{", "if", "(", "!", "pd", ".", "c", "||", "(", "vtyp", "===", "typeof", "pd", ".", "c", "&&", "Array", ".", "isArray", "(", "pd", ".", "c", ")", "===", "Array", ".", "isArray", "(", "v", ")", ")", ")", "dest", "[", "pd", ".", "n", "]", "=", "v", ";", "}", "}", "return", "dest", ";", "}" ]
Assigns a property value on a destination object or asserts that the destination object property is within the defined boundaries when a source object is passed along with its name @arg {Object} dest the object to assign properties to or assert properties for @arg {Object} pd the property definition that determine which property will be assigned or asserted @arg {String} pd.n the name of the property that will be assigned or asserted @arg {*} [pd.d] a default value that will be used when there is no property defined on the source object (assignment only) @arg {Boolean} [pd.i] true to inherit value from the passed source object (assignment only) @arg {Number} [pd.l] when the property is a number, the lowest acceptable numeric value for the property (assignment only) @arg {Number} [pd.h] when the property is a number, the highest acceptable numeric value for the property (assignment only) @arg {Object[]} [pd.r] a range of valid values that the property value will be restricted to (assignment only) @arg {*} [pd.c] a reference object that will be used to constrain the destination property to (uses typeof and Array.isArray- assignment only) @arg {Object} [src] source object that will be used for default property values or when assertion will be used for equallity @arg {Boolean} [isrc] true to always inherit from the source object properties when the value is not undefined, regardless of property definition (assignment only) @arg {String} [nm] a name assigned to the object (assertion only) @arg {String} [nmsrc] a name assigned to the source object (assertion only) @returns {Object} the passed object
[ "Assigns", "a", "property", "value", "on", "a", "destination", "object", "or", "asserts", "that", "the", "destination", "object", "property", "is", "within", "the", "defined", "boundaries", "when", "a", "source", "object", "is", "passed", "along", "with", "its", "name" ]
214b186e1b72bed9c99c0a7903c70de4eca3c259
https://github.com/ugate/pulses/blob/214b186e1b72bed9c99c0a7903c70de4eca3c259/lib/platelets.js#L177-L191
55,659
icanjs/grid-filter
src/grid-filter.js
function(el){ var self = this; var $input = $('input.tokenSearch', el); var suggestions = new can.List([]); this.viewModel.attr('searchInput', $input); // http://loopj.com/jquery-tokeninput/ $input.tokenInput(suggestions, { theme: 'facebook', placeholder:'Search...', preventDuplicates: true, allowFreeTagging:true, tokenLimit:3, allowTabOut:false, /** * onResult is used to pre-process suggestions. * In our case we want to show current item if there is no results. */ onResult: function (item) { if($.isEmptyObject(item)){ var tempObj={ id: $('input:first', el).val(), name: $('input:first', el).val()}; return [tempObj]; }else{ return item; } }, /** * onAdd is used to maintain the suggestion dropdown box and the searchTerms in the scope. * It is called internally by the jquery.tokenInput plugin when either the enter key * is pressed in the input box or a selection is made in the suggestions dropdown. */ onAdd: function (item) { // Check if it already exists in the suggestions list. Duplicates aren't allowed. var exists = false; for(var j = 0; j < suggestions.length; j++){ if(suggestions[j].attr('name').toLowerCase() === item.name.toLowerCase()){ exists=true; break; } } // If it didn't exist, add it to the list of suggestions and the searchTerms. if(!exists){ suggestions.push(item); } // We are using searchTerms's setter to execute the filter, so have to set the property (not just update): var searchTerms = self.viewModel.attr('searchTerms').attr().concat(item.name); self.viewModel.attr('searchTerms', searchTerms); }, /** * onDelete is used to remove items from searchTerms in the scope. It is called internally * by the jquery.tokenInput plugin when a tag gets removed from the input box. */ onDelete: function (item) { var searchTerms = self.viewModel.attr('searchTerms').attr(), searchTerm = item && (item.id || item.name || item); searchTerms.splice(searchTerms.indexOf(searchTerm), 1); // We are using searchTerms's setter to execute the filter, so have to set the property (not just update): self.viewModel.attr('searchTerms', searchTerms); } }); }
javascript
function(el){ var self = this; var $input = $('input.tokenSearch', el); var suggestions = new can.List([]); this.viewModel.attr('searchInput', $input); // http://loopj.com/jquery-tokeninput/ $input.tokenInput(suggestions, { theme: 'facebook', placeholder:'Search...', preventDuplicates: true, allowFreeTagging:true, tokenLimit:3, allowTabOut:false, /** * onResult is used to pre-process suggestions. * In our case we want to show current item if there is no results. */ onResult: function (item) { if($.isEmptyObject(item)){ var tempObj={ id: $('input:first', el).val(), name: $('input:first', el).val()}; return [tempObj]; }else{ return item; } }, /** * onAdd is used to maintain the suggestion dropdown box and the searchTerms in the scope. * It is called internally by the jquery.tokenInput plugin when either the enter key * is pressed in the input box or a selection is made in the suggestions dropdown. */ onAdd: function (item) { // Check if it already exists in the suggestions list. Duplicates aren't allowed. var exists = false; for(var j = 0; j < suggestions.length; j++){ if(suggestions[j].attr('name').toLowerCase() === item.name.toLowerCase()){ exists=true; break; } } // If it didn't exist, add it to the list of suggestions and the searchTerms. if(!exists){ suggestions.push(item); } // We are using searchTerms's setter to execute the filter, so have to set the property (not just update): var searchTerms = self.viewModel.attr('searchTerms').attr().concat(item.name); self.viewModel.attr('searchTerms', searchTerms); }, /** * onDelete is used to remove items from searchTerms in the scope. It is called internally * by the jquery.tokenInput plugin when a tag gets removed from the input box. */ onDelete: function (item) { var searchTerms = self.viewModel.attr('searchTerms').attr(), searchTerm = item && (item.id || item.name || item); searchTerms.splice(searchTerms.indexOf(searchTerm), 1); // We are using searchTerms's setter to execute the filter, so have to set the property (not just update): self.viewModel.attr('searchTerms', searchTerms); } }); }
[ "function", "(", "el", ")", "{", "var", "self", "=", "this", ";", "var", "$input", "=", "$", "(", "'input.tokenSearch'", ",", "el", ")", ";", "var", "suggestions", "=", "new", "can", ".", "List", "(", "[", "]", ")", ";", "this", ".", "viewModel", ".", "attr", "(", "'searchInput'", ",", "$input", ")", ";", "// http://loopj.com/jquery-tokeninput/", "$input", ".", "tokenInput", "(", "suggestions", ",", "{", "theme", ":", "'facebook'", ",", "placeholder", ":", "'Search...'", ",", "preventDuplicates", ":", "true", ",", "allowFreeTagging", ":", "true", ",", "tokenLimit", ":", "3", ",", "allowTabOut", ":", "false", ",", "/**\n * onResult is used to pre-process suggestions.\n * In our case we want to show current item if there is no results.\n */", "onResult", ":", "function", "(", "item", ")", "{", "if", "(", "$", ".", "isEmptyObject", "(", "item", ")", ")", "{", "var", "tempObj", "=", "{", "id", ":", "$", "(", "'input:first'", ",", "el", ")", ".", "val", "(", ")", ",", "name", ":", "$", "(", "'input:first'", ",", "el", ")", ".", "val", "(", ")", "}", ";", "return", "[", "tempObj", "]", ";", "}", "else", "{", "return", "item", ";", "}", "}", ",", "/**\n * onAdd is used to maintain the suggestion dropdown box and the searchTerms in the scope. \n * It is called internally by the jquery.tokenInput plugin when either the enter key \n * is pressed in the input box or a selection is made in the suggestions dropdown.\n */", "onAdd", ":", "function", "(", "item", ")", "{", "// Check if it already exists in the suggestions list. Duplicates aren't allowed.", "var", "exists", "=", "false", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "suggestions", ".", "length", ";", "j", "++", ")", "{", "if", "(", "suggestions", "[", "j", "]", ".", "attr", "(", "'name'", ")", ".", "toLowerCase", "(", ")", "===", "item", ".", "name", ".", "toLowerCase", "(", ")", ")", "{", "exists", "=", "true", ";", "break", ";", "}", "}", "// If it didn't exist, add it to the list of suggestions and the searchTerms.", "if", "(", "!", "exists", ")", "{", "suggestions", ".", "push", "(", "item", ")", ";", "}", "// We are using searchTerms's setter to execute the filter, so have to set the property (not just update):", "var", "searchTerms", "=", "self", ".", "viewModel", ".", "attr", "(", "'searchTerms'", ")", ".", "attr", "(", ")", ".", "concat", "(", "item", ".", "name", ")", ";", "self", ".", "viewModel", ".", "attr", "(", "'searchTerms'", ",", "searchTerms", ")", ";", "}", ",", "/**\n * onDelete is used to remove items from searchTerms in the scope. It is called internally \n * by the jquery.tokenInput plugin when a tag gets removed from the input box.\n */", "onDelete", ":", "function", "(", "item", ")", "{", "var", "searchTerms", "=", "self", ".", "viewModel", ".", "attr", "(", "'searchTerms'", ")", ".", "attr", "(", ")", ",", "searchTerm", "=", "item", "&&", "(", "item", ".", "id", "||", "item", ".", "name", "||", "item", ")", ";", "searchTerms", ".", "splice", "(", "searchTerms", ".", "indexOf", "(", "searchTerm", ")", ",", "1", ")", ";", "// We are using searchTerms's setter to execute the filter, so have to set the property (not just update):", "self", ".", "viewModel", ".", "attr", "(", "'searchTerms'", ",", "searchTerms", ")", ";", "}", "}", ")", ";", "}" ]
Run the jQuery.tokenizer plugin when the templated is inserted. When the input updates, the tokenizer will update the searchTerms in the viewModel.
[ "Run", "the", "jQuery", ".", "tokenizer", "plugin", "when", "the", "templated", "is", "inserted", ".", "When", "the", "input", "updates", "the", "tokenizer", "will", "update", "the", "searchTerms", "in", "the", "viewModel", "." ]
48d9ce876cdc6ef459fcae70ac67b23229e85a5a
https://github.com/icanjs/grid-filter/blob/48d9ce876cdc6ef459fcae70ac67b23229e85a5a/src/grid-filter.js#L25-L89
55,660
icanjs/grid-filter
src/grid-filter.js
function (item) { if($.isEmptyObject(item)){ var tempObj={ id: $('input:first', el).val(), name: $('input:first', el).val()}; return [tempObj]; }else{ return item; } }
javascript
function (item) { if($.isEmptyObject(item)){ var tempObj={ id: $('input:first', el).val(), name: $('input:first', el).val()}; return [tempObj]; }else{ return item; } }
[ "function", "(", "item", ")", "{", "if", "(", "$", ".", "isEmptyObject", "(", "item", ")", ")", "{", "var", "tempObj", "=", "{", "id", ":", "$", "(", "'input:first'", ",", "el", ")", ".", "val", "(", ")", ",", "name", ":", "$", "(", "'input:first'", ",", "el", ")", ".", "val", "(", ")", "}", ";", "return", "[", "tempObj", "]", ";", "}", "else", "{", "return", "item", ";", "}", "}" ]
onResult is used to pre-process suggestions. In our case we want to show current item if there is no results.
[ "onResult", "is", "used", "to", "pre", "-", "process", "suggestions", ".", "In", "our", "case", "we", "want", "to", "show", "current", "item", "if", "there", "is", "no", "results", "." ]
48d9ce876cdc6ef459fcae70ac67b23229e85a5a
https://github.com/icanjs/grid-filter/blob/48d9ce876cdc6ef459fcae70ac67b23229e85a5a/src/grid-filter.js#L44-L51
55,661
icanjs/grid-filter
src/grid-filter.js
function (item) { // Check if it already exists in the suggestions list. Duplicates aren't allowed. var exists = false; for(var j = 0; j < suggestions.length; j++){ if(suggestions[j].attr('name').toLowerCase() === item.name.toLowerCase()){ exists=true; break; } } // If it didn't exist, add it to the list of suggestions and the searchTerms. if(!exists){ suggestions.push(item); } // We are using searchTerms's setter to execute the filter, so have to set the property (not just update): var searchTerms = self.viewModel.attr('searchTerms').attr().concat(item.name); self.viewModel.attr('searchTerms', searchTerms); }
javascript
function (item) { // Check if it already exists in the suggestions list. Duplicates aren't allowed. var exists = false; for(var j = 0; j < suggestions.length; j++){ if(suggestions[j].attr('name').toLowerCase() === item.name.toLowerCase()){ exists=true; break; } } // If it didn't exist, add it to the list of suggestions and the searchTerms. if(!exists){ suggestions.push(item); } // We are using searchTerms's setter to execute the filter, so have to set the property (not just update): var searchTerms = self.viewModel.attr('searchTerms').attr().concat(item.name); self.viewModel.attr('searchTerms', searchTerms); }
[ "function", "(", "item", ")", "{", "// Check if it already exists in the suggestions list. Duplicates aren't allowed.", "var", "exists", "=", "false", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "suggestions", ".", "length", ";", "j", "++", ")", "{", "if", "(", "suggestions", "[", "j", "]", ".", "attr", "(", "'name'", ")", ".", "toLowerCase", "(", ")", "===", "item", ".", "name", ".", "toLowerCase", "(", ")", ")", "{", "exists", "=", "true", ";", "break", ";", "}", "}", "// If it didn't exist, add it to the list of suggestions and the searchTerms.", "if", "(", "!", "exists", ")", "{", "suggestions", ".", "push", "(", "item", ")", ";", "}", "// We are using searchTerms's setter to execute the filter, so have to set the property (not just update):", "var", "searchTerms", "=", "self", ".", "viewModel", ".", "attr", "(", "'searchTerms'", ")", ".", "attr", "(", ")", ".", "concat", "(", "item", ".", "name", ")", ";", "self", ".", "viewModel", ".", "attr", "(", "'searchTerms'", ",", "searchTerms", ")", ";", "}" ]
onAdd is used to maintain the suggestion dropdown box and the searchTerms in the scope. It is called internally by the jquery.tokenInput plugin when either the enter key is pressed in the input box or a selection is made in the suggestions dropdown.
[ "onAdd", "is", "used", "to", "maintain", "the", "suggestion", "dropdown", "box", "and", "the", "searchTerms", "in", "the", "scope", ".", "It", "is", "called", "internally", "by", "the", "jquery", ".", "tokenInput", "plugin", "when", "either", "the", "enter", "key", "is", "pressed", "in", "the", "input", "box", "or", "a", "selection", "is", "made", "in", "the", "suggestions", "dropdown", "." ]
48d9ce876cdc6ef459fcae70ac67b23229e85a5a
https://github.com/icanjs/grid-filter/blob/48d9ce876cdc6ef459fcae70ac67b23229e85a5a/src/grid-filter.js#L58-L75
55,662
icanjs/grid-filter
src/grid-filter.js
function (item) { var searchTerms = self.viewModel.attr('searchTerms').attr(), searchTerm = item && (item.id || item.name || item); searchTerms.splice(searchTerms.indexOf(searchTerm), 1); // We are using searchTerms's setter to execute the filter, so have to set the property (not just update): self.viewModel.attr('searchTerms', searchTerms); }
javascript
function (item) { var searchTerms = self.viewModel.attr('searchTerms').attr(), searchTerm = item && (item.id || item.name || item); searchTerms.splice(searchTerms.indexOf(searchTerm), 1); // We are using searchTerms's setter to execute the filter, so have to set the property (not just update): self.viewModel.attr('searchTerms', searchTerms); }
[ "function", "(", "item", ")", "{", "var", "searchTerms", "=", "self", ".", "viewModel", ".", "attr", "(", "'searchTerms'", ")", ".", "attr", "(", ")", ",", "searchTerm", "=", "item", "&&", "(", "item", ".", "id", "||", "item", ".", "name", "||", "item", ")", ";", "searchTerms", ".", "splice", "(", "searchTerms", ".", "indexOf", "(", "searchTerm", ")", ",", "1", ")", ";", "// We are using searchTerms's setter to execute the filter, so have to set the property (not just update):", "self", ".", "viewModel", ".", "attr", "(", "'searchTerms'", ",", "searchTerms", ")", ";", "}" ]
onDelete is used to remove items from searchTerms in the scope. It is called internally by the jquery.tokenInput plugin when a tag gets removed from the input box.
[ "onDelete", "is", "used", "to", "remove", "items", "from", "searchTerms", "in", "the", "scope", ".", "It", "is", "called", "internally", "by", "the", "jquery", ".", "tokenInput", "plugin", "when", "a", "tag", "gets", "removed", "from", "the", "input", "box", "." ]
48d9ce876cdc6ef459fcae70ac67b23229e85a5a
https://github.com/icanjs/grid-filter/blob/48d9ce876cdc6ef459fcae70ac67b23229e85a5a/src/grid-filter.js#L81-L87
55,663
Pocketbrain/native-ads-web-ad-library
src/page.js
xPath
function xPath(xPathString) { var xResult = document.evaluate(xPathString, document, null, 0, null); var xNodes = []; var xRes = xResult.iterateNext(); while (xRes) { xNodes.push(xRes); xRes = xResult.iterateNext(); } return xNodes; }
javascript
function xPath(xPathString) { var xResult = document.evaluate(xPathString, document, null, 0, null); var xNodes = []; var xRes = xResult.iterateNext(); while (xRes) { xNodes.push(xRes); xRes = xResult.iterateNext(); } return xNodes; }
[ "function", "xPath", "(", "xPathString", ")", "{", "var", "xResult", "=", "document", ".", "evaluate", "(", "xPathString", ",", "document", ",", "null", ",", "0", ",", "null", ")", ";", "var", "xNodes", "=", "[", "]", ";", "var", "xRes", "=", "xResult", ".", "iterateNext", "(", ")", ";", "while", "(", "xRes", ")", "{", "xNodes", ".", "push", "(", "xRes", ")", ";", "xRes", "=", "xResult", ".", "iterateNext", "(", ")", ";", "}", "return", "xNodes", ";", "}" ]
Evaluates xPath on a page @param {string} xPathString - The Xpath string to evaluate @returns {Array.<HTMLElement>} - An array of the found HTML elements
[ "Evaluates", "xPath", "on", "a", "page" ]
aafee1c42e0569ee77f334fc2c4eb71eb146957e
https://github.com/Pocketbrain/native-ads-web-ad-library/blob/aafee1c42e0569ee77f334fc2c4eb71eb146957e/src/page.js#L25-L35
55,664
Pocketbrain/native-ads-web-ad-library
src/page.js
execWaitReadyFunctions
function execWaitReadyFunctions() { if (isReady()) { logger.info('Page is ready. Executing ' + callbacksOnReady.length + ' functions that are waiting.'); for (var i = 0; i < callbacksOnReady.length; i++) { var callback = callbacksOnReady[i]; callback(); } } }
javascript
function execWaitReadyFunctions() { if (isReady()) { logger.info('Page is ready. Executing ' + callbacksOnReady.length + ' functions that are waiting.'); for (var i = 0; i < callbacksOnReady.length; i++) { var callback = callbacksOnReady[i]; callback(); } } }
[ "function", "execWaitReadyFunctions", "(", ")", "{", "if", "(", "isReady", "(", ")", ")", "{", "logger", ".", "info", "(", "'Page is ready. Executing '", "+", "callbacksOnReady", ".", "length", "+", "' functions that are waiting.'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "callbacksOnReady", ".", "length", ";", "i", "++", ")", "{", "var", "callback", "=", "callbacksOnReady", "[", "i", "]", ";", "callback", "(", ")", ";", "}", "}", "}" ]
Execute all the functions that are waiting for the page to finish loading
[ "Execute", "all", "the", "functions", "that", "are", "waiting", "for", "the", "page", "to", "finish", "loading" ]
aafee1c42e0569ee77f334fc2c4eb71eb146957e
https://github.com/Pocketbrain/native-ads-web-ad-library/blob/aafee1c42e0569ee77f334fc2c4eb71eb146957e/src/page.js#L52-L60
55,665
Pocketbrain/native-ads-web-ad-library
src/page.js
whenReady
function whenReady(funcToExecute) { if (isReady()) { logger.info('Page is already loaded, instantly executing!'); funcToExecute(); return; } logger.info('Waiting for page to be ready'); callbacksOnReady.push(funcToExecute); }
javascript
function whenReady(funcToExecute) { if (isReady()) { logger.info('Page is already loaded, instantly executing!'); funcToExecute(); return; } logger.info('Waiting for page to be ready'); callbacksOnReady.push(funcToExecute); }
[ "function", "whenReady", "(", "funcToExecute", ")", "{", "if", "(", "isReady", "(", ")", ")", "{", "logger", ".", "info", "(", "'Page is already loaded, instantly executing!'", ")", ";", "funcToExecute", "(", ")", ";", "return", ";", "}", "logger", ".", "info", "(", "'Waiting for page to be ready'", ")", ";", "callbacksOnReady", ".", "push", "(", "funcToExecute", ")", ";", "}" ]
Returns a promise that resolves when the page is ready @param funcToExecute - The function to execute when the page is loaded
[ "Returns", "a", "promise", "that", "resolves", "when", "the", "page", "is", "ready" ]
aafee1c42e0569ee77f334fc2c4eb71eb146957e
https://github.com/Pocketbrain/native-ads-web-ad-library/blob/aafee1c42e0569ee77f334fc2c4eb71eb146957e/src/page.js#L75-L84
55,666
Pocketbrain/native-ads-web-ad-library
src/page.js
function (adUnitSettings) { var containers = adUnitSettings.containers; var adContainers = []; for (var i = 0; i < containers.length; i++) { var container = containers[i]; var containerXPath = container.xPath; var adContainerElements = xPath(containerXPath); if (!adContainerElements.length) { logger.warn("Ad container with xPath: \"" + containerXPath + "\" could not be found on page"); continue; } if (adContainerElements.length > 1) { logger.warn("Ad container with xPath: \"" + containerXPath + "\" has multiple matches"); } adContainers.push(new AdContainer(container, adContainerElements[0])); } return adContainers; }
javascript
function (adUnitSettings) { var containers = adUnitSettings.containers; var adContainers = []; for (var i = 0; i < containers.length; i++) { var container = containers[i]; var containerXPath = container.xPath; var adContainerElements = xPath(containerXPath); if (!adContainerElements.length) { logger.warn("Ad container with xPath: \"" + containerXPath + "\" could not be found on page"); continue; } if (adContainerElements.length > 1) { logger.warn("Ad container with xPath: \"" + containerXPath + "\" has multiple matches"); } adContainers.push(new AdContainer(container, adContainerElements[0])); } return adContainers; }
[ "function", "(", "adUnitSettings", ")", "{", "var", "containers", "=", "adUnitSettings", ".", "containers", ";", "var", "adContainers", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "containers", ".", "length", ";", "i", "++", ")", "{", "var", "container", "=", "containers", "[", "i", "]", ";", "var", "containerXPath", "=", "container", ".", "xPath", ";", "var", "adContainerElements", "=", "xPath", "(", "containerXPath", ")", ";", "if", "(", "!", "adContainerElements", ".", "length", ")", "{", "logger", ".", "warn", "(", "\"Ad container with xPath: \\\"\"", "+", "containerXPath", "+", "\"\\\" could not be found on page\"", ")", ";", "continue", ";", "}", "if", "(", "adContainerElements", ".", "length", ">", "1", ")", "{", "logger", ".", "warn", "(", "\"Ad container with xPath: \\\"\"", "+", "containerXPath", "+", "\"\\\" has multiple matches\"", ")", ";", "}", "adContainers", ".", "push", "(", "new", "AdContainer", "(", "container", ",", "adContainerElements", "[", "0", "]", ")", ")", ";", "}", "return", "adContainers", ";", "}" ]
Gets the adcontainers on the page from the container xPath @param adUnitSettings the settings for the adUnit to get the container of @returns {Array.<Object>} the AdContainer object or null if not found
[ "Gets", "the", "adcontainers", "on", "the", "page", "from", "the", "container", "xPath" ]
aafee1c42e0569ee77f334fc2c4eb71eb146957e
https://github.com/Pocketbrain/native-ads-web-ad-library/blob/aafee1c42e0569ee77f334fc2c4eb71eb146957e/src/page.js#L100-L124
55,667
andreypopp/es6-destructuring-jstransform
visitors.js
render
function render(expr, traverse, path, state) { if (isString(expr)) { utils.append(expr, state); } else if (Array.isArray(expr)) { expr.forEach(function(w) { render(w, traverse, path, state); }); } else { utils.move(expr.range[0], state); traverse(expr, path, state); utils.catchup(expr.range[1], state); } }
javascript
function render(expr, traverse, path, state) { if (isString(expr)) { utils.append(expr, state); } else if (Array.isArray(expr)) { expr.forEach(function(w) { render(w, traverse, path, state); }); } else { utils.move(expr.range[0], state); traverse(expr, path, state); utils.catchup(expr.range[1], state); } }
[ "function", "render", "(", "expr", ",", "traverse", ",", "path", ",", "state", ")", "{", "if", "(", "isString", "(", "expr", ")", ")", "{", "utils", ".", "append", "(", "expr", ",", "state", ")", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "expr", ")", ")", "{", "expr", ".", "forEach", "(", "function", "(", "w", ")", "{", "render", "(", "w", ",", "traverse", ",", "path", ",", "state", ")", ";", "}", ")", ";", "}", "else", "{", "utils", ".", "move", "(", "expr", ".", "range", "[", "0", "]", ",", "state", ")", ";", "traverse", "(", "expr", ",", "path", ",", "state", ")", ";", "utils", ".", "catchup", "(", "expr", ".", "range", "[", "1", "]", ",", "state", ")", ";", "}", "}" ]
Render an expression This is a helper which can render AST nodes, sting values or arrays which can contain both of the types. @param {Node|String|Array} expr Expression to render @param {Function} traverse @param {Object} path @param {Object} state
[ "Render", "an", "expression" ]
c0f238286a323fa9d009e4da9ccb54f99e9efb0b
https://github.com/andreypopp/es6-destructuring-jstransform/blob/c0f238286a323fa9d009e4da9ccb54f99e9efb0b/visitors.js#L17-L29
55,668
andreypopp/es6-destructuring-jstransform
visitors.js
renderExpressionMemoized
function renderExpressionMemoized(expr, traverse, path, state) { var evaluated; if (expr.type === Syntax.Identifier) { evaluated = expr.name; } else if (isString(expr)) { evaluated = expr; } else { evaluated = genID('var'); utils.append(evaluated + ' = ', state); render(expr, traverse, path, state); utils.append(', ', state); } return evaluated; }
javascript
function renderExpressionMemoized(expr, traverse, path, state) { var evaluated; if (expr.type === Syntax.Identifier) { evaluated = expr.name; } else if (isString(expr)) { evaluated = expr; } else { evaluated = genID('var'); utils.append(evaluated + ' = ', state); render(expr, traverse, path, state); utils.append(', ', state); } return evaluated; }
[ "function", "renderExpressionMemoized", "(", "expr", ",", "traverse", ",", "path", ",", "state", ")", "{", "var", "evaluated", ";", "if", "(", "expr", ".", "type", "===", "Syntax", ".", "Identifier", ")", "{", "evaluated", "=", "expr", ".", "name", ";", "}", "else", "if", "(", "isString", "(", "expr", ")", ")", "{", "evaluated", "=", "expr", ";", "}", "else", "{", "evaluated", "=", "genID", "(", "'var'", ")", ";", "utils", ".", "append", "(", "evaluated", "+", "' = '", ",", "state", ")", ";", "render", "(", "expr", ",", "traverse", ",", "path", ",", "state", ")", ";", "utils", ".", "append", "(", "', '", ",", "state", ")", ";", "}", "return", "evaluated", ";", "}" ]
Render expression into a variable declaration and return its id. If we destructure is an identifier (or a string) we use its "value" directly, otherwise we cache it in variable declaration to prevent extra "effectful" evaluations. @param {Node|String|Array} expr Expression to render @param {Function} traverse @param {Object} path @param {Object} state
[ "Render", "expression", "into", "a", "variable", "declaration", "and", "return", "its", "id", "." ]
c0f238286a323fa9d009e4da9ccb54f99e9efb0b
https://github.com/andreypopp/es6-destructuring-jstransform/blob/c0f238286a323fa9d009e4da9ccb54f99e9efb0b/visitors.js#L43-L57
55,669
andreypopp/es6-destructuring-jstransform
visitors.js
renderDesructuration
function renderDesructuration(pattern, expr, traverse, path, state) { utils.catchupNewlines(pattern.range[1], state); var id; if (pattern.type === Syntax.ObjectPattern && pattern.properties.length === 1) { id = expr; } else if (pattern.type === Syntax.ArrayPattern && pattern.elements.length === 1) { id = expr; } else { id = renderExpressionMemoized(expr, traverse, path, state); } if (pattern.type === Syntax.ObjectPattern) { pattern.properties.forEach(function(prop, idx) { var comma = (idx !== pattern.properties.length - 1) ? ', ' : ''; if (isPattern(prop.value)) { renderDesructuration(prop.value, [id, '.', prop.key.name], traverse, path, state); } else { utils.append(prop.value.name + ' = ', state); render([id, '.' + prop.key.name], traverse, path, state); utils.append(comma, state); } }); } else { pattern.elements.forEach(function(elem, idx) { // null means skip if (elem === null) { return; } var comma = (idx !== pattern.elements.length - 1) ? ', ' : ''; if (isPattern(elem)) { renderDesructuration(elem, [id, '[' + idx + ']'], traverse, path, state); } else if (elem.type === Syntax.SpreadElement) { utils.append(elem.argument.name + ' = ', state); render([id, '.slice(' + idx + ')'], traverse, path, state); utils.append(comma, state); } else { utils.append(elem.name + ' = ', state); render([id, '[' + idx + ']'], traverse, path, state); utils.append(comma, state); } }); } }
javascript
function renderDesructuration(pattern, expr, traverse, path, state) { utils.catchupNewlines(pattern.range[1], state); var id; if (pattern.type === Syntax.ObjectPattern && pattern.properties.length === 1) { id = expr; } else if (pattern.type === Syntax.ArrayPattern && pattern.elements.length === 1) { id = expr; } else { id = renderExpressionMemoized(expr, traverse, path, state); } if (pattern.type === Syntax.ObjectPattern) { pattern.properties.forEach(function(prop, idx) { var comma = (idx !== pattern.properties.length - 1) ? ', ' : ''; if (isPattern(prop.value)) { renderDesructuration(prop.value, [id, '.', prop.key.name], traverse, path, state); } else { utils.append(prop.value.name + ' = ', state); render([id, '.' + prop.key.name], traverse, path, state); utils.append(comma, state); } }); } else { pattern.elements.forEach(function(elem, idx) { // null means skip if (elem === null) { return; } var comma = (idx !== pattern.elements.length - 1) ? ', ' : ''; if (isPattern(elem)) { renderDesructuration(elem, [id, '[' + idx + ']'], traverse, path, state); } else if (elem.type === Syntax.SpreadElement) { utils.append(elem.argument.name + ' = ', state); render([id, '.slice(' + idx + ')'], traverse, path, state); utils.append(comma, state); } else { utils.append(elem.name + ' = ', state); render([id, '[' + idx + ']'], traverse, path, state); utils.append(comma, state); } }); } }
[ "function", "renderDesructuration", "(", "pattern", ",", "expr", ",", "traverse", ",", "path", ",", "state", ")", "{", "utils", ".", "catchupNewlines", "(", "pattern", ".", "range", "[", "1", "]", ",", "state", ")", ";", "var", "id", ";", "if", "(", "pattern", ".", "type", "===", "Syntax", ".", "ObjectPattern", "&&", "pattern", ".", "properties", ".", "length", "===", "1", ")", "{", "id", "=", "expr", ";", "}", "else", "if", "(", "pattern", ".", "type", "===", "Syntax", ".", "ArrayPattern", "&&", "pattern", ".", "elements", ".", "length", "===", "1", ")", "{", "id", "=", "expr", ";", "}", "else", "{", "id", "=", "renderExpressionMemoized", "(", "expr", ",", "traverse", ",", "path", ",", "state", ")", ";", "}", "if", "(", "pattern", ".", "type", "===", "Syntax", ".", "ObjectPattern", ")", "{", "pattern", ".", "properties", ".", "forEach", "(", "function", "(", "prop", ",", "idx", ")", "{", "var", "comma", "=", "(", "idx", "!==", "pattern", ".", "properties", ".", "length", "-", "1", ")", "?", "', '", ":", "''", ";", "if", "(", "isPattern", "(", "prop", ".", "value", ")", ")", "{", "renderDesructuration", "(", "prop", ".", "value", ",", "[", "id", ",", "'.'", ",", "prop", ".", "key", ".", "name", "]", ",", "traverse", ",", "path", ",", "state", ")", ";", "}", "else", "{", "utils", ".", "append", "(", "prop", ".", "value", ".", "name", "+", "' = '", ",", "state", ")", ";", "render", "(", "[", "id", ",", "'.'", "+", "prop", ".", "key", ".", "name", "]", ",", "traverse", ",", "path", ",", "state", ")", ";", "utils", ".", "append", "(", "comma", ",", "state", ")", ";", "}", "}", ")", ";", "}", "else", "{", "pattern", ".", "elements", ".", "forEach", "(", "function", "(", "elem", ",", "idx", ")", "{", "// null means skip", "if", "(", "elem", "===", "null", ")", "{", "return", ";", "}", "var", "comma", "=", "(", "idx", "!==", "pattern", ".", "elements", ".", "length", "-", "1", ")", "?", "', '", ":", "''", ";", "if", "(", "isPattern", "(", "elem", ")", ")", "{", "renderDesructuration", "(", "elem", ",", "[", "id", ",", "'['", "+", "idx", "+", "']'", "]", ",", "traverse", ",", "path", ",", "state", ")", ";", "}", "else", "if", "(", "elem", ".", "type", "===", "Syntax", ".", "SpreadElement", ")", "{", "utils", ".", "append", "(", "elem", ".", "argument", ".", "name", "+", "' = '", ",", "state", ")", ";", "render", "(", "[", "id", ",", "'.slice('", "+", "idx", "+", "')'", "]", ",", "traverse", ",", "path", ",", "state", ")", ";", "utils", ".", "append", "(", "comma", ",", "state", ")", ";", "}", "else", "{", "utils", ".", "append", "(", "elem", ".", "name", "+", "' = '", ",", "state", ")", ";", "render", "(", "[", "id", ",", "'['", "+", "idx", "+", "']'", "]", ",", "traverse", ",", "path", ",", "state", ")", ";", "utils", ".", "append", "(", "comma", ",", "state", ")", ";", "}", "}", ")", ";", "}", "}" ]
Render destructuration of the `expr` using provided `pattern`. @param {Node} pattern Pattern to use for destructuration @param {Node|String|Array} expr Expression to destructure @param {Function} traverse @param {Object} path @param {Object} state
[ "Render", "destructuration", "of", "the", "expr", "using", "provided", "pattern", "." ]
c0f238286a323fa9d009e4da9ccb54f99e9efb0b
https://github.com/andreypopp/es6-destructuring-jstransform/blob/c0f238286a323fa9d009e4da9ccb54f99e9efb0b/visitors.js#L68-L118
55,670
phated/grunt-enyo
tasks/init/bootplate/root/enyo/source/touch/gesture.js
function(inPositions) { var p = inPositions; // yay math!, rad -> deg var a = Math.asin(p.y / p.h) * (180 / Math.PI); // fix for range limits of asin (-90 to 90) // Quadrants II and III if (p.x < 0) { a = 180 - a; } // Quadrant IV if (p.x > 0 && p.y < 0) { a += 360; } return a; }
javascript
function(inPositions) { var p = inPositions; // yay math!, rad -> deg var a = Math.asin(p.y / p.h) * (180 / Math.PI); // fix for range limits of asin (-90 to 90) // Quadrants II and III if (p.x < 0) { a = 180 - a; } // Quadrant IV if (p.x > 0 && p.y < 0) { a += 360; } return a; }
[ "function", "(", "inPositions", ")", "{", "var", "p", "=", "inPositions", ";", "// yay math!, rad -> deg", "var", "a", "=", "Math", ".", "asin", "(", "p", ".", "y", "/", "p", ".", "h", ")", "*", "(", "180", "/", "Math", ".", "PI", ")", ";", "// fix for range limits of asin (-90 to 90)", "// Quadrants II and III", "if", "(", "p", ".", "x", "<", "0", ")", "{", "a", "=", "180", "-", "a", ";", "}", "// Quadrant IV", "if", "(", "p", ".", "x", ">", "0", "&&", "p", ".", "y", "<", "0", ")", "{", "a", "+=", "360", ";", "}", "return", "a", ";", "}" ]
find rotation angle
[ "find", "rotation", "angle" ]
d2990ee4cd85eea8db4108c43086c6d8c3c90c30
https://github.com/phated/grunt-enyo/blob/d2990ee4cd85eea8db4108c43086c6d8c3c90c30/tasks/init/bootplate/root/enyo/source/touch/gesture.js#L81-L95
55,671
phated/grunt-enyo
tasks/init/bootplate/root/enyo/source/touch/gesture.js
function(inPositions) { // the least recent touch and the most recent touch determine the bounding box of the gesture event var p = inPositions; // center the first touch as 0,0 return { magnitude: p.h, xcenter: Math.abs(Math.round(p.fx + (p.x / 2))), ycenter: Math.abs(Math.round(p.fy + (p.y / 2))) }; }
javascript
function(inPositions) { // the least recent touch and the most recent touch determine the bounding box of the gesture event var p = inPositions; // center the first touch as 0,0 return { magnitude: p.h, xcenter: Math.abs(Math.round(p.fx + (p.x / 2))), ycenter: Math.abs(Math.round(p.fy + (p.y / 2))) }; }
[ "function", "(", "inPositions", ")", "{", "// the least recent touch and the most recent touch determine the bounding box of the gesture event", "var", "p", "=", "inPositions", ";", "// center the first touch as 0,0", "return", "{", "magnitude", ":", "p", ".", "h", ",", "xcenter", ":", "Math", ".", "abs", "(", "Math", ".", "round", "(", "p", ".", "fx", "+", "(", "p", ".", "x", "/", "2", ")", ")", ")", ",", "ycenter", ":", "Math", ".", "abs", "(", "Math", ".", "round", "(", "p", ".", "fy", "+", "(", "p", ".", "y", "/", "2", ")", ")", ")", "}", ";", "}" ]
find bounding box
[ "find", "bounding", "box" ]
d2990ee4cd85eea8db4108c43086c6d8c3c90c30
https://github.com/phated/grunt-enyo/blob/d2990ee4cd85eea8db4108c43086c6d8c3c90c30/tasks/init/bootplate/root/enyo/source/touch/gesture.js#L97-L106
55,672
phated/grunt-enyo
tasks/init/enyo/root/enyo/source/kernel/Component.js
function(inInfos, inCommonInfo) { if (inInfos) { var cs = []; for (var i=0, ci; (ci=inInfos[i]); i++) { cs.push(this._createComponent(ci, inCommonInfo)); } return cs; } }
javascript
function(inInfos, inCommonInfo) { if (inInfos) { var cs = []; for (var i=0, ci; (ci=inInfos[i]); i++) { cs.push(this._createComponent(ci, inCommonInfo)); } return cs; } }
[ "function", "(", "inInfos", ",", "inCommonInfo", ")", "{", "if", "(", "inInfos", ")", "{", "var", "cs", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "ci", ";", "(", "ci", "=", "inInfos", "[", "i", "]", ")", ";", "i", "++", ")", "{", "cs", ".", "push", "(", "this", ".", "_createComponent", "(", "ci", ",", "inCommonInfo", ")", ")", ";", "}", "return", "cs", ";", "}", "}" ]
Creates Components as defined by the array of configurations _inInfo_. Each configuration in _inInfo_ is combined with _inCommonInfo_ as described in _createComponent_. _createComponents_ returns an array of references to the created components. ask foo to create components _bar_ and _zot_, but set the owner of both components to _this_. this.$.foo.createComponents([ {name: "bar"}, {name: "zot"} ], {owner: this});
[ "Creates", "Components", "as", "defined", "by", "the", "array", "of", "configurations", "_inInfo_", ".", "Each", "configuration", "in", "_inInfo_", "is", "combined", "with", "_inCommonInfo_", "as", "described", "in", "_createComponent_", "." ]
d2990ee4cd85eea8db4108c43086c6d8c3c90c30
https://github.com/phated/grunt-enyo/blob/d2990ee4cd85eea8db4108c43086c6d8c3c90c30/tasks/init/enyo/root/enyo/source/kernel/Component.js#L249-L257
55,673
phated/grunt-enyo
tasks/init/enyo/root/enyo/source/kernel/Component.js
function(inMethodName, inEvent, inSender) { var fn = inMethodName && this[inMethodName]; if (fn) { return fn.call(this, inSender || this, inEvent); } }
javascript
function(inMethodName, inEvent, inSender) { var fn = inMethodName && this[inMethodName]; if (fn) { return fn.call(this, inSender || this, inEvent); } }
[ "function", "(", "inMethodName", ",", "inEvent", ",", "inSender", ")", "{", "var", "fn", "=", "inMethodName", "&&", "this", "[", "inMethodName", "]", ";", "if", "(", "fn", ")", "{", "return", "fn", ".", "call", "(", "this", ",", "inSender", "||", "this", ",", "inEvent", ")", ";", "}", "}" ]
Dispatch the event to named delegate inMethodName, if it exists. Sub-kinds may re-route dispatches. Note that both 'handlers' events and events delegated from owned controls arrive here. If you need to handle these differently, you may need to also override dispatchEvent.
[ "Dispatch", "the", "event", "to", "named", "delegate", "inMethodName", "if", "it", "exists", ".", "Sub", "-", "kinds", "may", "re", "-", "route", "dispatches", ".", "Note", "that", "both", "handlers", "events", "and", "events", "delegated", "from", "owned", "controls", "arrive", "here", ".", "If", "you", "need", "to", "handle", "these", "differently", "you", "may", "need", "to", "also", "override", "dispatchEvent", "." ]
d2990ee4cd85eea8db4108c43086c6d8c3c90c30
https://github.com/phated/grunt-enyo/blob/d2990ee4cd85eea8db4108c43086c6d8c3c90c30/tasks/init/enyo/root/enyo/source/kernel/Component.js#L384-L389
55,674
phated/grunt-enyo
tasks/init/enyo/root/enyo/source/kernel/Component.js
function(inMessageName, inMessage, inSender) { //this.log(inMessageName, (inSender || this).name, "=>", this.name); if (this.dispatchEvent(inMessageName, inMessage, inSender)) { return true; } this.waterfallDown(inMessageName, inMessage, inSender || this); }
javascript
function(inMessageName, inMessage, inSender) { //this.log(inMessageName, (inSender || this).name, "=>", this.name); if (this.dispatchEvent(inMessageName, inMessage, inSender)) { return true; } this.waterfallDown(inMessageName, inMessage, inSender || this); }
[ "function", "(", "inMessageName", ",", "inMessage", ",", "inSender", ")", "{", "//this.log(inMessageName, (inSender || this).name, \"=>\", this.name);\r", "if", "(", "this", ".", "dispatchEvent", "(", "inMessageName", ",", "inMessage", ",", "inSender", ")", ")", "{", "return", "true", ";", "}", "this", ".", "waterfallDown", "(", "inMessageName", ",", "inMessage", ",", "inSender", "||", "this", ")", ";", "}" ]
Sends a message to myself and my descendants.
[ "Sends", "a", "message", "to", "myself", "and", "my", "descendants", "." ]
d2990ee4cd85eea8db4108c43086c6d8c3c90c30
https://github.com/phated/grunt-enyo/blob/d2990ee4cd85eea8db4108c43086c6d8c3c90c30/tasks/init/enyo/root/enyo/source/kernel/Component.js#L393-L399
55,675
skerit/creatures
lib/creatures_application.js
restoreState
function restoreState(top_err) { if (previous_state === true) { that.pause(function madePaused(err) { // Ignore errors? callback(top_err); }); } else { callback(top_err); } }
javascript
function restoreState(top_err) { if (previous_state === true) { that.pause(function madePaused(err) { // Ignore errors? callback(top_err); }); } else { callback(top_err); } }
[ "function", "restoreState", "(", "top_err", ")", "{", "if", "(", "previous_state", "===", "true", ")", "{", "that", ".", "pause", "(", "function", "madePaused", "(", "err", ")", "{", "// Ignore errors?", "callback", "(", "top_err", ")", ";", "}", ")", ";", "}", "else", "{", "callback", "(", "top_err", ")", ";", "}", "}" ]
Function to restate paused state
[ "Function", "to", "restate", "paused", "state" ]
019c2f00ef9f1bc9bdfd30470676248b0d82dfda
https://github.com/skerit/creatures/blob/019c2f00ef9f1bc9bdfd30470676248b0d82dfda/lib/creatures_application.js#L1536-L1545
55,676
skerit/creatures
lib/creatures_application.js
done
function done(err) { that._gcw = 'done_get_creatures'; bomb.defuse(); // Unsee the 'getting_creatures' event that.unsee('getting_creatures'); // Call next on the next tick (in case we call back with an error) Blast.nextTick(next); if (err) { that.log('error', 'Error getting creatures: ' + err) callback(err); } else { let result = []; for (let id in that.creatures_by_id) { if (that.creatures_by_id[id]) { result.push(that.creatures_by_id[id]); } } callback(null, result); that.emit('_got_creatures', err, result); } }
javascript
function done(err) { that._gcw = 'done_get_creatures'; bomb.defuse(); // Unsee the 'getting_creatures' event that.unsee('getting_creatures'); // Call next on the next tick (in case we call back with an error) Blast.nextTick(next); if (err) { that.log('error', 'Error getting creatures: ' + err) callback(err); } else { let result = []; for (let id in that.creatures_by_id) { if (that.creatures_by_id[id]) { result.push(that.creatures_by_id[id]); } } callback(null, result); that.emit('_got_creatures', err, result); } }
[ "function", "done", "(", "err", ")", "{", "that", ".", "_gcw", "=", "'done_get_creatures'", ";", "bomb", ".", "defuse", "(", ")", ";", "// Unsee the 'getting_creatures' event", "that", ".", "unsee", "(", "'getting_creatures'", ")", ";", "// Call next on the next tick (in case we call back with an error)", "Blast", ".", "nextTick", "(", "next", ")", ";", "if", "(", "err", ")", "{", "that", ".", "log", "(", "'error'", ",", "'Error getting creatures: '", "+", "err", ")", "callback", "(", "err", ")", ";", "}", "else", "{", "let", "result", "=", "[", "]", ";", "for", "(", "let", "id", "in", "that", ".", "creatures_by_id", ")", "{", "if", "(", "that", ".", "creatures_by_id", "[", "id", "]", ")", "{", "result", ".", "push", "(", "that", ".", "creatures_by_id", "[", "id", "]", ")", ";", "}", "}", "callback", "(", "null", ",", "result", ")", ";", "that", ".", "emit", "(", "'_got_creatures'", ",", "err", ",", "result", ")", ";", "}", "}" ]
Function that'll call next on the queue & the callback
[ "Function", "that", "ll", "call", "next", "on", "the", "queue", "&", "the", "callback" ]
019c2f00ef9f1bc9bdfd30470676248b0d82dfda
https://github.com/skerit/creatures/blob/019c2f00ef9f1bc9bdfd30470676248b0d82dfda/lib/creatures_application.js#L1768-L1796
55,677
nodys/htmly
support/updatedoc.js
flux
function flux (path) { return function (done) { fs.createReadStream(resolve(__dirname, path)) .pipe(docflux()) .pipe(docflux.markdown({depth: DEPTH, indent: INDENT})) .pipe(concat(function (data) { done(null, data.toString()) })) } }
javascript
function flux (path) { return function (done) { fs.createReadStream(resolve(__dirname, path)) .pipe(docflux()) .pipe(docflux.markdown({depth: DEPTH, indent: INDENT})) .pipe(concat(function (data) { done(null, data.toString()) })) } }
[ "function", "flux", "(", "path", ")", "{", "return", "function", "(", "done", ")", "{", "fs", ".", "createReadStream", "(", "resolve", "(", "__dirname", ",", "path", ")", ")", ".", "pipe", "(", "docflux", "(", ")", ")", ".", "pipe", "(", "docflux", ".", "markdown", "(", "{", "depth", ":", "DEPTH", ",", "indent", ":", "INDENT", "}", ")", ")", ".", "pipe", "(", "concat", "(", "function", "(", "data", ")", "{", "done", "(", "null", ",", "data", ".", "toString", "(", ")", ")", "}", ")", ")", "}", "}" ]
Return a docflux transformer function @param {String} path Code source to read (relative path) @return {Function} Function for async.js
[ "Return", "a", "docflux", "transformer", "function" ]
770560274167b7efd78cf56544ec72f52efb3fb8
https://github.com/nodys/htmly/blob/770560274167b7efd78cf56544ec72f52efb3fb8/support/updatedoc.js#L38-L47
55,678
Endare/node-bb10
lib/PushInitiator.js
PushInitiator
function PushInitiator(applicationId, password, contentProviderId, evaluation) { this.applicationId = applicationId; this.authToken = new Buffer(applicationId + ':' + password).toString('base64'); this.contentProviderId = contentProviderId; this.isEvaluation = evaluation || false; }
javascript
function PushInitiator(applicationId, password, contentProviderId, evaluation) { this.applicationId = applicationId; this.authToken = new Buffer(applicationId + ':' + password).toString('base64'); this.contentProviderId = contentProviderId; this.isEvaluation = evaluation || false; }
[ "function", "PushInitiator", "(", "applicationId", ",", "password", ",", "contentProviderId", ",", "evaluation", ")", "{", "this", ".", "applicationId", "=", "applicationId", ";", "this", ".", "authToken", "=", "new", "Buffer", "(", "applicationId", "+", "':'", "+", "password", ")", ".", "toString", "(", "'base64'", ")", ";", "this", ".", "contentProviderId", "=", "contentProviderId", ";", "this", ".", "isEvaluation", "=", "evaluation", "||", "false", ";", "}" ]
Creats a new PushInitiator object that can be used to push messages to the Push Protocol Gateway. @param {Object} applicationId The unique application identifier provided by BlackBerry. @param {Object} password The server side password provided by BlackBerry. @param {Object} contentProviderId The CPID number provided by BlackBerry. @param {Object} evaluation Set this to true if you are running in debug. Leave empty if you are running in production.
[ "Creats", "a", "new", "PushInitiator", "object", "that", "can", "be", "used", "to", "push", "messages", "to", "the", "Push", "Protocol", "Gateway", "." ]
69ac4806d1c02b0c7f4735f15f3ba3adc61b9617
https://github.com/Endare/node-bb10/blob/69ac4806d1c02b0c7f4735f15f3ba3adc61b9617/lib/PushInitiator.js#L30-L35
55,679
shinuza/captain-core
lib/models/tags.js
findById
function findById(id, cb) { db.getClient(function(err, client, done) { client.query(SELECT_ID, [id], function(err, r) { var result = r && r.rows[0]; if(!err && !result) err = new exceptions.NotFound(); if(err) { cb(err); done(err); } else { cb(null, result); done(); } }); }); }
javascript
function findById(id, cb) { db.getClient(function(err, client, done) { client.query(SELECT_ID, [id], function(err, r) { var result = r && r.rows[0]; if(!err && !result) err = new exceptions.NotFound(); if(err) { cb(err); done(err); } else { cb(null, result); done(); } }); }); }
[ "function", "findById", "(", "id", ",", "cb", ")", "{", "db", ".", "getClient", "(", "function", "(", "err", ",", "client", ",", "done", ")", "{", "client", ".", "query", "(", "SELECT_ID", ",", "[", "id", "]", ",", "function", "(", "err", ",", "r", ")", "{", "var", "result", "=", "r", "&&", "r", ".", "rows", "[", "0", "]", ";", "if", "(", "!", "err", "&&", "!", "result", ")", "err", "=", "new", "exceptions", ".", "NotFound", "(", ")", ";", "if", "(", "err", ")", "{", "cb", "(", "err", ")", ";", "done", "(", "err", ")", ";", "}", "else", "{", "cb", "(", "null", ",", "result", ")", ";", "done", "(", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Finds a tag by `id` `cb` is passed the matching tag or exceptions.NotFound @param {Number} id @param {Function} cb
[ "Finds", "a", "tag", "by", "id" ]
02f3a404cdfca608e8726bbacc33e32fec484b21
https://github.com/shinuza/captain-core/blob/02f3a404cdfca608e8726bbacc33e32fec484b21/lib/models/tags.js#L84-L98
55,680
shinuza/captain-core
lib/models/tags.js
create
function create(body, cb) { var validates = Schema(body); if(!validates) { return cb(new exceptions.BadRequest()); } body.slug = string.slugify(body.title); var q = qb.insert(body); db.getClient(function(err, client, done) { client.query(q[0], q[1], function(err, r) { if(err) { if(err.code == 23505) { err = new exceptions.AlreadyExists(); } cb(err); done(err); } else { cb(null, r.rows[0]); done(); } }); }); }
javascript
function create(body, cb) { var validates = Schema(body); if(!validates) { return cb(new exceptions.BadRequest()); } body.slug = string.slugify(body.title); var q = qb.insert(body); db.getClient(function(err, client, done) { client.query(q[0], q[1], function(err, r) { if(err) { if(err.code == 23505) { err = new exceptions.AlreadyExists(); } cb(err); done(err); } else { cb(null, r.rows[0]); done(); } }); }); }
[ "function", "create", "(", "body", ",", "cb", ")", "{", "var", "validates", "=", "Schema", "(", "body", ")", ";", "if", "(", "!", "validates", ")", "{", "return", "cb", "(", "new", "exceptions", ".", "BadRequest", "(", ")", ")", ";", "}", "body", ".", "slug", "=", "string", ".", "slugify", "(", "body", ".", "title", ")", ";", "var", "q", "=", "qb", ".", "insert", "(", "body", ")", ";", "db", ".", "getClient", "(", "function", "(", "err", ",", "client", ",", "done", ")", "{", "client", ".", "query", "(", "q", "[", "0", "]", ",", "q", "[", "1", "]", ",", "function", "(", "err", ",", "r", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", ".", "code", "==", "23505", ")", "{", "err", "=", "new", "exceptions", ".", "AlreadyExists", "(", ")", ";", "}", "cb", "(", "err", ")", ";", "done", "(", "err", ")", ";", "}", "else", "{", "cb", "(", "null", ",", "r", ".", "rows", "[", "0", "]", ")", ";", "done", "(", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Creates a new tag. `cb` is passed the newly created tag, or: * exceptions.BadRequest: if the `body` does not satisfy the schema * exceptions.AlreadyExists: if a tag with the same slug already exists @param {Object} body @param {Function} cb
[ "Creates", "a", "new", "tag", "." ]
02f3a404cdfca608e8726bbacc33e32fec484b21
https://github.com/shinuza/captain-core/blob/02f3a404cdfca608e8726bbacc33e32fec484b21/lib/models/tags.js#L113-L137
55,681
shinuza/captain-core
lib/models/tags.js
all
function all(options, cb) { var q , page = Number(options.page) || 1 , limit = Number(options.limit) || conf.objects_by_page , offset = (page - 1) * limit; count(function(err, count) { if(err) { return cb(err); } q = select('LEFT JOIN'); q += ' LIMIT ' + limit + ' OFFSET ' + offset; db.getClient(function(err, client, done) { client.query(q, function(err, r) { if(err) { cb(err); done(err); } else { cb(null, { rows: r.rows, count: count, limit: limit, offset: offset, page: page }); done(); } }); }); }); }
javascript
function all(options, cb) { var q , page = Number(options.page) || 1 , limit = Number(options.limit) || conf.objects_by_page , offset = (page - 1) * limit; count(function(err, count) { if(err) { return cb(err); } q = select('LEFT JOIN'); q += ' LIMIT ' + limit + ' OFFSET ' + offset; db.getClient(function(err, client, done) { client.query(q, function(err, r) { if(err) { cb(err); done(err); } else { cb(null, { rows: r.rows, count: count, limit: limit, offset: offset, page: page }); done(); } }); }); }); }
[ "function", "all", "(", "options", ",", "cb", ")", "{", "var", "q", ",", "page", "=", "Number", "(", "options", ".", "page", ")", "||", "1", ",", "limit", "=", "Number", "(", "options", ".", "limit", ")", "||", "conf", ".", "objects_by_page", ",", "offset", "=", "(", "page", "-", "1", ")", "*", "limit", ";", "count", "(", "function", "(", "err", ",", "count", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "q", "=", "select", "(", "'LEFT JOIN'", ")", ";", "q", "+=", "' LIMIT '", "+", "limit", "+", "' OFFSET '", "+", "offset", ";", "db", ".", "getClient", "(", "function", "(", "err", ",", "client", ",", "done", ")", "{", "client", ".", "query", "(", "q", ",", "function", "(", "err", ",", "r", ")", "{", "if", "(", "err", ")", "{", "cb", "(", "err", ")", ";", "done", "(", "err", ")", ";", "}", "else", "{", "cb", "(", "null", ",", "{", "rows", ":", "r", ".", "rows", ",", "count", ":", "count", ",", "limit", ":", "limit", ",", "offset", ":", "offset", ",", "page", ":", "page", "}", ")", ";", "done", "(", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Finds all tags @param {Object} options @param {Function} cb
[ "Finds", "all", "tags" ]
02f3a404cdfca608e8726bbacc33e32fec484b21
https://github.com/shinuza/captain-core/blob/02f3a404cdfca608e8726bbacc33e32fec484b21/lib/models/tags.js#L212-L242
55,682
MikeyBurkman/eggnog
src/context.js
nodeJsGlobalResolverFn
function nodeJsGlobalResolverFn(normalizedId) { var globalId = normalizedId.id; var x = global[globalId]; if (!x) { var msg = 'Could not find global Node module [' + globalId + ']'; throw new Error(buildMissingDepMsg(msg, globalId, Object.keys(global))); } return x; }
javascript
function nodeJsGlobalResolverFn(normalizedId) { var globalId = normalizedId.id; var x = global[globalId]; if (!x) { var msg = 'Could not find global Node module [' + globalId + ']'; throw new Error(buildMissingDepMsg(msg, globalId, Object.keys(global))); } return x; }
[ "function", "nodeJsGlobalResolverFn", "(", "normalizedId", ")", "{", "var", "globalId", "=", "normalizedId", ".", "id", ";", "var", "x", "=", "global", "[", "globalId", "]", ";", "if", "(", "!", "x", ")", "{", "var", "msg", "=", "'Could not find global Node module ['", "+", "globalId", "+", "']'", ";", "throw", "new", "Error", "(", "buildMissingDepMsg", "(", "msg", ",", "globalId", ",", "Object", ".", "keys", "(", "global", ")", ")", ")", ";", "}", "return", "x", ";", "}" ]
Returns a variable that available in the list of globals
[ "Returns", "a", "variable", "that", "available", "in", "the", "list", "of", "globals" ]
bdd64778e2d791b479cdf18bce81654fc9671f31
https://github.com/MikeyBurkman/eggnog/blob/bdd64778e2d791b479cdf18bce81654fc9671f31/src/context.js#L253-L261
55,683
MikeyBurkman/eggnog
src/context.js
nodeModulesResolverFn
function nodeModulesResolverFn(normalizedId) { if (!nodeModulesAt) { throw new Error('Before you can load external dependencies, you must specify where node_modules can be found by ' + 'setting the \'nodeModulesAt\' option when creating the context'); } var extId = normalizedId.id; var modulePath = path.join(nodeModulesAt, extId); if (!externalDepExists[modulePath]) { // yes I know the docs don't like this method. // But it's a little better user experience than trying to require a file that isn't there. if (fs.existsSync(modulePath)) { externalDepExists[modulePath] = true; // cache it so we avoid the lookup next time } else { var msg = 'Could not find external dependency [' + extId + '] at path [' + modulePath + ']'; throw new Error(buildMissingDepMsg(msg, extId, allExternalIds())); } } return require(modulePath); }
javascript
function nodeModulesResolverFn(normalizedId) { if (!nodeModulesAt) { throw new Error('Before you can load external dependencies, you must specify where node_modules can be found by ' + 'setting the \'nodeModulesAt\' option when creating the context'); } var extId = normalizedId.id; var modulePath = path.join(nodeModulesAt, extId); if (!externalDepExists[modulePath]) { // yes I know the docs don't like this method. // But it's a little better user experience than trying to require a file that isn't there. if (fs.existsSync(modulePath)) { externalDepExists[modulePath] = true; // cache it so we avoid the lookup next time } else { var msg = 'Could not find external dependency [' + extId + '] at path [' + modulePath + ']'; throw new Error(buildMissingDepMsg(msg, extId, allExternalIds())); } } return require(modulePath); }
[ "function", "nodeModulesResolverFn", "(", "normalizedId", ")", "{", "if", "(", "!", "nodeModulesAt", ")", "{", "throw", "new", "Error", "(", "'Before you can load external dependencies, you must specify where node_modules can be found by '", "+", "'setting the \\'nodeModulesAt\\' option when creating the context'", ")", ";", "}", "var", "extId", "=", "normalizedId", ".", "id", ";", "var", "modulePath", "=", "path", ".", "join", "(", "nodeModulesAt", ",", "extId", ")", ";", "if", "(", "!", "externalDepExists", "[", "modulePath", "]", ")", "{", "// yes I know the docs don't like this method.", "// But it's a little better user experience than trying to require a file that isn't there.", "if", "(", "fs", ".", "existsSync", "(", "modulePath", ")", ")", "{", "externalDepExists", "[", "modulePath", "]", "=", "true", ";", "// cache it so we avoid the lookup next time", "}", "else", "{", "var", "msg", "=", "'Could not find external dependency ['", "+", "extId", "+", "'] at path ['", "+", "modulePath", "+", "']'", ";", "throw", "new", "Error", "(", "buildMissingDepMsg", "(", "msg", ",", "extId", ",", "allExternalIds", "(", ")", ")", ")", ";", "}", "}", "return", "require", "(", "modulePath", ")", ";", "}" ]
Requires modules from the node_modules directory
[ "Requires", "modules", "from", "the", "node_modules", "directory" ]
bdd64778e2d791b479cdf18bce81654fc9671f31
https://github.com/MikeyBurkman/eggnog/blob/bdd64778e2d791b479cdf18bce81654fc9671f31/src/context.js#L269-L292
55,684
timkuijsten/node-idb-readable-stream
index.js
idbReadableStream
function idbReadableStream(db, storeName, opts) { if (typeof db !== 'object') throw new TypeError('db must be an object') if (typeof storeName !== 'string') throw new TypeError('storeName must be a string') if (opts == null) opts = {} if (typeof opts !== 'object') throw new TypeError('opts must be an object') // use transform stream for buffering and back pressure var transformer = new stream.Transform(xtend(opts, { objectMode: true, transform: function(obj, enc, cb) { cb(null, obj) } })) opts = xtend({ snapshot: false }, opts) var lastIteratedKey = null transformer._cursorsOpened = 0 function startCursor() { var lower, upper, lowerOpen, upperOpen var direction = opts.direction || 'next' var range = opts.range || {} lower = range.lower upper = range.upper lowerOpen = !!range.lowerOpen upperOpen = !!range.upperOpen // if this is not the first iteration, use lastIteratedKey if (lastIteratedKey) { if (direction === 'next') { lowerOpen = true // exclude the last iterated key itself lower = lastIteratedKey } else { upperOpen = true // exclude the last iterated key itself upper = lastIteratedKey } } var keyRange if (lower && upper) keyRange = IDBKeyRange.bound(lower, upper, lowerOpen, upperOpen) else if (lower) keyRange = IDBKeyRange.lowerBound(lower, lowerOpen) else if (upper) keyRange = IDBKeyRange.upperBound(upper, upperOpen) var tx = db.transaction(storeName, 'readonly') var store = tx.objectStore(storeName) transformer._cursorsOpened++ var req = store.openCursor(keyRange, opts.direction) function proceed(cursor) { try { cursor.continue() // throws a TransactionInactiveError if the cursor timed out } catch(err) { // either reopen a cursor or propagate the error if (err.name === 'TransactionInactiveError' && !opts.snapshot) startCursor() // IndexedDB timed out the cursor else transformer.emit('error', err) } } req.onsuccess = function() { var cursor = req.result if (cursor) { lastIteratedKey = cursor.key var go = transformer.write({ key: cursor.key, value: cursor.value }) if (opts.snapshot || go) proceed(cursor) else transformer.once('drain', function() { proceed(cursor) }) } else transformer.end() } tx.onabort = function() { transformer.emit('error', tx.error) } tx.onerror = function() { transformer.emit('error', tx.error) } } startCursor() return transformer }
javascript
function idbReadableStream(db, storeName, opts) { if (typeof db !== 'object') throw new TypeError('db must be an object') if (typeof storeName !== 'string') throw new TypeError('storeName must be a string') if (opts == null) opts = {} if (typeof opts !== 'object') throw new TypeError('opts must be an object') // use transform stream for buffering and back pressure var transformer = new stream.Transform(xtend(opts, { objectMode: true, transform: function(obj, enc, cb) { cb(null, obj) } })) opts = xtend({ snapshot: false }, opts) var lastIteratedKey = null transformer._cursorsOpened = 0 function startCursor() { var lower, upper, lowerOpen, upperOpen var direction = opts.direction || 'next' var range = opts.range || {} lower = range.lower upper = range.upper lowerOpen = !!range.lowerOpen upperOpen = !!range.upperOpen // if this is not the first iteration, use lastIteratedKey if (lastIteratedKey) { if (direction === 'next') { lowerOpen = true // exclude the last iterated key itself lower = lastIteratedKey } else { upperOpen = true // exclude the last iterated key itself upper = lastIteratedKey } } var keyRange if (lower && upper) keyRange = IDBKeyRange.bound(lower, upper, lowerOpen, upperOpen) else if (lower) keyRange = IDBKeyRange.lowerBound(lower, lowerOpen) else if (upper) keyRange = IDBKeyRange.upperBound(upper, upperOpen) var tx = db.transaction(storeName, 'readonly') var store = tx.objectStore(storeName) transformer._cursorsOpened++ var req = store.openCursor(keyRange, opts.direction) function proceed(cursor) { try { cursor.continue() // throws a TransactionInactiveError if the cursor timed out } catch(err) { // either reopen a cursor or propagate the error if (err.name === 'TransactionInactiveError' && !opts.snapshot) startCursor() // IndexedDB timed out the cursor else transformer.emit('error', err) } } req.onsuccess = function() { var cursor = req.result if (cursor) { lastIteratedKey = cursor.key var go = transformer.write({ key: cursor.key, value: cursor.value }) if (opts.snapshot || go) proceed(cursor) else transformer.once('drain', function() { proceed(cursor) }) } else transformer.end() } tx.onabort = function() { transformer.emit('error', tx.error) } tx.onerror = function() { transformer.emit('error', tx.error) } } startCursor() return transformer }
[ "function", "idbReadableStream", "(", "db", ",", "storeName", ",", "opts", ")", "{", "if", "(", "typeof", "db", "!==", "'object'", ")", "throw", "new", "TypeError", "(", "'db must be an object'", ")", "if", "(", "typeof", "storeName", "!==", "'string'", ")", "throw", "new", "TypeError", "(", "'storeName must be a string'", ")", "if", "(", "opts", "==", "null", ")", "opts", "=", "{", "}", "if", "(", "typeof", "opts", "!==", "'object'", ")", "throw", "new", "TypeError", "(", "'opts must be an object'", ")", "// use transform stream for buffering and back pressure", "var", "transformer", "=", "new", "stream", ".", "Transform", "(", "xtend", "(", "opts", ",", "{", "objectMode", ":", "true", ",", "transform", ":", "function", "(", "obj", ",", "enc", ",", "cb", ")", "{", "cb", "(", "null", ",", "obj", ")", "}", "}", ")", ")", "opts", "=", "xtend", "(", "{", "snapshot", ":", "false", "}", ",", "opts", ")", "var", "lastIteratedKey", "=", "null", "transformer", ".", "_cursorsOpened", "=", "0", "function", "startCursor", "(", ")", "{", "var", "lower", ",", "upper", ",", "lowerOpen", ",", "upperOpen", "var", "direction", "=", "opts", ".", "direction", "||", "'next'", "var", "range", "=", "opts", ".", "range", "||", "{", "}", "lower", "=", "range", ".", "lower", "upper", "=", "range", ".", "upper", "lowerOpen", "=", "!", "!", "range", ".", "lowerOpen", "upperOpen", "=", "!", "!", "range", ".", "upperOpen", "// if this is not the first iteration, use lastIteratedKey", "if", "(", "lastIteratedKey", ")", "{", "if", "(", "direction", "===", "'next'", ")", "{", "lowerOpen", "=", "true", "// exclude the last iterated key itself", "lower", "=", "lastIteratedKey", "}", "else", "{", "upperOpen", "=", "true", "// exclude the last iterated key itself", "upper", "=", "lastIteratedKey", "}", "}", "var", "keyRange", "if", "(", "lower", "&&", "upper", ")", "keyRange", "=", "IDBKeyRange", ".", "bound", "(", "lower", ",", "upper", ",", "lowerOpen", ",", "upperOpen", ")", "else", "if", "(", "lower", ")", "keyRange", "=", "IDBKeyRange", ".", "lowerBound", "(", "lower", ",", "lowerOpen", ")", "else", "if", "(", "upper", ")", "keyRange", "=", "IDBKeyRange", ".", "upperBound", "(", "upper", ",", "upperOpen", ")", "var", "tx", "=", "db", ".", "transaction", "(", "storeName", ",", "'readonly'", ")", "var", "store", "=", "tx", ".", "objectStore", "(", "storeName", ")", "transformer", ".", "_cursorsOpened", "++", "var", "req", "=", "store", ".", "openCursor", "(", "keyRange", ",", "opts", ".", "direction", ")", "function", "proceed", "(", "cursor", ")", "{", "try", "{", "cursor", ".", "continue", "(", ")", "// throws a TransactionInactiveError if the cursor timed out", "}", "catch", "(", "err", ")", "{", "// either reopen a cursor or propagate the error", "if", "(", "err", ".", "name", "===", "'TransactionInactiveError'", "&&", "!", "opts", ".", "snapshot", ")", "startCursor", "(", ")", "// IndexedDB timed out the cursor", "else", "transformer", ".", "emit", "(", "'error'", ",", "err", ")", "}", "}", "req", ".", "onsuccess", "=", "function", "(", ")", "{", "var", "cursor", "=", "req", ".", "result", "if", "(", "cursor", ")", "{", "lastIteratedKey", "=", "cursor", ".", "key", "var", "go", "=", "transformer", ".", "write", "(", "{", "key", ":", "cursor", ".", "key", ",", "value", ":", "cursor", ".", "value", "}", ")", "if", "(", "opts", ".", "snapshot", "||", "go", ")", "proceed", "(", "cursor", ")", "else", "transformer", ".", "once", "(", "'drain'", ",", "function", "(", ")", "{", "proceed", "(", "cursor", ")", "}", ")", "}", "else", "transformer", ".", "end", "(", ")", "}", "tx", ".", "onabort", "=", "function", "(", ")", "{", "transformer", ".", "emit", "(", "'error'", ",", "tx", ".", "error", ")", "}", "tx", ".", "onerror", "=", "function", "(", ")", "{", "transformer", ".", "emit", "(", "'error'", ",", "tx", ".", "error", ")", "}", "}", "startCursor", "(", ")", "return", "transformer", "}" ]
Iterate over an IndexedDB object store with a readable stream. @param {IDBDatabase} db - IndexedDB instance @param {String} storeName - name of the object store to iterate over @param {Object} [opts] Options: @param {IDBKeyRange} opts.range - a valid IndexedDB key range @param {IDBCursorDirection} opts.direction - one of "next", "nextunique", "prev", "prevunique" @param {Boolean} opts.snapshot=false - Iterate over a snapshot of the database by opening only one cursor. This disables any form of back pressure to prevent cursor timeout issues.
[ "Iterate", "over", "an", "IndexedDB", "object", "store", "with", "a", "readable", "stream", "." ]
b37424e5404ee631cccf563414cce0de1f867f8e
https://github.com/timkuijsten/node-idb-readable-stream/blob/b37424e5404ee631cccf563414cce0de1f867f8e/index.js#L38-L134
55,685
melvincarvalho/rdf-shell
bin/ls.js
bin
function bin(argv) { var uri = argv[2] if (!uri) { console.error('uri is required') } shell.ls(uri, function(err, arr) { for (i=0; i<arr.length; i++) { console.log(arr[i]) } }) }
javascript
function bin(argv) { var uri = argv[2] if (!uri) { console.error('uri is required') } shell.ls(uri, function(err, arr) { for (i=0; i<arr.length; i++) { console.log(arr[i]) } }) }
[ "function", "bin", "(", "argv", ")", "{", "var", "uri", "=", "argv", "[", "2", "]", "if", "(", "!", "uri", ")", "{", "console", ".", "error", "(", "'uri is required'", ")", "}", "shell", ".", "ls", "(", "uri", ",", "function", "(", "err", ",", "arr", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "arr", ".", "length", ";", "i", "++", ")", "{", "console", ".", "log", "(", "arr", "[", "i", "]", ")", "}", "}", ")", "}" ]
list the contents of a directory @param {[type]} argv [description] @return {[type]} [description]
[ "list", "the", "contents", "of", "a", "directory" ]
bf2015f6f333855e69a18ce3ec9e917bbddfb425
https://github.com/melvincarvalho/rdf-shell/blob/bf2015f6f333855e69a18ce3ec9e917bbddfb425/bin/ls.js#L10-L20
55,686
intervolga/bem-utils
lib/file-exist.js
fileExist
function fileExist(fileName) { return new Promise((resolve, reject) => { fs.stat(fileName, (err, stats) => { if (err === null && stats.isFile()) { resolve(fileName); } else { resolve(false); } }); }); }
javascript
function fileExist(fileName) { return new Promise((resolve, reject) => { fs.stat(fileName, (err, stats) => { if (err === null && stats.isFile()) { resolve(fileName); } else { resolve(false); } }); }); }
[ "function", "fileExist", "(", "fileName", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "fs", ".", "stat", "(", "fileName", ",", "(", "err", ",", "stats", ")", "=>", "{", "if", "(", "err", "===", "null", "&&", "stats", ".", "isFile", "(", ")", ")", "{", "resolve", "(", "fileName", ")", ";", "}", "else", "{", "resolve", "(", "false", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Promisified "file exist" check @param {String} fileName @return {Promise} resolves to fileName if exist, false otherwise
[ "Promisified", "file", "exist", "check" ]
3b81bb9bc408275486175326dc7f35c563a46563
https://github.com/intervolga/bem-utils/blob/3b81bb9bc408275486175326dc7f35c563a46563/lib/file-exist.js#L9-L19
55,687
iamchenxin/tagged-literals
lib/sql.js
SQL
function SQL(strs) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var values = []; var text = strs.reduce(function (prev, curr, i) { var arg = args[i - 1]; if (arg instanceof InsertValue) { return prev + arg.value + curr; } else { values.push(arg); return prev + '$' + values.length + curr; } }); return { text: text, values: values }; }
javascript
function SQL(strs) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var values = []; var text = strs.reduce(function (prev, curr, i) { var arg = args[i - 1]; if (arg instanceof InsertValue) { return prev + arg.value + curr; } else { values.push(arg); return prev + '$' + values.length + curr; } }); return { text: text, values: values }; }
[ "function", "SQL", "(", "strs", ")", "{", "for", "(", "var", "_len", "=", "arguments", ".", "length", ",", "args", "=", "Array", "(", "_len", ">", "1", "?", "_len", "-", "1", ":", "0", ")", ",", "_key", "=", "1", ";", "_key", "<", "_len", ";", "_key", "++", ")", "{", "args", "[", "_key", "-", "1", "]", "=", "arguments", "[", "_key", "]", ";", "}", "var", "values", "=", "[", "]", ";", "var", "text", "=", "strs", ".", "reduce", "(", "function", "(", "prev", ",", "curr", ",", "i", ")", "{", "var", "arg", "=", "args", "[", "i", "-", "1", "]", ";", "if", "(", "arg", "instanceof", "InsertValue", ")", "{", "return", "prev", "+", "arg", ".", "value", "+", "curr", ";", "}", "else", "{", "values", ".", "push", "(", "arg", ")", ";", "return", "prev", "+", "'$'", "+", "values", ".", "length", "+", "curr", ";", "}", "}", ")", ";", "return", "{", "text", ":", "text", ",", "values", ":", "values", "}", ";", "}" ]
for postgres sql
[ "for", "postgres", "sql" ]
932f803ff4006be76a49fa12675f3fad1092c517
https://github.com/iamchenxin/tagged-literals/blob/932f803ff4006be76a49fa12675f3fad1092c517/lib/sql.js#L26-L46
55,688
tunnckoCore/async-simple-iterator
index.js
AsyncSimpleIterator
function AsyncSimpleIterator (options) { if (!(this instanceof AsyncSimpleIterator)) { return new AsyncSimpleIterator(options) } this.defaultOptions(options) AppBase.call(this) this.on = utils.emitter.compose.call(this, 'on', this.options) this.off = utils.emitter.compose.call(this, 'off', this.options) this.once = utils.emitter.compose.call(this, 'once', this.options) this.emit = utils.emitter.compose.call(this, 'emit', this.options) }
javascript
function AsyncSimpleIterator (options) { if (!(this instanceof AsyncSimpleIterator)) { return new AsyncSimpleIterator(options) } this.defaultOptions(options) AppBase.call(this) this.on = utils.emitter.compose.call(this, 'on', this.options) this.off = utils.emitter.compose.call(this, 'off', this.options) this.once = utils.emitter.compose.call(this, 'once', this.options) this.emit = utils.emitter.compose.call(this, 'emit', this.options) }
[ "function", "AsyncSimpleIterator", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "AsyncSimpleIterator", ")", ")", "{", "return", "new", "AsyncSimpleIterator", "(", "options", ")", "}", "this", ".", "defaultOptions", "(", "options", ")", "AppBase", ".", "call", "(", "this", ")", "this", ".", "on", "=", "utils", ".", "emitter", ".", "compose", ".", "call", "(", "this", ",", "'on'", ",", "this", ".", "options", ")", "this", ".", "off", "=", "utils", ".", "emitter", ".", "compose", ".", "call", "(", "this", ",", "'off'", ",", "this", ".", "options", ")", "this", ".", "once", "=", "utils", ".", "emitter", ".", "compose", ".", "call", "(", "this", ",", "'once'", ",", "this", ".", "options", ")", "this", ".", "emit", "=", "utils", ".", "emitter", ".", "compose", ".", "call", "(", "this", ",", "'emit'", ",", "this", ".", "options", ")", "}" ]
> Initialize `AsyncSimpleIterator` with `options`. **Example** ```js var ctrl = require('async') var AsyncSimpleIterator = require('async-simple-iterator').AsyncSimpleIterator var fs = require('fs') var base = new AsyncSimpleIterator({ settle: true, beforeEach: function (val) { console.log('before each:', val) }, error: function (err, res, val) { console.log('on error:', val) } }) var iterator = base.wrapIterator(fs.stat, { afterEach: function (err, res, val) { console.log('after each:', val) } }) ctrl.map([ 'path/to/existing/file.js', 'filepath/not/exist', 'path/to/file' ], iterator, function (err, results) { // => `err` will always be null, if `settle:true` // => `results` is now an array of stats for each file }) ``` @param {Object=} `options` Pass `beforeEach`, `afterEach` and `error` hooks or `settle:true`. @api public
[ ">", "Initialize", "AsyncSimpleIterator", "with", "options", "." ]
c08b8b7f431c9013961a7d7255ee6a4e38d293ed
https://github.com/tunnckoCore/async-simple-iterator/blob/c08b8b7f431c9013961a7d7255ee6a4e38d293ed/index.js#L52-L62
55,689
TribeMedia/tribemedia-kurento-client-elements-js
lib/complexTypes/MediaProfileSpecType.js
checkMediaProfileSpecType
function checkMediaProfileSpecType(key, value) { if(typeof value != 'string') throw SyntaxError(key+' param should be a String, not '+typeof value); if(!value.match('WEBM|MP4|WEBM_VIDEO_ONLY|WEBM_AUDIO_ONLY|MP4_VIDEO_ONLY|MP4_AUDIO_ONLY')) throw SyntaxError(key+' param is not one of [WEBM|MP4|WEBM_VIDEO_ONLY|WEBM_AUDIO_ONLY|MP4_VIDEO_ONLY|MP4_AUDIO_ONLY] ('+value+')'); }
javascript
function checkMediaProfileSpecType(key, value) { if(typeof value != 'string') throw SyntaxError(key+' param should be a String, not '+typeof value); if(!value.match('WEBM|MP4|WEBM_VIDEO_ONLY|WEBM_AUDIO_ONLY|MP4_VIDEO_ONLY|MP4_AUDIO_ONLY')) throw SyntaxError(key+' param is not one of [WEBM|MP4|WEBM_VIDEO_ONLY|WEBM_AUDIO_ONLY|MP4_VIDEO_ONLY|MP4_AUDIO_ONLY] ('+value+')'); }
[ "function", "checkMediaProfileSpecType", "(", "key", ",", "value", ")", "{", "if", "(", "typeof", "value", "!=", "'string'", ")", "throw", "SyntaxError", "(", "key", "+", "' param should be a String, not '", "+", "typeof", "value", ")", ";", "if", "(", "!", "value", ".", "match", "(", "'WEBM|MP4|WEBM_VIDEO_ONLY|WEBM_AUDIO_ONLY|MP4_VIDEO_ONLY|MP4_AUDIO_ONLY'", ")", ")", "throw", "SyntaxError", "(", "key", "+", "' param is not one of [WEBM|MP4|WEBM_VIDEO_ONLY|WEBM_AUDIO_ONLY|MP4_VIDEO_ONLY|MP4_AUDIO_ONLY] ('", "+", "value", "+", "')'", ")", ";", "}" ]
Media Profile. Currently WEBM and MP4 are supported. @typedef elements/complexTypes.MediaProfileSpecType @type {(WEBM|MP4|WEBM_VIDEO_ONLY|WEBM_AUDIO_ONLY|MP4_VIDEO_ONLY|MP4_AUDIO_ONLY)} Checker for {@link elements/complexTypes.MediaProfileSpecType} @memberof module:elements/complexTypes @param {external:String} key @param {module:elements/complexTypes.MediaProfileSpecType} value
[ "Media", "Profile", ".", "Currently", "WEBM", "and", "MP4", "are", "supported", "." ]
1a5570f05bf8c2c25bbeceb4f96cb2770f634de9
https://github.com/TribeMedia/tribemedia-kurento-client-elements-js/blob/1a5570f05bf8c2c25bbeceb4f96cb2770f634de9/lib/complexTypes/MediaProfileSpecType.js#L38-L45
55,690
uugolab/sycle
lib/sycle.js
createApplication
function createApplication(options) { options = options || {}; var sapp = new Application(); sapp.sycle = sycle; if (options.loadBuiltinModels) { sapp.phase(require('./boot/builtin-models')()); } return sapp; }
javascript
function createApplication(options) { options = options || {}; var sapp = new Application(); sapp.sycle = sycle; if (options.loadBuiltinModels) { sapp.phase(require('./boot/builtin-models')()); } return sapp; }
[ "function", "createApplication", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "sapp", "=", "new", "Application", "(", ")", ";", "sapp", ".", "sycle", "=", "sycle", ";", "if", "(", "options", ".", "loadBuiltinModels", ")", "{", "sapp", ".", "phase", "(", "require", "(", "'./boot/builtin-models'", ")", "(", ")", ")", ";", "}", "return", "sapp", ";", "}" ]
Create an sycle application. @param options @returns {Application} @api public
[ "Create", "an", "sycle", "application", "." ]
90902246537860adee22664a584c66d72826b5bb
https://github.com/uugolab/sycle/blob/90902246537860adee22664a584c66d72826b5bb/lib/sycle.js#L15-L26
55,691
arpinum-oss/js-promising
benchmarks/queue.js
enqueueAll
function enqueueAll() { for (let i = 0; i < count - 1; i++) { enqueue(); } return enqueue(); function enqueue() { return queue.enqueue(() => new Date()); } }
javascript
function enqueueAll() { for (let i = 0; i < count - 1; i++) { enqueue(); } return enqueue(); function enqueue() { return queue.enqueue(() => new Date()); } }
[ "function", "enqueueAll", "(", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "count", "-", "1", ";", "i", "++", ")", "{", "enqueue", "(", ")", ";", "}", "return", "enqueue", "(", ")", ";", "function", "enqueue", "(", ")", "{", "return", "queue", ".", "enqueue", "(", "(", ")", "=>", "new", "Date", "(", ")", ")", ";", "}", "}" ]
100000 functions enqueued in 798 ms
[ "100000", "functions", "enqueued", "in", "798", "ms" ]
710712e7d2b1429bda92d21c420d79d16cc6160a
https://github.com/arpinum-oss/js-promising/blob/710712e7d2b1429bda92d21c420d79d16cc6160a/benchmarks/queue.js#L13-L22
55,692
zoopdoop/zoopinator
lib/zoopinator.js
bakeFolder
function bakeFolder(source, dest) { var args = createArgs(source, dest, {}); wrapFunction('BakeFolder', args, function () { args.files = fs.readdirSync(args.source); args.filters = [filterHidden]; wrapFunction('FilterFiles', args, function () { args.filters.forEach(function (filter) { args.files = args.files.filter(filter); }); }); delete args.filters; wrapFunction('BakeFiles', args, function () { var files = [], dirs = []; // seperate the files from the directories args.files.forEach(function (file) { var stats = fs.statSync(path.join(args.source, file)); if (stats.isDirectory()) { dirs.push(file); } else { files.push(file); } }); // process all the files first files.forEach(function (file) { bakeFile(path.join(args.source, file), path.join(args.dest, file)); }); // and then process the sub directories dirs.forEach(function (file) { bakeFolder(path.join(args.source, file), path.join(args.dest, file)); }); }); }); function filterHidden(file) { return !(/^\.|~$/).test(file); } }
javascript
function bakeFolder(source, dest) { var args = createArgs(source, dest, {}); wrapFunction('BakeFolder', args, function () { args.files = fs.readdirSync(args.source); args.filters = [filterHidden]; wrapFunction('FilterFiles', args, function () { args.filters.forEach(function (filter) { args.files = args.files.filter(filter); }); }); delete args.filters; wrapFunction('BakeFiles', args, function () { var files = [], dirs = []; // seperate the files from the directories args.files.forEach(function (file) { var stats = fs.statSync(path.join(args.source, file)); if (stats.isDirectory()) { dirs.push(file); } else { files.push(file); } }); // process all the files first files.forEach(function (file) { bakeFile(path.join(args.source, file), path.join(args.dest, file)); }); // and then process the sub directories dirs.forEach(function (file) { bakeFolder(path.join(args.source, file), path.join(args.dest, file)); }); }); }); function filterHidden(file) { return !(/^\.|~$/).test(file); } }
[ "function", "bakeFolder", "(", "source", ",", "dest", ")", "{", "var", "args", "=", "createArgs", "(", "source", ",", "dest", ",", "{", "}", ")", ";", "wrapFunction", "(", "'BakeFolder'", ",", "args", ",", "function", "(", ")", "{", "args", ".", "files", "=", "fs", ".", "readdirSync", "(", "args", ".", "source", ")", ";", "args", ".", "filters", "=", "[", "filterHidden", "]", ";", "wrapFunction", "(", "'FilterFiles'", ",", "args", ",", "function", "(", ")", "{", "args", ".", "filters", ".", "forEach", "(", "function", "(", "filter", ")", "{", "args", ".", "files", "=", "args", ".", "files", ".", "filter", "(", "filter", ")", ";", "}", ")", ";", "}", ")", ";", "delete", "args", ".", "filters", ";", "wrapFunction", "(", "'BakeFiles'", ",", "args", ",", "function", "(", ")", "{", "var", "files", "=", "[", "]", ",", "dirs", "=", "[", "]", ";", "// seperate the files from the directories", "args", ".", "files", ".", "forEach", "(", "function", "(", "file", ")", "{", "var", "stats", "=", "fs", ".", "statSync", "(", "path", ".", "join", "(", "args", ".", "source", ",", "file", ")", ")", ";", "if", "(", "stats", ".", "isDirectory", "(", ")", ")", "{", "dirs", ".", "push", "(", "file", ")", ";", "}", "else", "{", "files", ".", "push", "(", "file", ")", ";", "}", "}", ")", ";", "// process all the files first", "files", ".", "forEach", "(", "function", "(", "file", ")", "{", "bakeFile", "(", "path", ".", "join", "(", "args", ".", "source", ",", "file", ")", ",", "path", ".", "join", "(", "args", ".", "dest", ",", "file", ")", ")", ";", "}", ")", ";", "// and then process the sub directories", "dirs", ".", "forEach", "(", "function", "(", "file", ")", "{", "bakeFolder", "(", "path", ".", "join", "(", "args", ".", "source", ",", "file", ")", ",", "path", ".", "join", "(", "args", ".", "dest", ",", "file", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "function", "filterHidden", "(", "file", ")", "{", "return", "!", "(", "/", "^\\.|~$", "/", ")", ".", "test", "(", "file", ")", ";", "}", "}" ]
processes all the files in a folder
[ "processes", "all", "the", "files", "in", "a", "folder" ]
64526031b6657eec4e00dfd5cf3ec2dc0a4ddf01
https://github.com/zoopdoop/zoopinator/blob/64526031b6657eec4e00dfd5cf3ec2dc0a4ddf01/lib/zoopinator.js#L125-L170
55,693
camshaft/pack-n-stack
lib/proto.js
defaults
function defaults(route, name, handle) { if (typeof route === 'function') { handle = route; name = handle.name; route = '/'; } else if (typeof name === 'function') { handle = name; name = handle.name; } // A name needs to be provided if (!name) throw new NameError(); // wrap sub-apps if ('function' == typeof handle.handle) { var server = handle; handle.route = route; handle = function(req, res, next){ server.handle(req, res, next); }; } // wrap vanilla http.Servers if (handle instanceof http.Server) { handle = handle.listeners('request')[0]; } // strip trailing slash if ('/' == route[route.length - 1]) { route = route.slice(0, -1); } return {route: route, name: name, handle: handle}; }
javascript
function defaults(route, name, handle) { if (typeof route === 'function') { handle = route; name = handle.name; route = '/'; } else if (typeof name === 'function') { handle = name; name = handle.name; } // A name needs to be provided if (!name) throw new NameError(); // wrap sub-apps if ('function' == typeof handle.handle) { var server = handle; handle.route = route; handle = function(req, res, next){ server.handle(req, res, next); }; } // wrap vanilla http.Servers if (handle instanceof http.Server) { handle = handle.listeners('request')[0]; } // strip trailing slash if ('/' == route[route.length - 1]) { route = route.slice(0, -1); } return {route: route, name: name, handle: handle}; }
[ "function", "defaults", "(", "route", ",", "name", ",", "handle", ")", "{", "if", "(", "typeof", "route", "===", "'function'", ")", "{", "handle", "=", "route", ";", "name", "=", "handle", ".", "name", ";", "route", "=", "'/'", ";", "}", "else", "if", "(", "typeof", "name", "===", "'function'", ")", "{", "handle", "=", "name", ";", "name", "=", "handle", ".", "name", ";", "}", "// A name needs to be provided", "if", "(", "!", "name", ")", "throw", "new", "NameError", "(", ")", ";", "// wrap sub-apps", "if", "(", "'function'", "==", "typeof", "handle", ".", "handle", ")", "{", "var", "server", "=", "handle", ";", "handle", ".", "route", "=", "route", ";", "handle", "=", "function", "(", "req", ",", "res", ",", "next", ")", "{", "server", ".", "handle", "(", "req", ",", "res", ",", "next", ")", ";", "}", ";", "}", "// wrap vanilla http.Servers", "if", "(", "handle", "instanceof", "http", ".", "Server", ")", "{", "handle", "=", "handle", ".", "listeners", "(", "'request'", ")", "[", "0", "]", ";", "}", "// strip trailing slash", "if", "(", "'/'", "==", "route", "[", "route", ".", "length", "-", "1", "]", ")", "{", "route", "=", "route", ".", "slice", "(", "0", ",", "-", "1", ")", ";", "}", "return", "{", "route", ":", "route", ",", "name", ":", "name", ",", "handle", ":", "handle", "}", ";", "}" ]
Default the parameters @api private
[ "Default", "the", "parameters" ]
ec5fe9a4cb9895b89e137e966a4eaffb7931881c
https://github.com/camshaft/pack-n-stack/blob/ec5fe9a4cb9895b89e137e966a4eaffb7931881c/lib/proto.js#L224-L258
55,694
camshaft/pack-n-stack
lib/proto.js
NameError
function NameError(message) { Error.call(this); Error.captureStackTrace(this, arguments.callee); this.name = 'Middleware Name Error'; this.message = message || 'The argument must be a named function or supply a name'; }
javascript
function NameError(message) { Error.call(this); Error.captureStackTrace(this, arguments.callee); this.name = 'Middleware Name Error'; this.message = message || 'The argument must be a named function or supply a name'; }
[ "function", "NameError", "(", "message", ")", "{", "Error", ".", "call", "(", "this", ")", ";", "Error", ".", "captureStackTrace", "(", "this", ",", "arguments", ".", "callee", ")", ";", "this", ".", "name", "=", "'Middleware Name Error'", ";", "this", ".", "message", "=", "message", "||", "'The argument must be a named function or supply a name'", ";", "}" ]
errors Define an error for middleware not being named
[ "errors", "Define", "an", "error", "for", "middleware", "not", "being", "named" ]
ec5fe9a4cb9895b89e137e966a4eaffb7931881c
https://github.com/camshaft/pack-n-stack/blob/ec5fe9a4cb9895b89e137e966a4eaffb7931881c/lib/proto.js#L265-L270
55,695
camshaft/pack-n-stack
lib/proto.js
ExistsError
function ExistsError(name, message) { Error.call(this); Error.captureStackTrace(this, arguments.callee); this.name = 'Middleware Exists Error'; this.message = message || 'Middleware named ' + name + ' already exists. Provide an alternative name.'; }
javascript
function ExistsError(name, message) { Error.call(this); Error.captureStackTrace(this, arguments.callee); this.name = 'Middleware Exists Error'; this.message = message || 'Middleware named ' + name + ' already exists. Provide an alternative name.'; }
[ "function", "ExistsError", "(", "name", ",", "message", ")", "{", "Error", ".", "call", "(", "this", ")", ";", "Error", ".", "captureStackTrace", "(", "this", ",", "arguments", ".", "callee", ")", ";", "this", ".", "name", "=", "'Middleware Exists Error'", ";", "this", ".", "message", "=", "message", "||", "'Middleware named '", "+", "name", "+", "' already exists. Provide an alternative name.'", ";", "}" ]
Define an error for middleware already in the stack
[ "Define", "an", "error", "for", "middleware", "already", "in", "the", "stack" ]
ec5fe9a4cb9895b89e137e966a4eaffb7931881c
https://github.com/camshaft/pack-n-stack/blob/ec5fe9a4cb9895b89e137e966a4eaffb7931881c/lib/proto.js#L276-L281
55,696
camshaft/pack-n-stack
lib/proto.js
NotFoundError
function NotFoundError(name) { Error.call(this); Error.captureStackTrace(this, arguments.callee); this.name = 'Middleware Not Found Error'; this.message = name + ' not found in the current stack'; }
javascript
function NotFoundError(name) { Error.call(this); Error.captureStackTrace(this, arguments.callee); this.name = 'Middleware Not Found Error'; this.message = name + ' not found in the current stack'; }
[ "function", "NotFoundError", "(", "name", ")", "{", "Error", ".", "call", "(", "this", ")", ";", "Error", ".", "captureStackTrace", "(", "this", ",", "arguments", ".", "callee", ")", ";", "this", ".", "name", "=", "'Middleware Not Found Error'", ";", "this", ".", "message", "=", "name", "+", "' not found in the current stack'", ";", "}" ]
Define an error for middleware not found in the stack
[ "Define", "an", "error", "for", "middleware", "not", "found", "in", "the", "stack" ]
ec5fe9a4cb9895b89e137e966a4eaffb7931881c
https://github.com/camshaft/pack-n-stack/blob/ec5fe9a4cb9895b89e137e966a4eaffb7931881c/lib/proto.js#L287-L292
55,697
AndreasMadsen/immortal
lib/core/process.js
Process
function Process(settings) { // save arguments this.settings = settings; // build args this.args = [settings.file].concat(settings.args || []); // build env this.env = helpers.mergeObject({}, settings.env || process.env); if (settings.options) { this.env.spawnOptions = JSON.stringify(settings.options); } // defaults properties this.closed = !!settings.close; this.suicide = false; this.pid = null; this.alive = false; // this streams will relay data from and to the process this.stderr = new streams.RelayStream({ paused: false }); this.stdout = new streams.RelayStream({ paused: false }); this.stdin = new streams.RelayStream({ paused: false }); // relay io if (this.settings.ipc && helpers.support.pipeFork) { this.send = function () { this.process.send.apply(this.process, arguments); }; this.flush = function () {}; } }
javascript
function Process(settings) { // save arguments this.settings = settings; // build args this.args = [settings.file].concat(settings.args || []); // build env this.env = helpers.mergeObject({}, settings.env || process.env); if (settings.options) { this.env.spawnOptions = JSON.stringify(settings.options); } // defaults properties this.closed = !!settings.close; this.suicide = false; this.pid = null; this.alive = false; // this streams will relay data from and to the process this.stderr = new streams.RelayStream({ paused: false }); this.stdout = new streams.RelayStream({ paused: false }); this.stdin = new streams.RelayStream({ paused: false }); // relay io if (this.settings.ipc && helpers.support.pipeFork) { this.send = function () { this.process.send.apply(this.process, arguments); }; this.flush = function () {}; } }
[ "function", "Process", "(", "settings", ")", "{", "// save arguments", "this", ".", "settings", "=", "settings", ";", "// build args", "this", ".", "args", "=", "[", "settings", ".", "file", "]", ".", "concat", "(", "settings", ".", "args", "||", "[", "]", ")", ";", "// build env", "this", ".", "env", "=", "helpers", ".", "mergeObject", "(", "{", "}", ",", "settings", ".", "env", "||", "process", ".", "env", ")", ";", "if", "(", "settings", ".", "options", ")", "{", "this", ".", "env", ".", "spawnOptions", "=", "JSON", ".", "stringify", "(", "settings", ".", "options", ")", ";", "}", "// defaults properties", "this", ".", "closed", "=", "!", "!", "settings", ".", "close", ";", "this", ".", "suicide", "=", "false", ";", "this", ".", "pid", "=", "null", ";", "this", ".", "alive", "=", "false", ";", "// this streams will relay data from and to the process", "this", ".", "stderr", "=", "new", "streams", ".", "RelayStream", "(", "{", "paused", ":", "false", "}", ")", ";", "this", ".", "stdout", "=", "new", "streams", ".", "RelayStream", "(", "{", "paused", ":", "false", "}", ")", ";", "this", ".", "stdin", "=", "new", "streams", ".", "RelayStream", "(", "{", "paused", ":", "false", "}", ")", ";", "// relay io", "if", "(", "this", ".", "settings", ".", "ipc", "&&", "helpers", ".", "support", ".", "pipeFork", ")", "{", "this", ".", "send", "=", "function", "(", ")", "{", "this", ".", "process", ".", "send", ".", "apply", "(", "this", ".", "process", ",", "arguments", ")", ";", "}", ";", "this", ".", "flush", "=", "function", "(", ")", "{", "}", ";", "}", "}" ]
this constrcutor will spawn a new process using a option object
[ "this", "constrcutor", "will", "spawn", "a", "new", "process", "using", "a", "option", "object" ]
c1ab5a4287a543fdfd980604a9e9927d663a9ef2
https://github.com/AndreasMadsen/immortal/blob/c1ab5a4287a543fdfd980604a9e9927d663a9ef2/lib/core/process.js#L17-L48
55,698
AndreasMadsen/immortal
lib/core/process.js
function () { var suicide = self.suicide; self.suicide = false; self.alive = false; self.emit('stop', suicide); }
javascript
function () { var suicide = self.suicide; self.suicide = false; self.alive = false; self.emit('stop', suicide); }
[ "function", "(", ")", "{", "var", "suicide", "=", "self", ".", "suicide", ";", "self", ".", "suicide", "=", "false", ";", "self", ".", "alive", "=", "false", ";", "self", ".", "emit", "(", "'stop'", ",", "suicide", ")", ";", "}" ]
handle process stdio close event
[ "handle", "process", "stdio", "close", "event" ]
c1ab5a4287a543fdfd980604a9e9927d663a9ef2
https://github.com/AndreasMadsen/immortal/blob/c1ab5a4287a543fdfd980604a9e9927d663a9ef2/lib/core/process.js#L134-L139
55,699
AndreasMadsen/immortal
lib/core/process.js
forceClose
function forceClose(channel) { if (!channel) return; var destroyer = setTimeout(function () { channel.destroy(); }, 200); channel.once('close', function () { clearTimeout(destroyer); }); }
javascript
function forceClose(channel) { if (!channel) return; var destroyer = setTimeout(function () { channel.destroy(); }, 200); channel.once('close', function () { clearTimeout(destroyer); }); }
[ "function", "forceClose", "(", "channel", ")", "{", "if", "(", "!", "channel", ")", "return", ";", "var", "destroyer", "=", "setTimeout", "(", "function", "(", ")", "{", "channel", ".", "destroy", "(", ")", ";", "}", ",", "200", ")", ";", "channel", ".", "once", "(", "'close'", ",", "function", "(", ")", "{", "clearTimeout", "(", "destroyer", ")", ";", "}", ")", ";", "}" ]
close all streams
[ "close", "all", "streams" ]
c1ab5a4287a543fdfd980604a9e9927d663a9ef2
https://github.com/AndreasMadsen/immortal/blob/c1ab5a4287a543fdfd980604a9e9927d663a9ef2/lib/core/process.js#L166-L176