repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
sony/cordova-plugin-cdp-nativebridge | dev/build/tasks/build.lower.js | lowerCSSInfo | function lowerCSSInfo(docDom) {
// read index file, and getting target ts files.
var $scripts = $(docDom).find('link[rel="stylesheet"][href]');
$scripts.each(function () {
$(this).attr('href', function (idx, path) {
return path.toLowerCase();
});
});
} | javascript | function lowerCSSInfo(docDom) {
// read index file, and getting target ts files.
var $scripts = $(docDom).find('link[rel="stylesheet"][href]');
$scripts.each(function () {
$(this).attr('href', function (idx, path) {
return path.toLowerCase();
});
});
} | [
"function",
"lowerCSSInfo",
"(",
"docDom",
")",
"{",
"var",
"$scripts",
"=",
"$",
"(",
"docDom",
")",
".",
"find",
"(",
"'link[rel=\"stylesheet\"][href]'",
")",
";",
"$scripts",
".",
"each",
"(",
"function",
"(",
")",
"{",
"$",
"(",
"this",
")",
".",
"attr",
"(",
"'href'",
",",
"function",
"(",
"idx",
",",
"path",
")",
"{",
"return",
"path",
".",
"toLowerCase",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| lower href of CSS . | [
"lower",
"href",
"of",
"CSS",
"."
]
| 6c4f0c3bb875a81395c9ce727f8f6e335a465705 | https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/build/tasks/build.lower.js#L107-L115 | train |
vega/vega-loader | src/loader.js | sanitize | function sanitize(uri, options) {
options = extend({}, this.options, options);
return new Promise(function(accept, reject) {
var result = {href: null},
isFile, hasProtocol, loadFile, base;
if (uri == null || typeof uri !== 'string') {
reject('Sanitize failure, invalid URI: ' + stringValue(uri));
return;
}
hasProtocol = protocol_re.test(uri);
// if relative url (no protocol/host), prepend baseURL
if ((base = options.baseURL) && !hasProtocol) {
// Ensure that there is a slash between the baseURL (e.g. hostname) and url
if (!startsWith(uri, '/') && base[base.length-1] !== '/') {
uri = '/' + uri;
}
uri = base + uri;
}
// should we load from file system?
loadFile = (isFile = startsWith(uri, fileProtocol))
|| options.mode === 'file'
|| options.mode !== 'http' && !hasProtocol && fs();
if (isFile) {
// strip file protocol
uri = uri.slice(fileProtocol.length);
} else if (startsWith(uri, '//')) {
if (options.defaultProtocol === 'file') {
// if is file, strip protocol and set loadFile flag
uri = uri.slice(2);
loadFile = true;
} else {
// if relative protocol (starts with '//'), prepend default protocol
uri = (options.defaultProtocol || 'http') + ':' + uri;
}
}
// set non-enumerable mode flag to indicate local file load
Object.defineProperty(result, 'localFile', {value: !!loadFile});
// set uri
result.href = uri;
// set default result target, if specified
if (options.target) {
result.target = options.target + '';
}
// return
accept(result);
});
} | javascript | function sanitize(uri, options) {
options = extend({}, this.options, options);
return new Promise(function(accept, reject) {
var result = {href: null},
isFile, hasProtocol, loadFile, base;
if (uri == null || typeof uri !== 'string') {
reject('Sanitize failure, invalid URI: ' + stringValue(uri));
return;
}
hasProtocol = protocol_re.test(uri);
// if relative url (no protocol/host), prepend baseURL
if ((base = options.baseURL) && !hasProtocol) {
// Ensure that there is a slash between the baseURL (e.g. hostname) and url
if (!startsWith(uri, '/') && base[base.length-1] !== '/') {
uri = '/' + uri;
}
uri = base + uri;
}
// should we load from file system?
loadFile = (isFile = startsWith(uri, fileProtocol))
|| options.mode === 'file'
|| options.mode !== 'http' && !hasProtocol && fs();
if (isFile) {
// strip file protocol
uri = uri.slice(fileProtocol.length);
} else if (startsWith(uri, '//')) {
if (options.defaultProtocol === 'file') {
// if is file, strip protocol and set loadFile flag
uri = uri.slice(2);
loadFile = true;
} else {
// if relative protocol (starts with '//'), prepend default protocol
uri = (options.defaultProtocol || 'http') + ':' + uri;
}
}
// set non-enumerable mode flag to indicate local file load
Object.defineProperty(result, 'localFile', {value: !!loadFile});
// set uri
result.href = uri;
// set default result target, if specified
if (options.target) {
result.target = options.target + '';
}
// return
accept(result);
});
} | [
"function",
"sanitize",
"(",
"uri",
",",
"options",
")",
"{",
"options",
"=",
"extend",
"(",
"{",
"}",
",",
"this",
".",
"options",
",",
"options",
")",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"accept",
",",
"reject",
")",
"{",
"var",
"result",
"=",
"{",
"href",
":",
"null",
"}",
",",
"isFile",
",",
"hasProtocol",
",",
"loadFile",
",",
"base",
";",
"if",
"(",
"uri",
"==",
"null",
"||",
"typeof",
"uri",
"!==",
"'string'",
")",
"{",
"reject",
"(",
"'Sanitize failure, invalid URI: '",
"+",
"stringValue",
"(",
"uri",
")",
")",
";",
"return",
";",
"}",
"hasProtocol",
"=",
"protocol_re",
".",
"test",
"(",
"uri",
")",
";",
"if",
"(",
"(",
"base",
"=",
"options",
".",
"baseURL",
")",
"&&",
"!",
"hasProtocol",
")",
"{",
"if",
"(",
"!",
"startsWith",
"(",
"uri",
",",
"'/'",
")",
"&&",
"base",
"[",
"base",
".",
"length",
"-",
"1",
"]",
"!==",
"'/'",
")",
"{",
"uri",
"=",
"'/'",
"+",
"uri",
";",
"}",
"uri",
"=",
"base",
"+",
"uri",
";",
"}",
"loadFile",
"=",
"(",
"isFile",
"=",
"startsWith",
"(",
"uri",
",",
"fileProtocol",
")",
")",
"||",
"options",
".",
"mode",
"===",
"'file'",
"||",
"options",
".",
"mode",
"!==",
"'http'",
"&&",
"!",
"hasProtocol",
"&&",
"fs",
"(",
")",
";",
"if",
"(",
"isFile",
")",
"{",
"uri",
"=",
"uri",
".",
"slice",
"(",
"fileProtocol",
".",
"length",
")",
";",
"}",
"else",
"if",
"(",
"startsWith",
"(",
"uri",
",",
"'//'",
")",
")",
"{",
"if",
"(",
"options",
".",
"defaultProtocol",
"===",
"'file'",
")",
"{",
"uri",
"=",
"uri",
".",
"slice",
"(",
"2",
")",
";",
"loadFile",
"=",
"true",
";",
"}",
"else",
"{",
"uri",
"=",
"(",
"options",
".",
"defaultProtocol",
"||",
"'http'",
")",
"+",
"':'",
"+",
"uri",
";",
"}",
"}",
"Object",
".",
"defineProperty",
"(",
"result",
",",
"'localFile'",
",",
"{",
"value",
":",
"!",
"!",
"loadFile",
"}",
")",
";",
"result",
".",
"href",
"=",
"uri",
";",
"if",
"(",
"options",
".",
"target",
")",
"{",
"result",
".",
"target",
"=",
"options",
".",
"target",
"+",
"''",
";",
"}",
"accept",
"(",
"result",
")",
";",
"}",
")",
";",
"}"
]
| URI sanitizer function.
@param {string} uri - The uri (url or filename) to sanity check.
@param {object} options - An options hash.
@return {Promise} - A promise that resolves to an object containing
sanitized uri data, or rejects it the input uri is deemed invalid.
The properties of the resolved object are assumed to be
valid attributes for an HTML 'a' tag. The sanitized uri *must* be
provided by the 'href' property of the returned object. | [
"URI",
"sanitizer",
"function",
"."
]
| 1f537ef53e3b7d6ccced0f4326ec302adc6a1832 | https://github.com/vega/vega-loader/blob/1f537ef53e3b7d6ccced0f4326ec302adc6a1832/src/loader.js#L57-L113 | train |
vega/vega-loader | src/loader.js | http | function http(url, options) {
return request(url, extend({}, this.options.http, options))
.then(function(response) {
if (!response.ok) throw response.status + '' + response.statusText;
return response.text();
});
} | javascript | function http(url, options) {
return request(url, extend({}, this.options.http, options))
.then(function(response) {
if (!response.ok) throw response.status + '' + response.statusText;
return response.text();
});
} | [
"function",
"http",
"(",
"url",
",",
"options",
")",
"{",
"return",
"request",
"(",
"url",
",",
"extend",
"(",
"{",
"}",
",",
"this",
".",
"options",
".",
"http",
",",
"options",
")",
")",
".",
"then",
"(",
"function",
"(",
"response",
")",
"{",
"if",
"(",
"!",
"response",
".",
"ok",
")",
"throw",
"response",
".",
"status",
"+",
"''",
"+",
"response",
".",
"statusText",
";",
"return",
"response",
".",
"text",
"(",
")",
";",
"}",
")",
";",
"}"
]
| HTTP request loader.
@param {string} url - The url to request.
@param {object} options - An options hash.
@return {Promise} - A promise that resolves to the file contents. | [
"HTTP",
"request",
"loader",
"."
]
| 1f537ef53e3b7d6ccced0f4326ec302adc6a1832 | https://github.com/vega/vega-loader/blob/1f537ef53e3b7d6ccced0f4326ec302adc6a1832/src/loader.js#L121-L127 | train |
creationix/brozula | cli.js | compile | function compile(path, callback) {
if (/\.luax/.test(path)) {
// Load already compiled bytecode
loadBytecode(path);
}
if (/\.lua$/.test(path)) {
luaToBytecode(path, function (err, newpath) {
if (err) return callback(err);
loadBytecode(newpath);
});
}
function loadBytecode(path) {
readFile(path, function (err, buffer) {
if (err) return callback(err);
generate(buffer);
});
}
function generate(buffer) {
var program;
try {
program = parse(buffer);
}
catch (err) {
return callback(err);
}
callback(null, program);
}
} | javascript | function compile(path, callback) {
if (/\.luax/.test(path)) {
// Load already compiled bytecode
loadBytecode(path);
}
if (/\.lua$/.test(path)) {
luaToBytecode(path, function (err, newpath) {
if (err) return callback(err);
loadBytecode(newpath);
});
}
function loadBytecode(path) {
readFile(path, function (err, buffer) {
if (err) return callback(err);
generate(buffer);
});
}
function generate(buffer) {
var program;
try {
program = parse(buffer);
}
catch (err) {
return callback(err);
}
callback(null, program);
}
} | [
"function",
"compile",
"(",
"path",
",",
"callback",
")",
"{",
"if",
"(",
"/",
"\\.luax",
"/",
".",
"test",
"(",
"path",
")",
")",
"{",
"loadBytecode",
"(",
"path",
")",
";",
"}",
"if",
"(",
"/",
"\\.lua$",
"/",
".",
"test",
"(",
"path",
")",
")",
"{",
"luaToBytecode",
"(",
"path",
",",
"function",
"(",
"err",
",",
"newpath",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"loadBytecode",
"(",
"newpath",
")",
";",
"}",
")",
";",
"}",
"function",
"loadBytecode",
"(",
"path",
")",
"{",
"readFile",
"(",
"path",
",",
"function",
"(",
"err",
",",
"buffer",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"generate",
"(",
"buffer",
")",
";",
"}",
")",
";",
"}",
"function",
"generate",
"(",
"buffer",
")",
"{",
"var",
"program",
";",
"try",
"{",
"program",
"=",
"parse",
"(",
"buffer",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"callback",
"(",
"null",
",",
"program",
")",
";",
"}",
"}"
]
| Compile a lua script to javascript source string | [
"Compile",
"a",
"lua",
"script",
"to",
"javascript",
"source",
"string"
]
| d3a0b315d23e17fd6d1c71c3e87ce3601949a8fc | https://github.com/creationix/brozula/blob/d3a0b315d23e17fd6d1c71c3e87ce3601949a8fc/cli.js#L48-L75 | train |
IonicaBizau/electronify | lib/index.js | Electronify | function Electronify(path, options) {
if (!_isReady) {
app.on("ready", () => Electronify(path, options));
return app;
}
// Defaults
var bwOpts = ul.merge(options, {
width: 800
, height: 600
, _path: path
});
_opts = bwOpts;
createWindow(_opts);
return app;
} | javascript | function Electronify(path, options) {
if (!_isReady) {
app.on("ready", () => Electronify(path, options));
return app;
}
// Defaults
var bwOpts = ul.merge(options, {
width: 800
, height: 600
, _path: path
});
_opts = bwOpts;
createWindow(_opts);
return app;
} | [
"function",
"Electronify",
"(",
"path",
",",
"options",
")",
"{",
"if",
"(",
"!",
"_isReady",
")",
"{",
"app",
".",
"on",
"(",
"\"ready\"",
",",
"(",
")",
"=>",
"Electronify",
"(",
"path",
",",
"options",
")",
")",
";",
"return",
"app",
";",
"}",
"var",
"bwOpts",
"=",
"ul",
".",
"merge",
"(",
"options",
",",
"{",
"width",
":",
"800",
",",
"height",
":",
"600",
",",
"_path",
":",
"path",
"}",
")",
";",
"_opts",
"=",
"bwOpts",
";",
"createWindow",
"(",
"_opts",
")",
";",
"return",
"app",
";",
"}"
]
| Electronify
Creates a new browser window based on Electron.
@name Electronify
@function
@param {String} path The path to the HTML file.
@param {Object} options An object representing the browser window options. It has the following defaults:
- `width` (Number): The window width (default: `800`).
- `height` (Number): The window height (default: `600`).
@return {ElectronApp} The Electron app object extended with the following fields:
- `mainWindow` (BrowserWindow): The browser window that was created. | [
"Electronify",
"Creates",
"a",
"new",
"browser",
"window",
"based",
"on",
"Electron",
"."
]
| 38678753073e24a59532e2f7a6276a702ad8496e | https://github.com/IonicaBizau/electronify/blob/38678753073e24a59532e2f7a6276a702ad8496e/lib/index.js#L49-L66 | train |
IjzerenHein/famous-map | examples/homer/example.js | _createFPS | function _createFPS(context) {
// Render FPS in right-top
var modifier = new Modifier({
align: [1, 0],
origin: [1, 0],
size: [100, 50]
});
var surface = new Surface({
content: 'fps',
classes: ['fps']
});
context.add(modifier).add(surface);
// Update every 5 ticks
Timer.every(function () {
surface.setContent(Math.round(Engine.getFPS()) + ' fps');
}, 2);
} | javascript | function _createFPS(context) {
// Render FPS in right-top
var modifier = new Modifier({
align: [1, 0],
origin: [1, 0],
size: [100, 50]
});
var surface = new Surface({
content: 'fps',
classes: ['fps']
});
context.add(modifier).add(surface);
// Update every 5 ticks
Timer.every(function () {
surface.setContent(Math.round(Engine.getFPS()) + ' fps');
}, 2);
} | [
"function",
"_createFPS",
"(",
"context",
")",
"{",
"var",
"modifier",
"=",
"new",
"Modifier",
"(",
"{",
"align",
":",
"[",
"1",
",",
"0",
"]",
",",
"origin",
":",
"[",
"1",
",",
"0",
"]",
",",
"size",
":",
"[",
"100",
",",
"50",
"]",
"}",
")",
";",
"var",
"surface",
"=",
"new",
"Surface",
"(",
"{",
"content",
":",
"'fps'",
",",
"classes",
":",
"[",
"'fps'",
"]",
"}",
")",
";",
"context",
".",
"add",
"(",
"modifier",
")",
".",
"add",
"(",
"surface",
")",
";",
"Timer",
".",
"every",
"(",
"function",
"(",
")",
"{",
"surface",
".",
"setContent",
"(",
"Math",
".",
"round",
"(",
"Engine",
".",
"getFPS",
"(",
")",
")",
"+",
"' fps'",
")",
";",
"}",
",",
"2",
")",
";",
"}"
]
| Creates the FPS-indicator in the right-top corner.
@method _createFPS
@private | [
"Creates",
"the",
"FPS",
"-",
"indicator",
"in",
"the",
"right",
"-",
"top",
"corner",
"."
]
| aa9b173dc0693503be4cab52c6c88ff3ac6315dd | https://github.com/IjzerenHein/famous-map/blob/aa9b173dc0693503be4cab52c6c88ff3ac6315dd/examples/homer/example.js#L131-L149 | train |
koajs/is-json | index.js | isJSON | function isJSON(body) {
if (!body) return false;
if ('string' == typeof body) return false;
if ('function' == typeof body.pipe) return false;
if (Buffer.isBuffer(body)) return false;
return true;
} | javascript | function isJSON(body) {
if (!body) return false;
if ('string' == typeof body) return false;
if ('function' == typeof body.pipe) return false;
if (Buffer.isBuffer(body)) return false;
return true;
} | [
"function",
"isJSON",
"(",
"body",
")",
"{",
"if",
"(",
"!",
"body",
")",
"return",
"false",
";",
"if",
"(",
"'string'",
"==",
"typeof",
"body",
")",
"return",
"false",
";",
"if",
"(",
"'function'",
"==",
"typeof",
"body",
".",
"pipe",
")",
"return",
"false",
";",
"if",
"(",
"Buffer",
".",
"isBuffer",
"(",
"body",
")",
")",
"return",
"false",
";",
"return",
"true",
";",
"}"
]
| Check if `body` should be interpreted as json. | [
"Check",
"if",
"body",
"should",
"be",
"interpreted",
"as",
"json",
"."
]
| e8e2633d37ecf7250ef1bd04b88e084d543d2a53 | https://github.com/koajs/is-json/blob/e8e2633d37ecf7250ef1bd04b88e084d543d2a53/index.js#L8-L14 | train |
IjzerenHein/famous-map | examples/photos/main.js | _createPhotoMarker | function _createPhotoMarker(photo) {
var randomAngle = (Math.PI / 180) * (10 - (Math.random() * 20));
var marker = {
mapModifier: new MapModifier({
mapView: mapView,
position: photo.loc
}),
modifier: new StateModifier({
align: [0, 0],
origin: [0.5, 0.5]
}),
content: {
modifier: new Modifier({
size: [36, 26],
transform: Transform.rotateZ(randomAngle)
}),
back: new Surface({
classes: ['photo-frame']
}),
photoModifier: new Modifier({
origin: [0.5, 0.5],
align: [0.5, 0.5],
transform: Transform.scale(0.86, 0.78, 1)
}),
photo: new ImageSurface({
classes: ['photo']
})
}
};
marker.renderable = new RenderNode(marker.mapModifier);
var renderable = marker.renderable.add(marker.modifier).add(marker.content.modifier);
renderable.add(marker.content.back);
renderable.add(marker.content.photoModifier).add(marker.content.photo);
return marker;
} | javascript | function _createPhotoMarker(photo) {
var randomAngle = (Math.PI / 180) * (10 - (Math.random() * 20));
var marker = {
mapModifier: new MapModifier({
mapView: mapView,
position: photo.loc
}),
modifier: new StateModifier({
align: [0, 0],
origin: [0.5, 0.5]
}),
content: {
modifier: new Modifier({
size: [36, 26],
transform: Transform.rotateZ(randomAngle)
}),
back: new Surface({
classes: ['photo-frame']
}),
photoModifier: new Modifier({
origin: [0.5, 0.5],
align: [0.5, 0.5],
transform: Transform.scale(0.86, 0.78, 1)
}),
photo: new ImageSurface({
classes: ['photo']
})
}
};
marker.renderable = new RenderNode(marker.mapModifier);
var renderable = marker.renderable.add(marker.modifier).add(marker.content.modifier);
renderable.add(marker.content.back);
renderable.add(marker.content.photoModifier).add(marker.content.photo);
return marker;
} | [
"function",
"_createPhotoMarker",
"(",
"photo",
")",
"{",
"var",
"randomAngle",
"=",
"(",
"Math",
".",
"PI",
"/",
"180",
")",
"*",
"(",
"10",
"-",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"20",
")",
")",
";",
"var",
"marker",
"=",
"{",
"mapModifier",
":",
"new",
"MapModifier",
"(",
"{",
"mapView",
":",
"mapView",
",",
"position",
":",
"photo",
".",
"loc",
"}",
")",
",",
"modifier",
":",
"new",
"StateModifier",
"(",
"{",
"align",
":",
"[",
"0",
",",
"0",
"]",
",",
"origin",
":",
"[",
"0.5",
",",
"0.5",
"]",
"}",
")",
",",
"content",
":",
"{",
"modifier",
":",
"new",
"Modifier",
"(",
"{",
"size",
":",
"[",
"36",
",",
"26",
"]",
",",
"transform",
":",
"Transform",
".",
"rotateZ",
"(",
"randomAngle",
")",
"}",
")",
",",
"back",
":",
"new",
"Surface",
"(",
"{",
"classes",
":",
"[",
"'photo-frame'",
"]",
"}",
")",
",",
"photoModifier",
":",
"new",
"Modifier",
"(",
"{",
"origin",
":",
"[",
"0.5",
",",
"0.5",
"]",
",",
"align",
":",
"[",
"0.5",
",",
"0.5",
"]",
",",
"transform",
":",
"Transform",
".",
"scale",
"(",
"0.86",
",",
"0.78",
",",
"1",
")",
"}",
")",
",",
"photo",
":",
"new",
"ImageSurface",
"(",
"{",
"classes",
":",
"[",
"'photo'",
"]",
"}",
")",
"}",
"}",
";",
"marker",
".",
"renderable",
"=",
"new",
"RenderNode",
"(",
"marker",
".",
"mapModifier",
")",
";",
"var",
"renderable",
"=",
"marker",
".",
"renderable",
".",
"add",
"(",
"marker",
".",
"modifier",
")",
".",
"add",
"(",
"marker",
".",
"content",
".",
"modifier",
")",
";",
"renderable",
".",
"add",
"(",
"marker",
".",
"content",
".",
"back",
")",
";",
"renderable",
".",
"add",
"(",
"marker",
".",
"content",
".",
"photoModifier",
")",
".",
"add",
"(",
"marker",
".",
"content",
".",
"photo",
")",
";",
"return",
"marker",
";",
"}"
]
| Creates a photo-marker | [
"Creates",
"a",
"photo",
"-",
"marker"
]
| aa9b173dc0693503be4cab52c6c88ff3ac6315dd | https://github.com/IjzerenHein/famous-map/blob/aa9b173dc0693503be4cab52c6c88ff3ac6315dd/examples/photos/main.js#L147-L181 | train |
IjzerenHein/famous-map | dist/famous-map.js | _elementIsChildOfMapView | function _elementIsChildOfMapView(element) {
if (element.className.indexOf('fm-mapview') >= 0) {
return true;
}
return element.parentElement ? _elementIsChildOfMapView(element.parentElement) : false;
} | javascript | function _elementIsChildOfMapView(element) {
if (element.className.indexOf('fm-mapview') >= 0) {
return true;
}
return element.parentElement ? _elementIsChildOfMapView(element.parentElement) : false;
} | [
"function",
"_elementIsChildOfMapView",
"(",
"element",
")",
"{",
"if",
"(",
"element",
".",
"className",
".",
"indexOf",
"(",
"'fm-mapview'",
")",
">=",
"0",
")",
"{",
"return",
"true",
";",
"}",
"return",
"element",
".",
"parentElement",
"?",
"_elementIsChildOfMapView",
"(",
"element",
".",
"parentElement",
")",
":",
"false",
";",
"}"
]
| Helper function that checks whether the given DOM element
is a child of a MapView. | [
"Helper",
"function",
"that",
"checks",
"whether",
"the",
"given",
"DOM",
"element",
"is",
"a",
"child",
"of",
"a",
"MapView",
"."
]
| aa9b173dc0693503be4cab52c6c88ff3ac6315dd | https://github.com/IjzerenHein/famous-map/blob/aa9b173dc0693503be4cab52c6c88ff3ac6315dd/dist/famous-map.js#L1026-L1031 | train |
LukaszWatroba/v-tabs | src/vTabs/directives/vTab.js | TabDirectiveController | function TabDirectiveController ($scope) {
var ctrl = this;
ctrl.isActive = function isActive () {
return !!$scope.isActive;
};
ctrl.activate = function activate () {
$scope.tabsCtrl.activate($scope);
};
$scope.internalControl = {
activate: ctrl.activate,
isActive: ctrl.isActive
};
} | javascript | function TabDirectiveController ($scope) {
var ctrl = this;
ctrl.isActive = function isActive () {
return !!$scope.isActive;
};
ctrl.activate = function activate () {
$scope.tabsCtrl.activate($scope);
};
$scope.internalControl = {
activate: ctrl.activate,
isActive: ctrl.isActive
};
} | [
"function",
"TabDirectiveController",
"(",
"$scope",
")",
"{",
"var",
"ctrl",
"=",
"this",
";",
"ctrl",
".",
"isActive",
"=",
"function",
"isActive",
"(",
")",
"{",
"return",
"!",
"!",
"$scope",
".",
"isActive",
";",
"}",
";",
"ctrl",
".",
"activate",
"=",
"function",
"activate",
"(",
")",
"{",
"$scope",
".",
"tabsCtrl",
".",
"activate",
"(",
"$scope",
")",
";",
"}",
";",
"$scope",
".",
"internalControl",
"=",
"{",
"activate",
":",
"ctrl",
".",
"activate",
",",
"isActive",
":",
"ctrl",
".",
"isActive",
"}",
";",
"}"
]
| vTab directive controller | [
"vTab",
"directive",
"controller"
]
| 82ce9f8f82ea3af5094b13280f0788a5ce3cd94b | https://github.com/LukaszWatroba/v-tabs/blob/82ce9f8f82ea3af5094b13280f0788a5ce3cd94b/src/vTabs/directives/vTab.js#L129-L144 | train |
Pupix/lol-esports-api | API.js | init | function init() {
require('dotenv').load();
app.port = process.env.PORT || 3002;
// Default route
app.get('/', function (req, res) {
res.json({
name: 'League of Legends eSports API',
version: "0.9.0",
author: "Robert Manolea <[email protected]>",
repository: "https://github.com/Pupix/lol-esports-api"
});
});
// Dynamic API routes
XP.forEach(routes, function (func, route) {
app.get(route, requestHandler);
});
//Error Handling
app.use(function (req, res) { res.status(404).json({error: 404, message: "Not Found"}); });
app.use(function (req, res) { res.status(500).json({error: 500, message: 'Internal Server Error'}); });
// Listening
app.listen(app.port, function () { console.log('League of Legends eSports API is listening on port ' + app.port); });
} | javascript | function init() {
require('dotenv').load();
app.port = process.env.PORT || 3002;
// Default route
app.get('/', function (req, res) {
res.json({
name: 'League of Legends eSports API',
version: "0.9.0",
author: "Robert Manolea <[email protected]>",
repository: "https://github.com/Pupix/lol-esports-api"
});
});
// Dynamic API routes
XP.forEach(routes, function (func, route) {
app.get(route, requestHandler);
});
//Error Handling
app.use(function (req, res) { res.status(404).json({error: 404, message: "Not Found"}); });
app.use(function (req, res) { res.status(500).json({error: 500, message: 'Internal Server Error'}); });
// Listening
app.listen(app.port, function () { console.log('League of Legends eSports API is listening on port ' + app.port); });
} | [
"function",
"init",
"(",
")",
"{",
"require",
"(",
"'dotenv'",
")",
".",
"load",
"(",
")",
";",
"app",
".",
"port",
"=",
"process",
".",
"env",
".",
"PORT",
"||",
"3002",
";",
"app",
".",
"get",
"(",
"'/'",
",",
"function",
"(",
"req",
",",
"res",
")",
"{",
"res",
".",
"json",
"(",
"{",
"name",
":",
"'League of Legends eSports API'",
",",
"version",
":",
"\"0.9.0\"",
",",
"author",
":",
"\"Robert Manolea <[email protected]>\"",
",",
"repository",
":",
"\"https://github.com/Pupix/lol-esports-api\"",
"}",
")",
";",
"}",
")",
";",
"XP",
".",
"forEach",
"(",
"routes",
",",
"function",
"(",
"func",
",",
"route",
")",
"{",
"app",
".",
"get",
"(",
"route",
",",
"requestHandler",
")",
";",
"}",
")",
";",
"app",
".",
"use",
"(",
"function",
"(",
"req",
",",
"res",
")",
"{",
"res",
".",
"status",
"(",
"404",
")",
".",
"json",
"(",
"{",
"error",
":",
"404",
",",
"message",
":",
"\"Not Found\"",
"}",
")",
";",
"}",
")",
";",
"app",
".",
"use",
"(",
"function",
"(",
"req",
",",
"res",
")",
"{",
"res",
".",
"status",
"(",
"500",
")",
".",
"json",
"(",
"{",
"error",
":",
"500",
",",
"message",
":",
"'Internal Server Error'",
"}",
")",
";",
"}",
")",
";",
"app",
".",
"listen",
"(",
"app",
".",
"port",
",",
"function",
"(",
")",
"{",
"console",
".",
"log",
"(",
"'League of Legends eSports API is listening on port '",
"+",
"app",
".",
"port",
")",
";",
"}",
")",
";",
"}"
]
| Main function of the API | [
"Main",
"function",
"of",
"the",
"API"
]
| 43aada008d50dfcf1a3b1a27c1c1054348ddd03e | https://github.com/Pupix/lol-esports-api/blob/43aada008d50dfcf1a3b1a27c1c1054348ddd03e/API.js#L137-L164 | train |
LukaszWatroba/v-tabs | src/vTabs/directives/vPages.js | vPagesDirectiveController | function vPagesDirectiveController ($scope) {
var ctrl = this;
$scope.pages = [];
ctrl.getPagesId = function getPagesId () {
return $scope.id;
};
ctrl.getPageByIndex = function (index) {
return $scope.pages[index];
};
ctrl.getPageIndex = function (page) {
return $scope.pages.indexOf(page);
};
ctrl.getPageIndexById = function getPageIndexById (id) {
var length = $scope.pages.length,
index = null;
for (var i = 0; i < length; i++) {
var iteratedPage = $scope.pages[i];
if (iteratedPage.id && iteratedPage.id === id) { index = i; }
}
return index;
};
ctrl.addPage = function (page) {
$scope.pages.push(page);
if ($scope.activeIndex === ctrl.getPageIndex(page)) {
ctrl.activate(page);
}
};
ctrl.next = function () {
var newActiveIndex = $scope.activeIndex + 1;
if (newActiveIndex > $scope.pages.length - 1) {
newActiveIndex = 0;
}
$scope.activeIndex = newActiveIndex;
};
ctrl.previous = function () {
var newActiveIndex = $scope.activeIndex - 1;
if (newActiveIndex < 0) {
newActiveIndex = $scope.pages.length - 1;
}
$scope.activeIndex = newActiveIndex;
};
ctrl.activate = function (pageToActivate) {
if (!pageToActivate) { return; }
if (!pageToActivate.isActive) {
pageToActivate.isActive = true;
angular.forEach($scope.pages, function (iteratedPage) {
if (iteratedPage !== pageToActivate && iteratedPage.isActive) {
iteratedPage.isActive = false;
}
});
}
};
$scope.$watch('activeIndex', function (newValue, oldValue) {
if (newValue === oldValue) { return; }
var pageToActivate = ctrl.getPageByIndex(newValue);
if (pageToActivate.isDisabled) {
$scope.activeIndex = (angular.isDefined(oldValue)) ? oldValue : 0;
return false;
}
ctrl.activate(pageToActivate);
});
// API
$scope.internalControl = {
next: function () {
ctrl.next();
},
previous: function () {
ctrl.previous();
},
activate: function (indexOrId) {
if (angular.isString(indexOrId)) {
$scope.activeIndex = ctrl.getPageIndexById(indexOrId);
} else {
$scope.activeIndex = indexOrId;
}
}
};
} | javascript | function vPagesDirectiveController ($scope) {
var ctrl = this;
$scope.pages = [];
ctrl.getPagesId = function getPagesId () {
return $scope.id;
};
ctrl.getPageByIndex = function (index) {
return $scope.pages[index];
};
ctrl.getPageIndex = function (page) {
return $scope.pages.indexOf(page);
};
ctrl.getPageIndexById = function getPageIndexById (id) {
var length = $scope.pages.length,
index = null;
for (var i = 0; i < length; i++) {
var iteratedPage = $scope.pages[i];
if (iteratedPage.id && iteratedPage.id === id) { index = i; }
}
return index;
};
ctrl.addPage = function (page) {
$scope.pages.push(page);
if ($scope.activeIndex === ctrl.getPageIndex(page)) {
ctrl.activate(page);
}
};
ctrl.next = function () {
var newActiveIndex = $scope.activeIndex + 1;
if (newActiveIndex > $scope.pages.length - 1) {
newActiveIndex = 0;
}
$scope.activeIndex = newActiveIndex;
};
ctrl.previous = function () {
var newActiveIndex = $scope.activeIndex - 1;
if (newActiveIndex < 0) {
newActiveIndex = $scope.pages.length - 1;
}
$scope.activeIndex = newActiveIndex;
};
ctrl.activate = function (pageToActivate) {
if (!pageToActivate) { return; }
if (!pageToActivate.isActive) {
pageToActivate.isActive = true;
angular.forEach($scope.pages, function (iteratedPage) {
if (iteratedPage !== pageToActivate && iteratedPage.isActive) {
iteratedPage.isActive = false;
}
});
}
};
$scope.$watch('activeIndex', function (newValue, oldValue) {
if (newValue === oldValue) { return; }
var pageToActivate = ctrl.getPageByIndex(newValue);
if (pageToActivate.isDisabled) {
$scope.activeIndex = (angular.isDefined(oldValue)) ? oldValue : 0;
return false;
}
ctrl.activate(pageToActivate);
});
// API
$scope.internalControl = {
next: function () {
ctrl.next();
},
previous: function () {
ctrl.previous();
},
activate: function (indexOrId) {
if (angular.isString(indexOrId)) {
$scope.activeIndex = ctrl.getPageIndexById(indexOrId);
} else {
$scope.activeIndex = indexOrId;
}
}
};
} | [
"function",
"vPagesDirectiveController",
"(",
"$scope",
")",
"{",
"var",
"ctrl",
"=",
"this",
";",
"$scope",
".",
"pages",
"=",
"[",
"]",
";",
"ctrl",
".",
"getPagesId",
"=",
"function",
"getPagesId",
"(",
")",
"{",
"return",
"$scope",
".",
"id",
";",
"}",
";",
"ctrl",
".",
"getPageByIndex",
"=",
"function",
"(",
"index",
")",
"{",
"return",
"$scope",
".",
"pages",
"[",
"index",
"]",
";",
"}",
";",
"ctrl",
".",
"getPageIndex",
"=",
"function",
"(",
"page",
")",
"{",
"return",
"$scope",
".",
"pages",
".",
"indexOf",
"(",
"page",
")",
";",
"}",
";",
"ctrl",
".",
"getPageIndexById",
"=",
"function",
"getPageIndexById",
"(",
"id",
")",
"{",
"var",
"length",
"=",
"$scope",
".",
"pages",
".",
"length",
",",
"index",
"=",
"null",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"var",
"iteratedPage",
"=",
"$scope",
".",
"pages",
"[",
"i",
"]",
";",
"if",
"(",
"iteratedPage",
".",
"id",
"&&",
"iteratedPage",
".",
"id",
"===",
"id",
")",
"{",
"index",
"=",
"i",
";",
"}",
"}",
"return",
"index",
";",
"}",
";",
"ctrl",
".",
"addPage",
"=",
"function",
"(",
"page",
")",
"{",
"$scope",
".",
"pages",
".",
"push",
"(",
"page",
")",
";",
"if",
"(",
"$scope",
".",
"activeIndex",
"===",
"ctrl",
".",
"getPageIndex",
"(",
"page",
")",
")",
"{",
"ctrl",
".",
"activate",
"(",
"page",
")",
";",
"}",
"}",
";",
"ctrl",
".",
"next",
"=",
"function",
"(",
")",
"{",
"var",
"newActiveIndex",
"=",
"$scope",
".",
"activeIndex",
"+",
"1",
";",
"if",
"(",
"newActiveIndex",
">",
"$scope",
".",
"pages",
".",
"length",
"-",
"1",
")",
"{",
"newActiveIndex",
"=",
"0",
";",
"}",
"$scope",
".",
"activeIndex",
"=",
"newActiveIndex",
";",
"}",
";",
"ctrl",
".",
"previous",
"=",
"function",
"(",
")",
"{",
"var",
"newActiveIndex",
"=",
"$scope",
".",
"activeIndex",
"-",
"1",
";",
"if",
"(",
"newActiveIndex",
"<",
"0",
")",
"{",
"newActiveIndex",
"=",
"$scope",
".",
"pages",
".",
"length",
"-",
"1",
";",
"}",
"$scope",
".",
"activeIndex",
"=",
"newActiveIndex",
";",
"}",
";",
"ctrl",
".",
"activate",
"=",
"function",
"(",
"pageToActivate",
")",
"{",
"if",
"(",
"!",
"pageToActivate",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"pageToActivate",
".",
"isActive",
")",
"{",
"pageToActivate",
".",
"isActive",
"=",
"true",
";",
"angular",
".",
"forEach",
"(",
"$scope",
".",
"pages",
",",
"function",
"(",
"iteratedPage",
")",
"{",
"if",
"(",
"iteratedPage",
"!==",
"pageToActivate",
"&&",
"iteratedPage",
".",
"isActive",
")",
"{",
"iteratedPage",
".",
"isActive",
"=",
"false",
";",
"}",
"}",
")",
";",
"}",
"}",
";",
"$scope",
".",
"$watch",
"(",
"'activeIndex'",
",",
"function",
"(",
"newValue",
",",
"oldValue",
")",
"{",
"if",
"(",
"newValue",
"===",
"oldValue",
")",
"{",
"return",
";",
"}",
"var",
"pageToActivate",
"=",
"ctrl",
".",
"getPageByIndex",
"(",
"newValue",
")",
";",
"if",
"(",
"pageToActivate",
".",
"isDisabled",
")",
"{",
"$scope",
".",
"activeIndex",
"=",
"(",
"angular",
".",
"isDefined",
"(",
"oldValue",
")",
")",
"?",
"oldValue",
":",
"0",
";",
"return",
"false",
";",
"}",
"ctrl",
".",
"activate",
"(",
"pageToActivate",
")",
";",
"}",
")",
";",
"$scope",
".",
"internalControl",
"=",
"{",
"next",
":",
"function",
"(",
")",
"{",
"ctrl",
".",
"next",
"(",
")",
";",
"}",
",",
"previous",
":",
"function",
"(",
")",
"{",
"ctrl",
".",
"previous",
"(",
")",
";",
"}",
",",
"activate",
":",
"function",
"(",
"indexOrId",
")",
"{",
"if",
"(",
"angular",
".",
"isString",
"(",
"indexOrId",
")",
")",
"{",
"$scope",
".",
"activeIndex",
"=",
"ctrl",
".",
"getPageIndexById",
"(",
"indexOrId",
")",
";",
"}",
"else",
"{",
"$scope",
".",
"activeIndex",
"=",
"indexOrId",
";",
"}",
"}",
"}",
";",
"}"
]
| vPages directive controller | [
"vPages",
"directive",
"controller"
]
| 82ce9f8f82ea3af5094b13280f0788a5ce3cd94b | https://github.com/LukaszWatroba/v-tabs/blob/82ce9f8f82ea3af5094b13280f0788a5ce3cd94b/src/vTabs/directives/vPages.js#L59-L156 | train |
ancasicolica/node-wifi-scanner | lib/netsh.js | parseOutput | function parseOutput(str, callback) {
var blocks = str.split('\n\n');
var wifis = [];
var err = null;
try {
if (blocks.length < 2) {
// 2nd try, with \r\n
blocks = str.split('\r\n\r\n')
}
if (!blocks || blocks.length === 1) {
// No WiFis found
return callback(null, []);
}
// Each block has the same structure, while some parts might be available and others
// not. A sample structure:
// SSID 1 : AP-Test1
// Network type : Infrastructure
// Authentication : WPA2-Personal
// Encryption : CCMP
// BSSID 1 : 00:aa:f2:77:a5:53
// Signal : 46%
// Radio type : 802.11n
// Channel : 6
// Basic rates (MBit/s) : 1 2 5.5 11
// Other rates (MBit/s) : 6 9 12 18 24 36 48 54
for (var i = 1, l = blocks.length; i < l; i++) {
var network = {};
var lines = blocks[i].split('\n');
var regexChannel = /[a-zA-Z0-9()\s]+:[\s]*[0-9]+$/g;
if (!lines || lines.length < 2) {
continue;
}
// First line is always the SSID (which can be empty)
var ssid = lines[0].substring(lines[0].indexOf(':') + 1).trim();
for (var t = 1, n = lines.length; t < n; t++) {
if (lines[t].split(':').length === 7) {
// This is the mac address, use this one as trigger for a new network
if (network.mac) {
wifis.push(network);
}
network = {
ssid: ssid,
mac : lines[t].substring(lines[t].indexOf(':') + 1).trim()
};
}
else if (lines[t].indexOf('%') > 0) {
// Network signal strength, identified by '%'
var level = parseInt(lines[t].split(':')[1].split('%')[0].trim(), 10);
network.rssi = (level / 2) - 100;
}
else if (!network.channel) {
// A tricky one: the channel is the first one having just ONE number. Set only
// if the channel is not already set ("Basic Rates" can be a single number also)
if (regexChannel.exec(lines[t].trim())) {
network.channel = parseInt(lines[t].split(':')[1].trim(), 10);
}
}
}
if (network) {
wifis.push(network);
}
}
}
catch (ex) {
err = ex;
}
callback(err, wifis);
} | javascript | function parseOutput(str, callback) {
var blocks = str.split('\n\n');
var wifis = [];
var err = null;
try {
if (blocks.length < 2) {
// 2nd try, with \r\n
blocks = str.split('\r\n\r\n')
}
if (!blocks || blocks.length === 1) {
// No WiFis found
return callback(null, []);
}
// Each block has the same structure, while some parts might be available and others
// not. A sample structure:
// SSID 1 : AP-Test1
// Network type : Infrastructure
// Authentication : WPA2-Personal
// Encryption : CCMP
// BSSID 1 : 00:aa:f2:77:a5:53
// Signal : 46%
// Radio type : 802.11n
// Channel : 6
// Basic rates (MBit/s) : 1 2 5.5 11
// Other rates (MBit/s) : 6 9 12 18 24 36 48 54
for (var i = 1, l = blocks.length; i < l; i++) {
var network = {};
var lines = blocks[i].split('\n');
var regexChannel = /[a-zA-Z0-9()\s]+:[\s]*[0-9]+$/g;
if (!lines || lines.length < 2) {
continue;
}
// First line is always the SSID (which can be empty)
var ssid = lines[0].substring(lines[0].indexOf(':') + 1).trim();
for (var t = 1, n = lines.length; t < n; t++) {
if (lines[t].split(':').length === 7) {
// This is the mac address, use this one as trigger for a new network
if (network.mac) {
wifis.push(network);
}
network = {
ssid: ssid,
mac : lines[t].substring(lines[t].indexOf(':') + 1).trim()
};
}
else if (lines[t].indexOf('%') > 0) {
// Network signal strength, identified by '%'
var level = parseInt(lines[t].split(':')[1].split('%')[0].trim(), 10);
network.rssi = (level / 2) - 100;
}
else if (!network.channel) {
// A tricky one: the channel is the first one having just ONE number. Set only
// if the channel is not already set ("Basic Rates" can be a single number also)
if (regexChannel.exec(lines[t].trim())) {
network.channel = parseInt(lines[t].split(':')[1].trim(), 10);
}
}
}
if (network) {
wifis.push(network);
}
}
}
catch (ex) {
err = ex;
}
callback(err, wifis);
} | [
"function",
"parseOutput",
"(",
"str",
",",
"callback",
")",
"{",
"var",
"blocks",
"=",
"str",
".",
"split",
"(",
"'\\n\\n'",
")",
";",
"\\n",
"\\n",
"var",
"wifis",
"=",
"[",
"]",
";",
"var",
"err",
"=",
"null",
";",
"}"
]
| Parsing netnsh output. Unfortunately netsh supplies the network information
in the language of the operating system. Translating the terms into every
language supplied is not possible, therefore this implementation follows
an approach of analyzing the structure of the output | [
"Parsing",
"netnsh",
"output",
".",
"Unfortunately",
"netsh",
"supplies",
"the",
"network",
"information",
"in",
"the",
"language",
"of",
"the",
"operating",
"system",
".",
"Translating",
"the",
"terms",
"into",
"every",
"language",
"supplied",
"is",
"not",
"possible",
"therefore",
"this",
"implementation",
"follows",
"an",
"approach",
"of",
"analyzing",
"the",
"structure",
"of",
"the",
"output"
]
| bc61dc2f02c07169bfd0b43e9fbc9230ab316c85 | https://github.com/ancasicolica/node-wifi-scanner/blob/bc61dc2f02c07169bfd0b43e9fbc9230ab316c85/lib/netsh.js#L17-L88 | train |
LukaszWatroba/v-tabs | src/vTabs/directives/vPage.js | PageDirectiveController | function PageDirectiveController ($scope) {
var ctrl = this;
ctrl.isActive = function isActive () {
return !!$scope.isActive;
};
ctrl.activate = function activate () {
$scope.pagesCtrl.activate($scope);
};
$scope.internalControl = {
activate: ctrl.activate,
isActive: ctrl.isActive
};
} | javascript | function PageDirectiveController ($scope) {
var ctrl = this;
ctrl.isActive = function isActive () {
return !!$scope.isActive;
};
ctrl.activate = function activate () {
$scope.pagesCtrl.activate($scope);
};
$scope.internalControl = {
activate: ctrl.activate,
isActive: ctrl.isActive
};
} | [
"function",
"PageDirectiveController",
"(",
"$scope",
")",
"{",
"var",
"ctrl",
"=",
"this",
";",
"ctrl",
".",
"isActive",
"=",
"function",
"isActive",
"(",
")",
"{",
"return",
"!",
"!",
"$scope",
".",
"isActive",
";",
"}",
";",
"ctrl",
".",
"activate",
"=",
"function",
"activate",
"(",
")",
"{",
"$scope",
".",
"pagesCtrl",
".",
"activate",
"(",
"$scope",
")",
";",
"}",
";",
"$scope",
".",
"internalControl",
"=",
"{",
"activate",
":",
"ctrl",
".",
"activate",
",",
"isActive",
":",
"ctrl",
".",
"isActive",
"}",
";",
"}"
]
| vPage directive controller | [
"vPage",
"directive",
"controller"
]
| 82ce9f8f82ea3af5094b13280f0788a5ce3cd94b | https://github.com/LukaszWatroba/v-tabs/blob/82ce9f8f82ea3af5094b13280f0788a5ce3cd94b/src/vTabs/directives/vPage.js#L62-L77 | train |
ancasicolica/node-wifi-scanner | index.js | initTools | function initTools(callback) {
// When a command is not found, an error is issued and async would finish. Therefore we pack
// the error into the result and check it later on.
async.parallel([
function (cb) {
exec(airport.detector, function (err) {
cb(null, {err: err, scanner: airport}
)
}
);
},
function (cb) {
exec(iwlist.detector, function (err) {
cb(null, {err: err, scanner: iwlist}
)
}
);
},
function (cb) {
exec(netsh.detector, function (err) {
cb(null, {err: err, scanner: netsh}
)
}
);
}
],
function (err, results) {
var res = _.find(results,
function (f) {
return !f.err
});
if (res) {
return callback(null, res.scanner);
}
callback(new Error('No scanner found'));
}
);
} | javascript | function initTools(callback) {
// When a command is not found, an error is issued and async would finish. Therefore we pack
// the error into the result and check it later on.
async.parallel([
function (cb) {
exec(airport.detector, function (err) {
cb(null, {err: err, scanner: airport}
)
}
);
},
function (cb) {
exec(iwlist.detector, function (err) {
cb(null, {err: err, scanner: iwlist}
)
}
);
},
function (cb) {
exec(netsh.detector, function (err) {
cb(null, {err: err, scanner: netsh}
)
}
);
}
],
function (err, results) {
var res = _.find(results,
function (f) {
return !f.err
});
if (res) {
return callback(null, res.scanner);
}
callback(new Error('No scanner found'));
}
);
} | [
"function",
"initTools",
"(",
"callback",
")",
"{",
"async",
".",
"parallel",
"(",
"[",
"function",
"(",
"cb",
")",
"{",
"exec",
"(",
"airport",
".",
"detector",
",",
"function",
"(",
"err",
")",
"{",
"cb",
"(",
"null",
",",
"{",
"err",
":",
"err",
",",
"scanner",
":",
"airport",
"}",
")",
"}",
")",
";",
"}",
",",
"function",
"(",
"cb",
")",
"{",
"exec",
"(",
"iwlist",
".",
"detector",
",",
"function",
"(",
"err",
")",
"{",
"cb",
"(",
"null",
",",
"{",
"err",
":",
"err",
",",
"scanner",
":",
"iwlist",
"}",
")",
"}",
")",
";",
"}",
",",
"function",
"(",
"cb",
")",
"{",
"exec",
"(",
"netsh",
".",
"detector",
",",
"function",
"(",
"err",
")",
"{",
"cb",
"(",
"null",
",",
"{",
"err",
":",
"err",
",",
"scanner",
":",
"netsh",
"}",
")",
"}",
")",
";",
"}",
"]",
",",
"function",
"(",
"err",
",",
"results",
")",
"{",
"var",
"res",
"=",
"_",
".",
"find",
"(",
"results",
",",
"function",
"(",
"f",
")",
"{",
"return",
"!",
"f",
".",
"err",
"}",
")",
";",
"if",
"(",
"res",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"res",
".",
"scanner",
")",
";",
"}",
"callback",
"(",
"new",
"Error",
"(",
"'No scanner found'",
")",
")",
";",
"}",
")",
";",
"}"
]
| Initializing the tools | [
"Initializing",
"the",
"tools"
]
| bc61dc2f02c07169bfd0b43e9fbc9230ab316c85 | https://github.com/ancasicolica/node-wifi-scanner/blob/bc61dc2f02c07169bfd0b43e9fbc9230ab316c85/index.js#L17-L56 | train |
ancasicolica/node-wifi-scanner | index.js | scanNetworks | function scanNetworks(callback) {
exec(scanner.cmdLine, function (err, stdout) {
if (err) {
callback(err, null);
return;
}
scanner.parseOutput(stdout, callback);
});
} | javascript | function scanNetworks(callback) {
exec(scanner.cmdLine, function (err, stdout) {
if (err) {
callback(err, null);
return;
}
scanner.parseOutput(stdout, callback);
});
} | [
"function",
"scanNetworks",
"(",
"callback",
")",
"{",
"exec",
"(",
"scanner",
".",
"cmdLine",
",",
"function",
"(",
"err",
",",
"stdout",
")",
"{",
"if",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
",",
"null",
")",
";",
"return",
";",
"}",
"scanner",
".",
"parseOutput",
"(",
"stdout",
",",
"callback",
")",
";",
"}",
")",
";",
"}"
]
| Scan the networks with the scanner detected before
@param callback | [
"Scan",
"the",
"networks",
"with",
"the",
"scanner",
"detected",
"before"
]
| bc61dc2f02c07169bfd0b43e9fbc9230ab316c85 | https://github.com/ancasicolica/node-wifi-scanner/blob/bc61dc2f02c07169bfd0b43e9fbc9230ab316c85/index.js#L62-L70 | train |
ancasicolica/node-wifi-scanner | index.js | function (callback) {
if (!scanner) {
initTools(function (err, s) {
if (err) {
return callback(err);
}
scanner = s;
scanNetworks(callback);
});
return;
}
scanNetworks(callback);
} | javascript | function (callback) {
if (!scanner) {
initTools(function (err, s) {
if (err) {
return callback(err);
}
scanner = s;
scanNetworks(callback);
});
return;
}
scanNetworks(callback);
} | [
"function",
"(",
"callback",
")",
"{",
"if",
"(",
"!",
"scanner",
")",
"{",
"initTools",
"(",
"function",
"(",
"err",
",",
"s",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"scanner",
"=",
"s",
";",
"scanNetworks",
"(",
"callback",
")",
";",
"}",
")",
";",
"return",
";",
"}",
"scanNetworks",
"(",
"callback",
")",
";",
"}"
]
| Scan for wifis
@param callback | [
"Scan",
"for",
"wifis"
]
| bc61dc2f02c07169bfd0b43e9fbc9230ab316c85 | https://github.com/ancasicolica/node-wifi-scanner/blob/bc61dc2f02c07169bfd0b43e9fbc9230ab316c85/index.js#L77-L89 | train |
|
steveush/foodoc | src/static/js/table-of-contents.js | TOC | function TOC(enabled){
if (!(this instanceof TOC)) return new TOC(enabled);
this.enabled = !!enabled;
this._items = {all:[],h1:[],h2:[],h3:[],h4:[]};
this._last = {h1:null,h2:null,h3:null,h4:null};
} | javascript | function TOC(enabled){
if (!(this instanceof TOC)) return new TOC(enabled);
this.enabled = !!enabled;
this._items = {all:[],h1:[],h2:[],h3:[],h4:[]};
this._last = {h1:null,h2:null,h3:null,h4:null};
} | [
"function",
"TOC",
"(",
"enabled",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"TOC",
")",
")",
"return",
"new",
"TOC",
"(",
"enabled",
")",
";",
"this",
".",
"enabled",
"=",
"!",
"!",
"enabled",
";",
"this",
".",
"_items",
"=",
"{",
"all",
":",
"[",
"]",
",",
"h1",
":",
"[",
"]",
",",
"h2",
":",
"[",
"]",
",",
"h3",
":",
"[",
"]",
",",
"h4",
":",
"[",
"]",
"}",
";",
"this",
".",
"_last",
"=",
"{",
"h1",
":",
"null",
",",
"h2",
":",
"null",
",",
"h3",
":",
"null",
",",
"h4",
":",
"null",
"}",
";",
"}"
]
| While this is called `TOC` it actually performs a few functions related to anchors and scrolling.
1. It parses the page for all `H1`, `H2`, `H3` and `H4` elements and ensures they have an id, using either the existing one or generating one by slugifying the headers' text.
2. It adds an `A` element with a link icon that appears on hover to all parsed headers that when clicked simply links back to the current symbol allowing a user to easily get a link to specific documentation.
3. It builds the Table of Contents from the parsed headers and provides the underlying logic for that component.
4. It listens to the `hashchange` event and hijacks all anchor element clicks in the page to ensure when navigating the browser correctly offsets itself.
When disabled by setting the `showTableOfContents` option, the above steps 1, 2 and 4 are still performed to ensure anchor clicks are handled correctly.
@summary Used to parse the page for headers to build the Table of Contents.
@constructor TOC
@param {boolean} enabled - Whether or not the Table of Contents is enabled for this doclet.
@example {@caption The following shows the ready callback that is registered when this script is loaded. The `DOCLET_TOC_ENABLED` variable is set by the template on `window` object.}
$(function(){
var toc = new TOC(DOCLET_TOC_ENABLED);
toc.parse();
if (toc.enabled && toc.any()) {
toc.init();
} else {
toc.fixColumns();
}
toc.offsetScroll(60);
}); | [
"While",
"this",
"is",
"called",
"TOC",
"it",
"actually",
"performs",
"a",
"few",
"functions",
"related",
"to",
"anchors",
"and",
"scrolling",
"."
]
| b7cc2cd1fbbeaeb08e12f74352399a5371d29f7e | https://github.com/steveush/foodoc/blob/b7cc2cd1fbbeaeb08e12f74352399a5371d29f7e/src/static/js/table-of-contents.js#L29-L34 | train |
timshadel/passport-oauth2-public-client | lib/passport-oauth2-public-client/strategy.js | Strategy | function Strategy(options, verifyPublic) {
if (typeof options == 'function') {
verifyPublic = options;
options = {};
}
if (!verifyPublic) throw new Error('OAuth 2.0 public client strategy requires a verifyPublic function');
passport.Strategy.call(this);
this.name = 'oauth2-public-client';
this._verifyPublic = verifyPublic;
this._passReqToCallback = options.passReqToCallback;
} | javascript | function Strategy(options, verifyPublic) {
if (typeof options == 'function') {
verifyPublic = options;
options = {};
}
if (!verifyPublic) throw new Error('OAuth 2.0 public client strategy requires a verifyPublic function');
passport.Strategy.call(this);
this.name = 'oauth2-public-client';
this._verifyPublic = verifyPublic;
this._passReqToCallback = options.passReqToCallback;
} | [
"function",
"Strategy",
"(",
"options",
",",
"verifyPublic",
")",
"{",
"if",
"(",
"typeof",
"options",
"==",
"'function'",
")",
"{",
"verifyPublic",
"=",
"options",
";",
"options",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"!",
"verifyPublic",
")",
"throw",
"new",
"Error",
"(",
"'OAuth 2.0 public client strategy requires a verifyPublic function'",
")",
";",
"passport",
".",
"Strategy",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"name",
"=",
"'oauth2-public-client'",
";",
"this",
".",
"_verifyPublic",
"=",
"verifyPublic",
";",
"this",
".",
"_passReqToCallback",
"=",
"options",
".",
"passReqToCallback",
";",
"}"
]
| `PublicClientStrategy` constructor.
@api protected | [
"PublicClientStrategy",
"constructor",
"."
]
| aeb71104b80e74bb18516acb18b2401e5e0b19ef | https://github.com/timshadel/passport-oauth2-public-client/blob/aeb71104b80e74bb18516acb18b2401e5e0b19ef/lib/passport-oauth2-public-client/strategy.js#L13-L24 | train |
amper5and/voice.js | examples/tokens.js | newToken | function newToken(){ // check if the client has all the tokens
var allRetrieved = true;
var tokens = client.getTokens();
['auth', 'gvx', 'rnr'].forEach(function(type){
if(!tokens.hasOwnProperty(type)){
allRetrieved = false;
}
});
if(allRetrieved){ // save tokens once all have been retrieved
fs.writeFileSync('./tokens.json', JSON.stringify(tokens));
console.log('\n\nALL TOKENS SAVED TO tokens.json')
}
} | javascript | function newToken(){ // check if the client has all the tokens
var allRetrieved = true;
var tokens = client.getTokens();
['auth', 'gvx', 'rnr'].forEach(function(type){
if(!tokens.hasOwnProperty(type)){
allRetrieved = false;
}
});
if(allRetrieved){ // save tokens once all have been retrieved
fs.writeFileSync('./tokens.json', JSON.stringify(tokens));
console.log('\n\nALL TOKENS SAVED TO tokens.json')
}
} | [
"function",
"newToken",
"(",
")",
"{",
"var",
"allRetrieved",
"=",
"true",
";",
"var",
"tokens",
"=",
"client",
".",
"getTokens",
"(",
")",
";",
"[",
"'auth'",
",",
"'gvx'",
",",
"'rnr'",
"]",
".",
"forEach",
"(",
"function",
"(",
"type",
")",
"{",
"if",
"(",
"!",
"tokens",
".",
"hasOwnProperty",
"(",
"type",
")",
")",
"{",
"allRetrieved",
"=",
"false",
";",
"}",
"}",
")",
";",
"if",
"(",
"allRetrieved",
")",
"{",
"fs",
".",
"writeFileSync",
"(",
"'./tokens.json'",
",",
"JSON",
".",
"stringify",
"(",
"tokens",
")",
")",
";",
"console",
".",
"log",
"(",
"'\\n\\nALL TOKENS SAVED TO tokens.json'",
")",
"}",
"}"
]
| This fn will monitor token events until all 3 tokens are retrieved. When all three are retrieved, they will be saved to tokens.json | [
"This",
"fn",
"will",
"monitor",
"token",
"events",
"until",
"all",
"3",
"tokens",
"are",
"retrieved",
".",
"When",
"all",
"three",
"are",
"retrieved",
"they",
"will",
"be",
"saved",
"to",
"tokens",
".",
"json"
]
| 362992e3be792ac4c3a948d8b445df2aea19d926 | https://github.com/amper5and/voice.js/blob/362992e3be792ac4c3a948d8b445df2aea19d926/examples/tokens.js#L15-L29 | train |
olalonde/eslint-import-resolver-babel-root-import | src/index.js | getConfigFromBabel | function getConfigFromBabel(start, babelrc = '.babelrc') {
if (start === '/') return [];
const packageJSONPath = path.join(start, 'package.json');
const packageJSON = require(packageJSONPath);
const babelConfig = packageJSON.babel;
if (babelConfig) {
const pluginConfig = babelConfig.plugins.find(p => (
p[0] === 'babel-root-import'
));
process.chdir(path.dirname(packageJSONPath));
return pluginConfig[1];
}
const babelrcPath = path.join(start, babelrc);
if (fs.existsSync(babelrcPath)) {
const babelrcJson = JSON5.parse(fs.readFileSync(babelrcPath, 'utf8'));
if (babelrcJson && Array.isArray(babelrcJson.plugins)) {
const pluginConfig = babelrcJson.plugins.find(p => (
p[0] === 'babel-plugin-root-import'
));
// The src path inside babelrc are from the root so we have
// to change the working directory for the same directory
// to make the mapping to work properly
process.chdir(path.dirname(babelrcPath));
return pluginConfig[1];
}
}
return getConfigFromBabel(path.dirname(start));
} | javascript | function getConfigFromBabel(start, babelrc = '.babelrc') {
if (start === '/') return [];
const packageJSONPath = path.join(start, 'package.json');
const packageJSON = require(packageJSONPath);
const babelConfig = packageJSON.babel;
if (babelConfig) {
const pluginConfig = babelConfig.plugins.find(p => (
p[0] === 'babel-root-import'
));
process.chdir(path.dirname(packageJSONPath));
return pluginConfig[1];
}
const babelrcPath = path.join(start, babelrc);
if (fs.existsSync(babelrcPath)) {
const babelrcJson = JSON5.parse(fs.readFileSync(babelrcPath, 'utf8'));
if (babelrcJson && Array.isArray(babelrcJson.plugins)) {
const pluginConfig = babelrcJson.plugins.find(p => (
p[0] === 'babel-plugin-root-import'
));
// The src path inside babelrc are from the root so we have
// to change the working directory for the same directory
// to make the mapping to work properly
process.chdir(path.dirname(babelrcPath));
return pluginConfig[1];
}
}
return getConfigFromBabel(path.dirname(start));
} | [
"function",
"getConfigFromBabel",
"(",
"start",
",",
"babelrc",
"=",
"'.babelrc'",
")",
"{",
"if",
"(",
"start",
"===",
"'/'",
")",
"return",
"[",
"]",
";",
"const",
"packageJSONPath",
"=",
"path",
".",
"join",
"(",
"start",
",",
"'package.json'",
")",
";",
"const",
"packageJSON",
"=",
"require",
"(",
"packageJSONPath",
")",
";",
"const",
"babelConfig",
"=",
"packageJSON",
".",
"babel",
";",
"if",
"(",
"babelConfig",
")",
"{",
"const",
"pluginConfig",
"=",
"babelConfig",
".",
"plugins",
".",
"find",
"(",
"p",
"=>",
"(",
"p",
"[",
"0",
"]",
"===",
"'babel-root-import'",
")",
")",
";",
"process",
".",
"chdir",
"(",
"path",
".",
"dirname",
"(",
"packageJSONPath",
")",
")",
";",
"return",
"pluginConfig",
"[",
"1",
"]",
";",
"}",
"const",
"babelrcPath",
"=",
"path",
".",
"join",
"(",
"start",
",",
"babelrc",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"babelrcPath",
")",
")",
"{",
"const",
"babelrcJson",
"=",
"JSON5",
".",
"parse",
"(",
"fs",
".",
"readFileSync",
"(",
"babelrcPath",
",",
"'utf8'",
")",
")",
";",
"if",
"(",
"babelrcJson",
"&&",
"Array",
".",
"isArray",
"(",
"babelrcJson",
".",
"plugins",
")",
")",
"{",
"const",
"pluginConfig",
"=",
"babelrcJson",
".",
"plugins",
".",
"find",
"(",
"p",
"=>",
"(",
"p",
"[",
"0",
"]",
"===",
"'babel-plugin-root-import'",
")",
")",
";",
"process",
".",
"chdir",
"(",
"path",
".",
"dirname",
"(",
"babelrcPath",
")",
")",
";",
"return",
"pluginConfig",
"[",
"1",
"]",
";",
"}",
"}",
"return",
"getConfigFromBabel",
"(",
"path",
".",
"dirname",
"(",
"start",
")",
")",
";",
"}"
]
| returns the root import config as an object | [
"returns",
"the",
"root",
"import",
"config",
"as",
"an",
"object"
]
| 86c7a0358489c89519df63fb69b5b7b4cd849c7a | https://github.com/olalonde/eslint-import-resolver-babel-root-import/blob/86c7a0358489c89519df63fb69b5b7b4cd849c7a/src/index.js#L28-L57 | train |
FauzanKhan/angular-popover | src/js/ngPopover.js | function($scope, element, attrs, ctrl) {
$scope.popoverClass = attrs.popoverClass;
$scope.dropDirection = attrs.direction || 'bottom';
var left, top;
var trigger = document.querySelector('#'+$scope.trigger);
var target = document.querySelector('.ng-popover[trigger="'+$scope.trigger+'"]');
// Add click event listener to trigger
trigger.addEventListener('click', function(ev){
var left, top;
var trigger = this; //get trigger element
var target = document.querySelector('.ng-popover[trigger="'+$scope.trigger+'"]'); //get triger's target popover
ev.preventDefault();
calcPopoverPosition(trigger, target); //calculate the position of the popover
hideAllPopovers(trigger);
target.classList.toggle('hide'); //toggle display of target popover
// if target popover is visible then add click listener to body and call the open popover callback
if(!target.classList.contains('hide')){
ctrl.registerBodyListener();
$scope.onOpen();
$scope.$apply();
}
//else remove click listener from body and call close popover callback
else{
ctrl.unregisterBodyListener();
$scope.onClose();
$scope.$apply();
}
});
var getTriggerOffset = function(){
var triggerRect = trigger.getBoundingClientRect();
var bodyRect = document.body.getBoundingClientRect();
return {
top: triggerRect.top + document.body.scrollTop,
left: triggerRect.left + document.body.scrollLeft
}
};
// calculates the position of the popover
var calcPopoverPosition = function(trigger, target){
target.classList.toggle('hide');
var targetWidth = target.offsetWidth;
var targetHeight = target.offsetHeight;
target.classList.toggle('hide');
var triggerWidth = trigger.offsetWidth;
var triggerHeight = trigger.offsetHeight;
switch($scope.dropDirection){
case 'left': {
left = getTriggerOffset().left - targetWidth - 10 + 'px';
top = getTriggerOffset().top + 'px';
break;
}
case 'right':{
left = getTriggerOffset().left + triggerWidth + 10 + 'px';
top = getTriggerOffset().top + 'px';
break;
}
case'top':{
left = getTriggerOffset().left + 'px';
top = getTriggerOffset().top - targetHeight - 10 + 'px';
break;
}
default:{
left = getTriggerOffset().left +'px';
top = getTriggerOffset().top + triggerHeight + 10 + 'px'
}
}
target.style.position = 'absolute';
target.style.left = left;
target.style.top = top;
}
calcPopoverPosition(trigger, target);
} | javascript | function($scope, element, attrs, ctrl) {
$scope.popoverClass = attrs.popoverClass;
$scope.dropDirection = attrs.direction || 'bottom';
var left, top;
var trigger = document.querySelector('#'+$scope.trigger);
var target = document.querySelector('.ng-popover[trigger="'+$scope.trigger+'"]');
// Add click event listener to trigger
trigger.addEventListener('click', function(ev){
var left, top;
var trigger = this; //get trigger element
var target = document.querySelector('.ng-popover[trigger="'+$scope.trigger+'"]'); //get triger's target popover
ev.preventDefault();
calcPopoverPosition(trigger, target); //calculate the position of the popover
hideAllPopovers(trigger);
target.classList.toggle('hide'); //toggle display of target popover
// if target popover is visible then add click listener to body and call the open popover callback
if(!target.classList.contains('hide')){
ctrl.registerBodyListener();
$scope.onOpen();
$scope.$apply();
}
//else remove click listener from body and call close popover callback
else{
ctrl.unregisterBodyListener();
$scope.onClose();
$scope.$apply();
}
});
var getTriggerOffset = function(){
var triggerRect = trigger.getBoundingClientRect();
var bodyRect = document.body.getBoundingClientRect();
return {
top: triggerRect.top + document.body.scrollTop,
left: triggerRect.left + document.body.scrollLeft
}
};
// calculates the position of the popover
var calcPopoverPosition = function(trigger, target){
target.classList.toggle('hide');
var targetWidth = target.offsetWidth;
var targetHeight = target.offsetHeight;
target.classList.toggle('hide');
var triggerWidth = trigger.offsetWidth;
var triggerHeight = trigger.offsetHeight;
switch($scope.dropDirection){
case 'left': {
left = getTriggerOffset().left - targetWidth - 10 + 'px';
top = getTriggerOffset().top + 'px';
break;
}
case 'right':{
left = getTriggerOffset().left + triggerWidth + 10 + 'px';
top = getTriggerOffset().top + 'px';
break;
}
case'top':{
left = getTriggerOffset().left + 'px';
top = getTriggerOffset().top - targetHeight - 10 + 'px';
break;
}
default:{
left = getTriggerOffset().left +'px';
top = getTriggerOffset().top + triggerHeight + 10 + 'px'
}
}
target.style.position = 'absolute';
target.style.left = left;
target.style.top = top;
}
calcPopoverPosition(trigger, target);
} | [
"function",
"(",
"$scope",
",",
"element",
",",
"attrs",
",",
"ctrl",
")",
"{",
"$scope",
".",
"popoverClass",
"=",
"attrs",
".",
"popoverClass",
";",
"$scope",
".",
"dropDirection",
"=",
"attrs",
".",
"direction",
"||",
"'bottom'",
";",
"var",
"left",
",",
"top",
";",
"var",
"trigger",
"=",
"document",
".",
"querySelector",
"(",
"'#'",
"+",
"$scope",
".",
"trigger",
")",
";",
"var",
"target",
"=",
"document",
".",
"querySelector",
"(",
"'.ng-popover[trigger=\"'",
"+",
"$scope",
".",
"trigger",
"+",
"'\"]'",
")",
";",
"trigger",
".",
"addEventListener",
"(",
"'click'",
",",
"function",
"(",
"ev",
")",
"{",
"var",
"left",
",",
"top",
";",
"var",
"trigger",
"=",
"this",
";",
"var",
"target",
"=",
"document",
".",
"querySelector",
"(",
"'.ng-popover[trigger=\"'",
"+",
"$scope",
".",
"trigger",
"+",
"'\"]'",
")",
";",
"ev",
".",
"preventDefault",
"(",
")",
";",
"calcPopoverPosition",
"(",
"trigger",
",",
"target",
")",
";",
"hideAllPopovers",
"(",
"trigger",
")",
";",
"target",
".",
"classList",
".",
"toggle",
"(",
"'hide'",
")",
";",
"if",
"(",
"!",
"target",
".",
"classList",
".",
"contains",
"(",
"'hide'",
")",
")",
"{",
"ctrl",
".",
"registerBodyListener",
"(",
")",
";",
"$scope",
".",
"onOpen",
"(",
")",
";",
"$scope",
".",
"$apply",
"(",
")",
";",
"}",
"else",
"{",
"ctrl",
".",
"unregisterBodyListener",
"(",
")",
";",
"$scope",
".",
"onClose",
"(",
")",
";",
"$scope",
".",
"$apply",
"(",
")",
";",
"}",
"}",
")",
";",
"var",
"getTriggerOffset",
"=",
"function",
"(",
")",
"{",
"var",
"triggerRect",
"=",
"trigger",
".",
"getBoundingClientRect",
"(",
")",
";",
"var",
"bodyRect",
"=",
"document",
".",
"body",
".",
"getBoundingClientRect",
"(",
")",
";",
"return",
"{",
"top",
":",
"triggerRect",
".",
"top",
"+",
"document",
".",
"body",
".",
"scrollTop",
",",
"left",
":",
"triggerRect",
".",
"left",
"+",
"document",
".",
"body",
".",
"scrollLeft",
"}",
"}",
";",
"var",
"calcPopoverPosition",
"=",
"function",
"(",
"trigger",
",",
"target",
")",
"{",
"target",
".",
"classList",
".",
"toggle",
"(",
"'hide'",
")",
";",
"var",
"targetWidth",
"=",
"target",
".",
"offsetWidth",
";",
"var",
"targetHeight",
"=",
"target",
".",
"offsetHeight",
";",
"target",
".",
"classList",
".",
"toggle",
"(",
"'hide'",
")",
";",
"var",
"triggerWidth",
"=",
"trigger",
".",
"offsetWidth",
";",
"var",
"triggerHeight",
"=",
"trigger",
".",
"offsetHeight",
";",
"switch",
"(",
"$scope",
".",
"dropDirection",
")",
"{",
"case",
"'left'",
":",
"{",
"left",
"=",
"getTriggerOffset",
"(",
")",
".",
"left",
"-",
"targetWidth",
"-",
"10",
"+",
"'px'",
";",
"top",
"=",
"getTriggerOffset",
"(",
")",
".",
"top",
"+",
"'px'",
";",
"break",
";",
"}",
"case",
"'right'",
":",
"{",
"left",
"=",
"getTriggerOffset",
"(",
")",
".",
"left",
"+",
"triggerWidth",
"+",
"10",
"+",
"'px'",
";",
"top",
"=",
"getTriggerOffset",
"(",
")",
".",
"top",
"+",
"'px'",
";",
"break",
";",
"}",
"case",
"'top'",
":",
"{",
"left",
"=",
"getTriggerOffset",
"(",
")",
".",
"left",
"+",
"'px'",
";",
"top",
"=",
"getTriggerOffset",
"(",
")",
".",
"top",
"-",
"targetHeight",
"-",
"10",
"+",
"'px'",
";",
"break",
";",
"}",
"default",
":",
"{",
"left",
"=",
"getTriggerOffset",
"(",
")",
".",
"left",
"+",
"'px'",
";",
"top",
"=",
"getTriggerOffset",
"(",
")",
".",
"top",
"+",
"triggerHeight",
"+",
"10",
"+",
"'px'",
"}",
"}",
"target",
".",
"style",
".",
"position",
"=",
"'absolute'",
";",
"target",
".",
"style",
".",
"left",
"=",
"left",
";",
"target",
".",
"style",
".",
"top",
"=",
"top",
";",
"}",
"calcPopoverPosition",
"(",
"trigger",
",",
"target",
")",
";",
"}"
]
| we want to insert custom content inside the directive | [
"we",
"want",
"to",
"insert",
"custom",
"content",
"inside",
"the",
"directive"
]
| 057869772aa22e2df643495e4595dc7448975875 | https://github.com/FauzanKhan/angular-popover/blob/057869772aa22e2df643495e4595dc7448975875/src/js/ngPopover.js#L16-L92 | train |
|
FauzanKhan/angular-popover | src/js/ngPopover.js | function(trigger, target){
target.classList.toggle('hide');
var targetWidth = target.offsetWidth;
var targetHeight = target.offsetHeight;
target.classList.toggle('hide');
var triggerWidth = trigger.offsetWidth;
var triggerHeight = trigger.offsetHeight;
switch($scope.dropDirection){
case 'left': {
left = getTriggerOffset().left - targetWidth - 10 + 'px';
top = getTriggerOffset().top + 'px';
break;
}
case 'right':{
left = getTriggerOffset().left + triggerWidth + 10 + 'px';
top = getTriggerOffset().top + 'px';
break;
}
case'top':{
left = getTriggerOffset().left + 'px';
top = getTriggerOffset().top - targetHeight - 10 + 'px';
break;
}
default:{
left = getTriggerOffset().left +'px';
top = getTriggerOffset().top + triggerHeight + 10 + 'px'
}
}
target.style.position = 'absolute';
target.style.left = left;
target.style.top = top;
} | javascript | function(trigger, target){
target.classList.toggle('hide');
var targetWidth = target.offsetWidth;
var targetHeight = target.offsetHeight;
target.classList.toggle('hide');
var triggerWidth = trigger.offsetWidth;
var triggerHeight = trigger.offsetHeight;
switch($scope.dropDirection){
case 'left': {
left = getTriggerOffset().left - targetWidth - 10 + 'px';
top = getTriggerOffset().top + 'px';
break;
}
case 'right':{
left = getTriggerOffset().left + triggerWidth + 10 + 'px';
top = getTriggerOffset().top + 'px';
break;
}
case'top':{
left = getTriggerOffset().left + 'px';
top = getTriggerOffset().top - targetHeight - 10 + 'px';
break;
}
default:{
left = getTriggerOffset().left +'px';
top = getTriggerOffset().top + triggerHeight + 10 + 'px'
}
}
target.style.position = 'absolute';
target.style.left = left;
target.style.top = top;
} | [
"function",
"(",
"trigger",
",",
"target",
")",
"{",
"target",
".",
"classList",
".",
"toggle",
"(",
"'hide'",
")",
";",
"var",
"targetWidth",
"=",
"target",
".",
"offsetWidth",
";",
"var",
"targetHeight",
"=",
"target",
".",
"offsetHeight",
";",
"target",
".",
"classList",
".",
"toggle",
"(",
"'hide'",
")",
";",
"var",
"triggerWidth",
"=",
"trigger",
".",
"offsetWidth",
";",
"var",
"triggerHeight",
"=",
"trigger",
".",
"offsetHeight",
";",
"switch",
"(",
"$scope",
".",
"dropDirection",
")",
"{",
"case",
"'left'",
":",
"{",
"left",
"=",
"getTriggerOffset",
"(",
")",
".",
"left",
"-",
"targetWidth",
"-",
"10",
"+",
"'px'",
";",
"top",
"=",
"getTriggerOffset",
"(",
")",
".",
"top",
"+",
"'px'",
";",
"break",
";",
"}",
"case",
"'right'",
":",
"{",
"left",
"=",
"getTriggerOffset",
"(",
")",
".",
"left",
"+",
"triggerWidth",
"+",
"10",
"+",
"'px'",
";",
"top",
"=",
"getTriggerOffset",
"(",
")",
".",
"top",
"+",
"'px'",
";",
"break",
";",
"}",
"case",
"'top'",
":",
"{",
"left",
"=",
"getTriggerOffset",
"(",
")",
".",
"left",
"+",
"'px'",
";",
"top",
"=",
"getTriggerOffset",
"(",
")",
".",
"top",
"-",
"targetHeight",
"-",
"10",
"+",
"'px'",
";",
"break",
";",
"}",
"default",
":",
"{",
"left",
"=",
"getTriggerOffset",
"(",
")",
".",
"left",
"+",
"'px'",
";",
"top",
"=",
"getTriggerOffset",
"(",
")",
".",
"top",
"+",
"triggerHeight",
"+",
"10",
"+",
"'px'",
"}",
"}",
"target",
".",
"style",
".",
"position",
"=",
"'absolute'",
";",
"target",
".",
"style",
".",
"left",
"=",
"left",
";",
"target",
".",
"style",
".",
"top",
"=",
"top",
";",
"}"
]
| calculates the position of the popover | [
"calculates",
"the",
"position",
"of",
"the",
"popover"
]
| 057869772aa22e2df643495e4595dc7448975875 | https://github.com/FauzanKhan/angular-popover/blob/057869772aa22e2df643495e4595dc7448975875/src/js/ngPopover.js#L56-L90 | train |
|
FauzanKhan/angular-popover | src/js/ngPopover.js | function(trigger){
var triggerId;
if(trigger)
triggerId = trigger.getAttribute('id');
var allPopovers = trigger != undefined ? document.querySelectorAll('.ng-popover:not([trigger="'+triggerId+'"])') : document.querySelectorAll('.ng-popover');
for(var i =0; i<allPopovers.length; i++){
var popover = allPopovers[i];
if(!popover.classList.contains('hide'))
popover.classList.add('hide')
}
} | javascript | function(trigger){
var triggerId;
if(trigger)
triggerId = trigger.getAttribute('id');
var allPopovers = trigger != undefined ? document.querySelectorAll('.ng-popover:not([trigger="'+triggerId+'"])') : document.querySelectorAll('.ng-popover');
for(var i =0; i<allPopovers.length; i++){
var popover = allPopovers[i];
if(!popover.classList.contains('hide'))
popover.classList.add('hide')
}
} | [
"function",
"(",
"trigger",
")",
"{",
"var",
"triggerId",
";",
"if",
"(",
"trigger",
")",
"triggerId",
"=",
"trigger",
".",
"getAttribute",
"(",
"'id'",
")",
";",
"var",
"allPopovers",
"=",
"trigger",
"!=",
"undefined",
"?",
"document",
".",
"querySelectorAll",
"(",
"'.ng-popover:not([trigger=\"'",
"+",
"triggerId",
"+",
"'\"])'",
")",
":",
"document",
".",
"querySelectorAll",
"(",
"'.ng-popover'",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"allPopovers",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"popover",
"=",
"allPopovers",
"[",
"i",
"]",
";",
"if",
"(",
"!",
"popover",
".",
"classList",
".",
"contains",
"(",
"'hide'",
")",
")",
"popover",
".",
"classList",
".",
"add",
"(",
"'hide'",
")",
"}",
"}"
]
| Hides all popovers, skips the popover whose trigger Id is provided in the function call | [
"Hides",
"all",
"popovers",
"skips",
"the",
"popover",
"whose",
"trigger",
"Id",
"is",
"provided",
"in",
"the",
"function",
"call"
]
| 057869772aa22e2df643495e4595dc7448975875 | https://github.com/FauzanKhan/angular-popover/blob/057869772aa22e2df643495e4595dc7448975875/src/js/ngPopover.js#L140-L150 | train |
|
gwtw/js-binary-heap | index.js | heapify | function heapify(heap, i) {
var l = getLeft(i);
var r = getRight(i);
var smallest = i;
if (l < heap.list.length &&
heap.compare(heap.list[l], heap.list[i]) < 0) {
smallest = l;
}
if (r < heap.list.length &&
heap.compare(heap.list[r], heap.list[smallest]) < 0) {
smallest = r;
}
if (smallest !== i) {
swap(heap.list, i, smallest);
heapify(heap, smallest);
}
} | javascript | function heapify(heap, i) {
var l = getLeft(i);
var r = getRight(i);
var smallest = i;
if (l < heap.list.length &&
heap.compare(heap.list[l], heap.list[i]) < 0) {
smallest = l;
}
if (r < heap.list.length &&
heap.compare(heap.list[r], heap.list[smallest]) < 0) {
smallest = r;
}
if (smallest !== i) {
swap(heap.list, i, smallest);
heapify(heap, smallest);
}
} | [
"function",
"heapify",
"(",
"heap",
",",
"i",
")",
"{",
"var",
"l",
"=",
"getLeft",
"(",
"i",
")",
";",
"var",
"r",
"=",
"getRight",
"(",
"i",
")",
";",
"var",
"smallest",
"=",
"i",
";",
"if",
"(",
"l",
"<",
"heap",
".",
"list",
".",
"length",
"&&",
"heap",
".",
"compare",
"(",
"heap",
".",
"list",
"[",
"l",
"]",
",",
"heap",
".",
"list",
"[",
"i",
"]",
")",
"<",
"0",
")",
"{",
"smallest",
"=",
"l",
";",
"}",
"if",
"(",
"r",
"<",
"heap",
".",
"list",
".",
"length",
"&&",
"heap",
".",
"compare",
"(",
"heap",
".",
"list",
"[",
"r",
"]",
",",
"heap",
".",
"list",
"[",
"smallest",
"]",
")",
"<",
"0",
")",
"{",
"smallest",
"=",
"r",
";",
"}",
"if",
"(",
"smallest",
"!==",
"i",
")",
"{",
"swap",
"(",
"heap",
".",
"list",
",",
"i",
",",
"smallest",
")",
";",
"heapify",
"(",
"heap",
",",
"smallest",
")",
";",
"}",
"}"
]
| Heapifies a node.
@private
@param {BinaryHeap} heap The heap containing the node to heapify.
@param {number} i The index of the node to heapify. | [
"Heapifies",
"a",
"node",
"."
]
| 4550c7a686672333433bbfe134e34d84a35ddc91 | https://github.com/gwtw/js-binary-heap/blob/4550c7a686672333433bbfe134e34d84a35ddc91/index.js#L151-L167 | train |
gwtw/js-binary-heap | index.js | buildHeapFromNodeArray | function buildHeapFromNodeArray(heap, nodeArray) {
heap.list = nodeArray;
for (var i = Math.floor(heap.list.length / 2); i >= 0; i--) {
heapify(heap, i);
}
} | javascript | function buildHeapFromNodeArray(heap, nodeArray) {
heap.list = nodeArray;
for (var i = Math.floor(heap.list.length / 2); i >= 0; i--) {
heapify(heap, i);
}
} | [
"function",
"buildHeapFromNodeArray",
"(",
"heap",
",",
"nodeArray",
")",
"{",
"heap",
".",
"list",
"=",
"nodeArray",
";",
"for",
"(",
"var",
"i",
"=",
"Math",
".",
"floor",
"(",
"heap",
".",
"list",
".",
"length",
"/",
"2",
")",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"heapify",
"(",
"heap",
",",
"i",
")",
";",
"}",
"}"
]
| Builds a heap from a node array, this will discard the heap's current data.
@private
@param {BinaryHeap} heap The heap to override.
@param {Node[]} nodeArray The array of nodes for the new heap. | [
"Builds",
"a",
"heap",
"from",
"a",
"node",
"array",
"this",
"will",
"discard",
"the",
"heap",
"s",
"current",
"data",
"."
]
| 4550c7a686672333433bbfe134e34d84a35ddc91 | https://github.com/gwtw/js-binary-heap/blob/4550c7a686672333433bbfe134e34d84a35ddc91/index.js#L176-L181 | train |
SmartTeleMax/MaSha | docs/js/packed.js | function() {
var this_ = this;
this.msg = (typeof this.options.select_message == 'string'?
document.getElementById(this.options.select_message):
this.options.select_message);
this.close_button = this.get_close_button();
this.msg_autoclose = null;
addEvent(this.close_button, 'click', function(e){
preventDefault(e);
this_.hide_message();
this_.save_message_closed();
clearTimeout(this_.msg_autoclose);
});
} | javascript | function() {
var this_ = this;
this.msg = (typeof this.options.select_message == 'string'?
document.getElementById(this.options.select_message):
this.options.select_message);
this.close_button = this.get_close_button();
this.msg_autoclose = null;
addEvent(this.close_button, 'click', function(e){
preventDefault(e);
this_.hide_message();
this_.save_message_closed();
clearTimeout(this_.msg_autoclose);
});
} | [
"function",
"(",
")",
"{",
"var",
"this_",
"=",
"this",
";",
"this",
".",
"msg",
"=",
"(",
"typeof",
"this",
".",
"options",
".",
"select_message",
"==",
"'string'",
"?",
"document",
".",
"getElementById",
"(",
"this",
".",
"options",
".",
"select_message",
")",
":",
"this",
".",
"options",
".",
"select_message",
")",
";",
"this",
".",
"close_button",
"=",
"this",
".",
"get_close_button",
"(",
")",
";",
"this",
".",
"msg_autoclose",
"=",
"null",
";",
"addEvent",
"(",
"this",
".",
"close_button",
",",
"'click'",
",",
"function",
"(",
"e",
")",
"{",
"preventDefault",
"(",
"e",
")",
";",
"this_",
".",
"hide_message",
"(",
")",
";",
"this_",
".",
"save_message_closed",
"(",
")",
";",
"clearTimeout",
"(",
"this_",
".",
"msg_autoclose",
")",
";",
"}",
")",
";",
"}"
]
| message.js | [
"message",
".",
"js"
]
| 5002411033f3f3969930a61e7aaa4b8e818cf5d8 | https://github.com/SmartTeleMax/MaSha/blob/5002411033f3f3969930a61e7aaa4b8e818cf5d8/docs/js/packed.js#L12195-L12210 | train |
|
ngokevin/aframe-physics-components | src/index.js | function () {
var body = this.body;
var el = this.el;
el.setAttribute('position', body.position);
el.setAttribute('rotation', {
x: deg(body.quaternion.x),
y: deg(body.quaternion.y),
z: deg(body.quaternion.z)
});
} | javascript | function () {
var body = this.body;
var el = this.el;
el.setAttribute('position', body.position);
el.setAttribute('rotation', {
x: deg(body.quaternion.x),
y: deg(body.quaternion.y),
z: deg(body.quaternion.z)
});
} | [
"function",
"(",
")",
"{",
"var",
"body",
"=",
"this",
".",
"body",
";",
"var",
"el",
"=",
"this",
".",
"el",
";",
"el",
".",
"setAttribute",
"(",
"'position'",
",",
"body",
".",
"position",
")",
";",
"el",
".",
"setAttribute",
"(",
"'rotation'",
",",
"{",
"x",
":",
"deg",
"(",
"body",
".",
"quaternion",
".",
"x",
")",
",",
"y",
":",
"deg",
"(",
"body",
".",
"quaternion",
".",
"y",
")",
",",
"z",
":",
"deg",
"(",
"body",
".",
"quaternion",
".",
"z",
")",
"}",
")",
";",
"}"
]
| Copy CANNON rigid body properties to THREE object3D. | [
"Copy",
"CANNON",
"rigid",
"body",
"properties",
"to",
"THREE",
"object3D",
"."
]
| 3676f496d36a0c7e2611f184fe4be528b010cb9a | https://github.com/ngokevin/aframe-physics-components/blob/3676f496d36a0c7e2611f184fe4be528b010cb9a/src/index.js#L269-L278 | train |
|
SmartTeleMax/MaSha | src/js/masha.js | function(numclasses) {
for (var i = numclasses.length; i--;) {
var numclass = numclasses[i];
var spans = byClassName(this.selectable, numclass);
var closewrap = firstWithClass(spans[spans.length - 1], 'closewrap');
closewrap.parentNode.removeChild(closewrap);
this.removeTextSelection(spans);
delete this.ranges[numclass];
}
} | javascript | function(numclasses) {
for (var i = numclasses.length; i--;) {
var numclass = numclasses[i];
var spans = byClassName(this.selectable, numclass);
var closewrap = firstWithClass(spans[spans.length - 1], 'closewrap');
closewrap.parentNode.removeChild(closewrap);
this.removeTextSelection(spans);
delete this.ranges[numclass];
}
} | [
"function",
"(",
"numclasses",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"numclasses",
".",
"length",
";",
"i",
"--",
";",
")",
"{",
"var",
"numclass",
"=",
"numclasses",
"[",
"i",
"]",
";",
"var",
"spans",
"=",
"byClassName",
"(",
"this",
".",
"selectable",
",",
"numclass",
")",
";",
"var",
"closewrap",
"=",
"firstWithClass",
"(",
"spans",
"[",
"spans",
".",
"length",
"-",
"1",
"]",
",",
"'closewrap'",
")",
";",
"closewrap",
".",
"parentNode",
".",
"removeChild",
"(",
"closewrap",
")",
";",
"this",
".",
"removeTextSelection",
"(",
"spans",
")",
";",
"delete",
"this",
".",
"ranges",
"[",
"numclass",
"]",
";",
"}",
"}"
]
| XXX sort methods logically | [
"XXX",
"sort",
"methods",
"logically"
]
| 5002411033f3f3969930a61e7aaa4b8e818cf5d8 | https://github.com/SmartTeleMax/MaSha/blob/5002411033f3f3969930a61e7aaa4b8e818cf5d8/src/js/masha.js#L333-L343 | train |
|
vega/vega-scale | src/scales.js | create | function create(type, constructor) {
return function scale() {
var s = constructor();
if (!s.invertRange) {
s.invertRange = s.invert ? invertRange(s)
: s.invertExtent ? invertRangeExtent(s)
: undefined;
}
s.type = type;
return s;
};
} | javascript | function create(type, constructor) {
return function scale() {
var s = constructor();
if (!s.invertRange) {
s.invertRange = s.invert ? invertRange(s)
: s.invertExtent ? invertRangeExtent(s)
: undefined;
}
s.type = type;
return s;
};
} | [
"function",
"create",
"(",
"type",
",",
"constructor",
")",
"{",
"return",
"function",
"scale",
"(",
")",
"{",
"var",
"s",
"=",
"constructor",
"(",
")",
";",
"if",
"(",
"!",
"s",
".",
"invertRange",
")",
"{",
"s",
".",
"invertRange",
"=",
"s",
".",
"invert",
"?",
"invertRange",
"(",
"s",
")",
":",
"s",
".",
"invertExtent",
"?",
"invertRangeExtent",
"(",
"s",
")",
":",
"undefined",
";",
"}",
"s",
".",
"type",
"=",
"type",
";",
"return",
"s",
";",
"}",
";",
"}"
]
| Augment scales with their type and needed inverse methods. | [
"Augment",
"scales",
"with",
"their",
"type",
"and",
"needed",
"inverse",
"methods",
"."
]
| 6c29c4a4e6ddf50ac2cdeb8e105228a9b86f86b5 | https://github.com/vega/vega-scale/blob/6c29c4a4e6ddf50ac2cdeb8e105228a9b86f86b5/src/scales.js#L18-L31 | train |
rd-dev-ukraine/angular-io-datepicker | src/datepicker/datePicker.js | parserFabric | function parserFabric(mode, format) {
return function (value, parseFn) {
parseFn = parseFn || moment_1.utc;
if (value === null || value === undefined || value === "") {
return null;
}
var formatsToParse = parseFormat[mode || "date"];
return parseFn(value, [format].concat(formatsToParse), true);
};
} | javascript | function parserFabric(mode, format) {
return function (value, parseFn) {
parseFn = parseFn || moment_1.utc;
if (value === null || value === undefined || value === "") {
return null;
}
var formatsToParse = parseFormat[mode || "date"];
return parseFn(value, [format].concat(formatsToParse), true);
};
} | [
"function",
"parserFabric",
"(",
"mode",
",",
"format",
")",
"{",
"return",
"function",
"(",
"value",
",",
"parseFn",
")",
"{",
"parseFn",
"=",
"parseFn",
"||",
"moment_1",
".",
"utc",
";",
"if",
"(",
"value",
"===",
"null",
"||",
"value",
"===",
"undefined",
"||",
"value",
"===",
"\"\"",
")",
"{",
"return",
"null",
";",
"}",
"var",
"formatsToParse",
"=",
"parseFormat",
"[",
"mode",
"||",
"\"date\"",
"]",
";",
"return",
"parseFn",
"(",
"value",
",",
"[",
"format",
"]",
".",
"concat",
"(",
"formatsToParse",
")",
",",
"true",
")",
";",
"}",
";",
"}"
]
| Parses the given value as date using moment.js.
If value cannot be parsed the invalid Moment object is returned.
The calling code should not assume if the method returns local or utc value and
must convert value to corresponding form itself. | [
"Parses",
"the",
"given",
"value",
"as",
"date",
"using",
"moment",
".",
"js",
".",
"If",
"value",
"cannot",
"be",
"parsed",
"the",
"invalid",
"Moment",
"object",
"is",
"returned",
".",
"The",
"calling",
"code",
"should",
"not",
"assume",
"if",
"the",
"method",
"returns",
"local",
"or",
"utc",
"value",
"and",
"must",
"convert",
"value",
"to",
"corresponding",
"form",
"itself",
"."
]
| 8338812942fd9f7f68138b328dc637a4f0ff33e0 | https://github.com/rd-dev-ukraine/angular-io-datepicker/blob/8338812942fd9f7f68138b328dc637a4f0ff33e0/src/datepicker/datePicker.js#L60-L69 | train |
ryym/mocha-each | gulpfile.babel.js | runAndWatch | function runAndWatch(watchPattern, initialValue, task) {
gulp.watch(watchPattern, event => {
task(event.path, event);
});
return task(initialValue);
} | javascript | function runAndWatch(watchPattern, initialValue, task) {
gulp.watch(watchPattern, event => {
task(event.path, event);
});
return task(initialValue);
} | [
"function",
"runAndWatch",
"(",
"watchPattern",
",",
"initialValue",
",",
"task",
")",
"{",
"gulp",
".",
"watch",
"(",
"watchPattern",
",",
"event",
"=>",
"{",
"task",
"(",
"event",
".",
"path",
",",
"event",
")",
";",
"}",
")",
";",
"return",
"task",
"(",
"initialValue",
")",
";",
"}"
]
| Run a given task. And re-run it whenever the specified files change. | [
"Run",
"a",
"given",
"task",
".",
"And",
"re",
"-",
"run",
"it",
"whenever",
"the",
"specified",
"files",
"change",
"."
]
| 99d70474c4ec222c6eab6ceaac0886410dfe0dca | https://github.com/ryym/mocha-each/blob/99d70474c4ec222c6eab6ceaac0886410dfe0dca/gulpfile.babel.js#L53-L58 | train |
ryym/mocha-each | gulpfile.babel.js | lintFiles | function lintFiles(pattern, strict, configs) {
const linter = new eslint.CLIEngine(configs);
const report = linter.executeOnFiles([pattern]);
const formatter = linter.getFormatter();
console.log(formatter(report.results));
if (0 < report.errorCount || (strict && 0 < report.warningCount)) {
throw new Error('eslint reports some problems.');
}
} | javascript | function lintFiles(pattern, strict, configs) {
const linter = new eslint.CLIEngine(configs);
const report = linter.executeOnFiles([pattern]);
const formatter = linter.getFormatter();
console.log(formatter(report.results));
if (0 < report.errorCount || (strict && 0 < report.warningCount)) {
throw new Error('eslint reports some problems.');
}
} | [
"function",
"lintFiles",
"(",
"pattern",
",",
"strict",
",",
"configs",
")",
"{",
"const",
"linter",
"=",
"new",
"eslint",
".",
"CLIEngine",
"(",
"configs",
")",
";",
"const",
"report",
"=",
"linter",
".",
"executeOnFiles",
"(",
"[",
"pattern",
"]",
")",
";",
"const",
"formatter",
"=",
"linter",
".",
"getFormatter",
"(",
")",
";",
"console",
".",
"log",
"(",
"formatter",
"(",
"report",
".",
"results",
")",
")",
";",
"if",
"(",
"0",
"<",
"report",
".",
"errorCount",
"||",
"(",
"strict",
"&&",
"0",
"<",
"report",
".",
"warningCount",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'eslint reports some problems.'",
")",
";",
"}",
"}"
]
| Lint the specified files using eslint. | [
"Lint",
"the",
"specified",
"files",
"using",
"eslint",
"."
]
| 99d70474c4ec222c6eab6ceaac0886410dfe0dca | https://github.com/ryym/mocha-each/blob/99d70474c4ec222c6eab6ceaac0886410dfe0dca/gulpfile.babel.js#L86-L94 | train |
ryym/mocha-each | lib/index.js | forEach | function forEach(parameters, dIt = global.it, dDescribe = global.describe) {
const it = makeTestCaseDefiner(parameters, dIt);
it.skip = makeParameterizedSkip(parameters, dIt);
it.only = makeParameterizedOnly(parameters, dIt);
const describe = makeTestCaseDefiner(parameters, dDescribe);
describe.skip = makeParameterizedSkip(parameters, dDescribe);
describe.only = makeParameterizedOnly(parameters, dDescribe);
return { it, describe };
} | javascript | function forEach(parameters, dIt = global.it, dDescribe = global.describe) {
const it = makeTestCaseDefiner(parameters, dIt);
it.skip = makeParameterizedSkip(parameters, dIt);
it.only = makeParameterizedOnly(parameters, dIt);
const describe = makeTestCaseDefiner(parameters, dDescribe);
describe.skip = makeParameterizedSkip(parameters, dDescribe);
describe.only = makeParameterizedOnly(parameters, dDescribe);
return { it, describe };
} | [
"function",
"forEach",
"(",
"parameters",
",",
"dIt",
"=",
"global",
".",
"it",
",",
"dDescribe",
"=",
"global",
".",
"describe",
")",
"{",
"const",
"it",
"=",
"makeTestCaseDefiner",
"(",
"parameters",
",",
"dIt",
")",
";",
"it",
".",
"skip",
"=",
"makeParameterizedSkip",
"(",
"parameters",
",",
"dIt",
")",
";",
"it",
".",
"only",
"=",
"makeParameterizedOnly",
"(",
"parameters",
",",
"dIt",
")",
";",
"const",
"describe",
"=",
"makeTestCaseDefiner",
"(",
"parameters",
",",
"dDescribe",
")",
";",
"describe",
".",
"skip",
"=",
"makeParameterizedSkip",
"(",
"parameters",
",",
"dDescribe",
")",
";",
"describe",
".",
"only",
"=",
"makeParameterizedOnly",
"(",
"parameters",
",",
"dDescribe",
")",
";",
"return",
"{",
"it",
",",
"describe",
"}",
";",
"}"
]
| Defines Mocha test cases for each given parameter.
@param {Array} parameters
@param {function} dIt - The 'it' function used in this function.
If omitted, 'it' in global name space is used.
@param {function} dDescribe - The 'describe' function used in this function.
If omitted, 'describe' in global name space is used.
@return {Object} The object which has a method to define test cases. | [
"Defines",
"Mocha",
"test",
"cases",
"for",
"each",
"given",
"parameter",
"."
]
| 99d70474c4ec222c6eab6ceaac0886410dfe0dca | https://github.com/ryym/mocha-each/blob/99d70474c4ec222c6eab6ceaac0886410dfe0dca/lib/index.js#L14-L22 | train |
ryym/mocha-each | lib/index.js | makeParameterizedOnly | function makeParameterizedOnly(parameters, defaultIt) {
return function(title, test) {
const it = makeTestCaseDefiner(parameters, defaultIt);
global.describe.only('', () => it(title, test));
};
} | javascript | function makeParameterizedOnly(parameters, defaultIt) {
return function(title, test) {
const it = makeTestCaseDefiner(parameters, defaultIt);
global.describe.only('', () => it(title, test));
};
} | [
"function",
"makeParameterizedOnly",
"(",
"parameters",
",",
"defaultIt",
")",
"{",
"return",
"function",
"(",
"title",
",",
"test",
")",
"{",
"const",
"it",
"=",
"makeTestCaseDefiner",
"(",
"parameters",
",",
"defaultIt",
")",
";",
"global",
".",
"describe",
".",
"only",
"(",
"''",
",",
"(",
")",
"=>",
"it",
"(",
"title",
",",
"test",
")",
")",
";",
"}",
";",
"}"
]
| Create a function which define exclusive parameterized tests.
@private | [
"Create",
"a",
"function",
"which",
"define",
"exclusive",
"parameterized",
"tests",
"."
]
| 99d70474c4ec222c6eab6ceaac0886410dfe0dca | https://github.com/ryym/mocha-each/blob/99d70474c4ec222c6eab6ceaac0886410dfe0dca/lib/index.js#L40-L45 | train |
rd-dev-ukraine/angular-io-datepicker | src/datepicker/dateUtils.js | monthCalendar | function monthCalendar(date) {
var start = date.clone().startOf("month").startOf("week").startOf("day");
var end = date.clone().endOf("month").endOf("week").startOf("day");
var result = [];
var current = start.weekday(0).subtract(1, "d");
while (true) {
current = current.clone().add(1, "d");
result.push(current);
if (areDatesEqual(current, end)) {
break;
}
}
return result;
} | javascript | function monthCalendar(date) {
var start = date.clone().startOf("month").startOf("week").startOf("day");
var end = date.clone().endOf("month").endOf("week").startOf("day");
var result = [];
var current = start.weekday(0).subtract(1, "d");
while (true) {
current = current.clone().add(1, "d");
result.push(current);
if (areDatesEqual(current, end)) {
break;
}
}
return result;
} | [
"function",
"monthCalendar",
"(",
"date",
")",
"{",
"var",
"start",
"=",
"date",
".",
"clone",
"(",
")",
".",
"startOf",
"(",
"\"month\"",
")",
".",
"startOf",
"(",
"\"week\"",
")",
".",
"startOf",
"(",
"\"day\"",
")",
";",
"var",
"end",
"=",
"date",
".",
"clone",
"(",
")",
".",
"endOf",
"(",
"\"month\"",
")",
".",
"endOf",
"(",
"\"week\"",
")",
".",
"startOf",
"(",
"\"day\"",
")",
";",
"var",
"result",
"=",
"[",
"]",
";",
"var",
"current",
"=",
"start",
".",
"weekday",
"(",
"0",
")",
".",
"subtract",
"(",
"1",
",",
"\"d\"",
")",
";",
"while",
"(",
"true",
")",
"{",
"current",
"=",
"current",
".",
"clone",
"(",
")",
".",
"add",
"(",
"1",
",",
"\"d\"",
")",
";",
"result",
".",
"push",
"(",
"current",
")",
";",
"if",
"(",
"areDatesEqual",
"(",
"current",
",",
"end",
")",
")",
"{",
"break",
";",
"}",
"}",
"return",
"result",
";",
"}"
]
| Array of days belongs to the month of the specified date
including previous and next month days which are on the same week as first and last month days. | [
"Array",
"of",
"days",
"belongs",
"to",
"the",
"month",
"of",
"the",
"specified",
"date",
"including",
"previous",
"and",
"next",
"month",
"days",
"which",
"are",
"on",
"the",
"same",
"week",
"as",
"first",
"and",
"last",
"month",
"days",
"."
]
| 8338812942fd9f7f68138b328dc637a4f0ff33e0 | https://github.com/rd-dev-ukraine/angular-io-datepicker/blob/8338812942fd9f7f68138b328dc637a4f0ff33e0/src/datepicker/dateUtils.js#L19-L32 | train |
rd-dev-ukraine/angular-io-datepicker | src/datepicker/dateUtils.js | daysOfWeek | function daysOfWeek() {
var result = [];
for (var weekday = 0; weekday < 7; weekday++) {
result.push(moment_1.utc().weekday(weekday).format("dd"));
}
return result;
} | javascript | function daysOfWeek() {
var result = [];
for (var weekday = 0; weekday < 7; weekday++) {
result.push(moment_1.utc().weekday(weekday).format("dd"));
}
return result;
} | [
"function",
"daysOfWeek",
"(",
")",
"{",
"var",
"result",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"weekday",
"=",
"0",
";",
"weekday",
"<",
"7",
";",
"weekday",
"++",
")",
"{",
"result",
".",
"push",
"(",
"moment_1",
".",
"utc",
"(",
")",
".",
"weekday",
"(",
"weekday",
")",
".",
"format",
"(",
"\"dd\"",
")",
")",
";",
"}",
"return",
"result",
";",
"}"
]
| Gets array of localized days of week. | [
"Gets",
"array",
"of",
"localized",
"days",
"of",
"week",
"."
]
| 8338812942fd9f7f68138b328dc637a4f0ff33e0 | https://github.com/rd-dev-ukraine/angular-io-datepicker/blob/8338812942fd9f7f68138b328dc637a4f0ff33e0/src/datepicker/dateUtils.js#L37-L43 | train |
mairatma/babel-plugin-globals | index.js | assignDeclarationToGlobal | function assignDeclarationToGlobal(state, nodes, declaration) {
var filenameNoExt = getFilenameNoExt(state.file.opts.filename);
var expr = getGlobalExpression(state, filenameNoExt, declaration.id.name);
assignToGlobal(expr, nodes, declaration.id);
} | javascript | function assignDeclarationToGlobal(state, nodes, declaration) {
var filenameNoExt = getFilenameNoExt(state.file.opts.filename);
var expr = getGlobalExpression(state, filenameNoExt, declaration.id.name);
assignToGlobal(expr, nodes, declaration.id);
} | [
"function",
"assignDeclarationToGlobal",
"(",
"state",
",",
"nodes",
",",
"declaration",
")",
"{",
"var",
"filenameNoExt",
"=",
"getFilenameNoExt",
"(",
"state",
".",
"file",
".",
"opts",
".",
"filename",
")",
";",
"var",
"expr",
"=",
"getGlobalExpression",
"(",
"state",
",",
"filenameNoExt",
",",
"declaration",
".",
"id",
".",
"name",
")",
";",
"assignToGlobal",
"(",
"expr",
",",
"nodes",
",",
"declaration",
".",
"id",
")",
";",
"}"
]
| Assigns the given declaration to the appropriate global variable.
@param {!Object} state
@param {!Array} nodes
@param {!Declaration} declaration | [
"Assigns",
"the",
"given",
"declaration",
"to",
"the",
"appropriate",
"global",
"variable",
"."
]
| 37499200e1c34a2bf86add2910cc31dd66f2a8a7 | https://github.com/mairatma/babel-plugin-globals/blob/37499200e1c34a2bf86add2910cc31dd66f2a8a7/index.js#L26-L30 | train |
mairatma/babel-plugin-globals | index.js | assignToGlobal | function assignToGlobal(expr, nodes, expression) {
createGlobal(expr, nodes);
if (!t.isExpression(expression)) {
expression = t.toExpression(expression);
}
nodes.push(t.expressionStatement(t.assignmentExpression('=', expr, expression)));
} | javascript | function assignToGlobal(expr, nodes, expression) {
createGlobal(expr, nodes);
if (!t.isExpression(expression)) {
expression = t.toExpression(expression);
}
nodes.push(t.expressionStatement(t.assignmentExpression('=', expr, expression)));
} | [
"function",
"assignToGlobal",
"(",
"expr",
",",
"nodes",
",",
"expression",
")",
"{",
"createGlobal",
"(",
"expr",
",",
"nodes",
")",
";",
"if",
"(",
"!",
"t",
".",
"isExpression",
"(",
"expression",
")",
")",
"{",
"expression",
"=",
"t",
".",
"toExpression",
"(",
"expression",
")",
";",
"}",
"nodes",
".",
"push",
"(",
"t",
".",
"expressionStatement",
"(",
"t",
".",
"assignmentExpression",
"(",
"'='",
",",
"expr",
",",
"expression",
")",
")",
")",
";",
"}"
]
| Assigns the given expression to a global with the given id.
@param {!MemberExpression} expr
@param {!Array} nodes
@param {!Expression} expression | [
"Assigns",
"the",
"given",
"expression",
"to",
"a",
"global",
"with",
"the",
"given",
"id",
"."
]
| 37499200e1c34a2bf86add2910cc31dd66f2a8a7 | https://github.com/mairatma/babel-plugin-globals/blob/37499200e1c34a2bf86add2910cc31dd66f2a8a7/index.js#L38-L44 | train |
mairatma/babel-plugin-globals | index.js | createGlobal | function createGlobal(expr, nodes, opt_namedPartial) {
var exprs = [];
while (t.isMemberExpression(expr)) {
exprs.push(expr);
expr = expr.object;
}
var currGlobalName = '';
for (var i = exprs.length - 2; opt_namedPartial ? i >= 0 : i > 0; i--) {
currGlobalName += '.' + exprs[i].property.value;
if (!createdGlobals[currGlobalName]) {
createdGlobals[currGlobalName] = true;
nodes.push(t.expressionStatement(
t.assignmentExpression('=', exprs[i], t.logicalExpression(
'||',
exprs[i],
t.objectExpression([])
))
));
}
}
} | javascript | function createGlobal(expr, nodes, opt_namedPartial) {
var exprs = [];
while (t.isMemberExpression(expr)) {
exprs.push(expr);
expr = expr.object;
}
var currGlobalName = '';
for (var i = exprs.length - 2; opt_namedPartial ? i >= 0 : i > 0; i--) {
currGlobalName += '.' + exprs[i].property.value;
if (!createdGlobals[currGlobalName]) {
createdGlobals[currGlobalName] = true;
nodes.push(t.expressionStatement(
t.assignmentExpression('=', exprs[i], t.logicalExpression(
'||',
exprs[i],
t.objectExpression([])
))
));
}
}
} | [
"function",
"createGlobal",
"(",
"expr",
",",
"nodes",
",",
"opt_namedPartial",
")",
"{",
"var",
"exprs",
"=",
"[",
"]",
";",
"while",
"(",
"t",
".",
"isMemberExpression",
"(",
"expr",
")",
")",
"{",
"exprs",
".",
"push",
"(",
"expr",
")",
";",
"expr",
"=",
"expr",
".",
"object",
";",
"}",
"var",
"currGlobalName",
"=",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"exprs",
".",
"length",
"-",
"2",
";",
"opt_namedPartial",
"?",
"i",
">=",
"0",
":",
"i",
">",
"0",
";",
"i",
"--",
")",
"{",
"currGlobalName",
"+=",
"'.'",
"+",
"exprs",
"[",
"i",
"]",
".",
"property",
".",
"value",
";",
"if",
"(",
"!",
"createdGlobals",
"[",
"currGlobalName",
"]",
")",
"{",
"createdGlobals",
"[",
"currGlobalName",
"]",
"=",
"true",
";",
"nodes",
".",
"push",
"(",
"t",
".",
"expressionStatement",
"(",
"t",
".",
"assignmentExpression",
"(",
"'='",
",",
"exprs",
"[",
"i",
"]",
",",
"t",
".",
"logicalExpression",
"(",
"'||'",
",",
"exprs",
"[",
"i",
"]",
",",
"t",
".",
"objectExpression",
"(",
"[",
"]",
")",
")",
")",
")",
")",
";",
"}",
"}",
"}"
]
| Creates the global for the given name, if it hasn't been created yet.
@param {!MemberExpression} expr
@param {!Array} nodes Array to add the global creation assignments to. | [
"Creates",
"the",
"global",
"for",
"the",
"given",
"name",
"if",
"it",
"hasn",
"t",
"been",
"created",
"yet",
"."
]
| 37499200e1c34a2bf86add2910cc31dd66f2a8a7 | https://github.com/mairatma/babel-plugin-globals/blob/37499200e1c34a2bf86add2910cc31dd66f2a8a7/index.js#L51-L72 | train |
mairatma/babel-plugin-globals | index.js | getGlobalExpression | function getGlobalExpression(state, filePath, name, opt_isWildcard) {
assertFilenameRequired(state.file.opts.filename);
var globalName = state.opts.globalName;
var id;
if (typeof globalName === 'function') {
id = globalName(state, filePath, name, opt_isWildcard);
}
else {
if (name || opt_isWildcard) {
globalName += 'Named';
}
filePath = path.resolve(path.dirname(state.file.opts.filename), filePath);
var splitPath = filePath.split(path.sep);
var moduleName = splitPath[splitPath.length - 1];
id = 'this.' + globalName + '.' + moduleName + (name && name !== true ? '.' + name : '');
}
var parts = id.split('.');
var expr = t.identifier(parts[0]);
for (var i = 1; i < parts.length; i++) {
expr = t.memberExpression(expr, t.stringLiteral(parts[i]), true);
}
return expr;
} | javascript | function getGlobalExpression(state, filePath, name, opt_isWildcard) {
assertFilenameRequired(state.file.opts.filename);
var globalName = state.opts.globalName;
var id;
if (typeof globalName === 'function') {
id = globalName(state, filePath, name, opt_isWildcard);
}
else {
if (name || opt_isWildcard) {
globalName += 'Named';
}
filePath = path.resolve(path.dirname(state.file.opts.filename), filePath);
var splitPath = filePath.split(path.sep);
var moduleName = splitPath[splitPath.length - 1];
id = 'this.' + globalName + '.' + moduleName + (name && name !== true ? '.' + name : '');
}
var parts = id.split('.');
var expr = t.identifier(parts[0]);
for (var i = 1; i < parts.length; i++) {
expr = t.memberExpression(expr, t.stringLiteral(parts[i]), true);
}
return expr;
} | [
"function",
"getGlobalExpression",
"(",
"state",
",",
"filePath",
",",
"name",
",",
"opt_isWildcard",
")",
"{",
"assertFilenameRequired",
"(",
"state",
".",
"file",
".",
"opts",
".",
"filename",
")",
";",
"var",
"globalName",
"=",
"state",
".",
"opts",
".",
"globalName",
";",
"var",
"id",
";",
"if",
"(",
"typeof",
"globalName",
"===",
"'function'",
")",
"{",
"id",
"=",
"globalName",
"(",
"state",
",",
"filePath",
",",
"name",
",",
"opt_isWildcard",
")",
";",
"}",
"else",
"{",
"if",
"(",
"name",
"||",
"opt_isWildcard",
")",
"{",
"globalName",
"+=",
"'Named'",
";",
"}",
"filePath",
"=",
"path",
".",
"resolve",
"(",
"path",
".",
"dirname",
"(",
"state",
".",
"file",
".",
"opts",
".",
"filename",
")",
",",
"filePath",
")",
";",
"var",
"splitPath",
"=",
"filePath",
".",
"split",
"(",
"path",
".",
"sep",
")",
";",
"var",
"moduleName",
"=",
"splitPath",
"[",
"splitPath",
".",
"length",
"-",
"1",
"]",
";",
"id",
"=",
"'this.'",
"+",
"globalName",
"+",
"'.'",
"+",
"moduleName",
"+",
"(",
"name",
"&&",
"name",
"!==",
"true",
"?",
"'.'",
"+",
"name",
":",
"''",
")",
";",
"}",
"var",
"parts",
"=",
"id",
".",
"split",
"(",
"'.'",
")",
";",
"var",
"expr",
"=",
"t",
".",
"identifier",
"(",
"parts",
"[",
"0",
"]",
")",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"parts",
".",
"length",
";",
"i",
"++",
")",
"{",
"expr",
"=",
"t",
".",
"memberExpression",
"(",
"expr",
",",
"t",
".",
"stringLiteral",
"(",
"parts",
"[",
"i",
"]",
")",
",",
"true",
")",
";",
"}",
"return",
"expr",
";",
"}"
]
| Gets the global identifier for the given information.
@param {!Object} state This plugin's current state object.
@param {string} filePath The path of the module.
@param {?string} name The name of the variable being imported or exported from
the module.
@param {boolean=} opt_isWildcard If the import or export declaration is using a wildcard.
@return {!MemberExpression} | [
"Gets",
"the",
"global",
"identifier",
"for",
"the",
"given",
"information",
"."
]
| 37499200e1c34a2bf86add2910cc31dd66f2a8a7 | https://github.com/mairatma/babel-plugin-globals/blob/37499200e1c34a2bf86add2910cc31dd66f2a8a7/index.js#L96-L121 | train |
mairatma/babel-plugin-globals | index.js | removeExtensions | function removeExtensions(filename) {
var extension = path.extname(filename);
while (extension !== '') {
filename = path.basename(filename, extension);
extension = path.extname(filename);
}
return filename;
} | javascript | function removeExtensions(filename) {
var extension = path.extname(filename);
while (extension !== '') {
filename = path.basename(filename, extension);
extension = path.extname(filename);
}
return filename;
} | [
"function",
"removeExtensions",
"(",
"filename",
")",
"{",
"var",
"extension",
"=",
"path",
".",
"extname",
"(",
"filename",
")",
";",
"while",
"(",
"extension",
"!==",
"''",
")",
"{",
"filename",
"=",
"path",
".",
"basename",
"(",
"filename",
",",
"extension",
")",
";",
"extension",
"=",
"path",
".",
"extname",
"(",
"filename",
")",
";",
"}",
"return",
"filename",
";",
"}"
]
| Removes all extensions from the given filename.
@param {string} filename
@return {string} | [
"Removes",
"all",
"extensions",
"from",
"the",
"given",
"filename",
"."
]
| 37499200e1c34a2bf86add2910cc31dd66f2a8a7 | https://github.com/mairatma/babel-plugin-globals/blob/37499200e1c34a2bf86add2910cc31dd66f2a8a7/index.js#L128-L135 | train |
mairatma/babel-plugin-globals | index.js | function(nodePath) {
createdGlobals = {};
filenameNoExtCache = null;
var node = nodePath.node;
var contents = node.body;
node.body = [t.expressionStatement(t.callExpression(
t.memberExpression(
t.functionExpression(null, [], t.blockStatement(contents)),
t.identifier('call'),
false
),
[t.identifier('this')]
))];
} | javascript | function(nodePath) {
createdGlobals = {};
filenameNoExtCache = null;
var node = nodePath.node;
var contents = node.body;
node.body = [t.expressionStatement(t.callExpression(
t.memberExpression(
t.functionExpression(null, [], t.blockStatement(contents)),
t.identifier('call'),
false
),
[t.identifier('this')]
))];
} | [
"function",
"(",
"nodePath",
")",
"{",
"createdGlobals",
"=",
"{",
"}",
";",
"filenameNoExtCache",
"=",
"null",
";",
"var",
"node",
"=",
"nodePath",
".",
"node",
";",
"var",
"contents",
"=",
"node",
".",
"body",
";",
"node",
".",
"body",
"=",
"[",
"t",
".",
"expressionStatement",
"(",
"t",
".",
"callExpression",
"(",
"t",
".",
"memberExpression",
"(",
"t",
".",
"functionExpression",
"(",
"null",
",",
"[",
"]",
",",
"t",
".",
"blockStatement",
"(",
"contents",
")",
")",
",",
"t",
".",
"identifier",
"(",
"'call'",
")",
",",
"false",
")",
",",
"[",
"t",
".",
"identifier",
"(",
"'this'",
")",
"]",
")",
")",
"]",
";",
"}"
]
| Wraps the program body in a closure, protecting local variables.
@param {!NodePath} nodePath | [
"Wraps",
"the",
"program",
"body",
"in",
"a",
"closure",
"protecting",
"local",
"variables",
"."
]
| 37499200e1c34a2bf86add2910cc31dd66f2a8a7 | https://github.com/mairatma/babel-plugin-globals/blob/37499200e1c34a2bf86add2910cc31dd66f2a8a7/index.js#L143-L157 | train |
|
mairatma/babel-plugin-globals | index.js | function(nodePath, state) {
var replacements = [];
if ( nodePath.node.source.value.match(/^[\./]/) ) {
nodePath.node.specifiers.forEach(function(specifier) {
var expr = getGlobalExpression(
state,
removeExtensions(nodePath.node.source.value),
specifier.imported ? specifier.imported.name : null,
t.isImportNamespaceSpecifier(specifier)
);
replacements.push(t.variableDeclaration('var', [
t.variableDeclarator(specifier.local, expr)
]));
});
}
nodePath.replaceWithMultiple(replacements);
} | javascript | function(nodePath, state) {
var replacements = [];
if ( nodePath.node.source.value.match(/^[\./]/) ) {
nodePath.node.specifiers.forEach(function(specifier) {
var expr = getGlobalExpression(
state,
removeExtensions(nodePath.node.source.value),
specifier.imported ? specifier.imported.name : null,
t.isImportNamespaceSpecifier(specifier)
);
replacements.push(t.variableDeclaration('var', [
t.variableDeclarator(specifier.local, expr)
]));
});
}
nodePath.replaceWithMultiple(replacements);
} | [
"function",
"(",
"nodePath",
",",
"state",
")",
"{",
"var",
"replacements",
"=",
"[",
"]",
";",
"if",
"(",
"nodePath",
".",
"node",
".",
"source",
".",
"value",
".",
"match",
"(",
"/",
"^[\\./]",
"/",
")",
")",
"{",
"nodePath",
".",
"node",
".",
"specifiers",
".",
"forEach",
"(",
"function",
"(",
"specifier",
")",
"{",
"var",
"expr",
"=",
"getGlobalExpression",
"(",
"state",
",",
"removeExtensions",
"(",
"nodePath",
".",
"node",
".",
"source",
".",
"value",
")",
",",
"specifier",
".",
"imported",
"?",
"specifier",
".",
"imported",
".",
"name",
":",
"null",
",",
"t",
".",
"isImportNamespaceSpecifier",
"(",
"specifier",
")",
")",
";",
"replacements",
".",
"push",
"(",
"t",
".",
"variableDeclaration",
"(",
"'var'",
",",
"[",
"t",
".",
"variableDeclarator",
"(",
"specifier",
".",
"local",
",",
"expr",
")",
"]",
")",
")",
";",
"}",
")",
";",
"}",
"nodePath",
".",
"replaceWithMultiple",
"(",
"replacements",
")",
";",
"}"
]
| Replaces import declarations with assignments from global to local variables.
@param {!NodePath} nodePath
@param {!Object} state | [
"Replaces",
"import",
"declarations",
"with",
"assignments",
"from",
"global",
"to",
"local",
"variables",
"."
]
| 37499200e1c34a2bf86add2910cc31dd66f2a8a7 | https://github.com/mairatma/babel-plugin-globals/blob/37499200e1c34a2bf86add2910cc31dd66f2a8a7/index.js#L164-L181 | train |
|
mairatma/babel-plugin-globals | index.js | function(nodePath, state) {
var replacements = [];
var expr = getGlobalExpression(state, getFilenameNoExt(state.file.opts.filename));
var expression = nodePath.node.declaration;
if (expression.id &&
(t.isFunctionDeclaration(expression) || t.isClassDeclaration(expression))) {
replacements.push(expression);
expression = expression.id;
}
assignToGlobal(expr, replacements, expression);
nodePath.replaceWithMultiple(replacements);
} | javascript | function(nodePath, state) {
var replacements = [];
var expr = getGlobalExpression(state, getFilenameNoExt(state.file.opts.filename));
var expression = nodePath.node.declaration;
if (expression.id &&
(t.isFunctionDeclaration(expression) || t.isClassDeclaration(expression))) {
replacements.push(expression);
expression = expression.id;
}
assignToGlobal(expr, replacements, expression);
nodePath.replaceWithMultiple(replacements);
} | [
"function",
"(",
"nodePath",
",",
"state",
")",
"{",
"var",
"replacements",
"=",
"[",
"]",
";",
"var",
"expr",
"=",
"getGlobalExpression",
"(",
"state",
",",
"getFilenameNoExt",
"(",
"state",
".",
"file",
".",
"opts",
".",
"filename",
")",
")",
";",
"var",
"expression",
"=",
"nodePath",
".",
"node",
".",
"declaration",
";",
"if",
"(",
"expression",
".",
"id",
"&&",
"(",
"t",
".",
"isFunctionDeclaration",
"(",
"expression",
")",
"||",
"t",
".",
"isClassDeclaration",
"(",
"expression",
")",
")",
")",
"{",
"replacements",
".",
"push",
"(",
"expression",
")",
";",
"expression",
"=",
"expression",
".",
"id",
";",
"}",
"assignToGlobal",
"(",
"expr",
",",
"replacements",
",",
"expression",
")",
";",
"nodePath",
".",
"replaceWithMultiple",
"(",
"replacements",
")",
";",
"}"
]
| Replaces default export declarations with assignments to global variables.
@param {!NodePath} nodePath
@param {!Object} state | [
"Replaces",
"default",
"export",
"declarations",
"with",
"assignments",
"to",
"global",
"variables",
"."
]
| 37499200e1c34a2bf86add2910cc31dd66f2a8a7 | https://github.com/mairatma/babel-plugin-globals/blob/37499200e1c34a2bf86add2910cc31dd66f2a8a7/index.js#L225-L236 | train |
|
mairatma/babel-plugin-globals | index.js | function(nodePath, state) {
var replacements = [];
var node = nodePath.node;
if (node.declaration) {
replacements.push(node.declaration);
if (t.isVariableDeclaration(node.declaration)) {
node.declaration.declarations.forEach(assignDeclarationToGlobal.bind(null, state, replacements));
} else {
assignDeclarationToGlobal(state, replacements, node.declaration);
}
} else {
node.specifiers.forEach(function(specifier) {
var exprToAssign = specifier.local;
if (node.source) {
var specifierName = specifier.local ? specifier.local.name : null;
exprToAssign = getGlobalExpression(state, node.source.value, specifierName);
}
var filenameNoExt = getFilenameNoExt(state.file.opts.filename);
var expr = getGlobalExpression(state, filenameNoExt, specifier.exported.name);
assignToGlobal(expr, replacements, exprToAssign);
});
}
nodePath.replaceWithMultiple(replacements);
} | javascript | function(nodePath, state) {
var replacements = [];
var node = nodePath.node;
if (node.declaration) {
replacements.push(node.declaration);
if (t.isVariableDeclaration(node.declaration)) {
node.declaration.declarations.forEach(assignDeclarationToGlobal.bind(null, state, replacements));
} else {
assignDeclarationToGlobal(state, replacements, node.declaration);
}
} else {
node.specifiers.forEach(function(specifier) {
var exprToAssign = specifier.local;
if (node.source) {
var specifierName = specifier.local ? specifier.local.name : null;
exprToAssign = getGlobalExpression(state, node.source.value, specifierName);
}
var filenameNoExt = getFilenameNoExt(state.file.opts.filename);
var expr = getGlobalExpression(state, filenameNoExt, specifier.exported.name);
assignToGlobal(expr, replacements, exprToAssign);
});
}
nodePath.replaceWithMultiple(replacements);
} | [
"function",
"(",
"nodePath",
",",
"state",
")",
"{",
"var",
"replacements",
"=",
"[",
"]",
";",
"var",
"node",
"=",
"nodePath",
".",
"node",
";",
"if",
"(",
"node",
".",
"declaration",
")",
"{",
"replacements",
".",
"push",
"(",
"node",
".",
"declaration",
")",
";",
"if",
"(",
"t",
".",
"isVariableDeclaration",
"(",
"node",
".",
"declaration",
")",
")",
"{",
"node",
".",
"declaration",
".",
"declarations",
".",
"forEach",
"(",
"assignDeclarationToGlobal",
".",
"bind",
"(",
"null",
",",
"state",
",",
"replacements",
")",
")",
";",
"}",
"else",
"{",
"assignDeclarationToGlobal",
"(",
"state",
",",
"replacements",
",",
"node",
".",
"declaration",
")",
";",
"}",
"}",
"else",
"{",
"node",
".",
"specifiers",
".",
"forEach",
"(",
"function",
"(",
"specifier",
")",
"{",
"var",
"exprToAssign",
"=",
"specifier",
".",
"local",
";",
"if",
"(",
"node",
".",
"source",
")",
"{",
"var",
"specifierName",
"=",
"specifier",
".",
"local",
"?",
"specifier",
".",
"local",
".",
"name",
":",
"null",
";",
"exprToAssign",
"=",
"getGlobalExpression",
"(",
"state",
",",
"node",
".",
"source",
".",
"value",
",",
"specifierName",
")",
";",
"}",
"var",
"filenameNoExt",
"=",
"getFilenameNoExt",
"(",
"state",
".",
"file",
".",
"opts",
".",
"filename",
")",
";",
"var",
"expr",
"=",
"getGlobalExpression",
"(",
"state",
",",
"filenameNoExt",
",",
"specifier",
".",
"exported",
".",
"name",
")",
";",
"assignToGlobal",
"(",
"expr",
",",
"replacements",
",",
"exprToAssign",
")",
";",
"}",
")",
";",
"}",
"nodePath",
".",
"replaceWithMultiple",
"(",
"replacements",
")",
";",
"}"
]
| Replaces named export declarations with assignments to global variables.
@param {!NodePath} nodePath
@param {!Object} state | [
"Replaces",
"named",
"export",
"declarations",
"with",
"assignments",
"to",
"global",
"variables",
"."
]
| 37499200e1c34a2bf86add2910cc31dd66f2a8a7 | https://github.com/mairatma/babel-plugin-globals/blob/37499200e1c34a2bf86add2910cc31dd66f2a8a7/index.js#L243-L268 | train |
|
ivnivnch/angular-parse | src/Parse.js | defineAttributes | function defineAttributes(object, attributes) {
if (object instanceof Parse.Object) {
if (!(attributes instanceof Array)) attributes = Array.prototype.slice.call(arguments, 1);
attributes.forEach(function (attribute) {
Object.defineProperty(object, attribute, {
get: function () {
return this.get(attribute);
},
set: function (value) {
this.set(attribute, value);
},
configurable: true,
enumerable: true
});
});
} else if (typeof object == 'function') {
return defineAttributes(object.prototype, attributes)
} else {
if (object instanceof Array) attributes = object;
else attributes = Array.prototype.slice.call(arguments, 0);
return function defineAttributesDecorator(target) {
defineAttributes(target, attributes);
}
}
} | javascript | function defineAttributes(object, attributes) {
if (object instanceof Parse.Object) {
if (!(attributes instanceof Array)) attributes = Array.prototype.slice.call(arguments, 1);
attributes.forEach(function (attribute) {
Object.defineProperty(object, attribute, {
get: function () {
return this.get(attribute);
},
set: function (value) {
this.set(attribute, value);
},
configurable: true,
enumerable: true
});
});
} else if (typeof object == 'function') {
return defineAttributes(object.prototype, attributes)
} else {
if (object instanceof Array) attributes = object;
else attributes = Array.prototype.slice.call(arguments, 0);
return function defineAttributesDecorator(target) {
defineAttributes(target, attributes);
}
}
} | [
"function",
"defineAttributes",
"(",
"object",
",",
"attributes",
")",
"{",
"if",
"(",
"object",
"instanceof",
"Parse",
".",
"Object",
")",
"{",
"if",
"(",
"!",
"(",
"attributes",
"instanceof",
"Array",
")",
")",
"attributes",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
";",
"attributes",
".",
"forEach",
"(",
"function",
"(",
"attribute",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"object",
",",
"attribute",
",",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"this",
".",
"get",
"(",
"attribute",
")",
";",
"}",
",",
"set",
":",
"function",
"(",
"value",
")",
"{",
"this",
".",
"set",
"(",
"attribute",
",",
"value",
")",
";",
"}",
",",
"configurable",
":",
"true",
",",
"enumerable",
":",
"true",
"}",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"object",
"==",
"'function'",
")",
"{",
"return",
"defineAttributes",
"(",
"object",
".",
"prototype",
",",
"attributes",
")",
"}",
"else",
"{",
"if",
"(",
"object",
"instanceof",
"Array",
")",
"attributes",
"=",
"object",
";",
"else",
"attributes",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"0",
")",
";",
"return",
"function",
"defineAttributesDecorator",
"(",
"target",
")",
"{",
"defineAttributes",
"(",
"target",
",",
"attributes",
")",
";",
"}",
"}",
"}"
]
| Defines getters and setters for the attributes
of the given object or function prototype.
Or create a decorator that defines getters
and setters for the subclass Parse.Object.
@param {Object|Function|String|String[]} object
@param {...String|String[]=} attributes
@returns {*} | [
"Defines",
"getters",
"and",
"setters",
"for",
"the",
"attributes",
"of",
"the",
"given",
"object",
"or",
"function",
"prototype",
".",
"Or",
"create",
"a",
"decorator",
"that",
"defines",
"getters",
"and",
"setters",
"for",
"the",
"subclass",
"Parse",
".",
"Object",
"."
]
| 27a8cbe1d348c168a898f05a53cd69f6dad67671 | https://github.com/ivnivnch/angular-parse/blob/27a8cbe1d348c168a898f05a53cd69f6dad67671/src/Parse.js#L23-L47 | train |
ivnivnch/angular-parse | src/Parse.js | wrapParsePromise | function wrapParsePromise(promise, parsePromise) {
['_rejected', '_rejectedCallbacks', '_resolved', '_resolvedCallbacks', '_result', 'reject', 'resolve']
.forEach(function (prop) {
promise[prop] = parsePromise[prop];
});
['_continueWith', '_thenRunCallbacks', 'always', 'done', 'fail'].forEach(function (method) {
promise[method] = wrap(parsePromise[method]);
});
['then', 'catch'].forEach(function (method) {
var func = promise[method];
promise[method] = function wrappedAngularPromise() {
var args = Array.prototype.slice.call(arguments, 0);
var promise = func.apply(this, args);
wrapParsePromise(promise, parsePromise);
return promise;
};
});
return promise;
} | javascript | function wrapParsePromise(promise, parsePromise) {
['_rejected', '_rejectedCallbacks', '_resolved', '_resolvedCallbacks', '_result', 'reject', 'resolve']
.forEach(function (prop) {
promise[prop] = parsePromise[prop];
});
['_continueWith', '_thenRunCallbacks', 'always', 'done', 'fail'].forEach(function (method) {
promise[method] = wrap(parsePromise[method]);
});
['then', 'catch'].forEach(function (method) {
var func = promise[method];
promise[method] = function wrappedAngularPromise() {
var args = Array.prototype.slice.call(arguments, 0);
var promise = func.apply(this, args);
wrapParsePromise(promise, parsePromise);
return promise;
};
});
return promise;
} | [
"function",
"wrapParsePromise",
"(",
"promise",
",",
"parsePromise",
")",
"{",
"[",
"'_rejected'",
",",
"'_rejectedCallbacks'",
",",
"'_resolved'",
",",
"'_resolvedCallbacks'",
",",
"'_result'",
",",
"'reject'",
",",
"'resolve'",
"]",
".",
"forEach",
"(",
"function",
"(",
"prop",
")",
"{",
"promise",
"[",
"prop",
"]",
"=",
"parsePromise",
"[",
"prop",
"]",
";",
"}",
")",
";",
"[",
"'_continueWith'",
",",
"'_thenRunCallbacks'",
",",
"'always'",
",",
"'done'",
",",
"'fail'",
"]",
".",
"forEach",
"(",
"function",
"(",
"method",
")",
"{",
"promise",
"[",
"method",
"]",
"=",
"wrap",
"(",
"parsePromise",
"[",
"method",
"]",
")",
";",
"}",
")",
";",
"[",
"'then'",
",",
"'catch'",
"]",
".",
"forEach",
"(",
"function",
"(",
"method",
")",
"{",
"var",
"func",
"=",
"promise",
"[",
"method",
"]",
";",
"promise",
"[",
"method",
"]",
"=",
"function",
"wrappedAngularPromise",
"(",
")",
"{",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"0",
")",
";",
"var",
"promise",
"=",
"func",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"wrapParsePromise",
"(",
"promise",
",",
"parsePromise",
")",
";",
"return",
"promise",
";",
"}",
";",
"}",
")",
";",
"return",
"promise",
";",
"}"
]
| Wraps Promise.
@param {Object} promise
@param {Object} parsePromise
@returns {Object} | [
"Wraps",
"Promise",
"."
]
| 27a8cbe1d348c168a898f05a53cd69f6dad67671 | https://github.com/ivnivnch/angular-parse/blob/27a8cbe1d348c168a898f05a53cd69f6dad67671/src/Parse.js#L85-L106 | train |
ivnivnch/angular-parse | src/Parse.js | wrap | function wrap(func) {
return function wrappedParsePromise() {
var args = Array.prototype.slice.call(arguments, 0);
var parsePromise = func.apply(this, args);
var promise = $q(parsePromise.then.bind(parsePromise));
wrapParsePromise(promise, parsePromise);
return promise;
};
} | javascript | function wrap(func) {
return function wrappedParsePromise() {
var args = Array.prototype.slice.call(arguments, 0);
var parsePromise = func.apply(this, args);
var promise = $q(parsePromise.then.bind(parsePromise));
wrapParsePromise(promise, parsePromise);
return promise;
};
} | [
"function",
"wrap",
"(",
"func",
")",
"{",
"return",
"function",
"wrappedParsePromise",
"(",
")",
"{",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"0",
")",
";",
"var",
"parsePromise",
"=",
"func",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"var",
"promise",
"=",
"$q",
"(",
"parsePromise",
".",
"then",
".",
"bind",
"(",
"parsePromise",
")",
")",
";",
"wrapParsePromise",
"(",
"promise",
",",
"parsePromise",
")",
";",
"return",
"promise",
";",
"}",
";",
"}"
]
| Wraps function.
@param {Function} func Function that returns
[Parse.Promise]{@link https://parse.com/docs/js/api/classes/Parse.Promise.html}.
@returns {Function} Function that returns $q promises. | [
"Wraps",
"function",
"."
]
| 27a8cbe1d348c168a898f05a53cd69f6dad67671 | https://github.com/ivnivnch/angular-parse/blob/27a8cbe1d348c168a898f05a53cd69f6dad67671/src/Parse.js#L115-L123 | train |
ivnivnch/angular-parse | src/Parse.js | wrapObject | function wrapObject(object, methods) {
if (!(methods instanceof Array)) methods = Array.prototype.slice.call(arguments, 1);
methods.forEach(function (method) {
object[method] = wrap(object[method]);
});
} | javascript | function wrapObject(object, methods) {
if (!(methods instanceof Array)) methods = Array.prototype.slice.call(arguments, 1);
methods.forEach(function (method) {
object[method] = wrap(object[method]);
});
} | [
"function",
"wrapObject",
"(",
"object",
",",
"methods",
")",
"{",
"if",
"(",
"!",
"(",
"methods",
"instanceof",
"Array",
")",
")",
"methods",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
";",
"methods",
".",
"forEach",
"(",
"function",
"(",
"method",
")",
"{",
"object",
"[",
"method",
"]",
"=",
"wrap",
"(",
"object",
"[",
"method",
"]",
")",
";",
"}",
")",
";",
"}"
]
| Wraps object.
@param {Object} object
@param {...String|String[]=} methods | [
"Wraps",
"object",
"."
]
| 27a8cbe1d348c168a898f05a53cd69f6dad67671 | https://github.com/ivnivnch/angular-parse/blob/27a8cbe1d348c168a898f05a53cd69f6dad67671/src/Parse.js#L131-L136 | train |
emmetio/abbreviation | lib/attribute.js | eatUnquoted | function eatUnquoted(stream) {
const start = stream.pos;
if (stream.eatWhile(isUnquoted)) {
stream.start = start;
return true;
}
} | javascript | function eatUnquoted(stream) {
const start = stream.pos;
if (stream.eatWhile(isUnquoted)) {
stream.start = start;
return true;
}
} | [
"function",
"eatUnquoted",
"(",
"stream",
")",
"{",
"const",
"start",
"=",
"stream",
".",
"pos",
";",
"if",
"(",
"stream",
".",
"eatWhile",
"(",
"isUnquoted",
")",
")",
"{",
"stream",
".",
"start",
"=",
"start",
";",
"return",
"true",
";",
"}",
"}"
]
| Eats token that can be an unquoted value from given stream
@param {StreamReader} stream
@return {Boolean} | [
"Eats",
"token",
"that",
"can",
"be",
"an",
"unquoted",
"value",
"from",
"given",
"stream"
]
| 9b1dde05eedccb7d824bd6d67d06921dfab524cd | https://github.com/emmetio/abbreviation/blob/9b1dde05eedccb7d824bd6d67d06921dfab524cd/lib/attribute.js#L112-L118 | train |
fzaninotto/cron-as-a-service | app/web/public/javascripts/jquery.form.js | doSubmit | function doSubmit() {
// make sure form attrs are set
var t = $form.attr('target'), a = $form.attr('action');
// update form attrs in IE friendly way
form.setAttribute('target',id);
if (!method) {
form.setAttribute('method', 'POST');
}
if (a != s.url) {
form.setAttribute('action', s.url);
}
// ie borks in some cases when setting encoding
if (! s.skipEncodingOverride && (!method || /post/i.test(method))) {
$form.attr({
encoding: 'multipart/form-data',
enctype: 'multipart/form-data'
});
}
// support timout
if (s.timeout) {
timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout);
}
// look for server aborts
function checkState() {
try {
var state = getDoc(io).readyState;
log('state = ' + state);
if (state && state.toLowerCase() == 'uninitialized')
setTimeout(checkState,50);
}
catch(e) {
log('Server abort: ' , e, ' (', e.name, ')');
cb(SERVER_ABORT);
if (timeoutHandle)
clearTimeout(timeoutHandle);
timeoutHandle = undefined;
}
}
// add "extra" data to form if provided in options
var extraInputs = [];
try {
if (s.extraData) {
for (var n in s.extraData) {
if (s.extraData.hasOwnProperty(n)) {
extraInputs.push(
$('<input type="hidden" name="'+n+'">').attr('value',s.extraData[n])
.appendTo(form)[0]);
}
}
}
if (!s.iframeTarget) {
// add iframe to doc and submit the form
$io.appendTo('body');
if (io.attachEvent)
io.attachEvent('onload', cb);
else
io.addEventListener('load', cb, false);
}
setTimeout(checkState,15);
form.submit();
}
finally {
// reset attrs and remove "extra" input elements
form.setAttribute('action',a);
if(t) {
form.setAttribute('target', t);
} else {
$form.removeAttr('target');
}
$(extraInputs).remove();
}
} | javascript | function doSubmit() {
// make sure form attrs are set
var t = $form.attr('target'), a = $form.attr('action');
// update form attrs in IE friendly way
form.setAttribute('target',id);
if (!method) {
form.setAttribute('method', 'POST');
}
if (a != s.url) {
form.setAttribute('action', s.url);
}
// ie borks in some cases when setting encoding
if (! s.skipEncodingOverride && (!method || /post/i.test(method))) {
$form.attr({
encoding: 'multipart/form-data',
enctype: 'multipart/form-data'
});
}
// support timout
if (s.timeout) {
timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout);
}
// look for server aborts
function checkState() {
try {
var state = getDoc(io).readyState;
log('state = ' + state);
if (state && state.toLowerCase() == 'uninitialized')
setTimeout(checkState,50);
}
catch(e) {
log('Server abort: ' , e, ' (', e.name, ')');
cb(SERVER_ABORT);
if (timeoutHandle)
clearTimeout(timeoutHandle);
timeoutHandle = undefined;
}
}
// add "extra" data to form if provided in options
var extraInputs = [];
try {
if (s.extraData) {
for (var n in s.extraData) {
if (s.extraData.hasOwnProperty(n)) {
extraInputs.push(
$('<input type="hidden" name="'+n+'">').attr('value',s.extraData[n])
.appendTo(form)[0]);
}
}
}
if (!s.iframeTarget) {
// add iframe to doc and submit the form
$io.appendTo('body');
if (io.attachEvent)
io.attachEvent('onload', cb);
else
io.addEventListener('load', cb, false);
}
setTimeout(checkState,15);
form.submit();
}
finally {
// reset attrs and remove "extra" input elements
form.setAttribute('action',a);
if(t) {
form.setAttribute('target', t);
} else {
$form.removeAttr('target');
}
$(extraInputs).remove();
}
} | [
"function",
"doSubmit",
"(",
")",
"{",
"var",
"t",
"=",
"$form",
".",
"attr",
"(",
"'target'",
")",
",",
"a",
"=",
"$form",
".",
"attr",
"(",
"'action'",
")",
";",
"form",
".",
"setAttribute",
"(",
"'target'",
",",
"id",
")",
";",
"if",
"(",
"!",
"method",
")",
"{",
"form",
".",
"setAttribute",
"(",
"'method'",
",",
"'POST'",
")",
";",
"}",
"if",
"(",
"a",
"!=",
"s",
".",
"url",
")",
"{",
"form",
".",
"setAttribute",
"(",
"'action'",
",",
"s",
".",
"url",
")",
";",
"}",
"if",
"(",
"!",
"s",
".",
"skipEncodingOverride",
"&&",
"(",
"!",
"method",
"||",
"/",
"post",
"/",
"i",
".",
"test",
"(",
"method",
")",
")",
")",
"{",
"$form",
".",
"attr",
"(",
"{",
"encoding",
":",
"'multipart/form-data'",
",",
"enctype",
":",
"'multipart/form-data'",
"}",
")",
";",
"}",
"if",
"(",
"s",
".",
"timeout",
")",
"{",
"timeoutHandle",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"timedOut",
"=",
"true",
";",
"cb",
"(",
"CLIENT_TIMEOUT_ABORT",
")",
";",
"}",
",",
"s",
".",
"timeout",
")",
";",
"}",
"function",
"checkState",
"(",
")",
"{",
"try",
"{",
"var",
"state",
"=",
"getDoc",
"(",
"io",
")",
".",
"readyState",
";",
"log",
"(",
"'state = '",
"+",
"state",
")",
";",
"if",
"(",
"state",
"&&",
"state",
".",
"toLowerCase",
"(",
")",
"==",
"'uninitialized'",
")",
"setTimeout",
"(",
"checkState",
",",
"50",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"log",
"(",
"'Server abort: '",
",",
"e",
",",
"' ('",
",",
"e",
".",
"name",
",",
"')'",
")",
";",
"cb",
"(",
"SERVER_ABORT",
")",
";",
"if",
"(",
"timeoutHandle",
")",
"clearTimeout",
"(",
"timeoutHandle",
")",
";",
"timeoutHandle",
"=",
"undefined",
";",
"}",
"}",
"var",
"extraInputs",
"=",
"[",
"]",
";",
"try",
"{",
"if",
"(",
"s",
".",
"extraData",
")",
"{",
"for",
"(",
"var",
"n",
"in",
"s",
".",
"extraData",
")",
"{",
"if",
"(",
"s",
".",
"extraData",
".",
"hasOwnProperty",
"(",
"n",
")",
")",
"{",
"extraInputs",
".",
"push",
"(",
"$",
"(",
"'<input type=\"hidden\" name=\"'",
"+",
"n",
"+",
"'\">'",
")",
".",
"attr",
"(",
"'value'",
",",
"s",
".",
"extraData",
"[",
"n",
"]",
")",
".",
"appendTo",
"(",
"form",
")",
"[",
"0",
"]",
")",
";",
"}",
"}",
"}",
"if",
"(",
"!",
"s",
".",
"iframeTarget",
")",
"{",
"$io",
".",
"appendTo",
"(",
"'body'",
")",
";",
"if",
"(",
"io",
".",
"attachEvent",
")",
"io",
".",
"attachEvent",
"(",
"'onload'",
",",
"cb",
")",
";",
"else",
"io",
".",
"addEventListener",
"(",
"'load'",
",",
"cb",
",",
"false",
")",
";",
"}",
"setTimeout",
"(",
"checkState",
",",
"15",
")",
";",
"form",
".",
"submit",
"(",
")",
";",
"}",
"finally",
"{",
"form",
".",
"setAttribute",
"(",
"'action'",
",",
"a",
")",
";",
"if",
"(",
"t",
")",
"{",
"form",
".",
"setAttribute",
"(",
"'target'",
",",
"t",
")",
";",
"}",
"else",
"{",
"$form",
".",
"removeAttr",
"(",
"'target'",
")",
";",
"}",
"$",
"(",
"extraInputs",
")",
".",
"remove",
"(",
")",
";",
"}",
"}"
]
| take a breath so that pending repaints get some cpu time before the upload starts | [
"take",
"a",
"breath",
"so",
"that",
"pending",
"repaints",
"get",
"some",
"cpu",
"time",
"before",
"the",
"upload",
"starts"
]
| 35334898730d44c96c1f7b4c235295c48fb992ab | https://github.com/fzaninotto/cron-as-a-service/blob/35334898730d44c96c1f7b4c235295c48fb992ab/app/web/public/javascripts/jquery.form.js#L380-L457 | train |
fzaninotto/cron-as-a-service | app/web/public/javascripts/jquery.form.js | checkState | function checkState() {
try {
var state = getDoc(io).readyState;
log('state = ' + state);
if (state && state.toLowerCase() == 'uninitialized')
setTimeout(checkState,50);
}
catch(e) {
log('Server abort: ' , e, ' (', e.name, ')');
cb(SERVER_ABORT);
if (timeoutHandle)
clearTimeout(timeoutHandle);
timeoutHandle = undefined;
}
} | javascript | function checkState() {
try {
var state = getDoc(io).readyState;
log('state = ' + state);
if (state && state.toLowerCase() == 'uninitialized')
setTimeout(checkState,50);
}
catch(e) {
log('Server abort: ' , e, ' (', e.name, ')');
cb(SERVER_ABORT);
if (timeoutHandle)
clearTimeout(timeoutHandle);
timeoutHandle = undefined;
}
} | [
"function",
"checkState",
"(",
")",
"{",
"try",
"{",
"var",
"state",
"=",
"getDoc",
"(",
"io",
")",
".",
"readyState",
";",
"log",
"(",
"'state = '",
"+",
"state",
")",
";",
"if",
"(",
"state",
"&&",
"state",
".",
"toLowerCase",
"(",
")",
"==",
"'uninitialized'",
")",
"setTimeout",
"(",
"checkState",
",",
"50",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"log",
"(",
"'Server abort: '",
",",
"e",
",",
"' ('",
",",
"e",
".",
"name",
",",
"')'",
")",
";",
"cb",
"(",
"SERVER_ABORT",
")",
";",
"if",
"(",
"timeoutHandle",
")",
"clearTimeout",
"(",
"timeoutHandle",
")",
";",
"timeoutHandle",
"=",
"undefined",
";",
"}",
"}"
]
| look for server aborts | [
"look",
"for",
"server",
"aborts"
]
| 35334898730d44c96c1f7b4c235295c48fb992ab | https://github.com/fzaninotto/cron-as-a-service/blob/35334898730d44c96c1f7b4c235295c48fb992ab/app/web/public/javascripts/jquery.form.js#L407-L421 | train |
fzaninotto/cron-as-a-service | app/web/public/javascripts/jquery.form.js | doAjaxSubmit | function doAjaxSubmit(e) {
/*jshint validthis:true */
var options = e.data;
if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
e.preventDefault();
$(this).ajaxSubmit(options);
}
} | javascript | function doAjaxSubmit(e) {
/*jshint validthis:true */
var options = e.data;
if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
e.preventDefault();
$(this).ajaxSubmit(options);
}
} | [
"function",
"doAjaxSubmit",
"(",
"e",
")",
"{",
"var",
"options",
"=",
"e",
".",
"data",
";",
"if",
"(",
"!",
"e",
".",
"isDefaultPrevented",
"(",
")",
")",
"{",
"e",
".",
"preventDefault",
"(",
")",
";",
"$",
"(",
"this",
")",
".",
"ajaxSubmit",
"(",
"options",
")",
";",
"}",
"}"
]
| private event handlers | [
"private",
"event",
"handlers"
]
| 35334898730d44c96c1f7b4c235295c48fb992ab | https://github.com/fzaninotto/cron-as-a-service/blob/35334898730d44c96c1f7b4c235295c48fb992ab/app/web/public/javascripts/jquery.form.js#L713-L720 | train |
daleeidd/postcss-define-property | index.js | function (properties, rule, options) {
var signature = rule.selector || rule.params;
var name = signature.match(customPropertyPattern).shift().replace(propertyKeyDelimiter, '').trim();
var parameters = signature.replace(customPropertyPattern, '').match(parametersPattern).map(function (parameter) {
return parameter.replace(options.syntax.parameter, options.syntax.variable);
});
var property = {
name: name,
parameters: parameters,
declarations: rule.nodes.map(function (node) {
return {
property: node.prop,
value: node.value,
// Parses variables that are also parameters. Ignores other variables for compatability with Sass variables.
// We only need the index of each parameter
variables: (node.value.match(variablesPattern) || [])
.filter(function (variable) {
return node.value.indexOf(variable) !== -1;
}).map(function (variable) {
return parameters.indexOf(variable);
})
};
})
};
properties[options.syntax.property + property.name + signatureSeparator + parameters.length] = property;
rule.remove();
} | javascript | function (properties, rule, options) {
var signature = rule.selector || rule.params;
var name = signature.match(customPropertyPattern).shift().replace(propertyKeyDelimiter, '').trim();
var parameters = signature.replace(customPropertyPattern, '').match(parametersPattern).map(function (parameter) {
return parameter.replace(options.syntax.parameter, options.syntax.variable);
});
var property = {
name: name,
parameters: parameters,
declarations: rule.nodes.map(function (node) {
return {
property: node.prop,
value: node.value,
// Parses variables that are also parameters. Ignores other variables for compatability with Sass variables.
// We only need the index of each parameter
variables: (node.value.match(variablesPattern) || [])
.filter(function (variable) {
return node.value.indexOf(variable) !== -1;
}).map(function (variable) {
return parameters.indexOf(variable);
})
};
})
};
properties[options.syntax.property + property.name + signatureSeparator + parameters.length] = property;
rule.remove();
} | [
"function",
"(",
"properties",
",",
"rule",
",",
"options",
")",
"{",
"var",
"signature",
"=",
"rule",
".",
"selector",
"||",
"rule",
".",
"params",
";",
"var",
"name",
"=",
"signature",
".",
"match",
"(",
"customPropertyPattern",
")",
".",
"shift",
"(",
")",
".",
"replace",
"(",
"propertyKeyDelimiter",
",",
"''",
")",
".",
"trim",
"(",
")",
";",
"var",
"parameters",
"=",
"signature",
".",
"replace",
"(",
"customPropertyPattern",
",",
"''",
")",
".",
"match",
"(",
"parametersPattern",
")",
".",
"map",
"(",
"function",
"(",
"parameter",
")",
"{",
"return",
"parameter",
".",
"replace",
"(",
"options",
".",
"syntax",
".",
"parameter",
",",
"options",
".",
"syntax",
".",
"variable",
")",
";",
"}",
")",
";",
"var",
"property",
"=",
"{",
"name",
":",
"name",
",",
"parameters",
":",
"parameters",
",",
"declarations",
":",
"rule",
".",
"nodes",
".",
"map",
"(",
"function",
"(",
"node",
")",
"{",
"return",
"{",
"property",
":",
"node",
".",
"prop",
",",
"value",
":",
"node",
".",
"value",
",",
"variables",
":",
"(",
"node",
".",
"value",
".",
"match",
"(",
"variablesPattern",
")",
"||",
"[",
"]",
")",
".",
"filter",
"(",
"function",
"(",
"variable",
")",
"{",
"return",
"node",
".",
"value",
".",
"indexOf",
"(",
"variable",
")",
"!==",
"-",
"1",
";",
"}",
")",
".",
"map",
"(",
"function",
"(",
"variable",
")",
"{",
"return",
"parameters",
".",
"indexOf",
"(",
"variable",
")",
";",
"}",
")",
"}",
";",
"}",
")",
"}",
";",
"properties",
"[",
"options",
".",
"syntax",
".",
"property",
"+",
"property",
".",
"name",
"+",
"signatureSeparator",
"+",
"parameters",
".",
"length",
"]",
"=",
"property",
";",
"rule",
".",
"remove",
"(",
")",
";",
"}"
]
| Adds a property definition to properties | [
"Adds",
"a",
"property",
"definition",
"to",
"properties"
]
| 8dbd84ea1e86cff37d96f5539f55e5dbaaa6d453 | https://github.com/daleeidd/postcss-define-property/blob/8dbd84ea1e86cff37d96f5539f55e5dbaaa6d453/index.js#L13-L41 | train |
|
daleeidd/postcss-define-property | index.js | function (customProperty, declaration) {
customProperty.declarations.forEach(function (customDeclaration) {
// No need to copy value here as replace will copy value
var value = customDeclaration.value;
// Replace parameter variables with user given values
customDeclaration.variables.forEach(function (variable) {
value = value.replace(customProperty.parameters[variable],
declaration.values[variable]);
});
// Using cloneBefore to insert declaration provides sourcemap support
declaration.cloneBefore({
prop: customDeclaration.property,
value: value
});
});
declaration.remove();
} | javascript | function (customProperty, declaration) {
customProperty.declarations.forEach(function (customDeclaration) {
// No need to copy value here as replace will copy value
var value = customDeclaration.value;
// Replace parameter variables with user given values
customDeclaration.variables.forEach(function (variable) {
value = value.replace(customProperty.parameters[variable],
declaration.values[variable]);
});
// Using cloneBefore to insert declaration provides sourcemap support
declaration.cloneBefore({
prop: customDeclaration.property,
value: value
});
});
declaration.remove();
} | [
"function",
"(",
"customProperty",
",",
"declaration",
")",
"{",
"customProperty",
".",
"declarations",
".",
"forEach",
"(",
"function",
"(",
"customDeclaration",
")",
"{",
"var",
"value",
"=",
"customDeclaration",
".",
"value",
";",
"customDeclaration",
".",
"variables",
".",
"forEach",
"(",
"function",
"(",
"variable",
")",
"{",
"value",
"=",
"value",
".",
"replace",
"(",
"customProperty",
".",
"parameters",
"[",
"variable",
"]",
",",
"declaration",
".",
"values",
"[",
"variable",
"]",
")",
";",
"}",
")",
";",
"declaration",
".",
"cloneBefore",
"(",
"{",
"prop",
":",
"customDeclaration",
".",
"property",
",",
"value",
":",
"value",
"}",
")",
";",
"}",
")",
";",
"declaration",
".",
"remove",
"(",
")",
";",
"}"
]
| Applies the custom property to the given declaration | [
"Applies",
"the",
"custom",
"property",
"to",
"the",
"given",
"declaration"
]
| 8dbd84ea1e86cff37d96f5539f55e5dbaaa6d453 | https://github.com/daleeidd/postcss-define-property/blob/8dbd84ea1e86cff37d96f5539f55e5dbaaa6d453/index.js#L44-L63 | train |
|
samuelcarreira/electron-shutdown-command | index.js | abort | function abort(options = {}) {
if (process.platform !== 'win32' && process.platform !== 'linux') {
throw new Error('Unsupported OS (only Windows and Linux are supported)!');
}
let cmdarguments = ['shutdown'];
if (process.platform === 'win32') {
cmdarguments.push('-a'); // abort
} else {
// linux
cmdarguments.push('-c'); // cancel a pending shutdown
}
executeCmd(cmdarguments, options.debug, options.quitapp);
} | javascript | function abort(options = {}) {
if (process.platform !== 'win32' && process.platform !== 'linux') {
throw new Error('Unsupported OS (only Windows and Linux are supported)!');
}
let cmdarguments = ['shutdown'];
if (process.platform === 'win32') {
cmdarguments.push('-a'); // abort
} else {
// linux
cmdarguments.push('-c'); // cancel a pending shutdown
}
executeCmd(cmdarguments, options.debug, options.quitapp);
} | [
"function",
"abort",
"(",
"options",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"process",
".",
"platform",
"!==",
"'win32'",
"&&",
"process",
".",
"platform",
"!==",
"'linux'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Unsupported OS (only Windows and Linux are supported)!'",
")",
";",
"}",
"let",
"cmdarguments",
"=",
"[",
"'shutdown'",
"]",
";",
"if",
"(",
"process",
".",
"platform",
"===",
"'win32'",
")",
"{",
"cmdarguments",
".",
"push",
"(",
"'-a'",
")",
";",
"}",
"else",
"{",
"cmdarguments",
".",
"push",
"(",
"'-c'",
")",
";",
"}",
"executeCmd",
"(",
"cmdarguments",
",",
"options",
".",
"debug",
",",
"options",
".",
"quitapp",
")",
";",
"}"
]
| Aborts current scheduled shutdown
@param {Object} options | [
"Aborts",
"current",
"scheduled",
"shutdown"
]
| 1c2dd056a1fe524cd5663eed96dc66993b11285c | https://github.com/samuelcarreira/electron-shutdown-command/blob/1c2dd056a1fe524cd5663eed96dc66993b11285c/index.js#L100-L115 | train |
samuelcarreira/electron-shutdown-command | index.js | setTimer | function setTimer(timervalue) {
let cmdarguments = [];
if (process.platform === 'linux' ) {
if (timervalue) {
cmdarguments.push(timervalue.toString());
} else {
cmdarguments.push('now');
}
}
if (process.platform === 'darwin') {
if (timervalue) {
let timeinminutes = Math.round(Number(timervalue) / 60);
if (timeinminutes === 0) {
timeinminutes = 1; // min 1 minute
}
cmdarguments.push('-t ' + timeinminutes.toString());
} else {
cmdarguments.push('now');
}
}
if (process.platform === 'win32') {
if (timervalue) {
cmdarguments.push('-t ' + timervalue.toString());
} else {
cmdarguments.push('-t 0'); // set to 0 because default is 20 seconds
}
}
return cmdarguments;
} | javascript | function setTimer(timervalue) {
let cmdarguments = [];
if (process.platform === 'linux' ) {
if (timervalue) {
cmdarguments.push(timervalue.toString());
} else {
cmdarguments.push('now');
}
}
if (process.platform === 'darwin') {
if (timervalue) {
let timeinminutes = Math.round(Number(timervalue) / 60);
if (timeinminutes === 0) {
timeinminutes = 1; // min 1 minute
}
cmdarguments.push('-t ' + timeinminutes.toString());
} else {
cmdarguments.push('now');
}
}
if (process.platform === 'win32') {
if (timervalue) {
cmdarguments.push('-t ' + timervalue.toString());
} else {
cmdarguments.push('-t 0'); // set to 0 because default is 20 seconds
}
}
return cmdarguments;
} | [
"function",
"setTimer",
"(",
"timervalue",
")",
"{",
"let",
"cmdarguments",
"=",
"[",
"]",
";",
"if",
"(",
"process",
".",
"platform",
"===",
"'linux'",
")",
"{",
"if",
"(",
"timervalue",
")",
"{",
"cmdarguments",
".",
"push",
"(",
"timervalue",
".",
"toString",
"(",
")",
")",
";",
"}",
"else",
"{",
"cmdarguments",
".",
"push",
"(",
"'now'",
")",
";",
"}",
"}",
"if",
"(",
"process",
".",
"platform",
"===",
"'darwin'",
")",
"{",
"if",
"(",
"timervalue",
")",
"{",
"let",
"timeinminutes",
"=",
"Math",
".",
"round",
"(",
"Number",
"(",
"timervalue",
")",
"/",
"60",
")",
";",
"if",
"(",
"timeinminutes",
"===",
"0",
")",
"{",
"timeinminutes",
"=",
"1",
";",
"}",
"cmdarguments",
".",
"push",
"(",
"'-t '",
"+",
"timeinminutes",
".",
"toString",
"(",
")",
")",
";",
"}",
"else",
"{",
"cmdarguments",
".",
"push",
"(",
"'now'",
")",
";",
"}",
"}",
"if",
"(",
"process",
".",
"platform",
"===",
"'win32'",
")",
"{",
"if",
"(",
"timervalue",
")",
"{",
"cmdarguments",
".",
"push",
"(",
"'-t '",
"+",
"timervalue",
".",
"toString",
"(",
")",
")",
";",
"}",
"else",
"{",
"cmdarguments",
".",
"push",
"(",
"'-t 0'",
")",
";",
"}",
"}",
"return",
"cmdarguments",
";",
"}"
]
| set current time argument
@param {Number} timervalue value in seconds to delay, false to execute now | [
"set",
"current",
"time",
"argument"
]
| 1c2dd056a1fe524cd5663eed96dc66993b11285c | https://github.com/samuelcarreira/electron-shutdown-command/blob/1c2dd056a1fe524cd5663eed96dc66993b11285c/index.js#L153-L185 | train |
KoryNunn/interact | interact.js | getActualTarget | function getActualTarget() {
var scrollX = window.scrollX,
scrollY = window.scrollY;
// IE is stupid and doesn't support scrollX/Y
if(scrollX === undefined){
scrollX = d.body.scrollLeft;
scrollY = d.body.scrollTop;
}
return d.elementFromPoint(this.pageX - window.scrollX, this.pageY - window.scrollY);
} | javascript | function getActualTarget() {
var scrollX = window.scrollX,
scrollY = window.scrollY;
// IE is stupid and doesn't support scrollX/Y
if(scrollX === undefined){
scrollX = d.body.scrollLeft;
scrollY = d.body.scrollTop;
}
return d.elementFromPoint(this.pageX - window.scrollX, this.pageY - window.scrollY);
} | [
"function",
"getActualTarget",
"(",
")",
"{",
"var",
"scrollX",
"=",
"window",
".",
"scrollX",
",",
"scrollY",
"=",
"window",
".",
"scrollY",
";",
"if",
"(",
"scrollX",
"===",
"undefined",
")",
"{",
"scrollX",
"=",
"d",
".",
"body",
".",
"scrollLeft",
";",
"scrollY",
"=",
"d",
".",
"body",
".",
"scrollTop",
";",
"}",
"return",
"d",
".",
"elementFromPoint",
"(",
"this",
".",
"pageX",
"-",
"window",
".",
"scrollX",
",",
"this",
".",
"pageY",
"-",
"window",
".",
"scrollY",
")",
";",
"}"
]
| For some reason touch browsers never change the event target during a touch. This is, lets face it, fucking stupid. | [
"For",
"some",
"reason",
"touch",
"browsers",
"never",
"change",
"the",
"event",
"target",
"during",
"a",
"touch",
".",
"This",
"is",
"lets",
"face",
"it",
"fucking",
"stupid",
"."
]
| c11e9596359f8cea166778a261d48a747a0e3533 | https://github.com/KoryNunn/interact/blob/c11e9596359f8cea166778a261d48a747a0e3533/interact.js#L74-L85 | train |
hutkev/Shared | lib/shared.js | defaultLogger | function defaultLogger() {
if(!_defaultLogger) {
var prefix = 'master';
if(cluster.worker) {
prefix = 'work ' + cluster.worker.id;
}
_defaultLogger = new Logger(process.stdout, prefix, utils.LogLevel.INFO, []);
}
return _defaultLogger;
} | javascript | function defaultLogger() {
if(!_defaultLogger) {
var prefix = 'master';
if(cluster.worker) {
prefix = 'work ' + cluster.worker.id;
}
_defaultLogger = new Logger(process.stdout, prefix, utils.LogLevel.INFO, []);
}
return _defaultLogger;
} | [
"function",
"defaultLogger",
"(",
")",
"{",
"if",
"(",
"!",
"_defaultLogger",
")",
"{",
"var",
"prefix",
"=",
"'master'",
";",
"if",
"(",
"cluster",
".",
"worker",
")",
"{",
"prefix",
"=",
"'work '",
"+",
"cluster",
".",
"worker",
".",
"id",
";",
"}",
"_defaultLogger",
"=",
"new",
"Logger",
"(",
"process",
".",
"stdout",
",",
"prefix",
",",
"utils",
".",
"LogLevel",
".",
"INFO",
",",
"[",
"]",
")",
";",
"}",
"return",
"_defaultLogger",
";",
"}"
]
| Obtains the default logger. If one has not been set then logging is
to process.stdout at the INFO level. | [
"Obtains",
"the",
"default",
"logger",
".",
"If",
"one",
"has",
"not",
"been",
"set",
"then",
"logging",
"is",
"to",
"process",
".",
"stdout",
"at",
"the",
"INFO",
"level",
"."
]
| 9fb63e54d16256c6b8fbac381e11adc4daea5dc6 | https://github.com/hutkev/Shared/blob/9fb63e54d16256c6b8fbac381e11adc4daea5dc6/lib/shared.js#L462-L471 | train |
hutkev/Shared | lib/shared.js | typeOf | function typeOf(value) {
var s = typeof value;
if(s === 'object') {
if(value) {
if(value instanceof Array) {
s = 'array';
}
} else {
s = 'null';
}
}
return s;
} | javascript | function typeOf(value) {
var s = typeof value;
if(s === 'object') {
if(value) {
if(value instanceof Array) {
s = 'array';
}
} else {
s = 'null';
}
}
return s;
} | [
"function",
"typeOf",
"(",
"value",
")",
"{",
"var",
"s",
"=",
"typeof",
"value",
";",
"if",
"(",
"s",
"===",
"'object'",
")",
"{",
"if",
"(",
"value",
")",
"{",
"if",
"(",
"value",
"instanceof",
"Array",
")",
"{",
"s",
"=",
"'array'",
";",
"}",
"}",
"else",
"{",
"s",
"=",
"'null'",
";",
"}",
"}",
"return",
"s",
";",
"}"
]
| Corrected type of value.
Arrays & null are not 'objects' | [
"Corrected",
"type",
"of",
"value",
".",
"Arrays",
"&",
"null",
"are",
"not",
"objects"
]
| 9fb63e54d16256c6b8fbac381e11adc4daea5dc6 | https://github.com/hutkev/Shared/blob/9fb63e54d16256c6b8fbac381e11adc4daea5dc6/lib/shared.js#L568-L580 | train |
hutkev/Shared | lib/shared.js | treatAs | function treatAs(value) {
var s = typeof value;
if(s === 'object') {
if(value) {
return Object.prototype.toString.call(value).match(/^\[object\s(.*)\]$/)[1];
} else {
s = 'null';
}
}
return s;
} | javascript | function treatAs(value) {
var s = typeof value;
if(s === 'object') {
if(value) {
return Object.prototype.toString.call(value).match(/^\[object\s(.*)\]$/)[1];
} else {
s = 'null';
}
}
return s;
} | [
"function",
"treatAs",
"(",
"value",
")",
"{",
"var",
"s",
"=",
"typeof",
"value",
";",
"if",
"(",
"s",
"===",
"'object'",
")",
"{",
"if",
"(",
"value",
")",
"{",
"return",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"value",
")",
".",
"match",
"(",
"/",
"^\\[object\\s(.*)\\]$",
"/",
")",
"[",
"1",
"]",
";",
"}",
"else",
"{",
"s",
"=",
"'null'",
";",
"}",
"}",
"return",
"s",
";",
"}"
]
| Corrected type of value.
Arrays & null are not 'objects'
Objects return their prototype type. | [
"Corrected",
"type",
"of",
"value",
".",
"Arrays",
"&",
"null",
"are",
"not",
"objects",
"Objects",
"return",
"their",
"prototype",
"type",
"."
]
| 9fb63e54d16256c6b8fbac381e11adc4daea5dc6 | https://github.com/hutkev/Shared/blob/9fb63e54d16256c6b8fbac381e11adc4daea5dc6/lib/shared.js#L587-L597 | train |
hutkev/Shared | lib/shared.js | toInteger | function toInteger(val) {
var v = +val;// toNumber conversion
if(isNaN(v)) {
return 0;
}
if(v === 0 || v === Infinity || v == -Infinity) {
return v;
}
if(v < 0) {
return -1 * Math.floor(-v);
} else {
return Math.floor(v);
}
} | javascript | function toInteger(val) {
var v = +val;// toNumber conversion
if(isNaN(v)) {
return 0;
}
if(v === 0 || v === Infinity || v == -Infinity) {
return v;
}
if(v < 0) {
return -1 * Math.floor(-v);
} else {
return Math.floor(v);
}
} | [
"function",
"toInteger",
"(",
"val",
")",
"{",
"var",
"v",
"=",
"+",
"val",
";",
"if",
"(",
"isNaN",
"(",
"v",
")",
")",
"{",
"return",
"0",
";",
"}",
"if",
"(",
"v",
"===",
"0",
"||",
"v",
"===",
"Infinity",
"||",
"v",
"==",
"-",
"Infinity",
")",
"{",
"return",
"v",
";",
"}",
"if",
"(",
"v",
"<",
"0",
")",
"{",
"return",
"-",
"1",
"*",
"Math",
".",
"floor",
"(",
"-",
"v",
")",
";",
"}",
"else",
"{",
"return",
"Math",
".",
"floor",
"(",
"v",
")",
";",
"}",
"}"
]
| ES5 9.2 | [
"ES5",
"9",
".",
"2"
]
| 9fb63e54d16256c6b8fbac381e11adc4daea5dc6 | https://github.com/hutkev/Shared/blob/9fb63e54d16256c6b8fbac381e11adc4daea5dc6/lib/shared.js#L623-L637 | train |
hutkev/Shared | lib/shared.js | UnknownReference | function UnknownReference(id, prop, missing) {
this._id = id;
this._prop = prop;
this._missing = missing;
} | javascript | function UnknownReference(id, prop, missing) {
this._id = id;
this._prop = prop;
this._missing = missing;
} | [
"function",
"UnknownReference",
"(",
"id",
",",
"prop",
",",
"missing",
")",
"{",
"this",
".",
"_id",
"=",
"id",
";",
"this",
".",
"_prop",
"=",
"prop",
";",
"this",
".",
"_missing",
"=",
"missing",
";",
"}"
]
| Id of missing object | [
"Id",
"of",
"missing",
"object"
]
| 9fb63e54d16256c6b8fbac381e11adc4daea5dc6 | https://github.com/hutkev/Shared/blob/9fb63e54d16256c6b8fbac381e11adc4daea5dc6/lib/shared.js#L1186-L1190 | train |
hutkev/Shared | lib/shared.js | function (obj, prop, value) {
shared.utils.dassert(getTracker(obj) === this);
this._lastTx = this.tc().addNew(obj, prop, value, this._lastTx);
} | javascript | function (obj, prop, value) {
shared.utils.dassert(getTracker(obj) === this);
this._lastTx = this.tc().addNew(obj, prop, value, this._lastTx);
} | [
"function",
"(",
"obj",
",",
"prop",
",",
"value",
")",
"{",
"shared",
".",
"utils",
".",
"dassert",
"(",
"getTracker",
"(",
"obj",
")",
"===",
"this",
")",
";",
"this",
".",
"_lastTx",
"=",
"this",
".",
"tc",
"(",
")",
".",
"addNew",
"(",
"obj",
",",
"prop",
",",
"value",
",",
"this",
".",
"_lastTx",
")",
";",
"}"
]
| Change notification handlers called to record changes | [
"Change",
"notification",
"handlers",
"called",
"to",
"record",
"changes"
]
| 9fb63e54d16256c6b8fbac381e11adc4daea5dc6 | https://github.com/hutkev/Shared/blob/9fb63e54d16256c6b8fbac381e11adc4daea5dc6/lib/shared.js#L1377-L1380 | train |
|
hutkev/Shared | lib/shared.js | function (obj) {
shared.utils.dassert(getTracker(obj) === this);
this._rev += 1;
this._type = shared.types.TypeStore.instance().type(obj);
} | javascript | function (obj) {
shared.utils.dassert(getTracker(obj) === this);
this._rev += 1;
this._type = shared.types.TypeStore.instance().type(obj);
} | [
"function",
"(",
"obj",
")",
"{",
"shared",
".",
"utils",
".",
"dassert",
"(",
"getTracker",
"(",
"obj",
")",
"===",
"this",
")",
";",
"this",
".",
"_rev",
"+=",
"1",
";",
"this",
".",
"_type",
"=",
"shared",
".",
"types",
".",
"TypeStore",
".",
"instance",
"(",
")",
".",
"type",
"(",
"obj",
")",
";",
"}"
]
| Uprev an object recording new properties | [
"Uprev",
"an",
"object",
"recording",
"new",
"properties"
]
| 9fb63e54d16256c6b8fbac381e11adc4daea5dc6 | https://github.com/hutkev/Shared/blob/9fb63e54d16256c6b8fbac381e11adc4daea5dc6/lib/shared.js#L1434-L1438 | train |
|
hutkev/Shared | lib/shared.js | MongoStore | function MongoStore(options) {
if (typeof options === "undefined") { options = {
}; }
_super.call(this);
this._logger = shared.utils.defaultLogger();
// Database stuff
this._collection = null;
this._pending = [];
// Outstanding work queue
this._root = null;
// Root object
this._cache = new shared.mtx.ObjectCache();
this._host = options.host || 'localhost';
this._port = options.port || 27017;
this._dbName = options.db || 'shared';
this._collectionName = options.collection || 'shared';
this._safe = options.safe || 'false';
this._logger.debug('STORE', '%s: Store created', this.id());
} | javascript | function MongoStore(options) {
if (typeof options === "undefined") { options = {
}; }
_super.call(this);
this._logger = shared.utils.defaultLogger();
// Database stuff
this._collection = null;
this._pending = [];
// Outstanding work queue
this._root = null;
// Root object
this._cache = new shared.mtx.ObjectCache();
this._host = options.host || 'localhost';
this._port = options.port || 27017;
this._dbName = options.db || 'shared';
this._collectionName = options.collection || 'shared';
this._safe = options.safe || 'false';
this._logger.debug('STORE', '%s: Store created', this.id());
} | [
"function",
"MongoStore",
"(",
"options",
")",
"{",
"if",
"(",
"typeof",
"options",
"===",
"\"undefined\"",
")",
"{",
"options",
"=",
"{",
"}",
";",
"}",
"_super",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"_logger",
"=",
"shared",
".",
"utils",
".",
"defaultLogger",
"(",
")",
";",
"this",
".",
"_collection",
"=",
"null",
";",
"this",
".",
"_pending",
"=",
"[",
"]",
";",
"this",
".",
"_root",
"=",
"null",
";",
"this",
".",
"_cache",
"=",
"new",
"shared",
".",
"mtx",
".",
"ObjectCache",
"(",
")",
";",
"this",
".",
"_host",
"=",
"options",
".",
"host",
"||",
"'localhost'",
";",
"this",
".",
"_port",
"=",
"options",
".",
"port",
"||",
"27017",
";",
"this",
".",
"_dbName",
"=",
"options",
".",
"db",
"||",
"'shared'",
";",
"this",
".",
"_collectionName",
"=",
"options",
".",
"collection",
"||",
"'shared'",
";",
"this",
".",
"_safe",
"=",
"options",
".",
"safe",
"||",
"'false'",
";",
"this",
".",
"_logger",
".",
"debug",
"(",
"'STORE'",
",",
"'%s: Store created'",
",",
"this",
".",
"id",
"(",
")",
")",
";",
"}"
]
| For checking for lock changes | [
"For",
"checking",
"for",
"lock",
"changes"
]
| 9fb63e54d16256c6b8fbac381e11adc4daea5dc6 | https://github.com/hutkev/Shared/blob/9fb63e54d16256c6b8fbac381e11adc4daea5dc6/lib/shared.js#L2509-L2527 | train |
emiloberg/markdown-styleguide-generator | index.js | saveFile | function saveFile(html) {
fs.outputFile(options.outputFile, html, function(err, data) {
if (err) {
console.log(error('ERROR!'));
console.dir(err);
process.exit(1);
}
console.log(good('\n\nAll done!'));
console.log('Created file: ' + good(options.outputFile));
});
} | javascript | function saveFile(html) {
fs.outputFile(options.outputFile, html, function(err, data) {
if (err) {
console.log(error('ERROR!'));
console.dir(err);
process.exit(1);
}
console.log(good('\n\nAll done!'));
console.log('Created file: ' + good(options.outputFile));
});
} | [
"function",
"saveFile",
"(",
"html",
")",
"{",
"fs",
".",
"outputFile",
"(",
"options",
".",
"outputFile",
",",
"html",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"error",
"(",
"'ERROR!'",
")",
")",
";",
"console",
".",
"dir",
"(",
"err",
")",
";",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
"console",
".",
"log",
"(",
"good",
"(",
"'\\n\\nAll done!'",
")",
")",
";",
"\\n",
"}",
")",
";",
"}"
]
| Save html to file
@param html | [
"Save",
"html",
"to",
"file"
]
| 7052f4185fba682c4e309faa78fd1a40ed2c010d | https://github.com/emiloberg/markdown-styleguide-generator/blob/7052f4185fba682c4e309faa78fd1a40ed2c010d/index.js#L213-L223 | train |
emiloberg/markdown-styleguide-generator | index.js | doTemplating | function doTemplating(json) {
// Adding '#styleguide .hljs pre' to highlight css, to override common used styling for 'pre'
highlightSource = highlightSource.replace('.hljs {', '#styleguide .hljs pre, .hljs {');
handlebars.registerPartial("jquery", '<script>\n' + jqSource+ '\n</script>');
handlebars.registerPartial("theme", '<style>\n' + themeSource + '\n</style>');
handlebars.registerPartial("highlight", '<style>\n' + highlightSource + '\n</style>');
var template = handlebars.compile(templateSource);
return template(json);
} | javascript | function doTemplating(json) {
// Adding '#styleguide .hljs pre' to highlight css, to override common used styling for 'pre'
highlightSource = highlightSource.replace('.hljs {', '#styleguide .hljs pre, .hljs {');
handlebars.registerPartial("jquery", '<script>\n' + jqSource+ '\n</script>');
handlebars.registerPartial("theme", '<style>\n' + themeSource + '\n</style>');
handlebars.registerPartial("highlight", '<style>\n' + highlightSource + '\n</style>');
var template = handlebars.compile(templateSource);
return template(json);
} | [
"function",
"doTemplating",
"(",
"json",
")",
"{",
"highlightSource",
"=",
"highlightSource",
".",
"replace",
"(",
"'.hljs {'",
",",
"'#styleguide .hljs pre, .hljs {'",
")",
";",
"handlebars",
".",
"registerPartial",
"(",
"\"jquery\"",
",",
"'<script>\\n'",
"+",
"\\n",
"+",
"jqSource",
")",
";",
"'\\n</script>'",
"\\n",
"handlebars",
".",
"registerPartial",
"(",
"\"theme\"",
",",
"'<style>\\n'",
"+",
"\\n",
"+",
"themeSource",
")",
";",
"'\\n</style>'",
"}"
]
| Run through Handlebars to create HTML
@param {object} json
@returns {string} html | [
"Run",
"through",
"Handlebars",
"to",
"create",
"HTML"
]
| 7052f4185fba682c4e309faa78fd1a40ed2c010d | https://github.com/emiloberg/markdown-styleguide-generator/blob/7052f4185fba682c4e309faa78fd1a40ed2c010d/index.js#L231-L241 | train |
roccivic/cron-converter | src/seeker.js | Seeker | function Seeker(cron, now) {
if (cron.parts === null) {
throw new Error('No schedule found');
}
var date;
if (cron.options.timezone) {
date = moment.tz(now, cron.options.timezone);
} else {
date = moment(now);
}
if (!date.isValid()) {
throw new Error('Invalid date provided');
}
if (date.seconds() > 0) {
// Add a minute to the date to prevent returning dates in the past
date.add(1, 'minute');
}
this.cron = cron;
this.now = date;
this.date = date;
this.pristine = true;
} | javascript | function Seeker(cron, now) {
if (cron.parts === null) {
throw new Error('No schedule found');
}
var date;
if (cron.options.timezone) {
date = moment.tz(now, cron.options.timezone);
} else {
date = moment(now);
}
if (!date.isValid()) {
throw new Error('Invalid date provided');
}
if (date.seconds() > 0) {
// Add a minute to the date to prevent returning dates in the past
date.add(1, 'minute');
}
this.cron = cron;
this.now = date;
this.date = date;
this.pristine = true;
} | [
"function",
"Seeker",
"(",
"cron",
",",
"now",
")",
"{",
"if",
"(",
"cron",
".",
"parts",
"===",
"null",
")",
"{",
"throw",
"new",
"Error",
"(",
"'No schedule found'",
")",
";",
"}",
"var",
"date",
";",
"if",
"(",
"cron",
".",
"options",
".",
"timezone",
")",
"{",
"date",
"=",
"moment",
".",
"tz",
"(",
"now",
",",
"cron",
".",
"options",
".",
"timezone",
")",
";",
"}",
"else",
"{",
"date",
"=",
"moment",
"(",
"now",
")",
";",
"}",
"if",
"(",
"!",
"date",
".",
"isValid",
"(",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid date provided'",
")",
";",
"}",
"if",
"(",
"date",
".",
"seconds",
"(",
")",
">",
"0",
")",
"{",
"date",
".",
"add",
"(",
"1",
",",
"'minute'",
")",
";",
"}",
"this",
".",
"cron",
"=",
"cron",
";",
"this",
".",
"now",
"=",
"date",
";",
"this",
".",
"date",
"=",
"date",
";",
"this",
".",
"pristine",
"=",
"true",
";",
"}"
]
| Creates an instance of Seeker.
Seeker objects search for execution times of a cron schedule.
@constructor
@this {Seeker} | [
"Creates",
"an",
"instance",
"of",
"Seeker",
".",
"Seeker",
"objects",
"search",
"for",
"execution",
"times",
"of",
"a",
"cron",
"schedule",
"."
]
| ebfae6a2f5cf3fd621af1ad1e34dfbe4ee6f7df9 | https://github.com/roccivic/cron-converter/blob/ebfae6a2f5cf3fd621af1ad1e34dfbe4ee6f7df9/src/seeker.js#L12-L33 | train |
roccivic/cron-converter | src/seeker.js | function(parts, date, reverse) {
var operation = 'add';
var reset = 'startOf';
if (reverse) {
operation = 'subtract';
reset = 'endOf';
date.subtract(1, 'minute'); // Ensure prev and next cannot be same time
}
var retry = 24;
while (--retry) {
shiftMonth(parts, date, operation, reset);
var monthChanged = shiftDay(parts, date, operation, reset);
if (!monthChanged) {
var dayChanged = shiftHour(parts, date, operation, reset);
if (!dayChanged) {
var hourChanged = shiftMinute(parts, date, operation, reset);
if (!hourChanged) {
break;
}
}
}
}
if (!retry) {
throw new Error('Unable to find execution time for schedule');
}
date.seconds(0).milliseconds(0);
// Return new moment object
return moment(date);
} | javascript | function(parts, date, reverse) {
var operation = 'add';
var reset = 'startOf';
if (reverse) {
operation = 'subtract';
reset = 'endOf';
date.subtract(1, 'minute'); // Ensure prev and next cannot be same time
}
var retry = 24;
while (--retry) {
shiftMonth(parts, date, operation, reset);
var monthChanged = shiftDay(parts, date, operation, reset);
if (!monthChanged) {
var dayChanged = shiftHour(parts, date, operation, reset);
if (!dayChanged) {
var hourChanged = shiftMinute(parts, date, operation, reset);
if (!hourChanged) {
break;
}
}
}
}
if (!retry) {
throw new Error('Unable to find execution time for schedule');
}
date.seconds(0).milliseconds(0);
// Return new moment object
return moment(date);
} | [
"function",
"(",
"parts",
",",
"date",
",",
"reverse",
")",
"{",
"var",
"operation",
"=",
"'add'",
";",
"var",
"reset",
"=",
"'startOf'",
";",
"if",
"(",
"reverse",
")",
"{",
"operation",
"=",
"'subtract'",
";",
"reset",
"=",
"'endOf'",
";",
"date",
".",
"subtract",
"(",
"1",
",",
"'minute'",
")",
";",
"}",
"var",
"retry",
"=",
"24",
";",
"while",
"(",
"--",
"retry",
")",
"{",
"shiftMonth",
"(",
"parts",
",",
"date",
",",
"operation",
",",
"reset",
")",
";",
"var",
"monthChanged",
"=",
"shiftDay",
"(",
"parts",
",",
"date",
",",
"operation",
",",
"reset",
")",
";",
"if",
"(",
"!",
"monthChanged",
")",
"{",
"var",
"dayChanged",
"=",
"shiftHour",
"(",
"parts",
",",
"date",
",",
"operation",
",",
"reset",
")",
";",
"if",
"(",
"!",
"dayChanged",
")",
"{",
"var",
"hourChanged",
"=",
"shiftMinute",
"(",
"parts",
",",
"date",
",",
"operation",
",",
"reset",
")",
";",
"if",
"(",
"!",
"hourChanged",
")",
"{",
"break",
";",
"}",
"}",
"}",
"}",
"if",
"(",
"!",
"retry",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Unable to find execution time for schedule'",
")",
";",
"}",
"date",
".",
"seconds",
"(",
"0",
")",
".",
"milliseconds",
"(",
"0",
")",
";",
"return",
"moment",
"(",
"date",
")",
";",
"}"
]
| Returns the time the schedule would run next.
@param {array} parts An array of Cron parts.
@param {Date} date The reference date.
@param {boolean} reverse Whether to find the previous value instead of next.
@return {Moment} The date the schedule would have executed at. | [
"Returns",
"the",
"time",
"the",
"schedule",
"would",
"run",
"next",
"."
]
| ebfae6a2f5cf3fd621af1ad1e34dfbe4ee6f7df9 | https://github.com/roccivic/cron-converter/blob/ebfae6a2f5cf3fd621af1ad1e34dfbe4ee6f7df9/src/seeker.js#L79-L107 | train |
|
cubehouse/PSNjs | psn_request.js | DebugLog | function DebugLog(msg)
{
console.log("[PSN] :: " + ((typeof msg == "object") ? JSON.stringify(msg, null, 2) : msg));
} | javascript | function DebugLog(msg)
{
console.log("[PSN] :: " + ((typeof msg == "object") ? JSON.stringify(msg, null, 2) : msg));
} | [
"function",
"DebugLog",
"(",
"msg",
")",
"{",
"console",
".",
"log",
"(",
"\"[PSN] :: \"",
"+",
"(",
"(",
"typeof",
"msg",
"==",
"\"object\"",
")",
"?",
"JSON",
".",
"stringify",
"(",
"msg",
",",
"null",
",",
"2",
")",
":",
"msg",
")",
")",
";",
"}"
]
| In-Build logger | [
"In",
"-",
"Build",
"logger"
]
| 1da280d26e1c61f1237c8ed3b86ea3af48494769 | https://github.com/cubehouse/PSNjs/blob/1da280d26e1c61f1237c8ed3b86ea3af48494769/psn_request.js#L100-L103 | train |
cubehouse/PSNjs | psn_request.js | GetHeaders | function GetHeaders(additional_headers)
{
var ret_headers = {};
// clone default headers into our return object (parsed)
for(var key in headers)
{
ret_headers[key] = ParseStaches(headers[key]);
}
// add accept-language header based on our language
ret_headers['Accept-Language'] = auth_obj.npLanguage + "," + languages.join(',');
// add access token (if we have one)
if (auth_obj.access_token)
{
ret_headers['Authorization'] = 'Bearer ' + auth_obj.access_token;
}
// add additional headers (if supplied) (parsed)
if (additional_headers) for(var key in additional_headers)
{
ret_headers[key] = ParseStaches(additional_headers[key]);
}
return ret_headers;
} | javascript | function GetHeaders(additional_headers)
{
var ret_headers = {};
// clone default headers into our return object (parsed)
for(var key in headers)
{
ret_headers[key] = ParseStaches(headers[key]);
}
// add accept-language header based on our language
ret_headers['Accept-Language'] = auth_obj.npLanguage + "," + languages.join(',');
// add access token (if we have one)
if (auth_obj.access_token)
{
ret_headers['Authorization'] = 'Bearer ' + auth_obj.access_token;
}
// add additional headers (if supplied) (parsed)
if (additional_headers) for(var key in additional_headers)
{
ret_headers[key] = ParseStaches(additional_headers[key]);
}
return ret_headers;
} | [
"function",
"GetHeaders",
"(",
"additional_headers",
")",
"{",
"var",
"ret_headers",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"key",
"in",
"headers",
")",
"{",
"ret_headers",
"[",
"key",
"]",
"=",
"ParseStaches",
"(",
"headers",
"[",
"key",
"]",
")",
";",
"}",
"ret_headers",
"[",
"'Accept-Language'",
"]",
"=",
"auth_obj",
".",
"npLanguage",
"+",
"\",\"",
"+",
"languages",
".",
"join",
"(",
"','",
")",
";",
"if",
"(",
"auth_obj",
".",
"access_token",
")",
"{",
"ret_headers",
"[",
"'Authorization'",
"]",
"=",
"'Bearer '",
"+",
"auth_obj",
".",
"access_token",
";",
"}",
"if",
"(",
"additional_headers",
")",
"for",
"(",
"var",
"key",
"in",
"additional_headers",
")",
"{",
"ret_headers",
"[",
"key",
"]",
"=",
"ParseStaches",
"(",
"additional_headers",
"[",
"key",
"]",
")",
";",
"}",
"return",
"ret_headers",
";",
"}"
]
| Generate headers for a PSN request | [
"Generate",
"headers",
"for",
"a",
"PSN",
"request"
]
| 1da280d26e1c61f1237c8ed3b86ea3af48494769 | https://github.com/cubehouse/PSNjs/blob/1da280d26e1c61f1237c8ed3b86ea3af48494769/psn_request.js#L207-L232 | train |
cubehouse/PSNjs | psn_request.js | GetOAuthData | function GetOAuthData(additional_fields)
{
var ret_fields = {};
// clone base oauth settings
for(var key in oauth_settings)
{
ret_fields[key] = ParseStaches(oauth_settings[key]);
}
// add additional fields (if supplied)
if (additional_fields) for(var key in additional_fields)
{
ret_fields[key] = ParseStaches(additional_fields[key]);
}
return ret_fields;
} | javascript | function GetOAuthData(additional_fields)
{
var ret_fields = {};
// clone base oauth settings
for(var key in oauth_settings)
{
ret_fields[key] = ParseStaches(oauth_settings[key]);
}
// add additional fields (if supplied)
if (additional_fields) for(var key in additional_fields)
{
ret_fields[key] = ParseStaches(additional_fields[key]);
}
return ret_fields;
} | [
"function",
"GetOAuthData",
"(",
"additional_fields",
")",
"{",
"var",
"ret_fields",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"key",
"in",
"oauth_settings",
")",
"{",
"ret_fields",
"[",
"key",
"]",
"=",
"ParseStaches",
"(",
"oauth_settings",
"[",
"key",
"]",
")",
";",
"}",
"if",
"(",
"additional_fields",
")",
"for",
"(",
"var",
"key",
"in",
"additional_fields",
")",
"{",
"ret_fields",
"[",
"key",
"]",
"=",
"ParseStaches",
"(",
"additional_fields",
"[",
"key",
"]",
")",
";",
"}",
"return",
"ret_fields",
";",
"}"
]
| Get OAuth data | [
"Get",
"OAuth",
"data"
]
| 1da280d26e1c61f1237c8ed3b86ea3af48494769 | https://github.com/cubehouse/PSNjs/blob/1da280d26e1c61f1237c8ed3b86ea3af48494769/psn_request.js#L235-L251 | train |
cubehouse/PSNjs | psn_request.js | URLGET | function URLGET(url, fields, method, callback)
{
// method variable is optional
if (typeof method == "function")
{
callback = method;
method = "GET";
}
_URLGET(url, fields, GetHeaders({"Access-Control-Request-Method": method}), method, function(err, body) {
if (err)
{
// got error, bounce it up
if (callback) callback(err);
return;
}
else
{
var JSONBody;
if (typeof body == "object")
{
// already a JSON object?
JSONBody = body;
}
else
{
// try to parse JSON body
if (!body || !/\S/.test(body))
{
// string is empty, return empty object
if (callback) callback(false, {});
return;
}
else
{
try
{
JSONBody = JSON.parse(body);
}
catch(parse_err)
{
// error parsing JSON result
Log("Parse JSON error: " + parse_err + "\r\nURL:\r\n" + url + "\r\nBody:\r\n" + body);
if (callback) callback("Parse JSON error: " + parse_err);
return;
}
}
}
// success! return JSON object
if (callback) callback(false, JSONBody);
}
});
} | javascript | function URLGET(url, fields, method, callback)
{
// method variable is optional
if (typeof method == "function")
{
callback = method;
method = "GET";
}
_URLGET(url, fields, GetHeaders({"Access-Control-Request-Method": method}), method, function(err, body) {
if (err)
{
// got error, bounce it up
if (callback) callback(err);
return;
}
else
{
var JSONBody;
if (typeof body == "object")
{
// already a JSON object?
JSONBody = body;
}
else
{
// try to parse JSON body
if (!body || !/\S/.test(body))
{
// string is empty, return empty object
if (callback) callback(false, {});
return;
}
else
{
try
{
JSONBody = JSON.parse(body);
}
catch(parse_err)
{
// error parsing JSON result
Log("Parse JSON error: " + parse_err + "\r\nURL:\r\n" + url + "\r\nBody:\r\n" + body);
if (callback) callback("Parse JSON error: " + parse_err);
return;
}
}
}
// success! return JSON object
if (callback) callback(false, JSONBody);
}
});
} | [
"function",
"URLGET",
"(",
"url",
",",
"fields",
",",
"method",
",",
"callback",
")",
"{",
"if",
"(",
"typeof",
"method",
"==",
"\"function\"",
")",
"{",
"callback",
"=",
"method",
";",
"method",
"=",
"\"GET\"",
";",
"}",
"_URLGET",
"(",
"url",
",",
"fields",
",",
"GetHeaders",
"(",
"{",
"\"Access-Control-Request-Method\"",
":",
"method",
"}",
")",
",",
"method",
",",
"function",
"(",
"err",
",",
"body",
")",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"callback",
")",
"callback",
"(",
"err",
")",
";",
"return",
";",
"}",
"else",
"{",
"var",
"JSONBody",
";",
"if",
"(",
"typeof",
"body",
"==",
"\"object\"",
")",
"{",
"JSONBody",
"=",
"body",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"body",
"||",
"!",
"/",
"\\S",
"/",
".",
"test",
"(",
"body",
")",
")",
"{",
"if",
"(",
"callback",
")",
"callback",
"(",
"false",
",",
"{",
"}",
")",
";",
"return",
";",
"}",
"else",
"{",
"try",
"{",
"JSONBody",
"=",
"JSON",
".",
"parse",
"(",
"body",
")",
";",
"}",
"catch",
"(",
"parse_err",
")",
"{",
"Log",
"(",
"\"Parse JSON error: \"",
"+",
"parse_err",
"+",
"\"\\r\\nURL:\\r\\n\"",
"+",
"\\r",
"+",
"\\n",
"+",
"\\r",
")",
";",
"\\n",
"url",
"}",
"}",
"}",
"\"\\r\\nBody:\\r\\n\"",
"}",
"}",
")",
";",
"}"
]
| Make a PSN GET request | [
"Make",
"a",
"PSN",
"GET",
"request"
]
| 1da280d26e1c61f1237c8ed3b86ea3af48494769 | https://github.com/cubehouse/PSNjs/blob/1da280d26e1c61f1237c8ed3b86ea3af48494769/psn_request.js#L254-L307 | train |
cubehouse/PSNjs | psn_request.js | Login | function Login(callback)
{
Log("Making OAuth Request...");
// start OAuth request (use our internal GET function as this is different!)
_URLGET(
// URL
urls.login_base + "/2.0/oauth/authorize",
// query string
GetOAuthData({
response_type: "code",
service_entity: "urn:service-entity:psn",
returnAuthCode: true,
state: "1156936032"
}),
// headers
{
'User-Agent': ParseStaches(useragent)
},
function(err, body, response)
{
if (err)
{
// return login error
if (callback) callback(err);
return;
}
else
{
// get the login path
var login_referrer = response.req.path;
Log("Logging in...");
// now actually login using the previous URL as the referrer
request(
{
url: urls.login_base + "/login.do",
method: "POST",
headers:
{
'User-Agent': ParseStaches(useragent),
'X-Requested-With': headers["X-Requested-With"],
'Origin': 'https://auth.api.sonyentertainmentnetwork.com',
'Referer': login_referrer,
},
form:
{
'params': new Buffer(login_params).toString('base64'),
'j_username': login_details.email,
'j_password': login_details.password
}
},
function (err, response, body)
{
if (err)
{
// login failed
Log("Failed to make login request");
if (callback) callback(err);
return;
}
else
{
Log("Following login...");
request.get(response.headers.location, function (err, response, body)
{
if (!err)
{
// parse URL
var result = url.parse(response.req.path, true);
if (result.query.authentication_error)
{
// try to extract login error from website
var error_message = /errorDivMessage\"\>\s*(.*)\<br \/\>/.exec(body);
if (error_message && error_message[1])
{
Log("Login failed! Error from Sony: " + error_message[1]);
if (callback) callback(error_message[1]);
}
else
{
Log("Login failed!");
if (callback) callback("Login failed!");
}
return;
}
else
{
// no auth error!
var auth_result = url.parse(result.query.targetUrl, true);
if (auth_result.query.authCode)
{
Log("Got auth code: " + auth_result.query.authCode);
auth_obj.auth_code = auth_result.query.authCode;
if (callback) callback(false);
return;
}
else
{
Log("Auth error " + auth_result.query.error_code + ": " + auth_result.query.error_description);
if (callback) callback("Auth error " + auth_result.query.error_code + ": " + auth_result.query.error_description);
return;
}
}
}
else
{
Log("Auth code fetch error: " + err);
if (callback) callback(err);
return;
}
});
}
}
);
}
}
);
} | javascript | function Login(callback)
{
Log("Making OAuth Request...");
// start OAuth request (use our internal GET function as this is different!)
_URLGET(
// URL
urls.login_base + "/2.0/oauth/authorize",
// query string
GetOAuthData({
response_type: "code",
service_entity: "urn:service-entity:psn",
returnAuthCode: true,
state: "1156936032"
}),
// headers
{
'User-Agent': ParseStaches(useragent)
},
function(err, body, response)
{
if (err)
{
// return login error
if (callback) callback(err);
return;
}
else
{
// get the login path
var login_referrer = response.req.path;
Log("Logging in...");
// now actually login using the previous URL as the referrer
request(
{
url: urls.login_base + "/login.do",
method: "POST",
headers:
{
'User-Agent': ParseStaches(useragent),
'X-Requested-With': headers["X-Requested-With"],
'Origin': 'https://auth.api.sonyentertainmentnetwork.com',
'Referer': login_referrer,
},
form:
{
'params': new Buffer(login_params).toString('base64'),
'j_username': login_details.email,
'j_password': login_details.password
}
},
function (err, response, body)
{
if (err)
{
// login failed
Log("Failed to make login request");
if (callback) callback(err);
return;
}
else
{
Log("Following login...");
request.get(response.headers.location, function (err, response, body)
{
if (!err)
{
// parse URL
var result = url.parse(response.req.path, true);
if (result.query.authentication_error)
{
// try to extract login error from website
var error_message = /errorDivMessage\"\>\s*(.*)\<br \/\>/.exec(body);
if (error_message && error_message[1])
{
Log("Login failed! Error from Sony: " + error_message[1]);
if (callback) callback(error_message[1]);
}
else
{
Log("Login failed!");
if (callback) callback("Login failed!");
}
return;
}
else
{
// no auth error!
var auth_result = url.parse(result.query.targetUrl, true);
if (auth_result.query.authCode)
{
Log("Got auth code: " + auth_result.query.authCode);
auth_obj.auth_code = auth_result.query.authCode;
if (callback) callback(false);
return;
}
else
{
Log("Auth error " + auth_result.query.error_code + ": " + auth_result.query.error_description);
if (callback) callback("Auth error " + auth_result.query.error_code + ": " + auth_result.query.error_description);
return;
}
}
}
else
{
Log("Auth code fetch error: " + err);
if (callback) callback(err);
return;
}
});
}
}
);
}
}
);
} | [
"function",
"Login",
"(",
"callback",
")",
"{",
"Log",
"(",
"\"Making OAuth Request...\"",
")",
";",
"_URLGET",
"(",
"urls",
".",
"login_base",
"+",
"\"/2.0/oauth/authorize\"",
",",
"GetOAuthData",
"(",
"{",
"response_type",
":",
"\"code\"",
",",
"service_entity",
":",
"\"urn:service-entity:psn\"",
",",
"returnAuthCode",
":",
"true",
",",
"state",
":",
"\"1156936032\"",
"}",
")",
",",
"{",
"'User-Agent'",
":",
"ParseStaches",
"(",
"useragent",
")",
"}",
",",
"function",
"(",
"err",
",",
"body",
",",
"response",
")",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"callback",
")",
"callback",
"(",
"err",
")",
";",
"return",
";",
"}",
"else",
"{",
"var",
"login_referrer",
"=",
"response",
".",
"req",
".",
"path",
";",
"Log",
"(",
"\"Logging in...\"",
")",
";",
"request",
"(",
"{",
"url",
":",
"urls",
".",
"login_base",
"+",
"\"/login.do\"",
",",
"method",
":",
"\"POST\"",
",",
"headers",
":",
"{",
"'User-Agent'",
":",
"ParseStaches",
"(",
"useragent",
")",
",",
"'X-Requested-With'",
":",
"headers",
"[",
"\"X-Requested-With\"",
"]",
",",
"'Origin'",
":",
"'https://auth.api.sonyentertainmentnetwork.com'",
",",
"'Referer'",
":",
"login_referrer",
",",
"}",
",",
"form",
":",
"{",
"'params'",
":",
"new",
"Buffer",
"(",
"login_params",
")",
".",
"toString",
"(",
"'base64'",
")",
",",
"'j_username'",
":",
"login_details",
".",
"email",
",",
"'j_password'",
":",
"login_details",
".",
"password",
"}",
"}",
",",
"function",
"(",
"err",
",",
"response",
",",
"body",
")",
"{",
"if",
"(",
"err",
")",
"{",
"Log",
"(",
"\"Failed to make login request\"",
")",
";",
"if",
"(",
"callback",
")",
"callback",
"(",
"err",
")",
";",
"return",
";",
"}",
"else",
"{",
"Log",
"(",
"\"Following login...\"",
")",
";",
"request",
".",
"get",
"(",
"response",
".",
"headers",
".",
"location",
",",
"function",
"(",
"err",
",",
"response",
",",
"body",
")",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"var",
"result",
"=",
"url",
".",
"parse",
"(",
"response",
".",
"req",
".",
"path",
",",
"true",
")",
";",
"if",
"(",
"result",
".",
"query",
".",
"authentication_error",
")",
"{",
"var",
"error_message",
"=",
"/",
"errorDivMessage\\\"\\>\\s*(.*)\\<br \\/\\>",
"/",
".",
"exec",
"(",
"body",
")",
";",
"if",
"(",
"error_message",
"&&",
"error_message",
"[",
"1",
"]",
")",
"{",
"Log",
"(",
"\"Login failed! Error from Sony: \"",
"+",
"error_message",
"[",
"1",
"]",
")",
";",
"if",
"(",
"callback",
")",
"callback",
"(",
"error_message",
"[",
"1",
"]",
")",
";",
"}",
"else",
"{",
"Log",
"(",
"\"Login failed!\"",
")",
";",
"if",
"(",
"callback",
")",
"callback",
"(",
"\"Login failed!\"",
")",
";",
"}",
"return",
";",
"}",
"else",
"{",
"var",
"auth_result",
"=",
"url",
".",
"parse",
"(",
"result",
".",
"query",
".",
"targetUrl",
",",
"true",
")",
";",
"if",
"(",
"auth_result",
".",
"query",
".",
"authCode",
")",
"{",
"Log",
"(",
"\"Got auth code: \"",
"+",
"auth_result",
".",
"query",
".",
"authCode",
")",
";",
"auth_obj",
".",
"auth_code",
"=",
"auth_result",
".",
"query",
".",
"authCode",
";",
"if",
"(",
"callback",
")",
"callback",
"(",
"false",
")",
";",
"return",
";",
"}",
"else",
"{",
"Log",
"(",
"\"Auth error \"",
"+",
"auth_result",
".",
"query",
".",
"error_code",
"+",
"\": \"",
"+",
"auth_result",
".",
"query",
".",
"error_description",
")",
";",
"if",
"(",
"callback",
")",
"callback",
"(",
"\"Auth error \"",
"+",
"auth_result",
".",
"query",
".",
"error_code",
"+",
"\": \"",
"+",
"auth_result",
".",
"query",
".",
"error_description",
")",
";",
"return",
";",
"}",
"}",
"}",
"else",
"{",
"Log",
"(",
"\"Auth code fetch error: \"",
"+",
"err",
")",
";",
"if",
"(",
"callback",
")",
"callback",
"(",
"err",
")",
";",
"return",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Login to app and get auth token | [
"Login",
"to",
"app",
"and",
"get",
"auth",
"token"
]
| 1da280d26e1c61f1237c8ed3b86ea3af48494769 | https://github.com/cubehouse/PSNjs/blob/1da280d26e1c61f1237c8ed3b86ea3af48494769/psn_request.js#L424-L544 | train |
cubehouse/PSNjs | psn_request.js | GetAccessToken | function GetAccessToken(callback)
{
// do we have a refresh token? Or do we need to login from scratch?
if (auth_obj.refresh_token)
{
// we have a refresh token!
Log("Refreshing session...");
if (!auth_obj.refresh_token)
{
if (callback) callback("No refresh token found!");
return;
}
// request new access_token
request.post(
{
url: urls.oauth,
form: GetOAuthData({
"grant_type": "refresh_token",
"refresh_token": auth_obj.refresh_token
})
},
function(err, response, body)
{
_ParseTokenResponse(err, body, callback);
}
);
}
else
{
// no refresh token, sign-in from scratch
Log("Signing in with OAuth...");
// make sure we have an authcode
if (!auth_obj.auth_code)
{
if (callback) callback("No authcode available for OAuth!");
return;
}
// request initial access_token
request.post(
{
url: urls.oauth,
form: GetOAuthData({
"grant_type": "authorization_code",
"code": auth_obj.auth_code
})
},
function(err, response, body)
{
_ParseTokenResponse(err, body, callback);
}
);
}
} | javascript | function GetAccessToken(callback)
{
// do we have a refresh token? Or do we need to login from scratch?
if (auth_obj.refresh_token)
{
// we have a refresh token!
Log("Refreshing session...");
if (!auth_obj.refresh_token)
{
if (callback) callback("No refresh token found!");
return;
}
// request new access_token
request.post(
{
url: urls.oauth,
form: GetOAuthData({
"grant_type": "refresh_token",
"refresh_token": auth_obj.refresh_token
})
},
function(err, response, body)
{
_ParseTokenResponse(err, body, callback);
}
);
}
else
{
// no refresh token, sign-in from scratch
Log("Signing in with OAuth...");
// make sure we have an authcode
if (!auth_obj.auth_code)
{
if (callback) callback("No authcode available for OAuth!");
return;
}
// request initial access_token
request.post(
{
url: urls.oauth,
form: GetOAuthData({
"grant_type": "authorization_code",
"code": auth_obj.auth_code
})
},
function(err, response, body)
{
_ParseTokenResponse(err, body, callback);
}
);
}
} | [
"function",
"GetAccessToken",
"(",
"callback",
")",
"{",
"if",
"(",
"auth_obj",
".",
"refresh_token",
")",
"{",
"Log",
"(",
"\"Refreshing session...\"",
")",
";",
"if",
"(",
"!",
"auth_obj",
".",
"refresh_token",
")",
"{",
"if",
"(",
"callback",
")",
"callback",
"(",
"\"No refresh token found!\"",
")",
";",
"return",
";",
"}",
"request",
".",
"post",
"(",
"{",
"url",
":",
"urls",
".",
"oauth",
",",
"form",
":",
"GetOAuthData",
"(",
"{",
"\"grant_type\"",
":",
"\"refresh_token\"",
",",
"\"refresh_token\"",
":",
"auth_obj",
".",
"refresh_token",
"}",
")",
"}",
",",
"function",
"(",
"err",
",",
"response",
",",
"body",
")",
"{",
"_ParseTokenResponse",
"(",
"err",
",",
"body",
",",
"callback",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"Log",
"(",
"\"Signing in with OAuth...\"",
")",
";",
"if",
"(",
"!",
"auth_obj",
".",
"auth_code",
")",
"{",
"if",
"(",
"callback",
")",
"callback",
"(",
"\"No authcode available for OAuth!\"",
")",
";",
"return",
";",
"}",
"request",
".",
"post",
"(",
"{",
"url",
":",
"urls",
".",
"oauth",
",",
"form",
":",
"GetOAuthData",
"(",
"{",
"\"grant_type\"",
":",
"\"authorization_code\"",
",",
"\"code\"",
":",
"auth_obj",
".",
"auth_code",
"}",
")",
"}",
",",
"function",
"(",
"err",
",",
"response",
",",
"body",
")",
"{",
"_ParseTokenResponse",
"(",
"err",
",",
"body",
",",
"callback",
")",
";",
"}",
")",
";",
"}",
"}"
]
| Get an access token using the PSN oauth service using our current auth config | [
"Get",
"an",
"access",
"token",
"using",
"the",
"PSN",
"oauth",
"service",
"using",
"our",
"current",
"auth",
"config"
]
| 1da280d26e1c61f1237c8ed3b86ea3af48494769 | https://github.com/cubehouse/PSNjs/blob/1da280d26e1c61f1237c8ed3b86ea3af48494769/psn_request.js#L547-L603 | train |
cubehouse/PSNjs | psn_request.js | GetUserData | function GetUserData(callback)
{
Log("Fetching user profile data");
// get the current user's data
parent.Get("https://vl.api.np.km.playstation.net/vl/api/v1/mobile/users/me/info", {}, function(error, data)
{
if (error)
{
Log("Error fetching user profile: " + error);
if (callback) callback("Error fetching user profile: " + error);
return;
}
if (!data.onlineId)
{
Log("Missing PSNId from profile result: " + JSON.stringify(data, null, 2));
if (callback) callback("Missing PSNId from profile result: " + JSON.stringify(data, null, 2));
return;
}
// store user ID
Log("We're logged in as " + data.onlineId);
auth_obj.username = data.onlineId;
// store user's region too
auth_obj.region = data.region;
// save updated data object
DoSave(function()
{
// return no error
if (callback) callback(false);
}
);
// supply self to let API know we are a token fetch function
}, GetUserData);
} | javascript | function GetUserData(callback)
{
Log("Fetching user profile data");
// get the current user's data
parent.Get("https://vl.api.np.km.playstation.net/vl/api/v1/mobile/users/me/info", {}, function(error, data)
{
if (error)
{
Log("Error fetching user profile: " + error);
if (callback) callback("Error fetching user profile: " + error);
return;
}
if (!data.onlineId)
{
Log("Missing PSNId from profile result: " + JSON.stringify(data, null, 2));
if (callback) callback("Missing PSNId from profile result: " + JSON.stringify(data, null, 2));
return;
}
// store user ID
Log("We're logged in as " + data.onlineId);
auth_obj.username = data.onlineId;
// store user's region too
auth_obj.region = data.region;
// save updated data object
DoSave(function()
{
// return no error
if (callback) callback(false);
}
);
// supply self to let API know we are a token fetch function
}, GetUserData);
} | [
"function",
"GetUserData",
"(",
"callback",
")",
"{",
"Log",
"(",
"\"Fetching user profile data\"",
")",
";",
"parent",
".",
"Get",
"(",
"\"https://vl.api.np.km.playstation.net/vl/api/v1/mobile/users/me/info\"",
",",
"{",
"}",
",",
"function",
"(",
"error",
",",
"data",
")",
"{",
"if",
"(",
"error",
")",
"{",
"Log",
"(",
"\"Error fetching user profile: \"",
"+",
"error",
")",
";",
"if",
"(",
"callback",
")",
"callback",
"(",
"\"Error fetching user profile: \"",
"+",
"error",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"data",
".",
"onlineId",
")",
"{",
"Log",
"(",
"\"Missing PSNId from profile result: \"",
"+",
"JSON",
".",
"stringify",
"(",
"data",
",",
"null",
",",
"2",
")",
")",
";",
"if",
"(",
"callback",
")",
"callback",
"(",
"\"Missing PSNId from profile result: \"",
"+",
"JSON",
".",
"stringify",
"(",
"data",
",",
"null",
",",
"2",
")",
")",
";",
"return",
";",
"}",
"Log",
"(",
"\"We're logged in as \"",
"+",
"data",
".",
"onlineId",
")",
";",
"auth_obj",
".",
"username",
"=",
"data",
".",
"onlineId",
";",
"auth_obj",
".",
"region",
"=",
"data",
".",
"region",
";",
"DoSave",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"callback",
")",
"callback",
"(",
"false",
")",
";",
"}",
")",
";",
"}",
",",
"GetUserData",
")",
";",
"}"
]
| Fetch the user's profile data | [
"Fetch",
"the",
"user",
"s",
"profile",
"data"
]
| 1da280d26e1c61f1237c8ed3b86ea3af48494769 | https://github.com/cubehouse/PSNjs/blob/1da280d26e1c61f1237c8ed3b86ea3af48494769/psn_request.js#L698-L734 | train |
cubehouse/PSNjs | psn_request.js | CheckTokens | function CheckTokens(callback, token_fetch)
{
// build list of tokens we're missing
var todo = [];
// force token_fetch to an array
token_fetch = [].concat(token_fetch);
// make sure we're actually logged in first
if (!auth_obj.auth_code)
{
Log("Need to login - no auth token found");
todo.push({name: "Login", func: Login});
}
if (!auth_obj.expire_time || auth_obj.expire_time < new Date().getTime())
{
// token has expired! Fetch access_token again
Log("Need to fetch access tokens - tokens expired");
todo.push({name: "GetAccessToken", func: GetAccessToken});
}
else if (!auth_obj.access_token)
{
// we have no access token (?!)
Log("Need to fetch access tokens - no token available");
todo.push({name: "GetAccessToken", func: GetAccessToken});
}
if (!auth_obj.username || !auth_obj.region)
{
// missing player username/region
Log("Need to fetch userdata - no region or username available");
todo.push({name: "GetUserData", func: GetUserData});
}
if (todo.length == 0)
{
// everything is fine
if (callback) callback(false);
}
else
{
// work through our list of tokens we need to update
var step = function()
{
var func = todo.shift();
if (!func)
{
// all done!
if (callback) callback(false);
return;
}
if (token_fetch.indexOf(func.func) >= 0)
{
// if we're actually calling a token fetch function, skip!
process.nextTick(step);
}
else
{
func.func(function(error) {
if (error)
{
// token fetching error!
if (callback) callback(func.name + " :: " + error);
return;
}
// do next step
process.nextTick(step);
});
}
};
// start updating tokens
process.nextTick(step);
}
} | javascript | function CheckTokens(callback, token_fetch)
{
// build list of tokens we're missing
var todo = [];
// force token_fetch to an array
token_fetch = [].concat(token_fetch);
// make sure we're actually logged in first
if (!auth_obj.auth_code)
{
Log("Need to login - no auth token found");
todo.push({name: "Login", func: Login});
}
if (!auth_obj.expire_time || auth_obj.expire_time < new Date().getTime())
{
// token has expired! Fetch access_token again
Log("Need to fetch access tokens - tokens expired");
todo.push({name: "GetAccessToken", func: GetAccessToken});
}
else if (!auth_obj.access_token)
{
// we have no access token (?!)
Log("Need to fetch access tokens - no token available");
todo.push({name: "GetAccessToken", func: GetAccessToken});
}
if (!auth_obj.username || !auth_obj.region)
{
// missing player username/region
Log("Need to fetch userdata - no region or username available");
todo.push({name: "GetUserData", func: GetUserData});
}
if (todo.length == 0)
{
// everything is fine
if (callback) callback(false);
}
else
{
// work through our list of tokens we need to update
var step = function()
{
var func = todo.shift();
if (!func)
{
// all done!
if (callback) callback(false);
return;
}
if (token_fetch.indexOf(func.func) >= 0)
{
// if we're actually calling a token fetch function, skip!
process.nextTick(step);
}
else
{
func.func(function(error) {
if (error)
{
// token fetching error!
if (callback) callback(func.name + " :: " + error);
return;
}
// do next step
process.nextTick(step);
});
}
};
// start updating tokens
process.nextTick(step);
}
} | [
"function",
"CheckTokens",
"(",
"callback",
",",
"token_fetch",
")",
"{",
"var",
"todo",
"=",
"[",
"]",
";",
"token_fetch",
"=",
"[",
"]",
".",
"concat",
"(",
"token_fetch",
")",
";",
"if",
"(",
"!",
"auth_obj",
".",
"auth_code",
")",
"{",
"Log",
"(",
"\"Need to login - no auth token found\"",
")",
";",
"todo",
".",
"push",
"(",
"{",
"name",
":",
"\"Login\"",
",",
"func",
":",
"Login",
"}",
")",
";",
"}",
"if",
"(",
"!",
"auth_obj",
".",
"expire_time",
"||",
"auth_obj",
".",
"expire_time",
"<",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
")",
"{",
"Log",
"(",
"\"Need to fetch access tokens - tokens expired\"",
")",
";",
"todo",
".",
"push",
"(",
"{",
"name",
":",
"\"GetAccessToken\"",
",",
"func",
":",
"GetAccessToken",
"}",
")",
";",
"}",
"else",
"if",
"(",
"!",
"auth_obj",
".",
"access_token",
")",
"{",
"Log",
"(",
"\"Need to fetch access tokens - no token available\"",
")",
";",
"todo",
".",
"push",
"(",
"{",
"name",
":",
"\"GetAccessToken\"",
",",
"func",
":",
"GetAccessToken",
"}",
")",
";",
"}",
"if",
"(",
"!",
"auth_obj",
".",
"username",
"||",
"!",
"auth_obj",
".",
"region",
")",
"{",
"Log",
"(",
"\"Need to fetch userdata - no region or username available\"",
")",
";",
"todo",
".",
"push",
"(",
"{",
"name",
":",
"\"GetUserData\"",
",",
"func",
":",
"GetUserData",
"}",
")",
";",
"}",
"if",
"(",
"todo",
".",
"length",
"==",
"0",
")",
"{",
"if",
"(",
"callback",
")",
"callback",
"(",
"false",
")",
";",
"}",
"else",
"{",
"var",
"step",
"=",
"function",
"(",
")",
"{",
"var",
"func",
"=",
"todo",
".",
"shift",
"(",
")",
";",
"if",
"(",
"!",
"func",
")",
"{",
"if",
"(",
"callback",
")",
"callback",
"(",
"false",
")",
";",
"return",
";",
"}",
"if",
"(",
"token_fetch",
".",
"indexOf",
"(",
"func",
".",
"func",
")",
">=",
"0",
")",
"{",
"process",
".",
"nextTick",
"(",
"step",
")",
";",
"}",
"else",
"{",
"func",
".",
"func",
"(",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"error",
")",
"{",
"if",
"(",
"callback",
")",
"callback",
"(",
"func",
".",
"name",
"+",
"\" :: \"",
"+",
"error",
")",
";",
"return",
";",
"}",
"process",
".",
"nextTick",
"(",
"step",
")",
";",
"}",
")",
";",
"}",
"}",
";",
"process",
".",
"nextTick",
"(",
"step",
")",
";",
"}",
"}"
]
| Check the session's tokens are still valid! token_fetch var is the function calling the token check in cases where the function is actually already fetching tokens! | [
"Check",
"the",
"session",
"s",
"tokens",
"are",
"still",
"valid!",
"token_fetch",
"var",
"is",
"the",
"function",
"calling",
"the",
"token",
"check",
"in",
"cases",
"where",
"the",
"function",
"is",
"actually",
"already",
"fetching",
"tokens!"
]
| 1da280d26e1c61f1237c8ed3b86ea3af48494769 | https://github.com/cubehouse/PSNjs/blob/1da280d26e1c61f1237c8ed3b86ea3af48494769/psn_request.js#L738-L815 | train |
cubehouse/PSNjs | psn_request.js | function()
{
var func = todo.shift();
if (!func)
{
// all done!
if (callback) callback(false);
return;
}
if (token_fetch.indexOf(func.func) >= 0)
{
// if we're actually calling a token fetch function, skip!
process.nextTick(step);
}
else
{
func.func(function(error) {
if (error)
{
// token fetching error!
if (callback) callback(func.name + " :: " + error);
return;
}
// do next step
process.nextTick(step);
});
}
} | javascript | function()
{
var func = todo.shift();
if (!func)
{
// all done!
if (callback) callback(false);
return;
}
if (token_fetch.indexOf(func.func) >= 0)
{
// if we're actually calling a token fetch function, skip!
process.nextTick(step);
}
else
{
func.func(function(error) {
if (error)
{
// token fetching error!
if (callback) callback(func.name + " :: " + error);
return;
}
// do next step
process.nextTick(step);
});
}
} | [
"function",
"(",
")",
"{",
"var",
"func",
"=",
"todo",
".",
"shift",
"(",
")",
";",
"if",
"(",
"!",
"func",
")",
"{",
"if",
"(",
"callback",
")",
"callback",
"(",
"false",
")",
";",
"return",
";",
"}",
"if",
"(",
"token_fetch",
".",
"indexOf",
"(",
"func",
".",
"func",
")",
">=",
"0",
")",
"{",
"process",
".",
"nextTick",
"(",
"step",
")",
";",
"}",
"else",
"{",
"func",
".",
"func",
"(",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"error",
")",
"{",
"if",
"(",
"callback",
")",
"callback",
"(",
"func",
".",
"name",
"+",
"\" :: \"",
"+",
"error",
")",
";",
"return",
";",
"}",
"process",
".",
"nextTick",
"(",
"step",
")",
";",
"}",
")",
";",
"}",
"}"
]
| work through our list of tokens we need to update | [
"work",
"through",
"our",
"list",
"of",
"tokens",
"we",
"need",
"to",
"update"
]
| 1da280d26e1c61f1237c8ed3b86ea3af48494769 | https://github.com/cubehouse/PSNjs/blob/1da280d26e1c61f1237c8ed3b86ea3af48494769/psn_request.js#L781-L810 | train |
|
cubehouse/PSNjs | psn_request.js | MakePSNRequest | function MakePSNRequest(method, url, fields, callback, token_fetch)
{
// use fields var as callback if it's missed out
if (typeof fields == "function")
{
token_fetch = false;
callback = fields;
fields = {};
}
else if (typeof method == "function")
{
token_fetch = false;
callback = method;
}
// parse stache fields in fields list
for(var field_key in fields)
{
fields[field_key] = ParseStaches(fields[field_key]);
}
CheckTokens(function(error)
{
// check our tokens are fine
if (!error)
{
// make PSN GET request
URLGET(
// parse URL for region etc.
ParseStaches(url),
fields,
method,
function(error, data)
{
if (error)
{
Log("PSN " + method + " Error: " + error);
if (callback) callback(error);
return;
}
if (data.error && (data.error.code === 2105858 || data.error.code === 2138626))
{
// access token has expired/failed/borked
// login again!
Log("Access token failure, try to login again.");
Login(function(error) {
if (error)
{
if (callback) callback(error);
return;
}
// call ourselves
parent.Get(url, fields, callback, token_fetch);
});
}
if (data.error && data.error.message)
{
// server error
if (callback) callback(data.error.code + ": " + data.error.message, data.error);
return;
}
// everything is fine! return data
if (callback) callback(false, data);
}
);
}
else
{
Log("Token error: " + error);
if (callback) callback(error);
return;
}
}, token_fetch);
} | javascript | function MakePSNRequest(method, url, fields, callback, token_fetch)
{
// use fields var as callback if it's missed out
if (typeof fields == "function")
{
token_fetch = false;
callback = fields;
fields = {};
}
else if (typeof method == "function")
{
token_fetch = false;
callback = method;
}
// parse stache fields in fields list
for(var field_key in fields)
{
fields[field_key] = ParseStaches(fields[field_key]);
}
CheckTokens(function(error)
{
// check our tokens are fine
if (!error)
{
// make PSN GET request
URLGET(
// parse URL for region etc.
ParseStaches(url),
fields,
method,
function(error, data)
{
if (error)
{
Log("PSN " + method + " Error: " + error);
if (callback) callback(error);
return;
}
if (data.error && (data.error.code === 2105858 || data.error.code === 2138626))
{
// access token has expired/failed/borked
// login again!
Log("Access token failure, try to login again.");
Login(function(error) {
if (error)
{
if (callback) callback(error);
return;
}
// call ourselves
parent.Get(url, fields, callback, token_fetch);
});
}
if (data.error && data.error.message)
{
// server error
if (callback) callback(data.error.code + ": " + data.error.message, data.error);
return;
}
// everything is fine! return data
if (callback) callback(false, data);
}
);
}
else
{
Log("Token error: " + error);
if (callback) callback(error);
return;
}
}, token_fetch);
} | [
"function",
"MakePSNRequest",
"(",
"method",
",",
"url",
",",
"fields",
",",
"callback",
",",
"token_fetch",
")",
"{",
"if",
"(",
"typeof",
"fields",
"==",
"\"function\"",
")",
"{",
"token_fetch",
"=",
"false",
";",
"callback",
"=",
"fields",
";",
"fields",
"=",
"{",
"}",
";",
"}",
"else",
"if",
"(",
"typeof",
"method",
"==",
"\"function\"",
")",
"{",
"token_fetch",
"=",
"false",
";",
"callback",
"=",
"method",
";",
"}",
"for",
"(",
"var",
"field_key",
"in",
"fields",
")",
"{",
"fields",
"[",
"field_key",
"]",
"=",
"ParseStaches",
"(",
"fields",
"[",
"field_key",
"]",
")",
";",
"}",
"CheckTokens",
"(",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"!",
"error",
")",
"{",
"URLGET",
"(",
"ParseStaches",
"(",
"url",
")",
",",
"fields",
",",
"method",
",",
"function",
"(",
"error",
",",
"data",
")",
"{",
"if",
"(",
"error",
")",
"{",
"Log",
"(",
"\"PSN \"",
"+",
"method",
"+",
"\" Error: \"",
"+",
"error",
")",
";",
"if",
"(",
"callback",
")",
"callback",
"(",
"error",
")",
";",
"return",
";",
"}",
"if",
"(",
"data",
".",
"error",
"&&",
"(",
"data",
".",
"error",
".",
"code",
"===",
"2105858",
"||",
"data",
".",
"error",
".",
"code",
"===",
"2138626",
")",
")",
"{",
"Log",
"(",
"\"Access token failure, try to login again.\"",
")",
";",
"Login",
"(",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"error",
")",
"{",
"if",
"(",
"callback",
")",
"callback",
"(",
"error",
")",
";",
"return",
";",
"}",
"parent",
".",
"Get",
"(",
"url",
",",
"fields",
",",
"callback",
",",
"token_fetch",
")",
";",
"}",
")",
";",
"}",
"if",
"(",
"data",
".",
"error",
"&&",
"data",
".",
"error",
".",
"message",
")",
"{",
"if",
"(",
"callback",
")",
"callback",
"(",
"data",
".",
"error",
".",
"code",
"+",
"\": \"",
"+",
"data",
".",
"error",
".",
"message",
",",
"data",
".",
"error",
")",
";",
"return",
";",
"}",
"if",
"(",
"callback",
")",
"callback",
"(",
"false",
",",
"data",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"Log",
"(",
"\"Token error: \"",
"+",
"error",
")",
";",
"if",
"(",
"callback",
")",
"callback",
"(",
"error",
")",
";",
"return",
";",
"}",
"}",
",",
"token_fetch",
")",
";",
"}"
]
| Make a PSN request | [
"Make",
"a",
"PSN",
"request"
]
| 1da280d26e1c61f1237c8ed3b86ea3af48494769 | https://github.com/cubehouse/PSNjs/blob/1da280d26e1c61f1237c8ed3b86ea3af48494769/psn_request.js#L819-L896 | train |
cubehouse/PSNjs | psn_request.js | Ready | function Ready()
{
if (options.autoconnect)
{
// make a connection request immediately (optional)
parent.GetPSN(true, function() {
if (options.onReady) options.onReady();
return;
});
}
else
{
// just callback that we're ready (if anyone is listening)
if (options.onReady) options.onReady();
return;
}
} | javascript | function Ready()
{
if (options.autoconnect)
{
// make a connection request immediately (optional)
parent.GetPSN(true, function() {
if (options.onReady) options.onReady();
return;
});
}
else
{
// just callback that we're ready (if anyone is listening)
if (options.onReady) options.onReady();
return;
}
} | [
"function",
"Ready",
"(",
")",
"{",
"if",
"(",
"options",
".",
"autoconnect",
")",
"{",
"parent",
".",
"GetPSN",
"(",
"true",
",",
"function",
"(",
")",
"{",
"if",
"(",
"options",
".",
"onReady",
")",
"options",
".",
"onReady",
"(",
")",
";",
"return",
";",
"}",
")",
";",
"}",
"else",
"{",
"if",
"(",
"options",
".",
"onReady",
")",
"options",
".",
"onReady",
"(",
")",
";",
"return",
";",
"}",
"}"
]
| Called when we're all setup | [
"Called",
"when",
"we",
"re",
"all",
"setup"
]
| 1da280d26e1c61f1237c8ed3b86ea3af48494769 | https://github.com/cubehouse/PSNjs/blob/1da280d26e1c61f1237c8ed3b86ea3af48494769/psn_request.js#L944-L960 | train |
kchapelier/poisson-disk-sampling | src/poisson-disk-sampling.js | squaredEuclideanDistance | function squaredEuclideanDistance (point1, point2) {
var result = 0,
i = 0;
for (; i < point1.length; i++) {
result += Math.pow(point1[i] - point2[i], 2);
}
return result;
} | javascript | function squaredEuclideanDistance (point1, point2) {
var result = 0,
i = 0;
for (; i < point1.length; i++) {
result += Math.pow(point1[i] - point2[i], 2);
}
return result;
} | [
"function",
"squaredEuclideanDistance",
"(",
"point1",
",",
"point2",
")",
"{",
"var",
"result",
"=",
"0",
",",
"i",
"=",
"0",
";",
"for",
"(",
";",
"i",
"<",
"point1",
".",
"length",
";",
"i",
"++",
")",
"{",
"result",
"+=",
"Math",
".",
"pow",
"(",
"point1",
"[",
"i",
"]",
"-",
"point2",
"[",
"i",
"]",
",",
"2",
")",
";",
"}",
"return",
"result",
";",
"}"
]
| Get the squared euclidean distance from two points of arbitrary, but equal, dimensions
@param {Array} point1
@param {Array} point2
@returns {number} Squared euclidean distance | [
"Get",
"the",
"squared",
"euclidean",
"distance",
"from",
"two",
"points",
"of",
"arbitrary",
"but",
"equal",
"dimensions"
]
| 61246065acb2398bce9447370caa3926cf15989c | https://github.com/kchapelier/poisson-disk-sampling/blob/61246065acb2398bce9447370caa3926cf15989c/src/poisson-disk-sampling.js#L13-L22 | train |
kchapelier/poisson-disk-sampling | src/poisson-disk-sampling.js | getNeighbourhood | function getNeighbourhood (dimensionNumber) {
var neighbourhood = moore(2, dimensionNumber),
origin = [],
dimension;
for (dimension = 0; dimension < dimensionNumber; dimension++) {
origin.push(0);
}
neighbourhood.push(origin);
// sort by ascending distance to optimize proximity checks
// see point 5.1 in Parallel Poisson Disk Sampling by Li-Yi Wei, 2008
// http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.460.3061&rank=1
neighbourhood.sort(function (n1, n2) {
var squareDist1 = 0,
squareDist2 = 0;
for (var dimension = 0; dimension < dimensionNumber; dimension++) {
squareDist1 += Math.pow(n1[dimension], 2);
squareDist2 += Math.pow(n2[dimension], 2);
}
if (squareDist1 < squareDist2) {
return -1;
} else if(squareDist1 > squareDist2) {
return 1;
} else {
return 0;
}
});
return neighbourhood;
} | javascript | function getNeighbourhood (dimensionNumber) {
var neighbourhood = moore(2, dimensionNumber),
origin = [],
dimension;
for (dimension = 0; dimension < dimensionNumber; dimension++) {
origin.push(0);
}
neighbourhood.push(origin);
// sort by ascending distance to optimize proximity checks
// see point 5.1 in Parallel Poisson Disk Sampling by Li-Yi Wei, 2008
// http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.460.3061&rank=1
neighbourhood.sort(function (n1, n2) {
var squareDist1 = 0,
squareDist2 = 0;
for (var dimension = 0; dimension < dimensionNumber; dimension++) {
squareDist1 += Math.pow(n1[dimension], 2);
squareDist2 += Math.pow(n2[dimension], 2);
}
if (squareDist1 < squareDist2) {
return -1;
} else if(squareDist1 > squareDist2) {
return 1;
} else {
return 0;
}
});
return neighbourhood;
} | [
"function",
"getNeighbourhood",
"(",
"dimensionNumber",
")",
"{",
"var",
"neighbourhood",
"=",
"moore",
"(",
"2",
",",
"dimensionNumber",
")",
",",
"origin",
"=",
"[",
"]",
",",
"dimension",
";",
"for",
"(",
"dimension",
"=",
"0",
";",
"dimension",
"<",
"dimensionNumber",
";",
"dimension",
"++",
")",
"{",
"origin",
".",
"push",
"(",
"0",
")",
";",
"}",
"neighbourhood",
".",
"push",
"(",
"origin",
")",
";",
"neighbourhood",
".",
"sort",
"(",
"function",
"(",
"n1",
",",
"n2",
")",
"{",
"var",
"squareDist1",
"=",
"0",
",",
"squareDist2",
"=",
"0",
";",
"for",
"(",
"var",
"dimension",
"=",
"0",
";",
"dimension",
"<",
"dimensionNumber",
";",
"dimension",
"++",
")",
"{",
"squareDist1",
"+=",
"Math",
".",
"pow",
"(",
"n1",
"[",
"dimension",
"]",
",",
"2",
")",
";",
"squareDist2",
"+=",
"Math",
".",
"pow",
"(",
"n2",
"[",
"dimension",
"]",
",",
"2",
")",
";",
"}",
"if",
"(",
"squareDist1",
"<",
"squareDist2",
")",
"{",
"return",
"-",
"1",
";",
"}",
"else",
"if",
"(",
"squareDist1",
">",
"squareDist2",
")",
"{",
"return",
"1",
";",
"}",
"else",
"{",
"return",
"0",
";",
"}",
"}",
")",
";",
"return",
"neighbourhood",
";",
"}"
]
| Get the neighbourhood ordered by distance, including the origin point
@param {int} dimensionNumber Number of dimensions
@returns {Array} Neighbourhood | [
"Get",
"the",
"neighbourhood",
"ordered",
"by",
"distance",
"including",
"the",
"origin",
"point"
]
| 61246065acb2398bce9447370caa3926cf15989c | https://github.com/kchapelier/poisson-disk-sampling/blob/61246065acb2398bce9447370caa3926cf15989c/src/poisson-disk-sampling.js#L29-L62 | train |
nightwolfz/mobx-connect | src/connect.js | provide | function provide() {
if (console) console.warn('@provide is now deprecated. Use @connect instead');
return composeWithContext(Array.prototype.slice.call(arguments))
} | javascript | function provide() {
if (console) console.warn('@provide is now deprecated. Use @connect instead');
return composeWithContext(Array.prototype.slice.call(arguments))
} | [
"function",
"provide",
"(",
")",
"{",
"if",
"(",
"console",
")",
"console",
".",
"warn",
"(",
"'@provide is now deprecated. Use @connect instead'",
")",
";",
"return",
"composeWithContext",
"(",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
")",
"}"
]
| Grant components access to store and state without making observable
@param args {Component|...String}
@returns {Component|Object} | [
"Grant",
"components",
"access",
"to",
"store",
"and",
"state",
"without",
"making",
"observable"
]
| 139636954359079717f4ac522fe5943efab6744d | https://github.com/nightwolfz/mobx-connect/blob/139636954359079717f4ac522fe5943efab6744d/src/connect.js#L76-L79 | train |
dailymotion/vmap-js | src/parser_utils.js | parseNodeValue | function parseNodeValue(node) {
const childNodes = node && node.childNodes && [...node.childNodes];
if (!childNodes) {
return {};
}
// Trying to find and parse CDATA as JSON
const cdatas = childNodes.filter((childNode) => childNode.nodeName === '#cdata-section');
if (cdatas && cdatas.length > 0) {
try {
return JSON.parse(cdatas[0].data);
} catch (e) {}
}
// Didn't find any CDATA or failed to parse it as JSON
return childNodes.reduce((previousText, childNode) => {
let nodeText = '';
switch (childNode.nodeName) {
case '#text':
nodeText = childNode.textContent.trim();
break;
case '#cdata-section':
nodeText = childNode.data;
break;
}
return previousText + nodeText;
}, '');
} | javascript | function parseNodeValue(node) {
const childNodes = node && node.childNodes && [...node.childNodes];
if (!childNodes) {
return {};
}
// Trying to find and parse CDATA as JSON
const cdatas = childNodes.filter((childNode) => childNode.nodeName === '#cdata-section');
if (cdatas && cdatas.length > 0) {
try {
return JSON.parse(cdatas[0].data);
} catch (e) {}
}
// Didn't find any CDATA or failed to parse it as JSON
return childNodes.reduce((previousText, childNode) => {
let nodeText = '';
switch (childNode.nodeName) {
case '#text':
nodeText = childNode.textContent.trim();
break;
case '#cdata-section':
nodeText = childNode.data;
break;
}
return previousText + nodeText;
}, '');
} | [
"function",
"parseNodeValue",
"(",
"node",
")",
"{",
"const",
"childNodes",
"=",
"node",
"&&",
"node",
".",
"childNodes",
"&&",
"[",
"...",
"node",
".",
"childNodes",
"]",
";",
"if",
"(",
"!",
"childNodes",
")",
"{",
"return",
"{",
"}",
";",
"}",
"const",
"cdatas",
"=",
"childNodes",
".",
"filter",
"(",
"(",
"childNode",
")",
"=>",
"childNode",
".",
"nodeName",
"===",
"'#cdata-section'",
")",
";",
"if",
"(",
"cdatas",
"&&",
"cdatas",
".",
"length",
">",
"0",
")",
"{",
"try",
"{",
"return",
"JSON",
".",
"parse",
"(",
"cdatas",
"[",
"0",
"]",
".",
"data",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"}",
"return",
"childNodes",
".",
"reduce",
"(",
"(",
"previousText",
",",
"childNode",
")",
"=>",
"{",
"let",
"nodeText",
"=",
"''",
";",
"switch",
"(",
"childNode",
".",
"nodeName",
")",
"{",
"case",
"'#text'",
":",
"nodeText",
"=",
"childNode",
".",
"textContent",
".",
"trim",
"(",
")",
";",
"break",
";",
"case",
"'#cdata-section'",
":",
"nodeText",
"=",
"childNode",
".",
"data",
";",
"break",
";",
"}",
"return",
"previousText",
"+",
"nodeText",
";",
"}",
",",
"''",
")",
";",
"}"
]
| Parses a node value giving priority to CDATA as a JSON over text, if CDATA is not a valid JSON it is converted to text
@param {Object} node - The node to parse the value from.
@return {String|Object} | [
"Parses",
"a",
"node",
"value",
"giving",
"priority",
"to",
"CDATA",
"as",
"a",
"JSON",
"over",
"text",
"if",
"CDATA",
"is",
"not",
"a",
"valid",
"JSON",
"it",
"is",
"converted",
"to",
"text"
]
| 7c16cc5745dc819343856de4f7252659a66c463e | https://github.com/dailymotion/vmap-js/blob/7c16cc5745dc819343856de4f7252659a66c463e/src/parser_utils.js#L21-L48 | train |
dailymotion/vmap-js | src/parser_utils.js | parseXMLNode | function parseXMLNode(node) {
const parsedNode = {
attributes: {},
children: {},
value: {},
};
parsedNode.value = parseNodeValue(node);
if (node.attributes) {
[...node.attributes].forEach((nodeAttr) => {
if (nodeAttr.nodeName && nodeAttr.nodeValue !== undefined && nodeAttr.nodeValue !== null) {
parsedNode.attributes[nodeAttr.nodeName] = nodeAttr.nodeValue;
}
});
}
if (node.childNodes) {
[...node.childNodes]
.filter((childNode) => childNode.nodeName.substring(0, 1) !== '#')
.forEach((childNode) => {
parsedNode.children[childNode.nodeName] = parseXMLNode(childNode);
});
}
return parsedNode;
} | javascript | function parseXMLNode(node) {
const parsedNode = {
attributes: {},
children: {},
value: {},
};
parsedNode.value = parseNodeValue(node);
if (node.attributes) {
[...node.attributes].forEach((nodeAttr) => {
if (nodeAttr.nodeName && nodeAttr.nodeValue !== undefined && nodeAttr.nodeValue !== null) {
parsedNode.attributes[nodeAttr.nodeName] = nodeAttr.nodeValue;
}
});
}
if (node.childNodes) {
[...node.childNodes]
.filter((childNode) => childNode.nodeName.substring(0, 1) !== '#')
.forEach((childNode) => {
parsedNode.children[childNode.nodeName] = parseXMLNode(childNode);
});
}
return parsedNode;
} | [
"function",
"parseXMLNode",
"(",
"node",
")",
"{",
"const",
"parsedNode",
"=",
"{",
"attributes",
":",
"{",
"}",
",",
"children",
":",
"{",
"}",
",",
"value",
":",
"{",
"}",
",",
"}",
";",
"parsedNode",
".",
"value",
"=",
"parseNodeValue",
"(",
"node",
")",
";",
"if",
"(",
"node",
".",
"attributes",
")",
"{",
"[",
"...",
"node",
".",
"attributes",
"]",
".",
"forEach",
"(",
"(",
"nodeAttr",
")",
"=>",
"{",
"if",
"(",
"nodeAttr",
".",
"nodeName",
"&&",
"nodeAttr",
".",
"nodeValue",
"!==",
"undefined",
"&&",
"nodeAttr",
".",
"nodeValue",
"!==",
"null",
")",
"{",
"parsedNode",
".",
"attributes",
"[",
"nodeAttr",
".",
"nodeName",
"]",
"=",
"nodeAttr",
".",
"nodeValue",
";",
"}",
"}",
")",
";",
"}",
"if",
"(",
"node",
".",
"childNodes",
")",
"{",
"[",
"...",
"node",
".",
"childNodes",
"]",
".",
"filter",
"(",
"(",
"childNode",
")",
"=>",
"childNode",
".",
"nodeName",
".",
"substring",
"(",
"0",
",",
"1",
")",
"!==",
"'#'",
")",
".",
"forEach",
"(",
"(",
"childNode",
")",
"=>",
"{",
"parsedNode",
".",
"children",
"[",
"childNode",
".",
"nodeName",
"]",
"=",
"parseXMLNode",
"(",
"childNode",
")",
";",
"}",
")",
";",
"}",
"return",
"parsedNode",
";",
"}"
]
| Parses an XML node recursively.
@param {Object} node - The node to parse.
@return {Object} | [
"Parses",
"an",
"XML",
"node",
"recursively",
"."
]
| 7c16cc5745dc819343856de4f7252659a66c463e | https://github.com/dailymotion/vmap-js/blob/7c16cc5745dc819343856de4f7252659a66c463e/src/parser_utils.js#L55-L81 | train |
c-h-/node-run-cmd | index.js | async | function async(makeGenerator) {
return () => {
const generator = makeGenerator(...arguments);
function handle(result) {
// result => { done: [Boolean], value: [Object] }
if (result.done) {
return Promise.resolve(result.value);
}
return Promise.resolve(result.value).then(res => {
return handle(generator.next(res));
}, err => {
return handle(generator.throw(err));
});
}
try {
return handle(generator.next());
} catch (ex) {
return Promise.reject(ex);
}
};
} | javascript | function async(makeGenerator) {
return () => {
const generator = makeGenerator(...arguments);
function handle(result) {
// result => { done: [Boolean], value: [Object] }
if (result.done) {
return Promise.resolve(result.value);
}
return Promise.resolve(result.value).then(res => {
return handle(generator.next(res));
}, err => {
return handle(generator.throw(err));
});
}
try {
return handle(generator.next());
} catch (ex) {
return Promise.reject(ex);
}
};
} | [
"function",
"async",
"(",
"makeGenerator",
")",
"{",
"return",
"(",
")",
"=>",
"{",
"const",
"generator",
"=",
"makeGenerator",
"(",
"...",
"arguments",
")",
";",
"function",
"handle",
"(",
"result",
")",
"{",
"if",
"(",
"result",
".",
"done",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"result",
".",
"value",
")",
";",
"}",
"return",
"Promise",
".",
"resolve",
"(",
"result",
".",
"value",
")",
".",
"then",
"(",
"res",
"=>",
"{",
"return",
"handle",
"(",
"generator",
".",
"next",
"(",
"res",
")",
")",
";",
"}",
",",
"err",
"=>",
"{",
"return",
"handle",
"(",
"generator",
".",
"throw",
"(",
"err",
")",
")",
";",
"}",
")",
";",
"}",
"try",
"{",
"return",
"handle",
"(",
"generator",
".",
"next",
"(",
")",
")",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"ex",
")",
";",
"}",
"}",
";",
"}"
]
| Returns a function that resolves any yielded promises inside the generator.
@param {Function} makeGenerator - the function to turn into an async generator/promise
@returns {Function} the function that will iterate over interior promises on each call when invoked | [
"Returns",
"a",
"function",
"that",
"resolves",
"any",
"yielded",
"promises",
"inside",
"the",
"generator",
"."
]
| 2cca799e75cbb6afba63dc6ae1598324143a71d6 | https://github.com/c-h-/node-run-cmd/blob/2cca799e75cbb6afba63dc6ae1598324143a71d6/index.js#L107-L130 | train |
c-h-/node-run-cmd | index.js | runMultiple | function runMultiple(input, options) {
return new Promise((resolve, reject) => {
let commands = input;
// set default options
const defaultOpts = {
cwd: process.cwd(),
verbose: DEFAULT_VERBOSE,
mode: SEQUENTIAL,
logger: console.log,
};
// set global options
const globalOpts = Object.assign({}, defaultOpts, options);
// resolve string to proper input type
if (typeof commands === 'string') {
commands = [{ command: commands }];
}
// start execution
if (commands && typeof commands === 'object') {
if (Object.prototype.toString.call(commands) !== '[object Array]') {
// not array
commands = [commands];
}
else {
// is array, check type of children
commands = commands.map(cmd => typeof cmd === 'object' ? cmd : { command: cmd });
}
// run commands in parallel
if (globalOpts.mode === PARALLEL) {
const promises = commands.map(cmd => {
const resolvedOpts = Object.assign({}, globalOpts, cmd);
return run(resolvedOpts);
});
Promise.all(promises).then(resolve, reject);
}
else { // run commands in sequence (default)
async(function* () {
try {
const results = [];
for (const i in commands) {
const cmd = commands[i];
const resolvedOpts = Object.assign({}, globalOpts, cmd);
const result = yield run(resolvedOpts);
results.push(result);
}
if (results) {
resolve(results);
}
else {
reject('Falsy value in results');
}
}
catch (e) {
reject(e);
}
})();
}
}
else {
reject('Invalid input');
}
});
} | javascript | function runMultiple(input, options) {
return new Promise((resolve, reject) => {
let commands = input;
// set default options
const defaultOpts = {
cwd: process.cwd(),
verbose: DEFAULT_VERBOSE,
mode: SEQUENTIAL,
logger: console.log,
};
// set global options
const globalOpts = Object.assign({}, defaultOpts, options);
// resolve string to proper input type
if (typeof commands === 'string') {
commands = [{ command: commands }];
}
// start execution
if (commands && typeof commands === 'object') {
if (Object.prototype.toString.call(commands) !== '[object Array]') {
// not array
commands = [commands];
}
else {
// is array, check type of children
commands = commands.map(cmd => typeof cmd === 'object' ? cmd : { command: cmd });
}
// run commands in parallel
if (globalOpts.mode === PARALLEL) {
const promises = commands.map(cmd => {
const resolvedOpts = Object.assign({}, globalOpts, cmd);
return run(resolvedOpts);
});
Promise.all(promises).then(resolve, reject);
}
else { // run commands in sequence (default)
async(function* () {
try {
const results = [];
for (const i in commands) {
const cmd = commands[i];
const resolvedOpts = Object.assign({}, globalOpts, cmd);
const result = yield run(resolvedOpts);
results.push(result);
}
if (results) {
resolve(results);
}
else {
reject('Falsy value in results');
}
}
catch (e) {
reject(e);
}
})();
}
}
else {
reject('Invalid input');
}
});
} | [
"function",
"runMultiple",
"(",
"input",
",",
"options",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"let",
"commands",
"=",
"input",
";",
"const",
"defaultOpts",
"=",
"{",
"cwd",
":",
"process",
".",
"cwd",
"(",
")",
",",
"verbose",
":",
"DEFAULT_VERBOSE",
",",
"mode",
":",
"SEQUENTIAL",
",",
"logger",
":",
"console",
".",
"log",
",",
"}",
";",
"const",
"globalOpts",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"defaultOpts",
",",
"options",
")",
";",
"if",
"(",
"typeof",
"commands",
"===",
"'string'",
")",
"{",
"commands",
"=",
"[",
"{",
"command",
":",
"commands",
"}",
"]",
";",
"}",
"if",
"(",
"commands",
"&&",
"typeof",
"commands",
"===",
"'object'",
")",
"{",
"if",
"(",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"commands",
")",
"!==",
"'[object Array]'",
")",
"{",
"commands",
"=",
"[",
"commands",
"]",
";",
"}",
"else",
"{",
"commands",
"=",
"commands",
".",
"map",
"(",
"cmd",
"=>",
"typeof",
"cmd",
"===",
"'object'",
"?",
"cmd",
":",
"{",
"command",
":",
"cmd",
"}",
")",
";",
"}",
"if",
"(",
"globalOpts",
".",
"mode",
"===",
"PARALLEL",
")",
"{",
"const",
"promises",
"=",
"commands",
".",
"map",
"(",
"cmd",
"=>",
"{",
"const",
"resolvedOpts",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"globalOpts",
",",
"cmd",
")",
";",
"return",
"run",
"(",
"resolvedOpts",
")",
";",
"}",
")",
";",
"Promise",
".",
"all",
"(",
"promises",
")",
".",
"then",
"(",
"resolve",
",",
"reject",
")",
";",
"}",
"else",
"{",
"async",
"(",
"function",
"*",
"(",
")",
"{",
"try",
"{",
"const",
"results",
"=",
"[",
"]",
";",
"for",
"(",
"const",
"i",
"in",
"commands",
")",
"{",
"const",
"cmd",
"=",
"commands",
"[",
"i",
"]",
";",
"const",
"resolvedOpts",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"globalOpts",
",",
"cmd",
")",
";",
"const",
"result",
"=",
"yield",
"run",
"(",
"resolvedOpts",
")",
";",
"results",
".",
"push",
"(",
"result",
")",
";",
"}",
"if",
"(",
"results",
")",
"{",
"resolve",
"(",
"results",
")",
";",
"}",
"else",
"{",
"reject",
"(",
"'Falsy value in results'",
")",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"reject",
"(",
"e",
")",
";",
"}",
"}",
")",
"(",
")",
";",
"}",
"}",
"else",
"{",
"reject",
"(",
"'Invalid input'",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Run multiple commands.
@param {Array} commands - an array of objects or strings containing details of commands to run
@param {Object} options - an object containing global options for each command
@example
runMultiple(['mkdir test', 'cd test', 'ls']);
@example
runMultiple(['mkdir test', 'cd test', 'ls'], { cwd: '../myCustomWorkingDirectory' });
@example
const commandsToRun = [
{ command: 'ls', onData: function(data) { console.log(data) } },
override globalOptions working directory with each commands' options
{ command: 'mkdir test', cwd: '../../customCwdNumber2', onDone: function() { console.log('done mkdir!') } },
'ls ~/Desktop' // finish up with simple string command
];
const globalOptions = { cwd: '../myCustomWorkingDirectory' };
runMultiple(commandsToRun, globalOptions); | [
"Run",
"multiple",
"commands",
"."
]
| 2cca799e75cbb6afba63dc6ae1598324143a71d6 | https://github.com/c-h-/node-run-cmd/blob/2cca799e75cbb6afba63dc6ae1598324143a71d6/index.js#L151-L216 | train |
parkerd/statsd-zabbix-backend | lib/zabbix.js | itemsForCounter | function itemsForCounter(flushInterval, host, key, value) {
const avg = value / (flushInterval / 1000); // calculate "per second" rate
return [
{
host,
key: `${key}[total]`,
value,
},
{
host,
key: `${key}[avg]`,
value: avg,
},
];
} | javascript | function itemsForCounter(flushInterval, host, key, value) {
const avg = value / (flushInterval / 1000); // calculate "per second" rate
return [
{
host,
key: `${key}[total]`,
value,
},
{
host,
key: `${key}[avg]`,
value: avg,
},
];
} | [
"function",
"itemsForCounter",
"(",
"flushInterval",
",",
"host",
",",
"key",
",",
"value",
")",
"{",
"const",
"avg",
"=",
"value",
"/",
"(",
"flushInterval",
"/",
"1000",
")",
";",
"return",
"[",
"{",
"host",
",",
"key",
":",
"`",
"${",
"key",
"}",
"`",
",",
"value",
",",
"}",
",",
"{",
"host",
",",
"key",
":",
"`",
"${",
"key",
"}",
"`",
",",
"value",
":",
"avg",
",",
"}",
",",
"]",
";",
"}"
]
| Generate items for a counter.
@param {number} flushInterval How long stats were collected, for calculating average.
@param {string} host Hostname in Zabbix.
@param {string} key Item key in Zabbix.
@param {number} value Total collected during interval.
@returns {array} Array of {host, key, value} objects. | [
"Generate",
"items",
"for",
"a",
"counter",
"."
]
| e459939108ae6aee3b155eed6b76eba1dc053af9 | https://github.com/parkerd/statsd-zabbix-backend/blob/e459939108ae6aee3b155eed6b76eba1dc053af9/lib/zabbix.js#L116-L131 | train |
parkerd/statsd-zabbix-backend | lib/zabbix.js | itemsForTimer | function itemsForTimer(percentiles, host, key, data) {
const values = data.sort((a, b) => (a - b));
const count = values.length;
const min = values[0];
const max = values[count - 1];
let mean = min;
let maxAtThreshold = max;
const items = [
{
host,
key: `${key}[lower]`,
value: min || 0,
},
{
host,
key: `${key}[upper]`,
value: max || 0,
},
{
host,
key: `${key}[count]`,
value: count,
},
];
percentiles.forEach((percentile) => {
const strPercentile = percentile.toString().replace('.', '_');
if (count > 1) {
const thresholdIndex = Math.round(((100 - percentile) / 100) * count);
const numInThreshold = count - thresholdIndex;
const percentValues = values.slice(0, numInThreshold);
maxAtThreshold = percentValues[numInThreshold - 1];
// Average the remaining timings
let sum = 0;
for (let i = 0; i < numInThreshold; i += 1) {
sum += percentValues[i];
}
mean = sum / numInThreshold;
}
items.push({
host,
key: `${key}[mean][${strPercentile}]`,
value: mean || 0,
});
items.push({
host,
key: `${key}[upper][${strPercentile}]`,
value: maxAtThreshold || 0,
});
});
return items;
} | javascript | function itemsForTimer(percentiles, host, key, data) {
const values = data.sort((a, b) => (a - b));
const count = values.length;
const min = values[0];
const max = values[count - 1];
let mean = min;
let maxAtThreshold = max;
const items = [
{
host,
key: `${key}[lower]`,
value: min || 0,
},
{
host,
key: `${key}[upper]`,
value: max || 0,
},
{
host,
key: `${key}[count]`,
value: count,
},
];
percentiles.forEach((percentile) => {
const strPercentile = percentile.toString().replace('.', '_');
if (count > 1) {
const thresholdIndex = Math.round(((100 - percentile) / 100) * count);
const numInThreshold = count - thresholdIndex;
const percentValues = values.slice(0, numInThreshold);
maxAtThreshold = percentValues[numInThreshold - 1];
// Average the remaining timings
let sum = 0;
for (let i = 0; i < numInThreshold; i += 1) {
sum += percentValues[i];
}
mean = sum / numInThreshold;
}
items.push({
host,
key: `${key}[mean][${strPercentile}]`,
value: mean || 0,
});
items.push({
host,
key: `${key}[upper][${strPercentile}]`,
value: maxAtThreshold || 0,
});
});
return items;
} | [
"function",
"itemsForTimer",
"(",
"percentiles",
",",
"host",
",",
"key",
",",
"data",
")",
"{",
"const",
"values",
"=",
"data",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"(",
"a",
"-",
"b",
")",
")",
";",
"const",
"count",
"=",
"values",
".",
"length",
";",
"const",
"min",
"=",
"values",
"[",
"0",
"]",
";",
"const",
"max",
"=",
"values",
"[",
"count",
"-",
"1",
"]",
";",
"let",
"mean",
"=",
"min",
";",
"let",
"maxAtThreshold",
"=",
"max",
";",
"const",
"items",
"=",
"[",
"{",
"host",
",",
"key",
":",
"`",
"${",
"key",
"}",
"`",
",",
"value",
":",
"min",
"||",
"0",
",",
"}",
",",
"{",
"host",
",",
"key",
":",
"`",
"${",
"key",
"}",
"`",
",",
"value",
":",
"max",
"||",
"0",
",",
"}",
",",
"{",
"host",
",",
"key",
":",
"`",
"${",
"key",
"}",
"`",
",",
"value",
":",
"count",
",",
"}",
",",
"]",
";",
"percentiles",
".",
"forEach",
"(",
"(",
"percentile",
")",
"=>",
"{",
"const",
"strPercentile",
"=",
"percentile",
".",
"toString",
"(",
")",
".",
"replace",
"(",
"'.'",
",",
"'_'",
")",
";",
"if",
"(",
"count",
">",
"1",
")",
"{",
"const",
"thresholdIndex",
"=",
"Math",
".",
"round",
"(",
"(",
"(",
"100",
"-",
"percentile",
")",
"/",
"100",
")",
"*",
"count",
")",
";",
"const",
"numInThreshold",
"=",
"count",
"-",
"thresholdIndex",
";",
"const",
"percentValues",
"=",
"values",
".",
"slice",
"(",
"0",
",",
"numInThreshold",
")",
";",
"maxAtThreshold",
"=",
"percentValues",
"[",
"numInThreshold",
"-",
"1",
"]",
";",
"let",
"sum",
"=",
"0",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"numInThreshold",
";",
"i",
"+=",
"1",
")",
"{",
"sum",
"+=",
"percentValues",
"[",
"i",
"]",
";",
"}",
"mean",
"=",
"sum",
"/",
"numInThreshold",
";",
"}",
"items",
".",
"push",
"(",
"{",
"host",
",",
"key",
":",
"`",
"${",
"key",
"}",
"${",
"strPercentile",
"}",
"`",
",",
"value",
":",
"mean",
"||",
"0",
",",
"}",
")",
";",
"items",
".",
"push",
"(",
"{",
"host",
",",
"key",
":",
"`",
"${",
"key",
"}",
"${",
"strPercentile",
"}",
"`",
",",
"value",
":",
"maxAtThreshold",
"||",
"0",
",",
"}",
")",
";",
"}",
")",
";",
"return",
"items",
";",
"}"
]
| Generate items for a timer.
@param {array} percentiles Array of numbers, percentiles to calculate mean and max for.
@param {string} host Hostname in Zabbix.
@param {string} key Item key in Zabbix.
@param {number} data All timing values collected during interval.
@returns {array} Array of {host, key, value} objects. | [
"Generate",
"items",
"for",
"a",
"timer",
"."
]
| e459939108ae6aee3b155eed6b76eba1dc053af9 | https://github.com/parkerd/statsd-zabbix-backend/blob/e459939108ae6aee3b155eed6b76eba1dc053af9/lib/zabbix.js#L141-L199 | train |
parkerd/statsd-zabbix-backend | lib/zabbix.js | flush | function flush(targetBuilder, sender, flushInterval, timestamp, metrics) {
debug(`starting flush for timestamp ${timestamp}`);
const flushStart = tsNow();
const handle = (processor, stat, value) => {
try {
const { host, key } = targetBuilder(stat);
processor(host, key, value).forEach((item) => {
sender.addItem(item.host, item.key, item.value);
debug(`${item.host} -> ${item.key} -> ${item.value}`);
});
} catch (err) {
stats.last_exception = tsNow();
error(err);
}
};
const counterProcessor = itemsForCounter.bind(undefined, flushInterval);
Object.keys(metrics.counters).forEach((stat) => {
handle(counterProcessor, stat, metrics.counters[stat]);
});
const timerProcessor = itemsForTimer.bind(undefined, metrics.pctThreshold);
Object.keys(metrics.timers).forEach((stat) => {
handle(timerProcessor, stat, metrics.timers[stat]);
});
Object.keys(metrics.gauges).forEach((stat) => {
handle(itemsForGauge, stat, metrics.gauges[stat]);
});
stats.flush_length = sender.items.length;
debug(`flushing ${stats.flush_length} items to zabbix`);
// Send the items to Zabbix
sender.send((err, res) => {
if (err) {
stats.last_exception = tsNow();
error(err);
// eslint-disable-next-line no-param-reassign
sender.items = [];
} else {
stats.last_flush = timestamp;
stats.flush_time = flushStart - stats.last_flush;
debug(`flush completed in ${stats.flush_time} seconds`);
}
if (res.info) {
info(res.info);
}
});
} | javascript | function flush(targetBuilder, sender, flushInterval, timestamp, metrics) {
debug(`starting flush for timestamp ${timestamp}`);
const flushStart = tsNow();
const handle = (processor, stat, value) => {
try {
const { host, key } = targetBuilder(stat);
processor(host, key, value).forEach((item) => {
sender.addItem(item.host, item.key, item.value);
debug(`${item.host} -> ${item.key} -> ${item.value}`);
});
} catch (err) {
stats.last_exception = tsNow();
error(err);
}
};
const counterProcessor = itemsForCounter.bind(undefined, flushInterval);
Object.keys(metrics.counters).forEach((stat) => {
handle(counterProcessor, stat, metrics.counters[stat]);
});
const timerProcessor = itemsForTimer.bind(undefined, metrics.pctThreshold);
Object.keys(metrics.timers).forEach((stat) => {
handle(timerProcessor, stat, metrics.timers[stat]);
});
Object.keys(metrics.gauges).forEach((stat) => {
handle(itemsForGauge, stat, metrics.gauges[stat]);
});
stats.flush_length = sender.items.length;
debug(`flushing ${stats.flush_length} items to zabbix`);
// Send the items to Zabbix
sender.send((err, res) => {
if (err) {
stats.last_exception = tsNow();
error(err);
// eslint-disable-next-line no-param-reassign
sender.items = [];
} else {
stats.last_flush = timestamp;
stats.flush_time = flushStart - stats.last_flush;
debug(`flush completed in ${stats.flush_time} seconds`);
}
if (res.info) {
info(res.info);
}
});
} | [
"function",
"flush",
"(",
"targetBuilder",
",",
"sender",
",",
"flushInterval",
",",
"timestamp",
",",
"metrics",
")",
"{",
"debug",
"(",
"`",
"${",
"timestamp",
"}",
"`",
")",
";",
"const",
"flushStart",
"=",
"tsNow",
"(",
")",
";",
"const",
"handle",
"=",
"(",
"processor",
",",
"stat",
",",
"value",
")",
"=>",
"{",
"try",
"{",
"const",
"{",
"host",
",",
"key",
"}",
"=",
"targetBuilder",
"(",
"stat",
")",
";",
"processor",
"(",
"host",
",",
"key",
",",
"value",
")",
".",
"forEach",
"(",
"(",
"item",
")",
"=>",
"{",
"sender",
".",
"addItem",
"(",
"item",
".",
"host",
",",
"item",
".",
"key",
",",
"item",
".",
"value",
")",
";",
"debug",
"(",
"`",
"${",
"item",
".",
"host",
"}",
"${",
"item",
".",
"key",
"}",
"${",
"item",
".",
"value",
"}",
"`",
")",
";",
"}",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"stats",
".",
"last_exception",
"=",
"tsNow",
"(",
")",
";",
"error",
"(",
"err",
")",
";",
"}",
"}",
";",
"const",
"counterProcessor",
"=",
"itemsForCounter",
".",
"bind",
"(",
"undefined",
",",
"flushInterval",
")",
";",
"Object",
".",
"keys",
"(",
"metrics",
".",
"counters",
")",
".",
"forEach",
"(",
"(",
"stat",
")",
"=>",
"{",
"handle",
"(",
"counterProcessor",
",",
"stat",
",",
"metrics",
".",
"counters",
"[",
"stat",
"]",
")",
";",
"}",
")",
";",
"const",
"timerProcessor",
"=",
"itemsForTimer",
".",
"bind",
"(",
"undefined",
",",
"metrics",
".",
"pctThreshold",
")",
";",
"Object",
".",
"keys",
"(",
"metrics",
".",
"timers",
")",
".",
"forEach",
"(",
"(",
"stat",
")",
"=>",
"{",
"handle",
"(",
"timerProcessor",
",",
"stat",
",",
"metrics",
".",
"timers",
"[",
"stat",
"]",
")",
";",
"}",
")",
";",
"Object",
".",
"keys",
"(",
"metrics",
".",
"gauges",
")",
".",
"forEach",
"(",
"(",
"stat",
")",
"=>",
"{",
"handle",
"(",
"itemsForGauge",
",",
"stat",
",",
"metrics",
".",
"gauges",
"[",
"stat",
"]",
")",
";",
"}",
")",
";",
"stats",
".",
"flush_length",
"=",
"sender",
".",
"items",
".",
"length",
";",
"debug",
"(",
"`",
"${",
"stats",
".",
"flush_length",
"}",
"`",
")",
";",
"sender",
".",
"send",
"(",
"(",
"err",
",",
"res",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"stats",
".",
"last_exception",
"=",
"tsNow",
"(",
")",
";",
"error",
"(",
"err",
")",
";",
"sender",
".",
"items",
"=",
"[",
"]",
";",
"}",
"else",
"{",
"stats",
".",
"last_flush",
"=",
"timestamp",
";",
"stats",
".",
"flush_time",
"=",
"flushStart",
"-",
"stats",
".",
"last_flush",
";",
"debug",
"(",
"`",
"${",
"stats",
".",
"flush_time",
"}",
"`",
")",
";",
"}",
"if",
"(",
"res",
".",
"info",
")",
"{",
"info",
"(",
"res",
".",
"info",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Flush metrics data to Zabbix.
@param {function} targetBuilder Returns a {host,key} object based on the stat provided.
@param {ZabbixSender} sender Instance of ZabbixSender for sending stats to Zabbix.
@param {number} flushInterval How long stats were collected, for calculating average.
@param {number} timestamp Time of flush as unix timestamp.
@param {Object} metrics Metrics provided by StatsD.
@returns {undefined} | [
"Flush",
"metrics",
"data",
"to",
"Zabbix",
"."
]
| e459939108ae6aee3b155eed6b76eba1dc053af9 | https://github.com/parkerd/statsd-zabbix-backend/blob/e459939108ae6aee3b155eed6b76eba1dc053af9/lib/zabbix.js#L227-L277 | train |
parkerd/statsd-zabbix-backend | lib/zabbix.js | status | function status(writeCb) {
Object.keys(stats).forEach((stat) => {
writeCb(null, 'zabbix', stat, stats[stat]);
});
} | javascript | function status(writeCb) {
Object.keys(stats).forEach((stat) => {
writeCb(null, 'zabbix', stat, stats[stat]);
});
} | [
"function",
"status",
"(",
"writeCb",
")",
"{",
"Object",
".",
"keys",
"(",
"stats",
")",
".",
"forEach",
"(",
"(",
"stat",
")",
"=>",
"{",
"writeCb",
"(",
"null",
",",
"'zabbix'",
",",
"stat",
",",
"stats",
"[",
"stat",
"]",
")",
";",
"}",
")",
";",
"}"
]
| Dump plugin stats.
@param {function} writeCb Callback to write stats to.
@returns {undefined} | [
"Dump",
"plugin",
"stats",
"."
]
| e459939108ae6aee3b155eed6b76eba1dc053af9 | https://github.com/parkerd/statsd-zabbix-backend/blob/e459939108ae6aee3b155eed6b76eba1dc053af9/lib/zabbix.js#L284-L288 | train |
parkerd/statsd-zabbix-backend | lib/zabbix.js | init | function init(startupTime, config, events, l) {
logger = l;
let targetBuilder;
if (config.zabbixTargetHostname) {
targetBuilder = targetStatic.bind(undefined, config.zabbixTargetHostname);
} else {
targetBuilder = targetDecode;
}
const sender = new ZabbixSender({
host: config.zabbixHost || 'localhost',
port: config.zabbixPort || '10051',
with_timestamps: config.zabbixSendTimestamps || false,
});
stats.last_flush = 0;
stats.last_exception = 0;
stats.flush_time = 0;
stats.flush_length = 0;
events.on('flush', flush.bind(undefined, targetBuilder, sender, config.flushInterval));
events.on('status', status);
return true;
} | javascript | function init(startupTime, config, events, l) {
logger = l;
let targetBuilder;
if (config.zabbixTargetHostname) {
targetBuilder = targetStatic.bind(undefined, config.zabbixTargetHostname);
} else {
targetBuilder = targetDecode;
}
const sender = new ZabbixSender({
host: config.zabbixHost || 'localhost',
port: config.zabbixPort || '10051',
with_timestamps: config.zabbixSendTimestamps || false,
});
stats.last_flush = 0;
stats.last_exception = 0;
stats.flush_time = 0;
stats.flush_length = 0;
events.on('flush', flush.bind(undefined, targetBuilder, sender, config.flushInterval));
events.on('status', status);
return true;
} | [
"function",
"init",
"(",
"startupTime",
",",
"config",
",",
"events",
",",
"l",
")",
"{",
"logger",
"=",
"l",
";",
"let",
"targetBuilder",
";",
"if",
"(",
"config",
".",
"zabbixTargetHostname",
")",
"{",
"targetBuilder",
"=",
"targetStatic",
".",
"bind",
"(",
"undefined",
",",
"config",
".",
"zabbixTargetHostname",
")",
";",
"}",
"else",
"{",
"targetBuilder",
"=",
"targetDecode",
";",
"}",
"const",
"sender",
"=",
"new",
"ZabbixSender",
"(",
"{",
"host",
":",
"config",
".",
"zabbixHost",
"||",
"'localhost'",
",",
"port",
":",
"config",
".",
"zabbixPort",
"||",
"'10051'",
",",
"with_timestamps",
":",
"config",
".",
"zabbixSendTimestamps",
"||",
"false",
",",
"}",
")",
";",
"stats",
".",
"last_flush",
"=",
"0",
";",
"stats",
".",
"last_exception",
"=",
"0",
";",
"stats",
".",
"flush_time",
"=",
"0",
";",
"stats",
".",
"flush_length",
"=",
"0",
";",
"events",
".",
"on",
"(",
"'flush'",
",",
"flush",
".",
"bind",
"(",
"undefined",
",",
"targetBuilder",
",",
"sender",
",",
"config",
".",
"flushInterval",
")",
")",
";",
"events",
".",
"on",
"(",
"'status'",
",",
"status",
")",
";",
"return",
"true",
";",
"}"
]
| Initalize the plugin.
@param {number} startupTime Timestamp StatsD started.
@param {Object} config Global configuration provided to StatsD.
@param {Object} events Event handler to register actions on.
@param {Object} l Global logger instance.
@returns {boolean} Status of initialization. | [
"Initalize",
"the",
"plugin",
"."
]
| e459939108ae6aee3b155eed6b76eba1dc053af9 | https://github.com/parkerd/statsd-zabbix-backend/blob/e459939108ae6aee3b155eed6b76eba1dc053af9/lib/zabbix.js#L298-L323 | train |
gagan-bansal/json-groupby | json-groupby.js | collectProperties | function collectProperties(groups, properties) {
var collection = {};
for (var key in groups) {
if (Array.isArray(groups[key])) {
collection[key] = groups[key].reduce(function(coll, item) {
properties.forEach(function(prop) {
if (!coll[prop]) coll[prop] = [];
coll[prop] = coll[prop].concat(propertyAt(item,prop));
})
return coll;
}, {})
} else {
collection[key] = collectProperties(groups[key], properties);
}
}
return collection;
} | javascript | function collectProperties(groups, properties) {
var collection = {};
for (var key in groups) {
if (Array.isArray(groups[key])) {
collection[key] = groups[key].reduce(function(coll, item) {
properties.forEach(function(prop) {
if (!coll[prop]) coll[prop] = [];
coll[prop] = coll[prop].concat(propertyAt(item,prop));
})
return coll;
}, {})
} else {
collection[key] = collectProperties(groups[key], properties);
}
}
return collection;
} | [
"function",
"collectProperties",
"(",
"groups",
",",
"properties",
")",
"{",
"var",
"collection",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"key",
"in",
"groups",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"groups",
"[",
"key",
"]",
")",
")",
"{",
"collection",
"[",
"key",
"]",
"=",
"groups",
"[",
"key",
"]",
".",
"reduce",
"(",
"function",
"(",
"coll",
",",
"item",
")",
"{",
"properties",
".",
"forEach",
"(",
"function",
"(",
"prop",
")",
"{",
"if",
"(",
"!",
"coll",
"[",
"prop",
"]",
")",
"coll",
"[",
"prop",
"]",
"=",
"[",
"]",
";",
"coll",
"[",
"prop",
"]",
"=",
"coll",
"[",
"prop",
"]",
".",
"concat",
"(",
"propertyAt",
"(",
"item",
",",
"prop",
")",
")",
";",
"}",
")",
"return",
"coll",
";",
"}",
",",
"{",
"}",
")",
"}",
"else",
"{",
"collection",
"[",
"key",
"]",
"=",
"collectProperties",
"(",
"groups",
"[",
"key",
"]",
",",
"properties",
")",
";",
"}",
"}",
"return",
"collection",
";",
"}"
]
| collect the properties in an array | [
"collect",
"the",
"properties",
"in",
"an",
"array"
]
| 4955b1ccb13320d4732147b2500cb162b69b076c | https://github.com/gagan-bansal/json-groupby/blob/4955b1ccb13320d4732147b2500cb162b69b076c/json-groupby.js#L56-L72 | train |
TooTallNate/file-uri-to-path | index.js | fileUriToPath | function fileUriToPath (uri) {
if ('string' != typeof uri ||
uri.length <= 7 ||
'file://' != uri.substring(0, 7)) {
throw new TypeError('must pass in a file:// URI to convert to a file path');
}
var rest = decodeURI(uri.substring(7));
var firstSlash = rest.indexOf('/');
var host = rest.substring(0, firstSlash);
var path = rest.substring(firstSlash + 1);
// 2. Scheme Definition
// As a special case, <host> can be the string "localhost" or the empty
// string; this is interpreted as "the machine from which the URL is
// being interpreted".
if ('localhost' == host) host = '';
if (host) {
host = sep + sep + host;
}
// 3.2 Drives, drive letters, mount points, file system root
// Drive letters are mapped into the top of a file URI in various ways,
// depending on the implementation; some applications substitute
// vertical bar ("|") for the colon after the drive letter, yielding
// "file:///c|/tmp/test.txt". In some cases, the colon is left
// unchanged, as in "file:///c:/tmp/test.txt". In other cases, the
// colon is simply omitted, as in "file:///c/tmp/test.txt".
path = path.replace(/^(.+)\|/, '$1:');
// for Windows, we need to invert the path separators from what a URI uses
if (sep == '\\') {
path = path.replace(/\//g, '\\');
}
if (/^.+\:/.test(path)) {
// has Windows drive at beginning of path
} else {
// unix path…
path = sep + path;
}
return host + path;
} | javascript | function fileUriToPath (uri) {
if ('string' != typeof uri ||
uri.length <= 7 ||
'file://' != uri.substring(0, 7)) {
throw new TypeError('must pass in a file:// URI to convert to a file path');
}
var rest = decodeURI(uri.substring(7));
var firstSlash = rest.indexOf('/');
var host = rest.substring(0, firstSlash);
var path = rest.substring(firstSlash + 1);
// 2. Scheme Definition
// As a special case, <host> can be the string "localhost" or the empty
// string; this is interpreted as "the machine from which the URL is
// being interpreted".
if ('localhost' == host) host = '';
if (host) {
host = sep + sep + host;
}
// 3.2 Drives, drive letters, mount points, file system root
// Drive letters are mapped into the top of a file URI in various ways,
// depending on the implementation; some applications substitute
// vertical bar ("|") for the colon after the drive letter, yielding
// "file:///c|/tmp/test.txt". In some cases, the colon is left
// unchanged, as in "file:///c:/tmp/test.txt". In other cases, the
// colon is simply omitted, as in "file:///c/tmp/test.txt".
path = path.replace(/^(.+)\|/, '$1:');
// for Windows, we need to invert the path separators from what a URI uses
if (sep == '\\') {
path = path.replace(/\//g, '\\');
}
if (/^.+\:/.test(path)) {
// has Windows drive at beginning of path
} else {
// unix path…
path = sep + path;
}
return host + path;
} | [
"function",
"fileUriToPath",
"(",
"uri",
")",
"{",
"if",
"(",
"'string'",
"!=",
"typeof",
"uri",
"||",
"uri",
".",
"length",
"<=",
"7",
"||",
"'file://'",
"!=",
"uri",
".",
"substring",
"(",
"0",
",",
"7",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'must pass in a file:// URI to convert to a file path'",
")",
";",
"}",
"var",
"rest",
"=",
"decodeURI",
"(",
"uri",
".",
"substring",
"(",
"7",
")",
")",
";",
"var",
"firstSlash",
"=",
"rest",
".",
"indexOf",
"(",
"'/'",
")",
";",
"var",
"host",
"=",
"rest",
".",
"substring",
"(",
"0",
",",
"firstSlash",
")",
";",
"var",
"path",
"=",
"rest",
".",
"substring",
"(",
"firstSlash",
"+",
"1",
")",
";",
"if",
"(",
"'localhost'",
"==",
"host",
")",
"host",
"=",
"''",
";",
"if",
"(",
"host",
")",
"{",
"host",
"=",
"sep",
"+",
"sep",
"+",
"host",
";",
"}",
"path",
"=",
"path",
".",
"replace",
"(",
"/",
"^(.+)\\|",
"/",
",",
"'$1:'",
")",
";",
"if",
"(",
"sep",
"==",
"'\\\\'",
")",
"\\\\",
"{",
"path",
"=",
"path",
".",
"replace",
"(",
"/",
"\\/",
"/",
"g",
",",
"'\\\\'",
")",
";",
"}",
"\\\\",
"}"
]
| File URI to Path function.
@param {String} uri
@return {String} path
@api public | [
"File",
"URI",
"to",
"Path",
"function",
"."
]
| db012b4db2c9da9f6eeb5202b4a493450482e0e4 | https://github.com/TooTallNate/file-uri-to-path/blob/db012b4db2c9da9f6eeb5202b4a493450482e0e4/index.js#L22-L66 | train |
stephanebachelier/superapi-cache | dist/hydrate.js | parseHeaders | function parseHeaders() {
var str = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0];
var lines = str.split(/\r?\n/);
var fields = {};
var index = undefined;
var line = undefined;
var field = undefined;
var val = undefined;
lines.pop(); // trailing CRLF
for (var i = 0, len = lines.length; i < len; i += 1) {
line = lines[i];
index = line.indexOf(':');
field = line.slice(0, index).toLowerCase();
val = trim(line.slice(index + 1));
fields[field] = val;
}
return fields;
} | javascript | function parseHeaders() {
var str = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0];
var lines = str.split(/\r?\n/);
var fields = {};
var index = undefined;
var line = undefined;
var field = undefined;
var val = undefined;
lines.pop(); // trailing CRLF
for (var i = 0, len = lines.length; i < len; i += 1) {
line = lines[i];
index = line.indexOf(':');
field = line.slice(0, index).toLowerCase();
val = trim(line.slice(index + 1));
fields[field] = val;
}
return fields;
} | [
"function",
"parseHeaders",
"(",
")",
"{",
"var",
"str",
"=",
"arguments",
".",
"length",
"<=",
"0",
"||",
"arguments",
"[",
"0",
"]",
"===",
"undefined",
"?",
"''",
":",
"arguments",
"[",
"0",
"]",
";",
"var",
"lines",
"=",
"str",
".",
"split",
"(",
"/",
"\\r?\\n",
"/",
")",
";",
"var",
"fields",
"=",
"{",
"}",
";",
"var",
"index",
"=",
"undefined",
";",
"var",
"line",
"=",
"undefined",
";",
"var",
"field",
"=",
"undefined",
";",
"var",
"val",
"=",
"undefined",
";",
"lines",
".",
"pop",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"lines",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"1",
")",
"{",
"line",
"=",
"lines",
"[",
"i",
"]",
";",
"index",
"=",
"line",
".",
"indexOf",
"(",
"':'",
")",
";",
"field",
"=",
"line",
".",
"slice",
"(",
"0",
",",
"index",
")",
".",
"toLowerCase",
"(",
")",
";",
"val",
"=",
"trim",
"(",
"line",
".",
"slice",
"(",
"index",
"+",
"1",
")",
")",
";",
"fields",
"[",
"field",
"]",
"=",
"val",
";",
"}",
"return",
"fields",
";",
"}"
]
| borrow from superagent | [
"borrow",
"from",
"superagent"
]
| 0d9ff011a52b369d8cf82cea135418a1d021e80c | https://github.com/stephanebachelier/superapi-cache/blob/0d9ff011a52b369d8cf82cea135418a1d021e80c/dist/hydrate.js#L28-L49 | train |
wanchain/wanx | src/btc/utils.js | buildHashTimeLockContract | function buildHashTimeLockContract(network, xHash, destH160Addr, revokerH160Addr, lockTime) {
const bitcoinNetwork = bitcoin.networks[network];
const redeemScript = bitcoin.script.compile([
bitcoin.opcodes.OP_IF,
bitcoin.opcodes.OP_SHA256,
Buffer.from(xHash, 'hex'),
bitcoin.opcodes.OP_EQUALVERIFY,
bitcoin.opcodes.OP_DUP,
bitcoin.opcodes.OP_HASH160,
Buffer.from(hex.stripPrefix(destH160Addr), 'hex'),
bitcoin.opcodes.OP_ELSE,
bitcoin.script.number.encode(lockTime),
bitcoin.opcodes.OP_CHECKLOCKTIMEVERIFY,
bitcoin.opcodes.OP_DROP,
bitcoin.opcodes.OP_DUP,
bitcoin.opcodes.OP_HASH160,
Buffer.from(hex.stripPrefix(revokerH160Addr), 'hex'),
bitcoin.opcodes.OP_ENDIF,
bitcoin.opcodes.OP_EQUALVERIFY,
bitcoin.opcodes.OP_CHECKSIG,
]);
const addressPay = bitcoin.payments.p2sh({
redeem: { output: redeemScript, network: bitcoinNetwork },
network: bitcoinNetwork,
});
const { address } = addressPay;
return {
// contract
address,
redeemScript: redeemScript.toString('hex'),
// params
xHash,
lockTime,
redeemer: hex.ensurePrefix(destH160Addr),
revoker: hex.ensurePrefix(revokerH160Addr),
};
} | javascript | function buildHashTimeLockContract(network, xHash, destH160Addr, revokerH160Addr, lockTime) {
const bitcoinNetwork = bitcoin.networks[network];
const redeemScript = bitcoin.script.compile([
bitcoin.opcodes.OP_IF,
bitcoin.opcodes.OP_SHA256,
Buffer.from(xHash, 'hex'),
bitcoin.opcodes.OP_EQUALVERIFY,
bitcoin.opcodes.OP_DUP,
bitcoin.opcodes.OP_HASH160,
Buffer.from(hex.stripPrefix(destH160Addr), 'hex'),
bitcoin.opcodes.OP_ELSE,
bitcoin.script.number.encode(lockTime),
bitcoin.opcodes.OP_CHECKLOCKTIMEVERIFY,
bitcoin.opcodes.OP_DROP,
bitcoin.opcodes.OP_DUP,
bitcoin.opcodes.OP_HASH160,
Buffer.from(hex.stripPrefix(revokerH160Addr), 'hex'),
bitcoin.opcodes.OP_ENDIF,
bitcoin.opcodes.OP_EQUALVERIFY,
bitcoin.opcodes.OP_CHECKSIG,
]);
const addressPay = bitcoin.payments.p2sh({
redeem: { output: redeemScript, network: bitcoinNetwork },
network: bitcoinNetwork,
});
const { address } = addressPay;
return {
// contract
address,
redeemScript: redeemScript.toString('hex'),
// params
xHash,
lockTime,
redeemer: hex.ensurePrefix(destH160Addr),
revoker: hex.ensurePrefix(revokerH160Addr),
};
} | [
"function",
"buildHashTimeLockContract",
"(",
"network",
",",
"xHash",
",",
"destH160Addr",
",",
"revokerH160Addr",
",",
"lockTime",
")",
"{",
"const",
"bitcoinNetwork",
"=",
"bitcoin",
".",
"networks",
"[",
"network",
"]",
";",
"const",
"redeemScript",
"=",
"bitcoin",
".",
"script",
".",
"compile",
"(",
"[",
"bitcoin",
".",
"opcodes",
".",
"OP_IF",
",",
"bitcoin",
".",
"opcodes",
".",
"OP_SHA256",
",",
"Buffer",
".",
"from",
"(",
"xHash",
",",
"'hex'",
")",
",",
"bitcoin",
".",
"opcodes",
".",
"OP_EQUALVERIFY",
",",
"bitcoin",
".",
"opcodes",
".",
"OP_DUP",
",",
"bitcoin",
".",
"opcodes",
".",
"OP_HASH160",
",",
"Buffer",
".",
"from",
"(",
"hex",
".",
"stripPrefix",
"(",
"destH160Addr",
")",
",",
"'hex'",
")",
",",
"bitcoin",
".",
"opcodes",
".",
"OP_ELSE",
",",
"bitcoin",
".",
"script",
".",
"number",
".",
"encode",
"(",
"lockTime",
")",
",",
"bitcoin",
".",
"opcodes",
".",
"OP_CHECKLOCKTIMEVERIFY",
",",
"bitcoin",
".",
"opcodes",
".",
"OP_DROP",
",",
"bitcoin",
".",
"opcodes",
".",
"OP_DUP",
",",
"bitcoin",
".",
"opcodes",
".",
"OP_HASH160",
",",
"Buffer",
".",
"from",
"(",
"hex",
".",
"stripPrefix",
"(",
"revokerH160Addr",
")",
",",
"'hex'",
")",
",",
"bitcoin",
".",
"opcodes",
".",
"OP_ENDIF",
",",
"bitcoin",
".",
"opcodes",
".",
"OP_EQUALVERIFY",
",",
"bitcoin",
".",
"opcodes",
".",
"OP_CHECKSIG",
",",
"]",
")",
";",
"const",
"addressPay",
"=",
"bitcoin",
".",
"payments",
".",
"p2sh",
"(",
"{",
"redeem",
":",
"{",
"output",
":",
"redeemScript",
",",
"network",
":",
"bitcoinNetwork",
"}",
",",
"network",
":",
"bitcoinNetwork",
",",
"}",
")",
";",
"const",
"{",
"address",
"}",
"=",
"addressPay",
";",
"return",
"{",
"address",
",",
"redeemScript",
":",
"redeemScript",
".",
"toString",
"(",
"'hex'",
")",
",",
"xHash",
",",
"lockTime",
",",
"redeemer",
":",
"hex",
".",
"ensurePrefix",
"(",
"destH160Addr",
")",
",",
"revoker",
":",
"hex",
".",
"ensurePrefix",
"(",
"revokerH160Addr",
")",
",",
"}",
";",
"}"
]
| Generate P2SH timelock contract
@param {string} network - Network name (mainnet, testnet)
@param {string} xHash - The xHash string
@param {string} destH160Addr - Hash160 of the receiver's bitcoin address
@param {string} revokerH160Addr - Hash160 of the revoker's bitcoin address
@param {number} lockTime - The timestamp when the revoker is allowed to spend
@returns {Object} Generated P2SH address and redeemScript | [
"Generate",
"P2SH",
"timelock",
"contract"
]
| 1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875 | https://github.com/wanchain/wanx/blob/1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875/src/btc/utils.js#L42-L85 | train |
wanchain/wanx | src/btc/utils.js | hashForRedeemSig | function hashForRedeemSig(network, txid, address, value, redeemScript) {
const tx = btcUtil.buildIncompleteRedeem(network, txid, address, value);
const sigHash = tx.hashForSignature(
0,
new Buffer.from(redeemScript, 'hex'),
bitcoin.Transaction.SIGHASH_ALL
);
return sigHash.toString('hex');
} | javascript | function hashForRedeemSig(network, txid, address, value, redeemScript) {
const tx = btcUtil.buildIncompleteRedeem(network, txid, address, value);
const sigHash = tx.hashForSignature(
0,
new Buffer.from(redeemScript, 'hex'),
bitcoin.Transaction.SIGHASH_ALL
);
return sigHash.toString('hex');
} | [
"function",
"hashForRedeemSig",
"(",
"network",
",",
"txid",
",",
"address",
",",
"value",
",",
"redeemScript",
")",
"{",
"const",
"tx",
"=",
"btcUtil",
".",
"buildIncompleteRedeem",
"(",
"network",
",",
"txid",
",",
"address",
",",
"value",
")",
";",
"const",
"sigHash",
"=",
"tx",
".",
"hashForSignature",
"(",
"0",
",",
"new",
"Buffer",
".",
"from",
"(",
"redeemScript",
",",
"'hex'",
")",
",",
"bitcoin",
".",
"Transaction",
".",
"SIGHASH_ALL",
")",
";",
"return",
"sigHash",
".",
"toString",
"(",
"'hex'",
")",
";",
"}"
]
| Get the hash to be signed for a redeem transaction
@param {string} network - Network name (mainnet, testnet)
@param {string} txid - The txid for the UTXO being spent
@param {string} address - The address to receive funds
@param {string|number} value - The amount of funds to be sent (in Satoshis)
@param {string} redeemScript - The redeemScript of the P2SH address
@returns {string} Hash to be signed | [
"Get",
"the",
"hash",
"to",
"be",
"signed",
"for",
"a",
"redeem",
"transaction"
]
| 1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875 | https://github.com/wanchain/wanx/blob/1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875/src/btc/utils.js#L96-L105 | train |
wanchain/wanx | src/btc/utils.js | hashForRevokeSig | function hashForRevokeSig(network, txid, address, value, lockTime, redeemScript) {
const tx = btcUtil.buildIncompleteRevoke(network, txid, address, value, lockTime);
const sigHash = tx.hashForSignature(
0,
new Buffer.from(redeemScript, 'hex'),
bitcoin.Transaction.SIGHASH_ALL
);
return sigHash.toString('hex');
} | javascript | function hashForRevokeSig(network, txid, address, value, lockTime, redeemScript) {
const tx = btcUtil.buildIncompleteRevoke(network, txid, address, value, lockTime);
const sigHash = tx.hashForSignature(
0,
new Buffer.from(redeemScript, 'hex'),
bitcoin.Transaction.SIGHASH_ALL
);
return sigHash.toString('hex');
} | [
"function",
"hashForRevokeSig",
"(",
"network",
",",
"txid",
",",
"address",
",",
"value",
",",
"lockTime",
",",
"redeemScript",
")",
"{",
"const",
"tx",
"=",
"btcUtil",
".",
"buildIncompleteRevoke",
"(",
"network",
",",
"txid",
",",
"address",
",",
"value",
",",
"lockTime",
")",
";",
"const",
"sigHash",
"=",
"tx",
".",
"hashForSignature",
"(",
"0",
",",
"new",
"Buffer",
".",
"from",
"(",
"redeemScript",
",",
"'hex'",
")",
",",
"bitcoin",
".",
"Transaction",
".",
"SIGHASH_ALL",
")",
";",
"return",
"sigHash",
".",
"toString",
"(",
"'hex'",
")",
";",
"}"
]
| Get the hash to be signed for a revoke transaction
@param {string} network - Network name (mainnet, testnet)
@param {string} txid - The txid for the UTXO being spent
@param {string} address - The address to receive funds
@param {string|number} value - The amount of funds to be sent (in Satoshis)
@param {number} lockTime - The lockTime of the P2SH address
@param {string} redeemScript - The redeemScript of the P2SH address
@returns {string} Hash to be signed | [
"Get",
"the",
"hash",
"to",
"be",
"signed",
"for",
"a",
"revoke",
"transaction"
]
| 1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875 | https://github.com/wanchain/wanx/blob/1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875/src/btc/utils.js#L117-L126 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.