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
20,800
haydenbbickerton/vue-charts
dist/vue-charts.common.js
buildWrapper
function buildWrapper(chartType, dataTable, options, containerId) { var wrapper = new google.visualization.ChartWrapper({ chartType: chartType, dataTable: dataTable, options: options, containerId: containerId }); return wrapper; }
javascript
function buildWrapper(chartType, dataTable, options, containerId) { var wrapper = new google.visualization.ChartWrapper({ chartType: chartType, dataTable: dataTable, options: options, containerId: containerId }); return wrapper; }
[ "function", "buildWrapper", "(", "chartType", ",", "dataTable", ",", "options", ",", "containerId", ")", "{", "var", "wrapper", "=", "new", "google", ".", "visualization", ".", "ChartWrapper", "(", "{", "chartType", ":", "chartType", ",", "dataTable", ":", "dataTable", ",", "options", ":", "options", ",", "containerId", ":", "containerId", "}", ")", ";", "return", "wrapper", ";", "}" ]
Initialize the wrapper @link https://developers.google.com/chart/interactive/docs/reference#chartwrapper-class @return object
[ "Initialize", "the", "wrapper" ]
f8bb783dd2476d854389678d0abe45b35ad8014b
https://github.com/haydenbbickerton/vue-charts/blob/f8bb783dd2476d854389678d0abe45b35ad8014b/dist/vue-charts.common.js#L290-L299
20,801
haydenbbickerton/vue-charts
dist/vue-charts.common.js
buildChart
function buildChart() { var self = this; // If dataTable isn't set, build it var dataTable = _.isEmpty(self.dataTable) ? self.buildDataTable() : self.dataTable; self.wrapper = self.buildWrapper(self.chartType, dataTable, self.options, self.chartId); // Set the datatable on this instance self.dataTable = self.wrapper.getDataTable(); // After chart is built, set it on this instance and resolve the promise. google.visualization.events.addOneTimeListener(self.wrapper, 'ready', function () { self.chart = self.wrapper.getChart(); chartDeferred.resolve(); }); }
javascript
function buildChart() { var self = this; // If dataTable isn't set, build it var dataTable = _.isEmpty(self.dataTable) ? self.buildDataTable() : self.dataTable; self.wrapper = self.buildWrapper(self.chartType, dataTable, self.options, self.chartId); // Set the datatable on this instance self.dataTable = self.wrapper.getDataTable(); // After chart is built, set it on this instance and resolve the promise. google.visualization.events.addOneTimeListener(self.wrapper, 'ready', function () { self.chart = self.wrapper.getChart(); chartDeferred.resolve(); }); }
[ "function", "buildChart", "(", ")", "{", "var", "self", "=", "this", ";", "// If dataTable isn't set, build it", "var", "dataTable", "=", "_", ".", "isEmpty", "(", "self", ".", "dataTable", ")", "?", "self", ".", "buildDataTable", "(", ")", ":", "self", ".", "dataTable", ";", "self", ".", "wrapper", "=", "self", ".", "buildWrapper", "(", "self", ".", "chartType", ",", "dataTable", ",", "self", ".", "options", ",", "self", ".", "chartId", ")", ";", "// Set the datatable on this instance", "self", ".", "dataTable", "=", "self", ".", "wrapper", ".", "getDataTable", "(", ")", ";", "// After chart is built, set it on this instance and resolve the promise.", "google", ".", "visualization", ".", "events", ".", "addOneTimeListener", "(", "self", ".", "wrapper", ",", "'ready'", ",", "function", "(", ")", "{", "self", ".", "chart", "=", "self", ".", "wrapper", ".", "getChart", "(", ")", ";", "chartDeferred", ".", "resolve", "(", ")", ";", "}", ")", ";", "}" ]
Build the chart. @return void
[ "Build", "the", "chart", "." ]
f8bb783dd2476d854389678d0abe45b35ad8014b
https://github.com/haydenbbickerton/vue-charts/blob/f8bb783dd2476d854389678d0abe45b35ad8014b/dist/vue-charts.common.js#L307-L323
20,802
haydenbbickerton/vue-charts
dist/vue-charts.common.js
drawChart
function drawChart() { var self = this; // We don't have any (usable) data, or we don't have columns. We can't draw a chart without those. if (!_.isEmpty(self.rows) && !_.isObjectLike(self.rows) || _.isEmpty(self.columns)) { return; } if (_.isNull(self.chart)) { // We haven't built the chart yet, so JUST. DO. IT! self.buildChart(); } else { // Chart already exists, just update the data self.updateDataTable(); } // Chart has been built/Data has been updated, draw the chart. self.wrapper.draw(); // Return promise. Resolves when chart finishes loading. return chartDeferred.promise; }
javascript
function drawChart() { var self = this; // We don't have any (usable) data, or we don't have columns. We can't draw a chart without those. if (!_.isEmpty(self.rows) && !_.isObjectLike(self.rows) || _.isEmpty(self.columns)) { return; } if (_.isNull(self.chart)) { // We haven't built the chart yet, so JUST. DO. IT! self.buildChart(); } else { // Chart already exists, just update the data self.updateDataTable(); } // Chart has been built/Data has been updated, draw the chart. self.wrapper.draw(); // Return promise. Resolves when chart finishes loading. return chartDeferred.promise; }
[ "function", "drawChart", "(", ")", "{", "var", "self", "=", "this", ";", "// We don't have any (usable) data, or we don't have columns. We can't draw a chart without those.", "if", "(", "!", "_", ".", "isEmpty", "(", "self", ".", "rows", ")", "&&", "!", "_", ".", "isObjectLike", "(", "self", ".", "rows", ")", "||", "_", ".", "isEmpty", "(", "self", ".", "columns", ")", ")", "{", "return", ";", "}", "if", "(", "_", ".", "isNull", "(", "self", ".", "chart", ")", ")", "{", "// We haven't built the chart yet, so JUST. DO. IT!", "self", ".", "buildChart", "(", ")", ";", "}", "else", "{", "// Chart already exists, just update the data", "self", ".", "updateDataTable", "(", ")", ";", "}", "// Chart has been built/Data has been updated, draw the chart.", "self", ".", "wrapper", ".", "draw", "(", ")", ";", "// Return promise. Resolves when chart finishes loading.", "return", "chartDeferred", ".", "promise", ";", "}" ]
Draw the chart. @return Promise
[ "Draw", "the", "chart", "." ]
f8bb783dd2476d854389678d0abe45b35ad8014b
https://github.com/haydenbbickerton/vue-charts/blob/f8bb783dd2476d854389678d0abe45b35ad8014b/dist/vue-charts.common.js#L331-L352
20,803
watson-developer-cloud/node-red-node-watson
services/personality_insights/v3.js
prepareParams
function prepareParams(msg, config) { var params = {}, inputlang = config.inputlang ? config.inputlang : 'en', outputlang = config.outputlang ? config.outputlang : 'en'; if (msg.piparams) { if (msg.piparams.inputlanguage && -1 < VALID_INPUT_LANGUAGES.indexOf(msg.piparams.inputlanguage)) { inputlang = msg.piparams.inputlanguage; } if (msg.piparams.responselanguage && -1 < VALID_RESPONSE_LANGUAGES.indexOf(msg.piparams.responselanguage)) { outputlang = msg.piparams.responselanguage; } } params = { content: msg.payload, consumption_preferences: config.consumption ? config.consumption : false, raw_scores: config.rawscores ? config.rawscores : false, headers: { 'content-language': inputlang, 'accept-language': outputlang, 'accept': 'application/json' } }; if ('string' === typeof msg.payload) { params.content_type = 'text/plain'; } else { params.content_type = 'application/json'; } return Promise.resolve(params); }
javascript
function prepareParams(msg, config) { var params = {}, inputlang = config.inputlang ? config.inputlang : 'en', outputlang = config.outputlang ? config.outputlang : 'en'; if (msg.piparams) { if (msg.piparams.inputlanguage && -1 < VALID_INPUT_LANGUAGES.indexOf(msg.piparams.inputlanguage)) { inputlang = msg.piparams.inputlanguage; } if (msg.piparams.responselanguage && -1 < VALID_RESPONSE_LANGUAGES.indexOf(msg.piparams.responselanguage)) { outputlang = msg.piparams.responselanguage; } } params = { content: msg.payload, consumption_preferences: config.consumption ? config.consumption : false, raw_scores: config.rawscores ? config.rawscores : false, headers: { 'content-language': inputlang, 'accept-language': outputlang, 'accept': 'application/json' } }; if ('string' === typeof msg.payload) { params.content_type = 'text/plain'; } else { params.content_type = 'application/json'; } return Promise.resolve(params); }
[ "function", "prepareParams", "(", "msg", ",", "config", ")", "{", "var", "params", "=", "{", "}", ",", "inputlang", "=", "config", ".", "inputlang", "?", "config", ".", "inputlang", ":", "'en'", ",", "outputlang", "=", "config", ".", "outputlang", "?", "config", ".", "outputlang", ":", "'en'", ";", "if", "(", "msg", ".", "piparams", ")", "{", "if", "(", "msg", ".", "piparams", ".", "inputlanguage", "&&", "-", "1", "<", "VALID_INPUT_LANGUAGES", ".", "indexOf", "(", "msg", ".", "piparams", ".", "inputlanguage", ")", ")", "{", "inputlang", "=", "msg", ".", "piparams", ".", "inputlanguage", ";", "}", "if", "(", "msg", ".", "piparams", ".", "responselanguage", "&&", "-", "1", "<", "VALID_RESPONSE_LANGUAGES", ".", "indexOf", "(", "msg", ".", "piparams", ".", "responselanguage", ")", ")", "{", "outputlang", "=", "msg", ".", "piparams", ".", "responselanguage", ";", "}", "}", "params", "=", "{", "content", ":", "msg", ".", "payload", ",", "consumption_preferences", ":", "config", ".", "consumption", "?", "config", ".", "consumption", ":", "false", ",", "raw_scores", ":", "config", ".", "rawscores", "?", "config", ".", "rawscores", ":", "false", ",", "headers", ":", "{", "'content-language'", ":", "inputlang", ",", "'accept-language'", ":", "outputlang", ",", "'accept'", ":", "'application/json'", "}", "}", ";", "if", "(", "'string'", "===", "typeof", "msg", ".", "payload", ")", "{", "params", ".", "content_type", "=", "'text/plain'", ";", "}", "else", "{", "params", ".", "content_type", "=", "'application/json'", ";", "}", "return", "Promise", ".", "resolve", "(", "params", ")", ";", "}" ]
This function prepares the params object for the call to Personality Insights
[ "This", "function", "prepares", "the", "params", "object", "for", "the", "call", "to", "Personality", "Insights" ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/personality_insights/v3.js#L93-L127
20,804
watson-developer-cloud/node-red-node-watson
services/personality_insights/v3.js
Node
function Node(config) { RED.nodes.createNode(this,config); var node = this, message = ''; this.on('input', function (msg) { node.status({}); payloadCheck(msg) .then(function(){ return wordcountCheck(msg, config); }) .then(function(){ return credentialsCheck(node); }) .then(function(){ return setEndPoint(config); }) .then(function(){ return prepareParams(msg, config); }) .then(function(params){ node.status({fill:'blue', shape:'dot', text:'requesting'}); return executeService(msg, params); }) .then(function(){ node.status({}); node.send(msg); }) .catch(function(err){ payloadutils.reportError(node, msg, err); node.send(msg); }); }); }
javascript
function Node(config) { RED.nodes.createNode(this,config); var node = this, message = ''; this.on('input', function (msg) { node.status({}); payloadCheck(msg) .then(function(){ return wordcountCheck(msg, config); }) .then(function(){ return credentialsCheck(node); }) .then(function(){ return setEndPoint(config); }) .then(function(){ return prepareParams(msg, config); }) .then(function(params){ node.status({fill:'blue', shape:'dot', text:'requesting'}); return executeService(msg, params); }) .then(function(){ node.status({}); node.send(msg); }) .catch(function(err){ payloadutils.reportError(node, msg, err); node.send(msg); }); }); }
[ "function", "Node", "(", "config", ")", "{", "RED", ".", "nodes", ".", "createNode", "(", "this", ",", "config", ")", ";", "var", "node", "=", "this", ",", "message", "=", "''", ";", "this", ".", "on", "(", "'input'", ",", "function", "(", "msg", ")", "{", "node", ".", "status", "(", "{", "}", ")", ";", "payloadCheck", "(", "msg", ")", ".", "then", "(", "function", "(", ")", "{", "return", "wordcountCheck", "(", "msg", ",", "config", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "credentialsCheck", "(", "node", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "setEndPoint", "(", "config", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "prepareParams", "(", "msg", ",", "config", ")", ";", "}", ")", ".", "then", "(", "function", "(", "params", ")", "{", "node", ".", "status", "(", "{", "fill", ":", "'blue'", ",", "shape", ":", "'dot'", ",", "text", ":", "'requesting'", "}", ")", ";", "return", "executeService", "(", "msg", ",", "params", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "node", ".", "status", "(", "{", "}", ")", ";", "node", ".", "send", "(", "msg", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "payloadutils", ".", "reportError", "(", "node", ",", "msg", ",", "err", ")", ";", "node", ".", "send", "(", "msg", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
This is the start of the Node Code. In this case only on input is being processed.
[ "This", "is", "the", "start", "of", "the", "Node", "Code", ".", "In", "this", "case", "only", "on", "input", "is", "being", "processed", "." ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/personality_insights/v3.js#L175-L210
20,805
watson-developer-cloud/node-red-node-watson
services/alchemy_language/v1.js
AlchemyFeatureExtractNode
function AlchemyFeatureExtractNode (config) { RED.nodes.createNode(this, config); var node = this; this.on('input', function (msg) { if (!msg.payload) { this.status({fill:'red', shape:'ring', text:'missing payload'}); var message = 'Missing property: msg.payload'; node.error(message, msg); return; } // If it is present the newly provided user entered key takes precedence over the existing one. apikey = s_apikey || this.credentials.apikey; this.status({}); if (!apikey) { this.status({fill:'red', shape:'ring', text:'missing credentials'}); var message = 'Missing Alchemy API service credentials'; node.error(message, msg); return; } var alchemy_language = watson.alchemy_language( { api_key: apikey } ); // Check which features have been requested. var enabled_features = Object.keys(FEATURES).filter(function (feature) { return config[feature] }); if (!enabled_features.length) { this.status({fill:'red', shape:'ring', text:'no features selected'}); var message = 'AlchemyAPI node must have at least one selected feature.'; node.error(message, msg); return; } var params = buildParams(enabled_features, config, msg); // Splice in the additional options from msg.alchemy_options // eg. The user may have entered msg.alchemy_options = {maxRetrieve: 2}; for (var key in msg.alchemy_options) { params[key] = msg.alchemy_options[key]; } alchemy_language.combined(params, function (err, response) { if (err || response.status === 'ERROR') { node.status({fill:'red', shape:'ring', text:'call to alchmeyapi language service failed'}); console.log('Error:', msg, err); node.error(err, msg); } else { msg.features = {}; //msg.features['all'] = response; Object.keys(FEATURES).forEach(function (feature) { var answer_feature = FEATURES[feature]; msg.features[feature] = response[answer_feature] || {}; }); node.send(msg); } }); }); }
javascript
function AlchemyFeatureExtractNode (config) { RED.nodes.createNode(this, config); var node = this; this.on('input', function (msg) { if (!msg.payload) { this.status({fill:'red', shape:'ring', text:'missing payload'}); var message = 'Missing property: msg.payload'; node.error(message, msg); return; } // If it is present the newly provided user entered key takes precedence over the existing one. apikey = s_apikey || this.credentials.apikey; this.status({}); if (!apikey) { this.status({fill:'red', shape:'ring', text:'missing credentials'}); var message = 'Missing Alchemy API service credentials'; node.error(message, msg); return; } var alchemy_language = watson.alchemy_language( { api_key: apikey } ); // Check which features have been requested. var enabled_features = Object.keys(FEATURES).filter(function (feature) { return config[feature] }); if (!enabled_features.length) { this.status({fill:'red', shape:'ring', text:'no features selected'}); var message = 'AlchemyAPI node must have at least one selected feature.'; node.error(message, msg); return; } var params = buildParams(enabled_features, config, msg); // Splice in the additional options from msg.alchemy_options // eg. The user may have entered msg.alchemy_options = {maxRetrieve: 2}; for (var key in msg.alchemy_options) { params[key] = msg.alchemy_options[key]; } alchemy_language.combined(params, function (err, response) { if (err || response.status === 'ERROR') { node.status({fill:'red', shape:'ring', text:'call to alchmeyapi language service failed'}); console.log('Error:', msg, err); node.error(err, msg); } else { msg.features = {}; //msg.features['all'] = response; Object.keys(FEATURES).forEach(function (feature) { var answer_feature = FEATURES[feature]; msg.features[feature] = response[answer_feature] || {}; }); node.send(msg); } }); }); }
[ "function", "AlchemyFeatureExtractNode", "(", "config", ")", "{", "RED", ".", "nodes", ".", "createNode", "(", "this", ",", "config", ")", ";", "var", "node", "=", "this", ";", "this", ".", "on", "(", "'input'", ",", "function", "(", "msg", ")", "{", "if", "(", "!", "msg", ".", "payload", ")", "{", "this", ".", "status", "(", "{", "fill", ":", "'red'", ",", "shape", ":", "'ring'", ",", "text", ":", "'missing payload'", "}", ")", ";", "var", "message", "=", "'Missing property: msg.payload'", ";", "node", ".", "error", "(", "message", ",", "msg", ")", ";", "return", ";", "}", "// If it is present the newly provided user entered key takes precedence over the existing one.", "apikey", "=", "s_apikey", "||", "this", ".", "credentials", ".", "apikey", ";", "this", ".", "status", "(", "{", "}", ")", ";", "if", "(", "!", "apikey", ")", "{", "this", ".", "status", "(", "{", "fill", ":", "'red'", ",", "shape", ":", "'ring'", ",", "text", ":", "'missing credentials'", "}", ")", ";", "var", "message", "=", "'Missing Alchemy API service credentials'", ";", "node", ".", "error", "(", "message", ",", "msg", ")", ";", "return", ";", "}", "var", "alchemy_language", "=", "watson", ".", "alchemy_language", "(", "{", "api_key", ":", "apikey", "}", ")", ";", "// Check which features have been requested.", "var", "enabled_features", "=", "Object", ".", "keys", "(", "FEATURES", ")", ".", "filter", "(", "function", "(", "feature", ")", "{", "return", "config", "[", "feature", "]", "}", ")", ";", "if", "(", "!", "enabled_features", ".", "length", ")", "{", "this", ".", "status", "(", "{", "fill", ":", "'red'", ",", "shape", ":", "'ring'", ",", "text", ":", "'no features selected'", "}", ")", ";", "var", "message", "=", "'AlchemyAPI node must have at least one selected feature.'", ";", "node", ".", "error", "(", "message", ",", "msg", ")", ";", "return", ";", "}", "var", "params", "=", "buildParams", "(", "enabled_features", ",", "config", ",", "msg", ")", ";", "// Splice in the additional options from msg.alchemy_options", "// eg. The user may have entered msg.alchemy_options = {maxRetrieve: 2};", "for", "(", "var", "key", "in", "msg", ".", "alchemy_options", ")", "{", "params", "[", "key", "]", "=", "msg", ".", "alchemy_options", "[", "key", "]", ";", "}", "alchemy_language", ".", "combined", "(", "params", ",", "function", "(", "err", ",", "response", ")", "{", "if", "(", "err", "||", "response", ".", "status", "===", "'ERROR'", ")", "{", "node", ".", "status", "(", "{", "fill", ":", "'red'", ",", "shape", ":", "'ring'", ",", "text", ":", "'call to alchmeyapi language service failed'", "}", ")", ";", "console", ".", "log", "(", "'Error:'", ",", "msg", ",", "err", ")", ";", "node", ".", "error", "(", "err", ",", "msg", ")", ";", "}", "else", "{", "msg", ".", "features", "=", "{", "}", ";", "//msg.features['all'] = response;", "Object", ".", "keys", "(", "FEATURES", ")", ".", "forEach", "(", "function", "(", "feature", ")", "{", "var", "answer_feature", "=", "FEATURES", "[", "feature", "]", ";", "msg", ".", "features", "[", "feature", "]", "=", "response", "[", "answer_feature", "]", "||", "{", "}", ";", "}", ")", ";", "node", ".", "send", "(", "msg", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
This is the Alchemy Data Node
[ "This", "is", "the", "Alchemy", "Data", "Node" ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/alchemy_language/v1.js#L87-L154
20,806
watson-developer-cloud/node-red-node-watson
services/natural_language_understanding/v1.js
NLUNode
function NLUNode (config) { RED.nodes.createNode(this, config); var node = this; this.on('input', function (msg) { var message = '', options = {}; node.status({}); username = sUsername || this.credentials.username; password = sPassword || this.credentials.password; apikey = sApikey || this.credentials.apikey; endpoint = sEndpoint; if ((!config['default-endpoint']) && config['service-endpoint']) { endpoint = config['service-endpoint']; } initialCheck(username, password, apikey) .then(function(){ return payloadCheck(msg, options); }) .then(function(){ return checkAdditonalMsgOptions(msg, options); }) .then(function(){ return checkFeatureRequest(config, options); }) .then(function(){ return checkFeatureOptions(msg, config, options); }) .then(function(){ return checkNonFeatureOptions(config, options); }) .then(function(){ node.status({fill:'blue', shape:'dot', text:'requesting'}); return invokeService(options); }) .then(function(data){ msg.features = data; node.send(msg); node.status({}); }) .catch(function(err){ reportError(node,msg,err); }); }); }
javascript
function NLUNode (config) { RED.nodes.createNode(this, config); var node = this; this.on('input', function (msg) { var message = '', options = {}; node.status({}); username = sUsername || this.credentials.username; password = sPassword || this.credentials.password; apikey = sApikey || this.credentials.apikey; endpoint = sEndpoint; if ((!config['default-endpoint']) && config['service-endpoint']) { endpoint = config['service-endpoint']; } initialCheck(username, password, apikey) .then(function(){ return payloadCheck(msg, options); }) .then(function(){ return checkAdditonalMsgOptions(msg, options); }) .then(function(){ return checkFeatureRequest(config, options); }) .then(function(){ return checkFeatureOptions(msg, config, options); }) .then(function(){ return checkNonFeatureOptions(config, options); }) .then(function(){ node.status({fill:'blue', shape:'dot', text:'requesting'}); return invokeService(options); }) .then(function(data){ msg.features = data; node.send(msg); node.status({}); }) .catch(function(err){ reportError(node,msg,err); }); }); }
[ "function", "NLUNode", "(", "config", ")", "{", "RED", ".", "nodes", ".", "createNode", "(", "this", ",", "config", ")", ";", "var", "node", "=", "this", ";", "this", ".", "on", "(", "'input'", ",", "function", "(", "msg", ")", "{", "var", "message", "=", "''", ",", "options", "=", "{", "}", ";", "node", ".", "status", "(", "{", "}", ")", ";", "username", "=", "sUsername", "||", "this", ".", "credentials", ".", "username", ";", "password", "=", "sPassword", "||", "this", ".", "credentials", ".", "password", ";", "apikey", "=", "sApikey", "||", "this", ".", "credentials", ".", "apikey", ";", "endpoint", "=", "sEndpoint", ";", "if", "(", "(", "!", "config", "[", "'default-endpoint'", "]", ")", "&&", "config", "[", "'service-endpoint'", "]", ")", "{", "endpoint", "=", "config", "[", "'service-endpoint'", "]", ";", "}", "initialCheck", "(", "username", ",", "password", ",", "apikey", ")", ".", "then", "(", "function", "(", ")", "{", "return", "payloadCheck", "(", "msg", ",", "options", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "checkAdditonalMsgOptions", "(", "msg", ",", "options", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "checkFeatureRequest", "(", "config", ",", "options", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "checkFeatureOptions", "(", "msg", ",", "config", ",", "options", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "checkNonFeatureOptions", "(", "config", ",", "options", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "node", ".", "status", "(", "{", "fill", ":", "'blue'", ",", "shape", ":", "'dot'", ",", "text", ":", "'requesting'", "}", ")", ";", "return", "invokeService", "(", "options", ")", ";", "}", ")", ".", "then", "(", "function", "(", "data", ")", "{", "msg", ".", "features", "=", "data", ";", "node", ".", "send", "(", "msg", ")", ";", "node", ".", "status", "(", "{", "}", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "reportError", "(", "node", ",", "msg", ",", "err", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
This is the Natural Language Understanding Node
[ "This", "is", "the", "Natural", "Language", "Understanding", "Node" ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/natural_language_understanding/v1.js#L266-L315
20,807
watson-developer-cloud/node-red-node-watson
services/speech_to_text/v1.js
overrideCheck
function overrideCheck(msg) { if (msg.srclang){ var langCode = payloadutils.langTransToSTTFormat(msg.srclang); config.lang = langCode; } return Promise.resolve(); }
javascript
function overrideCheck(msg) { if (msg.srclang){ var langCode = payloadutils.langTransToSTTFormat(msg.srclang); config.lang = langCode; } return Promise.resolve(); }
[ "function", "overrideCheck", "(", "msg", ")", "{", "if", "(", "msg", ".", "srclang", ")", "{", "var", "langCode", "=", "payloadutils", ".", "langTransToSTTFormat", "(", "msg", ".", "srclang", ")", ";", "config", ".", "lang", "=", "langCode", ";", "}", "return", "Promise", ".", "resolve", "(", ")", ";", "}" ]
Allow the language to be overridden through msg.srclang, no check for validity
[ "Allow", "the", "language", "to", "be", "overridden", "through", "msg", ".", "srclang", "no", "check", "for", "validity" ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/speech_to_text/v1.js#L140-L146
20,808
watson-developer-cloud/node-red-node-watson
services/speech_to_text/v1.js
payloadNonStreamCheck
function payloadNonStreamCheck(msg) { var message = ''; // The input comes in on msg.payload, and can either be an audio file or a string // representing a URL. if (!msg.payload instanceof Buffer || !typeof msg.payload === 'string') { message = 'Invalid property: msg.payload, can only be a URL or a Buffer.'; } else if (!(msg.payload instanceof Buffer)) { // This check is repeated just before the call to the service, but // its also performed here as a double check. if (typeof msg.payload === 'string' && !payloadutils.urlCheck(msg.payload)) { message = 'Invalid URL.'; } } else { var f = 'txt', ft = ''; ft = fileType(msg.payload); if (ft) { f = ft.ext; } switch (f) { case 'wav': case 'flac': case 'ogg': case 'mp3': case 'mpeg': break; default: if (! ft.mime.toLowerCase().includes('audio')) { message = 'Audio format (' + f + ') not supported, must be encoded as WAV, MP3, FLAC or OGG.'; } } } if (message) { return Promise.reject(message); } return Promise.resolve(); }
javascript
function payloadNonStreamCheck(msg) { var message = ''; // The input comes in on msg.payload, and can either be an audio file or a string // representing a URL. if (!msg.payload instanceof Buffer || !typeof msg.payload === 'string') { message = 'Invalid property: msg.payload, can only be a URL or a Buffer.'; } else if (!(msg.payload instanceof Buffer)) { // This check is repeated just before the call to the service, but // its also performed here as a double check. if (typeof msg.payload === 'string' && !payloadutils.urlCheck(msg.payload)) { message = 'Invalid URL.'; } } else { var f = 'txt', ft = ''; ft = fileType(msg.payload); if (ft) { f = ft.ext; } switch (f) { case 'wav': case 'flac': case 'ogg': case 'mp3': case 'mpeg': break; default: if (! ft.mime.toLowerCase().includes('audio')) { message = 'Audio format (' + f + ') not supported, must be encoded as WAV, MP3, FLAC or OGG.'; } } } if (message) { return Promise.reject(message); } return Promise.resolve(); }
[ "function", "payloadNonStreamCheck", "(", "msg", ")", "{", "var", "message", "=", "''", ";", "// The input comes in on msg.payload, and can either be an audio file or a string", "// representing a URL.", "if", "(", "!", "msg", ".", "payload", "instanceof", "Buffer", "||", "!", "typeof", "msg", ".", "payload", "===", "'string'", ")", "{", "message", "=", "'Invalid property: msg.payload, can only be a URL or a Buffer.'", ";", "}", "else", "if", "(", "!", "(", "msg", ".", "payload", "instanceof", "Buffer", ")", ")", "{", "// This check is repeated just before the call to the service, but", "// its also performed here as a double check.", "if", "(", "typeof", "msg", ".", "payload", "===", "'string'", "&&", "!", "payloadutils", ".", "urlCheck", "(", "msg", ".", "payload", ")", ")", "{", "message", "=", "'Invalid URL.'", ";", "}", "}", "else", "{", "var", "f", "=", "'txt'", ",", "ft", "=", "''", ";", "ft", "=", "fileType", "(", "msg", ".", "payload", ")", ";", "if", "(", "ft", ")", "{", "f", "=", "ft", ".", "ext", ";", "}", "switch", "(", "f", ")", "{", "case", "'wav'", ":", "case", "'flac'", ":", "case", "'ogg'", ":", "case", "'mp3'", ":", "case", "'mpeg'", ":", "break", ";", "default", ":", "if", "(", "!", "ft", ".", "mime", ".", "toLowerCase", "(", ")", ".", "includes", "(", "'audio'", ")", ")", "{", "message", "=", "'Audio format ('", "+", "f", "+", "') not supported, must be encoded as WAV, MP3, FLAC or OGG.'", ";", "}", "}", "}", "if", "(", "message", ")", "{", "return", "Promise", ".", "reject", "(", "message", ")", ";", "}", "return", "Promise", ".", "resolve", "(", ")", ";", "}" ]
Input is a standard msg.payload
[ "Input", "is", "a", "standard", "msg", ".", "payload" ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/speech_to_text/v1.js#L150-L188
20,809
watson-developer-cloud/node-red-node-watson
services/speech_to_text/v1.js
processInputStream
function processInputStream(msg) { var tmp = msg.payload; if ('string' === typeof msg.payload) { msg.payload = JSON.parse(tmp); } if (msg.payload.action) { if ('start' === msg.payload.action) { startPacket = msg.payload; } } else { msg.payload = { 'action' : 'data', 'data' : tmp }; } return Promise.resolve(msg.payload); }
javascript
function processInputStream(msg) { var tmp = msg.payload; if ('string' === typeof msg.payload) { msg.payload = JSON.parse(tmp); } if (msg.payload.action) { if ('start' === msg.payload.action) { startPacket = msg.payload; } } else { msg.payload = { 'action' : 'data', 'data' : tmp }; } return Promise.resolve(msg.payload); }
[ "function", "processInputStream", "(", "msg", ")", "{", "var", "tmp", "=", "msg", ".", "payload", ";", "if", "(", "'string'", "===", "typeof", "msg", ".", "payload", ")", "{", "msg", ".", "payload", "=", "JSON", ".", "parse", "(", "tmp", ")", ";", "}", "if", "(", "msg", ".", "payload", ".", "action", ")", "{", "if", "(", "'start'", "===", "msg", ".", "payload", ".", "action", ")", "{", "startPacket", "=", "msg", ".", "payload", ";", "}", "}", "else", "{", "msg", ".", "payload", "=", "{", "'action'", ":", "'data'", ",", "'data'", ":", "tmp", "}", ";", "}", "return", "Promise", ".", "resolve", "(", "msg", ".", "payload", ")", ";", "}" ]
The input is from a websocket stream in Node-RED. expect action of 'start' or 'stop' or a data blob if its a blob then its going to be audio.
[ "The", "input", "is", "from", "a", "websocket", "stream", "in", "Node", "-", "RED", ".", "expect", "action", "of", "start", "or", "stop", "or", "a", "data", "blob", "if", "its", "a", "blob", "then", "its", "going", "to", "be", "audio", "." ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/speech_to_text/v1.js#L260-L275
20,810
watson-developer-cloud/node-red-node-watson
services/speech_to_text/v1.js
connectIfNeeded
function connectIfNeeded() { // console.log('re-establishing the connect'); websocket = null; socketCreationInProcess = false; // The token may have expired so test for it. getToken(determineService()) .then(() => { return processSTTSocketStart(false); }) .then(() => { //return Promise.resolve(); return; }) .catch((err) => { //return Promise.resolve(); return; }); }
javascript
function connectIfNeeded() { // console.log('re-establishing the connect'); websocket = null; socketCreationInProcess = false; // The token may have expired so test for it. getToken(determineService()) .then(() => { return processSTTSocketStart(false); }) .then(() => { //return Promise.resolve(); return; }) .catch((err) => { //return Promise.resolve(); return; }); }
[ "function", "connectIfNeeded", "(", ")", "{", "// console.log('re-establishing the connect');", "websocket", "=", "null", ";", "socketCreationInProcess", "=", "false", ";", "// The token may have expired so test for it.", "getToken", "(", "determineService", "(", ")", ")", ".", "then", "(", "(", ")", "=>", "{", "return", "processSTTSocketStart", "(", "false", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "//return Promise.resolve();", "return", ";", "}", ")", ".", "catch", "(", "(", "err", ")", "=>", "{", "//return Promise.resolve();", "return", ";", "}", ")", ";", "}" ]
If we are going to connect to STT through websockets then its going to disconnect or timeout, so need to handle that occurrence.
[ "If", "we", "are", "going", "to", "connect", "to", "STT", "through", "websockets", "then", "its", "going", "to", "disconnect", "or", "timeout", "so", "need", "to", "handle", "that", "occurrence", "." ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/speech_to_text/v1.js#L589-L607
20,811
watson-developer-cloud/node-red-node-watson
utilities/service-utils.js
function(serviceName, returnBoolean, alchemyRegex) { var regex = alchemyRegex ? RegExp('(http|https)(://)('+serviceName+').*') : RegExp('(http|https)(://)([^\/]+)(/)('+serviceName+').*'); var services = appEnv.getServices(); for (var service in services) { if (services[service].hasOwnProperty('credentials')) { if (services[service].credentials.hasOwnProperty('url')){ if (services[service].credentials.url.search(regex) === 0){ return returnBoolean ? true : services[service].credentials; } } } } return returnBoolean ? false : null; }
javascript
function(serviceName, returnBoolean, alchemyRegex) { var regex = alchemyRegex ? RegExp('(http|https)(://)('+serviceName+').*') : RegExp('(http|https)(://)([^\/]+)(/)('+serviceName+').*'); var services = appEnv.getServices(); for (var service in services) { if (services[service].hasOwnProperty('credentials')) { if (services[service].credentials.hasOwnProperty('url')){ if (services[service].credentials.url.search(regex) === 0){ return returnBoolean ? true : services[service].credentials; } } } } return returnBoolean ? false : null; }
[ "function", "(", "serviceName", ",", "returnBoolean", ",", "alchemyRegex", ")", "{", "var", "regex", "=", "alchemyRegex", "?", "RegExp", "(", "'(http|https)(://)('", "+", "serviceName", "+", "').*'", ")", ":", "RegExp", "(", "'(http|https)(://)([^\\/]+)(/)('", "+", "serviceName", "+", "').*'", ")", ";", "var", "services", "=", "appEnv", ".", "getServices", "(", ")", ";", "for", "(", "var", "service", "in", "services", ")", "{", "if", "(", "services", "[", "service", "]", ".", "hasOwnProperty", "(", "'credentials'", ")", ")", "{", "if", "(", "services", "[", "service", "]", ".", "credentials", ".", "hasOwnProperty", "(", "'url'", ")", ")", "{", "if", "(", "services", "[", "service", "]", ".", "credentials", ".", "url", ".", "search", "(", "regex", ")", "===", "0", ")", "{", "return", "returnBoolean", "?", "true", ":", "services", "[", "service", "]", ".", "credentials", ";", "}", "}", "}", "}", "return", "returnBoolean", "?", "false", ":", "null", ";", "}" ]
function to determine if WDC service is bound. A simple check on name may fail because of duplicate usage. This function verifies that the url associated with the service, contains the matched input value, hence reducing the chances of a false match.
[ "function", "to", "determine", "if", "WDC", "service", "is", "bound", ".", "A", "simple", "check", "on", "name", "may", "fail", "because", "of", "duplicate", "usage", ".", "This", "function", "verifies", "that", "the", "url", "associated", "with", "the", "service", "contains", "the", "matched", "input", "value", "hence", "reducing", "the", "chances", "of", "a", "false", "match", "." ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/utilities/service-utils.js#L25-L42
20,812
watson-developer-cloud/node-red-node-watson
services/tone_analyzer/v3.js
function(credentials) { var taSettings = {}; username = sUsername || credentials.username; password = sPassword || credentials.password; apikey = sApikey || credentials.apikey; if (apikey) { taSettings.iam_apikey = apikey; } else if (username && password) { taSettings.username = username; taSettings.password = password; } else { taSettings = null; } return taSettings; }
javascript
function(credentials) { var taSettings = {}; username = sUsername || credentials.username; password = sPassword || credentials.password; apikey = sApikey || credentials.apikey; if (apikey) { taSettings.iam_apikey = apikey; } else if (username && password) { taSettings.username = username; taSettings.password = password; } else { taSettings = null; } return taSettings; }
[ "function", "(", "credentials", ")", "{", "var", "taSettings", "=", "{", "}", ";", "username", "=", "sUsername", "||", "credentials", ".", "username", ";", "password", "=", "sPassword", "||", "credentials", ".", "password", ";", "apikey", "=", "sApikey", "||", "credentials", ".", "apikey", ";", "if", "(", "apikey", ")", "{", "taSettings", ".", "iam_apikey", "=", "apikey", ";", "}", "else", "if", "(", "username", "&&", "password", ")", "{", "taSettings", ".", "username", "=", "username", ";", "taSettings", ".", "password", "=", "password", ";", "}", "else", "{", "taSettings", "=", "null", ";", "}", "return", "taSettings", ";", "}" ]
Check that the credentials have been provided Credentials are needed for each the service.
[ "Check", "that", "the", "credentials", "have", "been", "provided", "Credentials", "are", "needed", "for", "each", "the", "service", "." ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/tone_analyzer/v3.js#L55-L72
20,813
watson-developer-cloud/node-red-node-watson
services/tone_analyzer/v3.js
function(msg, node) { var message = null, taSettings = null; taSettings = checkCreds(node.credentials); if (!taSettings) { message = 'Missing Tone Analyzer service credentials'; } else if (msg.payload) { message = toneutils.checkPayload(msg.payload); } else { message = 'Missing property: msg.payload'; } if (message) { return Promise.reject(message); } else { return Promise.resolve(taSettings); } }
javascript
function(msg, node) { var message = null, taSettings = null; taSettings = checkCreds(node.credentials); if (!taSettings) { message = 'Missing Tone Analyzer service credentials'; } else if (msg.payload) { message = toneutils.checkPayload(msg.payload); } else { message = 'Missing property: msg.payload'; } if (message) { return Promise.reject(message); } else { return Promise.resolve(taSettings); } }
[ "function", "(", "msg", ",", "node", ")", "{", "var", "message", "=", "null", ",", "taSettings", "=", "null", ";", "taSettings", "=", "checkCreds", "(", "node", ".", "credentials", ")", ";", "if", "(", "!", "taSettings", ")", "{", "message", "=", "'Missing Tone Analyzer service credentials'", ";", "}", "else", "if", "(", "msg", ".", "payload", ")", "{", "message", "=", "toneutils", ".", "checkPayload", "(", "msg", ".", "payload", ")", ";", "}", "else", "{", "message", "=", "'Missing property: msg.payload'", ";", "}", "if", "(", "message", ")", "{", "return", "Promise", ".", "reject", "(", "message", ")", ";", "}", "else", "{", "return", "Promise", ".", "resolve", "(", "taSettings", ")", ";", "}", "}" ]
Function that checks the configuration to make sure that credentials, payload and options have been provied in the correct format.
[ "Function", "that", "checks", "the", "configuration", "to", "make", "sure", "that", "credentials", "payload", "and", "options", "have", "been", "provied", "in", "the", "correct", "format", "." ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/tone_analyzer/v3.js#L77-L96
20,814
watson-developer-cloud/node-red-node-watson
services/tone_analyzer/v3.js
function(msg, config, node) { checkConfiguration(msg, node) .then(function(settings) { var options = toneutils.parseOptions(msg, config); options = toneutils.parseLanguage(msg, config, options); node.status({fill:'blue', shape:'dot', text:'requesting'}); return invokeService(config, options, settings); }) .then(function(data){ node.status({}) msg.response = data; node.send(msg); node.status({}); }) .catch(function(err){ payloadutils.reportError(node,msg,err); node.send(msg); }); }
javascript
function(msg, config, node) { checkConfiguration(msg, node) .then(function(settings) { var options = toneutils.parseOptions(msg, config); options = toneutils.parseLanguage(msg, config, options); node.status({fill:'blue', shape:'dot', text:'requesting'}); return invokeService(config, options, settings); }) .then(function(data){ node.status({}) msg.response = data; node.send(msg); node.status({}); }) .catch(function(err){ payloadutils.reportError(node,msg,err); node.send(msg); }); }
[ "function", "(", "msg", ",", "config", ",", "node", ")", "{", "checkConfiguration", "(", "msg", ",", "node", ")", ".", "then", "(", "function", "(", "settings", ")", "{", "var", "options", "=", "toneutils", ".", "parseOptions", "(", "msg", ",", "config", ")", ";", "options", "=", "toneutils", ".", "parseLanguage", "(", "msg", ",", "config", ",", "options", ")", ";", "node", ".", "status", "(", "{", "fill", ":", "'blue'", ",", "shape", ":", "'dot'", ",", "text", ":", "'requesting'", "}", ")", ";", "return", "invokeService", "(", "config", ",", "options", ",", "settings", ")", ";", "}", ")", ".", "then", "(", "function", "(", "data", ")", "{", "node", ".", "status", "(", "{", "}", ")", "msg", ".", "response", "=", "data", ";", "node", ".", "send", "(", "msg", ")", ";", "node", ".", "status", "(", "{", "}", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "payloadutils", ".", "reportError", "(", "node", ",", "msg", ",", "err", ")", ";", "node", ".", "send", "(", "msg", ")", ";", "}", ")", ";", "}" ]
function when the node recieves input inside a flow. Configuration is first checked before the service is invoked.
[ "function", "when", "the", "node", "recieves", "input", "inside", "a", "flow", ".", "Configuration", "is", "first", "checked", "before", "the", "service", "is", "invoked", "." ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/tone_analyzer/v3.js#L153-L171
20,815
watson-developer-cloud/node-red-node-watson
services/tone_analyzer/v3.js
Node
function Node (config) { RED.nodes.createNode(this, config); var node = this; // Invoked when the node has received an input as part of a flow. this.on('input', function (msg) { processOnInput(msg, config, node); }); }
javascript
function Node (config) { RED.nodes.createNode(this, config); var node = this; // Invoked when the node has received an input as part of a flow. this.on('input', function (msg) { processOnInput(msg, config, node); }); }
[ "function", "Node", "(", "config", ")", "{", "RED", ".", "nodes", ".", "createNode", "(", "this", ",", "config", ")", ";", "var", "node", "=", "this", ";", "// Invoked when the node has received an input as part of a flow.", "this", ".", "on", "(", "'input'", ",", "function", "(", "msg", ")", "{", "processOnInput", "(", "msg", ",", "config", ",", "node", ")", ";", "}", ")", ";", "}" ]
This is the Tone Analyzer Node.
[ "This", "is", "the", "Tone", "Analyzer", "Node", "." ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/tone_analyzer/v3.js#L175-L183
20,816
watson-developer-cloud/node-red-node-watson
services/alchemy_vision/v1.js
performAction
function performAction(params, feature, cbdone, cbcleanup) { var alchemy_vision = watson.alchemy_vision( { api_key: apikey } ); if (feature == 'imageFaces') { alchemy_vision.recognizeFaces(params, cbdone); } else if (feature == 'imageLink') { alchemy_vision.getImageLinks(params, cbdone); } else if (feature == 'imageKeywords') { alchemy_vision.getImageKeywords(params, cbdone); } else if (feature == 'imageText') { alchemy_vision.getImageSceneText(params, cbdone); } if (cbcleanup) cbcleanup(); }
javascript
function performAction(params, feature, cbdone, cbcleanup) { var alchemy_vision = watson.alchemy_vision( { api_key: apikey } ); if (feature == 'imageFaces') { alchemy_vision.recognizeFaces(params, cbdone); } else if (feature == 'imageLink') { alchemy_vision.getImageLinks(params, cbdone); } else if (feature == 'imageKeywords') { alchemy_vision.getImageKeywords(params, cbdone); } else if (feature == 'imageText') { alchemy_vision.getImageSceneText(params, cbdone); } if (cbcleanup) cbcleanup(); }
[ "function", "performAction", "(", "params", ",", "feature", ",", "cbdone", ",", "cbcleanup", ")", "{", "var", "alchemy_vision", "=", "watson", ".", "alchemy_vision", "(", "{", "api_key", ":", "apikey", "}", ")", ";", "if", "(", "feature", "==", "'imageFaces'", ")", "{", "alchemy_vision", ".", "recognizeFaces", "(", "params", ",", "cbdone", ")", ";", "}", "else", "if", "(", "feature", "==", "'imageLink'", ")", "{", "alchemy_vision", ".", "getImageLinks", "(", "params", ",", "cbdone", ")", ";", "}", "else", "if", "(", "feature", "==", "'imageKeywords'", ")", "{", "alchemy_vision", ".", "getImageKeywords", "(", "params", ",", "cbdone", ")", ";", "}", "else", "if", "(", "feature", "==", "'imageText'", ")", "{", "alchemy_vision", ".", "getImageSceneText", "(", "params", ",", "cbdone", ")", ";", "}", "if", "(", "cbcleanup", ")", "cbcleanup", "(", ")", ";", "}" ]
Utility function that performs the alchemy vision call. the cleanup removes the temp storage, and I am not sure whether it should be called here or after alchemy returns and passed control back to cbdone.
[ "Utility", "function", "that", "performs", "the", "alchemy", "vision", "call", ".", "the", "cleanup", "removes", "the", "temp", "storage", "and", "I", "am", "not", "sure", "whether", "it", "should", "be", "called", "here", "or", "after", "alchemy", "returns", "and", "passed", "control", "back", "to", "cbdone", "." ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/alchemy_vision/v1.js#L82-L97
20,817
watson-developer-cloud/node-red-node-watson
services/alchemy_vision/v1.js
function(err, keywords) { if (err || keywords.status === 'ERROR') { node.status({fill:'red', shape:'ring', text:'call to alchmeyapi vision service failed'}); console.log('Error:', msg, err); node.error(err, msg); } else { msg.result = keywords[FEATURE_RESPONSES[feature]] || []; msg.fullresult = {}; msg.fullresult['all'] = keywords; node.send(msg); } }
javascript
function(err, keywords) { if (err || keywords.status === 'ERROR') { node.status({fill:'red', shape:'ring', text:'call to alchmeyapi vision service failed'}); console.log('Error:', msg, err); node.error(err, msg); } else { msg.result = keywords[FEATURE_RESPONSES[feature]] || []; msg.fullresult = {}; msg.fullresult['all'] = keywords; node.send(msg); } }
[ "function", "(", "err", ",", "keywords", ")", "{", "if", "(", "err", "||", "keywords", ".", "status", "===", "'ERROR'", ")", "{", "node", ".", "status", "(", "{", "fill", ":", "'red'", ",", "shape", ":", "'ring'", ",", "text", ":", "'call to alchmeyapi vision service failed'", "}", ")", ";", "console", ".", "log", "(", "'Error:'", ",", "msg", ",", "err", ")", ";", "node", ".", "error", "(", "err", ",", "msg", ")", ";", "}", "else", "{", "msg", ".", "result", "=", "keywords", "[", "FEATURE_RESPONSES", "[", "feature", "]", "]", "||", "[", "]", ";", "msg", ".", "fullresult", "=", "{", "}", ";", "msg", ".", "fullresult", "[", "'all'", "]", "=", "keywords", ";", "node", ".", "send", "(", "msg", ")", ";", "}", "}" ]
This is the callback after the call to the alchemy service. Set up as a var within this scope, so it has access to node, msg etc. in preparation for the Alchemy service action
[ "This", "is", "the", "callback", "after", "the", "call", "to", "the", "alchemy", "service", ".", "Set", "up", "as", "a", "var", "within", "this", "scope", "so", "it", "has", "access", "to", "node", "msg", "etc", ".", "in", "preparation", "for", "the", "Alchemy", "service", "action" ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/alchemy_vision/v1.js#L137-L149
20,818
watson-developer-cloud/node-red-node-watson
services/assistant/v1-workspace-manager.js
executeListExamples
function executeListExamples(node, conv, params, msg) { var p = new Promise(function resolver(resolve, reject){ conv.listExamples(params, function (err, response) { if (err) { reject(err); } else { msg['examples'] = response.examples ? response.examples: response; resolve(); } }); }); return p; }
javascript
function executeListExamples(node, conv, params, msg) { var p = new Promise(function resolver(resolve, reject){ conv.listExamples(params, function (err, response) { if (err) { reject(err); } else { msg['examples'] = response.examples ? response.examples: response; resolve(); } }); }); return p; }
[ "function", "executeListExamples", "(", "node", ",", "conv", ",", "params", ",", "msg", ")", "{", "var", "p", "=", "new", "Promise", "(", "function", "resolver", "(", "resolve", ",", "reject", ")", "{", "conv", ".", "listExamples", "(", "params", ",", "function", "(", "err", ",", "response", ")", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "else", "{", "msg", "[", "'examples'", "]", "=", "response", ".", "examples", "?", "response", ".", "examples", ":", "response", ";", "resolve", "(", ")", ";", "}", "}", ")", ";", "}", ")", ";", "return", "p", ";", "}" ]
For now we are not doing anything with the pagination response
[ "For", "now", "we", "are", "not", "doing", "anything", "with", "the", "pagination", "response" ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/assistant/v1-workspace-manager.js#L204-L217
20,819
watson-developer-cloud/node-red-node-watson
services/assistant/v1-workspace-manager.js
buildParams
function buildParams(msg, method, config, params) { var p = buildWorkspaceParams(msg, method, config, params) .then(function(){ return buildIntentParams(msg, method, config, params); }) .then(function(){ return buildExampleParams(msg, method, config, params); }) .then(function(){ return buildEntityParams(msg, method, config, params); }) .then(function(){ return buildEntityValueParams(msg, method, config, params); }) .then(function(){ return buildDialogParams(msg, method, config, params); }) .then(function(){ return buildExportParams(method, config, params); }); return p; }
javascript
function buildParams(msg, method, config, params) { var p = buildWorkspaceParams(msg, method, config, params) .then(function(){ return buildIntentParams(msg, method, config, params); }) .then(function(){ return buildExampleParams(msg, method, config, params); }) .then(function(){ return buildEntityParams(msg, method, config, params); }) .then(function(){ return buildEntityValueParams(msg, method, config, params); }) .then(function(){ return buildDialogParams(msg, method, config, params); }) .then(function(){ return buildExportParams(method, config, params); }); return p; }
[ "function", "buildParams", "(", "msg", ",", "method", ",", "config", ",", "params", ")", "{", "var", "p", "=", "buildWorkspaceParams", "(", "msg", ",", "method", ",", "config", ",", "params", ")", ".", "then", "(", "function", "(", ")", "{", "return", "buildIntentParams", "(", "msg", ",", "method", ",", "config", ",", "params", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "buildExampleParams", "(", "msg", ",", "method", ",", "config", ",", "params", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "buildEntityParams", "(", "msg", ",", "method", ",", "config", ",", "params", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "buildEntityValueParams", "(", "msg", ",", "method", ",", "config", ",", "params", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "buildDialogParams", "(", "msg", ",", "method", ",", "config", ",", "params", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "buildExportParams", "(", "method", ",", "config", ",", "params", ")", ";", "}", ")", ";", "return", "p", ";", "}" ]
Copy over the appropriate parameters for the required method from the node configuration
[ "Copy", "over", "the", "appropriate", "parameters", "for", "the", "required", "method", "from", "the", "node", "configuration" ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/assistant/v1-workspace-manager.js#L861-L883
20,820
watson-developer-cloud/node-red-node-watson
services/assistant/v1-workspace-manager.js
setWorkspaceParams
function setWorkspaceParams(method, params, workspaceObject) { var workspace_id = null; var stash = {}; if ('object' !== typeof workspaceObject) { return Promise.reject('json content expected as input on payload'); } switch(method) { case 'updateIntent': if (params['old_intent']) { stash['old_intent'] = params['old_intent']; } break; case 'updateEntity': if (params['old_entity']) { stash['old_entity'] = params['old_entity']; } break; case 'updateEntityValue': if (params['old_value']) { stash['old_value'] = params['old_value']; } if (params['entity']) { stash['entity'] = params['entity']; } break; case 'updateDialogNode': if (params['old_dialog_node']) { stash['old_dialog_node'] = params['old_dialog_node']; } break; } switch(method) { case 'updateWorkspace': case 'createIntent': case 'updateIntent': case 'createEntity': case 'updateEntity': case 'updateEntityValue': case 'createDialogNode': case 'updateDialogNode': if (params['workspace_id']) { stash['workspace_id'] = params['workspace_id']; } break; } if (workspaceObject) { params = workspaceObject; } if (stash) { for (var k in stash) { params[k] = stash[k]; } } return Promise.resolve(params); }
javascript
function setWorkspaceParams(method, params, workspaceObject) { var workspace_id = null; var stash = {}; if ('object' !== typeof workspaceObject) { return Promise.reject('json content expected as input on payload'); } switch(method) { case 'updateIntent': if (params['old_intent']) { stash['old_intent'] = params['old_intent']; } break; case 'updateEntity': if (params['old_entity']) { stash['old_entity'] = params['old_entity']; } break; case 'updateEntityValue': if (params['old_value']) { stash['old_value'] = params['old_value']; } if (params['entity']) { stash['entity'] = params['entity']; } break; case 'updateDialogNode': if (params['old_dialog_node']) { stash['old_dialog_node'] = params['old_dialog_node']; } break; } switch(method) { case 'updateWorkspace': case 'createIntent': case 'updateIntent': case 'createEntity': case 'updateEntity': case 'updateEntityValue': case 'createDialogNode': case 'updateDialogNode': if (params['workspace_id']) { stash['workspace_id'] = params['workspace_id']; } break; } if (workspaceObject) { params = workspaceObject; } if (stash) { for (var k in stash) { params[k] = stash[k]; } } return Promise.resolve(params); }
[ "function", "setWorkspaceParams", "(", "method", ",", "params", ",", "workspaceObject", ")", "{", "var", "workspace_id", "=", "null", ";", "var", "stash", "=", "{", "}", ";", "if", "(", "'object'", "!==", "typeof", "workspaceObject", ")", "{", "return", "Promise", ".", "reject", "(", "'json content expected as input on payload'", ")", ";", "}", "switch", "(", "method", ")", "{", "case", "'updateIntent'", ":", "if", "(", "params", "[", "'old_intent'", "]", ")", "{", "stash", "[", "'old_intent'", "]", "=", "params", "[", "'old_intent'", "]", ";", "}", "break", ";", "case", "'updateEntity'", ":", "if", "(", "params", "[", "'old_entity'", "]", ")", "{", "stash", "[", "'old_entity'", "]", "=", "params", "[", "'old_entity'", "]", ";", "}", "break", ";", "case", "'updateEntityValue'", ":", "if", "(", "params", "[", "'old_value'", "]", ")", "{", "stash", "[", "'old_value'", "]", "=", "params", "[", "'old_value'", "]", ";", "}", "if", "(", "params", "[", "'entity'", "]", ")", "{", "stash", "[", "'entity'", "]", "=", "params", "[", "'entity'", "]", ";", "}", "break", ";", "case", "'updateDialogNode'", ":", "if", "(", "params", "[", "'old_dialog_node'", "]", ")", "{", "stash", "[", "'old_dialog_node'", "]", "=", "params", "[", "'old_dialog_node'", "]", ";", "}", "break", ";", "}", "switch", "(", "method", ")", "{", "case", "'updateWorkspace'", ":", "case", "'createIntent'", ":", "case", "'updateIntent'", ":", "case", "'createEntity'", ":", "case", "'updateEntity'", ":", "case", "'updateEntityValue'", ":", "case", "'createDialogNode'", ":", "case", "'updateDialogNode'", ":", "if", "(", "params", "[", "'workspace_id'", "]", ")", "{", "stash", "[", "'workspace_id'", "]", "=", "params", "[", "'workspace_id'", "]", ";", "}", "break", ";", "}", "if", "(", "workspaceObject", ")", "{", "params", "=", "workspaceObject", ";", "}", "if", "(", "stash", ")", "{", "for", "(", "var", "k", "in", "stash", ")", "{", "params", "[", "k", "]", "=", "stash", "[", "k", "]", ";", "}", "}", "return", "Promise", ".", "resolve", "(", "params", ")", ";", "}" ]
No need to have complicated processing here Looking for individual fields in the json object, like name, language, entities etc. as these are the parameters required for this method are in the json object, at the top level of the json object. So it is safe to overwrite params. 'name', 'language', 'entities', 'intents', 'dialog_nodes', 'metadata', 'description', 'counterexamples' So will work for intent as is, for 'intent', 'description', 'examples' Just need to add the workspace id back in. For intent updates the old_intent will have already been set.
[ "No", "need", "to", "have", "complicated", "processing", "here", "Looking", "for", "individual", "fields", "in", "the", "json", "object", "like", "name", "language", "entities", "etc", ".", "as", "these", "are", "the", "parameters", "required", "for", "this", "method", "are", "in", "the", "json", "object", "at", "the", "top", "level", "of", "the", "json", "object", ".", "So", "it", "is", "safe", "to", "overwrite", "params", ".", "name", "language", "entities", "intents", "dialog_nodes", "metadata", "description", "counterexamples", "So", "will", "work", "for", "intent", "as", "is", "for", "intent", "description", "examples", "Just", "need", "to", "add", "the", "workspace", "id", "back", "in", ".", "For", "intent", "updates", "the", "old_intent", "will", "have", "already", "been", "set", "." ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/assistant/v1-workspace-manager.js#L898-L958
20,821
watson-developer-cloud/node-red-node-watson
services/assistant/v1-workspace-manager.js
processFileForWorkspace
function processFileForWorkspace(info, method) { var workspaceObject = null; switch (method) { case 'createWorkspace': case 'updateWorkspace': case 'createIntent': case 'updateIntent': case 'createEntity': case 'updateEntity': case 'updateEntityValue': case 'createDialogNode': case 'updateDialogNode': try { workspaceObject = JSON.parse(fs.readFileSync(info.path, 'utf8')); } catch (err) { workspaceObject = fs.createReadStream(info.path); } } return Promise.resolve(workspaceObject); }
javascript
function processFileForWorkspace(info, method) { var workspaceObject = null; switch (method) { case 'createWorkspace': case 'updateWorkspace': case 'createIntent': case 'updateIntent': case 'createEntity': case 'updateEntity': case 'updateEntityValue': case 'createDialogNode': case 'updateDialogNode': try { workspaceObject = JSON.parse(fs.readFileSync(info.path, 'utf8')); } catch (err) { workspaceObject = fs.createReadStream(info.path); } } return Promise.resolve(workspaceObject); }
[ "function", "processFileForWorkspace", "(", "info", ",", "method", ")", "{", "var", "workspaceObject", "=", "null", ";", "switch", "(", "method", ")", "{", "case", "'createWorkspace'", ":", "case", "'updateWorkspace'", ":", "case", "'createIntent'", ":", "case", "'updateIntent'", ":", "case", "'createEntity'", ":", "case", "'updateEntity'", ":", "case", "'updateEntityValue'", ":", "case", "'createDialogNode'", ":", "case", "'updateDialogNode'", ":", "try", "{", "workspaceObject", "=", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "info", ".", "path", ",", "'utf8'", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "workspaceObject", "=", "fs", ".", "createReadStream", "(", "info", ".", "path", ")", ";", "}", "}", "return", "Promise", ".", "resolve", "(", "workspaceObject", ")", ";", "}" ]
I know this says workspace, but its actually a json object that works both for workspace, intent and entity
[ "I", "know", "this", "says", "workspace", "but", "its", "actually", "a", "json", "object", "that", "works", "both", "for", "workspace", "intent", "and", "entity" ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/assistant/v1-workspace-manager.js#L991-L1012
20,822
watson-developer-cloud/node-red-node-watson
services/assistant/v1-workspace-manager.js
loadFile
function loadFile(node, method, params, msg) { var fileInfo = null; var p = openTheFile() .then(function(info){ fileInfo = info; return syncTheFile(fileInfo, msg); }) .then(function(){ return processFileForWorkspace(fileInfo, method); }) .then(function(workspaceObject){ return setWorkspaceParams(method, params, workspaceObject); }); return p; }
javascript
function loadFile(node, method, params, msg) { var fileInfo = null; var p = openTheFile() .then(function(info){ fileInfo = info; return syncTheFile(fileInfo, msg); }) .then(function(){ return processFileForWorkspace(fileInfo, method); }) .then(function(workspaceObject){ return setWorkspaceParams(method, params, workspaceObject); }); return p; }
[ "function", "loadFile", "(", "node", ",", "method", ",", "params", ",", "msg", ")", "{", "var", "fileInfo", "=", "null", ";", "var", "p", "=", "openTheFile", "(", ")", ".", "then", "(", "function", "(", "info", ")", "{", "fileInfo", "=", "info", ";", "return", "syncTheFile", "(", "fileInfo", ",", "msg", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "processFileForWorkspace", "(", "fileInfo", ",", "method", ")", ";", "}", ")", ".", "then", "(", "function", "(", "workspaceObject", ")", "{", "return", "setWorkspaceParams", "(", "method", ",", "params", ",", "workspaceObject", ")", ";", "}", ")", ";", "return", "p", ";", "}" ]
We are expecting a file on payload. Some of the functions used here are async, so this function is returning a consolidated promise, compromising of all the promises from the async and sync functions.
[ "We", "are", "expecting", "a", "file", "on", "payload", ".", "Some", "of", "the", "functions", "used", "here", "are", "async", "so", "this", "function", "is", "returning", "a", "consolidated", "promise", "compromising", "of", "all", "the", "promises", "from", "the", "async", "and", "sync", "functions", "." ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/assistant/v1-workspace-manager.js#L1020-L1035
20,823
watson-developer-cloud/node-red-node-watson
services/assistant/v1-workspace-manager.js
Node
function Node (config) { RED.nodes.createNode(this, config); var node = this; this.on('input', function (msg) { var method = config['cwm-custom-mode'], message = '', params = {}; username = sUsername || this.credentials.username; password = sPassword || this.credentials.password || config.password; apikey = sApikey || this.credentials.apikey || config.apikey; // All method to be overridden if (msg.params) { if (msg.params.method) { method = msg.params.method; } if (msg.params.username) { username = msg.params.username; } if (msg.params.password) { password = msg.params.password; } if (msg.params.apikey) { apikey = msg.params.apikey; } if (msg.params.version) { version = msg.params.version; } } endpoint = sEndpoint; if ((!config['cwm-default-endpoint']) && config['cwm-service-endpoint']) { endpoint = config['cwm-service-endpoint']; } node.status({}); initialCheck(apikey, username, password, method) .then(function(){ return buildParams(msg, method, config, params); }) .then(function(){ return checkForFile(method); }) .then(function(fileNeeded){ if (fileNeeded) { if (msg.payload instanceof Buffer) { return loadFile(node, method, params, msg); } // If the data is a json object then it will not // have been detected as a buffer. return setWorkspaceParams(method, params, msg.payload); } return Promise.resolve(params); }) .then(function(p){ params = p; node.status({fill:'blue', shape:'dot', text:'executing'}); return executeMethod(node, method, params, msg); }) .then(function(){ temp.cleanup(); node.status({}); node.send(msg); }) .catch(function(err){ temp.cleanup(); payloadutils.reportError(node,msg,err); }); }); }
javascript
function Node (config) { RED.nodes.createNode(this, config); var node = this; this.on('input', function (msg) { var method = config['cwm-custom-mode'], message = '', params = {}; username = sUsername || this.credentials.username; password = sPassword || this.credentials.password || config.password; apikey = sApikey || this.credentials.apikey || config.apikey; // All method to be overridden if (msg.params) { if (msg.params.method) { method = msg.params.method; } if (msg.params.username) { username = msg.params.username; } if (msg.params.password) { password = msg.params.password; } if (msg.params.apikey) { apikey = msg.params.apikey; } if (msg.params.version) { version = msg.params.version; } } endpoint = sEndpoint; if ((!config['cwm-default-endpoint']) && config['cwm-service-endpoint']) { endpoint = config['cwm-service-endpoint']; } node.status({}); initialCheck(apikey, username, password, method) .then(function(){ return buildParams(msg, method, config, params); }) .then(function(){ return checkForFile(method); }) .then(function(fileNeeded){ if (fileNeeded) { if (msg.payload instanceof Buffer) { return loadFile(node, method, params, msg); } // If the data is a json object then it will not // have been detected as a buffer. return setWorkspaceParams(method, params, msg.payload); } return Promise.resolve(params); }) .then(function(p){ params = p; node.status({fill:'blue', shape:'dot', text:'executing'}); return executeMethod(node, method, params, msg); }) .then(function(){ temp.cleanup(); node.status({}); node.send(msg); }) .catch(function(err){ temp.cleanup(); payloadutils.reportError(node,msg,err); }); }); }
[ "function", "Node", "(", "config", ")", "{", "RED", ".", "nodes", ".", "createNode", "(", "this", ",", "config", ")", ";", "var", "node", "=", "this", ";", "this", ".", "on", "(", "'input'", ",", "function", "(", "msg", ")", "{", "var", "method", "=", "config", "[", "'cwm-custom-mode'", "]", ",", "message", "=", "''", ",", "params", "=", "{", "}", ";", "username", "=", "sUsername", "||", "this", ".", "credentials", ".", "username", ";", "password", "=", "sPassword", "||", "this", ".", "credentials", ".", "password", "||", "config", ".", "password", ";", "apikey", "=", "sApikey", "||", "this", ".", "credentials", ".", "apikey", "||", "config", ".", "apikey", ";", "// All method to be overridden", "if", "(", "msg", ".", "params", ")", "{", "if", "(", "msg", ".", "params", ".", "method", ")", "{", "method", "=", "msg", ".", "params", ".", "method", ";", "}", "if", "(", "msg", ".", "params", ".", "username", ")", "{", "username", "=", "msg", ".", "params", ".", "username", ";", "}", "if", "(", "msg", ".", "params", ".", "password", ")", "{", "password", "=", "msg", ".", "params", ".", "password", ";", "}", "if", "(", "msg", ".", "params", ".", "apikey", ")", "{", "apikey", "=", "msg", ".", "params", ".", "apikey", ";", "}", "if", "(", "msg", ".", "params", ".", "version", ")", "{", "version", "=", "msg", ".", "params", ".", "version", ";", "}", "}", "endpoint", "=", "sEndpoint", ";", "if", "(", "(", "!", "config", "[", "'cwm-default-endpoint'", "]", ")", "&&", "config", "[", "'cwm-service-endpoint'", "]", ")", "{", "endpoint", "=", "config", "[", "'cwm-service-endpoint'", "]", ";", "}", "node", ".", "status", "(", "{", "}", ")", ";", "initialCheck", "(", "apikey", ",", "username", ",", "password", ",", "method", ")", ".", "then", "(", "function", "(", ")", "{", "return", "buildParams", "(", "msg", ",", "method", ",", "config", ",", "params", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "checkForFile", "(", "method", ")", ";", "}", ")", ".", "then", "(", "function", "(", "fileNeeded", ")", "{", "if", "(", "fileNeeded", ")", "{", "if", "(", "msg", ".", "payload", "instanceof", "Buffer", ")", "{", "return", "loadFile", "(", "node", ",", "method", ",", "params", ",", "msg", ")", ";", "}", "// If the data is a json object then it will not", "// have been detected as a buffer.", "return", "setWorkspaceParams", "(", "method", ",", "params", ",", "msg", ".", "payload", ")", ";", "}", "return", "Promise", ".", "resolve", "(", "params", ")", ";", "}", ")", ".", "then", "(", "function", "(", "p", ")", "{", "params", "=", "p", ";", "node", ".", "status", "(", "{", "fill", ":", "'blue'", ",", "shape", ":", "'dot'", ",", "text", ":", "'executing'", "}", ")", ";", "return", "executeMethod", "(", "node", ",", "method", ",", "params", ",", "msg", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "temp", ".", "cleanup", "(", ")", ";", "node", ".", "status", "(", "{", "}", ")", ";", "node", ".", "send", "(", "msg", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "temp", ".", "cleanup", "(", ")", ";", "payloadutils", ".", "reportError", "(", "node", ",", "msg", ",", "err", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
This is the Conversation Workspace Manager Node
[ "This", "is", "the", "Conversation", "Workspace", "Manager", "Node" ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/assistant/v1-workspace-manager.js#L1080-L1151
20,824
watson-developer-cloud/node-red-node-watson
services/language_translator/v3.js
doTranslate
function doTranslate(language_translator, msg, model_id) { var p = new Promise(function resolver(resolve, reject){ // Please be careful when reading the below. The first parameter is // a structure, and the tabbing enforced by codeacy imho obfuscates // the code, rather than making it clearer. I would have liked an // extra couple of spaces. language_translator.translate({ text: msg.payload, model_id: model_id }, function (err, response) { if (err) { reject(err); } else { msg.translation = {}; msg.translation.response = response; msg.payload = response.translations[0].translation; resolve(); } }); }); return p; }
javascript
function doTranslate(language_translator, msg, model_id) { var p = new Promise(function resolver(resolve, reject){ // Please be careful when reading the below. The first parameter is // a structure, and the tabbing enforced by codeacy imho obfuscates // the code, rather than making it clearer. I would have liked an // extra couple of spaces. language_translator.translate({ text: msg.payload, model_id: model_id }, function (err, response) { if (err) { reject(err); } else { msg.translation = {}; msg.translation.response = response; msg.payload = response.translations[0].translation; resolve(); } }); }); return p; }
[ "function", "doTranslate", "(", "language_translator", ",", "msg", ",", "model_id", ")", "{", "var", "p", "=", "new", "Promise", "(", "function", "resolver", "(", "resolve", ",", "reject", ")", "{", "// Please be careful when reading the below. The first parameter is", "// a structure, and the tabbing enforced by codeacy imho obfuscates", "// the code, rather than making it clearer. I would have liked an", "// extra couple of spaces.", "language_translator", ".", "translate", "(", "{", "text", ":", "msg", ".", "payload", ",", "model_id", ":", "model_id", "}", ",", "function", "(", "err", ",", "response", ")", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "else", "{", "msg", ".", "translation", "=", "{", "}", ";", "msg", ".", "translation", ".", "response", "=", "response", ";", "msg", ".", "payload", "=", "response", ".", "translations", "[", "0", "]", ".", "translation", ";", "resolve", "(", ")", ";", "}", "}", ")", ";", "}", ")", ";", "return", "p", ";", "}" ]
If a translation is requested, then the model id will have been built by the calling function based on source, target and domain.
[ "If", "a", "translation", "is", "requested", "then", "the", "model", "id", "will", "have", "been", "built", "by", "the", "calling", "function", "based", "on", "source", "target", "and", "domain", "." ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/language_translator/v3.js#L143-L166
20,825
watson-developer-cloud/node-red-node-watson
services/dialog/v1.js
performCreate
function performCreate(node,dialog,msg) { var params = {} node.status({fill:'blue', shape:'dot', text:'requesting create of new dialog template'}); //if ('file' in msg.dialog_params && 'dialog_name' in msg.dialog_params) { if ('dialog_name' in msg.dialog_params) { // extension supported : only XML // TODO : support other API format (json and encrypted crt) temp.open({suffix: '.xml'}, function (err, info) { if (err) throw err; //var fileBuffer = msg.dialog_params['file']; var fileBuffer = msg.payload; fs.writeFile(info.path, fileBuffer, function (err) { if (err) { console.error(err); throw err; } var aFileStream = fs.createReadStream(info.path); params.file = aFileStream; params.name = msg.dialog_params['dialog_name']; // Watson SDK call dialog.createDialog(params, function(err, dialog_data){ node.status({}); if (err) { node.status({fill:'red', shape:'ring', text:'call to dialog service failed'}); node.error(err, msg); } else { msg.dialog = dialog_data; msg.payload = 'Check msg.dialog dialog data'; node.send(msg); } }); }); }); } /* else if (! 'file' in msg.dialog_params) { var errtxt = 'Missing Dialog template file'; node.status({fill:'red', shape:'ring', text:errtxt}); node.error(errtxt, msg); }*/ else { errtxt = 'dialog_name not specified'; node.status({fill:'red', shape:'ring', text:errtxt}); node.error(errtxt, msg); } }
javascript
function performCreate(node,dialog,msg) { var params = {} node.status({fill:'blue', shape:'dot', text:'requesting create of new dialog template'}); //if ('file' in msg.dialog_params && 'dialog_name' in msg.dialog_params) { if ('dialog_name' in msg.dialog_params) { // extension supported : only XML // TODO : support other API format (json and encrypted crt) temp.open({suffix: '.xml'}, function (err, info) { if (err) throw err; //var fileBuffer = msg.dialog_params['file']; var fileBuffer = msg.payload; fs.writeFile(info.path, fileBuffer, function (err) { if (err) { console.error(err); throw err; } var aFileStream = fs.createReadStream(info.path); params.file = aFileStream; params.name = msg.dialog_params['dialog_name']; // Watson SDK call dialog.createDialog(params, function(err, dialog_data){ node.status({}); if (err) { node.status({fill:'red', shape:'ring', text:'call to dialog service failed'}); node.error(err, msg); } else { msg.dialog = dialog_data; msg.payload = 'Check msg.dialog dialog data'; node.send(msg); } }); }); }); } /* else if (! 'file' in msg.dialog_params) { var errtxt = 'Missing Dialog template file'; node.status({fill:'red', shape:'ring', text:errtxt}); node.error(errtxt, msg); }*/ else { errtxt = 'dialog_name not specified'; node.status({fill:'red', shape:'ring', text:errtxt}); node.error(errtxt, msg); } }
[ "function", "performCreate", "(", "node", ",", "dialog", ",", "msg", ")", "{", "var", "params", "=", "{", "}", "node", ".", "status", "(", "{", "fill", ":", "'blue'", ",", "shape", ":", "'dot'", ",", "text", ":", "'requesting create of new dialog template'", "}", ")", ";", "//if ('file' in msg.dialog_params && 'dialog_name' in msg.dialog_params) {", "if", "(", "'dialog_name'", "in", "msg", ".", "dialog_params", ")", "{", "// extension supported : only XML", "// TODO : support other API format (json and encrypted crt)", "temp", ".", "open", "(", "{", "suffix", ":", "'.xml'", "}", ",", "function", "(", "err", ",", "info", ")", "{", "if", "(", "err", ")", "throw", "err", ";", "//var fileBuffer = msg.dialog_params['file'];", "var", "fileBuffer", "=", "msg", ".", "payload", ";", "fs", ".", "writeFile", "(", "info", ".", "path", ",", "fileBuffer", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "console", ".", "error", "(", "err", ")", ";", "throw", "err", ";", "}", "var", "aFileStream", "=", "fs", ".", "createReadStream", "(", "info", ".", "path", ")", ";", "params", ".", "file", "=", "aFileStream", ";", "params", ".", "name", "=", "msg", ".", "dialog_params", "[", "'dialog_name'", "]", ";", "// Watson SDK call", "dialog", ".", "createDialog", "(", "params", ",", "function", "(", "err", ",", "dialog_data", ")", "{", "node", ".", "status", "(", "{", "}", ")", ";", "if", "(", "err", ")", "{", "node", ".", "status", "(", "{", "fill", ":", "'red'", ",", "shape", ":", "'ring'", ",", "text", ":", "'call to dialog service failed'", "}", ")", ";", "node", ".", "error", "(", "err", ",", "msg", ")", ";", "}", "else", "{", "msg", ".", "dialog", "=", "dialog_data", ";", "msg", ".", "payload", "=", "'Check msg.dialog dialog data'", ";", "node", ".", "send", "(", "msg", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", "/* else if (! 'file' in msg.dialog_params) {\n var errtxt = 'Missing Dialog template file';\n node.status({fill:'red', shape:'ring', text:errtxt}); \t\t\n node.error(errtxt, msg);\n }*/", "else", "{", "errtxt", "=", "'dialog_name not specified'", ";", "node", ".", "status", "(", "{", "fill", ":", "'red'", ",", "shape", ":", "'ring'", ",", "text", ":", "errtxt", "}", ")", ";", "node", ".", "error", "(", "errtxt", ",", "msg", ")", ";", "}", "}" ]
This function creates a new dialog template. The name must be unique, the file can be in any accepted format, and be either a text file or a binary buffer.
[ "This", "function", "creates", "a", "new", "dialog", "template", ".", "The", "name", "must", "be", "unique", "the", "file", "can", "be", "in", "any", "accepted", "format", "and", "be", "either", "a", "text", "file", "or", "a", "binary", "buffer", "." ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/dialog/v1.js#L184-L227
20,826
watson-developer-cloud/node-red-node-watson
services/dialog/v1.js
performDelete
function performDelete(node,dialog,msg, config) { var params = {}; var message = ''; node.status({fill:'blue', shape:'dot', text:'requesting delete of a dialog instance'}); if (!config.dialog || '' != config.dialog) { params.dialog_id = config.dialog; dialog.deleteDialog(params, function(err, dialog_data){ node.status({}); if (!err) { message='Dialog deleted successfully'; msg.dialog = dialog_data; msg.payload = message; node.send(msg); } else if (err && err.code==404) { message='Dialog already deleted or not existing (404)'; node.status({fill:'green', shape:'dot', text:message}); msg.payload = message; console.log(err); node.error(message, msg); } else { node.status({fill:'red', shape:'ring', text:'call to dialog service failed'}); node.error(err, msg); console.log(err); } }); } else { message = 'Dialog Id not specified'; node.status({fill:'red', shape:'ring', text:message}); node.error(errmessage, msg); } }
javascript
function performDelete(node,dialog,msg, config) { var params = {}; var message = ''; node.status({fill:'blue', shape:'dot', text:'requesting delete of a dialog instance'}); if (!config.dialog || '' != config.dialog) { params.dialog_id = config.dialog; dialog.deleteDialog(params, function(err, dialog_data){ node.status({}); if (!err) { message='Dialog deleted successfully'; msg.dialog = dialog_data; msg.payload = message; node.send(msg); } else if (err && err.code==404) { message='Dialog already deleted or not existing (404)'; node.status({fill:'green', shape:'dot', text:message}); msg.payload = message; console.log(err); node.error(message, msg); } else { node.status({fill:'red', shape:'ring', text:'call to dialog service failed'}); node.error(err, msg); console.log(err); } }); } else { message = 'Dialog Id not specified'; node.status({fill:'red', shape:'ring', text:message}); node.error(errmessage, msg); } }
[ "function", "performDelete", "(", "node", ",", "dialog", ",", "msg", ",", "config", ")", "{", "var", "params", "=", "{", "}", ";", "var", "message", "=", "''", ";", "node", ".", "status", "(", "{", "fill", ":", "'blue'", ",", "shape", ":", "'dot'", ",", "text", ":", "'requesting delete of a dialog instance'", "}", ")", ";", "if", "(", "!", "config", ".", "dialog", "||", "''", "!=", "config", ".", "dialog", ")", "{", "params", ".", "dialog_id", "=", "config", ".", "dialog", ";", "dialog", ".", "deleteDialog", "(", "params", ",", "function", "(", "err", ",", "dialog_data", ")", "{", "node", ".", "status", "(", "{", "}", ")", ";", "if", "(", "!", "err", ")", "{", "message", "=", "'Dialog deleted successfully'", ";", "msg", ".", "dialog", "=", "dialog_data", ";", "msg", ".", "payload", "=", "message", ";", "node", ".", "send", "(", "msg", ")", ";", "}", "else", "if", "(", "err", "&&", "err", ".", "code", "==", "404", ")", "{", "message", "=", "'Dialog already deleted or not existing (404)'", ";", "node", ".", "status", "(", "{", "fill", ":", "'green'", ",", "shape", ":", "'dot'", ",", "text", ":", "message", "}", ")", ";", "msg", ".", "payload", "=", "message", ";", "console", ".", "log", "(", "err", ")", ";", "node", ".", "error", "(", "message", ",", "msg", ")", ";", "}", "else", "{", "node", ".", "status", "(", "{", "fill", ":", "'red'", ",", "shape", ":", "'ring'", ",", "text", ":", "'call to dialog service failed'", "}", ")", ";", "node", ".", "error", "(", "err", ",", "msg", ")", ";", "console", ".", "log", "(", "err", ")", ";", "}", "}", ")", ";", "}", "else", "{", "message", "=", "'Dialog Id not specified'", ";", "node", ".", "status", "(", "{", "fill", ":", "'red'", ",", "shape", ":", "'ring'", ",", "text", ":", "message", "}", ")", ";", "node", ".", "error", "(", "errmessage", ",", "msg", ")", ";", "}", "}" ]
This function delete an existing dialog instance.
[ "This", "function", "delete", "an", "existing", "dialog", "instance", "." ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/dialog/v1.js#L230-L263
20,827
watson-developer-cloud/node-red-node-watson
services/dialog/v1.js
performList
function performList(node,dialog,msg) { node.status({fill:'blue', shape:'dot', text:'requesting list of dialogs'}); dialog.getDialogs({}, function(err, dialogs){ node.status({}); if (err) { node.status({fill:'red', shape:'ring', text:'call to dialog service failed'}); node.error(err, msg); } else { msg.dialog = dialogs; msg.payload = 'Check msg.dialog for list of dialogs'; node.send(msg); } }); }
javascript
function performList(node,dialog,msg) { node.status({fill:'blue', shape:'dot', text:'requesting list of dialogs'}); dialog.getDialogs({}, function(err, dialogs){ node.status({}); if (err) { node.status({fill:'red', shape:'ring', text:'call to dialog service failed'}); node.error(err, msg); } else { msg.dialog = dialogs; msg.payload = 'Check msg.dialog for list of dialogs'; node.send(msg); } }); }
[ "function", "performList", "(", "node", ",", "dialog", ",", "msg", ")", "{", "node", ".", "status", "(", "{", "fill", ":", "'blue'", ",", "shape", ":", "'dot'", ",", "text", ":", "'requesting list of dialogs'", "}", ")", ";", "dialog", ".", "getDialogs", "(", "{", "}", ",", "function", "(", "err", ",", "dialogs", ")", "{", "node", ".", "status", "(", "{", "}", ")", ";", "if", "(", "err", ")", "{", "node", ".", "status", "(", "{", "fill", ":", "'red'", ",", "shape", ":", "'ring'", ",", "text", ":", "'call to dialog service failed'", "}", ")", ";", "node", ".", "error", "(", "err", ",", "msg", ")", ";", "}", "else", "{", "msg", ".", "dialog", "=", "dialogs", ";", "msg", ".", "payload", "=", "'Check msg.dialog for list of dialogs'", ";", "node", ".", "send", "(", "msg", ")", ";", "}", "}", ")", ";", "}" ]
This function performs the operation to fetch a list of all dialog templates
[ "This", "function", "performs", "the", "operation", "to", "fetch", "a", "list", "of", "all", "dialog", "templates" ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/dialog/v1.js#L266-L280
20,828
watson-developer-cloud/node-red-node-watson
services/dialog/v1.js
performDeleteAll
function performDeleteAll(node,dialog,msg) { node.status({fill:'blue', shape:'dot', text:'requesting Delete All dialogs'}); dialog.getDialogs({}, function(err, dialogs){ node.status({}); if (err) { node.status({fill:'red', shape:'ring', text:'Delete All : call to getDialogs service failed'}); node.error(err, msg); } else { // Array to hold async tasks var asyncTasks = []; var nb_todelete = dialogs.dialogs.length; var nbdeleted = 0; dialogs.dialogs.forEach(function (aDialog) { asyncTasks.push(function (cb) { var parms = {}; parms.dialog_id=aDialog.dialog_id;; dialog.deleteDialog(parms, function(err, dialog_data){ node.status({}); if (err) { node.error(err, msg); console.log('Error with the removal of Dialog ID '+parms.dialog_id +' : ' + err); } else { console.log('Dialog ID '+ aDialog.dialog_id + ' deleted successfully.'); nbdeleted++; } cb(); }); }); }); } // else async.parallel(asyncTasks, function(){ // All tasks are done now console.log('Deleted ' + nbdeleted + ' dialog objects on ' + nb_todelete ); if (nbdeleted==nb_todelete) msg.payload = 'All Dialogs have been deleted'; else msg.payload = 'Some Dialogs could have not been deleted; See node-RED log for errors.'; console.log(msg.payload); node.send(msg); }); }); }
javascript
function performDeleteAll(node,dialog,msg) { node.status({fill:'blue', shape:'dot', text:'requesting Delete All dialogs'}); dialog.getDialogs({}, function(err, dialogs){ node.status({}); if (err) { node.status({fill:'red', shape:'ring', text:'Delete All : call to getDialogs service failed'}); node.error(err, msg); } else { // Array to hold async tasks var asyncTasks = []; var nb_todelete = dialogs.dialogs.length; var nbdeleted = 0; dialogs.dialogs.forEach(function (aDialog) { asyncTasks.push(function (cb) { var parms = {}; parms.dialog_id=aDialog.dialog_id;; dialog.deleteDialog(parms, function(err, dialog_data){ node.status({}); if (err) { node.error(err, msg); console.log('Error with the removal of Dialog ID '+parms.dialog_id +' : ' + err); } else { console.log('Dialog ID '+ aDialog.dialog_id + ' deleted successfully.'); nbdeleted++; } cb(); }); }); }); } // else async.parallel(asyncTasks, function(){ // All tasks are done now console.log('Deleted ' + nbdeleted + ' dialog objects on ' + nb_todelete ); if (nbdeleted==nb_todelete) msg.payload = 'All Dialogs have been deleted'; else msg.payload = 'Some Dialogs could have not been deleted; See node-RED log for errors.'; console.log(msg.payload); node.send(msg); }); }); }
[ "function", "performDeleteAll", "(", "node", ",", "dialog", ",", "msg", ")", "{", "node", ".", "status", "(", "{", "fill", ":", "'blue'", ",", "shape", ":", "'dot'", ",", "text", ":", "'requesting Delete All dialogs'", "}", ")", ";", "dialog", ".", "getDialogs", "(", "{", "}", ",", "function", "(", "err", ",", "dialogs", ")", "{", "node", ".", "status", "(", "{", "}", ")", ";", "if", "(", "err", ")", "{", "node", ".", "status", "(", "{", "fill", ":", "'red'", ",", "shape", ":", "'ring'", ",", "text", ":", "'Delete All : call to getDialogs service failed'", "}", ")", ";", "node", ".", "error", "(", "err", ",", "msg", ")", ";", "}", "else", "{", "// Array to hold async tasks", "var", "asyncTasks", "=", "[", "]", ";", "var", "nb_todelete", "=", "dialogs", ".", "dialogs", ".", "length", ";", "var", "nbdeleted", "=", "0", ";", "dialogs", ".", "dialogs", ".", "forEach", "(", "function", "(", "aDialog", ")", "{", "asyncTasks", ".", "push", "(", "function", "(", "cb", ")", "{", "var", "parms", "=", "{", "}", ";", "parms", ".", "dialog_id", "=", "aDialog", ".", "dialog_id", ";", ";", "dialog", ".", "deleteDialog", "(", "parms", ",", "function", "(", "err", ",", "dialog_data", ")", "{", "node", ".", "status", "(", "{", "}", ")", ";", "if", "(", "err", ")", "{", "node", ".", "error", "(", "err", ",", "msg", ")", ";", "console", ".", "log", "(", "'Error with the removal of Dialog ID '", "+", "parms", ".", "dialog_id", "+", "' : '", "+", "err", ")", ";", "}", "else", "{", "console", ".", "log", "(", "'Dialog ID '", "+", "aDialog", ".", "dialog_id", "+", "' deleted successfully.'", ")", ";", "nbdeleted", "++", ";", "}", "cb", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", "// else", "async", ".", "parallel", "(", "asyncTasks", ",", "function", "(", ")", "{", "// All tasks are done now", "console", ".", "log", "(", "'Deleted '", "+", "nbdeleted", "+", "' dialog objects on '", "+", "nb_todelete", ")", ";", "if", "(", "nbdeleted", "==", "nb_todelete", ")", "msg", ".", "payload", "=", "'All Dialogs have been deleted'", ";", "else", "msg", ".", "payload", "=", "'Some Dialogs could have not been deleted; See node-RED log for errors.'", ";", "console", ".", "log", "(", "msg", ".", "payload", ")", ";", "node", ".", "send", "(", "msg", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
This function performs the operation to Delete ALL Dialogs
[ "This", "function", "performs", "the", "operation", "to", "Delete", "ALL", "Dialogs" ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/dialog/v1.js#L283-L330
20,829
watson-developer-cloud/node-red-node-watson
services/visual_recognition/v3.js
addTask
function addTask(asyncTasks, msg, k, listParams, node) { asyncTasks.push(function(callback) { var buffer = msg.params[k]; temp.open({ suffix: '.' + fileType(buffer).ext }, function(err, info) { if (err) { node.status({ fill: 'red', shape: 'ring', text: 'unable to open image stream' }); node.error('Node has been unable to open the image stream', msg); return callback('open error on ' + k); } stream_buffer(info.path, msg.params[k], function() { let example_name = k; if (! (k.includes('positive') || k.includes('negative'))) { example_name = k.replace('examples', 'positive_examples'); } listParams[example_name] = fs.createReadStream(info.path); callback(null, example_name); }); }); }); }
javascript
function addTask(asyncTasks, msg, k, listParams, node) { asyncTasks.push(function(callback) { var buffer = msg.params[k]; temp.open({ suffix: '.' + fileType(buffer).ext }, function(err, info) { if (err) { node.status({ fill: 'red', shape: 'ring', text: 'unable to open image stream' }); node.error('Node has been unable to open the image stream', msg); return callback('open error on ' + k); } stream_buffer(info.path, msg.params[k], function() { let example_name = k; if (! (k.includes('positive') || k.includes('negative'))) { example_name = k.replace('examples', 'positive_examples'); } listParams[example_name] = fs.createReadStream(info.path); callback(null, example_name); }); }); }); }
[ "function", "addTask", "(", "asyncTasks", ",", "msg", ",", "k", ",", "listParams", ",", "node", ")", "{", "asyncTasks", ".", "push", "(", "function", "(", "callback", ")", "{", "var", "buffer", "=", "msg", ".", "params", "[", "k", "]", ";", "temp", ".", "open", "(", "{", "suffix", ":", "'.'", "+", "fileType", "(", "buffer", ")", ".", "ext", "}", ",", "function", "(", "err", ",", "info", ")", "{", "if", "(", "err", ")", "{", "node", ".", "status", "(", "{", "fill", ":", "'red'", ",", "shape", ":", "'ring'", ",", "text", ":", "'unable to open image stream'", "}", ")", ";", "node", ".", "error", "(", "'Node has been unable to open the image stream'", ",", "msg", ")", ";", "return", "callback", "(", "'open error on '", "+", "k", ")", ";", "}", "stream_buffer", "(", "info", ".", "path", ",", "msg", ".", "params", "[", "k", "]", ",", "function", "(", ")", "{", "let", "example_name", "=", "k", ";", "if", "(", "!", "(", "k", ".", "includes", "(", "'positive'", ")", "||", "k", ".", "includes", "(", "'negative'", ")", ")", ")", "{", "example_name", "=", "k", ".", "replace", "(", "'examples'", ",", "'positive_examples'", ")", ";", "}", "listParams", "[", "example_name", "]", "=", "fs", ".", "createReadStream", "(", "info", ".", "path", ")", ";", "callback", "(", "null", ",", "example_name", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
This is where the two read stream tasks are built, individually asynTasks will be the two functions that will be invoked added one at a time, each time this function is invoked msg holds the parameters k is the key value for the files in msg. listParams is where the files will go so that they can be sent to the service. callback is the callback that async forces so that it can control the async functions that it is invoking.
[ "This", "is", "where", "the", "two", "read", "stream", "tasks", "are", "built", "individually", "asynTasks", "will", "be", "the", "two", "functions", "that", "will", "be", "invoked", "added", "one", "at", "a", "time", "each", "time", "this", "function", "is", "invoked", "msg", "holds", "the", "parameters", "k", "is", "the", "key", "value", "for", "the", "files", "in", "msg", ".", "listParams", "is", "where", "the", "files", "will", "go", "so", "that", "they", "can", "be", "sent", "to", "the", "service", ".", "callback", "is", "the", "callback", "that", "async", "forces", "so", "that", "it", "can", "control", "the", "async", "functions", "that", "it", "is", "invoking", "." ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/visual_recognition/v3.js#L267-L292
20,830
watson-developer-cloud/node-red-node-watson
services/text_to_speech/v1-corpus-builder.js
Node
function Node (config) { RED.nodes.createNode(this, config); var node = this; this.on('input', function (msg) { var method = config['tts-custom-mode'], message = '', params = {}; username = sUsername || this.credentials.username; password = sPassword || this.credentials.password || config.password; apikey = sApikey || this.credentials.apikey || config.apikey; endpoint = sEndpoint; if ((!config['default-endpoint']) && config['service-endpoint']) { endpoint = config['service-endpoint']; } if (!apikey && (!username || !password)) { message = 'Missing Watson Text to Speech service credentials'; } else if (!method || '' === method) { message = 'Required mode has not been specified'; } else { params = buildParams(msg, method, config); } if (message) { payloadutils.reportError(node, msg, message); return; } if (checkForFile(method)) { if (msg.payload instanceof Buffer) { loadFile(node, method, params, msg); return; } params = setFileParams(method, params, msg); } executeMethod(node, method, params, msg); }); }
javascript
function Node (config) { RED.nodes.createNode(this, config); var node = this; this.on('input', function (msg) { var method = config['tts-custom-mode'], message = '', params = {}; username = sUsername || this.credentials.username; password = sPassword || this.credentials.password || config.password; apikey = sApikey || this.credentials.apikey || config.apikey; endpoint = sEndpoint; if ((!config['default-endpoint']) && config['service-endpoint']) { endpoint = config['service-endpoint']; } if (!apikey && (!username || !password)) { message = 'Missing Watson Text to Speech service credentials'; } else if (!method || '' === method) { message = 'Required mode has not been specified'; } else { params = buildParams(msg, method, config); } if (message) { payloadutils.reportError(node, msg, message); return; } if (checkForFile(method)) { if (msg.payload instanceof Buffer) { loadFile(node, method, params, msg); return; } params = setFileParams(method, params, msg); } executeMethod(node, method, params, msg); }); }
[ "function", "Node", "(", "config", ")", "{", "RED", ".", "nodes", ".", "createNode", "(", "this", ",", "config", ")", ";", "var", "node", "=", "this", ";", "this", ".", "on", "(", "'input'", ",", "function", "(", "msg", ")", "{", "var", "method", "=", "config", "[", "'tts-custom-mode'", "]", ",", "message", "=", "''", ",", "params", "=", "{", "}", ";", "username", "=", "sUsername", "||", "this", ".", "credentials", ".", "username", ";", "password", "=", "sPassword", "||", "this", ".", "credentials", ".", "password", "||", "config", ".", "password", ";", "apikey", "=", "sApikey", "||", "this", ".", "credentials", ".", "apikey", "||", "config", ".", "apikey", ";", "endpoint", "=", "sEndpoint", ";", "if", "(", "(", "!", "config", "[", "'default-endpoint'", "]", ")", "&&", "config", "[", "'service-endpoint'", "]", ")", "{", "endpoint", "=", "config", "[", "'service-endpoint'", "]", ";", "}", "if", "(", "!", "apikey", "&&", "(", "!", "username", "||", "!", "password", ")", ")", "{", "message", "=", "'Missing Watson Text to Speech service credentials'", ";", "}", "else", "if", "(", "!", "method", "||", "''", "===", "method", ")", "{", "message", "=", "'Required mode has not been specified'", ";", "}", "else", "{", "params", "=", "buildParams", "(", "msg", ",", "method", ",", "config", ")", ";", "}", "if", "(", "message", ")", "{", "payloadutils", ".", "reportError", "(", "node", ",", "msg", ",", "message", ")", ";", "return", ";", "}", "if", "(", "checkForFile", "(", "method", ")", ")", "{", "if", "(", "msg", ".", "payload", "instanceof", "Buffer", ")", "{", "loadFile", "(", "node", ",", "method", ",", "params", ",", "msg", ")", ";", "return", ";", "}", "params", "=", "setFileParams", "(", "method", ",", "params", ",", "msg", ")", ";", "}", "executeMethod", "(", "node", ",", "method", ",", "params", ",", "msg", ")", ";", "}", ")", ";", "}" ]
This is the Speech to Text V1 Query Builder Node
[ "This", "is", "the", "Speech", "to", "Text", "V1", "Query", "Builder", "Node" ]
2869917ccf28a18cbdc2e58fe071666abd74bf71
https://github.com/watson-developer-cloud/node-red-node-watson/blob/2869917ccf28a18cbdc2e58fe071666abd74bf71/services/text_to_speech/v1-corpus-builder.js#L356-L397
20,831
astorije/chai-immutable
chai-immutable.js
assertCollectionSizeLeast
function assertCollectionSizeLeast(_super) { return function(n) { if (utils.flag(this, 'immutable.collection.size')) { assertIsIterable(this._obj); const { size } = this._obj; new Assertion(size).a('number'); this.assert( size >= n, 'expected #{this} to have a size of at least #{exp} but got #{act}', 'expected #{this} to not have a size of at least #{exp} but got ' + '#{act}', n, size ); } else { _super.apply(this, arguments); } }; }
javascript
function assertCollectionSizeLeast(_super) { return function(n) { if (utils.flag(this, 'immutable.collection.size')) { assertIsIterable(this._obj); const { size } = this._obj; new Assertion(size).a('number'); this.assert( size >= n, 'expected #{this} to have a size of at least #{exp} but got #{act}', 'expected #{this} to not have a size of at least #{exp} but got ' + '#{act}', n, size ); } else { _super.apply(this, arguments); } }; }
[ "function", "assertCollectionSizeLeast", "(", "_super", ")", "{", "return", "function", "(", "n", ")", "{", "if", "(", "utils", ".", "flag", "(", "this", ",", "'immutable.collection.size'", ")", ")", "{", "assertIsIterable", "(", "this", ".", "_obj", ")", ";", "const", "{", "size", "}", "=", "this", ".", "_obj", ";", "new", "Assertion", "(", "size", ")", ".", "a", "(", "'number'", ")", ";", "this", ".", "assert", "(", "size", ">=", "n", ",", "'expected #{this} to have a size of at least #{exp} but got #{act}'", ",", "'expected #{this} to not have a size of at least #{exp} but got '", "+", "'#{act}'", ",", "n", ",", "size", ")", ";", "}", "else", "{", "_super", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", "}", ";", "}" ]
Numerical comparator overwrites
[ "Numerical", "comparator", "overwrites" ]
3749bed866516061be66f6459840aa1b21dd7d28
https://github.com/astorije/chai-immutable/blob/3749bed866516061be66f6459840aa1b21dd7d28/chai-immutable.js#L682-L702
20,832
Paperspace/paperspace-node
lib/request.js
request
function request( host, method, path, params, query, headers, options, file, cb, debug ) { if (!options) options = {}; // Remove leading/trailing slash from the path/host so that we can join // the two together no matter which way the user chose to provide them. if (path[0] === FSLASH) { path = path.slice(1); } if (host[host.length - 1] === FSLASH) { host = host.slice(0, host.length - 1); } var url = host + FSLASH + path; var req = superagent[method](url); var bar; var prev_loaded = 0; if (!options.withoutCredentials) req.withCredentials(); if (!file) { // Clean up extra parameters that may have gotten in here // if the request came from the CLI module. This is hacky; move elsewhere if (params) { delete params._; delete params.$0; req.send(params); } if (query) { delete query._; delete query.$0; req.query(objectToQueryString(query)); } } else { //for file upload params are sent as query params req.accept('application/json'); req.timeout(600000); if (query.workspaceFileName && global.paperspace_cli && !query.json) { req.on('progress', function _progress(e) { if (!bar) bar = new ProgressBar('Uploading ' + node_path.basename(file) + ' [:bar] :rate/bps :percent :etas', { complete: '=', incomplete: ' ', width: 40, total: e.total, }); var chunkSize = e.loaded - prev_loaded; prev_loaded = e.loaded; bar.tick(chunkSize); }); } req.attach('file', file); delete query._; delete query.$0; if (query.json) delete query.json; req.query(objectToQueryString(query)); } if (headers) { for (var headerKey in headers) { req.set(headerKey, headers[headerKey]); } } // TODO: Add nicer debug utils? Use the 'debug' module? if (debug) { console.log(method, url, params, query, headers); } return req.end(function _requestCallback(err, res) { // if content is gzipped, then body is empty object, and content is in 'text' var body; if (res && res.text) { try { body = JSON.parse(res.text); } catch (parseErr) { //console.error(res.text); //console.error(parseErr); //console.error('res: ' + res) //body = {}; res.body = { message: res.text }; } } else if (res && res.body) { // res.body is expected to be text/json body = res.body; } else body = {}; // only return body in callback if (cb) return cb(err, body); // no callback provided; return the body return body; }); }
javascript
function request( host, method, path, params, query, headers, options, file, cb, debug ) { if (!options) options = {}; // Remove leading/trailing slash from the path/host so that we can join // the two together no matter which way the user chose to provide them. if (path[0] === FSLASH) { path = path.slice(1); } if (host[host.length - 1] === FSLASH) { host = host.slice(0, host.length - 1); } var url = host + FSLASH + path; var req = superagent[method](url); var bar; var prev_loaded = 0; if (!options.withoutCredentials) req.withCredentials(); if (!file) { // Clean up extra parameters that may have gotten in here // if the request came from the CLI module. This is hacky; move elsewhere if (params) { delete params._; delete params.$0; req.send(params); } if (query) { delete query._; delete query.$0; req.query(objectToQueryString(query)); } } else { //for file upload params are sent as query params req.accept('application/json'); req.timeout(600000); if (query.workspaceFileName && global.paperspace_cli && !query.json) { req.on('progress', function _progress(e) { if (!bar) bar = new ProgressBar('Uploading ' + node_path.basename(file) + ' [:bar] :rate/bps :percent :etas', { complete: '=', incomplete: ' ', width: 40, total: e.total, }); var chunkSize = e.loaded - prev_loaded; prev_loaded = e.loaded; bar.tick(chunkSize); }); } req.attach('file', file); delete query._; delete query.$0; if (query.json) delete query.json; req.query(objectToQueryString(query)); } if (headers) { for (var headerKey in headers) { req.set(headerKey, headers[headerKey]); } } // TODO: Add nicer debug utils? Use the 'debug' module? if (debug) { console.log(method, url, params, query, headers); } return req.end(function _requestCallback(err, res) { // if content is gzipped, then body is empty object, and content is in 'text' var body; if (res && res.text) { try { body = JSON.parse(res.text); } catch (parseErr) { //console.error(res.text); //console.error(parseErr); //console.error('res: ' + res) //body = {}; res.body = { message: res.text }; } } else if (res && res.body) { // res.body is expected to be text/json body = res.body; } else body = {}; // only return body in callback if (cb) return cb(err, body); // no callback provided; return the body return body; }); }
[ "function", "request", "(", "host", ",", "method", ",", "path", ",", "params", ",", "query", ",", "headers", ",", "options", ",", "file", ",", "cb", ",", "debug", ")", "{", "if", "(", "!", "options", ")", "options", "=", "{", "}", ";", "// Remove leading/trailing slash from the path/host so that we can join", "// the two together no matter which way the user chose to provide them.", "if", "(", "path", "[", "0", "]", "===", "FSLASH", ")", "{", "path", "=", "path", ".", "slice", "(", "1", ")", ";", "}", "if", "(", "host", "[", "host", ".", "length", "-", "1", "]", "===", "FSLASH", ")", "{", "host", "=", "host", ".", "slice", "(", "0", ",", "host", ".", "length", "-", "1", ")", ";", "}", "var", "url", "=", "host", "+", "FSLASH", "+", "path", ";", "var", "req", "=", "superagent", "[", "method", "]", "(", "url", ")", ";", "var", "bar", ";", "var", "prev_loaded", "=", "0", ";", "if", "(", "!", "options", ".", "withoutCredentials", ")", "req", ".", "withCredentials", "(", ")", ";", "if", "(", "!", "file", ")", "{", "// Clean up extra parameters that may have gotten in here", "// if the request came from the CLI module. This is hacky; move elsewhere", "if", "(", "params", ")", "{", "delete", "params", ".", "_", ";", "delete", "params", ".", "$0", ";", "req", ".", "send", "(", "params", ")", ";", "}", "if", "(", "query", ")", "{", "delete", "query", ".", "_", ";", "delete", "query", ".", "$0", ";", "req", ".", "query", "(", "objectToQueryString", "(", "query", ")", ")", ";", "}", "}", "else", "{", "//for file upload params are sent as query params", "req", ".", "accept", "(", "'application/json'", ")", ";", "req", ".", "timeout", "(", "600000", ")", ";", "if", "(", "query", ".", "workspaceFileName", "&&", "global", ".", "paperspace_cli", "&&", "!", "query", ".", "json", ")", "{", "req", ".", "on", "(", "'progress'", ",", "function", "_progress", "(", "e", ")", "{", "if", "(", "!", "bar", ")", "bar", "=", "new", "ProgressBar", "(", "'Uploading '", "+", "node_path", ".", "basename", "(", "file", ")", "+", "' [:bar] :rate/bps :percent :etas'", ",", "{", "complete", ":", "'='", ",", "incomplete", ":", "' '", ",", "width", ":", "40", ",", "total", ":", "e", ".", "total", ",", "}", ")", ";", "var", "chunkSize", "=", "e", ".", "loaded", "-", "prev_loaded", ";", "prev_loaded", "=", "e", ".", "loaded", ";", "bar", ".", "tick", "(", "chunkSize", ")", ";", "}", ")", ";", "}", "req", ".", "attach", "(", "'file'", ",", "file", ")", ";", "delete", "query", ".", "_", ";", "delete", "query", ".", "$0", ";", "if", "(", "query", ".", "json", ")", "delete", "query", ".", "json", ";", "req", ".", "query", "(", "objectToQueryString", "(", "query", ")", ")", ";", "}", "if", "(", "headers", ")", "{", "for", "(", "var", "headerKey", "in", "headers", ")", "{", "req", ".", "set", "(", "headerKey", ",", "headers", "[", "headerKey", "]", ")", ";", "}", "}", "// TODO: Add nicer debug utils? Use the 'debug' module?", "if", "(", "debug", ")", "{", "console", ".", "log", "(", "method", ",", "url", ",", "params", ",", "query", ",", "headers", ")", ";", "}", "return", "req", ".", "end", "(", "function", "_requestCallback", "(", "err", ",", "res", ")", "{", "// if content is gzipped, then body is empty object, and content is in 'text'", "var", "body", ";", "if", "(", "res", "&&", "res", ".", "text", ")", "{", "try", "{", "body", "=", "JSON", ".", "parse", "(", "res", ".", "text", ")", ";", "}", "catch", "(", "parseErr", ")", "{", "//console.error(res.text);", "//console.error(parseErr);", "//console.error('res: ' + res)", "//body = {};", "res", ".", "body", "=", "{", "message", ":", "res", ".", "text", "}", ";", "}", "}", "else", "if", "(", "res", "&&", "res", ".", "body", ")", "{", "// res.body is expected to be text/json", "body", "=", "res", ".", "body", ";", "}", "else", "body", "=", "{", "}", ";", "// only return body in callback", "if", "(", "cb", ")", "return", "cb", "(", "err", ",", "body", ")", ";", "// no callback provided; return the body", "return", "body", ";", "}", ")", ";", "}" ]
General-purpose HTTP request method, based on superagent
[ "General", "-", "purpose", "HTTP", "request", "method", "based", "on", "superagent" ]
aed9c28610dbefb70bf382189f068182062325a6
https://github.com/Paperspace/paperspace-node/blob/aed9c28610dbefb70bf382189f068182062325a6/lib/request.js#L21-L123
20,833
Paperspace/paperspace-node
lib/paperspace.js
eachEndpoint
function eachEndpoint(iterator) { for (var namespace in endpoints) { var methods = endpoints[namespace]; for (var name in methods) { var method = methods[name]; iterator(namespace, name, method); } } return endpoints; }
javascript
function eachEndpoint(iterator) { for (var namespace in endpoints) { var methods = endpoints[namespace]; for (var name in methods) { var method = methods[name]; iterator(namespace, name, method); } } return endpoints; }
[ "function", "eachEndpoint", "(", "iterator", ")", "{", "for", "(", "var", "namespace", "in", "endpoints", ")", "{", "var", "methods", "=", "endpoints", "[", "namespace", "]", ";", "for", "(", "var", "name", "in", "methods", ")", "{", "var", "method", "=", "methods", "[", "name", "]", ";", "iterator", "(", "namespace", ",", "name", ",", "method", ")", ";", "}", "}", "return", "endpoints", ";", "}" ]
Iterate through all the endpoints available and return the namespace, method name, and method to the iterator function
[ "Iterate", "through", "all", "the", "endpoints", "available", "and", "return", "the", "namespace", "method", "name", "and", "method", "to", "the", "iterator", "function" ]
aed9c28610dbefb70bf382189f068182062325a6
https://github.com/Paperspace/paperspace-node/blob/aed9c28610dbefb70bf382189f068182062325a6/lib/paperspace.js#L15-L27
20,834
Paperspace/paperspace-node
lib/paperspace.js
paperspace
function paperspace(options) { if (options && !isAnyAuthOptionPresent(options)) { throw NO_CREDS; } var api = {}; eachEndpoint(function _eachEndpoint(namespace, name, method) { if (!api[namespace]) api[namespace] = {}; api[namespace][name] = wrapMethod(method, options); }); return api; }
javascript
function paperspace(options) { if (options && !isAnyAuthOptionPresent(options)) { throw NO_CREDS; } var api = {}; eachEndpoint(function _eachEndpoint(namespace, name, method) { if (!api[namespace]) api[namespace] = {}; api[namespace][name] = wrapMethod(method, options); }); return api; }
[ "function", "paperspace", "(", "options", ")", "{", "if", "(", "options", "&&", "!", "isAnyAuthOptionPresent", "(", "options", ")", ")", "{", "throw", "NO_CREDS", ";", "}", "var", "api", "=", "{", "}", ";", "eachEndpoint", "(", "function", "_eachEndpoint", "(", "namespace", ",", "name", ",", "method", ")", "{", "if", "(", "!", "api", "[", "namespace", "]", ")", "api", "[", "namespace", "]", "=", "{", "}", ";", "api", "[", "namespace", "]", "[", "name", "]", "=", "wrapMethod", "(", "method", ",", "options", ")", ";", "}", ")", ";", "return", "api", ";", "}" ]
Entrypoint to the API for those who want to use a certain set of credentials for authenticating all requests
[ "Entrypoint", "to", "the", "API", "for", "those", "who", "want", "to", "use", "a", "certain", "set", "of", "credentials", "for", "authenticating", "all", "requests" ]
aed9c28610dbefb70bf382189f068182062325a6
https://github.com/Paperspace/paperspace-node/blob/aed9c28610dbefb70bf382189f068182062325a6/lib/paperspace.js#L56-L69
20,835
Paperspace/paperspace-node
lib/client.js
client
function client(method, path, inputs, headers, file, cb) { var body = null; var query = {}; var options = {}; // It's assumed these will be provided, but just in case... if (!headers) headers = {}; headers.ps_client_name = clientName; headers.ps_client_version = clientVersion; // Send input params as the query string if this is a GET, otherwise send // with the HTTP request body switch (method.toLowerCase()) { case 'get': query = inputs; break; case 'post': if (file) { query = inputs; break; } default: // eslint-disable-line no-fallthrough // Don't leave the access token on the inputs object since the jwt // really belongs on the query string (at least, per the way the interface // to the Paperspace API is currently set up). query.access_token = inputs.access_token; delete inputs.access_token; body = inputs; break; } // The rubber finally meets the road with 'request', which initiates // the request via Superagent return request( path === '/jobs/logs' ? config.logHost : config.host, method, path, body, query, headers, options, file, cb, inputs.debug ); }
javascript
function client(method, path, inputs, headers, file, cb) { var body = null; var query = {}; var options = {}; // It's assumed these will be provided, but just in case... if (!headers) headers = {}; headers.ps_client_name = clientName; headers.ps_client_version = clientVersion; // Send input params as the query string if this is a GET, otherwise send // with the HTTP request body switch (method.toLowerCase()) { case 'get': query = inputs; break; case 'post': if (file) { query = inputs; break; } default: // eslint-disable-line no-fallthrough // Don't leave the access token on the inputs object since the jwt // really belongs on the query string (at least, per the way the interface // to the Paperspace API is currently set up). query.access_token = inputs.access_token; delete inputs.access_token; body = inputs; break; } // The rubber finally meets the road with 'request', which initiates // the request via Superagent return request( path === '/jobs/logs' ? config.logHost : config.host, method, path, body, query, headers, options, file, cb, inputs.debug ); }
[ "function", "client", "(", "method", ",", "path", ",", "inputs", ",", "headers", ",", "file", ",", "cb", ")", "{", "var", "body", "=", "null", ";", "var", "query", "=", "{", "}", ";", "var", "options", "=", "{", "}", ";", "// It's assumed these will be provided, but just in case...", "if", "(", "!", "headers", ")", "headers", "=", "{", "}", ";", "headers", ".", "ps_client_name", "=", "clientName", ";", "headers", ".", "ps_client_version", "=", "clientVersion", ";", "// Send input params as the query string if this is a GET, otherwise send", "// with the HTTP request body", "switch", "(", "method", ".", "toLowerCase", "(", ")", ")", "{", "case", "'get'", ":", "query", "=", "inputs", ";", "break", ";", "case", "'post'", ":", "if", "(", "file", ")", "{", "query", "=", "inputs", ";", "break", ";", "}", "default", ":", "// eslint-disable-line no-fallthrough", "// Don't leave the access token on the inputs object since the jwt", "// really belongs on the query string (at least, per the way the interface", "// to the Paperspace API is currently set up).", "query", ".", "access_token", "=", "inputs", ".", "access_token", ";", "delete", "inputs", ".", "access_token", ";", "body", "=", "inputs", ";", "break", ";", "}", "// The rubber finally meets the road with 'request', which initiates", "// the request via Superagent", "return", "request", "(", "path", "===", "'/jobs/logs'", "?", "config", ".", "logHost", ":", "config", ".", "host", ",", "method", ",", "path", ",", "body", ",", "query", ",", "headers", ",", "options", ",", "file", ",", "cb", ",", "inputs", ".", "debug", ")", ";", "}" ]
Simple wrapper over the request function that inserts a 'host' parameter as the first argument, since most use cases are always going to use the same host as provided via the baked-in config.
[ "Simple", "wrapper", "over", "the", "request", "function", "that", "inserts", "a", "host", "parameter", "as", "the", "first", "argument", "since", "most", "use", "cases", "are", "always", "going", "to", "use", "the", "same", "host", "as", "provided", "via", "the", "baked", "-", "in", "config", "." ]
aed9c28610dbefb70bf382189f068182062325a6
https://github.com/Paperspace/paperspace-node/blob/aed9c28610dbefb70bf382189f068182062325a6/lib/client.js#L26-L73
20,836
cloudant/couchbackup
app.js
isSafePositiveInteger
function isSafePositiveInteger(x) { // https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; // Is it a number? return Object.prototype.toString.call(x) === '[object Number]' && // Is it an integer? x % 1 === 0 && // Is it positive? x > 0 && // Is it less than the maximum safe integer? x <= MAX_SAFE_INTEGER; }
javascript
function isSafePositiveInteger(x) { // https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; // Is it a number? return Object.prototype.toString.call(x) === '[object Number]' && // Is it an integer? x % 1 === 0 && // Is it positive? x > 0 && // Is it less than the maximum safe integer? x <= MAX_SAFE_INTEGER; }
[ "function", "isSafePositiveInteger", "(", "x", ")", "{", "// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER", "const", "MAX_SAFE_INTEGER", "=", "Number", ".", "MAX_SAFE_INTEGER", "||", "9007199254740991", ";", "// Is it a number?", "return", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "x", ")", "===", "'[object Number]'", "&&", "// Is it an integer?", "x", "%", "1", "===", "0", "&&", "// Is it positive?", "x", ">", "0", "&&", "// Is it less than the maximum safe integer?", "x", "<=", "MAX_SAFE_INTEGER", ";", "}" ]
Test for a positive, safe integer. @param {object} x - Object under test.
[ "Test", "for", "a", "positive", "safe", "integer", "." ]
73a0140a539971e97cdec0233def5db5f9d8f13b
https://github.com/cloudant/couchbackup/blob/73a0140a539971e97cdec0233def5db5f9d8f13b/app.js#L38-L49
20,837
cloudant/couchbackup
app.js
function(srcUrl, targetStream, opts, callback) { var listenerErrorIndicator = { errored: false }; if (typeof callback === 'undefined' && typeof opts === 'function') { callback = opts; opts = {}; } if (!validateArgs(srcUrl, opts, callback)) { // bad args, bail return; } // if there is an error writing to the stream, call the completion // callback with the error set addEventListener(listenerErrorIndicator, targetStream, 'error', function(err) { debug('Error ' + JSON.stringify(err)); if (callback) callback(err); }); opts = Object.assign({}, defaults(), opts); const ee = new events.EventEmitter(); // Set up the DB client const backupDB = request.client(srcUrl, opts); // Validate the DB exists, before proceeding to backup proceedIfDbValid(backupDB, function(err) { if (err) { if (err.name === 'DatabaseNotFound') { err.message = `${err.message} Ensure the backup source database exists.`; } // Didn't exist, or another fatal error, exit callback(err); return; } var backup = null; if (opts.mode === 'shallow') { backup = backupShallow; } else { // full mode backup = backupFull; } // If resuming write a newline as it's possible one would be missing from // an interruption of the previous backup. If the backup was clean this // will cause an empty line that will be gracefully handled by the restore. if (opts.resume) { targetStream.write('\n'); } // Get the event emitter from the backup process so we can handle events // before passing them on to the app's event emitter if needed. const internalEE = backup(backupDB, opts); addEventListener(listenerErrorIndicator, internalEE, 'changes', function(batch) { ee.emit('changes', batch); }); addEventListener(listenerErrorIndicator, internalEE, 'received', function(obj, q, logCompletedBatch) { // this may be too verbose to have as well as the "backed up" message // debug(' received batch', obj.batch, ' docs: ', obj.total, 'Time', obj.time); // Callback to emit the written event when the content is flushed function writeFlushed() { ee.emit('written', { total: obj.total, time: obj.time, batch: obj.batch }); if (logCompletedBatch) { logCompletedBatch(obj.batch); } debug(' backed up batch', obj.batch, ' docs: ', obj.total, 'Time', obj.time); } // Write the received content to the targetStream const continueWriting = targetStream.write(JSON.stringify(obj.data) + '\n', 'utf8', writeFlushed); if (!continueWriting) { // The buffer was full, pause the queue to stop the writes until we // get a drain event if (q && !q.isPaused) { q.pause(); targetStream.once('drain', function() { q.resume(); }); } } }); // For errors we expect, may or may not be fatal addEventListener(listenerErrorIndicator, internalEE, 'error', function(err) { debug('Error ' + JSON.stringify(err)); callback(err); }); addEventListener(listenerErrorIndicator, internalEE, 'finished', function(obj) { function emitFinished() { debug('Backup complete - written ' + JSON.stringify(obj)); const summary = { total: obj.total }; ee.emit('finished', summary); if (callback) callback(null, summary); } if (targetStream === process.stdout) { // stdout cannot emit a finish event so use a final write + callback targetStream.write('', 'utf8', emitFinished); } else { // If we're writing to a file, end the writes and register the // emitFinished function for a callback when the file stream's finish // event is emitted. targetStream.end('', 'utf8', emitFinished); } }); }); return ee; }
javascript
function(srcUrl, targetStream, opts, callback) { var listenerErrorIndicator = { errored: false }; if (typeof callback === 'undefined' && typeof opts === 'function') { callback = opts; opts = {}; } if (!validateArgs(srcUrl, opts, callback)) { // bad args, bail return; } // if there is an error writing to the stream, call the completion // callback with the error set addEventListener(listenerErrorIndicator, targetStream, 'error', function(err) { debug('Error ' + JSON.stringify(err)); if (callback) callback(err); }); opts = Object.assign({}, defaults(), opts); const ee = new events.EventEmitter(); // Set up the DB client const backupDB = request.client(srcUrl, opts); // Validate the DB exists, before proceeding to backup proceedIfDbValid(backupDB, function(err) { if (err) { if (err.name === 'DatabaseNotFound') { err.message = `${err.message} Ensure the backup source database exists.`; } // Didn't exist, or another fatal error, exit callback(err); return; } var backup = null; if (opts.mode === 'shallow') { backup = backupShallow; } else { // full mode backup = backupFull; } // If resuming write a newline as it's possible one would be missing from // an interruption of the previous backup. If the backup was clean this // will cause an empty line that will be gracefully handled by the restore. if (opts.resume) { targetStream.write('\n'); } // Get the event emitter from the backup process so we can handle events // before passing them on to the app's event emitter if needed. const internalEE = backup(backupDB, opts); addEventListener(listenerErrorIndicator, internalEE, 'changes', function(batch) { ee.emit('changes', batch); }); addEventListener(listenerErrorIndicator, internalEE, 'received', function(obj, q, logCompletedBatch) { // this may be too verbose to have as well as the "backed up" message // debug(' received batch', obj.batch, ' docs: ', obj.total, 'Time', obj.time); // Callback to emit the written event when the content is flushed function writeFlushed() { ee.emit('written', { total: obj.total, time: obj.time, batch: obj.batch }); if (logCompletedBatch) { logCompletedBatch(obj.batch); } debug(' backed up batch', obj.batch, ' docs: ', obj.total, 'Time', obj.time); } // Write the received content to the targetStream const continueWriting = targetStream.write(JSON.stringify(obj.data) + '\n', 'utf8', writeFlushed); if (!continueWriting) { // The buffer was full, pause the queue to stop the writes until we // get a drain event if (q && !q.isPaused) { q.pause(); targetStream.once('drain', function() { q.resume(); }); } } }); // For errors we expect, may or may not be fatal addEventListener(listenerErrorIndicator, internalEE, 'error', function(err) { debug('Error ' + JSON.stringify(err)); callback(err); }); addEventListener(listenerErrorIndicator, internalEE, 'finished', function(obj) { function emitFinished() { debug('Backup complete - written ' + JSON.stringify(obj)); const summary = { total: obj.total }; ee.emit('finished', summary); if (callback) callback(null, summary); } if (targetStream === process.stdout) { // stdout cannot emit a finish event so use a final write + callback targetStream.write('', 'utf8', emitFinished); } else { // If we're writing to a file, end the writes and register the // emitFinished function for a callback when the file stream's finish // event is emitted. targetStream.end('', 'utf8', emitFinished); } }); }); return ee; }
[ "function", "(", "srcUrl", ",", "targetStream", ",", "opts", ",", "callback", ")", "{", "var", "listenerErrorIndicator", "=", "{", "errored", ":", "false", "}", ";", "if", "(", "typeof", "callback", "===", "'undefined'", "&&", "typeof", "opts", "===", "'function'", ")", "{", "callback", "=", "opts", ";", "opts", "=", "{", "}", ";", "}", "if", "(", "!", "validateArgs", "(", "srcUrl", ",", "opts", ",", "callback", ")", ")", "{", "// bad args, bail", "return", ";", "}", "// if there is an error writing to the stream, call the completion", "// callback with the error set", "addEventListener", "(", "listenerErrorIndicator", ",", "targetStream", ",", "'error'", ",", "function", "(", "err", ")", "{", "debug", "(", "'Error '", "+", "JSON", ".", "stringify", "(", "err", ")", ")", ";", "if", "(", "callback", ")", "callback", "(", "err", ")", ";", "}", ")", ";", "opts", "=", "Object", ".", "assign", "(", "{", "}", ",", "defaults", "(", ")", ",", "opts", ")", ";", "const", "ee", "=", "new", "events", ".", "EventEmitter", "(", ")", ";", "// Set up the DB client", "const", "backupDB", "=", "request", ".", "client", "(", "srcUrl", ",", "opts", ")", ";", "// Validate the DB exists, before proceeding to backup", "proceedIfDbValid", "(", "backupDB", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", ".", "name", "===", "'DatabaseNotFound'", ")", "{", "err", ".", "message", "=", "`", "${", "err", ".", "message", "}", "`", ";", "}", "// Didn't exist, or another fatal error, exit", "callback", "(", "err", ")", ";", "return", ";", "}", "var", "backup", "=", "null", ";", "if", "(", "opts", ".", "mode", "===", "'shallow'", ")", "{", "backup", "=", "backupShallow", ";", "}", "else", "{", "// full mode", "backup", "=", "backupFull", ";", "}", "// If resuming write a newline as it's possible one would be missing from", "// an interruption of the previous backup. If the backup was clean this", "// will cause an empty line that will be gracefully handled by the restore.", "if", "(", "opts", ".", "resume", ")", "{", "targetStream", ".", "write", "(", "'\\n'", ")", ";", "}", "// Get the event emitter from the backup process so we can handle events", "// before passing them on to the app's event emitter if needed.", "const", "internalEE", "=", "backup", "(", "backupDB", ",", "opts", ")", ";", "addEventListener", "(", "listenerErrorIndicator", ",", "internalEE", ",", "'changes'", ",", "function", "(", "batch", ")", "{", "ee", ".", "emit", "(", "'changes'", ",", "batch", ")", ";", "}", ")", ";", "addEventListener", "(", "listenerErrorIndicator", ",", "internalEE", ",", "'received'", ",", "function", "(", "obj", ",", "q", ",", "logCompletedBatch", ")", "{", "// this may be too verbose to have as well as the \"backed up\" message", "// debug(' received batch', obj.batch, ' docs: ', obj.total, 'Time', obj.time);", "// Callback to emit the written event when the content is flushed", "function", "writeFlushed", "(", ")", "{", "ee", ".", "emit", "(", "'written'", ",", "{", "total", ":", "obj", ".", "total", ",", "time", ":", "obj", ".", "time", ",", "batch", ":", "obj", ".", "batch", "}", ")", ";", "if", "(", "logCompletedBatch", ")", "{", "logCompletedBatch", "(", "obj", ".", "batch", ")", ";", "}", "debug", "(", "' backed up batch'", ",", "obj", ".", "batch", ",", "' docs: '", ",", "obj", ".", "total", ",", "'Time'", ",", "obj", ".", "time", ")", ";", "}", "// Write the received content to the targetStream", "const", "continueWriting", "=", "targetStream", ".", "write", "(", "JSON", ".", "stringify", "(", "obj", ".", "data", ")", "+", "'\\n'", ",", "'utf8'", ",", "writeFlushed", ")", ";", "if", "(", "!", "continueWriting", ")", "{", "// The buffer was full, pause the queue to stop the writes until we", "// get a drain event", "if", "(", "q", "&&", "!", "q", ".", "isPaused", ")", "{", "q", ".", "pause", "(", ")", ";", "targetStream", ".", "once", "(", "'drain'", ",", "function", "(", ")", "{", "q", ".", "resume", "(", ")", ";", "}", ")", ";", "}", "}", "}", ")", ";", "// For errors we expect, may or may not be fatal", "addEventListener", "(", "listenerErrorIndicator", ",", "internalEE", ",", "'error'", ",", "function", "(", "err", ")", "{", "debug", "(", "'Error '", "+", "JSON", ".", "stringify", "(", "err", ")", ")", ";", "callback", "(", "err", ")", ";", "}", ")", ";", "addEventListener", "(", "listenerErrorIndicator", ",", "internalEE", ",", "'finished'", ",", "function", "(", "obj", ")", "{", "function", "emitFinished", "(", ")", "{", "debug", "(", "'Backup complete - written '", "+", "JSON", ".", "stringify", "(", "obj", ")", ")", ";", "const", "summary", "=", "{", "total", ":", "obj", ".", "total", "}", ";", "ee", ".", "emit", "(", "'finished'", ",", "summary", ")", ";", "if", "(", "callback", ")", "callback", "(", "null", ",", "summary", ")", ";", "}", "if", "(", "targetStream", "===", "process", ".", "stdout", ")", "{", "// stdout cannot emit a finish event so use a final write + callback", "targetStream", ".", "write", "(", "''", ",", "'utf8'", ",", "emitFinished", ")", ";", "}", "else", "{", "// If we're writing to a file, end the writes and register the", "// emitFinished function for a callback when the file stream's finish", "// event is emitted.", "targetStream", ".", "end", "(", "''", ",", "'utf8'", ",", "emitFinished", ")", ";", "}", "}", ")", ";", "}", ")", ";", "return", "ee", ";", "}" ]
Backup a Cloudant database to a stream. @param {string} srcUrl - URL of database to backup. @param {stream.Writable} targetStream - Stream to write content to. @param {object} opts - Backup options. @param {number} [opts.parallelism=5] - Number of parallel HTTP requests to use. @param {number} [opts.bufferSize=500] - Number of documents per batch request. @param {number} [opts.requestTimeout=120000] - Milliseconds to wait before retrying a HTTP request. @param {string} [opts.iamApiKey] - IAM API key to use to access Cloudant database. @param {string} [opts.log] - Log file name. Default uses a temporary file. @param {boolean} [opts.resume] - Whether to resume from existing log. @param {string} [opts.mode=full] - Use `full` or `shallow` mode. @param {backupRestoreCallback} callback - Called on completion.
[ "Backup", "a", "Cloudant", "database", "to", "a", "stream", "." ]
73a0140a539971e97cdec0233def5db5f9d8f13b
https://github.com/cloudant/couchbackup/blob/73a0140a539971e97cdec0233def5db5f9d8f13b/app.js#L200-L305
20,838
cloudant/couchbackup
app.js
function(srcStream, targetUrl, opts, callback) { var listenerErrorIndicator = { errored: false }; if (typeof callback === 'undefined' && typeof opts === 'function') { callback = opts; opts = {}; } validateArgs(targetUrl, opts, callback); opts = Object.assign({}, defaults(), opts); const ee = new events.EventEmitter(); // Set up the DB client const restoreDB = request.client(targetUrl, opts); // Validate the DB exists, before proceeding to restore proceedIfDbValid(restoreDB, function(err) { if (err) { if (err.name === 'DatabaseNotFound') { err.message = `${err.message} Create the target database before restoring.`; } // Didn't exist, or another fatal error, exit callback(err); return; } restoreInternal( restoreDB, opts, srcStream, ee, function(err, writer) { if (err) { callback(err, null); return; } if (writer != null) { addEventListener(listenerErrorIndicator, writer, 'restored', function(obj) { debug(' restored ', obj.total); ee.emit('restored', { documents: obj.documents, total: obj.total }); }); addEventListener(listenerErrorIndicator, writer, 'error', function(err) { debug('Error ' + JSON.stringify(err)); // Only call destroy if it is available on the stream if (srcStream.destroy && srcStream.destroy instanceof Function) { srcStream.destroy(); } callback(err); }); addEventListener(listenerErrorIndicator, writer, 'finished', function(obj) { debug('restore complete'); ee.emit('finished', { total: obj.total }); callback(null, obj); }); } } ); }); return ee; }
javascript
function(srcStream, targetUrl, opts, callback) { var listenerErrorIndicator = { errored: false }; if (typeof callback === 'undefined' && typeof opts === 'function') { callback = opts; opts = {}; } validateArgs(targetUrl, opts, callback); opts = Object.assign({}, defaults(), opts); const ee = new events.EventEmitter(); // Set up the DB client const restoreDB = request.client(targetUrl, opts); // Validate the DB exists, before proceeding to restore proceedIfDbValid(restoreDB, function(err) { if (err) { if (err.name === 'DatabaseNotFound') { err.message = `${err.message} Create the target database before restoring.`; } // Didn't exist, or another fatal error, exit callback(err); return; } restoreInternal( restoreDB, opts, srcStream, ee, function(err, writer) { if (err) { callback(err, null); return; } if (writer != null) { addEventListener(listenerErrorIndicator, writer, 'restored', function(obj) { debug(' restored ', obj.total); ee.emit('restored', { documents: obj.documents, total: obj.total }); }); addEventListener(listenerErrorIndicator, writer, 'error', function(err) { debug('Error ' + JSON.stringify(err)); // Only call destroy if it is available on the stream if (srcStream.destroy && srcStream.destroy instanceof Function) { srcStream.destroy(); } callback(err); }); addEventListener(listenerErrorIndicator, writer, 'finished', function(obj) { debug('restore complete'); ee.emit('finished', { total: obj.total }); callback(null, obj); }); } } ); }); return ee; }
[ "function", "(", "srcStream", ",", "targetUrl", ",", "opts", ",", "callback", ")", "{", "var", "listenerErrorIndicator", "=", "{", "errored", ":", "false", "}", ";", "if", "(", "typeof", "callback", "===", "'undefined'", "&&", "typeof", "opts", "===", "'function'", ")", "{", "callback", "=", "opts", ";", "opts", "=", "{", "}", ";", "}", "validateArgs", "(", "targetUrl", ",", "opts", ",", "callback", ")", ";", "opts", "=", "Object", ".", "assign", "(", "{", "}", ",", "defaults", "(", ")", ",", "opts", ")", ";", "const", "ee", "=", "new", "events", ".", "EventEmitter", "(", ")", ";", "// Set up the DB client", "const", "restoreDB", "=", "request", ".", "client", "(", "targetUrl", ",", "opts", ")", ";", "// Validate the DB exists, before proceeding to restore", "proceedIfDbValid", "(", "restoreDB", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", ".", "name", "===", "'DatabaseNotFound'", ")", "{", "err", ".", "message", "=", "`", "${", "err", ".", "message", "}", "`", ";", "}", "// Didn't exist, or another fatal error, exit", "callback", "(", "err", ")", ";", "return", ";", "}", "restoreInternal", "(", "restoreDB", ",", "opts", ",", "srcStream", ",", "ee", ",", "function", "(", "err", ",", "writer", ")", "{", "if", "(", "err", ")", "{", "callback", "(", "err", ",", "null", ")", ";", "return", ";", "}", "if", "(", "writer", "!=", "null", ")", "{", "addEventListener", "(", "listenerErrorIndicator", ",", "writer", ",", "'restored'", ",", "function", "(", "obj", ")", "{", "debug", "(", "' restored '", ",", "obj", ".", "total", ")", ";", "ee", ".", "emit", "(", "'restored'", ",", "{", "documents", ":", "obj", ".", "documents", ",", "total", ":", "obj", ".", "total", "}", ")", ";", "}", ")", ";", "addEventListener", "(", "listenerErrorIndicator", ",", "writer", ",", "'error'", ",", "function", "(", "err", ")", "{", "debug", "(", "'Error '", "+", "JSON", ".", "stringify", "(", "err", ")", ")", ";", "// Only call destroy if it is available on the stream", "if", "(", "srcStream", ".", "destroy", "&&", "srcStream", ".", "destroy", "instanceof", "Function", ")", "{", "srcStream", ".", "destroy", "(", ")", ";", "}", "callback", "(", "err", ")", ";", "}", ")", ";", "addEventListener", "(", "listenerErrorIndicator", ",", "writer", ",", "'finished'", ",", "function", "(", "obj", ")", "{", "debug", "(", "'restore complete'", ")", ";", "ee", ".", "emit", "(", "'finished'", ",", "{", "total", ":", "obj", ".", "total", "}", ")", ";", "callback", "(", "null", ",", "obj", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}", ")", ";", "return", "ee", ";", "}" ]
Restore a backup from a stream. @param {stream.Readable} srcStream - Stream containing backed up data. @param {string} targetUrl - Target database. @param {object} opts - Restore options. @param {number} opts.parallelism - Number of parallel HTTP requests to use. Default 5. @param {number} opts.bufferSize - Number of documents per batch request. Default 500. @param {number} opts.requestTimeout - Milliseconds to wait before retrying a HTTP request. Default 120000. @param {string} opts.iamApiKey - IAM API key to use to access Cloudant database. @param {backupRestoreCallback} callback - Called on completion.
[ "Restore", "a", "backup", "from", "a", "stream", "." ]
73a0140a539971e97cdec0233def5db5f9d8f13b
https://github.com/cloudant/couchbackup/blob/73a0140a539971e97cdec0233def5db5f9d8f13b/app.js#L319-L377
20,839
cloudant/couchbackup
includes/backup.js
downloadRemainingBatches
function downloadRemainingBatches(log, db, ee, startTime, batchesPerDownloadSession, parallelism) { var total = 0; // running total of documents downloaded so far var noRemainingBatches = false; // Generate a set of batches (up to batchesPerDownloadSession) to download from the // log file and download them. Set noRemainingBatches to `true` for last batch. function downloadSingleBatchSet(done) { // Fetch the doc IDs for the batches in the current set to // download them. function batchSetComplete(err, data) { total = data.total; done(); } function processRetrievedBatches(err, batches) { // process them in parallelised queue processBatchSet(db, parallelism, log, batches, ee, startTime, total, batchSetComplete); } readBatchSetIdsFromLogFile(log, batchesPerDownloadSession, function(err, batchSetIds) { if (err) { ee.emit('error', err); // Stop processing changes file for fatal errors noRemainingBatches = true; done(); } else { if (batchSetIds.length === 0) { noRemainingBatches = true; return done(); } logfilegetbatches(log, batchSetIds, processRetrievedBatches); } }); } // Return true if all batches in log file have been downloaded function isFinished() { return noRemainingBatches; } function onComplete() { ee.emit('finished', { total: total }); } async.doUntil(downloadSingleBatchSet, isFinished, onComplete); }
javascript
function downloadRemainingBatches(log, db, ee, startTime, batchesPerDownloadSession, parallelism) { var total = 0; // running total of documents downloaded so far var noRemainingBatches = false; // Generate a set of batches (up to batchesPerDownloadSession) to download from the // log file and download them. Set noRemainingBatches to `true` for last batch. function downloadSingleBatchSet(done) { // Fetch the doc IDs for the batches in the current set to // download them. function batchSetComplete(err, data) { total = data.total; done(); } function processRetrievedBatches(err, batches) { // process them in parallelised queue processBatchSet(db, parallelism, log, batches, ee, startTime, total, batchSetComplete); } readBatchSetIdsFromLogFile(log, batchesPerDownloadSession, function(err, batchSetIds) { if (err) { ee.emit('error', err); // Stop processing changes file for fatal errors noRemainingBatches = true; done(); } else { if (batchSetIds.length === 0) { noRemainingBatches = true; return done(); } logfilegetbatches(log, batchSetIds, processRetrievedBatches); } }); } // Return true if all batches in log file have been downloaded function isFinished() { return noRemainingBatches; } function onComplete() { ee.emit('finished', { total: total }); } async.doUntil(downloadSingleBatchSet, isFinished, onComplete); }
[ "function", "downloadRemainingBatches", "(", "log", ",", "db", ",", "ee", ",", "startTime", ",", "batchesPerDownloadSession", ",", "parallelism", ")", "{", "var", "total", "=", "0", ";", "// running total of documents downloaded so far", "var", "noRemainingBatches", "=", "false", ";", "// Generate a set of batches (up to batchesPerDownloadSession) to download from the", "// log file and download them. Set noRemainingBatches to `true` for last batch.", "function", "downloadSingleBatchSet", "(", "done", ")", "{", "// Fetch the doc IDs for the batches in the current set to", "// download them.", "function", "batchSetComplete", "(", "err", ",", "data", ")", "{", "total", "=", "data", ".", "total", ";", "done", "(", ")", ";", "}", "function", "processRetrievedBatches", "(", "err", ",", "batches", ")", "{", "// process them in parallelised queue", "processBatchSet", "(", "db", ",", "parallelism", ",", "log", ",", "batches", ",", "ee", ",", "startTime", ",", "total", ",", "batchSetComplete", ")", ";", "}", "readBatchSetIdsFromLogFile", "(", "log", ",", "batchesPerDownloadSession", ",", "function", "(", "err", ",", "batchSetIds", ")", "{", "if", "(", "err", ")", "{", "ee", ".", "emit", "(", "'error'", ",", "err", ")", ";", "// Stop processing changes file for fatal errors", "noRemainingBatches", "=", "true", ";", "done", "(", ")", ";", "}", "else", "{", "if", "(", "batchSetIds", ".", "length", "===", "0", ")", "{", "noRemainingBatches", "=", "true", ";", "return", "done", "(", ")", ";", "}", "logfilegetbatches", "(", "log", ",", "batchSetIds", ",", "processRetrievedBatches", ")", ";", "}", "}", ")", ";", "}", "// Return true if all batches in log file have been downloaded", "function", "isFinished", "(", ")", "{", "return", "noRemainingBatches", ";", "}", "function", "onComplete", "(", ")", "{", "ee", ".", "emit", "(", "'finished'", ",", "{", "total", ":", "total", "}", ")", ";", "}", "async", ".", "doUntil", "(", "downloadSingleBatchSet", ",", "isFinished", ",", "onComplete", ")", ";", "}" ]
Download remaining batches in a log file, splitting batches into sets to avoid enqueueing too many in one go. @param {string} log - log file name to maintain download state @param {string} db - nodejs-cloudant db @param {events.EventEmitter} ee - event emitter to emit received events on @param {time} startTime - start time for backup process @param {number} batchesPerDownloadSession - max batches to enqueue for download at a time. As batches contain many doc IDs, this helps avoid exhausting memory. @param {number} parallelism - number of concurrent downloads @returns function to call do download remaining batches with signature (err, {batches: batch, docs: doccount}) {@see spoolchanges}.
[ "Download", "remaining", "batches", "in", "a", "log", "file", "splitting", "batches", "into", "sets", "to", "avoid", "enqueueing", "too", "many", "in", "one", "go", "." ]
73a0140a539971e97cdec0233def5db5f9d8f13b
https://github.com/cloudant/couchbackup/blob/73a0140a539971e97cdec0233def5db5f9d8f13b/includes/backup.js#L111-L153
20,840
cloudant/couchbackup
includes/backup.js
readBatchSetIdsFromLogFile
function readBatchSetIdsFromLogFile(log, batchesPerDownloadSession, callback) { logfilesummary(log, function processSummary(err, summary) { if (!summary.changesComplete) { callback(new error.BackupError('IncompleteChangesInLogFile', 'WARNING: Changes did not finish spooling')); return; } if (Object.keys(summary.batches).length === 0) { return callback(null, []); } // batch IDs are the property names of summary.batches var batchSetIds = getPropertyNames(summary.batches, batchesPerDownloadSession); callback(null, batchSetIds); }); }
javascript
function readBatchSetIdsFromLogFile(log, batchesPerDownloadSession, callback) { logfilesummary(log, function processSummary(err, summary) { if (!summary.changesComplete) { callback(new error.BackupError('IncompleteChangesInLogFile', 'WARNING: Changes did not finish spooling')); return; } if (Object.keys(summary.batches).length === 0) { return callback(null, []); } // batch IDs are the property names of summary.batches var batchSetIds = getPropertyNames(summary.batches, batchesPerDownloadSession); callback(null, batchSetIds); }); }
[ "function", "readBatchSetIdsFromLogFile", "(", "log", ",", "batchesPerDownloadSession", ",", "callback", ")", "{", "logfilesummary", "(", "log", ",", "function", "processSummary", "(", "err", ",", "summary", ")", "{", "if", "(", "!", "summary", ".", "changesComplete", ")", "{", "callback", "(", "new", "error", ".", "BackupError", "(", "'IncompleteChangesInLogFile'", ",", "'WARNING: Changes did not finish spooling'", ")", ")", ";", "return", ";", "}", "if", "(", "Object", ".", "keys", "(", "summary", ".", "batches", ")", ".", "length", "===", "0", ")", "{", "return", "callback", "(", "null", ",", "[", "]", ")", ";", "}", "// batch IDs are the property names of summary.batches", "var", "batchSetIds", "=", "getPropertyNames", "(", "summary", ".", "batches", ",", "batchesPerDownloadSession", ")", ";", "callback", "(", "null", ",", "batchSetIds", ")", ";", "}", ")", ";", "}" ]
Return a set of uncompleted download batch IDs from the log file. @param {string} log - log file path @param {number} batchesPerDownloadSession - maximum IDs to return @param {function} callback - sign (err, batchSetIds array)
[ "Return", "a", "set", "of", "uncompleted", "download", "batch", "IDs", "from", "the", "log", "file", "." ]
73a0140a539971e97cdec0233def5db5f9d8f13b
https://github.com/cloudant/couchbackup/blob/73a0140a539971e97cdec0233def5db5f9d8f13b/includes/backup.js#L162-L177
20,841
cloudant/couchbackup
includes/backup.js
processBatchSet
function processBatchSet(db, parallelism, log, batches, ee, start, grandtotal, callback) { var hasErrored = false; var total = grandtotal; // queue to process the fetch requests in an orderly fashion using _bulk_get var q = async.queue(function(payload, done) { var output = []; var thisBatch = payload.batch; delete payload.batch; delete payload.command; function logCompletedBatch(batch) { if (log) { fs.appendFile(log, ':d batch' + thisBatch + '\n', done); } else { done(); } } // do the /db/_bulk_get request // Note: this should use built-in _bulk_get, but revs is not accepted as // part of the request body by the server yet. Working around using request // method to POST with a query string. db.server.request( { method: 'POST', db: db.config.db, path: '_bulk_get', qs: { revs: true }, body: payload }, function(err, body) { if (err) { if (!hasErrored) { hasErrored = true; err = error.convertResponseError(err); // Kill the queue for fatal errors q.kill(); ee.emit('error', err); } done(); } else { // create an output array with the docs returned body.results.forEach(function(d) { if (d.docs) { d.docs.forEach(function(doc) { if (doc.ok) { output.push(doc.ok); } }); } }); total += output.length; var t = (new Date().getTime() - start) / 1000; ee.emit('received', { batch: thisBatch, data: output, length: output.length, time: t, total: total }, q, logCompletedBatch); } }); }, parallelism); for (var i in batches) { q.push(batches[i]); } q.drain = function() { callback(null, { total: total }); }; }
javascript
function processBatchSet(db, parallelism, log, batches, ee, start, grandtotal, callback) { var hasErrored = false; var total = grandtotal; // queue to process the fetch requests in an orderly fashion using _bulk_get var q = async.queue(function(payload, done) { var output = []; var thisBatch = payload.batch; delete payload.batch; delete payload.command; function logCompletedBatch(batch) { if (log) { fs.appendFile(log, ':d batch' + thisBatch + '\n', done); } else { done(); } } // do the /db/_bulk_get request // Note: this should use built-in _bulk_get, but revs is not accepted as // part of the request body by the server yet. Working around using request // method to POST with a query string. db.server.request( { method: 'POST', db: db.config.db, path: '_bulk_get', qs: { revs: true }, body: payload }, function(err, body) { if (err) { if (!hasErrored) { hasErrored = true; err = error.convertResponseError(err); // Kill the queue for fatal errors q.kill(); ee.emit('error', err); } done(); } else { // create an output array with the docs returned body.results.forEach(function(d) { if (d.docs) { d.docs.forEach(function(doc) { if (doc.ok) { output.push(doc.ok); } }); } }); total += output.length; var t = (new Date().getTime() - start) / 1000; ee.emit('received', { batch: thisBatch, data: output, length: output.length, time: t, total: total }, q, logCompletedBatch); } }); }, parallelism); for (var i in batches) { q.push(batches[i]); } q.drain = function() { callback(null, { total: total }); }; }
[ "function", "processBatchSet", "(", "db", ",", "parallelism", ",", "log", ",", "batches", ",", "ee", ",", "start", ",", "grandtotal", ",", "callback", ")", "{", "var", "hasErrored", "=", "false", ";", "var", "total", "=", "grandtotal", ";", "// queue to process the fetch requests in an orderly fashion using _bulk_get", "var", "q", "=", "async", ".", "queue", "(", "function", "(", "payload", ",", "done", ")", "{", "var", "output", "=", "[", "]", ";", "var", "thisBatch", "=", "payload", ".", "batch", ";", "delete", "payload", ".", "batch", ";", "delete", "payload", ".", "command", ";", "function", "logCompletedBatch", "(", "batch", ")", "{", "if", "(", "log", ")", "{", "fs", ".", "appendFile", "(", "log", ",", "':d batch'", "+", "thisBatch", "+", "'\\n'", ",", "done", ")", ";", "}", "else", "{", "done", "(", ")", ";", "}", "}", "// do the /db/_bulk_get request", "// Note: this should use built-in _bulk_get, but revs is not accepted as", "// part of the request body by the server yet. Working around using request", "// method to POST with a query string.", "db", ".", "server", ".", "request", "(", "{", "method", ":", "'POST'", ",", "db", ":", "db", ".", "config", ".", "db", ",", "path", ":", "'_bulk_get'", ",", "qs", ":", "{", "revs", ":", "true", "}", ",", "body", ":", "payload", "}", ",", "function", "(", "err", ",", "body", ")", "{", "if", "(", "err", ")", "{", "if", "(", "!", "hasErrored", ")", "{", "hasErrored", "=", "true", ";", "err", "=", "error", ".", "convertResponseError", "(", "err", ")", ";", "// Kill the queue for fatal errors", "q", ".", "kill", "(", ")", ";", "ee", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", "done", "(", ")", ";", "}", "else", "{", "// create an output array with the docs returned", "body", ".", "results", ".", "forEach", "(", "function", "(", "d", ")", "{", "if", "(", "d", ".", "docs", ")", "{", "d", ".", "docs", ".", "forEach", "(", "function", "(", "doc", ")", "{", "if", "(", "doc", ".", "ok", ")", "{", "output", ".", "push", "(", "doc", ".", "ok", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "total", "+=", "output", ".", "length", ";", "var", "t", "=", "(", "new", "Date", "(", ")", ".", "getTime", "(", ")", "-", "start", ")", "/", "1000", ";", "ee", ".", "emit", "(", "'received'", ",", "{", "batch", ":", "thisBatch", ",", "data", ":", "output", ",", "length", ":", "output", ".", "length", ",", "time", ":", "t", ",", "total", ":", "total", "}", ",", "q", ",", "logCompletedBatch", ")", ";", "}", "}", ")", ";", "}", ",", "parallelism", ")", ";", "for", "(", "var", "i", "in", "batches", ")", "{", "q", ".", "push", "(", "batches", "[", "i", "]", ")", ";", "}", "q", ".", "drain", "=", "function", "(", ")", "{", "callback", "(", "null", ",", "{", "total", ":", "total", "}", ")", ";", "}", ";", "}" ]
Download a set of batches retrieved from a log file. When a download is complete, add a line to the logfile indicating such. @param {any} db - nodejs-cloudant database @param {any} parallelism - number of concurrent requests to make @param {any} log - log file to drive downloads from @param {any} batches - batches to download @param {any} ee - event emitter for progress. This funciton emits received and error events. @param {any} start - time backup started, to report deltas @param {any} grandtotal - count of documents downloaded prior to this set of batches @param {any} callback - completion callback, (err, {total: number}).
[ "Download", "a", "set", "of", "batches", "retrieved", "from", "a", "log", "file", ".", "When", "a", "download", "is", "complete", "add", "a", "line", "to", "the", "logfile", "indicating", "such", "." ]
73a0140a539971e97cdec0233def5db5f9d8f13b
https://github.com/cloudant/couchbackup/blob/73a0140a539971e97cdec0233def5db5f9d8f13b/includes/backup.js#L194-L260
20,842
cloudant/couchbackup
includes/backup.js
getPropertyNames
function getPropertyNames(obj, count) { // decide which batch numbers to deal with var batchestofetch = []; var j = 0; for (var i in obj) { batchestofetch.push(parseInt(i)); j++; if (j >= count) break; } return batchestofetch; }
javascript
function getPropertyNames(obj, count) { // decide which batch numbers to deal with var batchestofetch = []; var j = 0; for (var i in obj) { batchestofetch.push(parseInt(i)); j++; if (j >= count) break; } return batchestofetch; }
[ "function", "getPropertyNames", "(", "obj", ",", "count", ")", "{", "// decide which batch numbers to deal with", "var", "batchestofetch", "=", "[", "]", ";", "var", "j", "=", "0", ";", "for", "(", "var", "i", "in", "obj", ")", "{", "batchestofetch", ".", "push", "(", "parseInt", "(", "i", ")", ")", ";", "j", "++", ";", "if", "(", "j", ">=", "count", ")", "break", ";", "}", "return", "batchestofetch", ";", "}" ]
Returns first N properties on an object. @param {object} obj - object with properties @param {number} count - number of properties to return
[ "Returns", "first", "N", "properties", "on", "an", "object", "." ]
73a0140a539971e97cdec0233def5db5f9d8f13b
https://github.com/cloudant/couchbackup/blob/73a0140a539971e97cdec0233def5db5f9d8f13b/includes/backup.js#L268-L278
20,843
cloudant/couchbackup
examples/s3-backup-stream.js
bucketAccessible
function bucketAccessible(s3, bucketName) { return new Promise(function(resolve, reject) { var params = { Bucket: bucketName }; s3.headBucket(params, function(err, data) { if (err) { reject(new VError(err, 'S3 bucket not accessible')); } else { resolve(); } }); }); }
javascript
function bucketAccessible(s3, bucketName) { return new Promise(function(resolve, reject) { var params = { Bucket: bucketName }; s3.headBucket(params, function(err, data) { if (err) { reject(new VError(err, 'S3 bucket not accessible')); } else { resolve(); } }); }); }
[ "function", "bucketAccessible", "(", "s3", ",", "bucketName", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "params", "=", "{", "Bucket", ":", "bucketName", "}", ";", "s3", ".", "headBucket", "(", "params", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "reject", "(", "new", "VError", "(", "err", ",", "'S3 bucket not accessible'", ")", ")", ";", "}", "else", "{", "resolve", "(", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Return a promise that resolves if the bucket is available and rejects if not. @param {any} s3 S3 client object @param {any} bucketName Bucket name @returns Promise
[ "Return", "a", "promise", "that", "resolves", "if", "the", "bucket", "is", "available", "and", "rejects", "if", "not", "." ]
73a0140a539971e97cdec0233def5db5f9d8f13b
https://github.com/cloudant/couchbackup/blob/73a0140a539971e97cdec0233def5db5f9d8f13b/examples/s3-backup-stream.js#L92-L105
20,844
cloudant/couchbackup
examples/s3-backup-stream.js
backupToS3
function backupToS3(sourceUrl, s3Client, s3Bucket, s3Key, shallow) { return new Promise((resolve, reject) => { debug(`Setting up S3 upload to ${s3Bucket}/${s3Key}`); // A pass through stream that has couchbackup's output // written to it and it then read by the S3 upload client. // It has a 64MB highwater mark to allow for fairly // uneven network connectivity. const streamToUpload = new stream.PassThrough({ highWaterMark: 67108864 }); // Set up S3 upload. const params = { Bucket: s3Bucket, Key: s3Key, Body: streamToUpload }; s3Client.upload(params, function(err, data) { debug('Object store upload done'); if (err) { debug(err); reject(new VError(err, 'Object store upload failed')); return; } debug('Object store upload succeeded'); debug(data); resolve(); }).httpUploadProgress = (progress) => { debug(`Object store upload progress: ${progress}`); }; debug(`Starting streaming data from ${s(sourceUrl)}`); couchbackup.backup( sourceUrl, streamToUpload, (err, obj) => { if (err) { debug(err); reject(new VError(err, 'CouchBackup failed with an error')); return; } debug(`Download from ${s(sourceUrl)} complete.`); streamToUpload.end(); // must call end() to complete upload. // resolve() is called by the upload } ); }); }
javascript
function backupToS3(sourceUrl, s3Client, s3Bucket, s3Key, shallow) { return new Promise((resolve, reject) => { debug(`Setting up S3 upload to ${s3Bucket}/${s3Key}`); // A pass through stream that has couchbackup's output // written to it and it then read by the S3 upload client. // It has a 64MB highwater mark to allow for fairly // uneven network connectivity. const streamToUpload = new stream.PassThrough({ highWaterMark: 67108864 }); // Set up S3 upload. const params = { Bucket: s3Bucket, Key: s3Key, Body: streamToUpload }; s3Client.upload(params, function(err, data) { debug('Object store upload done'); if (err) { debug(err); reject(new VError(err, 'Object store upload failed')); return; } debug('Object store upload succeeded'); debug(data); resolve(); }).httpUploadProgress = (progress) => { debug(`Object store upload progress: ${progress}`); }; debug(`Starting streaming data from ${s(sourceUrl)}`); couchbackup.backup( sourceUrl, streamToUpload, (err, obj) => { if (err) { debug(err); reject(new VError(err, 'CouchBackup failed with an error')); return; } debug(`Download from ${s(sourceUrl)} complete.`); streamToUpload.end(); // must call end() to complete upload. // resolve() is called by the upload } ); }); }
[ "function", "backupToS3", "(", "sourceUrl", ",", "s3Client", ",", "s3Bucket", ",", "s3Key", ",", "shallow", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "debug", "(", "`", "${", "s3Bucket", "}", "${", "s3Key", "}", "`", ")", ";", "// A pass through stream that has couchbackup's output", "// written to it and it then read by the S3 upload client.", "// It has a 64MB highwater mark to allow for fairly", "// uneven network connectivity.", "const", "streamToUpload", "=", "new", "stream", ".", "PassThrough", "(", "{", "highWaterMark", ":", "67108864", "}", ")", ";", "// Set up S3 upload.", "const", "params", "=", "{", "Bucket", ":", "s3Bucket", ",", "Key", ":", "s3Key", ",", "Body", ":", "streamToUpload", "}", ";", "s3Client", ".", "upload", "(", "params", ",", "function", "(", "err", ",", "data", ")", "{", "debug", "(", "'Object store upload done'", ")", ";", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "reject", "(", "new", "VError", "(", "err", ",", "'Object store upload failed'", ")", ")", ";", "return", ";", "}", "debug", "(", "'Object store upload succeeded'", ")", ";", "debug", "(", "data", ")", ";", "resolve", "(", ")", ";", "}", ")", ".", "httpUploadProgress", "=", "(", "progress", ")", "=>", "{", "debug", "(", "`", "${", "progress", "}", "`", ")", ";", "}", ";", "debug", "(", "`", "${", "s", "(", "sourceUrl", ")", "}", "`", ")", ";", "couchbackup", ".", "backup", "(", "sourceUrl", ",", "streamToUpload", ",", "(", "err", ",", "obj", ")", "=>", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "reject", "(", "new", "VError", "(", "err", ",", "'CouchBackup failed with an error'", ")", ")", ";", "return", ";", "}", "debug", "(", "`", "${", "s", "(", "sourceUrl", ")", "}", "`", ")", ";", "streamToUpload", ".", "end", "(", ")", ";", "// must call end() to complete upload.", "// resolve() is called by the upload", "}", ")", ";", "}", ")", ";", "}" ]
Backup directly from Cloudant to an object store object via a stream. @param {any} sourceUrl URL of database @param {any} s3Client Object store client @param {any} s3Bucket Backup destination bucket @param {any} s3Key Backup destination key name (shouldn't exist) @param {any} shallow Whether to use the couchbackup `shallow` mode @returns Promise
[ "Backup", "directly", "from", "Cloudant", "to", "an", "object", "store", "object", "via", "a", "stream", "." ]
73a0140a539971e97cdec0233def5db5f9d8f13b
https://github.com/cloudant/couchbackup/blob/73a0140a539971e97cdec0233def5db5f9d8f13b/examples/s3-backup-stream.js#L117-L163
20,845
cloudant/couchbackup
includes/logfilesummary.js
function(obj) { if (obj.command === 't') { state[obj.batch] = true; } else if (obj.command === 'd') { delete state[obj.batch]; } else if (obj.command === 'changes_complete') { changesComplete = true; } }
javascript
function(obj) { if (obj.command === 't') { state[obj.batch] = true; } else if (obj.command === 'd') { delete state[obj.batch]; } else if (obj.command === 'changes_complete') { changesComplete = true; } }
[ "function", "(", "obj", ")", "{", "if", "(", "obj", ".", "command", "===", "'t'", ")", "{", "state", "[", "obj", ".", "batch", "]", "=", "true", ";", "}", "else", "if", "(", "obj", ".", "command", "===", "'d'", ")", "{", "delete", "state", "[", "obj", ".", "batch", "]", ";", "}", "else", "if", "(", "obj", ".", "command", "===", "'changes_complete'", ")", "{", "changesComplete", "=", "true", ";", "}", "}" ]
called with each line from the log file
[ "called", "with", "each", "line", "from", "the", "log", "file" ]
73a0140a539971e97cdec0233def5db5f9d8f13b
https://github.com/cloudant/couchbackup/blob/73a0140a539971e97cdec0233def5db5f9d8f13b/includes/logfilesummary.js#L74-L82
20,846
cloudant/couchbackup
examples/s3-backup-file.js
createBackupFile
function createBackupFile(sourceUrl, backupTmpFilePath) { return new Promise((resolve, reject) => { couchbackup.backup( sourceUrl, fs.createWriteStream(backupTmpFilePath), (err) => { if (err) { return reject(new VError(err, 'CouchBackup process failed')); } debug('couchbackup to file done; uploading to S3'); resolve('creating backup file complete'); } ); }); }
javascript
function createBackupFile(sourceUrl, backupTmpFilePath) { return new Promise((resolve, reject) => { couchbackup.backup( sourceUrl, fs.createWriteStream(backupTmpFilePath), (err) => { if (err) { return reject(new VError(err, 'CouchBackup process failed')); } debug('couchbackup to file done; uploading to S3'); resolve('creating backup file complete'); } ); }); }
[ "function", "createBackupFile", "(", "sourceUrl", ",", "backupTmpFilePath", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "couchbackup", ".", "backup", "(", "sourceUrl", ",", "fs", ".", "createWriteStream", "(", "backupTmpFilePath", ")", ",", "(", "err", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "reject", "(", "new", "VError", "(", "err", ",", "'CouchBackup process failed'", ")", ")", ";", "}", "debug", "(", "'couchbackup to file done; uploading to S3'", ")", ";", "resolve", "(", "'creating backup file complete'", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Use couchbackup to create a backup of the specified database to a file path. @param {any} sourceUrl Database URL @param {any} backupTmpFilePath Path to write file @returns Promise
[ "Use", "couchbackup", "to", "create", "a", "backup", "of", "the", "specified", "database", "to", "a", "file", "path", "." ]
73a0140a539971e97cdec0233def5db5f9d8f13b
https://github.com/cloudant/couchbackup/blob/73a0140a539971e97cdec0233def5db5f9d8f13b/examples/s3-backup-file.js#L120-L134
20,847
cloudant/couchbackup
examples/s3-backup-file.js
uploadNewBackup
function uploadNewBackup(s3, backupTmpFilePath, bucket, key) { return new Promise((resolve, reject) => { debug(`Uploading from ${backupTmpFilePath} to ${bucket}/${key}`); function uploadFromStream(s3, bucket, key) { const pass = new stream.PassThrough(); const params = { Bucket: bucket, Key: key, Body: pass }; s3.upload(params, function(err, data) { debug('S3 upload done'); if (err) { debug(err); reject(new VError(err, 'Upload failed')); return; } debug('Upload succeeded'); debug(data); resolve(); }).httpUploadProgress = (progress) => { debug(`S3 upload progress: ${progress}`); }; return pass; } const inputStream = fs.createReadStream(backupTmpFilePath); const s3Stream = uploadFromStream(s3, bucket, key); inputStream.pipe(s3Stream); }); }
javascript
function uploadNewBackup(s3, backupTmpFilePath, bucket, key) { return new Promise((resolve, reject) => { debug(`Uploading from ${backupTmpFilePath} to ${bucket}/${key}`); function uploadFromStream(s3, bucket, key) { const pass = new stream.PassThrough(); const params = { Bucket: bucket, Key: key, Body: pass }; s3.upload(params, function(err, data) { debug('S3 upload done'); if (err) { debug(err); reject(new VError(err, 'Upload failed')); return; } debug('Upload succeeded'); debug(data); resolve(); }).httpUploadProgress = (progress) => { debug(`S3 upload progress: ${progress}`); }; return pass; } const inputStream = fs.createReadStream(backupTmpFilePath); const s3Stream = uploadFromStream(s3, bucket, key); inputStream.pipe(s3Stream); }); }
[ "function", "uploadNewBackup", "(", "s3", ",", "backupTmpFilePath", ",", "bucket", ",", "key", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "debug", "(", "`", "${", "backupTmpFilePath", "}", "${", "bucket", "}", "${", "key", "}", "`", ")", ";", "function", "uploadFromStream", "(", "s3", ",", "bucket", ",", "key", ")", "{", "const", "pass", "=", "new", "stream", ".", "PassThrough", "(", ")", ";", "const", "params", "=", "{", "Bucket", ":", "bucket", ",", "Key", ":", "key", ",", "Body", ":", "pass", "}", ";", "s3", ".", "upload", "(", "params", ",", "function", "(", "err", ",", "data", ")", "{", "debug", "(", "'S3 upload done'", ")", ";", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "reject", "(", "new", "VError", "(", "err", ",", "'Upload failed'", ")", ")", ";", "return", ";", "}", "debug", "(", "'Upload succeeded'", ")", ";", "debug", "(", "data", ")", ";", "resolve", "(", ")", ";", "}", ")", ".", "httpUploadProgress", "=", "(", "progress", ")", "=>", "{", "debug", "(", "`", "${", "progress", "}", "`", ")", ";", "}", ";", "return", "pass", ";", "}", "const", "inputStream", "=", "fs", ".", "createReadStream", "(", "backupTmpFilePath", ")", ";", "const", "s3Stream", "=", "uploadFromStream", "(", "s3", ",", "bucket", ",", "key", ")", ";", "inputStream", ".", "pipe", "(", "s3Stream", ")", ";", "}", ")", ";", "}" ]
Upload a backup file to an S3 bucket. @param {any} s3 Object store client @param {any} backupTmpFilePath Path of backup file to write. @param {any} bucket Object store bucket name @param {any} key Object store key name @returns Promise
[ "Upload", "a", "backup", "file", "to", "an", "S3", "bucket", "." ]
73a0140a539971e97cdec0233def5db5f9d8f13b
https://github.com/cloudant/couchbackup/blob/73a0140a539971e97cdec0233def5db5f9d8f13b/examples/s3-backup-file.js#L145-L178
20,848
cloudant/couchbackup
includes/config.js
apiDefaults
function apiDefaults() { return { parallelism: 5, bufferSize: 500, requestTimeout: 120000, log: tmp.fileSync().name, resume: false, mode: 'full' }; }
javascript
function apiDefaults() { return { parallelism: 5, bufferSize: 500, requestTimeout: 120000, log: tmp.fileSync().name, resume: false, mode: 'full' }; }
[ "function", "apiDefaults", "(", ")", "{", "return", "{", "parallelism", ":", "5", ",", "bufferSize", ":", "500", ",", "requestTimeout", ":", "120000", ",", "log", ":", "tmp", ".", "fileSync", "(", ")", ".", "name", ",", "resume", ":", "false", ",", "mode", ":", "'full'", "}", ";", "}" ]
Return API default settings.
[ "Return", "API", "default", "settings", "." ]
73a0140a539971e97cdec0233def5db5f9d8f13b
https://github.com/cloudant/couchbackup/blob/73a0140a539971e97cdec0233def5db5f9d8f13b/includes/config.js#L22-L31
20,849
cloudant/couchbackup
includes/writer.js
processBuffer
function processBuffer(flush, callback) { function taskCallback(err, payload) { if (err && !didError) { debug(`Queue task failed with error ${err.name}`); didError = true; q.kill(); writer.emit('error', err); } } if (flush || buffer.length >= bufferSize) { // work through the buffer to break off bufferSize chunks // and feed the chunks to the queue do { // split the buffer into bufferSize chunks var toSend = buffer.splice(0, bufferSize); // and add the chunk to the queue debug(`Adding ${toSend.length} to the write queue.`); q.push({ docs: toSend }, taskCallback); } while (buffer.length >= bufferSize); // send any leftover documents to the queue if (flush && buffer.length > 0) { debug(`Adding remaining ${buffer.length} to the write queue.`); q.push({ docs: buffer }, taskCallback); } // wait until the queue size falls to a reasonable level async.until( // wait until the queue length drops to twice the paralellism // or until empty on the last write function() { // if we encountered an error, stop this until loop if (didError) { return true; } if (flush) { return q.idle() && q.length() === 0; } else { return q.length() <= parallelism * 2; } }, function(cb) { setTimeout(cb, 20); }, function() { if (flush && !didError) { writer.emit('finished', { total: written }); } // callback when we're happy with the queue size callback(); }); } else { callback(); } }
javascript
function processBuffer(flush, callback) { function taskCallback(err, payload) { if (err && !didError) { debug(`Queue task failed with error ${err.name}`); didError = true; q.kill(); writer.emit('error', err); } } if (flush || buffer.length >= bufferSize) { // work through the buffer to break off bufferSize chunks // and feed the chunks to the queue do { // split the buffer into bufferSize chunks var toSend = buffer.splice(0, bufferSize); // and add the chunk to the queue debug(`Adding ${toSend.length} to the write queue.`); q.push({ docs: toSend }, taskCallback); } while (buffer.length >= bufferSize); // send any leftover documents to the queue if (flush && buffer.length > 0) { debug(`Adding remaining ${buffer.length} to the write queue.`); q.push({ docs: buffer }, taskCallback); } // wait until the queue size falls to a reasonable level async.until( // wait until the queue length drops to twice the paralellism // or until empty on the last write function() { // if we encountered an error, stop this until loop if (didError) { return true; } if (flush) { return q.idle() && q.length() === 0; } else { return q.length() <= parallelism * 2; } }, function(cb) { setTimeout(cb, 20); }, function() { if (flush && !didError) { writer.emit('finished', { total: written }); } // callback when we're happy with the queue size callback(); }); } else { callback(); } }
[ "function", "processBuffer", "(", "flush", ",", "callback", ")", "{", "function", "taskCallback", "(", "err", ",", "payload", ")", "{", "if", "(", "err", "&&", "!", "didError", ")", "{", "debug", "(", "`", "${", "err", ".", "name", "}", "`", ")", ";", "didError", "=", "true", ";", "q", ".", "kill", "(", ")", ";", "writer", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", "}", "if", "(", "flush", "||", "buffer", ".", "length", ">=", "bufferSize", ")", "{", "// work through the buffer to break off bufferSize chunks", "// and feed the chunks to the queue", "do", "{", "// split the buffer into bufferSize chunks", "var", "toSend", "=", "buffer", ".", "splice", "(", "0", ",", "bufferSize", ")", ";", "// and add the chunk to the queue", "debug", "(", "`", "${", "toSend", ".", "length", "}", "`", ")", ";", "q", ".", "push", "(", "{", "docs", ":", "toSend", "}", ",", "taskCallback", ")", ";", "}", "while", "(", "buffer", ".", "length", ">=", "bufferSize", ")", ";", "// send any leftover documents to the queue", "if", "(", "flush", "&&", "buffer", ".", "length", ">", "0", ")", "{", "debug", "(", "`", "${", "buffer", ".", "length", "}", "`", ")", ";", "q", ".", "push", "(", "{", "docs", ":", "buffer", "}", ",", "taskCallback", ")", ";", "}", "// wait until the queue size falls to a reasonable level", "async", ".", "until", "(", "// wait until the queue length drops to twice the paralellism", "// or until empty on the last write", "function", "(", ")", "{", "// if we encountered an error, stop this until loop", "if", "(", "didError", ")", "{", "return", "true", ";", "}", "if", "(", "flush", ")", "{", "return", "q", ".", "idle", "(", ")", "&&", "q", ".", "length", "(", ")", "===", "0", ";", "}", "else", "{", "return", "q", ".", "length", "(", ")", "<=", "parallelism", "*", "2", ";", "}", "}", ",", "function", "(", "cb", ")", "{", "setTimeout", "(", "cb", ",", "20", ")", ";", "}", ",", "function", "(", ")", "{", "if", "(", "flush", "&&", "!", "didError", ")", "{", "writer", ".", "emit", "(", "'finished'", ",", "{", "total", ":", "written", "}", ")", ";", "}", "// callback when we're happy with the queue size", "callback", "(", ")", ";", "}", ")", ";", "}", "else", "{", "callback", "(", ")", ";", "}", "}" ]
write the contents of the buffer to CouchDB in blocks of bufferSize
[ "write", "the", "contents", "of", "the", "buffer", "to", "CouchDB", "in", "blocks", "of", "bufferSize" ]
73a0140a539971e97cdec0233def5db5f9d8f13b
https://github.com/cloudant/couchbackup/blob/73a0140a539971e97cdec0233def5db5f9d8f13b/includes/writer.js#L96-L154
20,850
cloudant/couchbackup
includes/writer.js
function() { // if we encountered an error, stop this until loop if (didError) { return true; } if (flush) { return q.idle() && q.length() === 0; } else { return q.length() <= parallelism * 2; } }
javascript
function() { // if we encountered an error, stop this until loop if (didError) { return true; } if (flush) { return q.idle() && q.length() === 0; } else { return q.length() <= parallelism * 2; } }
[ "function", "(", ")", "{", "// if we encountered an error, stop this until loop", "if", "(", "didError", ")", "{", "return", "true", ";", "}", "if", "(", "flush", ")", "{", "return", "q", ".", "idle", "(", ")", "&&", "q", ".", "length", "(", ")", "===", "0", ";", "}", "else", "{", "return", "q", ".", "length", "(", ")", "<=", "parallelism", "*", "2", ";", "}", "}" ]
wait until the queue length drops to twice the paralellism or until empty on the last write
[ "wait", "until", "the", "queue", "length", "drops", "to", "twice", "the", "paralellism", "or", "until", "empty", "on", "the", "last", "write" ]
73a0140a539971e97cdec0233def5db5f9d8f13b
https://github.com/cloudant/couchbackup/blob/73a0140a539971e97cdec0233def5db5f9d8f13b/includes/writer.js#L128-L138
20,851
cloudant/couchbackup
includes/spoolchanges.js
function(lastOne) { if (buffer.length >= bufferSize || (lastOne && buffer.length > 0)) { debug('writing', buffer.length, 'changes to the backup file'); var b = { docs: buffer.splice(0, bufferSize), batch: batch }; logStream.write(':t batch' + batch + ' ' + JSON.stringify(b.docs) + '\n'); ee.emit('changes', batch); batch++; } }
javascript
function(lastOne) { if (buffer.length >= bufferSize || (lastOne && buffer.length > 0)) { debug('writing', buffer.length, 'changes to the backup file'); var b = { docs: buffer.splice(0, bufferSize), batch: batch }; logStream.write(':t batch' + batch + ' ' + JSON.stringify(b.docs) + '\n'); ee.emit('changes', batch); batch++; } }
[ "function", "(", "lastOne", ")", "{", "if", "(", "buffer", ".", "length", ">=", "bufferSize", "||", "(", "lastOne", "&&", "buffer", ".", "length", ">", "0", ")", ")", "{", "debug", "(", "'writing'", ",", "buffer", ".", "length", ",", "'changes to the backup file'", ")", ";", "var", "b", "=", "{", "docs", ":", "buffer", ".", "splice", "(", "0", ",", "bufferSize", ")", ",", "batch", ":", "batch", "}", ";", "logStream", ".", "write", "(", "':t batch'", "+", "batch", "+", "' '", "+", "JSON", ".", "stringify", "(", "b", ".", "docs", ")", "+", "'\\n'", ")", ";", "ee", ".", "emit", "(", "'changes'", ",", "batch", ")", ";", "batch", "++", ";", "}", "}" ]
send documents ids to the queue in batches of bufferSize + the last batch
[ "send", "documents", "ids", "to", "the", "queue", "in", "batches", "of", "bufferSize", "+", "the", "last", "batch" ]
73a0140a539971e97cdec0233def5db5f9d8f13b
https://github.com/cloudant/couchbackup/blob/73a0140a539971e97cdec0233def5db5f9d8f13b/includes/spoolchanges.js#L39-L47
20,852
cloudant/couchbackup
includes/spoolchanges.js
function(c) { if (c) { if (c.error) { ee.emit('error', new error.BackupError('InvalidChange', `Received invalid change: ${c}`)); } else if (c.changes) { var obj = { id: c.id }; buffer.push(obj); processBuffer(false); } else if (c.last_seq) { lastSeq = c.last_seq; } } }
javascript
function(c) { if (c) { if (c.error) { ee.emit('error', new error.BackupError('InvalidChange', `Received invalid change: ${c}`)); } else if (c.changes) { var obj = { id: c.id }; buffer.push(obj); processBuffer(false); } else if (c.last_seq) { lastSeq = c.last_seq; } } }
[ "function", "(", "c", ")", "{", "if", "(", "c", ")", "{", "if", "(", "c", ".", "error", ")", "{", "ee", ".", "emit", "(", "'error'", ",", "new", "error", ".", "BackupError", "(", "'InvalidChange'", ",", "`", "${", "c", "}", "`", ")", ")", ";", "}", "else", "if", "(", "c", ".", "changes", ")", "{", "var", "obj", "=", "{", "id", ":", "c", ".", "id", "}", ";", "buffer", ".", "push", "(", "obj", ")", ";", "processBuffer", "(", "false", ")", ";", "}", "else", "if", "(", "c", ".", "last_seq", ")", "{", "lastSeq", "=", "c", ".", "last_seq", ";", "}", "}", "}" ]
called once per received change
[ "called", "once", "per", "received", "change" ]
73a0140a539971e97cdec0233def5db5f9d8f13b
https://github.com/cloudant/couchbackup/blob/73a0140a539971e97cdec0233def5db5f9d8f13b/includes/spoolchanges.js#L50-L62
20,853
gentooboontoo/js-quantities
lib/JSLitmus.js
function(n) { if (n == Infinity) { return 'Infinity'; } else if (n > 1e9) { n = Math.round(n/1e8); return n/10 + 'B'; } else if (n > 1e6) { n = Math.round(n/1e5); return n/10 + 'M'; } else if (n > 1e3) { n = Math.round(n/1e2); return n/10 + 'K'; } return n; }
javascript
function(n) { if (n == Infinity) { return 'Infinity'; } else if (n > 1e9) { n = Math.round(n/1e8); return n/10 + 'B'; } else if (n > 1e6) { n = Math.round(n/1e5); return n/10 + 'M'; } else if (n > 1e3) { n = Math.round(n/1e2); return n/10 + 'K'; } return n; }
[ "function", "(", "n", ")", "{", "if", "(", "n", "==", "Infinity", ")", "{", "return", "'Infinity'", ";", "}", "else", "if", "(", "n", ">", "1e9", ")", "{", "n", "=", "Math", ".", "round", "(", "n", "/", "1e8", ")", ";", "return", "n", "/", "10", "+", "'B'", ";", "}", "else", "if", "(", "n", ">", "1e6", ")", "{", "n", "=", "Math", ".", "round", "(", "n", "/", "1e5", ")", ";", "return", "n", "/", "10", "+", "'M'", ";", "}", "else", "if", "(", "n", ">", "1e3", ")", "{", "n", "=", "Math", ".", "round", "(", "n", "/", "1e2", ")", ";", "return", "n", "/", "10", "+", "'K'", ";", "}", "return", "n", ";", "}" ]
Convert a number to an abbreviated string like, "15K" or "10M"
[ "Convert", "a", "number", "to", "an", "abbreviated", "string", "like", "15K", "or", "10M" ]
368d45526500dda7cc31a25fd77c30d7ec4b3208
https://github.com/gentooboontoo/js-quantities/blob/368d45526500dda7cc31a25fd77c30d7ec4b3208/lib/JSLitmus.js#L64-L78
20,854
gentooboontoo/js-quantities
lib/JSLitmus.js
function(count) { var me = this; // Make sure calibration tests have run if (!me.isCalibration && Test.calibrate(function() {me.run(count);})) return; this.error = null; try { var start, f = this.f, now, i = count; // Start the timer start = new Date(); // Now for the money shot. If this is a looping function ... if (this.loopArg) { // ... let it do the iteration itself f(count); } else { // ... otherwise do the iteration for it while (i--) f(); } // Get time test took (in secs) this.time = Math.max(1,new Date() - start)/1000; // Store iteration count and per-operation time taken this.count = count; this.period = this.time/count; // Do we need to do another run? this.running = this.time <= this.MIN_TIME; // ... if so, compute how many times we should iterate if (this.running) { // Bump the count to the nearest power of 2 var x = this.MIN_TIME/this.time; var pow = Math.pow(2, Math.max(1, Math.ceil(Math.log(x)/Math.log(2)))); count *= pow; if (count > this.MAX_COUNT) { throw new Error('Max count exceeded. If this test uses a looping function, make sure the iteration loop is working properly.'); } } } catch (e) { // Exceptions are caught and displayed in the test UI this.reset(); this.error = e; } // Figure out what to do next if (this.running) { me.run(count); } else { jsl.status(''); me.onStop(me); } // Finish up this.onChange(this); }
javascript
function(count) { var me = this; // Make sure calibration tests have run if (!me.isCalibration && Test.calibrate(function() {me.run(count);})) return; this.error = null; try { var start, f = this.f, now, i = count; // Start the timer start = new Date(); // Now for the money shot. If this is a looping function ... if (this.loopArg) { // ... let it do the iteration itself f(count); } else { // ... otherwise do the iteration for it while (i--) f(); } // Get time test took (in secs) this.time = Math.max(1,new Date() - start)/1000; // Store iteration count and per-operation time taken this.count = count; this.period = this.time/count; // Do we need to do another run? this.running = this.time <= this.MIN_TIME; // ... if so, compute how many times we should iterate if (this.running) { // Bump the count to the nearest power of 2 var x = this.MIN_TIME/this.time; var pow = Math.pow(2, Math.max(1, Math.ceil(Math.log(x)/Math.log(2)))); count *= pow; if (count > this.MAX_COUNT) { throw new Error('Max count exceeded. If this test uses a looping function, make sure the iteration loop is working properly.'); } } } catch (e) { // Exceptions are caught and displayed in the test UI this.reset(); this.error = e; } // Figure out what to do next if (this.running) { me.run(count); } else { jsl.status(''); me.onStop(me); } // Finish up this.onChange(this); }
[ "function", "(", "count", ")", "{", "var", "me", "=", "this", ";", "// Make sure calibration tests have run", "if", "(", "!", "me", ".", "isCalibration", "&&", "Test", ".", "calibrate", "(", "function", "(", ")", "{", "me", ".", "run", "(", "count", ")", ";", "}", ")", ")", "return", ";", "this", ".", "error", "=", "null", ";", "try", "{", "var", "start", ",", "f", "=", "this", ".", "f", ",", "now", ",", "i", "=", "count", ";", "// Start the timer", "start", "=", "new", "Date", "(", ")", ";", "// Now for the money shot. If this is a looping function ...", "if", "(", "this", ".", "loopArg", ")", "{", "// ... let it do the iteration itself", "f", "(", "count", ")", ";", "}", "else", "{", "// ... otherwise do the iteration for it", "while", "(", "i", "--", ")", "f", "(", ")", ";", "}", "// Get time test took (in secs)", "this", ".", "time", "=", "Math", ".", "max", "(", "1", ",", "new", "Date", "(", ")", "-", "start", ")", "/", "1000", ";", "// Store iteration count and per-operation time taken", "this", ".", "count", "=", "count", ";", "this", ".", "period", "=", "this", ".", "time", "/", "count", ";", "// Do we need to do another run?", "this", ".", "running", "=", "this", ".", "time", "<=", "this", ".", "MIN_TIME", ";", "// ... if so, compute how many times we should iterate", "if", "(", "this", ".", "running", ")", "{", "// Bump the count to the nearest power of 2", "var", "x", "=", "this", ".", "MIN_TIME", "/", "this", ".", "time", ";", "var", "pow", "=", "Math", ".", "pow", "(", "2", ",", "Math", ".", "max", "(", "1", ",", "Math", ".", "ceil", "(", "Math", ".", "log", "(", "x", ")", "/", "Math", ".", "log", "(", "2", ")", ")", ")", ")", ";", "count", "*=", "pow", ";", "if", "(", "count", ">", "this", ".", "MAX_COUNT", ")", "{", "throw", "new", "Error", "(", "'Max count exceeded. If this test uses a looping function, make sure the iteration loop is working properly.'", ")", ";", "}", "}", "}", "catch", "(", "e", ")", "{", "// Exceptions are caught and displayed in the test UI", "this", ".", "reset", "(", ")", ";", "this", ".", "error", "=", "e", ";", "}", "// Figure out what to do next", "if", "(", "this", ".", "running", ")", "{", "me", ".", "run", "(", "count", ")", ";", "}", "else", "{", "jsl", ".", "status", "(", "''", ")", ";", "me", ".", "onStop", "(", "me", ")", ";", "}", "// Finish up", "this", ".", "onChange", "(", "this", ")", ";", "}" ]
The nuts and bolts code that actually runs a test
[ "The", "nuts", "and", "bolts", "code", "that", "actually", "runs", "a", "test" ]
368d45526500dda7cc31a25fd77c30d7ec4b3208
https://github.com/gentooboontoo/js-quantities/blob/368d45526500dda7cc31a25fd77c30d7ec4b3208/lib/JSLitmus.js#L191-L249
20,855
gentooboontoo/js-quantities
lib/JSLitmus.js
function(/**Boolean*/ normalize) { var p = this.period; // Adjust period based on the calibration test time if (normalize && !this.isCalibration) { var cal = Test.CALIBRATIONS[this.loopArg ? 0 : 1]; // If the period is within 20% of the calibration time, then zero the // it out p = p < cal.period*1.2 ? 0 : p - cal.period; } return Math.round(1/p); }
javascript
function(/**Boolean*/ normalize) { var p = this.period; // Adjust period based on the calibration test time if (normalize && !this.isCalibration) { var cal = Test.CALIBRATIONS[this.loopArg ? 0 : 1]; // If the period is within 20% of the calibration time, then zero the // it out p = p < cal.period*1.2 ? 0 : p - cal.period; } return Math.round(1/p); }
[ "function", "(", "/**Boolean*/", "normalize", ")", "{", "var", "p", "=", "this", ".", "period", ";", "// Adjust period based on the calibration test time", "if", "(", "normalize", "&&", "!", "this", ".", "isCalibration", ")", "{", "var", "cal", "=", "Test", ".", "CALIBRATIONS", "[", "this", ".", "loopArg", "?", "0", ":", "1", "]", ";", "// If the period is within 20% of the calibration time, then zero the", "// it out", "p", "=", "p", "<", "cal", ".", "period", "*", "1.2", "?", "0", ":", "p", "-", "cal", ".", "period", ";", "}", "return", "Math", ".", "round", "(", "1", "/", "p", ")", ";", "}" ]
Get the number of operations per second for this test. @param normalize if true, iteration loop overhead taken into account
[ "Get", "the", "number", "of", "operations", "per", "second", "for", "this", "test", "." ]
368d45526500dda7cc31a25fd77c30d7ec4b3208
https://github.com/gentooboontoo/js-quantities/blob/368d45526500dda7cc31a25fd77c30d7ec4b3208/lib/JSLitmus.js#L256-L269
20,856
gentooboontoo/js-quantities
lib/JSLitmus.js
function() { var el = jsl.$('jslitmus_container'); if (!el) document.body.appendChild(el = document.createElement('div')); el.innerHTML = MARKUP; // Render the UI for all our tests for (var i=0; i < JSLitmus._tests.length; i++) JSLitmus.renderTest(JSLitmus._tests[i]); }
javascript
function() { var el = jsl.$('jslitmus_container'); if (!el) document.body.appendChild(el = document.createElement('div')); el.innerHTML = MARKUP; // Render the UI for all our tests for (var i=0; i < JSLitmus._tests.length; i++) JSLitmus.renderTest(JSLitmus._tests[i]); }
[ "function", "(", ")", "{", "var", "el", "=", "jsl", ".", "$", "(", "'jslitmus_container'", ")", ";", "if", "(", "!", "el", ")", "document", ".", "body", ".", "appendChild", "(", "el", "=", "document", ".", "createElement", "(", "'div'", ")", ")", ";", "el", ".", "innerHTML", "=", "MARKUP", ";", "// Render the UI for all our tests", "for", "(", "var", "i", "=", "0", ";", "i", "<", "JSLitmus", ".", "_tests", ".", "length", ";", "i", "++", ")", "JSLitmus", ".", "renderTest", "(", "JSLitmus", ".", "_tests", "[", "i", "]", ")", ";", "}" ]
Set up the UI
[ "Set", "up", "the", "UI" ]
368d45526500dda7cc31a25fd77c30d7ec4b3208
https://github.com/gentooboontoo/js-quantities/blob/368d45526500dda7cc31a25fd77c30d7ec4b3208/lib/JSLitmus.js#L441-L450
20,857
gentooboontoo/js-quantities
lib/JSLitmus.js
function(name, f) { // Create the Test object var test = new Test(name, f); JSLitmus._tests.push(test); // Re-render if the test state changes test.onChange = JSLitmus.renderTest; // Run the next test if this one finished test.onStop = function(test) { if (JSLitmus.onTestFinish) JSLitmus.onTestFinish(test); JSLitmus.currentTest = null; JSLitmus._nextTest(); }; // Render the new test this.renderTest(test); }
javascript
function(name, f) { // Create the Test object var test = new Test(name, f); JSLitmus._tests.push(test); // Re-render if the test state changes test.onChange = JSLitmus.renderTest; // Run the next test if this one finished test.onStop = function(test) { if (JSLitmus.onTestFinish) JSLitmus.onTestFinish(test); JSLitmus.currentTest = null; JSLitmus._nextTest(); }; // Render the new test this.renderTest(test); }
[ "function", "(", "name", ",", "f", ")", "{", "// Create the Test object", "var", "test", "=", "new", "Test", "(", "name", ",", "f", ")", ";", "JSLitmus", ".", "_tests", ".", "push", "(", "test", ")", ";", "// Re-render if the test state changes", "test", ".", "onChange", "=", "JSLitmus", ".", "renderTest", ";", "// Run the next test if this one finished", "test", ".", "onStop", "=", "function", "(", "test", ")", "{", "if", "(", "JSLitmus", ".", "onTestFinish", ")", "JSLitmus", ".", "onTestFinish", "(", "test", ")", ";", "JSLitmus", ".", "currentTest", "=", "null", ";", "JSLitmus", ".", "_nextTest", "(", ")", ";", "}", ";", "// Render the new test", "this", ".", "renderTest", "(", "test", ")", ";", "}" ]
Create a new test
[ "Create", "a", "new", "test" ]
368d45526500dda7cc31a25fd77c30d7ec4b3208
https://github.com/gentooboontoo/js-quantities/blob/368d45526500dda7cc31a25fd77c30d7ec4b3208/lib/JSLitmus.js#L524-L541
20,858
gentooboontoo/js-quantities
lib/JSLitmus.js
function(e) { e = e || window.event; var reverse = e && e.shiftKey, len = JSLitmus._tests.length; for (var i = 0; i < len; i++) { JSLitmus._queueTest(JSLitmus._tests[!reverse ? i : (len - i - 1)]); } }
javascript
function(e) { e = e || window.event; var reverse = e && e.shiftKey, len = JSLitmus._tests.length; for (var i = 0; i < len; i++) { JSLitmus._queueTest(JSLitmus._tests[!reverse ? i : (len - i - 1)]); } }
[ "function", "(", "e", ")", "{", "e", "=", "e", "||", "window", ".", "event", ";", "var", "reverse", "=", "e", "&&", "e", ".", "shiftKey", ",", "len", "=", "JSLitmus", ".", "_tests", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "JSLitmus", ".", "_queueTest", "(", "JSLitmus", ".", "_tests", "[", "!", "reverse", "?", "i", ":", "(", "len", "-", "i", "-", "1", ")", "]", ")", ";", "}", "}" ]
Add all tests to the run queue
[ "Add", "all", "tests", "to", "the", "run", "queue" ]
368d45526500dda7cc31a25fd77c30d7ec4b3208
https://github.com/gentooboontoo/js-quantities/blob/368d45526500dda7cc31a25fd77c30d7ec4b3208/lib/JSLitmus.js#L546-L552
20,859
gentooboontoo/js-quantities
lib/JSLitmus.js
function() { while (JSLitmus._queue.length) { var test = JSLitmus._queue.shift(); JSLitmus.renderTest(test); } }
javascript
function() { while (JSLitmus._queue.length) { var test = JSLitmus._queue.shift(); JSLitmus.renderTest(test); } }
[ "function", "(", ")", "{", "while", "(", "JSLitmus", ".", "_queue", ".", "length", ")", "{", "var", "test", "=", "JSLitmus", ".", "_queue", ".", "shift", "(", ")", ";", "JSLitmus", ".", "renderTest", "(", "test", ")", ";", "}", "}" ]
Remove all tests from the run queue. The current test has to finish on it's own though
[ "Remove", "all", "tests", "from", "the", "run", "queue", ".", "The", "current", "test", "has", "to", "finish", "on", "it", "s", "own", "though" ]
368d45526500dda7cc31a25fd77c30d7ec4b3208
https://github.com/gentooboontoo/js-quantities/blob/368d45526500dda7cc31a25fd77c30d7ec4b3208/lib/JSLitmus.js#L558-L563
20,860
gentooboontoo/js-quantities
lib/JSLitmus.js
function() { if (!JSLitmus.currentTest) { var test = JSLitmus._queue.shift(); if (test) { jsl.$('stop_button').disabled = false; JSLitmus.currentTest = test; test.run(); JSLitmus.renderTest(test); if (JSLitmus.onTestStart) JSLitmus.onTestStart(test); } else { jsl.$('stop_button').disabled = true; JSLitmus.renderChart(); } } }
javascript
function() { if (!JSLitmus.currentTest) { var test = JSLitmus._queue.shift(); if (test) { jsl.$('stop_button').disabled = false; JSLitmus.currentTest = test; test.run(); JSLitmus.renderTest(test); if (JSLitmus.onTestStart) JSLitmus.onTestStart(test); } else { jsl.$('stop_button').disabled = true; JSLitmus.renderChart(); } } }
[ "function", "(", ")", "{", "if", "(", "!", "JSLitmus", ".", "currentTest", ")", "{", "var", "test", "=", "JSLitmus", ".", "_queue", ".", "shift", "(", ")", ";", "if", "(", "test", ")", "{", "jsl", ".", "$", "(", "'stop_button'", ")", ".", "disabled", "=", "false", ";", "JSLitmus", ".", "currentTest", "=", "test", ";", "test", ".", "run", "(", ")", ";", "JSLitmus", ".", "renderTest", "(", "test", ")", ";", "if", "(", "JSLitmus", ".", "onTestStart", ")", "JSLitmus", ".", "onTestStart", "(", "test", ")", ";", "}", "else", "{", "jsl", ".", "$", "(", "'stop_button'", ")", ".", "disabled", "=", "true", ";", "JSLitmus", ".", "renderChart", "(", ")", ";", "}", "}", "}" ]
Run the next test in the run queue
[ "Run", "the", "next", "test", "in", "the", "run", "queue" ]
368d45526500dda7cc31a25fd77c30d7ec4b3208
https://github.com/gentooboontoo/js-quantities/blob/368d45526500dda7cc31a25fd77c30d7ec4b3208/lib/JSLitmus.js#L568-L582
20,861
gentooboontoo/js-quantities
lib/JSLitmus.js
function(test) { if (jsl.indexOf(JSLitmus._queue, test) >= 0) return; JSLitmus._queue.push(test); JSLitmus.renderTest(test); JSLitmus._nextTest(); }
javascript
function(test) { if (jsl.indexOf(JSLitmus._queue, test) >= 0) return; JSLitmus._queue.push(test); JSLitmus.renderTest(test); JSLitmus._nextTest(); }
[ "function", "(", "test", ")", "{", "if", "(", "jsl", ".", "indexOf", "(", "JSLitmus", ".", "_queue", ",", "test", ")", ">=", "0", ")", "return", ";", "JSLitmus", ".", "_queue", ".", "push", "(", "test", ")", ";", "JSLitmus", ".", "renderTest", "(", "test", ")", ";", "JSLitmus", ".", "_nextTest", "(", ")", ";", "}" ]
Add a test to the run queue
[ "Add", "a", "test", "to", "the", "run", "queue" ]
368d45526500dda7cc31a25fd77c30d7ec4b3208
https://github.com/gentooboontoo/js-quantities/blob/368d45526500dda7cc31a25fd77c30d7ec4b3208/lib/JSLitmus.js#L587-L592
20,862
gentooboontoo/js-quantities
lib/JSLitmus.js
function() { var n = JSLitmus._tests.length, markers = [], data = []; var d, min = 0, max = -1e10; var normalize = jsl.$('test_normalize').checked; // Gather test data for (var i=0; i < JSLitmus._tests.length; i++) { var test = JSLitmus._tests[i]; if (test.count) { var hz = test.getHz(normalize); var v = hz != Infinity ? hz : 0; data.push(v); markers.push('t' + jsl.escape(test.name + '(' + jsl.toLabel(hz)+ ')') + ',000000,0,' + markers.length + ',10'); max = Math.max(v, max); } } if (markers.length <= 0) return null; // Build chart title var title = document.getElementsByTagName('title'); title = (title && title.length) ? title[0].innerHTML : null; var chart_title = []; if (title) chart_title.push(title); chart_title.push('Ops/sec (' + platform + ')'); // Build labels var labels = [jsl.toLabel(min), jsl.toLabel(max)]; var w = 250, bw = 15; var bs = 5; var h = markers.length*(bw + bs) + 30 + chart_title.length*20; var params = { chtt: escape(chart_title.join('|')), chts: '000000,10', cht: 'bhg', // chart type chd: 't:' + data.join(','), // data set chds: min + ',' + max, // max/min of data chxt: 'x', // label axes chxl: '0:|' + labels.join('|'), // labels chsp: '0,1', chm: markers.join('|'), // test names chbh: [bw, 0, bs].join(','), // bar widths // chf: 'bg,lg,0,eeeeee,0,eeeeee,.5,ffffff,1', // gradient chs: w + 'x' + h }; return 'http://chart.apis.google.com/chart?' + jsl.join(params, '=', '&'); }
javascript
function() { var n = JSLitmus._tests.length, markers = [], data = []; var d, min = 0, max = -1e10; var normalize = jsl.$('test_normalize').checked; // Gather test data for (var i=0; i < JSLitmus._tests.length; i++) { var test = JSLitmus._tests[i]; if (test.count) { var hz = test.getHz(normalize); var v = hz != Infinity ? hz : 0; data.push(v); markers.push('t' + jsl.escape(test.name + '(' + jsl.toLabel(hz)+ ')') + ',000000,0,' + markers.length + ',10'); max = Math.max(v, max); } } if (markers.length <= 0) return null; // Build chart title var title = document.getElementsByTagName('title'); title = (title && title.length) ? title[0].innerHTML : null; var chart_title = []; if (title) chart_title.push(title); chart_title.push('Ops/sec (' + platform + ')'); // Build labels var labels = [jsl.toLabel(min), jsl.toLabel(max)]; var w = 250, bw = 15; var bs = 5; var h = markers.length*(bw + bs) + 30 + chart_title.length*20; var params = { chtt: escape(chart_title.join('|')), chts: '000000,10', cht: 'bhg', // chart type chd: 't:' + data.join(','), // data set chds: min + ',' + max, // max/min of data chxt: 'x', // label axes chxl: '0:|' + labels.join('|'), // labels chsp: '0,1', chm: markers.join('|'), // test names chbh: [bw, 0, bs].join(','), // bar widths // chf: 'bg,lg,0,eeeeee,0,eeeeee,.5,ffffff,1', // gradient chs: w + 'x' + h }; return 'http://chart.apis.google.com/chart?' + jsl.join(params, '=', '&'); }
[ "function", "(", ")", "{", "var", "n", "=", "JSLitmus", ".", "_tests", ".", "length", ",", "markers", "=", "[", "]", ",", "data", "=", "[", "]", ";", "var", "d", ",", "min", "=", "0", ",", "max", "=", "-", "1e10", ";", "var", "normalize", "=", "jsl", ".", "$", "(", "'test_normalize'", ")", ".", "checked", ";", "// Gather test data", "for", "(", "var", "i", "=", "0", ";", "i", "<", "JSLitmus", ".", "_tests", ".", "length", ";", "i", "++", ")", "{", "var", "test", "=", "JSLitmus", ".", "_tests", "[", "i", "]", ";", "if", "(", "test", ".", "count", ")", "{", "var", "hz", "=", "test", ".", "getHz", "(", "normalize", ")", ";", "var", "v", "=", "hz", "!=", "Infinity", "?", "hz", ":", "0", ";", "data", ".", "push", "(", "v", ")", ";", "markers", ".", "push", "(", "'t'", "+", "jsl", ".", "escape", "(", "test", ".", "name", "+", "'('", "+", "jsl", ".", "toLabel", "(", "hz", ")", "+", "')'", ")", "+", "',000000,0,'", "+", "markers", ".", "length", "+", "',10'", ")", ";", "max", "=", "Math", ".", "max", "(", "v", ",", "max", ")", ";", "}", "}", "if", "(", "markers", ".", "length", "<=", "0", ")", "return", "null", ";", "// Build chart title", "var", "title", "=", "document", ".", "getElementsByTagName", "(", "'title'", ")", ";", "title", "=", "(", "title", "&&", "title", ".", "length", ")", "?", "title", "[", "0", "]", ".", "innerHTML", ":", "null", ";", "var", "chart_title", "=", "[", "]", ";", "if", "(", "title", ")", "chart_title", ".", "push", "(", "title", ")", ";", "chart_title", ".", "push", "(", "'Ops/sec ('", "+", "platform", "+", "')'", ")", ";", "// Build labels", "var", "labels", "=", "[", "jsl", ".", "toLabel", "(", "min", ")", ",", "jsl", ".", "toLabel", "(", "max", ")", "]", ";", "var", "w", "=", "250", ",", "bw", "=", "15", ";", "var", "bs", "=", "5", ";", "var", "h", "=", "markers", ".", "length", "*", "(", "bw", "+", "bs", ")", "+", "30", "+", "chart_title", ".", "length", "*", "20", ";", "var", "params", "=", "{", "chtt", ":", "escape", "(", "chart_title", ".", "join", "(", "'|'", ")", ")", ",", "chts", ":", "'000000,10'", ",", "cht", ":", "'bhg'", ",", "// chart type", "chd", ":", "'t:'", "+", "data", ".", "join", "(", "','", ")", ",", "// data set", "chds", ":", "min", "+", "','", "+", "max", ",", "// max/min of data", "chxt", ":", "'x'", ",", "// label axes", "chxl", ":", "'0:|'", "+", "labels", ".", "join", "(", "'|'", ")", ",", "// labels", "chsp", ":", "'0,1'", ",", "chm", ":", "markers", ".", "join", "(", "'|'", ")", ",", "// test names", "chbh", ":", "[", "bw", ",", "0", ",", "bs", "]", ".", "join", "(", "','", ")", ",", "// bar widths", "// chf: 'bg,lg,0,eeeeee,0,eeeeee,.5,ffffff,1', // gradient", "chs", ":", "w", "+", "'x'", "+", "h", "}", ";", "return", "'http://chart.apis.google.com/chart?'", "+", "jsl", ".", "join", "(", "params", ",", "'='", ",", "'&'", ")", ";", "}" ]
Generate a Google Chart URL that shows the data for all tests
[ "Generate", "a", "Google", "Chart", "URL", "that", "shows", "the", "data", "for", "all", "tests" ]
368d45526500dda7cc31a25fd77c30d7ec4b3208
https://github.com/gentooboontoo/js-quantities/blob/368d45526500dda7cc31a25fd77c30d7ec4b3208/lib/JSLitmus.js#L597-L645
20,863
castillo-io/angular-css
angular-css.js
mapBreakpointToMedia
function mapBreakpointToMedia(stylesheet) { if (angular.isDefined(options.breakpoints)) { if (stylesheet.breakpoint in options.breakpoints) { stylesheet.media = options.breakpoints[stylesheet.breakpoint]; } delete stylesheet.breakpoints; } }
javascript
function mapBreakpointToMedia(stylesheet) { if (angular.isDefined(options.breakpoints)) { if (stylesheet.breakpoint in options.breakpoints) { stylesheet.media = options.breakpoints[stylesheet.breakpoint]; } delete stylesheet.breakpoints; } }
[ "function", "mapBreakpointToMedia", "(", "stylesheet", ")", "{", "if", "(", "angular", ".", "isDefined", "(", "options", ".", "breakpoints", ")", ")", "{", "if", "(", "stylesheet", ".", "breakpoint", "in", "options", ".", "breakpoints", ")", "{", "stylesheet", ".", "media", "=", "options", ".", "breakpoints", "[", "stylesheet", ".", "breakpoint", "]", ";", "}", "delete", "stylesheet", ".", "breakpoints", ";", "}", "}" ]
Map breakpoitns defined in defaults to stylesheet media attribute
[ "Map", "breakpoitns", "defined", "in", "defaults", "to", "stylesheet", "media", "attribute" ]
94a58bd8daf0c2b5e3b398002e60d78219ec0c6b
https://github.com/castillo-io/angular-css/blob/94a58bd8daf0c2b5e3b398002e60d78219ec0c6b/angular-css.js#L116-L123
20,864
castillo-io/angular-css
angular-css.js
addViaMediaQuery
function addViaMediaQuery(stylesheet) { if (!stylesheet) { if(DEBUG) $log.error('No stylesheet provided'); return; } // Media query object mediaQuery[stylesheet.href] = $window.matchMedia(stylesheet.media); // Media Query Listener function mediaQueryListener[stylesheet.href] = function(mediaQuery) { // Trigger digest $timeout(function () { if (mediaQuery.matches) { // Add stylesheet $rootScope.stylesheets.push(stylesheet); } else { var index = $rootScope.stylesheets.indexOf($filter('filter')($rootScope.stylesheets, { href: stylesheet.href })[0]); // Remove stylesheet if (index !== -1) { $rootScope.stylesheets.splice(index, 1); } } }); }; // Listen for media query changes mediaQuery[stylesheet.href].addListener(mediaQueryListener[stylesheet.href]); // Invoke first media query check mediaQueryListener[stylesheet.href](mediaQuery[stylesheet.href]); }
javascript
function addViaMediaQuery(stylesheet) { if (!stylesheet) { if(DEBUG) $log.error('No stylesheet provided'); return; } // Media query object mediaQuery[stylesheet.href] = $window.matchMedia(stylesheet.media); // Media Query Listener function mediaQueryListener[stylesheet.href] = function(mediaQuery) { // Trigger digest $timeout(function () { if (mediaQuery.matches) { // Add stylesheet $rootScope.stylesheets.push(stylesheet); } else { var index = $rootScope.stylesheets.indexOf($filter('filter')($rootScope.stylesheets, { href: stylesheet.href })[0]); // Remove stylesheet if (index !== -1) { $rootScope.stylesheets.splice(index, 1); } } }); }; // Listen for media query changes mediaQuery[stylesheet.href].addListener(mediaQueryListener[stylesheet.href]); // Invoke first media query check mediaQueryListener[stylesheet.href](mediaQuery[stylesheet.href]); }
[ "function", "addViaMediaQuery", "(", "stylesheet", ")", "{", "if", "(", "!", "stylesheet", ")", "{", "if", "(", "DEBUG", ")", "$log", ".", "error", "(", "'No stylesheet provided'", ")", ";", "return", ";", "}", "// Media query object", "mediaQuery", "[", "stylesheet", ".", "href", "]", "=", "$window", ".", "matchMedia", "(", "stylesheet", ".", "media", ")", ";", "// Media Query Listener function", "mediaQueryListener", "[", "stylesheet", ".", "href", "]", "=", "function", "(", "mediaQuery", ")", "{", "// Trigger digest", "$timeout", "(", "function", "(", ")", "{", "if", "(", "mediaQuery", ".", "matches", ")", "{", "// Add stylesheet", "$rootScope", ".", "stylesheets", ".", "push", "(", "stylesheet", ")", ";", "}", "else", "{", "var", "index", "=", "$rootScope", ".", "stylesheets", ".", "indexOf", "(", "$filter", "(", "'filter'", ")", "(", "$rootScope", ".", "stylesheets", ",", "{", "href", ":", "stylesheet", ".", "href", "}", ")", "[", "0", "]", ")", ";", "// Remove stylesheet", "if", "(", "index", "!==", "-", "1", ")", "{", "$rootScope", ".", "stylesheets", ".", "splice", "(", "index", ",", "1", ")", ";", "}", "}", "}", ")", ";", "}", ";", "// Listen for media query changes", "mediaQuery", "[", "stylesheet", ".", "href", "]", ".", "addListener", "(", "mediaQueryListener", "[", "stylesheet", ".", "href", "]", ")", ";", "// Invoke first media query check", "mediaQueryListener", "[", "stylesheet", ".", "href", "]", "(", "mediaQuery", "[", "stylesheet", ".", "href", "]", ")", ";", "}" ]
Add Media Query
[ "Add", "Media", "Query" ]
94a58bd8daf0c2b5e3b398002e60d78219ec0c6b
https://github.com/castillo-io/angular-css/blob/94a58bd8daf0c2b5e3b398002e60d78219ec0c6b/angular-css.js#L211-L240
20,865
castillo-io/angular-css
angular-css.js
removeViaMediaQuery
function removeViaMediaQuery(stylesheet) { if (!stylesheet) { if(DEBUG) $log.error('No stylesheet provided'); return; } // Remove media query listener if ($rootScope && angular.isDefined(mediaQuery) && mediaQuery[stylesheet.href] && angular.isDefined(mediaQueryListener)) { mediaQuery[stylesheet.href].removeListener(mediaQueryListener[stylesheet.href]); } }
javascript
function removeViaMediaQuery(stylesheet) { if (!stylesheet) { if(DEBUG) $log.error('No stylesheet provided'); return; } // Remove media query listener if ($rootScope && angular.isDefined(mediaQuery) && mediaQuery[stylesheet.href] && angular.isDefined(mediaQueryListener)) { mediaQuery[stylesheet.href].removeListener(mediaQueryListener[stylesheet.href]); } }
[ "function", "removeViaMediaQuery", "(", "stylesheet", ")", "{", "if", "(", "!", "stylesheet", ")", "{", "if", "(", "DEBUG", ")", "$log", ".", "error", "(", "'No stylesheet provided'", ")", ";", "return", ";", "}", "// Remove media query listener", "if", "(", "$rootScope", "&&", "angular", ".", "isDefined", "(", "mediaQuery", ")", "&&", "mediaQuery", "[", "stylesheet", ".", "href", "]", "&&", "angular", ".", "isDefined", "(", "mediaQueryListener", ")", ")", "{", "mediaQuery", "[", "stylesheet", ".", "href", "]", ".", "removeListener", "(", "mediaQueryListener", "[", "stylesheet", ".", "href", "]", ")", ";", "}", "}" ]
Remove Media Query
[ "Remove", "Media", "Query" ]
94a58bd8daf0c2b5e3b398002e60d78219ec0c6b
https://github.com/castillo-io/angular-css/blob/94a58bd8daf0c2b5e3b398002e60d78219ec0c6b/angular-css.js#L245-L256
20,866
webpack-contrib/webpack-command
lib/compiler.js
requireReporter
function requireReporter(name) { const prefix = capitalize(camelcase(name)); const locations = [`./reporters/${prefix}Reporter`, name, path.resolve(name)]; let result = null; for (const location of locations) { try { // eslint-disable-next-line import/no-dynamic-require, global-require result = require(location); } catch (e) { // noop } if (result) { break; } } return result; }
javascript
function requireReporter(name) { const prefix = capitalize(camelcase(name)); const locations = [`./reporters/${prefix}Reporter`, name, path.resolve(name)]; let result = null; for (const location of locations) { try { // eslint-disable-next-line import/no-dynamic-require, global-require result = require(location); } catch (e) { // noop } if (result) { break; } } return result; }
[ "function", "requireReporter", "(", "name", ")", "{", "const", "prefix", "=", "capitalize", "(", "camelcase", "(", "name", ")", ")", ";", "const", "locations", "=", "[", "`", "${", "prefix", "}", "`", ",", "name", ",", "path", ".", "resolve", "(", "name", ")", "]", ";", "let", "result", "=", "null", ";", "for", "(", "const", "location", "of", "locations", ")", "{", "try", "{", "// eslint-disable-next-line import/no-dynamic-require, global-require", "result", "=", "require", "(", "location", ")", ";", "}", "catch", "(", "e", ")", "{", "// noop", "}", "if", "(", "result", ")", "{", "break", ";", "}", "}", "return", "result", ";", "}" ]
Attempts to require a specified reporter. Tries the local built-ins first, and if that fails, attempts to load an npm module that exports a reporter handler function, and if that fails, attempts to load the reporter relative to the current working directory.
[ "Attempts", "to", "require", "a", "specified", "reporter", ".", "Tries", "the", "local", "built", "-", "ins", "first", "and", "if", "that", "fails", "attempts", "to", "load", "an", "npm", "module", "that", "exports", "a", "reporter", "handler", "function", "and", "if", "that", "fails", "attempts", "to", "load", "the", "reporter", "relative", "to", "the", "current", "working", "directory", "." ]
be83d805be69b7e2495f13e2b09a0c5092569190
https://github.com/webpack-contrib/webpack-command/blob/be83d805be69b7e2495f13e2b09a0c5092569190/lib/compiler.js#L48-L67
20,867
webpack-contrib/webpack-command
lib/compiler.js
sanitize
function sanitize(config) { const configs = [].concat(config).map((conf) => { const result = merge({}, conf); delete result.progress; delete result.reporter; delete result.watchStdin; // TODO: remove the need for this for (const property of ['entry', 'output']) { const target = result[property]; if (target && Object.keys(target).length === 0) { delete result[property]; } } return result; }); // if we always return an array, every compilation will be a MultiCompiler return configs.length > 1 ? configs : configs[0]; }
javascript
function sanitize(config) { const configs = [].concat(config).map((conf) => { const result = merge({}, conf); delete result.progress; delete result.reporter; delete result.watchStdin; // TODO: remove the need for this for (const property of ['entry', 'output']) { const target = result[property]; if (target && Object.keys(target).length === 0) { delete result[property]; } } return result; }); // if we always return an array, every compilation will be a MultiCompiler return configs.length > 1 ? configs : configs[0]; }
[ "function", "sanitize", "(", "config", ")", "{", "const", "configs", "=", "[", "]", ".", "concat", "(", "config", ")", ".", "map", "(", "(", "conf", ")", "=>", "{", "const", "result", "=", "merge", "(", "{", "}", ",", "conf", ")", ";", "delete", "result", ".", "progress", ";", "delete", "result", ".", "reporter", ";", "delete", "result", ".", "watchStdin", ";", "// TODO: remove the need for this", "for", "(", "const", "property", "of", "[", "'entry'", ",", "'output'", "]", ")", "{", "const", "target", "=", "result", "[", "property", "]", ";", "if", "(", "target", "&&", "Object", ".", "keys", "(", "target", ")", ".", "length", "===", "0", ")", "{", "delete", "result", "[", "property", "]", ";", "}", "}", "return", "result", ";", "}", ")", ";", "// if we always return an array, every compilation will be a MultiCompiler", "return", "configs", ".", "length", ">", "1", "?", "configs", ":", "configs", "[", "0", "]", ";", "}" ]
Removes invalid webpack config properties leftover from applying flags
[ "Removes", "invalid", "webpack", "config", "properties", "leftover", "from", "applying", "flags" ]
be83d805be69b7e2495f13e2b09a0c5092569190
https://github.com/webpack-contrib/webpack-command/blob/be83d805be69b7e2495f13e2b09a0c5092569190/lib/compiler.js#L72-L92
20,868
stealjs/steal-tools
lib/loader/find_bundle.js
minusJS
function minusJS(name) { var idx = name.indexOf(".js"); return idx === -1 ? name : name.substr(0, idx); }
javascript
function minusJS(name) { var idx = name.indexOf(".js"); return idx === -1 ? name : name.substr(0, idx); }
[ "function", "minusJS", "(", "name", ")", "{", "var", "idx", "=", "name", ".", "indexOf", "(", "\".js\"", ")", ";", "return", "idx", "===", "-", "1", "?", "name", ":", "name", ".", "substr", "(", "0", ",", "idx", ")", ";", "}" ]
Remove the .js extension to make these proper module names.
[ "Remove", "the", ".", "js", "extension", "to", "make", "these", "proper", "module", "names", "." ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/loader/find_bundle.js#L69-L72
20,869
stealjs/steal-tools
lib/loader/normalize_bundle.js
getLoader
function getLoader(data) { if(typeof Loader !== "undefined" && (data instanceof global.Loader)) { return data; } else if(typeof LoaderPolyfill !== "undefined" && (data instanceof global.LoaderPolyfill)) { return data; } else { return data.steal.System; } }
javascript
function getLoader(data) { if(typeof Loader !== "undefined" && (data instanceof global.Loader)) { return data; } else if(typeof LoaderPolyfill !== "undefined" && (data instanceof global.LoaderPolyfill)) { return data; } else { return data.steal.System; } }
[ "function", "getLoader", "(", "data", ")", "{", "if", "(", "typeof", "Loader", "!==", "\"undefined\"", "&&", "(", "data", "instanceof", "global", ".", "Loader", ")", ")", "{", "return", "data", ";", "}", "else", "if", "(", "typeof", "LoaderPolyfill", "!==", "\"undefined\"", "&&", "(", "data", "instanceof", "global", ".", "LoaderPolyfill", ")", ")", "{", "return", "data", ";", "}", "else", "{", "return", "data", ".", "steal", ".", "System", ";", "}", "}" ]
We could directly receive a loader or this might be a dependencyGraph object containing the loader.
[ "We", "could", "directly", "receive", "a", "loader", "or", "this", "might", "be", "a", "dependencyGraph", "object", "containing", "the", "loader", "." ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/loader/normalize_bundle.js#L19-L27
20,870
stealjs/steal-tools
lib/stream/adjust_bundles_path.js
adjustBundlesPath
function adjustBundlesPath(data, options) { var path = require("path"); var configuration = clone(data.configuration); var bundlesPath = configuration.bundlesPath; Object.defineProperty(configuration, "bundlesPath", { configurable: true, get: function() { return path.join(bundlesPath, options.target); } }); return assign({}, omit(data, ["configuration"]), { configuration: configuration }); }
javascript
function adjustBundlesPath(data, options) { var path = require("path"); var configuration = clone(data.configuration); var bundlesPath = configuration.bundlesPath; Object.defineProperty(configuration, "bundlesPath", { configurable: true, get: function() { return path.join(bundlesPath, options.target); } }); return assign({}, omit(data, ["configuration"]), { configuration: configuration }); }
[ "function", "adjustBundlesPath", "(", "data", ",", "options", ")", "{", "var", "path", "=", "require", "(", "\"path\"", ")", ";", "var", "configuration", "=", "clone", "(", "data", ".", "configuration", ")", ";", "var", "bundlesPath", "=", "configuration", ".", "bundlesPath", ";", "Object", ".", "defineProperty", "(", "configuration", ",", "\"bundlesPath\"", ",", "{", "configurable", ":", "true", ",", "get", ":", "function", "(", ")", "{", "return", "path", ".", "join", "(", "bundlesPath", ",", "options", ".", "target", ")", ";", "}", "}", ")", ";", "return", "assign", "(", "{", "}", ",", "omit", "(", "data", ",", "[", "\"configuration\"", "]", ")", ",", "{", "configuration", ":", "configuration", "}", ")", ";", "}" ]
Appends the target name to the bundles path Each target build should be written in its own subfolder, e.g: dist/bundles/node dist/bundles/web dist/bundles/worker This should only happen when target is explicitly set.
[ "Appends", "the", "target", "name", "to", "the", "bundles", "path" ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/stream/adjust_bundles_path.js#L27-L42
20,871
stealjs/steal-tools
lib/graph/make_graph_with_bundles.js
mergeIntoMasterAndAddBundle
function mergeIntoMasterAndAddBundle(opts) { var mains = opts.mains; var loader = opts.loader; var newGraph = opts.newGraph; var bundleName = opts.bundleName; var masterGraph = opts.masterGraph; for(var name in newGraph) { var oldNode = masterGraph[name]; var newNode = newGraph[name]; if(!oldNode || hasNewDeps(oldNode, newNode)) { masterGraph[name] = newGraph[name]; } // If it's a plugin we'll use the new node but need to copy any previous // bundles onto the new node else if(masterGraph[name] && masterGraph[name].isPlugin) { var oldBundle = masterGraph[name].bundles || []; masterGraph[name] = newGraph[name]; oldBundle.forEach(function(bundle){ addBundle(masterGraph[name], bundle); }); } // If this is the configMain like package.json!npm we need to override // the source every time because it continuously changes. else if(masterGraph[name] && name === loader.configMain) { var node = masterGraph[name]; node.load.source = newGraph[name].load.source; } // do not track bundles of entry point modules (a.k.a mains) unless // it is its own bundle. if (name === bundleName || !includes(mains, name)) { addBundle(masterGraph[name], bundleName); } } }
javascript
function mergeIntoMasterAndAddBundle(opts) { var mains = opts.mains; var loader = opts.loader; var newGraph = opts.newGraph; var bundleName = opts.bundleName; var masterGraph = opts.masterGraph; for(var name in newGraph) { var oldNode = masterGraph[name]; var newNode = newGraph[name]; if(!oldNode || hasNewDeps(oldNode, newNode)) { masterGraph[name] = newGraph[name]; } // If it's a plugin we'll use the new node but need to copy any previous // bundles onto the new node else if(masterGraph[name] && masterGraph[name].isPlugin) { var oldBundle = masterGraph[name].bundles || []; masterGraph[name] = newGraph[name]; oldBundle.forEach(function(bundle){ addBundle(masterGraph[name], bundle); }); } // If this is the configMain like package.json!npm we need to override // the source every time because it continuously changes. else if(masterGraph[name] && name === loader.configMain) { var node = masterGraph[name]; node.load.source = newGraph[name].load.source; } // do not track bundles of entry point modules (a.k.a mains) unless // it is its own bundle. if (name === bundleName || !includes(mains, name)) { addBundle(masterGraph[name], bundleName); } } }
[ "function", "mergeIntoMasterAndAddBundle", "(", "opts", ")", "{", "var", "mains", "=", "opts", ".", "mains", ";", "var", "loader", "=", "opts", ".", "loader", ";", "var", "newGraph", "=", "opts", ".", "newGraph", ";", "var", "bundleName", "=", "opts", ".", "bundleName", ";", "var", "masterGraph", "=", "opts", ".", "masterGraph", ";", "for", "(", "var", "name", "in", "newGraph", ")", "{", "var", "oldNode", "=", "masterGraph", "[", "name", "]", ";", "var", "newNode", "=", "newGraph", "[", "name", "]", ";", "if", "(", "!", "oldNode", "||", "hasNewDeps", "(", "oldNode", ",", "newNode", ")", ")", "{", "masterGraph", "[", "name", "]", "=", "newGraph", "[", "name", "]", ";", "}", "// If it's a plugin we'll use the new node but need to copy any previous", "// bundles onto the new node", "else", "if", "(", "masterGraph", "[", "name", "]", "&&", "masterGraph", "[", "name", "]", ".", "isPlugin", ")", "{", "var", "oldBundle", "=", "masterGraph", "[", "name", "]", ".", "bundles", "||", "[", "]", ";", "masterGraph", "[", "name", "]", "=", "newGraph", "[", "name", "]", ";", "oldBundle", ".", "forEach", "(", "function", "(", "bundle", ")", "{", "addBundle", "(", "masterGraph", "[", "name", "]", ",", "bundle", ")", ";", "}", ")", ";", "}", "// If this is the configMain like package.json!npm we need to override", "// the source every time because it continuously changes.", "else", "if", "(", "masterGraph", "[", "name", "]", "&&", "name", "===", "loader", ".", "configMain", ")", "{", "var", "node", "=", "masterGraph", "[", "name", "]", ";", "node", ".", "load", ".", "source", "=", "newGraph", "[", "name", "]", ".", "load", ".", "source", ";", "}", "// do not track bundles of entry point modules (a.k.a mains) unless", "// it is its own bundle.", "if", "(", "name", "===", "bundleName", "||", "!", "includes", "(", "mains", ",", "name", ")", ")", "{", "addBundle", "(", "masterGraph", "[", "name", "]", ",", "bundleName", ")", ";", "}", "}", "}" ]
merges everything in `newGraph` into `masterGraph` and make sure it lists `bundle` as one of its bundles.
[ "merges", "everything", "in", "newGraph", "into", "masterGraph", "and", "make", "sure", "it", "lists", "bundle", "as", "one", "of", "its", "bundles", "." ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/graph/make_graph_with_bundles.js#L36-L72
20,872
stealjs/steal-tools
lib/graph/make_graph_with_bundles.js
createModuleConfig
function createModuleConfig(loader) { var tmp = require("tmp"); var config = {}; var virtualModules = loader.virtualModules || {}; for(var moduleName in virtualModules) { var filename = tmp.fileSync().name; var source = virtualModules[moduleName]; fs.writeFileSync(filename, source, "utf8"); var paths = config.paths = config.paths || {}; paths[moduleName] = "file:"+filename; } return config; }
javascript
function createModuleConfig(loader) { var tmp = require("tmp"); var config = {}; var virtualModules = loader.virtualModules || {}; for(var moduleName in virtualModules) { var filename = tmp.fileSync().name; var source = virtualModules[moduleName]; fs.writeFileSync(filename, source, "utf8"); var paths = config.paths = config.paths || {}; paths[moduleName] = "file:"+filename; } return config; }
[ "function", "createModuleConfig", "(", "loader", ")", "{", "var", "tmp", "=", "require", "(", "\"tmp\"", ")", ";", "var", "config", "=", "{", "}", ";", "var", "virtualModules", "=", "loader", ".", "virtualModules", "||", "{", "}", ";", "for", "(", "var", "moduleName", "in", "virtualModules", ")", "{", "var", "filename", "=", "tmp", ".", "fileSync", "(", ")", ".", "name", ";", "var", "source", "=", "virtualModules", "[", "moduleName", "]", ";", "fs", ".", "writeFileSync", "(", "filename", ",", "source", ",", "\"utf8\"", ")", ";", "var", "paths", "=", "config", ".", "paths", "=", "config", ".", "paths", "||", "{", "}", ";", "paths", "[", "moduleName", "]", "=", "\"file:\"", "+", "filename", ";", "}", "return", "config", ";", "}" ]
Create temporary files for virtual modules.
[ "Create", "temporary", "files", "for", "virtual", "modules", "." ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/graph/make_graph_with_bundles.js#L75-L88
20,873
stealjs/steal-tools
lib/graph/make_graph_with_bundles.js
copyIfSet
function copyIfSet(src, dest, prop) { if (src[prop]) { dest[prop] = src[prop]; } }
javascript
function copyIfSet(src, dest, prop) { if (src[prop]) { dest[prop] = src[prop]; } }
[ "function", "copyIfSet", "(", "src", ",", "dest", ",", "prop", ")", "{", "if", "(", "src", "[", "prop", "]", ")", "{", "dest", "[", "prop", "]", "=", "src", "[", "prop", "]", ";", "}", "}" ]
If `prop` exists in the `src` object, it copies its value to `dest`
[ "If", "prop", "exists", "in", "the", "src", "object", "it", "copies", "its", "value", "to", "dest" ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/graph/make_graph_with_bundles.js#L91-L95
20,874
stealjs/steal-tools
lib/stream/add_plugin_names.js
addPluginName
function addPluginName(data) { var loader = data.loader; var bundles = data.bundles; var promises = bundles.map(function(bundle) { if (!isJavaScriptBundle(bundle)) { return loader.normalize(bundle.name).then(function(name) { bundle.pluginName = name.substring(name.indexOf("!") + 1); }); } }); return Promise.all(promises).then(function() { return data; }); }
javascript
function addPluginName(data) { var loader = data.loader; var bundles = data.bundles; var promises = bundles.map(function(bundle) { if (!isJavaScriptBundle(bundle)) { return loader.normalize(bundle.name).then(function(name) { bundle.pluginName = name.substring(name.indexOf("!") + 1); }); } }); return Promise.all(promises).then(function() { return data; }); }
[ "function", "addPluginName", "(", "data", ")", "{", "var", "loader", "=", "data", ".", "loader", ";", "var", "bundles", "=", "data", ".", "bundles", ";", "var", "promises", "=", "bundles", ".", "map", "(", "function", "(", "bundle", ")", "{", "if", "(", "!", "isJavaScriptBundle", "(", "bundle", ")", ")", "{", "return", "loader", ".", "normalize", "(", "bundle", ".", "name", ")", ".", "then", "(", "function", "(", "name", ")", "{", "bundle", ".", "pluginName", "=", "name", ".", "substring", "(", "name", ".", "indexOf", "(", "\"!\"", ")", "+", "1", ")", ";", "}", ")", ";", "}", "}", ")", ";", "return", "Promise", ".", "all", "(", "promises", ")", ".", "then", "(", "function", "(", ")", "{", "return", "data", ";", "}", ")", ";", "}" ]
Adds `pluginName` property to non JS bundles
[ "Adds", "pluginName", "property", "to", "non", "JS", "bundles" ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/stream/add_plugin_names.js#L17-L32
20,875
stealjs/steal-tools
lib/stream/write_bundle_manifest.js
getWeightOf
function getWeightOf(bundle) { var isCss = bundle.buildType === "css"; var isMainBundle = bundle.bundles.length === 1; if (isCss) { return 1; } else if (isMainBundle) { return 2; } else { return 3; } }
javascript
function getWeightOf(bundle) { var isCss = bundle.buildType === "css"; var isMainBundle = bundle.bundles.length === 1; if (isCss) { return 1; } else if (isMainBundle) { return 2; } else { return 3; } }
[ "function", "getWeightOf", "(", "bundle", ")", "{", "var", "isCss", "=", "bundle", ".", "buildType", "===", "\"css\"", ";", "var", "isMainBundle", "=", "bundle", ".", "bundles", ".", "length", "===", "1", ";", "if", "(", "isCss", ")", "{", "return", "1", ";", "}", "else", "if", "(", "isMainBundle", ")", "{", "return", "2", ";", "}", "else", "{", "return", "3", ";", "}", "}" ]
A very simplified version of HTTP2 stream priorities Bundles with the lowest weight should be loaded first @param {Object} bundle - A bundle object @return {Number} 1 for css bundles, 2 for main JS bundles, 3 for shared bundles
[ "A", "very", "simplified", "version", "of", "HTTP2", "stream", "priorities", "Bundles", "with", "the", "lowest", "weight", "should", "be", "loaded", "first" ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/stream/write_bundle_manifest.js#L72-L83
20,876
stealjs/steal-tools
lib/stream/write_bundle_manifest.js
getSharedBundlesOf
function getSharedBundlesOf(name, baseUrl, bundles, mains) { var shared = {}; var normalize = require("normalize-path"); // this will ensure that we only add the main bundle if there is a single // main; not a multi-main project. var singleMain = mains.length === 1 && mains[0]; bundles.forEach(function(bundle) { if (includes(bundle.bundles, name) || includes(bundle.bundles, singleMain)) { var relative = normalize( path.relative( baseUrl.replace("file:", ""), bundle.bundlePath ) ); shared[relative] = { weight: getWeightOf(bundle), type: isJavaScriptBundle(bundle) ? "script" : "style" }; } }); return shared; }
javascript
function getSharedBundlesOf(name, baseUrl, bundles, mains) { var shared = {}; var normalize = require("normalize-path"); // this will ensure that we only add the main bundle if there is a single // main; not a multi-main project. var singleMain = mains.length === 1 && mains[0]; bundles.forEach(function(bundle) { if (includes(bundle.bundles, name) || includes(bundle.bundles, singleMain)) { var relative = normalize( path.relative( baseUrl.replace("file:", ""), bundle.bundlePath ) ); shared[relative] = { weight: getWeightOf(bundle), type: isJavaScriptBundle(bundle) ? "script" : "style" }; } }); return shared; }
[ "function", "getSharedBundlesOf", "(", "name", ",", "baseUrl", ",", "bundles", ",", "mains", ")", "{", "var", "shared", "=", "{", "}", ";", "var", "normalize", "=", "require", "(", "\"normalize-path\"", ")", ";", "// this will ensure that we only add the main bundle if there is a single", "// main; not a multi-main project.", "var", "singleMain", "=", "mains", ".", "length", "===", "1", "&&", "mains", "[", "0", "]", ";", "bundles", ".", "forEach", "(", "function", "(", "bundle", ")", "{", "if", "(", "includes", "(", "bundle", ".", "bundles", ",", "name", ")", "||", "includes", "(", "bundle", ".", "bundles", ",", "singleMain", ")", ")", "{", "var", "relative", "=", "normalize", "(", "path", ".", "relative", "(", "baseUrl", ".", "replace", "(", "\"file:\"", ",", "\"\"", ")", ",", "bundle", ".", "bundlePath", ")", ")", ";", "shared", "[", "relative", "]", "=", "{", "weight", ":", "getWeightOf", "(", "bundle", ")", ",", "type", ":", "isJavaScriptBundle", "(", "bundle", ")", "?", "\"script\"", ":", "\"style\"", "}", ";", "}", "}", ")", ";", "return", "shared", ";", "}" ]
Returns an object of shared bundles data @param {string} name - A bundle name @param {string} baseUrl - The loader's baseURL @param {Array} bundles - The bundles array created by the build process @param {Array} mains - The main entry point modules @return {Object} Each key is a shared bundle relative path and the value contains the `weight` and `type` of the bundle
[ "Returns", "an", "object", "of", "shared", "bundles", "data" ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/stream/write_bundle_manifest.js#L94-L119
20,877
stealjs/steal-tools
lib/bundle/make_bundles_config.js
getBundlesPaths
function getBundlesPaths(configuration){ // If a bundlesPath is not provided, the paths are not needed because they are // already set up in steal.js if(!configuration.loader.bundlesPath) { return ""; } var bundlesPath = configuration.bundlesPathURL; // Get the dist directory and set the paths output var paths = util.format('\tSystem.paths["bundles/*.css"] ="%s/*css";\n' + '\tSystem.paths["bundles/*"] = "%s/*.js";\n', bundlesPath, bundlesPath); return "if(!System.bundlesPath) {\n" + paths + "}\n"; }
javascript
function getBundlesPaths(configuration){ // If a bundlesPath is not provided, the paths are not needed because they are // already set up in steal.js if(!configuration.loader.bundlesPath) { return ""; } var bundlesPath = configuration.bundlesPathURL; // Get the dist directory and set the paths output var paths = util.format('\tSystem.paths["bundles/*.css"] ="%s/*css";\n' + '\tSystem.paths["bundles/*"] = "%s/*.js";\n', bundlesPath, bundlesPath); return "if(!System.bundlesPath) {\n" + paths + "}\n"; }
[ "function", "getBundlesPaths", "(", "configuration", ")", "{", "// If a bundlesPath is not provided, the paths are not needed because they are", "// already set up in steal.js", "if", "(", "!", "configuration", ".", "loader", ".", "bundlesPath", ")", "{", "return", "\"\"", ";", "}", "var", "bundlesPath", "=", "configuration", ".", "bundlesPathURL", ";", "// Get the dist directory and set the paths output", "var", "paths", "=", "util", ".", "format", "(", "'\\tSystem.paths[\"bundles/*.css\"] =\"%s/*css\";\\n'", "+", "'\\tSystem.paths[\"bundles/*\"] = \"%s/*.js\";\\n'", ",", "bundlesPath", ",", "bundlesPath", ")", ";", "return", "\"if(!System.bundlesPath) {\\n\"", "+", "paths", "+", "\"}\\n\"", ";", "}" ]
Get the System.paths needed to map bundles, if a different bundlesPath is provided.
[ "Get", "the", "System", ".", "paths", "needed", "to", "map", "bundles", "if", "a", "different", "bundlesPath", "is", "provided", "." ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/bundle/make_bundles_config.js#L57-L70
20,878
stealjs/steal-tools
lib/graph/recycle.js
regenerate
function regenerate(moduleName, done){ var cfg = clone(config, true); // if the moduleName is not in the graph, make it the main. if(moduleName && !cachedData.graph[moduleName]) { cfg.main = moduleName; } makeBundleGraph(cfg, options).then(function(data){ var graph = data.graph; var oldGraph = cachedData ? cachedData.graph : {}; for(var name in graph){ if(name !== moduleName && oldGraph[name]) { graph[name].transforms = oldGraph[name].transforms; } } cachedData = cloneData(data); done(null, data); }, done); }
javascript
function regenerate(moduleName, done){ var cfg = clone(config, true); // if the moduleName is not in the graph, make it the main. if(moduleName && !cachedData.graph[moduleName]) { cfg.main = moduleName; } makeBundleGraph(cfg, options).then(function(data){ var graph = data.graph; var oldGraph = cachedData ? cachedData.graph : {}; for(var name in graph){ if(name !== moduleName && oldGraph[name]) { graph[name].transforms = oldGraph[name].transforms; } } cachedData = cloneData(data); done(null, data); }, done); }
[ "function", "regenerate", "(", "moduleName", ",", "done", ")", "{", "var", "cfg", "=", "clone", "(", "config", ",", "true", ")", ";", "// if the moduleName is not in the graph, make it the main.", "if", "(", "moduleName", "&&", "!", "cachedData", ".", "graph", "[", "moduleName", "]", ")", "{", "cfg", ".", "main", "=", "moduleName", ";", "}", "makeBundleGraph", "(", "cfg", ",", "options", ")", ".", "then", "(", "function", "(", "data", ")", "{", "var", "graph", "=", "data", ".", "graph", ";", "var", "oldGraph", "=", "cachedData", "?", "cachedData", ".", "graph", ":", "{", "}", ";", "for", "(", "var", "name", "in", "graph", ")", "{", "if", "(", "name", "!==", "moduleName", "&&", "oldGraph", "[", "name", "]", ")", "{", "graph", "[", "name", "]", ".", "transforms", "=", "oldGraph", "[", "name", "]", ".", "transforms", ";", "}", "}", "cachedData", "=", "cloneData", "(", "data", ")", ";", "done", "(", "null", ",", "data", ")", ";", "}", ",", "done", ")", ";", "}" ]
Regenerate a new bundle graph and copy over the transforms so they can be reused.
[ "Regenerate", "a", "new", "bundle", "graph", "and", "copy", "over", "the", "transforms", "so", "they", "can", "be", "reused", "." ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/graph/recycle.js#L18-L36
20,879
stealjs/steal-tools
lib/graph/recycle.js
diff
function diff(node) { var oldBundle = (cachedData.loader.bundle || []).slice(); return getDependencies(node.load).then(function(result){ var newBundle = (cachedData.loader.bundle || []).slice(); // If the deps are the same we can return the existing graph. if(same(node.deps, result.deps) && same(oldBundle, newBundle)) { clean(node, result.source); if(result.virtualModules.length) { var promises = result.virtualModules.map(function(l){ var node = cachedData.graph[l.name]; node.load.source = l.source; node.load.metadata.useSource = true; return diff(node); }); return Promise.all(promises).then(function(results){ result.same = results.every(function(res){ return res.same; }); return result; }); } result.same = true; } return result; }); }
javascript
function diff(node) { var oldBundle = (cachedData.loader.bundle || []).slice(); return getDependencies(node.load).then(function(result){ var newBundle = (cachedData.loader.bundle || []).slice(); // If the deps are the same we can return the existing graph. if(same(node.deps, result.deps) && same(oldBundle, newBundle)) { clean(node, result.source); if(result.virtualModules.length) { var promises = result.virtualModules.map(function(l){ var node = cachedData.graph[l.name]; node.load.source = l.source; node.load.metadata.useSource = true; return diff(node); }); return Promise.all(promises).then(function(results){ result.same = results.every(function(res){ return res.same; }); return result; }); } result.same = true; } return result; }); }
[ "function", "diff", "(", "node", ")", "{", "var", "oldBundle", "=", "(", "cachedData", ".", "loader", ".", "bundle", "||", "[", "]", ")", ".", "slice", "(", ")", ";", "return", "getDependencies", "(", "node", ".", "load", ")", ".", "then", "(", "function", "(", "result", ")", "{", "var", "newBundle", "=", "(", "cachedData", ".", "loader", ".", "bundle", "||", "[", "]", ")", ".", "slice", "(", ")", ";", "// If the deps are the same we can return the existing graph.", "if", "(", "same", "(", "node", ".", "deps", ",", "result", ".", "deps", ")", "&&", "same", "(", "oldBundle", ",", "newBundle", ")", ")", "{", "clean", "(", "node", ",", "result", ".", "source", ")", ";", "if", "(", "result", ".", "virtualModules", ".", "length", ")", "{", "var", "promises", "=", "result", ".", "virtualModules", ".", "map", "(", "function", "(", "l", ")", "{", "var", "node", "=", "cachedData", ".", "graph", "[", "l", ".", "name", "]", ";", "node", ".", "load", ".", "source", "=", "l", ".", "source", ";", "node", ".", "load", ".", "metadata", ".", "useSource", "=", "true", ";", "return", "diff", "(", "node", ")", ";", "}", ")", ";", "return", "Promise", ".", "all", "(", "promises", ")", ".", "then", "(", "function", "(", "results", ")", "{", "result", ".", "same", "=", "results", ".", "every", "(", "function", "(", "res", ")", "{", "return", "res", ".", "same", ";", "}", ")", ";", "return", "result", ";", "}", ")", ";", "}", "result", ".", "same", "=", "true", ";", "}", "return", "result", ";", "}", ")", ";", "}" ]
Check to see if the node has changed. Do this by looking at the source and running it through System.instantiate to see if new deps were added. Recursively do the same for any System.defined modules.
[ "Check", "to", "see", "if", "the", "node", "has", "changed", ".", "Do", "this", "by", "looking", "at", "the", "source", "and", "running", "it", "through", "System", ".", "instantiate", "to", "see", "if", "new", "deps", "were", "added", ".", "Recursively", "do", "the", "same", "for", "any", "System", ".", "defined", "modules", "." ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/graph/recycle.js#L97-L129
20,880
stealjs/steal-tools
lib/stream/envify.js
inlineNodeEnvironmentVariables
function inlineNodeEnvironmentVariables(data) { var dependencyGraph = data.graph; var configuration = data.configuration; var options = configuration.options; if (options.envify) { winston.info("Inlining Node-style environment variables..."); envifyGraph(dependencyGraph, options); envifyGraph(data.configGraph, options); } return data; }
javascript
function inlineNodeEnvironmentVariables(data) { var dependencyGraph = data.graph; var configuration = data.configuration; var options = configuration.options; if (options.envify) { winston.info("Inlining Node-style environment variables..."); envifyGraph(dependencyGraph, options); envifyGraph(data.configGraph, options); } return data; }
[ "function", "inlineNodeEnvironmentVariables", "(", "data", ")", "{", "var", "dependencyGraph", "=", "data", ".", "graph", ";", "var", "configuration", "=", "data", ".", "configuration", ";", "var", "options", "=", "configuration", ".", "options", ";", "if", "(", "options", ".", "envify", ")", "{", "winston", ".", "info", "(", "\"Inlining Node-style environment variables...\"", ")", ";", "envifyGraph", "(", "dependencyGraph", ",", "options", ")", ";", "envifyGraph", "(", "data", ".", "configGraph", ",", "options", ")", ";", "}", "return", "data", ";", "}" ]
Replaces Node-style environment variables with plain strings.
[ "Replaces", "Node", "-", "style", "environment", "variables", "with", "plain", "strings", "." ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/stream/envify.js#L16-L28
20,881
stealjs/steal-tools
lib/process_babel_presets.js
getPresetName
function getPresetName(preset) { if (includesPresetName(preset)) { return _.isString(preset) ? preset : _.head(preset); } else { return null; } }
javascript
function getPresetName(preset) { if (includesPresetName(preset)) { return _.isString(preset) ? preset : _.head(preset); } else { return null; } }
[ "function", "getPresetName", "(", "preset", ")", "{", "if", "(", "includesPresetName", "(", "preset", ")", ")", "{", "return", "_", ".", "isString", "(", "preset", ")", "?", "preset", ":", "_", ".", "head", "(", "preset", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Gets the babel preset name @param {BabelPreset} preset A babel preset @return {?string} The preset name
[ "Gets", "the", "babel", "preset", "name" ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/process_babel_presets.js#L92-L99
20,882
stealjs/steal-tools
lib/process_babel_presets.js
includesPresetName
function includesPresetName(preset) { return _.isString(preset) || _.isArray(preset) && _.isString(_.head(preset)); }
javascript
function includesPresetName(preset) { return _.isString(preset) || _.isArray(preset) && _.isString(_.head(preset)); }
[ "function", "includesPresetName", "(", "preset", ")", "{", "return", "_", ".", "isString", "(", "preset", ")", "||", "_", ".", "isArray", "(", "preset", ")", "&&", "_", ".", "isString", "(", "_", ".", "head", "(", "preset", ")", ")", ";", "}" ]
Whether the babel preset name was provided @param {BabelPreset} preset @return {boolean}
[ "Whether", "the", "babel", "preset", "name", "was", "provided" ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/process_babel_presets.js#L106-L109
20,883
stealjs/steal-tools
lib/process_babel_presets.js
isBuiltinPreset
function isBuiltinPreset(name) { var isNpmPresetName = /^(?:babel-preset-)/; var availablePresets = babel.availablePresets || {}; var shorthand = isNpmPresetName.test(name) ? name.replace("babel-preset-", "") : name; return !!availablePresets[shorthand]; }
javascript
function isBuiltinPreset(name) { var isNpmPresetName = /^(?:babel-preset-)/; var availablePresets = babel.availablePresets || {}; var shorthand = isNpmPresetName.test(name) ? name.replace("babel-preset-", "") : name; return !!availablePresets[shorthand]; }
[ "function", "isBuiltinPreset", "(", "name", ")", "{", "var", "isNpmPresetName", "=", "/", "^(?:babel-preset-)", "/", ";", "var", "availablePresets", "=", "babel", ".", "availablePresets", "||", "{", "}", ";", "var", "shorthand", "=", "isNpmPresetName", ".", "test", "(", "name", ")", "?", "name", ".", "replace", "(", "\"babel-preset-\"", ",", "\"\"", ")", ":", "name", ";", "return", "!", "!", "availablePresets", "[", "shorthand", "]", ";", "}" ]
Whether the preset is built in babel-standalone @param {string} name A preset path @return {boolean} `true` if preset is builtin, `false` otherwise Babel presets can be set using the following variations: 1) the npm preset name, which by convention starts with `babel-preset-` 2) A shorthand name, which is the npm name without the prefix 3) A path to where the preset is defined babel-standalone registers the builtin presets using the shorthand version.
[ "Whether", "the", "preset", "is", "built", "in", "babel", "-", "standalone" ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/process_babel_presets.js#L139-L148
20,884
stealjs/steal-tools
lib/stream/load_node_builder.js
loadNodeBuilder
function loadNodeBuilder(data) { return new Promise(function(resolve, reject) { var graph = data.graph; var loader = data.loader; var promises = keys(graph).map(function(nodeName) { var node = graph[nodeName]; // pluginBuilder | extensionBuilder is a module identifier that // should be loaded to replace the node's source during the build var nodeBuilder = node.value && (node.value.pluginBuilder || node.value.extensionBuilder); // nothing to do in this case, return right away if (!nodeBuilder) return; return loader .normalize(nodeBuilder) .then(locate) .then(_fetch) .then(makeReplace(node)); }); function locate(name) { return Promise.all([name, loader.locate({ name: name, metadata: {} })]); } // [ name, address ] function _fetch(data) { return Promise.all([ data[1], loader.fetch({ name: data[0], address: data[1], metadata: {} }) ]); } function makeReplace(node) { // [ address, load ] return function replace(data) { node.load = assign(node.load, { address: data[0], source: data[1], metadata: {} }); }; } Promise.all(promises) .then(function() { resolve(graph); }) .catch(reject); }); }
javascript
function loadNodeBuilder(data) { return new Promise(function(resolve, reject) { var graph = data.graph; var loader = data.loader; var promises = keys(graph).map(function(nodeName) { var node = graph[nodeName]; // pluginBuilder | extensionBuilder is a module identifier that // should be loaded to replace the node's source during the build var nodeBuilder = node.value && (node.value.pluginBuilder || node.value.extensionBuilder); // nothing to do in this case, return right away if (!nodeBuilder) return; return loader .normalize(nodeBuilder) .then(locate) .then(_fetch) .then(makeReplace(node)); }); function locate(name) { return Promise.all([name, loader.locate({ name: name, metadata: {} })]); } // [ name, address ] function _fetch(data) { return Promise.all([ data[1], loader.fetch({ name: data[0], address: data[1], metadata: {} }) ]); } function makeReplace(node) { // [ address, load ] return function replace(data) { node.load = assign(node.load, { address: data[0], source: data[1], metadata: {} }); }; } Promise.all(promises) .then(function() { resolve(graph); }) .catch(reject); }); }
[ "function", "loadNodeBuilder", "(", "data", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "graph", "=", "data", ".", "graph", ";", "var", "loader", "=", "data", ".", "loader", ";", "var", "promises", "=", "keys", "(", "graph", ")", ".", "map", "(", "function", "(", "nodeName", ")", "{", "var", "node", "=", "graph", "[", "nodeName", "]", ";", "// pluginBuilder | extensionBuilder is a module identifier that", "// should be loaded to replace the node's source during the build", "var", "nodeBuilder", "=", "node", ".", "value", "&&", "(", "node", ".", "value", ".", "pluginBuilder", "||", "node", ".", "value", ".", "extensionBuilder", ")", ";", "// nothing to do in this case, return right away", "if", "(", "!", "nodeBuilder", ")", "return", ";", "return", "loader", ".", "normalize", "(", "nodeBuilder", ")", ".", "then", "(", "locate", ")", ".", "then", "(", "_fetch", ")", ".", "then", "(", "makeReplace", "(", "node", ")", ")", ";", "}", ")", ";", "function", "locate", "(", "name", ")", "{", "return", "Promise", ".", "all", "(", "[", "name", ",", "loader", ".", "locate", "(", "{", "name", ":", "name", ",", "metadata", ":", "{", "}", "}", ")", "]", ")", ";", "}", "// [ name, address ]", "function", "_fetch", "(", "data", ")", "{", "return", "Promise", ".", "all", "(", "[", "data", "[", "1", "]", ",", "loader", ".", "fetch", "(", "{", "name", ":", "data", "[", "0", "]", ",", "address", ":", "data", "[", "1", "]", ",", "metadata", ":", "{", "}", "}", ")", "]", ")", ";", "}", "function", "makeReplace", "(", "node", ")", "{", "// [ address, load ]", "return", "function", "replace", "(", "data", ")", "{", "node", ".", "load", "=", "assign", "(", "node", ".", "load", ",", "{", "address", ":", "data", "[", "0", "]", ",", "source", ":", "data", "[", "1", "]", ",", "metadata", ":", "{", "}", "}", ")", ";", "}", ";", "}", "Promise", ".", "all", "(", "promises", ")", ".", "then", "(", "function", "(", ")", "{", "resolve", "(", "graph", ")", ";", "}", ")", ".", "catch", "(", "reject", ")", ";", "}", ")", ";", "}" ]
Replaces a node source with its builder module @param {Object} data - The stream's data object @return {Promise.<graph>}
[ "Replaces", "a", "node", "source", "with", "its", "builder", "module" ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/stream/load_node_builder.js#L20-L72
20,885
stealjs/steal-tools
lib/build/export.js
normalize
function normalize(loader, mods) { var modNames = (mods && !Array.isArray(mods)) ? [mods] : mods; return (modNames || []).map(function(moduleName) { return !_.isString(moduleName) ? Promise.resolve(moduleName) : loader.normalize(moduleName); }); }
javascript
function normalize(loader, mods) { var modNames = (mods && !Array.isArray(mods)) ? [mods] : mods; return (modNames || []).map(function(moduleName) { return !_.isString(moduleName) ? Promise.resolve(moduleName) : loader.normalize(moduleName); }); }
[ "function", "normalize", "(", "loader", ",", "mods", ")", "{", "var", "modNames", "=", "(", "mods", "&&", "!", "Array", ".", "isArray", "(", "mods", ")", ")", "?", "[", "mods", "]", ":", "mods", ";", "return", "(", "modNames", "||", "[", "]", ")", ".", "map", "(", "function", "(", "moduleName", ")", "{", "return", "!", "_", ".", "isString", "(", "moduleName", ")", "?", "Promise", ".", "resolve", "(", "moduleName", ")", ":", "loader", ".", "normalize", "(", "moduleName", ")", ";", "}", ")", ";", "}" ]
Normalize module names @param {string|Array.<string>} mods A module name (or a list of them) @return {Array.<Promise.<string>>} An array of promises that resolved to normalized module names.
[ "Normalize", "module", "names" ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/build/export.js#L54-L62
20,886
stealjs/steal-tools
lib/graph/slim_graph.js
isExcludedFromBuild
function isExcludedFromBuild(node) { if (node.load.excludeFromBuild) { return true; } if ( node.load.metadata && node.load.metadata.hasOwnProperty("bundle") && node.load.metadata.bundle === false ) { return true; } if ( node.isPlugin && !node.value.includeInBuild && !node.load.metadata.includeInBuild ) { return true; } return false; }
javascript
function isExcludedFromBuild(node) { if (node.load.excludeFromBuild) { return true; } if ( node.load.metadata && node.load.metadata.hasOwnProperty("bundle") && node.load.metadata.bundle === false ) { return true; } if ( node.isPlugin && !node.value.includeInBuild && !node.load.metadata.includeInBuild ) { return true; } return false; }
[ "function", "isExcludedFromBuild", "(", "node", ")", "{", "if", "(", "node", ".", "load", ".", "excludeFromBuild", ")", "{", "return", "true", ";", "}", "if", "(", "node", ".", "load", ".", "metadata", "&&", "node", ".", "load", ".", "metadata", ".", "hasOwnProperty", "(", "\"bundle\"", ")", "&&", "node", ".", "load", ".", "metadata", ".", "bundle", "===", "false", ")", "{", "return", "true", ";", "}", "if", "(", "node", ".", "isPlugin", "&&", "!", "node", ".", "value", ".", "includeInBuild", "&&", "!", "node", ".", "load", ".", "metadata", ".", "includeInBuild", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Whether the node is flagged to be removed from the build @param {Object} node - A node from a bundle @return {boolean} `true` if flagged, `false` otherwise
[ "Whether", "the", "node", "is", "flagged", "to", "be", "removed", "from", "the", "build" ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/graph/slim_graph.js#L198-L220
20,887
stealjs/steal-tools
lib/graph/make_graph.js
ignoredMetas
function ignoredMetas(cfgs, metas){ cfgs = cfgs || {}; Object.keys(metas).forEach(function(name){ var cfg = metas[name]; if(cfg && cfg.bundle === false) { cfgs[name] = cfg; } }); return { meta: cfgs }; }
javascript
function ignoredMetas(cfgs, metas){ cfgs = cfgs || {}; Object.keys(metas).forEach(function(name){ var cfg = metas[name]; if(cfg && cfg.bundle === false) { cfgs[name] = cfg; } }); return { meta: cfgs }; }
[ "function", "ignoredMetas", "(", "cfgs", ",", "metas", ")", "{", "cfgs", "=", "cfgs", "||", "{", "}", ";", "Object", ".", "keys", "(", "metas", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "var", "cfg", "=", "metas", "[", "name", "]", ";", "if", "(", "cfg", "&&", "cfg", ".", "bundle", "===", "false", ")", "{", "cfgs", "[", "name", "]", "=", "cfg", ";", "}", "}", ")", ";", "return", "{", "meta", ":", "cfgs", "}", ";", "}" ]
Create a config of the ignored meta modules
[ "Create", "a", "config", "of", "the", "ignored", "meta", "modules" ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/graph/make_graph.js#L176-L185
20,888
stealjs/steal-tools
lib/process_babel_plugins.js
processPlugins
function processPlugins(baseURL, plugins) { var normalized = []; // path.resolve does not work correctly if baseURL starts with "file:" baseURL = baseURL.replace("file:", ""); plugins = plugins || []; plugins.forEach(function(plugin) { var name = getPluginName(plugin); if (isPluginFunction(plugin) || isBuiltinPlugin(name)) { normalized.push(plugin); } else if (!isBuiltinPlugin(name)) { var npmPluginNameOrPath = getNpmPluginNameOrPath(baseURL, name); // load the plugin! var pluginFn = require(npmPluginNameOrPath); if (_.isString(plugin)) { normalized.push(pluginFn); } else if (_.isArray(plugin)) { // [ pluginName, pluginOptions ] normalized.push([pluginFn, plugin[1]]); } } }); return normalized; }
javascript
function processPlugins(baseURL, plugins) { var normalized = []; // path.resolve does not work correctly if baseURL starts with "file:" baseURL = baseURL.replace("file:", ""); plugins = plugins || []; plugins.forEach(function(plugin) { var name = getPluginName(plugin); if (isPluginFunction(plugin) || isBuiltinPlugin(name)) { normalized.push(plugin); } else if (!isBuiltinPlugin(name)) { var npmPluginNameOrPath = getNpmPluginNameOrPath(baseURL, name); // load the plugin! var pluginFn = require(npmPluginNameOrPath); if (_.isString(plugin)) { normalized.push(pluginFn); } else if (_.isArray(plugin)) { // [ pluginName, pluginOptions ] normalized.push([pluginFn, plugin[1]]); } } }); return normalized; }
[ "function", "processPlugins", "(", "baseURL", ",", "plugins", ")", "{", "var", "normalized", "=", "[", "]", ";", "// path.resolve does not work correctly if baseURL starts with \"file:\"", "baseURL", "=", "baseURL", ".", "replace", "(", "\"file:\"", ",", "\"\"", ")", ";", "plugins", "=", "plugins", "||", "[", "]", ";", "plugins", ".", "forEach", "(", "function", "(", "plugin", ")", "{", "var", "name", "=", "getPluginName", "(", "plugin", ")", ";", "if", "(", "isPluginFunction", "(", "plugin", ")", "||", "isBuiltinPlugin", "(", "name", ")", ")", "{", "normalized", ".", "push", "(", "plugin", ")", ";", "}", "else", "if", "(", "!", "isBuiltinPlugin", "(", "name", ")", ")", "{", "var", "npmPluginNameOrPath", "=", "getNpmPluginNameOrPath", "(", "baseURL", ",", "name", ")", ";", "// load the plugin!", "var", "pluginFn", "=", "require", "(", "npmPluginNameOrPath", ")", ";", "if", "(", "_", ".", "isString", "(", "plugin", ")", ")", "{", "normalized", ".", "push", "(", "pluginFn", ")", ";", "}", "else", "if", "(", "_", ".", "isArray", "(", "plugin", ")", ")", "{", "// [ pluginName, pluginOptions ]", "normalized", ".", "push", "(", "[", "pluginFn", ",", "plugin", "[", "1", "]", "]", ")", ";", "}", "}", "}", ")", ";", "return", "normalized", ";", "}" ]
Collect builtin plugin names and non builtin plugin functions @param {string} baseURL The loader baseURL value @param {BabelPlugin[]} plugins An array of babel plugins @return {BabelPlugin[]} An array of babel plugins filtered by the babel environment name and with non-builtins replaced by their respective functions
[ "Collect", "builtin", "plugin", "names", "and", "non", "builtin", "plugin", "functions" ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/process_babel_plugins.js#L54-L84
20,889
stealjs/steal-tools
lib/process_babel_plugins.js
isPluginFunction
function isPluginFunction(plugin) { return _.isFunction(plugin) || _.isFunction(_.head(plugin)); }
javascript
function isPluginFunction(plugin) { return _.isFunction(plugin) || _.isFunction(_.head(plugin)); }
[ "function", "isPluginFunction", "(", "plugin", ")", "{", "return", "_", ".", "isFunction", "(", "plugin", ")", "||", "_", ".", "isFunction", "(", "_", ".", "head", "(", "plugin", ")", ")", ";", "}" ]
Whether the plugin function was provided instead of the plugin name @param {BabelPlugin} plugin @return {boolean} `true` if a plugin function was provided, `false` otherwise
[ "Whether", "the", "plugin", "function", "was", "provided", "instead", "of", "the", "plugin", "name" ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/process_babel_plugins.js#L91-L93
20,890
stealjs/steal-tools
lib/process_babel_plugins.js
getPluginName
function getPluginName(plugin) { if (isPluginFunction(plugin)) return null; return _.isString(plugin) ? plugin : _.head(plugin); }
javascript
function getPluginName(plugin) { if (isPluginFunction(plugin)) return null; return _.isString(plugin) ? plugin : _.head(plugin); }
[ "function", "getPluginName", "(", "plugin", ")", "{", "if", "(", "isPluginFunction", "(", "plugin", ")", ")", "return", "null", ";", "return", "_", ".", "isString", "(", "plugin", ")", "?", "plugin", ":", "_", ".", "head", "(", "plugin", ")", ";", "}" ]
Gets the plugin name @param {BabelPlugin} plugin An item inside of `babelOptions.plugins` @return {?string} The plugin name
[ "Gets", "the", "plugin", "name" ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/process_babel_plugins.js#L114-L118
20,891
stealjs/steal-tools
lib/process_babel_plugins.js
isBuiltinPlugin
function isBuiltinPlugin(name) { var isNpmPluginName = /^(?:babel-plugin-)/; var availablePlugins = babel.availablePlugins; // if the full npm plugin name was set in `babelOptions.plugins`, use the // shorthand to check whether the plugin is included in babel-standalone; // shorthand plugin names are used internally by babel-standalone var shorthand = isNpmPluginName.test(name) ? name.replace("babel-plugin-", "") : name; return !!availablePlugins[shorthand]; }
javascript
function isBuiltinPlugin(name) { var isNpmPluginName = /^(?:babel-plugin-)/; var availablePlugins = babel.availablePlugins; // if the full npm plugin name was set in `babelOptions.plugins`, use the // shorthand to check whether the plugin is included in babel-standalone; // shorthand plugin names are used internally by babel-standalone var shorthand = isNpmPluginName.test(name) ? name.replace("babel-plugin-", "") : name; return !!availablePlugins[shorthand]; }
[ "function", "isBuiltinPlugin", "(", "name", ")", "{", "var", "isNpmPluginName", "=", "/", "^(?:babel-plugin-)", "/", ";", "var", "availablePlugins", "=", "babel", ".", "availablePlugins", ";", "// if the full npm plugin name was set in `babelOptions.plugins`, use the", "// shorthand to check whether the plugin is included in babel-standalone;", "// shorthand plugin names are used internally by babel-standalone", "var", "shorthand", "=", "isNpmPluginName", ".", "test", "(", "name", ")", "?", "name", ".", "replace", "(", "\"babel-plugin-\"", ",", "\"\"", ")", ":", "name", ";", "return", "!", "!", "availablePlugins", "[", "shorthand", "]", ";", "}" ]
Whether the plugin is built in babel-standalone @param {string} name A plugin path or shorthand name. @return {boolean} `true` if plugin is bundled, `false` otherwise Babel plugins can be set using the following variations: 1) the npm plugin name, which by convention starts with `babel-plugin-` (e.g babel-plugin-transform-decorators). 2) A shorthand name, which is the npm name without the `babel-plugin-` prefix 3) A path to where the plugin function is defined babel-standalone registers the plugins bundled with it using the shorthand version.
[ "Whether", "the", "plugin", "is", "built", "in", "babel", "-", "standalone" ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/process_babel_plugins.js#L136-L148
20,892
stealjs/steal-tools
lib/build/continuous.js
rebuild
function rebuild(moduleNames){ moduleName = moduleNames[0] || ""; moduleNames.forEach(function(moduleName){ graphStream.write(moduleName); }); }
javascript
function rebuild(moduleNames){ moduleName = moduleNames[0] || ""; moduleNames.forEach(function(moduleName){ graphStream.write(moduleName); }); }
[ "function", "rebuild", "(", "moduleNames", ")", "{", "moduleName", "=", "moduleNames", "[", "0", "]", "||", "\"\"", ";", "moduleNames", ".", "forEach", "(", "function", "(", "moduleName", ")", "{", "graphStream", ".", "write", "(", "moduleName", ")", ";", "}", ")", ";", "}" ]
A function that is called whenever a module is found by the watch stream. Called with the name of the module and used to rebuild.
[ "A", "function", "that", "is", "called", "whenever", "a", "module", "is", "found", "by", "the", "watch", "stream", ".", "Called", "with", "the", "name", "of", "the", "module", "and", "used", "to", "rebuild", "." ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/build/continuous.js#L23-L28
20,893
stealjs/steal-tools
lib/graph/transpile.js
flagCircularDependencies
function flagCircularDependencies(graph) { var includes = require("lodash/includes"); var nodes = Array.isArray(graph) ? graph : require("lodash/values")(graph); for (var i = 0; i < nodes.length; i += 1) { var curr = nodes[i]; for (var j = i + 1; j < nodes.length; j += 1) { var next = nodes[j]; if ( includes(curr.dependencies, next.load.name) && includes(next.dependencies, curr.load.name) ) { curr.load.circular = true; next.load.circular = true; } } } return graph; }
javascript
function flagCircularDependencies(graph) { var includes = require("lodash/includes"); var nodes = Array.isArray(graph) ? graph : require("lodash/values")(graph); for (var i = 0; i < nodes.length; i += 1) { var curr = nodes[i]; for (var j = i + 1; j < nodes.length; j += 1) { var next = nodes[j]; if ( includes(curr.dependencies, next.load.name) && includes(next.dependencies, curr.load.name) ) { curr.load.circular = true; next.load.circular = true; } } } return graph; }
[ "function", "flagCircularDependencies", "(", "graph", ")", "{", "var", "includes", "=", "require", "(", "\"lodash/includes\"", ")", ";", "var", "nodes", "=", "Array", ".", "isArray", "(", "graph", ")", "?", "graph", ":", "require", "(", "\"lodash/values\"", ")", "(", "graph", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "nodes", ".", "length", ";", "i", "+=", "1", ")", "{", "var", "curr", "=", "nodes", "[", "i", "]", ";", "for", "(", "var", "j", "=", "i", "+", "1", ";", "j", "<", "nodes", ".", "length", ";", "j", "+=", "1", ")", "{", "var", "next", "=", "nodes", "[", "j", "]", ";", "if", "(", "includes", "(", "curr", ".", "dependencies", ",", "next", ".", "load", ".", "name", ")", "&&", "includes", "(", "next", ".", "dependencies", ",", "curr", ".", "load", ".", "name", ")", ")", "{", "curr", ".", "load", ".", "circular", "=", "true", ";", "next", ".", "load", ".", "circular", "=", "true", ";", "}", "}", "}", "return", "graph", ";", "}" ]
Adds a circular flag to the load object of cyclic dependencies MUTATES THE GRAPH @param {Object} graph - The graph to check
[ "Adds", "a", "circular", "flag", "to", "the", "load", "object", "of", "cyclic", "dependencies" ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/graph/transpile.js#L172-L193
20,894
stealjs/steal-tools
lib/node/make_slim_config_node.js
getRelativeBundlePath
function getRelativeBundlePath(target, bundle) { var baseUrl = options.baseUrl.replace("file:", ""); return target !== "web" ? getBundleFileName(bundle) : path.join( path.relative(baseUrl, options.bundlesPath), getBundleFileName(bundle) ); }
javascript
function getRelativeBundlePath(target, bundle) { var baseUrl = options.baseUrl.replace("file:", ""); return target !== "web" ? getBundleFileName(bundle) : path.join( path.relative(baseUrl, options.bundlesPath), getBundleFileName(bundle) ); }
[ "function", "getRelativeBundlePath", "(", "target", ",", "bundle", ")", "{", "var", "baseUrl", "=", "options", ".", "baseUrl", ".", "replace", "(", "\"file:\"", ",", "\"\"", ")", ";", "return", "target", "!==", "\"web\"", "?", "getBundleFileName", "(", "bundle", ")", ":", "path", ".", "join", "(", "path", ".", "relative", "(", "baseUrl", ",", "options", ".", "bundlesPath", ")", ",", "getBundleFileName", "(", "bundle", ")", ")", ";", "}" ]
Returns the bundle's path For nodejs, the name of the bundle is returned since `require` will locate the bundle relative to the main module folder. For the web, a relative path to the loader baseUrl is returned, so the loader can use script tags to load the bundles during runtime. @param {string} target - The name of the build target (node, web) @param {Object} bundle - The bundle object @return {string} the relative path
[ "Returns", "the", "bundle", "s", "path", "For", "nodejs", "the", "name", "of", "the", "bundle", "is", "returned", "since", "require", "will", "locate", "the", "bundle", "relative", "to", "the", "main", "module", "folder", ".", "For", "the", "web", "a", "relative", "path", "to", "the", "loader", "baseUrl", "is", "returned", "so", "the", "loader", "can", "use", "script", "tags", "to", "load", "the", "bundles", "during", "runtime", "." ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/node/make_slim_config_node.js#L52-L61
20,895
stealjs/steal-tools
lib/build/slim.js
function(results) { var value; if (targets.length) { value = {}; results.forEach(function(result, index) { value[targets[index]] = result; }); } else { value = results[0]; } slimDfd.resolve(value); }
javascript
function(results) { var value; if (targets.length) { value = {}; results.forEach(function(result, index) { value[targets[index]] = result; }); } else { value = results[0]; } slimDfd.resolve(value); }
[ "function", "(", "results", ")", "{", "var", "value", ";", "if", "(", "targets", ".", "length", ")", "{", "value", "=", "{", "}", ";", "results", ".", "forEach", "(", "function", "(", "result", ",", "index", ")", "{", "value", "[", "targets", "[", "index", "]", "]", "=", "result", ";", "}", ")", ";", "}", "else", "{", "value", "=", "results", "[", "0", "]", ";", "}", "slimDfd", ".", "resolve", "(", "value", ")", ";", "}" ]
If no `target` is provided resolves `buildResult`; otherwise resolves an object where the key is the target name and its value the `buildResult` object.
[ "If", "no", "target", "is", "provided", "resolves", "buildResult", ";", "otherwise", "resolves", "an", "object", "where", "the", "key", "is", "the", "target", "name", "and", "its", "value", "the", "buildResult", "object", "." ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/build/slim.js#L126-L139
20,896
stealjs/steal-tools
lib/bundle/name.js
getUniqueName
function getUniqueName(dirName, shortened, buildTypeSuffix) { if (!usedBundleNames[dirName + shortened + buildTypeSuffix]) { return dirName + shortened + buildTypeSuffix + ""; }else { return dirName + shortened + "-" + (bundleCounter++) + buildTypeSuffix + ""; } }
javascript
function getUniqueName(dirName, shortened, buildTypeSuffix) { if (!usedBundleNames[dirName + shortened + buildTypeSuffix]) { return dirName + shortened + buildTypeSuffix + ""; }else { return dirName + shortened + "-" + (bundleCounter++) + buildTypeSuffix + ""; } }
[ "function", "getUniqueName", "(", "dirName", ",", "shortened", ",", "buildTypeSuffix", ")", "{", "if", "(", "!", "usedBundleNames", "[", "dirName", "+", "shortened", "+", "buildTypeSuffix", "]", ")", "{", "return", "dirName", "+", "shortened", "+", "buildTypeSuffix", "+", "\"\"", ";", "}", "else", "{", "return", "dirName", "+", "shortened", "+", "\"-\"", "+", "(", "bundleCounter", "++", ")", "+", "buildTypeSuffix", "+", "\"\"", ";", "}", "}" ]
get a unique name, based on bundleCounter @param dirName @param shortened @param buildTypeSuffix @returns {string}
[ "get", "a", "unique", "name", "based", "on", "bundleCounter" ]
48cfb4ff67f421765be53a71b90a70ba857ca583
https://github.com/stealjs/steal-tools/blob/48cfb4ff67f421765be53a71b90a70ba857ca583/lib/bundle/name.js#L101-L107
20,897
panuhorsmalahti/gulp-tslint
index.js
log
function log(message, level) { var prefix = "[" + colors.cyan("gulp-tslint") + "]"; if (level === "error") { fancyLog(prefix, colors.red("error"), message); } else { fancyLog(prefix, message); } }
javascript
function log(message, level) { var prefix = "[" + colors.cyan("gulp-tslint") + "]"; if (level === "error") { fancyLog(prefix, colors.red("error"), message); } else { fancyLog(prefix, message); } }
[ "function", "log", "(", "message", ",", "level", ")", "{", "var", "prefix", "=", "\"[\"", "+", "colors", ".", "cyan", "(", "\"gulp-tslint\"", ")", "+", "\"]\"", ";", "if", "(", "level", "===", "\"error\"", ")", "{", "fancyLog", "(", "prefix", ",", "colors", ".", "red", "(", "\"error\"", ")", ",", "message", ")", ";", "}", "else", "{", "fancyLog", "(", "prefix", ",", "message", ")", ";", "}", "}" ]
Log an event or error using gutil.log. @param {string} message the log message. @param {string} level can be "error". Optional. Leave empty for the default logging type.
[ "Log", "an", "event", "or", "error", "using", "gutil", ".", "log", "." ]
bdea3ff458044129f40df91874efc07866e68b65
https://github.com/panuhorsmalahti/gulp-tslint/blob/bdea3ff458044129f40df91874efc07866e68b65/index.js#L45-L53
20,898
panuhorsmalahti/gulp-tslint
index.js
function (pluginOptions) { // If user options are undefined, set an empty options object if (!pluginOptions) { pluginOptions = {}; } // Save off pluginOptions so we can get it in `report()` tslintPlugin.pluginOptions = pluginOptions; // TSLint default options var options = { fix: pluginOptions.fix || false, formatter: pluginOptions.formatter || "prose", formattersDirectory: pluginOptions.formattersDirectory || null, rulesDirectory: pluginOptions.rulesDirectory || null }; var linter = getTslint(pluginOptions); var tslint = new linter.Linter(options, pluginOptions.program); return map(function (file, cb) { // Skip if (file.isNull()) { return cb(null, file); } // Stream is not supported if (file.isStream()) { return cb(new PluginError("gulp-tslint", "Streaming not supported")); } var configuration = (pluginOptions.configuration === null || pluginOptions.configuration === undefined || isString(pluginOptions.configuration)) // Configuration can be a file path or null, if it's unknown ? linter.Configuration.findConfiguration(pluginOptions.configuration || null, file.path).results : pluginOptions.configuration; tslint.lint(file.path, file.contents.toString("utf8"), configuration); file.tslint = tslint.getResult(); // Clear all results for current file from tslint tslint.failures = []; tslint.fixes = []; // Pass file cb(null, file); }); }
javascript
function (pluginOptions) { // If user options are undefined, set an empty options object if (!pluginOptions) { pluginOptions = {}; } // Save off pluginOptions so we can get it in `report()` tslintPlugin.pluginOptions = pluginOptions; // TSLint default options var options = { fix: pluginOptions.fix || false, formatter: pluginOptions.formatter || "prose", formattersDirectory: pluginOptions.formattersDirectory || null, rulesDirectory: pluginOptions.rulesDirectory || null }; var linter = getTslint(pluginOptions); var tslint = new linter.Linter(options, pluginOptions.program); return map(function (file, cb) { // Skip if (file.isNull()) { return cb(null, file); } // Stream is not supported if (file.isStream()) { return cb(new PluginError("gulp-tslint", "Streaming not supported")); } var configuration = (pluginOptions.configuration === null || pluginOptions.configuration === undefined || isString(pluginOptions.configuration)) // Configuration can be a file path or null, if it's unknown ? linter.Configuration.findConfiguration(pluginOptions.configuration || null, file.path).results : pluginOptions.configuration; tslint.lint(file.path, file.contents.toString("utf8"), configuration); file.tslint = tslint.getResult(); // Clear all results for current file from tslint tslint.failures = []; tslint.fixes = []; // Pass file cb(null, file); }); }
[ "function", "(", "pluginOptions", ")", "{", "// If user options are undefined, set an empty options object", "if", "(", "!", "pluginOptions", ")", "{", "pluginOptions", "=", "{", "}", ";", "}", "// Save off pluginOptions so we can get it in `report()`", "tslintPlugin", ".", "pluginOptions", "=", "pluginOptions", ";", "// TSLint default options", "var", "options", "=", "{", "fix", ":", "pluginOptions", ".", "fix", "||", "false", ",", "formatter", ":", "pluginOptions", ".", "formatter", "||", "\"prose\"", ",", "formattersDirectory", ":", "pluginOptions", ".", "formattersDirectory", "||", "null", ",", "rulesDirectory", ":", "pluginOptions", ".", "rulesDirectory", "||", "null", "}", ";", "var", "linter", "=", "getTslint", "(", "pluginOptions", ")", ";", "var", "tslint", "=", "new", "linter", ".", "Linter", "(", "options", ",", "pluginOptions", ".", "program", ")", ";", "return", "map", "(", "function", "(", "file", ",", "cb", ")", "{", "// Skip", "if", "(", "file", ".", "isNull", "(", ")", ")", "{", "return", "cb", "(", "null", ",", "file", ")", ";", "}", "// Stream is not supported", "if", "(", "file", ".", "isStream", "(", ")", ")", "{", "return", "cb", "(", "new", "PluginError", "(", "\"gulp-tslint\"", ",", "\"Streaming not supported\"", ")", ")", ";", "}", "var", "configuration", "=", "(", "pluginOptions", ".", "configuration", "===", "null", "||", "pluginOptions", ".", "configuration", "===", "undefined", "||", "isString", "(", "pluginOptions", ".", "configuration", ")", ")", "// Configuration can be a file path or null, if it's unknown", "?", "linter", ".", "Configuration", ".", "findConfiguration", "(", "pluginOptions", ".", "configuration", "||", "null", ",", "file", ".", "path", ")", ".", "results", ":", "pluginOptions", ".", "configuration", ";", "tslint", ".", "lint", "(", "file", ".", "path", ",", "file", ".", "contents", ".", "toString", "(", "\"utf8\"", ")", ",", "configuration", ")", ";", "file", ".", "tslint", "=", "tslint", ".", "getResult", "(", ")", ";", "// Clear all results for current file from tslint", "tslint", ".", "failures", "=", "[", "]", ";", "tslint", ".", "fixes", "=", "[", "]", ";", "// Pass file", "cb", "(", "null", ",", "file", ")", ";", "}", ")", ";", "}" ]
Main plugin function @param {PluginOptions} [pluginOptions] contains the options for gulp-tslint. Optional. @returns {any}
[ "Main", "plugin", "function" ]
bdea3ff458044129f40df91874efc07866e68b65
https://github.com/panuhorsmalahti/gulp-tslint/blob/bdea3ff458044129f40df91874efc07866e68b65/index.js#L73-L112
20,899
panuhorsmalahti/gulp-tslint
index.js
function (file) { if (file.tslint) { // Version 5.0.0 of tslint no longer has a failureCount member // It was renamed to errorCount. See tslint issue #2439 var failureCount = file.tslint.errorCount; if (!options.allowWarnings) { failureCount += file.tslint.warningCount; } if (failureCount > 0) { errorFiles.push(file); Array.prototype.push.apply(allFailures, file.tslint.failures); if (options.reportLimit <= 0 || (options.reportLimit && options.reportLimit > totalReported)) { if (file.tslint.output !== undefined) { // If any errors were found, print all warnings and errors console.log(file.tslint.output); } totalReported += failureCount; if (options.reportLimit > 0 && options.reportLimit <= totalReported) { log("More than " + options.reportLimit + " failures reported. Turning off reporter."); } } } else if (options.allowWarnings && file.tslint.warningCount > 0) { // Íf only warnings were emitted, format and print them // Figure out which formatter the user requested in `tslintPlugin()` and construct one var formatterConstructor = TSLint.findFormatter(tslintPlugin.pluginOptions.formatter); var formatter = new formatterConstructor(); // Get just the warnings var warnings = file.tslint.failures.filter(function (failure) { return failure.getRuleSeverity() === "warning"; }); // Print the output of those console.log(formatter.format(warnings)); } } // Pass file this.emit("data", file); }
javascript
function (file) { if (file.tslint) { // Version 5.0.0 of tslint no longer has a failureCount member // It was renamed to errorCount. See tslint issue #2439 var failureCount = file.tslint.errorCount; if (!options.allowWarnings) { failureCount += file.tslint.warningCount; } if (failureCount > 0) { errorFiles.push(file); Array.prototype.push.apply(allFailures, file.tslint.failures); if (options.reportLimit <= 0 || (options.reportLimit && options.reportLimit > totalReported)) { if (file.tslint.output !== undefined) { // If any errors were found, print all warnings and errors console.log(file.tslint.output); } totalReported += failureCount; if (options.reportLimit > 0 && options.reportLimit <= totalReported) { log("More than " + options.reportLimit + " failures reported. Turning off reporter."); } } } else if (options.allowWarnings && file.tslint.warningCount > 0) { // Íf only warnings were emitted, format and print them // Figure out which formatter the user requested in `tslintPlugin()` and construct one var formatterConstructor = TSLint.findFormatter(tslintPlugin.pluginOptions.formatter); var formatter = new formatterConstructor(); // Get just the warnings var warnings = file.tslint.failures.filter(function (failure) { return failure.getRuleSeverity() === "warning"; }); // Print the output of those console.log(formatter.format(warnings)); } } // Pass file this.emit("data", file); }
[ "function", "(", "file", ")", "{", "if", "(", "file", ".", "tslint", ")", "{", "// Version 5.0.0 of tslint no longer has a failureCount member", "// It was renamed to errorCount. See tslint issue #2439", "var", "failureCount", "=", "file", ".", "tslint", ".", "errorCount", ";", "if", "(", "!", "options", ".", "allowWarnings", ")", "{", "failureCount", "+=", "file", ".", "tslint", ".", "warningCount", ";", "}", "if", "(", "failureCount", ">", "0", ")", "{", "errorFiles", ".", "push", "(", "file", ")", ";", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "allFailures", ",", "file", ".", "tslint", ".", "failures", ")", ";", "if", "(", "options", ".", "reportLimit", "<=", "0", "||", "(", "options", ".", "reportLimit", "&&", "options", ".", "reportLimit", ">", "totalReported", ")", ")", "{", "if", "(", "file", ".", "tslint", ".", "output", "!==", "undefined", ")", "{", "// If any errors were found, print all warnings and errors", "console", ".", "log", "(", "file", ".", "tslint", ".", "output", ")", ";", "}", "totalReported", "+=", "failureCount", ";", "if", "(", "options", ".", "reportLimit", ">", "0", "&&", "options", ".", "reportLimit", "<=", "totalReported", ")", "{", "log", "(", "\"More than \"", "+", "options", ".", "reportLimit", "+", "\" failures reported. Turning off reporter.\"", ")", ";", "}", "}", "}", "else", "if", "(", "options", ".", "allowWarnings", "&&", "file", ".", "tslint", ".", "warningCount", ">", "0", ")", "{", "// Íf only warnings were emitted, format and print them", "// Figure out which formatter the user requested in `tslintPlugin()` and construct one", "var", "formatterConstructor", "=", "TSLint", ".", "findFormatter", "(", "tslintPlugin", ".", "pluginOptions", ".", "formatter", ")", ";", "var", "formatter", "=", "new", "formatterConstructor", "(", ")", ";", "// Get just the warnings", "var", "warnings", "=", "file", ".", "tslint", ".", "failures", ".", "filter", "(", "function", "(", "failure", ")", "{", "return", "failure", ".", "getRuleSeverity", "(", ")", "===", "\"warning\"", ";", "}", ")", ";", "// Print the output of those", "console", ".", "log", "(", "formatter", ".", "format", "(", "warnings", ")", ")", ";", "}", "}", "// Pass file", "this", ".", "emit", "(", "\"data\"", ",", "file", ")", ";", "}" ]
Log formatted output for each file individually
[ "Log", "formatted", "output", "for", "each", "file", "individually" ]
bdea3ff458044129f40df91874efc07866e68b65
https://github.com/panuhorsmalahti/gulp-tslint/blob/bdea3ff458044129f40df91874efc07866e68b65/index.js#L138-L175