id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
45,300 | imjching/node-hackerearth | lib/hackerearth/HackerEarthAPI.js | HackerEarthAPI | function HackerEarthAPI (clientSecretKey, options) {
if (typeof clientSecretKey != 'string') {
clientSecretKey = null;
options = clientSecretKey;
}
if (!options) {
options = {};
}
if (!clientSecretKey) {
throw new Error('You have to provide a client secret key for this to work. If you do not have one, please register your client at https://www.hackerearth.com/api/register.');
}
if (!options.version || options.version == '3') {
this.version = 'v3';
} else if (options.version == '2') {
this.version = 'v2';
} else {
throw new Error('Version ' + options.version + ' of the HackerEarth API is currently not supported.');
}
this.clientSecretKey = clientSecretKey;
this.httpHost = 'api.hackerearth.com:443'
this.httpUri = 'https://' + this.httpHost;
this.possibleLangs = ['C', 'CPP', 'CPP11', 'CLOJURE', 'CSHARP', 'JAVA', 'JAVASCRIPT', 'HASKELL', 'PERL', 'PHP', 'PYTHON', 'RUBY'];
} | javascript | function HackerEarthAPI (clientSecretKey, options) {
if (typeof clientSecretKey != 'string') {
clientSecretKey = null;
options = clientSecretKey;
}
if (!options) {
options = {};
}
if (!clientSecretKey) {
throw new Error('You have to provide a client secret key for this to work. If you do not have one, please register your client at https://www.hackerearth.com/api/register.');
}
if (!options.version || options.version == '3') {
this.version = 'v3';
} else if (options.version == '2') {
this.version = 'v2';
} else {
throw new Error('Version ' + options.version + ' of the HackerEarth API is currently not supported.');
}
this.clientSecretKey = clientSecretKey;
this.httpHost = 'api.hackerearth.com:443'
this.httpUri = 'https://' + this.httpHost;
this.possibleLangs = ['C', 'CPP', 'CPP11', 'CLOJURE', 'CSHARP', 'JAVA', 'JAVASCRIPT', 'HASKELL', 'PERL', 'PHP', 'PYTHON', 'RUBY'];
} | [
"function",
"HackerEarthAPI",
"(",
"clientSecretKey",
",",
"options",
")",
"{",
"if",
"(",
"typeof",
"clientSecretKey",
"!=",
"'string'",
")",
"{",
"clientSecretKey",
"=",
"null",
";",
"options",
"=",
"clientSecretKey",
";",
"}",
"if",
"(",
"!",
"options",
")",
"{",
"options",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"!",
"clientSecretKey",
")",
"{",
"throw",
"new",
"Error",
"(",
"'You have to provide a client secret key for this to work. If you do not have one, please register your client at https://www.hackerearth.com/api/register.'",
")",
";",
"}",
"if",
"(",
"!",
"options",
".",
"version",
"||",
"options",
".",
"version",
"==",
"'3'",
")",
"{",
"this",
".",
"version",
"=",
"'v3'",
";",
"}",
"else",
"if",
"(",
"options",
".",
"version",
"==",
"'2'",
")",
"{",
"this",
".",
"version",
"=",
"'v2'",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Version '",
"+",
"options",
".",
"version",
"+",
"' of the HackerEarth API is currently not supported.'",
")",
";",
"}",
"this",
".",
"clientSecretKey",
"=",
"clientSecretKey",
";",
"this",
".",
"httpHost",
"=",
"'api.hackerearth.com:443'",
"this",
".",
"httpUri",
"=",
"'https://'",
"+",
"this",
".",
"httpHost",
";",
"this",
".",
"possibleLangs",
"=",
"[",
"'C'",
",",
"'CPP'",
",",
"'CPP11'",
",",
"'CLOJURE'",
",",
"'CSHARP'",
",",
"'JAVA'",
",",
"'JAVASCRIPT'",
",",
"'HASKELL'",
",",
"'PERL'",
",",
"'PHP'",
",",
"'PYTHON'",
",",
"'RUBY'",
"]",
";",
"}"
]
| Returns a HackerEarth API wrapper object of the specified version. Currently,
only version 3 is supported by this wrapper as HackerEarth has already discontinued
version 2.
Available options are:
- version The API version to use (2, 3). Defaults to 3.
@param clientSecretKey The client secret key to access the HackerEarth API
@param options Configuration options as described above
@return Instance of the HackerEarth API in the specified version | [
"Returns",
"a",
"HackerEarth",
"API",
"wrapper",
"object",
"of",
"the",
"specified",
"version",
".",
"Currently",
"only",
"version",
"3",
"is",
"supported",
"by",
"this",
"wrapper",
"as",
"HackerEarth",
"has",
"already",
"discontinued",
"version",
"2",
"."
]
| 62354fd8af0fa82b4dcecce96bf4c09ba24826e4 | https://github.com/imjching/node-hackerearth/blob/62354fd8af0fa82b4dcecce96bf4c09ba24826e4/lib/hackerearth/HackerEarthAPI.js#L16-L41 |
45,301 | styonsk/elmongoose | lib/elmongoose.js | unindex | function unindex (options) {
var self = this
var unindexUri = helpers.makeDocumentUri(options, self)
// console.log('unindex:', unindexUri)
var reqOpts = {
method: 'DELETE',
url: unindexUri
}
if(options.auth) {
reqOpts.auth = {
user: options.auth.user,
pass: options.auth.password,
sendImmediately: false
};
}
helpers.backOffRequest(reqOpts, function (err, res, body) {
if (err) {
var error = new Error('Elasticsearch document index deletion error: '+util.inspect(err, true, 10, true))
error.details = err
console.log('error', error);
//self.emit('error', error)
return
}
self.emit('elmongoose-unindexed', body)
})
} | javascript | function unindex (options) {
var self = this
var unindexUri = helpers.makeDocumentUri(options, self)
// console.log('unindex:', unindexUri)
var reqOpts = {
method: 'DELETE',
url: unindexUri
}
if(options.auth) {
reqOpts.auth = {
user: options.auth.user,
pass: options.auth.password,
sendImmediately: false
};
}
helpers.backOffRequest(reqOpts, function (err, res, body) {
if (err) {
var error = new Error('Elasticsearch document index deletion error: '+util.inspect(err, true, 10, true))
error.details = err
console.log('error', error);
//self.emit('error', error)
return
}
self.emit('elmongoose-unindexed', body)
})
} | [
"function",
"unindex",
"(",
"options",
")",
"{",
"var",
"self",
"=",
"this",
"var",
"unindexUri",
"=",
"helpers",
".",
"makeDocumentUri",
"(",
"options",
",",
"self",
")",
"// console.log('unindex:', unindexUri)",
"var",
"reqOpts",
"=",
"{",
"method",
":",
"'DELETE'",
",",
"url",
":",
"unindexUri",
"}",
"if",
"(",
"options",
".",
"auth",
")",
"{",
"reqOpts",
".",
"auth",
"=",
"{",
"user",
":",
"options",
".",
"auth",
".",
"user",
",",
"pass",
":",
"options",
".",
"auth",
".",
"password",
",",
"sendImmediately",
":",
"false",
"}",
";",
"}",
"helpers",
".",
"backOffRequest",
"(",
"reqOpts",
",",
"function",
"(",
"err",
",",
"res",
",",
"body",
")",
"{",
"if",
"(",
"err",
")",
"{",
"var",
"error",
"=",
"new",
"Error",
"(",
"'Elasticsearch document index deletion error: '",
"+",
"util",
".",
"inspect",
"(",
"err",
",",
"true",
",",
"10",
",",
"true",
")",
")",
"error",
".",
"details",
"=",
"err",
"console",
".",
"log",
"(",
"'error'",
",",
"error",
")",
";",
"//self.emit('error', error)",
"return",
"}",
"self",
".",
"emit",
"(",
"'elmongoose-unindexed'",
",",
"body",
")",
"}",
")",
"}"
]
| Remove a document from elasticsearch
@param {Object} options elasticsearch options object. Keys: host, port, index, type | [
"Remove",
"a",
"document",
"from",
"elasticsearch"
]
| b83f7dd67330c7288e7f17866d3e67f12a2adc1d | https://github.com/styonsk/elmongoose/blob/b83f7dd67330c7288e7f17866d3e67f12a2adc1d/lib/elmongoose.js#L165-L197 |
45,302 | jonschlinkert/engine-cache | index.js | normalizeEngine | function normalizeEngine(fn, options) {
if (utils.isEngine(options)) {
return normalizeEngine(options, fn); //<= reverse args
}
if (!isObject(fn) && typeof fn !== 'function') {
throw new TypeError('expected an object or function');
}
var engine = {};
engine.render = fn.render || fn;
engine.options = extend({}, options);
if (typeof engine.render !== 'function') {
throw new Error('expected engine to have a render method');
}
var keys = Object.keys(fn);
var len = keys.length;
var idx = -1;
while (++idx < len) {
var key = keys[idx];
if (key === 'options') {
engine.options = extend({}, engine.options, fn[key]);
continue;
}
if (key === '__express' && !fn.hasOwnProperty('renderFile')) {
engine.renderFile = fn[key];
}
engine[key] = fn[key];
}
return engine;
} | javascript | function normalizeEngine(fn, options) {
if (utils.isEngine(options)) {
return normalizeEngine(options, fn); //<= reverse args
}
if (!isObject(fn) && typeof fn !== 'function') {
throw new TypeError('expected an object or function');
}
var engine = {};
engine.render = fn.render || fn;
engine.options = extend({}, options);
if (typeof engine.render !== 'function') {
throw new Error('expected engine to have a render method');
}
var keys = Object.keys(fn);
var len = keys.length;
var idx = -1;
while (++idx < len) {
var key = keys[idx];
if (key === 'options') {
engine.options = extend({}, engine.options, fn[key]);
continue;
}
if (key === '__express' && !fn.hasOwnProperty('renderFile')) {
engine.renderFile = fn[key];
}
engine[key] = fn[key];
}
return engine;
} | [
"function",
"normalizeEngine",
"(",
"fn",
",",
"options",
")",
"{",
"if",
"(",
"utils",
".",
"isEngine",
"(",
"options",
")",
")",
"{",
"return",
"normalizeEngine",
"(",
"options",
",",
"fn",
")",
";",
"//<= reverse args",
"}",
"if",
"(",
"!",
"isObject",
"(",
"fn",
")",
"&&",
"typeof",
"fn",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'expected an object or function'",
")",
";",
"}",
"var",
"engine",
"=",
"{",
"}",
";",
"engine",
".",
"render",
"=",
"fn",
".",
"render",
"||",
"fn",
";",
"engine",
".",
"options",
"=",
"extend",
"(",
"{",
"}",
",",
"options",
")",
";",
"if",
"(",
"typeof",
"engine",
".",
"render",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'expected engine to have a render method'",
")",
";",
"}",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"fn",
")",
";",
"var",
"len",
"=",
"keys",
".",
"length",
";",
"var",
"idx",
"=",
"-",
"1",
";",
"while",
"(",
"++",
"idx",
"<",
"len",
")",
"{",
"var",
"key",
"=",
"keys",
"[",
"idx",
"]",
";",
"if",
"(",
"key",
"===",
"'options'",
")",
"{",
"engine",
".",
"options",
"=",
"extend",
"(",
"{",
"}",
",",
"engine",
".",
"options",
",",
"fn",
"[",
"key",
"]",
")",
";",
"continue",
";",
"}",
"if",
"(",
"key",
"===",
"'__express'",
"&&",
"!",
"fn",
".",
"hasOwnProperty",
"(",
"'renderFile'",
")",
")",
"{",
"engine",
".",
"renderFile",
"=",
"fn",
"[",
"key",
"]",
";",
"}",
"engine",
"[",
"key",
"]",
"=",
"fn",
"[",
"key",
"]",
";",
"}",
"return",
"engine",
";",
"}"
]
| Normalize engine so that `.render` is a property on the `engine` object. | [
"Normalize",
"engine",
"so",
"that",
".",
"render",
"is",
"a",
"property",
"on",
"the",
"engine",
"object",
"."
]
| 9df4c7e7abcbbed76fda79f354f040f2c68cb670 | https://github.com/jonschlinkert/engine-cache/blob/9df4c7e7abcbbed76fda79f354f040f2c68cb670/index.js#L151-L183 |
45,303 | jonschlinkert/engine-cache | index.js | inspect | function inspect(engine) {
var inspect = ['"' + engine.name + '"'];
var exts = utils.arrayify(engine.options.ext).join(', ');
inspect.push('<ext "' + exts + '">');
engine.inspect = function() {
return '<Engine ' + inspect.join(' ') + '>';
};
} | javascript | function inspect(engine) {
var inspect = ['"' + engine.name + '"'];
var exts = utils.arrayify(engine.options.ext).join(', ');
inspect.push('<ext "' + exts + '">');
engine.inspect = function() {
return '<Engine ' + inspect.join(' ') + '>';
};
} | [
"function",
"inspect",
"(",
"engine",
")",
"{",
"var",
"inspect",
"=",
"[",
"'\"'",
"+",
"engine",
".",
"name",
"+",
"'\"'",
"]",
";",
"var",
"exts",
"=",
"utils",
".",
"arrayify",
"(",
"engine",
".",
"options",
".",
"ext",
")",
".",
"join",
"(",
"', '",
")",
";",
"inspect",
".",
"push",
"(",
"'<ext \"'",
"+",
"exts",
"+",
"'\">'",
")",
";",
"engine",
".",
"inspect",
"=",
"function",
"(",
")",
"{",
"return",
"'<Engine '",
"+",
"inspect",
".",
"join",
"(",
"' '",
")",
"+",
"'>'",
";",
"}",
";",
"}"
]
| Add a custom inspect function onto the engine. | [
"Add",
"a",
"custom",
"inspect",
"function",
"onto",
"the",
"engine",
"."
]
| 9df4c7e7abcbbed76fda79f354f040f2c68cb670 | https://github.com/jonschlinkert/engine-cache/blob/9df4c7e7abcbbed76fda79f354f040f2c68cb670/index.js#L360-L367 |
45,304 | jonschlinkert/engine-cache | index.js | mergeHelpers | function mergeHelpers(engine, options) {
if (!options || typeof options !== 'object') {
throw new TypeError('expected an object');
}
var opts = extend({}, options);
var helpers = merge({}, engine.helpers.cache, opts.helpers);
var keys = Object.keys(helpers);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
engine.asyncHelpers.set(key, helpers[key]);
}
opts.helpers = engine.asyncHelpers.get({wrap: opts.async});
return opts;
} | javascript | function mergeHelpers(engine, options) {
if (!options || typeof options !== 'object') {
throw new TypeError('expected an object');
}
var opts = extend({}, options);
var helpers = merge({}, engine.helpers.cache, opts.helpers);
var keys = Object.keys(helpers);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
engine.asyncHelpers.set(key, helpers[key]);
}
opts.helpers = engine.asyncHelpers.get({wrap: opts.async});
return opts;
} | [
"function",
"mergeHelpers",
"(",
"engine",
",",
"options",
")",
"{",
"if",
"(",
"!",
"options",
"||",
"typeof",
"options",
"!==",
"'object'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'expected an object'",
")",
";",
"}",
"var",
"opts",
"=",
"extend",
"(",
"{",
"}",
",",
"options",
")",
";",
"var",
"helpers",
"=",
"merge",
"(",
"{",
"}",
",",
"engine",
".",
"helpers",
".",
"cache",
",",
"opts",
".",
"helpers",
")",
";",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"helpers",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"key",
"=",
"keys",
"[",
"i",
"]",
";",
"engine",
".",
"asyncHelpers",
".",
"set",
"(",
"key",
",",
"helpers",
"[",
"key",
"]",
")",
";",
"}",
"opts",
".",
"helpers",
"=",
"engine",
".",
"asyncHelpers",
".",
"get",
"(",
"{",
"wrap",
":",
"opts",
".",
"async",
"}",
")",
";",
"return",
"opts",
";",
"}"
]
| Merge the local engine helpers with the options helpers.
@param {Object} `options` Options passed into `render` or `compile`
@return {Object} Options object with merged helpers | [
"Merge",
"the",
"local",
"engine",
"helpers",
"with",
"the",
"options",
"helpers",
"."
]
| 9df4c7e7abcbbed76fda79f354f040f2c68cb670 | https://github.com/jonschlinkert/engine-cache/blob/9df4c7e7abcbbed76fda79f354f040f2c68cb670/index.js#L376-L391 |
45,305 | vadr-vr/VR-Analytics-JSCore | js/dataManager/dataManager.js | init | function init(){
eventDataPairs = 0;
currentSession = sessionManager.createSession();
lastRequestTime = utils.getUnixTimeInSeconds();
mediaPlaying = false;
// checks if time since last request has exceeded the maximum request time
if (timeSinceRequestChecker){
clearInterval(timeSinceRequestChecker);
timeSinceRequestChecker = null;
}
timeSinceRequestChecker = setInterval(
() => {
const currentTime = utils.getUnixTimeInSeconds();
if (currentTime - lastRequestTime > config.getDataPostTimeInterval()){
_createDataRequest();
}
},
1000);
} | javascript | function init(){
eventDataPairs = 0;
currentSession = sessionManager.createSession();
lastRequestTime = utils.getUnixTimeInSeconds();
mediaPlaying = false;
// checks if time since last request has exceeded the maximum request time
if (timeSinceRequestChecker){
clearInterval(timeSinceRequestChecker);
timeSinceRequestChecker = null;
}
timeSinceRequestChecker = setInterval(
() => {
const currentTime = utils.getUnixTimeInSeconds();
if (currentTime - lastRequestTime > config.getDataPostTimeInterval()){
_createDataRequest();
}
},
1000);
} | [
"function",
"init",
"(",
")",
"{",
"eventDataPairs",
"=",
"0",
";",
"currentSession",
"=",
"sessionManager",
".",
"createSession",
"(",
")",
";",
"lastRequestTime",
"=",
"utils",
".",
"getUnixTimeInSeconds",
"(",
")",
";",
"mediaPlaying",
"=",
"false",
";",
"// checks if time since last request has exceeded the maximum request time",
"if",
"(",
"timeSinceRequestChecker",
")",
"{",
"clearInterval",
"(",
"timeSinceRequestChecker",
")",
";",
"timeSinceRequestChecker",
"=",
"null",
";",
"}",
"timeSinceRequestChecker",
"=",
"setInterval",
"(",
"(",
")",
"=>",
"{",
"const",
"currentTime",
"=",
"utils",
".",
"getUnixTimeInSeconds",
"(",
")",
";",
"if",
"(",
"currentTime",
"-",
"lastRequestTime",
">",
"config",
".",
"getDataPostTimeInterval",
"(",
")",
")",
"{",
"_createDataRequest",
"(",
")",
";",
"}",
"}",
",",
"1000",
")",
";",
"}"
]
| Init the collection of data
@memberof DataManager | [
"Init",
"the",
"collection",
"of",
"data"
]
| 7e4a493c824c2c1716360dcb6a3bfecfede5df3b | https://github.com/vadr-vr/VR-Analytics-JSCore/blob/7e4a493c824c2c1716360dcb6a3bfecfede5df3b/js/dataManager/dataManager.js#L29-L55 |
45,306 | vadr-vr/VR-Analytics-JSCore | js/dataManager/dataManager.js | addScene | function addScene(sceneId, sceneName){
if (!sceneId && !sceneName){
logger.warn('SceneId or SceneName is required to starting a new scene session. Aborting');
return;
}
// close any previous media
if (mediaPlaying)
closeMedia();
currentSession.addScene(sceneId, sceneName);
} | javascript | function addScene(sceneId, sceneName){
if (!sceneId && !sceneName){
logger.warn('SceneId or SceneName is required to starting a new scene session. Aborting');
return;
}
// close any previous media
if (mediaPlaying)
closeMedia();
currentSession.addScene(sceneId, sceneName);
} | [
"function",
"addScene",
"(",
"sceneId",
",",
"sceneName",
")",
"{",
"if",
"(",
"!",
"sceneId",
"&&",
"!",
"sceneName",
")",
"{",
"logger",
".",
"warn",
"(",
"'SceneId or SceneName is required to starting a new scene session. Aborting'",
")",
";",
"return",
";",
"}",
"// close any previous media",
"if",
"(",
"mediaPlaying",
")",
"closeMedia",
"(",
")",
";",
"currentSession",
".",
"addScene",
"(",
"sceneId",
",",
"sceneName",
")",
";",
"}"
]
| Functions related to creating and deleting scene sessions and media sessions
create scene session
@memberof DataManager
@param {string} sceneId id of the new scene [optional - either this or sceneName]
@param {string} sceneName name of the new scene [optional - either this or sceneId] | [
"Functions",
"related",
"to",
"creating",
"and",
"deleting",
"scene",
"sessions",
"and",
"media",
"sessions",
"create",
"scene",
"session"
]
| 7e4a493c824c2c1716360dcb6a3bfecfede5df3b | https://github.com/vadr-vr/VR-Analytics-JSCore/blob/7e4a493c824c2c1716360dcb6a3bfecfede5df3b/js/dataManager/dataManager.js#L75-L90 |
45,307 | vadr-vr/VR-Analytics-JSCore | js/dataManager/dataManager.js | addMedia | function addMedia(mediaId, name, type, url){
// close any previous media
if (mediaPlaying)
closeMedia();
if (type != enums.media360.video && type != enums.media360.image){
logger.warn('Media type not supported. Aborting addind media.');
return;
}
if (type == enums.media360.video){
timeManager.playVideo();
}
mediaPlaying = true;
currentSession.addMedia(mediaId, name, type, url);
} | javascript | function addMedia(mediaId, name, type, url){
// close any previous media
if (mediaPlaying)
closeMedia();
if (type != enums.media360.video && type != enums.media360.image){
logger.warn('Media type not supported. Aborting addind media.');
return;
}
if (type == enums.media360.video){
timeManager.playVideo();
}
mediaPlaying = true;
currentSession.addMedia(mediaId, name, type, url);
} | [
"function",
"addMedia",
"(",
"mediaId",
",",
"name",
",",
"type",
",",
"url",
")",
"{",
"// close any previous media",
"if",
"(",
"mediaPlaying",
")",
"closeMedia",
"(",
")",
";",
"if",
"(",
"type",
"!=",
"enums",
".",
"media360",
".",
"video",
"&&",
"type",
"!=",
"enums",
".",
"media360",
".",
"image",
")",
"{",
"logger",
".",
"warn",
"(",
"'Media type not supported. Aborting addind media.'",
")",
";",
"return",
";",
"}",
"if",
"(",
"type",
"==",
"enums",
".",
"media360",
".",
"video",
")",
"{",
"timeManager",
".",
"playVideo",
"(",
")",
";",
"}",
"mediaPlaying",
"=",
"true",
";",
"currentSession",
".",
"addMedia",
"(",
"mediaId",
",",
"name",
",",
"type",
",",
"url",
")",
";",
"}"
]
| Adds media to the media list
@memberof DataManager
@param {string} mediaId Developer defined mediaId for the media
@param {string} name Media name to be displayed to the analytics user
@param {number} type Type of media 1 - Video, 2 - Photo
@param {string} url Url for the media [optional] | [
"Adds",
"media",
"to",
"the",
"media",
"list"
]
| 7e4a493c824c2c1716360dcb6a3bfecfede5df3b | https://github.com/vadr-vr/VR-Analytics-JSCore/blob/7e4a493c824c2c1716360dcb6a3bfecfede5df3b/js/dataManager/dataManager.js#L115-L137 |
45,308 | vadr-vr/VR-Analytics-JSCore | js/dataManager/dataManager.js | registerEvent | function registerEvent(eventName, position, extra){
currentSession.registerEvent(eventName, position, extra);
// check size of events and handle making request
_checkDataPairs();
} | javascript | function registerEvent(eventName, position, extra){
currentSession.registerEvent(eventName, position, extra);
// check size of events and handle making request
_checkDataPairs();
} | [
"function",
"registerEvent",
"(",
"eventName",
",",
"position",
",",
"extra",
")",
"{",
"currentSession",
".",
"registerEvent",
"(",
"eventName",
",",
"position",
",",
"extra",
")",
";",
"// check size of events and handle making request",
"_checkDataPairs",
"(",
")",
";",
"}"
]
| Adds event to event list of media if it exists, else to its own events list
@memberof DataManager
@param {string} eventName name of the event
@param {string} position 3D position associated with the event
@param {object} extra extra information and filter key-value pairs in the event | [
"Adds",
"event",
"to",
"event",
"list",
"of",
"media",
"if",
"it",
"exists",
"else",
"to",
"its",
"own",
"events",
"list"
]
| 7e4a493c824c2c1716360dcb6a3bfecfede5df3b | https://github.com/vadr-vr/VR-Analytics-JSCore/blob/7e4a493c824c2c1716360dcb6a3bfecfede5df3b/js/dataManager/dataManager.js#L212-L219 |
45,309 | vadr-vr/VR-Analytics-JSCore | js/dataManager/dataManager.js | _createDataRequest | function _createDataRequest(){
logger.info('Creating data request');
eventDataPairs = 0;
const currentSessionData = currentSession.getDictionary();
serverRequestManager.addDataRequest(currentSessionData);
currentSession = currentSession.getDuplicate();
lastRequestTime = utils.getUnixTimeInSeconds();
sessionManager.setSessionCookie();
} | javascript | function _createDataRequest(){
logger.info('Creating data request');
eventDataPairs = 0;
const currentSessionData = currentSession.getDictionary();
serverRequestManager.addDataRequest(currentSessionData);
currentSession = currentSession.getDuplicate();
lastRequestTime = utils.getUnixTimeInSeconds();
sessionManager.setSessionCookie();
} | [
"function",
"_createDataRequest",
"(",
")",
"{",
"logger",
".",
"info",
"(",
"'Creating data request'",
")",
";",
"eventDataPairs",
"=",
"0",
";",
"const",
"currentSessionData",
"=",
"currentSession",
".",
"getDictionary",
"(",
")",
";",
"serverRequestManager",
".",
"addDataRequest",
"(",
"currentSessionData",
")",
";",
"currentSession",
"=",
"currentSession",
".",
"getDuplicate",
"(",
")",
";",
"lastRequestTime",
"=",
"utils",
".",
"getUnixTimeInSeconds",
"(",
")",
";",
"sessionManager",
".",
"setSessionCookie",
"(",
")",
";",
"}"
]
| list all the private functions
Pushes the stored data till now to request manager, clears the session data
@memberof DataManager
@private | [
"list",
"all",
"the",
"private",
"functions",
"Pushes",
"the",
"stored",
"data",
"till",
"now",
"to",
"request",
"manager",
"clears",
"the",
"session",
"data"
]
| 7e4a493c824c2c1716360dcb6a3bfecfede5df3b | https://github.com/vadr-vr/VR-Analytics-JSCore/blob/7e4a493c824c2c1716360dcb6a3bfecfede5df3b/js/dataManager/dataManager.js#L246-L257 |
45,310 | atd-schubert/node-tor-relay | relay.js | function () {
return crypto.createHash('sha1')
.update(Date.now().toString() + Math.random().toString())
.digest('hex');
} | javascript | function () {
return crypto.createHash('sha1')
.update(Date.now().toString() + Math.random().toString())
.digest('hex');
} | [
"function",
"(",
")",
"{",
"return",
"crypto",
".",
"createHash",
"(",
"'sha1'",
")",
".",
"update",
"(",
"Date",
".",
"now",
"(",
")",
".",
"toString",
"(",
")",
"+",
"Math",
".",
"random",
"(",
")",
".",
"toString",
"(",
")",
")",
".",
"digest",
"(",
"'hex'",
")",
";",
"}"
]
| Create random credentials
@private
@returns {*} | [
"Create",
"random",
"credentials"
]
| 816a9ca623dffe5b51f9b41b070a0404deb2897f | https://github.com/atd-schubert/node-tor-relay/blob/816a9ca623dffe5b51f9b41b070a0404deb2897f/relay.js#L18-L22 |
|
45,311 | atd-schubert/node-tor-relay | relay.js | TorRelay | function TorRelay(opts) {
var self = this;
opts = opts || {};
if (!opts.hasOwnProperty('autoCredentials')) {
opts.autoCredentials = true;
}
this.dataDirectory = opts.dataDirectory || null;
if (!opts.hasOwnProperty('cleanUpOnExit')) {
this.cleanUpOnExit = true;
} else {
this.cleanUpOnExit = opts.cleanUpOnExit;
}
if (opts.hasOwnProperty('retries')) {
this.retries = opts.retries;
}
if (opts.hasOwnProperty('timeout')) {
this.timeout = opts.timeout;
}
/**
* Configuration of the services
* @type {{control: {password: (string|*), port: (string|*|null)}, socks: {port: (string|*|null)}}}
*/
this.service = {
control: {
password: opts.controlPassword || (opts.autoCredentials ? createCredential() : null),
port: opts.controlPort || null
},
socks: {
username: opts.socksUsername || null,
password: opts.socksPassword || null,
port: opts.socksPort || null
}
};
if (!opts.hasOwnProperty('socksUsername') && opts.autoCredentials) {
this.service.socks.username = createCredential();
}
if (!opts.hasOwnProperty('socksPassword') && opts.autoCredentials) {
this.service.socks.password = createCredential();
}
process.on('exit', function () {
if (self.process && self.cleanUpOnExit) {
console.error('Killing tor sub-process');
self.process.kill('SIGTERM');
self.process.kill('SIGKILL');
}
});
} | javascript | function TorRelay(opts) {
var self = this;
opts = opts || {};
if (!opts.hasOwnProperty('autoCredentials')) {
opts.autoCredentials = true;
}
this.dataDirectory = opts.dataDirectory || null;
if (!opts.hasOwnProperty('cleanUpOnExit')) {
this.cleanUpOnExit = true;
} else {
this.cleanUpOnExit = opts.cleanUpOnExit;
}
if (opts.hasOwnProperty('retries')) {
this.retries = opts.retries;
}
if (opts.hasOwnProperty('timeout')) {
this.timeout = opts.timeout;
}
/**
* Configuration of the services
* @type {{control: {password: (string|*), port: (string|*|null)}, socks: {port: (string|*|null)}}}
*/
this.service = {
control: {
password: opts.controlPassword || (opts.autoCredentials ? createCredential() : null),
port: opts.controlPort || null
},
socks: {
username: opts.socksUsername || null,
password: opts.socksPassword || null,
port: opts.socksPort || null
}
};
if (!opts.hasOwnProperty('socksUsername') && opts.autoCredentials) {
this.service.socks.username = createCredential();
}
if (!opts.hasOwnProperty('socksPassword') && opts.autoCredentials) {
this.service.socks.password = createCredential();
}
process.on('exit', function () {
if (self.process && self.cleanUpOnExit) {
console.error('Killing tor sub-process');
self.process.kill('SIGTERM');
self.process.kill('SIGKILL');
}
});
} | [
"function",
"TorRelay",
"(",
"opts",
")",
"{",
"var",
"self",
"=",
"this",
";",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"if",
"(",
"!",
"opts",
".",
"hasOwnProperty",
"(",
"'autoCredentials'",
")",
")",
"{",
"opts",
".",
"autoCredentials",
"=",
"true",
";",
"}",
"this",
".",
"dataDirectory",
"=",
"opts",
".",
"dataDirectory",
"||",
"null",
";",
"if",
"(",
"!",
"opts",
".",
"hasOwnProperty",
"(",
"'cleanUpOnExit'",
")",
")",
"{",
"this",
".",
"cleanUpOnExit",
"=",
"true",
";",
"}",
"else",
"{",
"this",
".",
"cleanUpOnExit",
"=",
"opts",
".",
"cleanUpOnExit",
";",
"}",
"if",
"(",
"opts",
".",
"hasOwnProperty",
"(",
"'retries'",
")",
")",
"{",
"this",
".",
"retries",
"=",
"opts",
".",
"retries",
";",
"}",
"if",
"(",
"opts",
".",
"hasOwnProperty",
"(",
"'timeout'",
")",
")",
"{",
"this",
".",
"timeout",
"=",
"opts",
".",
"timeout",
";",
"}",
"/**\n * Configuration of the services\n * @type {{control: {password: (string|*), port: (string|*|null)}, socks: {port: (string|*|null)}}}\n */",
"this",
".",
"service",
"=",
"{",
"control",
":",
"{",
"password",
":",
"opts",
".",
"controlPassword",
"||",
"(",
"opts",
".",
"autoCredentials",
"?",
"createCredential",
"(",
")",
":",
"null",
")",
",",
"port",
":",
"opts",
".",
"controlPort",
"||",
"null",
"}",
",",
"socks",
":",
"{",
"username",
":",
"opts",
".",
"socksUsername",
"||",
"null",
",",
"password",
":",
"opts",
".",
"socksPassword",
"||",
"null",
",",
"port",
":",
"opts",
".",
"socksPort",
"||",
"null",
"}",
"}",
";",
"if",
"(",
"!",
"opts",
".",
"hasOwnProperty",
"(",
"'socksUsername'",
")",
"&&",
"opts",
".",
"autoCredentials",
")",
"{",
"this",
".",
"service",
".",
"socks",
".",
"username",
"=",
"createCredential",
"(",
")",
";",
"}",
"if",
"(",
"!",
"opts",
".",
"hasOwnProperty",
"(",
"'socksPassword'",
")",
"&&",
"opts",
".",
"autoCredentials",
")",
"{",
"this",
".",
"service",
".",
"socks",
".",
"password",
"=",
"createCredential",
"(",
")",
";",
"}",
"process",
".",
"on",
"(",
"'exit'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"self",
".",
"process",
"&&",
"self",
".",
"cleanUpOnExit",
")",
"{",
"console",
".",
"error",
"(",
"'Killing tor sub-process'",
")",
";",
"self",
".",
"process",
".",
"kill",
"(",
"'SIGTERM'",
")",
";",
"self",
".",
"process",
".",
"kill",
"(",
"'SIGKILL'",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Relay class for tor relays
@param {{}} [opts] - Options for relay
@param {boolean} [opts.autoCredentials] - Automatically create credentials
@param {boolean} [opts.cleanUpOnExit=true] - Remove temporary dir an close unused child-processes on exit
@param {string} [opts.dataDirectory] - Specify a directory to store tor data (default is an auto-created temporary dir, this will be removed if cleanUpOnExit is true)
@param {string} [opts.controlPassword] - Password for tor control (default is a random password)
@param {string} [opts.controlPort] - Port for tor control (default is a random free port)
@param {number} [opts.retries=5] - Number of retries to find a circuit
@param {string} [opts.socksPort] - Port for socks5 (default is a random free port)
@param {string} [opts.socksUsername] - Username for socks5 (default is a random like a password)
@param {string} [opts.socksPassword] - Password for socks5 (default is a random password)
@param {number} [opts.timeout=60000] - Timeout for finding a circuit
@constructor | [
"Relay",
"class",
"for",
"tor",
"relays"
]
| 816a9ca623dffe5b51f9b41b070a0404deb2897f | https://github.com/atd-schubert/node-tor-relay/blob/816a9ca623dffe5b51f9b41b070a0404deb2897f/relay.js#L39-L92 |
45,312 | atd-schubert/node-tor-relay | relay.js | restartRelay | function restartRelay(cb) {
var self = this;
this.stop(function (err) {
if (err) {
return cb(err);
}
self.start(cb);
});
} | javascript | function restartRelay(cb) {
var self = this;
this.stop(function (err) {
if (err) {
return cb(err);
}
self.start(cb);
});
} | [
"function",
"restartRelay",
"(",
"cb",
")",
"{",
"var",
"self",
"=",
"this",
";",
"this",
".",
"stop",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"self",
".",
"start",
"(",
"cb",
")",
";",
"}",
")",
";",
"}"
]
| Stop and start relay
@param {TorRelay~startCallback} cb | [
"Stop",
"and",
"start",
"relay"
]
| 816a9ca623dffe5b51f9b41b070a0404deb2897f | https://github.com/atd-schubert/node-tor-relay/blob/816a9ca623dffe5b51f9b41b070a0404deb2897f/relay.js#L309-L317 |
45,313 | ExclamationLabs/sevr-cli | lib/manage/commands/find.js | function(doc, fields) {
return Object.keys(fields).reduce((prev, key) => {
let val
if (fields[key].hasOwnProperty('referenceCollection')) {
const displayField = fields[key].referenceCollection.defaultField
if (Array.isArray(doc[key])) {
val = doc[key].map(data => {
return data[displayField]
})
} else {
val = doc[key][displayField]
}
} else {
val = doc[key]
}
return Object.assign({}, prev, {
[key]: val
})
}, { _id: doc._id })
} | javascript | function(doc, fields) {
return Object.keys(fields).reduce((prev, key) => {
let val
if (fields[key].hasOwnProperty('referenceCollection')) {
const displayField = fields[key].referenceCollection.defaultField
if (Array.isArray(doc[key])) {
val = doc[key].map(data => {
return data[displayField]
})
} else {
val = doc[key][displayField]
}
} else {
val = doc[key]
}
return Object.assign({}, prev, {
[key]: val
})
}, { _id: doc._id })
} | [
"function",
"(",
"doc",
",",
"fields",
")",
"{",
"return",
"Object",
".",
"keys",
"(",
"fields",
")",
".",
"reduce",
"(",
"(",
"prev",
",",
"key",
")",
"=>",
"{",
"let",
"val",
"if",
"(",
"fields",
"[",
"key",
"]",
".",
"hasOwnProperty",
"(",
"'referenceCollection'",
")",
")",
"{",
"const",
"displayField",
"=",
"fields",
"[",
"key",
"]",
".",
"referenceCollection",
".",
"defaultField",
"if",
"(",
"Array",
".",
"isArray",
"(",
"doc",
"[",
"key",
"]",
")",
")",
"{",
"val",
"=",
"doc",
"[",
"key",
"]",
".",
"map",
"(",
"data",
"=>",
"{",
"return",
"data",
"[",
"displayField",
"]",
"}",
")",
"}",
"else",
"{",
"val",
"=",
"doc",
"[",
"key",
"]",
"[",
"displayField",
"]",
"}",
"}",
"else",
"{",
"val",
"=",
"doc",
"[",
"key",
"]",
"}",
"return",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"prev",
",",
"{",
"[",
"key",
"]",
":",
"val",
"}",
")",
"}",
",",
"{",
"_id",
":",
"doc",
".",
"_id",
"}",
")",
"}"
]
| Replace populated fields with only the default field value
@param {Object} doc
@param {Object} fields
@return {Object} | [
"Replace",
"populated",
"fields",
"with",
"only",
"the",
"default",
"field",
"value"
]
| a528cfd534d382fe17fcc50fe21664a01bef9e89 | https://github.com/ExclamationLabs/sevr-cli/blob/a528cfd534d382fe17fcc50fe21664a01bef9e89/lib/manage/commands/find.js#L66-L87 |
|
45,314 | ExclamationLabs/sevr-cli | lib/manage/commands/find.js | function(doc, def, labelTemplate) {
return Object.keys(doc)
.map(key => {
const field = doc[key]
const fieldDef = def[key]
if (!field || (!fieldDef && key != '_id')) {
return null
}
const name = key == '_id' ? 'id' : fieldDef.label
const template = labelTemplate || '%s'
const label = util.format(template, name)
if (typeof field == 'object' && !Array.isArray(field) && key != '_id') {
return getDocumentOutput(field, fieldDef.schemaType, label + ' (%s)')
}
return `${chalk.yellow(label)}: ${field}`
})
.filter(line => { return line !== null })
.join('\n')
} | javascript | function(doc, def, labelTemplate) {
return Object.keys(doc)
.map(key => {
const field = doc[key]
const fieldDef = def[key]
if (!field || (!fieldDef && key != '_id')) {
return null
}
const name = key == '_id' ? 'id' : fieldDef.label
const template = labelTemplate || '%s'
const label = util.format(template, name)
if (typeof field == 'object' && !Array.isArray(field) && key != '_id') {
return getDocumentOutput(field, fieldDef.schemaType, label + ' (%s)')
}
return `${chalk.yellow(label)}: ${field}`
})
.filter(line => { return line !== null })
.join('\n')
} | [
"function",
"(",
"doc",
",",
"def",
",",
"labelTemplate",
")",
"{",
"return",
"Object",
".",
"keys",
"(",
"doc",
")",
".",
"map",
"(",
"key",
"=>",
"{",
"const",
"field",
"=",
"doc",
"[",
"key",
"]",
"const",
"fieldDef",
"=",
"def",
"[",
"key",
"]",
"if",
"(",
"!",
"field",
"||",
"(",
"!",
"fieldDef",
"&&",
"key",
"!=",
"'_id'",
")",
")",
"{",
"return",
"null",
"}",
"const",
"name",
"=",
"key",
"==",
"'_id'",
"?",
"'id'",
":",
"fieldDef",
".",
"label",
"const",
"template",
"=",
"labelTemplate",
"||",
"'%s'",
"const",
"label",
"=",
"util",
".",
"format",
"(",
"template",
",",
"name",
")",
"if",
"(",
"typeof",
"field",
"==",
"'object'",
"&&",
"!",
"Array",
".",
"isArray",
"(",
"field",
")",
"&&",
"key",
"!=",
"'_id'",
")",
"{",
"return",
"getDocumentOutput",
"(",
"field",
",",
"fieldDef",
".",
"schemaType",
",",
"label",
"+",
"' (%s)'",
")",
"}",
"return",
"`",
"${",
"chalk",
".",
"yellow",
"(",
"label",
")",
"}",
"${",
"field",
"}",
"`",
"}",
")",
".",
"filter",
"(",
"line",
"=>",
"{",
"return",
"line",
"!==",
"null",
"}",
")",
".",
"join",
"(",
"'\\n'",
")",
"}"
]
| Get the string representation of the document
@param {Object} doc
@param {Object} def
@param {String} [labelTemplate='%s']
@return {String} | [
"Get",
"the",
"string",
"representation",
"of",
"the",
"document"
]
| a528cfd534d382fe17fcc50fe21664a01bef9e89 | https://github.com/ExclamationLabs/sevr-cli/blob/a528cfd534d382fe17fcc50fe21664a01bef9e89/lib/manage/commands/find.js#L96-L119 |
|
45,315 | SpoonX/typer | index.js | function (value) {
value += '';
if (value.search(/^\-?\d+$/) > -1) {
return 'integer';
}
if (value.search(/^\-?\d+\.\d+[\d.]*$/) > -1) {
return 'float';
}
if ('false' === value || 'true' === value) {
return 'boolean';
}
if (value.search(/^\d{4}\-\d{2}\-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z?$/) > -1) {
return 'datetime';
}
return 'string';
} | javascript | function (value) {
value += '';
if (value.search(/^\-?\d+$/) > -1) {
return 'integer';
}
if (value.search(/^\-?\d+\.\d+[\d.]*$/) > -1) {
return 'float';
}
if ('false' === value || 'true' === value) {
return 'boolean';
}
if (value.search(/^\d{4}\-\d{2}\-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z?$/) > -1) {
return 'datetime';
}
return 'string';
} | [
"function",
"(",
"value",
")",
"{",
"value",
"+=",
"''",
";",
"if",
"(",
"value",
".",
"search",
"(",
"/",
"^\\-?\\d+$",
"/",
")",
">",
"-",
"1",
")",
"{",
"return",
"'integer'",
";",
"}",
"if",
"(",
"value",
".",
"search",
"(",
"/",
"^\\-?\\d+\\.\\d+[\\d.]*$",
"/",
")",
">",
"-",
"1",
")",
"{",
"return",
"'float'",
";",
"}",
"if",
"(",
"'false'",
"===",
"value",
"||",
"'true'",
"===",
"value",
")",
"{",
"return",
"'boolean'",
";",
"}",
"if",
"(",
"value",
".",
"search",
"(",
"/",
"^\\d{4}\\-\\d{2}\\-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z?$",
"/",
")",
">",
"-",
"1",
")",
"{",
"return",
"'datetime'",
";",
"}",
"return",
"'string'",
";",
"}"
]
| Detect the type of `value`. Returns 'integer', 'float', 'boolean' or 'string'; defaults to 'string'.
@param {*} value
@returns {String} | [
"Detect",
"the",
"type",
"of",
"value",
".",
"Returns",
"integer",
"float",
"boolean",
"or",
"string",
";",
"defaults",
"to",
"string",
"."
]
| d949e57d70f195b534f0f5632791e861404b47de | https://github.com/SpoonX/typer/blob/d949e57d70f195b534f0f5632791e861404b47de/index.js#L9-L29 |
|
45,316 | SpoonX/typer | index.js | function (value, type) {
type = type || 'smart';
switch (type) {
case 'boolean':
case 'bool':
if (typeof value !== 'string') {
value = !!value;
} else {
value = ['null', 'undefined', '0', 'false'].indexOf(value) === -1;
}
break;
case 'string':
case 'text':
value = this.cast(value, 'boolean') ? value + '' : null
break;
case 'date':
case 'datetime':
value = new Date(value);
break;
case 'int':
case 'integer':
case 'number':
value = ~~value;
break;
case 'float':
value = parseFloat(value);
break;
case 'smart':
value = this.cast(value, this.detect(value));
break;
default:
throw new Error('Expected valid casting type.');
}
return value;
} | javascript | function (value, type) {
type = type || 'smart';
switch (type) {
case 'boolean':
case 'bool':
if (typeof value !== 'string') {
value = !!value;
} else {
value = ['null', 'undefined', '0', 'false'].indexOf(value) === -1;
}
break;
case 'string':
case 'text':
value = this.cast(value, 'boolean') ? value + '' : null
break;
case 'date':
case 'datetime':
value = new Date(value);
break;
case 'int':
case 'integer':
case 'number':
value = ~~value;
break;
case 'float':
value = parseFloat(value);
break;
case 'smart':
value = this.cast(value, this.detect(value));
break;
default:
throw new Error('Expected valid casting type.');
}
return value;
} | [
"function",
"(",
"value",
",",
"type",
")",
"{",
"type",
"=",
"type",
"||",
"'smart'",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"'boolean'",
":",
"case",
"'bool'",
":",
"if",
"(",
"typeof",
"value",
"!==",
"'string'",
")",
"{",
"value",
"=",
"!",
"!",
"value",
";",
"}",
"else",
"{",
"value",
"=",
"[",
"'null'",
",",
"'undefined'",
",",
"'0'",
",",
"'false'",
"]",
".",
"indexOf",
"(",
"value",
")",
"===",
"-",
"1",
";",
"}",
"break",
";",
"case",
"'string'",
":",
"case",
"'text'",
":",
"value",
"=",
"this",
".",
"cast",
"(",
"value",
",",
"'boolean'",
")",
"?",
"value",
"+",
"''",
":",
"null",
"break",
";",
"case",
"'date'",
":",
"case",
"'datetime'",
":",
"value",
"=",
"new",
"Date",
"(",
"value",
")",
";",
"break",
";",
"case",
"'int'",
":",
"case",
"'integer'",
":",
"case",
"'number'",
":",
"value",
"=",
"~",
"~",
"value",
";",
"break",
";",
"case",
"'float'",
":",
"value",
"=",
"parseFloat",
"(",
"value",
")",
";",
"break",
";",
"case",
"'smart'",
":",
"value",
"=",
"this",
".",
"cast",
"(",
"value",
",",
"this",
".",
"detect",
"(",
"value",
")",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"'Expected valid casting type.'",
")",
";",
"}",
"return",
"value",
";",
"}"
]
| Cast `value` to given `type`.
@param {*} value
@param {String} [type]
@returns {*} | [
"Cast",
"value",
"to",
"given",
"type",
"."
]
| d949e57d70f195b534f0f5632791e861404b47de | https://github.com/SpoonX/typer/blob/d949e57d70f195b534f0f5632791e861404b47de/index.js#L39-L82 |
|
45,317 | tensor5/JSLinter | lib/jslint.js | next_line | function next_line() {
// Put the next line of source in source_line. If the line contains tabs,
// replace them with spaces and give a warning. Also warn if the line contains
// unsafe characters or is too damn long.
let at;
column = 0;
line += 1;
source_line = lines[line];
if (source_line !== undefined) {
at = source_line.search(rx_tab);
if (at >= 0) {
if (!option.white) {
warn_at("use_spaces", line, at + 1);
}
source_line = source_line.replace(rx_tab, " ");
}
at = source_line.search(rx_unsafe);
if (at >= 0) {
warn_at(
"unsafe",
line,
column + at,
"U+" + source_line.charCodeAt(at).toString(16)
);
}
if (option.maxlen && option.maxlen < source_line.length) {
warn_at("too_long", line, source_line.length);
} else if (!option.white && source_line.slice(-1) === " ") {
warn_at(
"unexpected_trailing_space",
line,
source_line.length - 1
);
}
}
return source_line;
} | javascript | function next_line() {
// Put the next line of source in source_line. If the line contains tabs,
// replace them with spaces and give a warning. Also warn if the line contains
// unsafe characters or is too damn long.
let at;
column = 0;
line += 1;
source_line = lines[line];
if (source_line !== undefined) {
at = source_line.search(rx_tab);
if (at >= 0) {
if (!option.white) {
warn_at("use_spaces", line, at + 1);
}
source_line = source_line.replace(rx_tab, " ");
}
at = source_line.search(rx_unsafe);
if (at >= 0) {
warn_at(
"unsafe",
line,
column + at,
"U+" + source_line.charCodeAt(at).toString(16)
);
}
if (option.maxlen && option.maxlen < source_line.length) {
warn_at("too_long", line, source_line.length);
} else if (!option.white && source_line.slice(-1) === " ") {
warn_at(
"unexpected_trailing_space",
line,
source_line.length - 1
);
}
}
return source_line;
} | [
"function",
"next_line",
"(",
")",
"{",
"// Put the next line of source in source_line. If the line contains tabs,",
"// replace them with spaces and give a warning. Also warn if the line contains",
"// unsafe characters or is too damn long.",
"let",
"at",
";",
"column",
"=",
"0",
";",
"line",
"+=",
"1",
";",
"source_line",
"=",
"lines",
"[",
"line",
"]",
";",
"if",
"(",
"source_line",
"!==",
"undefined",
")",
"{",
"at",
"=",
"source_line",
".",
"search",
"(",
"rx_tab",
")",
";",
"if",
"(",
"at",
">=",
"0",
")",
"{",
"if",
"(",
"!",
"option",
".",
"white",
")",
"{",
"warn_at",
"(",
"\"use_spaces\"",
",",
"line",
",",
"at",
"+",
"1",
")",
";",
"}",
"source_line",
"=",
"source_line",
".",
"replace",
"(",
"rx_tab",
",",
"\" \"",
")",
";",
"}",
"at",
"=",
"source_line",
".",
"search",
"(",
"rx_unsafe",
")",
";",
"if",
"(",
"at",
">=",
"0",
")",
"{",
"warn_at",
"(",
"\"unsafe\"",
",",
"line",
",",
"column",
"+",
"at",
",",
"\"U+\"",
"+",
"source_line",
".",
"charCodeAt",
"(",
"at",
")",
".",
"toString",
"(",
"16",
")",
")",
";",
"}",
"if",
"(",
"option",
".",
"maxlen",
"&&",
"option",
".",
"maxlen",
"<",
"source_line",
".",
"length",
")",
"{",
"warn_at",
"(",
"\"too_long\"",
",",
"line",
",",
"source_line",
".",
"length",
")",
";",
"}",
"else",
"if",
"(",
"!",
"option",
".",
"white",
"&&",
"source_line",
".",
"slice",
"(",
"-",
"1",
")",
"===",
"\" \"",
")",
"{",
"warn_at",
"(",
"\"unexpected_trailing_space\"",
",",
"line",
",",
"source_line",
".",
"length",
"-",
"1",
")",
";",
"}",
"}",
"return",
"source_line",
";",
"}"
]
| the current line source string | [
"the",
"current",
"line",
"source",
"string"
]
| de21e3a5c790ecc4a7373ab86a9bef479453834d | https://github.com/tensor5/JSLinter/blob/de21e3a5c790ecc4a7373ab86a9bef479453834d/lib/jslint.js#L633-L671 |
45,318 | tensor5/JSLinter | lib/jslint.js | enroll | function enroll(name, role, readonly) {
// Enroll a name into the current function context. The role can be exception,
// function, label, parameter, or variable. We look for variable redefinition
// because it causes confusion.
const id = name.id;
// Reserved words may not be enrolled.
if (syntax[id] !== undefined && id !== "ignore") {
warn("reserved_a", name);
} else {
// Has the name been enrolled in this context?
let earlier = functionage.context[id];
if (earlier) {
warn(
"redefinition_a_b",
name,
name.id,
earlier.line + fudge
);
// Has the name been enrolled in an outer context?
} else {
stack.forEach(function (value) {
const item = value.context[id];
if (item !== undefined) {
earlier = item;
}
});
if (earlier) {
if (id === "ignore") {
if (earlier.role === "variable") {
warn("unexpected_a", name);
}
} else {
if (
(
role !== "exception"
|| earlier.role !== "exception"
)
&& role !== "parameter"
&& role !== "function"
) {
warn(
"redefinition_a_b",
name,
name.id,
earlier.line + fudge
);
}
}
}
// Enroll it.
functionage.context[id] = name;
name.dead = true;
name.function = functionage;
name.init = false;
name.role = role;
name.used = 0;
name.writable = !readonly;
}
}
} | javascript | function enroll(name, role, readonly) {
// Enroll a name into the current function context. The role can be exception,
// function, label, parameter, or variable. We look for variable redefinition
// because it causes confusion.
const id = name.id;
// Reserved words may not be enrolled.
if (syntax[id] !== undefined && id !== "ignore") {
warn("reserved_a", name);
} else {
// Has the name been enrolled in this context?
let earlier = functionage.context[id];
if (earlier) {
warn(
"redefinition_a_b",
name,
name.id,
earlier.line + fudge
);
// Has the name been enrolled in an outer context?
} else {
stack.forEach(function (value) {
const item = value.context[id];
if (item !== undefined) {
earlier = item;
}
});
if (earlier) {
if (id === "ignore") {
if (earlier.role === "variable") {
warn("unexpected_a", name);
}
} else {
if (
(
role !== "exception"
|| earlier.role !== "exception"
)
&& role !== "parameter"
&& role !== "function"
) {
warn(
"redefinition_a_b",
name,
name.id,
earlier.line + fudge
);
}
}
}
// Enroll it.
functionage.context[id] = name;
name.dead = true;
name.function = functionage;
name.init = false;
name.role = role;
name.used = 0;
name.writable = !readonly;
}
}
} | [
"function",
"enroll",
"(",
"name",
",",
"role",
",",
"readonly",
")",
"{",
"// Enroll a name into the current function context. The role can be exception,",
"// function, label, parameter, or variable. We look for variable redefinition",
"// because it causes confusion.",
"const",
"id",
"=",
"name",
".",
"id",
";",
"// Reserved words may not be enrolled.",
"if",
"(",
"syntax",
"[",
"id",
"]",
"!==",
"undefined",
"&&",
"id",
"!==",
"\"ignore\"",
")",
"{",
"warn",
"(",
"\"reserved_a\"",
",",
"name",
")",
";",
"}",
"else",
"{",
"// Has the name been enrolled in this context?",
"let",
"earlier",
"=",
"functionage",
".",
"context",
"[",
"id",
"]",
";",
"if",
"(",
"earlier",
")",
"{",
"warn",
"(",
"\"redefinition_a_b\"",
",",
"name",
",",
"name",
".",
"id",
",",
"earlier",
".",
"line",
"+",
"fudge",
")",
";",
"// Has the name been enrolled in an outer context?",
"}",
"else",
"{",
"stack",
".",
"forEach",
"(",
"function",
"(",
"value",
")",
"{",
"const",
"item",
"=",
"value",
".",
"context",
"[",
"id",
"]",
";",
"if",
"(",
"item",
"!==",
"undefined",
")",
"{",
"earlier",
"=",
"item",
";",
"}",
"}",
")",
";",
"if",
"(",
"earlier",
")",
"{",
"if",
"(",
"id",
"===",
"\"ignore\"",
")",
"{",
"if",
"(",
"earlier",
".",
"role",
"===",
"\"variable\"",
")",
"{",
"warn",
"(",
"\"unexpected_a\"",
",",
"name",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"(",
"role",
"!==",
"\"exception\"",
"||",
"earlier",
".",
"role",
"!==",
"\"exception\"",
")",
"&&",
"role",
"!==",
"\"parameter\"",
"&&",
"role",
"!==",
"\"function\"",
")",
"{",
"warn",
"(",
"\"redefinition_a_b\"",
",",
"name",
",",
"name",
".",
"id",
",",
"earlier",
".",
"line",
"+",
"fudge",
")",
";",
"}",
"}",
"}",
"// Enroll it.",
"functionage",
".",
"context",
"[",
"id",
"]",
"=",
"name",
";",
"name",
".",
"dead",
"=",
"true",
";",
"name",
".",
"function",
"=",
"functionage",
";",
"name",
".",
"init",
"=",
"false",
";",
"name",
".",
"role",
"=",
"role",
";",
"name",
".",
"used",
"=",
"0",
";",
"name",
".",
"writable",
"=",
"!",
"readonly",
";",
"}",
"}",
"}"
]
| Now we parse JavaScript. | [
"Now",
"we",
"parse",
"JavaScript",
"."
]
| de21e3a5c790ecc4a7373ab86a9bef479453834d | https://github.com/tensor5/JSLinter/blob/de21e3a5c790ecc4a7373ab86a9bef479453834d/lib/jslint.js#L1788-L1857 |
45,319 | vid/SenseBase | services/annotators/annotationSet.js | setAnnotationSets | function setAnnotationSets(sets) {
annotationSets = sets.map(function(s) {
var r = '\\b(' + s.terms.join('|') + ')\\b';
s.re = new RegExp(r, 'mi');
return s;
});
} | javascript | function setAnnotationSets(sets) {
annotationSets = sets.map(function(s) {
var r = '\\b(' + s.terms.join('|') + ')\\b';
s.re = new RegExp(r, 'mi');
return s;
});
} | [
"function",
"setAnnotationSets",
"(",
"sets",
")",
"{",
"annotationSets",
"=",
"sets",
".",
"map",
"(",
"function",
"(",
"s",
")",
"{",
"var",
"r",
"=",
"'\\\\b('",
"+",
"s",
".",
"terms",
".",
"join",
"(",
"'|'",
")",
"+",
"')\\\\b'",
";",
"s",
".",
"re",
"=",
"new",
"RegExp",
"(",
"r",
",",
"'mi'",
")",
";",
"return",
"s",
";",
"}",
")",
";",
"}"
]
| configure with these annotation sets | [
"configure",
"with",
"these",
"annotation",
"sets"
]
| d60bcf28239e7dde437d8a6bdae41a6921dcd05b | https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/services/annotators/annotationSet.js#L29-L35 |
45,320 | imbo/imboclient-js-metadata | index.js | buildQuery | function buildQuery(opts, globalSearch) {
var imboQuery = new ImboQuery();
imboQuery.page(opts.page);
imboQuery.limit(opts.limit);
if (opts.users && globalSearch) {
imboQuery.users(opts.users);
}
if (opts.fields) {
imboQuery.fields(opts.fields);
}
if (opts.sort) {
imboQuery.addSorts(opts.sort);
}
if (opts.metadata) {
imboQuery.metadata(opts.metadata);
}
return imboQuery;
} | javascript | function buildQuery(opts, globalSearch) {
var imboQuery = new ImboQuery();
imboQuery.page(opts.page);
imboQuery.limit(opts.limit);
if (opts.users && globalSearch) {
imboQuery.users(opts.users);
}
if (opts.fields) {
imboQuery.fields(opts.fields);
}
if (opts.sort) {
imboQuery.addSorts(opts.sort);
}
if (opts.metadata) {
imboQuery.metadata(opts.metadata);
}
return imboQuery;
} | [
"function",
"buildQuery",
"(",
"opts",
",",
"globalSearch",
")",
"{",
"var",
"imboQuery",
"=",
"new",
"ImboQuery",
"(",
")",
";",
"imboQuery",
".",
"page",
"(",
"opts",
".",
"page",
")",
";",
"imboQuery",
".",
"limit",
"(",
"opts",
".",
"limit",
")",
";",
"if",
"(",
"opts",
".",
"users",
"&&",
"globalSearch",
")",
"{",
"imboQuery",
".",
"users",
"(",
"opts",
".",
"users",
")",
";",
"}",
"if",
"(",
"opts",
".",
"fields",
")",
"{",
"imboQuery",
".",
"fields",
"(",
"opts",
".",
"fields",
")",
";",
"}",
"if",
"(",
"opts",
".",
"sort",
")",
"{",
"imboQuery",
".",
"addSorts",
"(",
"opts",
".",
"sort",
")",
";",
"}",
"if",
"(",
"opts",
".",
"metadata",
")",
"{",
"imboQuery",
".",
"metadata",
"(",
"opts",
".",
"metadata",
")",
";",
"}",
"return",
"imboQuery",
";",
"}"
]
| Build the query object used to build the URI string
@param {Object} opts - Metadata query options
@param {bool} globalSearch - Whether we're searching globally or not
@return {Query} | [
"Build",
"the",
"query",
"object",
"used",
"to",
"build",
"the",
"URI",
"string"
]
| d99a989f1fbb68612e92b53fc2f64a87cfc52f1d | https://github.com/imbo/imboclient-js-metadata/blob/d99a989f1fbb68612e92b53fc2f64a87cfc52f1d/index.js#L13-L36 |
45,321 | imbo/imboclient-js-metadata | index.js | searchGlobalMetadata | function searchGlobalMetadata(query, opts, callback) {
if (typeof opts === 'function' && !callback) {
callback = opts;
opts = {};
}
var searchEndpointUrl = this.getResourceUrl({
path: '/images',
user: null,
query: buildQuery(opts, true).toString()
});
request({
method: 'SEARCH',
uri: searchEndpointUrl.toString(),
json: query,
header: {
'User-Agent': 'imboclient-js'
},
onComplete: function(err, res, body) {
callback(
err,
body ? body.images : [],
body ? body.search : {},
res
);
}
});
return true;
} | javascript | function searchGlobalMetadata(query, opts, callback) {
if (typeof opts === 'function' && !callback) {
callback = opts;
opts = {};
}
var searchEndpointUrl = this.getResourceUrl({
path: '/images',
user: null,
query: buildQuery(opts, true).toString()
});
request({
method: 'SEARCH',
uri: searchEndpointUrl.toString(),
json: query,
header: {
'User-Agent': 'imboclient-js'
},
onComplete: function(err, res, body) {
callback(
err,
body ? body.images : [],
body ? body.search : {},
res
);
}
});
return true;
} | [
"function",
"searchGlobalMetadata",
"(",
"query",
",",
"opts",
",",
"callback",
")",
"{",
"if",
"(",
"typeof",
"opts",
"===",
"'function'",
"&&",
"!",
"callback",
")",
"{",
"callback",
"=",
"opts",
";",
"opts",
"=",
"{",
"}",
";",
"}",
"var",
"searchEndpointUrl",
"=",
"this",
".",
"getResourceUrl",
"(",
"{",
"path",
":",
"'/images'",
",",
"user",
":",
"null",
",",
"query",
":",
"buildQuery",
"(",
"opts",
",",
"true",
")",
".",
"toString",
"(",
")",
"}",
")",
";",
"request",
"(",
"{",
"method",
":",
"'SEARCH'",
",",
"uri",
":",
"searchEndpointUrl",
".",
"toString",
"(",
")",
",",
"json",
":",
"query",
",",
"header",
":",
"{",
"'User-Agent'",
":",
"'imboclient-js'",
"}",
",",
"onComplete",
":",
"function",
"(",
"err",
",",
"res",
",",
"body",
")",
"{",
"callback",
"(",
"err",
",",
"body",
"?",
"body",
".",
"images",
":",
"[",
"]",
",",
"body",
"?",
"body",
".",
"search",
":",
"{",
"}",
",",
"res",
")",
";",
"}",
"}",
")",
";",
"return",
"true",
";",
"}"
]
| Search globally for images using metadata
@param {Object} query - Metadata search query
@param {Object} opts - Metadata query options
@param {Function} callback - Function to call with the search result
@return {boolean}
@this ImboClient | [
"Search",
"globally",
"for",
"images",
"using",
"metadata"
]
| d99a989f1fbb68612e92b53fc2f64a87cfc52f1d | https://github.com/imbo/imboclient-js-metadata/blob/d99a989f1fbb68612e92b53fc2f64a87cfc52f1d/index.js#L47-L77 |
45,322 | glaunay/ms-jobmanager | build/nativeJS/job-manager-server.js | granted | function granted(data, socket) {
return new Promise((resolve, reject) => {
setTimeout(() => {
logger.debug(`i grant access to ${util.format(data.id)}`);
broadcast('available');
let socketNamespace = data.id;
let newData = {
script: ss.createStream(),
inputs: {}
};
for (let inputSymbol in data.inputs) {
//let filePath = data.inputs[inputSymbol];
//logger.debug(`-->${filePath}`);
newData.inputs[inputSymbol] = ss.createStream();
logger.debug(`ssStream emission for input symbol '${inputSymbol}'`);
ss(socket).emit(socketNamespace + "/" + inputSymbol, newData.inputs[inputSymbol]);
//logger.warn('IeDump from' + socketNamespace + "/" + inputSymbol);
//newData.inputs[inputSymbol].pipe(process.stdout)
}
ss(socket).emit(socketNamespace + "/script", newData.script);
//logger.error(`TOTOT2\n${util.format(newData)}`);
for (let k in data) {
if (k !== 'inputs' && k !== 'script')
newData[k] = data[k];
}
newData.socket = socket;
socket.emit('granted', { jobID: data.id });
resolve(newData);
}, 250);
});
} | javascript | function granted(data, socket) {
return new Promise((resolve, reject) => {
setTimeout(() => {
logger.debug(`i grant access to ${util.format(data.id)}`);
broadcast('available');
let socketNamespace = data.id;
let newData = {
script: ss.createStream(),
inputs: {}
};
for (let inputSymbol in data.inputs) {
//let filePath = data.inputs[inputSymbol];
//logger.debug(`-->${filePath}`);
newData.inputs[inputSymbol] = ss.createStream();
logger.debug(`ssStream emission for input symbol '${inputSymbol}'`);
ss(socket).emit(socketNamespace + "/" + inputSymbol, newData.inputs[inputSymbol]);
//logger.warn('IeDump from' + socketNamespace + "/" + inputSymbol);
//newData.inputs[inputSymbol].pipe(process.stdout)
}
ss(socket).emit(socketNamespace + "/script", newData.script);
//logger.error(`TOTOT2\n${util.format(newData)}`);
for (let k in data) {
if (k !== 'inputs' && k !== 'script')
newData[k] = data[k];
}
newData.socket = socket;
socket.emit('granted', { jobID: data.id });
resolve(newData);
}, 250);
});
} | [
"function",
"granted",
"(",
"data",
",",
"socket",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"logger",
".",
"debug",
"(",
"`",
"${",
"util",
".",
"format",
"(",
"data",
".",
"id",
")",
"}",
"`",
")",
";",
"broadcast",
"(",
"'available'",
")",
";",
"let",
"socketNamespace",
"=",
"data",
".",
"id",
";",
"let",
"newData",
"=",
"{",
"script",
":",
"ss",
".",
"createStream",
"(",
")",
",",
"inputs",
":",
"{",
"}",
"}",
";",
"for",
"(",
"let",
"inputSymbol",
"in",
"data",
".",
"inputs",
")",
"{",
"//let filePath = data.inputs[inputSymbol];",
"//logger.debug(`-->${filePath}`);",
"newData",
".",
"inputs",
"[",
"inputSymbol",
"]",
"=",
"ss",
".",
"createStream",
"(",
")",
";",
"logger",
".",
"debug",
"(",
"`",
"${",
"inputSymbol",
"}",
"`",
")",
";",
"ss",
"(",
"socket",
")",
".",
"emit",
"(",
"socketNamespace",
"+",
"\"/\"",
"+",
"inputSymbol",
",",
"newData",
".",
"inputs",
"[",
"inputSymbol",
"]",
")",
";",
"//logger.warn('IeDump from' + socketNamespace + \"/\" + inputSymbol);",
"//newData.inputs[inputSymbol].pipe(process.stdout)",
"}",
"ss",
"(",
"socket",
")",
".",
"emit",
"(",
"socketNamespace",
"+",
"\"/script\"",
",",
"newData",
".",
"script",
")",
";",
"//logger.error(`TOTOT2\\n${util.format(newData)}`);",
"for",
"(",
"let",
"k",
"in",
"data",
")",
"{",
"if",
"(",
"k",
"!==",
"'inputs'",
"&&",
"k",
"!==",
"'script'",
")",
"newData",
"[",
"k",
"]",
"=",
"data",
"[",
"k",
"]",
";",
"}",
"newData",
".",
"socket",
"=",
"socket",
";",
"socket",
".",
"emit",
"(",
"'granted'",
",",
"{",
"jobID",
":",
"data",
".",
"id",
"}",
")",
";",
"resolve",
"(",
"newData",
")",
";",
"}",
",",
"250",
")",
";",
"}",
")",
";",
"}"
]
| We build streams only at granted | [
"We",
"build",
"streams",
"only",
"at",
"granted"
]
| 997d4fb25fd1d2b41acfae1dd576b33f2c92bd15 | https://github.com/glaunay/ms-jobmanager/blob/997d4fb25fd1d2b41acfae1dd576b33f2c92bd15/build/nativeJS/job-manager-server.js#L97-L127 |
45,323 | lial/coordist | coordist.js | getDecimalDegree | function getDecimalDegree(deg, min, sec) {
if (min == undefined) min = 0;
if (sec == undefined) sec = 0;
return deg < 0 ?
(Math.abs(deg) + Math.abs(min) / 60 + Math.absabs(sec) / 3600) * -1 :
Math.absabs(deg) + Math.absabs(min) / 60 + Math.absabs(sec) / 3600;
} | javascript | function getDecimalDegree(deg, min, sec) {
if (min == undefined) min = 0;
if (sec == undefined) sec = 0;
return deg < 0 ?
(Math.abs(deg) + Math.abs(min) / 60 + Math.absabs(sec) / 3600) * -1 :
Math.absabs(deg) + Math.absabs(min) / 60 + Math.absabs(sec) / 3600;
} | [
"function",
"getDecimalDegree",
"(",
"deg",
",",
"min",
",",
"sec",
")",
"{",
"if",
"(",
"min",
"==",
"undefined",
")",
"min",
"=",
"0",
";",
"if",
"(",
"sec",
"==",
"undefined",
")",
"sec",
"=",
"0",
";",
"return",
"deg",
"<",
"0",
"?",
"(",
"Math",
".",
"abs",
"(",
"deg",
")",
"+",
"Math",
".",
"abs",
"(",
"min",
")",
"/",
"60",
"+",
"Math",
".",
"absabs",
"(",
"sec",
")",
"/",
"3600",
")",
"*",
"-",
"1",
":",
"Math",
".",
"absabs",
"(",
"deg",
")",
"+",
"Math",
".",
"absabs",
"(",
"min",
")",
"/",
"60",
"+",
"Math",
".",
"absabs",
"(",
"sec",
")",
"/",
"3600",
";",
"}"
]
| Return decimal value of angle
@param Number deg Value in degrees
@param Number min Value in minutes
@param Number sec Value in seconds
@return Number | [
"Return",
"decimal",
"value",
"of",
"angle"
]
| 57cfd7ed3da23a8417550e672647729b0ebb8f73 | https://github.com/lial/coordist/blob/57cfd7ed3da23a8417550e672647729b0ebb8f73/coordist.js#L74-L81 |
45,324 | lial/coordist | coordist.js | getTrueAngle | function getTrueAngle(point) {
return Math.atan((minorAxisSquare / majorAxisSquare) * Math.tan(Deg2Rad(point.lat))) * 180 / Math.PI;
} | javascript | function getTrueAngle(point) {
return Math.atan((minorAxisSquare / majorAxisSquare) * Math.tan(Deg2Rad(point.lat))) * 180 / Math.PI;
} | [
"function",
"getTrueAngle",
"(",
"point",
")",
"{",
"return",
"Math",
".",
"atan",
"(",
"(",
"minorAxisSquare",
"/",
"majorAxisSquare",
")",
"*",
"Math",
".",
"tan",
"(",
"Deg2Rad",
"(",
"point",
".",
"lat",
")",
")",
")",
"*",
"180",
"/",
"Math",
".",
"PI",
";",
"}"
]
| Determine true angle for point on surface
@param Object point Point on surface
@var point {lat, lng, alt}
@var lat - latitude (широта)
@var lng - longitude (долгота)
@var alt - altitude (высота над уровнем моря)
@return Number | [
"Determine",
"true",
"angle",
"for",
"point",
"on",
"surface"
]
| 57cfd7ed3da23a8417550e672647729b0ebb8f73 | https://github.com/lial/coordist/blob/57cfd7ed3da23a8417550e672647729b0ebb8f73/coordist.js#L96-L98 |
45,325 | warehouseai/warehouse-models | lib/package.js | tryParse | function tryParse(data) {
var json;
try {
json = JSON.parse(data);
} catch (ex) { debug('tryParse exception %s for data %s', ex, data); }
return json || data;
} | javascript | function tryParse(data) {
var json;
try {
json = JSON.parse(data);
} catch (ex) { debug('tryParse exception %s for data %s', ex, data); }
return json || data;
} | [
"function",
"tryParse",
"(",
"data",
")",
"{",
"var",
"json",
";",
"try",
"{",
"json",
"=",
"JSON",
".",
"parse",
"(",
"data",
")",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"debug",
"(",
"'tryParse exception %s for data %s'",
",",
"ex",
",",
"data",
")",
";",
"}",
"return",
"json",
"||",
"data",
";",
"}"
]
| Try to parse a string as JSON, otherwise return the string | [
"Try",
"to",
"parse",
"a",
"string",
"as",
"JSON",
"otherwise",
"return",
"the",
"string"
]
| ee65aa759adc6a7f83f4b02608a4e74fe562aa89 | https://github.com/warehouseai/warehouse-models/blob/ee65aa759adc6a7f83f4b02608a4e74fe562aa89/lib/package.js#L229-L236 |
45,326 | christill/grunt-sanitize | tasks/sanitize.js | formatFileName | function formatFileName(filepath) {
var validFilename;
validFilename = filepath.replace(/\s/g, options.separator);
validFilename = validFilename.replace(/[^a-zA-Z_0-9.]/, '');
validFilename = validFilename.toLowerCase();
return validFilename;
} | javascript | function formatFileName(filepath) {
var validFilename;
validFilename = filepath.replace(/\s/g, options.separator);
validFilename = validFilename.replace(/[^a-zA-Z_0-9.]/, '');
validFilename = validFilename.toLowerCase();
return validFilename;
} | [
"function",
"formatFileName",
"(",
"filepath",
")",
"{",
"var",
"validFilename",
";",
"validFilename",
"=",
"filepath",
".",
"replace",
"(",
"/",
"\\s",
"/",
"g",
",",
"options",
".",
"separator",
")",
";",
"validFilename",
"=",
"validFilename",
".",
"replace",
"(",
"/",
"[^a-zA-Z_0-9.]",
"/",
",",
"''",
")",
";",
"validFilename",
"=",
"validFilename",
".",
"toLowerCase",
"(",
")",
";",
"return",
"validFilename",
";",
"}"
]
| Format file name
@param {String} path
@return {String} | [
"Format",
"file",
"name"
]
| 2df717ed926a5b40f251ce6b5b1209756548d65d | https://github.com/christill/grunt-sanitize/blob/2df717ed926a5b40f251ce6b5b1209756548d65d/tasks/sanitize.js#L22-L31 |
45,327 | KeithPepin/prevent-forbidden-code | index.js | checkFile | function checkFile(fileName, contents) {
forbiddenCode.forEach(function(forbiddenItem) {
if (contents.indexOf(forbiddenItem) > -1) {
/* eslint-disable */
console.log('FAILURE: '.red + 'You left a '.reset + forbiddenItem.yellow + ' in '.reset + fileName.cyan);
/* eslint-enable */
errorFound = true;
}
});
} | javascript | function checkFile(fileName, contents) {
forbiddenCode.forEach(function(forbiddenItem) {
if (contents.indexOf(forbiddenItem) > -1) {
/* eslint-disable */
console.log('FAILURE: '.red + 'You left a '.reset + forbiddenItem.yellow + ' in '.reset + fileName.cyan);
/* eslint-enable */
errorFound = true;
}
});
} | [
"function",
"checkFile",
"(",
"fileName",
",",
"contents",
")",
"{",
"forbiddenCode",
".",
"forEach",
"(",
"function",
"(",
"forbiddenItem",
")",
"{",
"if",
"(",
"contents",
".",
"indexOf",
"(",
"forbiddenItem",
")",
">",
"-",
"1",
")",
"{",
"/* eslint-disable */",
"console",
".",
"log",
"(",
"'FAILURE: '",
".",
"red",
"+",
"'You left a '",
".",
"reset",
"+",
"forbiddenItem",
".",
"yellow",
"+",
"' in '",
".",
"reset",
"+",
"fileName",
".",
"cyan",
")",
";",
"/* eslint-enable */",
"errorFound",
"=",
"true",
";",
"}",
"}",
")",
";",
"}"
]
| Analyzes a given file for forbidden code
@param {String} fileName
@param {String} contents | [
"Analyzes",
"a",
"given",
"file",
"for",
"forbidden",
"code"
]
| 64eb3038a47494d55251c5c68e327919f5ba7b33 | https://github.com/KeithPepin/prevent-forbidden-code/blob/64eb3038a47494d55251c5c68e327919f5ba7b33/index.js#L37-L46 |
45,328 | KeithPepin/prevent-forbidden-code | index.js | fileExists | function fileExists(file) {
var fileExists = true;
try {
fs.statSync(file, function(err, stat) {
if (err == null) {
fileExists = true;
} else {
fileExists = false;
}
});
} catch (e) {
fileExists = false;
}
return fileExists;
} | javascript | function fileExists(file) {
var fileExists = true;
try {
fs.statSync(file, function(err, stat) {
if (err == null) {
fileExists = true;
} else {
fileExists = false;
}
});
} catch (e) {
fileExists = false;
}
return fileExists;
} | [
"function",
"fileExists",
"(",
"file",
")",
"{",
"var",
"fileExists",
"=",
"true",
";",
"try",
"{",
"fs",
".",
"statSync",
"(",
"file",
",",
"function",
"(",
"err",
",",
"stat",
")",
"{",
"if",
"(",
"err",
"==",
"null",
")",
"{",
"fileExists",
"=",
"true",
";",
"}",
"else",
"{",
"fileExists",
"=",
"false",
";",
"}",
"}",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"fileExists",
"=",
"false",
";",
"}",
"return",
"fileExists",
";",
"}"
]
| Indicates if a given file exists or not
@param {String} file
@return {boolean} | [
"Indicates",
"if",
"a",
"given",
"file",
"exists",
"or",
"not"
]
| 64eb3038a47494d55251c5c68e327919f5ba7b33 | https://github.com/KeithPepin/prevent-forbidden-code/blob/64eb3038a47494d55251c5c68e327919f5ba7b33/index.js#L64-L80 |
45,329 | opentargets/RestApiJs | src/structure.js | cloneNode | function cloneNode (n) {
var c = {
__association_score: n.__association_score,
__evidence_count: n.__evidence_count,
id: n.id,
__id: n.__id,
__name: n.__name,
target: {
id: n.target.id,
name: n.target.gene_info.name,
symbol: n.target.gene_info.symbol
},
disease: cloneDisease(n.disease),
association_score: cloneAssociationScore(n.association_score),
evidence_count: cloneEvidenceCount(n.evidence_count)
};
if (n.is_direct) {
c.is_direct = n.is_direct;
}
return c;
} | javascript | function cloneNode (n) {
var c = {
__association_score: n.__association_score,
__evidence_count: n.__evidence_count,
id: n.id,
__id: n.__id,
__name: n.__name,
target: {
id: n.target.id,
name: n.target.gene_info.name,
symbol: n.target.gene_info.symbol
},
disease: cloneDisease(n.disease),
association_score: cloneAssociationScore(n.association_score),
evidence_count: cloneEvidenceCount(n.evidence_count)
};
if (n.is_direct) {
c.is_direct = n.is_direct;
}
return c;
} | [
"function",
"cloneNode",
"(",
"n",
")",
"{",
"var",
"c",
"=",
"{",
"__association_score",
":",
"n",
".",
"__association_score",
",",
"__evidence_count",
":",
"n",
".",
"__evidence_count",
",",
"id",
":",
"n",
".",
"id",
",",
"__id",
":",
"n",
".",
"__id",
",",
"__name",
":",
"n",
".",
"__name",
",",
"target",
":",
"{",
"id",
":",
"n",
".",
"target",
".",
"id",
",",
"name",
":",
"n",
".",
"target",
".",
"gene_info",
".",
"name",
",",
"symbol",
":",
"n",
".",
"target",
".",
"gene_info",
".",
"symbol",
"}",
",",
"disease",
":",
"cloneDisease",
"(",
"n",
".",
"disease",
")",
",",
"association_score",
":",
"cloneAssociationScore",
"(",
"n",
".",
"association_score",
")",
",",
"evidence_count",
":",
"cloneEvidenceCount",
"(",
"n",
".",
"evidence_count",
")",
"}",
";",
"if",
"(",
"n",
".",
"is_direct",
")",
"{",
"c",
".",
"is_direct",
"=",
"n",
".",
"is_direct",
";",
"}",
"return",
"c",
";",
"}"
]
| Fast clone methods | [
"Fast",
"clone",
"methods"
]
| afe7dcc61223419c4677b2ab69db17d26ca58a90 | https://github.com/opentargets/RestApiJs/blob/afe7dcc61223419c4677b2ab69db17d26ca58a90/src/structure.js#L155-L175 |
45,330 | Whitebolt/require-extra | src/try.js | _tryModuleSync | function _tryModuleSync(modulePath, defaultReturnValue) {
try {
return syncRequire({squashErrors:true}, modulePath.shift());
} catch (err) { }
if(!modulePath.length) return defaultReturnValue;
return _tryModuleSync(modulePath, defaultReturnValue);
} | javascript | function _tryModuleSync(modulePath, defaultReturnValue) {
try {
return syncRequire({squashErrors:true}, modulePath.shift());
} catch (err) { }
if(!modulePath.length) return defaultReturnValue;
return _tryModuleSync(modulePath, defaultReturnValue);
} | [
"function",
"_tryModuleSync",
"(",
"modulePath",
",",
"defaultReturnValue",
")",
"{",
"try",
"{",
"return",
"syncRequire",
"(",
"{",
"squashErrors",
":",
"true",
"}",
",",
"modulePath",
".",
"shift",
"(",
")",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"}",
"if",
"(",
"!",
"modulePath",
".",
"length",
")",
"return",
"defaultReturnValue",
";",
"return",
"_tryModuleSync",
"(",
"modulePath",
",",
"defaultReturnValue",
")",
";",
"}"
]
| Load a module or return a default value. Can take an array to try. Will load module synchronously.
@private
@async
@param {Array.<string>} modulePath Paths to try.
@param {*} defaultReturnValue Default value to return.
@returns {*} | [
"Load",
"a",
"module",
"or",
"return",
"a",
"default",
"value",
".",
"Can",
"take",
"an",
"array",
"to",
"try",
".",
"Will",
"load",
"module",
"synchronously",
"."
]
| 2a8f737aab67305c9fda3ee56aa7953e97cee859 | https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/src/try.js#L53-L59 |
45,331 | synder/xpress | demo/body-parser/lib/types/json.js | json | function json (options) {
var opts = options || {}
var limit = typeof opts.limit !== 'number'
? bytes.parse(opts.limit || '100kb')
: opts.limit
var inflate = opts.inflate !== false
var reviver = opts.reviver
var strict = opts.strict !== false
var type = opts.type || 'application/json'
var verify = opts.verify || false
if (verify !== false && typeof verify !== 'function') {
throw new TypeError('option verify must be function')
}
// create the appropriate type checking function
var shouldParse = typeof type !== 'function'
? typeChecker(type)
: type
function parse (body) {
if (body.length === 0) {
// special-case empty json body, as it's a common client-side mistake
// TODO: maybe make this configurable or part of "strict" option
return {}
}
if (strict) {
var first = firstchar(body)
if (first !== '{' && first !== '[') {
debug('strict violation')
throw new SyntaxError('Unexpected token ' + first)
}
}
debug('parse json')
return JSON.parse(body, reviver)
}
return function jsonParser (req, res, next) {
if (req._body) {
debug('body already parsed')
next()
return
}
req.body = req.body || {}
// skip requests without bodies
if (!typeis.hasBody(req)) {
debug('skip empty body')
next()
return
}
debug('content-type %j', req.headers['content-type'])
// determine if request should be parsed
if (!shouldParse(req)) {
debug('skip parsing')
next()
return
}
// assert charset per RFC 7159 sec 8.1
var charset = getCharset(req) || 'utf-8'
if (charset.substr(0, 4) !== 'utf-') {
debug('invalid charset')
next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
charset: charset
}))
return
}
// read
read(req, res, next, parse, debug, {
encoding: charset,
inflate: inflate,
limit: limit,
verify: verify
})
}
} | javascript | function json (options) {
var opts = options || {}
var limit = typeof opts.limit !== 'number'
? bytes.parse(opts.limit || '100kb')
: opts.limit
var inflate = opts.inflate !== false
var reviver = opts.reviver
var strict = opts.strict !== false
var type = opts.type || 'application/json'
var verify = opts.verify || false
if (verify !== false && typeof verify !== 'function') {
throw new TypeError('option verify must be function')
}
// create the appropriate type checking function
var shouldParse = typeof type !== 'function'
? typeChecker(type)
: type
function parse (body) {
if (body.length === 0) {
// special-case empty json body, as it's a common client-side mistake
// TODO: maybe make this configurable or part of "strict" option
return {}
}
if (strict) {
var first = firstchar(body)
if (first !== '{' && first !== '[') {
debug('strict violation')
throw new SyntaxError('Unexpected token ' + first)
}
}
debug('parse json')
return JSON.parse(body, reviver)
}
return function jsonParser (req, res, next) {
if (req._body) {
debug('body already parsed')
next()
return
}
req.body = req.body || {}
// skip requests without bodies
if (!typeis.hasBody(req)) {
debug('skip empty body')
next()
return
}
debug('content-type %j', req.headers['content-type'])
// determine if request should be parsed
if (!shouldParse(req)) {
debug('skip parsing')
next()
return
}
// assert charset per RFC 7159 sec 8.1
var charset = getCharset(req) || 'utf-8'
if (charset.substr(0, 4) !== 'utf-') {
debug('invalid charset')
next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
charset: charset
}))
return
}
// read
read(req, res, next, parse, debug, {
encoding: charset,
inflate: inflate,
limit: limit,
verify: verify
})
}
} | [
"function",
"json",
"(",
"options",
")",
"{",
"var",
"opts",
"=",
"options",
"||",
"{",
"}",
"var",
"limit",
"=",
"typeof",
"opts",
".",
"limit",
"!==",
"'number'",
"?",
"bytes",
".",
"parse",
"(",
"opts",
".",
"limit",
"||",
"'100kb'",
")",
":",
"opts",
".",
"limit",
"var",
"inflate",
"=",
"opts",
".",
"inflate",
"!==",
"false",
"var",
"reviver",
"=",
"opts",
".",
"reviver",
"var",
"strict",
"=",
"opts",
".",
"strict",
"!==",
"false",
"var",
"type",
"=",
"opts",
".",
"type",
"||",
"'application/json'",
"var",
"verify",
"=",
"opts",
".",
"verify",
"||",
"false",
"if",
"(",
"verify",
"!==",
"false",
"&&",
"typeof",
"verify",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'option verify must be function'",
")",
"}",
"// create the appropriate type checking function",
"var",
"shouldParse",
"=",
"typeof",
"type",
"!==",
"'function'",
"?",
"typeChecker",
"(",
"type",
")",
":",
"type",
"function",
"parse",
"(",
"body",
")",
"{",
"if",
"(",
"body",
".",
"length",
"===",
"0",
")",
"{",
"// special-case empty json body, as it's a common client-side mistake",
"// TODO: maybe make this configurable or part of \"strict\" option",
"return",
"{",
"}",
"}",
"if",
"(",
"strict",
")",
"{",
"var",
"first",
"=",
"firstchar",
"(",
"body",
")",
"if",
"(",
"first",
"!==",
"'{'",
"&&",
"first",
"!==",
"'['",
")",
"{",
"debug",
"(",
"'strict violation'",
")",
"throw",
"new",
"SyntaxError",
"(",
"'Unexpected token '",
"+",
"first",
")",
"}",
"}",
"debug",
"(",
"'parse json'",
")",
"return",
"JSON",
".",
"parse",
"(",
"body",
",",
"reviver",
")",
"}",
"return",
"function",
"jsonParser",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"req",
".",
"_body",
")",
"{",
"debug",
"(",
"'body already parsed'",
")",
"next",
"(",
")",
"return",
"}",
"req",
".",
"body",
"=",
"req",
".",
"body",
"||",
"{",
"}",
"// skip requests without bodies",
"if",
"(",
"!",
"typeis",
".",
"hasBody",
"(",
"req",
")",
")",
"{",
"debug",
"(",
"'skip empty body'",
")",
"next",
"(",
")",
"return",
"}",
"debug",
"(",
"'content-type %j'",
",",
"req",
".",
"headers",
"[",
"'content-type'",
"]",
")",
"// determine if request should be parsed",
"if",
"(",
"!",
"shouldParse",
"(",
"req",
")",
")",
"{",
"debug",
"(",
"'skip parsing'",
")",
"next",
"(",
")",
"return",
"}",
"// assert charset per RFC 7159 sec 8.1",
"var",
"charset",
"=",
"getCharset",
"(",
"req",
")",
"||",
"'utf-8'",
"if",
"(",
"charset",
".",
"substr",
"(",
"0",
",",
"4",
")",
"!==",
"'utf-'",
")",
"{",
"debug",
"(",
"'invalid charset'",
")",
"next",
"(",
"createError",
"(",
"415",
",",
"'unsupported charset \"'",
"+",
"charset",
".",
"toUpperCase",
"(",
")",
"+",
"'\"'",
",",
"{",
"charset",
":",
"charset",
"}",
")",
")",
"return",
"}",
"// read",
"read",
"(",
"req",
",",
"res",
",",
"next",
",",
"parse",
",",
"debug",
",",
"{",
"encoding",
":",
"charset",
",",
"inflate",
":",
"inflate",
",",
"limit",
":",
"limit",
",",
"verify",
":",
"verify",
"}",
")",
"}",
"}"
]
| Create a middleware to parse JSON bodies.
@param {object} [options]
@return {function}
@public | [
"Create",
"a",
"middleware",
"to",
"parse",
"JSON",
"bodies",
"."
]
| 4b1e89208b6f34cd78ce90b8a858592115b6ccb5 | https://github.com/synder/xpress/blob/4b1e89208b6f34cd78ce90b8a858592115b6ccb5/demo/body-parser/lib/types/json.js#L50-L134 |
45,332 | Yoobic/loopback-connector-rethinkdbdash | lib/rethink.js | _hasIndex | function _hasIndex(_this, model, key) {
// Primary key always hasIndex
if(key === 'id') {
return true;
}
var modelDef = _this._models[model];
var retval = (_.isObject(modelDef.properties[key]) && modelDef.properties[key].index) || (_.isObject(modelDef.settings[key]) && modelDef.settings[key].index);
return retval;
} | javascript | function _hasIndex(_this, model, key) {
// Primary key always hasIndex
if(key === 'id') {
return true;
}
var modelDef = _this._models[model];
var retval = (_.isObject(modelDef.properties[key]) && modelDef.properties[key].index) || (_.isObject(modelDef.settings[key]) && modelDef.settings[key].index);
return retval;
} | [
"function",
"_hasIndex",
"(",
"_this",
",",
"model",
",",
"key",
")",
"{",
"// Primary key always hasIndex",
"if",
"(",
"key",
"===",
"'id'",
")",
"{",
"return",
"true",
";",
"}",
"var",
"modelDef",
"=",
"_this",
".",
"_models",
"[",
"model",
"]",
";",
"var",
"retval",
"=",
"(",
"_",
".",
"isObject",
"(",
"modelDef",
".",
"properties",
"[",
"key",
"]",
")",
"&&",
"modelDef",
".",
"properties",
"[",
"key",
"]",
".",
"index",
")",
"||",
"(",
"_",
".",
"isObject",
"(",
"modelDef",
".",
"settings",
"[",
"key",
"]",
")",
"&&",
"modelDef",
".",
"settings",
"[",
"key",
"]",
".",
"index",
")",
";",
"return",
"retval",
";",
"}"
]
| need to rewrite the function as it does not take into account a different name for the index | [
"need",
"to",
"rewrite",
"the",
"function",
"as",
"it",
"does",
"not",
"take",
"into",
"account",
"a",
"different",
"name",
"for",
"the",
"index"
]
| ac300966f8da483e014f5544cc726e12d1f8bfd9 | https://github.com/Yoobic/loopback-connector-rethinkdbdash/blob/ac300966f8da483e014f5544cc726e12d1f8bfd9/lib/rethink.js#L550-L560 |
45,333 | folkelib/folke-ko-grid | dist/index.js | register | function register() {
ko.extenders['searchArray'] = searchArrayExtension;
ko.components.register('grid', {
template: template,
viewModel: viewModel
});
} | javascript | function register() {
ko.extenders['searchArray'] = searchArrayExtension;
ko.components.register('grid', {
template: template,
viewModel: viewModel
});
} | [
"function",
"register",
"(",
")",
"{",
"ko",
".",
"extenders",
"[",
"'searchArray'",
"]",
"=",
"searchArrayExtension",
";",
"ko",
".",
"components",
".",
"register",
"(",
"'grid'",
",",
"{",
"template",
":",
"template",
",",
"viewModel",
":",
"viewModel",
"}",
")",
";",
"}"
]
| Register the extensions | [
"Register",
"the",
"extensions"
]
| 153185a15a10ab01e7f095732e970941f5d74ebc | https://github.com/folkelib/folke-ko-grid/blob/153185a15a10ab01e7f095732e970941f5d74ebc/dist/index.js#L110-L116 |
45,334 | Cellarise/gulp-async-func-runner | tasks/lib/coverageStats.js | addStats | function addStats(collection, pkg) {
var coverageType, stat;
for (coverageType in collection) {
if (collection.hasOwnProperty(coverageType)) {
for (stat in collection[coverageType]) {
if (collection[coverageType].hasOwnProperty(stat)) {
collection[coverageType][stat] = collection[coverageType][stat] +
pkg[coverageType][stat];
}
}
}
}
} | javascript | function addStats(collection, pkg) {
var coverageType, stat;
for (coverageType in collection) {
if (collection.hasOwnProperty(coverageType)) {
for (stat in collection[coverageType]) {
if (collection[coverageType].hasOwnProperty(stat)) {
collection[coverageType][stat] = collection[coverageType][stat] +
pkg[coverageType][stat];
}
}
}
}
} | [
"function",
"addStats",
"(",
"collection",
",",
"pkg",
")",
"{",
"var",
"coverageType",
",",
"stat",
";",
"for",
"(",
"coverageType",
"in",
"collection",
")",
"{",
"if",
"(",
"collection",
".",
"hasOwnProperty",
"(",
"coverageType",
")",
")",
"{",
"for",
"(",
"stat",
"in",
"collection",
"[",
"coverageType",
"]",
")",
"{",
"if",
"(",
"collection",
"[",
"coverageType",
"]",
".",
"hasOwnProperty",
"(",
"stat",
")",
")",
"{",
"collection",
"[",
"coverageType",
"]",
"[",
"stat",
"]",
"=",
"collection",
"[",
"coverageType",
"]",
"[",
"stat",
"]",
"+",
"pkg",
"[",
"coverageType",
"]",
"[",
"stat",
"]",
";",
"}",
"}",
"}",
"}",
"}"
]
| Helper function to append statistic properties from the provided collection to the provided package.json
@param {Object} collection - a collection of statistic properties
@param {Object} pkg - package.json object | [
"Helper",
"function",
"to",
"append",
"statistic",
"properties",
"from",
"the",
"provided",
"collection",
"to",
"the",
"provided",
"package",
".",
"json"
]
| 80cc072ca4b8585619f41f5b7bed20960b55f444 | https://github.com/Cellarise/gulp-async-func-runner/blob/80cc072ca4b8585619f41f5b7bed20960b55f444/tasks/lib/coverageStats.js#L17-L29 |
45,335 | Cellarise/gulp-async-func-runner | tasks/lib/coverageStats.js | deleteStats | function deleteStats(collection) {
var coverageType;
for (coverageType in collection) {
if (collection.hasOwnProperty(coverageType)) {
if (collection[coverageType].hasOwnProperty("total")) {
delete collection[coverageType].total;
}
if (collection[coverageType].hasOwnProperty("covered")) {
delete collection[coverageType].covered;
}
if (collection[coverageType].hasOwnProperty("skipped")) {
delete collection[coverageType].skipped;
}
}
}
} | javascript | function deleteStats(collection) {
var coverageType;
for (coverageType in collection) {
if (collection.hasOwnProperty(coverageType)) {
if (collection[coverageType].hasOwnProperty("total")) {
delete collection[coverageType].total;
}
if (collection[coverageType].hasOwnProperty("covered")) {
delete collection[coverageType].covered;
}
if (collection[coverageType].hasOwnProperty("skipped")) {
delete collection[coverageType].skipped;
}
}
}
} | [
"function",
"deleteStats",
"(",
"collection",
")",
"{",
"var",
"coverageType",
";",
"for",
"(",
"coverageType",
"in",
"collection",
")",
"{",
"if",
"(",
"collection",
".",
"hasOwnProperty",
"(",
"coverageType",
")",
")",
"{",
"if",
"(",
"collection",
"[",
"coverageType",
"]",
".",
"hasOwnProperty",
"(",
"\"total\"",
")",
")",
"{",
"delete",
"collection",
"[",
"coverageType",
"]",
".",
"total",
";",
"}",
"if",
"(",
"collection",
"[",
"coverageType",
"]",
".",
"hasOwnProperty",
"(",
"\"covered\"",
")",
")",
"{",
"delete",
"collection",
"[",
"coverageType",
"]",
".",
"covered",
";",
"}",
"if",
"(",
"collection",
"[",
"coverageType",
"]",
".",
"hasOwnProperty",
"(",
"\"skipped\"",
")",
")",
"{",
"delete",
"collection",
"[",
"coverageType",
"]",
".",
"skipped",
";",
"}",
"}",
"}",
"}"
]
| Helper function to delete total, covered and skipped statistic properties from a collection
@param {Object} collection - a collection of statistic properties | [
"Helper",
"function",
"to",
"delete",
"total",
"covered",
"and",
"skipped",
"statistic",
"properties",
"from",
"a",
"collection"
]
| 80cc072ca4b8585619f41f5b7bed20960b55f444 | https://github.com/Cellarise/gulp-async-func-runner/blob/80cc072ca4b8585619f41f5b7bed20960b55f444/tasks/lib/coverageStats.js#L35-L50 |
45,336 | Cellarise/gulp-async-func-runner | tasks/lib/coverageStats.js | badgeColour | function badgeColour(collection, stat, watermarks) {
var watermarkType = stat === "overall" ? "lines" : stat;
var low = watermarks[watermarkType][0];
var high = watermarks[watermarkType][1];
var mid = (high - low) / 2;
var value = collection[stat].pct;
if (value < low) {
collection[stat].colour = "red";
} else if (value < mid) {
collection[stat].colour = "orange";
} else if (value < high) {
collection[stat].colour = "yellow";
} else if (value < 100) {
collection[stat].colour = "green";
} else {
collection[stat].colour = "brightgreen";
}
} | javascript | function badgeColour(collection, stat, watermarks) {
var watermarkType = stat === "overall" ? "lines" : stat;
var low = watermarks[watermarkType][0];
var high = watermarks[watermarkType][1];
var mid = (high - low) / 2;
var value = collection[stat].pct;
if (value < low) {
collection[stat].colour = "red";
} else if (value < mid) {
collection[stat].colour = "orange";
} else if (value < high) {
collection[stat].colour = "yellow";
} else if (value < 100) {
collection[stat].colour = "green";
} else {
collection[stat].colour = "brightgreen";
}
} | [
"function",
"badgeColour",
"(",
"collection",
",",
"stat",
",",
"watermarks",
")",
"{",
"var",
"watermarkType",
"=",
"stat",
"===",
"\"overall\"",
"?",
"\"lines\"",
":",
"stat",
";",
"var",
"low",
"=",
"watermarks",
"[",
"watermarkType",
"]",
"[",
"0",
"]",
";",
"var",
"high",
"=",
"watermarks",
"[",
"watermarkType",
"]",
"[",
"1",
"]",
";",
"var",
"mid",
"=",
"(",
"high",
"-",
"low",
")",
"/",
"2",
";",
"var",
"value",
"=",
"collection",
"[",
"stat",
"]",
".",
"pct",
";",
"if",
"(",
"value",
"<",
"low",
")",
"{",
"collection",
"[",
"stat",
"]",
".",
"colour",
"=",
"\"red\"",
";",
"}",
"else",
"if",
"(",
"value",
"<",
"mid",
")",
"{",
"collection",
"[",
"stat",
"]",
".",
"colour",
"=",
"\"orange\"",
";",
"}",
"else",
"if",
"(",
"value",
"<",
"high",
")",
"{",
"collection",
"[",
"stat",
"]",
".",
"colour",
"=",
"\"yellow\"",
";",
"}",
"else",
"if",
"(",
"value",
"<",
"100",
")",
"{",
"collection",
"[",
"stat",
"]",
".",
"colour",
"=",
"\"green\"",
";",
"}",
"else",
"{",
"collection",
"[",
"stat",
"]",
".",
"colour",
"=",
"\"brightgreen\"",
";",
"}",
"}"
]
| Helper function to determine badge colour
@param {Object} collection - a collection of statistic properties
@param {Object} stat - a statistic from the collection to calculate the badge for
@param {Object} watermarks - the high and low watermarks for each statistic in collection | [
"Helper",
"function",
"to",
"determine",
"badge",
"colour"
]
| 80cc072ca4b8585619f41f5b7bed20960b55f444 | https://github.com/Cellarise/gulp-async-func-runner/blob/80cc072ca4b8585619f41f5b7bed20960b55f444/tasks/lib/coverageStats.js#L58-L75 |
45,337 | nfroidure/http-auth-utils | src/mechanisms/digest.js | computeHash | function computeHash(data) {
const ha1 =
data.ha1 ||
_computeHash(
data.algorithm,
[data.username, data.realm, data.password].join(':'),
);
const ha2 = _computeHash(data.algorithm, [data.method, data.uri].join(':'));
return _computeHash(
data.algorithm,
[ha1, data.nonce, data.nc, data.cnonce, data.qop, ha2].join(':'),
);
} | javascript | function computeHash(data) {
const ha1 =
data.ha1 ||
_computeHash(
data.algorithm,
[data.username, data.realm, data.password].join(':'),
);
const ha2 = _computeHash(data.algorithm, [data.method, data.uri].join(':'));
return _computeHash(
data.algorithm,
[ha1, data.nonce, data.nc, data.cnonce, data.qop, ha2].join(':'),
);
} | [
"function",
"computeHash",
"(",
"data",
")",
"{",
"const",
"ha1",
"=",
"data",
".",
"ha1",
"||",
"_computeHash",
"(",
"data",
".",
"algorithm",
",",
"[",
"data",
".",
"username",
",",
"data",
".",
"realm",
",",
"data",
".",
"password",
"]",
".",
"join",
"(",
"':'",
")",
",",
")",
";",
"const",
"ha2",
"=",
"_computeHash",
"(",
"data",
".",
"algorithm",
",",
"[",
"data",
".",
"method",
",",
"data",
".",
"uri",
"]",
".",
"join",
"(",
"':'",
")",
")",
";",
"return",
"_computeHash",
"(",
"data",
".",
"algorithm",
",",
"[",
"ha1",
",",
"data",
".",
"nonce",
",",
"data",
".",
"nc",
",",
"data",
".",
"cnonce",
",",
"data",
".",
"qop",
",",
"ha2",
"]",
".",
"join",
"(",
"':'",
")",
",",
")",
";",
"}"
]
| Compute the Digest authentication hash from the given credentials.
@param {Object} data The credentials to encode and other encoding details.
@return {String} The hash representing the credentials.
@example
assert.equal(
DIGEST.computeHash({
username: 'Mufasa',
realm: '[email protected]',
password: 'Circle Of Life',
method: 'GET',
uri: '/dir/index.html',
nonce: 'dcd98b7102dd2f0e8b11d0f600bfb0c093',
nc: '00000001',
cnonce: '0a4f113b',
qop: 'auth',
algorithm: 'md5'
}),
'6629fae49393a05397450978507c4ef1'
);
@api public | [
"Compute",
"the",
"Digest",
"authentication",
"hash",
"from",
"the",
"given",
"credentials",
"."
]
| 5941dcb853c1eed68fbc5d748c15a09774482cf0 | https://github.com/nfroidure/http-auth-utils/blob/5941dcb853c1eed68fbc5d748c15a09774482cf0/src/mechanisms/digest.js#L199-L212 |
45,338 | onecommons/base | routes/login.js | function(req, res) {
var url = passport.config.loginRedirect || '/profile';
var statusCode = 302; //303 is more accurate but express redirect() defaults
//to 302 so stick to that for consistency
if (req.session && req.session.returnTo) {
if (req.session.returnToMethod == req.method) {
statusCode = 307;
}
if (req.query.h && req.session.returnTo.indexOf('#') == -1) {
url = req.session.returnTo + '#' + req.query.h;
} else {
url = req.session.returnTo;
}
delete req.session.returnTo;
}
return res.redirect(statusCode, url);
} | javascript | function(req, res) {
var url = passport.config.loginRedirect || '/profile';
var statusCode = 302; //303 is more accurate but express redirect() defaults
//to 302 so stick to that for consistency
if (req.session && req.session.returnTo) {
if (req.session.returnToMethod == req.method) {
statusCode = 307;
}
if (req.query.h && req.session.returnTo.indexOf('#') == -1) {
url = req.session.returnTo + '#' + req.query.h;
} else {
url = req.session.returnTo;
}
delete req.session.returnTo;
}
return res.redirect(statusCode, url);
} | [
"function",
"(",
"req",
",",
"res",
")",
"{",
"var",
"url",
"=",
"passport",
".",
"config",
".",
"loginRedirect",
"||",
"'/profile'",
";",
"var",
"statusCode",
"=",
"302",
";",
"//303 is more accurate but express redirect() defaults",
"//to 302 so stick to that for consistency",
"if",
"(",
"req",
".",
"session",
"&&",
"req",
".",
"session",
".",
"returnTo",
")",
"{",
"if",
"(",
"req",
".",
"session",
".",
"returnToMethod",
"==",
"req",
".",
"method",
")",
"{",
"statusCode",
"=",
"307",
";",
"}",
"if",
"(",
"req",
".",
"query",
".",
"h",
"&&",
"req",
".",
"session",
".",
"returnTo",
".",
"indexOf",
"(",
"'#'",
")",
"==",
"-",
"1",
")",
"{",
"url",
"=",
"req",
".",
"session",
".",
"returnTo",
"+",
"'#'",
"+",
"req",
".",
"query",
".",
"h",
";",
"}",
"else",
"{",
"url",
"=",
"req",
".",
"session",
".",
"returnTo",
";",
"}",
"delete",
"req",
".",
"session",
".",
"returnTo",
";",
"}",
"return",
"res",
".",
"redirect",
"(",
"statusCode",
",",
"url",
")",
";",
"}"
]
| replace passport's successReturnToOrRedirect option with one that preserves the http method so that we can return to a redirected POST. | [
"replace",
"passport",
"s",
"successReturnToOrRedirect",
"option",
"with",
"one",
"that",
"preserves",
"the",
"http",
"method",
"so",
"that",
"we",
"can",
"return",
"to",
"a",
"redirected",
"POST",
"."
]
| 4f35d9f714d0367b0622a3504802363404290246 | https://github.com/onecommons/base/blob/4f35d9f714d0367b0622a3504802363404290246/routes/login.js#L31-L47 |
|
45,339 | vadr-vr/VR-Analytics-JSCore | js/logger.js | setLogLevel | function setLogLevel(level){
level = level > 0 ? level : 0;
level = level < 4 ? level : 4;
level = parseInt(level);
logLevel = level;
} | javascript | function setLogLevel(level){
level = level > 0 ? level : 0;
level = level < 4 ? level : 4;
level = parseInt(level);
logLevel = level;
} | [
"function",
"setLogLevel",
"(",
"level",
")",
"{",
"level",
"=",
"level",
">",
"0",
"?",
"level",
":",
"0",
";",
"level",
"=",
"level",
"<",
"4",
"?",
"level",
":",
"4",
";",
"level",
"=",
"parseInt",
"(",
"level",
")",
";",
"logLevel",
"=",
"level",
";",
"}"
]
| Set log level for analytics
@memberof Logger
@param {number} level Integer logLevel value between 0 and 4 | [
"Set",
"log",
"level",
"for",
"analytics"
]
| 7e4a493c824c2c1716360dcb6a3bfecfede5df3b | https://github.com/vadr-vr/VR-Analytics-JSCore/blob/7e4a493c824c2c1716360dcb6a3bfecfede5df3b/js/logger.js#L29-L37 |
45,340 | mikefrey/utml | utml.js | fromCache | function fromCache(options) {
var filename = options.filename;
if (options.cache) {
if (filename) {
if (cache[filename]) {
return cache[filename];
}
}
else {
throw new Error('filename is required when using the cache option');
}
}
return false;
} | javascript | function fromCache(options) {
var filename = options.filename;
if (options.cache) {
if (filename) {
if (cache[filename]) {
return cache[filename];
}
}
else {
throw new Error('filename is required when using the cache option');
}
}
return false;
} | [
"function",
"fromCache",
"(",
"options",
")",
"{",
"var",
"filename",
"=",
"options",
".",
"filename",
";",
"if",
"(",
"options",
".",
"cache",
")",
"{",
"if",
"(",
"filename",
")",
"{",
"if",
"(",
"cache",
"[",
"filename",
"]",
")",
"{",
"return",
"cache",
"[",
"filename",
"]",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'filename is required when using the cache option'",
")",
";",
"}",
"}",
"return",
"false",
";",
"}"
]
| Get a template from the cache
@param {object} options
@return {Function} | [
"Get",
"a",
"template",
"from",
"the",
"cache"
]
| e9f7c3da635557bc5be06383228956dddc39c280 | https://github.com/mikefrey/utml/blob/e9f7c3da635557bc5be06383228956dddc39c280/utml.js#L61-L74 |
45,341 | mikefrey/utml | utml.js | cacheTemplate | function cacheTemplate(fn, options) {
if (options.cache && options.filename) {
cache[options.filename] = fn;
}
} | javascript | function cacheTemplate(fn, options) {
if (options.cache && options.filename) {
cache[options.filename] = fn;
}
} | [
"function",
"cacheTemplate",
"(",
"fn",
",",
"options",
")",
"{",
"if",
"(",
"options",
".",
"cache",
"&&",
"options",
".",
"filename",
")",
"{",
"cache",
"[",
"options",
".",
"filename",
"]",
"=",
"fn",
";",
"}",
"}"
]
| Store the given fn in the cache
@param {Function} fn
@param {object} options | [
"Store",
"the",
"given",
"fn",
"in",
"the",
"cache"
]
| e9f7c3da635557bc5be06383228956dddc39c280 | https://github.com/mikefrey/utml/blob/e9f7c3da635557bc5be06383228956dddc39c280/utml.js#L83-L87 |
45,342 | kbarresi/calais-entity-extractor | lib/calais-entity-extractor.js | function (cb, text) {
var calais = this;
if (!calais.validateOptions())
return cb({}, 'Bad options');
if (this._undefinedOrNull(text) || typeof text != 'string' || text.length == 0)
text = this.options.content;
if (this._undefinedOrNull(text) || typeof text != 'string' || text.length == 0)
return cb({}, 'No text given in options or parameter');
var params = {
'Host' : calais.options.apiHost,
'x-ag-access-token' : calais.apiKey,
'x-calais-language' : calais.options.language,
'Content-Type' : calais.options.contentType,
'Accept' : 'application/json',
'Content-Length' : text.length,
'OutputFormat' : 'application/json'
}
var options = {
uri : 'https://' + calais.options.apiHost + calais.options.apiPath,
method : 'POST',
body : text,
headers: params
};
//Send the response
request(options, function (error, response, calaisData) {
if (error)
return cb({}, error);
if (response === undefined) {
return cb({}, 'Undefined Calais response');
} else if (response.statusCode === 200) {
if (!calaisData)
return cb({}, calais.errors);
try {
// parse to a Javascript object if requested
var result = JSON.parse(calaisData);
result = (typeof result === 'string') ? JSON.parse(result) : result;
var parsedResult;
if (calais.options.parseData) {
parsedResult = calais._parseCalaisData(result, calais.options.minConfidence);
} else {
parsedResult = result;
}
return cb(parsedResult, calais.errors);
} catch(e) {
return cb({}, e);
}
} else
return cb({}, 'Request error: ' + (typeof response === 'string' ? response : JSON.stringify(response)));
});
} | javascript | function (cb, text) {
var calais = this;
if (!calais.validateOptions())
return cb({}, 'Bad options');
if (this._undefinedOrNull(text) || typeof text != 'string' || text.length == 0)
text = this.options.content;
if (this._undefinedOrNull(text) || typeof text != 'string' || text.length == 0)
return cb({}, 'No text given in options or parameter');
var params = {
'Host' : calais.options.apiHost,
'x-ag-access-token' : calais.apiKey,
'x-calais-language' : calais.options.language,
'Content-Type' : calais.options.contentType,
'Accept' : 'application/json',
'Content-Length' : text.length,
'OutputFormat' : 'application/json'
}
var options = {
uri : 'https://' + calais.options.apiHost + calais.options.apiPath,
method : 'POST',
body : text,
headers: params
};
//Send the response
request(options, function (error, response, calaisData) {
if (error)
return cb({}, error);
if (response === undefined) {
return cb({}, 'Undefined Calais response');
} else if (response.statusCode === 200) {
if (!calaisData)
return cb({}, calais.errors);
try {
// parse to a Javascript object if requested
var result = JSON.parse(calaisData);
result = (typeof result === 'string') ? JSON.parse(result) : result;
var parsedResult;
if (calais.options.parseData) {
parsedResult = calais._parseCalaisData(result, calais.options.minConfidence);
} else {
parsedResult = result;
}
return cb(parsedResult, calais.errors);
} catch(e) {
return cb({}, e);
}
} else
return cb({}, 'Request error: ' + (typeof response === 'string' ? response : JSON.stringify(response)));
});
} | [
"function",
"(",
"cb",
",",
"text",
")",
"{",
"var",
"calais",
"=",
"this",
";",
"if",
"(",
"!",
"calais",
".",
"validateOptions",
"(",
")",
")",
"return",
"cb",
"(",
"{",
"}",
",",
"'Bad options'",
")",
";",
"if",
"(",
"this",
".",
"_undefinedOrNull",
"(",
"text",
")",
"||",
"typeof",
"text",
"!=",
"'string'",
"||",
"text",
".",
"length",
"==",
"0",
")",
"text",
"=",
"this",
".",
"options",
".",
"content",
";",
"if",
"(",
"this",
".",
"_undefinedOrNull",
"(",
"text",
")",
"||",
"typeof",
"text",
"!=",
"'string'",
"||",
"text",
".",
"length",
"==",
"0",
")",
"return",
"cb",
"(",
"{",
"}",
",",
"'No text given in options or parameter'",
")",
";",
"var",
"params",
"=",
"{",
"'Host'",
":",
"calais",
".",
"options",
".",
"apiHost",
",",
"'x-ag-access-token'",
":",
"calais",
".",
"apiKey",
",",
"'x-calais-language'",
":",
"calais",
".",
"options",
".",
"language",
",",
"'Content-Type'",
":",
"calais",
".",
"options",
".",
"contentType",
",",
"'Accept'",
":",
"'application/json'",
",",
"'Content-Length'",
":",
"text",
".",
"length",
",",
"'OutputFormat'",
":",
"'application/json'",
"}",
"var",
"options",
"=",
"{",
"uri",
":",
"'https://'",
"+",
"calais",
".",
"options",
".",
"apiHost",
"+",
"calais",
".",
"options",
".",
"apiPath",
",",
"method",
":",
"'POST'",
",",
"body",
":",
"text",
",",
"headers",
":",
"params",
"}",
";",
"//Send the response",
"request",
"(",
"options",
",",
"function",
"(",
"error",
",",
"response",
",",
"calaisData",
")",
"{",
"if",
"(",
"error",
")",
"return",
"cb",
"(",
"{",
"}",
",",
"error",
")",
";",
"if",
"(",
"response",
"===",
"undefined",
")",
"{",
"return",
"cb",
"(",
"{",
"}",
",",
"'Undefined Calais response'",
")",
";",
"}",
"else",
"if",
"(",
"response",
".",
"statusCode",
"===",
"200",
")",
"{",
"if",
"(",
"!",
"calaisData",
")",
"return",
"cb",
"(",
"{",
"}",
",",
"calais",
".",
"errors",
")",
";",
"try",
"{",
"// parse to a Javascript object if requested",
"var",
"result",
"=",
"JSON",
".",
"parse",
"(",
"calaisData",
")",
";",
"result",
"=",
"(",
"typeof",
"result",
"===",
"'string'",
")",
"?",
"JSON",
".",
"parse",
"(",
"result",
")",
":",
"result",
";",
"var",
"parsedResult",
";",
"if",
"(",
"calais",
".",
"options",
".",
"parseData",
")",
"{",
"parsedResult",
"=",
"calais",
".",
"_parseCalaisData",
"(",
"result",
",",
"calais",
".",
"options",
".",
"minConfidence",
")",
";",
"}",
"else",
"{",
"parsedResult",
"=",
"result",
";",
"}",
"return",
"cb",
"(",
"parsedResult",
",",
"calais",
".",
"errors",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"cb",
"(",
"{",
"}",
",",
"e",
")",
";",
"}",
"}",
"else",
"return",
"cb",
"(",
"{",
"}",
",",
"'Request error: '",
"+",
"(",
"typeof",
"response",
"===",
"'string'",
"?",
"response",
":",
"JSON",
".",
"stringify",
"(",
"response",
")",
")",
")",
";",
"}",
")",
";",
"}"
]
| Perform the analysis request with Calais. If no |text| is given or |text| is empty,
then we fall back to the set options.content value. If that is also empty, an error is
returned.
@param cb Callback function of form function(resultData, error);
@param text Optional, the text to perform extraction on. If not set, the options.content
value is used.
@returns nothing | [
"Perform",
"the",
"analysis",
"request",
"with",
"Calais",
".",
"If",
"no",
"|text|",
"is",
"given",
"or",
"|text|",
"is",
"empty",
"then",
"we",
"fall",
"back",
"to",
"the",
"set",
"options",
".",
"content",
"value",
".",
"If",
"that",
"is",
"also",
"empty",
"an",
"error",
"is",
"returned",
"."
]
| 5f32b956a664ae745d4ec84717479f99b9d6dbe2 | https://github.com/kbarresi/calais-entity-extractor/blob/5f32b956a664ae745d4ec84717479f99b9d6dbe2/lib/calais-entity-extractor.js#L324-L386 |
|
45,343 | kbarresi/calais-entity-extractor | lib/calais-entity-extractor.js | function(url, cb) {
var calais = this;
if (!calais.validateOptions())
return cb({}, 'Bad options');
//Make sure we were given a URL.
if (this._undefinedOrNull(url) || typeof url != 'string' || url.length == 0)
return cb({}, 'No URL given.');
//Make sure it's a valid URL.
if (!(/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(url)))
return cb({}, 'Bad URL');
request(url, function(error, response, html) {
if (error)
return cb({}, error);
//Limts to just under 100kb....
html = html.substring(0, 95000);
//We can upload the html directly to Calais if we set the contentType as text/html
var params = {
'Host' : calais.options.apiHost,
'x-ag-access-token' : calais.apiKey,
'x-calais-language' : calais.options.language,
'Content-Type' : 'text/html',
'Accept' : 'application/json',
'Content-Length' : html.length,
'OutputFormat' : 'application/json'
};
var options = {
uri : 'https://' + calais.options.apiHost + calais.options.apiPath,
method : 'POST',
body : html,
headers: params
};
request(options, function(error, response, calaisData) {
if (error)
return cb({}, error);
if (response === undefined) {
return cb({}, 'Undefined Calais response');
} else if (response.statusCode === 200) {
if (!calaisData)
return cb({}, calais.errors);
try {
// parse to a Javascript object if requested
var result = JSON.parse(calaisData);
result = (typeof result === 'string') ? JSON.parse(result) : result;
var parsedResult;
if (calais.options.parseData) {
parsedResult = calais._parseCalaisData(result, calais.options.minConfidence);
} else {
parsedResult = result;
}
return cb(parsedResult, calais.errors);
} catch(e) {
return cb({}, e);
}
} else
return cb({}, 'Request error: ' + (typeof response === 'string' ? response : JSON.stringify(response)));
});
});
} | javascript | function(url, cb) {
var calais = this;
if (!calais.validateOptions())
return cb({}, 'Bad options');
//Make sure we were given a URL.
if (this._undefinedOrNull(url) || typeof url != 'string' || url.length == 0)
return cb({}, 'No URL given.');
//Make sure it's a valid URL.
if (!(/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(url)))
return cb({}, 'Bad URL');
request(url, function(error, response, html) {
if (error)
return cb({}, error);
//Limts to just under 100kb....
html = html.substring(0, 95000);
//We can upload the html directly to Calais if we set the contentType as text/html
var params = {
'Host' : calais.options.apiHost,
'x-ag-access-token' : calais.apiKey,
'x-calais-language' : calais.options.language,
'Content-Type' : 'text/html',
'Accept' : 'application/json',
'Content-Length' : html.length,
'OutputFormat' : 'application/json'
};
var options = {
uri : 'https://' + calais.options.apiHost + calais.options.apiPath,
method : 'POST',
body : html,
headers: params
};
request(options, function(error, response, calaisData) {
if (error)
return cb({}, error);
if (response === undefined) {
return cb({}, 'Undefined Calais response');
} else if (response.statusCode === 200) {
if (!calaisData)
return cb({}, calais.errors);
try {
// parse to a Javascript object if requested
var result = JSON.parse(calaisData);
result = (typeof result === 'string') ? JSON.parse(result) : result;
var parsedResult;
if (calais.options.parseData) {
parsedResult = calais._parseCalaisData(result, calais.options.minConfidence);
} else {
parsedResult = result;
}
return cb(parsedResult, calais.errors);
} catch(e) {
return cb({}, e);
}
} else
return cb({}, 'Request error: ' + (typeof response === 'string' ? response : JSON.stringify(response)));
});
});
} | [
"function",
"(",
"url",
",",
"cb",
")",
"{",
"var",
"calais",
"=",
"this",
";",
"if",
"(",
"!",
"calais",
".",
"validateOptions",
"(",
")",
")",
"return",
"cb",
"(",
"{",
"}",
",",
"'Bad options'",
")",
";",
"//Make sure we were given a URL.",
"if",
"(",
"this",
".",
"_undefinedOrNull",
"(",
"url",
")",
"||",
"typeof",
"url",
"!=",
"'string'",
"||",
"url",
".",
"length",
"==",
"0",
")",
"return",
"cb",
"(",
"{",
"}",
",",
"'No URL given.'",
")",
";",
"//Make sure it's a valid URL.",
"if",
"(",
"!",
"(",
"/",
"^(https?|ftp):\\/\\/(((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:)*@)?(((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]))|((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?)(:\\d*)?)(\\/((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:|@)+(\\/(([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:|@)*)*)?)?(\\?((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:|@)|[\\uE000-\\uF8FF]|\\/|\\?)*)?(\\#((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:|@)|\\/|\\?)*)?$",
"/",
"i",
".",
"test",
"(",
"url",
")",
")",
")",
"return",
"cb",
"(",
"{",
"}",
",",
"'Bad URL'",
")",
";",
"request",
"(",
"url",
",",
"function",
"(",
"error",
",",
"response",
",",
"html",
")",
"{",
"if",
"(",
"error",
")",
"return",
"cb",
"(",
"{",
"}",
",",
"error",
")",
";",
"//Limts to just under 100kb....",
"html",
"=",
"html",
".",
"substring",
"(",
"0",
",",
"95000",
")",
";",
"//We can upload the html directly to Calais if we set the contentType as text/html",
"var",
"params",
"=",
"{",
"'Host'",
":",
"calais",
".",
"options",
".",
"apiHost",
",",
"'x-ag-access-token'",
":",
"calais",
".",
"apiKey",
",",
"'x-calais-language'",
":",
"calais",
".",
"options",
".",
"language",
",",
"'Content-Type'",
":",
"'text/html'",
",",
"'Accept'",
":",
"'application/json'",
",",
"'Content-Length'",
":",
"html",
".",
"length",
",",
"'OutputFormat'",
":",
"'application/json'",
"}",
";",
"var",
"options",
"=",
"{",
"uri",
":",
"'https://'",
"+",
"calais",
".",
"options",
".",
"apiHost",
"+",
"calais",
".",
"options",
".",
"apiPath",
",",
"method",
":",
"'POST'",
",",
"body",
":",
"html",
",",
"headers",
":",
"params",
"}",
";",
"request",
"(",
"options",
",",
"function",
"(",
"error",
",",
"response",
",",
"calaisData",
")",
"{",
"if",
"(",
"error",
")",
"return",
"cb",
"(",
"{",
"}",
",",
"error",
")",
";",
"if",
"(",
"response",
"===",
"undefined",
")",
"{",
"return",
"cb",
"(",
"{",
"}",
",",
"'Undefined Calais response'",
")",
";",
"}",
"else",
"if",
"(",
"response",
".",
"statusCode",
"===",
"200",
")",
"{",
"if",
"(",
"!",
"calaisData",
")",
"return",
"cb",
"(",
"{",
"}",
",",
"calais",
".",
"errors",
")",
";",
"try",
"{",
"// parse to a Javascript object if requested",
"var",
"result",
"=",
"JSON",
".",
"parse",
"(",
"calaisData",
")",
";",
"result",
"=",
"(",
"typeof",
"result",
"===",
"'string'",
")",
"?",
"JSON",
".",
"parse",
"(",
"result",
")",
":",
"result",
";",
"var",
"parsedResult",
";",
"if",
"(",
"calais",
".",
"options",
".",
"parseData",
")",
"{",
"parsedResult",
"=",
"calais",
".",
"_parseCalaisData",
"(",
"result",
",",
"calais",
".",
"options",
".",
"minConfidence",
")",
";",
"}",
"else",
"{",
"parsedResult",
"=",
"result",
";",
"}",
"return",
"cb",
"(",
"parsedResult",
",",
"calais",
".",
"errors",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"cb",
"(",
"{",
"}",
",",
"e",
")",
";",
"}",
"}",
"else",
"return",
"cb",
"(",
"{",
"}",
",",
"'Request error: '",
"+",
"(",
"typeof",
"response",
"===",
"'string'",
"?",
"response",
":",
"JSON",
".",
"stringify",
"(",
"response",
")",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Extract tags and entities from a given URL. We download the HTML from the URL, and submit
that to Calais using the extractFromText function
@param url The URL to analyze.
@param cb The callback function, of form function(result, error) | [
"Extract",
"tags",
"and",
"entities",
"from",
"a",
"given",
"URL",
".",
"We",
"download",
"the",
"HTML",
"from",
"the",
"URL",
"and",
"submit",
"that",
"to",
"Calais",
"using",
"the",
"extractFromText",
"function"
]
| 5f32b956a664ae745d4ec84717479f99b9d6dbe2 | https://github.com/kbarresi/calais-entity-extractor/blob/5f32b956a664ae745d4ec84717479f99b9d6dbe2/lib/calais-entity-extractor.js#L395-L472 |
|
45,344 | KAIT-HEMS/node-picogw-plugin-admin | ipv4.js | convToNum | function convToNum(ipstr) {
let ret = 0;
let mul = 256*256*256;
ipstr.split('.').forEach((numstr)=>{
ret += parseInt(numstr)*mul;
mul >>= 8;
});
return ret;
} | javascript | function convToNum(ipstr) {
let ret = 0;
let mul = 256*256*256;
ipstr.split('.').forEach((numstr)=>{
ret += parseInt(numstr)*mul;
mul >>= 8;
});
return ret;
} | [
"function",
"convToNum",
"(",
"ipstr",
")",
"{",
"let",
"ret",
"=",
"0",
";",
"let",
"mul",
"=",
"256",
"*",
"256",
"*",
"256",
";",
"ipstr",
".",
"split",
"(",
"'.'",
")",
".",
"forEach",
"(",
"(",
"numstr",
")",
"=>",
"{",
"ret",
"+=",
"parseInt",
"(",
"numstr",
")",
"*",
"mul",
";",
"mul",
">>=",
"8",
";",
"}",
")",
";",
"return",
"ret",
";",
"}"
]
| Convert to number value from string IP address
@param {string} ipstr : string IP address
@return {number} number value of IP address | [
"Convert",
"to",
"number",
"value",
"from",
"string",
"IP",
"address"
]
| 8c7ec31271b164eb90e12444388234a40cb470be | https://github.com/KAIT-HEMS/node-picogw-plugin-admin/blob/8c7ec31271b164eb90e12444388234a40cb470be/ipv4.js#L147-L155 |
45,345 | KAIT-HEMS/node-picogw-plugin-admin | ipv4.js | startCheckingArpTable | function startCheckingArpTable() {
setInterval(()=>{
chkArpTable();
for (const macinfo of Object.values(macs)) {
pingNet(macinfo.net, macinfo.ip);
}
}, CHECK_ARP_TABLE_AND_PING_INTERVAL);
// Initial check
chkArpTable();
} | javascript | function startCheckingArpTable() {
setInterval(()=>{
chkArpTable();
for (const macinfo of Object.values(macs)) {
pingNet(macinfo.net, macinfo.ip);
}
}, CHECK_ARP_TABLE_AND_PING_INTERVAL);
// Initial check
chkArpTable();
} | [
"function",
"startCheckingArpTable",
"(",
")",
"{",
"setInterval",
"(",
"(",
")",
"=>",
"{",
"chkArpTable",
"(",
")",
";",
"for",
"(",
"const",
"macinfo",
"of",
"Object",
".",
"values",
"(",
"macs",
")",
")",
"{",
"pingNet",
"(",
"macinfo",
".",
"net",
",",
"macinfo",
".",
"ip",
")",
";",
"}",
"}",
",",
"CHECK_ARP_TABLE_AND_PING_INTERVAL",
")",
";",
"// Initial check",
"chkArpTable",
"(",
")",
";",
"}"
]
| Start checking the arp table | [
"Start",
"checking",
"the",
"arp",
"table"
]
| 8c7ec31271b164eb90e12444388234a40cb470be | https://github.com/KAIT-HEMS/node-picogw-plugin-admin/blob/8c7ec31271b164eb90e12444388234a40cb470be/ipv4.js#L284-L293 |
45,346 | KAIT-HEMS/node-picogw-plugin-admin | ipv4.js | getNetworkInterfaces | function getNetworkInterfaces() {
const ret = {};
for (const macinfo of Object.values(macs)) {
if (!macinfo.self) {
continue;
}
ret[macinfo.net] = objCpy(macinfo);
}
return ret;
} | javascript | function getNetworkInterfaces() {
const ret = {};
for (const macinfo of Object.values(macs)) {
if (!macinfo.self) {
continue;
}
ret[macinfo.net] = objCpy(macinfo);
}
return ret;
} | [
"function",
"getNetworkInterfaces",
"(",
")",
"{",
"const",
"ret",
"=",
"{",
"}",
";",
"for",
"(",
"const",
"macinfo",
"of",
"Object",
".",
"values",
"(",
"macs",
")",
")",
"{",
"if",
"(",
"!",
"macinfo",
".",
"self",
")",
"{",
"continue",
";",
"}",
"ret",
"[",
"macinfo",
".",
"net",
"]",
"=",
"objCpy",
"(",
"macinfo",
")",
";",
"}",
"return",
"ret",
";",
"}"
]
| Return the network list for each interface
@return {object} network list | [
"Return",
"the",
"network",
"list",
"for",
"each",
"interface"
]
| 8c7ec31271b164eb90e12444388234a40cb470be | https://github.com/KAIT-HEMS/node-picogw-plugin-admin/blob/8c7ec31271b164eb90e12444388234a40cb470be/ipv4.js#L301-L310 |
45,347 | KAIT-HEMS/node-picogw-plugin-admin | ipv4.js | searchNetworkInterface | function searchNetworkInterface(ip, networks) {
networks = networks || getNetworkInterfaces();
for (const [net, netinfo] of Object.entries(networks)) {
const ipnet = netinfo.ip;
const mask = netinfo.netmask;
if (isNetworkSame(mask, ip, ipnet)) {
return net;
}
}
return null;
} | javascript | function searchNetworkInterface(ip, networks) {
networks = networks || getNetworkInterfaces();
for (const [net, netinfo] of Object.entries(networks)) {
const ipnet = netinfo.ip;
const mask = netinfo.netmask;
if (isNetworkSame(mask, ip, ipnet)) {
return net;
}
}
return null;
} | [
"function",
"searchNetworkInterface",
"(",
"ip",
",",
"networks",
")",
"{",
"networks",
"=",
"networks",
"||",
"getNetworkInterfaces",
"(",
")",
";",
"for",
"(",
"const",
"[",
"net",
",",
"netinfo",
"]",
"of",
"Object",
".",
"entries",
"(",
"networks",
")",
")",
"{",
"const",
"ipnet",
"=",
"netinfo",
".",
"ip",
";",
"const",
"mask",
"=",
"netinfo",
".",
"netmask",
";",
"if",
"(",
"isNetworkSame",
"(",
"mask",
",",
"ip",
",",
"ipnet",
")",
")",
"{",
"return",
"net",
";",
"}",
"}",
"return",
"null",
";",
"}"
]
| Look for the network interface from the IP address
@param {string} ip : IP address
@param {object} [networks] : List of my network interfaces. This is the same as getNetworks () 's return value.
@return {string} network interface. e.g. 'eth0' or 'wlan0' | [
"Look",
"for",
"the",
"network",
"interface",
"from",
"the",
"IP",
"address"
]
| 8c7ec31271b164eb90e12444388234a40cb470be | https://github.com/KAIT-HEMS/node-picogw-plugin-admin/blob/8c7ec31271b164eb90e12444388234a40cb470be/ipv4.js#L320-L330 |
45,348 | johnpaulvaughan/itunes-music-library-tracks | index.js | getItunesTracks | function getItunesTracks(librarypath) {
var libraryID;
var trackObj = {};
var isTrack = false;
var line;
var trackCount = 0;
var streamIn;
var streamOut = new stream_1.Readable;
streamOut._read = function () { };
streamIn = fs.createReadStream(librarypath);
streamIn.on('error', function () { return streamOut.emit("error", 'The file you selected does not exist'); });
streamIn = byline.createStream(streamIn);
/*
if (!module.exports.validPath(librarypath)) {
streamOut.emit("error", 'Not a valid XML file')
}
*/
streamIn.on('readable', function () {
while (null !== (line = streamIn.read())) {
if (line.indexOf("<key>Library Persistent ID</key>") > -1) {
/* ADD A KEY/VALUE PROPERTY */
var iDString = String(line).match("<key>Library Persistent ID</key><string>(.*)</string>");
libraryID = iDString[1];
}
else if (line.indexOf("<dict>") > -1) {
/* START A NEW TRACK */
trackObj = {};
isTrack = true;
}
else if (line.indexOf("<key>") > -1) {
/* ADD A PROPERTY TO THE TRACK */
Object.assign(trackObj, module.exports.buildProperty(line));
}
else if (line.indexOf("</dict>") > -1) {
/* END OF CURRENT TRACK */
if (module.exports.objectIsMusicTrack(trackObj)) {
trackObj['Library Persistent ID'] = libraryID; //add extra metadata
trackCount++;
streamOut.push(JSON.stringify(trackObj));
}
isTrack = false;
}
}
});
streamIn.on('end', function () {
if (trackCount == 0)
streamOut.emit("error", 'No tracks exist in the file');
trackCount = 0; //reset it
streamOut.push(null);
});
streamIn.on('error', function (err) {
streamOut.emit("error", 'Error parsing iTunes XML');
});
return streamOut;
} | javascript | function getItunesTracks(librarypath) {
var libraryID;
var trackObj = {};
var isTrack = false;
var line;
var trackCount = 0;
var streamIn;
var streamOut = new stream_1.Readable;
streamOut._read = function () { };
streamIn = fs.createReadStream(librarypath);
streamIn.on('error', function () { return streamOut.emit("error", 'The file you selected does not exist'); });
streamIn = byline.createStream(streamIn);
/*
if (!module.exports.validPath(librarypath)) {
streamOut.emit("error", 'Not a valid XML file')
}
*/
streamIn.on('readable', function () {
while (null !== (line = streamIn.read())) {
if (line.indexOf("<key>Library Persistent ID</key>") > -1) {
/* ADD A KEY/VALUE PROPERTY */
var iDString = String(line).match("<key>Library Persistent ID</key><string>(.*)</string>");
libraryID = iDString[1];
}
else if (line.indexOf("<dict>") > -1) {
/* START A NEW TRACK */
trackObj = {};
isTrack = true;
}
else if (line.indexOf("<key>") > -1) {
/* ADD A PROPERTY TO THE TRACK */
Object.assign(trackObj, module.exports.buildProperty(line));
}
else if (line.indexOf("</dict>") > -1) {
/* END OF CURRENT TRACK */
if (module.exports.objectIsMusicTrack(trackObj)) {
trackObj['Library Persistent ID'] = libraryID; //add extra metadata
trackCount++;
streamOut.push(JSON.stringify(trackObj));
}
isTrack = false;
}
}
});
streamIn.on('end', function () {
if (trackCount == 0)
streamOut.emit("error", 'No tracks exist in the file');
trackCount = 0; //reset it
streamOut.push(null);
});
streamIn.on('error', function (err) {
streamOut.emit("error", 'Error parsing iTunes XML');
});
return streamOut;
} | [
"function",
"getItunesTracks",
"(",
"librarypath",
")",
"{",
"var",
"libraryID",
";",
"var",
"trackObj",
"=",
"{",
"}",
";",
"var",
"isTrack",
"=",
"false",
";",
"var",
"line",
";",
"var",
"trackCount",
"=",
"0",
";",
"var",
"streamIn",
";",
"var",
"streamOut",
"=",
"new",
"stream_1",
".",
"Readable",
";",
"streamOut",
".",
"_read",
"=",
"function",
"(",
")",
"{",
"}",
";",
"streamIn",
"=",
"fs",
".",
"createReadStream",
"(",
"librarypath",
")",
";",
"streamIn",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
")",
"{",
"return",
"streamOut",
".",
"emit",
"(",
"\"error\"",
",",
"'The file you selected does not exist'",
")",
";",
"}",
")",
";",
"streamIn",
"=",
"byline",
".",
"createStream",
"(",
"streamIn",
")",
";",
"/*\n if (!module.exports.validPath(librarypath)) {\n streamOut.emit(\"error\", 'Not a valid XML file')\n }\n */",
"streamIn",
".",
"on",
"(",
"'readable'",
",",
"function",
"(",
")",
"{",
"while",
"(",
"null",
"!==",
"(",
"line",
"=",
"streamIn",
".",
"read",
"(",
")",
")",
")",
"{",
"if",
"(",
"line",
".",
"indexOf",
"(",
"\"<key>Library Persistent ID</key>\"",
")",
">",
"-",
"1",
")",
"{",
"/* ADD A KEY/VALUE PROPERTY */",
"var",
"iDString",
"=",
"String",
"(",
"line",
")",
".",
"match",
"(",
"\"<key>Library Persistent ID</key><string>(.*)</string>\"",
")",
";",
"libraryID",
"=",
"iDString",
"[",
"1",
"]",
";",
"}",
"else",
"if",
"(",
"line",
".",
"indexOf",
"(",
"\"<dict>\"",
")",
">",
"-",
"1",
")",
"{",
"/* START A NEW TRACK */",
"trackObj",
"=",
"{",
"}",
";",
"isTrack",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"line",
".",
"indexOf",
"(",
"\"<key>\"",
")",
">",
"-",
"1",
")",
"{",
"/* ADD A PROPERTY TO THE TRACK */",
"Object",
".",
"assign",
"(",
"trackObj",
",",
"module",
".",
"exports",
".",
"buildProperty",
"(",
"line",
")",
")",
";",
"}",
"else",
"if",
"(",
"line",
".",
"indexOf",
"(",
"\"</dict>\"",
")",
">",
"-",
"1",
")",
"{",
"/* END OF CURRENT TRACK */",
"if",
"(",
"module",
".",
"exports",
".",
"objectIsMusicTrack",
"(",
"trackObj",
")",
")",
"{",
"trackObj",
"[",
"'Library Persistent ID'",
"]",
"=",
"libraryID",
";",
"//add extra metadata",
"trackCount",
"++",
";",
"streamOut",
".",
"push",
"(",
"JSON",
".",
"stringify",
"(",
"trackObj",
")",
")",
";",
"}",
"isTrack",
"=",
"false",
";",
"}",
"}",
"}",
")",
";",
"streamIn",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"trackCount",
"==",
"0",
")",
"streamOut",
".",
"emit",
"(",
"\"error\"",
",",
"'No tracks exist in the file'",
")",
";",
"trackCount",
"=",
"0",
";",
"//reset it",
"streamOut",
".",
"push",
"(",
"null",
")",
";",
"}",
")",
";",
"streamIn",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"streamOut",
".",
"emit",
"(",
"\"error\"",
",",
"'Error parsing iTunes XML'",
")",
";",
"}",
")",
";",
"return",
"streamOut",
";",
"}"
]
| Creates an stream of JSON tracks from an iTunes Library XML file.
@param String
@return ReadableStream of JSON objects | [
"Creates",
"an",
"stream",
"of",
"JSON",
"tracks",
"from",
"an",
"iTunes",
"Library",
"XML",
"file",
"."
]
| c96dd579bc6b225d6d8c1d4c2d4f0c25d5dff4a2 | https://github.com/johnpaulvaughan/itunes-music-library-tracks/blob/c96dd579bc6b225d6d8c1d4c2d4f0c25d5dff4a2/index.js#L12-L66 |
45,349 | johnpaulvaughan/itunes-music-library-tracks | index.js | objectIsMusicTrack | function objectIsMusicTrack(obj) {
if ((obj.Name || obj.Artist)
&& !obj['Playlist ID']
&& (obj.Kind ==
('MPEG audio file'
|| 'AAC audio file'
|| 'Matched AAC audio file'
|| 'Protected AAC audio file'
|| 'Purchased AAC audio file')))
return true;
else
return false;
} | javascript | function objectIsMusicTrack(obj) {
if ((obj.Name || obj.Artist)
&& !obj['Playlist ID']
&& (obj.Kind ==
('MPEG audio file'
|| 'AAC audio file'
|| 'Matched AAC audio file'
|| 'Protected AAC audio file'
|| 'Purchased AAC audio file')))
return true;
else
return false;
} | [
"function",
"objectIsMusicTrack",
"(",
"obj",
")",
"{",
"if",
"(",
"(",
"obj",
".",
"Name",
"||",
"obj",
".",
"Artist",
")",
"&&",
"!",
"obj",
"[",
"'Playlist ID'",
"]",
"&&",
"(",
"obj",
".",
"Kind",
"==",
"(",
"'MPEG audio file'",
"||",
"'AAC audio file'",
"||",
"'Matched AAC audio file'",
"||",
"'Protected AAC audio file'",
"||",
"'Purchased AAC audio file'",
")",
")",
")",
"return",
"true",
";",
"else",
"return",
"false",
";",
"}"
]
| Ensures we have a music track and not a video or other non-music item.
@param Object
@return Boolean | [
"Ensures",
"we",
"have",
"a",
"music",
"track",
"and",
"not",
"a",
"video",
"or",
"other",
"non",
"-",
"music",
"item",
"."
]
| c96dd579bc6b225d6d8c1d4c2d4f0c25d5dff4a2 | https://github.com/johnpaulvaughan/itunes-music-library-tracks/blob/c96dd579bc6b225d6d8c1d4c2d4f0c25d5dff4a2/index.js#L87-L99 |
45,350 | godmodelabs/flora-errors | index.js | format | function format(err, options) {
const error = { message: 'Internal Server Error' };
options = options || {};
if (options.exposeErrors || (err.httpStatusCode && err.httpStatusCode < 500)) {
error.message = err.message;
if (err.code) error.code = err.code;
if (err.validation) error.validation = err.validation;
}
if (options.exposeErrors) {
if (err.stack) error.stack = err.stack.split(/\r?\n/);
if (err.info) {
Object.keys(err.info).forEach(key => {
if (!has(error, key) && has(err.info, key)) error[key] = err.info[key];
});
}
}
return error;
} | javascript | function format(err, options) {
const error = { message: 'Internal Server Error' };
options = options || {};
if (options.exposeErrors || (err.httpStatusCode && err.httpStatusCode < 500)) {
error.message = err.message;
if (err.code) error.code = err.code;
if (err.validation) error.validation = err.validation;
}
if (options.exposeErrors) {
if (err.stack) error.stack = err.stack.split(/\r?\n/);
if (err.info) {
Object.keys(err.info).forEach(key => {
if (!has(error, key) && has(err.info, key)) error[key] = err.info[key];
});
}
}
return error;
} | [
"function",
"format",
"(",
"err",
",",
"options",
")",
"{",
"const",
"error",
"=",
"{",
"message",
":",
"'Internal Server Error'",
"}",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"if",
"(",
"options",
".",
"exposeErrors",
"||",
"(",
"err",
".",
"httpStatusCode",
"&&",
"err",
".",
"httpStatusCode",
"<",
"500",
")",
")",
"{",
"error",
".",
"message",
"=",
"err",
".",
"message",
";",
"if",
"(",
"err",
".",
"code",
")",
"error",
".",
"code",
"=",
"err",
".",
"code",
";",
"if",
"(",
"err",
".",
"validation",
")",
"error",
".",
"validation",
"=",
"err",
".",
"validation",
";",
"}",
"if",
"(",
"options",
".",
"exposeErrors",
")",
"{",
"if",
"(",
"err",
".",
"stack",
")",
"error",
".",
"stack",
"=",
"err",
".",
"stack",
".",
"split",
"(",
"/",
"\\r?\\n",
"/",
")",
";",
"if",
"(",
"err",
".",
"info",
")",
"{",
"Object",
".",
"keys",
"(",
"err",
".",
"info",
")",
".",
"forEach",
"(",
"key",
"=>",
"{",
"if",
"(",
"!",
"has",
"(",
"error",
",",
"key",
")",
"&&",
"has",
"(",
"err",
".",
"info",
",",
"key",
")",
")",
"error",
"[",
"key",
"]",
"=",
"err",
".",
"info",
"[",
"key",
"]",
";",
"}",
")",
";",
"}",
"}",
"return",
"error",
";",
"}"
]
| Converts an error object to a stringifyable object format for use
in Flora responses.
@param {FloraError} err object
@param {Object=} options | [
"Converts",
"an",
"error",
"object",
"to",
"a",
"stringifyable",
"object",
"format",
"for",
"use",
"in",
"Flora",
"responses",
"."
]
| 87235f2fac83a550d2e6a134f2bc311807dc4197 | https://github.com/godmodelabs/flora-errors/blob/87235f2fac83a550d2e6a134f2bc311807dc4197/index.js#L100-L122 |
45,351 | RainBirdAi/rainbird-linter | lib/filesets.js | validateFileset | function validateFileset(fileset, setter) {
if (Array.isArray(fileset)) {
async.each(fileset, function(path, callback) {
if (typeof path === 'string') {
callback();
} else {
callback(util.format('Invalid path: %s', path));
}
}, function(err) {
if (err) {
console.log(chalk.red(err));
} else {
setter(fileset);
}
});
} else {
console.log(chalk.red('Fileset is not an array: %j'), fileset);
}
} | javascript | function validateFileset(fileset, setter) {
if (Array.isArray(fileset)) {
async.each(fileset, function(path, callback) {
if (typeof path === 'string') {
callback();
} else {
callback(util.format('Invalid path: %s', path));
}
}, function(err) {
if (err) {
console.log(chalk.red(err));
} else {
setter(fileset);
}
});
} else {
console.log(chalk.red('Fileset is not an array: %j'), fileset);
}
} | [
"function",
"validateFileset",
"(",
"fileset",
",",
"setter",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"fileset",
")",
")",
"{",
"async",
".",
"each",
"(",
"fileset",
",",
"function",
"(",
"path",
",",
"callback",
")",
"{",
"if",
"(",
"typeof",
"path",
"===",
"'string'",
")",
"{",
"callback",
"(",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"util",
".",
"format",
"(",
"'Invalid path: %s'",
",",
"path",
")",
")",
";",
"}",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"red",
"(",
"err",
")",
")",
";",
"}",
"else",
"{",
"setter",
"(",
"fileset",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"red",
"(",
"'Fileset is not an array: %j'",
")",
",",
"fileset",
")",
";",
"}",
"}"
]
| Filesets are validated by ensuring the fileset is an array and each item is a string. Valid filesets are applied, invalid ones are ignored. | [
"Filesets",
"are",
"validated",
"by",
"ensuring",
"the",
"fileset",
"is",
"an",
"array",
"and",
"each",
"item",
"is",
"a",
"string",
".",
"Valid",
"filesets",
"are",
"applied",
"invalid",
"ones",
"are",
"ignored",
"."
]
| 2831a0286bfe3fb956b5188f0508752c6d16a4de | https://github.com/RainBirdAi/rainbird-linter/blob/2831a0286bfe3fb956b5188f0508752c6d16a4de/lib/filesets.js#L26-L44 |
45,352 | RainBirdAi/rainbird-linter | lib/filesets.js | platoExcludes | function platoExcludes() {
var excludes = '';
excludeFileset.forEach(function (file) {
if (isDirectory(file)) {
excludes += file.replace(/\//g, '\/');
} else {
excludes += file;
}
excludes += '|';
});
if (excludes !== '') {
return new RegExp(excludes.slice(0, -1));
} else {
return null;
}
} | javascript | function platoExcludes() {
var excludes = '';
excludeFileset.forEach(function (file) {
if (isDirectory(file)) {
excludes += file.replace(/\//g, '\/');
} else {
excludes += file;
}
excludes += '|';
});
if (excludes !== '') {
return new RegExp(excludes.slice(0, -1));
} else {
return null;
}
} | [
"function",
"platoExcludes",
"(",
")",
"{",
"var",
"excludes",
"=",
"''",
";",
"excludeFileset",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"if",
"(",
"isDirectory",
"(",
"file",
")",
")",
"{",
"excludes",
"+=",
"file",
".",
"replace",
"(",
"/",
"\\/",
"/",
"g",
",",
"'\\/'",
")",
";",
"}",
"else",
"{",
"excludes",
"+=",
"file",
";",
"}",
"excludes",
"+=",
"'|'",
";",
"}",
")",
";",
"if",
"(",
"excludes",
"!==",
"''",
")",
"{",
"return",
"new",
"RegExp",
"(",
"excludes",
".",
"slice",
"(",
"0",
",",
"-",
"1",
")",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
]
| Plato uses a regular expression to exclude files so turn the list of exclude files into a properly formatted, pipe delimited list of files. If there are no filesets to exclude then `null` is returned. | [
"Plato",
"uses",
"a",
"regular",
"expression",
"to",
"exclude",
"files",
"so",
"turn",
"the",
"list",
"of",
"exclude",
"files",
"into",
"a",
"properly",
"formatted",
"pipe",
"delimited",
"list",
"of",
"files",
".",
"If",
"there",
"are",
"no",
"filesets",
"to",
"exclude",
"then",
"null",
"is",
"returned",
"."
]
| 2831a0286bfe3fb956b5188f0508752c6d16a4de | https://github.com/RainBirdAi/rainbird-linter/blob/2831a0286bfe3fb956b5188f0508752c6d16a4de/lib/filesets.js#L85-L101 |
45,353 | mchalapuk/hyper-text-slider | lib/polyfills/class-list.js | applyPolyfill | function applyPolyfill(ElementClass) {
if (ElementClass.prototype.hasOwnProperty('classList')) {
return;
}
Object.defineProperty(ElementClass.prototype, 'classList', {
get: lazyDefinePropertyValue('classList', function() {
if (!(this instanceof ElementClass)) {
throw new Error(
'\'get classList\' called on an object that does not implement interface Element.');
}
return new DOMTokenList(this, 'className');
}),
set: throwError('classList property is read-only'),
enumerable: true,
configurable: true,
});
} | javascript | function applyPolyfill(ElementClass) {
if (ElementClass.prototype.hasOwnProperty('classList')) {
return;
}
Object.defineProperty(ElementClass.prototype, 'classList', {
get: lazyDefinePropertyValue('classList', function() {
if (!(this instanceof ElementClass)) {
throw new Error(
'\'get classList\' called on an object that does not implement interface Element.');
}
return new DOMTokenList(this, 'className');
}),
set: throwError('classList property is read-only'),
enumerable: true,
configurable: true,
});
} | [
"function",
"applyPolyfill",
"(",
"ElementClass",
")",
"{",
"if",
"(",
"ElementClass",
".",
"prototype",
".",
"hasOwnProperty",
"(",
"'classList'",
")",
")",
"{",
"return",
";",
"}",
"Object",
".",
"defineProperty",
"(",
"ElementClass",
".",
"prototype",
",",
"'classList'",
",",
"{",
"get",
":",
"lazyDefinePropertyValue",
"(",
"'classList'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"ElementClass",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'\\'get classList\\' called on an object that does not implement interface Element.'",
")",
";",
"}",
"return",
"new",
"DOMTokenList",
"(",
"this",
",",
"'className'",
")",
";",
"}",
")",
",",
"set",
":",
"throwError",
"(",
"'classList property is read-only'",
")",
",",
"enumerable",
":",
"true",
",",
"configurable",
":",
"true",
",",
"}",
")",
";",
"}"
]
| Checks if prototype of passed ElementClass contains classList and,
in case not, creates a polyfill implementation. | [
"Checks",
"if",
"prototype",
"of",
"passed",
"ElementClass",
"contains",
"classList",
"and",
"in",
"case",
"not",
"creates",
"a",
"polyfill",
"implementation",
"."
]
| 2711b41b9bbf1d528e4a0bd31b2efdf91dce55b4 | https://github.com/mchalapuk/hyper-text-slider/blob/2711b41b9bbf1d528e4a0bd31b2efdf91dce55b4/lib/polyfills/class-list.js#L28-L45 |
45,354 | tableflip/footballbot-workshop | stubs/serialport.js | SpyConstructor | function SpyConstructor (opts) {
Constructor.call(this, opts)
// Spy on Constructor functions
for (var key in this) {
if (this[key] instanceof Function) {
this[key] = sinon.spy(this[key])
}
}
SpyConstructor.instances.push(this)
} | javascript | function SpyConstructor (opts) {
Constructor.call(this, opts)
// Spy on Constructor functions
for (var key in this) {
if (this[key] instanceof Function) {
this[key] = sinon.spy(this[key])
}
}
SpyConstructor.instances.push(this)
} | [
"function",
"SpyConstructor",
"(",
"opts",
")",
"{",
"Constructor",
".",
"call",
"(",
"this",
",",
"opts",
")",
"// Spy on Constructor functions",
"for",
"(",
"var",
"key",
"in",
"this",
")",
"{",
"if",
"(",
"this",
"[",
"key",
"]",
"instanceof",
"Function",
")",
"{",
"this",
"[",
"key",
"]",
"=",
"sinon",
".",
"spy",
"(",
"this",
"[",
"key",
"]",
")",
"}",
"}",
"SpyConstructor",
".",
"instances",
".",
"push",
"(",
"this",
")",
"}"
]
| Wrap methods with spies and store instances | [
"Wrap",
"methods",
"with",
"spies",
"and",
"store",
"instances"
]
| 3d9a31da2fe399b74199c7874caf4b5fcec42f8c | https://github.com/tableflip/footballbot-workshop/blob/3d9a31da2fe399b74199c7874caf4b5fcec42f8c/stubs/serialport.js#L18-L29 |
45,355 | socialally/air | lib/air/text.js | text | function text(txt) {
if(!this.length) {
return this;
}
if(txt === undefined) {
return this.dom[0].textContent;
}
txt = txt || '';
this.each(function(el) {
el.textContent = txt;
});
return this;
} | javascript | function text(txt) {
if(!this.length) {
return this;
}
if(txt === undefined) {
return this.dom[0].textContent;
}
txt = txt || '';
this.each(function(el) {
el.textContent = txt;
});
return this;
} | [
"function",
"text",
"(",
"txt",
")",
"{",
"if",
"(",
"!",
"this",
".",
"length",
")",
"{",
"return",
"this",
";",
"}",
"if",
"(",
"txt",
"===",
"undefined",
")",
"{",
"return",
"this",
".",
"dom",
"[",
"0",
"]",
".",
"textContent",
";",
"}",
"txt",
"=",
"txt",
"||",
"''",
";",
"this",
".",
"each",
"(",
"function",
"(",
"el",
")",
"{",
"el",
".",
"textContent",
"=",
"txt",
";",
"}",
")",
";",
"return",
"this",
";",
"}"
]
| IE9 supports textContent and innerText has various issues.
See: https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
See: http://www.kellegous.com/j/2013/02/27/innertext-vs-textcontent/ | [
"IE9",
"supports",
"textContent",
"and",
"innerText",
"has",
"various",
"issues",
"."
]
| a3d94de58aaa4930a425fbcc7266764bf6ca8ca6 | https://github.com/socialally/air/blob/a3d94de58aaa4930a425fbcc7266764bf6ca8ca6/lib/air/text.js#L7-L19 |
45,356 | OpenSmartEnvironment/ose | lib/http/content.js | init | function init(path, name) { // {{{2
/**
* Class constructor
*
* @param name {String} Name of HttpContent instance
* @param path {String} Path to content
*
* @method init
*/
this.modules = {};
this.handlers = {};
this.scripts = [];
this.styles = [];
this.path = path || Path.dirname(this.O.module.filename);
this.name = name || this.O.packageName || this.O.package.packageName;
// O.log.debug('Content', this.toString());
Http.addContent(this);
this.addFiles && this.addFiles();
} | javascript | function init(path, name) { // {{{2
/**
* Class constructor
*
* @param name {String} Name of HttpContent instance
* @param path {String} Path to content
*
* @method init
*/
this.modules = {};
this.handlers = {};
this.scripts = [];
this.styles = [];
this.path = path || Path.dirname(this.O.module.filename);
this.name = name || this.O.packageName || this.O.package.packageName;
// O.log.debug('Content', this.toString());
Http.addContent(this);
this.addFiles && this.addFiles();
} | [
"function",
"init",
"(",
"path",
",",
"name",
")",
"{",
"// {{{2",
"/**\n * Class constructor\n *\n * @param name {String} Name of HttpContent instance\n * @param path {String} Path to content\n *\n * @method init\n */",
"this",
".",
"modules",
"=",
"{",
"}",
";",
"this",
".",
"handlers",
"=",
"{",
"}",
";",
"this",
".",
"scripts",
"=",
"[",
"]",
";",
"this",
".",
"styles",
"=",
"[",
"]",
";",
"this",
".",
"path",
"=",
"path",
"||",
"Path",
".",
"dirname",
"(",
"this",
".",
"O",
".",
"module",
".",
"filename",
")",
";",
"this",
".",
"name",
"=",
"name",
"||",
"this",
".",
"O",
".",
"packageName",
"||",
"this",
".",
"O",
".",
"package",
".",
"packageName",
";",
"// O.log.debug('Content', this.toString());",
"Http",
".",
"addContent",
"(",
"this",
")",
";",
"this",
".",
"addFiles",
"&&",
"this",
".",
"addFiles",
"(",
")",
";",
"}"
]
| List of handlers provided by this content instance.
@property handlers
@type Object
Public {{{1 | [
"List",
"of",
"handlers",
"provided",
"by",
"this",
"content",
"instance",
"."
]
| 2ab051d9db6e77341c40abb9cbdae6ce586917e0 | https://github.com/OpenSmartEnvironment/ose/blob/2ab051d9db6e77341c40abb9cbdae6ce586917e0/lib/http/content.js#L71-L94 |
45,357 | nodejitsu/contour | pagelets/navigation.js | links | function links(data, page, options) {
if (!data || !data.length) return;
var targets = ['self', 'blank', 'parent', 'top']
, navigation = this;
return data.reduce(function reduce(menu, item) {
var url = item.href.split('/').filter(String)
, active = url.shift();
if (page) active = item.base || url.shift();
item.active = ~navigation[page ? 'page' : 'base'].indexOf(active)
? ' class="active"'
: '';
item.target = item.target && ~targets.indexOf(item.target)
? ' target=_' + item.target
: '';
return menu + options.fn(item);
}, '');
} | javascript | function links(data, page, options) {
if (!data || !data.length) return;
var targets = ['self', 'blank', 'parent', 'top']
, navigation = this;
return data.reduce(function reduce(menu, item) {
var url = item.href.split('/').filter(String)
, active = url.shift();
if (page) active = item.base || url.shift();
item.active = ~navigation[page ? 'page' : 'base'].indexOf(active)
? ' class="active"'
: '';
item.target = item.target && ~targets.indexOf(item.target)
? ' target=_' + item.target
: '';
return menu + options.fn(item);
}, '');
} | [
"function",
"links",
"(",
"data",
",",
"page",
",",
"options",
")",
"{",
"if",
"(",
"!",
"data",
"||",
"!",
"data",
".",
"length",
")",
"return",
";",
"var",
"targets",
"=",
"[",
"'self'",
",",
"'blank'",
",",
"'parent'",
",",
"'top'",
"]",
",",
"navigation",
"=",
"this",
";",
"return",
"data",
".",
"reduce",
"(",
"function",
"reduce",
"(",
"menu",
",",
"item",
")",
"{",
"var",
"url",
"=",
"item",
".",
"href",
".",
"split",
"(",
"'/'",
")",
".",
"filter",
"(",
"String",
")",
",",
"active",
"=",
"url",
".",
"shift",
"(",
")",
";",
"if",
"(",
"page",
")",
"active",
"=",
"item",
".",
"base",
"||",
"url",
".",
"shift",
"(",
")",
";",
"item",
".",
"active",
"=",
"~",
"navigation",
"[",
"page",
"?",
"'page'",
":",
"'base'",
"]",
".",
"indexOf",
"(",
"active",
")",
"?",
"' class=\"active\"'",
":",
"''",
";",
"item",
".",
"target",
"=",
"item",
".",
"target",
"&&",
"~",
"targets",
".",
"indexOf",
"(",
"item",
".",
"target",
")",
"?",
"' target=_'",
"+",
"item",
".",
"target",
":",
"''",
";",
"return",
"menu",
"+",
"options",
".",
"fn",
"(",
"item",
")",
";",
"}",
",",
"''",
")",
";",
"}"
]
| Handblebar helper to generate the navigation entries. The base is defined by
the active page and should match the first part of the `href` route or the
provided menu entry `base`.
@param {Object} options
@param {Boolean} page Current iteration over page or root of url
@return {String} generated template
@api private | [
"Handblebar",
"helper",
"to",
"generate",
"the",
"navigation",
"entries",
".",
"The",
"base",
"is",
"defined",
"by",
"the",
"active",
"page",
"and",
"should",
"match",
"the",
"first",
"part",
"of",
"the",
"href",
"route",
"or",
"the",
"provided",
"menu",
"entry",
"base",
"."
]
| 0828e9bd25ef1eeb97ea231c447118d9867021b6 | https://github.com/nodejitsu/contour/blob/0828e9bd25ef1eeb97ea231c447118d9867021b6/pagelets/navigation.js#L93-L114 |
45,358 | vid/SenseBase | services/annotators/structural.js | function(sMatch, text) {
for (var i = 0; i < sMatch.matches.length; i++) {
var r = sMatch.matches[i];
var found = text.match(r);
if (found) {
var exact = found[0];
var value = found[1].trim();
var key = sMatch.fields[i];
annoRows.push(annotations.createAnnotation({type: 'valueQuote', annotatedBy: sMatch.name, hasTarget: uri, key: key, value: value, ranges: annotations.createRange({ exact: exact, offset: found.index, selector: ''}) }));
}
}
return annoRows;
} | javascript | function(sMatch, text) {
for (var i = 0; i < sMatch.matches.length; i++) {
var r = sMatch.matches[i];
var found = text.match(r);
if (found) {
var exact = found[0];
var value = found[1].trim();
var key = sMatch.fields[i];
annoRows.push(annotations.createAnnotation({type: 'valueQuote', annotatedBy: sMatch.name, hasTarget: uri, key: key, value: value, ranges: annotations.createRange({ exact: exact, offset: found.index, selector: ''}) }));
}
}
return annoRows;
} | [
"function",
"(",
"sMatch",
",",
"text",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"sMatch",
".",
"matches",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"r",
"=",
"sMatch",
".",
"matches",
"[",
"i",
"]",
";",
"var",
"found",
"=",
"text",
".",
"match",
"(",
"r",
")",
";",
"if",
"(",
"found",
")",
"{",
"var",
"exact",
"=",
"found",
"[",
"0",
"]",
";",
"var",
"value",
"=",
"found",
"[",
"1",
"]",
".",
"trim",
"(",
")",
";",
"var",
"key",
"=",
"sMatch",
".",
"fields",
"[",
"i",
"]",
";",
"annoRows",
".",
"push",
"(",
"annotations",
".",
"createAnnotation",
"(",
"{",
"type",
":",
"'valueQuote'",
",",
"annotatedBy",
":",
"sMatch",
".",
"name",
",",
"hasTarget",
":",
"uri",
",",
"key",
":",
"key",
",",
"value",
":",
"value",
",",
"ranges",
":",
"annotations",
".",
"createRange",
"(",
"{",
"exact",
":",
"exact",
",",
"offset",
":",
"found",
".",
"index",
",",
"selector",
":",
"''",
"}",
")",
"}",
")",
")",
";",
"}",
"}",
"return",
"annoRows",
";",
"}"
]
| match a series of regexes, setting any found values | [
"match",
"a",
"series",
"of",
"regexes",
"setting",
"any",
"found",
"values"
]
| d60bcf28239e7dde437d8a6bdae41a6921dcd05b | https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/services/annotators/structural.js#L64-L77 |
|
45,359 | shamoons/linguist-samples | samples/JavaScript/json2_backbone.js | function(model, options) {
options || (options = {});
model = this._prepareModel(model, options);
if (!model) return false;
var already = this.getByCid(model) || this.get(model);
if (already) throw new Error(["Can't add the same model to a set twice", already.id]);
this._byId[model.id] = model;
this._byCid[model.cid] = model;
var index = options.at != null ? options.at :
this.comparator ? this.sortedIndex(model, this.comparator) :
this.length;
this.models.splice(index, 0, model);
model.bind('all', this._onModelEvent);
this.length++;
if (!options.silent) model.trigger('add', model, this, options);
return model;
} | javascript | function(model, options) {
options || (options = {});
model = this._prepareModel(model, options);
if (!model) return false;
var already = this.getByCid(model) || this.get(model);
if (already) throw new Error(["Can't add the same model to a set twice", already.id]);
this._byId[model.id] = model;
this._byCid[model.cid] = model;
var index = options.at != null ? options.at :
this.comparator ? this.sortedIndex(model, this.comparator) :
this.length;
this.models.splice(index, 0, model);
model.bind('all', this._onModelEvent);
this.length++;
if (!options.silent) model.trigger('add', model, this, options);
return model;
} | [
"function",
"(",
"model",
",",
"options",
")",
"{",
"options",
"||",
"(",
"options",
"=",
"{",
"}",
")",
";",
"model",
"=",
"this",
".",
"_prepareModel",
"(",
"model",
",",
"options",
")",
";",
"if",
"(",
"!",
"model",
")",
"return",
"false",
";",
"var",
"already",
"=",
"this",
".",
"getByCid",
"(",
"model",
")",
"||",
"this",
".",
"get",
"(",
"model",
")",
";",
"if",
"(",
"already",
")",
"throw",
"new",
"Error",
"(",
"[",
"\"Can't add the same model to a set twice\"",
",",
"already",
".",
"id",
"]",
")",
";",
"this",
".",
"_byId",
"[",
"model",
".",
"id",
"]",
"=",
"model",
";",
"this",
".",
"_byCid",
"[",
"model",
".",
"cid",
"]",
"=",
"model",
";",
"var",
"index",
"=",
"options",
".",
"at",
"!=",
"null",
"?",
"options",
".",
"at",
":",
"this",
".",
"comparator",
"?",
"this",
".",
"sortedIndex",
"(",
"model",
",",
"this",
".",
"comparator",
")",
":",
"this",
".",
"length",
";",
"this",
".",
"models",
".",
"splice",
"(",
"index",
",",
"0",
",",
"model",
")",
";",
"model",
".",
"bind",
"(",
"'all'",
",",
"this",
".",
"_onModelEvent",
")",
";",
"this",
".",
"length",
"++",
";",
"if",
"(",
"!",
"options",
".",
"silent",
")",
"model",
".",
"trigger",
"(",
"'add'",
",",
"model",
",",
"this",
",",
"options",
")",
";",
"return",
"model",
";",
"}"
]
| Internal implementation of adding a single model to the set, updating hash indexes for `id` and `cid` lookups. Returns the model, or 'false' if validation on a new model fails. | [
"Internal",
"implementation",
"of",
"adding",
"a",
"single",
"model",
"to",
"the",
"set",
"updating",
"hash",
"indexes",
"for",
"id",
"and",
"cid",
"lookups",
".",
"Returns",
"the",
"model",
"or",
"false",
"if",
"validation",
"on",
"a",
"new",
"model",
"fails",
"."
]
| 71c5ec1a535f7dde31f9e407679475f57fae0c08 | https://github.com/shamoons/linguist-samples/blob/71c5ec1a535f7dde31f9e407679475f57fae0c08/samples/JavaScript/json2_backbone.js#L584-L600 |
|
45,360 | synder/xpress | demo/body-parser/index.js | bodyParser | function bodyParser (options) {
var opts = {}
// exclude type option
if (options) {
for (var prop in options) {
if (prop !== 'type') {
opts[prop] = options[prop]
}
}
}
var _urlencoded = exports.urlencoded(opts)
var _json = exports.json(opts)
return function bodyParser (req, res, next) {
_json(req, res, function (err) {
if (err) return next(err)
_urlencoded(req, res, next)
})
}
} | javascript | function bodyParser (options) {
var opts = {}
// exclude type option
if (options) {
for (var prop in options) {
if (prop !== 'type') {
opts[prop] = options[prop]
}
}
}
var _urlencoded = exports.urlencoded(opts)
var _json = exports.json(opts)
return function bodyParser (req, res, next) {
_json(req, res, function (err) {
if (err) return next(err)
_urlencoded(req, res, next)
})
}
} | [
"function",
"bodyParser",
"(",
"options",
")",
"{",
"var",
"opts",
"=",
"{",
"}",
"// exclude type option",
"if",
"(",
"options",
")",
"{",
"for",
"(",
"var",
"prop",
"in",
"options",
")",
"{",
"if",
"(",
"prop",
"!==",
"'type'",
")",
"{",
"opts",
"[",
"prop",
"]",
"=",
"options",
"[",
"prop",
"]",
"}",
"}",
"}",
"var",
"_urlencoded",
"=",
"exports",
".",
"urlencoded",
"(",
"opts",
")",
"var",
"_json",
"=",
"exports",
".",
"json",
"(",
"opts",
")",
"return",
"function",
"bodyParser",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"_json",
"(",
"req",
",",
"res",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"err",
")",
"_urlencoded",
"(",
"req",
",",
"res",
",",
"next",
")",
"}",
")",
"}",
"}"
]
| Create a middleware to parse json and urlencoded bodies.
@param {object} [options]
@return {function}
@deprecated
@public | [
"Create",
"a",
"middleware",
"to",
"parse",
"json",
"and",
"urlencoded",
"bodies",
"."
]
| 4b1e89208b6f34cd78ce90b8a858592115b6ccb5 | https://github.com/synder/xpress/blob/4b1e89208b6f34cd78ce90b8a858592115b6ccb5/demo/body-parser/index.js#L93-L114 |
45,361 | synder/xpress | demo/body-parser/index.js | loadParser | function loadParser (parserName) {
var parser = parsers[parserName]
if (parser !== undefined) {
return parser
}
// this uses a switch for static require analysis
switch (parserName) {
case 'json':
parser = require('./lib/types/json')
break
case 'raw':
parser = require('./lib/types/raw')
break
case 'text':
parser = require('./lib/types/text')
break
case 'urlencoded':
parser = require('./lib/types/urlencoded')
break
}
// store to prevent invoking require()
return (parsers[parserName] = parser)
} | javascript | function loadParser (parserName) {
var parser = parsers[parserName]
if (parser !== undefined) {
return parser
}
// this uses a switch for static require analysis
switch (parserName) {
case 'json':
parser = require('./lib/types/json')
break
case 'raw':
parser = require('./lib/types/raw')
break
case 'text':
parser = require('./lib/types/text')
break
case 'urlencoded':
parser = require('./lib/types/urlencoded')
break
}
// store to prevent invoking require()
return (parsers[parserName] = parser)
} | [
"function",
"loadParser",
"(",
"parserName",
")",
"{",
"var",
"parser",
"=",
"parsers",
"[",
"parserName",
"]",
"if",
"(",
"parser",
"!==",
"undefined",
")",
"{",
"return",
"parser",
"}",
"// this uses a switch for static require analysis",
"switch",
"(",
"parserName",
")",
"{",
"case",
"'json'",
":",
"parser",
"=",
"require",
"(",
"'./lib/types/json'",
")",
"break",
"case",
"'raw'",
":",
"parser",
"=",
"require",
"(",
"'./lib/types/raw'",
")",
"break",
"case",
"'text'",
":",
"parser",
"=",
"require",
"(",
"'./lib/types/text'",
")",
"break",
"case",
"'urlencoded'",
":",
"parser",
"=",
"require",
"(",
"'./lib/types/urlencoded'",
")",
"break",
"}",
"// store to prevent invoking require()",
"return",
"(",
"parsers",
"[",
"parserName",
"]",
"=",
"parser",
")",
"}"
]
| Load a parser module.
@private | [
"Load",
"a",
"parser",
"module",
"."
]
| 4b1e89208b6f34cd78ce90b8a858592115b6ccb5 | https://github.com/synder/xpress/blob/4b1e89208b6f34cd78ce90b8a858592115b6ccb5/demo/body-parser/index.js#L132-L157 |
45,362 | imperodesign/jquery-autoselect | index.js | function( term ) {
var split_term = term.split(' ');
var matchers = [];
for (var i=0; i < split_term.length; i++) {
if ( split_term[i].length > 0 ) {
var matcher = {};
matcher['partial'] = new RegExp( $.ui.autocomplete.escapeRegex( split_term[i] ), "i" );
if ( context.settings['relevancy-sorting'] ) {
matcher['strict'] = new RegExp( "^" + $.ui.autocomplete.escapeRegex( split_term[i] ), "i" );
}
matchers.push( matcher );
}
};
return $.grep( context.options, function( option ) {
var partial_matches = 0;
if ( context.settings['relevancy-sorting'] ) {
var strict_match = false;
var split_option_matches = option.matches.split(' ');
}
for ( var i=0; i < matchers.length; i++ ) {
if ( matchers[i]['partial'].test( option.matches ) ) {
partial_matches++;
}
if ( context.settings['relevancy-sorting'] ) {
for (var q=0; q < split_option_matches.length; q++) {
if ( matchers[i]['strict'].test( split_option_matches[q] ) ) {
strict_match = true;
break;
}
};
}
};
if ( context.settings['relevancy-sorting'] ) {
var option_score = 0;
option_score += partial_matches * context.settings['relevancy-sorting-partial-match-value'];
if ( strict_match ) {
option_score += context.settings['relevancy-sorting-strict-match-value'];
}
option_score = option_score * option['relevancy-score-booster'];
option['relevancy-score'] = option_score;
}
return (!term || matchers.length === partial_matches );
});
} | javascript | function( term ) {
var split_term = term.split(' ');
var matchers = [];
for (var i=0; i < split_term.length; i++) {
if ( split_term[i].length > 0 ) {
var matcher = {};
matcher['partial'] = new RegExp( $.ui.autocomplete.escapeRegex( split_term[i] ), "i" );
if ( context.settings['relevancy-sorting'] ) {
matcher['strict'] = new RegExp( "^" + $.ui.autocomplete.escapeRegex( split_term[i] ), "i" );
}
matchers.push( matcher );
}
};
return $.grep( context.options, function( option ) {
var partial_matches = 0;
if ( context.settings['relevancy-sorting'] ) {
var strict_match = false;
var split_option_matches = option.matches.split(' ');
}
for ( var i=0; i < matchers.length; i++ ) {
if ( matchers[i]['partial'].test( option.matches ) ) {
partial_matches++;
}
if ( context.settings['relevancy-sorting'] ) {
for (var q=0; q < split_option_matches.length; q++) {
if ( matchers[i]['strict'].test( split_option_matches[q] ) ) {
strict_match = true;
break;
}
};
}
};
if ( context.settings['relevancy-sorting'] ) {
var option_score = 0;
option_score += partial_matches * context.settings['relevancy-sorting-partial-match-value'];
if ( strict_match ) {
option_score += context.settings['relevancy-sorting-strict-match-value'];
}
option_score = option_score * option['relevancy-score-booster'];
option['relevancy-score'] = option_score;
}
return (!term || matchers.length === partial_matches );
});
} | [
"function",
"(",
"term",
")",
"{",
"var",
"split_term",
"=",
"term",
".",
"split",
"(",
"' '",
")",
";",
"var",
"matchers",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"split_term",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"split_term",
"[",
"i",
"]",
".",
"length",
">",
"0",
")",
"{",
"var",
"matcher",
"=",
"{",
"}",
";",
"matcher",
"[",
"'partial'",
"]",
"=",
"new",
"RegExp",
"(",
"$",
".",
"ui",
".",
"autocomplete",
".",
"escapeRegex",
"(",
"split_term",
"[",
"i",
"]",
")",
",",
"\"i\"",
")",
";",
"if",
"(",
"context",
".",
"settings",
"[",
"'relevancy-sorting'",
"]",
")",
"{",
"matcher",
"[",
"'strict'",
"]",
"=",
"new",
"RegExp",
"(",
"\"^\"",
"+",
"$",
".",
"ui",
".",
"autocomplete",
".",
"escapeRegex",
"(",
"split_term",
"[",
"i",
"]",
")",
",",
"\"i\"",
")",
";",
"}",
"matchers",
".",
"push",
"(",
"matcher",
")",
";",
"}",
"}",
";",
"return",
"$",
".",
"grep",
"(",
"context",
".",
"options",
",",
"function",
"(",
"option",
")",
"{",
"var",
"partial_matches",
"=",
"0",
";",
"if",
"(",
"context",
".",
"settings",
"[",
"'relevancy-sorting'",
"]",
")",
"{",
"var",
"strict_match",
"=",
"false",
";",
"var",
"split_option_matches",
"=",
"option",
".",
"matches",
".",
"split",
"(",
"' '",
")",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"matchers",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"matchers",
"[",
"i",
"]",
"[",
"'partial'",
"]",
".",
"test",
"(",
"option",
".",
"matches",
")",
")",
"{",
"partial_matches",
"++",
";",
"}",
"if",
"(",
"context",
".",
"settings",
"[",
"'relevancy-sorting'",
"]",
")",
"{",
"for",
"(",
"var",
"q",
"=",
"0",
";",
"q",
"<",
"split_option_matches",
".",
"length",
";",
"q",
"++",
")",
"{",
"if",
"(",
"matchers",
"[",
"i",
"]",
"[",
"'strict'",
"]",
".",
"test",
"(",
"split_option_matches",
"[",
"q",
"]",
")",
")",
"{",
"strict_match",
"=",
"true",
";",
"break",
";",
"}",
"}",
";",
"}",
"}",
";",
"if",
"(",
"context",
".",
"settings",
"[",
"'relevancy-sorting'",
"]",
")",
"{",
"var",
"option_score",
"=",
"0",
";",
"option_score",
"+=",
"partial_matches",
"*",
"context",
".",
"settings",
"[",
"'relevancy-sorting-partial-match-value'",
"]",
";",
"if",
"(",
"strict_match",
")",
"{",
"option_score",
"+=",
"context",
".",
"settings",
"[",
"'relevancy-sorting-strict-match-value'",
"]",
";",
"}",
"option_score",
"=",
"option_score",
"*",
"option",
"[",
"'relevancy-score-booster'",
"]",
";",
"option",
"[",
"'relevancy-score'",
"]",
"=",
"option_score",
";",
"}",
"return",
"(",
"!",
"term",
"||",
"matchers",
".",
"length",
"===",
"partial_matches",
")",
";",
"}",
")",
";",
"}"
]
| loose matching of search terms | [
"loose",
"matching",
"of",
"search",
"terms"
]
| c4c92c7458f00b281128a8a2ba59381f105829b6 | https://github.com/imperodesign/jquery-autoselect/blob/c4c92c7458f00b281128a8a2ba59381f105829b6/index.js#L158-L202 |
|
45,363 | imperodesign/jquery-autoselect | index.js | function( option ) {
if ( option ) {
if ( context.$select_field.val() !== option['real-value'] ) {
context.$select_field.val( option['real-value'] );
context.$select_field.change();
}
} else {
var option_name = context.$text_field.val().toLowerCase();
var matching_option = { 'real-value': false };
for (var i=0; i < context.options.length; i++) {
if ( option_name === context.options[i]['label'].toLowerCase() ) {
matching_option = context.options[i];
break;
}
};
if ( context.$select_field.val() !== matching_option['real-value'] ) {
context.$select_field.val( matching_option['real-value'] || '' );
context.$select_field.change();
}
if ( matching_option['real-value'] ) {
context.$text_field.val( matching_option['label'] );
}
if ( typeof context.settings['handle_invalid_input'] === 'function' && context.$select_field.val() === '' ) {
context.settings['handle_invalid_input']( context );
}
}
} | javascript | function( option ) {
if ( option ) {
if ( context.$select_field.val() !== option['real-value'] ) {
context.$select_field.val( option['real-value'] );
context.$select_field.change();
}
} else {
var option_name = context.$text_field.val().toLowerCase();
var matching_option = { 'real-value': false };
for (var i=0; i < context.options.length; i++) {
if ( option_name === context.options[i]['label'].toLowerCase() ) {
matching_option = context.options[i];
break;
}
};
if ( context.$select_field.val() !== matching_option['real-value'] ) {
context.$select_field.val( matching_option['real-value'] || '' );
context.$select_field.change();
}
if ( matching_option['real-value'] ) {
context.$text_field.val( matching_option['label'] );
}
if ( typeof context.settings['handle_invalid_input'] === 'function' && context.$select_field.val() === '' ) {
context.settings['handle_invalid_input']( context );
}
}
} | [
"function",
"(",
"option",
")",
"{",
"if",
"(",
"option",
")",
"{",
"if",
"(",
"context",
".",
"$select_field",
".",
"val",
"(",
")",
"!==",
"option",
"[",
"'real-value'",
"]",
")",
"{",
"context",
".",
"$select_field",
".",
"val",
"(",
"option",
"[",
"'real-value'",
"]",
")",
";",
"context",
".",
"$select_field",
".",
"change",
"(",
")",
";",
"}",
"}",
"else",
"{",
"var",
"option_name",
"=",
"context",
".",
"$text_field",
".",
"val",
"(",
")",
".",
"toLowerCase",
"(",
")",
";",
"var",
"matching_option",
"=",
"{",
"'real-value'",
":",
"false",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"context",
".",
"options",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"option_name",
"===",
"context",
".",
"options",
"[",
"i",
"]",
"[",
"'label'",
"]",
".",
"toLowerCase",
"(",
")",
")",
"{",
"matching_option",
"=",
"context",
".",
"options",
"[",
"i",
"]",
";",
"break",
";",
"}",
"}",
";",
"if",
"(",
"context",
".",
"$select_field",
".",
"val",
"(",
")",
"!==",
"matching_option",
"[",
"'real-value'",
"]",
")",
"{",
"context",
".",
"$select_field",
".",
"val",
"(",
"matching_option",
"[",
"'real-value'",
"]",
"||",
"''",
")",
";",
"context",
".",
"$select_field",
".",
"change",
"(",
")",
";",
"}",
"if",
"(",
"matching_option",
"[",
"'real-value'",
"]",
")",
"{",
"context",
".",
"$text_field",
".",
"val",
"(",
"matching_option",
"[",
"'label'",
"]",
")",
";",
"}",
"if",
"(",
"typeof",
"context",
".",
"settings",
"[",
"'handle_invalid_input'",
"]",
"===",
"'function'",
"&&",
"context",
".",
"$select_field",
".",
"val",
"(",
")",
"===",
"''",
")",
"{",
"context",
".",
"settings",
"[",
"'handle_invalid_input'",
"]",
"(",
"context",
")",
";",
"}",
"}",
"}"
]
| update the select field value using either selected option or current input in the text field | [
"update",
"the",
"select",
"field",
"value",
"using",
"either",
"selected",
"option",
"or",
"current",
"input",
"in",
"the",
"text",
"field"
]
| c4c92c7458f00b281128a8a2ba59381f105829b6 | https://github.com/imperodesign/jquery-autoselect/blob/c4c92c7458f00b281128a8a2ba59381f105829b6/index.js#L204-L230 |
|
45,364 | wvv8oo/charm.js | samples/js/q.js | coerce | function coerce(promise) {
var deferred = defer();
nextTick(function () {
try {
promise.then(deferred.resolve, deferred.reject, deferred.notify);
} catch (exception) {
deferred.reject(exception);
}
});
return deferred.promise;
} | javascript | function coerce(promise) {
var deferred = defer();
nextTick(function () {
try {
promise.then(deferred.resolve, deferred.reject, deferred.notify);
} catch (exception) {
deferred.reject(exception);
}
});
return deferred.promise;
} | [
"function",
"coerce",
"(",
"promise",
")",
"{",
"var",
"deferred",
"=",
"defer",
"(",
")",
";",
"nextTick",
"(",
"function",
"(",
")",
"{",
"try",
"{",
"promise",
".",
"then",
"(",
"deferred",
".",
"resolve",
",",
"deferred",
".",
"reject",
",",
"deferred",
".",
"notify",
")",
";",
"}",
"catch",
"(",
"exception",
")",
"{",
"deferred",
".",
"reject",
"(",
"exception",
")",
";",
"}",
"}",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"}"
]
| Converts thenables to Q promises.
@param promise thenable promise
@returns a Q promise | [
"Converts",
"thenables",
"to",
"Q",
"promises",
"."
]
| 1c6098873bf065cf9db13fb0970d7eabe62fb72c | https://github.com/wvv8oo/charm.js/blob/1c6098873bf065cf9db13fb0970d7eabe62fb72c/samples/js/q.js#L1093-L1103 |
45,365 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | iterDeps | function iterDeps(method, obj, depKey, seen, meta) {
var guid = guidFor(obj);
if (!seen[guid]) seen[guid] = {};
if (seen[guid][depKey]) return;
seen[guid][depKey] = true;
var deps = meta.deps;
deps = deps && deps[depKey];
if (deps) {
for(var key in deps) {
if (DEP_SKIP[key]) continue;
method(obj, key);
}
}
} | javascript | function iterDeps(method, obj, depKey, seen, meta) {
var guid = guidFor(obj);
if (!seen[guid]) seen[guid] = {};
if (seen[guid][depKey]) return;
seen[guid][depKey] = true;
var deps = meta.deps;
deps = deps && deps[depKey];
if (deps) {
for(var key in deps) {
if (DEP_SKIP[key]) continue;
method(obj, key);
}
}
} | [
"function",
"iterDeps",
"(",
"method",
",",
"obj",
",",
"depKey",
",",
"seen",
",",
"meta",
")",
"{",
"var",
"guid",
"=",
"guidFor",
"(",
"obj",
")",
";",
"if",
"(",
"!",
"seen",
"[",
"guid",
"]",
")",
"seen",
"[",
"guid",
"]",
"=",
"{",
"}",
";",
"if",
"(",
"seen",
"[",
"guid",
"]",
"[",
"depKey",
"]",
")",
"return",
";",
"seen",
"[",
"guid",
"]",
"[",
"depKey",
"]",
"=",
"true",
";",
"var",
"deps",
"=",
"meta",
".",
"deps",
";",
"deps",
"=",
"deps",
"&&",
"deps",
"[",
"depKey",
"]",
";",
"if",
"(",
"deps",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"deps",
")",
"{",
"if",
"(",
"DEP_SKIP",
"[",
"key",
"]",
")",
"continue",
";",
"method",
"(",
"obj",
",",
"key",
")",
";",
"}",
"}",
"}"
]
| skip some keys and toString @private | [
"skip",
"some",
"keys",
"and",
"toString"
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L2046-L2061 |
45,366 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | actionSetFor | function actionSetFor(obj, eventName, target, writable) {
return metaPath(obj, ['listeners', eventName, guidFor(target)], writable);
} | javascript | function actionSetFor(obj, eventName, target, writable) {
return metaPath(obj, ['listeners', eventName, guidFor(target)], writable);
} | [
"function",
"actionSetFor",
"(",
"obj",
",",
"eventName",
",",
"target",
",",
"writable",
")",
"{",
"return",
"metaPath",
"(",
"obj",
",",
"[",
"'listeners'",
",",
"eventName",
",",
"guidFor",
"(",
"target",
")",
"]",
",",
"writable",
")",
";",
"}"
]
| Gets the set of all actions, keyed on the guid of each action's method property. @private | [
"Gets",
"the",
"set",
"of",
"all",
"actions",
"keyed",
"on",
"the",
"guid",
"of",
"each",
"action",
"s",
"method",
"property",
"."
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L3122-L3124 |
45,367 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | targetSetFor | function targetSetFor(obj, eventName) {
var listenerSet = meta(obj, false).listeners;
if (!listenerSet) { return false; }
return listenerSet[eventName] || false;
} | javascript | function targetSetFor(obj, eventName) {
var listenerSet = meta(obj, false).listeners;
if (!listenerSet) { return false; }
return listenerSet[eventName] || false;
} | [
"function",
"targetSetFor",
"(",
"obj",
",",
"eventName",
")",
"{",
"var",
"listenerSet",
"=",
"meta",
"(",
"obj",
",",
"false",
")",
".",
"listeners",
";",
"if",
"(",
"!",
"listenerSet",
")",
"{",
"return",
"false",
";",
"}",
"return",
"listenerSet",
"[",
"eventName",
"]",
"||",
"false",
";",
"}"
]
| Gets the set of all targets, keyed on the guid of each action's target property. @private | [
"Gets",
"the",
"set",
"of",
"all",
"targets",
"keyed",
"on",
"the",
"guid",
"of",
"each",
"action",
"s",
"target",
"property",
"."
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L3129-L3134 |
45,368 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | addListener | function addListener(obj, eventName, target, method) {
Ember.assert("You must pass at least an object and event name to Ember.addListener", !!obj && !!eventName);
if (!method && 'function' === typeof target) {
method = target;
target = null;
}
var actionSet = actionSetFor(obj, eventName, target, true),
methodGuid = guidFor(method);
if (!actionSet[methodGuid]) {
actionSet[methodGuid] = { target: target, method: method };
}
if ('function' === typeof obj.didAddListener) {
obj.didAddListener(eventName, target, method);
}
} | javascript | function addListener(obj, eventName, target, method) {
Ember.assert("You must pass at least an object and event name to Ember.addListener", !!obj && !!eventName);
if (!method && 'function' === typeof target) {
method = target;
target = null;
}
var actionSet = actionSetFor(obj, eventName, target, true),
methodGuid = guidFor(method);
if (!actionSet[methodGuid]) {
actionSet[methodGuid] = { target: target, method: method };
}
if ('function' === typeof obj.didAddListener) {
obj.didAddListener(eventName, target, method);
}
} | [
"function",
"addListener",
"(",
"obj",
",",
"eventName",
",",
"target",
",",
"method",
")",
"{",
"Ember",
".",
"assert",
"(",
"\"You must pass at least an object and event name to Ember.addListener\"",
",",
"!",
"!",
"obj",
"&&",
"!",
"!",
"eventName",
")",
";",
"if",
"(",
"!",
"method",
"&&",
"'function'",
"===",
"typeof",
"target",
")",
"{",
"method",
"=",
"target",
";",
"target",
"=",
"null",
";",
"}",
"var",
"actionSet",
"=",
"actionSetFor",
"(",
"obj",
",",
"eventName",
",",
"target",
",",
"true",
")",
",",
"methodGuid",
"=",
"guidFor",
"(",
"method",
")",
";",
"if",
"(",
"!",
"actionSet",
"[",
"methodGuid",
"]",
")",
"{",
"actionSet",
"[",
"methodGuid",
"]",
"=",
"{",
"target",
":",
"target",
",",
"method",
":",
"method",
"}",
";",
"}",
"if",
"(",
"'function'",
"===",
"typeof",
"obj",
".",
"didAddListener",
")",
"{",
"obj",
".",
"didAddListener",
"(",
"eventName",
",",
"target",
",",
"method",
")",
";",
"}",
"}"
]
| The sendEvent arguments > 2 are passed to an event listener.
@memberOf Ember | [
"The",
"sendEvent",
"arguments",
">",
"2",
"are",
"passed",
"to",
"an",
"event",
"listener",
"."
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L3185-L3203 |
45,369 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | watchedEvents | function watchedEvents(obj) {
var listeners = meta(obj, false).listeners, ret = [];
if (listeners) {
for(var eventName in listeners) {
if (!SKIP_PROPERTIES[eventName] && listeners[eventName]) {
ret.push(eventName);
}
}
}
return ret;
} | javascript | function watchedEvents(obj) {
var listeners = meta(obj, false).listeners, ret = [];
if (listeners) {
for(var eventName in listeners) {
if (!SKIP_PROPERTIES[eventName] && listeners[eventName]) {
ret.push(eventName);
}
}
}
return ret;
} | [
"function",
"watchedEvents",
"(",
"obj",
")",
"{",
"var",
"listeners",
"=",
"meta",
"(",
"obj",
",",
"false",
")",
".",
"listeners",
",",
"ret",
"=",
"[",
"]",
";",
"if",
"(",
"listeners",
")",
"{",
"for",
"(",
"var",
"eventName",
"in",
"listeners",
")",
"{",
"if",
"(",
"!",
"SKIP_PROPERTIES",
"[",
"eventName",
"]",
"&&",
"listeners",
"[",
"eventName",
"]",
")",
"{",
"ret",
".",
"push",
"(",
"eventName",
")",
";",
"}",
"}",
"}",
"return",
"ret",
";",
"}"
]
| returns a list of currently watched events @memberOf Ember | [
"returns",
"a",
"list",
"of",
"currently",
"watched",
"events"
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L3253-L3264 |
45,370 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | function(str) {
return str.replace(STRING_CAMELIZE_REGEXP, function(match, separator, chr) {
return chr ? chr.toUpperCase() : '';
});
} | javascript | function(str) {
return str.replace(STRING_CAMELIZE_REGEXP, function(match, separator, chr) {
return chr ? chr.toUpperCase() : '';
});
} | [
"function",
"(",
"str",
")",
"{",
"return",
"str",
".",
"replace",
"(",
"STRING_CAMELIZE_REGEXP",
",",
"function",
"(",
"match",
",",
"separator",
",",
"chr",
")",
"{",
"return",
"chr",
"?",
"chr",
".",
"toUpperCase",
"(",
")",
":",
"''",
";",
"}",
")",
";",
"}"
]
| Returns the lowerCaseCamel form of a string.
'innerHTML'.camelize() => 'innerHTML'
'action_name'.camelize() => 'actionName'
'css-class-name'.camelize() => 'cssClassName'
'my favorite items'.camelize() => 'myFavoriteItems'
@param {String} str
The string to camelize.
@returns {String} the camelized string. | [
"Returns",
"the",
"lowerCaseCamel",
"form",
"of",
"a",
"string",
"."
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L5571-L5575 |
|
45,371 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | function() {
if (this.isDestroying) { return; }
this.isDestroying = true;
if (this.willDestroy) { this.willDestroy(); }
set(this, 'isDestroyed', true);
Ember.run.schedule('destroy', this, this._scheduledDestroy);
return this;
} | javascript | function() {
if (this.isDestroying) { return; }
this.isDestroying = true;
if (this.willDestroy) { this.willDestroy(); }
set(this, 'isDestroyed', true);
Ember.run.schedule('destroy', this, this._scheduledDestroy);
return this;
} | [
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"isDestroying",
")",
"{",
"return",
";",
"}",
"this",
".",
"isDestroying",
"=",
"true",
";",
"if",
"(",
"this",
".",
"willDestroy",
")",
"{",
"this",
".",
"willDestroy",
"(",
")",
";",
"}",
"set",
"(",
"this",
",",
"'isDestroyed'",
",",
"true",
")",
";",
"Ember",
".",
"run",
".",
"schedule",
"(",
"'destroy'",
",",
"this",
",",
"this",
".",
"_scheduledDestroy",
")",
";",
"return",
"this",
";",
"}"
]
| Destroys an object by setting the isDestroyed flag and removing its
metadata, which effectively destroys observers and bindings.
If you try to set a property on a destroyed object, an exception will be
raised.
Note that destruction is scheduled for the end of the run loop and does not
happen immediately.
@returns {Ember.Object} receiver | [
"Destroys",
"an",
"object",
"by",
"setting",
"the",
"isDestroyed",
"flag",
"and",
"removing",
"its",
"metadata",
"which",
"effectively",
"destroys",
"observers",
"and",
"bindings",
"."
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L8322-L8332 |
|
45,372 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | function(router) {
var properties = Ember.A(Ember.keys(this)),
injections = get(this.constructor, 'injections'),
namespace = this, controller, name;
if (!router && Ember.Router.detect(namespace['Router'])) {
router = namespace['Router'].create();
this._createdRouter = router;
}
if (router) {
set(this, 'router', router);
// By default, the router's namespace is the current application.
//
// This allows it to find model classes when a state has a
// route like `/posts/:post_id`. In that case, it would first
// convert `post_id` into `Post`, and then look it up on its
// namespace.
set(router, 'namespace', this);
}
Ember.runLoadHooks('application', this);
injections.forEach(function(injection) {
properties.forEach(function(property) {
injection[1](namespace, router, property);
});
});
if (router && router instanceof Ember.Router) {
this.startRouting(router);
}
} | javascript | function(router) {
var properties = Ember.A(Ember.keys(this)),
injections = get(this.constructor, 'injections'),
namespace = this, controller, name;
if (!router && Ember.Router.detect(namespace['Router'])) {
router = namespace['Router'].create();
this._createdRouter = router;
}
if (router) {
set(this, 'router', router);
// By default, the router's namespace is the current application.
//
// This allows it to find model classes when a state has a
// route like `/posts/:post_id`. In that case, it would first
// convert `post_id` into `Post`, and then look it up on its
// namespace.
set(router, 'namespace', this);
}
Ember.runLoadHooks('application', this);
injections.forEach(function(injection) {
properties.forEach(function(property) {
injection[1](namespace, router, property);
});
});
if (router && router instanceof Ember.Router) {
this.startRouting(router);
}
} | [
"function",
"(",
"router",
")",
"{",
"var",
"properties",
"=",
"Ember",
".",
"A",
"(",
"Ember",
".",
"keys",
"(",
"this",
")",
")",
",",
"injections",
"=",
"get",
"(",
"this",
".",
"constructor",
",",
"'injections'",
")",
",",
"namespace",
"=",
"this",
",",
"controller",
",",
"name",
";",
"if",
"(",
"!",
"router",
"&&",
"Ember",
".",
"Router",
".",
"detect",
"(",
"namespace",
"[",
"'Router'",
"]",
")",
")",
"{",
"router",
"=",
"namespace",
"[",
"'Router'",
"]",
".",
"create",
"(",
")",
";",
"this",
".",
"_createdRouter",
"=",
"router",
";",
"}",
"if",
"(",
"router",
")",
"{",
"set",
"(",
"this",
",",
"'router'",
",",
"router",
")",
";",
"// By default, the router's namespace is the current application.",
"//",
"// This allows it to find model classes when a state has a",
"// route like `/posts/:post_id`. In that case, it would first",
"// convert `post_id` into `Post`, and then look it up on its",
"// namespace.",
"set",
"(",
"router",
",",
"'namespace'",
",",
"this",
")",
";",
"}",
"Ember",
".",
"runLoadHooks",
"(",
"'application'",
",",
"this",
")",
";",
"injections",
".",
"forEach",
"(",
"function",
"(",
"injection",
")",
"{",
"properties",
".",
"forEach",
"(",
"function",
"(",
"property",
")",
"{",
"injection",
"[",
"1",
"]",
"(",
"namespace",
",",
"router",
",",
"property",
")",
";",
"}",
")",
";",
"}",
")",
";",
"if",
"(",
"router",
"&&",
"router",
"instanceof",
"Ember",
".",
"Router",
")",
"{",
"this",
".",
"startRouting",
"(",
"router",
")",
";",
"}",
"}"
]
| Instantiate all controllers currently available on the namespace
and inject them onto a router.
Example:
App.PostsController = Ember.ArrayController.extend();
App.CommentsController = Ember.ArrayController.extend();
var router = Ember.Router.create({
...
});
App.initialize(router);
router.get('postsController') // <App.PostsController:ember1234>
router.get('commentsController') // <App.CommentsController:ember1235>
router.get('postsController.router') // router | [
"Instantiate",
"all",
"controllers",
"currently",
"available",
"on",
"the",
"namespace",
"and",
"inject",
"them",
"onto",
"a",
"router",
"."
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L10220-L10253 |
|
45,373 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | function(tagName, parent, fn, other) {
var buffer = new Ember._RenderBuffer(tagName);
buffer.parentBuffer = parent;
if (other) { Ember.$.extend(buffer, other); }
if (fn) { fn.call(this, buffer); }
return buffer;
} | javascript | function(tagName, parent, fn, other) {
var buffer = new Ember._RenderBuffer(tagName);
buffer.parentBuffer = parent;
if (other) { Ember.$.extend(buffer, other); }
if (fn) { fn.call(this, buffer); }
return buffer;
} | [
"function",
"(",
"tagName",
",",
"parent",
",",
"fn",
",",
"other",
")",
"{",
"var",
"buffer",
"=",
"new",
"Ember",
".",
"_RenderBuffer",
"(",
"tagName",
")",
";",
"buffer",
".",
"parentBuffer",
"=",
"parent",
";",
"if",
"(",
"other",
")",
"{",
"Ember",
".",
"$",
".",
"extend",
"(",
"buffer",
",",
"other",
")",
";",
"}",
"if",
"(",
"fn",
")",
"{",
"fn",
".",
"call",
"(",
"this",
",",
"buffer",
")",
";",
"}",
"return",
"buffer",
";",
"}"
]
| Create a new child render buffer from a parent buffer. Optionally set
additional properties on the buffer. Optionally invoke a callback
with the newly created buffer.
This is a primitive method used by other public methods: `begin`,
`prepend`, `replaceWith`, `insertAfter`.
@private
@param {String} tagName Tag name to use for the child buffer's element
@param {Ember._RenderBuffer} parent The parent render buffer that this
buffer should be appended to.
@param {Function} fn A callback to invoke with the newly created buffer.
@param {Object} other Additional properties to add to the newly created
buffer. | [
"Create",
"a",
"new",
"child",
"render",
"buffer",
"from",
"a",
"parent",
"buffer",
".",
"Optionally",
"set",
"additional",
"properties",
"on",
"the",
"buffer",
".",
"Optionally",
"invoke",
"a",
"callback",
"with",
"the",
"newly",
"created",
"buffer",
"."
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L10914-L10922 |
|
45,374 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | function(newBuffer) {
var parent = this.parentBuffer;
if (!parent) { return; }
var childBuffers = parent.childBuffers;
var index = indexOf.call(childBuffers, this);
if (newBuffer) {
childBuffers.splice(index, 1, newBuffer);
} else {
childBuffers.splice(index, 1);
}
} | javascript | function(newBuffer) {
var parent = this.parentBuffer;
if (!parent) { return; }
var childBuffers = parent.childBuffers;
var index = indexOf.call(childBuffers, this);
if (newBuffer) {
childBuffers.splice(index, 1, newBuffer);
} else {
childBuffers.splice(index, 1);
}
} | [
"function",
"(",
"newBuffer",
")",
"{",
"var",
"parent",
"=",
"this",
".",
"parentBuffer",
";",
"if",
"(",
"!",
"parent",
")",
"{",
"return",
";",
"}",
"var",
"childBuffers",
"=",
"parent",
".",
"childBuffers",
";",
"var",
"index",
"=",
"indexOf",
".",
"call",
"(",
"childBuffers",
",",
"this",
")",
";",
"if",
"(",
"newBuffer",
")",
"{",
"childBuffers",
".",
"splice",
"(",
"index",
",",
"1",
",",
"newBuffer",
")",
";",
"}",
"else",
"{",
"childBuffers",
".",
"splice",
"(",
"index",
",",
"1",
")",
";",
"}",
"}"
]
| Replace the current buffer with a new buffer. This is a primitive
used by `remove`, which passes `null` for `newBuffer`, and `replaceWith`,
which passes the new buffer it created.
@private
@param {Ember._RenderBuffer} buffer The buffer to insert in place of
the existing buffer. | [
"Replace",
"the",
"current",
"buffer",
"with",
"a",
"new",
"buffer",
".",
"This",
"is",
"a",
"primitive",
"used",
"by",
"remove",
"which",
"passes",
"null",
"for",
"newBuffer",
"and",
"replaceWith",
"which",
"passes",
"the",
"new",
"buffer",
"it",
"created",
"."
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L10933-L10946 |
|
45,375 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | function(tagName) {
var parentBuffer = get(this, 'parentBuffer');
return this.newBuffer(tagName, parentBuffer, function(buffer) {
var siblings = parentBuffer.childBuffers;
var index = indexOf.call(siblings, this);
siblings.splice(index + 1, 0, buffer);
});
} | javascript | function(tagName) {
var parentBuffer = get(this, 'parentBuffer');
return this.newBuffer(tagName, parentBuffer, function(buffer) {
var siblings = parentBuffer.childBuffers;
var index = indexOf.call(siblings, this);
siblings.splice(index + 1, 0, buffer);
});
} | [
"function",
"(",
"tagName",
")",
"{",
"var",
"parentBuffer",
"=",
"get",
"(",
"this",
",",
"'parentBuffer'",
")",
";",
"return",
"this",
".",
"newBuffer",
"(",
"tagName",
",",
"parentBuffer",
",",
"function",
"(",
"buffer",
")",
"{",
"var",
"siblings",
"=",
"parentBuffer",
".",
"childBuffers",
";",
"var",
"index",
"=",
"indexOf",
".",
"call",
"(",
"siblings",
",",
"this",
")",
";",
"siblings",
".",
"splice",
"(",
"index",
"+",
"1",
",",
"0",
",",
"buffer",
")",
";",
"}",
")",
";",
"}"
]
| Insert a new render buffer after the current render buffer.
@param {String} tagName Tag name to use for the new buffer's element | [
"Insert",
"a",
"new",
"render",
"buffer",
"after",
"the",
"current",
"render",
"buffer",
"."
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L10991-L10999 |
|
45,376 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | function(name, context) {
// Normalize arguments. Supported arguments:
//
// name
// name, context
// outletName, name
// outletName, name, context
// options
//
// The options hash has the following keys:
//
// name: the name of the controller and view
// to use. If this is passed, the name
// determines the view and controller.
// outletName: the name of the outlet to
// fill in. default: 'view'
// viewClass: the class of the view to instantiate
// controller: the controller instance to pass
// to the view
// context: an object that should become the
// controller's `content` and thus the
// template's context.
var outletName, viewClass, view, controller, options;
if (Ember.typeOf(context) === 'string') {
outletName = name;
name = context;
context = arguments[2];
}
if (arguments.length === 1) {
if (Ember.typeOf(name) === 'object') {
options = name;
outletName = options.outletName;
name = options.name;
viewClass = options.viewClass;
controller = options.controller;
context = options.context;
}
} else {
options = {};
}
outletName = outletName || 'view';
Ember.assert("You must supply a name or a view class to connectOutlets, but not both", (!!name && !viewClass && !controller) || (!name && !!viewClass));
if (name) {
var namespace = get(this, 'namespace'),
controllers = get(this, 'controllers');
var viewClassName = name.charAt(0).toUpperCase() + name.substr(1) + "View";
viewClass = get(namespace, viewClassName);
controller = get(controllers, name + 'Controller');
Ember.assert("The name you supplied " + name + " did not resolve to a view " + viewClassName, !!viewClass);
Ember.assert("The name you supplied " + name + " did not resolve to a controller " + name + 'Controller', (!!controller && !!context) || !context);
}
if (controller && context) { controller.set('content', context); }
view = viewClass.create();
if (controller) { set(view, 'controller', controller); }
set(this, outletName, view);
return view;
} | javascript | function(name, context) {
// Normalize arguments. Supported arguments:
//
// name
// name, context
// outletName, name
// outletName, name, context
// options
//
// The options hash has the following keys:
//
// name: the name of the controller and view
// to use. If this is passed, the name
// determines the view and controller.
// outletName: the name of the outlet to
// fill in. default: 'view'
// viewClass: the class of the view to instantiate
// controller: the controller instance to pass
// to the view
// context: an object that should become the
// controller's `content` and thus the
// template's context.
var outletName, viewClass, view, controller, options;
if (Ember.typeOf(context) === 'string') {
outletName = name;
name = context;
context = arguments[2];
}
if (arguments.length === 1) {
if (Ember.typeOf(name) === 'object') {
options = name;
outletName = options.outletName;
name = options.name;
viewClass = options.viewClass;
controller = options.controller;
context = options.context;
}
} else {
options = {};
}
outletName = outletName || 'view';
Ember.assert("You must supply a name or a view class to connectOutlets, but not both", (!!name && !viewClass && !controller) || (!name && !!viewClass));
if (name) {
var namespace = get(this, 'namespace'),
controllers = get(this, 'controllers');
var viewClassName = name.charAt(0).toUpperCase() + name.substr(1) + "View";
viewClass = get(namespace, viewClassName);
controller = get(controllers, name + 'Controller');
Ember.assert("The name you supplied " + name + " did not resolve to a view " + viewClassName, !!viewClass);
Ember.assert("The name you supplied " + name + " did not resolve to a controller " + name + 'Controller', (!!controller && !!context) || !context);
}
if (controller && context) { controller.set('content', context); }
view = viewClass.create();
if (controller) { set(view, 'controller', controller); }
set(this, outletName, view);
return view;
} | [
"function",
"(",
"name",
",",
"context",
")",
"{",
"// Normalize arguments. Supported arguments:",
"//",
"// name",
"// name, context",
"// outletName, name",
"// outletName, name, context",
"// options",
"//",
"// The options hash has the following keys:",
"//",
"// name: the name of the controller and view",
"// to use. If this is passed, the name",
"// determines the view and controller.",
"// outletName: the name of the outlet to",
"// fill in. default: 'view'",
"// viewClass: the class of the view to instantiate",
"// controller: the controller instance to pass",
"// to the view",
"// context: an object that should become the",
"// controller's `content` and thus the",
"// template's context.",
"var",
"outletName",
",",
"viewClass",
",",
"view",
",",
"controller",
",",
"options",
";",
"if",
"(",
"Ember",
".",
"typeOf",
"(",
"context",
")",
"===",
"'string'",
")",
"{",
"outletName",
"=",
"name",
";",
"name",
"=",
"context",
";",
"context",
"=",
"arguments",
"[",
"2",
"]",
";",
"}",
"if",
"(",
"arguments",
".",
"length",
"===",
"1",
")",
"{",
"if",
"(",
"Ember",
".",
"typeOf",
"(",
"name",
")",
"===",
"'object'",
")",
"{",
"options",
"=",
"name",
";",
"outletName",
"=",
"options",
".",
"outletName",
";",
"name",
"=",
"options",
".",
"name",
";",
"viewClass",
"=",
"options",
".",
"viewClass",
";",
"controller",
"=",
"options",
".",
"controller",
";",
"context",
"=",
"options",
".",
"context",
";",
"}",
"}",
"else",
"{",
"options",
"=",
"{",
"}",
";",
"}",
"outletName",
"=",
"outletName",
"||",
"'view'",
";",
"Ember",
".",
"assert",
"(",
"\"You must supply a name or a view class to connectOutlets, but not both\"",
",",
"(",
"!",
"!",
"name",
"&&",
"!",
"viewClass",
"&&",
"!",
"controller",
")",
"||",
"(",
"!",
"name",
"&&",
"!",
"!",
"viewClass",
")",
")",
";",
"if",
"(",
"name",
")",
"{",
"var",
"namespace",
"=",
"get",
"(",
"this",
",",
"'namespace'",
")",
",",
"controllers",
"=",
"get",
"(",
"this",
",",
"'controllers'",
")",
";",
"var",
"viewClassName",
"=",
"name",
".",
"charAt",
"(",
"0",
")",
".",
"toUpperCase",
"(",
")",
"+",
"name",
".",
"substr",
"(",
"1",
")",
"+",
"\"View\"",
";",
"viewClass",
"=",
"get",
"(",
"namespace",
",",
"viewClassName",
")",
";",
"controller",
"=",
"get",
"(",
"controllers",
",",
"name",
"+",
"'Controller'",
")",
";",
"Ember",
".",
"assert",
"(",
"\"The name you supplied \"",
"+",
"name",
"+",
"\" did not resolve to a view \"",
"+",
"viewClassName",
",",
"!",
"!",
"viewClass",
")",
";",
"Ember",
".",
"assert",
"(",
"\"The name you supplied \"",
"+",
"name",
"+",
"\" did not resolve to a controller \"",
"+",
"name",
"+",
"'Controller'",
",",
"(",
"!",
"!",
"controller",
"&&",
"!",
"!",
"context",
")",
"||",
"!",
"context",
")",
";",
"}",
"if",
"(",
"controller",
"&&",
"context",
")",
"{",
"controller",
".",
"set",
"(",
"'content'",
",",
"context",
")",
";",
"}",
"view",
"=",
"viewClass",
".",
"create",
"(",
")",
";",
"if",
"(",
"controller",
")",
"{",
"set",
"(",
"view",
",",
"'controller'",
",",
"controller",
")",
";",
"}",
"set",
"(",
"this",
",",
"outletName",
",",
"view",
")",
";",
"return",
"view",
";",
"}"
]
| `connectOutlet` creates a new instance of a provided view
class, wires it up to its associated controller, and
assigns the new view to a property on the current controller.
The purpose of this method is to enable views that use
outlets to quickly assign new views for a given outlet.
For example, an application view's template may look like
this:
<h1>My Blog</h1>
{{outlet}}
The view for this outlet is specified by assigning a
`view` property to the application's controller. The
following code will assign a new `App.PostsView` to
that outlet:
applicationController.connectOutlet('posts');
In general, you will also want to assign a controller
to the newly created view. By convention, a controller
named `postsController` will be assigned as the view's
controller.
In an application initialized using `app.initialize(router)`,
`connectOutlet` will look for `postsController` on the
router. The initialization process will automatically
create an instance of `App.PostsController` called
`postsController`, so you don't need to do anything
beyond `connectOutlet` to assign your view and wire it
up to its associated controller.
You can supply a `content` for the controller by supplying
a final argument after the view class:
applicationController.connectOutlet('posts', App.Post.find());
You can specify a particular outlet to use. For example, if your main
template looks like:
<h1>My Blog</h1>
{{outlet master}}
{{outlet detail}}
You can assign an `App.PostsView` to the master outlet:
applicationController.connectOutlet({
name: 'posts',
outletName: 'master',
context: App.Post.find()
});
You can write this as:
applicationController.connectOutlet('master', 'posts', App.Post.find());
@param {String} outletName a name for the outlet to set
@param {String} name a view/controller pair name
@param {Object} context a context object to assign to the
controller's `content` property, if a controller can be
found (optional) | [
"connectOutlet",
"creates",
"a",
"new",
"instance",
"of",
"a",
"provided",
"view",
"class",
"wires",
"it",
"up",
"to",
"its",
"associated",
"controller",
"and",
"assigns",
"the",
"new",
"view",
"to",
"a",
"property",
"on",
"the",
"current",
"controller",
"."
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L11396-L11462 |
|
45,377 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | function() {
var controllers = get(this, 'controllers'),
controllerNames = Array.prototype.slice.apply(arguments),
controllerName;
for (var i=0, l=controllerNames.length; i<l; i++) {
controllerName = controllerNames[i] + 'Controller';
set(this, controllerName, get(controllers, controllerName));
}
} | javascript | function() {
var controllers = get(this, 'controllers'),
controllerNames = Array.prototype.slice.apply(arguments),
controllerName;
for (var i=0, l=controllerNames.length; i<l; i++) {
controllerName = controllerNames[i] + 'Controller';
set(this, controllerName, get(controllers, controllerName));
}
} | [
"function",
"(",
")",
"{",
"var",
"controllers",
"=",
"get",
"(",
"this",
",",
"'controllers'",
")",
",",
"controllerNames",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"apply",
"(",
"arguments",
")",
",",
"controllerName",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"controllerNames",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"controllerName",
"=",
"controllerNames",
"[",
"i",
"]",
"+",
"'Controller'",
";",
"set",
"(",
"this",
",",
"controllerName",
",",
"get",
"(",
"controllers",
",",
"controllerName",
")",
")",
";",
"}",
"}"
]
| Convenience method to connect controllers. This method makes other controllers
available on the controller the method was invoked on.
For example, to make the `personController` and the `postController` available
on the `overviewController`, you would call:
overviewController.connectControllers('person', 'post');
@param {String...} controllerNames the controllers to make available | [
"Convenience",
"method",
"to",
"connect",
"controllers",
".",
"This",
"method",
"makes",
"other",
"controllers",
"available",
"on",
"the",
"controller",
"the",
"method",
"was",
"invoked",
"on",
"."
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L11475-L11484 |
|
45,378 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | function(buffer) {
var attributeBindings = get(this, 'attributeBindings'),
attributeValue, elem, type;
if (!attributeBindings) { return; }
a_forEach(attributeBindings, function(binding) {
var split = binding.split(':'),
property = split[0],
attributeName = split[1] || property;
// Create an observer to add/remove/change the attribute if the
// JavaScript property changes.
var observer = function() {
elem = this.$();
if (!elem) { return; }
attributeValue = get(this, property);
Ember.View.applyAttributeBindings(elem, attributeName, attributeValue);
};
addObserver(this, property, observer);
// Determine the current value and add it to the render buffer
// if necessary.
attributeValue = get(this, property);
Ember.View.applyAttributeBindings(buffer, attributeName, attributeValue);
}, this);
} | javascript | function(buffer) {
var attributeBindings = get(this, 'attributeBindings'),
attributeValue, elem, type;
if (!attributeBindings) { return; }
a_forEach(attributeBindings, function(binding) {
var split = binding.split(':'),
property = split[0],
attributeName = split[1] || property;
// Create an observer to add/remove/change the attribute if the
// JavaScript property changes.
var observer = function() {
elem = this.$();
if (!elem) { return; }
attributeValue = get(this, property);
Ember.View.applyAttributeBindings(elem, attributeName, attributeValue);
};
addObserver(this, property, observer);
// Determine the current value and add it to the render buffer
// if necessary.
attributeValue = get(this, property);
Ember.View.applyAttributeBindings(buffer, attributeName, attributeValue);
}, this);
} | [
"function",
"(",
"buffer",
")",
"{",
"var",
"attributeBindings",
"=",
"get",
"(",
"this",
",",
"'attributeBindings'",
")",
",",
"attributeValue",
",",
"elem",
",",
"type",
";",
"if",
"(",
"!",
"attributeBindings",
")",
"{",
"return",
";",
"}",
"a_forEach",
"(",
"attributeBindings",
",",
"function",
"(",
"binding",
")",
"{",
"var",
"split",
"=",
"binding",
".",
"split",
"(",
"':'",
")",
",",
"property",
"=",
"split",
"[",
"0",
"]",
",",
"attributeName",
"=",
"split",
"[",
"1",
"]",
"||",
"property",
";",
"// Create an observer to add/remove/change the attribute if the",
"// JavaScript property changes.",
"var",
"observer",
"=",
"function",
"(",
")",
"{",
"elem",
"=",
"this",
".",
"$",
"(",
")",
";",
"if",
"(",
"!",
"elem",
")",
"{",
"return",
";",
"}",
"attributeValue",
"=",
"get",
"(",
"this",
",",
"property",
")",
";",
"Ember",
".",
"View",
".",
"applyAttributeBindings",
"(",
"elem",
",",
"attributeName",
",",
"attributeValue",
")",
";",
"}",
";",
"addObserver",
"(",
"this",
",",
"property",
",",
"observer",
")",
";",
"// Determine the current value and add it to the render buffer",
"// if necessary.",
"attributeValue",
"=",
"get",
"(",
"this",
",",
"property",
")",
";",
"Ember",
".",
"View",
".",
"applyAttributeBindings",
"(",
"buffer",
",",
"attributeName",
",",
"attributeValue",
")",
";",
"}",
",",
"this",
")",
";",
"}"
]
| Iterates through the view's attribute bindings, sets up observers for each,
then applies the current value of the attributes to the passed render buffer.
@param {Ember.RenderBuffer} buffer | [
"Iterates",
"through",
"the",
"view",
"s",
"attribute",
"bindings",
"sets",
"up",
"observers",
"for",
"each",
"then",
"applies",
"the",
"current",
"value",
"of",
"the",
"attributes",
"to",
"the",
"passed",
"render",
"buffer",
"."
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L12521-L12550 |
|
45,379 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | function(tagName) {
tagName = tagName || get(this, 'tagName');
// Explicitly check for null or undefined, as tagName
// may be an empty string, which would evaluate to false.
if (tagName === null || tagName === undefined) {
tagName = 'div';
}
return Ember.RenderBuffer(tagName);
} | javascript | function(tagName) {
tagName = tagName || get(this, 'tagName');
// Explicitly check for null or undefined, as tagName
// may be an empty string, which would evaluate to false.
if (tagName === null || tagName === undefined) {
tagName = 'div';
}
return Ember.RenderBuffer(tagName);
} | [
"function",
"(",
"tagName",
")",
"{",
"tagName",
"=",
"tagName",
"||",
"get",
"(",
"this",
",",
"'tagName'",
")",
";",
"// Explicitly check for null or undefined, as tagName",
"// may be an empty string, which would evaluate to false.",
"if",
"(",
"tagName",
"===",
"null",
"||",
"tagName",
"===",
"undefined",
")",
"{",
"tagName",
"=",
"'div'",
";",
"}",
"return",
"Ember",
".",
"RenderBuffer",
"(",
"tagName",
")",
";",
"}"
]
| Creates a new renderBuffer with the passed tagName. You can override this
method to provide further customization to the buffer if needed. Normally
you will not need to call or override this method.
@returns {Ember.RenderBuffer} | [
"Creates",
"a",
"new",
"renderBuffer",
"with",
"the",
"passed",
"tagName",
".",
"You",
"can",
"override",
"this",
"method",
"to",
"provide",
"further",
"customization",
"to",
"the",
"buffer",
"if",
"needed",
".",
"Normally",
"you",
"will",
"not",
"need",
"to",
"call",
"or",
"override",
"this",
"method",
"."
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L12790-L12800 |
|
45,380 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | function(view) {
Ember.deprecate("Something you did caused a view to re-render after it rendered but before it was inserted into the DOM. Because this is avoidable and the cause of significant performance issues in applications, this behavior is deprecated. If you want to use the debugger to find out what caused this, you can set ENV.RAISE_ON_DEPRECATION to true.");
view._notifyWillRerender();
view.clearRenderedChildren();
view.renderToBuffer(view.buffer, 'replaceWith');
} | javascript | function(view) {
Ember.deprecate("Something you did caused a view to re-render after it rendered but before it was inserted into the DOM. Because this is avoidable and the cause of significant performance issues in applications, this behavior is deprecated. If you want to use the debugger to find out what caused this, you can set ENV.RAISE_ON_DEPRECATION to true.");
view._notifyWillRerender();
view.clearRenderedChildren();
view.renderToBuffer(view.buffer, 'replaceWith');
} | [
"function",
"(",
"view",
")",
"{",
"Ember",
".",
"deprecate",
"(",
"\"Something you did caused a view to re-render after it rendered but before it was inserted into the DOM. Because this is avoidable and the cause of significant performance issues in applications, this behavior is deprecated. If you want to use the debugger to find out what caused this, you can set ENV.RAISE_ON_DEPRECATION to true.\"",
")",
";",
"view",
".",
"_notifyWillRerender",
"(",
")",
";",
"view",
".",
"clearRenderedChildren",
"(",
")",
";",
"view",
".",
"renderToBuffer",
"(",
"view",
".",
"buffer",
",",
"'replaceWith'",
")",
";",
"}"
]
| when a view is rendered in a buffer, rerendering it simply replaces the existing buffer with a new one | [
"when",
"a",
"view",
"is",
"rendered",
"in",
"a",
"buffer",
"rerendering",
"it",
"simply",
"replaces",
"the",
"existing",
"buffer",
"with",
"a",
"new",
"one"
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L13747-L13754 |
|
45,381 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | function(views, start, removed) {
if (removed === 0) { return; }
var changedViews = views.slice(start, start+removed);
this.initializeViews(changedViews, null, null);
this.invokeForState('childViewsWillChange', views, start, removed);
} | javascript | function(views, start, removed) {
if (removed === 0) { return; }
var changedViews = views.slice(start, start+removed);
this.initializeViews(changedViews, null, null);
this.invokeForState('childViewsWillChange', views, start, removed);
} | [
"function",
"(",
"views",
",",
"start",
",",
"removed",
")",
"{",
"if",
"(",
"removed",
"===",
"0",
")",
"{",
"return",
";",
"}",
"var",
"changedViews",
"=",
"views",
".",
"slice",
"(",
"start",
",",
"start",
"+",
"removed",
")",
";",
"this",
".",
"initializeViews",
"(",
"changedViews",
",",
"null",
",",
"null",
")",
";",
"this",
".",
"invokeForState",
"(",
"'childViewsWillChange'",
",",
"views",
",",
"start",
",",
"removed",
")",
";",
"}"
]
| When a child view is removed, destroy its element so that
it is removed from the DOM.
The array observer that triggers this action is set up in the
`renderToBuffer` method.
@private
@param {Ember.Array} views the child views array before mutation
@param {Number} start the start position of the mutation
@param {Number} removed the number of child views removed | [
"When",
"a",
"child",
"view",
"is",
"removed",
"destroy",
"its",
"element",
"so",
"that",
"it",
"is",
"removed",
"from",
"the",
"DOM",
"."
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L14239-L14246 |
|
45,382 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | function(views, start, removed, added) {
var len = get(views, 'length');
// No new child views were added; bail out.
if (added === 0) return;
var changedViews = views.slice(start, start+added);
this.initializeViews(changedViews, this, get(this, 'templateData'));
// Let the current state handle the changes
this.invokeForState('childViewsDidChange', views, start, added);
} | javascript | function(views, start, removed, added) {
var len = get(views, 'length');
// No new child views were added; bail out.
if (added === 0) return;
var changedViews = views.slice(start, start+added);
this.initializeViews(changedViews, this, get(this, 'templateData'));
// Let the current state handle the changes
this.invokeForState('childViewsDidChange', views, start, added);
} | [
"function",
"(",
"views",
",",
"start",
",",
"removed",
",",
"added",
")",
"{",
"var",
"len",
"=",
"get",
"(",
"views",
",",
"'length'",
")",
";",
"// No new child views were added; bail out.",
"if",
"(",
"added",
"===",
"0",
")",
"return",
";",
"var",
"changedViews",
"=",
"views",
".",
"slice",
"(",
"start",
",",
"start",
"+",
"added",
")",
";",
"this",
".",
"initializeViews",
"(",
"changedViews",
",",
"this",
",",
"get",
"(",
"this",
",",
"'templateData'",
")",
")",
";",
"// Let the current state handle the changes",
"this",
".",
"invokeForState",
"(",
"'childViewsDidChange'",
",",
"views",
",",
"start",
",",
"added",
")",
";",
"}"
]
| When a child view is added, make sure the DOM gets updated appropriately.
If the view has already rendered an element, we tell the child view to
create an element and insert it into the DOM. If the enclosing container view
has already written to a buffer, but not yet converted that buffer into an
element, we insert the string representation of the child into the appropriate
place in the buffer.
@private
@param {Ember.Array} views the array of child views afte the mutation has occurred
@param {Number} start the start position of the mutation
@param {Number} removed the number of child views removed
@param {Number} the number of child views added | [
"When",
"a",
"child",
"view",
"is",
"added",
"make",
"sure",
"the",
"DOM",
"gets",
"updated",
"appropriately",
"."
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L14263-L14274 |
|
45,383 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | function(view, prev) {
if (prev) {
prev.domManager.after(prev, view);
} else {
this.domManager.prepend(this, view);
}
} | javascript | function(view, prev) {
if (prev) {
prev.domManager.after(prev, view);
} else {
this.domManager.prepend(this, view);
}
} | [
"function",
"(",
"view",
",",
"prev",
")",
"{",
"if",
"(",
"prev",
")",
"{",
"prev",
".",
"domManager",
".",
"after",
"(",
"prev",
",",
"view",
")",
";",
"}",
"else",
"{",
"this",
".",
"domManager",
".",
"prepend",
"(",
"this",
",",
"view",
")",
";",
"}",
"}"
]
| Schedules a child view to be inserted into the DOM after bindings have
finished syncing for this run loop.
@param {Ember.View} view the child view to insert
@param {Ember.View} prev the child view after which the specified view should
be inserted
@private | [
"Schedules",
"a",
"child",
"view",
"to",
"be",
"inserted",
"into",
"the",
"DOM",
"after",
"bindings",
"have",
"finished",
"syncing",
"for",
"this",
"run",
"loop",
"."
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L14295-L14301 |
|
45,384 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | function() {
this._super();
set(this, 'stateMeta', Ember.Map.create());
var initialState = get(this, 'initialState');
if (!initialState && get(this, 'states.start')) {
initialState = 'start';
}
if (initialState) {
this.transitionTo(initialState);
Ember.assert('Failed to transition to initial state "' + initialState + '"', !!get(this, 'currentState'));
}
} | javascript | function() {
this._super();
set(this, 'stateMeta', Ember.Map.create());
var initialState = get(this, 'initialState');
if (!initialState && get(this, 'states.start')) {
initialState = 'start';
}
if (initialState) {
this.transitionTo(initialState);
Ember.assert('Failed to transition to initial state "' + initialState + '"', !!get(this, 'currentState'));
}
} | [
"function",
"(",
")",
"{",
"this",
".",
"_super",
"(",
")",
";",
"set",
"(",
"this",
",",
"'stateMeta'",
",",
"Ember",
".",
"Map",
".",
"create",
"(",
")",
")",
";",
"var",
"initialState",
"=",
"get",
"(",
"this",
",",
"'initialState'",
")",
";",
"if",
"(",
"!",
"initialState",
"&&",
"get",
"(",
"this",
",",
"'states.start'",
")",
")",
"{",
"initialState",
"=",
"'start'",
";",
"}",
"if",
"(",
"initialState",
")",
"{",
"this",
".",
"transitionTo",
"(",
"initialState",
")",
";",
"Ember",
".",
"assert",
"(",
"'Failed to transition to initial state \"'",
"+",
"initialState",
"+",
"'\"'",
",",
"!",
"!",
"get",
"(",
"this",
",",
"'currentState'",
")",
")",
";",
"}",
"}"
]
| When creating a new statemanager, look for a default state to transition
into. This state can either be named `start`, or can be specified using the
`initialState` property. | [
"When",
"creating",
"a",
"new",
"statemanager",
"look",
"for",
"a",
"default",
"state",
"to",
"transition",
"into",
".",
"This",
"state",
"can",
"either",
"be",
"named",
"start",
"or",
"can",
"be",
"specified",
"using",
"the",
"initialState",
"property",
"."
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L15498-L15513 |
|
45,385 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | function(root, path) {
var parts = path.split('.'),
state = root;
for (var i=0, l=parts.length; i<l; i++) {
state = get(get(state, 'states'), parts[i]);
if (!state) { break; }
}
return state;
} | javascript | function(root, path) {
var parts = path.split('.'),
state = root;
for (var i=0, l=parts.length; i<l; i++) {
state = get(get(state, 'states'), parts[i]);
if (!state) { break; }
}
return state;
} | [
"function",
"(",
"root",
",",
"path",
")",
"{",
"var",
"parts",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
",",
"state",
"=",
"root",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"parts",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"state",
"=",
"get",
"(",
"get",
"(",
"state",
",",
"'states'",
")",
",",
"parts",
"[",
"i",
"]",
")",
";",
"if",
"(",
"!",
"state",
")",
"{",
"break",
";",
"}",
"}",
"return",
"state",
";",
"}"
]
| Finds a state by its state path.
Example:
manager = Ember.StateManager.create({
root: Ember.State.create({
dashboard: Ember.State.create()
})
});
manager.getStateByPath(manager, "root.dashboard")
returns the dashboard state
@param {Ember.State} root the state to start searching from
@param {String} path the state path to follow
@returns {Ember.State} the state at the end of the path | [
"Finds",
"a",
"state",
"by",
"its",
"state",
"path",
"."
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L15609-L15619 |
|
45,386 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | function(manager, params) {
var modelClass, routeMatcher, param;
if (modelClass = this.modelClassFor(get(manager, 'namespace'))) {
Ember.assert("Expected "+modelClass.toString()+" to implement `find` for use in '"+this.get('path')+"' `deserialize`. Please implement the `find` method or overwrite `deserialize`.", modelClass.find);
return modelClass.find(params[paramForClass(modelClass)]);
}
return params;
} | javascript | function(manager, params) {
var modelClass, routeMatcher, param;
if (modelClass = this.modelClassFor(get(manager, 'namespace'))) {
Ember.assert("Expected "+modelClass.toString()+" to implement `find` for use in '"+this.get('path')+"' `deserialize`. Please implement the `find` method or overwrite `deserialize`.", modelClass.find);
return modelClass.find(params[paramForClass(modelClass)]);
}
return params;
} | [
"function",
"(",
"manager",
",",
"params",
")",
"{",
"var",
"modelClass",
",",
"routeMatcher",
",",
"param",
";",
"if",
"(",
"modelClass",
"=",
"this",
".",
"modelClassFor",
"(",
"get",
"(",
"manager",
",",
"'namespace'",
")",
")",
")",
"{",
"Ember",
".",
"assert",
"(",
"\"Expected \"",
"+",
"modelClass",
".",
"toString",
"(",
")",
"+",
"\" to implement `find` for use in '\"",
"+",
"this",
".",
"get",
"(",
"'path'",
")",
"+",
"\"' `deserialize`. Please implement the `find` method or overwrite `deserialize`.\"",
",",
"modelClass",
".",
"find",
")",
";",
"return",
"modelClass",
".",
"find",
"(",
"params",
"[",
"paramForClass",
"(",
"modelClass",
")",
"]",
")",
";",
"}",
"return",
"params",
";",
"}"
]
| The default method that takes a `params` object and converts
it into an object.
By default, a params hash that looks like `{ post_id: 1 }`
will be looked up as `namespace.Post.find(1)`. This is
designed to work seamlessly with Ember Data, but will work
fine with any class that has a `find` method. | [
"The",
"default",
"method",
"that",
"takes",
"a",
"params",
"object",
"and",
"converts",
"it",
"into",
"an",
"object",
"."
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L16131-L16140 |
|
45,387 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | function(manager, context) {
var modelClass, routeMatcher, namespace, param, id;
if (Ember.empty(context)) { return ''; }
if (modelClass = this.modelClassFor(get(manager, 'namespace'))) {
param = paramForClass(modelClass);
id = get(context, 'id');
context = {};
context[param] = id;
}
return context;
} | javascript | function(manager, context) {
var modelClass, routeMatcher, namespace, param, id;
if (Ember.empty(context)) { return ''; }
if (modelClass = this.modelClassFor(get(manager, 'namespace'))) {
param = paramForClass(modelClass);
id = get(context, 'id');
context = {};
context[param] = id;
}
return context;
} | [
"function",
"(",
"manager",
",",
"context",
")",
"{",
"var",
"modelClass",
",",
"routeMatcher",
",",
"namespace",
",",
"param",
",",
"id",
";",
"if",
"(",
"Ember",
".",
"empty",
"(",
"context",
")",
")",
"{",
"return",
"''",
";",
"}",
"if",
"(",
"modelClass",
"=",
"this",
".",
"modelClassFor",
"(",
"get",
"(",
"manager",
",",
"'namespace'",
")",
")",
")",
"{",
"param",
"=",
"paramForClass",
"(",
"modelClass",
")",
";",
"id",
"=",
"get",
"(",
"context",
",",
"'id'",
")",
";",
"context",
"=",
"{",
"}",
";",
"context",
"[",
"param",
"]",
"=",
"id",
";",
"}",
"return",
"context",
";",
"}"
]
| The default method that takes an object and converts it into
a params hash.
By default, if there is a single dynamic segment named
`blog_post_id` and the object is a `BlogPost` with an
`id` of `12`, the serialize method will produce:
{ blog_post_id: 12 } | [
"The",
"default",
"method",
"that",
"takes",
"an",
"object",
"and",
"converts",
"it",
"into",
"a",
"params",
"hash",
"."
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L16152-L16165 |
|
45,388 | feilaoda/power | public/javascripts/vendor/javascripts/ember.js | function(root, parsedPath, options) {
var val,
path = parsedPath.path;
if (path === 'this') {
val = root;
} else if (path === '') {
val = true;
} else {
val = getPath(root, path, options);
}
return Ember.View._classStringForValue(path, val, parsedPath.className, parsedPath.falsyClassName);
} | javascript | function(root, parsedPath, options) {
var val,
path = parsedPath.path;
if (path === 'this') {
val = root;
} else if (path === '') {
val = true;
} else {
val = getPath(root, path, options);
}
return Ember.View._classStringForValue(path, val, parsedPath.className, parsedPath.falsyClassName);
} | [
"function",
"(",
"root",
",",
"parsedPath",
",",
"options",
")",
"{",
"var",
"val",
",",
"path",
"=",
"parsedPath",
".",
"path",
";",
"if",
"(",
"path",
"===",
"'this'",
")",
"{",
"val",
"=",
"root",
";",
"}",
"else",
"if",
"(",
"path",
"===",
"''",
")",
"{",
"val",
"=",
"true",
";",
"}",
"else",
"{",
"val",
"=",
"getPath",
"(",
"root",
",",
"path",
",",
"options",
")",
";",
"}",
"return",
"Ember",
".",
"View",
".",
"_classStringForValue",
"(",
"path",
",",
"val",
",",
"parsedPath",
".",
"className",
",",
"parsedPath",
".",
"falsyClassName",
")",
";",
"}"
]
| Helper method to retrieve the property from the context and determine which class string to return, based on whether it is a Boolean or not. | [
"Helper",
"method",
"to",
"retrieve",
"the",
"property",
"from",
"the",
"context",
"and",
"determine",
"which",
"class",
"string",
"to",
"return",
"based",
"on",
"whether",
"it",
"is",
"a",
"Boolean",
"or",
"not",
"."
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/ember.js#L18627-L18640 |
|
45,389 | uvworkspace/uvwlib | lib/utils/inherit.js | inherit | function inherit (base) {
if (typeof base === 'function') {
return initClass(protoize.apply(null, arguments), [], 0);
} else {
return initClass(Object.create(base), arguments, 1);
}
} | javascript | function inherit (base) {
if (typeof base === 'function') {
return initClass(protoize.apply(null, arguments), [], 0);
} else {
return initClass(Object.create(base), arguments, 1);
}
} | [
"function",
"inherit",
"(",
"base",
")",
"{",
"if",
"(",
"typeof",
"base",
"===",
"'function'",
")",
"{",
"return",
"initClass",
"(",
"protoize",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
",",
"[",
"]",
",",
"0",
")",
";",
"}",
"else",
"{",
"return",
"initClass",
"(",
"Object",
".",
"create",
"(",
"base",
")",
",",
"arguments",
",",
"1",
")",
";",
"}",
"}"
]
| inherit an ordinary prototype or classical constructor | [
"inherit",
"an",
"ordinary",
"prototype",
"or",
"classical",
"constructor"
]
| ef1893e0c9cdcaa321186dd5dc17fc2c9bd9e641 | https://github.com/uvworkspace/uvwlib/blob/ef1893e0c9cdcaa321186dd5dc17fc2c9bd9e641/lib/utils/inherit.js#L7-L13 |
45,390 | RainBirdAi/rainbird-linter | lib/reporter.js | getChalk | function getChalk(code) {
if (code.slice(0, 1) === 'I') {
return chalk.blue;
} else if (code.slice(0, 1) === 'W') {
return chalk.yellow;
} else {
return chalk.red;
}
} | javascript | function getChalk(code) {
if (code.slice(0, 1) === 'I') {
return chalk.blue;
} else if (code.slice(0, 1) === 'W') {
return chalk.yellow;
} else {
return chalk.red;
}
} | [
"function",
"getChalk",
"(",
"code",
")",
"{",
"if",
"(",
"code",
".",
"slice",
"(",
"0",
",",
"1",
")",
"===",
"'I'",
")",
"{",
"return",
"chalk",
".",
"blue",
";",
"}",
"else",
"if",
"(",
"code",
".",
"slice",
"(",
"0",
",",
"1",
")",
"===",
"'W'",
")",
"{",
"return",
"chalk",
".",
"yellow",
";",
"}",
"else",
"{",
"return",
"chalk",
".",
"red",
";",
"}",
"}"
]
| _JS Hint_ prefixes messages with a letter to determine if it's informational, a warning, or an error. By using these the correct log level can be determined | [
"_JS",
"Hint_",
"prefixes",
"messages",
"with",
"a",
"letter",
"to",
"determine",
"if",
"it",
"s",
"informational",
"a",
"warning",
"or",
"an",
"error",
".",
"By",
"using",
"these",
"the",
"correct",
"log",
"level",
"can",
"be",
"determined"
]
| 2831a0286bfe3fb956b5188f0508752c6d16a4de | https://github.com/RainBirdAi/rainbird-linter/blob/2831a0286bfe3fb956b5188f0508752c6d16a4de/lib/reporter.js#L14-L22 |
45,391 | RainBirdAi/rainbird-linter | lib/reporter.js | reporter | function reporter(error, file) {
// _JS Hint_ can sometimes call the reporter function with no error. This is
// simply ignored.
if (!error) {
return;
}
if (!(error.code in errors)) {
errors[error.code] = { reason: error.raw, count: 0 };
}
errors[error.code].count++;
totalErrors++;
console.log(getChalk(error.code)('%s: line %d, col %d, %s'),
file, error.line, error.character, error.reason);
if (error.evidence !== undefined) {
var evidence = error.evidence.trim();
console.log(chalk.grey(' %s'), evidence);
}
} | javascript | function reporter(error, file) {
// _JS Hint_ can sometimes call the reporter function with no error. This is
// simply ignored.
if (!error) {
return;
}
if (!(error.code in errors)) {
errors[error.code] = { reason: error.raw, count: 0 };
}
errors[error.code].count++;
totalErrors++;
console.log(getChalk(error.code)('%s: line %d, col %d, %s'),
file, error.line, error.character, error.reason);
if (error.evidence !== undefined) {
var evidence = error.evidence.trim();
console.log(chalk.grey(' %s'), evidence);
}
} | [
"function",
"reporter",
"(",
"error",
",",
"file",
")",
"{",
"// _JS Hint_ can sometimes call the reporter function with no error. This is",
"// simply ignored.",
"if",
"(",
"!",
"error",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"(",
"error",
".",
"code",
"in",
"errors",
")",
")",
"{",
"errors",
"[",
"error",
".",
"code",
"]",
"=",
"{",
"reason",
":",
"error",
".",
"raw",
",",
"count",
":",
"0",
"}",
";",
"}",
"errors",
"[",
"error",
".",
"code",
"]",
".",
"count",
"++",
";",
"totalErrors",
"++",
";",
"console",
".",
"log",
"(",
"getChalk",
"(",
"error",
".",
"code",
")",
"(",
"'%s: line %d, col %d, %s'",
")",
",",
"file",
",",
"error",
".",
"line",
",",
"error",
".",
"character",
",",
"error",
".",
"reason",
")",
";",
"if",
"(",
"error",
".",
"evidence",
"!==",
"undefined",
")",
"{",
"var",
"evidence",
"=",
"error",
".",
"evidence",
".",
"trim",
"(",
")",
";",
"console",
".",
"log",
"(",
"chalk",
".",
"grey",
"(",
"' %s'",
")",
",",
"evidence",
")",
";",
"}",
"}"
]
| The _JS Hint_ reporter displays a formatted line with the level determined by _JS Hint_, followed by the evidence for that error. | [
"The",
"_JS",
"Hint_",
"reporter",
"displays",
"a",
"formatted",
"line",
"with",
"the",
"level",
"determined",
"by",
"_JS",
"Hint_",
"followed",
"by",
"the",
"evidence",
"for",
"that",
"error",
"."
]
| 2831a0286bfe3fb956b5188f0508752c6d16a4de | https://github.com/RainBirdAi/rainbird-linter/blob/2831a0286bfe3fb956b5188f0508752c6d16a4de/lib/reporter.js#L27-L50 |
45,392 | RainBirdAi/rainbird-linter | lib/reporter.js | displaySummary | function displaySummary(errorCode) {
var error = errors[errorCode];
if (error.count > 1) {
console.log(getChalk(errorCode)('%s: %s (%d instances)'),
errorCode, error.reason, error.count);
} else {
console.log(getChalk(errorCode)('%s: %s (1 instance)'),
errorCode, error.reason);
}
} | javascript | function displaySummary(errorCode) {
var error = errors[errorCode];
if (error.count > 1) {
console.log(getChalk(errorCode)('%s: %s (%d instances)'),
errorCode, error.reason, error.count);
} else {
console.log(getChalk(errorCode)('%s: %s (1 instance)'),
errorCode, error.reason);
}
} | [
"function",
"displaySummary",
"(",
"errorCode",
")",
"{",
"var",
"error",
"=",
"errors",
"[",
"errorCode",
"]",
";",
"if",
"(",
"error",
".",
"count",
">",
"1",
")",
"{",
"console",
".",
"log",
"(",
"getChalk",
"(",
"errorCode",
")",
"(",
"'%s: %s (%d instances)'",
")",
",",
"errorCode",
",",
"error",
".",
"reason",
",",
"error",
".",
"count",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"getChalk",
"(",
"errorCode",
")",
"(",
"'%s: %s (1 instance)'",
")",
",",
"errorCode",
",",
"error",
".",
"reason",
")",
";",
"}",
"}"
]
| The summary output shows the JS Hint error code and the number of times it occurred. | [
"The",
"summary",
"output",
"shows",
"the",
"JS",
"Hint",
"error",
"code",
"and",
"the",
"number",
"of",
"times",
"it",
"occurred",
"."
]
| 2831a0286bfe3fb956b5188f0508752c6d16a4de | https://github.com/RainBirdAi/rainbird-linter/blob/2831a0286bfe3fb956b5188f0508752c6d16a4de/lib/reporter.js#L55-L64 |
45,393 | RainBirdAi/rainbird-linter | lib/reporter.js | callback | function callback(err, hasError) {
if (err !== null) {
console.log(chalk.red('Error running JSHint over project: %j\n'), err);
}
if (hasError) {
console.log(chalk.blue('\nSummary\n=======\n'));
for (var errorCode in errors) {
if (errors.hasOwnProperty(errorCode)) {
displaySummary(errorCode);
}
}
console.log('');
if (totalErrors > 1) {
console.log(chalk.red('Found %d errors.\n'), totalErrors);
} else {
console.log(chalk.red('Found 1 error.\n'));
}
} else {
console.log(chalk.green('No JSHint errors found.\n'));
}
} | javascript | function callback(err, hasError) {
if (err !== null) {
console.log(chalk.red('Error running JSHint over project: %j\n'), err);
}
if (hasError) {
console.log(chalk.blue('\nSummary\n=======\n'));
for (var errorCode in errors) {
if (errors.hasOwnProperty(errorCode)) {
displaySummary(errorCode);
}
}
console.log('');
if (totalErrors > 1) {
console.log(chalk.red('Found %d errors.\n'), totalErrors);
} else {
console.log(chalk.red('Found 1 error.\n'));
}
} else {
console.log(chalk.green('No JSHint errors found.\n'));
}
} | [
"function",
"callback",
"(",
"err",
",",
"hasError",
")",
"{",
"if",
"(",
"err",
"!==",
"null",
")",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"red",
"(",
"'Error running JSHint over project: %j\\n'",
")",
",",
"err",
")",
";",
"}",
"if",
"(",
"hasError",
")",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"blue",
"(",
"'\\nSummary\\n=======\\n'",
")",
")",
";",
"for",
"(",
"var",
"errorCode",
"in",
"errors",
")",
"{",
"if",
"(",
"errors",
".",
"hasOwnProperty",
"(",
"errorCode",
")",
")",
"{",
"displaySummary",
"(",
"errorCode",
")",
";",
"}",
"}",
"console",
".",
"log",
"(",
"''",
")",
";",
"if",
"(",
"totalErrors",
">",
"1",
")",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"red",
"(",
"'Found %d errors.\\n'",
")",
",",
"totalErrors",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"red",
"(",
"'Found 1 error.\\n'",
")",
")",
";",
"}",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"green",
"(",
"'No JSHint errors found.\\n'",
")",
")",
";",
"}",
"}"
]
| The callback is called when _JS Hint_ has finished parsing all files and is used to display a summary of all messages output. | [
"The",
"callback",
"is",
"called",
"when",
"_JS",
"Hint_",
"has",
"finished",
"parsing",
"all",
"files",
"and",
"is",
"used",
"to",
"display",
"a",
"summary",
"of",
"all",
"messages",
"output",
"."
]
| 2831a0286bfe3fb956b5188f0508752c6d16a4de | https://github.com/RainBirdAi/rainbird-linter/blob/2831a0286bfe3fb956b5188f0508752c6d16a4de/lib/reporter.js#L69-L93 |
45,394 | ericlathrop/game-keyboard | index.js | Keyboard | function Keyboard(keyMap) {
/**
* The current key states.
* @member {object}
* @private
*/
this.keys = {};
var self = this;
for (var kc in keyMap) {
if (keyMap.hasOwnProperty(kc)) {
this.keys[keyMap[kc]] = 0;
}
}
window.addEventListener("keydown", function(event) {
if (keyMap.hasOwnProperty(event.keyCode)) {
if (self.keys[keyMap[event.keyCode]] === 0) {
self.keys[keyMap[event.keyCode]] = 2;
}
return false;
}
});
window.addEventListener("keyup", function(event) {
if (keyMap.hasOwnProperty(event.keyCode)) {
self.keys[keyMap[event.keyCode]] = 0;
return false;
}
});
} | javascript | function Keyboard(keyMap) {
/**
* The current key states.
* @member {object}
* @private
*/
this.keys = {};
var self = this;
for (var kc in keyMap) {
if (keyMap.hasOwnProperty(kc)) {
this.keys[keyMap[kc]] = 0;
}
}
window.addEventListener("keydown", function(event) {
if (keyMap.hasOwnProperty(event.keyCode)) {
if (self.keys[keyMap[event.keyCode]] === 0) {
self.keys[keyMap[event.keyCode]] = 2;
}
return false;
}
});
window.addEventListener("keyup", function(event) {
if (keyMap.hasOwnProperty(event.keyCode)) {
self.keys[keyMap[event.keyCode]] = 0;
return false;
}
});
} | [
"function",
"Keyboard",
"(",
"keyMap",
")",
"{",
"/**\n\t * The current key states.\n\t * @member {object}\n\t * @private\n\t */",
"this",
".",
"keys",
"=",
"{",
"}",
";",
"var",
"self",
"=",
"this",
";",
"for",
"(",
"var",
"kc",
"in",
"keyMap",
")",
"{",
"if",
"(",
"keyMap",
".",
"hasOwnProperty",
"(",
"kc",
")",
")",
"{",
"this",
".",
"keys",
"[",
"keyMap",
"[",
"kc",
"]",
"]",
"=",
"0",
";",
"}",
"}",
"window",
".",
"addEventListener",
"(",
"\"keydown\"",
",",
"function",
"(",
"event",
")",
"{",
"if",
"(",
"keyMap",
".",
"hasOwnProperty",
"(",
"event",
".",
"keyCode",
")",
")",
"{",
"if",
"(",
"self",
".",
"keys",
"[",
"keyMap",
"[",
"event",
".",
"keyCode",
"]",
"]",
"===",
"0",
")",
"{",
"self",
".",
"keys",
"[",
"keyMap",
"[",
"event",
".",
"keyCode",
"]",
"]",
"=",
"2",
";",
"}",
"return",
"false",
";",
"}",
"}",
")",
";",
"window",
".",
"addEventListener",
"(",
"\"keyup\"",
",",
"function",
"(",
"event",
")",
"{",
"if",
"(",
"keyMap",
".",
"hasOwnProperty",
"(",
"event",
".",
"keyCode",
")",
")",
"{",
"self",
".",
"keys",
"[",
"keyMap",
"[",
"event",
".",
"keyCode",
"]",
"]",
"=",
"0",
";",
"return",
"false",
";",
"}",
"}",
")",
";",
"}"
]
| Keyboard input handling.
@constructor
@param {module:KeyMap} keymap A map of keycodes to descriptive key names. | [
"Keyboard",
"input",
"handling",
"."
]
| 5cf23565167b71bcdf055b54d36f064512365d90 | https://github.com/ericlathrop/game-keyboard/blob/5cf23565167b71bcdf055b54d36f064512365d90/index.js#L8-L36 |
45,395 | aheckmann/mongodb-schema-miner | lib/schema.js | merge | function merge (schema, doc, self) {
var keys = Object.keys(doc);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var type;
// if nothing in schema yet, just assign
if ('undefined' == typeof schema[key]) {
var type = self.getType(doc, key);
if (undefined !== type) {
schema[key] = type;
}
continue;
}
// exists in schema and incoming is an object?
if (isObject(doc[key])) {
if (isObject(schema[key])) {
merge(schema[key], doc[key], self);
} else {
type = self.getType(doc, key);
if (undefined !== type) {
if ('null' == schema[key]) {
schema[key] = type;
} else if (type != schema[key]) {
schema[key] = 'Mixed';
}
}
}
} else {
// exists in schema and incoming is not an object.
var type = self.getType(doc, key);
if (undefined === type) {
continue;
}
if ('null' == schema[key]) {
schema[key] = type;
} else if ('null' == type) {
// ignore
} else if (Array.isArray(schema[key]) && Array.isArray(type)) {
if (0 === schema[key].length) {
schema[key] = type;
} else if (schema[key][0] instanceof Schema && isObject(type[0])) {
// merge schemas
schema[key][0].combine(type[0]);
} else if (!equalType(schema[key], type)) {
schema[key] = ['Mixed'];
}
} else if (!equalType(schema[key], type)) {
schema[key] = 'Mixed';
}
}
}
} | javascript | function merge (schema, doc, self) {
var keys = Object.keys(doc);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var type;
// if nothing in schema yet, just assign
if ('undefined' == typeof schema[key]) {
var type = self.getType(doc, key);
if (undefined !== type) {
schema[key] = type;
}
continue;
}
// exists in schema and incoming is an object?
if (isObject(doc[key])) {
if (isObject(schema[key])) {
merge(schema[key], doc[key], self);
} else {
type = self.getType(doc, key);
if (undefined !== type) {
if ('null' == schema[key]) {
schema[key] = type;
} else if (type != schema[key]) {
schema[key] = 'Mixed';
}
}
}
} else {
// exists in schema and incoming is not an object.
var type = self.getType(doc, key);
if (undefined === type) {
continue;
}
if ('null' == schema[key]) {
schema[key] = type;
} else if ('null' == type) {
// ignore
} else if (Array.isArray(schema[key]) && Array.isArray(type)) {
if (0 === schema[key].length) {
schema[key] = type;
} else if (schema[key][0] instanceof Schema && isObject(type[0])) {
// merge schemas
schema[key][0].combine(type[0]);
} else if (!equalType(schema[key], type)) {
schema[key] = ['Mixed'];
}
} else if (!equalType(schema[key], type)) {
schema[key] = 'Mixed';
}
}
}
} | [
"function",
"merge",
"(",
"schema",
",",
"doc",
",",
"self",
")",
"{",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"doc",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"key",
"=",
"keys",
"[",
"i",
"]",
";",
"var",
"type",
";",
"// if nothing in schema yet, just assign",
"if",
"(",
"'undefined'",
"==",
"typeof",
"schema",
"[",
"key",
"]",
")",
"{",
"var",
"type",
"=",
"self",
".",
"getType",
"(",
"doc",
",",
"key",
")",
";",
"if",
"(",
"undefined",
"!==",
"type",
")",
"{",
"schema",
"[",
"key",
"]",
"=",
"type",
";",
"}",
"continue",
";",
"}",
"// exists in schema and incoming is an object?",
"if",
"(",
"isObject",
"(",
"doc",
"[",
"key",
"]",
")",
")",
"{",
"if",
"(",
"isObject",
"(",
"schema",
"[",
"key",
"]",
")",
")",
"{",
"merge",
"(",
"schema",
"[",
"key",
"]",
",",
"doc",
"[",
"key",
"]",
",",
"self",
")",
";",
"}",
"else",
"{",
"type",
"=",
"self",
".",
"getType",
"(",
"doc",
",",
"key",
")",
";",
"if",
"(",
"undefined",
"!==",
"type",
")",
"{",
"if",
"(",
"'null'",
"==",
"schema",
"[",
"key",
"]",
")",
"{",
"schema",
"[",
"key",
"]",
"=",
"type",
";",
"}",
"else",
"if",
"(",
"type",
"!=",
"schema",
"[",
"key",
"]",
")",
"{",
"schema",
"[",
"key",
"]",
"=",
"'Mixed'",
";",
"}",
"}",
"}",
"}",
"else",
"{",
"// exists in schema and incoming is not an object.",
"var",
"type",
"=",
"self",
".",
"getType",
"(",
"doc",
",",
"key",
")",
";",
"if",
"(",
"undefined",
"===",
"type",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"'null'",
"==",
"schema",
"[",
"key",
"]",
")",
"{",
"schema",
"[",
"key",
"]",
"=",
"type",
";",
"}",
"else",
"if",
"(",
"'null'",
"==",
"type",
")",
"{",
"// ignore",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"schema",
"[",
"key",
"]",
")",
"&&",
"Array",
".",
"isArray",
"(",
"type",
")",
")",
"{",
"if",
"(",
"0",
"===",
"schema",
"[",
"key",
"]",
".",
"length",
")",
"{",
"schema",
"[",
"key",
"]",
"=",
"type",
";",
"}",
"else",
"if",
"(",
"schema",
"[",
"key",
"]",
"[",
"0",
"]",
"instanceof",
"Schema",
"&&",
"isObject",
"(",
"type",
"[",
"0",
"]",
")",
")",
"{",
"// merge schemas",
"schema",
"[",
"key",
"]",
"[",
"0",
"]",
".",
"combine",
"(",
"type",
"[",
"0",
"]",
")",
";",
"}",
"else",
"if",
"(",
"!",
"equalType",
"(",
"schema",
"[",
"key",
"]",
",",
"type",
")",
")",
"{",
"schema",
"[",
"key",
"]",
"=",
"[",
"'Mixed'",
"]",
";",
"}",
"}",
"else",
"if",
"(",
"!",
"equalType",
"(",
"schema",
"[",
"key",
"]",
",",
"type",
")",
")",
"{",
"schema",
"[",
"key",
"]",
"=",
"'Mixed'",
";",
"}",
"}",
"}",
"}"
]
| Merge an object into schema | [
"Merge",
"an",
"object",
"into",
"schema"
]
| c56220bd527d82f6a1712f90b45f10828290961f | https://github.com/aheckmann/mongodb-schema-miner/blob/c56220bd527d82f6a1712f90b45f10828290961f/lib/schema.js#L33-L95 |
45,396 | aheckmann/mongodb-schema-miner | lib/schema.js | equalType | function equalType (a, b) {
if (Array.isArray(a) && Array.isArray(b)) {
if (0 === a.length || 0 === b.length) {
return true;
}
return equalType(a[0], b[0]);
}
if ('null' == a || 'null' == b) {
return true;
}
return a == b;
} | javascript | function equalType (a, b) {
if (Array.isArray(a) && Array.isArray(b)) {
if (0 === a.length || 0 === b.length) {
return true;
}
return equalType(a[0], b[0]);
}
if ('null' == a || 'null' == b) {
return true;
}
return a == b;
} | [
"function",
"equalType",
"(",
"a",
",",
"b",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"a",
")",
"&&",
"Array",
".",
"isArray",
"(",
"b",
")",
")",
"{",
"if",
"(",
"0",
"===",
"a",
".",
"length",
"||",
"0",
"===",
"b",
".",
"length",
")",
"{",
"return",
"true",
";",
"}",
"return",
"equalType",
"(",
"a",
"[",
"0",
"]",
",",
"b",
"[",
"0",
"]",
")",
";",
"}",
"if",
"(",
"'null'",
"==",
"a",
"||",
"'null'",
"==",
"b",
")",
"{",
"return",
"true",
";",
"}",
"return",
"a",
"==",
"b",
";",
"}"
]
| Determines if two types are equal | [
"Determines",
"if",
"two",
"types",
"are",
"equal"
]
| c56220bd527d82f6a1712f90b45f10828290961f | https://github.com/aheckmann/mongodb-schema-miner/blob/c56220bd527d82f6a1712f90b45f10828290961f/lib/schema.js#L272-L286 |
45,397 | aheckmann/mongodb-schema-miner | lib/schema.js | getArrayType | function getArrayType (arr, self) {
var compareDocs = false;
var type = self.getType(arr, 0);
if (isObject(type)) {
type = new Schema(arr[0]);
compareDocs = true;
}
var match = true;
var element;
var err;
for (var i = 1; i < arr.length; ++i) {
element = arr[i];
if (isObject(element)) {
if (compareDocs) {
err = type.consume(element);
if (err) throw err;
continue;
}
if ('null' == type) {
type = new Schema(element);
compareDocs = true;
continue;
}
match = false;
break;
}
if (!equalType(self.getType(arr, i), type)) {
match = false;
break;
}
}
if (match) return [type];
return ['Mixed'];
} | javascript | function getArrayType (arr, self) {
var compareDocs = false;
var type = self.getType(arr, 0);
if (isObject(type)) {
type = new Schema(arr[0]);
compareDocs = true;
}
var match = true;
var element;
var err;
for (var i = 1; i < arr.length; ++i) {
element = arr[i];
if (isObject(element)) {
if (compareDocs) {
err = type.consume(element);
if (err) throw err;
continue;
}
if ('null' == type) {
type = new Schema(element);
compareDocs = true;
continue;
}
match = false;
break;
}
if (!equalType(self.getType(arr, i), type)) {
match = false;
break;
}
}
if (match) return [type];
return ['Mixed'];
} | [
"function",
"getArrayType",
"(",
"arr",
",",
"self",
")",
"{",
"var",
"compareDocs",
"=",
"false",
";",
"var",
"type",
"=",
"self",
".",
"getType",
"(",
"arr",
",",
"0",
")",
";",
"if",
"(",
"isObject",
"(",
"type",
")",
")",
"{",
"type",
"=",
"new",
"Schema",
"(",
"arr",
"[",
"0",
"]",
")",
";",
"compareDocs",
"=",
"true",
";",
"}",
"var",
"match",
"=",
"true",
";",
"var",
"element",
";",
"var",
"err",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"arr",
".",
"length",
";",
"++",
"i",
")",
"{",
"element",
"=",
"arr",
"[",
"i",
"]",
";",
"if",
"(",
"isObject",
"(",
"element",
")",
")",
"{",
"if",
"(",
"compareDocs",
")",
"{",
"err",
"=",
"type",
".",
"consume",
"(",
"element",
")",
";",
"if",
"(",
"err",
")",
"throw",
"err",
";",
"continue",
";",
"}",
"if",
"(",
"'null'",
"==",
"type",
")",
"{",
"type",
"=",
"new",
"Schema",
"(",
"element",
")",
";",
"compareDocs",
"=",
"true",
";",
"continue",
";",
"}",
"match",
"=",
"false",
";",
"break",
";",
"}",
"if",
"(",
"!",
"equalType",
"(",
"self",
".",
"getType",
"(",
"arr",
",",
"i",
")",
",",
"type",
")",
")",
"{",
"match",
"=",
"false",
";",
"break",
";",
"}",
"}",
"if",
"(",
"match",
")",
"return",
"[",
"type",
"]",
";",
"return",
"[",
"'Mixed'",
"]",
";",
"}"
]
| Determine the type of array
example return vals:
['Mixed']
['Buffer']
[{ name: 'String', count: 'Number' }] | [
"Determine",
"the",
"type",
"of",
"array"
]
| c56220bd527d82f6a1712f90b45f10828290961f | https://github.com/aheckmann/mongodb-schema-miner/blob/c56220bd527d82f6a1712f90b45f10828290961f/lib/schema.js#L299-L340 |
45,398 | aheckmann/mongodb-schema-miner | lib/schema.js | convertObject | function convertObject (schema, self) {
var keys = Object.keys(schema);
var ret = {};
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
ret[key] = convertElement(schema[key], self);
}
return ret;
} | javascript | function convertObject (schema, self) {
var keys = Object.keys(schema);
var ret = {};
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
ret[key] = convertElement(schema[key], self);
}
return ret;
} | [
"function",
"convertObject",
"(",
"schema",
",",
"self",
")",
"{",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"schema",
")",
";",
"var",
"ret",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"key",
"=",
"keys",
"[",
"i",
"]",
";",
"ret",
"[",
"key",
"]",
"=",
"convertElement",
"(",
"schema",
"[",
"key",
"]",
",",
"self",
")",
";",
"}",
"return",
"ret",
";",
"}"
]
| Converts an object containing schemas to a plain object | [
"Converts",
"an",
"object",
"containing",
"schemas",
"to",
"a",
"plain",
"object"
]
| c56220bd527d82f6a1712f90b45f10828290961f | https://github.com/aheckmann/mongodb-schema-miner/blob/c56220bd527d82f6a1712f90b45f10828290961f/lib/schema.js#L356-L366 |
45,399 | aheckmann/mongodb-schema-miner | lib/schema.js | convertElement | function convertElement (el, self) {
if (el instanceof Schema) {
return el.toObject(self);
}
if (isObject(el)) {
return convertObject(el, self);
}
if (Array.isArray(el)) {
return el.map(function (item) {
return convertElement(item, self);
})
}
return el;
} | javascript | function convertElement (el, self) {
if (el instanceof Schema) {
return el.toObject(self);
}
if (isObject(el)) {
return convertObject(el, self);
}
if (Array.isArray(el)) {
return el.map(function (item) {
return convertElement(item, self);
})
}
return el;
} | [
"function",
"convertElement",
"(",
"el",
",",
"self",
")",
"{",
"if",
"(",
"el",
"instanceof",
"Schema",
")",
"{",
"return",
"el",
".",
"toObject",
"(",
"self",
")",
";",
"}",
"if",
"(",
"isObject",
"(",
"el",
")",
")",
"{",
"return",
"convertObject",
"(",
"el",
",",
"self",
")",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"el",
")",
")",
"{",
"return",
"el",
".",
"map",
"(",
"function",
"(",
"item",
")",
"{",
"return",
"convertElement",
"(",
"item",
",",
"self",
")",
";",
"}",
")",
"}",
"return",
"el",
";",
"}"
]
| Converts a single element to plain object | [
"Converts",
"a",
"single",
"element",
"to",
"plain",
"object"
]
| c56220bd527d82f6a1712f90b45f10828290961f | https://github.com/aheckmann/mongodb-schema-miner/blob/c56220bd527d82f6a1712f90b45f10828290961f/lib/schema.js#L372-L388 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.