repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
redisjs/jsr-log | lib/logger.js | Logger | function Logger() {
this._level = LEVELS.NOTICE;
this._out = process.stdout;
this._err = process.stderr;
/* istanbul ignore next: allow server to suppress logs */
if(process.env.NODE_ENV === Constants.TEST && !process.env.TEST_DEBUG) {
this.log = function noop(){};
}
} | javascript | function Logger() {
this._level = LEVELS.NOTICE;
this._out = process.stdout;
this._err = process.stderr;
/* istanbul ignore next: allow server to suppress logs */
if(process.env.NODE_ENV === Constants.TEST && !process.env.TEST_DEBUG) {
this.log = function noop(){};
}
} | [
"function",
"Logger",
"(",
")",
"{",
"this",
".",
"_level",
"=",
"LEVELS",
".",
"NOTICE",
";",
"this",
".",
"_out",
"=",
"process",
".",
"stdout",
";",
"this",
".",
"_err",
"=",
"process",
".",
"stderr",
";",
"if",
"(",
"process",
".",
"env",
".",
"NODE_ENV",
"===",
"Constants",
".",
"TEST",
"&&",
"!",
"process",
".",
"env",
".",
"TEST_DEBUG",
")",
"{",
"this",
".",
"log",
"=",
"function",
"noop",
"(",
")",
"{",
"}",
";",
"}",
"}"
]
| Create a logger. | [
"Create",
"a",
"logger",
"."
]
| a67a34285449b0d731493def58d8a5212aad5526 | https://github.com/redisjs/jsr-log/blob/a67a34285449b0d731493def58d8a5212aad5526/lib/logger.js#L60-L69 | train |
redisjs/jsr-log | lib/logger.js | level | function level(lvl) {
if(!lvl) return this._level;
if(!~LEVELS.indexOf(lvl)) {
throw new Error('invalid log level: ' + lvl);
}
this._level = lvl;
return this._level;
} | javascript | function level(lvl) {
if(!lvl) return this._level;
if(!~LEVELS.indexOf(lvl)) {
throw new Error('invalid log level: ' + lvl);
}
this._level = lvl;
return this._level;
} | [
"function",
"level",
"(",
"lvl",
")",
"{",
"if",
"(",
"!",
"lvl",
")",
"return",
"this",
".",
"_level",
";",
"if",
"(",
"!",
"~",
"LEVELS",
".",
"indexOf",
"(",
"lvl",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'invalid log level: '",
"+",
"lvl",
")",
";",
"}",
"this",
".",
"_level",
"=",
"lvl",
";",
"return",
"this",
".",
"_level",
";",
"}"
]
| Get or set the log level. | [
"Get",
"or",
"set",
"the",
"log",
"level",
"."
]
| a67a34285449b0d731493def58d8a5212aad5526 | https://github.com/redisjs/jsr-log/blob/a67a34285449b0d731493def58d8a5212aad5526/lib/logger.js#L107-L114 | train |
redisjs/jsr-log | lib/logger.js | warning | function warning() {
var args = [LEVELS.WARNING].concat(slice.apply(arguments));
return this.log.apply(this, args);
} | javascript | function warning() {
var args = [LEVELS.WARNING].concat(slice.apply(arguments));
return this.log.apply(this, args);
} | [
"function",
"warning",
"(",
")",
"{",
"var",
"args",
"=",
"[",
"LEVELS",
".",
"WARNING",
"]",
".",
"concat",
"(",
"slice",
".",
"apply",
"(",
"arguments",
")",
")",
";",
"return",
"this",
".",
"log",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}"
]
| Log a warning message. | [
"Log",
"a",
"warning",
"message",
"."
]
| a67a34285449b0d731493def58d8a5212aad5526 | https://github.com/redisjs/jsr-log/blob/a67a34285449b0d731493def58d8a5212aad5526/lib/logger.js#L145-L148 | train |
redisjs/jsr-log | lib/logger.js | notice | function notice() {
var args = [LEVELS.NOTICE].concat(slice.apply(arguments));
return this.log.apply(this, args);
} | javascript | function notice() {
var args = [LEVELS.NOTICE].concat(slice.apply(arguments));
return this.log.apply(this, args);
} | [
"function",
"notice",
"(",
")",
"{",
"var",
"args",
"=",
"[",
"LEVELS",
".",
"NOTICE",
"]",
".",
"concat",
"(",
"slice",
".",
"apply",
"(",
"arguments",
")",
")",
";",
"return",
"this",
".",
"log",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}"
]
| Log a notice message. | [
"Log",
"a",
"notice",
"message",
"."
]
| a67a34285449b0d731493def58d8a5212aad5526 | https://github.com/redisjs/jsr-log/blob/a67a34285449b0d731493def58d8a5212aad5526/lib/logger.js#L153-L156 | train |
redisjs/jsr-log | lib/logger.js | verbose | function verbose() {
var args = [LEVELS.VERBOSE].concat(slice.apply(arguments));
return this.log.apply(this, args);
} | javascript | function verbose() {
var args = [LEVELS.VERBOSE].concat(slice.apply(arguments));
return this.log.apply(this, args);
} | [
"function",
"verbose",
"(",
")",
"{",
"var",
"args",
"=",
"[",
"LEVELS",
".",
"VERBOSE",
"]",
".",
"concat",
"(",
"slice",
".",
"apply",
"(",
"arguments",
")",
")",
";",
"return",
"this",
".",
"log",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}"
]
| Log a verbose message. | [
"Log",
"a",
"verbose",
"message",
"."
]
| a67a34285449b0d731493def58d8a5212aad5526 | https://github.com/redisjs/jsr-log/blob/a67a34285449b0d731493def58d8a5212aad5526/lib/logger.js#L161-L164 | train |
ahwayakchih/serve-files | index.js | createConfiguration | function createConfiguration (options) {
const cfg = Object.assign({
followSymbolicLinks: false,
cacheTimeInSeconds : 0,
documentRoot : process.cwd(),
parsedURLName : 'urlParsed',
getFilePath : getFilePath,
getFileStats : getFileStats,
getResponseData : getResponseData,
standardResponses : null
}, options);
try {
let root = fs.realpathSync(cfg.documentRoot);
cfg.documentRootReal = root;
}
catch (e) {
return e;
}
return cfg;
} | javascript | function createConfiguration (options) {
const cfg = Object.assign({
followSymbolicLinks: false,
cacheTimeInSeconds : 0,
documentRoot : process.cwd(),
parsedURLName : 'urlParsed',
getFilePath : getFilePath,
getFileStats : getFileStats,
getResponseData : getResponseData,
standardResponses : null
}, options);
try {
let root = fs.realpathSync(cfg.documentRoot);
cfg.documentRootReal = root;
}
catch (e) {
return e;
}
return cfg;
} | [
"function",
"createConfiguration",
"(",
"options",
")",
"{",
"const",
"cfg",
"=",
"Object",
".",
"assign",
"(",
"{",
"followSymbolicLinks",
":",
"false",
",",
"cacheTimeInSeconds",
":",
"0",
",",
"documentRoot",
":",
"process",
".",
"cwd",
"(",
")",
",",
"parsedURLName",
":",
"'urlParsed'",
",",
"getFilePath",
":",
"getFilePath",
",",
"getFileStats",
":",
"getFileStats",
",",
"getResponseData",
":",
"getResponseData",
",",
"standardResponses",
":",
"null",
"}",
",",
"options",
")",
";",
"try",
"{",
"let",
"root",
"=",
"fs",
".",
"realpathSync",
"(",
"cfg",
".",
"documentRoot",
")",
";",
"cfg",
".",
"documentRootReal",
"=",
"root",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"e",
";",
"}",
"return",
"cfg",
";",
"}"
]
| Configuration object.
@typedef {Object} configuration
@property {boolean} followSymbolicLinks=false
@property {number} cacheTimeInSeconds=0
@property {string} documentRoot=process.cwd()
@property {string} parsedURLName='urlParsed'
@property {Function} getFilePath
@property {Function} getFileStats
@property {Function} getResponseData
@property {Function[]} standardResponses=null
Prepare configuration object.
@param {Object} options Check properties of {@link module:serve-files~configuration}
@return {module:serve-files~configuration} | [
"Configuration",
"object",
"."
]
| cd949252a37210bec229146ab519534ef641e942 | https://github.com/ahwayakchih/serve-files/blob/cd949252a37210bec229146ab519534ef641e942/index.js#L67-L88 | train |
ahwayakchih/serve-files | index.js | getFileStats | function getFileStats (cfg, filePath, callback) {
fs.realpath(filePath, function (err, realpath) {
// On Windows we can get different cases for the same disk letter :/.
let checkPath = realpath;
if (os.platform() === 'win32' && realpath) {
checkPath = realpath.toLowerCase();
}
if (err || checkPath.indexOf(cfg.documentRootReal) !== 0) {
return callback(err || new Error('Access denied'));
}
fs[cfg.followSymbolicLinks ? 'stat' : 'lstat'](filePath, function (err, stats) {
if (err || !stats.isFile()) {
return callback(err || new Error('Access denied'));
}
stats.path = realpath;
callback(null, stats);
});
});
} | javascript | function getFileStats (cfg, filePath, callback) {
fs.realpath(filePath, function (err, realpath) {
// On Windows we can get different cases for the same disk letter :/.
let checkPath = realpath;
if (os.platform() === 'win32' && realpath) {
checkPath = realpath.toLowerCase();
}
if (err || checkPath.indexOf(cfg.documentRootReal) !== 0) {
return callback(err || new Error('Access denied'));
}
fs[cfg.followSymbolicLinks ? 'stat' : 'lstat'](filePath, function (err, stats) {
if (err || !stats.isFile()) {
return callback(err || new Error('Access denied'));
}
stats.path = realpath;
callback(null, stats);
});
});
} | [
"function",
"getFileStats",
"(",
"cfg",
",",
"filePath",
",",
"callback",
")",
"{",
"fs",
".",
"realpath",
"(",
"filePath",
",",
"function",
"(",
"err",
",",
"realpath",
")",
"{",
"let",
"checkPath",
"=",
"realpath",
";",
"if",
"(",
"os",
".",
"platform",
"(",
")",
"===",
"'win32'",
"&&",
"realpath",
")",
"{",
"checkPath",
"=",
"realpath",
".",
"toLowerCase",
"(",
")",
";",
"}",
"if",
"(",
"err",
"||",
"checkPath",
".",
"indexOf",
"(",
"cfg",
".",
"documentRootReal",
")",
"!==",
"0",
")",
"{",
"return",
"callback",
"(",
"err",
"||",
"new",
"Error",
"(",
"'Access denied'",
")",
")",
";",
"}",
"fs",
"[",
"cfg",
".",
"followSymbolicLinks",
"?",
"'stat'",
":",
"'lstat'",
"]",
"(",
"filePath",
",",
"function",
"(",
"err",
",",
"stats",
")",
"{",
"if",
"(",
"err",
"||",
"!",
"stats",
".",
"isFile",
"(",
")",
")",
"{",
"return",
"callback",
"(",
"err",
"||",
"new",
"Error",
"(",
"'Access denied'",
")",
")",
";",
"}",
"stats",
".",
"path",
"=",
"realpath",
";",
"callback",
"(",
"null",
",",
"stats",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Calls back with error or null and fs.Stats object as second parameter.
fs.Stats object is extended with `path` property.
@param {!module:serve-files~configuration} cfg
@param {!string} cfg.documentRootReal
@param {string} [cfg.followSymbolicLinks=false]
@param {!string} filePath
@param {@Function} callback | [
"Calls",
"back",
"with",
"error",
"or",
"null",
"and",
"fs",
".",
"Stats",
"object",
"as",
"second",
"parameter",
".",
"fs",
".",
"Stats",
"object",
"is",
"extended",
"with",
"path",
"property",
"."
]
| cd949252a37210bec229146ab519534ef641e942 | https://github.com/ahwayakchih/serve-files/blob/cd949252a37210bec229146ab519534ef641e942/index.js#L118-L140 | train |
ahwayakchih/serve-files | index.js | getResponseDataWhole | function getResponseDataWhole (fileStats/* , headers*/) {
return {
body : fs.createReadStream(fileStats.path),
statusCode: HTTP_CODES.OK,
headers : {
'Content-Type' : mime(fileStats.path),
'Content-Length': fileStats.size,
'Last-Modified' : fileStats.mtime.toUTCString()
}
};
} | javascript | function getResponseDataWhole (fileStats/* , headers*/) {
return {
body : fs.createReadStream(fileStats.path),
statusCode: HTTP_CODES.OK,
headers : {
'Content-Type' : mime(fileStats.path),
'Content-Length': fileStats.size,
'Last-Modified' : fileStats.mtime.toUTCString()
}
};
} | [
"function",
"getResponseDataWhole",
"(",
"fileStats",
")",
"{",
"return",
"{",
"body",
":",
"fs",
".",
"createReadStream",
"(",
"fileStats",
".",
"path",
")",
",",
"statusCode",
":",
"HTTP_CODES",
".",
"OK",
",",
"headers",
":",
"{",
"'Content-Type'",
":",
"mime",
"(",
"fileStats",
".",
"path",
")",
",",
"'Content-Length'",
":",
"fileStats",
".",
"size",
",",
"'Last-Modified'",
":",
"fileStats",
".",
"mtime",
".",
"toUTCString",
"(",
")",
"}",
"}",
";",
"}"
]
| Creates responseData object with body set to readable stream of requested file.
@param {!external:"fs.Stats"} fileStats
@param {!string} fileStats.path path to the file in local filesystem
@param {!Date} fileStats.mtime date of last modification of file content
@param {!Number} fileStats.size number of bytes of data file contains
@param {!Object} headers
@return {module:serve-files~responseData} | [
"Creates",
"responseData",
"object",
"with",
"body",
"set",
"to",
"readable",
"stream",
"of",
"requested",
"file",
"."
]
| cd949252a37210bec229146ab519534ef641e942 | https://github.com/ahwayakchih/serve-files/blob/cd949252a37210bec229146ab519534ef641e942/index.js#L286-L296 | train |
ahwayakchih/serve-files | index.js | createFileResponseHandler | function createFileResponseHandler (options) {
const cfg = createConfiguration(options);
if (cfg instanceof Error) {
return cfg;
}
/**
* @private
* @param {!external:"http.IncomingMessage"} req
* @param {!external:"http.ServerResponse"} res
* @param {Function} [callback] called AFTER response is finished
*/
function serve (req, res, callback) {
if (callback && callback instanceof Function) {
res.once('finish', callback);
}
const filePath = cfg.getFilePath(cfg, req);
prepareFileResponse(cfg, filePath, req.headers, (err, data) => {
if (err) {
data = {
statusCode: HTTP_CODES.NOT_FOUND
};
}
serveFileResponse(cfg, data, res);
});
}
return serve;
} | javascript | function createFileResponseHandler (options) {
const cfg = createConfiguration(options);
if (cfg instanceof Error) {
return cfg;
}
/**
* @private
* @param {!external:"http.IncomingMessage"} req
* @param {!external:"http.ServerResponse"} res
* @param {Function} [callback] called AFTER response is finished
*/
function serve (req, res, callback) {
if (callback && callback instanceof Function) {
res.once('finish', callback);
}
const filePath = cfg.getFilePath(cfg, req);
prepareFileResponse(cfg, filePath, req.headers, (err, data) => {
if (err) {
data = {
statusCode: HTTP_CODES.NOT_FOUND
};
}
serveFileResponse(cfg, data, res);
});
}
return serve;
} | [
"function",
"createFileResponseHandler",
"(",
"options",
")",
"{",
"const",
"cfg",
"=",
"createConfiguration",
"(",
"options",
")",
";",
"if",
"(",
"cfg",
"instanceof",
"Error",
")",
"{",
"return",
"cfg",
";",
"}",
"function",
"serve",
"(",
"req",
",",
"res",
",",
"callback",
")",
"{",
"if",
"(",
"callback",
"&&",
"callback",
"instanceof",
"Function",
")",
"{",
"res",
".",
"once",
"(",
"'finish'",
",",
"callback",
")",
";",
"}",
"const",
"filePath",
"=",
"cfg",
".",
"getFilePath",
"(",
"cfg",
",",
"req",
")",
";",
"prepareFileResponse",
"(",
"cfg",
",",
"filePath",
",",
"req",
".",
"headers",
",",
"(",
"err",
",",
"data",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"data",
"=",
"{",
"statusCode",
":",
"HTTP_CODES",
".",
"NOT_FOUND",
"}",
";",
"}",
"serveFileResponse",
"(",
"cfg",
",",
"data",
",",
"res",
")",
";",
"}",
")",
";",
"}",
"return",
"serve",
";",
"}"
]
| Create function that will handle serving files.
@example
var fileHandler = serveFiles();
var server = http.createServer(function (req, res) {
fileHandler(req, res, err => console.error(err));
});
@param {object} [options]
@param {boolean} [options.followSymbolicLinks=false] symbolic links will not be followed by default, i.e., they will not be served
@param {number} [options.cacheTimeInSeconds=0] HTTP cache will be disabled by default
@param {string} [options.documentRoot=process.cwd()] files outside of root path will not be served
@param {string} [options.parsedURLName='urlParsed'] name of an optional property of a request object, which contains result of `url.parse(req.url)`
@return {Function|Error} | [
"Create",
"function",
"that",
"will",
"handle",
"serving",
"files",
"."
]
| cd949252a37210bec229146ab519534ef641e942 | https://github.com/ahwayakchih/serve-files/blob/cd949252a37210bec229146ab519534ef641e942/index.js#L389-L421 | train |
mcgaryes/grunt-combine | tasks/combine.js | function(inputIndex) {
_.each(tokens, function(token, index) {
// determain whether or not this is a file reference or a string
if(token.file) {
// read the file and reset replacement to what was loaded
fs.readFile(token.file, 'utf8', function(e, data) {
if(e) {
grunt.fail.warn("There was an error processing the replacement '" + token.file + "' file.");
}
tokens[index].contents = data;
processTokenCompleteCallback();
});
} else if(token.string) {
// we didn't need to load a file
tokens[index].contents = token.string;
processTokenCompleteCallback();
} else {
processTokenCompleteCallback();
}
}, this);
} | javascript | function(inputIndex) {
_.each(tokens, function(token, index) {
// determain whether or not this is a file reference or a string
if(token.file) {
// read the file and reset replacement to what was loaded
fs.readFile(token.file, 'utf8', function(e, data) {
if(e) {
grunt.fail.warn("There was an error processing the replacement '" + token.file + "' file.");
}
tokens[index].contents = data;
processTokenCompleteCallback();
});
} else if(token.string) {
// we didn't need to load a file
tokens[index].contents = token.string;
processTokenCompleteCallback();
} else {
processTokenCompleteCallback();
}
}, this);
} | [
"function",
"(",
"inputIndex",
")",
"{",
"_",
".",
"each",
"(",
"tokens",
",",
"function",
"(",
"token",
",",
"index",
")",
"{",
"if",
"(",
"token",
".",
"file",
")",
"{",
"fs",
".",
"readFile",
"(",
"token",
".",
"file",
",",
"'utf8'",
",",
"function",
"(",
"e",
",",
"data",
")",
"{",
"if",
"(",
"e",
")",
"{",
"grunt",
".",
"fail",
".",
"warn",
"(",
"\"There was an error processing the replacement '\"",
"+",
"token",
".",
"file",
"+",
"\"' file.\"",
")",
";",
"}",
"tokens",
"[",
"index",
"]",
".",
"contents",
"=",
"data",
";",
"processTokenCompleteCallback",
"(",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"token",
".",
"string",
")",
"{",
"tokens",
"[",
"index",
"]",
".",
"contents",
"=",
"token",
".",
"string",
";",
"processTokenCompleteCallback",
"(",
")",
";",
"}",
"else",
"{",
"processTokenCompleteCallback",
"(",
")",
";",
"}",
"}",
",",
"this",
")",
";",
"}"
]
| Processes all of the passed replacements
@for grunt-combine
@method processReplacements | [
"Processes",
"all",
"of",
"the",
"passed",
"replacements"
]
| 18a330b48f3eab4ec7af75f3c436294bf6f41319 | https://github.com/mcgaryes/grunt-combine/blob/18a330b48f3eab4ec7af75f3c436294bf6f41319/tasks/combine.js#L93-L117 | train |
|
mcgaryes/grunt-combine | tasks/combine.js | function(inputIndex) {
var inputPath = input[inputIndex].split("/");
inputPath = inputPath[inputPath.length - 1];
var path = outputIsPath ? output + inputPath : output;
// write the input string to the output file name
grunt.log.writeln('Writing Output: ' + (path).cyan);
fs.writeFile(path, fileContents[inputIndex], 'utf8', function(err) {
//console.log(fileContents[inputIndex]);
if(err) {
clearTimeout(timer);
grunt.fail.warn("Could not write output '" + output + "' file.");
}
processedFiles++;
if(processedFiles === fileContents.length) {
processedFiles = 0;
fileContents = [];
var endtime = (new Date()).getTime();
grunt.log.writeln('Combine task completed in ' + ((endtime - starttime) / 1000) + ' seconds');
clearTimeout(timer);
done();
}
});
} | javascript | function(inputIndex) {
var inputPath = input[inputIndex].split("/");
inputPath = inputPath[inputPath.length - 1];
var path = outputIsPath ? output + inputPath : output;
// write the input string to the output file name
grunt.log.writeln('Writing Output: ' + (path).cyan);
fs.writeFile(path, fileContents[inputIndex], 'utf8', function(err) {
//console.log(fileContents[inputIndex]);
if(err) {
clearTimeout(timer);
grunt.fail.warn("Could not write output '" + output + "' file.");
}
processedFiles++;
if(processedFiles === fileContents.length) {
processedFiles = 0;
fileContents = [];
var endtime = (new Date()).getTime();
grunt.log.writeln('Combine task completed in ' + ((endtime - starttime) / 1000) + ' seconds');
clearTimeout(timer);
done();
}
});
} | [
"function",
"(",
"inputIndex",
")",
"{",
"var",
"inputPath",
"=",
"input",
"[",
"inputIndex",
"]",
".",
"split",
"(",
"\"/\"",
")",
";",
"inputPath",
"=",
"inputPath",
"[",
"inputPath",
".",
"length",
"-",
"1",
"]",
";",
"var",
"path",
"=",
"outputIsPath",
"?",
"output",
"+",
"inputPath",
":",
"output",
";",
"grunt",
".",
"log",
".",
"writeln",
"(",
"'Writing Output: '",
"+",
"(",
"path",
")",
".",
"cyan",
")",
";",
"fs",
".",
"writeFile",
"(",
"path",
",",
"fileContents",
"[",
"inputIndex",
"]",
",",
"'utf8'",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"clearTimeout",
"(",
"timer",
")",
";",
"grunt",
".",
"fail",
".",
"warn",
"(",
"\"Could not write output '\"",
"+",
"output",
"+",
"\"' file.\"",
")",
";",
"}",
"processedFiles",
"++",
";",
"if",
"(",
"processedFiles",
"===",
"fileContents",
".",
"length",
")",
"{",
"processedFiles",
"=",
"0",
";",
"fileContents",
"=",
"[",
"]",
";",
"var",
"endtime",
"=",
"(",
"new",
"Date",
"(",
")",
")",
".",
"getTime",
"(",
")",
";",
"grunt",
".",
"log",
".",
"writeln",
"(",
"'Combine task completed in '",
"+",
"(",
"(",
"endtime",
"-",
"starttime",
")",
"/",
"1000",
")",
"+",
"' seconds'",
")",
";",
"clearTimeout",
"(",
"timer",
")",
";",
"done",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Writes the processed input file to the specified output name.
@for grunt-combine
@method findAndReplaceTokens | [
"Writes",
"the",
"processed",
"input",
"file",
"to",
"the",
"specified",
"output",
"name",
"."
]
| 18a330b48f3eab4ec7af75f3c436294bf6f41319 | https://github.com/mcgaryes/grunt-combine/blob/18a330b48f3eab4ec7af75f3c436294bf6f41319/tasks/combine.js#L164-L190 | train |
|
posttool/currentcms | examples/store/public/js/$$.js | string_component | function string_component(self, message, component) {
eventify(self);
valuable(self, update, '');
var $c = $$().addClass('control');
var $l = $("<label>" + message + "</label>");
var $i = $(component);
$c.append($l, $i);
self.$el = $c;
function update() {
$i.val(self._data);
}
$i.on('change', function () {
self._data = $i.val();
self.emit('change');
})
} | javascript | function string_component(self, message, component) {
eventify(self);
valuable(self, update, '');
var $c = $$().addClass('control');
var $l = $("<label>" + message + "</label>");
var $i = $(component);
$c.append($l, $i);
self.$el = $c;
function update() {
$i.val(self._data);
}
$i.on('change', function () {
self._data = $i.val();
self.emit('change');
})
} | [
"function",
"string_component",
"(",
"self",
",",
"message",
",",
"component",
")",
"{",
"eventify",
"(",
"self",
")",
";",
"valuable",
"(",
"self",
",",
"update",
",",
"''",
")",
";",
"var",
"$c",
"=",
"$$",
"(",
")",
".",
"addClass",
"(",
"'control'",
")",
";",
"var",
"$l",
"=",
"$",
"(",
"\"<label>\"",
"+",
"message",
"+",
"\"</label>\"",
")",
";",
"var",
"$i",
"=",
"$",
"(",
"component",
")",
";",
"$c",
".",
"append",
"(",
"$l",
",",
"$i",
")",
";",
"self",
".",
"$el",
"=",
"$c",
";",
"function",
"update",
"(",
")",
"{",
"$i",
".",
"val",
"(",
"self",
".",
"_data",
")",
";",
"}",
"$i",
".",
"on",
"(",
"'change'",
",",
"function",
"(",
")",
"{",
"self",
".",
"_data",
"=",
"$i",
".",
"val",
"(",
")",
";",
"self",
".",
"emit",
"(",
"'change'",
")",
";",
"}",
")",
"}"
]
| simple component ! | [
"simple",
"component",
"!"
]
| 9afc9f907bad3b018d961af66c3abb33cd82b051 | https://github.com/posttool/currentcms/blob/9afc9f907bad3b018d961af66c3abb33cd82b051/examples/store/public/js/$$.js#L168-L184 | train |
posttool/currentcms | examples/store/public/js/$$.js | attributable | function attributable(form, c, name) {
if (form._vals == null)
form._vals = {};
if (form._update == null)
form._update = function () {
for (var p in form._vals)
form._vals[p].data == form._data[p];
}
form._vals[name] = c;
c.on('change', function () {
form._data[name] = c.data;
form.emit('change');
});
} | javascript | function attributable(form, c, name) {
if (form._vals == null)
form._vals = {};
if (form._update == null)
form._update = function () {
for (var p in form._vals)
form._vals[p].data == form._data[p];
}
form._vals[name] = c;
c.on('change', function () {
form._data[name] = c.data;
form.emit('change');
});
} | [
"function",
"attributable",
"(",
"form",
",",
"c",
",",
"name",
")",
"{",
"if",
"(",
"form",
".",
"_vals",
"==",
"null",
")",
"form",
".",
"_vals",
"=",
"{",
"}",
";",
"if",
"(",
"form",
".",
"_update",
"==",
"null",
")",
"form",
".",
"_update",
"=",
"function",
"(",
")",
"{",
"for",
"(",
"var",
"p",
"in",
"form",
".",
"_vals",
")",
"form",
".",
"_vals",
"[",
"p",
"]",
".",
"data",
"==",
"form",
".",
"_data",
"[",
"p",
"]",
";",
"}",
"form",
".",
"_vals",
"[",
"name",
"]",
"=",
"c",
";",
"c",
".",
"on",
"(",
"'change'",
",",
"function",
"(",
")",
"{",
"form",
".",
"_data",
"[",
"name",
"]",
"=",
"c",
".",
"data",
";",
"form",
".",
"emit",
"(",
"'change'",
")",
";",
"}",
")",
";",
"}"
]
| form field utility | [
"form",
"field",
"utility"
]
| 9afc9f907bad3b018d961af66c3abb33cd82b051 | https://github.com/posttool/currentcms/blob/9afc9f907bad3b018d961af66c3abb33cd82b051/examples/store/public/js/$$.js#L240-L253 | train |
grydstedt/uservoice-sso | lib/index.js | UserVoiceSSO | function UserVoiceSSO(subdomain, ssoKey) {
// For UserVoice, the subdomain is used as password
// and the ssoKey is used as salt
this.subdomain = subdomain;
this.ssoKey = ssoKey;
if(!this.subdomain) {
throw new Error('No UserVoice subdomain given');
}
if(!this.ssoKey) {
throw new Error('No SSO key given. Find it ');
}
this.defaults = {};
} | javascript | function UserVoiceSSO(subdomain, ssoKey) {
// For UserVoice, the subdomain is used as password
// and the ssoKey is used as salt
this.subdomain = subdomain;
this.ssoKey = ssoKey;
if(!this.subdomain) {
throw new Error('No UserVoice subdomain given');
}
if(!this.ssoKey) {
throw new Error('No SSO key given. Find it ');
}
this.defaults = {};
} | [
"function",
"UserVoiceSSO",
"(",
"subdomain",
",",
"ssoKey",
")",
"{",
"this",
".",
"subdomain",
"=",
"subdomain",
";",
"this",
".",
"ssoKey",
"=",
"ssoKey",
";",
"if",
"(",
"!",
"this",
".",
"subdomain",
")",
"{",
"throw",
"new",
"Error",
"(",
"'No UserVoice subdomain given'",
")",
";",
"}",
"if",
"(",
"!",
"this",
".",
"ssoKey",
")",
"{",
"throw",
"new",
"Error",
"(",
"'No SSO key given. Find it '",
")",
";",
"}",
"this",
".",
"defaults",
"=",
"{",
"}",
";",
"}"
]
| UserVoice SSO Contstructor
@param {String} subdomain Subdomain name
@param {String} ssoKey SSO key | [
"UserVoice",
"SSO",
"Contstructor"
]
| 89a1e4dc0d72e964840c3e3e106cfeb12fc688cc | https://github.com/grydstedt/uservoice-sso/blob/89a1e4dc0d72e964840c3e3e106cfeb12fc688cc/lib/index.js#L24-L40 | train |
stormpython/jubilee | build/jubilee.js | getDomain | function getDomain(data, accessor) {
return data
.map(function (item) {
return accessor.call(this, item);
})
.filter(function (item, index, array) {
return array.indexOf(item) === index;
});
} | javascript | function getDomain(data, accessor) {
return data
.map(function (item) {
return accessor.call(this, item);
})
.filter(function (item, index, array) {
return array.indexOf(item) === index;
});
} | [
"function",
"getDomain",
"(",
"data",
",",
"accessor",
")",
"{",
"return",
"data",
".",
"map",
"(",
"function",
"(",
"item",
")",
"{",
"return",
"accessor",
".",
"call",
"(",
"this",
",",
"item",
")",
";",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"item",
",",
"index",
",",
"array",
")",
"{",
"return",
"array",
".",
"indexOf",
"(",
"item",
")",
"===",
"index",
";",
"}",
")",
";",
"}"
]
| Creates a unique array of items | [
"Creates",
"a",
"unique",
"array",
"of",
"items"
]
| 8263cec31ccfbef38e77229a5baaa7b337c6eefc | https://github.com/stormpython/jubilee/blob/8263cec31ccfbef38e77229a5baaa7b337c6eefc/build/jubilee.js#L11509-L11517 | train |
brianshaler/kerplunk-server | assets/js/ba-routematcher.js | validateRule | function validateRule(rule, value) {
// For a given rule, get the first letter of the string name of its
// constructor function. "R" -> RegExp, "F" -> Function (these shouldn't
// conflict with any other types one might specify). Note: instead of
// getting .toString from a new object {} or Object.prototype, I'm assuming
// that exports will always be an object, and using its .toString method.
// Bad idea? Let me know by filing an issue
var type = exports.toString.call(rule).charAt(8);
// If regexp, match. If function, invoke. Otherwise, compare. Note that ==
// is used because type coercion is needed, as `value` will always be a
// string, but `rule` might not.
return type === "R" ? rule.test(value) : type === "F" ? rule(value) : rule == value;
} | javascript | function validateRule(rule, value) {
// For a given rule, get the first letter of the string name of its
// constructor function. "R" -> RegExp, "F" -> Function (these shouldn't
// conflict with any other types one might specify). Note: instead of
// getting .toString from a new object {} or Object.prototype, I'm assuming
// that exports will always be an object, and using its .toString method.
// Bad idea? Let me know by filing an issue
var type = exports.toString.call(rule).charAt(8);
// If regexp, match. If function, invoke. Otherwise, compare. Note that ==
// is used because type coercion is needed, as `value` will always be a
// string, but `rule` might not.
return type === "R" ? rule.test(value) : type === "F" ? rule(value) : rule == value;
} | [
"function",
"validateRule",
"(",
"rule",
",",
"value",
")",
"{",
"var",
"type",
"=",
"exports",
".",
"toString",
".",
"call",
"(",
"rule",
")",
".",
"charAt",
"(",
"8",
")",
";",
"return",
"type",
"===",
"\"R\"",
"?",
"rule",
".",
"test",
"(",
"value",
")",
":",
"type",
"===",
"\"F\"",
"?",
"rule",
"(",
"value",
")",
":",
"rule",
"==",
"value",
";",
"}"
]
| Test to see if a value matches the corresponding rule. | [
"Test",
"to",
"see",
"if",
"a",
"value",
"matches",
"the",
"corresponding",
"rule",
"."
]
| f4ee71f2893a811b4968beace7a1ba0b8ea45182 | https://github.com/brianshaler/kerplunk-server/blob/f4ee71f2893a811b4968beace7a1ba0b8ea45182/assets/js/ba-routematcher.js#L13-L25 | train |
emitdb/dotfile | index.js | Dotfile | function Dotfile(basename, options) {
this.basename = basename;
this.extname = '.json';
this.dirname = (options && typeof options.dirname === 'string') ? options.dirname : Dotfile._tilde;
this.filepath = path.join(this.dirname, '.' + this.basename + this.extname);
} | javascript | function Dotfile(basename, options) {
this.basename = basename;
this.extname = '.json';
this.dirname = (options && typeof options.dirname === 'string') ? options.dirname : Dotfile._tilde;
this.filepath = path.join(this.dirname, '.' + this.basename + this.extname);
} | [
"function",
"Dotfile",
"(",
"basename",
",",
"options",
")",
"{",
"this",
".",
"basename",
"=",
"basename",
";",
"this",
".",
"extname",
"=",
"'.json'",
";",
"this",
".",
"dirname",
"=",
"(",
"options",
"&&",
"typeof",
"options",
".",
"dirname",
"===",
"'string'",
")",
"?",
"options",
".",
"dirname",
":",
"Dotfile",
".",
"_tilde",
";",
"this",
".",
"filepath",
"=",
"path",
".",
"join",
"(",
"this",
".",
"dirname",
",",
"'.'",
"+",
"this",
".",
"basename",
"+",
"this",
".",
"extname",
")",
";",
"}"
]
| Class to easily manage dot files
@param {String} basename What to name this dotfile
@author dscape | [
"Class",
"to",
"easily",
"manage",
"dot",
"files"
]
| 1d1f226b5d64d1c10876ee7d37f55feee2b96aa4 | https://github.com/emitdb/dotfile/blob/1d1f226b5d64d1c10876ee7d37f55feee2b96aa4/index.js#L12-L17 | train |
bredele/regurgitate | index.js | transform | function transform(value) {
if(typeof value === 'function') value = value()
if(value instanceof Array) {
var el = document.createDocumentFragment()
value.map(item => el.appendChild(transform(item)))
value = el
} else if(typeof value === 'object') {
if(typeof value.then === 'function') {
var tmp = document.createTextNode('')
value.then(function(data) {
tmp.parentElement.replaceChild(transform(data), tmp)
})
value = tmp
} else if(typeof value.on === 'function') {
var tmp = document.createTextNode('')
value.on('data', function(data) {
// need to transform? Streams are only text?
tmp.parentElement.insertBefore(document.createTextNode(data), tmp)
})
value = tmp
}
} else value = document.createTextNode(value)
return value
} | javascript | function transform(value) {
if(typeof value === 'function') value = value()
if(value instanceof Array) {
var el = document.createDocumentFragment()
value.map(item => el.appendChild(transform(item)))
value = el
} else if(typeof value === 'object') {
if(typeof value.then === 'function') {
var tmp = document.createTextNode('')
value.then(function(data) {
tmp.parentElement.replaceChild(transform(data), tmp)
})
value = tmp
} else if(typeof value.on === 'function') {
var tmp = document.createTextNode('')
value.on('data', function(data) {
// need to transform? Streams are only text?
tmp.parentElement.insertBefore(document.createTextNode(data), tmp)
})
value = tmp
}
} else value = document.createTextNode(value)
return value
} | [
"function",
"transform",
"(",
"value",
")",
"{",
"if",
"(",
"typeof",
"value",
"===",
"'function'",
")",
"value",
"=",
"value",
"(",
")",
"if",
"(",
"value",
"instanceof",
"Array",
")",
"{",
"var",
"el",
"=",
"document",
".",
"createDocumentFragment",
"(",
")",
"value",
".",
"map",
"(",
"item",
"=>",
"el",
".",
"appendChild",
"(",
"transform",
"(",
"item",
")",
")",
")",
"value",
"=",
"el",
"}",
"else",
"if",
"(",
"typeof",
"value",
"===",
"'object'",
")",
"{",
"if",
"(",
"typeof",
"value",
".",
"then",
"===",
"'function'",
")",
"{",
"var",
"tmp",
"=",
"document",
".",
"createTextNode",
"(",
"''",
")",
"value",
".",
"then",
"(",
"function",
"(",
"data",
")",
"{",
"tmp",
".",
"parentElement",
".",
"replaceChild",
"(",
"transform",
"(",
"data",
")",
",",
"tmp",
")",
"}",
")",
"value",
"=",
"tmp",
"}",
"else",
"if",
"(",
"typeof",
"value",
".",
"on",
"===",
"'function'",
")",
"{",
"var",
"tmp",
"=",
"document",
".",
"createTextNode",
"(",
"''",
")",
"value",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"data",
")",
"{",
"tmp",
".",
"parentElement",
".",
"insertBefore",
"(",
"document",
".",
"createTextNode",
"(",
"data",
")",
",",
"tmp",
")",
"}",
")",
"value",
"=",
"tmp",
"}",
"}",
"else",
"value",
"=",
"document",
".",
"createTextNode",
"(",
"value",
")",
"return",
"value",
"}"
]
| Transform value.
@param {Any|Function|Promise} value
@return {Element}
@api private | [
"Transform",
"value",
"."
]
| 313711f6871b083722a907353197f1ee27ad87c1 | https://github.com/bredele/regurgitate/blob/313711f6871b083722a907353197f1ee27ad87c1/index.js#L25-L48 | train |
dinvio/dinvio-js-sdk | lib/Requests.js | Requests | function Requests(apiUrl, version, publicKey) {
this.apiUrl = stripSlashes(apiUrl);
this.version = version.toString();
this.publicKey = publicKey;
} | javascript | function Requests(apiUrl, version, publicKey) {
this.apiUrl = stripSlashes(apiUrl);
this.version = version.toString();
this.publicKey = publicKey;
} | [
"function",
"Requests",
"(",
"apiUrl",
",",
"version",
",",
"publicKey",
")",
"{",
"this",
".",
"apiUrl",
"=",
"stripSlashes",
"(",
"apiUrl",
")",
";",
"this",
".",
"version",
"=",
"version",
".",
"toString",
"(",
")",
";",
"this",
".",
"publicKey",
"=",
"publicKey",
";",
"}"
]
| Dinvio API Requests module
@param {string} apiUrl
@param {string|number} version
@param {string} publicKey
@constructor | [
"Dinvio",
"API",
"Requests",
"module"
]
| 24e960a3670841ff924d10e2a091b23c38a05dd4 | https://github.com/dinvio/dinvio-js-sdk/blob/24e960a3670841ff924d10e2a091b23c38a05dd4/lib/Requests.js#L15-L19 | train |
hl198181/neptune | misc/demo/public/vendor/plupload-2.1.2/js/jquery.ui.plupload/jquery.ui.plupload.js | function(id) {
var file;
if (typeof id === 'number') {
file = this.uploader.files[id];
} else {
file = this.uploader.getFile(id);
}
return file;
} | javascript | function(id) {
var file;
if (typeof id === 'number') {
file = this.uploader.files[id];
} else {
file = this.uploader.getFile(id);
}
return file;
} | [
"function",
"(",
"id",
")",
"{",
"var",
"file",
";",
"if",
"(",
"typeof",
"id",
"===",
"'number'",
")",
"{",
"file",
"=",
"this",
".",
"uploader",
".",
"files",
"[",
"id",
"]",
";",
"}",
"else",
"{",
"file",
"=",
"this",
".",
"uploader",
".",
"getFile",
"(",
"id",
")",
";",
"}",
"return",
"file",
";",
"}"
]
| Retrieve file by it's unique id.
@method getFile
@param {String} id Unique id of the file
@return {plupload.File} | [
"Retrieve",
"file",
"by",
"it",
"s",
"unique",
"id",
"."
]
| 88030bb4222945900e6a225469380cc43a016c13 | https://github.com/hl198181/neptune/blob/88030bb4222945900e6a225469380cc43a016c13/misc/demo/public/vendor/plupload-2.1.2/js/jquery.ui.plupload/jquery.ui.plupload.js#L700-L709 | train |
|
hl198181/neptune | misc/demo/public/vendor/plupload-2.1.2/js/jquery.ui.plupload/jquery.ui.plupload.js | function(file) {
if (plupload.typeOf(file) === 'string') {
file = this.getFile(file);
}
this.uploader.removeFile(file);
} | javascript | function(file) {
if (plupload.typeOf(file) === 'string') {
file = this.getFile(file);
}
this.uploader.removeFile(file);
} | [
"function",
"(",
"file",
")",
"{",
"if",
"(",
"plupload",
".",
"typeOf",
"(",
"file",
")",
"===",
"'string'",
")",
"{",
"file",
"=",
"this",
".",
"getFile",
"(",
"file",
")",
";",
"}",
"this",
".",
"uploader",
".",
"removeFile",
"(",
"file",
")",
";",
"}"
]
| Remove the file from the queue.
@method removeFile
@param {plupload.File|String} file File to remove, might be specified directly or by it's unique id | [
"Remove",
"the",
"file",
"from",
"the",
"queue",
"."
]
| 88030bb4222945900e6a225469380cc43a016c13 | https://github.com/hl198181/neptune/blob/88030bb4222945900e6a225469380cc43a016c13/misc/demo/public/vendor/plupload-2.1.2/js/jquery.ui.plupload/jquery.ui.plupload.js#L728-L733 | train |
|
hl198181/neptune | misc/demo/public/vendor/plupload-2.1.2/js/jquery.ui.plupload/jquery.ui.plupload.js | function(type, message) {
var popup = $(
'<div class="plupload_message">' +
'<span class="plupload_message_close ui-icon ui-icon-circle-close" title="'+_('Close')+'"></span>' +
'<p><span class="ui-icon"></span>' + message + '</p>' +
'</div>'
);
popup
.addClass('ui-state-' + (type === 'error' ? 'error' : 'highlight'))
.find('p .ui-icon')
.addClass('ui-icon-' + (type === 'error' ? 'alert' : 'info'))
.end()
.find('.plupload_message_close')
.click(function() {
popup.remove();
})
.end();
$('.plupload_header', this.container).append(popup);
} | javascript | function(type, message) {
var popup = $(
'<div class="plupload_message">' +
'<span class="plupload_message_close ui-icon ui-icon-circle-close" title="'+_('Close')+'"></span>' +
'<p><span class="ui-icon"></span>' + message + '</p>' +
'</div>'
);
popup
.addClass('ui-state-' + (type === 'error' ? 'error' : 'highlight'))
.find('p .ui-icon')
.addClass('ui-icon-' + (type === 'error' ? 'alert' : 'info'))
.end()
.find('.plupload_message_close')
.click(function() {
popup.remove();
})
.end();
$('.plupload_header', this.container).append(popup);
} | [
"function",
"(",
"type",
",",
"message",
")",
"{",
"var",
"popup",
"=",
"$",
"(",
"'<div class=\"plupload_message\">'",
"+",
"'<span class=\"plupload_message_close ui-icon ui-icon-circle-close\" title=\"'",
"+",
"_",
"(",
"'Close'",
")",
"+",
"'\"></span>'",
"+",
"'<p><span class=\"ui-icon\"></span>'",
"+",
"message",
"+",
"'</p>'",
"+",
"'</div>'",
")",
";",
"popup",
".",
"addClass",
"(",
"'ui-state-'",
"+",
"(",
"type",
"===",
"'error'",
"?",
"'error'",
":",
"'highlight'",
")",
")",
".",
"find",
"(",
"'p .ui-icon'",
")",
".",
"addClass",
"(",
"'ui-icon-'",
"+",
"(",
"type",
"===",
"'error'",
"?",
"'alert'",
":",
"'info'",
")",
")",
".",
"end",
"(",
")",
".",
"find",
"(",
"'.plupload_message_close'",
")",
".",
"click",
"(",
"function",
"(",
")",
"{",
"popup",
".",
"remove",
"(",
")",
";",
"}",
")",
".",
"end",
"(",
")",
";",
"$",
"(",
"'.plupload_header'",
",",
"this",
".",
"container",
")",
".",
"append",
"(",
"popup",
")",
";",
"}"
]
| Display a message in notification area.
@method notify
@param {Enum} type Type of the message, either `error` or `info`
@param {String} message The text message to display. | [
"Display",
"a",
"message",
"in",
"notification",
"area",
"."
]
| 88030bb4222945900e6a225469380cc43a016c13 | https://github.com/hl198181/neptune/blob/88030bb4222945900e6a225469380cc43a016c13/misc/demo/public/vendor/plupload-2.1.2/js/jquery.ui.plupload/jquery.ui.plupload.js#L777-L797 | train |
|
hl198181/neptune | misc/demo/public/vendor/plupload-2.1.2/js/jquery.ui.plupload/jquery.ui.plupload.js | function() {
// destroy uploader instance
this.uploader.destroy();
// unbind all button events
$('.plupload_button', this.element).unbind();
// destroy buttons
if ($.ui.button) {
$('.plupload_add, .plupload_start, .plupload_stop', this.container)
.button('destroy');
}
// destroy progressbar
if ($.ui.progressbar) {
this.progressbar.progressbar('destroy');
}
// destroy sortable behavior
if ($.ui.sortable && this.options.sortable) {
$('tbody', this.filelist).sortable('destroy');
}
// restore the elements initial state
this.element
.empty()
.html(this.contents_bak);
this.contents_bak = '';
$.Widget.prototype.destroy.apply(this);
} | javascript | function() {
// destroy uploader instance
this.uploader.destroy();
// unbind all button events
$('.plupload_button', this.element).unbind();
// destroy buttons
if ($.ui.button) {
$('.plupload_add, .plupload_start, .plupload_stop', this.container)
.button('destroy');
}
// destroy progressbar
if ($.ui.progressbar) {
this.progressbar.progressbar('destroy');
}
// destroy sortable behavior
if ($.ui.sortable && this.options.sortable) {
$('tbody', this.filelist).sortable('destroy');
}
// restore the elements initial state
this.element
.empty()
.html(this.contents_bak);
this.contents_bak = '';
$.Widget.prototype.destroy.apply(this);
} | [
"function",
"(",
")",
"{",
"this",
".",
"uploader",
".",
"destroy",
"(",
")",
";",
"$",
"(",
"'.plupload_button'",
",",
"this",
".",
"element",
")",
".",
"unbind",
"(",
")",
";",
"if",
"(",
"$",
".",
"ui",
".",
"button",
")",
"{",
"$",
"(",
"'.plupload_add, .plupload_start, .plupload_stop'",
",",
"this",
".",
"container",
")",
".",
"button",
"(",
"'destroy'",
")",
";",
"}",
"if",
"(",
"$",
".",
"ui",
".",
"progressbar",
")",
"{",
"this",
".",
"progressbar",
".",
"progressbar",
"(",
"'destroy'",
")",
";",
"}",
"if",
"(",
"$",
".",
"ui",
".",
"sortable",
"&&",
"this",
".",
"options",
".",
"sortable",
")",
"{",
"$",
"(",
"'tbody'",
",",
"this",
".",
"filelist",
")",
".",
"sortable",
"(",
"'destroy'",
")",
";",
"}",
"this",
".",
"element",
".",
"empty",
"(",
")",
".",
"html",
"(",
"this",
".",
"contents_bak",
")",
";",
"this",
".",
"contents_bak",
"=",
"''",
";",
"$",
".",
"Widget",
".",
"prototype",
".",
"destroy",
".",
"apply",
"(",
"this",
")",
";",
"}"
]
| Destroy the widget, the uploader, free associated resources and bring back original html.
@method destroy | [
"Destroy",
"the",
"widget",
"the",
"uploader",
"free",
"associated",
"resources",
"and",
"bring",
"back",
"original",
"html",
"."
]
| 88030bb4222945900e6a225469380cc43a016c13 | https://github.com/hl198181/neptune/blob/88030bb4222945900e6a225469380cc43a016c13/misc/demo/public/vendor/plupload-2.1.2/js/jquery.ui.plupload/jquery.ui.plupload.js#L805-L835 | train |
|
hl198181/neptune | misc/demo/public/vendor/plupload-2.1.2/js/jquery.ui.plupload/jquery.ui.plupload.js | measure | function measure() {
if (!tw || !th) {
var wrapper = $('.plupload_file:eq(0)', self.filelist);
tw = wrapper.outerWidth(true);
th = wrapper.outerHeight(true);
}
var aw = self.content.width(), ah = self.content.height();
cols = Math.floor(aw / tw);
num = cols * (Math.ceil(ah / th) + 1);
} | javascript | function measure() {
if (!tw || !th) {
var wrapper = $('.plupload_file:eq(0)', self.filelist);
tw = wrapper.outerWidth(true);
th = wrapper.outerHeight(true);
}
var aw = self.content.width(), ah = self.content.height();
cols = Math.floor(aw / tw);
num = cols * (Math.ceil(ah / th) + 1);
} | [
"function",
"measure",
"(",
")",
"{",
"if",
"(",
"!",
"tw",
"||",
"!",
"th",
")",
"{",
"var",
"wrapper",
"=",
"$",
"(",
"'.plupload_file:eq(0)'",
",",
"self",
".",
"filelist",
")",
";",
"tw",
"=",
"wrapper",
".",
"outerWidth",
"(",
"true",
")",
";",
"th",
"=",
"wrapper",
".",
"outerHeight",
"(",
"true",
")",
";",
"}",
"var",
"aw",
"=",
"self",
".",
"content",
".",
"width",
"(",
")",
",",
"ah",
"=",
"self",
".",
"content",
".",
"height",
"(",
")",
";",
"cols",
"=",
"Math",
".",
"floor",
"(",
"aw",
"/",
"tw",
")",
";",
"num",
"=",
"cols",
"*",
"(",
"Math",
".",
"ceil",
"(",
"ah",
"/",
"th",
")",
"+",
"1",
")",
";",
"}"
]
| calculate number of simultaneously visible thumbs | [
"calculate",
"number",
"of",
"simultaneously",
"visible",
"thumbs"
]
| 88030bb4222945900e6a225469380cc43a016c13 | https://github.com/hl198181/neptune/blob/88030bb4222945900e6a225469380cc43a016c13/misc/demo/public/vendor/plupload-2.1.2/js/jquery.ui.plupload/jquery.ui.plupload.js#L1003-L1013 | train |
dominictarr/pull-obv | index.js | obv | function obv (fn, immediate) {
if(!fn) return state
listeners.push(fn)
if(immediate !== false && fn(state) === true) obv.more()
return function () {
var i = listeners.indexOf(fn)
listeners.splice(i, 1)
}
} | javascript | function obv (fn, immediate) {
if(!fn) return state
listeners.push(fn)
if(immediate !== false && fn(state) === true) obv.more()
return function () {
var i = listeners.indexOf(fn)
listeners.splice(i, 1)
}
} | [
"function",
"obv",
"(",
"fn",
",",
"immediate",
")",
"{",
"if",
"(",
"!",
"fn",
")",
"return",
"state",
"listeners",
".",
"push",
"(",
"fn",
")",
"if",
"(",
"immediate",
"!==",
"false",
"&&",
"fn",
"(",
"state",
")",
"===",
"true",
")",
"obv",
".",
"more",
"(",
")",
"return",
"function",
"(",
")",
"{",
"var",
"i",
"=",
"listeners",
".",
"indexOf",
"(",
"fn",
")",
"listeners",
".",
"splice",
"(",
"i",
",",
"1",
")",
"}",
"}"
]
| implement an observable | [
"implement",
"an",
"observable"
]
| 414d8959624f0d9207bfe27c9ac8aa60513114fb | https://github.com/dominictarr/pull-obv/blob/414d8959624f0d9207bfe27c9ac8aa60513114fb/index.js#L10-L18 | train |
sergiodxa/SukimaJS | index.js | isValid | function isValid (type, value) {
switch (type) {
case 'email':
return validator.isEmail(value);
break;
case 'url':
return validator.isURL(value);
break;
case 'domain':
return validator.isFQDN(value);
break;
case 'ip':
return validator.isIP(value);
break;
case 'alpha':
return validator.isAlpha(value);
break;
case 'number':
return validator.isNumeric(value);
break;
case 'alphanumeric':
return validator.isAlphanumeric(value);
break;
case 'base64':
return validator.isBase64(value);
break;
case 'hexadecimal':
return validator.isHexadecimal(value);
break;
case 'hexcolor':
return validator.isHexColor(value);
break;
case 'int':
return validator.isInt(value);
break;
case 'float':
return validator.isFloat(value);
break;
case 'null':
return validator.isNull(value);
break;
case 'uuid':
return validator.isUUID(value);
break;
case 'date':
return validator.isDate(value);
break;
case 'creditcard':
return validator.isCreditCard(value);
break;
case 'isbn':
return validator.isISBN(value);
break;
case 'mobilephone':
return validator.isMobilePhone(value);
break;
case 'json':
return validator.isJSON(value);
break;
case 'ascii':
return validator.isAscii(value);
break;
case 'mongoid':
return validator.isMongoId(value);
break;
default:
return false;
break;
}
} | javascript | function isValid (type, value) {
switch (type) {
case 'email':
return validator.isEmail(value);
break;
case 'url':
return validator.isURL(value);
break;
case 'domain':
return validator.isFQDN(value);
break;
case 'ip':
return validator.isIP(value);
break;
case 'alpha':
return validator.isAlpha(value);
break;
case 'number':
return validator.isNumeric(value);
break;
case 'alphanumeric':
return validator.isAlphanumeric(value);
break;
case 'base64':
return validator.isBase64(value);
break;
case 'hexadecimal':
return validator.isHexadecimal(value);
break;
case 'hexcolor':
return validator.isHexColor(value);
break;
case 'int':
return validator.isInt(value);
break;
case 'float':
return validator.isFloat(value);
break;
case 'null':
return validator.isNull(value);
break;
case 'uuid':
return validator.isUUID(value);
break;
case 'date':
return validator.isDate(value);
break;
case 'creditcard':
return validator.isCreditCard(value);
break;
case 'isbn':
return validator.isISBN(value);
break;
case 'mobilephone':
return validator.isMobilePhone(value);
break;
case 'json':
return validator.isJSON(value);
break;
case 'ascii':
return validator.isAscii(value);
break;
case 'mongoid':
return validator.isMongoId(value);
break;
default:
return false;
break;
}
} | [
"function",
"isValid",
"(",
"type",
",",
"value",
")",
"{",
"switch",
"(",
"type",
")",
"{",
"case",
"'email'",
":",
"return",
"validator",
".",
"isEmail",
"(",
"value",
")",
";",
"break",
";",
"case",
"'url'",
":",
"return",
"validator",
".",
"isURL",
"(",
"value",
")",
";",
"break",
";",
"case",
"'domain'",
":",
"return",
"validator",
".",
"isFQDN",
"(",
"value",
")",
";",
"break",
";",
"case",
"'ip'",
":",
"return",
"validator",
".",
"isIP",
"(",
"value",
")",
";",
"break",
";",
"case",
"'alpha'",
":",
"return",
"validator",
".",
"isAlpha",
"(",
"value",
")",
";",
"break",
";",
"case",
"'number'",
":",
"return",
"validator",
".",
"isNumeric",
"(",
"value",
")",
";",
"break",
";",
"case",
"'alphanumeric'",
":",
"return",
"validator",
".",
"isAlphanumeric",
"(",
"value",
")",
";",
"break",
";",
"case",
"'base64'",
":",
"return",
"validator",
".",
"isBase64",
"(",
"value",
")",
";",
"break",
";",
"case",
"'hexadecimal'",
":",
"return",
"validator",
".",
"isHexadecimal",
"(",
"value",
")",
";",
"break",
";",
"case",
"'hexcolor'",
":",
"return",
"validator",
".",
"isHexColor",
"(",
"value",
")",
";",
"break",
";",
"case",
"'int'",
":",
"return",
"validator",
".",
"isInt",
"(",
"value",
")",
";",
"break",
";",
"case",
"'float'",
":",
"return",
"validator",
".",
"isFloat",
"(",
"value",
")",
";",
"break",
";",
"case",
"'null'",
":",
"return",
"validator",
".",
"isNull",
"(",
"value",
")",
";",
"break",
";",
"case",
"'uuid'",
":",
"return",
"validator",
".",
"isUUID",
"(",
"value",
")",
";",
"break",
";",
"case",
"'date'",
":",
"return",
"validator",
".",
"isDate",
"(",
"value",
")",
";",
"break",
";",
"case",
"'creditcard'",
":",
"return",
"validator",
".",
"isCreditCard",
"(",
"value",
")",
";",
"break",
";",
"case",
"'isbn'",
":",
"return",
"validator",
".",
"isISBN",
"(",
"value",
")",
";",
"break",
";",
"case",
"'mobilephone'",
":",
"return",
"validator",
".",
"isMobilePhone",
"(",
"value",
")",
";",
"break",
";",
"case",
"'json'",
":",
"return",
"validator",
".",
"isJSON",
"(",
"value",
")",
";",
"break",
";",
"case",
"'ascii'",
":",
"return",
"validator",
".",
"isAscii",
"(",
"value",
")",
";",
"break",
";",
"case",
"'mongoid'",
":",
"return",
"validator",
".",
"isMongoId",
"(",
"value",
")",
";",
"break",
";",
"default",
":",
"return",
"false",
";",
"break",
";",
"}",
"}"
]
| call a validator method depending on type | [
"call",
"a",
"validator",
"method",
"depending",
"on",
"type"
]
| 9218a49ff2352a6d7ae989bf4150f70fed9e1b12 | https://github.com/sergiodxa/SukimaJS/blob/9218a49ff2352a6d7ae989bf4150f70fed9e1b12/index.js#L9-L78 | train |
dylants/debug-caller | lib/debug-caller.js | _buildNamespace | function _buildNamespace(appName, depth) {
var callerFile;
// Our default depth needs to be 2, since 1 is this file. Add the user
// supplied depth to 1 (for this file) to make it 2.
callerFile = caller(depth + 1);
// if for some reason we're unable to determine the caller, use the appName only
if (!callerFile) {
return appName;
}
// TODO in later versions of Node (v0.12.+), there is simple `path.parse`
// which will provide us with the file name property. But until most have
// moved up to that version, find the caller file name in this way...
// find the filename from the path
callerFile = path.basename(callerFile);
// strip off the suffix (if any)
if (path.extname(callerFile)) {
callerFile = callerFile.slice(0, callerFile.indexOf(path.extname(callerFile)));
}
return appName + ":" + callerFile;
} | javascript | function _buildNamespace(appName, depth) {
var callerFile;
// Our default depth needs to be 2, since 1 is this file. Add the user
// supplied depth to 1 (for this file) to make it 2.
callerFile = caller(depth + 1);
// if for some reason we're unable to determine the caller, use the appName only
if (!callerFile) {
return appName;
}
// TODO in later versions of Node (v0.12.+), there is simple `path.parse`
// which will provide us with the file name property. But until most have
// moved up to that version, find the caller file name in this way...
// find the filename from the path
callerFile = path.basename(callerFile);
// strip off the suffix (if any)
if (path.extname(callerFile)) {
callerFile = callerFile.slice(0, callerFile.indexOf(path.extname(callerFile)));
}
return appName + ":" + callerFile;
} | [
"function",
"_buildNamespace",
"(",
"appName",
",",
"depth",
")",
"{",
"var",
"callerFile",
";",
"callerFile",
"=",
"caller",
"(",
"depth",
"+",
"1",
")",
";",
"if",
"(",
"!",
"callerFile",
")",
"{",
"return",
"appName",
";",
"}",
"callerFile",
"=",
"path",
".",
"basename",
"(",
"callerFile",
")",
";",
"if",
"(",
"path",
".",
"extname",
"(",
"callerFile",
")",
")",
"{",
"callerFile",
"=",
"callerFile",
".",
"slice",
"(",
"0",
",",
"callerFile",
".",
"indexOf",
"(",
"path",
".",
"extname",
"(",
"callerFile",
")",
")",
")",
";",
"}",
"return",
"appName",
"+",
"\":\"",
"+",
"callerFile",
";",
"}"
]
| Returns the descriptive text used in the debug instantiation, which at this
point is the app + calling filename. Allow the user to specify a depth for the
calling filename, in the case they have a wrapping function calling this.
@param {String} appName The application name, used in the namespace
@param {Number} depth Depth used to determine caller filename
@return {String} The app + calling filename | [
"Returns",
"the",
"descriptive",
"text",
"used",
"in",
"the",
"debug",
"instantiation",
"which",
"at",
"this",
"point",
"is",
"the",
"app",
"+",
"calling",
"filename",
".",
"Allow",
"the",
"user",
"to",
"specify",
"a",
"depth",
"for",
"the",
"calling",
"filename",
"in",
"the",
"case",
"they",
"have",
"a",
"wrapping",
"function",
"calling",
"this",
"."
]
| b54c0f1d3825ef5015624f6f874ea6d955c08d92 | https://github.com/dylants/debug-caller/blob/b54c0f1d3825ef5015624f6f874ea6d955c08d92/lib/debug-caller.js#L18-L43 | train |
dylants/debug-caller | lib/debug-caller.js | logger | function logger(appName, options) {
var namespace, log, error;
options = options ? options : {};
// merge our default options with the user supplied
options = xtend({
depth: 1,
randomColors: false,
logColor: 7,
errorColor: 1,
}, options);
// get the filename which is used as the namespace for the debug module.
namespace = _buildNamespace(appName, options.depth);
// setup two debug'ers, one for console.log and one for console.error
log = debug(namespace);
// bind the log to console.log
log.log = console.log.bind(console);
error = debug(namespace);
// this should happen by default, but just to be sure...
error.log = console.error.bind(console);
// if we don't want random colors, assign log to options.logColor (default: white (7))
// and error to options.errorColor (default: red (1))
if (!options.randomColors) {
log.color = options.logColor;
error.color = options.errorColor;
}
return {
// return the two debug'ers under the log and error functions
log: log,
error: error,
// include the namespace in case the client needs it
namespace: namespace
};
} | javascript | function logger(appName, options) {
var namespace, log, error;
options = options ? options : {};
// merge our default options with the user supplied
options = xtend({
depth: 1,
randomColors: false,
logColor: 7,
errorColor: 1,
}, options);
// get the filename which is used as the namespace for the debug module.
namespace = _buildNamespace(appName, options.depth);
// setup two debug'ers, one for console.log and one for console.error
log = debug(namespace);
// bind the log to console.log
log.log = console.log.bind(console);
error = debug(namespace);
// this should happen by default, but just to be sure...
error.log = console.error.bind(console);
// if we don't want random colors, assign log to options.logColor (default: white (7))
// and error to options.errorColor (default: red (1))
if (!options.randomColors) {
log.color = options.logColor;
error.color = options.errorColor;
}
return {
// return the two debug'ers under the log and error functions
log: log,
error: error,
// include the namespace in case the client needs it
namespace: namespace
};
} | [
"function",
"logger",
"(",
"appName",
",",
"options",
")",
"{",
"var",
"namespace",
",",
"log",
",",
"error",
";",
"options",
"=",
"options",
"?",
"options",
":",
"{",
"}",
";",
"options",
"=",
"xtend",
"(",
"{",
"depth",
":",
"1",
",",
"randomColors",
":",
"false",
",",
"logColor",
":",
"7",
",",
"errorColor",
":",
"1",
",",
"}",
",",
"options",
")",
";",
"namespace",
"=",
"_buildNamespace",
"(",
"appName",
",",
"options",
".",
"depth",
")",
";",
"log",
"=",
"debug",
"(",
"namespace",
")",
";",
"log",
".",
"log",
"=",
"console",
".",
"log",
".",
"bind",
"(",
"console",
")",
";",
"error",
"=",
"debug",
"(",
"namespace",
")",
";",
"error",
".",
"log",
"=",
"console",
".",
"error",
".",
"bind",
"(",
"console",
")",
";",
"if",
"(",
"!",
"options",
".",
"randomColors",
")",
"{",
"log",
".",
"color",
"=",
"options",
".",
"logColor",
";",
"error",
".",
"color",
"=",
"options",
".",
"errorColor",
";",
"}",
"return",
"{",
"log",
":",
"log",
",",
"error",
":",
"error",
",",
"namespace",
":",
"namespace",
"}",
";",
"}"
]
| Creates the `debug` object using the namespace built from the `appName`
and calling filename. Creates 2 loggers, one for log, one for error.
@param {String} appName The application name, used in the namespace
@param {Object} options Optional: The options to use for configuration
@return {Object} An object with two debug'ers: log and error,
alone with the namespace used for the logger | [
"Creates",
"the",
"debug",
"object",
"using",
"the",
"namespace",
"built",
"from",
"the",
"appName",
"and",
"calling",
"filename",
".",
"Creates",
"2",
"loggers",
"one",
"for",
"log",
"one",
"for",
"error",
"."
]
| b54c0f1d3825ef5015624f6f874ea6d955c08d92 | https://github.com/dylants/debug-caller/blob/b54c0f1d3825ef5015624f6f874ea6d955c08d92/lib/debug-caller.js#L55-L94 | train |
sendanor/nor-api-session | src/session.js | init_session | function init_session(req) {
debug.assert(req.session).is('object');
if(!is.obj(req.session.client)) {
req.session.client = {};
}
if( (!is.obj(req.session.client.messages)) || is.array(req.session.client.messages) ) {
req.session.client.messages = {};
}
} | javascript | function init_session(req) {
debug.assert(req.session).is('object');
if(!is.obj(req.session.client)) {
req.session.client = {};
}
if( (!is.obj(req.session.client.messages)) || is.array(req.session.client.messages) ) {
req.session.client.messages = {};
}
} | [
"function",
"init_session",
"(",
"req",
")",
"{",
"debug",
".",
"assert",
"(",
"req",
".",
"session",
")",
".",
"is",
"(",
"'object'",
")",
";",
"if",
"(",
"!",
"is",
".",
"obj",
"(",
"req",
".",
"session",
".",
"client",
")",
")",
"{",
"req",
".",
"session",
".",
"client",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"(",
"!",
"is",
".",
"obj",
"(",
"req",
".",
"session",
".",
"client",
".",
"messages",
")",
")",
"||",
"is",
".",
"array",
"(",
"req",
".",
"session",
".",
"client",
".",
"messages",
")",
")",
"{",
"req",
".",
"session",
".",
"client",
".",
"messages",
"=",
"{",
"}",
";",
"}",
"}"
]
| Initialize the session | [
"Initialize",
"the",
"session"
]
| be1aa653a12ecad2d10b69c3698ca0e30c3099f1 | https://github.com/sendanor/nor-api-session/blob/be1aa653a12ecad2d10b69c3698ca0e30c3099f1/src/session.js#L15-L23 | train |
UXFoundry/hashdo-web | index.js | function (baseUrl, firebaseUrl, port, cardsDirectory) {
// Set environment variables.
process.env.BASE_URL = baseUrl || '';
process.env.FIREBASE_URL = firebaseUrl || 'https://hashdodemo.firebaseio.com/',
process.env.CARDS_DIRECTORY = cardsDirectory || process.cwd();
process.env.PORT = port || 4000;
var Path = require('path'),
Favicon = require('serve-favicon'),
Hpp = require('hpp');
App.use(Timeout('10s'));
App.use(Favicon(Path.join(__dirname, '/public/favicon.ico')));
App.use(Express.static('public'));
// Hacky, quick fix required for now.
// **********************************
App.use('/js', Express.static(Path.join(__dirname, '/node_modules/hashdo/public/js')));
App.use('/css', Express.static(Path.join(__dirname, '/node_modules/hashdo/public/css')));
// **********************************
App.use(BodyParser.urlencoded({extended: false, limit: '5mb'}));
App.use(Hpp());
App.use(Cors());
App.use(haltOnTimedout);
function haltOnTimedout(req, res, next){
if (!req.timedout) next();
}
// Assume cards directory is based off root if a full path is not provided.
if (!Path.isAbsolute(process.env.CARDS_DIRECTORY)) {
process.env.CARDS_DIRECTORY = Path.join(process.cwd(), process.env.CARDS_DIRECTORY);
}
HashDo.packs.init(baseUrl, process.env.CARDS_DIRECTORY);
// Make public card directories static
HashDo.packs.cards().forEach(function (card) {
var packDirectory = Path.join(cardsDirectory, 'hashdo-' + card.pack);
App.use('/' + card.pack + '/' + card.card, Express.static(Path.join(packDirectory, 'public', card.card)));
});
} | javascript | function (baseUrl, firebaseUrl, port, cardsDirectory) {
// Set environment variables.
process.env.BASE_URL = baseUrl || '';
process.env.FIREBASE_URL = firebaseUrl || 'https://hashdodemo.firebaseio.com/',
process.env.CARDS_DIRECTORY = cardsDirectory || process.cwd();
process.env.PORT = port || 4000;
var Path = require('path'),
Favicon = require('serve-favicon'),
Hpp = require('hpp');
App.use(Timeout('10s'));
App.use(Favicon(Path.join(__dirname, '/public/favicon.ico')));
App.use(Express.static('public'));
// Hacky, quick fix required for now.
// **********************************
App.use('/js', Express.static(Path.join(__dirname, '/node_modules/hashdo/public/js')));
App.use('/css', Express.static(Path.join(__dirname, '/node_modules/hashdo/public/css')));
// **********************************
App.use(BodyParser.urlencoded({extended: false, limit: '5mb'}));
App.use(Hpp());
App.use(Cors());
App.use(haltOnTimedout);
function haltOnTimedout(req, res, next){
if (!req.timedout) next();
}
// Assume cards directory is based off root if a full path is not provided.
if (!Path.isAbsolute(process.env.CARDS_DIRECTORY)) {
process.env.CARDS_DIRECTORY = Path.join(process.cwd(), process.env.CARDS_DIRECTORY);
}
HashDo.packs.init(baseUrl, process.env.CARDS_DIRECTORY);
// Make public card directories static
HashDo.packs.cards().forEach(function (card) {
var packDirectory = Path.join(cardsDirectory, 'hashdo-' + card.pack);
App.use('/' + card.pack + '/' + card.card, Express.static(Path.join(packDirectory, 'public', card.card)));
});
} | [
"function",
"(",
"baseUrl",
",",
"firebaseUrl",
",",
"port",
",",
"cardsDirectory",
")",
"{",
"process",
".",
"env",
".",
"BASE_URL",
"=",
"baseUrl",
"||",
"''",
";",
"process",
".",
"env",
".",
"FIREBASE_URL",
"=",
"firebaseUrl",
"||",
"'https://hashdodemo.firebaseio.com/'",
",",
"process",
".",
"env",
".",
"CARDS_DIRECTORY",
"=",
"cardsDirectory",
"||",
"process",
".",
"cwd",
"(",
")",
";",
"process",
".",
"env",
".",
"PORT",
"=",
"port",
"||",
"4000",
";",
"var",
"Path",
"=",
"require",
"(",
"'path'",
")",
",",
"Favicon",
"=",
"require",
"(",
"'serve-favicon'",
")",
",",
"Hpp",
"=",
"require",
"(",
"'hpp'",
")",
";",
"App",
".",
"use",
"(",
"Timeout",
"(",
"'10s'",
")",
")",
";",
"App",
".",
"use",
"(",
"Favicon",
"(",
"Path",
".",
"join",
"(",
"__dirname",
",",
"'/public/favicon.ico'",
")",
")",
")",
";",
"App",
".",
"use",
"(",
"Express",
".",
"static",
"(",
"'public'",
")",
")",
";",
"App",
".",
"use",
"(",
"'/js'",
",",
"Express",
".",
"static",
"(",
"Path",
".",
"join",
"(",
"__dirname",
",",
"'/node_modules/hashdo/public/js'",
")",
")",
")",
";",
"App",
".",
"use",
"(",
"'/css'",
",",
"Express",
".",
"static",
"(",
"Path",
".",
"join",
"(",
"__dirname",
",",
"'/node_modules/hashdo/public/css'",
")",
")",
")",
";",
"App",
".",
"use",
"(",
"BodyParser",
".",
"urlencoded",
"(",
"{",
"extended",
":",
"false",
",",
"limit",
":",
"'5mb'",
"}",
")",
")",
";",
"App",
".",
"use",
"(",
"Hpp",
"(",
")",
")",
";",
"App",
".",
"use",
"(",
"Cors",
"(",
")",
")",
";",
"App",
".",
"use",
"(",
"haltOnTimedout",
")",
";",
"function",
"haltOnTimedout",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"!",
"req",
".",
"timedout",
")",
"next",
"(",
")",
";",
"}",
"if",
"(",
"!",
"Path",
".",
"isAbsolute",
"(",
"process",
".",
"env",
".",
"CARDS_DIRECTORY",
")",
")",
"{",
"process",
".",
"env",
".",
"CARDS_DIRECTORY",
"=",
"Path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"process",
".",
"env",
".",
"CARDS_DIRECTORY",
")",
";",
"}",
"HashDo",
".",
"packs",
".",
"init",
"(",
"baseUrl",
",",
"process",
".",
"env",
".",
"CARDS_DIRECTORY",
")",
";",
"HashDo",
".",
"packs",
".",
"cards",
"(",
")",
".",
"forEach",
"(",
"function",
"(",
"card",
")",
"{",
"var",
"packDirectory",
"=",
"Path",
".",
"join",
"(",
"cardsDirectory",
",",
"'hashdo-'",
"+",
"card",
".",
"pack",
")",
";",
"App",
".",
"use",
"(",
"'/'",
"+",
"card",
".",
"pack",
"+",
"'/'",
"+",
"card",
".",
"card",
",",
"Express",
".",
"static",
"(",
"Path",
".",
"join",
"(",
"packDirectory",
",",
"'public'",
",",
"card",
".",
"card",
")",
")",
")",
";",
"}",
")",
";",
"}"
]
| Configured process events and middleware required to run the web application.
This function should always be called before starting the web server.
@method init
@param {String} baseUrl The URL that the web application will be accessible from.
@param {String} [firebaseUrl] Optional Firebase URL for real-time client updates. If not provided 'https://hashdodemo.firebaseio.com/' will be used.
@param {Number} [port] Optional port the web server will listen on. If not provided 4000 will be used.
@params {String} [cardsDirectory] Optional cards directory where your #Do cards will be loaded from. If not provided then cards will be searched for in the current working directory. | [
"Configured",
"process",
"events",
"and",
"middleware",
"required",
"to",
"run",
"the",
"web",
"application",
".",
"This",
"function",
"should",
"always",
"be",
"called",
"before",
"starting",
"the",
"web",
"server",
"."
]
| ec69928cf4515a496f85d9af5926bfe8a4344465 | https://github.com/UXFoundry/hashdo-web/blob/ec69928cf4515a496f85d9af5926bfe8a4344465/index.js#L41-L81 | train |
|
UXFoundry/hashdo-web | index.js | function (callback) {
var APIController = require('./controllers/api'),
DefaultController = require('./controllers/index'),
PackController = require('./controllers/pack'),
CardController = require('./controllers/card'),
WebHookController = require('./controllers/webhook'),
ProxyController = require('./controllers/proxy'),
JsonParser = BodyParser.json({strict: false});
// Disable caching middleware.
var nocache = function (req, res, next) {
res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
res.header('Expires', '-1');
res.header('Pragma', 'no-cache');
next();
};
// Setup routes late to give implementers routes higher priority and allow middleware as well.
App.get('/api/count', nocache, APIController.count);
App.get('/api/cards', nocache, APIController.cards);
App.get('/api/card', nocache, APIController.card);
App.post('/api/card/state/save', APIController.saveState);
App.post('/api/card/state/clear', APIController.clearState);
App.post('/api/card/analytics', APIController.recordAnalyticEvents);
// Proxy
App.post('/proxy/:pack/:card', ProxyController.post);
// Web Hooks
App.post('/webhook/:pack/:card', WebHookController.process);
// Card Routes
App.post('/:pack/:card', JsonParser, CardController.post);
App.get('/:pack/:card', CardController.get);
App.get('/:pack', PackController);
App.get('/', DefaultController);
var exit = function () {
HashDo.db.disconnect(function () {
process.exit(0);
});
};
// Gracefully disconnect from the database on expected exit.
process.on('SIGINT', exit);
process.on('SIGTERM', exit);
// Global error handler (always exit for programmatic errors).
process.on('uncaughtException', function (err) {
console.error('FATAL: ', err.message);
console.error(err.stack);
process.exit(1);
});
// Connect to the database and start server on successful connection.
HashDo.db.connect(function (err) {
if (err) {
console.error('FATAL: Could not connect to database.', err);
process.exit(1);
}
else {
console.log('WEB: Starting web server on port %d...', process.env.PORT);
App.listen(process.env.PORT, function () {
console.log();
console.log('Let\'s #Do');
callback && callback();
});
}
});
} | javascript | function (callback) {
var APIController = require('./controllers/api'),
DefaultController = require('./controllers/index'),
PackController = require('./controllers/pack'),
CardController = require('./controllers/card'),
WebHookController = require('./controllers/webhook'),
ProxyController = require('./controllers/proxy'),
JsonParser = BodyParser.json({strict: false});
// Disable caching middleware.
var nocache = function (req, res, next) {
res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
res.header('Expires', '-1');
res.header('Pragma', 'no-cache');
next();
};
// Setup routes late to give implementers routes higher priority and allow middleware as well.
App.get('/api/count', nocache, APIController.count);
App.get('/api/cards', nocache, APIController.cards);
App.get('/api/card', nocache, APIController.card);
App.post('/api/card/state/save', APIController.saveState);
App.post('/api/card/state/clear', APIController.clearState);
App.post('/api/card/analytics', APIController.recordAnalyticEvents);
// Proxy
App.post('/proxy/:pack/:card', ProxyController.post);
// Web Hooks
App.post('/webhook/:pack/:card', WebHookController.process);
// Card Routes
App.post('/:pack/:card', JsonParser, CardController.post);
App.get('/:pack/:card', CardController.get);
App.get('/:pack', PackController);
App.get('/', DefaultController);
var exit = function () {
HashDo.db.disconnect(function () {
process.exit(0);
});
};
// Gracefully disconnect from the database on expected exit.
process.on('SIGINT', exit);
process.on('SIGTERM', exit);
// Global error handler (always exit for programmatic errors).
process.on('uncaughtException', function (err) {
console.error('FATAL: ', err.message);
console.error(err.stack);
process.exit(1);
});
// Connect to the database and start server on successful connection.
HashDo.db.connect(function (err) {
if (err) {
console.error('FATAL: Could not connect to database.', err);
process.exit(1);
}
else {
console.log('WEB: Starting web server on port %d...', process.env.PORT);
App.listen(process.env.PORT, function () {
console.log();
console.log('Let\'s #Do');
callback && callback();
});
}
});
} | [
"function",
"(",
"callback",
")",
"{",
"var",
"APIController",
"=",
"require",
"(",
"'./controllers/api'",
")",
",",
"DefaultController",
"=",
"require",
"(",
"'./controllers/index'",
")",
",",
"PackController",
"=",
"require",
"(",
"'./controllers/pack'",
")",
",",
"CardController",
"=",
"require",
"(",
"'./controllers/card'",
")",
",",
"WebHookController",
"=",
"require",
"(",
"'./controllers/webhook'",
")",
",",
"ProxyController",
"=",
"require",
"(",
"'./controllers/proxy'",
")",
",",
"JsonParser",
"=",
"BodyParser",
".",
"json",
"(",
"{",
"strict",
":",
"false",
"}",
")",
";",
"var",
"nocache",
"=",
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"res",
".",
"header",
"(",
"'Cache-Control'",
",",
"'private, no-cache, no-store, must-revalidate'",
")",
";",
"res",
".",
"header",
"(",
"'Expires'",
",",
"'-1'",
")",
";",
"res",
".",
"header",
"(",
"'Pragma'",
",",
"'no-cache'",
")",
";",
"next",
"(",
")",
";",
"}",
";",
"App",
".",
"get",
"(",
"'/api/count'",
",",
"nocache",
",",
"APIController",
".",
"count",
")",
";",
"App",
".",
"get",
"(",
"'/api/cards'",
",",
"nocache",
",",
"APIController",
".",
"cards",
")",
";",
"App",
".",
"get",
"(",
"'/api/card'",
",",
"nocache",
",",
"APIController",
".",
"card",
")",
";",
"App",
".",
"post",
"(",
"'/api/card/state/save'",
",",
"APIController",
".",
"saveState",
")",
";",
"App",
".",
"post",
"(",
"'/api/card/state/clear'",
",",
"APIController",
".",
"clearState",
")",
";",
"App",
".",
"post",
"(",
"'/api/card/analytics'",
",",
"APIController",
".",
"recordAnalyticEvents",
")",
";",
"App",
".",
"post",
"(",
"'/proxy/:pack/:card'",
",",
"ProxyController",
".",
"post",
")",
";",
"App",
".",
"post",
"(",
"'/webhook/:pack/:card'",
",",
"WebHookController",
".",
"process",
")",
";",
"App",
".",
"post",
"(",
"'/:pack/:card'",
",",
"JsonParser",
",",
"CardController",
".",
"post",
")",
";",
"App",
".",
"get",
"(",
"'/:pack/:card'",
",",
"CardController",
".",
"get",
")",
";",
"App",
".",
"get",
"(",
"'/:pack'",
",",
"PackController",
")",
";",
"App",
".",
"get",
"(",
"'/'",
",",
"DefaultController",
")",
";",
"var",
"exit",
"=",
"function",
"(",
")",
"{",
"HashDo",
".",
"db",
".",
"disconnect",
"(",
"function",
"(",
")",
"{",
"process",
".",
"exit",
"(",
"0",
")",
";",
"}",
")",
";",
"}",
";",
"process",
".",
"on",
"(",
"'SIGINT'",
",",
"exit",
")",
";",
"process",
".",
"on",
"(",
"'SIGTERM'",
",",
"exit",
")",
";",
"process",
".",
"on",
"(",
"'uncaughtException'",
",",
"function",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"'FATAL: '",
",",
"err",
".",
"message",
")",
";",
"console",
".",
"error",
"(",
"err",
".",
"stack",
")",
";",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
")",
";",
"HashDo",
".",
"db",
".",
"connect",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"'FATAL: Could not connect to database.'",
",",
"err",
")",
";",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"'WEB: Starting web server on port %d...'",
",",
"process",
".",
"env",
".",
"PORT",
")",
";",
"App",
".",
"listen",
"(",
"process",
".",
"env",
".",
"PORT",
",",
"function",
"(",
")",
"{",
"console",
".",
"log",
"(",
")",
";",
"console",
".",
"log",
"(",
"'Let\\'s #Do'",
")",
";",
"\\'",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Sets up internal routes and starts the web server,
Ensure you call the init function before starting the web server.
@method start
@async
@param {Function} [callback] Optional callback to be nitified when the server has started and ready for requests. | [
"Sets",
"up",
"internal",
"routes",
"and",
"starts",
"the",
"web",
"server",
"Ensure",
"you",
"call",
"the",
"init",
"function",
"before",
"starting",
"the",
"web",
"server",
"."
]
| ec69928cf4515a496f85d9af5926bfe8a4344465 | https://github.com/UXFoundry/hashdo-web/blob/ec69928cf4515a496f85d9af5926bfe8a4344465/index.js#L92-L165 | train |
|
Tictrac/grunt-i18n-linter | tasks/lib/i18n_linter.js | run | function run(files, options) {
// If translations or templates are not supplied then error
if (options.translations.length === 0) {
grunt.fail.fatal('Please supply translations');
}
// If a missing translation regex has been supplied report the missing count
if (options.missingTranslationRegex !== null) {
linter.setMissingTranslationRegex(options.missingTranslationRegex);
}
// Add the translation keys to the linter
options.translations.forEach(function(file) {
var files = grunt.file.expand(file);
files.forEach(function(file) {
if (!grunt.file.exists(file)) {
grunt.fail.fatal('File ' + file + ' does not exist');
}
linter.addKeys(grunt.file.readJSON(file));
});
});
// Iterate through files and run them through the linter
files.forEach(function(file) {
if (!grunt.file.exists(file)) {
grunt.fail.fatal('File ' + file + ' does not exist');
}
linter.check(grunt.file.read(file));
});
} | javascript | function run(files, options) {
// If translations or templates are not supplied then error
if (options.translations.length === 0) {
grunt.fail.fatal('Please supply translations');
}
// If a missing translation regex has been supplied report the missing count
if (options.missingTranslationRegex !== null) {
linter.setMissingTranslationRegex(options.missingTranslationRegex);
}
// Add the translation keys to the linter
options.translations.forEach(function(file) {
var files = grunt.file.expand(file);
files.forEach(function(file) {
if (!grunt.file.exists(file)) {
grunt.fail.fatal('File ' + file + ' does not exist');
}
linter.addKeys(grunt.file.readJSON(file));
});
});
// Iterate through files and run them through the linter
files.forEach(function(file) {
if (!grunt.file.exists(file)) {
grunt.fail.fatal('File ' + file + ' does not exist');
}
linter.check(grunt.file.read(file));
});
} | [
"function",
"run",
"(",
"files",
",",
"options",
")",
"{",
"if",
"(",
"options",
".",
"translations",
".",
"length",
"===",
"0",
")",
"{",
"grunt",
".",
"fail",
".",
"fatal",
"(",
"'Please supply translations'",
")",
";",
"}",
"if",
"(",
"options",
".",
"missingTranslationRegex",
"!==",
"null",
")",
"{",
"linter",
".",
"setMissingTranslationRegex",
"(",
"options",
".",
"missingTranslationRegex",
")",
";",
"}",
"options",
".",
"translations",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"files",
"=",
"grunt",
".",
"file",
".",
"expand",
"(",
"file",
")",
";",
"files",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"if",
"(",
"!",
"grunt",
".",
"file",
".",
"exists",
"(",
"file",
")",
")",
"{",
"grunt",
".",
"fail",
".",
"fatal",
"(",
"'File '",
"+",
"file",
"+",
"' does not exist'",
")",
";",
"}",
"linter",
".",
"addKeys",
"(",
"grunt",
".",
"file",
".",
"readJSON",
"(",
"file",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"files",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"if",
"(",
"!",
"grunt",
".",
"file",
".",
"exists",
"(",
"file",
")",
")",
"{",
"grunt",
".",
"fail",
".",
"fatal",
"(",
"'File '",
"+",
"file",
"+",
"' does not exist'",
")",
";",
"}",
"linter",
".",
"check",
"(",
"grunt",
".",
"file",
".",
"read",
"(",
"file",
")",
")",
";",
"}",
")",
";",
"}"
]
| Run the linter against the given files and options
@param {Array} files List of files to check
@param {Object} options List of options | [
"Run",
"the",
"linter",
"against",
"the",
"given",
"files",
"and",
"options"
]
| 7a64e19ece1cf974beb29f85ec15dec17a39c45f | https://github.com/Tictrac/grunt-i18n-linter/blob/7a64e19ece1cf974beb29f85ec15dec17a39c45f/tasks/lib/i18n_linter.js#L31-L61 | train |
ugate/releasebot | lib/errors.js | logError | function logError(e) {
e = e instanceof Error ? e : e ? new Error(e) : null;
if (e) {
if (options && util.isRegExp(options.hideTokenRegExp)) {
e.message = e.message.replace(options.hideTokenRegExp, function(match, prefix, token, suffix) {
return prefix + '[SECURE]' + suffix;
});
}
errors.unshift(e);
rbot.log.error(e.stack || e.message);
}
} | javascript | function logError(e) {
e = e instanceof Error ? e : e ? new Error(e) : null;
if (e) {
if (options && util.isRegExp(options.hideTokenRegExp)) {
e.message = e.message.replace(options.hideTokenRegExp, function(match, prefix, token, suffix) {
return prefix + '[SECURE]' + suffix;
});
}
errors.unshift(e);
rbot.log.error(e.stack || e.message);
}
} | [
"function",
"logError",
"(",
"e",
")",
"{",
"e",
"=",
"e",
"instanceof",
"Error",
"?",
"e",
":",
"e",
"?",
"new",
"Error",
"(",
"e",
")",
":",
"null",
";",
"if",
"(",
"e",
")",
"{",
"if",
"(",
"options",
"&&",
"util",
".",
"isRegExp",
"(",
"options",
".",
"hideTokenRegExp",
")",
")",
"{",
"e",
".",
"message",
"=",
"e",
".",
"message",
".",
"replace",
"(",
"options",
".",
"hideTokenRegExp",
",",
"function",
"(",
"match",
",",
"prefix",
",",
"token",
",",
"suffix",
")",
"{",
"return",
"prefix",
"+",
"'[SECURE]'",
"+",
"suffix",
";",
"}",
")",
";",
"}",
"errors",
".",
"unshift",
"(",
"e",
")",
";",
"rbot",
".",
"log",
".",
"error",
"(",
"e",
".",
"stack",
"||",
"e",
".",
"message",
")",
";",
"}",
"}"
]
| Logs an error
@param e
the {Error} object or string | [
"Logs",
"an",
"error"
]
| 1a2ff42796e77f47f9590992c014fee461aad80b | https://github.com/ugate/releasebot/blob/1a2ff42796e77f47f9590992c014fee461aad80b/lib/errors.js#L44-L55 | train |
ImHype/koa-sdf | lib/loadFile.js | loadFile | function loadFile(name, dir, options) {
var pathname = path.normalize(path.join(options.prefix, name));
var obj = {};
var filename = (obj.path = path.join(dir, name));
var stats = fs.statSync(filename);
var buffer = fs.readFileSync(filename);
obj.cacheControl = options.cacheControl;
obj.maxAge = obj.maxAge ? obj.maxAge : options.maxAge || 0;
obj.type = obj.mime = mime.lookup(pathname) || "application/octet-stream";
obj.mtime = stats.mtime;
obj.length = stats.size;
obj.md5 = crypto.createHash("md5").update(buffer).digest("base64");
debug("file: " + JSON.stringify(obj, null, 2));
if (options.buffer) obj.buffer = buffer;
buffer = null;
return obj;
} | javascript | function loadFile(name, dir, options) {
var pathname = path.normalize(path.join(options.prefix, name));
var obj = {};
var filename = (obj.path = path.join(dir, name));
var stats = fs.statSync(filename);
var buffer = fs.readFileSync(filename);
obj.cacheControl = options.cacheControl;
obj.maxAge = obj.maxAge ? obj.maxAge : options.maxAge || 0;
obj.type = obj.mime = mime.lookup(pathname) || "application/octet-stream";
obj.mtime = stats.mtime;
obj.length = stats.size;
obj.md5 = crypto.createHash("md5").update(buffer).digest("base64");
debug("file: " + JSON.stringify(obj, null, 2));
if (options.buffer) obj.buffer = buffer;
buffer = null;
return obj;
} | [
"function",
"loadFile",
"(",
"name",
",",
"dir",
",",
"options",
")",
"{",
"var",
"pathname",
"=",
"path",
".",
"normalize",
"(",
"path",
".",
"join",
"(",
"options",
".",
"prefix",
",",
"name",
")",
")",
";",
"var",
"obj",
"=",
"{",
"}",
";",
"var",
"filename",
"=",
"(",
"obj",
".",
"path",
"=",
"path",
".",
"join",
"(",
"dir",
",",
"name",
")",
")",
";",
"var",
"stats",
"=",
"fs",
".",
"statSync",
"(",
"filename",
")",
";",
"var",
"buffer",
"=",
"fs",
".",
"readFileSync",
"(",
"filename",
")",
";",
"obj",
".",
"cacheControl",
"=",
"options",
".",
"cacheControl",
";",
"obj",
".",
"maxAge",
"=",
"obj",
".",
"maxAge",
"?",
"obj",
".",
"maxAge",
":",
"options",
".",
"maxAge",
"||",
"0",
";",
"obj",
".",
"type",
"=",
"obj",
".",
"mime",
"=",
"mime",
".",
"lookup",
"(",
"pathname",
")",
"||",
"\"application/octet-stream\"",
";",
"obj",
".",
"mtime",
"=",
"stats",
".",
"mtime",
";",
"obj",
".",
"length",
"=",
"stats",
".",
"size",
";",
"obj",
".",
"md5",
"=",
"crypto",
".",
"createHash",
"(",
"\"md5\"",
")",
".",
"update",
"(",
"buffer",
")",
".",
"digest",
"(",
"\"base64\"",
")",
";",
"debug",
"(",
"\"file: \"",
"+",
"JSON",
".",
"stringify",
"(",
"obj",
",",
"null",
",",
"2",
")",
")",
";",
"if",
"(",
"options",
".",
"buffer",
")",
"obj",
".",
"buffer",
"=",
"buffer",
";",
"buffer",
"=",
"null",
";",
"return",
"obj",
";",
"}"
]
| load file and add file content to cache
@param {String} name
@param {String} dir
@param {Object} options
@return {Object}
@api private | [
"load",
"file",
"and",
"add",
"file",
"content",
"to",
"cache"
]
| 7a88a6c4dfa99f34f6a8e4f5f9cf07a84015e53b | https://github.com/ImHype/koa-sdf/blob/7a88a6c4dfa99f34f6a8e4f5f9cf07a84015e53b/lib/loadFile.js#L16-L35 | train |
duzun/onemit | dist/lightonemit.1.0.0.js | on | function on(name, hdl) {
var list = eventHandlers[name] || (eventHandlers[name] = []);
list.push(hdl);
return this;
} | javascript | function on(name, hdl) {
var list = eventHandlers[name] || (eventHandlers[name] = []);
list.push(hdl);
return this;
} | [
"function",
"on",
"(",
"name",
",",
"hdl",
")",
"{",
"var",
"list",
"=",
"eventHandlers",
"[",
"name",
"]",
"||",
"(",
"eventHandlers",
"[",
"name",
"]",
"=",
"[",
"]",
")",
";",
"list",
".",
"push",
"(",
"hdl",
")",
";",
"return",
"this",
";",
"}"
]
| Bind an event listener to the model.
@param (string) name - event name
@param (function) hdl - event handler | [
"Bind",
"an",
"event",
"listener",
"to",
"the",
"model",
"."
]
| 12360553cf36379e9fc91d36c40d519a822d4987 | https://github.com/duzun/onemit/blob/12360553cf36379e9fc91d36c40d519a822d4987/dist/lightonemit.1.0.0.js#L18-L22 | train |
ayecue/node-klass | src/common/printf.js | function(string){
var pattern = /(^|\W)(\w)(\w*)/g,
result = [],
match;
while (pattern.exec(string)) {
result.push(RegExp.$1 + RegExp.$2.toUpperCase() + RegExp.$3);
}
return result.join('');
} | javascript | function(string){
var pattern = /(^|\W)(\w)(\w*)/g,
result = [],
match;
while (pattern.exec(string)) {
result.push(RegExp.$1 + RegExp.$2.toUpperCase() + RegExp.$3);
}
return result.join('');
} | [
"function",
"(",
"string",
")",
"{",
"var",
"pattern",
"=",
"/",
"(^|\\W)(\\w)(\\w*)",
"/",
"g",
",",
"result",
"=",
"[",
"]",
",",
"match",
";",
"while",
"(",
"pattern",
".",
"exec",
"(",
"string",
")",
")",
"{",
"result",
".",
"push",
"(",
"RegExp",
".",
"$1",
"+",
"RegExp",
".",
"$2",
".",
"toUpperCase",
"(",
")",
"+",
"RegExp",
".",
"$3",
")",
";",
"}",
"return",
"result",
".",
"join",
"(",
"''",
")",
";",
"}"
]
| Upper first letter | [
"Upper",
"first",
"letter"
]
| d0583db943bfc6186e45d205735bebd88828e117 | https://github.com/ayecue/node-klass/blob/d0583db943bfc6186e45d205735bebd88828e117/src/common/printf.js#L27-L37 | train |
|
zestjs/zest-server | zest-server.js | function(module) {
for (var i = 0; i < module.include.length; i++) {
var curInclude = module.include[i];
if (curInclude.substr(0, 2) == '^!') {
module.include[i] = curInclude.substr(2);
attachBuildIds.push(curInclude.substr(2));
}
}
} | javascript | function(module) {
for (var i = 0; i < module.include.length; i++) {
var curInclude = module.include[i];
if (curInclude.substr(0, 2) == '^!') {
module.include[i] = curInclude.substr(2);
attachBuildIds.push(curInclude.substr(2));
}
}
} | [
"function",
"(",
"module",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"module",
".",
"include",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"curInclude",
"=",
"module",
".",
"include",
"[",
"i",
"]",
";",
"if",
"(",
"curInclude",
".",
"substr",
"(",
"0",
",",
"2",
")",
"==",
"'^!'",
")",
"{",
"module",
".",
"include",
"[",
"i",
"]",
"=",
"curInclude",
".",
"substr",
"(",
"2",
")",
";",
"attachBuildIds",
".",
"push",
"(",
"curInclude",
".",
"substr",
"(",
"2",
")",
")",
";",
"}",
"}",
"}"
]
| remove the '^!' builds from the current module | [
"remove",
"the",
"^!",
"builds",
"from",
"the",
"current",
"module"
]
| 83209d0209da3bce0e9c24034fb4b5016e7bdcc8 | https://github.com/zestjs/zest-server/blob/83209d0209da3bce0e9c24034fb4b5016e7bdcc8/zest-server.js#L234-L242 | train |
|
itsa/itsa-event | event-base.js | function(customEvent, callback, context, filter, prepend) {
return this._addMultiSubs(false, customEvent, callback, context, filter, prepend);
} | javascript | function(customEvent, callback, context, filter, prepend) {
return this._addMultiSubs(false, customEvent, callback, context, filter, prepend);
} | [
"function",
"(",
"customEvent",
",",
"callback",
",",
"context",
",",
"filter",
",",
"prepend",
")",
"{",
"return",
"this",
".",
"_addMultiSubs",
"(",
"false",
",",
"customEvent",
",",
"callback",
",",
"context",
",",
"filter",
",",
"prepend",
")",
";",
"}"
]
| Subscribes to a customEvent. The callback will be executed `after` the defaultFn.
@static
@method after
@param customEvent {String|Array} the custom-event (or Array of events) to subscribe to. CustomEvents should
have the syntax: `emitterName:eventName`. Wildcard `*` may be used for both `emitterName` as well as `eventName`.
If `emitterName` is not defined, `UI` is assumed.
@param callback {Function} subscriber:will be invoked when the event occurs. An `eventobject` will be passed
as its only argument.
@param [context] {Object} the instance that subscribes to the event.
any object can passed through, even those are not extended with event-listener methods.
Note: Objects who are extended with listener-methods should use instance.after() instead.
@param [filter] {String|Function} to filter the event.
Use a String if you want to filter DOM-events by a `selector`
Use a function if you want to filter by any other means. If the function returns a trully value, the
subscriber gets invoked. The function gets the `eventobject` as its only argument and the context is
the subscriber.
@param [prepend=false] {Boolean} whether the subscriber should be the first in the list of after-subscribers.
@return {Object} handler with a `detach()`-method which can be used to detach the subscriber
@since 0.0.1 | [
"Subscribes",
"to",
"a",
"customEvent",
".",
"The",
"callback",
"will",
"be",
"executed",
"after",
"the",
"defaultFn",
"."
]
| fd7b5ede1a5e8b6a237f60bd8373f570d014f5fa | https://github.com/itsa/itsa-event/blob/fd7b5ede1a5e8b6a237f60bd8373f570d014f5fa/event-base.js#L83-L85 | train |
|
itsa/itsa-event | event-base.js | function(customEvent, callback, context, filter, prepend) {
return this._addMultiSubs(true, customEvent, callback, context, filter, prepend);
} | javascript | function(customEvent, callback, context, filter, prepend) {
return this._addMultiSubs(true, customEvent, callback, context, filter, prepend);
} | [
"function",
"(",
"customEvent",
",",
"callback",
",",
"context",
",",
"filter",
",",
"prepend",
")",
"{",
"return",
"this",
".",
"_addMultiSubs",
"(",
"true",
",",
"customEvent",
",",
"callback",
",",
"context",
",",
"filter",
",",
"prepend",
")",
";",
"}"
]
| Subscribes to a customEvent. The callback will be executed `before` the defaultFn.
@static
@method before
@param customEvent {String|Array} the custom-event (or Array of events) to subscribe to. CustomEvents should
have the syntax: `emitterName:eventName`. Wildcard `*` may be used for both `emitterName` as well as `eventName`.
If `emitterName` is not defined, `UI` is assumed.
@param callback {Function} subscriber:will be invoked when the event occurs. An `eventobject` will be passed
as its only argument.
@param [context] {Object} the instance that subscribes to the event.
any object can passed through, even those are not extended with event-listener methods.
Note: Objects who are extended with listener-methods should use instance.before() instead.
@param [filter] {String|Function} to filter the event.
Use a String if you want to filter DOM-events by a `selector`
Use a function if you want to filter by any other means. If the function returns a trully value, the
subscriber gets invoked. The function gets the `eventobject` as its only argument and the context is
the subscriber.
@param [prepend=false] {Boolean} whether the subscriber should be the first in the list of before-subscribers.
@return {Object} handler with a `detach()`-method which can be used to detach the subscriber
@since 0.0.1 | [
"Subscribes",
"to",
"a",
"customEvent",
".",
"The",
"callback",
"will",
"be",
"executed",
"before",
"the",
"defaultFn",
"."
]
| fd7b5ede1a5e8b6a237f60bd8373f570d014f5fa | https://github.com/itsa/itsa-event/blob/fd7b5ede1a5e8b6a237f60bd8373f570d014f5fa/event-base.js#L109-L111 | train |
|
itsa/itsa-event | event-base.js | function (emitterName) {
var instance = this,
pattern;
if (emitterName) {
pattern = new RegExp('^'+emitterName+':');
instance._ce.itsa_each(
function(value, key) {
key.match(pattern) && (delete instance._ce[key]);
}
);
}
else {
instance._ce.itsa_each(
function(value, key) {
delete instance._ce[key];
}
);
}
} | javascript | function (emitterName) {
var instance = this,
pattern;
if (emitterName) {
pattern = new RegExp('^'+emitterName+':');
instance._ce.itsa_each(
function(value, key) {
key.match(pattern) && (delete instance._ce[key]);
}
);
}
else {
instance._ce.itsa_each(
function(value, key) {
delete instance._ce[key];
}
);
}
} | [
"function",
"(",
"emitterName",
")",
"{",
"var",
"instance",
"=",
"this",
",",
"pattern",
";",
"if",
"(",
"emitterName",
")",
"{",
"pattern",
"=",
"new",
"RegExp",
"(",
"'^'",
"+",
"emitterName",
"+",
"':'",
")",
";",
"instance",
".",
"_ce",
".",
"itsa_each",
"(",
"function",
"(",
"value",
",",
"key",
")",
"{",
"key",
".",
"match",
"(",
"pattern",
")",
"&&",
"(",
"delete",
"instance",
".",
"_ce",
"[",
"key",
"]",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"instance",
".",
"_ce",
".",
"itsa_each",
"(",
"function",
"(",
"value",
",",
"key",
")",
"{",
"delete",
"instance",
".",
"_ce",
"[",
"key",
"]",
";",
"}",
")",
";",
"}",
"}"
]
| Removes all event-definitions of an emitter, specified by its `emitterName`.
When `emitterName` is not set, ALL event-definitions will be removed.
@static
@method undefAllEvents
@param [emitterName] {String} name of the customEvent conform the syntax: `emitterName:eventName`
@since 0.0.1 | [
"Removes",
"all",
"event",
"-",
"definitions",
"of",
"an",
"emitter",
"specified",
"by",
"its",
"emitterName",
".",
"When",
"emitterName",
"is",
"not",
"set",
"ALL",
"event",
"-",
"definitions",
"will",
"be",
"removed",
"."
]
| fd7b5ede1a5e8b6a237f60bd8373f570d014f5fa | https://github.com/itsa/itsa-event/blob/fd7b5ede1a5e8b6a237f60bd8373f570d014f5fa/event-base.js#L483-L501 | train |
|
itsa/itsa-event | event-base.js | function (e, checkFilter, before, preProcessor, subscribers) { // subscribers, plural
var subs, passesThis, passesFilter;
if (subscribers && !e.status.halted && !e.silent) {
subs = before ? subscribers.b : subscribers.a;
subs && subs.some(function(subscriber) {
if (preProcessor && preProcessor(subscriber, e)) {
return true;
}
// check: does it need to be itself because of subscribing through 'this'
passesThis = (!subscriber.s || (subscriber.o===e.target));
// check: does it pass the filter
passesFilter = (!checkFilter || !subscriber.f || subscriber.f.call(subscriber.o, e));
if (passesThis && passesFilter) {
// finally: invoke subscriber
subscriber.cb.call(subscriber.o, e);
}
if (e.status.unSilencable && e.silent) {
console.warn(NAME, ' event '+e.emitter+':'+e.type+' cannot made silent: this customEvent is defined as unSilencable');
e.silent = false;
}
return e.silent || (before && e.status.halted); // remember to check whether it was halted for any reason
});
}
} | javascript | function (e, checkFilter, before, preProcessor, subscribers) { // subscribers, plural
var subs, passesThis, passesFilter;
if (subscribers && !e.status.halted && !e.silent) {
subs = before ? subscribers.b : subscribers.a;
subs && subs.some(function(subscriber) {
if (preProcessor && preProcessor(subscriber, e)) {
return true;
}
// check: does it need to be itself because of subscribing through 'this'
passesThis = (!subscriber.s || (subscriber.o===e.target));
// check: does it pass the filter
passesFilter = (!checkFilter || !subscriber.f || subscriber.f.call(subscriber.o, e));
if (passesThis && passesFilter) {
// finally: invoke subscriber
subscriber.cb.call(subscriber.o, e);
}
if (e.status.unSilencable && e.silent) {
console.warn(NAME, ' event '+e.emitter+':'+e.type+' cannot made silent: this customEvent is defined as unSilencable');
e.silent = false;
}
return e.silent || (before && e.status.halted); // remember to check whether it was halted for any reason
});
}
} | [
"function",
"(",
"e",
",",
"checkFilter",
",",
"before",
",",
"preProcessor",
",",
"subscribers",
")",
"{",
"var",
"subs",
",",
"passesThis",
",",
"passesFilter",
";",
"if",
"(",
"subscribers",
"&&",
"!",
"e",
".",
"status",
".",
"halted",
"&&",
"!",
"e",
".",
"silent",
")",
"{",
"subs",
"=",
"before",
"?",
"subscribers",
".",
"b",
":",
"subscribers",
".",
"a",
";",
"subs",
"&&",
"subs",
".",
"some",
"(",
"function",
"(",
"subscriber",
")",
"{",
"if",
"(",
"preProcessor",
"&&",
"preProcessor",
"(",
"subscriber",
",",
"e",
")",
")",
"{",
"return",
"true",
";",
"}",
"passesThis",
"=",
"(",
"!",
"subscriber",
".",
"s",
"||",
"(",
"subscriber",
".",
"o",
"===",
"e",
".",
"target",
")",
")",
";",
"passesFilter",
"=",
"(",
"!",
"checkFilter",
"||",
"!",
"subscriber",
".",
"f",
"||",
"subscriber",
".",
"f",
".",
"call",
"(",
"subscriber",
".",
"o",
",",
"e",
")",
")",
";",
"if",
"(",
"passesThis",
"&&",
"passesFilter",
")",
"{",
"subscriber",
".",
"cb",
".",
"call",
"(",
"subscriber",
".",
"o",
",",
"e",
")",
";",
"}",
"if",
"(",
"e",
".",
"status",
".",
"unSilencable",
"&&",
"e",
".",
"silent",
")",
"{",
"console",
".",
"warn",
"(",
"NAME",
",",
"' event '",
"+",
"e",
".",
"emitter",
"+",
"':'",
"+",
"e",
".",
"type",
"+",
"' cannot made silent: this customEvent is defined as unSilencable'",
")",
";",
"e",
".",
"silent",
"=",
"false",
";",
"}",
"return",
"e",
".",
"silent",
"||",
"(",
"before",
"&&",
"e",
".",
"status",
".",
"halted",
")",
";",
"}",
")",
";",
"}",
"}"
]
| Does the actual invocation of a subscriber.
@method _invokeSubs
@param e {Object} event-object
@param [checkFilter] {Boolean}
@param [before] {Boolean} whether it concerns before subscribers
@param [checkFilter] {Boolean}
@param subscribers {Array} contains subscribers (objects) with these members:
<ul>
<li>subscriber.o {Object} context of the callback</li>
<li>subscriber.cb {Function} callback to be invoked</li>
<li>subscriber.f {Function} filter to be applied</li>
<li>subscriber.t {DOM-node} target for the specific selector, which will be set as e.target
only when event-dom is active and there are filter-selectors</li>
<li>subscriber.n {DOM-node} highest dom-node that acts as the container for delegation.
only when event-dom is active and there are filter-selectors</li>
<li>subscriber.s {Boolean} true when the subscription was set to itself by using "this:eventName"</li>
</ul>
@private
@since 0.0.1 | [
"Does",
"the",
"actual",
"invocation",
"of",
"a",
"subscriber",
"."
]
| fd7b5ede1a5e8b6a237f60bd8373f570d014f5fa | https://github.com/itsa/itsa-event/blob/fd7b5ede1a5e8b6a237f60bd8373f570d014f5fa/event-base.js#L916-L939 | train |
|
doowb/ask-for-github-auth | index.js | askForGithubAuth | function askForGithubAuth (options, cb) {
if (typeof options === 'function') {
cb = options;
options = {};
}
options = options || {};
options.store = options.store || 'default';
if (typeof options.store === 'string') {
options.store = 'for-github-auth.' + options.store;
}
loadQuestions(options.store);
var creds = {};
ask.once('github-auth.type', options, function (err, type) {
if (err) return cb(err);
creds.type = type;
ask.once(['github-auth', type].join('.'), options, function (err, answer) {
if (err) return cb(err);
if (type === 'oauth') {
creds.token = answer;
} else {
creds.username = answer.username;
creds.password = answer.password;
}
cb(null, creds);
});
});
} | javascript | function askForGithubAuth (options, cb) {
if (typeof options === 'function') {
cb = options;
options = {};
}
options = options || {};
options.store = options.store || 'default';
if (typeof options.store === 'string') {
options.store = 'for-github-auth.' + options.store;
}
loadQuestions(options.store);
var creds = {};
ask.once('github-auth.type', options, function (err, type) {
if (err) return cb(err);
creds.type = type;
ask.once(['github-auth', type].join('.'), options, function (err, answer) {
if (err) return cb(err);
if (type === 'oauth') {
creds.token = answer;
} else {
creds.username = answer.username;
creds.password = answer.password;
}
cb(null, creds);
});
});
} | [
"function",
"askForGithubAuth",
"(",
"options",
",",
"cb",
")",
"{",
"if",
"(",
"typeof",
"options",
"===",
"'function'",
")",
"{",
"cb",
"=",
"options",
";",
"options",
"=",
"{",
"}",
";",
"}",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"options",
".",
"store",
"=",
"options",
".",
"store",
"||",
"'default'",
";",
"if",
"(",
"typeof",
"options",
".",
"store",
"===",
"'string'",
")",
"{",
"options",
".",
"store",
"=",
"'for-github-auth.'",
"+",
"options",
".",
"store",
";",
"}",
"loadQuestions",
"(",
"options",
".",
"store",
")",
";",
"var",
"creds",
"=",
"{",
"}",
";",
"ask",
".",
"once",
"(",
"'github-auth.type'",
",",
"options",
",",
"function",
"(",
"err",
",",
"type",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"creds",
".",
"type",
"=",
"type",
";",
"ask",
".",
"once",
"(",
"[",
"'github-auth'",
",",
"type",
"]",
".",
"join",
"(",
"'.'",
")",
",",
"options",
",",
"function",
"(",
"err",
",",
"answer",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"if",
"(",
"type",
"===",
"'oauth'",
")",
"{",
"creds",
".",
"token",
"=",
"answer",
";",
"}",
"else",
"{",
"creds",
".",
"username",
"=",
"answer",
".",
"username",
";",
"creds",
".",
"password",
"=",
"answer",
".",
"password",
";",
"}",
"cb",
"(",
"null",
",",
"creds",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Prompt a user for their github authentication credentials.
Save the answer so they're only asked once.
```js
ask(function (err, creds) {
console.log(creds);
//=> {type: 'oauth', token: '123456'}
//=> or {type: 'basic', username: 'doowb', password: 'password'}
});
```
@param {Object} `options` Options to pass to [ask-once][]
@param {String} `options.store` a [data-store][] instance or name that can be passed to [ask-once][]
@param {Function} `cb` Callback function returning either an error or authentication credentials
@api public | [
"Prompt",
"a",
"user",
"for",
"their",
"github",
"authentication",
"credentials",
".",
"Save",
"the",
"answer",
"so",
"they",
"re",
"only",
"asked",
"once",
"."
]
| 1dc5763c911f44c1eb23247e698bf1142a42b111 | https://github.com/doowb/ask-for-github-auth/blob/1dc5763c911f44c1eb23247e698bf1142a42b111/index.js#L60-L89 | train |
jkenlooper/stripmq | stripmq.js | StripMQ | function StripMQ(input, options, formatOptions) {
options || (options = {});
formatOptions || (formatOptions = {});
options = {
type: options.type || 'screen',
width: options.width || 1024,
'device-width': options['device-width'] || options.width || 1024,
height: options.height || 768,
'device-height': options['device-height'] || options.height || 768,
resolution: options.resolution || '1dppx',
orientation: options.orientation || 'landscape',
'aspect-ratio': options['aspect-ratio'] || options.width/options.height || 1024/768,
color: options.color || 3
};
var tree = css.parse(input);
tree = stripMediaQueries(tree, options);
return css.stringify(tree, formatOptions);
} | javascript | function StripMQ(input, options, formatOptions) {
options || (options = {});
formatOptions || (formatOptions = {});
options = {
type: options.type || 'screen',
width: options.width || 1024,
'device-width': options['device-width'] || options.width || 1024,
height: options.height || 768,
'device-height': options['device-height'] || options.height || 768,
resolution: options.resolution || '1dppx',
orientation: options.orientation || 'landscape',
'aspect-ratio': options['aspect-ratio'] || options.width/options.height || 1024/768,
color: options.color || 3
};
var tree = css.parse(input);
tree = stripMediaQueries(tree, options);
return css.stringify(tree, formatOptions);
} | [
"function",
"StripMQ",
"(",
"input",
",",
"options",
",",
"formatOptions",
")",
"{",
"options",
"||",
"(",
"options",
"=",
"{",
"}",
")",
";",
"formatOptions",
"||",
"(",
"formatOptions",
"=",
"{",
"}",
")",
";",
"options",
"=",
"{",
"type",
":",
"options",
".",
"type",
"||",
"'screen'",
",",
"width",
":",
"options",
".",
"width",
"||",
"1024",
",",
"'device-width'",
":",
"options",
"[",
"'device-width'",
"]",
"||",
"options",
".",
"width",
"||",
"1024",
",",
"height",
":",
"options",
".",
"height",
"||",
"768",
",",
"'device-height'",
":",
"options",
"[",
"'device-height'",
"]",
"||",
"options",
".",
"height",
"||",
"768",
",",
"resolution",
":",
"options",
".",
"resolution",
"||",
"'1dppx'",
",",
"orientation",
":",
"options",
".",
"orientation",
"||",
"'landscape'",
",",
"'aspect-ratio'",
":",
"options",
"[",
"'aspect-ratio'",
"]",
"||",
"options",
".",
"width",
"/",
"options",
".",
"height",
"||",
"1024",
"/",
"768",
",",
"color",
":",
"options",
".",
"color",
"||",
"3",
"}",
";",
"var",
"tree",
"=",
"css",
".",
"parse",
"(",
"input",
")",
";",
"tree",
"=",
"stripMediaQueries",
"(",
"tree",
",",
"options",
")",
";",
"return",
"css",
".",
"stringify",
"(",
"tree",
",",
"formatOptions",
")",
";",
"}"
]
| strip media queries
@param {string} input
@param {object} options
@param {object} formatOptions
@returns {string} output | [
"strip",
"media",
"queries"
]
| 0fc9cfdc75e23271d8962d1c8c6365a05e91d67e | https://github.com/jkenlooper/stripmq/blob/0fc9cfdc75e23271d8962d1c8c6365a05e91d67e/stripmq.js#L29-L48 | train |
el2iot2/linksoup | lib/linksoup.js | parseSpans | function parseSpans(text) {
var links = parseLinks(text);
/*Represented as
[{
href: "http://yada",
start: startIndex,
end: endIndex
}]*/
var spans = [];
var lastSpan = null;
function isPrefixedLinkSpan(span)
{
return span && "href" in span && span.prefix && "proposed" in span.prefix;
}
function isTextSpan(span)
{
return span && !("href" in span);
}
function addTextSpan(text) {
//if the last span was a candidate
if (isPrefixedLinkSpan(lastSpan)) {
//make sure there is a valid suffix
if (regexen.matchMarkdownLinkSuffix.test(text)) {
//is there any valid whitespace remaining?
text = RegExp.$3;
//use the title (if specified)
if (RegExp.$2) {
lastSpan.title = RegExp.$2;
}
//use the proposed link text for the verified link
lastSpan.text = lastSpan.prefix.proposed.linkText;
//if there was valid prefix text, use it
if (lastSpan.prefix.proposed.text) {
lastSpan.prefix.text = lastSpan.prefix.proposed.text;
delete lastSpan.prefix["proposed"]; //clean up proposal
}
else {
spans.splice(spans.length - 2, 1); //remove prefix
lastSpan = lastSpan.prefix;
}
}
else {
delete lastSpan.prefix["proposed"]; //clean up proposal...no match...no modification
}
delete lastSpan["prefix"]; //clean up prefix scratchwork
}
if (text) {
lastSpan = {
text : text
};
spans.push(lastSpan);
}
}
function addLinkSpan(linkSpan) {
var span = {
href : linkSpan.href
};
if (isTextSpan(lastSpan) && regexen.matchMarkdownLinkPrefix.test(lastSpan.text)) {
lastSpan.proposed = { text: RegExp.$1, linkText: RegExp.$2 };
span.prefix = lastSpan;
}
lastSpan = span;
spans.push(lastSpan);
}
//No links found, all text
if (links.length === 0) {
addTextSpan(text);
}
//One or more links found
else {
var firstLink = links[0],
lastLink = links[links.length - 1];
//Was there text before the first link?
if (firstLink.start > 0) {
addTextSpan(text.substring(0, firstLink.start));
}
//Handle single link
if (links.length === 1) {
addLinkSpan(firstLink);
} else {
//push the firstLink
addLinkSpan(firstLink);
var prevLink = firstLink;
//loop from the second
for (var i = 1; i < links.length; i++) {
//is there text between?
if (links[i].start - prevLink.end >= 1) {
addTextSpan(text.substring(prevLink.end, links[i].start));
}
//add link
addLinkSpan(prevLink = links[i]);
}
}
//Was there text after the links?
if (lastLink.end < (text.length)) {
addTextSpan(text.substring(lastLink.end));
}
}
return spans;
} | javascript | function parseSpans(text) {
var links = parseLinks(text);
/*Represented as
[{
href: "http://yada",
start: startIndex,
end: endIndex
}]*/
var spans = [];
var lastSpan = null;
function isPrefixedLinkSpan(span)
{
return span && "href" in span && span.prefix && "proposed" in span.prefix;
}
function isTextSpan(span)
{
return span && !("href" in span);
}
function addTextSpan(text) {
//if the last span was a candidate
if (isPrefixedLinkSpan(lastSpan)) {
//make sure there is a valid suffix
if (regexen.matchMarkdownLinkSuffix.test(text)) {
//is there any valid whitespace remaining?
text = RegExp.$3;
//use the title (if specified)
if (RegExp.$2) {
lastSpan.title = RegExp.$2;
}
//use the proposed link text for the verified link
lastSpan.text = lastSpan.prefix.proposed.linkText;
//if there was valid prefix text, use it
if (lastSpan.prefix.proposed.text) {
lastSpan.prefix.text = lastSpan.prefix.proposed.text;
delete lastSpan.prefix["proposed"]; //clean up proposal
}
else {
spans.splice(spans.length - 2, 1); //remove prefix
lastSpan = lastSpan.prefix;
}
}
else {
delete lastSpan.prefix["proposed"]; //clean up proposal...no match...no modification
}
delete lastSpan["prefix"]; //clean up prefix scratchwork
}
if (text) {
lastSpan = {
text : text
};
spans.push(lastSpan);
}
}
function addLinkSpan(linkSpan) {
var span = {
href : linkSpan.href
};
if (isTextSpan(lastSpan) && regexen.matchMarkdownLinkPrefix.test(lastSpan.text)) {
lastSpan.proposed = { text: RegExp.$1, linkText: RegExp.$2 };
span.prefix = lastSpan;
}
lastSpan = span;
spans.push(lastSpan);
}
//No links found, all text
if (links.length === 0) {
addTextSpan(text);
}
//One or more links found
else {
var firstLink = links[0],
lastLink = links[links.length - 1];
//Was there text before the first link?
if (firstLink.start > 0) {
addTextSpan(text.substring(0, firstLink.start));
}
//Handle single link
if (links.length === 1) {
addLinkSpan(firstLink);
} else {
//push the firstLink
addLinkSpan(firstLink);
var prevLink = firstLink;
//loop from the second
for (var i = 1; i < links.length; i++) {
//is there text between?
if (links[i].start - prevLink.end >= 1) {
addTextSpan(text.substring(prevLink.end, links[i].start));
}
//add link
addLinkSpan(prevLink = links[i]);
}
}
//Was there text after the links?
if (lastLink.end < (text.length)) {
addTextSpan(text.substring(lastLink.end));
}
}
return spans;
} | [
"function",
"parseSpans",
"(",
"text",
")",
"{",
"var",
"links",
"=",
"parseLinks",
"(",
"text",
")",
";",
"var",
"spans",
"=",
"[",
"]",
";",
"var",
"lastSpan",
"=",
"null",
";",
"function",
"isPrefixedLinkSpan",
"(",
"span",
")",
"{",
"return",
"span",
"&&",
"\"href\"",
"in",
"span",
"&&",
"span",
".",
"prefix",
"&&",
"\"proposed\"",
"in",
"span",
".",
"prefix",
";",
"}",
"function",
"isTextSpan",
"(",
"span",
")",
"{",
"return",
"span",
"&&",
"!",
"(",
"\"href\"",
"in",
"span",
")",
";",
"}",
"function",
"addTextSpan",
"(",
"text",
")",
"{",
"if",
"(",
"isPrefixedLinkSpan",
"(",
"lastSpan",
")",
")",
"{",
"if",
"(",
"regexen",
".",
"matchMarkdownLinkSuffix",
".",
"test",
"(",
"text",
")",
")",
"{",
"text",
"=",
"RegExp",
".",
"$3",
";",
"if",
"(",
"RegExp",
".",
"$2",
")",
"{",
"lastSpan",
".",
"title",
"=",
"RegExp",
".",
"$2",
";",
"}",
"lastSpan",
".",
"text",
"=",
"lastSpan",
".",
"prefix",
".",
"proposed",
".",
"linkText",
";",
"if",
"(",
"lastSpan",
".",
"prefix",
".",
"proposed",
".",
"text",
")",
"{",
"lastSpan",
".",
"prefix",
".",
"text",
"=",
"lastSpan",
".",
"prefix",
".",
"proposed",
".",
"text",
";",
"delete",
"lastSpan",
".",
"prefix",
"[",
"\"proposed\"",
"]",
";",
"}",
"else",
"{",
"spans",
".",
"splice",
"(",
"spans",
".",
"length",
"-",
"2",
",",
"1",
")",
";",
"lastSpan",
"=",
"lastSpan",
".",
"prefix",
";",
"}",
"}",
"else",
"{",
"delete",
"lastSpan",
".",
"prefix",
"[",
"\"proposed\"",
"]",
";",
"}",
"delete",
"lastSpan",
"[",
"\"prefix\"",
"]",
";",
"}",
"if",
"(",
"text",
")",
"{",
"lastSpan",
"=",
"{",
"text",
":",
"text",
"}",
";",
"spans",
".",
"push",
"(",
"lastSpan",
")",
";",
"}",
"}",
"function",
"addLinkSpan",
"(",
"linkSpan",
")",
"{",
"var",
"span",
"=",
"{",
"href",
":",
"linkSpan",
".",
"href",
"}",
";",
"if",
"(",
"isTextSpan",
"(",
"lastSpan",
")",
"&&",
"regexen",
".",
"matchMarkdownLinkPrefix",
".",
"test",
"(",
"lastSpan",
".",
"text",
")",
")",
"{",
"lastSpan",
".",
"proposed",
"=",
"{",
"text",
":",
"RegExp",
".",
"$1",
",",
"linkText",
":",
"RegExp",
".",
"$2",
"}",
";",
"span",
".",
"prefix",
"=",
"lastSpan",
";",
"}",
"lastSpan",
"=",
"span",
";",
"spans",
".",
"push",
"(",
"lastSpan",
")",
";",
"}",
"if",
"(",
"links",
".",
"length",
"===",
"0",
")",
"{",
"addTextSpan",
"(",
"text",
")",
";",
"}",
"else",
"{",
"var",
"firstLink",
"=",
"links",
"[",
"0",
"]",
",",
"lastLink",
"=",
"links",
"[",
"links",
".",
"length",
"-",
"1",
"]",
";",
"if",
"(",
"firstLink",
".",
"start",
">",
"0",
")",
"{",
"addTextSpan",
"(",
"text",
".",
"substring",
"(",
"0",
",",
"firstLink",
".",
"start",
")",
")",
";",
"}",
"if",
"(",
"links",
".",
"length",
"===",
"1",
")",
"{",
"addLinkSpan",
"(",
"firstLink",
")",
";",
"}",
"else",
"{",
"addLinkSpan",
"(",
"firstLink",
")",
";",
"var",
"prevLink",
"=",
"firstLink",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"links",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"links",
"[",
"i",
"]",
".",
"start",
"-",
"prevLink",
".",
"end",
">=",
"1",
")",
"{",
"addTextSpan",
"(",
"text",
".",
"substring",
"(",
"prevLink",
".",
"end",
",",
"links",
"[",
"i",
"]",
".",
"start",
")",
")",
";",
"}",
"addLinkSpan",
"(",
"prevLink",
"=",
"links",
"[",
"i",
"]",
")",
";",
"}",
"}",
"if",
"(",
"lastLink",
".",
"end",
"<",
"(",
"text",
".",
"length",
")",
")",
"{",
"addTextSpan",
"(",
"text",
".",
"substring",
"(",
"lastLink",
".",
"end",
")",
")",
";",
"}",
"}",
"return",
"spans",
";",
"}"
]
| Parses the text into an array of spans | [
"Parses",
"the",
"text",
"into",
"an",
"array",
"of",
"spans"
]
| 316ca49d6d6fd91c2ec9dc27f3585d718a7f5f60 | https://github.com/el2iot2/linksoup/blob/316ca49d6d6fd91c2ec9dc27f3585d718a7f5f60/lib/linksoup.js#L15-L124 | train |
el2iot2/linksoup | lib/linksoup.js | makeFuncAsciiDomainReplace | function makeFuncAsciiDomainReplace(ctx) {
return function (asciiDomain) {
var asciiStartPosition = ctx.domain.indexOf(asciiDomain, ctx.asciiEndPosition);
ctx.asciiEndPosition = asciiStartPosition + asciiDomain.length;
ctx.lastLink = {
href : asciiDomain,
start: ctx.cursor.start + asciiStartPosition,
end: ctx.cursor.start + ctx.asciiEndPosition
};
ctx.lastLinkInvalidMatch = asciiDomain.match(regexen.invalidShortDomain);
if (!ctx.lastLinkInvalidMatch) {
ctx.links.push(ctx.lastLink);
}
};
} | javascript | function makeFuncAsciiDomainReplace(ctx) {
return function (asciiDomain) {
var asciiStartPosition = ctx.domain.indexOf(asciiDomain, ctx.asciiEndPosition);
ctx.asciiEndPosition = asciiStartPosition + asciiDomain.length;
ctx.lastLink = {
href : asciiDomain,
start: ctx.cursor.start + asciiStartPosition,
end: ctx.cursor.start + ctx.asciiEndPosition
};
ctx.lastLinkInvalidMatch = asciiDomain.match(regexen.invalidShortDomain);
if (!ctx.lastLinkInvalidMatch) {
ctx.links.push(ctx.lastLink);
}
};
} | [
"function",
"makeFuncAsciiDomainReplace",
"(",
"ctx",
")",
"{",
"return",
"function",
"(",
"asciiDomain",
")",
"{",
"var",
"asciiStartPosition",
"=",
"ctx",
".",
"domain",
".",
"indexOf",
"(",
"asciiDomain",
",",
"ctx",
".",
"asciiEndPosition",
")",
";",
"ctx",
".",
"asciiEndPosition",
"=",
"asciiStartPosition",
"+",
"asciiDomain",
".",
"length",
";",
"ctx",
".",
"lastLink",
"=",
"{",
"href",
":",
"asciiDomain",
",",
"start",
":",
"ctx",
".",
"cursor",
".",
"start",
"+",
"asciiStartPosition",
",",
"end",
":",
"ctx",
".",
"cursor",
".",
"start",
"+",
"ctx",
".",
"asciiEndPosition",
"}",
";",
"ctx",
".",
"lastLinkInvalidMatch",
"=",
"asciiDomain",
".",
"match",
"(",
"regexen",
".",
"invalidShortDomain",
")",
";",
"if",
"(",
"!",
"ctx",
".",
"lastLinkInvalidMatch",
")",
"{",
"ctx",
".",
"links",
".",
"push",
"(",
"ctx",
".",
"lastLink",
")",
";",
"}",
"}",
";",
"}"
]
| return a closure to handle a custom ascii domain replace | [
"return",
"a",
"closure",
"to",
"handle",
"a",
"custom",
"ascii",
"domain",
"replace"
]
| 316ca49d6d6fd91c2ec9dc27f3585d718a7f5f60 | https://github.com/el2iot2/linksoup/blob/316ca49d6d6fd91c2ec9dc27f3585d718a7f5f60/lib/linksoup.js#L198-L212 | train |
HAKASHUN/gulp-git-staged | index.js | function(stdout, next) {
var lines = stdout.split("\n");
var filenames = _.transform(lines, function(result, line) {
var status = line.slice(0, 2);
if (regExp.test(status)) {
result.push(_.last(line.split(' ')));
}
});
next(null, filenames);
} | javascript | function(stdout, next) {
var lines = stdout.split("\n");
var filenames = _.transform(lines, function(result, line) {
var status = line.slice(0, 2);
if (regExp.test(status)) {
result.push(_.last(line.split(' ')));
}
});
next(null, filenames);
} | [
"function",
"(",
"stdout",
",",
"next",
")",
"{",
"var",
"lines",
"=",
"stdout",
".",
"split",
"(",
"\"\\n\"",
")",
";",
"\\n",
"var",
"filenames",
"=",
"_",
".",
"transform",
"(",
"lines",
",",
"function",
"(",
"result",
",",
"line",
")",
"{",
"var",
"status",
"=",
"line",
".",
"slice",
"(",
"0",
",",
"2",
")",
";",
"if",
"(",
"regExp",
".",
"test",
"(",
"status",
")",
")",
"{",
"result",
".",
"push",
"(",
"_",
".",
"last",
"(",
"line",
".",
"split",
"(",
"' '",
")",
")",
")",
";",
"}",
"}",
")",
";",
"}"
]
| collect filename by status stdout | [
"collect",
"filename",
"by",
"status",
"stdout"
]
| 72862548634c27deae8c1a8a3062fcabb5bd307e | https://github.com/HAKASHUN/gulp-git-staged/blob/72862548634c27deae8c1a8a3062fcabb5bd307e/index.js#L50-L60 | train |
|
HAKASHUN/gulp-git-staged | index.js | function(filenames) {
var isIn = _.some(filenames, function(line) {
return file.path.indexOf(line) !== -1;
});
if (isIn) {
self.push(file);
}
callback();
} | javascript | function(filenames) {
var isIn = _.some(filenames, function(line) {
return file.path.indexOf(line) !== -1;
});
if (isIn) {
self.push(file);
}
callback();
} | [
"function",
"(",
"filenames",
")",
"{",
"var",
"isIn",
"=",
"_",
".",
"some",
"(",
"filenames",
",",
"function",
"(",
"line",
")",
"{",
"return",
"file",
".",
"path",
".",
"indexOf",
"(",
"line",
")",
"!==",
"-",
"1",
";",
"}",
")",
";",
"if",
"(",
"isIn",
")",
"{",
"self",
".",
"push",
"(",
"file",
")",
";",
"}",
"callback",
"(",
")",
";",
"}"
]
| filter file from stream | [
"filter",
"file",
"from",
"stream"
]
| 72862548634c27deae8c1a8a3062fcabb5bd307e | https://github.com/HAKASHUN/gulp-git-staged/blob/72862548634c27deae8c1a8a3062fcabb5bd307e/index.js#L62-L70 | train |
|
tualo/tualo-imap | lib/message.js | Message | function Message(rawText){
this.rawText = rawText;
this._parsed = false;
this._isFetch = false;
this._isNoop = false;
this._list = [];
this._search = [];
this._fetch = {
text: ''
};
this._parse();
} | javascript | function Message(rawText){
this.rawText = rawText;
this._parsed = false;
this._isFetch = false;
this._isNoop = false;
this._list = [];
this._search = [];
this._fetch = {
text: ''
};
this._parse();
} | [
"function",
"Message",
"(",
"rawText",
")",
"{",
"this",
".",
"rawText",
"=",
"rawText",
";",
"this",
".",
"_parsed",
"=",
"false",
";",
"this",
".",
"_isFetch",
"=",
"false",
";",
"this",
".",
"_isNoop",
"=",
"false",
";",
"this",
".",
"_list",
"=",
"[",
"]",
";",
"this",
".",
"_search",
"=",
"[",
"]",
";",
"this",
".",
"_fetch",
"=",
"{",
"text",
":",
"''",
"}",
";",
"this",
".",
"_parse",
"(",
")",
";",
"}"
]
| Create a new instance of Message.
Message parses a messages of th IMAP server.
-rawText of the message recieved from th IMAP server.
@constructor
@this {Message}
@param {string} rawText | [
"Create",
"a",
"new",
"instance",
"of",
"Message",
".",
"Message",
"parses",
"a",
"messages",
"of",
"th",
"IMAP",
"server",
"."
]
| 948d9cb4693eb0d0e82530365ece36c1d8dbecf3 | https://github.com/tualo/tualo-imap/blob/948d9cb4693eb0d0e82530365ece36c1d8dbecf3/lib/message.js#L14-L26 | train |
commenthol/asyncc | src/NoPromise.js | function () {
if (this._lock) return
this._lock = true
let task = this._tasks.shift()
let tstType = this.error ? ['catch', 'end'] : ['then', 'end']
while (task && !~tstType.indexOf(task.type)) {
task = this._tasks.shift()
}
if (task) {
let cb = (err, res) => {
this.error = err
this.result = res || this.result
this._lock = false
this._run()
}
let fn = task.fn
if (task.type === 'end') { // .end
fn(this.error, this.result)
} else {
try {
if (task.type === 'catch') { // .catch
fn(this.error, this.result, cb)
} else { // .then
fn(this.result, cb)
}
} catch (e) {
cb(e)
}
}
} else {
this._lock = false
}
} | javascript | function () {
if (this._lock) return
this._lock = true
let task = this._tasks.shift()
let tstType = this.error ? ['catch', 'end'] : ['then', 'end']
while (task && !~tstType.indexOf(task.type)) {
task = this._tasks.shift()
}
if (task) {
let cb = (err, res) => {
this.error = err
this.result = res || this.result
this._lock = false
this._run()
}
let fn = task.fn
if (task.type === 'end') { // .end
fn(this.error, this.result)
} else {
try {
if (task.type === 'catch') { // .catch
fn(this.error, this.result, cb)
} else { // .then
fn(this.result, cb)
}
} catch (e) {
cb(e)
}
}
} else {
this._lock = false
}
} | [
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"_lock",
")",
"return",
"this",
".",
"_lock",
"=",
"true",
"let",
"task",
"=",
"this",
".",
"_tasks",
".",
"shift",
"(",
")",
"let",
"tstType",
"=",
"this",
".",
"error",
"?",
"[",
"'catch'",
",",
"'end'",
"]",
":",
"[",
"'then'",
",",
"'end'",
"]",
"while",
"(",
"task",
"&&",
"!",
"~",
"tstType",
".",
"indexOf",
"(",
"task",
".",
"type",
")",
")",
"{",
"task",
"=",
"this",
".",
"_tasks",
".",
"shift",
"(",
")",
"}",
"if",
"(",
"task",
")",
"{",
"let",
"cb",
"=",
"(",
"err",
",",
"res",
")",
"=>",
"{",
"this",
".",
"error",
"=",
"err",
"this",
".",
"result",
"=",
"res",
"||",
"this",
".",
"result",
"this",
".",
"_lock",
"=",
"false",
"this",
".",
"_run",
"(",
")",
"}",
"let",
"fn",
"=",
"task",
".",
"fn",
"if",
"(",
"task",
".",
"type",
"===",
"'end'",
")",
"{",
"fn",
"(",
"this",
".",
"error",
",",
"this",
".",
"result",
")",
"}",
"else",
"{",
"try",
"{",
"if",
"(",
"task",
".",
"type",
"===",
"'catch'",
")",
"{",
"fn",
"(",
"this",
".",
"error",
",",
"this",
".",
"result",
",",
"cb",
")",
"}",
"else",
"{",
"fn",
"(",
"this",
".",
"result",
",",
"cb",
")",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"cb",
"(",
"e",
")",
"}",
"}",
"}",
"else",
"{",
"this",
".",
"_lock",
"=",
"false",
"}",
"}"
]
| runs the next function
@private | [
"runs",
"the",
"next",
"function"
]
| a58e16e025d669403ad6c29e60c14f8215769bd4 | https://github.com/commenthol/asyncc/blob/a58e16e025d669403ad6c29e60c14f8215769bd4/src/NoPromise.js#L92-L124 | train |
|
georgenorman/tessel-kit | lib/classes/button-mgr.js | function(time) {
var self = this;
self.eventDetection.recordRelease(time);
if (self.eventDetection.isLongPress()) {
// this is a "long-press" - reset detection states and notify the "long-press" observers
self.eventDetection.reset();
self._notifyObservers(self.onLongPressCallbackRegistry);
} else {
if (self.eventDetection.onReleaseCount >= 2) {
// this is a double-press (or more) event, so notify the "double-press" observers
self.eventDetection.reset();
self._notifyObservers(self.onDoublePressCallbackRegistry);
}
setTimeout(function(){
if (self.eventDetection.onReleaseCount == 1) {
// second press did not occur within the allotted time, so notify the "short-press" observers
self.eventDetection.reset();
self._notifyObservers(self.onShortPressCallbackRegistry);
}
}, 300); // @-@:p0 make this configurable?
}
} | javascript | function(time) {
var self = this;
self.eventDetection.recordRelease(time);
if (self.eventDetection.isLongPress()) {
// this is a "long-press" - reset detection states and notify the "long-press" observers
self.eventDetection.reset();
self._notifyObservers(self.onLongPressCallbackRegistry);
} else {
if (self.eventDetection.onReleaseCount >= 2) {
// this is a double-press (or more) event, so notify the "double-press" observers
self.eventDetection.reset();
self._notifyObservers(self.onDoublePressCallbackRegistry);
}
setTimeout(function(){
if (self.eventDetection.onReleaseCount == 1) {
// second press did not occur within the allotted time, so notify the "short-press" observers
self.eventDetection.reset();
self._notifyObservers(self.onShortPressCallbackRegistry);
}
}, 300); // @-@:p0 make this configurable?
}
} | [
"function",
"(",
"time",
")",
"{",
"var",
"self",
"=",
"this",
";",
"self",
".",
"eventDetection",
".",
"recordRelease",
"(",
"time",
")",
";",
"if",
"(",
"self",
".",
"eventDetection",
".",
"isLongPress",
"(",
")",
")",
"{",
"self",
".",
"eventDetection",
".",
"reset",
"(",
")",
";",
"self",
".",
"_notifyObservers",
"(",
"self",
".",
"onLongPressCallbackRegistry",
")",
";",
"}",
"else",
"{",
"if",
"(",
"self",
".",
"eventDetection",
".",
"onReleaseCount",
">=",
"2",
")",
"{",
"self",
".",
"eventDetection",
".",
"reset",
"(",
")",
";",
"self",
".",
"_notifyObservers",
"(",
"self",
".",
"onDoublePressCallbackRegistry",
")",
";",
"}",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"self",
".",
"eventDetection",
".",
"onReleaseCount",
"==",
"1",
")",
"{",
"self",
".",
"eventDetection",
".",
"reset",
"(",
")",
";",
"self",
".",
"_notifyObservers",
"(",
"self",
".",
"onShortPressCallbackRegistry",
")",
";",
"}",
"}",
",",
"300",
")",
";",
"}",
"}"
]
| Handle the button-release event generated by the button associated with this ButtonMgr instance.
@param time the time of the button-up event. | [
"Handle",
"the",
"button",
"-",
"release",
"event",
"generated",
"by",
"the",
"button",
"associated",
"with",
"this",
"ButtonMgr",
"instance",
"."
]
| 487e91360f0ecf8500d24297228842e2c01ac762 | https://github.com/georgenorman/tessel-kit/blob/487e91360f0ecf8500d24297228842e2c01ac762/lib/classes/button-mgr.js#L172-L195 | train |
|
crokita/functionite | examples/example4.js | longWait | function longWait (message, timer, cb) {
setTimeout(function () {
console.log(message);
cb("pang"); //always return "pang"
}, timer); //wait one second before logging
} | javascript | function longWait (message, timer, cb) {
setTimeout(function () {
console.log(message);
cb("pang"); //always return "pang"
}, timer); //wait one second before logging
} | [
"function",
"longWait",
"(",
"message",
",",
"timer",
",",
"cb",
")",
"{",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"console",
".",
"log",
"(",
"message",
")",
";",
"cb",
"(",
"\"pang\"",
")",
";",
"}",
",",
"timer",
")",
";",
"}"
]
| scenario 2 "skip" will call the next function as soon as the execution context leaves the function and will ignore anything passed in the callback | [
"scenario",
"2",
"skip",
"will",
"call",
"the",
"next",
"function",
"as",
"soon",
"as",
"the",
"execution",
"context",
"leaves",
"the",
"function",
"and",
"will",
"ignore",
"anything",
"passed",
"in",
"the",
"callback"
]
| e5d52b3bded8eac6b42413208e1dc61e0741ae34 | https://github.com/crokita/functionite/blob/e5d52b3bded8eac6b42413208e1dc61e0741ae34/examples/example4.js#L43-L48 | train |
treshugart/ubercod | index.js | resolveDeps | function resolveDeps (args) {
return deps.map(function (dep) {
if (args && args.length && typeof dep === 'number') {
return args[dep];
}
dep = that[dep];
if (dep) {
return dep;
}
});
} | javascript | function resolveDeps (args) {
return deps.map(function (dep) {
if (args && args.length && typeof dep === 'number') {
return args[dep];
}
dep = that[dep];
if (dep) {
return dep;
}
});
} | [
"function",
"resolveDeps",
"(",
"args",
")",
"{",
"return",
"deps",
".",
"map",
"(",
"function",
"(",
"dep",
")",
"{",
"if",
"(",
"args",
"&&",
"args",
".",
"length",
"&&",
"typeof",
"dep",
"===",
"'number'",
")",
"{",
"return",
"args",
"[",
"dep",
"]",
";",
"}",
"dep",
"=",
"that",
"[",
"dep",
"]",
";",
"if",
"(",
"dep",
")",
"{",
"return",
"dep",
";",
"}",
"}",
")",
";",
"}"
]
| Returns the dependencies of the current dependency and merges in any supplied, named arguments. Arguments take precedence over dependencies in the container. | [
"Returns",
"the",
"dependencies",
"of",
"the",
"current",
"dependency",
"and",
"merges",
"in",
"any",
"supplied",
"named",
"arguments",
".",
"Arguments",
"take",
"precedence",
"over",
"dependencies",
"in",
"the",
"container",
"."
]
| 772accd6957acf24b59ca56fb40253a1e1760e77 | https://github.com/treshugart/ubercod/blob/772accd6957acf24b59ca56fb40253a1e1760e77/index.js#L61-L73 | train |
treshugart/ubercod | index.js | getInst | function getInst (bind, args) {
args = resolveDeps(args);
return isCtor ? applyCtor(func, args) : func.apply(bind, args);
} | javascript | function getInst (bind, args) {
args = resolveDeps(args);
return isCtor ? applyCtor(func, args) : func.apply(bind, args);
} | [
"function",
"getInst",
"(",
"bind",
",",
"args",
")",
"{",
"args",
"=",
"resolveDeps",
"(",
"args",
")",
";",
"return",
"isCtor",
"?",
"applyCtor",
"(",
"func",
",",
"args",
")",
":",
"func",
".",
"apply",
"(",
"bind",
",",
"args",
")",
";",
"}"
]
| Returns a dependency. It checks to see if it's a constructor function or a regular function and calls it accordingly. | [
"Returns",
"a",
"dependency",
".",
"It",
"checks",
"to",
"see",
"if",
"it",
"s",
"a",
"constructor",
"function",
"or",
"a",
"regular",
"function",
"and",
"calls",
"it",
"accordingly",
"."
]
| 772accd6957acf24b59ca56fb40253a1e1760e77 | https://github.com/treshugart/ubercod/blob/772accd6957acf24b59ca56fb40253a1e1760e77/index.js#L77-L80 | train |
treshugart/ubercod | index.js | resolveInst | function resolveInst (bind, args) {
return isTransient ? getInst(bind, args) : cache || (cache = getInst(bind));
} | javascript | function resolveInst (bind, args) {
return isTransient ? getInst(bind, args) : cache || (cache = getInst(bind));
} | [
"function",
"resolveInst",
"(",
"bind",
",",
"args",
")",
"{",
"return",
"isTransient",
"?",
"getInst",
"(",
"bind",
",",
"args",
")",
":",
"cache",
"||",
"(",
"cache",
"=",
"getInst",
"(",
"bind",
")",
")",
";",
"}"
]
| Resolves the dependency based on if it's a singleton or transient dependency. Both forms allow arguments. If it's a singleton, then no arguments are allowed. If it's transient, named arguments are allowed. | [
"Resolves",
"the",
"dependency",
"based",
"on",
"if",
"it",
"s",
"a",
"singleton",
"or",
"transient",
"dependency",
".",
"Both",
"forms",
"allow",
"arguments",
".",
"If",
"it",
"s",
"a",
"singleton",
"then",
"no",
"arguments",
"are",
"allowed",
".",
"If",
"it",
"s",
"transient",
"named",
"arguments",
"are",
"allowed",
"."
]
| 772accd6957acf24b59ca56fb40253a1e1760e77 | https://github.com/treshugart/ubercod/blob/772accd6957acf24b59ca56fb40253a1e1760e77/index.js#L85-L87 | train |
treshugart/ubercod | index.js | init | function init (func) {
func = ensureFunc(func);
cache = undefined;
deps = parseDepsFromFunc(func);
} | javascript | function init (func) {
func = ensureFunc(func);
cache = undefined;
deps = parseDepsFromFunc(func);
} | [
"function",
"init",
"(",
"func",
")",
"{",
"func",
"=",
"ensureFunc",
"(",
"func",
")",
";",
"cache",
"=",
"undefined",
";",
"deps",
"=",
"parseDepsFromFunc",
"(",
"func",
")",
";",
"}"
]
| Initialises or re-initialises the state of the dependency. | [
"Initialises",
"or",
"re",
"-",
"initialises",
"the",
"state",
"of",
"the",
"dependency",
"."
]
| 772accd6957acf24b59ca56fb40253a1e1760e77 | https://github.com/treshugart/ubercod/blob/772accd6957acf24b59ca56fb40253a1e1760e77/index.js#L90-L94 | train |
skerit/alchemy-styleboost | public/ckeditor/4.4dev/plugins/toolbar/plugin.js | getItemDefinedGroups | function getItemDefinedGroups() {
var groups = {},
itemName, item, itemToolbar, group, order;
for ( itemName in editor.ui.items ) {
item = editor.ui.items[ itemName ];
itemToolbar = item.toolbar || 'others';
if ( itemToolbar ) {
// Break the toolbar property into its parts: "group_name[,order]".
itemToolbar = itemToolbar.split( ',' );
group = itemToolbar[ 0 ];
order = parseInt( itemToolbar[ 1 ] || -1, 10 );
// Initialize the group, if necessary.
groups[ group ] || ( groups[ group ] = [] );
// Push the data used to build the toolbar later.
groups[ group ].push( { name: itemName, order: order } );
}
}
// Put the items in the right order.
for ( group in groups ) {
groups[ group ] = groups[ group ].sort( function( a, b ) {
return a.order == b.order ? 0 :
b.order < 0 ? -1 :
a.order < 0 ? 1 :
a.order < b.order ? -1 :
1;
} );
}
return groups;
} | javascript | function getItemDefinedGroups() {
var groups = {},
itemName, item, itemToolbar, group, order;
for ( itemName in editor.ui.items ) {
item = editor.ui.items[ itemName ];
itemToolbar = item.toolbar || 'others';
if ( itemToolbar ) {
// Break the toolbar property into its parts: "group_name[,order]".
itemToolbar = itemToolbar.split( ',' );
group = itemToolbar[ 0 ];
order = parseInt( itemToolbar[ 1 ] || -1, 10 );
// Initialize the group, if necessary.
groups[ group ] || ( groups[ group ] = [] );
// Push the data used to build the toolbar later.
groups[ group ].push( { name: itemName, order: order } );
}
}
// Put the items in the right order.
for ( group in groups ) {
groups[ group ] = groups[ group ].sort( function( a, b ) {
return a.order == b.order ? 0 :
b.order < 0 ? -1 :
a.order < 0 ? 1 :
a.order < b.order ? -1 :
1;
} );
}
return groups;
} | [
"function",
"getItemDefinedGroups",
"(",
")",
"{",
"var",
"groups",
"=",
"{",
"}",
",",
"itemName",
",",
"item",
",",
"itemToolbar",
",",
"group",
",",
"order",
";",
"for",
"(",
"itemName",
"in",
"editor",
".",
"ui",
".",
"items",
")",
"{",
"item",
"=",
"editor",
".",
"ui",
".",
"items",
"[",
"itemName",
"]",
";",
"itemToolbar",
"=",
"item",
".",
"toolbar",
"||",
"'others'",
";",
"if",
"(",
"itemToolbar",
")",
"{",
"itemToolbar",
"=",
"itemToolbar",
".",
"split",
"(",
"','",
")",
";",
"group",
"=",
"itemToolbar",
"[",
"0",
"]",
";",
"order",
"=",
"parseInt",
"(",
"itemToolbar",
"[",
"1",
"]",
"||",
"-",
"1",
",",
"10",
")",
";",
"groups",
"[",
"group",
"]",
"||",
"(",
"groups",
"[",
"group",
"]",
"=",
"[",
"]",
")",
";",
"groups",
"[",
"group",
"]",
".",
"push",
"(",
"{",
"name",
":",
"itemName",
",",
"order",
":",
"order",
"}",
")",
";",
"}",
"}",
"for",
"(",
"group",
"in",
"groups",
")",
"{",
"groups",
"[",
"group",
"]",
"=",
"groups",
"[",
"group",
"]",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"a",
".",
"order",
"==",
"b",
".",
"order",
"?",
"0",
":",
"b",
".",
"order",
"<",
"0",
"?",
"-",
"1",
":",
"a",
".",
"order",
"<",
"0",
"?",
"1",
":",
"a",
".",
"order",
"<",
"b",
".",
"order",
"?",
"-",
"1",
":",
"1",
";",
"}",
")",
";",
"}",
"return",
"groups",
";",
"}"
]
| Returns an object containing all toolbar groups used by ui items. | [
"Returns",
"an",
"object",
"containing",
"all",
"toolbar",
"groups",
"used",
"by",
"ui",
"items",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/toolbar/plugin.js#L462-L495 | train |
activethread/vulpejs | lib/models/index.js | function (query, page, callback) {
var History = exports.get('History');
History.paginate(query, {
page: page,
limit: vulpejs.app.pagination.history,
}, function (error, items, pageCount, itemCount) {
if (error) {
vulpejs.log.error('HISTORY', error);
} else {
callback(error, {
items: items,
pageCount: pageCount,
itemCount: itemCount,
});
}
}, {
sortBy: {
version: -1,
},
});
} | javascript | function (query, page, callback) {
var History = exports.get('History');
History.paginate(query, {
page: page,
limit: vulpejs.app.pagination.history,
}, function (error, items, pageCount, itemCount) {
if (error) {
vulpejs.log.error('HISTORY', error);
} else {
callback(error, {
items: items,
pageCount: pageCount,
itemCount: itemCount,
});
}
}, {
sortBy: {
version: -1,
},
});
} | [
"function",
"(",
"query",
",",
"page",
",",
"callback",
")",
"{",
"var",
"History",
"=",
"exports",
".",
"get",
"(",
"'History'",
")",
";",
"History",
".",
"paginate",
"(",
"query",
",",
"{",
"page",
":",
"page",
",",
"limit",
":",
"vulpejs",
".",
"app",
".",
"pagination",
".",
"history",
",",
"}",
",",
"function",
"(",
"error",
",",
"items",
",",
"pageCount",
",",
"itemCount",
")",
"{",
"if",
"(",
"error",
")",
"{",
"vulpejs",
".",
"log",
".",
"error",
"(",
"'HISTORY'",
",",
"error",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"error",
",",
"{",
"items",
":",
"items",
",",
"pageCount",
":",
"pageCount",
",",
"itemCount",
":",
"itemCount",
",",
"}",
")",
";",
"}",
"}",
",",
"{",
"sortBy",
":",
"{",
"version",
":",
"-",
"1",
",",
"}",
",",
"}",
")",
";",
"}"
]
| Find and page histories of object in database.
@param {Object} query Query
@param {Number} page Page
@param {Function} callback Callback function | [
"Find",
"and",
"page",
"histories",
"of",
"object",
"in",
"database",
"."
]
| cba9529ebb13892b2c7d07219c7fa69137151fbd | https://github.com/activethread/vulpejs/blob/cba9529ebb13892b2c7d07219c7fa69137151fbd/lib/models/index.js#L445-L465 | train |
|
byu-oit/sans-server | bin/server/request.js | Request | function Request(server, keys, rejectable, config) {
if (!config) config = {};
if (typeof config !== 'object') config = { path: config };
const promise = new Promise((resolve, reject) => {
let fulfilled = false;
this.on('res-complete', () => {
if (fulfilled) {
req.log('fulfilled', 'Already fulfilled');
} else {
fulfilled = true;
req.log('fulfilled');
resolve(res.state);
}
});
this.on('error', err => {
req.log('error', err.stack.replace(/\n/g, '\n '));
if (fulfilled) {
req.log('fulfilled', 'Already fulfilled');
} else {
fulfilled = true;
res.reset().set('content-type', 'text/plain').status(500).body(httpStatus[500]);
req.log('fulfilled');
if (rejectable) {
reject(err);
} else {
resolve(res.state);
}
}
});
});
// initialize variables
const id = uuid();
const hooks = {};
const req = this;
const res = new Response(this, keys.response);
/**
* Get the unique ID associated with this request.
* @name Request#id
* @type {string}
* @readonly
*/
Object.defineProperty(this, 'id', {
configurable: false,
enumerable: true,
value: id
});
/**
* Get the response object that is tied to this request.
* @name Request#res
* @type {Response}
*/
Object.defineProperty(this, 'res', {
configurable: false,
enumerable: true,
value: res
});
/**
* Get the server instance that initialized this request.
* @name Request#server
* @type {SansServer}
*/
Object.defineProperty(this, 'server', {
enumerable: true,
configurable: false,
value: server
});
/**
* Get the request URL which consists of the path and the query parameters.
* @name Request#url
* @type {string}
* @readonly
*/
Object.defineProperty(this, 'url', {
configurable: false,
enumerable: true,
get: () => this.path + buildQueryString(this.query)
});
/**
* Add a rejection handler to the request promise.
* @name Request#catch
* @param {Function} onRejected
* @returns {Promise}
*/
this.catch = onRejected => promise.catch(onRejected);
/**
* Produce a request log event.
* @param {string} message
* @param {...*} [args]
* @returns {Request}
* @fires Request#log
*/
this.log = this.logger('sans-server', 'request', this);
/**
* Add request specific hooks
* @param {string} type
* @param {number} [weight=0]
* @param {...Function} hook
* @returns {Request}
*/
this.hook = addHook.bind(this, hooks);
/**
* @name Request#hook.run
* @param {Symbol} type
* @param {function} [next]
* @returns {Promise|undefined}
*/
this.hook.reverse = (type, next) => runHooksMode(req, hooks, 'reverse', type, next);
/**
* @name Request#hook.run
* @param {Symbol} type
* @param {function} [next]
* @returns {Promise|undefined}
*/
this.hook.run = (type, next) => runHooksMode(req, hooks, 'run', type, next);
/**
* Add fulfillment or rejection handlers to the request promise.
* @name Request#then
* @param {Function} onFulfilled
* @param {Function} [onRejected]
* @returns {Promise}
*/
this.then = (onFulfilled, onRejected) => promise.then(onFulfilled, onRejected);
/**
* The request body.
* @name Request#body
* @type {string|Object|Buffer|undefined}
*/
/**
* The request headers. This is an object that has lower-case keys and string values.
* @name Request#headers
* @type {Object<string,string>}
*/
/**
* This request method. The lower case equivalents of these value are acceptable but will be automatically lower-cased.
* @name Request#method
* @type {string} One of: 'GET', 'DELETE', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT'
*/
/**
* The request path, beginning with a '/'. Does not include domain or query string.
* @name Request#path
* @type {string}
*/
/**
* An object mapping query parameters by key.
* @name Request#query
* @type {object<string,string>}
*/
// validate and normalize input
Object.assign(this, config, normalize(req, config));
// wait one tick for any event listeners to be added
process.nextTick(() => {
// run request hooks
this.hook.run(keys.request)
.then(() => {
if (!res.sent) {
req.log('unhandled', 'request not handled');
if (res.state.statusCode === 0) {
res.sendStatus(404);
} else {
res.send();
}
}
})
.catch(err => {
this.emit('error', err)
});
});
} | javascript | function Request(server, keys, rejectable, config) {
if (!config) config = {};
if (typeof config !== 'object') config = { path: config };
const promise = new Promise((resolve, reject) => {
let fulfilled = false;
this.on('res-complete', () => {
if (fulfilled) {
req.log('fulfilled', 'Already fulfilled');
} else {
fulfilled = true;
req.log('fulfilled');
resolve(res.state);
}
});
this.on('error', err => {
req.log('error', err.stack.replace(/\n/g, '\n '));
if (fulfilled) {
req.log('fulfilled', 'Already fulfilled');
} else {
fulfilled = true;
res.reset().set('content-type', 'text/plain').status(500).body(httpStatus[500]);
req.log('fulfilled');
if (rejectable) {
reject(err);
} else {
resolve(res.state);
}
}
});
});
// initialize variables
const id = uuid();
const hooks = {};
const req = this;
const res = new Response(this, keys.response);
/**
* Get the unique ID associated with this request.
* @name Request#id
* @type {string}
* @readonly
*/
Object.defineProperty(this, 'id', {
configurable: false,
enumerable: true,
value: id
});
/**
* Get the response object that is tied to this request.
* @name Request#res
* @type {Response}
*/
Object.defineProperty(this, 'res', {
configurable: false,
enumerable: true,
value: res
});
/**
* Get the server instance that initialized this request.
* @name Request#server
* @type {SansServer}
*/
Object.defineProperty(this, 'server', {
enumerable: true,
configurable: false,
value: server
});
/**
* Get the request URL which consists of the path and the query parameters.
* @name Request#url
* @type {string}
* @readonly
*/
Object.defineProperty(this, 'url', {
configurable: false,
enumerable: true,
get: () => this.path + buildQueryString(this.query)
});
/**
* Add a rejection handler to the request promise.
* @name Request#catch
* @param {Function} onRejected
* @returns {Promise}
*/
this.catch = onRejected => promise.catch(onRejected);
/**
* Produce a request log event.
* @param {string} message
* @param {...*} [args]
* @returns {Request}
* @fires Request#log
*/
this.log = this.logger('sans-server', 'request', this);
/**
* Add request specific hooks
* @param {string} type
* @param {number} [weight=0]
* @param {...Function} hook
* @returns {Request}
*/
this.hook = addHook.bind(this, hooks);
/**
* @name Request#hook.run
* @param {Symbol} type
* @param {function} [next]
* @returns {Promise|undefined}
*/
this.hook.reverse = (type, next) => runHooksMode(req, hooks, 'reverse', type, next);
/**
* @name Request#hook.run
* @param {Symbol} type
* @param {function} [next]
* @returns {Promise|undefined}
*/
this.hook.run = (type, next) => runHooksMode(req, hooks, 'run', type, next);
/**
* Add fulfillment or rejection handlers to the request promise.
* @name Request#then
* @param {Function} onFulfilled
* @param {Function} [onRejected]
* @returns {Promise}
*/
this.then = (onFulfilled, onRejected) => promise.then(onFulfilled, onRejected);
/**
* The request body.
* @name Request#body
* @type {string|Object|Buffer|undefined}
*/
/**
* The request headers. This is an object that has lower-case keys and string values.
* @name Request#headers
* @type {Object<string,string>}
*/
/**
* This request method. The lower case equivalents of these value are acceptable but will be automatically lower-cased.
* @name Request#method
* @type {string} One of: 'GET', 'DELETE', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT'
*/
/**
* The request path, beginning with a '/'. Does not include domain or query string.
* @name Request#path
* @type {string}
*/
/**
* An object mapping query parameters by key.
* @name Request#query
* @type {object<string,string>}
*/
// validate and normalize input
Object.assign(this, config, normalize(req, config));
// wait one tick for any event listeners to be added
process.nextTick(() => {
// run request hooks
this.hook.run(keys.request)
.then(() => {
if (!res.sent) {
req.log('unhandled', 'request not handled');
if (res.state.statusCode === 0) {
res.sendStatus(404);
} else {
res.send();
}
}
})
.catch(err => {
this.emit('error', err)
});
});
} | [
"function",
"Request",
"(",
"server",
",",
"keys",
",",
"rejectable",
",",
"config",
")",
"{",
"if",
"(",
"!",
"config",
")",
"config",
"=",
"{",
"}",
";",
"if",
"(",
"typeof",
"config",
"!==",
"'object'",
")",
"config",
"=",
"{",
"path",
":",
"config",
"}",
";",
"const",
"promise",
"=",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"let",
"fulfilled",
"=",
"false",
";",
"this",
".",
"on",
"(",
"'res-complete'",
",",
"(",
")",
"=>",
"{",
"if",
"(",
"fulfilled",
")",
"{",
"req",
".",
"log",
"(",
"'fulfilled'",
",",
"'Already fulfilled'",
")",
";",
"}",
"else",
"{",
"fulfilled",
"=",
"true",
";",
"req",
".",
"log",
"(",
"'fulfilled'",
")",
";",
"resolve",
"(",
"res",
".",
"state",
")",
";",
"}",
"}",
")",
";",
"this",
".",
"on",
"(",
"'error'",
",",
"err",
"=>",
"{",
"req",
".",
"log",
"(",
"'error'",
",",
"err",
".",
"stack",
".",
"replace",
"(",
"/",
"\\n",
"/",
"g",
",",
"'\\n '",
")",
")",
";",
"\\n",
"}",
")",
";",
"}",
")",
";",
"if",
"(",
"fulfilled",
")",
"{",
"req",
".",
"log",
"(",
"'fulfilled'",
",",
"'Already fulfilled'",
")",
";",
"}",
"else",
"{",
"fulfilled",
"=",
"true",
";",
"res",
".",
"reset",
"(",
")",
".",
"set",
"(",
"'content-type'",
",",
"'text/plain'",
")",
".",
"status",
"(",
"500",
")",
".",
"body",
"(",
"httpStatus",
"[",
"500",
"]",
")",
";",
"req",
".",
"log",
"(",
"'fulfilled'",
")",
";",
"if",
"(",
"rejectable",
")",
"{",
"reject",
"(",
"err",
")",
";",
"}",
"else",
"{",
"resolve",
"(",
"res",
".",
"state",
")",
";",
"}",
"}",
"const",
"id",
"=",
"uuid",
"(",
")",
";",
"const",
"hooks",
"=",
"{",
"}",
";",
"const",
"req",
"=",
"this",
";",
"const",
"res",
"=",
"new",
"Response",
"(",
"this",
",",
"keys",
".",
"response",
")",
";",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'id'",
",",
"{",
"configurable",
":",
"false",
",",
"enumerable",
":",
"true",
",",
"value",
":",
"id",
"}",
")",
";",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'res'",
",",
"{",
"configurable",
":",
"false",
",",
"enumerable",
":",
"true",
",",
"value",
":",
"res",
"}",
")",
";",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'server'",
",",
"{",
"enumerable",
":",
"true",
",",
"configurable",
":",
"false",
",",
"value",
":",
"server",
"}",
")",
";",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'url'",
",",
"{",
"configurable",
":",
"false",
",",
"enumerable",
":",
"true",
",",
"get",
":",
"(",
")",
"=>",
"this",
".",
"path",
"+",
"buildQueryString",
"(",
"this",
".",
"query",
")",
"}",
")",
";",
"this",
".",
"catch",
"=",
"onRejected",
"=>",
"promise",
".",
"catch",
"(",
"onRejected",
")",
";",
"this",
".",
"log",
"=",
"this",
".",
"logger",
"(",
"'sans-server'",
",",
"'request'",
",",
"this",
")",
";",
"this",
".",
"hook",
"=",
"addHook",
".",
"bind",
"(",
"this",
",",
"hooks",
")",
";",
"this",
".",
"hook",
".",
"reverse",
"=",
"(",
"type",
",",
"next",
")",
"=>",
"runHooksMode",
"(",
"req",
",",
"hooks",
",",
"'reverse'",
",",
"type",
",",
"next",
")",
";",
"this",
".",
"hook",
".",
"run",
"=",
"(",
"type",
",",
"next",
")",
"=>",
"runHooksMode",
"(",
"req",
",",
"hooks",
",",
"'run'",
",",
"type",
",",
"next",
")",
";",
"this",
".",
"then",
"=",
"(",
"onFulfilled",
",",
"onRejected",
")",
"=>",
"promise",
".",
"then",
"(",
"onFulfilled",
",",
"onRejected",
")",
";",
"Object",
".",
"assign",
"(",
"this",
",",
"config",
",",
"normalize",
"(",
"req",
",",
"config",
")",
")",
";",
"}"
]
| Generate a request instance.
@param {SansServer} server
@param {object} keys
@param {boolean} rejectable
@param {string|Object} [config] A string representing the path or a configuration representing all properties
to accompany the request.
@returns {Request}
@constructor
@augments {EventEmitter}
@augments {Promise} | [
"Generate",
"a",
"request",
"instance",
"."
]
| 022bcf7b47321e6e8aa20467cd96a6a84a457ec8 | https://github.com/byu-oit/sans-server/blob/022bcf7b47321e6e8aa20467cd96a6a84a457ec8/bin/server/request.js#L40-L229 | train |
ericsaboia/migrate-database | tasks/lib/migrate.js | Migrate | function Migrate (grunt, adapter, config, steps) {
this.grunt = grunt;
this.adapter = adapter;
this.path = path.resolve(config.path);
this.steps = steps;
} | javascript | function Migrate (grunt, adapter, config, steps) {
this.grunt = grunt;
this.adapter = adapter;
this.path = path.resolve(config.path);
this.steps = steps;
} | [
"function",
"Migrate",
"(",
"grunt",
",",
"adapter",
",",
"config",
",",
"steps",
")",
"{",
"this",
".",
"grunt",
"=",
"grunt",
";",
"this",
".",
"adapter",
"=",
"adapter",
";",
"this",
".",
"path",
"=",
"path",
".",
"resolve",
"(",
"config",
".",
"path",
")",
";",
"this",
".",
"steps",
"=",
"steps",
";",
"}"
]
| Initialize a new migration `Migrate` with the given `grunt, adapter, path and steps`
@param {Object} grunt
@param {Adapter} adapter
@param {String} path
@param {Number} steps
@api private | [
"Initialize",
"a",
"new",
"migration",
"Migrate",
"with",
"the",
"given",
"grunt",
"adapter",
"path",
"and",
"steps"
]
| 7a9afb4d1b4aeb1bb5e6c1ae7a2a7c7e0fa16e5d | https://github.com/ericsaboia/migrate-database/blob/7a9afb4d1b4aeb1bb5e6c1ae7a2a7c7e0fa16e5d/tasks/lib/migrate.js#L35-L40 | train |
kmalakoff/backbone-articulation | vendor/lifecycle-1.0.2.js | function(parent, protoProps, staticProps) {
var child;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your extend definition), or defaulted
// by us to simply call the parent's constructor.
if (protoProps && protoProps.hasOwnProperty('constructor')) {
child = protoProps.constructor;
} else {
child = function(){ parent.apply(this, arguments); };
}
// Inherit class (static) properties from parent.
copyProps(child, parent);
// Set the prototype chain to inherit from parent, without calling
// parent's constructor function.
ctor.prototype = parent.prototype;
child.prototype = new ctor();
// Add prototype properties (instance properties) to the subclass,
// if supplied.
if (protoProps) copyProps(child.prototype, protoProps);
// Add static properties to the constructor function, if supplied.
if (staticProps) copyProps(child, staticProps);
// Correctly set child's 'prototype.constructor'.
child.prototype.constructor = child;
// Set a convenience property in case the parent's prototype is needed later.
child.__super__ = parent.prototype;
return child;
} | javascript | function(parent, protoProps, staticProps) {
var child;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your extend definition), or defaulted
// by us to simply call the parent's constructor.
if (protoProps && protoProps.hasOwnProperty('constructor')) {
child = protoProps.constructor;
} else {
child = function(){ parent.apply(this, arguments); };
}
// Inherit class (static) properties from parent.
copyProps(child, parent);
// Set the prototype chain to inherit from parent, without calling
// parent's constructor function.
ctor.prototype = parent.prototype;
child.prototype = new ctor();
// Add prototype properties (instance properties) to the subclass,
// if supplied.
if (protoProps) copyProps(child.prototype, protoProps);
// Add static properties to the constructor function, if supplied.
if (staticProps) copyProps(child, staticProps);
// Correctly set child's 'prototype.constructor'.
child.prototype.constructor = child;
// Set a convenience property in case the parent's prototype is needed later.
child.__super__ = parent.prototype;
return child;
} | [
"function",
"(",
"parent",
",",
"protoProps",
",",
"staticProps",
")",
"{",
"var",
"child",
";",
"if",
"(",
"protoProps",
"&&",
"protoProps",
".",
"hasOwnProperty",
"(",
"'constructor'",
")",
")",
"{",
"child",
"=",
"protoProps",
".",
"constructor",
";",
"}",
"else",
"{",
"child",
"=",
"function",
"(",
")",
"{",
"parent",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
";",
"}",
"copyProps",
"(",
"child",
",",
"parent",
")",
";",
"ctor",
".",
"prototype",
"=",
"parent",
".",
"prototype",
";",
"child",
".",
"prototype",
"=",
"new",
"ctor",
"(",
")",
";",
"if",
"(",
"protoProps",
")",
"copyProps",
"(",
"child",
".",
"prototype",
",",
"protoProps",
")",
";",
"if",
"(",
"staticProps",
")",
"copyProps",
"(",
"child",
",",
"staticProps",
")",
";",
"child",
".",
"prototype",
".",
"constructor",
"=",
"child",
";",
"child",
".",
"__super__",
"=",
"parent",
".",
"prototype",
";",
"return",
"child",
";",
"}"
]
| Helper function to correctly set up the prototype chain, for subclasses. Similar to 'goog.inherits', but uses a hash of prototype properties and class properties to be extended. | [
"Helper",
"function",
"to",
"correctly",
"set",
"up",
"the",
"prototype",
"chain",
"for",
"subclasses",
".",
"Similar",
"to",
"goog",
".",
"inherits",
"but",
"uses",
"a",
"hash",
"of",
"prototype",
"properties",
"and",
"class",
"properties",
"to",
"be",
"extended",
"."
]
| ce093551bab078369b5f9f4244873d108a344eb5 | https://github.com/kmalakoff/backbone-articulation/blob/ce093551bab078369b5f9f4244873d108a344eb5/vendor/lifecycle-1.0.2.js#L56-L90 | train |
|
jpitts/rapt-modelrizerly | lib/datastores/mongodb.js | function (finder) {
if (mongo_query_options && mongo_query_options.sort) {
finder.sort(mongo_query_options.sort).toArray(cb);
} else {
finder.toArray(cb);
}
} | javascript | function (finder) {
if (mongo_query_options && mongo_query_options.sort) {
finder.sort(mongo_query_options.sort).toArray(cb);
} else {
finder.toArray(cb);
}
} | [
"function",
"(",
"finder",
")",
"{",
"if",
"(",
"mongo_query_options",
"&&",
"mongo_query_options",
".",
"sort",
")",
"{",
"finder",
".",
"sort",
"(",
"mongo_query_options",
".",
"sort",
")",
".",
"toArray",
"(",
"cb",
")",
";",
"}",
"else",
"{",
"finder",
".",
"toArray",
"(",
"cb",
")",
";",
"}",
"}"
]
| final sorting and rendering to array | [
"final",
"sorting",
"and",
"rendering",
"to",
"array"
]
| 4b6b5bd0e7838c05029e7c20d500c9f4f7b0cc92 | https://github.com/jpitts/rapt-modelrizerly/blob/4b6b5bd0e7838c05029e7c20d500c9f4f7b0cc92/lib/datastores/mongodb.js#L227-L236 | train |
|
skerit/alchemy-styleboost | public/ckeditor/4.4dev/plugins/link/plugin.js | function( editor ) {
var selection = editor.getSelection();
var selectedElement = selection.getSelectedElement();
if ( selectedElement && selectedElement.is( 'a' ) )
return selectedElement;
var range = selection.getRanges()[ 0 ];
if ( range ) {
range.shrink( CKEDITOR.SHRINK_TEXT );
return editor.elementPath( range.getCommonAncestor() ).contains( 'a', 1 );
}
return null;
} | javascript | function( editor ) {
var selection = editor.getSelection();
var selectedElement = selection.getSelectedElement();
if ( selectedElement && selectedElement.is( 'a' ) )
return selectedElement;
var range = selection.getRanges()[ 0 ];
if ( range ) {
range.shrink( CKEDITOR.SHRINK_TEXT );
return editor.elementPath( range.getCommonAncestor() ).contains( 'a', 1 );
}
return null;
} | [
"function",
"(",
"editor",
")",
"{",
"var",
"selection",
"=",
"editor",
".",
"getSelection",
"(",
")",
";",
"var",
"selectedElement",
"=",
"selection",
".",
"getSelectedElement",
"(",
")",
";",
"if",
"(",
"selectedElement",
"&&",
"selectedElement",
".",
"is",
"(",
"'a'",
")",
")",
"return",
"selectedElement",
";",
"var",
"range",
"=",
"selection",
".",
"getRanges",
"(",
")",
"[",
"0",
"]",
";",
"if",
"(",
"range",
")",
"{",
"range",
".",
"shrink",
"(",
"CKEDITOR",
".",
"SHRINK_TEXT",
")",
";",
"return",
"editor",
".",
"elementPath",
"(",
"range",
".",
"getCommonAncestor",
"(",
")",
")",
".",
"contains",
"(",
"'a'",
",",
"1",
")",
";",
"}",
"return",
"null",
";",
"}"
]
| Get the surrounding link element of the current selection.
CKEDITOR.plugins.link.getSelectedLink( editor );
// The following selections will all return the link element.
<a href="#">li^nk</a>
<a href="#">[link]</a>
text[<a href="#">link]</a>
<a href="#">li[nk</a>]
[<b><a href="#">li]nk</a></b>]
[<a href="#"><b>li]nk</b></a>
@since 3.2.1
@param {CKEDITOR.editor} editor | [
"Get",
"the",
"surrounding",
"link",
"element",
"of",
"the",
"current",
"selection",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/link/plugin.js#L312-L325 | train |
|
christophercrouzet/pillr | lib/load_templates.js | loadTemplate | function loadTemplate(template, name, callback) {
async.waterfall([
cb => source(template.path, template.filter, template.readMode, cb),
(files, cb) => asDataMap(files, template.mapping, cb),
], (error, result) => {
async.nextTick(callback, error, result);
});
} | javascript | function loadTemplate(template, name, callback) {
async.waterfall([
cb => source(template.path, template.filter, template.readMode, cb),
(files, cb) => asDataMap(files, template.mapping, cb),
], (error, result) => {
async.nextTick(callback, error, result);
});
} | [
"function",
"loadTemplate",
"(",
"template",
",",
"name",
",",
"callback",
")",
"{",
"async",
".",
"waterfall",
"(",
"[",
"cb",
"=>",
"source",
"(",
"template",
".",
"path",
",",
"template",
".",
"filter",
",",
"template",
".",
"readMode",
",",
"cb",
")",
",",
"(",
"files",
",",
"cb",
")",
"=>",
"asDataMap",
"(",
"files",
",",
"template",
".",
"mapping",
",",
"cb",
")",
",",
"]",
",",
"(",
"error",
",",
"result",
")",
"=>",
"{",
"async",
".",
"nextTick",
"(",
"callback",
",",
"error",
",",
"result",
")",
";",
"}",
")",
";",
"}"
]
| Load a single template. | [
"Load",
"a",
"single",
"template",
"."
]
| 411ccd344a03478776c4e8d2e2f9bdc45dc8ee45 | https://github.com/christophercrouzet/pillr/blob/411ccd344a03478776c4e8d2e2f9bdc45dc8ee45/lib/load_templates.js#L23-L30 | train |
michaelnisi/pushup | index.js | Headers | function Headers (size, type, ttl, enc) {
if (!(this instanceof Headers)) return new Headers(size, type, ttl, enc)
if (size) this['Content-Length'] = size
if (type) this['Content-Type'] = type
if (!isNaN(ttl)) this['Cache-Control'] = 'max-age=' + ttl
if (enc) this['Content-Encoding'] = enc
} | javascript | function Headers (size, type, ttl, enc) {
if (!(this instanceof Headers)) return new Headers(size, type, ttl, enc)
if (size) this['Content-Length'] = size
if (type) this['Content-Type'] = type
if (!isNaN(ttl)) this['Cache-Control'] = 'max-age=' + ttl
if (enc) this['Content-Encoding'] = enc
} | [
"function",
"Headers",
"(",
"size",
",",
"type",
",",
"ttl",
",",
"enc",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Headers",
")",
")",
"return",
"new",
"Headers",
"(",
"size",
",",
"type",
",",
"ttl",
",",
"enc",
")",
"if",
"(",
"size",
")",
"this",
"[",
"'Content-Length'",
"]",
"=",
"size",
"if",
"(",
"type",
")",
"this",
"[",
"'Content-Type'",
"]",
"=",
"type",
"if",
"(",
"!",
"isNaN",
"(",
"ttl",
")",
")",
"this",
"[",
"'Cache-Control'",
"]",
"=",
"'max-age='",
"+",
"ttl",
"if",
"(",
"enc",
")",
"this",
"[",
"'Content-Encoding'",
"]",
"=",
"enc",
"}"
]
| - size the size of the entity-body in decimal number of octets - type the media type of the entity-body - ttl the maximum age in seconds - enc the modifier to the media-type | [
"-",
"size",
"the",
"size",
"of",
"the",
"entity",
"-",
"body",
"in",
"decimal",
"number",
"of",
"octets",
"-",
"type",
"the",
"media",
"type",
"of",
"the",
"entity",
"-",
"body",
"-",
"ttl",
"the",
"maximum",
"age",
"in",
"seconds",
"-",
"enc",
"the",
"modifier",
"to",
"the",
"media",
"-",
"type"
]
| 104c4db4a1938d89cf9e77cb97090c42ea3d35ed | https://github.com/michaelnisi/pushup/blob/104c4db4a1938d89cf9e77cb97090c42ea3d35ed/index.js#L70-L76 | train |
EyalAr/fume | bin/fume.js | function (next) {
async.each(input, function (path, done) {
fs.stat(path, function (err, stats) {
if (err) return done(err);
if (stats.isDirectory())
return done("Cannot have a directory as input");
done();
});
}, next);
} | javascript | function (next) {
async.each(input, function (path, done) {
fs.stat(path, function (err, stats) {
if (err) return done(err);
if (stats.isDirectory())
return done("Cannot have a directory as input");
done();
});
}, next);
} | [
"function",
"(",
"next",
")",
"{",
"async",
".",
"each",
"(",
"input",
",",
"function",
"(",
"path",
",",
"done",
")",
"{",
"fs",
".",
"stat",
"(",
"path",
",",
"function",
"(",
"err",
",",
"stats",
")",
"{",
"if",
"(",
"err",
")",
"return",
"done",
"(",
"err",
")",
";",
"if",
"(",
"stats",
".",
"isDirectory",
"(",
")",
")",
"return",
"done",
"(",
"\"Cannot have a directory as input\"",
")",
";",
"done",
"(",
")",
";",
"}",
")",
";",
"}",
",",
"next",
")",
";",
"}"
]
| make sure no directories in the input list | [
"make",
"sure",
"no",
"directories",
"in",
"the",
"input",
"list"
]
| 66f555d39b9cee18bbdf7a0a565919247163a227 | https://github.com/EyalAr/fume/blob/66f555d39b9cee18bbdf7a0a565919247163a227/bin/fume.js#L55-L66 | train |
|
codenothing/munit | lib/render.js | function( name ) {
if ( ! munit.isString( name ) || ! name.length ) {
throw new Error( "Name not found for removing formatter" );
}
if ( render._formatHash[ name ] ) {
delete render._formatHash[ name ];
render._formats = render._formats.filter(function( f ) {
return f.name !== name;
});
}
} | javascript | function( name ) {
if ( ! munit.isString( name ) || ! name.length ) {
throw new Error( "Name not found for removing formatter" );
}
if ( render._formatHash[ name ] ) {
delete render._formatHash[ name ];
render._formats = render._formats.filter(function( f ) {
return f.name !== name;
});
}
} | [
"function",
"(",
"name",
")",
"{",
"if",
"(",
"!",
"munit",
".",
"isString",
"(",
"name",
")",
"||",
"!",
"name",
".",
"length",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Name not found for removing formatter\"",
")",
";",
"}",
"if",
"(",
"render",
".",
"_formatHash",
"[",
"name",
"]",
")",
"{",
"delete",
"render",
".",
"_formatHash",
"[",
"name",
"]",
";",
"render",
".",
"_formats",
"=",
"render",
".",
"_formats",
".",
"filter",
"(",
"function",
"(",
"f",
")",
"{",
"return",
"f",
".",
"name",
"!==",
"name",
";",
"}",
")",
";",
"}",
"}"
]
| Removing a formatter | [
"Removing",
"a",
"formatter"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/render.js#L119-L130 | train |
|
codenothing/munit | lib/render.js | function( path, callback ) {
var parts = ( path || '' ).split( /\//g ),
filepath = '/';
// Trim Left
if ( ! parts[ 0 ].length ) {
parts.shift();
}
// Trim right
if ( parts.length && ! parts[ parts.length - 1 ].length ) {
parts.pop();
}
// Handle root '/' error
if ( ! parts.length ) {
return callback( new Error( "No directory path found to make" ) );
}
// Make sure each branch is created
async.mapSeries( parts,
function( dir, callback ) {
fs.stat( filepath += dir + '/', function( e, stat ) {
if ( stat && stat.isDirectory() ) {
callback();
}
else {
fs.mkdir( filepath, callback );
}
});
},
callback
);
} | javascript | function( path, callback ) {
var parts = ( path || '' ).split( /\//g ),
filepath = '/';
// Trim Left
if ( ! parts[ 0 ].length ) {
parts.shift();
}
// Trim right
if ( parts.length && ! parts[ parts.length - 1 ].length ) {
parts.pop();
}
// Handle root '/' error
if ( ! parts.length ) {
return callback( new Error( "No directory path found to make" ) );
}
// Make sure each branch is created
async.mapSeries( parts,
function( dir, callback ) {
fs.stat( filepath += dir + '/', function( e, stat ) {
if ( stat && stat.isDirectory() ) {
callback();
}
else {
fs.mkdir( filepath, callback );
}
});
},
callback
);
} | [
"function",
"(",
"path",
",",
"callback",
")",
"{",
"var",
"parts",
"=",
"(",
"path",
"||",
"''",
")",
".",
"split",
"(",
"/",
"\\/",
"/",
"g",
")",
",",
"filepath",
"=",
"'/'",
";",
"if",
"(",
"!",
"parts",
"[",
"0",
"]",
".",
"length",
")",
"{",
"parts",
".",
"shift",
"(",
")",
";",
"}",
"if",
"(",
"parts",
".",
"length",
"&&",
"!",
"parts",
"[",
"parts",
".",
"length",
"-",
"1",
"]",
".",
"length",
")",
"{",
"parts",
".",
"pop",
"(",
")",
";",
"}",
"if",
"(",
"!",
"parts",
".",
"length",
")",
"{",
"return",
"callback",
"(",
"new",
"Error",
"(",
"\"No directory path found to make\"",
")",
")",
";",
"}",
"async",
".",
"mapSeries",
"(",
"parts",
",",
"function",
"(",
"dir",
",",
"callback",
")",
"{",
"fs",
".",
"stat",
"(",
"filepath",
"+=",
"dir",
"+",
"'/'",
",",
"function",
"(",
"e",
",",
"stat",
")",
"{",
"if",
"(",
"stat",
"&&",
"stat",
".",
"isDirectory",
"(",
")",
")",
"{",
"callback",
"(",
")",
";",
"}",
"else",
"{",
"fs",
".",
"mkdir",
"(",
"filepath",
",",
"callback",
")",
";",
"}",
"}",
")",
";",
"}",
",",
"callback",
")",
";",
"}"
]
| Creates directory path if not already | [
"Creates",
"directory",
"path",
"if",
"not",
"already"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/render.js#L145-L178 | train |
|
codenothing/munit | lib/render.js | function( path, callback ) {
var match = munit.isRegExp( render.options.file_match ) ? render.options.file_match : rtestfile;
path += '/';
fs.readdir( path, function( e, files ) {
if ( e ) {
return callback( e );
}
async.each( files || [],
function( file, callback ) {
var fullpath = path + file;
fs.stat( fullpath, function( e, stat ) {
if ( e ) {
callback( e );
}
else if ( stat.isDirectory() ) {
render._renderPath( fullpath, callback );
}
else {
if ( stat.isFile() && match.exec( file ) ) {
munit.require( fullpath );
}
callback();
}
});
},
callback
);
});
} | javascript | function( path, callback ) {
var match = munit.isRegExp( render.options.file_match ) ? render.options.file_match : rtestfile;
path += '/';
fs.readdir( path, function( e, files ) {
if ( e ) {
return callback( e );
}
async.each( files || [],
function( file, callback ) {
var fullpath = path + file;
fs.stat( fullpath, function( e, stat ) {
if ( e ) {
callback( e );
}
else if ( stat.isDirectory() ) {
render._renderPath( fullpath, callback );
}
else {
if ( stat.isFile() && match.exec( file ) ) {
munit.require( fullpath );
}
callback();
}
});
},
callback
);
});
} | [
"function",
"(",
"path",
",",
"callback",
")",
"{",
"var",
"match",
"=",
"munit",
".",
"isRegExp",
"(",
"render",
".",
"options",
".",
"file_match",
")",
"?",
"render",
".",
"options",
".",
"file_match",
":",
"rtestfile",
";",
"path",
"+=",
"'/'",
";",
"fs",
".",
"readdir",
"(",
"path",
",",
"function",
"(",
"e",
",",
"files",
")",
"{",
"if",
"(",
"e",
")",
"{",
"return",
"callback",
"(",
"e",
")",
";",
"}",
"async",
".",
"each",
"(",
"files",
"||",
"[",
"]",
",",
"function",
"(",
"file",
",",
"callback",
")",
"{",
"var",
"fullpath",
"=",
"path",
"+",
"file",
";",
"fs",
".",
"stat",
"(",
"fullpath",
",",
"function",
"(",
"e",
",",
"stat",
")",
"{",
"if",
"(",
"e",
")",
"{",
"callback",
"(",
"e",
")",
";",
"}",
"else",
"if",
"(",
"stat",
".",
"isDirectory",
"(",
")",
")",
"{",
"render",
".",
"_renderPath",
"(",
"fullpath",
",",
"callback",
")",
";",
"}",
"else",
"{",
"if",
"(",
"stat",
".",
"isFile",
"(",
")",
"&&",
"match",
".",
"exec",
"(",
"file",
")",
")",
"{",
"munit",
".",
"require",
"(",
"fullpath",
")",
";",
"}",
"callback",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
",",
"callback",
")",
";",
"}",
")",
";",
"}"
]
| Loads up each possible test file | [
"Loads",
"up",
"each",
"possible",
"test",
"file"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/render.js#L181-L213 | train |
|
codenothing/munit | lib/render.js | function( nspath ) {
var found = true,
nsparts = nspath.split( rpathsplit ),
focus = render.options.focus;
// Allow single path string
if ( munit.isString( focus ) ) {
focus = [ focus ];
}
// If set, only add modules that belong on the focus path(s)
if ( munit.isArray( focus ) && focus.length ) {
found = false;
focus.forEach(function( fpath ) {
var fparts = fpath.split( rpathsplit ),
i = -1, l = Math.min( fparts.length, nsparts.length );
// Check that each namespace of the focus path
// exists inside the modules path
for ( ; ++i < l; ) {
if ( fparts[ i ] !== nsparts[ i ] ) {
return;
}
}
// Paths line up
found = true;
});
}
return found;
} | javascript | function( nspath ) {
var found = true,
nsparts = nspath.split( rpathsplit ),
focus = render.options.focus;
// Allow single path string
if ( munit.isString( focus ) ) {
focus = [ focus ];
}
// If set, only add modules that belong on the focus path(s)
if ( munit.isArray( focus ) && focus.length ) {
found = false;
focus.forEach(function( fpath ) {
var fparts = fpath.split( rpathsplit ),
i = -1, l = Math.min( fparts.length, nsparts.length );
// Check that each namespace of the focus path
// exists inside the modules path
for ( ; ++i < l; ) {
if ( fparts[ i ] !== nsparts[ i ] ) {
return;
}
}
// Paths line up
found = true;
});
}
return found;
} | [
"function",
"(",
"nspath",
")",
"{",
"var",
"found",
"=",
"true",
",",
"nsparts",
"=",
"nspath",
".",
"split",
"(",
"rpathsplit",
")",
",",
"focus",
"=",
"render",
".",
"options",
".",
"focus",
";",
"if",
"(",
"munit",
".",
"isString",
"(",
"focus",
")",
")",
"{",
"focus",
"=",
"[",
"focus",
"]",
";",
"}",
"if",
"(",
"munit",
".",
"isArray",
"(",
"focus",
")",
"&&",
"focus",
".",
"length",
")",
"{",
"found",
"=",
"false",
";",
"focus",
".",
"forEach",
"(",
"function",
"(",
"fpath",
")",
"{",
"var",
"fparts",
"=",
"fpath",
".",
"split",
"(",
"rpathsplit",
")",
",",
"i",
"=",
"-",
"1",
",",
"l",
"=",
"Math",
".",
"min",
"(",
"fparts",
".",
"length",
",",
"nsparts",
".",
"length",
")",
";",
"for",
"(",
";",
"++",
"i",
"<",
"l",
";",
")",
"{",
"if",
"(",
"fparts",
"[",
"i",
"]",
"!==",
"nsparts",
"[",
"i",
"]",
")",
"{",
"return",
";",
"}",
"}",
"found",
"=",
"true",
";",
"}",
")",
";",
"}",
"return",
"found",
";",
"}"
]
| Testing path to see if it exists in the focus option | [
"Testing",
"path",
"to",
"see",
"if",
"it",
"exists",
"in",
"the",
"focus",
"option"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/render.js#L216-L248 | train |
|
codenothing/munit | lib/render.js | function( required, startFunc ) {
if ( required !== render.state ) {
render._stateError( startFunc || render.requireState );
}
} | javascript | function( required, startFunc ) {
if ( required !== render.state ) {
render._stateError( startFunc || render.requireState );
}
} | [
"function",
"(",
"required",
",",
"startFunc",
")",
"{",
"if",
"(",
"required",
"!==",
"render",
".",
"state",
")",
"{",
"render",
".",
"_stateError",
"(",
"startFunc",
"||",
"render",
".",
"requireState",
")",
";",
"}",
"}"
]
| Throws an error if munit isn't in the required state | [
"Throws",
"an",
"error",
"if",
"munit",
"isn",
"t",
"in",
"the",
"required",
"state"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/render.js#L265-L269 | train |
|
codenothing/munit | lib/render.js | function( ns ) {
munit.each( ns, function( assert, name ) {
if ( render.focusPath( assert.nsPath ) ) {
munit.tests.push( assert );
}
else {
assert.trigger();
}
// Traverse down the module tree
render._renderNS( assert.ns );
});
return munit.tests;
} | javascript | function( ns ) {
munit.each( ns, function( assert, name ) {
if ( render.focusPath( assert.nsPath ) ) {
munit.tests.push( assert );
}
else {
assert.trigger();
}
// Traverse down the module tree
render._renderNS( assert.ns );
});
return munit.tests;
} | [
"function",
"(",
"ns",
")",
"{",
"munit",
".",
"each",
"(",
"ns",
",",
"function",
"(",
"assert",
",",
"name",
")",
"{",
"if",
"(",
"render",
".",
"focusPath",
"(",
"assert",
".",
"nsPath",
")",
")",
"{",
"munit",
".",
"tests",
".",
"push",
"(",
"assert",
")",
";",
"}",
"else",
"{",
"assert",
".",
"trigger",
"(",
")",
";",
"}",
"render",
".",
"_renderNS",
"(",
"assert",
".",
"ns",
")",
";",
"}",
")",
";",
"return",
"munit",
".",
"tests",
";",
"}"
]
| Renders each module | [
"Renders",
"each",
"module"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/render.js#L286-L300 | train |
|
codenothing/munit | lib/render.js | function( assert ) {
var stack = [], depends, i, l, module;
// Should only be checking dependencies when in compile mode
render.requireMinState( munit.RENDER_STATE_COMPILE, render.checkDepency );
// Build up the list of dependency paths
do {
depends = assert.option( 'depends' );
// Allow single path
if ( munit.isString( depends ) ) {
stack.push( depends );
}
// Add to stack of module dependencies
else if ( munit.isArray( depends ) ) {
stack = stack.concat( depends );
}
} while ( assert = assert.parAssert );
// Check each dependency for completion
for ( i = -1, l = stack.length; ++i < l; ) {
if ( munit( stack[ i ] || '' ).state < munit.ASSERT_STATE_CLOSED ) {
return false;
}
}
return true;
} | javascript | function( assert ) {
var stack = [], depends, i, l, module;
// Should only be checking dependencies when in compile mode
render.requireMinState( munit.RENDER_STATE_COMPILE, render.checkDepency );
// Build up the list of dependency paths
do {
depends = assert.option( 'depends' );
// Allow single path
if ( munit.isString( depends ) ) {
stack.push( depends );
}
// Add to stack of module dependencies
else if ( munit.isArray( depends ) ) {
stack = stack.concat( depends );
}
} while ( assert = assert.parAssert );
// Check each dependency for completion
for ( i = -1, l = stack.length; ++i < l; ) {
if ( munit( stack[ i ] || '' ).state < munit.ASSERT_STATE_CLOSED ) {
return false;
}
}
return true;
} | [
"function",
"(",
"assert",
")",
"{",
"var",
"stack",
"=",
"[",
"]",
",",
"depends",
",",
"i",
",",
"l",
",",
"module",
";",
"render",
".",
"requireMinState",
"(",
"munit",
".",
"RENDER_STATE_COMPILE",
",",
"render",
".",
"checkDepency",
")",
";",
"do",
"{",
"depends",
"=",
"assert",
".",
"option",
"(",
"'depends'",
")",
";",
"if",
"(",
"munit",
".",
"isString",
"(",
"depends",
")",
")",
"{",
"stack",
".",
"push",
"(",
"depends",
")",
";",
"}",
"else",
"if",
"(",
"munit",
".",
"isArray",
"(",
"depends",
")",
")",
"{",
"stack",
"=",
"stack",
".",
"concat",
"(",
"depends",
")",
";",
"}",
"}",
"while",
"(",
"assert",
"=",
"assert",
".",
"parAssert",
")",
";",
"for",
"(",
"i",
"=",
"-",
"1",
",",
"l",
"=",
"stack",
".",
"length",
";",
"++",
"i",
"<",
"l",
";",
")",
"{",
"if",
"(",
"munit",
"(",
"stack",
"[",
"i",
"]",
"||",
"''",
")",
".",
"state",
"<",
"munit",
".",
"ASSERT_STATE_CLOSED",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
]
| Checks test modules depencies to see if it can be run | [
"Checks",
"test",
"modules",
"depencies",
"to",
"see",
"if",
"it",
"can",
"be",
"run"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/render.js#L303-L331 | train |
|
codenothing/munit | lib/render.js | function(){
var options = render.options,
path = options.render = render._normalizePath( options.render );
// Ensure render path actually exists
fs.stat( path, function( e, stat ) {
if ( e || ! stat || ! stat.isDirectory() ) {
return munit.exit( 1, e, "'" + path + "' is not a directory" );
}
// Check for root munit config file
fs.exists( path + '/munit.js', function( exists ) {
if ( exists ) {
munit.require( path + '/munit.js' );
}
// Initialize all files in test path for submodule additions
render._renderPath( path, function( e ) {
if ( e ) {
return munit.exit( 1, e, "Unable to render test path" );
}
render._compile();
});
});
});
} | javascript | function(){
var options = render.options,
path = options.render = render._normalizePath( options.render );
// Ensure render path actually exists
fs.stat( path, function( e, stat ) {
if ( e || ! stat || ! stat.isDirectory() ) {
return munit.exit( 1, e, "'" + path + "' is not a directory" );
}
// Check for root munit config file
fs.exists( path + '/munit.js', function( exists ) {
if ( exists ) {
munit.require( path + '/munit.js' );
}
// Initialize all files in test path for submodule additions
render._renderPath( path, function( e ) {
if ( e ) {
return munit.exit( 1, e, "Unable to render test path" );
}
render._compile();
});
});
});
} | [
"function",
"(",
")",
"{",
"var",
"options",
"=",
"render",
".",
"options",
",",
"path",
"=",
"options",
".",
"render",
"=",
"render",
".",
"_normalizePath",
"(",
"options",
".",
"render",
")",
";",
"fs",
".",
"stat",
"(",
"path",
",",
"function",
"(",
"e",
",",
"stat",
")",
"{",
"if",
"(",
"e",
"||",
"!",
"stat",
"||",
"!",
"stat",
".",
"isDirectory",
"(",
")",
")",
"{",
"return",
"munit",
".",
"exit",
"(",
"1",
",",
"e",
",",
"\"'\"",
"+",
"path",
"+",
"\"' is not a directory\"",
")",
";",
"}",
"fs",
".",
"exists",
"(",
"path",
"+",
"'/munit.js'",
",",
"function",
"(",
"exists",
")",
"{",
"if",
"(",
"exists",
")",
"{",
"munit",
".",
"require",
"(",
"path",
"+",
"'/munit.js'",
")",
";",
"}",
"render",
".",
"_renderPath",
"(",
"path",
",",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"e",
")",
"{",
"return",
"munit",
".",
"exit",
"(",
"1",
",",
"e",
",",
"\"Unable to render test path\"",
")",
";",
"}",
"render",
".",
"_compile",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Setup for rendering a path | [
"Setup",
"for",
"rendering",
"a",
"path"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/render.js#L334-L360 | train |
|
codenothing/munit | lib/render.js | function(){
// Swap render state to compile mode for priority generation
render.requireState( munit.RENDER_STATE_READ, render._compile );
render.state = munit.RENDER_STATE_COMPILE;
render._renderNS( munit.ns );
// Just in case triggers set off any undesired state
render.requireState( munit.RENDER_STATE_COMPILE, render._compile );
render.state = munit.RENDER_STATE_TRIGGER;
// Sort modules on priority
munit.tests.sort(function( a, b ) {
if ( a.options.priority === b.options.priority ) {
return a._added > b._added ? 1 : -1;
}
else {
return a.options.priority > b.options.priority ? -1 : 1;
}
})
// Trigger modules based on priority
.forEach(function( assert ) {
// Stack modules waiting on a queue
if ( assert.options.queue ) {
munit.queue.addModule( assert );
}
else if ( render.checkDepency( assert ) ) {
assert.trigger();
}
});
// All modules triggered, check to see if we can close out
render.state = munit.RENDER_STATE_ACTIVE;
render.check();
} | javascript | function(){
// Swap render state to compile mode for priority generation
render.requireState( munit.RENDER_STATE_READ, render._compile );
render.state = munit.RENDER_STATE_COMPILE;
render._renderNS( munit.ns );
// Just in case triggers set off any undesired state
render.requireState( munit.RENDER_STATE_COMPILE, render._compile );
render.state = munit.RENDER_STATE_TRIGGER;
// Sort modules on priority
munit.tests.sort(function( a, b ) {
if ( a.options.priority === b.options.priority ) {
return a._added > b._added ? 1 : -1;
}
else {
return a.options.priority > b.options.priority ? -1 : 1;
}
})
// Trigger modules based on priority
.forEach(function( assert ) {
// Stack modules waiting on a queue
if ( assert.options.queue ) {
munit.queue.addModule( assert );
}
else if ( render.checkDepency( assert ) ) {
assert.trigger();
}
});
// All modules triggered, check to see if we can close out
render.state = munit.RENDER_STATE_ACTIVE;
render.check();
} | [
"function",
"(",
")",
"{",
"render",
".",
"requireState",
"(",
"munit",
".",
"RENDER_STATE_READ",
",",
"render",
".",
"_compile",
")",
";",
"render",
".",
"state",
"=",
"munit",
".",
"RENDER_STATE_COMPILE",
";",
"render",
".",
"_renderNS",
"(",
"munit",
".",
"ns",
")",
";",
"render",
".",
"requireState",
"(",
"munit",
".",
"RENDER_STATE_COMPILE",
",",
"render",
".",
"_compile",
")",
";",
"render",
".",
"state",
"=",
"munit",
".",
"RENDER_STATE_TRIGGER",
";",
"munit",
".",
"tests",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"if",
"(",
"a",
".",
"options",
".",
"priority",
"===",
"b",
".",
"options",
".",
"priority",
")",
"{",
"return",
"a",
".",
"_added",
">",
"b",
".",
"_added",
"?",
"1",
":",
"-",
"1",
";",
"}",
"else",
"{",
"return",
"a",
".",
"options",
".",
"priority",
">",
"b",
".",
"options",
".",
"priority",
"?",
"-",
"1",
":",
"1",
";",
"}",
"}",
")",
".",
"forEach",
"(",
"function",
"(",
"assert",
")",
"{",
"if",
"(",
"assert",
".",
"options",
".",
"queue",
")",
"{",
"munit",
".",
"queue",
".",
"addModule",
"(",
"assert",
")",
";",
"}",
"else",
"if",
"(",
"render",
".",
"checkDepency",
"(",
"assert",
")",
")",
"{",
"assert",
".",
"trigger",
"(",
")",
";",
"}",
"}",
")",
";",
"render",
".",
"state",
"=",
"munit",
".",
"RENDER_STATE_ACTIVE",
";",
"render",
".",
"check",
"(",
")",
";",
"}"
]
| Triggered after all file paths have been loaded | [
"Triggered",
"after",
"all",
"file",
"paths",
"have",
"been",
"loaded"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/render.js#L363-L396 | train |
|
codenothing/munit | lib/render.js | function(){
var color = munit.color.get[ munit.failed > 0 ? 'red' : 'green' ],
callback = render.callback;
// Can only complete a finished munit state
// (dont pass startFunc, we want _complete as part of the trace here)
render.requireState( munit.RENDER_STATE_FINISHED );
render.state = munit.RENDER_STATE_COMPLETE;
// Print out final results
munit.log([
"\n",
color( "Tests Passed: " + munit.passed ),
color( "Tests Failed: " + munit.failed ),
color( "Tests Skipped: " + munit.skipped ),
color( "Time: " + munit._relativeTime( munit.end - munit.start ) ),
"\n"
].join( "\n" ));
// Only exit if there is an error (callback will be triggered there)
if ( munit.failed > 0 ) {
munit.exit( 1, "Test failed with " + munit.failed + " errors" );
}
// Trigger callback if provided
else if ( callback ) {
render.callback = undefined;
callback( null, munit );
}
} | javascript | function(){
var color = munit.color.get[ munit.failed > 0 ? 'red' : 'green' ],
callback = render.callback;
// Can only complete a finished munit state
// (dont pass startFunc, we want _complete as part of the trace here)
render.requireState( munit.RENDER_STATE_FINISHED );
render.state = munit.RENDER_STATE_COMPLETE;
// Print out final results
munit.log([
"\n",
color( "Tests Passed: " + munit.passed ),
color( "Tests Failed: " + munit.failed ),
color( "Tests Skipped: " + munit.skipped ),
color( "Time: " + munit._relativeTime( munit.end - munit.start ) ),
"\n"
].join( "\n" ));
// Only exit if there is an error (callback will be triggered there)
if ( munit.failed > 0 ) {
munit.exit( 1, "Test failed with " + munit.failed + " errors" );
}
// Trigger callback if provided
else if ( callback ) {
render.callback = undefined;
callback( null, munit );
}
} | [
"function",
"(",
")",
"{",
"var",
"color",
"=",
"munit",
".",
"color",
".",
"get",
"[",
"munit",
".",
"failed",
">",
"0",
"?",
"'red'",
":",
"'green'",
"]",
",",
"callback",
"=",
"render",
".",
"callback",
";",
"render",
".",
"requireState",
"(",
"munit",
".",
"RENDER_STATE_FINISHED",
")",
";",
"render",
".",
"state",
"=",
"munit",
".",
"RENDER_STATE_COMPLETE",
";",
"munit",
".",
"log",
"(",
"[",
"\"\\n\"",
",",
"\\n",
",",
"color",
"(",
"\"Tests Passed: \"",
"+",
"munit",
".",
"passed",
")",
",",
"color",
"(",
"\"Tests Failed: \"",
"+",
"munit",
".",
"failed",
")",
",",
"color",
"(",
"\"Tests Skipped: \"",
"+",
"munit",
".",
"skipped",
")",
",",
"color",
"(",
"\"Time: \"",
"+",
"munit",
".",
"_relativeTime",
"(",
"munit",
".",
"end",
"-",
"munit",
".",
"start",
")",
")",
"]",
".",
"\"\\n\"",
"\\n",
")",
";",
"join",
"}"
]
| Finished off test result writing, print out suite results | [
"Finished",
"off",
"test",
"result",
"writing",
"print",
"out",
"suite",
"results"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/render.js#L399-L427 | train |
|
codenothing/munit | lib/render.js | function( dir ) {
// Make the root results directory first
render._mkdir( dir, function( e ) {
if ( e ) {
return munit.exit( 1, e, "Failed to make root results directory" );
}
// Make a working directory for each format
async.each( render._formats,
function( format, callback ) {
var path = dir + format.name + '/';
render._mkdir( path, function( e ) {
if ( e ) {
callback( e );
}
else {
format.callback( path, callback );
}
});
},
function( e ) {
if ( e ) {
munit.exit( 1, e );
}
else {
render._complete();
}
}
);
});
} | javascript | function( dir ) {
// Make the root results directory first
render._mkdir( dir, function( e ) {
if ( e ) {
return munit.exit( 1, e, "Failed to make root results directory" );
}
// Make a working directory for each format
async.each( render._formats,
function( format, callback ) {
var path = dir + format.name + '/';
render._mkdir( path, function( e ) {
if ( e ) {
callback( e );
}
else {
format.callback( path, callback );
}
});
},
function( e ) {
if ( e ) {
munit.exit( 1, e );
}
else {
render._complete();
}
}
);
});
} | [
"function",
"(",
"dir",
")",
"{",
"render",
".",
"_mkdir",
"(",
"dir",
",",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"e",
")",
"{",
"return",
"munit",
".",
"exit",
"(",
"1",
",",
"e",
",",
"\"Failed to make root results directory\"",
")",
";",
"}",
"async",
".",
"each",
"(",
"render",
".",
"_formats",
",",
"function",
"(",
"format",
",",
"callback",
")",
"{",
"var",
"path",
"=",
"dir",
"+",
"format",
".",
"name",
"+",
"'/'",
";",
"render",
".",
"_mkdir",
"(",
"path",
",",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"e",
")",
"{",
"callback",
"(",
"e",
")",
";",
"}",
"else",
"{",
"format",
".",
"callback",
"(",
"path",
",",
"callback",
")",
";",
"}",
"}",
")",
";",
"}",
",",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"e",
")",
"{",
"munit",
".",
"exit",
"(",
"1",
",",
"e",
")",
";",
"}",
"else",
"{",
"render",
".",
"_complete",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Generates result directories | [
"Generates",
"result",
"directories"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/render.js#L430-L461 | train |
|
codenothing/munit | lib/render.js | function(){
var finished = true,
now = Date.now(),
options = render.options,
results = options.results ? render._normalizePath( options.results ) : null;
// Wait until all modules have been triggered before checking states
if ( render.state < munit.RENDER_STATE_ACTIVE ) {
return;
}
// Can only check an active munit
render.requireState( munit.RENDER_STATE_ACTIVE, render.check );
// Check each module
munit.each( munit.ns, function( mod, name ) {
if ( mod.state < munit.ASSERT_STATE_FINISHED ) {
return ( finished = false );
}
});
// Check dependency chains if test suite isn't yet finished
if ( ! finished ) {
munit.queue.check();
// Check each untriggered module to see if it's dependencies have been closed
munit.tests.forEach(function( assert ) {
if ( assert.state === munit.ASSERT_STATE_DEFAULT && ! assert.option( 'queue' ) && render.checkDepency( assert ) ) {
assert.trigger();
}
});
}
// Only flush full results once all modules have completed
else {
render.state = munit.RENDER_STATE_FINISHED;
munit.end = now;
// Print out test results
if ( results && results.length ) {
render._renderResults( results + '/' );
}
else {
render._complete();
}
}
} | javascript | function(){
var finished = true,
now = Date.now(),
options = render.options,
results = options.results ? render._normalizePath( options.results ) : null;
// Wait until all modules have been triggered before checking states
if ( render.state < munit.RENDER_STATE_ACTIVE ) {
return;
}
// Can only check an active munit
render.requireState( munit.RENDER_STATE_ACTIVE, render.check );
// Check each module
munit.each( munit.ns, function( mod, name ) {
if ( mod.state < munit.ASSERT_STATE_FINISHED ) {
return ( finished = false );
}
});
// Check dependency chains if test suite isn't yet finished
if ( ! finished ) {
munit.queue.check();
// Check each untriggered module to see if it's dependencies have been closed
munit.tests.forEach(function( assert ) {
if ( assert.state === munit.ASSERT_STATE_DEFAULT && ! assert.option( 'queue' ) && render.checkDepency( assert ) ) {
assert.trigger();
}
});
}
// Only flush full results once all modules have completed
else {
render.state = munit.RENDER_STATE_FINISHED;
munit.end = now;
// Print out test results
if ( results && results.length ) {
render._renderResults( results + '/' );
}
else {
render._complete();
}
}
} | [
"function",
"(",
")",
"{",
"var",
"finished",
"=",
"true",
",",
"now",
"=",
"Date",
".",
"now",
"(",
")",
",",
"options",
"=",
"render",
".",
"options",
",",
"results",
"=",
"options",
".",
"results",
"?",
"render",
".",
"_normalizePath",
"(",
"options",
".",
"results",
")",
":",
"null",
";",
"if",
"(",
"render",
".",
"state",
"<",
"munit",
".",
"RENDER_STATE_ACTIVE",
")",
"{",
"return",
";",
"}",
"render",
".",
"requireState",
"(",
"munit",
".",
"RENDER_STATE_ACTIVE",
",",
"render",
".",
"check",
")",
";",
"munit",
".",
"each",
"(",
"munit",
".",
"ns",
",",
"function",
"(",
"mod",
",",
"name",
")",
"{",
"if",
"(",
"mod",
".",
"state",
"<",
"munit",
".",
"ASSERT_STATE_FINISHED",
")",
"{",
"return",
"(",
"finished",
"=",
"false",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"!",
"finished",
")",
"{",
"munit",
".",
"queue",
".",
"check",
"(",
")",
";",
"munit",
".",
"tests",
".",
"forEach",
"(",
"function",
"(",
"assert",
")",
"{",
"if",
"(",
"assert",
".",
"state",
"===",
"munit",
".",
"ASSERT_STATE_DEFAULT",
"&&",
"!",
"assert",
".",
"option",
"(",
"'queue'",
")",
"&&",
"render",
".",
"checkDepency",
"(",
"assert",
")",
")",
"{",
"assert",
".",
"trigger",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"render",
".",
"state",
"=",
"munit",
".",
"RENDER_STATE_FINISHED",
";",
"munit",
".",
"end",
"=",
"now",
";",
"if",
"(",
"results",
"&&",
"results",
".",
"length",
")",
"{",
"render",
".",
"_renderResults",
"(",
"results",
"+",
"'/'",
")",
";",
"}",
"else",
"{",
"render",
".",
"_complete",
"(",
")",
";",
"}",
"}",
"}"
]
| Checks all modules to see if they are finished | [
"Checks",
"all",
"modules",
"to",
"see",
"if",
"they",
"are",
"finished"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/render.js#L464-L509 | train |
|
mgesmundo/authorify-client | build/authorify.js | function(api, id, key, data) {
// get storage object
var obj = _getStorageObject(api, id);
if(obj === null) {
// create a new storage object
obj = {};
}
// update key
obj[key] = data;
// set storage object
_setStorageObject(api, id, obj);
} | javascript | function(api, id, key, data) {
// get storage object
var obj = _getStorageObject(api, id);
if(obj === null) {
// create a new storage object
obj = {};
}
// update key
obj[key] = data;
// set storage object
_setStorageObject(api, id, obj);
} | [
"function",
"(",
"api",
",",
"id",
",",
"key",
",",
"data",
")",
"{",
"var",
"obj",
"=",
"_getStorageObject",
"(",
"api",
",",
"id",
")",
";",
"if",
"(",
"obj",
"===",
"null",
")",
"{",
"obj",
"=",
"{",
"}",
";",
"}",
"obj",
"[",
"key",
"]",
"=",
"data",
";",
"_setStorageObject",
"(",
"api",
",",
"id",
",",
"obj",
")",
";",
"}"
]
| Stores an item in local storage.
@param api the storage interface.
@param id the storage ID to use.
@param key the key for the item.
@param data the data for the item (any javascript object/primitive). | [
"Stores",
"an",
"item",
"in",
"local",
"storage",
"."
]
| 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/build/authorify.js#L1420-L1432 | train |
|
mgesmundo/authorify-client | build/authorify.js | function(api, id, key) {
// get storage object
var rval = _getStorageObject(api, id);
if(rval !== null) {
// return data at key
rval = (key in rval) ? rval[key] : null;
}
return rval;
} | javascript | function(api, id, key) {
// get storage object
var rval = _getStorageObject(api, id);
if(rval !== null) {
// return data at key
rval = (key in rval) ? rval[key] : null;
}
return rval;
} | [
"function",
"(",
"api",
",",
"id",
",",
"key",
")",
"{",
"var",
"rval",
"=",
"_getStorageObject",
"(",
"api",
",",
"id",
")",
";",
"if",
"(",
"rval",
"!==",
"null",
")",
"{",
"rval",
"=",
"(",
"key",
"in",
"rval",
")",
"?",
"rval",
"[",
"key",
"]",
":",
"null",
";",
"}",
"return",
"rval",
";",
"}"
]
| Gets an item from local storage.
@param api the storage interface.
@param id the storage ID to use.
@param key the key for the item.
@return the item. | [
"Gets",
"an",
"item",
"from",
"local",
"storage",
"."
]
| 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/build/authorify.js#L1443-L1452 | train |
|
mgesmundo/authorify-client | build/authorify.js | function(api, id, key) {
// get storage object
var obj = _getStorageObject(api, id);
if(obj !== null && key in obj) {
// remove key
delete obj[key];
// see if entry has no keys remaining
var empty = true;
for(var prop in obj) {
empty = false;
break;
}
if(empty) {
// remove entry entirely if no keys are left
obj = null;
}
// set storage object
_setStorageObject(api, id, obj);
}
} | javascript | function(api, id, key) {
// get storage object
var obj = _getStorageObject(api, id);
if(obj !== null && key in obj) {
// remove key
delete obj[key];
// see if entry has no keys remaining
var empty = true;
for(var prop in obj) {
empty = false;
break;
}
if(empty) {
// remove entry entirely if no keys are left
obj = null;
}
// set storage object
_setStorageObject(api, id, obj);
}
} | [
"function",
"(",
"api",
",",
"id",
",",
"key",
")",
"{",
"var",
"obj",
"=",
"_getStorageObject",
"(",
"api",
",",
"id",
")",
";",
"if",
"(",
"obj",
"!==",
"null",
"&&",
"key",
"in",
"obj",
")",
"{",
"delete",
"obj",
"[",
"key",
"]",
";",
"var",
"empty",
"=",
"true",
";",
"for",
"(",
"var",
"prop",
"in",
"obj",
")",
"{",
"empty",
"=",
"false",
";",
"break",
";",
"}",
"if",
"(",
"empty",
")",
"{",
"obj",
"=",
"null",
";",
"}",
"_setStorageObject",
"(",
"api",
",",
"id",
",",
"obj",
")",
";",
"}",
"}"
]
| Removes an item from local storage.
@param api the storage interface.
@param id the storage ID to use.
@param key the key for the item. | [
"Removes",
"an",
"item",
"from",
"local",
"storage",
"."
]
| 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/build/authorify.js#L1461-L1482 | train |
|
mgesmundo/authorify-client | build/authorify.js | function(func, args, location) {
var rval = null;
// default storage types
if(typeof(location) === 'undefined') {
location = ['web', 'flash'];
}
// apply storage types in order of preference
var type;
var done = false;
var exception = null;
for(var idx in location) {
type = location[idx];
try {
if(type === 'flash' || type === 'both') {
if(args[0] === null) {
throw new Error('Flash local storage not available.');
} else {
rval = func.apply(this, args);
done = (type === 'flash');
}
}
if(type === 'web' || type === 'both') {
args[0] = localStorage;
rval = func.apply(this, args);
done = true;
}
} catch(ex) {
exception = ex;
}
if(done) {
break;
}
}
if(!done) {
throw exception;
}
return rval;
} | javascript | function(func, args, location) {
var rval = null;
// default storage types
if(typeof(location) === 'undefined') {
location = ['web', 'flash'];
}
// apply storage types in order of preference
var type;
var done = false;
var exception = null;
for(var idx in location) {
type = location[idx];
try {
if(type === 'flash' || type === 'both') {
if(args[0] === null) {
throw new Error('Flash local storage not available.');
} else {
rval = func.apply(this, args);
done = (type === 'flash');
}
}
if(type === 'web' || type === 'both') {
args[0] = localStorage;
rval = func.apply(this, args);
done = true;
}
} catch(ex) {
exception = ex;
}
if(done) {
break;
}
}
if(!done) {
throw exception;
}
return rval;
} | [
"function",
"(",
"func",
",",
"args",
",",
"location",
")",
"{",
"var",
"rval",
"=",
"null",
";",
"if",
"(",
"typeof",
"(",
"location",
")",
"===",
"'undefined'",
")",
"{",
"location",
"=",
"[",
"'web'",
",",
"'flash'",
"]",
";",
"}",
"var",
"type",
";",
"var",
"done",
"=",
"false",
";",
"var",
"exception",
"=",
"null",
";",
"for",
"(",
"var",
"idx",
"in",
"location",
")",
"{",
"type",
"=",
"location",
"[",
"idx",
"]",
";",
"try",
"{",
"if",
"(",
"type",
"===",
"'flash'",
"||",
"type",
"===",
"'both'",
")",
"{",
"if",
"(",
"args",
"[",
"0",
"]",
"===",
"null",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Flash local storage not available.'",
")",
";",
"}",
"else",
"{",
"rval",
"=",
"func",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"done",
"=",
"(",
"type",
"===",
"'flash'",
")",
";",
"}",
"}",
"if",
"(",
"type",
"===",
"'web'",
"||",
"type",
"===",
"'both'",
")",
"{",
"args",
"[",
"0",
"]",
"=",
"localStorage",
";",
"rval",
"=",
"func",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"done",
"=",
"true",
";",
"}",
"}",
"catch",
"(",
"ex",
")",
"{",
"exception",
"=",
"ex",
";",
"}",
"if",
"(",
"done",
")",
"{",
"break",
";",
"}",
"}",
"if",
"(",
"!",
"done",
")",
"{",
"throw",
"exception",
";",
"}",
"return",
"rval",
";",
"}"
]
| Calls a storage function.
@param func the function to call.
@param args the arguments for the function.
@param location the location argument.
@return the return value from the function. | [
"Calls",
"a",
"storage",
"function",
"."
]
| 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/build/authorify.js#L1503-L1544 | train |
|
mgesmundo/authorify-client | build/authorify.js | function(b) {
var b2 = b.getByte();
if(b2 === 0x80) {
return undefined;
}
// see if the length is "short form" or "long form" (bit 8 set)
var length;
var longForm = b2 & 0x80;
if(!longForm) {
// length is just the first byte
length = b2;
} else {
// the number of bytes the length is specified in bits 7 through 1
// and each length byte is in big-endian base-256
length = b.getInt((b2 & 0x7F) << 3);
}
return length;
} | javascript | function(b) {
var b2 = b.getByte();
if(b2 === 0x80) {
return undefined;
}
// see if the length is "short form" or "long form" (bit 8 set)
var length;
var longForm = b2 & 0x80;
if(!longForm) {
// length is just the first byte
length = b2;
} else {
// the number of bytes the length is specified in bits 7 through 1
// and each length byte is in big-endian base-256
length = b.getInt((b2 & 0x7F) << 3);
}
return length;
} | [
"function",
"(",
"b",
")",
"{",
"var",
"b2",
"=",
"b",
".",
"getByte",
"(",
")",
";",
"if",
"(",
"b2",
"===",
"0x80",
")",
"{",
"return",
"undefined",
";",
"}",
"var",
"length",
";",
"var",
"longForm",
"=",
"b2",
"&",
"0x80",
";",
"if",
"(",
"!",
"longForm",
")",
"{",
"length",
"=",
"b2",
";",
"}",
"else",
"{",
"length",
"=",
"b",
".",
"getInt",
"(",
"(",
"b2",
"&",
"0x7F",
")",
"<<",
"3",
")",
";",
"}",
"return",
"length",
";",
"}"
]
| Gets the length of an ASN.1 value.
In case the length is not specified, undefined is returned.
@param b the ASN.1 byte buffer.
@return the length of the ASN.1 value. | [
"Gets",
"the",
"length",
"of",
"an",
"ASN",
".",
"1",
"value",
"."
]
| 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/build/authorify.js#L5142-L5160 | train |
|
mgesmundo/authorify-client | build/authorify.js | _reseedSync | function _reseedSync() {
if(ctx.pools[0].messageLength >= 32) {
return _seed();
}
// not enough seed data...
var needed = (32 - ctx.pools[0].messageLength) << 5;
ctx.collect(ctx.seedFileSync(needed));
_seed();
} | javascript | function _reseedSync() {
if(ctx.pools[0].messageLength >= 32) {
return _seed();
}
// not enough seed data...
var needed = (32 - ctx.pools[0].messageLength) << 5;
ctx.collect(ctx.seedFileSync(needed));
_seed();
} | [
"function",
"_reseedSync",
"(",
")",
"{",
"if",
"(",
"ctx",
".",
"pools",
"[",
"0",
"]",
".",
"messageLength",
">=",
"32",
")",
"{",
"return",
"_seed",
"(",
")",
";",
"}",
"var",
"needed",
"=",
"(",
"32",
"-",
"ctx",
".",
"pools",
"[",
"0",
"]",
".",
"messageLength",
")",
"<<",
"5",
";",
"ctx",
".",
"collect",
"(",
"ctx",
".",
"seedFileSync",
"(",
"needed",
")",
")",
";",
"_seed",
"(",
")",
";",
"}"
]
| Private function that synchronously reseeds a generator. | [
"Private",
"function",
"that",
"synchronously",
"reseeds",
"a",
"generator",
"."
]
| 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/build/authorify.js#L9113-L9121 | train |
mgesmundo/authorify-client | build/authorify.js | _seed | function _seed() {
// create a plugin-based message digest
var md = ctx.plugin.md.create();
// digest pool 0's entropy and restart it
md.update(ctx.pools[0].digest().getBytes());
ctx.pools[0].start();
// digest the entropy of other pools whose index k meet the
// condition '2^k mod n == 0' where n is the number of reseeds
var k = 1;
for(var i = 1; i < 32; ++i) {
// prevent signed numbers from being used
k = (k === 31) ? 0x80000000 : (k << 2);
if(k % ctx.reseeds === 0) {
md.update(ctx.pools[i].digest().getBytes());
ctx.pools[i].start();
}
}
// get digest for key bytes and iterate again for seed bytes
var keyBytes = md.digest().getBytes();
md.start();
md.update(keyBytes);
var seedBytes = md.digest().getBytes();
// update
ctx.key = ctx.plugin.formatKey(keyBytes);
ctx.seed = ctx.plugin.formatSeed(seedBytes);
ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1;
ctx.generated = 0;
} | javascript | function _seed() {
// create a plugin-based message digest
var md = ctx.plugin.md.create();
// digest pool 0's entropy and restart it
md.update(ctx.pools[0].digest().getBytes());
ctx.pools[0].start();
// digest the entropy of other pools whose index k meet the
// condition '2^k mod n == 0' where n is the number of reseeds
var k = 1;
for(var i = 1; i < 32; ++i) {
// prevent signed numbers from being used
k = (k === 31) ? 0x80000000 : (k << 2);
if(k % ctx.reseeds === 0) {
md.update(ctx.pools[i].digest().getBytes());
ctx.pools[i].start();
}
}
// get digest for key bytes and iterate again for seed bytes
var keyBytes = md.digest().getBytes();
md.start();
md.update(keyBytes);
var seedBytes = md.digest().getBytes();
// update
ctx.key = ctx.plugin.formatKey(keyBytes);
ctx.seed = ctx.plugin.formatSeed(seedBytes);
ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1;
ctx.generated = 0;
} | [
"function",
"_seed",
"(",
")",
"{",
"var",
"md",
"=",
"ctx",
".",
"plugin",
".",
"md",
".",
"create",
"(",
")",
";",
"md",
".",
"update",
"(",
"ctx",
".",
"pools",
"[",
"0",
"]",
".",
"digest",
"(",
")",
".",
"getBytes",
"(",
")",
")",
";",
"ctx",
".",
"pools",
"[",
"0",
"]",
".",
"start",
"(",
")",
";",
"var",
"k",
"=",
"1",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"32",
";",
"++",
"i",
")",
"{",
"k",
"=",
"(",
"k",
"===",
"31",
")",
"?",
"0x80000000",
":",
"(",
"k",
"<<",
"2",
")",
";",
"if",
"(",
"k",
"%",
"ctx",
".",
"reseeds",
"===",
"0",
")",
"{",
"md",
".",
"update",
"(",
"ctx",
".",
"pools",
"[",
"i",
"]",
".",
"digest",
"(",
")",
".",
"getBytes",
"(",
")",
")",
";",
"ctx",
".",
"pools",
"[",
"i",
"]",
".",
"start",
"(",
")",
";",
"}",
"}",
"var",
"keyBytes",
"=",
"md",
".",
"digest",
"(",
")",
".",
"getBytes",
"(",
")",
";",
"md",
".",
"start",
"(",
")",
";",
"md",
".",
"update",
"(",
"keyBytes",
")",
";",
"var",
"seedBytes",
"=",
"md",
".",
"digest",
"(",
")",
".",
"getBytes",
"(",
")",
";",
"ctx",
".",
"key",
"=",
"ctx",
".",
"plugin",
".",
"formatKey",
"(",
"keyBytes",
")",
";",
"ctx",
".",
"seed",
"=",
"ctx",
".",
"plugin",
".",
"formatSeed",
"(",
"seedBytes",
")",
";",
"ctx",
".",
"reseeds",
"=",
"(",
"ctx",
".",
"reseeds",
"===",
"0xffffffff",
")",
"?",
"0",
":",
"ctx",
".",
"reseeds",
"+",
"1",
";",
"ctx",
".",
"generated",
"=",
"0",
";",
"}"
]
| Private function that seeds a generator once enough bytes are available. | [
"Private",
"function",
"that",
"seeds",
"a",
"generator",
"once",
"enough",
"bytes",
"are",
"available",
"."
]
| 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/build/authorify.js#L9126-L9157 | train |
mgesmundo/authorify-client | build/authorify.js | defaultSeedFile | function defaultSeedFile(needed) {
// use window.crypto.getRandomValues strong source of entropy if available
var getRandomValues = null;
if(typeof window !== 'undefined') {
var _crypto = window.crypto || window.msCrypto;
if(_crypto && _crypto.getRandomValues) {
getRandomValues = function(arr) {
return _crypto.getRandomValues(arr);
};
}
}
var b = forge.util.createBuffer();
if(getRandomValues) {
while(b.length() < needed) {
// max byte length is 65536 before QuotaExceededError is thrown
// http://www.w3.org/TR/WebCryptoAPI/#RandomSource-method-getRandomValues
var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4);
var entropy = new Uint32Array(Math.floor(count));
try {
getRandomValues(entropy);
for(var i = 0; i < entropy.length; ++i) {
b.putInt32(entropy[i]);
}
} catch(e) {
/* only ignore QuotaExceededError */
if(!(typeof QuotaExceededError !== 'undefined' &&
e instanceof QuotaExceededError)) {
throw e;
}
}
}
}
// be sad and add some weak random data
if(b.length() < needed) {
/* Draws from Park-Miller "minimal standard" 31 bit PRNG,
implemented with David G. Carta's optimization: with 32 bit math
and without division (Public Domain). */
var hi, lo, next;
var seed = Math.floor(Math.random() * 0x010000);
while(b.length() < needed) {
lo = 16807 * (seed & 0xFFFF);
hi = 16807 * (seed >> 16);
lo += (hi & 0x7FFF) << 16;
lo += hi >> 15;
lo = (lo & 0x7FFFFFFF) + (lo >> 31);
seed = lo & 0xFFFFFFFF;
// consume lower 3 bytes of seed
for(var i = 0; i < 3; ++i) {
// throw in more pseudo random
next = seed >>> (i << 3);
next ^= Math.floor(Math.random() * 0x0100);
b.putByte(String.fromCharCode(next & 0xFF));
}
}
}
return b.getBytes(needed);
} | javascript | function defaultSeedFile(needed) {
// use window.crypto.getRandomValues strong source of entropy if available
var getRandomValues = null;
if(typeof window !== 'undefined') {
var _crypto = window.crypto || window.msCrypto;
if(_crypto && _crypto.getRandomValues) {
getRandomValues = function(arr) {
return _crypto.getRandomValues(arr);
};
}
}
var b = forge.util.createBuffer();
if(getRandomValues) {
while(b.length() < needed) {
// max byte length is 65536 before QuotaExceededError is thrown
// http://www.w3.org/TR/WebCryptoAPI/#RandomSource-method-getRandomValues
var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4);
var entropy = new Uint32Array(Math.floor(count));
try {
getRandomValues(entropy);
for(var i = 0; i < entropy.length; ++i) {
b.putInt32(entropy[i]);
}
} catch(e) {
/* only ignore QuotaExceededError */
if(!(typeof QuotaExceededError !== 'undefined' &&
e instanceof QuotaExceededError)) {
throw e;
}
}
}
}
// be sad and add some weak random data
if(b.length() < needed) {
/* Draws from Park-Miller "minimal standard" 31 bit PRNG,
implemented with David G. Carta's optimization: with 32 bit math
and without division (Public Domain). */
var hi, lo, next;
var seed = Math.floor(Math.random() * 0x010000);
while(b.length() < needed) {
lo = 16807 * (seed & 0xFFFF);
hi = 16807 * (seed >> 16);
lo += (hi & 0x7FFF) << 16;
lo += hi >> 15;
lo = (lo & 0x7FFFFFFF) + (lo >> 31);
seed = lo & 0xFFFFFFFF;
// consume lower 3 bytes of seed
for(var i = 0; i < 3; ++i) {
// throw in more pseudo random
next = seed >>> (i << 3);
next ^= Math.floor(Math.random() * 0x0100);
b.putByte(String.fromCharCode(next & 0xFF));
}
}
}
return b.getBytes(needed);
} | [
"function",
"defaultSeedFile",
"(",
"needed",
")",
"{",
"var",
"getRandomValues",
"=",
"null",
";",
"if",
"(",
"typeof",
"window",
"!==",
"'undefined'",
")",
"{",
"var",
"_crypto",
"=",
"window",
".",
"crypto",
"||",
"window",
".",
"msCrypto",
";",
"if",
"(",
"_crypto",
"&&",
"_crypto",
".",
"getRandomValues",
")",
"{",
"getRandomValues",
"=",
"function",
"(",
"arr",
")",
"{",
"return",
"_crypto",
".",
"getRandomValues",
"(",
"arr",
")",
";",
"}",
";",
"}",
"}",
"var",
"b",
"=",
"forge",
".",
"util",
".",
"createBuffer",
"(",
")",
";",
"if",
"(",
"getRandomValues",
")",
"{",
"while",
"(",
"b",
".",
"length",
"(",
")",
"<",
"needed",
")",
"{",
"var",
"count",
"=",
"Math",
".",
"max",
"(",
"1",
",",
"Math",
".",
"min",
"(",
"needed",
"-",
"b",
".",
"length",
"(",
")",
",",
"65536",
")",
"/",
"4",
")",
";",
"var",
"entropy",
"=",
"new",
"Uint32Array",
"(",
"Math",
".",
"floor",
"(",
"count",
")",
")",
";",
"try",
"{",
"getRandomValues",
"(",
"entropy",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"entropy",
".",
"length",
";",
"++",
"i",
")",
"{",
"b",
".",
"putInt32",
"(",
"entropy",
"[",
"i",
"]",
")",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"!",
"(",
"typeof",
"QuotaExceededError",
"!==",
"'undefined'",
"&&",
"e",
"instanceof",
"QuotaExceededError",
")",
")",
"{",
"throw",
"e",
";",
"}",
"}",
"}",
"}",
"if",
"(",
"b",
".",
"length",
"(",
")",
"<",
"needed",
")",
"{",
"var",
"hi",
",",
"lo",
",",
"next",
";",
"var",
"seed",
"=",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"0x010000",
")",
";",
"while",
"(",
"b",
".",
"length",
"(",
")",
"<",
"needed",
")",
"{",
"lo",
"=",
"16807",
"*",
"(",
"seed",
"&",
"0xFFFF",
")",
";",
"hi",
"=",
"16807",
"*",
"(",
"seed",
">>",
"16",
")",
";",
"lo",
"+=",
"(",
"hi",
"&",
"0x7FFF",
")",
"<<",
"16",
";",
"lo",
"+=",
"hi",
">>",
"15",
";",
"lo",
"=",
"(",
"lo",
"&",
"0x7FFFFFFF",
")",
"+",
"(",
"lo",
">>",
"31",
")",
";",
"seed",
"=",
"lo",
"&",
"0xFFFFFFFF",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"3",
";",
"++",
"i",
")",
"{",
"next",
"=",
"seed",
">>>",
"(",
"i",
"<<",
"3",
")",
";",
"next",
"^=",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"0x0100",
")",
";",
"b",
".",
"putByte",
"(",
"String",
".",
"fromCharCode",
"(",
"next",
"&",
"0xFF",
")",
")",
";",
"}",
"}",
"}",
"return",
"b",
".",
"getBytes",
"(",
"needed",
")",
";",
"}"
]
| The built-in default seedFile. This seedFile is used when entropy
is needed immediately.
@param needed the number of bytes that are needed.
@return the random bytes. | [
"The",
"built",
"-",
"in",
"default",
"seedFile",
".",
"This",
"seedFile",
"is",
"used",
"when",
"entropy",
"is",
"needed",
"immediately",
"."
]
| 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/build/authorify.js#L9167-L9227 | train |
mgesmundo/authorify-client | build/authorify.js | spawnPrng | function spawnPrng() {
var ctx = forge.prng.create(prng_aes);
/**
* Gets random bytes. If a native secure crypto API is unavailable, this
* method tries to make the bytes more unpredictable by drawing from data that
* can be collected from the user of the browser, eg: mouse movement.
*
* If a callback is given, this method will be called asynchronously.
*
* @param count the number of random bytes to get.
* @param [callback(err, bytes)] called once the operation completes.
*
* @return the random bytes in a string.
*/
ctx.getBytes = function(count, callback) {
return ctx.generate(count, callback);
};
/**
* Gets random bytes asynchronously. If a native secure crypto API is
* unavailable, this method tries to make the bytes more unpredictable by
* drawing from data that can be collected from the user of the browser,
* eg: mouse movement.
*
* @param count the number of random bytes to get.
*
* @return the random bytes in a string.
*/
ctx.getBytesSync = function(count) {
return ctx.generate(count);
};
return ctx;
} | javascript | function spawnPrng() {
var ctx = forge.prng.create(prng_aes);
/**
* Gets random bytes. If a native secure crypto API is unavailable, this
* method tries to make the bytes more unpredictable by drawing from data that
* can be collected from the user of the browser, eg: mouse movement.
*
* If a callback is given, this method will be called asynchronously.
*
* @param count the number of random bytes to get.
* @param [callback(err, bytes)] called once the operation completes.
*
* @return the random bytes in a string.
*/
ctx.getBytes = function(count, callback) {
return ctx.generate(count, callback);
};
/**
* Gets random bytes asynchronously. If a native secure crypto API is
* unavailable, this method tries to make the bytes more unpredictable by
* drawing from data that can be collected from the user of the browser,
* eg: mouse movement.
*
* @param count the number of random bytes to get.
*
* @return the random bytes in a string.
*/
ctx.getBytesSync = function(count) {
return ctx.generate(count);
};
return ctx;
} | [
"function",
"spawnPrng",
"(",
")",
"{",
"var",
"ctx",
"=",
"forge",
".",
"prng",
".",
"create",
"(",
"prng_aes",
")",
";",
"ctx",
".",
"getBytes",
"=",
"function",
"(",
"count",
",",
"callback",
")",
"{",
"return",
"ctx",
".",
"generate",
"(",
"count",
",",
"callback",
")",
";",
"}",
";",
"ctx",
".",
"getBytesSync",
"=",
"function",
"(",
"count",
")",
"{",
"return",
"ctx",
".",
"generate",
"(",
"count",
")",
";",
"}",
";",
"return",
"ctx",
";",
"}"
]
| Creates a new PRNG. | [
"Creates",
"a",
"new",
"PRNG",
"."
]
| 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/build/authorify.js#L9447-L9481 | train |
mgesmundo/authorify-client | build/authorify.js | function(plan) {
var R = [];
/* Get data from input buffer and fill the four words into R */
for(i = 0; i < 4; i ++) {
var val = _input.getInt16Le();
if(_iv !== null) {
if(encrypt) {
/* We're encrypting, apply the IV first. */
val ^= _iv.getInt16Le();
} else {
/* We're decryption, keep cipher text for next block. */
_iv.putInt16Le(val);
}
}
R.push(val & 0xffff);
}
/* Reset global "j" variable as per spec. */
j = encrypt ? 0 : 63;
/* Run execution plan. */
for(var ptr = 0; ptr < plan.length; ptr ++) {
for(var ctr = 0; ctr < plan[ptr][0]; ctr ++) {
plan[ptr][1](R);
}
}
/* Write back result to output buffer. */
for(i = 0; i < 4; i ++) {
if(_iv !== null) {
if(encrypt) {
/* We're encrypting in CBC-mode, feed back encrypted bytes into
IV buffer to carry it forward to next block. */
_iv.putInt16Le(R[i]);
} else {
R[i] ^= _iv.getInt16Le();
}
}
_output.putInt16Le(R[i]);
}
} | javascript | function(plan) {
var R = [];
/* Get data from input buffer and fill the four words into R */
for(i = 0; i < 4; i ++) {
var val = _input.getInt16Le();
if(_iv !== null) {
if(encrypt) {
/* We're encrypting, apply the IV first. */
val ^= _iv.getInt16Le();
} else {
/* We're decryption, keep cipher text for next block. */
_iv.putInt16Le(val);
}
}
R.push(val & 0xffff);
}
/* Reset global "j" variable as per spec. */
j = encrypt ? 0 : 63;
/* Run execution plan. */
for(var ptr = 0; ptr < plan.length; ptr ++) {
for(var ctr = 0; ctr < plan[ptr][0]; ctr ++) {
plan[ptr][1](R);
}
}
/* Write back result to output buffer. */
for(i = 0; i < 4; i ++) {
if(_iv !== null) {
if(encrypt) {
/* We're encrypting in CBC-mode, feed back encrypted bytes into
IV buffer to carry it forward to next block. */
_iv.putInt16Le(R[i]);
} else {
R[i] ^= _iv.getInt16Le();
}
}
_output.putInt16Le(R[i]);
}
} | [
"function",
"(",
"plan",
")",
"{",
"var",
"R",
"=",
"[",
"]",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"4",
";",
"i",
"++",
")",
"{",
"var",
"val",
"=",
"_input",
".",
"getInt16Le",
"(",
")",
";",
"if",
"(",
"_iv",
"!==",
"null",
")",
"{",
"if",
"(",
"encrypt",
")",
"{",
"val",
"^=",
"_iv",
".",
"getInt16Le",
"(",
")",
";",
"}",
"else",
"{",
"_iv",
".",
"putInt16Le",
"(",
"val",
")",
";",
"}",
"}",
"R",
".",
"push",
"(",
"val",
"&",
"0xffff",
")",
";",
"}",
"j",
"=",
"encrypt",
"?",
"0",
":",
"63",
";",
"for",
"(",
"var",
"ptr",
"=",
"0",
";",
"ptr",
"<",
"plan",
".",
"length",
";",
"ptr",
"++",
")",
"{",
"for",
"(",
"var",
"ctr",
"=",
"0",
";",
"ctr",
"<",
"plan",
"[",
"ptr",
"]",
"[",
"0",
"]",
";",
"ctr",
"++",
")",
"{",
"plan",
"[",
"ptr",
"]",
"[",
"1",
"]",
"(",
"R",
")",
";",
"}",
"}",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"4",
";",
"i",
"++",
")",
"{",
"if",
"(",
"_iv",
"!==",
"null",
")",
"{",
"if",
"(",
"encrypt",
")",
"{",
"_iv",
".",
"putInt16Le",
"(",
"R",
"[",
"i",
"]",
")",
";",
"}",
"else",
"{",
"R",
"[",
"i",
"]",
"^=",
"_iv",
".",
"getInt16Le",
"(",
")",
";",
"}",
"}",
"_output",
".",
"putInt16Le",
"(",
"R",
"[",
"i",
"]",
")",
";",
"}",
"}"
]
| Run the specified cipher execution plan.
This function takes four words from the input buffer, applies the IV on
it (if requested) and runs the provided execution plan.
The plan must be put together in form of a array of arrays. Where the
outer one is simply a list of steps to perform and the inner one needs
to have two elements: the first one telling how many rounds to perform,
the second one telling what to do (i.e. the function to call).
@param {Array} plan The plan to execute. | [
"Run",
"the",
"specified",
"cipher",
"execution",
"plan",
"."
]
| 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/build/authorify.js#L9803-L9847 | train |
|
mgesmundo/authorify-client | build/authorify.js | function(input) {
if(!_finish) {
// not finishing, so fill the input buffer with more input
_input.putBuffer(input);
}
while(_input.length() >= 8) {
runPlan([
[ 5, mixRound ],
[ 1, mashRound ],
[ 6, mixRound ],
[ 1, mashRound ],
[ 5, mixRound ]
]);
}
} | javascript | function(input) {
if(!_finish) {
// not finishing, so fill the input buffer with more input
_input.putBuffer(input);
}
while(_input.length() >= 8) {
runPlan([
[ 5, mixRound ],
[ 1, mashRound ],
[ 6, mixRound ],
[ 1, mashRound ],
[ 5, mixRound ]
]);
}
} | [
"function",
"(",
"input",
")",
"{",
"if",
"(",
"!",
"_finish",
")",
"{",
"_input",
".",
"putBuffer",
"(",
"input",
")",
";",
"}",
"while",
"(",
"_input",
".",
"length",
"(",
")",
">=",
"8",
")",
"{",
"runPlan",
"(",
"[",
"[",
"5",
",",
"mixRound",
"]",
",",
"[",
"1",
",",
"mashRound",
"]",
",",
"[",
"6",
",",
"mixRound",
"]",
",",
"[",
"1",
",",
"mashRound",
"]",
",",
"[",
"5",
",",
"mixRound",
"]",
"]",
")",
";",
"}",
"}"
]
| Updates the next block.
@param input the buffer to read from. | [
"Updates",
"the",
"next",
"block",
"."
]
| 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/build/authorify.js#L9884-L9899 | train |
|
mgesmundo/authorify-client | build/authorify.js | function(pad) {
var rval = true;
if(encrypt) {
if(pad) {
rval = pad(8, _input, !encrypt);
} else {
// add PKCS#7 padding to block (each pad byte is the
// value of the number of pad bytes)
var padding = (_input.length() === 8) ? 8 : (8 - _input.length());
_input.fillWithByte(padding, padding);
}
}
if(rval) {
// do final update
_finish = true;
cipher.update();
}
if(!encrypt) {
// check for error: input data not a multiple of block size
rval = (_input.length() === 0);
if(rval) {
if(pad) {
rval = pad(8, _output, !encrypt);
} else {
// ensure padding byte count is valid
var len = _output.length();
var count = _output.at(len - 1);
if(count > len) {
rval = false;
} else {
// trim off padding bytes
_output.truncate(count);
}
}
}
}
return rval;
} | javascript | function(pad) {
var rval = true;
if(encrypt) {
if(pad) {
rval = pad(8, _input, !encrypt);
} else {
// add PKCS#7 padding to block (each pad byte is the
// value of the number of pad bytes)
var padding = (_input.length() === 8) ? 8 : (8 - _input.length());
_input.fillWithByte(padding, padding);
}
}
if(rval) {
// do final update
_finish = true;
cipher.update();
}
if(!encrypt) {
// check for error: input data not a multiple of block size
rval = (_input.length() === 0);
if(rval) {
if(pad) {
rval = pad(8, _output, !encrypt);
} else {
// ensure padding byte count is valid
var len = _output.length();
var count = _output.at(len - 1);
if(count > len) {
rval = false;
} else {
// trim off padding bytes
_output.truncate(count);
}
}
}
}
return rval;
} | [
"function",
"(",
"pad",
")",
"{",
"var",
"rval",
"=",
"true",
";",
"if",
"(",
"encrypt",
")",
"{",
"if",
"(",
"pad",
")",
"{",
"rval",
"=",
"pad",
"(",
"8",
",",
"_input",
",",
"!",
"encrypt",
")",
";",
"}",
"else",
"{",
"var",
"padding",
"=",
"(",
"_input",
".",
"length",
"(",
")",
"===",
"8",
")",
"?",
"8",
":",
"(",
"8",
"-",
"_input",
".",
"length",
"(",
")",
")",
";",
"_input",
".",
"fillWithByte",
"(",
"padding",
",",
"padding",
")",
";",
"}",
"}",
"if",
"(",
"rval",
")",
"{",
"_finish",
"=",
"true",
";",
"cipher",
".",
"update",
"(",
")",
";",
"}",
"if",
"(",
"!",
"encrypt",
")",
"{",
"rval",
"=",
"(",
"_input",
".",
"length",
"(",
")",
"===",
"0",
")",
";",
"if",
"(",
"rval",
")",
"{",
"if",
"(",
"pad",
")",
"{",
"rval",
"=",
"pad",
"(",
"8",
",",
"_output",
",",
"!",
"encrypt",
")",
";",
"}",
"else",
"{",
"var",
"len",
"=",
"_output",
".",
"length",
"(",
")",
";",
"var",
"count",
"=",
"_output",
".",
"at",
"(",
"len",
"-",
"1",
")",
";",
"if",
"(",
"count",
">",
"len",
")",
"{",
"rval",
"=",
"false",
";",
"}",
"else",
"{",
"_output",
".",
"truncate",
"(",
"count",
")",
";",
"}",
"}",
"}",
"}",
"return",
"rval",
";",
"}"
]
| Finishes encrypting or decrypting.
@param pad a padding function to use, null for PKCS#7 padding,
signature(blockSize, buffer, decrypt).
@return true if successful, false on error. | [
"Finishes",
"encrypting",
"or",
"decrypting",
"."
]
| 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/build/authorify.js#L9909-L9951 | train |
|
mgesmundo/authorify-client | build/authorify.js | bnGetPrng | function bnGetPrng() {
// create prng with api that matches BigInteger secure random
return {
// x is an array to fill with bytes
nextBytes: function(x) {
for(var i = 0; i < x.length; ++i) {
x[i] = Math.floor(Math.random() * 0xFF);
}
}
};
} | javascript | function bnGetPrng() {
// create prng with api that matches BigInteger secure random
return {
// x is an array to fill with bytes
nextBytes: function(x) {
for(var i = 0; i < x.length; ++i) {
x[i] = Math.floor(Math.random() * 0xFF);
}
}
};
} | [
"function",
"bnGetPrng",
"(",
")",
"{",
"return",
"{",
"nextBytes",
":",
"function",
"(",
"x",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"x",
".",
"length",
";",
"++",
"i",
")",
"{",
"x",
"[",
"i",
"]",
"=",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"0xFF",
")",
";",
"}",
"}",
"}",
";",
"}"
]
| get pseudo random number generator | [
"get",
"pseudo",
"random",
"number",
"generator"
]
| 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/build/authorify.js#L11280-L11290 | train |
mgesmundo/authorify-client | build/authorify.js | getPrime | function getPrime(bits, callback) {
// TODO: consider optimizing by starting workers outside getPrime() ...
// note that in order to clean up they will have to be made internally
// asynchronous which may actually be slower
// start workers immediately
var workers = [];
for(var i = 0; i < numWorkers; ++i) {
// FIXME: fix path or use blob URLs
workers[i] = new Worker(workerScript);
}
var running = numWorkers;
// initialize random number
var num = generateRandom();
// listen for requests from workers and assign ranges to find prime
for(var i = 0; i < numWorkers; ++i) {
workers[i].addEventListener('message', workerMessage);
}
/* Note: The distribution of random numbers is unknown. Therefore, each
web worker is continuously allocated a range of numbers to check for a
random number until one is found.
Every 30 numbers will be checked just 8 times, because prime numbers
have the form:
30k+i, for i < 30 and gcd(30, i)=1 (there are 8 values of i for this)
Therefore, if we want a web worker to run N checks before asking for
a new range of numbers, each range must contain N*30/8 numbers.
For 100 checks (workLoad), this is a range of 375. */
function generateRandom() {
var bits1 = bits - 1;
var num = new BigInteger(bits, state.rng);
// force MSB set
if(!num.testBit(bits1)) {
num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num);
}
// align number on 30k+1 boundary
num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0);
return num;
}
var found = false;
function workerMessage(e) {
// ignore message, prime already found
if(found) {
return;
}
--running;
var data = e.data;
if(data.found) {
// terminate all workers
for(var i = 0; i < workers.length; ++i) {
workers[i].terminate();
}
found = true;
return callback(null, new BigInteger(data.prime, 16));
}
// overflow, regenerate prime
if(num.bitLength() > bits) {
num = generateRandom();
}
// assign new range to check
var hex = num.toString(16);
// start prime search
e.target.postMessage({
e: state.eInt,
hex: hex,
workLoad: workLoad
});
num.dAddOffset(range, 0);
}
} | javascript | function getPrime(bits, callback) {
// TODO: consider optimizing by starting workers outside getPrime() ...
// note that in order to clean up they will have to be made internally
// asynchronous which may actually be slower
// start workers immediately
var workers = [];
for(var i = 0; i < numWorkers; ++i) {
// FIXME: fix path or use blob URLs
workers[i] = new Worker(workerScript);
}
var running = numWorkers;
// initialize random number
var num = generateRandom();
// listen for requests from workers and assign ranges to find prime
for(var i = 0; i < numWorkers; ++i) {
workers[i].addEventListener('message', workerMessage);
}
/* Note: The distribution of random numbers is unknown. Therefore, each
web worker is continuously allocated a range of numbers to check for a
random number until one is found.
Every 30 numbers will be checked just 8 times, because prime numbers
have the form:
30k+i, for i < 30 and gcd(30, i)=1 (there are 8 values of i for this)
Therefore, if we want a web worker to run N checks before asking for
a new range of numbers, each range must contain N*30/8 numbers.
For 100 checks (workLoad), this is a range of 375. */
function generateRandom() {
var bits1 = bits - 1;
var num = new BigInteger(bits, state.rng);
// force MSB set
if(!num.testBit(bits1)) {
num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num);
}
// align number on 30k+1 boundary
num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0);
return num;
}
var found = false;
function workerMessage(e) {
// ignore message, prime already found
if(found) {
return;
}
--running;
var data = e.data;
if(data.found) {
// terminate all workers
for(var i = 0; i < workers.length; ++i) {
workers[i].terminate();
}
found = true;
return callback(null, new BigInteger(data.prime, 16));
}
// overflow, regenerate prime
if(num.bitLength() > bits) {
num = generateRandom();
}
// assign new range to check
var hex = num.toString(16);
// start prime search
e.target.postMessage({
e: state.eInt,
hex: hex,
workLoad: workLoad
});
num.dAddOffset(range, 0);
}
} | [
"function",
"getPrime",
"(",
"bits",
",",
"callback",
")",
"{",
"var",
"workers",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"numWorkers",
";",
"++",
"i",
")",
"{",
"workers",
"[",
"i",
"]",
"=",
"new",
"Worker",
"(",
"workerScript",
")",
";",
"}",
"var",
"running",
"=",
"numWorkers",
";",
"var",
"num",
"=",
"generateRandom",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"numWorkers",
";",
"++",
"i",
")",
"{",
"workers",
"[",
"i",
"]",
".",
"addEventListener",
"(",
"'message'",
",",
"workerMessage",
")",
";",
"}",
"function",
"generateRandom",
"(",
")",
"{",
"var",
"bits1",
"=",
"bits",
"-",
"1",
";",
"var",
"num",
"=",
"new",
"BigInteger",
"(",
"bits",
",",
"state",
".",
"rng",
")",
";",
"if",
"(",
"!",
"num",
".",
"testBit",
"(",
"bits1",
")",
")",
"{",
"num",
".",
"bitwiseTo",
"(",
"BigInteger",
".",
"ONE",
".",
"shiftLeft",
"(",
"bits1",
")",
",",
"op_or",
",",
"num",
")",
";",
"}",
"num",
".",
"dAddOffset",
"(",
"31",
"-",
"num",
".",
"mod",
"(",
"THIRTY",
")",
".",
"byteValue",
"(",
")",
",",
"0",
")",
";",
"return",
"num",
";",
"}",
"var",
"found",
"=",
"false",
";",
"function",
"workerMessage",
"(",
"e",
")",
"{",
"if",
"(",
"found",
")",
"{",
"return",
";",
"}",
"--",
"running",
";",
"var",
"data",
"=",
"e",
".",
"data",
";",
"if",
"(",
"data",
".",
"found",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"workers",
".",
"length",
";",
"++",
"i",
")",
"{",
"workers",
"[",
"i",
"]",
".",
"terminate",
"(",
")",
";",
"}",
"found",
"=",
"true",
";",
"return",
"callback",
"(",
"null",
",",
"new",
"BigInteger",
"(",
"data",
".",
"prime",
",",
"16",
")",
")",
";",
"}",
"if",
"(",
"num",
".",
"bitLength",
"(",
")",
">",
"bits",
")",
"{",
"num",
"=",
"generateRandom",
"(",
")",
";",
"}",
"var",
"hex",
"=",
"num",
".",
"toString",
"(",
"16",
")",
";",
"e",
".",
"target",
".",
"postMessage",
"(",
"{",
"e",
":",
"state",
".",
"eInt",
",",
"hex",
":",
"hex",
",",
"workLoad",
":",
"workLoad",
"}",
")",
";",
"num",
".",
"dAddOffset",
"(",
"range",
",",
"0",
")",
";",
"}",
"}"
]
| implement prime number generation using web workers | [
"implement",
"prime",
"number",
"generation",
"using",
"web",
"workers"
]
| 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/build/authorify.js#L13286-L13368 | train |
mgesmundo/authorify-client | build/authorify.js | _bnToBytes | function _bnToBytes(b) {
// prepend 0x00 if first byte >= 0x80
var hex = b.toString(16);
if(hex[0] >= '8') {
hex = '00' + hex;
}
return forge.util.hexToBytes(hex);
} | javascript | function _bnToBytes(b) {
// prepend 0x00 if first byte >= 0x80
var hex = b.toString(16);
if(hex[0] >= '8') {
hex = '00' + hex;
}
return forge.util.hexToBytes(hex);
} | [
"function",
"_bnToBytes",
"(",
"b",
")",
"{",
"var",
"hex",
"=",
"b",
".",
"toString",
"(",
"16",
")",
";",
"if",
"(",
"hex",
"[",
"0",
"]",
">=",
"'8'",
")",
"{",
"hex",
"=",
"'00'",
"+",
"hex",
";",
"}",
"return",
"forge",
".",
"util",
".",
"hexToBytes",
"(",
"hex",
")",
";",
"}"
]
| Converts a positive BigInteger into 2's-complement big-endian bytes.
@param b the big integer to convert.
@return the bytes. | [
"Converts",
"a",
"positive",
"BigInteger",
"into",
"2",
"s",
"-",
"complement",
"big",
"-",
"endian",
"bytes",
"."
]
| 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/build/authorify.js#L13424-L13431 | train |
mgesmundo/authorify-client | build/authorify.js | evpBytesToKey | function evpBytesToKey(password, salt, dkLen) {
var digests = [md5(password + salt)];
for(var length = 16, i = 1; length < dkLen; ++i, length += 16) {
digests.push(md5(digests[i - 1] + password + salt));
}
return digests.join('').substr(0, dkLen);
} | javascript | function evpBytesToKey(password, salt, dkLen) {
var digests = [md5(password + salt)];
for(var length = 16, i = 1; length < dkLen; ++i, length += 16) {
digests.push(md5(digests[i - 1] + password + salt));
}
return digests.join('').substr(0, dkLen);
} | [
"function",
"evpBytesToKey",
"(",
"password",
",",
"salt",
",",
"dkLen",
")",
"{",
"var",
"digests",
"=",
"[",
"md5",
"(",
"password",
"+",
"salt",
")",
"]",
";",
"for",
"(",
"var",
"length",
"=",
"16",
",",
"i",
"=",
"1",
";",
"length",
"<",
"dkLen",
";",
"++",
"i",
",",
"length",
"+=",
"16",
")",
"{",
"digests",
".",
"push",
"(",
"md5",
"(",
"digests",
"[",
"i",
"-",
"1",
"]",
"+",
"password",
"+",
"salt",
")",
")",
";",
"}",
"return",
"digests",
".",
"join",
"(",
"''",
")",
".",
"substr",
"(",
"0",
",",
"dkLen",
")",
";",
"}"
]
| OpenSSL's legacy key derivation function.
See: http://www.openssl.org/docs/crypto/EVP_BytesToKey.html
@param password the password to derive the key from.
@param salt the salt to use.
@param dkLen the number of bytes needed for the derived key. | [
"OpenSSL",
"s",
"legacy",
"key",
"derivation",
"function",
"."
]
| 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/build/authorify.js#L14408-L14414 | train |
mgesmundo/authorify-client | build/authorify.js | _extensionsToAsn1 | function _extensionsToAsn1(exts) {
// create top-level extension container
var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []);
// create extension sequence (stores a sequence for each extension)
var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
rval.value.push(seq);
var ext, extseq;
for(var i = 0; i < exts.length; ++i) {
ext = exts[i];
// create a sequence for each extension
extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
seq.value.push(extseq);
// extnID (OID)
extseq.value.push(asn1.create(
asn1.Class.UNIVERSAL, asn1.Type.OID, false,
asn1.oidToDer(ext.id).getBytes()));
// critical defaults to false
if(ext.critical) {
// critical BOOLEAN DEFAULT FALSE
extseq.value.push(asn1.create(
asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,
String.fromCharCode(0xFF)));
}
var value = ext.value;
if(typeof ext.value !== 'string') {
// value is asn.1
value = asn1.toDer(value).getBytes();
}
// extnValue (OCTET STRING)
extseq.value.push(asn1.create(
asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, value));
}
return rval;
} | javascript | function _extensionsToAsn1(exts) {
// create top-level extension container
var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []);
// create extension sequence (stores a sequence for each extension)
var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
rval.value.push(seq);
var ext, extseq;
for(var i = 0; i < exts.length; ++i) {
ext = exts[i];
// create a sequence for each extension
extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
seq.value.push(extseq);
// extnID (OID)
extseq.value.push(asn1.create(
asn1.Class.UNIVERSAL, asn1.Type.OID, false,
asn1.oidToDer(ext.id).getBytes()));
// critical defaults to false
if(ext.critical) {
// critical BOOLEAN DEFAULT FALSE
extseq.value.push(asn1.create(
asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,
String.fromCharCode(0xFF)));
}
var value = ext.value;
if(typeof ext.value !== 'string') {
// value is asn.1
value = asn1.toDer(value).getBytes();
}
// extnValue (OCTET STRING)
extseq.value.push(asn1.create(
asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, value));
}
return rval;
} | [
"function",
"_extensionsToAsn1",
"(",
"exts",
")",
"{",
"var",
"rval",
"=",
"asn1",
".",
"create",
"(",
"asn1",
".",
"Class",
".",
"CONTEXT_SPECIFIC",
",",
"3",
",",
"true",
",",
"[",
"]",
")",
";",
"var",
"seq",
"=",
"asn1",
".",
"create",
"(",
"asn1",
".",
"Class",
".",
"UNIVERSAL",
",",
"asn1",
".",
"Type",
".",
"SEQUENCE",
",",
"true",
",",
"[",
"]",
")",
";",
"rval",
".",
"value",
".",
"push",
"(",
"seq",
")",
";",
"var",
"ext",
",",
"extseq",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"exts",
".",
"length",
";",
"++",
"i",
")",
"{",
"ext",
"=",
"exts",
"[",
"i",
"]",
";",
"extseq",
"=",
"asn1",
".",
"create",
"(",
"asn1",
".",
"Class",
".",
"UNIVERSAL",
",",
"asn1",
".",
"Type",
".",
"SEQUENCE",
",",
"true",
",",
"[",
"]",
")",
";",
"seq",
".",
"value",
".",
"push",
"(",
"extseq",
")",
";",
"extseq",
".",
"value",
".",
"push",
"(",
"asn1",
".",
"create",
"(",
"asn1",
".",
"Class",
".",
"UNIVERSAL",
",",
"asn1",
".",
"Type",
".",
"OID",
",",
"false",
",",
"asn1",
".",
"oidToDer",
"(",
"ext",
".",
"id",
")",
".",
"getBytes",
"(",
")",
")",
")",
";",
"if",
"(",
"ext",
".",
"critical",
")",
"{",
"extseq",
".",
"value",
".",
"push",
"(",
"asn1",
".",
"create",
"(",
"asn1",
".",
"Class",
".",
"UNIVERSAL",
",",
"asn1",
".",
"Type",
".",
"BOOLEAN",
",",
"false",
",",
"String",
".",
"fromCharCode",
"(",
"0xFF",
")",
")",
")",
";",
"}",
"var",
"value",
"=",
"ext",
".",
"value",
";",
"if",
"(",
"typeof",
"ext",
".",
"value",
"!==",
"'string'",
")",
"{",
"value",
"=",
"asn1",
".",
"toDer",
"(",
"value",
")",
".",
"getBytes",
"(",
")",
";",
"}",
"extseq",
".",
"value",
".",
"push",
"(",
"asn1",
".",
"create",
"(",
"asn1",
".",
"Class",
".",
"UNIVERSAL",
",",
"asn1",
".",
"Type",
".",
"OCTETSTRING",
",",
"false",
",",
"value",
")",
")",
";",
"}",
"return",
"rval",
";",
"}"
]
| Converts X.509v3 certificate extensions to ASN.1.
@param exts the extensions to convert.
@return the extensions in ASN.1 format. | [
"Converts",
"X",
".",
"509v3",
"certificate",
"extensions",
"to",
"ASN",
".",
"1",
"."
]
| 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/build/authorify.js#L17430-L17471 | train |
mgesmundo/authorify-client | build/authorify.js | _CRIAttributesToAsn1 | function _CRIAttributesToAsn1(csr) {
// create an empty context-specific container
var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []);
// no attributes, return empty container
if(csr.attributes.length === 0) {
return rval;
}
// each attribute has a sequence with a type and a set of values
var attrs = csr.attributes;
for(var i = 0; i < attrs.length; ++i) {
var attr = attrs[i];
var value = attr.value;
// reuse tag class for attribute value if available
var valueTagClass = asn1.Type.UTF8;
if('valueTagClass' in attr) {
valueTagClass = attr.valueTagClass;
}
if(valueTagClass === asn1.Type.UTF8) {
value = forge.util.encodeUtf8(value);
}
// FIXME: handle more encodings
// create a RelativeDistinguishedName set
// each value in the set is an AttributeTypeAndValue first
// containing the type (an OID) and second the value
var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// AttributeType
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
asn1.oidToDer(attr.type).getBytes()),
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [
// AttributeValue
asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value)
])
]);
rval.value.push(seq);
}
return rval;
} | javascript | function _CRIAttributesToAsn1(csr) {
// create an empty context-specific container
var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []);
// no attributes, return empty container
if(csr.attributes.length === 0) {
return rval;
}
// each attribute has a sequence with a type and a set of values
var attrs = csr.attributes;
for(var i = 0; i < attrs.length; ++i) {
var attr = attrs[i];
var value = attr.value;
// reuse tag class for attribute value if available
var valueTagClass = asn1.Type.UTF8;
if('valueTagClass' in attr) {
valueTagClass = attr.valueTagClass;
}
if(valueTagClass === asn1.Type.UTF8) {
value = forge.util.encodeUtf8(value);
}
// FIXME: handle more encodings
// create a RelativeDistinguishedName set
// each value in the set is an AttributeTypeAndValue first
// containing the type (an OID) and second the value
var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
// AttributeType
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
asn1.oidToDer(attr.type).getBytes()),
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [
// AttributeValue
asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value)
])
]);
rval.value.push(seq);
}
return rval;
} | [
"function",
"_CRIAttributesToAsn1",
"(",
"csr",
")",
"{",
"var",
"rval",
"=",
"asn1",
".",
"create",
"(",
"asn1",
".",
"Class",
".",
"CONTEXT_SPECIFIC",
",",
"0",
",",
"true",
",",
"[",
"]",
")",
";",
"if",
"(",
"csr",
".",
"attributes",
".",
"length",
"===",
"0",
")",
"{",
"return",
"rval",
";",
"}",
"var",
"attrs",
"=",
"csr",
".",
"attributes",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"attrs",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"attr",
"=",
"attrs",
"[",
"i",
"]",
";",
"var",
"value",
"=",
"attr",
".",
"value",
";",
"var",
"valueTagClass",
"=",
"asn1",
".",
"Type",
".",
"UTF8",
";",
"if",
"(",
"'valueTagClass'",
"in",
"attr",
")",
"{",
"valueTagClass",
"=",
"attr",
".",
"valueTagClass",
";",
"}",
"if",
"(",
"valueTagClass",
"===",
"asn1",
".",
"Type",
".",
"UTF8",
")",
"{",
"value",
"=",
"forge",
".",
"util",
".",
"encodeUtf8",
"(",
"value",
")",
";",
"}",
"var",
"seq",
"=",
"asn1",
".",
"create",
"(",
"asn1",
".",
"Class",
".",
"UNIVERSAL",
",",
"asn1",
".",
"Type",
".",
"SEQUENCE",
",",
"true",
",",
"[",
"asn1",
".",
"create",
"(",
"asn1",
".",
"Class",
".",
"UNIVERSAL",
",",
"asn1",
".",
"Type",
".",
"OID",
",",
"false",
",",
"asn1",
".",
"oidToDer",
"(",
"attr",
".",
"type",
")",
".",
"getBytes",
"(",
")",
")",
",",
"asn1",
".",
"create",
"(",
"asn1",
".",
"Class",
".",
"UNIVERSAL",
",",
"asn1",
".",
"Type",
".",
"SET",
",",
"true",
",",
"[",
"asn1",
".",
"create",
"(",
"asn1",
".",
"Class",
".",
"UNIVERSAL",
",",
"valueTagClass",
",",
"false",
",",
"value",
")",
"]",
")",
"]",
")",
";",
"rval",
".",
"value",
".",
"push",
"(",
"seq",
")",
";",
"}",
"return",
"rval",
";",
"}"
]
| Converts a certification request's attributes to an ASN.1 set of
CRIAttributes.
@param csr certification request.
@return the ASN.1 set of CRIAttributes. | [
"Converts",
"a",
"certification",
"request",
"s",
"attributes",
"to",
"an",
"ASN",
".",
"1",
"set",
"of",
"CRIAttributes",
"."
]
| 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/build/authorify.js#L17608-L17649 | train |
mgesmundo/authorify-client | build/authorify.js | function(filter) {
var rval = {};
var localKeyId;
if('localKeyId' in filter) {
localKeyId = filter.localKeyId;
} else if('localKeyIdHex' in filter) {
localKeyId = forge.util.hexToBytes(filter.localKeyIdHex);
}
// filter on bagType only
if(localKeyId === undefined && !('friendlyName' in filter) &&
'bagType' in filter) {
rval[filter.bagType] = _getBagsByAttribute(
pfx.safeContents, null, null, filter.bagType);
}
if(localKeyId !== undefined) {
rval.localKeyId = _getBagsByAttribute(
pfx.safeContents, 'localKeyId',
localKeyId, filter.bagType);
}
if('friendlyName' in filter) {
rval.friendlyName = _getBagsByAttribute(
pfx.safeContents, 'friendlyName',
filter.friendlyName, filter.bagType);
}
return rval;
} | javascript | function(filter) {
var rval = {};
var localKeyId;
if('localKeyId' in filter) {
localKeyId = filter.localKeyId;
} else if('localKeyIdHex' in filter) {
localKeyId = forge.util.hexToBytes(filter.localKeyIdHex);
}
// filter on bagType only
if(localKeyId === undefined && !('friendlyName' in filter) &&
'bagType' in filter) {
rval[filter.bagType] = _getBagsByAttribute(
pfx.safeContents, null, null, filter.bagType);
}
if(localKeyId !== undefined) {
rval.localKeyId = _getBagsByAttribute(
pfx.safeContents, 'localKeyId',
localKeyId, filter.bagType);
}
if('friendlyName' in filter) {
rval.friendlyName = _getBagsByAttribute(
pfx.safeContents, 'friendlyName',
filter.friendlyName, filter.bagType);
}
return rval;
} | [
"function",
"(",
"filter",
")",
"{",
"var",
"rval",
"=",
"{",
"}",
";",
"var",
"localKeyId",
";",
"if",
"(",
"'localKeyId'",
"in",
"filter",
")",
"{",
"localKeyId",
"=",
"filter",
".",
"localKeyId",
";",
"}",
"else",
"if",
"(",
"'localKeyIdHex'",
"in",
"filter",
")",
"{",
"localKeyId",
"=",
"forge",
".",
"util",
".",
"hexToBytes",
"(",
"filter",
".",
"localKeyIdHex",
")",
";",
"}",
"if",
"(",
"localKeyId",
"===",
"undefined",
"&&",
"!",
"(",
"'friendlyName'",
"in",
"filter",
")",
"&&",
"'bagType'",
"in",
"filter",
")",
"{",
"rval",
"[",
"filter",
".",
"bagType",
"]",
"=",
"_getBagsByAttribute",
"(",
"pfx",
".",
"safeContents",
",",
"null",
",",
"null",
",",
"filter",
".",
"bagType",
")",
";",
"}",
"if",
"(",
"localKeyId",
"!==",
"undefined",
")",
"{",
"rval",
".",
"localKeyId",
"=",
"_getBagsByAttribute",
"(",
"pfx",
".",
"safeContents",
",",
"'localKeyId'",
",",
"localKeyId",
",",
"filter",
".",
"bagType",
")",
";",
"}",
"if",
"(",
"'friendlyName'",
"in",
"filter",
")",
"{",
"rval",
".",
"friendlyName",
"=",
"_getBagsByAttribute",
"(",
"pfx",
".",
"safeContents",
",",
"'friendlyName'",
",",
"filter",
".",
"friendlyName",
",",
"filter",
".",
"bagType",
")",
";",
"}",
"return",
"rval",
";",
"}"
]
| Gets bags with matching attributes.
@param filter the attributes to filter by:
[localKeyId] the localKeyId to search for.
[localKeyIdHex] the localKeyId in hex to search for.
[friendlyName] the friendly name to search for.
[bagType] bag type to narrow each attribute search by.
@return a map of attribute type to an array of matching bags or, if no
attribute was given but a bag type, the map key will be the
bag type. | [
"Gets",
"bags",
"with",
"matching",
"attributes",
"."
]
| 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/build/authorify.js#L18696-L18725 | train |
|
mgesmundo/authorify-client | build/authorify.js | function(secret, label, seed, length) {
var rval = forge.util.createBuffer();
/* For TLS 1.0, the secret is split in half, into two secrets of equal
length. If the secret has an odd length then the last byte of the first
half will be the same as the first byte of the second. The length of the
two secrets is half of the secret rounded up. */
var idx = (secret.length >> 1);
var slen = idx + (secret.length & 1);
var s1 = secret.substr(0, slen);
var s2 = secret.substr(idx, slen);
var ai = forge.util.createBuffer();
var hmac = forge.hmac.create();
seed = label + seed;
// determine the number of iterations that must be performed to generate
// enough output bytes, md5 creates 16 byte hashes, sha1 creates 20
var md5itr = Math.ceil(length / 16);
var sha1itr = Math.ceil(length / 20);
// do md5 iterations
hmac.start('MD5', s1);
var md5bytes = forge.util.createBuffer();
ai.putBytes(seed);
for(var i = 0; i < md5itr; ++i) {
// HMAC_hash(secret, A(i-1))
hmac.start(null, null);
hmac.update(ai.getBytes());
ai.putBuffer(hmac.digest());
// HMAC_hash(secret, A(i) + seed)
hmac.start(null, null);
hmac.update(ai.bytes() + seed);
md5bytes.putBuffer(hmac.digest());
}
// do sha1 iterations
hmac.start('SHA1', s2);
var sha1bytes = forge.util.createBuffer();
ai.clear();
ai.putBytes(seed);
for(var i = 0; i < sha1itr; ++i) {
// HMAC_hash(secret, A(i-1))
hmac.start(null, null);
hmac.update(ai.getBytes());
ai.putBuffer(hmac.digest());
// HMAC_hash(secret, A(i) + seed)
hmac.start(null, null);
hmac.update(ai.bytes() + seed);
sha1bytes.putBuffer(hmac.digest());
}
// XOR the md5 bytes with the sha1 bytes
rval.putBytes(forge.util.xorBytes(
md5bytes.getBytes(), sha1bytes.getBytes(), length));
return rval;
} | javascript | function(secret, label, seed, length) {
var rval = forge.util.createBuffer();
/* For TLS 1.0, the secret is split in half, into two secrets of equal
length. If the secret has an odd length then the last byte of the first
half will be the same as the first byte of the second. The length of the
two secrets is half of the secret rounded up. */
var idx = (secret.length >> 1);
var slen = idx + (secret.length & 1);
var s1 = secret.substr(0, slen);
var s2 = secret.substr(idx, slen);
var ai = forge.util.createBuffer();
var hmac = forge.hmac.create();
seed = label + seed;
// determine the number of iterations that must be performed to generate
// enough output bytes, md5 creates 16 byte hashes, sha1 creates 20
var md5itr = Math.ceil(length / 16);
var sha1itr = Math.ceil(length / 20);
// do md5 iterations
hmac.start('MD5', s1);
var md5bytes = forge.util.createBuffer();
ai.putBytes(seed);
for(var i = 0; i < md5itr; ++i) {
// HMAC_hash(secret, A(i-1))
hmac.start(null, null);
hmac.update(ai.getBytes());
ai.putBuffer(hmac.digest());
// HMAC_hash(secret, A(i) + seed)
hmac.start(null, null);
hmac.update(ai.bytes() + seed);
md5bytes.putBuffer(hmac.digest());
}
// do sha1 iterations
hmac.start('SHA1', s2);
var sha1bytes = forge.util.createBuffer();
ai.clear();
ai.putBytes(seed);
for(var i = 0; i < sha1itr; ++i) {
// HMAC_hash(secret, A(i-1))
hmac.start(null, null);
hmac.update(ai.getBytes());
ai.putBuffer(hmac.digest());
// HMAC_hash(secret, A(i) + seed)
hmac.start(null, null);
hmac.update(ai.bytes() + seed);
sha1bytes.putBuffer(hmac.digest());
}
// XOR the md5 bytes with the sha1 bytes
rval.putBytes(forge.util.xorBytes(
md5bytes.getBytes(), sha1bytes.getBytes(), length));
return rval;
} | [
"function",
"(",
"secret",
",",
"label",
",",
"seed",
",",
"length",
")",
"{",
"var",
"rval",
"=",
"forge",
".",
"util",
".",
"createBuffer",
"(",
")",
";",
"var",
"idx",
"=",
"(",
"secret",
".",
"length",
">>",
"1",
")",
";",
"var",
"slen",
"=",
"idx",
"+",
"(",
"secret",
".",
"length",
"&",
"1",
")",
";",
"var",
"s1",
"=",
"secret",
".",
"substr",
"(",
"0",
",",
"slen",
")",
";",
"var",
"s2",
"=",
"secret",
".",
"substr",
"(",
"idx",
",",
"slen",
")",
";",
"var",
"ai",
"=",
"forge",
".",
"util",
".",
"createBuffer",
"(",
")",
";",
"var",
"hmac",
"=",
"forge",
".",
"hmac",
".",
"create",
"(",
")",
";",
"seed",
"=",
"label",
"+",
"seed",
";",
"var",
"md5itr",
"=",
"Math",
".",
"ceil",
"(",
"length",
"/",
"16",
")",
";",
"var",
"sha1itr",
"=",
"Math",
".",
"ceil",
"(",
"length",
"/",
"20",
")",
";",
"hmac",
".",
"start",
"(",
"'MD5'",
",",
"s1",
")",
";",
"var",
"md5bytes",
"=",
"forge",
".",
"util",
".",
"createBuffer",
"(",
")",
";",
"ai",
".",
"putBytes",
"(",
"seed",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"md5itr",
";",
"++",
"i",
")",
"{",
"hmac",
".",
"start",
"(",
"null",
",",
"null",
")",
";",
"hmac",
".",
"update",
"(",
"ai",
".",
"getBytes",
"(",
")",
")",
";",
"ai",
".",
"putBuffer",
"(",
"hmac",
".",
"digest",
"(",
")",
")",
";",
"hmac",
".",
"start",
"(",
"null",
",",
"null",
")",
";",
"hmac",
".",
"update",
"(",
"ai",
".",
"bytes",
"(",
")",
"+",
"seed",
")",
";",
"md5bytes",
".",
"putBuffer",
"(",
"hmac",
".",
"digest",
"(",
")",
")",
";",
"}",
"hmac",
".",
"start",
"(",
"'SHA1'",
",",
"s2",
")",
";",
"var",
"sha1bytes",
"=",
"forge",
".",
"util",
".",
"createBuffer",
"(",
")",
";",
"ai",
".",
"clear",
"(",
")",
";",
"ai",
".",
"putBytes",
"(",
"seed",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"sha1itr",
";",
"++",
"i",
")",
"{",
"hmac",
".",
"start",
"(",
"null",
",",
"null",
")",
";",
"hmac",
".",
"update",
"(",
"ai",
".",
"getBytes",
"(",
")",
")",
";",
"ai",
".",
"putBuffer",
"(",
"hmac",
".",
"digest",
"(",
")",
")",
";",
"hmac",
".",
"start",
"(",
"null",
",",
"null",
")",
";",
"hmac",
".",
"update",
"(",
"ai",
".",
"bytes",
"(",
")",
"+",
"seed",
")",
";",
"sha1bytes",
".",
"putBuffer",
"(",
"hmac",
".",
"digest",
"(",
")",
")",
";",
"}",
"rval",
".",
"putBytes",
"(",
"forge",
".",
"util",
".",
"xorBytes",
"(",
"md5bytes",
".",
"getBytes",
"(",
")",
",",
"sha1bytes",
".",
"getBytes",
"(",
")",
",",
"length",
")",
")",
";",
"return",
"rval",
";",
"}"
]
| Generates pseudo random bytes by mixing the result of two hash functions,
MD5 and SHA-1.
prf_TLS1(secret, label, seed) =
P_MD5(S1, label + seed) XOR P_SHA-1(S2, label + seed);
Each P_hash function functions as follows:
P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
HMAC_hash(secret, A(2) + seed) +
HMAC_hash(secret, A(3) + seed) + ...
A() is defined as:
A(0) = seed
A(i) = HMAC_hash(secret, A(i-1))
The '+' operator denotes concatenation.
As many iterations A(N) as are needed are performed to generate enough
pseudo random byte output. If an iteration creates more data than is
necessary, then it is truncated.
Therefore:
A(1) = HMAC_hash(secret, A(0))
= HMAC_hash(secret, seed)
A(2) = HMAC_hash(secret, A(1))
= HMAC_hash(secret, HMAC_hash(secret, seed))
Therefore:
P_hash(secret, seed) =
HMAC_hash(secret, HMAC_hash(secret, A(0)) + seed) +
HMAC_hash(secret, HMAC_hash(secret, A(1)) + seed) +
...
Therefore:
P_hash(secret, seed) =
HMAC_hash(secret, HMAC_hash(secret, seed) + seed) +
HMAC_hash(secret, HMAC_hash(secret, HMAC_hash(secret, seed)) + seed) +
...
@param secret the secret to use.
@param label the label to use.
@param seed the seed value to use.
@param length the number of bytes to generate.
@return the pseudo random bytes in a byte buffer. | [
"Generates",
"pseudo",
"random",
"bytes",
"by",
"mixing",
"the",
"result",
"of",
"two",
"hash",
"functions",
"MD5",
"and",
"SHA",
"-",
"1",
"."
]
| 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/build/authorify.js#L19920-L19978 | train |
|
mgesmundo/authorify-client | build/authorify.js | function(key, seqNum, record) {
/* MAC is computed like so:
HMAC_hash(
key, seqNum +
TLSCompressed.type +
TLSCompressed.version +
TLSCompressed.length +
TLSCompressed.fragment)
*/
var hmac = forge.hmac.create();
hmac.start('SHA1', key);
var b = forge.util.createBuffer();
b.putInt32(seqNum[0]);
b.putInt32(seqNum[1]);
b.putByte(record.type);
b.putByte(record.version.major);
b.putByte(record.version.minor);
b.putInt16(record.length);
b.putBytes(record.fragment.bytes());
hmac.update(b.getBytes());
return hmac.digest().getBytes();
} | javascript | function(key, seqNum, record) {
/* MAC is computed like so:
HMAC_hash(
key, seqNum +
TLSCompressed.type +
TLSCompressed.version +
TLSCompressed.length +
TLSCompressed.fragment)
*/
var hmac = forge.hmac.create();
hmac.start('SHA1', key);
var b = forge.util.createBuffer();
b.putInt32(seqNum[0]);
b.putInt32(seqNum[1]);
b.putByte(record.type);
b.putByte(record.version.major);
b.putByte(record.version.minor);
b.putInt16(record.length);
b.putBytes(record.fragment.bytes());
hmac.update(b.getBytes());
return hmac.digest().getBytes();
} | [
"function",
"(",
"key",
",",
"seqNum",
",",
"record",
")",
"{",
"var",
"hmac",
"=",
"forge",
".",
"hmac",
".",
"create",
"(",
")",
";",
"hmac",
".",
"start",
"(",
"'SHA1'",
",",
"key",
")",
";",
"var",
"b",
"=",
"forge",
".",
"util",
".",
"createBuffer",
"(",
")",
";",
"b",
".",
"putInt32",
"(",
"seqNum",
"[",
"0",
"]",
")",
";",
"b",
".",
"putInt32",
"(",
"seqNum",
"[",
"1",
"]",
")",
";",
"b",
".",
"putByte",
"(",
"record",
".",
"type",
")",
";",
"b",
".",
"putByte",
"(",
"record",
".",
"version",
".",
"major",
")",
";",
"b",
".",
"putByte",
"(",
"record",
".",
"version",
".",
"minor",
")",
";",
"b",
".",
"putInt16",
"(",
"record",
".",
"length",
")",
";",
"b",
".",
"putBytes",
"(",
"record",
".",
"fragment",
".",
"bytes",
"(",
")",
")",
";",
"hmac",
".",
"update",
"(",
"b",
".",
"getBytes",
"(",
")",
")",
";",
"return",
"hmac",
".",
"digest",
"(",
")",
".",
"getBytes",
"(",
")",
";",
"}"
]
| Gets a MAC for a record using the SHA-1 hash algorithm.
@param key the mac key.
@param state the sequence number (array of two 32-bit integers).
@param record the record.
@return the sha-1 hash (20 bytes) for the given record. | [
"Gets",
"a",
"MAC",
"for",
"a",
"record",
"using",
"the",
"SHA",
"-",
"1",
"hash",
"algorithm",
"."
]
| 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/build/authorify.js#L20003-L20024 | train |
|
mgesmundo/authorify-client | build/authorify.js | encrypt_aes_cbc_sha1 | function encrypt_aes_cbc_sha1(record, s) {
var rval = false;
// append MAC to fragment, update sequence number
var mac = s.macFunction(s.macKey, s.sequenceNumber, record);
record.fragment.putBytes(mac);
s.updateSequenceNumber();
// TLS 1.1+ use an explicit IV every time to protect against CBC attacks
var iv;
if(record.version.minor === tls.Versions.TLS_1_0.minor) {
// use the pre-generated IV when initializing for TLS 1.0, otherwise use
// the residue from the previous encryption
iv = s.cipherState.init ? null : s.cipherState.iv;
} else {
iv = forge.random.getBytesSync(16);
}
s.cipherState.init = true;
// start cipher
var cipher = s.cipherState.cipher;
cipher.start({iv: iv});
// TLS 1.1+ write IV into output
if(record.version.minor >= tls.Versions.TLS_1_1.minor) {
cipher.output.putBytes(iv);
}
// do encryption (default padding is appropriate)
cipher.update(record.fragment);
if(cipher.finish(encrypt_aes_cbc_sha1_padding)) {
// set record fragment to encrypted output
record.fragment = cipher.output;
record.length = record.fragment.length();
rval = true;
}
return rval;
} | javascript | function encrypt_aes_cbc_sha1(record, s) {
var rval = false;
// append MAC to fragment, update sequence number
var mac = s.macFunction(s.macKey, s.sequenceNumber, record);
record.fragment.putBytes(mac);
s.updateSequenceNumber();
// TLS 1.1+ use an explicit IV every time to protect against CBC attacks
var iv;
if(record.version.minor === tls.Versions.TLS_1_0.minor) {
// use the pre-generated IV when initializing for TLS 1.0, otherwise use
// the residue from the previous encryption
iv = s.cipherState.init ? null : s.cipherState.iv;
} else {
iv = forge.random.getBytesSync(16);
}
s.cipherState.init = true;
// start cipher
var cipher = s.cipherState.cipher;
cipher.start({iv: iv});
// TLS 1.1+ write IV into output
if(record.version.minor >= tls.Versions.TLS_1_1.minor) {
cipher.output.putBytes(iv);
}
// do encryption (default padding is appropriate)
cipher.update(record.fragment);
if(cipher.finish(encrypt_aes_cbc_sha1_padding)) {
// set record fragment to encrypted output
record.fragment = cipher.output;
record.length = record.fragment.length();
rval = true;
}
return rval;
} | [
"function",
"encrypt_aes_cbc_sha1",
"(",
"record",
",",
"s",
")",
"{",
"var",
"rval",
"=",
"false",
";",
"var",
"mac",
"=",
"s",
".",
"macFunction",
"(",
"s",
".",
"macKey",
",",
"s",
".",
"sequenceNumber",
",",
"record",
")",
";",
"record",
".",
"fragment",
".",
"putBytes",
"(",
"mac",
")",
";",
"s",
".",
"updateSequenceNumber",
"(",
")",
";",
"var",
"iv",
";",
"if",
"(",
"record",
".",
"version",
".",
"minor",
"===",
"tls",
".",
"Versions",
".",
"TLS_1_0",
".",
"minor",
")",
"{",
"iv",
"=",
"s",
".",
"cipherState",
".",
"init",
"?",
"null",
":",
"s",
".",
"cipherState",
".",
"iv",
";",
"}",
"else",
"{",
"iv",
"=",
"forge",
".",
"random",
".",
"getBytesSync",
"(",
"16",
")",
";",
"}",
"s",
".",
"cipherState",
".",
"init",
"=",
"true",
";",
"var",
"cipher",
"=",
"s",
".",
"cipherState",
".",
"cipher",
";",
"cipher",
".",
"start",
"(",
"{",
"iv",
":",
"iv",
"}",
")",
";",
"if",
"(",
"record",
".",
"version",
".",
"minor",
">=",
"tls",
".",
"Versions",
".",
"TLS_1_1",
".",
"minor",
")",
"{",
"cipher",
".",
"output",
".",
"putBytes",
"(",
"iv",
")",
";",
"}",
"cipher",
".",
"update",
"(",
"record",
".",
"fragment",
")",
";",
"if",
"(",
"cipher",
".",
"finish",
"(",
"encrypt_aes_cbc_sha1_padding",
")",
")",
"{",
"record",
".",
"fragment",
"=",
"cipher",
".",
"output",
";",
"record",
".",
"length",
"=",
"record",
".",
"fragment",
".",
"length",
"(",
")",
";",
"rval",
"=",
"true",
";",
"}",
"return",
"rval",
";",
"}"
]
| Encrypts the TLSCompressed record into a TLSCipherText record using AES
in CBC mode.
@param record the TLSCompressed record to encrypt.
@param s the ConnectionState to use.
@return true on success, false on failure. | [
"Encrypts",
"the",
"TLSCompressed",
"record",
"into",
"a",
"TLSCipherText",
"record",
"using",
"AES",
"in",
"CBC",
"mode",
"."
]
| 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/build/authorify.js#L24037-L24076 | train |
mgesmundo/authorify-client | build/authorify.js | decrypt_aes_cbc_sha1_padding | function decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) {
var rval = true;
if(decrypt) {
/* The last byte in the output specifies the number of padding bytes not
including itself. Each of the padding bytes has the same value as that
last byte (known as the padding_length). Here we check all padding
bytes to ensure they have the value of padding_length even if one of
them is bad in order to ward-off timing attacks. */
var len = output.length();
var paddingLength = output.last();
for(var i = len - 1 - paddingLength; i < len - 1; ++i) {
rval = rval && (output.at(i) == paddingLength);
}
if(rval) {
// trim off padding bytes and last padding length byte
output.truncate(paddingLength + 1);
}
}
return rval;
} | javascript | function decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) {
var rval = true;
if(decrypt) {
/* The last byte in the output specifies the number of padding bytes not
including itself. Each of the padding bytes has the same value as that
last byte (known as the padding_length). Here we check all padding
bytes to ensure they have the value of padding_length even if one of
them is bad in order to ward-off timing attacks. */
var len = output.length();
var paddingLength = output.last();
for(var i = len - 1 - paddingLength; i < len - 1; ++i) {
rval = rval && (output.at(i) == paddingLength);
}
if(rval) {
// trim off padding bytes and last padding length byte
output.truncate(paddingLength + 1);
}
}
return rval;
} | [
"function",
"decrypt_aes_cbc_sha1_padding",
"(",
"blockSize",
",",
"output",
",",
"decrypt",
")",
"{",
"var",
"rval",
"=",
"true",
";",
"if",
"(",
"decrypt",
")",
"{",
"var",
"len",
"=",
"output",
".",
"length",
"(",
")",
";",
"var",
"paddingLength",
"=",
"output",
".",
"last",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"len",
"-",
"1",
"-",
"paddingLength",
";",
"i",
"<",
"len",
"-",
"1",
";",
"++",
"i",
")",
"{",
"rval",
"=",
"rval",
"&&",
"(",
"output",
".",
"at",
"(",
"i",
")",
"==",
"paddingLength",
")",
";",
"}",
"if",
"(",
"rval",
")",
"{",
"output",
".",
"truncate",
"(",
"paddingLength",
"+",
"1",
")",
";",
"}",
"}",
"return",
"rval",
";",
"}"
]
| Handles padding for aes_cbc_sha1 in decrypt mode.
@param blockSize the block size.
@param output the output buffer.
@param decrypt true in decrypt mode, false in encrypt mode.
@return true on success, false on failure. | [
"Handles",
"padding",
"for",
"aes_cbc_sha1",
"in",
"decrypt",
"mode",
"."
]
| 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/build/authorify.js#L24125-L24144 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.