id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
39,600
salesforce/refocus-collector-eval
src/RefocusCollectorEval.js
acceptMatcher
function acceptMatcher(acc, actual) { /* Exact match or full wildcard match on both type and subtype */ if (actual.contentType === acc.item || acc.item === '*/*') return true; /* Otherwise check for "*" wildcard matches */ const a = acc.item.split(MIME_SUBTYPE_SEPARATOR); const accepted = { type: a[0], subtype: a[1], }; /* Exact match type, wildcard subtype */ if (actual.type === accepted.type && accepted.subtype === '*') { return true; } /* Wildcard type, exact match subtype */ if (accepted.type === '*' && accepted.subtype === actual.subtype) { return true; } }
javascript
function acceptMatcher(acc, actual) { /* Exact match or full wildcard match on both type and subtype */ if (actual.contentType === acc.item || acc.item === '*/*') return true; /* Otherwise check for "*" wildcard matches */ const a = acc.item.split(MIME_SUBTYPE_SEPARATOR); const accepted = { type: a[0], subtype: a[1], }; /* Exact match type, wildcard subtype */ if (actual.type === accepted.type && accepted.subtype === '*') { return true; } /* Wildcard type, exact match subtype */ if (accepted.type === '*' && accepted.subtype === actual.subtype) { return true; } }
[ "function", "acceptMatcher", "(", "acc", ",", "actual", ")", "{", "/* Exact match or full wildcard match on both type and subtype */", "if", "(", "actual", ".", "contentType", "===", "acc", ".", "item", "||", "acc", ".", "item", "===", "'*/*'", ")", "return", "true", ";", "/* Otherwise check for \"*\" wildcard matches */", "const", "a", "=", "acc", ".", "item", ".", "split", "(", "MIME_SUBTYPE_SEPARATOR", ")", ";", "const", "accepted", "=", "{", "type", ":", "a", "[", "0", "]", ",", "subtype", ":", "a", "[", "1", "]", ",", "}", ";", "/* Exact match type, wildcard subtype */", "if", "(", "actual", ".", "type", "===", "accepted", ".", "type", "&&", "accepted", ".", "subtype", "===", "'*'", ")", "{", "return", "true", ";", "}", "/* Wildcard type, exact match subtype */", "if", "(", "accepted", ".", "type", "===", "'*'", "&&", "accepted", ".", "subtype", "===", "actual", ".", "subtype", ")", "{", "return", "true", ";", "}", "}" ]
Checks whether the actual content type matches this particular accepted type. @param {Object} acc - one of the array elements returned by parsing the Accept headers using "accept-parser" @param {Object} actual - An object representing the actual content type received, with attributes ["contentType", "type", "subtype"] @returns {Boolean} true if the actual content type matches this particular "Accept" entry, either an exact match or a wildcard match
[ "Checks", "whether", "the", "actual", "content", "type", "matches", "this", "particular", "accepted", "type", "." ]
9d657a7e1627775ef44e84d532f9d50bb52d24e1
https://github.com/salesforce/refocus-collector-eval/blob/9d657a7e1627775ef44e84d532f9d50bb52d24e1/src/RefocusCollectorEval.js#L39-L59
39,601
crcn/bindable.js
lib/object/index.js
function (property) { var isString; // optimal if ((isString = (typeof property === "string")) && !~property.indexOf(".")) { return this[property]; } // avoid split if possible var chain = isString ? property.split(".") : property, currentValue = this, currentProperty; // go through all the properties for (var i = 0, n = chain.length - 1; i < n; i++) { currentValue = currentValue[chain[i]]; if (!currentValue) return; } // might be a bindable object if(currentValue) return currentValue[chain[i]]; }
javascript
function (property) { var isString; // optimal if ((isString = (typeof property === "string")) && !~property.indexOf(".")) { return this[property]; } // avoid split if possible var chain = isString ? property.split(".") : property, currentValue = this, currentProperty; // go through all the properties for (var i = 0, n = chain.length - 1; i < n; i++) { currentValue = currentValue[chain[i]]; if (!currentValue) return; } // might be a bindable object if(currentValue) return currentValue[chain[i]]; }
[ "function", "(", "property", ")", "{", "var", "isString", ";", "// optimal", "if", "(", "(", "isString", "=", "(", "typeof", "property", "===", "\"string\"", ")", ")", "&&", "!", "~", "property", ".", "indexOf", "(", "\".\"", ")", ")", "{", "return", "this", "[", "property", "]", ";", "}", "// avoid split if possible", "var", "chain", "=", "isString", "?", "property", ".", "split", "(", "\".\"", ")", ":", "property", ",", "currentValue", "=", "this", ",", "currentProperty", ";", "// go through all the properties", "for", "(", "var", "i", "=", "0", ",", "n", "=", "chain", ".", "length", "-", "1", ";", "i", "<", "n", ";", "i", "++", ")", "{", "currentValue", "=", "currentValue", "[", "chain", "[", "i", "]", "]", ";", "if", "(", "!", "currentValue", ")", "return", ";", "}", "// might be a bindable object", "if", "(", "currentValue", ")", "return", "currentValue", "[", "chain", "[", "i", "]", "]", ";", "}" ]
Returns a property stored in the bindable object context @method get @param {String} path path to the value. Can be something like `person.city.name`.
[ "Returns", "a", "property", "stored", "in", "the", "bindable", "object", "context" ]
562dcd4a0e208e2a11ac7613654b32b01c7d92ac
https://github.com/crcn/bindable.js/blob/562dcd4a0e208e2a11ac7613654b32b01c7d92ac/lib/object/index.js#L130-L154
39,602
crcn/bindable.js
lib/object/index.js
function (property, value) { var isString, hasChanged, oldValue, chain; // optimal if ((isString = (typeof property === "string")) && !~property.indexOf(".")) { hasChanged = (oldValue = this[property]) !== value; if (hasChanged) this[property] = value; } else { // avoid split if possible chain = isString ? property.split(".") : property; var currentValue = this, previousValue, currentProperty, newChain; for (var i = 0, n = chain.length - 1; i < n; i++) { currentProperty = chain[i]; previousValue = currentValue; currentValue = currentValue[currentProperty]; // need to take into account functions - easier not to check // if value exists if (!currentValue /* || (typeof currentValue !== "object")*/) { currentValue = previousValue[currentProperty] = {}; } // is the previous value bindable? pass it on if (currentValue.__isBindable) { newChain = chain.slice(i + 1); // check if the value has changed hasChanged = (oldValue = currentValue.get(newChain)) !== value; currentValue.set(newChain, value); currentValue = oldValue; break; } } if (!newChain && (hasChanged = (currentValue !== value))) { currentProperty = chain[i]; oldValue = currentValue[currentProperty]; currentValue[currentProperty] = value; } } if (!hasChanged) return value; var prop = chain ? chain.join(".") : property; this.emit("change:" + prop, value, oldValue); this.emit("change", prop, value, oldValue); return value; }
javascript
function (property, value) { var isString, hasChanged, oldValue, chain; // optimal if ((isString = (typeof property === "string")) && !~property.indexOf(".")) { hasChanged = (oldValue = this[property]) !== value; if (hasChanged) this[property] = value; } else { // avoid split if possible chain = isString ? property.split(".") : property; var currentValue = this, previousValue, currentProperty, newChain; for (var i = 0, n = chain.length - 1; i < n; i++) { currentProperty = chain[i]; previousValue = currentValue; currentValue = currentValue[currentProperty]; // need to take into account functions - easier not to check // if value exists if (!currentValue /* || (typeof currentValue !== "object")*/) { currentValue = previousValue[currentProperty] = {}; } // is the previous value bindable? pass it on if (currentValue.__isBindable) { newChain = chain.slice(i + 1); // check if the value has changed hasChanged = (oldValue = currentValue.get(newChain)) !== value; currentValue.set(newChain, value); currentValue = oldValue; break; } } if (!newChain && (hasChanged = (currentValue !== value))) { currentProperty = chain[i]; oldValue = currentValue[currentProperty]; currentValue[currentProperty] = value; } } if (!hasChanged) return value; var prop = chain ? chain.join(".") : property; this.emit("change:" + prop, value, oldValue); this.emit("change", prop, value, oldValue); return value; }
[ "function", "(", "property", ",", "value", ")", "{", "var", "isString", ",", "hasChanged", ",", "oldValue", ",", "chain", ";", "// optimal", "if", "(", "(", "isString", "=", "(", "typeof", "property", "===", "\"string\"", ")", ")", "&&", "!", "~", "property", ".", "indexOf", "(", "\".\"", ")", ")", "{", "hasChanged", "=", "(", "oldValue", "=", "this", "[", "property", "]", ")", "!==", "value", ";", "if", "(", "hasChanged", ")", "this", "[", "property", "]", "=", "value", ";", "}", "else", "{", "// avoid split if possible", "chain", "=", "isString", "?", "property", ".", "split", "(", "\".\"", ")", ":", "property", ";", "var", "currentValue", "=", "this", ",", "previousValue", ",", "currentProperty", ",", "newChain", ";", "for", "(", "var", "i", "=", "0", ",", "n", "=", "chain", ".", "length", "-", "1", ";", "i", "<", "n", ";", "i", "++", ")", "{", "currentProperty", "=", "chain", "[", "i", "]", ";", "previousValue", "=", "currentValue", ";", "currentValue", "=", "currentValue", "[", "currentProperty", "]", ";", "// need to take into account functions - easier not to check", "// if value exists", "if", "(", "!", "currentValue", "/* || (typeof currentValue !== \"object\")*/", ")", "{", "currentValue", "=", "previousValue", "[", "currentProperty", "]", "=", "{", "}", ";", "}", "// is the previous value bindable? pass it on", "if", "(", "currentValue", ".", "__isBindable", ")", "{", "newChain", "=", "chain", ".", "slice", "(", "i", "+", "1", ")", ";", "// check if the value has changed", "hasChanged", "=", "(", "oldValue", "=", "currentValue", ".", "get", "(", "newChain", ")", ")", "!==", "value", ";", "currentValue", ".", "set", "(", "newChain", ",", "value", ")", ";", "currentValue", "=", "oldValue", ";", "break", ";", "}", "}", "if", "(", "!", "newChain", "&&", "(", "hasChanged", "=", "(", "currentValue", "!==", "value", ")", ")", ")", "{", "currentProperty", "=", "chain", "[", "i", "]", ";", "oldValue", "=", "currentValue", "[", "currentProperty", "]", ";", "currentValue", "[", "currentProperty", "]", "=", "value", ";", "}", "}", "if", "(", "!", "hasChanged", ")", "return", "value", ";", "var", "prop", "=", "chain", "?", "chain", ".", "join", "(", "\".\"", ")", ":", "property", ";", "this", ".", "emit", "(", "\"change:\"", "+", "prop", ",", "value", ",", "oldValue", ")", ";", "this", ".", "emit", "(", "\"change\"", ",", "prop", ",", "value", ",", "oldValue", ")", ";", "return", "value", ";", "}" ]
Sets a property on the bindable object's context @method set @param {String} path path to the value. Can be something like `person.city.name`.
[ "Sets", "a", "property", "on", "the", "bindable", "object", "s", "context" ]
562dcd4a0e208e2a11ac7613654b32b01c7d92ac
https://github.com/crcn/bindable.js/blob/562dcd4a0e208e2a11ac7613654b32b01c7d92ac/lib/object/index.js#L176-L235
39,603
crcn/bindable.js
lib/object/index.js
function () { var obj = {}, value; var keys = Object.keys(this); for (var i = 0, n = keys.length; i < n; i++) { var key = keys[i]; if (key.substr(0, 2) === "__") continue; value = this[key]; if(value && value.__isBindable) { value = value.toJSON(); } obj[key] = value; } return obj; }
javascript
function () { var obj = {}, value; var keys = Object.keys(this); for (var i = 0, n = keys.length; i < n; i++) { var key = keys[i]; if (key.substr(0, 2) === "__") continue; value = this[key]; if(value && value.__isBindable) { value = value.toJSON(); } obj[key] = value; } return obj; }
[ "function", "(", ")", "{", "var", "obj", "=", "{", "}", ",", "value", ";", "var", "keys", "=", "Object", ".", "keys", "(", "this", ")", ";", "for", "(", "var", "i", "=", "0", ",", "n", "=", "keys", ".", "length", ";", "i", "<", "n", ";", "i", "++", ")", "{", "var", "key", "=", "keys", "[", "i", "]", ";", "if", "(", "key", ".", "substr", "(", "0", ",", "2", ")", "===", "\"__\"", ")", "continue", ";", "value", "=", "this", "[", "key", "]", ";", "if", "(", "value", "&&", "value", ".", "__isBindable", ")", "{", "value", "=", "value", ".", "toJSON", "(", ")", ";", "}", "obj", "[", "key", "]", "=", "value", ";", "}", "return", "obj", ";", "}" ]
Converts the context to a JSON object @method toJSON
[ "Converts", "the", "context", "to", "a", "JSON", "object" ]
562dcd4a0e208e2a11ac7613654b32b01c7d92ac
https://github.com/crcn/bindable.js/blob/562dcd4a0e208e2a11ac7613654b32b01c7d92ac/lib/object/index.js#L264-L282
39,604
ofzza/enTT
dist/entt.js
cast
function cast(data, EntityClass) { // Check if/how EntityClass is defined or implied if (!EntityClass && !_lodash2.default.isArray(data)) { // No explicit class definition, casting data not array return _dataManagement2.default.cast(data, this); } else if (!EntityClass && _lodash2.default.isArray(data)) { // No explicit class definition, casting data is array return _dataManagement2.default.cast(data, [this]); } else if (_lodash2.default.isArray(EntityClass) && EntityClass.length === 0) { // Explicit class definition as array with implicit members return _dataManagement2.default.cast(data, [this]); } else if (_lodash2.default.isObject(EntityClass) && !_lodash2.default.isFunction(EntityClass) && _lodash2.default.values(EntityClass).length === 0) { // Explicit class definition as hashmap with implicit members return _dataManagement2.default.cast(data, _defineProperty({}, this.name, this)); } else { // Explicit class definition return _dataManagement2.default.cast(data, EntityClass); } }
javascript
function cast(data, EntityClass) { // Check if/how EntityClass is defined or implied if (!EntityClass && !_lodash2.default.isArray(data)) { // No explicit class definition, casting data not array return _dataManagement2.default.cast(data, this); } else if (!EntityClass && _lodash2.default.isArray(data)) { // No explicit class definition, casting data is array return _dataManagement2.default.cast(data, [this]); } else if (_lodash2.default.isArray(EntityClass) && EntityClass.length === 0) { // Explicit class definition as array with implicit members return _dataManagement2.default.cast(data, [this]); } else if (_lodash2.default.isObject(EntityClass) && !_lodash2.default.isFunction(EntityClass) && _lodash2.default.values(EntityClass).length === 0) { // Explicit class definition as hashmap with implicit members return _dataManagement2.default.cast(data, _defineProperty({}, this.name, this)); } else { // Explicit class definition return _dataManagement2.default.cast(data, EntityClass); } }
[ "function", "cast", "(", "data", ",", "EntityClass", ")", "{", "// Check if/how EntityClass is defined or implied", "if", "(", "!", "EntityClass", "&&", "!", "_lodash2", ".", "default", ".", "isArray", "(", "data", ")", ")", "{", "// No explicit class definition, casting data not array", "return", "_dataManagement2", ".", "default", ".", "cast", "(", "data", ",", "this", ")", ";", "}", "else", "if", "(", "!", "EntityClass", "&&", "_lodash2", ".", "default", ".", "isArray", "(", "data", ")", ")", "{", "// No explicit class definition, casting data is array", "return", "_dataManagement2", ".", "default", ".", "cast", "(", "data", ",", "[", "this", "]", ")", ";", "}", "else", "if", "(", "_lodash2", ".", "default", ".", "isArray", "(", "EntityClass", ")", "&&", "EntityClass", ".", "length", "===", "0", ")", "{", "// Explicit class definition as array with implicit members", "return", "_dataManagement2", ".", "default", ".", "cast", "(", "data", ",", "[", "this", "]", ")", ";", "}", "else", "if", "(", "_lodash2", ".", "default", ".", "isObject", "(", "EntityClass", ")", "&&", "!", "_lodash2", ".", "default", ".", "isFunction", "(", "EntityClass", ")", "&&", "_lodash2", ".", "default", ".", "values", "(", "EntityClass", ")", ".", "length", "===", "0", ")", "{", "// Explicit class definition as hashmap with implicit members", "return", "_dataManagement2", ".", "default", ".", "cast", "(", "data", ",", "_defineProperty", "(", "{", "}", ",", "this", ".", "name", ",", "this", ")", ")", ";", "}", "else", "{", "// Explicit class definition", "return", "_dataManagement2", ".", "default", ".", "cast", "(", "data", ",", "EntityClass", ")", ";", "}", "}" ]
Casts provided data as a EnTT instance of given type @export @param {any} data Data to cast @param {any} EntityClass Extended EnTT class to cast as - if not provided, will cast to EnTT class this static method is being called from - if empty array provided, will cast to array of instances of EnTT class this static method is being called from - if empty hashmap provided, will cast to array of instances of EnTT class this static method is being called from @returns {any} Instance of required EnTT class with provided data cast into it
[ "Casts", "provided", "data", "as", "a", "EnTT", "instance", "of", "given", "type" ]
fdf27de4142b3c65a3e51dee70e0d7625dff897c
https://github.com/ofzza/enTT/blob/fdf27de4142b3c65a3e51dee70e0d7625dff897c/dist/entt.js#L74-L92
39,605
ofzza/enTT
dist/entt.js
getClassExtensions
function getClassExtensions(classes) { // Extract property definitions from all inherited classes' static ".props" property var extensions = _lodash2.default.reduceRight(classes, function (extensions, current) { var extensionsArray = current.includes ? _lodash2.default.isArray(current.includes) ? current.includes : [current.includes] : []; _lodash2.default.forEach(extensionsArray, function (extension) { extensions.push(extension); }); return extensions; }, []); // Return extracted properties return extensions; }
javascript
function getClassExtensions(classes) { // Extract property definitions from all inherited classes' static ".props" property var extensions = _lodash2.default.reduceRight(classes, function (extensions, current) { var extensionsArray = current.includes ? _lodash2.default.isArray(current.includes) ? current.includes : [current.includes] : []; _lodash2.default.forEach(extensionsArray, function (extension) { extensions.push(extension); }); return extensions; }, []); // Return extracted properties return extensions; }
[ "function", "getClassExtensions", "(", "classes", ")", "{", "// Extract property definitions from all inherited classes' static \".props\" property", "var", "extensions", "=", "_lodash2", ".", "default", ".", "reduceRight", "(", "classes", ",", "function", "(", "extensions", ",", "current", ")", "{", "var", "extensionsArray", "=", "current", ".", "includes", "?", "_lodash2", ".", "default", ".", "isArray", "(", "current", ".", "includes", ")", "?", "current", ".", "includes", ":", "[", "current", ".", "includes", "]", ":", "[", "]", ";", "_lodash2", ".", "default", ".", "forEach", "(", "extensionsArray", ",", "function", "(", "extension", ")", "{", "extensions", ".", "push", "(", "extension", ")", ";", "}", ")", ";", "return", "extensions", ";", "}", ",", "[", "]", ")", ";", "// Return extracted properties", "return", "extensions", ";", "}" ]
Gets class extensions by traversing and merging static ".includes" property of the instance's class and it's inherited classes @param {any} classes Array of inherited from classes @returns {any} Array of extensions applied to the class
[ "Gets", "class", "extensions", "by", "traversing", "and", "merging", "static", ".", "includes", "property", "of", "the", "instance", "s", "class", "and", "it", "s", "inherited", "classes" ]
fdf27de4142b3c65a3e51dee70e0d7625dff897c
https://github.com/ofzza/enTT/blob/fdf27de4142b3c65a3e51dee70e0d7625dff897c/dist/entt.js#L229-L242
39,606
ofzza/enTT
dist/entt.js
getClassProperties
function getClassProperties(classes) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, extensionsManager = _ref.extensionsManager; // Define checks for shorthand casting configurations var isPropertyShorthandCastAsSingleEntity = function isPropertyShorthandCastAsSingleEntity(propertyConfiguration) { if (propertyConfiguration // Check if class extending EnTT && propertyConfiguration.prototype instanceof EnTT) { return propertyConfiguration; } }; var isPropertyShorthandCastAsEntityArray = function isPropertyShorthandCastAsEntityArray(propertyConfiguration) { if (propertyConfiguration // Check if array && _lodash2.default.isArray(propertyConfiguration) // Check if array has a single member && propertyConfiguration.length === 1 // Check if single array memeber is a class extending EnTT && propertyConfiguration[0].prototype instanceof EnTT) { return propertyConfiguration[0]; } }; var isPropertyShorthandCastAsEntityHashmap = function isPropertyShorthandCastAsEntityHashmap(propertyConfiguration) { if (propertyConfiguration // Check if object && _lodash2.default.isObject(propertyConfiguration) // Check if object has a single member && _lodash2.default.values(propertyConfiguration).length // Check if single object member is a class extending EnTT && _lodash2.default.values(propertyConfiguration)[0].prototype instanceof EnTT // Check if single object member's property key equals class name && _lodash2.default.keys(propertyConfiguration)[0] === _lodash2.default.values(propertyConfiguration)[0].name) { return _lodash2.default.values(propertyConfiguration)[0]; } }; // Extract property definitions from all inherited classes' static ".props" property var properties = _lodash2.default.reduceRight(classes, function (properties, current) { // Extract currentProperties var currentProperties = current.props, CastClass = void 0; // Edit short-hand configuration syntax where possible _lodash2.default.forEach(currentProperties, function (propertyConfiguration, propertyName) { // Replace "casting properties" short-hand configuration syntax for single entity CastClass = isPropertyShorthandCastAsSingleEntity(propertyConfiguration); if (CastClass) { // Replace shorthand cast-as-single-entity syntax currentProperties[propertyName] = { cast: propertyConfiguration }; return; } // Replace "casting properties" short-hand configuration syntax for entity array CastClass = isPropertyShorthandCastAsEntityArray(propertyConfiguration); if (CastClass) { // Replace shorthand cast-as-entity-array syntax currentProperties[propertyName] = { cast: [CastClass] }; return; } // Replace "casting properties" short-hand configuration syntax for entity array CastClass = isPropertyShorthandCastAsEntityHashmap(propertyConfiguration); if (CastClass) { // Replace shorthand cast-as-entity-hashmap syntax currentProperties[propertyName] = { cast: _defineProperty({}, new CastClass().constructor.name, CastClass) }; return; } // EXTENSIONS HOOK: .processShorthandPropertyConfiguration(...) // Lets extensions process short-hand property configuration currentProperties[propertyName] = extensionsManager.processShorthandPropertyConfiguration(propertyConfiguration); }); // Merge with existing properties return _lodash2.default.merge(properties, currentProperties || {}); }, {}); // Update property configuration with default configuration values _lodash2.default.forEach(properties, function (propertyConfiguration, key) { properties[key] = _lodash2.default.merge({}, EnTT.default, propertyConfiguration); }); // Return extracted properties return properties; }
javascript
function getClassProperties(classes) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, extensionsManager = _ref.extensionsManager; // Define checks for shorthand casting configurations var isPropertyShorthandCastAsSingleEntity = function isPropertyShorthandCastAsSingleEntity(propertyConfiguration) { if (propertyConfiguration // Check if class extending EnTT && propertyConfiguration.prototype instanceof EnTT) { return propertyConfiguration; } }; var isPropertyShorthandCastAsEntityArray = function isPropertyShorthandCastAsEntityArray(propertyConfiguration) { if (propertyConfiguration // Check if array && _lodash2.default.isArray(propertyConfiguration) // Check if array has a single member && propertyConfiguration.length === 1 // Check if single array memeber is a class extending EnTT && propertyConfiguration[0].prototype instanceof EnTT) { return propertyConfiguration[0]; } }; var isPropertyShorthandCastAsEntityHashmap = function isPropertyShorthandCastAsEntityHashmap(propertyConfiguration) { if (propertyConfiguration // Check if object && _lodash2.default.isObject(propertyConfiguration) // Check if object has a single member && _lodash2.default.values(propertyConfiguration).length // Check if single object member is a class extending EnTT && _lodash2.default.values(propertyConfiguration)[0].prototype instanceof EnTT // Check if single object member's property key equals class name && _lodash2.default.keys(propertyConfiguration)[0] === _lodash2.default.values(propertyConfiguration)[0].name) { return _lodash2.default.values(propertyConfiguration)[0]; } }; // Extract property definitions from all inherited classes' static ".props" property var properties = _lodash2.default.reduceRight(classes, function (properties, current) { // Extract currentProperties var currentProperties = current.props, CastClass = void 0; // Edit short-hand configuration syntax where possible _lodash2.default.forEach(currentProperties, function (propertyConfiguration, propertyName) { // Replace "casting properties" short-hand configuration syntax for single entity CastClass = isPropertyShorthandCastAsSingleEntity(propertyConfiguration); if (CastClass) { // Replace shorthand cast-as-single-entity syntax currentProperties[propertyName] = { cast: propertyConfiguration }; return; } // Replace "casting properties" short-hand configuration syntax for entity array CastClass = isPropertyShorthandCastAsEntityArray(propertyConfiguration); if (CastClass) { // Replace shorthand cast-as-entity-array syntax currentProperties[propertyName] = { cast: [CastClass] }; return; } // Replace "casting properties" short-hand configuration syntax for entity array CastClass = isPropertyShorthandCastAsEntityHashmap(propertyConfiguration); if (CastClass) { // Replace shorthand cast-as-entity-hashmap syntax currentProperties[propertyName] = { cast: _defineProperty({}, new CastClass().constructor.name, CastClass) }; return; } // EXTENSIONS HOOK: .processShorthandPropertyConfiguration(...) // Lets extensions process short-hand property configuration currentProperties[propertyName] = extensionsManager.processShorthandPropertyConfiguration(propertyConfiguration); }); // Merge with existing properties return _lodash2.default.merge(properties, currentProperties || {}); }, {}); // Update property configuration with default configuration values _lodash2.default.forEach(properties, function (propertyConfiguration, key) { properties[key] = _lodash2.default.merge({}, EnTT.default, propertyConfiguration); }); // Return extracted properties return properties; }
[ "function", "getClassProperties", "(", "classes", ")", "{", "var", "_ref", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "{", "}", ",", "extensionsManager", "=", "_ref", ".", "extensionsManager", ";", "// Define checks for shorthand casting configurations", "var", "isPropertyShorthandCastAsSingleEntity", "=", "function", "isPropertyShorthandCastAsSingleEntity", "(", "propertyConfiguration", ")", "{", "if", "(", "propertyConfiguration", "// Check if class extending EnTT", "&&", "propertyConfiguration", ".", "prototype", "instanceof", "EnTT", ")", "{", "return", "propertyConfiguration", ";", "}", "}", ";", "var", "isPropertyShorthandCastAsEntityArray", "=", "function", "isPropertyShorthandCastAsEntityArray", "(", "propertyConfiguration", ")", "{", "if", "(", "propertyConfiguration", "// Check if array", "&&", "_lodash2", ".", "default", ".", "isArray", "(", "propertyConfiguration", ")", "// Check if array has a single member", "&&", "propertyConfiguration", ".", "length", "===", "1", "// Check if single array memeber is a class extending EnTT", "&&", "propertyConfiguration", "[", "0", "]", ".", "prototype", "instanceof", "EnTT", ")", "{", "return", "propertyConfiguration", "[", "0", "]", ";", "}", "}", ";", "var", "isPropertyShorthandCastAsEntityHashmap", "=", "function", "isPropertyShorthandCastAsEntityHashmap", "(", "propertyConfiguration", ")", "{", "if", "(", "propertyConfiguration", "// Check if object", "&&", "_lodash2", ".", "default", ".", "isObject", "(", "propertyConfiguration", ")", "// Check if object has a single member", "&&", "_lodash2", ".", "default", ".", "values", "(", "propertyConfiguration", ")", ".", "length", "// Check if single object member is a class extending EnTT", "&&", "_lodash2", ".", "default", ".", "values", "(", "propertyConfiguration", ")", "[", "0", "]", ".", "prototype", "instanceof", "EnTT", "// Check if single object member's property key equals class name", "&&", "_lodash2", ".", "default", ".", "keys", "(", "propertyConfiguration", ")", "[", "0", "]", "===", "_lodash2", ".", "default", ".", "values", "(", "propertyConfiguration", ")", "[", "0", "]", ".", "name", ")", "{", "return", "_lodash2", ".", "default", ".", "values", "(", "propertyConfiguration", ")", "[", "0", "]", ";", "}", "}", ";", "// Extract property definitions from all inherited classes' static \".props\" property", "var", "properties", "=", "_lodash2", ".", "default", ".", "reduceRight", "(", "classes", ",", "function", "(", "properties", ",", "current", ")", "{", "// Extract currentProperties", "var", "currentProperties", "=", "current", ".", "props", ",", "CastClass", "=", "void", "0", ";", "// Edit short-hand configuration syntax where possible", "_lodash2", ".", "default", ".", "forEach", "(", "currentProperties", ",", "function", "(", "propertyConfiguration", ",", "propertyName", ")", "{", "// Replace \"casting properties\" short-hand configuration syntax for single entity", "CastClass", "=", "isPropertyShorthandCastAsSingleEntity", "(", "propertyConfiguration", ")", ";", "if", "(", "CastClass", ")", "{", "// Replace shorthand cast-as-single-entity syntax", "currentProperties", "[", "propertyName", "]", "=", "{", "cast", ":", "propertyConfiguration", "}", ";", "return", ";", "}", "// Replace \"casting properties\" short-hand configuration syntax for entity array", "CastClass", "=", "isPropertyShorthandCastAsEntityArray", "(", "propertyConfiguration", ")", ";", "if", "(", "CastClass", ")", "{", "// Replace shorthand cast-as-entity-array syntax", "currentProperties", "[", "propertyName", "]", "=", "{", "cast", ":", "[", "CastClass", "]", "}", ";", "return", ";", "}", "// Replace \"casting properties\" short-hand configuration syntax for entity array", "CastClass", "=", "isPropertyShorthandCastAsEntityHashmap", "(", "propertyConfiguration", ")", ";", "if", "(", "CastClass", ")", "{", "// Replace shorthand cast-as-entity-hashmap syntax", "currentProperties", "[", "propertyName", "]", "=", "{", "cast", ":", "_defineProperty", "(", "{", "}", ",", "new", "CastClass", "(", ")", ".", "constructor", ".", "name", ",", "CastClass", ")", "}", ";", "return", ";", "}", "// EXTENSIONS HOOK: .processShorthandPropertyConfiguration(...)", "// Lets extensions process short-hand property configuration", "currentProperties", "[", "propertyName", "]", "=", "extensionsManager", ".", "processShorthandPropertyConfiguration", "(", "propertyConfiguration", ")", ";", "}", ")", ";", "// Merge with existing properties", "return", "_lodash2", ".", "default", ".", "merge", "(", "properties", ",", "currentProperties", "||", "{", "}", ")", ";", "}", ",", "{", "}", ")", ";", "// Update property configuration with default configuration values", "_lodash2", ".", "default", ".", "forEach", "(", "properties", ",", "function", "(", "propertyConfiguration", ",", "key", ")", "{", "properties", "[", "key", "]", "=", "_lodash2", ".", "default", ".", "merge", "(", "{", "}", ",", "EnTT", ".", "default", ",", "propertyConfiguration", ")", ";", "}", ")", ";", "// Return extracted properties", "return", "properties", ";", "}" ]
Gets class properties configuration by traversing and merging static ".props" property of the instance's class and all it's inherited classes @param {any} classes Array of inherited from classes @param {any} extensionsManager Extensions manager @returns {any} Property configuration for all class' properties
[ "Gets", "class", "properties", "configuration", "by", "traversing", "and", "merging", "static", ".", "props", "property", "of", "the", "instance", "s", "class", "and", "all", "it", "s", "inherited", "classes" ]
fdf27de4142b3c65a3e51dee70e0d7625dff897c
https://github.com/ofzza/enTT/blob/fdf27de4142b3c65a3e51dee70e0d7625dff897c/dist/entt.js#L250-L335
39,607
S3bb1/ah-dashboard-plugin
public/dashboard/bower_components/admin-lte/plugins/datatables/extensions/Responsive/js/dataTables.responsive.js
function ( settings, opts ) { // Sanity check that we are using DataTables 1.10 or newer if ( ! DataTable.versionCheck || ! DataTable.versionCheck( '1.10.1' ) ) { throw 'DataTables Responsive requires DataTables 1.10.1 or newer'; } this.s = { dt: new DataTable.Api( settings ), columns: [] }; // Check if responsive has already been initialised on this table if ( this.s.dt.settings()[0].responsive ) { return; } // details is an object, but for simplicity the user can give it as a string if ( opts && typeof opts.details === 'string' ) { opts.details = { type: opts.details }; } this.c = $.extend( true, {}, Responsive.defaults, DataTable.defaults.responsive, opts ); settings.responsive = this; this._constructor(); }
javascript
function ( settings, opts ) { // Sanity check that we are using DataTables 1.10 or newer if ( ! DataTable.versionCheck || ! DataTable.versionCheck( '1.10.1' ) ) { throw 'DataTables Responsive requires DataTables 1.10.1 or newer'; } this.s = { dt: new DataTable.Api( settings ), columns: [] }; // Check if responsive has already been initialised on this table if ( this.s.dt.settings()[0].responsive ) { return; } // details is an object, but for simplicity the user can give it as a string if ( opts && typeof opts.details === 'string' ) { opts.details = { type: opts.details }; } this.c = $.extend( true, {}, Responsive.defaults, DataTable.defaults.responsive, opts ); settings.responsive = this; this._constructor(); }
[ "function", "(", "settings", ",", "opts", ")", "{", "// Sanity check that we are using DataTables 1.10 or newer", "if", "(", "!", "DataTable", ".", "versionCheck", "||", "!", "DataTable", ".", "versionCheck", "(", "'1.10.1'", ")", ")", "{", "throw", "'DataTables Responsive requires DataTables 1.10.1 or newer'", ";", "}", "this", ".", "s", "=", "{", "dt", ":", "new", "DataTable", ".", "Api", "(", "settings", ")", ",", "columns", ":", "[", "]", "}", ";", "// Check if responsive has already been initialised on this table", "if", "(", "this", ".", "s", ".", "dt", ".", "settings", "(", ")", "[", "0", "]", ".", "responsive", ")", "{", "return", ";", "}", "// details is an object, but for simplicity the user can give it as a string", "if", "(", "opts", "&&", "typeof", "opts", ".", "details", "===", "'string'", ")", "{", "opts", ".", "details", "=", "{", "type", ":", "opts", ".", "details", "}", ";", "}", "this", ".", "c", "=", "$", ".", "extend", "(", "true", ",", "{", "}", ",", "Responsive", ".", "defaults", ",", "DataTable", ".", "defaults", ".", "responsive", ",", "opts", ")", ";", "settings", ".", "responsive", "=", "this", ";", "this", ".", "_constructor", "(", ")", ";", "}" ]
Responsive is a plug-in for the DataTables library that makes use of DataTables' ability to change the visibility of columns, changing the visibility of columns so the displayed columns fit into the table container. The end result is that complex tables will be dynamically adjusted to fit into the viewport, be it on a desktop, tablet or mobile browser. Responsive for DataTables has two modes of operation, which can used individually or combined: * Class name based control - columns assigned class names that match the breakpoint logic can be shown / hidden as required for each breakpoint. * Automatic control - columns are automatically hidden when there is no room left to display them. Columns removed from the right. In additional to column visibility control, Responsive also has built into options to use DataTables' child row display to show / hide the information from the table that has been hidden. There are also two modes of operation for this child row display: * Inline - when the control element that the user can use to show / hide child rows is displayed inside the first column of the table. * Column - where a whole column is dedicated to be the show / hide control. Initialisation of Responsive is performed by: * Adding the class `responsive` or `dt-responsive` to the table. In this case Responsive will automatically be initialised with the default configuration options when the DataTable is created. * Using the `responsive` option in the DataTables configuration options. This can also be used to specify the configuration options, or simply set to `true` to use the defaults. @class @param {object} settings DataTables settings object for the host table @param {object} [opts] Configuration options @requires jQuery 1.7+ @requires DataTables 1.10.1+ @example $('#example').DataTable( { responsive: true } ); } );
[ "Responsive", "is", "a", "plug", "-", "in", "for", "the", "DataTables", "library", "that", "makes", "use", "of", "DataTables", "ability", "to", "change", "the", "visibility", "of", "columns", "changing", "the", "visibility", "of", "columns", "so", "the", "displayed", "columns", "fit", "into", "the", "table", "container", ".", "The", "end", "result", "is", "that", "complex", "tables", "will", "be", "dynamically", "adjusted", "to", "fit", "into", "the", "viewport", "be", "it", "on", "a", "desktop", "tablet", "or", "mobile", "browser", "." ]
c283370ec0f99a25db5bb7029a98b4febf8c5251
https://github.com/S3bb1/ah-dashboard-plugin/blob/c283370ec0f99a25db5bb7029a98b4febf8c5251/public/dashboard/bower_components/admin-lte/plugins/datatables/extensions/Responsive/js/dataTables.responsive.js#L75-L99
39,608
S3bb1/ah-dashboard-plugin
public/dashboard/bower_components/admin-lte/plugins/datatables/extensions/Responsive/js/dataTables.responsive.js
function ( colIdx, name ) { var includeIn = columns[ colIdx ].includeIn; if ( $.inArray( name, includeIn ) === -1 ) { includeIn.push( name ); } }
javascript
function ( colIdx, name ) { var includeIn = columns[ colIdx ].includeIn; if ( $.inArray( name, includeIn ) === -1 ) { includeIn.push( name ); } }
[ "function", "(", "colIdx", ",", "name", ")", "{", "var", "includeIn", "=", "columns", "[", "colIdx", "]", ".", "includeIn", ";", "if", "(", "$", ".", "inArray", "(", "name", ",", "includeIn", ")", "===", "-", "1", ")", "{", "includeIn", ".", "push", "(", "name", ")", ";", "}", "}" ]
Simply add a breakpoint to `includeIn` array, ensuring that there are no duplicates
[ "Simply", "add", "a", "breakpoint", "to", "includeIn", "array", "ensuring", "that", "there", "are", "no", "duplicates" ]
c283370ec0f99a25db5bb7029a98b4febf8c5251
https://github.com/S3bb1/ah-dashboard-plugin/blob/c283370ec0f99a25db5bb7029a98b4febf8c5251/public/dashboard/bower_components/admin-lte/plugins/datatables/extensions/Responsive/js/dataTables.responsive.js#L314-L320
39,609
S3bb1/ah-dashboard-plugin
public/dashboard/bower_components/admin-lte/plugins/datatables/extensions/Responsive/js/dataTables.responsive.js
function () { var that = this; var dt = this.s.dt; var details = this.c.details; // The inline type always uses the first child as the target if ( details.type === 'inline' ) { details.target = 'td:first-child'; } // type.target can be a string jQuery selector or a column index var target = details.target; var selector = typeof target === 'string' ? target : 'td'; // Click handler to show / hide the details rows when they are available $( dt.table().body() ).on( 'click', selector, function (e) { // If the table is not collapsed (i.e. there is no hidden columns) // then take no action if ( ! $(dt.table().node()).hasClass('collapsed' ) ) { return; } // Check that the row is actually a DataTable's controlled node if ( ! dt.row( $(this).closest('tr') ).length ) { return; } // For column index, we determine if we should act or not in the // handler - otherwise it is already okay if ( typeof target === 'number' ) { var targetIdx = target < 0 ? dt.columns().eq(0).length + target : target; if ( dt.cell( this ).index().column !== targetIdx ) { return; } } // $().closest() includes itself in its check var row = dt.row( $(this).closest('tr') ); if ( row.child.isShown() ) { row.child( false ); $( row.node() ).removeClass( 'parent' ); } else { var info = that.c.details.renderer( dt, row[0] ); row.child( info, 'child' ).show(); $( row.node() ).addClass( 'parent' ); } } ); }
javascript
function () { var that = this; var dt = this.s.dt; var details = this.c.details; // The inline type always uses the first child as the target if ( details.type === 'inline' ) { details.target = 'td:first-child'; } // type.target can be a string jQuery selector or a column index var target = details.target; var selector = typeof target === 'string' ? target : 'td'; // Click handler to show / hide the details rows when they are available $( dt.table().body() ).on( 'click', selector, function (e) { // If the table is not collapsed (i.e. there is no hidden columns) // then take no action if ( ! $(dt.table().node()).hasClass('collapsed' ) ) { return; } // Check that the row is actually a DataTable's controlled node if ( ! dt.row( $(this).closest('tr') ).length ) { return; } // For column index, we determine if we should act or not in the // handler - otherwise it is already okay if ( typeof target === 'number' ) { var targetIdx = target < 0 ? dt.columns().eq(0).length + target : target; if ( dt.cell( this ).index().column !== targetIdx ) { return; } } // $().closest() includes itself in its check var row = dt.row( $(this).closest('tr') ); if ( row.child.isShown() ) { row.child( false ); $( row.node() ).removeClass( 'parent' ); } else { var info = that.c.details.renderer( dt, row[0] ); row.child( info, 'child' ).show(); $( row.node() ).addClass( 'parent' ); } } ); }
[ "function", "(", ")", "{", "var", "that", "=", "this", ";", "var", "dt", "=", "this", ".", "s", ".", "dt", ";", "var", "details", "=", "this", ".", "c", ".", "details", ";", "// The inline type always uses the first child as the target", "if", "(", "details", ".", "type", "===", "'inline'", ")", "{", "details", ".", "target", "=", "'td:first-child'", ";", "}", "// type.target can be a string jQuery selector or a column index", "var", "target", "=", "details", ".", "target", ";", "var", "selector", "=", "typeof", "target", "===", "'string'", "?", "target", ":", "'td'", ";", "// Click handler to show / hide the details rows when they are available", "$", "(", "dt", ".", "table", "(", ")", ".", "body", "(", ")", ")", ".", "on", "(", "'click'", ",", "selector", ",", "function", "(", "e", ")", "{", "// If the table is not collapsed (i.e. there is no hidden columns)", "// then take no action", "if", "(", "!", "$", "(", "dt", ".", "table", "(", ")", ".", "node", "(", ")", ")", ".", "hasClass", "(", "'collapsed'", ")", ")", "{", "return", ";", "}", "// Check that the row is actually a DataTable's controlled node", "if", "(", "!", "dt", ".", "row", "(", "$", "(", "this", ")", ".", "closest", "(", "'tr'", ")", ")", ".", "length", ")", "{", "return", ";", "}", "// For column index, we determine if we should act or not in the", "// handler - otherwise it is already okay", "if", "(", "typeof", "target", "===", "'number'", ")", "{", "var", "targetIdx", "=", "target", "<", "0", "?", "dt", ".", "columns", "(", ")", ".", "eq", "(", "0", ")", ".", "length", "+", "target", ":", "target", ";", "if", "(", "dt", ".", "cell", "(", "this", ")", ".", "index", "(", ")", ".", "column", "!==", "targetIdx", ")", "{", "return", ";", "}", "}", "// $().closest() includes itself in its check", "var", "row", "=", "dt", ".", "row", "(", "$", "(", "this", ")", ".", "closest", "(", "'tr'", ")", ")", ";", "if", "(", "row", ".", "child", ".", "isShown", "(", ")", ")", "{", "row", ".", "child", "(", "false", ")", ";", "$", "(", "row", ".", "node", "(", ")", ")", ".", "removeClass", "(", "'parent'", ")", ";", "}", "else", "{", "var", "info", "=", "that", ".", "c", ".", "details", ".", "renderer", "(", "dt", ",", "row", "[", "0", "]", ")", ";", "row", ".", "child", "(", "info", ",", "'child'", ")", ".", "show", "(", ")", ";", "$", "(", "row", ".", "node", "(", ")", ")", ".", "addClass", "(", "'parent'", ")", ";", "}", "}", ")", ";", "}" ]
Initialisation for the details handler @private
[ "Initialisation", "for", "the", "details", "handler" ]
c283370ec0f99a25db5bb7029a98b4febf8c5251
https://github.com/S3bb1/ah-dashboard-plugin/blob/c283370ec0f99a25db5bb7029a98b4febf8c5251/public/dashboard/bower_components/admin-lte/plugins/datatables/extensions/Responsive/js/dataTables.responsive.js#L426-L479
39,610
S3bb1/ah-dashboard-plugin
public/dashboard/bower_components/admin-lte/plugins/datatables/extensions/Responsive/js/dataTables.responsive.js
function () { var that = this; var dt = this.s.dt; // Find how many columns are hidden var hiddenColumns = dt.columns().indexes().filter( function ( idx ) { var col = dt.column( idx ); if ( col.visible() ) { return null; } // Only counts as hidden if it doesn't have the `never` class return $( col.header() ).hasClass( 'never' ) ? null : idx; } ); var haveHidden = true; if ( hiddenColumns.length === 0 || ( hiddenColumns.length === 1 && this.s.columns[ hiddenColumns[0] ].control ) ) { haveHidden = false; } if ( haveHidden ) { // Show all existing child rows dt.rows( { page: 'current' } ).eq(0).each( function (idx) { var row = dt.row( idx ); if ( row.child() ) { var info = that.c.details.renderer( dt, row[0] ); // The renderer can return false to have no child row if ( info === false ) { row.child.hide(); } else { row.child( info, 'child' ).show(); } } } ); } else { // Hide all existing child rows dt.rows( { page: 'current' } ).eq(0).each( function (idx) { dt.row( idx ).child.hide(); } ); } }
javascript
function () { var that = this; var dt = this.s.dt; // Find how many columns are hidden var hiddenColumns = dt.columns().indexes().filter( function ( idx ) { var col = dt.column( idx ); if ( col.visible() ) { return null; } // Only counts as hidden if it doesn't have the `never` class return $( col.header() ).hasClass( 'never' ) ? null : idx; } ); var haveHidden = true; if ( hiddenColumns.length === 0 || ( hiddenColumns.length === 1 && this.s.columns[ hiddenColumns[0] ].control ) ) { haveHidden = false; } if ( haveHidden ) { // Show all existing child rows dt.rows( { page: 'current' } ).eq(0).each( function (idx) { var row = dt.row( idx ); if ( row.child() ) { var info = that.c.details.renderer( dt, row[0] ); // The renderer can return false to have no child row if ( info === false ) { row.child.hide(); } else { row.child( info, 'child' ).show(); } } } ); } else { // Hide all existing child rows dt.rows( { page: 'current' } ).eq(0).each( function (idx) { dt.row( idx ).child.hide(); } ); } }
[ "function", "(", ")", "{", "var", "that", "=", "this", ";", "var", "dt", "=", "this", ".", "s", ".", "dt", ";", "// Find how many columns are hidden", "var", "hiddenColumns", "=", "dt", ".", "columns", "(", ")", ".", "indexes", "(", ")", ".", "filter", "(", "function", "(", "idx", ")", "{", "var", "col", "=", "dt", ".", "column", "(", "idx", ")", ";", "if", "(", "col", ".", "visible", "(", ")", ")", "{", "return", "null", ";", "}", "// Only counts as hidden if it doesn't have the `never` class", "return", "$", "(", "col", ".", "header", "(", ")", ")", ".", "hasClass", "(", "'never'", ")", "?", "null", ":", "idx", ";", "}", ")", ";", "var", "haveHidden", "=", "true", ";", "if", "(", "hiddenColumns", ".", "length", "===", "0", "||", "(", "hiddenColumns", ".", "length", "===", "1", "&&", "this", ".", "s", ".", "columns", "[", "hiddenColumns", "[", "0", "]", "]", ".", "control", ")", ")", "{", "haveHidden", "=", "false", ";", "}", "if", "(", "haveHidden", ")", "{", "// Show all existing child rows", "dt", ".", "rows", "(", "{", "page", ":", "'current'", "}", ")", ".", "eq", "(", "0", ")", ".", "each", "(", "function", "(", "idx", ")", "{", "var", "row", "=", "dt", ".", "row", "(", "idx", ")", ";", "if", "(", "row", ".", "child", "(", ")", ")", "{", "var", "info", "=", "that", ".", "c", ".", "details", ".", "renderer", "(", "dt", ",", "row", "[", "0", "]", ")", ";", "// The renderer can return false to have no child row", "if", "(", "info", "===", "false", ")", "{", "row", ".", "child", ".", "hide", "(", ")", ";", "}", "else", "{", "row", ".", "child", "(", "info", ",", "'child'", ")", ".", "show", "(", ")", ";", "}", "}", "}", ")", ";", "}", "else", "{", "// Hide all existing child rows", "dt", ".", "rows", "(", "{", "page", ":", "'current'", "}", ")", ".", "eq", "(", "0", ")", ".", "each", "(", "function", "(", "idx", ")", "{", "dt", ".", "row", "(", "idx", ")", ".", "child", ".", "hide", "(", ")", ";", "}", ")", ";", "}", "}" ]
Update the child rows in the table whenever the column visibility changes @private
[ "Update", "the", "child", "rows", "in", "the", "table", "whenever", "the", "column", "visibility", "changes" ]
c283370ec0f99a25db5bb7029a98b4febf8c5251
https://github.com/S3bb1/ah-dashboard-plugin/blob/c283370ec0f99a25db5bb7029a98b4febf8c5251/public/dashboard/bower_components/admin-lte/plugins/datatables/extensions/Responsive/js/dataTables.responsive.js#L487-L533
39,611
S3bb1/ah-dashboard-plugin
public/dashboard/bower_components/admin-lte/plugins/datatables/extensions/Responsive/js/dataTables.responsive.js
function ( name ) { var breakpoints = this.c.breakpoints; for ( var i=0, ien=breakpoints.length ; i<ien ; i++ ) { if ( breakpoints[i].name === name ) { return breakpoints[i]; } } }
javascript
function ( name ) { var breakpoints = this.c.breakpoints; for ( var i=0, ien=breakpoints.length ; i<ien ; i++ ) { if ( breakpoints[i].name === name ) { return breakpoints[i]; } } }
[ "function", "(", "name", ")", "{", "var", "breakpoints", "=", "this", ".", "c", ".", "breakpoints", ";", "for", "(", "var", "i", "=", "0", ",", "ien", "=", "breakpoints", ".", "length", ";", "i", "<", "ien", ";", "i", "++", ")", "{", "if", "(", "breakpoints", "[", "i", "]", ".", "name", "===", "name", ")", "{", "return", "breakpoints", "[", "i", "]", ";", "}", "}", "}" ]
Find a breakpoint object from a name @param {string} name Breakpoint name to find @return {object} Breakpoint description object
[ "Find", "a", "breakpoint", "object", "from", "a", "name" ]
c283370ec0f99a25db5bb7029a98b4febf8c5251
https://github.com/S3bb1/ah-dashboard-plugin/blob/c283370ec0f99a25db5bb7029a98b4febf8c5251/public/dashboard/bower_components/admin-lte/plugins/datatables/extensions/Responsive/js/dataTables.responsive.js#L541-L550
39,612
S3bb1/ah-dashboard-plugin
public/dashboard/bower_components/admin-lte/plugins/datatables/extensions/Responsive/js/dataTables.responsive.js
function () { var dt = this.s.dt; var width = $(window).width(); var breakpoints = this.c.breakpoints; var breakpoint = breakpoints[0].name; var columns = this.s.columns; var i, ien; // Determine what breakpoint we are currently at for ( i=breakpoints.length-1 ; i>=0 ; i-- ) { if ( width <= breakpoints[i].width ) { breakpoint = breakpoints[i].name; break; } } // Show the columns for that break point var columnsVis = this._columnsVisiblity( breakpoint ); // Set the class before the column visibility is changed so event // listeners know what the state is. Need to determine if there are // any columns that are not visible but can be shown var collapsedClass = false; for ( i=0, ien=columns.length ; i<ien ; i++ ) { if ( columnsVis[i] === false && ! columns[i].never ) { collapsedClass = true; break; } } $( dt.table().node() ).toggleClass('collapsed', collapsedClass ); dt.columns().eq(0).each( function ( colIdx, i ) { dt.column( colIdx ).visible( columnsVis[i] ); } ); }
javascript
function () { var dt = this.s.dt; var width = $(window).width(); var breakpoints = this.c.breakpoints; var breakpoint = breakpoints[0].name; var columns = this.s.columns; var i, ien; // Determine what breakpoint we are currently at for ( i=breakpoints.length-1 ; i>=0 ; i-- ) { if ( width <= breakpoints[i].width ) { breakpoint = breakpoints[i].name; break; } } // Show the columns for that break point var columnsVis = this._columnsVisiblity( breakpoint ); // Set the class before the column visibility is changed so event // listeners know what the state is. Need to determine if there are // any columns that are not visible but can be shown var collapsedClass = false; for ( i=0, ien=columns.length ; i<ien ; i++ ) { if ( columnsVis[i] === false && ! columns[i].never ) { collapsedClass = true; break; } } $( dt.table().node() ).toggleClass('collapsed', collapsedClass ); dt.columns().eq(0).each( function ( colIdx, i ) { dt.column( colIdx ).visible( columnsVis[i] ); } ); }
[ "function", "(", ")", "{", "var", "dt", "=", "this", ".", "s", ".", "dt", ";", "var", "width", "=", "$", "(", "window", ")", ".", "width", "(", ")", ";", "var", "breakpoints", "=", "this", ".", "c", ".", "breakpoints", ";", "var", "breakpoint", "=", "breakpoints", "[", "0", "]", ".", "name", ";", "var", "columns", "=", "this", ".", "s", ".", "columns", ";", "var", "i", ",", "ien", ";", "// Determine what breakpoint we are currently at", "for", "(", "i", "=", "breakpoints", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "width", "<=", "breakpoints", "[", "i", "]", ".", "width", ")", "{", "breakpoint", "=", "breakpoints", "[", "i", "]", ".", "name", ";", "break", ";", "}", "}", "// Show the columns for that break point", "var", "columnsVis", "=", "this", ".", "_columnsVisiblity", "(", "breakpoint", ")", ";", "// Set the class before the column visibility is changed so event", "// listeners know what the state is. Need to determine if there are", "// any columns that are not visible but can be shown", "var", "collapsedClass", "=", "false", ";", "for", "(", "i", "=", "0", ",", "ien", "=", "columns", ".", "length", ";", "i", "<", "ien", ";", "i", "++", ")", "{", "if", "(", "columnsVis", "[", "i", "]", "===", "false", "&&", "!", "columns", "[", "i", "]", ".", "never", ")", "{", "collapsedClass", "=", "true", ";", "break", ";", "}", "}", "$", "(", "dt", ".", "table", "(", ")", ".", "node", "(", ")", ")", ".", "toggleClass", "(", "'collapsed'", ",", "collapsedClass", ")", ";", "dt", ".", "columns", "(", ")", ".", "eq", "(", "0", ")", ".", "each", "(", "function", "(", "colIdx", ",", "i", ")", "{", "dt", ".", "column", "(", "colIdx", ")", ".", "visible", "(", "columnsVis", "[", "i", "]", ")", ";", "}", ")", ";", "}" ]
Alter the table display for a resized viewport. This involves first determining what breakpoint the window currently is in, getting the column visibilities to apply and then setting them. @private
[ "Alter", "the", "table", "display", "for", "a", "resized", "viewport", ".", "This", "involves", "first", "determining", "what", "breakpoint", "the", "window", "currently", "is", "in", "getting", "the", "column", "visibilities", "to", "apply", "and", "then", "setting", "them", "." ]
c283370ec0f99a25db5bb7029a98b4febf8c5251
https://github.com/S3bb1/ah-dashboard-plugin/blob/c283370ec0f99a25db5bb7029a98b4febf8c5251/public/dashboard/bower_components/admin-lte/plugins/datatables/extensions/Responsive/js/dataTables.responsive.js#L560-L596
39,613
S3bb1/ah-dashboard-plugin
public/dashboard/bower_components/admin-lte/plugins/datatables/extensions/Responsive/js/dataTables.responsive.js
function () { var dt = this.s.dt; var columns = this.s.columns; // Are we allowed to do auto sizing? if ( ! this.c.auto ) { return; } // Are there any columns that actually need auto-sizing, or do they all // have classes defined if ( $.inArray( true, $.map( columns, function (c) { return c.auto; } ) ) === -1 ) { return; } // Clone the table with the current data in it var tableWidth = dt.table().node().offsetWidth; var columnWidths = dt.columns; var clonedTable = dt.table().node().cloneNode( false ); var clonedHeader = $( dt.table().header().cloneNode( false ) ).appendTo( clonedTable ); var clonedBody = $( dt.table().body().cloneNode( false ) ).appendTo( clonedTable ); $( dt.table().footer() ).clone( false ).appendTo( clonedTable ); // This is a bit slow, but we need to get a clone of each row that // includes all columns. As such, try to do this as little as possible. dt.rows( { page: 'current' } ).indexes().flatten().each( function ( idx ) { var clone = dt.row( idx ).node().cloneNode( true ); if ( dt.columns( ':hidden' ).flatten().length ) { $(clone).append( dt.cells( idx, ':hidden' ).nodes().to$().clone() ); } $(clone).appendTo( clonedBody ); } ); var cells = dt.columns().header().to$().clone( false ); $('<tr/>') .append( cells ) .appendTo( clonedHeader ); // In the inline case extra padding is applied to the first column to // give space for the show / hide icon. We need to use this in the // calculation if ( this.c.details.type === 'inline' ) { $(clonedTable).addClass( 'dtr-inline collapsed' ); } var inserted = $('<div/>') .css( { width: 1, height: 1, overflow: 'hidden' } ) .append( clonedTable ); // Remove columns which are not to be included inserted.find('th.never, td.never').remove(); inserted.insertBefore( dt.table().node() ); // The cloned header now contains the smallest that each column can be dt.columns().eq(0).each( function ( idx ) { columns[idx].minWidth = cells[ idx ].offsetWidth || 0; } ); inserted.remove(); }
javascript
function () { var dt = this.s.dt; var columns = this.s.columns; // Are we allowed to do auto sizing? if ( ! this.c.auto ) { return; } // Are there any columns that actually need auto-sizing, or do they all // have classes defined if ( $.inArray( true, $.map( columns, function (c) { return c.auto; } ) ) === -1 ) { return; } // Clone the table with the current data in it var tableWidth = dt.table().node().offsetWidth; var columnWidths = dt.columns; var clonedTable = dt.table().node().cloneNode( false ); var clonedHeader = $( dt.table().header().cloneNode( false ) ).appendTo( clonedTable ); var clonedBody = $( dt.table().body().cloneNode( false ) ).appendTo( clonedTable ); $( dt.table().footer() ).clone( false ).appendTo( clonedTable ); // This is a bit slow, but we need to get a clone of each row that // includes all columns. As such, try to do this as little as possible. dt.rows( { page: 'current' } ).indexes().flatten().each( function ( idx ) { var clone = dt.row( idx ).node().cloneNode( true ); if ( dt.columns( ':hidden' ).flatten().length ) { $(clone).append( dt.cells( idx, ':hidden' ).nodes().to$().clone() ); } $(clone).appendTo( clonedBody ); } ); var cells = dt.columns().header().to$().clone( false ); $('<tr/>') .append( cells ) .appendTo( clonedHeader ); // In the inline case extra padding is applied to the first column to // give space for the show / hide icon. We need to use this in the // calculation if ( this.c.details.type === 'inline' ) { $(clonedTable).addClass( 'dtr-inline collapsed' ); } var inserted = $('<div/>') .css( { width: 1, height: 1, overflow: 'hidden' } ) .append( clonedTable ); // Remove columns which are not to be included inserted.find('th.never, td.never').remove(); inserted.insertBefore( dt.table().node() ); // The cloned header now contains the smallest that each column can be dt.columns().eq(0).each( function ( idx ) { columns[idx].minWidth = cells[ idx ].offsetWidth || 0; } ); inserted.remove(); }
[ "function", "(", ")", "{", "var", "dt", "=", "this", ".", "s", ".", "dt", ";", "var", "columns", "=", "this", ".", "s", ".", "columns", ";", "// Are we allowed to do auto sizing?", "if", "(", "!", "this", ".", "c", ".", "auto", ")", "{", "return", ";", "}", "// Are there any columns that actually need auto-sizing, or do they all", "// have classes defined", "if", "(", "$", ".", "inArray", "(", "true", ",", "$", ".", "map", "(", "columns", ",", "function", "(", "c", ")", "{", "return", "c", ".", "auto", ";", "}", ")", ")", "===", "-", "1", ")", "{", "return", ";", "}", "// Clone the table with the current data in it", "var", "tableWidth", "=", "dt", ".", "table", "(", ")", ".", "node", "(", ")", ".", "offsetWidth", ";", "var", "columnWidths", "=", "dt", ".", "columns", ";", "var", "clonedTable", "=", "dt", ".", "table", "(", ")", ".", "node", "(", ")", ".", "cloneNode", "(", "false", ")", ";", "var", "clonedHeader", "=", "$", "(", "dt", ".", "table", "(", ")", ".", "header", "(", ")", ".", "cloneNode", "(", "false", ")", ")", ".", "appendTo", "(", "clonedTable", ")", ";", "var", "clonedBody", "=", "$", "(", "dt", ".", "table", "(", ")", ".", "body", "(", ")", ".", "cloneNode", "(", "false", ")", ")", ".", "appendTo", "(", "clonedTable", ")", ";", "$", "(", "dt", ".", "table", "(", ")", ".", "footer", "(", ")", ")", ".", "clone", "(", "false", ")", ".", "appendTo", "(", "clonedTable", ")", ";", "// This is a bit slow, but we need to get a clone of each row that", "// includes all columns. As such, try to do this as little as possible.", "dt", ".", "rows", "(", "{", "page", ":", "'current'", "}", ")", ".", "indexes", "(", ")", ".", "flatten", "(", ")", ".", "each", "(", "function", "(", "idx", ")", "{", "var", "clone", "=", "dt", ".", "row", "(", "idx", ")", ".", "node", "(", ")", ".", "cloneNode", "(", "true", ")", ";", "if", "(", "dt", ".", "columns", "(", "':hidden'", ")", ".", "flatten", "(", ")", ".", "length", ")", "{", "$", "(", "clone", ")", ".", "append", "(", "dt", ".", "cells", "(", "idx", ",", "':hidden'", ")", ".", "nodes", "(", ")", ".", "to$", "(", ")", ".", "clone", "(", ")", ")", ";", "}", "$", "(", "clone", ")", ".", "appendTo", "(", "clonedBody", ")", ";", "}", ")", ";", "var", "cells", "=", "dt", ".", "columns", "(", ")", ".", "header", "(", ")", ".", "to$", "(", ")", ".", "clone", "(", "false", ")", ";", "$", "(", "'<tr/>'", ")", ".", "append", "(", "cells", ")", ".", "appendTo", "(", "clonedHeader", ")", ";", "// In the inline case extra padding is applied to the first column to", "// give space for the show / hide icon. We need to use this in the", "// calculation", "if", "(", "this", ".", "c", ".", "details", ".", "type", "===", "'inline'", ")", "{", "$", "(", "clonedTable", ")", ".", "addClass", "(", "'dtr-inline collapsed'", ")", ";", "}", "var", "inserted", "=", "$", "(", "'<div/>'", ")", ".", "css", "(", "{", "width", ":", "1", ",", "height", ":", "1", ",", "overflow", ":", "'hidden'", "}", ")", ".", "append", "(", "clonedTable", ")", ";", "// Remove columns which are not to be included", "inserted", ".", "find", "(", "'th.never, td.never'", ")", ".", "remove", "(", ")", ";", "inserted", ".", "insertBefore", "(", "dt", ".", "table", "(", ")", ".", "node", "(", ")", ")", ";", "// The cloned header now contains the smallest that each column can be", "dt", ".", "columns", "(", ")", ".", "eq", "(", "0", ")", ".", "each", "(", "function", "(", "idx", ")", "{", "columns", "[", "idx", "]", ".", "minWidth", "=", "cells", "[", "idx", "]", ".", "offsetWidth", "||", "0", ";", "}", ")", ";", "inserted", ".", "remove", "(", ")", ";", "}" ]
Determine the width of each column in the table so the auto column hiding has that information to work with. This method is never going to be 100% perfect since column widths can change slightly per page, but without seriously compromising performance this is quite effective. @private
[ "Determine", "the", "width", "of", "each", "column", "in", "the", "table", "so", "the", "auto", "column", "hiding", "has", "that", "information", "to", "work", "with", ".", "This", "method", "is", "never", "going", "to", "be", "100%", "perfect", "since", "column", "widths", "can", "change", "slightly", "per", "page", "but", "without", "seriously", "compromising", "performance", "this", "is", "quite", "effective", "." ]
c283370ec0f99a25db5bb7029a98b4febf8c5251
https://github.com/S3bb1/ah-dashboard-plugin/blob/c283370ec0f99a25db5bb7029a98b4febf8c5251/public/dashboard/bower_components/admin-lte/plugins/datatables/extensions/Responsive/js/dataTables.responsive.js#L607-L675
39,614
MaddHacker/server-lite
lib/sl-content.js
Content
function Content(mimeType, content) { var obj = {}; obj.type = mimeType + '; charset=utf-8'; obj.value = content; obj.length = content.length; return obj; }
javascript
function Content(mimeType, content) { var obj = {}; obj.type = mimeType + '; charset=utf-8'; obj.value = content; obj.length = content.length; return obj; }
[ "function", "Content", "(", "mimeType", ",", "content", ")", "{", "var", "obj", "=", "{", "}", ";", "obj", ".", "type", "=", "mimeType", "+", "'; charset=utf-8'", ";", "obj", ".", "value", "=", "content", ";", "obj", ".", "length", "=", "content", ".", "length", ";", "return", "obj", ";", "}" ]
Generic concept of a Content-Type model => all content is assumed to have charset = 'utf-8' @param {String} mimeType => how the client should read the content @param {Object} content => actual content (file, image, etc) @returns {Content} content wrapper for given payload.
[ "Generic", "concept", "of", "a", "Content", "-", "Type", "model", "=", ">", "all", "content", "is", "assumed", "to", "have", "charset", "=", "utf", "-", "8" ]
5cf606503bb7c434c5a29b3bbbf39fab1cb24fa8
https://github.com/MaddHacker/server-lite/blob/5cf606503bb7c434c5a29b3bbbf39fab1cb24fa8/lib/sl-content.js#L26-L34
39,615
adrai/node-cqs
lib/domain/domain.js
function(cmdPointer, next) { // Publish it now... commandDispatcher.dispatch(cmdPointer.command, function(err) { if (cmdPointer.callback) cmdPointer.callback(null); next(); }); }
javascript
function(cmdPointer, next) { // Publish it now... commandDispatcher.dispatch(cmdPointer.command, function(err) { if (cmdPointer.callback) cmdPointer.callback(null); next(); }); }
[ "function", "(", "cmdPointer", ",", "next", ")", "{", "// Publish it now...", "commandDispatcher", ".", "dispatch", "(", "cmdPointer", ".", "command", ",", "function", "(", "err", ")", "{", "if", "(", "cmdPointer", ".", "callback", ")", "cmdPointer", ".", "callback", "(", "null", ")", ";", "next", "(", ")", ";", "}", ")", ";", "}" ]
dipatch one command in queue and call the _next_ callback, which will call _process_ for the next command in queue.
[ "dipatch", "one", "command", "in", "queue", "and", "call", "the", "_next_", "callback", "which", "will", "call", "_process_", "for", "the", "next", "command", "in", "queue", "." ]
1691670a6e35d0b20904a5bd1b74adbe92f496eb
https://github.com/adrai/node-cqs/blob/1691670a6e35d0b20904a5bd1b74adbe92f496eb/lib/domain/domain.js#L163-L170
39,616
bBlocks/dom
dom.js
function(selector, all) { if (!this.querySelector) {bb.warn('Find should be used with DOM elements'); return;} return all && this.querySelectorAll(selector) || this.querySelector(selector); }
javascript
function(selector, all) { if (!this.querySelector) {bb.warn('Find should be used with DOM elements'); return;} return all && this.querySelectorAll(selector) || this.querySelector(selector); }
[ "function", "(", "selector", ",", "all", ")", "{", "if", "(", "!", "this", ".", "querySelector", ")", "{", "bb", ".", "warn", "(", "'Find should be used with DOM elements'", ")", ";", "return", ";", "}", "return", "all", "&&", "this", ".", "querySelectorAll", "(", "selector", ")", "||", "this", ".", "querySelector", "(", "selector", ")", ";", "}" ]
Finds child element matching provided selector @param {string} selector - Selector has limitations based on the browser support. @param {boolean} all - Flag to find all matching elements. Otherwise fist found element is returned. @return {element|array|undefined} - Found element or array of elements
[ "Finds", "child", "element", "matching", "provided", "selector" ]
3381b3bf3a0415a852f60d8f53c7cac2765ee9b6
https://github.com/bBlocks/dom/blob/3381b3bf3a0415a852f60d8f53c7cac2765ee9b6/dom.js#L40-L43
39,617
bBlocks/dom
dom.js
function(html, tag) { var el = document.createElement(tag || 'div'); el.innerHTML = html; return el; }
javascript
function(html, tag) { var el = document.createElement(tag || 'div'); el.innerHTML = html; return el; }
[ "function", "(", "html", ",", "tag", ")", "{", "var", "el", "=", "document", ".", "createElement", "(", "tag", "||", "'div'", ")", ";", "el", ".", "innerHTML", "=", "html", ";", "return", "el", ";", "}" ]
Creates a new HTMLElement with provided contents @param {string} html - HTML contents @param {string=} tag - Optional tag of the element to create
[ "Creates", "a", "new", "HTMLElement", "with", "provided", "contents" ]
3381b3bf3a0415a852f60d8f53c7cac2765ee9b6
https://github.com/bBlocks/dom/blob/3381b3bf3a0415a852f60d8f53c7cac2765ee9b6/dom.js#L103-L107
39,618
enquirer/terminal-paginator
index.js
Paginator
function Paginator(options) { debug('initializing from <%s>', __filename); this.options = options || {}; this.footer = this.options.footer; if (typeof this.footer !== 'string') { this.footer = '(Move up and down to reveal more choices)'; } this.firstRender = true; this.lastIndex = 0; this.position = 0; }
javascript
function Paginator(options) { debug('initializing from <%s>', __filename); this.options = options || {}; this.footer = this.options.footer; if (typeof this.footer !== 'string') { this.footer = '(Move up and down to reveal more choices)'; } this.firstRender = true; this.lastIndex = 0; this.position = 0; }
[ "function", "Paginator", "(", "options", ")", "{", "debug", "(", "'initializing from <%s>'", ",", "__filename", ")", ";", "this", ".", "options", "=", "options", "||", "{", "}", ";", "this", ".", "footer", "=", "this", ".", "options", ".", "footer", ";", "if", "(", "typeof", "this", ".", "footer", "!==", "'string'", ")", "{", "this", ".", "footer", "=", "'(Move up and down to reveal more choices)'", ";", "}", "this", ".", "firstRender", "=", "true", ";", "this", ".", "lastIndex", "=", "0", ";", "this", ".", "position", "=", "0", ";", "}" ]
The paginator keeps track of a position index in a list and returns a subset of the choices if the list is too long.
[ "The", "paginator", "keeps", "track", "of", "a", "position", "index", "in", "a", "list", "and", "returns", "a", "subset", "of", "the", "choices", "if", "the", "list", "is", "too", "long", "." ]
56413bd88a0870ee6c1d6ba897c0fc4111fc9bea
https://github.com/enquirer/terminal-paginator/blob/56413bd88a0870ee6c1d6ba897c0fc4111fc9bea/index.js#L13-L23
39,619
mongodb-js/electron-installer-run
lib/index.js
getBinPath
function getBinPath(cmd, fn) { which(cmd, function(err, bin) { if (err) { return fn(err); } fs.exists(bin, function(exists) { if (!exists) { return fn(new Error(format( 'Expected file for `%s` does not exist at `%s`', cmd, bin))); } fn(null, bin); }); }); }
javascript
function getBinPath(cmd, fn) { which(cmd, function(err, bin) { if (err) { return fn(err); } fs.exists(bin, function(exists) { if (!exists) { return fn(new Error(format( 'Expected file for `%s` does not exist at `%s`', cmd, bin))); } fn(null, bin); }); }); }
[ "function", "getBinPath", "(", "cmd", ",", "fn", ")", "{", "which", "(", "cmd", ",", "function", "(", "err", ",", "bin", ")", "{", "if", "(", "err", ")", "{", "return", "fn", "(", "err", ")", ";", "}", "fs", ".", "exists", "(", "bin", ",", "function", "(", "exists", ")", "{", "if", "(", "!", "exists", ")", "{", "return", "fn", "(", "new", "Error", "(", "format", "(", "'Expected file for `%s` does not exist at `%s`'", ",", "cmd", ",", "bin", ")", ")", ")", ";", "}", "fn", "(", "null", ",", "bin", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Gets the absolute path for a `cmd`. @param {String} cmd - e.g. `codesign`. @param {Function} fn - Callback which receives `(err, binPath)`. @return {void}
[ "Gets", "the", "absolute", "path", "for", "a", "cmd", "." ]
dc47ecac35d5dd945cadb306a6a12975bf2c4ded
https://github.com/mongodb-js/electron-installer-run/blob/dc47ecac35d5dd945cadb306a6a12975bf2c4ded/lib/index.js#L13-L28
39,620
mongodb-js/electron-installer-run
lib/index.js
run
function run(cmd, args, opts, fn) { if (typeof opts === 'function') { fn = opts; opts = {}; } if (typeof args === 'function') { fn = args; args = []; opts = {}; } getBinPath(cmd, function(err, bin) { if (err) { return fn(err); } debug('running', { cmd: cmd, args: args }); var output = []; var proc = spawn(bin, args, opts); proc.stdout.on('data', function(buf) { buf.toString('utf-8').split('\n').map(function(line) { debug(' %s> %s', cmd, line); }); output.push(buf); }); proc.stderr.on('data', function(buf) { buf.toString('utf-8').split('\n').map(function(line) { debug(' %s> %s', cmd, line); }); output.push(buf); }); proc.on('exit', function(code) { if (code !== 0) { debug('command failed!', { cmd: cmd, bin: bin, args: args, opts: opts, code: code, output: Buffer.concat(output).toString('utf-8') }); fn(new Error('Command failed! ' + 'Please try again with debugging enabled.'), Buffer.concat(output).toString('utf-8')); return; } debug('completed! %j', { cmd: cmd, bin: bin, args: args, opts: opts, code: code }); fn(null, Buffer.concat(output).toString('utf-8')); }); }); }
javascript
function run(cmd, args, opts, fn) { if (typeof opts === 'function') { fn = opts; opts = {}; } if (typeof args === 'function') { fn = args; args = []; opts = {}; } getBinPath(cmd, function(err, bin) { if (err) { return fn(err); } debug('running', { cmd: cmd, args: args }); var output = []; var proc = spawn(bin, args, opts); proc.stdout.on('data', function(buf) { buf.toString('utf-8').split('\n').map(function(line) { debug(' %s> %s', cmd, line); }); output.push(buf); }); proc.stderr.on('data', function(buf) { buf.toString('utf-8').split('\n').map(function(line) { debug(' %s> %s', cmd, line); }); output.push(buf); }); proc.on('exit', function(code) { if (code !== 0) { debug('command failed!', { cmd: cmd, bin: bin, args: args, opts: opts, code: code, output: Buffer.concat(output).toString('utf-8') }); fn(new Error('Command failed! ' + 'Please try again with debugging enabled.'), Buffer.concat(output).toString('utf-8')); return; } debug('completed! %j', { cmd: cmd, bin: bin, args: args, opts: opts, code: code }); fn(null, Buffer.concat(output).toString('utf-8')); }); }); }
[ "function", "run", "(", "cmd", ",", "args", ",", "opts", ",", "fn", ")", "{", "if", "(", "typeof", "opts", "===", "'function'", ")", "{", "fn", "=", "opts", ";", "opts", "=", "{", "}", ";", "}", "if", "(", "typeof", "args", "===", "'function'", ")", "{", "fn", "=", "args", ";", "args", "=", "[", "]", ";", "opts", "=", "{", "}", ";", "}", "getBinPath", "(", "cmd", ",", "function", "(", "err", ",", "bin", ")", "{", "if", "(", "err", ")", "{", "return", "fn", "(", "err", ")", ";", "}", "debug", "(", "'running'", ",", "{", "cmd", ":", "cmd", ",", "args", ":", "args", "}", ")", ";", "var", "output", "=", "[", "]", ";", "var", "proc", "=", "spawn", "(", "bin", ",", "args", ",", "opts", ")", ";", "proc", ".", "stdout", ".", "on", "(", "'data'", ",", "function", "(", "buf", ")", "{", "buf", ".", "toString", "(", "'utf-8'", ")", ".", "split", "(", "'\\n'", ")", ".", "map", "(", "function", "(", "line", ")", "{", "debug", "(", "' %s> %s'", ",", "cmd", ",", "line", ")", ";", "}", ")", ";", "output", ".", "push", "(", "buf", ")", ";", "}", ")", ";", "proc", ".", "stderr", ".", "on", "(", "'data'", ",", "function", "(", "buf", ")", "{", "buf", ".", "toString", "(", "'utf-8'", ")", ".", "split", "(", "'\\n'", ")", ".", "map", "(", "function", "(", "line", ")", "{", "debug", "(", "' %s> %s'", ",", "cmd", ",", "line", ")", ";", "}", ")", ";", "output", ".", "push", "(", "buf", ")", ";", "}", ")", ";", "proc", ".", "on", "(", "'exit'", ",", "function", "(", "code", ")", "{", "if", "(", "code", "!==", "0", ")", "{", "debug", "(", "'command failed!'", ",", "{", "cmd", ":", "cmd", ",", "bin", ":", "bin", ",", "args", ":", "args", ",", "opts", ":", "opts", ",", "code", ":", "code", ",", "output", ":", "Buffer", ".", "concat", "(", "output", ")", ".", "toString", "(", "'utf-8'", ")", "}", ")", ";", "fn", "(", "new", "Error", "(", "'Command failed! '", "+", "'Please try again with debugging enabled.'", ")", ",", "Buffer", ".", "concat", "(", "output", ")", ".", "toString", "(", "'utf-8'", ")", ")", ";", "return", ";", "}", "debug", "(", "'completed! %j'", ",", "{", "cmd", ":", "cmd", ",", "bin", ":", "bin", ",", "args", ":", "args", ",", "opts", ":", "opts", ",", "code", ":", "code", "}", ")", ";", "fn", "(", "null", ",", "Buffer", ".", "concat", "(", "output", ")", ".", "toString", "(", "'utf-8'", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Use me when you want to run an external command instead of using `child_process` directly because I'll handle lots of platform edge cases for you and provide nice debugging output when things go wrong! @example var run = require('electron-installer-run'); var args = ['--verify', process.env.APP_PATH]; run('codesign', args, function(err){ if(err){ console.error('codesign verification failed!'); process.exit(1); } console.log('codesign verification succeeded!'); }); @param {String} cmd - The bin name of your command, e.g. `grep`. @param {Array} [args] - Arguments to pass to the command [Default `[]`]. @param {Object} [opts] - Options to pass to `child_process.spawn` [Default `{}`]. @param {Function} fn - Callback which recieves `(err, output)`.
[ "Use", "me", "when", "you", "want", "to", "run", "an", "external", "command", "instead", "of", "using", "child_process", "directly", "because", "I", "ll", "handle", "lots", "of", "platform", "edge", "cases", "for", "you", "and", "provide", "nice", "debugging", "output", "when", "things", "go", "wrong!" ]
dc47ecac35d5dd945cadb306a6a12975bf2c4ded
https://github.com/mongodb-js/electron-installer-run/blob/dc47ecac35d5dd945cadb306a6a12975bf2c4ded/lib/index.js#L52-L114
39,621
balderdashy/mast
newExample/bootstrap.js
bootstrap
function bootstrap(options, cb) { var adapters = options.adapters || {}; var connections = options.connections || {}; var collections = options.collections || {}; Object.keys(adapters).forEach(function(identity) { var def = adapters[identity]; // Make sure our adapter defs have `identity` properties def.identity = def.identity || identity; }); var extendedCollections = []; Object.keys(collections).forEach(function(identity) { var def = collections[identity]; // Make sure our collection defs have `identity` properties def.identity = def.identity || identity; // Fold object of collection definitions into an array // of extended Waterline collections. extendedCollections.push(Waterline.Collection.extend(def)); }); // Instantiate Waterline and load the already-extended // Waterline collections. var waterline = new Waterline(); extendedCollections.forEach(function(collection) { waterline.loadCollection(collection); }); // Initialize Waterline // (and tell it about our adapters) waterline.initialize({ adapters: adapters, connections: connections }, cb); return waterline; }
javascript
function bootstrap(options, cb) { var adapters = options.adapters || {}; var connections = options.connections || {}; var collections = options.collections || {}; Object.keys(adapters).forEach(function(identity) { var def = adapters[identity]; // Make sure our adapter defs have `identity` properties def.identity = def.identity || identity; }); var extendedCollections = []; Object.keys(collections).forEach(function(identity) { var def = collections[identity]; // Make sure our collection defs have `identity` properties def.identity = def.identity || identity; // Fold object of collection definitions into an array // of extended Waterline collections. extendedCollections.push(Waterline.Collection.extend(def)); }); // Instantiate Waterline and load the already-extended // Waterline collections. var waterline = new Waterline(); extendedCollections.forEach(function(collection) { waterline.loadCollection(collection); }); // Initialize Waterline // (and tell it about our adapters) waterline.initialize({ adapters: adapters, connections: connections }, cb); return waterline; }
[ "function", "bootstrap", "(", "options", ",", "cb", ")", "{", "var", "adapters", "=", "options", ".", "adapters", "||", "{", "}", ";", "var", "connections", "=", "options", ".", "connections", "||", "{", "}", ";", "var", "collections", "=", "options", ".", "collections", "||", "{", "}", ";", "Object", ".", "keys", "(", "adapters", ")", ".", "forEach", "(", "function", "(", "identity", ")", "{", "var", "def", "=", "adapters", "[", "identity", "]", ";", "// Make sure our adapter defs have `identity` properties", "def", ".", "identity", "=", "def", ".", "identity", "||", "identity", ";", "}", ")", ";", "var", "extendedCollections", "=", "[", "]", ";", "Object", ".", "keys", "(", "collections", ")", ".", "forEach", "(", "function", "(", "identity", ")", "{", "var", "def", "=", "collections", "[", "identity", "]", ";", "// Make sure our collection defs have `identity` properties", "def", ".", "identity", "=", "def", ".", "identity", "||", "identity", ";", "// Fold object of collection definitions into an array", "// of extended Waterline collections.", "extendedCollections", ".", "push", "(", "Waterline", ".", "Collection", ".", "extend", "(", "def", ")", ")", ";", "}", ")", ";", "// Instantiate Waterline and load the already-extended", "// Waterline collections.", "var", "waterline", "=", "new", "Waterline", "(", ")", ";", "extendedCollections", ".", "forEach", "(", "function", "(", "collection", ")", "{", "waterline", ".", "loadCollection", "(", "collection", ")", ";", "}", ")", ";", "// Initialize Waterline", "// (and tell it about our adapters)", "waterline", ".", "initialize", "(", "{", "adapters", ":", "adapters", ",", "connections", ":", "connections", "}", ",", "cb", ")", ";", "return", "waterline", ";", "}" ]
Simple bootstrap to set up Waterline given some collection, connection, and adapter definitions. @param options :: {Object} adapters [i.e. a dictionary] :: {Object} connections [i.e. a dictionary] :: {Object} collections [i.e. a dictionary] @param {Function} cb () {Error} err () ontology :: {Object} collections :: {Object} connections @return {Waterline}
[ "Simple", "bootstrap", "to", "set", "up", "Waterline", "given", "some", "collection", "connection", "and", "adapter", "definitions", "." ]
6fc2b07849ec6a6fe15f66e456e556e5270ed37f
https://github.com/balderdashy/mast/blob/6fc2b07849ec6a6fe15f66e456e556e5270ed37f/newExample/bootstrap.js#L19-L64
39,622
spyfu/spyfu-vue-factory
dist/spyfu-vue-factory.esm.js
function (name) { return { name: name, component: { render: function render(h) { return h('div'); }, functional: true }, path: '/' + name.replace(/[^\w]/g, "-") }; }
javascript
function (name) { return { name: name, component: { render: function render(h) { return h('div'); }, functional: true }, path: '/' + name.replace(/[^\w]/g, "-") }; }
[ "function", "(", "name", ")", "{", "return", "{", "name", ":", "name", ",", "component", ":", "{", "render", ":", "function", "render", "(", "h", ")", "{", "return", "h", "(", "'div'", ")", ";", "}", ",", "functional", ":", "true", "}", ",", "path", ":", "'/'", "+", "name", ".", "replace", "(", "/", "[^\\w]", "/", "g", ",", "\"-\"", ")", "}", ";", "}" ]
Stub a named route. @param {string} name the name of the route being stubbed @return {Array}
[ "Stub", "a", "named", "route", "." ]
9d0513ecbd7f56ab082ded01bb17a28ac4f72430
https://github.com/spyfu/spyfu-vue-factory/blob/9d0513ecbd7f56ab082ded01bb17a28ac4f72430/dist/spyfu-vue-factory.esm.js#L156-L167
39,623
spyfu/spyfu-vue-factory
dist/spyfu-vue-factory.esm.js
normalizeModules
function normalizeModules(modules) { var normalized = {}; Object.keys(modules).forEach(function (key) { var module = modules[key]; // make sure each vuex module has all keys defined normalized[key] = { actions: module.actions || {}, getters: module.getters || {}, modules: module.modules ? normalizeModules(module.modules) : {}, mutations: module.mutations || {}, namespaced: module.namespaced || false, state: {} }; // make sure our state is a fresh object if (typeof module.state === 'function') { normalized[key].state = module.state(); } else if (_typeof(module.state) === 'object') { normalized[key].state = JSON.parse(JSON.stringify(module.state)); } }); return normalized; }
javascript
function normalizeModules(modules) { var normalized = {}; Object.keys(modules).forEach(function (key) { var module = modules[key]; // make sure each vuex module has all keys defined normalized[key] = { actions: module.actions || {}, getters: module.getters || {}, modules: module.modules ? normalizeModules(module.modules) : {}, mutations: module.mutations || {}, namespaced: module.namespaced || false, state: {} }; // make sure our state is a fresh object if (typeof module.state === 'function') { normalized[key].state = module.state(); } else if (_typeof(module.state) === 'object') { normalized[key].state = JSON.parse(JSON.stringify(module.state)); } }); return normalized; }
[ "function", "normalizeModules", "(", "modules", ")", "{", "var", "normalized", "=", "{", "}", ";", "Object", ".", "keys", "(", "modules", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "var", "module", "=", "modules", "[", "key", "]", ";", "// make sure each vuex module has all keys defined", "normalized", "[", "key", "]", "=", "{", "actions", ":", "module", ".", "actions", "||", "{", "}", ",", "getters", ":", "module", ".", "getters", "||", "{", "}", ",", "modules", ":", "module", ".", "modules", "?", "normalizeModules", "(", "module", ".", "modules", ")", ":", "{", "}", ",", "mutations", ":", "module", ".", "mutations", "||", "{", "}", ",", "namespaced", ":", "module", ".", "namespaced", "||", "false", ",", "state", ":", "{", "}", "}", ";", "// make sure our state is a fresh object", "if", "(", "typeof", "module", ".", "state", "===", "'function'", ")", "{", "normalized", "[", "key", "]", ".", "state", "=", "module", ".", "state", "(", ")", ";", "}", "else", "if", "(", "_typeof", "(", "module", ".", "state", ")", "===", "'object'", ")", "{", "normalized", "[", "key", "]", ".", "state", "=", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "module", ".", "state", ")", ")", ";", "}", "}", ")", ";", "return", "normalized", ";", "}" ]
helper function to evaluate the state functions of vuex modules
[ "helper", "function", "to", "evaluate", "the", "state", "functions", "of", "vuex", "modules" ]
9d0513ecbd7f56ab082ded01bb17a28ac4f72430
https://github.com/spyfu/spyfu-vue-factory/blob/9d0513ecbd7f56ab082ded01bb17a28ac4f72430/dist/spyfu-vue-factory.esm.js#L289-L314
39,624
spyfu/spyfu-vue-factory
dist/spyfu-vue-factory.esm.js
findModule
function findModule(store, namespace) { return namespace.split('/').reduce(function (obj, key) { // root modules will exist directly on the store if (obj && obj[key]) { return obj[key]; } // child stores will exist in a modules object if (obj && obj.modules && obj.modules[key]) { return obj.modules[key]; } // if we couldn't find the module, throw an error // istanbul ignore next throw new Error('Could not find module "' + namespace + '" in store.'); }, store); }
javascript
function findModule(store, namespace) { return namespace.split('/').reduce(function (obj, key) { // root modules will exist directly on the store if (obj && obj[key]) { return obj[key]; } // child stores will exist in a modules object if (obj && obj.modules && obj.modules[key]) { return obj.modules[key]; } // if we couldn't find the module, throw an error // istanbul ignore next throw new Error('Could not find module "' + namespace + '" in store.'); }, store); }
[ "function", "findModule", "(", "store", ",", "namespace", ")", "{", "return", "namespace", ".", "split", "(", "'/'", ")", ".", "reduce", "(", "function", "(", "obj", ",", "key", ")", "{", "// root modules will exist directly on the store", "if", "(", "obj", "&&", "obj", "[", "key", "]", ")", "{", "return", "obj", "[", "key", "]", ";", "}", "// child stores will exist in a modules object", "if", "(", "obj", "&&", "obj", ".", "modules", "&&", "obj", ".", "modules", "[", "key", "]", ")", "{", "return", "obj", ".", "modules", "[", "key", "]", ";", "}", "// if we couldn't find the module, throw an error", "// istanbul ignore next", "throw", "new", "Error", "(", "'Could not find module \"'", "+", "namespace", "+", "'\" in store.'", ")", ";", "}", ",", "store", ")", ";", "}" ]
helper to find vuex modules via their namespace
[ "helper", "to", "find", "vuex", "modules", "via", "their", "namespace" ]
9d0513ecbd7f56ab082ded01bb17a28ac4f72430
https://github.com/spyfu/spyfu-vue-factory/blob/9d0513ecbd7f56ab082ded01bb17a28ac4f72430/dist/spyfu-vue-factory.esm.js#L317-L333
39,625
express-bem/express-bem
lib/view-lookup.js
patchView
function patchView (ExpressView, opts) { var proto = ExpressView.prototype; function View (name, options) { options = options || {}; this.name = name; this.root = options.root; var engines = options.engines; this.defaultEngine = options.defaultEngine; var extensions = (typeof opts.extensions === 'function') ? opts.extensions() : opts.extensions; this.extensions = extensions; var ext = this.ext = extname(name, extensions); if (!ext && !this.defaultEngine) { throw Error('No default engine was specified and no extension was provided.'); } if (!ext) { name += (ext = this.ext = (this.defaultEngine[0] !== '.' ? '.' : '') + this.defaultEngine); } this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express); this.path = this.lookup(name); } View.prototype = proto; function extname (name, extensions) { if (Array.isArray(extensions) && extensions.length > 0) { var ext; for (var i = 0, l = extensions.length; i < l; i += 1) { ext = extensions[i]; if (typeof name === 'string' && name.indexOf(ext) !== -1) { return ext; } } } return PATH.extname(name); } // replace original with new our own proto.lookup = createLookup(proto.lookup, opts); return View; }
javascript
function patchView (ExpressView, opts) { var proto = ExpressView.prototype; function View (name, options) { options = options || {}; this.name = name; this.root = options.root; var engines = options.engines; this.defaultEngine = options.defaultEngine; var extensions = (typeof opts.extensions === 'function') ? opts.extensions() : opts.extensions; this.extensions = extensions; var ext = this.ext = extname(name, extensions); if (!ext && !this.defaultEngine) { throw Error('No default engine was specified and no extension was provided.'); } if (!ext) { name += (ext = this.ext = (this.defaultEngine[0] !== '.' ? '.' : '') + this.defaultEngine); } this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express); this.path = this.lookup(name); } View.prototype = proto; function extname (name, extensions) { if (Array.isArray(extensions) && extensions.length > 0) { var ext; for (var i = 0, l = extensions.length; i < l; i += 1) { ext = extensions[i]; if (typeof name === 'string' && name.indexOf(ext) !== -1) { return ext; } } } return PATH.extname(name); } // replace original with new our own proto.lookup = createLookup(proto.lookup, opts); return View; }
[ "function", "patchView", "(", "ExpressView", ",", "opts", ")", "{", "var", "proto", "=", "ExpressView", ".", "prototype", ";", "function", "View", "(", "name", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "name", "=", "name", ";", "this", ".", "root", "=", "options", ".", "root", ";", "var", "engines", "=", "options", ".", "engines", ";", "this", ".", "defaultEngine", "=", "options", ".", "defaultEngine", ";", "var", "extensions", "=", "(", "typeof", "opts", ".", "extensions", "===", "'function'", ")", "?", "opts", ".", "extensions", "(", ")", ":", "opts", ".", "extensions", ";", "this", ".", "extensions", "=", "extensions", ";", "var", "ext", "=", "this", ".", "ext", "=", "extname", "(", "name", ",", "extensions", ")", ";", "if", "(", "!", "ext", "&&", "!", "this", ".", "defaultEngine", ")", "{", "throw", "Error", "(", "'No default engine was specified and no extension was provided.'", ")", ";", "}", "if", "(", "!", "ext", ")", "{", "name", "+=", "(", "ext", "=", "this", ".", "ext", "=", "(", "this", ".", "defaultEngine", "[", "0", "]", "!==", "'.'", "?", "'.'", ":", "''", ")", "+", "this", ".", "defaultEngine", ")", ";", "}", "this", ".", "engine", "=", "engines", "[", "ext", "]", "||", "(", "engines", "[", "ext", "]", "=", "require", "(", "ext", ".", "slice", "(", "1", ")", ")", ".", "__express", ")", ";", "this", ".", "path", "=", "this", ".", "lookup", "(", "name", ")", ";", "}", "View", ".", "prototype", "=", "proto", ";", "function", "extname", "(", "name", ",", "extensions", ")", "{", "if", "(", "Array", ".", "isArray", "(", "extensions", ")", "&&", "extensions", ".", "length", ">", "0", ")", "{", "var", "ext", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "extensions", ".", "length", ";", "i", "<", "l", ";", "i", "+=", "1", ")", "{", "ext", "=", "extensions", "[", "i", "]", ";", "if", "(", "typeof", "name", "===", "'string'", "&&", "name", ".", "indexOf", "(", "ext", ")", "!==", "-", "1", ")", "{", "return", "ext", ";", "}", "}", "}", "return", "PATH", ".", "extname", "(", "name", ")", ";", "}", "// replace original with new our own", "proto", ".", "lookup", "=", "createLookup", "(", "proto", ".", "lookup", ",", "opts", ")", ";", "return", "View", ";", "}" ]
Patches express view to lookup in another directories @api @param {Function} ExpressView @param {{path: String, extensions: String[]|Function}} opts
[ "Patches", "express", "view", "to", "lookup", "in", "another", "directories" ]
6ea49e5ecdd8e949dd5051ecc5762e40cbcead9c
https://github.com/express-bem/express-bem/blob/6ea49e5ecdd8e949dd5051ecc5762e40cbcead9c/lib/view-lookup.js#L20-L59
39,626
ofzza/enTT
dist/ext/validation.js
ValidationExtension
function ValidationExtension() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$reject = _ref.reject, reject = _ref$reject === undefined ? false : _ref$reject; _classCallCheck(this, ValidationExtension); // Store configuration var _this = _possibleConstructorReturn(this, (ValidationExtension.__proto__ || Object.getPrototypeOf(ValidationExtension)).call(this, { onEntityInstantiate: true, onChangeDetected: true })); _this.rejectInvalidValues = reject; return _this; }
javascript
function ValidationExtension() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$reject = _ref.reject, reject = _ref$reject === undefined ? false : _ref$reject; _classCallCheck(this, ValidationExtension); // Store configuration var _this = _possibleConstructorReturn(this, (ValidationExtension.__proto__ || Object.getPrototypeOf(ValidationExtension)).call(this, { onEntityInstantiate: true, onChangeDetected: true })); _this.rejectInvalidValues = reject; return _this; }
[ "function", "ValidationExtension", "(", ")", "{", "var", "_ref", "=", "arguments", ".", "length", ">", "0", "&&", "arguments", "[", "0", "]", "!==", "undefined", "?", "arguments", "[", "0", "]", ":", "{", "}", ",", "_ref$reject", "=", "_ref", ".", "reject", ",", "reject", "=", "_ref$reject", "===", "undefined", "?", "false", ":", "_ref$reject", ";", "_classCallCheck", "(", "this", ",", "ValidationExtension", ")", ";", "// Store configuration", "var", "_this", "=", "_possibleConstructorReturn", "(", "this", ",", "(", "ValidationExtension", ".", "__proto__", "||", "Object", ".", "getPrototypeOf", "(", "ValidationExtension", ")", ")", ".", "call", "(", "this", ",", "{", "onEntityInstantiate", ":", "true", ",", "onChangeDetected", ":", "true", "}", ")", ")", ";", "_this", ".", "rejectInvalidValues", "=", "reject", ";", "return", "_this", ";", "}" ]
Creates an instance of ValidationExtension. @param {bool} reject If true, invalid values won't be assigned to the property @memberof ValidationExtension
[ "Creates", "an", "instance", "of", "ValidationExtension", "." ]
fdf27de4142b3c65a3e51dee70e0d7625dff897c
https://github.com/ofzza/enTT/blob/fdf27de4142b3c65a3e51dee70e0d7625dff897c/dist/ext/validation.js#L48-L63
39,627
ofzza/enTT
dist/ext/validation.js
validateProperties
function validateProperties(entity, properties, changedPropertyName, changedPropertyValue, currentPropertyValue) { var _this2 = this; // Validate default property values _lodash2.default.forEach(properties, function (propertyConfiguration, propertyName) { if (isValidationProperty(propertyConfiguration)) { // Run validation function var validatedValue = propertyName !== changedPropertyName ? entity[propertyName] : changedPropertyValue, resetValue = propertyName !== changedPropertyName ? null : currentPropertyValue, validation = propertyConfiguration.validate(validatedValue, entity); // Check if validation successful if (validation === undefined) { // Reset validation error delete entity.validation[propertyName]; } else { // Store validation error entity.validation[propertyName] = new ValidationOutput({ property: propertyName, value: validatedValue, message: validation }); // If rejecting invalid values, reset value to current value if (_this2.rejectInvalidValues) { // Unset default value (wrap into EnTTBypassEverythingValue to bypass validation and watchers) entity[propertyName] = new _properties.EnTTBypassEverythingValue(resetValue); } } } }); }
javascript
function validateProperties(entity, properties, changedPropertyName, changedPropertyValue, currentPropertyValue) { var _this2 = this; // Validate default property values _lodash2.default.forEach(properties, function (propertyConfiguration, propertyName) { if (isValidationProperty(propertyConfiguration)) { // Run validation function var validatedValue = propertyName !== changedPropertyName ? entity[propertyName] : changedPropertyValue, resetValue = propertyName !== changedPropertyName ? null : currentPropertyValue, validation = propertyConfiguration.validate(validatedValue, entity); // Check if validation successful if (validation === undefined) { // Reset validation error delete entity.validation[propertyName]; } else { // Store validation error entity.validation[propertyName] = new ValidationOutput({ property: propertyName, value: validatedValue, message: validation }); // If rejecting invalid values, reset value to current value if (_this2.rejectInvalidValues) { // Unset default value (wrap into EnTTBypassEverythingValue to bypass validation and watchers) entity[propertyName] = new _properties.EnTTBypassEverythingValue(resetValue); } } } }); }
[ "function", "validateProperties", "(", "entity", ",", "properties", ",", "changedPropertyName", ",", "changedPropertyValue", ",", "currentPropertyValue", ")", "{", "var", "_this2", "=", "this", ";", "// Validate default property values", "_lodash2", ".", "default", ".", "forEach", "(", "properties", ",", "function", "(", "propertyConfiguration", ",", "propertyName", ")", "{", "if", "(", "isValidationProperty", "(", "propertyConfiguration", ")", ")", "{", "// Run validation function", "var", "validatedValue", "=", "propertyName", "!==", "changedPropertyName", "?", "entity", "[", "propertyName", "]", ":", "changedPropertyValue", ",", "resetValue", "=", "propertyName", "!==", "changedPropertyName", "?", "null", ":", "currentPropertyValue", ",", "validation", "=", "propertyConfiguration", ".", "validate", "(", "validatedValue", ",", "entity", ")", ";", "// Check if validation successful", "if", "(", "validation", "===", "undefined", ")", "{", "// Reset validation error", "delete", "entity", ".", "validation", "[", "propertyName", "]", ";", "}", "else", "{", "// Store validation error", "entity", ".", "validation", "[", "propertyName", "]", "=", "new", "ValidationOutput", "(", "{", "property", ":", "propertyName", ",", "value", ":", "validatedValue", ",", "message", ":", "validation", "}", ")", ";", "// If rejecting invalid values, reset value to current value", "if", "(", "_this2", ".", "rejectInvalidValues", ")", "{", "// Unset default value (wrap into EnTTBypassEverythingValue to bypass validation and watchers)", "entity", "[", "propertyName", "]", "=", "new", "_properties", ".", "EnTTBypassEverythingValue", "(", "resetValue", ")", ";", "}", "}", "}", "}", ")", ";", "}" ]
Performs property validation and outputs results to errors object @param {any} entity Entity instance @param {any} properties Entity's properties' configuration @param {any} changedPropertyName Name of the property being validated @param {any} changedPropertyValue Value being validated @param {any} currentPropertyValue Current property value
[ "Performs", "property", "validation", "and", "outputs", "results", "to", "errors", "object" ]
fdf27de4142b3c65a3e51dee70e0d7625dff897c
https://github.com/ofzza/enTT/blob/fdf27de4142b3c65a3e51dee70e0d7625dff897c/dist/ext/validation.js#L136-L165
39,628
mongodb-js/precommit
index.js
resolve
function resolve(opts, done) { debug('resolving paths for globs:\n', JSON.stringify(opts.globs)); var tasks = opts.globs.map(function(pattern) { return function(cb) { debug('resolving `%s`...', pattern); glob(pattern, {}, function(err, files) { if (err) { return cb(err); } debug('resolved %d file(s) for `%s`', files.length, pattern); if (files.length > 0) { opts.files.push.apply(opts.files, files); } cb(); }); }; }); async.parallel(tasks, function(err) { if (err) { return done(err); } debug('checking and removing duplicate paths...'); opts.files = unique(opts.files); debug('final result has `%d` files', opts.files.length); done(null, opts.files); }); }
javascript
function resolve(opts, done) { debug('resolving paths for globs:\n', JSON.stringify(opts.globs)); var tasks = opts.globs.map(function(pattern) { return function(cb) { debug('resolving `%s`...', pattern); glob(pattern, {}, function(err, files) { if (err) { return cb(err); } debug('resolved %d file(s) for `%s`', files.length, pattern); if (files.length > 0) { opts.files.push.apply(opts.files, files); } cb(); }); }; }); async.parallel(tasks, function(err) { if (err) { return done(err); } debug('checking and removing duplicate paths...'); opts.files = unique(opts.files); debug('final result has `%d` files', opts.files.length); done(null, opts.files); }); }
[ "function", "resolve", "(", "opts", ",", "done", ")", "{", "debug", "(", "'resolving paths for globs:\\n'", ",", "JSON", ".", "stringify", "(", "opts", ".", "globs", ")", ")", ";", "var", "tasks", "=", "opts", ".", "globs", ".", "map", "(", "function", "(", "pattern", ")", "{", "return", "function", "(", "cb", ")", "{", "debug", "(", "'resolving `%s`...'", ",", "pattern", ")", ";", "glob", "(", "pattern", ",", "{", "}", ",", "function", "(", "err", ",", "files", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "debug", "(", "'resolved %d file(s) for `%s`'", ",", "files", ".", "length", ",", "pattern", ")", ";", "if", "(", "files", ".", "length", ">", "0", ")", "{", "opts", ".", "files", ".", "push", ".", "apply", "(", "opts", ".", "files", ",", "files", ")", ";", "}", "cb", "(", ")", ";", "}", ")", ";", "}", ";", "}", ")", ";", "async", ".", "parallel", "(", "tasks", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "done", "(", "err", ")", ";", "}", "debug", "(", "'checking and removing duplicate paths...'", ")", ";", "opts", ".", "files", "=", "unique", "(", "opts", ".", "files", ")", ";", "debug", "(", "'final result has `%d` files'", ",", "opts", ".", "files", ".", "length", ")", ";", "done", "(", "null", ",", "opts", ".", "files", ")", ";", "}", ")", ";", "}" ]
Expand globs into paths. @param {Object} opts @param {Function} done
[ "Expand", "globs", "into", "paths", "." ]
28d7d6a972b57ce364aed6f21ba5d328199befff
https://github.com/mongodb-js/precommit/blob/28d7d6a972b57ce364aed6f21ba5d328199befff/index.js#L21-L47
39,629
onechiporenko/eslint-plugin-ember-cleanup
lib/utils/node.js
getPropertyNamesInParentObjectExpression
function getPropertyNamesInParentObjectExpression(node) { var objectExpression = obj.get(node, "parent.parent"); var ret = []; if (!objectExpression) { return ret; } objectExpression.properties.forEach(function (p) { if (p.value !== node) { ret.push(p.key.name); } }); return ret; }
javascript
function getPropertyNamesInParentObjectExpression(node) { var objectExpression = obj.get(node, "parent.parent"); var ret = []; if (!objectExpression) { return ret; } objectExpression.properties.forEach(function (p) { if (p.value !== node) { ret.push(p.key.name); } }); return ret; }
[ "function", "getPropertyNamesInParentObjectExpression", "(", "node", ")", "{", "var", "objectExpression", "=", "obj", ".", "get", "(", "node", ",", "\"parent.parent\"", ")", ";", "var", "ret", "=", "[", "]", ";", "if", "(", "!", "objectExpression", ")", "{", "return", "ret", ";", "}", "objectExpression", ".", "properties", ".", "forEach", "(", "function", "(", "p", ")", "{", "if", "(", "p", ".", "value", "!==", "node", ")", "{", "ret", ".", "push", "(", "p", ".", "key", ".", "name", ")", ";", "}", "}", ")", ";", "return", "ret", ";", "}" ]
Get list of all properties in the Object Expression node Object - is a "grand parent" for the provided node Result doesn't contain name of the `node` property @param {ASTNode} node @returns {string[]}
[ "Get", "list", "of", "all", "properties", "in", "the", "Object", "Expression", "node", "Object", "-", "is", "a", "grand", "parent", "for", "the", "provided", "node", "Result", "doesn", "t", "contain", "name", "of", "the", "node", "property" ]
83618c6ba242d6349f4d724d793bb6e05f057b88
https://github.com/onechiporenko/eslint-plugin-ember-cleanup/blob/83618c6ba242d6349f4d724d793bb6e05f057b88/lib/utils/node.js#L49-L61
39,630
yoshuawuyts/wayfarer-to-server
index.js
toServer
function toServer (router) { assert.equal(typeof router, 'function') const syms = getOwnSymbols(router) const sym = syms.length ? syms[0] : router._sym assert.ok(sym, 'router should be an instance of wayfarer') emit._subrouters = router._subrouters emit._routes = router._routes emit[sym] = true emit.emit = emit emit.on = on return emit // match a route and execute the corresponding callback // (obj, obj) -> null // original: {path, params parentDefault} function emit (route, req, res) { assert.equal(typeof route, 'string') assert.ok(req, 'no req specified') if (!req._ssa) { assert.ok(res, 'no res specified') } // handle server init if (isReq(req) && isRes(res)) { const ssa = createSsa({}, req, res) const dft = { node: { cb: [ router._default ] } } return router(route, ssa, dft) } // handle subrouter const params = req const parentDefault = res router(route, params, parentDefault) } // register a new route on a method // (str, obj) -> obj function on (route, methods) { assert.equal(typeof route, 'string') methods = methods || {} // mount subrouter if (methods[sym]) return router.on(route, methods) assert.equal(typeof methods, 'object') // mount http methods router.on(route, function (args) { demuxSsa(args, function (req, res, params) { const meth = methodist(req, defaultFn, methods) meth(req, res, params) // default function to call if methods don't match // null -> null function defaultFn () { router._default(args) } }) }) return emit } }
javascript
function toServer (router) { assert.equal(typeof router, 'function') const syms = getOwnSymbols(router) const sym = syms.length ? syms[0] : router._sym assert.ok(sym, 'router should be an instance of wayfarer') emit._subrouters = router._subrouters emit._routes = router._routes emit[sym] = true emit.emit = emit emit.on = on return emit // match a route and execute the corresponding callback // (obj, obj) -> null // original: {path, params parentDefault} function emit (route, req, res) { assert.equal(typeof route, 'string') assert.ok(req, 'no req specified') if (!req._ssa) { assert.ok(res, 'no res specified') } // handle server init if (isReq(req) && isRes(res)) { const ssa = createSsa({}, req, res) const dft = { node: { cb: [ router._default ] } } return router(route, ssa, dft) } // handle subrouter const params = req const parentDefault = res router(route, params, parentDefault) } // register a new route on a method // (str, obj) -> obj function on (route, methods) { assert.equal(typeof route, 'string') methods = methods || {} // mount subrouter if (methods[sym]) return router.on(route, methods) assert.equal(typeof methods, 'object') // mount http methods router.on(route, function (args) { demuxSsa(args, function (req, res, params) { const meth = methodist(req, defaultFn, methods) meth(req, res, params) // default function to call if methods don't match // null -> null function defaultFn () { router._default(args) } }) }) return emit } }
[ "function", "toServer", "(", "router", ")", "{", "assert", ".", "equal", "(", "typeof", "router", ",", "'function'", ")", "const", "syms", "=", "getOwnSymbols", "(", "router", ")", "const", "sym", "=", "syms", ".", "length", "?", "syms", "[", "0", "]", ":", "router", ".", "_sym", "assert", ".", "ok", "(", "sym", ",", "'router should be an instance of wayfarer'", ")", "emit", ".", "_subrouters", "=", "router", ".", "_subrouters", "emit", ".", "_routes", "=", "router", ".", "_routes", "emit", "[", "sym", "]", "=", "true", "emit", ".", "emit", "=", "emit", "emit", ".", "on", "=", "on", "return", "emit", "// match a route and execute the corresponding callback", "// (obj, obj) -> null", "// original: {path, params parentDefault}", "function", "emit", "(", "route", ",", "req", ",", "res", ")", "{", "assert", ".", "equal", "(", "typeof", "route", ",", "'string'", ")", "assert", ".", "ok", "(", "req", ",", "'no req specified'", ")", "if", "(", "!", "req", ".", "_ssa", ")", "{", "assert", ".", "ok", "(", "res", ",", "'no res specified'", ")", "}", "// handle server init", "if", "(", "isReq", "(", "req", ")", "&&", "isRes", "(", "res", ")", ")", "{", "const", "ssa", "=", "createSsa", "(", "{", "}", ",", "req", ",", "res", ")", "const", "dft", "=", "{", "node", ":", "{", "cb", ":", "[", "router", ".", "_default", "]", "}", "}", "return", "router", "(", "route", ",", "ssa", ",", "dft", ")", "}", "// handle subrouter", "const", "params", "=", "req", "const", "parentDefault", "=", "res", "router", "(", "route", ",", "params", ",", "parentDefault", ")", "}", "// register a new route on a method", "// (str, obj) -> obj", "function", "on", "(", "route", ",", "methods", ")", "{", "assert", ".", "equal", "(", "typeof", "route", ",", "'string'", ")", "methods", "=", "methods", "||", "{", "}", "// mount subrouter", "if", "(", "methods", "[", "sym", "]", ")", "return", "router", ".", "on", "(", "route", ",", "methods", ")", "assert", ".", "equal", "(", "typeof", "methods", ",", "'object'", ")", "// mount http methods", "router", ".", "on", "(", "route", ",", "function", "(", "args", ")", "{", "demuxSsa", "(", "args", ",", "function", "(", "req", ",", "res", ",", "params", ")", "{", "const", "meth", "=", "methodist", "(", "req", ",", "defaultFn", ",", "methods", ")", "meth", "(", "req", ",", "res", ",", "params", ")", "// default function to call if methods don't match", "// null -> null", "function", "defaultFn", "(", ")", "{", "router", ".", "_default", "(", "args", ")", "}", "}", ")", "}", ")", "return", "emit", "}", "}" ]
wrap req, res, wayfarer to create new server obj -> obj
[ "wrap", "req", "res", "wayfarer", "to", "create", "new", "server", "obj", "-", ">", "obj" ]
55df6e33111753e952b9655ac9ec8d38ad41c698
https://github.com/yoshuawuyts/wayfarer-to-server/blob/55df6e33111753e952b9655ac9ec8d38ad41c698/index.js#L12-L77
39,631
ply-ct/ply
lib/retrieval.js
function(location, name) { this.location = location; this.name = name; if (this.isUrl(location)) { if (this.name) this.name = require('sanitize-filename')(this.name, {replacement: '_'}); if (typeof window === 'undefined') this.request = require('request').defaults({headers: {'User-Agent': 'limberest'}}); else this.request = require('browser-request'); } else { this.storage = new Storage(this.location, this.name); } this.path = this.location; if (this.name) this.path += '/' + this.name; }
javascript
function(location, name) { this.location = location; this.name = name; if (this.isUrl(location)) { if (this.name) this.name = require('sanitize-filename')(this.name, {replacement: '_'}); if (typeof window === 'undefined') this.request = require('request').defaults({headers: {'User-Agent': 'limberest'}}); else this.request = require('browser-request'); } else { this.storage = new Storage(this.location, this.name); } this.path = this.location; if (this.name) this.path += '/' + this.name; }
[ "function", "(", "location", ",", "name", ")", "{", "this", ".", "location", "=", "location", ";", "this", ".", "name", "=", "name", ";", "if", "(", "this", ".", "isUrl", "(", "location", ")", ")", "{", "if", "(", "this", ".", "name", ")", "this", ".", "name", "=", "require", "(", "'sanitize-filename'", ")", "(", "this", ".", "name", ",", "{", "replacement", ":", "'_'", "}", ")", ";", "if", "(", "typeof", "window", "===", "'undefined'", ")", "this", ".", "request", "=", "require", "(", "'request'", ")", ".", "defaults", "(", "{", "headers", ":", "{", "'User-Agent'", ":", "'limberest'", "}", "}", ")", ";", "else", "this", ".", "request", "=", "require", "(", "'browser-request'", ")", ";", "}", "else", "{", "this", ".", "storage", "=", "new", "Storage", "(", "this", ".", "location", ",", "this", ".", "name", ")", ";", "}", "this", ".", "path", "=", "this", ".", "location", ";", "if", "(", "this", ".", "name", ")", "this", ".", "path", "+=", "'/'", "+", "this", ".", "name", ";", "}" ]
Abstraction that uses either URL retrieval or storage. name is optional
[ "Abstraction", "that", "uses", "either", "URL", "retrieval", "or", "storage", ".", "name", "is", "optional" ]
1d4146829845fedd917f5f0626cd74cc3845d0c8
https://github.com/ply-ct/ply/blob/1d4146829845fedd917f5f0626cd74cc3845d0c8/lib/retrieval.js#L8-L28
39,632
janus-toendering/options-parser
src/parser.js
function(opts, argv, error) { var parser = new Parser(opts, argv, error); return parser.parse(); }
javascript
function(opts, argv, error) { var parser = new Parser(opts, argv, error); return parser.parse(); }
[ "function", "(", "opts", ",", "argv", ",", "error", ")", "{", "var", "parser", "=", "new", "Parser", "(", "opts", ",", "argv", ",", "error", ")", ";", "return", "parser", ".", "parse", "(", ")", ";", "}" ]
Parses command-line arguments @param {object} opts @param {Array} argv argument array @param {Function} error callback handler for missing options etc (default: throw exception) @returns {{opt: {}, args: Array}}
[ "Parses", "command", "-", "line", "arguments" ]
f1e39aac203f26e7e4e67fadba63c8dce1c7d70e
https://github.com/janus-toendering/options-parser/blob/f1e39aac203f26e7e4e67fadba63c8dce1c7d70e/src/parser.js#L195-L199
39,633
cflynn07/power-radix
lib/index.js
PowerRadix
function PowerRadix (digits, sourceRadix) { sourceRadix = Array.isArray(sourceRadix) ? sourceRadix : B62.slice(0, sourceRadix); this._digits = Array.isArray(digits) ? digits : (digits+'').split(''); this._sourceRadixLength = new BigInt(sourceRadix.length+''); this._sourceRadixMap = sourceRadix.reduce(function (map, char, i) { map[char+''] = new BigInt(i+''); return map; }, {}); }
javascript
function PowerRadix (digits, sourceRadix) { sourceRadix = Array.isArray(sourceRadix) ? sourceRadix : B62.slice(0, sourceRadix); this._digits = Array.isArray(digits) ? digits : (digits+'').split(''); this._sourceRadixLength = new BigInt(sourceRadix.length+''); this._sourceRadixMap = sourceRadix.reduce(function (map, char, i) { map[char+''] = new BigInt(i+''); return map; }, {}); }
[ "function", "PowerRadix", "(", "digits", ",", "sourceRadix", ")", "{", "sourceRadix", "=", "Array", ".", "isArray", "(", "sourceRadix", ")", "?", "sourceRadix", ":", "B62", ".", "slice", "(", "0", ",", "sourceRadix", ")", ";", "this", ".", "_digits", "=", "Array", ".", "isArray", "(", "digits", ")", "?", "digits", ":", "(", "digits", "+", "''", ")", ".", "split", "(", "''", ")", ";", "this", ".", "_sourceRadixLength", "=", "new", "BigInt", "(", "sourceRadix", ".", "length", "+", "''", ")", ";", "this", ".", "_sourceRadixMap", "=", "sourceRadix", ".", "reduce", "(", "function", "(", "map", ",", "char", ",", "i", ")", "{", "map", "[", "char", "+", "''", "]", "=", "new", "BigInt", "(", "i", "+", "''", ")", ";", "return", "map", ";", "}", ",", "{", "}", ")", ";", "}" ]
Creates a new instance of PowerRadix @class @throws {InvalidArgumentException} @param {Array|String} digits @param {Array|Number} sourceRadix
[ "Creates", "a", "new", "instance", "of", "PowerRadix" ]
90a800fce273a8281ba3c784bde026826aab29ce
https://github.com/cflynn07/power-radix/blob/90a800fce273a8281ba3c784bde026826aab29ce/lib/index.js#L31-L39
39,634
quase/quasejs
.pnp.js
makeError
function makeError(code, message, data = {}) { const error = new Error(message); return Object.assign(error, {code, data}); }
javascript
function makeError(code, message, data = {}) { const error = new Error(message); return Object.assign(error, {code, data}); }
[ "function", "makeError", "(", "code", ",", "message", ",", "data", "=", "{", "}", ")", "{", "const", "error", "=", "new", "Error", "(", "message", ")", ";", "return", "Object", ".", "assign", "(", "error", ",", "{", "code", ",", "data", "}", ")", ";", "}" ]
Simple helper function that assign an error code to an error, so that it can more easily be caught and used by third-parties.
[ "Simple", "helper", "function", "that", "assign", "an", "error", "code", "to", "an", "error", "so", "that", "it", "can", "more", "easily", "be", "caught", "and", "used", "by", "third", "-", "parties", "." ]
a8f46d6648db13abf30bbb4800fe63b25e49e1b3
https://github.com/quase/quasejs/blob/a8f46d6648db13abf30bbb4800fe63b25e49e1b3/.pnp.js#L54-L57
39,635
quase/quasejs
.pnp.js
getIssuerModule
function getIssuerModule(parent) { let issuer = parent; while (issuer && (issuer.id === '[eval]' || issuer.id === '<repl>' || !issuer.filename)) { issuer = issuer.parent; } return issuer; }
javascript
function getIssuerModule(parent) { let issuer = parent; while (issuer && (issuer.id === '[eval]' || issuer.id === '<repl>' || !issuer.filename)) { issuer = issuer.parent; } return issuer; }
[ "function", "getIssuerModule", "(", "parent", ")", "{", "let", "issuer", "=", "parent", ";", "while", "(", "issuer", "&&", "(", "issuer", ".", "id", "===", "'[eval]'", "||", "issuer", ".", "id", "===", "'<repl>'", "||", "!", "issuer", ".", "filename", ")", ")", "{", "issuer", "=", "issuer", ".", "parent", ";", "}", "return", "issuer", ";", "}" ]
Returns the module that should be used to resolve require calls. It's usually the direct parent, except if we're inside an eval expression.
[ "Returns", "the", "module", "that", "should", "be", "used", "to", "resolve", "require", "calls", ".", "It", "s", "usually", "the", "direct", "parent", "except", "if", "we", "re", "inside", "an", "eval", "expression", "." ]
a8f46d6648db13abf30bbb4800fe63b25e49e1b3
https://github.com/quase/quasejs/blob/a8f46d6648db13abf30bbb4800fe63b25e49e1b3/.pnp.js#L12567-L12575
39,636
quase/quasejs
.pnp.js
applyNodeExtensionResolution
function applyNodeExtensionResolution(unqualifiedPath, {extensions}) { // We use this "infinite while" so that we can restart the process as long as we hit package folders while (true) { let stat; try { stat = statSync(unqualifiedPath); } catch (error) {} // If the file exists and is a file, we can stop right there if (stat && !stat.isDirectory()) { // If the very last component of the resolved path is a symlink to a file, we then resolve it to a file. We only // do this first the last component, and not the rest of the path! This allows us to support the case of bin // symlinks, where a symlink in "/xyz/pkg-name/.bin/bin-name" will point somewhere else (like "/xyz/pkg-name/index.js"). // In such a case, we want relative requires to be resolved relative to "/xyz/pkg-name/" rather than "/xyz/pkg-name/.bin/". // // Also note that the reason we must use readlink on the last component (instead of realpath on the whole path) // is that we must preserve the other symlinks, in particular those used by pnp to deambiguate packages using // peer dependencies. For example, "/xyz/.pnp/local/pnp-01234569/.bin/bin-name" should see its relative requires // be resolved relative to "/xyz/.pnp/local/pnp-0123456789/" rather than "/xyz/pkg-with-peers/", because otherwise // we would lose the information that would tell us what are the dependencies of pkg-with-peers relative to its // ancestors. if (lstatSync(unqualifiedPath).isSymbolicLink()) { unqualifiedPath = path.normalize(path.resolve(path.dirname(unqualifiedPath), readlinkSync(unqualifiedPath))); } return unqualifiedPath; } // If the file is a directory, we must check if it contains a package.json with a "main" entry if (stat && stat.isDirectory()) { let pkgJson; try { pkgJson = JSON.parse(readFileSync(`${unqualifiedPath}/package.json`, 'utf-8')); } catch (error) {} let nextUnqualifiedPath; if (pkgJson && pkgJson.main) { nextUnqualifiedPath = path.resolve(unqualifiedPath, pkgJson.main); } // If the "main" field changed the path, we start again from this new location if (nextUnqualifiedPath && nextUnqualifiedPath !== unqualifiedPath) { const resolution = applyNodeExtensionResolution(nextUnqualifiedPath, {extensions}); if (resolution !== null) { return resolution; } } } // Otherwise we check if we find a file that match one of the supported extensions const qualifiedPath = extensions .map(extension => { return `${unqualifiedPath}${extension}`; }) .find(candidateFile => { return existsSync(candidateFile); }); if (qualifiedPath) { return qualifiedPath; } // Otherwise, we check if the path is a folder - in such a case, we try to use its index if (stat && stat.isDirectory()) { const indexPath = extensions .map(extension => { return `${unqualifiedPath}/index${extension}`; }) .find(candidateFile => { return existsSync(candidateFile); }); if (indexPath) { return indexPath; } } // Otherwise there's nothing else we can do :( return null; } }
javascript
function applyNodeExtensionResolution(unqualifiedPath, {extensions}) { // We use this "infinite while" so that we can restart the process as long as we hit package folders while (true) { let stat; try { stat = statSync(unqualifiedPath); } catch (error) {} // If the file exists and is a file, we can stop right there if (stat && !stat.isDirectory()) { // If the very last component of the resolved path is a symlink to a file, we then resolve it to a file. We only // do this first the last component, and not the rest of the path! This allows us to support the case of bin // symlinks, where a symlink in "/xyz/pkg-name/.bin/bin-name" will point somewhere else (like "/xyz/pkg-name/index.js"). // In such a case, we want relative requires to be resolved relative to "/xyz/pkg-name/" rather than "/xyz/pkg-name/.bin/". // // Also note that the reason we must use readlink on the last component (instead of realpath on the whole path) // is that we must preserve the other symlinks, in particular those used by pnp to deambiguate packages using // peer dependencies. For example, "/xyz/.pnp/local/pnp-01234569/.bin/bin-name" should see its relative requires // be resolved relative to "/xyz/.pnp/local/pnp-0123456789/" rather than "/xyz/pkg-with-peers/", because otherwise // we would lose the information that would tell us what are the dependencies of pkg-with-peers relative to its // ancestors. if (lstatSync(unqualifiedPath).isSymbolicLink()) { unqualifiedPath = path.normalize(path.resolve(path.dirname(unqualifiedPath), readlinkSync(unqualifiedPath))); } return unqualifiedPath; } // If the file is a directory, we must check if it contains a package.json with a "main" entry if (stat && stat.isDirectory()) { let pkgJson; try { pkgJson = JSON.parse(readFileSync(`${unqualifiedPath}/package.json`, 'utf-8')); } catch (error) {} let nextUnqualifiedPath; if (pkgJson && pkgJson.main) { nextUnqualifiedPath = path.resolve(unqualifiedPath, pkgJson.main); } // If the "main" field changed the path, we start again from this new location if (nextUnqualifiedPath && nextUnqualifiedPath !== unqualifiedPath) { const resolution = applyNodeExtensionResolution(nextUnqualifiedPath, {extensions}); if (resolution !== null) { return resolution; } } } // Otherwise we check if we find a file that match one of the supported extensions const qualifiedPath = extensions .map(extension => { return `${unqualifiedPath}${extension}`; }) .find(candidateFile => { return existsSync(candidateFile); }); if (qualifiedPath) { return qualifiedPath; } // Otherwise, we check if the path is a folder - in such a case, we try to use its index if (stat && stat.isDirectory()) { const indexPath = extensions .map(extension => { return `${unqualifiedPath}/index${extension}`; }) .find(candidateFile => { return existsSync(candidateFile); }); if (indexPath) { return indexPath; } } // Otherwise there's nothing else we can do :( return null; } }
[ "function", "applyNodeExtensionResolution", "(", "unqualifiedPath", ",", "{", "extensions", "}", ")", "{", "// We use this \"infinite while\" so that we can restart the process as long as we hit package folders", "while", "(", "true", ")", "{", "let", "stat", ";", "try", "{", "stat", "=", "statSync", "(", "unqualifiedPath", ")", ";", "}", "catch", "(", "error", ")", "{", "}", "// If the file exists and is a file, we can stop right there", "if", "(", "stat", "&&", "!", "stat", ".", "isDirectory", "(", ")", ")", "{", "// If the very last component of the resolved path is a symlink to a file, we then resolve it to a file. We only", "// do this first the last component, and not the rest of the path! This allows us to support the case of bin", "// symlinks, where a symlink in \"/xyz/pkg-name/.bin/bin-name\" will point somewhere else (like \"/xyz/pkg-name/index.js\").", "// In such a case, we want relative requires to be resolved relative to \"/xyz/pkg-name/\" rather than \"/xyz/pkg-name/.bin/\".", "//", "// Also note that the reason we must use readlink on the last component (instead of realpath on the whole path)", "// is that we must preserve the other symlinks, in particular those used by pnp to deambiguate packages using", "// peer dependencies. For example, \"/xyz/.pnp/local/pnp-01234569/.bin/bin-name\" should see its relative requires", "// be resolved relative to \"/xyz/.pnp/local/pnp-0123456789/\" rather than \"/xyz/pkg-with-peers/\", because otherwise", "// we would lose the information that would tell us what are the dependencies of pkg-with-peers relative to its", "// ancestors.", "if", "(", "lstatSync", "(", "unqualifiedPath", ")", ".", "isSymbolicLink", "(", ")", ")", "{", "unqualifiedPath", "=", "path", ".", "normalize", "(", "path", ".", "resolve", "(", "path", ".", "dirname", "(", "unqualifiedPath", ")", ",", "readlinkSync", "(", "unqualifiedPath", ")", ")", ")", ";", "}", "return", "unqualifiedPath", ";", "}", "// If the file is a directory, we must check if it contains a package.json with a \"main\" entry", "if", "(", "stat", "&&", "stat", ".", "isDirectory", "(", ")", ")", "{", "let", "pkgJson", ";", "try", "{", "pkgJson", "=", "JSON", ".", "parse", "(", "readFileSync", "(", "`", "${", "unqualifiedPath", "}", "`", ",", "'utf-8'", ")", ")", ";", "}", "catch", "(", "error", ")", "{", "}", "let", "nextUnqualifiedPath", ";", "if", "(", "pkgJson", "&&", "pkgJson", ".", "main", ")", "{", "nextUnqualifiedPath", "=", "path", ".", "resolve", "(", "unqualifiedPath", ",", "pkgJson", ".", "main", ")", ";", "}", "// If the \"main\" field changed the path, we start again from this new location", "if", "(", "nextUnqualifiedPath", "&&", "nextUnqualifiedPath", "!==", "unqualifiedPath", ")", "{", "const", "resolution", "=", "applyNodeExtensionResolution", "(", "nextUnqualifiedPath", ",", "{", "extensions", "}", ")", ";", "if", "(", "resolution", "!==", "null", ")", "{", "return", "resolution", ";", "}", "}", "}", "// Otherwise we check if we find a file that match one of the supported extensions", "const", "qualifiedPath", "=", "extensions", ".", "map", "(", "extension", "=>", "{", "return", "`", "${", "unqualifiedPath", "}", "${", "extension", "}", "`", ";", "}", ")", ".", "find", "(", "candidateFile", "=>", "{", "return", "existsSync", "(", "candidateFile", ")", ";", "}", ")", ";", "if", "(", "qualifiedPath", ")", "{", "return", "qualifiedPath", ";", "}", "// Otherwise, we check if the path is a folder - in such a case, we try to use its index", "if", "(", "stat", "&&", "stat", ".", "isDirectory", "(", ")", ")", "{", "const", "indexPath", "=", "extensions", ".", "map", "(", "extension", "=>", "{", "return", "`", "${", "unqualifiedPath", "}", "${", "extension", "}", "`", ";", "}", ")", ".", "find", "(", "candidateFile", "=>", "{", "return", "existsSync", "(", "candidateFile", ")", ";", "}", ")", ";", "if", "(", "indexPath", ")", "{", "return", "indexPath", ";", "}", "}", "// Otherwise there's nothing else we can do :(", "return", "null", ";", "}", "}" ]
Implements the node resolution for folder access and extension selection
[ "Implements", "the", "node", "resolution", "for", "folder", "access", "and", "extension", "selection" ]
a8f46d6648db13abf30bbb4800fe63b25e49e1b3
https://github.com/quase/quasejs/blob/a8f46d6648db13abf30bbb4800fe63b25e49e1b3/.pnp.js#L12598-L12689
39,637
quase/quasejs
.pnp.js
normalizePath
function normalizePath(fsPath) { fsPath = path.normalize(fsPath); if (process.platform === 'win32') { fsPath = fsPath.replace(backwardSlashRegExp, '/'); } return fsPath; }
javascript
function normalizePath(fsPath) { fsPath = path.normalize(fsPath); if (process.platform === 'win32') { fsPath = fsPath.replace(backwardSlashRegExp, '/'); } return fsPath; }
[ "function", "normalizePath", "(", "fsPath", ")", "{", "fsPath", "=", "path", ".", "normalize", "(", "fsPath", ")", ";", "if", "(", "process", ".", "platform", "===", "'win32'", ")", "{", "fsPath", "=", "fsPath", ".", "replace", "(", "backwardSlashRegExp", ",", "'/'", ")", ";", "}", "return", "fsPath", ";", "}" ]
Normalize path to posix format.
[ "Normalize", "path", "to", "posix", "format", "." ]
a8f46d6648db13abf30bbb4800fe63b25e49e1b3
https://github.com/quase/quasejs/blob/a8f46d6648db13abf30bbb4800fe63b25e49e1b3/.pnp.js#L12711-L12719
39,638
intesso/connect-locale
server.js
cleanupArray
function cleanupArray(obj, name) { var arr = obj[name]; if (!arr) throw new Error(name + ' option is missing'); if (Array.isArray(arr)) { arr = arr.join(','); } if (typeof arr !== 'string') throw new Error(name + ' option must be an Array or a comma separated String'); arr = arr.replace(/_/g, '-').replace(/\s/g, '').toLowerCase().split(','); return arr; }
javascript
function cleanupArray(obj, name) { var arr = obj[name]; if (!arr) throw new Error(name + ' option is missing'); if (Array.isArray(arr)) { arr = arr.join(','); } if (typeof arr !== 'string') throw new Error(name + ' option must be an Array or a comma separated String'); arr = arr.replace(/_/g, '-').replace(/\s/g, '').toLowerCase().split(','); return arr; }
[ "function", "cleanupArray", "(", "obj", ",", "name", ")", "{", "var", "arr", "=", "obj", "[", "name", "]", ";", "if", "(", "!", "arr", ")", "throw", "new", "Error", "(", "name", "+", "' option is missing'", ")", ";", "if", "(", "Array", ".", "isArray", "(", "arr", ")", ")", "{", "arr", "=", "arr", ".", "join", "(", "','", ")", ";", "}", "if", "(", "typeof", "arr", "!==", "'string'", ")", "throw", "new", "Error", "(", "name", "+", "' option must be an Array or a comma separated String'", ")", ";", "arr", "=", "arr", ".", "replace", "(", "/", "_", "/", "g", ",", "'-'", ")", ".", "replace", "(", "/", "\\s", "/", "g", ",", "''", ")", ".", "toLowerCase", "(", ")", ".", "split", "(", "','", ")", ";", "return", "arr", ";", "}" ]
helper function to trim, lowerCase the comma separated string or array
[ "helper", "function", "to", "trim", "lowerCase", "the", "comma", "separated", "string", "or", "array" ]
87e08bfe30f98b7cac8333f86cddecfb7161d67e
https://github.com/intesso/connect-locale/blob/87e08bfe30f98b7cac8333f86cddecfb7161d67e/server.js#L51-L60
39,639
intesso/connect-locale
server.js
matchLocale
function matchLocale(locale) { var found = false; if (!locale) return false; locale = locale.replace(/_/g, '-').toLowerCase(); if (localesLookup[locale]) return localesLookup[locale]; if (options.matchSubTags) { while (~locale.indexOf('-')) { var index = locale.lastIndexOf('-'); locale = locale.substring(0, index); if (localesLookup[locale]) { found = localesLookup[locale]; break; } } } return found; }
javascript
function matchLocale(locale) { var found = false; if (!locale) return false; locale = locale.replace(/_/g, '-').toLowerCase(); if (localesLookup[locale]) return localesLookup[locale]; if (options.matchSubTags) { while (~locale.indexOf('-')) { var index = locale.lastIndexOf('-'); locale = locale.substring(0, index); if (localesLookup[locale]) { found = localesLookup[locale]; break; } } } return found; }
[ "function", "matchLocale", "(", "locale", ")", "{", "var", "found", "=", "false", ";", "if", "(", "!", "locale", ")", "return", "false", ";", "locale", "=", "locale", ".", "replace", "(", "/", "_", "/", "g", ",", "'-'", ")", ".", "toLowerCase", "(", ")", ";", "if", "(", "localesLookup", "[", "locale", "]", ")", "return", "localesLookup", "[", "locale", "]", ";", "if", "(", "options", ".", "matchSubTags", ")", "{", "while", "(", "~", "locale", ".", "indexOf", "(", "'-'", ")", ")", "{", "var", "index", "=", "locale", ".", "lastIndexOf", "(", "'-'", ")", ";", "locale", "=", "locale", ".", "substring", "(", "0", ",", "index", ")", ";", "if", "(", "localesLookup", "[", "locale", "]", ")", "{", "found", "=", "localesLookup", "[", "locale", "]", ";", "break", ";", "}", "}", "}", "return", "found", ";", "}" ]
helper function to detect locale or sublocale
[ "helper", "function", "to", "detect", "locale", "or", "sublocale" ]
87e08bfe30f98b7cac8333f86cddecfb7161d67e
https://github.com/intesso/connect-locale/blob/87e08bfe30f98b7cac8333f86cddecfb7161d67e/server.js#L64-L80
39,640
crcn/bindable.js
lib/collection/index.js
BindableCollection
function BindableCollection (source) { BindableObject.call(this, this); this.source = source || []; this._updateInfo(); this.bind("source", _.bind(this._onSourceChange, this)); }
javascript
function BindableCollection (source) { BindableObject.call(this, this); this.source = source || []; this._updateInfo(); this.bind("source", _.bind(this._onSourceChange, this)); }
[ "function", "BindableCollection", "(", "source", ")", "{", "BindableObject", ".", "call", "(", "this", ",", "this", ")", ";", "this", ".", "source", "=", "source", "||", "[", "]", ";", "this", ".", "_updateInfo", "(", ")", ";", "this", ".", "bind", "(", "\"source\"", ",", "_", ".", "bind", "(", "this", ".", "_onSourceChange", ",", "this", ")", ")", ";", "}" ]
Emitted when an item is removed @event remove @param {Object} item removed Emitted when items are replaced @event replace @param {Array} newItems @param {Array} oldItems
[ "Emitted", "when", "an", "item", "is", "removed" ]
562dcd4a0e208e2a11ac7613654b32b01c7d92ac
https://github.com/crcn/bindable.js/blob/562dcd4a0e208e2a11ac7613654b32b01c7d92ac/lib/collection/index.js#L39-L44
39,641
crcn/bindable.js
lib/collection/index.js
function () { var items = Array.prototype.slice.call(arguments); this.source.push.apply(this.source, items); this._updateInfo(); // DEPRECATED this.emit("insert", items[0], this.length - 1); this.emit("update", { insert: items, index: this.length - 1}); }
javascript
function () { var items = Array.prototype.slice.call(arguments); this.source.push.apply(this.source, items); this._updateInfo(); // DEPRECATED this.emit("insert", items[0], this.length - 1); this.emit("update", { insert: items, index: this.length - 1}); }
[ "function", "(", ")", "{", "var", "items", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "this", ".", "source", ".", "push", ".", "apply", "(", "this", ".", "source", ",", "items", ")", ";", "this", ".", "_updateInfo", "(", ")", ";", "// DEPRECATED", "this", ".", "emit", "(", "\"insert\"", ",", "items", "[", "0", "]", ",", "this", ".", "length", "-", "1", ")", ";", "this", ".", "emit", "(", "\"update\"", ",", "{", "insert", ":", "items", ",", "index", ":", "this", ".", "length", "-", "1", "}", ")", ";", "}" ]
Pushes an item onto the collection @method push @param {Object} item
[ "Pushes", "an", "item", "onto", "the", "collection" ]
562dcd4a0e208e2a11ac7613654b32b01c7d92ac
https://github.com/crcn/bindable.js/blob/562dcd4a0e208e2a11ac7613654b32b01c7d92ac/lib/collection/index.js#L142-L150
39,642
crcn/bindable.js
lib/collection/index.js
function () { var items = Array.prototype.slice.call(arguments); this.source.unshift.apply(this.source, items); this._updateInfo(); // DEPRECATED this.emit("insert", items[0], 0); this.emit("update", { insert: items }); }
javascript
function () { var items = Array.prototype.slice.call(arguments); this.source.unshift.apply(this.source, items); this._updateInfo(); // DEPRECATED this.emit("insert", items[0], 0); this.emit("update", { insert: items }); }
[ "function", "(", ")", "{", "var", "items", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "this", ".", "source", ".", "unshift", ".", "apply", "(", "this", ".", "source", ",", "items", ")", ";", "this", ".", "_updateInfo", "(", ")", ";", "// DEPRECATED", "this", ".", "emit", "(", "\"insert\"", ",", "items", "[", "0", "]", ",", "0", ")", ";", "this", ".", "emit", "(", "\"update\"", ",", "{", "insert", ":", "items", "}", ")", ";", "}" ]
Unshifts an item onto the collection @method unshift @param {Object} item
[ "Unshifts", "an", "item", "onto", "the", "collection" ]
562dcd4a0e208e2a11ac7613654b32b01c7d92ac
https://github.com/crcn/bindable.js/blob/562dcd4a0e208e2a11ac7613654b32b01c7d92ac/lib/collection/index.js#L158-L167
39,643
crcn/bindable.js
lib/collection/index.js
function (index, count) { var newItems = Array.prototype.slice.call(arguments, 2), oldItems = this.source.splice.apply(this.source, arguments); this._updateInfo(); // DEPRECATED this.emit("replace", newItems, oldItems, index); this.emit("update", { insert: newItems, remove: oldItems }); }
javascript
function (index, count) { var newItems = Array.prototype.slice.call(arguments, 2), oldItems = this.source.splice.apply(this.source, arguments); this._updateInfo(); // DEPRECATED this.emit("replace", newItems, oldItems, index); this.emit("update", { insert: newItems, remove: oldItems }); }
[ "function", "(", "index", ",", "count", ")", "{", "var", "newItems", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "2", ")", ",", "oldItems", "=", "this", ".", "source", ".", "splice", ".", "apply", "(", "this", ".", "source", ",", "arguments", ")", ";", "this", ".", "_updateInfo", "(", ")", ";", "// DEPRECATED", "this", ".", "emit", "(", "\"replace\"", ",", "newItems", ",", "oldItems", ",", "index", ")", ";", "this", ".", "emit", "(", "\"update\"", ",", "{", "insert", ":", "newItems", ",", "remove", ":", "oldItems", "}", ")", ";", "}" ]
Removes N Number of items @method splice @param {Number} index start index @param {Number} count number of items to remove
[ "Removes", "N", "Number", "of", "items" ]
562dcd4a0e208e2a11ac7613654b32b01c7d92ac
https://github.com/crcn/bindable.js/blob/562dcd4a0e208e2a11ac7613654b32b01c7d92ac/lib/collection/index.js#L176-L185
39,644
crcn/bindable.js
lib/collection/index.js
function (item) { var i = this.indexOf(item); if (!~i) return false; this.source.splice(i, 1); this._updateInfo(); this.emit("remove", item, i); this.emit("update", { remove: [item] }); return item; }
javascript
function (item) { var i = this.indexOf(item); if (!~i) return false; this.source.splice(i, 1); this._updateInfo(); this.emit("remove", item, i); this.emit("update", { remove: [item] }); return item; }
[ "function", "(", "item", ")", "{", "var", "i", "=", "this", ".", "indexOf", "(", "item", ")", ";", "if", "(", "!", "~", "i", ")", "return", "false", ";", "this", ".", "source", ".", "splice", "(", "i", ",", "1", ")", ";", "this", ".", "_updateInfo", "(", ")", ";", "this", ".", "emit", "(", "\"remove\"", ",", "item", ",", "i", ")", ";", "this", ".", "emit", "(", "\"update\"", ",", "{", "remove", ":", "[", "item", "]", "}", ")", ";", "return", "item", ";", "}" ]
Removes an item from the collection @method remove @param {Object} item item to remove
[ "Removes", "an", "item", "from", "the", "collection" ]
562dcd4a0e208e2a11ac7613654b32b01c7d92ac
https://github.com/crcn/bindable.js/blob/562dcd4a0e208e2a11ac7613654b32b01c7d92ac/lib/collection/index.js#L193-L202
39,645
techninja/robopaint-mode-example
example.js
paperLoadedInit
function paperLoadedInit() { console.log('Paper ready!'); // Set center adjusters based on size of canvas $('#hcenter').attr({ value: 0, min: -(robopaint.canvas.width / 2), max: robopaint.canvas.width / 2 }); $('#vcenter').attr({ value: 0, min: -(robopaint.canvas.height / 2), max: robopaint.canvas.height / 2 }); $(window).resize(); // Use mode settings management on all "managed" class items. This // saves/loads settings from/into the elements on change/init. mode.settings.$manage('.managed'); // With Paper ready, send a single up to fill values for buffer & pen. mode.run('up'); }
javascript
function paperLoadedInit() { console.log('Paper ready!'); // Set center adjusters based on size of canvas $('#hcenter').attr({ value: 0, min: -(robopaint.canvas.width / 2), max: robopaint.canvas.width / 2 }); $('#vcenter').attr({ value: 0, min: -(robopaint.canvas.height / 2), max: robopaint.canvas.height / 2 }); $(window).resize(); // Use mode settings management on all "managed" class items. This // saves/loads settings from/into the elements on change/init. mode.settings.$manage('.managed'); // With Paper ready, send a single up to fill values for buffer & pen. mode.run('up'); }
[ "function", "paperLoadedInit", "(", ")", "{", "console", ".", "log", "(", "'Paper ready!'", ")", ";", "// Set center adjusters based on size of canvas", "$", "(", "'#hcenter'", ")", ".", "attr", "(", "{", "value", ":", "0", ",", "min", ":", "-", "(", "robopaint", ".", "canvas", ".", "width", "/", "2", ")", ",", "max", ":", "robopaint", ".", "canvas", ".", "width", "/", "2", "}", ")", ";", "$", "(", "'#vcenter'", ")", ".", "attr", "(", "{", "value", ":", "0", ",", "min", ":", "-", "(", "robopaint", ".", "canvas", ".", "height", "/", "2", ")", ",", "max", ":", "robopaint", ".", "canvas", ".", "height", "/", "2", "}", ")", ";", "$", "(", "window", ")", ".", "resize", "(", ")", ";", "// Use mode settings management on all \"managed\" class items. This", "// saves/loads settings from/into the elements on change/init.", "mode", ".", "settings", ".", "$manage", "(", "'.managed'", ")", ";", "// With Paper ready, send a single up to fill values for buffer & pen.", "mode", ".", "run", "(", "'up'", ")", ";", "}" ]
Callback that tells us that our Paper.js canvas is ready!
[ "Callback", "that", "tells", "us", "that", "our", "Paper", ".", "js", "canvas", "is", "ready!" ]
9af42cbe3e27f404185b812c0a91d8a354ba970b
https://github.com/techninja/robopaint-mode-example/blob/9af42cbe3e27f404185b812c0a91d8a354ba970b/example.js#L36-L60
39,646
smbape/node-umd-builder
lib/appenders/file.js
fileAppender
function fileAppender(config, layout) { const appender = new FileAppender(config, layout); // push file to the stack of open handlers appenderList.push(appender); return appender.write; }
javascript
function fileAppender(config, layout) { const appender = new FileAppender(config, layout); // push file to the stack of open handlers appenderList.push(appender); return appender.write; }
[ "function", "fileAppender", "(", "config", ",", "layout", ")", "{", "const", "appender", "=", "new", "FileAppender", "(", "config", ",", "layout", ")", ";", "// push file to the stack of open handlers", "appenderList", ".", "push", "(", "appender", ")", ";", "return", "appender", ".", "write", ";", "}" ]
File Appender writing the logs to a text file. Supports rolling of logs by size. @param file file log messages will be written to @param layout a function that takes a logevent and returns a string * (defaults to basicLayout). @param logSize - the maximum size (in bytes) for a log file, * if not provided then logs won't be rotated. @param numBackups - the number of log files to keep after logSize * has been reached (default 5) @param compress - flag that controls log file compression @param timezoneOffset - optional timezone offset in minutes (default system local) @param stripAnsi - flag that controls if ansi should be strip (default true)
[ "File", "Appender", "writing", "the", "logs", "to", "a", "text", "file", ".", "Supports", "rolling", "of", "logs", "by", "size", "." ]
73b03e8c985f2660948f5df71140e4a8fb162549
https://github.com/smbape/node-umd-builder/blob/73b03e8c985f2660948f5df71140e4a8fb162549/lib/appenders/file.js#L29-L36
39,647
S3bb1/ah-dashboard-plugin
public/dashboard/app/angular-ui-dashboard.js
function (widgets) { if (!this.storage) { return true; } var serialized = _.map(widgets, function (widget) { var widgetObject = { title: widget.title, name: widget.name, style: widget.style, dataModelOptions: widget.dataModelOptions, storageHash: widget.storageHash, attrs: widget.attrs }; return widgetObject; }); var item = { widgets: serialized, hash: this.hash }; if (this.stringify) { item = JSON.stringify(item); } this.storage.setItem(this.id, item); return true; }
javascript
function (widgets) { if (!this.storage) { return true; } var serialized = _.map(widgets, function (widget) { var widgetObject = { title: widget.title, name: widget.name, style: widget.style, dataModelOptions: widget.dataModelOptions, storageHash: widget.storageHash, attrs: widget.attrs }; return widgetObject; }); var item = { widgets: serialized, hash: this.hash }; if (this.stringify) { item = JSON.stringify(item); } this.storage.setItem(this.id, item); return true; }
[ "function", "(", "widgets", ")", "{", "if", "(", "!", "this", ".", "storage", ")", "{", "return", "true", ";", "}", "var", "serialized", "=", "_", ".", "map", "(", "widgets", ",", "function", "(", "widget", ")", "{", "var", "widgetObject", "=", "{", "title", ":", "widget", ".", "title", ",", "name", ":", "widget", ".", "name", ",", "style", ":", "widget", ".", "style", ",", "dataModelOptions", ":", "widget", ".", "dataModelOptions", ",", "storageHash", ":", "widget", ".", "storageHash", ",", "attrs", ":", "widget", ".", "attrs", "}", ";", "return", "widgetObject", ";", "}", ")", ";", "var", "item", "=", "{", "widgets", ":", "serialized", ",", "hash", ":", "this", ".", "hash", "}", ";", "if", "(", "this", ".", "stringify", ")", "{", "item", "=", "JSON", ".", "stringify", "(", "item", ")", ";", "}", "this", ".", "storage", ".", "setItem", "(", "this", ".", "id", ",", "item", ")", ";", "return", "true", ";", "}" ]
Takes array of widget instance objects, serializes, and saves state. @param {Array} widgets scope.widgets from dashboard directive @return {Boolean} true on success, false on failure
[ "Takes", "array", "of", "widget", "instance", "objects", "serializes", "and", "saves", "state", "." ]
c283370ec0f99a25db5bb7029a98b4febf8c5251
https://github.com/S3bb1/ah-dashboard-plugin/blob/c283370ec0f99a25db5bb7029a98b4febf8c5251/public/dashboard/app/angular-ui-dashboard.js#L786-L813
39,648
S3bb1/ah-dashboard-plugin
public/dashboard/app/angular-ui-dashboard.js
function () { if (!this.storage) { return null; } var serialized; // try loading storage item serialized = this.storage.getItem(this.id); if (serialized) { // check for promise if (typeof serialized === 'object' && typeof serialized.then === 'function') { return this._handleAsyncLoad(serialized); } // otherwise handle synchronous load return this._handleSyncLoad(serialized); } else { return null; } }
javascript
function () { if (!this.storage) { return null; } var serialized; // try loading storage item serialized = this.storage.getItem(this.id); if (serialized) { // check for promise if (typeof serialized === 'object' && typeof serialized.then === 'function') { return this._handleAsyncLoad(serialized); } // otherwise handle synchronous load return this._handleSyncLoad(serialized); } else { return null; } }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "storage", ")", "{", "return", "null", ";", "}", "var", "serialized", ";", "// try loading storage item", "serialized", "=", "this", ".", "storage", ".", "getItem", "(", "this", ".", "id", ")", ";", "if", "(", "serialized", ")", "{", "// check for promise", "if", "(", "typeof", "serialized", "===", "'object'", "&&", "typeof", "serialized", ".", "then", "===", "'function'", ")", "{", "return", "this", ".", "_handleAsyncLoad", "(", "serialized", ")", ";", "}", "// otherwise handle synchronous load", "return", "this", ".", "_handleSyncLoad", "(", "serialized", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Loads dashboard state from the storage object. Can handle a synchronous response or a promise. @return {Array|Promise} Array of widget definitions or a promise
[ "Loads", "dashboard", "state", "from", "the", "storage", "object", ".", "Can", "handle", "a", "synchronous", "response", "or", "a", "promise", "." ]
c283370ec0f99a25db5bb7029a98b4febf8c5251
https://github.com/S3bb1/ah-dashboard-plugin/blob/c283370ec0f99a25db5bb7029a98b4febf8c5251/public/dashboard/app/angular-ui-dashboard.js#L821-L842
39,649
S3bb1/ah-dashboard-plugin
public/dashboard/app/angular-ui-dashboard.js
WidgetModel
function WidgetModel(Class, overrides) { var defaults = { title: 'Widget', name: Class.name, attrs: Class.attrs, dataAttrName: Class.dataAttrName, dataModelType: Class.dataModelType, dataModelArgs: Class.dataModelArgs, // used in data model constructor, not serialized //AW Need deep copy of options to support widget options editing dataModelOptions: Class.dataModelOptions, settingsModalOptions: Class.settingsModalOptions, onSettingsClose: Class.onSettingsClose, onSettingsDismiss: Class.onSettingsDismiss, style: Class.style }; overrides = overrides || {}; angular.extend(this, angular.copy(defaults), overrides); this.style = this.style || { width: '33%' }; this.setWidth(this.style.width); if (Class.templateUrl) { this.templateUrl = Class.templateUrl; } else if (Class.template) { this.template = Class.template; } else { var directive = Class.directive || Class.name; this.directive = directive; } }
javascript
function WidgetModel(Class, overrides) { var defaults = { title: 'Widget', name: Class.name, attrs: Class.attrs, dataAttrName: Class.dataAttrName, dataModelType: Class.dataModelType, dataModelArgs: Class.dataModelArgs, // used in data model constructor, not serialized //AW Need deep copy of options to support widget options editing dataModelOptions: Class.dataModelOptions, settingsModalOptions: Class.settingsModalOptions, onSettingsClose: Class.onSettingsClose, onSettingsDismiss: Class.onSettingsDismiss, style: Class.style }; overrides = overrides || {}; angular.extend(this, angular.copy(defaults), overrides); this.style = this.style || { width: '33%' }; this.setWidth(this.style.width); if (Class.templateUrl) { this.templateUrl = Class.templateUrl; } else if (Class.template) { this.template = Class.template; } else { var directive = Class.directive || Class.name; this.directive = directive; } }
[ "function", "WidgetModel", "(", "Class", ",", "overrides", ")", "{", "var", "defaults", "=", "{", "title", ":", "'Widget'", ",", "name", ":", "Class", ".", "name", ",", "attrs", ":", "Class", ".", "attrs", ",", "dataAttrName", ":", "Class", ".", "dataAttrName", ",", "dataModelType", ":", "Class", ".", "dataModelType", ",", "dataModelArgs", ":", "Class", ".", "dataModelArgs", ",", "// used in data model constructor, not serialized", "//AW Need deep copy of options to support widget options editing", "dataModelOptions", ":", "Class", ".", "dataModelOptions", ",", "settingsModalOptions", ":", "Class", ".", "settingsModalOptions", ",", "onSettingsClose", ":", "Class", ".", "onSettingsClose", ",", "onSettingsDismiss", ":", "Class", ".", "onSettingsDismiss", ",", "style", ":", "Class", ".", "style", "}", ";", "overrides", "=", "overrides", "||", "{", "}", ";", "angular", ".", "extend", "(", "this", ",", "angular", ".", "copy", "(", "defaults", ")", ",", "overrides", ")", ";", "this", ".", "style", "=", "this", ".", "style", "||", "{", "width", ":", "'33%'", "}", ";", "this", ".", "setWidth", "(", "this", ".", "style", ".", "width", ")", ";", "if", "(", "Class", ".", "templateUrl", ")", "{", "this", ".", "templateUrl", "=", "Class", ".", "templateUrl", ";", "}", "else", "if", "(", "Class", ".", "template", ")", "{", "this", ".", "template", "=", "Class", ".", "template", ";", "}", "else", "{", "var", "directive", "=", "Class", ".", "directive", "||", "Class", ".", "name", ";", "this", ".", "directive", "=", "directive", ";", "}", "}" ]
constructor for widget model instances
[ "constructor", "for", "widget", "model", "instances" ]
c283370ec0f99a25db5bb7029a98b4febf8c5251
https://github.com/S3bb1/ah-dashboard-plugin/blob/c283370ec0f99a25db5bb7029a98b4febf8c5251/public/dashboard/app/angular-ui-dashboard.js#L1044-L1072
39,650
S3bb1/ah-dashboard-plugin
public/dashboard/app/angular-ui-dashboard.js
function (e) { var curX = e.clientX; var pixelChange = curX - initX; var newWidth = pixelWidth + pixelChange; $marquee.css('width', newWidth + 'px'); }
javascript
function (e) { var curX = e.clientX; var pixelChange = curX - initX; var newWidth = pixelWidth + pixelChange; $marquee.css('width', newWidth + 'px'); }
[ "function", "(", "e", ")", "{", "var", "curX", "=", "e", ".", "clientX", ";", "var", "pixelChange", "=", "curX", "-", "initX", ";", "var", "newWidth", "=", "pixelWidth", "+", "pixelChange", ";", "$marquee", ".", "css", "(", "'width'", ",", "newWidth", "+", "'px'", ")", ";", "}" ]
updates marquee with preview of new width
[ "updates", "marquee", "with", "preview", "of", "new", "width" ]
c283370ec0f99a25db5bb7029a98b4febf8c5251
https://github.com/S3bb1/ah-dashboard-plugin/blob/c283370ec0f99a25db5bb7029a98b4febf8c5251/public/dashboard/app/angular-ui-dashboard.js#L1234-L1239
39,651
S3bb1/ah-dashboard-plugin
public/dashboard/app/angular-ui-dashboard.js
function (e) { // remove listener and marquee jQuery($window).off('mousemove', mousemove); $marquee.remove(); // calculate change in units var curX = e.clientX; var pixelChange = curX - initX; var unitChange = Math.round(pixelChange * transformMultiplier * 100) / 100; // add to initial unit width var newWidth = unitWidth * 1 + unitChange; widget.setWidth(newWidth + widthUnits); $scope.$emit('widgetChanged', widget); $scope.$apply(); }
javascript
function (e) { // remove listener and marquee jQuery($window).off('mousemove', mousemove); $marquee.remove(); // calculate change in units var curX = e.clientX; var pixelChange = curX - initX; var unitChange = Math.round(pixelChange * transformMultiplier * 100) / 100; // add to initial unit width var newWidth = unitWidth * 1 + unitChange; widget.setWidth(newWidth + widthUnits); $scope.$emit('widgetChanged', widget); $scope.$apply(); }
[ "function", "(", "e", ")", "{", "// remove listener and marquee", "jQuery", "(", "$window", ")", ".", "off", "(", "'mousemove'", ",", "mousemove", ")", ";", "$marquee", ".", "remove", "(", ")", ";", "// calculate change in units", "var", "curX", "=", "e", ".", "clientX", ";", "var", "pixelChange", "=", "curX", "-", "initX", ";", "var", "unitChange", "=", "Math", ".", "round", "(", "pixelChange", "*", "transformMultiplier", "*", "100", ")", "/", "100", ";", "// add to initial unit width", "var", "newWidth", "=", "unitWidth", "*", "1", "+", "unitChange", ";", "widget", ".", "setWidth", "(", "newWidth", "+", "widthUnits", ")", ";", "$scope", ".", "$emit", "(", "'widgetChanged'", ",", "widget", ")", ";", "$scope", ".", "$apply", "(", ")", ";", "}" ]
sets new widget width on mouseup
[ "sets", "new", "widget", "width", "on", "mouseup" ]
c283370ec0f99a25db5bb7029a98b4febf8c5251
https://github.com/S3bb1/ah-dashboard-plugin/blob/c283370ec0f99a25db5bb7029a98b4febf8c5251/public/dashboard/app/angular-ui-dashboard.js#L1242-L1257
39,652
techninja/robopaint-mode-example
example.ps.js
onMouseMove
function onMouseMove(event) { project.deselectAll(); if (event.item) { event.item.selected = true; } }
javascript
function onMouseMove(event) { project.deselectAll(); if (event.item) { event.item.selected = true; } }
[ "function", "onMouseMove", "(", "event", ")", "{", "project", ".", "deselectAll", "(", ")", ";", "if", "(", "event", ".", "item", ")", "{", "event", ".", "item", ".", "selected", "=", "true", ";", "}", "}" ]
Show preview paths
[ "Show", "preview", "paths" ]
9af42cbe3e27f404185b812c0a91d8a354ba970b
https://github.com/techninja/robopaint-mode-example/blob/9af42cbe3e27f404185b812c0a91d8a354ba970b/example.ps.js#L24-L30
39,653
bigpipe/backtrace
index.js
Stack
function Stack(trace, options) { if (!(this instanceof Stack)) return new Stack(trace, options); if ('object' === typeof trace && !trace.length) { options = trace; trace = null; } options = options || {}; options.guess = 'guess' in options ? options.guess : true; if (!trace) { var imp = new stacktrace.implementation() , err = options.error || options.err || options.e , traced; traced = imp.run(err); trace = options.guess ? imp.guessAnonymousFunctions(traced) : traced; } this.traces = this.parse(trace); }
javascript
function Stack(trace, options) { if (!(this instanceof Stack)) return new Stack(trace, options); if ('object' === typeof trace && !trace.length) { options = trace; trace = null; } options = options || {}; options.guess = 'guess' in options ? options.guess : true; if (!trace) { var imp = new stacktrace.implementation() , err = options.error || options.err || options.e , traced; traced = imp.run(err); trace = options.guess ? imp.guessAnonymousFunctions(traced) : traced; } this.traces = this.parse(trace); }
[ "function", "Stack", "(", "trace", ",", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Stack", ")", ")", "return", "new", "Stack", "(", "trace", ",", "options", ")", ";", "if", "(", "'object'", "===", "typeof", "trace", "&&", "!", "trace", ".", "length", ")", "{", "options", "=", "trace", ";", "trace", "=", "null", ";", "}", "options", "=", "options", "||", "{", "}", ";", "options", ".", "guess", "=", "'guess'", "in", "options", "?", "options", ".", "guess", ":", "true", ";", "if", "(", "!", "trace", ")", "{", "var", "imp", "=", "new", "stacktrace", ".", "implementation", "(", ")", ",", "err", "=", "options", ".", "error", "||", "options", ".", "err", "||", "options", ".", "e", ",", "traced", ";", "traced", "=", "imp", ".", "run", "(", "err", ")", ";", "trace", "=", "options", ".", "guess", "?", "imp", ".", "guessAnonymousFunctions", "(", "traced", ")", ":", "traced", ";", "}", "this", ".", "traces", "=", "this", ".", "parse", "(", "trace", ")", ";", "}" ]
Representation of a stack trace. Options: - **guess**: Guess the names of anonymous functions. @constructor @param {Array} trace Array of traces. @param {Object} err @api private
[ "Representation", "of", "a", "stack", "trace", "." ]
f9a5dfda5574d4660769d8dfa0ed2c491313837a
https://github.com/bigpipe/backtrace/blob/f9a5dfda5574d4660769d8dfa0ed2c491313837a/index.js#L17-L38
39,654
markfinger/cyclic-dependency-graph
src/graph.js
traceFromNode
function traceFromNode(name) { const job = { node: name, isValid: true }; invalidatePendingJobsForNode(pendingJobs, name); // Ensure the job can be tracked pendingJobs.push(job); // Force an asynchronous start to the tracing so that other parts of a // codebase can synchronously trigger the job to be invalidated. This // helps to avoid any unnecessary work that may no longer be relevant process.nextTick(startTracingNode); if (!hasSignalledStart) { hasSignalledStart = true; events.emit('started', {state: state}); } function startTracingNode() { // Handle situations where a job may have been invalidated further // down the stack from where the original call originated from if (!job.isValid) { return; } getDependencies(name) .then(handleDependencies) .catch(handleError) .then(signalIfCompleted); function handleDependencies(dependencies) { // If this job has been invalidated, we can ignore anything that may // have resulted from it if (!job.isValid) { return; } // Indicate that this job is no longer blocking the `completed` stage pull(pendingJobs, job); // Sanity check if (!isArray(dependencies)) { return Promise.reject( new Error(`Dependencies should be specified in an array. Received ${dependencies}`) ); } const previousState = state; if (!isNodeDefined(state, name)) { state = addNode(state, name); } // If there are any dependencies encountered that we don't already // know about, we start tracing them dependencies.forEach(depName => { if ( !isNodeDefined(state, depName) && !isNodePending(pendingJobs, depName) ) { traceFromNode(depName); } if (!isNodeDefined(state, depName)) { state = addNode(state, depName); } state = addEdge(state, name, depName); }); // Enable progress updates events.emit('traced', { node: name, diff: Diff({ from: previousState, to: state }) }); } function handleError(err) { // Indicate that this job is no longer blocking the `completed` stage pull(pendingJobs, job); // If the job has been invalidated, we ignore the error if (!job.isValid) { return; } const signal = { error: err, node: name, state: state }; errors.push(signal); events.emit('error', signal); } } }
javascript
function traceFromNode(name) { const job = { node: name, isValid: true }; invalidatePendingJobsForNode(pendingJobs, name); // Ensure the job can be tracked pendingJobs.push(job); // Force an asynchronous start to the tracing so that other parts of a // codebase can synchronously trigger the job to be invalidated. This // helps to avoid any unnecessary work that may no longer be relevant process.nextTick(startTracingNode); if (!hasSignalledStart) { hasSignalledStart = true; events.emit('started', {state: state}); } function startTracingNode() { // Handle situations where a job may have been invalidated further // down the stack from where the original call originated from if (!job.isValid) { return; } getDependencies(name) .then(handleDependencies) .catch(handleError) .then(signalIfCompleted); function handleDependencies(dependencies) { // If this job has been invalidated, we can ignore anything that may // have resulted from it if (!job.isValid) { return; } // Indicate that this job is no longer blocking the `completed` stage pull(pendingJobs, job); // Sanity check if (!isArray(dependencies)) { return Promise.reject( new Error(`Dependencies should be specified in an array. Received ${dependencies}`) ); } const previousState = state; if (!isNodeDefined(state, name)) { state = addNode(state, name); } // If there are any dependencies encountered that we don't already // know about, we start tracing them dependencies.forEach(depName => { if ( !isNodeDefined(state, depName) && !isNodePending(pendingJobs, depName) ) { traceFromNode(depName); } if (!isNodeDefined(state, depName)) { state = addNode(state, depName); } state = addEdge(state, name, depName); }); // Enable progress updates events.emit('traced', { node: name, diff: Diff({ from: previousState, to: state }) }); } function handleError(err) { // Indicate that this job is no longer blocking the `completed` stage pull(pendingJobs, job); // If the job has been invalidated, we ignore the error if (!job.isValid) { return; } const signal = { error: err, node: name, state: state }; errors.push(signal); events.emit('error', signal); } } }
[ "function", "traceFromNode", "(", "name", ")", "{", "const", "job", "=", "{", "node", ":", "name", ",", "isValid", ":", "true", "}", ";", "invalidatePendingJobsForNode", "(", "pendingJobs", ",", "name", ")", ";", "// Ensure the job can be tracked", "pendingJobs", ".", "push", "(", "job", ")", ";", "// Force an asynchronous start to the tracing so that other parts of a", "// codebase can synchronously trigger the job to be invalidated. This", "// helps to avoid any unnecessary work that may no longer be relevant", "process", ".", "nextTick", "(", "startTracingNode", ")", ";", "if", "(", "!", "hasSignalledStart", ")", "{", "hasSignalledStart", "=", "true", ";", "events", ".", "emit", "(", "'started'", ",", "{", "state", ":", "state", "}", ")", ";", "}", "function", "startTracingNode", "(", ")", "{", "// Handle situations where a job may have been invalidated further", "// down the stack from where the original call originated from", "if", "(", "!", "job", ".", "isValid", ")", "{", "return", ";", "}", "getDependencies", "(", "name", ")", ".", "then", "(", "handleDependencies", ")", ".", "catch", "(", "handleError", ")", ".", "then", "(", "signalIfCompleted", ")", ";", "function", "handleDependencies", "(", "dependencies", ")", "{", "// If this job has been invalidated, we can ignore anything that may", "// have resulted from it", "if", "(", "!", "job", ".", "isValid", ")", "{", "return", ";", "}", "// Indicate that this job is no longer blocking the `completed` stage", "pull", "(", "pendingJobs", ",", "job", ")", ";", "// Sanity check", "if", "(", "!", "isArray", "(", "dependencies", ")", ")", "{", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "`", "${", "dependencies", "}", "`", ")", ")", ";", "}", "const", "previousState", "=", "state", ";", "if", "(", "!", "isNodeDefined", "(", "state", ",", "name", ")", ")", "{", "state", "=", "addNode", "(", "state", ",", "name", ")", ";", "}", "// If there are any dependencies encountered that we don't already", "// know about, we start tracing them", "dependencies", ".", "forEach", "(", "depName", "=>", "{", "if", "(", "!", "isNodeDefined", "(", "state", ",", "depName", ")", "&&", "!", "isNodePending", "(", "pendingJobs", ",", "depName", ")", ")", "{", "traceFromNode", "(", "depName", ")", ";", "}", "if", "(", "!", "isNodeDefined", "(", "state", ",", "depName", ")", ")", "{", "state", "=", "addNode", "(", "state", ",", "depName", ")", ";", "}", "state", "=", "addEdge", "(", "state", ",", "name", ",", "depName", ")", ";", "}", ")", ";", "// Enable progress updates", "events", ".", "emit", "(", "'traced'", ",", "{", "node", ":", "name", ",", "diff", ":", "Diff", "(", "{", "from", ":", "previousState", ",", "to", ":", "state", "}", ")", "}", ")", ";", "}", "function", "handleError", "(", "err", ")", "{", "// Indicate that this job is no longer blocking the `completed` stage", "pull", "(", "pendingJobs", ",", "job", ")", ";", "// If the job has been invalidated, we ignore the error", "if", "(", "!", "job", ".", "isValid", ")", "{", "return", ";", "}", "const", "signal", "=", "{", "error", ":", "err", ",", "node", ":", "name", ",", "state", ":", "state", "}", ";", "errors", ".", "push", "(", "signal", ")", ";", "events", ".", "emit", "(", "'error'", ",", "signal", ")", ";", "}", "}", "}" ]
Invoke the specified `getDependencies` function and build the graph by recursively traversing unknown nodes @param {String} name
[ "Invoke", "the", "specified", "getDependencies", "function", "and", "build", "the", "graph", "by", "recursively", "traversing", "unknown", "nodes" ]
fac9249ec3a9d29199bed9fedcf99267b2c61c44
https://github.com/markfinger/cyclic-dependency-graph/blob/fac9249ec3a9d29199bed9fedcf99267b2c61c44/src/graph.js#L56-L158
39,655
markfinger/cyclic-dependency-graph
src/graph.js
pruneNode
function pruneNode(name) { const previousState = state; // If the node is still pending, invalidate the associated job so // that it becomes a no-op if (isNodePending(pendingJobs, name)) { invalidatePendingJobsForNode(pendingJobs, name); } if (isNodeDefined(state, name)) { let updatedState = previousState; const node = updatedState.get(name); node.dependents.forEach(dependent => { updatedState = removeEdge(updatedState, dependent, name); }); node.dependencies.forEach(dependency => { updatedState = removeEdge(updatedState, name, dependency); }); updatedState = removeNode(updatedState, name); state = updatedState; } signalIfCompleted(); return Diff({ from: previousState, to: state }); }
javascript
function pruneNode(name) { const previousState = state; // If the node is still pending, invalidate the associated job so // that it becomes a no-op if (isNodePending(pendingJobs, name)) { invalidatePendingJobsForNode(pendingJobs, name); } if (isNodeDefined(state, name)) { let updatedState = previousState; const node = updatedState.get(name); node.dependents.forEach(dependent => { updatedState = removeEdge(updatedState, dependent, name); }); node.dependencies.forEach(dependency => { updatedState = removeEdge(updatedState, name, dependency); }); updatedState = removeNode(updatedState, name); state = updatedState; } signalIfCompleted(); return Diff({ from: previousState, to: state }); }
[ "function", "pruneNode", "(", "name", ")", "{", "const", "previousState", "=", "state", ";", "// If the node is still pending, invalidate the associated job so", "// that it becomes a no-op", "if", "(", "isNodePending", "(", "pendingJobs", ",", "name", ")", ")", "{", "invalidatePendingJobsForNode", "(", "pendingJobs", ",", "name", ")", ";", "}", "if", "(", "isNodeDefined", "(", "state", ",", "name", ")", ")", "{", "let", "updatedState", "=", "previousState", ";", "const", "node", "=", "updatedState", ".", "get", "(", "name", ")", ";", "node", ".", "dependents", ".", "forEach", "(", "dependent", "=>", "{", "updatedState", "=", "removeEdge", "(", "updatedState", ",", "dependent", ",", "name", ")", ";", "}", ")", ";", "node", ".", "dependencies", ".", "forEach", "(", "dependency", "=>", "{", "updatedState", "=", "removeEdge", "(", "updatedState", ",", "name", ",", "dependency", ")", ";", "}", ")", ";", "updatedState", "=", "removeNode", "(", "updatedState", ",", "name", ")", ";", "state", "=", "updatedState", ";", "}", "signalIfCompleted", "(", ")", ";", "return", "Diff", "(", "{", "from", ":", "previousState", ",", "to", ":", "state", "}", ")", ";", "}" ]
Removes a node and its edges from the graph. Any pending jobs for the node will be invalidated. Be aware that pruning a single node may leave other nodes disconnected from an entry node. You may want to call `pruneDisconnectedNodes` to clean the graph of unwanted dependencies. @param {String} name @returns {Diff}
[ "Removes", "a", "node", "and", "its", "edges", "from", "the", "graph", ".", "Any", "pending", "jobs", "for", "the", "node", "will", "be", "invalidated", "." ]
fac9249ec3a9d29199bed9fedcf99267b2c61c44
https://github.com/markfinger/cyclic-dependency-graph/blob/fac9249ec3a9d29199bed9fedcf99267b2c61c44/src/graph.js#L171-L204
39,656
markfinger/cyclic-dependency-graph
src/graph.js
pruneDisconnectedNodes
function pruneDisconnectedNodes() { const previousState = state; const disconnected = findNodesDisconnectedFromEntryNodes(state); let updatedState = previousState; disconnected.forEach(name => { if (updatedState.has(name)) { const data = pruneNodeAndUniqueDependencies(updatedState, name); updatedState = data.nodes; } }); state = updatedState; return Diff({ from: previousState, to: state }); }
javascript
function pruneDisconnectedNodes() { const previousState = state; const disconnected = findNodesDisconnectedFromEntryNodes(state); let updatedState = previousState; disconnected.forEach(name => { if (updatedState.has(name)) { const data = pruneNodeAndUniqueDependencies(updatedState, name); updatedState = data.nodes; } }); state = updatedState; return Diff({ from: previousState, to: state }); }
[ "function", "pruneDisconnectedNodes", "(", ")", "{", "const", "previousState", "=", "state", ";", "const", "disconnected", "=", "findNodesDisconnectedFromEntryNodes", "(", "state", ")", ";", "let", "updatedState", "=", "previousState", ";", "disconnected", ".", "forEach", "(", "name", "=>", "{", "if", "(", "updatedState", ".", "has", "(", "name", ")", ")", "{", "const", "data", "=", "pruneNodeAndUniqueDependencies", "(", "updatedState", ",", "name", ")", ";", "updatedState", "=", "data", ".", "nodes", ";", "}", "}", ")", ";", "state", "=", "updatedState", ";", "return", "Diff", "(", "{", "from", ":", "previousState", ",", "to", ":", "state", "}", ")", ";", "}" ]
There are edge-cases where particular circular graphs may not have been pruned completely, so we may still be persisting references to nodes which are disconnected to the entry nodes. An easy example of a situation that can cause this is a tournament. https://en.wikipedia.org/wiki/Tournament_(graph_theory) To get around this problem, we need to walk the graph from the entry nodes, note any that are unreachable, and then prune them directly @returns {Diff}
[ "There", "are", "edge", "-", "cases", "where", "particular", "circular", "graphs", "may", "not", "have", "been", "pruned", "completely", "so", "we", "may", "still", "be", "persisting", "references", "to", "nodes", "which", "are", "disconnected", "to", "the", "entry", "nodes", "." ]
fac9249ec3a9d29199bed9fedcf99267b2c61c44
https://github.com/markfinger/cyclic-dependency-graph/blob/fac9249ec3a9d29199bed9fedcf99267b2c61c44/src/graph.js#L219-L237
39,657
markfinger/cyclic-dependency-graph
src/graph.js
setNodeAsEntry
function setNodeAsEntry(name) { const previousState = state; if (!isNodeDefined(state, name)) { state = addNode(state, name); } state = defineEntryNode(state, name); return Diff({ from: previousState, to: state }); }
javascript
function setNodeAsEntry(name) { const previousState = state; if (!isNodeDefined(state, name)) { state = addNode(state, name); } state = defineEntryNode(state, name); return Diff({ from: previousState, to: state }); }
[ "function", "setNodeAsEntry", "(", "name", ")", "{", "const", "previousState", "=", "state", ";", "if", "(", "!", "isNodeDefined", "(", "state", ",", "name", ")", ")", "{", "state", "=", "addNode", "(", "state", ",", "name", ")", ";", "}", "state", "=", "defineEntryNode", "(", "state", ",", "name", ")", ";", "return", "Diff", "(", "{", "from", ":", "previousState", ",", "to", ":", "state", "}", ")", ";", "}" ]
Dependency graphs emerge from one or more entry nodes. The ability to distinguish an entry node from a normal dependency node allows us to aggressively prune a node and all of its dependencies. As a basic example of why the concept is important, if `a -> b -> c` and we want to prune `b`, we know that we can safely prune `c` as well. But if `a -> b -> c -> a` and we want to prune `b`, then we need to know that `a` is an entry node, so that we don't traverse the cyclic graph and prune every node. This concept becomes increasingly important once we start dealing with more complicated cyclic graphs, as pruning can result in disconnected sub-graphs. For example, if we have `a -> b -> c -> d -> b` and we want to prune `a`, we can't safely prune `b -> c -> d -> b` as well, as `b` has a dependent `d`. However, if we don't prune them, then they are left disconnected from the other nodes. Hence we need to know a graph's entry points so that we can traverse it from the entries and find the nodes which are disconnected @param {String} name @returns {Diff}
[ "Dependency", "graphs", "emerge", "from", "one", "or", "more", "entry", "nodes", ".", "The", "ability", "to", "distinguish", "an", "entry", "node", "from", "a", "normal", "dependency", "node", "allows", "us", "to", "aggressively", "prune", "a", "node", "and", "all", "of", "its", "dependencies", "." ]
fac9249ec3a9d29199bed9fedcf99267b2c61c44
https://github.com/markfinger/cyclic-dependency-graph/blob/fac9249ec3a9d29199bed9fedcf99267b2c61c44/src/graph.js#L264-L277
39,658
Neil-G/redux-mastermind
lib/createUpdaterParts.js
processActionGroup
function processActionGroup(_ref2) { var _ref2$updateSchemaNam = _ref2.updateSchemaName, updateSchemaName = _ref2$updateSchemaNam === undefined ? undefined : _ref2$updateSchemaNam, _ref2$store = _ref2.store, store = _ref2$store === undefined ? _store : _ref2$store, _ref2$error = _ref2.error, error = _ref2$error === undefined ? {} : _ref2$error, _ref2$res = _ref2.res, res = _ref2$res === undefined ? {} : _ref2$res, _ref2$actionGroup = _ref2.actionGroup, actionGroup = _ref2$actionGroup === undefined ? {} : _ref2$actionGroup; if (actionGroup == undefined) return; var actionNames = Object.keys(actionGroup); actionNames.forEach(function (actionName) { var action = actionGroup[actionName]; // TODO: check for required fields: branch, location, operation, value || valueFunction, location || locationFunction // updateIn, update + updateIn, update // destructure action values used in processing var valueFunction = action.valueFunction, value = action.value, shouldDispatch = action.shouldDispatch, uiEventFunction = action.uiEventFunction, updateFunction = action.updateFunction, location = action.location, locationFunction = action.locationFunction, operation = action.operation; // create action to be processed var $action = {}; // update value $action.value = valueFunction ? valueFunction({ error: error, res: res, store: store, value: value }) : value; // update location $action.location = locationFunction ? locationFunction({ error: error, res: res, store: store, value: value }) : location; // add type $action.type = $action.location[0]; // trim first value from location $action.location = $action.location.slice(1); // add name $action.name = actionName; // add update function params $action.updateFunction = updateFunction ? updateFunction.bind(null, { res: res, error: error, store: store, fromJS: _immutable.fromJS, value: value }) : undefined; // add operation if ($action.updateFunction) { $action.operation = 'updateIn'; } else if (!$action.value) { $action.operation = 'deleteIn'; } else { $action.operation = 'setIn'; } // TODO: add meta information about the updateSchemaCreator // dispatch action depending on fire if (shouldDispatch == undefined || shouldDispatch({ error: error, res: res, store: store, value: value })) { // dispatch the action here store.dispatch($action); // fire ui event if (uiEventFunction) uiEventFunction({ action: action, value: value, res: res, error: error, store: store }); } }); }
javascript
function processActionGroup(_ref2) { var _ref2$updateSchemaNam = _ref2.updateSchemaName, updateSchemaName = _ref2$updateSchemaNam === undefined ? undefined : _ref2$updateSchemaNam, _ref2$store = _ref2.store, store = _ref2$store === undefined ? _store : _ref2$store, _ref2$error = _ref2.error, error = _ref2$error === undefined ? {} : _ref2$error, _ref2$res = _ref2.res, res = _ref2$res === undefined ? {} : _ref2$res, _ref2$actionGroup = _ref2.actionGroup, actionGroup = _ref2$actionGroup === undefined ? {} : _ref2$actionGroup; if (actionGroup == undefined) return; var actionNames = Object.keys(actionGroup); actionNames.forEach(function (actionName) { var action = actionGroup[actionName]; // TODO: check for required fields: branch, location, operation, value || valueFunction, location || locationFunction // updateIn, update + updateIn, update // destructure action values used in processing var valueFunction = action.valueFunction, value = action.value, shouldDispatch = action.shouldDispatch, uiEventFunction = action.uiEventFunction, updateFunction = action.updateFunction, location = action.location, locationFunction = action.locationFunction, operation = action.operation; // create action to be processed var $action = {}; // update value $action.value = valueFunction ? valueFunction({ error: error, res: res, store: store, value: value }) : value; // update location $action.location = locationFunction ? locationFunction({ error: error, res: res, store: store, value: value }) : location; // add type $action.type = $action.location[0]; // trim first value from location $action.location = $action.location.slice(1); // add name $action.name = actionName; // add update function params $action.updateFunction = updateFunction ? updateFunction.bind(null, { res: res, error: error, store: store, fromJS: _immutable.fromJS, value: value }) : undefined; // add operation if ($action.updateFunction) { $action.operation = 'updateIn'; } else if (!$action.value) { $action.operation = 'deleteIn'; } else { $action.operation = 'setIn'; } // TODO: add meta information about the updateSchemaCreator // dispatch action depending on fire if (shouldDispatch == undefined || shouldDispatch({ error: error, res: res, store: store, value: value })) { // dispatch the action here store.dispatch($action); // fire ui event if (uiEventFunction) uiEventFunction({ action: action, value: value, res: res, error: error, store: store }); } }); }
[ "function", "processActionGroup", "(", "_ref2", ")", "{", "var", "_ref2$updateSchemaNam", "=", "_ref2", ".", "updateSchemaName", ",", "updateSchemaName", "=", "_ref2$updateSchemaNam", "===", "undefined", "?", "undefined", ":", "_ref2$updateSchemaNam", ",", "_ref2$store", "=", "_ref2", ".", "store", ",", "store", "=", "_ref2$store", "===", "undefined", "?", "_store", ":", "_ref2$store", ",", "_ref2$error", "=", "_ref2", ".", "error", ",", "error", "=", "_ref2$error", "===", "undefined", "?", "{", "}", ":", "_ref2$error", ",", "_ref2$res", "=", "_ref2", ".", "res", ",", "res", "=", "_ref2$res", "===", "undefined", "?", "{", "}", ":", "_ref2$res", ",", "_ref2$actionGroup", "=", "_ref2", ".", "actionGroup", ",", "actionGroup", "=", "_ref2$actionGroup", "===", "undefined", "?", "{", "}", ":", "_ref2$actionGroup", ";", "if", "(", "actionGroup", "==", "undefined", ")", "return", ";", "var", "actionNames", "=", "Object", ".", "keys", "(", "actionGroup", ")", ";", "actionNames", ".", "forEach", "(", "function", "(", "actionName", ")", "{", "var", "action", "=", "actionGroup", "[", "actionName", "]", ";", "// TODO: check for required fields: branch, location, operation, value || valueFunction, location || locationFunction", "// updateIn, update + updateIn, update", "// destructure action values used in processing", "var", "valueFunction", "=", "action", ".", "valueFunction", ",", "value", "=", "action", ".", "value", ",", "shouldDispatch", "=", "action", ".", "shouldDispatch", ",", "uiEventFunction", "=", "action", ".", "uiEventFunction", ",", "updateFunction", "=", "action", ".", "updateFunction", ",", "location", "=", "action", ".", "location", ",", "locationFunction", "=", "action", ".", "locationFunction", ",", "operation", "=", "action", ".", "operation", ";", "// create action to be processed", "var", "$action", "=", "{", "}", ";", "// update value", "$action", ".", "value", "=", "valueFunction", "?", "valueFunction", "(", "{", "error", ":", "error", ",", "res", ":", "res", ",", "store", ":", "store", ",", "value", ":", "value", "}", ")", ":", "value", ";", "// update location", "$action", ".", "location", "=", "locationFunction", "?", "locationFunction", "(", "{", "error", ":", "error", ",", "res", ":", "res", ",", "store", ":", "store", ",", "value", ":", "value", "}", ")", ":", "location", ";", "// add type", "$action", ".", "type", "=", "$action", ".", "location", "[", "0", "]", ";", "// trim first value from location", "$action", ".", "location", "=", "$action", ".", "location", ".", "slice", "(", "1", ")", ";", "// add name", "$action", ".", "name", "=", "actionName", ";", "// add update function params", "$action", ".", "updateFunction", "=", "updateFunction", "?", "updateFunction", ".", "bind", "(", "null", ",", "{", "res", ":", "res", ",", "error", ":", "error", ",", "store", ":", "store", ",", "fromJS", ":", "_immutable", ".", "fromJS", ",", "value", ":", "value", "}", ")", ":", "undefined", ";", "// add operation", "if", "(", "$action", ".", "updateFunction", ")", "{", "$action", ".", "operation", "=", "'updateIn'", ";", "}", "else", "if", "(", "!", "$action", ".", "value", ")", "{", "$action", ".", "operation", "=", "'deleteIn'", ";", "}", "else", "{", "$action", ".", "operation", "=", "'setIn'", ";", "}", "// TODO: add meta information about the updateSchemaCreator", "// dispatch action depending on fire", "if", "(", "shouldDispatch", "==", "undefined", "||", "shouldDispatch", "(", "{", "error", ":", "error", ",", "res", ":", "res", ",", "store", ":", "store", ",", "value", ":", "value", "}", ")", ")", "{", "// dispatch the action here", "store", ".", "dispatch", "(", "$action", ")", ";", "// fire ui event", "if", "(", "uiEventFunction", ")", "uiEventFunction", "(", "{", "action", ":", "action", ",", "value", ":", "value", ",", "res", ":", "res", ",", "error", ":", "error", ",", "store", ":", "store", "}", ")", ";", "}", "}", ")", ";", "}" ]
this will process an object full of actions
[ "this", "will", "process", "an", "object", "full", "of", "actions" ]
669e2978b4a7cdd48fbd33d4fd6dbe47e92d3cef
https://github.com/Neil-G/redux-mastermind/blob/669e2978b4a7cdd48fbd33d4fd6dbe47e92d3cef/lib/createUpdaterParts.js#L18-L94
39,659
alexcjohnson/world-calendars
jquery-src/jquery.calendars.mayan.js
function(year) { var date = this._validate(year, this.minMonth, this.minDay, $.calendars.local.invalidYear); year = date.year(); var baktun = Math.floor(year / 400); year = year % 400; year += (year < 0 ? 400 : 0); var katun = Math.floor(year / 20); return baktun + '.' + katun + '.' + (year % 20); }
javascript
function(year) { var date = this._validate(year, this.minMonth, this.minDay, $.calendars.local.invalidYear); year = date.year(); var baktun = Math.floor(year / 400); year = year % 400; year += (year < 0 ? 400 : 0); var katun = Math.floor(year / 20); return baktun + '.' + katun + '.' + (year % 20); }
[ "function", "(", "year", ")", "{", "var", "date", "=", "this", ".", "_validate", "(", "year", ",", "this", ".", "minMonth", ",", "this", ".", "minDay", ",", "$", ".", "calendars", ".", "local", ".", "invalidYear", ")", ";", "year", "=", "date", ".", "year", "(", ")", ";", "var", "baktun", "=", "Math", ".", "floor", "(", "year", "/", "400", ")", ";", "year", "=", "year", "%", "400", ";", "year", "+=", "(", "year", "<", "0", "?", "400", ":", "0", ")", ";", "var", "katun", "=", "Math", ".", "floor", "(", "year", "/", "20", ")", ";", "return", "baktun", "+", "'.'", "+", "katun", "+", "'.'", "+", "(", "year", "%", "20", ")", ";", "}" ]
Format the year, if not a simple sequential number. @memberof MayanCalendar @param year {CDate|number} The date to format or the year to format. @return {string} The formatted year. @throws Error if an invalid year or a different calendar used.
[ "Format", "the", "year", "if", "not", "a", "simple", "sequential", "number", "." ]
810693882512dec1b804456f8d435b962bd6cf31
https://github.com/alexcjohnson/world-calendars/blob/810693882512dec1b804456f8d435b962bd6cf31/jquery-src/jquery.calendars.mayan.js#L96-L104
39,660
alexcjohnson/world-calendars
jquery-src/jquery.calendars.mayan.js
function(years) { years = years.split('.'); if (years.length < 3) { throw 'Invalid Mayan year'; } var year = 0; for (var i = 0; i < years.length; i++) { var y = parseInt(years[i], 10); if (Math.abs(y) > 19 || (i > 0 && y < 0)) { throw 'Invalid Mayan year'; } year = year * 20 + y; } return year; }
javascript
function(years) { years = years.split('.'); if (years.length < 3) { throw 'Invalid Mayan year'; } var year = 0; for (var i = 0; i < years.length; i++) { var y = parseInt(years[i], 10); if (Math.abs(y) > 19 || (i > 0 && y < 0)) { throw 'Invalid Mayan year'; } year = year * 20 + y; } return year; }
[ "function", "(", "years", ")", "{", "years", "=", "years", ".", "split", "(", "'.'", ")", ";", "if", "(", "years", ".", "length", "<", "3", ")", "{", "throw", "'Invalid Mayan year'", ";", "}", "var", "year", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "years", ".", "length", ";", "i", "++", ")", "{", "var", "y", "=", "parseInt", "(", "years", "[", "i", "]", ",", "10", ")", ";", "if", "(", "Math", ".", "abs", "(", "y", ")", ">", "19", "||", "(", "i", ">", "0", "&&", "y", "<", "0", ")", ")", "{", "throw", "'Invalid Mayan year'", ";", "}", "year", "=", "year", "*", "20", "+", "y", ";", "}", "return", "year", ";", "}" ]
Convert from the formatted year back to a single number. @memberof MayanCalendar @param years {string} The year as n.n.n. @return {number} The sequential year. @throws Error if an invalid value is supplied.
[ "Convert", "from", "the", "formatted", "year", "back", "to", "a", "single", "number", "." ]
810693882512dec1b804456f8d435b962bd6cf31
https://github.com/alexcjohnson/world-calendars/blob/810693882512dec1b804456f8d435b962bd6cf31/jquery-src/jquery.calendars.mayan.js#L111-L125
39,661
alexcjohnson/world-calendars
jquery-src/jquery.calendars.mayan.js
function(year, month, day) { var date = this._validate(year, month, day, $.calendars.local.invalidDate); var jd = date.toJD(); var haab = this._toHaab(jd); var tzolkin = this._toTzolkin(jd); return {haabMonthName: this.local.haabMonths[haab[0] - 1], haabMonth: haab[0], haabDay: haab[1], tzolkinDayName: this.local.tzolkinMonths[tzolkin[0] - 1], tzolkinDay: tzolkin[0], tzolkinTrecena: tzolkin[1]}; }
javascript
function(year, month, day) { var date = this._validate(year, month, day, $.calendars.local.invalidDate); var jd = date.toJD(); var haab = this._toHaab(jd); var tzolkin = this._toTzolkin(jd); return {haabMonthName: this.local.haabMonths[haab[0] - 1], haabMonth: haab[0], haabDay: haab[1], tzolkinDayName: this.local.tzolkinMonths[tzolkin[0] - 1], tzolkinDay: tzolkin[0], tzolkinTrecena: tzolkin[1]}; }
[ "function", "(", "year", ",", "month", ",", "day", ")", "{", "var", "date", "=", "this", ".", "_validate", "(", "year", ",", "month", ",", "day", ",", "$", ".", "calendars", ".", "local", ".", "invalidDate", ")", ";", "var", "jd", "=", "date", ".", "toJD", "(", ")", ";", "var", "haab", "=", "this", ".", "_toHaab", "(", "jd", ")", ";", "var", "tzolkin", "=", "this", ".", "_toTzolkin", "(", "jd", ")", ";", "return", "{", "haabMonthName", ":", "this", ".", "local", ".", "haabMonths", "[", "haab", "[", "0", "]", "-", "1", "]", ",", "haabMonth", ":", "haab", "[", "0", "]", ",", "haabDay", ":", "haab", "[", "1", "]", ",", "tzolkinDayName", ":", "this", ".", "local", ".", "tzolkinMonths", "[", "tzolkin", "[", "0", "]", "-", "1", "]", ",", "tzolkinDay", ":", "tzolkin", "[", "0", "]", ",", "tzolkinTrecena", ":", "tzolkin", "[", "1", "]", "}", ";", "}" ]
Retrieve additional information about a date - Haab and Tzolkin equivalents. @memberof MayanCalendar @param year {CDate|number} The date to examine or the year to examine. @param [month] {number} The month to examine. @param [day] {number} The day to examine. @return {object} Additional information - contents depends on calendar. @throws Error if an invalid date or a different calendar used.
[ "Retrieve", "additional", "information", "about", "a", "date", "-", "Haab", "and", "Tzolkin", "equivalents", "." ]
810693882512dec1b804456f8d435b962bd6cf31
https://github.com/alexcjohnson/world-calendars/blob/810693882512dec1b804456f8d435b962bd6cf31/jquery-src/jquery.calendars.mayan.js#L208-L217
39,662
alexcjohnson/world-calendars
jquery-src/jquery.calendars.mayan.js
function(jd) { jd -= this.jdEpoch; var day = mod(jd + 8 + ((18 - 1) * 20), 365); return [Math.floor(day / 20) + 1, mod(day, 20)]; }
javascript
function(jd) { jd -= this.jdEpoch; var day = mod(jd + 8 + ((18 - 1) * 20), 365); return [Math.floor(day / 20) + 1, mod(day, 20)]; }
[ "function", "(", "jd", ")", "{", "jd", "-=", "this", ".", "jdEpoch", ";", "var", "day", "=", "mod", "(", "jd", "+", "8", "+", "(", "(", "18", "-", "1", ")", "*", "20", ")", ",", "365", ")", ";", "return", "[", "Math", ".", "floor", "(", "day", "/", "20", ")", "+", "1", ",", "mod", "(", "day", ",", "20", ")", "]", ";", "}" ]
Retrieve Haab date from a Julian date. @memberof MayanCalendar @private @param jd {number} The Julian date. @return {number[]} Corresponding Haab month and day.
[ "Retrieve", "Haab", "date", "from", "a", "Julian", "date", "." ]
810693882512dec1b804456f8d435b962bd6cf31
https://github.com/alexcjohnson/world-calendars/blob/810693882512dec1b804456f8d435b962bd6cf31/jquery-src/jquery.calendars.mayan.js#L224-L228
39,663
S3bb1/ah-dashboard-plugin
public/dashboard/bower_components/admin-lte/plugins/datatables/extensions/FixedHeader/js/dataTables.fixedHeader.js
function ( source, dest ) { var that = this; if ( source.nodeName.toUpperCase() === "TR" || source.nodeName.toUpperCase() === "TH" || source.nodeName.toUpperCase() === "TD" || source.nodeName.toUpperCase() === "SPAN" ) { dest.className = source.className; } $(source).children().each( function (i) { that._fnClassUpdate( $(source).children()[i], $(dest).children()[i] ); } ); }
javascript
function ( source, dest ) { var that = this; if ( source.nodeName.toUpperCase() === "TR" || source.nodeName.toUpperCase() === "TH" || source.nodeName.toUpperCase() === "TD" || source.nodeName.toUpperCase() === "SPAN" ) { dest.className = source.className; } $(source).children().each( function (i) { that._fnClassUpdate( $(source).children()[i], $(dest).children()[i] ); } ); }
[ "function", "(", "source", ",", "dest", ")", "{", "var", "that", "=", "this", ";", "if", "(", "source", ".", "nodeName", ".", "toUpperCase", "(", ")", "===", "\"TR\"", "||", "source", ".", "nodeName", ".", "toUpperCase", "(", ")", "===", "\"TH\"", "||", "source", ".", "nodeName", ".", "toUpperCase", "(", ")", "===", "\"TD\"", "||", "source", ".", "nodeName", ".", "toUpperCase", "(", ")", "===", "\"SPAN\"", ")", "{", "dest", ".", "className", "=", "source", ".", "className", ";", "}", "$", "(", "source", ")", ".", "children", "(", ")", ".", "each", "(", "function", "(", "i", ")", "{", "that", ".", "_fnClassUpdate", "(", "$", "(", "source", ")", ".", "children", "(", ")", "[", "i", "]", ",", "$", "(", "dest", ")", ".", "children", "(", ")", "[", "i", "]", ")", ";", "}", ")", ";", "}" ]
Copy the classes of all child nodes from one element to another. This implies that the two have identical structure - no error checking is performed to that fact. @param {element} source Node to copy classes from @param {element} dest Node to copy classes too
[ "Copy", "the", "classes", "of", "all", "child", "nodes", "from", "one", "element", "to", "another", ".", "This", "implies", "that", "the", "two", "have", "identical", "structure", "-", "no", "error", "checking", "is", "performed", "to", "that", "fact", "." ]
c283370ec0f99a25db5bb7029a98b4febf8c5251
https://github.com/S3bb1/ah-dashboard-plugin/blob/c283370ec0f99a25db5bb7029a98b4febf8c5251/public/dashboard/bower_components/admin-lte/plugins/datatables/extensions/FixedHeader/js/dataTables.fixedHeader.js#L669-L682
39,664
S3bb1/ah-dashboard-plugin
public/dashboard/bower_components/admin-lte/plugins/datatables/extensions/FixedHeader/js/dataTables.fixedHeader.js
function ( parent, original, clone ) { var that = this; var originals = $(parent +' tr', original); var height; $(parent+' tr', clone).each( function (k) { height = originals.eq( k ).css('height'); // This is nasty :-(. IE has a sub-pixel error even when setting // the height below (the Firefox fix) which causes the fixed column // to go out of alignment. Need to add a pixel before the assignment // Can this be feature detected? Not sure how... if ( navigator.appName == 'Microsoft Internet Explorer' ) { height = parseInt( height, 10 ) + 1; } $(this).css( 'height', height ); // For Firefox to work, we need to also set the height of the // original row, to the value that we read from it! Otherwise there // is a sub-pixel rounding error originals.eq( k ).css( 'height', height ); } ); }
javascript
function ( parent, original, clone ) { var that = this; var originals = $(parent +' tr', original); var height; $(parent+' tr', clone).each( function (k) { height = originals.eq( k ).css('height'); // This is nasty :-(. IE has a sub-pixel error even when setting // the height below (the Firefox fix) which causes the fixed column // to go out of alignment. Need to add a pixel before the assignment // Can this be feature detected? Not sure how... if ( navigator.appName == 'Microsoft Internet Explorer' ) { height = parseInt( height, 10 ) + 1; } $(this).css( 'height', height ); // For Firefox to work, we need to also set the height of the // original row, to the value that we read from it! Otherwise there // is a sub-pixel rounding error originals.eq( k ).css( 'height', height ); } ); }
[ "function", "(", "parent", ",", "original", ",", "clone", ")", "{", "var", "that", "=", "this", ";", "var", "originals", "=", "$", "(", "parent", "+", "' tr'", ",", "original", ")", ";", "var", "height", ";", "$", "(", "parent", "+", "' tr'", ",", "clone", ")", ".", "each", "(", "function", "(", "k", ")", "{", "height", "=", "originals", ".", "eq", "(", "k", ")", ".", "css", "(", "'height'", ")", ";", "// This is nasty :-(. IE has a sub-pixel error even when setting", "// the height below (the Firefox fix) which causes the fixed column", "// to go out of alignment. Need to add a pixel before the assignment", "// Can this be feature detected? Not sure how...", "if", "(", "navigator", ".", "appName", "==", "'Microsoft Internet Explorer'", ")", "{", "height", "=", "parseInt", "(", "height", ",", "10", ")", "+", "1", ";", "}", "$", "(", "this", ")", ".", "css", "(", "'height'", ",", "height", ")", ";", "// For Firefox to work, we need to also set the height of the", "// original row, to the value that we read from it! Otherwise there", "// is a sub-pixel rounding error", "originals", ".", "eq", "(", "k", ")", ".", "css", "(", "'height'", ",", "height", ")", ";", "}", ")", ";", "}" ]
Equalise the heights of the rows in a given table node in a cross browser way. Note that this is more or less lifted as is from FixedColumns @method fnEqualiseHeights @returns void @param {string} parent Node type - thead, tbody or tfoot @param {element} original Original node to take the heights from @param {element} clone Copy the heights to @private
[ "Equalise", "the", "heights", "of", "the", "rows", "in", "a", "given", "table", "node", "in", "a", "cross", "browser", "way", ".", "Note", "that", "this", "is", "more", "or", "less", "lifted", "as", "is", "from", "FixedColumns" ]
c283370ec0f99a25db5bb7029a98b4febf8c5251
https://github.com/S3bb1/ah-dashboard-plugin/blob/c283370ec0f99a25db5bb7029a98b4febf8c5251/public/dashboard/bower_components/admin-lte/plugins/datatables/extensions/FixedHeader/js/dataTables.fixedHeader.js#L894-L918
39,665
apigee-internal/rbac-abacus
npm/bizancio.js
getCollector
function getCollector() { var collector = new Collector(); if (global['__coverage__']) { collector.add(global['__coverage__']); } else { console.error('No global coverage found for the node process'); } return collector; }
javascript
function getCollector() { var collector = new Collector(); if (global['__coverage__']) { collector.add(global['__coverage__']); } else { console.error('No global coverage found for the node process'); } return collector; }
[ "function", "getCollector", "(", ")", "{", "var", "collector", "=", "new", "Collector", "(", ")", ";", "if", "(", "global", "[", "'__coverage__'", "]", ")", "{", "collector", ".", "add", "(", "global", "[", "'__coverage__'", "]", ")", ";", "}", "else", "{", "console", ".", "error", "(", "'No global coverage found for the node process'", ")", ";", "}", "return", "collector", ";", "}" ]
returns the coverage collector, creating one and automatically adding the contents of the global coverage object. You can use this method in an exit handler to get the accumulated coverage.
[ "returns", "the", "coverage", "collector", "creating", "one", "and", "automatically", "adding", "the", "contents", "of", "the", "global", "coverage", "object", ".", "You", "can", "use", "this", "method", "in", "an", "exit", "handler", "to", "get", "the", "accumulated", "coverage", "." ]
6b3929194c0adf5adf3b9571fe0f25390c981f88
https://github.com/apigee-internal/rbac-abacus/blob/6b3929194c0adf5adf3b9571fe0f25390c981f88/npm/bizancio.js#L33-L42
39,666
smbape/node-umd-builder
lib/compilers/jst/template.js
template
function template(string, options, otherOptions) { // Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/) // and Laura Doktorova's doT.js (https://github.com/olado/doT). const settings = templateSettings; if (otherOptions && isIterateeCall(string, options, otherOptions)) { options = otherOptions = undefined; } string = baseToString(string); options = extendWith({ ignore: reIgnore }, otherOptions || options, settings, extendDefaults); const imports = extendWith({}, options.imports, settings.imports, extendDefaults); const importsKeys = keys(imports); const importsValues = baseValues(imports, importsKeys); let isEscaping, isEvaluating; let index = 0; const interpolate = options.interpolate || reNoMatch; let source = ["__p[__p.length] = '"]; // Compile the regexp to match each delimiter. const reDelimiters = RegExp( (options.ignore || reNoMatch).source + "|" + (options.escape || reNoMatch).source + "|" + interpolate.source + "|" + (options.esInterpolate !== false && interpolate.source === reInterpolate.source ? reEsTemplate : reNoMatch).source + "|" + (options.evaluate || reNoMatch).source + "|$", "g"); // Use a sourceURL for easier debugging. const sourceURL = "//# sourceURL=" + ("sourceURL" in options ? options.sourceURL : "lodash.templateSources[" + ++templateCounter + "]") + "\n"; string.replace(reDelimiters, function(match, ignoreValue, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { if (!interpolateValue) { interpolateValue = esTemplateValue; } // Escape characters that can't be included in string literals. source.push(string.slice(index, offset).replace(reUnescapedString, escapeStringChar)); if (!ignoreValue) { // Replace delimiters with snippets. if (escapeValue) { isEscaping = true; source.push("' +\n__e(" + escapeValue + ") +\n'"); } if (evaluateValue) { isEvaluating = true; source.push("';\n" + evaluateValue + ";\n__p[__p.length] = '"); } if (interpolateValue) { source.push("' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"); } } index = offset + match.length; // The JS engine embedded in Adobe products requires returning the `match` // string in order to produce the correct `offset` value. return match; }); source.push("';\n"); source = source.join(""); // If `variable` is not specified wrap a with-statement around the generated // code to add the data object to the top of the scope chain. let variable = options.variable; if (variable == null) { source = "with (obj) {\n" + source + "\n}\n"; variable = "obj"; } // Cleanup code by stripping empty strings. source = isEvaluating ? source.replace(reEmptyStringLeading, "") : source; source = source.replace(reEmptyStringMiddle, "$1").replace(reEmptyStringTrailing, "$1;"); // Frame code as the function body. const declaration = options.async ? "async function" : "function"; source = declaration + "(" + variable + ") {\n" + "if (" + variable + " == null) { " + variable + " = {}; }\n" + "var __t, __p = []" + (isEscaping ? ", __e = _.escape" : "") + (isEvaluating ? ", __j = Array.prototype.join;\n" + "function print() { __p[__p.length] = __j.call(arguments, '') }\n" : ";\n" ) + source + "return __p.join(\"\")\n};"; const result = attempt(function() { // eslint-disable-next-line no-new-func return Function(importsKeys, sourceURL + "return " + source).apply(undefined, importsValues); }); // Provide the compiled function's source by its `toString` method or // the `source` property as a convenience for inlining compiled templates. result.source = source; if (isError(result)) { throw result; } return result; }
javascript
function template(string, options, otherOptions) { // Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/) // and Laura Doktorova's doT.js (https://github.com/olado/doT). const settings = templateSettings; if (otherOptions && isIterateeCall(string, options, otherOptions)) { options = otherOptions = undefined; } string = baseToString(string); options = extendWith({ ignore: reIgnore }, otherOptions || options, settings, extendDefaults); const imports = extendWith({}, options.imports, settings.imports, extendDefaults); const importsKeys = keys(imports); const importsValues = baseValues(imports, importsKeys); let isEscaping, isEvaluating; let index = 0; const interpolate = options.interpolate || reNoMatch; let source = ["__p[__p.length] = '"]; // Compile the regexp to match each delimiter. const reDelimiters = RegExp( (options.ignore || reNoMatch).source + "|" + (options.escape || reNoMatch).source + "|" + interpolate.source + "|" + (options.esInterpolate !== false && interpolate.source === reInterpolate.source ? reEsTemplate : reNoMatch).source + "|" + (options.evaluate || reNoMatch).source + "|$", "g"); // Use a sourceURL for easier debugging. const sourceURL = "//# sourceURL=" + ("sourceURL" in options ? options.sourceURL : "lodash.templateSources[" + ++templateCounter + "]") + "\n"; string.replace(reDelimiters, function(match, ignoreValue, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { if (!interpolateValue) { interpolateValue = esTemplateValue; } // Escape characters that can't be included in string literals. source.push(string.slice(index, offset).replace(reUnescapedString, escapeStringChar)); if (!ignoreValue) { // Replace delimiters with snippets. if (escapeValue) { isEscaping = true; source.push("' +\n__e(" + escapeValue + ") +\n'"); } if (evaluateValue) { isEvaluating = true; source.push("';\n" + evaluateValue + ";\n__p[__p.length] = '"); } if (interpolateValue) { source.push("' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"); } } index = offset + match.length; // The JS engine embedded in Adobe products requires returning the `match` // string in order to produce the correct `offset` value. return match; }); source.push("';\n"); source = source.join(""); // If `variable` is not specified wrap a with-statement around the generated // code to add the data object to the top of the scope chain. let variable = options.variable; if (variable == null) { source = "with (obj) {\n" + source + "\n}\n"; variable = "obj"; } // Cleanup code by stripping empty strings. source = isEvaluating ? source.replace(reEmptyStringLeading, "") : source; source = source.replace(reEmptyStringMiddle, "$1").replace(reEmptyStringTrailing, "$1;"); // Frame code as the function body. const declaration = options.async ? "async function" : "function"; source = declaration + "(" + variable + ") {\n" + "if (" + variable + " == null) { " + variable + " = {}; }\n" + "var __t, __p = []" + (isEscaping ? ", __e = _.escape" : "") + (isEvaluating ? ", __j = Array.prototype.join;\n" + "function print() { __p[__p.length] = __j.call(arguments, '') }\n" : ";\n" ) + source + "return __p.join(\"\")\n};"; const result = attempt(function() { // eslint-disable-next-line no-new-func return Function(importsKeys, sourceURL + "return " + source).apply(undefined, importsValues); }); // Provide the compiled function's source by its `toString` method or // the `source` property as a convenience for inlining compiled templates. result.source = source; if (isError(result)) { throw result; } return result; }
[ "function", "template", "(", "string", ",", "options", ",", "otherOptions", ")", "{", "// Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/)", "// and Laura Doktorova's doT.js (https://github.com/olado/doT).", "const", "settings", "=", "templateSettings", ";", "if", "(", "otherOptions", "&&", "isIterateeCall", "(", "string", ",", "options", ",", "otherOptions", ")", ")", "{", "options", "=", "otherOptions", "=", "undefined", ";", "}", "string", "=", "baseToString", "(", "string", ")", ";", "options", "=", "extendWith", "(", "{", "ignore", ":", "reIgnore", "}", ",", "otherOptions", "||", "options", ",", "settings", ",", "extendDefaults", ")", ";", "const", "imports", "=", "extendWith", "(", "{", "}", ",", "options", ".", "imports", ",", "settings", ".", "imports", ",", "extendDefaults", ")", ";", "const", "importsKeys", "=", "keys", "(", "imports", ")", ";", "const", "importsValues", "=", "baseValues", "(", "imports", ",", "importsKeys", ")", ";", "let", "isEscaping", ",", "isEvaluating", ";", "let", "index", "=", "0", ";", "const", "interpolate", "=", "options", ".", "interpolate", "||", "reNoMatch", ";", "let", "source", "=", "[", "\"__p[__p.length] = '\"", "]", ";", "// Compile the regexp to match each delimiter.", "const", "reDelimiters", "=", "RegExp", "(", "(", "options", ".", "ignore", "||", "reNoMatch", ")", ".", "source", "+", "\"|\"", "+", "(", "options", ".", "escape", "||", "reNoMatch", ")", ".", "source", "+", "\"|\"", "+", "interpolate", ".", "source", "+", "\"|\"", "+", "(", "options", ".", "esInterpolate", "!==", "false", "&&", "interpolate", ".", "source", "===", "reInterpolate", ".", "source", "?", "reEsTemplate", ":", "reNoMatch", ")", ".", "source", "+", "\"|\"", "+", "(", "options", ".", "evaluate", "||", "reNoMatch", ")", ".", "source", "+", "\"|$\"", ",", "\"g\"", ")", ";", "// Use a sourceURL for easier debugging.", "const", "sourceURL", "=", "\"//# sourceURL=\"", "+", "(", "\"sourceURL\"", "in", "options", "?", "options", ".", "sourceURL", ":", "\"lodash.templateSources[\"", "+", "++", "templateCounter", "+", "\"]\"", ")", "+", "\"\\n\"", ";", "string", ".", "replace", "(", "reDelimiters", ",", "function", "(", "match", ",", "ignoreValue", ",", "escapeValue", ",", "interpolateValue", ",", "esTemplateValue", ",", "evaluateValue", ",", "offset", ")", "{", "if", "(", "!", "interpolateValue", ")", "{", "interpolateValue", "=", "esTemplateValue", ";", "}", "// Escape characters that can't be included in string literals.", "source", ".", "push", "(", "string", ".", "slice", "(", "index", ",", "offset", ")", ".", "replace", "(", "reUnescapedString", ",", "escapeStringChar", ")", ")", ";", "if", "(", "!", "ignoreValue", ")", "{", "// Replace delimiters with snippets.", "if", "(", "escapeValue", ")", "{", "isEscaping", "=", "true", ";", "source", ".", "push", "(", "\"' +\\n__e(\"", "+", "escapeValue", "+", "\") +\\n'\"", ")", ";", "}", "if", "(", "evaluateValue", ")", "{", "isEvaluating", "=", "true", ";", "source", ".", "push", "(", "\"';\\n\"", "+", "evaluateValue", "+", "\";\\n__p[__p.length] = '\"", ")", ";", "}", "if", "(", "interpolateValue", ")", "{", "source", ".", "push", "(", "\"' +\\n((__t = (\"", "+", "interpolateValue", "+", "\")) == null ? '' : __t) +\\n'\"", ")", ";", "}", "}", "index", "=", "offset", "+", "match", ".", "length", ";", "// The JS engine embedded in Adobe products requires returning the `match`", "// string in order to produce the correct `offset` value.", "return", "match", ";", "}", ")", ";", "source", ".", "push", "(", "\"';\\n\"", ")", ";", "source", "=", "source", ".", "join", "(", "\"\"", ")", ";", "// If `variable` is not specified wrap a with-statement around the generated", "// code to add the data object to the top of the scope chain.", "let", "variable", "=", "options", ".", "variable", ";", "if", "(", "variable", "==", "null", ")", "{", "source", "=", "\"with (obj) {\\n\"", "+", "source", "+", "\"\\n}\\n\"", ";", "variable", "=", "\"obj\"", ";", "}", "// Cleanup code by stripping empty strings.", "source", "=", "isEvaluating", "?", "source", ".", "replace", "(", "reEmptyStringLeading", ",", "\"\"", ")", ":", "source", ";", "source", "=", "source", ".", "replace", "(", "reEmptyStringMiddle", ",", "\"$1\"", ")", ".", "replace", "(", "reEmptyStringTrailing", ",", "\"$1;\"", ")", ";", "// Frame code as the function body.", "const", "declaration", "=", "options", ".", "async", "?", "\"async function\"", ":", "\"function\"", ";", "source", "=", "declaration", "+", "\"(\"", "+", "variable", "+", "\") {\\n\"", "+", "\"if (\"", "+", "variable", "+", "\" == null) { \"", "+", "variable", "+", "\" = {}; }\\n\"", "+", "\"var __t, __p = []\"", "+", "(", "isEscaping", "?", "\", __e = _.escape\"", ":", "\"\"", ")", "+", "(", "isEvaluating", "?", "\", __j = Array.prototype.join;\\n\"", "+", "\"function print() { __p[__p.length] = __j.call(arguments, '') }\\n\"", ":", "\";\\n\"", ")", "+", "source", "+", "\"return __p.join(\\\"\\\")\\n};\"", ";", "const", "result", "=", "attempt", "(", "function", "(", ")", "{", "// eslint-disable-next-line no-new-func", "return", "Function", "(", "importsKeys", ",", "sourceURL", "+", "\"return \"", "+", "source", ")", ".", "apply", "(", "undefined", ",", "importsValues", ")", ";", "}", ")", ";", "// Provide the compiled function's source by its `toString` method or", "// the `source` property as a convenience for inlining compiled templates.", "result", ".", "source", "=", "source", ";", "if", "(", "isError", "(", "result", ")", ")", "{", "throw", "result", ";", "}", "return", "result", ";", "}" ]
Creates a compiled template function that can interpolate data properties in "interpolate" delimiters, HTML-escape interpolated data properties in "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data properties may be accessed as free variables in the template. If a setting object is provided it takes precedence over `_.templateSettings` values. **Note:** In the development build `_.template` utilizes [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) for easier debugging. For more information on precompiling templates see [lodash's custom builds documentation](https://lodash.com/custom-builds). For more information on Chrome extension sandboxes see [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). @static @memberOf _ @category String @param {string} [string=''] The template string. @param {Object} [options] The options object. @param {RegExp} [options.escape] The HTML "escape" delimiter. @param {RegExp} [options.evaluate] The "evaluate" delimiter. @param {Object} [options.imports] An object to import into the template as free variables. @param {RegExp} [options.interpolate] The "interpolate" delimiter. @param {string} [options.sourceURL] The sourceURL of the template's compiled source. @param {string} [options.variable] The data object variable name. @param- {Object} [otherOptions] Enables the legacy `options` param signature. @returns {Function} Returns the compiled template function. @example // using the "interpolate" delimiter to create a compiled template let compiled = _.template('hello <%= user %>!'); compiled({ 'user': 'fred' }); // => 'hello fred!' // using the HTML "escape" delimiter to escape data property values let compiled = _.template('<b><%- value %></b>'); compiled({ 'value': '<script>' }); // => '<b>&lt;script&gt;</b>' // using the "evaluate" delimiter to execute JavaScript and generate HTML let compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>'); compiled({ 'users': ['fred', 'barney'] }); // => '<li>fred</li><li>barney</li>' // using the internal `print` function in "evaluate" delimiters let compiled = _.template('<% print("hello " + user); %>!'); compiled({ 'user': 'barney' }); // => 'hello barney!' // using the ES delimiter as an alternative to the default "interpolate" delimiter let compiled = _.template('hello ${ user }!'); compiled({ 'user': 'pebbles' }); // => 'hello pebbles!' // using custom template delimiters _.templateSettings.interpolate = /{{([\s\S]+?)}}/g; let compiled = _.template('hello {{ user }}!'); compiled({ 'user': 'mustache' }); // => 'hello mustache!' // using backslashes to treat delimiters as plain text let compiled = _.template('<%= "\\<%- value %\\>" %>'); compiled({ 'value': 'ignored' }); // => '<%- value %>' // using the `imports` option to import `jQuery` as `jq` let text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>'; let compiled = _.template(text, { 'imports': { 'jq': jQuery } }); compiled({ 'users': ['fred', 'barney'] }); // => '<li>fred</li><li>barney</li>' // using the `sourceURL` option to specify a custom sourceURL for the template let compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' }); compiled(data); // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector // using the `variable` option to ensure a with-statement isn't used in the compiled template let compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' }); compiled.source; // => function(data) { // var __t, __p = []; // __p[__p.length] = 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!'; // return __p; // } // using the `source` property to inline compiled templates for meaningful // line numbers in error messages and a stack trace fs.writeFileSync(path.join(cwd, 'jst.js'), '\ let JST = {\ "main": ' + _.template(mainText).source + '\ };\ ');
[ "Creates", "a", "compiled", "template", "function", "that", "can", "interpolate", "data", "properties", "in", "interpolate", "delimiters", "HTML", "-", "escape", "interpolated", "data", "properties", "in", "escape", "delimiters", "and", "execute", "JavaScript", "in", "evaluate", "delimiters", ".", "Data", "properties", "may", "be", "accessed", "as", "free", "variables", "in", "the", "template", ".", "If", "a", "setting", "object", "is", "provided", "it", "takes", "precedence", "over", "_", ".", "templateSettings", "values", "." ]
73b03e8c985f2660948f5df71140e4a8fb162549
https://github.com/smbape/node-umd-builder/blob/73b03e8c985f2660948f5df71140e4a8fb162549/lib/compilers/jst/template.js#L258-L360
39,667
S3bb1/ah-dashboard-plugin
public/dashboard/bower_components/fancytree/dist/src/jquery.fancytree.debug.js
function(ctx, force, deep, collapsed){ // ctx.tree.debug("**** PROFILER nodeRender"); var s = this.options.prefix + "render '" + ctx.node + "'"; /*jshint expr:true */ window.console && window.console.time && window.console.time(s); this._super(ctx, force, deep, collapsed); window.console && window.console.timeEnd && window.console.timeEnd(s); }
javascript
function(ctx, force, deep, collapsed){ // ctx.tree.debug("**** PROFILER nodeRender"); var s = this.options.prefix + "render '" + ctx.node + "'"; /*jshint expr:true */ window.console && window.console.time && window.console.time(s); this._super(ctx, force, deep, collapsed); window.console && window.console.timeEnd && window.console.timeEnd(s); }
[ "function", "(", "ctx", ",", "force", ",", "deep", ",", "collapsed", ")", "{", "// ctx.tree.debug(\"**** PROFILER nodeRender\");", "var", "s", "=", "this", ".", "options", ".", "prefix", "+", "\"render '\"", "+", "ctx", ".", "node", "+", "\"'\"", ";", "/*jshint expr:true */", "window", ".", "console", "&&", "window", ".", "console", ".", "time", "&&", "window", ".", "console", ".", "time", "(", "s", ")", ";", "this", ".", "_super", "(", "ctx", ",", "force", ",", "deep", ",", "collapsed", ")", ";", "window", ".", "console", "&&", "window", ".", "console", ".", "timeEnd", "&&", "window", ".", "console", ".", "timeEnd", "(", "s", ")", ";", "}" ]
Overide virtual methods for this extension
[ "Overide", "virtual", "methods", "for", "this", "extension" ]
c283370ec0f99a25db5bb7029a98b4febf8c5251
https://github.com/S3bb1/ah-dashboard-plugin/blob/c283370ec0f99a25db5bb7029a98b4febf8c5251/public/dashboard/bower_components/fancytree/dist/src/jquery.fancytree.debug.js#L133-L140
39,668
tentwentyfour/helpbox
source/create-error-type.js
createErrorType
function createErrorType(initialize = undefined, ErrorClass = undefined, prototype = undefined) { ErrorClass = ErrorClass || Error; let Constructor = function (message) { let error = Object.create(Constructor.prototype); error.message = message; error.stack = (new Error).stack; if (initialize) { initialize(error, message); } return error; }; Constructor.prototype = Object.assign(Object.create(ErrorClass.prototype), prototype); return Constructor; }
javascript
function createErrorType(initialize = undefined, ErrorClass = undefined, prototype = undefined) { ErrorClass = ErrorClass || Error; let Constructor = function (message) { let error = Object.create(Constructor.prototype); error.message = message; error.stack = (new Error).stack; if (initialize) { initialize(error, message); } return error; }; Constructor.prototype = Object.assign(Object.create(ErrorClass.prototype), prototype); return Constructor; }
[ "function", "createErrorType", "(", "initialize", "=", "undefined", ",", "ErrorClass", "=", "undefined", ",", "prototype", "=", "undefined", ")", "{", "ErrorClass", "=", "ErrorClass", "||", "Error", ";", "let", "Constructor", "=", "function", "(", "message", ")", "{", "let", "error", "=", "Object", ".", "create", "(", "Constructor", ".", "prototype", ")", ";", "error", ".", "message", "=", "message", ";", "error", ".", "stack", "=", "(", "new", "Error", ")", ".", "stack", ";", "if", "(", "initialize", ")", "{", "initialize", "(", "error", ",", "message", ")", ";", "}", "return", "error", ";", "}", ";", "Constructor", ".", "prototype", "=", "Object", ".", "assign", "(", "Object", ".", "create", "(", "ErrorClass", ".", "prototype", ")", ",", "prototype", ")", ";", "return", "Constructor", ";", "}" ]
Return a constructor for a new error type. @function createErrorType @param initialize {Function} A function that gets passed the constructed error and the passed message and runs during the construction of new instances. @param ErrorClass {Function} An error class you wish to subclass. Defaults to Error. @param prototype {Object} Additional properties and methods for the new error type. @return {Function} The constructor for the new error type.
[ "Return", "a", "constructor", "for", "a", "new", "error", "type", "." ]
94b802016d81391b486f02bd61f7ec89ff5fe8e7
https://github.com/tentwentyfour/helpbox/blob/94b802016d81391b486f02bd61f7ec89ff5fe8e7/source/create-error-type.js#L15-L34
39,669
joelvh/Sysmo.js
lib/sysmo.js
function(target, namespace, graph) { //if the first param is a string, //we are including the namespace on Sysmo if (typeof target == 'string') { graph = namespace; namespace = target; target = Sysmo; } //create namespace on target Sysmo.namespace(namespace, target); //get inner most object in namespace target = Sysmo.getDeepValue(target, namespace); //merge graph on inner most object in namespace return Sysmo.extend(target, graph); }
javascript
function(target, namespace, graph) { //if the first param is a string, //we are including the namespace on Sysmo if (typeof target == 'string') { graph = namespace; namespace = target; target = Sysmo; } //create namespace on target Sysmo.namespace(namespace, target); //get inner most object in namespace target = Sysmo.getDeepValue(target, namespace); //merge graph on inner most object in namespace return Sysmo.extend(target, graph); }
[ "function", "(", "target", ",", "namespace", ",", "graph", ")", "{", "//if the first param is a string, ", "//we are including the namespace on Sysmo", "if", "(", "typeof", "target", "==", "'string'", ")", "{", "graph", "=", "namespace", ";", "namespace", "=", "target", ";", "target", "=", "Sysmo", ";", "}", "//create namespace on target", "Sysmo", ".", "namespace", "(", "namespace", ",", "target", ")", ";", "//get inner most object in namespace", "target", "=", "Sysmo", ".", "getDeepValue", "(", "target", ",", "namespace", ")", ";", "//merge graph on inner most object in namespace", "return", "Sysmo", ".", "extend", "(", "target", ",", "graph", ")", ";", "}" ]
include an object graph in another
[ "include", "an", "object", "graph", "in", "another" ]
0487e562437c3933f66f4c29505d0c50ccb3e8e9
https://github.com/joelvh/Sysmo.js/blob/0487e562437c3933f66f4c29505d0c50ccb3e8e9/lib/sysmo.js#L69-L86
39,670
joelvh/Sysmo.js
lib/sysmo.js
function(namespace, target) { target = target || {}; var names = namespace.split('.'), context = target; for (var i = 0; i < names.length; i++) { var name = names[i]; context = (name in context) ? context[name] : (context[name] = {}); } return target; }
javascript
function(namespace, target) { target = target || {}; var names = namespace.split('.'), context = target; for (var i = 0; i < names.length; i++) { var name = names[i]; context = (name in context) ? context[name] : (context[name] = {}); } return target; }
[ "function", "(", "namespace", ",", "target", ")", "{", "target", "=", "target", "||", "{", "}", ";", "var", "names", "=", "namespace", ".", "split", "(", "'.'", ")", ",", "context", "=", "target", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "names", ".", "length", ";", "i", "++", ")", "{", "var", "name", "=", "names", "[", "i", "]", ";", "context", "=", "(", "name", "in", "context", ")", "?", "context", "[", "name", "]", ":", "(", "context", "[", "name", "]", "=", "{", "}", ")", ";", "}", "return", "target", ";", "}" ]
build an object graph from a namespace. adds properties to the target object or returns a new object graph.
[ "build", "an", "object", "graph", "from", "a", "namespace", ".", "adds", "properties", "to", "the", "target", "object", "or", "returns", "a", "new", "object", "graph", "." ]
0487e562437c3933f66f4c29505d0c50ccb3e8e9
https://github.com/joelvh/Sysmo.js/blob/0487e562437c3933f66f4c29505d0c50ccb3e8e9/lib/sysmo.js#L90-L103
39,671
joelvh/Sysmo.js
lib/sysmo.js
function (target, path, traverseArrays) { // if traversing arrays is enabled and this is an array, loop // may be a "array-like" node list (or similar), in which case it needs to be converted if (traverseArrays && Sysmo.isArrayLike(target)) { target = Sysmo.makeArray(target); var children = []; for (var i = 0; i < target.length; i++) { // recursively loop through children var child = Sysmo.getDeepValue(target[i], path, traverseArrays); // ignore if undefined if (typeof child != "undefined") { //flatten array because the original path points to one flat result set if (Sysmo.isArray(child)) { for (var j = 0; j < child.length; j++) { children.push(child[j]); } } else { children.push(child); } } } return (children.length) ? children : void(0); } var invoke_regex = /\(\)$/, properties = path.split('.'), property; if (target != null && properties.length) { var propertyName = properties.shift(), invoke = invoke_regex.test(propertyName) if (invoke) { propertyName = propertyName.replace(invoke_regex, ""); } if (invoke && propertyName in target) { target = target[propertyName](); } else { target = target[propertyName]; } path = properties.join('.'); if (path) { target = Sysmo.getDeepValue(target, path, traverseArrays); } } return target; }
javascript
function (target, path, traverseArrays) { // if traversing arrays is enabled and this is an array, loop // may be a "array-like" node list (or similar), in which case it needs to be converted if (traverseArrays && Sysmo.isArrayLike(target)) { target = Sysmo.makeArray(target); var children = []; for (var i = 0; i < target.length; i++) { // recursively loop through children var child = Sysmo.getDeepValue(target[i], path, traverseArrays); // ignore if undefined if (typeof child != "undefined") { //flatten array because the original path points to one flat result set if (Sysmo.isArray(child)) { for (var j = 0; j < child.length; j++) { children.push(child[j]); } } else { children.push(child); } } } return (children.length) ? children : void(0); } var invoke_regex = /\(\)$/, properties = path.split('.'), property; if (target != null && properties.length) { var propertyName = properties.shift(), invoke = invoke_regex.test(propertyName) if (invoke) { propertyName = propertyName.replace(invoke_regex, ""); } if (invoke && propertyName in target) { target = target[propertyName](); } else { target = target[propertyName]; } path = properties.join('.'); if (path) { target = Sysmo.getDeepValue(target, path, traverseArrays); } } return target; }
[ "function", "(", "target", ",", "path", ",", "traverseArrays", ")", "{", "// if traversing arrays is enabled and this is an array, loop", "// may be a \"array-like\" node list (or similar), in which case it needs to be converted", "if", "(", "traverseArrays", "&&", "Sysmo", ".", "isArrayLike", "(", "target", ")", ")", "{", "target", "=", "Sysmo", ".", "makeArray", "(", "target", ")", ";", "var", "children", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "target", ".", "length", ";", "i", "++", ")", "{", "// recursively loop through children", "var", "child", "=", "Sysmo", ".", "getDeepValue", "(", "target", "[", "i", "]", ",", "path", ",", "traverseArrays", ")", ";", "// ignore if undefined", "if", "(", "typeof", "child", "!=", "\"undefined\"", ")", "{", "//flatten array because the original path points to one flat result set", "if", "(", "Sysmo", ".", "isArray", "(", "child", ")", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "child", ".", "length", ";", "j", "++", ")", "{", "children", ".", "push", "(", "child", "[", "j", "]", ")", ";", "}", "}", "else", "{", "children", ".", "push", "(", "child", ")", ";", "}", "}", "}", "return", "(", "children", ".", "length", ")", "?", "children", ":", "void", "(", "0", ")", ";", "}", "var", "invoke_regex", "=", "/", "\\(\\)$", "/", ",", "properties", "=", "path", ".", "split", "(", "'.'", ")", ",", "property", ";", "if", "(", "target", "!=", "null", "&&", "properties", ".", "length", ")", "{", "var", "propertyName", "=", "properties", ".", "shift", "(", ")", ",", "invoke", "=", "invoke_regex", ".", "test", "(", "propertyName", ")", "if", "(", "invoke", ")", "{", "propertyName", "=", "propertyName", ".", "replace", "(", "invoke_regex", ",", "\"\"", ")", ";", "}", "if", "(", "invoke", "&&", "propertyName", "in", "target", ")", "{", "target", "=", "target", "[", "propertyName", "]", "(", ")", ";", "}", "else", "{", "target", "=", "target", "[", "propertyName", "]", ";", "}", "path", "=", "properties", ".", "join", "(", "'.'", ")", ";", "if", "(", "path", ")", "{", "target", "=", "Sysmo", ".", "getDeepValue", "(", "target", ",", "path", ",", "traverseArrays", ")", ";", "}", "}", "return", "target", ";", "}" ]
get the value of a property deeply nested in an object hierarchy
[ "get", "the", "value", "of", "a", "property", "deeply", "nested", "in", "an", "object", "hierarchy" ]
0487e562437c3933f66f4c29505d0c50ccb3e8e9
https://github.com/joelvh/Sysmo.js/blob/0487e562437c3933f66f4c29505d0c50ccb3e8e9/lib/sysmo.js#L105-L166
39,672
alv-ch/styleguide
src/assets/fabricator/scripts/fabricator.js
function () { var href = window.location.href, items = parsedItems(), id, index; // get window 'id' if (href.indexOf('#') > -1) { id = window.location.hash.replace('#', ''); } else { id = window.location.pathname.split('/').pop().replace(/\.[^/.]+$/, ''); } // In case the first menu item isn't the index page. if (id === '') { id = 'index'; } // find the window id in the items array index = (items.indexOf(id) > -1) ? items.indexOf(id) : 0; // set the matched item as active fabricator.dom.menuItems[index].classList.add('f-active'); }
javascript
function () { var href = window.location.href, items = parsedItems(), id, index; // get window 'id' if (href.indexOf('#') > -1) { id = window.location.hash.replace('#', ''); } else { id = window.location.pathname.split('/').pop().replace(/\.[^/.]+$/, ''); } // In case the first menu item isn't the index page. if (id === '') { id = 'index'; } // find the window id in the items array index = (items.indexOf(id) > -1) ? items.indexOf(id) : 0; // set the matched item as active fabricator.dom.menuItems[index].classList.add('f-active'); }
[ "function", "(", ")", "{", "var", "href", "=", "window", ".", "location", ".", "href", ",", "items", "=", "parsedItems", "(", ")", ",", "id", ",", "index", ";", "// get window 'id'", "if", "(", "href", ".", "indexOf", "(", "'#'", ")", ">", "-", "1", ")", "{", "id", "=", "window", ".", "location", ".", "hash", ".", "replace", "(", "'#'", ",", "''", ")", ";", "}", "else", "{", "id", "=", "window", ".", "location", ".", "pathname", ".", "split", "(", "'/'", ")", ".", "pop", "(", ")", ".", "replace", "(", "/", "\\.[^/.]+$", "/", ",", "''", ")", ";", "}", "// In case the first menu item isn't the index page.", "if", "(", "id", "===", "''", ")", "{", "id", "=", "'index'", ";", "}", "// find the window id in the items array", "index", "=", "(", "items", ".", "indexOf", "(", "id", ")", ">", "-", "1", ")", "?", "items", ".", "indexOf", "(", "id", ")", ":", "0", ";", "// set the matched item as active", "fabricator", ".", "dom", ".", "menuItems", "[", "index", "]", ".", "classList", ".", "add", "(", "'f-active'", ")", ";", "}" ]
Match the 'id' in the window location with the menu item, set menu item as active
[ "Match", "the", "id", "in", "the", "window", "location", "with", "the", "menu", "item", "set", "menu", "item", "as", "active" ]
197269a8d80fdc760c1bf2b39f82cbc539c861d8
https://github.com/alv-ch/styleguide/blob/197269a8d80fdc760c1bf2b39f82cbc539c861d8/src/assets/fabricator/scripts/fabricator.js#L133-L157
39,673
ofzza/enTT
tasks/task-3-script-babel.js
sourceRootFn
function sourceRootFn (file) { let sourcePath = file.history[0], targetPath = path.join(__dirname, '../src/'), relativePath = path.join(path.relative(sourcePath, targetPath), './src'); return relativePath; }
javascript
function sourceRootFn (file) { let sourcePath = file.history[0], targetPath = path.join(__dirname, '../src/'), relativePath = path.join(path.relative(sourcePath, targetPath), './src'); return relativePath; }
[ "function", "sourceRootFn", "(", "file", ")", "{", "let", "sourcePath", "=", "file", ".", "history", "[", "0", "]", ",", "targetPath", "=", "path", ".", "join", "(", "__dirname", ",", "'../src/'", ")", ",", "relativePath", "=", "path", ".", "join", "(", "path", ".", "relative", "(", "sourcePath", ",", "targetPath", ")", ",", "'./src'", ")", ";", "return", "relativePath", ";", "}" ]
Composes source-maps' sourceRoot property for a file @param {any} file File being processed @returns {any} sourceRoot value
[ "Composes", "source", "-", "maps", "sourceRoot", "property", "for", "a", "file" ]
fdf27de4142b3c65a3e51dee70e0d7625dff897c
https://github.com/ofzza/enTT/blob/fdf27de4142b3c65a3e51dee70e0d7625dff897c/tasks/task-3-script-babel.js#L45-L50
39,674
ofzza/enTT
dist/ext/dynamic-properties.js
DynamicPropertiesExtension
function DynamicPropertiesExtension() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$deferred = _ref.deferred, deferred = _ref$deferred === undefined ? false : _ref$deferred; _classCallCheck(this, DynamicPropertiesExtension); return _possibleConstructorReturn(this, (DynamicPropertiesExtension.__proto__ || Object.getPrototypeOf(DynamicPropertiesExtension)).call(this, { processShorthandPropertyConfiguration: true, updatePropertyConfiguration: true, // If not deferred, regenerate dynamic property value on initialization and change detected onEntityInstantiate: !deferred, onChangeDetected: !deferred, // If deferred, regenerate dynamic property value on get interceptPropertyGet: deferred })); }
javascript
function DynamicPropertiesExtension() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$deferred = _ref.deferred, deferred = _ref$deferred === undefined ? false : _ref$deferred; _classCallCheck(this, DynamicPropertiesExtension); return _possibleConstructorReturn(this, (DynamicPropertiesExtension.__proto__ || Object.getPrototypeOf(DynamicPropertiesExtension)).call(this, { processShorthandPropertyConfiguration: true, updatePropertyConfiguration: true, // If not deferred, regenerate dynamic property value on initialization and change detected onEntityInstantiate: !deferred, onChangeDetected: !deferred, // If deferred, regenerate dynamic property value on get interceptPropertyGet: deferred })); }
[ "function", "DynamicPropertiesExtension", "(", ")", "{", "var", "_ref", "=", "arguments", ".", "length", ">", "0", "&&", "arguments", "[", "0", "]", "!==", "undefined", "?", "arguments", "[", "0", "]", ":", "{", "}", ",", "_ref$deferred", "=", "_ref", ".", "deferred", ",", "deferred", "=", "_ref$deferred", "===", "undefined", "?", "false", ":", "_ref$deferred", ";", "_classCallCheck", "(", "this", ",", "DynamicPropertiesExtension", ")", ";", "return", "_possibleConstructorReturn", "(", "this", ",", "(", "DynamicPropertiesExtension", ".", "__proto__", "||", "Object", ".", "getPrototypeOf", "(", "DynamicPropertiesExtension", ")", ")", ".", "call", "(", "this", ",", "{", "processShorthandPropertyConfiguration", ":", "true", ",", "updatePropertyConfiguration", ":", "true", ",", "// If not deferred, regenerate dynamic property value on initialization and change detected", "onEntityInstantiate", ":", "!", "deferred", ",", "onChangeDetected", ":", "!", "deferred", ",", "// If deferred, regenerate dynamic property value on get", "interceptPropertyGet", ":", "deferred", "}", ")", ")", ";", "}" ]
Creates an instance of DynamicPropertiesExtension. @param {any} deferred If true, the dynamic property value will be generated each time the property getter is called instead of on change detection @memberof DynamicPropertiesExtension
[ "Creates", "an", "instance", "of", "DynamicPropertiesExtension", "." ]
fdf27de4142b3c65a3e51dee70e0d7625dff897c
https://github.com/ofzza/enTT/blob/fdf27de4142b3c65a3e51dee70e0d7625dff897c/dist/ext/dynamic-properties.js#L54-L70
39,675
expo/project-repl
index.js
readFileAsync
async function readFileAsync(...args) { return new Promise((resolve, reject) => { fs.readFile(...args, (err, result) => { if (err) { reject(err); } else { resolve(result); } }); }); }
javascript
async function readFileAsync(...args) { return new Promise((resolve, reject) => { fs.readFile(...args, (err, result) => { if (err) { reject(err); } else { resolve(result); } }); }); }
[ "async", "function", "readFileAsync", "(", "...", "args", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "fs", ".", "readFile", "(", "...", "args", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "else", "{", "resolve", "(", "result", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Promise interface for `fs.readFile` @param {<string> | <Buffer> | <URL> | <integer>} p filename or file descriptor @param {<Object> | <string>} options
[ "Promise", "interface", "for", "fs", ".", "readFile" ]
9c4c91d6cbe9ce2c42a82329505b1148d06d6d44
https://github.com/expo/project-repl/blob/9c4c91d6cbe9ce2c42a82329505b1148d06d6d44/index.js#L12-L22
39,676
ggarek/debug-dude
lib/index.js
createLoggers
function createLoggers(ns) { var debug = (0, _debug2['default'])(ns + ':debug'); debug.log = function () { return console.log.apply(console, arguments); }; var log = (0, _debug2['default'])(ns + ':log'); log.log = function () { return console.log.apply(console, arguments); }; var info = (0, _debug2['default'])(ns + ':info'); info.log = function () { return console.info.apply(console, arguments); }; var warn = (0, _debug2['default'])(ns + ':warn'); warn.log = function () { return console.warn.apply(console, arguments); }; var error = (0, _debug2['default'])(ns + ':error'); error.log = function () { return console.error.apply(console, arguments); }; return { debug: debug, log: log, info: info, warn: warn, error: error }; }
javascript
function createLoggers(ns) { var debug = (0, _debug2['default'])(ns + ':debug'); debug.log = function () { return console.log.apply(console, arguments); }; var log = (0, _debug2['default'])(ns + ':log'); log.log = function () { return console.log.apply(console, arguments); }; var info = (0, _debug2['default'])(ns + ':info'); info.log = function () { return console.info.apply(console, arguments); }; var warn = (0, _debug2['default'])(ns + ':warn'); warn.log = function () { return console.warn.apply(console, arguments); }; var error = (0, _debug2['default'])(ns + ':error'); error.log = function () { return console.error.apply(console, arguments); }; return { debug: debug, log: log, info: info, warn: warn, error: error }; }
[ "function", "createLoggers", "(", "ns", ")", "{", "var", "debug", "=", "(", "0", ",", "_debug2", "[", "'default'", "]", ")", "(", "ns", "+", "':debug'", ")", ";", "debug", ".", "log", "=", "function", "(", ")", "{", "return", "console", ".", "log", ".", "apply", "(", "console", ",", "arguments", ")", ";", "}", ";", "var", "log", "=", "(", "0", ",", "_debug2", "[", "'default'", "]", ")", "(", "ns", "+", "':log'", ")", ";", "log", ".", "log", "=", "function", "(", ")", "{", "return", "console", ".", "log", ".", "apply", "(", "console", ",", "arguments", ")", ";", "}", ";", "var", "info", "=", "(", "0", ",", "_debug2", "[", "'default'", "]", ")", "(", "ns", "+", "':info'", ")", ";", "info", ".", "log", "=", "function", "(", ")", "{", "return", "console", ".", "info", ".", "apply", "(", "console", ",", "arguments", ")", ";", "}", ";", "var", "warn", "=", "(", "0", ",", "_debug2", "[", "'default'", "]", ")", "(", "ns", "+", "':warn'", ")", ";", "warn", ".", "log", "=", "function", "(", ")", "{", "return", "console", ".", "warn", ".", "apply", "(", "console", ",", "arguments", ")", ";", "}", ";", "var", "error", "=", "(", "0", ",", "_debug2", "[", "'default'", "]", ")", "(", "ns", "+", "':error'", ")", ";", "error", ".", "log", "=", "function", "(", ")", "{", "return", "console", ".", "error", ".", "apply", "(", "console", ",", "arguments", ")", ";", "}", ";", "return", "{", "debug", ":", "debug", ",", "log", ":", "log", ",", "info", ":", "info", ",", "warn", ":", "warn", ",", "error", ":", "error", "}", ";", "}" ]
Create debug instances and bind log method to specific console method
[ "Create", "debug", "instances", "and", "bind", "log", "method", "to", "specific", "console", "method" ]
c6ddca34863630a7d257f22b9ea332110cdb60c5
https://github.com/ggarek/debug-dude/blob/c6ddca34863630a7d257f22b9ea332110cdb60c5/lib/index.js#L18-L51
39,677
mikolalysenko/red-blue-line-segment-intersect
rblsi.js
BruteForceList
function BruteForceList(capacity) { this.intervals = pool.mallocDouble(2 * capacity) this.index = pool.mallocInt32(capacity) this.count = 0 }
javascript
function BruteForceList(capacity) { this.intervals = pool.mallocDouble(2 * capacity) this.index = pool.mallocInt32(capacity) this.count = 0 }
[ "function", "BruteForceList", "(", "capacity", ")", "{", "this", ".", "intervals", "=", "pool", ".", "mallocDouble", "(", "2", "*", "capacity", ")", "this", ".", "index", "=", "pool", ".", "mallocInt32", "(", "capacity", ")", "this", ".", "count", "=", "0", "}" ]
It is silly, but this is faster than doing the right thing for up to a few thousand segments, which hardly occurs in practice.
[ "It", "is", "silly", "but", "this", "is", "faster", "than", "doing", "the", "right", "thing", "for", "up", "to", "a", "few", "thousand", "segments", "which", "hardly", "occurs", "in", "practice", "." ]
d8ecd805e1846d8f3644ef84b410cb6110c1c00f
https://github.com/mikolalysenko/red-blue-line-segment-intersect/blob/d8ecd805e1846d8f3644ef84b410cb6110c1c00f/rblsi.js#L55-L59
39,678
yaniswang/PromiseClass
lib/promiseclass.js
chaiSupportChainPromise
function chaiSupportChainPromise(chai, utils){ function copyChainPromise(promise, assertion){ let protoPromise = Object.getPrototypeOf(promise); let protoNames = Object.getOwnPropertyNames(protoPromise); let protoAssertion = Object.getPrototypeOf(assertion); protoNames.forEach(function(protoName){ if(protoName !== 'constructor' && !protoAssertion[protoName]){ assertion[protoName] = promise[protoName].bind(promise); } }); } function doAsserterAsync(asserter, assertion, args){ let self = utils.flag(assertion, "object"); if(self && self.then && typeof self.then === "function"){ let promise = self.then(function(value){ assertion._obj = value; asserter.apply(assertion, args); return value; }, function(error){ assertion._obj = new Error(error); asserter.apply(assertion, args); }); copyChainPromise(promise, assertion); } else{ return asserter.apply(assertion, args); } } let Assertion = chai.Assertion; let propertyNames = Object.getOwnPropertyNames(Assertion.prototype); let propertyDescs = {}; propertyNames.forEach(function (name) { propertyDescs[name] = Object.getOwnPropertyDescriptor(Assertion.prototype, name); }); let methodNames = propertyNames.filter(function (name) { return name !== "assert" && typeof propertyDescs[name].value === "function"; }); methodNames.forEach(function (methodName) { Assertion.overwriteMethod(methodName, function (originalMethod) { return function () { doAsserterAsync(originalMethod, this, arguments); }; }); }); let getterNames = propertyNames.filter(function (name) { return name !== "_obj" && typeof propertyDescs[name].get === "function"; }); getterNames.forEach(function (getterName) { let isChainableMethod = Assertion.prototype.__methods.hasOwnProperty(getterName); if (isChainableMethod) { Assertion.overwriteChainableMethod( getterName, function (originalMethod) { return function() { doAsserterAsync(originalMethod, this, arguments); }; }, function (originalGetter) { return function() { doAsserterAsync(originalGetter, this); }; } ); } else { Assertion.overwriteProperty(getterName, function (originalGetter) { return function () { doAsserterAsync(originalGetter, this); }; }); } }); }
javascript
function chaiSupportChainPromise(chai, utils){ function copyChainPromise(promise, assertion){ let protoPromise = Object.getPrototypeOf(promise); let protoNames = Object.getOwnPropertyNames(protoPromise); let protoAssertion = Object.getPrototypeOf(assertion); protoNames.forEach(function(protoName){ if(protoName !== 'constructor' && !protoAssertion[protoName]){ assertion[protoName] = promise[protoName].bind(promise); } }); } function doAsserterAsync(asserter, assertion, args){ let self = utils.flag(assertion, "object"); if(self && self.then && typeof self.then === "function"){ let promise = self.then(function(value){ assertion._obj = value; asserter.apply(assertion, args); return value; }, function(error){ assertion._obj = new Error(error); asserter.apply(assertion, args); }); copyChainPromise(promise, assertion); } else{ return asserter.apply(assertion, args); } } let Assertion = chai.Assertion; let propertyNames = Object.getOwnPropertyNames(Assertion.prototype); let propertyDescs = {}; propertyNames.forEach(function (name) { propertyDescs[name] = Object.getOwnPropertyDescriptor(Assertion.prototype, name); }); let methodNames = propertyNames.filter(function (name) { return name !== "assert" && typeof propertyDescs[name].value === "function"; }); methodNames.forEach(function (methodName) { Assertion.overwriteMethod(methodName, function (originalMethod) { return function () { doAsserterAsync(originalMethod, this, arguments); }; }); }); let getterNames = propertyNames.filter(function (name) { return name !== "_obj" && typeof propertyDescs[name].get === "function"; }); getterNames.forEach(function (getterName) { let isChainableMethod = Assertion.prototype.__methods.hasOwnProperty(getterName); if (isChainableMethod) { Assertion.overwriteChainableMethod( getterName, function (originalMethod) { return function() { doAsserterAsync(originalMethod, this, arguments); }; }, function (originalGetter) { return function() { doAsserterAsync(originalGetter, this); }; } ); } else { Assertion.overwriteProperty(getterName, function (originalGetter) { return function () { doAsserterAsync(originalGetter, this); }; }); } }); }
[ "function", "chaiSupportChainPromise", "(", "chai", ",", "utils", ")", "{", "function", "copyChainPromise", "(", "promise", ",", "assertion", ")", "{", "let", "protoPromise", "=", "Object", ".", "getPrototypeOf", "(", "promise", ")", ";", "let", "protoNames", "=", "Object", ".", "getOwnPropertyNames", "(", "protoPromise", ")", ";", "let", "protoAssertion", "=", "Object", ".", "getPrototypeOf", "(", "assertion", ")", ";", "protoNames", ".", "forEach", "(", "function", "(", "protoName", ")", "{", "if", "(", "protoName", "!==", "'constructor'", "&&", "!", "protoAssertion", "[", "protoName", "]", ")", "{", "assertion", "[", "protoName", "]", "=", "promise", "[", "protoName", "]", ".", "bind", "(", "promise", ")", ";", "}", "}", ")", ";", "}", "function", "doAsserterAsync", "(", "asserter", ",", "assertion", ",", "args", ")", "{", "let", "self", "=", "utils", ".", "flag", "(", "assertion", ",", "\"object\"", ")", ";", "if", "(", "self", "&&", "self", ".", "then", "&&", "typeof", "self", ".", "then", "===", "\"function\"", ")", "{", "let", "promise", "=", "self", ".", "then", "(", "function", "(", "value", ")", "{", "assertion", ".", "_obj", "=", "value", ";", "asserter", ".", "apply", "(", "assertion", ",", "args", ")", ";", "return", "value", ";", "}", ",", "function", "(", "error", ")", "{", "assertion", ".", "_obj", "=", "new", "Error", "(", "error", ")", ";", "asserter", ".", "apply", "(", "assertion", ",", "args", ")", ";", "}", ")", ";", "copyChainPromise", "(", "promise", ",", "assertion", ")", ";", "}", "else", "{", "return", "asserter", ".", "apply", "(", "assertion", ",", "args", ")", ";", "}", "}", "let", "Assertion", "=", "chai", ".", "Assertion", ";", "let", "propertyNames", "=", "Object", ".", "getOwnPropertyNames", "(", "Assertion", ".", "prototype", ")", ";", "let", "propertyDescs", "=", "{", "}", ";", "propertyNames", ".", "forEach", "(", "function", "(", "name", ")", "{", "propertyDescs", "[", "name", "]", "=", "Object", ".", "getOwnPropertyDescriptor", "(", "Assertion", ".", "prototype", ",", "name", ")", ";", "}", ")", ";", "let", "methodNames", "=", "propertyNames", ".", "filter", "(", "function", "(", "name", ")", "{", "return", "name", "!==", "\"assert\"", "&&", "typeof", "propertyDescs", "[", "name", "]", ".", "value", "===", "\"function\"", ";", "}", ")", ";", "methodNames", ".", "forEach", "(", "function", "(", "methodName", ")", "{", "Assertion", ".", "overwriteMethod", "(", "methodName", ",", "function", "(", "originalMethod", ")", "{", "return", "function", "(", ")", "{", "doAsserterAsync", "(", "originalMethod", ",", "this", ",", "arguments", ")", ";", "}", ";", "}", ")", ";", "}", ")", ";", "let", "getterNames", "=", "propertyNames", ".", "filter", "(", "function", "(", "name", ")", "{", "return", "name", "!==", "\"_obj\"", "&&", "typeof", "propertyDescs", "[", "name", "]", ".", "get", "===", "\"function\"", ";", "}", ")", ";", "getterNames", ".", "forEach", "(", "function", "(", "getterName", ")", "{", "let", "isChainableMethod", "=", "Assertion", ".", "prototype", ".", "__methods", ".", "hasOwnProperty", "(", "getterName", ")", ";", "if", "(", "isChainableMethod", ")", "{", "Assertion", ".", "overwriteChainableMethod", "(", "getterName", ",", "function", "(", "originalMethod", ")", "{", "return", "function", "(", ")", "{", "doAsserterAsync", "(", "originalMethod", ",", "this", ",", "arguments", ")", ";", "}", ";", "}", ",", "function", "(", "originalGetter", ")", "{", "return", "function", "(", ")", "{", "doAsserterAsync", "(", "originalGetter", ",", "this", ")", ";", "}", ";", "}", ")", ";", "}", "else", "{", "Assertion", ".", "overwriteProperty", "(", "getterName", ",", "function", "(", "originalGetter", ")", "{", "return", "function", "(", ")", "{", "doAsserterAsync", "(", "originalGetter", ",", "this", ")", ";", "}", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
support ChainPromise for chai
[ "support", "ChainPromise", "for", "chai" ]
3ead8295500618eb7730eecb71ebcbb3294b9729
https://github.com/yaniswang/PromiseClass/blob/3ead8295500618eb7730eecb71ebcbb3294b9729/lib/promiseclass.js#L161-L237
39,679
tcardoso2/vermon
PluginManager.js
RemovePlugin
function RemovePlugin (ext_module_id) { let copy = plugins[ext_module_id] let runPreWorkflowFunctions = function () { if (!plugins[ext_module_id].PreRemovePlugin) throw new Error('Error: PreRemovePlugin function must be implemented.') plugins[ext_module_id].PreRemovePlugin() } let runPostWorkflowFunctions = function () { if (!copy.PostRemovePlugin) throw new Error('Error: PostRemovePlugin function must be implemented.') copy.PostRemovePlugin(module.exports) } runPreWorkflowFunctions() delete plugins[ext_module_id] log.info('Removed Plugin', ext_module_id) runPostWorkflowFunctions() return true }
javascript
function RemovePlugin (ext_module_id) { let copy = plugins[ext_module_id] let runPreWorkflowFunctions = function () { if (!plugins[ext_module_id].PreRemovePlugin) throw new Error('Error: PreRemovePlugin function must be implemented.') plugins[ext_module_id].PreRemovePlugin() } let runPostWorkflowFunctions = function () { if (!copy.PostRemovePlugin) throw new Error('Error: PostRemovePlugin function must be implemented.') copy.PostRemovePlugin(module.exports) } runPreWorkflowFunctions() delete plugins[ext_module_id] log.info('Removed Plugin', ext_module_id) runPostWorkflowFunctions() return true }
[ "function", "RemovePlugin", "(", "ext_module_id", ")", "{", "let", "copy", "=", "plugins", "[", "ext_module_id", "]", "let", "runPreWorkflowFunctions", "=", "function", "(", ")", "{", "if", "(", "!", "plugins", "[", "ext_module_id", "]", ".", "PreRemovePlugin", ")", "throw", "new", "Error", "(", "'Error: PreRemovePlugin function must be implemented.'", ")", "plugins", "[", "ext_module_id", "]", ".", "PreRemovePlugin", "(", ")", "}", "let", "runPostWorkflowFunctions", "=", "function", "(", ")", "{", "if", "(", "!", "copy", ".", "PostRemovePlugin", ")", "throw", "new", "Error", "(", "'Error: PostRemovePlugin function must be implemented.'", ")", "copy", ".", "PostRemovePlugin", "(", "module", ".", "exports", ")", "}", "runPreWorkflowFunctions", "(", ")", "delete", "plugins", "[", "ext_module_id", "]", "log", ".", "info", "(", "'Removed Plugin'", ",", "ext_module_id", ")", "runPostWorkflowFunctions", "(", ")", "return", "true", "}" ]
Removes an existing Extention plugin from the library @param {string} ext_module_id is the id of the module to remove. @return {boolean} True the plugin was successfully removed.
[ "Removes", "an", "existing", "Extention", "plugin", "from", "the", "library" ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/PluginManager.js#L54-L73
39,680
tcardoso2/vermon
main.js
_InternalAddEnvironment
function _InternalAddEnvironment (env = new ent.Environment()) { if (env instanceof ent.Environment) { em.SetEnvironment(env) return true } else { log.warning("'environment' object is not of type Environment") } return false }
javascript
function _InternalAddEnvironment (env = new ent.Environment()) { if (env instanceof ent.Environment) { em.SetEnvironment(env) return true } else { log.warning("'environment' object is not of type Environment") } return false }
[ "function", "_InternalAddEnvironment", "(", "env", "=", "new", "ent", ".", "Environment", "(", ")", ")", "{", "if", "(", "env", "instanceof", "ent", ".", "Environment", ")", "{", "em", ".", "SetEnvironment", "(", "env", ")", "return", "true", "}", "else", "{", "log", ".", "warning", "(", "\"'environment' object is not of type Environment\"", ")", "}", "return", "false", "}" ]
Adds an Environment into the current context. The environment needs to be if instance Environment, if not if fails silently, logs the error in the logger and returns false. @param {object} env is the Environment object to add. This function is internal @internal @returns {Boolean} true if the environment is successfully created.
[ "Adds", "an", "Environment", "into", "the", "current", "context", ".", "The", "environment", "needs", "to", "be", "if", "instance", "Environment", "if", "not", "if", "fails", "silently", "logs", "the", "error", "in", "the", "logger", "and", "returns", "false", "." ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L69-L77
39,681
tcardoso2/vermon
main.js
AddDetectorToSubEnvironmentOnly
function AddDetectorToSubEnvironmentOnly (detector, force = false, subEnvironment) { return em.AddDetectorToSubEnvironmentOnly(detector, force, subEnvironment) }
javascript
function AddDetectorToSubEnvironmentOnly (detector, force = false, subEnvironment) { return em.AddDetectorToSubEnvironmentOnly(detector, force, subEnvironment) }
[ "function", "AddDetectorToSubEnvironmentOnly", "(", "detector", ",", "force", "=", "false", ",", "subEnvironment", ")", "{", "return", "em", ".", "AddDetectorToSubEnvironmentOnly", "(", "detector", ",", "force", ",", "subEnvironment", ")", "}" ]
Adds a detector to a SubEnvironment. Assumes that the main Environment is a MultiEnvironment. @param {object} detector is the MotionDetector object to add. @param {boolean} force can be set to true to push the detector even if not of {MotionDetector} instance @param {string} subEnvironment is the Environment to add to, within the MultiEnvironment @returns {Boolean} true if the detector is successfully created. @public
[ "Adds", "a", "detector", "to", "a", "SubEnvironment", ".", "Assumes", "that", "the", "main", "Environment", "is", "a", "MultiEnvironment", "." ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L167-L169
39,682
tcardoso2/vermon
main.js
RemoveNotifier
function RemoveNotifier (notifier, silent = false) { let index = em.GetNotifiers().indexOf(notifier) log.info('Removing Notifier...') if (index > -1) { if (!silent) { em.GetNotifiers()[index].notify('Removing Notifier...') } em.GetNotifiers().splice(index, 1) return true } else { log.info(chalk.yellow(`Notifier ${notifier} not found, ignoring and returning false...`)) } return false }
javascript
function RemoveNotifier (notifier, silent = false) { let index = em.GetNotifiers().indexOf(notifier) log.info('Removing Notifier...') if (index > -1) { if (!silent) { em.GetNotifiers()[index].notify('Removing Notifier...') } em.GetNotifiers().splice(index, 1) return true } else { log.info(chalk.yellow(`Notifier ${notifier} not found, ignoring and returning false...`)) } return false }
[ "function", "RemoveNotifier", "(", "notifier", ",", "silent", "=", "false", ")", "{", "let", "index", "=", "em", ".", "GetNotifiers", "(", ")", ".", "indexOf", "(", "notifier", ")", "log", ".", "info", "(", "'Removing Notifier...'", ")", "if", "(", "index", ">", "-", "1", ")", "{", "if", "(", "!", "silent", ")", "{", "em", ".", "GetNotifiers", "(", ")", "[", "index", "]", ".", "notify", "(", "'Removing Notifier...'", ")", "}", "em", ".", "GetNotifiers", "(", ")", ".", "splice", "(", "index", ",", "1", ")", "return", "true", "}", "else", "{", "log", ".", "info", "(", "chalk", ".", "yellow", "(", "`", "${", "notifier", "}", "`", ")", ")", "}", "return", "false", "}" ]
Removes an existing notifier from the context. Does not fail if the notifier is not found. @param {object} notifier is the notifier instance to remove. @param {booleal} sileng states if = true the removal should not send a notification @returns true if the notifier was found (and subsequently removed). @public
[ "Removes", "an", "existing", "notifier", "from", "the", "context", ".", "Does", "not", "fail", "if", "the", "notifier", "is", "not", "found", "." ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L203-L216
39,683
tcardoso2/vermon
main.js
RemoveDetector
function RemoveDetector (detector) { let index = motionDetectors.indexOf(detector) log.info('Removing Detector...') if (index > -1) { em.GetEnvironment().unbindDetector(detector) motionDetectors.splice(index, 1) // Redundant: Motion detectors are also copied to environment! em.GetEnvironment().motionDetectors.splice(index, 1) return true } else { log.info(chalk.yellow(`Detector ${detector} not found, ignoring and returning false...`)) } return false }
javascript
function RemoveDetector (detector) { let index = motionDetectors.indexOf(detector) log.info('Removing Detector...') if (index > -1) { em.GetEnvironment().unbindDetector(detector) motionDetectors.splice(index, 1) // Redundant: Motion detectors are also copied to environment! em.GetEnvironment().motionDetectors.splice(index, 1) return true } else { log.info(chalk.yellow(`Detector ${detector} not found, ignoring and returning false...`)) } return false }
[ "function", "RemoveDetector", "(", "detector", ")", "{", "let", "index", "=", "motionDetectors", ".", "indexOf", "(", "detector", ")", "log", ".", "info", "(", "'Removing Detector...'", ")", "if", "(", "index", ">", "-", "1", ")", "{", "em", ".", "GetEnvironment", "(", ")", ".", "unbindDetector", "(", "detector", ")", "motionDetectors", ".", "splice", "(", "index", ",", "1", ")", "// Redundant: Motion detectors are also copied to environment!", "em", ".", "GetEnvironment", "(", ")", ".", "motionDetectors", ".", "splice", "(", "index", ",", "1", ")", "return", "true", "}", "else", "{", "log", ".", "info", "(", "chalk", ".", "yellow", "(", "`", "${", "detector", "}", "`", ")", ")", "}", "return", "false", "}" ]
Removes an existing MotionDetector from the context, including its event listeners. Does not fail if the detector is not found. @param {object} detector is the MotionDetector instance to remove. @returns true if the detector was found (and subsequently removed). @public
[ "Removes", "an", "existing", "MotionDetector", "from", "the", "context", "including", "its", "event", "listeners", ".", "Does", "not", "fail", "if", "the", "detector", "is", "not", "found", "." ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L225-L238
39,684
tcardoso2/vermon
main.js
GetSubEnvironment
function GetSubEnvironment (subEnvironmentName) { let e = GetSubEnvironments()[subEnvironmentName] if (!e) { throw new Error('SubEnvironment does not exist.') } if (!(e instanceof ent.Environment)) { throw new Error('SubEnvironment is invalid.') } return e }
javascript
function GetSubEnvironment (subEnvironmentName) { let e = GetSubEnvironments()[subEnvironmentName] if (!e) { throw new Error('SubEnvironment does not exist.') } if (!(e instanceof ent.Environment)) { throw new Error('SubEnvironment is invalid.') } return e }
[ "function", "GetSubEnvironment", "(", "subEnvironmentName", ")", "{", "let", "e", "=", "GetSubEnvironments", "(", ")", "[", "subEnvironmentName", "]", "if", "(", "!", "e", ")", "{", "throw", "new", "Error", "(", "'SubEnvironment does not exist.'", ")", "}", "if", "(", "!", "(", "e", "instanceof", "ent", ".", "Environment", ")", ")", "{", "throw", "new", "Error", "(", "'SubEnvironment is invalid.'", ")", "}", "return", "e", "}" ]
Gets a particular sub-Environments of the context, raises error if it's not of type Environment. @returns Environment object. @public
[ "Gets", "a", "particular", "sub", "-", "Environments", "of", "the", "context", "raises", "error", "if", "it", "s", "not", "of", "type", "Environment", "." ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L273-L282
39,685
tcardoso2/vermon
main.js
GetMotionDetector
function GetMotionDetector (name) { // It's assumed the number of motion detectors will be sufficiently small to be ok to iterate without major loss of efficiency console.log("Attention! this function GetMotionDetectors returns a singleton of motion detectors! If you are running several instances only one instance prevails!"); return _.filter(motionDetectors, x => x.name === name)[0] // Another alternative way: lodash.filter(motionDetectors, { 'name': 'Something' } ); }
javascript
function GetMotionDetector (name) { // It's assumed the number of motion detectors will be sufficiently small to be ok to iterate without major loss of efficiency console.log("Attention! this function GetMotionDetectors returns a singleton of motion detectors! If you are running several instances only one instance prevails!"); return _.filter(motionDetectors, x => x.name === name)[0] // Another alternative way: lodash.filter(motionDetectors, { 'name': 'Something' } ); }
[ "function", "GetMotionDetector", "(", "name", ")", "{", "// It's assumed the number of motion detectors will be sufficiently small to be ok to iterate without major loss of efficiency", "console", ".", "log", "(", "\"Attention! this function GetMotionDetectors returns a singleton of motion detectors! If you are running several instances only one instance prevails!\"", ")", ";", "return", "_", ".", "filter", "(", "motionDetectors", ",", "x", "=>", "x", ".", "name", "===", "name", ")", "[", "0", "]", "// Another alternative way: lodash.filter(motionDetectors, { 'name': 'Something' } );", "}" ]
Gets the Motion Detectors with the given name. Will throw an exception if there is no Motion detector with such name. @param {string} name is the name of the MotionDetector instance to get. @returns a MotionDetector objects. Attention! motion detectors is a singleton! @public
[ "Gets", "the", "Motion", "Detectors", "with", "the", "given", "name", ".", "Will", "throw", "an", "exception", "if", "there", "is", "no", "Motion", "detector", "with", "such", "name", "." ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L313-L318
39,686
tcardoso2/vermon
main.js
GetFilters
function GetFilters () { let result = [] log.debug(`Fetching filters in the existing ${motionDetectors.length} detector(s)...`) for (let i in motionDetectors) { result = result.concat(motionDetectors[i].filters) } log.debug(`Getting ${result.length} filters...`) return result }
javascript
function GetFilters () { let result = [] log.debug(`Fetching filters in the existing ${motionDetectors.length} detector(s)...`) for (let i in motionDetectors) { result = result.concat(motionDetectors[i].filters) } log.debug(`Getting ${result.length} filters...`) return result }
[ "function", "GetFilters", "(", ")", "{", "let", "result", "=", "[", "]", "log", ".", "debug", "(", "`", "${", "motionDetectors", ".", "length", "}", "`", ")", "for", "(", "let", "i", "in", "motionDetectors", ")", "{", "result", "=", "result", ".", "concat", "(", "motionDetectors", "[", "i", "]", ".", "filters", ")", "}", "log", ".", "debug", "(", "`", "${", "result", ".", "length", "}", "`", ")", "return", "result", "}" ]
Gets all the existing Filters present in the current context. @returns {object} an Array of Filter objects. @public
[ "Gets", "all", "the", "existing", "Filters", "present", "in", "the", "current", "context", "." ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L325-L333
39,687
tcardoso2/vermon
main.js
Reset
function Reset () { log.info('Reseting environment...') for (let m in motionDetectors) { RemoveDetector(motionDetectors[m]) } for (let n in em.GetNotifiers()) { RemoveNotifier(em.GetNotifiers()[n], true) } em.SetNotifiers([]) if (em.GetEnvironment()) { em.GetEnvironment().removeAllListeners('changedState') em.GetEnvironment().exit() em.SetEnvironment(undefined) } motionDetectors = [] Object.keys(pm.GetPlugins()).forEach(function (key) { let p = pm.GetPlugins()[key] console.log(` Attempting to reset plugin ${p.id} with key ${key}...`) if (p.Reset) { p.Reset() log.info('ok.') } }) pm.ResetPlugins() config = {} log.info('Done Reseting environment.') }
javascript
function Reset () { log.info('Reseting environment...') for (let m in motionDetectors) { RemoveDetector(motionDetectors[m]) } for (let n in em.GetNotifiers()) { RemoveNotifier(em.GetNotifiers()[n], true) } em.SetNotifiers([]) if (em.GetEnvironment()) { em.GetEnvironment().removeAllListeners('changedState') em.GetEnvironment().exit() em.SetEnvironment(undefined) } motionDetectors = [] Object.keys(pm.GetPlugins()).forEach(function (key) { let p = pm.GetPlugins()[key] console.log(` Attempting to reset plugin ${p.id} with key ${key}...`) if (p.Reset) { p.Reset() log.info('ok.') } }) pm.ResetPlugins() config = {} log.info('Done Reseting environment.') }
[ "function", "Reset", "(", ")", "{", "log", ".", "info", "(", "'Reseting environment...'", ")", "for", "(", "let", "m", "in", "motionDetectors", ")", "{", "RemoveDetector", "(", "motionDetectors", "[", "m", "]", ")", "}", "for", "(", "let", "n", "in", "em", ".", "GetNotifiers", "(", ")", ")", "{", "RemoveNotifier", "(", "em", ".", "GetNotifiers", "(", ")", "[", "n", "]", ",", "true", ")", "}", "em", ".", "SetNotifiers", "(", "[", "]", ")", "if", "(", "em", ".", "GetEnvironment", "(", ")", ")", "{", "em", ".", "GetEnvironment", "(", ")", ".", "removeAllListeners", "(", "'changedState'", ")", "em", ".", "GetEnvironment", "(", ")", ".", "exit", "(", ")", "em", ".", "SetEnvironment", "(", "undefined", ")", "}", "motionDetectors", "=", "[", "]", "Object", ".", "keys", "(", "pm", ".", "GetPlugins", "(", ")", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "let", "p", "=", "pm", ".", "GetPlugins", "(", ")", "[", "key", "]", "console", ".", "log", "(", "`", "${", "p", ".", "id", "}", "${", "key", "}", "`", ")", "if", "(", "p", ".", "Reset", ")", "{", "p", ".", "Reset", "(", ")", "log", ".", "info", "(", "'ok.'", ")", "}", "}", ")", "pm", ".", "ResetPlugins", "(", ")", "config", "=", "{", "}", "log", ".", "info", "(", "'Done Reseting environment.'", ")", "}" ]
Resets the current context environment, notifiers and motion detectors. @public
[ "Resets", "the", "current", "context", "environment", "notifiers", "and", "motion", "detectors", "." ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L339-L365
39,688
tcardoso2/vermon
main.js
_StartPlugins
function _StartPlugins (e, m, n, f) { log.info(`Checking if any plugin exists which should be started...`) let plugins = pm.GetPlugins() Object.keys(plugins).forEach(function (key) { let p = plugins[key] log.info(` Plugin found. Checking plugin signature methods ShouldStart and Start for plugin ${key}...`) if (!p.ShouldStart) throw new Error("A plugin must have a 'ShouldStart' method implemented.") if (!p.Start) throw new Error("A plugin must have a 'Start' method implemented.") // TODO, add a way to call StartWithConfig log.info(' Checking if plugin should start...') if (p.ShouldStart(e, m, n, f, config)) { log.info('Plugin should start = true. Starting plugin...') p.Start(e, m, n, f, config) } else { log.info('Plugin will not start because returned false when asked if it should start.') } console.log('ok.') }) }
javascript
function _StartPlugins (e, m, n, f) { log.info(`Checking if any plugin exists which should be started...`) let plugins = pm.GetPlugins() Object.keys(plugins).forEach(function (key) { let p = plugins[key] log.info(` Plugin found. Checking plugin signature methods ShouldStart and Start for plugin ${key}...`) if (!p.ShouldStart) throw new Error("A plugin must have a 'ShouldStart' method implemented.") if (!p.Start) throw new Error("A plugin must have a 'Start' method implemented.") // TODO, add a way to call StartWithConfig log.info(' Checking if plugin should start...') if (p.ShouldStart(e, m, n, f, config)) { log.info('Plugin should start = true. Starting plugin...') p.Start(e, m, n, f, config) } else { log.info('Plugin will not start because returned false when asked if it should start.') } console.log('ok.') }) }
[ "function", "_StartPlugins", "(", "e", ",", "m", ",", "n", ",", "f", ")", "{", "log", ".", "info", "(", "`", "`", ")", "let", "plugins", "=", "pm", ".", "GetPlugins", "(", ")", "Object", ".", "keys", "(", "plugins", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "let", "p", "=", "plugins", "[", "key", "]", "log", ".", "info", "(", "`", "${", "key", "}", "`", ")", "if", "(", "!", "p", ".", "ShouldStart", ")", "throw", "new", "Error", "(", "\"A plugin must have a 'ShouldStart' method implemented.\"", ")", "if", "(", "!", "p", ".", "Start", ")", "throw", "new", "Error", "(", "\"A plugin must have a 'Start' method implemented.\"", ")", "// TODO, add a way to call StartWithConfig", "log", ".", "info", "(", "' Checking if plugin should start...'", ")", "if", "(", "p", ".", "ShouldStart", "(", "e", ",", "m", ",", "n", ",", "f", ",", "config", ")", ")", "{", "log", ".", "info", "(", "'Plugin should start = true. Starting plugin...'", ")", "p", ".", "Start", "(", "e", ",", "m", ",", "n", ",", "f", ",", "config", ")", "}", "else", "{", "log", ".", "info", "(", "'Plugin will not start because returned false when asked if it should start.'", ")", "}", "console", ".", "log", "(", "'ok.'", ")", "}", ")", "}" ]
Internal function which Starts all the Plugins, ran when StartWithConfir is called. Throws an Error if any of the plugins does not implement the "Start" method. @param {e} The current Environment. @param {m} The current MotionDetectors. @param {n} The current Notifiers. @param {f} The current Filters.
[ "Internal", "function", "which", "Starts", "all", "the", "Plugins", "ran", "when", "StartWithConfir", "is", "called", ".", "Throws", "an", "Error", "if", "any", "of", "the", "plugins", "does", "not", "implement", "the", "Start", "method", "." ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L417-L435
39,689
tcardoso2/vermon
main.js
SaveAllToConfig
function SaveAllToConfig (src, callback, force = false) { let status = 1 let message let resultError = function (message) { message = `Error: ${message}` log.error(message) callback(1, message) } let resultWarning = function (message) { message = `Warn: ${message}` log.warning(message) callback(0, message) } let addConfigDefinitions = function (jsonContent) { return jsonContent = 'profiles = ' + jsonContent + '\nexports.profiles = profiles;' + '\nexports.default = profiles.default;' } if (fs.existsSync(src) && !force) { return resultError('File exists, if you want to overwrite it, use the force attribute') } else { let contents = addConfigDefinitions(_InternalSerializeCurrentContext()) fs.writeFile(src, contents, function (err) { if (err) { return resultError(err) } else { status = 0 message = 'Success' } callback(status, message) }) } }
javascript
function SaveAllToConfig (src, callback, force = false) { let status = 1 let message let resultError = function (message) { message = `Error: ${message}` log.error(message) callback(1, message) } let resultWarning = function (message) { message = `Warn: ${message}` log.warning(message) callback(0, message) } let addConfigDefinitions = function (jsonContent) { return jsonContent = 'profiles = ' + jsonContent + '\nexports.profiles = profiles;' + '\nexports.default = profiles.default;' } if (fs.existsSync(src) && !force) { return resultError('File exists, if you want to overwrite it, use the force attribute') } else { let contents = addConfigDefinitions(_InternalSerializeCurrentContext()) fs.writeFile(src, contents, function (err) { if (err) { return resultError(err) } else { status = 0 message = 'Success' } callback(status, message) }) } }
[ "function", "SaveAllToConfig", "(", "src", ",", "callback", ",", "force", "=", "false", ")", "{", "let", "status", "=", "1", "let", "message", "let", "resultError", "=", "function", "(", "message", ")", "{", "message", "=", "`", "${", "message", "}", "`", "log", ".", "error", "(", "message", ")", "callback", "(", "1", ",", "message", ")", "}", "let", "resultWarning", "=", "function", "(", "message", ")", "{", "message", "=", "`", "${", "message", "}", "`", "log", ".", "warning", "(", "message", ")", "callback", "(", "0", ",", "message", ")", "}", "let", "addConfigDefinitions", "=", "function", "(", "jsonContent", ")", "{", "return", "jsonContent", "=", "'profiles = '", "+", "jsonContent", "+", "'\\nexports.profiles = profiles;'", "+", "'\\nexports.default = profiles.default;'", "}", "if", "(", "fs", ".", "existsSync", "(", "src", ")", "&&", "!", "force", ")", "{", "return", "resultError", "(", "'File exists, if you want to overwrite it, use the force attribute'", ")", "}", "else", "{", "let", "contents", "=", "addConfigDefinitions", "(", "_InternalSerializeCurrentContext", "(", ")", ")", "fs", ".", "writeFile", "(", "src", ",", "contents", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "resultError", "(", "err", ")", "}", "else", "{", "status", "=", "0", "message", "=", "'Success'", "}", "callback", "(", "status", ",", "message", ")", "}", ")", "}", "}" ]
Saves all the Environment, Detector, Notifiers and Filters information into a config file @param {String} src is the path of the config file to use @param {Function} callback is the callback function to call once the Save is all done, it passes status and message as arguments to the function: \m status = 0: Successfully has performed the action. status = 1: Error: File exists already. @param {Boolean} force true if the user wants to overwrite an already existing file.
[ "Saves", "all", "the", "Environment", "Detector", "Notifiers", "and", "Filters", "information", "into", "a", "config", "file" ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L710-L747
39,690
tcardoso2/vermon
main.js
_InternalSerializeCurrentContext
function _InternalSerializeCurrentContext () { let profile = { default: {} } // Separate this function into another utils library. let serializeEntity = function (ent) { if (ent.constructor.name === 'Array') { serializeArray() } else { profile.default[ent.constructor.name] = ent } } let serializeArray = function (ent) { let entityName for (let ei in ent) { // First, it creates as many entries of the same object as existing and initializes as empty arrays if (ent[ei].constructor.name !== entityName) { entityName = ent[ei].constructor.name profile.default[entityName] = [] } } for (let ei in ent) { // Then it reiterates again, this time pushing the contents to the correct array record profile.default[ent[ei].constructor.name].push(ent[ei]) } } serializeEntity(GetEnvironment()) serializeArray(GetMotionDetectors()) serializeArray(GetNotifiers()) serializeArray(GetFilters()) return utils.JSON.stringify(profile) }
javascript
function _InternalSerializeCurrentContext () { let profile = { default: {} } // Separate this function into another utils library. let serializeEntity = function (ent) { if (ent.constructor.name === 'Array') { serializeArray() } else { profile.default[ent.constructor.name] = ent } } let serializeArray = function (ent) { let entityName for (let ei in ent) { // First, it creates as many entries of the same object as existing and initializes as empty arrays if (ent[ei].constructor.name !== entityName) { entityName = ent[ei].constructor.name profile.default[entityName] = [] } } for (let ei in ent) { // Then it reiterates again, this time pushing the contents to the correct array record profile.default[ent[ei].constructor.name].push(ent[ei]) } } serializeEntity(GetEnvironment()) serializeArray(GetMotionDetectors()) serializeArray(GetNotifiers()) serializeArray(GetFilters()) return utils.JSON.stringify(profile) }
[ "function", "_InternalSerializeCurrentContext", "(", ")", "{", "let", "profile", "=", "{", "default", ":", "{", "}", "}", "// Separate this function into another utils library.", "let", "serializeEntity", "=", "function", "(", "ent", ")", "{", "if", "(", "ent", ".", "constructor", ".", "name", "===", "'Array'", ")", "{", "serializeArray", "(", ")", "}", "else", "{", "profile", ".", "default", "[", "ent", ".", "constructor", ".", "name", "]", "=", "ent", "}", "}", "let", "serializeArray", "=", "function", "(", "ent", ")", "{", "let", "entityName", "for", "(", "let", "ei", "in", "ent", ")", "{", "// First, it creates as many entries of the same object as existing and initializes as empty arrays", "if", "(", "ent", "[", "ei", "]", ".", "constructor", ".", "name", "!==", "entityName", ")", "{", "entityName", "=", "ent", "[", "ei", "]", ".", "constructor", ".", "name", "profile", ".", "default", "[", "entityName", "]", "=", "[", "]", "}", "}", "for", "(", "let", "ei", "in", "ent", ")", "{", "// Then it reiterates again, this time pushing the contents to the correct array record", "profile", ".", "default", "[", "ent", "[", "ei", "]", ".", "constructor", ".", "name", "]", ".", "push", "(", "ent", "[", "ei", "]", ")", "}", "}", "serializeEntity", "(", "GetEnvironment", "(", ")", ")", "serializeArray", "(", "GetMotionDetectors", "(", ")", ")", "serializeArray", "(", "GetNotifiers", "(", ")", ")", "serializeArray", "(", "GetFilters", "(", ")", ")", "return", "utils", ".", "JSON", ".", "stringify", "(", "profile", ")", "}" ]
Internal function which serializes the current Context into the format matching the "profile" object of the config file. @returns {object} Returns a "profile" object in JSON.stringify format @internal
[ "Internal", "function", "which", "serializes", "the", "current", "Context", "into", "the", "format", "matching", "the", "profile", "object", "of", "the", "config", "file", "." ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L755-L788
39,691
tcardoso2/vermon
main.js
function (ent) { if (ent.constructor.name === 'Array') { serializeArray() } else { profile.default[ent.constructor.name] = ent } }
javascript
function (ent) { if (ent.constructor.name === 'Array') { serializeArray() } else { profile.default[ent.constructor.name] = ent } }
[ "function", "(", "ent", ")", "{", "if", "(", "ent", ".", "constructor", ".", "name", "===", "'Array'", ")", "{", "serializeArray", "(", ")", "}", "else", "{", "profile", ".", "default", "[", "ent", ".", "constructor", ".", "name", "]", "=", "ent", "}", "}" ]
Separate this function into another utils library.
[ "Separate", "this", "function", "into", "another", "utils", "library", "." ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L759-L765
39,692
alexcjohnson/world-calendars
jquery-src/jquery.calendars.picker.ext.js
function(onHover) { return function(picker, calendar, inst) { if ($.isFunction(onHover)) { var target = this; var renderer = inst.options.renderer; picker.find(renderer.daySelector + ' a, ' + renderer.daySelector + ' span'). hover(function() { onHover.apply(target, [$(target).calendarsPicker('retrieveDate', this), this.nodeName.toLowerCase() === 'a']); }, function() { onHover.apply(target, []); }); } }; }
javascript
function(onHover) { return function(picker, calendar, inst) { if ($.isFunction(onHover)) { var target = this; var renderer = inst.options.renderer; picker.find(renderer.daySelector + ' a, ' + renderer.daySelector + ' span'). hover(function() { onHover.apply(target, [$(target).calendarsPicker('retrieveDate', this), this.nodeName.toLowerCase() === 'a']); }, function() { onHover.apply(target, []); }); } }; }
[ "function", "(", "onHover", ")", "{", "return", "function", "(", "picker", ",", "calendar", ",", "inst", ")", "{", "if", "(", "$", ".", "isFunction", "(", "onHover", ")", ")", "{", "var", "target", "=", "this", ";", "var", "renderer", "=", "inst", ".", "options", ".", "renderer", ";", "picker", ".", "find", "(", "renderer", ".", "daySelector", "+", "' a, '", "+", "renderer", ".", "daySelector", "+", "' span'", ")", ".", "hover", "(", "function", "(", ")", "{", "onHover", ".", "apply", "(", "target", ",", "[", "$", "(", "target", ")", ".", "calendarsPicker", "(", "'retrieveDate'", ",", "this", ")", ",", "this", ".", "nodeName", ".", "toLowerCase", "(", ")", "===", "'a'", "]", ")", ";", "}", ",", "function", "(", ")", "{", "onHover", ".", "apply", "(", "target", ",", "[", "]", ")", ";", "}", ")", ";", "}", "}", ";", "}" ]
A function to call when a date is hovered. @callback CalendarsPickerOnHover @param date {CDate} The date being hovered or <code>null</code> on exit. @param selectable {boolean} <code>true</code> if this date is selectable, <code>false</code> if not. @example function showHovered(date, selectable) { $('#feedback').text('You are viewing ' + (date ? date.formatDate() : 'nothing')); } Add a callback when hovering over dates. Found in the <code>jquery.calendars.picker.ext.js</code> module. @memberof CalendarsPicker @param onHover {CalendarsPickerOnHover} The callback when hovering. @example onShow: $.calendarsPicker.hoverCallback(showHovered)
[ "A", "function", "to", "call", "when", "a", "date", "is", "hovered", "." ]
810693882512dec1b804456f8d435b962bd6cf31
https://github.com/alexcjohnson/world-calendars/blob/810693882512dec1b804456f8d435b962bd6cf31/jquery-src/jquery.calendars.picker.ext.js#L111-L124
39,693
ImAdamTM/actions-ai-app
bin/lib/store.js
Store
function Store(context, app, data) { const state = Object.assign({}, defaultState, data); return { dispatch(key, payload) { const reducers = context.reducers[key]; /* istanbul ignore next */ if (!reducers) return; for (let i = 0, len = reducers.length; i < len; i += 1) { const reducer = reducers[i]; const newState = reducer.method(state[reducer.namespace], payload); if (newState === undefined) { debug( chalk.bold('Reducer did not return a new state:'), chalk.bold.magenta(`${reducer.namespace}.${key}`)); } else { state[reducer.namespace] = newState; } } app.data = Object.assign({}, app.data, state); }, getState() { return state; }, }; }
javascript
function Store(context, app, data) { const state = Object.assign({}, defaultState, data); return { dispatch(key, payload) { const reducers = context.reducers[key]; /* istanbul ignore next */ if (!reducers) return; for (let i = 0, len = reducers.length; i < len; i += 1) { const reducer = reducers[i]; const newState = reducer.method(state[reducer.namespace], payload); if (newState === undefined) { debug( chalk.bold('Reducer did not return a new state:'), chalk.bold.magenta(`${reducer.namespace}.${key}`)); } else { state[reducer.namespace] = newState; } } app.data = Object.assign({}, app.data, state); }, getState() { return state; }, }; }
[ "function", "Store", "(", "context", ",", "app", ",", "data", ")", "{", "const", "state", "=", "Object", ".", "assign", "(", "{", "}", ",", "defaultState", ",", "data", ")", ";", "return", "{", "dispatch", "(", "key", ",", "payload", ")", "{", "const", "reducers", "=", "context", ".", "reducers", "[", "key", "]", ";", "/* istanbul ignore next */", "if", "(", "!", "reducers", ")", "return", ";", "for", "(", "let", "i", "=", "0", ",", "len", "=", "reducers", ".", "length", ";", "i", "<", "len", ";", "i", "+=", "1", ")", "{", "const", "reducer", "=", "reducers", "[", "i", "]", ";", "const", "newState", "=", "reducer", ".", "method", "(", "state", "[", "reducer", ".", "namespace", "]", ",", "payload", ")", ";", "if", "(", "newState", "===", "undefined", ")", "{", "debug", "(", "chalk", ".", "bold", "(", "'Reducer did not return a new state:'", ")", ",", "chalk", ".", "bold", ".", "magenta", "(", "`", "${", "reducer", ".", "namespace", "}", "${", "key", "}", "`", ")", ")", ";", "}", "else", "{", "state", "[", "reducer", ".", "namespace", "]", "=", "newState", ";", "}", "}", "app", ".", "data", "=", "Object", ".", "assign", "(", "{", "}", ",", "app", ".", "data", ",", "state", ")", ";", "}", ",", "getState", "(", ")", "{", "return", "state", ";", "}", ",", "}", ";", "}" ]
The data `Store` is used to manage the session data for the application. We do not want to manipulate `app.data` directly as it becomes un-managable as things expand. Instead, we use a `redux` style approach where the data is managed via state. To learn more, read the [redux docs](http://redux.js.org/docs/basics/) @param {App} context the current instance context @param {Object} app the app response data @param {Object} data the data to assign to the state on creation @return {Object} the exposed methods for manipulating the store/state @private
[ "The", "data", "Store", "is", "used", "to", "manage", "the", "session", "data", "for", "the", "application", ".", "We", "do", "not", "want", "to", "manipulate", "app", ".", "data", "directly", "as", "it", "becomes", "un", "-", "managable", "as", "things", "expand", ".", "Instead", "we", "use", "a", "redux", "style", "approach", "where", "the", "data", "is", "managed", "via", "state", "." ]
2a236dde0508610ad38654c22669eab949260777
https://github.com/ImAdamTM/actions-ai-app/blob/2a236dde0508610ad38654c22669eab949260777/bin/lib/store.js#L22-L50
39,694
dinoboff/firebase-json
index.js
error
function error(original, fileName) { if ( original == null || original.location == null || original.location.start == null ) { return original; } const start = original.location.start; const lineNumber = start.line == null ? 1 : start.line; const columnNumber = start.column == null ? 1 : start.column; const err = new SyntaxError(`Line ${lineNumber}, column ${columnNumber}: ${original.message}`); Object.assign(err, {fileName, lineNumber, columnNumber, original}); if (fileName == null) { return err; } err.stack = `SyntaxError: ${err.message}\n at ${fileName}:${lineNumber}:${columnNumber} `; return err; }
javascript
function error(original, fileName) { if ( original == null || original.location == null || original.location.start == null ) { return original; } const start = original.location.start; const lineNumber = start.line == null ? 1 : start.line; const columnNumber = start.column == null ? 1 : start.column; const err = new SyntaxError(`Line ${lineNumber}, column ${columnNumber}: ${original.message}`); Object.assign(err, {fileName, lineNumber, columnNumber, original}); if (fileName == null) { return err; } err.stack = `SyntaxError: ${err.message}\n at ${fileName}:${lineNumber}:${columnNumber} `; return err; }
[ "function", "error", "(", "original", ",", "fileName", ")", "{", "if", "(", "original", "==", "null", "||", "original", ".", "location", "==", "null", "||", "original", ".", "location", ".", "start", "==", "null", ")", "{", "return", "original", ";", "}", "const", "start", "=", "original", ".", "location", ".", "start", ";", "const", "lineNumber", "=", "start", ".", "line", "==", "null", "?", "1", ":", "start", ".", "line", ";", "const", "columnNumber", "=", "start", ".", "column", "==", "null", "?", "1", ":", "start", ".", "column", ";", "const", "err", "=", "new", "SyntaxError", "(", "`", "${", "lineNumber", "}", "${", "columnNumber", "}", "${", "original", ".", "message", "}", "`", ")", ";", "Object", ".", "assign", "(", "err", ",", "{", "fileName", ",", "lineNumber", ",", "columnNumber", ",", "original", "}", ")", ";", "if", "(", "fileName", "==", "null", ")", "{", "return", "err", ";", "}", "err", ".", "stack", "=", "`", "${", "err", ".", "message", "}", "\\n", "${", "fileName", "}", "${", "lineNumber", "}", "${", "columnNumber", "}", "`", ";", "return", "err", ";", "}" ]
Create a SyntaxError with fileName, lineNumber, columnNumber and stack pointing to the syntax error in the the json file. @param {Error} original Pegjs syntax error @param {string} fileName JSON file name @return {Error}
[ "Create", "a", "SyntaxError", "with", "fileName", "lineNumber", "columnNumber", "and", "stack", "pointing", "to", "the", "syntax", "error", "in", "the", "the", "json", "file", "." ]
9f9c34e0167510916223bb4045127a81e02fd39f
https://github.com/dinoboff/firebase-json/blob/9f9c34e0167510916223bb4045127a81e02fd39f/index.js#L14-L39
39,695
dinoboff/firebase-json
index.js
astValue
function astValue(node) { switch (node.type) { case 'ExpressionStatement': return astValue(node.expression); case 'ObjectExpression': return node.properties.reduce( (obj, prop) => Object.assign(obj, {[prop.key.value]: astValue(prop.value)}), {} ); case 'ArrayExpression': return node.elements.map(element => astValue(element)); case 'Literal': return node.value; default: throw new Error(`Unexpected ast node type: ${node.type}`); } }
javascript
function astValue(node) { switch (node.type) { case 'ExpressionStatement': return astValue(node.expression); case 'ObjectExpression': return node.properties.reduce( (obj, prop) => Object.assign(obj, {[prop.key.value]: astValue(prop.value)}), {} ); case 'ArrayExpression': return node.elements.map(element => astValue(element)); case 'Literal': return node.value; default: throw new Error(`Unexpected ast node type: ${node.type}`); } }
[ "function", "astValue", "(", "node", ")", "{", "switch", "(", "node", ".", "type", ")", "{", "case", "'ExpressionStatement'", ":", "return", "astValue", "(", "node", ".", "expression", ")", ";", "case", "'ObjectExpression'", ":", "return", "node", ".", "properties", ".", "reduce", "(", "(", "obj", ",", "prop", ")", "=>", "Object", ".", "assign", "(", "obj", ",", "{", "[", "prop", ".", "key", ".", "value", "]", ":", "astValue", "(", "prop", ".", "value", ")", "}", ")", ",", "{", "}", ")", ";", "case", "'ArrayExpression'", ":", "return", "node", ".", "elements", ".", "map", "(", "element", "=>", "astValue", "(", "element", ")", ")", ";", "case", "'Literal'", ":", "return", "node", ".", "value", ";", "default", ":", "throw", "new", "Error", "(", "`", "${", "node", ".", "type", "}", "`", ")", ";", "}", "}" ]
Evaluate AST node to a value. @param {object} node Node to evaluate @return {any}
[ "Evaluate", "AST", "node", "to", "a", "value", "." ]
9f9c34e0167510916223bb4045127a81e02fd39f
https://github.com/dinoboff/firebase-json/blob/9f9c34e0167510916223bb4045127a81e02fd39f/index.js#L47-L70
39,696
smbape/node-umd-builder
build.js
remove
function remove(file, options, done) { if (arguments.length === 2 && 'function' === typeof options) { done = options; options = {}; } if ('function' !== typeof done) { done = function() {}; } function callfile(file, stats, done) { fs.unlink(file, done); } function calldir(dir, stats, files, state, done) { if (state === 'end') { if (options.empty && dir === file) { done(); } else { if (stats.isSymbolicLink()) { fs.unlink(dir, done); } else { fs.rmdir(dir, function(er) { if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) { // try in few time, last deletion is not completely ended setTimeout(function() { fs.rmdir(dir, done); }, 10); } else { done(er); } }); } } } else { done(); } } options = Object.assign({ fs: fs, resolve: true, followSymlink: false }, options); _explore(file, callfile, calldir, options, done); }
javascript
function remove(file, options, done) { if (arguments.length === 2 && 'function' === typeof options) { done = options; options = {}; } if ('function' !== typeof done) { done = function() {}; } function callfile(file, stats, done) { fs.unlink(file, done); } function calldir(dir, stats, files, state, done) { if (state === 'end') { if (options.empty && dir === file) { done(); } else { if (stats.isSymbolicLink()) { fs.unlink(dir, done); } else { fs.rmdir(dir, function(er) { if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) { // try in few time, last deletion is not completely ended setTimeout(function() { fs.rmdir(dir, done); }, 10); } else { done(er); } }); } } } else { done(); } } options = Object.assign({ fs: fs, resolve: true, followSymlink: false }, options); _explore(file, callfile, calldir, options, done); }
[ "function", "remove", "(", "file", ",", "options", ",", "done", ")", "{", "if", "(", "arguments", ".", "length", "===", "2", "&&", "'function'", "===", "typeof", "options", ")", "{", "done", "=", "options", ";", "options", "=", "{", "}", ";", "}", "if", "(", "'function'", "!==", "typeof", "done", ")", "{", "done", "=", "function", "(", ")", "{", "}", ";", "}", "function", "callfile", "(", "file", ",", "stats", ",", "done", ")", "{", "fs", ".", "unlink", "(", "file", ",", "done", ")", ";", "}", "function", "calldir", "(", "dir", ",", "stats", ",", "files", ",", "state", ",", "done", ")", "{", "if", "(", "state", "===", "'end'", ")", "{", "if", "(", "options", ".", "empty", "&&", "dir", "===", "file", ")", "{", "done", "(", ")", ";", "}", "else", "{", "if", "(", "stats", ".", "isSymbolicLink", "(", ")", ")", "{", "fs", ".", "unlink", "(", "dir", ",", "done", ")", ";", "}", "else", "{", "fs", ".", "rmdir", "(", "dir", ",", "function", "(", "er", ")", "{", "if", "(", "er", "&&", "(", "er", ".", "code", "===", "'ENOTEMPTY'", "||", "er", ".", "code", "===", "'EEXIST'", "||", "er", ".", "code", "===", "'EPERM'", ")", ")", "{", "// try in few time, last deletion is not completely ended", "setTimeout", "(", "function", "(", ")", "{", "fs", ".", "rmdir", "(", "dir", ",", "done", ")", ";", "}", ",", "10", ")", ";", "}", "else", "{", "done", "(", "er", ")", ";", "}", "}", ")", ";", "}", "}", "}", "else", "{", "done", "(", ")", ";", "}", "}", "options", "=", "Object", ".", "assign", "(", "{", "fs", ":", "fs", ",", "resolve", ":", "true", ",", "followSymlink", ":", "false", "}", ",", "options", ")", ";", "_explore", "(", "file", ",", "callfile", ",", "calldir", ",", "options", ",", "done", ")", ";", "}" ]
rm -rf. Symlink are not resolved by default, avoiding unwanted deep deletion there should be a way to do it with rimraf, but too much options digging to find a way to do it @param {String} file or folder to remove @param {Function} done called on end
[ "rm", "-", "rf", ".", "Symlink", "are", "not", "resolved", "by", "default", "avoiding", "unwanted", "deep", "deletion", "there", "should", "be", "a", "way", "to", "do", "it", "with", "rimraf", "but", "too", "much", "options", "digging", "to", "find", "a", "way", "to", "do", "it" ]
73b03e8c985f2660948f5df71140e4a8fb162549
https://github.com/smbape/node-umd-builder/blob/73b03e8c985f2660948f5df71140e4a8fb162549/build.js#L111-L157
39,697
sat-utils/sat-api-lib
libs/ingest-csv.js
processFiles
function processFiles(bucket, key, transform, cb, currentFileNum=0, lastFileNum=0, arn=null, retries=0) { const maxRetries = 5 var nextFileNum = (currentFileNum < lastFileNum) ? currentFileNum + 1 : null //invokeLambda(bucket, key, currentFileNum, lastFileNum, arn) processFile( bucket, `${key}${currentFileNum}.csv`, transform ).then((n_scenes) => { invokeLambda(bucket, key, nextFileNum, lastFileNum, arn, 0) cb() }).catch((e) => { // if CSV failed, try it again if (retries < maxRetries) { invokeLambda(bucket, key, currentFileNum, lastFileNum, arn, retries + 1) } else { // log and move onto the next one console.log(`error: maxRetries hit in file ${currentFileNum}`) invokeLambda(bucket, key, nextFileNum, lastFileNum, arn, 0) } cb() }) }
javascript
function processFiles(bucket, key, transform, cb, currentFileNum=0, lastFileNum=0, arn=null, retries=0) { const maxRetries = 5 var nextFileNum = (currentFileNum < lastFileNum) ? currentFileNum + 1 : null //invokeLambda(bucket, key, currentFileNum, lastFileNum, arn) processFile( bucket, `${key}${currentFileNum}.csv`, transform ).then((n_scenes) => { invokeLambda(bucket, key, nextFileNum, lastFileNum, arn, 0) cb() }).catch((e) => { // if CSV failed, try it again if (retries < maxRetries) { invokeLambda(bucket, key, currentFileNum, lastFileNum, arn, retries + 1) } else { // log and move onto the next one console.log(`error: maxRetries hit in file ${currentFileNum}`) invokeLambda(bucket, key, nextFileNum, lastFileNum, arn, 0) } cb() }) }
[ "function", "processFiles", "(", "bucket", ",", "key", ",", "transform", ",", "cb", ",", "currentFileNum", "=", "0", ",", "lastFileNum", "=", "0", ",", "arn", "=", "null", ",", "retries", "=", "0", ")", "{", "const", "maxRetries", "=", "5", "var", "nextFileNum", "=", "(", "currentFileNum", "<", "lastFileNum", ")", "?", "currentFileNum", "+", "1", ":", "null", "//invokeLambda(bucket, key, currentFileNum, lastFileNum, arn)", "processFile", "(", "bucket", ",", "`", "${", "key", "}", "${", "currentFileNum", "}", "`", ",", "transform", ")", ".", "then", "(", "(", "n_scenes", ")", "=>", "{", "invokeLambda", "(", "bucket", ",", "key", ",", "nextFileNum", ",", "lastFileNum", ",", "arn", ",", "0", ")", "cb", "(", ")", "}", ")", ".", "catch", "(", "(", "e", ")", "=>", "{", "// if CSV failed, try it again", "if", "(", "retries", "<", "maxRetries", ")", "{", "invokeLambda", "(", "bucket", ",", "key", ",", "currentFileNum", ",", "lastFileNum", ",", "arn", ",", "retries", "+", "1", ")", "}", "else", "{", "// log and move onto the next one", "console", ".", "log", "(", "`", "${", "currentFileNum", "}", "`", ")", "invokeLambda", "(", "bucket", ",", "key", ",", "nextFileNum", ",", "lastFileNum", ",", "arn", ",", "0", ")", "}", "cb", "(", ")", "}", ")", "}" ]
Process 1 or more CSV files by processing one at a time, then invoking the next
[ "Process", "1", "or", "more", "CSV", "files", "by", "processing", "one", "at", "a", "time", "then", "invoking", "the", "next" ]
74ef1cb09789ecc9c18512781a95eada6fdc3813
https://github.com/sat-utils/sat-api-lib/blob/74ef1cb09789ecc9c18512781a95eada6fdc3813/libs/ingest-csv.js#L123-L145
39,698
sat-utils/sat-api-lib
libs/ingest-csv.js
processFile
function processFile(bucket, key, transform) { // get the csv file s3://${bucket}/${key} console.log(`Processing s3://${bucket}/${key}`) const s3 = new AWS.S3() const csvStream = csv.parse({ headers: true, objectMode: true }) s3.getObject({Bucket: bucket, Key: key}).createReadStream().pipe(csvStream) return es.streamToEs(csvStream, transform, esClient, index) }
javascript
function processFile(bucket, key, transform) { // get the csv file s3://${bucket}/${key} console.log(`Processing s3://${bucket}/${key}`) const s3 = new AWS.S3() const csvStream = csv.parse({ headers: true, objectMode: true }) s3.getObject({Bucket: bucket, Key: key}).createReadStream().pipe(csvStream) return es.streamToEs(csvStream, transform, esClient, index) }
[ "function", "processFile", "(", "bucket", ",", "key", ",", "transform", ")", "{", "// get the csv file s3://${bucket}/${key}", "console", ".", "log", "(", "`", "${", "bucket", "}", "${", "key", "}", "`", ")", "const", "s3", "=", "new", "AWS", ".", "S3", "(", ")", "const", "csvStream", "=", "csv", ".", "parse", "(", "{", "headers", ":", "true", ",", "objectMode", ":", "true", "}", ")", "s3", ".", "getObject", "(", "{", "Bucket", ":", "bucket", ",", "Key", ":", "key", "}", ")", ".", "createReadStream", "(", ")", ".", "pipe", "(", "csvStream", ")", "return", "es", ".", "streamToEs", "(", "csvStream", ",", "transform", ",", "esClient", ",", "index", ")", "}" ]
Process single CSV file
[ "Process", "single", "CSV", "file" ]
74ef1cb09789ecc9c18512781a95eada6fdc3813
https://github.com/sat-utils/sat-api-lib/blob/74ef1cb09789ecc9c18512781a95eada6fdc3813/libs/ingest-csv.js#L149-L156
39,699
sat-utils/sat-api-lib
libs/ingest-csv.js
invokeLambda
function invokeLambda(bucket, key, nextFileNum, lastFileNum, arn, retries) { // figure out if there's a next file to process if (nextFileNum && arn) { const stepfunctions = new AWS.StepFunctions() const params = { stateMachineArn: arn, input: JSON.stringify({ bucket, key, currentFileNum: nextFileNum, lastFileNum, arn, retries}), name: `ingest_${nextFileNum}_${Date.now()}` } stepfunctions.startExecution(params, function(err, data) { if (err) { console.log(err, err.stack) } else { console.log(`launched ${JSON.stringify(params)}`) } }) } }
javascript
function invokeLambda(bucket, key, nextFileNum, lastFileNum, arn, retries) { // figure out if there's a next file to process if (nextFileNum && arn) { const stepfunctions = new AWS.StepFunctions() const params = { stateMachineArn: arn, input: JSON.stringify({ bucket, key, currentFileNum: nextFileNum, lastFileNum, arn, retries}), name: `ingest_${nextFileNum}_${Date.now()}` } stepfunctions.startExecution(params, function(err, data) { if (err) { console.log(err, err.stack) } else { console.log(`launched ${JSON.stringify(params)}`) } }) } }
[ "function", "invokeLambda", "(", "bucket", ",", "key", ",", "nextFileNum", ",", "lastFileNum", ",", "arn", ",", "retries", ")", "{", "// figure out if there's a next file to process", "if", "(", "nextFileNum", "&&", "arn", ")", "{", "const", "stepfunctions", "=", "new", "AWS", ".", "StepFunctions", "(", ")", "const", "params", "=", "{", "stateMachineArn", ":", "arn", ",", "input", ":", "JSON", ".", "stringify", "(", "{", "bucket", ",", "key", ",", "currentFileNum", ":", "nextFileNum", ",", "lastFileNum", ",", "arn", ",", "retries", "}", ")", ",", "name", ":", "`", "${", "nextFileNum", "}", "${", "Date", ".", "now", "(", ")", "}", "`", "}", "stepfunctions", ".", "startExecution", "(", "params", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "console", ".", "log", "(", "err", ",", "err", ".", "stack", ")", "}", "else", "{", "console", ".", "log", "(", "`", "${", "JSON", ".", "stringify", "(", "params", ")", "}", "`", ")", "}", "}", ")", "}", "}" ]
kick off processing next CSV file
[ "kick", "off", "processing", "next", "CSV", "file" ]
74ef1cb09789ecc9c18512781a95eada6fdc3813
https://github.com/sat-utils/sat-api-lib/blob/74ef1cb09789ecc9c18512781a95eada6fdc3813/libs/ingest-csv.js#L160-L177