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
56,100
sittingbool/sbool-node-utils
util/configLoader.js
function( path) { var stat = null; try { stat = fs.statSync( path ); } catch (err) { console.log(err); } return ( stat && stat.isFile() ); }
javascript
function( path) { var stat = null; try { stat = fs.statSync( path ); } catch (err) { console.log(err); } return ( stat && stat.isFile() ); }
[ "function", "(", "path", ")", "{", "var", "stat", "=", "null", ";", "try", "{", "stat", "=", "fs", ".", "statSync", "(", "path", ")", ";", "}", "catch", "(", "err", ")", "{", "console", ".", "log", "(", "err", ")", ";", "}", "return", "(", "stat", "&&", "stat", ".", "isFile", "(", ")", ")", ";", "}" ]
Loads config file with many options @param configDir - directory which should be used for @param options - object that can take following parameters: configEnvironmentVar: key that is used on process.env[<key>] to use it as oath to config directory subDirPath: path within the directory loaded over configEnvironmentVar fileToBeLoaded: name of the file that should be found altDirNameKey: if directory has an index.js we will require it and use this key to get get the path for the subdirectory altFileNameKey: if directory has an index.js we will require it and use this key to get get the file name that should be loaded defaultFilePath: path to fallback file
[ "Loads", "config", "file", "with", "many", "options" ]
30a5b71bc258b160883451ede8c6c3991294fd68
https://github.com/sittingbool/sbool-node-utils/blob/30a5b71bc258b160883451ede8c6c3991294fd68/util/configLoader.js#L24-L35
56,101
joshwnj/marki
src/setup-highlighter.js
loadHighlighter
function loadHighlighter () { var headElem = d.querySelector('head'); headElem.appendChild(h('link', { rel: 'stylesheet', href: 'http://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css' })); headElem.appendChild(h('script', { src: 'http://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js' })); var interval = setInterval(function () { if (!!window.hljs) { clearInterval(interval); applyHighlighter(); } }, 100); }
javascript
function loadHighlighter () { var headElem = d.querySelector('head'); headElem.appendChild(h('link', { rel: 'stylesheet', href: 'http://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css' })); headElem.appendChild(h('script', { src: 'http://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js' })); var interval = setInterval(function () { if (!!window.hljs) { clearInterval(interval); applyHighlighter(); } }, 100); }
[ "function", "loadHighlighter", "(", ")", "{", "var", "headElem", "=", "d", ".", "querySelector", "(", "'head'", ")", ";", "headElem", ".", "appendChild", "(", "h", "(", "'link'", ",", "{", "rel", ":", "'stylesheet'", ",", "href", ":", "'http://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css'", "}", ")", ")", ";", "headElem", ".", "appendChild", "(", "h", "(", "'script'", ",", "{", "src", ":", "'http://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js'", "}", ")", ")", ";", "var", "interval", "=", "setInterval", "(", "function", "(", ")", "{", "if", "(", "!", "!", "window", ".", "hljs", ")", "{", "clearInterval", "(", "interval", ")", ";", "applyHighlighter", "(", ")", ";", "}", "}", ",", "100", ")", ";", "}" ]
load syntax highlighting code
[ "load", "syntax", "highlighting", "code" ]
1809630593c74b38313add82d54f88491e00cd4f
https://github.com/joshwnj/marki/blob/1809630593c74b38313add82d54f88491e00cd4f/src/setup-highlighter.js#L5-L23
56,102
fibo/algebra-ring
algebra-ring.js
algebraRing
function algebraRing (identities, given) { // A ring is a group, with multiplication. const ring = group({ identity: identities[0], contains: given.contains, equality: given.equality, compositionLaw: given.addition, inversion: given.negation }) // operators function multiplication () { return [].slice.call(arguments).reduce(given.multiplication) } function inversion (a) { if (ring.equality(a, ring.zero)) { throw new TypeError(error.cannotDivideByZero) } return given.inversion(a) } function division (a) { const rest = [].slice.call(arguments, 1) return given.multiplication(a, rest.map(inversion).reduce(given.multiplication)) } ring.multiplication = multiplication ring.inversion = inversion ring.division = division // Multiplicative identity. const one = identities[1] if (ring.notContains(one)) { throw new TypeError(error.doesNotContainIdentity) } // Check that one*one=one. if (ring.disequality(given.multiplication(one, one), one)) { throw new TypeError(error.identityIsNotNeutral) } if (ring.notContains(identities[1])) { throw new TypeError(error.doesNotContainIdentity) } ring.one = identities[1] return ring }
javascript
function algebraRing (identities, given) { // A ring is a group, with multiplication. const ring = group({ identity: identities[0], contains: given.contains, equality: given.equality, compositionLaw: given.addition, inversion: given.negation }) // operators function multiplication () { return [].slice.call(arguments).reduce(given.multiplication) } function inversion (a) { if (ring.equality(a, ring.zero)) { throw new TypeError(error.cannotDivideByZero) } return given.inversion(a) } function division (a) { const rest = [].slice.call(arguments, 1) return given.multiplication(a, rest.map(inversion).reduce(given.multiplication)) } ring.multiplication = multiplication ring.inversion = inversion ring.division = division // Multiplicative identity. const one = identities[1] if (ring.notContains(one)) { throw new TypeError(error.doesNotContainIdentity) } // Check that one*one=one. if (ring.disequality(given.multiplication(one, one), one)) { throw new TypeError(error.identityIsNotNeutral) } if (ring.notContains(identities[1])) { throw new TypeError(error.doesNotContainIdentity) } ring.one = identities[1] return ring }
[ "function", "algebraRing", "(", "identities", ",", "given", ")", "{", "// A ring is a group, with multiplication.", "const", "ring", "=", "group", "(", "{", "identity", ":", "identities", "[", "0", "]", ",", "contains", ":", "given", ".", "contains", ",", "equality", ":", "given", ".", "equality", ",", "compositionLaw", ":", "given", ".", "addition", ",", "inversion", ":", "given", ".", "negation", "}", ")", "// operators", "function", "multiplication", "(", ")", "{", "return", "[", "]", ".", "slice", ".", "call", "(", "arguments", ")", ".", "reduce", "(", "given", ".", "multiplication", ")", "}", "function", "inversion", "(", "a", ")", "{", "if", "(", "ring", ".", "equality", "(", "a", ",", "ring", ".", "zero", ")", ")", "{", "throw", "new", "TypeError", "(", "error", ".", "cannotDivideByZero", ")", "}", "return", "given", ".", "inversion", "(", "a", ")", "}", "function", "division", "(", "a", ")", "{", "const", "rest", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", "return", "given", ".", "multiplication", "(", "a", ",", "rest", ".", "map", "(", "inversion", ")", ".", "reduce", "(", "given", ".", "multiplication", ")", ")", "}", "ring", ".", "multiplication", "=", "multiplication", "ring", ".", "inversion", "=", "inversion", "ring", ".", "division", "=", "division", "// Multiplicative identity.", "const", "one", "=", "identities", "[", "1", "]", "if", "(", "ring", ".", "notContains", "(", "one", ")", ")", "{", "throw", "new", "TypeError", "(", "error", ".", "doesNotContainIdentity", ")", "}", "// Check that one*one=one.", "if", "(", "ring", ".", "disequality", "(", "given", ".", "multiplication", "(", "one", ",", "one", ")", ",", "one", ")", ")", "{", "throw", "new", "TypeError", "(", "error", ".", "identityIsNotNeutral", ")", "}", "if", "(", "ring", ".", "notContains", "(", "identities", "[", "1", "]", ")", ")", "{", "throw", "new", "TypeError", "(", "error", ".", "doesNotContainIdentity", ")", "}", "ring", ".", "one", "=", "identities", "[", "1", "]", "return", "ring", "}" ]
Define an algebra ring structure @param {Array} identities @param {*} identities[0] a.k.a zero @param {*} identities[1] a.k.a uno @param {Object} given operator functions @param {Function} given.contains @param {Function} given.equality @param {Function} given.addition @param {Function} given.negation @param {Function} given.multiplication @param {Function} given.inversion @returns {Object} ring
[ "Define", "an", "algebra", "ring", "structure" ]
5fb3c6e88e6ded23f20b478eb5aeb1ff142a59a4
https://github.com/fibo/algebra-ring/blob/5fb3c6e88e6ded23f20b478eb5aeb1ff142a59a4/algebra-ring.js#L37-L92
56,103
substance/converter
src/converter.js
__pandocAvailable
function __pandocAvailable(cb) { var test = spawn('pandoc', ['--help']); test.on('error', function() { console.error('Pandoc not found'); cb('Pandoc not found'); }); test.on('exit', function() { cb(null); }); test.stdin.end(); }
javascript
function __pandocAvailable(cb) { var test = spawn('pandoc', ['--help']); test.on('error', function() { console.error('Pandoc not found'); cb('Pandoc not found'); }); test.on('exit', function() { cb(null); }); test.stdin.end(); }
[ "function", "__pandocAvailable", "(", "cb", ")", "{", "var", "test", "=", "spawn", "(", "'pandoc'", ",", "[", "'--help'", "]", ")", ";", "test", ".", "on", "(", "'error'", ",", "function", "(", ")", "{", "console", ".", "error", "(", "'Pandoc not found'", ")", ";", "cb", "(", "'Pandoc not found'", ")", ";", "}", ")", ";", "test", ".", "on", "(", "'exit'", ",", "function", "(", ")", "{", "cb", "(", "null", ")", ";", "}", ")", ";", "test", ".", "stdin", ".", "end", "(", ")", ";", "}" ]
Checks if the pandoc tool is available
[ "Checks", "if", "the", "pandoc", "tool", "is", "available" ]
d98f4d531a339cada47ac6329cec4b7aaacb1605
https://github.com/substance/converter/blob/d98f4d531a339cada47ac6329cec4b7aaacb1605/src/converter.js#L30-L38
56,104
RnbWd/parse-browserify
lib/facebook.js
function(user, permissions, options) { if (!permissions || _.isString(permissions)) { if (!initialized) { throw "You must initialize FacebookUtils before calling link."; } requestedPermissions = permissions; return user._linkWith("facebook", options); } else { var newOptions = _.clone(options) || {}; newOptions.authData = permissions; return user._linkWith("facebook", newOptions); } }
javascript
function(user, permissions, options) { if (!permissions || _.isString(permissions)) { if (!initialized) { throw "You must initialize FacebookUtils before calling link."; } requestedPermissions = permissions; return user._linkWith("facebook", options); } else { var newOptions = _.clone(options) || {}; newOptions.authData = permissions; return user._linkWith("facebook", newOptions); } }
[ "function", "(", "user", ",", "permissions", ",", "options", ")", "{", "if", "(", "!", "permissions", "||", "_", ".", "isString", "(", "permissions", ")", ")", "{", "if", "(", "!", "initialized", ")", "{", "throw", "\"You must initialize FacebookUtils before calling link.\"", ";", "}", "requestedPermissions", "=", "permissions", ";", "return", "user", ".", "_linkWith", "(", "\"facebook\"", ",", "options", ")", ";", "}", "else", "{", "var", "newOptions", "=", "_", ".", "clone", "(", "options", ")", "||", "{", "}", ";", "newOptions", ".", "authData", "=", "permissions", ";", "return", "user", ".", "_linkWith", "(", "\"facebook\"", ",", "newOptions", ")", ";", "}", "}" ]
Links Facebook to an existing PFUser. This method delegates to the Facebook SDK to authenticate the user, and then automatically links the account to the Parse.User. @param {Parse.User} user User to link to Facebook. This must be the current user. @param {String, Object} permissions The permissions required for Facebook log in. This is a comma-separated string of permissions. Alternatively, supply a Facebook authData object as described in our REST API docs if you want to handle getting facebook auth tokens yourself. @param {Object} options Standard options object with success and error callbacks.
[ "Links", "Facebook", "to", "an", "existing", "PFUser", ".", "This", "method", "delegates", "to", "the", "Facebook", "SDK", "to", "authenticate", "the", "user", "and", "then", "automatically", "links", "the", "account", "to", "the", "Parse", ".", "User", "." ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/facebook.js#L162-L174
56,105
cli-kit/cli-property
lib/expand.js
expand
function expand(source, opts) { opts = opts || {}; var re = opts.re = opts.re || '.' , isre = (re instanceof RegExp) , o = {}, k, v, parts, i, p; for(k in source) { v = source[k]; if(isre ? !re.test(k) : !~k.indexOf(re)) { o[k] = v; }else{ parts = k.split(re); p = o; for(i = 0;i < parts.length;i++) { k = parts[i]; if(i < parts.length - 1) { p[k] = p[k] || {}; p = p[k]; }else{ p[k] = v; } } } } return o; }
javascript
function expand(source, opts) { opts = opts || {}; var re = opts.re = opts.re || '.' , isre = (re instanceof RegExp) , o = {}, k, v, parts, i, p; for(k in source) { v = source[k]; if(isre ? !re.test(k) : !~k.indexOf(re)) { o[k] = v; }else{ parts = k.split(re); p = o; for(i = 0;i < parts.length;i++) { k = parts[i]; if(i < parts.length - 1) { p[k] = p[k] || {}; p = p[k]; }else{ p[k] = v; } } } } return o; }
[ "function", "expand", "(", "source", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "var", "re", "=", "opts", ".", "re", "=", "opts", ".", "re", "||", "'.'", ",", "isre", "=", "(", "re", "instanceof", "RegExp", ")", ",", "o", "=", "{", "}", ",", "k", ",", "v", ",", "parts", ",", "i", ",", "p", ";", "for", "(", "k", "in", "source", ")", "{", "v", "=", "source", "[", "k", "]", ";", "if", "(", "isre", "?", "!", "re", ".", "test", "(", "k", ")", ":", "!", "~", "k", ".", "indexOf", "(", "re", ")", ")", "{", "o", "[", "k", "]", "=", "v", ";", "}", "else", "{", "parts", "=", "k", ".", "split", "(", "re", ")", ";", "p", "=", "o", ";", "for", "(", "i", "=", "0", ";", "i", "<", "parts", ".", "length", ";", "i", "++", ")", "{", "k", "=", "parts", "[", "i", "]", ";", "if", "(", "i", "<", "parts", ".", "length", "-", "1", ")", "{", "p", "[", "k", "]", "=", "p", "[", "k", "]", "||", "{", "}", ";", "p", "=", "p", "[", "k", "]", ";", "}", "else", "{", "p", "[", "k", "]", "=", "v", ";", "}", "}", "}", "}", "return", "o", ";", "}" ]
Takes a source object with dot-delimited keys and expands it to a deep object representation. Such that: {'obj.field.num': 10} Becomes: {obj:{field: {num: 10}}} Returns the transformed object. @param source The source object to expand. @param opts Processing opts. @param opts.re The string or regexp delimiter used to split the keys.
[ "Takes", "a", "source", "object", "with", "dot", "-", "delimited", "keys", "and", "expands", "it", "to", "a", "deep", "object", "representation", "." ]
de6f727af1f8fc1f613fe42200c5e070aa6b0b21
https://github.com/cli-kit/cli-property/blob/de6f727af1f8fc1f613fe42200c5e070aa6b0b21/lib/expand.js#L20-L44
56,106
ugate/releasebot
lib/utils.js
validateFile
function validateFile(path, rollCall) { var stat = path ? fs.statSync(path) : { size : 0 }; if (!stat.size) { rollCall.error('Failed to find any entries in "' + path + '" (file size: ' + stat.size + ')'); return false; } return true; }
javascript
function validateFile(path, rollCall) { var stat = path ? fs.statSync(path) : { size : 0 }; if (!stat.size) { rollCall.error('Failed to find any entries in "' + path + '" (file size: ' + stat.size + ')'); return false; } return true; }
[ "function", "validateFile", "(", "path", ",", "rollCall", ")", "{", "var", "stat", "=", "path", "?", "fs", ".", "statSync", "(", "path", ")", ":", "{", "size", ":", "0", "}", ";", "if", "(", "!", "stat", ".", "size", ")", "{", "rollCall", ".", "error", "(", "'Failed to find any entries in \"'", "+", "path", "+", "'\" (file size: '", "+", "stat", ".", "size", "+", "')'", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Determines if a file has content and logs an error when the the file is empty @param path the path to the file @param the roll call instance @returns true when the file contains data or the path is invalid
[ "Determines", "if", "a", "file", "has", "content", "and", "logs", "an", "error", "when", "the", "the", "file", "is", "empty" ]
1a2ff42796e77f47f9590992c014fee461aad80b
https://github.com/ugate/releasebot/blob/1a2ff42796e77f47f9590992c014fee461aad80b/lib/utils.js#L85-L94
56,107
ugate/releasebot
lib/utils.js
updateFiles
function updateFiles(files, func, bpath, eh) { try { if (Array.isArray(files) && typeof func === 'function') { for (var i = 0; i < files.length; i++) { var p = path.join(bpath, files[i]), au = ''; var content = rbot.file.read(p, { encoding : rbot.file.defaultEncoding }); var ec = func(content, p); if (content !== ec) { rbot.file.write(p, ec); return au; } } } } catch (e) { if (typeof eh === 'function') { return eh('Unable to update "' + (Array.isArray(files) ? files.join(',') : '') + '" using: ' + func, e); } throw e; } }
javascript
function updateFiles(files, func, bpath, eh) { try { if (Array.isArray(files) && typeof func === 'function') { for (var i = 0; i < files.length; i++) { var p = path.join(bpath, files[i]), au = ''; var content = rbot.file.read(p, { encoding : rbot.file.defaultEncoding }); var ec = func(content, p); if (content !== ec) { rbot.file.write(p, ec); return au; } } } } catch (e) { if (typeof eh === 'function') { return eh('Unable to update "' + (Array.isArray(files) ? files.join(',') : '') + '" using: ' + func, e); } throw e; } }
[ "function", "updateFiles", "(", "files", ",", "func", ",", "bpath", ",", "eh", ")", "{", "try", "{", "if", "(", "Array", ".", "isArray", "(", "files", ")", "&&", "typeof", "func", "===", "'function'", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "files", ".", "length", ";", "i", "++", ")", "{", "var", "p", "=", "path", ".", "join", "(", "bpath", ",", "files", "[", "i", "]", ")", ",", "au", "=", "''", ";", "var", "content", "=", "rbot", ".", "file", ".", "read", "(", "p", ",", "{", "encoding", ":", "rbot", ".", "file", ".", "defaultEncoding", "}", ")", ";", "var", "ec", "=", "func", "(", "content", ",", "p", ")", ";", "if", "(", "content", "!==", "ec", ")", "{", "rbot", ".", "file", ".", "write", "(", "p", ",", "ec", ")", ";", "return", "au", ";", "}", "}", "}", "}", "catch", "(", "e", ")", "{", "if", "(", "typeof", "eh", "===", "'function'", ")", "{", "return", "eh", "(", "'Unable to update \"'", "+", "(", "Array", ".", "isArray", "(", "files", ")", "?", "files", ".", "join", "(", "','", ")", ":", "''", ")", "+", "'\" using: '", "+", "func", ",", "e", ")", ";", "}", "throw", "e", ";", "}", "}" ]
Updates file contents using a specified function @param files the {Array} of files to read/write @param func the function to call for the read/write operation @param bpath the base path to that will be used to prefix each file used in the update process @param eh an optional function that will be called when the update fails @returns {String} the replaced URL (undefined if nothing was replaced)
[ "Updates", "file", "contents", "using", "a", "specified", "function" ]
1a2ff42796e77f47f9590992c014fee461aad80b
https://github.com/ugate/releasebot/blob/1a2ff42796e77f47f9590992c014fee461aad80b/lib/utils.js#L110-L131
56,108
sdgluck/pick-to-array
index.js
pickToArray
function pickToArray (entities, property, deep) { if (!(entities instanceof Array) && !isPlainObject(entities)) { throw new Error('Expecting entity to be object or array of objects') } else if (typeof property !== 'string' && !(property instanceof Array)) { throw new Error('Expecting property to be string or array') } var arr = entities instanceof Array ? entities : [entities] return arr.reduce(function (result, obj) { if (!(obj instanceof Array) && !isPlainObject(obj)) { return result } forEach(obj, function (value, key) { if ( (property instanceof Array && property.indexOf(key) !== -1) || (key === property) ) { result.push(value) if (!(property instanceof Array)) { return false } } else if (deep && (value instanceof Array || isPlainObject(value))) { result = result.concat(pickToArray(value, property, deep)) } }) return result }, []) }
javascript
function pickToArray (entities, property, deep) { if (!(entities instanceof Array) && !isPlainObject(entities)) { throw new Error('Expecting entity to be object or array of objects') } else if (typeof property !== 'string' && !(property instanceof Array)) { throw new Error('Expecting property to be string or array') } var arr = entities instanceof Array ? entities : [entities] return arr.reduce(function (result, obj) { if (!(obj instanceof Array) && !isPlainObject(obj)) { return result } forEach(obj, function (value, key) { if ( (property instanceof Array && property.indexOf(key) !== -1) || (key === property) ) { result.push(value) if (!(property instanceof Array)) { return false } } else if (deep && (value instanceof Array || isPlainObject(value))) { result = result.concat(pickToArray(value, property, deep)) } }) return result }, []) }
[ "function", "pickToArray", "(", "entities", ",", "property", ",", "deep", ")", "{", "if", "(", "!", "(", "entities", "instanceof", "Array", ")", "&&", "!", "isPlainObject", "(", "entities", ")", ")", "{", "throw", "new", "Error", "(", "'Expecting entity to be object or array of objects'", ")", "}", "else", "if", "(", "typeof", "property", "!==", "'string'", "&&", "!", "(", "property", "instanceof", "Array", ")", ")", "{", "throw", "new", "Error", "(", "'Expecting property to be string or array'", ")", "}", "var", "arr", "=", "entities", "instanceof", "Array", "?", "entities", ":", "[", "entities", "]", "return", "arr", ".", "reduce", "(", "function", "(", "result", ",", "obj", ")", "{", "if", "(", "!", "(", "obj", "instanceof", "Array", ")", "&&", "!", "isPlainObject", "(", "obj", ")", ")", "{", "return", "result", "}", "forEach", "(", "obj", ",", "function", "(", "value", ",", "key", ")", "{", "if", "(", "(", "property", "instanceof", "Array", "&&", "property", ".", "indexOf", "(", "key", ")", "!==", "-", "1", ")", "||", "(", "key", "===", "property", ")", ")", "{", "result", ".", "push", "(", "value", ")", "if", "(", "!", "(", "property", "instanceof", "Array", ")", ")", "{", "return", "false", "}", "}", "else", "if", "(", "deep", "&&", "(", "value", "instanceof", "Array", "||", "isPlainObject", "(", "value", ")", ")", ")", "{", "result", "=", "result", ".", "concat", "(", "pickToArray", "(", "value", ",", "property", ",", "deep", ")", ")", "}", "}", ")", "return", "result", "}", ",", "[", "]", ")", "}" ]
Pick the value of the `property` property from each object in `entities`. Operation is recursive with `deep == true`. @param {Array|Object} entities An array of objects or a single object @param {String|Array} property Property name(s) to pick @param {Boolean} [deep] Pick from nested properties, default false @returns {Array} Values
[ "Pick", "the", "value", "of", "the", "property", "property", "from", "each", "object", "in", "entities", ".", "Operation", "is", "recursive", "with", "deep", "==", "true", "." ]
b496e27770b41ad9aa1260390664b1c282498a34
https://github.com/sdgluck/pick-to-array/blob/b496e27770b41ad9aa1260390664b1c282498a34/index.js#L35-L66
56,109
rxaviers/builder-amd-css
bower_components/require-css/css-builder.js
loadFile
function loadFile(path) { if ( config.asReference && config.asReference.loadFile ) { return config.asReference.loadFile( path ); } else if (typeof process !== "undefined" && process.versions && !!process.versions.node && require.nodeRequire) { var fs = require.nodeRequire('fs'); var file = fs.readFileSync(path, 'utf8'); if (file.indexOf('\uFEFF') === 0) return file.substring(1); return file; } else { var file = new java.io.File(path), lineSeparator = java.lang.System.getProperty("line.separator"), input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), 'utf-8')), stringBuffer, line; try { stringBuffer = new java.lang.StringBuffer(); line = input.readLine(); if (line && line.length() && line.charAt(0) === 0xfeff) line = line.substring(1); stringBuffer.append(line); while ((line = input.readLine()) !== null) { stringBuffer.append(lineSeparator).append(line); } return String(stringBuffer.toString()); } finally { input.close(); } } }
javascript
function loadFile(path) { if ( config.asReference && config.asReference.loadFile ) { return config.asReference.loadFile( path ); } else if (typeof process !== "undefined" && process.versions && !!process.versions.node && require.nodeRequire) { var fs = require.nodeRequire('fs'); var file = fs.readFileSync(path, 'utf8'); if (file.indexOf('\uFEFF') === 0) return file.substring(1); return file; } else { var file = new java.io.File(path), lineSeparator = java.lang.System.getProperty("line.separator"), input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), 'utf-8')), stringBuffer, line; try { stringBuffer = new java.lang.StringBuffer(); line = input.readLine(); if (line && line.length() && line.charAt(0) === 0xfeff) line = line.substring(1); stringBuffer.append(line); while ((line = input.readLine()) !== null) { stringBuffer.append(lineSeparator).append(line); } return String(stringBuffer.toString()); } finally { input.close(); } } }
[ "function", "loadFile", "(", "path", ")", "{", "if", "(", "config", ".", "asReference", "&&", "config", ".", "asReference", ".", "loadFile", ")", "{", "return", "config", ".", "asReference", ".", "loadFile", "(", "path", ")", ";", "}", "else", "if", "(", "typeof", "process", "!==", "\"undefined\"", "&&", "process", ".", "versions", "&&", "!", "!", "process", ".", "versions", ".", "node", "&&", "require", ".", "nodeRequire", ")", "{", "var", "fs", "=", "require", ".", "nodeRequire", "(", "'fs'", ")", ";", "var", "file", "=", "fs", ".", "readFileSync", "(", "path", ",", "'utf8'", ")", ";", "if", "(", "file", ".", "indexOf", "(", "'\\uFEFF'", ")", "===", "0", ")", "return", "file", ".", "substring", "(", "1", ")", ";", "return", "file", ";", "}", "else", "{", "var", "file", "=", "new", "java", ".", "io", ".", "File", "(", "path", ")", ",", "lineSeparator", "=", "java", ".", "lang", ".", "System", ".", "getProperty", "(", "\"line.separator\"", ")", ",", "input", "=", "new", "java", ".", "io", ".", "BufferedReader", "(", "new", "java", ".", "io", ".", "InputStreamReader", "(", "new", "java", ".", "io", ".", "FileInputStream", "(", "file", ")", ",", "'utf-8'", ")", ")", ",", "stringBuffer", ",", "line", ";", "try", "{", "stringBuffer", "=", "new", "java", ".", "lang", ".", "StringBuffer", "(", ")", ";", "line", "=", "input", ".", "readLine", "(", ")", ";", "if", "(", "line", "&&", "line", ".", "length", "(", ")", "&&", "line", ".", "charAt", "(", "0", ")", "===", "0xfeff", ")", "line", "=", "line", ".", "substring", "(", "1", ")", ";", "stringBuffer", ".", "append", "(", "line", ")", ";", "while", "(", "(", "line", "=", "input", ".", "readLine", "(", ")", ")", "!==", "null", ")", "{", "stringBuffer", ".", "append", "(", "lineSeparator", ")", ".", "append", "(", "line", ")", ";", "}", "return", "String", "(", "stringBuffer", ".", "toString", "(", ")", ")", ";", "}", "finally", "{", "input", ".", "close", "(", ")", ";", "}", "}", "}" ]
load file code - stolen from text plugin
[ "load", "file", "code", "-", "stolen", "from", "text", "plugin" ]
ad225d76285a68c5fa750fdc31e2f2c7365aa8b3
https://github.com/rxaviers/builder-amd-css/blob/ad225d76285a68c5fa750fdc31e2f2c7365aa8b3/bower_components/require-css/css-builder.js#L35-L65
56,110
rxaviers/builder-amd-css
bower_components/require-css/css-builder.js
escape
function escape(content) { return content.replace(/(["'\\])/g, '\\$1') .replace(/[\f]/g, "\\f") .replace(/[\b]/g, "\\b") .replace(/[\n]/g, "\\n") .replace(/[\t]/g, "\\t") .replace(/[\r]/g, "\\r"); }
javascript
function escape(content) { return content.replace(/(["'\\])/g, '\\$1') .replace(/[\f]/g, "\\f") .replace(/[\b]/g, "\\b") .replace(/[\n]/g, "\\n") .replace(/[\t]/g, "\\t") .replace(/[\r]/g, "\\r"); }
[ "function", "escape", "(", "content", ")", "{", "return", "content", ".", "replace", "(", "/", "([\"'\\\\])", "/", "g", ",", "'\\\\$1'", ")", ".", "replace", "(", "/", "[\\f]", "/", "g", ",", "\"\\\\f\"", ")", ".", "replace", "(", "/", "[\\b]", "/", "g", ",", "\"\\\\b\"", ")", ".", "replace", "(", "/", "[\\n]", "/", "g", ",", "\"\\\\n\"", ")", ".", "replace", "(", "/", "[\\t]", "/", "g", ",", "\"\\\\t\"", ")", ".", "replace", "(", "/", "[\\r]", "/", "g", ",", "\"\\\\r\"", ")", ";", "}" ]
when adding to the link buffer, paths are normalised to the baseUrl when removing from the link buffer, paths are normalised to the output file path
[ "when", "adding", "to", "the", "link", "buffer", "paths", "are", "normalised", "to", "the", "baseUrl", "when", "removing", "from", "the", "link", "buffer", "paths", "are", "normalised", "to", "the", "output", "file", "path" ]
ad225d76285a68c5fa750fdc31e2f2c7365aa8b3
https://github.com/rxaviers/builder-amd-css/blob/ad225d76285a68c5fa750fdc31e2f2c7365aa8b3/bower_components/require-css/css-builder.js#L91-L98
56,111
agitojs/agito-json-loader
lib/agitoJsonLoader.js
areArgumentsValid
function areArgumentsValid(args) { var isValid = args.every(function(arg) { if (Array.isArray(arg)) { return areArgumentsValid(arg); } return (arg !== null && typeof arg === 'object'); }); return isValid; }
javascript
function areArgumentsValid(args) { var isValid = args.every(function(arg) { if (Array.isArray(arg)) { return areArgumentsValid(arg); } return (arg !== null && typeof arg === 'object'); }); return isValid; }
[ "function", "areArgumentsValid", "(", "args", ")", "{", "var", "isValid", "=", "args", ".", "every", "(", "function", "(", "arg", ")", "{", "if", "(", "Array", ".", "isArray", "(", "arg", ")", ")", "{", "return", "areArgumentsValid", "(", "arg", ")", ";", "}", "return", "(", "arg", "!==", "null", "&&", "typeof", "arg", "===", "'object'", ")", ";", "}", ")", ";", "return", "isValid", ";", "}" ]
Check if the passed arguments are valid. As long as arrays are encountered, they are recursively checked. @param {*[]} args - The arguments to check @return {Boolean} - true when the arguments are correct, otherwise false
[ "Check", "if", "the", "passed", "arguments", "are", "valid", ".", "As", "long", "as", "arrays", "are", "encountered", "they", "are", "recursively", "checked", "." ]
158543455359bcc2bed8cc28c794f9b7b50244aa
https://github.com/agitojs/agito-json-loader/blob/158543455359bcc2bed8cc28c794f9b7b50244aa/lib/agitoJsonLoader.js#L33-L44
56,112
prescottprue/devshare
examples/react/app/containers/Account/Account.js
mapStateToProps
function mapStateToProps (state) { return { account: state.account ? state.entities.accounts[state.account.id] : null, router: state.router } }
javascript
function mapStateToProps (state) { return { account: state.account ? state.entities.accounts[state.account.id] : null, router: state.router } }
[ "function", "mapStateToProps", "(", "state", ")", "{", "return", "{", "account", ":", "state", ".", "account", "?", "state", ".", "entities", ".", "accounts", "[", "state", ".", "account", ".", "id", "]", ":", "null", ",", "router", ":", "state", ".", "router", "}", "}" ]
Place state of redux store into props of component
[ "Place", "state", "of", "redux", "store", "into", "props", "of", "component" ]
38a7081f210857f2ef106836c30ea404c12c1643
https://github.com/prescottprue/devshare/blob/38a7081f210857f2ef106836c30ea404c12c1643/examples/react/app/containers/Account/Account.js#L44-L49
56,113
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/range.js
function() { var clone = new CKEDITOR.dom.range( this.root ); clone.startContainer = this.startContainer; clone.startOffset = this.startOffset; clone.endContainer = this.endContainer; clone.endOffset = this.endOffset; clone.collapsed = this.collapsed; return clone; }
javascript
function() { var clone = new CKEDITOR.dom.range( this.root ); clone.startContainer = this.startContainer; clone.startOffset = this.startOffset; clone.endContainer = this.endContainer; clone.endOffset = this.endOffset; clone.collapsed = this.collapsed; return clone; }
[ "function", "(", ")", "{", "var", "clone", "=", "new", "CKEDITOR", ".", "dom", ".", "range", "(", "this", ".", "root", ")", ";", "clone", ".", "startContainer", "=", "this", ".", "startContainer", ";", "clone", ".", "startOffset", "=", "this", ".", "startOffset", ";", "clone", ".", "endContainer", "=", "this", ".", "endContainer", ";", "clone", ".", "endOffset", "=", "this", ".", "endOffset", ";", "clone", ".", "collapsed", "=", "this", ".", "collapsed", ";", "return", "clone", ";", "}" ]
Clones this range. @returns {CKEDITOR.dom.range}
[ "Clones", "this", "range", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/range.js#L460-L470
56,114
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/range.js
getLengthOfPrecedingTextNodes
function getLengthOfPrecedingTextNodes( node ) { var sum = 0; while ( ( node = node.getPrevious() ) && node.type == CKEDITOR.NODE_TEXT ) sum += node.getLength(); return sum; }
javascript
function getLengthOfPrecedingTextNodes( node ) { var sum = 0; while ( ( node = node.getPrevious() ) && node.type == CKEDITOR.NODE_TEXT ) sum += node.getLength(); return sum; }
[ "function", "getLengthOfPrecedingTextNodes", "(", "node", ")", "{", "var", "sum", "=", "0", ";", "while", "(", "(", "node", "=", "node", ".", "getPrevious", "(", ")", ")", "&&", "node", ".", "type", "==", "CKEDITOR", ".", "NODE_TEXT", ")", "sum", "+=", "node", ".", "getLength", "(", ")", ";", "return", "sum", ";", "}" ]
Sums lengths of all preceding text nodes.
[ "Sums", "lengths", "of", "all", "preceding", "text", "nodes", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/range.js#L647-L654
56,115
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/range.js
function() { var startNode = this.startContainer, endNode = this.endContainer, startOffset = this.startOffset, endOffset = this.endOffset, childCount; if ( startNode.type == CKEDITOR.NODE_ELEMENT ) { childCount = startNode.getChildCount(); if ( childCount > startOffset ) startNode = startNode.getChild( startOffset ); else if ( childCount < 1 ) startNode = startNode.getPreviousSourceNode(); else // startOffset > childCount but childCount is not 0 { // Try to take the node just after the current position. startNode = startNode.$; while ( startNode.lastChild ) startNode = startNode.lastChild; startNode = new CKEDITOR.dom.node( startNode ); // Normally we should take the next node in DFS order. But it // is also possible that we've already reached the end of // document. startNode = startNode.getNextSourceNode() || startNode; } } if ( endNode.type == CKEDITOR.NODE_ELEMENT ) { childCount = endNode.getChildCount(); if ( childCount > endOffset ) endNode = endNode.getChild( endOffset ).getPreviousSourceNode( true ); else if ( childCount < 1 ) endNode = endNode.getPreviousSourceNode(); else // endOffset > childCount but childCount is not 0 { // Try to take the node just before the current position. endNode = endNode.$; while ( endNode.lastChild ) endNode = endNode.lastChild; endNode = new CKEDITOR.dom.node( endNode ); } } // Sometimes the endNode will come right before startNode for collapsed // ranges. Fix it. (#3780) if ( startNode.getPosition( endNode ) & CKEDITOR.POSITION_FOLLOWING ) startNode = endNode; return { startNode: startNode, endNode: endNode }; }
javascript
function() { var startNode = this.startContainer, endNode = this.endContainer, startOffset = this.startOffset, endOffset = this.endOffset, childCount; if ( startNode.type == CKEDITOR.NODE_ELEMENT ) { childCount = startNode.getChildCount(); if ( childCount > startOffset ) startNode = startNode.getChild( startOffset ); else if ( childCount < 1 ) startNode = startNode.getPreviousSourceNode(); else // startOffset > childCount but childCount is not 0 { // Try to take the node just after the current position. startNode = startNode.$; while ( startNode.lastChild ) startNode = startNode.lastChild; startNode = new CKEDITOR.dom.node( startNode ); // Normally we should take the next node in DFS order. But it // is also possible that we've already reached the end of // document. startNode = startNode.getNextSourceNode() || startNode; } } if ( endNode.type == CKEDITOR.NODE_ELEMENT ) { childCount = endNode.getChildCount(); if ( childCount > endOffset ) endNode = endNode.getChild( endOffset ).getPreviousSourceNode( true ); else if ( childCount < 1 ) endNode = endNode.getPreviousSourceNode(); else // endOffset > childCount but childCount is not 0 { // Try to take the node just before the current position. endNode = endNode.$; while ( endNode.lastChild ) endNode = endNode.lastChild; endNode = new CKEDITOR.dom.node( endNode ); } } // Sometimes the endNode will come right before startNode for collapsed // ranges. Fix it. (#3780) if ( startNode.getPosition( endNode ) & CKEDITOR.POSITION_FOLLOWING ) startNode = endNode; return { startNode: startNode, endNode: endNode }; }
[ "function", "(", ")", "{", "var", "startNode", "=", "this", ".", "startContainer", ",", "endNode", "=", "this", ".", "endContainer", ",", "startOffset", "=", "this", ".", "startOffset", ",", "endOffset", "=", "this", ".", "endOffset", ",", "childCount", ";", "if", "(", "startNode", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", ")", "{", "childCount", "=", "startNode", ".", "getChildCount", "(", ")", ";", "if", "(", "childCount", ">", "startOffset", ")", "startNode", "=", "startNode", ".", "getChild", "(", "startOffset", ")", ";", "else", "if", "(", "childCount", "<", "1", ")", "startNode", "=", "startNode", ".", "getPreviousSourceNode", "(", ")", ";", "else", "// startOffset > childCount but childCount is not 0", "{", "// Try to take the node just after the current position.", "startNode", "=", "startNode", ".", "$", ";", "while", "(", "startNode", ".", "lastChild", ")", "startNode", "=", "startNode", ".", "lastChild", ";", "startNode", "=", "new", "CKEDITOR", ".", "dom", ".", "node", "(", "startNode", ")", ";", "// Normally we should take the next node in DFS order. But it", "// is also possible that we've already reached the end of", "// document.", "startNode", "=", "startNode", ".", "getNextSourceNode", "(", ")", "||", "startNode", ";", "}", "}", "if", "(", "endNode", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", ")", "{", "childCount", "=", "endNode", ".", "getChildCount", "(", ")", ";", "if", "(", "childCount", ">", "endOffset", ")", "endNode", "=", "endNode", ".", "getChild", "(", "endOffset", ")", ".", "getPreviousSourceNode", "(", "true", ")", ";", "else", "if", "(", "childCount", "<", "1", ")", "endNode", "=", "endNode", ".", "getPreviousSourceNode", "(", ")", ";", "else", "// endOffset > childCount but childCount is not 0", "{", "// Try to take the node just before the current position.", "endNode", "=", "endNode", ".", "$", ";", "while", "(", "endNode", ".", "lastChild", ")", "endNode", "=", "endNode", ".", "lastChild", ";", "endNode", "=", "new", "CKEDITOR", ".", "dom", ".", "node", "(", "endNode", ")", ";", "}", "}", "// Sometimes the endNode will come right before startNode for collapsed", "// ranges. Fix it. (#3780)", "if", "(", "startNode", ".", "getPosition", "(", "endNode", ")", "&", "CKEDITOR", ".", "POSITION_FOLLOWING", ")", "startNode", "=", "endNode", ";", "return", "{", "startNode", ":", "startNode", ",", "endNode", ":", "endNode", "}", ";", "}" ]
Returns two nodes which are on the boundaries of this range. @returns {Object} @returns {CKEDITOR.dom.node} return.startNode @returns {CKEDITOR.dom.node} return.endNode @todo precise desc/algorithm
[ "Returns", "two", "nodes", "which", "are", "on", "the", "boundaries", "of", "this", "range", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/range.js#L769-L818
56,116
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/range.js
function( includeSelf, ignoreTextNode ) { var start = this.startContainer, end = this.endContainer, ancestor; if ( start.equals( end ) ) { if ( includeSelf && start.type == CKEDITOR.NODE_ELEMENT && this.startOffset == this.endOffset - 1 ) ancestor = start.getChild( this.startOffset ); else ancestor = start; } else { ancestor = start.getCommonAncestor( end ); } return ignoreTextNode && !ancestor.is ? ancestor.getParent() : ancestor; }
javascript
function( includeSelf, ignoreTextNode ) { var start = this.startContainer, end = this.endContainer, ancestor; if ( start.equals( end ) ) { if ( includeSelf && start.type == CKEDITOR.NODE_ELEMENT && this.startOffset == this.endOffset - 1 ) ancestor = start.getChild( this.startOffset ); else ancestor = start; } else { ancestor = start.getCommonAncestor( end ); } return ignoreTextNode && !ancestor.is ? ancestor.getParent() : ancestor; }
[ "function", "(", "includeSelf", ",", "ignoreTextNode", ")", "{", "var", "start", "=", "this", ".", "startContainer", ",", "end", "=", "this", ".", "endContainer", ",", "ancestor", ";", "if", "(", "start", ".", "equals", "(", "end", ")", ")", "{", "if", "(", "includeSelf", "&&", "start", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", "&&", "this", ".", "startOffset", "==", "this", ".", "endOffset", "-", "1", ")", "ancestor", "=", "start", ".", "getChild", "(", "this", ".", "startOffset", ")", ";", "else", "ancestor", "=", "start", ";", "}", "else", "{", "ancestor", "=", "start", ".", "getCommonAncestor", "(", "end", ")", ";", "}", "return", "ignoreTextNode", "&&", "!", "ancestor", ".", "is", "?", "ancestor", ".", "getParent", "(", ")", ":", "ancestor", ";", "}" ]
Find the node which fully contains the range. @param {Boolean} [includeSelf=false] @param {Boolean} [ignoreTextNode=false] Whether ignore {@link CKEDITOR#NODE_TEXT} type. @returns {CKEDITOR.dom.element}
[ "Find", "the", "node", "which", "fully", "contains", "the", "range", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/range.js#L827-L842
56,117
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/range.js
getValidEnlargeable
function getValidEnlargeable( enlargeable ) { return enlargeable && enlargeable.type == CKEDITOR.NODE_ELEMENT && enlargeable.hasAttribute( 'contenteditable' ) ? null : enlargeable; }
javascript
function getValidEnlargeable( enlargeable ) { return enlargeable && enlargeable.type == CKEDITOR.NODE_ELEMENT && enlargeable.hasAttribute( 'contenteditable' ) ? null : enlargeable; }
[ "function", "getValidEnlargeable", "(", "enlargeable", ")", "{", "return", "enlargeable", "&&", "enlargeable", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", "&&", "enlargeable", ".", "hasAttribute", "(", "'contenteditable'", ")", "?", "null", ":", "enlargeable", ";", "}" ]
Ensures that returned element can be enlarged by selection, null otherwise. @param {CKEDITOR.dom.element} enlargeable @returns {CKEDITOR.dom.element/null}
[ "Ensures", "that", "returned", "element", "can", "be", "enlarged", "by", "selection", "null", "otherwise", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/range.js#L1468-L1471
56,118
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/range.js
function( mode, selectContents, shrinkOnBlockBoundary ) { // Unable to shrink a collapsed range. if ( !this.collapsed ) { mode = mode || CKEDITOR.SHRINK_TEXT; var walkerRange = this.clone(); var startContainer = this.startContainer, endContainer = this.endContainer, startOffset = this.startOffset, endOffset = this.endOffset; // Whether the start/end boundary is moveable. var moveStart = 1, moveEnd = 1; if ( startContainer && startContainer.type == CKEDITOR.NODE_TEXT ) { if ( !startOffset ) walkerRange.setStartBefore( startContainer ); else if ( startOffset >= startContainer.getLength() ) walkerRange.setStartAfter( startContainer ); else { // Enlarge the range properly to avoid walker making // DOM changes caused by triming the text nodes later. walkerRange.setStartBefore( startContainer ); moveStart = 0; } } if ( endContainer && endContainer.type == CKEDITOR.NODE_TEXT ) { if ( !endOffset ) walkerRange.setEndBefore( endContainer ); else if ( endOffset >= endContainer.getLength() ) walkerRange.setEndAfter( endContainer ); else { walkerRange.setEndAfter( endContainer ); moveEnd = 0; } } var walker = new CKEDITOR.dom.walker( walkerRange ), isBookmark = CKEDITOR.dom.walker.bookmark(); walker.evaluator = function( node ) { return node.type == ( mode == CKEDITOR.SHRINK_ELEMENT ? CKEDITOR.NODE_ELEMENT : CKEDITOR.NODE_TEXT ); }; var currentElement; walker.guard = function( node, movingOut ) { if ( isBookmark( node ) ) return true; // Stop when we're shrink in element mode while encountering a text node. if ( mode == CKEDITOR.SHRINK_ELEMENT && node.type == CKEDITOR.NODE_TEXT ) return false; // Stop when we've already walked "through" an element. if ( movingOut && node.equals( currentElement ) ) return false; if ( shrinkOnBlockBoundary === false && node.type == CKEDITOR.NODE_ELEMENT && node.isBlockBoundary() ) return false; // Stop shrinking when encountering an editable border. if ( node.type == CKEDITOR.NODE_ELEMENT && node.hasAttribute( 'contenteditable' ) ) return false; if ( !movingOut && node.type == CKEDITOR.NODE_ELEMENT ) currentElement = node; return true; }; if ( moveStart ) { var textStart = walker[ mode == CKEDITOR.SHRINK_ELEMENT ? 'lastForward' : 'next' ](); textStart && this.setStartAt( textStart, selectContents ? CKEDITOR.POSITION_AFTER_START : CKEDITOR.POSITION_BEFORE_START ); } if ( moveEnd ) { walker.reset(); var textEnd = walker[ mode == CKEDITOR.SHRINK_ELEMENT ? 'lastBackward' : 'previous' ](); textEnd && this.setEndAt( textEnd, selectContents ? CKEDITOR.POSITION_BEFORE_END : CKEDITOR.POSITION_AFTER_END ); } return !!( moveStart || moveEnd ); } }
javascript
function( mode, selectContents, shrinkOnBlockBoundary ) { // Unable to shrink a collapsed range. if ( !this.collapsed ) { mode = mode || CKEDITOR.SHRINK_TEXT; var walkerRange = this.clone(); var startContainer = this.startContainer, endContainer = this.endContainer, startOffset = this.startOffset, endOffset = this.endOffset; // Whether the start/end boundary is moveable. var moveStart = 1, moveEnd = 1; if ( startContainer && startContainer.type == CKEDITOR.NODE_TEXT ) { if ( !startOffset ) walkerRange.setStartBefore( startContainer ); else if ( startOffset >= startContainer.getLength() ) walkerRange.setStartAfter( startContainer ); else { // Enlarge the range properly to avoid walker making // DOM changes caused by triming the text nodes later. walkerRange.setStartBefore( startContainer ); moveStart = 0; } } if ( endContainer && endContainer.type == CKEDITOR.NODE_TEXT ) { if ( !endOffset ) walkerRange.setEndBefore( endContainer ); else if ( endOffset >= endContainer.getLength() ) walkerRange.setEndAfter( endContainer ); else { walkerRange.setEndAfter( endContainer ); moveEnd = 0; } } var walker = new CKEDITOR.dom.walker( walkerRange ), isBookmark = CKEDITOR.dom.walker.bookmark(); walker.evaluator = function( node ) { return node.type == ( mode == CKEDITOR.SHRINK_ELEMENT ? CKEDITOR.NODE_ELEMENT : CKEDITOR.NODE_TEXT ); }; var currentElement; walker.guard = function( node, movingOut ) { if ( isBookmark( node ) ) return true; // Stop when we're shrink in element mode while encountering a text node. if ( mode == CKEDITOR.SHRINK_ELEMENT && node.type == CKEDITOR.NODE_TEXT ) return false; // Stop when we've already walked "through" an element. if ( movingOut && node.equals( currentElement ) ) return false; if ( shrinkOnBlockBoundary === false && node.type == CKEDITOR.NODE_ELEMENT && node.isBlockBoundary() ) return false; // Stop shrinking when encountering an editable border. if ( node.type == CKEDITOR.NODE_ELEMENT && node.hasAttribute( 'contenteditable' ) ) return false; if ( !movingOut && node.type == CKEDITOR.NODE_ELEMENT ) currentElement = node; return true; }; if ( moveStart ) { var textStart = walker[ mode == CKEDITOR.SHRINK_ELEMENT ? 'lastForward' : 'next' ](); textStart && this.setStartAt( textStart, selectContents ? CKEDITOR.POSITION_AFTER_START : CKEDITOR.POSITION_BEFORE_START ); } if ( moveEnd ) { walker.reset(); var textEnd = walker[ mode == CKEDITOR.SHRINK_ELEMENT ? 'lastBackward' : 'previous' ](); textEnd && this.setEndAt( textEnd, selectContents ? CKEDITOR.POSITION_BEFORE_END : CKEDITOR.POSITION_AFTER_END ); } return !!( moveStart || moveEnd ); } }
[ "function", "(", "mode", ",", "selectContents", ",", "shrinkOnBlockBoundary", ")", "{", "// Unable to shrink a collapsed range.", "if", "(", "!", "this", ".", "collapsed", ")", "{", "mode", "=", "mode", "||", "CKEDITOR", ".", "SHRINK_TEXT", ";", "var", "walkerRange", "=", "this", ".", "clone", "(", ")", ";", "var", "startContainer", "=", "this", ".", "startContainer", ",", "endContainer", "=", "this", ".", "endContainer", ",", "startOffset", "=", "this", ".", "startOffset", ",", "endOffset", "=", "this", ".", "endOffset", ";", "// Whether the start/end boundary is moveable.", "var", "moveStart", "=", "1", ",", "moveEnd", "=", "1", ";", "if", "(", "startContainer", "&&", "startContainer", ".", "type", "==", "CKEDITOR", ".", "NODE_TEXT", ")", "{", "if", "(", "!", "startOffset", ")", "walkerRange", ".", "setStartBefore", "(", "startContainer", ")", ";", "else", "if", "(", "startOffset", ">=", "startContainer", ".", "getLength", "(", ")", ")", "walkerRange", ".", "setStartAfter", "(", "startContainer", ")", ";", "else", "{", "// Enlarge the range properly to avoid walker making", "// DOM changes caused by triming the text nodes later.", "walkerRange", ".", "setStartBefore", "(", "startContainer", ")", ";", "moveStart", "=", "0", ";", "}", "}", "if", "(", "endContainer", "&&", "endContainer", ".", "type", "==", "CKEDITOR", ".", "NODE_TEXT", ")", "{", "if", "(", "!", "endOffset", ")", "walkerRange", ".", "setEndBefore", "(", "endContainer", ")", ";", "else", "if", "(", "endOffset", ">=", "endContainer", ".", "getLength", "(", ")", ")", "walkerRange", ".", "setEndAfter", "(", "endContainer", ")", ";", "else", "{", "walkerRange", ".", "setEndAfter", "(", "endContainer", ")", ";", "moveEnd", "=", "0", ";", "}", "}", "var", "walker", "=", "new", "CKEDITOR", ".", "dom", ".", "walker", "(", "walkerRange", ")", ",", "isBookmark", "=", "CKEDITOR", ".", "dom", ".", "walker", ".", "bookmark", "(", ")", ";", "walker", ".", "evaluator", "=", "function", "(", "node", ")", "{", "return", "node", ".", "type", "==", "(", "mode", "==", "CKEDITOR", ".", "SHRINK_ELEMENT", "?", "CKEDITOR", ".", "NODE_ELEMENT", ":", "CKEDITOR", ".", "NODE_TEXT", ")", ";", "}", ";", "var", "currentElement", ";", "walker", ".", "guard", "=", "function", "(", "node", ",", "movingOut", ")", "{", "if", "(", "isBookmark", "(", "node", ")", ")", "return", "true", ";", "// Stop when we're shrink in element mode while encountering a text node.", "if", "(", "mode", "==", "CKEDITOR", ".", "SHRINK_ELEMENT", "&&", "node", ".", "type", "==", "CKEDITOR", ".", "NODE_TEXT", ")", "return", "false", ";", "// Stop when we've already walked \"through\" an element.", "if", "(", "movingOut", "&&", "node", ".", "equals", "(", "currentElement", ")", ")", "return", "false", ";", "if", "(", "shrinkOnBlockBoundary", "===", "false", "&&", "node", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", "&&", "node", ".", "isBlockBoundary", "(", ")", ")", "return", "false", ";", "// Stop shrinking when encountering an editable border.", "if", "(", "node", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", "&&", "node", ".", "hasAttribute", "(", "'contenteditable'", ")", ")", "return", "false", ";", "if", "(", "!", "movingOut", "&&", "node", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", ")", "currentElement", "=", "node", ";", "return", "true", ";", "}", ";", "if", "(", "moveStart", ")", "{", "var", "textStart", "=", "walker", "[", "mode", "==", "CKEDITOR", ".", "SHRINK_ELEMENT", "?", "'lastForward'", ":", "'next'", "]", "(", ")", ";", "textStart", "&&", "this", ".", "setStartAt", "(", "textStart", ",", "selectContents", "?", "CKEDITOR", ".", "POSITION_AFTER_START", ":", "CKEDITOR", ".", "POSITION_BEFORE_START", ")", ";", "}", "if", "(", "moveEnd", ")", "{", "walker", ".", "reset", "(", ")", ";", "var", "textEnd", "=", "walker", "[", "mode", "==", "CKEDITOR", ".", "SHRINK_ELEMENT", "?", "'lastBackward'", ":", "'previous'", "]", "(", ")", ";", "textEnd", "&&", "this", ".", "setEndAt", "(", "textEnd", ",", "selectContents", "?", "CKEDITOR", ".", "POSITION_BEFORE_END", ":", "CKEDITOR", ".", "POSITION_AFTER_END", ")", ";", "}", "return", "!", "!", "(", "moveStart", "||", "moveEnd", ")", ";", "}", "}" ]
Descrease the range to make sure that boundaries always anchor beside text nodes or innermost element. @param {Number} mode The shrinking mode ({@link CKEDITOR#SHRINK_ELEMENT} or {@link CKEDITOR#SHRINK_TEXT}). * {@link CKEDITOR#SHRINK_ELEMENT} - Shrink the range boundaries to the edge of the innermost element. * {@link CKEDITOR#SHRINK_TEXT} - Shrink the range boudaries to anchor by the side of enclosed text node, range remains if there's no text nodes on boundaries at all. @param {Boolean} selectContents Whether result range anchors at the inner OR outer boundary of the node.
[ "Descrease", "the", "range", "to", "make", "sure", "that", "boundaries", "always", "anchor", "beside", "text", "nodes", "or", "innermost", "element", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/range.js#L1486-L1572
56,119
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/range.js
function( node ) { this.optimizeBookmark(); this.trim( false, true ); var startContainer = this.startContainer; var startOffset = this.startOffset; var nextNode = startContainer.getChild( startOffset ); if ( nextNode ) node.insertBefore( nextNode ); else startContainer.append( node ); // Check if we need to update the end boundary. if ( node.getParent() && node.getParent().equals( this.endContainer ) ) this.endOffset++; // Expand the range to embrace the new node. this.setStartBefore( node ); }
javascript
function( node ) { this.optimizeBookmark(); this.trim( false, true ); var startContainer = this.startContainer; var startOffset = this.startOffset; var nextNode = startContainer.getChild( startOffset ); if ( nextNode ) node.insertBefore( nextNode ); else startContainer.append( node ); // Check if we need to update the end boundary. if ( node.getParent() && node.getParent().equals( this.endContainer ) ) this.endOffset++; // Expand the range to embrace the new node. this.setStartBefore( node ); }
[ "function", "(", "node", ")", "{", "this", ".", "optimizeBookmark", "(", ")", ";", "this", ".", "trim", "(", "false", ",", "true", ")", ";", "var", "startContainer", "=", "this", ".", "startContainer", ";", "var", "startOffset", "=", "this", ".", "startOffset", ";", "var", "nextNode", "=", "startContainer", ".", "getChild", "(", "startOffset", ")", ";", "if", "(", "nextNode", ")", "node", ".", "insertBefore", "(", "nextNode", ")", ";", "else", "startContainer", ".", "append", "(", "node", ")", ";", "// Check if we need to update the end boundary.", "if", "(", "node", ".", "getParent", "(", ")", "&&", "node", ".", "getParent", "(", ")", ".", "equals", "(", "this", ".", "endContainer", ")", ")", "this", ".", "endOffset", "++", ";", "// Expand the range to embrace the new node.", "this", ".", "setStartBefore", "(", "node", ")", ";", "}" ]
Inserts a node at the start of the range. The range will be expanded the contain the node. @param {CKEDITOR.dom.node} node
[ "Inserts", "a", "node", "at", "the", "start", "of", "the", "range", ".", "The", "range", "will", "be", "expanded", "the", "contain", "the", "node", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/range.js#L1580-L1600
56,120
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/range.js
function( range ) { this.setStart( range.startContainer, range.startOffset ); this.setEnd( range.endContainer, range.endOffset ); }
javascript
function( range ) { this.setStart( range.startContainer, range.startOffset ); this.setEnd( range.endContainer, range.endOffset ); }
[ "function", "(", "range", ")", "{", "this", ".", "setStart", "(", "range", ".", "startContainer", ",", "range", ".", "startOffset", ")", ";", "this", ".", "setEnd", "(", "range", ".", "endContainer", ",", "range", ".", "endOffset", ")", ";", "}" ]
Moves the range to the exact position of the specified range. @param {CKEDITOR.dom.range} range
[ "Moves", "the", "range", "to", "the", "exact", "position", "of", "the", "specified", "range", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/range.js#L1626-L1629
56,121
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/range.js
function( startNode, startOffset ) { // W3C requires a check for the new position. If it is after the end // boundary, the range should be collapsed to the new start. It seams // we will not need this check for our use of this class so we can // ignore it for now. // Fixing invalid range start inside dtd empty elements. if ( startNode.type == CKEDITOR.NODE_ELEMENT && CKEDITOR.dtd.$empty[ startNode.getName() ] ) startOffset = startNode.getIndex(), startNode = startNode.getParent(); this.startContainer = startNode; this.startOffset = startOffset; if ( !this.endContainer ) { this.endContainer = startNode; this.endOffset = startOffset; } updateCollapsed( this ); }
javascript
function( startNode, startOffset ) { // W3C requires a check for the new position. If it is after the end // boundary, the range should be collapsed to the new start. It seams // we will not need this check for our use of this class so we can // ignore it for now. // Fixing invalid range start inside dtd empty elements. if ( startNode.type == CKEDITOR.NODE_ELEMENT && CKEDITOR.dtd.$empty[ startNode.getName() ] ) startOffset = startNode.getIndex(), startNode = startNode.getParent(); this.startContainer = startNode; this.startOffset = startOffset; if ( !this.endContainer ) { this.endContainer = startNode; this.endOffset = startOffset; } updateCollapsed( this ); }
[ "function", "(", "startNode", ",", "startOffset", ")", "{", "// W3C requires a check for the new position. If it is after the end", "// boundary, the range should be collapsed to the new start. It seams", "// we will not need this check for our use of this class so we can", "// ignore it for now.", "// Fixing invalid range start inside dtd empty elements.", "if", "(", "startNode", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", "&&", "CKEDITOR", ".", "dtd", ".", "$empty", "[", "startNode", ".", "getName", "(", ")", "]", ")", "startOffset", "=", "startNode", ".", "getIndex", "(", ")", ",", "startNode", "=", "startNode", ".", "getParent", "(", ")", ";", "this", ".", "startContainer", "=", "startNode", ";", "this", ".", "startOffset", "=", "startOffset", ";", "if", "(", "!", "this", ".", "endContainer", ")", "{", "this", ".", "endContainer", "=", "startNode", ";", "this", ".", "endOffset", "=", "startOffset", ";", "}", "updateCollapsed", "(", "this", ")", ";", "}" ]
Sets the start position of a range. @param {CKEDITOR.dom.node} startNode The node to start the range. @param {Number} startOffset An integer greater than or equal to zero representing the offset for the start of the range from the start of `startNode`.
[ "Sets", "the", "start", "position", "of", "a", "range", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/range.js#L1649-L1668
56,122
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/range.js
function( endNode, endOffset ) { // W3C requires a check for the new position. If it is before the start // boundary, the range should be collapsed to the new end. It seams we // will not need this check for our use of this class so we can ignore // it for now. // Fixing invalid range end inside dtd empty elements. if ( endNode.type == CKEDITOR.NODE_ELEMENT && CKEDITOR.dtd.$empty[ endNode.getName() ] ) endOffset = endNode.getIndex() + 1, endNode = endNode.getParent(); this.endContainer = endNode; this.endOffset = endOffset; if ( !this.startContainer ) { this.startContainer = endNode; this.startOffset = endOffset; } updateCollapsed( this ); }
javascript
function( endNode, endOffset ) { // W3C requires a check for the new position. If it is before the start // boundary, the range should be collapsed to the new end. It seams we // will not need this check for our use of this class so we can ignore // it for now. // Fixing invalid range end inside dtd empty elements. if ( endNode.type == CKEDITOR.NODE_ELEMENT && CKEDITOR.dtd.$empty[ endNode.getName() ] ) endOffset = endNode.getIndex() + 1, endNode = endNode.getParent(); this.endContainer = endNode; this.endOffset = endOffset; if ( !this.startContainer ) { this.startContainer = endNode; this.startOffset = endOffset; } updateCollapsed( this ); }
[ "function", "(", "endNode", ",", "endOffset", ")", "{", "// W3C requires a check for the new position. If it is before the start", "// boundary, the range should be collapsed to the new end. It seams we", "// will not need this check for our use of this class so we can ignore", "// it for now.", "// Fixing invalid range end inside dtd empty elements.", "if", "(", "endNode", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", "&&", "CKEDITOR", ".", "dtd", ".", "$empty", "[", "endNode", ".", "getName", "(", ")", "]", ")", "endOffset", "=", "endNode", ".", "getIndex", "(", ")", "+", "1", ",", "endNode", "=", "endNode", ".", "getParent", "(", ")", ";", "this", ".", "endContainer", "=", "endNode", ";", "this", ".", "endOffset", "=", "endOffset", ";", "if", "(", "!", "this", ".", "startContainer", ")", "{", "this", ".", "startContainer", "=", "endNode", ";", "this", ".", "startOffset", "=", "endOffset", ";", "}", "updateCollapsed", "(", "this", ")", ";", "}" ]
Sets the end position of a Range. @param {CKEDITOR.dom.node} endNode The node to end the range. @param {Number} endOffset An integer greater than or equal to zero representing the offset for the end of the range from the start of `endNode`.
[ "Sets", "the", "end", "position", "of", "a", "Range", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/range.js#L1678-L1697
56,123
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/range.js
function( toSplit ) { if ( !this.collapsed ) return null; // Extract the contents of the block from the selection point to the end // of its contents. this.setEndAt( toSplit, CKEDITOR.POSITION_BEFORE_END ); var documentFragment = this.extractContents(); // Duplicate the element after it. var clone = toSplit.clone( false ); // Place the extracted contents into the duplicated element. documentFragment.appendTo( clone ); clone.insertAfter( toSplit ); this.moveToPosition( toSplit, CKEDITOR.POSITION_AFTER_END ); return clone; }
javascript
function( toSplit ) { if ( !this.collapsed ) return null; // Extract the contents of the block from the selection point to the end // of its contents. this.setEndAt( toSplit, CKEDITOR.POSITION_BEFORE_END ); var documentFragment = this.extractContents(); // Duplicate the element after it. var clone = toSplit.clone( false ); // Place the extracted contents into the duplicated element. documentFragment.appendTo( clone ); clone.insertAfter( toSplit ); this.moveToPosition( toSplit, CKEDITOR.POSITION_AFTER_END ); return clone; }
[ "function", "(", "toSplit", ")", "{", "if", "(", "!", "this", ".", "collapsed", ")", "return", "null", ";", "// Extract the contents of the block from the selection point to the end", "// of its contents.", "this", ".", "setEndAt", "(", "toSplit", ",", "CKEDITOR", ".", "POSITION_BEFORE_END", ")", ";", "var", "documentFragment", "=", "this", ".", "extractContents", "(", ")", ";", "// Duplicate the element after it.", "var", "clone", "=", "toSplit", ".", "clone", "(", "false", ")", ";", "// Place the extracted contents into the duplicated element.", "documentFragment", ".", "appendTo", "(", "clone", ")", ";", "clone", ".", "insertAfter", "(", "toSplit", ")", ";", "this", ".", "moveToPosition", "(", "toSplit", ",", "CKEDITOR", ".", "POSITION_AFTER_END", ")", ";", "return", "clone", ";", "}" ]
Branch the specified element from the collapsed range position and place the caret between the two result branches. **Note:** The range must be collapsed and been enclosed by this element. @param {CKEDITOR.dom.element} element @returns {CKEDITOR.dom.element} Root element of the new branch after the split.
[ "Branch", "the", "specified", "element", "from", "the", "collapsed", "range", "position", "and", "place", "the", "caret", "between", "the", "two", "result", "branches", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/range.js#L1953-L1970
56,124
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/range.js
function() { var walkerRange = this.clone(); // Optimize and analyze the range to avoid DOM destructive nature of walker. (#5780) walkerRange.optimize(); if ( walkerRange.startContainer.type != CKEDITOR.NODE_ELEMENT || walkerRange.endContainer.type != CKEDITOR.NODE_ELEMENT ) return null; var walker = new CKEDITOR.dom.walker( walkerRange ), isNotBookmarks = CKEDITOR.dom.walker.bookmark( false, true ), isNotWhitespaces = CKEDITOR.dom.walker.whitespaces( true ); walker.evaluator = function( node ) { return isNotWhitespaces( node ) && isNotBookmarks( node ); }; var node = walker.next(); walker.reset(); return node && node.equals( walker.previous() ) ? node : null; }
javascript
function() { var walkerRange = this.clone(); // Optimize and analyze the range to avoid DOM destructive nature of walker. (#5780) walkerRange.optimize(); if ( walkerRange.startContainer.type != CKEDITOR.NODE_ELEMENT || walkerRange.endContainer.type != CKEDITOR.NODE_ELEMENT ) return null; var walker = new CKEDITOR.dom.walker( walkerRange ), isNotBookmarks = CKEDITOR.dom.walker.bookmark( false, true ), isNotWhitespaces = CKEDITOR.dom.walker.whitespaces( true ); walker.evaluator = function( node ) { return isNotWhitespaces( node ) && isNotBookmarks( node ); }; var node = walker.next(); walker.reset(); return node && node.equals( walker.previous() ) ? node : null; }
[ "function", "(", ")", "{", "var", "walkerRange", "=", "this", ".", "clone", "(", ")", ";", "// Optimize and analyze the range to avoid DOM destructive nature of walker. (#5780)", "walkerRange", ".", "optimize", "(", ")", ";", "if", "(", "walkerRange", ".", "startContainer", ".", "type", "!=", "CKEDITOR", ".", "NODE_ELEMENT", "||", "walkerRange", ".", "endContainer", ".", "type", "!=", "CKEDITOR", ".", "NODE_ELEMENT", ")", "return", "null", ";", "var", "walker", "=", "new", "CKEDITOR", ".", "dom", ".", "walker", "(", "walkerRange", ")", ",", "isNotBookmarks", "=", "CKEDITOR", ".", "dom", ".", "walker", ".", "bookmark", "(", "false", ",", "true", ")", ",", "isNotWhitespaces", "=", "CKEDITOR", ".", "dom", ".", "walker", ".", "whitespaces", "(", "true", ")", ";", "walker", ".", "evaluator", "=", "function", "(", "node", ")", "{", "return", "isNotWhitespaces", "(", "node", ")", "&&", "isNotBookmarks", "(", "node", ")", ";", "}", ";", "var", "node", "=", "walker", ".", "next", "(", ")", ";", "walker", ".", "reset", "(", ")", ";", "return", "node", "&&", "node", ".", "equals", "(", "walker", ".", "previous", "(", ")", ")", "?", "node", ":", "null", ";", "}" ]
Get the single node enclosed within the range if there's one. @returns {CKEDITOR.dom.node}
[ "Get", "the", "single", "node", "enclosed", "within", "the", "range", "if", "there", "s", "one", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/range.js#L2368-L2386
56,125
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/range.js
function() { // The reference element contains a zero-width space to avoid // a premature removal. The view is to be scrolled with respect // to this element. var reference = new CKEDITOR.dom.element.createFromHtml( '<span>&nbsp;</span>', this.document ), afterCaretNode, startContainerText, isStartText; var range = this.clone(); // Work with the range to obtain a proper caret position. range.optimize(); // Currently in a text node, so we need to split it into two // halves and put the reference between. if ( isStartText = range.startContainer.type == CKEDITOR.NODE_TEXT ) { // Keep the original content. It will be restored. startContainerText = range.startContainer.getText(); // Split the startContainer at the this position. afterCaretNode = range.startContainer.split( range.startOffset ); // Insert the reference between two text nodes. reference.insertAfter( range.startContainer ); } // If not in a text node, simply insert the reference into the range. else { range.insertNode( reference ); } // Scroll with respect to the reference element. reference.scrollIntoView(); // Get rid of split parts if "in a text node" case. // Revert the original text of the startContainer. if ( isStartText ) { range.startContainer.setText( startContainerText ); afterCaretNode.remove(); } // Get rid of the reference node. It is no longer necessary. reference.remove(); }
javascript
function() { // The reference element contains a zero-width space to avoid // a premature removal. The view is to be scrolled with respect // to this element. var reference = new CKEDITOR.dom.element.createFromHtml( '<span>&nbsp;</span>', this.document ), afterCaretNode, startContainerText, isStartText; var range = this.clone(); // Work with the range to obtain a proper caret position. range.optimize(); // Currently in a text node, so we need to split it into two // halves and put the reference between. if ( isStartText = range.startContainer.type == CKEDITOR.NODE_TEXT ) { // Keep the original content. It will be restored. startContainerText = range.startContainer.getText(); // Split the startContainer at the this position. afterCaretNode = range.startContainer.split( range.startOffset ); // Insert the reference between two text nodes. reference.insertAfter( range.startContainer ); } // If not in a text node, simply insert the reference into the range. else { range.insertNode( reference ); } // Scroll with respect to the reference element. reference.scrollIntoView(); // Get rid of split parts if "in a text node" case. // Revert the original text of the startContainer. if ( isStartText ) { range.startContainer.setText( startContainerText ); afterCaretNode.remove(); } // Get rid of the reference node. It is no longer necessary. reference.remove(); }
[ "function", "(", ")", "{", "// The reference element contains a zero-width space to avoid", "// a premature removal. The view is to be scrolled with respect", "// to this element.", "var", "reference", "=", "new", "CKEDITOR", ".", "dom", ".", "element", ".", "createFromHtml", "(", "'<span>&nbsp;</span>'", ",", "this", ".", "document", ")", ",", "afterCaretNode", ",", "startContainerText", ",", "isStartText", ";", "var", "range", "=", "this", ".", "clone", "(", ")", ";", "// Work with the range to obtain a proper caret position.", "range", ".", "optimize", "(", ")", ";", "// Currently in a text node, so we need to split it into two", "// halves and put the reference between.", "if", "(", "isStartText", "=", "range", ".", "startContainer", ".", "type", "==", "CKEDITOR", ".", "NODE_TEXT", ")", "{", "// Keep the original content. It will be restored.", "startContainerText", "=", "range", ".", "startContainer", ".", "getText", "(", ")", ";", "// Split the startContainer at the this position.", "afterCaretNode", "=", "range", ".", "startContainer", ".", "split", "(", "range", ".", "startOffset", ")", ";", "// Insert the reference between two text nodes.", "reference", ".", "insertAfter", "(", "range", ".", "startContainer", ")", ";", "}", "// If not in a text node, simply insert the reference into the range.", "else", "{", "range", ".", "insertNode", "(", "reference", ")", ";", "}", "// Scroll with respect to the reference element.", "reference", ".", "scrollIntoView", "(", ")", ";", "// Get rid of split parts if \"in a text node\" case.", "// Revert the original text of the startContainer.", "if", "(", "isStartText", ")", "{", "range", ".", "startContainer", ".", "setText", "(", "startContainerText", ")", ";", "afterCaretNode", ".", "remove", "(", ")", ";", "}", "// Get rid of the reference node. It is no longer necessary.", "reference", ".", "remove", "(", ")", ";", "}" ]
Scrolls the start of current range into view.
[ "Scrolls", "the", "start", "of", "current", "range", "into", "view", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/range.js#L2440-L2483
56,126
JChapman202/flux-rx
src/PureView.js
shallowEquals
function shallowEquals(objA, objB) { var returnVal = false; if (objA === objB || objA === null && objB === null) { returnVal = true; } if (!returnVal) { var propsEqual = true; if (Object.keys(objA).length === Object.keys(objB).length) { for (var key in objA) { propsEqual = propsEqual && objA[key] === objB[key]; } returnVal = propsEqual; } } return returnVal; }
javascript
function shallowEquals(objA, objB) { var returnVal = false; if (objA === objB || objA === null && objB === null) { returnVal = true; } if (!returnVal) { var propsEqual = true; if (Object.keys(objA).length === Object.keys(objB).length) { for (var key in objA) { propsEqual = propsEqual && objA[key] === objB[key]; } returnVal = propsEqual; } } return returnVal; }
[ "function", "shallowEquals", "(", "objA", ",", "objB", ")", "{", "var", "returnVal", "=", "false", ";", "if", "(", "objA", "===", "objB", "||", "objA", "===", "null", "&&", "objB", "===", "null", ")", "{", "returnVal", "=", "true", ";", "}", "if", "(", "!", "returnVal", ")", "{", "var", "propsEqual", "=", "true", ";", "if", "(", "Object", ".", "keys", "(", "objA", ")", ".", "length", "===", "Object", ".", "keys", "(", "objB", ")", ".", "length", ")", "{", "for", "(", "var", "key", "in", "objA", ")", "{", "propsEqual", "=", "propsEqual", "&&", "objA", "[", "key", "]", "===", "objB", "[", "key", "]", ";", "}", "returnVal", "=", "propsEqual", ";", "}", "}", "return", "returnVal", ";", "}" ]
Utility function which evaluates if the two provided instances have all of the same properties as each other and if all of the properties on each other are equal. @param {Object} objA [description] @param {Object} objB [description] @return {Boolean} [description]
[ "Utility", "function", "which", "evaluates", "if", "the", "two", "provided", "instances", "have", "all", "of", "the", "same", "properties", "as", "each", "other", "and", "if", "all", "of", "the", "properties", "on", "each", "other", "are", "equal", "." ]
0063c400c991c5347e6a9751f9a86f8f2aa083fe
https://github.com/JChapman202/flux-rx/blob/0063c400c991c5347e6a9751f9a86f8f2aa083fe/src/PureView.js#L23-L42
56,127
ngageoint/eslint-plugin-opensphere
no-suppress.js
checkCommentForSuppress
function checkCommentForSuppress(node) { // Skip if types aren't provided or the comment is empty. if (!node || !node.value || node.value.length === 0) { return; } const match = node.value.match(/@suppress \{(.*?)\}/); if (match && match.length === 2) { if (!blacklistedTypes || blacklistedTypes.length === 0) { // Array is not present or empty, so block all types. context.report(node, '@suppress not allowed for any types'); } else { // Report which matched types are blocked. const matched = []; const types = match[1].split('|'); types.forEach(function(type) { if (blacklistedTypes.indexOf(type) !== -1 && matched.indexOf(type) === -1) { matched.push(type); } }); if (matched.length > 0) { const typeString = matched.join(', '); context.report(node, `@suppress not allowed for: ${typeString}`); } } } }
javascript
function checkCommentForSuppress(node) { // Skip if types aren't provided or the comment is empty. if (!node || !node.value || node.value.length === 0) { return; } const match = node.value.match(/@suppress \{(.*?)\}/); if (match && match.length === 2) { if (!blacklistedTypes || blacklistedTypes.length === 0) { // Array is not present or empty, so block all types. context.report(node, '@suppress not allowed for any types'); } else { // Report which matched types are blocked. const matched = []; const types = match[1].split('|'); types.forEach(function(type) { if (blacklistedTypes.indexOf(type) !== -1 && matched.indexOf(type) === -1) { matched.push(type); } }); if (matched.length > 0) { const typeString = matched.join(', '); context.report(node, `@suppress not allowed for: ${typeString}`); } } } }
[ "function", "checkCommentForSuppress", "(", "node", ")", "{", "// Skip if types aren't provided or the comment is empty.", "if", "(", "!", "node", "||", "!", "node", ".", "value", "||", "node", ".", "value", ".", "length", "===", "0", ")", "{", "return", ";", "}", "const", "match", "=", "node", ".", "value", ".", "match", "(", "/", "@suppress \\{(.*?)\\}", "/", ")", ";", "if", "(", "match", "&&", "match", ".", "length", "===", "2", ")", "{", "if", "(", "!", "blacklistedTypes", "||", "blacklistedTypes", ".", "length", "===", "0", ")", "{", "// Array is not present or empty, so block all types.", "context", ".", "report", "(", "node", ",", "'@suppress not allowed for any types'", ")", ";", "}", "else", "{", "// Report which matched types are blocked.", "const", "matched", "=", "[", "]", ";", "const", "types", "=", "match", "[", "1", "]", ".", "split", "(", "'|'", ")", ";", "types", ".", "forEach", "(", "function", "(", "type", ")", "{", "if", "(", "blacklistedTypes", ".", "indexOf", "(", "type", ")", "!==", "-", "1", "&&", "matched", ".", "indexOf", "(", "type", ")", "===", "-", "1", ")", "{", "matched", ".", "push", "(", "type", ")", ";", "}", "}", ")", ";", "if", "(", "matched", ".", "length", ">", "0", ")", "{", "const", "typeString", "=", "matched", ".", "join", "(", "', '", ")", ";", "context", ".", "report", "(", "node", ",", "`", "${", "typeString", "}", "`", ")", ";", "}", "}", "}", "}" ]
Reports a given comment if it contains blocked suppress types. @param {ASTNode} node A comment node to check.
[ "Reports", "a", "given", "comment", "if", "it", "contains", "blocked", "suppress", "types", "." ]
3d1804b49a0349aeba0eb694e45266fb2cb2d83b
https://github.com/ngageoint/eslint-plugin-opensphere/blob/3d1804b49a0349aeba0eb694e45266fb2cb2d83b/no-suppress.js#L28-L55
56,128
ForbesLindesay-Unmaintained/to-bool-function
index.js
toBoolFunction
function toBoolFunction(selector, condition) { if (arguments.length == 2) { selector = toBoolFunction(selector); condition = toBoolFunction(condition); return function () { return condition(selector.apply(this, arguments)); }; } else { condition = selector; } var alternate = false; try { switch (type(condition)) { case 'regexp': alternate = regexpToFunction(condition); break; case 'string': alternate = stringToFunction(condition); break; case 'function': alternate = condition; break; case 'object': alternate = objectToFunction(condition); break; } } catch (ex) { //ignore things that aren't valid functions } return function (val) { return (val === condition) || (alternate && alternate.apply(this, arguments)); } }
javascript
function toBoolFunction(selector, condition) { if (arguments.length == 2) { selector = toBoolFunction(selector); condition = toBoolFunction(condition); return function () { return condition(selector.apply(this, arguments)); }; } else { condition = selector; } var alternate = false; try { switch (type(condition)) { case 'regexp': alternate = regexpToFunction(condition); break; case 'string': alternate = stringToFunction(condition); break; case 'function': alternate = condition; break; case 'object': alternate = objectToFunction(condition); break; } } catch (ex) { //ignore things that aren't valid functions } return function (val) { return (val === condition) || (alternate && alternate.apply(this, arguments)); } }
[ "function", "toBoolFunction", "(", "selector", ",", "condition", ")", "{", "if", "(", "arguments", ".", "length", "==", "2", ")", "{", "selector", "=", "toBoolFunction", "(", "selector", ")", ";", "condition", "=", "toBoolFunction", "(", "condition", ")", ";", "return", "function", "(", ")", "{", "return", "condition", "(", "selector", ".", "apply", "(", "this", ",", "arguments", ")", ")", ";", "}", ";", "}", "else", "{", "condition", "=", "selector", ";", "}", "var", "alternate", "=", "false", ";", "try", "{", "switch", "(", "type", "(", "condition", ")", ")", "{", "case", "'regexp'", ":", "alternate", "=", "regexpToFunction", "(", "condition", ")", ";", "break", ";", "case", "'string'", ":", "alternate", "=", "stringToFunction", "(", "condition", ")", ";", "break", ";", "case", "'function'", ":", "alternate", "=", "condition", ";", "break", ";", "case", "'object'", ":", "alternate", "=", "objectToFunction", "(", "condition", ")", ";", "break", ";", "}", "}", "catch", "(", "ex", ")", "{", "//ignore things that aren't valid functions", "}", "return", "function", "(", "val", ")", "{", "return", "(", "val", "===", "condition", ")", "||", "(", "alternate", "&&", "alternate", ".", "apply", "(", "this", ",", "arguments", ")", ")", ";", "}", "}" ]
Convert various possible things into a match function @param {Any} [selector] @param {Any} condition @return {Function}
[ "Convert", "various", "possible", "things", "into", "a", "match", "function" ]
731073819369d97559ef4038937df998df3e5e90
https://github.com/ForbesLindesay-Unmaintained/to-bool-function/blob/731073819369d97559ef4038937df998df3e5e90/index.js#L12-L45
56,129
ForbesLindesay-Unmaintained/to-bool-function
index.js
objectToFunction
function objectToFunction(obj) { var fns = Object.keys(obj) .map(function (key) { return toBoolFunction(key, obj[key]); }); return function(o){ for (var i = 0; i < fns.length; i++) { if (!fns[i](o)) return false; } return true; } }
javascript
function objectToFunction(obj) { var fns = Object.keys(obj) .map(function (key) { return toBoolFunction(key, obj[key]); }); return function(o){ for (var i = 0; i < fns.length; i++) { if (!fns[i](o)) return false; } return true; } }
[ "function", "objectToFunction", "(", "obj", ")", "{", "var", "fns", "=", "Object", ".", "keys", "(", "obj", ")", ".", "map", "(", "function", "(", "key", ")", "{", "return", "toBoolFunction", "(", "key", ",", "obj", "[", "key", "]", ")", ";", "}", ")", ";", "return", "function", "(", "o", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "fns", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "fns", "[", "i", "]", "(", "o", ")", ")", "return", "false", ";", "}", "return", "true", ";", "}", "}" ]
Convert `obj` into a match function. @param {Object} obj @return {Function} @api private
[ "Convert", "obj", "into", "a", "match", "function", "." ]
731073819369d97559ef4038937df998df3e5e90
https://github.com/ForbesLindesay-Unmaintained/to-bool-function/blob/731073819369d97559ef4038937df998df3e5e90/index.js#L67-L78
56,130
ForbesLindesay-Unmaintained/to-bool-function
index.js
stringToFunction
function stringToFunction(str) { // immediate such as "> 20" if (/^ *\W+/.test(str)) return new Function('_', 'return _ ' + str); // properties such as "name.first" or "age > 18" var fn = new Function('_', 'return _.' + str); return fn }
javascript
function stringToFunction(str) { // immediate such as "> 20" if (/^ *\W+/.test(str)) return new Function('_', 'return _ ' + str); // properties such as "name.first" or "age > 18" var fn = new Function('_', 'return _.' + str); return fn }
[ "function", "stringToFunction", "(", "str", ")", "{", "// immediate such as \"> 20\"", "if", "(", "/", "^ *\\W+", "/", ".", "test", "(", "str", ")", ")", "return", "new", "Function", "(", "'_'", ",", "'return _ '", "+", "str", ")", ";", "// properties such as \"name.first\" or \"age > 18\"", "var", "fn", "=", "new", "Function", "(", "'_'", ",", "'return _.'", "+", "str", ")", ";", "return", "fn", "}" ]
Convert property `str` to a function. @param {String} str @return {Function} @api private
[ "Convert", "property", "str", "to", "a", "function", "." ]
731073819369d97559ef4038937df998df3e5e90
https://github.com/ForbesLindesay-Unmaintained/to-bool-function/blob/731073819369d97559ef4038937df998df3e5e90/index.js#L88-L95
56,131
benzhou1/iod
index.js
function(apiKey, host, port, reqOpts) { var iod = this if (_.isObject(host)) { reqOpts = host host = null } else if (_.isObject(port)) { reqOpts = port port = null } if (!apiKey) throw Error('IOD apiKey is missing!') else if (host && !url.parse(host, false, true).protocol) { throw Error('Protocol not found on host: ' + host) } var httpHost = 'http://api.idolondemand.com' var httpsHost = 'https://api.idolondemand.com' var httpPort = 80 var httpsPort = 443 // If Https port point to Https host and vice versa if (host == null && port === httpsPort) host = httpsHost else if (host == null && port === httpPort) host = httpHost else if (port == null && host && host.toLowerCase() === httpsHost) port = httpsPort else if (port == null && host && host.toLowerCase() === httpHost) port = httpPort iod.apiKey = apiKey iod.host = host || httpsHost iod.port = port || httpsPort iod.reqOpts = _.defaults(reqOpts || {}, { timeout: 300000 }) iod.ACTIONS = _.cloneDeep(CONSTANTS.ACTIONS) iod.eventEmitter = eventEmitter SchemaU.initSchemas(iod) _.bindAll.apply(_, [iod].concat(_.functions(IOD.prototype))) }
javascript
function(apiKey, host, port, reqOpts) { var iod = this if (_.isObject(host)) { reqOpts = host host = null } else if (_.isObject(port)) { reqOpts = port port = null } if (!apiKey) throw Error('IOD apiKey is missing!') else if (host && !url.parse(host, false, true).protocol) { throw Error('Protocol not found on host: ' + host) } var httpHost = 'http://api.idolondemand.com' var httpsHost = 'https://api.idolondemand.com' var httpPort = 80 var httpsPort = 443 // If Https port point to Https host and vice versa if (host == null && port === httpsPort) host = httpsHost else if (host == null && port === httpPort) host = httpHost else if (port == null && host && host.toLowerCase() === httpsHost) port = httpsPort else if (port == null && host && host.toLowerCase() === httpHost) port = httpPort iod.apiKey = apiKey iod.host = host || httpsHost iod.port = port || httpsPort iod.reqOpts = _.defaults(reqOpts || {}, { timeout: 300000 }) iod.ACTIONS = _.cloneDeep(CONSTANTS.ACTIONS) iod.eventEmitter = eventEmitter SchemaU.initSchemas(iod) _.bindAll.apply(_, [iod].concat(_.functions(IOD.prototype))) }
[ "function", "(", "apiKey", ",", "host", ",", "port", ",", "reqOpts", ")", "{", "var", "iod", "=", "this", "if", "(", "_", ".", "isObject", "(", "host", ")", ")", "{", "reqOpts", "=", "host", "host", "=", "null", "}", "else", "if", "(", "_", ".", "isObject", "(", "port", ")", ")", "{", "reqOpts", "=", "port", "port", "=", "null", "}", "if", "(", "!", "apiKey", ")", "throw", "Error", "(", "'IOD apiKey is missing!'", ")", "else", "if", "(", "host", "&&", "!", "url", ".", "parse", "(", "host", ",", "false", ",", "true", ")", ".", "protocol", ")", "{", "throw", "Error", "(", "'Protocol not found on host: '", "+", "host", ")", "}", "var", "httpHost", "=", "'http://api.idolondemand.com'", "var", "httpsHost", "=", "'https://api.idolondemand.com'", "var", "httpPort", "=", "80", "var", "httpsPort", "=", "443", "// If Https port point to Https host and vice versa", "if", "(", "host", "==", "null", "&&", "port", "===", "httpsPort", ")", "host", "=", "httpsHost", "else", "if", "(", "host", "==", "null", "&&", "port", "===", "httpPort", ")", "host", "=", "httpHost", "else", "if", "(", "port", "==", "null", "&&", "host", "&&", "host", ".", "toLowerCase", "(", ")", "===", "httpsHost", ")", "port", "=", "httpsPort", "else", "if", "(", "port", "==", "null", "&&", "host", "&&", "host", ".", "toLowerCase", "(", ")", "===", "httpHost", ")", "port", "=", "httpPort", "iod", ".", "apiKey", "=", "apiKey", "iod", ".", "host", "=", "host", "||", "httpsHost", "iod", ".", "port", "=", "port", "||", "httpsPort", "iod", ".", "reqOpts", "=", "_", ".", "defaults", "(", "reqOpts", "||", "{", "}", ",", "{", "timeout", ":", "300000", "}", ")", "iod", ".", "ACTIONS", "=", "_", ".", "cloneDeep", "(", "CONSTANTS", ".", "ACTIONS", ")", "iod", ".", "eventEmitter", "=", "eventEmitter", "SchemaU", ".", "initSchemas", "(", "iod", ")", "_", ".", "bindAll", ".", "apply", "(", "_", ",", "[", "iod", "]", ".", "concat", "(", "_", ".", "functions", "(", "IOD", ".", "prototype", ")", ")", ")", "}" ]
Creates a IOD object with specified apiKey, host and port. @param {String} apiKey - Api key @param {String} [host] - IOD host @param {Integer | null} [port] - IOD port @param {Integer} [reqOpts] - Request options @property {String} apiKey - Api key @property {String} host - IOD host @property {Integer} port - IOD port @property {Object} reqOpts - Request options @constructor @throws {Error} If api key does not exists. If host does not contain protocol
[ "Creates", "a", "IOD", "object", "with", "specified", "apiKey", "host", "and", "port", "." ]
a346628f9bc5e4420e4d00e8f21c4cb268b6237c
https://github.com/benzhou1/iod/blob/a346628f9bc5e4420e4d00e8f21c4cb268b6237c/index.js#L35-L73
56,132
icanjs/grid-filter
src/jquery-tokeninput/jquery-tokeninput.js
insert_token
function insert_token(item) { var $this_token = $($(input).data("settings").tokenFormatter(item)); var readonly = item.readonly === true ? true : false; if(readonly) $this_token.addClass($(input).data("settings").classes.tokenReadOnly); $this_token.addClass($(input).data("settings").classes.token).insertBefore(input_token); // The 'delete token' button if(!readonly) { $("<span>" + $(input).data("settings").deleteText + "</span>") .addClass($(input).data("settings").classes.tokenDelete) .appendTo($this_token) .click(function () { if (!$(input).data("settings").disabled) { delete_token($(this).parent()); hidden_input.change(); return false; } }); } // Store data on the token var token_data = item; $.data($this_token.get(0), "tokeninput", item); // Save this token for duplicate checking saved_tokens = saved_tokens.slice(0,selected_token_index).concat([token_data]).concat(saved_tokens.slice(selected_token_index)); selected_token_index++; // Update the hidden input update_hidden_input(saved_tokens, hidden_input); token_count += 1; // Check the token limit if($(input).data("settings").tokenLimit !== null && token_count >= $(input).data("settings").tokenLimit) { input_box.hide(); hide_dropdown(); } return $this_token; }
javascript
function insert_token(item) { var $this_token = $($(input).data("settings").tokenFormatter(item)); var readonly = item.readonly === true ? true : false; if(readonly) $this_token.addClass($(input).data("settings").classes.tokenReadOnly); $this_token.addClass($(input).data("settings").classes.token).insertBefore(input_token); // The 'delete token' button if(!readonly) { $("<span>" + $(input).data("settings").deleteText + "</span>") .addClass($(input).data("settings").classes.tokenDelete) .appendTo($this_token) .click(function () { if (!$(input).data("settings").disabled) { delete_token($(this).parent()); hidden_input.change(); return false; } }); } // Store data on the token var token_data = item; $.data($this_token.get(0), "tokeninput", item); // Save this token for duplicate checking saved_tokens = saved_tokens.slice(0,selected_token_index).concat([token_data]).concat(saved_tokens.slice(selected_token_index)); selected_token_index++; // Update the hidden input update_hidden_input(saved_tokens, hidden_input); token_count += 1; // Check the token limit if($(input).data("settings").tokenLimit !== null && token_count >= $(input).data("settings").tokenLimit) { input_box.hide(); hide_dropdown(); } return $this_token; }
[ "function", "insert_token", "(", "item", ")", "{", "var", "$this_token", "=", "$", "(", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "tokenFormatter", "(", "item", ")", ")", ";", "var", "readonly", "=", "item", ".", "readonly", "===", "true", "?", "true", ":", "false", ";", "if", "(", "readonly", ")", "$this_token", ".", "addClass", "(", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "classes", ".", "tokenReadOnly", ")", ";", "$this_token", ".", "addClass", "(", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "classes", ".", "token", ")", ".", "insertBefore", "(", "input_token", ")", ";", "// The 'delete token' button", "if", "(", "!", "readonly", ")", "{", "$", "(", "\"<span>\"", "+", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "deleteText", "+", "\"</span>\"", ")", ".", "addClass", "(", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "classes", ".", "tokenDelete", ")", ".", "appendTo", "(", "$this_token", ")", ".", "click", "(", "function", "(", ")", "{", "if", "(", "!", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "disabled", ")", "{", "delete_token", "(", "$", "(", "this", ")", ".", "parent", "(", ")", ")", ";", "hidden_input", ".", "change", "(", ")", ";", "return", "false", ";", "}", "}", ")", ";", "}", "// Store data on the token", "var", "token_data", "=", "item", ";", "$", ".", "data", "(", "$this_token", ".", "get", "(", "0", ")", ",", "\"tokeninput\"", ",", "item", ")", ";", "// Save this token for duplicate checking", "saved_tokens", "=", "saved_tokens", ".", "slice", "(", "0", ",", "selected_token_index", ")", ".", "concat", "(", "[", "token_data", "]", ")", ".", "concat", "(", "saved_tokens", ".", "slice", "(", "selected_token_index", ")", ")", ";", "selected_token_index", "++", ";", "// Update the hidden input", "update_hidden_input", "(", "saved_tokens", ",", "hidden_input", ")", ";", "token_count", "+=", "1", ";", "// Check the token limit", "if", "(", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "tokenLimit", "!==", "null", "&&", "token_count", ">=", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "tokenLimit", ")", "{", "input_box", ".", "hide", "(", ")", ";", "hide_dropdown", "(", ")", ";", "}", "return", "$this_token", ";", "}" ]
Inner function to a token to the list
[ "Inner", "function", "to", "a", "token", "to", "the", "list" ]
48d9ce876cdc6ef459fcae70ac67b23229e85a5a
https://github.com/icanjs/grid-filter/blob/48d9ce876cdc6ef459fcae70ac67b23229e85a5a/src/jquery-tokeninput/jquery-tokeninput.js#L607-L649
56,133
icanjs/grid-filter
src/jquery-tokeninput/jquery-tokeninput.js
add_token
function add_token (item) { var callback = $(input).data("settings").onAdd; // See if the token already exists and select it if we don't want duplicates if(token_count > 0 && $(input).data("settings").preventDuplicates) { var found_existing_token = null; token_list.children().each(function () { var existing_token = $(this); var existing_data = $.data(existing_token.get(0), "tokeninput"); if(existing_data && existing_data[settings.tokenValue] === item[settings.tokenValue]) { found_existing_token = existing_token; return false; } }); if(found_existing_token) { select_token(found_existing_token); input_token.insertAfter(found_existing_token); focus_with_timeout(input_box); return; } } // Squeeze input_box so we force no unnecessary line break input_box.width(1); // Insert the new tokens if($(input).data("settings").tokenLimit == null || token_count < $(input).data("settings").tokenLimit) { insert_token(item); // Remove the placeholder so it's not seen after you've added a token input_box.attr("placeholder", null) checkTokenLimit(); } // Clear input box input_box.val(""); // Don't show the help dropdown, they've got the idea hide_dropdown(); // Execute the onAdd callback if defined if($.isFunction(callback)) { callback.call(hidden_input,item); } }
javascript
function add_token (item) { var callback = $(input).data("settings").onAdd; // See if the token already exists and select it if we don't want duplicates if(token_count > 0 && $(input).data("settings").preventDuplicates) { var found_existing_token = null; token_list.children().each(function () { var existing_token = $(this); var existing_data = $.data(existing_token.get(0), "tokeninput"); if(existing_data && existing_data[settings.tokenValue] === item[settings.tokenValue]) { found_existing_token = existing_token; return false; } }); if(found_existing_token) { select_token(found_existing_token); input_token.insertAfter(found_existing_token); focus_with_timeout(input_box); return; } } // Squeeze input_box so we force no unnecessary line break input_box.width(1); // Insert the new tokens if($(input).data("settings").tokenLimit == null || token_count < $(input).data("settings").tokenLimit) { insert_token(item); // Remove the placeholder so it's not seen after you've added a token input_box.attr("placeholder", null) checkTokenLimit(); } // Clear input box input_box.val(""); // Don't show the help dropdown, they've got the idea hide_dropdown(); // Execute the onAdd callback if defined if($.isFunction(callback)) { callback.call(hidden_input,item); } }
[ "function", "add_token", "(", "item", ")", "{", "var", "callback", "=", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "onAdd", ";", "// See if the token already exists and select it if we don't want duplicates", "if", "(", "token_count", ">", "0", "&&", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "preventDuplicates", ")", "{", "var", "found_existing_token", "=", "null", ";", "token_list", ".", "children", "(", ")", ".", "each", "(", "function", "(", ")", "{", "var", "existing_token", "=", "$", "(", "this", ")", ";", "var", "existing_data", "=", "$", ".", "data", "(", "existing_token", ".", "get", "(", "0", ")", ",", "\"tokeninput\"", ")", ";", "if", "(", "existing_data", "&&", "existing_data", "[", "settings", ".", "tokenValue", "]", "===", "item", "[", "settings", ".", "tokenValue", "]", ")", "{", "found_existing_token", "=", "existing_token", ";", "return", "false", ";", "}", "}", ")", ";", "if", "(", "found_existing_token", ")", "{", "select_token", "(", "found_existing_token", ")", ";", "input_token", ".", "insertAfter", "(", "found_existing_token", ")", ";", "focus_with_timeout", "(", "input_box", ")", ";", "return", ";", "}", "}", "// Squeeze input_box so we force no unnecessary line break", "input_box", ".", "width", "(", "1", ")", ";", "// Insert the new tokens", "if", "(", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "tokenLimit", "==", "null", "||", "token_count", "<", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "tokenLimit", ")", "{", "insert_token", "(", "item", ")", ";", "// Remove the placeholder so it's not seen after you've added a token", "input_box", ".", "attr", "(", "\"placeholder\"", ",", "null", ")", "checkTokenLimit", "(", ")", ";", "}", "// Clear input box", "input_box", ".", "val", "(", "\"\"", ")", ";", "// Don't show the help dropdown, they've got the idea", "hide_dropdown", "(", ")", ";", "// Execute the onAdd callback if defined", "if", "(", "$", ".", "isFunction", "(", "callback", ")", ")", "{", "callback", ".", "call", "(", "hidden_input", ",", "item", ")", ";", "}", "}" ]
Add a token to the token list based on user input
[ "Add", "a", "token", "to", "the", "token", "list", "based", "on", "user", "input" ]
48d9ce876cdc6ef459fcae70ac67b23229e85a5a
https://github.com/icanjs/grid-filter/blob/48d9ce876cdc6ef459fcae70ac67b23229e85a5a/src/jquery-tokeninput/jquery-tokeninput.js#L652-L696
56,134
icanjs/grid-filter
src/jquery-tokeninput/jquery-tokeninput.js
select_token
function select_token (token) { if (!$(input).data("settings").disabled) { token.addClass($(input).data("settings").classes.selectedToken); selected_token = token.get(0); // Hide input box input_box.val(""); // Hide dropdown if it is visible (eg if we clicked to select token) hide_dropdown(); } }
javascript
function select_token (token) { if (!$(input).data("settings").disabled) { token.addClass($(input).data("settings").classes.selectedToken); selected_token = token.get(0); // Hide input box input_box.val(""); // Hide dropdown if it is visible (eg if we clicked to select token) hide_dropdown(); } }
[ "function", "select_token", "(", "token", ")", "{", "if", "(", "!", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "disabled", ")", "{", "token", ".", "addClass", "(", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "classes", ".", "selectedToken", ")", ";", "selected_token", "=", "token", ".", "get", "(", "0", ")", ";", "// Hide input box", "input_box", ".", "val", "(", "\"\"", ")", ";", "// Hide dropdown if it is visible (eg if we clicked to select token)", "hide_dropdown", "(", ")", ";", "}", "}" ]
Select a token in the token list
[ "Select", "a", "token", "in", "the", "token", "list" ]
48d9ce876cdc6ef459fcae70ac67b23229e85a5a
https://github.com/icanjs/grid-filter/blob/48d9ce876cdc6ef459fcae70ac67b23229e85a5a/src/jquery-tokeninput/jquery-tokeninput.js#L699-L710
56,135
icanjs/grid-filter
src/jquery-tokeninput/jquery-tokeninput.js
deselect_token
function deselect_token (token, position) { token.removeClass($(input).data("settings").classes.selectedToken); selected_token = null; if(position === POSITION.BEFORE) { input_token.insertBefore(token); selected_token_index--; } else if(position === POSITION.AFTER) { input_token.insertAfter(token); selected_token_index++; } else { input_token.appendTo(token_list); selected_token_index = token_count; } // Show the input box and give it focus again focus_with_timeout(input_box); }
javascript
function deselect_token (token, position) { token.removeClass($(input).data("settings").classes.selectedToken); selected_token = null; if(position === POSITION.BEFORE) { input_token.insertBefore(token); selected_token_index--; } else if(position === POSITION.AFTER) { input_token.insertAfter(token); selected_token_index++; } else { input_token.appendTo(token_list); selected_token_index = token_count; } // Show the input box and give it focus again focus_with_timeout(input_box); }
[ "function", "deselect_token", "(", "token", ",", "position", ")", "{", "token", ".", "removeClass", "(", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "classes", ".", "selectedToken", ")", ";", "selected_token", "=", "null", ";", "if", "(", "position", "===", "POSITION", ".", "BEFORE", ")", "{", "input_token", ".", "insertBefore", "(", "token", ")", ";", "selected_token_index", "--", ";", "}", "else", "if", "(", "position", "===", "POSITION", ".", "AFTER", ")", "{", "input_token", ".", "insertAfter", "(", "token", ")", ";", "selected_token_index", "++", ";", "}", "else", "{", "input_token", ".", "appendTo", "(", "token_list", ")", ";", "selected_token_index", "=", "token_count", ";", "}", "// Show the input box and give it focus again", "focus_with_timeout", "(", "input_box", ")", ";", "}" ]
Deselect a token in the token list
[ "Deselect", "a", "token", "in", "the", "token", "list" ]
48d9ce876cdc6ef459fcae70ac67b23229e85a5a
https://github.com/icanjs/grid-filter/blob/48d9ce876cdc6ef459fcae70ac67b23229e85a5a/src/jquery-tokeninput/jquery-tokeninput.js#L713-L730
56,136
icanjs/grid-filter
src/jquery-tokeninput/jquery-tokeninput.js
toggle_select_token
function toggle_select_token(token) { var previous_selected_token = selected_token; if(selected_token) { deselect_token($(selected_token), POSITION.END); } if(previous_selected_token === token.get(0)) { deselect_token(token, POSITION.END); } else { select_token(token); } }
javascript
function toggle_select_token(token) { var previous_selected_token = selected_token; if(selected_token) { deselect_token($(selected_token), POSITION.END); } if(previous_selected_token === token.get(0)) { deselect_token(token, POSITION.END); } else { select_token(token); } }
[ "function", "toggle_select_token", "(", "token", ")", "{", "var", "previous_selected_token", "=", "selected_token", ";", "if", "(", "selected_token", ")", "{", "deselect_token", "(", "$", "(", "selected_token", ")", ",", "POSITION", ".", "END", ")", ";", "}", "if", "(", "previous_selected_token", "===", "token", ".", "get", "(", "0", ")", ")", "{", "deselect_token", "(", "token", ",", "POSITION", ".", "END", ")", ";", "}", "else", "{", "select_token", "(", "token", ")", ";", "}", "}" ]
Toggle selection of a token in the token list
[ "Toggle", "selection", "of", "a", "token", "in", "the", "token", "list" ]
48d9ce876cdc6ef459fcae70ac67b23229e85a5a
https://github.com/icanjs/grid-filter/blob/48d9ce876cdc6ef459fcae70ac67b23229e85a5a/src/jquery-tokeninput/jquery-tokeninput.js#L733-L745
56,137
icanjs/grid-filter
src/jquery-tokeninput/jquery-tokeninput.js
delete_token
function delete_token (token) { // Remove the id from the saved list var token_data = $.data(token.get(0), "tokeninput"); var callback = $(input).data("settings").onDelete; var index = token.prevAll().length; if(index > selected_token_index) index--; // Delete the token token.remove(); selected_token = null; // Show the input box and give it focus again focus_with_timeout(input_box); // Remove this token from the saved list saved_tokens = saved_tokens.slice(0,index).concat(saved_tokens.slice(index+1)); if (saved_tokens.length == 0) { input_box.attr("placeholder", settings.placeholder) } if(index < selected_token_index) selected_token_index--; // Update the hidden input update_hidden_input(saved_tokens, hidden_input); token_count -= 1; if($(input).data("settings").tokenLimit !== null) { input_box .show() .val(""); focus_with_timeout(input_box); } // Execute the onDelete callback if defined if($.isFunction(callback)) { callback.call(hidden_input,token_data); } }
javascript
function delete_token (token) { // Remove the id from the saved list var token_data = $.data(token.get(0), "tokeninput"); var callback = $(input).data("settings").onDelete; var index = token.prevAll().length; if(index > selected_token_index) index--; // Delete the token token.remove(); selected_token = null; // Show the input box and give it focus again focus_with_timeout(input_box); // Remove this token from the saved list saved_tokens = saved_tokens.slice(0,index).concat(saved_tokens.slice(index+1)); if (saved_tokens.length == 0) { input_box.attr("placeholder", settings.placeholder) } if(index < selected_token_index) selected_token_index--; // Update the hidden input update_hidden_input(saved_tokens, hidden_input); token_count -= 1; if($(input).data("settings").tokenLimit !== null) { input_box .show() .val(""); focus_with_timeout(input_box); } // Execute the onDelete callback if defined if($.isFunction(callback)) { callback.call(hidden_input,token_data); } }
[ "function", "delete_token", "(", "token", ")", "{", "// Remove the id from the saved list", "var", "token_data", "=", "$", ".", "data", "(", "token", ".", "get", "(", "0", ")", ",", "\"tokeninput\"", ")", ";", "var", "callback", "=", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "onDelete", ";", "var", "index", "=", "token", ".", "prevAll", "(", ")", ".", "length", ";", "if", "(", "index", ">", "selected_token_index", ")", "index", "--", ";", "// Delete the token", "token", ".", "remove", "(", ")", ";", "selected_token", "=", "null", ";", "// Show the input box and give it focus again", "focus_with_timeout", "(", "input_box", ")", ";", "// Remove this token from the saved list", "saved_tokens", "=", "saved_tokens", ".", "slice", "(", "0", ",", "index", ")", ".", "concat", "(", "saved_tokens", ".", "slice", "(", "index", "+", "1", ")", ")", ";", "if", "(", "saved_tokens", ".", "length", "==", "0", ")", "{", "input_box", ".", "attr", "(", "\"placeholder\"", ",", "settings", ".", "placeholder", ")", "}", "if", "(", "index", "<", "selected_token_index", ")", "selected_token_index", "--", ";", "// Update the hidden input", "update_hidden_input", "(", "saved_tokens", ",", "hidden_input", ")", ";", "token_count", "-=", "1", ";", "if", "(", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "tokenLimit", "!==", "null", ")", "{", "input_box", ".", "show", "(", ")", ".", "val", "(", "\"\"", ")", ";", "focus_with_timeout", "(", "input_box", ")", ";", "}", "// Execute the onDelete callback if defined", "if", "(", "$", ".", "isFunction", "(", "callback", ")", ")", "{", "callback", ".", "call", "(", "hidden_input", ",", "token_data", ")", ";", "}", "}" ]
Delete a token from the token list
[ "Delete", "a", "token", "from", "the", "token", "list" ]
48d9ce876cdc6ef459fcae70ac67b23229e85a5a
https://github.com/icanjs/grid-filter/blob/48d9ce876cdc6ef459fcae70ac67b23229e85a5a/src/jquery-tokeninput/jquery-tokeninput.js#L748-L786
56,138
icanjs/grid-filter
src/jquery-tokeninput/jquery-tokeninput.js
update_hidden_input
function update_hidden_input(saved_tokens, hidden_input) { var token_values = $.map(saved_tokens, function (el) { if(typeof $(input).data("settings").tokenValue == 'function') return $(input).data("settings").tokenValue.call(this, el); return el[$(input).data("settings").tokenValue]; }); hidden_input.val(token_values.join($(input).data("settings").tokenDelimiter)); }
javascript
function update_hidden_input(saved_tokens, hidden_input) { var token_values = $.map(saved_tokens, function (el) { if(typeof $(input).data("settings").tokenValue == 'function') return $(input).data("settings").tokenValue.call(this, el); return el[$(input).data("settings").tokenValue]; }); hidden_input.val(token_values.join($(input).data("settings").tokenDelimiter)); }
[ "function", "update_hidden_input", "(", "saved_tokens", ",", "hidden_input", ")", "{", "var", "token_values", "=", "$", ".", "map", "(", "saved_tokens", ",", "function", "(", "el", ")", "{", "if", "(", "typeof", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "tokenValue", "==", "'function'", ")", "return", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "tokenValue", ".", "call", "(", "this", ",", "el", ")", ";", "return", "el", "[", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "tokenValue", "]", ";", "}", ")", ";", "hidden_input", ".", "val", "(", "token_values", ".", "join", "(", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "tokenDelimiter", ")", ")", ";", "}" ]
Update the hidden input box value
[ "Update", "the", "hidden", "input", "box", "value" ]
48d9ce876cdc6ef459fcae70ac67b23229e85a5a
https://github.com/icanjs/grid-filter/blob/48d9ce876cdc6ef459fcae70ac67b23229e85a5a/src/jquery-tokeninput/jquery-tokeninput.js#L789-L798
56,139
icanjs/grid-filter
src/jquery-tokeninput/jquery-tokeninput.js
highlight_term
function highlight_term(value, term) { return value.replace( new RegExp( "(?![^&;]+;)(?!<[^<>]*)(" + regexp_escape(term) + ")(?![^<>]*>)(?![^&;]+;)", "gi" ), function(match, p1) { return "<b>" + escapeHTML(p1) + "</b>"; } ); }
javascript
function highlight_term(value, term) { return value.replace( new RegExp( "(?![^&;]+;)(?!<[^<>]*)(" + regexp_escape(term) + ")(?![^<>]*>)(?![^&;]+;)", "gi" ), function(match, p1) { return "<b>" + escapeHTML(p1) + "</b>"; } ); }
[ "function", "highlight_term", "(", "value", ",", "term", ")", "{", "return", "value", ".", "replace", "(", "new", "RegExp", "(", "\"(?![^&;]+;)(?!<[^<>]*)(\"", "+", "regexp_escape", "(", "term", ")", "+", "\")(?![^<>]*>)(?![^&;]+;)\"", ",", "\"gi\"", ")", ",", "function", "(", "match", ",", "p1", ")", "{", "return", "\"<b>\"", "+", "escapeHTML", "(", "p1", ")", "+", "\"</b>\"", ";", "}", ")", ";", "}" ]
Highlight the query part of the search term
[ "Highlight", "the", "query", "part", "of", "the", "search", "term" ]
48d9ce876cdc6ef459fcae70ac67b23229e85a5a
https://github.com/icanjs/grid-filter/blob/48d9ce876cdc6ef459fcae70ac67b23229e85a5a/src/jquery-tokeninput/jquery-tokeninput.js#L838-L847
56,140
icanjs/grid-filter
src/jquery-tokeninput/jquery-tokeninput.js
excludeCurrent
function excludeCurrent(results) { if ($(input).data("settings").excludeCurrent) { var currentTokens = $(input).data("tokenInputObject").getTokens(), trimmedList = []; if (currentTokens.length) { $.each(results, function(index, value) { var notFound = true; $.each(currentTokens, function(cIndex, cValue) { if (value[$(input).data("settings").propertyToSearch] == cValue[$(input).data("settings").propertyToSearch]) { notFound = false; return false; } }); if (notFound) { trimmedList.push(value); } }); results = trimmedList; } } return results; }
javascript
function excludeCurrent(results) { if ($(input).data("settings").excludeCurrent) { var currentTokens = $(input).data("tokenInputObject").getTokens(), trimmedList = []; if (currentTokens.length) { $.each(results, function(index, value) { var notFound = true; $.each(currentTokens, function(cIndex, cValue) { if (value[$(input).data("settings").propertyToSearch] == cValue[$(input).data("settings").propertyToSearch]) { notFound = false; return false; } }); if (notFound) { trimmedList.push(value); } }); results = trimmedList; } } return results; }
[ "function", "excludeCurrent", "(", "results", ")", "{", "if", "(", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "excludeCurrent", ")", "{", "var", "currentTokens", "=", "$", "(", "input", ")", ".", "data", "(", "\"tokenInputObject\"", ")", ".", "getTokens", "(", ")", ",", "trimmedList", "=", "[", "]", ";", "if", "(", "currentTokens", ".", "length", ")", "{", "$", ".", "each", "(", "results", ",", "function", "(", "index", ",", "value", ")", "{", "var", "notFound", "=", "true", ";", "$", ".", "each", "(", "currentTokens", ",", "function", "(", "cIndex", ",", "cValue", ")", "{", "if", "(", "value", "[", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "propertyToSearch", "]", "==", "cValue", "[", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "propertyToSearch", "]", ")", "{", "notFound", "=", "false", ";", "return", "false", ";", "}", "}", ")", ";", "if", "(", "notFound", ")", "{", "trimmedList", ".", "push", "(", "value", ")", ";", "}", "}", ")", ";", "results", "=", "trimmedList", ";", "}", "}", "return", "results", ";", "}" ]
exclude existing tokens from dropdown, so the list is clearer
[ "exclude", "existing", "tokens", "from", "dropdown", "so", "the", "list", "is", "clearer" ]
48d9ce876cdc6ef459fcae70ac67b23229e85a5a
https://github.com/icanjs/grid-filter/blob/48d9ce876cdc6ef459fcae70ac67b23229e85a5a/src/jquery-tokeninput/jquery-tokeninput.js#L854-L877
56,141
icanjs/grid-filter
src/jquery-tokeninput/jquery-tokeninput.js
populate_dropdown
function populate_dropdown (query, results) { // exclude current tokens if configured results = excludeCurrent(results); if(results && results.length) { dropdown.empty(); var dropdown_ul = $("<ul/>") .appendTo(dropdown) .mouseover(function (event) { select_dropdown_item($(event.target).closest("li")); }) .mousedown(function (event) { add_token($(event.target).closest("li").data("tokeninput")); hidden_input.change(); return false; }) .hide(); if ($(input).data("settings").resultsLimit && results.length > $(input).data("settings").resultsLimit) { results = results.slice(0, $(input).data("settings").resultsLimit); } $.each(results, function(index, value) { var this_li = $(input).data("settings").resultsFormatter(value); this_li = find_value_and_highlight_term(this_li ,value[$(input).data("settings").propertyToSearch], query); this_li = $(this_li).appendTo(dropdown_ul); if(index % 2) { this_li.addClass($(input).data("settings").classes.dropdownItem); } else { this_li.addClass($(input).data("settings").classes.dropdownItem2); } if(index === 0 && $(input).data("settings").autoSelectFirstResult) { select_dropdown_item(this_li); } $.data(this_li.get(0), "tokeninput", value); }); show_dropdown(); if($(input).data("settings").animateDropdown) { dropdown_ul.slideDown("fast"); } else { dropdown_ul.show(); } } else { if($(input).data("settings").noResultsText) { dropdown.html("<p>" + escapeHTML($(input).data("settings").noResultsText) + "</p>"); show_dropdown(); } } }
javascript
function populate_dropdown (query, results) { // exclude current tokens if configured results = excludeCurrent(results); if(results && results.length) { dropdown.empty(); var dropdown_ul = $("<ul/>") .appendTo(dropdown) .mouseover(function (event) { select_dropdown_item($(event.target).closest("li")); }) .mousedown(function (event) { add_token($(event.target).closest("li").data("tokeninput")); hidden_input.change(); return false; }) .hide(); if ($(input).data("settings").resultsLimit && results.length > $(input).data("settings").resultsLimit) { results = results.slice(0, $(input).data("settings").resultsLimit); } $.each(results, function(index, value) { var this_li = $(input).data("settings").resultsFormatter(value); this_li = find_value_and_highlight_term(this_li ,value[$(input).data("settings").propertyToSearch], query); this_li = $(this_li).appendTo(dropdown_ul); if(index % 2) { this_li.addClass($(input).data("settings").classes.dropdownItem); } else { this_li.addClass($(input).data("settings").classes.dropdownItem2); } if(index === 0 && $(input).data("settings").autoSelectFirstResult) { select_dropdown_item(this_li); } $.data(this_li.get(0), "tokeninput", value); }); show_dropdown(); if($(input).data("settings").animateDropdown) { dropdown_ul.slideDown("fast"); } else { dropdown_ul.show(); } } else { if($(input).data("settings").noResultsText) { dropdown.html("<p>" + escapeHTML($(input).data("settings").noResultsText) + "</p>"); show_dropdown(); } } }
[ "function", "populate_dropdown", "(", "query", ",", "results", ")", "{", "// exclude current tokens if configured", "results", "=", "excludeCurrent", "(", "results", ")", ";", "if", "(", "results", "&&", "results", ".", "length", ")", "{", "dropdown", ".", "empty", "(", ")", ";", "var", "dropdown_ul", "=", "$", "(", "\"<ul/>\"", ")", ".", "appendTo", "(", "dropdown", ")", ".", "mouseover", "(", "function", "(", "event", ")", "{", "select_dropdown_item", "(", "$", "(", "event", ".", "target", ")", ".", "closest", "(", "\"li\"", ")", ")", ";", "}", ")", ".", "mousedown", "(", "function", "(", "event", ")", "{", "add_token", "(", "$", "(", "event", ".", "target", ")", ".", "closest", "(", "\"li\"", ")", ".", "data", "(", "\"tokeninput\"", ")", ")", ";", "hidden_input", ".", "change", "(", ")", ";", "return", "false", ";", "}", ")", ".", "hide", "(", ")", ";", "if", "(", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "resultsLimit", "&&", "results", ".", "length", ">", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "resultsLimit", ")", "{", "results", "=", "results", ".", "slice", "(", "0", ",", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "resultsLimit", ")", ";", "}", "$", ".", "each", "(", "results", ",", "function", "(", "index", ",", "value", ")", "{", "var", "this_li", "=", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "resultsFormatter", "(", "value", ")", ";", "this_li", "=", "find_value_and_highlight_term", "(", "this_li", ",", "value", "[", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "propertyToSearch", "]", ",", "query", ")", ";", "this_li", "=", "$", "(", "this_li", ")", ".", "appendTo", "(", "dropdown_ul", ")", ";", "if", "(", "index", "%", "2", ")", "{", "this_li", ".", "addClass", "(", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "classes", ".", "dropdownItem", ")", ";", "}", "else", "{", "this_li", ".", "addClass", "(", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "classes", ".", "dropdownItem2", ")", ";", "}", "if", "(", "index", "===", "0", "&&", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "autoSelectFirstResult", ")", "{", "select_dropdown_item", "(", "this_li", ")", ";", "}", "$", ".", "data", "(", "this_li", ".", "get", "(", "0", ")", ",", "\"tokeninput\"", ",", "value", ")", ";", "}", ")", ";", "show_dropdown", "(", ")", ";", "if", "(", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "animateDropdown", ")", "{", "dropdown_ul", ".", "slideDown", "(", "\"fast\"", ")", ";", "}", "else", "{", "dropdown_ul", ".", "show", "(", ")", ";", "}", "}", "else", "{", "if", "(", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "noResultsText", ")", "{", "dropdown", ".", "html", "(", "\"<p>\"", "+", "escapeHTML", "(", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "noResultsText", ")", "+", "\"</p>\"", ")", ";", "show_dropdown", "(", ")", ";", "}", "}", "}" ]
Populate the results dropdown with some results
[ "Populate", "the", "results", "dropdown", "with", "some", "results" ]
48d9ce876cdc6ef459fcae70ac67b23229e85a5a
https://github.com/icanjs/grid-filter/blob/48d9ce876cdc6ef459fcae70ac67b23229e85a5a/src/jquery-tokeninput/jquery-tokeninput.js#L880-L934
56,142
icanjs/grid-filter
src/jquery-tokeninput/jquery-tokeninput.js
select_dropdown_item
function select_dropdown_item (item) { if(item) { if(selected_dropdown_item) { deselect_dropdown_item($(selected_dropdown_item)); } item.addClass($(input).data("settings").classes.selectedDropdownItem); selected_dropdown_item = item.get(0); } }
javascript
function select_dropdown_item (item) { if(item) { if(selected_dropdown_item) { deselect_dropdown_item($(selected_dropdown_item)); } item.addClass($(input).data("settings").classes.selectedDropdownItem); selected_dropdown_item = item.get(0); } }
[ "function", "select_dropdown_item", "(", "item", ")", "{", "if", "(", "item", ")", "{", "if", "(", "selected_dropdown_item", ")", "{", "deselect_dropdown_item", "(", "$", "(", "selected_dropdown_item", ")", ")", ";", "}", "item", ".", "addClass", "(", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "classes", ".", "selectedDropdownItem", ")", ";", "selected_dropdown_item", "=", "item", ".", "get", "(", "0", ")", ";", "}", "}" ]
Highlight an item in the results dropdown
[ "Highlight", "an", "item", "in", "the", "results", "dropdown" ]
48d9ce876cdc6ef459fcae70ac67b23229e85a5a
https://github.com/icanjs/grid-filter/blob/48d9ce876cdc6ef459fcae70ac67b23229e85a5a/src/jquery-tokeninput/jquery-tokeninput.js#L937-L946
56,143
icanjs/grid-filter
src/jquery-tokeninput/jquery-tokeninput.js
deselect_dropdown_item
function deselect_dropdown_item (item) { item.removeClass($(input).data("settings").classes.selectedDropdownItem); selected_dropdown_item = null; }
javascript
function deselect_dropdown_item (item) { item.removeClass($(input).data("settings").classes.selectedDropdownItem); selected_dropdown_item = null; }
[ "function", "deselect_dropdown_item", "(", "item", ")", "{", "item", ".", "removeClass", "(", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "classes", ".", "selectedDropdownItem", ")", ";", "selected_dropdown_item", "=", "null", ";", "}" ]
Remove highlighting from an item in the results dropdown
[ "Remove", "highlighting", "from", "an", "item", "in", "the", "results", "dropdown" ]
48d9ce876cdc6ef459fcae70ac67b23229e85a5a
https://github.com/icanjs/grid-filter/blob/48d9ce876cdc6ef459fcae70ac67b23229e85a5a/src/jquery-tokeninput/jquery-tokeninput.js#L949-L952
56,144
icanjs/grid-filter
src/jquery-tokeninput/jquery-tokeninput.js
computeURL
function computeURL() { var url = $(input).data("settings").url; if(typeof $(input).data("settings").url == 'function') { url = $(input).data("settings").url.call($(input).data("settings")); } return url; }
javascript
function computeURL() { var url = $(input).data("settings").url; if(typeof $(input).data("settings").url == 'function') { url = $(input).data("settings").url.call($(input).data("settings")); } return url; }
[ "function", "computeURL", "(", ")", "{", "var", "url", "=", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "url", ";", "if", "(", "typeof", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "url", "==", "'function'", ")", "{", "url", "=", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ".", "url", ".", "call", "(", "$", "(", "input", ")", ".", "data", "(", "\"settings\"", ")", ")", ";", "}", "return", "url", ";", "}" ]
compute the dynamic URL
[ "compute", "the", "dynamic", "URL" ]
48d9ce876cdc6ef459fcae70ac67b23229e85a5a
https://github.com/icanjs/grid-filter/blob/48d9ce876cdc6ef459fcae70ac67b23229e85a5a/src/jquery-tokeninput/jquery-tokeninput.js#L1064-L1070
56,145
shyam-dasgupta/mongo-query-builder
index.js
_matchAllFields
function _matchAllFields(fields, matchAnyRegex) { var regExp = regExps ? matchAnyRegex ? regExps.any : regExps.all : null; if (regExp) { for (var i = 0; i < fields.length; ++i) { parentBuilder.field(fields[i]).is("$regex", regExp); } } return parentBuilder; }
javascript
function _matchAllFields(fields, matchAnyRegex) { var regExp = regExps ? matchAnyRegex ? regExps.any : regExps.all : null; if (regExp) { for (var i = 0; i < fields.length; ++i) { parentBuilder.field(fields[i]).is("$regex", regExp); } } return parentBuilder; }
[ "function", "_matchAllFields", "(", "fields", ",", "matchAnyRegex", ")", "{", "var", "regExp", "=", "regExps", "?", "matchAnyRegex", "?", "regExps", ".", "any", ":", "regExps", ".", "all", ":", "null", ";", "if", "(", "regExp", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "fields", ".", "length", ";", "++", "i", ")", "{", "parentBuilder", ".", "field", "(", "fields", "[", "i", "]", ")", ".", "is", "(", "\"$regex\"", ",", "regExp", ")", ";", "}", "}", "return", "parentBuilder", ";", "}" ]
Matches the given Regular expression with all the fields. @param {Array.<string>} fields Array of document fields. @param {boolean} [matchAnyRegex=false] If true, match any of the search query tokens, else match all. @returns {QueryBuilder} the parent Builder. @private
[ "Matches", "the", "given", "Regular", "expression", "with", "all", "the", "fields", "." ]
adc7af2389aeba40d3041e81c91ffee9bd6ca68a
https://github.com/shyam-dasgupta/mongo-query-builder/blob/adc7af2389aeba40d3041e81c91ffee9bd6ca68a/index.js#L39-L47
56,146
shyam-dasgupta/mongo-query-builder
index.js
_matchAnyField
function _matchAnyField(fields, matchAnyRegex) { var regExp = regExps ? matchAnyRegex ? regExps.any : regExps.all : null; if (regExp) { var orBuilder = parentBuilder.either(); for (var i = 0; i < fields.length; ++i) { orBuilder = orBuilder.or().field(fields[i]).is("$regex", regExp); } } return parentBuilder; }
javascript
function _matchAnyField(fields, matchAnyRegex) { var regExp = regExps ? matchAnyRegex ? regExps.any : regExps.all : null; if (regExp) { var orBuilder = parentBuilder.either(); for (var i = 0; i < fields.length; ++i) { orBuilder = orBuilder.or().field(fields[i]).is("$regex", regExp); } } return parentBuilder; }
[ "function", "_matchAnyField", "(", "fields", ",", "matchAnyRegex", ")", "{", "var", "regExp", "=", "regExps", "?", "matchAnyRegex", "?", "regExps", ".", "any", ":", "regExps", ".", "all", ":", "null", ";", "if", "(", "regExp", ")", "{", "var", "orBuilder", "=", "parentBuilder", ".", "either", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "fields", ".", "length", ";", "++", "i", ")", "{", "orBuilder", "=", "orBuilder", ".", "or", "(", ")", ".", "field", "(", "fields", "[", "i", "]", ")", ".", "is", "(", "\"$regex\"", ",", "regExp", ")", ";", "}", "}", "return", "parentBuilder", ";", "}" ]
Matches the given Regular expression with at least one of the fields. @param {Array.<string>} fields Array of document fields. @param {boolean} [matchAnyRegex=false] If true, match any of the search query tokens, else match all. @returns {QueryBuilder} the parent Builder. @private
[ "Matches", "the", "given", "Regular", "expression", "with", "at", "least", "one", "of", "the", "fields", "." ]
adc7af2389aeba40d3041e81c91ffee9bd6ca68a
https://github.com/shyam-dasgupta/mongo-query-builder/blob/adc7af2389aeba40d3041e81c91ffee9bd6ca68a/index.js#L58-L67
56,147
shyam-dasgupta/mongo-query-builder
index.js
function (parentBuilder, field) { if (!dataUtils.isValidStr(field)) throw "Invalid field, should be a string: " + dataUtils.JSONstringify(field); /** * Ensures a comparison of the field with the value. * @param {string} comparator e.g. "$gt", "$gte", etc. * @param {*} value * @returns {QueryBuilder} the parent Builder. Use .andField() * to chain further with this builder. */ this.is = function (comparator, value) { return parentBuilder._compare(field, comparator, value); }; /** * Ensures that the field matches the given value. This is same * as calling matchAll([value]). * @param {*} value * @returns {QueryBuilder} the parent Builder. Use .andField() * to chain further with this builder. */ this.matches = function (value) { return parentBuilder._matchesAll(field, [value]); }; /** * Ensures that the field matches all the values. * @param {Array.<*>} values * @returns {QueryBuilder} the parent Builder. Use .andField() * to chain further with this builder. */ this.matchesAll = function (values) { return parentBuilder._matchesAll(field, values); }; /** * Ensures that the field matches at least one of the values. * @param {Array.<*>} values * @param {boolean} [addToExistingOr=false] If true, this will * be added to the existing OR list ($in), if any. * @returns {QueryBuilder} the parent Builder. Use .andField() * to chain further with this builder. */ this.matchesAny = function (values, addToExistingOr) { return parentBuilder._matchesAny(field, values, addToExistingOr); }; }
javascript
function (parentBuilder, field) { if (!dataUtils.isValidStr(field)) throw "Invalid field, should be a string: " + dataUtils.JSONstringify(field); /** * Ensures a comparison of the field with the value. * @param {string} comparator e.g. "$gt", "$gte", etc. * @param {*} value * @returns {QueryBuilder} the parent Builder. Use .andField() * to chain further with this builder. */ this.is = function (comparator, value) { return parentBuilder._compare(field, comparator, value); }; /** * Ensures that the field matches the given value. This is same * as calling matchAll([value]). * @param {*} value * @returns {QueryBuilder} the parent Builder. Use .andField() * to chain further with this builder. */ this.matches = function (value) { return parentBuilder._matchesAll(field, [value]); }; /** * Ensures that the field matches all the values. * @param {Array.<*>} values * @returns {QueryBuilder} the parent Builder. Use .andField() * to chain further with this builder. */ this.matchesAll = function (values) { return parentBuilder._matchesAll(field, values); }; /** * Ensures that the field matches at least one of the values. * @param {Array.<*>} values * @param {boolean} [addToExistingOr=false] If true, this will * be added to the existing OR list ($in), if any. * @returns {QueryBuilder} the parent Builder. Use .andField() * to chain further with this builder. */ this.matchesAny = function (values, addToExistingOr) { return parentBuilder._matchesAny(field, values, addToExistingOr); }; }
[ "function", "(", "parentBuilder", ",", "field", ")", "{", "if", "(", "!", "dataUtils", ".", "isValidStr", "(", "field", ")", ")", "throw", "\"Invalid field, should be a string: \"", "+", "dataUtils", ".", "JSONstringify", "(", "field", ")", ";", "/**\n * Ensures a comparison of the field with the value.\n * @param {string} comparator e.g. \"$gt\", \"$gte\", etc.\n * @param {*} value\n * @returns {QueryBuilder} the parent Builder. Use .andField()\n * to chain further with this builder.\n */", "this", ".", "is", "=", "function", "(", "comparator", ",", "value", ")", "{", "return", "parentBuilder", ".", "_compare", "(", "field", ",", "comparator", ",", "value", ")", ";", "}", ";", "/**\n * Ensures that the field matches the given value. This is same\n * as calling matchAll([value]).\n * @param {*} value\n * @returns {QueryBuilder} the parent Builder. Use .andField()\n * to chain further with this builder.\n */", "this", ".", "matches", "=", "function", "(", "value", ")", "{", "return", "parentBuilder", ".", "_matchesAll", "(", "field", ",", "[", "value", "]", ")", ";", "}", ";", "/**\n * Ensures that the field matches all the values.\n * @param {Array.<*>} values\n * @returns {QueryBuilder} the parent Builder. Use .andField()\n * to chain further with this builder.\n */", "this", ".", "matchesAll", "=", "function", "(", "values", ")", "{", "return", "parentBuilder", ".", "_matchesAll", "(", "field", ",", "values", ")", ";", "}", ";", "/**\n * Ensures that the field matches at least one of the values.\n * @param {Array.<*>} values\n * @param {boolean} [addToExistingOr=false] If true, this will\n * be added to the existing OR list ($in), if any.\n * @returns {QueryBuilder} the parent Builder. Use .andField()\n * to chain further with this builder.\n */", "this", ".", "matchesAny", "=", "function", "(", "values", ",", "addToExistingOr", ")", "{", "return", "parentBuilder", ".", "_matchesAny", "(", "field", ",", "values", ",", "addToExistingOr", ")", ";", "}", ";", "}" ]
This builder helps create efficient queries and expressions for document fields. @param {QueryBuilder} parentBuilder The parent query builder. @param {string} field A field in the target document. @constructor
[ "This", "builder", "helps", "create", "efficient", "queries", "and", "expressions", "for", "document", "fields", "." ]
adc7af2389aeba40d3041e81c91ffee9bd6ca68a
https://github.com/shyam-dasgupta/mongo-query-builder/blob/adc7af2389aeba40d3041e81c91ffee9bd6ca68a/index.js#L180-L226
56,148
shyam-dasgupta/mongo-query-builder
index.js
function () { var _orBuilder = this; var _queries = []; var _currentChildBuilder = new ChildQueryBuilder(_orBuilder); /** * Process the current OR entry, and continue adding to this OR * query group. * @returns {ChildQueryBuilder} A new {@link ChildQueryBuilder} * child in this OR group. */ this.or = function () { _orBuilder.flush(); return _currentChildBuilder; }; /** * Returns the array of query objects generated by this * builder. * @returns {Array.<{}>} the array of query objects generated * by this builder. */ this.flush = function () { // save current builder var q = _currentChildBuilder.build(); // only if the query is non-empty if (Object.keys(q).length) { if (!dataUtils.arrayContainsValue(_queries, q)) _queries.push(q); // renew current builder _currentChildBuilder = new ChildQueryBuilder(_orBuilder); } return _queries; }; }
javascript
function () { var _orBuilder = this; var _queries = []; var _currentChildBuilder = new ChildQueryBuilder(_orBuilder); /** * Process the current OR entry, and continue adding to this OR * query group. * @returns {ChildQueryBuilder} A new {@link ChildQueryBuilder} * child in this OR group. */ this.or = function () { _orBuilder.flush(); return _currentChildBuilder; }; /** * Returns the array of query objects generated by this * builder. * @returns {Array.<{}>} the array of query objects generated * by this builder. */ this.flush = function () { // save current builder var q = _currentChildBuilder.build(); // only if the query is non-empty if (Object.keys(q).length) { if (!dataUtils.arrayContainsValue(_queries, q)) _queries.push(q); // renew current builder _currentChildBuilder = new ChildQueryBuilder(_orBuilder); } return _queries; }; }
[ "function", "(", ")", "{", "var", "_orBuilder", "=", "this", ";", "var", "_queries", "=", "[", "]", ";", "var", "_currentChildBuilder", "=", "new", "ChildQueryBuilder", "(", "_orBuilder", ")", ";", "/**\n * Process the current OR entry, and continue adding to this OR\n * query group.\n * @returns {ChildQueryBuilder} A new {@link ChildQueryBuilder}\n * child in this OR group.\n */", "this", ".", "or", "=", "function", "(", ")", "{", "_orBuilder", ".", "flush", "(", ")", ";", "return", "_currentChildBuilder", ";", "}", ";", "/**\n * Returns the array of query objects generated by this\n * builder.\n * @returns {Array.<{}>} the array of query objects generated\n * by this builder.\n */", "this", ".", "flush", "=", "function", "(", ")", "{", "// save current builder", "var", "q", "=", "_currentChildBuilder", ".", "build", "(", ")", ";", "// only if the query is non-empty", "if", "(", "Object", ".", "keys", "(", "q", ")", ".", "length", ")", "{", "if", "(", "!", "dataUtils", ".", "arrayContainsValue", "(", "_queries", ",", "q", ")", ")", "_queries", ".", "push", "(", "q", ")", ";", "// renew current builder", "_currentChildBuilder", "=", "new", "ChildQueryBuilder", "(", "_orBuilder", ")", ";", "}", "return", "_queries", ";", "}", ";", "}" ]
This builder helps create efficient OR queries and expressions. @constructor
[ "This", "builder", "helps", "create", "efficient", "OR", "queries", "and", "expressions", "." ]
adc7af2389aeba40d3041e81c91ffee9bd6ca68a
https://github.com/shyam-dasgupta/mongo-query-builder/blob/adc7af2389aeba40d3041e81c91ffee9bd6ca68a/index.js#L232-L265
56,149
travism/solid-logger-js
lib/solid-logger.js
init
function init(configuration){ var self = { config : configuration, adapters : [], getWhenCurrentWritesDone : getWhenCurrentWritesDone }; _.each(self.config.adapters, function(adapter){ var adapterInstance; try { adapterInstance = require('./adapters/' + adapter.type).init(adapter); } catch (e) { console.log(chalk.red('Initialization Error: '), e); throw e; } adapterInstance.writeQueue = BB.resolve(); self.adapters.push(adapterInstance); }); [ 'error', 'info', 'debug', 'warn', 'trace', 'critical' ].forEach(function (type) { /** * Create a TYPE log entry * @param category Categorize your error with a user defined label * @param args Include your customized messages. This should be a comma separated list just like `console.log` */ self[type] = function () { // If we are still logging and there are messages to write if(arguments.length > 0){ var category = (arguments.length > 1 && _.isString(arguments[0])) ? arguments[0] : '', startIdx = (arguments.length > 1) ? 1 : 0; _write.call(self, type, category, Array.prototype.slice.call(arguments, startIdx)); } }; }); return self; }
javascript
function init(configuration){ var self = { config : configuration, adapters : [], getWhenCurrentWritesDone : getWhenCurrentWritesDone }; _.each(self.config.adapters, function(adapter){ var adapterInstance; try { adapterInstance = require('./adapters/' + adapter.type).init(adapter); } catch (e) { console.log(chalk.red('Initialization Error: '), e); throw e; } adapterInstance.writeQueue = BB.resolve(); self.adapters.push(adapterInstance); }); [ 'error', 'info', 'debug', 'warn', 'trace', 'critical' ].forEach(function (type) { /** * Create a TYPE log entry * @param category Categorize your error with a user defined label * @param args Include your customized messages. This should be a comma separated list just like `console.log` */ self[type] = function () { // If we are still logging and there are messages to write if(arguments.length > 0){ var category = (arguments.length > 1 && _.isString(arguments[0])) ? arguments[0] : '', startIdx = (arguments.length > 1) ? 1 : 0; _write.call(self, type, category, Array.prototype.slice.call(arguments, startIdx)); } }; }); return self; }
[ "function", "init", "(", "configuration", ")", "{", "var", "self", "=", "{", "config", ":", "configuration", ",", "adapters", ":", "[", "]", ",", "getWhenCurrentWritesDone", ":", "getWhenCurrentWritesDone", "}", ";", "_", ".", "each", "(", "self", ".", "config", ".", "adapters", ",", "function", "(", "adapter", ")", "{", "var", "adapterInstance", ";", "try", "{", "adapterInstance", "=", "require", "(", "'./adapters/'", "+", "adapter", ".", "type", ")", ".", "init", "(", "adapter", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "log", "(", "chalk", ".", "red", "(", "'Initialization Error: '", ")", ",", "e", ")", ";", "throw", "e", ";", "}", "adapterInstance", ".", "writeQueue", "=", "BB", ".", "resolve", "(", ")", ";", "self", ".", "adapters", ".", "push", "(", "adapterInstance", ")", ";", "}", ")", ";", "[", "'error'", ",", "'info'", ",", "'debug'", ",", "'warn'", ",", "'trace'", ",", "'critical'", "]", ".", "forEach", "(", "function", "(", "type", ")", "{", "/**\n * Create a TYPE log entry\n * @param category Categorize your error with a user defined label\n * @param args Include your customized messages. This should be a comma separated list just like `console.log`\n */", "self", "[", "type", "]", "=", "function", "(", ")", "{", "// If we are still logging and there are messages to write", "if", "(", "arguments", ".", "length", ">", "0", ")", "{", "var", "category", "=", "(", "arguments", ".", "length", ">", "1", "&&", "_", ".", "isString", "(", "arguments", "[", "0", "]", ")", ")", "?", "arguments", "[", "0", "]", ":", "''", ",", "startIdx", "=", "(", "arguments", ".", "length", ">", "1", ")", "?", "1", ":", "0", ";", "_write", ".", "call", "(", "self", ",", "type", ",", "category", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "startIdx", ")", ")", ";", "}", "}", ";", "}", ")", ";", "return", "self", ";", "}" ]
Public method required to load in all of the configuration info for adapters. Init initialize and reinitializes, so the list of adapters is set to empty before it runs. @param configuration Object for your adapters. @returns {logger}
[ "Public", "method", "required", "to", "load", "in", "all", "of", "the", "configuration", "info", "for", "adapters", ".", "Init", "initialize", "and", "reinitializes", "so", "the", "list", "of", "adapters", "is", "set", "to", "empty", "before", "it", "runs", "." ]
e5287dcfc680fcfa3eb449dd29bc8c92106184a9
https://github.com/travism/solid-logger-js/blob/e5287dcfc680fcfa3eb449dd29bc8c92106184a9/lib/solid-logger.js#L23-L70
56,150
travism/solid-logger-js
lib/solid-logger.js
initWithFile
function initWithFile(configPath){ var configString = fs.readFileSync(path.resolve(configPath)); this.config = JSON.parse(configString); this.init(this.config); return this; }
javascript
function initWithFile(configPath){ var configString = fs.readFileSync(path.resolve(configPath)); this.config = JSON.parse(configString); this.init(this.config); return this; }
[ "function", "initWithFile", "(", "configPath", ")", "{", "var", "configString", "=", "fs", ".", "readFileSync", "(", "path", ".", "resolve", "(", "configPath", ")", ")", ";", "this", ".", "config", "=", "JSON", ".", "parse", "(", "configString", ")", ";", "this", ".", "init", "(", "this", ".", "config", ")", ";", "return", "this", ";", "}" ]
Method that will load configuration info for your adapters from a file. Method that will load configuration info for your adapters from a file. @param configPath path to your configuration file @returns {logger}
[ "Method", "that", "will", "load", "configuration", "info", "for", "your", "adapters", "from", "a", "file", ".", "Method", "that", "will", "load", "configuration", "info", "for", "your", "adapters", "from", "a", "file", "." ]
e5287dcfc680fcfa3eb449dd29bc8c92106184a9
https://github.com/travism/solid-logger-js/blob/e5287dcfc680fcfa3eb449dd29bc8c92106184a9/lib/solid-logger.js#L78-L85
56,151
travism/solid-logger-js
lib/solid-logger.js
_write
function _write(type, category, message){ var config = this.config; this.adapters.forEach(function(adapter) { //Check configuration to see if we should continue. if(adapter.config.filter && (adapter.config.filter.indexOf(type) > -1)){ return; } //We are not filtering this out. Continue adapter.write(type, category, message); }); }
javascript
function _write(type, category, message){ var config = this.config; this.adapters.forEach(function(adapter) { //Check configuration to see if we should continue. if(adapter.config.filter && (adapter.config.filter.indexOf(type) > -1)){ return; } //We are not filtering this out. Continue adapter.write(type, category, message); }); }
[ "function", "_write", "(", "type", ",", "category", ",", "message", ")", "{", "var", "config", "=", "this", ".", "config", ";", "this", ".", "adapters", ".", "forEach", "(", "function", "(", "adapter", ")", "{", "//Check configuration to see if we should continue.", "if", "(", "adapter", ".", "config", ".", "filter", "&&", "(", "adapter", ".", "config", ".", "filter", ".", "indexOf", "(", "type", ")", ">", "-", "1", ")", ")", "{", "return", ";", "}", "//We are not filtering this out. Continue", "adapter", ".", "write", "(", "type", ",", "category", ",", "message", ")", ";", "}", ")", ";", "}" ]
Local method to load up a write 'job'. We create a tracker so that the async callbacks stay in order and then we kick off the adapterWrite method which recursively loads the adapters and write per their 'write' method. It will also load in the configuration for the adapter each time so you can have the same type of adapters with different settings. @param type error, debug, info, trace, warn @param category User definted category for grouping log entries. @param message Message to be logged.
[ "Local", "method", "to", "load", "up", "a", "write", "job", ".", "We", "create", "a", "tracker", "so", "that", "the", "async", "callbacks", "stay", "in", "order", "and", "then", "we", "kick", "off", "the", "adapterWrite", "method", "which", "recursively", "loads", "the", "adapters", "and", "write", "per", "their", "write", "method", ".", "It", "will", "also", "load", "in", "the", "configuration", "for", "the", "adapter", "each", "time", "so", "you", "can", "have", "the", "same", "type", "of", "adapters", "with", "different", "settings", "." ]
e5287dcfc680fcfa3eb449dd29bc8c92106184a9
https://github.com/travism/solid-logger-js/blob/e5287dcfc680fcfa3eb449dd29bc8c92106184a9/lib/solid-logger.js#L109-L121
56,152
CloudCoreo/gitane-windows
index.js
clone
function clone(args, baseDir, privKey, cb) { run(baseDir, privKey, "git clone " + args, cb) }
javascript
function clone(args, baseDir, privKey, cb) { run(baseDir, privKey, "git clone " + args, cb) }
[ "function", "clone", "(", "args", ",", "baseDir", ",", "privKey", ",", "cb", ")", "{", "run", "(", "baseDir", ",", "privKey", ",", "\"git clone \"", "+", "args", ",", "cb", ")", "}" ]
convenience wrapper for clone. maybe add more later.
[ "convenience", "wrapper", "for", "clone", ".", "maybe", "add", "more", "later", "." ]
4adf92f1640cc7e5c34ccc17722d0ecf409e03d7
https://github.com/CloudCoreo/gitane-windows/blob/4adf92f1640cc7e5c34ccc17722d0ecf409e03d7/index.js#L185-L187
56,153
bestander/jasmine-node-sugar
index.js
function (spec) { spec.addMatchers({ /** * Array contains all elements of another array * @param needles another array * @returns {Boolean} true/false */ toContainAll: function(needles) { var haystack = this.actual; return needles.every(function (elem) { return haystack.some(function (sackElem) { return spec.env.equals_(elem, sackElem); }); }); } }); }
javascript
function (spec) { spec.addMatchers({ /** * Array contains all elements of another array * @param needles another array * @returns {Boolean} true/false */ toContainAll: function(needles) { var haystack = this.actual; return needles.every(function (elem) { return haystack.some(function (sackElem) { return spec.env.equals_(elem, sackElem); }); }); } }); }
[ "function", "(", "spec", ")", "{", "spec", ".", "addMatchers", "(", "{", "/**\n * Array contains all elements of another array\n * @param needles another array\n * @returns {Boolean} true/false\n */", "toContainAll", ":", "function", "(", "needles", ")", "{", "var", "haystack", "=", "this", ".", "actual", ";", "return", "needles", ".", "every", "(", "function", "(", "elem", ")", "{", "return", "haystack", ".", "some", "(", "function", "(", "sackElem", ")", "{", "return", "spec", ".", "env", ".", "equals_", "(", "elem", ",", "sackElem", ")", ";", "}", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
call this in beforeEach method to add more available matchers @param spec "this" within spec
[ "call", "this", "in", "beforeEach", "method", "to", "add", "more", "available", "matchers" ]
8e49710fa63b6216ec717b4dbecd84a77eee2148
https://github.com/bestander/jasmine-node-sugar/blob/8e49710fa63b6216ec717b4dbecd84a77eee2148/index.js#L20-L36
56,154
kjirou/mocha-automatic-coffeemaker
index.js
function(data) { var filePath = data.filePath; var noExtensionFilePath = data.noExtensionFilePath; var fileName = data.fileName; var noExtensionFileName = data.noExtensionFileName; return [ "describe('" + noExtensionFilePath + "', function() {", "});", ].join('\n'); }
javascript
function(data) { var filePath = data.filePath; var noExtensionFilePath = data.noExtensionFilePath; var fileName = data.fileName; var noExtensionFileName = data.noExtensionFileName; return [ "describe('" + noExtensionFilePath + "', function() {", "});", ].join('\n'); }
[ "function", "(", "data", ")", "{", "var", "filePath", "=", "data", ".", "filePath", ";", "var", "noExtensionFilePath", "=", "data", ".", "noExtensionFilePath", ";", "var", "fileName", "=", "data", ".", "fileName", ";", "var", "noExtensionFileName", "=", "data", ".", "noExtensionFileName", ";", "return", "[", "\"describe('\"", "+", "noExtensionFilePath", "+", "\"', function() {\"", ",", "\"});\"", ",", "]", ".", "join", "(", "'\\n'", ")", ";", "}" ]
get test code template
[ "get", "test", "code", "template" ]
52db2766030bc039e9f9ffc133dbd2b8bc162085
https://github.com/kjirou/mocha-automatic-coffeemaker/blob/52db2766030bc039e9f9ffc133dbd2b8bc162085/index.js#L54-L64
56,155
75lb/reduce-extract
lib/reduce-extract.js
extract
function extract (query) { var toSplice = [] var extracted = [] return function (prev, curr, index, array) { if (prev !== extracted) { if (testValue(prev, query)) { extracted.push(prev) toSplice.push(index - 1) } } if (testValue(curr, query)) { extracted.push(curr) toSplice.push(index) } if (index === array.length - 1) { toSplice.reverse() for (var i = 0; i < toSplice.length; i++) { array.splice(toSplice[i], 1) } } return extracted } }
javascript
function extract (query) { var toSplice = [] var extracted = [] return function (prev, curr, index, array) { if (prev !== extracted) { if (testValue(prev, query)) { extracted.push(prev) toSplice.push(index - 1) } } if (testValue(curr, query)) { extracted.push(curr) toSplice.push(index) } if (index === array.length - 1) { toSplice.reverse() for (var i = 0; i < toSplice.length; i++) { array.splice(toSplice[i], 1) } } return extracted } }
[ "function", "extract", "(", "query", ")", "{", "var", "toSplice", "=", "[", "]", "var", "extracted", "=", "[", "]", "return", "function", "(", "prev", ",", "curr", ",", "index", ",", "array", ")", "{", "if", "(", "prev", "!==", "extracted", ")", "{", "if", "(", "testValue", "(", "prev", ",", "query", ")", ")", "{", "extracted", ".", "push", "(", "prev", ")", "toSplice", ".", "push", "(", "index", "-", "1", ")", "}", "}", "if", "(", "testValue", "(", "curr", ",", "query", ")", ")", "{", "extracted", ".", "push", "(", "curr", ")", "toSplice", ".", "push", "(", "index", ")", "}", "if", "(", "index", "===", "array", ".", "length", "-", "1", ")", "{", "toSplice", ".", "reverse", "(", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "toSplice", ".", "length", ";", "i", "++", ")", "{", "array", ".", "splice", "(", "toSplice", "[", "i", "]", ",", "1", ")", "}", "}", "return", "extracted", "}", "}" ]
Removes items from `array` which satisfy the query. Modifies the input array, returns the extracted. @param {Array} - the input array, modified directly @param {any} - if an item in the input array passes this test it is removed @alias module:reduce-extract @example > DJs = [ { name: "Trevor", sacked: true }, { name: "Mike", sacked: true }, { name: "Chris", sacked: false }, { name: "Alan", sacked: false } ] > a.extract(DJs, { sacked: true }) [ { name: 'Trevor', sacked: true }, { name: 'Mike', sacked: true } ] > DJs [ { name: 'Chris', sacked: false }, { name: 'Alan', sacked: false } ]
[ "Removes", "items", "from", "array", "which", "satisfy", "the", "query", ".", "Modifies", "the", "input", "array", "returns", "the", "extracted", "." ]
6482517dd0107b4adea56aa3516e586c189e44f5
https://github.com/75lb/reduce-extract/blob/6482517dd0107b4adea56aa3516e586c189e44f5/lib/reduce-extract.js#L32-L56
56,156
fresheneesz/grapetree-core
grapetreeCore.js
getNewRouteInfo
function getNewRouteInfo(that, newRoutePath, path, pathToEmit) { var indexes = getDivergenceIndexes(that.currentPath, path, newRoutePath) if(indexes === undefined) { return undefined } var routeDivergenceIndex = indexes.routeIndex var pathDivergenceIndex = indexes.pathIndex var lastRoute = newRoutePath[routeDivergenceIndex-1].route var newPathSegment = path.slice(pathDivergenceIndex) // routing var newRoutes = traverseRoute(that, lastRoute, newPathSegment, pathDivergenceIndex) if(newRoutes === undefined) { var pathAdditions = [] for(var n=routeDivergenceIndex-1; n>=0; n--) { // go in reverse and take the closest default handler if(that.currentRoutes[n].route.defaultHandler !== undefined) { var defaultHandler = that.currentRoutes[n].route.defaultHandler break; } else { pathAdditions = that.currentRoutes[n].route.pathSegment.concat(pathAdditions) } } if(defaultHandler !== undefined) { var handlerParameters = [getPathSegementToOutput(that.transform, pathAdditions.concat(newPathSegment))] var subroute = new Route(newPathSegment, that.transform, true) defaultHandler.apply(subroute, handlerParameters) var pathIndexEnd = pathDivergenceIndex+newPathSegment.length if(newPathSegment.length !== 0) { pathIndexEnd-- } newRoutes = [{route: subroute, pathIndexes: {start:pathDivergenceIndex, end: pathIndexEnd}}] } else { throw new Error("No route matched path: "+JSON.stringify(getPathToOutput(that.transform, path))) } } else { var newRouteInfo = getRedirectRoute(that, path, newRoutePath, newRoutes, routeDivergenceIndex) if(newRouteInfo !== false) { return newRouteInfo } } return {newRoutes: newRoutes, divergenceIndex: routeDivergenceIndex, pathToEmit: pathToEmit} }
javascript
function getNewRouteInfo(that, newRoutePath, path, pathToEmit) { var indexes = getDivergenceIndexes(that.currentPath, path, newRoutePath) if(indexes === undefined) { return undefined } var routeDivergenceIndex = indexes.routeIndex var pathDivergenceIndex = indexes.pathIndex var lastRoute = newRoutePath[routeDivergenceIndex-1].route var newPathSegment = path.slice(pathDivergenceIndex) // routing var newRoutes = traverseRoute(that, lastRoute, newPathSegment, pathDivergenceIndex) if(newRoutes === undefined) { var pathAdditions = [] for(var n=routeDivergenceIndex-1; n>=0; n--) { // go in reverse and take the closest default handler if(that.currentRoutes[n].route.defaultHandler !== undefined) { var defaultHandler = that.currentRoutes[n].route.defaultHandler break; } else { pathAdditions = that.currentRoutes[n].route.pathSegment.concat(pathAdditions) } } if(defaultHandler !== undefined) { var handlerParameters = [getPathSegementToOutput(that.transform, pathAdditions.concat(newPathSegment))] var subroute = new Route(newPathSegment, that.transform, true) defaultHandler.apply(subroute, handlerParameters) var pathIndexEnd = pathDivergenceIndex+newPathSegment.length if(newPathSegment.length !== 0) { pathIndexEnd-- } newRoutes = [{route: subroute, pathIndexes: {start:pathDivergenceIndex, end: pathIndexEnd}}] } else { throw new Error("No route matched path: "+JSON.stringify(getPathToOutput(that.transform, path))) } } else { var newRouteInfo = getRedirectRoute(that, path, newRoutePath, newRoutes, routeDivergenceIndex) if(newRouteInfo !== false) { return newRouteInfo } } return {newRoutes: newRoutes, divergenceIndex: routeDivergenceIndex, pathToEmit: pathToEmit} }
[ "function", "getNewRouteInfo", "(", "that", ",", "newRoutePath", ",", "path", ",", "pathToEmit", ")", "{", "var", "indexes", "=", "getDivergenceIndexes", "(", "that", ".", "currentPath", ",", "path", ",", "newRoutePath", ")", "if", "(", "indexes", "===", "undefined", ")", "{", "return", "undefined", "}", "var", "routeDivergenceIndex", "=", "indexes", ".", "routeIndex", "var", "pathDivergenceIndex", "=", "indexes", ".", "pathIndex", "var", "lastRoute", "=", "newRoutePath", "[", "routeDivergenceIndex", "-", "1", "]", ".", "route", "var", "newPathSegment", "=", "path", ".", "slice", "(", "pathDivergenceIndex", ")", "// routing", "var", "newRoutes", "=", "traverseRoute", "(", "that", ",", "lastRoute", ",", "newPathSegment", ",", "pathDivergenceIndex", ")", "if", "(", "newRoutes", "===", "undefined", ")", "{", "var", "pathAdditions", "=", "[", "]", "for", "(", "var", "n", "=", "routeDivergenceIndex", "-", "1", ";", "n", ">=", "0", ";", "n", "--", ")", "{", "// go in reverse and take the closest default handler", "if", "(", "that", ".", "currentRoutes", "[", "n", "]", ".", "route", ".", "defaultHandler", "!==", "undefined", ")", "{", "var", "defaultHandler", "=", "that", ".", "currentRoutes", "[", "n", "]", ".", "route", ".", "defaultHandler", "break", ";", "}", "else", "{", "pathAdditions", "=", "that", ".", "currentRoutes", "[", "n", "]", ".", "route", ".", "pathSegment", ".", "concat", "(", "pathAdditions", ")", "}", "}", "if", "(", "defaultHandler", "!==", "undefined", ")", "{", "var", "handlerParameters", "=", "[", "getPathSegementToOutput", "(", "that", ".", "transform", ",", "pathAdditions", ".", "concat", "(", "newPathSegment", ")", ")", "]", "var", "subroute", "=", "new", "Route", "(", "newPathSegment", ",", "that", ".", "transform", ",", "true", ")", "defaultHandler", ".", "apply", "(", "subroute", ",", "handlerParameters", ")", "var", "pathIndexEnd", "=", "pathDivergenceIndex", "+", "newPathSegment", ".", "length", "if", "(", "newPathSegment", ".", "length", "!==", "0", ")", "{", "pathIndexEnd", "--", "}", "newRoutes", "=", "[", "{", "route", ":", "subroute", ",", "pathIndexes", ":", "{", "start", ":", "pathDivergenceIndex", ",", "end", ":", "pathIndexEnd", "}", "}", "]", "}", "else", "{", "throw", "new", "Error", "(", "\"No route matched path: \"", "+", "JSON", ".", "stringify", "(", "getPathToOutput", "(", "that", ".", "transform", ",", "path", ")", ")", ")", "}", "}", "else", "{", "var", "newRouteInfo", "=", "getRedirectRoute", "(", "that", ",", "path", ",", "newRoutePath", ",", "newRoutes", ",", "routeDivergenceIndex", ")", "if", "(", "newRouteInfo", "!==", "false", ")", "{", "return", "newRouteInfo", "}", "}", "return", "{", "newRoutes", ":", "newRoutes", ",", "divergenceIndex", ":", "routeDivergenceIndex", ",", "pathToEmit", ":", "pathToEmit", "}", "}" ]
returns an object with the properties newRoutes - an array of Route objects; the list of new routes to enter divergenceIndex - the route divergence index pathToEmit - the path to use when emitting the 'change' event or undefined - if the paths are the same
[ "returns", "an", "object", "with", "the", "properties", "newRoutes", "-", "an", "array", "of", "Route", "objects", ";", "the", "list", "of", "new", "routes", "to", "enter", "divergenceIndex", "-", "the", "route", "divergence", "index", "pathToEmit", "-", "the", "path", "to", "use", "when", "emitting", "the", "change", "event", "or", "undefined", "-", "if", "the", "paths", "are", "the", "same" ]
3dbe622ba56cb1d227e104dd68d4787ae9aaf201
https://github.com/fresheneesz/grapetree-core/blob/3dbe622ba56cb1d227e104dd68d4787ae9aaf201/grapetreeCore.js#L136-L182
56,157
fresheneesz/grapetree-core
grapetreeCore.js
loopThroughHandlers
function loopThroughHandlers(lastFuture, n) { if(n < routes.length) { var route = routes[n].route var handler = route[handlerProperty] if(direction === -1) { var originalIndexFromCurrentRoutes = currentRoutes.length - n - 1 var distance = routes.length - n // divergenceDistance } else { var originalIndexFromCurrentRoutes = routeVergenceIndex+n var distance = undefined // no more leafDistance: routes.length - n - 1 // leafDistance } return lastFuture.then(function() { if(handler !== undefined) { if(originalIndexFromCurrentRoutes > 0) { var parentRoute = currentRoutes[originalIndexFromCurrentRoutes-1] var lastValue = parentRoute.route.lastValue } var nextFuture = handler.call(route, lastValue, distance) if(nextFuture !== undefined) { nextFuture.then(function(value) { route.lastValue = value }) // no done because nextFuture's errors are handled elsewhere } } if(nextFuture === undefined) { nextFuture = Future(undefined) } return loopThroughHandlers(nextFuture, n+1) }).catch(function(e){ return handleError(currentRoutes, originalIndexFromCurrentRoutes, type, e, []).then(function() { if(direction === 1) { return Future(n + routeVergenceIndex) } else { // -1 exit handlers return loopThroughHandlers(Future(undefined), n+1) // continue executing the parent exit handlers } }) }) } else { return lastFuture.then(function() { return Future(n + routeVergenceIndex) }).catch(function(e) { throw e // propagate the error not the value }) } }
javascript
function loopThroughHandlers(lastFuture, n) { if(n < routes.length) { var route = routes[n].route var handler = route[handlerProperty] if(direction === -1) { var originalIndexFromCurrentRoutes = currentRoutes.length - n - 1 var distance = routes.length - n // divergenceDistance } else { var originalIndexFromCurrentRoutes = routeVergenceIndex+n var distance = undefined // no more leafDistance: routes.length - n - 1 // leafDistance } return lastFuture.then(function() { if(handler !== undefined) { if(originalIndexFromCurrentRoutes > 0) { var parentRoute = currentRoutes[originalIndexFromCurrentRoutes-1] var lastValue = parentRoute.route.lastValue } var nextFuture = handler.call(route, lastValue, distance) if(nextFuture !== undefined) { nextFuture.then(function(value) { route.lastValue = value }) // no done because nextFuture's errors are handled elsewhere } } if(nextFuture === undefined) { nextFuture = Future(undefined) } return loopThroughHandlers(nextFuture, n+1) }).catch(function(e){ return handleError(currentRoutes, originalIndexFromCurrentRoutes, type, e, []).then(function() { if(direction === 1) { return Future(n + routeVergenceIndex) } else { // -1 exit handlers return loopThroughHandlers(Future(undefined), n+1) // continue executing the parent exit handlers } }) }) } else { return lastFuture.then(function() { return Future(n + routeVergenceIndex) }).catch(function(e) { throw e // propagate the error not the value }) } }
[ "function", "loopThroughHandlers", "(", "lastFuture", ",", "n", ")", "{", "if", "(", "n", "<", "routes", ".", "length", ")", "{", "var", "route", "=", "routes", "[", "n", "]", ".", "route", "var", "handler", "=", "route", "[", "handlerProperty", "]", "if", "(", "direction", "===", "-", "1", ")", "{", "var", "originalIndexFromCurrentRoutes", "=", "currentRoutes", ".", "length", "-", "n", "-", "1", "var", "distance", "=", "routes", ".", "length", "-", "n", "// divergenceDistance", "}", "else", "{", "var", "originalIndexFromCurrentRoutes", "=", "routeVergenceIndex", "+", "n", "var", "distance", "=", "undefined", "// no more leafDistance: routes.length - n - 1 // leafDistance", "}", "return", "lastFuture", ".", "then", "(", "function", "(", ")", "{", "if", "(", "handler", "!==", "undefined", ")", "{", "if", "(", "originalIndexFromCurrentRoutes", ">", "0", ")", "{", "var", "parentRoute", "=", "currentRoutes", "[", "originalIndexFromCurrentRoutes", "-", "1", "]", "var", "lastValue", "=", "parentRoute", ".", "route", ".", "lastValue", "}", "var", "nextFuture", "=", "handler", ".", "call", "(", "route", ",", "lastValue", ",", "distance", ")", "if", "(", "nextFuture", "!==", "undefined", ")", "{", "nextFuture", ".", "then", "(", "function", "(", "value", ")", "{", "route", ".", "lastValue", "=", "value", "}", ")", "// no done because nextFuture's errors are handled elsewhere", "}", "}", "if", "(", "nextFuture", "===", "undefined", ")", "{", "nextFuture", "=", "Future", "(", "undefined", ")", "}", "return", "loopThroughHandlers", "(", "nextFuture", ",", "n", "+", "1", ")", "}", ")", ".", "catch", "(", "function", "(", "e", ")", "{", "return", "handleError", "(", "currentRoutes", ",", "originalIndexFromCurrentRoutes", ",", "type", ",", "e", ",", "[", "]", ")", ".", "then", "(", "function", "(", ")", "{", "if", "(", "direction", "===", "1", ")", "{", "return", "Future", "(", "n", "+", "routeVergenceIndex", ")", "}", "else", "{", "// -1 exit handlers", "return", "loopThroughHandlers", "(", "Future", "(", "undefined", ")", ",", "n", "+", "1", ")", "// continue executing the parent exit handlers", "}", "}", ")", "}", ")", "}", "else", "{", "return", "lastFuture", ".", "then", "(", "function", "(", ")", "{", "return", "Future", "(", "n", "+", "routeVergenceIndex", ")", "}", ")", ".", "catch", "(", "function", "(", "e", ")", "{", "throw", "e", "// propagate the error not the value", "}", ")", "}", "}" ]
returns a future that resolves to the maximum depth that succeeded
[ "returns", "a", "future", "that", "resolves", "to", "the", "maximum", "depth", "that", "succeeded" ]
3dbe622ba56cb1d227e104dd68d4787ae9aaf201
https://github.com/fresheneesz/grapetree-core/blob/3dbe622ba56cb1d227e104dd68d4787ae9aaf201/grapetreeCore.js#L413-L463
56,158
feedm3/hypem-resolver
hypem-resolver.js
urlToId
function urlToId(hypemUrl) { var trimmedUrl = _.trim(hypemUrl); if (_.startsWith(trimmedUrl, HYPEM_TRACK_URL)) { var parsedUrl = url.parse(hypemUrl); var pathname = parsedUrl.pathname; // '/trach/31jfi/...' var hypemId = pathname.split("/")[2]; return hypemId; } return ""; }
javascript
function urlToId(hypemUrl) { var trimmedUrl = _.trim(hypemUrl); if (_.startsWith(trimmedUrl, HYPEM_TRACK_URL)) { var parsedUrl = url.parse(hypemUrl); var pathname = parsedUrl.pathname; // '/trach/31jfi/...' var hypemId = pathname.split("/")[2]; return hypemId; } return ""; }
[ "function", "urlToId", "(", "hypemUrl", ")", "{", "var", "trimmedUrl", "=", "_", ".", "trim", "(", "hypemUrl", ")", ";", "if", "(", "_", ".", "startsWith", "(", "trimmedUrl", ",", "HYPEM_TRACK_URL", ")", ")", "{", "var", "parsedUrl", "=", "url", ".", "parse", "(", "hypemUrl", ")", ";", "var", "pathname", "=", "parsedUrl", ".", "pathname", ";", "// '/trach/31jfi/...'", "var", "hypemId", "=", "pathname", ".", "split", "(", "\"/\"", ")", "[", "2", "]", ";", "return", "hypemId", ";", "}", "return", "\"\"", ";", "}" ]
Extract the hypem id from a song's url. @param {string} hypemUrl the url to extract the id @returns {string} the id or "" if no id was found
[ "Extract", "the", "hypem", "id", "from", "a", "song", "s", "url", "." ]
e20e0cf1ba93eac47f830c4b8693f13c4ca2588b
https://github.com/feedm3/hypem-resolver/blob/e20e0cf1ba93eac47f830c4b8693f13c4ca2588b/hypem-resolver.js#L27-L36
56,159
feedm3/hypem-resolver
hypem-resolver.js
getById
function getById(hypemId, callback) { var options = { method: 'HEAD', url: HYPEM_GO_URL + hypemId, followRedirect: false, timeout: FIVE_SECONDS_IN_MILLIS }; request(options, function (error, response) { if (error || response.statusCode !== 302) { callback(error, null); return; } var songUrl = response.headers.location; if (isSoundcloudUrl(songUrl)) { var soundcloudUrl = getNormalizedSoundcloudUrl(songUrl); callback(null, soundcloudUrl); } else { requestHypemKey(hypemId, function (error, hypemKey) { if (error) { callback(error, null); return; } requestMp3Url(hypemId, hypemKey, callback); }); } }); }
javascript
function getById(hypemId, callback) { var options = { method: 'HEAD', url: HYPEM_GO_URL + hypemId, followRedirect: false, timeout: FIVE_SECONDS_IN_MILLIS }; request(options, function (error, response) { if (error || response.statusCode !== 302) { callback(error, null); return; } var songUrl = response.headers.location; if (isSoundcloudUrl(songUrl)) { var soundcloudUrl = getNormalizedSoundcloudUrl(songUrl); callback(null, soundcloudUrl); } else { requestHypemKey(hypemId, function (error, hypemKey) { if (error) { callback(error, null); return; } requestMp3Url(hypemId, hypemKey, callback); }); } }); }
[ "function", "getById", "(", "hypemId", ",", "callback", ")", "{", "var", "options", "=", "{", "method", ":", "'HEAD'", ",", "url", ":", "HYPEM_GO_URL", "+", "hypemId", ",", "followRedirect", ":", "false", ",", "timeout", ":", "FIVE_SECONDS_IN_MILLIS", "}", ";", "request", "(", "options", ",", "function", "(", "error", ",", "response", ")", "{", "if", "(", "error", "||", "response", ".", "statusCode", "!==", "302", ")", "{", "callback", "(", "error", ",", "null", ")", ";", "return", ";", "}", "var", "songUrl", "=", "response", ".", "headers", ".", "location", ";", "if", "(", "isSoundcloudUrl", "(", "songUrl", ")", ")", "{", "var", "soundcloudUrl", "=", "getNormalizedSoundcloudUrl", "(", "songUrl", ")", ";", "callback", "(", "null", ",", "soundcloudUrl", ")", ";", "}", "else", "{", "requestHypemKey", "(", "hypemId", ",", "function", "(", "error", ",", "hypemKey", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ",", "null", ")", ";", "return", ";", "}", "requestMp3Url", "(", "hypemId", ",", "hypemKey", ",", "callback", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
Get the soundcloud or mp3 url from a song's id. @param hypemId {string} the id of the song @param {Function}[callback] callback function @param {Error} callback.err null if no error occurred @param {string} callback.url the soundcloud or mp3 url
[ "Get", "the", "soundcloud", "or", "mp3", "url", "from", "a", "song", "s", "id", "." ]
e20e0cf1ba93eac47f830c4b8693f13c4ca2588b
https://github.com/feedm3/hypem-resolver/blob/e20e0cf1ba93eac47f830c4b8693f13c4ca2588b/hypem-resolver.js#L46-L73
56,160
feedm3/hypem-resolver
hypem-resolver.js
requestHypemKey
function requestHypemKey(hypemId, callback) { var options = { method: "GET", url: HYPEM_TRACK_URL + hypemId, headers: {"Cookie": COOKIE}, timeout: FIVE_SECONDS_IN_MILLIS }; request(options, function (error, response) { if (!error && response.statusCode === 200) { var bodyLines = response.body.split('\n'); _.forIn(bodyLines, function (bodyLine) { if (bodyLine.indexOf('key') !== -1) { // first hit should be the correct one // fix if hypem changes that try { var key = JSON.parse(bodyLine.replace('</script>', '')).tracks[0].key; callback(null, key); } catch (error) { // if an error happen here do nothing and parse // the rest of the document } } }); } else { callback(new Error("Nothing found: " + options.url), null); } }); }
javascript
function requestHypemKey(hypemId, callback) { var options = { method: "GET", url: HYPEM_TRACK_URL + hypemId, headers: {"Cookie": COOKIE}, timeout: FIVE_SECONDS_IN_MILLIS }; request(options, function (error, response) { if (!error && response.statusCode === 200) { var bodyLines = response.body.split('\n'); _.forIn(bodyLines, function (bodyLine) { if (bodyLine.indexOf('key') !== -1) { // first hit should be the correct one // fix if hypem changes that try { var key = JSON.parse(bodyLine.replace('</script>', '')).tracks[0].key; callback(null, key); } catch (error) { // if an error happen here do nothing and parse // the rest of the document } } }); } else { callback(new Error("Nothing found: " + options.url), null); } }); }
[ "function", "requestHypemKey", "(", "hypemId", ",", "callback", ")", "{", "var", "options", "=", "{", "method", ":", "\"GET\"", ",", "url", ":", "HYPEM_TRACK_URL", "+", "hypemId", ",", "headers", ":", "{", "\"Cookie\"", ":", "COOKIE", "}", ",", "timeout", ":", "FIVE_SECONDS_IN_MILLIS", "}", ";", "request", "(", "options", ",", "function", "(", "error", ",", "response", ")", "{", "if", "(", "!", "error", "&&", "response", ".", "statusCode", "===", "200", ")", "{", "var", "bodyLines", "=", "response", ".", "body", ".", "split", "(", "'\\n'", ")", ";", "_", ".", "forIn", "(", "bodyLines", ",", "function", "(", "bodyLine", ")", "{", "if", "(", "bodyLine", ".", "indexOf", "(", "'key'", ")", "!==", "-", "1", ")", "{", "// first hit should be the correct one", "// fix if hypem changes that", "try", "{", "var", "key", "=", "JSON", ".", "parse", "(", "bodyLine", ".", "replace", "(", "'</script>'", ",", "''", ")", ")", ".", "tracks", "[", "0", "]", ".", "key", ";", "callback", "(", "null", ",", "key", ")", ";", "}", "catch", "(", "error", ")", "{", "// if an error happen here do nothing and parse", "// the rest of the document", "}", "}", "}", ")", ";", "}", "else", "{", "callback", "(", "new", "Error", "(", "\"Nothing found: \"", "+", "options", ".", "url", ")", ",", "null", ")", ";", "}", "}", ")", ";", "}" ]
Get the key for hypem. The key is necessary to request the hypem serve url which gives us the mp3 url. We dont need a key if the song is hosted on soundcloud. @private @param {string} hypemId the id of the song @param {Function}[callback] callback function @param {Error} callback.err null if no error occurred @param {string} callback.url the key to request a hypem song url
[ "Get", "the", "key", "for", "hypem", ".", "The", "key", "is", "necessary", "to", "request", "the", "hypem", "serve", "url", "which", "gives", "us", "the", "mp3", "url", ".", "We", "dont", "need", "a", "key", "if", "the", "song", "is", "hosted", "on", "soundcloud", "." ]
e20e0cf1ba93eac47f830c4b8693f13c4ca2588b
https://github.com/feedm3/hypem-resolver/blob/e20e0cf1ba93eac47f830c4b8693f13c4ca2588b/hypem-resolver.js#L91-L119
56,161
feedm3/hypem-resolver
hypem-resolver.js
requestMp3Url
function requestMp3Url(hypemId, hypemKey, callback) { var options = { method: "GET", url: HYPEM_SERVE_URL + hypemId + "/" + hypemKey, headers: {"Cookie": COOKIE}, timeout: FIVE_SECONDS_IN_MILLIS }; request(options, function (error, response) { if (!error && response.statusCode === 200) { try { // the request got a json from hypem // where the link to the mp3 file is saved var jsonBody = JSON.parse(response.body); var mp3Url = jsonBody.url; callback(null, mp3Url); } catch (error) { callback(error, null); } } else { callback(new Error("Nothing found: " + options.url), null); } }); }
javascript
function requestMp3Url(hypemId, hypemKey, callback) { var options = { method: "GET", url: HYPEM_SERVE_URL + hypemId + "/" + hypemKey, headers: {"Cookie": COOKIE}, timeout: FIVE_SECONDS_IN_MILLIS }; request(options, function (error, response) { if (!error && response.statusCode === 200) { try { // the request got a json from hypem // where the link to the mp3 file is saved var jsonBody = JSON.parse(response.body); var mp3Url = jsonBody.url; callback(null, mp3Url); } catch (error) { callback(error, null); } } else { callback(new Error("Nothing found: " + options.url), null); } }); }
[ "function", "requestMp3Url", "(", "hypemId", ",", "hypemKey", ",", "callback", ")", "{", "var", "options", "=", "{", "method", ":", "\"GET\"", ",", "url", ":", "HYPEM_SERVE_URL", "+", "hypemId", "+", "\"/\"", "+", "hypemKey", ",", "headers", ":", "{", "\"Cookie\"", ":", "COOKIE", "}", ",", "timeout", ":", "FIVE_SECONDS_IN_MILLIS", "}", ";", "request", "(", "options", ",", "function", "(", "error", ",", "response", ")", "{", "if", "(", "!", "error", "&&", "response", ".", "statusCode", "===", "200", ")", "{", "try", "{", "// the request got a json from hypem", "// where the link to the mp3 file is saved", "var", "jsonBody", "=", "JSON", ".", "parse", "(", "response", ".", "body", ")", ";", "var", "mp3Url", "=", "jsonBody", ".", "url", ";", "callback", "(", "null", ",", "mp3Url", ")", ";", "}", "catch", "(", "error", ")", "{", "callback", "(", "error", ",", "null", ")", ";", "}", "}", "else", "{", "callback", "(", "new", "Error", "(", "\"Nothing found: \"", "+", "options", ".", "url", ")", ",", "null", ")", ";", "}", "}", ")", ";", "}" ]
Get the mp3 url of the song's id with a given key. @private @param {string} hypemId the id of the song @param {string} hypemKey the key to make the request succeed @param {Function}[callback] callback function @param {Error} callback.err null if no error occurred @param {string} callback.url the mp3 url
[ "Get", "the", "mp3", "url", "of", "the", "song", "s", "id", "with", "a", "given", "key", "." ]
e20e0cf1ba93eac47f830c4b8693f13c4ca2588b
https://github.com/feedm3/hypem-resolver/blob/e20e0cf1ba93eac47f830c4b8693f13c4ca2588b/hypem-resolver.js#L131-L154
56,162
feedm3/hypem-resolver
hypem-resolver.js
getNormalizedSoundcloudUrl
function getNormalizedSoundcloudUrl(soundcloudUrl) { var parsedUrl = url.parse(soundcloudUrl); var protocol = parsedUrl.protocol; var host = parsedUrl.host; var pathname = parsedUrl.pathname; var splitHostname = pathname.split('/'); var normalizedUrl = protocol + "//" + host + "/" + splitHostname[1] + "/" + splitHostname[2]; return normalizedUrl; }
javascript
function getNormalizedSoundcloudUrl(soundcloudUrl) { var parsedUrl = url.parse(soundcloudUrl); var protocol = parsedUrl.protocol; var host = parsedUrl.host; var pathname = parsedUrl.pathname; var splitHostname = pathname.split('/'); var normalizedUrl = protocol + "//" + host + "/" + splitHostname[1] + "/" + splitHostname[2]; return normalizedUrl; }
[ "function", "getNormalizedSoundcloudUrl", "(", "soundcloudUrl", ")", "{", "var", "parsedUrl", "=", "url", ".", "parse", "(", "soundcloudUrl", ")", ";", "var", "protocol", "=", "parsedUrl", ".", "protocol", ";", "var", "host", "=", "parsedUrl", ".", "host", ";", "var", "pathname", "=", "parsedUrl", ".", "pathname", ";", "var", "splitHostname", "=", "pathname", ".", "split", "(", "'/'", ")", ";", "var", "normalizedUrl", "=", "protocol", "+", "\"//\"", "+", "host", "+", "\"/\"", "+", "splitHostname", "[", "1", "]", "+", "\"/\"", "+", "splitHostname", "[", "2", "]", ";", "return", "normalizedUrl", ";", "}" ]
Get the normalized soundcloud url. This means that every parameter or path which is not necessary gets removed. @private @param {string} soundcloudUrl the url to normalize @returns {string} the normalized soundcloud url
[ "Get", "the", "normalized", "soundcloud", "url", ".", "This", "means", "that", "every", "parameter", "or", "path", "which", "is", "not", "necessary", "gets", "removed", "." ]
e20e0cf1ba93eac47f830c4b8693f13c4ca2588b
https://github.com/feedm3/hypem-resolver/blob/e20e0cf1ba93eac47f830c4b8693f13c4ca2588b/hypem-resolver.js#L176-L184
56,163
mrself/ya-del
del.js
function(options) { this.DelOptions = $.extend({}, defaults, this.DelOptions, options); this.dName = this.DelOptions.dName || this._name; this.selector = this.selector || '.' + this.dName; this.namespace = this.DelOptions.namespace || this.dName; this.initEl(); }
javascript
function(options) { this.DelOptions = $.extend({}, defaults, this.DelOptions, options); this.dName = this.DelOptions.dName || this._name; this.selector = this.selector || '.' + this.dName; this.namespace = this.DelOptions.namespace || this.dName; this.initEl(); }
[ "function", "(", "options", ")", "{", "this", ".", "DelOptions", "=", "$", ".", "extend", "(", "{", "}", ",", "defaults", ",", "this", ".", "DelOptions", ",", "options", ")", ";", "this", ".", "dName", "=", "this", ".", "DelOptions", ".", "dName", "||", "this", ".", "_name", ";", "this", ".", "selector", "=", "this", ".", "selector", "||", "'.'", "+", "this", ".", "dName", ";", "this", ".", "namespace", "=", "this", ".", "DelOptions", ".", "namespace", "||", "this", ".", "dName", ";", "this", ".", "initEl", "(", ")", ";", "}" ]
Init del module @param {Object} options @param {String} [options.dName] @param {String} [options.namespace] Namespace @param {jQuery|DOMElement} [options.$el]
[ "Init", "del", "module" ]
11f8bff925f4df385a79e74f5d53830b20447b17
https://github.com/mrself/ya-del/blob/11f8bff925f4df385a79e74f5d53830b20447b17/del.js#L23-L29
56,164
mrself/ya-del
del.js
function(el) { return (el instanceof $ ? el : $(el)).find(this.makeSelector.apply(this, [].slice.call(arguments, 1))); }
javascript
function(el) { return (el instanceof $ ? el : $(el)).find(this.makeSelector.apply(this, [].slice.call(arguments, 1))); }
[ "function", "(", "el", ")", "{", "return", "(", "el", "instanceof", "$", "?", "el", ":", "$", "(", "el", ")", ")", ".", "find", "(", "this", ".", "makeSelector", ".", "apply", "(", "this", ",", "[", "]", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ")", ")", ";", "}" ]
Find element in other el @param {jQuery|string|DOMElement} el el to find in @param {string|array} element name @return {jQuery}
[ "Find", "element", "in", "other", "el" ]
11f8bff925f4df385a79e74f5d53830b20447b17
https://github.com/mrself/ya-del/blob/11f8bff925f4df385a79e74f5d53830b20447b17/del.js#L79-L81
56,165
gabrielcsapo/krayon
util.js
parse
function parse (code) { Object.keys(syntax).forEach((s) => { code = code.replace(syntax[s], (_, m) => { // ensure if the regex only matches part of the string that we keep the leftover let leftOver = _.replace(m, '') // encode the string and class let parsed = `{#${s}#${encode(m)}#}` if (s === 'function' && leftOver) { // we want to parse sub commands and the easiest way to do that is to // run over the leftOver portion of the function call with the same regex let startingParenthesis = leftOver.indexOf('(') let endingParenthesis = leftOver.lastIndexOf(')') let endingComma = leftOver.lastIndexOf(';') // since we don't want to create a new string for every operation // we can simply walk the string and replace the character that needs it let subFunction = leftOver.replace(/./g, (c, i) => { // we can define a waterfall case that only replaces the three positions with nothing // leaving the other characters in their place switch (i) { case startingParenthesis: case endingParenthesis: case endingComma: return '' default: return c } }) leftOver = `(${parse(subFunction)})${endingComma > -1 ? ';' : ''}` } return parsed + leftOver }) }) return code }
javascript
function parse (code) { Object.keys(syntax).forEach((s) => { code = code.replace(syntax[s], (_, m) => { // ensure if the regex only matches part of the string that we keep the leftover let leftOver = _.replace(m, '') // encode the string and class let parsed = `{#${s}#${encode(m)}#}` if (s === 'function' && leftOver) { // we want to parse sub commands and the easiest way to do that is to // run over the leftOver portion of the function call with the same regex let startingParenthesis = leftOver.indexOf('(') let endingParenthesis = leftOver.lastIndexOf(')') let endingComma = leftOver.lastIndexOf(';') // since we don't want to create a new string for every operation // we can simply walk the string and replace the character that needs it let subFunction = leftOver.replace(/./g, (c, i) => { // we can define a waterfall case that only replaces the three positions with nothing // leaving the other characters in their place switch (i) { case startingParenthesis: case endingParenthesis: case endingComma: return '' default: return c } }) leftOver = `(${parse(subFunction)})${endingComma > -1 ? ';' : ''}` } return parsed + leftOver }) }) return code }
[ "function", "parse", "(", "code", ")", "{", "Object", ".", "keys", "(", "syntax", ")", ".", "forEach", "(", "(", "s", ")", "=>", "{", "code", "=", "code", ".", "replace", "(", "syntax", "[", "s", "]", ",", "(", "_", ",", "m", ")", "=>", "{", "// ensure if the regex only matches part of the string that we keep the leftover", "let", "leftOver", "=", "_", ".", "replace", "(", "m", ",", "''", ")", "// encode the string and class", "let", "parsed", "=", "`", "${", "s", "}", "${", "encode", "(", "m", ")", "}", "`", "if", "(", "s", "===", "'function'", "&&", "leftOver", ")", "{", "// we want to parse sub commands and the easiest way to do that is to", "// run over the leftOver portion of the function call with the same regex", "let", "startingParenthesis", "=", "leftOver", ".", "indexOf", "(", "'('", ")", "let", "endingParenthesis", "=", "leftOver", ".", "lastIndexOf", "(", "')'", ")", "let", "endingComma", "=", "leftOver", ".", "lastIndexOf", "(", "';'", ")", "// since we don't want to create a new string for every operation", "// we can simply walk the string and replace the character that needs it", "let", "subFunction", "=", "leftOver", ".", "replace", "(", "/", ".", "/", "g", ",", "(", "c", ",", "i", ")", "=>", "{", "// we can define a waterfall case that only replaces the three positions with nothing", "// leaving the other characters in their place", "switch", "(", "i", ")", "{", "case", "startingParenthesis", ":", "case", "endingParenthesis", ":", "case", "endingComma", ":", "return", "''", "default", ":", "return", "c", "}", "}", ")", "leftOver", "=", "`", "${", "parse", "(", "subFunction", ")", "}", "${", "endingComma", ">", "-", "1", "?", "';'", ":", "''", "}", "`", "}", "return", "parsed", "+", "leftOver", "}", ")", "}", ")", "return", "code", "}" ]
walks through the syntaxes that we have and tokenizes the entities that correspond @method parse @param {String} code - raw code string @return {String} - encoded code string
[ "walks", "through", "the", "syntaxes", "that", "we", "have", "and", "tokenizes", "the", "entities", "that", "correspond" ]
3a97cd33715a6e2fe5d9cac3c8c6a7e6e15d43c2
https://github.com/gabrielcsapo/krayon/blob/3a97cd33715a6e2fe5d9cac3c8c6a7e6e15d43c2/util.js#L48-L83
56,166
gabrielcsapo/krayon
util.js
encode
function encode (str) { return str.split('').map((s) => { if (s.charCodeAt(0) > 127) return s return String.fromCharCode(s.charCodeAt(0) + 0x2800) }).join(' ') }
javascript
function encode (str) { return str.split('').map((s) => { if (s.charCodeAt(0) > 127) return s return String.fromCharCode(s.charCodeAt(0) + 0x2800) }).join(' ') }
[ "function", "encode", "(", "str", ")", "{", "return", "str", ".", "split", "(", "''", ")", ".", "map", "(", "(", "s", ")", "=>", "{", "if", "(", "s", ".", "charCodeAt", "(", "0", ")", ">", "127", ")", "return", "s", "return", "String", ".", "fromCharCode", "(", "s", ".", "charCodeAt", "(", "0", ")", "+", "0x2800", ")", "}", ")", ".", "join", "(", "' '", ")", "}" ]
encode utf8 string to braile @method encode @param {String} str - utf8 string @return {String} - brailed encoded string
[ "encode", "utf8", "string", "to", "braile" ]
3a97cd33715a6e2fe5d9cac3c8c6a7e6e15d43c2
https://github.com/gabrielcsapo/krayon/blob/3a97cd33715a6e2fe5d9cac3c8c6a7e6e15d43c2/util.js#L91-L96
56,167
gabrielcsapo/krayon
util.js
decode
function decode (str) { return str.trim().split(' ').map((s) => { if (s.charCodeAt(0) - 0x2800 > 127) return s return String.fromCharCode(s.charCodeAt(0) - 0x2800) }).join('') }
javascript
function decode (str) { return str.trim().split(' ').map((s) => { if (s.charCodeAt(0) - 0x2800 > 127) return s return String.fromCharCode(s.charCodeAt(0) - 0x2800) }).join('') }
[ "function", "decode", "(", "str", ")", "{", "return", "str", ".", "trim", "(", ")", ".", "split", "(", "' '", ")", ".", "map", "(", "(", "s", ")", "=>", "{", "if", "(", "s", ".", "charCodeAt", "(", "0", ")", "-", "0x2800", ">", "127", ")", "return", "s", "return", "String", ".", "fromCharCode", "(", "s", ".", "charCodeAt", "(", "0", ")", "-", "0x2800", ")", "}", ")", ".", "join", "(", "''", ")", "}" ]
decode brail back to utf8 @method decode @param {String} str - brail string @return {String} - utf8 decoded string
[ "decode", "brail", "back", "to", "utf8" ]
3a97cd33715a6e2fe5d9cac3c8c6a7e6e15d43c2
https://github.com/gabrielcsapo/krayon/blob/3a97cd33715a6e2fe5d9cac3c8c6a7e6e15d43c2/util.js#L104-L109
56,168
ForbesLindesay-Unmaintained/sauce-test
lib/run-browsers-bail.js
runBrowsersBail
function runBrowsersBail(location, remote, platforms, options) { var throttle = options.throttle || function (fn) { return fn(); }; var results = []; results.passedBrowsers = []; results.failedBrowsers = []; return new Promise(function (resolve) { function next(i) { if (i >= platforms.length) { return resolve(results); } var platform = platforms[i]; if (options.onQueue) options.onQueue(platform); throttle(function () { if (options.onStart) options.onStart(platform); return runSingleBrowser(location, remote, platform, { name: options.name, capabilities: options.capabilities, debug: options.debug, httpDebug: options.httpDebug, jobInfo: options.jobInfo, allowExceptions: options.allowExceptions, testComplete: options.testComplete, testPassed: options.testPassed, timeout: options.timeout }); }).done(function (result) { Object.keys(platform).forEach(function (key) { result[key] = platform[key]; }); results.push(result); if (options.onResult) options.onResult(result); if (result.passed) { results.passedBrowsers.push(result); next(i + 1); } else { results.failedBrowsers = [result]; resolve(results); } }, function (err) { var result = {passed: false, duration: err.duration, err: err}; Object.keys(platform).forEach(function (key) { result[key] = platform[key]; }); results.push(result); if (options.onResult) options.onResult(result); results.failedBrowsers = [result]; resolve(results); }); } next(0); }); }
javascript
function runBrowsersBail(location, remote, platforms, options) { var throttle = options.throttle || function (fn) { return fn(); }; var results = []; results.passedBrowsers = []; results.failedBrowsers = []; return new Promise(function (resolve) { function next(i) { if (i >= platforms.length) { return resolve(results); } var platform = platforms[i]; if (options.onQueue) options.onQueue(platform); throttle(function () { if (options.onStart) options.onStart(platform); return runSingleBrowser(location, remote, platform, { name: options.name, capabilities: options.capabilities, debug: options.debug, httpDebug: options.httpDebug, jobInfo: options.jobInfo, allowExceptions: options.allowExceptions, testComplete: options.testComplete, testPassed: options.testPassed, timeout: options.timeout }); }).done(function (result) { Object.keys(platform).forEach(function (key) { result[key] = platform[key]; }); results.push(result); if (options.onResult) options.onResult(result); if (result.passed) { results.passedBrowsers.push(result); next(i + 1); } else { results.failedBrowsers = [result]; resolve(results); } }, function (err) { var result = {passed: false, duration: err.duration, err: err}; Object.keys(platform).forEach(function (key) { result[key] = platform[key]; }); results.push(result); if (options.onResult) options.onResult(result); results.failedBrowsers = [result]; resolve(results); }); } next(0); }); }
[ "function", "runBrowsersBail", "(", "location", ",", "remote", ",", "platforms", ",", "options", ")", "{", "var", "throttle", "=", "options", ".", "throttle", "||", "function", "(", "fn", ")", "{", "return", "fn", "(", ")", ";", "}", ";", "var", "results", "=", "[", "]", ";", "results", ".", "passedBrowsers", "=", "[", "]", ";", "results", ".", "failedBrowsers", "=", "[", "]", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "function", "next", "(", "i", ")", "{", "if", "(", "i", ">=", "platforms", ".", "length", ")", "{", "return", "resolve", "(", "results", ")", ";", "}", "var", "platform", "=", "platforms", "[", "i", "]", ";", "if", "(", "options", ".", "onQueue", ")", "options", ".", "onQueue", "(", "platform", ")", ";", "throttle", "(", "function", "(", ")", "{", "if", "(", "options", ".", "onStart", ")", "options", ".", "onStart", "(", "platform", ")", ";", "return", "runSingleBrowser", "(", "location", ",", "remote", ",", "platform", ",", "{", "name", ":", "options", ".", "name", ",", "capabilities", ":", "options", ".", "capabilities", ",", "debug", ":", "options", ".", "debug", ",", "httpDebug", ":", "options", ".", "httpDebug", ",", "jobInfo", ":", "options", ".", "jobInfo", ",", "allowExceptions", ":", "options", ".", "allowExceptions", ",", "testComplete", ":", "options", ".", "testComplete", ",", "testPassed", ":", "options", ".", "testPassed", ",", "timeout", ":", "options", ".", "timeout", "}", ")", ";", "}", ")", ".", "done", "(", "function", "(", "result", ")", "{", "Object", ".", "keys", "(", "platform", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "result", "[", "key", "]", "=", "platform", "[", "key", "]", ";", "}", ")", ";", "results", ".", "push", "(", "result", ")", ";", "if", "(", "options", ".", "onResult", ")", "options", ".", "onResult", "(", "result", ")", ";", "if", "(", "result", ".", "passed", ")", "{", "results", ".", "passedBrowsers", ".", "push", "(", "result", ")", ";", "next", "(", "i", "+", "1", ")", ";", "}", "else", "{", "results", ".", "failedBrowsers", "=", "[", "result", "]", ";", "resolve", "(", "results", ")", ";", "}", "}", ",", "function", "(", "err", ")", "{", "var", "result", "=", "{", "passed", ":", "false", ",", "duration", ":", "err", ".", "duration", ",", "err", ":", "err", "}", ";", "Object", ".", "keys", "(", "platform", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "result", "[", "key", "]", "=", "platform", "[", "key", "]", ";", "}", ")", ";", "results", ".", "push", "(", "result", ")", ";", "if", "(", "options", ".", "onResult", ")", "options", ".", "onResult", "(", "result", ")", ";", "results", ".", "failedBrowsers", "=", "[", "result", "]", ";", "resolve", "(", "results", ")", ";", "}", ")", ";", "}", "next", "(", "0", ")", ";", "}", ")", ";", "}" ]
Run a test in a series of browsers, one at at time until one of them fails @option {Function} throttle @option {Object} capabilities @option {Boolean} debug @option {Object|Function} jobInfo @option {Boolean} allowExceptions @option {String|Function} testComplete @option {String|Function} testPassed @option {String} timeout @option {Function.<Result>} onResult Returns: ```js [{ "passed": true, "duration": "3000", ...Platform }, ...] ``` @param {Location} location @param {Object} remote @param {Array.<Platform>} platforms @param {Options} options @returns {Promise}
[ "Run", "a", "test", "in", "a", "series", "of", "browsers", "one", "at", "at", "time", "until", "one", "of", "them", "fails" ]
7c671b3321dc63aefc00c1c8d49e943ead2e7f5e
https://github.com/ForbesLindesay-Unmaintained/sauce-test/blob/7c671b3321dc63aefc00c1c8d49e943ead2e7f5e/lib/run-browsers-bail.js#L32-L83
56,169
danheberden/bear
lib/bear.js
function() { var bear = this; // don't bind until we're ready var srv = bear.ready.then( function() { var dfd = _.Deferred(); // only make once if ( !bear.githInstance ) { bear.githInstance = bear.gith({ repo: bear.settings.repo, }).on( 'all', bear._processPayload.bind( bear ) ); } dfd.resolve( bear.githInstance ); return dfd.promise(); }); return srv; }
javascript
function() { var bear = this; // don't bind until we're ready var srv = bear.ready.then( function() { var dfd = _.Deferred(); // only make once if ( !bear.githInstance ) { bear.githInstance = bear.gith({ repo: bear.settings.repo, }).on( 'all', bear._processPayload.bind( bear ) ); } dfd.resolve( bear.githInstance ); return dfd.promise(); }); return srv; }
[ "function", "(", ")", "{", "var", "bear", "=", "this", ";", "// don't bind until we're ready", "var", "srv", "=", "bear", ".", "ready", ".", "then", "(", "function", "(", ")", "{", "var", "dfd", "=", "_", ".", "Deferred", "(", ")", ";", "// only make once", "if", "(", "!", "bear", ".", "githInstance", ")", "{", "bear", ".", "githInstance", "=", "bear", ".", "gith", "(", "{", "repo", ":", "bear", ".", "settings", ".", "repo", ",", "}", ")", ".", "on", "(", "'all'", ",", "bear", ".", "_processPayload", ".", "bind", "(", "bear", ")", ")", ";", "}", "dfd", ".", "resolve", "(", "bear", ".", "githInstance", ")", ";", "return", "dfd", ".", "promise", "(", ")", ";", "}", ")", ";", "return", "srv", ";", "}" ]
but this is where the gold is
[ "but", "this", "is", "where", "the", "gold", "is" ]
c712108a0fe0ba105e9f65e925f9918b25ecec5c
https://github.com/danheberden/bear/blob/c712108a0fe0ba105e9f65e925f9918b25ecec5c/lib/bear.js#L187-L203
56,170
danheberden/bear
lib/bear.js
function( payload ) { var bear = this; var dfd = _.Deferred(); var action = dfd.promise(); // ok to launch live? if ( payload.branch === bear.settings.liveBranch ) { // can we just upload master without worrying about tags? if ( !bear.settings.deployOnTag ) { action = action.then( function() { return bear.live( bear.settings.liveBranch); }); } else if ( payload.tag ) { // since we tagged and that's required, only launch at that sha action = action.then( function() { return bear.live( bear.settings.liveBranch, payload.sha ); }); } } // either way, setup the staging version action = action.then( function() { return bear.stage( payload.branch ); }); // if we assigned a callback, fire it when these are done if ( bear.settings.githCallback ) { action.done( function() { bear.settings.githCallback.call( bear, payload ); }); } // start us off dfd.resolve(); }
javascript
function( payload ) { var bear = this; var dfd = _.Deferred(); var action = dfd.promise(); // ok to launch live? if ( payload.branch === bear.settings.liveBranch ) { // can we just upload master without worrying about tags? if ( !bear.settings.deployOnTag ) { action = action.then( function() { return bear.live( bear.settings.liveBranch); }); } else if ( payload.tag ) { // since we tagged and that's required, only launch at that sha action = action.then( function() { return bear.live( bear.settings.liveBranch, payload.sha ); }); } } // either way, setup the staging version action = action.then( function() { return bear.stage( payload.branch ); }); // if we assigned a callback, fire it when these are done if ( bear.settings.githCallback ) { action.done( function() { bear.settings.githCallback.call( bear, payload ); }); } // start us off dfd.resolve(); }
[ "function", "(", "payload", ")", "{", "var", "bear", "=", "this", ";", "var", "dfd", "=", "_", ".", "Deferred", "(", ")", ";", "var", "action", "=", "dfd", ".", "promise", "(", ")", ";", "// ok to launch live?", "if", "(", "payload", ".", "branch", "===", "bear", ".", "settings", ".", "liveBranch", ")", "{", "// can we just upload master without worrying about tags?", "if", "(", "!", "bear", ".", "settings", ".", "deployOnTag", ")", "{", "action", "=", "action", ".", "then", "(", "function", "(", ")", "{", "return", "bear", ".", "live", "(", "bear", ".", "settings", ".", "liveBranch", ")", ";", "}", ")", ";", "}", "else", "if", "(", "payload", ".", "tag", ")", "{", "// since we tagged and that's required, only launch at that sha", "action", "=", "action", ".", "then", "(", "function", "(", ")", "{", "return", "bear", ".", "live", "(", "bear", ".", "settings", ".", "liveBranch", ",", "payload", ".", "sha", ")", ";", "}", ")", ";", "}", "}", "// either way, setup the staging version", "action", "=", "action", ".", "then", "(", "function", "(", ")", "{", "return", "bear", ".", "stage", "(", "payload", ".", "branch", ")", ";", "}", ")", ";", "// if we assigned a callback, fire it when these are done", "if", "(", "bear", ".", "settings", ".", "githCallback", ")", "{", "action", ".", "done", "(", "function", "(", ")", "{", "bear", ".", "settings", ".", "githCallback", ".", "call", "(", "bear", ",", "payload", ")", ";", "}", ")", ";", "}", "// start us off", "dfd", ".", "resolve", "(", ")", ";", "}" ]
process the payload gith emitted
[ "process", "the", "payload", "gith", "emitted" ]
c712108a0fe0ba105e9f65e925f9918b25ecec5c
https://github.com/danheberden/bear/blob/c712108a0fe0ba105e9f65e925f9918b25ecec5c/lib/bear.js#L206-L240
56,171
danheberden/bear
lib/bear.js
function() { return dexec( 'cd ' + this.settings.git + '; npm install' ).done(function( stdout, stderr ) { log( 'npm install successful' ); log.extra( stdout, stderr ); }); }
javascript
function() { return dexec( 'cd ' + this.settings.git + '; npm install' ).done(function( stdout, stderr ) { log( 'npm install successful' ); log.extra( stdout, stderr ); }); }
[ "function", "(", ")", "{", "return", "dexec", "(", "'cd '", "+", "this", ".", "settings", ".", "git", "+", "'; npm install'", ")", ".", "done", "(", "function", "(", "stdout", ",", "stderr", ")", "{", "log", "(", "'npm install successful'", ")", ";", "log", ".", "extra", "(", "stdout", ",", "stderr", ")", ";", "}", ")", ";", "}" ]
hook into our process
[ "hook", "into", "our", "process" ]
c712108a0fe0ba105e9f65e925f9918b25ecec5c
https://github.com/danheberden/bear/blob/c712108a0fe0ba105e9f65e925f9918b25ecec5c/lib/bear.js#L268-L273
56,172
sfrdmn/node-randword
index.js
textStream
function textStream() { var start = randomInt(0, config.size - bufferSize) return fs.createReadStream(dictPath, { encoding: config.encoding, start: start, end: start + bufferSize }) }
javascript
function textStream() { var start = randomInt(0, config.size - bufferSize) return fs.createReadStream(dictPath, { encoding: config.encoding, start: start, end: start + bufferSize }) }
[ "function", "textStream", "(", ")", "{", "var", "start", "=", "randomInt", "(", "0", ",", "config", ".", "size", "-", "bufferSize", ")", "return", "fs", ".", "createReadStream", "(", "dictPath", ",", "{", "encoding", ":", "config", ".", "encoding", ",", "start", ":", "start", ",", "end", ":", "start", "+", "bufferSize", "}", ")", "}" ]
read dictionary with stream
[ "read", "dictionary", "with", "stream" ]
cab6611aa44c4b572ba405e266f0a4f736a21e3d
https://github.com/sfrdmn/node-randword/blob/cab6611aa44c4b572ba405e266f0a4f736a21e3d/index.js#L12-L19
56,173
transomjs/transom-socketio-internal
lib/socket-io-handler.js
SocketioHandler
function SocketioHandler(io, options) { /** * Emit 'data' to all sockets for the provided User or array of Users. * * @param {*} channelName * @param {*} users * @param {*} data */ function emitToUsers(users, channelName, data) { const usersArray = Array.isArray(users) ? users : [users]; usersArray.map(function (user) { Object.keys(io.sockets.sockets).filter(function (key) { return io.sockets.sockets[key].transomUser._id.toString() === user._id.toString(); }).map(function (socketKey) { io.sockets.sockets[socketKey].emit(channelName, data); }); }); } /** * Emit 'data' to all sockets for the authenticated Users. * * @param {*} channelName * @param {*} data */ function emitToEveryone(channelName, data) { Object.keys(io.sockets.sockets).filter(function (key) { return !!io.sockets.sockets[key].transomUser; }).map(function (socketKey) { io.sockets.sockets[socketKey].emit(channelName, data); }); } return { emitToUsers, emitToEveryone, // simple getter that allows access to io, while dis-allowing updates. get io() { return io; } }; }
javascript
function SocketioHandler(io, options) { /** * Emit 'data' to all sockets for the provided User or array of Users. * * @param {*} channelName * @param {*} users * @param {*} data */ function emitToUsers(users, channelName, data) { const usersArray = Array.isArray(users) ? users : [users]; usersArray.map(function (user) { Object.keys(io.sockets.sockets).filter(function (key) { return io.sockets.sockets[key].transomUser._id.toString() === user._id.toString(); }).map(function (socketKey) { io.sockets.sockets[socketKey].emit(channelName, data); }); }); } /** * Emit 'data' to all sockets for the authenticated Users. * * @param {*} channelName * @param {*} data */ function emitToEveryone(channelName, data) { Object.keys(io.sockets.sockets).filter(function (key) { return !!io.sockets.sockets[key].transomUser; }).map(function (socketKey) { io.sockets.sockets[socketKey].emit(channelName, data); }); } return { emitToUsers, emitToEveryone, // simple getter that allows access to io, while dis-allowing updates. get io() { return io; } }; }
[ "function", "SocketioHandler", "(", "io", ",", "options", ")", "{", "/**\n * Emit 'data' to all sockets for the provided User or array of Users.\n * \n * @param {*} channelName \n * @param {*} users \n * @param {*} data \n */", "function", "emitToUsers", "(", "users", ",", "channelName", ",", "data", ")", "{", "const", "usersArray", "=", "Array", ".", "isArray", "(", "users", ")", "?", "users", ":", "[", "users", "]", ";", "usersArray", ".", "map", "(", "function", "(", "user", ")", "{", "Object", ".", "keys", "(", "io", ".", "sockets", ".", "sockets", ")", ".", "filter", "(", "function", "(", "key", ")", "{", "return", "io", ".", "sockets", ".", "sockets", "[", "key", "]", ".", "transomUser", ".", "_id", ".", "toString", "(", ")", "===", "user", ".", "_id", ".", "toString", "(", ")", ";", "}", ")", ".", "map", "(", "function", "(", "socketKey", ")", "{", "io", ".", "sockets", ".", "sockets", "[", "socketKey", "]", ".", "emit", "(", "channelName", ",", "data", ")", ";", "}", ")", ";", "}", ")", ";", "}", "/**\n * Emit 'data' to all sockets for the authenticated Users.\n * \n * @param {*} channelName \n * @param {*} data \n */", "function", "emitToEveryone", "(", "channelName", ",", "data", ")", "{", "Object", ".", "keys", "(", "io", ".", "sockets", ".", "sockets", ")", ".", "filter", "(", "function", "(", "key", ")", "{", "return", "!", "!", "io", ".", "sockets", ".", "sockets", "[", "key", "]", ".", "transomUser", ";", "}", ")", ".", "map", "(", "function", "(", "socketKey", ")", "{", "io", ".", "sockets", ".", "sockets", "[", "socketKey", "]", ".", "emit", "(", "channelName", ",", "data", ")", ";", "}", ")", ";", "}", "return", "{", "emitToUsers", ",", "emitToEveryone", ",", "// simple getter that allows access to io, while dis-allowing updates.", "get", "io", "(", ")", "{", "return", "io", ";", "}", "}", ";", "}" ]
Module for the socket handler. Exports this function that creates the instance of the handler. which is added to the server registry as 'transomMessageClient' @param {*} io the initialized SocketIO server @param {*} options The socketHandler options object
[ "Module", "for", "the", "socket", "handler", ".", "Exports", "this", "function", "that", "creates", "the", "instance", "of", "the", "handler", ".", "which", "is", "added", "to", "the", "server", "registry", "as", "transomMessageClient" ]
24932b1f3614ec3d234ff8654f63f15b395126e8
https://github.com/transomjs/transom-socketio-internal/blob/24932b1f3614ec3d234ff8654f63f15b395126e8/lib/socket-io-handler.js#L10-L52
56,174
transomjs/transom-socketio-internal
lib/socket-io-handler.js
emitToUsers
function emitToUsers(users, channelName, data) { const usersArray = Array.isArray(users) ? users : [users]; usersArray.map(function (user) { Object.keys(io.sockets.sockets).filter(function (key) { return io.sockets.sockets[key].transomUser._id.toString() === user._id.toString(); }).map(function (socketKey) { io.sockets.sockets[socketKey].emit(channelName, data); }); }); }
javascript
function emitToUsers(users, channelName, data) { const usersArray = Array.isArray(users) ? users : [users]; usersArray.map(function (user) { Object.keys(io.sockets.sockets).filter(function (key) { return io.sockets.sockets[key].transomUser._id.toString() === user._id.toString(); }).map(function (socketKey) { io.sockets.sockets[socketKey].emit(channelName, data); }); }); }
[ "function", "emitToUsers", "(", "users", ",", "channelName", ",", "data", ")", "{", "const", "usersArray", "=", "Array", ".", "isArray", "(", "users", ")", "?", "users", ":", "[", "users", "]", ";", "usersArray", ".", "map", "(", "function", "(", "user", ")", "{", "Object", ".", "keys", "(", "io", ".", "sockets", ".", "sockets", ")", ".", "filter", "(", "function", "(", "key", ")", "{", "return", "io", ".", "sockets", ".", "sockets", "[", "key", "]", ".", "transomUser", ".", "_id", ".", "toString", "(", ")", "===", "user", ".", "_id", ".", "toString", "(", ")", ";", "}", ")", ".", "map", "(", "function", "(", "socketKey", ")", "{", "io", ".", "sockets", ".", "sockets", "[", "socketKey", "]", ".", "emit", "(", "channelName", ",", "data", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Emit 'data' to all sockets for the provided User or array of Users. @param {*} channelName @param {*} users @param {*} data
[ "Emit", "data", "to", "all", "sockets", "for", "the", "provided", "User", "or", "array", "of", "Users", "." ]
24932b1f3614ec3d234ff8654f63f15b395126e8
https://github.com/transomjs/transom-socketio-internal/blob/24932b1f3614ec3d234ff8654f63f15b395126e8/lib/socket-io-handler.js#L19-L28
56,175
transomjs/transom-socketio-internal
lib/socket-io-handler.js
emitToEveryone
function emitToEveryone(channelName, data) { Object.keys(io.sockets.sockets).filter(function (key) { return !!io.sockets.sockets[key].transomUser; }).map(function (socketKey) { io.sockets.sockets[socketKey].emit(channelName, data); }); }
javascript
function emitToEveryone(channelName, data) { Object.keys(io.sockets.sockets).filter(function (key) { return !!io.sockets.sockets[key].transomUser; }).map(function (socketKey) { io.sockets.sockets[socketKey].emit(channelName, data); }); }
[ "function", "emitToEveryone", "(", "channelName", ",", "data", ")", "{", "Object", ".", "keys", "(", "io", ".", "sockets", ".", "sockets", ")", ".", "filter", "(", "function", "(", "key", ")", "{", "return", "!", "!", "io", ".", "sockets", ".", "sockets", "[", "key", "]", ".", "transomUser", ";", "}", ")", ".", "map", "(", "function", "(", "socketKey", ")", "{", "io", ".", "sockets", ".", "sockets", "[", "socketKey", "]", ".", "emit", "(", "channelName", ",", "data", ")", ";", "}", ")", ";", "}" ]
Emit 'data' to all sockets for the authenticated Users. @param {*} channelName @param {*} data
[ "Emit", "data", "to", "all", "sockets", "for", "the", "authenticated", "Users", "." ]
24932b1f3614ec3d234ff8654f63f15b395126e8
https://github.com/transomjs/transom-socketio-internal/blob/24932b1f3614ec3d234ff8654f63f15b395126e8/lib/socket-io-handler.js#L36-L42
56,176
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/floatingspace/plugin.js
updatePos
function updatePos( pos, prop, val ) { floatSpace.setStyle( prop, pixelate( val ) ); floatSpace.setStyle( 'position', pos ); }
javascript
function updatePos( pos, prop, val ) { floatSpace.setStyle( prop, pixelate( val ) ); floatSpace.setStyle( 'position', pos ); }
[ "function", "updatePos", "(", "pos", ",", "prop", ",", "val", ")", "{", "floatSpace", ".", "setStyle", "(", "prop", ",", "pixelate", "(", "val", ")", ")", ";", "floatSpace", ".", "setStyle", "(", "'position'", ",", "pos", ")", ";", "}" ]
Update the float space position.
[ "Update", "the", "float", "space", "position", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/floatingspace/plugin.js#L49-L52
56,177
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/floatingspace/plugin.js
changeMode
function changeMode( newMode ) { var editorPos = editable.getDocumentPosition(); switch ( newMode ) { case 'top': updatePos( 'absolute', 'top', editorPos.y - spaceHeight - dockedOffsetY ); break; case 'pin': updatePos( 'fixed', 'top', pinnedOffsetY ); break; case 'bottom': updatePos( 'absolute', 'top', editorPos.y + ( editorRect.height || editorRect.bottom - editorRect.top ) + dockedOffsetY ); break; } mode = newMode; }
javascript
function changeMode( newMode ) { var editorPos = editable.getDocumentPosition(); switch ( newMode ) { case 'top': updatePos( 'absolute', 'top', editorPos.y - spaceHeight - dockedOffsetY ); break; case 'pin': updatePos( 'fixed', 'top', pinnedOffsetY ); break; case 'bottom': updatePos( 'absolute', 'top', editorPos.y + ( editorRect.height || editorRect.bottom - editorRect.top ) + dockedOffsetY ); break; } mode = newMode; }
[ "function", "changeMode", "(", "newMode", ")", "{", "var", "editorPos", "=", "editable", ".", "getDocumentPosition", "(", ")", ";", "switch", "(", "newMode", ")", "{", "case", "'top'", ":", "updatePos", "(", "'absolute'", ",", "'top'", ",", "editorPos", ".", "y", "-", "spaceHeight", "-", "dockedOffsetY", ")", ";", "break", ";", "case", "'pin'", ":", "updatePos", "(", "'fixed'", ",", "'top'", ",", "pinnedOffsetY", ")", ";", "break", ";", "case", "'bottom'", ":", "updatePos", "(", "'absolute'", ",", "'top'", ",", "editorPos", ".", "y", "+", "(", "editorRect", ".", "height", "||", "editorRect", ".", "bottom", "-", "editorRect", ".", "top", ")", "+", "dockedOffsetY", ")", ";", "break", ";", "}", "mode", "=", "newMode", ";", "}" ]
Change the current mode and update float space position accordingly.
[ "Change", "the", "current", "mode", "and", "update", "float", "space", "position", "accordingly", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/floatingspace/plugin.js#L55-L71
56,178
agneta/angularjs
source/ui/gallery/photoswipe.module.js
function(e) { e = e || window.event; e.preventDefault ? e.preventDefault() : (e.returnValue = false); var eTarget = e.target || e.srcElement; // find root element of slide var clickedListItem = closest(eTarget, function(el) { //console.log(el.getAttribute('ui-gallery-item')); return el.getAttribute('ui-gallery-item') != null; }); if (!clickedListItem) { return; } var parentNode = closest(eTarget, function(el) { return el.getAttribute('ui-gallery') != null; }); if (!parentNode) { return; } var childNodes = parentNode.querySelectorAll('[ui-gallery-item]'); // find index of clicked item by looping through all child nodes // alternatively, you may define index via data- attribute var clickedGallery = parentNode, numChildNodes = childNodes.length, nodeIndex = 0, index; for (var i = 0; i < numChildNodes; i++) { if (childNodes[i].nodeType !== 1) { continue; } if (childNodes[i] === clickedListItem) { index = nodeIndex; break; } nodeIndex++; } if (index >= 0) { // open PhotoSwipe if valid index found openPhotoSwipe(index, clickedGallery); } return false; }
javascript
function(e) { e = e || window.event; e.preventDefault ? e.preventDefault() : (e.returnValue = false); var eTarget = e.target || e.srcElement; // find root element of slide var clickedListItem = closest(eTarget, function(el) { //console.log(el.getAttribute('ui-gallery-item')); return el.getAttribute('ui-gallery-item') != null; }); if (!clickedListItem) { return; } var parentNode = closest(eTarget, function(el) { return el.getAttribute('ui-gallery') != null; }); if (!parentNode) { return; } var childNodes = parentNode.querySelectorAll('[ui-gallery-item]'); // find index of clicked item by looping through all child nodes // alternatively, you may define index via data- attribute var clickedGallery = parentNode, numChildNodes = childNodes.length, nodeIndex = 0, index; for (var i = 0; i < numChildNodes; i++) { if (childNodes[i].nodeType !== 1) { continue; } if (childNodes[i] === clickedListItem) { index = nodeIndex; break; } nodeIndex++; } if (index >= 0) { // open PhotoSwipe if valid index found openPhotoSwipe(index, clickedGallery); } return false; }
[ "function", "(", "e", ")", "{", "e", "=", "e", "||", "window", ".", "event", ";", "e", ".", "preventDefault", "?", "e", ".", "preventDefault", "(", ")", ":", "(", "e", ".", "returnValue", "=", "false", ")", ";", "var", "eTarget", "=", "e", ".", "target", "||", "e", ".", "srcElement", ";", "// find root element of slide", "var", "clickedListItem", "=", "closest", "(", "eTarget", ",", "function", "(", "el", ")", "{", "//console.log(el.getAttribute('ui-gallery-item'));", "return", "el", ".", "getAttribute", "(", "'ui-gallery-item'", ")", "!=", "null", ";", "}", ")", ";", "if", "(", "!", "clickedListItem", ")", "{", "return", ";", "}", "var", "parentNode", "=", "closest", "(", "eTarget", ",", "function", "(", "el", ")", "{", "return", "el", ".", "getAttribute", "(", "'ui-gallery'", ")", "!=", "null", ";", "}", ")", ";", "if", "(", "!", "parentNode", ")", "{", "return", ";", "}", "var", "childNodes", "=", "parentNode", ".", "querySelectorAll", "(", "'[ui-gallery-item]'", ")", ";", "// find index of clicked item by looping through all child nodes", "// alternatively, you may define index via data- attribute", "var", "clickedGallery", "=", "parentNode", ",", "numChildNodes", "=", "childNodes", ".", "length", ",", "nodeIndex", "=", "0", ",", "index", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numChildNodes", ";", "i", "++", ")", "{", "if", "(", "childNodes", "[", "i", "]", ".", "nodeType", "!==", "1", ")", "{", "continue", ";", "}", "if", "(", "childNodes", "[", "i", "]", "===", "clickedListItem", ")", "{", "index", "=", "nodeIndex", ";", "break", ";", "}", "nodeIndex", "++", ";", "}", "if", "(", "index", ">=", "0", ")", "{", "// open PhotoSwipe if valid index found", "openPhotoSwipe", "(", "index", ",", "clickedGallery", ")", ";", "}", "return", "false", ";", "}" ]
triggers when user clicks on thumbnail
[ "triggers", "when", "user", "clicks", "on", "thumbnail" ]
25fa30337a609b4f79948d7f1b86f8d49208a417
https://github.com/agneta/angularjs/blob/25fa30337a609b4f79948d7f1b86f8d49208a417/source/ui/gallery/photoswipe.module.js#L60-L109
56,179
alonbardavid/coffee-script-mapped
lib/source-map-support.js
handleUncaughtExceptions
function handleUncaughtExceptions(error) { if (!error || !error.stack) { console.log('Uncaught exception:', error); process.exit(); } var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack); if (match) { var cache = {}; var position = mapSourcePosition(cache, { source: match[1], line: match[2], column: match[3] }); if (fs.existsSync(position.source)) { var contents = fs.readFileSync(position.source, 'utf8'); var line = contents.split(/(?:\r\n|\r|\n)/)[position.line - 1]; if (line) { console.log('\n' + position.source + ':' + position.line); console.log(line); console.log(new Array(+position.column).join(' ') + '^'); } } } console.log(error.stack); process.exit(); }
javascript
function handleUncaughtExceptions(error) { if (!error || !error.stack) { console.log('Uncaught exception:', error); process.exit(); } var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack); if (match) { var cache = {}; var position = mapSourcePosition(cache, { source: match[1], line: match[2], column: match[3] }); if (fs.existsSync(position.source)) { var contents = fs.readFileSync(position.source, 'utf8'); var line = contents.split(/(?:\r\n|\r|\n)/)[position.line - 1]; if (line) { console.log('\n' + position.source + ':' + position.line); console.log(line); console.log(new Array(+position.column).join(' ') + '^'); } } } console.log(error.stack); process.exit(); }
[ "function", "handleUncaughtExceptions", "(", "error", ")", "{", "if", "(", "!", "error", "||", "!", "error", ".", "stack", ")", "{", "console", ".", "log", "(", "'Uncaught exception:'", ",", "error", ")", ";", "process", ".", "exit", "(", ")", ";", "}", "var", "match", "=", "/", "\\n at [^(]+ \\((.*):(\\d+):(\\d+)\\)", "/", ".", "exec", "(", "error", ".", "stack", ")", ";", "if", "(", "match", ")", "{", "var", "cache", "=", "{", "}", ";", "var", "position", "=", "mapSourcePosition", "(", "cache", ",", "{", "source", ":", "match", "[", "1", "]", ",", "line", ":", "match", "[", "2", "]", ",", "column", ":", "match", "[", "3", "]", "}", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "position", ".", "source", ")", ")", "{", "var", "contents", "=", "fs", ".", "readFileSync", "(", "position", ".", "source", ",", "'utf8'", ")", ";", "var", "line", "=", "contents", ".", "split", "(", "/", "(?:\\r\\n|\\r|\\n)", "/", ")", "[", "position", ".", "line", "-", "1", "]", ";", "if", "(", "line", ")", "{", "console", ".", "log", "(", "'\\n'", "+", "position", ".", "source", "+", "':'", "+", "position", ".", "line", ")", ";", "console", ".", "log", "(", "line", ")", ";", "console", ".", "log", "(", "new", "Array", "(", "+", "position", ".", "column", ")", ".", "join", "(", "' '", ")", "+", "'^'", ")", ";", "}", "}", "}", "console", ".", "log", "(", "error", ".", "stack", ")", ";", "process", ".", "exit", "(", ")", ";", "}" ]
Mimic node's stack trace printing when an exception escapes the process
[ "Mimic", "node", "s", "stack", "trace", "printing", "when", "an", "exception", "escapes", "the", "process" ]
c658ca79ab24800ab5bbde6e56343cfa4a5e6dfe
https://github.com/alonbardavid/coffee-script-mapped/blob/c658ca79ab24800ab5bbde6e56343cfa4a5e6dfe/lib/source-map-support.js#L127-L152
56,180
JohnnieFucker/dreamix-admin
lib/master/masterAgent.js
broadcastMonitors
function broadcastMonitors(records, moduleId, msg) { msg = protocol.composeRequest(null, moduleId, msg); if (records instanceof Array) { for (let i = 0, l = records.length; i < l; i++) { const socket = records[i].socket; doSend(socket, 'monitor', msg); } } else { for (const id in records) { if (records.hasOwnProperty(id)) { const socket = records[id].socket; doSend(socket, 'monitor', msg); } } } }
javascript
function broadcastMonitors(records, moduleId, msg) { msg = protocol.composeRequest(null, moduleId, msg); if (records instanceof Array) { for (let i = 0, l = records.length; i < l; i++) { const socket = records[i].socket; doSend(socket, 'monitor', msg); } } else { for (const id in records) { if (records.hasOwnProperty(id)) { const socket = records[id].socket; doSend(socket, 'monitor', msg); } } } }
[ "function", "broadcastMonitors", "(", "records", ",", "moduleId", ",", "msg", ")", "{", "msg", "=", "protocol", ".", "composeRequest", "(", "null", ",", "moduleId", ",", "msg", ")", ";", "if", "(", "records", "instanceof", "Array", ")", "{", "for", "(", "let", "i", "=", "0", ",", "l", "=", "records", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "const", "socket", "=", "records", "[", "i", "]", ".", "socket", ";", "doSend", "(", "socket", ",", "'monitor'", ",", "msg", ")", ";", "}", "}", "else", "{", "for", "(", "const", "id", "in", "records", ")", "{", "if", "(", "records", ".", "hasOwnProperty", "(", "id", ")", ")", "{", "const", "socket", "=", "records", "[", "id", "]", ".", "socket", ";", "doSend", "(", "socket", ",", "'monitor'", ",", "msg", ")", ";", "}", "}", "}", "}" ]
broadcast msg to monitor @param {Object} records registered modules @param {String} moduleId module id/name @param {Object} msg message @api private
[ "broadcast", "msg", "to", "monitor" ]
fc169e2481d5a7456725fb33f7a7907e0776ef79
https://github.com/JohnnieFucker/dreamix-admin/blob/fc169e2481d5a7456725fb33f7a7907e0776ef79/lib/master/masterAgent.js#L137-L153
56,181
OctaveWealth/passy
lib/baseURL.js
getChar
function getChar (bits) { var index = parseInt(bits,2); if (isNaN(index) || index < 0 || index > 63) throw new Error('baseURL#getChar: Need valid bitString'); return ALPHABET[index]; }
javascript
function getChar (bits) { var index = parseInt(bits,2); if (isNaN(index) || index < 0 || index > 63) throw new Error('baseURL#getChar: Need valid bitString'); return ALPHABET[index]; }
[ "function", "getChar", "(", "bits", ")", "{", "var", "index", "=", "parseInt", "(", "bits", ",", "2", ")", ";", "if", "(", "isNaN", "(", "index", ")", "||", "index", "<", "0", "||", "index", ">", "63", ")", "throw", "new", "Error", "(", "'baseURL#getChar: Need valid bitString'", ")", ";", "return", "ALPHABET", "[", "index", "]", ";", "}" ]
Get baseURL char from given 6bit bitstring @param {string} bits 6bit bitstring @return {string} baseURL char
[ "Get", "baseURL", "char", "from", "given", "6bit", "bitstring" ]
6e357b018952f73e8570b89eda95393780328fab
https://github.com/OctaveWealth/passy/blob/6e357b018952f73e8570b89eda95393780328fab/lib/baseURL.js#L26-L30
56,182
OctaveWealth/passy
lib/baseURL.js
indexOfBits
function indexOfBits (char) { var index = ALPHABET.indexOf(char); if (index < 0) throw new Error('baseURL#indexOfBits: Need valid baseURL char'); return bitString.pad(index.toString(2), 6) ; }
javascript
function indexOfBits (char) { var index = ALPHABET.indexOf(char); if (index < 0) throw new Error('baseURL#indexOfBits: Need valid baseURL char'); return bitString.pad(index.toString(2), 6) ; }
[ "function", "indexOfBits", "(", "char", ")", "{", "var", "index", "=", "ALPHABET", ".", "indexOf", "(", "char", ")", ";", "if", "(", "index", "<", "0", ")", "throw", "new", "Error", "(", "'baseURL#indexOfBits: Need valid baseURL char'", ")", ";", "return", "bitString", ".", "pad", "(", "index", ".", "toString", "(", "2", ")", ",", "6", ")", ";", "}" ]
Get 6bit bitstring given a baseURL char @param {string} char Single baseURL char @return {string} 6bit bitstring of 'indexof' (0-63)
[ "Get", "6bit", "bitstring", "given", "a", "baseURL", "char" ]
6e357b018952f73e8570b89eda95393780328fab
https://github.com/OctaveWealth/passy/blob/6e357b018952f73e8570b89eda95393780328fab/lib/baseURL.js#L37-L41
56,183
OctaveWealth/passy
lib/baseURL.js
encode
function encode (bits) { if (!bitString.isValid(bits)) throw new Error('baseURL#encode: bits not valid bitstring'); if (bits.length % 6 !== 0) throw new Error('baseURL#encode: bits must be a multiple of 6'); var result = ''; for (var i = 0; i < bits.length; i = i + 6) { result += getChar(bits.slice(i, i + 6 )); } return result; }
javascript
function encode (bits) { if (!bitString.isValid(bits)) throw new Error('baseURL#encode: bits not valid bitstring'); if (bits.length % 6 !== 0) throw new Error('baseURL#encode: bits must be a multiple of 6'); var result = ''; for (var i = 0; i < bits.length; i = i + 6) { result += getChar(bits.slice(i, i + 6 )); } return result; }
[ "function", "encode", "(", "bits", ")", "{", "if", "(", "!", "bitString", ".", "isValid", "(", "bits", ")", ")", "throw", "new", "Error", "(", "'baseURL#encode: bits not valid bitstring'", ")", ";", "if", "(", "bits", ".", "length", "%", "6", "!==", "0", ")", "throw", "new", "Error", "(", "'baseURL#encode: bits must be a multiple of 6'", ")", ";", "var", "result", "=", "''", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "bits", ".", "length", ";", "i", "=", "i", "+", "6", ")", "{", "result", "+=", "getChar", "(", "bits", ".", "slice", "(", "i", ",", "i", "+", "6", ")", ")", ";", "}", "return", "result", ";", "}" ]
Encode a mod 6 bitstring into a baseURL string @param {string} bits A mod 6 bitstring @return {string} baseURL encoded string
[ "Encode", "a", "mod", "6", "bitstring", "into", "a", "baseURL", "string" ]
6e357b018952f73e8570b89eda95393780328fab
https://github.com/OctaveWealth/passy/blob/6e357b018952f73e8570b89eda95393780328fab/lib/baseURL.js#L48-L57
56,184
OctaveWealth/passy
lib/baseURL.js
decode
function decode (str) { if (!isValid(str)) throw new Error('baseURL#decode: str not valid baseURL string'); var bits = ''; // Decode for (var i = 0; i < str.length; i++) { bits += indexOfBits(str[i]); } return bits; }
javascript
function decode (str) { if (!isValid(str)) throw new Error('baseURL#decode: str not valid baseURL string'); var bits = ''; // Decode for (var i = 0; i < str.length; i++) { bits += indexOfBits(str[i]); } return bits; }
[ "function", "decode", "(", "str", ")", "{", "if", "(", "!", "isValid", "(", "str", ")", ")", "throw", "new", "Error", "(", "'baseURL#decode: str not valid baseURL string'", ")", ";", "var", "bits", "=", "''", ";", "// Decode", "for", "(", "var", "i", "=", "0", ";", "i", "<", "str", ".", "length", ";", "i", "++", ")", "{", "bits", "+=", "indexOfBits", "(", "str", "[", "i", "]", ")", ";", "}", "return", "bits", ";", "}" ]
Decode a baseURL string to a mod 6 bitstring @param {string} str A valid baseURL string @return {string} A mod 6 bitstring
[ "Decode", "a", "baseURL", "string", "to", "a", "mod", "6", "bitstring" ]
6e357b018952f73e8570b89eda95393780328fab
https://github.com/OctaveWealth/passy/blob/6e357b018952f73e8570b89eda95393780328fab/lib/baseURL.js#L75-L84
56,185
Pilatch/simple-component-v0
index.js
simpleComponent
function simpleComponent(elementName, elementClass, elementClassToExtend) { elementClass = elementClass || {} elementClassToExtend = elementClassToExtend || HTMLElement elementClass.prototype = Object.create(elementClassToExtend.prototype) assign(elementClass.prototype, elementClass) elementClass.__template = template(elementName) if (elementClass.prototype.createdCallback) { elementClass.prototype.__originalCreatedCallback = elementClass.prototype.createdCallback } elementClass.prototype.createdCallback = function() { fill(this, elementClass.__template) if (elementClass.prototype.__originalCreatedCallback) { elementClass.prototype.__originalCreatedCallback.call(this) } } document.registerElement(elementName, elementClass) }
javascript
function simpleComponent(elementName, elementClass, elementClassToExtend) { elementClass = elementClass || {} elementClassToExtend = elementClassToExtend || HTMLElement elementClass.prototype = Object.create(elementClassToExtend.prototype) assign(elementClass.prototype, elementClass) elementClass.__template = template(elementName) if (elementClass.prototype.createdCallback) { elementClass.prototype.__originalCreatedCallback = elementClass.prototype.createdCallback } elementClass.prototype.createdCallback = function() { fill(this, elementClass.__template) if (elementClass.prototype.__originalCreatedCallback) { elementClass.prototype.__originalCreatedCallback.call(this) } } document.registerElement(elementName, elementClass) }
[ "function", "simpleComponent", "(", "elementName", ",", "elementClass", ",", "elementClassToExtend", ")", "{", "elementClass", "=", "elementClass", "||", "{", "}", "elementClassToExtend", "=", "elementClassToExtend", "||", "HTMLElement", "elementClass", ".", "prototype", "=", "Object", ".", "create", "(", "elementClassToExtend", ".", "prototype", ")", "assign", "(", "elementClass", ".", "prototype", ",", "elementClass", ")", "elementClass", ".", "__template", "=", "template", "(", "elementName", ")", "if", "(", "elementClass", ".", "prototype", ".", "createdCallback", ")", "{", "elementClass", ".", "prototype", ".", "__originalCreatedCallback", "=", "elementClass", ".", "prototype", ".", "createdCallback", "}", "elementClass", ".", "prototype", ".", "createdCallback", "=", "function", "(", ")", "{", "fill", "(", "this", ",", "elementClass", ".", "__template", ")", "if", "(", "elementClass", ".", "prototype", ".", "__originalCreatedCallback", ")", "{", "elementClass", ".", "prototype", ".", "__originalCreatedCallback", ".", "call", "(", "this", ")", "}", "}", "document", ".", "registerElement", "(", "elementName", ",", "elementClass", ")", "}" ]
Define a stateless custom element with no behaviors. Give the element's template an ID attribute with the "-template" suffix. @module simpleComponent @example <template id="simple-bling-template"> <style> simple-bling { color: gold; font-weight: bold; } </style> </template> <script> simpleComponent('simple-bling') </script> @param {String} elementName Name of the custom element @param {Object} [elementClass] An object with lifecycle callbacks on it. Not actually an ES6 class for compatability purposes. @param {Function} [elementClassToExtend] An existing HTML element class to extend, e.g. HTMLButtonElement. @return {void}
[ "Define", "a", "stateless", "custom", "element", "with", "no", "behaviors", ".", "Give", "the", "element", "s", "template", "an", "ID", "attribute", "with", "the", "-", "template", "suffix", "." ]
da1f223a85beff68420f579e34a07f6b2851d734
https://github.com/Pilatch/simple-component-v0/blob/da1f223a85beff68420f579e34a07f6b2851d734/index.js#L36-L56
56,186
Pilatch/simple-component-v0
index.js
fill
function fill(toElement, templateElement) { var templateContentClone = templateElement.content.cloneNode(true) var slot var i if (toElement.childNodes.length) { slot = templateContentClone.querySelector('slot') if (slot) { while (toElement.childNodes.length) { slot.appendChild(toElement.firstChild) } } } toElement.appendChild(templateContentClone) }
javascript
function fill(toElement, templateElement) { var templateContentClone = templateElement.content.cloneNode(true) var slot var i if (toElement.childNodes.length) { slot = templateContentClone.querySelector('slot') if (slot) { while (toElement.childNodes.length) { slot.appendChild(toElement.firstChild) } } } toElement.appendChild(templateContentClone) }
[ "function", "fill", "(", "toElement", ",", "templateElement", ")", "{", "var", "templateContentClone", "=", "templateElement", ".", "content", ".", "cloneNode", "(", "true", ")", "var", "slot", "var", "i", "if", "(", "toElement", ".", "childNodes", ".", "length", ")", "{", "slot", "=", "templateContentClone", ".", "querySelector", "(", "'slot'", ")", "if", "(", "slot", ")", "{", "while", "(", "toElement", ".", "childNodes", ".", "length", ")", "{", "slot", ".", "appendChild", "(", "toElement", ".", "firstChild", ")", "}", "}", "}", "toElement", ".", "appendChild", "(", "templateContentClone", ")", "}" ]
Attach a template's content to an element. @public @memberof module:simpleComponent @param {HTMLElement} toElement The element to attach the template content to @param {HTMLElement} template A template element that has the markup guts for the custom element. @return {void}
[ "Attach", "a", "template", "s", "content", "to", "an", "element", "." ]
da1f223a85beff68420f579e34a07f6b2851d734
https://github.com/Pilatch/simple-component-v0/blob/da1f223a85beff68420f579e34a07f6b2851d734/index.js#L66-L82
56,187
bryanwayb/js-html
lib/context.js
makeRequire
function makeRequire(m, self) { function _require(_path) { return m.require(_path); } _require.resolve = function(request) { return _module._resolveFilename(request, self); }; _require.cache = _module._cache; _require.extensions = _module._extensions; return _require; }
javascript
function makeRequire(m, self) { function _require(_path) { return m.require(_path); } _require.resolve = function(request) { return _module._resolveFilename(request, self); }; _require.cache = _module._cache; _require.extensions = _module._extensions; return _require; }
[ "function", "makeRequire", "(", "m", ",", "self", ")", "{", "function", "_require", "(", "_path", ")", "{", "return", "m", ".", "require", "(", "_path", ")", ";", "}", "_require", ".", "resolve", "=", "function", "(", "request", ")", "{", "return", "_module", ".", "_resolveFilename", "(", "request", ",", "self", ")", ";", "}", ";", "_require", ".", "cache", "=", "_module", ".", "_cache", ";", "_require", ".", "extensions", "=", "_module", ".", "_extensions", ";", "return", "_require", ";", "}" ]
Basically takes the place of Module.prototype._compile, with some features stripped out
[ "Basically", "takes", "the", "place", "of", "Module", ".", "prototype", ".", "_compile", "with", "some", "features", "stripped", "out" ]
6cfb9bb73cc4609d3089da0eba6ed2b3c3ce4380
https://github.com/bryanwayb/js-html/blob/6cfb9bb73cc4609d3089da0eba6ed2b3c3ce4380/lib/context.js#L88-L100
56,188
Industryswarm/isnode-mod-data
lib/mongodb/mongodb-core/lib/connection/pool.js
_connectionFailureHandler
function _connectionFailureHandler(self) { return function() { if (this._connectionFailHandled) return; this._connectionFailHandled = true; // Destroy the connection this.destroy(); // Count down the number of reconnects self.retriesLeft = self.retriesLeft - 1; // How many retries are left if (self.retriesLeft <= 0) { // Destroy the instance self.destroy(); // Emit close event self.emit( 'reconnectFailed', new MongoNetworkError( f( 'failed to reconnect after %s attempts with interval %s ms', self.options.reconnectTries, self.options.reconnectInterval ) ) ); } else { self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval); } }; }
javascript
function _connectionFailureHandler(self) { return function() { if (this._connectionFailHandled) return; this._connectionFailHandled = true; // Destroy the connection this.destroy(); // Count down the number of reconnects self.retriesLeft = self.retriesLeft - 1; // How many retries are left if (self.retriesLeft <= 0) { // Destroy the instance self.destroy(); // Emit close event self.emit( 'reconnectFailed', new MongoNetworkError( f( 'failed to reconnect after %s attempts with interval %s ms', self.options.reconnectTries, self.options.reconnectInterval ) ) ); } else { self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval); } }; }
[ "function", "_connectionFailureHandler", "(", "self", ")", "{", "return", "function", "(", ")", "{", "if", "(", "this", ".", "_connectionFailHandled", ")", "return", ";", "this", ".", "_connectionFailHandled", "=", "true", ";", "// Destroy the connection", "this", ".", "destroy", "(", ")", ";", "// Count down the number of reconnects", "self", ".", "retriesLeft", "=", "self", ".", "retriesLeft", "-", "1", ";", "// How many retries are left", "if", "(", "self", ".", "retriesLeft", "<=", "0", ")", "{", "// Destroy the instance", "self", ".", "destroy", "(", ")", ";", "// Emit close event", "self", ".", "emit", "(", "'reconnectFailed'", ",", "new", "MongoNetworkError", "(", "f", "(", "'failed to reconnect after %s attempts with interval %s ms'", ",", "self", ".", "options", ".", "reconnectTries", ",", "self", ".", "options", ".", "reconnectInterval", ")", ")", ")", ";", "}", "else", "{", "self", ".", "reconnectId", "=", "setTimeout", "(", "attemptReconnect", "(", "self", ")", ",", "self", ".", "options", ".", "reconnectInterval", ")", ";", "}", "}", ";", "}" ]
If we have failure schedule a retry
[ "If", "we", "have", "failure", "schedule", "a", "retry" ]
5adc639b88a0d72cbeef23a6b5df7f4540745089
https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb-core/lib/connection/pool.js#L349-L376
56,189
Industryswarm/isnode-mod-data
lib/mongodb/mongodb-core/lib/connection/pool.js
_connectHandler
function _connectHandler(self) { return function() { // Assign var connection = this; // Pool destroyed stop the connection if (self.state === DESTROYED || self.state === DESTROYING) { return connection.destroy(); } // Clear out all handlers handlers.forEach(function(event) { connection.removeAllListeners(event); }); // Reset reconnect id self.reconnectId = null; // Apply pool connection handlers connection.on('error', connectionFailureHandler(self, 'error')); connection.on('close', connectionFailureHandler(self, 'close')); connection.on('timeout', connectionFailureHandler(self, 'timeout')); connection.on('parseError', connectionFailureHandler(self, 'parseError')); // Apply any auth to the connection reauthenticate(self, this, function() { // Reset retries self.retriesLeft = self.options.reconnectTries; // Push to available connections self.availableConnections.push(connection); // Set the reconnectConnection to null self.reconnectConnection = null; // Emit reconnect event self.emit('reconnect', self); // Trigger execute to start everything up again _execute(self)(); }); }; }
javascript
function _connectHandler(self) { return function() { // Assign var connection = this; // Pool destroyed stop the connection if (self.state === DESTROYED || self.state === DESTROYING) { return connection.destroy(); } // Clear out all handlers handlers.forEach(function(event) { connection.removeAllListeners(event); }); // Reset reconnect id self.reconnectId = null; // Apply pool connection handlers connection.on('error', connectionFailureHandler(self, 'error')); connection.on('close', connectionFailureHandler(self, 'close')); connection.on('timeout', connectionFailureHandler(self, 'timeout')); connection.on('parseError', connectionFailureHandler(self, 'parseError')); // Apply any auth to the connection reauthenticate(self, this, function() { // Reset retries self.retriesLeft = self.options.reconnectTries; // Push to available connections self.availableConnections.push(connection); // Set the reconnectConnection to null self.reconnectConnection = null; // Emit reconnect event self.emit('reconnect', self); // Trigger execute to start everything up again _execute(self)(); }); }; }
[ "function", "_connectHandler", "(", "self", ")", "{", "return", "function", "(", ")", "{", "// Assign", "var", "connection", "=", "this", ";", "// Pool destroyed stop the connection", "if", "(", "self", ".", "state", "===", "DESTROYED", "||", "self", ".", "state", "===", "DESTROYING", ")", "{", "return", "connection", ".", "destroy", "(", ")", ";", "}", "// Clear out all handlers", "handlers", ".", "forEach", "(", "function", "(", "event", ")", "{", "connection", ".", "removeAllListeners", "(", "event", ")", ";", "}", ")", ";", "// Reset reconnect id", "self", ".", "reconnectId", "=", "null", ";", "// Apply pool connection handlers", "connection", ".", "on", "(", "'error'", ",", "connectionFailureHandler", "(", "self", ",", "'error'", ")", ")", ";", "connection", ".", "on", "(", "'close'", ",", "connectionFailureHandler", "(", "self", ",", "'close'", ")", ")", ";", "connection", ".", "on", "(", "'timeout'", ",", "connectionFailureHandler", "(", "self", ",", "'timeout'", ")", ")", ";", "connection", ".", "on", "(", "'parseError'", ",", "connectionFailureHandler", "(", "self", ",", "'parseError'", ")", ")", ";", "// Apply any auth to the connection", "reauthenticate", "(", "self", ",", "this", ",", "function", "(", ")", "{", "// Reset retries", "self", ".", "retriesLeft", "=", "self", ".", "options", ".", "reconnectTries", ";", "// Push to available connections", "self", ".", "availableConnections", ".", "push", "(", "connection", ")", ";", "// Set the reconnectConnection to null", "self", ".", "reconnectConnection", "=", "null", ";", "// Emit reconnect event", "self", ".", "emit", "(", "'reconnect'", ",", "self", ")", ";", "// Trigger execute to start everything up again", "_execute", "(", "self", ")", "(", ")", ";", "}", ")", ";", "}", ";", "}" ]
Got a connect handler
[ "Got", "a", "connect", "handler" ]
5adc639b88a0d72cbeef23a6b5df7f4540745089
https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb-core/lib/connection/pool.js#L379-L417
56,190
Industryswarm/isnode-mod-data
lib/mongodb/mongodb-core/lib/connection/pool.js
authenticateStragglers
function authenticateStragglers(self, connection, callback) { // Get any non authenticated connections var connections = self.nonAuthenticatedConnections.slice(0); var nonAuthenticatedConnections = self.nonAuthenticatedConnections; self.nonAuthenticatedConnections = []; // Establish if the connection need to be authenticated // Add to authentication list if // 1. we were in an authentication process when the operation was executed // 2. our current authentication timestamp is from the workItem one, meaning an auth has happened if ( connection.workItems.length === 1 && (connection.workItems[0].authenticating === true || (typeof connection.workItems[0].authenticatingTimestamp === 'number' && connection.workItems[0].authenticatingTimestamp !== self.authenticatingTimestamp)) ) { // Add connection to the list connections.push(connection); } // No connections need to be re-authenticated if (connections.length === 0) { // Release the connection back to the pool moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); // Finish return callback(); } // Apply re-authentication to all connections before releasing back to pool var connectionCount = connections.length; // Authenticate all connections for (var i = 0; i < connectionCount; i++) { reauthenticate(self, connections[i], function() { connectionCount = connectionCount - 1; if (connectionCount === 0) { // Put non authenticated connections in available connections self.availableConnections = self.availableConnections.concat( nonAuthenticatedConnections ); // Release the connection back to the pool moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); // Return callback(); } }); } }
javascript
function authenticateStragglers(self, connection, callback) { // Get any non authenticated connections var connections = self.nonAuthenticatedConnections.slice(0); var nonAuthenticatedConnections = self.nonAuthenticatedConnections; self.nonAuthenticatedConnections = []; // Establish if the connection need to be authenticated // Add to authentication list if // 1. we were in an authentication process when the operation was executed // 2. our current authentication timestamp is from the workItem one, meaning an auth has happened if ( connection.workItems.length === 1 && (connection.workItems[0].authenticating === true || (typeof connection.workItems[0].authenticatingTimestamp === 'number' && connection.workItems[0].authenticatingTimestamp !== self.authenticatingTimestamp)) ) { // Add connection to the list connections.push(connection); } // No connections need to be re-authenticated if (connections.length === 0) { // Release the connection back to the pool moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); // Finish return callback(); } // Apply re-authentication to all connections before releasing back to pool var connectionCount = connections.length; // Authenticate all connections for (var i = 0; i < connectionCount; i++) { reauthenticate(self, connections[i], function() { connectionCount = connectionCount - 1; if (connectionCount === 0) { // Put non authenticated connections in available connections self.availableConnections = self.availableConnections.concat( nonAuthenticatedConnections ); // Release the connection back to the pool moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); // Return callback(); } }); } }
[ "function", "authenticateStragglers", "(", "self", ",", "connection", ",", "callback", ")", "{", "// Get any non authenticated connections", "var", "connections", "=", "self", ".", "nonAuthenticatedConnections", ".", "slice", "(", "0", ")", ";", "var", "nonAuthenticatedConnections", "=", "self", ".", "nonAuthenticatedConnections", ";", "self", ".", "nonAuthenticatedConnections", "=", "[", "]", ";", "// Establish if the connection need to be authenticated", "// Add to authentication list if", "// 1. we were in an authentication process when the operation was executed", "// 2. our current authentication timestamp is from the workItem one, meaning an auth has happened", "if", "(", "connection", ".", "workItems", ".", "length", "===", "1", "&&", "(", "connection", ".", "workItems", "[", "0", "]", ".", "authenticating", "===", "true", "||", "(", "typeof", "connection", ".", "workItems", "[", "0", "]", ".", "authenticatingTimestamp", "===", "'number'", "&&", "connection", ".", "workItems", "[", "0", "]", ".", "authenticatingTimestamp", "!==", "self", ".", "authenticatingTimestamp", ")", ")", ")", "{", "// Add connection to the list", "connections", ".", "push", "(", "connection", ")", ";", "}", "// No connections need to be re-authenticated", "if", "(", "connections", ".", "length", "===", "0", ")", "{", "// Release the connection back to the pool", "moveConnectionBetween", "(", "connection", ",", "self", ".", "inUseConnections", ",", "self", ".", "availableConnections", ")", ";", "// Finish", "return", "callback", "(", ")", ";", "}", "// Apply re-authentication to all connections before releasing back to pool", "var", "connectionCount", "=", "connections", ".", "length", ";", "// Authenticate all connections", "for", "(", "var", "i", "=", "0", ";", "i", "<", "connectionCount", ";", "i", "++", ")", "{", "reauthenticate", "(", "self", ",", "connections", "[", "i", "]", ",", "function", "(", ")", "{", "connectionCount", "=", "connectionCount", "-", "1", ";", "if", "(", "connectionCount", "===", "0", ")", "{", "// Put non authenticated connections in available connections", "self", ".", "availableConnections", "=", "self", ".", "availableConnections", ".", "concat", "(", "nonAuthenticatedConnections", ")", ";", "// Release the connection back to the pool", "moveConnectionBetween", "(", "connection", ",", "self", ".", "inUseConnections", ",", "self", ".", "availableConnections", ")", ";", "// Return", "callback", "(", ")", ";", "}", "}", ")", ";", "}", "}" ]
Authenticate any straggler connections
[ "Authenticate", "any", "straggler", "connections" ]
5adc639b88a0d72cbeef23a6b5df7f4540745089
https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb-core/lib/connection/pool.js#L479-L526
56,191
Industryswarm/isnode-mod-data
lib/mongodb/mongodb-core/lib/connection/pool.js
authenticateLiveConnections
function authenticateLiveConnections(self, args, cb) { // Get the current viable connections var connections = self.allConnections(); // Allow nothing else to use the connections while we authenticate them self.availableConnections = []; self.inUseConnections = []; self.connectingConnections = []; var connectionsCount = connections.length; var error = null; // No connections available, return if (connectionsCount === 0) { self.authenticating = false; return callback(null); } // Authenticate the connections for (var i = 0; i < connections.length; i++) { authenticate(self, args, connections[i], function(err, result) { connectionsCount = connectionsCount - 1; // Store the error if (err) error = err; // Processed all connections if (connectionsCount === 0) { // Auth finished self.authenticating = false; // Add the connections back to available connections self.availableConnections = self.availableConnections.concat(connections); // We had an error, return it if (error) { // Log the error if (self.logger.isError()) { self.logger.error( f( '[%s] failed to authenticate against server %s:%s', self.id, self.options.host, self.options.port ) ); } return cb(error, result); } cb(null, result); } }); } }
javascript
function authenticateLiveConnections(self, args, cb) { // Get the current viable connections var connections = self.allConnections(); // Allow nothing else to use the connections while we authenticate them self.availableConnections = []; self.inUseConnections = []; self.connectingConnections = []; var connectionsCount = connections.length; var error = null; // No connections available, return if (connectionsCount === 0) { self.authenticating = false; return callback(null); } // Authenticate the connections for (var i = 0; i < connections.length; i++) { authenticate(self, args, connections[i], function(err, result) { connectionsCount = connectionsCount - 1; // Store the error if (err) error = err; // Processed all connections if (connectionsCount === 0) { // Auth finished self.authenticating = false; // Add the connections back to available connections self.availableConnections = self.availableConnections.concat(connections); // We had an error, return it if (error) { // Log the error if (self.logger.isError()) { self.logger.error( f( '[%s] failed to authenticate against server %s:%s', self.id, self.options.host, self.options.port ) ); } return cb(error, result); } cb(null, result); } }); } }
[ "function", "authenticateLiveConnections", "(", "self", ",", "args", ",", "cb", ")", "{", "// Get the current viable connections", "var", "connections", "=", "self", ".", "allConnections", "(", ")", ";", "// Allow nothing else to use the connections while we authenticate them", "self", ".", "availableConnections", "=", "[", "]", ";", "self", ".", "inUseConnections", "=", "[", "]", ";", "self", ".", "connectingConnections", "=", "[", "]", ";", "var", "connectionsCount", "=", "connections", ".", "length", ";", "var", "error", "=", "null", ";", "// No connections available, return", "if", "(", "connectionsCount", "===", "0", ")", "{", "self", ".", "authenticating", "=", "false", ";", "return", "callback", "(", "null", ")", ";", "}", "// Authenticate the connections", "for", "(", "var", "i", "=", "0", ";", "i", "<", "connections", ".", "length", ";", "i", "++", ")", "{", "authenticate", "(", "self", ",", "args", ",", "connections", "[", "i", "]", ",", "function", "(", "err", ",", "result", ")", "{", "connectionsCount", "=", "connectionsCount", "-", "1", ";", "// Store the error", "if", "(", "err", ")", "error", "=", "err", ";", "// Processed all connections", "if", "(", "connectionsCount", "===", "0", ")", "{", "// Auth finished", "self", ".", "authenticating", "=", "false", ";", "// Add the connections back to available connections", "self", ".", "availableConnections", "=", "self", ".", "availableConnections", ".", "concat", "(", "connections", ")", ";", "// We had an error, return it", "if", "(", "error", ")", "{", "// Log the error", "if", "(", "self", ".", "logger", ".", "isError", "(", ")", ")", "{", "self", ".", "logger", ".", "error", "(", "f", "(", "'[%s] failed to authenticate against server %s:%s'", ",", "self", ".", "id", ",", "self", ".", "options", ".", "host", ",", "self", ".", "options", ".", "port", ")", ")", ";", "}", "return", "cb", "(", "error", ",", "result", ")", ";", "}", "cb", "(", "null", ",", "result", ")", ";", "}", "}", ")", ";", "}", "}" ]
Authenticate all live connections
[ "Authenticate", "all", "live", "connections" ]
5adc639b88a0d72cbeef23a6b5df7f4540745089
https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb-core/lib/connection/pool.js#L801-L851
56,192
Industryswarm/isnode-mod-data
lib/mongodb/mongodb-core/lib/connection/pool.js
waitForLogout
function waitForLogout(self, cb) { if (!self.loggingout) return cb(); setTimeout(function() { waitForLogout(self, cb); }, 1); }
javascript
function waitForLogout(self, cb) { if (!self.loggingout) return cb(); setTimeout(function() { waitForLogout(self, cb); }, 1); }
[ "function", "waitForLogout", "(", "self", ",", "cb", ")", "{", "if", "(", "!", "self", ".", "loggingout", ")", "return", "cb", "(", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "waitForLogout", "(", "self", ",", "cb", ")", ";", "}", ",", "1", ")", ";", "}" ]
Wait for a logout in process to happen
[ "Wait", "for", "a", "logout", "in", "process", "to", "happen" ]
5adc639b88a0d72cbeef23a6b5df7f4540745089
https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb-core/lib/connection/pool.js#L854-L859
56,193
Industryswarm/isnode-mod-data
lib/mongodb/mongodb-core/lib/connection/pool.js
function(_connection) { return function() { // Destroyed state return if (self.state === DESTROYED || self.state === DESTROYING) { // Remove the connection from the list removeConnection(self, _connection); return _connection.destroy(); } // Destroy all event emitters handlers.forEach(function(e) { _connection.removeAllListeners(e); }); // Add the final handlers _connection.once('close', connectionFailureHandler(self, 'close')); _connection.once('error', connectionFailureHandler(self, 'error')); _connection.once('timeout', connectionFailureHandler(self, 'timeout')); _connection.once('parseError', connectionFailureHandler(self, 'parseError')); // Signal reauthenticate(self, _connection, function(err) { if (self.state === DESTROYED || self.state === DESTROYING) { return _connection.destroy(); } // Remove the connection from the connectingConnections list removeConnection(self, _connection); // Handle error if (err) { return _connection.destroy(); } // If we are c at the moment // Do not automatially put in available connections // As we need to apply the credentials first if (self.authenticating) { self.nonAuthenticatedConnections.push(_connection); } else { // Push to available self.availableConnections.push(_connection); // Execute any work waiting _execute(self)(); } }); }; }
javascript
function(_connection) { return function() { // Destroyed state return if (self.state === DESTROYED || self.state === DESTROYING) { // Remove the connection from the list removeConnection(self, _connection); return _connection.destroy(); } // Destroy all event emitters handlers.forEach(function(e) { _connection.removeAllListeners(e); }); // Add the final handlers _connection.once('close', connectionFailureHandler(self, 'close')); _connection.once('error', connectionFailureHandler(self, 'error')); _connection.once('timeout', connectionFailureHandler(self, 'timeout')); _connection.once('parseError', connectionFailureHandler(self, 'parseError')); // Signal reauthenticate(self, _connection, function(err) { if (self.state === DESTROYED || self.state === DESTROYING) { return _connection.destroy(); } // Remove the connection from the connectingConnections list removeConnection(self, _connection); // Handle error if (err) { return _connection.destroy(); } // If we are c at the moment // Do not automatially put in available connections // As we need to apply the credentials first if (self.authenticating) { self.nonAuthenticatedConnections.push(_connection); } else { // Push to available self.availableConnections.push(_connection); // Execute any work waiting _execute(self)(); } }); }; }
[ "function", "(", "_connection", ")", "{", "return", "function", "(", ")", "{", "// Destroyed state return", "if", "(", "self", ".", "state", "===", "DESTROYED", "||", "self", ".", "state", "===", "DESTROYING", ")", "{", "// Remove the connection from the list", "removeConnection", "(", "self", ",", "_connection", ")", ";", "return", "_connection", ".", "destroy", "(", ")", ";", "}", "// Destroy all event emitters", "handlers", ".", "forEach", "(", "function", "(", "e", ")", "{", "_connection", ".", "removeAllListeners", "(", "e", ")", ";", "}", ")", ";", "// Add the final handlers", "_connection", ".", "once", "(", "'close'", ",", "connectionFailureHandler", "(", "self", ",", "'close'", ")", ")", ";", "_connection", ".", "once", "(", "'error'", ",", "connectionFailureHandler", "(", "self", ",", "'error'", ")", ")", ";", "_connection", ".", "once", "(", "'timeout'", ",", "connectionFailureHandler", "(", "self", ",", "'timeout'", ")", ")", ";", "_connection", ".", "once", "(", "'parseError'", ",", "connectionFailureHandler", "(", "self", ",", "'parseError'", ")", ")", ";", "// Signal", "reauthenticate", "(", "self", ",", "_connection", ",", "function", "(", "err", ")", "{", "if", "(", "self", ".", "state", "===", "DESTROYED", "||", "self", ".", "state", "===", "DESTROYING", ")", "{", "return", "_connection", ".", "destroy", "(", ")", ";", "}", "// Remove the connection from the connectingConnections list", "removeConnection", "(", "self", ",", "_connection", ")", ";", "// Handle error", "if", "(", "err", ")", "{", "return", "_connection", ".", "destroy", "(", ")", ";", "}", "// If we are c at the moment", "// Do not automatially put in available connections", "// As we need to apply the credentials first", "if", "(", "self", ".", "authenticating", ")", "{", "self", ".", "nonAuthenticatedConnections", ".", "push", "(", "_connection", ")", ";", "}", "else", "{", "// Push to available", "self", ".", "availableConnections", ".", "push", "(", "_connection", ")", ";", "// Execute any work waiting", "_execute", "(", "self", ")", "(", ")", ";", "}", "}", ")", ";", "}", ";", "}" ]
Handle successful connection
[ "Handle", "successful", "connection" ]
5adc639b88a0d72cbeef23a6b5df7f4540745089
https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb-core/lib/connection/pool.js#L1336-L1382
56,194
decanat/miscue
lib/miscue.js
Miscue
function Miscue(code, data) { if (!(this instanceof Miscue)) return new Miscue(code, data); return this.initialize(code, data); }
javascript
function Miscue(code, data) { if (!(this instanceof Miscue)) return new Miscue(code, data); return this.initialize(code, data); }
[ "function", "Miscue", "(", "code", ",", "data", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Miscue", ")", ")", "return", "new", "Miscue", "(", "code", ",", "data", ")", ";", "return", "this", ".", "initialize", "(", "code", ",", "data", ")", ";", "}" ]
Creates a new Miscue object @constructor @param {Number} code @param {Mixed} data [optional] @return {Object}
[ "Creates", "a", "new", "Miscue", "object" ]
45e4cbbfe0868c81cb5a407e6139656b237e9191
https://github.com/decanat/miscue/blob/45e4cbbfe0868c81cb5a407e6139656b237e9191/lib/miscue.js#L42-L47
56,195
meisterplayer/js-dev
gulp/eslint.js
createLint
function createLint(inPath, opts = {}) { if (!inPath) { throw new Error('Input path argument is required'); } return function lint() { return gulp.src(inPath) .pipe(eslint(opts)) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }; }
javascript
function createLint(inPath, opts = {}) { if (!inPath) { throw new Error('Input path argument is required'); } return function lint() { return gulp.src(inPath) .pipe(eslint(opts)) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }; }
[ "function", "createLint", "(", "inPath", ",", "opts", "=", "{", "}", ")", "{", "if", "(", "!", "inPath", ")", "{", "throw", "new", "Error", "(", "'Input path argument is required'", ")", ";", "}", "return", "function", "lint", "(", ")", "{", "return", "gulp", ".", "src", "(", "inPath", ")", ".", "pipe", "(", "eslint", "(", "opts", ")", ")", ".", "pipe", "(", "eslint", ".", "format", "(", ")", ")", ".", "pipe", "(", "eslint", ".", "failAfterError", "(", ")", ")", ";", "}", ";", "}" ]
Higher order function to create gulp function that lints files using eslint. @param {string|string[]} inPath The globs to the files that need to be copied. @param {Object} [opts={}] Options object to be passed to the gulp eslint plugin. @return {function} Function that can be used as a gulp task.
[ "Higher", "order", "function", "to", "create", "gulp", "function", "that", "lints", "files", "using", "eslint", "." ]
c2646678c49dcdaa120ba3f24824da52b0c63e31
https://github.com/meisterplayer/js-dev/blob/c2646678c49dcdaa120ba3f24824da52b0c63e31/gulp/eslint.js#L10-L21
56,196
angeloocana/joj-core
dist-esnext/Board.js
getStartEndRowsFromBoardSize
function getStartEndRowsFromBoardSize(boardSize) { const endRow = boardSize.y - 1; return { white: getStartEndRow(endRow, false), black: getStartEndRow(endRow, true) }; }
javascript
function getStartEndRowsFromBoardSize(boardSize) { const endRow = boardSize.y - 1; return { white: getStartEndRow(endRow, false), black: getStartEndRow(endRow, true) }; }
[ "function", "getStartEndRowsFromBoardSize", "(", "boardSize", ")", "{", "const", "endRow", "=", "boardSize", ".", "y", "-", "1", ";", "return", "{", "white", ":", "getStartEndRow", "(", "endRow", ",", "false", ")", ",", "black", ":", "getStartEndRow", "(", "endRow", ",", "true", ")", "}", ";", "}" ]
Takes a boardSize and return START and END rows for WHITE and BLACK. returns { white:{startRow, endRow}, black:{startRow, endRow} }
[ "Takes", "a", "boardSize", "and", "return", "START", "and", "END", "rows", "for", "WHITE", "and", "BLACK", "." ]
14bc7801c004271cefafff6cc0abb0c3173c805a
https://github.com/angeloocana/joj-core/blob/14bc7801c004271cefafff6cc0abb0c3173c805a/dist-esnext/Board.js#L37-L43
56,197
angeloocana/joj-core
dist-esnext/Board.js
getJumpPosition
function getJumpPosition(from, toJump, board) { const jumpXY = getJumpXY(from, toJump); if (!hasPosition(board, jumpXY)) return; const jumpPosition = getPositionFromBoard(board, jumpXY); if (Position.hasPiece(jumpPosition)) return; return jumpPosition; }
javascript
function getJumpPosition(from, toJump, board) { const jumpXY = getJumpXY(from, toJump); if (!hasPosition(board, jumpXY)) return; const jumpPosition = getPositionFromBoard(board, jumpXY); if (Position.hasPiece(jumpPosition)) return; return jumpPosition; }
[ "function", "getJumpPosition", "(", "from", ",", "toJump", ",", "board", ")", "{", "const", "jumpXY", "=", "getJumpXY", "(", "from", ",", "toJump", ")", ";", "if", "(", "!", "hasPosition", "(", "board", ",", "jumpXY", ")", ")", "return", ";", "const", "jumpPosition", "=", "getPositionFromBoard", "(", "board", ",", "jumpXY", ")", ";", "if", "(", "Position", ".", "hasPiece", "(", "jumpPosition", ")", ")", "return", ";", "return", "jumpPosition", ";", "}" ]
Returns the target board position from a jump if this position exists and is empty.
[ "Returns", "the", "target", "board", "position", "from", "a", "jump", "if", "this", "position", "exists", "and", "is", "empty", "." ]
14bc7801c004271cefafff6cc0abb0c3173c805a
https://github.com/angeloocana/joj-core/blob/14bc7801c004271cefafff6cc0abb0c3173c805a/dist-esnext/Board.js#L284-L292
56,198
s-p-n/devez-node-gyp
lib/install.js
isValid
function isValid (path, entry) { var isValid = valid(path) if (isValid) { log.verbose('extracted file from tarball', path) extractCount++ } else { // invalid log.silly('ignoring from tarball', path) } return isValid }
javascript
function isValid (path, entry) { var isValid = valid(path) if (isValid) { log.verbose('extracted file from tarball', path) extractCount++ } else { // invalid log.silly('ignoring from tarball', path) } return isValid }
[ "function", "isValid", "(", "path", ",", "entry", ")", "{", "var", "isValid", "=", "valid", "(", "path", ")", "if", "(", "isValid", ")", "{", "log", ".", "verbose", "(", "'extracted file from tarball'", ",", "path", ")", "extractCount", "++", "}", "else", "{", "// invalid", "log", ".", "silly", "(", "'ignoring from tarball'", ",", "path", ")", "}", "return", "isValid", "}" ]
checks if a file to be extracted from the tarball is valid. only .h header files and the gyp files get extracted
[ "checks", "if", "a", "file", "to", "be", "extracted", "from", "the", "tarball", "is", "valid", ".", "only", ".", "h", "header", "files", "and", "the", "gyp", "files", "get", "extracted" ]
a55f5b8c885c417e7d1ce0af5e16aabfaa6ed73e
https://github.com/s-p-n/devez-node-gyp/blob/a55f5b8c885c417e7d1ce0af5e16aabfaa6ed73e/lib/install.js#L155-L165
56,199
adoyle-h/config-sp
src/get.js
get
function get(path) { var conf = this; if (typeof path !== 'string') { throw new Error('path should be a string!'); } else if (path.length === 0) { throw new Error('path cannot be empty!'); } var result = baseGet(conf, getPathArray(path)); if (result === undefined) { throw new Error('the value is undefined!'); } else { bindGetMethod(result); // eslint-disable-line } return result; }
javascript
function get(path) { var conf = this; if (typeof path !== 'string') { throw new Error('path should be a string!'); } else if (path.length === 0) { throw new Error('path cannot be empty!'); } var result = baseGet(conf, getPathArray(path)); if (result === undefined) { throw new Error('the value is undefined!'); } else { bindGetMethod(result); // eslint-disable-line } return result; }
[ "function", "get", "(", "path", ")", "{", "var", "conf", "=", "this", ";", "if", "(", "typeof", "path", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "'path should be a string!'", ")", ";", "}", "else", "if", "(", "path", ".", "length", "===", "0", ")", "{", "throw", "new", "Error", "(", "'path cannot be empty!'", ")", ";", "}", "var", "result", "=", "baseGet", "(", "conf", ",", "getPathArray", "(", "path", ")", ")", ";", "if", "(", "result", "===", "undefined", ")", "{", "throw", "new", "Error", "(", "'the value is undefined!'", ")", ";", "}", "else", "{", "bindGetMethod", "(", "result", ")", ";", "// eslint-disable-line", "}", "return", "result", ";", "}" ]
Gets the property value at path of config. If the resolved value is undefined, it will throw an error. @param {String} path @return {*} @method get
[ "Gets", "the", "property", "value", "at", "path", "of", "config", ".", "If", "the", "resolved", "value", "is", "undefined", "it", "will", "throw", "an", "error", "." ]
cdfefc1b1c292d834b1144695bb284f0e26a6a77
https://github.com/adoyle-h/config-sp/blob/cdfefc1b1c292d834b1144695bb284f0e26a6a77/src/get.js#L64-L81