id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
|---|---|---|---|---|---|---|---|---|---|---|---|
18,700
|
trailsjs/sails-permissions
|
api/services/ModelService.js
|
function (req) {
// TODO there has to be a more sails-y way to do this without including
// external modules
if (_.isString(req.options.alias)) {
sails.log.silly('singularizing', req.options.alias, 'to use as target model');
return pluralize.singular(req.options.alias);
} else if (_.isString(req.options.model)) {
return req.options.model;
} else {
return req.model && req.model.identity;
}
}
|
javascript
|
function (req) {
// TODO there has to be a more sails-y way to do this without including
// external modules
if (_.isString(req.options.alias)) {
sails.log.silly('singularizing', req.options.alias, 'to use as target model');
return pluralize.singular(req.options.alias);
} else if (_.isString(req.options.model)) {
return req.options.model;
} else {
return req.model && req.model.identity;
}
}
|
[
"function",
"(",
"req",
")",
"{",
"// TODO there has to be a more sails-y way to do this without including",
"// external modules",
"if",
"(",
"_",
".",
"isString",
"(",
"req",
".",
"options",
".",
"alias",
")",
")",
"{",
"sails",
".",
"log",
".",
"silly",
"(",
"'singularizing'",
",",
"req",
".",
"options",
".",
"alias",
",",
"'to use as target model'",
")",
";",
"return",
"pluralize",
".",
"singular",
"(",
"req",
".",
"options",
".",
"alias",
")",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isString",
"(",
"req",
".",
"options",
".",
"model",
")",
")",
"{",
"return",
"req",
".",
"options",
".",
"model",
";",
"}",
"else",
"{",
"return",
"req",
".",
"model",
"&&",
"req",
".",
"model",
".",
"identity",
";",
"}",
"}"
] |
Return the type of model acted upon by this request.
|
[
"Return",
"the",
"type",
"of",
"model",
"acted",
"upon",
"by",
"this",
"request",
"."
] |
826d504711662bf43a5c266667dd4487553a8a41
|
https://github.com/trailsjs/sails-permissions/blob/826d504711662bf43a5c266667dd4487553a8a41/api/services/ModelService.js#L8-L19
|
|
18,701
|
ksc-fe/kpc
|
components/upload/index.spec.js
|
fixInputChange
|
function fixInputChange(input) {
let files;
Object.defineProperty(input, 'files', {
set(v) { files = v; dispatchEvent(input, 'change'); },
get(v) { return files }
});
}
|
javascript
|
function fixInputChange(input) {
let files;
Object.defineProperty(input, 'files', {
set(v) { files = v; dispatchEvent(input, 'change'); },
get(v) { return files }
});
}
|
[
"function",
"fixInputChange",
"(",
"input",
")",
"{",
"let",
"files",
";",
"Object",
".",
"defineProperty",
"(",
"input",
",",
"'files'",
",",
"{",
"set",
"(",
"v",
")",
"{",
"files",
"=",
"v",
";",
"dispatchEvent",
"(",
"input",
",",
"'change'",
")",
";",
"}",
",",
"get",
"(",
"v",
")",
"{",
"return",
"files",
"}",
"}",
")",
";",
"}"
] |
we should trigger change event manually in the newest ChromeHeadless
|
[
"we",
"should",
"trigger",
"change",
"event",
"manually",
"in",
"the",
"newest",
"ChromeHeadless"
] |
5e5dcdbf95562ce3ab24dd670677348be91988c3
|
https://github.com/ksc-fe/kpc/blob/5e5dcdbf95562ce3ab24dd670677348be91988c3/components/upload/index.spec.js#L25-L31
|
18,702
|
nathanhleung/install-peerdeps
|
src/install-peerdeps.js
|
getPackageData
|
function getPackageData({ encodedPackageName, registry, auth, proxy }) {
const requestHeaders = {};
if (auth) {
requestHeaders.Authorization = `Bearer ${auth}`;
}
const options = {
uri: `${registry}/${encodedPackageName}`,
resolveWithFullResponse: true,
// When simple is true, all non-200 status codes throw an
// error. However, we want to handle status code errors in
// the .then(), so we make simple false.
simple: false,
headers: requestHeaders
};
// If any proxy setting were passed then include the http proxy agent.
const requestProxy =
process.env.HTTP_PROXY || process.env.http_proxy || `${proxy}`;
if (requestProxy !== "undefined") {
options.agent = new HttpsProxyAgent(requestProxy);
}
return request(options).then(response => {
const { statusCode } = response;
if (statusCode === 404) {
throw new Error(
"That package doesn't exist. Did you mean to specify a custom registry?"
);
}
// If the statusCode not 200 or 404, assume that something must
// have gone wrong with the connection
if (statusCode !== 200) {
throw new Error("There was a problem connecting to the registry.");
}
const { body } = response;
const parsedData = JSON.parse(body);
return parsedData;
});
}
|
javascript
|
function getPackageData({ encodedPackageName, registry, auth, proxy }) {
const requestHeaders = {};
if (auth) {
requestHeaders.Authorization = `Bearer ${auth}`;
}
const options = {
uri: `${registry}/${encodedPackageName}`,
resolveWithFullResponse: true,
// When simple is true, all non-200 status codes throw an
// error. However, we want to handle status code errors in
// the .then(), so we make simple false.
simple: false,
headers: requestHeaders
};
// If any proxy setting were passed then include the http proxy agent.
const requestProxy =
process.env.HTTP_PROXY || process.env.http_proxy || `${proxy}`;
if (requestProxy !== "undefined") {
options.agent = new HttpsProxyAgent(requestProxy);
}
return request(options).then(response => {
const { statusCode } = response;
if (statusCode === 404) {
throw new Error(
"That package doesn't exist. Did you mean to specify a custom registry?"
);
}
// If the statusCode not 200 or 404, assume that something must
// have gone wrong with the connection
if (statusCode !== 200) {
throw new Error("There was a problem connecting to the registry.");
}
const { body } = response;
const parsedData = JSON.parse(body);
return parsedData;
});
}
|
[
"function",
"getPackageData",
"(",
"{",
"encodedPackageName",
",",
"registry",
",",
"auth",
",",
"proxy",
"}",
")",
"{",
"const",
"requestHeaders",
"=",
"{",
"}",
";",
"if",
"(",
"auth",
")",
"{",
"requestHeaders",
".",
"Authorization",
"=",
"`",
"${",
"auth",
"}",
"`",
";",
"}",
"const",
"options",
"=",
"{",
"uri",
":",
"`",
"${",
"registry",
"}",
"${",
"encodedPackageName",
"}",
"`",
",",
"resolveWithFullResponse",
":",
"true",
",",
"// When simple is true, all non-200 status codes throw an",
"// error. However, we want to handle status code errors in",
"// the .then(), so we make simple false.",
"simple",
":",
"false",
",",
"headers",
":",
"requestHeaders",
"}",
";",
"// If any proxy setting were passed then include the http proxy agent.",
"const",
"requestProxy",
"=",
"process",
".",
"env",
".",
"HTTP_PROXY",
"||",
"process",
".",
"env",
".",
"http_proxy",
"||",
"`",
"${",
"proxy",
"}",
"`",
";",
"if",
"(",
"requestProxy",
"!==",
"\"undefined\"",
")",
"{",
"options",
".",
"agent",
"=",
"new",
"HttpsProxyAgent",
"(",
"requestProxy",
")",
";",
"}",
"return",
"request",
"(",
"options",
")",
".",
"then",
"(",
"response",
"=>",
"{",
"const",
"{",
"statusCode",
"}",
"=",
"response",
";",
"if",
"(",
"statusCode",
"===",
"404",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"That package doesn't exist. Did you mean to specify a custom registry?\"",
")",
";",
"}",
"// If the statusCode not 200 or 404, assume that something must",
"// have gone wrong with the connection",
"if",
"(",
"statusCode",
"!==",
"200",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"There was a problem connecting to the registry.\"",
")",
";",
"}",
"const",
"{",
"body",
"}",
"=",
"response",
";",
"const",
"parsedData",
"=",
"JSON",
".",
"parse",
"(",
"body",
")",
";",
"return",
"parsedData",
";",
"}",
")",
";",
"}"
] |
Gets metadata about the package from the provided registry
@param {Object} requestInfo - information needed to make the request for the data
@param {string} requestInfo.encodedPackageName - the urlencoded name of the package
@param {string} requestInfo.registry - the URI of the registry on which the package is hosted
@returns {Promise<Object>} - a Promise which resolves to the JSON response from the registry
|
[
"Gets",
"metadata",
"about",
"the",
"package",
"from",
"the",
"provided",
"registry"
] |
402b697996ab3e6dbda503282e7a00b1e409a41e
|
https://github.com/nathanhleung/install-peerdeps/blob/402b697996ab3e6dbda503282e7a00b1e409a41e/src/install-peerdeps.js#L34-L73
|
18,703
|
nathanhleung/install-peerdeps
|
src/install-peerdeps.js
|
spawnInstall
|
function spawnInstall(command, args) {
return new Promise((resolve, reject) => {
// Spawn install process
const installProcess = spawn(command, args, {
cwd: process.cwd(),
// Something to do with this, progress bar only shows if stdio is inherit
// https://github.com/yarnpkg/yarn/issues/2200
stdio: "inherit"
});
installProcess.on("error", err => reject(err));
installProcess.on("close", code => {
if (code !== 0) {
return reject(
new Error(`The install process exited with error code ${code}.`)
);
}
return resolve();
});
});
}
|
javascript
|
function spawnInstall(command, args) {
return new Promise((resolve, reject) => {
// Spawn install process
const installProcess = spawn(command, args, {
cwd: process.cwd(),
// Something to do with this, progress bar only shows if stdio is inherit
// https://github.com/yarnpkg/yarn/issues/2200
stdio: "inherit"
});
installProcess.on("error", err => reject(err));
installProcess.on("close", code => {
if (code !== 0) {
return reject(
new Error(`The install process exited with error code ${code}.`)
);
}
return resolve();
});
});
}
|
[
"function",
"spawnInstall",
"(",
"command",
",",
"args",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"// Spawn install process",
"const",
"installProcess",
"=",
"spawn",
"(",
"command",
",",
"args",
",",
"{",
"cwd",
":",
"process",
".",
"cwd",
"(",
")",
",",
"// Something to do with this, progress bar only shows if stdio is inherit",
"// https://github.com/yarnpkg/yarn/issues/2200",
"stdio",
":",
"\"inherit\"",
"}",
")",
";",
"installProcess",
".",
"on",
"(",
"\"error\"",
",",
"err",
"=>",
"reject",
"(",
"err",
")",
")",
";",
"installProcess",
".",
"on",
"(",
"\"close\"",
",",
"code",
"=>",
"{",
"if",
"(",
"code",
"!==",
"0",
")",
"{",
"return",
"reject",
"(",
"new",
"Error",
"(",
"`",
"${",
"code",
"}",
"`",
")",
")",
";",
"}",
"return",
"resolve",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Spawns the package manager
@param {string} command - the command to spawn
@returns {Promise} - a Promise which resolves when the install process is finished
|
[
"Spawns",
"the",
"package",
"manager"
] |
402b697996ab3e6dbda503282e7a00b1e409a41e
|
https://github.com/nathanhleung/install-peerdeps/blob/402b697996ab3e6dbda503282e7a00b1e409a41e/src/install-peerdeps.js#L80-L99
|
18,704
|
nathanhleung/install-peerdeps
|
src/cli.js
|
printPackageFormatError
|
function printPackageFormatError() {
console.log(
`${
C.errorText
} Please specify the package to install with peerDeps in the form of \`package\` or \`package@n.n.n\``
);
console.log(
`${
C.errorText
} At this time you must provide the full semver version of the package.`
);
console.log(
`${
C.errorText
} Alternatively, omit it to automatically install the latest version of the package.`
);
}
|
javascript
|
function printPackageFormatError() {
console.log(
`${
C.errorText
} Please specify the package to install with peerDeps in the form of \`package\` or \`package@n.n.n\``
);
console.log(
`${
C.errorText
} At this time you must provide the full semver version of the package.`
);
console.log(
`${
C.errorText
} Alternatively, omit it to automatically install the latest version of the package.`
);
}
|
[
"function",
"printPackageFormatError",
"(",
")",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"C",
".",
"errorText",
"}",
"\\`",
"\\`",
"\\`",
"\\`",
"`",
")",
";",
"console",
".",
"log",
"(",
"`",
"${",
"C",
".",
"errorText",
"}",
"`",
")",
";",
"console",
".",
"log",
"(",
"`",
"${",
"C",
".",
"errorText",
"}",
"`",
")",
";",
"}"
] |
Error message that is printed when the program can't
parse the package string.
|
[
"Error",
"message",
"that",
"is",
"printed",
"when",
"the",
"program",
"can",
"t",
"parse",
"the",
"package",
"string",
"."
] |
402b697996ab3e6dbda503282e7a00b1e409a41e
|
https://github.com/nathanhleung/install-peerdeps/blob/402b697996ab3e6dbda503282e7a00b1e409a41e/src/cli.js#L24-L40
|
18,705
|
nathanhleung/install-peerdeps
|
src/cli.js
|
installCb
|
function installCb(err) {
if (err) {
console.log(`${C.errorText} ${err.message}`);
process.exit(1);
}
let successMessage = `${C.successText} ${packageName}
and its peerDeps were installed successfully.`;
if (program.onlyPeers) {
successMessage = `${
C.successText
} The peerDeps of ${packageName} were installed successfully.`;
}
console.log(successMessage);
process.exit(0);
}
|
javascript
|
function installCb(err) {
if (err) {
console.log(`${C.errorText} ${err.message}`);
process.exit(1);
}
let successMessage = `${C.successText} ${packageName}
and its peerDeps were installed successfully.`;
if (program.onlyPeers) {
successMessage = `${
C.successText
} The peerDeps of ${packageName} were installed successfully.`;
}
console.log(successMessage);
process.exit(0);
}
|
[
"function",
"installCb",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"C",
".",
"errorText",
"}",
"${",
"err",
".",
"message",
"}",
"`",
")",
";",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
"let",
"successMessage",
"=",
"`",
"${",
"C",
".",
"successText",
"}",
"${",
"packageName",
"}",
"`",
";",
"if",
"(",
"program",
".",
"onlyPeers",
")",
"{",
"successMessage",
"=",
"`",
"${",
"C",
".",
"successText",
"}",
"${",
"packageName",
"}",
"`",
";",
"}",
"console",
".",
"log",
"(",
"successMessage",
")",
";",
"process",
".",
"exit",
"(",
"0",
")",
";",
"}"
] |
Callback which is called after the installation
process finishes
@callback
@param {Error} [err] - the error, if any, that occurred during installation
|
[
"Callback",
"which",
"is",
"called",
"after",
"the",
"installation",
"process",
"finishes"
] |
402b697996ab3e6dbda503282e7a00b1e409a41e
|
https://github.com/nathanhleung/install-peerdeps/blob/402b697996ab3e6dbda503282e7a00b1e409a41e/src/cli.js#L209-L223
|
18,706
|
springmeyer/arc.js
|
example/bezier/polymaps.js
|
projection
|
function projection(c) {
var zoom = c.zoom,
max = zoom < 0 ? 1 : 1 << zoom,
column = c.column % max,
row = c.row;
if (column < 0) column += max;
return {
locationPoint: function(l) {
var c = po.map.locationCoordinate(l),
k = Math.pow(2, zoom - c.zoom);
return {
x: tileSize.x * (k * c.column - column),
y: tileSize.y * (k * c.row - row)
};
}
};
}
|
javascript
|
function projection(c) {
var zoom = c.zoom,
max = zoom < 0 ? 1 : 1 << zoom,
column = c.column % max,
row = c.row;
if (column < 0) column += max;
return {
locationPoint: function(l) {
var c = po.map.locationCoordinate(l),
k = Math.pow(2, zoom - c.zoom);
return {
x: tileSize.x * (k * c.column - column),
y: tileSize.y * (k * c.row - row)
};
}
};
}
|
[
"function",
"projection",
"(",
"c",
")",
"{",
"var",
"zoom",
"=",
"c",
".",
"zoom",
",",
"max",
"=",
"zoom",
"<",
"0",
"?",
"1",
":",
"1",
"<<",
"zoom",
",",
"column",
"=",
"c",
".",
"column",
"%",
"max",
",",
"row",
"=",
"c",
".",
"row",
";",
"if",
"(",
"column",
"<",
"0",
")",
"column",
"+=",
"max",
";",
"return",
"{",
"locationPoint",
":",
"function",
"(",
"l",
")",
"{",
"var",
"c",
"=",
"po",
".",
"map",
".",
"locationCoordinate",
"(",
"l",
")",
",",
"k",
"=",
"Math",
".",
"pow",
"(",
"2",
",",
"zoom",
"-",
"c",
".",
"zoom",
")",
";",
"return",
"{",
"x",
":",
"tileSize",
".",
"x",
"*",
"(",
"k",
"*",
"c",
".",
"column",
"-",
"column",
")",
",",
"y",
":",
"tileSize",
".",
"y",
"*",
"(",
"k",
"*",
"c",
".",
"row",
"-",
"row",
")",
"}",
";",
"}",
"}",
";",
"}"
] |
tile-specific projection
|
[
"tile",
"-",
"specific",
"projection"
] |
7ea51c89915604f6e691b28b6fbdeeb95e54e820
|
https://github.com/springmeyer/arc.js/blob/7ea51c89915604f6e691b28b6fbdeeb95e54e820/example/bezier/polymaps.js#L832-L848
|
18,707
|
springmeyer/arc.js
|
example/bezier/polymaps.js
|
cleanup
|
function cleanup(e) {
if (e.tile.proxyRefs) {
for (var proxyKey in e.tile.proxyRefs) {
var proxyTile = e.tile.proxyRefs[proxyKey];
if ((--proxyTile.proxyCount <= 0) && cache.unload(proxyKey)) {
proxyTile.element.parentNode.removeChild(proxyTile.element);
}
}
delete e.tile.proxyRefs;
}
}
|
javascript
|
function cleanup(e) {
if (e.tile.proxyRefs) {
for (var proxyKey in e.tile.proxyRefs) {
var proxyTile = e.tile.proxyRefs[proxyKey];
if ((--proxyTile.proxyCount <= 0) && cache.unload(proxyKey)) {
proxyTile.element.parentNode.removeChild(proxyTile.element);
}
}
delete e.tile.proxyRefs;
}
}
|
[
"function",
"cleanup",
"(",
"e",
")",
"{",
"if",
"(",
"e",
".",
"tile",
".",
"proxyRefs",
")",
"{",
"for",
"(",
"var",
"proxyKey",
"in",
"e",
".",
"tile",
".",
"proxyRefs",
")",
"{",
"var",
"proxyTile",
"=",
"e",
".",
"tile",
".",
"proxyRefs",
"[",
"proxyKey",
"]",
";",
"if",
"(",
"(",
"--",
"proxyTile",
".",
"proxyCount",
"<=",
"0",
")",
"&&",
"cache",
".",
"unload",
"(",
"proxyKey",
")",
")",
"{",
"proxyTile",
".",
"element",
".",
"parentNode",
".",
"removeChild",
"(",
"proxyTile",
".",
"element",
")",
";",
"}",
"}",
"delete",
"e",
".",
"tile",
".",
"proxyRefs",
";",
"}",
"}"
] |
remove proxy tiles when tiles load
|
[
"remove",
"proxy",
"tiles",
"when",
"tiles",
"load"
] |
7ea51c89915604f6e691b28b6fbdeeb95e54e820
|
https://github.com/springmeyer/arc.js/blob/7ea51c89915604f6e691b28b6fbdeeb95e54e820/example/bezier/polymaps.js#L964-L974
|
18,708
|
springmeyer/arc.js
|
example/bezier/polymaps.js
|
touchstart
|
function touchstart(e) {
var i = -1,
n = e.touches.length,
t = Date.now();
// doubletap detection
if ((n == 1) && (t - last < 300)) {
var z = map.zoom();
map.zoomBy(1 - z + Math.floor(z), map.mouse(e.touches[0]));
e.preventDefault();
}
last = t;
// store original zoom & touch locations
zoom = map.zoom();
angle = map.angle();
while (++i < n) {
t = e.touches[i];
locations[t.identifier] = map.pointLocation(map.mouse(t));
}
}
|
javascript
|
function touchstart(e) {
var i = -1,
n = e.touches.length,
t = Date.now();
// doubletap detection
if ((n == 1) && (t - last < 300)) {
var z = map.zoom();
map.zoomBy(1 - z + Math.floor(z), map.mouse(e.touches[0]));
e.preventDefault();
}
last = t;
// store original zoom & touch locations
zoom = map.zoom();
angle = map.angle();
while (++i < n) {
t = e.touches[i];
locations[t.identifier] = map.pointLocation(map.mouse(t));
}
}
|
[
"function",
"touchstart",
"(",
"e",
")",
"{",
"var",
"i",
"=",
"-",
"1",
",",
"n",
"=",
"e",
".",
"touches",
".",
"length",
",",
"t",
"=",
"Date",
".",
"now",
"(",
")",
";",
"// doubletap detection",
"if",
"(",
"(",
"n",
"==",
"1",
")",
"&&",
"(",
"t",
"-",
"last",
"<",
"300",
")",
")",
"{",
"var",
"z",
"=",
"map",
".",
"zoom",
"(",
")",
";",
"map",
".",
"zoomBy",
"(",
"1",
"-",
"z",
"+",
"Math",
".",
"floor",
"(",
"z",
")",
",",
"map",
".",
"mouse",
"(",
"e",
".",
"touches",
"[",
"0",
"]",
")",
")",
";",
"e",
".",
"preventDefault",
"(",
")",
";",
"}",
"last",
"=",
"t",
";",
"// store original zoom & touch locations",
"zoom",
"=",
"map",
".",
"zoom",
"(",
")",
";",
"angle",
"=",
"map",
".",
"angle",
"(",
")",
";",
"while",
"(",
"++",
"i",
"<",
"n",
")",
"{",
"t",
"=",
"e",
".",
"touches",
"[",
"i",
"]",
";",
"locations",
"[",
"t",
".",
"identifier",
"]",
"=",
"map",
".",
"pointLocation",
"(",
"map",
".",
"mouse",
"(",
"t",
")",
")",
";",
"}",
"}"
] |
touch identifier -> location
|
[
"touch",
"identifier",
"-",
">",
"location"
] |
7ea51c89915604f6e691b28b6fbdeeb95e54e820
|
https://github.com/springmeyer/arc.js/blob/7ea51c89915604f6e691b28b6fbdeeb95e54e820/example/bezier/polymaps.js#L1874-L1894
|
18,709
|
standard/eslint-plugin-standard
|
rules/array-bracket-even-spacing.js
|
isOptionSet
|
function isOptionSet (option) {
return context.options[1] != null ? context.options[1][option] === !spaced : false
}
|
javascript
|
function isOptionSet (option) {
return context.options[1] != null ? context.options[1][option] === !spaced : false
}
|
[
"function",
"isOptionSet",
"(",
"option",
")",
"{",
"return",
"context",
".",
"options",
"[",
"1",
"]",
"!=",
"null",
"?",
"context",
".",
"options",
"[",
"1",
"]",
"[",
"option",
"]",
"===",
"!",
"spaced",
":",
"false",
"}"
] |
Determines whether an option is set, relative to the spacing option.
If spaced is "always", then check whether option is set to false.
If spaced is "never", then check whether option is set to true.
@param {Object} option - The option to exclude.
@returns {boolean} Whether or not the property is excluded.
|
[
"Determines",
"whether",
"an",
"option",
"is",
"set",
"relative",
"to",
"the",
"spacing",
"option",
".",
"If",
"spaced",
"is",
"always",
"then",
"check",
"whether",
"option",
"is",
"set",
"to",
"false",
".",
"If",
"spaced",
"is",
"never",
"then",
"check",
"whether",
"option",
"is",
"set",
"to",
"true",
"."
] |
deb1a2a05d8ed5dd2126e340e9589d94db16b670
|
https://github.com/standard/eslint-plugin-standard/blob/deb1a2a05d8ed5dd2126e340e9589d94db16b670/rules/array-bracket-even-spacing.js#L33-L35
|
18,710
|
standard/eslint-plugin-standard
|
rules/array-bracket-even-spacing.js
|
isSameLine
|
function isSameLine (left, right) {
return left.loc.start.line === right.loc.start.line
}
|
javascript
|
function isSameLine (left, right) {
return left.loc.start.line === right.loc.start.line
}
|
[
"function",
"isSameLine",
"(",
"left",
",",
"right",
")",
"{",
"return",
"left",
".",
"loc",
".",
"start",
".",
"line",
"===",
"right",
".",
"loc",
".",
"start",
".",
"line",
"}"
] |
Determines whether two adjacent tokens are on the same line.
@param {Object} left - The left token object.
@param {Object} right - The right token object.
@returns {boolean} Whether or not the tokens are on the same line.
|
[
"Determines",
"whether",
"two",
"adjacent",
"tokens",
"are",
"on",
"the",
"same",
"line",
"."
] |
deb1a2a05d8ed5dd2126e340e9589d94db16b670
|
https://github.com/standard/eslint-plugin-standard/blob/deb1a2a05d8ed5dd2126e340e9589d94db16b670/rules/array-bracket-even-spacing.js#L65-L67
|
18,711
|
standard/eslint-plugin-standard
|
rules/array-bracket-even-spacing.js
|
reportNoBeginningSpace
|
function reportNoBeginningSpace (node, token) {
context.report(node, token.loc.start,
"There should be no space after '" + token.value + "'")
}
|
javascript
|
function reportNoBeginningSpace (node, token) {
context.report(node, token.loc.start,
"There should be no space after '" + token.value + "'")
}
|
[
"function",
"reportNoBeginningSpace",
"(",
"node",
",",
"token",
")",
"{",
"context",
".",
"report",
"(",
"node",
",",
"token",
".",
"loc",
".",
"start",
",",
"\"There should be no space after '\"",
"+",
"token",
".",
"value",
"+",
"\"'\"",
")",
"}"
] |
Reports that there shouldn't be a space after the first token
@param {ASTNode} node - The node to report in the event of an error.
@param {Token} token - The token to use for the report.
@returns {void}
|
[
"Reports",
"that",
"there",
"shouldn",
"t",
"be",
"a",
"space",
"after",
"the",
"first",
"token"
] |
deb1a2a05d8ed5dd2126e340e9589d94db16b670
|
https://github.com/standard/eslint-plugin-standard/blob/deb1a2a05d8ed5dd2126e340e9589d94db16b670/rules/array-bracket-even-spacing.js#L75-L78
|
18,712
|
standard/eslint-plugin-standard
|
rules/array-bracket-even-spacing.js
|
validateArraySpacing
|
function validateArraySpacing (node) {
if (node.elements.length === 0) {
return
}
var first = context.getFirstToken(node)
var second = context.getFirstToken(node, 1)
var penultimate = context.getLastToken(node, 1)
var last = context.getLastToken(node)
var openingBracketMustBeSpaced =
(options.objectsInArraysException && second.value === '{') ||
(options.arraysInArraysException && second.value === '[') ||
(options.singleElementException && node.elements.length === 1)
? !options.spaced : options.spaced
var closingBracketMustBeSpaced =
(options.objectsInArraysException && penultimate.value === '}') ||
(options.arraysInArraysException && penultimate.value === ']') ||
(options.singleElementException && node.elements.length === 1)
? !options.spaced : options.spaced
// we only care about evenly spaced things
if (options.either) {
// newlines at any point means return
if (!isSameLine(first, last)) {
return
}
// confirm that the object expression/literal is spaced evenly
if (!isEvenlySpacedAndNotTooLong(node, [first, second], [penultimate, last])) {
context.report(node, 'Expected consistent spacing')
}
return
}
if (isSameLine(first, second)) {
if (openingBracketMustBeSpaced && !isSpaced(first, second)) {
reportRequiredBeginningSpace(node, first)
}
if (!openingBracketMustBeSpaced && isSpaced(first, second)) {
reportNoBeginningSpace(node, first)
}
}
if (isSameLine(penultimate, last)) {
if (closingBracketMustBeSpaced && !isSpaced(penultimate, last)) {
reportRequiredEndingSpace(node, last)
}
if (!closingBracketMustBeSpaced && isSpaced(penultimate, last)) {
reportNoEndingSpace(node, last)
}
}
}
|
javascript
|
function validateArraySpacing (node) {
if (node.elements.length === 0) {
return
}
var first = context.getFirstToken(node)
var second = context.getFirstToken(node, 1)
var penultimate = context.getLastToken(node, 1)
var last = context.getLastToken(node)
var openingBracketMustBeSpaced =
(options.objectsInArraysException && second.value === '{') ||
(options.arraysInArraysException && second.value === '[') ||
(options.singleElementException && node.elements.length === 1)
? !options.spaced : options.spaced
var closingBracketMustBeSpaced =
(options.objectsInArraysException && penultimate.value === '}') ||
(options.arraysInArraysException && penultimate.value === ']') ||
(options.singleElementException && node.elements.length === 1)
? !options.spaced : options.spaced
// we only care about evenly spaced things
if (options.either) {
// newlines at any point means return
if (!isSameLine(first, last)) {
return
}
// confirm that the object expression/literal is spaced evenly
if (!isEvenlySpacedAndNotTooLong(node, [first, second], [penultimate, last])) {
context.report(node, 'Expected consistent spacing')
}
return
}
if (isSameLine(first, second)) {
if (openingBracketMustBeSpaced && !isSpaced(first, second)) {
reportRequiredBeginningSpace(node, first)
}
if (!openingBracketMustBeSpaced && isSpaced(first, second)) {
reportNoBeginningSpace(node, first)
}
}
if (isSameLine(penultimate, last)) {
if (closingBracketMustBeSpaced && !isSpaced(penultimate, last)) {
reportRequiredEndingSpace(node, last)
}
if (!closingBracketMustBeSpaced && isSpaced(penultimate, last)) {
reportNoEndingSpace(node, last)
}
}
}
|
[
"function",
"validateArraySpacing",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"elements",
".",
"length",
"===",
"0",
")",
"{",
"return",
"}",
"var",
"first",
"=",
"context",
".",
"getFirstToken",
"(",
"node",
")",
"var",
"second",
"=",
"context",
".",
"getFirstToken",
"(",
"node",
",",
"1",
")",
"var",
"penultimate",
"=",
"context",
".",
"getLastToken",
"(",
"node",
",",
"1",
")",
"var",
"last",
"=",
"context",
".",
"getLastToken",
"(",
"node",
")",
"var",
"openingBracketMustBeSpaced",
"=",
"(",
"options",
".",
"objectsInArraysException",
"&&",
"second",
".",
"value",
"===",
"'{'",
")",
"||",
"(",
"options",
".",
"arraysInArraysException",
"&&",
"second",
".",
"value",
"===",
"'['",
")",
"||",
"(",
"options",
".",
"singleElementException",
"&&",
"node",
".",
"elements",
".",
"length",
"===",
"1",
")",
"?",
"!",
"options",
".",
"spaced",
":",
"options",
".",
"spaced",
"var",
"closingBracketMustBeSpaced",
"=",
"(",
"options",
".",
"objectsInArraysException",
"&&",
"penultimate",
".",
"value",
"===",
"'}'",
")",
"||",
"(",
"options",
".",
"arraysInArraysException",
"&&",
"penultimate",
".",
"value",
"===",
"']'",
")",
"||",
"(",
"options",
".",
"singleElementException",
"&&",
"node",
".",
"elements",
".",
"length",
"===",
"1",
")",
"?",
"!",
"options",
".",
"spaced",
":",
"options",
".",
"spaced",
"// we only care about evenly spaced things",
"if",
"(",
"options",
".",
"either",
")",
"{",
"// newlines at any point means return",
"if",
"(",
"!",
"isSameLine",
"(",
"first",
",",
"last",
")",
")",
"{",
"return",
"}",
"// confirm that the object expression/literal is spaced evenly",
"if",
"(",
"!",
"isEvenlySpacedAndNotTooLong",
"(",
"node",
",",
"[",
"first",
",",
"second",
"]",
",",
"[",
"penultimate",
",",
"last",
"]",
")",
")",
"{",
"context",
".",
"report",
"(",
"node",
",",
"'Expected consistent spacing'",
")",
"}",
"return",
"}",
"if",
"(",
"isSameLine",
"(",
"first",
",",
"second",
")",
")",
"{",
"if",
"(",
"openingBracketMustBeSpaced",
"&&",
"!",
"isSpaced",
"(",
"first",
",",
"second",
")",
")",
"{",
"reportRequiredBeginningSpace",
"(",
"node",
",",
"first",
")",
"}",
"if",
"(",
"!",
"openingBracketMustBeSpaced",
"&&",
"isSpaced",
"(",
"first",
",",
"second",
")",
")",
"{",
"reportNoBeginningSpace",
"(",
"node",
",",
"first",
")",
"}",
"}",
"if",
"(",
"isSameLine",
"(",
"penultimate",
",",
"last",
")",
")",
"{",
"if",
"(",
"closingBracketMustBeSpaced",
"&&",
"!",
"isSpaced",
"(",
"penultimate",
",",
"last",
")",
")",
"{",
"reportRequiredEndingSpace",
"(",
"node",
",",
"last",
")",
"}",
"if",
"(",
"!",
"closingBracketMustBeSpaced",
"&&",
"isSpaced",
"(",
"penultimate",
",",
"last",
")",
")",
"{",
"reportNoEndingSpace",
"(",
"node",
",",
"last",
")",
"}",
"}",
"}"
] |
Validates the spacing around array brackets
@param {ASTNode} node - The node we're checking for spacing
@returns {void}
|
[
"Validates",
"the",
"spacing",
"around",
"array",
"brackets"
] |
deb1a2a05d8ed5dd2126e340e9589d94db16b670
|
https://github.com/standard/eslint-plugin-standard/blob/deb1a2a05d8ed5dd2126e340e9589d94db16b670/rules/array-bracket-even-spacing.js#L132-L186
|
18,713
|
standard/eslint-plugin-standard
|
rules/computed-property-even-spacing.js
|
checkSpacing
|
function checkSpacing (propertyName) {
return function (node) {
if (!node.computed) {
return
}
var property = node[propertyName]
var before = context.getTokenBefore(property)
var first = context.getFirstToken(property)
var last = context.getLastToken(property)
var after = context.getTokenAfter(property)
var startSpace, endSpace
if (propertyNameMustBeEven) {
if (!isSameLine(before, after)) {
context.report(node, 'Expected "[" and "]" to be on the same line')
return
}
startSpace = first.loc.start.column - before.loc.end.column
endSpace = after.loc.start.column - last.loc.end.column
if (startSpace !== endSpace || startSpace > 1) {
context.report(node, 'Expected 1 or 0 spaces around "[" and "]"')
}
return
}
if (isSameLine(before, first)) {
if (propertyNameMustBeSpaced) {
if (!isSpaced(before, first) && isSameLine(before, first)) {
reportRequiredBeginningSpace(node, before)
}
} else {
if (isSpaced(before, first)) {
reportNoBeginningSpace(node, before)
}
}
}
if (isSameLine(last, after)) {
if (propertyNameMustBeSpaced) {
if (!isSpaced(last, after) && isSameLine(last, after)) {
reportRequiredEndingSpace(node, after)
}
} else {
if (isSpaced(last, after)) {
reportNoEndingSpace(node, after)
}
}
}
}
}
|
javascript
|
function checkSpacing (propertyName) {
return function (node) {
if (!node.computed) {
return
}
var property = node[propertyName]
var before = context.getTokenBefore(property)
var first = context.getFirstToken(property)
var last = context.getLastToken(property)
var after = context.getTokenAfter(property)
var startSpace, endSpace
if (propertyNameMustBeEven) {
if (!isSameLine(before, after)) {
context.report(node, 'Expected "[" and "]" to be on the same line')
return
}
startSpace = first.loc.start.column - before.loc.end.column
endSpace = after.loc.start.column - last.loc.end.column
if (startSpace !== endSpace || startSpace > 1) {
context.report(node, 'Expected 1 or 0 spaces around "[" and "]"')
}
return
}
if (isSameLine(before, first)) {
if (propertyNameMustBeSpaced) {
if (!isSpaced(before, first) && isSameLine(before, first)) {
reportRequiredBeginningSpace(node, before)
}
} else {
if (isSpaced(before, first)) {
reportNoBeginningSpace(node, before)
}
}
}
if (isSameLine(last, after)) {
if (propertyNameMustBeSpaced) {
if (!isSpaced(last, after) && isSameLine(last, after)) {
reportRequiredEndingSpace(node, after)
}
} else {
if (isSpaced(last, after)) {
reportNoEndingSpace(node, after)
}
}
}
}
}
|
[
"function",
"checkSpacing",
"(",
"propertyName",
")",
"{",
"return",
"function",
"(",
"node",
")",
"{",
"if",
"(",
"!",
"node",
".",
"computed",
")",
"{",
"return",
"}",
"var",
"property",
"=",
"node",
"[",
"propertyName",
"]",
"var",
"before",
"=",
"context",
".",
"getTokenBefore",
"(",
"property",
")",
"var",
"first",
"=",
"context",
".",
"getFirstToken",
"(",
"property",
")",
"var",
"last",
"=",
"context",
".",
"getLastToken",
"(",
"property",
")",
"var",
"after",
"=",
"context",
".",
"getTokenAfter",
"(",
"property",
")",
"var",
"startSpace",
",",
"endSpace",
"if",
"(",
"propertyNameMustBeEven",
")",
"{",
"if",
"(",
"!",
"isSameLine",
"(",
"before",
",",
"after",
")",
")",
"{",
"context",
".",
"report",
"(",
"node",
",",
"'Expected \"[\" and \"]\" to be on the same line'",
")",
"return",
"}",
"startSpace",
"=",
"first",
".",
"loc",
".",
"start",
".",
"column",
"-",
"before",
".",
"loc",
".",
"end",
".",
"column",
"endSpace",
"=",
"after",
".",
"loc",
".",
"start",
".",
"column",
"-",
"last",
".",
"loc",
".",
"end",
".",
"column",
"if",
"(",
"startSpace",
"!==",
"endSpace",
"||",
"startSpace",
">",
"1",
")",
"{",
"context",
".",
"report",
"(",
"node",
",",
"'Expected 1 or 0 spaces around \"[\" and \"]\"'",
")",
"}",
"return",
"}",
"if",
"(",
"isSameLine",
"(",
"before",
",",
"first",
")",
")",
"{",
"if",
"(",
"propertyNameMustBeSpaced",
")",
"{",
"if",
"(",
"!",
"isSpaced",
"(",
"before",
",",
"first",
")",
"&&",
"isSameLine",
"(",
"before",
",",
"first",
")",
")",
"{",
"reportRequiredBeginningSpace",
"(",
"node",
",",
"before",
")",
"}",
"}",
"else",
"{",
"if",
"(",
"isSpaced",
"(",
"before",
",",
"first",
")",
")",
"{",
"reportNoBeginningSpace",
"(",
"node",
",",
"before",
")",
"}",
"}",
"}",
"if",
"(",
"isSameLine",
"(",
"last",
",",
"after",
")",
")",
"{",
"if",
"(",
"propertyNameMustBeSpaced",
")",
"{",
"if",
"(",
"!",
"isSpaced",
"(",
"last",
",",
"after",
")",
"&&",
"isSameLine",
"(",
"last",
",",
"after",
")",
")",
"{",
"reportRequiredEndingSpace",
"(",
"node",
",",
"after",
")",
"}",
"}",
"else",
"{",
"if",
"(",
"isSpaced",
"(",
"last",
",",
"after",
")",
")",
"{",
"reportNoEndingSpace",
"(",
"node",
",",
"after",
")",
"}",
"}",
"}",
"}",
"}"
] |
Returns a function that checks the spacing of a node on the property name
that was passed in.
@param {String} propertyName The property on the node to check for spacing
@returns {Function} A function that will check spacing on a node
|
[
"Returns",
"a",
"function",
"that",
"checks",
"the",
"spacing",
"of",
"a",
"node",
"on",
"the",
"property",
"name",
"that",
"was",
"passed",
"in",
"."
] |
deb1a2a05d8ed5dd2126e340e9589d94db16b670
|
https://github.com/standard/eslint-plugin-standard/blob/deb1a2a05d8ed5dd2126e340e9589d94db16b670/rules/computed-property-even-spacing.js#L97-L150
|
18,714
|
standard/eslint-plugin-standard
|
rules/object-curly-even-spacing.js
|
validateBraceSpacing
|
function validateBraceSpacing (node, first, second, penultimate, last) {
var closingCurlyBraceMustBeSpaced =
(options.arraysInObjectsException && penultimate.value === ']') ||
(options.objectsInObjectsException && penultimate.value === '}')
? !options.spaced : options.spaced
// we only care about evenly spaced things
if (options.either) {
// newlines at any point means return
if (!isSameLine(first, last)) {
return
}
// confirm that the object expression/literal is spaced evenly
if (!isEvenlySpacedAndNotTooLong(node, [first, second], [penultimate, last])) {
context.report(node, 'Expected consistent spacing')
}
return
}
// { and key are on same line
if (isSameLine(first, second)) {
if (options.spaced && !isSpaced(first, second)) {
reportRequiredBeginningSpace(node, first)
}
if (!options.spaced && isSpaced(first, second)) {
reportNoBeginningSpace(node, first)
}
}
// final key and } ore on the same line
if (isSameLine(penultimate, last)) {
if (closingCurlyBraceMustBeSpaced && !isSpaced(penultimate, last)) {
reportRequiredEndingSpace(node, last)
}
if (!closingCurlyBraceMustBeSpaced && isSpaced(penultimate, last)) {
reportNoEndingSpace(node, last)
}
}
}
|
javascript
|
function validateBraceSpacing (node, first, second, penultimate, last) {
var closingCurlyBraceMustBeSpaced =
(options.arraysInObjectsException && penultimate.value === ']') ||
(options.objectsInObjectsException && penultimate.value === '}')
? !options.spaced : options.spaced
// we only care about evenly spaced things
if (options.either) {
// newlines at any point means return
if (!isSameLine(first, last)) {
return
}
// confirm that the object expression/literal is spaced evenly
if (!isEvenlySpacedAndNotTooLong(node, [first, second], [penultimate, last])) {
context.report(node, 'Expected consistent spacing')
}
return
}
// { and key are on same line
if (isSameLine(first, second)) {
if (options.spaced && !isSpaced(first, second)) {
reportRequiredBeginningSpace(node, first)
}
if (!options.spaced && isSpaced(first, second)) {
reportNoBeginningSpace(node, first)
}
}
// final key and } ore on the same line
if (isSameLine(penultimate, last)) {
if (closingCurlyBraceMustBeSpaced && !isSpaced(penultimate, last)) {
reportRequiredEndingSpace(node, last)
}
if (!closingCurlyBraceMustBeSpaced && isSpaced(penultimate, last)) {
reportNoEndingSpace(node, last)
}
}
}
|
[
"function",
"validateBraceSpacing",
"(",
"node",
",",
"first",
",",
"second",
",",
"penultimate",
",",
"last",
")",
"{",
"var",
"closingCurlyBraceMustBeSpaced",
"=",
"(",
"options",
".",
"arraysInObjectsException",
"&&",
"penultimate",
".",
"value",
"===",
"']'",
")",
"||",
"(",
"options",
".",
"objectsInObjectsException",
"&&",
"penultimate",
".",
"value",
"===",
"'}'",
")",
"?",
"!",
"options",
".",
"spaced",
":",
"options",
".",
"spaced",
"// we only care about evenly spaced things",
"if",
"(",
"options",
".",
"either",
")",
"{",
"// newlines at any point means return",
"if",
"(",
"!",
"isSameLine",
"(",
"first",
",",
"last",
")",
")",
"{",
"return",
"}",
"// confirm that the object expression/literal is spaced evenly",
"if",
"(",
"!",
"isEvenlySpacedAndNotTooLong",
"(",
"node",
",",
"[",
"first",
",",
"second",
"]",
",",
"[",
"penultimate",
",",
"last",
"]",
")",
")",
"{",
"context",
".",
"report",
"(",
"node",
",",
"'Expected consistent spacing'",
")",
"}",
"return",
"}",
"// { and key are on same line",
"if",
"(",
"isSameLine",
"(",
"first",
",",
"second",
")",
")",
"{",
"if",
"(",
"options",
".",
"spaced",
"&&",
"!",
"isSpaced",
"(",
"first",
",",
"second",
")",
")",
"{",
"reportRequiredBeginningSpace",
"(",
"node",
",",
"first",
")",
"}",
"if",
"(",
"!",
"options",
".",
"spaced",
"&&",
"isSpaced",
"(",
"first",
",",
"second",
")",
")",
"{",
"reportNoBeginningSpace",
"(",
"node",
",",
"first",
")",
"}",
"}",
"// final key and } ore on the same line",
"if",
"(",
"isSameLine",
"(",
"penultimate",
",",
"last",
")",
")",
"{",
"if",
"(",
"closingCurlyBraceMustBeSpaced",
"&&",
"!",
"isSpaced",
"(",
"penultimate",
",",
"last",
")",
")",
"{",
"reportRequiredEndingSpace",
"(",
"node",
",",
"last",
")",
"}",
"if",
"(",
"!",
"closingCurlyBraceMustBeSpaced",
"&&",
"isSpaced",
"(",
"penultimate",
",",
"last",
")",
")",
"{",
"reportNoEndingSpace",
"(",
"node",
",",
"last",
")",
"}",
"}",
"}"
] |
Determines if spacing in curly braces is valid.
@param {ASTNode} node The AST node to check.
@param {Token} first The first token to check (should be the opening brace)
@param {Token} second The second token to check (should be first after the opening brace)
@param {Token} penultimate The penultimate token to check (should be last before closing brace)
@param {Token} last The last token to check (should be closing brace)
@returns {void}
|
[
"Determines",
"if",
"spacing",
"in",
"curly",
"braces",
"is",
"valid",
"."
] |
deb1a2a05d8ed5dd2126e340e9589d94db16b670
|
https://github.com/standard/eslint-plugin-standard/blob/deb1a2a05d8ed5dd2126e340e9589d94db16b670/rules/object-curly-even-spacing.js#L135-L175
|
18,715
|
prey/prey-node-client
|
lib/agent/triggers/auto-connect/mac.js
|
function() {
var cmd = `networksetup -setairportnetwork ${net_interface} "${ssid}"`;
run_as_user(cmd, [], function(err, out) {
return cb(err, out);
});
}
|
javascript
|
function() {
var cmd = `networksetup -setairportnetwork ${net_interface} "${ssid}"`;
run_as_user(cmd, [], function(err, out) {
return cb(err, out);
});
}
|
[
"function",
"(",
")",
"{",
"var",
"cmd",
"=",
"`",
"${",
"net_interface",
"}",
"${",
"ssid",
"}",
"`",
";",
"run_as_user",
"(",
"cmd",
",",
"[",
"]",
",",
"function",
"(",
"err",
",",
"out",
")",
"{",
"return",
"cb",
"(",
"err",
",",
"out",
")",
";",
"}",
")",
";",
"}"
] |
revisar cb si va
|
[
"revisar",
"cb",
"si",
"va"
] |
ade20bd28502a4126cdafbe00fe79043dff4e977
|
https://github.com/prey/prey-node-client/blob/ade20bd28502a4126cdafbe00fe79043dff4e977/lib/agent/triggers/auto-connect/mac.js#L59-L64
|
|
18,716
|
prey/prey-node-client
|
lib/conf/account.js
|
function(key, cb) {
// ensure the plugin is loaded if registration succeeds
var success = function() {
shared.plugin_manager.force_enable('control-panel', function(err) {
cb();
});
}
// set API key and clear Device key
shared.keys.set_api_key(key, function(err) {
if (err) return cb(err);
log('Linking device...');
shared.panel.link(function(err) {
if (!err) return success();
// ok, we got an error. clear the API key before returning.
// call back the original error as well.
shared.keys.set_api_key('', function(e) {
cb(err);
});
});
})
}
|
javascript
|
function(key, cb) {
// ensure the plugin is loaded if registration succeeds
var success = function() {
shared.plugin_manager.force_enable('control-panel', function(err) {
cb();
});
}
// set API key and clear Device key
shared.keys.set_api_key(key, function(err) {
if (err) return cb(err);
log('Linking device...');
shared.panel.link(function(err) {
if (!err) return success();
// ok, we got an error. clear the API key before returning.
// call back the original error as well.
shared.keys.set_api_key('', function(e) {
cb(err);
});
});
})
}
|
[
"function",
"(",
"key",
",",
"cb",
")",
"{",
"// ensure the plugin is loaded if registration succeeds",
"var",
"success",
"=",
"function",
"(",
")",
"{",
"shared",
".",
"plugin_manager",
".",
"force_enable",
"(",
"'control-panel'",
",",
"function",
"(",
"err",
")",
"{",
"cb",
"(",
")",
";",
"}",
")",
";",
"}",
"// set API key and clear Device key",
"shared",
".",
"keys",
".",
"set_api_key",
"(",
"key",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"log",
"(",
"'Linking device...'",
")",
";",
"shared",
".",
"panel",
".",
"link",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"!",
"err",
")",
"return",
"success",
"(",
")",
";",
"// ok, we got an error. clear the API key before returning.",
"// call back the original error as well.",
"shared",
".",
"keys",
".",
"set_api_key",
"(",
"''",
",",
"function",
"(",
"e",
")",
"{",
"cb",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
"}"
] |
set api key and call setup so device gets linked called from cli.js after signing up or signing in
|
[
"set",
"api",
"key",
"and",
"call",
"setup",
"so",
"device",
"gets",
"linked",
"called",
"from",
"cli",
".",
"js",
"after",
"signing",
"up",
"or",
"signing",
"in"
] |
ade20bd28502a4126cdafbe00fe79043dff4e977
|
https://github.com/prey/prey-node-client/blob/ade20bd28502a4126cdafbe00fe79043dff4e977/lib/conf/account.js#L20-L44
|
|
18,717
|
prey/prey-node-client
|
lib/agent/actions/wipe/index.js
|
function(error, method) {
queued++;
if (typeof wipe[method] == 'function') {
wipe[method](function(err, removed) {
if (err) last_err = err;
removed += removed;
--queued || finished(last_err);
})
} else return finished(error);
}
|
javascript
|
function(error, method) {
queued++;
if (typeof wipe[method] == 'function') {
wipe[method](function(err, removed) {
if (err) last_err = err;
removed += removed;
--queued || finished(last_err);
})
} else return finished(error);
}
|
[
"function",
"(",
"error",
",",
"method",
")",
"{",
"queued",
"++",
";",
"if",
"(",
"typeof",
"wipe",
"[",
"method",
"]",
"==",
"'function'",
")",
"{",
"wipe",
"[",
"method",
"]",
"(",
"function",
"(",
"err",
",",
"removed",
")",
"{",
"if",
"(",
"err",
")",
"last_err",
"=",
"err",
";",
"removed",
"+=",
"removed",
";",
"--",
"queued",
"||",
"finished",
"(",
"last_err",
")",
";",
"}",
")",
"}",
"else",
"return",
"finished",
"(",
"error",
")",
";",
"}"
] |
runs it within this context, unlike the spawn option
|
[
"runs",
"it",
"within",
"this",
"context",
"unlike",
"the",
"spawn",
"option"
] |
ade20bd28502a4126cdafbe00fe79043dff4e977
|
https://github.com/prey/prey-node-client/blob/ade20bd28502a4126cdafbe00fe79043dff4e977/lib/agent/actions/wipe/index.js#L74-L84
|
|
18,718
|
prey/prey-node-client
|
lib/package.js
|
function(file, cb) {
var error,
hash = createHash('sha1'),
stream = fs.ReadStream(file);
stream.on('data', function(chunk) {
hash.update(chunk);
});
stream.on('error', function(e) {
if (!error) cb(e);
error = e;
})
stream.on('end', function() {
if (!error) cb(null, hash.digest('hex'));
});
}
|
javascript
|
function(file, cb) {
var error,
hash = createHash('sha1'),
stream = fs.ReadStream(file);
stream.on('data', function(chunk) {
hash.update(chunk);
});
stream.on('error', function(e) {
if (!error) cb(e);
error = e;
})
stream.on('end', function() {
if (!error) cb(null, hash.digest('hex'));
});
}
|
[
"function",
"(",
"file",
",",
"cb",
")",
"{",
"var",
"error",
",",
"hash",
"=",
"createHash",
"(",
"'sha1'",
")",
",",
"stream",
"=",
"fs",
".",
"ReadStream",
"(",
"file",
")",
";",
"stream",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"chunk",
")",
"{",
"hash",
".",
"update",
"(",
"chunk",
")",
";",
"}",
")",
";",
"stream",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"!",
"error",
")",
"cb",
"(",
"e",
")",
";",
"error",
"=",
"e",
";",
"}",
")",
"stream",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"error",
")",
"cb",
"(",
"null",
",",
"hash",
".",
"digest",
"(",
"'hex'",
")",
")",
";",
"}",
")",
";",
"}"
] |
returns sha1 checksum for file
|
[
"returns",
"sha1",
"checksum",
"for",
"file"
] |
ade20bd28502a4126cdafbe00fe79043dff4e977
|
https://github.com/prey/prey-node-client/blob/ade20bd28502a4126cdafbe00fe79043dff4e977/lib/package.js#L36-L53
|
|
18,719
|
prey/prey-node-client
|
lib/package.js
|
like_a_boss
|
function like_a_boss(attempt) {
fs.rename(from, to, function(err) {
if (err) log('Error when moving directory: ' + err.message);
// if no error, or err is not EPERM/EACCES, we're done
if (!err || (err.code != 'EPERM' && err.code != 'EACCES'))
cb();
else if (attempt >= 30) // max attempts reached, so give up.
cb(err);
else
setTimeout(function() { like_a_boss(attempt + 1) }, 1000);
})
}
|
javascript
|
function like_a_boss(attempt) {
fs.rename(from, to, function(err) {
if (err) log('Error when moving directory: ' + err.message);
// if no error, or err is not EPERM/EACCES, we're done
if (!err || (err.code != 'EPERM' && err.code != 'EACCES'))
cb();
else if (attempt >= 30) // max attempts reached, so give up.
cb(err);
else
setTimeout(function() { like_a_boss(attempt + 1) }, 1000);
})
}
|
[
"function",
"like_a_boss",
"(",
"attempt",
")",
"{",
"fs",
".",
"rename",
"(",
"from",
",",
"to",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"log",
"(",
"'Error when moving directory: '",
"+",
"err",
".",
"message",
")",
";",
"// if no error, or err is not EPERM/EACCES, we're done",
"if",
"(",
"!",
"err",
"||",
"(",
"err",
".",
"code",
"!=",
"'EPERM'",
"&&",
"err",
".",
"code",
"!=",
"'EACCES'",
")",
")",
"cb",
"(",
")",
";",
"else",
"if",
"(",
"attempt",
">=",
"30",
")",
"// max attempts reached, so give up.",
"cb",
"(",
"err",
")",
";",
"else",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"like_a_boss",
"(",
"attempt",
"+",
"1",
")",
"}",
",",
"1000",
")",
";",
"}",
")",
"}"
] |
on windows, antivirus softwares lock new folders until all files are scanned which causes a EPERM error when doing a fs.rename. to prevent this from ruining the process, we'll retry the fs.rename 10 times every one second if we do get a EPERM error.
|
[
"on",
"windows",
"antivirus",
"softwares",
"lock",
"new",
"folders",
"until",
"all",
"files",
"are",
"scanned",
"which",
"causes",
"a",
"EPERM",
"error",
"when",
"doing",
"a",
"fs",
".",
"rename",
".",
"to",
"prevent",
"this",
"from",
"ruining",
"the",
"process",
"we",
"ll",
"retry",
"the",
"fs",
".",
"rename",
"10",
"times",
"every",
"one",
"second",
"if",
"we",
"do",
"get",
"a",
"EPERM",
"error",
"."
] |
ade20bd28502a4126cdafbe00fe79043dff4e977
|
https://github.com/prey/prey-node-client/blob/ade20bd28502a4126cdafbe00fe79043dff4e977/lib/package.js#L73-L86
|
18,720
|
prey/prey-node-client
|
lib/agent/providers/lan/windows.js
|
function(hostname, callback) {
get_nodes(function(err,nodes) {
if (err) return callback(err);
var n = nodes.filter(function(node) {
return node.name === hostname;
});
callback(null,(n.length === 1) ? n[0].ip_address : null);
});
}
|
javascript
|
function(hostname, callback) {
get_nodes(function(err,nodes) {
if (err) return callback(err);
var n = nodes.filter(function(node) {
return node.name === hostname;
});
callback(null,(n.length === 1) ? n[0].ip_address : null);
});
}
|
[
"function",
"(",
"hostname",
",",
"callback",
")",
"{",
"get_nodes",
"(",
"function",
"(",
"err",
",",
"nodes",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"var",
"n",
"=",
"nodes",
".",
"filter",
"(",
"function",
"(",
"node",
")",
"{",
"return",
"node",
".",
"name",
"===",
"hostname",
";",
"}",
")",
";",
"callback",
"(",
"null",
",",
"(",
"n",
".",
"length",
"===",
"1",
")",
"?",
"n",
"[",
"0",
"]",
".",
"ip_address",
":",
"null",
")",
";",
"}",
")",
";",
"}"
] |
Callsback an ip address or null if can't find the hostname
|
[
"Callsback",
"an",
"ip",
"address",
"or",
"null",
"if",
"can",
"t",
"find",
"the",
"hostname"
] |
ade20bd28502a4126cdafbe00fe79043dff4e977
|
https://github.com/prey/prey-node-client/blob/ade20bd28502a4126cdafbe00fe79043dff4e977/lib/agent/providers/lan/windows.js#L37-L47
|
|
18,721
|
prey/prey-node-client
|
lib/conf/install.js
|
function(version, cb) {
var version_path = join(paths.versions, version),
opts = { env: process.env, cwd: version_path },
args = ['config', 'activate'];
opts.env.UPGRADING_FROM = common.version;
if (process.platform == 'win32') {
var bin = join(version_path, 'bin', 'node.exe');
args = [join('lib', 'conf', 'cli.js')].concat(args);
} else {
var bin = join(version_path, 'bin', paths.bin);
}
run_synced(bin, args, opts, function(err, code) {
if (!err && code === 0) return cb();
shared.log('Failed. Rolling back!');
// something went wrong while upgrading.
// remove new package & undo pre_uninstall
shared.version_manager.remove(version, function(er) {
cb(er || err);
});
});
}
|
javascript
|
function(version, cb) {
var version_path = join(paths.versions, version),
opts = { env: process.env, cwd: version_path },
args = ['config', 'activate'];
opts.env.UPGRADING_FROM = common.version;
if (process.platform == 'win32') {
var bin = join(version_path, 'bin', 'node.exe');
args = [join('lib', 'conf', 'cli.js')].concat(args);
} else {
var bin = join(version_path, 'bin', paths.bin);
}
run_synced(bin, args, opts, function(err, code) {
if (!err && code === 0) return cb();
shared.log('Failed. Rolling back!');
// something went wrong while upgrading.
// remove new package & undo pre_uninstall
shared.version_manager.remove(version, function(er) {
cb(er || err);
});
});
}
|
[
"function",
"(",
"version",
",",
"cb",
")",
"{",
"var",
"version_path",
"=",
"join",
"(",
"paths",
".",
"versions",
",",
"version",
")",
",",
"opts",
"=",
"{",
"env",
":",
"process",
".",
"env",
",",
"cwd",
":",
"version_path",
"}",
",",
"args",
"=",
"[",
"'config'",
",",
"'activate'",
"]",
";",
"opts",
".",
"env",
".",
"UPGRADING_FROM",
"=",
"common",
".",
"version",
";",
"if",
"(",
"process",
".",
"platform",
"==",
"'win32'",
")",
"{",
"var",
"bin",
"=",
"join",
"(",
"version_path",
",",
"'bin'",
",",
"'node.exe'",
")",
";",
"args",
"=",
"[",
"join",
"(",
"'lib'",
",",
"'conf'",
",",
"'cli.js'",
")",
"]",
".",
"concat",
"(",
"args",
")",
";",
"}",
"else",
"{",
"var",
"bin",
"=",
"join",
"(",
"version_path",
",",
"'bin'",
",",
"paths",
".",
"bin",
")",
";",
"}",
"run_synced",
"(",
"bin",
",",
"args",
",",
"opts",
",",
"function",
"(",
"err",
",",
"code",
")",
"{",
"if",
"(",
"!",
"err",
"&&",
"code",
"===",
"0",
")",
"return",
"cb",
"(",
")",
";",
"shared",
".",
"log",
"(",
"'Failed. Rolling back!'",
")",
";",
"// something went wrong while upgrading.",
"// remove new package & undo pre_uninstall",
"shared",
".",
"version_manager",
".",
"remove",
"(",
"version",
",",
"function",
"(",
"er",
")",
"{",
"cb",
"(",
"er",
"||",
"err",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
calls 'prey config activate' on the new installation, so that it performs the activation using its own paths and logic. if it fails, roll back by removing it
|
[
"calls",
"prey",
"config",
"activate",
"on",
"the",
"new",
"installation",
"so",
"that",
"it",
"performs",
"the",
"activation",
"using",
"its",
"own",
"paths",
"and",
"logic",
".",
"if",
"it",
"fails",
"roll",
"back",
"by",
"removing",
"it"
] |
ade20bd28502a4126cdafbe00fe79043dff4e977
|
https://github.com/prey/prey-node-client/blob/ade20bd28502a4126cdafbe00fe79043dff4e977/lib/conf/install.js#L14-L39
|
|
18,722
|
prey/prey-node-client
|
lib/agent/actions.js
|
function(type, action, name, opts, emitter) {
logger.info('Running: ' + name)
running[name] = action;
emitter.once('end', function(err, out) {
if (err) hooks.trigger('error', err);
logger.info('Stopped: ' + name);
action_stopped(name);
setTimeout(function() {
hooks.trigger(type, 'stopped', name, opts, err, out);
}, 1000);
if (action.events)
emitter.removeAllListeners();
})
if (!action.events) return;
watch_action_events(action.events, emitter);
}
|
javascript
|
function(type, action, name, opts, emitter) {
logger.info('Running: ' + name)
running[name] = action;
emitter.once('end', function(err, out) {
if (err) hooks.trigger('error', err);
logger.info('Stopped: ' + name);
action_stopped(name);
setTimeout(function() {
hooks.trigger(type, 'stopped', name, opts, err, out);
}, 1000);
if (action.events)
emitter.removeAllListeners();
})
if (!action.events) return;
watch_action_events(action.events, emitter);
}
|
[
"function",
"(",
"type",
",",
"action",
",",
"name",
",",
"opts",
",",
"emitter",
")",
"{",
"logger",
".",
"info",
"(",
"'Running: '",
"+",
"name",
")",
"running",
"[",
"name",
"]",
"=",
"action",
";",
"emitter",
".",
"once",
"(",
"'end'",
",",
"function",
"(",
"err",
",",
"out",
")",
"{",
"if",
"(",
"err",
")",
"hooks",
".",
"trigger",
"(",
"'error'",
",",
"err",
")",
";",
"logger",
".",
"info",
"(",
"'Stopped: '",
"+",
"name",
")",
";",
"action_stopped",
"(",
"name",
")",
";",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"hooks",
".",
"trigger",
"(",
"type",
",",
"'stopped'",
",",
"name",
",",
"opts",
",",
"err",
",",
"out",
")",
";",
"}",
",",
"1000",
")",
";",
"if",
"(",
"action",
".",
"events",
")",
"emitter",
".",
"removeAllListeners",
"(",
")",
";",
"}",
")",
"if",
"(",
"!",
"action",
".",
"events",
")",
"return",
";",
"watch_action_events",
"(",
"action",
".",
"events",
",",
"emitter",
")",
";",
"}"
] |
type can be 'action' or 'trigger'
|
[
"type",
"can",
"be",
"action",
"or",
"trigger"
] |
ade20bd28502a4126cdafbe00fe79043dff4e977
|
https://github.com/prey/prey-node-client/blob/ade20bd28502a4126cdafbe00fe79043dff4e977/lib/agent/actions.js#L20-L40
|
|
18,723
|
prey/prey-node-client
|
lib/agent/plugins/retry-failed-reports/index.js
|
store
|
function store(err, resp, data) {
if (err && (err.code == 'EADDRINFO' || err.code == 'ENOTFOUND'))
failed.push(data);
}
|
javascript
|
function store(err, resp, data) {
if (err && (err.code == 'EADDRINFO' || err.code == 'ENOTFOUND'))
failed.push(data);
}
|
[
"function",
"store",
"(",
"err",
",",
"resp",
",",
"data",
")",
"{",
"if",
"(",
"err",
"&&",
"(",
"err",
".",
"code",
"==",
"'EADDRINFO'",
"||",
"err",
".",
"code",
"==",
"'ENOTFOUND'",
")",
")",
"failed",
".",
"push",
"(",
"data",
")",
";",
"}"
] |
wait 20 seconds before requeing each one
|
[
"wait",
"20",
"seconds",
"before",
"requeing",
"each",
"one"
] |
ade20bd28502a4126cdafbe00fe79043dff4e977
|
https://github.com/prey/prey-node-client/blob/ade20bd28502a4126cdafbe00fe79043dff4e977/lib/agent/plugins/retry-failed-reports/index.js#L5-L8
|
18,724
|
prey/prey-node-client
|
lib/agent/cli.js
|
warn
|
function warn(str, code) {
if (process.stdout.writable)
process.stdout.write(str + '\n');
if (typeof code != 'undefined')
process.exit(code);
}
|
javascript
|
function warn(str, code) {
if (process.stdout.writable)
process.stdout.write(str + '\n');
if (typeof code != 'undefined')
process.exit(code);
}
|
[
"function",
"warn",
"(",
"str",
",",
"code",
")",
"{",
"if",
"(",
"process",
".",
"stdout",
".",
"writable",
")",
"process",
".",
"stdout",
".",
"write",
"(",
"str",
"+",
"'\\n'",
")",
";",
"if",
"(",
"typeof",
"code",
"!=",
"'undefined'",
")",
"process",
".",
"exit",
"(",
"code",
")",
";",
"}"
] |
null unless we do set one.
|
[
"null",
"unless",
"we",
"do",
"set",
"one",
"."
] |
ade20bd28502a4126cdafbe00fe79043dff4e977
|
https://github.com/prey/prey-node-client/blob/ade20bd28502a4126cdafbe00fe79043dff4e977/lib/agent/cli.js#L40-L46
|
18,725
|
prey/prey-node-client
|
lib/agent/plugin.js
|
visible
|
function visible(plugin_name) {
var obj = get_base_object();
obj.config = scoped_config(plugin_name);
obj.logger = scoped_logger(plugin_name);
return obj;
}
|
javascript
|
function visible(plugin_name) {
var obj = get_base_object();
obj.config = scoped_config(plugin_name);
obj.logger = scoped_logger(plugin_name);
return obj;
}
|
[
"function",
"visible",
"(",
"plugin_name",
")",
"{",
"var",
"obj",
"=",
"get_base_object",
"(",
")",
";",
"obj",
".",
"config",
"=",
"scoped_config",
"(",
"plugin_name",
")",
";",
"obj",
".",
"logger",
"=",
"scoped_logger",
"(",
"plugin_name",
")",
";",
"return",
"obj",
";",
"}"
] |
returns the visible object that is passed over to plugin basically base + scoped_config + scoped_logger
|
[
"returns",
"the",
"visible",
"object",
"that",
"is",
"passed",
"over",
"to",
"plugin",
"basically",
"base",
"+",
"scoped_config",
"+",
"scoped_logger"
] |
ade20bd28502a4126cdafbe00fe79043dff4e977
|
https://github.com/prey/prey-node-client/blob/ade20bd28502a4126cdafbe00fe79043dff4e977/lib/agent/plugin.js#L26-L31
|
18,726
|
prey/prey-node-client
|
lib/agent/commands.js
|
function(type, name, opts) {
if (!watching) return;
var storable = ['start', 'watch', 'report'];
if (type == 'cancel') // report cancelled
remove('report', name);
else if (storable.indexOf(type) !== -1) // ok for launch
store(type, name, opts);
}
|
javascript
|
function(type, name, opts) {
if (!watching) return;
var storable = ['start', 'watch', 'report'];
if (type == 'cancel') // report cancelled
remove('report', name);
else if (storable.indexOf(type) !== -1) // ok for launch
store(type, name, opts);
}
|
[
"function",
"(",
"type",
",",
"name",
",",
"opts",
")",
"{",
"if",
"(",
"!",
"watching",
")",
"return",
";",
"var",
"storable",
"=",
"[",
"'start'",
",",
"'watch'",
",",
"'report'",
"]",
";",
"if",
"(",
"type",
"==",
"'cancel'",
")",
"// report cancelled",
"remove",
"(",
"'report'",
",",
"name",
")",
";",
"else",
"if",
"(",
"storable",
".",
"indexOf",
"(",
"type",
")",
"!==",
"-",
"1",
")",
"// ok for launch",
"store",
"(",
"type",
",",
"name",
",",
"opts",
")",
";",
"}"
] |
record when actions, triggers and reports are started
|
[
"record",
"when",
"actions",
"triggers",
"and",
"reports",
"are",
"started"
] |
ade20bd28502a4126cdafbe00fe79043dff4e977
|
https://github.com/prey/prey-node-client/blob/ade20bd28502a4126cdafbe00fe79043dff4e977/lib/agent/commands.js#L163-L172
|
|
18,727
|
prey/prey-node-client
|
lib/agent/commands.js
|
function() {
if (!watching) return;
hooks.on('action', function(event, name) {
if (event == 'stopped' || event == 'failed')
remove('start', name);
});
hooks.on('trigger', function(event, name) {
if (event == 'stopped')
remove('watch', name);
});
}
|
javascript
|
function() {
if (!watching) return;
hooks.on('action', function(event, name) {
if (event == 'stopped' || event == 'failed')
remove('start', name);
});
hooks.on('trigger', function(event, name) {
if (event == 'stopped')
remove('watch', name);
});
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"!",
"watching",
")",
"return",
";",
"hooks",
".",
"on",
"(",
"'action'",
",",
"function",
"(",
"event",
",",
"name",
")",
"{",
"if",
"(",
"event",
"==",
"'stopped'",
"||",
"event",
"==",
"'failed'",
")",
"remove",
"(",
"'start'",
",",
"name",
")",
";",
"}",
")",
";",
"hooks",
".",
"on",
"(",
"'trigger'",
",",
"function",
"(",
"event",
",",
"name",
")",
"{",
"if",
"(",
"event",
"==",
"'stopped'",
")",
"remove",
"(",
"'watch'",
",",
"name",
")",
";",
"}",
")",
";",
"}"
] |
listen for new commands and add them to storage, in case the app crashes
|
[
"listen",
"for",
"new",
"commands",
"and",
"add",
"them",
"to",
"storage",
"in",
"case",
"the",
"app",
"crashes"
] |
ade20bd28502a4126cdafbe00fe79043dff4e977
|
https://github.com/prey/prey-node-client/blob/ade20bd28502a4126cdafbe00fe79043dff4e977/lib/agent/commands.js#L175-L187
|
|
18,728
|
OfficeDev/office-js-helpers
|
demo/app.js
|
prettify
|
function prettify(data) {
let json = JSON.stringify(data);
json = json.replace(/{/g, "{\n\n\t");
json = json.replace(/,/g, ",\n\t");
json = json.replace(/}/g, ",\n\n}");
return json;
}
|
javascript
|
function prettify(data) {
let json = JSON.stringify(data);
json = json.replace(/{/g, "{\n\n\t");
json = json.replace(/,/g, ",\n\t");
json = json.replace(/}/g, ",\n\n}");
return json;
}
|
[
"function",
"prettify",
"(",
"data",
")",
"{",
"let",
"json",
"=",
"JSON",
".",
"stringify",
"(",
"data",
")",
";",
"json",
"=",
"json",
".",
"replace",
"(",
"/",
"{",
"/",
"g",
",",
"\"{\\n\\n\\t\"",
")",
";",
"json",
"=",
"json",
".",
"replace",
"(",
"/",
",",
"/",
"g",
",",
"\",\\n\\t\"",
")",
";",
"json",
"=",
"json",
".",
"replace",
"(",
"/",
"}",
"/",
"g",
",",
"\",\\n\\n}\"",
")",
";",
"return",
"json",
";",
"}"
] |
Just a random helper to prettify json
|
[
"Just",
"a",
"random",
"helper",
"to",
"prettify",
"json"
] |
9bc0682bb16e60430278bf7814353aec0410352e
|
https://github.com/OfficeDev/office-js-helpers/blob/9bc0682bb16e60430278bf7814353aec0410352e/demo/app.js#L5-L11
|
18,729
|
cwjohan/markdown-to-html
|
web-demo/routes/index.js
|
setOptions
|
function setOptions(options) {
exports.options = options;
home.options = options;
renderMarkdown.options = options;
renderGithubMarkdown.options = options;
}
|
javascript
|
function setOptions(options) {
exports.options = options;
home.options = options;
renderMarkdown.options = options;
renderGithubMarkdown.options = options;
}
|
[
"function",
"setOptions",
"(",
"options",
")",
"{",
"exports",
".",
"options",
"=",
"options",
";",
"home",
".",
"options",
"=",
"options",
";",
"renderMarkdown",
".",
"options",
"=",
"options",
";",
"renderGithubMarkdown",
".",
"options",
"=",
"options",
";",
"}"
] |
options shared to all routing modules
|
[
"options",
"shared",
"to",
"all",
"routing",
"modules"
] |
15162bde7993220a141ec0dbe9ae7037bbbc3d00
|
https://github.com/cwjohan/markdown-to-html/blob/15162bde7993220a141ec0dbe9ae7037bbbc3d00/web-demo/routes/index.js#L7-L12
|
18,730
|
cwjohan/markdown-to-html
|
web-demo/routes/renderMarkdown.js
|
RenderMarkdown
|
function RenderMarkdown() {
this.options = {}; // Default value only.
this.routeMe = function(req, res) {
var md = new Markdown();
var debug = req.param('debug', false);
md.debug = debug;
md.bufmax = 2048;
var fileName = path.join(viewsDir, req.params.filename);
if (debug) console.error('>>>renderMarkdown: fileName="' + fileName + '"');
res.write(jade.renderFile(
path.join(viewsDir, 'mdheader.jade'),
{title: this.options.title, subtitle: 'Markdown', pretty: true}));
md.once('end', function() {
res.write(jade.renderFile(path.join(viewsDir, 'mdtrailer.jade'), {pretty: true}));
res.end();
});
md.render(fileName, mdOpts, function(err) {
if (debug) console.error('>>>renderMarkdown: err=' + err);
if (err) { res.write('>>>' + err); res.end(); return; }
else md.pipe(res);
});
};
}
|
javascript
|
function RenderMarkdown() {
this.options = {}; // Default value only.
this.routeMe = function(req, res) {
var md = new Markdown();
var debug = req.param('debug', false);
md.debug = debug;
md.bufmax = 2048;
var fileName = path.join(viewsDir, req.params.filename);
if (debug) console.error('>>>renderMarkdown: fileName="' + fileName + '"');
res.write(jade.renderFile(
path.join(viewsDir, 'mdheader.jade'),
{title: this.options.title, subtitle: 'Markdown', pretty: true}));
md.once('end', function() {
res.write(jade.renderFile(path.join(viewsDir, 'mdtrailer.jade'), {pretty: true}));
res.end();
});
md.render(fileName, mdOpts, function(err) {
if (debug) console.error('>>>renderMarkdown: err=' + err);
if (err) { res.write('>>>' + err); res.end(); return; }
else md.pipe(res);
});
};
}
|
[
"function",
"RenderMarkdown",
"(",
")",
"{",
"this",
".",
"options",
"=",
"{",
"}",
";",
"// Default value only.",
"this",
".",
"routeMe",
"=",
"function",
"(",
"req",
",",
"res",
")",
"{",
"var",
"md",
"=",
"new",
"Markdown",
"(",
")",
";",
"var",
"debug",
"=",
"req",
".",
"param",
"(",
"'debug'",
",",
"false",
")",
";",
"md",
".",
"debug",
"=",
"debug",
";",
"md",
".",
"bufmax",
"=",
"2048",
";",
"var",
"fileName",
"=",
"path",
".",
"join",
"(",
"viewsDir",
",",
"req",
".",
"params",
".",
"filename",
")",
";",
"if",
"(",
"debug",
")",
"console",
".",
"error",
"(",
"'>>>renderMarkdown: fileName=\"'",
"+",
"fileName",
"+",
"'\"'",
")",
";",
"res",
".",
"write",
"(",
"jade",
".",
"renderFile",
"(",
"path",
".",
"join",
"(",
"viewsDir",
",",
"'mdheader.jade'",
")",
",",
"{",
"title",
":",
"this",
".",
"options",
".",
"title",
",",
"subtitle",
":",
"'Markdown'",
",",
"pretty",
":",
"true",
"}",
")",
")",
";",
"md",
".",
"once",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"res",
".",
"write",
"(",
"jade",
".",
"renderFile",
"(",
"path",
".",
"join",
"(",
"viewsDir",
",",
"'mdtrailer.jade'",
")",
",",
"{",
"pretty",
":",
"true",
"}",
")",
")",
";",
"res",
".",
"end",
"(",
")",
";",
"}",
")",
";",
"md",
".",
"render",
"(",
"fileName",
",",
"mdOpts",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"debug",
")",
"console",
".",
"error",
"(",
"'>>>renderMarkdown: err='",
"+",
"err",
")",
";",
"if",
"(",
"err",
")",
"{",
"res",
".",
"write",
"(",
"'>>>'",
"+",
"err",
")",
";",
"res",
".",
"end",
"(",
")",
";",
"return",
";",
"}",
"else",
"md",
".",
"pipe",
"(",
"res",
")",
";",
"}",
")",
";",
"}",
";",
"}"
] |
Class RenderMarkdown.
|
[
"Class",
"RenderMarkdown",
"."
] |
15162bde7993220a141ec0dbe9ae7037bbbc3d00
|
https://github.com/cwjohan/markdown-to-html/blob/15162bde7993220a141ec0dbe9ae7037bbbc3d00/web-demo/routes/renderMarkdown.js#L16-L39
|
18,731
|
pzavolinsky/elmx
|
cheatsheet/elm.js
|
fromListPush
|
function fromListPush(toPush, nodes)
{
var h = toPush.height;
// Maybe the node on this height does not exist.
if (nodes.length === h)
{
var node = {
ctor: '_Array',
height: h + 1,
table: [],
lengths: []
};
nodes.push(node);
}
nodes[h].table.push(toPush);
var len = length(toPush);
if (nodes[h].lengths.length > 0)
{
len += nodes[h].lengths[nodes[h].lengths.length - 1];
}
nodes[h].lengths.push(len);
if (nodes[h].table.length === M)
{
fromListPush(nodes[h], nodes);
nodes[h] = {
ctor: '_Array',
height: h + 1,
table: [],
lengths: []
};
}
}
|
javascript
|
function fromListPush(toPush, nodes)
{
var h = toPush.height;
// Maybe the node on this height does not exist.
if (nodes.length === h)
{
var node = {
ctor: '_Array',
height: h + 1,
table: [],
lengths: []
};
nodes.push(node);
}
nodes[h].table.push(toPush);
var len = length(toPush);
if (nodes[h].lengths.length > 0)
{
len += nodes[h].lengths[nodes[h].lengths.length - 1];
}
nodes[h].lengths.push(len);
if (nodes[h].table.length === M)
{
fromListPush(nodes[h], nodes);
nodes[h] = {
ctor: '_Array',
height: h + 1,
table: [],
lengths: []
};
}
}
|
[
"function",
"fromListPush",
"(",
"toPush",
",",
"nodes",
")",
"{",
"var",
"h",
"=",
"toPush",
".",
"height",
";",
"// Maybe the node on this height does not exist.",
"if",
"(",
"nodes",
".",
"length",
"===",
"h",
")",
"{",
"var",
"node",
"=",
"{",
"ctor",
":",
"'_Array'",
",",
"height",
":",
"h",
"+",
"1",
",",
"table",
":",
"[",
"]",
",",
"lengths",
":",
"[",
"]",
"}",
";",
"nodes",
".",
"push",
"(",
"node",
")",
";",
"}",
"nodes",
"[",
"h",
"]",
".",
"table",
".",
"push",
"(",
"toPush",
")",
";",
"var",
"len",
"=",
"length",
"(",
"toPush",
")",
";",
"if",
"(",
"nodes",
"[",
"h",
"]",
".",
"lengths",
".",
"length",
">",
"0",
")",
"{",
"len",
"+=",
"nodes",
"[",
"h",
"]",
".",
"lengths",
"[",
"nodes",
"[",
"h",
"]",
".",
"lengths",
".",
"length",
"-",
"1",
"]",
";",
"}",
"nodes",
"[",
"h",
"]",
".",
"lengths",
".",
"push",
"(",
"len",
")",
";",
"if",
"(",
"nodes",
"[",
"h",
"]",
".",
"table",
".",
"length",
"===",
"M",
")",
"{",
"fromListPush",
"(",
"nodes",
"[",
"h",
"]",
",",
"nodes",
")",
";",
"nodes",
"[",
"h",
"]",
"=",
"{",
"ctor",
":",
"'_Array'",
",",
"height",
":",
"h",
"+",
"1",
",",
"table",
":",
"[",
"]",
",",
"lengths",
":",
"[",
"]",
"}",
";",
"}",
"}"
] |
Push a node into a higher node as a child.
|
[
"Push",
"a",
"node",
"into",
"a",
"higher",
"node",
"as",
"a",
"child",
"."
] |
ae125fa9a749273a65d224bc87bbecbf06f253d8
|
https://github.com/pzavolinsky/elmx/blob/ae125fa9a749273a65d224bc87bbecbf06f253d8/cheatsheet/elm.js#L334-L368
|
18,732
|
pzavolinsky/elmx
|
cheatsheet/elm.js
|
push
|
function push(item, a)
{
var pushed = push_(item, a);
if (pushed !== null)
{
return pushed;
}
var newTree = create(item, a.height);
return siblise(a, newTree);
}
|
javascript
|
function push(item, a)
{
var pushed = push_(item, a);
if (pushed !== null)
{
return pushed;
}
var newTree = create(item, a.height);
return siblise(a, newTree);
}
|
[
"function",
"push",
"(",
"item",
",",
"a",
")",
"{",
"var",
"pushed",
"=",
"push_",
"(",
"item",
",",
"a",
")",
";",
"if",
"(",
"pushed",
"!==",
"null",
")",
"{",
"return",
"pushed",
";",
"}",
"var",
"newTree",
"=",
"create",
"(",
"item",
",",
"a",
".",
"height",
")",
";",
"return",
"siblise",
"(",
"a",
",",
"newTree",
")",
";",
"}"
] |
Pushes an item via push_ to the bottom right of a tree.
|
[
"Pushes",
"an",
"item",
"via",
"push_",
"to",
"the",
"bottom",
"right",
"of",
"a",
"tree",
"."
] |
ae125fa9a749273a65d224bc87bbecbf06f253d8
|
https://github.com/pzavolinsky/elmx/blob/ae125fa9a749273a65d224bc87bbecbf06f253d8/cheatsheet/elm.js#L371-L381
|
18,733
|
pzavolinsky/elmx
|
cheatsheet/elm.js
|
push_
|
function push_(item, a)
{
// Handle resursion stop at leaf level.
if (a.height === 0)
{
if (a.table.length < M)
{
var newA = {
ctor: '_Array',
height: 0,
table: a.table.slice()
};
newA.table.push(item);
return newA;
}
else
{
return null;
}
}
// Recursively push
var pushed = push_(item, botRight(a));
// There was space in the bottom right tree, so the slot will
// be updated.
if (pushed !== null)
{
var newA = nodeCopy(a);
newA.table[newA.table.length - 1] = pushed;
newA.lengths[newA.lengths.length - 1]++;
return newA;
}
// When there was no space left, check if there is space left
// for a new slot with a tree which contains only the item
// at the bottom.
if (a.table.length < M)
{
var newSlot = create(item, a.height - 1);
var newA = nodeCopy(a);
newA.table.push(newSlot);
newA.lengths.push(newA.lengths[newA.lengths.length - 1] + length(newSlot));
return newA;
}
else
{
return null;
}
}
|
javascript
|
function push_(item, a)
{
// Handle resursion stop at leaf level.
if (a.height === 0)
{
if (a.table.length < M)
{
var newA = {
ctor: '_Array',
height: 0,
table: a.table.slice()
};
newA.table.push(item);
return newA;
}
else
{
return null;
}
}
// Recursively push
var pushed = push_(item, botRight(a));
// There was space in the bottom right tree, so the slot will
// be updated.
if (pushed !== null)
{
var newA = nodeCopy(a);
newA.table[newA.table.length - 1] = pushed;
newA.lengths[newA.lengths.length - 1]++;
return newA;
}
// When there was no space left, check if there is space left
// for a new slot with a tree which contains only the item
// at the bottom.
if (a.table.length < M)
{
var newSlot = create(item, a.height - 1);
var newA = nodeCopy(a);
newA.table.push(newSlot);
newA.lengths.push(newA.lengths[newA.lengths.length - 1] + length(newSlot));
return newA;
}
else
{
return null;
}
}
|
[
"function",
"push_",
"(",
"item",
",",
"a",
")",
"{",
"// Handle resursion stop at leaf level.",
"if",
"(",
"a",
".",
"height",
"===",
"0",
")",
"{",
"if",
"(",
"a",
".",
"table",
".",
"length",
"<",
"M",
")",
"{",
"var",
"newA",
"=",
"{",
"ctor",
":",
"'_Array'",
",",
"height",
":",
"0",
",",
"table",
":",
"a",
".",
"table",
".",
"slice",
"(",
")",
"}",
";",
"newA",
".",
"table",
".",
"push",
"(",
"item",
")",
";",
"return",
"newA",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}",
"// Recursively push",
"var",
"pushed",
"=",
"push_",
"(",
"item",
",",
"botRight",
"(",
"a",
")",
")",
";",
"// There was space in the bottom right tree, so the slot will",
"// be updated.",
"if",
"(",
"pushed",
"!==",
"null",
")",
"{",
"var",
"newA",
"=",
"nodeCopy",
"(",
"a",
")",
";",
"newA",
".",
"table",
"[",
"newA",
".",
"table",
".",
"length",
"-",
"1",
"]",
"=",
"pushed",
";",
"newA",
".",
"lengths",
"[",
"newA",
".",
"lengths",
".",
"length",
"-",
"1",
"]",
"++",
";",
"return",
"newA",
";",
"}",
"// When there was no space left, check if there is space left",
"// for a new slot with a tree which contains only the item",
"// at the bottom.",
"if",
"(",
"a",
".",
"table",
".",
"length",
"<",
"M",
")",
"{",
"var",
"newSlot",
"=",
"create",
"(",
"item",
",",
"a",
".",
"height",
"-",
"1",
")",
";",
"var",
"newA",
"=",
"nodeCopy",
"(",
"a",
")",
";",
"newA",
".",
"table",
".",
"push",
"(",
"newSlot",
")",
";",
"newA",
".",
"lengths",
".",
"push",
"(",
"newA",
".",
"lengths",
"[",
"newA",
".",
"lengths",
".",
"length",
"-",
"1",
"]",
"+",
"length",
"(",
"newSlot",
")",
")",
";",
"return",
"newA",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
] |
Recursively tries to push an item to the bottom-right most tree possible. If there is no space left for the item, null will be returned.
|
[
"Recursively",
"tries",
"to",
"push",
"an",
"item",
"to",
"the",
"bottom",
"-",
"right",
"most",
"tree",
"possible",
".",
"If",
"there",
"is",
"no",
"space",
"left",
"for",
"the",
"item",
"null",
"will",
"be",
"returned",
"."
] |
ae125fa9a749273a65d224bc87bbecbf06f253d8
|
https://github.com/pzavolinsky/elmx/blob/ae125fa9a749273a65d224bc87bbecbf06f253d8/cheatsheet/elm.js#L386-L435
|
18,734
|
pzavolinsky/elmx
|
cheatsheet/elm.js
|
map
|
function map(f, a)
{
var newA = {
ctor: '_Array',
height: a.height,
table: new Array(a.table.length)
};
if (a.height > 0)
{
newA.lengths = a.lengths;
}
for (var i = 0; i < a.table.length; i++)
{
newA.table[i] =
a.height === 0
? f(a.table[i])
: map(f, a.table[i]);
}
return newA;
}
|
javascript
|
function map(f, a)
{
var newA = {
ctor: '_Array',
height: a.height,
table: new Array(a.table.length)
};
if (a.height > 0)
{
newA.lengths = a.lengths;
}
for (var i = 0; i < a.table.length; i++)
{
newA.table[i] =
a.height === 0
? f(a.table[i])
: map(f, a.table[i]);
}
return newA;
}
|
[
"function",
"map",
"(",
"f",
",",
"a",
")",
"{",
"var",
"newA",
"=",
"{",
"ctor",
":",
"'_Array'",
",",
"height",
":",
"a",
".",
"height",
",",
"table",
":",
"new",
"Array",
"(",
"a",
".",
"table",
".",
"length",
")",
"}",
";",
"if",
"(",
"a",
".",
"height",
">",
"0",
")",
"{",
"newA",
".",
"lengths",
"=",
"a",
".",
"lengths",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"a",
".",
"table",
".",
"length",
";",
"i",
"++",
")",
"{",
"newA",
".",
"table",
"[",
"i",
"]",
"=",
"a",
".",
"height",
"===",
"0",
"?",
"f",
"(",
"a",
".",
"table",
"[",
"i",
"]",
")",
":",
"map",
"(",
"f",
",",
"a",
".",
"table",
"[",
"i",
"]",
")",
";",
"}",
"return",
"newA",
";",
"}"
] |
Maps a function over the elements of an array.
|
[
"Maps",
"a",
"function",
"over",
"the",
"elements",
"of",
"an",
"array",
"."
] |
ae125fa9a749273a65d224bc87bbecbf06f253d8
|
https://github.com/pzavolinsky/elmx/blob/ae125fa9a749273a65d224bc87bbecbf06f253d8/cheatsheet/elm.js#L456-L475
|
18,735
|
pzavolinsky/elmx
|
cheatsheet/elm.js
|
append
|
function append(a,b)
{
if (a.table.length === 0)
{
return b;
}
if (b.table.length === 0)
{
return a;
}
var c = append_(a, b);
// Check if both nodes can be crunshed together.
if (c[0].table.length + c[1].table.length <= M)
{
if (c[0].table.length === 0)
{
return c[1];
}
if (c[1].table.length === 0)
{
return c[0];
}
// Adjust .table and .lengths
c[0].table = c[0].table.concat(c[1].table);
if (c[0].height > 0)
{
var len = length(c[0]);
for (var i = 0; i < c[1].lengths.length; i++)
{
c[1].lengths[i] += len;
}
c[0].lengths = c[0].lengths.concat(c[1].lengths);
}
return c[0];
}
if (c[0].height > 0)
{
var toRemove = calcToRemove(a, b);
if (toRemove > E)
{
c = shuffle(c[0], c[1], toRemove);
}
}
return siblise(c[0], c[1]);
}
|
javascript
|
function append(a,b)
{
if (a.table.length === 0)
{
return b;
}
if (b.table.length === 0)
{
return a;
}
var c = append_(a, b);
// Check if both nodes can be crunshed together.
if (c[0].table.length + c[1].table.length <= M)
{
if (c[0].table.length === 0)
{
return c[1];
}
if (c[1].table.length === 0)
{
return c[0];
}
// Adjust .table and .lengths
c[0].table = c[0].table.concat(c[1].table);
if (c[0].height > 0)
{
var len = length(c[0]);
for (var i = 0; i < c[1].lengths.length; i++)
{
c[1].lengths[i] += len;
}
c[0].lengths = c[0].lengths.concat(c[1].lengths);
}
return c[0];
}
if (c[0].height > 0)
{
var toRemove = calcToRemove(a, b);
if (toRemove > E)
{
c = shuffle(c[0], c[1], toRemove);
}
}
return siblise(c[0], c[1]);
}
|
[
"function",
"append",
"(",
"a",
",",
"b",
")",
"{",
"if",
"(",
"a",
".",
"table",
".",
"length",
"===",
"0",
")",
"{",
"return",
"b",
";",
"}",
"if",
"(",
"b",
".",
"table",
".",
"length",
"===",
"0",
")",
"{",
"return",
"a",
";",
"}",
"var",
"c",
"=",
"append_",
"(",
"a",
",",
"b",
")",
";",
"// Check if both nodes can be crunshed together.",
"if",
"(",
"c",
"[",
"0",
"]",
".",
"table",
".",
"length",
"+",
"c",
"[",
"1",
"]",
".",
"table",
".",
"length",
"<=",
"M",
")",
"{",
"if",
"(",
"c",
"[",
"0",
"]",
".",
"table",
".",
"length",
"===",
"0",
")",
"{",
"return",
"c",
"[",
"1",
"]",
";",
"}",
"if",
"(",
"c",
"[",
"1",
"]",
".",
"table",
".",
"length",
"===",
"0",
")",
"{",
"return",
"c",
"[",
"0",
"]",
";",
"}",
"// Adjust .table and .lengths",
"c",
"[",
"0",
"]",
".",
"table",
"=",
"c",
"[",
"0",
"]",
".",
"table",
".",
"concat",
"(",
"c",
"[",
"1",
"]",
".",
"table",
")",
";",
"if",
"(",
"c",
"[",
"0",
"]",
".",
"height",
">",
"0",
")",
"{",
"var",
"len",
"=",
"length",
"(",
"c",
"[",
"0",
"]",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"c",
"[",
"1",
"]",
".",
"lengths",
".",
"length",
";",
"i",
"++",
")",
"{",
"c",
"[",
"1",
"]",
".",
"lengths",
"[",
"i",
"]",
"+=",
"len",
";",
"}",
"c",
"[",
"0",
"]",
".",
"lengths",
"=",
"c",
"[",
"0",
"]",
".",
"lengths",
".",
"concat",
"(",
"c",
"[",
"1",
"]",
".",
"lengths",
")",
";",
"}",
"return",
"c",
"[",
"0",
"]",
";",
"}",
"if",
"(",
"c",
"[",
"0",
"]",
".",
"height",
">",
"0",
")",
"{",
"var",
"toRemove",
"=",
"calcToRemove",
"(",
"a",
",",
"b",
")",
";",
"if",
"(",
"toRemove",
">",
"E",
")",
"{",
"c",
"=",
"shuffle",
"(",
"c",
"[",
"0",
"]",
",",
"c",
"[",
"1",
"]",
",",
"toRemove",
")",
";",
"}",
"}",
"return",
"siblise",
"(",
"c",
"[",
"0",
"]",
",",
"c",
"[",
"1",
"]",
")",
";",
"}"
] |
Appends two trees.
|
[
"Appends",
"two",
"trees",
"."
] |
ae125fa9a749273a65d224bc87bbecbf06f253d8
|
https://github.com/pzavolinsky/elmx/blob/ae125fa9a749273a65d224bc87bbecbf06f253d8/cheatsheet/elm.js#L641-L691
|
18,736
|
pzavolinsky/elmx
|
cheatsheet/elm.js
|
insertRight
|
function insertRight(parent, node)
{
var index = parent.table.length - 1;
parent.table[index] = node;
parent.lengths[index] = length(node);
parent.lengths[index] += index > 0 ? parent.lengths[index - 1] : 0;
}
|
javascript
|
function insertRight(parent, node)
{
var index = parent.table.length - 1;
parent.table[index] = node;
parent.lengths[index] = length(node);
parent.lengths[index] += index > 0 ? parent.lengths[index - 1] : 0;
}
|
[
"function",
"insertRight",
"(",
"parent",
",",
"node",
")",
"{",
"var",
"index",
"=",
"parent",
".",
"table",
".",
"length",
"-",
"1",
";",
"parent",
".",
"table",
"[",
"index",
"]",
"=",
"node",
";",
"parent",
".",
"lengths",
"[",
"index",
"]",
"=",
"length",
"(",
"node",
")",
";",
"parent",
".",
"lengths",
"[",
"index",
"]",
"+=",
"index",
">",
"0",
"?",
"parent",
".",
"lengths",
"[",
"index",
"-",
"1",
"]",
":",
"0",
";",
"}"
] |
Helperfunctions for append_. Replaces a child node at the side of the parent.
|
[
"Helperfunctions",
"for",
"append_",
".",
"Replaces",
"a",
"child",
"node",
"at",
"the",
"side",
"of",
"the",
"parent",
"."
] |
ae125fa9a749273a65d224bc87bbecbf06f253d8
|
https://github.com/pzavolinsky/elmx/blob/ae125fa9a749273a65d224bc87bbecbf06f253d8/cheatsheet/elm.js#L747-L753
|
18,737
|
pzavolinsky/elmx
|
cheatsheet/elm.js
|
get2
|
function get2(a, b, index)
{
return index < a.length
? a[index]
: b[index - a.length];
}
|
javascript
|
function get2(a, b, index)
{
return index < a.length
? a[index]
: b[index - a.length];
}
|
[
"function",
"get2",
"(",
"a",
",",
"b",
",",
"index",
")",
"{",
"return",
"index",
"<",
"a",
".",
"length",
"?",
"a",
"[",
"index",
"]",
":",
"b",
"[",
"index",
"-",
"a",
".",
"length",
"]",
";",
"}"
] |
get2, set2 and saveSlot are helpers for accessing elements over two arrays.
|
[
"get2",
"set2",
"and",
"saveSlot",
"are",
"helpers",
"for",
"accessing",
"elements",
"over",
"two",
"arrays",
"."
] |
ae125fa9a749273a65d224bc87bbecbf06f253d8
|
https://github.com/pzavolinsky/elmx/blob/ae125fa9a749273a65d224bc87bbecbf06f253d8/cheatsheet/elm.js#L798-L803
|
18,738
|
pzavolinsky/elmx
|
cheatsheet/elm.js
|
createNode
|
function createNode(h, length)
{
if (length < 0)
{
length = 0;
}
var a = {
ctor: '_Array',
height: h,
table: new Array(length)
};
if (h > 0)
{
a.lengths = new Array(length);
}
return a;
}
|
javascript
|
function createNode(h, length)
{
if (length < 0)
{
length = 0;
}
var a = {
ctor: '_Array',
height: h,
table: new Array(length)
};
if (h > 0)
{
a.lengths = new Array(length);
}
return a;
}
|
[
"function",
"createNode",
"(",
"h",
",",
"length",
")",
"{",
"if",
"(",
"length",
"<",
"0",
")",
"{",
"length",
"=",
"0",
";",
"}",
"var",
"a",
"=",
"{",
"ctor",
":",
"'_Array'",
",",
"height",
":",
"h",
",",
"table",
":",
"new",
"Array",
"(",
"length",
")",
"}",
";",
"if",
"(",
"h",
">",
"0",
")",
"{",
"a",
".",
"lengths",
"=",
"new",
"Array",
"(",
"length",
")",
";",
"}",
"return",
"a",
";",
"}"
] |
Creates a node or leaf with a given length at their arrays for perfomance. Is only used by shuffle.
|
[
"Creates",
"a",
"node",
"or",
"leaf",
"with",
"a",
"given",
"length",
"at",
"their",
"arrays",
"for",
"perfomance",
".",
"Is",
"only",
"used",
"by",
"shuffle",
"."
] |
ae125fa9a749273a65d224bc87bbecbf06f253d8
|
https://github.com/pzavolinsky/elmx/blob/ae125fa9a749273a65d224bc87bbecbf06f253d8/cheatsheet/elm.js#L830-L846
|
18,739
|
pzavolinsky/elmx
|
cheatsheet/elm.js
|
nodeCopy
|
function nodeCopy(a)
{
var newA = {
ctor: '_Array',
height: a.height,
table: a.table.slice()
};
if (a.height > 0)
{
newA.lengths = a.lengths.slice();
}
return newA;
}
|
javascript
|
function nodeCopy(a)
{
var newA = {
ctor: '_Array',
height: a.height,
table: a.table.slice()
};
if (a.height > 0)
{
newA.lengths = a.lengths.slice();
}
return newA;
}
|
[
"function",
"nodeCopy",
"(",
"a",
")",
"{",
"var",
"newA",
"=",
"{",
"ctor",
":",
"'_Array'",
",",
"height",
":",
"a",
".",
"height",
",",
"table",
":",
"a",
".",
"table",
".",
"slice",
"(",
")",
"}",
";",
"if",
"(",
"a",
".",
"height",
">",
"0",
")",
"{",
"newA",
".",
"lengths",
"=",
"a",
".",
"lengths",
".",
"slice",
"(",
")",
";",
"}",
"return",
"newA",
";",
"}"
] |
Copies a node for updating. Note that you should not use this if only updating only one of "table" or "lengths" for performance reasons.
|
[
"Copies",
"a",
"node",
"for",
"updating",
".",
"Note",
"that",
"you",
"should",
"not",
"use",
"this",
"if",
"only",
"updating",
"only",
"one",
"of",
"table",
"or",
"lengths",
"for",
"performance",
"reasons",
"."
] |
ae125fa9a749273a65d224bc87bbecbf06f253d8
|
https://github.com/pzavolinsky/elmx/blob/ae125fa9a749273a65d224bc87bbecbf06f253d8/cheatsheet/elm.js#L938-L950
|
18,740
|
pzavolinsky/elmx
|
cheatsheet/elm.js
|
length
|
function length(array)
{
if (array.height === 0)
{
return array.table.length;
}
else
{
return array.lengths[array.lengths.length - 1];
}
}
|
javascript
|
function length(array)
{
if (array.height === 0)
{
return array.table.length;
}
else
{
return array.lengths[array.lengths.length - 1];
}
}
|
[
"function",
"length",
"(",
"array",
")",
"{",
"if",
"(",
"array",
".",
"height",
"===",
"0",
")",
"{",
"return",
"array",
".",
"table",
".",
"length",
";",
"}",
"else",
"{",
"return",
"array",
".",
"lengths",
"[",
"array",
".",
"lengths",
".",
"length",
"-",
"1",
"]",
";",
"}",
"}"
] |
Returns how many items are in the tree.
|
[
"Returns",
"how",
"many",
"items",
"are",
"in",
"the",
"tree",
"."
] |
ae125fa9a749273a65d224bc87bbecbf06f253d8
|
https://github.com/pzavolinsky/elmx/blob/ae125fa9a749273a65d224bc87bbecbf06f253d8/cheatsheet/elm.js#L953-L963
|
18,741
|
pzavolinsky/elmx
|
cheatsheet/elm.js
|
getSlot
|
function getSlot(i, a)
{
var slot = i >> (5 * a.height);
while (a.lengths[slot] <= i)
{
slot++;
}
return slot;
}
|
javascript
|
function getSlot(i, a)
{
var slot = i >> (5 * a.height);
while (a.lengths[slot] <= i)
{
slot++;
}
return slot;
}
|
[
"function",
"getSlot",
"(",
"i",
",",
"a",
")",
"{",
"var",
"slot",
"=",
"i",
">>",
"(",
"5",
"*",
"a",
".",
"height",
")",
";",
"while",
"(",
"a",
".",
"lengths",
"[",
"slot",
"]",
"<=",
"i",
")",
"{",
"slot",
"++",
";",
"}",
"return",
"slot",
";",
"}"
] |
Calculates in which slot of "table" the item probably is, then find the exact slot via forward searching in "lengths". Returns the index.
|
[
"Calculates",
"in",
"which",
"slot",
"of",
"table",
"the",
"item",
"probably",
"is",
"then",
"find",
"the",
"exact",
"slot",
"via",
"forward",
"searching",
"in",
"lengths",
".",
"Returns",
"the",
"index",
"."
] |
ae125fa9a749273a65d224bc87bbecbf06f253d8
|
https://github.com/pzavolinsky/elmx/blob/ae125fa9a749273a65d224bc87bbecbf06f253d8/cheatsheet/elm.js#L967-L975
|
18,742
|
pzavolinsky/elmx
|
cheatsheet/elm.js
|
create
|
function create(item, h)
{
if (h === 0)
{
return {
ctor: '_Array',
height: 0,
table: [item]
};
}
return {
ctor: '_Array',
height: h,
table: [create(item, h - 1)],
lengths: [1]
};
}
|
javascript
|
function create(item, h)
{
if (h === 0)
{
return {
ctor: '_Array',
height: 0,
table: [item]
};
}
return {
ctor: '_Array',
height: h,
table: [create(item, h - 1)],
lengths: [1]
};
}
|
[
"function",
"create",
"(",
"item",
",",
"h",
")",
"{",
"if",
"(",
"h",
"===",
"0",
")",
"{",
"return",
"{",
"ctor",
":",
"'_Array'",
",",
"height",
":",
"0",
",",
"table",
":",
"[",
"item",
"]",
"}",
";",
"}",
"return",
"{",
"ctor",
":",
"'_Array'",
",",
"height",
":",
"h",
",",
"table",
":",
"[",
"create",
"(",
"item",
",",
"h",
"-",
"1",
")",
"]",
",",
"lengths",
":",
"[",
"1",
"]",
"}",
";",
"}"
] |
Recursively creates a tree with a given height containing only the given item.
|
[
"Recursively",
"creates",
"a",
"tree",
"with",
"a",
"given",
"height",
"containing",
"only",
"the",
"given",
"item",
"."
] |
ae125fa9a749273a65d224bc87bbecbf06f253d8
|
https://github.com/pzavolinsky/elmx/blob/ae125fa9a749273a65d224bc87bbecbf06f253d8/cheatsheet/elm.js#L979-L995
|
18,743
|
pzavolinsky/elmx
|
cheatsheet/elm.js
|
mainToProgram
|
function mainToProgram(moduleName, wrappedMain)
{
var main = wrappedMain.main;
if (typeof main.init === 'undefined')
{
var emptyBag = batch(_elm_lang$core$Native_List.Nil);
var noChange = _elm_lang$core$Native_Utils.Tuple2(
_elm_lang$core$Native_Utils.Tuple0,
emptyBag
);
return _elm_lang$virtual_dom$VirtualDom$programWithFlags({
init: function() { return noChange; },
view: function() { return main; },
update: F2(function() { return noChange; }),
subscriptions: function () { return emptyBag; }
});
}
var flags = wrappedMain.flags;
var init = flags
? initWithFlags(moduleName, main.init, flags)
: initWithoutFlags(moduleName, main.init);
return _elm_lang$virtual_dom$VirtualDom$programWithFlags({
init: init,
view: main.view,
update: main.update,
subscriptions: main.subscriptions,
});
}
|
javascript
|
function mainToProgram(moduleName, wrappedMain)
{
var main = wrappedMain.main;
if (typeof main.init === 'undefined')
{
var emptyBag = batch(_elm_lang$core$Native_List.Nil);
var noChange = _elm_lang$core$Native_Utils.Tuple2(
_elm_lang$core$Native_Utils.Tuple0,
emptyBag
);
return _elm_lang$virtual_dom$VirtualDom$programWithFlags({
init: function() { return noChange; },
view: function() { return main; },
update: F2(function() { return noChange; }),
subscriptions: function () { return emptyBag; }
});
}
var flags = wrappedMain.flags;
var init = flags
? initWithFlags(moduleName, main.init, flags)
: initWithoutFlags(moduleName, main.init);
return _elm_lang$virtual_dom$VirtualDom$programWithFlags({
init: init,
view: main.view,
update: main.update,
subscriptions: main.subscriptions,
});
}
|
[
"function",
"mainToProgram",
"(",
"moduleName",
",",
"wrappedMain",
")",
"{",
"var",
"main",
"=",
"wrappedMain",
".",
"main",
";",
"if",
"(",
"typeof",
"main",
".",
"init",
"===",
"'undefined'",
")",
"{",
"var",
"emptyBag",
"=",
"batch",
"(",
"_elm_lang$core$Native_List",
".",
"Nil",
")",
";",
"var",
"noChange",
"=",
"_elm_lang$core$Native_Utils",
".",
"Tuple2",
"(",
"_elm_lang$core$Native_Utils",
".",
"Tuple0",
",",
"emptyBag",
")",
";",
"return",
"_elm_lang$virtual_dom$VirtualDom$programWithFlags",
"(",
"{",
"init",
":",
"function",
"(",
")",
"{",
"return",
"noChange",
";",
"}",
",",
"view",
":",
"function",
"(",
")",
"{",
"return",
"main",
";",
"}",
",",
"update",
":",
"F2",
"(",
"function",
"(",
")",
"{",
"return",
"noChange",
";",
"}",
")",
",",
"subscriptions",
":",
"function",
"(",
")",
"{",
"return",
"emptyBag",
";",
"}",
"}",
")",
";",
"}",
"var",
"flags",
"=",
"wrappedMain",
".",
"flags",
";",
"var",
"init",
"=",
"flags",
"?",
"initWithFlags",
"(",
"moduleName",
",",
"main",
".",
"init",
",",
"flags",
")",
":",
"initWithoutFlags",
"(",
"moduleName",
",",
"main",
".",
"init",
")",
";",
"return",
"_elm_lang$virtual_dom$VirtualDom$programWithFlags",
"(",
"{",
"init",
":",
"init",
",",
"view",
":",
"main",
".",
"view",
",",
"update",
":",
"main",
".",
"update",
",",
"subscriptions",
":",
"main",
".",
"subscriptions",
",",
"}",
")",
";",
"}"
] |
MAIN TO PROGRAM
|
[
"MAIN",
"TO",
"PROGRAM"
] |
ae125fa9a749273a65d224bc87bbecbf06f253d8
|
https://github.com/pzavolinsky/elmx/blob/ae125fa9a749273a65d224bc87bbecbf06f253d8/cheatsheet/elm.js#L2903-L2934
|
18,744
|
pzavolinsky/elmx
|
cheatsheet/elm.js
|
makeEmbedHelp
|
function makeEmbedHelp(moduleName, program, rootDomNode, flags)
{
var init = program.init;
var update = program.update;
var subscriptions = program.subscriptions;
var view = program.view;
var makeRenderer = program.renderer;
// ambient state
var managers = {};
var renderer;
// init and update state in main process
var initApp = _elm_lang$core$Native_Scheduler.nativeBinding(function(callback) {
var results = init(flags);
var model = results._0;
renderer = makeRenderer(rootDomNode, enqueue, view(model));
var cmds = results._1;
var subs = subscriptions(model);
dispatchEffects(managers, cmds, subs);
callback(_elm_lang$core$Native_Scheduler.succeed(model));
});
function onMessage(msg, model)
{
return _elm_lang$core$Native_Scheduler.nativeBinding(function(callback) {
var results = A2(update, msg, model);
model = results._0;
renderer.update(view(model));
var cmds = results._1;
var subs = subscriptions(model);
dispatchEffects(managers, cmds, subs);
callback(_elm_lang$core$Native_Scheduler.succeed(model));
});
}
var mainProcess = spawnLoop(initApp, onMessage);
function enqueue(msg)
{
_elm_lang$core$Native_Scheduler.rawSend(mainProcess, msg);
}
var ports = setupEffects(managers, enqueue);
return ports ? { ports: ports } : {};
}
|
javascript
|
function makeEmbedHelp(moduleName, program, rootDomNode, flags)
{
var init = program.init;
var update = program.update;
var subscriptions = program.subscriptions;
var view = program.view;
var makeRenderer = program.renderer;
// ambient state
var managers = {};
var renderer;
// init and update state in main process
var initApp = _elm_lang$core$Native_Scheduler.nativeBinding(function(callback) {
var results = init(flags);
var model = results._0;
renderer = makeRenderer(rootDomNode, enqueue, view(model));
var cmds = results._1;
var subs = subscriptions(model);
dispatchEffects(managers, cmds, subs);
callback(_elm_lang$core$Native_Scheduler.succeed(model));
});
function onMessage(msg, model)
{
return _elm_lang$core$Native_Scheduler.nativeBinding(function(callback) {
var results = A2(update, msg, model);
model = results._0;
renderer.update(view(model));
var cmds = results._1;
var subs = subscriptions(model);
dispatchEffects(managers, cmds, subs);
callback(_elm_lang$core$Native_Scheduler.succeed(model));
});
}
var mainProcess = spawnLoop(initApp, onMessage);
function enqueue(msg)
{
_elm_lang$core$Native_Scheduler.rawSend(mainProcess, msg);
}
var ports = setupEffects(managers, enqueue);
return ports ? { ports: ports } : {};
}
|
[
"function",
"makeEmbedHelp",
"(",
"moduleName",
",",
"program",
",",
"rootDomNode",
",",
"flags",
")",
"{",
"var",
"init",
"=",
"program",
".",
"init",
";",
"var",
"update",
"=",
"program",
".",
"update",
";",
"var",
"subscriptions",
"=",
"program",
".",
"subscriptions",
";",
"var",
"view",
"=",
"program",
".",
"view",
";",
"var",
"makeRenderer",
"=",
"program",
".",
"renderer",
";",
"// ambient state",
"var",
"managers",
"=",
"{",
"}",
";",
"var",
"renderer",
";",
"// init and update state in main process",
"var",
"initApp",
"=",
"_elm_lang$core$Native_Scheduler",
".",
"nativeBinding",
"(",
"function",
"(",
"callback",
")",
"{",
"var",
"results",
"=",
"init",
"(",
"flags",
")",
";",
"var",
"model",
"=",
"results",
".",
"_0",
";",
"renderer",
"=",
"makeRenderer",
"(",
"rootDomNode",
",",
"enqueue",
",",
"view",
"(",
"model",
")",
")",
";",
"var",
"cmds",
"=",
"results",
".",
"_1",
";",
"var",
"subs",
"=",
"subscriptions",
"(",
"model",
")",
";",
"dispatchEffects",
"(",
"managers",
",",
"cmds",
",",
"subs",
")",
";",
"callback",
"(",
"_elm_lang$core$Native_Scheduler",
".",
"succeed",
"(",
"model",
")",
")",
";",
"}",
")",
";",
"function",
"onMessage",
"(",
"msg",
",",
"model",
")",
"{",
"return",
"_elm_lang$core$Native_Scheduler",
".",
"nativeBinding",
"(",
"function",
"(",
"callback",
")",
"{",
"var",
"results",
"=",
"A2",
"(",
"update",
",",
"msg",
",",
"model",
")",
";",
"model",
"=",
"results",
".",
"_0",
";",
"renderer",
".",
"update",
"(",
"view",
"(",
"model",
")",
")",
";",
"var",
"cmds",
"=",
"results",
".",
"_1",
";",
"var",
"subs",
"=",
"subscriptions",
"(",
"model",
")",
";",
"dispatchEffects",
"(",
"managers",
",",
"cmds",
",",
"subs",
")",
";",
"callback",
"(",
"_elm_lang$core$Native_Scheduler",
".",
"succeed",
"(",
"model",
")",
")",
";",
"}",
")",
";",
"}",
"var",
"mainProcess",
"=",
"spawnLoop",
"(",
"initApp",
",",
"onMessage",
")",
";",
"function",
"enqueue",
"(",
"msg",
")",
"{",
"_elm_lang$core$Native_Scheduler",
".",
"rawSend",
"(",
"mainProcess",
",",
"msg",
")",
";",
"}",
"var",
"ports",
"=",
"setupEffects",
"(",
"managers",
",",
"enqueue",
")",
";",
"return",
"ports",
"?",
"{",
"ports",
":",
"ports",
"}",
":",
"{",
"}",
";",
"}"
] |
SETUP RUNTIME SYSTEM
|
[
"SETUP",
"RUNTIME",
"SYSTEM"
] |
ae125fa9a749273a65d224bc87bbecbf06f253d8
|
https://github.com/pzavolinsky/elmx/blob/ae125fa9a749273a65d224bc87bbecbf06f253d8/cheatsheet/elm.js#L2972-L3018
|
18,745
|
aurelia-ui-toolkits/aurelia-materialize-bridge
|
dist/commonjs/common/events.js
|
fireEvent
|
function fireEvent(element, name, data) {
if (data === void 0) { data = {}; }
var event = new CustomEvent(name, {
detail: data,
bubbles: true
});
element.dispatchEvent(event);
return event;
}
|
javascript
|
function fireEvent(element, name, data) {
if (data === void 0) { data = {}; }
var event = new CustomEvent(name, {
detail: data,
bubbles: true
});
element.dispatchEvent(event);
return event;
}
|
[
"function",
"fireEvent",
"(",
"element",
",",
"name",
",",
"data",
")",
"{",
"if",
"(",
"data",
"===",
"void",
"0",
")",
"{",
"data",
"=",
"{",
"}",
";",
"}",
"var",
"event",
"=",
"new",
"CustomEvent",
"(",
"name",
",",
"{",
"detail",
":",
"data",
",",
"bubbles",
":",
"true",
"}",
")",
";",
"element",
".",
"dispatchEvent",
"(",
"event",
")",
";",
"return",
"event",
";",
"}"
] |
Fire DOM event on an element
@param element The Element which the DOM event will be fired on
@param name The Event's name
@param data Addition data to attach to an event
|
[
"Fire",
"DOM",
"event",
"on",
"an",
"element"
] |
a25f1131465d19e8139c99dc5022df1cda5001c1
|
https://github.com/aurelia-ui-toolkits/aurelia-materialize-bridge/blob/a25f1131465d19e8139c99dc5022df1cda5001c1/dist/commonjs/common/events.js#L10-L18
|
18,746
|
aurelia-ui-toolkits/aurelia-materialize-bridge
|
dist/commonjs/common/events.js
|
fireMaterializeEvent
|
function fireMaterializeEvent(element, name, data) {
if (data === void 0) { data = {}; }
return fireEvent(element, "" + constants_1.constants.eventPrefix + name, data);
}
|
javascript
|
function fireMaterializeEvent(element, name, data) {
if (data === void 0) { data = {}; }
return fireEvent(element, "" + constants_1.constants.eventPrefix + name, data);
}
|
[
"function",
"fireMaterializeEvent",
"(",
"element",
",",
"name",
",",
"data",
")",
"{",
"if",
"(",
"data",
"===",
"void",
"0",
")",
"{",
"data",
"=",
"{",
"}",
";",
"}",
"return",
"fireEvent",
"(",
"element",
",",
"\"\"",
"+",
"constants_1",
".",
"constants",
".",
"eventPrefix",
"+",
"name",
",",
"data",
")",
";",
"}"
] |
Fire DOM event on an element with the md-on prefix
@param element The Element which the DOM event will be fired on
@param name The Event's name, without md-on prefix
@param data Addition data to attach to an event
|
[
"Fire",
"DOM",
"event",
"on",
"an",
"element",
"with",
"the",
"md",
"-",
"on",
"prefix"
] |
a25f1131465d19e8139c99dc5022df1cda5001c1
|
https://github.com/aurelia-ui-toolkits/aurelia-materialize-bridge/blob/a25f1131465d19e8139c99dc5022df1cda5001c1/dist/commonjs/common/events.js#L26-L29
|
18,747
|
aurelia-ui-toolkits/aurelia-materialize-bridge
|
dist/system/common/util.js
|
cleanOptions
|
function cleanOptions(options) {
Object.keys(options).filter(function (key) { return options[key] === undefined; }).forEach(function (key) { return delete options[key]; });
}
|
javascript
|
function cleanOptions(options) {
Object.keys(options).filter(function (key) { return options[key] === undefined; }).forEach(function (key) { return delete options[key]; });
}
|
[
"function",
"cleanOptions",
"(",
"options",
")",
"{",
"Object",
".",
"keys",
"(",
"options",
")",
".",
"filter",
"(",
"function",
"(",
"key",
")",
"{",
"return",
"options",
"[",
"key",
"]",
"===",
"undefined",
";",
"}",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"return",
"delete",
"options",
"[",
"key",
"]",
";",
"}",
")",
";",
"}"
] |
Remove undefined fields from an object
@param options An object to clean
|
[
"Remove",
"undefined",
"fields",
"from",
"an",
"object"
] |
a25f1131465d19e8139c99dc5022df1cda5001c1
|
https://github.com/aurelia-ui-toolkits/aurelia-materialize-bridge/blob/a25f1131465d19e8139c99dc5022df1cda5001c1/dist/system/common/util.js#L26-L28
|
18,748
|
jonschlinkert/to-regex
|
index.js
|
makeRe
|
function makeRe(pattern, options) {
if (pattern instanceof RegExp) {
return pattern;
}
if (typeof pattern !== 'string') {
throw new TypeError('expected a string');
}
if (pattern.length > MAX_LENGTH) {
throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters');
}
var key = pattern;
// do this before shallow cloning options, it's a lot faster
if (!options || (options && options.cache !== false)) {
key = createKey(pattern, options);
if (cache.hasOwnProperty(key)) {
return cache[key];
}
}
var opts = extend({}, options);
if (opts.contains === true) {
if (opts.negate === true) {
opts.strictNegate = false;
} else {
opts.strict = false;
}
}
if (opts.strict === false) {
opts.strictOpen = false;
opts.strictClose = false;
}
var open = opts.strictOpen !== false ? '^' : '';
var close = opts.strictClose !== false ? '$' : '';
var flags = opts.flags || '';
var regex;
if (opts.nocase === true && !/i/.test(flags)) {
flags += 'i';
}
try {
if (opts.negate || typeof opts.strictNegate === 'boolean') {
pattern = not.create(pattern, opts);
}
var str = open + '(?:' + pattern + ')' + close;
regex = new RegExp(str, flags);
if (opts.safe === true && safe(regex) === false) {
throw new Error('potentially unsafe regular expression: ' + regex.source);
}
} catch (err) {
if (opts.strictErrors === true || opts.safe === true) {
err.key = key;
err.pattern = pattern;
err.originalOptions = options;
err.createdOptions = opts;
throw err;
}
try {
regex = new RegExp('^' + pattern.replace(/(\W)/g, '\\$1') + '$');
} catch (err) {
regex = /.^/; //<= match nothing
}
}
if (opts.cache !== false) {
memoize(regex, key, pattern, opts);
}
return regex;
}
|
javascript
|
function makeRe(pattern, options) {
if (pattern instanceof RegExp) {
return pattern;
}
if (typeof pattern !== 'string') {
throw new TypeError('expected a string');
}
if (pattern.length > MAX_LENGTH) {
throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters');
}
var key = pattern;
// do this before shallow cloning options, it's a lot faster
if (!options || (options && options.cache !== false)) {
key = createKey(pattern, options);
if (cache.hasOwnProperty(key)) {
return cache[key];
}
}
var opts = extend({}, options);
if (opts.contains === true) {
if (opts.negate === true) {
opts.strictNegate = false;
} else {
opts.strict = false;
}
}
if (opts.strict === false) {
opts.strictOpen = false;
opts.strictClose = false;
}
var open = opts.strictOpen !== false ? '^' : '';
var close = opts.strictClose !== false ? '$' : '';
var flags = opts.flags || '';
var regex;
if (opts.nocase === true && !/i/.test(flags)) {
flags += 'i';
}
try {
if (opts.negate || typeof opts.strictNegate === 'boolean') {
pattern = not.create(pattern, opts);
}
var str = open + '(?:' + pattern + ')' + close;
regex = new RegExp(str, flags);
if (opts.safe === true && safe(regex) === false) {
throw new Error('potentially unsafe regular expression: ' + regex.source);
}
} catch (err) {
if (opts.strictErrors === true || opts.safe === true) {
err.key = key;
err.pattern = pattern;
err.originalOptions = options;
err.createdOptions = opts;
throw err;
}
try {
regex = new RegExp('^' + pattern.replace(/(\W)/g, '\\$1') + '$');
} catch (err) {
regex = /.^/; //<= match nothing
}
}
if (opts.cache !== false) {
memoize(regex, key, pattern, opts);
}
return regex;
}
|
[
"function",
"makeRe",
"(",
"pattern",
",",
"options",
")",
"{",
"if",
"(",
"pattern",
"instanceof",
"RegExp",
")",
"{",
"return",
"pattern",
";",
"}",
"if",
"(",
"typeof",
"pattern",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'expected a string'",
")",
";",
"}",
"if",
"(",
"pattern",
".",
"length",
">",
"MAX_LENGTH",
")",
"{",
"throw",
"new",
"Error",
"(",
"'expected pattern to be less than '",
"+",
"MAX_LENGTH",
"+",
"' characters'",
")",
";",
"}",
"var",
"key",
"=",
"pattern",
";",
"// do this before shallow cloning options, it's a lot faster",
"if",
"(",
"!",
"options",
"||",
"(",
"options",
"&&",
"options",
".",
"cache",
"!==",
"false",
")",
")",
"{",
"key",
"=",
"createKey",
"(",
"pattern",
",",
"options",
")",
";",
"if",
"(",
"cache",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"return",
"cache",
"[",
"key",
"]",
";",
"}",
"}",
"var",
"opts",
"=",
"extend",
"(",
"{",
"}",
",",
"options",
")",
";",
"if",
"(",
"opts",
".",
"contains",
"===",
"true",
")",
"{",
"if",
"(",
"opts",
".",
"negate",
"===",
"true",
")",
"{",
"opts",
".",
"strictNegate",
"=",
"false",
";",
"}",
"else",
"{",
"opts",
".",
"strict",
"=",
"false",
";",
"}",
"}",
"if",
"(",
"opts",
".",
"strict",
"===",
"false",
")",
"{",
"opts",
".",
"strictOpen",
"=",
"false",
";",
"opts",
".",
"strictClose",
"=",
"false",
";",
"}",
"var",
"open",
"=",
"opts",
".",
"strictOpen",
"!==",
"false",
"?",
"'^'",
":",
"''",
";",
"var",
"close",
"=",
"opts",
".",
"strictClose",
"!==",
"false",
"?",
"'$'",
":",
"''",
";",
"var",
"flags",
"=",
"opts",
".",
"flags",
"||",
"''",
";",
"var",
"regex",
";",
"if",
"(",
"opts",
".",
"nocase",
"===",
"true",
"&&",
"!",
"/",
"i",
"/",
".",
"test",
"(",
"flags",
")",
")",
"{",
"flags",
"+=",
"'i'",
";",
"}",
"try",
"{",
"if",
"(",
"opts",
".",
"negate",
"||",
"typeof",
"opts",
".",
"strictNegate",
"===",
"'boolean'",
")",
"{",
"pattern",
"=",
"not",
".",
"create",
"(",
"pattern",
",",
"opts",
")",
";",
"}",
"var",
"str",
"=",
"open",
"+",
"'(?:'",
"+",
"pattern",
"+",
"')'",
"+",
"close",
";",
"regex",
"=",
"new",
"RegExp",
"(",
"str",
",",
"flags",
")",
";",
"if",
"(",
"opts",
".",
"safe",
"===",
"true",
"&&",
"safe",
"(",
"regex",
")",
"===",
"false",
")",
"{",
"throw",
"new",
"Error",
"(",
"'potentially unsafe regular expression: '",
"+",
"regex",
".",
"source",
")",
";",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"if",
"(",
"opts",
".",
"strictErrors",
"===",
"true",
"||",
"opts",
".",
"safe",
"===",
"true",
")",
"{",
"err",
".",
"key",
"=",
"key",
";",
"err",
".",
"pattern",
"=",
"pattern",
";",
"err",
".",
"originalOptions",
"=",
"options",
";",
"err",
".",
"createdOptions",
"=",
"opts",
";",
"throw",
"err",
";",
"}",
"try",
"{",
"regex",
"=",
"new",
"RegExp",
"(",
"'^'",
"+",
"pattern",
".",
"replace",
"(",
"/",
"(\\W)",
"/",
"g",
",",
"'\\\\$1'",
")",
"+",
"'$'",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"regex",
"=",
"/",
".^",
"/",
";",
"//<= match nothing",
"}",
"}",
"if",
"(",
"opts",
".",
"cache",
"!==",
"false",
")",
"{",
"memoize",
"(",
"regex",
",",
"key",
",",
"pattern",
",",
"opts",
")",
";",
"}",
"return",
"regex",
";",
"}"
] |
Create a regular expression from the given `pattern` string.
@param {String|RegExp} `pattern` Pattern can be a string or regular expression.
@param {Object} `options`
@return {RegExp}
@api public
|
[
"Create",
"a",
"regular",
"expression",
"from",
"the",
"given",
"pattern",
"string",
"."
] |
cc5735f98f62c8e9cfb98ae5b309abea1c8a2432
|
https://github.com/jonschlinkert/to-regex/blob/cc5735f98f62c8e9cfb98ae5b309abea1c8a2432/index.js#L40-L118
|
18,749
|
jonschlinkert/to-regex
|
index.js
|
memoize
|
function memoize(regex, key, pattern, options) {
define(regex, 'cached', true);
define(regex, 'pattern', pattern);
define(regex, 'options', options);
define(regex, 'key', key);
cache[key] = regex;
}
|
javascript
|
function memoize(regex, key, pattern, options) {
define(regex, 'cached', true);
define(regex, 'pattern', pattern);
define(regex, 'options', options);
define(regex, 'key', key);
cache[key] = regex;
}
|
[
"function",
"memoize",
"(",
"regex",
",",
"key",
",",
"pattern",
",",
"options",
")",
"{",
"define",
"(",
"regex",
",",
"'cached'",
",",
"true",
")",
";",
"define",
"(",
"regex",
",",
"'pattern'",
",",
"pattern",
")",
";",
"define",
"(",
"regex",
",",
"'options'",
",",
"options",
")",
";",
"define",
"(",
"regex",
",",
"'key'",
",",
"key",
")",
";",
"cache",
"[",
"key",
"]",
"=",
"regex",
";",
"}"
] |
Memoize generated regex. This can result in dramatic speed improvements
and simplify debugging by adding options and pattern to the regex. It can be
disabled by passing setting `options.cache` to false.
|
[
"Memoize",
"generated",
"regex",
".",
"This",
"can",
"result",
"in",
"dramatic",
"speed",
"improvements",
"and",
"simplify",
"debugging",
"by",
"adding",
"options",
"and",
"pattern",
"to",
"the",
"regex",
".",
"It",
"can",
"be",
"disabled",
"by",
"passing",
"setting",
"options",
".",
"cache",
"to",
"false",
"."
] |
cc5735f98f62c8e9cfb98ae5b309abea1c8a2432
|
https://github.com/jonschlinkert/to-regex/blob/cc5735f98f62c8e9cfb98ae5b309abea1c8a2432/index.js#L126-L132
|
18,750
|
tj/react-enroute
|
example/index.js
|
Link
|
function Link({ to, children }) {
function click(e) {
e.preventDefault()
navigate(to)
}
return <a href={to} onClick={click}>
{children}
</a>
}
|
javascript
|
function Link({ to, children }) {
function click(e) {
e.preventDefault()
navigate(to)
}
return <a href={to} onClick={click}>
{children}
</a>
}
|
[
"function",
"Link",
"(",
"{",
"to",
",",
"children",
"}",
")",
"{",
"function",
"click",
"(",
"e",
")",
"{",
"e",
".",
"preventDefault",
"(",
")",
"navigate",
"(",
"to",
")",
"}",
"return",
"<",
"a",
"href",
"=",
"{",
"to",
"}",
"onClick",
"=",
"{",
"click",
"}",
">",
"\n ",
"{",
"children",
"}",
"\n ",
"<",
"/",
"a",
">",
"}"
] |
note this is just an example, this package does not provide a Link equivalent found in react-router, nor does it provide bindings for tools like Redux. You'll need to wire these up as desired.
|
[
"note",
"this",
"is",
"just",
"an",
"example",
"this",
"package",
"does",
"not",
"provide",
"a",
"Link",
"equivalent",
"found",
"in",
"react",
"-",
"router",
"nor",
"does",
"it",
"provide",
"bindings",
"for",
"tools",
"like",
"Redux",
".",
"You",
"ll",
"need",
"to",
"wire",
"these",
"up",
"as",
"desired",
"."
] |
9b3f99a01f13da69990553ac83e3e42932b7b59b
|
https://github.com/tj/react-enroute/blob/9b3f99a01f13da69990553ac83e3e42932b7b59b/example/index.js#L10-L19
|
18,751
|
rambler-digital-solutions/rambler-ui
|
src/utils/colors.js
|
clamp
|
function clamp(value, min, max) {
if (value < min) return min
if (value > max) return max
return value
}
|
javascript
|
function clamp(value, min, max) {
if (value < min) return min
if (value > max) return max
return value
}
|
[
"function",
"clamp",
"(",
"value",
",",
"min",
",",
"max",
")",
"{",
"if",
"(",
"value",
"<",
"min",
")",
"return",
"min",
"if",
"(",
"value",
">",
"max",
")",
"return",
"max",
"return",
"value",
"}"
] |
Returns a number whose value is limited to the given range.
@param {number} value The value to be clamped
@param {number} min The lower boundary of the output range
@param {number} max The upper boundary of the output range
@returns {number} A number in the range [min, max]
|
[
"Returns",
"a",
"number",
"whose",
"value",
"is",
"limited",
"to",
"the",
"given",
"range",
"."
] |
5c503a4e900efca11a1f318a329fa9d99cba0fb8
|
https://github.com/rambler-digital-solutions/rambler-ui/blob/5c503a4e900efca11a1f318a329fa9d99cba0fb8/src/utils/colors.js#L9-L13
|
18,752
|
rambler-digital-solutions/rambler-ui
|
src/utils/colors.js
|
convertHexToRGB
|
function convertHexToRGB(color) {
if (color.length === 4) {
let extendedColor = '#'
for (let i = 1; i < color.length; i++)
extendedColor += color.charAt(i) + color.charAt(i)
color = extendedColor
}
const values = {
r: parseInt(color.substr(1, 2), 16),
g: parseInt(color.substr(3, 2), 16),
b: parseInt(color.substr(5, 2), 16)
}
return `rgb(${values.r}, ${values.g}, ${values.b})`
}
|
javascript
|
function convertHexToRGB(color) {
if (color.length === 4) {
let extendedColor = '#'
for (let i = 1; i < color.length; i++)
extendedColor += color.charAt(i) + color.charAt(i)
color = extendedColor
}
const values = {
r: parseInt(color.substr(1, 2), 16),
g: parseInt(color.substr(3, 2), 16),
b: parseInt(color.substr(5, 2), 16)
}
return `rgb(${values.r}, ${values.g}, ${values.b})`
}
|
[
"function",
"convertHexToRGB",
"(",
"color",
")",
"{",
"if",
"(",
"color",
".",
"length",
"===",
"4",
")",
"{",
"let",
"extendedColor",
"=",
"'#'",
"for",
"(",
"let",
"i",
"=",
"1",
";",
"i",
"<",
"color",
".",
"length",
";",
"i",
"++",
")",
"extendedColor",
"+=",
"color",
".",
"charAt",
"(",
"i",
")",
"+",
"color",
".",
"charAt",
"(",
"i",
")",
"color",
"=",
"extendedColor",
"}",
"const",
"values",
"=",
"{",
"r",
":",
"parseInt",
"(",
"color",
".",
"substr",
"(",
"1",
",",
"2",
")",
",",
"16",
")",
",",
"g",
":",
"parseInt",
"(",
"color",
".",
"substr",
"(",
"3",
",",
"2",
")",
",",
"16",
")",
",",
"b",
":",
"parseInt",
"(",
"color",
".",
"substr",
"(",
"5",
",",
"2",
")",
",",
"16",
")",
"}",
"return",
"`",
"${",
"values",
".",
"r",
"}",
"${",
"values",
".",
"g",
"}",
"${",
"values",
".",
"b",
"}",
"`",
"}"
] |
Converts a color from CSS hex format to CSS rgb format.
@param {string} color - Hex color, i.e. #nnn or #nnnnnn
@returns {string} A CSS rgb color string
|
[
"Converts",
"a",
"color",
"from",
"CSS",
"hex",
"format",
"to",
"CSS",
"rgb",
"format",
"."
] |
5c503a4e900efca11a1f318a329fa9d99cba0fb8
|
https://github.com/rambler-digital-solutions/rambler-ui/blob/5c503a4e900efca11a1f318a329fa9d99cba0fb8/src/utils/colors.js#L21-L36
|
18,753
|
rambler-digital-solutions/rambler-ui
|
src/utils/colors.js
|
decomposeColor
|
function decomposeColor(color) {
if (color.charAt(0) === '#') return decomposeColor(convertHexToRGB(color))
color = color.replace(/\s/g, '')
const marker = color.indexOf('(')
if (marker === -1)
throw new Error(`Rambler UI: The ${color} color was not parsed correctly,
because it has an unsupported format (color name or RGB %). This may cause issues in component rendering.`)
const type = color.substring(0, marker)
let values = color.substring(marker + 1, color.length - 1).split(',')
values = values.map(value => parseFloat(value))
return {type, values}
}
|
javascript
|
function decomposeColor(color) {
if (color.charAt(0) === '#') return decomposeColor(convertHexToRGB(color))
color = color.replace(/\s/g, '')
const marker = color.indexOf('(')
if (marker === -1)
throw new Error(`Rambler UI: The ${color} color was not parsed correctly,
because it has an unsupported format (color name or RGB %). This may cause issues in component rendering.`)
const type = color.substring(0, marker)
let values = color.substring(marker + 1, color.length - 1).split(',')
values = values.map(value => parseFloat(value))
return {type, values}
}
|
[
"function",
"decomposeColor",
"(",
"color",
")",
"{",
"if",
"(",
"color",
".",
"charAt",
"(",
"0",
")",
"===",
"'#'",
")",
"return",
"decomposeColor",
"(",
"convertHexToRGB",
"(",
"color",
")",
")",
"color",
"=",
"color",
".",
"replace",
"(",
"/",
"\\s",
"/",
"g",
",",
"''",
")",
"const",
"marker",
"=",
"color",
".",
"indexOf",
"(",
"'('",
")",
"if",
"(",
"marker",
"===",
"-",
"1",
")",
"throw",
"new",
"Error",
"(",
"`",
"${",
"color",
"}",
"`",
")",
"const",
"type",
"=",
"color",
".",
"substring",
"(",
"0",
",",
"marker",
")",
"let",
"values",
"=",
"color",
".",
"substring",
"(",
"marker",
"+",
"1",
",",
"color",
".",
"length",
"-",
"1",
")",
".",
"split",
"(",
"','",
")",
"values",
"=",
"values",
".",
"map",
"(",
"value",
"=>",
"parseFloat",
"(",
"value",
")",
")",
"return",
"{",
"type",
",",
"values",
"}",
"}"
] |
Returns an object with the type and values of a color.
Note: Does not support rgb % values and color names.
@param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
@returns {{type: string, values: number[]}} A MUI color object
|
[
"Returns",
"an",
"object",
"with",
"the",
"type",
"and",
"values",
"of",
"a",
"color",
"."
] |
5c503a4e900efca11a1f318a329fa9d99cba0fb8
|
https://github.com/rambler-digital-solutions/rambler-ui/blob/5c503a4e900efca11a1f318a329fa9d99cba0fb8/src/utils/colors.js#L46-L60
|
18,754
|
rambler-digital-solutions/rambler-ui
|
src/utils/colors.js
|
getLuminance
|
function getLuminance(color) {
color = decomposeColor(color)
if (color.type.indexOf('rgb') > -1) {
const rgb = color.values.map(val => {
val /= 255 // normalized
return val <= 0.03928 ? val / 12.92 : Math.pow((val + 0.055) / 1.055, 2.4)
})
return Number(
(0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]).toFixed(3)
) // Truncate at 3 digits
} else if (color.type.indexOf('hsl') > -1) {
return color.values[2] / 100
}
}
|
javascript
|
function getLuminance(color) {
color = decomposeColor(color)
if (color.type.indexOf('rgb') > -1) {
const rgb = color.values.map(val => {
val /= 255 // normalized
return val <= 0.03928 ? val / 12.92 : Math.pow((val + 0.055) / 1.055, 2.4)
})
return Number(
(0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]).toFixed(3)
) // Truncate at 3 digits
} else if (color.type.indexOf('hsl') > -1) {
return color.values[2] / 100
}
}
|
[
"function",
"getLuminance",
"(",
"color",
")",
"{",
"color",
"=",
"decomposeColor",
"(",
"color",
")",
"if",
"(",
"color",
".",
"type",
".",
"indexOf",
"(",
"'rgb'",
")",
">",
"-",
"1",
")",
"{",
"const",
"rgb",
"=",
"color",
".",
"values",
".",
"map",
"(",
"val",
"=>",
"{",
"val",
"/=",
"255",
"// normalized",
"return",
"val",
"<=",
"0.03928",
"?",
"val",
"/",
"12.92",
":",
"Math",
".",
"pow",
"(",
"(",
"val",
"+",
"0.055",
")",
"/",
"1.055",
",",
"2.4",
")",
"}",
")",
"return",
"Number",
"(",
"(",
"0.2126",
"*",
"rgb",
"[",
"0",
"]",
"+",
"0.7152",
"*",
"rgb",
"[",
"1",
"]",
"+",
"0.0722",
"*",
"rgb",
"[",
"2",
"]",
")",
".",
"toFixed",
"(",
"3",
")",
")",
"// Truncate at 3 digits",
"}",
"else",
"if",
"(",
"color",
".",
"type",
".",
"indexOf",
"(",
"'hsl'",
")",
">",
"-",
"1",
")",
"{",
"return",
"color",
".",
"values",
"[",
"2",
"]",
"/",
"100",
"}",
"}"
] |
The relative brightness of any point in a color space,
normalized to 0 for darkest black and 1 for lightest white.
Formula: https://www.w3.org/WAI/GL/wiki/Relative_luminance
@param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
@returns {number} The relative brightness of the color in the range 0 - 1
|
[
"The",
"relative",
"brightness",
"of",
"any",
"point",
"in",
"a",
"color",
"space",
"normalized",
"to",
"0",
"for",
"darkest",
"black",
"and",
"1",
"for",
"lightest",
"white",
"."
] |
5c503a4e900efca11a1f318a329fa9d99cba0fb8
|
https://github.com/rambler-digital-solutions/rambler-ui/blob/5c503a4e900efca11a1f318a329fa9d99cba0fb8/src/utils/colors.js#L71-L85
|
18,755
|
rambler-digital-solutions/rambler-ui
|
src/utils/colors.js
|
convertColorToString
|
function convertColorToString(color) {
const {type, values} = color
// Only convert the first 3 values to int (i.e. not alpha)
if (type.indexOf('rgb') > -1)
for (let i = 0; i < 3; i++) values[i] = parseInt(values[i])
let colorString
if (type.indexOf('hsl') > -1)
colorString = `${color.type}(${values[0]}, ${values[1]}%, ${values[2]}%`
else colorString = `${color.type}(${values[0]}, ${values[1]}, ${values[2]}`
if (values.length === 4) colorString += `, ${color.values[3].toFixed(2)})`
else colorString += ')'
return colorString
}
|
javascript
|
function convertColorToString(color) {
const {type, values} = color
// Only convert the first 3 values to int (i.e. not alpha)
if (type.indexOf('rgb') > -1)
for (let i = 0; i < 3; i++) values[i] = parseInt(values[i])
let colorString
if (type.indexOf('hsl') > -1)
colorString = `${color.type}(${values[0]}, ${values[1]}%, ${values[2]}%`
else colorString = `${color.type}(${values[0]}, ${values[1]}, ${values[2]}`
if (values.length === 4) colorString += `, ${color.values[3].toFixed(2)})`
else colorString += ')'
return colorString
}
|
[
"function",
"convertColorToString",
"(",
"color",
")",
"{",
"const",
"{",
"type",
",",
"values",
"}",
"=",
"color",
"// Only convert the first 3 values to int (i.e. not alpha)",
"if",
"(",
"type",
".",
"indexOf",
"(",
"'rgb'",
")",
">",
"-",
"1",
")",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"3",
";",
"i",
"++",
")",
"values",
"[",
"i",
"]",
"=",
"parseInt",
"(",
"values",
"[",
"i",
"]",
")",
"let",
"colorString",
"if",
"(",
"type",
".",
"indexOf",
"(",
"'hsl'",
")",
">",
"-",
"1",
")",
"colorString",
"=",
"`",
"${",
"color",
".",
"type",
"}",
"${",
"values",
"[",
"0",
"]",
"}",
"${",
"values",
"[",
"1",
"]",
"}",
"${",
"values",
"[",
"2",
"]",
"}",
"`",
"else",
"colorString",
"=",
"`",
"${",
"color",
".",
"type",
"}",
"${",
"values",
"[",
"0",
"]",
"}",
"${",
"values",
"[",
"1",
"]",
"}",
"${",
"values",
"[",
"2",
"]",
"}",
"`",
"if",
"(",
"values",
".",
"length",
"===",
"4",
")",
"colorString",
"+=",
"`",
"${",
"color",
".",
"values",
"[",
"3",
"]",
".",
"toFixed",
"(",
"2",
")",
"}",
"`",
"else",
"colorString",
"+=",
"')'",
"return",
"colorString",
"}"
] |
Converts a color object with type and values to a string.
@param {object} color - Decomposed color
@param {string} color.type - One of, 'rgb', 'rgba', 'hsl', 'hsla'
@param {array} color.values - [n,n,n] or [n,n,n,n]
@returns {string} A CSS color string
|
[
"Converts",
"a",
"color",
"object",
"with",
"type",
"and",
"values",
"to",
"a",
"string",
"."
] |
5c503a4e900efca11a1f318a329fa9d99cba0fb8
|
https://github.com/rambler-digital-solutions/rambler-ui/blob/5c503a4e900efca11a1f318a329fa9d99cba0fb8/src/utils/colors.js#L95-L112
|
18,756
|
petrovich/petrovich-js
|
dist/petrovich.js
|
inflect
|
function inflect(gender, name, gcase, nametype) {
var nametype_rulesets = rules[nametype],
parts = name.split('-'),
result = [];
for (var i = 0; i < parts.length; i++) {
var part = parts[i], first_word = i === 0 && parts.size > 1,
rule = find_rule_global(gender, part,
nametype_rulesets, {first_word: first_word});
if (rule) result.push(apply_rule(part, gcase, rule));
else result.push(part);
}
return result.join('-');
}
|
javascript
|
function inflect(gender, name, gcase, nametype) {
var nametype_rulesets = rules[nametype],
parts = name.split('-'),
result = [];
for (var i = 0; i < parts.length; i++) {
var part = parts[i], first_word = i === 0 && parts.size > 1,
rule = find_rule_global(gender, part,
nametype_rulesets, {first_word: first_word});
if (rule) result.push(apply_rule(part, gcase, rule));
else result.push(part);
}
return result.join('-');
}
|
[
"function",
"inflect",
"(",
"gender",
",",
"name",
",",
"gcase",
",",
"nametype",
")",
"{",
"var",
"nametype_rulesets",
"=",
"rules",
"[",
"nametype",
"]",
",",
"parts",
"=",
"name",
".",
"split",
"(",
"'-'",
")",
",",
"result",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"parts",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"part",
"=",
"parts",
"[",
"i",
"]",
",",
"first_word",
"=",
"i",
"===",
"0",
"&&",
"parts",
".",
"size",
">",
"1",
",",
"rule",
"=",
"find_rule_global",
"(",
"gender",
",",
"part",
",",
"nametype_rulesets",
",",
"{",
"first_word",
":",
"first_word",
"}",
")",
";",
"if",
"(",
"rule",
")",
"result",
".",
"push",
"(",
"apply_rule",
"(",
"part",
",",
"gcase",
",",
"rule",
")",
")",
";",
"else",
"result",
".",
"push",
"(",
"part",
")",
";",
"}",
"return",
"result",
".",
"join",
"(",
"'-'",
")",
";",
"}"
] |
Key private method, used by all public methods
|
[
"Key",
"private",
"method",
"used",
"by",
"all",
"public",
"methods"
] |
809d5f7bb0e3af9ab2dcd8f0efa22b0bdd4f80ec
|
https://github.com/petrovich/petrovich-js/blob/809d5f7bb0e3af9ab2dcd8f0efa22b0bdd4f80ec/dist/petrovich.js#L91-L103
|
18,757
|
petrovich/petrovich-js
|
dist/petrovich.js
|
find_rule_global
|
function find_rule_global(gender, name, nametype_rulesets, features) {
if (!features) features = {};
var tags = [];
for (var key in features) {
if (features.hasOwnProperty(key)) tags.push(key);
}
if (nametype_rulesets.exceptions) {
var rule = find_rule_local(
gender, name, nametype_rulesets.exceptions, true, tags);
if (rule) return rule;
}
return find_rule_local(
gender, name, nametype_rulesets.suffixes, false, tags);
}
|
javascript
|
function find_rule_global(gender, name, nametype_rulesets, features) {
if (!features) features = {};
var tags = [];
for (var key in features) {
if (features.hasOwnProperty(key)) tags.push(key);
}
if (nametype_rulesets.exceptions) {
var rule = find_rule_local(
gender, name, nametype_rulesets.exceptions, true, tags);
if (rule) return rule;
}
return find_rule_local(
gender, name, nametype_rulesets.suffixes, false, tags);
}
|
[
"function",
"find_rule_global",
"(",
"gender",
",",
"name",
",",
"nametype_rulesets",
",",
"features",
")",
"{",
"if",
"(",
"!",
"features",
")",
"features",
"=",
"{",
"}",
";",
"var",
"tags",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"key",
"in",
"features",
")",
"{",
"if",
"(",
"features",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"tags",
".",
"push",
"(",
"key",
")",
";",
"}",
"if",
"(",
"nametype_rulesets",
".",
"exceptions",
")",
"{",
"var",
"rule",
"=",
"find_rule_local",
"(",
"gender",
",",
"name",
",",
"nametype_rulesets",
".",
"exceptions",
",",
"true",
",",
"tags",
")",
";",
"if",
"(",
"rule",
")",
"return",
"rule",
";",
"}",
"return",
"find_rule_local",
"(",
"gender",
",",
"name",
",",
"nametype_rulesets",
".",
"suffixes",
",",
"false",
",",
"tags",
")",
";",
"}"
] |
Find groups of rules in exceptions or suffixes of given nametype
|
[
"Find",
"groups",
"of",
"rules",
"in",
"exceptions",
"or",
"suffixes",
"of",
"given",
"nametype"
] |
809d5f7bb0e3af9ab2dcd8f0efa22b0bdd4f80ec
|
https://github.com/petrovich/petrovich-js/blob/809d5f7bb0e3af9ab2dcd8f0efa22b0bdd4f80ec/dist/petrovich.js#L107-L120
|
18,758
|
petrovich/petrovich-js
|
dist/petrovich.js
|
find_rule_local
|
function find_rule_local(gender, name, ruleset, match_whole_word, tags) {
for (var i = 0; i < ruleset.length; i++) {
var rule = ruleset[i];
if (rule.tags) {
var common_tags = [];
for (var j = 0; j < rule.tags.length; j++) {
var tag = rule.tags[j];
if (!contains(tags, tag)) common_tags.push(tag);
}
if (!common_tags.length) continue;
}
if (rule.gender !== 'androgynous' && gender !== rule.gender)
continue;
name = name.toLowerCase();
for (var j = 0; j < rule.test.length; j++) {
var sample = rule.test[j];
var test = match_whole_word ? name :
name.substr(name.length - sample.length);
if (test === sample) return rule;
}
}
return false;
}
|
javascript
|
function find_rule_local(gender, name, ruleset, match_whole_word, tags) {
for (var i = 0; i < ruleset.length; i++) {
var rule = ruleset[i];
if (rule.tags) {
var common_tags = [];
for (var j = 0; j < rule.tags.length; j++) {
var tag = rule.tags[j];
if (!contains(tags, tag)) common_tags.push(tag);
}
if (!common_tags.length) continue;
}
if (rule.gender !== 'androgynous' && gender !== rule.gender)
continue;
name = name.toLowerCase();
for (var j = 0; j < rule.test.length; j++) {
var sample = rule.test[j];
var test = match_whole_word ? name :
name.substr(name.length - sample.length);
if (test === sample) return rule;
}
}
return false;
}
|
[
"function",
"find_rule_local",
"(",
"gender",
",",
"name",
",",
"ruleset",
",",
"match_whole_word",
",",
"tags",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"ruleset",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"rule",
"=",
"ruleset",
"[",
"i",
"]",
";",
"if",
"(",
"rule",
".",
"tags",
")",
"{",
"var",
"common_tags",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"rule",
".",
"tags",
".",
"length",
";",
"j",
"++",
")",
"{",
"var",
"tag",
"=",
"rule",
".",
"tags",
"[",
"j",
"]",
";",
"if",
"(",
"!",
"contains",
"(",
"tags",
",",
"tag",
")",
")",
"common_tags",
".",
"push",
"(",
"tag",
")",
";",
"}",
"if",
"(",
"!",
"common_tags",
".",
"length",
")",
"continue",
";",
"}",
"if",
"(",
"rule",
".",
"gender",
"!==",
"'androgynous'",
"&&",
"gender",
"!==",
"rule",
".",
"gender",
")",
"continue",
";",
"name",
"=",
"name",
".",
"toLowerCase",
"(",
")",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"rule",
".",
"test",
".",
"length",
";",
"j",
"++",
")",
"{",
"var",
"sample",
"=",
"rule",
".",
"test",
"[",
"j",
"]",
";",
"var",
"test",
"=",
"match_whole_word",
"?",
"name",
":",
"name",
".",
"substr",
"(",
"name",
".",
"length",
"-",
"sample",
".",
"length",
")",
";",
"if",
"(",
"test",
"===",
"sample",
")",
"return",
"rule",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Local search in rulesets of exceptions or suffixes
|
[
"Local",
"search",
"in",
"rulesets",
"of",
"exceptions",
"or",
"suffixes"
] |
809d5f7bb0e3af9ab2dcd8f0efa22b0bdd4f80ec
|
https://github.com/petrovich/petrovich-js/blob/809d5f7bb0e3af9ab2dcd8f0efa22b0bdd4f80ec/dist/petrovich.js#L124-L147
|
18,759
|
petrovich/petrovich-js
|
dist/petrovich.js
|
apply_rule
|
function apply_rule(name, gcase, rule) {
var mod;
if (gcase === 'nominative') mod = '.';
else {
for (var i = 0; i < predef.cases.length; i++) {
if (gcase === predef.cases[i]) {
mod = rule.mods[i - 1];
break;
}
}
}
for (var i = 0; i < mod.length; i++) {
var chr = mod[i];
switch (chr) {
case '.':
break;
case '-':
name = name.substr(0, name.length - 1);
break;
default:
name += chr;
}
}
return name;
}
|
javascript
|
function apply_rule(name, gcase, rule) {
var mod;
if (gcase === 'nominative') mod = '.';
else {
for (var i = 0; i < predef.cases.length; i++) {
if (gcase === predef.cases[i]) {
mod = rule.mods[i - 1];
break;
}
}
}
for (var i = 0; i < mod.length; i++) {
var chr = mod[i];
switch (chr) {
case '.':
break;
case '-':
name = name.substr(0, name.length - 1);
break;
default:
name += chr;
}
}
return name;
}
|
[
"function",
"apply_rule",
"(",
"name",
",",
"gcase",
",",
"rule",
")",
"{",
"var",
"mod",
";",
"if",
"(",
"gcase",
"===",
"'nominative'",
")",
"mod",
"=",
"'.'",
";",
"else",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"predef",
".",
"cases",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"gcase",
"===",
"predef",
".",
"cases",
"[",
"i",
"]",
")",
"{",
"mod",
"=",
"rule",
".",
"mods",
"[",
"i",
"-",
"1",
"]",
";",
"break",
";",
"}",
"}",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"mod",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"chr",
"=",
"mod",
"[",
"i",
"]",
";",
"switch",
"(",
"chr",
")",
"{",
"case",
"'.'",
":",
"break",
";",
"case",
"'-'",
":",
"name",
"=",
"name",
".",
"substr",
"(",
"0",
",",
"name",
".",
"length",
"-",
"1",
")",
";",
"break",
";",
"default",
":",
"name",
"+=",
"chr",
";",
"}",
"}",
"return",
"name",
";",
"}"
] |
Apply found rule to given name Move error throwing from this function to API method
|
[
"Apply",
"found",
"rule",
"to",
"given",
"name",
"Move",
"error",
"throwing",
"from",
"this",
"function",
"to",
"API",
"method"
] |
809d5f7bb0e3af9ab2dcd8f0efa22b0bdd4f80ec
|
https://github.com/petrovich/petrovich-js/blob/809d5f7bb0e3af9ab2dcd8f0efa22b0bdd4f80ec/dist/petrovich.js#L152-L178
|
18,760
|
testdouble/teenytest
|
lib/run/results-store.js
|
function (metadata) {
var result = createResult(metadata)
var parentResult = current()
if (parentResult) {
parentResult.children.push(result)
}
currentNesting.push(result)
}
|
javascript
|
function (metadata) {
var result = createResult(metadata)
var parentResult = current()
if (parentResult) {
parentResult.children.push(result)
}
currentNesting.push(result)
}
|
[
"function",
"(",
"metadata",
")",
"{",
"var",
"result",
"=",
"createResult",
"(",
"metadata",
")",
"var",
"parentResult",
"=",
"current",
"(",
")",
"if",
"(",
"parentResult",
")",
"{",
"parentResult",
".",
"children",
".",
"push",
"(",
"result",
")",
"}",
"currentNesting",
".",
"push",
"(",
"result",
")",
"}"
] |
Mutate current context
|
[
"Mutate",
"current",
"context"
] |
51243f4f457fda21c55d81c347b675d0629de51d
|
https://github.com/testdouble/teenytest/blob/51243f4f457fda21c55d81c347b675d0629de51d/lib/run/results-store.js#L29-L36
|
|
18,761
|
tumblr/tumblr.js
|
lib/tumblr.js
|
createFunction
|
function createFunction(name, args, fn) {
if (isFunction(args)) {
fn = args;
args = [];
}
return new Function('body',
'return function ' + name + '(' + args.join(', ') + ') { return body.apply(this, arguments); };'
)(fn);
}
|
javascript
|
function createFunction(name, args, fn) {
if (isFunction(args)) {
fn = args;
args = [];
}
return new Function('body',
'return function ' + name + '(' + args.join(', ') + ') { return body.apply(this, arguments); };'
)(fn);
}
|
[
"function",
"createFunction",
"(",
"name",
",",
"args",
",",
"fn",
")",
"{",
"if",
"(",
"isFunction",
"(",
"args",
")",
")",
"{",
"fn",
"=",
"args",
";",
"args",
"=",
"[",
"]",
";",
"}",
"return",
"new",
"Function",
"(",
"'body'",
",",
"'return function '",
"+",
"name",
"+",
"'('",
"+",
"args",
".",
"join",
"(",
"', '",
")",
"+",
"') { return body.apply(this, arguments); };'",
")",
"(",
"fn",
")",
";",
"}"
] |
Creates a named function with the desired signature
@param {string} name - function name
@param {Array} [args] - array of argument names
@param {Function} fn - function that contains the logic that should run
@return {Function} a named function that takes the desired arguments
@private
|
[
"Creates",
"a",
"named",
"function",
"with",
"the",
"desired",
"signature"
] |
87301bbbc2f3f6e60c3270e0147454ac02f0acfb
|
https://github.com/tumblr/tumblr.js/blob/87301bbbc2f3f6e60c3270e0147454ac02f0acfb/lib/tumblr.js#L380-L389
|
18,762
|
tumblr/tumblr.js
|
lib/tumblr.js
|
promisifyRequest
|
function promisifyRequest(requestMethod) {
return function(apiPath, params, callback) {
const promise = new Promise(function(resolve, reject) {
requestMethod.call(this, apiPath, params, function(err, resp) {
if (err) {
reject(err);
} else {
resolve(resp);
}
});
}.bind(this));
if (callback) {
promise
.then(function(body) {
callback(null, body);
})
.catch(function(err) {
callback(err, null);
});
}
return promise;
};
}
|
javascript
|
function promisifyRequest(requestMethod) {
return function(apiPath, params, callback) {
const promise = new Promise(function(resolve, reject) {
requestMethod.call(this, apiPath, params, function(err, resp) {
if (err) {
reject(err);
} else {
resolve(resp);
}
});
}.bind(this));
if (callback) {
promise
.then(function(body) {
callback(null, body);
})
.catch(function(err) {
callback(err, null);
});
}
return promise;
};
}
|
[
"function",
"promisifyRequest",
"(",
"requestMethod",
")",
"{",
"return",
"function",
"(",
"apiPath",
",",
"params",
",",
"callback",
")",
"{",
"const",
"promise",
"=",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"requestMethod",
".",
"call",
"(",
"this",
",",
"apiPath",
",",
"params",
",",
"function",
"(",
"err",
",",
"resp",
")",
"{",
"if",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"}",
"else",
"{",
"resolve",
"(",
"resp",
")",
";",
"}",
"}",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"if",
"(",
"callback",
")",
"{",
"promise",
".",
"then",
"(",
"function",
"(",
"body",
")",
"{",
"callback",
"(",
"null",
",",
"body",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
",",
"null",
")",
";",
"}",
")",
";",
"}",
"return",
"promise",
";",
"}",
";",
"}"
] |
Take a callback-based function and returns a Promise instead
@param {Function} requestMethod - callback-based method to promisify
@return {Function} function that returns a Promise that resolves with the response body or
rejects with the error message
@private
|
[
"Take",
"a",
"callback",
"-",
"based",
"function",
"and",
"returns",
"a",
"Promise",
"instead"
] |
87301bbbc2f3f6e60c3270e0147454ac02f0acfb
|
https://github.com/tumblr/tumblr.js/blob/87301bbbc2f3f6e60c3270e0147454ac02f0acfb/lib/tumblr.js#L401-L425
|
18,763
|
tumblr/tumblr.js
|
lib/tumblr.js
|
getRequest
|
function getRequest(requestGet, credentials, baseUrl, apiPath, requestOptions, params, callback) {
params = params || {};
if (credentials.consumer_key) {
params.api_key = credentials.consumer_key;
}
return requestGet(extend({
url: baseUrl + apiPath + '?' + qs.stringify(params),
oauth: credentials,
json: true,
}, requestOptions), requestCallback(callback));
}
|
javascript
|
function getRequest(requestGet, credentials, baseUrl, apiPath, requestOptions, params, callback) {
params = params || {};
if (credentials.consumer_key) {
params.api_key = credentials.consumer_key;
}
return requestGet(extend({
url: baseUrl + apiPath + '?' + qs.stringify(params),
oauth: credentials,
json: true,
}, requestOptions), requestCallback(callback));
}
|
[
"function",
"getRequest",
"(",
"requestGet",
",",
"credentials",
",",
"baseUrl",
",",
"apiPath",
",",
"requestOptions",
",",
"params",
",",
"callback",
")",
"{",
"params",
"=",
"params",
"||",
"{",
"}",
";",
"if",
"(",
"credentials",
".",
"consumer_key",
")",
"{",
"params",
".",
"api_key",
"=",
"credentials",
".",
"consumer_key",
";",
"}",
"return",
"requestGet",
"(",
"extend",
"(",
"{",
"url",
":",
"baseUrl",
"+",
"apiPath",
"+",
"'?'",
"+",
"qs",
".",
"stringify",
"(",
"params",
")",
",",
"oauth",
":",
"credentials",
",",
"json",
":",
"true",
",",
"}",
",",
"requestOptions",
")",
",",
"requestCallback",
"(",
"callback",
")",
")",
";",
"}"
] |
Make a get request
@param {Function} requestGet - function that performs a get request
@param {Object} credentials - OAuth credentials
@param {string} baseUrl - base URL for the request
@param {string} apiPath - URL path for the request
@param {Object} requestOptions - additional request options
@param {Object} params - query parameters
@param {TumblrClient~callback} callback - request callback
@return {Request} Request object
@private
|
[
"Make",
"a",
"get",
"request"
] |
87301bbbc2f3f6e60c3270e0147454ac02f0acfb
|
https://github.com/tumblr/tumblr.js/blob/87301bbbc2f3f6e60c3270e0147454ac02f0acfb/lib/tumblr.js#L474-L486
|
18,764
|
tumblr/tumblr.js
|
lib/tumblr.js
|
postRequest
|
function postRequest(requestPost, credentials, baseUrl, apiPath, requestOptions, params, callback) {
params = params || {};
// Sign without multipart data
const currentRequest = requestPost(extend({
url: baseUrl + apiPath,
oauth: credentials,
}, requestOptions), function(err, response, body) {
try {
body = JSON.parse(body);
} catch (e) {
body = {
error: 'Malformed Response: ' + body,
};
}
requestCallback(callback)(err, response, body);
});
// Sign it with the non-data parameters
const dataKeys = ['data'];
currentRequest.form(omit(params, dataKeys));
currentRequest.oauth(credentials);
// Clear the side effects from form(param)
delete currentRequest.headers['content-type'];
delete currentRequest.body;
// if 'data' is an array, rename it with indices
if ('data' in params && Array.isArray(params.data)) {
for (let i = 0; i < params.data.length; ++i) {
params['data[' + i + ']'] = params.data[i];
}
delete params.data;
}
// And then add the full body
const form = currentRequest.form();
for (const key in params) {
form.append(key, params[key]);
}
// Add the form header back
extend(currentRequest.headers, form.getHeaders());
return currentRequest;
}
|
javascript
|
function postRequest(requestPost, credentials, baseUrl, apiPath, requestOptions, params, callback) {
params = params || {};
// Sign without multipart data
const currentRequest = requestPost(extend({
url: baseUrl + apiPath,
oauth: credentials,
}, requestOptions), function(err, response, body) {
try {
body = JSON.parse(body);
} catch (e) {
body = {
error: 'Malformed Response: ' + body,
};
}
requestCallback(callback)(err, response, body);
});
// Sign it with the non-data parameters
const dataKeys = ['data'];
currentRequest.form(omit(params, dataKeys));
currentRequest.oauth(credentials);
// Clear the side effects from form(param)
delete currentRequest.headers['content-type'];
delete currentRequest.body;
// if 'data' is an array, rename it with indices
if ('data' in params && Array.isArray(params.data)) {
for (let i = 0; i < params.data.length; ++i) {
params['data[' + i + ']'] = params.data[i];
}
delete params.data;
}
// And then add the full body
const form = currentRequest.form();
for (const key in params) {
form.append(key, params[key]);
}
// Add the form header back
extend(currentRequest.headers, form.getHeaders());
return currentRequest;
}
|
[
"function",
"postRequest",
"(",
"requestPost",
",",
"credentials",
",",
"baseUrl",
",",
"apiPath",
",",
"requestOptions",
",",
"params",
",",
"callback",
")",
"{",
"params",
"=",
"params",
"||",
"{",
"}",
";",
"// Sign without multipart data",
"const",
"currentRequest",
"=",
"requestPost",
"(",
"extend",
"(",
"{",
"url",
":",
"baseUrl",
"+",
"apiPath",
",",
"oauth",
":",
"credentials",
",",
"}",
",",
"requestOptions",
")",
",",
"function",
"(",
"err",
",",
"response",
",",
"body",
")",
"{",
"try",
"{",
"body",
"=",
"JSON",
".",
"parse",
"(",
"body",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"body",
"=",
"{",
"error",
":",
"'Malformed Response: '",
"+",
"body",
",",
"}",
";",
"}",
"requestCallback",
"(",
"callback",
")",
"(",
"err",
",",
"response",
",",
"body",
")",
";",
"}",
")",
";",
"// Sign it with the non-data parameters",
"const",
"dataKeys",
"=",
"[",
"'data'",
"]",
";",
"currentRequest",
".",
"form",
"(",
"omit",
"(",
"params",
",",
"dataKeys",
")",
")",
";",
"currentRequest",
".",
"oauth",
"(",
"credentials",
")",
";",
"// Clear the side effects from form(param)",
"delete",
"currentRequest",
".",
"headers",
"[",
"'content-type'",
"]",
";",
"delete",
"currentRequest",
".",
"body",
";",
"// if 'data' is an array, rename it with indices",
"if",
"(",
"'data'",
"in",
"params",
"&&",
"Array",
".",
"isArray",
"(",
"params",
".",
"data",
")",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"params",
".",
"data",
".",
"length",
";",
"++",
"i",
")",
"{",
"params",
"[",
"'data['",
"+",
"i",
"+",
"']'",
"]",
"=",
"params",
".",
"data",
"[",
"i",
"]",
";",
"}",
"delete",
"params",
".",
"data",
";",
"}",
"// And then add the full body",
"const",
"form",
"=",
"currentRequest",
".",
"form",
"(",
")",
";",
"for",
"(",
"const",
"key",
"in",
"params",
")",
"{",
"form",
".",
"append",
"(",
"key",
",",
"params",
"[",
"key",
"]",
")",
";",
"}",
"// Add the form header back",
"extend",
"(",
"currentRequest",
".",
"headers",
",",
"form",
".",
"getHeaders",
"(",
")",
")",
";",
"return",
"currentRequest",
";",
"}"
] |
Create a function to make POST requests to the Tumblr API
@param {Function} requestPost - function that performs a get request
@param {Object} credentials - OAuth credentials
@param {string} baseUrl - base URL for the request
@param {string} apiPath - URL path for the request
@param {Object} requestOptions - additional request options
@param {Object} params - form data
@param {TumblrClient~callback} callback - request callback
@return {Request} Request object
@private
|
[
"Create",
"a",
"function",
"to",
"make",
"POST",
"requests",
"to",
"the",
"Tumblr",
"API"
] |
87301bbbc2f3f6e60c3270e0147454ac02f0acfb
|
https://github.com/tumblr/tumblr.js/blob/87301bbbc2f3f6e60c3270e0147454ac02f0acfb/lib/tumblr.js#L503-L548
|
18,765
|
tumblr/tumblr.js
|
lib/tumblr.js
|
addMethod
|
function addMethod(client, methodName, apiPath, paramNames, requestType) {
const apiPathSplit = apiPath.split('/');
const apiPathParamsCount = apiPath.split(/\/:[^\/]+/).length - 1;
const buildApiPath = function(args) {
let pathParamIndex = 0;
return reduce(apiPathSplit, function(apiPath, apiPathChunk, i) {
// Parse arguments in the path
if (apiPathChunk === ':blogIdentifier') {
// Blog URLs are special
apiPathChunk = forceFullBlogUrl(args[pathParamIndex++]);
} else if (apiPathChunk[0] === ':') {
apiPathChunk = args[pathParamIndex++];
}
if (apiPathChunk) {
return apiPath + '/' + apiPathChunk;
} else {
return apiPath;
}
}, '');
};
const namedParams = (apiPath.match(/\/:[^\/]+/g) || []).map(function(param) {
return param.substr(2);
}).concat(paramNames, 'params', 'callback');
const methodBody = function() {
const argsLength = arguments.length;
const args = new Array(argsLength);
for (let i = 0; i < argsLength; i++) {
args[i] = arguments[i];
}
const requiredParamsStart = apiPathParamsCount;
const requiredParamsEnd = requiredParamsStart + paramNames.length;
const requiredParamArgs = args.slice(requiredParamsStart, requiredParamsEnd);
// Callback is at the end
const callback = isFunction(args[args.length - 1]) ? args.pop() : null;
// Required Parmas
const params = zipObject(paramNames, requiredParamArgs);
extend(params, isPlainObject(args[args.length - 1]) ? args.pop() : {});
// Path arguments are determined after required parameters
const apiPathArgs = args.slice(0, apiPathParamsCount);
let request = requestType;
if (isString(requestType)) {
request = requestType.toUpperCase() === 'POST' ? client.postRequest : client.getRequest;
} else if (!isFunction(requestType)) {
request = client.getRequest;
}
return request.call(client, buildApiPath(apiPathArgs), params, callback);
};
set(client, methodName, createFunction(methodName, namedParams, methodBody));
}
|
javascript
|
function addMethod(client, methodName, apiPath, paramNames, requestType) {
const apiPathSplit = apiPath.split('/');
const apiPathParamsCount = apiPath.split(/\/:[^\/]+/).length - 1;
const buildApiPath = function(args) {
let pathParamIndex = 0;
return reduce(apiPathSplit, function(apiPath, apiPathChunk, i) {
// Parse arguments in the path
if (apiPathChunk === ':blogIdentifier') {
// Blog URLs are special
apiPathChunk = forceFullBlogUrl(args[pathParamIndex++]);
} else if (apiPathChunk[0] === ':') {
apiPathChunk = args[pathParamIndex++];
}
if (apiPathChunk) {
return apiPath + '/' + apiPathChunk;
} else {
return apiPath;
}
}, '');
};
const namedParams = (apiPath.match(/\/:[^\/]+/g) || []).map(function(param) {
return param.substr(2);
}).concat(paramNames, 'params', 'callback');
const methodBody = function() {
const argsLength = arguments.length;
const args = new Array(argsLength);
for (let i = 0; i < argsLength; i++) {
args[i] = arguments[i];
}
const requiredParamsStart = apiPathParamsCount;
const requiredParamsEnd = requiredParamsStart + paramNames.length;
const requiredParamArgs = args.slice(requiredParamsStart, requiredParamsEnd);
// Callback is at the end
const callback = isFunction(args[args.length - 1]) ? args.pop() : null;
// Required Parmas
const params = zipObject(paramNames, requiredParamArgs);
extend(params, isPlainObject(args[args.length - 1]) ? args.pop() : {});
// Path arguments are determined after required parameters
const apiPathArgs = args.slice(0, apiPathParamsCount);
let request = requestType;
if (isString(requestType)) {
request = requestType.toUpperCase() === 'POST' ? client.postRequest : client.getRequest;
} else if (!isFunction(requestType)) {
request = client.getRequest;
}
return request.call(client, buildApiPath(apiPathArgs), params, callback);
};
set(client, methodName, createFunction(methodName, namedParams, methodBody));
}
|
[
"function",
"addMethod",
"(",
"client",
",",
"methodName",
",",
"apiPath",
",",
"paramNames",
",",
"requestType",
")",
"{",
"const",
"apiPathSplit",
"=",
"apiPath",
".",
"split",
"(",
"'/'",
")",
";",
"const",
"apiPathParamsCount",
"=",
"apiPath",
".",
"split",
"(",
"/",
"\\/:[^\\/]+",
"/",
")",
".",
"length",
"-",
"1",
";",
"const",
"buildApiPath",
"=",
"function",
"(",
"args",
")",
"{",
"let",
"pathParamIndex",
"=",
"0",
";",
"return",
"reduce",
"(",
"apiPathSplit",
",",
"function",
"(",
"apiPath",
",",
"apiPathChunk",
",",
"i",
")",
"{",
"// Parse arguments in the path",
"if",
"(",
"apiPathChunk",
"===",
"':blogIdentifier'",
")",
"{",
"// Blog URLs are special",
"apiPathChunk",
"=",
"forceFullBlogUrl",
"(",
"args",
"[",
"pathParamIndex",
"++",
"]",
")",
";",
"}",
"else",
"if",
"(",
"apiPathChunk",
"[",
"0",
"]",
"===",
"':'",
")",
"{",
"apiPathChunk",
"=",
"args",
"[",
"pathParamIndex",
"++",
"]",
";",
"}",
"if",
"(",
"apiPathChunk",
")",
"{",
"return",
"apiPath",
"+",
"'/'",
"+",
"apiPathChunk",
";",
"}",
"else",
"{",
"return",
"apiPath",
";",
"}",
"}",
",",
"''",
")",
";",
"}",
";",
"const",
"namedParams",
"=",
"(",
"apiPath",
".",
"match",
"(",
"/",
"\\/:[^\\/]+",
"/",
"g",
")",
"||",
"[",
"]",
")",
".",
"map",
"(",
"function",
"(",
"param",
")",
"{",
"return",
"param",
".",
"substr",
"(",
"2",
")",
";",
"}",
")",
".",
"concat",
"(",
"paramNames",
",",
"'params'",
",",
"'callback'",
")",
";",
"const",
"methodBody",
"=",
"function",
"(",
")",
"{",
"const",
"argsLength",
"=",
"arguments",
".",
"length",
";",
"const",
"args",
"=",
"new",
"Array",
"(",
"argsLength",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"argsLength",
";",
"i",
"++",
")",
"{",
"args",
"[",
"i",
"]",
"=",
"arguments",
"[",
"i",
"]",
";",
"}",
"const",
"requiredParamsStart",
"=",
"apiPathParamsCount",
";",
"const",
"requiredParamsEnd",
"=",
"requiredParamsStart",
"+",
"paramNames",
".",
"length",
";",
"const",
"requiredParamArgs",
"=",
"args",
".",
"slice",
"(",
"requiredParamsStart",
",",
"requiredParamsEnd",
")",
";",
"// Callback is at the end",
"const",
"callback",
"=",
"isFunction",
"(",
"args",
"[",
"args",
".",
"length",
"-",
"1",
"]",
")",
"?",
"args",
".",
"pop",
"(",
")",
":",
"null",
";",
"// Required Parmas",
"const",
"params",
"=",
"zipObject",
"(",
"paramNames",
",",
"requiredParamArgs",
")",
";",
"extend",
"(",
"params",
",",
"isPlainObject",
"(",
"args",
"[",
"args",
".",
"length",
"-",
"1",
"]",
")",
"?",
"args",
".",
"pop",
"(",
")",
":",
"{",
"}",
")",
";",
"// Path arguments are determined after required parameters",
"const",
"apiPathArgs",
"=",
"args",
".",
"slice",
"(",
"0",
",",
"apiPathParamsCount",
")",
";",
"let",
"request",
"=",
"requestType",
";",
"if",
"(",
"isString",
"(",
"requestType",
")",
")",
"{",
"request",
"=",
"requestType",
".",
"toUpperCase",
"(",
")",
"===",
"'POST'",
"?",
"client",
".",
"postRequest",
":",
"client",
".",
"getRequest",
";",
"}",
"else",
"if",
"(",
"!",
"isFunction",
"(",
"requestType",
")",
")",
"{",
"request",
"=",
"client",
".",
"getRequest",
";",
"}",
"return",
"request",
".",
"call",
"(",
"client",
",",
"buildApiPath",
"(",
"apiPathArgs",
")",
",",
"params",
",",
"callback",
")",
";",
"}",
";",
"set",
"(",
"client",
",",
"methodName",
",",
"createFunction",
"(",
"methodName",
",",
"namedParams",
",",
"methodBody",
")",
")",
";",
"}"
] |
Adds a request method to the client
@param {Object} client - add the method to this object
@param {string} methodName - the name of the method
@param {string} apiPath - the API route, which uses any colon-prefixed segments as arguments
@param {Array} paramNames - ordered list of required request parameters used as arguments
@param {String|Function} requestType - the request type or a function that makes the request
@private
|
[
"Adds",
"a",
"request",
"method",
"to",
"the",
"client"
] |
87301bbbc2f3f6e60c3270e0147454ac02f0acfb
|
https://github.com/tumblr/tumblr.js/blob/87301bbbc2f3f6e60c3270e0147454ac02f0acfb/lib/tumblr.js#L561-L620
|
18,766
|
tumblr/tumblr.js
|
lib/tumblr.js
|
addMethods
|
function addMethods(client, methods, requestType) {
let apiPath, paramNames;
for (const methodName in methods) {
apiPath = methods[methodName];
if (isString(apiPath)) {
paramNames = [];
} else if (isPlainObject(apiPath)) {
paramNames = apiPath.paramNames || [];
apiPath = apiPath.path;
} else {
paramNames = apiPath[1] || [];
apiPath = apiPath[0];
}
addMethod(client, methodName, apiPath, paramNames, requestType || 'GET');
}
}
|
javascript
|
function addMethods(client, methods, requestType) {
let apiPath, paramNames;
for (const methodName in methods) {
apiPath = methods[methodName];
if (isString(apiPath)) {
paramNames = [];
} else if (isPlainObject(apiPath)) {
paramNames = apiPath.paramNames || [];
apiPath = apiPath.path;
} else {
paramNames = apiPath[1] || [];
apiPath = apiPath[0];
}
addMethod(client, methodName, apiPath, paramNames, requestType || 'GET');
}
}
|
[
"function",
"addMethods",
"(",
"client",
",",
"methods",
",",
"requestType",
")",
"{",
"let",
"apiPath",
",",
"paramNames",
";",
"for",
"(",
"const",
"methodName",
"in",
"methods",
")",
"{",
"apiPath",
"=",
"methods",
"[",
"methodName",
"]",
";",
"if",
"(",
"isString",
"(",
"apiPath",
")",
")",
"{",
"paramNames",
"=",
"[",
"]",
";",
"}",
"else",
"if",
"(",
"isPlainObject",
"(",
"apiPath",
")",
")",
"{",
"paramNames",
"=",
"apiPath",
".",
"paramNames",
"||",
"[",
"]",
";",
"apiPath",
"=",
"apiPath",
".",
"path",
";",
"}",
"else",
"{",
"paramNames",
"=",
"apiPath",
"[",
"1",
"]",
"||",
"[",
"]",
";",
"apiPath",
"=",
"apiPath",
"[",
"0",
"]",
";",
"}",
"addMethod",
"(",
"client",
",",
"methodName",
",",
"apiPath",
",",
"paramNames",
",",
"requestType",
"||",
"'GET'",
")",
";",
"}",
"}"
] |
Adds methods to the client
@param {TumblrClient} client - an instance of the `tumblr.js` API client
@param {Object} methods - mapping of method names to endpoints. Endpoints can be a string or an
array of format `[apiPathString, requireParamsArray]`
@param {String|Function} requestType - the request type or a function that makes the request
@private
|
[
"Adds",
"methods",
"to",
"the",
"client"
] |
87301bbbc2f3f6e60c3270e0147454ac02f0acfb
|
https://github.com/tumblr/tumblr.js/blob/87301bbbc2f3f6e60c3270e0147454ac02f0acfb/lib/tumblr.js#L632-L647
|
18,767
|
tumblr/tumblr.js
|
lib/tumblr.js
|
wrapCreatePost
|
function wrapCreatePost(type, validate) {
return function(blogIdentifier, params, callback) {
params = extend({type: type}, params);
if (isArray(validate)) {
validate = partial(function(params, requireKeys) {
if (requireKeys.length) {
const keyIntersection = intersection(keys(params), requireKeys);
if (requireKeys.length === 1 && !keyIntersection.length) {
throw new Error('Missing required field: ' + requireKeys[0]);
} else if (!keyIntersection.length) {
throw new Error('Missing one of: ' + requireKeys.join(', '));
} else if (keyIntersection.length > 1) {
throw new Error('Can only use one of: ' + requireKeys.join(', '));
}
}
return true;
}, params, validate);
}
if (isFunction(validate)) {
if (!validate(params)) {
throw new Error('Error validating parameters');
}
}
if (arguments.length > 2) {
return this.createPost(blogIdentifier, params, callback);
} else {
return this.createPost(blogIdentifier, params);
}
};
}
|
javascript
|
function wrapCreatePost(type, validate) {
return function(blogIdentifier, params, callback) {
params = extend({type: type}, params);
if (isArray(validate)) {
validate = partial(function(params, requireKeys) {
if (requireKeys.length) {
const keyIntersection = intersection(keys(params), requireKeys);
if (requireKeys.length === 1 && !keyIntersection.length) {
throw new Error('Missing required field: ' + requireKeys[0]);
} else if (!keyIntersection.length) {
throw new Error('Missing one of: ' + requireKeys.join(', '));
} else if (keyIntersection.length > 1) {
throw new Error('Can only use one of: ' + requireKeys.join(', '));
}
}
return true;
}, params, validate);
}
if (isFunction(validate)) {
if (!validate(params)) {
throw new Error('Error validating parameters');
}
}
if (arguments.length > 2) {
return this.createPost(blogIdentifier, params, callback);
} else {
return this.createPost(blogIdentifier, params);
}
};
}
|
[
"function",
"wrapCreatePost",
"(",
"type",
",",
"validate",
")",
"{",
"return",
"function",
"(",
"blogIdentifier",
",",
"params",
",",
"callback",
")",
"{",
"params",
"=",
"extend",
"(",
"{",
"type",
":",
"type",
"}",
",",
"params",
")",
";",
"if",
"(",
"isArray",
"(",
"validate",
")",
")",
"{",
"validate",
"=",
"partial",
"(",
"function",
"(",
"params",
",",
"requireKeys",
")",
"{",
"if",
"(",
"requireKeys",
".",
"length",
")",
"{",
"const",
"keyIntersection",
"=",
"intersection",
"(",
"keys",
"(",
"params",
")",
",",
"requireKeys",
")",
";",
"if",
"(",
"requireKeys",
".",
"length",
"===",
"1",
"&&",
"!",
"keyIntersection",
".",
"length",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing required field: '",
"+",
"requireKeys",
"[",
"0",
"]",
")",
";",
"}",
"else",
"if",
"(",
"!",
"keyIntersection",
".",
"length",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing one of: '",
"+",
"requireKeys",
".",
"join",
"(",
"', '",
")",
")",
";",
"}",
"else",
"if",
"(",
"keyIntersection",
".",
"length",
">",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Can only use one of: '",
"+",
"requireKeys",
".",
"join",
"(",
"', '",
")",
")",
";",
"}",
"}",
"return",
"true",
";",
"}",
",",
"params",
",",
"validate",
")",
";",
"}",
"if",
"(",
"isFunction",
"(",
"validate",
")",
")",
"{",
"if",
"(",
"!",
"validate",
"(",
"params",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Error validating parameters'",
")",
";",
"}",
"}",
"if",
"(",
"arguments",
".",
"length",
">",
"2",
")",
"{",
"return",
"this",
".",
"createPost",
"(",
"blogIdentifier",
",",
"params",
",",
"callback",
")",
";",
"}",
"else",
"{",
"return",
"this",
".",
"createPost",
"(",
"blogIdentifier",
",",
"params",
")",
";",
"}",
"}",
";",
"}"
] |
Wraps createPost to specify `type` and validate the parameters
@param {string} type - post type
@param {Function} [validate] - returns `true` if the parameters validate
@return {Function} wrapped function
@private
|
[
"Wraps",
"createPost",
"to",
"specify",
"type",
"and",
"validate",
"the",
"parameters"
] |
87301bbbc2f3f6e60c3270e0147454ac02f0acfb
|
https://github.com/tumblr/tumblr.js/blob/87301bbbc2f3f6e60c3270e0147454ac02f0acfb/lib/tumblr.js#L659-L691
|
18,768
|
tumblr/tumblr.js
|
lib/tumblr.js
|
TumblrClient
|
function TumblrClient(options) {
// Support for `TumblrClient(credentials, baseUrl, requestLibrary)`
if (arguments.length > 1) {
options = {
credentials: arguments[0],
baseUrl: arguments[1],
request: arguments[2],
returnPromises: false,
};
}
options = options || {};
this.version = CLIENT_VERSION;
this.credentials = get(options, 'credentials', omit(options, 'baseUrl', 'request'));
this.baseUrl = get(options, 'baseUrl', API_BASE_URL);
this.request = get(options, 'request', request);
this.requestOptions = {
followRedirect: false,
headers: {
'User-Agent': 'tumblr.js/' + CLIENT_VERSION,
},
};
this.addGetMethods(API_METHODS.GET);
this.addPostMethods(API_METHODS.POST);
/**
* Creates a text post on the given blog
*
* @see {@link https://www.tumblr.com/docs/api/v2#ptext-posts|API docs}
*
* @method createTextPost
*
* @param {string} blogIdentifier - blog name or URL
* @param {Object} params - parameters sent with the request
* @param {string} [params.title] - post title text
* @param {string} params.body - post body text
* @param {TumblrClient~callback} [callback] - invoked when the request completes
*
* @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used
*
* @memberof TumblrClient
*/
this.createTextPost = wrapCreatePost('text', ['body']);
/**
* Creates a photo post on the given blog
*
* @see {@link https://www.tumblr.com/docs/api/v2#pphoto-posts|API docs}
*
* @method createPhotoPost
*
* @param {string} blogIdentifier - blog name or URL
* @param {Object} params - parameters sent with the request
* @param {string} params.source - image source URL
* @param {Stream|Array} params.data - an image or array of images
* @param {string} params.data64 - base64-encoded image data
* @param {string} [params.caption] - post caption text
* @param {TumblrClient~callback} [callback] - invoked when the request completes
*
* @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used
*
* @memberof TumblrClient
*/
this.createPhotoPost = wrapCreatePost('photo', ['data', 'data64', 'source']);
/**
* Creates a quote post on the given blog
*
* @see {@link https://www.tumblr.com/docs/api/v2#pquote-posts|API docs}
*
* @method createQuotePost
*
* @param {string} blogIdentifier - blog name or URL
* @param {Object} params - parameters sent with the request
* @param {string} params.quote - quote text
* @param {string} [params.source] - quote source
* @param {TumblrClient~callback} [callback] - invoked when the request completes
*
* @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used
*
* @memberof TumblrClient
*/
this.createQuotePost = wrapCreatePost('quote', ['quote']);
/**
* Creates a link post on the given blog
*
* @see {@link https://www.tumblr.com/docs/api/v2#plink-posts|API docs}
*
* @method createLinkPost
*
* @param {string} blogIdentifier - blog name or URL
* @param {Object} params - parameters sent with the request
* @param {string} [params.title] - post title text
* @param {string} params.url - the link URL
* @param {string} [params.thumbnail] - the URL of an image to use as the thumbnail
* @param {string} [params.excerpt] - an excerpt from the page the link points to
* @param {string} [params.author] - the name of the author of the page the link points to
* @param {string} [params.description] - post caption text
* @param {TumblrClient~callback} [callback] - invoked when the request completes
*
* @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used
*
* @memberof TumblrClient
*/
this.createLinkPost = wrapCreatePost('link', ['url']);
/**
* Creates a chat post on the given blog
*
* @see {@link https://www.tumblr.com/docs/api/v2#pchat-posts|API docs}
*
* @method createChatPost
*
* @param {string} blogIdentifier - blog name or URL
* @param {Object} params - parameters sent with the request
* @param {string} [params.title] - post title text
* @param {string} params.conversation - chat text
* @param {TumblrClient~callback} [callback] - invoked when the request completes
*
* @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used
*
* @memberof TumblrClient
*/
this.createChatPost = wrapCreatePost('chat', ['conversation']);
/**
* Creates an audio post on the given blog
*
* @see {@link https://www.tumblr.com/docs/api/v2#paudio-posts|API docs}
*
* @method createAudioPost
*
* @param {string} blogIdentifier - blog name or URL
* @param {Object} params - parameters sent with the request
* @param {string} params.external_url - image source URL
* @param {Stream} params.data - an audio file
* @param {string} [params.caption] - post caption text
* @param {TumblrClient~callback} [callback] - invoked when the request completes
*
* @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used
*
* @memberof TumblrClient
*/
this.createAudioPost = wrapCreatePost('audio', ['data', 'data64', 'external_url']);
/**
* Creates a video post on the given blog
*
* @see {@link https://www.tumblr.com/docs/api/v2#pvideo-posts|API docs}
*
* @method createVideoPost
*
* @param {string} blogIdentifier - blog name or URL
* @param {Object} params - parameters sent with the request
* @param {string} params.embed - embed code or a video URL
* @param {Stream} params.data - a video file
* @param {string} [params.caption] - post caption text
* @param {TumblrClient~callback} [callback] - invoked when the request completes
*
* @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used
*
* @memberof TumblrClient
*/
this.createVideoPost = wrapCreatePost('video', ['data', 'data64', 'embed']);
// Enable Promise mode
if (get(options, 'returnPromises', false)) {
this.returnPromises();
}
}
|
javascript
|
function TumblrClient(options) {
// Support for `TumblrClient(credentials, baseUrl, requestLibrary)`
if (arguments.length > 1) {
options = {
credentials: arguments[0],
baseUrl: arguments[1],
request: arguments[2],
returnPromises: false,
};
}
options = options || {};
this.version = CLIENT_VERSION;
this.credentials = get(options, 'credentials', omit(options, 'baseUrl', 'request'));
this.baseUrl = get(options, 'baseUrl', API_BASE_URL);
this.request = get(options, 'request', request);
this.requestOptions = {
followRedirect: false,
headers: {
'User-Agent': 'tumblr.js/' + CLIENT_VERSION,
},
};
this.addGetMethods(API_METHODS.GET);
this.addPostMethods(API_METHODS.POST);
/**
* Creates a text post on the given blog
*
* @see {@link https://www.tumblr.com/docs/api/v2#ptext-posts|API docs}
*
* @method createTextPost
*
* @param {string} blogIdentifier - blog name or URL
* @param {Object} params - parameters sent with the request
* @param {string} [params.title] - post title text
* @param {string} params.body - post body text
* @param {TumblrClient~callback} [callback] - invoked when the request completes
*
* @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used
*
* @memberof TumblrClient
*/
this.createTextPost = wrapCreatePost('text', ['body']);
/**
* Creates a photo post on the given blog
*
* @see {@link https://www.tumblr.com/docs/api/v2#pphoto-posts|API docs}
*
* @method createPhotoPost
*
* @param {string} blogIdentifier - blog name or URL
* @param {Object} params - parameters sent with the request
* @param {string} params.source - image source URL
* @param {Stream|Array} params.data - an image or array of images
* @param {string} params.data64 - base64-encoded image data
* @param {string} [params.caption] - post caption text
* @param {TumblrClient~callback} [callback] - invoked when the request completes
*
* @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used
*
* @memberof TumblrClient
*/
this.createPhotoPost = wrapCreatePost('photo', ['data', 'data64', 'source']);
/**
* Creates a quote post on the given blog
*
* @see {@link https://www.tumblr.com/docs/api/v2#pquote-posts|API docs}
*
* @method createQuotePost
*
* @param {string} blogIdentifier - blog name or URL
* @param {Object} params - parameters sent with the request
* @param {string} params.quote - quote text
* @param {string} [params.source] - quote source
* @param {TumblrClient~callback} [callback] - invoked when the request completes
*
* @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used
*
* @memberof TumblrClient
*/
this.createQuotePost = wrapCreatePost('quote', ['quote']);
/**
* Creates a link post on the given blog
*
* @see {@link https://www.tumblr.com/docs/api/v2#plink-posts|API docs}
*
* @method createLinkPost
*
* @param {string} blogIdentifier - blog name or URL
* @param {Object} params - parameters sent with the request
* @param {string} [params.title] - post title text
* @param {string} params.url - the link URL
* @param {string} [params.thumbnail] - the URL of an image to use as the thumbnail
* @param {string} [params.excerpt] - an excerpt from the page the link points to
* @param {string} [params.author] - the name of the author of the page the link points to
* @param {string} [params.description] - post caption text
* @param {TumblrClient~callback} [callback] - invoked when the request completes
*
* @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used
*
* @memberof TumblrClient
*/
this.createLinkPost = wrapCreatePost('link', ['url']);
/**
* Creates a chat post on the given blog
*
* @see {@link https://www.tumblr.com/docs/api/v2#pchat-posts|API docs}
*
* @method createChatPost
*
* @param {string} blogIdentifier - blog name or URL
* @param {Object} params - parameters sent with the request
* @param {string} [params.title] - post title text
* @param {string} params.conversation - chat text
* @param {TumblrClient~callback} [callback] - invoked when the request completes
*
* @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used
*
* @memberof TumblrClient
*/
this.createChatPost = wrapCreatePost('chat', ['conversation']);
/**
* Creates an audio post on the given blog
*
* @see {@link https://www.tumblr.com/docs/api/v2#paudio-posts|API docs}
*
* @method createAudioPost
*
* @param {string} blogIdentifier - blog name or URL
* @param {Object} params - parameters sent with the request
* @param {string} params.external_url - image source URL
* @param {Stream} params.data - an audio file
* @param {string} [params.caption] - post caption text
* @param {TumblrClient~callback} [callback] - invoked when the request completes
*
* @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used
*
* @memberof TumblrClient
*/
this.createAudioPost = wrapCreatePost('audio', ['data', 'data64', 'external_url']);
/**
* Creates a video post on the given blog
*
* @see {@link https://www.tumblr.com/docs/api/v2#pvideo-posts|API docs}
*
* @method createVideoPost
*
* @param {string} blogIdentifier - blog name or URL
* @param {Object} params - parameters sent with the request
* @param {string} params.embed - embed code or a video URL
* @param {Stream} params.data - a video file
* @param {string} [params.caption] - post caption text
* @param {TumblrClient~callback} [callback] - invoked when the request completes
*
* @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used
*
* @memberof TumblrClient
*/
this.createVideoPost = wrapCreatePost('video', ['data', 'data64', 'embed']);
// Enable Promise mode
if (get(options, 'returnPromises', false)) {
this.returnPromises();
}
}
|
[
"function",
"TumblrClient",
"(",
"options",
")",
"{",
"// Support for `TumblrClient(credentials, baseUrl, requestLibrary)`",
"if",
"(",
"arguments",
".",
"length",
">",
"1",
")",
"{",
"options",
"=",
"{",
"credentials",
":",
"arguments",
"[",
"0",
"]",
",",
"baseUrl",
":",
"arguments",
"[",
"1",
"]",
",",
"request",
":",
"arguments",
"[",
"2",
"]",
",",
"returnPromises",
":",
"false",
",",
"}",
";",
"}",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"this",
".",
"version",
"=",
"CLIENT_VERSION",
";",
"this",
".",
"credentials",
"=",
"get",
"(",
"options",
",",
"'credentials'",
",",
"omit",
"(",
"options",
",",
"'baseUrl'",
",",
"'request'",
")",
")",
";",
"this",
".",
"baseUrl",
"=",
"get",
"(",
"options",
",",
"'baseUrl'",
",",
"API_BASE_URL",
")",
";",
"this",
".",
"request",
"=",
"get",
"(",
"options",
",",
"'request'",
",",
"request",
")",
";",
"this",
".",
"requestOptions",
"=",
"{",
"followRedirect",
":",
"false",
",",
"headers",
":",
"{",
"'User-Agent'",
":",
"'tumblr.js/'",
"+",
"CLIENT_VERSION",
",",
"}",
",",
"}",
";",
"this",
".",
"addGetMethods",
"(",
"API_METHODS",
".",
"GET",
")",
";",
"this",
".",
"addPostMethods",
"(",
"API_METHODS",
".",
"POST",
")",
";",
"/**\n * Creates a text post on the given blog\n *\n * @see {@link https://www.tumblr.com/docs/api/v2#ptext-posts|API docs}\n *\n * @method createTextPost\n *\n * @param {string} blogIdentifier - blog name or URL\n * @param {Object} params - parameters sent with the request\n * @param {string} [params.title] - post title text\n * @param {string} params.body - post body text\n * @param {TumblrClient~callback} [callback] - invoked when the request completes\n *\n * @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used\n *\n * @memberof TumblrClient\n */",
"this",
".",
"createTextPost",
"=",
"wrapCreatePost",
"(",
"'text'",
",",
"[",
"'body'",
"]",
")",
";",
"/**\n * Creates a photo post on the given blog\n *\n * @see {@link https://www.tumblr.com/docs/api/v2#pphoto-posts|API docs}\n *\n * @method createPhotoPost\n *\n * @param {string} blogIdentifier - blog name or URL\n * @param {Object} params - parameters sent with the request\n * @param {string} params.source - image source URL\n * @param {Stream|Array} params.data - an image or array of images\n * @param {string} params.data64 - base64-encoded image data\n * @param {string} [params.caption] - post caption text\n * @param {TumblrClient~callback} [callback] - invoked when the request completes\n *\n * @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used\n *\n * @memberof TumblrClient\n */",
"this",
".",
"createPhotoPost",
"=",
"wrapCreatePost",
"(",
"'photo'",
",",
"[",
"'data'",
",",
"'data64'",
",",
"'source'",
"]",
")",
";",
"/**\n * Creates a quote post on the given blog\n *\n * @see {@link https://www.tumblr.com/docs/api/v2#pquote-posts|API docs}\n *\n * @method createQuotePost\n *\n * @param {string} blogIdentifier - blog name or URL\n * @param {Object} params - parameters sent with the request\n * @param {string} params.quote - quote text\n * @param {string} [params.source] - quote source\n * @param {TumblrClient~callback} [callback] - invoked when the request completes\n *\n * @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used\n *\n * @memberof TumblrClient\n */",
"this",
".",
"createQuotePost",
"=",
"wrapCreatePost",
"(",
"'quote'",
",",
"[",
"'quote'",
"]",
")",
";",
"/**\n * Creates a link post on the given blog\n *\n * @see {@link https://www.tumblr.com/docs/api/v2#plink-posts|API docs}\n *\n * @method createLinkPost\n *\n * @param {string} blogIdentifier - blog name or URL\n * @param {Object} params - parameters sent with the request\n * @param {string} [params.title] - post title text\n * @param {string} params.url - the link URL\n * @param {string} [params.thumbnail] - the URL of an image to use as the thumbnail\n * @param {string} [params.excerpt] - an excerpt from the page the link points to\n * @param {string} [params.author] - the name of the author of the page the link points to\n * @param {string} [params.description] - post caption text\n * @param {TumblrClient~callback} [callback] - invoked when the request completes\n *\n * @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used\n *\n * @memberof TumblrClient\n */",
"this",
".",
"createLinkPost",
"=",
"wrapCreatePost",
"(",
"'link'",
",",
"[",
"'url'",
"]",
")",
";",
"/**\n * Creates a chat post on the given blog\n *\n * @see {@link https://www.tumblr.com/docs/api/v2#pchat-posts|API docs}\n *\n * @method createChatPost\n *\n * @param {string} blogIdentifier - blog name or URL\n * @param {Object} params - parameters sent with the request\n * @param {string} [params.title] - post title text\n * @param {string} params.conversation - chat text\n * @param {TumblrClient~callback} [callback] - invoked when the request completes\n *\n * @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used\n *\n * @memberof TumblrClient\n */",
"this",
".",
"createChatPost",
"=",
"wrapCreatePost",
"(",
"'chat'",
",",
"[",
"'conversation'",
"]",
")",
";",
"/**\n * Creates an audio post on the given blog\n *\n * @see {@link https://www.tumblr.com/docs/api/v2#paudio-posts|API docs}\n *\n * @method createAudioPost\n *\n * @param {string} blogIdentifier - blog name or URL\n * @param {Object} params - parameters sent with the request\n * @param {string} params.external_url - image source URL\n * @param {Stream} params.data - an audio file\n * @param {string} [params.caption] - post caption text\n * @param {TumblrClient~callback} [callback] - invoked when the request completes\n *\n * @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used\n *\n * @memberof TumblrClient\n */",
"this",
".",
"createAudioPost",
"=",
"wrapCreatePost",
"(",
"'audio'",
",",
"[",
"'data'",
",",
"'data64'",
",",
"'external_url'",
"]",
")",
";",
"/**\n * Creates a video post on the given blog\n *\n * @see {@link https://www.tumblr.com/docs/api/v2#pvideo-posts|API docs}\n *\n * @method createVideoPost\n *\n * @param {string} blogIdentifier - blog name or URL\n * @param {Object} params - parameters sent with the request\n * @param {string} params.embed - embed code or a video URL\n * @param {Stream} params.data - a video file\n * @param {string} [params.caption] - post caption text\n * @param {TumblrClient~callback} [callback] - invoked when the request completes\n *\n * @return {Request|Promise} Request object, or Promise if {@link returnPromises} was used\n *\n * @memberof TumblrClient\n */",
"this",
".",
"createVideoPost",
"=",
"wrapCreatePost",
"(",
"'video'",
",",
"[",
"'data'",
",",
"'data64'",
",",
"'embed'",
"]",
")",
";",
"// Enable Promise mode",
"if",
"(",
"get",
"(",
"options",
",",
"'returnPromises'",
",",
"false",
")",
")",
"{",
"this",
".",
"returnPromises",
"(",
")",
";",
"}",
"}"
] |
Creates a Tumblr API client using the given options
@param {Object} [options] - client options
@param {Object} [options.credentials] - OAuth credentials
@param {string} [options.baseUrl] - API base URL
@param {Object} [options.request] - library to use for making requests
@constructor
|
[
"Creates",
"a",
"Tumblr",
"API",
"client",
"using",
"the",
"given",
"options"
] |
87301bbbc2f3f6e60c3270e0147454ac02f0acfb
|
https://github.com/tumblr/tumblr.js/blob/87301bbbc2f3f6e60c3270e0147454ac02f0acfb/lib/tumblr.js#L703-L875
|
18,769
|
tumblr/tumblr.js
|
lib/tumblr.js
|
function(options) {
// Support for `TumblrClient(credentials, baseUrl, requestLibrary)`
if (arguments.length > 1) {
options = {
credentials: arguments[0],
baseUrl: arguments[1],
request: arguments[2],
returnPromises: false,
};
}
// Create the Tumblr Client
const client = new TumblrClient(options);
return client;
}
|
javascript
|
function(options) {
// Support for `TumblrClient(credentials, baseUrl, requestLibrary)`
if (arguments.length > 1) {
options = {
credentials: arguments[0],
baseUrl: arguments[1],
request: arguments[2],
returnPromises: false,
};
}
// Create the Tumblr Client
const client = new TumblrClient(options);
return client;
}
|
[
"function",
"(",
"options",
")",
"{",
"// Support for `TumblrClient(credentials, baseUrl, requestLibrary)`",
"if",
"(",
"arguments",
".",
"length",
">",
"1",
")",
"{",
"options",
"=",
"{",
"credentials",
":",
"arguments",
"[",
"0",
"]",
",",
"baseUrl",
":",
"arguments",
"[",
"1",
"]",
",",
"request",
":",
"arguments",
"[",
"2",
"]",
",",
"returnPromises",
":",
"false",
",",
"}",
";",
"}",
"// Create the Tumblr Client",
"const",
"client",
"=",
"new",
"TumblrClient",
"(",
"options",
")",
";",
"return",
"client",
";",
"}"
] |
Creates a Tumblr Client
@param {Object} [options] - client options
@param {Object} [options.credentials] - OAuth credentials
@param {string} [options.baseUrl] - API base URL
@param {Object} [options.request] - library to use for making requests
@return {TumblrClient} {@link TumblrClient} instance
@memberof tumblr
@see {@link TumblrClient}
|
[
"Creates",
"a",
"Tumblr",
"Client"
] |
87301bbbc2f3f6e60c3270e0147454ac02f0acfb
|
https://github.com/tumblr/tumblr.js/blob/87301bbbc2f3f6e60c3270e0147454ac02f0acfb/lib/tumblr.js#L972-L987
|
|
18,770
|
aheckmann/node-ses
|
lib/email.js
|
Email
|
function Email (options) {
this.action = options.action || SEND_EMAIL_ACTION;
this.key = options.key;
this.secret = options.secret;
this.amazon = options.amazon;
this.from = options.from;
this.subject = options.subject;
this.message = options.message;
this.altText = options.altText;
this.rawMessage = options.rawMessage;
this.configurationSet = options.configurationSet;
this.messageTags = options.messageTags;
this.extractRecipient(options, 'to');
this.extractRecipient(options, 'cc');
this.extractRecipient(options, 'bcc');
this.extractRecipient(options, 'replyTo');
}
|
javascript
|
function Email (options) {
this.action = options.action || SEND_EMAIL_ACTION;
this.key = options.key;
this.secret = options.secret;
this.amazon = options.amazon;
this.from = options.from;
this.subject = options.subject;
this.message = options.message;
this.altText = options.altText;
this.rawMessage = options.rawMessage;
this.configurationSet = options.configurationSet;
this.messageTags = options.messageTags;
this.extractRecipient(options, 'to');
this.extractRecipient(options, 'cc');
this.extractRecipient(options, 'bcc');
this.extractRecipient(options, 'replyTo');
}
|
[
"function",
"Email",
"(",
"options",
")",
"{",
"this",
".",
"action",
"=",
"options",
".",
"action",
"||",
"SEND_EMAIL_ACTION",
";",
"this",
".",
"key",
"=",
"options",
".",
"key",
";",
"this",
".",
"secret",
"=",
"options",
".",
"secret",
";",
"this",
".",
"amazon",
"=",
"options",
".",
"amazon",
";",
"this",
".",
"from",
"=",
"options",
".",
"from",
";",
"this",
".",
"subject",
"=",
"options",
".",
"subject",
";",
"this",
".",
"message",
"=",
"options",
".",
"message",
";",
"this",
".",
"altText",
"=",
"options",
".",
"altText",
";",
"this",
".",
"rawMessage",
"=",
"options",
".",
"rawMessage",
";",
"this",
".",
"configurationSet",
"=",
"options",
".",
"configurationSet",
";",
"this",
".",
"messageTags",
"=",
"options",
".",
"messageTags",
";",
"this",
".",
"extractRecipient",
"(",
"options",
",",
"'to'",
")",
";",
"this",
".",
"extractRecipient",
"(",
"options",
",",
"'cc'",
")",
";",
"this",
".",
"extractRecipient",
"(",
"options",
",",
"'bcc'",
")",
";",
"this",
".",
"extractRecipient",
"(",
"options",
",",
"'replyTo'",
")",
";",
"}"
] |
Email constructor.
@param {Object} options
|
[
"Email",
"constructor",
"."
] |
03230e8f5a6278de736f3fbe4f1f7f12dac7aa42
|
https://github.com/aheckmann/node-ses/blob/03230e8f5a6278de736f3fbe4f1f7f12dac7aa42/lib/email.js#L22-L38
|
18,771
|
thinkloop/memoizerific
|
src/memoizerific.js
|
moveToMostRecentLru
|
function moveToMostRecentLru(lru, lruPath) {
var lruLen = lru.length,
lruPathLen = lruPath.length,
isMatch,
i, ii;
for (i = 0; i < lruLen; i++) {
isMatch = true;
for (ii = 0; ii < lruPathLen; ii++) {
if (!isEqual(lru[i][ii].arg, lruPath[ii].arg)) {
isMatch = false;
break;
}
}
if (isMatch) {
break;
}
}
lru.push(lru.splice(i, 1)[0]);
}
|
javascript
|
function moveToMostRecentLru(lru, lruPath) {
var lruLen = lru.length,
lruPathLen = lruPath.length,
isMatch,
i, ii;
for (i = 0; i < lruLen; i++) {
isMatch = true;
for (ii = 0; ii < lruPathLen; ii++) {
if (!isEqual(lru[i][ii].arg, lruPath[ii].arg)) {
isMatch = false;
break;
}
}
if (isMatch) {
break;
}
}
lru.push(lru.splice(i, 1)[0]);
}
|
[
"function",
"moveToMostRecentLru",
"(",
"lru",
",",
"lruPath",
")",
"{",
"var",
"lruLen",
"=",
"lru",
".",
"length",
",",
"lruPathLen",
"=",
"lruPath",
".",
"length",
",",
"isMatch",
",",
"i",
",",
"ii",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"lruLen",
";",
"i",
"++",
")",
"{",
"isMatch",
"=",
"true",
";",
"for",
"(",
"ii",
"=",
"0",
";",
"ii",
"<",
"lruPathLen",
";",
"ii",
"++",
")",
"{",
"if",
"(",
"!",
"isEqual",
"(",
"lru",
"[",
"i",
"]",
"[",
"ii",
"]",
".",
"arg",
",",
"lruPath",
"[",
"ii",
"]",
".",
"arg",
")",
")",
"{",
"isMatch",
"=",
"false",
";",
"break",
";",
"}",
"}",
"if",
"(",
"isMatch",
")",
"{",
"break",
";",
"}",
"}",
"lru",
".",
"push",
"(",
"lru",
".",
"splice",
"(",
"i",
",",
"1",
")",
"[",
"0",
"]",
")",
";",
"}"
] |
move current args to most recent position
|
[
"move",
"current",
"args",
"to",
"most",
"recent",
"position"
] |
d13074d4ef0b02924871c9e3958aa76628056605
|
https://github.com/thinkloop/memoizerific/blob/d13074d4ef0b02924871c9e3958aa76628056605/src/memoizerific.js#L94-L114
|
18,772
|
thinkloop/memoizerific
|
src/memoizerific.js
|
removeCachedResult
|
function removeCachedResult(removedLru) {
var removedLruLen = removedLru.length,
currentLru = removedLru[removedLruLen - 1],
tmp,
i;
currentLru.cacheItem.delete(currentLru.arg);
// walk down the tree removing dead branches (size 0) along the way
for (i = removedLruLen - 2; i >= 0; i--) {
currentLru = removedLru[i];
tmp = currentLru.cacheItem.get(currentLru.arg);
if (!tmp || !tmp.size) {
currentLru.cacheItem.delete(currentLru.arg);
} else {
break;
}
}
}
|
javascript
|
function removeCachedResult(removedLru) {
var removedLruLen = removedLru.length,
currentLru = removedLru[removedLruLen - 1],
tmp,
i;
currentLru.cacheItem.delete(currentLru.arg);
// walk down the tree removing dead branches (size 0) along the way
for (i = removedLruLen - 2; i >= 0; i--) {
currentLru = removedLru[i];
tmp = currentLru.cacheItem.get(currentLru.arg);
if (!tmp || !tmp.size) {
currentLru.cacheItem.delete(currentLru.arg);
} else {
break;
}
}
}
|
[
"function",
"removeCachedResult",
"(",
"removedLru",
")",
"{",
"var",
"removedLruLen",
"=",
"removedLru",
".",
"length",
",",
"currentLru",
"=",
"removedLru",
"[",
"removedLruLen",
"-",
"1",
"]",
",",
"tmp",
",",
"i",
";",
"currentLru",
".",
"cacheItem",
".",
"delete",
"(",
"currentLru",
".",
"arg",
")",
";",
"// walk down the tree removing dead branches (size 0) along the way",
"for",
"(",
"i",
"=",
"removedLruLen",
"-",
"2",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"currentLru",
"=",
"removedLru",
"[",
"i",
"]",
";",
"tmp",
"=",
"currentLru",
".",
"cacheItem",
".",
"get",
"(",
"currentLru",
".",
"arg",
")",
";",
"if",
"(",
"!",
"tmp",
"||",
"!",
"tmp",
".",
"size",
")",
"{",
"currentLru",
".",
"cacheItem",
".",
"delete",
"(",
"currentLru",
".",
"arg",
")",
";",
"}",
"else",
"{",
"break",
";",
"}",
"}",
"}"
] |
remove least recently used cache item and all dead branches
|
[
"remove",
"least",
"recently",
"used",
"cache",
"item",
"and",
"all",
"dead",
"branches"
] |
d13074d4ef0b02924871c9e3958aa76628056605
|
https://github.com/thinkloop/memoizerific/blob/d13074d4ef0b02924871c9e3958aa76628056605/src/memoizerific.js#L117-L136
|
18,773
|
workshopper/goingnative
|
lib/gyp.js
|
rebuild
|
function rebuild (dir, _callback) {
var cwd = process.cwd()
, gypInst = gyp()
var callback = function (err) {
_callback(err)
}
gypInst.parseArgv([ null, null, 'rebuild', '--loglevel', 'silent' ])
process.chdir(dir)
gypInst.commands.clean([], function (err) {
if (err)
return callback(new Error('node-gyp clean: ' + err.message))
gypInst.commands.configure([], function (err) {
if (err)
return callback(new Error('node-gyp configure: ' + err.message))
gypInst.commands.build([], function (err) {
if (err)
return callback(new Error('node-gyp build: ' + err.message))
process.chdir(cwd)
return callback()
})
})
})
}
|
javascript
|
function rebuild (dir, _callback) {
var cwd = process.cwd()
, gypInst = gyp()
var callback = function (err) {
_callback(err)
}
gypInst.parseArgv([ null, null, 'rebuild', '--loglevel', 'silent' ])
process.chdir(dir)
gypInst.commands.clean([], function (err) {
if (err)
return callback(new Error('node-gyp clean: ' + err.message))
gypInst.commands.configure([], function (err) {
if (err)
return callback(new Error('node-gyp configure: ' + err.message))
gypInst.commands.build([], function (err) {
if (err)
return callback(new Error('node-gyp build: ' + err.message))
process.chdir(cwd)
return callback()
})
})
})
}
|
[
"function",
"rebuild",
"(",
"dir",
",",
"_callback",
")",
"{",
"var",
"cwd",
"=",
"process",
".",
"cwd",
"(",
")",
",",
"gypInst",
"=",
"gyp",
"(",
")",
"var",
"callback",
"=",
"function",
"(",
"err",
")",
"{",
"_callback",
"(",
"err",
")",
"}",
"gypInst",
".",
"parseArgv",
"(",
"[",
"null",
",",
"null",
",",
"'rebuild'",
",",
"'--loglevel'",
",",
"'silent'",
"]",
")",
"process",
".",
"chdir",
"(",
"dir",
")",
"gypInst",
".",
"commands",
".",
"clean",
"(",
"[",
"]",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'node-gyp clean: '",
"+",
"err",
".",
"message",
")",
")",
"gypInst",
".",
"commands",
".",
"configure",
"(",
"[",
"]",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'node-gyp configure: '",
"+",
"err",
".",
"message",
")",
")",
"gypInst",
".",
"commands",
".",
"build",
"(",
"[",
"]",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'node-gyp build: '",
"+",
"err",
".",
"message",
")",
")",
"process",
".",
"chdir",
"(",
"cwd",
")",
"return",
"callback",
"(",
")",
"}",
")",
"}",
")",
"}",
")",
"}"
] |
invoke `node-gyp rebuild` programatically, runs clean;configure;build
|
[
"invoke",
"node",
"-",
"gyp",
"rebuild",
"programatically",
"runs",
"clean",
";",
"configure",
";",
"build"
] |
bfdc437383df849f5f9aab6028933cb490eac272
|
https://github.com/workshopper/goingnative/blob/bfdc437383df849f5f9aab6028933cb490eac272/lib/gyp.js#L9-L34
|
18,774
|
workshopper/goingnative
|
lib/gyp.js
|
checkBinding
|
function checkBinding (mode, callback) {
var exercise = this
function fail (msg) {
exercise.emit('fail', msg)
return callback(null, false)
}
fs.readFile(path.join(exercise.submission, 'binding.gyp'), 'utf8', function (err, data) {
if (err)
return fail('Read binding.gyp (' + err.message + ')')
var doc
try {
doc = yaml.safeLoad(data)
} catch (e) {
return fail('Parse binding.gyp (' + e.message + ')')
}
if (!is.isObject(doc))
return fail('binding.gyp does not contain a parent object ({ ... })')
if (!is.isArray(doc.targets))
return fail('binding.gyp does not contain a targets array ({ targets: [ ... ] })')
if (!is.isString(doc.targets[0].target_name))
return fail('binding.gyp does not contain a target_name for the first target')
if (doc.targets[0].target_name != 'myaddon')
return fail('binding.gyp does not name the first target "myaddon"')
exercise.emit('pass', 'binding.gyp includes a "myaddon" target')
if (!is.isArray(doc.targets[0].sources))
return fail('binding.gyp does not contain a sources array for the first target (sources: [ ... ])')
if (!doc.targets[0].sources.some(function (s) { return s == 'myaddon.cc' }))
return fail('binding.gyp does not list "myaddon.cc" in the sources array for the first target')
exercise.emit('pass', 'binding.gyp includes "myaddon.cc" as a source file')
if (!is.isArray(doc.targets[0].include_dirs))
return fail('binding.gyp does not contain a include_dirs array for the first target (include_dirs: [ ... ])')
var nanConstruct = '<!(node -e "require(\'nan\')")'
//TODO: grep the source for this string to make sure it's got `"` style quotes
if (!doc.targets[0].include_dirs.some(function (s) { return s == nanConstruct }))
return fail('binding.gyp does not list NAN properly in the include_dirs array for the first target')
exercise.emit('pass', 'binding.gyp includes a correct NAN include statement')
callback(null, true)
})
}
|
javascript
|
function checkBinding (mode, callback) {
var exercise = this
function fail (msg) {
exercise.emit('fail', msg)
return callback(null, false)
}
fs.readFile(path.join(exercise.submission, 'binding.gyp'), 'utf8', function (err, data) {
if (err)
return fail('Read binding.gyp (' + err.message + ')')
var doc
try {
doc = yaml.safeLoad(data)
} catch (e) {
return fail('Parse binding.gyp (' + e.message + ')')
}
if (!is.isObject(doc))
return fail('binding.gyp does not contain a parent object ({ ... })')
if (!is.isArray(doc.targets))
return fail('binding.gyp does not contain a targets array ({ targets: [ ... ] })')
if (!is.isString(doc.targets[0].target_name))
return fail('binding.gyp does not contain a target_name for the first target')
if (doc.targets[0].target_name != 'myaddon')
return fail('binding.gyp does not name the first target "myaddon"')
exercise.emit('pass', 'binding.gyp includes a "myaddon" target')
if (!is.isArray(doc.targets[0].sources))
return fail('binding.gyp does not contain a sources array for the first target (sources: [ ... ])')
if (!doc.targets[0].sources.some(function (s) { return s == 'myaddon.cc' }))
return fail('binding.gyp does not list "myaddon.cc" in the sources array for the first target')
exercise.emit('pass', 'binding.gyp includes "myaddon.cc" as a source file')
if (!is.isArray(doc.targets[0].include_dirs))
return fail('binding.gyp does not contain a include_dirs array for the first target (include_dirs: [ ... ])')
var nanConstruct = '<!(node -e "require(\'nan\')")'
//TODO: grep the source for this string to make sure it's got `"` style quotes
if (!doc.targets[0].include_dirs.some(function (s) { return s == nanConstruct }))
return fail('binding.gyp does not list NAN properly in the include_dirs array for the first target')
exercise.emit('pass', 'binding.gyp includes a correct NAN include statement')
callback(null, true)
})
}
|
[
"function",
"checkBinding",
"(",
"mode",
",",
"callback",
")",
"{",
"var",
"exercise",
"=",
"this",
"function",
"fail",
"(",
"msg",
")",
"{",
"exercise",
".",
"emit",
"(",
"'fail'",
",",
"msg",
")",
"return",
"callback",
"(",
"null",
",",
"false",
")",
"}",
"fs",
".",
"readFile",
"(",
"path",
".",
"join",
"(",
"exercise",
".",
"submission",
",",
"'binding.gyp'",
")",
",",
"'utf8'",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"return",
"fail",
"(",
"'Read binding.gyp ('",
"+",
"err",
".",
"message",
"+",
"')'",
")",
"var",
"doc",
"try",
"{",
"doc",
"=",
"yaml",
".",
"safeLoad",
"(",
"data",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"fail",
"(",
"'Parse binding.gyp ('",
"+",
"e",
".",
"message",
"+",
"')'",
")",
"}",
"if",
"(",
"!",
"is",
".",
"isObject",
"(",
"doc",
")",
")",
"return",
"fail",
"(",
"'binding.gyp does not contain a parent object ({ ... })'",
")",
"if",
"(",
"!",
"is",
".",
"isArray",
"(",
"doc",
".",
"targets",
")",
")",
"return",
"fail",
"(",
"'binding.gyp does not contain a targets array ({ targets: [ ... ] })'",
")",
"if",
"(",
"!",
"is",
".",
"isString",
"(",
"doc",
".",
"targets",
"[",
"0",
"]",
".",
"target_name",
")",
")",
"return",
"fail",
"(",
"'binding.gyp does not contain a target_name for the first target'",
")",
"if",
"(",
"doc",
".",
"targets",
"[",
"0",
"]",
".",
"target_name",
"!=",
"'myaddon'",
")",
"return",
"fail",
"(",
"'binding.gyp does not name the first target \"myaddon\"'",
")",
"exercise",
".",
"emit",
"(",
"'pass'",
",",
"'binding.gyp includes a \"myaddon\" target'",
")",
"if",
"(",
"!",
"is",
".",
"isArray",
"(",
"doc",
".",
"targets",
"[",
"0",
"]",
".",
"sources",
")",
")",
"return",
"fail",
"(",
"'binding.gyp does not contain a sources array for the first target (sources: [ ... ])'",
")",
"if",
"(",
"!",
"doc",
".",
"targets",
"[",
"0",
"]",
".",
"sources",
".",
"some",
"(",
"function",
"(",
"s",
")",
"{",
"return",
"s",
"==",
"'myaddon.cc'",
"}",
")",
")",
"return",
"fail",
"(",
"'binding.gyp does not list \"myaddon.cc\" in the sources array for the first target'",
")",
"exercise",
".",
"emit",
"(",
"'pass'",
",",
"'binding.gyp includes \"myaddon.cc\" as a source file'",
")",
"if",
"(",
"!",
"is",
".",
"isArray",
"(",
"doc",
".",
"targets",
"[",
"0",
"]",
".",
"include_dirs",
")",
")",
"return",
"fail",
"(",
"'binding.gyp does not contain a include_dirs array for the first target (include_dirs: [ ... ])'",
")",
"var",
"nanConstruct",
"=",
"'<!(node -e \"require(\\'nan\\')\")'",
"//TODO: grep the source for this string to make sure it's got `\"` style quotes",
"if",
"(",
"!",
"doc",
".",
"targets",
"[",
"0",
"]",
".",
"include_dirs",
".",
"some",
"(",
"function",
"(",
"s",
")",
"{",
"return",
"s",
"==",
"nanConstruct",
"}",
")",
")",
"return",
"fail",
"(",
"'binding.gyp does not list NAN properly in the include_dirs array for the first target'",
")",
"exercise",
".",
"emit",
"(",
"'pass'",
",",
"'binding.gyp includes a correct NAN include statement'",
")",
"callback",
"(",
"null",
",",
"true",
")",
"}",
")",
"}"
] |
check binding.gyp to see if it's parsable YAML and contains the basic structure that we need for this to work
|
[
"check",
"binding",
".",
"gyp",
"to",
"see",
"if",
"it",
"s",
"parsable",
"YAML",
"and",
"contains",
"the",
"basic",
"structure",
"that",
"we",
"need",
"for",
"this",
"to",
"work"
] |
bfdc437383df849f5f9aab6028933cb490eac272
|
https://github.com/workshopper/goingnative/blob/bfdc437383df849f5f9aab6028933cb490eac272/lib/gyp.js#L39-L94
|
18,775
|
workshopper/goingnative
|
lib/check.js
|
checkSubmissionDir
|
function checkSubmissionDir (mode, callback) {
var exercise = this
exercise.submission = this.args[0] // submission first arg obviously
function failBadPath () {
exercise.emit('fail', 'Submitted a readable directory path (please supply a path to your solution)')
callback(null, false)
}
if (!exercise.submission)
return failBadPath()
fs.stat(exercise.submission, function (err, stat) {
if (err)
return failBadPath()
if (!stat.isDirectory())
return failBadPath()
callback(null, true)
})
}
|
javascript
|
function checkSubmissionDir (mode, callback) {
var exercise = this
exercise.submission = this.args[0] // submission first arg obviously
function failBadPath () {
exercise.emit('fail', 'Submitted a readable directory path (please supply a path to your solution)')
callback(null, false)
}
if (!exercise.submission)
return failBadPath()
fs.stat(exercise.submission, function (err, stat) {
if (err)
return failBadPath()
if (!stat.isDirectory())
return failBadPath()
callback(null, true)
})
}
|
[
"function",
"checkSubmissionDir",
"(",
"mode",
",",
"callback",
")",
"{",
"var",
"exercise",
"=",
"this",
"exercise",
".",
"submission",
"=",
"this",
".",
"args",
"[",
"0",
"]",
"// submission first arg obviously",
"function",
"failBadPath",
"(",
")",
"{",
"exercise",
".",
"emit",
"(",
"'fail'",
",",
"'Submitted a readable directory path (please supply a path to your solution)'",
")",
"callback",
"(",
"null",
",",
"false",
")",
"}",
"if",
"(",
"!",
"exercise",
".",
"submission",
")",
"return",
"failBadPath",
"(",
")",
"fs",
".",
"stat",
"(",
"exercise",
".",
"submission",
",",
"function",
"(",
"err",
",",
"stat",
")",
"{",
"if",
"(",
"err",
")",
"return",
"failBadPath",
"(",
")",
"if",
"(",
"!",
"stat",
".",
"isDirectory",
"(",
")",
")",
"return",
"failBadPath",
"(",
")",
"callback",
"(",
"null",
",",
"true",
")",
"}",
")",
"}"
] |
simple check to see they are running a verify or run with an actual directory
|
[
"simple",
"check",
"to",
"see",
"they",
"are",
"running",
"a",
"verify",
"or",
"run",
"with",
"an",
"actual",
"directory"
] |
bfdc437383df849f5f9aab6028933cb490eac272
|
https://github.com/workshopper/goingnative/blob/bfdc437383df849f5f9aab6028933cb490eac272/lib/check.js#L5-L28
|
18,776
|
workshopper/goingnative
|
lib/compile.js
|
checkCompile
|
function checkCompile (dir) {
return function (mode, callback) {
var exercise = this
if (!exercise.passed)
return callback(null, true) // shortcut if we've already had a failure
gyp.rebuild(dir, function (err) {
if (err) {
exercise.emit('fail', err.message)
return callback(null, false)
}
callback(null, true)
})
}
}
|
javascript
|
function checkCompile (dir) {
return function (mode, callback) {
var exercise = this
if (!exercise.passed)
return callback(null, true) // shortcut if we've already had a failure
gyp.rebuild(dir, function (err) {
if (err) {
exercise.emit('fail', err.message)
return callback(null, false)
}
callback(null, true)
})
}
}
|
[
"function",
"checkCompile",
"(",
"dir",
")",
"{",
"return",
"function",
"(",
"mode",
",",
"callback",
")",
"{",
"var",
"exercise",
"=",
"this",
"if",
"(",
"!",
"exercise",
".",
"passed",
")",
"return",
"callback",
"(",
"null",
",",
"true",
")",
"// shortcut if we've already had a failure",
"gyp",
".",
"rebuild",
"(",
"dir",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"exercise",
".",
"emit",
"(",
"'fail'",
",",
"err",
".",
"message",
")",
"return",
"callback",
"(",
"null",
",",
"false",
")",
"}",
"callback",
"(",
"null",
",",
"true",
")",
"}",
")",
"}",
"}"
] |
run a `node-gyp rebuild` on their unmolested code in our copy
|
[
"run",
"a",
"node",
"-",
"gyp",
"rebuild",
"on",
"their",
"unmolested",
"code",
"in",
"our",
"copy"
] |
bfdc437383df849f5f9aab6028933cb490eac272
|
https://github.com/workshopper/goingnative/blob/bfdc437383df849f5f9aab6028933cb490eac272/lib/compile.js#L5-L21
|
18,777
|
workshopper/goingnative
|
lib/copy.js
|
cleanup
|
function cleanup (dirs) {
return function (mode, pass, callback) {
var done = after(dirs.length, callback)
dirs.forEach(function (dir) {
rimraf(dir, done)
})
}
}
|
javascript
|
function cleanup (dirs) {
return function (mode, pass, callback) {
var done = after(dirs.length, callback)
dirs.forEach(function (dir) {
rimraf(dir, done)
})
}
}
|
[
"function",
"cleanup",
"(",
"dirs",
")",
"{",
"return",
"function",
"(",
"mode",
",",
"pass",
",",
"callback",
")",
"{",
"var",
"done",
"=",
"after",
"(",
"dirs",
".",
"length",
",",
"callback",
")",
"dirs",
".",
"forEach",
"(",
"function",
"(",
"dir",
")",
"{",
"rimraf",
"(",
"dir",
",",
"done",
")",
"}",
")",
"}",
"}"
] |
don't leave the tmp dirs
|
[
"don",
"t",
"leave",
"the",
"tmp",
"dirs"
] |
bfdc437383df849f5f9aab6028933cb490eac272
|
https://github.com/workshopper/goingnative/blob/bfdc437383df849f5f9aab6028933cb490eac272/lib/copy.js#L50-L58
|
18,778
|
workshopper/goingnative
|
exercises/am_i_ready/exercise.js
|
setup
|
function setup (mode, callback) {
copy(testPackageSrc, testPackageRnd, { overwrite: true }, function (err) {
if (err)
return callback(err)
copy.copyDeps(testPackageRnd, callback)
})
}
|
javascript
|
function setup (mode, callback) {
copy(testPackageSrc, testPackageRnd, { overwrite: true }, function (err) {
if (err)
return callback(err)
copy.copyDeps(testPackageRnd, callback)
})
}
|
[
"function",
"setup",
"(",
"mode",
",",
"callback",
")",
"{",
"copy",
"(",
"testPackageSrc",
",",
"testPackageRnd",
",",
"{",
"overwrite",
":",
"true",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
"copy",
".",
"copyDeps",
"(",
"testPackageRnd",
",",
"callback",
")",
"}",
")",
"}"
] |
copy test package to a temporary location, populate it with bindings and nan
|
[
"copy",
"test",
"package",
"to",
"a",
"temporary",
"location",
"populate",
"it",
"with",
"bindings",
"and",
"nan"
] |
bfdc437383df849f5f9aab6028933cb490eac272
|
https://github.com/workshopper/goingnative/blob/bfdc437383df849f5f9aab6028933cb490eac272/exercises/am_i_ready/exercise.js#L37-L44
|
18,779
|
simsalabim/sisyphus
|
vendor/jasmine/jasmine-jquery.js
|
function(eventName, eventHandler) {
var stack = this.actual.data("events")[eventName];
var i;
for (i = 0; i < stack.length; i++) {
if (stack[i].handler == eventHandler) {
return true;
}
}
return false;
}
|
javascript
|
function(eventName, eventHandler) {
var stack = this.actual.data("events")[eventName];
var i;
for (i = 0; i < stack.length; i++) {
if (stack[i].handler == eventHandler) {
return true;
}
}
return false;
}
|
[
"function",
"(",
"eventName",
",",
"eventHandler",
")",
"{",
"var",
"stack",
"=",
"this",
".",
"actual",
".",
"data",
"(",
"\"events\"",
")",
"[",
"eventName",
"]",
";",
"var",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"stack",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"stack",
"[",
"i",
"]",
".",
"handler",
"==",
"eventHandler",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
tests the existence of a specific event binding + handler
|
[
"tests",
"the",
"existence",
"of",
"a",
"specific",
"event",
"binding",
"+",
"handler"
] |
1878a0f51ffc3062ff3d1740b22a8c8c7f616262
|
https://github.com/simsalabim/sisyphus/blob/1878a0f51ffc3062ff3d1740b22a8c8c7f616262/vendor/jasmine/jasmine-jquery.js#L228-L237
|
|
18,780
|
simsalabim/sisyphus
|
sisyphus.js
|
function ( options ) {
var defaults = {
excludeFields: [],
customKeySuffix: "",
locationBased: false,
timeout: 0,
autoRelease: true,
onBeforeSave: function() {},
onSave: function() {},
onBeforeRestore: function() {},
onRestore: function() {},
onRelease: function() {}
};
this.options = this.options || $.extend( defaults, options );
this.browserStorage = browserStorage;
}
|
javascript
|
function ( options ) {
var defaults = {
excludeFields: [],
customKeySuffix: "",
locationBased: false,
timeout: 0,
autoRelease: true,
onBeforeSave: function() {},
onSave: function() {},
onBeforeRestore: function() {},
onRestore: function() {},
onRelease: function() {}
};
this.options = this.options || $.extend( defaults, options );
this.browserStorage = browserStorage;
}
|
[
"function",
"(",
"options",
")",
"{",
"var",
"defaults",
"=",
"{",
"excludeFields",
":",
"[",
"]",
",",
"customKeySuffix",
":",
"\"\"",
",",
"locationBased",
":",
"false",
",",
"timeout",
":",
"0",
",",
"autoRelease",
":",
"true",
",",
"onBeforeSave",
":",
"function",
"(",
")",
"{",
"}",
",",
"onSave",
":",
"function",
"(",
")",
"{",
"}",
",",
"onBeforeRestore",
":",
"function",
"(",
")",
"{",
"}",
",",
"onRestore",
":",
"function",
"(",
")",
"{",
"}",
",",
"onRelease",
":",
"function",
"(",
")",
"{",
"}",
"}",
";",
"this",
".",
"options",
"=",
"this",
".",
"options",
"||",
"$",
".",
"extend",
"(",
"defaults",
",",
"options",
")",
";",
"this",
".",
"browserStorage",
"=",
"browserStorage",
";",
"}"
] |
Set plugin initial options
@param [Object] options
@return void
|
[
"Set",
"plugin",
"initial",
"options"
] |
1878a0f51ffc3062ff3d1740b22a8c8c7f616262
|
https://github.com/simsalabim/sisyphus/blob/1878a0f51ffc3062ff3d1740b22a8c8c7f616262/sisyphus.js#L121-L136
|
|
18,781
|
simsalabim/sisyphus
|
sisyphus.js
|
function( targets, options ) {
this.setOptions( options );
targets = targets || {};
var self = this;
this.targets = this.targets || [];
if ( self.options.name ) {
this.href = self.options.name;
} else {
this.href = location.hostname + location.pathname + location.search + location.hash;
}
this.targets = $.merge( this.targets, targets );
this.targets = $.unique( this.targets );
this.targets = $( this.targets );
if ( ! this.browserStorage.isAvailable() ) {
return false;
}
var callback_result = self.options.onBeforeRestore.call( self );
if ( callback_result === undefined || callback_result ) {
self.restoreAllData();
}
if ( this.options.autoRelease ) {
self.bindReleaseData();
}
if ( ! params.started[ this.getInstanceIdentifier() ] ) {
if ( self.isCKEditorPresent() ) {
var intervalId = setInterval( function() {
if (CKEDITOR.isLoaded) {
clearInterval(intervalId);
self.bindSaveData();
params.started[ self.getInstanceIdentifier() ] = true;
}
}, 100);
} else {
self.bindSaveData();
params.started[ self.getInstanceIdentifier() ] = true;
}
}
}
|
javascript
|
function( targets, options ) {
this.setOptions( options );
targets = targets || {};
var self = this;
this.targets = this.targets || [];
if ( self.options.name ) {
this.href = self.options.name;
} else {
this.href = location.hostname + location.pathname + location.search + location.hash;
}
this.targets = $.merge( this.targets, targets );
this.targets = $.unique( this.targets );
this.targets = $( this.targets );
if ( ! this.browserStorage.isAvailable() ) {
return false;
}
var callback_result = self.options.onBeforeRestore.call( self );
if ( callback_result === undefined || callback_result ) {
self.restoreAllData();
}
if ( this.options.autoRelease ) {
self.bindReleaseData();
}
if ( ! params.started[ this.getInstanceIdentifier() ] ) {
if ( self.isCKEditorPresent() ) {
var intervalId = setInterval( function() {
if (CKEDITOR.isLoaded) {
clearInterval(intervalId);
self.bindSaveData();
params.started[ self.getInstanceIdentifier() ] = true;
}
}, 100);
} else {
self.bindSaveData();
params.started[ self.getInstanceIdentifier() ] = true;
}
}
}
|
[
"function",
"(",
"targets",
",",
"options",
")",
"{",
"this",
".",
"setOptions",
"(",
"options",
")",
";",
"targets",
"=",
"targets",
"||",
"{",
"}",
";",
"var",
"self",
"=",
"this",
";",
"this",
".",
"targets",
"=",
"this",
".",
"targets",
"||",
"[",
"]",
";",
"if",
"(",
"self",
".",
"options",
".",
"name",
")",
"{",
"this",
".",
"href",
"=",
"self",
".",
"options",
".",
"name",
";",
"}",
"else",
"{",
"this",
".",
"href",
"=",
"location",
".",
"hostname",
"+",
"location",
".",
"pathname",
"+",
"location",
".",
"search",
"+",
"location",
".",
"hash",
";",
"}",
"this",
".",
"targets",
"=",
"$",
".",
"merge",
"(",
"this",
".",
"targets",
",",
"targets",
")",
";",
"this",
".",
"targets",
"=",
"$",
".",
"unique",
"(",
"this",
".",
"targets",
")",
";",
"this",
".",
"targets",
"=",
"$",
"(",
"this",
".",
"targets",
")",
";",
"if",
"(",
"!",
"this",
".",
"browserStorage",
".",
"isAvailable",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"var",
"callback_result",
"=",
"self",
".",
"options",
".",
"onBeforeRestore",
".",
"call",
"(",
"self",
")",
";",
"if",
"(",
"callback_result",
"===",
"undefined",
"||",
"callback_result",
")",
"{",
"self",
".",
"restoreAllData",
"(",
")",
";",
"}",
"if",
"(",
"this",
".",
"options",
".",
"autoRelease",
")",
"{",
"self",
".",
"bindReleaseData",
"(",
")",
";",
"}",
"if",
"(",
"!",
"params",
".",
"started",
"[",
"this",
".",
"getInstanceIdentifier",
"(",
")",
"]",
")",
"{",
"if",
"(",
"self",
".",
"isCKEditorPresent",
"(",
")",
")",
"{",
"var",
"intervalId",
"=",
"setInterval",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"CKEDITOR",
".",
"isLoaded",
")",
"{",
"clearInterval",
"(",
"intervalId",
")",
";",
"self",
".",
"bindSaveData",
"(",
")",
";",
"params",
".",
"started",
"[",
"self",
".",
"getInstanceIdentifier",
"(",
")",
"]",
"=",
"true",
";",
"}",
"}",
",",
"100",
")",
";",
"}",
"else",
"{",
"self",
".",
"bindSaveData",
"(",
")",
";",
"params",
".",
"started",
"[",
"self",
".",
"getInstanceIdentifier",
"(",
")",
"]",
"=",
"true",
";",
"}",
"}",
"}"
] |
Protect specified forms, store it's fields data to local storage and restore them on page load
@param [Object] targets forms object(s), result of jQuery selector
@param Object options plugin options
@return void
|
[
"Protect",
"specified",
"forms",
"store",
"it",
"s",
"fields",
"data",
"to",
"local",
"storage",
"and",
"restore",
"them",
"on",
"page",
"load"
] |
1878a0f51ffc3062ff3d1740b22a8c8c7f616262
|
https://github.com/simsalabim/sisyphus/blob/1878a0f51ffc3062ff3d1740b22a8c8c7f616262/sisyphus.js#L158-L198
|
|
18,782
|
simsalabim/sisyphus
|
sisyphus.js
|
function() {
var self = this;
if ( self.options.timeout ) {
self.saveDataByTimeout();
}
self.targets.each( function() {
var targetFormIdAndName = getElementIdentifier( $( this ) );
self.findFieldsToProtect( $( this ) ).each( function() {
if ( $.inArray( this, self.options.excludeFields ) !== -1 ) {
// Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
return true;
}
var field = $( this );
var prefix = (self.options.locationBased ? self.href : "") + targetFormIdAndName + getElementIdentifier( field ) + self.options.customKeySuffix;
if ( field.is( ":text" ) || field.is( "textarea" ) ) {
if ( ! self.options.timeout ) {
self.bindSaveDataImmediately( field, prefix );
}
}
self.bindSaveDataOnChange( field );
} );
} );
}
|
javascript
|
function() {
var self = this;
if ( self.options.timeout ) {
self.saveDataByTimeout();
}
self.targets.each( function() {
var targetFormIdAndName = getElementIdentifier( $( this ) );
self.findFieldsToProtect( $( this ) ).each( function() {
if ( $.inArray( this, self.options.excludeFields ) !== -1 ) {
// Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
return true;
}
var field = $( this );
var prefix = (self.options.locationBased ? self.href : "") + targetFormIdAndName + getElementIdentifier( field ) + self.options.customKeySuffix;
if ( field.is( ":text" ) || field.is( "textarea" ) ) {
if ( ! self.options.timeout ) {
self.bindSaveDataImmediately( field, prefix );
}
}
self.bindSaveDataOnChange( field );
} );
} );
}
|
[
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"self",
".",
"options",
".",
"timeout",
")",
"{",
"self",
".",
"saveDataByTimeout",
"(",
")",
";",
"}",
"self",
".",
"targets",
".",
"each",
"(",
"function",
"(",
")",
"{",
"var",
"targetFormIdAndName",
"=",
"getElementIdentifier",
"(",
"$",
"(",
"this",
")",
")",
";",
"self",
".",
"findFieldsToProtect",
"(",
"$",
"(",
"this",
")",
")",
".",
"each",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"$",
".",
"inArray",
"(",
"this",
",",
"self",
".",
"options",
".",
"excludeFields",
")",
"!==",
"-",
"1",
")",
"{",
"// Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.",
"return",
"true",
";",
"}",
"var",
"field",
"=",
"$",
"(",
"this",
")",
";",
"var",
"prefix",
"=",
"(",
"self",
".",
"options",
".",
"locationBased",
"?",
"self",
".",
"href",
":",
"\"\"",
")",
"+",
"targetFormIdAndName",
"+",
"getElementIdentifier",
"(",
"field",
")",
"+",
"self",
".",
"options",
".",
"customKeySuffix",
";",
"if",
"(",
"field",
".",
"is",
"(",
"\":text\"",
")",
"||",
"field",
".",
"is",
"(",
"\"textarea\"",
")",
")",
"{",
"if",
"(",
"!",
"self",
".",
"options",
".",
"timeout",
")",
"{",
"self",
".",
"bindSaveDataImmediately",
"(",
"field",
",",
"prefix",
")",
";",
"}",
"}",
"self",
".",
"bindSaveDataOnChange",
"(",
"field",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Bind saving data
@return void
|
[
"Bind",
"saving",
"data"
] |
1878a0f51ffc3062ff3d1740b22a8c8c7f616262
|
https://github.com/simsalabim/sisyphus/blob/1878a0f51ffc3062ff3d1740b22a8c8c7f616262/sisyphus.js#L225-L249
|
|
18,783
|
simsalabim/sisyphus
|
sisyphus.js
|
function() {
var self = this;
var restored = false;
self.targets.each( function() {
var target = $( this );
var targetFormIdAndName = getElementIdentifier( $( this ) );
self.findFieldsToProtect( target ).each( function() {
if ( $.inArray( this, self.options.excludeFields ) !== -1 ) {
// Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
return true;
}
var field = $( this );
var prefix = (self.options.locationBased ? self.href : "") + targetFormIdAndName + getElementIdentifier( field ) + self.options.customKeySuffix;
var resque = self.browserStorage.get( prefix );
if ( resque !== null ) {
self.restoreFieldsData( field, resque );
restored = true;
}
} );
} );
if ( restored ) {
self.options.onRestore.call( self );
}
}
|
javascript
|
function() {
var self = this;
var restored = false;
self.targets.each( function() {
var target = $( this );
var targetFormIdAndName = getElementIdentifier( $( this ) );
self.findFieldsToProtect( target ).each( function() {
if ( $.inArray( this, self.options.excludeFields ) !== -1 ) {
// Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
return true;
}
var field = $( this );
var prefix = (self.options.locationBased ? self.href : "") + targetFormIdAndName + getElementIdentifier( field ) + self.options.customKeySuffix;
var resque = self.browserStorage.get( prefix );
if ( resque !== null ) {
self.restoreFieldsData( field, resque );
restored = true;
}
} );
} );
if ( restored ) {
self.options.onRestore.call( self );
}
}
|
[
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"restored",
"=",
"false",
";",
"self",
".",
"targets",
".",
"each",
"(",
"function",
"(",
")",
"{",
"var",
"target",
"=",
"$",
"(",
"this",
")",
";",
"var",
"targetFormIdAndName",
"=",
"getElementIdentifier",
"(",
"$",
"(",
"this",
")",
")",
";",
"self",
".",
"findFieldsToProtect",
"(",
"target",
")",
".",
"each",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"$",
".",
"inArray",
"(",
"this",
",",
"self",
".",
"options",
".",
"excludeFields",
")",
"!==",
"-",
"1",
")",
"{",
"// Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.",
"return",
"true",
";",
"}",
"var",
"field",
"=",
"$",
"(",
"this",
")",
";",
"var",
"prefix",
"=",
"(",
"self",
".",
"options",
".",
"locationBased",
"?",
"self",
".",
"href",
":",
"\"\"",
")",
"+",
"targetFormIdAndName",
"+",
"getElementIdentifier",
"(",
"field",
")",
"+",
"self",
".",
"options",
".",
"customKeySuffix",
";",
"var",
"resque",
"=",
"self",
".",
"browserStorage",
".",
"get",
"(",
"prefix",
")",
";",
"if",
"(",
"resque",
"!==",
"null",
")",
"{",
"self",
".",
"restoreFieldsData",
"(",
"field",
",",
"resque",
")",
";",
"restored",
"=",
"true",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"if",
"(",
"restored",
")",
"{",
"self",
".",
"options",
".",
"onRestore",
".",
"call",
"(",
"self",
")",
";",
"}",
"}"
] |
Restore forms data from Local Storage
@return void
|
[
"Restore",
"forms",
"data",
"from",
"Local",
"Storage"
] |
1878a0f51ffc3062ff3d1740b22a8c8c7f616262
|
https://github.com/simsalabim/sisyphus/blob/1878a0f51ffc3062ff3d1740b22a8c8c7f616262/sisyphus.js#L318-L344
|
|
18,784
|
simsalabim/sisyphus
|
sisyphus.js
|
function( field, resque ) {
if ( field.attr( "name" ) === undefined && field.attr( "id" ) === undefined ) {
return false;
}
var name = field.attr( "name" );
if ( field.is( ":checkbox" ) && resque !== "false" && ( name === undefined || name.indexOf( "[" ) === -1 ) ) {
// If we aren't named by name (e.g. id) or we aren't in a multiple element field
field.prop( "checked", true );
} else if( field.is( ":checkbox" ) && resque === "false" && ( name === undefined || name.indexOf( "[" ) === -1 ) ) {
// If we aren't named by name (e.g. id) or we aren't in a multiple element field
field.prop( "checked", false );
} else if ( field.is( ":radio" ) ) {
if ( field.val() === resque ) {
field.prop( "checked", true );
}
} else if ( name === undefined || name.indexOf( "[" ) === -1 ) {
// If we aren't named by name (e.g. id) or we aren't in a multiple element field
field.val( resque );
} else {
resque = resque.split( "," );
field.val( resque );
}
}
|
javascript
|
function( field, resque ) {
if ( field.attr( "name" ) === undefined && field.attr( "id" ) === undefined ) {
return false;
}
var name = field.attr( "name" );
if ( field.is( ":checkbox" ) && resque !== "false" && ( name === undefined || name.indexOf( "[" ) === -1 ) ) {
// If we aren't named by name (e.g. id) or we aren't in a multiple element field
field.prop( "checked", true );
} else if( field.is( ":checkbox" ) && resque === "false" && ( name === undefined || name.indexOf( "[" ) === -1 ) ) {
// If we aren't named by name (e.g. id) or we aren't in a multiple element field
field.prop( "checked", false );
} else if ( field.is( ":radio" ) ) {
if ( field.val() === resque ) {
field.prop( "checked", true );
}
} else if ( name === undefined || name.indexOf( "[" ) === -1 ) {
// If we aren't named by name (e.g. id) or we aren't in a multiple element field
field.val( resque );
} else {
resque = resque.split( "," );
field.val( resque );
}
}
|
[
"function",
"(",
"field",
",",
"resque",
")",
"{",
"if",
"(",
"field",
".",
"attr",
"(",
"\"name\"",
")",
"===",
"undefined",
"&&",
"field",
".",
"attr",
"(",
"\"id\"",
")",
"===",
"undefined",
")",
"{",
"return",
"false",
";",
"}",
"var",
"name",
"=",
"field",
".",
"attr",
"(",
"\"name\"",
")",
";",
"if",
"(",
"field",
".",
"is",
"(",
"\":checkbox\"",
")",
"&&",
"resque",
"!==",
"\"false\"",
"&&",
"(",
"name",
"===",
"undefined",
"||",
"name",
".",
"indexOf",
"(",
"\"[\"",
")",
"===",
"-",
"1",
")",
")",
"{",
"// If we aren't named by name (e.g. id) or we aren't in a multiple element field",
"field",
".",
"prop",
"(",
"\"checked\"",
",",
"true",
")",
";",
"}",
"else",
"if",
"(",
"field",
".",
"is",
"(",
"\":checkbox\"",
")",
"&&",
"resque",
"===",
"\"false\"",
"&&",
"(",
"name",
"===",
"undefined",
"||",
"name",
".",
"indexOf",
"(",
"\"[\"",
")",
"===",
"-",
"1",
")",
")",
"{",
"// If we aren't named by name (e.g. id) or we aren't in a multiple element field",
"field",
".",
"prop",
"(",
"\"checked\"",
",",
"false",
")",
";",
"}",
"else",
"if",
"(",
"field",
".",
"is",
"(",
"\":radio\"",
")",
")",
"{",
"if",
"(",
"field",
".",
"val",
"(",
")",
"===",
"resque",
")",
"{",
"field",
".",
"prop",
"(",
"\"checked\"",
",",
"true",
")",
";",
"}",
"}",
"else",
"if",
"(",
"name",
"===",
"undefined",
"||",
"name",
".",
"indexOf",
"(",
"\"[\"",
")",
"===",
"-",
"1",
")",
"{",
"// If we aren't named by name (e.g. id) or we aren't in a multiple element field",
"field",
".",
"val",
"(",
"resque",
")",
";",
"}",
"else",
"{",
"resque",
"=",
"resque",
".",
"split",
"(",
"\",\"",
")",
";",
"field",
".",
"val",
"(",
"resque",
")",
";",
"}",
"}"
] |
Restore form field data from local storage
@param Object field jQuery form element object
@param String resque previously stored fields data
@return void
|
[
"Restore",
"form",
"field",
"data",
"from",
"local",
"storage"
] |
1878a0f51ffc3062ff3d1740b22a8c8c7f616262
|
https://github.com/simsalabim/sisyphus/blob/1878a0f51ffc3062ff3d1740b22a8c8c7f616262/sisyphus.js#L354-L376
|
|
18,785
|
simsalabim/sisyphus
|
sisyphus.js
|
function( key, value, fireCallback ) {
var self = this;
var callback_result = self.options.onBeforeSave.call( self );
if ( callback_result !== undefined && callback_result === false ) {
return;
}
// if fireCallback is undefined it should be true
fireCallback = fireCallback === undefined ? true : fireCallback;
this.browserStorage.set( key, value );
if ( fireCallback && value !== "" ) {
this.options.onSave.call( this );
}
}
|
javascript
|
function( key, value, fireCallback ) {
var self = this;
var callback_result = self.options.onBeforeSave.call( self );
if ( callback_result !== undefined && callback_result === false ) {
return;
}
// if fireCallback is undefined it should be true
fireCallback = fireCallback === undefined ? true : fireCallback;
this.browserStorage.set( key, value );
if ( fireCallback && value !== "" ) {
this.options.onSave.call( this );
}
}
|
[
"function",
"(",
"key",
",",
"value",
",",
"fireCallback",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"callback_result",
"=",
"self",
".",
"options",
".",
"onBeforeSave",
".",
"call",
"(",
"self",
")",
";",
"if",
"(",
"callback_result",
"!==",
"undefined",
"&&",
"callback_result",
"===",
"false",
")",
"{",
"return",
";",
"}",
"// if fireCallback is undefined it should be true",
"fireCallback",
"=",
"fireCallback",
"===",
"undefined",
"?",
"true",
":",
"fireCallback",
";",
"this",
".",
"browserStorage",
".",
"set",
"(",
"key",
",",
"value",
")",
";",
"if",
"(",
"fireCallback",
"&&",
"value",
"!==",
"\"\"",
")",
"{",
"this",
".",
"options",
".",
"onSave",
".",
"call",
"(",
"this",
")",
";",
"}",
"}"
] |
Save data to Local Storage and fire callback if defined
@param String key
@param String value
@param Boolean [true] fireCallback
@return void
|
[
"Save",
"data",
"to",
"Local",
"Storage",
"and",
"fire",
"callback",
"if",
"defined"
] |
1878a0f51ffc3062ff3d1740b22a8c8c7f616262
|
https://github.com/simsalabim/sisyphus/blob/1878a0f51ffc3062ff3d1740b22a8c8c7f616262/sisyphus.js#L417-L431
|
|
18,786
|
simsalabim/sisyphus
|
sisyphus.js
|
function() {
var self = this;
self.targets.each( function() {
var target = $( this );
var formIdAndName = getElementIdentifier( target );
self.releaseData( formIdAndName, self.findFieldsToProtect( target ) );
} );
}
|
javascript
|
function() {
var self = this;
self.targets.each( function() {
var target = $( this );
var formIdAndName = getElementIdentifier( target );
self.releaseData( formIdAndName, self.findFieldsToProtect( target ) );
} );
}
|
[
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"self",
".",
"targets",
".",
"each",
"(",
"function",
"(",
")",
"{",
"var",
"target",
"=",
"$",
"(",
"this",
")",
";",
"var",
"formIdAndName",
"=",
"getElementIdentifier",
"(",
"target",
")",
";",
"self",
".",
"releaseData",
"(",
"formIdAndName",
",",
"self",
".",
"findFieldsToProtect",
"(",
"target",
")",
")",
";",
"}",
")",
";",
"}"
] |
Manually release form fields
@return void
|
[
"Manually",
"release",
"form",
"fields"
] |
1878a0f51ffc3062ff3d1740b22a8c8c7f616262
|
https://github.com/simsalabim/sisyphus/blob/1878a0f51ffc3062ff3d1740b22a8c8c7f616262/sisyphus.js#L485-L492
|
|
18,787
|
jhiesey/stream-http
|
lib/request.js
|
statusValid
|
function statusValid (xhr) {
try {
var status = xhr.status
return (status !== null && status !== 0)
} catch (e) {
return false
}
}
|
javascript
|
function statusValid (xhr) {
try {
var status = xhr.status
return (status !== null && status !== 0)
} catch (e) {
return false
}
}
|
[
"function",
"statusValid",
"(",
"xhr",
")",
"{",
"try",
"{",
"var",
"status",
"=",
"xhr",
".",
"status",
"return",
"(",
"status",
"!==",
"null",
"&&",
"status",
"!==",
"0",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"false",
"}",
"}"
] |
Checks if xhr.status is readable and non-zero, indicating no error.
Even though the spec says it should be available in readyState 3,
accessing it throws an exception in IE8
|
[
"Checks",
"if",
"xhr",
".",
"status",
"is",
"readable",
"and",
"non",
"-",
"zero",
"indicating",
"no",
"error",
".",
"Even",
"though",
"the",
"spec",
"says",
"it",
"should",
"be",
"available",
"in",
"readyState",
"3",
"accessing",
"it",
"throws",
"an",
"exception",
"in",
"IE8"
] |
e60ce5fb99d1c74e96120aa1086197c43fc100a8
|
https://github.com/jhiesey/stream-http/blob/e60ce5fb99d1c74e96120aa1086197c43fc100a8/lib/request.js#L224-L231
|
18,788
|
klei/gulp-inject
|
src/inject/index.js
|
handleVinylStream
|
function handleVinylStream(sources, opt) {
var collected = streamToArray(sources);
return through2.obj(function (target, enc, cb) {
if (target.isStream()) {
return cb(error('Streams not supported for target templates!'));
}
collected.then(function (collection) {
target.contents = getNewContent(target, collection, opt);
this.push(target);
cb();
}.bind(this))
.catch(function (error) {
cb(error);
});
});
}
|
javascript
|
function handleVinylStream(sources, opt) {
var collected = streamToArray(sources);
return through2.obj(function (target, enc, cb) {
if (target.isStream()) {
return cb(error('Streams not supported for target templates!'));
}
collected.then(function (collection) {
target.contents = getNewContent(target, collection, opt);
this.push(target);
cb();
}.bind(this))
.catch(function (error) {
cb(error);
});
});
}
|
[
"function",
"handleVinylStream",
"(",
"sources",
",",
"opt",
")",
"{",
"var",
"collected",
"=",
"streamToArray",
"(",
"sources",
")",
";",
"return",
"through2",
".",
"obj",
"(",
"function",
"(",
"target",
",",
"enc",
",",
"cb",
")",
"{",
"if",
"(",
"target",
".",
"isStream",
"(",
")",
")",
"{",
"return",
"cb",
"(",
"error",
"(",
"'Streams not supported for target templates!'",
")",
")",
";",
"}",
"collected",
".",
"then",
"(",
"function",
"(",
"collection",
")",
"{",
"target",
".",
"contents",
"=",
"getNewContent",
"(",
"target",
",",
"collection",
",",
"opt",
")",
";",
"this",
".",
"push",
"(",
"target",
")",
";",
"cb",
"(",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
".",
"catch",
"(",
"function",
"(",
"error",
")",
"{",
"cb",
"(",
"error",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Handle injection when files to
inject comes from a Vinyl File Stream
@param {Stream} sources
@param {Object} opt
@returns {Stream}
|
[
"Handle",
"injection",
"when",
"files",
"to",
"inject",
"comes",
"from",
"a",
"Vinyl",
"File",
"Stream"
] |
59bf9c68e4fe8cd500d196669df3bbd6e29611a9
|
https://github.com/klei/gulp-inject/blob/59bf9c68e4fe8cd500d196669df3bbd6e29611a9/src/inject/index.js#L80-L96
|
18,789
|
klei/gulp-inject
|
src/inject/index.js
|
getNewContent
|
function getNewContent(target, collection, opt) {
var logger = opt.quiet ? noop : function (filesCount) {
if (filesCount) {
var pluralState = filesCount > 1 ? 's' : '';
log(cyan(filesCount) + ' file' + pluralState + ' into ' + magenta(target.relative) + '.');
} else {
log('Nothing to inject into ' + magenta(target.relative) + '.');
}
};
var content = String(target.contents);
var targetExt = extname(target.path);
var files = prepareFiles(collection, targetExt, opt, target);
var filesPerTags = groupArray(files, 'tagKey');
var startAndEndTags = Object.keys(filesPerTags);
var matches = [];
var injectedFilesCount = 0;
startAndEndTags.forEach(function (tagKey) {
var files = filesPerTags[tagKey];
var startTag = files[0].startTag;
var endTag = files[0].endTag;
var tagsToInject = getTagsToInject(files, target, opt);
content = inject(content, {
startTag: startTag,
endTag: endTag,
tagsToInject: tagsToInject,
removeTags: opt.removeTags,
empty: opt.empty,
willInject: function (filesToInject) {
injectedFilesCount += filesToInject.length;
},
onMatch: function (match) {
matches.push(match[0]);
}
});
});
logger(injectedFilesCount);
if (opt.empty) {
var ext = '{{ANY}}';
var startTag = getTagRegExp(opt.tags.start(targetExt, ext, opt.starttag), ext, opt);
var endTag = getTagRegExp(opt.tags.end(targetExt, ext, opt.endtag), ext, opt);
content = inject(content, {
startTag: startTag,
endTag: endTag,
tagsToInject: [],
removeTags: opt.removeTags,
empty: opt.empty,
shouldAbort: function (match) {
return matches.indexOf(match[0]) !== -1;
}
});
}
return Buffer.from(content);
}
|
javascript
|
function getNewContent(target, collection, opt) {
var logger = opt.quiet ? noop : function (filesCount) {
if (filesCount) {
var pluralState = filesCount > 1 ? 's' : '';
log(cyan(filesCount) + ' file' + pluralState + ' into ' + magenta(target.relative) + '.');
} else {
log('Nothing to inject into ' + magenta(target.relative) + '.');
}
};
var content = String(target.contents);
var targetExt = extname(target.path);
var files = prepareFiles(collection, targetExt, opt, target);
var filesPerTags = groupArray(files, 'tagKey');
var startAndEndTags = Object.keys(filesPerTags);
var matches = [];
var injectedFilesCount = 0;
startAndEndTags.forEach(function (tagKey) {
var files = filesPerTags[tagKey];
var startTag = files[0].startTag;
var endTag = files[0].endTag;
var tagsToInject = getTagsToInject(files, target, opt);
content = inject(content, {
startTag: startTag,
endTag: endTag,
tagsToInject: tagsToInject,
removeTags: opt.removeTags,
empty: opt.empty,
willInject: function (filesToInject) {
injectedFilesCount += filesToInject.length;
},
onMatch: function (match) {
matches.push(match[0]);
}
});
});
logger(injectedFilesCount);
if (opt.empty) {
var ext = '{{ANY}}';
var startTag = getTagRegExp(opt.tags.start(targetExt, ext, opt.starttag), ext, opt);
var endTag = getTagRegExp(opt.tags.end(targetExt, ext, opt.endtag), ext, opt);
content = inject(content, {
startTag: startTag,
endTag: endTag,
tagsToInject: [],
removeTags: opt.removeTags,
empty: opt.empty,
shouldAbort: function (match) {
return matches.indexOf(match[0]) !== -1;
}
});
}
return Buffer.from(content);
}
|
[
"function",
"getNewContent",
"(",
"target",
",",
"collection",
",",
"opt",
")",
"{",
"var",
"logger",
"=",
"opt",
".",
"quiet",
"?",
"noop",
":",
"function",
"(",
"filesCount",
")",
"{",
"if",
"(",
"filesCount",
")",
"{",
"var",
"pluralState",
"=",
"filesCount",
">",
"1",
"?",
"'s'",
":",
"''",
";",
"log",
"(",
"cyan",
"(",
"filesCount",
")",
"+",
"' file'",
"+",
"pluralState",
"+",
"' into '",
"+",
"magenta",
"(",
"target",
".",
"relative",
")",
"+",
"'.'",
")",
";",
"}",
"else",
"{",
"log",
"(",
"'Nothing to inject into '",
"+",
"magenta",
"(",
"target",
".",
"relative",
")",
"+",
"'.'",
")",
";",
"}",
"}",
";",
"var",
"content",
"=",
"String",
"(",
"target",
".",
"contents",
")",
";",
"var",
"targetExt",
"=",
"extname",
"(",
"target",
".",
"path",
")",
";",
"var",
"files",
"=",
"prepareFiles",
"(",
"collection",
",",
"targetExt",
",",
"opt",
",",
"target",
")",
";",
"var",
"filesPerTags",
"=",
"groupArray",
"(",
"files",
",",
"'tagKey'",
")",
";",
"var",
"startAndEndTags",
"=",
"Object",
".",
"keys",
"(",
"filesPerTags",
")",
";",
"var",
"matches",
"=",
"[",
"]",
";",
"var",
"injectedFilesCount",
"=",
"0",
";",
"startAndEndTags",
".",
"forEach",
"(",
"function",
"(",
"tagKey",
")",
"{",
"var",
"files",
"=",
"filesPerTags",
"[",
"tagKey",
"]",
";",
"var",
"startTag",
"=",
"files",
"[",
"0",
"]",
".",
"startTag",
";",
"var",
"endTag",
"=",
"files",
"[",
"0",
"]",
".",
"endTag",
";",
"var",
"tagsToInject",
"=",
"getTagsToInject",
"(",
"files",
",",
"target",
",",
"opt",
")",
";",
"content",
"=",
"inject",
"(",
"content",
",",
"{",
"startTag",
":",
"startTag",
",",
"endTag",
":",
"endTag",
",",
"tagsToInject",
":",
"tagsToInject",
",",
"removeTags",
":",
"opt",
".",
"removeTags",
",",
"empty",
":",
"opt",
".",
"empty",
",",
"willInject",
":",
"function",
"(",
"filesToInject",
")",
"{",
"injectedFilesCount",
"+=",
"filesToInject",
".",
"length",
";",
"}",
",",
"onMatch",
":",
"function",
"(",
"match",
")",
"{",
"matches",
".",
"push",
"(",
"match",
"[",
"0",
"]",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"logger",
"(",
"injectedFilesCount",
")",
";",
"if",
"(",
"opt",
".",
"empty",
")",
"{",
"var",
"ext",
"=",
"'{{ANY}}'",
";",
"var",
"startTag",
"=",
"getTagRegExp",
"(",
"opt",
".",
"tags",
".",
"start",
"(",
"targetExt",
",",
"ext",
",",
"opt",
".",
"starttag",
")",
",",
"ext",
",",
"opt",
")",
";",
"var",
"endTag",
"=",
"getTagRegExp",
"(",
"opt",
".",
"tags",
".",
"end",
"(",
"targetExt",
",",
"ext",
",",
"opt",
".",
"endtag",
")",
",",
"ext",
",",
"opt",
")",
";",
"content",
"=",
"inject",
"(",
"content",
",",
"{",
"startTag",
":",
"startTag",
",",
"endTag",
":",
"endTag",
",",
"tagsToInject",
":",
"[",
"]",
",",
"removeTags",
":",
"opt",
".",
"removeTags",
",",
"empty",
":",
"opt",
".",
"empty",
",",
"shouldAbort",
":",
"function",
"(",
"match",
")",
"{",
"return",
"matches",
".",
"indexOf",
"(",
"match",
"[",
"0",
"]",
")",
"!==",
"-",
"1",
";",
"}",
"}",
")",
";",
"}",
"return",
"Buffer",
".",
"from",
"(",
"content",
")",
";",
"}"
] |
Get new content for template
with all injections made
@param {Object} target
@param {Array} collection
@param {Object} opt
@returns {Buffer}
|
[
"Get",
"new",
"content",
"for",
"template",
"with",
"all",
"injections",
"made"
] |
59bf9c68e4fe8cd500d196669df3bbd6e29611a9
|
https://github.com/klei/gulp-inject/blob/59bf9c68e4fe8cd500d196669df3bbd6e29611a9/src/inject/index.js#L107-L164
|
18,790
|
klei/gulp-inject
|
src/inject/index.js
|
inject
|
function inject(content, opt) {
var startTag = opt.startTag;
var endTag = opt.endTag;
var startMatch;
var endMatch;
/**
* The content consists of:
*
* <everything before startMatch>
* <startMatch>
* <previousInnerContent>
* <endMatch>
* <everything after endMatch>
*/
while ((startMatch = startTag.exec(content)) !== null) {
if (typeof opt.onMatch === 'function') {
opt.onMatch(startMatch);
}
if (typeof opt.shouldAbort === 'function' && opt.shouldAbort(startMatch)) {
continue;
}
// Take care of content length change:
endTag.lastIndex = startTag.lastIndex;
endMatch = endTag.exec(content);
if (!endMatch) {
throw error('Missing end tag for start tag: ' + startMatch[0]);
}
var toInject = opt.tagsToInject.slice();
if (typeof opt.willInject === 'function') {
opt.willInject(toInject);
}
// <everything before startMatch>:
var newContents = content.slice(0, startMatch.index);
if (opt.removeTags) {
if (opt.empty) {
// Take care of content length change:
startTag.lastIndex -= startMatch[0].length;
}
} else {
// <startMatch> + <endMatch>
toInject.unshift(startMatch[0]);
toInject.push(endMatch[0]);
}
var previousInnerContent = content.substring(startTag.lastIndex, endMatch.index);
var indent = getLeadingWhitespace(previousInnerContent);
// <new inner content>:
newContents += toInject.join(indent);
// <everything after endMatch>:
newContents += content.slice(endTag.lastIndex);
// Replace old content with new:
content = newContents;
}
return content;
}
|
javascript
|
function inject(content, opt) {
var startTag = opt.startTag;
var endTag = opt.endTag;
var startMatch;
var endMatch;
/**
* The content consists of:
*
* <everything before startMatch>
* <startMatch>
* <previousInnerContent>
* <endMatch>
* <everything after endMatch>
*/
while ((startMatch = startTag.exec(content)) !== null) {
if (typeof opt.onMatch === 'function') {
opt.onMatch(startMatch);
}
if (typeof opt.shouldAbort === 'function' && opt.shouldAbort(startMatch)) {
continue;
}
// Take care of content length change:
endTag.lastIndex = startTag.lastIndex;
endMatch = endTag.exec(content);
if (!endMatch) {
throw error('Missing end tag for start tag: ' + startMatch[0]);
}
var toInject = opt.tagsToInject.slice();
if (typeof opt.willInject === 'function') {
opt.willInject(toInject);
}
// <everything before startMatch>:
var newContents = content.slice(0, startMatch.index);
if (opt.removeTags) {
if (opt.empty) {
// Take care of content length change:
startTag.lastIndex -= startMatch[0].length;
}
} else {
// <startMatch> + <endMatch>
toInject.unshift(startMatch[0]);
toInject.push(endMatch[0]);
}
var previousInnerContent = content.substring(startTag.lastIndex, endMatch.index);
var indent = getLeadingWhitespace(previousInnerContent);
// <new inner content>:
newContents += toInject.join(indent);
// <everything after endMatch>:
newContents += content.slice(endTag.lastIndex);
// Replace old content with new:
content = newContents;
}
return content;
}
|
[
"function",
"inject",
"(",
"content",
",",
"opt",
")",
"{",
"var",
"startTag",
"=",
"opt",
".",
"startTag",
";",
"var",
"endTag",
"=",
"opt",
".",
"endTag",
";",
"var",
"startMatch",
";",
"var",
"endMatch",
";",
"/**\n * The content consists of:\n *\n * <everything before startMatch>\n * <startMatch>\n * <previousInnerContent>\n * <endMatch>\n * <everything after endMatch>\n */",
"while",
"(",
"(",
"startMatch",
"=",
"startTag",
".",
"exec",
"(",
"content",
")",
")",
"!==",
"null",
")",
"{",
"if",
"(",
"typeof",
"opt",
".",
"onMatch",
"===",
"'function'",
")",
"{",
"opt",
".",
"onMatch",
"(",
"startMatch",
")",
";",
"}",
"if",
"(",
"typeof",
"opt",
".",
"shouldAbort",
"===",
"'function'",
"&&",
"opt",
".",
"shouldAbort",
"(",
"startMatch",
")",
")",
"{",
"continue",
";",
"}",
"// Take care of content length change:",
"endTag",
".",
"lastIndex",
"=",
"startTag",
".",
"lastIndex",
";",
"endMatch",
"=",
"endTag",
".",
"exec",
"(",
"content",
")",
";",
"if",
"(",
"!",
"endMatch",
")",
"{",
"throw",
"error",
"(",
"'Missing end tag for start tag: '",
"+",
"startMatch",
"[",
"0",
"]",
")",
";",
"}",
"var",
"toInject",
"=",
"opt",
".",
"tagsToInject",
".",
"slice",
"(",
")",
";",
"if",
"(",
"typeof",
"opt",
".",
"willInject",
"===",
"'function'",
")",
"{",
"opt",
".",
"willInject",
"(",
"toInject",
")",
";",
"}",
"// <everything before startMatch>:",
"var",
"newContents",
"=",
"content",
".",
"slice",
"(",
"0",
",",
"startMatch",
".",
"index",
")",
";",
"if",
"(",
"opt",
".",
"removeTags",
")",
"{",
"if",
"(",
"opt",
".",
"empty",
")",
"{",
"// Take care of content length change:",
"startTag",
".",
"lastIndex",
"-=",
"startMatch",
"[",
"0",
"]",
".",
"length",
";",
"}",
"}",
"else",
"{",
"// <startMatch> + <endMatch>",
"toInject",
".",
"unshift",
"(",
"startMatch",
"[",
"0",
"]",
")",
";",
"toInject",
".",
"push",
"(",
"endMatch",
"[",
"0",
"]",
")",
";",
"}",
"var",
"previousInnerContent",
"=",
"content",
".",
"substring",
"(",
"startTag",
".",
"lastIndex",
",",
"endMatch",
".",
"index",
")",
";",
"var",
"indent",
"=",
"getLeadingWhitespace",
"(",
"previousInnerContent",
")",
";",
"// <new inner content>:",
"newContents",
"+=",
"toInject",
".",
"join",
"(",
"indent",
")",
";",
"// <everything after endMatch>:",
"newContents",
"+=",
"content",
".",
"slice",
"(",
"endTag",
".",
"lastIndex",
")",
";",
"// Replace old content with new:",
"content",
"=",
"newContents",
";",
"}",
"return",
"content",
";",
"}"
] |
Inject tags into content for given
start and end tags
@param {String} content
@param {Object} opt
@returns {String}
|
[
"Inject",
"tags",
"into",
"content",
"for",
"given",
"start",
"and",
"end",
"tags"
] |
59bf9c68e4fe8cd500d196669df3bbd6e29611a9
|
https://github.com/klei/gulp-inject/blob/59bf9c68e4fe8cd500d196669df3bbd6e29611a9/src/inject/index.js#L174-L233
|
18,791
|
brianleroux/lawnchair
|
src/adapters/chrome-storage.js
|
function () {
return !!storage && function() {
// in mobile safari if safe browsing is enabled, window.storage
// is defined but setItem calls throw exceptions.
var success = true
var value = Math.random()
value = "" + value + "" //ensure that we are dealing with a string
try {
var _set = {}
_set[value] = value;
storage.set(_set)
} catch (e) {
success = false
}
storage.remove(value)
return success
}()
}
|
javascript
|
function () {
return !!storage && function() {
// in mobile safari if safe browsing is enabled, window.storage
// is defined but setItem calls throw exceptions.
var success = true
var value = Math.random()
value = "" + value + "" //ensure that we are dealing with a string
try {
var _set = {}
_set[value] = value;
storage.set(_set)
} catch (e) {
success = false
}
storage.remove(value)
return success
}()
}
|
[
"function",
"(",
")",
"{",
"return",
"!",
"!",
"storage",
"&&",
"function",
"(",
")",
"{",
"// in mobile safari if safe browsing is enabled, window.storage",
"// is defined but setItem calls throw exceptions.",
"var",
"success",
"=",
"true",
"var",
"value",
"=",
"Math",
".",
"random",
"(",
")",
"value",
"=",
"\"\"",
"+",
"value",
"+",
"\"\"",
"//ensure that we are dealing with a string",
"try",
"{",
"var",
"_set",
"=",
"{",
"}",
"_set",
"[",
"value",
"]",
"=",
"value",
";",
"storage",
".",
"set",
"(",
"_set",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"success",
"=",
"false",
"}",
"storage",
".",
"remove",
"(",
"value",
")",
"return",
"success",
"}",
"(",
")",
"}"
] |
ensure we are in an env with chrome.storage
|
[
"ensure",
"we",
"are",
"in",
"an",
"env",
"with",
"chrome",
".",
"storage"
] |
4a20309b14cee3b6eb74b24c688c5a4a5a98f879
|
https://github.com/brianleroux/lawnchair/blob/4a20309b14cee3b6eb74b24c688c5a4a5a98f879/src/adapters/chrome-storage.js#L97-L114
|
|
18,792
|
brianleroux/lawnchair
|
lib/lawnchair.js
|
function () {
return !!storage && function() {
// in mobile safari if safe browsing is enabled, window.storage
// is defined but setItem calls throw exceptions.
var success = true
var value = Math.random()
try {
storage.setItem(value, value)
} catch (e) {
success = false
}
storage.removeItem(value)
return success
}()
}
|
javascript
|
function () {
return !!storage && function() {
// in mobile safari if safe browsing is enabled, window.storage
// is defined but setItem calls throw exceptions.
var success = true
var value = Math.random()
try {
storage.setItem(value, value)
} catch (e) {
success = false
}
storage.removeItem(value)
return success
}()
}
|
[
"function",
"(",
")",
"{",
"return",
"!",
"!",
"storage",
"&&",
"function",
"(",
")",
"{",
"// in mobile safari if safe browsing is enabled, window.storage",
"// is defined but setItem calls throw exceptions.",
"var",
"success",
"=",
"true",
"var",
"value",
"=",
"Math",
".",
"random",
"(",
")",
"try",
"{",
"storage",
".",
"setItem",
"(",
"value",
",",
"value",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"success",
"=",
"false",
"}",
"storage",
".",
"removeItem",
"(",
"value",
")",
"return",
"success",
"}",
"(",
")",
"}"
] |
ensure we are in an env with localStorage
|
[
"ensure",
"we",
"are",
"in",
"an",
"env",
"with",
"localStorage"
] |
4a20309b14cee3b6eb74b24c688c5a4a5a98f879
|
https://github.com/brianleroux/lawnchair/blob/4a20309b14cee3b6eb74b24c688c5a4a5a98f879/lib/lawnchair.js#L358-L372
|
|
18,793
|
brianleroux/lawnchair
|
src/adapters/html5-filesystem.js
|
function( callback ) {
var me = this;
root( this, function( store ) {
ls( store.createReader(), function( entries ) {
if ( callback ) me.fn( 'keys', callback ).call( me, entries );
});
});
return this;
}
|
javascript
|
function( callback ) {
var me = this;
root( this, function( store ) {
ls( store.createReader(), function( entries ) {
if ( callback ) me.fn( 'keys', callback ).call( me, entries );
});
});
return this;
}
|
[
"function",
"(",
"callback",
")",
"{",
"var",
"me",
"=",
"this",
";",
"root",
"(",
"this",
",",
"function",
"(",
"store",
")",
"{",
"ls",
"(",
"store",
".",
"createReader",
"(",
")",
",",
"function",
"(",
"entries",
")",
"{",
"if",
"(",
"callback",
")",
"me",
".",
"fn",
"(",
"'keys'",
",",
"callback",
")",
".",
"call",
"(",
"me",
",",
"entries",
")",
";",
"}",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}"
] |
returns all the keys in the store
|
[
"returns",
"all",
"the",
"keys",
"in",
"the",
"store"
] |
4a20309b14cee3b6eb74b24c688c5a4a5a98f879
|
https://github.com/brianleroux/lawnchair/blob/4a20309b14cee3b6eb74b24c688c5a4a5a98f879/src/adapters/html5-filesystem.js#L62-L70
|
|
18,794
|
brianleroux/lawnchair
|
src/adapters/html5-filesystem.js
|
function( objs, callback ) {
var me = this;
var saved = [];
for ( var i = 0, il = objs.length; i < il; i++ ) {
me.save( objs[i], function( obj ) {
saved.push( obj );
if ( saved.length === il && callback ) {
me.lambda( callback ).call( me, saved );
}
});
}
return this;
}
|
javascript
|
function( objs, callback ) {
var me = this;
var saved = [];
for ( var i = 0, il = objs.length; i < il; i++ ) {
me.save( objs[i], function( obj ) {
saved.push( obj );
if ( saved.length === il && callback ) {
me.lambda( callback ).call( me, saved );
}
});
}
return this;
}
|
[
"function",
"(",
"objs",
",",
"callback",
")",
"{",
"var",
"me",
"=",
"this",
";",
"var",
"saved",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"il",
"=",
"objs",
".",
"length",
";",
"i",
"<",
"il",
";",
"i",
"++",
")",
"{",
"me",
".",
"save",
"(",
"objs",
"[",
"i",
"]",
",",
"function",
"(",
"obj",
")",
"{",
"saved",
".",
"push",
"(",
"obj",
")",
";",
"if",
"(",
"saved",
".",
"length",
"===",
"il",
"&&",
"callback",
")",
"{",
"me",
".",
"lambda",
"(",
"callback",
")",
".",
"call",
"(",
"me",
",",
"saved",
")",
";",
"}",
"}",
")",
";",
"}",
"return",
"this",
";",
"}"
] |
batch save array of objs
|
[
"batch",
"save",
"array",
"of",
"objs"
] |
4a20309b14cee3b6eb74b24c688c5a4a5a98f879
|
https://github.com/brianleroux/lawnchair/blob/4a20309b14cee3b6eb74b24c688c5a4a5a98f879/src/adapters/html5-filesystem.js#L101-L113
|
|
18,795
|
brianleroux/lawnchair
|
src/plugins/callbacks.js
|
function () {
for (var i = 0, l = methods.length; i < l; i++) {
this.evented(methods[i])
}
}
|
javascript
|
function () {
for (var i = 0, l = methods.length; i < l; i++) {
this.evented(methods[i])
}
}
|
[
"function",
"(",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"methods",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"this",
".",
"evented",
"(",
"methods",
"[",
"i",
"]",
")",
"}",
"}"
] |
start of module roll thru each method we with to augment
|
[
"start",
"of",
"module",
"roll",
"thru",
"each",
"method",
"we",
"with",
"to",
"augment"
] |
4a20309b14cee3b6eb74b24c688c5a4a5a98f879
|
https://github.com/brianleroux/lawnchair/blob/4a20309b14cee3b6eb74b24c688c5a4a5a98f879/src/plugins/callbacks.js#L18-L22
|
|
18,796
|
brianleroux/lawnchair
|
src/adapters/indexed-db.js
|
onupgradeneeded
|
function onupgradeneeded() {
self.db = request.result;
self.transaction = request.transaction;
// NB! in case of a version conflict, we don't try to migrate,
// instead just throw away the old store and create a new one.
// this happens if somebody changed the
try {
self.db.deleteObjectStore(self.record);
} catch (e) { /* ignore */ }
// create object store.
var objectStoreOptions = {
autoIncrement: useAutoIncrement()
}
if( typeof( self.keyPath )) {
objectStoreOptions.keyPath = self.keyPath;
}
self.db.createObjectStore(self.record, objectStoreOptions);
}
|
javascript
|
function onupgradeneeded() {
self.db = request.result;
self.transaction = request.transaction;
// NB! in case of a version conflict, we don't try to migrate,
// instead just throw away the old store and create a new one.
// this happens if somebody changed the
try {
self.db.deleteObjectStore(self.record);
} catch (e) { /* ignore */ }
// create object store.
var objectStoreOptions = {
autoIncrement: useAutoIncrement()
}
if( typeof( self.keyPath )) {
objectStoreOptions.keyPath = self.keyPath;
}
self.db.createObjectStore(self.record, objectStoreOptions);
}
|
[
"function",
"onupgradeneeded",
"(",
")",
"{",
"self",
".",
"db",
"=",
"request",
".",
"result",
";",
"self",
".",
"transaction",
"=",
"request",
".",
"transaction",
";",
"// NB! in case of a version conflict, we don't try to migrate,",
"// instead just throw away the old store and create a new one.",
"// this happens if somebody changed the ",
"try",
"{",
"self",
".",
"db",
".",
"deleteObjectStore",
"(",
"self",
".",
"record",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"/* ignore */",
"}",
"// create object store.",
"var",
"objectStoreOptions",
"=",
"{",
"autoIncrement",
":",
"useAutoIncrement",
"(",
")",
"}",
"if",
"(",
"typeof",
"(",
"self",
".",
"keyPath",
")",
")",
"{",
"objectStoreOptions",
".",
"keyPath",
"=",
"self",
".",
"keyPath",
";",
"}",
"self",
".",
"db",
".",
"createObjectStore",
"(",
"self",
".",
"record",
",",
"objectStoreOptions",
")",
";",
"}"
] |
first start or indexeddb needs a version upgrade
|
[
"first",
"start",
"or",
"indexeddb",
"needs",
"a",
"version",
"upgrade"
] |
4a20309b14cee3b6eb74b24c688c5a4a5a98f879
|
https://github.com/brianleroux/lawnchair/blob/4a20309b14cee3b6eb74b24c688c5a4a5a98f879/src/adapters/indexed-db.js#L56-L75
|
18,797
|
brianleroux/lawnchair
|
src/adapters/indexed-db.js
|
onsuccess
|
function onsuccess(event) {
// remember the db instance
self.db = event.target.result;
// storage is now possible
self.store = true;
// execute all pending operations
while (self.waiting.length) {
self.waiting.shift().call(self);
}
// we're done, fire the callback
if (cb) {
cb.call(self, self);
}
}
|
javascript
|
function onsuccess(event) {
// remember the db instance
self.db = event.target.result;
// storage is now possible
self.store = true;
// execute all pending operations
while (self.waiting.length) {
self.waiting.shift().call(self);
}
// we're done, fire the callback
if (cb) {
cb.call(self, self);
}
}
|
[
"function",
"onsuccess",
"(",
"event",
")",
"{",
"// remember the db instance",
"self",
".",
"db",
"=",
"event",
".",
"target",
".",
"result",
";",
"// storage is now possible",
"self",
".",
"store",
"=",
"true",
";",
"// execute all pending operations",
"while",
"(",
"self",
".",
"waiting",
".",
"length",
")",
"{",
"self",
".",
"waiting",
".",
"shift",
"(",
")",
".",
"call",
"(",
"self",
")",
";",
"}",
"// we're done, fire the callback",
"if",
"(",
"cb",
")",
"{",
"cb",
".",
"call",
"(",
"self",
",",
"self",
")",
";",
"}",
"}"
] |
database is ready for use
|
[
"database",
"is",
"ready",
"for",
"use"
] |
4a20309b14cee3b6eb74b24c688c5a4a5a98f879
|
https://github.com/brianleroux/lawnchair/blob/4a20309b14cee3b6eb74b24c688c5a4a5a98f879/src/adapters/indexed-db.js#L78-L94
|
18,798
|
brianleroux/lawnchair
|
src/plugins/aggregation.js
|
function (property, callback) {
// if only one arg we count the collection
if ([].slice.call(arguments).length === 1) {
callback = property
property = 'key'
}
var c = 0
this.each(function(e){
if (e[property]) c++
})
this.fn('count', callback).call(this, c)
}
|
javascript
|
function (property, callback) {
// if only one arg we count the collection
if ([].slice.call(arguments).length === 1) {
callback = property
property = 'key'
}
var c = 0
this.each(function(e){
if (e[property]) c++
})
this.fn('count', callback).call(this, c)
}
|
[
"function",
"(",
"property",
",",
"callback",
")",
"{",
"// if only one arg we count the collection",
"if",
"(",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
".",
"length",
"===",
"1",
")",
"{",
"callback",
"=",
"property",
"property",
"=",
"'key'",
"}",
"var",
"c",
"=",
"0",
"this",
".",
"each",
"(",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"e",
"[",
"property",
"]",
")",
"c",
"++",
"}",
")",
"this",
".",
"fn",
"(",
"'count'",
",",
"callback",
")",
".",
"call",
"(",
"this",
",",
"c",
")",
"}"
] |
count of rows in the lawnchair collection with property
|
[
"count",
"of",
"rows",
"in",
"the",
"lawnchair",
"collection",
"with",
"property"
] |
4a20309b14cee3b6eb74b24c688c5a4a5a98f879
|
https://github.com/brianleroux/lawnchair/blob/4a20309b14cee3b6eb74b24c688c5a4a5a98f879/src/plugins/aggregation.js#L4-L15
|
|
18,799
|
brianleroux/lawnchair
|
src/plugins/aggregation.js
|
function (property, callback) {
var sum = 0
this.each(function(e){
if (e[property]) sum += e[property]
})
this.fn('sum', callback).call(this, sum)
}
|
javascript
|
function (property, callback) {
var sum = 0
this.each(function(e){
if (e[property]) sum += e[property]
})
this.fn('sum', callback).call(this, sum)
}
|
[
"function",
"(",
"property",
",",
"callback",
")",
"{",
"var",
"sum",
"=",
"0",
"this",
".",
"each",
"(",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"e",
"[",
"property",
"]",
")",
"sum",
"+=",
"e",
"[",
"property",
"]",
"}",
")",
"this",
".",
"fn",
"(",
"'sum'",
",",
"callback",
")",
".",
"call",
"(",
"this",
",",
"sum",
")",
"}"
] |
adds up property and returns sum
|
[
"adds",
"up",
"property",
"and",
"returns",
"sum"
] |
4a20309b14cee3b6eb74b24c688c5a4a5a98f879
|
https://github.com/brianleroux/lawnchair/blob/4a20309b14cee3b6eb74b24c688c5a4a5a98f879/src/plugins/aggregation.js#L18-L24
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.