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",
"(",
"pStat... | 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);... | 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);... | [
"function",
"(",
"err",
",",
"content_name",
",",
"parsed_content",
",",
"modified_date",
")",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"parsed_contents",
"[",
"content_name",
"]",
"=",
"parsed_content",
";",
"if",
"(",
"modified_date",
">",
"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.r... | 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.r... | [
"function",
"(",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"sections",
"=",
"[",
"Path",
".",
"join",
"(",
"\"/\"",
")",
"]",
";",
"var",
"paths_to_traverse",
"=",
"[",
"]",
";",
"var",
"should_exclude",
"=",
"function",
"(",
"ent... | 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(bas... | 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(bas... | [
"function",
"(",
"basePath",
",",
"output_extension",
",",
"options",
",",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"collected_contents",
"=",
"{",
"}",
";",
"var",
"content_options",
"=",
"{",
"}",
";",
"var",
"last_modified",
"=",
... | 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);
... | 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);
... | [
"function",
"start",
"(",
"app",
")",
"{",
"/**\n * Create HTTP server.\n */",
"const",
"config",
"=",
"require",
"(",
"'./config'",
")",
"(",
")",
";",
"port",
"=",
"normalizePort",
"(",
"config",
".",
"get",
"(",
"'port'",
")",
")",
";",
"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.r... | 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.r... | [
"function",
"estimatedNumberOfRows",
"(",
"node",
",",
"context",
",",
"callback",
")",
"{",
"var",
"sql",
"=",
"estimatedCountTemplate",
"(",
"{",
"sourceQuery",
":",
"node",
".",
"sql",
"(",
")",
"}",
")",
";",
"context",
".",
"runSQL",
"(",
"sql",
","... | 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 av... | [
"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",
"... | 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(e... | 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(e... | [
"function",
"numberOfRows",
"(",
"node",
",",
"context",
",",
"callback",
")",
"{",
"var",
"sql",
"=",
"exactCountTemplate",
"(",
"{",
"sourceQuery",
":",
"node",
".",
"sql",
"(",
")",
"}",
")",
";",
"context",
".",
"runSQL",
"(",
"sql",
",",
"function... | 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",
... | 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_... | 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_... | [
"function",
"numberOfDistinctValues",
"(",
"node",
",",
"context",
",",
"columnName",
",",
"callback",
")",
"{",
"var",
"sql",
"=",
"countDistinctValuesTemplate",
"(",
"{",
"source",
":",
"node",
".",
"sql",
"(",
")",
",",
"column",
":",
"columnName",
"}",
... | 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... | 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... | [
"function",
"(",
"parallels",
"=",
"1",
")",
"{",
"this",
".",
"_parallels",
"=",
"parallels",
"||",
"1",
";",
"/**\n * _queueCounter\n * each lock() increased this number\n * each unlock() decreases this number\n * If _qC==0, the state is in idle\n * @type {Number}... | 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",
"="... | 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);
idleQ... | 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);
idleQ... | [
"function",
"_removeIdlePromise",
"(",
"idleQueue",
",",
"promise",
")",
"{",
"if",
"(",
"!",
"promise",
")",
"return",
";",
"// remove timeout if exists",
"if",
"(",
"promise",
".",
"_timeoutObj",
")",
"clearTimeout",
"(",
"promise",
".",
"_timeoutObj",
")",
... | 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 = f... | 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 = f... | [
"function",
"_tryIdleCall",
"(",
"idleQueue",
")",
"{",
"// ensure this does not run in parallel",
"if",
"(",
"idleQueue",
".",
"_tryIR",
"||",
"idleQueue",
".",
"_iC",
".",
"size",
"===",
"0",
")",
"return",
";",
"idleQueue",
".",
"_tryIR",
"=",
"true",
";",
... | 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(... | 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(... | [
"function",
"(",
"view",
",",
"config",
")",
"{",
"var",
"formInputs",
"=",
"getForm",
"(",
"view",
")",
";",
"formInputs",
"=",
"_",
".",
"reject",
"(",
"formInputs",
",",
"function",
"(",
"el",
")",
"{",
"var",
"reject",
";",
"var",
"myType",
"=",
... | 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;... | 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;... | [
"function",
"(",
"options",
")",
"{",
"var",
"config",
"=",
"_",
".",
"clone",
"(",
"options",
")",
"||",
"{",
"}",
";",
"config",
".",
"ignoredTypes",
"=",
"_",
".",
"clone",
"(",
"Syphon",
".",
"ignoredTypes",
")",
";",
"config",
".",
"inputReaders... | 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(hostnam... | 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(hostnam... | [
"function",
"getSocketAddressFromURLSafeHostname",
"(",
"hostname",
")",
"{",
"return",
"__awaiter",
"(",
"this",
",",
"void",
"0",
",",
"void",
"0",
",",
"function",
"*",
"(",
")",
"{",
"// IPv4 addresses are fine",
"if",
"(",
"net_1",
".",
"isIPv4",
"(",
"... | 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",
")",
... | 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... | 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... | [
"function",
"padStart",
"(",
"str",
",",
"targetLen",
",",
"fill",
"=",
"\" \"",
")",
"{",
"// simply return strings that are long enough to not be padded",
"if",
"(",
"str",
"!=",
"null",
"&&",
"str",
".",
"length",
">=",
"targetLen",
")",
"return",
"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",
"[",
... | 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]);
... | 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]);
... | [
"function",
"(",
"str",
")",
"{",
"var",
"deliminator_stack",
"=",
"[",
"]",
";",
"var",
"length",
"=",
"str",
".",
"length",
";",
"var",
"i",
";",
"var",
"parts",
"=",
"[",
"]",
";",
"var",
"current_part",
"=",
"''",
";",
"var",
"opening_index",
"... | 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.m... | 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.m... | [
"function",
"(",
"cmdfunc",
")",
"{",
"var",
"outfunc",
"=",
"function",
"(",
"msg",
",",
"reply",
",",
"meta",
")",
"{",
"if",
"(",
"'save'",
"!==",
"msg",
".",
"cmd",
")",
"{",
"if",
"(",
"null",
"==",
"msg",
".",
"q",
")",
"{",
"msg",
".",
... | 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 proce... | 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 proce... | [
"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",
... | 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(/^./... | 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",
"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",
"(",
"/",... | 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",
"(",... | 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(resul... | 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(resul... | [
"function",
"configureConfigFile",
"(",
"err",
",",
"result",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"result",
")",
"{",
"if",
"(",
"key",
"===",
"'port'",
"&&",
"!",
"result",
"[",
"key",
"]",
"||",
"key",
"===",
"'port'",
"&&",
"result",
"[",
... | 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 terrib... | [
"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 = builtinConverter... | 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 = builtinConverter... | [
"function",
"(",
"value",
")",
"{",
"if",
"(",
"typeof",
"value",
"===",
"'object'",
"&&",
"value",
"!==",
"null",
")",
"{",
"if",
"(",
"_",
".",
"size",
"(",
"value",
")",
"<=",
"2",
"&&",
"_",
".",
"all",
"(",
"value",
",",
"function",
"(",
"... | 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 st... | 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 st... | [
"function",
"SetConfigNodeConnectionListeners",
"(",
"node",
")",
"{",
"node",
".",
"clientNode",
".",
"rtmClient",
".",
"on",
"(",
"\"connecting\"",
",",
"(",
")",
"=>",
"{",
"node",
".",
"status",
"(",
"statuses",
".",
"connecting",
")",
";",
"}",
")",
... | 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) {
... | 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) {
... | [
"function",
"SlackState",
"(",
"n",
")",
"{",
"RED",
".",
"nodes",
".",
"createNode",
"(",
"this",
",",
"n",
")",
";",
"var",
"node",
"=",
"this",
";",
"this",
".",
"client",
"=",
"n",
".",
"client",
";",
"this",
".",
"clientNode",
"=",
"RED",
".... | 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",
"(",
"positio... | 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('... | 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('... | [
"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... | 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",
"... | 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",
")",... | 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('&')
}
... | 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('&')
}
... | [
"function",
"stringifyParams",
"(",
"obj",
")",
"{",
"return",
"obj",
"?",
"arrayMap",
"(",
"objectKeys",
"(",
"obj",
")",
".",
"sort",
"(",
")",
",",
"function",
"(",
"key",
")",
"{",
"var",
"val",
"=",
"obj",
"[",
"key",
"]",
"if",
"(",
"angular"... | 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",
")",
"{",
"// for the benefit of testing",
"// perform dependency injection.",
"_",
".",
"extend",
"(",
"this",
",",
"{",
"tmp",
":",
"require",
"(",
"'tmp'",
")",
",",
"logger",
":",
"require",
"(",
"config",
".",
"get"... | 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... | 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... | [
"function",
"Worker",
"(",
"opts",
")",
"{",
"_",
".",
"extend",
"(",
"this",
",",
"{",
"grabber",
":",
"null",
",",
"saver",
":",
"null",
",",
"logger",
":",
"require",
"(",
"config",
".",
"get",
"(",
"'logger'",
")",
")",
"}",
",",
"opts",
")",... | 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 {
thi... | 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 {
thi... | [
"function",
"Client",
"(",
"opts",
")",
"{",
"// update client instance and config",
"// with overrides from opts.",
"_",
".",
"extend",
"(",
"this",
",",
"{",
"Saver",
":",
"require",
"(",
"'./saver'",
")",
".",
"Saver",
"}",
",",
"opts",
")",
"config",
".",
... | 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 en... | 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 en... | [
"function",
"buildOpts",
"(",
"keys",
")",
"{",
"var",
"opts",
"=",
"{",
"}",
"var",
"pairs",
"=",
"_",
".",
"pairs",
"(",
"keys",
")",
"for",
"(",
"var",
"i",
"in",
"pairs",
")",
"{",
"var",
"argvKey",
"=",
"pairs",
"[",
"i",
"]",
"[",
"0",
... | 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",
"||",
"[",
"... | 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) ||
internalDepend... | 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) ||
internalDepend... | [
"function",
"(",
"buildConfig",
",",
"path",
")",
"{",
"ensureBlacklistsComputed",
"(",
"buildConfig",
")",
";",
"var",
"buildConfigBlacklistRE",
"=",
"buildConfig",
".",
"blacklistRE",
";",
"var",
"internalDependenciesBlacklistRE",
"=",
"buildConfig",
".",
"_reactPag... | 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 liste... | [
"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",... | 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 someo... | [
"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() {
... | 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() {
... | [
"function",
"rm",
"(",
"filepath",
",",
"callback",
")",
"{",
"var",
"killswitch",
"=",
"false",
";",
"fs",
".",
"stat",
"(",
"filepath",
",",
"function",
"(",
"err",
",",
"stat",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
"... | 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).s... | 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).s... | [
"function",
"forcelink",
"(",
"src",
",",
"dest",
",",
"options",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"options",
"||",
"!",
"options",
".",
"cache",
")",
"throw",
"new",
"Error",
"(",
"'options.cache not defined!'",
")",
";",
"if",
"(",
"!",
"ca... | 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... | 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... | [
"function",
"localize",
"(",
"url",
",",
"options",
",",
"callback",
")",
"{",
"existsAsync",
"(",
"options",
".",
"filepath",
",",
"function",
"(",
"exists",
")",
"{",
"if",
"(",
"exists",
")",
"{",
"var",
"re_download",
"=",
"false",
";",
"// unideal w... | 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... | 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... | [
"function",
"cachepath",
"(",
"location",
")",
"{",
"var",
"uri",
"=",
"url",
".",
"parse",
"(",
"location",
")",
";",
"if",
"(",
"!",
"uri",
".",
"protocol",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid URL: '",
"+",
"location",
")",
";",
"}",
... | 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));
... | 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));
... | [
"function",
"readExtension",
"(",
"file",
",",
"cb",
")",
"{",
"fs",
".",
"readFile",
"(",
"metapath",
"(",
"file",
")",
",",
"'utf-8'",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"code"... | 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];
... | 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];
... | [
"function",
"fixSRS",
"(",
"obj",
")",
"{",
"if",
"(",
"!",
"obj",
".",
"srs",
")",
"return",
";",
"var",
"normalized",
"=",
"_",
"(",
"obj",
".",
"srs",
".",
"split",
"(",
"' '",
")",
")",
".",
"chain",
"(",
")",
".",
"select",
"(",
"function"... | 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 || []);
va... | 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 || []);
va... | [
"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-... | 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[... | 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[... | [
"function",
"indexOf",
"(",
"haystack",
",",
"needle",
",",
"i",
")",
"{",
"if",
"(",
"!",
"Buffer",
".",
"isBuffer",
"(",
"needle",
")",
")",
"needle",
"=",
"new",
"Buffer",
"(",
"needle",
")",
";",
"if",
"(",
"typeof",
"i",
"===",
"'undefined'",
... | 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",
... | 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 computed... | 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 computed... | [
"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",
")",
"{",
"ret... | `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",
")"... | 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",
"payloadIsV... | 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",
"++",
")",
"{",
"p... | 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",
"clientI... | 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 {
n... | javascript | function getPathToDestination(pathToSource, pathToDestinationFile) {
var isDestinationDirectory = (/\/$/).test(pathToDestinationFile);
var fileName = path.basename(pathToSource);
var newPathToDestination;
if (typeof pathToDestinationFile === 'undefined') {
newPathToDestination = pathToSource;
} else {
n... | [
"function",
"getPathToDestination",
"(",
"pathToSource",
",",
"pathToDestinationFile",
")",
"{",
"var",
"isDestinationDirectory",
"=",
"(",
"/",
"\\/$",
"/",
")",
".",
"test",
"(",
"pathToDestinationFile",
")",
";",
"var",
"fileName",
"=",
"path",
".",
"basename... | 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.repl... | 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.repl... | [
"function",
"fixHeaders",
"(",
"contents",
")",
"{",
"contents",
"=",
"contents",
".",
"replace",
"(",
"/",
"x-poedit-keywordslist:",
"/",
"i",
",",
"'X-Poedit-KeywordsList:'",
")",
";",
"contents",
"=",
"contents",
".",
"replace",
"(",
"/",
"x-poedit-searchpath... | 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-revisi... | 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-revisi... | [
"function",
"normalizeForComparison",
"(",
"pot",
")",
"{",
"var",
"clone",
"=",
"_",
".",
"cloneDeep",
"(",
"pot",
")",
";",
"if",
"(",
"!",
"pot",
")",
"{",
"return",
"pot",
";",
"}",
"// Normalize the content type case.",
"clone",
".",
"headers",
"[",
... | 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... | 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... | 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));
}... | 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));
}... | [
"function",
"updatePoFiles",
"(",
"filename",
",",
"pattern",
")",
"{",
"var",
"merged",
"=",
"[",
"]",
";",
"var",
"searchPath",
"=",
"path",
".",
"dirname",
"(",
"filename",
")",
";",
"pattern",
"=",
"pattern",
"||",
"'*.po'",
";",
"glob",
".",
"sync... | 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.dirn... | 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.dirn... | [
"function",
"guessSlug",
"(",
"wpPackage",
")",
"{",
"var",
"directory",
"=",
"wpPackage",
".",
"getPath",
"(",
")",
";",
"var",
"slug",
"=",
"path",
".",
"basename",
"(",
"directory",
")",
";",
"var",
"slug2",
"=",
"path",
".",
"basename",
"(",
"path"... | 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 Na... | 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 Na... | [
"function",
"findMainFile",
"(",
"wpPackage",
")",
"{",
"if",
"(",
"wpPackage",
".",
"isType",
"(",
"'wp-theme'",
")",
")",
"{",
"return",
"'style.css'",
";",
"}",
"var",
"found",
"=",
"''",
";",
"var",
"pluginFile",
"=",
"guessSlug",
"(",
"wpPackage",
"... | 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",
... | 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"... | 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);
}... | 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);
}... | [
"function",
"GitkitClient",
"(",
"options",
")",
"{",
"this",
".",
"widgetUrl",
"=",
"options",
".",
"widgetUrl",
";",
"this",
".",
"maxTokenExpiration",
"=",
"86400",
"*",
"30",
";",
"// 30 days",
"this",
".",
"audiences",
"=",
"[",
"]",
";",
"if",
"(",... | 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.v... | 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.v... | [
"async",
"function",
"getStudySetup",
"(",
")",
"{",
"// shallow copy",
"const",
"studySetup",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"baseStudySetup",
")",
";",
"studySetup",
".",
"allowEnroll",
"=",
"await",
"cachingFirstRunShouldAllowEnroll",
"(",
... | 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(`... | 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(`... | [
"async",
"function",
"sendTelemetry",
"(",
"payload",
")",
"{",
"utilsLogger",
".",
"debug",
"(",
"\"called sendTelemetry payload\"",
")",
";",
"function",
"throwIfInvalid",
"(",
"obj",
")",
"{",
"// Check: all keys and values must be strings,",
"for",
"(",
"const",
"... | 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' f... | [
"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 se... | 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",
... | 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 de... | [
"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) {
o... | 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) {
o... | [
"function",
"(",
"csv",
",",
"options",
")",
"{",
"// cache settings",
"var",
"separator",
"=",
"options",
".",
"separator",
";",
"var",
"delimiter",
"=",
"options",
".",
"delimiter",
";",
"// set initial state if it's missing",
"if",
"(",
"!",
"options",
".",
... | 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",... | 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 obje... | [
"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",
"en... | 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 = d... | 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 = d... | [
"function",
"(",
"e",
")",
"{",
"d",
".",
"unbind",
"(",
"'touchend.'",
"+",
"SIGNATURE",
"+",
"' mouseup.'",
"+",
"SIGNATURE",
")",
".",
"unbind",
"(",
"'touchmove.'",
"+",
"SIGNATURE",
"+",
"' mousemove.'",
"+",
"SIGNATURE",
")",
";",
"$",
"(",
"\"head... | 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; //t... | 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; //t... | [
"function",
"(",
")",
"{",
"for",
"(",
"t",
"in",
"tables",
")",
"{",
"var",
"t",
"=",
"tables",
"[",
"t",
"]",
",",
"i",
",",
"mw",
"=",
"0",
";",
"t",
".",
"removeClass",
"(",
"SIGNATURE",
")",
";",
"//firefox doesnt like layout-fixed in some cases",... | 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.nTab... | 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.nTab... | [
"function",
"(",
"oSettings",
")",
"{",
"//trick to show row numbers",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"oSettings",
".",
"aiDisplay",
".",
"length",
";",
"i",
"++",
")",
"{",
"$",
"(",
"\"td:eq(0)\"",
",",
"oSettings",
".",
"aoData",
"... | 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",
")",
";... | 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"... | 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) {
... | 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) {
... | [
"function",
"containsMultipartFormData",
"(",
"api",
")",
"{",
"if",
"(",
"_",
".",
"includes",
"(",
"api",
".",
"consumes",
",",
"'multipart/form-data'",
")",
")",
"{",
"return",
"true",
";",
"}",
"var",
"foundMultipartData",
"=",
"false",
";",
"_",
".",
... | 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... | 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... | [
"function",
"handleMulterConfig",
"(",
"multerConfig",
",",
"logger",
",",
"serviceLoader",
")",
"{",
"// Special handling of storage",
"var",
"storageString",
"=",
"_",
".",
"get",
"(",
"multerConfig",
",",
"'storage'",
")",
";",
"if",
"(",
"storageString",
")",
... | 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])) {
... | 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])) {
... | [
"function",
"setDefaultQueryParams",
"(",
"req",
",",
"data",
",",
"logger",
")",
"{",
"var",
"parameters",
"=",
"_",
".",
"toArray",
"(",
"data",
".",
"parameters",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"parameters",
".",
"lengt... | 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",
... | 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 ... | 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 ... | [
"function",
"injectDependencies",
"(",
"serviceLoader",
")",
"{",
"var",
"EventEmitter",
"=",
"require",
"(",
"'events'",
")",
".",
"EventEmitter",
";",
"serviceLoader",
".",
"inject",
"(",
"'events'",
",",
"new",
"EventEmitter",
"(",
")",
")",
";",
"//inject ... | 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",
".... | 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('Fou... | 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('Fou... | [
"function",
"setAuthCodeOnReq",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"req",
".",
"query",
".",
"code",
")",
"{",
"req",
".",
"code",
"=",
"req",
".",
"query",
".",
"code",
";",
"debug",
"(",
"'Found auth code %s on query param'",
"... | 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"... | 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',
r... | 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',
r... | [
"function",
"authCodeCallback",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"code",
"=",
"req",
".",
"code",
";",
"if",
"(",
"!",
"code",
")",
"{",
"return",
"res",
".",
"status",
"(",
"400",
")",
".",
"send",
"(",
"'Missing auth code'",
... | 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",
... | 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... | 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... | [
"function",
"signOutUser",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"debug",
"(",
"'Signing out user'",
")",
";",
"//make a best attempt effort at revoking the tokens",
"var",
"accessToken",
"=",
"req",
".",
"session",
".",
"auth",
"?",
"req",
".",
"sessio... | 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) { /... | 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) { /... | [
"function",
"getToken",
"(",
"data",
",",
"callback",
")",
"{",
"request",
".",
"post",
"(",
"{",
"url",
":",
"TOKEN_URL",
",",
"form",
":",
"data",
"}",
",",
"function",
"(",
"err",
",",
"resp",
",",
"body",
")",
"{",
"//this would be something like a c... | 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);
... | 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);
... | [
"function",
"fetchUnmetDependencies",
"(",
")",
"{",
"var",
"runAgain",
"=",
"false",
";",
"for",
"(",
"var",
"id",
"in",
"dependencyMap",
")",
"{",
"_",
".",
"forEach",
"(",
"dependencyMap",
"[",
"id",
"]",
",",
"function",
"(",
"depId",
")",
"{",
"if... | 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",... | 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 ... | 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 ... | [
"function",
"(",
"dir",
",",
"failOnDups",
")",
"{",
"debug",
"(",
"'Loading services from %s'",
",",
"dir",
")",
";",
"di",
".",
"iterateOverJsFiles",
"(",
"dir",
",",
"function",
"(",
"dir",
",",
"file",
")",
"{",
"var",
"modPath",
"=",
"path",
".",
... | 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 ... | [
"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 mus... | 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 mus... | [
"function",
"(",
")",
"{",
"var",
"loader",
"=",
"this",
";",
"return",
"{",
"//callback is optional, but will guarantee module was initialized",
"get",
":",
"function",
"(",
"name",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isString",
"(",
"name",... | 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');
... | 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');
... | [
"function",
"loadFromIndividualConfigFile",
"(",
"key",
")",
"{",
"key",
"=",
"_",
".",
"replace",
"(",
"key",
",",
"/",
"\\/|\\\\",
"/",
"g",
",",
"''",
")",
";",
"//forward and backslashes are unsafe when resolving filenames",
"if",
"(",
"individualKeyCache",
"[... | 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",
... | 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... | 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... | [
"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... | 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",
".",... | 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... | 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 i... | 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 i... | [
"function",
"containsEncryptedData",
"(",
"obj",
")",
"{",
"var",
"foundEncrypted",
"=",
"false",
";",
"if",
"(",
"_",
".",
"isString",
"(",
"obj",
")",
")",
"{",
"foundEncrypted",
"=",
"isEncrypted",
"(",
"obj",
")",
";",
"}",
"else",
"if",
"(",
"_",
... | 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 {
decryptObj... | 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 {
decryptObj... | [
"function",
"decryptObject",
"(",
"obj",
",",
"decryptFunction",
")",
"{",
"if",
"(",
"_",
".",
"isArray",
"(",
"obj",
")",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"obj",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
... | 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) {
... | 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) {
... | [
"function",
"collectStats",
"(",
"callback",
")",
"{",
"var",
"serviceStats",
"=",
"{",
"}",
";",
"var",
"services",
"=",
"loader",
".",
"listServices",
"(",
")",
";",
"async",
".",
"each",
"(",
"services",
",",
"function",
"(",
"service",
",",
"callback... | 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
SQL Console for semeru/code-text-javascript
Retrieves 20,000 non-null code samples labeled as JavaScript, providing a basic overview of the dataset.