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
28,700
AckerApple/ack-angular-fx
bin/src/animations/helper.js
inFromVoid
function inFromVoid(from, to) { return to !== null && to !== 'nofx' && from === 'void' && to !== 'void' ? true : false; }
javascript
function inFromVoid(from, to) { return to !== null && to !== 'nofx' && from === 'void' && to !== 'void' ? true : false; }
[ "function", "inFromVoid", "(", "from", ",", "to", ")", "{", "return", "to", "!==", "null", "&&", "to", "!==", "'nofx'", "&&", "from", "===", "'void'", "&&", "to", "!==", "'void'", "?", "true", ":", "false", ";", "}" ]
used for showing
[ "used", "for", "showing" ]
35308841b3d5a5736063a0cabdb414ced0522747
https://github.com/AckerApple/ack-angular-fx/blob/35308841b3d5a5736063a0cabdb414ced0522747/bin/src/animations/helper.js#L46-L48
28,701
soney/constraintjs
src/state_machine/cjs_events.js
function(event_type) { var rest_args = arguments.length > 1 ? rest(arguments) : root, // no parent, no filter by default event = new CJSEvent(false, false, function(transition) { var targets = [], timeout_id = false, event_type_val = [], listener = bind(this._fire, this), fsm = transition.getFSM(), from = transition.getFrom(), state_selector = new StateSelector(from), from_state_selector = new TransitionSelector(true, state_selector, new AnyStateSelector()), on_listener = function() { each(event_type_val, function(event_type) { // If the event is 'timeout' if(event_type === timeout_event_type) { // clear the previous timeout if(timeout_id) { cTO(timeout_id); timeout_id = false; } // and set a new one var delay = cjs.get(rest_args[0]); if(!isNumber(delay) || delay < 0) { delay = 0; } timeout_id = sTO(listener, delay); } else { each(targets, function(target) { // otherwise, add the event listener to every one of my targets aEL(target, event_type, listener); }); } }); }, off_listener = function() { each(event_type_val, function(event_type) { each(targets, function(target) { if(event_type === timeout_event_type) { // If the event is 'timeout' if(timeout_id) { cTO(timeout_id); timeout_id = false; } } else { rEL(target, event_type, listener); } }); }); }, live_fn = cjs.liven(function() { off_listener(); event_type_val = split_and_trim(cjs.get(event_type)); // only use DOM elements (or the window) as my target targets = flatten(map(filter(get_dom_array(rest_args), isElementOrWindow), getDOMChildren , true)); // when entering the state, add the event listeners, then remove them when leaving the state fsm .on(state_selector, on_listener) .on(from_state_selector, off_listener); if(fsm.is(from)) { // if the FSM is already in the transition's starting state on_listener(); } }); return live_fn; }); return event; }
javascript
function(event_type) { var rest_args = arguments.length > 1 ? rest(arguments) : root, // no parent, no filter by default event = new CJSEvent(false, false, function(transition) { var targets = [], timeout_id = false, event_type_val = [], listener = bind(this._fire, this), fsm = transition.getFSM(), from = transition.getFrom(), state_selector = new StateSelector(from), from_state_selector = new TransitionSelector(true, state_selector, new AnyStateSelector()), on_listener = function() { each(event_type_val, function(event_type) { // If the event is 'timeout' if(event_type === timeout_event_type) { // clear the previous timeout if(timeout_id) { cTO(timeout_id); timeout_id = false; } // and set a new one var delay = cjs.get(rest_args[0]); if(!isNumber(delay) || delay < 0) { delay = 0; } timeout_id = sTO(listener, delay); } else { each(targets, function(target) { // otherwise, add the event listener to every one of my targets aEL(target, event_type, listener); }); } }); }, off_listener = function() { each(event_type_val, function(event_type) { each(targets, function(target) { if(event_type === timeout_event_type) { // If the event is 'timeout' if(timeout_id) { cTO(timeout_id); timeout_id = false; } } else { rEL(target, event_type, listener); } }); }); }, live_fn = cjs.liven(function() { off_listener(); event_type_val = split_and_trim(cjs.get(event_type)); // only use DOM elements (or the window) as my target targets = flatten(map(filter(get_dom_array(rest_args), isElementOrWindow), getDOMChildren , true)); // when entering the state, add the event listeners, then remove them when leaving the state fsm .on(state_selector, on_listener) .on(from_state_selector, off_listener); if(fsm.is(from)) { // if the FSM is already in the transition's starting state on_listener(); } }); return live_fn; }); return event; }
[ "function", "(", "event_type", ")", "{", "var", "rest_args", "=", "arguments", ".", "length", ">", "1", "?", "rest", "(", "arguments", ")", ":", "root", ",", "// no parent, no filter by default", "event", "=", "new", "CJSEvent", "(", "false", ",", "false", ...
Create a new event for use in a finite state machine transition @constructs CJSEvent @method cjs.on @param {string} event_type - the type of event to listen for (e.g. mousedown, timeout) @param {element|number} ...targets=window - Any number of target objects to listen to @return {CJSEvent} - An event that can be attached to @example When the window resizes cjs.on("resize") @example When the user clicks `elem1` or `elem2` cjs.on("click", elem1, elem2) @example After 3 seconds cjs.on("timeout", 3000)
[ "Create", "a", "new", "event", "for", "use", "in", "a", "finite", "state", "machine", "transition" ]
98a164063efc8d3b59a372b332c7a3e0a1292561
https://github.com/soney/constraintjs/blob/98a164063efc8d3b59a372b332c7a3e0a1292561/src/state_machine/cjs_events.js#L138-L209
28,702
soney/constraintjs
src/memoize.js
function () { var args = slice.call(arguments), constraint = options.args_map.getOrPut(args, function() { return new Constraint(function () { return getter_fn.apply(options.context, args); }); }); return constraint.get(); }
javascript
function () { var args = slice.call(arguments), constraint = options.args_map.getOrPut(args, function() { return new Constraint(function () { return getter_fn.apply(options.context, args); }); }); return constraint.get(); }
[ "function", "(", ")", "{", "var", "args", "=", "slice", ".", "call", "(", "arguments", ")", ",", "constraint", "=", "options", ".", "args_map", ".", "getOrPut", "(", "args", ",", "function", "(", ")", "{", "return", "new", "Constraint", "(", "function"...
When getting a value either create a constraint or return the existing value
[ "When", "getting", "a", "value", "either", "create", "a", "constraint", "or", "return", "the", "existing", "value" ]
98a164063efc8d3b59a372b332c7a3e0a1292561
https://github.com/soney/constraintjs/blob/98a164063efc8d3b59a372b332c7a3e0a1292561/src/memoize.js#L76-L84
28,703
soney/constraintjs
src/liven.js
function (silent) { if(options.on_destroy) { options.on_destroy.call(options.context, silent); } node.destroy(silent); }
javascript
function (silent) { if(options.on_destroy) { options.on_destroy.call(options.context, silent); } node.destroy(silent); }
[ "function", "(", "silent", ")", "{", "if", "(", "options", ".", "on_destroy", ")", "{", "options", ".", "on_destroy", ".", "call", "(", "options", ".", "context", ",", "silent", ")", ";", "}", "node", ".", "destroy", "(", "silent", ")", ";", "}" ]
Destroy the node and make sure no memory is allocated
[ "Destroy", "the", "node", "and", "make", "sure", "no", "memory", "is", "allocated" ]
98a164063efc8d3b59a372b332c7a3e0a1292561
https://github.com/soney/constraintjs/blob/98a164063efc8d3b59a372b332c7a3e0a1292561/src/liven.js#L59-L64
28,704
soney/constraintjs
src/liven.js
function () { if(paused === true) { paused = false; node.onChangeWithPriority(options.priority, do_get); if(options.run_on_create !== false) { if (constraint_solver.semaphore >= 0) { node.get(false); } else { each(node._changeListeners, constraint_solver.add_in_call_stack, constraint_solver); } } return true; // successfully resumed } return false; }
javascript
function () { if(paused === true) { paused = false; node.onChangeWithPriority(options.priority, do_get); if(options.run_on_create !== false) { if (constraint_solver.semaphore >= 0) { node.get(false); } else { each(node._changeListeners, constraint_solver.add_in_call_stack, constraint_solver); } } return true; // successfully resumed } return false; }
[ "function", "(", ")", "{", "if", "(", "paused", "===", "true", ")", "{", "paused", "=", "false", ";", "node", ".", "onChangeWithPriority", "(", "options", ".", "priority", ",", "do_get", ")", ";", "if", "(", "options", ".", "run_on_create", "!==", "fal...
Re-add to the event queue
[ "Re", "-", "add", "to", "the", "event", "queue" ]
98a164063efc8d3b59a372b332c7a3e0a1292561
https://github.com/soney/constraintjs/blob/98a164063efc8d3b59a372b332c7a3e0a1292561/src/liven.js#L77-L91
28,705
soney/constraintjs
src/binding.js
function(options) { this.options = options; this.targets = options.targets; // the DOM nodes var setter = options.setter, // a function that sets the attribute value getter = options.getter, // a function that gets the attribute value init_val = options.init_val, // the value of the attribute before the binding was set curr_value, // used in live fn last_value, // used in live fn old_targets = [], // used in live fn do_update = function() { this._timeout_id = false; // Make it clear that I don't have a timeout set var new_targets = filter(get_dom_array(this.targets), isAnyElement); // update the list of targets if(has(options, "onChange")) { options.onChange.call(this, curr_value, last_value); } // For every target, update the attribute each(new_targets, function(target) { setter.call(this, target, curr_value, last_value); }, this); // track the last value so that next time we call diff last_value = curr_value; }; this._throttle_delay = false; // Optional throttling to improve performance this._timeout_id = false; // tracks the timeout that helps throttle if(isFunction(init_val)) { // If init_val is a getter, call it on the first element last_value = init_val(get_dom_array(this.targets[0])); } else { // Otherwise, just take it as is last_value = init_val; } this.$live_fn = cjs.liven(function() { curr_value = getter(); // get the value once and inside of live fn to make sure a dependency is added if(this._throttle_delay) { // We shouldn't update values right away if(!this._timeout_id) { // If there isn't any timeout set yet, then set a timeout to delay the call to do update this._timeout_id = sTO(bind(do_update, this), this._throttle_delay); } } else { // we can update the value right away if no throttle delay is set do_update.call(this); } }, { context: this }); }
javascript
function(options) { this.options = options; this.targets = options.targets; // the DOM nodes var setter = options.setter, // a function that sets the attribute value getter = options.getter, // a function that gets the attribute value init_val = options.init_val, // the value of the attribute before the binding was set curr_value, // used in live fn last_value, // used in live fn old_targets = [], // used in live fn do_update = function() { this._timeout_id = false; // Make it clear that I don't have a timeout set var new_targets = filter(get_dom_array(this.targets), isAnyElement); // update the list of targets if(has(options, "onChange")) { options.onChange.call(this, curr_value, last_value); } // For every target, update the attribute each(new_targets, function(target) { setter.call(this, target, curr_value, last_value); }, this); // track the last value so that next time we call diff last_value = curr_value; }; this._throttle_delay = false; // Optional throttling to improve performance this._timeout_id = false; // tracks the timeout that helps throttle if(isFunction(init_val)) { // If init_val is a getter, call it on the first element last_value = init_val(get_dom_array(this.targets[0])); } else { // Otherwise, just take it as is last_value = init_val; } this.$live_fn = cjs.liven(function() { curr_value = getter(); // get the value once and inside of live fn to make sure a dependency is added if(this._throttle_delay) { // We shouldn't update values right away if(!this._timeout_id) { // If there isn't any timeout set yet, then set a timeout to delay the call to do update this._timeout_id = sTO(bind(do_update, this), this._throttle_delay); } } else { // we can update the value right away if no throttle delay is set do_update.call(this); } }, { context: this }); }
[ "function", "(", "options", ")", "{", "this", ".", "options", "=", "options", ";", "this", ".", "targets", "=", "options", ".", "targets", ";", "// the DOM nodes", "var", "setter", "=", "options", ".", "setter", ",", "// a function that sets the attribute value"...
A binding calls some arbitrary functions passed into options. It is responsible for keeping some aspect of a DOM node in line with a constraint value. For example, it might keep an element's class name in sync with a class_name constraint @private @class cjs.Binding @param {object} options @classdesc Bind a DOM node property to a constraint value
[ "A", "binding", "calls", "some", "arbitrary", "functions", "passed", "into", "options", ".", "It", "is", "responsible", "for", "keeping", "some", "aspect", "of", "a", "DOM", "node", "in", "line", "with", "a", "constraint", "value", ".", "For", "example", "...
98a164063efc8d3b59a372b332c7a3e0a1292561
https://github.com/soney/constraintjs/blob/98a164063efc8d3b59a372b332c7a3e0a1292561/src/binding.js#L79-L126
28,706
soney/constraintjs
src/binding.js
function() { this._timeout_id = false; // Make it clear that I don't have a timeout set var new_targets = filter(get_dom_array(this.targets), isAnyElement); // update the list of targets if(has(options, "onChange")) { options.onChange.call(this, curr_value, last_value); } // For every target, update the attribute each(new_targets, function(target) { setter.call(this, target, curr_value, last_value); }, this); // track the last value so that next time we call diff last_value = curr_value; }
javascript
function() { this._timeout_id = false; // Make it clear that I don't have a timeout set var new_targets = filter(get_dom_array(this.targets), isAnyElement); // update the list of targets if(has(options, "onChange")) { options.onChange.call(this, curr_value, last_value); } // For every target, update the attribute each(new_targets, function(target) { setter.call(this, target, curr_value, last_value); }, this); // track the last value so that next time we call diff last_value = curr_value; }
[ "function", "(", ")", "{", "this", ".", "_timeout_id", "=", "false", ";", "// Make it clear that I don't have a timeout set", "var", "new_targets", "=", "filter", "(", "get_dom_array", "(", "this", ".", "targets", ")", ",", "isAnyElement", ")", ";", "// update the...
the DOM nodes
[ "the", "DOM", "nodes" ]
98a164063efc8d3b59a372b332c7a3e0a1292561
https://github.com/soney/constraintjs/blob/98a164063efc8d3b59a372b332c7a3e0a1292561/src/binding.js#L88-L103
28,707
soney/constraintjs
src/map.js
function (infos, silent) { each(infos, function (info) { info.key.destroy(silent); info.value.destroy(silent); info.index.destroy(silent); }); }
javascript
function (infos, silent) { each(infos, function (info) { info.key.destroy(silent); info.value.destroy(silent); info.index.destroy(silent); }); }
[ "function", "(", "infos", ",", "silent", ")", "{", "each", "(", "infos", ",", "function", "(", "info", ")", "{", "info", ".", "key", ".", "destroy", "(", "silent", ")", ";", "info", ".", "value", ".", "destroy", "(", "silent", ")", ";", "info", "...
Deallocate memory from constraints
[ "Deallocate", "memory", "from", "constraints" ]
98a164063efc8d3b59a372b332c7a3e0a1292561
https://github.com/soney/constraintjs/blob/98a164063efc8d3b59a372b332c7a3e0a1292561/src/map.js#L370-L376
28,708
soney/constraintjs
src/map.js
function (index, silent) { var info = this._ordered_values[index]; _destroy_info(this._ordered_values.splice(index, 1), silent); if(silent !== true) { this.$size.invalidate(); } }
javascript
function (index, silent) { var info = this._ordered_values[index]; _destroy_info(this._ordered_values.splice(index, 1), silent); if(silent !== true) { this.$size.invalidate(); } }
[ "function", "(", "index", ",", "silent", ")", "{", "var", "info", "=", "this", ".", "_ordered_values", "[", "index", "]", ";", "_destroy_info", "(", "this", ".", "_ordered_values", ".", "splice", "(", "index", ",", "1", ")", ",", "silent", ")", ";", ...
removes the selected item and destroys its value to deallocate it
[ "removes", "the", "selected", "item", "and", "destroys", "its", "value", "to", "deallocate", "it" ]
98a164063efc8d3b59a372b332c7a3e0a1292561
https://github.com/soney/constraintjs/blob/98a164063efc8d3b59a372b332c7a3e0a1292561/src/map.js#L379-L385
28,709
soney/constraintjs
src/template/cjs_template.js
function(dom_node) { var index = get_template_instance_index(getFirstDOMChild(dom_node)), instance = index >= 0 ? template_instances[index] : false; if(instance) { delete template_instances[index]; instance.destroy(); } return this; }
javascript
function(dom_node) { var index = get_template_instance_index(getFirstDOMChild(dom_node)), instance = index >= 0 ? template_instances[index] : false; if(instance) { delete template_instances[index]; instance.destroy(); } return this; }
[ "function", "(", "dom_node", ")", "{", "var", "index", "=", "get_template_instance_index", "(", "getFirstDOMChild", "(", "dom_node", ")", ")", ",", "instance", "=", "index", ">=", "0", "?", "template_instances", "[", "index", "]", ":", "false", ";", "if", ...
Destroy a template instance @method cjs.destroyTemplate @param {dom} node - The dom node created by `createTemplate` @return {boolean} - Whether the template was successfully removed @see cjs.createTemplate @see cjs.pauseTemplate @see cjs.resumeTemplate
[ "Destroy", "a", "template", "instance" ]
98a164063efc8d3b59a372b332c7a3e0a1292561
https://github.com/soney/constraintjs/blob/98a164063efc8d3b59a372b332c7a3e0a1292561/src/template/cjs_template.js#L963-L972
28,710
soney/constraintjs
src/template/cjs_template.js
function(str, context) { return cjs(function() { try { var node = jsep(cjs.get(str)); if(node.type === LITERAL) { return node.value; } else { return get_node_value(node, context, [context]); } } catch(e) { console.error(e); } }); }
javascript
function(str, context) { return cjs(function() { try { var node = jsep(cjs.get(str)); if(node.type === LITERAL) { return node.value; } else { return get_node_value(node, context, [context]); } } catch(e) { console.error(e); } }); }
[ "function", "(", "str", ",", "context", ")", "{", "return", "cjs", "(", "function", "(", ")", "{", "try", "{", "var", "node", "=", "jsep", "(", "cjs", ".", "get", "(", "str", ")", ")", ";", "if", "(", "node", ".", "type", "===", "LITERAL", ")",...
Parses a string and returns a constraint whose value represents the result of `eval`ing that string @method cjs.createParsedConstraint @param {string} str - The string to parse @param {object} context - The context in which to look for variables @return {cjs.Cosntraint} - Whether the template was successfully resumed @example Creating a parsed constraint `x` var a = cjs(1); var x = cjs.createParsedConstraint("a+b", {a: a, b: cjs(2)}) x.get(); // 3 a.set(2); x.get(); // 4
[ "Parses", "a", "string", "and", "returns", "a", "constraint", "whose", "value", "represents", "the", "result", "of", "eval", "ing", "that", "string" ]
98a164063efc8d3b59a372b332c7a3e0a1292561
https://github.com/soney/constraintjs/blob/98a164063efc8d3b59a372b332c7a3e0a1292561/src/template/cjs_template.js#L1022-L1036
28,711
nteract/kernelspecs
lib/traverse.js
promisify
function promisify(f, args) { return new Promise((resolve, reject) => f.apply(this, args.concat((err, x) => err ? reject(err) : resolve(x)))); }
javascript
function promisify(f, args) { return new Promise((resolve, reject) => f.apply(this, args.concat((err, x) => err ? reject(err) : resolve(x)))); }
[ "function", "promisify", "(", "f", ",", "args", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "f", ".", "apply", "(", "this", ",", "args", ".", "concat", "(", "(", "err", ",", "x", ")", "=>", "err", "?", "...
Converts a callback style call to a Promise @param {function} f a node style function that accepts a callback @param {Object[]} args arguments to pass to the function when invoking it @return {Promise<Object>} object returned by the function
[ "Converts", "a", "callback", "style", "call", "to", "a", "Promise" ]
fee333ef5561e2eede5242b3affd98d37b173343
https://github.com/nteract/kernelspecs/blob/fee333ef5561e2eede5242b3affd98d37b173343/lib/traverse.js#L11-L13
28,712
nteract/kernelspecs
lib/traverse.js
getKernelResources
function getKernelResources(kernelInfo) { return promisify(fs.readdir, [kernelInfo.resourceDir]).then(files => { const kernelJSONIndex = files.indexOf('kernel.json'); if (kernelJSONIndex === -1) { throw new Error('kernel.json not found'); } return promisify(fs.readFile, [path.join(kernelInfo.resourceDir, 'kernel.json')]).then(data => ({ name: kernelInfo.name, files: files.map(x => path.join(kernelInfo.resourceDir, x)), resources_dir: kernelInfo.resourceDir, // eslint-disable-line camelcase spec: JSON.parse(data), })); }); }
javascript
function getKernelResources(kernelInfo) { return promisify(fs.readdir, [kernelInfo.resourceDir]).then(files => { const kernelJSONIndex = files.indexOf('kernel.json'); if (kernelJSONIndex === -1) { throw new Error('kernel.json not found'); } return promisify(fs.readFile, [path.join(kernelInfo.resourceDir, 'kernel.json')]).then(data => ({ name: kernelInfo.name, files: files.map(x => path.join(kernelInfo.resourceDir, x)), resources_dir: kernelInfo.resourceDir, // eslint-disable-line camelcase spec: JSON.parse(data), })); }); }
[ "function", "getKernelResources", "(", "kernelInfo", ")", "{", "return", "promisify", "(", "fs", ".", "readdir", ",", "[", "kernelInfo", ".", "resourceDir", "]", ")", ".", "then", "(", "files", "=>", "{", "const", "kernelJSONIndex", "=", "files", ".", "ind...
Get a kernel resources object @param {Object} kernelInfo description of a kernel @param {string} kernelInfo.name name of the kernel @param {string} kernelInfo.resourceDir kernel's resources directory @return {Promise<Object>} Promise for a kernelResources object
[ "Get", "a", "kernel", "resources", "object" ]
fee333ef5561e2eede5242b3affd98d37b173343
https://github.com/nteract/kernelspecs/blob/fee333ef5561e2eede5242b3affd98d37b173343/lib/traverse.js#L22-L36
28,713
nteract/kernelspecs
lib/traverse.js
getKernelInfos
function getKernelInfos(directory) { return promisify(fs.readdir, [directory]).then(files => files.map(fileName => ({ name: fileName, resourceDir: path.join(directory, fileName), })) ); }
javascript
function getKernelInfos(directory) { return promisify(fs.readdir, [directory]).then(files => files.map(fileName => ({ name: fileName, resourceDir: path.join(directory, fileName), })) ); }
[ "function", "getKernelInfos", "(", "directory", ")", "{", "return", "promisify", "(", "fs", ".", "readdir", ",", "[", "directory", "]", ")", ".", "then", "(", "files", "=>", "files", ".", "map", "(", "fileName", "=>", "(", "{", "name", ":", "fileName",...
Gets a list of kernelInfo objects for a given directory of kernels @param {string} directory path to a directory full of kernels @return {Promise<Object[]>} Promise for an array of kernelInfo objects
[ "Gets", "a", "list", "of", "kernelInfo", "objects", "for", "a", "given", "directory", "of", "kernels" ]
fee333ef5561e2eede5242b3affd98d37b173343
https://github.com/nteract/kernelspecs/blob/fee333ef5561e2eede5242b3affd98d37b173343/lib/traverse.js#L43-L50
28,714
nteract/kernelspecs
lib/traverse.js
find
function find(kernelName) { return jp.dataDirs({ withSysPrefix: true }).then(dirs => { const kernelInfos = dirs.map(dir => ({ name: kernelName, resourceDir: path.join(dir, 'kernels', kernelName), })) return extractKernelResources(kernelInfos); }).then(kernelResource => kernelResource[kernelName]) }
javascript
function find(kernelName) { return jp.dataDirs({ withSysPrefix: true }).then(dirs => { const kernelInfos = dirs.map(dir => ({ name: kernelName, resourceDir: path.join(dir, 'kernels', kernelName), })) return extractKernelResources(kernelInfos); }).then(kernelResource => kernelResource[kernelName]) }
[ "function", "find", "(", "kernelName", ")", "{", "return", "jp", ".", "dataDirs", "(", "{", "withSysPrefix", ":", "true", "}", ")", ".", "then", "(", "dirs", "=>", "{", "const", "kernelInfos", "=", "dirs", ".", "map", "(", "dir", "=>", "(", "{", "n...
find a kernel by name @param {string} kernelName the kernel to locate @return {Object} kernelResource object
[ "find", "a", "kernel", "by", "name" ]
fee333ef5561e2eede5242b3affd98d37b173343
https://github.com/nteract/kernelspecs/blob/fee333ef5561e2eede5242b3affd98d37b173343/lib/traverse.js#L57-L67
28,715
nteract/kernelspecs
lib/traverse.js
findAll
function findAll() { return jp.dataDirs({ withSysPrefix: true }).then(dirs => { return Promise.all(dirs // get kernel infos for each directory and ignore errors .map(dir => getKernelInfos(path.join(dir, 'kernels')).catch(() => {})) ).then(extractKernelResources) }); }
javascript
function findAll() { return jp.dataDirs({ withSysPrefix: true }).then(dirs => { return Promise.all(dirs // get kernel infos for each directory and ignore errors .map(dir => getKernelInfos(path.join(dir, 'kernels')).catch(() => {})) ).then(extractKernelResources) }); }
[ "function", "findAll", "(", ")", "{", "return", "jp", ".", "dataDirs", "(", "{", "withSysPrefix", ":", "true", "}", ")", ".", "then", "(", "dirs", "=>", "{", "return", "Promise", ".", "all", "(", "dirs", "// get kernel infos for each directory and ignore error...
Get an array of kernelResources objects for the host environment This matches the Jupyter notebook API for kernelspecs exactly @return {Promise<Object<string,kernelResource>} Promise for an array of kernelResources objects
[ "Get", "an", "array", "of", "kernelResources", "objects", "for", "the", "host", "environment", "This", "matches", "the", "Jupyter", "notebook", "API", "for", "kernelspecs", "exactly" ]
fee333ef5561e2eede5242b3affd98d37b173343
https://github.com/nteract/kernelspecs/blob/fee333ef5561e2eede5242b3affd98d37b173343/lib/traverse.js#L90-L97
28,716
iopipe/iopipe-js-trace
src/shimmerHttp.js
extendedCallback
function extendedCallback(res) { timeline.mark(`end:${id}`); // add full response data moduleData[id].response = getResDataObject(res); // flatten object for easy transformation/filtering later moduleData[id] = flatten(moduleData[id], { maxDepth: 5 }); moduleData[id] = filterData(config, moduleData[id]); // if filter function returns falsey value, drop all data completely if (typeof moduleData[id] !== 'object') { timeline.data = timeline.data.filter( d => !new RegExp(id).test(d.name) ); delete moduleData[id]; } if (typeof originalCallback === 'function') { return originalCallback.apply(this, [res]); } return true; }
javascript
function extendedCallback(res) { timeline.mark(`end:${id}`); // add full response data moduleData[id].response = getResDataObject(res); // flatten object for easy transformation/filtering later moduleData[id] = flatten(moduleData[id], { maxDepth: 5 }); moduleData[id] = filterData(config, moduleData[id]); // if filter function returns falsey value, drop all data completely if (typeof moduleData[id] !== 'object') { timeline.data = timeline.data.filter( d => !new RegExp(id).test(d.name) ); delete moduleData[id]; } if (typeof originalCallback === 'function') { return originalCallback.apply(this, [res]); } return true; }
[ "function", "extendedCallback", "(", "res", ")", "{", "timeline", ".", "mark", "(", "`", "${", "id", "}", "`", ")", ";", "// add full response data", "moduleData", "[", "id", "]", ".", "response", "=", "getResDataObject", "(", "res", ")", ";", "// flatten ...
the func to execute at the end of the http call
[ "the", "func", "to", "execute", "at", "the", "end", "of", "the", "http", "call" ]
20783f04fcfce6f374f7e5699101ae138499adb9
https://github.com/iopipe/iopipe-js-trace/blob/20783f04fcfce6f374f7e5699101ae138499adb9/src/shimmerHttp.js#L156-L176
28,717
kayahr/console-shim
console-shim.js
function(func, scope, args) { var fixedArgs = Array.prototype.slice.call(arguments, 2); return function() { var args = fixedArgs.concat(Array.prototype.slice.call(arguments, 0)); (/** @type {Function} */ func).apply(scope, args); }; }
javascript
function(func, scope, args) { var fixedArgs = Array.prototype.slice.call(arguments, 2); return function() { var args = fixedArgs.concat(Array.prototype.slice.call(arguments, 0)); (/** @type {Function} */ func).apply(scope, args); }; }
[ "function", "(", "func", ",", "scope", ",", "args", ")", "{", "var", "fixedArgs", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "2", ")", ";", "return", "function", "(", ")", "{", "var", "args", "=", "fixedArgs", ...
Returns a function which calls the specified function in the specified scope. @param {Function} func The function to call. @param {Object} scope The scope to call the function in. @param {...*} args Additional arguments to pass to the bound function. @returns {function(...[*]): undefined} The bound function.
[ "Returns", "a", "function", "which", "calls", "the", "specified", "function", "in", "the", "specified", "scope", "." ]
2c18ef22194222ad0e21cd48dad073c086f9253d
https://github.com/kayahr/console-shim/blob/2c18ef22194222ad0e21cd48dad073c086f9253d/console-shim.js#L26-L34
28,718
kayahr/console-shim
console-shim.js
function(args) { var i, max, match, log; // Convert argument list to real array args = Array.prototype.slice.call(arguments, 0); // First argument is the log method to call log = args.shift(); max = args.length; if (max > 1 && window["__consoleShimTest__"] !== false) { // When first parameter is not a string then add a format string to // the argument list so we are able to modify it in the next stop if (typeof(args[0]) != "string") { args.unshift("%o"); max += 1; } // For each additional parameter which has no placeholder in the // format string we add another placeholder separated with a // space character. match = args[0].match(/%[a-z]/g); for (i = match ? match.length + 1 : 1; i < max; i += 1) { args[0] += " %o"; } } Function.apply.call(log, console, args); }
javascript
function(args) { var i, max, match, log; // Convert argument list to real array args = Array.prototype.slice.call(arguments, 0); // First argument is the log method to call log = args.shift(); max = args.length; if (max > 1 && window["__consoleShimTest__"] !== false) { // When first parameter is not a string then add a format string to // the argument list so we are able to modify it in the next stop if (typeof(args[0]) != "string") { args.unshift("%o"); max += 1; } // For each additional parameter which has no placeholder in the // format string we add another placeholder separated with a // space character. match = args[0].match(/%[a-z]/g); for (i = match ? match.length + 1 : 1; i < max; i += 1) { args[0] += " %o"; } } Function.apply.call(log, console, args); }
[ "function", "(", "args", ")", "{", "var", "i", ",", "max", ",", "match", ",", "log", ";", "// Convert argument list to real array", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ";", "// First argument ...
Wraps the call to a real IE logging method. Modifies the arguments so parameters which are not represented by a placeholder are properly printed with a space character as separator. @param {...*} args The function arguments. First argument is the log function to call, the other arguments are the log arguments.
[ "Wraps", "the", "call", "to", "a", "real", "IE", "logging", "method", ".", "Modifies", "the", "arguments", "so", "parameters", "which", "are", "not", "represented", "by", "a", "placeholder", "are", "properly", "printed", "with", "a", "space", "character", "a...
2c18ef22194222ad0e21cd48dad073c086f9253d
https://github.com/kayahr/console-shim/blob/2c18ef22194222ad0e21cd48dad073c086f9253d/console-shim.js#L82-L113
28,719
stldo/url-slug
src/index.js
parseOptions
function parseOptions(options) { let separator let transformer if (2 === options.length) { [separator, transformer] = options if (defaultTransformers[transformer]) { transformer = defaultTransformers[transformer] /* Don't validate */ validate({ separator }) } else { validate({ separator, transformer }) } } else if (1 === options.length) { const option = options[0] if (false === option || 'function' === typeof option) { transformer = option /* Don't validate */ } else if (defaultTransformers[option]) { transformer = defaultTransformers[option] /* Don't validate */ } else { separator = option validate({ separator }) } } return { separator, transformer } }
javascript
function parseOptions(options) { let separator let transformer if (2 === options.length) { [separator, transformer] = options if (defaultTransformers[transformer]) { transformer = defaultTransformers[transformer] /* Don't validate */ validate({ separator }) } else { validate({ separator, transformer }) } } else if (1 === options.length) { const option = options[0] if (false === option || 'function' === typeof option) { transformer = option /* Don't validate */ } else if (defaultTransformers[option]) { transformer = defaultTransformers[option] /* Don't validate */ } else { separator = option validate({ separator }) } } return { separator, transformer } }
[ "function", "parseOptions", "(", "options", ")", "{", "let", "separator", "let", "transformer", "if", "(", "2", "===", "options", ".", "length", ")", "{", "[", "separator", ",", "transformer", "]", "=", "options", "if", "(", "defaultTransformers", "[", "tr...
Check and return validated options
[ "Check", "and", "return", "validated", "options" ]
4e124d7c5d4ffeef25c3eb4df1bb659771095056
https://github.com/stldo/url-slug/blob/4e124d7c5d4ffeef25c3eb4df1bb659771095056/src/index.js#L34-L59
28,720
uber-workflow/probot-app-release-notes
generate-changelog.js
getWeight
function getWeight(labels, labelWeight) { const places = labels.map(label => labelWeight.indexOf(label.name)); let binary = ''; for (let i = 0; i < labelWeight.length; i++) { binary += places.includes(i) ? '1' : '0'; } return parseInt(binary, 2); }
javascript
function getWeight(labels, labelWeight) { const places = labels.map(label => labelWeight.indexOf(label.name)); let binary = ''; for (let i = 0; i < labelWeight.length; i++) { binary += places.includes(i) ? '1' : '0'; } return parseInt(binary, 2); }
[ "function", "getWeight", "(", "labels", ",", "labelWeight", ")", "{", "const", "places", "=", "labels", ".", "map", "(", "label", "=>", "labelWeight", ".", "indexOf", "(", "label", ".", "name", ")", ")", ";", "let", "binary", "=", "''", ";", "for", "...
Calculates the weight of a given array of labels
[ "Calculates", "the", "weight", "of", "a", "given", "array", "of", "labels" ]
a3321d07ad091516dce5d3c973fd963d67bcc364
https://github.com/uber-workflow/probot-app-release-notes/blob/a3321d07ad091516dce5d3c973fd963d67bcc364/generate-changelog.js#L58-L65
28,721
uber-workflow/probot-app-release-notes
index.js
getReleaseInfo
async function getReleaseInfo(context, childTags) { const tagShas = []; const releasesBySha = await fetchAllReleases(context, release => { if (childTags.has(release.tag_name)) { // put in reverse order // later releases come first, // but we want to iterate beginning oldest releases first tagShas.unshift(release.target_commitish); // tagSha.push(release.target_commitish); } }); return {releasesBySha, tagShas}; }
javascript
async function getReleaseInfo(context, childTags) { const tagShas = []; const releasesBySha = await fetchAllReleases(context, release => { if (childTags.has(release.tag_name)) { // put in reverse order // later releases come first, // but we want to iterate beginning oldest releases first tagShas.unshift(release.target_commitish); // tagSha.push(release.target_commitish); } }); return {releasesBySha, tagShas}; }
[ "async", "function", "getReleaseInfo", "(", "context", ",", "childTags", ")", "{", "const", "tagShas", "=", "[", "]", ";", "const", "releasesBySha", "=", "await", "fetchAllReleases", "(", "context", ",", "release", "=>", "{", "if", "(", "childTags", ".", "...
fetches all releases also finds releases corresponding to provided tags
[ "fetches", "all", "releases", "also", "finds", "releases", "corresponding", "to", "provided", "tags" ]
a3321d07ad091516dce5d3c973fd963d67bcc364
https://github.com/uber-workflow/probot-app-release-notes/blob/a3321d07ad091516dce5d3c973fd963d67bcc364/index.js#L79-L93
28,722
litixsoft/lx-valid
lx-valid.js
getType
function getType(value) { // inspired by http://techblog.badoo.com/blog/2013/11/01/type-checking-in-javascript/ // handle null in old IE if (value === null) { return 'null'; } // handle DOM elements if (value && (value.nodeType === 1 || value.nodeType === 9)) { return 'element'; } var s = Object.prototype.toString.call(value); var type = s.match(/\[object (.*?)\]/)[1].toLowerCase(); // handle NaN and Infinity if (type === 'number') { if (isNaN(value)) { return 'nan'; } if (!isFinite(value)) { return 'infinity'; } } return type; }
javascript
function getType(value) { // inspired by http://techblog.badoo.com/blog/2013/11/01/type-checking-in-javascript/ // handle null in old IE if (value === null) { return 'null'; } // handle DOM elements if (value && (value.nodeType === 1 || value.nodeType === 9)) { return 'element'; } var s = Object.prototype.toString.call(value); var type = s.match(/\[object (.*?)\]/)[1].toLowerCase(); // handle NaN and Infinity if (type === 'number') { if (isNaN(value)) { return 'nan'; } if (!isFinite(value)) { return 'infinity'; } } return type; }
[ "function", "getType", "(", "value", ")", "{", "// inspired by http://techblog.badoo.com/blog/2013/11/01/type-checking-in-javascript/", "// handle null in old IE", "if", "(", "value", "===", "null", ")", "{", "return", "'null'", ";", "}", "// handle DOM elements", "if", "("...
Gets the type of the value in lower case. @param {*} value The value to test. @returns {string}
[ "Gets", "the", "type", "of", "the", "value", "in", "lower", "case", "." ]
ae879336d2fdea69afa86dc6d1332587fda7bc18
https://github.com/litixsoft/lx-valid/blob/ae879336d2fdea69afa86dc6d1332587fda7bc18/lx-valid.js#L18-L45
28,723
litixsoft/lx-valid
lx-valid.js
extendFormatExtensions
function extendFormatExtensions (extensionName, extensionValue) { if (typeof extensionName !== 'string' || !(extensionValue instanceof RegExp)) { throw new Error('extensionName or extensionValue undefined or not correct type'); } if (revalidator.validate.formats.hasOwnProperty(extensionName) || revalidator.validate.formats.hasOwnProperty(extensionName)) { var msg = 'extensionName: ' + extensionName + ' already exists in formatExtensions.'; throw new Error(msg); } revalidator.validate.formatExtensions[extensionName] = extensionValue; }
javascript
function extendFormatExtensions (extensionName, extensionValue) { if (typeof extensionName !== 'string' || !(extensionValue instanceof RegExp)) { throw new Error('extensionName or extensionValue undefined or not correct type'); } if (revalidator.validate.formats.hasOwnProperty(extensionName) || revalidator.validate.formats.hasOwnProperty(extensionName)) { var msg = 'extensionName: ' + extensionName + ' already exists in formatExtensions.'; throw new Error(msg); } revalidator.validate.formatExtensions[extensionName] = extensionValue; }
[ "function", "extendFormatExtensions", "(", "extensionName", ",", "extensionValue", ")", "{", "if", "(", "typeof", "extensionName", "!==", "'string'", "||", "!", "(", "extensionValue", "instanceof", "RegExp", ")", ")", "{", "throw", "new", "Error", "(", "'extensi...
Extend revalidator format extensions @param extensionName @param extensionValue
[ "Extend", "revalidator", "format", "extensions" ]
ae879336d2fdea69afa86dc6d1332587fda7bc18
https://github.com/litixsoft/lx-valid/blob/ae879336d2fdea69afa86dc6d1332587fda7bc18/lx-valid.js#L819-L831
28,724
litixsoft/lx-valid
lx-valid.js
getError
function getError (type, expected, actual) { return { attribute: type, expected: expected, actual: actual, message: getMsg(type, expected) }; }
javascript
function getError (type, expected, actual) { return { attribute: type, expected: expected, actual: actual, message: getMsg(type, expected) }; }
[ "function", "getError", "(", "type", ",", "expected", ",", "actual", ")", "{", "return", "{", "attribute", ":", "type", ",", "expected", ":", "expected", ",", "actual", ":", "actual", ",", "message", ":", "getMsg", "(", "type", ",", "expected", ")", "}...
Get an error object @param type @param expected @param actual @return {Object}
[ "Get", "an", "error", "object" ]
ae879336d2fdea69afa86dc6d1332587fda7bc18
https://github.com/litixsoft/lx-valid/blob/ae879336d2fdea69afa86dc6d1332587fda7bc18/lx-valid.js#L850-L857
28,725
litixsoft/lx-valid
lx-valid.js
getResult
function getResult (err) { var res = { valid: true, errors: [] }; if (err !== null) { res.valid = false; res.errors.push(err); } return res; }
javascript
function getResult (err) { var res = { valid: true, errors: [] }; if (err !== null) { res.valid = false; res.errors.push(err); } return res; }
[ "function", "getResult", "(", "err", ")", "{", "var", "res", "=", "{", "valid", ":", "true", ",", "errors", ":", "[", "]", "}", ";", "if", "(", "err", "!==", "null", ")", "{", "res", ".", "valid", "=", "false", ";", "res", ".", "errors", ".", ...
Get an validation result @param err @return {object}
[ "Get", "an", "validation", "result" ]
ae879336d2fdea69afa86dc6d1332587fda7bc18
https://github.com/litixsoft/lx-valid/blob/ae879336d2fdea69afa86dc6d1332587fda7bc18/lx-valid.js#L864-L876
28,726
litixsoft/lx-valid
lx-valid.js
uniqueArrayHelper
function uniqueArrayHelper (val) { var h = {}; for (var i = 0, l = val.length; i < l; i++) { var key = JSON.stringify(val[i]); if (h[key]) { return false; } h[key] = true; } return true; }
javascript
function uniqueArrayHelper (val) { var h = {}; for (var i = 0, l = val.length; i < l; i++) { var key = JSON.stringify(val[i]); if (h[key]) { return false; } h[key] = true; } return true; }
[ "function", "uniqueArrayHelper", "(", "val", ")", "{", "var", "h", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "val", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "var", "key", "=", "JSON", ".", "str...
Check if array is unique @param val @return {Boolean}
[ "Check", "if", "array", "is", "unique" ]
ae879336d2fdea69afa86dc6d1332587fda7bc18
https://github.com/litixsoft/lx-valid/blob/ae879336d2fdea69afa86dc6d1332587fda7bc18/lx-valid.js#L883-L895
28,727
litixsoft/lx-valid
lx-valid.js
getValidationFunction
function getValidationFunction (validationOptions) { validationOptions = validationOptions || {}; return function (doc, schema, options) { doc = doc || {}; options = options || {}; options.isUpdate = options.isUpdate || false; // check is update if (options.isUpdate) { var i, keys = Object.keys(schema.properties), length = keys.length; for (i = 0; i < length; i++) { if (!doc.hasOwnProperty(keys[i])) { // set property required to false schema.properties[keys[i]].required = false; // remove property from required array if (Array.isArray(schema.required) && schema.required.indexOf(keys[i]) > -1) { schema.required.splice(schema.required.indexOf(keys[i]), 1); } } } } // add default validation options to options object for (var key in validationOptions) { // only add options, do not override if (validationOptions.hasOwnProperty(key) && !options.hasOwnProperty(key)) { options[key] = validationOptions[key]; } } // json schema validate return exports.validate(doc, schema, options); }; }
javascript
function getValidationFunction (validationOptions) { validationOptions = validationOptions || {}; return function (doc, schema, options) { doc = doc || {}; options = options || {}; options.isUpdate = options.isUpdate || false; // check is update if (options.isUpdate) { var i, keys = Object.keys(schema.properties), length = keys.length; for (i = 0; i < length; i++) { if (!doc.hasOwnProperty(keys[i])) { // set property required to false schema.properties[keys[i]].required = false; // remove property from required array if (Array.isArray(schema.required) && schema.required.indexOf(keys[i]) > -1) { schema.required.splice(schema.required.indexOf(keys[i]), 1); } } } } // add default validation options to options object for (var key in validationOptions) { // only add options, do not override if (validationOptions.hasOwnProperty(key) && !options.hasOwnProperty(key)) { options[key] = validationOptions[key]; } } // json schema validate return exports.validate(doc, schema, options); }; }
[ "function", "getValidationFunction", "(", "validationOptions", ")", "{", "validationOptions", "=", "validationOptions", "||", "{", "}", ";", "return", "function", "(", "doc", ",", "schema", ",", "options", ")", "{", "doc", "=", "doc", "||", "{", "}", ";", ...
Gets the validate function and encapsulates some param checks @param {object=} validationOptions The validation options for revalidator. @return {function(doc, schema, options)}
[ "Gets", "the", "validate", "function", "and", "encapsulates", "some", "param", "checks" ]
ae879336d2fdea69afa86dc6d1332587fda7bc18
https://github.com/litixsoft/lx-valid/blob/ae879336d2fdea69afa86dc6d1332587fda7bc18/lx-valid.js#L1244-L1282
28,728
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
componentExists
function componentExists(componentPath) { const existsInExtensions = fs.existsSync(path.resolve(EXTENSIONS_PATH, componentPath)); const existsInWidgets = fs.existsSync(path.resolve(themes.getPath(), 'widgets', componentPath)); return !(!existsInExtensions && !existsInWidgets); }
javascript
function componentExists(componentPath) { const existsInExtensions = fs.existsSync(path.resolve(EXTENSIONS_PATH, componentPath)); const existsInWidgets = fs.existsSync(path.resolve(themes.getPath(), 'widgets', componentPath)); return !(!existsInExtensions && !existsInWidgets); }
[ "function", "componentExists", "(", "componentPath", ")", "{", "const", "existsInExtensions", "=", "fs", ".", "existsSync", "(", "path", ".", "resolve", "(", "EXTENSIONS_PATH", ",", "componentPath", ")", ")", ";", "const", "existsInWidgets", "=", "fs", ".", "e...
Checks if the component exists. @param {string} componentPath The component path. @return {boolean}
[ "Checks", "if", "the", "component", "exists", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L37-L42
28,729
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
readConfig
function readConfig(options) { return new Promise((resolve, reject) => { const { type, config, importsStart = null, importsEnd = null, exportsStart = 'export default {', exportsEnd = '};', isArray = false, } = options; if (!config || !isPlainObject(config)) { return reject(new TypeError(t('SUPPLIED_CONFIG_IS_NOT_AN_OBJECT', { typeofConfig: typeof config, }))); } const imports = importsStart ? [importsStart] : []; // Holds the import strings. const exports = [exportsStart]; // Holds the export strings. // eslint-disable-next-line global-require, import/no-dynamic-require const themePackage = require(`${themes.getPath()}/package.json`); if ( (type === TYPE_PORTALS || type === TYPE_WIDGETS) && has(themePackage.dependencies, 'react-loadable') ) { imports.push('import Loadable from \'react-loadable\';'); imports.push('import Loading from \'@shopgate/pwa-common/components/Loading\';'); imports.push(''); } try { Object.keys(config).forEach((id) => { const component = config[id]; const componentPath = isDev ? component.path.replace('/dist/', '/src/') : component.path; if (!componentExists(componentPath)) { return; } const variableName = getVariableName(id); const isPortalsOrWidgets = ( (type === TYPE_PORTALS && component.target !== 'app.routes') || type === TYPE_WIDGETS ); if (isPortalsOrWidgets && has(themePackage.dependencies, 'react-loadable')) { imports.push(`const ${variableName} = Loadable({\n loader: () => import('${componentPath}'),\n loading: Loading,\n});\n`); } else { imports.push(`import ${variableName} from '${componentPath}';`); } if (isArray) { exports.push(` ${variableName},`); return; } exports.push(` '${id}': ${variableName},`); }); } catch (e) { return reject(e); } if (importsEnd) { imports.push(importsEnd); } exports.push(exportsEnd); return resolve({ imports, exports, }); }); }
javascript
function readConfig(options) { return new Promise((resolve, reject) => { const { type, config, importsStart = null, importsEnd = null, exportsStart = 'export default {', exportsEnd = '};', isArray = false, } = options; if (!config || !isPlainObject(config)) { return reject(new TypeError(t('SUPPLIED_CONFIG_IS_NOT_AN_OBJECT', { typeofConfig: typeof config, }))); } const imports = importsStart ? [importsStart] : []; // Holds the import strings. const exports = [exportsStart]; // Holds the export strings. // eslint-disable-next-line global-require, import/no-dynamic-require const themePackage = require(`${themes.getPath()}/package.json`); if ( (type === TYPE_PORTALS || type === TYPE_WIDGETS) && has(themePackage.dependencies, 'react-loadable') ) { imports.push('import Loadable from \'react-loadable\';'); imports.push('import Loading from \'@shopgate/pwa-common/components/Loading\';'); imports.push(''); } try { Object.keys(config).forEach((id) => { const component = config[id]; const componentPath = isDev ? component.path.replace('/dist/', '/src/') : component.path; if (!componentExists(componentPath)) { return; } const variableName = getVariableName(id); const isPortalsOrWidgets = ( (type === TYPE_PORTALS && component.target !== 'app.routes') || type === TYPE_WIDGETS ); if (isPortalsOrWidgets && has(themePackage.dependencies, 'react-loadable')) { imports.push(`const ${variableName} = Loadable({\n loader: () => import('${componentPath}'),\n loading: Loading,\n});\n`); } else { imports.push(`import ${variableName} from '${componentPath}';`); } if (isArray) { exports.push(` ${variableName},`); return; } exports.push(` '${id}': ${variableName},`); }); } catch (e) { return reject(e); } if (importsEnd) { imports.push(importsEnd); } exports.push(exportsEnd); return resolve({ imports, exports, }); }); }
[ "function", "readConfig", "(", "options", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "{", "type", ",", "config", ",", "importsStart", "=", "null", ",", "importsEnd", "=", "null", ",", "exportsStart"...
Reads the components config and creates import and export variables. @param {Object} options The read config options. @return {Promise}
[ "Reads", "the", "components", "config", "and", "creates", "import", "and", "export", "variables", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L58-L135
28,730
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
getIndexLogTranslations
function getIndexLogTranslations(type = TYPE_WIDGETS) { const params = { type: t(`TYPE_${type}`) }; return { logStart: ` ${t('INDEXING_TYPE', params)}`, logEnd: ` ${t('INDEXED_TYPE', params)}`, logNotFound: ` ${t('NO_EXTENSIONS_FOUND_FOR_TYPE', params)}`, }; }
javascript
function getIndexLogTranslations(type = TYPE_WIDGETS) { const params = { type: t(`TYPE_${type}`) }; return { logStart: ` ${t('INDEXING_TYPE', params)}`, logEnd: ` ${t('INDEXED_TYPE', params)}`, logNotFound: ` ${t('NO_EXTENSIONS_FOUND_FOR_TYPE', params)}`, }; }
[ "function", "getIndexLogTranslations", "(", "type", "=", "TYPE_WIDGETS", ")", "{", "const", "params", "=", "{", "type", ":", "t", "(", "`", "${", "type", "}", "`", ")", "}", ";", "return", "{", "logStart", ":", "`", "${", "t", "(", "'INDEXING_TYPE'", ...
Creates translations for the extension indexing log. @param {string} type The indexed type. @returns {Object}
[ "Creates", "translations", "for", "the", "extension", "indexing", "log", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L142-L150
28,731
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
validateExtensions
function validateExtensions(input) { return new Promise((resolve, reject) => { try { const extensionPath = getExtensionsPath(); if (!fs.existsSync(extensionPath)) { fs.mkdirSync(extensionPath); } if (!input.imports.length) { return resolve(null); } return resolve(input); } catch (e) { return reject(new Error(t('EXTENSION_COULD_NOT_BE_VALIDATED'))); } }); }
javascript
function validateExtensions(input) { return new Promise((resolve, reject) => { try { const extensionPath = getExtensionsPath(); if (!fs.existsSync(extensionPath)) { fs.mkdirSync(extensionPath); } if (!input.imports.length) { return resolve(null); } return resolve(input); } catch (e) { return reject(new Error(t('EXTENSION_COULD_NOT_BE_VALIDATED'))); } }); }
[ "function", "validateExtensions", "(", "input", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "try", "{", "const", "extensionPath", "=", "getExtensionsPath", "(", ")", ";", "if", "(", "!", "fs", ".", "existsSyn...
Validates the extensions input. @param {Object} input The input. @return {Promise}
[ "Validates", "the", "extensions", "input", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L157-L175
28,732
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
createStrings
function createStrings(input) { return new Promise((resolve, reject) => { try { if (!input) { return resolve(null); } const importsString = input.imports.length ? `${input.imports.join('\n')}\n\n` : ''; const exportsString = input.exports.length ? `${input.exports.join('\n')}\n` : ''; const indexString = `${importsString}${exportsString}`.replace('\n\n\n', '\n\n'); return resolve(indexString.length ? indexString : null); } catch (e) { return reject(new Error(t('STRINGS_COULD_NOT_BE_CREATED'))); } }); }
javascript
function createStrings(input) { return new Promise((resolve, reject) => { try { if (!input) { return resolve(null); } const importsString = input.imports.length ? `${input.imports.join('\n')}\n\n` : ''; const exportsString = input.exports.length ? `${input.exports.join('\n')}\n` : ''; const indexString = `${importsString}${exportsString}`.replace('\n\n\n', '\n\n'); return resolve(indexString.length ? indexString : null); } catch (e) { return reject(new Error(t('STRINGS_COULD_NOT_BE_CREATED'))); } }); }
[ "function", "createStrings", "(", "input", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "try", "{", "if", "(", "!", "input", ")", "{", "return", "resolve", "(", "null", ")", ";", "}", "const", "importsStri...
Creates the string that is written into the appropriate file. @param {Object} input The input object. @return {string}
[ "Creates", "the", "string", "that", "is", "written", "into", "the", "appropriate", "file", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L182-L198
28,733
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
writeExtensionFile
function writeExtensionFile(options) { return new Promise((resolve, reject) => { try { const { file, input, defaultContent, logNotFound, logEnd, } = options; const filePath = path.resolve(getExtensionsPath(), file); if (!input) { logger.warn(logNotFound); fs.writeFileSync(filePath, defaultContent, { flag: 'w+' }); return resolve(); } fs.writeFileSync(filePath, input, { flag: 'w+' }); logger.log(logEnd); return resolve(); } catch (e) { return reject(e); } }); }
javascript
function writeExtensionFile(options) { return new Promise((resolve, reject) => { try { const { file, input, defaultContent, logNotFound, logEnd, } = options; const filePath = path.resolve(getExtensionsPath(), file); if (!input) { logger.warn(logNotFound); fs.writeFileSync(filePath, defaultContent, { flag: 'w+' }); return resolve(); } fs.writeFileSync(filePath, input, { flag: 'w+' }); logger.log(logEnd); return resolve(); } catch (e) { return reject(e); } }); }
[ "function", "writeExtensionFile", "(", "options", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "try", "{", "const", "{", "file", ",", "input", ",", "defaultContent", ",", "logNotFound", ",", "logEnd", ",", "}"...
Writes to extension file. @param {Object} options The action object. @return {Promise}
[ "Writes", "to", "extension", "file", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L205-L231
28,734
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
index
function index(options) { const { file, config, logStart, logNotFound, logEnd, defaultContent = defaultFileContent, } = options; logger.log(logStart); return readConfig(config) .then(input => validateExtensions(input)) .then(input => createStrings(input)) .then(input => writeExtensionFile({ input, file, defaultContent, logNotFound, logEnd, })); }
javascript
function index(options) { const { file, config, logStart, logNotFound, logEnd, defaultContent = defaultFileContent, } = options; logger.log(logStart); return readConfig(config) .then(input => validateExtensions(input)) .then(input => createStrings(input)) .then(input => writeExtensionFile({ input, file, defaultContent, logNotFound, logEnd, })); }
[ "function", "index", "(", "options", ")", "{", "const", "{", "file", ",", "config", ",", "logStart", ",", "logNotFound", ",", "logEnd", ",", "defaultContent", "=", "defaultFileContent", ",", "}", "=", "options", ";", "logger", ".", "log", "(", "logStart", ...
Creates an index. @param {Object} options The indexing options, @return {Promise}
[ "Creates", "an", "index", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L238-L260
28,735
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
indexWidgets
function indexWidgets() { const { widgets = {} } = getComponentsSettings(); return index({ file: 'widgets.js', config: { type: TYPE_WIDGETS, config: widgets, }, ...getIndexLogTranslations(TYPE_WIDGETS), }); }
javascript
function indexWidgets() { const { widgets = {} } = getComponentsSettings(); return index({ file: 'widgets.js', config: { type: TYPE_WIDGETS, config: widgets, }, ...getIndexLogTranslations(TYPE_WIDGETS), }); }
[ "function", "indexWidgets", "(", ")", "{", "const", "{", "widgets", "=", "{", "}", "}", "=", "getComponentsSettings", "(", ")", ";", "return", "index", "(", "{", "file", ":", "'widgets.js'", ",", "config", ":", "{", "type", ":", "TYPE_WIDGETS", ",", "c...
Indexes the widgets. @return {Promise}
[ "Indexes", "the", "widgets", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L266-L277
28,736
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
indexTracking
function indexTracking() { const { tracking = {} } = getComponentsSettings(); return index({ file: 'tracking.js', config: { type: TYPE_TRACKERS, config: tracking, }, ...getIndexLogTranslations(TYPE_TRACKERS), }); }
javascript
function indexTracking() { const { tracking = {} } = getComponentsSettings(); return index({ file: 'tracking.js', config: { type: TYPE_TRACKERS, config: tracking, }, ...getIndexLogTranslations(TYPE_TRACKERS), }); }
[ "function", "indexTracking", "(", ")", "{", "const", "{", "tracking", "=", "{", "}", "}", "=", "getComponentsSettings", "(", ")", ";", "return", "index", "(", "{", "file", ":", "'tracking.js'", ",", "config", ":", "{", "type", ":", "TYPE_TRACKERS", ",", ...
Indexes the tracking. @return {Promise}
[ "Indexes", "the", "tracking", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L283-L294
28,737
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
indexPortals
function indexPortals() { const { portals = {} } = getComponentsSettings(); return index({ file: 'portals.js', config: { type: TYPE_PORTALS, config: portals, importsStart: 'import portalCollection from \'@shopgate/pwa-common/helpers/portals/portalCollection\';', exportsStart: 'portalCollection.registerPortals({', exportsEnd: '});', }, ...getIndexLogTranslations(TYPE_PORTALS), }); }
javascript
function indexPortals() { const { portals = {} } = getComponentsSettings(); return index({ file: 'portals.js', config: { type: TYPE_PORTALS, config: portals, importsStart: 'import portalCollection from \'@shopgate/pwa-common/helpers/portals/portalCollection\';', exportsStart: 'portalCollection.registerPortals({', exportsEnd: '});', }, ...getIndexLogTranslations(TYPE_PORTALS), }); }
[ "function", "indexPortals", "(", ")", "{", "const", "{", "portals", "=", "{", "}", "}", "=", "getComponentsSettings", "(", ")", ";", "return", "index", "(", "{", "file", ":", "'portals.js'", ",", "config", ":", "{", "type", ":", "TYPE_PORTALS", ",", "c...
Indexes the portals. @return {Promise}
[ "Indexes", "the", "portals", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L300-L314
28,738
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
indexReducers
function indexReducers() { const { reducers = {} } = getComponentsSettings(); return index({ file: 'reducers.js', config: { type: TYPE_REDUCERS, config: reducers, }, defaultContent: 'export default null;\n', ...getIndexLogTranslations(TYPE_REDUCERS), }); }
javascript
function indexReducers() { const { reducers = {} } = getComponentsSettings(); return index({ file: 'reducers.js', config: { type: TYPE_REDUCERS, config: reducers, }, defaultContent: 'export default null;\n', ...getIndexLogTranslations(TYPE_REDUCERS), }); }
[ "function", "indexReducers", "(", ")", "{", "const", "{", "reducers", "=", "{", "}", "}", "=", "getComponentsSettings", "(", ")", ";", "return", "index", "(", "{", "file", ":", "'reducers.js'", ",", "config", ":", "{", "type", ":", "TYPE_REDUCERS", ",", ...
Indexes the reducers from extensions. @return {Promise}
[ "Indexes", "the", "reducers", "from", "extensions", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L320-L332
28,739
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
indexSubscribers
function indexSubscribers() { const { subscribers = {} } = getComponentsSettings(); return index({ file: 'subscribers.js', config: { type: TYPE_SUBSCRIBERS, config: subscribers, exportsStart: 'export default [', exportsEnd: '];', isArray: true, }, defaultContent: 'export default [];\n', ...getIndexLogTranslations(TYPE_SUBSCRIBERS), }); }
javascript
function indexSubscribers() { const { subscribers = {} } = getComponentsSettings(); return index({ file: 'subscribers.js', config: { type: TYPE_SUBSCRIBERS, config: subscribers, exportsStart: 'export default [', exportsEnd: '];', isArray: true, }, defaultContent: 'export default [];\n', ...getIndexLogTranslations(TYPE_SUBSCRIBERS), }); }
[ "function", "indexSubscribers", "(", ")", "{", "const", "{", "subscribers", "=", "{", "}", "}", "=", "getComponentsSettings", "(", ")", ";", "return", "index", "(", "{", "file", ":", "'subscribers.js'", ",", "config", ":", "{", "type", ":", "TYPE_SUBSCRIBE...
Indexes the RxJS subscriptions from extensions. @return {Promise}
[ "Indexes", "the", "RxJS", "subscriptions", "from", "extensions", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L338-L353
28,740
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
indexTranslations
function indexTranslations() { const { translations = {} } = getComponentsSettings(); return index({ file: 'translations.js', config: { type: TYPE_TRANSLATIONS, config: translations, }, defaultContent: 'export default null;\n', ...getIndexLogTranslations(TYPE_TRANSLATIONS), }); }
javascript
function indexTranslations() { const { translations = {} } = getComponentsSettings(); return index({ file: 'translations.js', config: { type: TYPE_TRANSLATIONS, config: translations, }, defaultContent: 'export default null;\n', ...getIndexLogTranslations(TYPE_TRANSLATIONS), }); }
[ "function", "indexTranslations", "(", ")", "{", "const", "{", "translations", "=", "{", "}", "}", "=", "getComponentsSettings", "(", ")", ";", "return", "index", "(", "{", "file", ":", "'translations.js'", ",", "config", ":", "{", "type", ":", "TYPE_TRANSL...
Indexes the translations from extensions. @return {Promise}
[ "Indexes", "the", "translations", "from", "extensions", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L359-L371
28,741
cheminfo-js/openchemlib-extended
src/db/search.js
search
function search(query, options = {}) { const { format = 'idCode', mode = 'substructure', flattenResult = true, keepMolecule = false, limit = Number.MAX_SAFE_INTEGER } = options; if (typeof query === 'string') { const getMoleculeCreators = require('./moleculeCreators'); const moleculeCreators = getMoleculeCreators(this.OCL.Molecule); query = moleculeCreators.get(format.toLowerCase())(query); } else if (!(query instanceof this.OCL.Molecule)) { throw new TypeError('toSearch must be a Molecule or string'); } let result; switch (mode.toLowerCase()) { case 'exact': result = exactSearch(this.moleculeDB.db, query, limit); break; case 'substructure': result = subStructureSearch(this.moleculeDB, query, limit); break; case 'similarity': result = similaritySearch(this.moleculeDB, this.OCL, query, limit); break; default: throw new Error(`unknown search mode: ${options.mode}`); } return processResult(result, { flattenResult, keepMolecule, limit }); }
javascript
function search(query, options = {}) { const { format = 'idCode', mode = 'substructure', flattenResult = true, keepMolecule = false, limit = Number.MAX_SAFE_INTEGER } = options; if (typeof query === 'string') { const getMoleculeCreators = require('./moleculeCreators'); const moleculeCreators = getMoleculeCreators(this.OCL.Molecule); query = moleculeCreators.get(format.toLowerCase())(query); } else if (!(query instanceof this.OCL.Molecule)) { throw new TypeError('toSearch must be a Molecule or string'); } let result; switch (mode.toLowerCase()) { case 'exact': result = exactSearch(this.moleculeDB.db, query, limit); break; case 'substructure': result = subStructureSearch(this.moleculeDB, query, limit); break; case 'similarity': result = similaritySearch(this.moleculeDB, this.OCL, query, limit); break; default: throw new Error(`unknown search mode: ${options.mode}`); } return processResult(result, { flattenResult, keepMolecule, limit }); }
[ "function", "search", "(", "query", ",", "options", "=", "{", "}", ")", "{", "const", "{", "format", "=", "'idCode'", ",", "mode", "=", "'substructure'", ",", "flattenResult", "=", "true", ",", "keepMolecule", "=", "false", ",", "limit", "=", "Number", ...
Search in a MoleculeDB Inside the database all the same molecules are group together @memberof DB @instance @param {string|OCL.Molecule} [query] smiles, molfile, oclCode or instance of Molecule to look for @param {object} [options={}] @param {string} [options.format='idCode'] - query is in the format 'smiles', 'oclid' or 'molfile' @param {string} [options.mode='substructure'] - search by 'substructure', 'exact' or 'similarity' @param {boolean} [options.flattenResult=true] - The database group the data for the same product. This allows to flatten the result @param {boolean} [options.keepMolecule=false] - keep the OCL.Molecule object in the result @param {number} [options.limit=Number.MAX_SAFE_INTEGER] - maximal number of result @return {Array} array of object of the type {(molecule), idCode, data, properties}
[ "Search", "in", "a", "MoleculeDB", "Inside", "the", "database", "all", "the", "same", "molecules", "are", "group", "together" ]
45775a97f0ca952ba2aae4e6fe1c35846be4e1f8
https://github.com/cheminfo-js/openchemlib-extended/blob/45775a97f0ca952ba2aae4e6fe1c35846be4e1f8/src/db/search.js#L17-L49
28,742
ipfs-shipyard/ipfs-redux-bundle
src/js-ipfs-api/index.js
maybeApi
async function maybeApi ({ apiAddress, apiOpts, ipfsConnectionTest, IpfsApi }) { try { const ipfs = new IpfsApi(apiAddress, apiOpts) await ipfsConnectionTest(ipfs) return { ipfs, provider, apiAddress } } catch (error) { console.log('Failed to connect to ipfs-api', apiAddress) } }
javascript
async function maybeApi ({ apiAddress, apiOpts, ipfsConnectionTest, IpfsApi }) { try { const ipfs = new IpfsApi(apiAddress, apiOpts) await ipfsConnectionTest(ipfs) return { ipfs, provider, apiAddress } } catch (error) { console.log('Failed to connect to ipfs-api', apiAddress) } }
[ "async", "function", "maybeApi", "(", "{", "apiAddress", ",", "apiOpts", ",", "ipfsConnectionTest", ",", "IpfsApi", "}", ")", "{", "try", "{", "const", "ipfs", "=", "new", "IpfsApi", "(", "apiAddress", ",", "apiOpts", ")", "await", "ipfsConnectionTest", "(",...
Helper to construct and test an api client. Returns an js-ipfs-api instance or null
[ "Helper", "to", "construct", "and", "test", "an", "api", "client", ".", "Returns", "an", "js", "-", "ipfs", "-", "api", "instance", "or", "null" ]
c53610427538d321d6f7614b402fabd5d469e6de
https://github.com/ipfs-shipyard/ipfs-redux-bundle/blob/c53610427538d321d6f7614b402fabd5d469e6de/src/js-ipfs-api/index.js#L43-L51
28,743
cheminfo-js/openchemlib-extended
src/extend/diastereotopic/migrated/DiastereotopicAtomID.js
addMissingChirality
function addMissingChirality(molecule, esrType = Molecule.cESRTypeAnd) { for (let iAtom = 0; iAtom < molecule.getAllAtoms(); iAtom++) { let tempMolecule = molecule.getCompactCopy(); changeAtomForStereo(tempMolecule, iAtom); // After copy, helpers must be recalculated tempMolecule.ensureHelperArrays(Molecule.cHelperParities); // We need to have >0 and not >1 because there could be unspecified chirality in racemate for (let i = 0; i < tempMolecule.getAtoms(); i++) { // changed from from handling below; TLS 9.Nov.2015 if ( tempMolecule.isAtomStereoCenter(i) && tempMolecule.getStereoBond(i) === -1 ) { let stereoBond = tempMolecule.getAtomPreferredStereoBond(i); if (stereoBond !== -1) { molecule.setBondType(stereoBond, Molecule.cBondTypeUp); if (molecule.getBondAtom(1, stereoBond) === i) { let connAtom = molecule.getBondAtom(0, stereoBond); molecule.setBondAtom(0, stereoBond, i); molecule.setBondAtom(1, stereoBond, connAtom); } // To me it seems that we have to add all stereo centers into AND group 0. TLS 9.Nov.2015 molecule.setAtomESR(i, esrType, 0); } } } } }
javascript
function addMissingChirality(molecule, esrType = Molecule.cESRTypeAnd) { for (let iAtom = 0; iAtom < molecule.getAllAtoms(); iAtom++) { let tempMolecule = molecule.getCompactCopy(); changeAtomForStereo(tempMolecule, iAtom); // After copy, helpers must be recalculated tempMolecule.ensureHelperArrays(Molecule.cHelperParities); // We need to have >0 and not >1 because there could be unspecified chirality in racemate for (let i = 0; i < tempMolecule.getAtoms(); i++) { // changed from from handling below; TLS 9.Nov.2015 if ( tempMolecule.isAtomStereoCenter(i) && tempMolecule.getStereoBond(i) === -1 ) { let stereoBond = tempMolecule.getAtomPreferredStereoBond(i); if (stereoBond !== -1) { molecule.setBondType(stereoBond, Molecule.cBondTypeUp); if (molecule.getBondAtom(1, stereoBond) === i) { let connAtom = molecule.getBondAtom(0, stereoBond); molecule.setBondAtom(0, stereoBond, i); molecule.setBondAtom(1, stereoBond, connAtom); } // To me it seems that we have to add all stereo centers into AND group 0. TLS 9.Nov.2015 molecule.setAtomESR(i, esrType, 0); } } } } }
[ "function", "addMissingChirality", "(", "molecule", ",", "esrType", "=", "Molecule", ".", "cESRTypeAnd", ")", "{", "for", "(", "let", "iAtom", "=", "0", ";", "iAtom", "<", "molecule", ".", "getAllAtoms", "(", ")", ";", "iAtom", "++", ")", "{", "let", "...
The problem is that sometimes we need to add chiral bond that was not planned because it is the same group This is the case for example for the valine where the 2 C of the methyl groups are diastereotopic @param molecule
[ "The", "problem", "is", "that", "sometimes", "we", "need", "to", "add", "chiral", "bond", "that", "was", "not", "planned", "because", "it", "is", "the", "same", "group", "This", "is", "the", "case", "for", "example", "for", "the", "valine", "where", "the...
45775a97f0ca952ba2aae4e6fe1c35846be4e1f8
https://github.com/cheminfo-js/openchemlib-extended/blob/45775a97f0ca952ba2aae4e6fe1c35846be4e1f8/src/extend/diastereotopic/migrated/DiastereotopicAtomID.js#L33-L60
28,744
cheminfo-js/openchemlib-extended
src/extend/diastereotopic/migrated/DiastereotopicAtomID.js
markDiastereotopicAtoms
function markDiastereotopicAtoms(molecule) { // changed from markDiastereo(); TLS 9.Nov.2015 let ids = getAtomIDs(molecule); let analyzed = {}; let group = 0; for (let id of ids) { console.log(`${id} - ${group}`); if (!analyzed.contains(id)) { analyzed[id] = true; for (let iAtom = 0; iAtom < ids.length; iAtom++) { if (id.equals(ids[iAtom])) { molecule.setAtomCustomLabel(iAtom, group); } } group++; } } }
javascript
function markDiastereotopicAtoms(molecule) { // changed from markDiastereo(); TLS 9.Nov.2015 let ids = getAtomIDs(molecule); let analyzed = {}; let group = 0; for (let id of ids) { console.log(`${id} - ${group}`); if (!analyzed.contains(id)) { analyzed[id] = true; for (let iAtom = 0; iAtom < ids.length; iAtom++) { if (id.equals(ids[iAtom])) { molecule.setAtomCustomLabel(iAtom, group); } } group++; } } }
[ "function", "markDiastereotopicAtoms", "(", "molecule", ")", "{", "// changed from markDiastereo(); TLS 9.Nov.2015", "let", "ids", "=", "getAtomIDs", "(", "molecule", ")", ";", "let", "analyzed", "=", "{", "}", ";", "let", "group", "=", "0", ";", "for", "(", "...
In order to debug we could number the group of diastereotopic atoms @param molecule
[ "In", "order", "to", "debug", "we", "could", "number", "the", "group", "of", "diastereotopic", "atoms" ]
45775a97f0ca952ba2aae4e6fe1c35846be4e1f8
https://github.com/cheminfo-js/openchemlib-extended/blob/45775a97f0ca952ba2aae4e6fe1c35846be4e1f8/src/extend/diastereotopic/migrated/DiastereotopicAtomID.js#L83-L100
28,745
shopgate/cloud-sdk-webpack
lib/helpers/getThemeConfig.js
getContrastColor
function getContrastColor(bgColor, colors) { // We set a rather high cutoff to prefer light text if possible. const cutoff = 0.74; // Calculate the perceived luminosity (relative brightness) of the color. const perceivedLuminosity = Color(bgColor).luminosity(); return perceivedLuminosity >= cutoff ? colors.dark : colors.light; }
javascript
function getContrastColor(bgColor, colors) { // We set a rather high cutoff to prefer light text if possible. const cutoff = 0.74; // Calculate the perceived luminosity (relative brightness) of the color. const perceivedLuminosity = Color(bgColor).luminosity(); return perceivedLuminosity >= cutoff ? colors.dark : colors.light; }
[ "function", "getContrastColor", "(", "bgColor", ",", "colors", ")", "{", "// We set a rather high cutoff to prefer light text if possible.", "const", "cutoff", "=", "0.74", ";", "// Calculate the perceived luminosity (relative brightness) of the color.", "const", "perceivedLuminosity...
Calculates a contrast color for a given background color. The color will either be black or white depending on the perceived luminosity of the background color. @param {string} bgColor The background color. @param {Object} colors The full color variables. @returns {string} The contrast color.
[ "Calculates", "a", "contrast", "color", "for", "a", "given", "background", "color", ".", "The", "color", "will", "either", "be", "black", "or", "white", "depending", "on", "the", "perceived", "luminosity", "of", "the", "background", "color", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/getThemeConfig.js#L14-L22
28,746
shopgate/cloud-sdk-webpack
lib/helpers/getThemeConfig.js
getFocusColor
function getFocusColor(colors) { if (Color(colors.primary).luminosity() >= 0.8) { return colors.accent; } return colors.primary; }
javascript
function getFocusColor(colors) { if (Color(colors.primary).luminosity() >= 0.8) { return colors.accent; } return colors.primary; }
[ "function", "getFocusColor", "(", "colors", ")", "{", "if", "(", "Color", "(", "colors", ".", "primary", ")", ".", "luminosity", "(", ")", ">=", "0.8", ")", "{", "return", "colors", ".", "accent", ";", "}", "return", "colors", ".", "primary", ";", "}...
Gets the default focus color. This usually is the themes primary color. However, if this color is too bright, the result of ths method will fall back to the accent color. @param {Object} colors The full color variables. @return {string} The color.
[ "Gets", "the", "default", "focus", "color", ".", "This", "usually", "is", "the", "themes", "primary", "color", ".", "However", "if", "this", "color", "is", "too", "bright", "the", "result", "of", "ths", "method", "will", "fall", "back", "to", "the", "acc...
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/getThemeConfig.js#L31-L37
28,747
shopgate/cloud-sdk-webpack
lib/helpers/getThemeConfig.js
applyContrastColors
function applyContrastColors(config) { const { colors } = config; return { ...config, colors: { ...colors, primaryContrast: getContrastColor(colors.primary, colors), accentContrast: getContrastColor(colors.accent, colors), focus: getFocusColor(colors), }, }; }
javascript
function applyContrastColors(config) { const { colors } = config; return { ...config, colors: { ...colors, primaryContrast: getContrastColor(colors.primary, colors), accentContrast: getContrastColor(colors.accent, colors), focus: getFocusColor(colors), }, }; }
[ "function", "applyContrastColors", "(", "config", ")", "{", "const", "{", "colors", "}", "=", "config", ";", "return", "{", "...", "config", ",", "colors", ":", "{", "...", "colors", ",", "primaryContrast", ":", "getContrastColor", "(", "colors", ".", "pri...
Applies the contrast and focus colors to the colors configuration. @param {Object} config The complete theme configuration. @return {Object}
[ "Applies", "the", "contrast", "and", "focus", "colors", "to", "the", "colors", "configuration", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/getThemeConfig.js#L44-L56
28,748
shopgate/cloud-sdk-webpack
lib/helpers/getThemeConfig.js
applyCustomColors
function applyCustomColors(config) { const { colors } = getAppSettings(); if (!config.hasOwnProperty('colors')) { return { ...config, colors, }; } return { ...config, colors: { ...config.colors, ...colors, }, }; }
javascript
function applyCustomColors(config) { const { colors } = getAppSettings(); if (!config.hasOwnProperty('colors')) { return { ...config, colors, }; } return { ...config, colors: { ...config.colors, ...colors, }, }; }
[ "function", "applyCustomColors", "(", "config", ")", "{", "const", "{", "colors", "}", "=", "getAppSettings", "(", ")", ";", "if", "(", "!", "config", ".", "hasOwnProperty", "(", "'colors'", ")", ")", "{", "return", "{", "...", "config", ",", "colors", ...
Applies custom colors @param {[type]} config [description] @return {[type]} [description]
[ "Applies", "custom", "colors" ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/getThemeConfig.js#L63-L80
28,749
Open-Xchange-Frontend/appserver
lib/middleware/appsload.js
module
function module(filename) { return function () { if (verbose.local) console.log(filename); response.write(fs.readFileSync(filename) + '\n/*:oxsep:*/\n'); }; }
javascript
function module(filename) { return function () { if (verbose.local) console.log(filename); response.write(fs.readFileSync(filename) + '\n/*:oxsep:*/\n'); }; }
[ "function", "module", "(", "filename", ")", "{", "return", "function", "(", ")", "{", "if", "(", "verbose", ".", "local", ")", "console", ".", "log", "(", "filename", ")", ";", "response", ".", "write", "(", "fs", ".", "readFileSync", "(", "filename", ...
normal RequireJS module
[ "normal", "RequireJS", "module" ]
bcf65b97842c44351464fafaafd20ae45dcd78fa
https://github.com/Open-Xchange-Frontend/appserver/blob/bcf65b97842c44351464fafaafd20ae45dcd78fa/lib/middleware/appsload.js#L89-L94
28,750
developmentseed/collecticons-processor
src/core/bundle.js
collecticonsBundle
async function collecticonsBundle (params) { const { dirPath, destFile } = params; await validateDirPath(dirPath); const resultFiles = await collecticonsCompile({ dirPath, styleFormats: ['css'], styleDest: './styles', fontDest: './', fontTypes: ['woff', 'woff2'], previewDest: './', noFileOutput: true }); if (resultFiles === null) return; // Create zip. let zip = new JSZip(); // Add generated files. resultFiles.forEach(file => { zip.file(file.path, file.contents); }); // Add the icons. const dir = await fs.readdir(dirPath); const svgs = await Promise.all(dir.map(async file => { return file.endsWith('.svg') ? ( { path: `icons/${file}`, contents: await fs.readFile(path.resolve(dirPath, file)) } ) : null; })); svgs.forEach(file => { zip.file(file.path, file.contents); }); await fs.ensureDir(path.dirname(destFile)); await fs.writeFile(destFile, zip.generate({ base64: false, compression: 'DEFLATE' }), 'binary'); }
javascript
async function collecticonsBundle (params) { const { dirPath, destFile } = params; await validateDirPath(dirPath); const resultFiles = await collecticonsCompile({ dirPath, styleFormats: ['css'], styleDest: './styles', fontDest: './', fontTypes: ['woff', 'woff2'], previewDest: './', noFileOutput: true }); if (resultFiles === null) return; // Create zip. let zip = new JSZip(); // Add generated files. resultFiles.forEach(file => { zip.file(file.path, file.contents); }); // Add the icons. const dir = await fs.readdir(dirPath); const svgs = await Promise.all(dir.map(async file => { return file.endsWith('.svg') ? ( { path: `icons/${file}`, contents: await fs.readFile(path.resolve(dirPath, file)) } ) : null; })); svgs.forEach(file => { zip.file(file.path, file.contents); }); await fs.ensureDir(path.dirname(destFile)); await fs.writeFile(destFile, zip.generate({ base64: false, compression: 'DEFLATE' }), 'binary'); }
[ "async", "function", "collecticonsBundle", "(", "params", ")", "{", "const", "{", "dirPath", ",", "destFile", "}", "=", "params", ";", "await", "validateDirPath", "(", "dirPath", ")", ";", "const", "resultFiles", "=", "await", "collecticonsCompile", "(", "{", ...
Compiles the collecticons font and zips it. Contains all the used icons, the fonts, stylesheet and preview. @param {object} params @param {string} params.dirPath Source path for the svg icons. @param {string} params.destFile Destination of the zip file.
[ "Compiles", "the", "collecticons", "font", "and", "zips", "it", ".", "Contains", "all", "the", "used", "icons", "the", "fonts", "stylesheet", "and", "preview", "." ]
1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9
https://github.com/developmentseed/collecticons-processor/blob/1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9/src/core/bundle.js#L18-L65
28,751
canjs/can-map-define
can-map-define.js
function(errors) { //!steal-remove-start if (process.env.NODE_ENV !== 'production') { clearTimeout(asyncTimer); } //!steal-remove-end var stub = error && error.call(self, errors); // if 'validations' is on the page it will trigger // the error itself and we dont want to trigger // the event twice. :) if (stub !== false) { mapEventsMixin.dispatch.call(self, 'error', [ prop, errors ], true); } return false; }
javascript
function(errors) { //!steal-remove-start if (process.env.NODE_ENV !== 'production') { clearTimeout(asyncTimer); } //!steal-remove-end var stub = error && error.call(self, errors); // if 'validations' is on the page it will trigger // the error itself and we dont want to trigger // the event twice. :) if (stub !== false) { mapEventsMixin.dispatch.call(self, 'error', [ prop, errors ], true); } return false; }
[ "function", "(", "errors", ")", "{", "//!steal-remove-start", "if", "(", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", ")", "{", "clearTimeout", "(", "asyncTimer", ")", ";", "}", "//!steal-remove-end", "var", "stub", "=", "error", "&&", "err...
check if there's a setter
[ "check", "if", "there", "s", "a", "setter" ]
1327861b2baa1f4dc8b3bc4ef6995ec30bc7e49d
https://github.com/canjs/can-map-define/blob/1327861b2baa1f4dc8b3bc4ef6995ec30bc7e49d/can-map-define.js#L174-L189
28,752
canjs/can-map-define
can-map-define.js
function(map, attr, val) { var serializer = attr === "*" ? false : getPropDefineBehavior("serialize", attr, map.define); if (serializer === undefined) { return oldSingleSerialize.call(map, attr, val); } else if (serializer !== false) { return typeof serializer === "function" ? serializer.call(map, val, attr) : oldSingleSerialize.call(map, attr, val); } }
javascript
function(map, attr, val) { var serializer = attr === "*" ? false : getPropDefineBehavior("serialize", attr, map.define); if (serializer === undefined) { return oldSingleSerialize.call(map, attr, val); } else if (serializer !== false) { return typeof serializer === "function" ? serializer.call(map, val, attr) : oldSingleSerialize.call(map, attr, val); } }
[ "function", "(", "map", ",", "attr", ",", "val", ")", "{", "var", "serializer", "=", "attr", "===", "\"*\"", "?", "false", ":", "getPropDefineBehavior", "(", "\"serialize\"", ",", "attr", ",", "map", ".", "define", ")", ";", "if", "(", "serializer", "=...
If the map has a define serializer for the given attr, run it.
[ "If", "the", "map", "has", "a", "define", "serializer", "for", "the", "given", "attr", "run", "it", "." ]
1327861b2baa1f4dc8b3bc4ef6995ec30bc7e49d
https://github.com/canjs/can-map-define/blob/1327861b2baa1f4dc8b3bc4ef6995ec30bc7e49d/can-map-define.js#L380-L387
28,753
developmentseed/collecticons-processor
src/font-generator.js
generateFonts
async function generateFonts (options = {}) { if (!options.fontName) throw new TypeError('Missing fontName argument'); if (!options.icons || !Array.isArray(options.icons) || !options.icons.length) { throw new TypeError('Invalid or empty icons argument'); } // Store created tasks to match dependencies. let genTasks = {}; /** * First, creates tasks for dependent font types. * Then creates task for specified font type and chains it to dependencies promises. * If some task already exists, it reuses it. */ const makeGenTask = type => { // If already defined return. if (genTasks[type]) return genTasks[type]; // Get generator function. const gen = generators[type]; // Create dependent functions const depsTasks = (gen.deps || []).map(depType => makeGenTask(depType)); const task = Promise.all(depsTasks).then(results => gen.fn(options, results) ); genTasks[type] = task; return task; }; // Make a gen task for each type. const types = ['svg', 'ttf', 'woff', 'woff2']; const tasks = types.map(type => { return makeGenTask(type); }); const results = await Promise.all(tasks); return zipObject(types, results); }
javascript
async function generateFonts (options = {}) { if (!options.fontName) throw new TypeError('Missing fontName argument'); if (!options.icons || !Array.isArray(options.icons) || !options.icons.length) { throw new TypeError('Invalid or empty icons argument'); } // Store created tasks to match dependencies. let genTasks = {}; /** * First, creates tasks for dependent font types. * Then creates task for specified font type and chains it to dependencies promises. * If some task already exists, it reuses it. */ const makeGenTask = type => { // If already defined return. if (genTasks[type]) return genTasks[type]; // Get generator function. const gen = generators[type]; // Create dependent functions const depsTasks = (gen.deps || []).map(depType => makeGenTask(depType)); const task = Promise.all(depsTasks).then(results => gen.fn(options, results) ); genTasks[type] = task; return task; }; // Make a gen task for each type. const types = ['svg', 'ttf', 'woff', 'woff2']; const tasks = types.map(type => { return makeGenTask(type); }); const results = await Promise.all(tasks); return zipObject(types, results); }
[ "async", "function", "generateFonts", "(", "options", "=", "{", "}", ")", "{", "if", "(", "!", "options", ".", "fontName", ")", "throw", "new", "TypeError", "(", "'Missing fontName argument'", ")", ";", "if", "(", "!", "options", ".", "icons", "||", "!",...
Generated the svg, ttf, woff, and woff2 fonts. @param {object} options Configuration @param {string} options.fontName Name of the font. @param {array} options.icons List of icons. Each should have a `name` and `codepoint` properties.boolean @param {object} options.formatOptions Configuration for each of the font generation plugins @returns {object} Object keyed with the font type and respective content. All fonts are returned in Buffer format.
[ "Generated", "the", "svg", "ttf", "woff", "and", "woff2", "fonts", "." ]
1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9
https://github.com/developmentseed/collecticons-processor/blob/1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9/src/font-generator.js#L97-L132
28,754
developmentseed/collecticons-processor
src/renderers/index.js
renderSass
async function renderSass (opts = {}) { const tpl = await fs.readFile(path.resolve(__dirname, 'sass.ejs'), 'utf8'); return ejs.render(tpl, opts); }
javascript
async function renderSass (opts = {}) { const tpl = await fs.readFile(path.resolve(__dirname, 'sass.ejs'), 'utf8'); return ejs.render(tpl, opts); }
[ "async", "function", "renderSass", "(", "opts", "=", "{", "}", ")", "{", "const", "tpl", "=", "await", "fs", ".", "readFile", "(", "path", ".", "resolve", "(", "__dirname", ",", "'sass.ejs'", ")", ",", "'utf8'", ")", ";", "return", "ejs", ".", "rende...
Renders the sass file using the `sass.ejs` template. @param {object} opts Option for the generation. @param {string} opts.fontName Name of the font to render. @param {string} opts.embed Whether or not to embed the fonts defined in the `fonts` option. @param {object} opts.fonts Fonts to use. Only `woff` and `woff2` are supported. The object key should be the font type and each should have a contents in Buffer format and a path to the font File. The path is not needed if embed is set to `true`. Example: woff: { contents: Buffer path: String } @param {string} opts.authorName Name of the font author. Will go into the style header comment. @param {string} opts.authorUrl Url of the font author. Will go into the style header comment. @param {string} opts.className Class name / sass placeholder to use. @param {array} opts.icons List of icons. Each should have a `name` and `codepoint` properties.boolean @param {boolean} opts.sassPlaceholder Whether or not to use sass placeholders. @param {boolean} opts.cssClass Whether or not to use css classes. @param {string} opts.dateFormatted Generation date. Will go into the style header comment. @returns {string} Rendered data
[ "Renders", "the", "sass", "file", "using", "the", "sass", ".", "ejs", "template", "." ]
1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9
https://github.com/developmentseed/collecticons-processor/blob/1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9/src/renderers/index.js#L67-L70
28,755
developmentseed/collecticons-processor
src/renderers/index.js
renderCatalog
async function renderCatalog (opts = {}) { if (!opts.fontName) throw new ReferenceError('fontName is undefined'); if (!opts.className) throw new ReferenceError('className is undefined'); if (!opts.icons || !opts.icons.length) throw new ReferenceError('icons is undefined or empty'); const fonts = opts.fonts ? Object.keys(opts.fonts).reduce((acc, name) => { return { ...acc, [name]: opts.fonts[name].contents.toString('base64') }; }, {}) : undefined; return JSON.stringify({ name: opts.fontName, className: opts.className, fonts, icons: opts.icons.map(i => ({ icon: `${opts.className}-${i.name}`, charCode: `${i.codepoint.toString(16).toUpperCase()}` })) }); }
javascript
async function renderCatalog (opts = {}) { if (!opts.fontName) throw new ReferenceError('fontName is undefined'); if (!opts.className) throw new ReferenceError('className is undefined'); if (!opts.icons || !opts.icons.length) throw new ReferenceError('icons is undefined or empty'); const fonts = opts.fonts ? Object.keys(opts.fonts).reduce((acc, name) => { return { ...acc, [name]: opts.fonts[name].contents.toString('base64') }; }, {}) : undefined; return JSON.stringify({ name: opts.fontName, className: opts.className, fonts, icons: opts.icons.map(i => ({ icon: `${opts.className}-${i.name}`, charCode: `${i.codepoint.toString(16).toUpperCase()}` })) }); }
[ "async", "function", "renderCatalog", "(", "opts", "=", "{", "}", ")", "{", "if", "(", "!", "opts", ".", "fontName", ")", "throw", "new", "ReferenceError", "(", "'fontName is undefined'", ")", ";", "if", "(", "!", "opts", ".", "className", ")", "throw", ...
Renders the catalog file returning a json string. @param {object} opts Option for the generation. @param {string} opts.fontName Name of the font to render. @param {string} opts.className Class name / sass placeholder to use. @param {object} opts.fonts Fonts to include as base64 strings. Each object key is the font type and its value is the encoded string. @param {array} opts.icons List of icons. Each should have a `name` and `codepoint` properties.boolean @returns {string} Rendered data
[ "Renders", "the", "catalog", "file", "returning", "a", "json", "string", "." ]
1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9
https://github.com/developmentseed/collecticons-processor/blob/1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9/src/renderers/index.js#L103-L126
28,756
developmentseed/collecticons-processor
src/utils.js
Logger
function Logger () { const levels = [ 'fatal', // 1 'error', // 2 'warn', // 3 'info', // 4 'debug' // 5 ]; let verbosity = 3; levels.forEach((level, idx) => { this[level] = (...params) => { if (idx + 1 <= verbosity) console.log(...params); // eslint-disable-line }; }); this.setLevel = (_) => { verbosity = _; }; return this; }
javascript
function Logger () { const levels = [ 'fatal', // 1 'error', // 2 'warn', // 3 'info', // 4 'debug' // 5 ]; let verbosity = 3; levels.forEach((level, idx) => { this[level] = (...params) => { if (idx + 1 <= verbosity) console.log(...params); // eslint-disable-line }; }); this.setLevel = (_) => { verbosity = _; }; return this; }
[ "function", "Logger", "(", ")", "{", "const", "levels", "=", "[", "'fatal'", ",", "// 1", "'error'", ",", "// 2", "'warn'", ",", "// 3", "'info'", ",", "// 4", "'debug'", "// 5", "]", ";", "let", "verbosity", "=", "3", ";", "levels", ".", "forEach", ...
Simple logger with levels. 1 - fatal 2 - error 3 - warn 4 - info 5 - debug Logger level set globally with setLevel(). Logging done using logger.<level>().
[ "Simple", "logger", "with", "levels", ".", "1", "-", "fatal", "2", "-", "error", "3", "-", "warn", "4", "-", "info", "5", "-", "debug" ]
1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9
https://github.com/developmentseed/collecticons-processor/blob/1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9/src/utils.js#L15-L36
28,757
developmentseed/collecticons-processor
src/utils.js
userError
function userError (details = [], code) { const err = new Error('User error'); err.userError = true; err.code = code; err.details = details; return err; }
javascript
function userError (details = [], code) { const err = new Error('User error'); err.userError = true; err.code = code; err.details = details; return err; }
[ "function", "userError", "(", "details", "=", "[", "]", ",", "code", ")", "{", "const", "err", "=", "new", "Error", "(", "'User error'", ")", ";", "err", ".", "userError", "=", "true", ";", "err", ".", "code", "=", "code", ";", "err", ".", "details...
Creates a User Error object. Each error has a details array where each entry is a message line to be printed. The error is supposed to bubble up the chain and print the cli help if the option is enabled. The `userError` property can be used to know if the error is created on purpose rather than thrown by something else. @param {array} details The message lines @returns Error
[ "Creates", "a", "User", "Error", "object", ".", "Each", "error", "has", "a", "details", "array", "where", "each", "entry", "is", "a", "message", "line", "to", "be", "printed", ".", "The", "error", "is", "supposed", "to", "bubble", "up", "the", "chain", ...
1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9
https://github.com/developmentseed/collecticons-processor/blob/1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9/src/utils.js#L51-L57
28,758
developmentseed/collecticons-processor
src/utils.js
time
function time (name) { const t = timers[name]; if (t) { let elapsed = Date.now() - t; if (elapsed < 1000) return `${elapsed}ms`; if (elapsed < 60 * 1000) return `${elapsed / 1000}s`; elapsed /= 1000; const h = Math.floor(elapsed / 3600); const m = Math.floor((elapsed % 3600) / 60); const s = Math.floor((elapsed % 3600) % 60); delete timers[name]; return `${h}h ${m}m ${s}s`; } else { timers[name] = Date.now(); } }
javascript
function time (name) { const t = timers[name]; if (t) { let elapsed = Date.now() - t; if (elapsed < 1000) return `${elapsed}ms`; if (elapsed < 60 * 1000) return `${elapsed / 1000}s`; elapsed /= 1000; const h = Math.floor(elapsed / 3600); const m = Math.floor((elapsed % 3600) / 60); const s = Math.floor((elapsed % 3600) % 60); delete timers[name]; return `${h}h ${m}m ${s}s`; } else { timers[name] = Date.now(); } }
[ "function", "time", "(", "name", ")", "{", "const", "t", "=", "timers", "[", "name", "]", ";", "if", "(", "t", ")", "{", "let", "elapsed", "=", "Date", ".", "now", "(", ")", "-", "t", ";", "if", "(", "elapsed", "<", "1000", ")", "return", "`"...
Like console.time but better. Instead of printing the value returns it. Displays 1h 10m 10s notation for times above 60 seconds. Uses a global timers variable to keep track of timers. On the first call sets the time, on the second returns the value @param {string} name Timer name
[ "Like", "console", ".", "time", "but", "better", ".", "Instead", "of", "printing", "the", "value", "returns", "it", ".", "Displays", "1h", "10m", "10s", "notation", "for", "times", "above", "60", "seconds", ".", "Uses", "a", "global", "timers", "variable",...
1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9
https://github.com/developmentseed/collecticons-processor/blob/1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9/src/utils.js#L69-L87
28,759
developmentseed/collecticons-processor
src/utils.js
validateDirPath
async function validateDirPath (dirPath) { try { const stats = await fs.lstat(dirPath); if (!stats.isDirectory()) { throw userError([ 'Source path must be a directory', '' ]); } } catch (error) { if (error.code === 'ENOENT') { throw userError([ 'No files or directories found at ' + dirPath, '' ]); } throw error; } }
javascript
async function validateDirPath (dirPath) { try { const stats = await fs.lstat(dirPath); if (!stats.isDirectory()) { throw userError([ 'Source path must be a directory', '' ]); } } catch (error) { if (error.code === 'ENOENT') { throw userError([ 'No files or directories found at ' + dirPath, '' ]); } throw error; } }
[ "async", "function", "validateDirPath", "(", "dirPath", ")", "{", "try", "{", "const", "stats", "=", "await", "fs", ".", "lstat", "(", "dirPath", ")", ";", "if", "(", "!", "stats", ".", "isDirectory", "(", ")", ")", "{", "throw", "userError", "(", "[...
Validates that the given path is a directory, throwing user errors in other cases. @param {string} dirPath Path to validate @see userError() @throws Error if validation fails
[ "Validates", "that", "the", "given", "path", "is", "a", "directory", "throwing", "user", "errors", "in", "other", "cases", "." ]
1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9
https://github.com/developmentseed/collecticons-processor/blob/1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9/src/utils.js#L98-L117
28,760
developmentseed/collecticons-processor
src/utils.js
validateDirPathForCLI
async function validateDirPathForCLI (dirPath) { try { await validateDirPath(dirPath); } catch (error) { if (!error.userError) throw error; if (error.details[0].startsWith('Source path must be a directory')) { const args = process.argv.reduce((acc, o, idx) => { // Discard the first 2 arguments. if (idx < 1) return acc; if (o === dirPath) return acc.concat(path.dirname(dirPath)); return acc.concat(o); }, []); throw userError([ 'Source path must be a directory. Try running with the following instead:', '', ` node ${args.join(' ')}`, '' ]); } throw error; } }
javascript
async function validateDirPathForCLI (dirPath) { try { await validateDirPath(dirPath); } catch (error) { if (!error.userError) throw error; if (error.details[0].startsWith('Source path must be a directory')) { const args = process.argv.reduce((acc, o, idx) => { // Discard the first 2 arguments. if (idx < 1) return acc; if (o === dirPath) return acc.concat(path.dirname(dirPath)); return acc.concat(o); }, []); throw userError([ 'Source path must be a directory. Try running with the following instead:', '', ` node ${args.join(' ')}`, '' ]); } throw error; } }
[ "async", "function", "validateDirPathForCLI", "(", "dirPath", ")", "{", "try", "{", "await", "validateDirPath", "(", "dirPath", ")", ";", "}", "catch", "(", "error", ")", "{", "if", "(", "!", "error", ".", "userError", ")", "throw", "error", ";", "if", ...
Same functionality as validateDirPath but with error messages directed at a CLI tool. Validates that the given path is a directory, throwing user errors in other cases. @param {string} dirPath Path to validate @see validateDirPath() @throws Error if validation fails
[ "Same", "functionality", "as", "validateDirPath", "but", "with", "error", "messages", "directed", "at", "a", "CLI", "tool", ".", "Validates", "that", "the", "given", "path", "is", "a", "directory", "throwing", "user", "errors", "in", "other", "cases", "." ]
1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9
https://github.com/developmentseed/collecticons-processor/blob/1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9/src/utils.js#L130-L152
28,761
developmentseed/collecticons-processor
bin/programs.js
compileProgram
async function compileProgram (dirPath, command) { await validateDirPathForCLI(dirPath); const params = pick(command, [ 'fontName', 'sassPlaceholder', 'cssClass', 'fontTypes', 'styleFormats', 'styleDest', 'styleName', 'fontDest', 'authorName', 'authorUrl', 'className', 'previewDest', 'preview', 'catalogDest', 'experimentalFontOnCatalog', 'experimentalDisableStyles' ]); try { return collecticonsCompile({ dirPath, ...params }); } catch (error) { if (!error.userError) throw error; // Capture some errors and convert to their command line alternative. const code = error.code; if (code === 'PLC_CLASS_EXC') { error.details = ['Error: --no-sass-placeholder and --no-css-class are mutually exclusive']; } else if (code === 'FONT_TYPE') { error.details = ['Error: invalid font type value passed to --font-types']; } else if (code === 'CLASS_CSS_FORMAT') { error.details = ['Error: "--no-css-class" and "--style-formats css" are not compatible']; } else if (code === 'STYLE_TYPE') { error.details = ['Error: invalid style format value passed to --style-format']; } throw error; } }
javascript
async function compileProgram (dirPath, command) { await validateDirPathForCLI(dirPath); const params = pick(command, [ 'fontName', 'sassPlaceholder', 'cssClass', 'fontTypes', 'styleFormats', 'styleDest', 'styleName', 'fontDest', 'authorName', 'authorUrl', 'className', 'previewDest', 'preview', 'catalogDest', 'experimentalFontOnCatalog', 'experimentalDisableStyles' ]); try { return collecticonsCompile({ dirPath, ...params }); } catch (error) { if (!error.userError) throw error; // Capture some errors and convert to their command line alternative. const code = error.code; if (code === 'PLC_CLASS_EXC') { error.details = ['Error: --no-sass-placeholder and --no-css-class are mutually exclusive']; } else if (code === 'FONT_TYPE') { error.details = ['Error: invalid font type value passed to --font-types']; } else if (code === 'CLASS_CSS_FORMAT') { error.details = ['Error: "--no-css-class" and "--style-formats css" are not compatible']; } else if (code === 'STYLE_TYPE') { error.details = ['Error: invalid style format value passed to --style-format']; } throw error; } }
[ "async", "function", "compileProgram", "(", "dirPath", ",", "command", ")", "{", "await", "validateDirPathForCLI", "(", "dirPath", ")", ";", "const", "params", "=", "pick", "(", "command", ",", "[", "'fontName'", ",", "'sassPlaceholder'", ",", "'cssClass'", ",...
Collecticons compile wrapped for use in the CLI tool.
[ "Collecticons", "compile", "wrapped", "for", "use", "in", "the", "CLI", "tool", "." ]
1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9
https://github.com/developmentseed/collecticons-processor/blob/1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9/bin/programs.js#L13-L56
28,762
developmentseed/collecticons-processor
bin/programs.js
bundleProgram
async function bundleProgram (dirPath, destFile) { await validateDirPathForCLI(dirPath); return collecticonsBundle({ dirPath, destFile }); }
javascript
async function bundleProgram (dirPath, destFile) { await validateDirPathForCLI(dirPath); return collecticonsBundle({ dirPath, destFile }); }
[ "async", "function", "bundleProgram", "(", "dirPath", ",", "destFile", ")", "{", "await", "validateDirPathForCLI", "(", "dirPath", ")", ";", "return", "collecticonsBundle", "(", "{", "dirPath", ",", "destFile", "}", ")", ";", "}" ]
Collecticons bundle wrapped for use in the CLI tool.
[ "Collecticons", "bundle", "wrapped", "for", "use", "in", "the", "CLI", "tool", "." ]
1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9
https://github.com/developmentseed/collecticons-processor/blob/1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9/bin/programs.js#L61-L67
28,763
RackHD/on-core
lib/common/connection.js
Connection
function Connection (options, clientOptions, label) { this.options = options; this.clientOptions = clientOptions; this.label = label; this.initialConnection = false; this.initialConnectionRetries = 0; this.maxConnectionRetries = 60; Object.defineProperty(this, 'exchanges', { get: function () { if (this.connection) { return this.connection.exchanges; } } }); Object.defineProperty(this, 'connected', { get: function () { return this.connection !== undefined; } }); }
javascript
function Connection (options, clientOptions, label) { this.options = options; this.clientOptions = clientOptions; this.label = label; this.initialConnection = false; this.initialConnectionRetries = 0; this.maxConnectionRetries = 60; Object.defineProperty(this, 'exchanges', { get: function () { if (this.connection) { return this.connection.exchanges; } } }); Object.defineProperty(this, 'connected', { get: function () { return this.connection !== undefined; } }); }
[ "function", "Connection", "(", "options", ",", "clientOptions", ",", "label", ")", "{", "this", ".", "options", "=", "options", ";", "this", ".", "clientOptions", "=", "clientOptions", ";", "this", ".", "label", "=", "label", ";", "this", ".", "initialConn...
Connection provides a wrapper around the AMQP connection logic which presents a simplified interface for using multiple connections in the messenger. @param {Object} options node-amqp createConnection options. @param {type} [clientOptions] node-amqp createConnection client options.
[ "Connection", "provides", "a", "wrapper", "around", "the", "AMQP", "connection", "logic", "which", "presents", "a", "simplified", "interface", "for", "using", "multiple", "connections", "in", "the", "messenger", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/connection.js#L24-L45
28,764
RackHD/on-core
lib/common/json-schema-validator.js
resolveRef
function resolveRef(schemaObj, resolvedValues) { // the array store referenced value var refVal = schemaObj.refVal; // the map store full ref id and index of the referenced value in refVal // example: { 'test#definitions/option' : 1, 'test#definitions/repo' : 2 } var refs = schemaObj.refs; // the map to store schema value with sub reference var subRefs = {}; _.forEach(refs, function (index, refId) { // if reference id already resolved then continue the loop if (refId in resolvedValues) { return true; // continue } var refValue = refVal[index]; // if no further nested reference, add to resolved map if (_.isEmpty(refValue.refs)) { resolvedValues[refId] = refValue; return true; } // add schema value with sub reference to map to resolve later subRefs[refId] = refValue; }); // resolve sub reference recursively _.forEach(subRefs, function (subRef, refId) { resolvedValues[refId] = 1; resolvedValues[refId] = resolveRef(subRef, resolvedValues); }); return schemaObj.schema; }
javascript
function resolveRef(schemaObj, resolvedValues) { // the array store referenced value var refVal = schemaObj.refVal; // the map store full ref id and index of the referenced value in refVal // example: { 'test#definitions/option' : 1, 'test#definitions/repo' : 2 } var refs = schemaObj.refs; // the map to store schema value with sub reference var subRefs = {}; _.forEach(refs, function (index, refId) { // if reference id already resolved then continue the loop if (refId in resolvedValues) { return true; // continue } var refValue = refVal[index]; // if no further nested reference, add to resolved map if (_.isEmpty(refValue.refs)) { resolvedValues[refId] = refValue; return true; } // add schema value with sub reference to map to resolve later subRefs[refId] = refValue; }); // resolve sub reference recursively _.forEach(subRefs, function (subRef, refId) { resolvedValues[refId] = 1; resolvedValues[refId] = resolveRef(subRef, resolvedValues); }); return schemaObj.schema; }
[ "function", "resolveRef", "(", "schemaObj", ",", "resolvedValues", ")", "{", "// the array store referenced value", "var", "refVal", "=", "schemaObj", ".", "refVal", ";", "// the map store full ref id and index of the referenced value in refVal", "// example: { 'test#definitions/op...
resolve reference recursively it search the compiled schema data structure from ajv.getSchema, find out and store referenced value to resolvedValues map
[ "resolve", "reference", "recursively", "it", "search", "the", "compiled", "schema", "data", "structure", "from", "ajv", ".", "getSchema", "find", "out", "and", "store", "referenced", "value", "to", "resolvedValues", "map" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/json-schema-validator.js#L246-L279
28,765
bminer/node-static-asset
lib/static-asset.js
assetFingerprint
function assetFingerprint(label, fingerprint, cacheInfo) { if(arguments.length > 1) { //Add a label var labelInfo = labels[label] = {"fingerprint": fingerprint}; if(cacheInfo) for(var i in cacheInfo) labelInfo[i] = cacheInfo[i]; } else { //Try to get a fingerprint from a registered label var info = labels[label]; if(info) { fingerprints[info.fingerprint] = info; return info.fingerprint; } else { info = {}; //Try to get a fingerprint using the specified cache strategy var fullPath = path.resolve(rootPath + "/" + (label || this.url) ); //Use the "cache strategy" to get a fingerprint //Prefer the use of etag over lastModified when generating fingerprints if(!fs.existsSync(fullPath) ) return label; if(strategy.lastModified) { var mdate = info.lastModified = strategy.lastModified(fullPath); mdate.setMilliseconds(0); } if(strategy.etag) info.etag = strategy.etag(fullPath); if(strategy.expires) info.expires = strategy.expires(fullPath); if(strategy.fileFingerprint) { var fingerprint = strategy.fileFingerprint(label, fullPath); fingerprints[fingerprint] = info; return fingerprint; } else return label; //Do not generate a fingerprint } } }
javascript
function assetFingerprint(label, fingerprint, cacheInfo) { if(arguments.length > 1) { //Add a label var labelInfo = labels[label] = {"fingerprint": fingerprint}; if(cacheInfo) for(var i in cacheInfo) labelInfo[i] = cacheInfo[i]; } else { //Try to get a fingerprint from a registered label var info = labels[label]; if(info) { fingerprints[info.fingerprint] = info; return info.fingerprint; } else { info = {}; //Try to get a fingerprint using the specified cache strategy var fullPath = path.resolve(rootPath + "/" + (label || this.url) ); //Use the "cache strategy" to get a fingerprint //Prefer the use of etag over lastModified when generating fingerprints if(!fs.existsSync(fullPath) ) return label; if(strategy.lastModified) { var mdate = info.lastModified = strategy.lastModified(fullPath); mdate.setMilliseconds(0); } if(strategy.etag) info.etag = strategy.etag(fullPath); if(strategy.expires) info.expires = strategy.expires(fullPath); if(strategy.fileFingerprint) { var fingerprint = strategy.fileFingerprint(label, fullPath); fingerprints[fingerprint] = info; return fingerprint; } else return label; //Do not generate a fingerprint } } }
[ "function", "assetFingerprint", "(", "label", ",", "fingerprint", ",", "cacheInfo", ")", "{", "if", "(", "arguments", ".", "length", ">", "1", ")", "{", "//Add a label", "var", "labelInfo", "=", "labels", "[", "label", "]", "=", "{", "\"fingerprint\"", ":"...
req.assetFingerprint function
[ "req", ".", "assetFingerprint", "function" ]
cd7bbe1fcbc6d5e2e1738c7f4b9b823471222097
https://github.com/bminer/node-static-asset/blob/cd7bbe1fcbc6d5e2e1738c7f4b9b823471222097/lib/static-asset.js#L72-L118
28,766
RackHD/on-core
lib/models/node.js
function() { var self = this; return waterline.catalogs.findOne({"node": self.id}) .then(function(catalog) { return !_.isEmpty(catalog); }); }
javascript
function() { var self = this; return waterline.catalogs.findOne({"node": self.id}) .then(function(catalog) { return !_.isEmpty(catalog); }); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "return", "waterline", ".", "catalogs", ".", "findOne", "(", "{", "\"node\"", ":", "self", ".", "id", "}", ")", ".", "then", "(", "function", "(", "catalog", ")", "{", "return", "!", "_", ...
We only count a node as having been discovered if a node document exists AND it has any catalogs associated with it
[ "We", "only", "count", "a", "node", "as", "having", "been", "discovered", "if", "a", "node", "document", "exists", "AND", "it", "has", "any", "catalogs", "associated", "with", "it" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/models/node.js#L90-L96
28,767
RackHD/on-core
spec/helper.js
function () { var waterline = this.injector.get('Services.Waterline'); return bluebird.all( _.map(waterline, function (collection) { if (typeof collection.destroy === 'function') { return bluebird.fromNode(collection.destroy.bind(collection)).then(function () { if (collection.adapterDictionary.define !== 'mongo') { return bluebird.fromNode( collection.adapter.define.bind(collection.adapter) ); } }); } }) ); }
javascript
function () { var waterline = this.injector.get('Services.Waterline'); return bluebird.all( _.map(waterline, function (collection) { if (typeof collection.destroy === 'function') { return bluebird.fromNode(collection.destroy.bind(collection)).then(function () { if (collection.adapterDictionary.define !== 'mongo') { return bluebird.fromNode( collection.adapter.define.bind(collection.adapter) ); } }); } }) ); }
[ "function", "(", ")", "{", "var", "waterline", "=", "this", ".", "injector", ".", "get", "(", "'Services.Waterline'", ")", ";", "return", "bluebird", ".", "all", "(", "_", ".", "map", "(", "waterline", ",", "function", "(", "collection", ")", "{", "if"...
maps through all collections loaded into Services.Waterline and destroys them to reset testing state. Usage: beforeEach(function() { this.timeout(5000); // gives the system 5 seconds to do the wiping return waterline.start().then(function() { return helper.reset(); }) }) @returns {Promise}
[ "maps", "through", "all", "collections", "loaded", "into", "Services", ".", "Waterline", "and", "destroys", "them", "to", "reset", "testing", "state", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/spec/helper.js#L198-L214
28,768
RackHD/on-core
lib/common/child-process.js
ChildProcess
function ChildProcess (command, args, env, code, maxBuffer) { var self = this; assert.string(command); assert.optionalArrayOfNumber(code); self.command = command; self.file = self._parseCommandPath(self.command); self.args = args; self.environment = env || {}; self.exitCode = code || [0]; self.maxBuffer = maxBuffer || Constants.ChildProcess.MaxBuffer; if (!self.file) { throw new Error('Unable to locate command file (' + self.command +').'); } if (!_.isEmpty(self.args)) { try { assert.arrayOfString(self.args, 'ChildProcess command arguments'); } catch (e) { throw new Error('args must be an array of strings'); } } self.hasBeenKilled = false; self.hasBeenCancelled = false; self.spawnInstance = undefined; }
javascript
function ChildProcess (command, args, env, code, maxBuffer) { var self = this; assert.string(command); assert.optionalArrayOfNumber(code); self.command = command; self.file = self._parseCommandPath(self.command); self.args = args; self.environment = env || {}; self.exitCode = code || [0]; self.maxBuffer = maxBuffer || Constants.ChildProcess.MaxBuffer; if (!self.file) { throw new Error('Unable to locate command file (' + self.command +').'); } if (!_.isEmpty(self.args)) { try { assert.arrayOfString(self.args, 'ChildProcess command arguments'); } catch (e) { throw new Error('args must be an array of strings'); } } self.hasBeenKilled = false; self.hasBeenCancelled = false; self.spawnInstance = undefined; }
[ "function", "ChildProcess", "(", "command", ",", "args", ",", "env", ",", "code", ",", "maxBuffer", ")", "{", "var", "self", "=", "this", ";", "assert", ".", "string", "(", "command", ")", ";", "assert", ".", "optionalArrayOfNumber", "(", "code", ")", ...
ChildProcess provides a promise based mechanism to run shell commands in a fairly secure manner. @constructor
[ "ChildProcess", "provides", "a", "promise", "based", "mechanism", "to", "run", "shell", "commands", "in", "a", "fairly", "secure", "manner", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/child-process.js#L48-L75
28,769
RackHD/on-core
lib/di.js
provideName
function provideName(obj, token){ if(!isString(token)) { throw new Error('Must provide string as name of module'); } di.annotate(obj, new di.Provide(token)); }
javascript
function provideName(obj, token){ if(!isString(token)) { throw new Error('Must provide string as name of module'); } di.annotate(obj, new di.Provide(token)); }
[ "function", "provideName", "(", "obj", ",", "token", ")", "{", "if", "(", "!", "isString", "(", "token", ")", ")", "{", "throw", "new", "Error", "(", "'Must provide string as name of module'", ")", ";", "}", "di", ".", "annotate", "(", "obj", ",", "new",...
Apply provide annotation to object @private @param {*} obj @param {string} token string to apply as provide annotation
[ "Apply", "provide", "annotation", "to", "object" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L251-L256
28,770
RackHD/on-core
lib/di.js
providePromise
function providePromise(obj, providePromiseName) { if(!isString(providePromiseName)) { throw new Error('Must provide string as name of promised module'); } di.annotate(obj, new di.ProvidePromise(providePromiseName)); }
javascript
function providePromise(obj, providePromiseName) { if(!isString(providePromiseName)) { throw new Error('Must provide string as name of promised module'); } di.annotate(obj, new di.ProvidePromise(providePromiseName)); }
[ "function", "providePromise", "(", "obj", ",", "providePromiseName", ")", "{", "if", "(", "!", "isString", "(", "providePromiseName", ")", ")", "{", "throw", "new", "Error", "(", "'Must provide string as name of promised module'", ")", ";", "}", "di", ".", "anno...
Apply provide promise annotation to object @private @param {*} obj @param {string} providePromiseName string to apply as provide promise annotation
[ "Apply", "provide", "promise", "annotation", "to", "object" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L263-L268
28,771
RackHD/on-core
lib/di.js
resolveProvide
function resolveProvide(obj, override) { var provide = override || obj.$provide; if(isString(provide)) { return provideName(obj, provide); } if(isObject(provide)) { if (isString(provide.promise)) { return providePromise(obj, provide.promise); } else if (isString(provide.provide)) { return provideName(obj, provide.provide); } } }
javascript
function resolveProvide(obj, override) { var provide = override || obj.$provide; if(isString(provide)) { return provideName(obj, provide); } if(isObject(provide)) { if (isString(provide.promise)) { return providePromise(obj, provide.promise); } else if (isString(provide.provide)) { return provideName(obj, provide.provide); } } }
[ "function", "resolveProvide", "(", "obj", ",", "override", ")", "{", "var", "provide", "=", "override", "||", "obj", ".", "$provide", ";", "if", "(", "isString", "(", "provide", ")", ")", "{", "return", "provideName", "(", "obj", ",", "provide", ")", "...
resolve the type of promise and the name given the underlying object and any overrides @private @param {*} obj @param {string|object} [override] - specify any of the overides
[ "resolve", "the", "type", "of", "promise", "and", "the", "name", "given", "the", "underlying", "object", "and", "any", "overrides" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L276-L290
28,772
RackHD/on-core
lib/di.js
addInject
function addInject(obj, inject) { if(!exists(inject)) { return; } var injectMe; if (inject === '$injector') { injectMe = new di.Inject(di.Injector); } else if (isObject(inject)) { if(isString(inject.inject)){ injectMe = new di.Inject(inject.inject); } else if(isString(inject.promise)) { injectMe = new di.InjectPromise(inject.promise); } else if(isString(inject.lazy)) { injectMe = new di.InjectLazy(inject.lazy); } } else { injectMe = new di.Inject(inject); } di.annotate(obj, injectMe); }
javascript
function addInject(obj, inject) { if(!exists(inject)) { return; } var injectMe; if (inject === '$injector') { injectMe = new di.Inject(di.Injector); } else if (isObject(inject)) { if(isString(inject.inject)){ injectMe = new di.Inject(inject.inject); } else if(isString(inject.promise)) { injectMe = new di.InjectPromise(inject.promise); } else if(isString(inject.lazy)) { injectMe = new di.InjectLazy(inject.lazy); } } else { injectMe = new di.Inject(inject); } di.annotate(obj, injectMe); }
[ "function", "addInject", "(", "obj", ",", "inject", ")", "{", "if", "(", "!", "exists", "(", "inject", ")", ")", "{", "return", ";", "}", "var", "injectMe", ";", "if", "(", "inject", "===", "'$injector'", ")", "{", "injectMe", "=", "new", "di", "."...
Add Inject Annotation @private @param {*} obj @param {string|object} inject
[ "Add", "Inject", "Annotation" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L298-L320
28,773
RackHD/on-core
lib/di.js
resolveInjects
function resolveInjects(obj, override){ var injects = obj.$inject || override; if (exists(injects)) { if (!Array.isArray(injects)) { injects = [injects]; } injects.forEach(function addInjects(element) { addInject(obj, element); }); } }
javascript
function resolveInjects(obj, override){ var injects = obj.$inject || override; if (exists(injects)) { if (!Array.isArray(injects)) { injects = [injects]; } injects.forEach(function addInjects(element) { addInject(obj, element); }); } }
[ "function", "resolveInjects", "(", "obj", ",", "override", ")", "{", "var", "injects", "=", "obj", ".", "$inject", "||", "override", ";", "if", "(", "exists", "(", "injects", ")", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "injects", ")"...
adds provided annotations to obj @private @param obj @param override
[ "adds", "provided", "annotations", "to", "obj" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L328-L339
28,774
RackHD/on-core
lib/di.js
injectableWrapper
function injectableWrapper(obj, provide, injects, isTransientScope) { // TODO(@davequick): discuss with @halfspiral whether isTransientScope might just better // be an array of Annotations var wrappedObject = function wrapOrCreateObject() { if(isFunction(obj) && (exists(obj.$provide) || exists(obj.$inject) || provide || injects)){ var instance = Object.create(obj.prototype); return obj.apply(instance,arguments) || instance; } return obj; }; return _wrapper(obj, wrappedObject, provide, injects, isTransientScope); }
javascript
function injectableWrapper(obj, provide, injects, isTransientScope) { // TODO(@davequick): discuss with @halfspiral whether isTransientScope might just better // be an array of Annotations var wrappedObject = function wrapOrCreateObject() { if(isFunction(obj) && (exists(obj.$provide) || exists(obj.$inject) || provide || injects)){ var instance = Object.create(obj.prototype); return obj.apply(instance,arguments) || instance; } return obj; }; return _wrapper(obj, wrappedObject, provide, injects, isTransientScope); }
[ "function", "injectableWrapper", "(", "obj", ",", "provide", ",", "injects", ",", "isTransientScope", ")", "{", "// TODO(@davequick): discuss with @halfspiral whether isTransientScope might just better", "// be an array of Annotations", "var", "wrappedObject", "=", "function", "w...
This is meant to be used where you have an injectable that might be an injectable function. if it is we want to actually have the injection happen while it is being returned. @param obj @param provide @param injects @param isTransientScope @returns {*}
[ "This", "is", "meant", "to", "be", "used", "where", "you", "have", "an", "injectable", "that", "might", "be", "an", "injectable", "function", ".", "if", "it", "is", "we", "want", "to", "actually", "have", "the", "injection", "happen", "while", "it", "is"...
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L410-L421
28,775
RackHD/on-core
lib/di.js
_requireFile
function _requireFile(requirable, directory) { var required; try{ var res = resolve.sync(requirable, { basedir: directory}); required = require(res); } catch(err) { required = (void 0); } return required; }
javascript
function _requireFile(requirable, directory) { var required; try{ var res = resolve.sync(requirable, { basedir: directory}); required = require(res); } catch(err) { required = (void 0); } return required; }
[ "function", "_requireFile", "(", "requirable", ",", "directory", ")", "{", "var", "required", ";", "try", "{", "var", "res", "=", "resolve", ".", "sync", "(", "requirable", ",", "{", "basedir", ":", "directory", "}", ")", ";", "required", "=", "require",...
Attempt to fetch the supplied filename, no exceptions on fail @private @param {string} requirable to try and require @param {string} [directory] - directory to attempt resolving filename path with @returns {*} the result of the require, undefined if not found
[ "Attempt", "to", "fetch", "the", "supplied", "filename", "no", "exceptions", "on", "fail" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L456-L466
28,776
RackHD/on-core
lib/di.js
_require
function _require(requireMe, provides, injects, currentDirectory, next) { var requireResult = _requireFile (requireMe, currentDirectory) || _requireFile (requireMe, defaultDirectory) || _requireFile (requireMe, __dirname) || _requireFile (requireMe, process.cwd()) || _requireFile (requireMe, (void 0)); if(!exists(requireResult)) { var directories = 'directories:('; directories += exists(currentDirectory) ? currentDirectory + ', ' : ''; directories += exists(defaultDirectory) ? defaultDirectory + ', ' : ''; directories += __dirname + ')'; throw new Error('dihelper incapable of finding specified file for require filename:' + requireMe + ', ' + directories); } if (typeof provides === 'undefined' && !exists(requireResult.$provide)) { //TODO(@davequick): also look for annotations once ES6, for now can't because you would // receive a different di instance if you did require('di/dist/cjs/annotations') so class // equalities would not work. Once all is ES6, then instanceof for the classes should work // and add it here. For now you have to have a string or object on yourmodule.$provide or // it will be overwritten. provides = requireMe; } return next(requireResult, provides, injects); }
javascript
function _require(requireMe, provides, injects, currentDirectory, next) { var requireResult = _requireFile (requireMe, currentDirectory) || _requireFile (requireMe, defaultDirectory) || _requireFile (requireMe, __dirname) || _requireFile (requireMe, process.cwd()) || _requireFile (requireMe, (void 0)); if(!exists(requireResult)) { var directories = 'directories:('; directories += exists(currentDirectory) ? currentDirectory + ', ' : ''; directories += exists(defaultDirectory) ? defaultDirectory + ', ' : ''; directories += __dirname + ')'; throw new Error('dihelper incapable of finding specified file for require filename:' + requireMe + ', ' + directories); } if (typeof provides === 'undefined' && !exists(requireResult.$provide)) { //TODO(@davequick): also look for annotations once ES6, for now can't because you would // receive a different di instance if you did require('di/dist/cjs/annotations') so class // equalities would not work. Once all is ES6, then instanceof for the classes should work // and add it here. For now you have to have a string or object on yourmodule.$provide or // it will be overwritten. provides = requireMe; } return next(requireResult, provides, injects); }
[ "function", "_require", "(", "requireMe", ",", "provides", ",", "injects", ",", "currentDirectory", ",", "next", ")", "{", "var", "requireResult", "=", "_requireFile", "(", "requireMe", ",", "currentDirectory", ")", "||", "_requireFile", "(", "requireMe", ",", ...
internal helper for the exposed require helpers to cut down on replication of code. @private @param {string} requireMe is string passed to require() @param {string|object} [provides] - is either an array or string of things this object provides @param {string|string[]|object|objects[]} [injects] - is either a single string or array of strings of module names to be injected @param {string} [currentDirectory] - directory to attempt first require from @param {function} next function (wrap or override) to call with the result of the require @returns {*}
[ "internal", "helper", "for", "the", "exposed", "require", "helpers", "to", "cut", "down", "on", "replication", "of", "code", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L480-L508
28,777
RackHD/on-core
lib/di.js
requireWrapper
function requireWrapper(requireMe, provides, injects, directory) { return _require(requireMe, provides, injects, directory, simpleWrapper); }
javascript
function requireWrapper(requireMe, provides, injects, directory) { return _require(requireMe, provides, injects, directory, simpleWrapper); }
[ "function", "requireWrapper", "(", "requireMe", ",", "provides", ",", "injects", ",", "directory", ")", "{", "return", "_require", "(", "requireMe", ",", "provides", ",", "injects", ",", "directory", ",", "simpleWrapper", ")", ";", "}" ]
this one does the require for you and returns an object that is annotated @param requireMe is string passed to require() @param [provides] - is either an array or string of things this object provides @param [injects] - is either a single string or array of strings of module names to be injected @param [directory] - to attempt first require from @returns {*}
[ "this", "one", "does", "the", "require", "for", "you", "and", "returns", "an", "object", "that", "is", "annotated" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L518-L520
28,778
RackHD/on-core
lib/di.js
requireGlob
function requireGlob(pattern) { return _.map(glob.sync(pattern), function (file) { var required = require(file); resolveProvide(required); resolveInjects(required); return required; }); }
javascript
function requireGlob(pattern) { return _.map(glob.sync(pattern), function (file) { var required = require(file); resolveProvide(required); resolveInjects(required); return required; }); }
[ "function", "requireGlob", "(", "pattern", ")", "{", "return", "_", ".", "map", "(", "glob", ".", "sync", "(", "pattern", ")", ",", "function", "(", "file", ")", "{", "var", "required", "=", "require", "(", "file", ")", ";", "resolveProvide", "(", "r...
requireGlob requires all files matching the glob pattern and provides a list of injectables based on that pattern. @param {String} pattern A glob pattern to search for files to require. @return {Array.<Object>} A list of require'd objects to provide to the injector.
[ "requireGlob", "requires", "all", "files", "matching", "the", "glob", "pattern", "and", "provides", "a", "list", "of", "injectables", "based", "on", "that", "pattern", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L528-L537
28,779
RackHD/on-core
lib/di.js
injectableFromFile
function injectableFromFile(requireMe, provides, injects, directory) { return _require(requireMe, provides, injects, directory, injectableWrapper); }
javascript
function injectableFromFile(requireMe, provides, injects, directory) { return _require(requireMe, provides, injects, directory, injectableWrapper); }
[ "function", "injectableFromFile", "(", "requireMe", ",", "provides", ",", "injects", ",", "directory", ")", "{", "return", "_require", "(", "requireMe", ",", "provides", ",", "injects", ",", "directory", ",", "injectableWrapper", ")", ";", "}" ]
expecting an injeciton aware function and the function is called with the injectables on get. @param requireMe is string passed to require() @param [provides] - is either an array or string of things this object provides @param [injects] - is either a single string or array of strings of module names to be injected @param [directory] - to attempt first require from @returns {*}
[ "expecting", "an", "injeciton", "aware", "function", "and", "the", "function", "is", "called", "with", "the", "injectables", "on", "get", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L560-L562
28,780
RackHD/on-core
lib/di.js
requireOverrideInjection
function requireOverrideInjection(requireMe, provides, injects, directory) { return _require(requireMe, provides, injects, directory, overrideInjection); }
javascript
function requireOverrideInjection(requireMe, provides, injects, directory) { return _require(requireMe, provides, injects, directory, overrideInjection); }
[ "function", "requireOverrideInjection", "(", "requireMe", ",", "provides", ",", "injects", ",", "directory", ")", "{", "return", "_require", "(", "requireMe", ",", "provides", ",", "injects", ",", "directory", ",", "overrideInjection", ")", ";", "}" ]
overides the given require with the injectables provided @param requireMe is string passed to require() @param [provides] - is either an array or string of things this object provides @param [injects] - is either a single string or array of strings of module names to be injected @param [directory] - to attempt first require from @returns {*}
[ "overides", "the", "given", "require", "with", "the", "injectables", "provided" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L572-L574
28,781
bigpipe/env-variable
index.js
env
function env(environment) { environment = environment || {}; if ('object' === typeof process && 'object' === typeof process.env) { env.merge(environment, process.env); } if ('undefined' !== typeof window) { if ('string' === window.name && window.name.length) { env.merge(environment, env.parse(window.name)); } if (window.localStorage) { try { env.merge(environment, env.parse(window.localStorage.env || window.localStorage.debug)); } catch (e) {} } if ( 'object' === typeof window.location && 'string' === typeof window.location.hash && window.location.hash.length ) { env.merge(environment, env.parse(window.location.hash.charAt(0) === '#' ? window.location.hash.slice(1) : window.location.hash )); } } // // Also add lower case variants to the object for easy access. // var key, lower; for (key in environment) { lower = key.toLowerCase(); if (!(lower in environment)) { environment[lower] = environment[key]; } } return environment; }
javascript
function env(environment) { environment = environment || {}; if ('object' === typeof process && 'object' === typeof process.env) { env.merge(environment, process.env); } if ('undefined' !== typeof window) { if ('string' === window.name && window.name.length) { env.merge(environment, env.parse(window.name)); } if (window.localStorage) { try { env.merge(environment, env.parse(window.localStorage.env || window.localStorage.debug)); } catch (e) {} } if ( 'object' === typeof window.location && 'string' === typeof window.location.hash && window.location.hash.length ) { env.merge(environment, env.parse(window.location.hash.charAt(0) === '#' ? window.location.hash.slice(1) : window.location.hash )); } } // // Also add lower case variants to the object for easy access. // var key, lower; for (key in environment) { lower = key.toLowerCase(); if (!(lower in environment)) { environment[lower] = environment[key]; } } return environment; }
[ "function", "env", "(", "environment", ")", "{", "environment", "=", "environment", "||", "{", "}", ";", "if", "(", "'object'", "===", "typeof", "process", "&&", "'object'", "===", "typeof", "process", ".", "env", ")", "{", "env", ".", "merge", "(", "e...
Gather environment variables from various locations. @param {Object} environment The default environment variables. @returns {Object} environment. @api public
[ "Gather", "environment", "variables", "from", "various", "locations", "." ]
f663c23ac41beff094378738843584c5754cd6cf
https://github.com/bigpipe/env-variable/blob/f663c23ac41beff094378738843584c5754cd6cf/index.js#L12-L54
28,782
g13013/broccoli-compass
index.js
moveToDest
function moveToDest(srcDir, destDir) { if (!this.options.cleanOutput) { return srcDir; } var content, cssDir, src; var copiedCache = this.copiedCache || {}; var copied = {}; var options = this.options; var tree = this.walkDir(srcDir, {cache: this.cache}); var cache = tree.paths; var generated = tree.changed; var linkedFiles = []; for (var i = 0; i < generated.length; i += 1) { file = generated[i]; if (cache[file].isDirectory || copiedCache[file] === cache[file].statsHash) { continue; } src = srcDir + '/' + file; if (file.substr(-4) === '.css') { content = fs.readFileSync(src); cssDir = path.dirname(file); while ((linkedFile = urlRe.exec(content))) { linkedFile = (linkedFile[1][0] === '/') ? linkedFile[1].substr(1) : path.normalize(cssDir + '/' + linkedFile[1]); linkedFiles.push(linkedFile); } } mkdirp(destDir + '/' + path.dirname(file)); symlinkOrCopy(src, destDir + '/' + file); copied[file] = cache[file].statsHash; } for (i = 0; i < linkedFiles.length; i += 1) { file = linkedFiles[i]; if (file in copied) { continue; } if (!cache[file] || copiedCache[file] !== cache[file].statsHash) { copied[file] = cache[file] && cache[file].statsHash; mkdirp(destDir + '/' + path.dirname(file)); symlinkOrCopy(srcDir + '/' + file, destDir + '/' + file); } } this.copiedCache = copied; return destDir; }
javascript
function moveToDest(srcDir, destDir) { if (!this.options.cleanOutput) { return srcDir; } var content, cssDir, src; var copiedCache = this.copiedCache || {}; var copied = {}; var options = this.options; var tree = this.walkDir(srcDir, {cache: this.cache}); var cache = tree.paths; var generated = tree.changed; var linkedFiles = []; for (var i = 0; i < generated.length; i += 1) { file = generated[i]; if (cache[file].isDirectory || copiedCache[file] === cache[file].statsHash) { continue; } src = srcDir + '/' + file; if (file.substr(-4) === '.css') { content = fs.readFileSync(src); cssDir = path.dirname(file); while ((linkedFile = urlRe.exec(content))) { linkedFile = (linkedFile[1][0] === '/') ? linkedFile[1].substr(1) : path.normalize(cssDir + '/' + linkedFile[1]); linkedFiles.push(linkedFile); } } mkdirp(destDir + '/' + path.dirname(file)); symlinkOrCopy(src, destDir + '/' + file); copied[file] = cache[file].statsHash; } for (i = 0; i < linkedFiles.length; i += 1) { file = linkedFiles[i]; if (file in copied) { continue; } if (!cache[file] || copiedCache[file] !== cache[file].statsHash) { copied[file] = cache[file] && cache[file].statsHash; mkdirp(destDir + '/' + path.dirname(file)); symlinkOrCopy(srcDir + '/' + file, destDir + '/' + file); } } this.copiedCache = copied; return destDir; }
[ "function", "moveToDest", "(", "srcDir", ",", "destDir", ")", "{", "if", "(", "!", "this", ".", "options", ".", "cleanOutput", ")", "{", "return", "srcDir", ";", "}", "var", "content", ",", "cssDir", ",", "src", ";", "var", "copiedCache", "=", "this", ...
Walks the tree and looks for css files under css directory, if `cleanOutput` is TRUE, css content is read to extract images and fonts paths to add them to the queue. Note that this function simply return srcDir if `cleanOutput` is false. @param {String} srcDir Source directory @param {String} destDir Destination
[ "Walks", "the", "tree", "and", "looks", "for", "css", "files", "under", "css", "directory", "if", "cleanOutput", "is", "TRUE", "css", "content", "is", "read", "to", "extract", "images", "and", "fonts", "paths", "to", "add", "them", "to", "the", "queue", ...
d915daa711491f13d6129cdd41c9fce2dbaf2ade
https://github.com/g13013/broccoli-compass/blob/d915daa711491f13d6129cdd41c9fce2dbaf2ade/index.js#L57-L99
28,783
g13013/broccoli-compass
index.js
CompassCompiler
function CompassCompiler(inputTree, files, options) { options = arguments.length > 2 ? (options || {}) : (files || {}); if (arguments.length > 2) { console.log('[broccoli-compass] DEPRECATION: passing files to broccoli-compass constructor as second parameter is deprecated, ' + 'use options.files instead'); options.files = files; } if (!(this instanceof CompassCompiler)) { return new CompassCompiler(inputTree, options); } if (options.exclude) { console.log('[broccoli-compass] DEPRECATION: The exclude option has been deprecated in favour of the `cleanOutput` option'); } this.options = merge(true, this.defaultOptions); merge(this.options, options); options = this.options; options.files = (options.files instanceof Array) ? options.files : []; this.generateCmdLine(); this.inputTree = inputTree; }
javascript
function CompassCompiler(inputTree, files, options) { options = arguments.length > 2 ? (options || {}) : (files || {}); if (arguments.length > 2) { console.log('[broccoli-compass] DEPRECATION: passing files to broccoli-compass constructor as second parameter is deprecated, ' + 'use options.files instead'); options.files = files; } if (!(this instanceof CompassCompiler)) { return new CompassCompiler(inputTree, options); } if (options.exclude) { console.log('[broccoli-compass] DEPRECATION: The exclude option has been deprecated in favour of the `cleanOutput` option'); } this.options = merge(true, this.defaultOptions); merge(this.options, options); options = this.options; options.files = (options.files instanceof Array) ? options.files : []; this.generateCmdLine(); this.inputTree = inputTree; }
[ "function", "CompassCompiler", "(", "inputTree", ",", "files", ",", "options", ")", "{", "options", "=", "arguments", ".", "length", ">", "2", "?", "(", "options", "||", "{", "}", ")", ":", "(", "files", "||", "{", "}", ")", ";", "if", "(", "argume...
broccoli-compass Constructor. @param inputTree Any Broccoli tree. @param files [Optional] An array of sass files to compile. @param options The compass options. @returns {CompassCompiler}
[ "broccoli", "-", "compass", "Constructor", "." ]
d915daa711491f13d6129cdd41c9fce2dbaf2ade
https://github.com/g13013/broccoli-compass/blob/d915daa711491f13d6129cdd41c9fce2dbaf2ade/index.js#L145-L167
28,784
bminer/node-static-asset
lib/cache-strategies/default.js
addToCache
function addToCache(filename, obj) { if(cacheOn) { var x = cache[filename]; if(!x) x = cache[filename] = {}; x.mtime = obj.mtime || x.mtime; x.etag = obj.etag || x.etag; x.size = obj.size || x.size; } }
javascript
function addToCache(filename, obj) { if(cacheOn) { var x = cache[filename]; if(!x) x = cache[filename] = {}; x.mtime = obj.mtime || x.mtime; x.etag = obj.etag || x.etag; x.size = obj.size || x.size; } }
[ "function", "addToCache", "(", "filename", ",", "obj", ")", "{", "if", "(", "cacheOn", ")", "{", "var", "x", "=", "cache", "[", "filename", "]", ";", "if", "(", "!", "x", ")", "x", "=", "cache", "[", "filename", "]", "=", "{", "}", ";", "x", ...
Adds information to the cache
[ "Adds", "information", "to", "the", "cache" ]
cd7bbe1fcbc6d5e2e1738c7f4b9b823471222097
https://github.com/bminer/node-static-asset/blob/cd7bbe1fcbc6d5e2e1738c7f4b9b823471222097/lib/cache-strategies/default.js#L6-L16
28,785
RackHD/on-core
lib/common/model.js
function () { var self = this; var indexes = self.$indexes || []; return Promise.try (function() { assert.arrayOfObject(indexes, '$indexes should be an array of object'); //validate and assign default arguments before creating indexes //if necessary, convert the indexes format to fit for different database _.forEach(indexes, function(indexItem) { assert.object(indexItem.keys, 'Database index keys should be object'); if (indexItem.options) { assert.object(indexItem.options, 'Database index options should be object'); } else { indexItem.options = {}; } }); return indexes; }) .then(function(indexes) { if (_.isEmpty(indexes)) { return; } switch(self.connection.toString()) { case 'mongo': return Promise.map(indexes, function(indexItem) { return self.createMongoIndexes([indexItem.keys, indexItem.options]); }); default: break; } }); }
javascript
function () { var self = this; var indexes = self.$indexes || []; return Promise.try (function() { assert.arrayOfObject(indexes, '$indexes should be an array of object'); //validate and assign default arguments before creating indexes //if necessary, convert the indexes format to fit for different database _.forEach(indexes, function(indexItem) { assert.object(indexItem.keys, 'Database index keys should be object'); if (indexItem.options) { assert.object(indexItem.options, 'Database index options should be object'); } else { indexItem.options = {}; } }); return indexes; }) .then(function(indexes) { if (_.isEmpty(indexes)) { return; } switch(self.connection.toString()) { case 'mongo': return Promise.map(indexes, function(indexItem) { return self.createMongoIndexes([indexItem.keys, indexItem.options]); }); default: break; } }); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "var", "indexes", "=", "self", ".", "$indexes", "||", "[", "]", ";", "return", "Promise", ".", "try", "(", "function", "(", ")", "{", "assert", ".", "arrayOfObject", "(", "indexes", ",", "...
Create indexes for different database the waterline has bug for index creation and it also doesn't support compound index, this function is to manually create indexes regardless what waterline will do. This function support both single-field and compound index @return {Promise} Resolved if create indexes successfully.
[ "Create", "indexes", "for", "different", "database" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/model.js#L150-L184
28,786
RackHD/on-core
lib/common/model.js
function (criteria) { var identity = this.identity; return this.findOne(criteria).then(function (record) { if (!record) { throw new Errors.NotFoundError( 'Could not find %s with criteria %j.'.format( pluralize.singular(identity), criteria ), { criteria: criteria, collection: identity }); } return record; }); }
javascript
function (criteria) { var identity = this.identity; return this.findOne(criteria).then(function (record) { if (!record) { throw new Errors.NotFoundError( 'Could not find %s with criteria %j.'.format( pluralize.singular(identity), criteria ), { criteria: criteria, collection: identity }); } return record; }); }
[ "function", "(", "criteria", ")", "{", "var", "identity", "=", "this", ".", "identity", ";", "return", "this", ".", "findOne", "(", "criteria", ")", ".", "then", "(", "function", "(", "record", ")", "{", "if", "(", "!", "record", ")", "{", "throw", ...
Find a single document via criteria and resolve it, otherwise reject with a NotFoundError.
[ "Find", "a", "single", "document", "via", "criteria", "and", "resolve", "it", "otherwise", "reject", "with", "a", "NotFoundError", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/model.js#L586-L603
28,787
RackHD/on-core
lib/common/model.js
function (criteria, document) { var self = this; return this.needOne(criteria).then(function (target) { return self.update(target.id, document).then(function (documents) { return documents[0]; }); }); }
javascript
function (criteria, document) { var self = this; return this.needOne(criteria).then(function (target) { return self.update(target.id, document).then(function (documents) { return documents[0]; }); }); }
[ "function", "(", "criteria", ",", "document", ")", "{", "var", "self", "=", "this", ";", "return", "this", ".", "needOne", "(", "criteria", ")", ".", "then", "(", "function", "(", "target", ")", "{", "return", "self", ".", "update", "(", "target", "....
Update a single document by criteria and resolve it, otherwise reject with a NotFoundError.
[ "Update", "a", "single", "document", "by", "criteria", "and", "resolve", "it", "otherwise", "reject", "with", "a", "NotFoundError", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/model.js#L617-L625
28,788
RackHD/on-core
lib/common/model.js
function (criteria) { var self = this; return this.needOne(criteria).then(function (target) { return self.destroy(target.id).then(function (documents) { return documents[0]; }); }); }
javascript
function (criteria) { var self = this; return this.needOne(criteria).then(function (target) { return self.destroy(target.id).then(function (documents) { return documents[0]; }); }); }
[ "function", "(", "criteria", ")", "{", "var", "self", "=", "this", ";", "return", "this", ".", "needOne", "(", "criteria", ")", ".", "then", "(", "function", "(", "target", ")", "{", "return", "self", ".", "destroy", "(", "target", ".", "id", ")", ...
Destroy a single document by criteria and resolve it, otherwies reject with a NotFoundError.
[ "Destroy", "a", "single", "document", "by", "criteria", "and", "resolve", "it", "otherwies", "reject", "with", "a", "NotFoundError", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/model.js#L770-L778
28,789
RackHD/on-core
lib/common/errors.js
BaseError
function BaseError(message, context) { this.message = message; this.name = this.constructor.name; this.context = context || {}; Error.captureStackTrace(this, BaseError); }
javascript
function BaseError(message, context) { this.message = message; this.name = this.constructor.name; this.context = context || {}; Error.captureStackTrace(this, BaseError); }
[ "function", "BaseError", "(", "message", ",", "context", ")", "{", "this", ".", "message", "=", "message", ";", "this", ".", "name", "=", "this", ".", "constructor", ".", "name", ";", "this", ".", "context", "=", "context", "||", "{", "}", ";", "Erro...
Base error object which should be inherited, not used directly. @constructor @param {string} message Error Message
[ "Base", "error", "object", "which", "should", "be", "inherited", "not", "used", "directly", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/errors.js#L18-L24
28,790
RackHD/on-core
lib/common/subscription.js
Subscription
function Subscription (queue, options) { assert.object(queue, 'queue'); assert.object(options, 'options'); this.MAX_DISPOSE_RETRIES = 3; this.retryDelay = 1000; this.queue = queue; this.options = options; this._disposed = false; }
javascript
function Subscription (queue, options) { assert.object(queue, 'queue'); assert.object(options, 'options'); this.MAX_DISPOSE_RETRIES = 3; this.retryDelay = 1000; this.queue = queue; this.options = options; this._disposed = false; }
[ "function", "Subscription", "(", "queue", ",", "options", ")", "{", "assert", ".", "object", "(", "queue", ",", "'queue'", ")", ";", "assert", ".", "object", "(", "options", ",", "'options'", ")", ";", "this", ".", "MAX_DISPOSE_RETRIES", "=", "3", ";", ...
Creates a new subscription to a queue @param queue {string} @constructor
[ "Creates", "a", "new", "subscription", "to", "a", "queue" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/subscription.js#L22-L31
28,791
choojs/choo-devtools
lib/perf.js
Perf
function Perf (stats, name, filter, rename) { this.stats = stats this.name = name this.filter = filter || function () { return true } this.rename = rename || function (name) { return name } }
javascript
function Perf (stats, name, filter, rename) { this.stats = stats this.name = name this.filter = filter || function () { return true } this.rename = rename || function (name) { return name } }
[ "function", "Perf", "(", "stats", ",", "name", ",", "filter", ",", "rename", ")", "{", "this", ".", "stats", "=", "stats", "this", ".", "name", "=", "name", "this", ".", "filter", "=", "filter", "||", "function", "(", ")", "{", "return", "true", "}...
Create a new Perf instance by passing it a filter
[ "Create", "a", "new", "Perf", "instance", "by", "passing", "it", "a", "filter" ]
d23bcacbf5d7cc05dc121b9580d33b28a2b2d0f9
https://github.com/choojs/choo-devtools/blob/d23bcacbf5d7cc05dc121b9580d33b28a2b2d0f9/lib/perf.js#L67-L72
28,792
choojs/choo-devtools
lib/perf.js
getMedian
function getMedian (args) { if (!args.length) return 0 var numbers = args.slice(0).sort(function (a, b) { return a - b }) var middle = Math.floor(numbers.length / 2) var isEven = numbers.length % 2 === 0 var res = isEven ? (numbers[middle] + numbers[middle - 1]) / 2 : numbers[middle] return Number(res.toFixed(2)) }
javascript
function getMedian (args) { if (!args.length) return 0 var numbers = args.slice(0).sort(function (a, b) { return a - b }) var middle = Math.floor(numbers.length / 2) var isEven = numbers.length % 2 === 0 var res = isEven ? (numbers[middle] + numbers[middle - 1]) / 2 : numbers[middle] return Number(res.toFixed(2)) }
[ "function", "getMedian", "(", "args", ")", "{", "if", "(", "!", "args", ".", "length", ")", "return", "0", "var", "numbers", "=", "args", ".", "slice", "(", "0", ")", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "a", "-...
Get the median from an array of numbers.
[ "Get", "the", "median", "from", "an", "array", "of", "numbers", "." ]
d23bcacbf5d7cc05dc121b9580d33b28a2b2d0f9
https://github.com/choojs/choo-devtools/blob/d23bcacbf5d7cc05dc121b9580d33b28a2b2d0f9/lib/perf.js#L129-L136
28,793
RackHD/on-core
lib/common/message.js
Message
function Message (data, headers, deliveryInfo) { assert.object(data); assert.object(headers); assert.object(deliveryInfo); this.data = Message.factory(data, deliveryInfo.type); this.headers = headers; this.deliveryInfo = deliveryInfo; }
javascript
function Message (data, headers, deliveryInfo) { assert.object(data); assert.object(headers); assert.object(deliveryInfo); this.data = Message.factory(data, deliveryInfo.type); this.headers = headers; this.deliveryInfo = deliveryInfo; }
[ "function", "Message", "(", "data", ",", "headers", ",", "deliveryInfo", ")", "{", "assert", ".", "object", "(", "data", ")", ";", "assert", ".", "object", "(", "headers", ")", ";", "assert", ".", "object", "(", "deliveryInfo", ")", ";", "this", ".", ...
Constructor for a message @param {*} messenger @param {Object} data @param {*} [options] @constructor
[ "Constructor", "for", "a", "message" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/message.js#L24-L32
28,794
RackHD/on-core
lib/common/profile.js
profileServiceFactory
function profileServiceFactory( Constants, Promise, _, DbRenderable, Util ) { Util.inherits(ProfileService, DbRenderable); /** * ProfileService is a singleton object which provides key/value store * access to profile files loaded from disk via FileLoader. * @constructor * @extends {FileLoader} */ function ProfileService () { DbRenderable.call(this, { directory: Constants.Profiles.Directory, collectionName: 'profiles' }); } ProfileService.prototype.get = function (name, raw, scope ) { return ProfileService.super_.prototype.get.call(this, name, scope) .then(function(profile) { if (profile && raw) { return profile.contents; } else { return profile; } }); }; return new ProfileService(); }
javascript
function profileServiceFactory( Constants, Promise, _, DbRenderable, Util ) { Util.inherits(ProfileService, DbRenderable); /** * ProfileService is a singleton object which provides key/value store * access to profile files loaded from disk via FileLoader. * @constructor * @extends {FileLoader} */ function ProfileService () { DbRenderable.call(this, { directory: Constants.Profiles.Directory, collectionName: 'profiles' }); } ProfileService.prototype.get = function (name, raw, scope ) { return ProfileService.super_.prototype.get.call(this, name, scope) .then(function(profile) { if (profile && raw) { return profile.contents; } else { return profile; } }); }; return new ProfileService(); }
[ "function", "profileServiceFactory", "(", "Constants", ",", "Promise", ",", "_", ",", "DbRenderable", ",", "Util", ")", "{", "Util", ".", "inherits", "(", "ProfileService", ",", "DbRenderable", ")", ";", "/**\n * ProfileService is a singleton object which provides k...
profileServiceFactory provides the profile-service singleton object. @private @param {FileLoader} FileLoader A FileLoader class for extension. @param {configuration} configuration An instance of the configuration configuration object. @return {ProfileService} An instance of the ProfileService.
[ "profileServiceFactory", "provides", "the", "profile", "-", "service", "singleton", "object", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/profile.js#L23-L57
28,795
RackHD/on-core
lib/common/logger.js
loggerFactory
function loggerFactory( events, Constants, assert, _, util, stack, nconf ) { var levels = _.keys(Constants.Logging.Levels); function getCaller (depth) { var current = stack.get()[depth]; var file = current.getFileName().replace( Constants.WorkingDirectory, '' ) + ':' + current.getLineNumber(); return file.replace(/^node_modules/, ''); } function Logger (module) { var provides = util.provides(module); if (provides !== undefined) { this.module = provides; } else { if (_.isFunction(module)) { this.module = module.name; } else { this.module = module || 'No Module'; } } } Logger.prototype.log = function (level, message, context) { assert.isIn(level, levels); assert.string(message, 'message'); // Exit if the log level of this message is less than the minimum log level. var minLogLevel = nconf.get('minLogLevel'); if ((minLogLevel === undefined) || (typeof minLogLevel !== 'number')) { minLogLevel = 0; } if (Constants.Logging.Levels[level] < minLogLevel) { return; } events.log({ name: Constants.Name, host: Constants.Host, module: this.module, level: level, message: message, context: context, timestamp: new Date().toISOString(), caller: getCaller(3), subject: 'Server' }); }; _.forEach(levels, function(level) { Logger.prototype[level] = function (message, context) { this.log(level, message, context); }; }); Logger.prototype.deprecate = function (message, frames) { console.error([ 'DEPRECATION:', this.module, '-', message, getCaller(frames || 2) ].join(' ')); }; Logger.initialize = function (module) { return new Logger(module); }; return Logger; }
javascript
function loggerFactory( events, Constants, assert, _, util, stack, nconf ) { var levels = _.keys(Constants.Logging.Levels); function getCaller (depth) { var current = stack.get()[depth]; var file = current.getFileName().replace( Constants.WorkingDirectory, '' ) + ':' + current.getLineNumber(); return file.replace(/^node_modules/, ''); } function Logger (module) { var provides = util.provides(module); if (provides !== undefined) { this.module = provides; } else { if (_.isFunction(module)) { this.module = module.name; } else { this.module = module || 'No Module'; } } } Logger.prototype.log = function (level, message, context) { assert.isIn(level, levels); assert.string(message, 'message'); // Exit if the log level of this message is less than the minimum log level. var minLogLevel = nconf.get('minLogLevel'); if ((minLogLevel === undefined) || (typeof minLogLevel !== 'number')) { minLogLevel = 0; } if (Constants.Logging.Levels[level] < minLogLevel) { return; } events.log({ name: Constants.Name, host: Constants.Host, module: this.module, level: level, message: message, context: context, timestamp: new Date().toISOString(), caller: getCaller(3), subject: 'Server' }); }; _.forEach(levels, function(level) { Logger.prototype[level] = function (message, context) { this.log(level, message, context); }; }); Logger.prototype.deprecate = function (message, frames) { console.error([ 'DEPRECATION:', this.module, '-', message, getCaller(frames || 2) ].join(' ')); }; Logger.initialize = function (module) { return new Logger(module); }; return Logger; }
[ "function", "loggerFactory", "(", "events", ",", "Constants", ",", "assert", ",", "_", ",", "util", ",", "stack", ",", "nconf", ")", "{", "var", "levels", "=", "_", ".", "keys", "(", "Constants", ".", "Logging", ".", "Levels", ")", ";", "function", "...
loggerFactory returns a Logger instance. @private
[ "loggerFactory", "returns", "a", "Logger", "instance", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/logger.js#L22-L105
28,796
RackHD/on-core
lib/common/graph-progress.js
GraphProgress
function GraphProgress(graph, graphDescription) { assert.object(graph, 'graph'); assert.string(graphDescription, 'graphDescription'); this.graph = graph; this.data = { graphId: graph.instanceId, nodeId: graph.node, graphName: graph.name || 'Not available', status: graph._status, progress: { description: graphDescription || 'Not available', } }; this._calculateGraphProgress(); }
javascript
function GraphProgress(graph, graphDescription) { assert.object(graph, 'graph'); assert.string(graphDescription, 'graphDescription'); this.graph = graph; this.data = { graphId: graph.instanceId, nodeId: graph.node, graphName: graph.name || 'Not available', status: graph._status, progress: { description: graphDescription || 'Not available', } }; this._calculateGraphProgress(); }
[ "function", "GraphProgress", "(", "graph", ",", "graphDescription", ")", "{", "assert", ".", "object", "(", "graph", ",", "'graph'", ")", ";", "assert", ".", "string", "(", "graphDescription", ",", "'graphDescription'", ")", ";", "this", ".", "graph", "=", ...
Creates a new GraphProgress and calculate the graph progress @param graph {Object} @param graphDescription {String} @constructor
[ "Creates", "a", "new", "GraphProgress", "and", "calculate", "the", "graph", "progress" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/graph-progress.js#L24-L39
28,797
RackHD/on-core
lib/common/http-tool.js
HttpTool
function HttpTool(){ this.settings = {}; this.urlObject = {}; this.dataToWrite = ''; // ********** Helper Functions/Members ********** var validMethods = ['GET', 'PUT', 'POST', 'DELETE', 'PATCH']; /** * Make sure that settings has at least property of url and method. * @return {boolean} whether settings is valid. */ this.isSettingValid = function(settings){ if (_.isEmpty(settings)) { return false; } if ( ! (settings.hasOwnProperty('url') && settings.hasOwnProperty('method'))) { return false; } if (_.isEmpty(settings.url) || _.isEmpty(settings.method)) { return false; } if (_.indexOf(validMethods, settings.method) === -1) { return false; } return true; }; /** * Parse and convert setting into a urlObject that suitable for * http/https module in NodeJs. * @return {object} - the object that suitable for Node http/https module. */ this.setupUrlOptions = function(settings) { var urlTool = require('url'); var urlObject = {}; // Parse the string into url options if (typeof (settings.url) === 'string') { urlObject = urlTool.parse(settings.url); } else { urlObject = settings.url; } // set the REST options urlObject.method = settings.method; // set up the REST headers if (! _.isEmpty(settings.headers)){ urlObject.headers = settings.headers; } else { urlObject.headers = {}; } urlObject.headers['Content-Length'] = 0; if (settings.hasOwnProperty('data')){ switch (typeof settings.data) { case 'object': this.dataToWrite = JSON.stringify(settings.data); urlObject.headers['Content-Type'] = 'application/json'; break; case 'string': this.dataToWrite = settings.data; break; default: throw new TypeError("Data field can only be object or string," + " but got " + (typeof settings.data)); } urlObject.headers['Content-Length'] = Buffer.byteLength(this.dataToWrite); } if (! _.isEmpty(settings.credential)){ if (!_.isEmpty(settings.credential.password) && _.isEmpty(settings.credential.username)) { throw new Error('Please provide username and password '+ 'for basic authentication.'); } else { urlObject.auth = settings.credential.username +':'+ settings.credential.password; } } // set the protolcol paramter if (urlObject.protocol.substr(-1) !== ':') { urlObject.protocol = urlObject.protocol + ':'; } urlObject.rejectUnauthorized = settings.verifySSL || false; urlObject.recvTimeoutMs = settings.recvTimeoutMs; return urlObject; }; }
javascript
function HttpTool(){ this.settings = {}; this.urlObject = {}; this.dataToWrite = ''; // ********** Helper Functions/Members ********** var validMethods = ['GET', 'PUT', 'POST', 'DELETE', 'PATCH']; /** * Make sure that settings has at least property of url and method. * @return {boolean} whether settings is valid. */ this.isSettingValid = function(settings){ if (_.isEmpty(settings)) { return false; } if ( ! (settings.hasOwnProperty('url') && settings.hasOwnProperty('method'))) { return false; } if (_.isEmpty(settings.url) || _.isEmpty(settings.method)) { return false; } if (_.indexOf(validMethods, settings.method) === -1) { return false; } return true; }; /** * Parse and convert setting into a urlObject that suitable for * http/https module in NodeJs. * @return {object} - the object that suitable for Node http/https module. */ this.setupUrlOptions = function(settings) { var urlTool = require('url'); var urlObject = {}; // Parse the string into url options if (typeof (settings.url) === 'string') { urlObject = urlTool.parse(settings.url); } else { urlObject = settings.url; } // set the REST options urlObject.method = settings.method; // set up the REST headers if (! _.isEmpty(settings.headers)){ urlObject.headers = settings.headers; } else { urlObject.headers = {}; } urlObject.headers['Content-Length'] = 0; if (settings.hasOwnProperty('data')){ switch (typeof settings.data) { case 'object': this.dataToWrite = JSON.stringify(settings.data); urlObject.headers['Content-Type'] = 'application/json'; break; case 'string': this.dataToWrite = settings.data; break; default: throw new TypeError("Data field can only be object or string," + " but got " + (typeof settings.data)); } urlObject.headers['Content-Length'] = Buffer.byteLength(this.dataToWrite); } if (! _.isEmpty(settings.credential)){ if (!_.isEmpty(settings.credential.password) && _.isEmpty(settings.credential.username)) { throw new Error('Please provide username and password '+ 'for basic authentication.'); } else { urlObject.auth = settings.credential.username +':'+ settings.credential.password; } } // set the protolcol paramter if (urlObject.protocol.substr(-1) !== ':') { urlObject.protocol = urlObject.protocol + ':'; } urlObject.rejectUnauthorized = settings.verifySSL || false; urlObject.recvTimeoutMs = settings.recvTimeoutMs; return urlObject; }; }
[ "function", "HttpTool", "(", ")", "{", "this", ".", "settings", "=", "{", "}", ";", "this", ".", "urlObject", "=", "{", "}", ";", "this", ".", "dataToWrite", "=", "''", ";", "// ********** Helper Functions/Members **********", "var", "validMethods", "=", "["...
Tool class that does HTTP methods @constructor
[ "Tool", "class", "that", "does", "HTTP", "methods" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/http-tool.js#L25-L121
28,798
RackHD/on-core
lib/common/template.js
templateServiceFactory
function templateServiceFactory( Constants, Promise, _, DbRenderable, Util ) { Util.inherits(TemplateService, DbRenderable); /** * TemplateService is a singleton object which provides key/value store * access to template files loaded from disk via FileLoader. * @constructor * @extends {FileLoader} */ function TemplateService () { DbRenderable.call(this, { directory: Constants.Templates.Directory, collectionName: 'templates' }); } return new TemplateService(); }
javascript
function templateServiceFactory( Constants, Promise, _, DbRenderable, Util ) { Util.inherits(TemplateService, DbRenderable); /** * TemplateService is a singleton object which provides key/value store * access to template files loaded from disk via FileLoader. * @constructor * @extends {FileLoader} */ function TemplateService () { DbRenderable.call(this, { directory: Constants.Templates.Directory, collectionName: 'templates' }); } return new TemplateService(); }
[ "function", "templateServiceFactory", "(", "Constants", ",", "Promise", ",", "_", ",", "DbRenderable", ",", "Util", ")", "{", "Util", ".", "inherits", "(", "TemplateService", ",", "DbRenderable", ")", ";", "/**\n * TemplateService is a singleton object which provide...
templateServiceFactory provides the template-service singleton object. @private @param {FileLoader} FileLoader A FileLoader class for extension. @param {configuration} configuration An instance of the configuration configuration object. @return {TemplateService} An instance of the TemplateService.
[ "templateServiceFactory", "provides", "the", "template", "-", "service", "singleton", "object", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/template.js#L23-L46
28,799
tapjs/foreground-child
index.js
normalizeFgArgs
function normalizeFgArgs(fgArgs) { var program, args, cb; var processArgsEnd = fgArgs.length; var lastFgArg = fgArgs[fgArgs.length - 1]; if (typeof lastFgArg === "function") { cb = lastFgArg; processArgsEnd -= 1; } else { cb = function(done) { done(); }; } if (Array.isArray(fgArgs[0])) { program = fgArgs[0][0]; args = fgArgs[0].slice(1); } else { program = fgArgs[0]; args = Array.isArray(fgArgs[1]) ? fgArgs[1] : fgArgs.slice(1, processArgsEnd); } return {program: program, args: args, cb: cb}; }
javascript
function normalizeFgArgs(fgArgs) { var program, args, cb; var processArgsEnd = fgArgs.length; var lastFgArg = fgArgs[fgArgs.length - 1]; if (typeof lastFgArg === "function") { cb = lastFgArg; processArgsEnd -= 1; } else { cb = function(done) { done(); }; } if (Array.isArray(fgArgs[0])) { program = fgArgs[0][0]; args = fgArgs[0].slice(1); } else { program = fgArgs[0]; args = Array.isArray(fgArgs[1]) ? fgArgs[1] : fgArgs.slice(1, processArgsEnd); } return {program: program, args: args, cb: cb}; }
[ "function", "normalizeFgArgs", "(", "fgArgs", ")", "{", "var", "program", ",", "args", ",", "cb", ";", "var", "processArgsEnd", "=", "fgArgs", ".", "length", ";", "var", "lastFgArg", "=", "fgArgs", "[", "fgArgs", ".", "length", "-", "1", "]", ";", "if"...
Normalizes the arguments passed to `foregroundChild`. See the signature of `foregroundChild` for the supported arguments. @param fgArgs Array of arguments passed to `foregroundChild`. @return Normalized arguments @internal
[ "Normalizes", "the", "arguments", "passed", "to", "foregroundChild", "." ]
df07e2426a4072eca9dd15a52aaf3b6c4b117338
https://github.com/tapjs/foreground-child/blob/df07e2426a4072eca9dd15a52aaf3b6c4b117338/index.js#L16-L36