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
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
angelnu/castv2-player
|
lib/persistentPlayer.js
|
function (err, pStatus) {
if (err) {
log.error(that._name + " - Could not get player status- " + err);
} else {
that._playerStatus(pStatus);
}
}
|
javascript
|
function (err, pStatus) {
if (err) {
log.error(that._name + " - Could not get player status- " + err);
} else {
that._playerStatus(pStatus);
}
}
|
[
"function",
"(",
"err",
",",
"pStatus",
")",
"{",
"if",
"(",
"err",
")",
"{",
"log",
".",
"error",
"(",
"that",
".",
"_name",
"+",
"\" - Could not get player status- \"",
"+",
"err",
")",
";",
"}",
"else",
"{",
"that",
".",
"_playerStatus",
"(",
"pStatus",
")",
";",
"}",
"}"
] |
Handle player status updates
|
[
"Handle",
"player",
"status",
"updates"
] |
b7797ad3fb97d4e8b33bddaa4c1659c7e219c580
|
https://github.com/angelnu/castv2-player/blob/b7797ad3fb97d4e8b33bddaa4c1659c7e219c580/lib/persistentPlayer.js#L652-L658
|
train
|
|
laktek/punch
|
lib/content_handler.js
|
function(err, content_name, parsed_content, modified_date) {
if (!err) {
parsed_contents[content_name] = parsed_content;
if (modified_date > last_modified) {
last_modified = modified_date;
}
}
if (content_files.length) {
return parseFile(content_files.pop(), parse_file_callback);
} else {
return callback(null, parsed_contents, last_modified);
}
}
|
javascript
|
function(err, content_name, parsed_content, modified_date) {
if (!err) {
parsed_contents[content_name] = parsed_content;
if (modified_date > last_modified) {
last_modified = modified_date;
}
}
if (content_files.length) {
return parseFile(content_files.pop(), parse_file_callback);
} else {
return callback(null, parsed_contents, last_modified);
}
}
|
[
"function",
"(",
"err",
",",
"content_name",
",",
"parsed_content",
",",
"modified_date",
")",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"parsed_contents",
"[",
"content_name",
"]",
"=",
"parsed_content",
";",
"if",
"(",
"modified_date",
">",
"last_modified",
")",
"{",
"last_modified",
"=",
"modified_date",
";",
"}",
"}",
"if",
"(",
"content_files",
".",
"length",
")",
"{",
"return",
"parseFile",
"(",
"content_files",
".",
"pop",
"(",
")",
",",
"parse_file_callback",
")",
";",
"}",
"else",
"{",
"return",
"callback",
"(",
"null",
",",
"parsed_contents",
",",
"last_modified",
")",
";",
"}",
"}"
] |
parse each file
|
[
"parse",
"each",
"file"
] |
180278c2b2251b007652fbbdb0914d3d3fa13580
|
https://github.com/laktek/punch/blob/180278c2b2251b007652fbbdb0914d3d3fa13580/lib/content_handler.js#L125-L139
|
train
|
|
laktek/punch
|
lib/content_handler.js
|
function(callback) {
var self = this;
var sections = [Path.join("/")];
var paths_to_traverse = [];
var should_exclude = function(entry) {
return entry[0] === "." || entry[0] === "_" || entry === "shared";
};
var traverse_path = function() {
var current_path = paths_to_traverse.shift() || "";
Fs.readdir(Path.join(self.contentDir, current_path), function(err, entries) {
if (err) {
throw err;
}
var run_callbacks = function() {
if (entries.length) {
return next_entry();
} else if (paths_to_traverse.length) {
return traverse_path();
} else {
return callback(sections);
}
};
var next_entry = function() {
var current_entry = entries.shift();
if (should_exclude(current_entry)) {
return run_callbacks();
}
var current_entry_path = Path.join(current_path, current_entry);
Fs.stat(Path.join(self.contentDir, current_entry_path), function(err, stat) {
if (err) {
return run_callbacks();
}
if (stat.isDirectory()) {
sections.push(Path.join("/",current_entry_path));
paths_to_traverse.push(current_entry_path);
}
return run_callbacks();
});
};
return run_callbacks();
});
};
return traverse_path();
}
|
javascript
|
function(callback) {
var self = this;
var sections = [Path.join("/")];
var paths_to_traverse = [];
var should_exclude = function(entry) {
return entry[0] === "." || entry[0] === "_" || entry === "shared";
};
var traverse_path = function() {
var current_path = paths_to_traverse.shift() || "";
Fs.readdir(Path.join(self.contentDir, current_path), function(err, entries) {
if (err) {
throw err;
}
var run_callbacks = function() {
if (entries.length) {
return next_entry();
} else if (paths_to_traverse.length) {
return traverse_path();
} else {
return callback(sections);
}
};
var next_entry = function() {
var current_entry = entries.shift();
if (should_exclude(current_entry)) {
return run_callbacks();
}
var current_entry_path = Path.join(current_path, current_entry);
Fs.stat(Path.join(self.contentDir, current_entry_path), function(err, stat) {
if (err) {
return run_callbacks();
}
if (stat.isDirectory()) {
sections.push(Path.join("/",current_entry_path));
paths_to_traverse.push(current_entry_path);
}
return run_callbacks();
});
};
return run_callbacks();
});
};
return traverse_path();
}
|
[
"function",
"(",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"sections",
"=",
"[",
"Path",
".",
"join",
"(",
"\"/\"",
")",
"]",
";",
"var",
"paths_to_traverse",
"=",
"[",
"]",
";",
"var",
"should_exclude",
"=",
"function",
"(",
"entry",
")",
"{",
"return",
"entry",
"[",
"0",
"]",
"===",
"\".\"",
"||",
"entry",
"[",
"0",
"]",
"===",
"\"_\"",
"||",
"entry",
"===",
"\"shared\"",
";",
"}",
";",
"var",
"traverse_path",
"=",
"function",
"(",
")",
"{",
"var",
"current_path",
"=",
"paths_to_traverse",
".",
"shift",
"(",
")",
"||",
"\"\"",
";",
"Fs",
".",
"readdir",
"(",
"Path",
".",
"join",
"(",
"self",
".",
"contentDir",
",",
"current_path",
")",
",",
"function",
"(",
"err",
",",
"entries",
")",
"{",
"if",
"(",
"err",
")",
"{",
"throw",
"err",
";",
"}",
"var",
"run_callbacks",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"entries",
".",
"length",
")",
"{",
"return",
"next_entry",
"(",
")",
";",
"}",
"else",
"if",
"(",
"paths_to_traverse",
".",
"length",
")",
"{",
"return",
"traverse_path",
"(",
")",
";",
"}",
"else",
"{",
"return",
"callback",
"(",
"sections",
")",
";",
"}",
"}",
";",
"var",
"next_entry",
"=",
"function",
"(",
")",
"{",
"var",
"current_entry",
"=",
"entries",
".",
"shift",
"(",
")",
";",
"if",
"(",
"should_exclude",
"(",
"current_entry",
")",
")",
"{",
"return",
"run_callbacks",
"(",
")",
";",
"}",
"var",
"current_entry_path",
"=",
"Path",
".",
"join",
"(",
"current_path",
",",
"current_entry",
")",
";",
"Fs",
".",
"stat",
"(",
"Path",
".",
"join",
"(",
"self",
".",
"contentDir",
",",
"current_entry_path",
")",
",",
"function",
"(",
"err",
",",
"stat",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"run_callbacks",
"(",
")",
";",
"}",
"if",
"(",
"stat",
".",
"isDirectory",
"(",
")",
")",
"{",
"sections",
".",
"push",
"(",
"Path",
".",
"join",
"(",
"\"/\"",
",",
"current_entry_path",
")",
")",
";",
"paths_to_traverse",
".",
"push",
"(",
"current_entry_path",
")",
";",
"}",
"return",
"run_callbacks",
"(",
")",
";",
"}",
")",
";",
"}",
";",
"return",
"run_callbacks",
"(",
")",
";",
"}",
")",
";",
"}",
";",
"return",
"traverse_path",
"(",
")",
";",
"}"
] |
returns all available sections rooting from the given path
|
[
"returns",
"all",
"available",
"sections",
"rooting",
"from",
"the",
"given",
"path"
] |
180278c2b2251b007652fbbdb0914d3d3fa13580
|
https://github.com/laktek/punch/blob/180278c2b2251b007652fbbdb0914d3d3fa13580/lib/content_handler.js#L209-L260
|
train
|
|
laktek/punch
|
lib/content_handler.js
|
function(basePath, output_extension, options, callback) {
var self = this;
var collected_contents = {};
var content_options = {};
var last_modified = null;
// treat files with special output extensions
if (output_extension !== ".html") {
basePath = basePath + output_extension;
}
self.getContent(basePath, function(err, contents, modified_date) {
if (!err) {
collected_contents = _.extend(collected_contents, contents);
last_modified = modified_date;
var run_callback = function() {
return callback(null, collected_contents, content_options, last_modified);
};
//fetch shared content
self.getSharedContent(function(err, shared_content, shared_modified_date) {
if (!err) {
collected_contents = _.extend(shared_content, collected_contents);
if (shared_modified_date > last_modified) {
last_modified = shared_modified_date;
}
}
return run_callback();
});
} else {
return callback("[Error: Content for " + basePath + " not found]", null, null, {});
}
});
}
|
javascript
|
function(basePath, output_extension, options, callback) {
var self = this;
var collected_contents = {};
var content_options = {};
var last_modified = null;
// treat files with special output extensions
if (output_extension !== ".html") {
basePath = basePath + output_extension;
}
self.getContent(basePath, function(err, contents, modified_date) {
if (!err) {
collected_contents = _.extend(collected_contents, contents);
last_modified = modified_date;
var run_callback = function() {
return callback(null, collected_contents, content_options, last_modified);
};
//fetch shared content
self.getSharedContent(function(err, shared_content, shared_modified_date) {
if (!err) {
collected_contents = _.extend(shared_content, collected_contents);
if (shared_modified_date > last_modified) {
last_modified = shared_modified_date;
}
}
return run_callback();
});
} else {
return callback("[Error: Content for " + basePath + " not found]", null, null, {});
}
});
}
|
[
"function",
"(",
"basePath",
",",
"output_extension",
",",
"options",
",",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"collected_contents",
"=",
"{",
"}",
";",
"var",
"content_options",
"=",
"{",
"}",
";",
"var",
"last_modified",
"=",
"null",
";",
"if",
"(",
"output_extension",
"!==",
"\".html\"",
")",
"{",
"basePath",
"=",
"basePath",
"+",
"output_extension",
";",
"}",
"self",
".",
"getContent",
"(",
"basePath",
",",
"function",
"(",
"err",
",",
"contents",
",",
"modified_date",
")",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"collected_contents",
"=",
"_",
".",
"extend",
"(",
"collected_contents",
",",
"contents",
")",
";",
"last_modified",
"=",
"modified_date",
";",
"var",
"run_callback",
"=",
"function",
"(",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"collected_contents",
",",
"content_options",
",",
"last_modified",
")",
";",
"}",
";",
"self",
".",
"getSharedContent",
"(",
"function",
"(",
"err",
",",
"shared_content",
",",
"shared_modified_date",
")",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"collected_contents",
"=",
"_",
".",
"extend",
"(",
"shared_content",
",",
"collected_contents",
")",
";",
"if",
"(",
"shared_modified_date",
">",
"last_modified",
")",
"{",
"last_modified",
"=",
"shared_modified_date",
";",
"}",
"}",
"return",
"run_callback",
"(",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"return",
"callback",
"(",
"\"[Error: Content for \"",
"+",
"basePath",
"+",
"\" not found]\"",
",",
"null",
",",
"null",
",",
"{",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] |
provide the best matching content for the given arguments
|
[
"provide",
"the",
"best",
"matching",
"content",
"for",
"the",
"given",
"arguments"
] |
180278c2b2251b007652fbbdb0914d3d3fa13580
|
https://github.com/laktek/punch/blob/180278c2b2251b007652fbbdb0914d3d3fa13580/lib/content_handler.js#L304-L339
|
train
|
|
TryGhost/Ignition
|
lib/server.js
|
start
|
function start(app) {
/**
* Create HTTP server.
*/
const config = require('./config')();
port = normalizePort(config.get('port'));
server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
app.set('port', port);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
return server;
}
|
javascript
|
function start(app) {
/**
* Create HTTP server.
*/
const config = require('./config')();
port = normalizePort(config.get('port'));
server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
app.set('port', port);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
return server;
}
|
[
"function",
"start",
"(",
"app",
")",
"{",
"const",
"config",
"=",
"require",
"(",
"'./config'",
")",
"(",
")",
";",
"port",
"=",
"normalizePort",
"(",
"config",
".",
"get",
"(",
"'port'",
")",
")",
";",
"server",
"=",
"http",
".",
"createServer",
"(",
"app",
")",
";",
"app",
".",
"set",
"(",
"'port'",
",",
"port",
")",
";",
"server",
".",
"listen",
"(",
"port",
")",
";",
"server",
".",
"on",
"(",
"'error'",
",",
"onError",
")",
";",
"server",
".",
"on",
"(",
"'listening'",
",",
"onListening",
")",
";",
"return",
"server",
";",
"}"
] |
Get port from nconf
|
[
"Get",
"port",
"from",
"nconf"
] |
db5119b4b54eff9ab535b9d852b80a786aa31133
|
https://github.com/TryGhost/Ignition/blob/db5119b4b54eff9ab535b9d852b80a786aa31133/lib/server.js#L11-L30
|
train
|
CartoDB/camshaft
|
lib/limits/estimates.js
|
estimatedNumberOfRows
|
function estimatedNumberOfRows(node, context, callback) {
var sql = estimatedCountTemplate({
sourceQuery: node.sql()
});
context.runSQL(sql, function(err, resultSet){
var estimated_rows = null;
if (!err) {
if (resultSet.rows) {
estimated_rows = resultSet.rows[0]['QUERY PLAN'][0].Plan['Plan Rows'];
} else {
// If we get no results (e.g. working with a fake db)
// we make a most permissive estimate
estimated_rows = 0;
}
}
return callback(err, estimated_rows);
});
}
|
javascript
|
function estimatedNumberOfRows(node, context, callback) {
var sql = estimatedCountTemplate({
sourceQuery: node.sql()
});
context.runSQL(sql, function(err, resultSet){
var estimated_rows = null;
if (!err) {
if (resultSet.rows) {
estimated_rows = resultSet.rows[0]['QUERY PLAN'][0].Plan['Plan Rows'];
} else {
// If we get no results (e.g. working with a fake db)
// we make a most permissive estimate
estimated_rows = 0;
}
}
return callback(err, estimated_rows);
});
}
|
[
"function",
"estimatedNumberOfRows",
"(",
"node",
",",
"context",
",",
"callback",
")",
"{",
"var",
"sql",
"=",
"estimatedCountTemplate",
"(",
"{",
"sourceQuery",
":",
"node",
".",
"sql",
"(",
")",
"}",
")",
";",
"context",
".",
"runSQL",
"(",
"sql",
",",
"function",
"(",
"err",
",",
"resultSet",
")",
"{",
"var",
"estimated_rows",
"=",
"null",
";",
"if",
"(",
"!",
"err",
")",
"{",
"if",
"(",
"resultSet",
".",
"rows",
")",
"{",
"estimated_rows",
"=",
"resultSet",
".",
"rows",
"[",
"0",
"]",
"[",
"'QUERY PLAN'",
"]",
"[",
"0",
"]",
".",
"Plan",
"[",
"'Plan Rows'",
"]",
";",
"}",
"else",
"{",
"estimated_rows",
"=",
"0",
";",
"}",
"}",
"return",
"callback",
"(",
"err",
",",
"estimated_rows",
")",
";",
"}",
")",
";",
"}"
] |
Estimated number of rows in the result of a node. A LimitsContext object must be provided. This is an asynchronous method; an error object and the number of estimated rows will be passed to the callback provided. This uses PostgreSQL query planner and statistics; it could fail, returning a null count if no stats are available or if a timeout occurs.
|
[
"Estimated",
"number",
"of",
"rows",
"in",
"the",
"result",
"of",
"a",
"node",
".",
"A",
"LimitsContext",
"object",
"must",
"be",
"provided",
".",
"This",
"is",
"an",
"asynchronous",
"method",
";",
"an",
"error",
"object",
"and",
"the",
"number",
"of",
"estimated",
"rows",
"will",
"be",
"passed",
"to",
"the",
"callback",
"provided",
".",
"This",
"uses",
"PostgreSQL",
"query",
"planner",
"and",
"statistics",
";",
"it",
"could",
"fail",
"returning",
"a",
"null",
"count",
"if",
"no",
"stats",
"are",
"available",
"or",
"if",
"a",
"timeout",
"occurs",
"."
] |
3cae41a41d4a3c037389c6f02630919197476f37
|
https://github.com/CartoDB/camshaft/blob/3cae41a41d4a3c037389c6f02630919197476f37/lib/limits/estimates.js#L27-L44
|
train
|
CartoDB/camshaft
|
lib/limits/estimates.js
|
numberOfRows
|
function numberOfRows(node, context, callback) {
var sql = exactCountTemplate({
sourceQuery: node.sql()
});
context.runSQL(sql, function(err, resultSet){
var counted_rows = null;
if (!err) {
counted_rows = resultSet.rows[0].result_rows;
}
return callback(err, counted_rows);
});
}
|
javascript
|
function numberOfRows(node, context, callback) {
var sql = exactCountTemplate({
sourceQuery: node.sql()
});
context.runSQL(sql, function(err, resultSet){
var counted_rows = null;
if (!err) {
counted_rows = resultSet.rows[0].result_rows;
}
return callback(err, counted_rows);
});
}
|
[
"function",
"numberOfRows",
"(",
"node",
",",
"context",
",",
"callback",
")",
"{",
"var",
"sql",
"=",
"exactCountTemplate",
"(",
"{",
"sourceQuery",
":",
"node",
".",
"sql",
"(",
")",
"}",
")",
";",
"context",
".",
"runSQL",
"(",
"sql",
",",
"function",
"(",
"err",
",",
"resultSet",
")",
"{",
"var",
"counted_rows",
"=",
"null",
";",
"if",
"(",
"!",
"err",
")",
"{",
"counted_rows",
"=",
"resultSet",
".",
"rows",
"[",
"0",
"]",
".",
"result_rows",
";",
"}",
"return",
"callback",
"(",
"err",
",",
"counted_rows",
")",
";",
"}",
")",
";",
"}"
] |
Number of rows in the result of the node. A LimitsContext object must be provided. This is an asynchronous method; an error object and the number of estimated rows will be passed to the callback provided. This can be slow for large tables or complex queries.
|
[
"Number",
"of",
"rows",
"in",
"the",
"result",
"of",
"the",
"node",
".",
"A",
"LimitsContext",
"object",
"must",
"be",
"provided",
".",
"This",
"is",
"an",
"asynchronous",
"method",
";",
"an",
"error",
"object",
"and",
"the",
"number",
"of",
"estimated",
"rows",
"will",
"be",
"passed",
"to",
"the",
"callback",
"provided",
".",
"This",
"can",
"be",
"slow",
"for",
"large",
"tables",
"or",
"complex",
"queries",
"."
] |
3cae41a41d4a3c037389c6f02630919197476f37
|
https://github.com/CartoDB/camshaft/blob/3cae41a41d4a3c037389c6f02630919197476f37/lib/limits/estimates.js#L51-L62
|
train
|
CartoDB/camshaft
|
lib/limits/estimates.js
|
numberOfDistinctValues
|
function numberOfDistinctValues(node, context, columnName, callback) {
var sql = countDistinctValuesTemplate({
source: node.sql(),
column: columnName
});
context.runSQL(sql, function(err, resultSet){
var number = null;
if (!err) {
number = resultSet.rows[0].count_distict_values;
}
return callback(err, number);
});
}
|
javascript
|
function numberOfDistinctValues(node, context, columnName, callback) {
var sql = countDistinctValuesTemplate({
source: node.sql(),
column: columnName
});
context.runSQL(sql, function(err, resultSet){
var number = null;
if (!err) {
number = resultSet.rows[0].count_distict_values;
}
return callback(err, number);
});
}
|
[
"function",
"numberOfDistinctValues",
"(",
"node",
",",
"context",
",",
"columnName",
",",
"callback",
")",
"{",
"var",
"sql",
"=",
"countDistinctValuesTemplate",
"(",
"{",
"source",
":",
"node",
".",
"sql",
"(",
")",
",",
"column",
":",
"columnName",
"}",
")",
";",
"context",
".",
"runSQL",
"(",
"sql",
",",
"function",
"(",
"err",
",",
"resultSet",
")",
"{",
"var",
"number",
"=",
"null",
";",
"if",
"(",
"!",
"err",
")",
"{",
"number",
"=",
"resultSet",
".",
"rows",
"[",
"0",
"]",
".",
"count_distict_values",
";",
"}",
"return",
"callback",
"(",
"err",
",",
"number",
")",
";",
"}",
")",
";",
"}"
] |
Estimate number of distict values of a column in a node's query.
|
[
"Estimate",
"number",
"of",
"distict",
"values",
"of",
"a",
"column",
"in",
"a",
"node",
"s",
"query",
"."
] |
3cae41a41d4a3c037389c6f02630919197476f37
|
https://github.com/CartoDB/camshaft/blob/3cae41a41d4a3c037389c6f02630919197476f37/lib/limits/estimates.js#L65-L77
|
train
|
pubkey/custom-idle-queue
|
src/index.js
|
function(parallels = 1) {
this._parallels = parallels || 1;
/**
* _queueCounter
* each lock() increased this number
* each unlock() decreases this number
* If _qC==0, the state is in idle
* @type {Number}
*/
this._qC = 0;
/**
* _idleCalls
* contains all promises that where added via requestIdlePromise()
* and not have been resolved
* @type {Set<Promise>} _iC with oldest promise first
*/
this._iC = new Set();
/**
* _lastHandleNumber
* @type {Number}
*/
this._lHN = 0;
/**
* _handlePromiseMap
* Contains the handleNumber on the left
* And the assigned promise on the right.
* This is stored so you can use cancelIdleCallback(handleNumber)
* to stop executing the callback.
* @type {Map<Number><Promise>}
*/
this._hPM = new Map();
this._pHM = new Map(); // _promiseHandleMap
}
|
javascript
|
function(parallels = 1) {
this._parallels = parallels || 1;
/**
* _queueCounter
* each lock() increased this number
* each unlock() decreases this number
* If _qC==0, the state is in idle
* @type {Number}
*/
this._qC = 0;
/**
* _idleCalls
* contains all promises that where added via requestIdlePromise()
* and not have been resolved
* @type {Set<Promise>} _iC with oldest promise first
*/
this._iC = new Set();
/**
* _lastHandleNumber
* @type {Number}
*/
this._lHN = 0;
/**
* _handlePromiseMap
* Contains the handleNumber on the left
* And the assigned promise on the right.
* This is stored so you can use cancelIdleCallback(handleNumber)
* to stop executing the callback.
* @type {Map<Number><Promise>}
*/
this._hPM = new Map();
this._pHM = new Map(); // _promiseHandleMap
}
|
[
"function",
"(",
"parallels",
"=",
"1",
")",
"{",
"this",
".",
"_parallels",
"=",
"parallels",
"||",
"1",
";",
"this",
".",
"_qC",
"=",
"0",
";",
"this",
".",
"_iC",
"=",
"new",
"Set",
"(",
")",
";",
"this",
".",
"_lHN",
"=",
"0",
";",
"this",
".",
"_hPM",
"=",
"new",
"Map",
"(",
")",
";",
"this",
".",
"_pHM",
"=",
"new",
"Map",
"(",
")",
";",
"}"
] |
Creates a new Idle-Queue
@constructor
@param {number} [parallels=1] amount of parrallel runs of the limited-ressource
|
[
"Creates",
"a",
"new",
"Idle",
"-",
"Queue"
] |
de44f52271c6cdcdce34b8bb0ba84cd9702978bb
|
https://github.com/pubkey/custom-idle-queue/blob/de44f52271c6cdcdce34b8bb0ba84cd9702978bb/src/index.js#L6-L42
|
train
|
|
pubkey/custom-idle-queue
|
src/index.js
|
_resolveOneIdleCall
|
function _resolveOneIdleCall(idleQueue) {
if (idleQueue._iC.size === 0) return;
const iterator = idleQueue._iC.values();
const oldestPromise = iterator.next().value;
oldestPromise._manRes();
// try to call the next tick
setTimeout(() => _tryIdleCall(idleQueue), 0);
}
|
javascript
|
function _resolveOneIdleCall(idleQueue) {
if (idleQueue._iC.size === 0) return;
const iterator = idleQueue._iC.values();
const oldestPromise = iterator.next().value;
oldestPromise._manRes();
// try to call the next tick
setTimeout(() => _tryIdleCall(idleQueue), 0);
}
|
[
"function",
"_resolveOneIdleCall",
"(",
"idleQueue",
")",
"{",
"if",
"(",
"idleQueue",
".",
"_iC",
".",
"size",
"===",
"0",
")",
"return",
";",
"const",
"iterator",
"=",
"idleQueue",
".",
"_iC",
".",
"values",
"(",
")",
";",
"const",
"oldestPromise",
"=",
"iterator",
".",
"next",
"(",
")",
".",
"value",
";",
"oldestPromise",
".",
"_manRes",
"(",
")",
";",
"setTimeout",
"(",
"(",
")",
"=>",
"_tryIdleCall",
"(",
"idleQueue",
")",
",",
"0",
")",
";",
"}"
] |
processes the oldest call of the idleCalls-queue
@return {Promise<void>}
|
[
"processes",
"the",
"oldest",
"call",
"of",
"the",
"idleCalls",
"-",
"queue"
] |
de44f52271c6cdcdce34b8bb0ba84cd9702978bb
|
https://github.com/pubkey/custom-idle-queue/blob/de44f52271c6cdcdce34b8bb0ba84cd9702978bb/src/index.js#L190-L200
|
train
|
pubkey/custom-idle-queue
|
src/index.js
|
_removeIdlePromise
|
function _removeIdlePromise(idleQueue, promise) {
if (!promise) return;
// remove timeout if exists
if (promise._timeoutObj)
clearTimeout(promise._timeoutObj);
// remove handle-nr if exists
if (idleQueue._pHM.has(promise)) {
const handle = idleQueue._pHM.get(promise);
idleQueue._hPM.delete(handle);
idleQueue._pHM.delete(promise);
}
// remove from queue
idleQueue._iC.delete(promise);
}
|
javascript
|
function _removeIdlePromise(idleQueue, promise) {
if (!promise) return;
// remove timeout if exists
if (promise._timeoutObj)
clearTimeout(promise._timeoutObj);
// remove handle-nr if exists
if (idleQueue._pHM.has(promise)) {
const handle = idleQueue._pHM.get(promise);
idleQueue._hPM.delete(handle);
idleQueue._pHM.delete(promise);
}
// remove from queue
idleQueue._iC.delete(promise);
}
|
[
"function",
"_removeIdlePromise",
"(",
"idleQueue",
",",
"promise",
")",
"{",
"if",
"(",
"!",
"promise",
")",
"return",
";",
"if",
"(",
"promise",
".",
"_timeoutObj",
")",
"clearTimeout",
"(",
"promise",
".",
"_timeoutObj",
")",
";",
"if",
"(",
"idleQueue",
".",
"_pHM",
".",
"has",
"(",
"promise",
")",
")",
"{",
"const",
"handle",
"=",
"idleQueue",
".",
"_pHM",
".",
"get",
"(",
"promise",
")",
";",
"idleQueue",
".",
"_hPM",
".",
"delete",
"(",
"handle",
")",
";",
"idleQueue",
".",
"_pHM",
".",
"delete",
"(",
"promise",
")",
";",
"}",
"idleQueue",
".",
"_iC",
".",
"delete",
"(",
"promise",
")",
";",
"}"
] |
removes the promise from the queue and maps and also its corresponding handle-number
@param {Promise} promise from requestIdlePromise()
@return {void}
|
[
"removes",
"the",
"promise",
"from",
"the",
"queue",
"and",
"maps",
"and",
"also",
"its",
"corresponding",
"handle",
"-",
"number"
] |
de44f52271c6cdcdce34b8bb0ba84cd9702978bb
|
https://github.com/pubkey/custom-idle-queue/blob/de44f52271c6cdcdce34b8bb0ba84cd9702978bb/src/index.js#L208-L224
|
train
|
pubkey/custom-idle-queue
|
src/index.js
|
_tryIdleCall
|
function _tryIdleCall(idleQueue) {
// ensure this does not run in parallel
if (idleQueue._tryIR || idleQueue._iC.size === 0)
return;
idleQueue._tryIR = true;
// w8 one tick
setTimeout(() => {
// check if queue empty
if (!idleQueue.isIdle()) {
idleQueue._tryIR = false;
return;
}
/**
* wait 1 tick here
* because many functions do IO->CPU->IO
* which means the queue is empty for a short time
* but the ressource is not idle
*/
setTimeout(() => {
// check if queue still empty
if (!idleQueue.isIdle()) {
idleQueue._tryIR = false;
return;
}
// ressource is idle
_resolveOneIdleCall(idleQueue);
idleQueue._tryIR = false;
}, 0);
}, 0);
}
|
javascript
|
function _tryIdleCall(idleQueue) {
// ensure this does not run in parallel
if (idleQueue._tryIR || idleQueue._iC.size === 0)
return;
idleQueue._tryIR = true;
// w8 one tick
setTimeout(() => {
// check if queue empty
if (!idleQueue.isIdle()) {
idleQueue._tryIR = false;
return;
}
/**
* wait 1 tick here
* because many functions do IO->CPU->IO
* which means the queue is empty for a short time
* but the ressource is not idle
*/
setTimeout(() => {
// check if queue still empty
if (!idleQueue.isIdle()) {
idleQueue._tryIR = false;
return;
}
// ressource is idle
_resolveOneIdleCall(idleQueue);
idleQueue._tryIR = false;
}, 0);
}, 0);
}
|
[
"function",
"_tryIdleCall",
"(",
"idleQueue",
")",
"{",
"if",
"(",
"idleQueue",
".",
"_tryIR",
"||",
"idleQueue",
".",
"_iC",
".",
"size",
"===",
"0",
")",
"return",
";",
"idleQueue",
".",
"_tryIR",
"=",
"true",
";",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"if",
"(",
"!",
"idleQueue",
".",
"isIdle",
"(",
")",
")",
"{",
"idleQueue",
".",
"_tryIR",
"=",
"false",
";",
"return",
";",
"}",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"if",
"(",
"!",
"idleQueue",
".",
"isIdle",
"(",
")",
")",
"{",
"idleQueue",
".",
"_tryIR",
"=",
"false",
";",
"return",
";",
"}",
"_resolveOneIdleCall",
"(",
"idleQueue",
")",
";",
"idleQueue",
".",
"_tryIR",
"=",
"false",
";",
"}",
",",
"0",
")",
";",
"}",
",",
"0",
")",
";",
"}"
] |
resolves the last entry of this._iC
but only if the queue is empty
@return {Promise}
|
[
"resolves",
"the",
"last",
"entry",
"of",
"this",
".",
"_iC",
"but",
"only",
"if",
"the",
"queue",
"is",
"empty"
] |
de44f52271c6cdcdce34b8bb0ba84cd9702978bb
|
https://github.com/pubkey/custom-idle-queue/blob/de44f52271c6cdcdce34b8bb0ba84cd9702978bb/src/index.js#L231-L263
|
train
|
marionettejs/backbone.syphon
|
src/backbone.syphon.js
|
function(view, config) {
var formInputs = getForm(view);
formInputs = _.reject(formInputs, function(el) {
var reject;
var myType = getElementType(el);
var extractor = config.keyExtractors.get(myType);
var identifier = extractor($(el));
var foundInIgnored = _.find(config.ignoredTypes, function(ignoredTypeOrSelector) {
return (ignoredTypeOrSelector === myType) || $(el).is(ignoredTypeOrSelector);
});
var foundInInclude = _.includes(config.include, identifier);
var foundInExclude = _.includes(config.exclude, identifier);
if (foundInInclude) {
reject = false;
} else {
if (config.include) {
reject = true;
} else {
reject = (foundInExclude || foundInIgnored);
}
}
return reject;
});
return formInputs;
}
|
javascript
|
function(view, config) {
var formInputs = getForm(view);
formInputs = _.reject(formInputs, function(el) {
var reject;
var myType = getElementType(el);
var extractor = config.keyExtractors.get(myType);
var identifier = extractor($(el));
var foundInIgnored = _.find(config.ignoredTypes, function(ignoredTypeOrSelector) {
return (ignoredTypeOrSelector === myType) || $(el).is(ignoredTypeOrSelector);
});
var foundInInclude = _.includes(config.include, identifier);
var foundInExclude = _.includes(config.exclude, identifier);
if (foundInInclude) {
reject = false;
} else {
if (config.include) {
reject = true;
} else {
reject = (foundInExclude || foundInIgnored);
}
}
return reject;
});
return formInputs;
}
|
[
"function",
"(",
"view",
",",
"config",
")",
"{",
"var",
"formInputs",
"=",
"getForm",
"(",
"view",
")",
";",
"formInputs",
"=",
"_",
".",
"reject",
"(",
"formInputs",
",",
"function",
"(",
"el",
")",
"{",
"var",
"reject",
";",
"var",
"myType",
"=",
"getElementType",
"(",
"el",
")",
";",
"var",
"extractor",
"=",
"config",
".",
"keyExtractors",
".",
"get",
"(",
"myType",
")",
";",
"var",
"identifier",
"=",
"extractor",
"(",
"$",
"(",
"el",
")",
")",
";",
"var",
"foundInIgnored",
"=",
"_",
".",
"find",
"(",
"config",
".",
"ignoredTypes",
",",
"function",
"(",
"ignoredTypeOrSelector",
")",
"{",
"return",
"(",
"ignoredTypeOrSelector",
"===",
"myType",
")",
"||",
"$",
"(",
"el",
")",
".",
"is",
"(",
"ignoredTypeOrSelector",
")",
";",
"}",
")",
";",
"var",
"foundInInclude",
"=",
"_",
".",
"includes",
"(",
"config",
".",
"include",
",",
"identifier",
")",
";",
"var",
"foundInExclude",
"=",
"_",
".",
"includes",
"(",
"config",
".",
"exclude",
",",
"identifier",
")",
";",
"if",
"(",
"foundInInclude",
")",
"{",
"reject",
"=",
"false",
";",
"}",
"else",
"{",
"if",
"(",
"config",
".",
"include",
")",
"{",
"reject",
"=",
"true",
";",
"}",
"else",
"{",
"reject",
"=",
"(",
"foundInExclude",
"||",
"foundInIgnored",
")",
";",
"}",
"}",
"return",
"reject",
";",
"}",
")",
";",
"return",
"formInputs",
";",
"}"
] |
Retrieve all of the form inputs from the form
|
[
"Retrieve",
"all",
"of",
"the",
"form",
"inputs",
"from",
"the",
"form"
] |
85f6c0961b2a74f0b4dbd78be0319c765dc12da1
|
https://github.com/marionettejs/backbone.syphon/blob/85f6c0961b2a74f0b4dbd78be0319c765dc12da1/src/backbone.syphon.js#L89-L119
|
train
|
|
marionettejs/backbone.syphon
|
src/backbone.syphon.js
|
function(options) {
var config = _.clone(options) || {};
config.ignoredTypes = _.clone(Syphon.ignoredTypes);
config.inputReaders = config.inputReaders || Syphon.InputReaders;
config.inputWriters = config.inputWriters || Syphon.InputWriters;
config.keyExtractors = config.keyExtractors || Syphon.KeyExtractors;
config.keySplitter = config.keySplitter || Syphon.KeySplitter;
config.keyJoiner = config.keyJoiner || Syphon.KeyJoiner;
config.keyAssignmentValidators = config.keyAssignmentValidators || Syphon.KeyAssignmentValidators;
return config;
}
|
javascript
|
function(options) {
var config = _.clone(options) || {};
config.ignoredTypes = _.clone(Syphon.ignoredTypes);
config.inputReaders = config.inputReaders || Syphon.InputReaders;
config.inputWriters = config.inputWriters || Syphon.InputWriters;
config.keyExtractors = config.keyExtractors || Syphon.KeyExtractors;
config.keySplitter = config.keySplitter || Syphon.KeySplitter;
config.keyJoiner = config.keyJoiner || Syphon.KeyJoiner;
config.keyAssignmentValidators = config.keyAssignmentValidators || Syphon.KeyAssignmentValidators;
return config;
}
|
[
"function",
"(",
"options",
")",
"{",
"var",
"config",
"=",
"_",
".",
"clone",
"(",
"options",
")",
"||",
"{",
"}",
";",
"config",
".",
"ignoredTypes",
"=",
"_",
".",
"clone",
"(",
"Syphon",
".",
"ignoredTypes",
")",
";",
"config",
".",
"inputReaders",
"=",
"config",
".",
"inputReaders",
"||",
"Syphon",
".",
"InputReaders",
";",
"config",
".",
"inputWriters",
"=",
"config",
".",
"inputWriters",
"||",
"Syphon",
".",
"InputWriters",
";",
"config",
".",
"keyExtractors",
"=",
"config",
".",
"keyExtractors",
"||",
"Syphon",
".",
"KeyExtractors",
";",
"config",
".",
"keySplitter",
"=",
"config",
".",
"keySplitter",
"||",
"Syphon",
".",
"KeySplitter",
";",
"config",
".",
"keyJoiner",
"=",
"config",
".",
"keyJoiner",
"||",
"Syphon",
".",
"KeyJoiner",
";",
"config",
".",
"keyAssignmentValidators",
"=",
"config",
".",
"keyAssignmentValidators",
"||",
"Syphon",
".",
"KeyAssignmentValidators",
";",
"return",
"config",
";",
"}"
] |
Build a configuration object and initialize default values.
|
[
"Build",
"a",
"configuration",
"object",
"and",
"initialize",
"default",
"values",
"."
] |
85f6c0961b2a74f0b4dbd78be0319c765dc12da1
|
https://github.com/marionettejs/backbone.syphon/blob/85f6c0961b2a74f0b4dbd78be0319c765dc12da1/src/backbone.syphon.js#L162-L174
|
train
|
|
AlCalzone/node-coap-client
|
build/lib/Hostname.js
|
getSocketAddressFromURLSafeHostname
|
function getSocketAddressFromURLSafeHostname(hostname) {
return __awaiter(this, void 0, void 0, function* () {
// IPv4 addresses are fine
if (net_1.isIPv4(hostname))
return hostname;
// IPv6 addresses are wrapped in [], which need to be removed
if (/^\[.+\]$/.test(hostname)) {
const potentialIPv6 = hostname.slice(1, -1);
if (net_1.isIPv6(potentialIPv6))
return potentialIPv6;
}
// This is a hostname, look it up
try {
const address = yield lookupAsync(hostname);
// We found an address
if (address)
return address;
}
catch (e) {
// Lookup failed, continue working with the hostname
}
return hostname;
});
}
|
javascript
|
function getSocketAddressFromURLSafeHostname(hostname) {
return __awaiter(this, void 0, void 0, function* () {
// IPv4 addresses are fine
if (net_1.isIPv4(hostname))
return hostname;
// IPv6 addresses are wrapped in [], which need to be removed
if (/^\[.+\]$/.test(hostname)) {
const potentialIPv6 = hostname.slice(1, -1);
if (net_1.isIPv6(potentialIPv6))
return potentialIPv6;
}
// This is a hostname, look it up
try {
const address = yield lookupAsync(hostname);
// We found an address
if (address)
return address;
}
catch (e) {
// Lookup failed, continue working with the hostname
}
return hostname;
});
}
|
[
"function",
"getSocketAddressFromURLSafeHostname",
"(",
"hostname",
")",
"{",
"return",
"__awaiter",
"(",
"this",
",",
"void",
"0",
",",
"void",
"0",
",",
"function",
"*",
"(",
")",
"{",
"if",
"(",
"net_1",
".",
"isIPv4",
"(",
"hostname",
")",
")",
"return",
"hostname",
";",
"if",
"(",
"/",
"^\\[.+\\]$",
"/",
".",
"test",
"(",
"hostname",
")",
")",
"{",
"const",
"potentialIPv6",
"=",
"hostname",
".",
"slice",
"(",
"1",
",",
"-",
"1",
")",
";",
"if",
"(",
"net_1",
".",
"isIPv6",
"(",
"potentialIPv6",
")",
")",
"return",
"potentialIPv6",
";",
"}",
"try",
"{",
"const",
"address",
"=",
"yield",
"lookupAsync",
"(",
"hostname",
")",
";",
"if",
"(",
"address",
")",
"return",
"address",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"return",
"hostname",
";",
"}",
")",
";",
"}"
] |
Takes an URL-safe hostname and converts it to an address to be used in UDP sockets
|
[
"Takes",
"an",
"URL",
"-",
"safe",
"hostname",
"and",
"converts",
"it",
"to",
"an",
"address",
"to",
"be",
"used",
"in",
"UDP",
"sockets"
] |
e690881a7be677b922325ce0103ddab2fc3ca091
|
https://github.com/AlCalzone/node-coap-client/blob/e690881a7be677b922325ce0103ddab2fc3ca091/build/lib/Hostname.js#L21-L44
|
train
|
AlCalzone/node-coap-client
|
build/lib/Hostname.js
|
lookupAsync
|
function lookupAsync(hostname) {
return new Promise((resolve, reject) => {
dns.lookup(hostname, { all: true }, (err, addresses) => {
if (err)
return reject(err);
resolve(addresses[0].address);
});
});
}
|
javascript
|
function lookupAsync(hostname) {
return new Promise((resolve, reject) => {
dns.lookup(hostname, { all: true }, (err, addresses) => {
if (err)
return reject(err);
resolve(addresses[0].address);
});
});
}
|
[
"function",
"lookupAsync",
"(",
"hostname",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"dns",
".",
"lookup",
"(",
"hostname",
",",
"{",
"all",
":",
"true",
"}",
",",
"(",
"err",
",",
"addresses",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"reject",
"(",
"err",
")",
";",
"resolve",
"(",
"addresses",
"[",
"0",
"]",
".",
"address",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Tries to look up a hostname and returns the first IP address found
|
[
"Tries",
"to",
"look",
"up",
"a",
"hostname",
"and",
"returns",
"the",
"first",
"IP",
"address",
"found"
] |
e690881a7be677b922325ce0103ddab2fc3ca091
|
https://github.com/AlCalzone/node-coap-client/blob/e690881a7be677b922325ce0103ddab2fc3ca091/build/lib/Hostname.js#L47-L55
|
train
|
AlCalzone/node-coap-client
|
build/lib/strings.js
|
padStart
|
function padStart(str, targetLen, fill = " ") {
// simply return strings that are long enough to not be padded
if (str != null && str.length >= targetLen)
return str;
// make sure that <fill> isn't empty
if (fill == null || fill.length < 1)
throw new Error("fill must be at least one char");
// figure out how often we need to repeat <fill>
const missingLength = targetLen - str.length;
const repeats = Math.ceil(missingLength / fill.length);
return fill.repeat(repeats).substr(0, missingLength) + str;
}
|
javascript
|
function padStart(str, targetLen, fill = " ") {
// simply return strings that are long enough to not be padded
if (str != null && str.length >= targetLen)
return str;
// make sure that <fill> isn't empty
if (fill == null || fill.length < 1)
throw new Error("fill must be at least one char");
// figure out how often we need to repeat <fill>
const missingLength = targetLen - str.length;
const repeats = Math.ceil(missingLength / fill.length);
return fill.repeat(repeats).substr(0, missingLength) + str;
}
|
[
"function",
"padStart",
"(",
"str",
",",
"targetLen",
",",
"fill",
"=",
"\" \"",
")",
"{",
"if",
"(",
"str",
"!=",
"null",
"&&",
"str",
".",
"length",
">=",
"targetLen",
")",
"return",
"str",
";",
"if",
"(",
"fill",
"==",
"null",
"||",
"fill",
".",
"length",
"<",
"1",
")",
"throw",
"new",
"Error",
"(",
"\"fill must be at least one char\"",
")",
";",
"const",
"missingLength",
"=",
"targetLen",
"-",
"str",
".",
"length",
";",
"const",
"repeats",
"=",
"Math",
".",
"ceil",
"(",
"missingLength",
"/",
"fill",
".",
"length",
")",
";",
"return",
"fill",
".",
"repeat",
"(",
"repeats",
")",
".",
"substr",
"(",
"0",
",",
"missingLength",
")",
"+",
"str",
";",
"}"
] |
Pads a string to the given length by repeatedly prepending the filler at the beginning of the string.
@param str The string to pad
@param targetLen The target length
@param fill The filler string to prepend. Depending on the lenght requirements, this might get truncated.
|
[
"Pads",
"a",
"string",
"to",
"the",
"given",
"length",
"by",
"repeatedly",
"prepending",
"the",
"filler",
"at",
"the",
"beginning",
"of",
"the",
"string",
"."
] |
e690881a7be677b922325ce0103ddab2fc3ca091
|
https://github.com/AlCalzone/node-coap-client/blob/e690881a7be677b922325ce0103ddab2fc3ca091/build/lib/strings.js#L9-L20
|
train
|
jsakas/CSSStyleDeclaration
|
lib/parsers.js
|
function(dashed) {
var i;
var camel = '';
var nextCap = false;
for (i = 0; i < dashed.length; i++) {
if (dashed[i] !== '-') {
camel += nextCap ? dashed[i].toUpperCase() : dashed[i];
nextCap = false;
} else {
nextCap = true;
}
}
return camel;
}
|
javascript
|
function(dashed) {
var i;
var camel = '';
var nextCap = false;
for (i = 0; i < dashed.length; i++) {
if (dashed[i] !== '-') {
camel += nextCap ? dashed[i].toUpperCase() : dashed[i];
nextCap = false;
} else {
nextCap = true;
}
}
return camel;
}
|
[
"function",
"(",
"dashed",
")",
"{",
"var",
"i",
";",
"var",
"camel",
"=",
"''",
";",
"var",
"nextCap",
"=",
"false",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"dashed",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"dashed",
"[",
"i",
"]",
"!==",
"'-'",
")",
"{",
"camel",
"+=",
"nextCap",
"?",
"dashed",
"[",
"i",
"]",
".",
"toUpperCase",
"(",
")",
":",
"dashed",
"[",
"i",
"]",
";",
"nextCap",
"=",
"false",
";",
"}",
"else",
"{",
"nextCap",
"=",
"true",
";",
"}",
"}",
"return",
"camel",
";",
"}"
] |
utility to translate from border-width to borderWidth
|
[
"utility",
"to",
"translate",
"from",
"border",
"-",
"width",
"to",
"borderWidth"
] |
8cc6e5875a769767fc9f02bdd1c53c49bceb8c26
|
https://github.com/jsakas/CSSStyleDeclaration/blob/8cc6e5875a769767fc9f02bdd1c53c49bceb8c26/lib/parsers.js#L437-L450
|
train
|
|
jsakas/CSSStyleDeclaration
|
lib/parsers.js
|
function(str) {
var deliminator_stack = [];
var length = str.length;
var i;
var parts = [];
var current_part = '';
var opening_index;
var closing_index;
for (i = 0; i < length; i++) {
opening_index = opening_deliminators.indexOf(str[i]);
closing_index = closing_deliminators.indexOf(str[i]);
if (is_space.test(str[i])) {
if (deliminator_stack.length === 0) {
if (current_part !== '') {
parts.push(current_part);
}
current_part = '';
} else {
current_part += str[i];
}
} else {
if (str[i] === '\\') {
i++;
current_part += str[i];
} else {
current_part += str[i];
if (
closing_index !== -1 &&
closing_index === deliminator_stack[deliminator_stack.length - 1]
) {
deliminator_stack.pop();
} else if (opening_index !== -1) {
deliminator_stack.push(opening_index);
}
}
}
}
if (current_part !== '') {
parts.push(current_part);
}
return parts;
}
|
javascript
|
function(str) {
var deliminator_stack = [];
var length = str.length;
var i;
var parts = [];
var current_part = '';
var opening_index;
var closing_index;
for (i = 0; i < length; i++) {
opening_index = opening_deliminators.indexOf(str[i]);
closing_index = closing_deliminators.indexOf(str[i]);
if (is_space.test(str[i])) {
if (deliminator_stack.length === 0) {
if (current_part !== '') {
parts.push(current_part);
}
current_part = '';
} else {
current_part += str[i];
}
} else {
if (str[i] === '\\') {
i++;
current_part += str[i];
} else {
current_part += str[i];
if (
closing_index !== -1 &&
closing_index === deliminator_stack[deliminator_stack.length - 1]
) {
deliminator_stack.pop();
} else if (opening_index !== -1) {
deliminator_stack.push(opening_index);
}
}
}
}
if (current_part !== '') {
parts.push(current_part);
}
return parts;
}
|
[
"function",
"(",
"str",
")",
"{",
"var",
"deliminator_stack",
"=",
"[",
"]",
";",
"var",
"length",
"=",
"str",
".",
"length",
";",
"var",
"i",
";",
"var",
"parts",
"=",
"[",
"]",
";",
"var",
"current_part",
"=",
"''",
";",
"var",
"opening_index",
";",
"var",
"closing_index",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"opening_index",
"=",
"opening_deliminators",
".",
"indexOf",
"(",
"str",
"[",
"i",
"]",
")",
";",
"closing_index",
"=",
"closing_deliminators",
".",
"indexOf",
"(",
"str",
"[",
"i",
"]",
")",
";",
"if",
"(",
"is_space",
".",
"test",
"(",
"str",
"[",
"i",
"]",
")",
")",
"{",
"if",
"(",
"deliminator_stack",
".",
"length",
"===",
"0",
")",
"{",
"if",
"(",
"current_part",
"!==",
"''",
")",
"{",
"parts",
".",
"push",
"(",
"current_part",
")",
";",
"}",
"current_part",
"=",
"''",
";",
"}",
"else",
"{",
"current_part",
"+=",
"str",
"[",
"i",
"]",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"str",
"[",
"i",
"]",
"===",
"'\\\\'",
")",
"\\\\",
"else",
"{",
"i",
"++",
";",
"current_part",
"+=",
"str",
"[",
"i",
"]",
";",
"}",
"}",
"}",
"{",
"current_part",
"+=",
"str",
"[",
"i",
"]",
";",
"if",
"(",
"closing_index",
"!==",
"-",
"1",
"&&",
"closing_index",
"===",
"deliminator_stack",
"[",
"deliminator_stack",
".",
"length",
"-",
"1",
"]",
")",
"{",
"deliminator_stack",
".",
"pop",
"(",
")",
";",
"}",
"else",
"if",
"(",
"opening_index",
"!==",
"-",
"1",
")",
"{",
"deliminator_stack",
".",
"push",
"(",
"opening_index",
")",
";",
"}",
"}",
"if",
"(",
"current_part",
"!==",
"''",
")",
"{",
"parts",
".",
"push",
"(",
"current_part",
")",
";",
"}",
"}"
] |
this splits on whitespace, but keeps quoted and parened parts together
|
[
"this",
"splits",
"on",
"whitespace",
"but",
"keeps",
"quoted",
"and",
"parened",
"parts",
"together"
] |
8cc6e5875a769767fc9f02bdd1c53c49bceb8c26
|
https://github.com/jsakas/CSSStyleDeclaration/blob/8cc6e5875a769767fc9f02bdd1c53c49bceb8c26/lib/parsers.js#L457-L498
|
train
|
|
jsakas/CSSStyleDeclaration
|
lib/CSSStyleDeclaration.js
|
function(value) {
var i;
for (i = value; i < this._length; i++) {
delete this[i];
}
this._length = value;
}
|
javascript
|
function(value) {
var i;
for (i = value; i < this._length; i++) {
delete this[i];
}
this._length = value;
}
|
[
"function",
"(",
"value",
")",
"{",
"var",
"i",
";",
"for",
"(",
"i",
"=",
"value",
";",
"i",
"<",
"this",
".",
"_length",
";",
"i",
"++",
")",
"{",
"delete",
"this",
"[",
"i",
"]",
";",
"}",
"this",
".",
"_length",
"=",
"value",
";",
"}"
] |
This deletes indices if the new length is less then the current
length. If the new length is more, it does nothing, the new indices
will be undefined until set.
|
[
"This",
"deletes",
"indices",
"if",
"the",
"new",
"length",
"is",
"less",
"then",
"the",
"current",
"length",
".",
"If",
"the",
"new",
"length",
"is",
"more",
"it",
"does",
"nothing",
"the",
"new",
"indices",
"will",
"be",
"undefined",
"until",
"set",
"."
] |
8cc6e5875a769767fc9f02bdd1c53c49bceb8c26
|
https://github.com/jsakas/CSSStyleDeclaration/blob/8cc6e5875a769767fc9f02bdd1c53c49bceb8c26/lib/CSSStyleDeclaration.js#L225-L231
|
train
|
|
senecajs/seneca-entity
|
lib/store.js
|
function(cmdfunc) {
var outfunc = function(msg, reply, meta) {
if ('save' !== msg.cmd) {
if (null == msg.q) {
msg.q = {}
if (null != msg.id) {
msg.q.id = msg.id
delete msg.id
}
}
if (null == msg.qent) {
msg.qent = this.make$({
entity$: {
name: msg.name,
base: msg.base,
zone: msg.zone
}
})
}
}
if (null != msg.ent && 'function' != typeof msg.ent.canon$) {
msg.ent = this.make$({
entity$: {
name: msg.name,
base: msg.base,
zone: msg.zone
}
}).data$(msg.ent)
}
return cmdfunc.call(this, msg, reply, meta)
}
return outfunc
}
|
javascript
|
function(cmdfunc) {
var outfunc = function(msg, reply, meta) {
if ('save' !== msg.cmd) {
if (null == msg.q) {
msg.q = {}
if (null != msg.id) {
msg.q.id = msg.id
delete msg.id
}
}
if (null == msg.qent) {
msg.qent = this.make$({
entity$: {
name: msg.name,
base: msg.base,
zone: msg.zone
}
})
}
}
if (null != msg.ent && 'function' != typeof msg.ent.canon$) {
msg.ent = this.make$({
entity$: {
name: msg.name,
base: msg.base,
zone: msg.zone
}
}).data$(msg.ent)
}
return cmdfunc.call(this, msg, reply, meta)
}
return outfunc
}
|
[
"function",
"(",
"cmdfunc",
")",
"{",
"var",
"outfunc",
"=",
"function",
"(",
"msg",
",",
"reply",
",",
"meta",
")",
"{",
"if",
"(",
"'save'",
"!==",
"msg",
".",
"cmd",
")",
"{",
"if",
"(",
"null",
"==",
"msg",
".",
"q",
")",
"{",
"msg",
".",
"q",
"=",
"{",
"}",
"if",
"(",
"null",
"!=",
"msg",
".",
"id",
")",
"{",
"msg",
".",
"q",
".",
"id",
"=",
"msg",
".",
"id",
"delete",
"msg",
".",
"id",
"}",
"}",
"if",
"(",
"null",
"==",
"msg",
".",
"qent",
")",
"{",
"msg",
".",
"qent",
"=",
"this",
".",
"make$",
"(",
"{",
"entity$",
":",
"{",
"name",
":",
"msg",
".",
"name",
",",
"base",
":",
"msg",
".",
"base",
",",
"zone",
":",
"msg",
".",
"zone",
"}",
"}",
")",
"}",
"}",
"if",
"(",
"null",
"!=",
"msg",
".",
"ent",
"&&",
"'function'",
"!=",
"typeof",
"msg",
".",
"ent",
".",
"canon$",
")",
"{",
"msg",
".",
"ent",
"=",
"this",
".",
"make$",
"(",
"{",
"entity$",
":",
"{",
"name",
":",
"msg",
".",
"name",
",",
"base",
":",
"msg",
".",
"base",
",",
"zone",
":",
"msg",
".",
"zone",
"}",
"}",
")",
".",
"data$",
"(",
"msg",
".",
"ent",
")",
"}",
"return",
"cmdfunc",
".",
"call",
"(",
"this",
",",
"msg",
",",
"reply",
",",
"meta",
")",
"}",
"return",
"outfunc",
"}"
] |
Ensure entity objects are instantiated
|
[
"Ensure",
"entity",
"objects",
"are",
"instantiated"
] |
358c2be92994b09747b762246067c5709b3793ec
|
https://github.com/senecajs/seneca-entity/blob/358c2be92994b09747b762246067c5709b3793ec/lib/store.js#L139-L176
|
train
|
|
jfrog/jfrog-ui-essentials
|
Gulpfile.js
|
function (err) {
//if any error happened in the previous tasks, exit with a code > 0
if (err) {
var exitCode = 2;
console.log('[ERROR] gulp build task failed', err);
console.log('[FAIL] gulp build task failed - exiting with code ' + exitCode);
return process.exit(exitCode);
}
else {
return callback();
}
}
|
javascript
|
function (err) {
//if any error happened in the previous tasks, exit with a code > 0
if (err) {
var exitCode = 2;
console.log('[ERROR] gulp build task failed', err);
console.log('[FAIL] gulp build task failed - exiting with code ' + exitCode);
return process.exit(exitCode);
}
else {
return callback();
}
}
|
[
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"var",
"exitCode",
"=",
"2",
";",
"console",
".",
"log",
"(",
"'[ERROR] gulp build task failed'",
",",
"err",
")",
";",
"console",
".",
"log",
"(",
"'[FAIL] gulp build task failed - exiting with code '",
"+",
"exitCode",
")",
";",
"return",
"process",
".",
"exit",
"(",
"exitCode",
")",
";",
"}",
"else",
"{",
"return",
"callback",
"(",
")",
";",
"}",
"}"
] |
this callback is executed at the end, if any of the previous tasks errored, the first param contains the error
|
[
"this",
"callback",
"is",
"executed",
"at",
"the",
"end",
"if",
"any",
"of",
"the",
"previous",
"tasks",
"errored",
"the",
"first",
"param",
"contains",
"the",
"error"
] |
552920ee17d481e092576d624e5aa73634cf8ad6
|
https://github.com/jfrog/jfrog-ui-essentials/blob/552920ee17d481e092576d624e5aa73634cf8ad6/Gulpfile.js#L67-L78
|
train
|
|
jfrog/jfrog-ui-essentials
|
src/filters/split_words.js
|
splitWords
|
function splitWords(str) {
return str
// insert a space between lower & upper
.replace(/([a-z])([A-Z])/g, '$1 $2')
// space before last upper in a sequence followed by lower
.replace(/\b([A-Z]+)([A-Z])([a-z])/, '$1 $2$3')
// uppercase the first character
.replace(/^./, function(str){ return str.toUpperCase(); })
}
|
javascript
|
function splitWords(str) {
return str
// insert a space between lower & upper
.replace(/([a-z])([A-Z])/g, '$1 $2')
// space before last upper in a sequence followed by lower
.replace(/\b([A-Z]+)([A-Z])([a-z])/, '$1 $2$3')
// uppercase the first character
.replace(/^./, function(str){ return str.toUpperCase(); })
}
|
[
"function",
"splitWords",
"(",
"str",
")",
"{",
"return",
"str",
".",
"replace",
"(",
"/",
"([a-z])([A-Z])",
"/",
"g",
",",
"'$1 $2'",
")",
".",
"replace",
"(",
"/",
"\\b([A-Z]+)([A-Z])([a-z])",
"/",
",",
"'$1 $2$3'",
")",
".",
"replace",
"(",
"/",
"^.",
"/",
",",
"function",
"(",
"str",
")",
"{",
"return",
"str",
".",
"toUpperCase",
"(",
")",
";",
"}",
")",
"}"
] |
Splits a camel-case or Pascal-case variable name into individual words.
@param {string} s
@returns {string[]}
|
[
"Splits",
"a",
"camel",
"-",
"case",
"or",
"Pascal",
"-",
"case",
"variable",
"name",
"into",
"individual",
"words",
"."
] |
552920ee17d481e092576d624e5aa73634cf8ad6
|
https://github.com/jfrog/jfrog-ui-essentials/blob/552920ee17d481e092576d624e5aa73634cf8ad6/src/filters/split_words.js#L12-L20
|
train
|
jfrog/jfrog-ui-essentials
|
src/directives/jf_markup_editor/codemirror-asciidoc.js
|
function (stream, state) {
var plannedToken = state.plannedTokens.shift();
if (plannedToken === undefined) {
return null;
}
stream.match(plannedToken.value);
var tokens = plannedToken.type.split('.');
return cmTokenFromAceTokens(tokens);
}
|
javascript
|
function (stream, state) {
var plannedToken = state.plannedTokens.shift();
if (plannedToken === undefined) {
return null;
}
stream.match(plannedToken.value);
var tokens = plannedToken.type.split('.');
return cmTokenFromAceTokens(tokens);
}
|
[
"function",
"(",
"stream",
",",
"state",
")",
"{",
"var",
"plannedToken",
"=",
"state",
".",
"plannedTokens",
".",
"shift",
"(",
")",
";",
"if",
"(",
"plannedToken",
"===",
"undefined",
")",
"{",
"return",
"null",
";",
"}",
"stream",
".",
"match",
"(",
"plannedToken",
".",
"value",
")",
";",
"var",
"tokens",
"=",
"plannedToken",
".",
"type",
".",
"split",
"(",
"'.'",
")",
";",
"return",
"cmTokenFromAceTokens",
"(",
"tokens",
")",
";",
"}"
] |
Consume a token from plannedTokens.
|
[
"Consume",
"a",
"token",
"from",
"plannedTokens",
"."
] |
552920ee17d481e092576d624e5aa73634cf8ad6
|
https://github.com/jfrog/jfrog-ui-essentials/blob/552920ee17d481e092576d624e5aa73634cf8ad6/src/directives/jf_markup_editor/codemirror-asciidoc.js#L610-L618
|
train
|
|
eanplatter/enclave
|
src/postinstall/index.js
|
configureConfigFile
|
function configureConfigFile(err, result) {
for (var key in result) {
if (key === 'port' && !result[key] || key === 'port' && result[key] !== result[key]) {
shell.echo('exports.' + key + ' = 8080' + '\n').toEnd(clientFiles.config)
} else {
shell.echo('exports.' + key + ' = ' + JSON.stringify(result[key]) + '\n').toEnd(clientFiles.config)
}
}
if (err) {
return onErr(err)
}
console.log(chalk.yellow('Here\'s what I\'ve got down, if something is wrong you can edit this in your enclave.js file.:'))
console.log(chalk.red(' entry: ') + chalk.magenta(result.entry))
console.log(chalk.red(' output: ') + chalk.magenta(result.output))
console.log(!result.port ? chalk.red(' port: 8080') : chalk.red(' port: ') + chalk.magenta(result.port))
console.log(chalk.red(' index: ') + chalk.magenta(result.index))
console.log(chalk.red(' autoInstall: ') + chalk.magenta(result.autoInstall))
console.log(chalk.red(' live: ') + chalk.magenta(result.live))
console.log(chalk.green('To run your app, just type'), chalk.green.bold('$ npm run enclave-serve'))
shell.sed(insertScript.flag, insertScript.insertionPoint, insertScript.addition, insertScript.file)
preventFinishFor(5000)
}
|
javascript
|
function configureConfigFile(err, result) {
for (var key in result) {
if (key === 'port' && !result[key] || key === 'port' && result[key] !== result[key]) {
shell.echo('exports.' + key + ' = 8080' + '\n').toEnd(clientFiles.config)
} else {
shell.echo('exports.' + key + ' = ' + JSON.stringify(result[key]) + '\n').toEnd(clientFiles.config)
}
}
if (err) {
return onErr(err)
}
console.log(chalk.yellow('Here\'s what I\'ve got down, if something is wrong you can edit this in your enclave.js file.:'))
console.log(chalk.red(' entry: ') + chalk.magenta(result.entry))
console.log(chalk.red(' output: ') + chalk.magenta(result.output))
console.log(!result.port ? chalk.red(' port: 8080') : chalk.red(' port: ') + chalk.magenta(result.port))
console.log(chalk.red(' index: ') + chalk.magenta(result.index))
console.log(chalk.red(' autoInstall: ') + chalk.magenta(result.autoInstall))
console.log(chalk.red(' live: ') + chalk.magenta(result.live))
console.log(chalk.green('To run your app, just type'), chalk.green.bold('$ npm run enclave-serve'))
shell.sed(insertScript.flag, insertScript.insertionPoint, insertScript.addition, insertScript.file)
preventFinishFor(5000)
}
|
[
"function",
"configureConfigFile",
"(",
"err",
",",
"result",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"result",
")",
"{",
"if",
"(",
"key",
"===",
"'port'",
"&&",
"!",
"result",
"[",
"key",
"]",
"||",
"key",
"===",
"'port'",
"&&",
"result",
"[",
"key",
"]",
"!==",
"result",
"[",
"key",
"]",
")",
"{",
"shell",
".",
"echo",
"(",
"'exports.'",
"+",
"key",
"+",
"' = 8080'",
"+",
"'\\n'",
")",
".",
"\\n",
"toEnd",
"}",
"else",
"(",
"clientFiles",
".",
"config",
")",
"}",
"{",
"shell",
".",
"echo",
"(",
"'exports.'",
"+",
"key",
"+",
"' = '",
"+",
"JSON",
".",
"stringify",
"(",
"result",
"[",
"key",
"]",
")",
"+",
"'\\n'",
")",
".",
"\\n",
"toEnd",
"}",
"(",
"clientFiles",
".",
"config",
")",
"if",
"(",
"err",
")",
"{",
"return",
"onErr",
"(",
"err",
")",
"}",
"console",
".",
"log",
"(",
"chalk",
".",
"yellow",
"(",
"'Here\\'s what I\\'ve got down, if something is wrong you can edit this in your enclave.js file.:'",
")",
")",
"\\'",
"\\'",
"console",
".",
"log",
"(",
"chalk",
".",
"red",
"(",
"' entry: '",
")",
"+",
"chalk",
".",
"magenta",
"(",
"result",
".",
"entry",
")",
")",
"console",
".",
"log",
"(",
"chalk",
".",
"red",
"(",
"' output: '",
")",
"+",
"chalk",
".",
"magenta",
"(",
"result",
".",
"output",
")",
")",
"console",
".",
"log",
"(",
"!",
"result",
".",
"port",
"?",
"chalk",
".",
"red",
"(",
"' port: 8080'",
")",
":",
"chalk",
".",
"red",
"(",
"' port: '",
")",
"+",
"chalk",
".",
"magenta",
"(",
"result",
".",
"port",
")",
")",
"console",
".",
"log",
"(",
"chalk",
".",
"red",
"(",
"' index: '",
")",
"+",
"chalk",
".",
"magenta",
"(",
"result",
".",
"index",
")",
")",
"console",
".",
"log",
"(",
"chalk",
".",
"red",
"(",
"' autoInstall: '",
")",
"+",
"chalk",
".",
"magenta",
"(",
"result",
".",
"autoInstall",
")",
")",
"}"
] |
This method is really ugly and implicit, I'm sorry.
It loops through the prompt's result object, and adds each result to a file in the user's root
to be referenced later.
It also console logs the result object with this weird color library that extends the String
prototype to have color properties, god this is terrible.
@param err
@param {object} result
@returns {number}
|
[
"This",
"method",
"is",
"really",
"ugly",
"and",
"implicit",
"I",
"m",
"sorry",
"."
] |
7caefed189e299bf1939987c0a6282686cf41c31
|
https://github.com/eanplatter/enclave/blob/7caefed189e299bf1939987c0a6282686cf41c31/src/postinstall/index.js#L59-L80
|
train
|
primus/ejson
|
vendor/ejson.js
|
function (value) {
if (typeof value === 'object' && value !== null) {
if (_.size(value) <= 2
&& _.all(value, function (v, k) {
return typeof k === 'string' && k.substr(0, 1) === '$';
})) {
for (var i = 0; i < builtinConverters.length; i++) {
var converter = builtinConverters[i];
if (converter.matchJSONValue(value)) {
return converter.fromJSONValue(value);
}
}
}
}
return value;
}
|
javascript
|
function (value) {
if (typeof value === 'object' && value !== null) {
if (_.size(value) <= 2
&& _.all(value, function (v, k) {
return typeof k === 'string' && k.substr(0, 1) === '$';
})) {
for (var i = 0; i < builtinConverters.length; i++) {
var converter = builtinConverters[i];
if (converter.matchJSONValue(value)) {
return converter.fromJSONValue(value);
}
}
}
}
return value;
}
|
[
"function",
"(",
"value",
")",
"{",
"if",
"(",
"typeof",
"value",
"===",
"'object'",
"&&",
"value",
"!==",
"null",
")",
"{",
"if",
"(",
"_",
".",
"size",
"(",
"value",
")",
"<=",
"2",
"&&",
"_",
".",
"all",
"(",
"value",
",",
"function",
"(",
"v",
",",
"k",
")",
"{",
"return",
"typeof",
"k",
"===",
"'string'",
"&&",
"k",
".",
"substr",
"(",
"0",
",",
"1",
")",
"===",
"'$'",
";",
"}",
")",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"builtinConverters",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"converter",
"=",
"builtinConverters",
"[",
"i",
"]",
";",
"if",
"(",
"converter",
".",
"matchJSONValue",
"(",
"value",
")",
")",
"{",
"return",
"converter",
".",
"fromJSONValue",
"(",
"value",
")",
";",
"}",
"}",
"}",
"}",
"return",
"value",
";",
"}"
] |
DOES NOT RECURSE. For actually getting the fully-changed value, use EJSON.fromJSONValue
|
[
"DOES",
"NOT",
"RECURSE",
".",
"For",
"actually",
"getting",
"the",
"fully",
"-",
"changed",
"value",
"use",
"EJSON",
".",
"fromJSONValue"
] |
249b4aced9b66d11a2cac1fa8cc9037dcf1760a0
|
https://github.com/primus/ejson/blob/249b4aced9b66d11a2cac1fa8cc9037dcf1760a0/vendor/ejson.js#L295-L310
|
train
|
|
yayadrian/node-red-slack
|
slackpost.js
|
SetConfigNodeConnectionListeners
|
function SetConfigNodeConnectionListeners(node) {
node.clientNode.rtmClient.on("connecting", () => {
node.status(statuses.connecting);
});
node.clientNode.rtmClient.on("ready", () => {
node.status(statuses.connected);
});
node.clientNode.rtmClient.on("disconnected", e => {
var status = statuses.disconnected;
/**
* {
* code: 'slackclient_platform_error',
* data: { ok: false, error: 'invalid_auth' }
* }
*/
if (e.code == "slackclient_platform_error" && e.data.ok === false) {
status.text = e.data.error;
}
node.status(status);
});
/**
* if connectivity is dropped we go from connected -> reconnecting
* directly bypassing disconnected
*/
node.clientNode.rtmClient.on("reconnecting", () => {
node.status(statuses.disconnected);
});
}
|
javascript
|
function SetConfigNodeConnectionListeners(node) {
node.clientNode.rtmClient.on("connecting", () => {
node.status(statuses.connecting);
});
node.clientNode.rtmClient.on("ready", () => {
node.status(statuses.connected);
});
node.clientNode.rtmClient.on("disconnected", e => {
var status = statuses.disconnected;
/**
* {
* code: 'slackclient_platform_error',
* data: { ok: false, error: 'invalid_auth' }
* }
*/
if (e.code == "slackclient_platform_error" && e.data.ok === false) {
status.text = e.data.error;
}
node.status(status);
});
/**
* if connectivity is dropped we go from connected -> reconnecting
* directly bypassing disconnected
*/
node.clientNode.rtmClient.on("reconnecting", () => {
node.status(statuses.disconnected);
});
}
|
[
"function",
"SetConfigNodeConnectionListeners",
"(",
"node",
")",
"{",
"node",
".",
"clientNode",
".",
"rtmClient",
".",
"on",
"(",
"\"connecting\"",
",",
"(",
")",
"=>",
"{",
"node",
".",
"status",
"(",
"statuses",
".",
"connecting",
")",
";",
"}",
")",
";",
"node",
".",
"clientNode",
".",
"rtmClient",
".",
"on",
"(",
"\"ready\"",
",",
"(",
")",
"=>",
"{",
"node",
".",
"status",
"(",
"statuses",
".",
"connected",
")",
";",
"}",
")",
";",
"node",
".",
"clientNode",
".",
"rtmClient",
".",
"on",
"(",
"\"disconnected\"",
",",
"e",
"=>",
"{",
"var",
"status",
"=",
"statuses",
".",
"disconnected",
";",
"if",
"(",
"e",
".",
"code",
"==",
"\"slackclient_platform_error\"",
"&&",
"e",
".",
"data",
".",
"ok",
"===",
"false",
")",
"{",
"status",
".",
"text",
"=",
"e",
".",
"data",
".",
"error",
";",
"}",
"node",
".",
"status",
"(",
"status",
")",
";",
"}",
")",
";",
"node",
".",
"clientNode",
".",
"rtmClient",
".",
"on",
"(",
"\"reconnecting\"",
",",
"(",
")",
"=>",
"{",
"node",
".",
"status",
"(",
"statuses",
".",
"disconnected",
")",
";",
"}",
")",
";",
"}"
] |
Common event listeners to set status indicators
@param {*} node
|
[
"Common",
"event",
"listeners",
"to",
"set",
"status",
"indicators"
] |
9136f5f9a6489f1be4268a9d285ca026ffa690e2
|
https://github.com/yayadrian/node-red-slack/blob/9136f5f9a6489f1be4268a9d285ca026ffa690e2/slackpost.js#L113-L145
|
train
|
yayadrian/node-red-slack
|
slackpost.js
|
SlackState
|
function SlackState(n) {
RED.nodes.createNode(this, n);
var node = this;
this.client = n.client;
this.clientNode = RED.nodes.getNode(this.client);
node.status(statuses.disconnected);
if (node.client) {
SetConfigNodeConnectionListeners(node);
node.on("input", function(msg) {
SlackDebug("slack-state incomiming message", msg);
node.status(statuses.sending);
/**
* support for forcing a refresh of data
*/
if (msg.payload === true) {
node.clientNode
.refreshState()
.then(() => {
msg.slackState = node.clientNode.state;
node.send(msg);
node.status(statuses.connected);
})
.catch(e => {
SlackDebug("slack-state error response", e.data);
msg.payload = e.data;
node.send(msg);
node.status(statuses.connected);
});
} else {
msg.slackState = node.clientNode.state;
node.send(msg);
node.status(statuses.connected);
}
});
["state_initialized"].forEach(eventName => {
node.clientNode.on(eventName, e => {
node.status(statuses.sending);
var msg = {};
switch (eventName) {
case "state_initialized":
eventName = "ready";
break;
}
msg.slackState = node.clientNode.state;
msg.payload = {
type: eventName
};
node.send([null, msg]);
node.status(statuses.connected);
});
});
} else {
node.status(statuses.misconfigured);
}
}
|
javascript
|
function SlackState(n) {
RED.nodes.createNode(this, n);
var node = this;
this.client = n.client;
this.clientNode = RED.nodes.getNode(this.client);
node.status(statuses.disconnected);
if (node.client) {
SetConfigNodeConnectionListeners(node);
node.on("input", function(msg) {
SlackDebug("slack-state incomiming message", msg);
node.status(statuses.sending);
/**
* support for forcing a refresh of data
*/
if (msg.payload === true) {
node.clientNode
.refreshState()
.then(() => {
msg.slackState = node.clientNode.state;
node.send(msg);
node.status(statuses.connected);
})
.catch(e => {
SlackDebug("slack-state error response", e.data);
msg.payload = e.data;
node.send(msg);
node.status(statuses.connected);
});
} else {
msg.slackState = node.clientNode.state;
node.send(msg);
node.status(statuses.connected);
}
});
["state_initialized"].forEach(eventName => {
node.clientNode.on(eventName, e => {
node.status(statuses.sending);
var msg = {};
switch (eventName) {
case "state_initialized":
eventName = "ready";
break;
}
msg.slackState = node.clientNode.state;
msg.payload = {
type: eventName
};
node.send([null, msg]);
node.status(statuses.connected);
});
});
} else {
node.status(statuses.misconfigured);
}
}
|
[
"function",
"SlackState",
"(",
"n",
")",
"{",
"RED",
".",
"nodes",
".",
"createNode",
"(",
"this",
",",
"n",
")",
";",
"var",
"node",
"=",
"this",
";",
"this",
".",
"client",
"=",
"n",
".",
"client",
";",
"this",
".",
"clientNode",
"=",
"RED",
".",
"nodes",
".",
"getNode",
"(",
"this",
".",
"client",
")",
";",
"node",
".",
"status",
"(",
"statuses",
".",
"disconnected",
")",
";",
"if",
"(",
"node",
".",
"client",
")",
"{",
"SetConfigNodeConnectionListeners",
"(",
"node",
")",
";",
"node",
".",
"on",
"(",
"\"input\"",
",",
"function",
"(",
"msg",
")",
"{",
"SlackDebug",
"(",
"\"slack-state incomiming message\"",
",",
"msg",
")",
";",
"node",
".",
"status",
"(",
"statuses",
".",
"sending",
")",
";",
"if",
"(",
"msg",
".",
"payload",
"===",
"true",
")",
"{",
"node",
".",
"clientNode",
".",
"refreshState",
"(",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"msg",
".",
"slackState",
"=",
"node",
".",
"clientNode",
".",
"state",
";",
"node",
".",
"send",
"(",
"msg",
")",
";",
"node",
".",
"status",
"(",
"statuses",
".",
"connected",
")",
";",
"}",
")",
".",
"catch",
"(",
"e",
"=>",
"{",
"SlackDebug",
"(",
"\"slack-state error response\"",
",",
"e",
".",
"data",
")",
";",
"msg",
".",
"payload",
"=",
"e",
".",
"data",
";",
"node",
".",
"send",
"(",
"msg",
")",
";",
"node",
".",
"status",
"(",
"statuses",
".",
"connected",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"msg",
".",
"slackState",
"=",
"node",
".",
"clientNode",
".",
"state",
";",
"node",
".",
"send",
"(",
"msg",
")",
";",
"node",
".",
"status",
"(",
"statuses",
".",
"connected",
")",
";",
"}",
"}",
")",
";",
"[",
"\"state_initialized\"",
"]",
".",
"forEach",
"(",
"eventName",
"=>",
"{",
"node",
".",
"clientNode",
".",
"on",
"(",
"eventName",
",",
"e",
"=>",
"{",
"node",
".",
"status",
"(",
"statuses",
".",
"sending",
")",
";",
"var",
"msg",
"=",
"{",
"}",
";",
"switch",
"(",
"eventName",
")",
"{",
"case",
"\"state_initialized\"",
":",
"eventName",
"=",
"\"ready\"",
";",
"break",
";",
"}",
"msg",
".",
"slackState",
"=",
"node",
".",
"clientNode",
".",
"state",
";",
"msg",
".",
"payload",
"=",
"{",
"type",
":",
"eventName",
"}",
";",
"node",
".",
"send",
"(",
"[",
"null",
",",
"msg",
"]",
")",
";",
"node",
".",
"status",
"(",
"statuses",
".",
"connected",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"node",
".",
"status",
"(",
"statuses",
".",
"misconfigured",
")",
";",
"}",
"}"
] |
Send the current state of the config object out
@param {*} n
|
[
"Send",
"the",
"current",
"state",
"of",
"the",
"config",
"object",
"out"
] |
9136f5f9a6489f1be4268a9d285ca026ffa690e2
|
https://github.com/yayadrian/node-red-slack/blob/9136f5f9a6489f1be4268a9d285ca026ffa690e2/slackpost.js#L918-L981
|
train
|
comicrelief/pattern-lab
|
sass/themes/cr/2019/components/membership-signup/js/membership-signup.js
|
moneyBuyDescriptionHandler
|
function moneyBuyDescriptionHandler(descriptions, position) {
descriptions.each(function (i) {
$(this).removeClass('show-money-buy-copy');
if (position === i + 1) {
$(this).addClass('show-money-buy-copy');
}
})
}
|
javascript
|
function moneyBuyDescriptionHandler(descriptions, position) {
descriptions.each(function (i) {
$(this).removeClass('show-money-buy-copy');
if (position === i + 1) {
$(this).addClass('show-money-buy-copy');
}
})
}
|
[
"function",
"moneyBuyDescriptionHandler",
"(",
"descriptions",
",",
"position",
")",
"{",
"descriptions",
".",
"each",
"(",
"function",
"(",
"i",
")",
"{",
"$",
"(",
"this",
")",
".",
"removeClass",
"(",
"'show-money-buy-copy'",
")",
";",
"if",
"(",
"position",
"===",
"i",
"+",
"1",
")",
"{",
"$",
"(",
"this",
")",
".",
"addClass",
"(",
"'show-money-buy-copy'",
")",
";",
"}",
"}",
")",
"}"
] |
Money buy description handler
|
[
"Money",
"buy",
"description",
"handler"
] |
ab0b6c106ce6b634ec9c1226ab93eb10c41bd9f3
|
https://github.com/comicrelief/pattern-lab/blob/ab0b6c106ce6b634ec9c1226ab93eb10c41bd9f3/sass/themes/cr/2019/components/membership-signup/js/membership-signup.js#L250-L257
|
train
|
comicrelief/pattern-lab
|
sass/themes/cr/2019/components/copy-video/js/copy-video.js
|
onYouTubePlayerAPIReady
|
function onYouTubePlayerAPIReady() {
// Loop through each iframe video on the page
jQuery( "iframe.copy-video__video").each(function (index) {
// Create IDs dynamically
var iframeID = "js-copy-video-" + index;
var buttonID = "js-copy-video-" + index + "__button";
// Set IDs
jQuery(this).attr('id', iframeID);
jQuery(this).next('button.copy-video__button').attr('id', buttonID);
// Associate video player with button via index
players[buttonID] = { player: null, }
// Set-up a player object for each video
players[buttonID].player = new YT.Player(iframeID, {
events: { 'onReady': onPlayerReady }
});
});
}
|
javascript
|
function onYouTubePlayerAPIReady() {
// Loop through each iframe video on the page
jQuery( "iframe.copy-video__video").each(function (index) {
// Create IDs dynamically
var iframeID = "js-copy-video-" + index;
var buttonID = "js-copy-video-" + index + "__button";
// Set IDs
jQuery(this).attr('id', iframeID);
jQuery(this).next('button.copy-video__button').attr('id', buttonID);
// Associate video player with button via index
players[buttonID] = { player: null, }
// Set-up a player object for each video
players[buttonID].player = new YT.Player(iframeID, {
events: { 'onReady': onPlayerReady }
});
});
}
|
[
"function",
"onYouTubePlayerAPIReady",
"(",
")",
"{",
"jQuery",
"(",
"\"iframe.copy-video__video\"",
")",
".",
"each",
"(",
"function",
"(",
"index",
")",
"{",
"var",
"iframeID",
"=",
"\"js-copy-video-\"",
"+",
"index",
";",
"var",
"buttonID",
"=",
"\"js-copy-video-\"",
"+",
"index",
"+",
"\"__button\"",
";",
"jQuery",
"(",
"this",
")",
".",
"attr",
"(",
"'id'",
",",
"iframeID",
")",
";",
"jQuery",
"(",
"this",
")",
".",
"next",
"(",
"'button.copy-video__button'",
")",
".",
"attr",
"(",
"'id'",
",",
"buttonID",
")",
";",
"players",
"[",
"buttonID",
"]",
"=",
"{",
"player",
":",
"null",
",",
"}",
"players",
"[",
"buttonID",
"]",
".",
"player",
"=",
"new",
"YT",
".",
"Player",
"(",
"iframeID",
",",
"{",
"events",
":",
"{",
"'onReady'",
":",
"onPlayerReady",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Only called on successful YT API load
|
[
"Only",
"called",
"on",
"successful",
"YT",
"API",
"load"
] |
ab0b6c106ce6b634ec9c1226ab93eb10c41bd9f3
|
https://github.com/comicrelief/pattern-lab/blob/ab0b6c106ce6b634ec9c1226ab93eb10c41bd9f3/sass/themes/cr/2019/components/copy-video/js/copy-video.js#L17-L37
|
train
|
ctumolosus/jsdoc-babel
|
example/src/async.js
|
getProcessedData
|
async function getProcessedData(url) {
let data;
try {
data = await downloadData(url);
} catch (error) {
data = await downloadFallbackData(url);
}
return processDataInWorker(data);
}
|
javascript
|
async function getProcessedData(url) {
let data;
try {
data = await downloadData(url);
} catch (error) {
data = await downloadFallbackData(url);
}
return processDataInWorker(data);
}
|
[
"async",
"function",
"getProcessedData",
"(",
"url",
")",
"{",
"let",
"data",
";",
"try",
"{",
"data",
"=",
"await",
"downloadData",
"(",
"url",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"data",
"=",
"await",
"downloadFallbackData",
"(",
"url",
")",
";",
"}",
"return",
"processDataInWorker",
"(",
"data",
")",
";",
"}"
] |
Downloads and processes data from specified URL
@param {String} url - Location for resource to be processed.
|
[
"Downloads",
"and",
"processes",
"data",
"from",
"specified",
"URL"
] |
f6f06815df7ae8abc9edbe8357048f80fd4184c9
|
https://github.com/ctumolosus/jsdoc-babel/blob/f6f06815df7ae8abc9edbe8357048f80fd4184c9/example/src/async.js#L5-L15
|
train
|
cultureamp/cultureamp-style-guide
|
webpack/elmSvgAssetLoader.js
|
regexpForFunctionCall
|
function regexpForFunctionCall(fnName, args) {
const optionalWhitespace = '\\s*';
const argumentParts = args.map(
arg => optionalWhitespace + arg + optionalWhitespace
);
let parts = [fnName, '\\(', argumentParts.join(','), '\\)'];
return new RegExp(parts.join(''), 'g');
}
|
javascript
|
function regexpForFunctionCall(fnName, args) {
const optionalWhitespace = '\\s*';
const argumentParts = args.map(
arg => optionalWhitespace + arg + optionalWhitespace
);
let parts = [fnName, '\\(', argumentParts.join(','), '\\)'];
return new RegExp(parts.join(''), 'g');
}
|
[
"function",
"regexpForFunctionCall",
"(",
"fnName",
",",
"args",
")",
"{",
"const",
"optionalWhitespace",
"=",
"'\\\\s*'",
";",
"\\\\",
"const",
"argumentParts",
"=",
"args",
".",
"map",
"(",
"arg",
"=>",
"optionalWhitespace",
"+",
"arg",
"+",
"optionalWhitespace",
")",
";",
"let",
"parts",
"=",
"[",
"fnName",
",",
"'\\\\('",
",",
"\\\\",
",",
"argumentParts",
".",
"join",
"(",
"','",
")",
"]",
";",
"}"
] |
Create a regular expression to match a function call.
@param fnName The name of the function being called. Can include
property access (eg `console.log`)
@param args An array of arguments we expect to find. Each of these
can be a regular expression to match the expected type of argument, and can
include capture groups.
|
[
"Create",
"a",
"regular",
"expression",
"to",
"match",
"a",
"function",
"call",
"."
] |
c06ad03bbc1e25b203199f66577fb16d135623a2
|
https://github.com/cultureamp/cultureamp-style-guide/blob/c06ad03bbc1e25b203199f66577fb16d135623a2/webpack/elmSvgAssetLoader.js#L55-L62
|
train
|
shaungrady/angular-http-etag
|
src/httpDecorator.js
|
stringifyParams
|
function stringifyParams (obj) {
return obj ? arrayMap(objectKeys(obj).sort(), function (key) {
var val = obj[key]
if (angular.isArray(val)) {
return arrayMap(val.sort(), function (val2) {
return encodeURIComponent(key) + '=' + encodeURIComponent(val2)
}).join('&')
}
return encodeURIComponent(key) + '=' + encodeURIComponent(val)
}).join('&') : ''
}
|
javascript
|
function stringifyParams (obj) {
return obj ? arrayMap(objectKeys(obj).sort(), function (key) {
var val = obj[key]
if (angular.isArray(val)) {
return arrayMap(val.sort(), function (val2) {
return encodeURIComponent(key) + '=' + encodeURIComponent(val2)
}).join('&')
}
return encodeURIComponent(key) + '=' + encodeURIComponent(val)
}).join('&') : ''
}
|
[
"function",
"stringifyParams",
"(",
"obj",
")",
"{",
"return",
"obj",
"?",
"arrayMap",
"(",
"objectKeys",
"(",
"obj",
")",
".",
"sort",
"(",
")",
",",
"function",
"(",
"key",
")",
"{",
"var",
"val",
"=",
"obj",
"[",
"key",
"]",
"if",
"(",
"angular",
".",
"isArray",
"(",
"val",
")",
")",
"{",
"return",
"arrayMap",
"(",
"val",
".",
"sort",
"(",
")",
",",
"function",
"(",
"val2",
")",
"{",
"return",
"encodeURIComponent",
"(",
"key",
")",
"+",
"'='",
"+",
"encodeURIComponent",
"(",
"val2",
")",
"}",
")",
".",
"join",
"(",
"'&'",
")",
"}",
"return",
"encodeURIComponent",
"(",
"key",
")",
"+",
"'='",
"+",
"encodeURIComponent",
"(",
"val",
")",
"}",
")",
".",
"join",
"(",
"'&'",
")",
":",
"''",
"}"
] |
Based on npm package "query-string"
|
[
"Based",
"on",
"npm",
"package",
"query",
"-",
"string"
] |
6a25b59fe5635e1f5cda04f0c4bb79c93f3a651e
|
https://github.com/shaungrady/angular-http-etag/blob/6a25b59fe5635e1f5cda04f0c4bb79c93f3a651e/src/httpDecorator.js#L179-L191
|
train
|
bcoe/thumbd
|
lib/thumbnailer.js
|
Thumbnailer
|
function Thumbnailer (opts) {
// for the benefit of testing
// perform dependency injection.
_.extend(this, {
tmp: require('tmp'),
logger: require(config.get('logger'))
}, opts)
}
|
javascript
|
function Thumbnailer (opts) {
// for the benefit of testing
// perform dependency injection.
_.extend(this, {
tmp: require('tmp'),
logger: require(config.get('logger'))
}, opts)
}
|
[
"function",
"Thumbnailer",
"(",
"opts",
")",
"{",
"_",
".",
"extend",
"(",
"this",
",",
"{",
"tmp",
":",
"require",
"(",
"'tmp'",
")",
",",
"logger",
":",
"require",
"(",
"config",
".",
"get",
"(",
"'logger'",
")",
")",
"}",
",",
"opts",
")",
"}"
] |
Initialize the Thumbnailer
|
[
"Initialize",
"the",
"Thumbnailer"
] |
9148ca81dd0a3b3b061721e6dbad2f2d41d30d07
|
https://github.com/bcoe/thumbd/blob/9148ca81dd0a3b3b061721e6dbad2f2d41d30d07/lib/thumbnailer.js#L10-L17
|
train
|
bcoe/thumbd
|
lib/worker.js
|
Worker
|
function Worker (opts) {
_.extend(this, {
grabber: null,
saver: null,
logger: require(config.get('logger'))
}, opts)
this.sqs = new aws.SQS({
accessKeyId: config.get('awsKey'),
secretAccessKey: config.get('awsSecret'),
region: config.get('awsRegion')
})
config.set('sqsQueueUrl', this.sqs.endpoint.protocol + '//' + this.sqs.endpoint.hostname + '/' + config.get('sqsQueue'))
}
|
javascript
|
function Worker (opts) {
_.extend(this, {
grabber: null,
saver: null,
logger: require(config.get('logger'))
}, opts)
this.sqs = new aws.SQS({
accessKeyId: config.get('awsKey'),
secretAccessKey: config.get('awsSecret'),
region: config.get('awsRegion')
})
config.set('sqsQueueUrl', this.sqs.endpoint.protocol + '//' + this.sqs.endpoint.hostname + '/' + config.get('sqsQueue'))
}
|
[
"function",
"Worker",
"(",
"opts",
")",
"{",
"_",
".",
"extend",
"(",
"this",
",",
"{",
"grabber",
":",
"null",
",",
"saver",
":",
"null",
",",
"logger",
":",
"require",
"(",
"config",
".",
"get",
"(",
"'logger'",
")",
")",
"}",
",",
"opts",
")",
"this",
".",
"sqs",
"=",
"new",
"aws",
".",
"SQS",
"(",
"{",
"accessKeyId",
":",
"config",
".",
"get",
"(",
"'awsKey'",
")",
",",
"secretAccessKey",
":",
"config",
".",
"get",
"(",
"'awsSecret'",
")",
",",
"region",
":",
"config",
".",
"get",
"(",
"'awsRegion'",
")",
"}",
")",
"config",
".",
"set",
"(",
"'sqsQueueUrl'",
",",
"this",
".",
"sqs",
".",
"endpoint",
".",
"protocol",
"+",
"'//'",
"+",
"this",
".",
"sqs",
".",
"endpoint",
".",
"hostname",
"+",
"'/'",
"+",
"config",
".",
"get",
"(",
"'sqsQueue'",
")",
")",
"}"
] |
Initialize the Worker
@param object opts Worker configuration. Optional.
|
[
"Initialize",
"the",
"Worker"
] |
9148ca81dd0a3b3b061721e6dbad2f2d41d30d07
|
https://github.com/bcoe/thumbd/blob/9148ca81dd0a3b3b061721e6dbad2f2d41d30d07/lib/worker.js#L14-L28
|
train
|
bcoe/thumbd
|
lib/client.js
|
Client
|
function Client (opts) {
// update client instance and config
// with overrides from opts.
_.extend(this, {
Saver: require('./saver').Saver
}, opts)
config.extend(opts)
// allow sqs to be overridden
// in tests.
if (opts && opts.sqs) {
this.sqs = opts.sqs
delete opts.sqs
} else {
this.sqs = new aws.SQS({
accessKeyId: config.get('awsKey'),
secretAccessKey: config.get('awsSecret'),
region: config.get('awsRegion')
})
}
config.set('sqsQueueUrl', this.sqs.endpoint.protocol + '//' + this.sqs.endpoint.hostname + '/' + config.get('sqsQueue'))
}
|
javascript
|
function Client (opts) {
// update client instance and config
// with overrides from opts.
_.extend(this, {
Saver: require('./saver').Saver
}, opts)
config.extend(opts)
// allow sqs to be overridden
// in tests.
if (opts && opts.sqs) {
this.sqs = opts.sqs
delete opts.sqs
} else {
this.sqs = new aws.SQS({
accessKeyId: config.get('awsKey'),
secretAccessKey: config.get('awsSecret'),
region: config.get('awsRegion')
})
}
config.set('sqsQueueUrl', this.sqs.endpoint.protocol + '//' + this.sqs.endpoint.hostname + '/' + config.get('sqsQueue'))
}
|
[
"function",
"Client",
"(",
"opts",
")",
"{",
"_",
".",
"extend",
"(",
"this",
",",
"{",
"Saver",
":",
"require",
"(",
"'./saver'",
")",
".",
"Saver",
"}",
",",
"opts",
")",
"config",
".",
"extend",
"(",
"opts",
")",
"if",
"(",
"opts",
"&&",
"opts",
".",
"sqs",
")",
"{",
"this",
".",
"sqs",
"=",
"opts",
".",
"sqs",
"delete",
"opts",
".",
"sqs",
"}",
"else",
"{",
"this",
".",
"sqs",
"=",
"new",
"aws",
".",
"SQS",
"(",
"{",
"accessKeyId",
":",
"config",
".",
"get",
"(",
"'awsKey'",
")",
",",
"secretAccessKey",
":",
"config",
".",
"get",
"(",
"'awsSecret'",
")",
",",
"region",
":",
"config",
".",
"get",
"(",
"'awsRegion'",
")",
"}",
")",
"}",
"config",
".",
"set",
"(",
"'sqsQueueUrl'",
",",
"this",
".",
"sqs",
".",
"endpoint",
".",
"protocol",
"+",
"'//'",
"+",
"this",
".",
"sqs",
".",
"endpoint",
".",
"hostname",
"+",
"'/'",
"+",
"config",
".",
"get",
"(",
"'sqsQueue'",
")",
")",
"}"
] |
Initialize the Client
@param object opts The Client options
|
[
"Initialize",
"the",
"Client"
] |
9148ca81dd0a3b3b061721e6dbad2f2d41d30d07
|
https://github.com/bcoe/thumbd/blob/9148ca81dd0a3b3b061721e6dbad2f2d41d30d07/lib/client.js#L10-L33
|
train
|
bcoe/thumbd
|
bin/thumbd.js
|
buildOpts
|
function buildOpts (keys) {
var opts = {}
var pairs = _.pairs(keys)
for (var i in pairs) {
var argvKey = pairs[i][0]
var envKey = argvKey.toUpperCase()
var configKey = pairs[i][1]
opts[configKey] = argv[argvKey] || config.get(configKey)
if (opts[configKey] === null) {
throw Error("The environment variable '" + envKey + "', or command line parameter '--" + argvKey + "' must be set.")
}
}
return opts
}
|
javascript
|
function buildOpts (keys) {
var opts = {}
var pairs = _.pairs(keys)
for (var i in pairs) {
var argvKey = pairs[i][0]
var envKey = argvKey.toUpperCase()
var configKey = pairs[i][1]
opts[configKey] = argv[argvKey] || config.get(configKey)
if (opts[configKey] === null) {
throw Error("The environment variable '" + envKey + "', or command line parameter '--" + argvKey + "' must be set.")
}
}
return opts
}
|
[
"function",
"buildOpts",
"(",
"keys",
")",
"{",
"var",
"opts",
"=",
"{",
"}",
"var",
"pairs",
"=",
"_",
".",
"pairs",
"(",
"keys",
")",
"for",
"(",
"var",
"i",
"in",
"pairs",
")",
"{",
"var",
"argvKey",
"=",
"pairs",
"[",
"i",
"]",
"[",
"0",
"]",
"var",
"envKey",
"=",
"argvKey",
".",
"toUpperCase",
"(",
")",
"var",
"configKey",
"=",
"pairs",
"[",
"i",
"]",
"[",
"1",
"]",
"opts",
"[",
"configKey",
"]",
"=",
"argv",
"[",
"argvKey",
"]",
"||",
"config",
".",
"get",
"(",
"configKey",
")",
"if",
"(",
"opts",
"[",
"configKey",
"]",
"===",
"null",
")",
"{",
"throw",
"Error",
"(",
"\"The environment variable '\"",
"+",
"envKey",
"+",
"\"', or command line parameter '--\"",
"+",
"argvKey",
"+",
"\"' must be set.\"",
")",
"}",
"}",
"return",
"opts",
"}"
] |
Extract the command line parameters
@param object keys A mapping of cli option => config key names
@return object
|
[
"Extract",
"the",
"command",
"line",
"parameters"
] |
9148ca81dd0a3b3b061721e6dbad2f2d41d30d07
|
https://github.com/bcoe/thumbd/blob/9148ca81dd0a3b3b061721e6dbad2f2d41d30d07/bin/thumbd.js#L130-L143
|
train
|
facebookarchive/react-page-middleware
|
src/SymbolicLinkFinder.js
|
SymbolicLinkFinder
|
function SymbolicLinkFinder(options) {
this.scanDirs = options && options.scanDirs || ['.'];
this.extensions = options && options.extensions || ['.js'];
this.ignore = options && options.ignore || null;
}
|
javascript
|
function SymbolicLinkFinder(options) {
this.scanDirs = options && options.scanDirs || ['.'];
this.extensions = options && options.extensions || ['.js'];
this.ignore = options && options.ignore || null;
}
|
[
"function",
"SymbolicLinkFinder",
"(",
"options",
")",
"{",
"this",
".",
"scanDirs",
"=",
"options",
"&&",
"options",
".",
"scanDirs",
"||",
"[",
"'.'",
"]",
";",
"this",
".",
"extensions",
"=",
"options",
"&&",
"options",
".",
"extensions",
"||",
"[",
"'.js'",
"]",
";",
"this",
".",
"ignore",
"=",
"options",
"&&",
"options",
".",
"ignore",
"||",
"null",
";",
"}"
] |
Wrapper for options for a find call
@class
@param {Object} options
|
[
"Wrapper",
"for",
"options",
"for",
"a",
"find",
"call"
] |
4f4db543db07cb40490e7f003c7de2190e5ab7d0
|
https://github.com/facebookarchive/react-page-middleware/blob/4f4db543db07cb40490e7f003c7de2190e5ab7d0/src/SymbolicLinkFinder.js#L86-L90
|
train
|
facebookarchive/react-page-middleware
|
src/Packager.js
|
function(buildConfig, path) {
ensureBlacklistsComputed(buildConfig);
var buildConfigBlacklistRE = buildConfig.blacklistRE;
var internalDependenciesBlacklistRE = buildConfig._reactPageBlacklistRE;
if (BLACKLIST_FILE_EXTS_RE.test(path) ||
buildConfig._middlewareBlacklistRE.test(path) ||
internalDependenciesBlacklistRE.test(path) ||
buildConfigBlacklistRE && buildConfigBlacklistRE.test(path) ||
buildConfig.ignorePaths && buildConfig.ignorePaths(path)) {
return true;
}
return false;
}
|
javascript
|
function(buildConfig, path) {
ensureBlacklistsComputed(buildConfig);
var buildConfigBlacklistRE = buildConfig.blacklistRE;
var internalDependenciesBlacklistRE = buildConfig._reactPageBlacklistRE;
if (BLACKLIST_FILE_EXTS_RE.test(path) ||
buildConfig._middlewareBlacklistRE.test(path) ||
internalDependenciesBlacklistRE.test(path) ||
buildConfigBlacklistRE && buildConfigBlacklistRE.test(path) ||
buildConfig.ignorePaths && buildConfig.ignorePaths(path)) {
return true;
}
return false;
}
|
[
"function",
"(",
"buildConfig",
",",
"path",
")",
"{",
"ensureBlacklistsComputed",
"(",
"buildConfig",
")",
";",
"var",
"buildConfigBlacklistRE",
"=",
"buildConfig",
".",
"blacklistRE",
";",
"var",
"internalDependenciesBlacklistRE",
"=",
"buildConfig",
".",
"_reactPageBlacklistRE",
";",
"if",
"(",
"BLACKLIST_FILE_EXTS_RE",
".",
"test",
"(",
"path",
")",
"||",
"buildConfig",
".",
"_middlewareBlacklistRE",
".",
"test",
"(",
"path",
")",
"||",
"internalDependenciesBlacklistRE",
".",
"test",
"(",
"path",
")",
"||",
"buildConfigBlacklistRE",
"&&",
"buildConfigBlacklistRE",
".",
"test",
"(",
"path",
")",
"||",
"buildConfig",
".",
"ignorePaths",
"&&",
"buildConfig",
".",
"ignorePaths",
"(",
"path",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
The `react-page` `projectRoot` is the search root. By default, everything
under it is inherently whitelisted. The user may black list certain
directories under it. They should be careful not to blacklist the
`browser-builtins` in `react-page-middleware`.
We ignore any directory that is, or is *inside* of a black listed path.
@param {object} buildConfig React-page build config.
@param {string} path Absolute path in question.
@return {boolean} Whether or not path should be ignored.
|
[
"The",
"react",
"-",
"page",
"projectRoot",
"is",
"the",
"search",
"root",
".",
"By",
"default",
"everything",
"under",
"it",
"is",
"inherently",
"whitelisted",
".",
"The",
"user",
"may",
"black",
"list",
"certain",
"directories",
"under",
"it",
".",
"They",
"should",
"be",
"careful",
"not",
"to",
"blacklist",
"the",
"browser",
"-",
"builtins",
"in",
"react",
"-",
"page",
"-",
"middleware",
"."
] |
4f4db543db07cb40490e7f003c7de2190e5ab7d0
|
https://github.com/facebookarchive/react-page-middleware/blob/4f4db543db07cb40490e7f003c7de2190e5ab7d0/src/Packager.js#L138-L150
|
train
|
|
facebookarchive/react-page-middleware
|
polyfill/require.js
|
requireLazy
|
function requireLazy(dependencies, factory, context) {
return define(
dependencies,
factory,
undefined,
REQUIRE_WHEN_READY,
context,
1
);
}
|
javascript
|
function requireLazy(dependencies, factory, context) {
return define(
dependencies,
factory,
undefined,
REQUIRE_WHEN_READY,
context,
1
);
}
|
[
"function",
"requireLazy",
"(",
"dependencies",
",",
"factory",
",",
"context",
")",
"{",
"return",
"define",
"(",
"dependencies",
",",
"factory",
",",
"undefined",
",",
"REQUIRE_WHEN_READY",
",",
"context",
",",
"1",
")",
";",
"}"
] |
Special version of define that executes the factory as soon as all
dependencies are met.
define() does just that, defines a module. Module's factory will not be
called until required by other module. This makes sense for most of our
library modules: we do not want to execute the factory unless it's being
used by someone.
On the other hand there are modules, that you can call "entrance points".
You want to run the "factory" method for them as soon as all dependencies
are met.
@example
define('BaseClass', [], function() { return ... });
// ^^ factory for BaseClass was just stored in modulesMap
define('SubClass', ['BaseClass'], function() { ... });
// SubClass module is marked as ready (waiting == 0), factory is just
// stored
define('OtherClass, ['BaseClass'], function() { ... });
// OtherClass module is marked as ready (waiting == 0), factory is just
// stored
requireLazy(['SubClass', 'ChatConfig'],
function() { ... });
// ChatRunner is waiting for ChatConfig to come
define('ChatConfig', [], { foo: 'bar' });
// at this point ChatRunner is marked as ready, and its factory
// executed + all dependent factories are executed too: BaseClass,
// SubClass, ChatConfig notice that OtherClass's factory won't be
// executed unless explicitly required by someone
@param {Array} dependencies
@param {Object|Function} factory
|
[
"Special",
"version",
"of",
"define",
"that",
"executes",
"the",
"factory",
"as",
"soon",
"as",
"all",
"dependencies",
"are",
"met",
"."
] |
4f4db543db07cb40490e7f003c7de2190e5ab7d0
|
https://github.com/facebookarchive/react-page-middleware/blob/4f4db543db07cb40490e7f003c7de2190e5ab7d0/polyfill/require.js#L459-L468
|
train
|
facebookarchive/react-page-middleware
|
polyfill/require.js
|
function(id, deps, factory, _special) {
define(id, deps, factory, _special || USED_AS_TRANSPORT);
}
|
javascript
|
function(id, deps, factory, _special) {
define(id, deps, factory, _special || USED_AS_TRANSPORT);
}
|
[
"function",
"(",
"id",
",",
"deps",
",",
"factory",
",",
"_special",
")",
"{",
"define",
"(",
"id",
",",
"deps",
",",
"factory",
",",
"_special",
"||",
"USED_AS_TRANSPORT",
")",
";",
"}"
] |
shortcuts for haste transport
|
[
"shortcuts",
"for",
"haste",
"transport"
] |
4f4db543db07cb40490e7f003c7de2190e5ab7d0
|
https://github.com/facebookarchive/react-page-middleware/blob/4f4db543db07cb40490e7f003c7de2190e5ab7d0/polyfill/require.js#L561-L563
|
train
|
|
adopted-ember-addons/ember-cli-hot-loader
|
addon/utils/clear-requirejs.js
|
requireUnsee
|
function requireUnsee(module) {
if (window.requirejs.has(module)) {
window.requirejs.unsee(module);
}
}
|
javascript
|
function requireUnsee(module) {
if (window.requirejs.has(module)) {
window.requirejs.unsee(module);
}
}
|
[
"function",
"requireUnsee",
"(",
"module",
")",
"{",
"if",
"(",
"window",
".",
"requirejs",
".",
"has",
"(",
"module",
")",
")",
"{",
"window",
".",
"requirejs",
".",
"unsee",
"(",
"module",
")",
";",
"}",
"}"
] |
Unsee a requirejs module if it exists
@param {String} module The requirejs module name
|
[
"Unsee",
"a",
"requirejs",
"module",
"if",
"it",
"exists"
] |
bd47bb5b90a39a5ecf1a8c0a4f0794152f053025
|
https://github.com/adopted-ember-addons/ember-cli-hot-loader/blob/bd47bb5b90a39a5ecf1a8c0a4f0794152f053025/addon/utils/clear-requirejs.js#L8-L12
|
train
|
tilemill-project/millstone
|
lib/util.js
|
rm
|
function rm(filepath, callback) {
var killswitch = false;
fs.stat(filepath, function(err, stat) {
if (err) return callback(err);
if (stat.isFile()) return fs.unlink(filepath, callback);
if (!stat.isDirectory()) return callback(new Error('Unrecognized file.'));
Step(function() {
fs.readdir(filepath, this);
},
function(err, files) {
if (err) throw err;
if (files.length === 0) return this(null, []);
var group = this.group();
_(files).each(function(file) {
rm(path.join(filepath, file), group());
});
},
function(err) {
if (err) return callback(err);
fs.rmdir(filepath, callback);
});
});
}
|
javascript
|
function rm(filepath, callback) {
var killswitch = false;
fs.stat(filepath, function(err, stat) {
if (err) return callback(err);
if (stat.isFile()) return fs.unlink(filepath, callback);
if (!stat.isDirectory()) return callback(new Error('Unrecognized file.'));
Step(function() {
fs.readdir(filepath, this);
},
function(err, files) {
if (err) throw err;
if (files.length === 0) return this(null, []);
var group = this.group();
_(files).each(function(file) {
rm(path.join(filepath, file), group());
});
},
function(err) {
if (err) return callback(err);
fs.rmdir(filepath, callback);
});
});
}
|
[
"function",
"rm",
"(",
"filepath",
",",
"callback",
")",
"{",
"var",
"killswitch",
"=",
"false",
";",
"fs",
".",
"stat",
"(",
"filepath",
",",
"function",
"(",
"err",
",",
"stat",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"if",
"(",
"stat",
".",
"isFile",
"(",
")",
")",
"return",
"fs",
".",
"unlink",
"(",
"filepath",
",",
"callback",
")",
";",
"if",
"(",
"!",
"stat",
".",
"isDirectory",
"(",
")",
")",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'Unrecognized file.'",
")",
")",
";",
"Step",
"(",
"function",
"(",
")",
"{",
"fs",
".",
"readdir",
"(",
"filepath",
",",
"this",
")",
";",
"}",
",",
"function",
"(",
"err",
",",
"files",
")",
"{",
"if",
"(",
"err",
")",
"throw",
"err",
";",
"if",
"(",
"files",
".",
"length",
"===",
"0",
")",
"return",
"this",
"(",
"null",
",",
"[",
"]",
")",
";",
"var",
"group",
"=",
"this",
".",
"group",
"(",
")",
";",
"_",
"(",
"files",
")",
".",
"each",
"(",
"function",
"(",
"file",
")",
"{",
"rm",
"(",
"path",
".",
"join",
"(",
"filepath",
",",
"file",
")",
",",
"group",
"(",
")",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"fs",
".",
"rmdir",
"(",
"filepath",
",",
"callback",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Recursive rm.
|
[
"Recursive",
"rm",
"."
] |
7440d62881c5e95fe30138d3e07baeb931d97b51
|
https://github.com/tilemill-project/millstone/blob/7440d62881c5e95fe30138d3e07baeb931d97b51/lib/util.js#L9-L31
|
train
|
tilemill-project/millstone
|
lib/util.js
|
forcelink
|
function forcelink(src, dest, options, callback) {
if (!options || !options.cache) throw new Error('options.cache not defined!');
if (!callback) throw new Error('callback not defined!');
// uses relative path if linking to cache dir
if (path.relative) {
src = path.relative(options.cache, dest).slice(0, 2) !== '..' ? path.relative(path.dirname(dest), src) : src;
}
fs.lstat(dest, function(err, stat) {
// Error.
if (err && err.code !== 'ENOENT') {
return callback(err);
}
// Path does not exist. Symlink.
if (err && err.code === 'ENOENT') {
if (env == 'development') console.error("[millstone] linking '" + dest + "' -> '" + src + "'");
return fs.symlink(src, dest, callback);
}
// Path exists and is not a symlink. Do nothing.
if (!stat.isSymbolicLink()) {
if (env == 'development') console.error("[millstone] skipping re-linking '" + src + "' because '" + dest + " is already an existing file");
return callback();
}
// Path exists and is a symlink. Check existing link path and update if necessary.
// NOTE : broken symlinks will pass through this step
fs.readlink(dest, function(err, old) {
if (err) return callback(err);
if (old === src) return callback();
fs.unlink(dest, function(err) {
if (err) return callback(err);
if (env == 'development') console.error("[millstone] re-linking '" + dest + "' -> '" + src + "'");
fs.symlink(src, dest, callback);
});
});
});
}
|
javascript
|
function forcelink(src, dest, options, callback) {
if (!options || !options.cache) throw new Error('options.cache not defined!');
if (!callback) throw new Error('callback not defined!');
// uses relative path if linking to cache dir
if (path.relative) {
src = path.relative(options.cache, dest).slice(0, 2) !== '..' ? path.relative(path.dirname(dest), src) : src;
}
fs.lstat(dest, function(err, stat) {
// Error.
if (err && err.code !== 'ENOENT') {
return callback(err);
}
// Path does not exist. Symlink.
if (err && err.code === 'ENOENT') {
if (env == 'development') console.error("[millstone] linking '" + dest + "' -> '" + src + "'");
return fs.symlink(src, dest, callback);
}
// Path exists and is not a symlink. Do nothing.
if (!stat.isSymbolicLink()) {
if (env == 'development') console.error("[millstone] skipping re-linking '" + src + "' because '" + dest + " is already an existing file");
return callback();
}
// Path exists and is a symlink. Check existing link path and update if necessary.
// NOTE : broken symlinks will pass through this step
fs.readlink(dest, function(err, old) {
if (err) return callback(err);
if (old === src) return callback();
fs.unlink(dest, function(err) {
if (err) return callback(err);
if (env == 'development') console.error("[millstone] re-linking '" + dest + "' -> '" + src + "'");
fs.symlink(src, dest, callback);
});
});
});
}
|
[
"function",
"forcelink",
"(",
"src",
",",
"dest",
",",
"options",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"options",
"||",
"!",
"options",
".",
"cache",
")",
"throw",
"new",
"Error",
"(",
"'options.cache not defined!'",
")",
";",
"if",
"(",
"!",
"callback",
")",
"throw",
"new",
"Error",
"(",
"'callback not defined!'",
")",
";",
"if",
"(",
"path",
".",
"relative",
")",
"{",
"src",
"=",
"path",
".",
"relative",
"(",
"options",
".",
"cache",
",",
"dest",
")",
".",
"slice",
"(",
"0",
",",
"2",
")",
"!==",
"'..'",
"?",
"path",
".",
"relative",
"(",
"path",
".",
"dirname",
"(",
"dest",
")",
",",
"src",
")",
":",
"src",
";",
"}",
"fs",
".",
"lstat",
"(",
"dest",
",",
"function",
"(",
"err",
",",
"stat",
")",
"{",
"if",
"(",
"err",
"&&",
"err",
".",
"code",
"!==",
"'ENOENT'",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"if",
"(",
"err",
"&&",
"err",
".",
"code",
"===",
"'ENOENT'",
")",
"{",
"if",
"(",
"env",
"==",
"'development'",
")",
"console",
".",
"error",
"(",
"\"[millstone] linking '\"",
"+",
"dest",
"+",
"\"' -> '\"",
"+",
"src",
"+",
"\"'\"",
")",
";",
"return",
"fs",
".",
"symlink",
"(",
"src",
",",
"dest",
",",
"callback",
")",
";",
"}",
"if",
"(",
"!",
"stat",
".",
"isSymbolicLink",
"(",
")",
")",
"{",
"if",
"(",
"env",
"==",
"'development'",
")",
"console",
".",
"error",
"(",
"\"[millstone] skipping re-linking '\"",
"+",
"src",
"+",
"\"' because '\"",
"+",
"dest",
"+",
"\" is already an existing file\"",
")",
";",
"return",
"callback",
"(",
")",
";",
"}",
"fs",
".",
"readlink",
"(",
"dest",
",",
"function",
"(",
"err",
",",
"old",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"if",
"(",
"old",
"===",
"src",
")",
"return",
"callback",
"(",
")",
";",
"fs",
".",
"unlink",
"(",
"dest",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"if",
"(",
"env",
"==",
"'development'",
")",
"console",
".",
"error",
"(",
"\"[millstone] re-linking '\"",
"+",
"dest",
"+",
"\"' -> '\"",
"+",
"src",
"+",
"\"'\"",
")",
";",
"fs",
".",
"symlink",
"(",
"src",
",",
"dest",
",",
"callback",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Like fs.symlink except that it will overwrite stale symlinks at the given path if it exists.
|
[
"Like",
"fs",
".",
"symlink",
"except",
"that",
"it",
"will",
"overwrite",
"stale",
"symlinks",
"at",
"the",
"given",
"path",
"if",
"it",
"exists",
"."
] |
7440d62881c5e95fe30138d3e07baeb931d97b51
|
https://github.com/tilemill-project/millstone/blob/7440d62881c5e95fe30138d3e07baeb931d97b51/lib/util.js#L35-L72
|
train
|
tilemill-project/millstone
|
lib/millstone.js
|
localize
|
function localize(url, options, callback) {
existsAsync(options.filepath, function(exists) {
if (exists) {
var re_download = false;
// unideal workaround for frequently corrupt/partially downloaded zips
// https://github.com/mapbox/millstone/issues/85
if (path.extname(options.filepath) == '.zip') {
try {
var zf = new zipfile.ZipFile(options.filepath);
if (zf.names.length < 1) {
throw new Error("could not find any valid data in zip archive: '" + options.filepath + "'");
}
} catch (e) {
if (env == 'development') console.error('[millstone] could not open zip archive: "' + options.filepath + '" attempting to re-download from "'+url+"'");
re_download = true;
}
}
if (!re_download) {
return callback(null, options.filepath);
}
}
var dir_path = path.dirname(options.filepath);
mkdirp(dir_path, 0755, function(err) {
if (err && err.code !== 'EEXIST') {
if (env == 'development') console.error('[millstone] could not create directory: ' + dir_path);
callback(err);
} else {
download(url, options, function(err, filepath) {
if (err) return callback(err);
callback(null, filepath);
});
}
});
});
}
|
javascript
|
function localize(url, options, callback) {
existsAsync(options.filepath, function(exists) {
if (exists) {
var re_download = false;
// unideal workaround for frequently corrupt/partially downloaded zips
// https://github.com/mapbox/millstone/issues/85
if (path.extname(options.filepath) == '.zip') {
try {
var zf = new zipfile.ZipFile(options.filepath);
if (zf.names.length < 1) {
throw new Error("could not find any valid data in zip archive: '" + options.filepath + "'");
}
} catch (e) {
if (env == 'development') console.error('[millstone] could not open zip archive: "' + options.filepath + '" attempting to re-download from "'+url+"'");
re_download = true;
}
}
if (!re_download) {
return callback(null, options.filepath);
}
}
var dir_path = path.dirname(options.filepath);
mkdirp(dir_path, 0755, function(err) {
if (err && err.code !== 'EEXIST') {
if (env == 'development') console.error('[millstone] could not create directory: ' + dir_path);
callback(err);
} else {
download(url, options, function(err, filepath) {
if (err) return callback(err);
callback(null, filepath);
});
}
});
});
}
|
[
"function",
"localize",
"(",
"url",
",",
"options",
",",
"callback",
")",
"{",
"existsAsync",
"(",
"options",
".",
"filepath",
",",
"function",
"(",
"exists",
")",
"{",
"if",
"(",
"exists",
")",
"{",
"var",
"re_download",
"=",
"false",
";",
"if",
"(",
"path",
".",
"extname",
"(",
"options",
".",
"filepath",
")",
"==",
"'.zip'",
")",
"{",
"try",
"{",
"var",
"zf",
"=",
"new",
"zipfile",
".",
"ZipFile",
"(",
"options",
".",
"filepath",
")",
";",
"if",
"(",
"zf",
".",
"names",
".",
"length",
"<",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"could not find any valid data in zip archive: '\"",
"+",
"options",
".",
"filepath",
"+",
"\"'\"",
")",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"env",
"==",
"'development'",
")",
"console",
".",
"error",
"(",
"'[millstone] could not open zip archive: \"'",
"+",
"options",
".",
"filepath",
"+",
"'\" attempting to re-download from \"'",
"+",
"url",
"+",
"\"'\"",
")",
";",
"re_download",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"!",
"re_download",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"options",
".",
"filepath",
")",
";",
"}",
"}",
"var",
"dir_path",
"=",
"path",
".",
"dirname",
"(",
"options",
".",
"filepath",
")",
";",
"mkdirp",
"(",
"dir_path",
",",
"0755",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
"&&",
"err",
".",
"code",
"!==",
"'EEXIST'",
")",
"{",
"if",
"(",
"env",
"==",
"'development'",
")",
"console",
".",
"error",
"(",
"'[millstone] could not create directory: '",
"+",
"dir_path",
")",
";",
"callback",
"(",
"err",
")",
";",
"}",
"else",
"{",
"download",
"(",
"url",
",",
"options",
",",
"function",
"(",
"err",
",",
"filepath",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"callback",
"(",
"null",
",",
"filepath",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Retrieve a remote copy of a resource only if we don't already have it.
|
[
"Retrieve",
"a",
"remote",
"copy",
"of",
"a",
"resource",
"only",
"if",
"we",
"don",
"t",
"already",
"have",
"it",
"."
] |
7440d62881c5e95fe30138d3e07baeb931d97b51
|
https://github.com/tilemill-project/millstone/blob/7440d62881c5e95fe30138d3e07baeb931d97b51/lib/millstone.js#L191-L225
|
train
|
tilemill-project/millstone
|
lib/millstone.js
|
cachepath
|
function cachepath(location) {
var uri = url.parse(location);
if (!uri.protocol) {
throw new Error('Invalid URL: ' + location);
} else {
var hash = crypto.createHash('md5')
.update(location)
.digest('hex')
.substr(0,8) +
'-' + path.basename(uri.pathname, path.extname(uri.pathname));
var extname = path.extname(uri.pathname);
return _(['.shp', '.zip', '']).include(extname.toLowerCase()) ?
path.join(hash, hash + extname)
: path.join(hash + extname);
}
}
|
javascript
|
function cachepath(location) {
var uri = url.parse(location);
if (!uri.protocol) {
throw new Error('Invalid URL: ' + location);
} else {
var hash = crypto.createHash('md5')
.update(location)
.digest('hex')
.substr(0,8) +
'-' + path.basename(uri.pathname, path.extname(uri.pathname));
var extname = path.extname(uri.pathname);
return _(['.shp', '.zip', '']).include(extname.toLowerCase()) ?
path.join(hash, hash + extname)
: path.join(hash + extname);
}
}
|
[
"function",
"cachepath",
"(",
"location",
")",
"{",
"var",
"uri",
"=",
"url",
".",
"parse",
"(",
"location",
")",
";",
"if",
"(",
"!",
"uri",
".",
"protocol",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid URL: '",
"+",
"location",
")",
";",
"}",
"else",
"{",
"var",
"hash",
"=",
"crypto",
".",
"createHash",
"(",
"'md5'",
")",
".",
"update",
"(",
"location",
")",
".",
"digest",
"(",
"'hex'",
")",
".",
"substr",
"(",
"0",
",",
"8",
")",
"+",
"'-'",
"+",
"path",
".",
"basename",
"(",
"uri",
".",
"pathname",
",",
"path",
".",
"extname",
"(",
"uri",
".",
"pathname",
")",
")",
";",
"var",
"extname",
"=",
"path",
".",
"extname",
"(",
"uri",
".",
"pathname",
")",
";",
"return",
"_",
"(",
"[",
"'.shp'",
",",
"'.zip'",
",",
"''",
"]",
")",
".",
"include",
"(",
"extname",
".",
"toLowerCase",
"(",
")",
")",
"?",
"path",
".",
"join",
"(",
"hash",
",",
"hash",
"+",
"extname",
")",
":",
"path",
".",
"join",
"(",
"hash",
"+",
"extname",
")",
";",
"}",
"}"
] |
Generate the cache path for a given URL.
|
[
"Generate",
"the",
"cache",
"path",
"for",
"a",
"given",
"URL",
"."
] |
7440d62881c5e95fe30138d3e07baeb931d97b51
|
https://github.com/tilemill-project/millstone/blob/7440d62881c5e95fe30138d3e07baeb931d97b51/lib/millstone.js#L228-L243
|
train
|
tilemill-project/millstone
|
lib/millstone.js
|
metapath
|
function metapath(filepath) {
return path.join(path.dirname(filepath), '.' + path.basename(filepath));
}
|
javascript
|
function metapath(filepath) {
return path.join(path.dirname(filepath), '.' + path.basename(filepath));
}
|
[
"function",
"metapath",
"(",
"filepath",
")",
"{",
"return",
"path",
".",
"join",
"(",
"path",
".",
"dirname",
"(",
"filepath",
")",
",",
"'.'",
"+",
"path",
".",
"basename",
"(",
"filepath",
")",
")",
";",
"}"
] |
Determine the path for a files dotfile.
|
[
"Determine",
"the",
"path",
"for",
"a",
"files",
"dotfile",
"."
] |
7440d62881c5e95fe30138d3e07baeb931d97b51
|
https://github.com/tilemill-project/millstone/blob/7440d62881c5e95fe30138d3e07baeb931d97b51/lib/millstone.js#L246-L248
|
train
|
tilemill-project/millstone
|
lib/millstone.js
|
readExtension
|
function readExtension(file, cb) {
fs.readFile(metapath(file), 'utf-8', function(err, data) {
if (err) {
if (err.code === 'ENOENT') return cb(new Error('Metadata file does not exist.'));
return cb(err);
}
try {
var ext = guessExtension(JSON.parse(data));
if (ext) {
if (env == 'development') console.error("[millstone] detected extension of '" + ext + "' for '" + file + "'");
}
return cb(null, ext);
} catch (e) {
return cb(e);
}
});
}
|
javascript
|
function readExtension(file, cb) {
fs.readFile(metapath(file), 'utf-8', function(err, data) {
if (err) {
if (err.code === 'ENOENT') return cb(new Error('Metadata file does not exist.'));
return cb(err);
}
try {
var ext = guessExtension(JSON.parse(data));
if (ext) {
if (env == 'development') console.error("[millstone] detected extension of '" + ext + "' for '" + file + "'");
}
return cb(null, ext);
} catch (e) {
return cb(e);
}
});
}
|
[
"function",
"readExtension",
"(",
"file",
",",
"cb",
")",
"{",
"fs",
".",
"readFile",
"(",
"metapath",
"(",
"file",
")",
",",
"'utf-8'",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"code",
"===",
"'ENOENT'",
")",
"return",
"cb",
"(",
"new",
"Error",
"(",
"'Metadata file does not exist.'",
")",
")",
";",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"try",
"{",
"var",
"ext",
"=",
"guessExtension",
"(",
"JSON",
".",
"parse",
"(",
"data",
")",
")",
";",
"if",
"(",
"ext",
")",
"{",
"if",
"(",
"env",
"==",
"'development'",
")",
"console",
".",
"error",
"(",
"\"[millstone] detected extension of '\"",
"+",
"ext",
"+",
"\"' for '\"",
"+",
"file",
"+",
"\"'\"",
")",
";",
"}",
"return",
"cb",
"(",
"null",
",",
"ext",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"cb",
"(",
"e",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Read headers and guess extension
|
[
"Read",
"headers",
"and",
"guess",
"extension"
] |
7440d62881c5e95fe30138d3e07baeb931d97b51
|
https://github.com/tilemill-project/millstone/blob/7440d62881c5e95fe30138d3e07baeb931d97b51/lib/millstone.js#L328-L344
|
train
|
tilemill-project/millstone
|
lib/millstone.js
|
fixSRS
|
function fixSRS(obj) {
if (!obj.srs) return;
var normalized = _(obj.srs.split(' ')).chain()
.select(function(s) { return s.indexOf('=') > 0; })
.sortBy(function(s) { return s; })
.reduce(function(memo, s) {
var key = s.split('=')[0];
var val = s.split('=')[1];
if (val === '0') val = '0.0';
memo[key] = val;
return memo;
}, {})
.value();
var legacy = {
'+a': '6378137',
'+b': '6378137',
'+lat_ts': '0.0',
'+lon_0': '0.0',
'+proj': 'merc',
'+units': 'm',
'+x_0': '0.0',
'+y_0': '0.0'
};
if (!_(legacy).chain()
.reject(function(v, k) { return normalized[k] === v; })
.size()
.value()) obj.srs = SRS['900913'];
}
|
javascript
|
function fixSRS(obj) {
if (!obj.srs) return;
var normalized = _(obj.srs.split(' ')).chain()
.select(function(s) { return s.indexOf('=') > 0; })
.sortBy(function(s) { return s; })
.reduce(function(memo, s) {
var key = s.split('=')[0];
var val = s.split('=')[1];
if (val === '0') val = '0.0';
memo[key] = val;
return memo;
}, {})
.value();
var legacy = {
'+a': '6378137',
'+b': '6378137',
'+lat_ts': '0.0',
'+lon_0': '0.0',
'+proj': 'merc',
'+units': 'm',
'+x_0': '0.0',
'+y_0': '0.0'
};
if (!_(legacy).chain()
.reject(function(v, k) { return normalized[k] === v; })
.size()
.value()) obj.srs = SRS['900913'];
}
|
[
"function",
"fixSRS",
"(",
"obj",
")",
"{",
"if",
"(",
"!",
"obj",
".",
"srs",
")",
"return",
";",
"var",
"normalized",
"=",
"_",
"(",
"obj",
".",
"srs",
".",
"split",
"(",
"' '",
")",
")",
".",
"chain",
"(",
")",
".",
"select",
"(",
"function",
"(",
"s",
")",
"{",
"return",
"s",
".",
"indexOf",
"(",
"'='",
")",
">",
"0",
";",
"}",
")",
".",
"sortBy",
"(",
"function",
"(",
"s",
")",
"{",
"return",
"s",
";",
"}",
")",
".",
"reduce",
"(",
"function",
"(",
"memo",
",",
"s",
")",
"{",
"var",
"key",
"=",
"s",
".",
"split",
"(",
"'='",
")",
"[",
"0",
"]",
";",
"var",
"val",
"=",
"s",
".",
"split",
"(",
"'='",
")",
"[",
"1",
"]",
";",
"if",
"(",
"val",
"===",
"'0'",
")",
"val",
"=",
"'0.0'",
";",
"memo",
"[",
"key",
"]",
"=",
"val",
";",
"return",
"memo",
";",
"}",
",",
"{",
"}",
")",
".",
"value",
"(",
")",
";",
"var",
"legacy",
"=",
"{",
"'+a'",
":",
"'6378137'",
",",
"'+b'",
":",
"'6378137'",
",",
"'+lat_ts'",
":",
"'0.0'",
",",
"'+lon_0'",
":",
"'0.0'",
",",
"'+proj'",
":",
"'merc'",
",",
"'+units'",
":",
"'m'",
",",
"'+x_0'",
":",
"'0.0'",
",",
"'+y_0'",
":",
"'0.0'",
"}",
";",
"if",
"(",
"!",
"_",
"(",
"legacy",
")",
".",
"chain",
"(",
")",
".",
"reject",
"(",
"function",
"(",
"v",
",",
"k",
")",
"{",
"return",
"normalized",
"[",
"k",
"]",
"===",
"v",
";",
"}",
")",
".",
"size",
"(",
")",
".",
"value",
"(",
")",
")",
"obj",
".",
"srs",
"=",
"SRS",
"[",
"'900913'",
"]",
";",
"}"
] |
Fix known bad SRS strings to good ones.
|
[
"Fix",
"known",
"bad",
"SRS",
"strings",
"to",
"good",
"ones",
"."
] |
7440d62881c5e95fe30138d3e07baeb931d97b51
|
https://github.com/tilemill-project/millstone/blob/7440d62881c5e95fe30138d3e07baeb931d97b51/lib/millstone.js#L463-L491
|
train
|
tilemill-project/millstone
|
lib/millstone.js
|
localizeCartoURIs
|
function localizeCartoURIs(s,cb) {
// Get all unique URIs in stylesheet
// TODO - avoid finding non url( uris?
var matches = s.data.match(/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi);
var URIs = _.uniq(matches || []);
var CartoURIs = [];
// remove any matched urls that are not clearly
// part of a carto style
// TODO - consider moving to carto so we can also avoid
// downloading commented out code
URIs.forEach(function(u) {
var idx = s.data.indexOf(u);
if (idx > -1) {
var pre_url = s.data.slice(idx-5,idx);
if (pre_url.indexOf('url(') > -1) {
CartoURIs.push(u);
// Update number of async calls so that we don't
// call this() too soon (before everything is done)
remaining += 1;
}
}
});
CartoURIs.forEach(function(u) {
var uri = url.parse(encodeURI(u));
// URL.
if (uri.protocol && (uri.protocol == 'http:' || uri.protocol == 'https:')) {
var filepath = path.join(cache, cachepath(u));
localize(uri.href, {filepath:filepath,name:s.id}, function(err, file) {
if (err) {
cb(err);
} else {
var extname = path.extname(file);
if (!extname) {
readExtension(file, function(error, ext) {
// note - we ignore any readExtension errors
if (ext) {
var new_filename = file + ext;
fs.rename(file, new_filename, function(err) {
s.data = s.data.split(u).join(new_filename);
cb(err);
});
} else {
s.data = s.data.split(u).join(file);
cb(err);
}
});
} else {
s.data = s.data.split(u).join(file);
cb(err);
}
}
});
} else {
cb();
}
});
cb();
}
|
javascript
|
function localizeCartoURIs(s,cb) {
// Get all unique URIs in stylesheet
// TODO - avoid finding non url( uris?
var matches = s.data.match(/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi);
var URIs = _.uniq(matches || []);
var CartoURIs = [];
// remove any matched urls that are not clearly
// part of a carto style
// TODO - consider moving to carto so we can also avoid
// downloading commented out code
URIs.forEach(function(u) {
var idx = s.data.indexOf(u);
if (idx > -1) {
var pre_url = s.data.slice(idx-5,idx);
if (pre_url.indexOf('url(') > -1) {
CartoURIs.push(u);
// Update number of async calls so that we don't
// call this() too soon (before everything is done)
remaining += 1;
}
}
});
CartoURIs.forEach(function(u) {
var uri = url.parse(encodeURI(u));
// URL.
if (uri.protocol && (uri.protocol == 'http:' || uri.protocol == 'https:')) {
var filepath = path.join(cache, cachepath(u));
localize(uri.href, {filepath:filepath,name:s.id}, function(err, file) {
if (err) {
cb(err);
} else {
var extname = path.extname(file);
if (!extname) {
readExtension(file, function(error, ext) {
// note - we ignore any readExtension errors
if (ext) {
var new_filename = file + ext;
fs.rename(file, new_filename, function(err) {
s.data = s.data.split(u).join(new_filename);
cb(err);
});
} else {
s.data = s.data.split(u).join(file);
cb(err);
}
});
} else {
s.data = s.data.split(u).join(file);
cb(err);
}
}
});
} else {
cb();
}
});
cb();
}
|
[
"function",
"localizeCartoURIs",
"(",
"s",
",",
"cb",
")",
"{",
"var",
"matches",
"=",
"s",
".",
"data",
".",
"match",
"(",
"/",
"[-a-zA-Z0-9@:%_\\+.~#?&//=]{2,256}\\.[a-z]{2,4}\\b(\\/[-a-zA-Z0-9@:%_\\+.~#?&//=]*)?",
"/",
"gi",
")",
";",
"var",
"URIs",
"=",
"_",
".",
"uniq",
"(",
"matches",
"||",
"[",
"]",
")",
";",
"var",
"CartoURIs",
"=",
"[",
"]",
";",
"URIs",
".",
"forEach",
"(",
"function",
"(",
"u",
")",
"{",
"var",
"idx",
"=",
"s",
".",
"data",
".",
"indexOf",
"(",
"u",
")",
";",
"if",
"(",
"idx",
">",
"-",
"1",
")",
"{",
"var",
"pre_url",
"=",
"s",
".",
"data",
".",
"slice",
"(",
"idx",
"-",
"5",
",",
"idx",
")",
";",
"if",
"(",
"pre_url",
".",
"indexOf",
"(",
"'url('",
")",
">",
"-",
"1",
")",
"{",
"CartoURIs",
".",
"push",
"(",
"u",
")",
";",
"remaining",
"+=",
"1",
";",
"}",
"}",
"}",
")",
";",
"CartoURIs",
".",
"forEach",
"(",
"function",
"(",
"u",
")",
"{",
"var",
"uri",
"=",
"url",
".",
"parse",
"(",
"encodeURI",
"(",
"u",
")",
")",
";",
"if",
"(",
"uri",
".",
"protocol",
"&&",
"(",
"uri",
".",
"protocol",
"==",
"'http:'",
"||",
"uri",
".",
"protocol",
"==",
"'https:'",
")",
")",
"{",
"var",
"filepath",
"=",
"path",
".",
"join",
"(",
"cache",
",",
"cachepath",
"(",
"u",
")",
")",
";",
"localize",
"(",
"uri",
".",
"href",
",",
"{",
"filepath",
":",
"filepath",
",",
"name",
":",
"s",
".",
"id",
"}",
",",
"function",
"(",
"err",
",",
"file",
")",
"{",
"if",
"(",
"err",
")",
"{",
"cb",
"(",
"err",
")",
";",
"}",
"else",
"{",
"var",
"extname",
"=",
"path",
".",
"extname",
"(",
"file",
")",
";",
"if",
"(",
"!",
"extname",
")",
"{",
"readExtension",
"(",
"file",
",",
"function",
"(",
"error",
",",
"ext",
")",
"{",
"if",
"(",
"ext",
")",
"{",
"var",
"new_filename",
"=",
"file",
"+",
"ext",
";",
"fs",
".",
"rename",
"(",
"file",
",",
"new_filename",
",",
"function",
"(",
"err",
")",
"{",
"s",
".",
"data",
"=",
"s",
".",
"data",
".",
"split",
"(",
"u",
")",
".",
"join",
"(",
"new_filename",
")",
";",
"cb",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"s",
".",
"data",
"=",
"s",
".",
"data",
".",
"split",
"(",
"u",
")",
".",
"join",
"(",
"file",
")",
";",
"cb",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"s",
".",
"data",
"=",
"s",
".",
"data",
".",
"split",
"(",
"u",
")",
".",
"join",
"(",
"file",
")",
";",
"cb",
"(",
"err",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
"else",
"{",
"cb",
"(",
")",
";",
"}",
"}",
")",
";",
"cb",
"(",
")",
";",
"}"
] |
Handle URIs within the Carto CSS
|
[
"Handle",
"URIs",
"within",
"the",
"Carto",
"CSS"
] |
7440d62881c5e95fe30138d3e07baeb931d97b51
|
https://github.com/tilemill-project/millstone/blob/7440d62881c5e95fe30138d3e07baeb931d97b51/lib/millstone.js#L548-L606
|
train
|
solderjs/node-bufferjs
|
bufferjs/indexOf.js
|
indexOf
|
function indexOf(haystack, needle, i) {
if (!Buffer.isBuffer(needle)) needle = new Buffer(needle);
if (typeof i === 'undefined') i = 0;
var l = haystack.length - needle.length + 1;
while (i<l) {
var good = true;
for (var j=0, n=needle.length; j<n; j++) {
if (haystack[i+j] !== needle[j]) {
good = false;
break;
}
}
if (good) return i;
i++;
}
return -1;
}
|
javascript
|
function indexOf(haystack, needle, i) {
if (!Buffer.isBuffer(needle)) needle = new Buffer(needle);
if (typeof i === 'undefined') i = 0;
var l = haystack.length - needle.length + 1;
while (i<l) {
var good = true;
for (var j=0, n=needle.length; j<n; j++) {
if (haystack[i+j] !== needle[j]) {
good = false;
break;
}
}
if (good) return i;
i++;
}
return -1;
}
|
[
"function",
"indexOf",
"(",
"haystack",
",",
"needle",
",",
"i",
")",
"{",
"if",
"(",
"!",
"Buffer",
".",
"isBuffer",
"(",
"needle",
")",
")",
"needle",
"=",
"new",
"Buffer",
"(",
"needle",
")",
";",
"if",
"(",
"typeof",
"i",
"===",
"'undefined'",
")",
"i",
"=",
"0",
";",
"var",
"l",
"=",
"haystack",
".",
"length",
"-",
"needle",
".",
"length",
"+",
"1",
";",
"while",
"(",
"i",
"<",
"l",
")",
"{",
"var",
"good",
"=",
"true",
";",
"for",
"(",
"var",
"j",
"=",
"0",
",",
"n",
"=",
"needle",
".",
"length",
";",
"j",
"<",
"n",
";",
"j",
"++",
")",
"{",
"if",
"(",
"haystack",
"[",
"i",
"+",
"j",
"]",
"!==",
"needle",
"[",
"j",
"]",
")",
"{",
"good",
"=",
"false",
";",
"break",
";",
"}",
"}",
"if",
"(",
"good",
")",
"return",
"i",
";",
"i",
"++",
";",
"}",
"return",
"-",
"1",
";",
"}"
] |
A naiive 'Buffer.indexOf' function. Requires both the
needle and haystack to be Buffer instances.
|
[
"A",
"naiive",
"Buffer",
".",
"indexOf",
"function",
".",
"Requires",
"both",
"the",
"needle",
"and",
"haystack",
"to",
"be",
"Buffer",
"instances",
"."
] |
b192950a61afd23e2a92c468873b8393e157f70a
|
https://github.com/solderjs/node-bufferjs/blob/b192950a61afd23e2a92c468873b8393e157f70a/bufferjs/indexOf.js#L9-L25
|
train
|
kasperisager/sails-generate-auth
|
templates/api/models/Passport.js
|
hashPassword
|
function hashPassword (passport, next) {
if (passport.password) {
bcrypt.hash(passport.password, 10, function (err, hash) {
passport.password = hash;
next(err, passport);
});
} else {
next(null, passport);
}
}
|
javascript
|
function hashPassword (passport, next) {
if (passport.password) {
bcrypt.hash(passport.password, 10, function (err, hash) {
passport.password = hash;
next(err, passport);
});
} else {
next(null, passport);
}
}
|
[
"function",
"hashPassword",
"(",
"passport",
",",
"next",
")",
"{",
"if",
"(",
"passport",
".",
"password",
")",
"{",
"bcrypt",
".",
"hash",
"(",
"passport",
".",
"password",
",",
"10",
",",
"function",
"(",
"err",
",",
"hash",
")",
"{",
"passport",
".",
"password",
"=",
"hash",
";",
"next",
"(",
"err",
",",
"passport",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"next",
"(",
"null",
",",
"passport",
")",
";",
"}",
"}"
] |
Hash a passport password.
@param {Object} password
@param {Function} next
|
[
"Hash",
"a",
"passport",
"password",
"."
] |
d256c6bc3984df3612408a9c30dd197d5fabde79
|
https://github.com/kasperisager/sails-generate-auth/blob/d256c6bc3984df3612408a9c30dd197d5fabde79/templates/api/models/Passport.js#L9-L18
|
train
|
canjs/can-observe
|
src/-make-array.js
|
function(target, key, value, receiver) {
// If the receiver is not this observable (the observable might be on the proto chain),
// set the key on the reciever.
if (receiver !== this.proxy) {
return makeObject.setKey(receiver, key, value, this);
}
// If it has a defined property definiition
var computedValue = computedHelpers.set(receiver, key, value);
if(computedValue === true ) {
return true;
}
// Gets the observable value to set.
value = makeObject.getValueToSet(key, value, this);
var startingLength = target.length;
// Sets the value on the target. If there
// is a change, calls the callback.
makeObject.setValueAndOnChange(key, value, this, function(key, value, meta, hadOwn, old) {
// Determine the patches this change should dispatch
var patches = [{
key: key,
type: hadOwn ? "set" : "add",
value: value
}];
var numberKey = !isSymbolLike(key) && +key;
// If we are adding an indexed value like `arr[5] =value` ...
if ( isInteger(numberKey) ) {
// If we set an enumerable property after the length ...
if (!hadOwn && numberKey > startingLength) {
// ... add patches for those values.
patches.push({
index: startingLength,
deleteCount: 0,
insert: target.slice(startingLength),
type: "splice"
});
} else {
// Otherwise, splice the value into the array.
patches.push.apply(patches, mutateMethods.splice(target, [numberKey, 1, value]));
}
}
// In the case of deleting items by setting the length of the array,
// add patches that splice the items removed.
// (deleting individual items from an array doesn't change the length; it just creates holes)
if (didLengthChangeCauseDeletions(key, value, old, meta)) {
patches.push({
index: value,
deleteCount: old - value,
insert: [],
type: "splice"
});
}
//!steal-remove-start
var reasonLog = [canReflect.getName(meta.proxy)+" set", key,"to", value];
//!steal-remove-end
var dispatchArgs = {
type: key,
patches: patches,
keyChanged: !hadOwn ? key : undefined
};
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
dispatchArgs.reasonLog = reasonLog;
}
//!steal-remove-end
mapBindings.dispatch.call( meta.proxy, dispatchArgs, [value, old]);
});
return true;
}
|
javascript
|
function(target, key, value, receiver) {
// If the receiver is not this observable (the observable might be on the proto chain),
// set the key on the reciever.
if (receiver !== this.proxy) {
return makeObject.setKey(receiver, key, value, this);
}
// If it has a defined property definiition
var computedValue = computedHelpers.set(receiver, key, value);
if(computedValue === true ) {
return true;
}
// Gets the observable value to set.
value = makeObject.getValueToSet(key, value, this);
var startingLength = target.length;
// Sets the value on the target. If there
// is a change, calls the callback.
makeObject.setValueAndOnChange(key, value, this, function(key, value, meta, hadOwn, old) {
// Determine the patches this change should dispatch
var patches = [{
key: key,
type: hadOwn ? "set" : "add",
value: value
}];
var numberKey = !isSymbolLike(key) && +key;
// If we are adding an indexed value like `arr[5] =value` ...
if ( isInteger(numberKey) ) {
// If we set an enumerable property after the length ...
if (!hadOwn && numberKey > startingLength) {
// ... add patches for those values.
patches.push({
index: startingLength,
deleteCount: 0,
insert: target.slice(startingLength),
type: "splice"
});
} else {
// Otherwise, splice the value into the array.
patches.push.apply(patches, mutateMethods.splice(target, [numberKey, 1, value]));
}
}
// In the case of deleting items by setting the length of the array,
// add patches that splice the items removed.
// (deleting individual items from an array doesn't change the length; it just creates holes)
if (didLengthChangeCauseDeletions(key, value, old, meta)) {
patches.push({
index: value,
deleteCount: old - value,
insert: [],
type: "splice"
});
}
//!steal-remove-start
var reasonLog = [canReflect.getName(meta.proxy)+" set", key,"to", value];
//!steal-remove-end
var dispatchArgs = {
type: key,
patches: patches,
keyChanged: !hadOwn ? key : undefined
};
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
dispatchArgs.reasonLog = reasonLog;
}
//!steal-remove-end
mapBindings.dispatch.call( meta.proxy, dispatchArgs, [value, old]);
});
return true;
}
|
[
"function",
"(",
"target",
",",
"key",
",",
"value",
",",
"receiver",
")",
"{",
"if",
"(",
"receiver",
"!==",
"this",
".",
"proxy",
")",
"{",
"return",
"makeObject",
".",
"setKey",
"(",
"receiver",
",",
"key",
",",
"value",
",",
"this",
")",
";",
"}",
"var",
"computedValue",
"=",
"computedHelpers",
".",
"set",
"(",
"receiver",
",",
"key",
",",
"value",
")",
";",
"if",
"(",
"computedValue",
"===",
"true",
")",
"{",
"return",
"true",
";",
"}",
"value",
"=",
"makeObject",
".",
"getValueToSet",
"(",
"key",
",",
"value",
",",
"this",
")",
";",
"var",
"startingLength",
"=",
"target",
".",
"length",
";",
"makeObject",
".",
"setValueAndOnChange",
"(",
"key",
",",
"value",
",",
"this",
",",
"function",
"(",
"key",
",",
"value",
",",
"meta",
",",
"hadOwn",
",",
"old",
")",
"{",
"var",
"patches",
"=",
"[",
"{",
"key",
":",
"key",
",",
"type",
":",
"hadOwn",
"?",
"\"set\"",
":",
"\"add\"",
",",
"value",
":",
"value",
"}",
"]",
";",
"var",
"numberKey",
"=",
"!",
"isSymbolLike",
"(",
"key",
")",
"&&",
"+",
"key",
";",
"if",
"(",
"isInteger",
"(",
"numberKey",
")",
")",
"{",
"if",
"(",
"!",
"hadOwn",
"&&",
"numberKey",
">",
"startingLength",
")",
"{",
"patches",
".",
"push",
"(",
"{",
"index",
":",
"startingLength",
",",
"deleteCount",
":",
"0",
",",
"insert",
":",
"target",
".",
"slice",
"(",
"startingLength",
")",
",",
"type",
":",
"\"splice\"",
"}",
")",
";",
"}",
"else",
"{",
"patches",
".",
"push",
".",
"apply",
"(",
"patches",
",",
"mutateMethods",
".",
"splice",
"(",
"target",
",",
"[",
"numberKey",
",",
"1",
",",
"value",
"]",
")",
")",
";",
"}",
"}",
"if",
"(",
"didLengthChangeCauseDeletions",
"(",
"key",
",",
"value",
",",
"old",
",",
"meta",
")",
")",
"{",
"patches",
".",
"push",
"(",
"{",
"index",
":",
"value",
",",
"deleteCount",
":",
"old",
"-",
"value",
",",
"insert",
":",
"[",
"]",
",",
"type",
":",
"\"splice\"",
"}",
")",
";",
"}",
"var",
"reasonLog",
"=",
"[",
"canReflect",
".",
"getName",
"(",
"meta",
".",
"proxy",
")",
"+",
"\" set\"",
",",
"key",
",",
"\"to\"",
",",
"value",
"]",
";",
"var",
"dispatchArgs",
"=",
"{",
"type",
":",
"key",
",",
"patches",
":",
"patches",
",",
"keyChanged",
":",
"!",
"hadOwn",
"?",
"key",
":",
"undefined",
"}",
";",
"if",
"(",
"process",
".",
"env",
".",
"NODE_ENV",
"!==",
"'production'",
")",
"{",
"dispatchArgs",
".",
"reasonLog",
"=",
"reasonLog",
";",
"}",
"mapBindings",
".",
"dispatch",
".",
"call",
"(",
"meta",
".",
"proxy",
",",
"dispatchArgs",
",",
"[",
"value",
",",
"old",
"]",
")",
";",
"}",
")",
";",
"return",
"true",
";",
"}"
] |
`set` is called when a property is set on the proxy or an object that has the proxy on its prototype.
|
[
"set",
"is",
"called",
"when",
"a",
"property",
"is",
"set",
"on",
"the",
"proxy",
"or",
"an",
"object",
"that",
"has",
"the",
"proxy",
"on",
"its",
"prototype",
"."
] |
e85c7d8121f043e8b5dda80386959986366add10
|
https://github.com/canjs/can-observe/blob/e85c7d8121f043e8b5dda80386959986366add10/src/-make-array.js#L234-L313
|
train
|
|
canjs/can-connect-feathers
|
utils/utils.js
|
getStoredToken
|
function getStoredToken (storageLocation) {
var token = readCookie(storageLocation);
if (!token && (window && window.localStorage || window.sessionStorage)) {
token = window.sessionStorage.getItem(storageLocation) || window.localStorage.getItem(storageLocation);
}
return token;
}
|
javascript
|
function getStoredToken (storageLocation) {
var token = readCookie(storageLocation);
if (!token && (window && window.localStorage || window.sessionStorage)) {
token = window.sessionStorage.getItem(storageLocation) || window.localStorage.getItem(storageLocation);
}
return token;
}
|
[
"function",
"getStoredToken",
"(",
"storageLocation",
")",
"{",
"var",
"token",
"=",
"readCookie",
"(",
"storageLocation",
")",
";",
"if",
"(",
"!",
"token",
"&&",
"(",
"window",
"&&",
"window",
".",
"localStorage",
"||",
"window",
".",
"sessionStorage",
")",
")",
"{",
"token",
"=",
"window",
".",
"sessionStorage",
".",
"getItem",
"(",
"storageLocation",
")",
"||",
"window",
".",
"localStorage",
".",
"getItem",
"(",
"storageLocation",
")",
";",
"}",
"return",
"token",
";",
"}"
] |
Reads the token from a cookie, sessionStorage, or localStorage, in that order.
|
[
"Reads",
"the",
"token",
"from",
"a",
"cookie",
"sessionStorage",
"or",
"localStorage",
"in",
"that",
"order",
"."
] |
5dea97b0c1c1347e0e489fe1f5943015e93f3aa6
|
https://github.com/canjs/can-connect-feathers/blob/5dea97b0c1c1347e0e489fe1f5943015e93f3aa6/utils/utils.js#L22-L28
|
train
|
canjs/can-connect-feathers
|
utils/utils.js
|
hasValidToken
|
function hasValidToken (storageLocation) {
var token = getStoredToken(storageLocation);
if (token) {
try {
var payload = decode(token);
return payloadIsValid(payload);
} catch (error) {
return false;
}
}
return false;
}
|
javascript
|
function hasValidToken (storageLocation) {
var token = getStoredToken(storageLocation);
if (token) {
try {
var payload = decode(token);
return payloadIsValid(payload);
} catch (error) {
return false;
}
}
return false;
}
|
[
"function",
"hasValidToken",
"(",
"storageLocation",
")",
"{",
"var",
"token",
"=",
"getStoredToken",
"(",
"storageLocation",
")",
";",
"if",
"(",
"token",
")",
"{",
"try",
"{",
"var",
"payload",
"=",
"decode",
"(",
"token",
")",
";",
"return",
"payloadIsValid",
"(",
"payload",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Gets a stored token and returns a boolean of whether it was valid.
|
[
"Gets",
"a",
"stored",
"token",
"and",
"returns",
"a",
"boolean",
"of",
"whether",
"it",
"was",
"valid",
"."
] |
5dea97b0c1c1347e0e489fe1f5943015e93f3aa6
|
https://github.com/canjs/can-connect-feathers/blob/5dea97b0c1c1347e0e489fe1f5943015e93f3aa6/utils/utils.js#L36-L47
|
train
|
Picolab/pico-engine
|
packages/pico-engine-core/src/processEvent.js
|
toPairs
|
function toPairs (v) {
if (ktypes.isArray(v)) {
var pairs = []
var i
for (i = 0; i < v.length; i++) {
pairs.push([i, v[i]])
}
return pairs
}
return _.toPairs(v)
}
|
javascript
|
function toPairs (v) {
if (ktypes.isArray(v)) {
var pairs = []
var i
for (i = 0; i < v.length; i++) {
pairs.push([i, v[i]])
}
return pairs
}
return _.toPairs(v)
}
|
[
"function",
"toPairs",
"(",
"v",
")",
"{",
"if",
"(",
"ktypes",
".",
"isArray",
"(",
"v",
")",
")",
"{",
"var",
"pairs",
"=",
"[",
"]",
"var",
"i",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"v",
".",
"length",
";",
"i",
"++",
")",
"{",
"pairs",
".",
"push",
"(",
"[",
"i",
",",
"v",
"[",
"i",
"]",
"]",
")",
"}",
"return",
"pairs",
"}",
"return",
"_",
".",
"toPairs",
"(",
"v",
")",
"}"
] |
used by `foreach` in krl
Array's use index numbers, maps use key strings
|
[
"used",
"by",
"foreach",
"in",
"krl",
"Array",
"s",
"use",
"index",
"numbers",
"maps",
"use",
"key",
"strings"
] |
809ab9c99fd97f59f6c6932a8383d7f117b4c2ef
|
https://github.com/Picolab/pico-engine/blob/809ab9c99fd97f59f6c6932a8383d7f117b4c2ef/packages/pico-engine-core/src/processEvent.js#L65-L75
|
train
|
Picolab/pico-engine
|
packages/pico-engine/src/oauth_server.js
|
function (auth) {
var clientCredentials = Buffer.from(auth.slice('basic '.length), 'base64').toString().split(':')
var clientId = querystring.unescape(clientCredentials[0])
var clientSecret = querystring.unescape(clientCredentials[1])
return { id: clientId, secret: clientSecret }
}
|
javascript
|
function (auth) {
var clientCredentials = Buffer.from(auth.slice('basic '.length), 'base64').toString().split(':')
var clientId = querystring.unescape(clientCredentials[0])
var clientSecret = querystring.unescape(clientCredentials[1])
return { id: clientId, secret: clientSecret }
}
|
[
"function",
"(",
"auth",
")",
"{",
"var",
"clientCredentials",
"=",
"Buffer",
".",
"from",
"(",
"auth",
".",
"slice",
"(",
"'basic '",
".",
"length",
")",
",",
"'base64'",
")",
".",
"toString",
"(",
")",
".",
"split",
"(",
"':'",
")",
"var",
"clientId",
"=",
"querystring",
".",
"unescape",
"(",
"clientCredentials",
"[",
"0",
"]",
")",
"var",
"clientSecret",
"=",
"querystring",
".",
"unescape",
"(",
"clientCredentials",
"[",
"1",
"]",
")",
"return",
"{",
"id",
":",
"clientId",
",",
"secret",
":",
"clientSecret",
"}",
"}"
] |
start of code borrowed from OAuth in Action
|
[
"start",
"of",
"code",
"borrowed",
"from",
"OAuth",
"in",
"Action"
] |
809ab9c99fd97f59f6c6932a8383d7f117b4c2ef
|
https://github.com/Picolab/pico-engine/blob/809ab9c99fd97f59f6c6932a8383d7f117b4c2ef/packages/pico-engine/src/oauth_server.js#L68-L73
|
train
|
|
Picolab/pico-engine
|
packages/krl-parser/src/grammar.js
|
function(x){
if(!x || x.type !== type){
return false;
}
if(value){
return x.src === value;
}
return true;
}
|
javascript
|
function(x){
if(!x || x.type !== type){
return false;
}
if(value){
return x.src === value;
}
return true;
}
|
[
"function",
"(",
"x",
")",
"{",
"if",
"(",
"!",
"x",
"||",
"x",
".",
"type",
"!==",
"type",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"value",
")",
"{",
"return",
"x",
".",
"src",
"===",
"value",
";",
"}",
"return",
"true",
";",
"}"
] |
hint for "unparsing"
|
[
"hint",
"for",
"unparsing"
] |
809ab9c99fd97f59f6c6932a8383d7f117b4c2ef
|
https://github.com/Picolab/pico-engine/blob/809ab9c99fd97f59f6c6932a8383d7f117b4c2ef/packages/krl-parser/src/grammar.js#L254-L262
|
train
|
|
chyingp/grunt-inline
|
tasks/inline.js
|
getPathToDestination
|
function getPathToDestination(pathToSource, pathToDestinationFile) {
var isDestinationDirectory = (/\/$/).test(pathToDestinationFile);
var fileName = path.basename(pathToSource);
var newPathToDestination;
if (typeof pathToDestinationFile === 'undefined') {
newPathToDestination = pathToSource;
} else {
newPathToDestination = pathToDestinationFile + (isDestinationDirectory ? fileName : '');
}
return newPathToDestination;
}
|
javascript
|
function getPathToDestination(pathToSource, pathToDestinationFile) {
var isDestinationDirectory = (/\/$/).test(pathToDestinationFile);
var fileName = path.basename(pathToSource);
var newPathToDestination;
if (typeof pathToDestinationFile === 'undefined') {
newPathToDestination = pathToSource;
} else {
newPathToDestination = pathToDestinationFile + (isDestinationDirectory ? fileName : '');
}
return newPathToDestination;
}
|
[
"function",
"getPathToDestination",
"(",
"pathToSource",
",",
"pathToDestinationFile",
")",
"{",
"var",
"isDestinationDirectory",
"=",
"(",
"/",
"\\/$",
"/",
")",
".",
"test",
"(",
"pathToDestinationFile",
")",
";",
"var",
"fileName",
"=",
"path",
".",
"basename",
"(",
"pathToSource",
")",
";",
"var",
"newPathToDestination",
";",
"if",
"(",
"typeof",
"pathToDestinationFile",
"===",
"'undefined'",
")",
"{",
"newPathToDestination",
"=",
"pathToSource",
";",
"}",
"else",
"{",
"newPathToDestination",
"=",
"pathToDestinationFile",
"+",
"(",
"isDestinationDirectory",
"?",
"fileName",
":",
"''",
")",
";",
"}",
"return",
"newPathToDestination",
";",
"}"
] |
from grunt-text-replace.js in grunt-text-replace
|
[
"from",
"grunt",
"-",
"text",
"-",
"replace",
".",
"js",
"in",
"grunt",
"-",
"text",
"-",
"replace"
] |
b25f9bc1529e39610ef5fef7ebb2bf6865bffde4
|
https://github.com/chyingp/grunt-inline/blob/b25f9bc1529e39610ef5fef7ebb2bf6865bffde4/tasks/inline.js#L83-L93
|
train
|
cedaro/node-wp-i18n
|
lib/pot.js
|
fixHeaders
|
function fixHeaders(contents) {
contents = contents.replace(/x-poedit-keywordslist:/i, 'X-Poedit-KeywordsList:');
contents = contents.replace(/x-poedit-searchpath-/ig, 'X-Poedit-SearchPath-');
contents = contents.replace(/x-poedit-searchpathexcluded-/ig, 'X-Poedit-SearchPathExcluded-');
contents = contents.replace(/x-poedit-sourcecharset:/i, 'X-Poedit-SourceCharset:');
return contents;
}
|
javascript
|
function fixHeaders(contents) {
contents = contents.replace(/x-poedit-keywordslist:/i, 'X-Poedit-KeywordsList:');
contents = contents.replace(/x-poedit-searchpath-/ig, 'X-Poedit-SearchPath-');
contents = contents.replace(/x-poedit-searchpathexcluded-/ig, 'X-Poedit-SearchPathExcluded-');
contents = contents.replace(/x-poedit-sourcecharset:/i, 'X-Poedit-SourceCharset:');
return contents;
}
|
[
"function",
"fixHeaders",
"(",
"contents",
")",
"{",
"contents",
"=",
"contents",
".",
"replace",
"(",
"/",
"x-poedit-keywordslist:",
"/",
"i",
",",
"'X-Poedit-KeywordsList:'",
")",
";",
"contents",
"=",
"contents",
".",
"replace",
"(",
"/",
"x-poedit-searchpath-",
"/",
"ig",
",",
"'X-Poedit-SearchPath-'",
")",
";",
"contents",
"=",
"contents",
".",
"replace",
"(",
"/",
"x-poedit-searchpathexcluded-",
"/",
"ig",
",",
"'X-Poedit-SearchPathExcluded-'",
")",
";",
"contents",
"=",
"contents",
".",
"replace",
"(",
"/",
"x-poedit-sourcecharset:",
"/",
"i",
",",
"'X-Poedit-SourceCharset:'",
")",
";",
"return",
"contents",
";",
"}"
] |
Fix POT file headers.
Updates case-sensitive Poedit headers.
@param {string} pot POT file contents.
@returns {string}
|
[
"Fix",
"POT",
"file",
"headers",
"."
] |
4633a5332b643e2e74de4ece96ec1c0232ed4914
|
https://github.com/cedaro/node-wp-i18n/blob/4633a5332b643e2e74de4ece96ec1c0232ed4914/lib/pot.js#L27-L33
|
train
|
cedaro/node-wp-i18n
|
lib/pot.js
|
normalizeForComparison
|
function normalizeForComparison(pot) {
var clone = _.cloneDeep(pot);
if (!pot) {
return pot;
}
// Normalize the content type case.
clone.headers['content-type'] = clone.headers['content-type'].toLowerCase();
// Blank out the dates.
clone.headers['pot-creation-date'] = '';
clone.headers['po-revision-date'] = '';
// Blank out the headers in the translations object. These are used for
// reference only and won't be compiled, so they shouldn't be used when
// comparing POT objects.
clone.translations['']['']['msgstr'] = '';
return clone;
}
|
javascript
|
function normalizeForComparison(pot) {
var clone = _.cloneDeep(pot);
if (!pot) {
return pot;
}
// Normalize the content type case.
clone.headers['content-type'] = clone.headers['content-type'].toLowerCase();
// Blank out the dates.
clone.headers['pot-creation-date'] = '';
clone.headers['po-revision-date'] = '';
// Blank out the headers in the translations object. These are used for
// reference only and won't be compiled, so they shouldn't be used when
// comparing POT objects.
clone.translations['']['']['msgstr'] = '';
return clone;
}
|
[
"function",
"normalizeForComparison",
"(",
"pot",
")",
"{",
"var",
"clone",
"=",
"_",
".",
"cloneDeep",
"(",
"pot",
")",
";",
"if",
"(",
"!",
"pot",
")",
"{",
"return",
"pot",
";",
"}",
"clone",
".",
"headers",
"[",
"'content-type'",
"]",
"=",
"clone",
".",
"headers",
"[",
"'content-type'",
"]",
".",
"toLowerCase",
"(",
")",
";",
"clone",
".",
"headers",
"[",
"'pot-creation-date'",
"]",
"=",
"''",
";",
"clone",
".",
"headers",
"[",
"'po-revision-date'",
"]",
"=",
"''",
";",
"clone",
".",
"translations",
"[",
"''",
"]",
"[",
"''",
"]",
"[",
"'msgstr'",
"]",
"=",
"''",
";",
"return",
"clone",
";",
"}"
] |
Normalize Pot contents created by gettext-parser.
This normalizes dynamic strings in a POT file in order to compare them and
determine if anything has changed.
Headers are stored in two locations.
@param {Object} pot Pot contents created by gettext-parser.
@returns {Object}
|
[
"Normalize",
"Pot",
"contents",
"created",
"by",
"gettext",
"-",
"parser",
"."
] |
4633a5332b643e2e74de4ece96ec1c0232ed4914
|
https://github.com/cedaro/node-wp-i18n/blob/4633a5332b643e2e74de4ece96ec1c0232ed4914/lib/pot.js#L50-L70
|
train
|
cedaro/node-wp-i18n
|
lib/pot.js
|
Pot
|
function Pot(filename) {
if (! (this instanceof Pot)) {
return new Pot(filename);
}
this.isOpen = false;
this.filename = filename;
this.contents = '';
this.initialDate = '';
this.fingerprint = '';
}
|
javascript
|
function Pot(filename) {
if (! (this instanceof Pot)) {
return new Pot(filename);
}
this.isOpen = false;
this.filename = filename;
this.contents = '';
this.initialDate = '';
this.fingerprint = '';
}
|
[
"function",
"Pot",
"(",
"filename",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Pot",
")",
")",
"{",
"return",
"new",
"Pot",
"(",
"filename",
")",
";",
"}",
"this",
".",
"isOpen",
"=",
"false",
";",
"this",
".",
"filename",
"=",
"filename",
";",
"this",
".",
"contents",
"=",
"''",
";",
"this",
".",
"initialDate",
"=",
"''",
";",
"this",
".",
"fingerprint",
"=",
"''",
";",
"}"
] |
Create a new Pot object.
@class Pot
|
[
"Create",
"a",
"new",
"Pot",
"object",
"."
] |
4633a5332b643e2e74de4ece96ec1c0232ed4914
|
https://github.com/cedaro/node-wp-i18n/blob/4633a5332b643e2e74de4ece96ec1c0232ed4914/lib/pot.js#L77-L87
|
train
|
cedaro/node-wp-i18n
|
lib/util.js
|
function(file, args) {
return new Promise(function(resolve, reject) {
var child = spawn(file, args, { stdio: 'inherit' });
child.on('error', reject);
child.on('close', resolve);
});
}
|
javascript
|
function(file, args) {
return new Promise(function(resolve, reject) {
var child = spawn(file, args, { stdio: 'inherit' });
child.on('error', reject);
child.on('close', resolve);
});
}
|
[
"function",
"(",
"file",
",",
"args",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"var",
"child",
"=",
"spawn",
"(",
"file",
",",
"args",
",",
"{",
"stdio",
":",
"'inherit'",
"}",
")",
";",
"child",
".",
"on",
"(",
"'error'",
",",
"reject",
")",
";",
"child",
".",
"on",
"(",
"'close'",
",",
"resolve",
")",
";",
"}",
")",
";",
"}"
] |
Spawn a process and return a promise.
@param {string} file Filename of the program to run.
@param {string[]} args List of string arguments.
@returns {Promise}
|
[
"Spawn",
"a",
"process",
"and",
"return",
"a",
"promise",
"."
] |
4633a5332b643e2e74de4ece96ec1c0232ed4914
|
https://github.com/cedaro/node-wp-i18n/blob/4633a5332b643e2e74de4ece96ec1c0232ed4914/lib/util.js#L61-L67
|
train
|
|
cedaro/node-wp-i18n
|
lib/msgmerge.js
|
updatePoFiles
|
function updatePoFiles(filename, pattern) {
var merged = [];
var searchPath = path.dirname(filename);
pattern = pattern || '*.po';
glob.sync(pattern, {
cwd: path.dirname(filename)
}).forEach(function(file) {
var poFile = path.join(searchPath, file);
merged.push(mergeFiles(filename, poFile));
});
return Promise.all(merged);
}
|
javascript
|
function updatePoFiles(filename, pattern) {
var merged = [];
var searchPath = path.dirname(filename);
pattern = pattern || '*.po';
glob.sync(pattern, {
cwd: path.dirname(filename)
}).forEach(function(file) {
var poFile = path.join(searchPath, file);
merged.push(mergeFiles(filename, poFile));
});
return Promise.all(merged);
}
|
[
"function",
"updatePoFiles",
"(",
"filename",
",",
"pattern",
")",
"{",
"var",
"merged",
"=",
"[",
"]",
";",
"var",
"searchPath",
"=",
"path",
".",
"dirname",
"(",
"filename",
")",
";",
"pattern",
"=",
"pattern",
"||",
"'*.po'",
";",
"glob",
".",
"sync",
"(",
"pattern",
",",
"{",
"cwd",
":",
"path",
".",
"dirname",
"(",
"filename",
")",
"}",
")",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"poFile",
"=",
"path",
".",
"join",
"(",
"searchPath",
",",
"file",
")",
";",
"merged",
".",
"push",
"(",
"mergeFiles",
"(",
"filename",
",",
"poFile",
")",
")",
";",
"}",
")",
";",
"return",
"Promise",
".",
"all",
"(",
"merged",
")",
";",
"}"
] |
Set multiple headers at once.
Magically expands certain values to add Poedit headers.
@param {string} filename Full path to a POT file.
@param {string} pattern Optional. Glob pattern of PO files to update.
@returns {Promise}
|
[
"Set",
"multiple",
"headers",
"at",
"once",
"."
] |
4633a5332b643e2e74de4ece96ec1c0232ed4914
|
https://github.com/cedaro/node-wp-i18n/blob/4633a5332b643e2e74de4ece96ec1c0232ed4914/lib/msgmerge.js#L41-L55
|
train
|
cedaro/node-wp-i18n
|
lib/package.js
|
guessSlug
|
function guessSlug(wpPackage) {
var directory = wpPackage.getPath();
var slug = path.basename(directory);
var slug2 = path.basename(path.dirname(directory));
if ('trunk' === slug || 'src' === slug) {
slug = slug2;
} else if (-1 !== ['branches', 'tags'].indexOf(slug2)) {
slug = path.basename(path.dirname(path.dirname(directory)));
}
return slug;
}
|
javascript
|
function guessSlug(wpPackage) {
var directory = wpPackage.getPath();
var slug = path.basename(directory);
var slug2 = path.basename(path.dirname(directory));
if ('trunk' === slug || 'src' === slug) {
slug = slug2;
} else if (-1 !== ['branches', 'tags'].indexOf(slug2)) {
slug = path.basename(path.dirname(path.dirname(directory)));
}
return slug;
}
|
[
"function",
"guessSlug",
"(",
"wpPackage",
")",
"{",
"var",
"directory",
"=",
"wpPackage",
".",
"getPath",
"(",
")",
";",
"var",
"slug",
"=",
"path",
".",
"basename",
"(",
"directory",
")",
";",
"var",
"slug2",
"=",
"path",
".",
"basename",
"(",
"path",
".",
"dirname",
"(",
"directory",
")",
")",
";",
"if",
"(",
"'trunk'",
"===",
"slug",
"||",
"'src'",
"===",
"slug",
")",
"{",
"slug",
"=",
"slug2",
";",
"}",
"else",
"if",
"(",
"-",
"1",
"!==",
"[",
"'branches'",
",",
"'tags'",
"]",
".",
"indexOf",
"(",
"slug2",
")",
")",
"{",
"slug",
"=",
"path",
".",
"basename",
"(",
"path",
".",
"dirname",
"(",
"path",
".",
"dirname",
"(",
"directory",
")",
")",
")",
";",
"}",
"return",
"slug",
";",
"}"
] |
Guess the wpPackage slug.
See MakePOT::guess_plugin_slug() in makepot.php
@returns {string}
|
[
"Guess",
"the",
"wpPackage",
"slug",
"."
] |
4633a5332b643e2e74de4ece96ec1c0232ed4914
|
https://github.com/cedaro/node-wp-i18n/blob/4633a5332b643e2e74de4ece96ec1c0232ed4914/lib/package.js#L26-L38
|
train
|
cedaro/node-wp-i18n
|
lib/package.js
|
findMainFile
|
function findMainFile(wpPackage) {
if (wpPackage.isType('wp-theme')) {
return 'style.css';
}
var found = '';
var pluginFile = guessSlug(wpPackage) + '.php';
var filename = wpPackage.getPath(pluginFile);
// Check if the main file exists.
if (util.fileExists(filename) && wpPackage.getHeader('Plugin Name', filename)) {
return pluginFile;
}
// Search for plugin headers in php files in the main directory.
glob.sync('*.php', {
cwd: wpPackage.getPath()
}).forEach(function(file) {
var filename = wpPackage.getPath(file);
if (wpPackage.getHeader('Plugin Name', filename)) {
found = file;
}
});
return found;
}
|
javascript
|
function findMainFile(wpPackage) {
if (wpPackage.isType('wp-theme')) {
return 'style.css';
}
var found = '';
var pluginFile = guessSlug(wpPackage) + '.php';
var filename = wpPackage.getPath(pluginFile);
// Check if the main file exists.
if (util.fileExists(filename) && wpPackage.getHeader('Plugin Name', filename)) {
return pluginFile;
}
// Search for plugin headers in php files in the main directory.
glob.sync('*.php', {
cwd: wpPackage.getPath()
}).forEach(function(file) {
var filename = wpPackage.getPath(file);
if (wpPackage.getHeader('Plugin Name', filename)) {
found = file;
}
});
return found;
}
|
[
"function",
"findMainFile",
"(",
"wpPackage",
")",
"{",
"if",
"(",
"wpPackage",
".",
"isType",
"(",
"'wp-theme'",
")",
")",
"{",
"return",
"'style.css'",
";",
"}",
"var",
"found",
"=",
"''",
";",
"var",
"pluginFile",
"=",
"guessSlug",
"(",
"wpPackage",
")",
"+",
"'.php'",
";",
"var",
"filename",
"=",
"wpPackage",
".",
"getPath",
"(",
"pluginFile",
")",
";",
"if",
"(",
"util",
".",
"fileExists",
"(",
"filename",
")",
"&&",
"wpPackage",
".",
"getHeader",
"(",
"'Plugin Name'",
",",
"filename",
")",
")",
"{",
"return",
"pluginFile",
";",
"}",
"glob",
".",
"sync",
"(",
"'*.php'",
",",
"{",
"cwd",
":",
"wpPackage",
".",
"getPath",
"(",
")",
"}",
")",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"filename",
"=",
"wpPackage",
".",
"getPath",
"(",
"file",
")",
";",
"if",
"(",
"wpPackage",
".",
"getHeader",
"(",
"'Plugin Name'",
",",
"filename",
")",
")",
"{",
"found",
"=",
"file",
";",
"}",
"}",
")",
";",
"return",
"found",
";",
"}"
] |
Discover the main package file.
For themes, the main file will be style.css. The main file for plugins
contains the plugin headers.
@param {WPPackage} wpPackage Package object.
@returns {string}
|
[
"Discover",
"the",
"main",
"package",
"file",
"."
] |
4633a5332b643e2e74de4ece96ec1c0232ed4914
|
https://github.com/cedaro/node-wp-i18n/blob/4633a5332b643e2e74de4ece96ec1c0232ed4914/lib/package.js#L49-L75
|
train
|
cedaro/node-wp-i18n
|
lib/package.js
|
WPPackage
|
function WPPackage(directory, type) {
if (!(this instanceof WPPackage)) {
return new WPPackage(directory, type);
}
this.directory = null;
this.domainPath = null;
this.mainFile = null;
this.potFile = null;
this.type = 'wp-plugin';
this.initialize(directory, type);
}
|
javascript
|
function WPPackage(directory, type) {
if (!(this instanceof WPPackage)) {
return new WPPackage(directory, type);
}
this.directory = null;
this.domainPath = null;
this.mainFile = null;
this.potFile = null;
this.type = 'wp-plugin';
this.initialize(directory, type);
}
|
[
"function",
"WPPackage",
"(",
"directory",
",",
"type",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"WPPackage",
")",
")",
"{",
"return",
"new",
"WPPackage",
"(",
"directory",
",",
"type",
")",
";",
"}",
"this",
".",
"directory",
"=",
"null",
";",
"this",
".",
"domainPath",
"=",
"null",
";",
"this",
".",
"mainFile",
"=",
"null",
";",
"this",
".",
"potFile",
"=",
"null",
";",
"this",
".",
"type",
"=",
"'wp-plugin'",
";",
"this",
".",
"initialize",
"(",
"directory",
",",
"type",
")",
";",
"}"
] |
Create a new package.
@class WPPackage
|
[
"Create",
"a",
"new",
"package",
"."
] |
4633a5332b643e2e74de4ece96ec1c0232ed4914
|
https://github.com/cedaro/node-wp-i18n/blob/4633a5332b643e2e74de4ece96ec1c0232ed4914/lib/package.js#L82-L94
|
train
|
MikaAK/angular-safeguard
|
docs/js/tree.js
|
function(o) {
for (i in o) {
if (!!o[i] && typeof(o[i]) == "object") {
if (!o[i].length && o[i].type === 'tag') {
nodeCount += 1;
o[i]._id = nodeCount;
}
traverseIds(o[i]);
}
}
}
|
javascript
|
function(o) {
for (i in o) {
if (!!o[i] && typeof(o[i]) == "object") {
if (!o[i].length && o[i].type === 'tag') {
nodeCount += 1;
o[i]._id = nodeCount;
}
traverseIds(o[i]);
}
}
}
|
[
"function",
"(",
"o",
")",
"{",
"for",
"(",
"i",
"in",
"o",
")",
"{",
"if",
"(",
"!",
"!",
"o",
"[",
"i",
"]",
"&&",
"typeof",
"(",
"o",
"[",
"i",
"]",
")",
"==",
"\"object\"",
")",
"{",
"if",
"(",
"!",
"o",
"[",
"i",
"]",
".",
"length",
"&&",
"o",
"[",
"i",
"]",
".",
"type",
"===",
"'tag'",
")",
"{",
"nodeCount",
"+=",
"1",
";",
"o",
"[",
"i",
"]",
".",
"_id",
"=",
"nodeCount",
";",
"}",
"traverseIds",
"(",
"o",
"[",
"i",
"]",
")",
";",
"}",
"}",
"}"
] |
Add id for nodes
|
[
"Add",
"id",
"for",
"nodes"
] |
80fabdd0cb3f8493c925ae349c39df263dbb8ef9
|
https://github.com/MikaAK/angular-safeguard/blob/80fabdd0cb3f8493c925ae349c39df263dbb8ef9/docs/js/tree.js#L23-L33
|
train
|
|
google/identity-toolkit-node-client
|
lib/gitkitclient.js
|
GitkitClient
|
function GitkitClient(options) {
this.widgetUrl = options.widgetUrl;
this.maxTokenExpiration = 86400 * 30; // 30 days
this.audiences = [];
if (options.projectId !== undefined) {
this.audiences.push(options.projectId);
}
if (options.clientId !== undefined) {
this.audiences.push(options.clientId);
}
if (this.audiences.length == 0) {
throw new Error("Missing projectId or clientId in server configuration.");
}
this.authClient = new google.auth.JWT(
options.serviceAccountEmail,
options.serviceAccountPrivateKeyFile,
options.serviceAccountPrivateKey,
[GitkitClient.GITKIT_SCOPE],
'');
this.certificateCache = null;
this.certificateExpiry = null;
}
|
javascript
|
function GitkitClient(options) {
this.widgetUrl = options.widgetUrl;
this.maxTokenExpiration = 86400 * 30; // 30 days
this.audiences = [];
if (options.projectId !== undefined) {
this.audiences.push(options.projectId);
}
if (options.clientId !== undefined) {
this.audiences.push(options.clientId);
}
if (this.audiences.length == 0) {
throw new Error("Missing projectId or clientId in server configuration.");
}
this.authClient = new google.auth.JWT(
options.serviceAccountEmail,
options.serviceAccountPrivateKeyFile,
options.serviceAccountPrivateKey,
[GitkitClient.GITKIT_SCOPE],
'');
this.certificateCache = null;
this.certificateExpiry = null;
}
|
[
"function",
"GitkitClient",
"(",
"options",
")",
"{",
"this",
".",
"widgetUrl",
"=",
"options",
".",
"widgetUrl",
";",
"this",
".",
"maxTokenExpiration",
"=",
"86400",
"*",
"30",
";",
"this",
".",
"audiences",
"=",
"[",
"]",
";",
"if",
"(",
"options",
".",
"projectId",
"!==",
"undefined",
")",
"{",
"this",
".",
"audiences",
".",
"push",
"(",
"options",
".",
"projectId",
")",
";",
"}",
"if",
"(",
"options",
".",
"clientId",
"!==",
"undefined",
")",
"{",
"this",
".",
"audiences",
".",
"push",
"(",
"options",
".",
"clientId",
")",
";",
"}",
"if",
"(",
"this",
".",
"audiences",
".",
"length",
"==",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Missing projectId or clientId in server configuration.\"",
")",
";",
"}",
"this",
".",
"authClient",
"=",
"new",
"google",
".",
"auth",
".",
"JWT",
"(",
"options",
".",
"serviceAccountEmail",
",",
"options",
".",
"serviceAccountPrivateKeyFile",
",",
"options",
".",
"serviceAccountPrivateKey",
",",
"[",
"GitkitClient",
".",
"GITKIT_SCOPE",
"]",
",",
"''",
")",
";",
"this",
".",
"certificateCache",
"=",
"null",
";",
"this",
".",
"certificateExpiry",
"=",
"null",
";",
"}"
] |
Gitkit client constructor.
@param {object} options Options to be passed in
@constructor
|
[
"Gitkit",
"client",
"constructor",
"."
] |
587d3a7d0725bd45e44a9d9558d93cc440dbe07c
|
https://github.com/google/identity-toolkit-node-client/blob/587d3a7d0725bd45e44a9d9558d93cc440dbe07c/lib/gitkitclient.js#L37-L58
|
train
|
mozilla/shield-studies-addon-utils
|
examples/small-study/src/studySetup.js
|
getStudySetup
|
async function getStudySetup() {
// shallow copy
const studySetup = Object.assign({}, baseStudySetup);
studySetup.allowEnroll = await cachingFirstRunShouldAllowEnroll(studySetup);
const testingOverrides = await browser.study.getTestingOverrides();
studySetup.testing = {
variationName: testingOverrides.variationName,
firstRunTimestamp: testingOverrides.firstRunTimestamp,
expired: testingOverrides.expired,
};
return studySetup;
}
|
javascript
|
async function getStudySetup() {
// shallow copy
const studySetup = Object.assign({}, baseStudySetup);
studySetup.allowEnroll = await cachingFirstRunShouldAllowEnroll(studySetup);
const testingOverrides = await browser.study.getTestingOverrides();
studySetup.testing = {
variationName: testingOverrides.variationName,
firstRunTimestamp: testingOverrides.firstRunTimestamp,
expired: testingOverrides.expired,
};
return studySetup;
}
|
[
"async",
"function",
"getStudySetup",
"(",
")",
"{",
"const",
"studySetup",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"baseStudySetup",
")",
";",
"studySetup",
".",
"allowEnroll",
"=",
"await",
"cachingFirstRunShouldAllowEnroll",
"(",
"studySetup",
")",
";",
"const",
"testingOverrides",
"=",
"await",
"browser",
".",
"study",
".",
"getTestingOverrides",
"(",
")",
";",
"studySetup",
".",
"testing",
"=",
"{",
"variationName",
":",
"testingOverrides",
".",
"variationName",
",",
"firstRunTimestamp",
":",
"testingOverrides",
".",
"firstRunTimestamp",
",",
"expired",
":",
"testingOverrides",
".",
"expired",
",",
"}",
";",
"return",
"studySetup",
";",
"}"
] |
Augment declarative studySetup with any necessary async values
@return {object} studySetup A complete study setup object
|
[
"Augment",
"declarative",
"studySetup",
"with",
"any",
"necessary",
"async",
"values"
] |
c636c2eb2065dde43d79dcdf3f151dd926e324ac
|
https://github.com/mozilla/shield-studies-addon-utils/blob/c636c2eb2065dde43d79dcdf3f151dd926e324ac/examples/small-study/src/studySetup.js#L161-L175
|
train
|
mozilla/shield-studies-addon-utils
|
webExtensionApis/study/src/index.js
|
sendTelemetry
|
async function sendTelemetry(payload) {
utilsLogger.debug("called sendTelemetry payload");
function throwIfInvalid(obj) {
// Check: all keys and values must be strings,
for (const k in obj) {
if (typeof k !== "string")
throw new ExtensionError(`key ${k} not a string`);
if (typeof obj[k] !== "string")
throw new ExtensionError(`value ${k} ${obj[k]} not a string`);
}
return true;
}
throwIfInvalid(payload);
return studyUtils.telemetry(payload);
}
|
javascript
|
async function sendTelemetry(payload) {
utilsLogger.debug("called sendTelemetry payload");
function throwIfInvalid(obj) {
// Check: all keys and values must be strings,
for (const k in obj) {
if (typeof k !== "string")
throw new ExtensionError(`key ${k} not a string`);
if (typeof obj[k] !== "string")
throw new ExtensionError(`value ${k} ${obj[k]} not a string`);
}
return true;
}
throwIfInvalid(payload);
return studyUtils.telemetry(payload);
}
|
[
"async",
"function",
"sendTelemetry",
"(",
"payload",
")",
"{",
"utilsLogger",
".",
"debug",
"(",
"\"called sendTelemetry payload\"",
")",
";",
"function",
"throwIfInvalid",
"(",
"obj",
")",
"{",
"for",
"(",
"const",
"k",
"in",
"obj",
")",
"{",
"if",
"(",
"typeof",
"k",
"!==",
"\"string\"",
")",
"throw",
"new",
"ExtensionError",
"(",
"`",
"${",
"k",
"}",
"`",
")",
";",
"if",
"(",
"typeof",
"obj",
"[",
"k",
"]",
"!==",
"\"string\"",
")",
"throw",
"new",
"ExtensionError",
"(",
"`",
"${",
"k",
"}",
"${",
"obj",
"[",
"k",
"]",
"}",
"`",
")",
";",
"}",
"return",
"true",
";",
"}",
"throwIfInvalid",
"(",
"payload",
")",
";",
"return",
"studyUtils",
".",
"telemetry",
"(",
"payload",
")",
";",
"}"
] |
Send Telemetry using appropriate shield or pioneer methods.
shield:
- `shield-study-addon` ping, requires object string keys and string values
pioneer:
- TBD
Note:
- no conversions / coercion of data happens.
Note:
- undefined what happens if validation fails
- undefined what happens when you try to send 'shield' from 'pioneer'
TBD fix the parameters here.
@param {Object} payload Non-nested object with key strings, and key values
@returns {undefined}
|
[
"Send",
"Telemetry",
"using",
"appropriate",
"shield",
"or",
"pioneer",
"methods",
"."
] |
c636c2eb2065dde43d79dcdf3f151dd926e324ac
|
https://github.com/mozilla/shield-studies-addon-utils/blob/c636c2eb2065dde43d79dcdf3f151dd926e324ac/webExtensionApis/study/src/index.js#L325-L341
|
train
|
mozilla/shield-studies-addon-utils
|
examples/small-study/src/background.js
|
onEveryExtensionLoad
|
async function onEveryExtensionLoad() {
new StudyLifeCycleHandler();
const studySetup = await getStudySetup();
await browser.study.logger.log(["Study setup: ", studySetup]);
await browser.study.setup(studySetup);
}
|
javascript
|
async function onEveryExtensionLoad() {
new StudyLifeCycleHandler();
const studySetup = await getStudySetup();
await browser.study.logger.log(["Study setup: ", studySetup]);
await browser.study.setup(studySetup);
}
|
[
"async",
"function",
"onEveryExtensionLoad",
"(",
")",
"{",
"new",
"StudyLifeCycleHandler",
"(",
")",
";",
"const",
"studySetup",
"=",
"await",
"getStudySetup",
"(",
")",
";",
"await",
"browser",
".",
"study",
".",
"logger",
".",
"log",
"(",
"[",
"\"Study setup: \"",
",",
"studySetup",
"]",
")",
";",
"await",
"browser",
".",
"study",
".",
"setup",
"(",
"studySetup",
")",
";",
"}"
] |
Run every startup to get config and instantiate the feature
@returns {undefined}
|
[
"Run",
"every",
"startup",
"to",
"get",
"config",
"and",
"instantiate",
"the",
"feature"
] |
c636c2eb2065dde43d79dcdf3f151dd926e324ac
|
https://github.com/mozilla/shield-studies-addon-utils/blob/c636c2eb2065dde43d79dcdf3f151dd926e324ac/examples/small-study/src/background.js#L157-L163
|
train
|
mozilla/shield-studies-addon-utils
|
webExtensionApis/study/src/logger.js
|
createLogger
|
function createLogger(prefix, maxLogLevelPref, maxLogLevel = "warn") {
const ConsoleAPI = ChromeUtils.import(
"resource://gre/modules/Console.jsm",
{},
).ConsoleAPI;
return new ConsoleAPI({
prefix,
maxLogLevelPref,
maxLogLevel,
});
}
|
javascript
|
function createLogger(prefix, maxLogLevelPref, maxLogLevel = "warn") {
const ConsoleAPI = ChromeUtils.import(
"resource://gre/modules/Console.jsm",
{},
).ConsoleAPI;
return new ConsoleAPI({
prefix,
maxLogLevelPref,
maxLogLevel,
});
}
|
[
"function",
"createLogger",
"(",
"prefix",
",",
"maxLogLevelPref",
",",
"maxLogLevel",
"=",
"\"warn\"",
")",
"{",
"const",
"ConsoleAPI",
"=",
"ChromeUtils",
".",
"import",
"(",
"\"resource://gre/modules/Console.jsm\"",
",",
"{",
"}",
",",
")",
".",
"ConsoleAPI",
";",
"return",
"new",
"ConsoleAPI",
"(",
"{",
"prefix",
",",
"maxLogLevelPref",
",",
"maxLogLevel",
",",
"}",
")",
";",
"}"
] |
Creates a logger for debugging.
The pref to control this is "shieldStudy.logLevel"
@param {string} prefix - a prefix string to be printed before
the actual logged message
@param {string} maxLogLevelPref - String pref name which contains the
level to use for maxLogLevel
@param {string} maxLogLevel - level to use by default, see LOG_LEVELS in gre/modules/Console.jsm
@returns {Object} - the Console instance, see gre/modules/Console.jsm
|
[
"Creates",
"a",
"logger",
"for",
"debugging",
"."
] |
c636c2eb2065dde43d79dcdf3f151dd926e324ac
|
https://github.com/mozilla/shield-studies-addon-utils/blob/c636c2eb2065dde43d79dcdf3f151dd926e324ac/webExtensionApis/study/src/logger.js#L17-L27
|
train
|
OpenTriply/YASGUI.YASR
|
lib/jquery.csv-0.71.js
|
function(csv, options) {
// cache settings
var separator = options.separator;
var delimiter = options.delimiter;
// set initial state if it's missing
if(!options.state.rowNum) {
options.state.rowNum = 1;
}
if(!options.state.colNum) {
options.state.colNum = 1;
}
// clear initial state
var entry = [];
var state = 0;
var value = '';
function endOfValue() {
if(options.onParseValue === undefined) {
// onParseValue hook not set
entry.push(value);
} else {
var hook = options.onParseValue(value, options.state); // onParseValue Hook
// false skips the value, configurable through a hook
if(hook !== false) {
entry.push(hook);
}
}
// reset the state
value = '';
state = 0;
// update global state
options.state.colNum++;
}
// checked for a cached regEx first
if(!options.match) {
// escape regex-specific control chars
var escSeparator = RegExp.escape(separator);
var escDelimiter = RegExp.escape(delimiter);
// compile the regEx str using the custom delimiter/separator
var match = /(D|S|\n|\r|[^DS\r\n]+)/;
var matchSrc = match.source;
matchSrc = matchSrc.replace(/S/g, escSeparator);
matchSrc = matchSrc.replace(/D/g, escDelimiter);
options.match = RegExp(matchSrc, 'gm');
}
// put on your fancy pants...
// process control chars individually, use look-ahead on non-control chars
csv.replace(options.match, function (m0) {
switch (state) {
// the start of a value
case 0:
// null last value
if (m0 === separator) {
value += '';
endOfValue();
break;
}
// opening delimiter
if (m0 === delimiter) {
state = 1;
break;
}
// skip un-delimited new-lines
if (m0 === '\n' || m0 === '\r') {
break;
}
// un-delimited value
value += m0;
state = 3;
break;
// delimited input
case 1:
// second delimiter? check further
if (m0 === delimiter) {
state = 2;
break;
}
// delimited data
value += m0;
state = 1;
break;
// delimiter found in delimited input
case 2:
// escaped delimiter?
if (m0 === delimiter) {
value += m0;
state = 1;
break;
}
// null value
if (m0 === separator) {
endOfValue();
break;
}
// skip un-delimited new-lines
if (m0 === '\n' || m0 === '\r') {
break;
}
// broken paser?
throw new Error('CSVDataError: Illegal State [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']');
// un-delimited input
case 3:
// null last value
if (m0 === separator) {
endOfValue();
break;
}
// skip un-delimited new-lines
if (m0 === '\n' || m0 === '\r') {
break;
}
// non-compliant data
if (m0 === delimiter) {
throw new Error('CSVDataError: Illegal Quote [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']');
}
// broken parser?
throw new Error('CSVDataError: Illegal Data [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']');
default:
// shenanigans
throw new Error('CSVDataError: Unknown State [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']');
}
//console.log('val:' + m0 + ' state:' + state);
});
// submit the last value
endOfValue();
return entry;
}
|
javascript
|
function(csv, options) {
// cache settings
var separator = options.separator;
var delimiter = options.delimiter;
// set initial state if it's missing
if(!options.state.rowNum) {
options.state.rowNum = 1;
}
if(!options.state.colNum) {
options.state.colNum = 1;
}
// clear initial state
var entry = [];
var state = 0;
var value = '';
function endOfValue() {
if(options.onParseValue === undefined) {
// onParseValue hook not set
entry.push(value);
} else {
var hook = options.onParseValue(value, options.state); // onParseValue Hook
// false skips the value, configurable through a hook
if(hook !== false) {
entry.push(hook);
}
}
// reset the state
value = '';
state = 0;
// update global state
options.state.colNum++;
}
// checked for a cached regEx first
if(!options.match) {
// escape regex-specific control chars
var escSeparator = RegExp.escape(separator);
var escDelimiter = RegExp.escape(delimiter);
// compile the regEx str using the custom delimiter/separator
var match = /(D|S|\n|\r|[^DS\r\n]+)/;
var matchSrc = match.source;
matchSrc = matchSrc.replace(/S/g, escSeparator);
matchSrc = matchSrc.replace(/D/g, escDelimiter);
options.match = RegExp(matchSrc, 'gm');
}
// put on your fancy pants...
// process control chars individually, use look-ahead on non-control chars
csv.replace(options.match, function (m0) {
switch (state) {
// the start of a value
case 0:
// null last value
if (m0 === separator) {
value += '';
endOfValue();
break;
}
// opening delimiter
if (m0 === delimiter) {
state = 1;
break;
}
// skip un-delimited new-lines
if (m0 === '\n' || m0 === '\r') {
break;
}
// un-delimited value
value += m0;
state = 3;
break;
// delimited input
case 1:
// second delimiter? check further
if (m0 === delimiter) {
state = 2;
break;
}
// delimited data
value += m0;
state = 1;
break;
// delimiter found in delimited input
case 2:
// escaped delimiter?
if (m0 === delimiter) {
value += m0;
state = 1;
break;
}
// null value
if (m0 === separator) {
endOfValue();
break;
}
// skip un-delimited new-lines
if (m0 === '\n' || m0 === '\r') {
break;
}
// broken paser?
throw new Error('CSVDataError: Illegal State [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']');
// un-delimited input
case 3:
// null last value
if (m0 === separator) {
endOfValue();
break;
}
// skip un-delimited new-lines
if (m0 === '\n' || m0 === '\r') {
break;
}
// non-compliant data
if (m0 === delimiter) {
throw new Error('CSVDataError: Illegal Quote [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']');
}
// broken parser?
throw new Error('CSVDataError: Illegal Data [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']');
default:
// shenanigans
throw new Error('CSVDataError: Unknown State [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']');
}
//console.log('val:' + m0 + ' state:' + state);
});
// submit the last value
endOfValue();
return entry;
}
|
[
"function",
"(",
"csv",
",",
"options",
")",
"{",
"var",
"separator",
"=",
"options",
".",
"separator",
";",
"var",
"delimiter",
"=",
"options",
".",
"delimiter",
";",
"if",
"(",
"!",
"options",
".",
"state",
".",
"rowNum",
")",
"{",
"options",
".",
"state",
".",
"rowNum",
"=",
"1",
";",
"}",
"if",
"(",
"!",
"options",
".",
"state",
".",
"colNum",
")",
"{",
"options",
".",
"state",
".",
"colNum",
"=",
"1",
";",
"}",
"var",
"entry",
"=",
"[",
"]",
";",
"var",
"state",
"=",
"0",
";",
"var",
"value",
"=",
"''",
";",
"function",
"endOfValue",
"(",
")",
"{",
"if",
"(",
"options",
".",
"onParseValue",
"===",
"undefined",
")",
"{",
"entry",
".",
"push",
"(",
"value",
")",
";",
"}",
"else",
"{",
"var",
"hook",
"=",
"options",
".",
"onParseValue",
"(",
"value",
",",
"options",
".",
"state",
")",
";",
"if",
"(",
"hook",
"!==",
"false",
")",
"{",
"entry",
".",
"push",
"(",
"hook",
")",
";",
"}",
"}",
"value",
"=",
"''",
";",
"state",
"=",
"0",
";",
"options",
".",
"state",
".",
"colNum",
"++",
";",
"}",
"if",
"(",
"!",
"options",
".",
"match",
")",
"{",
"var",
"escSeparator",
"=",
"RegExp",
".",
"escape",
"(",
"separator",
")",
";",
"var",
"escDelimiter",
"=",
"RegExp",
".",
"escape",
"(",
"delimiter",
")",
";",
"var",
"match",
"=",
"/",
"(D|S|\\n|\\r|[^DS\\r\\n]+)",
"/",
";",
"var",
"matchSrc",
"=",
"match",
".",
"source",
";",
"matchSrc",
"=",
"matchSrc",
".",
"replace",
"(",
"/",
"S",
"/",
"g",
",",
"escSeparator",
")",
";",
"matchSrc",
"=",
"matchSrc",
".",
"replace",
"(",
"/",
"D",
"/",
"g",
",",
"escDelimiter",
")",
";",
"options",
".",
"match",
"=",
"RegExp",
"(",
"matchSrc",
",",
"'gm'",
")",
";",
"}",
"csv",
".",
"replace",
"(",
"options",
".",
"match",
",",
"function",
"(",
"m0",
")",
"{",
"switch",
"(",
"state",
")",
"{",
"case",
"0",
":",
"if",
"(",
"m0",
"===",
"separator",
")",
"{",
"value",
"+=",
"''",
";",
"endOfValue",
"(",
")",
";",
"break",
";",
"}",
"if",
"(",
"m0",
"===",
"delimiter",
")",
"{",
"state",
"=",
"1",
";",
"break",
";",
"}",
"if",
"(",
"m0",
"===",
"'\\n'",
"||",
"\\n",
")",
"m0",
"===",
"'\\r'",
"\\r",
"{",
"break",
";",
"}",
"value",
"+=",
"m0",
";",
"state",
"=",
"3",
";",
"break",
";",
"case",
"1",
":",
"if",
"(",
"m0",
"===",
"delimiter",
")",
"{",
"state",
"=",
"2",
";",
"break",
";",
"}",
"value",
"+=",
"m0",
";",
"state",
"=",
"1",
";",
"break",
";",
"case",
"2",
":",
"if",
"(",
"m0",
"===",
"delimiter",
")",
"{",
"value",
"+=",
"m0",
";",
"state",
"=",
"1",
";",
"break",
";",
"}",
"if",
"(",
"m0",
"===",
"separator",
")",
"{",
"endOfValue",
"(",
")",
";",
"break",
";",
"}",
"if",
"(",
"m0",
"===",
"'\\n'",
"||",
"\\n",
")",
"m0",
"===",
"'\\r'",
"\\r",
"}",
"}",
")",
";",
"{",
"break",
";",
"}",
"throw",
"new",
"Error",
"(",
"'CSVDataError: Illegal State [Row:'",
"+",
"options",
".",
"state",
".",
"rowNum",
"+",
"'][Col:'",
"+",
"options",
".",
"state",
".",
"colNum",
"+",
"']'",
")",
";",
"}"
] |
a csv entry parser
|
[
"a",
"csv",
"entry",
"parser"
] |
4de0a4e3b182c23b63897376ab9fb141fea17af8
|
https://github.com/OpenTriply/YASGUI.YASR/blob/4de0a4e3b182c23b63897376ab9fb141fea17af8/lib/jquery.csv-0.71.js#L449-L585
|
train
|
|
OpenTriply/YASGUI.YASR
|
lib/colResizable-1.4.js
|
function(t,i,isOver){
var inc = drag.x-drag.l, c = t.c[i], c2 = t.c[i+1];
var w = c.w + inc; var w2= c2.w- inc; //their new width is obtained
c.width( w + PX); c2.width(w2 + PX); //and set
t.cg.eq(i).width( w + PX); t.cg.eq(i+1).width( w2 + PX);
if(isOver){c.w=w; c2.w=w2;}
}
|
javascript
|
function(t,i,isOver){
var inc = drag.x-drag.l, c = t.c[i], c2 = t.c[i+1];
var w = c.w + inc; var w2= c2.w- inc; //their new width is obtained
c.width( w + PX); c2.width(w2 + PX); //and set
t.cg.eq(i).width( w + PX); t.cg.eq(i+1).width( w2 + PX);
if(isOver){c.w=w; c2.w=w2;}
}
|
[
"function",
"(",
"t",
",",
"i",
",",
"isOver",
")",
"{",
"var",
"inc",
"=",
"drag",
".",
"x",
"-",
"drag",
".",
"l",
",",
"c",
"=",
"t",
".",
"c",
"[",
"i",
"]",
",",
"c2",
"=",
"t",
".",
"c",
"[",
"i",
"+",
"1",
"]",
";",
"var",
"w",
"=",
"c",
".",
"w",
"+",
"inc",
";",
"var",
"w2",
"=",
"c2",
".",
"w",
"-",
"inc",
";",
"c",
".",
"width",
"(",
"w",
"+",
"PX",
")",
";",
"c2",
".",
"width",
"(",
"w2",
"+",
"PX",
")",
";",
"t",
".",
"cg",
".",
"eq",
"(",
"i",
")",
".",
"width",
"(",
"w",
"+",
"PX",
")",
";",
"t",
".",
"cg",
".",
"eq",
"(",
"i",
"+",
"1",
")",
".",
"width",
"(",
"w2",
"+",
"PX",
")",
";",
"if",
"(",
"isOver",
")",
"{",
"c",
".",
"w",
"=",
"w",
";",
"c2",
".",
"w",
"=",
"w2",
";",
"}",
"}"
] |
This function updates column's width according to the horizontal position increment of the grip being
dragged. The function can be called while dragging if liveDragging is enabled and also from the onGripDragOver
event handler to synchronize grip's position with their related columns.
@param {jQuery ref} t - table object
@param {nunmber} i - index of the grip being dragged
@param {bool} isOver - to identify when the function is being called from the onGripDragOver event
|
[
"This",
"function",
"updates",
"column",
"s",
"width",
"according",
"to",
"the",
"horizontal",
"position",
"increment",
"of",
"the",
"grip",
"being",
"dragged",
".",
"The",
"function",
"can",
"be",
"called",
"while",
"dragging",
"if",
"liveDragging",
"is",
"enabled",
"and",
"also",
"from",
"the",
"onGripDragOver",
"event",
"handler",
"to",
"synchronize",
"grip",
"s",
"position",
"with",
"their",
"related",
"columns",
"."
] |
4de0a4e3b182c23b63897376ab9fb141fea17af8
|
https://github.com/OpenTriply/YASGUI.YASR/blob/4de0a4e3b182c23b63897376ab9fb141fea17af8/lib/colResizable-1.4.js#L169-L175
|
train
|
|
OpenTriply/YASGUI.YASR
|
lib/colResizable-1.4.js
|
function(e){
d.unbind('touchend.'+SIGNATURE+' mouseup.'+SIGNATURE).unbind('touchmove.'+SIGNATURE+' mousemove.'+SIGNATURE);
$("head :last-child").remove(); //remove the dragging cursor style
if(!drag) return;
drag.removeClass(drag.t.opt.draggingClass); //remove the grip's dragging css-class
var t = drag.t;
var cb = t.opt.onResize; //get some values
if(drag.x){ //only if the column width has been changed
syncCols(t,drag.i, true); syncGrips(t); //the columns and grips are updated
if (cb) { e.currentTarget = t[0]; cb(e); } //if there is a callback function, it is fired
}
if(t.p && S) memento(t); //if postbackSafe is enabled and there is sessionStorage support, the new layout is serialized and stored
drag = null; //since the grip's dragging is over
}
|
javascript
|
function(e){
d.unbind('touchend.'+SIGNATURE+' mouseup.'+SIGNATURE).unbind('touchmove.'+SIGNATURE+' mousemove.'+SIGNATURE);
$("head :last-child").remove(); //remove the dragging cursor style
if(!drag) return;
drag.removeClass(drag.t.opt.draggingClass); //remove the grip's dragging css-class
var t = drag.t;
var cb = t.opt.onResize; //get some values
if(drag.x){ //only if the column width has been changed
syncCols(t,drag.i, true); syncGrips(t); //the columns and grips are updated
if (cb) { e.currentTarget = t[0]; cb(e); } //if there is a callback function, it is fired
}
if(t.p && S) memento(t); //if postbackSafe is enabled and there is sessionStorage support, the new layout is serialized and stored
drag = null; //since the grip's dragging is over
}
|
[
"function",
"(",
"e",
")",
"{",
"d",
".",
"unbind",
"(",
"'touchend.'",
"+",
"SIGNATURE",
"+",
"' mouseup.'",
"+",
"SIGNATURE",
")",
".",
"unbind",
"(",
"'touchmove.'",
"+",
"SIGNATURE",
"+",
"' mousemove.'",
"+",
"SIGNATURE",
")",
";",
"$",
"(",
"\"head :last-child\"",
")",
".",
"remove",
"(",
")",
";",
"if",
"(",
"!",
"drag",
")",
"return",
";",
"drag",
".",
"removeClass",
"(",
"drag",
".",
"t",
".",
"opt",
".",
"draggingClass",
")",
";",
"var",
"t",
"=",
"drag",
".",
"t",
";",
"var",
"cb",
"=",
"t",
".",
"opt",
".",
"onResize",
";",
"if",
"(",
"drag",
".",
"x",
")",
"{",
"syncCols",
"(",
"t",
",",
"drag",
".",
"i",
",",
"true",
")",
";",
"syncGrips",
"(",
"t",
")",
";",
"if",
"(",
"cb",
")",
"{",
"e",
".",
"currentTarget",
"=",
"t",
"[",
"0",
"]",
";",
"cb",
"(",
"e",
")",
";",
"}",
"}",
"if",
"(",
"t",
".",
"p",
"&&",
"S",
")",
"memento",
"(",
"t",
")",
";",
"drag",
"=",
"null",
";",
"}"
] |
Event handler fired when the dragging is over, updating table layout
|
[
"Event",
"handler",
"fired",
"when",
"the",
"dragging",
"is",
"over",
"updating",
"table",
"layout"
] |
4de0a4e3b182c23b63897376ab9fb141fea17af8
|
https://github.com/OpenTriply/YASGUI.YASR/blob/4de0a4e3b182c23b63897376ab9fb141fea17af8/lib/colResizable-1.4.js#L215-L229
|
train
|
|
OpenTriply/YASGUI.YASR
|
lib/colResizable-1.4.js
|
function(){
for(t in tables){
var t = tables[t], i, mw=0;
t.removeClass(SIGNATURE); //firefox doesnt like layout-fixed in some cases
if (t.w != t.width()) { //if the the table's width has changed
t.w = t.width(); //its new value is kept
for(i=0; i<t.ln; i++) mw+= t.c[i].w; //the active cells area is obtained
//cell rendering is not as trivial as it might seem, and it is slightly different for
//each browser. In the begining i had a big switch for each browser, but since the code
//was extremelly ugly now I use a different approach with several reflows. This works
//pretty well but it's a bit slower. For now, lets keep things simple...
for(i=0; i<t.ln; i++) t.c[i].css("width", M.round(1000*t.c[i].w/mw)/10 + "%").l=true;
//c.l locks the column, telling us that its c.w is outdated
}
syncGrips(t.addClass(SIGNATURE));
}
}
|
javascript
|
function(){
for(t in tables){
var t = tables[t], i, mw=0;
t.removeClass(SIGNATURE); //firefox doesnt like layout-fixed in some cases
if (t.w != t.width()) { //if the the table's width has changed
t.w = t.width(); //its new value is kept
for(i=0; i<t.ln; i++) mw+= t.c[i].w; //the active cells area is obtained
//cell rendering is not as trivial as it might seem, and it is slightly different for
//each browser. In the begining i had a big switch for each browser, but since the code
//was extremelly ugly now I use a different approach with several reflows. This works
//pretty well but it's a bit slower. For now, lets keep things simple...
for(i=0; i<t.ln; i++) t.c[i].css("width", M.round(1000*t.c[i].w/mw)/10 + "%").l=true;
//c.l locks the column, telling us that its c.w is outdated
}
syncGrips(t.addClass(SIGNATURE));
}
}
|
[
"function",
"(",
")",
"{",
"for",
"(",
"t",
"in",
"tables",
")",
"{",
"var",
"t",
"=",
"tables",
"[",
"t",
"]",
",",
"i",
",",
"mw",
"=",
"0",
";",
"t",
".",
"removeClass",
"(",
"SIGNATURE",
")",
";",
"if",
"(",
"t",
".",
"w",
"!=",
"t",
".",
"width",
"(",
")",
")",
"{",
"t",
".",
"w",
"=",
"t",
".",
"width",
"(",
")",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"t",
".",
"ln",
";",
"i",
"++",
")",
"mw",
"+=",
"t",
".",
"c",
"[",
"i",
"]",
".",
"w",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"t",
".",
"ln",
";",
"i",
"++",
")",
"t",
".",
"c",
"[",
"i",
"]",
".",
"css",
"(",
"\"width\"",
",",
"M",
".",
"round",
"(",
"1000",
"*",
"t",
".",
"c",
"[",
"i",
"]",
".",
"w",
"/",
"mw",
")",
"/",
"10",
"+",
"\"%\"",
")",
".",
"l",
"=",
"true",
";",
"}",
"syncGrips",
"(",
"t",
".",
"addClass",
"(",
"SIGNATURE",
")",
")",
";",
"}",
"}"
] |
Event handler fired when the browser is resized. The main purpose of this function is to update
table layout according to the browser's size synchronizing related grips
|
[
"Event",
"handler",
"fired",
"when",
"the",
"browser",
"is",
"resized",
".",
"The",
"main",
"purpose",
"of",
"this",
"function",
"is",
"to",
"update",
"table",
"layout",
"according",
"to",
"the",
"browser",
"s",
"size",
"synchronizing",
"related",
"grips"
] |
4de0a4e3b182c23b63897376ab9fb141fea17af8
|
https://github.com/OpenTriply/YASGUI.YASR/blob/4de0a4e3b182c23b63897376ab9fb141fea17af8/lib/colResizable-1.4.js#L258-L274
|
train
|
|
OpenTriply/YASGUI.YASR
|
src/table.js
|
function(oSettings) {
//trick to show row numbers
for (var i = 0; i < oSettings.aiDisplay.length; i++) {
$("td:eq(0)", oSettings.aoData[oSettings.aiDisplay[i]].nTr).html(i + 1);
}
//Hide pagination when we have a single page
var activePaginateButton = false;
$(oSettings.nTableWrapper).find(".paginate_button").each(function() {
if ($(this).attr("class").indexOf("current") == -1 && $(this).attr("class").indexOf("disabled") == -1) {
activePaginateButton = true;
}
});
if (activePaginateButton) {
$(oSettings.nTableWrapper).find(".dataTables_paginate").show();
} else {
$(oSettings.nTableWrapper).find(".dataTables_paginate").hide();
}
}
|
javascript
|
function(oSettings) {
//trick to show row numbers
for (var i = 0; i < oSettings.aiDisplay.length; i++) {
$("td:eq(0)", oSettings.aoData[oSettings.aiDisplay[i]].nTr).html(i + 1);
}
//Hide pagination when we have a single page
var activePaginateButton = false;
$(oSettings.nTableWrapper).find(".paginate_button").each(function() {
if ($(this).attr("class").indexOf("current") == -1 && $(this).attr("class").indexOf("disabled") == -1) {
activePaginateButton = true;
}
});
if (activePaginateButton) {
$(oSettings.nTableWrapper).find(".dataTables_paginate").show();
} else {
$(oSettings.nTableWrapper).find(".dataTables_paginate").hide();
}
}
|
[
"function",
"(",
"oSettings",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"oSettings",
".",
"aiDisplay",
".",
"length",
";",
"i",
"++",
")",
"{",
"$",
"(",
"\"td:eq(0)\"",
",",
"oSettings",
".",
"aoData",
"[",
"oSettings",
".",
"aiDisplay",
"[",
"i",
"]",
"]",
".",
"nTr",
")",
".",
"html",
"(",
"i",
"+",
"1",
")",
";",
"}",
"var",
"activePaginateButton",
"=",
"false",
";",
"$",
"(",
"oSettings",
".",
"nTableWrapper",
")",
".",
"find",
"(",
"\".paginate_button\"",
")",
".",
"each",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"$",
"(",
"this",
")",
".",
"attr",
"(",
"\"class\"",
")",
".",
"indexOf",
"(",
"\"current\"",
")",
"==",
"-",
"1",
"&&",
"$",
"(",
"this",
")",
".",
"attr",
"(",
"\"class\"",
")",
".",
"indexOf",
"(",
"\"disabled\"",
")",
"==",
"-",
"1",
")",
"{",
"activePaginateButton",
"=",
"true",
";",
"}",
"}",
")",
";",
"if",
"(",
"activePaginateButton",
")",
"{",
"$",
"(",
"oSettings",
".",
"nTableWrapper",
")",
".",
"find",
"(",
"\".dataTables_paginate\"",
")",
".",
"show",
"(",
")",
";",
"}",
"else",
"{",
"$",
"(",
"oSettings",
".",
"nTableWrapper",
")",
".",
"find",
"(",
"\".dataTables_paginate\"",
")",
".",
"hide",
"(",
")",
";",
"}",
"}"
] |
how to show the pagination options
|
[
"how",
"to",
"show",
"the",
"pagination",
"options"
] |
4de0a4e3b182c23b63897376ab9fb141fea17af8
|
https://github.com/OpenTriply/YASGUI.YASR/blob/4de0a4e3b182c23b63897376ab9fb141fea17af8/src/table.js#L357-L375
|
train
|
|
OpenCerts/open-attestation
|
src/signature/merkle/merkle.js
|
getLayers
|
function getLayers(elements) {
if (elements.length === 0) {
return [[""]];
}
const layers = [];
layers.push(elements);
while (layers[layers.length - 1].length > 1) {
layers.push(getNextLayer(layers[layers.length - 1]));
}
return layers;
}
|
javascript
|
function getLayers(elements) {
if (elements.length === 0) {
return [[""]];
}
const layers = [];
layers.push(elements);
while (layers[layers.length - 1].length > 1) {
layers.push(getNextLayer(layers[layers.length - 1]));
}
return layers;
}
|
[
"function",
"getLayers",
"(",
"elements",
")",
"{",
"if",
"(",
"elements",
".",
"length",
"===",
"0",
")",
"{",
"return",
"[",
"[",
"\"\"",
"]",
"]",
";",
"}",
"const",
"layers",
"=",
"[",
"]",
";",
"layers",
".",
"push",
"(",
"elements",
")",
";",
"while",
"(",
"layers",
"[",
"layers",
".",
"length",
"-",
"1",
"]",
".",
"length",
">",
"1",
")",
"{",
"layers",
".",
"push",
"(",
"getNextLayer",
"(",
"layers",
"[",
"layers",
".",
"length",
"-",
"1",
"]",
")",
")",
";",
"}",
"return",
"layers",
";",
"}"
] |
This function procduces the hashes and the merkle tree
If there are no elements, return empty array of array
@param {*} elements
|
[
"This",
"function",
"procduces",
"the",
"hashes",
"and",
"the",
"merkle",
"tree",
"If",
"there",
"are",
"no",
"elements",
"return",
"empty",
"array",
"of",
"array"
] |
480d534fc6a1f4be4a993dcf5ccea89aef3986d4
|
https://github.com/OpenCerts/open-attestation/blob/480d534fc6a1f4be4a993dcf5ccea89aef3986d4/src/signature/merkle/merkle.js#L24-L34
|
train
|
OpenCerts/open-attestation
|
src/signature/merkle/merkle.js
|
getProof
|
function getProof(index, layers) {
let i = index;
const proof = layers.reduce((current, layer) => {
const pair = getPair(i, layer);
if (pair) {
current.push(pair);
}
i = Math.floor(i / 2); // finds the index of the parent of the current node
return current;
}, []);
return proof;
}
|
javascript
|
function getProof(index, layers) {
let i = index;
const proof = layers.reduce((current, layer) => {
const pair = getPair(i, layer);
if (pair) {
current.push(pair);
}
i = Math.floor(i / 2); // finds the index of the parent of the current node
return current;
}, []);
return proof;
}
|
[
"function",
"getProof",
"(",
"index",
",",
"layers",
")",
"{",
"let",
"i",
"=",
"index",
";",
"const",
"proof",
"=",
"layers",
".",
"reduce",
"(",
"(",
"current",
",",
"layer",
")",
"=>",
"{",
"const",
"pair",
"=",
"getPair",
"(",
"i",
",",
"layer",
")",
";",
"if",
"(",
"pair",
")",
"{",
"current",
".",
"push",
"(",
"pair",
")",
";",
"}",
"i",
"=",
"Math",
".",
"floor",
"(",
"i",
"/",
"2",
")",
";",
"return",
"current",
";",
"}",
",",
"[",
"]",
")",
";",
"return",
"proof",
";",
"}"
] |
Finds all the "uncle" nodes required to prove a given element in the merkle tree
@param {*} index
@param {*} layers
|
[
"Finds",
"all",
"the",
"uncle",
"nodes",
"required",
"to",
"prove",
"a",
"given",
"element",
"in",
"the",
"merkle",
"tree"
] |
480d534fc6a1f4be4a993dcf5ccea89aef3986d4
|
https://github.com/OpenCerts/open-attestation/blob/480d534fc6a1f4be4a993dcf5ccea89aef3986d4/src/signature/merkle/merkle.js#L68-L79
|
train
|
BlueOakJS/blueoak-server
|
handlers/_swagger.js
|
containsMultipartFormData
|
function containsMultipartFormData(api) {
if (_.includes(api.consumes, 'multipart/form-data')) {
return true;
}
var foundMultipartData = false;
_.forEach(_.keys(api.paths), function (path) {
var pathData = api.paths[path];
_.forEach(_.keys(pathData), function (method) {
if (_.includes(pathData[method].consumes, 'multipart/form-data')) {
foundMultipartData = true;
return;
}
});
if (foundMultipartData) {
return;
}
});
return foundMultipartData;
}
|
javascript
|
function containsMultipartFormData(api) {
if (_.includes(api.consumes, 'multipart/form-data')) {
return true;
}
var foundMultipartData = false;
_.forEach(_.keys(api.paths), function (path) {
var pathData = api.paths[path];
_.forEach(_.keys(pathData), function (method) {
if (_.includes(pathData[method].consumes, 'multipart/form-data')) {
foundMultipartData = true;
return;
}
});
if (foundMultipartData) {
return;
}
});
return foundMultipartData;
}
|
[
"function",
"containsMultipartFormData",
"(",
"api",
")",
"{",
"if",
"(",
"_",
".",
"includes",
"(",
"api",
".",
"consumes",
",",
"'multipart/form-data'",
")",
")",
"{",
"return",
"true",
";",
"}",
"var",
"foundMultipartData",
"=",
"false",
";",
"_",
".",
"forEach",
"(",
"_",
".",
"keys",
"(",
"api",
".",
"paths",
")",
",",
"function",
"(",
"path",
")",
"{",
"var",
"pathData",
"=",
"api",
".",
"paths",
"[",
"path",
"]",
";",
"_",
".",
"forEach",
"(",
"_",
".",
"keys",
"(",
"pathData",
")",
",",
"function",
"(",
"method",
")",
"{",
"if",
"(",
"_",
".",
"includes",
"(",
"pathData",
"[",
"method",
"]",
".",
"consumes",
",",
"'multipart/form-data'",
")",
")",
"{",
"foundMultipartData",
"=",
"true",
";",
"return",
";",
"}",
"}",
")",
";",
"if",
"(",
"foundMultipartData",
")",
"{",
"return",
";",
"}",
"}",
")",
";",
"return",
"foundMultipartData",
";",
"}"
] |
determine if something in the spec uses formdata The entire api can contain a consume field, or just an individual route
|
[
"determine",
"if",
"something",
"in",
"the",
"spec",
"uses",
"formdata",
"The",
"entire",
"api",
"can",
"contain",
"a",
"consume",
"field",
"or",
"just",
"an",
"individual",
"route"
] |
7e82bb64aac7064dc998db8f2104529fcdb579f9
|
https://github.com/BlueOakJS/blueoak-server/blob/7e82bb64aac7064dc998db8f2104529fcdb579f9/handlers/_swagger.js#L172-L193
|
train
|
BlueOakJS/blueoak-server
|
handlers/_swagger.js
|
handleMulterConfig
|
function handleMulterConfig(multerConfig, logger, serviceLoader) {
// Special handling of storage
var storageString = _.get(multerConfig, 'storage');
if (storageString) {
var multerStorage;
if (storageString === MULTER_MEMORY_STORAGE) {
// simple memory storage
logger.debug('loading simple multer memoryStorage');
multerStorage = multer.memoryStorage();
} else {
// otherwise try and load the service for custom multer storage engine
logger.debug('loading custom multer storage service');
var multerService = serviceLoader.get(storageString);
if (!multerService) {
logger.warn('Multer config "storage" property must either be "' + MULTER_MEMORY_STORAGE + '"');
logger.warn('or the name of a service that returns a multer storage engine');
} else {
multerStorage = multerService.storage;
}
}
_.set(multerConfig, 'storage', multerStorage);
}
return multerConfig;
}
|
javascript
|
function handleMulterConfig(multerConfig, logger, serviceLoader) {
// Special handling of storage
var storageString = _.get(multerConfig, 'storage');
if (storageString) {
var multerStorage;
if (storageString === MULTER_MEMORY_STORAGE) {
// simple memory storage
logger.debug('loading simple multer memoryStorage');
multerStorage = multer.memoryStorage();
} else {
// otherwise try and load the service for custom multer storage engine
logger.debug('loading custom multer storage service');
var multerService = serviceLoader.get(storageString);
if (!multerService) {
logger.warn('Multer config "storage" property must either be "' + MULTER_MEMORY_STORAGE + '"');
logger.warn('or the name of a service that returns a multer storage engine');
} else {
multerStorage = multerService.storage;
}
}
_.set(multerConfig, 'storage', multerStorage);
}
return multerConfig;
}
|
[
"function",
"handleMulterConfig",
"(",
"multerConfig",
",",
"logger",
",",
"serviceLoader",
")",
"{",
"var",
"storageString",
"=",
"_",
".",
"get",
"(",
"multerConfig",
",",
"'storage'",
")",
";",
"if",
"(",
"storageString",
")",
"{",
"var",
"multerStorage",
";",
"if",
"(",
"storageString",
"===",
"MULTER_MEMORY_STORAGE",
")",
"{",
"logger",
".",
"debug",
"(",
"'loading simple multer memoryStorage'",
")",
";",
"multerStorage",
"=",
"multer",
".",
"memoryStorage",
"(",
")",
";",
"}",
"else",
"{",
"logger",
".",
"debug",
"(",
"'loading custom multer storage service'",
")",
";",
"var",
"multerService",
"=",
"serviceLoader",
".",
"get",
"(",
"storageString",
")",
";",
"if",
"(",
"!",
"multerService",
")",
"{",
"logger",
".",
"warn",
"(",
"'Multer config \"storage\" property must either be \"'",
"+",
"MULTER_MEMORY_STORAGE",
"+",
"'\"'",
")",
";",
"logger",
".",
"warn",
"(",
"'or the name of a service that returns a multer storage engine'",
")",
";",
"}",
"else",
"{",
"multerStorage",
"=",
"multerService",
".",
"storage",
";",
"}",
"}",
"_",
".",
"set",
"(",
"multerConfig",
",",
"'storage'",
",",
"multerStorage",
")",
";",
"}",
"return",
"multerConfig",
";",
"}"
] |
Checks the multer config if the storage property is set to either the memoryStorage enum or the name of a custom multerService implementing a multer storage engine.
|
[
"Checks",
"the",
"multer",
"config",
"if",
"the",
"storage",
"property",
"is",
"set",
"to",
"either",
"the",
"memoryStorage",
"enum",
"or",
"the",
"name",
"of",
"a",
"custom",
"multerService",
"implementing",
"a",
"multer",
"storage",
"engine",
"."
] |
7e82bb64aac7064dc998db8f2104529fcdb579f9
|
https://github.com/BlueOakJS/blueoak-server/blob/7e82bb64aac7064dc998db8f2104529fcdb579f9/handlers/_swagger.js#L243-L267
|
train
|
BlueOakJS/blueoak-server
|
handlers/_swagger.js
|
setDefaultQueryParams
|
function setDefaultQueryParams(req, data, logger) {
var parameters = _.toArray(data.parameters);
for (var i = 0; i < parameters.length; i++) {
var parm = parameters[i];
if (parm.in === 'query') {
if (!_.isUndefined(parm.default) && _.isUndefined(req.query[parm.name])) {
req.query[parm.name] = swaggerUtil.cast(parm, parm.default);
}
}
}
}
|
javascript
|
function setDefaultQueryParams(req, data, logger) {
var parameters = _.toArray(data.parameters);
for (var i = 0; i < parameters.length; i++) {
var parm = parameters[i];
if (parm.in === 'query') {
if (!_.isUndefined(parm.default) && _.isUndefined(req.query[parm.name])) {
req.query[parm.name] = swaggerUtil.cast(parm, parm.default);
}
}
}
}
|
[
"function",
"setDefaultQueryParams",
"(",
"req",
",",
"data",
",",
"logger",
")",
"{",
"var",
"parameters",
"=",
"_",
".",
"toArray",
"(",
"data",
".",
"parameters",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"parameters",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"parm",
"=",
"parameters",
"[",
"i",
"]",
";",
"if",
"(",
"parm",
".",
"in",
"===",
"'query'",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isUndefined",
"(",
"parm",
".",
"default",
")",
"&&",
"_",
".",
"isUndefined",
"(",
"req",
".",
"query",
"[",
"parm",
".",
"name",
"]",
")",
")",
"{",
"req",
".",
"query",
"[",
"parm",
".",
"name",
"]",
"=",
"swaggerUtil",
".",
"cast",
"(",
"parm",
",",
"parm",
".",
"default",
")",
";",
"}",
"}",
"}",
"}"
] |
Any parameter with a default that's not already defined will be set to the default value
|
[
"Any",
"parameter",
"with",
"a",
"default",
"that",
"s",
"not",
"already",
"defined",
"will",
"be",
"set",
"to",
"the",
"default",
"value"
] |
7e82bb64aac7064dc998db8f2104529fcdb579f9
|
https://github.com/BlueOakJS/blueoak-server/blob/7e82bb64aac7064dc998db8f2104529fcdb579f9/handlers/_swagger.js#L425-L435
|
train
|
BlueOakJS/blueoak-server
|
lib/project.js
|
function(callback) {
var toInit = ['config', 'logger'];
loader.loadServices(path.resolve(serverRoot, 'services'));
injectDependencies(loader);
loader.init(toInit, function(err) {
callback(err);
});
}
|
javascript
|
function(callback) {
var toInit = ['config', 'logger'];
loader.loadServices(path.resolve(serverRoot, 'services'));
injectDependencies(loader);
loader.init(toInit, function(err) {
callback(err);
});
}
|
[
"function",
"(",
"callback",
")",
"{",
"var",
"toInit",
"=",
"[",
"'config'",
",",
"'logger'",
"]",
";",
"loader",
".",
"loadServices",
"(",
"path",
".",
"resolve",
"(",
"serverRoot",
",",
"'services'",
")",
")",
";",
"injectDependencies",
"(",
"loader",
")",
";",
"loader",
".",
"init",
"(",
"toInit",
",",
"function",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"}",
")",
";",
"}"
] |
Loads the config and logger services This should always be called before initProject For the master process, only bootstrap will be called
|
[
"Loads",
"the",
"config",
"and",
"logger",
"services",
"This",
"should",
"always",
"be",
"called",
"before",
"initProject",
"For",
"the",
"master",
"process",
"only",
"bootstrap",
"will",
"be",
"called"
] |
7e82bb64aac7064dc998db8f2104529fcdb579f9
|
https://github.com/BlueOakJS/blueoak-server/blob/7e82bb64aac7064dc998db8f2104529fcdb579f9/lib/project.js#L17-L25
|
train
|
|
BlueOakJS/blueoak-server
|
lib/project.js
|
injectDependencies
|
function injectDependencies(serviceLoader) {
var EventEmitter = require('events').EventEmitter;
serviceLoader.inject('events', new EventEmitter());
//inject itself so that services can directly use the service loader
serviceLoader.inject('serviceLoader', serviceLoader);
//app will be injected by middleware, so this is a placeholder to force our dependency calculations to be correct
serviceLoader.inject('app', {}, ['middleware']);
}
|
javascript
|
function injectDependencies(serviceLoader) {
var EventEmitter = require('events').EventEmitter;
serviceLoader.inject('events', new EventEmitter());
//inject itself so that services can directly use the service loader
serviceLoader.inject('serviceLoader', serviceLoader);
//app will be injected by middleware, so this is a placeholder to force our dependency calculations to be correct
serviceLoader.inject('app', {}, ['middleware']);
}
|
[
"function",
"injectDependencies",
"(",
"serviceLoader",
")",
"{",
"var",
"EventEmitter",
"=",
"require",
"(",
"'events'",
")",
".",
"EventEmitter",
";",
"serviceLoader",
".",
"inject",
"(",
"'events'",
",",
"new",
"EventEmitter",
"(",
")",
")",
";",
"serviceLoader",
".",
"inject",
"(",
"'serviceLoader'",
",",
"serviceLoader",
")",
";",
"serviceLoader",
".",
"inject",
"(",
"'app'",
",",
"{",
"}",
",",
"[",
"'middleware'",
"]",
")",
";",
"}"
] |
Injects items into the loader that aren't loaded through the normal services mechanism
|
[
"Injects",
"items",
"into",
"the",
"loader",
"that",
"aren",
"t",
"loaded",
"through",
"the",
"normal",
"services",
"mechanism"
] |
7e82bb64aac7064dc998db8f2104529fcdb579f9
|
https://github.com/BlueOakJS/blueoak-server/blob/7e82bb64aac7064dc998db8f2104529fcdb579f9/lib/project.js#L69-L79
|
train
|
BlueOakJS/blueoak-server
|
index.js
|
function (err) {
var message = {cmd: 'startupComplete', pid: process.pid};
if (err) {
console.warn(err.stack);
message.error = err.message;
}
process.send(message);
}
|
javascript
|
function (err) {
var message = {cmd: 'startupComplete', pid: process.pid};
if (err) {
console.warn(err.stack);
message.error = err.message;
}
process.send(message);
}
|
[
"function",
"(",
"err",
")",
"{",
"var",
"message",
"=",
"{",
"cmd",
":",
"'startupComplete'",
",",
"pid",
":",
"process",
".",
"pid",
"}",
";",
"if",
"(",
"err",
")",
"{",
"console",
".",
"warn",
"(",
"err",
".",
"stack",
")",
";",
"message",
".",
"error",
"=",
"err",
".",
"message",
";",
"}",
"process",
".",
"send",
"(",
"message",
")",
";",
"}"
] |
Use this callback to notify back to the cluster master that we're started, either successfully or with error
|
[
"Use",
"this",
"callback",
"to",
"notify",
"back",
"to",
"the",
"cluster",
"master",
"that",
"we",
"re",
"started",
"either",
"successfully",
"or",
"with",
"error"
] |
7e82bb64aac7064dc998db8f2104529fcdb579f9
|
https://github.com/BlueOakJS/blueoak-server/blob/7e82bb64aac7064dc998db8f2104529fcdb579f9/index.js#L303-L310
|
train
|
|
BlueOakJS/blueoak-server
|
auth/google-oauth.js
|
setAuthCodeOnReq
|
function setAuthCodeOnReq(req, res, next) {
if (req.query.code) {
req.code = req.query.code;
debug('Found auth code %s on query param', req.code);
return next();
}
//look for something like {"code": "..."}
if (req.body.code) {
req.code = req.body.code;
debug('Found auth code %s in JSON body', req.code);
return next();
}
getRawBody(req, function(err, string) {
if (err) {
debug(err);
}
if (string.toString().length > 0) {
req.code = string.toString();
debug('Found auth code %s in body', req.code);
}
next();
});
}
|
javascript
|
function setAuthCodeOnReq(req, res, next) {
if (req.query.code) {
req.code = req.query.code;
debug('Found auth code %s on query param', req.code);
return next();
}
//look for something like {"code": "..."}
if (req.body.code) {
req.code = req.body.code;
debug('Found auth code %s in JSON body', req.code);
return next();
}
getRawBody(req, function(err, string) {
if (err) {
debug(err);
}
if (string.toString().length > 0) {
req.code = string.toString();
debug('Found auth code %s in body', req.code);
}
next();
});
}
|
[
"function",
"setAuthCodeOnReq",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"req",
".",
"query",
".",
"code",
")",
"{",
"req",
".",
"code",
"=",
"req",
".",
"query",
".",
"code",
";",
"debug",
"(",
"'Found auth code %s on query param'",
",",
"req",
".",
"code",
")",
";",
"return",
"next",
"(",
")",
";",
"}",
"if",
"(",
"req",
".",
"body",
".",
"code",
")",
"{",
"req",
".",
"code",
"=",
"req",
".",
"body",
".",
"code",
";",
"debug",
"(",
"'Found auth code %s in JSON body'",
",",
"req",
".",
"code",
")",
";",
"return",
"next",
"(",
")",
";",
"}",
"getRawBody",
"(",
"req",
",",
"function",
"(",
"err",
",",
"string",
")",
"{",
"if",
"(",
"err",
")",
"{",
"debug",
"(",
"err",
")",
";",
"}",
"if",
"(",
"string",
".",
"toString",
"(",
")",
".",
"length",
">",
"0",
")",
"{",
"req",
".",
"code",
"=",
"string",
".",
"toString",
"(",
")",
";",
"debug",
"(",
"'Found auth code %s in body'",
",",
"req",
".",
"code",
")",
";",
"}",
"next",
"(",
")",
";",
"}",
")",
";",
"}"
] |
Look for an auth code on a request. The code is either stored on a query param, in a JSON POST body, or as a raw POST body. If found, it sets req.code, otherwise continue on. Uses raw-body library to get the request body so that bodyParser doesn't have to be configured.
|
[
"Look",
"for",
"an",
"auth",
"code",
"on",
"a",
"request",
".",
"The",
"code",
"is",
"either",
"stored",
"on",
"a",
"query",
"param",
"in",
"a",
"JSON",
"POST",
"body",
"or",
"as",
"a",
"raw",
"POST",
"body",
".",
"If",
"found",
"it",
"sets",
"req",
".",
"code",
"otherwise",
"continue",
"on",
".",
"Uses",
"raw",
"-",
"body",
"library",
"to",
"get",
"the",
"request",
"body",
"so",
"that",
"bodyParser",
"doesn",
"t",
"have",
"to",
"be",
"configured",
"."
] |
7e82bb64aac7064dc998db8f2104529fcdb579f9
|
https://github.com/BlueOakJS/blueoak-server/blob/7e82bb64aac7064dc998db8f2104529fcdb579f9/auth/google-oauth.js#L73-L97
|
train
|
BlueOakJS/blueoak-server
|
auth/google-oauth.js
|
authCodeCallback
|
function authCodeCallback(req, res, next) {
var code = req.code;
if (!code) {
return res.status(400).send('Missing auth code');
}
var tokenData = {
code: code,
client_id: _cfg.clientId,
client_secret: _cfg.clientSecret,
grant_type: 'authorization_code',
redirect_uri: _cfg.redirectURI
};
getToken(tokenData, function (err, authData) {
if (err) {
debug('Error getting new access token: %s', err);
return res.sendStatus(401);
} else {
req.session.auth = authData;
if (_cfg.profile === true) { //optional step to get profile data
debug('Requesting profile data');
getProfileData(authData.access_token, function(err, data) {
if (err) {
debug('Error getting profile data: %s', err.message);
return next(err);
}
req.session.auth.profile = data;
res.sendStatus(200);
});
} else {
res.sendStatus(200);
}
}
});
}
|
javascript
|
function authCodeCallback(req, res, next) {
var code = req.code;
if (!code) {
return res.status(400).send('Missing auth code');
}
var tokenData = {
code: code,
client_id: _cfg.clientId,
client_secret: _cfg.clientSecret,
grant_type: 'authorization_code',
redirect_uri: _cfg.redirectURI
};
getToken(tokenData, function (err, authData) {
if (err) {
debug('Error getting new access token: %s', err);
return res.sendStatus(401);
} else {
req.session.auth = authData;
if (_cfg.profile === true) { //optional step to get profile data
debug('Requesting profile data');
getProfileData(authData.access_token, function(err, data) {
if (err) {
debug('Error getting profile data: %s', err.message);
return next(err);
}
req.session.auth.profile = data;
res.sendStatus(200);
});
} else {
res.sendStatus(200);
}
}
});
}
|
[
"function",
"authCodeCallback",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"code",
"=",
"req",
".",
"code",
";",
"if",
"(",
"!",
"code",
")",
"{",
"return",
"res",
".",
"status",
"(",
"400",
")",
".",
"send",
"(",
"'Missing auth code'",
")",
";",
"}",
"var",
"tokenData",
"=",
"{",
"code",
":",
"code",
",",
"client_id",
":",
"_cfg",
".",
"clientId",
",",
"client_secret",
":",
"_cfg",
".",
"clientSecret",
",",
"grant_type",
":",
"'authorization_code'",
",",
"redirect_uri",
":",
"_cfg",
".",
"redirectURI",
"}",
";",
"getToken",
"(",
"tokenData",
",",
"function",
"(",
"err",
",",
"authData",
")",
"{",
"if",
"(",
"err",
")",
"{",
"debug",
"(",
"'Error getting new access token: %s'",
",",
"err",
")",
";",
"return",
"res",
".",
"sendStatus",
"(",
"401",
")",
";",
"}",
"else",
"{",
"req",
".",
"session",
".",
"auth",
"=",
"authData",
";",
"if",
"(",
"_cfg",
".",
"profile",
"===",
"true",
")",
"{",
"debug",
"(",
"'Requesting profile data'",
")",
";",
"getProfileData",
"(",
"authData",
".",
"access_token",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"{",
"debug",
"(",
"'Error getting profile data: %s'",
",",
"err",
".",
"message",
")",
";",
"return",
"next",
"(",
"err",
")",
";",
"}",
"req",
".",
"session",
".",
"auth",
".",
"profile",
"=",
"data",
";",
"res",
".",
"sendStatus",
"(",
"200",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"res",
".",
"sendStatus",
"(",
"200",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
] |
This gets called when someone hits the auth code callback endpoint It expects that a valid google auth code is supplied through either the "code" query param or in the request body. Let's setAuthCodeOnReq handle getting the auth code. If anything fails, it returns an error status, otherwise a 200
|
[
"This",
"gets",
"called",
"when",
"someone",
"hits",
"the",
"auth",
"code",
"callback",
"endpoint",
"It",
"expects",
"that",
"a",
"valid",
"google",
"auth",
"code",
"is",
"supplied",
"through",
"either",
"the",
"code",
"query",
"param",
"or",
"in",
"the",
"request",
"body",
".",
"Let",
"s",
"setAuthCodeOnReq",
"handle",
"getting",
"the",
"auth",
"code",
".",
"If",
"anything",
"fails",
"it",
"returns",
"an",
"error",
"status",
"otherwise",
"a",
"200"
] |
7e82bb64aac7064dc998db8f2104529fcdb579f9
|
https://github.com/BlueOakJS/blueoak-server/blob/7e82bb64aac7064dc998db8f2104529fcdb579f9/auth/google-oauth.js#L160-L199
|
train
|
BlueOakJS/blueoak-server
|
auth/google-oauth.js
|
signOutUser
|
function signOutUser(req, res, next) {
debug('Signing out user');
//make a best attempt effort at revoking the tokens
var accessToken = req.session.auth ? req.session.auth.access_token: null;
var refreshToken = req.session.auth ? req.session.auth.refresh_token: null;
if (accessToken) {
debug('Revoking access token');
request.get({
url: LOGOUT_URL,
qs: {
token: accessToken
}
}, function(err, response, body) {
if (err) {
debug('Error revoking access token', err.message);
} else {
debug('Revoked access token, %s', response.statusCode);
}
});
}
if (refreshToken) {
request.get({
url: LOGOUT_URL,
qs: {
token: refreshToken
}
}, function (err, response, body) {
if (err) {
debug('Error revoking refresh token', err.message);
} else {
debug('Revoked refresh token, %s', response.statusCode);
}
});
}
delete req.session.auth;
res.sendStatus(200);
}
|
javascript
|
function signOutUser(req, res, next) {
debug('Signing out user');
//make a best attempt effort at revoking the tokens
var accessToken = req.session.auth ? req.session.auth.access_token: null;
var refreshToken = req.session.auth ? req.session.auth.refresh_token: null;
if (accessToken) {
debug('Revoking access token');
request.get({
url: LOGOUT_URL,
qs: {
token: accessToken
}
}, function(err, response, body) {
if (err) {
debug('Error revoking access token', err.message);
} else {
debug('Revoked access token, %s', response.statusCode);
}
});
}
if (refreshToken) {
request.get({
url: LOGOUT_URL,
qs: {
token: refreshToken
}
}, function (err, response, body) {
if (err) {
debug('Error revoking refresh token', err.message);
} else {
debug('Revoked refresh token, %s', response.statusCode);
}
});
}
delete req.session.auth;
res.sendStatus(200);
}
|
[
"function",
"signOutUser",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"debug",
"(",
"'Signing out user'",
")",
";",
"var",
"accessToken",
"=",
"req",
".",
"session",
".",
"auth",
"?",
"req",
".",
"session",
".",
"auth",
".",
"access_token",
":",
"null",
";",
"var",
"refreshToken",
"=",
"req",
".",
"session",
".",
"auth",
"?",
"req",
".",
"session",
".",
"auth",
".",
"refresh_token",
":",
"null",
";",
"if",
"(",
"accessToken",
")",
"{",
"debug",
"(",
"'Revoking access token'",
")",
";",
"request",
".",
"get",
"(",
"{",
"url",
":",
"LOGOUT_URL",
",",
"qs",
":",
"{",
"token",
":",
"accessToken",
"}",
"}",
",",
"function",
"(",
"err",
",",
"response",
",",
"body",
")",
"{",
"if",
"(",
"err",
")",
"{",
"debug",
"(",
"'Error revoking access token'",
",",
"err",
".",
"message",
")",
";",
"}",
"else",
"{",
"debug",
"(",
"'Revoked access token, %s'",
",",
"response",
".",
"statusCode",
")",
";",
"}",
"}",
")",
";",
"}",
"if",
"(",
"refreshToken",
")",
"{",
"request",
".",
"get",
"(",
"{",
"url",
":",
"LOGOUT_URL",
",",
"qs",
":",
"{",
"token",
":",
"refreshToken",
"}",
"}",
",",
"function",
"(",
"err",
",",
"response",
",",
"body",
")",
"{",
"if",
"(",
"err",
")",
"{",
"debug",
"(",
"'Error revoking refresh token'",
",",
"err",
".",
"message",
")",
";",
"}",
"else",
"{",
"debug",
"(",
"'Revoked refresh token, %s'",
",",
"response",
".",
"statusCode",
")",
";",
"}",
"}",
")",
";",
"}",
"delete",
"req",
".",
"session",
".",
"auth",
";",
"res",
".",
"sendStatus",
"(",
"200",
")",
";",
"}"
] |
Revoke the access token, refresh token, and cookies
|
[
"Revoke",
"the",
"access",
"token",
"refresh",
"token",
"and",
"cookies"
] |
7e82bb64aac7064dc998db8f2104529fcdb579f9
|
https://github.com/BlueOakJS/blueoak-server/blob/7e82bb64aac7064dc998db8f2104529fcdb579f9/auth/google-oauth.js#L202-L240
|
train
|
BlueOakJS/blueoak-server
|
auth/google-oauth.js
|
getToken
|
function getToken(data, callback) {
request.post({url: TOKEN_URL, form: data}, function (err, resp, body) {
//this would be something like a connection error
if (err) {
return callback({statusCode: 500, message: err.message});
}
if (resp.statusCode !== 200) { //error
return callback({statusCode: resp.statusCode, message: JSON.parse(body)});
} else {
debug('Got response back from token endpoint', body);
/*
Body should look like
{
"access_token": "ya29.UQH0mtJ5M-CNiXc-mDF9II_R7CRzRQm6AmxIc6TjtouR_HxUtg-I1icHJy36e065UUmIL5HIdfBijg",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "1/7EBZ1cWgvFaPji8FNuAcMIGHYj3nHJkNDjb7CSaAPfM",
"id_token": "..."
}
*/
var authData = JSON.parse(body);
//id_token is a JWT token. Since we're getting this directly from google, no need to authenticate it
var idData = jwt.decode(authData.id_token);
/*
Sample id data
{ iss: 'accounts.google.com',
sub: '103117966615020283234',
azp: '107463652566-jo264sjf04n1uk17i2ijdqbs2tuu2rf0.apps.googleusercontent.com',
email: '[email protected]',
at_hash: 'qCF-HkLhiGtrHgv6EsPzQQ',
email_verified: true,
aud: '107463652566-jo264sjf04n1uk17i2ijdqbs2tuu2rf0.apps.googleusercontent.com',
iat: 1428691188,
exp: 1428694788 }
*/
return callback(null, {
id: idData.sub,
email: idData.email,
access_token: authData.access_token,
expiration: Date.now() + (1000 * authData.expires_in),
refresh_token: authData.refresh_token || data.refresh_token
});
}
});
}
|
javascript
|
function getToken(data, callback) {
request.post({url: TOKEN_URL, form: data}, function (err, resp, body) {
//this would be something like a connection error
if (err) {
return callback({statusCode: 500, message: err.message});
}
if (resp.statusCode !== 200) { //error
return callback({statusCode: resp.statusCode, message: JSON.parse(body)});
} else {
debug('Got response back from token endpoint', body);
/*
Body should look like
{
"access_token": "ya29.UQH0mtJ5M-CNiXc-mDF9II_R7CRzRQm6AmxIc6TjtouR_HxUtg-I1icHJy36e065UUmIL5HIdfBijg",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "1/7EBZ1cWgvFaPji8FNuAcMIGHYj3nHJkNDjb7CSaAPfM",
"id_token": "..."
}
*/
var authData = JSON.parse(body);
//id_token is a JWT token. Since we're getting this directly from google, no need to authenticate it
var idData = jwt.decode(authData.id_token);
/*
Sample id data
{ iss: 'accounts.google.com',
sub: '103117966615020283234',
azp: '107463652566-jo264sjf04n1uk17i2ijdqbs2tuu2rf0.apps.googleusercontent.com',
email: '[email protected]',
at_hash: 'qCF-HkLhiGtrHgv6EsPzQQ',
email_verified: true,
aud: '107463652566-jo264sjf04n1uk17i2ijdqbs2tuu2rf0.apps.googleusercontent.com',
iat: 1428691188,
exp: 1428694788 }
*/
return callback(null, {
id: idData.sub,
email: idData.email,
access_token: authData.access_token,
expiration: Date.now() + (1000 * authData.expires_in),
refresh_token: authData.refresh_token || data.refresh_token
});
}
});
}
|
[
"function",
"getToken",
"(",
"data",
",",
"callback",
")",
"{",
"request",
".",
"post",
"(",
"{",
"url",
":",
"TOKEN_URL",
",",
"form",
":",
"data",
"}",
",",
"function",
"(",
"err",
",",
"resp",
",",
"body",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"{",
"statusCode",
":",
"500",
",",
"message",
":",
"err",
".",
"message",
"}",
")",
";",
"}",
"if",
"(",
"resp",
".",
"statusCode",
"!==",
"200",
")",
"{",
"return",
"callback",
"(",
"{",
"statusCode",
":",
"resp",
".",
"statusCode",
",",
"message",
":",
"JSON",
".",
"parse",
"(",
"body",
")",
"}",
")",
";",
"}",
"else",
"{",
"debug",
"(",
"'Got response back from token endpoint'",
",",
"body",
")",
";",
"var",
"authData",
"=",
"JSON",
".",
"parse",
"(",
"body",
")",
";",
"var",
"idData",
"=",
"jwt",
".",
"decode",
"(",
"authData",
".",
"id_token",
")",
";",
"return",
"callback",
"(",
"null",
",",
"{",
"id",
":",
"idData",
".",
"sub",
",",
"email",
":",
"idData",
".",
"email",
",",
"access_token",
":",
"authData",
".",
"access_token",
",",
"expiration",
":",
"Date",
".",
"now",
"(",
")",
"+",
"(",
"1000",
"*",
"authData",
".",
"expires_in",
")",
",",
"refresh_token",
":",
"authData",
".",
"refresh_token",
"||",
"data",
".",
"refresh_token",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Makes a call to the google token service using the given data
Data should either have a grant type of refresh_token or authorization_code
Callback is of the form callback(err, result) where result contains some auth data, such as
id, email, access_token, expiration, and refresh_token
@param data
@param callback
|
[
"Makes",
"a",
"call",
"to",
"the",
"google",
"token",
"service",
"using",
"the",
"given",
"data"
] |
7e82bb64aac7064dc998db8f2104529fcdb579f9
|
https://github.com/BlueOakJS/blueoak-server/blob/7e82bb64aac7064dc998db8f2104529fcdb579f9/auth/google-oauth.js#L251-L300
|
train
|
BlueOakJS/blueoak-server
|
lib/nodeCacheInterface.js
|
function (key, callback) {
return client.get(key, function (err, result) {
return callback(err, result);
});
}
|
javascript
|
function (key, callback) {
return client.get(key, function (err, result) {
return callback(err, result);
});
}
|
[
"function",
"(",
"key",
",",
"callback",
")",
"{",
"return",
"client",
".",
"get",
"(",
"key",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"return",
"callback",
"(",
"err",
",",
"result",
")",
";",
"}",
")",
";",
"}"
] |
node cache can return the value directly rather than using a callback
|
[
"node",
"cache",
"can",
"return",
"the",
"value",
"directly",
"rather",
"than",
"using",
"a",
"callback"
] |
7e82bb64aac7064dc998db8f2104529fcdb579f9
|
https://github.com/BlueOakJS/blueoak-server/blob/7e82bb64aac7064dc998db8f2104529fcdb579f9/lib/nodeCacheInterface.js#L19-L23
|
train
|
|
BlueOakJS/blueoak-server
|
lib/loader.js
|
fetchUnmetDependencies
|
function fetchUnmetDependencies() {
var runAgain = false;
for (var id in dependencyMap) {
_.forEach(dependencyMap[id], function (depId) {
if (!dependencyMap[depId] && !injectedMap[depId]) {
try {
loadExternalModule(id, depId);
} catch (err) {
throw new Error('Error loading dependency ' + depId + ' for ' + id + ': ' + err.message);
}
runAgain = true;
}
});
}
if (runAgain) { //continue until all we don't have any more unmet dependencies
fetchUnmetDependencies();
}
}
|
javascript
|
function fetchUnmetDependencies() {
var runAgain = false;
for (var id in dependencyMap) {
_.forEach(dependencyMap[id], function (depId) {
if (!dependencyMap[depId] && !injectedMap[depId]) {
try {
loadExternalModule(id, depId);
} catch (err) {
throw new Error('Error loading dependency ' + depId + ' for ' + id + ': ' + err.message);
}
runAgain = true;
}
});
}
if (runAgain) { //continue until all we don't have any more unmet dependencies
fetchUnmetDependencies();
}
}
|
[
"function",
"fetchUnmetDependencies",
"(",
")",
"{",
"var",
"runAgain",
"=",
"false",
";",
"for",
"(",
"var",
"id",
"in",
"dependencyMap",
")",
"{",
"_",
".",
"forEach",
"(",
"dependencyMap",
"[",
"id",
"]",
",",
"function",
"(",
"depId",
")",
"{",
"if",
"(",
"!",
"dependencyMap",
"[",
"depId",
"]",
"&&",
"!",
"injectedMap",
"[",
"depId",
"]",
")",
"{",
"try",
"{",
"loadExternalModule",
"(",
"id",
",",
"depId",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Error loading dependency '",
"+",
"depId",
"+",
"' for '",
"+",
"id",
"+",
"': '",
"+",
"err",
".",
"message",
")",
";",
"}",
"runAgain",
"=",
"true",
";",
"}",
"}",
")",
";",
"}",
"if",
"(",
"runAgain",
")",
"{",
"fetchUnmetDependencies",
"(",
")",
";",
"}",
"}"
] |
Recursively find any unmet dependencies in the dependency tree.
Unmet dependencies are assumed to be third party modules, so it will
continue to load those modules until all dependencies have been met.
|
[
"Recursively",
"find",
"any",
"unmet",
"dependencies",
"in",
"the",
"dependency",
"tree",
".",
"Unmet",
"dependencies",
"are",
"assumed",
"to",
"be",
"third",
"party",
"modules",
"so",
"it",
"will",
"continue",
"to",
"load",
"those",
"modules",
"until",
"all",
"dependencies",
"have",
"been",
"met",
"."
] |
7e82bb64aac7064dc998db8f2104529fcdb579f9
|
https://github.com/BlueOakJS/blueoak-server/blob/7e82bb64aac7064dc998db8f2104529fcdb579f9/lib/loader.js#L67-L86
|
train
|
BlueOakJS/blueoak-server
|
lib/loader.js
|
function (dir, failOnDups) {
debug('Loading services from %s', dir);
di.iterateOverJsFiles(dir, function(dir, file) {
var modPath = path.resolve(dir, file);
var mod;
try {
mod = subRequire(modPath); //subRequire inserts the _id field
} catch (e) {
throw new Error('Could not load ' + modPath + ': ' + e.message);
}
registerServiceModule(mod, failOnDups);
});
}
|
javascript
|
function (dir, failOnDups) {
debug('Loading services from %s', dir);
di.iterateOverJsFiles(dir, function(dir, file) {
var modPath = path.resolve(dir, file);
var mod;
try {
mod = subRequire(modPath); //subRequire inserts the _id field
} catch (e) {
throw new Error('Could not load ' + modPath + ': ' + e.message);
}
registerServiceModule(mod, failOnDups);
});
}
|
[
"function",
"(",
"dir",
",",
"failOnDups",
")",
"{",
"debug",
"(",
"'Loading services from %s'",
",",
"dir",
")",
";",
"di",
".",
"iterateOverJsFiles",
"(",
"dir",
",",
"function",
"(",
"dir",
",",
"file",
")",
"{",
"var",
"modPath",
"=",
"path",
".",
"resolve",
"(",
"dir",
",",
"file",
")",
";",
"var",
"mod",
";",
"try",
"{",
"mod",
"=",
"subRequire",
"(",
"modPath",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Could not load '",
"+",
"modPath",
"+",
"': '",
"+",
"e",
".",
"message",
")",
";",
"}",
"registerServiceModule",
"(",
"mod",
",",
"failOnDups",
")",
";",
"}",
")",
";",
"}"
] |
Load all the services in a given directory.
The service is registered based on its filename, e.g. service.js is registered as service.
Dependencies are calculated based on the parameter names of the init method of the service.
@param dir
@param failOnDups - if specified, error out if there are name collisions with an existing service
|
[
"Load",
"all",
"the",
"services",
"in",
"a",
"given",
"directory",
"."
] |
7e82bb64aac7064dc998db8f2104529fcdb579f9
|
https://github.com/BlueOakJS/blueoak-server/blob/7e82bb64aac7064dc998db8f2104529fcdb579f9/lib/loader.js#L156-L169
|
train
|
|
BlueOakJS/blueoak-server
|
lib/loader.js
|
function() {
var loader = this;
return {
//callback is optional, but will guarantee module was initialized
get: function(name, callback) {
if (!_.isString(name)) {
debug('To get a registered service, the service name must be provided.');
return;
}
var normalizedName = normalizeServiceName(name);
if (!callback) { //sync version
if (!_.includes(initMods, normalizedName)) { //hasn't been initialized
debug('Using services.get on %s before it has been initialized.', name);
}
return loader.get(normalizedName);
} else { //async version
if (_.includes(initMods, normalizedName)) { //already initialized
debug('Found already-initialized module %s, invoking callback.', name);
return callback(loader.get(normalizedName));
} else {
debug('Adding callback %s to notify list for service %s', (callback.name || '<anonymous>'),
name);
notifyList.push({name: normalizedName, callback: callback});
}
}
}
};
}
|
javascript
|
function() {
var loader = this;
return {
//callback is optional, but will guarantee module was initialized
get: function(name, callback) {
if (!_.isString(name)) {
debug('To get a registered service, the service name must be provided.');
return;
}
var normalizedName = normalizeServiceName(name);
if (!callback) { //sync version
if (!_.includes(initMods, normalizedName)) { //hasn't been initialized
debug('Using services.get on %s before it has been initialized.', name);
}
return loader.get(normalizedName);
} else { //async version
if (_.includes(initMods, normalizedName)) { //already initialized
debug('Found already-initialized module %s, invoking callback.', name);
return callback(loader.get(normalizedName));
} else {
debug('Adding callback %s to notify list for service %s', (callback.name || '<anonymous>'),
name);
notifyList.push({name: normalizedName, callback: callback});
}
}
}
};
}
|
[
"function",
"(",
")",
"{",
"var",
"loader",
"=",
"this",
";",
"return",
"{",
"get",
":",
"function",
"(",
"name",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isString",
"(",
"name",
")",
")",
"{",
"debug",
"(",
"'To get a registered service, the service name must be provided.'",
")",
";",
"return",
";",
"}",
"var",
"normalizedName",
"=",
"normalizeServiceName",
"(",
"name",
")",
";",
"if",
"(",
"!",
"callback",
")",
"{",
"if",
"(",
"!",
"_",
".",
"includes",
"(",
"initMods",
",",
"normalizedName",
")",
")",
"{",
"debug",
"(",
"'Using services.get on %s before it has been initialized.'",
",",
"name",
")",
";",
"}",
"return",
"loader",
".",
"get",
"(",
"normalizedName",
")",
";",
"}",
"else",
"{",
"if",
"(",
"_",
".",
"includes",
"(",
"initMods",
",",
"normalizedName",
")",
")",
"{",
"debug",
"(",
"'Found already-initialized module %s, invoking callback.'",
",",
"name",
")",
";",
"return",
"callback",
"(",
"loader",
".",
"get",
"(",
"normalizedName",
")",
")",
";",
"}",
"else",
"{",
"debug",
"(",
"'Adding callback %s to notify list for service %s'",
",",
"(",
"callback",
".",
"name",
"||",
"'<anonymous>'",
")",
",",
"name",
")",
";",
"notifyList",
".",
"push",
"(",
"{",
"name",
":",
"normalizedName",
",",
"callback",
":",
"callback",
"}",
")",
";",
"}",
"}",
"}",
"}",
";",
"}"
] |
This is what we would expose for apps to use to manually load services
|
[
"This",
"is",
"what",
"we",
"would",
"expose",
"for",
"apps",
"to",
"use",
"to",
"manually",
"load",
"services"
] |
7e82bb64aac7064dc998db8f2104529fcdb579f9
|
https://github.com/BlueOakJS/blueoak-server/blob/7e82bb64aac7064dc998db8f2104529fcdb579f9/lib/loader.js#L392-L421
|
train
|
|
BlueOakJS/blueoak-server
|
services/config.js
|
loadFromIndividualConfigFile
|
function loadFromIndividualConfigFile(key) {
key = _.replace(key, /\/|\\/g, ''); //forward and backslashes are unsafe when resolving filenames
if (individualKeyCache[key]) {
return individualKeyCache[key];
} else {
var toLoad = path.resolve(global.__appDir, 'config/' + key + '.json');
var content = '{}';
try {
content = fs.readFileSync(toLoad);
} catch (err) {
//file must not exists
}
var json = {};
try {
json = JSON.parse(stripJsonComments(content.toString()));
} catch (err) {
console.warn('Error parsing JSON for %s', toLoad);
}
security.decryptObject(json, function (str) {
//Decryption function
return security.decrypt(str, process.env.decryptionKey);
});
individualKeyCache[key] = json;
return individualKeyCache[key];
}
}
|
javascript
|
function loadFromIndividualConfigFile(key) {
key = _.replace(key, /\/|\\/g, ''); //forward and backslashes are unsafe when resolving filenames
if (individualKeyCache[key]) {
return individualKeyCache[key];
} else {
var toLoad = path.resolve(global.__appDir, 'config/' + key + '.json');
var content = '{}';
try {
content = fs.readFileSync(toLoad);
} catch (err) {
//file must not exists
}
var json = {};
try {
json = JSON.parse(stripJsonComments(content.toString()));
} catch (err) {
console.warn('Error parsing JSON for %s', toLoad);
}
security.decryptObject(json, function (str) {
//Decryption function
return security.decrypt(str, process.env.decryptionKey);
});
individualKeyCache[key] = json;
return individualKeyCache[key];
}
}
|
[
"function",
"loadFromIndividualConfigFile",
"(",
"key",
")",
"{",
"key",
"=",
"_",
".",
"replace",
"(",
"key",
",",
"/",
"\\/|\\\\",
"/",
"g",
",",
"''",
")",
";",
"if",
"(",
"individualKeyCache",
"[",
"key",
"]",
")",
"{",
"return",
"individualKeyCache",
"[",
"key",
"]",
";",
"}",
"else",
"{",
"var",
"toLoad",
"=",
"path",
".",
"resolve",
"(",
"global",
".",
"__appDir",
",",
"'config/'",
"+",
"key",
"+",
"'.json'",
")",
";",
"var",
"content",
"=",
"'{}'",
";",
"try",
"{",
"content",
"=",
"fs",
".",
"readFileSync",
"(",
"toLoad",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"}",
"var",
"json",
"=",
"{",
"}",
";",
"try",
"{",
"json",
"=",
"JSON",
".",
"parse",
"(",
"stripJsonComments",
"(",
"content",
".",
"toString",
"(",
")",
")",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"console",
".",
"warn",
"(",
"'Error parsing JSON for %s'",
",",
"toLoad",
")",
";",
"}",
"security",
".",
"decryptObject",
"(",
"json",
",",
"function",
"(",
"str",
")",
"{",
"return",
"security",
".",
"decrypt",
"(",
"str",
",",
"process",
".",
"env",
".",
"decryptionKey",
")",
";",
"}",
")",
";",
"individualKeyCache",
"[",
"key",
"]",
"=",
"json",
";",
"return",
"individualKeyCache",
"[",
"key",
"]",
";",
"}",
"}"
] |
For every requested config key, check if there's a json file by that name in the config dir. If there is, load the contents and return it so that it can be merged in.
|
[
"For",
"every",
"requested",
"config",
"key",
"check",
"if",
"there",
"s",
"a",
"json",
"file",
"by",
"that",
"name",
"in",
"the",
"config",
"dir",
".",
"If",
"there",
"is",
"load",
"the",
"contents",
"and",
"return",
"it",
"so",
"that",
"it",
"can",
"be",
"merged",
"in",
"."
] |
7e82bb64aac7064dc998db8f2104529fcdb579f9
|
https://github.com/BlueOakJS/blueoak-server/blob/7e82bb64aac7064dc998db8f2104529fcdb579f9/services/config.js#L80-L110
|
train
|
BlueOakJS/blueoak-server
|
services/logger.js
|
getLocation
|
function getLocation() {
var trace = stackTrace.get();
//trace.forEach(function(e){
// console.log('mytrace: ' + e.getFileName());
//});
//use (start at) index 2 because 0 is the call to getLocation, and 1 is the call to logger
// However, component loggers put an extra level in, so search down until the location is not 'logger'
// There's code to search a long way down the stack, but in practice the next (3) will be hit and used
// since its name is not logger.
var idx = 2;
var modNm = 'logger';
var rmodNm = null;
var skip = ['logger', 'logger.js'];
while ((_.includes(skip, modNm)) && trace.length > idx) {
var fpath = trace[idx].getFileName();
++idx;
if (fpath.slice(0, 'native'.length) === 'native') {
continue; // skip native modules
}
modNm = null;
var mod = null;
try {
mod = require(fpath);
} catch (err) {
// do nothing here, it's checked later
}
if (mod) { //__id is injected into services by the loader
if (!mod.__id) {
modNm = _.split(fpath, '/').pop();
rmodNm = modNm;
} else {
modNm = mod.__id;
if (modNm !== null) {
rmodNm = modNm;
}
}
} else {
modNm = _.split(fpath, '/').pop();
rmodNm = modNm;
}
}
return rmodNm;
}
|
javascript
|
function getLocation() {
var trace = stackTrace.get();
//trace.forEach(function(e){
// console.log('mytrace: ' + e.getFileName());
//});
//use (start at) index 2 because 0 is the call to getLocation, and 1 is the call to logger
// However, component loggers put an extra level in, so search down until the location is not 'logger'
// There's code to search a long way down the stack, but in practice the next (3) will be hit and used
// since its name is not logger.
var idx = 2;
var modNm = 'logger';
var rmodNm = null;
var skip = ['logger', 'logger.js'];
while ((_.includes(skip, modNm)) && trace.length > idx) {
var fpath = trace[idx].getFileName();
++idx;
if (fpath.slice(0, 'native'.length) === 'native') {
continue; // skip native modules
}
modNm = null;
var mod = null;
try {
mod = require(fpath);
} catch (err) {
// do nothing here, it's checked later
}
if (mod) { //__id is injected into services by the loader
if (!mod.__id) {
modNm = _.split(fpath, '/').pop();
rmodNm = modNm;
} else {
modNm = mod.__id;
if (modNm !== null) {
rmodNm = modNm;
}
}
} else {
modNm = _.split(fpath, '/').pop();
rmodNm = modNm;
}
}
return rmodNm;
}
|
[
"function",
"getLocation",
"(",
")",
"{",
"var",
"trace",
"=",
"stackTrace",
".",
"get",
"(",
")",
";",
"var",
"idx",
"=",
"2",
";",
"var",
"modNm",
"=",
"'logger'",
";",
"var",
"rmodNm",
"=",
"null",
";",
"var",
"skip",
"=",
"[",
"'logger'",
",",
"'logger.js'",
"]",
";",
"while",
"(",
"(",
"_",
".",
"includes",
"(",
"skip",
",",
"modNm",
")",
")",
"&&",
"trace",
".",
"length",
">",
"idx",
")",
"{",
"var",
"fpath",
"=",
"trace",
"[",
"idx",
"]",
".",
"getFileName",
"(",
")",
";",
"++",
"idx",
";",
"if",
"(",
"fpath",
".",
"slice",
"(",
"0",
",",
"'native'",
".",
"length",
")",
"===",
"'native'",
")",
"{",
"continue",
";",
"}",
"modNm",
"=",
"null",
";",
"var",
"mod",
"=",
"null",
";",
"try",
"{",
"mod",
"=",
"require",
"(",
"fpath",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"}",
"if",
"(",
"mod",
")",
"{",
"if",
"(",
"!",
"mod",
".",
"__id",
")",
"{",
"modNm",
"=",
"_",
".",
"split",
"(",
"fpath",
",",
"'/'",
")",
".",
"pop",
"(",
")",
";",
"rmodNm",
"=",
"modNm",
";",
"}",
"else",
"{",
"modNm",
"=",
"mod",
".",
"__id",
";",
"if",
"(",
"modNm",
"!==",
"null",
")",
"{",
"rmodNm",
"=",
"modNm",
";",
"}",
"}",
"}",
"else",
"{",
"modNm",
"=",
"_",
".",
"split",
"(",
"fpath",
",",
"'/'",
")",
".",
"pop",
"(",
")",
";",
"rmodNm",
"=",
"modNm",
";",
"}",
"}",
"return",
"rmodNm",
";",
"}"
] |
Determine the name of the service or javascript module that called logger
|
[
"Determine",
"the",
"name",
"of",
"the",
"service",
"or",
"javascript",
"module",
"that",
"called",
"logger"
] |
7e82bb64aac7064dc998db8f2104529fcdb579f9
|
https://github.com/BlueOakJS/blueoak-server/blob/7e82bb64aac7064dc998db8f2104529fcdb579f9/services/logger.js#L164-L209
|
train
|
BlueOakJS/blueoak-server
|
services/swagger.js
|
isBlueoakProject
|
function isBlueoakProject() {
if ((path.basename(global.__appDir) !== 'server')) {
return false;
}
try {
return fs.statSync(path.resolve(global.__appDir, '../common/swagger')).isDirectory();
} catch (err) {
return false;
}
}
|
javascript
|
function isBlueoakProject() {
if ((path.basename(global.__appDir) !== 'server')) {
return false;
}
try {
return fs.statSync(path.resolve(global.__appDir, '../common/swagger')).isDirectory();
} catch (err) {
return false;
}
}
|
[
"function",
"isBlueoakProject",
"(",
")",
"{",
"if",
"(",
"(",
"path",
".",
"basename",
"(",
"global",
".",
"__appDir",
")",
"!==",
"'server'",
")",
")",
"{",
"return",
"false",
";",
"}",
"try",
"{",
"return",
"fs",
".",
"statSync",
"(",
"path",
".",
"resolve",
"(",
"global",
".",
"__appDir",
",",
"'../common/swagger'",
")",
")",
".",
"isDirectory",
"(",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"false",
";",
"}",
"}"
] |
There are two possible places for loading swagger. If we're part of a broader blueoak client-server project, blueoak is running from a 'server' directory, and there's a sibling directory named 'common' which contains the swagger directory. Otherwise we just look in the normal swagger folder within the project
|
[
"There",
"are",
"two",
"possible",
"places",
"for",
"loading",
"swagger",
".",
"If",
"we",
"re",
"part",
"of",
"a",
"broader",
"blueoak",
"client",
"-",
"server",
"project",
"blueoak",
"is",
"running",
"from",
"a",
"server",
"directory",
"and",
"there",
"s",
"a",
"sibling",
"directory",
"named",
"common",
"which",
"contains",
"the",
"swagger",
"directory",
".",
"Otherwise",
"we",
"just",
"look",
"in",
"the",
"normal",
"swagger",
"folder",
"within",
"the",
"project"
] |
7e82bb64aac7064dc998db8f2104529fcdb579f9
|
https://github.com/BlueOakJS/blueoak-server/blob/7e82bb64aac7064dc998db8f2104529fcdb579f9/services/swagger.js#L327-L336
|
train
|
BlueOakJS/blueoak-server
|
lib/security.js
|
containsEncryptedData
|
function containsEncryptedData(obj) {
var foundEncrypted = false;
if (_.isString(obj)) {
foundEncrypted = isEncrypted(obj);
} else if (_.isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
foundEncrypted = foundEncrypted || containsEncryptedData(obj[i]);
}
} else if (_.isObject(obj)) {
for (var key in obj) {
foundEncrypted = foundEncrypted || containsEncryptedData(obj[key]);
}
}
return foundEncrypted;
}
|
javascript
|
function containsEncryptedData(obj) {
var foundEncrypted = false;
if (_.isString(obj)) {
foundEncrypted = isEncrypted(obj);
} else if (_.isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
foundEncrypted = foundEncrypted || containsEncryptedData(obj[i]);
}
} else if (_.isObject(obj)) {
for (var key in obj) {
foundEncrypted = foundEncrypted || containsEncryptedData(obj[key]);
}
}
return foundEncrypted;
}
|
[
"function",
"containsEncryptedData",
"(",
"obj",
")",
"{",
"var",
"foundEncrypted",
"=",
"false",
";",
"if",
"(",
"_",
".",
"isString",
"(",
"obj",
")",
")",
"{",
"foundEncrypted",
"=",
"isEncrypted",
"(",
"obj",
")",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isArray",
"(",
"obj",
")",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"obj",
".",
"length",
";",
"i",
"++",
")",
"{",
"foundEncrypted",
"=",
"foundEncrypted",
"||",
"containsEncryptedData",
"(",
"obj",
"[",
"i",
"]",
")",
";",
"}",
"}",
"else",
"if",
"(",
"_",
".",
"isObject",
"(",
"obj",
")",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"obj",
")",
"{",
"foundEncrypted",
"=",
"foundEncrypted",
"||",
"containsEncryptedData",
"(",
"obj",
"[",
"key",
"]",
")",
";",
"}",
"}",
"return",
"foundEncrypted",
";",
"}"
] |
Recurse through the provided json object, looking for strings that are encrypted
@param obj
@returns {*}
|
[
"Recurse",
"through",
"the",
"provided",
"json",
"object",
"looking",
"for",
"strings",
"that",
"are",
"encrypted"
] |
7e82bb64aac7064dc998db8f2104529fcdb579f9
|
https://github.com/BlueOakJS/blueoak-server/blob/7e82bb64aac7064dc998db8f2104529fcdb579f9/lib/security.js#L68-L83
|
train
|
BlueOakJS/blueoak-server
|
lib/security.js
|
decryptObject
|
function decryptObject(obj, decryptFunction) {
if (_.isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
if (_.isString(obj[i])) {
if (isEncrypted(obj[i])) {
obj[i] = decryptFunction(obj[i]);
}
} else {
decryptObject(obj[i], decryptFunction);
}
}
} else if (_.isObject(obj)) {
for (var key in obj) {
if (_.isString(obj[key])) {
if (isEncrypted(obj[key])) {
obj[key] = decryptFunction(obj[key]);
}
} else {
decryptObject(obj[key], decryptFunction);
}
}
}
}
|
javascript
|
function decryptObject(obj, decryptFunction) {
if (_.isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
if (_.isString(obj[i])) {
if (isEncrypted(obj[i])) {
obj[i] = decryptFunction(obj[i]);
}
} else {
decryptObject(obj[i], decryptFunction);
}
}
} else if (_.isObject(obj)) {
for (var key in obj) {
if (_.isString(obj[key])) {
if (isEncrypted(obj[key])) {
obj[key] = decryptFunction(obj[key]);
}
} else {
decryptObject(obj[key], decryptFunction);
}
}
}
}
|
[
"function",
"decryptObject",
"(",
"obj",
",",
"decryptFunction",
")",
"{",
"if",
"(",
"_",
".",
"isArray",
"(",
"obj",
")",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"obj",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"_",
".",
"isString",
"(",
"obj",
"[",
"i",
"]",
")",
")",
"{",
"if",
"(",
"isEncrypted",
"(",
"obj",
"[",
"i",
"]",
")",
")",
"{",
"obj",
"[",
"i",
"]",
"=",
"decryptFunction",
"(",
"obj",
"[",
"i",
"]",
")",
";",
"}",
"}",
"else",
"{",
"decryptObject",
"(",
"obj",
"[",
"i",
"]",
",",
"decryptFunction",
")",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"_",
".",
"isObject",
"(",
"obj",
")",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"obj",
")",
"{",
"if",
"(",
"_",
".",
"isString",
"(",
"obj",
"[",
"key",
"]",
")",
")",
"{",
"if",
"(",
"isEncrypted",
"(",
"obj",
"[",
"key",
"]",
")",
")",
"{",
"obj",
"[",
"key",
"]",
"=",
"decryptFunction",
"(",
"obj",
"[",
"key",
"]",
")",
";",
"}",
"}",
"else",
"{",
"decryptObject",
"(",
"obj",
"[",
"key",
"]",
",",
"decryptFunction",
")",
";",
"}",
"}",
"}",
"}"
] |
Recurse through an object looking for encrypted strings. If found, replace the string with the decrypted text.
@param obj
@param decryptFunction
|
[
"Recurse",
"through",
"an",
"object",
"looking",
"for",
"encrypted",
"strings",
".",
"If",
"found",
"replace",
"the",
"string",
"with",
"the",
"decrypted",
"text",
"."
] |
7e82bb64aac7064dc998db8f2104529fcdb579f9
|
https://github.com/BlueOakJS/blueoak-server/blob/7e82bb64aac7064dc998db8f2104529fcdb579f9/lib/security.js#L90-L112
|
train
|
BlueOakJS/blueoak-server
|
services/stats.js
|
collectStats
|
function collectStats(callback) {
var serviceStats = {};
var services = loader.listServices();
async.each(services, function(service, callback) {
var mod = loader.get(service);
if (mod.stats) { //does it have a stats function?
invokeStatsOnMod(mod, function(err, data) {
serviceStats[service] = data;
return callback(err);
});
} else {
return callback(); //nothing to do, no stats method exposed
}
}, function(err) {
callback(err, serviceStats);
});
}
|
javascript
|
function collectStats(callback) {
var serviceStats = {};
var services = loader.listServices();
async.each(services, function(service, callback) {
var mod = loader.get(service);
if (mod.stats) { //does it have a stats function?
invokeStatsOnMod(mod, function(err, data) {
serviceStats[service] = data;
return callback(err);
});
} else {
return callback(); //nothing to do, no stats method exposed
}
}, function(err) {
callback(err, serviceStats);
});
}
|
[
"function",
"collectStats",
"(",
"callback",
")",
"{",
"var",
"serviceStats",
"=",
"{",
"}",
";",
"var",
"services",
"=",
"loader",
".",
"listServices",
"(",
")",
";",
"async",
".",
"each",
"(",
"services",
",",
"function",
"(",
"service",
",",
"callback",
")",
"{",
"var",
"mod",
"=",
"loader",
".",
"get",
"(",
"service",
")",
";",
"if",
"(",
"mod",
".",
"stats",
")",
"{",
"invokeStatsOnMod",
"(",
"mod",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"serviceStats",
"[",
"service",
"]",
"=",
"data",
";",
"return",
"callback",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"return",
"callback",
"(",
")",
";",
"}",
"}",
",",
"function",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
",",
"serviceStats",
")",
";",
"}",
")",
";",
"}"
] |
Query all the services and invoke the stats method if it exists
|
[
"Query",
"all",
"the",
"services",
"and",
"invoke",
"the",
"stats",
"method",
"if",
"it",
"exists"
] |
7e82bb64aac7064dc998db8f2104529fcdb579f9
|
https://github.com/BlueOakJS/blueoak-server/blob/7e82bb64aac7064dc998db8f2104529fcdb579f9/services/stats.js#L13-L31
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.