repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
deployd/dpd-dashboard
dashboard/js/lib/ui.js
Menu
function Menu() { ui.Emitter.call(this); this.items = {}; this.el = $(html).hide().appendTo('body'); this.el.hover(this.deselect.bind(this)); $('html').click(this.hide.bind(this)); this.on('show', this.bindKeyboardEvents.bind(this)); this.on('hide', this.unbindKeyboardEvents.bind(this)); }
javascript
function Menu() { ui.Emitter.call(this); this.items = {}; this.el = $(html).hide().appendTo('body'); this.el.hover(this.deselect.bind(this)); $('html').click(this.hide.bind(this)); this.on('show', this.bindKeyboardEvents.bind(this)); this.on('hide', this.unbindKeyboardEvents.bind(this)); }
[ "function", "Menu", "(", ")", "{", "ui", ".", "Emitter", ".", "call", "(", "this", ")", ";", "this", ".", "items", "=", "{", "}", ";", "this", ".", "el", "=", "$", "(", "html", ")", ".", "hide", "(", ")", ".", "appendTo", "(", "'body'", ")", ";", "this", ".", "el", ".", "hover", "(", "this", ".", "deselect", ".", "bind", "(", "this", ")", ")", ";", "$", "(", "'html'", ")", ".", "click", "(", "this", ".", "hide", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "on", "(", "'show'", ",", "this", ".", "bindKeyboardEvents", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "on", "(", "'hide'", ",", "this", ".", "unbindKeyboardEvents", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Initialize a new `Menu`. Emits: - "show" when shown - "hide" when hidden - "remove" with the item name when an item is removed - * menu item events are emitted when clicked @api public
[ "Initialize", "a", "new", "Menu", "." ]
1ffb4c09cbeba7bf040dfe388aa46f206292be18
https://github.com/deployd/dpd-dashboard/blob/1ffb4c09cbeba7bf040dfe388aa46f206292be18/dashboard/js/lib/ui.js#L1316-L1324
train
deployd/dpd-dashboard
dashboard/js/lib/ui.js
Card
function Card(front, back) { ui.Emitter.call(this); this._front = front || $('<p>front</p>'); this._back = back || $('<p>back</p>'); this.template = html; this.render(); }
javascript
function Card(front, back) { ui.Emitter.call(this); this._front = front || $('<p>front</p>'); this._back = back || $('<p>back</p>'); this.template = html; this.render(); }
[ "function", "Card", "(", "front", ",", "back", ")", "{", "ui", ".", "Emitter", ".", "call", "(", "this", ")", ";", "this", ".", "_front", "=", "front", "||", "$", "(", "'<p>front</p>'", ")", ";", "this", ".", "_back", "=", "back", "||", "$", "(", "'<p>back</p>'", ")", ";", "this", ".", "template", "=", "html", ";", "this", ".", "render", "(", ")", ";", "}" ]
Initialize a new `Card` with content for face `front` and `back`. Emits "flip" event. @param {Mixed} front @param {Mixed} back @api public
[ "Initialize", "a", "new", "Card", "with", "content", "for", "face", "front", "and", "back", "." ]
1ffb4c09cbeba7bf040dfe388aa46f206292be18
https://github.com/deployd/dpd-dashboard/blob/1ffb4c09cbeba7bf040dfe388aa46f206292be18/dashboard/js/lib/ui.js#L1557-L1563
train
segmentio/analytics.js-integration-tester
lib/index.js
stringify
function stringify(name, attrs) { var str = []; str.push('<' + name); each(function(val, key) { str.push(' ' + key + '="' + val + '"'); }, attrs); str.push('>'); // block if (name !== 'img') { str.push('</' + name + '>'); } return str.join(''); }
javascript
function stringify(name, attrs) { var str = []; str.push('<' + name); each(function(val, key) { str.push(' ' + key + '="' + val + '"'); }, attrs); str.push('>'); // block if (name !== 'img') { str.push('</' + name + '>'); } return str.join(''); }
[ "function", "stringify", "(", "name", ",", "attrs", ")", "{", "var", "str", "=", "[", "]", ";", "str", ".", "push", "(", "'<'", "+", "name", ")", ";", "each", "(", "function", "(", "val", ",", "key", ")", "{", "str", ".", "push", "(", "' '", "+", "key", "+", "'=\"'", "+", "val", "+", "'\"'", ")", ";", "}", ",", "attrs", ")", ";", "str", ".", "push", "(", "'>'", ")", ";", "if", "(", "name", "!==", "'img'", ")", "{", "str", ".", "push", "(", "'</'", "+", "name", "+", "'>'", ")", ";", "}", "return", "str", ".", "join", "(", "''", ")", ";", "}" ]
Create a DOM node string.
[ "Create", "a", "DOM", "node", "string", "." ]
38821ad2b5d96c0e81d8eeec9b6390de6360e4c3
https://github.com/segmentio/analytics.js-integration-tester/blob/38821ad2b5d96c0e81d8eeec9b6390de6360e4c3/lib/index.js#L438-L450
train
segmentio/analytics.js-integration-tester
lib/index.js
attributes
function attributes(node) { var obj = {}; each(function(attr) { obj[attr.name] = attr.value; }, node.attributes); return obj; }
javascript
function attributes(node) { var obj = {}; each(function(attr) { obj[attr.name] = attr.value; }, node.attributes); return obj; }
[ "function", "attributes", "(", "node", ")", "{", "var", "obj", "=", "{", "}", ";", "each", "(", "function", "(", "attr", ")", "{", "obj", "[", "attr", ".", "name", "]", "=", "attr", ".", "value", ";", "}", ",", "node", ".", "attributes", ")", ";", "return", "obj", ";", "}" ]
DOM node attributes as object. @param {Element} @return {Object}
[ "DOM", "node", "attributes", "as", "object", "." ]
38821ad2b5d96c0e81d8eeec9b6390de6360e4c3
https://github.com/segmentio/analytics.js-integration-tester/blob/38821ad2b5d96c0e81d8eeec9b6390de6360e4c3/lib/index.js#L458-L464
train
rmariuzzo/php-array-parser
index.js
function (source) { var ast = parser.parseEval(source) var array = ast.children.find((child) => child.kind === 'array') return parseValue(array) }
javascript
function (source) { var ast = parser.parseEval(source) var array = ast.children.find((child) => child.kind === 'array') return parseValue(array) }
[ "function", "(", "source", ")", "{", "var", "ast", "=", "parser", ".", "parseEval", "(", "source", ")", "var", "array", "=", "ast", ".", "children", ".", "find", "(", "(", "child", ")", "=>", "child", ".", "kind", "===", "'array'", ")", "return", "parseValue", "(", "array", ")", "}" ]
The PHP array parser. @param {String} source The PHP source contents. @return {Object} The parsed contents.
[ "The", "PHP", "array", "parser", "." ]
3ab01181032adbb29012f1d88896ec7c3e7b3f27
https://github.com/rmariuzzo/php-array-parser/blob/3ab01181032adbb29012f1d88896ec7c3e7b3f27/index.js#L12-L16
train
fabienb4/meteor-jsdoc
template/publish.js
function(data) { var tagDict = {}; if (data.tags) { each(data.tags, function(tag) { tagDict[tag.title] = tag.value; }); } return tagDict; }
javascript
function(data) { var tagDict = {}; if (data.tags) { each(data.tags, function(tag) { tagDict[tag.title] = tag.value; }); } return tagDict; }
[ "function", "(", "data", ")", "{", "var", "tagDict", "=", "{", "}", ";", "if", "(", "data", ".", "tags", ")", "{", "each", "(", "data", ".", "tags", ",", "function", "(", "tag", ")", "{", "tagDict", "[", "tag", ".", "title", "]", "=", "tag", ".", "value", ";", "}", ")", ";", "}", "return", "tagDict", ";", "}" ]
Get a tag dictionary from the tags field on the object, for custom fields like package @param {JSDocData} data The thing you get in the TaffyDB from JSDoc @return {Object} Keys are the parameter names, values are the values.
[ "Get", "a", "tag", "dictionary", "from", "the", "tags", "field", "on", "the", "object", "for", "custom", "fields", "like", "package" ]
f11ea7d694fac18025f53cb4826cafe80c69c625
https://github.com/fabienb4/meteor-jsdoc/blob/f11ea7d694fac18025f53cb4826cafe80c69c625/template/publish.js#L26-L36
train
jpodwys/cache-service-redis
redisCacheModule.js
prefixKey
function prefixKey(key) { if (self.nameSpace.length > 0 && !key.startsWith(self.nameSpace)) { return `${self.nameSpace}:${key}` } return key; }
javascript
function prefixKey(key) { if (self.nameSpace.length > 0 && !key.startsWith(self.nameSpace)) { return `${self.nameSpace}:${key}` } return key; }
[ "function", "prefixKey", "(", "key", ")", "{", "if", "(", "self", ".", "nameSpace", ".", "length", ">", "0", "&&", "!", "key", ".", "startsWith", "(", "self", ".", "nameSpace", ")", ")", "{", "return", "`", "${", "self", ".", "nameSpace", "}", "${", "key", "}", "`", "}", "return", "key", ";", "}" ]
Prefix key with namespace @param {string} key
[ "Prefix", "key", "with", "namespace" ]
d24c2917457b3c7731b9450fae0866c77f4a754c
https://github.com/jpodwys/cache-service-redis/blob/d24c2917457b3c7731b9450fae0866c77f4a754c/redisCacheModule.js#L124-L129
train
Jeff-Mott-OR/xmultiple
lib/index.js
xmultipleObjects
function xmultipleObjects(parents, proxyTarget = Object.create(null)) { // Create proxy that traps property accesses and forwards to each parent, returning the first defined value we find const forwardingProxy = new Proxy(proxyTarget, { get: function (proxyTarget, propertyKey) { // The proxy target gets first dibs // So, for example, if the proxy target is constructible, this will find its prototype if (Object.prototype.hasOwnProperty.call(proxyTarget, propertyKey)) { return proxyTarget[propertyKey]; } // Check every parent for the property key // We might find more than one defined value if multiple parents have the same property const foundValues = parents.reduce(function(foundValues, parent) { // It's important that we access the object property only once, // because it might be a getter that causes side-effects const currentValue = parent[propertyKey]; if (currentValue !== undefined) { foundValues.push(currentValue); } return foundValues; }, []); // Just because we found multiple values doesn't necessarily mean there's a collision // If, for example, we inherit from three plain objects that each inherit from Object.prototype, // then we would find three references for the key "hasOwnProperty" // But that doesn't mean we have three different functions; it means we have three references to the *same* function // Thus, if every found value compares strictly equal, then don't treat it as a collision const firstValue = foundValues[0]; const areFoundValuesSame = foundValues.every(value => value === firstValue); if (!areFoundValuesSame) { throw new Error(`Ambiguous property: ${propertyKey}.`); } return firstValue; } }); return forwardingProxy; }
javascript
function xmultipleObjects(parents, proxyTarget = Object.create(null)) { // Create proxy that traps property accesses and forwards to each parent, returning the first defined value we find const forwardingProxy = new Proxy(proxyTarget, { get: function (proxyTarget, propertyKey) { // The proxy target gets first dibs // So, for example, if the proxy target is constructible, this will find its prototype if (Object.prototype.hasOwnProperty.call(proxyTarget, propertyKey)) { return proxyTarget[propertyKey]; } // Check every parent for the property key // We might find more than one defined value if multiple parents have the same property const foundValues = parents.reduce(function(foundValues, parent) { // It's important that we access the object property only once, // because it might be a getter that causes side-effects const currentValue = parent[propertyKey]; if (currentValue !== undefined) { foundValues.push(currentValue); } return foundValues; }, []); // Just because we found multiple values doesn't necessarily mean there's a collision // If, for example, we inherit from three plain objects that each inherit from Object.prototype, // then we would find three references for the key "hasOwnProperty" // But that doesn't mean we have three different functions; it means we have three references to the *same* function // Thus, if every found value compares strictly equal, then don't treat it as a collision const firstValue = foundValues[0]; const areFoundValuesSame = foundValues.every(value => value === firstValue); if (!areFoundValuesSame) { throw new Error(`Ambiguous property: ${propertyKey}.`); } return firstValue; } }); return forwardingProxy; }
[ "function", "xmultipleObjects", "(", "parents", ",", "proxyTarget", "=", "Object", ".", "create", "(", "null", ")", ")", "{", "const", "forwardingProxy", "=", "new", "Proxy", "(", "proxyTarget", ",", "{", "get", ":", "function", "(", "proxyTarget", ",", "propertyKey", ")", "{", "if", "(", "Object", ".", "prototype", ".", "hasOwnProperty", ".", "call", "(", "proxyTarget", ",", "propertyKey", ")", ")", "{", "return", "proxyTarget", "[", "propertyKey", "]", ";", "}", "const", "foundValues", "=", "parents", ".", "reduce", "(", "function", "(", "foundValues", ",", "parent", ")", "{", "const", "currentValue", "=", "parent", "[", "propertyKey", "]", ";", "if", "(", "currentValue", "!==", "undefined", ")", "{", "foundValues", ".", "push", "(", "currentValue", ")", ";", "}", "return", "foundValues", ";", "}", ",", "[", "]", ")", ";", "const", "firstValue", "=", "foundValues", "[", "0", "]", ";", "const", "areFoundValuesSame", "=", "foundValues", ".", "every", "(", "value", "=>", "value", "===", "firstValue", ")", ";", "if", "(", "!", "areFoundValuesSame", ")", "{", "throw", "new", "Error", "(", "`", "${", "propertyKey", "}", "`", ")", ";", "}", "return", "firstValue", ";", "}", "}", ")", ";", "return", "forwardingProxy", ";", "}" ]
Creates a proxy that delegates to multiple other plain objects. @param {Array<Object>} parents The list of objects to delegate to. @param {any=Object.create(null)} proxyTarget Object for the proxy to virtualize. Some characteristics of the proxy are verified against the target. For example, for the proxy to be considered constructible, the target must be constructible. @return {Proxy}
[ "Creates", "a", "proxy", "that", "delegates", "to", "multiple", "other", "plain", "objects", "." ]
301e6ebff11bc80b04a285ebe010523b870acf3f
https://github.com/Jeff-Mott-OR/xmultiple/blob/301e6ebff11bc80b04a285ebe010523b870acf3f/lib/index.js#L77-L116
train
Jeff-Mott-OR/xmultiple
lib/index.js
xmultipleClasses
function xmultipleClasses(parents) { // A dummy constructor because a class can only extend something constructible function ConstructibleProxyTarget() {} // Replace prototype with a forwarding proxy to parents' prototypes ConstructibleProxyTarget.prototype = xmultipleObjects(parents.map(parent => parent.prototype)); // Forward static calls to parents const ClassForwardingProxy = xmultipleObjects(parents, ConstructibleProxyTarget); return ClassForwardingProxy; }
javascript
function xmultipleClasses(parents) { // A dummy constructor because a class can only extend something constructible function ConstructibleProxyTarget() {} // Replace prototype with a forwarding proxy to parents' prototypes ConstructibleProxyTarget.prototype = xmultipleObjects(parents.map(parent => parent.prototype)); // Forward static calls to parents const ClassForwardingProxy = xmultipleObjects(parents, ConstructibleProxyTarget); return ClassForwardingProxy; }
[ "function", "xmultipleClasses", "(", "parents", ")", "{", "function", "ConstructibleProxyTarget", "(", ")", "{", "}", "ConstructibleProxyTarget", ".", "prototype", "=", "xmultipleObjects", "(", "parents", ".", "map", "(", "parent", "=>", "parent", ".", "prototype", ")", ")", ";", "const", "ClassForwardingProxy", "=", "xmultipleObjects", "(", "parents", ",", "ConstructibleProxyTarget", ")", ";", "return", "ClassForwardingProxy", ";", "}" ]
Creates a proxy that delegates to multiple other constructor functions and their prototypes. @param {Array<ConstructorFunction>} parents The list of constructor functions to delegate to. @return {Proxy}
[ "Creates", "a", "proxy", "that", "delegates", "to", "multiple", "other", "constructor", "functions", "and", "their", "prototypes", "." ]
301e6ebff11bc80b04a285ebe010523b870acf3f
https://github.com/Jeff-Mott-OR/xmultiple/blob/301e6ebff11bc80b04a285ebe010523b870acf3f/lib/index.js#L126-L137
train
gethuman/fakeblock
lib/field.filter.js
removeItemsFromList
function removeItemsFromList(list, itemsToRemove) { var result = []; _.each(list, function (item) { var valid = true; for (var i = 0; i < itemsToRemove.length; i++) { // if the item match one of the items to remove don't includ it in the result list if (item.indexOf(itemsToRemove[i]) === 0) { valid = false; break; } } if (valid) { result.push(item); } }); return result; }
javascript
function removeItemsFromList(list, itemsToRemove) { var result = []; _.each(list, function (item) { var valid = true; for (var i = 0; i < itemsToRemove.length; i++) { // if the item match one of the items to remove don't includ it in the result list if (item.indexOf(itemsToRemove[i]) === 0) { valid = false; break; } } if (valid) { result.push(item); } }); return result; }
[ "function", "removeItemsFromList", "(", "list", ",", "itemsToRemove", ")", "{", "var", "result", "=", "[", "]", ";", "_", ".", "each", "(", "list", ",", "function", "(", "item", ")", "{", "var", "valid", "=", "true", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "itemsToRemove", ".", "length", ";", "i", "++", ")", "{", "if", "(", "item", ".", "indexOf", "(", "itemsToRemove", "[", "i", "]", ")", "===", "0", ")", "{", "valid", "=", "false", ";", "break", ";", "}", "}", "if", "(", "valid", ")", "{", "result", ".", "push", "(", "item", ")", ";", "}", "}", ")", ";", "return", "result", ";", "}" ]
Remove items from a list @param list @param itemsToRemove @returns {Array}
[ "Remove", "items", "from", "a", "list" ]
5ea5218dddb5e289db3a37b2ddeebf72cedeca30
https://github.com/gethuman/fakeblock/blob/5ea5218dddb5e289db3a37b2ddeebf72cedeca30/lib/field.filter.js#L17-L37
train
gethuman/fakeblock
lib/field.filter.js
getItemsFromList
function getItemsFromList(list, itemsToGet) { var result = []; _.each(list, function (item) { for (var i = 0; i < itemsToGet.length; i++) { if (item.indexOf(itemsToGet[i]) === 0) { result.push(item); } } }); return result; }
javascript
function getItemsFromList(list, itemsToGet) { var result = []; _.each(list, function (item) { for (var i = 0; i < itemsToGet.length; i++) { if (item.indexOf(itemsToGet[i]) === 0) { result.push(item); } } }); return result; }
[ "function", "getItemsFromList", "(", "list", ",", "itemsToGet", ")", "{", "var", "result", "=", "[", "]", ";", "_", ".", "each", "(", "list", ",", "function", "(", "item", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "itemsToGet", ".", "length", ";", "i", "++", ")", "{", "if", "(", "item", ".", "indexOf", "(", "itemsToGet", "[", "i", "]", ")", "===", "0", ")", "{", "result", ".", "push", "(", "item", ")", ";", "}", "}", "}", ")", ";", "return", "result", ";", "}" ]
Get all items from a list that match specified items. @param list @param itemsToGet @returns {Array}
[ "Get", "all", "items", "from", "a", "list", "that", "match", "specified", "items", "." ]
5ea5218dddb5e289db3a37b2ddeebf72cedeca30
https://github.com/gethuman/fakeblock/blob/5ea5218dddb5e289db3a37b2ddeebf72cedeca30/lib/field.filter.js#L45-L57
train
gethuman/fakeblock
lib/field.filter.js
removeFieldsFromObj
function removeFieldsFromObj(data, fieldsToRemove) { _.each(fieldsToRemove, function (fieldToRemove) { // if field to remove is in the data, just remove it and go to the next one if (data[fieldToRemove]) { delete data[fieldToRemove]; return true; } var fieldParts = fieldToRemove.split('.'); var fieldPart; var dataPointer = data; var len = fieldParts.length; for (var i = 0; i < len; i++) { fieldPart = fieldParts[i]; // if the field doesn't exist, break out of the loop if (!dataPointer[fieldPart]) { break; } // if we are at the end then delete the item from the updatedData else if (i === (len - 1)) { delete dataPointer[fieldPart]; } // else move the pointer down the object tree and go to the next iteration else { dataPointer = dataPointer[fieldPart]; } } return true; }); return data; }
javascript
function removeFieldsFromObj(data, fieldsToRemove) { _.each(fieldsToRemove, function (fieldToRemove) { // if field to remove is in the data, just remove it and go to the next one if (data[fieldToRemove]) { delete data[fieldToRemove]; return true; } var fieldParts = fieldToRemove.split('.'); var fieldPart; var dataPointer = data; var len = fieldParts.length; for (var i = 0; i < len; i++) { fieldPart = fieldParts[i]; // if the field doesn't exist, break out of the loop if (!dataPointer[fieldPart]) { break; } // if we are at the end then delete the item from the updatedData else if (i === (len - 1)) { delete dataPointer[fieldPart]; } // else move the pointer down the object tree and go to the next iteration else { dataPointer = dataPointer[fieldPart]; } } return true; }); return data; }
[ "function", "removeFieldsFromObj", "(", "data", ",", "fieldsToRemove", ")", "{", "_", ".", "each", "(", "fieldsToRemove", ",", "function", "(", "fieldToRemove", ")", "{", "if", "(", "data", "[", "fieldToRemove", "]", ")", "{", "delete", "data", "[", "fieldToRemove", "]", ";", "return", "true", ";", "}", "var", "fieldParts", "=", "fieldToRemove", ".", "split", "(", "'.'", ")", ";", "var", "fieldPart", ";", "var", "dataPointer", "=", "data", ";", "var", "len", "=", "fieldParts", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "fieldPart", "=", "fieldParts", "[", "i", "]", ";", "if", "(", "!", "dataPointer", "[", "fieldPart", "]", ")", "{", "break", ";", "}", "else", "if", "(", "i", "===", "(", "len", "-", "1", ")", ")", "{", "delete", "dataPointer", "[", "fieldPart", "]", ";", "}", "else", "{", "dataPointer", "=", "dataPointer", "[", "fieldPart", "]", ";", "}", "}", "return", "true", ";", "}", ")", ";", "return", "data", ";", "}" ]
Remove all specified fields from a given object based on input of field paths. The field path must match a object field to be removed. @param data Data to be changed @param fieldsToRemove An array of field paths @returns {{}}
[ "Remove", "all", "specified", "fields", "from", "a", "given", "object", "based", "on", "input", "of", "field", "paths", ".", "The", "field", "path", "must", "match", "a", "object", "field", "to", "be", "removed", "." ]
5ea5218dddb5e289db3a37b2ddeebf72cedeca30
https://github.com/gethuman/fakeblock/blob/5ea5218dddb5e289db3a37b2ddeebf72cedeca30/lib/field.filter.js#L67-L101
train
gethuman/fakeblock
lib/field.filter.js
getFieldsFromObj
function getFieldsFromObj(data, fieldsToGet) { var newObj = {}; _.each(fieldsToGet, function (fieldToGet) { // if the field to get is in the data, then just transfer it over and that is it if (data.hasOwnProperty(fieldToGet)) { newObj[fieldToGet] = data[fieldToGet]; return true; } var fieldParts = fieldToGet.split('.'); var len = fieldParts.length; var dataPointer = data; var tempPointer = newObj; var fieldPart, i; for (i = 0; i < len; i++) { fieldPart = fieldParts[i]; // if doesn't exist, then break out of loop as there is no value in data for this if (typeof dataPointer[fieldPart] === 'undefined') { break; } // else we are at the end, so copy this value to the newObj else if (i === (len - 1)) { tempPointer[fieldPart] = dataPointer[fieldPart]; } else { dataPointer = dataPointer[fieldPart]; tempPointer = tempPointer[fieldPart] = tempPointer[fieldPart] || {}; } } return true; }); return newObj; }
javascript
function getFieldsFromObj(data, fieldsToGet) { var newObj = {}; _.each(fieldsToGet, function (fieldToGet) { // if the field to get is in the data, then just transfer it over and that is it if (data.hasOwnProperty(fieldToGet)) { newObj[fieldToGet] = data[fieldToGet]; return true; } var fieldParts = fieldToGet.split('.'); var len = fieldParts.length; var dataPointer = data; var tempPointer = newObj; var fieldPart, i; for (i = 0; i < len; i++) { fieldPart = fieldParts[i]; // if doesn't exist, then break out of loop as there is no value in data for this if (typeof dataPointer[fieldPart] === 'undefined') { break; } // else we are at the end, so copy this value to the newObj else if (i === (len - 1)) { tempPointer[fieldPart] = dataPointer[fieldPart]; } else { dataPointer = dataPointer[fieldPart]; tempPointer = tempPointer[fieldPart] = tempPointer[fieldPart] || {}; } } return true; }); return newObj; }
[ "function", "getFieldsFromObj", "(", "data", ",", "fieldsToGet", ")", "{", "var", "newObj", "=", "{", "}", ";", "_", ".", "each", "(", "fieldsToGet", ",", "function", "(", "fieldToGet", ")", "{", "if", "(", "data", ".", "hasOwnProperty", "(", "fieldToGet", ")", ")", "{", "newObj", "[", "fieldToGet", "]", "=", "data", "[", "fieldToGet", "]", ";", "return", "true", ";", "}", "var", "fieldParts", "=", "fieldToGet", ".", "split", "(", "'.'", ")", ";", "var", "len", "=", "fieldParts", ".", "length", ";", "var", "dataPointer", "=", "data", ";", "var", "tempPointer", "=", "newObj", ";", "var", "fieldPart", ",", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "fieldPart", "=", "fieldParts", "[", "i", "]", ";", "if", "(", "typeof", "dataPointer", "[", "fieldPart", "]", "===", "'undefined'", ")", "{", "break", ";", "}", "else", "if", "(", "i", "===", "(", "len", "-", "1", ")", ")", "{", "tempPointer", "[", "fieldPart", "]", "=", "dataPointer", "[", "fieldPart", "]", ";", "}", "else", "{", "dataPointer", "=", "dataPointer", "[", "fieldPart", "]", ";", "tempPointer", "=", "tempPointer", "[", "fieldPart", "]", "=", "tempPointer", "[", "fieldPart", "]", "||", "{", "}", ";", "}", "}", "return", "true", ";", "}", ")", ";", "return", "newObj", ";", "}" ]
Get all fields specified from an object @param data @param fieldsToGet An array of fields where each field is dot notation @returns {{}}
[ "Get", "all", "fields", "specified", "from", "an", "object" ]
5ea5218dddb5e289db3a37b2ddeebf72cedeca30
https://github.com/gethuman/fakeblock/blob/5ea5218dddb5e289db3a37b2ddeebf72cedeca30/lib/field.filter.js#L109-L146
train
gethuman/fakeblock
lib/field.filter.js
applyFilter
function applyFilter(data, restrictedFields, allowedFields) { var filterFunc; // if string, something like a sort where each word should be a value var isString = _.isString(data); if (isString) { data = data.split(' '); } if (restrictedFields) { filterFunc = _.isArray(data) ? removeItemsFromList : removeFieldsFromObj; data = filterFunc(data, restrictedFields); } else if (allowedFields) { filterFunc = _.isArray(data) ? getItemsFromList : getFieldsFromObj; data = filterFunc(data, allowedFields); } return isString ? data[0] : data; }
javascript
function applyFilter(data, restrictedFields, allowedFields) { var filterFunc; // if string, something like a sort where each word should be a value var isString = _.isString(data); if (isString) { data = data.split(' '); } if (restrictedFields) { filterFunc = _.isArray(data) ? removeItemsFromList : removeFieldsFromObj; data = filterFunc(data, restrictedFields); } else if (allowedFields) { filterFunc = _.isArray(data) ? getItemsFromList : getFieldsFromObj; data = filterFunc(data, allowedFields); } return isString ? data[0] : data; }
[ "function", "applyFilter", "(", "data", ",", "restrictedFields", ",", "allowedFields", ")", "{", "var", "filterFunc", ";", "var", "isString", "=", "_", ".", "isString", "(", "data", ")", ";", "if", "(", "isString", ")", "{", "data", "=", "data", ".", "split", "(", "' '", ")", ";", "}", "if", "(", "restrictedFields", ")", "{", "filterFunc", "=", "_", ".", "isArray", "(", "data", ")", "?", "removeItemsFromList", ":", "removeFieldsFromObj", ";", "data", "=", "filterFunc", "(", "data", ",", "restrictedFields", ")", ";", "}", "else", "if", "(", "allowedFields", ")", "{", "filterFunc", "=", "_", ".", "isArray", "(", "data", ")", "?", "getItemsFromList", ":", "getFieldsFromObj", ";", "data", "=", "filterFunc", "(", "data", ",", "allowedFields", ")", ";", "}", "return", "isString", "?", "data", "[", "0", "]", ":", "data", ";", "}" ]
Apply the appropriate filter based on the input data @param data @param restrictedFields @param allowedFields @returns {{}}
[ "Apply", "the", "appropriate", "filter", "based", "on", "the", "input", "data" ]
5ea5218dddb5e289db3a37b2ddeebf72cedeca30
https://github.com/gethuman/fakeblock/blob/5ea5218dddb5e289db3a37b2ddeebf72cedeca30/lib/field.filter.js#L156-L173
train
glenjamin/devboard
example/datatypes.card.js
function(card) { return ( <div> <p> <button onClick={() => card.setState({ n: 0 })}> ZERO </button> <button onClick={() => card.setState(s => ({ n: s.n + 1 }))}> INC </button> <button onClick={() => card.setState(s => ({ n: s.n - 1 }))}> DEC </button> </p> <p> The current value of <kbd>n</kbd> is <kbd>{card.state.n}</kbd> </p> </div> ); }
javascript
function(card) { return ( <div> <p> <button onClick={() => card.setState({ n: 0 })}> ZERO </button> <button onClick={() => card.setState(s => ({ n: s.n + 1 }))}> INC </button> <button onClick={() => card.setState(s => ({ n: s.n - 1 }))}> DEC </button> </p> <p> The current value of <kbd>n</kbd> is <kbd>{card.state.n}</kbd> </p> </div> ); }
[ "function", "(", "card", ")", "{", "return", "(", "<", "div", ">", " ", "<", "p", ">", " ", "<", "button", "onClick", "=", "{", "(", ")", "=>", "card", ".", "setState", "(", "{", "n", ":", "0", "}", ")", "}", ">", " ZERO ", "<", "/", "button", ">", " ", "<", "button", "onClick", "=", "{", "(", ")", "=>", "card", ".", "setState", "(", "s", "=>", "(", "{", "n", ":", "s", ".", "n", "+", "1", "}", ")", ")", "}", ">", " INC ", "<", "/", "button", ">", " ", "<", "button", "onClick", "=", "{", "(", ")", "=>", "card", ".", "setState", "(", "s", "=>", "(", "{", "n", ":", "s", ".", "n", "-", "1", "}", ")", ")", "}", ">", " DEC ", "<", "/", "button", ">", " ", "<", "/", "p", ">", " ", "<", "p", ">", " The current value of ", "<", "kbd", ">", "n", "<", "/", "kbd", ">", " is ", "<", "kbd", ">", "{", "card", ".", "state", ".", "n", "}", "<", "/", "kbd", ">", " ", "<", "/", "p", ">", " ", "<", "/", "div", ">", ")", ";", "}" ]
func-state
[ "func", "-", "state" ]
c02080a25feac6672fa305a6d86514df0dc83944
https://github.com/glenjamin/devboard/blob/c02080a25feac6672fa305a6d86514df0dc83944/example/datatypes.card.js#L62-L81
train
glenjamin/devboard
example/datatypes.card.js
function(card) { var bg = ['#333', '#ccc'][card.state]; return ( <div style={{ width: 100, height: 50, lineHeight: '50px', margin: '0 auto', textAlign: 'center', border: '1px solid black', transition: 'background-color 3s', backgroundColor: bg, color: 'white' }}> {bg} </div> ); }
javascript
function(card) { var bg = ['#333', '#ccc'][card.state]; return ( <div style={{ width: 100, height: 50, lineHeight: '50px', margin: '0 auto', textAlign: 'center', border: '1px solid black', transition: 'background-color 3s', backgroundColor: bg, color: 'white' }}> {bg} </div> ); }
[ "function", "(", "card", ")", "{", "var", "bg", "=", "[", "'#333'", ",", "'#ccc'", "]", "[", "card", ".", "state", "]", ";", "return", "(", "<", "div", "style", "=", "{", "{", "width", ":", "100", ",", "height", ":", "50", ",", "lineHeight", ":", "'50px'", ",", "margin", ":", "'0 auto'", ",", "textAlign", ":", "'center'", ",", "border", ":", "'1px solid black'", ",", "transition", ":", "'background-color 3s'", ",", "backgroundColor", ":", "bg", ",", "color", ":", "'white'", "}", "}", ">", " ", "{", "bg", "}", " ", "<", "/", "div", ">", ")", ";", "}" ]
state-timer
[ "state", "-", "timer" ]
c02080a25feac6672fa305a6d86514df0dc83944
https://github.com/glenjamin/devboard/blob/c02080a25feac6672fa305a6d86514df0dc83944/example/datatypes.card.js#L109-L125
train
glenjamin/devboard
example/datatypes.card.js
function(card) { return devboard.DOMNode( function render(node) { node.innerHTML = ( '<button>I can count to: ' + card.state + '</button>' ); node.onclick = () => card.setState(n => n + 1); } ); }
javascript
function(card) { return devboard.DOMNode( function render(node) { node.innerHTML = ( '<button>I can count to: ' + card.state + '</button>' ); node.onclick = () => card.setState(n => n + 1); } ); }
[ "function", "(", "card", ")", "{", "return", "devboard", ".", "DOMNode", "(", "function", "render", "(", "node", ")", "{", "node", ".", "innerHTML", "=", "(", "'<button>I can count to: '", "+", "card", ".", "state", "+", "'</button>'", ")", ";", "node", ".", "onclick", "=", "(", ")", "=>", "card", ".", "setState", "(", "n", "=>", "n", "+", "1", ")", ";", "}", ")", ";", "}" ]
dom-state
[ "dom", "-", "state" ]
c02080a25feac6672fa305a6d86514df0dc83944
https://github.com/glenjamin/devboard/blob/c02080a25feac6672fa305a6d86514df0dc83944/example/datatypes.card.js#L242-L253
train
mikolalysenko/to-px
browser.js
getSizeBrutal
function getSizeBrutal(unit, element) { var testDIV = document.createElement('div') testDIV.style['height'] = '128' + unit element.appendChild(testDIV) var size = getPropertyInPX(testDIV, 'height') / 128 element.removeChild(testDIV) return size }
javascript
function getSizeBrutal(unit, element) { var testDIV = document.createElement('div') testDIV.style['height'] = '128' + unit element.appendChild(testDIV) var size = getPropertyInPX(testDIV, 'height') / 128 element.removeChild(testDIV) return size }
[ "function", "getSizeBrutal", "(", "unit", ",", "element", ")", "{", "var", "testDIV", "=", "document", ".", "createElement", "(", "'div'", ")", "testDIV", ".", "style", "[", "'height'", "]", "=", "'128'", "+", "unit", "element", ".", "appendChild", "(", "testDIV", ")", "var", "size", "=", "getPropertyInPX", "(", "testDIV", ",", "'height'", ")", "/", "128", "element", ".", "removeChild", "(", "testDIV", ")", "return", "size", "}" ]
This brutal hack is needed
[ "This", "brutal", "hack", "is", "needed" ]
e42e61ac13ee7b9fe93c9f37eb331ab1213addf4
https://github.com/mikolalysenko/to-px/blob/e42e61ac13ee7b9fe93c9f37eb331ab1213addf4/browser.js#L16-L23
train
bryanrsmith/aurelia-react-loader
src/index.js
camelToKebab
function camelToKebab(str) { // Matches all places where a two upper case chars followed by a lower case char are and split them with an hyphen return str.replace(/([a-zA-Z])([A-Z][a-z])/g, (match, before, after) => `${before.toLowerCase()}-${after.toLowerCase()}` ).toLowerCase(); }
javascript
function camelToKebab(str) { // Matches all places where a two upper case chars followed by a lower case char are and split them with an hyphen return str.replace(/([a-zA-Z])([A-Z][a-z])/g, (match, before, after) => `${before.toLowerCase()}-${after.toLowerCase()}` ).toLowerCase(); }
[ "function", "camelToKebab", "(", "str", ")", "{", "return", "str", ".", "replace", "(", "/", "([a-zA-Z])([A-Z][a-z])", "/", "g", ",", "(", "match", ",", "before", ",", "after", ")", "=>", "`", "${", "before", ".", "toLowerCase", "(", ")", "}", "${", "after", ".", "toLowerCase", "(", ")", "}", "`", ")", ".", "toLowerCase", "(", ")", ";", "}" ]
Converts camel case to kebab case @param {string} str @returns {string}
[ "Converts", "camel", "case", "to", "kebab", "case" ]
a3072194e003f11e716a96c9be0157a56071acde
https://github.com/bryanrsmith/aurelia-react-loader/blob/a3072194e003f11e716a96c9be0157a56071acde/src/index.js#L40-L45
train
bryanrsmith/aurelia-react-loader
src/index.js
wrapComponent
function wrapComponent(component, elementName) { let bindableProps = []; if (component.propTypes) { bindableProps = Object.keys(component.propTypes).map(prop => bindable({ name: prop, attribute: camelToKebab(prop), changeHandler: 'updateProps', defaultBindingMode: 1 })); } return decorators( noView(), customElement(elementName), bindable({name: 'props', attribute: 'props', changeHandler: 'updateProps', defaultBindingMode: 1}), ...bindableProps ).on(createWrapperClass(component)); }
javascript
function wrapComponent(component, elementName) { let bindableProps = []; if (component.propTypes) { bindableProps = Object.keys(component.propTypes).map(prop => bindable({ name: prop, attribute: camelToKebab(prop), changeHandler: 'updateProps', defaultBindingMode: 1 })); } return decorators( noView(), customElement(elementName), bindable({name: 'props', attribute: 'props', changeHandler: 'updateProps', defaultBindingMode: 1}), ...bindableProps ).on(createWrapperClass(component)); }
[ "function", "wrapComponent", "(", "component", ",", "elementName", ")", "{", "let", "bindableProps", "=", "[", "]", ";", "if", "(", "component", ".", "propTypes", ")", "{", "bindableProps", "=", "Object", ".", "keys", "(", "component", ".", "propTypes", ")", ".", "map", "(", "prop", "=>", "bindable", "(", "{", "name", ":", "prop", ",", "attribute", ":", "camelToKebab", "(", "prop", ")", ",", "changeHandler", ":", "'updateProps'", ",", "defaultBindingMode", ":", "1", "}", ")", ")", ";", "}", "return", "decorators", "(", "noView", "(", ")", ",", "customElement", "(", "elementName", ")", ",", "bindable", "(", "{", "name", ":", "'props'", ",", "attribute", ":", "'props'", ",", "changeHandler", ":", "'updateProps'", ",", "defaultBindingMode", ":", "1", "}", ")", ",", "...", "bindableProps", ")", ".", "on", "(", "createWrapperClass", "(", "component", ")", ")", ";", "}" ]
Wrap the React components into an ViewModel with bound attributes for the defined PropTypes @param {Object} component @param {string} elementName @returns {Object}
[ "Wrap", "the", "React", "components", "into", "an", "ViewModel", "with", "bound", "attributes", "for", "the", "defined", "PropTypes" ]
a3072194e003f11e716a96c9be0157a56071acde
https://github.com/bryanrsmith/aurelia-react-loader/blob/a3072194e003f11e716a96c9be0157a56071acde/src/index.js#L53-L69
train
scootykins/4chan-list-webm
lib/list-webm.js
listWebm
function listWebm (...args) { let board let threadNo let protocol if (args[1] === undefined) { ;({ board, threadNo, protocol } = parseUrl(args[0])) } else { [ board, threadNo ] = args args[2] = args[2] || {} protocol = args[2].https ? 'https' : 'http' } const apiUrl = `${protocol}://a.4cdn.org/${board}/thread/${threadNo}.json` return axios.get(apiUrl).then(res => transform(res.data, protocol, board)) }
javascript
function listWebm (...args) { let board let threadNo let protocol if (args[1] === undefined) { ;({ board, threadNo, protocol } = parseUrl(args[0])) } else { [ board, threadNo ] = args args[2] = args[2] || {} protocol = args[2].https ? 'https' : 'http' } const apiUrl = `${protocol}://a.4cdn.org/${board}/thread/${threadNo}.json` return axios.get(apiUrl).then(res => transform(res.data, protocol, board)) }
[ "function", "listWebm", "(", "...", "args", ")", "{", "let", "board", "let", "threadNo", "let", "protocol", "if", "(", "args", "[", "1", "]", "===", "undefined", ")", "{", ";", "(", "{", "board", ",", "threadNo", ",", "protocol", "}", "=", "parseUrl", "(", "args", "[", "0", "]", ")", ")", "}", "else", "{", "[", "board", ",", "threadNo", "]", "=", "args", "args", "[", "2", "]", "=", "args", "[", "2", "]", "||", "{", "}", "protocol", "=", "args", "[", "2", "]", ".", "https", "?", "'https'", ":", "'http'", "}", "const", "apiUrl", "=", "`", "${", "protocol", "}", "${", "board", "}", "${", "threadNo", "}", "`", "return", "axios", ".", "get", "(", "apiUrl", ")", ".", "then", "(", "res", "=>", "transform", "(", "res", ".", "data", ",", "protocol", ",", "board", ")", ")", "}" ]
Get webm data from a thread @func listWebm @param {Array} args Argument array containing either a thread URL, or a board shortname and a thread number @returns {Promise<Object>} Resolves to JSON object with webm URLs
[ "Get", "webm", "data", "from", "a", "thread" ]
6936ddd659930ef26d2a0fe6c400e59095ffc727
https://github.com/scootykins/4chan-list-webm/blob/6936ddd659930ef26d2a0fe6c400e59095ffc727/lib/list-webm.js#L14-L30
train
bahmutov/grunt-nice-package
tasks/nice_package.js
tightenDependenciesVersions
function tightenDependenciesVersions(grunt, deps) { console.assert(deps, 'missing deps object'); Object.keys(deps).forEach(function (name) { var version = deps[name]; warnOnLooseVersion(grunt, name, version); version = tightenVersion(version); deps[name] = version; }); }
javascript
function tightenDependenciesVersions(grunt, deps) { console.assert(deps, 'missing deps object'); Object.keys(deps).forEach(function (name) { var version = deps[name]; warnOnLooseVersion(grunt, name, version); version = tightenVersion(version); deps[name] = version; }); }
[ "function", "tightenDependenciesVersions", "(", "grunt", ",", "deps", ")", "{", "console", ".", "assert", "(", "deps", ",", "'missing deps object'", ")", ";", "Object", ".", "keys", "(", "deps", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "var", "version", "=", "deps", "[", "name", "]", ";", "warnOnLooseVersion", "(", "grunt", ",", "name", ",", "version", ")", ";", "version", "=", "tightenVersion", "(", "version", ")", ";", "deps", "[", "name", "]", "=", "version", ";", "}", ")", ";", "}" ]
removes ~, ^, etc from dependencies versions
[ "removes", "~", "^", "etc", "from", "dependencies", "versions" ]
366c7819f6fef179478194d984bcab9aee04f28a
https://github.com/bahmutov/grunt-nice-package/blob/366c7819f6fef179478194d984bcab9aee04f28a/tasks/nice_package.js#L41-L49
train
scootykins/4chan-list-webm
lib/parse-url.js
parseUrl
function parseUrl (url) { const regex = /(https?).*\/(.+)\/thread\/(\d+)/g let protocol let board let threadNo try { [, protocol, board, threadNo] = regex.exec(url) } catch (err) { throw new Error('Invalid 4chan URL!') } return { protocol, board, threadNo: Number.parseInt(threadNo) } }
javascript
function parseUrl (url) { const regex = /(https?).*\/(.+)\/thread\/(\d+)/g let protocol let board let threadNo try { [, protocol, board, threadNo] = regex.exec(url) } catch (err) { throw new Error('Invalid 4chan URL!') } return { protocol, board, threadNo: Number.parseInt(threadNo) } }
[ "function", "parseUrl", "(", "url", ")", "{", "const", "regex", "=", "/", "(https?).*\\/(.+)\\/thread\\/(\\d+)", "/", "g", "let", "protocol", "let", "board", "let", "threadNo", "try", "{", "[", ",", "protocol", ",", "board", ",", "threadNo", "]", "=", "regex", ".", "exec", "(", "url", ")", "}", "catch", "(", "err", ")", "{", "throw", "new", "Error", "(", "'Invalid 4chan URL!'", ")", "}", "return", "{", "protocol", ",", "board", ",", "threadNo", ":", "Number", ".", "parseInt", "(", "threadNo", ")", "}", "}" ]
Extracts the protocol, board and thread number from a 4chan URL @func parseUrl @param {String} url A 4chan url @returns {Object} Object containing the protocol, board and thread number
[ "Extracts", "the", "protocol", "board", "and", "thread", "number", "from", "a", "4chan", "URL" ]
6936ddd659930ef26d2a0fe6c400e59095ffc727
https://github.com/scootykins/4chan-list-webm/blob/6936ddd659930ef26d2a0fe6c400e59095ffc727/lib/parse-url.js#L9-L26
train
Inist-CNRS/node-inotifywait
lib/inotifywait.js
function() { var mix = {}; [].forEach.call(arguments, function(arg) { for (var name in arg) { if (arg.hasOwnProperty(name)) { mix[name] = arg[name]; } } }); return mix; }
javascript
function() { var mix = {}; [].forEach.call(arguments, function(arg) { for (var name in arg) { if (arg.hasOwnProperty(name)) { mix[name] = arg[name]; } } }); return mix; }
[ "function", "(", ")", "{", "var", "mix", "=", "{", "}", ";", "[", "]", ".", "forEach", ".", "call", "(", "arguments", ",", "function", "(", "arg", ")", "{", "for", "(", "var", "name", "in", "arg", ")", "{", "if", "(", "arg", ".", "hasOwnProperty", "(", "name", ")", ")", "{", "mix", "[", "name", "]", "=", "arg", "[", "name", "]", ";", "}", "}", "}", ")", ";", "return", "mix", ";", "}" ]
Mixing object properties.
[ "Mixing", "object", "properties", "." ]
7b533cae9d4cf12f3257c913d0b6d95d44a630fd
https://github.com/Inist-CNRS/node-inotifywait/blob/7b533cae9d4cf12f3257c913d0b6d95d44a630fd/lib/inotifywait.js#L196-L206
train
nodemailer/libbase64
lib/libbase64.js
wrap
function wrap(str, lineLength) { str = (str || '').toString(); lineLength = lineLength || 76; if (str.length <= lineLength) { return str; } let result = []; let pos = 0; let chunkLength = lineLength * 1024; while (pos < str.length) { let wrappedLines = str .substr(pos, chunkLength) .replace(new RegExp('.{' + lineLength + '}', 'g'), '$&\r\n') .trim(); result.push(wrappedLines); pos += chunkLength; } return result.join('\r\n').trim(); }
javascript
function wrap(str, lineLength) { str = (str || '').toString(); lineLength = lineLength || 76; if (str.length <= lineLength) { return str; } let result = []; let pos = 0; let chunkLength = lineLength * 1024; while (pos < str.length) { let wrappedLines = str .substr(pos, chunkLength) .replace(new RegExp('.{' + lineLength + '}', 'g'), '$&\r\n') .trim(); result.push(wrappedLines); pos += chunkLength; } return result.join('\r\n').trim(); }
[ "function", "wrap", "(", "str", ",", "lineLength", ")", "{", "str", "=", "(", "str", "||", "''", ")", ".", "toString", "(", ")", ";", "lineLength", "=", "lineLength", "||", "76", ";", "if", "(", "str", ".", "length", "<=", "lineLength", ")", "{", "return", "str", ";", "}", "let", "result", "=", "[", "]", ";", "let", "pos", "=", "0", ";", "let", "chunkLength", "=", "lineLength", "*", "1024", ";", "while", "(", "pos", "<", "str", ".", "length", ")", "{", "let", "wrappedLines", "=", "str", ".", "substr", "(", "pos", ",", "chunkLength", ")", ".", "replace", "(", "new", "RegExp", "(", "'.{'", "+", "lineLength", "+", "'}'", ",", "'g'", ")", ",", "'$&\\r\\n'", ")", ".", "\\r", "\\n", ";", "trim", "(", ")", "}", "result", ".", "push", "(", "wrappedLines", ")", ";", "}" ]
Adds soft line breaks to a base64 string @param {String} str base64 encoded string that might need line wrapping @param {Number} [lineLength=76] Maximum allowed length for a line @returns {String} Soft-wrapped base64 encoded string
[ "Adds", "soft", "line", "breaks", "to", "a", "base64", "string" ]
eddbb21ed6beeed77812bfb1fba5e1ba96308c95
https://github.com/nodemailer/libbase64/blob/eddbb21ed6beeed77812bfb1fba5e1ba96308c95/lib/libbase64.js#L38-L59
train
socites/beyond
trash/applications/build/deploy/applications/js/application1/phonegap/android/eng/libraries/beyond/main/code.js
function (value) { var process = value.split('-'); value = beyond.css.values; for (var i in process) { value = value[process[i]]; if (typeof value === 'undefined') return; } return value; }
javascript
function (value) { var process = value.split('-'); value = beyond.css.values; for (var i in process) { value = value[process[i]]; if (typeof value === 'undefined') return; } return value; }
[ "function", "(", "value", ")", "{", "var", "process", "=", "value", ".", "split", "(", "'-'", ")", ";", "value", "=", "beyond", ".", "css", ".", "values", ";", "for", "(", "var", "i", "in", "process", ")", "{", "value", "=", "value", "[", "process", "[", "i", "]", "]", ";", "if", "(", "typeof", "value", "===", "'undefined'", ")", "return", ";", "}", "return", "value", ";", "}" ]
find a css value
[ "find", "a", "css", "value" ]
839d9534f73b669e511d7b2503a3f4f984ea3e0a
https://github.com/socites/beyond/blob/839d9534f73b669e511d7b2503a3f4f984ea3e0a/trash/applications/build/deploy/applications/js/application1/phonegap/android/eng/libraries/beyond/main/code.js#L1750-L1763
train
rap1ds/keyword
lib/keyword.js
createKeywordWrapper
function createKeywordWrapper(keywordsToRun) { var wrapper = function(next) { var args = _.rest(arguments); runner.run(keywordsToRun, keywords, args).then(next); }; return wrapper; }
javascript
function createKeywordWrapper(keywordsToRun) { var wrapper = function(next) { var args = _.rest(arguments); runner.run(keywordsToRun, keywords, args).then(next); }; return wrapper; }
[ "function", "createKeywordWrapper", "(", "keywordsToRun", ")", "{", "var", "wrapper", "=", "function", "(", "next", ")", "{", "var", "args", "=", "_", ".", "rest", "(", "arguments", ")", ";", "runner", ".", "run", "(", "keywordsToRun", ",", "keywords", ",", "args", ")", ".", "then", "(", "next", ")", ";", "}", ";", "return", "wrapper", ";", "}" ]
Take `keywordsToRun` and wrap the run command into a function, which can used as a new keyword Usage: ``` keywords["Login"] = createKeywordWrapper( "Go To Page", ["http://mysite.com/login"], "Fill In Credentials", ["user", "pa55w0rd"] "Click Element", ["#login-button"] ); ``` Now you can use the new `Login` keywords like this: key.run("Login").then( ... )
[ "Take", "keywordsToRun", "and", "wrap", "the", "run", "command", "into", "a", "function", "which", "can", "used", "as", "a", "new", "keyword" ]
860fea352a16c6dacbee2727fe408ddc19a79715
https://github.com/rap1ds/keyword/blob/860fea352a16c6dacbee2727fe408ddc19a79715/lib/keyword.js#L41-L47
train
rap1ds/keyword
lib/helpers.js
createKeywords
function createKeywords(args) { // TODO Hmm.. Circular dependency... something smells here... var validators = require('./validators'); var keys = []; for(var i = 0; i < args.length; i++) { var keyword = {name: args[i]}; if(_.isArray(args[i + 1])) { i++; keyword.args = args[i]; } if(validators.isReturn(args[i + 1])) { i++; keyword.returnVar = pickReturnVar(args[i]); } keys.push(keyword); } return keys; }
javascript
function createKeywords(args) { // TODO Hmm.. Circular dependency... something smells here... var validators = require('./validators'); var keys = []; for(var i = 0; i < args.length; i++) { var keyword = {name: args[i]}; if(_.isArray(args[i + 1])) { i++; keyword.args = args[i]; } if(validators.isReturn(args[i + 1])) { i++; keyword.returnVar = pickReturnVar(args[i]); } keys.push(keyword); } return keys; }
[ "function", "createKeywords", "(", "args", ")", "{", "var", "validators", "=", "require", "(", "'./validators'", ")", ";", "var", "keys", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "args", ".", "length", ";", "i", "++", ")", "{", "var", "keyword", "=", "{", "name", ":", "args", "[", "i", "]", "}", ";", "if", "(", "_", ".", "isArray", "(", "args", "[", "i", "+", "1", "]", ")", ")", "{", "i", "++", ";", "keyword", ".", "args", "=", "args", "[", "i", "]", ";", "}", "if", "(", "validators", ".", "isReturn", "(", "args", "[", "i", "+", "1", "]", ")", ")", "{", "i", "++", ";", "keyword", ".", "returnVar", "=", "pickReturnVar", "(", "args", "[", "i", "]", ")", ";", "}", "keys", ".", "push", "(", "keyword", ")", ";", "}", "return", "keys", ";", "}" ]
Take arguments passed to `key.def` function. Return keyword objs.
[ "Take", "arguments", "passed", "to", "key", ".", "def", "function", ".", "Return", "keyword", "objs", "." ]
860fea352a16c6dacbee2727fe408ddc19a79715
https://github.com/rap1ds/keyword/blob/860fea352a16c6dacbee2727fe408ddc19a79715/lib/helpers.js#L78-L98
train
rap1ds/keyword
lib/helpers.js
mergeArray
function mergeArray(arr, mergeItems) { var mergeKeys = _.chain(mergeItems) .keys(mergeItems) .map(Number) .value(); var maxId = _.max(mergeKeys); return rangeWhile(function(i) { return i < (maxId + 1) || arr.length; }, function(i) { return _.contains(mergeKeys, i) ? mergeItems[i] : arr.shift(); }); }
javascript
function mergeArray(arr, mergeItems) { var mergeKeys = _.chain(mergeItems) .keys(mergeItems) .map(Number) .value(); var maxId = _.max(mergeKeys); return rangeWhile(function(i) { return i < (maxId + 1) || arr.length; }, function(i) { return _.contains(mergeKeys, i) ? mergeItems[i] : arr.shift(); }); }
[ "function", "mergeArray", "(", "arr", ",", "mergeItems", ")", "{", "var", "mergeKeys", "=", "_", ".", "chain", "(", "mergeItems", ")", ".", "keys", "(", "mergeItems", ")", ".", "map", "(", "Number", ")", ".", "value", "(", ")", ";", "var", "maxId", "=", "_", ".", "max", "(", "mergeKeys", ")", ";", "return", "rangeWhile", "(", "function", "(", "i", ")", "{", "return", "i", "<", "(", "maxId", "+", "1", ")", "||", "arr", ".", "length", ";", "}", ",", "function", "(", "i", ")", "{", "return", "_", ".", "contains", "(", "mergeKeys", ",", "i", ")", "?", "mergeItems", "[", "i", "]", ":", "arr", ".", "shift", "(", ")", ";", "}", ")", ";", "}" ]
Take `array` and `mergeItems` and merge them together. ## Params: - `array` just a regular array - `mergeItems` an object of `index` and `value` pairs ## Example mergeArray([], {1: true, 3: false}) => [undefined, true, undefined, false] mergeArray([1, 2, 3], {1: true, 3: false}) => [1, true, 2, false, 3]
[ "Take", "array", "and", "mergeItems", "and", "merge", "them", "together", "." ]
860fea352a16c6dacbee2727fe408ddc19a79715
https://github.com/rap1ds/keyword/blob/860fea352a16c6dacbee2727fe408ddc19a79715/lib/helpers.js#L175-L188
train
bitwalker/keys.js
src/keys.js
areDefined
function areDefined() { var objects = Array.prototype.slice.call(arguments); for (var i = 0; i < objects.length; i++) { if (objects[i] !== null && typeof objects[i] === 'undefined') return false; } return true; }
javascript
function areDefined() { var objects = Array.prototype.slice.call(arguments); for (var i = 0; i < objects.length; i++) { if (objects[i] !== null && typeof objects[i] === 'undefined') return false; } return true; }
[ "function", "areDefined", "(", ")", "{", "var", "objects", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "objects", ".", "length", ";", "i", "++", ")", "{", "if", "(", "objects", "[", "i", "]", "!==", "null", "&&", "typeof", "objects", "[", "i", "]", "===", "'undefined'", ")", "return", "false", ";", "}", "return", "true", ";", "}" ]
Determine if all of the provided object arguments are defined. Useful for argument validation within functions. @param {object} objects* - A variadic number of object arguments to check @return {boolean}
[ "Determine", "if", "all", "of", "the", "provided", "object", "arguments", "are", "defined", ".", "Useful", "for", "argument", "validation", "within", "functions", "." ]
fadb8834499d656960b28d405f44904f2b3b1b77
https://github.com/bitwalker/keys.js/blob/fadb8834499d656960b28d405f44904f2b3b1b77/src/keys.js#L44-L51
train
bitwalker/keys.js
src/keys.js
isObject
function isObject(obj) { if (!obj || !obj.constructor || obj.constructor.name !== 'Object') return false; else return true; }
javascript
function isObject(obj) { if (!obj || !obj.constructor || obj.constructor.name !== 'Object') return false; else return true; }
[ "function", "isObject", "(", "obj", ")", "{", "if", "(", "!", "obj", "||", "!", "obj", ".", "constructor", "||", "obj", ".", "constructor", ".", "name", "!==", "'Object'", ")", "return", "false", ";", "else", "return", "true", ";", "}" ]
Determine if the provided argument is an object @param {object} obj @return {Boolean}
[ "Determine", "if", "the", "provided", "argument", "is", "an", "object" ]
fadb8834499d656960b28d405f44904f2b3b1b77
https://github.com/bitwalker/keys.js/blob/fadb8834499d656960b28d405f44904f2b3b1b77/src/keys.js#L58-L62
train
bitwalker/keys.js
src/keys.js
tap
function tap(collection, fn, debugOnly) { if (!debugOnly || exports.debug) { // Clone the original array to prevent tampering, and send each element to the tap collection.slice().forEach(function(element) { fn.call(null, element); }); } return collection; }
javascript
function tap(collection, fn, debugOnly) { if (!debugOnly || exports.debug) { // Clone the original array to prevent tampering, and send each element to the tap collection.slice().forEach(function(element) { fn.call(null, element); }); } return collection; }
[ "function", "tap", "(", "collection", ",", "fn", ",", "debugOnly", ")", "{", "if", "(", "!", "debugOnly", "||", "exports", ".", "debug", ")", "{", "collection", ".", "slice", "(", ")", ".", "forEach", "(", "function", "(", "element", ")", "{", "fn", ".", "call", "(", "null", ",", "element", ")", ";", "}", ")", ";", "}", "return", "collection", ";", "}" ]
Allows you to tap into the current set of elements without affecting them in any way, additionally allowing you to chain calls together with this in the middle for debugging @static @param {array} collection - The array to tap @param {function} fn - The function to call for each element the tap encounters @param {boolean} debugOnly - If true, will only execute the tap fn if debug === true, defaults to false (always on)
[ "Allows", "you", "to", "tap", "into", "the", "current", "set", "of", "elements", "without", "affecting", "them", "in", "any", "way", "additionally", "allowing", "you", "to", "chain", "calls", "together", "with", "this", "in", "the", "middle", "for", "debugging" ]
fadb8834499d656960b28d405f44904f2b3b1b77
https://github.com/bitwalker/keys.js/blob/fadb8834499d656960b28d405f44904f2b3b1b77/src/keys.js#L194-L200
train
bitwalker/keys.js
src/keys.js
zipmap
function zipmap(collection) { var arrays = Array.prototype.slice.call(arguments, 1); return collection.map(function(element, i) { var others = []; for (var j = 0; j < arrays.length; j++) { var el = arrays[j] && arrays[j][i]; others.push(el !== null && typeof el !== 'undefined' ? el : null); } return [element].concat(others); }); }
javascript
function zipmap(collection) { var arrays = Array.prototype.slice.call(arguments, 1); return collection.map(function(element, i) { var others = []; for (var j = 0; j < arrays.length; j++) { var el = arrays[j] && arrays[j][i]; others.push(el !== null && typeof el !== 'undefined' ? el : null); } return [element].concat(others); }); }
[ "function", "zipmap", "(", "collection", ")", "{", "var", "arrays", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "return", "collection", ".", "map", "(", "function", "(", "element", ",", "i", ")", "{", "var", "others", "=", "[", "]", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "arrays", ".", "length", ";", "j", "++", ")", "{", "var", "el", "=", "arrays", "[", "j", "]", "&&", "arrays", "[", "j", "]", "[", "i", "]", ";", "others", ".", "push", "(", "el", "!==", "null", "&&", "typeof", "el", "!==", "'undefined'", "?", "el", ":", "null", ")", ";", "}", "return", "[", "element", "]", ".", "concat", "(", "others", ")", ";", "}", ")", ";", "}" ]
Produces an array of arrays which are the result of zipping together the elements of `this` and the array arguments. If any of the array arguments are longer than `this`, their remaining elements will be skipped. If any of the array arguments are shorter than `this`, their missing elements will be replaced with null. @static @param {array} collection - The source array @param {array} arrays* - A variadic number of arrays to be zipmapped
[ "Produces", "an", "array", "of", "arrays", "which", "are", "the", "result", "of", "zipping", "together", "the", "elements", "of", "this", "and", "the", "array", "arguments", ".", "If", "any", "of", "the", "array", "arguments", "are", "longer", "than", "this", "their", "remaining", "elements", "will", "be", "skipped", ".", "If", "any", "of", "the", "array", "arguments", "are", "shorter", "than", "this", "their", "missing", "elements", "will", "be", "replaced", "with", "null", "." ]
fadb8834499d656960b28d405f44904f2b3b1b77
https://github.com/bitwalker/keys.js/blob/fadb8834499d656960b28d405f44904f2b3b1b77/src/keys.js#L212-L222
train
bitwalker/keys.js
src/keys.js
endsWith
function endsWith(str, ending) { if (str.length - ending.length === str.lastIndexOf(ending)) return true; else return false; }
javascript
function endsWith(str, ending) { if (str.length - ending.length === str.lastIndexOf(ending)) return true; else return false; }
[ "function", "endsWith", "(", "str", ",", "ending", ")", "{", "if", "(", "str", ".", "length", "-", "ending", ".", "length", "===", "str", ".", "lastIndexOf", "(", "ending", ")", ")", "return", "true", ";", "else", "return", "false", ";", "}" ]
Determine if a string ends with the provided string. @memberof String @instance @param {string} str - The string to check @param {string} ending - The string to match
[ "Determine", "if", "a", "string", "ends", "with", "the", "provided", "string", "." ]
fadb8834499d656960b28d405f44904f2b3b1b77
https://github.com/bitwalker/keys.js/blob/fadb8834499d656960b28d405f44904f2b3b1b77/src/keys.js#L232-L236
train
bitwalker/keys.js
src/keys.js
find
function find (c, predicate) { for (var i = 0; i < c.length; i++) { if (predicate(c[i])) return c[i]; } return null; }
javascript
function find (c, predicate) { for (var i = 0; i < c.length; i++) { if (predicate(c[i])) return c[i]; } return null; }
[ "function", "find", "(", "c", ",", "predicate", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "c", ".", "length", ";", "i", "++", ")", "{", "if", "(", "predicate", "(", "c", "[", "i", "]", ")", ")", "return", "c", "[", "i", "]", ";", "}", "return", "null", ";", "}" ]
Search for the first element that matches a predicate within the collection @param {array} c - the collection to search @param {function} predicate - the predicate function to match with @return {object} The first matching element or null if not found
[ "Search", "for", "the", "first", "element", "that", "matches", "a", "predicate", "within", "the", "collection" ]
fadb8834499d656960b28d405f44904f2b3b1b77
https://github.com/bitwalker/keys.js/blob/fadb8834499d656960b28d405f44904f2b3b1b77/src/keys.js#L244-L250
train
bitwalker/keys.js
src/keys.js
Key
function Key(name, code) { this.name = name; this.code = code; // If a new Key is instantiated with a name that isn't // in the internal keymap, make sure we add it Key.internals.keymap[name] = Key.internals.keymap[name] || code; }
javascript
function Key(name, code) { this.name = name; this.code = code; // If a new Key is instantiated with a name that isn't // in the internal keymap, make sure we add it Key.internals.keymap[name] = Key.internals.keymap[name] || code; }
[ "function", "Key", "(", "name", ",", "code", ")", "{", "this", ".", "name", "=", "name", ";", "this", ".", "code", "=", "code", ";", "Key", ".", "internals", ".", "keymap", "[", "name", "]", "=", "Key", ".", "internals", ".", "keymap", "[", "name", "]", "||", "code", ";", "}" ]
Constructs a new instance of Key from a name and a keycode @class Key @classdesc Key represents the mapping between a physical key's name and it's machine code. It contains static references to all known keys, e.x. `Key.A` - and allows you to map a name or key code to one of those static instances. @param {string} name - The name of the key @param {number} code - The key code for the key
[ "Constructs", "a", "new", "instance", "of", "Key", "from", "a", "name", "and", "a", "keycode" ]
fadb8834499d656960b28d405f44904f2b3b1b77
https://github.com/bitwalker/keys.js/blob/fadb8834499d656960b28d405f44904f2b3b1b77/src/keys.js#L261-L268
train
bitwalker/keys.js
src/keys.js
Combo
function Combo(key, meta) { var keys = null; if (arguments.length === 2 && meta instanceof Array) { keys = meta; } else if (arguments.length >= 2) { keys = Array.prototype.slice.call(arguments, 1); } else if (arguments.length === 1) { this.key = key; this.ctrl = key.eq(Key.CTRL); this.shift = key.eq(Key.SHIFT); this.alt = key.eq(Key.ALT); this.meta = key.eq(Key.META) || key.eq(Key.META_RIGHT); return; } else { throw new Error('Combo: Invalid number of arguments provided.'); } var invalid = find(keys, function(k) { switch (k.code) { case Key.CTRL.code: case Key.SHIFT.code: case Key.ALT.code: case Key.META.code: case Key.META_RIGHT.code: return false; default: return true; } }); if (invalid) { throw new Error('Combo: Attempted to create a Combo with multiple non-meta Keys. This is not supported.'); } this.key = key; this.ctrl = hasKey(keys, Key.CTRL) || key.eq(Key.CTRL); this.shift = hasKey(keys, Key.SHIFT) || key.eq(Key.SHIFT); this.alt = hasKey(keys, Key.ALT) || key.eq(Key.ALT); this.meta = hasKey(keys, Key.META) || hasKey(keys, Key.META_RIGHT); this.meta = this.meta || (key.eq(Key.META) || key.eq(Key.META_RIGHT)); function hasKey(collection, k) { return find(collection, function(x) { return k.eq(x); }) !== null; } }
javascript
function Combo(key, meta) { var keys = null; if (arguments.length === 2 && meta instanceof Array) { keys = meta; } else if (arguments.length >= 2) { keys = Array.prototype.slice.call(arguments, 1); } else if (arguments.length === 1) { this.key = key; this.ctrl = key.eq(Key.CTRL); this.shift = key.eq(Key.SHIFT); this.alt = key.eq(Key.ALT); this.meta = key.eq(Key.META) || key.eq(Key.META_RIGHT); return; } else { throw new Error('Combo: Invalid number of arguments provided.'); } var invalid = find(keys, function(k) { switch (k.code) { case Key.CTRL.code: case Key.SHIFT.code: case Key.ALT.code: case Key.META.code: case Key.META_RIGHT.code: return false; default: return true; } }); if (invalid) { throw new Error('Combo: Attempted to create a Combo with multiple non-meta Keys. This is not supported.'); } this.key = key; this.ctrl = hasKey(keys, Key.CTRL) || key.eq(Key.CTRL); this.shift = hasKey(keys, Key.SHIFT) || key.eq(Key.SHIFT); this.alt = hasKey(keys, Key.ALT) || key.eq(Key.ALT); this.meta = hasKey(keys, Key.META) || hasKey(keys, Key.META_RIGHT); this.meta = this.meta || (key.eq(Key.META) || key.eq(Key.META_RIGHT)); function hasKey(collection, k) { return find(collection, function(x) { return k.eq(x); }) !== null; } }
[ "function", "Combo", "(", "key", ",", "meta", ")", "{", "var", "keys", "=", "null", ";", "if", "(", "arguments", ".", "length", "===", "2", "&&", "meta", "instanceof", "Array", ")", "{", "keys", "=", "meta", ";", "}", "else", "if", "(", "arguments", ".", "length", ">=", "2", ")", "{", "keys", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "}", "else", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "this", ".", "key", "=", "key", ";", "this", ".", "ctrl", "=", "key", ".", "eq", "(", "Key", ".", "CTRL", ")", ";", "this", ".", "shift", "=", "key", ".", "eq", "(", "Key", ".", "SHIFT", ")", ";", "this", ".", "alt", "=", "key", ".", "eq", "(", "Key", ".", "ALT", ")", ";", "this", ".", "meta", "=", "key", ".", "eq", "(", "Key", ".", "META", ")", "||", "key", ".", "eq", "(", "Key", ".", "META_RIGHT", ")", ";", "return", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Combo: Invalid number of arguments provided.'", ")", ";", "}", "var", "invalid", "=", "find", "(", "keys", ",", "function", "(", "k", ")", "{", "switch", "(", "k", ".", "code", ")", "{", "case", "Key", ".", "CTRL", ".", "code", ":", "case", "Key", ".", "SHIFT", ".", "code", ":", "case", "Key", ".", "ALT", ".", "code", ":", "case", "Key", ".", "META", ".", "code", ":", "case", "Key", ".", "META_RIGHT", ".", "code", ":", "return", "false", ";", "default", ":", "return", "true", ";", "}", "}", ")", ";", "if", "(", "invalid", ")", "{", "throw", "new", "Error", "(", "'Combo: Attempted to create a Combo with multiple non-meta Keys. This is not supported.'", ")", ";", "}", "this", ".", "key", "=", "key", ";", "this", ".", "ctrl", "=", "hasKey", "(", "keys", ",", "Key", ".", "CTRL", ")", "||", "key", ".", "eq", "(", "Key", ".", "CTRL", ")", ";", "this", ".", "shift", "=", "hasKey", "(", "keys", ",", "Key", ".", "SHIFT", ")", "||", "key", ".", "eq", "(", "Key", ".", "SHIFT", ")", ";", "this", ".", "alt", "=", "hasKey", "(", "keys", ",", "Key", ".", "ALT", ")", "||", "key", ".", "eq", "(", "Key", ".", "ALT", ")", ";", "this", ".", "meta", "=", "hasKey", "(", "keys", ",", "Key", ".", "META", ")", "||", "hasKey", "(", "keys", ",", "Key", ".", "META_RIGHT", ")", ";", "this", ".", "meta", "=", "this", ".", "meta", "||", "(", "key", ".", "eq", "(", "Key", ".", "META", ")", "||", "key", ".", "eq", "(", "Key", ".", "META_RIGHT", ")", ")", ";", "function", "hasKey", "(", "collection", ",", "k", ")", "{", "return", "find", "(", "collection", ",", "function", "(", "x", ")", "{", "return", "k", ".", "eq", "(", "x", ")", ";", "}", ")", "!==", "null", ";", "}", "}" ]
Creates a new Combo from a key code and array of meta key codes @class @classdesc Combo represents the physical combination of a single key and any meta keys that ultimately are used to trigger a keybinding. It is at the Combo level that we match a configured keybinding with the current set of pressed keys. @example var combo = new Combo(Key.A, [ Key.CTRL, Key.SHIFT ]); @namespace Combo @constructor @param {Key} key - The primary Key for this Combo. @param {array} meta - An array of meta Keys needed for this Combo to be activated. {optional}
[ "Creates", "a", "new", "Combo", "from", "a", "key", "code", "and", "array", "of", "meta", "key", "codes" ]
fadb8834499d656960b28d405f44904f2b3b1b77
https://github.com/bitwalker/keys.js/blob/fadb8834499d656960b28d405f44904f2b3b1b77/src/keys.js#L501-L548
train
bitwalker/keys.js
src/keys.js
constructMetaParams
function constructMetaParams(flags) { if (!flags || !(flags instanceof Array)) { flags = [ false, false, false, false ]; } // Predicate to filter meta keys by var isActive = function(m) { return m[1] === true; }; // Extractor var extractKey = function(m) { return m[0]; }; // Determine which meta keys were active, and map those to instances of Key return zipmap(Key.metaKeys, flags).filter(isActive).map(extractKey); }
javascript
function constructMetaParams(flags) { if (!flags || !(flags instanceof Array)) { flags = [ false, false, false, false ]; } // Predicate to filter meta keys by var isActive = function(m) { return m[1] === true; }; // Extractor var extractKey = function(m) { return m[0]; }; // Determine which meta keys were active, and map those to instances of Key return zipmap(Key.metaKeys, flags).filter(isActive).map(extractKey); }
[ "function", "constructMetaParams", "(", "flags", ")", "{", "if", "(", "!", "flags", "||", "!", "(", "flags", "instanceof", "Array", ")", ")", "{", "flags", "=", "[", "false", ",", "false", ",", "false", ",", "false", "]", ";", "}", "var", "isActive", "=", "function", "(", "m", ")", "{", "return", "m", "[", "1", "]", "===", "true", ";", "}", ";", "var", "extractKey", "=", "function", "(", "m", ")", "{", "return", "m", "[", "0", "]", ";", "}", ";", "return", "zipmap", "(", "Key", ".", "metaKeys", ",", "flags", ")", ".", "filter", "(", "isActive", ")", ".", "map", "(", "extractKey", ")", ";", "}" ]
This function is reused across a number of Combo functions to determine the meta Key instances to construct a new Combo instance with. @param {array} flags - These flags, when present, must be in CTRL > ALT > SHIFT > META order. @return {array} An array of Key instances matching the meta key flags passed in
[ "This", "function", "is", "reused", "across", "a", "number", "of", "Combo", "functions", "to", "determine", "the", "meta", "Key", "instances", "to", "construct", "a", "new", "Combo", "instance", "with", "." ]
fadb8834499d656960b28d405f44904f2b3b1b77
https://github.com/bitwalker/keys.js/blob/fadb8834499d656960b28d405f44904f2b3b1b77/src/keys.js#L620-L630
train
ravelsoft/node-jinjs
lib/module_template.js
render
function render ($$) { $$ = ($$ === undefined || $$ === null) ? {} : $$; var _ref = undefined; var _res = ''; var _i = 0; var __extends__ = null; _res += 'var _require = function (mod) { \n if ((typeof mod === \"object\") && (mod.render != null))\n return mod;\n return '; _res += ((_ref = $default.call($$,$$.require_exp, "require")) !== undefined && _ref !== null ? _ref : '').toString(); _res += '(mod);\n};\nvar __last_ctx__ = null;\n\nvar __indexOf = [].indexOf || function(x) {\n for (var i = this.length - 1; i >= 0; i--)\n if (this[i] === x) return i;\n};\n\nif (!Object.keys) Object.keys = function(o){\n if (o !== Object(o))\n throw new TypeError(\'Object.keys called on non-object\');\n var ret=[],p;\n for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p);\n return ret;\n}\n\n'; (function() {var _fref = $$.utils || [], _prev_loop = $$.loop, _prev_key = $$['fname'], _prev_value = $$['fn'], k = null, v = null, i = 0, l = 0, x = null, last_v = null, last_k = null;$$.loop = { }; if (_fref instanceof Array) {l = _fref.length;for (i = 0; i < l; i++) {$$.loop.last = (i == l - 1);$$.loop.first = (i == 0);$$.loop.index0 = i;$$.loop.index = i + 1;$$['fname'] = _fref[i]; $$['fn'] = i; _res += ((_ref = $$.fn) !== undefined && _ref !== null ? _ref : '').toString();} } else {$$.loop = { first: true, last: false };l = Object.keys(_fref).length;for (x in _fref) { if (_fref.hasOwnProperty(x)) {$$.loop.last = (i == l - 1);$$['fname'] = x;$$['fn'] = _fref[x];$$.loop.index0 = i;$$.loop.index = i + 1; _res += ((_ref = $$.fn) !== undefined && _ref !== null ? _ref : '').toString();i += 1;$$.loop.first = false;} }} if ($$.loop.index == undefined) {}$$.loop = _prev_loop; $$['fname'] = _prev_key; $$['fn'] = _prev_value;})(); _res += '\n'; (function() {var _fref = $$.filters_used || [], _prev_loop = $$.loop, _prev_key = $$['fn_name'], _prev_value = $$['decl'], k = null, v = null, i = 0, l = 0, x = null, last_v = null, last_k = null;$$.loop = { }; if (_fref instanceof Array) {l = _fref.length;for (i = 0; i < l; i++) {$$.loop.last = (i == l - 1);$$.loop.first = (i == 0);$$.loop.index0 = i;$$.loop.index = i + 1;$$['fn_name'] = _fref[i]; $$['decl'] = i; _res += ((_ref = $$.decl) !== undefined && _ref !== null ? _ref : '').toString(); _res += '\n';} } else {$$.loop = { first: true, last: false };l = Object.keys(_fref).length;for (x in _fref) { if (_fref.hasOwnProperty(x)) {$$.loop.last = (i == l - 1);$$['fn_name'] = x;$$['decl'] = _fref[x];$$.loop.index0 = i;$$.loop.index = i + 1; _res += ((_ref = $$.decl) !== undefined && _ref !== null ? _ref : '').toString(); _res += '\n';i += 1;$$.loop.first = false;} }} if ($$.loop.index == undefined) {}$$.loop = _prev_loop; $$['fn_name'] = _prev_key; $$['decl'] = _prev_value;})(); _res += '\n'; if ($$.blocks) { _res += '// Start Block Definitions\n\n'; (function() {var _fref = $$.blocks || [], _prev_loop = $$.loop, _prev_key = $$['name'], _prev_value = $$['contents'], k = null, v = null, i = 0, l = 0, x = null, last_v = null, last_k = null;$$.loop = { }; if (_fref instanceof Array) {l = _fref.length;for (i = 0; i < l; i++) {$$.loop.last = (i == l - 1);$$.loop.first = (i == 0);$$.loop.index0 = i;$$.loop.index = i + 1;$$['name'] = _fref[i]; $$['contents'] = i; _res += '// Block declaration of \"'; _res += ((_ref = $$.name) !== undefined && _ref !== null ? _ref : '').toString(); _res += '\"\nfunction __block_'; _res += ((_ref = $$.name) !== undefined && _ref !== null ? _ref : '').toString(); _res += ' ($$) {\n var require = _require;\n var _b = ($$ ? $$.__blocks__ : {});\n var _res = \"\";\n var __extends__ = null;\n '; _res += ((_ref = $$.contents) !== undefined && _ref !== null ? _ref : '').toString(); _res += '\n return _res;\n}\n';} } else {$$.loop = { first: true, last: false };l = Object.keys(_fref).length;for (x in _fref) { if (_fref.hasOwnProperty(x)) {$$.loop.last = (i == l - 1);$$['name'] = x;$$['contents'] = _fref[x];$$.loop.index0 = i;$$.loop.index = i + 1; _res += '// Block declaration of \"'; _res += ((_ref = $$.name) !== undefined && _ref !== null ? _ref : '').toString(); _res += '\"\nfunction __block_'; _res += ((_ref = $$.name) !== undefined && _ref !== null ? _ref : '').toString(); _res += ' ($$) {\n var require = _require;\n var _b = ($$ ? $$.__blocks__ : {});\n var _res = \"\";\n var __extends__ = null;\n '; _res += ((_ref = $$.contents) !== undefined && _ref !== null ? _ref : '').toString(); _res += '\n return _res;\n}\n';i += 1;$$.loop.first = false;} }} if ($$.loop.index == undefined) {}$$.loop = _prev_loop; $$['name'] = _prev_key; $$['contents'] = _prev_value;})(); _res += '\n// End Block Definitions\n'; } _res += '// RENDERING FUNCTION, EVERYTHING HAPPENS HERE.\nfunction render ($$) {\n $$ = ($$ === undefined || $$ === null) ? {} : $$;\n var _ref = undefined;\n var _res = \'\';\n var _i = 0;\n var __extends__ = null;\n var require = _require;\n '; if ($$.blocks) { _res += ' var _b = null;\n ($$.__blocks__ == null) && ($$.__blocks__ = {});\n _b = $$.__blocks__;\n var __newblocks__ = {};\n var _block_iterator = null;\n '; } _res += ' '; _res += ((_ref = $$.body) !== undefined && _ref !== null ? _ref : '').toString(); _res += '\n if (__extends__ !== undefined && __extends__ !== null) return __extends__.render($$);\n return _res;\n}\nexports.render = render;\n\nfunction _cached_ctx () {\n if (!__last_ctx__) {\n __last_ctx__ = {};\n render(__last_ctx__);\n }\n return __last_ctx__;\n}\nexports._cached_ctx = _cached_ctx;\n'; if (__extends__ !== undefined && __extends__ !== null) return __extends__.render($$); return _res; }
javascript
function render ($$) { $$ = ($$ === undefined || $$ === null) ? {} : $$; var _ref = undefined; var _res = ''; var _i = 0; var __extends__ = null; _res += 'var _require = function (mod) { \n if ((typeof mod === \"object\") && (mod.render != null))\n return mod;\n return '; _res += ((_ref = $default.call($$,$$.require_exp, "require")) !== undefined && _ref !== null ? _ref : '').toString(); _res += '(mod);\n};\nvar __last_ctx__ = null;\n\nvar __indexOf = [].indexOf || function(x) {\n for (var i = this.length - 1; i >= 0; i--)\n if (this[i] === x) return i;\n};\n\nif (!Object.keys) Object.keys = function(o){\n if (o !== Object(o))\n throw new TypeError(\'Object.keys called on non-object\');\n var ret=[],p;\n for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p);\n return ret;\n}\n\n'; (function() {var _fref = $$.utils || [], _prev_loop = $$.loop, _prev_key = $$['fname'], _prev_value = $$['fn'], k = null, v = null, i = 0, l = 0, x = null, last_v = null, last_k = null;$$.loop = { }; if (_fref instanceof Array) {l = _fref.length;for (i = 0; i < l; i++) {$$.loop.last = (i == l - 1);$$.loop.first = (i == 0);$$.loop.index0 = i;$$.loop.index = i + 1;$$['fname'] = _fref[i]; $$['fn'] = i; _res += ((_ref = $$.fn) !== undefined && _ref !== null ? _ref : '').toString();} } else {$$.loop = { first: true, last: false };l = Object.keys(_fref).length;for (x in _fref) { if (_fref.hasOwnProperty(x)) {$$.loop.last = (i == l - 1);$$['fname'] = x;$$['fn'] = _fref[x];$$.loop.index0 = i;$$.loop.index = i + 1; _res += ((_ref = $$.fn) !== undefined && _ref !== null ? _ref : '').toString();i += 1;$$.loop.first = false;} }} if ($$.loop.index == undefined) {}$$.loop = _prev_loop; $$['fname'] = _prev_key; $$['fn'] = _prev_value;})(); _res += '\n'; (function() {var _fref = $$.filters_used || [], _prev_loop = $$.loop, _prev_key = $$['fn_name'], _prev_value = $$['decl'], k = null, v = null, i = 0, l = 0, x = null, last_v = null, last_k = null;$$.loop = { }; if (_fref instanceof Array) {l = _fref.length;for (i = 0; i < l; i++) {$$.loop.last = (i == l - 1);$$.loop.first = (i == 0);$$.loop.index0 = i;$$.loop.index = i + 1;$$['fn_name'] = _fref[i]; $$['decl'] = i; _res += ((_ref = $$.decl) !== undefined && _ref !== null ? _ref : '').toString(); _res += '\n';} } else {$$.loop = { first: true, last: false };l = Object.keys(_fref).length;for (x in _fref) { if (_fref.hasOwnProperty(x)) {$$.loop.last = (i == l - 1);$$['fn_name'] = x;$$['decl'] = _fref[x];$$.loop.index0 = i;$$.loop.index = i + 1; _res += ((_ref = $$.decl) !== undefined && _ref !== null ? _ref : '').toString(); _res += '\n';i += 1;$$.loop.first = false;} }} if ($$.loop.index == undefined) {}$$.loop = _prev_loop; $$['fn_name'] = _prev_key; $$['decl'] = _prev_value;})(); _res += '\n'; if ($$.blocks) { _res += '// Start Block Definitions\n\n'; (function() {var _fref = $$.blocks || [], _prev_loop = $$.loop, _prev_key = $$['name'], _prev_value = $$['contents'], k = null, v = null, i = 0, l = 0, x = null, last_v = null, last_k = null;$$.loop = { }; if (_fref instanceof Array) {l = _fref.length;for (i = 0; i < l; i++) {$$.loop.last = (i == l - 1);$$.loop.first = (i == 0);$$.loop.index0 = i;$$.loop.index = i + 1;$$['name'] = _fref[i]; $$['contents'] = i; _res += '// Block declaration of \"'; _res += ((_ref = $$.name) !== undefined && _ref !== null ? _ref : '').toString(); _res += '\"\nfunction __block_'; _res += ((_ref = $$.name) !== undefined && _ref !== null ? _ref : '').toString(); _res += ' ($$) {\n var require = _require;\n var _b = ($$ ? $$.__blocks__ : {});\n var _res = \"\";\n var __extends__ = null;\n '; _res += ((_ref = $$.contents) !== undefined && _ref !== null ? _ref : '').toString(); _res += '\n return _res;\n}\n';} } else {$$.loop = { first: true, last: false };l = Object.keys(_fref).length;for (x in _fref) { if (_fref.hasOwnProperty(x)) {$$.loop.last = (i == l - 1);$$['name'] = x;$$['contents'] = _fref[x];$$.loop.index0 = i;$$.loop.index = i + 1; _res += '// Block declaration of \"'; _res += ((_ref = $$.name) !== undefined && _ref !== null ? _ref : '').toString(); _res += '\"\nfunction __block_'; _res += ((_ref = $$.name) !== undefined && _ref !== null ? _ref : '').toString(); _res += ' ($$) {\n var require = _require;\n var _b = ($$ ? $$.__blocks__ : {});\n var _res = \"\";\n var __extends__ = null;\n '; _res += ((_ref = $$.contents) !== undefined && _ref !== null ? _ref : '').toString(); _res += '\n return _res;\n}\n';i += 1;$$.loop.first = false;} }} if ($$.loop.index == undefined) {}$$.loop = _prev_loop; $$['name'] = _prev_key; $$['contents'] = _prev_value;})(); _res += '\n// End Block Definitions\n'; } _res += '// RENDERING FUNCTION, EVERYTHING HAPPENS HERE.\nfunction render ($$) {\n $$ = ($$ === undefined || $$ === null) ? {} : $$;\n var _ref = undefined;\n var _res = \'\';\n var _i = 0;\n var __extends__ = null;\n var require = _require;\n '; if ($$.blocks) { _res += ' var _b = null;\n ($$.__blocks__ == null) && ($$.__blocks__ = {});\n _b = $$.__blocks__;\n var __newblocks__ = {};\n var _block_iterator = null;\n '; } _res += ' '; _res += ((_ref = $$.body) !== undefined && _ref !== null ? _ref : '').toString(); _res += '\n if (__extends__ !== undefined && __extends__ !== null) return __extends__.render($$);\n return _res;\n}\nexports.render = render;\n\nfunction _cached_ctx () {\n if (!__last_ctx__) {\n __last_ctx__ = {};\n render(__last_ctx__);\n }\n return __last_ctx__;\n}\nexports._cached_ctx = _cached_ctx;\n'; if (__extends__ !== undefined && __extends__ !== null) return __extends__.render($$); return _res; }
[ "function", "render", "(", "$$", ")", "{", "$$", "=", "(", "$$", "===", "undefined", "||", "$$", "===", "null", ")", "?", "{", "}", ":", "$$", ";", "var", "_ref", "=", "undefined", ";", "var", "_res", "=", "''", ";", "var", "_i", "=", "0", ";", "var", "__extends__", "=", "null", ";", "_res", "+=", "'var _require = function (mod) { \\n if ((typeof mod === \\\"object\\\") && (mod.render != null))\\n return mod;\\n return '", ";", "\\n", "\\\"", "\\\"", "\\n", "\\n", "_res", "+=", "(", "(", "_ref", "=", "$default", ".", "call", "(", "$$", ",", "$$", ".", "require_exp", ",", "\"require\"", ")", ")", "!==", "undefined", "&&", "_ref", "!==", "null", "?", "_ref", ":", "''", ")", ".", "toString", "(", ")", ";", "_res", "+=", "'(mod);\\n};\\nvar __last_ctx__ = null;\\n\\nvar __indexOf = [].indexOf || function(x) {\\n for (var i = this.length - 1; i >= 0; i--)\\n if (this[i] === x) return i;\\n};\\n\\nif (!Object.keys) Object.keys = function(o){\\n if (o !== Object(o))\\n throw new TypeError(\\'Object.keys called on non-object\\');\\n var ret=[],p;\\n for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p);\\n return ret;\\n}\\n\\n'", ";", "\\n", "\\n", "\\n", "\\n", "\\n", "\\n", "\\n", "}" ]
RENDERING FUNCTION, EVERYTHING HAPPENS HERE.
[ "RENDERING", "FUNCTION", "EVERYTHING", "HAPPENS", "HERE", "." ]
4b5aa840cac2f83078b20737b443c33275005a98
https://github.com/ravelsoft/node-jinjs/blob/4b5aa840cac2f83078b20737b443c33275005a98/lib/module_template.js#L47-L104
train
cpettitt/dig.js
src/dig/digraph.js
_safeGetNode
function _safeGetNode(g, u) { var V = g._nodes; if (!(u in V)) { throw new Error("Node not in graph: " + u); } return V[u]; }
javascript
function _safeGetNode(g, u) { var V = g._nodes; if (!(u in V)) { throw new Error("Node not in graph: " + u); } return V[u]; }
[ "function", "_safeGetNode", "(", "g", ",", "u", ")", "{", "var", "V", "=", "g", ".", "_nodes", ";", "if", "(", "!", "(", "u", "in", "V", ")", ")", "{", "throw", "new", "Error", "(", "\"Node not in graph: \"", "+", "u", ")", ";", "}", "return", "V", "[", "u", "]", ";", "}" ]
Returns the node object for u in V or throws an error if the node does node exist.
[ "Returns", "the", "node", "object", "for", "u", "in", "V", "or", "throws", "an", "error", "if", "the", "node", "does", "node", "exist", "." ]
997a63ddf4eba689d761ce25a126b33d2c87762d
https://github.com/cpettitt/dig.js/blob/997a63ddf4eba689d761ce25a126b33d2c87762d/src/dig/digraph.js#L5-L11
train
cpettitt/dig.js
src/dig/digraph.js
_shallowCopyAttrs
function _shallowCopyAttrs(src, dst) { if (Object.prototype.toString.call(src) !== '[object Object]') { throw new Error("Attributes are not an object: " + src); } for (var k in src) { dst[k] = src[k]; } }
javascript
function _shallowCopyAttrs(src, dst) { if (Object.prototype.toString.call(src) !== '[object Object]') { throw new Error("Attributes are not an object: " + src); } for (var k in src) { dst[k] = src[k]; } }
[ "function", "_shallowCopyAttrs", "(", "src", ",", "dst", ")", "{", "if", "(", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "src", ")", "!==", "'[object Object]'", ")", "{", "throw", "new", "Error", "(", "\"Attributes are not an object: \"", "+", "src", ")", ";", "}", "for", "(", "var", "k", "in", "src", ")", "{", "dst", "[", "k", "]", "=", "src", "[", "k", "]", ";", "}", "}" ]
Copies the first level of keys and values from src to dst.
[ "Copies", "the", "first", "level", "of", "keys", "and", "values", "from", "src", "to", "dst", "." ]
997a63ddf4eba689d761ce25a126b33d2c87762d
https://github.com/cpettitt/dig.js/blob/997a63ddf4eba689d761ce25a126b33d2c87762d/src/dig/digraph.js#L38-L45
train
cpettitt/dig.js
src/dig/digraph.js
_shallowEqual
function _shallowEqual(lhs, rhs) { var lhsKeys = Object.keys(lhs); var rhsKeys = Object.keys(rhs); if (lhsKeys.length !== rhsKeys.length) { return false; } for (var k in lhs) { if (lhs[k] !== rhs[k]) { return false; } } return true; }
javascript
function _shallowEqual(lhs, rhs) { var lhsKeys = Object.keys(lhs); var rhsKeys = Object.keys(rhs); if (lhsKeys.length !== rhsKeys.length) { return false; } for (var k in lhs) { if (lhs[k] !== rhs[k]) { return false; } } return true; }
[ "function", "_shallowEqual", "(", "lhs", ",", "rhs", ")", "{", "var", "lhsKeys", "=", "Object", ".", "keys", "(", "lhs", ")", ";", "var", "rhsKeys", "=", "Object", ".", "keys", "(", "rhs", ")", ";", "if", "(", "lhsKeys", ".", "length", "!==", "rhsKeys", ".", "length", ")", "{", "return", "false", ";", "}", "for", "(", "var", "k", "in", "lhs", ")", "{", "if", "(", "lhs", "[", "k", "]", "!==", "rhs", "[", "k", "]", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Checks for equality of all keys and values on the two objects.
[ "Checks", "for", "equality", "of", "all", "keys", "and", "values", "on", "the", "two", "objects", "." ]
997a63ddf4eba689d761ce25a126b33d2c87762d
https://github.com/cpettitt/dig.js/blob/997a63ddf4eba689d761ce25a126b33d2c87762d/src/dig/digraph.js#L48-L60
train
scootykins/4chan-list-webm
lib/transform.js
transform
function transform (raw, protocol, board) { const reducer = (acc, file) => acc.concat([{ filename: file.filename, url: webmUrl(protocol, board, file.tim), thumbnail: thumbUrl(protocol, board, file.tim) }]) const payload = { webms: raw.posts.filter(isWebm).reduce(reducer, []) } if (raw.posts[0].sub) { payload.subject = raw.posts[0].sub } return payload }
javascript
function transform (raw, protocol, board) { const reducer = (acc, file) => acc.concat([{ filename: file.filename, url: webmUrl(protocol, board, file.tim), thumbnail: thumbUrl(protocol, board, file.tim) }]) const payload = { webms: raw.posts.filter(isWebm).reduce(reducer, []) } if (raw.posts[0].sub) { payload.subject = raw.posts[0].sub } return payload }
[ "function", "transform", "(", "raw", ",", "protocol", ",", "board", ")", "{", "const", "reducer", "=", "(", "acc", ",", "file", ")", "=>", "acc", ".", "concat", "(", "[", "{", "filename", ":", "file", ".", "filename", ",", "url", ":", "webmUrl", "(", "protocol", ",", "board", ",", "file", ".", "tim", ")", ",", "thumbnail", ":", "thumbUrl", "(", "protocol", ",", "board", ",", "file", ".", "tim", ")", "}", "]", ")", "const", "payload", "=", "{", "webms", ":", "raw", ".", "posts", ".", "filter", "(", "isWebm", ")", ".", "reduce", "(", "reducer", ",", "[", "]", ")", "}", "if", "(", "raw", ".", "posts", "[", "0", "]", ".", "sub", ")", "{", "payload", ".", "subject", "=", "raw", ".", "posts", "[", "0", "]", ".", "sub", "}", "return", "payload", "}" ]
Transforms a 4chan thread payload into a JSON with webm data @func transform @param {Object} raw Raw thread JSON payload @param {String} protocol Protocol to use for generating links @param {String} board Board shortname, eg. 'b' @returns {Object} JSON containing thread subject and webm data
[ "Transforms", "a", "4chan", "thread", "payload", "into", "a", "JSON", "with", "webm", "data" ]
6936ddd659930ef26d2a0fe6c400e59095ffc727
https://github.com/scootykins/4chan-list-webm/blob/6936ddd659930ef26d2a0fe6c400e59095ffc727/lib/transform.js#L43-L59
train
fullcube/loopback-ds-changed-mixin
lib/changed.js
convertItemsToProperties
function convertItemsToProperties(items) { // The object that contains the converted items const result = {} // Loop through all the inserted items _.mapKeys(items, (changes, itemId) => { // Loop through changes for this item _.mapKeys(changes, (value, property) => { // Add basic structure to hold ids and values if (_.isUndefined(result[property])) { result[property] = { ids: {}, values: {} } } // Create an array to hold ids for each value if (_.isUndefined(result[property].values[value])) { result[property].values[value] = [] } // Create an object { itemId: value } result[property].ids[itemId] = value // Enter itemId in the array for this value result[property].values[value].push(itemId) }) }) const changedProperties = {} _.mapKeys(result, (changeset, property) => { changedProperties[property] = new ChangeSet(changeset) }) return changedProperties }
javascript
function convertItemsToProperties(items) { // The object that contains the converted items const result = {} // Loop through all the inserted items _.mapKeys(items, (changes, itemId) => { // Loop through changes for this item _.mapKeys(changes, (value, property) => { // Add basic structure to hold ids and values if (_.isUndefined(result[property])) { result[property] = { ids: {}, values: {} } } // Create an array to hold ids for each value if (_.isUndefined(result[property].values[value])) { result[property].values[value] = [] } // Create an object { itemId: value } result[property].ids[itemId] = value // Enter itemId in the array for this value result[property].values[value].push(itemId) }) }) const changedProperties = {} _.mapKeys(result, (changeset, property) => { changedProperties[property] = new ChangeSet(changeset) }) return changedProperties }
[ "function", "convertItemsToProperties", "(", "items", ")", "{", "const", "result", "=", "{", "}", "_", ".", "mapKeys", "(", "items", ",", "(", "changes", ",", "itemId", ")", "=>", "{", "_", ".", "mapKeys", "(", "changes", ",", "(", "value", ",", "property", ")", "=>", "{", "if", "(", "_", ".", "isUndefined", "(", "result", "[", "property", "]", ")", ")", "{", "result", "[", "property", "]", "=", "{", "ids", ":", "{", "}", ",", "values", ":", "{", "}", "}", "}", "if", "(", "_", ".", "isUndefined", "(", "result", "[", "property", "]", ".", "values", "[", "value", "]", ")", ")", "{", "result", "[", "property", "]", ".", "values", "[", "value", "]", "=", "[", "]", "}", "result", "[", "property", "]", ".", "ids", "[", "itemId", "]", "=", "value", "result", "[", "property", "]", ".", "values", "[", "value", "]", ".", "push", "(", "itemId", ")", "}", ")", "}", ")", "const", "changedProperties", "=", "{", "}", "_", ".", "mapKeys", "(", "result", ",", "(", "changeset", ",", "property", ")", "=>", "{", "changedProperties", "[", "property", "]", "=", "new", "ChangeSet", "(", "changeset", ")", "}", ")", "return", "changedProperties", "}" ]
Helper method that converts the set of items to a set of property In the future this structure should be used directly by the code that detects the changes. Input: { '5586c51948fb091e068f80f4': { status: 'pending' }, '5586c51948fb091e068f80f5': { status: 'pending' } } Output: { status: { ids: { '5586c58848fb091e068f8115': 'pending', '5586c58848fb091e068f8116': 'pending' }, values: { pending: [ '5586c58848fb091e068f8115', '5586c58848fb091e068f8116' ] } } } @returns {{}}
[ "Helper", "method", "that", "converts", "the", "set", "of", "items", "to", "a", "set", "of", "property", "In", "the", "future", "this", "structure", "should", "be", "used", "directly", "by", "the", "code", "that", "detects", "the", "changes", "." ]
99016bbedf0f9c83ae7dde55323a205304fd0eee
https://github.com/fullcube/loopback-ds-changed-mixin/blob/99016bbedf0f9c83ae7dde55323a205304fd0eee/lib/changed.js#L85-L122
train
twilson63/node-cloudq
app.js
notify
function notify (doc) { // find queue, find worker... if (_.isArray(workers[doc.type]) && !_.isEmpty(workers[doc.type])) { var wkr = workers[doc.type].shift(); // update doc as processing db.atomic('dequeue', 'id', doc._id, function (err, body) { if (err) { log.error(err); return wkr.send(ERROR, err); } var job = _.extend(doc.job, { id: doc._id, ok: true }); wkr.send(SUCCESS, job); }); } }
javascript
function notify (doc) { // find queue, find worker... if (_.isArray(workers[doc.type]) && !_.isEmpty(workers[doc.type])) { var wkr = workers[doc.type].shift(); // update doc as processing db.atomic('dequeue', 'id', doc._id, function (err, body) { if (err) { log.error(err); return wkr.send(ERROR, err); } var job = _.extend(doc.job, { id: doc._id, ok: true }); wkr.send(SUCCESS, job); }); } }
[ "function", "notify", "(", "doc", ")", "{", "if", "(", "_", ".", "isArray", "(", "workers", "[", "doc", ".", "type", "]", ")", "&&", "!", "_", ".", "isEmpty", "(", "workers", "[", "doc", ".", "type", "]", ")", ")", "{", "var", "wkr", "=", "workers", "[", "doc", ".", "type", "]", ".", "shift", "(", ")", ";", "db", ".", "atomic", "(", "'dequeue'", ",", "'id'", ",", "doc", ".", "_id", ",", "function", "(", "err", ",", "body", ")", "{", "if", "(", "err", ")", "{", "log", ".", "error", "(", "err", ")", ";", "return", "wkr", ".", "send", "(", "ERROR", ",", "err", ")", ";", "}", "var", "job", "=", "_", ".", "extend", "(", "doc", ".", "job", ",", "{", "id", ":", "doc", ".", "_id", ",", "ok", ":", "true", "}", ")", ";", "wkr", ".", "send", "(", "SUCCESS", ",", "job", ")", ";", "}", ")", ";", "}", "}" ]
if worker is listening - notify..
[ "if", "worker", "is", "listening", "-", "notify", ".." ]
8abdec96a1e0951f4e997c73f54cee759873315e
https://github.com/twilson63/node-cloudq/blob/8abdec96a1e0951f4e997c73f54cee759873315e/app.js#L206-L224
train
socites/beyond
lib/client/beyond/modules/module/rpc.older_delete/cache.js
function (request) { let serialized = request.serialized; serialized.application = beyond.params.name; serialized = JSON.stringify(serialized); let hash = serialized.split('').reduce(function (a, b) { a = ((a << 5) - a) + b.charCodeAt(0); return Math.abs(a & a); }, 0); hash = 'RPC:' + hash; return hash; }
javascript
function (request) { let serialized = request.serialized; serialized.application = beyond.params.name; serialized = JSON.stringify(serialized); let hash = serialized.split('').reduce(function (a, b) { a = ((a << 5) - a) + b.charCodeAt(0); return Math.abs(a & a); }, 0); hash = 'RPC:' + hash; return hash; }
[ "function", "(", "request", ")", "{", "let", "serialized", "=", "request", ".", "serialized", ";", "serialized", ".", "application", "=", "beyond", ".", "params", ".", "name", ";", "serialized", "=", "JSON", ".", "stringify", "(", "serialized", ")", ";", "let", "hash", "=", "serialized", ".", "split", "(", "''", ")", ".", "reduce", "(", "function", "(", "a", ",", "b", ")", "{", "a", "=", "(", "(", "a", "<<", "5", ")", "-", "a", ")", "+", "b", ".", "charCodeAt", "(", "0", ")", ";", "return", "Math", ".", "abs", "(", "a", "&", "a", ")", ";", "}", ",", "0", ")", ";", "hash", "=", "'RPC:'", "+", "hash", ";", "return", "hash", ";", "}" ]
generate the hash
[ "generate", "the", "hash" ]
839d9534f73b669e511d7b2503a3f4f984ea3e0a
https://github.com/socites/beyond/blob/839d9534f73b669e511d7b2503a3f4f984ea3e0a/lib/client/beyond/modules/module/rpc.older_delete/cache.js#L4-L19
train
gethuman/fakeblock
lib/fakeblock.js
function (opts) { opts = opts || {}; this.name = opts.name || 'unknown'; this.userId = opts.userId; this.userRole = opts.userRole || 'anonymous'; this.acl = opts.acl || {}; this.permissions = opts.permissions || []; }
javascript
function (opts) { opts = opts || {}; this.name = opts.name || 'unknown'; this.userId = opts.userId; this.userRole = opts.userRole || 'anonymous'; this.acl = opts.acl || {}; this.permissions = opts.permissions || []; }
[ "function", "(", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "this", ".", "name", "=", "opts", ".", "name", "||", "'unknown'", ";", "this", ".", "userId", "=", "opts", ".", "userId", ";", "this", ".", "userRole", "=", "opts", ".", "userRole", "||", "'anonymous'", ";", "this", ".", "acl", "=", "opts", ".", "acl", "||", "{", "}", ";", "this", ".", "permissions", "=", "opts", ".", "permissions", "||", "[", "]", ";", "}" ]
Set the values for Fakeblock on a per ACL and per user basis @param opts @constructor
[ "Set", "the", "values", "for", "Fakeblock", "on", "a", "per", "ACL", "and", "per", "user", "basis" ]
5ea5218dddb5e289db3a37b2ddeebf72cedeca30
https://github.com/gethuman/fakeblock/blob/5ea5218dddb5e289db3a37b2ddeebf72cedeca30/lib/fakeblock.js#L19-L26
train
socites/beyond
lib/helpers/rest/config/hosts.js
function (config, ID) { if (!ID) ID = '/'; if (typeof config[environment] === 'string') hosts[ID] = config[environment]; for (let element in config) { let elementID = (ID === '/') ? '/' + element : ID + '/' + element; if (typeof config[element] === 'object') iterate(config[element], elementID); } }
javascript
function (config, ID) { if (!ID) ID = '/'; if (typeof config[environment] === 'string') hosts[ID] = config[environment]; for (let element in config) { let elementID = (ID === '/') ? '/' + element : ID + '/' + element; if (typeof config[element] === 'object') iterate(config[element], elementID); } }
[ "function", "(", "config", ",", "ID", ")", "{", "if", "(", "!", "ID", ")", "ID", "=", "'/'", ";", "if", "(", "typeof", "config", "[", "environment", "]", "===", "'string'", ")", "hosts", "[", "ID", "]", "=", "config", "[", "environment", "]", ";", "for", "(", "let", "element", "in", "config", ")", "{", "let", "elementID", "=", "(", "ID", "===", "'/'", ")", "?", "'/'", "+", "element", ":", "ID", "+", "'/'", "+", "element", ";", "if", "(", "typeof", "config", "[", "element", "]", "===", "'object'", ")", "iterate", "(", "config", "[", "element", "]", ",", "elementID", ")", ";", "}", "}" ]
recursively set the applications hosts
[ "recursively", "set", "the", "applications", "hosts" ]
839d9534f73b669e511d7b2503a3f4f984ea3e0a
https://github.com/socites/beyond/blob/839d9534f73b669e511d7b2503a3f4f984ea3e0a/lib/helpers/rest/config/hosts.js#L14-L27
train
Bitcoin-com/wormhole-sdk
examples/burn-bch/burn-bch.js
getBCHBalance
async function getBCHBalance(addr, verbose) { try { const result = await Wormhole.Address.details([addr]) if (verbose) console.log(result) const bchBalance = result[0] return bchBalance.balance } catch (err) { console.error(`Error in getBCHBalance: `, err) console.log(`addr: ${addr}`) throw err } }
javascript
async function getBCHBalance(addr, verbose) { try { const result = await Wormhole.Address.details([addr]) if (verbose) console.log(result) const bchBalance = result[0] return bchBalance.balance } catch (err) { console.error(`Error in getBCHBalance: `, err) console.log(`addr: ${addr}`) throw err } }
[ "async", "function", "getBCHBalance", "(", "addr", ",", "verbose", ")", "{", "try", "{", "const", "result", "=", "await", "Wormhole", ".", "Address", ".", "details", "(", "[", "addr", "]", ")", "if", "(", "verbose", ")", "console", ".", "log", "(", "result", ")", "const", "bchBalance", "=", "result", "[", "0", "]", "return", "bchBalance", ".", "balance", "}", "catch", "(", "err", ")", "{", "console", ".", "error", "(", "`", "`", ",", "err", ")", "console", ".", "log", "(", "`", "${", "addr", "}", "`", ")", "throw", "err", "}", "}" ]
Get the balance in BCH of a BCH address.
[ "Get", "the", "balance", "in", "BCH", "of", "a", "BCH", "address", "." ]
13dd35295b0b3a6bb84e895f96c978cbb906193b
https://github.com/Bitcoin-com/wormhole-sdk/blob/13dd35295b0b3a6bb84e895f96c978cbb906193b/examples/burn-bch/burn-bch.js#L150-L164
train
here-be/snapdragon-util
index.js
append
function append(compiler, value, node) { if (typeof compiler.append !== 'function') { return compiler.emit(value, node); } return compiler.append(value, node); }
javascript
function append(compiler, value, node) { if (typeof compiler.append !== 'function') { return compiler.emit(value, node); } return compiler.append(value, node); }
[ "function", "append", "(", "compiler", ",", "value", ",", "node", ")", "{", "if", "(", "typeof", "compiler", ".", "append", "!==", "'function'", ")", "{", "return", "compiler", ".", "emit", "(", "value", ",", "node", ")", ";", "}", "return", "compiler", ".", "append", "(", "value", ",", "node", ")", ";", "}" ]
Shim to ensure the `.append` methods work with any version of snapdragon
[ "Shim", "to", "ensure", "the", ".", "append", "methods", "work", "with", "any", "version", "of", "snapdragon" ]
a920514eb3f56241d5840d97636eabea384869db
https://github.com/here-be/snapdragon-util/blob/a920514eb3f56241d5840d97636eabea384869db/index.js#L1100-L1105
train
apifytech/apify-shared-js
src/utilities.client.js
function (obj, clone, keyTransformFunc) { // primitive types don't need to be cloned or further traversed if (obj === null || typeof (obj) !== 'object' || Object.prototype.toString.call(obj) === '[object Date]') return obj; let result; if (Array.isArray(obj)) { // obj is an array, keys are numbers and never need to be escaped result = clone ? new Array(obj.length) : obj; for (let i = 0; i < obj.length; i++) { const val = _traverseObject(obj[i], clone, keyTransformFunc); if (clone) result[i] = val; } } else { // obj is an object, all keys need to be checked result = clone ? {} : obj; for (const key in obj) { const val = _traverseObject(obj[key], clone, keyTransformFunc); const escapedKey = keyTransformFunc(key); if (key === escapedKey) { // key doesn't need to be renamed if (clone) result[key] = val; } else { // key needs to be renamed result[escapedKey] = val; if (!clone) delete obj[key]; } } } return result; }
javascript
function (obj, clone, keyTransformFunc) { // primitive types don't need to be cloned or further traversed if (obj === null || typeof (obj) !== 'object' || Object.prototype.toString.call(obj) === '[object Date]') return obj; let result; if (Array.isArray(obj)) { // obj is an array, keys are numbers and never need to be escaped result = clone ? new Array(obj.length) : obj; for (let i = 0; i < obj.length; i++) { const val = _traverseObject(obj[i], clone, keyTransformFunc); if (clone) result[i] = val; } } else { // obj is an object, all keys need to be checked result = clone ? {} : obj; for (const key in obj) { const val = _traverseObject(obj[key], clone, keyTransformFunc); const escapedKey = keyTransformFunc(key); if (key === escapedKey) { // key doesn't need to be renamed if (clone) result[key] = val; } else { // key needs to be renamed result[escapedKey] = val; if (!clone) delete obj[key]; } } } return result; }
[ "function", "(", "obj", ",", "clone", ",", "keyTransformFunc", ")", "{", "if", "(", "obj", "===", "null", "||", "typeof", "(", "obj", ")", "!==", "'object'", "||", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "obj", ")", "===", "'[object Date]'", ")", "return", "obj", ";", "let", "result", ";", "if", "(", "Array", ".", "isArray", "(", "obj", ")", ")", "{", "result", "=", "clone", "?", "new", "Array", "(", "obj", ".", "length", ")", ":", "obj", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "obj", ".", "length", ";", "i", "++", ")", "{", "const", "val", "=", "_traverseObject", "(", "obj", "[", "i", "]", ",", "clone", ",", "keyTransformFunc", ")", ";", "if", "(", "clone", ")", "result", "[", "i", "]", "=", "val", ";", "}", "}", "else", "{", "result", "=", "clone", "?", "{", "}", ":", "obj", ";", "for", "(", "const", "key", "in", "obj", ")", "{", "const", "val", "=", "_traverseObject", "(", "obj", "[", "key", "]", ",", "clone", ",", "keyTransformFunc", ")", ";", "const", "escapedKey", "=", "keyTransformFunc", "(", "key", ")", ";", "if", "(", "key", "===", "escapedKey", ")", "{", "if", "(", "clone", ")", "result", "[", "key", "]", "=", "val", ";", "}", "else", "{", "result", "[", "escapedKey", "]", "=", "val", ";", "if", "(", "!", "clone", ")", "delete", "obj", "[", "key", "]", ";", "}", "}", "}", "return", "result", ";", "}" ]
Traverses an object, creates a deep clone if requested and transforms object keys using a provided function. @param obj Object to traverse, it must not contain circular references! @param clone If true, object is not modified but cloned. @param keyTransformFunc Function used to transform the property names. It has one string argument and one string return value. @returns {*} @private
[ "Traverses", "an", "object", "creates", "a", "deep", "clone", "if", "requested", "and", "transforms", "object", "keys", "using", "a", "provided", "function", "." ]
72a6bae8c05e4889b6a5a56cef73d0eba0a36884
https://github.com/apifytech/apify-shared-js/blob/72a6bae8c05e4889b6a5a56cef73d0eba0a36884/src/utilities.client.js#L267-L298
train
apifytech/apify-shared-js
src/utilities.client.js
validateProxyField
function validateProxyField(fieldKey, value, isRequired = false, options = null) { const fieldErrors = []; if (isRequired) { // Nullable error is already handled by AJV if (value === null) return fieldErrors; if (!value) { const message = m('inputSchema.validation.required', { fieldKey }); fieldErrors.push(message); return fieldErrors; } const { useApifyProxy, proxyUrls } = value; if (!useApifyProxy && (!Array.isArray(proxyUrls) || proxyUrls.length === 0)) { fieldErrors.push(m('inputSchema.validation.proxyRequired', { fieldKey })); return fieldErrors; } } // Input is not required, so missing value is valid if (!value) return fieldErrors; const { useApifyProxy, proxyUrls, apifyProxyGroups } = value; if (!useApifyProxy && Array.isArray(proxyUrls)) { let invalidUrl = false; proxyUrls.forEach((url) => { if (!regex.PROXY_URL_REGEX.test(url.trim())) invalidUrl = url.trim(); }); if (invalidUrl) { fieldErrors.push(m('inputSchema.validation.customProxyInvalid', { invalidUrl })); } } // If Apify proxy is not used skip additional checks if (!useApifyProxy) return fieldErrors; // If options are not provided skip additional checks if (!options) return fieldErrors; const selectedProxyGroups = (apifyProxyGroups || []); // Auto mode, check that user has access to alteast one proxy group usable in this mode if (!selectedProxyGroups.length && !options.hasAutoProxyGroups) { fieldErrors.push(m('inputSchema.validation.noAvailableAutoProxy')); return fieldErrors; } // Check if proxy groups selected by user are available to him const availableProxyGroupsById = {}; (options.availableProxyGroups || []).forEach((group) => { availableProxyGroupsById[group] = true; }); const unavailableProxyGroups = selectedProxyGroups.filter(group => !availableProxyGroupsById[group]); if (unavailableProxyGroups.length) { fieldErrors.push(m('inputSchema.validation.proxyGroupsNotAvailable', { fieldKey, groups: unavailableProxyGroups.join(', ') })); } // Check if any of the proxy groups are blocked and if yes then output the associated message const blockedProxyGroupsById = options.disabledProxyGroups || {}; selectedProxyGroups.filter(group => blockedProxyGroupsById[group]).forEach((blockedGroup) => { fieldErrors.push(blockedProxyGroupsById[blockedGroup]); }); return fieldErrors; }
javascript
function validateProxyField(fieldKey, value, isRequired = false, options = null) { const fieldErrors = []; if (isRequired) { // Nullable error is already handled by AJV if (value === null) return fieldErrors; if (!value) { const message = m('inputSchema.validation.required', { fieldKey }); fieldErrors.push(message); return fieldErrors; } const { useApifyProxy, proxyUrls } = value; if (!useApifyProxy && (!Array.isArray(proxyUrls) || proxyUrls.length === 0)) { fieldErrors.push(m('inputSchema.validation.proxyRequired', { fieldKey })); return fieldErrors; } } // Input is not required, so missing value is valid if (!value) return fieldErrors; const { useApifyProxy, proxyUrls, apifyProxyGroups } = value; if (!useApifyProxy && Array.isArray(proxyUrls)) { let invalidUrl = false; proxyUrls.forEach((url) => { if (!regex.PROXY_URL_REGEX.test(url.trim())) invalidUrl = url.trim(); }); if (invalidUrl) { fieldErrors.push(m('inputSchema.validation.customProxyInvalid', { invalidUrl })); } } // If Apify proxy is not used skip additional checks if (!useApifyProxy) return fieldErrors; // If options are not provided skip additional checks if (!options) return fieldErrors; const selectedProxyGroups = (apifyProxyGroups || []); // Auto mode, check that user has access to alteast one proxy group usable in this mode if (!selectedProxyGroups.length && !options.hasAutoProxyGroups) { fieldErrors.push(m('inputSchema.validation.noAvailableAutoProxy')); return fieldErrors; } // Check if proxy groups selected by user are available to him const availableProxyGroupsById = {}; (options.availableProxyGroups || []).forEach((group) => { availableProxyGroupsById[group] = true; }); const unavailableProxyGroups = selectedProxyGroups.filter(group => !availableProxyGroupsById[group]); if (unavailableProxyGroups.length) { fieldErrors.push(m('inputSchema.validation.proxyGroupsNotAvailable', { fieldKey, groups: unavailableProxyGroups.join(', ') })); } // Check if any of the proxy groups are blocked and if yes then output the associated message const blockedProxyGroupsById = options.disabledProxyGroups || {}; selectedProxyGroups.filter(group => blockedProxyGroupsById[group]).forEach((blockedGroup) => { fieldErrors.push(blockedProxyGroupsById[blockedGroup]); }); return fieldErrors; }
[ "function", "validateProxyField", "(", "fieldKey", ",", "value", ",", "isRequired", "=", "false", ",", "options", "=", "null", ")", "{", "const", "fieldErrors", "=", "[", "]", ";", "if", "(", "isRequired", ")", "{", "if", "(", "value", "===", "null", ")", "return", "fieldErrors", ";", "if", "(", "!", "value", ")", "{", "const", "message", "=", "m", "(", "'inputSchema.validation.required'", ",", "{", "fieldKey", "}", ")", ";", "fieldErrors", ".", "push", "(", "message", ")", ";", "return", "fieldErrors", ";", "}", "const", "{", "useApifyProxy", ",", "proxyUrls", "}", "=", "value", ";", "if", "(", "!", "useApifyProxy", "&&", "(", "!", "Array", ".", "isArray", "(", "proxyUrls", ")", "||", "proxyUrls", ".", "length", "===", "0", ")", ")", "{", "fieldErrors", ".", "push", "(", "m", "(", "'inputSchema.validation.proxyRequired'", ",", "{", "fieldKey", "}", ")", ")", ";", "return", "fieldErrors", ";", "}", "}", "if", "(", "!", "value", ")", "return", "fieldErrors", ";", "const", "{", "useApifyProxy", ",", "proxyUrls", ",", "apifyProxyGroups", "}", "=", "value", ";", "if", "(", "!", "useApifyProxy", "&&", "Array", ".", "isArray", "(", "proxyUrls", ")", ")", "{", "let", "invalidUrl", "=", "false", ";", "proxyUrls", ".", "forEach", "(", "(", "url", ")", "=>", "{", "if", "(", "!", "regex", ".", "PROXY_URL_REGEX", ".", "test", "(", "url", ".", "trim", "(", ")", ")", ")", "invalidUrl", "=", "url", ".", "trim", "(", ")", ";", "}", ")", ";", "if", "(", "invalidUrl", ")", "{", "fieldErrors", ".", "push", "(", "m", "(", "'inputSchema.validation.customProxyInvalid'", ",", "{", "invalidUrl", "}", ")", ")", ";", "}", "}", "if", "(", "!", "useApifyProxy", ")", "return", "fieldErrors", ";", "if", "(", "!", "options", ")", "return", "fieldErrors", ";", "const", "selectedProxyGroups", "=", "(", "apifyProxyGroups", "||", "[", "]", ")", ";", "if", "(", "!", "selectedProxyGroups", ".", "length", "&&", "!", "options", ".", "hasAutoProxyGroups", ")", "{", "fieldErrors", ".", "push", "(", "m", "(", "'inputSchema.validation.noAvailableAutoProxy'", ")", ")", ";", "return", "fieldErrors", ";", "}", "const", "availableProxyGroupsById", "=", "{", "}", ";", "(", "options", ".", "availableProxyGroups", "||", "[", "]", ")", ".", "forEach", "(", "(", "group", ")", "=>", "{", "availableProxyGroupsById", "[", "group", "]", "=", "true", ";", "}", ")", ";", "const", "unavailableProxyGroups", "=", "selectedProxyGroups", ".", "filter", "(", "group", "=>", "!", "availableProxyGroupsById", "[", "group", "]", ")", ";", "if", "(", "unavailableProxyGroups", ".", "length", ")", "{", "fieldErrors", ".", "push", "(", "m", "(", "'inputSchema.validation.proxyGroupsNotAvailable'", ",", "{", "fieldKey", ",", "groups", ":", "unavailableProxyGroups", ".", "join", "(", "', '", ")", "}", ")", ")", ";", "}", "const", "blockedProxyGroupsById", "=", "options", ".", "disabledProxyGroups", "||", "{", "}", ";", "selectedProxyGroups", ".", "filter", "(", "group", "=>", "blockedProxyGroupsById", "[", "group", "]", ")", ".", "forEach", "(", "(", "blockedGroup", ")", "=>", "{", "fieldErrors", ".", "push", "(", "blockedProxyGroupsById", "[", "blockedGroup", "]", ")", ";", "}", ")", ";", "return", "fieldErrors", ";", "}" ]
Validate's input field configured with proxy editor @param {Object} fieldKey Proxy field value @param {Object} value Proxy field value @param {Boolean} isRequired Whether the field is required or not @param {Object} options (Optional) Information about proxy groups availability @param {Boolean} options.hasAutoProxyGroups Informs validation whether user has atleast one proxy group available in auto mode @param {Array<String>} options.availableProxyGroups List of available proxy groups @param {Object} options.disabledProxyGroups Object with groupId as key and error message as value (mostly for residential/SERP)
[ "Validate", "s", "input", "field", "configured", "with", "proxy", "editor" ]
72a6bae8c05e4889b6a5a56cef73d0eba0a36884
https://github.com/apifytech/apify-shared-js/blob/72a6bae8c05e4889b6a5a56cef73d0eba0a36884/src/utilities.client.js#L362-L425
train
words/dale-chall-formula
index.js
daleChallGradeLevel
function daleChallGradeLevel(score) { score = Math.floor(score) if (score < 5) { score = 4 } else if (score > 9) { score = 10 } return gradeMap[score].concat() }
javascript
function daleChallGradeLevel(score) { score = Math.floor(score) if (score < 5) { score = 4 } else if (score > 9) { score = 10 } return gradeMap[score].concat() }
[ "function", "daleChallGradeLevel", "(", "score", ")", "{", "score", "=", "Math", ".", "floor", "(", "score", ")", "if", "(", "score", "<", "5", ")", "{", "score", "=", "4", "}", "else", "if", "(", "score", ">", "9", ")", "{", "score", "=", "10", "}", "return", "gradeMap", "[", "score", "]", ".", "concat", "(", ")", "}" ]
Mapping between a dale-chall score and a U.S. grade level.
[ "Mapping", "between", "a", "dale", "-", "chall", "score", "and", "a", "U", ".", "S", ".", "grade", "level", "." ]
0b5ba85d9c4c21f8950c9a8df40e810fbc141479
https://github.com/words/dale-chall-formula/blob/0b5ba85d9c4c21f8950c9a8df40e810fbc141479/index.js#L46-L56
train
abagames/gif-capture-canvas
web_modules/jsgif/index.js
reset
function reset() { // reset for subsequent use transIndex = 0; image = null; pixels = null; indexedPixels = null; colorTab = null; closeStream = false; firstFrame = true; }
javascript
function reset() { // reset for subsequent use transIndex = 0; image = null; pixels = null; indexedPixels = null; colorTab = null; closeStream = false; firstFrame = true; }
[ "function", "reset", "(", ")", "{", "transIndex", "=", "0", ";", "image", "=", "null", ";", "pixels", "=", "null", ";", "indexedPixels", "=", "null", ";", "colorTab", "=", "null", ";", "closeStream", "=", "false", ";", "firstFrame", "=", "true", ";", "}" ]
Resets some members so that a new stream can be started. This method is actually called by the start method
[ "Resets", "some", "members", "so", "that", "a", "new", "stream", "can", "be", "started", ".", "This", "method", "is", "actually", "called", "by", "the", "start", "method" ]
d4c694cd30783046c87dfaa05de834a6c3686dec
https://github.com/abagames/gif-capture-canvas/blob/d4c694cd30783046c87dfaa05de834a6c3686dec/web_modules/jsgif/index.js#L241-L251
train
abagames/gif-capture-canvas
web_modules/jsgif/index.js
analyzePixels
function analyzePixels() { var len = pixels.length; var nPix = len / 3; indexedPixels = []; var nq = new NeuQuant(pixels, len, sample); // initialize quantizer colorTab = nq.process(); // create reduced palette // map image pixels to new palette var k = 0; for (var j = 0; j < nPix; j++) { var index = nq.map(pixels[k++] & 0xff, pixels[k++] & 0xff, pixels[k++] & 0xff); usedEntry[index] = true; indexedPixels[j] = index; } pixels = null; colorDepth = 8; palSize = 7; // get closest match to transparent color if specified if (transparent !== null) { transIndex = findClosest(transparent); } }
javascript
function analyzePixels() { var len = pixels.length; var nPix = len / 3; indexedPixels = []; var nq = new NeuQuant(pixels, len, sample); // initialize quantizer colorTab = nq.process(); // create reduced palette // map image pixels to new palette var k = 0; for (var j = 0; j < nPix; j++) { var index = nq.map(pixels[k++] & 0xff, pixels[k++] & 0xff, pixels[k++] & 0xff); usedEntry[index] = true; indexedPixels[j] = index; } pixels = null; colorDepth = 8; palSize = 7; // get closest match to transparent color if specified if (transparent !== null) { transIndex = findClosest(transparent); } }
[ "function", "analyzePixels", "(", ")", "{", "var", "len", "=", "pixels", ".", "length", ";", "var", "nPix", "=", "len", "/", "3", ";", "indexedPixels", "=", "[", "]", ";", "var", "nq", "=", "new", "NeuQuant", "(", "pixels", ",", "len", ",", "sample", ")", ";", "colorTab", "=", "nq", ".", "process", "(", ")", ";", "var", "k", "=", "0", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "nPix", ";", "j", "++", ")", "{", "var", "index", "=", "nq", ".", "map", "(", "pixels", "[", "k", "++", "]", "&", "0xff", ",", "pixels", "[", "k", "++", "]", "&", "0xff", ",", "pixels", "[", "k", "++", "]", "&", "0xff", ")", ";", "usedEntry", "[", "index", "]", "=", "true", ";", "indexedPixels", "[", "j", "]", "=", "index", ";", "}", "pixels", "=", "null", ";", "colorDepth", "=", "8", ";", "palSize", "=", "7", ";", "if", "(", "transparent", "!==", "null", ")", "{", "transIndex", "=", "findClosest", "(", "transparent", ")", ";", "}", "}" ]
Analyzes image colors and creates color map.
[ "Analyzes", "image", "colors", "and", "creates", "color", "map", "." ]
d4c694cd30783046c87dfaa05de834a6c3686dec
https://github.com/abagames/gif-capture-canvas/blob/d4c694cd30783046c87dfaa05de834a6c3686dec/web_modules/jsgif/index.js#L335-L361
train
abagames/gif-capture-canvas
web_modules/jsgif/index.js
findClosest
function findClosest(c) { if (colorTab === null) return -1; var r = (c & 0xFF0000) >> 16; var g = (c & 0x00FF00) >> 8; var b = (c & 0x0000FF); var minpos = 0; var dmin = 256 * 256 * 256; var len = colorTab.length; for (var i = 0; i < len;) { var dr = r - (colorTab[i++] & 0xff); var dg = g - (colorTab[i++] & 0xff); var db = b - (colorTab[i] & 0xff); var d = dr * dr + dg * dg + db * db; var index = i / 3; if (usedEntry[index] && (d < dmin)) { dmin = d; minpos = index; } i++; } return minpos; }
javascript
function findClosest(c) { if (colorTab === null) return -1; var r = (c & 0xFF0000) >> 16; var g = (c & 0x00FF00) >> 8; var b = (c & 0x0000FF); var minpos = 0; var dmin = 256 * 256 * 256; var len = colorTab.length; for (var i = 0; i < len;) { var dr = r - (colorTab[i++] & 0xff); var dg = g - (colorTab[i++] & 0xff); var db = b - (colorTab[i] & 0xff); var d = dr * dr + dg * dg + db * db; var index = i / 3; if (usedEntry[index] && (d < dmin)) { dmin = d; minpos = index; } i++; } return minpos; }
[ "function", "findClosest", "(", "c", ")", "{", "if", "(", "colorTab", "===", "null", ")", "return", "-", "1", ";", "var", "r", "=", "(", "c", "&", "0xFF0000", ")", ">>", "16", ";", "var", "g", "=", "(", "c", "&", "0x00FF00", ")", ">>", "8", ";", "var", "b", "=", "(", "c", "&", "0x0000FF", ")", ";", "var", "minpos", "=", "0", ";", "var", "dmin", "=", "256", "*", "256", "*", "256", ";", "var", "len", "=", "colorTab", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "len", ";", ")", "{", "var", "dr", "=", "r", "-", "(", "colorTab", "[", "i", "++", "]", "&", "0xff", ")", ";", "var", "dg", "=", "g", "-", "(", "colorTab", "[", "i", "++", "]", "&", "0xff", ")", ";", "var", "db", "=", "b", "-", "(", "colorTab", "[", "i", "]", "&", "0xff", ")", ";", "var", "d", "=", "dr", "*", "dr", "+", "dg", "*", "dg", "+", "db", "*", "db", ";", "var", "index", "=", "i", "/", "3", ";", "if", "(", "usedEntry", "[", "index", "]", "&&", "(", "d", "<", "dmin", ")", ")", "{", "dmin", "=", "d", ";", "minpos", "=", "index", ";", "}", "i", "++", ";", "}", "return", "minpos", ";", "}" ]
Returns index of palette color closest to c
[ "Returns", "index", "of", "palette", "color", "closest", "to", "c" ]
d4c694cd30783046c87dfaa05de834a6c3686dec
https://github.com/abagames/gif-capture-canvas/blob/d4c694cd30783046c87dfaa05de834a6c3686dec/web_modules/jsgif/index.js#L367-L390
train
abagames/gif-capture-canvas
web_modules/jsgif/index.js
getImagePixels
function getImagePixels() { var w = width; var h = height; pixels = []; var data = image; var count = 0; for (var i = 0; i < h; i++) { for (var j = 0; j < w; j++) { var b = (i * w * 4) + j * 4; pixels[count++] = data[b]; pixels[count++] = data[b + 1]; pixels[count++] = data[b + 2]; } } }
javascript
function getImagePixels() { var w = width; var h = height; pixels = []; var data = image; var count = 0; for (var i = 0; i < h; i++) { for (var j = 0; j < w; j++) { var b = (i * w * 4) + j * 4; pixels[count++] = data[b]; pixels[count++] = data[b + 1]; pixels[count++] = data[b + 2]; } } }
[ "function", "getImagePixels", "(", ")", "{", "var", "w", "=", "width", ";", "var", "h", "=", "height", ";", "pixels", "=", "[", "]", ";", "var", "data", "=", "image", ";", "var", "count", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "h", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "w", ";", "j", "++", ")", "{", "var", "b", "=", "(", "i", "*", "w", "*", "4", ")", "+", "j", "*", "4", ";", "pixels", "[", "count", "++", "]", "=", "data", "[", "b", "]", ";", "pixels", "[", "count", "++", "]", "=", "data", "[", "b", "+", "1", "]", ";", "pixels", "[", "count", "++", "]", "=", "data", "[", "b", "+", "2", "]", ";", "}", "}", "}" ]
Extracts image pixels into byte array "pixels
[ "Extracts", "image", "pixels", "into", "byte", "array", "pixels" ]
d4c694cd30783046c87dfaa05de834a6c3686dec
https://github.com/abagames/gif-capture-canvas/blob/d4c694cd30783046c87dfaa05de834a6c3686dec/web_modules/jsgif/index.js#L396-L415
train
abagames/gif-capture-canvas
web_modules/jsgif/index.js
writeGraphicCtrlExt
function writeGraphicCtrlExt() { out.writeByte(0x21); // extension introducer out.writeByte(0xf9); // GCE label out.writeByte(4); // data block size var transp; var disp; if (transparent === null) { transp = 0; disp = 0; // dispose = no action } else { transp = 1; disp = 2; // force clear if using transparent color } if (dispose >= 0) { disp = dispose & 7; // user override } disp <<= 2; // packed fields out.writeByte(0 | // 1:3 reserved disp | // 4:6 disposal 0 | // 7 user input - 0 = none transp); // 8 transparency flag WriteShort(delay); // delay x 1/100 sec out.writeByte(transIndex); // transparent color index out.writeByte(0); // block terminator }
javascript
function writeGraphicCtrlExt() { out.writeByte(0x21); // extension introducer out.writeByte(0xf9); // GCE label out.writeByte(4); // data block size var transp; var disp; if (transparent === null) { transp = 0; disp = 0; // dispose = no action } else { transp = 1; disp = 2; // force clear if using transparent color } if (dispose >= 0) { disp = dispose & 7; // user override } disp <<= 2; // packed fields out.writeByte(0 | // 1:3 reserved disp | // 4:6 disposal 0 | // 7 user input - 0 = none transp); // 8 transparency flag WriteShort(delay); // delay x 1/100 sec out.writeByte(transIndex); // transparent color index out.writeByte(0); // block terminator }
[ "function", "writeGraphicCtrlExt", "(", ")", "{", "out", ".", "writeByte", "(", "0x21", ")", ";", "out", ".", "writeByte", "(", "0xf9", ")", ";", "out", ".", "writeByte", "(", "4", ")", ";", "var", "transp", ";", "var", "disp", ";", "if", "(", "transparent", "===", "null", ")", "{", "transp", "=", "0", ";", "disp", "=", "0", ";", "}", "else", "{", "transp", "=", "1", ";", "disp", "=", "2", ";", "}", "if", "(", "dispose", ">=", "0", ")", "{", "disp", "=", "dispose", "&", "7", ";", "}", "disp", "<<=", "2", ";", "out", ".", "writeByte", "(", "0", "|", "disp", "|", "0", "|", "transp", ")", ";", "WriteShort", "(", "delay", ")", ";", "out", ".", "writeByte", "(", "transIndex", ")", ";", "out", ".", "writeByte", "(", "0", ")", ";", "}" ]
Writes Graphic Control Extension
[ "Writes", "Graphic", "Control", "Extension" ]
d4c694cd30783046c87dfaa05de834a6c3686dec
https://github.com/abagames/gif-capture-canvas/blob/d4c694cd30783046c87dfaa05de834a6c3686dec/web_modules/jsgif/index.js#L421-L447
train
abagames/gif-capture-canvas
web_modules/jsgif/index.js
writeCommentExt
function writeCommentExt() { out.writeByte(0x21); // extension introducer out.writeByte(0xfe); // comment label out.writeByte(comment.length); // Block Size (s) out.writeUTFBytes(comment); out.writeByte(0); // block terminator }
javascript
function writeCommentExt() { out.writeByte(0x21); // extension introducer out.writeByte(0xfe); // comment label out.writeByte(comment.length); // Block Size (s) out.writeUTFBytes(comment); out.writeByte(0); // block terminator }
[ "function", "writeCommentExt", "(", ")", "{", "out", ".", "writeByte", "(", "0x21", ")", ";", "out", ".", "writeByte", "(", "0xfe", ")", ";", "out", ".", "writeByte", "(", "comment", ".", "length", ")", ";", "out", ".", "writeUTFBytes", "(", "comment", ")", ";", "out", ".", "writeByte", "(", "0", ")", ";", "}" ]
Writes Comment Extention
[ "Writes", "Comment", "Extention" ]
d4c694cd30783046c87dfaa05de834a6c3686dec
https://github.com/abagames/gif-capture-canvas/blob/d4c694cd30783046c87dfaa05de834a6c3686dec/web_modules/jsgif/index.js#L453-L459
train
abagames/gif-capture-canvas
web_modules/jsgif/index.js
writeImageDesc
function writeImageDesc() { out.writeByte(0x2c); // image separator WriteShort(0); // image position x,y = 0,0 WriteShort(0); WriteShort(width); // image size WriteShort(height); // packed fields if (firstFrame) { // no LCT - GCT is used for first (or only) frame out.writeByte(0); } else { // specify normal LCT out.writeByte(0x80 | // 1 local color table 1=yes 0 | // 2 interlace - 0=no 0 | // 3 sorted - 0=no 0 | // 4-5 reserved palSize); // 6-8 size of color table } }
javascript
function writeImageDesc() { out.writeByte(0x2c); // image separator WriteShort(0); // image position x,y = 0,0 WriteShort(0); WriteShort(width); // image size WriteShort(height); // packed fields if (firstFrame) { // no LCT - GCT is used for first (or only) frame out.writeByte(0); } else { // specify normal LCT out.writeByte(0x80 | // 1 local color table 1=yes 0 | // 2 interlace - 0=no 0 | // 3 sorted - 0=no 0 | // 4-5 reserved palSize); // 6-8 size of color table } }
[ "function", "writeImageDesc", "(", ")", "{", "out", ".", "writeByte", "(", "0x2c", ")", ";", "WriteShort", "(", "0", ")", ";", "WriteShort", "(", "0", ")", ";", "WriteShort", "(", "width", ")", ";", "WriteShort", "(", "height", ")", ";", "if", "(", "firstFrame", ")", "{", "out", ".", "writeByte", "(", "0", ")", ";", "}", "else", "{", "out", ".", "writeByte", "(", "0x80", "|", "0", "|", "0", "|", "0", "|", "palSize", ")", ";", "}", "}" ]
Writes Image Descriptor
[ "Writes", "Image", "Descriptor" ]
d4c694cd30783046c87dfaa05de834a6c3686dec
https://github.com/abagames/gif-capture-canvas/blob/d4c694cd30783046c87dfaa05de834a6c3686dec/web_modules/jsgif/index.js#L466-L486
train
abagames/gif-capture-canvas
web_modules/jsgif/index.js
writeLSD
function writeLSD() { // logical screen size WriteShort(width); WriteShort(height); // packed fields out.writeByte((0x80 | // 1 : global color table flag = 1 (gct used) 0x70 | // 2-4 : color resolution = 7 0x00 | // 5 : gct sort flag = 0 palSize)); // 6-8 : gct size out.writeByte(0); // background color index out.writeByte(0); // pixel aspect ratio - assume 1:1 }
javascript
function writeLSD() { // logical screen size WriteShort(width); WriteShort(height); // packed fields out.writeByte((0x80 | // 1 : global color table flag = 1 (gct used) 0x70 | // 2-4 : color resolution = 7 0x00 | // 5 : gct sort flag = 0 palSize)); // 6-8 : gct size out.writeByte(0); // background color index out.writeByte(0); // pixel aspect ratio - assume 1:1 }
[ "function", "writeLSD", "(", ")", "{", "WriteShort", "(", "width", ")", ";", "WriteShort", "(", "height", ")", ";", "out", ".", "writeByte", "(", "(", "0x80", "|", "0x70", "|", "0x00", "|", "palSize", ")", ")", ";", "out", ".", "writeByte", "(", "0", ")", ";", "out", ".", "writeByte", "(", "0", ")", ";", "}" ]
Writes Logical Screen Descriptor
[ "Writes", "Logical", "Screen", "Descriptor" ]
d4c694cd30783046c87dfaa05de834a6c3686dec
https://github.com/abagames/gif-capture-canvas/blob/d4c694cd30783046c87dfaa05de834a6c3686dec/web_modules/jsgif/index.js#L492-L505
train
abagames/gif-capture-canvas
web_modules/jsgif/index.js
writeNetscapeExt
function writeNetscapeExt() { out.writeByte(0x21); // extension introducer out.writeByte(0xff); // app extension label out.writeByte(11); // block size out.writeUTFBytes("NETSCAPE" + "2.0"); // app id + auth code out.writeByte(3); // sub-block size out.writeByte(1); // loop sub-block id WriteShort(repeat); // loop count (extra iterations, 0=repeat forever) out.writeByte(0); // block terminator }
javascript
function writeNetscapeExt() { out.writeByte(0x21); // extension introducer out.writeByte(0xff); // app extension label out.writeByte(11); // block size out.writeUTFBytes("NETSCAPE" + "2.0"); // app id + auth code out.writeByte(3); // sub-block size out.writeByte(1); // loop sub-block id WriteShort(repeat); // loop count (extra iterations, 0=repeat forever) out.writeByte(0); // block terminator }
[ "function", "writeNetscapeExt", "(", ")", "{", "out", ".", "writeByte", "(", "0x21", ")", ";", "out", ".", "writeByte", "(", "0xff", ")", ";", "out", ".", "writeByte", "(", "11", ")", ";", "out", ".", "writeUTFBytes", "(", "\"NETSCAPE\"", "+", "\"2.0\"", ")", ";", "out", ".", "writeByte", "(", "3", ")", ";", "out", ".", "writeByte", "(", "1", ")", ";", "WriteShort", "(", "repeat", ")", ";", "out", ".", "writeByte", "(", "0", ")", ";", "}" ]
Writes Netscape application extension to define repeat count.
[ "Writes", "Netscape", "application", "extension", "to", "define", "repeat", "count", "." ]
d4c694cd30783046c87dfaa05de834a6c3686dec
https://github.com/abagames/gif-capture-canvas/blob/d4c694cd30783046c87dfaa05de834a6c3686dec/web_modules/jsgif/index.js#L511-L520
train
abagames/gif-capture-canvas
web_modules/jsgif/index.js
writePalette
function writePalette() { out.writeBytes(colorTab); var n = (3 * 256) - colorTab.length; for (var i = 0; i < n; i++) out.writeByte(0); }
javascript
function writePalette() { out.writeBytes(colorTab); var n = (3 * 256) - colorTab.length; for (var i = 0; i < n; i++) out.writeByte(0); }
[ "function", "writePalette", "(", ")", "{", "out", ".", "writeBytes", "(", "colorTab", ")", ";", "var", "n", "=", "(", "3", "*", "256", ")", "-", "colorTab", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "out", ".", "writeByte", "(", "0", ")", ";", "}" ]
Writes color table
[ "Writes", "color", "table" ]
d4c694cd30783046c87dfaa05de834a6c3686dec
https://github.com/abagames/gif-capture-canvas/blob/d4c694cd30783046c87dfaa05de834a6c3686dec/web_modules/jsgif/index.js#L526-L530
train
abagames/gif-capture-canvas
web_modules/jsgif/index.js
writePixels
function writePixels() { var myencoder = new LZWEncoder(width, height, indexedPixels, colorDepth); myencoder.encode(out); }
javascript
function writePixels() { var myencoder = new LZWEncoder(width, height, indexedPixels, colorDepth); myencoder.encode(out); }
[ "function", "writePixels", "(", ")", "{", "var", "myencoder", "=", "new", "LZWEncoder", "(", "width", ",", "height", ",", "indexedPixels", ",", "colorDepth", ")", ";", "myencoder", ".", "encode", "(", "out", ")", ";", "}" ]
Encodes and writes pixel data
[ "Encodes", "and", "writes", "pixel", "data" ]
d4c694cd30783046c87dfaa05de834a6c3686dec
https://github.com/abagames/gif-capture-canvas/blob/d4c694cd30783046c87dfaa05de834a6c3686dec/web_modules/jsgif/index.js#L541-L544
train
hobbyquaker/binrpc
example.js
subscribe
function subscribe() { console.log(' > ', 'init', ['xmlrpc_bin://' + thisHost + ':2031', 'test123']); rpcClient.methodCall('init', ['xmlrpc_bin://' + thisHost + ':2031', 'test123'], function (err, res) { console.log(err, res); }); }
javascript
function subscribe() { console.log(' > ', 'init', ['xmlrpc_bin://' + thisHost + ':2031', 'test123']); rpcClient.methodCall('init', ['xmlrpc_bin://' + thisHost + ':2031', 'test123'], function (err, res) { console.log(err, res); }); }
[ "function", "subscribe", "(", ")", "{", "console", ".", "log", "(", "' > '", ",", "'init'", ",", "[", "'xmlrpc_bin://'", "+", "thisHost", "+", "':2031'", ",", "'test123'", "]", ")", ";", "rpcClient", ".", "methodCall", "(", "'init'", ",", "[", "'xmlrpc_bin://'", "+", "thisHost", "+", "':2031'", ",", "'test123'", "]", ",", "function", "(", "err", ",", "res", ")", "{", "console", ".", "log", "(", "err", ",", "res", ")", ";", "}", ")", ";", "}" ]
Tell the CCU that we want to receive events
[ "Tell", "the", "CCU", "that", "we", "want", "to", "receive", "events" ]
4206e2c62be4335f742da8d41538fdbd004ff694
https://github.com/hobbyquaker/binrpc/blob/4206e2c62be4335f742da8d41538fdbd004ff694/example.js#L47-L52
train
hobbyquaker/binrpc
example.js
unsubscribe
function unsubscribe() { console.log(' > ', 'init', ['xmlrpc_bin://' + thisHost + ':2031', '']); rpcClient.methodCall('init', ['xmlrpc_bin://' + thisHost + ':2031', ''], function (err, res) { console.log(err, res); process.exit(0); }); setTimeout(function () { console.log('force quit'); process.exit(1); }, 1000); }
javascript
function unsubscribe() { console.log(' > ', 'init', ['xmlrpc_bin://' + thisHost + ':2031', '']); rpcClient.methodCall('init', ['xmlrpc_bin://' + thisHost + ':2031', ''], function (err, res) { console.log(err, res); process.exit(0); }); setTimeout(function () { console.log('force quit'); process.exit(1); }, 1000); }
[ "function", "unsubscribe", "(", ")", "{", "console", ".", "log", "(", "' > '", ",", "'init'", ",", "[", "'xmlrpc_bin://'", "+", "thisHost", "+", "':2031'", ",", "''", "]", ")", ";", "rpcClient", ".", "methodCall", "(", "'init'", ",", "[", "'xmlrpc_bin://'", "+", "thisHost", "+", "':2031'", ",", "''", "]", ",", "function", "(", "err", ",", "res", ")", "{", "console", ".", "log", "(", "err", ",", "res", ")", ";", "process", ".", "exit", "(", "0", ")", ";", "}", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "console", ".", "log", "(", "'force quit'", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", ",", "1000", ")", ";", "}" ]
Tell the CCU that we no longer want to receive events
[ "Tell", "the", "CCU", "that", "we", "no", "longer", "want", "to", "receive", "events" ]
4206e2c62be4335f742da8d41538fdbd004ff694
https://github.com/hobbyquaker/binrpc/blob/4206e2c62be4335f742da8d41538fdbd004ff694/example.js#L62-L73
train
GoblinDBRocks/GoblinDB
lib/ambush.js
restoreFn
function restoreFn(db) { return db.map(function(amb) { return Object.assign({}, amb, {action: JSONfn.parse(amb.action)}); }); }
javascript
function restoreFn(db) { return db.map(function(amb) { return Object.assign({}, amb, {action: JSONfn.parse(amb.action)}); }); }
[ "function", "restoreFn", "(", "db", ")", "{", "return", "db", ".", "map", "(", "function", "(", "amb", ")", "{", "return", "Object", ".", "assign", "(", "{", "}", ",", "amb", ",", "{", "action", ":", "JSONfn", ".", "parse", "(", "amb", ".", "action", ")", "}", ")", ";", "}", ")", ";", "}" ]
Parse functions when loading file restoring then to js valid objects. @param {array} db Ambush functions db @returns {arrat} Parsed db ready to use.
[ "Parse", "functions", "when", "loading", "file", "restoring", "then", "to", "js", "valid", "objects", "." ]
82e479396f49e5f2aa0b6bef0af91f1f187578ba
https://github.com/GoblinDBRocks/GoblinDB/blob/82e479396f49e5f2aa0b6bef0af91f1f187578ba/lib/ambush.js#L61-L65
train
GoblinDBRocks/GoblinDB
lib/ambush.js
compileFn
function compileFn(db) { return db.map(function(amb) { return Object.assign({}, amb, {action: JSONfn.stringify(amb.action)}); }); return result; }
javascript
function compileFn(db) { return db.map(function(amb) { return Object.assign({}, amb, {action: JSONfn.stringify(amb.action)}); }); return result; }
[ "function", "compileFn", "(", "db", ")", "{", "return", "db", ".", "map", "(", "function", "(", "amb", ")", "{", "return", "Object", ".", "assign", "(", "{", "}", ",", "amb", ",", "{", "action", ":", "JSONfn", ".", "stringify", "(", "amb", ".", "action", ")", "}", ")", ";", "}", ")", ";", "return", "result", ";", "}" ]
Turn actions in every ambush function into valid json strings. @param {array} db Ambush functions db. @returns {arrat} Compiled db ready to save.
[ "Turn", "actions", "in", "every", "ambush", "function", "into", "valid", "json", "strings", "." ]
82e479396f49e5f2aa0b6bef0af91f1f187578ba
https://github.com/GoblinDBRocks/GoblinDB/blob/82e479396f49e5f2aa0b6bef0af91f1f187578ba/lib/ambush.js#L73-L79
train
GoblinDBRocks/GoblinDB
lib/ambush.js
add
function add(object) { if (!_isValidAmbush(object)) { return false; } object.description = _cleanDescription(object.description); if (!_belongToAStoredAmbush(object.id)) { const newObject = Object.assign({}, object); goblin.ambush.push(newObject); goblin.ambushEmitter.emit('change', { type: 'add', value: newObject }); } else { logger('AMBUSH_ADD_ERROR'); } }
javascript
function add(object) { if (!_isValidAmbush(object)) { return false; } object.description = _cleanDescription(object.description); if (!_belongToAStoredAmbush(object.id)) { const newObject = Object.assign({}, object); goblin.ambush.push(newObject); goblin.ambushEmitter.emit('change', { type: 'add', value: newObject }); } else { logger('AMBUSH_ADD_ERROR'); } }
[ "function", "add", "(", "object", ")", "{", "if", "(", "!", "_isValidAmbush", "(", "object", ")", ")", "{", "return", "false", ";", "}", "object", ".", "description", "=", "_cleanDescription", "(", "object", ".", "description", ")", ";", "if", "(", "!", "_belongToAStoredAmbush", "(", "object", ".", "id", ")", ")", "{", "const", "newObject", "=", "Object", ".", "assign", "(", "{", "}", ",", "object", ")", ";", "goblin", ".", "ambush", ".", "push", "(", "newObject", ")", ";", "goblin", ".", "ambushEmitter", ".", "emit", "(", "'change'", ",", "{", "type", ":", "'add'", ",", "value", ":", "newObject", "}", ")", ";", "}", "else", "{", "logger", "(", "'AMBUSH_ADD_ERROR'", ")", ";", "}", "}" ]
Store a new ambush function. Validates id doesn't exist already, etc. @param {Ambush} object Ambush function data. @returns {void} Nothing.
[ "Store", "a", "new", "ambush", "function", ".", "Validates", "id", "doesn", "t", "exist", "already", "etc", "." ]
82e479396f49e5f2aa0b6bef0af91f1f187578ba
https://github.com/GoblinDBRocks/GoblinDB/blob/82e479396f49e5f2aa0b6bef0af91f1f187578ba/lib/ambush.js#L87-L101
train
GoblinDBRocks/GoblinDB
lib/ambush.js
remove
function remove(id) { if (!_isValidId(id)) { return false; } const oldValue = JSONfn.clone(goblin.ambush); _.remove(goblin.ambush, function(current) { return current.id === id; }); goblin.ambushEmitter.emit('change', { type: 'remove', oldValue: oldValue }); }
javascript
function remove(id) { if (!_isValidId(id)) { return false; } const oldValue = JSONfn.clone(goblin.ambush); _.remove(goblin.ambush, function(current) { return current.id === id; }); goblin.ambushEmitter.emit('change', { type: 'remove', oldValue: oldValue }); }
[ "function", "remove", "(", "id", ")", "{", "if", "(", "!", "_isValidId", "(", "id", ")", ")", "{", "return", "false", ";", "}", "const", "oldValue", "=", "JSONfn", ".", "clone", "(", "goblin", ".", "ambush", ")", ";", "_", ".", "remove", "(", "goblin", ".", "ambush", ",", "function", "(", "current", ")", "{", "return", "current", ".", "id", "===", "id", ";", "}", ")", ";", "goblin", ".", "ambushEmitter", ".", "emit", "(", "'change'", ",", "{", "type", ":", "'remove'", ",", "oldValue", ":", "oldValue", "}", ")", ";", "}" ]
Remove an ambush function from the database. @param {string} id Ambush function id. @returns {void} Nothing.
[ "Remove", "an", "ambush", "function", "from", "the", "database", "." ]
82e479396f49e5f2aa0b6bef0af91f1f187578ba
https://github.com/GoblinDBRocks/GoblinDB/blob/82e479396f49e5f2aa0b6bef0af91f1f187578ba/lib/ambush.js#L109-L124
train
GoblinDBRocks/GoblinDB
lib/ambush.js
update
function update(id, object) { // Validations if (!_isValidId(id)) { return false; } // Action const index = _getIndexOfId(id); if (index > -1) { if (_isValidAmbushOnUpdate(id, object)) { const current = goblin.ambush[index]; const newAmbush = Object.assign({}, current, object); newAmbush.description = _cleanDescription(newAmbush.description); // Set updated ambush goblin.ambush[index] = newAmbush; goblin.ambushEmitter.emit( 'change', { type: 'update', oldValue: JSONfn.clone(current), value: JSONfn.clone(goblin.ambush[index]) } ); } } else { logger('AMBUSH_UPDATE_INVALID_REFERENCE'); } return true; }
javascript
function update(id, object) { // Validations if (!_isValidId(id)) { return false; } // Action const index = _getIndexOfId(id); if (index > -1) { if (_isValidAmbushOnUpdate(id, object)) { const current = goblin.ambush[index]; const newAmbush = Object.assign({}, current, object); newAmbush.description = _cleanDescription(newAmbush.description); // Set updated ambush goblin.ambush[index] = newAmbush; goblin.ambushEmitter.emit( 'change', { type: 'update', oldValue: JSONfn.clone(current), value: JSONfn.clone(goblin.ambush[index]) } ); } } else { logger('AMBUSH_UPDATE_INVALID_REFERENCE'); } return true; }
[ "function", "update", "(", "id", ",", "object", ")", "{", "if", "(", "!", "_isValidId", "(", "id", ")", ")", "{", "return", "false", ";", "}", "const", "index", "=", "_getIndexOfId", "(", "id", ")", ";", "if", "(", "index", ">", "-", "1", ")", "{", "if", "(", "_isValidAmbushOnUpdate", "(", "id", ",", "object", ")", ")", "{", "const", "current", "=", "goblin", ".", "ambush", "[", "index", "]", ";", "const", "newAmbush", "=", "Object", ".", "assign", "(", "{", "}", ",", "current", ",", "object", ")", ";", "newAmbush", ".", "description", "=", "_cleanDescription", "(", "newAmbush", ".", "description", ")", ";", "goblin", ".", "ambush", "[", "index", "]", "=", "newAmbush", ";", "goblin", ".", "ambushEmitter", ".", "emit", "(", "'change'", ",", "{", "type", ":", "'update'", ",", "oldValue", ":", "JSONfn", ".", "clone", "(", "current", ")", ",", "value", ":", "JSONfn", ".", "clone", "(", "goblin", ".", "ambush", "[", "index", "]", ")", "}", ")", ";", "}", "}", "else", "{", "logger", "(", "'AMBUSH_UPDATE_INVALID_REFERENCE'", ")", ";", "}", "return", "true", ";", "}" ]
Updates an ambush function. @param {string} id Ambush function id. @param {Ambush} object Ambush function data. @returns {bool} If updated or not.
[ "Updates", "an", "ambush", "function", "." ]
82e479396f49e5f2aa0b6bef0af91f1f187578ba
https://github.com/GoblinDBRocks/GoblinDB/blob/82e479396f49e5f2aa0b6bef0af91f1f187578ba/lib/ambush.js#L133-L164
train
GoblinDBRocks/GoblinDB
lib/ambush.js
details
function details(id) { if (!_isValidId(id)) { return false; } const index = _getIndexOfId(id); if (index === -1) { return logger('AMBUSH_NOT_STORED_ID'); } return goblin.ambush[index]; }
javascript
function details(id) { if (!_isValidId(id)) { return false; } const index = _getIndexOfId(id); if (index === -1) { return logger('AMBUSH_NOT_STORED_ID'); } return goblin.ambush[index]; }
[ "function", "details", "(", "id", ")", "{", "if", "(", "!", "_isValidId", "(", "id", ")", ")", "{", "return", "false", ";", "}", "const", "index", "=", "_getIndexOfId", "(", "id", ")", ";", "if", "(", "index", "===", "-", "1", ")", "{", "return", "logger", "(", "'AMBUSH_NOT_STORED_ID'", ")", ";", "}", "return", "goblin", ".", "ambush", "[", "index", "]", ";", "}" ]
Gets an ambush function data. @param {string} id Ambush function id. @returns {Ambush} Ambush function data.
[ "Gets", "an", "ambush", "function", "data", "." ]
82e479396f49e5f2aa0b6bef0af91f1f187578ba
https://github.com/GoblinDBRocks/GoblinDB/blob/82e479396f49e5f2aa0b6bef0af91f1f187578ba/lib/ambush.js#L172-L184
train
GoblinDBRocks/GoblinDB
lib/ambush.js
list
function list(category){ let list = []; if (category && typeof(category) === 'string') { list = _(goblin.ambush).filter(function(current) { return _.includes(current.category, category); }).map('id').value(); } else { list = _(goblin.ambush).map('id').value(); } return list; }
javascript
function list(category){ let list = []; if (category && typeof(category) === 'string') { list = _(goblin.ambush).filter(function(current) { return _.includes(current.category, category); }).map('id').value(); } else { list = _(goblin.ambush).map('id').value(); } return list; }
[ "function", "list", "(", "category", ")", "{", "let", "list", "=", "[", "]", ";", "if", "(", "category", "&&", "typeof", "(", "category", ")", "===", "'string'", ")", "{", "list", "=", "_", "(", "goblin", ".", "ambush", ")", ".", "filter", "(", "function", "(", "current", ")", "{", "return", "_", ".", "includes", "(", "current", ".", "category", ",", "category", ")", ";", "}", ")", ".", "map", "(", "'id'", ")", ".", "value", "(", ")", ";", "}", "else", "{", "list", "=", "_", "(", "goblin", ".", "ambush", ")", ".", "map", "(", "'id'", ")", ".", "value", "(", ")", ";", "}", "return", "list", ";", "}" ]
List all ambush function ids that match the passed category. If actegory is a falsy then all ambush functions will be listed. @param {string} category Ambush function category. @returns {array} Ids of the ambush functions of that category.
[ "List", "all", "ambush", "function", "ids", "that", "match", "the", "passed", "category", ".", "If", "actegory", "is", "a", "falsy", "then", "all", "ambush", "functions", "will", "be", "listed", "." ]
82e479396f49e5f2aa0b6bef0af91f1f187578ba
https://github.com/GoblinDBRocks/GoblinDB/blob/82e479396f49e5f2aa0b6bef0af91f1f187578ba/lib/ambush.js#L193-L206
train
GoblinDBRocks/GoblinDB
lib/ambush.js
run
function run(id, parameter, callback) { if (!_isValidId(id)) { return false; } if (callback && typeof(callback) !== 'function') { logger('AMBUSH_NO_CALLBACK'); } const index = _getIndexOfId(id); if (index > -1) { goblin.ambush[index].action(parameter, callback); } else { logger('AMBUSH_INVALID_REFERENCE'); } }
javascript
function run(id, parameter, callback) { if (!_isValidId(id)) { return false; } if (callback && typeof(callback) !== 'function') { logger('AMBUSH_NO_CALLBACK'); } const index = _getIndexOfId(id); if (index > -1) { goblin.ambush[index].action(parameter, callback); } else { logger('AMBUSH_INVALID_REFERENCE'); } }
[ "function", "run", "(", "id", ",", "parameter", ",", "callback", ")", "{", "if", "(", "!", "_isValidId", "(", "id", ")", ")", "{", "return", "false", ";", "}", "if", "(", "callback", "&&", "typeof", "(", "callback", ")", "!==", "'function'", ")", "{", "logger", "(", "'AMBUSH_NO_CALLBACK'", ")", ";", "}", "const", "index", "=", "_getIndexOfId", "(", "id", ")", ";", "if", "(", "index", ">", "-", "1", ")", "{", "goblin", ".", "ambush", "[", "index", "]", ".", "action", "(", "parameter", ",", "callback", ")", ";", "}", "else", "{", "logger", "(", "'AMBUSH_INVALID_REFERENCE'", ")", ";", "}", "}" ]
Run an ambush function action. @param {string} id Ambush function id. @param {any} parameter First parameter for the ambush function action. @param {function} callback Second parameter for the ambush function action. @returns {array} Ids of the ambush functions of that category.
[ "Run", "an", "ambush", "function", "action", "." ]
82e479396f49e5f2aa0b6bef0af91f1f187578ba
https://github.com/GoblinDBRocks/GoblinDB/blob/82e479396f49e5f2aa0b6bef0af91f1f187578ba/lib/ambush.js#L216-L232
train
GoblinDBRocks/GoblinDB
lib/ambush.js
_isValidAmbush
function _isValidAmbush(object) { return _isValidObject(object) && _isValidId(object.id) && _isUniqueId(null, object.id) && _isValidCategory(object.category) && _isValidAction(object.action); }
javascript
function _isValidAmbush(object) { return _isValidObject(object) && _isValidId(object.id) && _isUniqueId(null, object.id) && _isValidCategory(object.category) && _isValidAction(object.action); }
[ "function", "_isValidAmbush", "(", "object", ")", "{", "return", "_isValidObject", "(", "object", ")", "&&", "_isValidId", "(", "object", ".", "id", ")", "&&", "_isUniqueId", "(", "null", ",", "object", ".", "id", ")", "&&", "_isValidCategory", "(", "object", ".", "category", ")", "&&", "_isValidAction", "(", "object", ".", "action", ")", ";", "}" ]
Validates ambush function data object on create. @param {Ambush} object Ambush function data. @returns {bool} If it's valid or not.
[ "Validates", "ambush", "function", "data", "object", "on", "create", "." ]
82e479396f49e5f2aa0b6bef0af91f1f187578ba
https://github.com/GoblinDBRocks/GoblinDB/blob/82e479396f49e5f2aa0b6bef0af91f1f187578ba/lib/ambush.js#L252-L258
train
GoblinDBRocks/GoblinDB
lib/ambush.js
_isValidAmbushOnUpdate
function _isValidAmbushOnUpdate(id, object) { return _isValidObject(object) && _isValidNotRequired(object.id, _isValidId) && _isUniqueId(id, object.id) && _isValidNotRequired(object.category, _isValidCategory) && _isValidNotRequired(object.action, _isValidAction); }
javascript
function _isValidAmbushOnUpdate(id, object) { return _isValidObject(object) && _isValidNotRequired(object.id, _isValidId) && _isUniqueId(id, object.id) && _isValidNotRequired(object.category, _isValidCategory) && _isValidNotRequired(object.action, _isValidAction); }
[ "function", "_isValidAmbushOnUpdate", "(", "id", ",", "object", ")", "{", "return", "_isValidObject", "(", "object", ")", "&&", "_isValidNotRequired", "(", "object", ".", "id", ",", "_isValidId", ")", "&&", "_isUniqueId", "(", "id", ",", "object", ".", "id", ")", "&&", "_isValidNotRequired", "(", "object", ".", "category", ",", "_isValidCategory", ")", "&&", "_isValidNotRequired", "(", "object", ".", "action", ",", "_isValidAction", ")", ";", "}" ]
Validates ambush function data object on update. @param {string} id Ambush function id. @param {Ambush} object Ambush function data. @returns {bool} If it's valid or not.
[ "Validates", "ambush", "function", "data", "object", "on", "update", "." ]
82e479396f49e5f2aa0b6bef0af91f1f187578ba
https://github.com/GoblinDBRocks/GoblinDB/blob/82e479396f49e5f2aa0b6bef0af91f1f187578ba/lib/ambush.js#L267-L273
train
GoblinDBRocks/GoblinDB
lib/ambush.js
_isUniqueId
function _isUniqueId(currentId, newId) { if ( newId !== undefined && currentId !== newId && _belongToAStoredAmbush(newId) ) { logger('AMBUSH_PROVIDED_ID_ALREADY_EXIST'); return false; } return true; }
javascript
function _isUniqueId(currentId, newId) { if ( newId !== undefined && currentId !== newId && _belongToAStoredAmbush(newId) ) { logger('AMBUSH_PROVIDED_ID_ALREADY_EXIST'); return false; } return true; }
[ "function", "_isUniqueId", "(", "currentId", ",", "newId", ")", "{", "if", "(", "newId", "!==", "undefined", "&&", "currentId", "!==", "newId", "&&", "_belongToAStoredAmbush", "(", "newId", ")", ")", "{", "logger", "(", "'AMBUSH_PROVIDED_ID_ALREADY_EXIST'", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Validates an id doesn't belong to an already stored ambush function. When updating an ambush function id check if the new id it's already in use. @param {string} currentId Ambush function current id. @param {string} newId Ambush function new id. @returns {bool} If it already exist or not.
[ "Validates", "an", "id", "doesn", "t", "belong", "to", "an", "already", "stored", "ambush", "function", ".", "When", "updating", "an", "ambush", "function", "id", "check", "if", "the", "new", "id", "it", "s", "already", "in", "use", "." ]
82e479396f49e5f2aa0b6bef0af91f1f187578ba
https://github.com/GoblinDBRocks/GoblinDB/blob/82e479396f49e5f2aa0b6bef0af91f1f187578ba/lib/ambush.js#L343-L354
train
GoblinDBRocks/GoblinDB
lib/database.js
init
function init(cb) { Storage.read(goblin.config.files.db, {}, function(err, db) { if (err) { return cb(err); } goblin.db = db; cb(); }) }
javascript
function init(cb) { Storage.read(goblin.config.files.db, {}, function(err, db) { if (err) { return cb(err); } goblin.db = db; cb(); }) }
[ "function", "init", "(", "cb", ")", "{", "Storage", ".", "read", "(", "goblin", ".", "config", ".", "files", ".", "db", ",", "{", "}", ",", "function", "(", "err", ",", "db", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "goblin", ".", "db", "=", "db", ";", "cb", "(", ")", ";", "}", ")", "}" ]
Initialize database. @param {function} cb Callback function called when the database is initialized, meaning the functions have been restored from file. The function gets a parameter which is an error message if any. @returns {void}
[ "Initialize", "database", "." ]
82e479396f49e5f2aa0b6bef0af91f1f187578ba
https://github.com/GoblinDBRocks/GoblinDB/blob/82e479396f49e5f2aa0b6bef0af91f1f187578ba/lib/database.js#L33-L42
train
GoblinDBRocks/GoblinDB
lib/database.js
get
function get(point) { if (point && typeof(point) === 'string') { const tree = point.split(goblin.config.pointerSymbol); let parent = goblin.db; for (let i = 0; i < tree.length; i++) { if(i !== tree.length-1) { if(typeof parent[tree[i]] === 'undefined') { // If there is no child here, won't be deeper. Return undefined return undefined; } parent = parent[tree[i]]; } else { return parent[tree[i]]; } } } else { return goblin.db; } }
javascript
function get(point) { if (point && typeof(point) === 'string') { const tree = point.split(goblin.config.pointerSymbol); let parent = goblin.db; for (let i = 0; i < tree.length; i++) { if(i !== tree.length-1) { if(typeof parent[tree[i]] === 'undefined') { // If there is no child here, won't be deeper. Return undefined return undefined; } parent = parent[tree[i]]; } else { return parent[tree[i]]; } } } else { return goblin.db; } }
[ "function", "get", "(", "point", ")", "{", "if", "(", "point", "&&", "typeof", "(", "point", ")", "===", "'string'", ")", "{", "const", "tree", "=", "point", ".", "split", "(", "goblin", ".", "config", ".", "pointerSymbol", ")", ";", "let", "parent", "=", "goblin", ".", "db", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "tree", ".", "length", ";", "i", "++", ")", "{", "if", "(", "i", "!==", "tree", ".", "length", "-", "1", ")", "{", "if", "(", "typeof", "parent", "[", "tree", "[", "i", "]", "]", "===", "'undefined'", ")", "{", "return", "undefined", ";", "}", "parent", "=", "parent", "[", "tree", "[", "i", "]", "]", ";", "}", "else", "{", "return", "parent", "[", "tree", "[", "i", "]", "]", ";", "}", "}", "}", "else", "{", "return", "goblin", ".", "db", ";", "}", "}" ]
Gets the data from a point in the nested tree. If you don't set a point then all db will be returned. @param {string} point The place where the data is stored. If there is no such place in the nested tree then it'll return undefined. @returns {any} The stored data.
[ "Gets", "the", "data", "from", "a", "point", "in", "the", "nested", "tree", ".", "If", "you", "don", "t", "set", "a", "point", "then", "all", "db", "will", "be", "returned", "." ]
82e479396f49e5f2aa0b6bef0af91f1f187578ba
https://github.com/GoblinDBRocks/GoblinDB/blob/82e479396f49e5f2aa0b6bef0af91f1f187578ba/lib/database.js#L52-L71
train
GoblinDBRocks/GoblinDB
lib/database.js
push
function push(data, point) { if (!point) { point = ''; } else if (typeof(point) === 'string') { point = point + '.'; } else { logger('DB_SAVE_INVALID_REFERENCE'); } const newKey = point + randomstring.generate(); set(data, newKey, true); goblin.goblinDataEmitter.emit('change', { type: 'push', value: data, key: newKey }); }
javascript
function push(data, point) { if (!point) { point = ''; } else if (typeof(point) === 'string') { point = point + '.'; } else { logger('DB_SAVE_INVALID_REFERENCE'); } const newKey = point + randomstring.generate(); set(data, newKey, true); goblin.goblinDataEmitter.emit('change', { type: 'push', value: data, key: newKey }); }
[ "function", "push", "(", "data", ",", "point", ")", "{", "if", "(", "!", "point", ")", "{", "point", "=", "''", ";", "}", "else", "if", "(", "typeof", "(", "point", ")", "===", "'string'", ")", "{", "point", "=", "point", "+", "'.'", ";", "}", "else", "{", "logger", "(", "'DB_SAVE_INVALID_REFERENCE'", ")", ";", "}", "const", "newKey", "=", "point", "+", "randomstring", ".", "generate", "(", ")", ";", "set", "(", "data", ",", "newKey", ",", "true", ")", ";", "goblin", ".", "goblinDataEmitter", ".", "emit", "(", "'change'", ",", "{", "type", ":", "'push'", ",", "value", ":", "data", ",", "key", ":", "newKey", "}", ")", ";", "}" ]
Push data to a point in the database nested tree. If you don't set a point where to store the data then it'll be stored in higher level, in that case the data can not be an array. The first element of the DB has to be always an object. @param {object | array} data The data to store in the database. @param {string} point The place to store the data. @returns {void}
[ "Push", "data", "to", "a", "point", "in", "the", "database", "nested", "tree", ".", "If", "you", "don", "t", "set", "a", "point", "where", "to", "store", "the", "data", "then", "it", "ll", "be", "stored", "in", "higher", "level", "in", "that", "case", "the", "data", "can", "not", "be", "an", "array", ".", "The", "first", "element", "of", "the", "DB", "has", "to", "be", "always", "an", "object", "." ]
82e479396f49e5f2aa0b6bef0af91f1f187578ba
https://github.com/GoblinDBRocks/GoblinDB/blob/82e479396f49e5f2aa0b6bef0af91f1f187578ba/lib/database.js#L82-L98
train
GoblinDBRocks/GoblinDB
lib/database.js
set
function set(data, point, silent) { if (!data || typeof(data) !== 'object') { return logger('DB_SAVE_INVALID_DATA'); } if (point && typeof(point) === 'string') { const tree = point.split(goblin.config.pointerSymbol); let parent = goblin.db; for (let i = 0; i < tree.length; i++) { if (i !== tree.length - 1) { if (typeof parent[tree[i]] === 'undefined') { parent[tree[i]] = {}; } parent = parent[tree[i]]; } else { if (!silent) { goblin.goblinDataEmitter.emit('change', { type: 'set', value: data, oldValue: goblin.db[point], key: point }); } parent[tree[i]] = data; } } } else { if (Array.isArray(data)) { return logger('DB_SAVE_ARRAY'); } const oldValue = goblin.db; goblin.db = data; !silent && goblin.goblinDataEmitter.emit('change', { type: 'set', value: goblin.db, oldValue: oldValue }); } }
javascript
function set(data, point, silent) { if (!data || typeof(data) !== 'object') { return logger('DB_SAVE_INVALID_DATA'); } if (point && typeof(point) === 'string') { const tree = point.split(goblin.config.pointerSymbol); let parent = goblin.db; for (let i = 0; i < tree.length; i++) { if (i !== tree.length - 1) { if (typeof parent[tree[i]] === 'undefined') { parent[tree[i]] = {}; } parent = parent[tree[i]]; } else { if (!silent) { goblin.goblinDataEmitter.emit('change', { type: 'set', value: data, oldValue: goblin.db[point], key: point }); } parent[tree[i]] = data; } } } else { if (Array.isArray(data)) { return logger('DB_SAVE_ARRAY'); } const oldValue = goblin.db; goblin.db = data; !silent && goblin.goblinDataEmitter.emit('change', { type: 'set', value: goblin.db, oldValue: oldValue }); } }
[ "function", "set", "(", "data", ",", "point", ",", "silent", ")", "{", "if", "(", "!", "data", "||", "typeof", "(", "data", ")", "!==", "'object'", ")", "{", "return", "logger", "(", "'DB_SAVE_INVALID_DATA'", ")", ";", "}", "if", "(", "point", "&&", "typeof", "(", "point", ")", "===", "'string'", ")", "{", "const", "tree", "=", "point", ".", "split", "(", "goblin", ".", "config", ".", "pointerSymbol", ")", ";", "let", "parent", "=", "goblin", ".", "db", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "tree", ".", "length", ";", "i", "++", ")", "{", "if", "(", "i", "!==", "tree", ".", "length", "-", "1", ")", "{", "if", "(", "typeof", "parent", "[", "tree", "[", "i", "]", "]", "===", "'undefined'", ")", "{", "parent", "[", "tree", "[", "i", "]", "]", "=", "{", "}", ";", "}", "parent", "=", "parent", "[", "tree", "[", "i", "]", "]", ";", "}", "else", "{", "if", "(", "!", "silent", ")", "{", "goblin", ".", "goblinDataEmitter", ".", "emit", "(", "'change'", ",", "{", "type", ":", "'set'", ",", "value", ":", "data", ",", "oldValue", ":", "goblin", ".", "db", "[", "point", "]", ",", "key", ":", "point", "}", ")", ";", "}", "parent", "[", "tree", "[", "i", "]", "]", "=", "data", ";", "}", "}", "}", "else", "{", "if", "(", "Array", ".", "isArray", "(", "data", ")", ")", "{", "return", "logger", "(", "'DB_SAVE_ARRAY'", ")", ";", "}", "const", "oldValue", "=", "goblin", ".", "db", ";", "goblin", ".", "db", "=", "data", ";", "!", "silent", "&&", "goblin", ".", "goblinDataEmitter", ".", "emit", "(", "'change'", ",", "{", "type", ":", "'set'", ",", "value", ":", "goblin", ".", "db", ",", "oldValue", ":", "oldValue", "}", ")", ";", "}", "}" ]
Set data to a point in the database nested tree. If you don't set a point where to store the data then it'll be stored in higher level, in that case the data can not be an array. The first element of the DB has to be always an object. @param {object | array} data The data to store in the database. @param {string} point The place to store the data. @param {bool} silent Internal use. When this is true this method doesn't trigger events. @returns {void}
[ "Set", "data", "to", "a", "point", "in", "the", "database", "nested", "tree", ".", "If", "you", "don", "t", "set", "a", "point", "where", "to", "store", "the", "data", "then", "it", "ll", "be", "stored", "in", "higher", "level", "in", "that", "case", "the", "data", "can", "not", "be", "an", "array", ".", "The", "first", "element", "of", "the", "DB", "has", "to", "be", "always", "an", "object", "." ]
82e479396f49e5f2aa0b6bef0af91f1f187578ba
https://github.com/GoblinDBRocks/GoblinDB/blob/82e479396f49e5f2aa0b6bef0af91f1f187578ba/lib/database.js#L112-L154
train
GoblinDBRocks/GoblinDB
lib/database.js
update
function update(data, point) { if (!data || typeof(data) !== 'object') { return logger('DB_SAVE_INVALID_DATA'); } if (point && typeof(point) === 'string') { const tree = point.split('.'); let parent = goblin.db; for (let i = 0; i < tree.length; i++) { if (i !== tree.length-1) { if (typeof parent[tree[i]] === 'undefined') { parent[tree[i]] = {}; } parent = parent[tree[i]]; } else { const oldValue = parent[tree[i]]; parent[tree[i]] = Object.assign({}, goblin.db, data); goblin.goblinDataEmitter.emit('change', { type: 'update', value: parent[tree[i]], oldValue: oldValue, key: point }); } } } else { if (Array.isArray(data)) { return logger('DB_SAVE_ARRAY'); } const oldValue = goblin.db; goblin.db = Object.assign({}, goblin.db, data); goblin.goblinDataEmitter.emit('change', { type: 'update', value: goblin.db, oldValue: oldValue }); } }
javascript
function update(data, point) { if (!data || typeof(data) !== 'object') { return logger('DB_SAVE_INVALID_DATA'); } if (point && typeof(point) === 'string') { const tree = point.split('.'); let parent = goblin.db; for (let i = 0; i < tree.length; i++) { if (i !== tree.length-1) { if (typeof parent[tree[i]] === 'undefined') { parent[tree[i]] = {}; } parent = parent[tree[i]]; } else { const oldValue = parent[tree[i]]; parent[tree[i]] = Object.assign({}, goblin.db, data); goblin.goblinDataEmitter.emit('change', { type: 'update', value: parent[tree[i]], oldValue: oldValue, key: point }); } } } else { if (Array.isArray(data)) { return logger('DB_SAVE_ARRAY'); } const oldValue = goblin.db; goblin.db = Object.assign({}, goblin.db, data); goblin.goblinDataEmitter.emit('change', { type: 'update', value: goblin.db, oldValue: oldValue }); } }
[ "function", "update", "(", "data", ",", "point", ")", "{", "if", "(", "!", "data", "||", "typeof", "(", "data", ")", "!==", "'object'", ")", "{", "return", "logger", "(", "'DB_SAVE_INVALID_DATA'", ")", ";", "}", "if", "(", "point", "&&", "typeof", "(", "point", ")", "===", "'string'", ")", "{", "const", "tree", "=", "point", ".", "split", "(", "'.'", ")", ";", "let", "parent", "=", "goblin", ".", "db", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "tree", ".", "length", ";", "i", "++", ")", "{", "if", "(", "i", "!==", "tree", ".", "length", "-", "1", ")", "{", "if", "(", "typeof", "parent", "[", "tree", "[", "i", "]", "]", "===", "'undefined'", ")", "{", "parent", "[", "tree", "[", "i", "]", "]", "=", "{", "}", ";", "}", "parent", "=", "parent", "[", "tree", "[", "i", "]", "]", ";", "}", "else", "{", "const", "oldValue", "=", "parent", "[", "tree", "[", "i", "]", "]", ";", "parent", "[", "tree", "[", "i", "]", "]", "=", "Object", ".", "assign", "(", "{", "}", ",", "goblin", ".", "db", ",", "data", ")", ";", "goblin", ".", "goblinDataEmitter", ".", "emit", "(", "'change'", ",", "{", "type", ":", "'update'", ",", "value", ":", "parent", "[", "tree", "[", "i", "]", "]", ",", "oldValue", ":", "oldValue", ",", "key", ":", "point", "}", ")", ";", "}", "}", "}", "else", "{", "if", "(", "Array", ".", "isArray", "(", "data", ")", ")", "{", "return", "logger", "(", "'DB_SAVE_ARRAY'", ")", ";", "}", "const", "oldValue", "=", "goblin", ".", "db", ";", "goblin", ".", "db", "=", "Object", ".", "assign", "(", "{", "}", ",", "goblin", ".", "db", ",", "data", ")", ";", "goblin", ".", "goblinDataEmitter", ".", "emit", "(", "'change'", ",", "{", "type", ":", "'update'", ",", "value", ":", "goblin", ".", "db", ",", "oldValue", ":", "oldValue", "}", ")", ";", "}", "}" ]
Update data to a point in the database nested tree. If you don't set a point where to update the stored data then it'll replace all db, in that case the data can not be an array. The first element of the DB has to be always an object. @param {object | array} data The data to store in the database. @param {string} point The place to store the data. @returns {void}
[ "Update", "data", "to", "a", "point", "in", "the", "database", "nested", "tree", ".", "If", "you", "don", "t", "set", "a", "point", "where", "to", "update", "the", "stored", "data", "then", "it", "ll", "replace", "all", "db", "in", "that", "case", "the", "data", "can", "not", "be", "an", "array", ".", "The", "first", "element", "of", "the", "DB", "has", "to", "be", "always", "an", "object", "." ]
82e479396f49e5f2aa0b6bef0af91f1f187578ba
https://github.com/GoblinDBRocks/GoblinDB/blob/82e479396f49e5f2aa0b6bef0af91f1f187578ba/lib/database.js#L166-L205
train
GoblinDBRocks/GoblinDB
lib/database.js
deleteFn
function deleteFn(point) { if (point && typeof(point) === 'string') { const tree = point.split('.'); let source = goblin.db; return tree.every((node, i) => { if (source[node] === undefined) { logger('DB_DELETE_INVALID_POINT', node); return false; } if (i === tree.length - 1) { let oldValue = source[node]; if (Array.isArray(source)) { source.splice(node, 1); return true; } if (delete source[node]) { goblin.goblinDataEmitter.emit('change', { type: 'delete', value: undefined, oldValue: oldValue }); return true; } else { return false; } } source = source[node]; return true; }); } logger('DB_DELETE_MISSING_POINT'); return false; }
javascript
function deleteFn(point) { if (point && typeof(point) === 'string') { const tree = point.split('.'); let source = goblin.db; return tree.every((node, i) => { if (source[node] === undefined) { logger('DB_DELETE_INVALID_POINT', node); return false; } if (i === tree.length - 1) { let oldValue = source[node]; if (Array.isArray(source)) { source.splice(node, 1); return true; } if (delete source[node]) { goblin.goblinDataEmitter.emit('change', { type: 'delete', value: undefined, oldValue: oldValue }); return true; } else { return false; } } source = source[node]; return true; }); } logger('DB_DELETE_MISSING_POINT'); return false; }
[ "function", "deleteFn", "(", "point", ")", "{", "if", "(", "point", "&&", "typeof", "(", "point", ")", "===", "'string'", ")", "{", "const", "tree", "=", "point", ".", "split", "(", "'.'", ")", ";", "let", "source", "=", "goblin", ".", "db", ";", "return", "tree", ".", "every", "(", "(", "node", ",", "i", ")", "=>", "{", "if", "(", "source", "[", "node", "]", "===", "undefined", ")", "{", "logger", "(", "'DB_DELETE_INVALID_POINT'", ",", "node", ")", ";", "return", "false", ";", "}", "if", "(", "i", "===", "tree", ".", "length", "-", "1", ")", "{", "let", "oldValue", "=", "source", "[", "node", "]", ";", "if", "(", "Array", ".", "isArray", "(", "source", ")", ")", "{", "source", ".", "splice", "(", "node", ",", "1", ")", ";", "return", "true", ";", "}", "if", "(", "delete", "source", "[", "node", "]", ")", "{", "goblin", ".", "goblinDataEmitter", ".", "emit", "(", "'change'", ",", "{", "type", ":", "'delete'", ",", "value", ":", "undefined", ",", "oldValue", ":", "oldValue", "}", ")", ";", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}", "source", "=", "source", "[", "node", "]", ";", "return", "true", ";", "}", ")", ";", "}", "logger", "(", "'DB_DELETE_MISSING_POINT'", ")", ";", "return", "false", ";", "}" ]
Deletes the content stored where point indicates. @param {string} point The place where the data is stored. @returns {bool} Success
[ "Deletes", "the", "content", "stored", "where", "point", "indicates", "." ]
82e479396f49e5f2aa0b6bef0af91f1f187578ba
https://github.com/GoblinDBRocks/GoblinDB/blob/82e479396f49e5f2aa0b6bef0af91f1f187578ba/lib/database.js#L213-L252
train
Bitcoin-com/wormhole-sdk
examples/send-bch/send-bch.js
changeAddrFromMnemonic
function changeAddrFromMnemonic(mnemonic) { // root seed buffer const rootSeed = Wormhole.Mnemonic.toSeed(mnemonic) // master HDNode let masterHDNode if (NETWORK === "testnet") masterHDNode = Wormhole.HDNode.fromSeed(rootSeed, "testnet") else masterHDNode = Wormhole.HDNode.fromSeed(rootSeed) // HDNode of BIP44 account const account = Wormhole.HDNode.derivePath(masterHDNode, "m/44'/145'/0'") // derive the first external change address HDNode which is going to spend utxo const change = Wormhole.HDNode.derivePath(account, "0/0") return change }
javascript
function changeAddrFromMnemonic(mnemonic) { // root seed buffer const rootSeed = Wormhole.Mnemonic.toSeed(mnemonic) // master HDNode let masterHDNode if (NETWORK === "testnet") masterHDNode = Wormhole.HDNode.fromSeed(rootSeed, "testnet") else masterHDNode = Wormhole.HDNode.fromSeed(rootSeed) // HDNode of BIP44 account const account = Wormhole.HDNode.derivePath(masterHDNode, "m/44'/145'/0'") // derive the first external change address HDNode which is going to spend utxo const change = Wormhole.HDNode.derivePath(account, "0/0") return change }
[ "function", "changeAddrFromMnemonic", "(", "mnemonic", ")", "{", "const", "rootSeed", "=", "Wormhole", ".", "Mnemonic", ".", "toSeed", "(", "mnemonic", ")", "let", "masterHDNode", "if", "(", "NETWORK", "===", "\"testnet\"", ")", "masterHDNode", "=", "Wormhole", ".", "HDNode", ".", "fromSeed", "(", "rootSeed", ",", "\"testnet\"", ")", "else", "masterHDNode", "=", "Wormhole", ".", "HDNode", ".", "fromSeed", "(", "rootSeed", ")", "const", "account", "=", "Wormhole", ".", "HDNode", ".", "derivePath", "(", "masterHDNode", ",", "\"m/44'/145'/0'\"", ")", "const", "change", "=", "Wormhole", ".", "HDNode", ".", "derivePath", "(", "account", ",", "\"0/0\"", ")", "return", "change", "}" ]
Generate a change address from a Mnemonic of a private key.
[ "Generate", "a", "change", "address", "from", "a", "Mnemonic", "of", "a", "private", "key", "." ]
13dd35295b0b3a6bb84e895f96c978cbb906193b
https://github.com/Bitcoin-com/wormhole-sdk/blob/13dd35295b0b3a6bb84e895f96c978cbb906193b/examples/send-bch/send-bch.js#L125-L142
train
MrSlide/parseSRT
src/parse-srt.js
lastNonEmptyLine
function lastNonEmptyLine (linesArray) { let idx = linesArray.length - 1 while (idx >= 0 && !linesArray[idx]) { idx-- } return idx }
javascript
function lastNonEmptyLine (linesArray) { let idx = linesArray.length - 1 while (idx >= 0 && !linesArray[idx]) { idx-- } return idx }
[ "function", "lastNonEmptyLine", "(", "linesArray", ")", "{", "let", "idx", "=", "linesArray", ".", "length", "-", "1", "while", "(", "idx", ">=", "0", "&&", "!", "linesArray", "[", "idx", "]", ")", "{", "idx", "--", "}", "return", "idx", "}" ]
Get the last non empty line number. @private @param {Array<String>} linesArray - All the lines. @return {Number} - The number of the last non empty line.
[ "Get", "the", "last", "non", "empty", "line", "number", "." ]
a643978ca81590496ab3e9a471256b7efe04ffe3
https://github.com/MrSlide/parseSRT/blob/a643978ca81590496ab3e9a471256b7efe04ffe3/src/parse-srt.js#L69-L77
train
GoblinDBRocks/GoblinDB
lib/storage/filesystem.js
writeToFile
function writeToFile(file) { if (!writeQueue[file]) { return; } // If not already saving then save, but using the object we make sure to take only // the last changes. // Truncate - https://stackoverflow.com/questions/35178903/overwrite-a-file-in-node-js fs.truncate(file, err => { const beforeSaveVersion = writeQueue[file].version; fse.outputJson(file, writeQueue[file].db, err => { // Something has been saved while the filesystem was writing to file then // save again if (beforeSaveVersion !== writeQueue[file].version) { writeToFile(file); } resolveAllWriteQueueCallbacks(file, err); delete writeQueue[file]; }); }); }
javascript
function writeToFile(file) { if (!writeQueue[file]) { return; } // If not already saving then save, but using the object we make sure to take only // the last changes. // Truncate - https://stackoverflow.com/questions/35178903/overwrite-a-file-in-node-js fs.truncate(file, err => { const beforeSaveVersion = writeQueue[file].version; fse.outputJson(file, writeQueue[file].db, err => { // Something has been saved while the filesystem was writing to file then // save again if (beforeSaveVersion !== writeQueue[file].version) { writeToFile(file); } resolveAllWriteQueueCallbacks(file, err); delete writeQueue[file]; }); }); }
[ "function", "writeToFile", "(", "file", ")", "{", "if", "(", "!", "writeQueue", "[", "file", "]", ")", "{", "return", ";", "}", "fs", ".", "truncate", "(", "file", ",", "err", "=>", "{", "const", "beforeSaveVersion", "=", "writeQueue", "[", "file", "]", ".", "version", ";", "fse", ".", "outputJson", "(", "file", ",", "writeQueue", "[", "file", "]", ".", "db", ",", "err", "=>", "{", "if", "(", "beforeSaveVersion", "!==", "writeQueue", "[", "file", "]", ".", "version", ")", "{", "writeToFile", "(", "file", ")", ";", "}", "resolveAllWriteQueueCallbacks", "(", "file", ",", "err", ")", ";", "delete", "writeQueue", "[", "file", "]", ";", "}", ")", ";", "}", ")", ";", "}" ]
Save db data to a file from the write queue. @param {string} file File path. @returns {void} Nothing
[ "Save", "db", "data", "to", "a", "file", "from", "the", "write", "queue", "." ]
82e479396f49e5f2aa0b6bef0af91f1f187578ba
https://github.com/GoblinDBRocks/GoblinDB/blob/82e479396f49e5f2aa0b6bef0af91f1f187578ba/lib/storage/filesystem.js#L67-L88
train
GoblinDBRocks/GoblinDB
lib/storage/filesystem.js
resolveAllWriteQueueCallbacks
function resolveAllWriteQueueCallbacks(file, error) { writeQueue[file].callbacks.forEach(cb => cb(error)); }
javascript
function resolveAllWriteQueueCallbacks(file, error) { writeQueue[file].callbacks.forEach(cb => cb(error)); }
[ "function", "resolveAllWriteQueueCallbacks", "(", "file", ",", "error", ")", "{", "writeQueue", "[", "file", "]", ".", "callbacks", ".", "forEach", "(", "cb", "=>", "cb", "(", "error", ")", ")", ";", "}" ]
Internal. Call to every callback of a the write queue for a file. @param {string} file File path . @param {string} error Error message or null. @returns {void} Nothing.
[ "Internal", ".", "Call", "to", "every", "callback", "of", "a", "the", "write", "queue", "for", "a", "file", "." ]
82e479396f49e5f2aa0b6bef0af91f1f187578ba
https://github.com/GoblinDBRocks/GoblinDB/blob/82e479396f49e5f2aa0b6bef0af91f1f187578ba/lib/storage/filesystem.js#L120-L122
train
monotonee/escape-regex-string
index.js
escapeRegexString
function escapeRegexString(unescapedString, escapeCharsRegex) { // Validate arguments. if (Object.prototype.toString.call(unescapedString) !== '[object String]') { throw new TypeError('Argument 1 should be a string.'); } if (escapeCharsRegex === undefined) { escapeCharsRegex = defaultEscapeCharsRegex; } else if (Object.prototype.toString.call(escapeCharsRegex) !== '[object RegExp]') { throw new TypeError('Argument 2 should be a RegExp object.'); } // Escape the string. return unescapedString.replace(escapeCharsRegex, '\\$&'); }
javascript
function escapeRegexString(unescapedString, escapeCharsRegex) { // Validate arguments. if (Object.prototype.toString.call(unescapedString) !== '[object String]') { throw new TypeError('Argument 1 should be a string.'); } if (escapeCharsRegex === undefined) { escapeCharsRegex = defaultEscapeCharsRegex; } else if (Object.prototype.toString.call(escapeCharsRegex) !== '[object RegExp]') { throw new TypeError('Argument 2 should be a RegExp object.'); } // Escape the string. return unescapedString.replace(escapeCharsRegex, '\\$&'); }
[ "function", "escapeRegexString", "(", "unescapedString", ",", "escapeCharsRegex", ")", "{", "if", "(", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "unescapedString", ")", "!==", "'[object String]'", ")", "{", "throw", "new", "TypeError", "(", "'Argument 1 should be a string.'", ")", ";", "}", "if", "(", "escapeCharsRegex", "===", "undefined", ")", "{", "escapeCharsRegex", "=", "defaultEscapeCharsRegex", ";", "}", "else", "if", "(", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "escapeCharsRegex", ")", "!==", "'[object RegExp]'", ")", "{", "throw", "new", "TypeError", "(", "'Argument 2 should be a RegExp object.'", ")", ";", "}", "return", "unescapedString", ".", "replace", "(", "escapeCharsRegex", ",", "'\\\\$&'", ")", ";", "}" ]
Escape a string literal for use as an argument in the standard RegExp constructor. @alias module:escape-regex-string @param {string} unescapedString - The string containing a regex pattern to be escaped. @param {RegExp} [escapeCharsRegex] - An optional RegEx pattern containing a set of characters to escape. If not passed, value will be set to default. @return {string} - The escaped regex pattern string. @throws {TypeError} - Arguments must be correct type. @property {RegExp} defaultEscapeCharsRegex - A read-only property that contains the default escape character RegExp instance. The value of this property is the value used when the optional second argument is omitted in a call to {@link module:escape-regex-string}.
[ "Escape", "a", "string", "literal", "for", "use", "as", "an", "argument", "in", "the", "standard", "RegExp", "constructor", "." ]
9f46a7e4bb6b3b40bcd487005947235fdeaa84c6
https://github.com/monotonee/escape-regex-string/blob/9f46a7e4bb6b3b40bcd487005947235fdeaa84c6/index.js#L26-L39
train
observing/argh
index.js
parse
function parse(argv) { argv = argv || process.argv.slice(2); /** * This is where the actual parsing happens, we can use array#reduce to * iterate over the arguments and change it to an object. We can easily bail * out of the loop by destroying `argv` array. * * @param {Object} argh The object that stores the parsed arguments * @param {String} option The command line flag * @param {Number} index The position of the flag in argv's * @param {Array} argv The argument variables * @returns {Object} argh, the parsed commands * @api private */ return argv.reduce(function parser(argh, option, index, argv) { var next = argv[index + 1] , value , data; // // Special case, -- indicates that it should stop parsing the options and // store everything in a "special" key. // if (option === '--') { // // By splicing the argv array, we also cancel the reduce as there are no // more options to parse. // argh.argv = argh.argv || []; argh.argv = argh.argv.concat(argv.splice(index + 1)); return argh; } if (data = /^--?(?:no|disable)-(.*)/.exec(option)) { // // --no-<key> indicates that this is a boolean value. // insert(argh, data[1], false, option); } else if (data = /^-(?!-)(.*)/.exec(option)) { insert(argh, data[1], true, option); } else if (data = /^--([^=]+)=["']?([\s!#$%&\x28-\x7e]+)["']?$/.exec(option)) { // // --foo="bar" and --foo=bar are alternate styles to --foo bar. // insert(argh, data[1], data[2], option); } else if (data = /^--(.*)/.exec(option)) { // // Check if this was a bool argument // if (!next || next.charAt(0) === '-' || (value = /^true|false$/.test(next))) { insert(argh, data[1], value ? argv.splice(index + 1, 1)[0] : true, option); } else { value = argv.splice(index + 1, 1)[0]; insert(argh, data[1], value, option); } } else { // // This argument is not prefixed. // if (!argh.argv) argh.argv = []; argh.argv.push(option); } return argh; }, Object.create(null)); }
javascript
function parse(argv) { argv = argv || process.argv.slice(2); /** * This is where the actual parsing happens, we can use array#reduce to * iterate over the arguments and change it to an object. We can easily bail * out of the loop by destroying `argv` array. * * @param {Object} argh The object that stores the parsed arguments * @param {String} option The command line flag * @param {Number} index The position of the flag in argv's * @param {Array} argv The argument variables * @returns {Object} argh, the parsed commands * @api private */ return argv.reduce(function parser(argh, option, index, argv) { var next = argv[index + 1] , value , data; // // Special case, -- indicates that it should stop parsing the options and // store everything in a "special" key. // if (option === '--') { // // By splicing the argv array, we also cancel the reduce as there are no // more options to parse. // argh.argv = argh.argv || []; argh.argv = argh.argv.concat(argv.splice(index + 1)); return argh; } if (data = /^--?(?:no|disable)-(.*)/.exec(option)) { // // --no-<key> indicates that this is a boolean value. // insert(argh, data[1], false, option); } else if (data = /^-(?!-)(.*)/.exec(option)) { insert(argh, data[1], true, option); } else if (data = /^--([^=]+)=["']?([\s!#$%&\x28-\x7e]+)["']?$/.exec(option)) { // // --foo="bar" and --foo=bar are alternate styles to --foo bar. // insert(argh, data[1], data[2], option); } else if (data = /^--(.*)/.exec(option)) { // // Check if this was a bool argument // if (!next || next.charAt(0) === '-' || (value = /^true|false$/.test(next))) { insert(argh, data[1], value ? argv.splice(index + 1, 1)[0] : true, option); } else { value = argv.splice(index + 1, 1)[0]; insert(argh, data[1], value, option); } } else { // // This argument is not prefixed. // if (!argh.argv) argh.argv = []; argh.argv.push(option); } return argh; }, Object.create(null)); }
[ "function", "parse", "(", "argv", ")", "{", "argv", "=", "argv", "||", "process", ".", "argv", ".", "slice", "(", "2", ")", ";", "return", "argv", ".", "reduce", "(", "function", "parser", "(", "argh", ",", "option", ",", "index", ",", "argv", ")", "{", "var", "next", "=", "argv", "[", "index", "+", "1", "]", ",", "value", ",", "data", ";", "if", "(", "option", "===", "'--'", ")", "{", "argh", ".", "argv", "=", "argh", ".", "argv", "||", "[", "]", ";", "argh", ".", "argv", "=", "argh", ".", "argv", ".", "concat", "(", "argv", ".", "splice", "(", "index", "+", "1", ")", ")", ";", "return", "argh", ";", "}", "if", "(", "data", "=", "/", "^--?(?:no|disable)-(.*)", "/", ".", "exec", "(", "option", ")", ")", "{", "insert", "(", "argh", ",", "data", "[", "1", "]", ",", "false", ",", "option", ")", ";", "}", "else", "if", "(", "data", "=", "/", "^-(?!-)(.*)", "/", ".", "exec", "(", "option", ")", ")", "{", "insert", "(", "argh", ",", "data", "[", "1", "]", ",", "true", ",", "option", ")", ";", "}", "else", "if", "(", "data", "=", "/", "^--([^=]+)=[\"']?([\\s!#$%&\\x28-\\x7e]+)[\"']?$", "/", ".", "exec", "(", "option", ")", ")", "{", "insert", "(", "argh", ",", "data", "[", "1", "]", ",", "data", "[", "2", "]", ",", "option", ")", ";", "}", "else", "if", "(", "data", "=", "/", "^--(.*)", "/", ".", "exec", "(", "option", ")", ")", "{", "if", "(", "!", "next", "||", "next", ".", "charAt", "(", "0", ")", "===", "'-'", "||", "(", "value", "=", "/", "^true|false$", "/", ".", "test", "(", "next", ")", ")", ")", "{", "insert", "(", "argh", ",", "data", "[", "1", "]", ",", "value", "?", "argv", ".", "splice", "(", "index", "+", "1", ",", "1", ")", "[", "0", "]", ":", "true", ",", "option", ")", ";", "}", "else", "{", "value", "=", "argv", ".", "splice", "(", "index", "+", "1", ",", "1", ")", "[", "0", "]", ";", "insert", "(", "argh", ",", "data", "[", "1", "]", ",", "value", ",", "option", ")", ";", "}", "}", "else", "{", "if", "(", "!", "argh", ".", "argv", ")", "argh", ".", "argv", "=", "[", "]", ";", "argh", ".", "argv", ".", "push", "(", "option", ")", ";", "}", "return", "argh", ";", "}", ",", "Object", ".", "create", "(", "null", ")", ")", ";", "}" ]
Argv is a extremely light weight options parser for Node.js it's been built for just one single purpose, parsing arguments. It does nothing more than that. @param {Array} argv The arguments that need to be parsed, defaults to process.argv @returns {Object} Parsed arguments. @api public
[ "Argv", "is", "a", "extremely", "light", "weight", "options", "parser", "for", "Node", ".", "js", "it", "s", "been", "built", "for", "just", "one", "single", "purpose", "parsing", "arguments", ".", "It", "does", "nothing", "more", "than", "that", "." ]
74ed701a7214ad581efe3303ea65cf71998308ac
https://github.com/observing/argh/blob/74ed701a7214ad581efe3303ea65cf71998308ac/index.js#L12-L78
train
observing/argh
index.js
insert
function insert(argh, key, value, option) { // // Automatic value conversion. This makes sure we store the correct "type" // if ('string' === typeof value && !isNaN(+value)) value = +value; if (value === 'true' || value === 'false') value = value === 'true'; var single = option.charAt(1) !== '-' , properties = key.split('.') , position = argh; if (single && key.length > 1) return key.split('').forEach(function short(char) { insert(argh, char, value, option); }); // // We don't have any deeply nested properties, so we should just bail out // early enough so we don't have to do any processing // if (!properties.length) return argh[key] = value; while (properties.length) { var property = properties.shift(); if (properties.length) { if ('object' !== typeof position[property] && !Array.isArray(position[property])) { position[property] = Object.create(null); } } else { position[property] = value; } position = position[property]; } }
javascript
function insert(argh, key, value, option) { // // Automatic value conversion. This makes sure we store the correct "type" // if ('string' === typeof value && !isNaN(+value)) value = +value; if (value === 'true' || value === 'false') value = value === 'true'; var single = option.charAt(1) !== '-' , properties = key.split('.') , position = argh; if (single && key.length > 1) return key.split('').forEach(function short(char) { insert(argh, char, value, option); }); // // We don't have any deeply nested properties, so we should just bail out // early enough so we don't have to do any processing // if (!properties.length) return argh[key] = value; while (properties.length) { var property = properties.shift(); if (properties.length) { if ('object' !== typeof position[property] && !Array.isArray(position[property])) { position[property] = Object.create(null); } } else { position[property] = value; } position = position[property]; } }
[ "function", "insert", "(", "argh", ",", "key", ",", "value", ",", "option", ")", "{", "if", "(", "'string'", "===", "typeof", "value", "&&", "!", "isNaN", "(", "+", "value", ")", ")", "value", "=", "+", "value", ";", "if", "(", "value", "===", "'true'", "||", "value", "===", "'false'", ")", "value", "=", "value", "===", "'true'", ";", "var", "single", "=", "option", ".", "charAt", "(", "1", ")", "!==", "'-'", ",", "properties", "=", "key", ".", "split", "(", "'.'", ")", ",", "position", "=", "argh", ";", "if", "(", "single", "&&", "key", ".", "length", ">", "1", ")", "return", "key", ".", "split", "(", "''", ")", ".", "forEach", "(", "function", "short", "(", "char", ")", "{", "insert", "(", "argh", ",", "char", ",", "value", ",", "option", ")", ";", "}", ")", ";", "if", "(", "!", "properties", ".", "length", ")", "return", "argh", "[", "key", "]", "=", "value", ";", "while", "(", "properties", ".", "length", ")", "{", "var", "property", "=", "properties", ".", "shift", "(", ")", ";", "if", "(", "properties", ".", "length", ")", "{", "if", "(", "'object'", "!==", "typeof", "position", "[", "property", "]", "&&", "!", "Array", ".", "isArray", "(", "position", "[", "property", "]", ")", ")", "{", "position", "[", "property", "]", "=", "Object", ".", "create", "(", "null", ")", ";", "}", "}", "else", "{", "position", "[", "property", "]", "=", "value", ";", "}", "position", "=", "position", "[", "property", "]", ";", "}", "}" ]
Inserts the value in the argh object @param {Object} argh The object where we store the values @param {String} key The received command line flag @param {String} value The command line flag's value @param {String} option The actual option @api private
[ "Inserts", "the", "value", "in", "the", "argh", "object" ]
74ed701a7214ad581efe3303ea65cf71998308ac
https://github.com/observing/argh/blob/74ed701a7214ad581efe3303ea65cf71998308ac/index.js#L89-L123
train
Clever-Labs/seo-checker
src/index.js
function(url, callback) { // Check if user input protocol if (url.indexOf('http://') < 0 && url.indexOf('https://') < 0) { // TODO: Turn this into its own function url = 'http://' + url; } // Make request and fire callback request.get(url.toLowerCase(), function(error, response, body) { if (!error && response.statusCode === 200) { return callback(body); } return callback(false); }); }
javascript
function(url, callback) { // Check if user input protocol if (url.indexOf('http://') < 0 && url.indexOf('https://') < 0) { // TODO: Turn this into its own function url = 'http://' + url; } // Make request and fire callback request.get(url.toLowerCase(), function(error, response, body) { if (!error && response.statusCode === 200) { return callback(body); } return callback(false); }); }
[ "function", "(", "url", ",", "callback", ")", "{", "if", "(", "url", ".", "indexOf", "(", "'http://'", ")", "<", "0", "&&", "url", ".", "indexOf", "(", "'https://'", ")", "<", "0", ")", "{", "url", "=", "'http://'", "+", "url", ";", "}", "request", ".", "get", "(", "url", ".", "toLowerCase", "(", ")", ",", "function", "(", "error", ",", "response", ",", "body", ")", "{", "if", "(", "!", "error", "&&", "response", ".", "statusCode", "===", "200", ")", "{", "return", "callback", "(", "body", ")", ";", "}", "return", "callback", "(", "false", ")", ";", "}", ")", ";", "}" ]
Load HTML for a single URL Use this to fetch the contents of a single URL then pass the result to the `meta` function or any other code that can parse or transform the response body of an HTTP request. `url` [String] - URL of page to read `callback` [Function] - Function to call on completion Returns the response body of an HTTP request as a string
[ "Load", "HTML", "for", "a", "single", "URL" ]
11501c9e4a90cd014dcded8961528e3948b8930e
https://github.com/Clever-Labs/seo-checker/blob/11501c9e4a90cd014dcded8961528e3948b8930e/src/index.js#L26-L40
train
Clever-Labs/seo-checker
src/index.js
function(body) { var $ = cheerio.load(body), page = {}; // Meta signals page.title = $('title').text() || null; page.description = $('meta[name=description]').attr('content') || null; page.author = $('meta[name=author]').attr('content') || null; page.keywords = $('meta[name=keywords]').attr('content') || null; // Heading signals var h1s = 0; $('h1').each(function() { h1s++; }); page.heading1 = $('body h1:first-child').text().trim().replace('\n', ''); page.totalHeadings = h1s; // Accessibility signals var totalImgs = 0, accessibleImgs = 0; $('img').each(function(index) { totalImgs++; if ($(this).attr('alt') || $(this).attr('title')) { accessibleImgs++; } }); page.imgAccessibility = (accessibleImgs / totalImgs) * 100; return page; }
javascript
function(body) { var $ = cheerio.load(body), page = {}; // Meta signals page.title = $('title').text() || null; page.description = $('meta[name=description]').attr('content') || null; page.author = $('meta[name=author]').attr('content') || null; page.keywords = $('meta[name=keywords]').attr('content') || null; // Heading signals var h1s = 0; $('h1').each(function() { h1s++; }); page.heading1 = $('body h1:first-child').text().trim().replace('\n', ''); page.totalHeadings = h1s; // Accessibility signals var totalImgs = 0, accessibleImgs = 0; $('img').each(function(index) { totalImgs++; if ($(this).attr('alt') || $(this).attr('title')) { accessibleImgs++; } }); page.imgAccessibility = (accessibleImgs / totalImgs) * 100; return page; }
[ "function", "(", "body", ")", "{", "var", "$", "=", "cheerio", ".", "load", "(", "body", ")", ",", "page", "=", "{", "}", ";", "page", ".", "title", "=", "$", "(", "'title'", ")", ".", "text", "(", ")", "||", "null", ";", "page", ".", "description", "=", "$", "(", "'meta[name=description]'", ")", ".", "attr", "(", "'content'", ")", "||", "null", ";", "page", ".", "author", "=", "$", "(", "'meta[name=author]'", ")", ".", "attr", "(", "'content'", ")", "||", "null", ";", "page", ".", "keywords", "=", "$", "(", "'meta[name=keywords]'", ")", ".", "attr", "(", "'content'", ")", "||", "null", ";", "var", "h1s", "=", "0", ";", "$", "(", "'h1'", ")", ".", "each", "(", "function", "(", ")", "{", "h1s", "++", ";", "}", ")", ";", "page", ".", "heading1", "=", "$", "(", "'body h1:first-child'", ")", ".", "text", "(", ")", ".", "trim", "(", ")", ".", "replace", "(", "'\\n'", ",", "\\n", ")", ";", "''", "page", ".", "totalHeadings", "=", "h1s", ";", "var", "totalImgs", "=", "0", ",", "accessibleImgs", "=", "0", ";", "$", "(", "'img'", ")", ".", "each", "(", "function", "(", "index", ")", "{", "totalImgs", "++", ";", "if", "(", "$", "(", "this", ")", ".", "attr", "(", "'alt'", ")", "||", "$", "(", "this", ")", ".", "attr", "(", "'title'", ")", ")", "{", "accessibleImgs", "++", ";", "}", "}", ")", ";", "page", ".", "imgAccessibility", "=", "(", "accessibleImgs", "/", "totalImgs", ")", "*", "100", ";", "}" ]
Parse meta data from an HTTP response body `body` [String] - The HTML of a web page to parse Returns an object containing data related to the SEO signals of the page that was parsed. Pass the result to another function to determine an "SEO score".
[ "Parse", "meta", "data", "from", "an", "HTTP", "response", "body" ]
11501c9e4a90cd014dcded8961528e3948b8930e
https://github.com/Clever-Labs/seo-checker/blob/11501c9e4a90cd014dcded8961528e3948b8930e/src/index.js#L51-L80
train
Clever-Labs/seo-checker
src/index.js
function(url, options, callback) { var crawler = Crawler.crawl(url.toLowerCase()), opts = options || {}, maxPages = opts.maxPages || 10, parsedPages = [], // Store parsed pages in this array seoParser = this.meta, // Reference to `meta` method to call during crawl crawlResults = []; // Store results in this array and then return it to caller // Crawler settings crawler.interval = opts.interval || 250; // Time between spooling up new requests crawler.maxDepth = opts.depth || 2; // Maximum deptch of crawl crawler.maxConcurrency = opts.concurrency || 2; // Number of processes to spawn at a time crawler.timeout = opts.timeout || 1000; // Milliseconds to wait for server to send headers crawler.downloadUnsupported = opts.unsupported || false; // Save resources by only downloading files Simple Crawler can parse // The user agent string to provide - Be cool and don't trick people crawler.userAgent = opts.useragent || 'SEO Checker v1 (https://github.com/Clever-Labs/seo-checker)'; // Only fetch HTML! You should always set this option unless you have a good reason not to if (opts.htmlOnly === true) { // Being explicit about truthy values here var htmlCondition = crawler.addFetchCondition(function(parsedURL) { return !parsedURL.path.match(/\.jpg|jpeg|png|gif|js|txt|css|pdf$/i); }); } crawler.on('fetchcomplete', function(queueItem, responseBuffer, response) { if (queueItem.stateData.code === 200) { crawlResults.push({ url: queueItem.url, body: responseBuffer.toString() }); } if (crawlResults.length >= maxPages) { this.stop(); // Stop the crawler crawlResults.forEach(function(page, index, results) { parsedPages.push({url: page.url, results: seoParser(page.body)}); }); if (!callback) { return parsedPages; } else { callback(parsedPages); } } }); }
javascript
function(url, options, callback) { var crawler = Crawler.crawl(url.toLowerCase()), opts = options || {}, maxPages = opts.maxPages || 10, parsedPages = [], // Store parsed pages in this array seoParser = this.meta, // Reference to `meta` method to call during crawl crawlResults = []; // Store results in this array and then return it to caller // Crawler settings crawler.interval = opts.interval || 250; // Time between spooling up new requests crawler.maxDepth = opts.depth || 2; // Maximum deptch of crawl crawler.maxConcurrency = opts.concurrency || 2; // Number of processes to spawn at a time crawler.timeout = opts.timeout || 1000; // Milliseconds to wait for server to send headers crawler.downloadUnsupported = opts.unsupported || false; // Save resources by only downloading files Simple Crawler can parse // The user agent string to provide - Be cool and don't trick people crawler.userAgent = opts.useragent || 'SEO Checker v1 (https://github.com/Clever-Labs/seo-checker)'; // Only fetch HTML! You should always set this option unless you have a good reason not to if (opts.htmlOnly === true) { // Being explicit about truthy values here var htmlCondition = crawler.addFetchCondition(function(parsedURL) { return !parsedURL.path.match(/\.jpg|jpeg|png|gif|js|txt|css|pdf$/i); }); } crawler.on('fetchcomplete', function(queueItem, responseBuffer, response) { if (queueItem.stateData.code === 200) { crawlResults.push({ url: queueItem.url, body: responseBuffer.toString() }); } if (crawlResults.length >= maxPages) { this.stop(); // Stop the crawler crawlResults.forEach(function(page, index, results) { parsedPages.push({url: page.url, results: seoParser(page.body)}); }); if (!callback) { return parsedPages; } else { callback(parsedPages); } } }); }
[ "function", "(", "url", ",", "options", ",", "callback", ")", "{", "var", "crawler", "=", "Crawler", ".", "crawl", "(", "url", ".", "toLowerCase", "(", ")", ")", ",", "opts", "=", "options", "||", "{", "}", ",", "maxPages", "=", "opts", ".", "maxPages", "||", "10", ",", "parsedPages", "=", "[", "]", ",", "seoParser", "=", "this", ".", "meta", ",", "crawlResults", "=", "[", "]", ";", "crawler", ".", "interval", "=", "opts", ".", "interval", "||", "250", ";", "crawler", ".", "maxDepth", "=", "opts", ".", "depth", "||", "2", ";", "crawler", ".", "maxConcurrency", "=", "opts", ".", "concurrency", "||", "2", ";", "crawler", ".", "timeout", "=", "opts", ".", "timeout", "||", "1000", ";", "crawler", ".", "downloadUnsupported", "=", "opts", ".", "unsupported", "||", "false", ";", "crawler", ".", "userAgent", "=", "opts", ".", "useragent", "||", "'SEO Checker v1 (https://github.com/Clever-Labs/seo-checker)'", ";", "if", "(", "opts", ".", "htmlOnly", "===", "true", ")", "{", "var", "htmlCondition", "=", "crawler", ".", "addFetchCondition", "(", "function", "(", "parsedURL", ")", "{", "return", "!", "parsedURL", ".", "path", ".", "match", "(", "/", "\\.jpg|jpeg|png|gif|js|txt|css|pdf$", "/", "i", ")", ";", "}", ")", ";", "}", "crawler", ".", "on", "(", "'fetchcomplete'", ",", "function", "(", "queueItem", ",", "responseBuffer", ",", "response", ")", "{", "if", "(", "queueItem", ".", "stateData", ".", "code", "===", "200", ")", "{", "crawlResults", ".", "push", "(", "{", "url", ":", "queueItem", ".", "url", ",", "body", ":", "responseBuffer", ".", "toString", "(", ")", "}", ")", ";", "}", "if", "(", "crawlResults", ".", "length", ">=", "maxPages", ")", "{", "this", ".", "stop", "(", ")", ";", "crawlResults", ".", "forEach", "(", "function", "(", "page", ",", "index", ",", "results", ")", "{", "parsedPages", ".", "push", "(", "{", "url", ":", "page", ".", "url", ",", "results", ":", "seoParser", "(", "page", ".", "body", ")", "}", ")", ";", "}", ")", ";", "if", "(", "!", "callback", ")", "{", "return", "parsedPages", ";", "}", "else", "{", "callback", "(", "parsedPages", ")", ";", "}", "}", "}", ")", ";", "}" ]
Generate SEO data for multiple pages of a site at once `url` [String] - The URL to begin the crawl `options` [Object] - Options to pass to the crawler. Uses a subset of the `simplecrawler` lib's options: - `maxPages` [Number] - The max number of pages to crawl (defaults to 10) - `interval` [Number] - Delay between each request for a new page - `maxDepth` [Number] - Depth of crawl. See simplecrawler docs for an explanation - `maxConcurrency` [Number] - Number of processes to spawn at a time - `timeout` [Number] - Time to wait for a server response before moving on - `downloadUnsupported` [Boolean] - Determines whether crawler downloads files it cannot parse - `userAgent` [String] - The UA string to send with requests - `htmlOnly` [Boolean] - Tells crawler not to crawl any non-HTML text/html pages. This is a required option and has no default Returns an array of objects containing SEO data and URL. Example return value: [{ url: 'http://example.com/page1.html', results: { <results object identical to signature of this.meta()'s return value> } }]
[ "Generate", "SEO", "data", "for", "multiple", "pages", "of", "a", "site", "at", "once" ]
11501c9e4a90cd014dcded8961528e3948b8930e
https://github.com/Clever-Labs/seo-checker/blob/11501c9e4a90cd014dcded8961528e3948b8930e/src/index.js#L103-L143
train
TourCMS/node-tourcms
node-tourcms.js
apiResponded
function apiResponded(apiResponse) { // Convert XML to JS object var parser = new xml2js.Parser({explicitArray:false}); parser.parseString(apiResponse, function (err, result) { // If the method processes the response, give it back // Otherwise call the original callback if(typeof a.processor !== 'undefined') a.processor(result.response, a.callback); else a.callback(result.response); }); }
javascript
function apiResponded(apiResponse) { // Convert XML to JS object var parser = new xml2js.Parser({explicitArray:false}); parser.parseString(apiResponse, function (err, result) { // If the method processes the response, give it back // Otherwise call the original callback if(typeof a.processor !== 'undefined') a.processor(result.response, a.callback); else a.callback(result.response); }); }
[ "function", "apiResponded", "(", "apiResponse", ")", "{", "var", "parser", "=", "new", "xml2js", ".", "Parser", "(", "{", "explicitArray", ":", "false", "}", ")", ";", "parser", ".", "parseString", "(", "apiResponse", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "typeof", "a", ".", "processor", "!==", "'undefined'", ")", "a", ".", "processor", "(", "result", ".", "response", ",", "a", ".", "callback", ")", ";", "else", "a", ".", "callback", "(", "result", ".", "response", ")", ";", "}", ")", ";", "}" ]
Process API response
[ "Process", "API", "response" ]
1d23ff7ba4ed6fcda5e84f2018d27129efec4978
https://github.com/TourCMS/node-tourcms/blob/1d23ff7ba4ed6fcda5e84f2018d27129efec4978/node-tourcms.js#L87-L101
train
Bitcoin-com/wormhole-sdk
examples/data-retrieval/token-info-from-tx/token-info-from-tx.js
getTxInfo
async function getTxInfo() { const retVal = await Wormhole.DataRetrieval.transaction(TXID) console.log(`Info from TXID ${TXID}: ${JSON.stringify(retVal, null, 2)}`) }
javascript
async function getTxInfo() { const retVal = await Wormhole.DataRetrieval.transaction(TXID) console.log(`Info from TXID ${TXID}: ${JSON.stringify(retVal, null, 2)}`) }
[ "async", "function", "getTxInfo", "(", ")", "{", "const", "retVal", "=", "await", "Wormhole", ".", "DataRetrieval", ".", "transaction", "(", "TXID", ")", "console", ".", "log", "(", "`", "${", "TXID", "}", "${", "JSON", ".", "stringify", "(", "retVal", ",", "null", ",", "2", ")", "}", "`", ")", "}" ]
Get Token info from the TX.
[ "Get", "Token", "info", "from", "the", "TX", "." ]
13dd35295b0b3a6bb84e895f96c978cbb906193b
https://github.com/Bitcoin-com/wormhole-sdk/blob/13dd35295b0b3a6bb84e895f96c978cbb906193b/examples/data-retrieval/token-info-from-tx/token-info-from-tx.js#L20-L24
train
qixotic/s3-to-logstore
index.js
function(data, prefix) { prefix = prefix || ''; var row = Object.keys(data).map(function(key) { if (typeof data[key] !== 'object') { return util.format('%s%s="%s"', prefix, key, data[key]); } // Flatten this nested object. return _reformat(data[key], key + '.'); }); return row.join(' '); }
javascript
function(data, prefix) { prefix = prefix || ''; var row = Object.keys(data).map(function(key) { if (typeof data[key] !== 'object') { return util.format('%s%s="%s"', prefix, key, data[key]); } // Flatten this nested object. return _reformat(data[key], key + '.'); }); return row.join(' '); }
[ "function", "(", "data", ",", "prefix", ")", "{", "prefix", "=", "prefix", "||", "''", ";", "var", "row", "=", "Object", ".", "keys", "(", "data", ")", ".", "map", "(", "function", "(", "key", ")", "{", "if", "(", "typeof", "data", "[", "key", "]", "!==", "'object'", ")", "{", "return", "util", ".", "format", "(", "'%s%s=\"%s\"'", ",", "prefix", ",", "key", ",", "data", "[", "key", "]", ")", ";", "}", "return", "_reformat", "(", "data", "[", "key", "]", ",", "key", "+", "'.'", ")", ";", "}", ")", ";", "return", "row", ".", "join", "(", "' '", ")", ";", "}" ]
data - json object representation of a log line. prefix - string to prefix a key with. Used in flattening nested objects. Returns a single string of concatenated key=value pairs.
[ "data", "-", "json", "object", "representation", "of", "a", "log", "line", ".", "prefix", "-", "string", "to", "prefix", "a", "key", "with", ".", "Used", "in", "flattening", "nested", "objects", ".", "Returns", "a", "single", "string", "of", "concatenated", "key", "=", "value", "pairs", "." ]
5b29d237f2d9bd3f996f281488f62ccfe3f1888b
https://github.com/qixotic/s3-to-logstore/blob/5b29d237f2d9bd3f996f281488f62ccfe3f1888b/index.js#L13-L23
train
frank198/pomelo-upgrade
template/web-server/public/js/lib/socket.io.js
Socket
function Socket (options) { this.options = { port: 80 , secure: false , document: 'document' in global ? document : false , resource: 'socket.io' , transports: io.transports , 'connect timeout': 10000 , 'try multiple transports': true , 'reconnect': true , 'reconnection delay': 500 , 'reconnection limit': Infinity , 'reopen delay': 3000 , 'max reconnection attempts': 10 , 'sync disconnect on unload': true , 'auto connect': true , 'flash policy port': 10843 }; io.util.merge(this.options, options); this.connected = false; this.open = false; this.connecting = false; this.reconnecting = false; this.namespaces = {}; this.buffer = []; this.doBuffer = false; if (this.options['sync disconnect on unload'] && (!this.isXDomain() || io.util.ua.hasCORS)) { var self = this; io.util.on(global, 'unload', function () { self.disconnectSync(); }, false); } if (this.options['auto connect']) { this.connect(); } }
javascript
function Socket (options) { this.options = { port: 80 , secure: false , document: 'document' in global ? document : false , resource: 'socket.io' , transports: io.transports , 'connect timeout': 10000 , 'try multiple transports': true , 'reconnect': true , 'reconnection delay': 500 , 'reconnection limit': Infinity , 'reopen delay': 3000 , 'max reconnection attempts': 10 , 'sync disconnect on unload': true , 'auto connect': true , 'flash policy port': 10843 }; io.util.merge(this.options, options); this.connected = false; this.open = false; this.connecting = false; this.reconnecting = false; this.namespaces = {}; this.buffer = []; this.doBuffer = false; if (this.options['sync disconnect on unload'] && (!this.isXDomain() || io.util.ua.hasCORS)) { var self = this; io.util.on(global, 'unload', function () { self.disconnectSync(); }, false); } if (this.options['auto connect']) { this.connect(); } }
[ "function", "Socket", "(", "options", ")", "{", "this", ".", "options", "=", "{", "port", ":", "80", ",", "secure", ":", "false", ",", "document", ":", "'document'", "in", "global", "?", "document", ":", "false", ",", "resource", ":", "'socket.io'", ",", "transports", ":", "io", ".", "transports", ",", "'connect timeout'", ":", "10000", ",", "'try multiple transports'", ":", "true", ",", "'reconnect'", ":", "true", ",", "'reconnection delay'", ":", "500", ",", "'reconnection limit'", ":", "Infinity", ",", "'reopen delay'", ":", "3000", ",", "'max reconnection attempts'", ":", "10", ",", "'sync disconnect on unload'", ":", "true", ",", "'auto connect'", ":", "true", ",", "'flash policy port'", ":", "10843", "}", ";", "io", ".", "util", ".", "merge", "(", "this", ".", "options", ",", "options", ")", ";", "this", ".", "connected", "=", "false", ";", "this", ".", "open", "=", "false", ";", "this", ".", "connecting", "=", "false", ";", "this", ".", "reconnecting", "=", "false", ";", "this", ".", "namespaces", "=", "{", "}", ";", "this", ".", "buffer", "=", "[", "]", ";", "this", ".", "doBuffer", "=", "false", ";", "if", "(", "this", ".", "options", "[", "'sync disconnect on unload'", "]", "&&", "(", "!", "this", ".", "isXDomain", "(", ")", "||", "io", ".", "util", ".", "ua", ".", "hasCORS", ")", ")", "{", "var", "self", "=", "this", ";", "io", ".", "util", ".", "on", "(", "global", ",", "'unload'", ",", "function", "(", ")", "{", "self", ".", "disconnectSync", "(", ")", ";", "}", ",", "false", ")", ";", "}", "if", "(", "this", ".", "options", "[", "'auto connect'", "]", ")", "{", "this", ".", "connect", "(", ")", ";", "}", "}" ]
Create a new `Socket.IO client` which can establish a persistent connection with a Socket.IO enabled server. @api public
[ "Create", "a", "new", "Socket", ".", "IO", "client", "which", "can", "establish", "a", "persistent", "connection", "with", "a", "Socket", ".", "IO", "enabled", "server", "." ]
6d56e02d0e61b3ffd05bd69a2337ec3a4ed9b0e5
https://github.com/frank198/pomelo-upgrade/blob/6d56e02d0e61b3ffd05bd69a2337ec3a4ed9b0e5/template/web-server/public/js/lib/socket.io.js#L1491-L1532
train
Urigo/meteor-native-packages
packages/ddp-client/stub_stream.js
function (name, callback) { var self = this; if (!self.callbacks[name]) self.callbacks[name] = [callback]; else self.callbacks[name].push(callback); }
javascript
function (name, callback) { var self = this; if (!self.callbacks[name]) self.callbacks[name] = [callback]; else self.callbacks[name].push(callback); }
[ "function", "(", "name", ",", "callback", ")", "{", "var", "self", "=", "this", ";", "if", "(", "!", "self", ".", "callbacks", "[", "name", "]", ")", "self", ".", "callbacks", "[", "name", "]", "=", "[", "callback", "]", ";", "else", "self", ".", "callbacks", "[", "name", "]", ".", "push", "(", "callback", ")", ";", "}" ]
Methods from Stream
[ "Methods", "from", "Stream" ]
8eb7fdd554aad0ff78a0dc19b9c62016d2b2e7a7
https://github.com/Urigo/meteor-native-packages/blob/8eb7fdd554aad0ff78a0dc19b9c62016d2b2e7a7/packages/ddp-client/stub_stream.js#L11-L18
train
Urigo/meteor-native-packages
packages/ddp-client/stub_stream.js
function (data) { var self = this; if (typeof data === 'object') { data = EJSON.stringify(data); } _.each(self.callbacks['message'], function (cb) { cb(data); }); }
javascript
function (data) { var self = this; if (typeof data === 'object') { data = EJSON.stringify(data); } _.each(self.callbacks['message'], function (cb) { cb(data); }); }
[ "function", "(", "data", ")", "{", "var", "self", "=", "this", ";", "if", "(", "typeof", "data", "===", "'object'", ")", "{", "data", "=", "EJSON", ".", "stringify", "(", "data", ")", ";", "}", "_", ".", "each", "(", "self", ".", "callbacks", "[", "'message'", "]", ",", "function", "(", "cb", ")", "{", "cb", "(", "data", ")", ";", "}", ")", ";", "}" ]
Methods for tests
[ "Methods", "for", "tests" ]
8eb7fdd554aad0ff78a0dc19b9c62016d2b2e7a7
https://github.com/Urigo/meteor-native-packages/blob/8eb7fdd554aad0ff78a0dc19b9c62016d2b2e7a7/packages/ddp-client/stub_stream.js#L38-L48
train
Collaborne/gulp-polymer-build-utils
integrated-build.js
build
function build(config) { return lazypipe() .pipe(() => polymerBuild(config)) .pipe(() => addCspCompliance()) .pipe(() => addCacheBusting()) .pipe(() => optimizeAssets()) .pipe(() => injectCustomElementsEs5Adapter()); }
javascript
function build(config) { return lazypipe() .pipe(() => polymerBuild(config)) .pipe(() => addCspCompliance()) .pipe(() => addCacheBusting()) .pipe(() => optimizeAssets()) .pipe(() => injectCustomElementsEs5Adapter()); }
[ "function", "build", "(", "config", ")", "{", "return", "lazypipe", "(", ")", ".", "pipe", "(", "(", ")", "=>", "polymerBuild", "(", "config", ")", ")", ".", "pipe", "(", "(", ")", "=>", "addCspCompliance", "(", ")", ")", ".", "pipe", "(", "(", ")", "=>", "addCacheBusting", "(", ")", ")", ".", "pipe", "(", "(", ")", "=>", "optimizeAssets", "(", ")", ")", ".", "pipe", "(", "(", ")", "=>", "injectCustomElementsEs5Adapter", "(", ")", ")", ";", "}" ]
Best practice build pipeline. This only only chains up the various build steps. @param {Object} config Content of polymer.json @return
[ "Best", "practice", "build", "pipeline", ".", "This", "only", "only", "chains", "up", "the", "various", "build", "steps", "." ]
76f83ea018f726a9e4390444deef65dbe9dde1ff
https://github.com/Collaborne/gulp-polymer-build-utils/blob/76f83ea018f726a9e4390444deef65dbe9dde1ff/integrated-build.js#L16-L23
train