id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
35,300
uladkasach/clientside-require
src/utilities/content_loading/commonjs.js
function(request, options){ if(typeof options == "undefined") options = {}; // define options if not yet defined options.relative_path_root = relative_path_root; // overwrite user defined rel path root - TODO - make this a private property return require_function(request, options); }
javascript
function(request, options){ if(typeof options == "undefined") options = {}; // define options if not yet defined options.relative_path_root = relative_path_root; // overwrite user defined rel path root - TODO - make this a private property return require_function(request, options); }
[ "function", "(", "request", ",", "options", ")", "{", "if", "(", "typeof", "options", "==", "\"undefined\"", ")", "options", "=", "{", "}", ";", "// define options if not yet defined", "options", ".", "relative_path_root", "=", "relative_path_root", ";", "// overwrite user defined rel path root - TODO - make this a private property", "return", "require_function", "(", "request", ",", "options", ")", ";", "}" ]
build the require function to inject
[ "build", "the", "require", "function", "to", "inject" ]
7f20105fb3935fe7ae86a687632c632f4a5dc88b
https://github.com/uladkasach/clientside-require/blob/7f20105fb3935fe7ae86a687632c632f4a5dc88b/src/utilities/content_loading/commonjs.js#L126-L130
35,301
JamesMessinger/json-schema-lib
lib/plugins/ArrayDecoderPlugin.js
stripBOM
function stripBOM (str) { var bom = str.charCodeAt(0); // Check for the UTF-16 byte order mark (0xFEFF or 0xFFFE) if (bom === 0xFEFF || bom === 0xFFFE) { return str.slice(1); } return str; }
javascript
function stripBOM (str) { var bom = str.charCodeAt(0); // Check for the UTF-16 byte order mark (0xFEFF or 0xFFFE) if (bom === 0xFEFF || bom === 0xFFFE) { return str.slice(1); } return str; }
[ "function", "stripBOM", "(", "str", ")", "{", "var", "bom", "=", "str", ".", "charCodeAt", "(", "0", ")", ";", "// Check for the UTF-16 byte order mark (0xFEFF or 0xFFFE)", "if", "(", "bom", "===", "0xFEFF", "||", "bom", "===", "0xFFFE", ")", "{", "return", "str", ".", "slice", "(", "1", ")", ";", "}", "return", "str", ";", "}" ]
Removes the UTF-16 byte order mark, if any, from a string. @param {string} str @returns {string}
[ "Removes", "the", "UTF", "-", "16", "byte", "order", "mark", "if", "any", "from", "a", "string", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/ArrayDecoderPlugin.js#L57-L66
35,302
JamesMessinger/json-schema-lib
lib/plugins/JsonPlugin.js
parseFile
function parseFile (args) { var file = args.file; var next = args.next; try { // Optimistically try to parse the file as JSON. return JSON.parse(file.data); } catch (error) { if (isJsonFile(file)) { // This is a JSON file, but its contents are invalid throw error; } else { // This probably isn't a JSON file, so call the next parser plugin next(); } } }
javascript
function parseFile (args) { var file = args.file; var next = args.next; try { // Optimistically try to parse the file as JSON. return JSON.parse(file.data); } catch (error) { if (isJsonFile(file)) { // This is a JSON file, but its contents are invalid throw error; } else { // This probably isn't a JSON file, so call the next parser plugin next(); } } }
[ "function", "parseFile", "(", "args", ")", "{", "var", "file", "=", "args", ".", "file", ";", "var", "next", "=", "args", ".", "next", ";", "try", "{", "// Optimistically try to parse the file as JSON.", "return", "JSON", ".", "parse", "(", "file", ".", "data", ")", ";", "}", "catch", "(", "error", ")", "{", "if", "(", "isJsonFile", "(", "file", ")", ")", "{", "// This is a JSON file, but its contents are invalid", "throw", "error", ";", "}", "else", "{", "// This probably isn't a JSON file, so call the next parser plugin", "next", "(", ")", ";", "}", "}", "}" ]
Parses the given file's data, in place. @param {File} args.file - The {@link File} to parse. @param {function} args.next - Calls the next plugin, if the file data cannot be parsed @returns {*}
[ "Parses", "the", "given", "file", "s", "data", "in", "place", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/JsonPlugin.js#L30-L48
35,303
JamesMessinger/json-schema-lib
lib/plugins/JsonPlugin.js
isJsonFile
function isJsonFile (file) { return file.data && // The file has data (typeof file.data === 'string') && // and it's a string ( mimeTypePattern.test(file.mimeType) || // and it has a JSON MIME type extensionPattern.test(file.url) // or at least a .json file extension ); }
javascript
function isJsonFile (file) { return file.data && // The file has data (typeof file.data === 'string') && // and it's a string ( mimeTypePattern.test(file.mimeType) || // and it has a JSON MIME type extensionPattern.test(file.url) // or at least a .json file extension ); }
[ "function", "isJsonFile", "(", "file", ")", "{", "return", "file", ".", "data", "&&", "// The file has data", "(", "typeof", "file", ".", "data", "===", "'string'", ")", "&&", "// and it's a string", "(", "mimeTypePattern", ".", "test", "(", "file", ".", "mimeType", ")", "||", "// and it has a JSON MIME type", "extensionPattern", ".", "test", "(", "file", ".", "url", ")", "// or at least a .json file extension", ")", ";", "}" ]
Determines whether the file data is JSON @param {File} file @returns {boolean}
[ "Determines", "whether", "the", "file", "data", "is", "JSON" ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/JsonPlugin.js#L57-L64
35,304
claudio-silva/grunt-angular-builder
tasks/middleware/exportRequiredTemplates.js
ExportRequiredTemplatesMiddleware
function ExportRequiredTemplatesMiddleware (context) { var options = context.options.requiredTemplates; var path = require ('path'); /** * Paths of the required templates. * @type {string[]} */ var paths = []; //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { /* jshint unused: vars */ // Do nothing }; this.trace = function (module) { scan (module.head, module.headPath); module.bodies.forEach (function (path, i) { scan (path, module.bodyPaths[i]); }); }; this.build = function (targetScript) { /* jshint unused: vars */ // Export file paths. context.grunt.config (options.exportToConfigProperty, paths); }; //-------------------------------------------------------------------------------------------------------------------- // PRIVATE //-------------------------------------------------------------------------------------------------------------------- /** * Extracts file paths from embedded comment references to templates and appends them to `paths`. * @param {string} sourceCode * @param {string} filePath */ function scan (sourceCode, filePath) { /* jshint -W083 */ var match; while ((match = MATCH_DIRECTIVE.exec (sourceCode))) { match[1].split (',').forEach (function (s) { var url = s.match (/(["'])(.*?)\1/)[2]; paths.push (path.normalize (path.dirname (filePath) + '/' + url)); }); } } }
javascript
function ExportRequiredTemplatesMiddleware (context) { var options = context.options.requiredTemplates; var path = require ('path'); /** * Paths of the required templates. * @type {string[]} */ var paths = []; //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { /* jshint unused: vars */ // Do nothing }; this.trace = function (module) { scan (module.head, module.headPath); module.bodies.forEach (function (path, i) { scan (path, module.bodyPaths[i]); }); }; this.build = function (targetScript) { /* jshint unused: vars */ // Export file paths. context.grunt.config (options.exportToConfigProperty, paths); }; //-------------------------------------------------------------------------------------------------------------------- // PRIVATE //-------------------------------------------------------------------------------------------------------------------- /** * Extracts file paths from embedded comment references to templates and appends them to `paths`. * @param {string} sourceCode * @param {string} filePath */ function scan (sourceCode, filePath) { /* jshint -W083 */ var match; while ((match = MATCH_DIRECTIVE.exec (sourceCode))) { match[1].split (',').forEach (function (s) { var url = s.match (/(["'])(.*?)\1/)[2]; paths.push (path.normalize (path.dirname (filePath) + '/' + url)); }); } } }
[ "function", "ExportRequiredTemplatesMiddleware", "(", "context", ")", "{", "var", "options", "=", "context", ".", "options", ".", "requiredTemplates", ";", "var", "path", "=", "require", "(", "'path'", ")", ";", "/**\n * Paths of the required templates.\n * @type {string[]}\n */", "var", "paths", "=", "[", "]", ";", "//--------------------------------------------------------------------------------------------------------------------", "// PUBLIC API", "//--------------------------------------------------------------------------------------------------------------------", "this", ".", "analyze", "=", "function", "(", "filesArray", ")", "{", "/* jshint unused: vars */", "// Do nothing", "}", ";", "this", ".", "trace", "=", "function", "(", "module", ")", "{", "scan", "(", "module", ".", "head", ",", "module", ".", "headPath", ")", ";", "module", ".", "bodies", ".", "forEach", "(", "function", "(", "path", ",", "i", ")", "{", "scan", "(", "path", ",", "module", ".", "bodyPaths", "[", "i", "]", ")", ";", "}", ")", ";", "}", ";", "this", ".", "build", "=", "function", "(", "targetScript", ")", "{", "/* jshint unused: vars */", "// Export file paths.", "context", ".", "grunt", ".", "config", "(", "options", ".", "exportToConfigProperty", ",", "paths", ")", ";", "}", ";", "//--------------------------------------------------------------------------------------------------------------------", "// PRIVATE", "//--------------------------------------------------------------------------------------------------------------------", "/**\n * Extracts file paths from embedded comment references to templates and appends them to `paths`.\n * @param {string} sourceCode\n * @param {string} filePath\n */", "function", "scan", "(", "sourceCode", ",", "filePath", ")", "{", "/* jshint -W083 */", "var", "match", ";", "while", "(", "(", "match", "=", "MATCH_DIRECTIVE", ".", "exec", "(", "sourceCode", ")", ")", ")", "{", "match", "[", "1", "]", ".", "split", "(", "','", ")", ".", "forEach", "(", "function", "(", "s", ")", "{", "var", "url", "=", "s", ".", "match", "(", "/", "([\"'])(.*?)\\1", "/", ")", "[", "2", "]", ";", "paths", ".", "push", "(", "path", ".", "normalize", "(", "path", ".", "dirname", "(", "filePath", ")", "+", "'/'", "+", "url", ")", ")", ";", "}", ")", ";", "}", "}", "}" ]
Exports to Grunt's global configuration the paths of all templates required by the application, in the order defined by the modules' dependency graph. @constructor @implements {MiddlewareInterface} @param {Context} context The execution context for the middleware stack.
[ "Exports", "to", "Grunt", "s", "global", "configuration", "the", "paths", "of", "all", "templates", "required", "by", "the", "application", "in", "the", "order", "defined", "by", "the", "modules", "dependency", "graph", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/exportRequiredTemplates.js#L59-L119
35,305
JamesMessinger/json-schema-lib
lib/api/FileArray.js
findFile
function findFile (schema, url) { if (schema.files.length === 0) { return null; } if (url instanceof File) { // Short-circuit behavior for File obejcts return findByURL(schema.files, url.url); } // Try to find an exact URL match var file = findByURL(schema.files, url); if (!file) { // Resolve the URL and see if we can find a match var absoluteURL = schema.plugins.resolveURL({ from: schema.rootURL, to: url }); file = findByURL(schema.files, absoluteURL); } return file; }
javascript
function findFile (schema, url) { if (schema.files.length === 0) { return null; } if (url instanceof File) { // Short-circuit behavior for File obejcts return findByURL(schema.files, url.url); } // Try to find an exact URL match var file = findByURL(schema.files, url); if (!file) { // Resolve the URL and see if we can find a match var absoluteURL = schema.plugins.resolveURL({ from: schema.rootURL, to: url }); file = findByURL(schema.files, absoluteURL); } return file; }
[ "function", "findFile", "(", "schema", ",", "url", ")", "{", "if", "(", "schema", ".", "files", ".", "length", "===", "0", ")", "{", "return", "null", ";", "}", "if", "(", "url", "instanceof", "File", ")", "{", "// Short-circuit behavior for File obejcts", "return", "findByURL", "(", "schema", ".", "files", ",", "url", ".", "url", ")", ";", "}", "// Try to find an exact URL match", "var", "file", "=", "findByURL", "(", "schema", ".", "files", ",", "url", ")", ";", "if", "(", "!", "file", ")", "{", "// Resolve the URL and see if we can find a match", "var", "absoluteURL", "=", "schema", ".", "plugins", ".", "resolveURL", "(", "{", "from", ":", "schema", ".", "rootURL", ",", "to", ":", "url", "}", ")", ";", "file", "=", "findByURL", "(", "schema", ".", "files", ",", "absoluteURL", ")", ";", "}", "return", "file", ";", "}" ]
Finds the given file in the schema @param {Schema} schema @param {string|File} url An absolute URL, or a relative URL (relative to the schema's root file), or a {@link File} object @returns {?File}
[ "Finds", "the", "given", "file", "in", "the", "schema" ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/FileArray.js#L82-L102
35,306
JamesMessinger/json-schema-lib
lib/api/FileArray.js
findByURL
function findByURL (files, url) { for (var i = 0; i < files.length; i++) { var file = files[i]; if (file.url === url) { return file; } } }
javascript
function findByURL (files, url) { for (var i = 0; i < files.length; i++) { var file = files[i]; if (file.url === url) { return file; } } }
[ "function", "findByURL", "(", "files", ",", "url", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "files", ".", "length", ";", "i", "++", ")", "{", "var", "file", "=", "files", "[", "i", "]", ";", "if", "(", "file", ".", "url", "===", "url", ")", "{", "return", "file", ";", "}", "}", "}" ]
Finds a file by its exact URL @param {FileArray} files @param {string} url @returns {?File}
[ "Finds", "a", "file", "by", "its", "exact", "URL" ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/FileArray.js#L111-L118
35,307
genie-js/genie-drs
src/DRS.js
function (num) { for (var ext = '', i = 0; i < 4; i++) { ext = String.fromCharCode(num & 0xFF) + ext num >>= 8 } return ext }
javascript
function (num) { for (var ext = '', i = 0; i < 4; i++) { ext = String.fromCharCode(num & 0xFF) + ext num >>= 8 } return ext }
[ "function", "(", "num", ")", "{", "for", "(", "var", "ext", "=", "''", ",", "i", "=", "0", ";", "i", "<", "4", ";", "i", "++", ")", "{", "ext", "=", "String", ".", "fromCharCode", "(", "num", "&", "0xFF", ")", "+", "ext", "num", ">>=", "8", "}", "return", "ext", "}" ]
Parse a numeric table type to a string.
[ "Parse", "a", "numeric", "table", "type", "to", "a", "string", "." ]
45535b6836c62d269cc6f30889fe6f43113f8dcf
https://github.com/genie-js/genie-drs/blob/45535b6836c62d269cc6f30889fe6f43113f8dcf/src/DRS.js#L33-L39
35,308
genie-js/genie-drs
src/DRS.js
function (str) { while (str.length < 4) str += ' ' for (var num = 0, i = 0; i < 4; i++) { num = (num << 8) + str.charCodeAt(i) } return num }
javascript
function (str) { while (str.length < 4) str += ' ' for (var num = 0, i = 0; i < 4; i++) { num = (num << 8) + str.charCodeAt(i) } return num }
[ "function", "(", "str", ")", "{", "while", "(", "str", ".", "length", "<", "4", ")", "str", "+=", "' '", "for", "(", "var", "num", "=", "0", ",", "i", "=", "0", ";", "i", "<", "4", ";", "i", "++", ")", "{", "num", "=", "(", "num", "<<", "8", ")", "+", "str", ".", "charCodeAt", "(", "i", ")", "}", "return", "num", "}" ]
Serialize a table type string to a 32-bit integer.
[ "Serialize", "a", "table", "type", "string", "to", "a", "32", "-", "bit", "integer", "." ]
45535b6836c62d269cc6f30889fe6f43113f8dcf
https://github.com/genie-js/genie-drs/blob/45535b6836c62d269cc6f30889fe6f43113f8dcf/src/DRS.js#L42-L48
35,309
genie-js/genie-drs
src/DRS.js
DRS
function DRS (file) { if (!(this instanceof DRS)) return new DRS(file) this.tables = [] this.isSWGB = null if (typeof file === 'undefined') { file = {} } if (typeof file === 'string') { if (typeof FsSource !== 'function') { throw new Error('Cannot instantiate with a string filename in the browser') } this.source = new FsSource(file) } else if (typeof Blob !== 'undefined' && file instanceof Blob) { // eslint-disable-line no-undef this.source = new BlobSource(file) } else { if (typeof file !== 'object') { throw new TypeError('Expected a file path string or an options object, got ' + typeof file) } this.isSWGB = file.hasOwnProperty('isSWGB') ? file.isSWGB : false this.copyright = file.hasOwnProperty('copyright') ? file.copyright : (this.isSWGB ? COPYRIGHT_SWGB : COPYRIGHT_AOE) this.fileVersion = file.hasOwnProperty('fileVersion') ? file.fileVersion : '1.00' this.fileType = file.hasOwnProperty('fileType') ? file.fileType : 'tribe\0\0\0\0\0\0\0' } }
javascript
function DRS (file) { if (!(this instanceof DRS)) return new DRS(file) this.tables = [] this.isSWGB = null if (typeof file === 'undefined') { file = {} } if (typeof file === 'string') { if (typeof FsSource !== 'function') { throw new Error('Cannot instantiate with a string filename in the browser') } this.source = new FsSource(file) } else if (typeof Blob !== 'undefined' && file instanceof Blob) { // eslint-disable-line no-undef this.source = new BlobSource(file) } else { if (typeof file !== 'object') { throw new TypeError('Expected a file path string or an options object, got ' + typeof file) } this.isSWGB = file.hasOwnProperty('isSWGB') ? file.isSWGB : false this.copyright = file.hasOwnProperty('copyright') ? file.copyright : (this.isSWGB ? COPYRIGHT_SWGB : COPYRIGHT_AOE) this.fileVersion = file.hasOwnProperty('fileVersion') ? file.fileVersion : '1.00' this.fileType = file.hasOwnProperty('fileType') ? file.fileType : 'tribe\0\0\0\0\0\0\0' } }
[ "function", "DRS", "(", "file", ")", "{", "if", "(", "!", "(", "this", "instanceof", "DRS", ")", ")", "return", "new", "DRS", "(", "file", ")", "this", ".", "tables", "=", "[", "]", "this", ".", "isSWGB", "=", "null", "if", "(", "typeof", "file", "===", "'undefined'", ")", "{", "file", "=", "{", "}", "}", "if", "(", "typeof", "file", "===", "'string'", ")", "{", "if", "(", "typeof", "FsSource", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "'Cannot instantiate with a string filename in the browser'", ")", "}", "this", ".", "source", "=", "new", "FsSource", "(", "file", ")", "}", "else", "if", "(", "typeof", "Blob", "!==", "'undefined'", "&&", "file", "instanceof", "Blob", ")", "{", "// eslint-disable-line no-undef", "this", ".", "source", "=", "new", "BlobSource", "(", "file", ")", "}", "else", "{", "if", "(", "typeof", "file", "!==", "'object'", ")", "{", "throw", "new", "TypeError", "(", "'Expected a file path string or an options object, got '", "+", "typeof", "file", ")", "}", "this", ".", "isSWGB", "=", "file", ".", "hasOwnProperty", "(", "'isSWGB'", ")", "?", "file", ".", "isSWGB", ":", "false", "this", ".", "copyright", "=", "file", ".", "hasOwnProperty", "(", "'copyright'", ")", "?", "file", ".", "copyright", ":", "(", "this", ".", "isSWGB", "?", "COPYRIGHT_SWGB", ":", "COPYRIGHT_AOE", ")", "this", ".", "fileVersion", "=", "file", ".", "hasOwnProperty", "(", "'fileVersion'", ")", "?", "file", ".", "fileVersion", ":", "'1.00'", "this", ".", "fileType", "=", "file", ".", "hasOwnProperty", "(", "'fileType'", ")", "?", "file", ".", "fileType", ":", "'tribe\\0\\0\\0\\0\\0\\0\\0'", "}", "}" ]
Represents a DRS file. @constructor @param {string} file Path to a .DRS file.
[ "Represents", "a", "DRS", "file", "." ]
45535b6836c62d269cc6f30889fe6f43113f8dcf
https://github.com/genie-js/genie-drs/blob/45535b6836c62d269cc6f30889fe6f43113f8dcf/src/DRS.js#L71-L98
35,310
claudio-silva/grunt-angular-builder
tasks/middleware/exportSourcePaths.js
ExportSourceCodePathsMiddleware
function ExportSourceCodePathsMiddleware (context) { var options = context.options.sourcePaths; /** * Paths of all the required files (excluding standalone scripts) in the correct loading order. * @type {string[]} */ var tracedPaths = []; //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { /* jshint unused: vars */ // Do nothing }; this.trace = function (module) { tracedPaths.push (module.headPath); arrayAppend (tracedPaths, module.bodyPaths); }; this.build = function (targetScript) { /* jshint unused: vars */ var scripts = []; // Include paths of forced-include scripts. if (context.standaloneScripts.length) arrayAppend (scripts, context.standaloneScripts.map (function (e) { return e.path; })); // Include all module files. arrayAppend (scripts, tracedPaths); // Export. context.grunt.config (options.exportToConfigProperty, scripts); }; }
javascript
function ExportSourceCodePathsMiddleware (context) { var options = context.options.sourcePaths; /** * Paths of all the required files (excluding standalone scripts) in the correct loading order. * @type {string[]} */ var tracedPaths = []; //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { /* jshint unused: vars */ // Do nothing }; this.trace = function (module) { tracedPaths.push (module.headPath); arrayAppend (tracedPaths, module.bodyPaths); }; this.build = function (targetScript) { /* jshint unused: vars */ var scripts = []; // Include paths of forced-include scripts. if (context.standaloneScripts.length) arrayAppend (scripts, context.standaloneScripts.map (function (e) { return e.path; })); // Include all module files. arrayAppend (scripts, tracedPaths); // Export. context.grunt.config (options.exportToConfigProperty, scripts); }; }
[ "function", "ExportSourceCodePathsMiddleware", "(", "context", ")", "{", "var", "options", "=", "context", ".", "options", ".", "sourcePaths", ";", "/**\n * Paths of all the required files (excluding standalone scripts) in the correct loading order.\n * @type {string[]}\n */", "var", "tracedPaths", "=", "[", "]", ";", "//--------------------------------------------------------------------------------------------------------------------", "// PUBLIC API", "//--------------------------------------------------------------------------------------------------------------------", "this", ".", "analyze", "=", "function", "(", "filesArray", ")", "{", "/* jshint unused: vars */", "// Do nothing", "}", ";", "this", ".", "trace", "=", "function", "(", "module", ")", "{", "tracedPaths", ".", "push", "(", "module", ".", "headPath", ")", ";", "arrayAppend", "(", "tracedPaths", ",", "module", ".", "bodyPaths", ")", ";", "}", ";", "this", ".", "build", "=", "function", "(", "targetScript", ")", "{", "/* jshint unused: vars */", "var", "scripts", "=", "[", "]", ";", "// Include paths of forced-include scripts.", "if", "(", "context", ".", "standaloneScripts", ".", "length", ")", "arrayAppend", "(", "scripts", ",", "context", ".", "standaloneScripts", ".", "map", "(", "function", "(", "e", ")", "{", "return", "e", ".", "path", ";", "}", ")", ")", ";", "// Include all module files.", "arrayAppend", "(", "scripts", ",", "tracedPaths", ")", ";", "// Export.", "context", ".", "grunt", ".", "config", "(", "options", ".", "exportToConfigProperty", ",", "scripts", ")", ";", "}", ";", "}" ]
Exports to Grunt's global configuration the paths of all script files that are required by the application, in the order defined by the modules' dependency graph. @constructor @implements {MiddlewareInterface} @param {Context} context The execution context for the middleware stack.
[ "Exports", "to", "Grunt", "s", "global", "configuration", "the", "paths", "of", "all", "script", "files", "that", "are", "required", "by", "the", "application", "in", "the", "order", "defined", "by", "the", "modules", "dependency", "graph", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/exportSourcePaths.js#L61-L108
35,311
matteodelabre/midijs
lib/connect/driver.js
Driver
function Driver(native) { var outputs = [], inputs = [], length, i; EventEmitter.call(this); this.native = native; length = native.outputs.size; for (i = 0; i < length; i += 1) { outputs[i] = new Output(native.outputs.get(i)); } length = native.inputs.size; for (i = 0; i < length; i += 1) { inputs[i] = new Input(native.inputs.get(i)); } this.outputs = outputs; this.output = null; this.inputs = inputs; this.input = null; native.onconnect = function (event) { var port = event.port; if (port.type === 'input') { port = new Input(port); this.inputs.push(port); } else { port = new Output(port); this.outputs.push(port); } this.emit('connect', port); }.bind(this); native.ondisconnect = function (event) { var port = event.port; if (port.type === 'input') { port = new Input(port); this.inputs = this.inputs.filter(function (input) { return (input.id !== port.id); }); } else { port = new Output(port); this.outputs = this.outputs.filter(function (output) { return (output.id !== port.id); }); } this.emit('disconnect', port); }.bind(this); }
javascript
function Driver(native) { var outputs = [], inputs = [], length, i; EventEmitter.call(this); this.native = native; length = native.outputs.size; for (i = 0; i < length; i += 1) { outputs[i] = new Output(native.outputs.get(i)); } length = native.inputs.size; for (i = 0; i < length; i += 1) { inputs[i] = new Input(native.inputs.get(i)); } this.outputs = outputs; this.output = null; this.inputs = inputs; this.input = null; native.onconnect = function (event) { var port = event.port; if (port.type === 'input') { port = new Input(port); this.inputs.push(port); } else { port = new Output(port); this.outputs.push(port); } this.emit('connect', port); }.bind(this); native.ondisconnect = function (event) { var port = event.port; if (port.type === 'input') { port = new Input(port); this.inputs = this.inputs.filter(function (input) { return (input.id !== port.id); }); } else { port = new Output(port); this.outputs = this.outputs.filter(function (output) { return (output.id !== port.id); }); } this.emit('disconnect', port); }.bind(this); }
[ "function", "Driver", "(", "native", ")", "{", "var", "outputs", "=", "[", "]", ",", "inputs", "=", "[", "]", ",", "length", ",", "i", ";", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "native", "=", "native", ";", "length", "=", "native", ".", "outputs", ".", "size", ";", "for", "(", "i", "=", "0", ";", "i", "<", "length", ";", "i", "+=", "1", ")", "{", "outputs", "[", "i", "]", "=", "new", "Output", "(", "native", ".", "outputs", ".", "get", "(", "i", ")", ")", ";", "}", "length", "=", "native", ".", "inputs", ".", "size", ";", "for", "(", "i", "=", "0", ";", "i", "<", "length", ";", "i", "+=", "1", ")", "{", "inputs", "[", "i", "]", "=", "new", "Input", "(", "native", ".", "inputs", ".", "get", "(", "i", ")", ")", ";", "}", "this", ".", "outputs", "=", "outputs", ";", "this", ".", "output", "=", "null", ";", "this", ".", "inputs", "=", "inputs", ";", "this", ".", "input", "=", "null", ";", "native", ".", "onconnect", "=", "function", "(", "event", ")", "{", "var", "port", "=", "event", ".", "port", ";", "if", "(", "port", ".", "type", "===", "'input'", ")", "{", "port", "=", "new", "Input", "(", "port", ")", ";", "this", ".", "inputs", ".", "push", "(", "port", ")", ";", "}", "else", "{", "port", "=", "new", "Output", "(", "port", ")", ";", "this", ".", "outputs", ".", "push", "(", "port", ")", ";", "}", "this", ".", "emit", "(", "'connect'", ",", "port", ")", ";", "}", ".", "bind", "(", "this", ")", ";", "native", ".", "ondisconnect", "=", "function", "(", "event", ")", "{", "var", "port", "=", "event", ".", "port", ";", "if", "(", "port", ".", "type", "===", "'input'", ")", "{", "port", "=", "new", "Input", "(", "port", ")", ";", "this", ".", "inputs", "=", "this", ".", "inputs", ".", "filter", "(", "function", "(", "input", ")", "{", "return", "(", "input", ".", "id", "!==", "port", ".", "id", ")", ";", "}", ")", ";", "}", "else", "{", "port", "=", "new", "Output", "(", "port", ")", ";", "this", ".", "outputs", "=", "this", ".", "outputs", ".", "filter", "(", "function", "(", "output", ")", "{", "return", "(", "output", ".", "id", "!==", "port", ".", "id", ")", ";", "}", ")", ";", "}", "this", ".", "emit", "(", "'disconnect'", ",", "port", ")", ";", "}", ".", "bind", "(", "this", ")", ";", "}" ]
Construct a new Driver @class Driver @extends events.EventEmitter @classdesc Enable you to access all the plugged-in MIDI devices and to control them @param {MIDIAccess} native Native MIDI access
[ "Construct", "a", "new", "Driver" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/connect/driver.js#L19-L73
35,312
claudio-silva/grunt-angular-builder
tasks/lib/types.js
Context
function Context (grunt, task, defaultOptions) { this.grunt = grunt; this.options = extend ({}, defaultOptions, task.options ()); switch (this.options.buildMode) { case 'release': this.options.debugBuild.enabled = false; this.options.releaseBuild.enabled = true; break; case 'debug': this.options.debugBuild.enabled = true; this.options.releaseBuild.enabled = false; } if (task.flags.debug !== undefined || grunt.option ('build') === 'debug') { this.options.debugBuild.enabled = true; this.options.releaseBuild.enabled = false; } this.verbose = grunt.option ('verbose'); // Clone the external modules and use it as a starting point. this.modules = extend ({}, this._setupExternalModules ()); // Reset tracer. this.loaded = {}; this.outputtedFiles = {}; this.filesRefCount = {}; // Reset the scripts list to a clone of the `require` option or to an empty list. this.standaloneScripts = (this.options.require || []).slice (); this.shared = {}; this._events = {}; }
javascript
function Context (grunt, task, defaultOptions) { this.grunt = grunt; this.options = extend ({}, defaultOptions, task.options ()); switch (this.options.buildMode) { case 'release': this.options.debugBuild.enabled = false; this.options.releaseBuild.enabled = true; break; case 'debug': this.options.debugBuild.enabled = true; this.options.releaseBuild.enabled = false; } if (task.flags.debug !== undefined || grunt.option ('build') === 'debug') { this.options.debugBuild.enabled = true; this.options.releaseBuild.enabled = false; } this.verbose = grunt.option ('verbose'); // Clone the external modules and use it as a starting point. this.modules = extend ({}, this._setupExternalModules ()); // Reset tracer. this.loaded = {}; this.outputtedFiles = {}; this.filesRefCount = {}; // Reset the scripts list to a clone of the `require` option or to an empty list. this.standaloneScripts = (this.options.require || []).slice (); this.shared = {}; this._events = {}; }
[ "function", "Context", "(", "grunt", ",", "task", ",", "defaultOptions", ")", "{", "this", ".", "grunt", "=", "grunt", ";", "this", ".", "options", "=", "extend", "(", "{", "}", ",", "defaultOptions", ",", "task", ".", "options", "(", ")", ")", ";", "switch", "(", "this", ".", "options", ".", "buildMode", ")", "{", "case", "'release'", ":", "this", ".", "options", ".", "debugBuild", ".", "enabled", "=", "false", ";", "this", ".", "options", ".", "releaseBuild", ".", "enabled", "=", "true", ";", "break", ";", "case", "'debug'", ":", "this", ".", "options", ".", "debugBuild", ".", "enabled", "=", "true", ";", "this", ".", "options", ".", "releaseBuild", ".", "enabled", "=", "false", ";", "}", "if", "(", "task", ".", "flags", ".", "debug", "!==", "undefined", "||", "grunt", ".", "option", "(", "'build'", ")", "===", "'debug'", ")", "{", "this", ".", "options", ".", "debugBuild", ".", "enabled", "=", "true", ";", "this", ".", "options", ".", "releaseBuild", ".", "enabled", "=", "false", ";", "}", "this", ".", "verbose", "=", "grunt", ".", "option", "(", "'verbose'", ")", ";", "// Clone the external modules and use it as a starting point.", "this", ".", "modules", "=", "extend", "(", "{", "}", ",", "this", ".", "_setupExternalModules", "(", ")", ")", ";", "// Reset tracer.", "this", ".", "loaded", "=", "{", "}", ";", "this", ".", "outputtedFiles", "=", "{", "}", ";", "this", ".", "filesRefCount", "=", "{", "}", ";", "// Reset the scripts list to a clone of the `require` option or to an empty list.", "this", ".", "standaloneScripts", "=", "(", "this", ".", "options", ".", "require", "||", "[", "]", ")", ".", "slice", "(", ")", ";", "this", ".", "shared", "=", "{", "}", ";", "this", ".", "_events", "=", "{", "}", ";", "}" ]
The execution context for the middleware stack. Contains shared information available throughout the middleware stack. @constructor @param grunt The Grunt API. @param task The currently executing Grunt task. @param {TaskOptions} defaultOptions The default values for all of the Angular Builder's options, including all middleware options.
[ "The", "execution", "context", "for", "the", "middleware", "stack", ".", "Contains", "shared", "information", "available", "throughout", "the", "middleware", "stack", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/lib/types.js#L230-L258
35,313
claudio-silva/grunt-angular-builder
tasks/lib/types.js
function (eventName, handler) { if (!this._events[eventName]) this._events[eventName] = []; this._events[eventName].push (handler); }
javascript
function (eventName, handler) { if (!this._events[eventName]) this._events[eventName] = []; this._events[eventName].push (handler); }
[ "function", "(", "eventName", ",", "handler", ")", "{", "if", "(", "!", "this", ".", "_events", "[", "eventName", "]", ")", "this", ".", "_events", "[", "eventName", "]", "=", "[", "]", ";", "this", ".", "_events", "[", "eventName", "]", ".", "push", "(", "handler", ")", ";", "}" ]
Registers an event handler. @param {ContextEvent} eventName @param {function()} handler
[ "Registers", "an", "event", "handler", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/lib/types.js#L328-L333
35,314
claudio-silva/grunt-angular-builder
tasks/lib/types.js
function (eventName, args) { var e = this._events[eventName]; if (e) { args = args || []; e.forEach (function (handler) { handler.apply (this, args); }); } }
javascript
function (eventName, args) { var e = this._events[eventName]; if (e) { args = args || []; e.forEach (function (handler) { handler.apply (this, args); }); } }
[ "function", "(", "eventName", ",", "args", ")", "{", "var", "e", "=", "this", ".", "_events", "[", "eventName", "]", ";", "if", "(", "e", ")", "{", "args", "=", "args", "||", "[", "]", ";", "e", ".", "forEach", "(", "function", "(", "handler", ")", "{", "handler", ".", "apply", "(", "this", ",", "args", ")", ";", "}", ")", ";", "}", "}" ]
Calls all registered event handlers for the specified event. @param {ContextEvent} eventName @param {Array?} args
[ "Calls", "all", "registered", "event", "handlers", "for", "the", "specified", "event", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/lib/types.js#L339-L349
35,315
claudio-silva/grunt-angular-builder
tasks/lib/types.js
function () { /** @type {Object.<string, ModuleDef>} */ var modules = {}; ((typeof this.options.externalModules === 'string' ? [this.options.externalModules] : this.options.externalModules ) || []). concat (this.options.builtinModules). forEach (function (moduleName) { // Ignore redundant names. if (!modules[moduleName]) { /** @type {ModuleDef} */ var module = modules[moduleName] = new ModuleDef (moduleName); module.external = true; } }); return modules; }
javascript
function () { /** @type {Object.<string, ModuleDef>} */ var modules = {}; ((typeof this.options.externalModules === 'string' ? [this.options.externalModules] : this.options.externalModules ) || []). concat (this.options.builtinModules). forEach (function (moduleName) { // Ignore redundant names. if (!modules[moduleName]) { /** @type {ModuleDef} */ var module = modules[moduleName] = new ModuleDef (moduleName); module.external = true; } }); return modules; }
[ "function", "(", ")", "{", "/** @type {Object.<string, ModuleDef>} */", "var", "modules", "=", "{", "}", ";", "(", "(", "typeof", "this", ".", "options", ".", "externalModules", "===", "'string'", "?", "[", "this", ".", "options", ".", "externalModules", "]", ":", "this", ".", "options", ".", "externalModules", ")", "||", "[", "]", ")", ".", "concat", "(", "this", ".", "options", ".", "builtinModules", ")", ".", "forEach", "(", "function", "(", "moduleName", ")", "{", "// Ignore redundant names.", "if", "(", "!", "modules", "[", "moduleName", "]", ")", "{", "/** @type {ModuleDef} */", "var", "module", "=", "modules", "[", "moduleName", "]", "=", "new", "ModuleDef", "(", "moduleName", ")", ";", "module", ".", "external", "=", "true", ";", "}", "}", ")", ";", "return", "modules", ";", "}" ]
Registers the configured external modules so that they can be ignored during the build output generation. @returns {Object.<string, ModuleDef>} @private
[ "Registers", "the", "configured", "external", "modules", "so", "that", "they", "can", "be", "ignored", "during", "the", "build", "output", "generation", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/lib/types.js#L355-L373
35,316
glennjones/elsewhere-profiles
lib/profile.js
function(urls){ if(this.hCards.length > -1){ // remove all organisational hCards using fn = org.organization-name pattern var i = this.hCards.length; while (i--) { if(this.hCards[i].org && this.hCards[i].org[0]['organization-name']){ if( this.hCards[i].fn === this.hCards[i].org[0]['organization-name'] ){ this.hCards.splice(i,1); } } } // if there is only one hcard use that if(this.hCards.length === 1){ this.representativehCard = this.hCards[0]; }else{ i = this.hCards.length; var x = 0; while (x < i) { var hcard = this.hCards[x]; if(hcard.url){ // match the urls of the hcard to the known urls for (var y = 0; y < urls.length; y++) { for (var z = 0; z < hcard.url.length; z++) { if( utils.compareUrl(urls[y], hcard.url[z]) ){ this.representativehCard = hcard; } } } // match the xfn urls of the page to hcard urls if(this.xfn.length > -1){ for (var z = 0; z < this.xfn.length; z++) { for (var y = 0; y < hcard.url.length; y++) { if( this.xfn[z].link !== undefined && this.xfn[z].rel !== undefined && utils.compareUrl(hcard.url[y], this.xfn[z].link) && this.xfn[z].rel === 'me'){ this.representativehCard = hcard; } } } } } x++; } } } // if we have a hresume use contact hcard if(this.hResumes.length !== 0){ if(this.hResumes[0].contact){ this.representativehCard = this.hResumes[0].contact // description if(this.hResumes[0].summary !== '') this.representativehCard.note = this.hResumes[0].summary; // job role // org } } this.filterRepresentativehCard(); }
javascript
function(urls){ if(this.hCards.length > -1){ // remove all organisational hCards using fn = org.organization-name pattern var i = this.hCards.length; while (i--) { if(this.hCards[i].org && this.hCards[i].org[0]['organization-name']){ if( this.hCards[i].fn === this.hCards[i].org[0]['organization-name'] ){ this.hCards.splice(i,1); } } } // if there is only one hcard use that if(this.hCards.length === 1){ this.representativehCard = this.hCards[0]; }else{ i = this.hCards.length; var x = 0; while (x < i) { var hcard = this.hCards[x]; if(hcard.url){ // match the urls of the hcard to the known urls for (var y = 0; y < urls.length; y++) { for (var z = 0; z < hcard.url.length; z++) { if( utils.compareUrl(urls[y], hcard.url[z]) ){ this.representativehCard = hcard; } } } // match the xfn urls of the page to hcard urls if(this.xfn.length > -1){ for (var z = 0; z < this.xfn.length; z++) { for (var y = 0; y < hcard.url.length; y++) { if( this.xfn[z].link !== undefined && this.xfn[z].rel !== undefined && utils.compareUrl(hcard.url[y], this.xfn[z].link) && this.xfn[z].rel === 'me'){ this.representativehCard = hcard; } } } } } x++; } } } // if we have a hresume use contact hcard if(this.hResumes.length !== 0){ if(this.hResumes[0].contact){ this.representativehCard = this.hResumes[0].contact // description if(this.hResumes[0].summary !== '') this.representativehCard.note = this.hResumes[0].summary; // job role // org } } this.filterRepresentativehCard(); }
[ "function", "(", "urls", ")", "{", "if", "(", "this", ".", "hCards", ".", "length", ">", "-", "1", ")", "{", "// remove all organisational hCards using fn = org.organization-name pattern", "var", "i", "=", "this", ".", "hCards", ".", "length", ";", "while", "(", "i", "--", ")", "{", "if", "(", "this", ".", "hCards", "[", "i", "]", ".", "org", "&&", "this", ".", "hCards", "[", "i", "]", ".", "org", "[", "0", "]", "[", "'organization-name'", "]", ")", "{", "if", "(", "this", ".", "hCards", "[", "i", "]", ".", "fn", "===", "this", ".", "hCards", "[", "i", "]", ".", "org", "[", "0", "]", "[", "'organization-name'", "]", ")", "{", "this", ".", "hCards", ".", "splice", "(", "i", ",", "1", ")", ";", "}", "}", "}", "// if there is only one hcard use that", "if", "(", "this", ".", "hCards", ".", "length", "===", "1", ")", "{", "this", ".", "representativehCard", "=", "this", ".", "hCards", "[", "0", "]", ";", "}", "else", "{", "i", "=", "this", ".", "hCards", ".", "length", ";", "var", "x", "=", "0", ";", "while", "(", "x", "<", "i", ")", "{", "var", "hcard", "=", "this", ".", "hCards", "[", "x", "]", ";", "if", "(", "hcard", ".", "url", ")", "{", "// match the urls of the hcard to the known urls", "for", "(", "var", "y", "=", "0", ";", "y", "<", "urls", ".", "length", ";", "y", "++", ")", "{", "for", "(", "var", "z", "=", "0", ";", "z", "<", "hcard", ".", "url", ".", "length", ";", "z", "++", ")", "{", "if", "(", "utils", ".", "compareUrl", "(", "urls", "[", "y", "]", ",", "hcard", ".", "url", "[", "z", "]", ")", ")", "{", "this", ".", "representativehCard", "=", "hcard", ";", "}", "}", "}", "// match the xfn urls of the page to hcard urls", "if", "(", "this", ".", "xfn", ".", "length", ">", "-", "1", ")", "{", "for", "(", "var", "z", "=", "0", ";", "z", "<", "this", ".", "xfn", ".", "length", ";", "z", "++", ")", "{", "for", "(", "var", "y", "=", "0", ";", "y", "<", "hcard", ".", "url", ".", "length", ";", "y", "++", ")", "{", "if", "(", "this", ".", "xfn", "[", "z", "]", ".", "link", "!==", "undefined", "&&", "this", ".", "xfn", "[", "z", "]", ".", "rel", "!==", "undefined", "&&", "utils", ".", "compareUrl", "(", "hcard", ".", "url", "[", "y", "]", ",", "this", ".", "xfn", "[", "z", "]", ".", "link", ")", "&&", "this", ".", "xfn", "[", "z", "]", ".", "rel", "===", "'me'", ")", "{", "this", ".", "representativehCard", "=", "hcard", ";", "}", "}", "}", "}", "}", "x", "++", ";", "}", "}", "}", "// if we have a hresume use contact hcard", "if", "(", "this", ".", "hResumes", ".", "length", "!==", "0", ")", "{", "if", "(", "this", ".", "hResumes", "[", "0", "]", ".", "contact", ")", "{", "this", ".", "representativehCard", "=", "this", ".", "hResumes", "[", "0", "]", ".", "contact", "// description", "if", "(", "this", ".", "hResumes", "[", "0", "]", ".", "summary", "!==", "''", ")", "this", ".", "representativehCard", ".", "note", "=", "this", ".", "hResumes", "[", "0", "]", ".", "summary", ";", "// job role", "// org", "}", "}", "this", ".", "filterRepresentativehCard", "(", ")", ";", "}" ]
using representative hCard parsing rules to find the right hCard
[ "using", "representative", "hCard", "parsing", "rules", "to", "find", "the", "right", "hCard" ]
f86a5d040d540d4f8ed4f86518b75a0e6c8855ba
https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/profile.js#L24-L93
35,317
glennjones/elsewhere-profiles
lib/profile.js
function(){ var i = filters.length, x = 0, urlObj = url.parse(this.url, parseQueryString=false); while (x < i) { if(filters[x].domain === urlObj.hostname){ for (var y = 0; y < filters[x].hCardBlockList.length; y++) { delete this.representativehCard.properties[filters[x].hCardBlockList[y]]; } } x++; } }
javascript
function(){ var i = filters.length, x = 0, urlObj = url.parse(this.url, parseQueryString=false); while (x < i) { if(filters[x].domain === urlObj.hostname){ for (var y = 0; y < filters[x].hCardBlockList.length; y++) { delete this.representativehCard.properties[filters[x].hCardBlockList[y]]; } } x++; } }
[ "function", "(", ")", "{", "var", "i", "=", "filters", ".", "length", ",", "x", "=", "0", ",", "urlObj", "=", "url", ".", "parse", "(", "this", ".", "url", ",", "parseQueryString", "=", "false", ")", ";", "while", "(", "x", "<", "i", ")", "{", "if", "(", "filters", "[", "x", "]", ".", "domain", "===", "urlObj", ".", "hostname", ")", "{", "for", "(", "var", "y", "=", "0", ";", "y", "<", "filters", "[", "x", "]", ".", "hCardBlockList", ".", "length", ";", "y", "++", ")", "{", "delete", "this", ".", "representativehCard", ".", "properties", "[", "filters", "[", "x", "]", ".", "hCardBlockList", "[", "y", "]", "]", ";", "}", "}", "x", "++", ";", "}", "}" ]
loops through the filter and deletes properties in the block list from the matching domains representative hCard
[ "loops", "through", "the", "filter", "and", "deletes", "properties", "in", "the", "block", "list", "from", "the", "matching", "domains", "representative", "hCard" ]
f86a5d040d540d4f8ed4f86518b75a0e6c8855ba
https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/profile.js#L98-L111
35,318
nattreid/cms
assets/js/cms.bundled.js
winnow
function winnow( elements, qualifier, not ) { if ( isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { return !!qualifier.call( elem, i, elem ) !== not; } ); } // Single element if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; } ); } // Arraylike of elements (jQuery, arguments, Array) if ( typeof qualifier !== "string" ) { return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) > -1 ) !== not; } ); } // Filtered directly for both simple and complex selectors return jQuery.filter( qualifier, elements, not ); }
javascript
function winnow( elements, qualifier, not ) { if ( isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { return !!qualifier.call( elem, i, elem ) !== not; } ); } // Single element if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; } ); } // Arraylike of elements (jQuery, arguments, Array) if ( typeof qualifier !== "string" ) { return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) > -1 ) !== not; } ); } // Filtered directly for both simple and complex selectors return jQuery.filter( qualifier, elements, not ); }
[ "function", "winnow", "(", "elements", ",", "qualifier", ",", "not", ")", "{", "if", "(", "isFunction", "(", "qualifier", ")", ")", "{", "return", "jQuery", ".", "grep", "(", "elements", ",", "function", "(", "elem", ",", "i", ")", "{", "return", "!", "!", "qualifier", ".", "call", "(", "elem", ",", "i", ",", "elem", ")", "!==", "not", ";", "}", ")", ";", "}", "// Single element", "if", "(", "qualifier", ".", "nodeType", ")", "{", "return", "jQuery", ".", "grep", "(", "elements", ",", "function", "(", "elem", ")", "{", "return", "(", "elem", "===", "qualifier", ")", "!==", "not", ";", "}", ")", ";", "}", "// Arraylike of elements (jQuery, arguments, Array)", "if", "(", "typeof", "qualifier", "!==", "\"string\"", ")", "{", "return", "jQuery", ".", "grep", "(", "elements", ",", "function", "(", "elem", ")", "{", "return", "(", "indexOf", ".", "call", "(", "qualifier", ",", "elem", ")", ">", "-", "1", ")", "!==", "not", ";", "}", ")", ";", "}", "// Filtered directly for both simple and complex selectors", "return", "jQuery", ".", "filter", "(", "qualifier", ",", "elements", ",", "not", ")", ";", "}" ]
Implement the identical functionality for filter and not
[ "Implement", "the", "identical", "functionality", "for", "filter", "and", "not" ]
28eae564c6a8cdaf01d32ff5a1dffba58232f9c1
https://github.com/nattreid/cms/blob/28eae564c6a8cdaf01d32ff5a1dffba58232f9c1/assets/js/cms.bundled.js#L2836-L2859
35,319
nattreid/cms
assets/js/cms.bundled.js
function( data ) { // For mutual compressibility with _default, replace `this` access with a local var. // `|| data` is dead code meant only to preserve the variable through minification. var el = this || data; // Claim the first handler if ( rcheckableType.test( el.type ) && el.click && nodeName( el, "input" ) ) { // dataPriv.set( el, "click", ... ) leverageNative( el, "click", returnTrue ); } // Return false to allow normal processing in the caller return false; }
javascript
function( data ) { // For mutual compressibility with _default, replace `this` access with a local var. // `|| data` is dead code meant only to preserve the variable through minification. var el = this || data; // Claim the first handler if ( rcheckableType.test( el.type ) && el.click && nodeName( el, "input" ) ) { // dataPriv.set( el, "click", ... ) leverageNative( el, "click", returnTrue ); } // Return false to allow normal processing in the caller return false; }
[ "function", "(", "data", ")", "{", "// For mutual compressibility with _default, replace `this` access with a local var.", "// `|| data` is dead code meant only to preserve the variable through minification.", "var", "el", "=", "this", "||", "data", ";", "// Claim the first handler", "if", "(", "rcheckableType", ".", "test", "(", "el", ".", "type", ")", "&&", "el", ".", "click", "&&", "nodeName", "(", "el", ",", "\"input\"", ")", ")", "{", "// dataPriv.set( el, \"click\", ... )", "leverageNative", "(", "el", ",", "\"click\"", ",", "returnTrue", ")", ";", "}", "// Return false to allow normal processing in the caller", "return", "false", ";", "}" ]
Utilize native event to ensure correct state for checkable inputs
[ "Utilize", "native", "event", "to", "ensure", "correct", "state", "for", "checkable", "inputs" ]
28eae564c6a8cdaf01d32ff5a1dffba58232f9c1
https://github.com/nattreid/cms/blob/28eae564c6a8cdaf01d32ff5a1dffba58232f9c1/assets/js/cms.bundled.js#L5358-L5374
35,320
nattreid/cms
assets/js/cms.bundled.js
finalPropName
function finalPropName( name ) { var final = jQuery.cssProps[ name ] || vendorProps[ name ]; if ( final ) { return final; } if ( name in emptyStyle ) { return name; } return vendorProps[ name ] = vendorPropName( name ) || name; }
javascript
function finalPropName( name ) { var final = jQuery.cssProps[ name ] || vendorProps[ name ]; if ( final ) { return final; } if ( name in emptyStyle ) { return name; } return vendorProps[ name ] = vendorPropName( name ) || name; }
[ "function", "finalPropName", "(", "name", ")", "{", "var", "final", "=", "jQuery", ".", "cssProps", "[", "name", "]", "||", "vendorProps", "[", "name", "]", ";", "if", "(", "final", ")", "{", "return", "final", ";", "}", "if", "(", "name", "in", "emptyStyle", ")", "{", "return", "name", ";", "}", "return", "vendorProps", "[", "name", "]", "=", "vendorPropName", "(", "name", ")", "||", "name", ";", "}" ]
Return a potentially-mapped jQuery.cssProps or vendor prefixed property
[ "Return", "a", "potentially", "-", "mapped", "jQuery", ".", "cssProps", "or", "vendor", "prefixed", "property" ]
28eae564c6a8cdaf01d32ff5a1dffba58232f9c1
https://github.com/nattreid/cms/blob/28eae564c6a8cdaf01d32ff5a1dffba58232f9c1/assets/js/cms.bundled.js#L6431-L6441
35,321
nattreid/cms
assets/js/cms.bundled.js
function( element, set ) { var i = 0, length = set.length; for ( ; i < length; i++ ) { if ( set[ i ] !== null ) { element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] ); } } }
javascript
function( element, set ) { var i = 0, length = set.length; for ( ; i < length; i++ ) { if ( set[ i ] !== null ) { element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] ); } } }
[ "function", "(", "element", ",", "set", ")", "{", "var", "i", "=", "0", ",", "length", "=", "set", ".", "length", ";", "for", "(", ";", "i", "<", "length", ";", "i", "++", ")", "{", "if", "(", "set", "[", "i", "]", "!==", "null", ")", "{", "element", ".", "data", "(", "dataSpace", "+", "set", "[", "i", "]", ",", "element", "[", "0", "]", ".", "style", "[", "set", "[", "i", "]", "]", ")", ";", "}", "}", "}" ]
Saves a set of properties in a data storage
[ "Saves", "a", "set", "of", "properties", "in", "a", "data", "storage" ]
28eae564c6a8cdaf01d32ff5a1dffba58232f9c1
https://github.com/nattreid/cms/blob/28eae564c6a8cdaf01d32ff5a1dffba58232f9c1/assets/js/cms.bundled.js#L12834-L12841
35,322
nattreid/cms
assets/js/cms.bundled.js
function( element ) { var placeholder, cssPosition = element.css( "position" ), position = element.position(); // Lock in margins first to account for form elements, which // will change margin if you explicitly set height // see: http://jsfiddle.net/JZSMt/3/ https://bugs.webkit.org/show_bug.cgi?id=107380 // Support: Safari element.css( { marginTop: element.css( "marginTop" ), marginBottom: element.css( "marginBottom" ), marginLeft: element.css( "marginLeft" ), marginRight: element.css( "marginRight" ) } ) .outerWidth( element.outerWidth() ) .outerHeight( element.outerHeight() ); if ( /^(static|relative)/.test( cssPosition ) ) { cssPosition = "absolute"; placeholder = $( "<" + element[ 0 ].nodeName + ">" ).insertAfter( element ).css( { // Convert inline to inline block to account for inline elements // that turn to inline block based on content (like img) display: /^(inline|ruby)/.test( element.css( "display" ) ) ? "inline-block" : "block", visibility: "hidden", // Margins need to be set to account for margin collapse marginTop: element.css( "marginTop" ), marginBottom: element.css( "marginBottom" ), marginLeft: element.css( "marginLeft" ), marginRight: element.css( "marginRight" ), "float": element.css( "float" ) } ) .outerWidth( element.outerWidth() ) .outerHeight( element.outerHeight() ) .addClass( "ui-effects-placeholder" ); element.data( dataSpace + "placeholder", placeholder ); } element.css( { position: cssPosition, left: position.left, top: position.top } ); return placeholder; }
javascript
function( element ) { var placeholder, cssPosition = element.css( "position" ), position = element.position(); // Lock in margins first to account for form elements, which // will change margin if you explicitly set height // see: http://jsfiddle.net/JZSMt/3/ https://bugs.webkit.org/show_bug.cgi?id=107380 // Support: Safari element.css( { marginTop: element.css( "marginTop" ), marginBottom: element.css( "marginBottom" ), marginLeft: element.css( "marginLeft" ), marginRight: element.css( "marginRight" ) } ) .outerWidth( element.outerWidth() ) .outerHeight( element.outerHeight() ); if ( /^(static|relative)/.test( cssPosition ) ) { cssPosition = "absolute"; placeholder = $( "<" + element[ 0 ].nodeName + ">" ).insertAfter( element ).css( { // Convert inline to inline block to account for inline elements // that turn to inline block based on content (like img) display: /^(inline|ruby)/.test( element.css( "display" ) ) ? "inline-block" : "block", visibility: "hidden", // Margins need to be set to account for margin collapse marginTop: element.css( "marginTop" ), marginBottom: element.css( "marginBottom" ), marginLeft: element.css( "marginLeft" ), marginRight: element.css( "marginRight" ), "float": element.css( "float" ) } ) .outerWidth( element.outerWidth() ) .outerHeight( element.outerHeight() ) .addClass( "ui-effects-placeholder" ); element.data( dataSpace + "placeholder", placeholder ); } element.css( { position: cssPosition, left: position.left, top: position.top } ); return placeholder; }
[ "function", "(", "element", ")", "{", "var", "placeholder", ",", "cssPosition", "=", "element", ".", "css", "(", "\"position\"", ")", ",", "position", "=", "element", ".", "position", "(", ")", ";", "// Lock in margins first to account for form elements, which", "// will change margin if you explicitly set height", "// see: http://jsfiddle.net/JZSMt/3/ https://bugs.webkit.org/show_bug.cgi?id=107380", "// Support: Safari", "element", ".", "css", "(", "{", "marginTop", ":", "element", ".", "css", "(", "\"marginTop\"", ")", ",", "marginBottom", ":", "element", ".", "css", "(", "\"marginBottom\"", ")", ",", "marginLeft", ":", "element", ".", "css", "(", "\"marginLeft\"", ")", ",", "marginRight", ":", "element", ".", "css", "(", "\"marginRight\"", ")", "}", ")", ".", "outerWidth", "(", "element", ".", "outerWidth", "(", ")", ")", ".", "outerHeight", "(", "element", ".", "outerHeight", "(", ")", ")", ";", "if", "(", "/", "^(static|relative)", "/", ".", "test", "(", "cssPosition", ")", ")", "{", "cssPosition", "=", "\"absolute\"", ";", "placeholder", "=", "$", "(", "\"<\"", "+", "element", "[", "0", "]", ".", "nodeName", "+", "\">\"", ")", ".", "insertAfter", "(", "element", ")", ".", "css", "(", "{", "// Convert inline to inline block to account for inline elements", "// that turn to inline block based on content (like img)", "display", ":", "/", "^(inline|ruby)", "/", ".", "test", "(", "element", ".", "css", "(", "\"display\"", ")", ")", "?", "\"inline-block\"", ":", "\"block\"", ",", "visibility", ":", "\"hidden\"", ",", "// Margins need to be set to account for margin collapse", "marginTop", ":", "element", ".", "css", "(", "\"marginTop\"", ")", ",", "marginBottom", ":", "element", ".", "css", "(", "\"marginBottom\"", ")", ",", "marginLeft", ":", "element", ".", "css", "(", "\"marginLeft\"", ")", ",", "marginRight", ":", "element", ".", "css", "(", "\"marginRight\"", ")", ",", "\"float\"", ":", "element", ".", "css", "(", "\"float\"", ")", "}", ")", ".", "outerWidth", "(", "element", ".", "outerWidth", "(", ")", ")", ".", "outerHeight", "(", "element", ".", "outerHeight", "(", ")", ")", ".", "addClass", "(", "\"ui-effects-placeholder\"", ")", ";", "element", ".", "data", "(", "dataSpace", "+", "\"placeholder\"", ",", "placeholder", ")", ";", "}", "element", ".", "css", "(", "{", "position", ":", "cssPosition", ",", "left", ":", "position", ".", "left", ",", "top", ":", "position", ".", "top", "}", ")", ";", "return", "placeholder", ";", "}" ]
Creates a placeholder element so that the original element can be made absolute
[ "Creates", "a", "placeholder", "element", "so", "that", "the", "original", "element", "can", "be", "made", "absolute" ]
28eae564c6a8cdaf01d32ff5a1dffba58232f9c1
https://github.com/nattreid/cms/blob/28eae564c6a8cdaf01d32ff5a1dffba58232f9c1/assets/js/cms.bundled.js#L13074-L13125
35,323
macalinao/preston
lib/preston.js
RestAPI
function RestAPI() { this.models = {}; this.router = express.Router(); this.router.use(require('res-error')({ log: false })); }
javascript
function RestAPI() { this.models = {}; this.router = express.Router(); this.router.use(require('res-error')({ log: false })); }
[ "function", "RestAPI", "(", ")", "{", "this", ".", "models", "=", "{", "}", ";", "this", ".", "router", "=", "express", ".", "Router", "(", ")", ";", "this", ".", "router", ".", "use", "(", "require", "(", "'res-error'", ")", "(", "{", "log", ":", "false", "}", ")", ")", ";", "}" ]
Represents a RESTful API powered by Restifier. @class
[ "Represents", "a", "RESTful", "API", "powered", "by", "Restifier", "." ]
87105425b2c30ce773be196c3f85872375099113
https://github.com/macalinao/preston/blob/87105425b2c30ce773be196c3f85872375099113/lib/preston.js#L13-L19
35,324
strues/boldr
project/server/middleware/rbac.js
hasRole
function hasRole(user = null, role = null) { return user && role && user.hasRole(role); }
javascript
function hasRole(user = null, role = null) { return user && role && user.hasRole(role); }
[ "function", "hasRole", "(", "user", "=", "null", ",", "role", "=", "null", ")", "{", "return", "user", "&&", "role", "&&", "user", ".", "hasRole", "(", "role", ")", ";", "}" ]
This checks to see if the user has the given role. @param {object} user the user object @param {string} role the role @returns {boolean} whether or not the user has the role
[ "This", "checks", "to", "see", "if", "the", "user", "has", "the", "given", "role", "." ]
21f1ed9a5ed754e01c50827249e89087b788e660
https://github.com/strues/boldr/blob/21f1ed9a5ed754e01c50827249e89087b788e660/project/server/middleware/rbac.js#L50-L52
35,325
mathiasvr/querystring
querystring.js
decodeStr
function decodeStr(s, decoder) { try { return decoder(s); } catch (e) { return QueryString.unescape(s, true); } }
javascript
function decodeStr(s, decoder) { try { return decoder(s); } catch (e) { return QueryString.unescape(s, true); } }
[ "function", "decodeStr", "(", "s", ",", "decoder", ")", "{", "try", "{", "return", "decoder", "(", "s", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "QueryString", ".", "unescape", "(", "s", ",", "true", ")", ";", "}", "}" ]
v8 does not optimize functions with try-catch blocks, so we isolate them here to minimize the damage
[ "v8", "does", "not", "optimize", "functions", "with", "try", "-", "catch", "blocks", "so", "we", "isolate", "them", "here", "to", "minimize", "the", "damage" ]
d283ad9ae6a0b50b7c0bb69aaa0a4b5a887c1a4d
https://github.com/mathiasvr/querystring/blob/d283ad9ae6a0b50b7c0bb69aaa0a4b5a887c1a4d/querystring.js#L396-L402
35,326
kellym/smartquotes.js
lib/index.js
smartquotes
function smartquotes(context) { if (typeof document !== 'undefined' && typeof context === 'undefined') { listen.runOnReady(() => element(document.body)); return smartquotes; } else if (typeof context === 'string') { return string(context); } else { return element(context); } }
javascript
function smartquotes(context) { if (typeof document !== 'undefined' && typeof context === 'undefined') { listen.runOnReady(() => element(document.body)); return smartquotes; } else if (typeof context === 'string') { return string(context); } else { return element(context); } }
[ "function", "smartquotes", "(", "context", ")", "{", "if", "(", "typeof", "document", "!==", "'undefined'", "&&", "typeof", "context", "===", "'undefined'", ")", "{", "listen", ".", "runOnReady", "(", "(", ")", "=>", "element", "(", "document", ".", "body", ")", ")", ";", "return", "smartquotes", ";", "}", "else", "if", "(", "typeof", "context", "===", "'string'", ")", "{", "return", "string", "(", "context", ")", ";", "}", "else", "{", "return", "element", "(", "context", ")", ";", "}", "}" ]
The smartquotes function should just delegate to the other functions
[ "The", "smartquotes", "function", "should", "just", "delegate", "to", "the", "other", "functions" ]
730d00cfe69955f818d1df432e0f18006a31f3d0
https://github.com/kellym/smartquotes.js/blob/730d00cfe69955f818d1df432e0f18006a31f3d0/lib/index.js#L8-L17
35,327
JamesMessinger/json-schema-lib
lib/util/omit.js
omit
function omit (obj, props) { props = Array.prototype.slice.call(arguments, 1); var keys = Object.keys(obj); var newObj = {}; for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (props.indexOf(key) === -1) { newObj[key] = obj[key]; } } return newObj; }
javascript
function omit (obj, props) { props = Array.prototype.slice.call(arguments, 1); var keys = Object.keys(obj); var newObj = {}; for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (props.indexOf(key) === -1) { newObj[key] = obj[key]; } } return newObj; }
[ "function", "omit", "(", "obj", ",", "props", ")", "{", "props", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "var", "keys", "=", "Object", ".", "keys", "(", "obj", ")", ";", "var", "newObj", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "var", "key", "=", "keys", "[", "i", "]", ";", "if", "(", "props", ".", "indexOf", "(", "key", ")", "===", "-", "1", ")", "{", "newObj", "[", "key", "]", "=", "obj", "[", "key", "]", ";", "}", "}", "return", "newObj", ";", "}" ]
Returns an object containing all properties of the given object, except for the specified properties to be omitted. @param {object} obj @param {...string} props @returns {object}
[ "Returns", "an", "object", "containing", "all", "properties", "of", "the", "given", "object", "except", "for", "the", "specified", "properties", "to", "be", "omitted", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/util/omit.js#L13-L27
35,328
matteodelabre/midijs
lib/connect/output.js
Output
function Output(native) { this.native = native; this.id = native.id; this.manufacturer = native.manufacturer; this.name = native.name; this.version = native.version; }
javascript
function Output(native) { this.native = native; this.id = native.id; this.manufacturer = native.manufacturer; this.name = native.name; this.version = native.version; }
[ "function", "Output", "(", "native", ")", "{", "this", ".", "native", "=", "native", ";", "this", ".", "id", "=", "native", ".", "id", ";", "this", ".", "manufacturer", "=", "native", ".", "manufacturer", ";", "this", ".", "name", "=", "native", ".", "name", ";", "this", ".", "version", "=", "native", ".", "version", ";", "}" ]
Construct a new Output @class Output @classdesc An output device to which we can send MIDI events @param {MIDIOutput} native Native MIDI output
[ "Construct", "a", "new", "Output" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/connect/output.js#L15-L22
35,329
JamesMessinger/json-schema-lib
lib/util/typeOf.js
typeOf
function typeOf (value) { var type = { hasValue: false, isArray: false, isPOJO: false, isNumber: false, }; if (value !== undefined && value !== null) { type.hasValue = true; var typeName = typeof value; if (typeName === 'number') { type.isNumber = !isNaN(value); } else if (Array.isArray(value)) { type.isArray = true; } else { type.isPOJO = (typeName === 'object') && !(value instanceof RegExp) && !(value instanceof Date); } } return type; }
javascript
function typeOf (value) { var type = { hasValue: false, isArray: false, isPOJO: false, isNumber: false, }; if (value !== undefined && value !== null) { type.hasValue = true; var typeName = typeof value; if (typeName === 'number') { type.isNumber = !isNaN(value); } else if (Array.isArray(value)) { type.isArray = true; } else { type.isPOJO = (typeName === 'object') && !(value instanceof RegExp) && !(value instanceof Date); } } return type; }
[ "function", "typeOf", "(", "value", ")", "{", "var", "type", "=", "{", "hasValue", ":", "false", ",", "isArray", ":", "false", ",", "isPOJO", ":", "false", ",", "isNumber", ":", "false", ",", "}", ";", "if", "(", "value", "!==", "undefined", "&&", "value", "!==", "null", ")", "{", "type", ".", "hasValue", "=", "true", ";", "var", "typeName", "=", "typeof", "value", ";", "if", "(", "typeName", "===", "'number'", ")", "{", "type", ".", "isNumber", "=", "!", "isNaN", "(", "value", ")", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "type", ".", "isArray", "=", "true", ";", "}", "else", "{", "type", ".", "isPOJO", "=", "(", "typeName", "===", "'object'", ")", "&&", "!", "(", "value", "instanceof", "RegExp", ")", "&&", "!", "(", "value", "instanceof", "Date", ")", ";", "}", "}", "return", "type", ";", "}" ]
Returns information about the type of the given value @param {*} value @returns {{ hasValue: boolean, isArray: boolean, isPOJO: boolean, isNumber: boolean }}
[ "Returns", "information", "about", "the", "type", "of", "the", "given", "value" ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/util/typeOf.js#L11-L38
35,330
LivePersonInc/chronosjs
src/courier/PostMessageCourier.js
_registerProxy
function _registerProxy(eventChannel) { if (eventChannel && "function" === typeof eventChannel.registerProxy) { eventChannel.registerProxy({ trigger: function () { _postMessage.call(this, Array.prototype.slice.apply(arguments), ACTION_TYPE.TRIGGER); }, context: this }); } }
javascript
function _registerProxy(eventChannel) { if (eventChannel && "function" === typeof eventChannel.registerProxy) { eventChannel.registerProxy({ trigger: function () { _postMessage.call(this, Array.prototype.slice.apply(arguments), ACTION_TYPE.TRIGGER); }, context: this }); } }
[ "function", "_registerProxy", "(", "eventChannel", ")", "{", "if", "(", "eventChannel", "&&", "\"function\"", "===", "typeof", "eventChannel", ".", "registerProxy", ")", "{", "eventChannel", ".", "registerProxy", "(", "{", "trigger", ":", "function", "(", ")", "{", "_postMessage", ".", "call", "(", "this", ",", "Array", ".", "prototype", ".", "slice", ".", "apply", "(", "arguments", ")", ",", "ACTION_TYPE", ".", "TRIGGER", ")", ";", "}", ",", "context", ":", "this", "}", ")", ";", "}", "}" ]
Registers an external call to trigger for events to propagate calls to Channels.trigger automatically @param eventChannel @private
[ "Registers", "an", "external", "call", "to", "trigger", "for", "events", "to", "propagate", "calls", "to", "Channels", ".", "trigger", "automatically" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageCourier.js#L201-L210
35,331
LivePersonInc/chronosjs
src/courier/PostMessageCourier.js
_initializeSerialization
function _initializeSerialization(options) { this.useObjects = false === options.useObjects ? options.useObjects : _getUseObjectsUrlIndicator(); if ("undefined" === typeof this.useObjects) { // Defaults to true this.useObjects = true; } options.useObjects = this.useObjects; // Define the serialize/deserialize methods to be used if ("function" !== typeof options.serialize || "function" !== typeof options.deserialize) { if (this.useObjects && PostMessageUtilities.hasPostMessageObjectsSupport()) { this.serialize = _de$serializeDummy; this.deserialize = _de$serializeDummy; } else { this.serialize = PostMessageUtilities.stringify; this.deserialize = JSON.parse; } options.serialize = this.serialize; options.deserialize = this.deserialize; } else { this.serialize = options.serialize; this.deserialize = options.deserialize; } }
javascript
function _initializeSerialization(options) { this.useObjects = false === options.useObjects ? options.useObjects : _getUseObjectsUrlIndicator(); if ("undefined" === typeof this.useObjects) { // Defaults to true this.useObjects = true; } options.useObjects = this.useObjects; // Define the serialize/deserialize methods to be used if ("function" !== typeof options.serialize || "function" !== typeof options.deserialize) { if (this.useObjects && PostMessageUtilities.hasPostMessageObjectsSupport()) { this.serialize = _de$serializeDummy; this.deserialize = _de$serializeDummy; } else { this.serialize = PostMessageUtilities.stringify; this.deserialize = JSON.parse; } options.serialize = this.serialize; options.deserialize = this.deserialize; } else { this.serialize = options.serialize; this.deserialize = options.deserialize; } }
[ "function", "_initializeSerialization", "(", "options", ")", "{", "this", ".", "useObjects", "=", "false", "===", "options", ".", "useObjects", "?", "options", ".", "useObjects", ":", "_getUseObjectsUrlIndicator", "(", ")", ";", "if", "(", "\"undefined\"", "===", "typeof", "this", ".", "useObjects", ")", "{", "// Defaults to true", "this", ".", "useObjects", "=", "true", ";", "}", "options", ".", "useObjects", "=", "this", ".", "useObjects", ";", "// Define the serialize/deserialize methods to be used", "if", "(", "\"function\"", "!==", "typeof", "options", ".", "serialize", "||", "\"function\"", "!==", "typeof", "options", ".", "deserialize", ")", "{", "if", "(", "this", ".", "useObjects", "&&", "PostMessageUtilities", ".", "hasPostMessageObjectsSupport", "(", ")", ")", "{", "this", ".", "serialize", "=", "_de$serializeDummy", ";", "this", ".", "deserialize", "=", "_de$serializeDummy", ";", "}", "else", "{", "this", ".", "serialize", "=", "PostMessageUtilities", ".", "stringify", ";", "this", ".", "deserialize", "=", "JSON", ".", "parse", ";", "}", "options", ".", "serialize", "=", "this", ".", "serialize", ";", "options", ".", "deserialize", "=", "this", ".", "deserialize", ";", "}", "else", "{", "this", ".", "serialize", "=", "options", ".", "serialize", ";", "this", ".", "deserialize", "=", "options", ".", "deserialize", ";", "}", "}" ]
Method for initializing the options for serialization of messages @param {Boolean} [options.useObjects = true upon browser support] - optional indication for passing objects by reference @param {Function} [options.serialize = JSON.stringify] - optional serialization method for post message @param {Function} [options.deserialize = JSON.parse] - optional deserialization method for post message @private
[ "Method", "for", "initializing", "the", "options", "for", "serialization", "of", "messages" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageCourier.js#L346-L372
35,332
LivePersonInc/chronosjs
src/courier/PostMessageCourier.js
_initializeCommunication
function _initializeCommunication(options) { var mapping; var onmessage; // Grab the event channel and initialize a new mapper this.eventChannel = options.eventChannel || new Channels({ events: options.events, commands: options.commands, reqres: options.reqres }); this.mapper = new PostMessageMapper(this.eventChannel); // Bind the mapping method to the mapper mapping = this.mapper.toEvent.bind(this.mapper); // Create the message handler which uses the mapping method onmessage = _createMessageHandler(mapping).bind(this); // Initialize a message channel with the message handler this.messageChannel = new PostMessageChannel(options, onmessage); }
javascript
function _initializeCommunication(options) { var mapping; var onmessage; // Grab the event channel and initialize a new mapper this.eventChannel = options.eventChannel || new Channels({ events: options.events, commands: options.commands, reqres: options.reqres }); this.mapper = new PostMessageMapper(this.eventChannel); // Bind the mapping method to the mapper mapping = this.mapper.toEvent.bind(this.mapper); // Create the message handler which uses the mapping method onmessage = _createMessageHandler(mapping).bind(this); // Initialize a message channel with the message handler this.messageChannel = new PostMessageChannel(options, onmessage); }
[ "function", "_initializeCommunication", "(", "options", ")", "{", "var", "mapping", ";", "var", "onmessage", ";", "// Grab the event channel and initialize a new mapper", "this", ".", "eventChannel", "=", "options", ".", "eventChannel", "||", "new", "Channels", "(", "{", "events", ":", "options", ".", "events", ",", "commands", ":", "options", ".", "commands", ",", "reqres", ":", "options", ".", "reqres", "}", ")", ";", "this", ".", "mapper", "=", "new", "PostMessageMapper", "(", "this", ".", "eventChannel", ")", ";", "// Bind the mapping method to the mapper", "mapping", "=", "this", ".", "mapper", ".", "toEvent", ".", "bind", "(", "this", ".", "mapper", ")", ";", "// Create the message handler which uses the mapping method", "onmessage", "=", "_createMessageHandler", "(", "mapping", ")", ".", "bind", "(", "this", ")", ";", "// Initialize a message channel with the message handler", "this", ".", "messageChannel", "=", "new", "PostMessageChannel", "(", "options", ",", "onmessage", ")", ";", "}" ]
Method for initializing the communication elements @param {Object} [options.eventChannel] - optional events channel to be used (if not supplied, a new one will be created OR optional events, optional commands, optional reqres to be used @private
[ "Method", "for", "initializing", "the", "communication", "elements" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageCourier.js#L379-L398
35,333
LivePersonInc/chronosjs
src/courier/PostMessageCourier.js
_initializeCache
function _initializeCache(options) { this.callbackCache = new Cacher({ max: PostMessageUtilities.parseNumber(options.maxConcurrency, DEFAULT_CONCURRENCY), ttl: PostMessageUtilities.parseNumber(options.timeout, DEFAULT_TIMEOUT), interval: CACHE_EVICTION_INTERVAL }); }
javascript
function _initializeCache(options) { this.callbackCache = new Cacher({ max: PostMessageUtilities.parseNumber(options.maxConcurrency, DEFAULT_CONCURRENCY), ttl: PostMessageUtilities.parseNumber(options.timeout, DEFAULT_TIMEOUT), interval: CACHE_EVICTION_INTERVAL }); }
[ "function", "_initializeCache", "(", "options", ")", "{", "this", ".", "callbackCache", "=", "new", "Cacher", "(", "{", "max", ":", "PostMessageUtilities", ".", "parseNumber", "(", "options", ".", "maxConcurrency", ",", "DEFAULT_CONCURRENCY", ")", ",", "ttl", ":", "PostMessageUtilities", ".", "parseNumber", "(", "options", ".", "timeout", ",", "DEFAULT_TIMEOUT", ")", ",", "interval", ":", "CACHE_EVICTION_INTERVAL", "}", ")", ";", "}" ]
Method for initializing the cache for responses @param {Number} [options.maxConcurrency = 100] - optional maximum concurrency that can be managed by the component before dropping @param {Number} [options.timeout = 30000] - optional milliseconds parameter for waiting before timeout to responses (default is 30 seconds) @private
[ "Method", "for", "initializing", "the", "cache", "for", "responses" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageCourier.js#L406-L412
35,334
LivePersonInc/chronosjs
src/courier/PostMessageCourier.js
_initializeFailFast
function _initializeFailFast(options) { var messureTime = PostMessageUtilities.parseNumber(options.messureTime, DEFAULT_MESSURE_TIME); this.circuit = new CircuitBreaker({ timeWindow: messureTime, slidesNumber: Math.ceil(messureTime / 100), tolerance: PostMessageUtilities.parseNumber(options.messureTolerance, DEFAULT_MESSURE_TOLERANCE), calibration: PostMessageUtilities.parseNumber(options.messureCalibration, DEFAULT_MESSURE_CALIBRATION), onopen: PostMessageUtilities.parseFunction(options.ondisconnect, true), onclose: PostMessageUtilities.parseFunction(options.onreconnect, true) }); }
javascript
function _initializeFailFast(options) { var messureTime = PostMessageUtilities.parseNumber(options.messureTime, DEFAULT_MESSURE_TIME); this.circuit = new CircuitBreaker({ timeWindow: messureTime, slidesNumber: Math.ceil(messureTime / 100), tolerance: PostMessageUtilities.parseNumber(options.messureTolerance, DEFAULT_MESSURE_TOLERANCE), calibration: PostMessageUtilities.parseNumber(options.messureCalibration, DEFAULT_MESSURE_CALIBRATION), onopen: PostMessageUtilities.parseFunction(options.ondisconnect, true), onclose: PostMessageUtilities.parseFunction(options.onreconnect, true) }); }
[ "function", "_initializeFailFast", "(", "options", ")", "{", "var", "messureTime", "=", "PostMessageUtilities", ".", "parseNumber", "(", "options", ".", "messureTime", ",", "DEFAULT_MESSURE_TIME", ")", ";", "this", ".", "circuit", "=", "new", "CircuitBreaker", "(", "{", "timeWindow", ":", "messureTime", ",", "slidesNumber", ":", "Math", ".", "ceil", "(", "messureTime", "/", "100", ")", ",", "tolerance", ":", "PostMessageUtilities", ".", "parseNumber", "(", "options", ".", "messureTolerance", ",", "DEFAULT_MESSURE_TOLERANCE", ")", ",", "calibration", ":", "PostMessageUtilities", ".", "parseNumber", "(", "options", ".", "messureCalibration", ",", "DEFAULT_MESSURE_CALIBRATION", ")", ",", "onopen", ":", "PostMessageUtilities", ".", "parseFunction", "(", "options", ".", "ondisconnect", ",", "true", ")", ",", "onclose", ":", "PostMessageUtilities", ".", "parseFunction", "(", "options", ".", "onreconnect", ",", "true", ")", "}", ")", ";", "}" ]
Method for initializing the fail fast mechanisms @param {Number} [options.messureTime = 30000] - optional milliseconds parameter for time measurement indicating the time window to apply when implementing the internal fail fast mechanism (default is 30 seconds) @param {Number} [options.messureTolerance = 30] - optional percentage parameter indicating the tolerance to apply on the measurements when implementing the internal fail fast mechanism (default is 30 percents) @param {Number} [options.messureCalibration = 10] optional numeric parameter indicating the calibration of minimum calls before starting to validate measurements when implementing the internal fail fast mechanism (default is 10 calls) @param {Function} [options.ondisconnect] - optional disconnect handler that will be invoked when the fail fast mechanism disconnects the component upon to many failures @param {Function} [options.onreconnect] - optional reconnect handler that will be invoked when the fail fast mechanism reconnects the component upon back to normal behaviour @private
[ "Method", "for", "initializing", "the", "fail", "fast", "mechanisms" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageCourier.js#L423-L433
35,335
LivePersonInc/chronosjs
src/courier/PostMessageCourier.js
_postMessage
function _postMessage(args, name) { return this.circuit.run(function (success, failure, timeout) { var message = _prepare.call(this, args, name, timeout); if (message) { try { var initiated = this.messageChannel.postMessage.call(this.messageChannel, message); if (false === initiated) { failure(); } else { success(); } } catch (ex) { failure(); } } else { // Cache is full, as a fail fast mechanism, we should not continue failure(); } }.bind(this)); }
javascript
function _postMessage(args, name) { return this.circuit.run(function (success, failure, timeout) { var message = _prepare.call(this, args, name, timeout); if (message) { try { var initiated = this.messageChannel.postMessage.call(this.messageChannel, message); if (false === initiated) { failure(); } else { success(); } } catch (ex) { failure(); } } else { // Cache is full, as a fail fast mechanism, we should not continue failure(); } }.bind(this)); }
[ "function", "_postMessage", "(", "args", ",", "name", ")", "{", "return", "this", ".", "circuit", ".", "run", "(", "function", "(", "success", ",", "failure", ",", "timeout", ")", "{", "var", "message", "=", "_prepare", ".", "call", "(", "this", ",", "args", ",", "name", ",", "timeout", ")", ";", "if", "(", "message", ")", "{", "try", "{", "var", "initiated", "=", "this", ".", "messageChannel", ".", "postMessage", ".", "call", "(", "this", ".", "messageChannel", ",", "message", ")", ";", "if", "(", "false", "===", "initiated", ")", "{", "failure", "(", ")", ";", "}", "else", "{", "success", "(", ")", ";", "}", "}", "catch", "(", "ex", ")", "{", "failure", "(", ")", ";", "}", "}", "else", "{", "// Cache is full, as a fail fast mechanism, we should not continue", "failure", "(", ")", ";", "}", "}", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Method for posting the message via the circuit breaker @param {Array} args - the arguments for the message to be processed. @param {String} name - name of type of command. @private
[ "Method", "for", "posting", "the", "message", "via", "the", "circuit", "breaker" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageCourier.js#L463-L487
35,336
LivePersonInc/chronosjs
src/courier/PostMessageCourier.js
_returnMessage
function _returnMessage(message, target) { return this.circuit.run(function (success, failure) { try { var initiated = this.messageChannel.postMessage.call(this.messageChannel, message, target); if (false === initiated) { failure(); } else { success(); } } catch (ex) { failure(); } }.bind(this)); }
javascript
function _returnMessage(message, target) { return this.circuit.run(function (success, failure) { try { var initiated = this.messageChannel.postMessage.call(this.messageChannel, message, target); if (false === initiated) { failure(); } else { success(); } } catch (ex) { failure(); } }.bind(this)); }
[ "function", "_returnMessage", "(", "message", ",", "target", ")", "{", "return", "this", ".", "circuit", ".", "run", "(", "function", "(", "success", ",", "failure", ")", "{", "try", "{", "var", "initiated", "=", "this", ".", "messageChannel", ".", "postMessage", ".", "call", "(", "this", ".", "messageChannel", ",", "message", ",", "target", ")", ";", "if", "(", "false", "===", "initiated", ")", "{", "failure", "(", ")", ";", "}", "else", "{", "success", "(", ")", ";", "}", "}", "catch", "(", "ex", ")", "{", "failure", "(", ")", ";", "}", "}", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Method for posting the returned message via the circuit breaker @param {Object} message - the message to post. @param {bject} [target] - optional target for post. @private
[ "Method", "for", "posting", "the", "returned", "message", "via", "the", "circuit", "breaker" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageCourier.js#L495-L511
35,337
LivePersonInc/chronosjs
src/courier/PostMessageCourier.js
_prepare
function _prepare(args, name, ontimeout) { var method; var ttl; var id = PostMessageUtilities.createUniqueSequence(MESSAGE_PREFIX + name + PostMessageUtilities.SEQUENCE_FORMAT); args.unshift(id, name); if (_isTwoWay(name)) { if (1 < args.length && "function" === typeof args[args.length - 1]) { method = args.pop(); } else if (2 < args.length && !isNaN(args[args.length - 1]) && "function" === typeof args[args.length - 2]) { ttl = parseInt(args.pop(), 10); method = args.pop(); } if (method) { if (!this.callbackCache.set(id, method, ttl, function (id, callback) { ontimeout(); _handleTimeout.call(this, id, callback); }.bind(this))) { // Cache is full, as a fail fast mechanism, we will not continue return void 0; } } } return this.mapper.toMessage.apply(this.mapper, args); }
javascript
function _prepare(args, name, ontimeout) { var method; var ttl; var id = PostMessageUtilities.createUniqueSequence(MESSAGE_PREFIX + name + PostMessageUtilities.SEQUENCE_FORMAT); args.unshift(id, name); if (_isTwoWay(name)) { if (1 < args.length && "function" === typeof args[args.length - 1]) { method = args.pop(); } else if (2 < args.length && !isNaN(args[args.length - 1]) && "function" === typeof args[args.length - 2]) { ttl = parseInt(args.pop(), 10); method = args.pop(); } if (method) { if (!this.callbackCache.set(id, method, ttl, function (id, callback) { ontimeout(); _handleTimeout.call(this, id, callback); }.bind(this))) { // Cache is full, as a fail fast mechanism, we will not continue return void 0; } } } return this.mapper.toMessage.apply(this.mapper, args); }
[ "function", "_prepare", "(", "args", ",", "name", ",", "ontimeout", ")", "{", "var", "method", ";", "var", "ttl", ";", "var", "id", "=", "PostMessageUtilities", ".", "createUniqueSequence", "(", "MESSAGE_PREFIX", "+", "name", "+", "PostMessageUtilities", ".", "SEQUENCE_FORMAT", ")", ";", "args", ".", "unshift", "(", "id", ",", "name", ")", ";", "if", "(", "_isTwoWay", "(", "name", ")", ")", "{", "if", "(", "1", "<", "args", ".", "length", "&&", "\"function\"", "===", "typeof", "args", "[", "args", ".", "length", "-", "1", "]", ")", "{", "method", "=", "args", ".", "pop", "(", ")", ";", "}", "else", "if", "(", "2", "<", "args", ".", "length", "&&", "!", "isNaN", "(", "args", "[", "args", ".", "length", "-", "1", "]", ")", "&&", "\"function\"", "===", "typeof", "args", "[", "args", ".", "length", "-", "2", "]", ")", "{", "ttl", "=", "parseInt", "(", "args", ".", "pop", "(", ")", ",", "10", ")", ";", "method", "=", "args", ".", "pop", "(", ")", ";", "}", "if", "(", "method", ")", "{", "if", "(", "!", "this", ".", "callbackCache", ".", "set", "(", "id", ",", "method", ",", "ttl", ",", "function", "(", "id", ",", "callback", ")", "{", "ontimeout", "(", ")", ";", "_handleTimeout", ".", "call", "(", "this", ",", "id", ",", "callback", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ")", "{", "// Cache is full, as a fail fast mechanism, we will not continue", "return", "void", "0", ";", "}", "}", "}", "return", "this", ".", "mapper", ".", "toMessage", ".", "apply", "(", "this", ".", "mapper", ",", "args", ")", ";", "}" ]
Method for preparing the message to be posted via the postmessage and caching the callback to be called if needed @param {Array} args - the arguments to pass to the message mapper @param {String} name - the action type name (trigger, command, request) @param {Function} [ontimeout] - the ontimeout measurement handler @returns {Function} handler function for messages @private
[ "Method", "for", "preparing", "the", "message", "to", "be", "posted", "via", "the", "postmessage", "and", "caching", "the", "callback", "to", "be", "called", "if", "needed" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageCourier.js#L521-L549
35,338
LivePersonInc/chronosjs
src/courier/PostMessageCourier.js
_handleTimeout
function _handleTimeout(id, callback) { // Handle timeout if (id && "function" === typeof callback) { try { callback.call(null, new Error("Callback: Operation Timeout!")); } catch (ex) { /* istanbul ignore next */ PostMessageUtilities.log("Error while trying to handle the timeout using the callback", "ERROR", "PostMessageCourier"); } } }
javascript
function _handleTimeout(id, callback) { // Handle timeout if (id && "function" === typeof callback) { try { callback.call(null, new Error("Callback: Operation Timeout!")); } catch (ex) { /* istanbul ignore next */ PostMessageUtilities.log("Error while trying to handle the timeout using the callback", "ERROR", "PostMessageCourier"); } } }
[ "function", "_handleTimeout", "(", "id", ",", "callback", ")", "{", "// Handle timeout", "if", "(", "id", "&&", "\"function\"", "===", "typeof", "callback", ")", "{", "try", "{", "callback", ".", "call", "(", "null", ",", "new", "Error", "(", "\"Callback: Operation Timeout!\"", ")", ")", ";", "}", "catch", "(", "ex", ")", "{", "/* istanbul ignore next */", "PostMessageUtilities", ".", "log", "(", "\"Error while trying to handle the timeout using the callback\"", ",", "\"ERROR\"", ",", "\"PostMessageCourier\"", ")", ";", "}", "}", "}" ]
Method for handling timeout of a cached callback @param {String} id - the id of the timed out callback @param {Function} callback - the callback object from cache @private
[ "Method", "for", "handling", "timeout", "of", "a", "cached", "callback" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageCourier.js#L567-L578
35,339
LivePersonInc/chronosjs
src/courier/PostMessageCourier.js
_handleReturnMessage
function _handleReturnMessage(id, method) { var callback = this.callbackCache.get(id, true); var args = method && method.args; if ("function" === typeof callback) { // First try to parse the first parameter in case the error is an object if (args && args.length && args[0] && "Error" === args[0].type && "string" === typeof args[0].message) { args[0] = new Error(args[0].message); } try { callback.apply(null, args); } catch (ex) { PostMessageUtilities.log("Error while trying to handle the returned message from request/command", "ERROR", "PostMessageCourier"); } } }
javascript
function _handleReturnMessage(id, method) { var callback = this.callbackCache.get(id, true); var args = method && method.args; if ("function" === typeof callback) { // First try to parse the first parameter in case the error is an object if (args && args.length && args[0] && "Error" === args[0].type && "string" === typeof args[0].message) { args[0] = new Error(args[0].message); } try { callback.apply(null, args); } catch (ex) { PostMessageUtilities.log("Error while trying to handle the returned message from request/command", "ERROR", "PostMessageCourier"); } } }
[ "function", "_handleReturnMessage", "(", "id", ",", "method", ")", "{", "var", "callback", "=", "this", ".", "callbackCache", ".", "get", "(", "id", ",", "true", ")", ";", "var", "args", "=", "method", "&&", "method", ".", "args", ";", "if", "(", "\"function\"", "===", "typeof", "callback", ")", "{", "// First try to parse the first parameter in case the error is an object", "if", "(", "args", "&&", "args", ".", "length", "&&", "args", "[", "0", "]", "&&", "\"Error\"", "===", "args", "[", "0", "]", ".", "type", "&&", "\"string\"", "===", "typeof", "args", "[", "0", "]", ".", "message", ")", "{", "args", "[", "0", "]", "=", "new", "Error", "(", "args", "[", "0", "]", ".", "message", ")", ";", "}", "try", "{", "callback", ".", "apply", "(", "null", ",", "args", ")", ";", "}", "catch", "(", "ex", ")", "{", "PostMessageUtilities", ".", "log", "(", "\"Error while trying to handle the returned message from request/command\"", ",", "\"ERROR\"", ",", "\"PostMessageCourier\"", ")", ";", "}", "}", "}" ]
Method for handling return messages from the callee @param {String} id - the id of the callback @param {Object} method - the method object with needed args @private
[ "Method", "for", "handling", "return", "messages", "from", "the", "callee" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageCourier.js#L586-L603
35,340
emgeee/gulp-standard
reporters/stylish.js
reportFile
function reportFile (filepath, data) { var lines = [] // Filename lines.push(colors.magenta.underline(path.relative(appRoot.path, filepath))) // Loop file specific error/warning messages data.results.forEach(function (file) { file.messages.forEach(function (msg) { var context = colors.yellow((options.showFilePath ? filepath + ':' : 'line ') + msg.line + ':' + msg.column) var message = colors.cyan(msg.message + (options.showRuleNames ? ' (' + msg.ruleId + ')' : '')) lines.push(context + '\t' + message) }) }) // Error/Warning count lines.push(logSymbols.error + ' ' + colors.red(data.errorCount + ' error' + (data.errorCount === 1 ? 's' : '')) + '\t' + logSymbols.warning + ' ' + colors.yellow(data.warningCount + ' warning' + (data.errorCount === 1 ? 's' : ''))) return lines.join('\n') + '\n' }
javascript
function reportFile (filepath, data) { var lines = [] // Filename lines.push(colors.magenta.underline(path.relative(appRoot.path, filepath))) // Loop file specific error/warning messages data.results.forEach(function (file) { file.messages.forEach(function (msg) { var context = colors.yellow((options.showFilePath ? filepath + ':' : 'line ') + msg.line + ':' + msg.column) var message = colors.cyan(msg.message + (options.showRuleNames ? ' (' + msg.ruleId + ')' : '')) lines.push(context + '\t' + message) }) }) // Error/Warning count lines.push(logSymbols.error + ' ' + colors.red(data.errorCount + ' error' + (data.errorCount === 1 ? 's' : '')) + '\t' + logSymbols.warning + ' ' + colors.yellow(data.warningCount + ' warning' + (data.errorCount === 1 ? 's' : ''))) return lines.join('\n') + '\n' }
[ "function", "reportFile", "(", "filepath", ",", "data", ")", "{", "var", "lines", "=", "[", "]", "// Filename", "lines", ".", "push", "(", "colors", ".", "magenta", ".", "underline", "(", "path", ".", "relative", "(", "appRoot", ".", "path", ",", "filepath", ")", ")", ")", "// Loop file specific error/warning messages", "data", ".", "results", ".", "forEach", "(", "function", "(", "file", ")", "{", "file", ".", "messages", ".", "forEach", "(", "function", "(", "msg", ")", "{", "var", "context", "=", "colors", ".", "yellow", "(", "(", "options", ".", "showFilePath", "?", "filepath", "+", "':'", ":", "'line '", ")", "+", "msg", ".", "line", "+", "':'", "+", "msg", ".", "column", ")", "var", "message", "=", "colors", ".", "cyan", "(", "msg", ".", "message", "+", "(", "options", ".", "showRuleNames", "?", "' ('", "+", "msg", ".", "ruleId", "+", "')'", ":", "''", ")", ")", "lines", ".", "push", "(", "context", "+", "'\\t'", "+", "message", ")", "}", ")", "}", ")", "// Error/Warning count", "lines", ".", "push", "(", "logSymbols", ".", "error", "+", "' '", "+", "colors", ".", "red", "(", "data", ".", "errorCount", "+", "' error'", "+", "(", "data", ".", "errorCount", "===", "1", "?", "'s'", ":", "''", ")", ")", "+", "'\\t'", "+", "logSymbols", ".", "warning", "+", "' '", "+", "colors", ".", "yellow", "(", "data", ".", "warningCount", "+", "' warning'", "+", "(", "data", ".", "errorCount", "===", "1", "?", "'s'", ":", "''", ")", ")", ")", "return", "lines", ".", "join", "(", "'\\n'", ")", "+", "'\\n'", "}" ]
File specific reporter
[ "File", "specific", "reporter" ]
6c9c7c0c1adf26424f39ca8f591cd3ab310a7615
https://github.com/emgeee/gulp-standard/blob/6c9c7c0c1adf26424f39ca8f591cd3ab310a7615/reporters/stylish.js#L17-L36
35,341
JamesMessinger/json-schema-lib
lib/plugins/XMLHttpRequestPlugin.js
readFileSync
function readFileSync (args) { var file = args.file; var config = args.config; var error, response; safeCall(sendRequest, false, file.url, config, function handleResponse (err, res) { error = err; response = res; }); if (error) { throw error; } else { setHttpMetadata(file, response); return response.data; } }
javascript
function readFileSync (args) { var file = args.file; var config = args.config; var error, response; safeCall(sendRequest, false, file.url, config, function handleResponse (err, res) { error = err; response = res; }); if (error) { throw error; } else { setHttpMetadata(file, response); return response.data; } }
[ "function", "readFileSync", "(", "args", ")", "{", "var", "file", "=", "args", ".", "file", ";", "var", "config", "=", "args", ".", "config", ";", "var", "error", ",", "response", ";", "safeCall", "(", "sendRequest", ",", "false", ",", "file", ".", "url", ",", "config", ",", "function", "handleResponse", "(", "err", ",", "res", ")", "{", "error", "=", "err", ";", "response", "=", "res", ";", "}", ")", ";", "if", "(", "error", ")", "{", "throw", "error", ";", "}", "else", "{", "setHttpMetadata", "(", "file", ",", "response", ")", ";", "return", "response", ".", "data", ";", "}", "}" ]
Synchronously downlaods a file. @param {File} args.file - The {@link File} to read @param {function} args.next - Calls the next plugin, if the file is not a local filesystem file
[ "Synchronously", "downlaods", "a", "file", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/XMLHttpRequestPlugin.js#L25-L42
35,342
JamesMessinger/json-schema-lib
lib/plugins/XMLHttpRequestPlugin.js
readFileAsync
function readFileAsync (args) { var file = args.file; var config = args.config; var next = args.next; safeCall(sendRequest, false, file.url, config, function handleResponse (err, res) { if (err) { next(err); } else { setHttpMetadata(file, res); next(null, res.data); } }); }
javascript
function readFileAsync (args) { var file = args.file; var config = args.config; var next = args.next; safeCall(sendRequest, false, file.url, config, function handleResponse (err, res) { if (err) { next(err); } else { setHttpMetadata(file, res); next(null, res.data); } }); }
[ "function", "readFileAsync", "(", "args", ")", "{", "var", "file", "=", "args", ".", "file", ";", "var", "config", "=", "args", ".", "config", ";", "var", "next", "=", "args", ".", "next", ";", "safeCall", "(", "sendRequest", ",", "false", ",", "file", ".", "url", ",", "config", ",", "function", "handleResponse", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "{", "next", "(", "err", ")", ";", "}", "else", "{", "setHttpMetadata", "(", "file", ",", "res", ")", ";", "next", "(", "null", ",", "res", ".", "data", ")", ";", "}", "}", ")", ";", "}" ]
Asynchronously downlaods a file. @param {File} args.file - The {@link File} to read @param {function} args.next - Calls the next plugin, if the file is not a local filesystem file
[ "Asynchronously", "downlaods", "a", "file", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/XMLHttpRequestPlugin.js#L50-L64
35,343
JamesMessinger/json-schema-lib
lib/plugins/XMLHttpRequestPlugin.js
sendRequest
function sendRequest (async, url, config, callback) { var req = new XMLHttpRequest(); req.open('GET', url, async); req.onerror = handleError; req.ontimeout = handleError; req.onload = handleResponse; setXHRConfig(req, config); req.send(); function handleResponse () { var res = { status: getResponseStatus(req.status, url), headers: parseResponseHeaders(req.getAllResponseHeaders()), data: req.response || req.responseText, }; if (res.status >= 200 && res.status < 300) { callback(null, res); } else if (res.status < 200 || res.status < 400) { callback(ono('Invalid/unsupported HTTP %d response', res.status)); } else { callback(ono('HTTP %d error occurred (%s)', res.status, req.statusText)); } } function handleError (err) { callback(err); } }
javascript
function sendRequest (async, url, config, callback) { var req = new XMLHttpRequest(); req.open('GET', url, async); req.onerror = handleError; req.ontimeout = handleError; req.onload = handleResponse; setXHRConfig(req, config); req.send(); function handleResponse () { var res = { status: getResponseStatus(req.status, url), headers: parseResponseHeaders(req.getAllResponseHeaders()), data: req.response || req.responseText, }; if (res.status >= 200 && res.status < 300) { callback(null, res); } else if (res.status < 200 || res.status < 400) { callback(ono('Invalid/unsupported HTTP %d response', res.status)); } else { callback(ono('HTTP %d error occurred (%s)', res.status, req.statusText)); } } function handleError (err) { callback(err); } }
[ "function", "sendRequest", "(", "async", ",", "url", ",", "config", ",", "callback", ")", "{", "var", "req", "=", "new", "XMLHttpRequest", "(", ")", ";", "req", ".", "open", "(", "'GET'", ",", "url", ",", "async", ")", ";", "req", ".", "onerror", "=", "handleError", ";", "req", ".", "ontimeout", "=", "handleError", ";", "req", ".", "onload", "=", "handleResponse", ";", "setXHRConfig", "(", "req", ",", "config", ")", ";", "req", ".", "send", "(", ")", ";", "function", "handleResponse", "(", ")", "{", "var", "res", "=", "{", "status", ":", "getResponseStatus", "(", "req", ".", "status", ",", "url", ")", ",", "headers", ":", "parseResponseHeaders", "(", "req", ".", "getAllResponseHeaders", "(", ")", ")", ",", "data", ":", "req", ".", "response", "||", "req", ".", "responseText", ",", "}", ";", "if", "(", "res", ".", "status", ">=", "200", "&&", "res", ".", "status", "<", "300", ")", "{", "callback", "(", "null", ",", "res", ")", ";", "}", "else", "if", "(", "res", ".", "status", "<", "200", "||", "res", ".", "status", "<", "400", ")", "{", "callback", "(", "ono", "(", "'Invalid/unsupported HTTP %d response'", ",", "res", ".", "status", ")", ")", ";", "}", "else", "{", "callback", "(", "ono", "(", "'HTTP %d error occurred (%s)'", ",", "res", ".", "status", ",", "req", ".", "statusText", ")", ")", ";", "}", "}", "function", "handleError", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "}", "}" ]
Sends an HTTP GET request using XMLHttpRequest. @param {boolean} async - Whether to send the request synchronously or asynchronously @param {string} url - The absolute URL to request @param {Config} config - Configuration settings, such as timeout, headers, etc. @param {function} callback - Called with an error or response object
[ "Sends", "an", "HTTP", "GET", "request", "using", "XMLHttpRequest", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/XMLHttpRequestPlugin.js#L76-L109
35,344
JamesMessinger/json-schema-lib
lib/plugins/XMLHttpRequestPlugin.js
setXHRConfig
function setXHRConfig (req, config) { try { req.withCredentials = config.http.withCredentials; } catch (err) { // Some browsers don't allow `withCredentials` to be set for synchronous requests } try { req.timeout = config.http.timeout; } catch (err) { // Some browsers don't allow `timeout` to be set for synchronous requests } // Set request headers Object.keys(config.http.headers).forEach(function (key) { var value = config.http.headers[key]; if (value !== undefined) { req.setRequestHeader(key, value); } }); }
javascript
function setXHRConfig (req, config) { try { req.withCredentials = config.http.withCredentials; } catch (err) { // Some browsers don't allow `withCredentials` to be set for synchronous requests } try { req.timeout = config.http.timeout; } catch (err) { // Some browsers don't allow `timeout` to be set for synchronous requests } // Set request headers Object.keys(config.http.headers).forEach(function (key) { var value = config.http.headers[key]; if (value !== undefined) { req.setRequestHeader(key, value); } }); }
[ "function", "setXHRConfig", "(", "req", ",", "config", ")", "{", "try", "{", "req", ".", "withCredentials", "=", "config", ".", "http", ".", "withCredentials", ";", "}", "catch", "(", "err", ")", "{", "// Some browsers don't allow `withCredentials` to be set for synchronous requests", "}", "try", "{", "req", ".", "timeout", "=", "config", ".", "http", ".", "timeout", ";", "}", "catch", "(", "err", ")", "{", "// Some browsers don't allow `timeout` to be set for synchronous requests", "}", "// Set request headers", "Object", ".", "keys", "(", "config", ".", "http", ".", "headers", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "var", "value", "=", "config", ".", "http", ".", "headers", "[", "key", "]", ";", "if", "(", "value", "!==", "undefined", ")", "{", "req", ".", "setRequestHeader", "(", "key", ",", "value", ")", ";", "}", "}", ")", ";", "}" ]
Sets the XMLHttpRequest properties, per the specified configuration. @param {XMLHttpRequest} req @param {Config} config
[ "Sets", "the", "XMLHttpRequest", "properties", "per", "the", "specified", "configuration", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/XMLHttpRequestPlugin.js#L117-L139
35,345
JamesMessinger/json-schema-lib
lib/plugins/XMLHttpRequestPlugin.js
parseResponseHeaders
function parseResponseHeaders (headers) { var parsed = {}; if (headers) { headers.split('\n').forEach(function (line) { var separatorIndex = line.indexOf(':'); var key = line.substr(0, separatorIndex).trim().toLowerCase(); var value = line.substr(separatorIndex + 1).trim().toLowerCase(); if (key) { parsed[key] = value; } }); } return parsed; }
javascript
function parseResponseHeaders (headers) { var parsed = {}; if (headers) { headers.split('\n').forEach(function (line) { var separatorIndex = line.indexOf(':'); var key = line.substr(0, separatorIndex).trim().toLowerCase(); var value = line.substr(separatorIndex + 1).trim().toLowerCase(); if (key) { parsed[key] = value; } }); } return parsed; }
[ "function", "parseResponseHeaders", "(", "headers", ")", "{", "var", "parsed", "=", "{", "}", ";", "if", "(", "headers", ")", "{", "headers", ".", "split", "(", "'\\n'", ")", ".", "forEach", "(", "function", "(", "line", ")", "{", "var", "separatorIndex", "=", "line", ".", "indexOf", "(", "':'", ")", ";", "var", "key", "=", "line", ".", "substr", "(", "0", ",", "separatorIndex", ")", ".", "trim", "(", ")", ".", "toLowerCase", "(", ")", ";", "var", "value", "=", "line", ".", "substr", "(", "separatorIndex", "+", "1", ")", ".", "trim", "(", ")", ".", "toLowerCase", "(", ")", ";", "if", "(", "key", ")", "{", "parsed", "[", "key", "]", "=", "value", ";", "}", "}", ")", ";", "}", "return", "parsed", ";", "}" ]
Parses HTTP response headers, and returns them as an object with header names as keys and header values as values. @param {?string} headers - Response headers, separated by CRLF @returns {object}
[ "Parses", "HTTP", "response", "headers", "and", "returns", "them", "as", "an", "object", "with", "header", "names", "as", "keys", "and", "header", "values", "as", "values", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/XMLHttpRequestPlugin.js#L174-L190
35,346
JamesMessinger/json-schema-lib
lib/api/Config.js
validateConfig
function validateConfig (config) { var type = typeOf(config); if (type.hasValue && !type.isPOJO) { throw ono('Invalid arguments. Expected a configuration object.'); } }
javascript
function validateConfig (config) { var type = typeOf(config); if (type.hasValue && !type.isPOJO) { throw ono('Invalid arguments. Expected a configuration object.'); } }
[ "function", "validateConfig", "(", "config", ")", "{", "var", "type", "=", "typeOf", "(", "config", ")", ";", "if", "(", "type", ".", "hasValue", "&&", "!", "type", ".", "isPOJO", ")", "{", "throw", "ono", "(", "'Invalid arguments. Expected a configuration object.'", ")", ";", "}", "}" ]
Ensures that a user-supplied value is a valid configuration POJO. An error is thrown if the value is invalid. @param {*} config - The user-supplied value to validate
[ "Ensures", "that", "a", "user", "-", "supplied", "value", "is", "a", "valid", "configuration", "POJO", ".", "An", "error", "is", "thrown", "if", "the", "value", "is", "invalid", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/Config.js#L85-L91
35,347
matteodelabre/midijs
lib/file/encoder/header.js
encodeHeader
function encodeHeader(header) { var cursor = new BufferCursor(new buffer.Buffer(6)); cursor.writeUInt16BE(header.getFileType()); cursor.writeUInt16BE(header._trackCount); cursor.writeUInt16BE(header.getTicksPerBeat() & 0x7FFF); return encodeChunk('MThd', cursor.buffer); }
javascript
function encodeHeader(header) { var cursor = new BufferCursor(new buffer.Buffer(6)); cursor.writeUInt16BE(header.getFileType()); cursor.writeUInt16BE(header._trackCount); cursor.writeUInt16BE(header.getTicksPerBeat() & 0x7FFF); return encodeChunk('MThd', cursor.buffer); }
[ "function", "encodeHeader", "(", "header", ")", "{", "var", "cursor", "=", "new", "BufferCursor", "(", "new", "buffer", ".", "Buffer", "(", "6", ")", ")", ";", "cursor", ".", "writeUInt16BE", "(", "header", ".", "getFileType", "(", ")", ")", ";", "cursor", ".", "writeUInt16BE", "(", "header", ".", "_trackCount", ")", ";", "cursor", ".", "writeUInt16BE", "(", "header", ".", "getTicksPerBeat", "(", ")", "&", "0x7FFF", ")", ";", "return", "encodeChunk", "(", "'MThd'", ",", "cursor", ".", "buffer", ")", ";", "}" ]
Encode a MIDI header chunk @param {module:midijs/lib/file/header~Header} header Header to encode @return {Buffer} Encoded header
[ "Encode", "a", "MIDI", "header", "chunk" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/encoder/header.js#L13-L21
35,348
silverbucket/webfinger.js
src/webfinger.js
isSecure
function isSecure(url) { if (typeof url !== 'string') { return false; } var parts = url.split('://'); if (parts[0] === 'https') { return true; } return false; }
javascript
function isSecure(url) { if (typeof url !== 'string') { return false; } var parts = url.split('://'); if (parts[0] === 'https') { return true; } return false; }
[ "function", "isSecure", "(", "url", ")", "{", "if", "(", "typeof", "url", "!==", "'string'", ")", "{", "return", "false", ";", "}", "var", "parts", "=", "url", ".", "split", "(", "'://'", ")", ";", "if", "(", "parts", "[", "0", "]", "===", "'https'", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
given a URL ensures it's HTTPS. returns false for null string or non-HTTPS URL.
[ "given", "a", "URL", "ensures", "it", "s", "HTTPS", ".", "returns", "false", "for", "null", "string", "or", "non", "-", "HTTPS", "URL", "." ]
d99ae22d55b37b517cf1f0713735104c23b0743d
https://github.com/silverbucket/webfinger.js/blob/d99ae22d55b37b517cf1f0713735104c23b0743d/src/webfinger.js#L68-L77
35,349
silverbucket/webfinger.js
src/webfinger.js
__fallbackChecks
function __fallbackChecks(err) { if ((self.config.uri_fallback) && (host !== 'webfist.org') && (uri_index !== URIS.length - 1)) { // we have uris left to try uri_index = uri_index + 1; return __call(); } else if ((!self.config.tls_only) && (protocol === 'https')) { // try normal http uri_index = 0; protocol = 'http'; return __call(); } else if ((self.config.webfist_fallback) && (host !== 'webfist.org')) { // webfist attempt uri_index = 0; protocol = 'http'; host = 'webfist.org'; // webfist will // 1. make a query to the webfist server for the users account // 2. from the response, get a link to the actual webfinger json data // (stored somewhere in control of the user) // 3. make a request to that url and get the json // 4. process it like a normal webfinger response var URL = __buildURL(); self.__fetchJRD(URL, cb, function (data) { // get link to users JRD self.__processJRD(URL, data, cb, function (result) { if ((typeof result.idx.links.webfist === 'object') && (typeof result.idx.links.webfist[0].href === 'string')) { self.__fetchJRD(result.idx.links.webfist[0].href, cb, function (JRD) { self.__processJRD(URL, JRD, cb, function (result) { return cb(null, cb); }); }); } }); }); } else { return cb(err); } }
javascript
function __fallbackChecks(err) { if ((self.config.uri_fallback) && (host !== 'webfist.org') && (uri_index !== URIS.length - 1)) { // we have uris left to try uri_index = uri_index + 1; return __call(); } else if ((!self.config.tls_only) && (protocol === 'https')) { // try normal http uri_index = 0; protocol = 'http'; return __call(); } else if ((self.config.webfist_fallback) && (host !== 'webfist.org')) { // webfist attempt uri_index = 0; protocol = 'http'; host = 'webfist.org'; // webfist will // 1. make a query to the webfist server for the users account // 2. from the response, get a link to the actual webfinger json data // (stored somewhere in control of the user) // 3. make a request to that url and get the json // 4. process it like a normal webfinger response var URL = __buildURL(); self.__fetchJRD(URL, cb, function (data) { // get link to users JRD self.__processJRD(URL, data, cb, function (result) { if ((typeof result.idx.links.webfist === 'object') && (typeof result.idx.links.webfist[0].href === 'string')) { self.__fetchJRD(result.idx.links.webfist[0].href, cb, function (JRD) { self.__processJRD(URL, JRD, cb, function (result) { return cb(null, cb); }); }); } }); }); } else { return cb(err); } }
[ "function", "__fallbackChecks", "(", "err", ")", "{", "if", "(", "(", "self", ".", "config", ".", "uri_fallback", ")", "&&", "(", "host", "!==", "'webfist.org'", ")", "&&", "(", "uri_index", "!==", "URIS", ".", "length", "-", "1", ")", ")", "{", "// we have uris left to try", "uri_index", "=", "uri_index", "+", "1", ";", "return", "__call", "(", ")", ";", "}", "else", "if", "(", "(", "!", "self", ".", "config", ".", "tls_only", ")", "&&", "(", "protocol", "===", "'https'", ")", ")", "{", "// try normal http", "uri_index", "=", "0", ";", "protocol", "=", "'http'", ";", "return", "__call", "(", ")", ";", "}", "else", "if", "(", "(", "self", ".", "config", ".", "webfist_fallback", ")", "&&", "(", "host", "!==", "'webfist.org'", ")", ")", "{", "// webfist attempt", "uri_index", "=", "0", ";", "protocol", "=", "'http'", ";", "host", "=", "'webfist.org'", ";", "// webfist will", "// 1. make a query to the webfist server for the users account", "// 2. from the response, get a link to the actual webfinger json data", "// (stored somewhere in control of the user)", "// 3. make a request to that url and get the json", "// 4. process it like a normal webfinger response", "var", "URL", "=", "__buildURL", "(", ")", ";", "self", ".", "__fetchJRD", "(", "URL", ",", "cb", ",", "function", "(", "data", ")", "{", "// get link to users JRD", "self", ".", "__processJRD", "(", "URL", ",", "data", ",", "cb", ",", "function", "(", "result", ")", "{", "if", "(", "(", "typeof", "result", ".", "idx", ".", "links", ".", "webfist", "===", "'object'", ")", "&&", "(", "typeof", "result", ".", "idx", ".", "links", ".", "webfist", "[", "0", "]", ".", "href", "===", "'string'", ")", ")", "{", "self", ".", "__fetchJRD", "(", "result", ".", "idx", ".", "links", ".", "webfist", "[", "0", "]", ".", "href", ",", "cb", ",", "function", "(", "JRD", ")", "{", "self", ".", "__processJRD", "(", "URL", ",", "JRD", ",", "cb", ",", "function", "(", "result", ")", "{", "return", "cb", "(", "null", ",", "cb", ")", ";", "}", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", "else", "{", "return", "cb", "(", "err", ")", ";", "}", "}" ]
control flow for failures, what to do in various cases, etc.
[ "control", "flow", "for", "failures", "what", "to", "do", "in", "various", "cases", "etc", "." ]
d99ae22d55b37b517cf1f0713735104c23b0743d
https://github.com/silverbucket/webfinger.js/blob/d99ae22d55b37b517cf1f0713735104c23b0743d/src/webfinger.js#L356-L390
35,350
LivePersonInc/chronosjs
src/Channels.js
_wrapCalls
function _wrapCalls(options){ return function(){ var api; options.func.apply(options.context, Array.prototype.slice.call(arguments, 0)); for (var i = 0; i < externalAPIS.length; i++) { api = externalAPIS[i]; if (api[options.triggerType]) { try { api[options.triggerType].apply(api.context,Array.prototype.slice.call(arguments, 0)); } catch (exc) {} } } }; }
javascript
function _wrapCalls(options){ return function(){ var api; options.func.apply(options.context, Array.prototype.slice.call(arguments, 0)); for (var i = 0; i < externalAPIS.length; i++) { api = externalAPIS[i]; if (api[options.triggerType]) { try { api[options.triggerType].apply(api.context,Array.prototype.slice.call(arguments, 0)); } catch (exc) {} } } }; }
[ "function", "_wrapCalls", "(", "options", ")", "{", "return", "function", "(", ")", "{", "var", "api", ";", "options", ".", "func", ".", "apply", "(", "options", ".", "context", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "externalAPIS", ".", "length", ";", "i", "++", ")", "{", "api", "=", "externalAPIS", "[", "i", "]", ";", "if", "(", "api", "[", "options", ".", "triggerType", "]", ")", "{", "try", "{", "api", "[", "options", ".", "triggerType", "]", ".", "apply", "(", "api", ".", "context", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ")", ";", "}", "catch", "(", "exc", ")", "{", "}", "}", "}", "}", ";", "}" ]
Wraps API calls to trigger other registered functions @param options @returns {Function} @private
[ "Wraps", "API", "calls", "to", "trigger", "other", "registered", "functions" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/Channels.js#L79-L95
35,351
JamesMessinger/json-schema-lib
lib/api/PluginHelper/callAsyncPlugin.js
callAsyncPlugin
function callAsyncPlugin (pluginHelper, methodName, args, callback) { var plugins = pluginHelper.filter(filterByMethod(methodName)); args.schema = pluginHelper[__internal].schema; args.config = args.schema.config; safeCall(callNextPlugin, plugins, methodName, args, callback); }
javascript
function callAsyncPlugin (pluginHelper, methodName, args, callback) { var plugins = pluginHelper.filter(filterByMethod(methodName)); args.schema = pluginHelper[__internal].schema; args.config = args.schema.config; safeCall(callNextPlugin, plugins, methodName, args, callback); }
[ "function", "callAsyncPlugin", "(", "pluginHelper", ",", "methodName", ",", "args", ",", "callback", ")", "{", "var", "plugins", "=", "pluginHelper", ".", "filter", "(", "filterByMethod", "(", "methodName", ")", ")", ";", "args", ".", "schema", "=", "pluginHelper", "[", "__internal", "]", ".", "schema", ";", "args", ".", "config", "=", "args", ".", "schema", ".", "config", ";", "safeCall", "(", "callNextPlugin", ",", "plugins", ",", "methodName", ",", "args", ",", "callback", ")", ";", "}" ]
Calls an asynchronous plugin method with the given arguments. @param {PluginHelper} pluginHelper - The {@link PluginHelper} whose plugins are called @param {string} methodName - The name of the plugin method to call @param {object} args - The arguments to pass to the method @param {function} callback - The callback to call when the method finishes
[ "Calls", "an", "asynchronous", "plugin", "method", "with", "the", "given", "arguments", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/PluginHelper/callAsyncPlugin.js#L18-L24
35,352
glennjones/elsewhere-profiles
lib/utilities.js
getNodeVaue
function getNodeVaue(path, obj) { // Gets a value from a JSON object // vcard[0].url[0] var output = null; try { var arrayDots = path.split("."); for (var i = 0; i < arrayDots.length; i++) { if (arrayDots[i].indexOf('[') > -1) { // Reconstructs and adds access to array of objects var arrayAB = arrayDots[i].split("["); var arrayName = arrayAB[0]; var arrayPosition = Number(arrayAB[1].substring(0, arrayAB[1].length - 1)); if (obj[arrayName] != null || obj[arrayName] != 'undefined') { if (obj[arrayName][arrayPosition] != null || obj[arrayName][arrayPosition] != 'undefined') obj = obj[arrayName][arrayPosition]; } else { currentObject = null; } } else { // Adds access to a property using property array ["given-name"] if (obj[arrayDots[i]] != null || obj[arrayDots[i]] != 'undefined') obj = obj[arrayDots[i]]; } } output = obj; } catch (err) { // Add error capture output = null; } return output; }
javascript
function getNodeVaue(path, obj) { // Gets a value from a JSON object // vcard[0].url[0] var output = null; try { var arrayDots = path.split("."); for (var i = 0; i < arrayDots.length; i++) { if (arrayDots[i].indexOf('[') > -1) { // Reconstructs and adds access to array of objects var arrayAB = arrayDots[i].split("["); var arrayName = arrayAB[0]; var arrayPosition = Number(arrayAB[1].substring(0, arrayAB[1].length - 1)); if (obj[arrayName] != null || obj[arrayName] != 'undefined') { if (obj[arrayName][arrayPosition] != null || obj[arrayName][arrayPosition] != 'undefined') obj = obj[arrayName][arrayPosition]; } else { currentObject = null; } } else { // Adds access to a property using property array ["given-name"] if (obj[arrayDots[i]] != null || obj[arrayDots[i]] != 'undefined') obj = obj[arrayDots[i]]; } } output = obj; } catch (err) { // Add error capture output = null; } return output; }
[ "function", "getNodeVaue", "(", "path", ",", "obj", ")", "{", "// Gets a value from a JSON object", "// vcard[0].url[0]", "var", "output", "=", "null", ";", "try", "{", "var", "arrayDots", "=", "path", ".", "split", "(", "\".\"", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arrayDots", ".", "length", ";", "i", "++", ")", "{", "if", "(", "arrayDots", "[", "i", "]", ".", "indexOf", "(", "'['", ")", ">", "-", "1", ")", "{", "// Reconstructs and adds access to array of objects", "var", "arrayAB", "=", "arrayDots", "[", "i", "]", ".", "split", "(", "\"[\"", ")", ";", "var", "arrayName", "=", "arrayAB", "[", "0", "]", ";", "var", "arrayPosition", "=", "Number", "(", "arrayAB", "[", "1", "]", ".", "substring", "(", "0", ",", "arrayAB", "[", "1", "]", ".", "length", "-", "1", ")", ")", ";", "if", "(", "obj", "[", "arrayName", "]", "!=", "null", "||", "obj", "[", "arrayName", "]", "!=", "'undefined'", ")", "{", "if", "(", "obj", "[", "arrayName", "]", "[", "arrayPosition", "]", "!=", "null", "||", "obj", "[", "arrayName", "]", "[", "arrayPosition", "]", "!=", "'undefined'", ")", "obj", "=", "obj", "[", "arrayName", "]", "[", "arrayPosition", "]", ";", "}", "else", "{", "currentObject", "=", "null", ";", "}", "}", "else", "{", "// Adds access to a property using property array [\"given-name\"]", "if", "(", "obj", "[", "arrayDots", "[", "i", "]", "]", "!=", "null", "||", "obj", "[", "arrayDots", "[", "i", "]", "]", "!=", "'undefined'", ")", "obj", "=", "obj", "[", "arrayDots", "[", "i", "]", "]", ";", "}", "}", "output", "=", "obj", ";", "}", "catch", "(", "err", ")", "{", "// Add error capture", "output", "=", "null", ";", "}", "return", "output", ";", "}" ]
a helper function, finds a property value of a given object literal
[ "a", "helper", "function", "finds", "a", "property", "value", "of", "a", "given", "object", "literal" ]
f86a5d040d540d4f8ed4f86518b75a0e6c8855ba
https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/utilities.js#L27-L62
35,353
glennjones/elsewhere-profiles
lib/utilities.js
getIdentity
function getIdentity(urlStr, urlTemplates, www) { var identity = {}; urlObj = urlParser.parse(urlStr); // Loop all the urlMappings for site object for(var y = 0; y <= urlTemplates.length-1; y++){ urlTemplate = urlTemplates[y]; // remove http protocol urlTemplate = removeHttpHttps(urlTemplate); // if the urlTemplate contains a username or userid parse it if (urlTemplate != '' && (urlTemplate.indexOf('{username}') > -1 || urlTemplate.indexOf('{userid}') > -1)) { // break up url template var parts = urlTemplate.split(/\{userid\}|\{username\}/), startMatch = false, endMatch = false, user = urlObj.href // remove protocol, querystring and fragment user = user.replace(urlObj.hash, ''); user = user.replace(urlObj.search, ''); user = removeHttpHttps(user); // remove www if subdomain is optional if(www){ user = user.replace('www.', '') ; urlStr = urlStr.replace('www.', '') ; } // remove any trailing / if (endsWith(user,'/')) user = user.substring(0, user.length - 1); // remove unwanted front section of url string if (user.indexOf(parts[0]) === 0){ startMatch = true; part = parts[0]; user = user.substring(part.length, user.length); } // remove unwanted end section of url string if (parts.length === 2){ // if no end part or its just and trailing / if (parts[1].length > 0 && parts[1] !== '/'){ // end part matches template if (endsWith(user,parts[1])){ endMatch = true; user = user.replace(parts[1], ''); } else if (endsWith(user,parts[1] + '/')) { // end part matches template with a trailing / endMatch = true; user = user.replace(parts[1] + '/', ''); } } else { endMatch = true; } } // if the user contain anymore / then do not use it if (user.indexOf("/") > -1) endMatch = false; if (startMatch && endMatch){ identity = {}; identity.domain = urlObj.host; identity.matchedUrl = urlStr; if (urlTemplate.indexOf("{username}") > -1){ identity.userName = user; identity.sgn = "sgn://" + urlObj.host + "/?ident=" + user; } if (urlTemplate.indexOf("{userid}") > -1){ identity.userId = user; identity.sgn = "sgn://" + urlObj.host + "/?pk=" + user; } break; } } } return identity; }
javascript
function getIdentity(urlStr, urlTemplates, www) { var identity = {}; urlObj = urlParser.parse(urlStr); // Loop all the urlMappings for site object for(var y = 0; y <= urlTemplates.length-1; y++){ urlTemplate = urlTemplates[y]; // remove http protocol urlTemplate = removeHttpHttps(urlTemplate); // if the urlTemplate contains a username or userid parse it if (urlTemplate != '' && (urlTemplate.indexOf('{username}') > -1 || urlTemplate.indexOf('{userid}') > -1)) { // break up url template var parts = urlTemplate.split(/\{userid\}|\{username\}/), startMatch = false, endMatch = false, user = urlObj.href // remove protocol, querystring and fragment user = user.replace(urlObj.hash, ''); user = user.replace(urlObj.search, ''); user = removeHttpHttps(user); // remove www if subdomain is optional if(www){ user = user.replace('www.', '') ; urlStr = urlStr.replace('www.', '') ; } // remove any trailing / if (endsWith(user,'/')) user = user.substring(0, user.length - 1); // remove unwanted front section of url string if (user.indexOf(parts[0]) === 0){ startMatch = true; part = parts[0]; user = user.substring(part.length, user.length); } // remove unwanted end section of url string if (parts.length === 2){ // if no end part or its just and trailing / if (parts[1].length > 0 && parts[1] !== '/'){ // end part matches template if (endsWith(user,parts[1])){ endMatch = true; user = user.replace(parts[1], ''); } else if (endsWith(user,parts[1] + '/')) { // end part matches template with a trailing / endMatch = true; user = user.replace(parts[1] + '/', ''); } } else { endMatch = true; } } // if the user contain anymore / then do not use it if (user.indexOf("/") > -1) endMatch = false; if (startMatch && endMatch){ identity = {}; identity.domain = urlObj.host; identity.matchedUrl = urlStr; if (urlTemplate.indexOf("{username}") > -1){ identity.userName = user; identity.sgn = "sgn://" + urlObj.host + "/?ident=" + user; } if (urlTemplate.indexOf("{userid}") > -1){ identity.userId = user; identity.sgn = "sgn://" + urlObj.host + "/?pk=" + user; } break; } } } return identity; }
[ "function", "getIdentity", "(", "urlStr", ",", "urlTemplates", ",", "www", ")", "{", "var", "identity", "=", "{", "}", ";", "urlObj", "=", "urlParser", ".", "parse", "(", "urlStr", ")", ";", "// Loop all the urlMappings for site object", "for", "(", "var", "y", "=", "0", ";", "y", "<=", "urlTemplates", ".", "length", "-", "1", ";", "y", "++", ")", "{", "urlTemplate", "=", "urlTemplates", "[", "y", "]", ";", "// remove http protocol ", "urlTemplate", "=", "removeHttpHttps", "(", "urlTemplate", ")", ";", "// if the urlTemplate contains a username or userid parse it", "if", "(", "urlTemplate", "!=", "''", "&&", "(", "urlTemplate", ".", "indexOf", "(", "'{username}'", ")", ">", "-", "1", "||", "urlTemplate", ".", "indexOf", "(", "'{userid}'", ")", ">", "-", "1", ")", ")", "{", "// break up url template", "var", "parts", "=", "urlTemplate", ".", "split", "(", "/", "\\{userid\\}|\\{username\\}", "/", ")", ",", "startMatch", "=", "false", ",", "endMatch", "=", "false", ",", "user", "=", "urlObj", ".", "href", "// remove protocol, querystring and fragment", "user", "=", "user", ".", "replace", "(", "urlObj", ".", "hash", ",", "''", ")", ";", "user", "=", "user", ".", "replace", "(", "urlObj", ".", "search", ",", "''", ")", ";", "user", "=", "removeHttpHttps", "(", "user", ")", ";", "// remove www if subdomain is optional", "if", "(", "www", ")", "{", "user", "=", "user", ".", "replace", "(", "'www.'", ",", "''", ")", ";", "urlStr", "=", "urlStr", ".", "replace", "(", "'www.'", ",", "''", ")", ";", "}", "// remove any trailing /", "if", "(", "endsWith", "(", "user", ",", "'/'", ")", ")", "user", "=", "user", ".", "substring", "(", "0", ",", "user", ".", "length", "-", "1", ")", ";", "// remove unwanted front section of url string", "if", "(", "user", ".", "indexOf", "(", "parts", "[", "0", "]", ")", "===", "0", ")", "{", "startMatch", "=", "true", ";", "part", "=", "parts", "[", "0", "]", ";", "user", "=", "user", ".", "substring", "(", "part", ".", "length", ",", "user", ".", "length", ")", ";", "}", "// remove unwanted end section of url string", "if", "(", "parts", ".", "length", "===", "2", ")", "{", "// if no end part or its just and trailing /", "if", "(", "parts", "[", "1", "]", ".", "length", ">", "0", "&&", "parts", "[", "1", "]", "!==", "'/'", ")", "{", "// end part matches template", "if", "(", "endsWith", "(", "user", ",", "parts", "[", "1", "]", ")", ")", "{", "endMatch", "=", "true", ";", "user", "=", "user", ".", "replace", "(", "parts", "[", "1", "]", ",", "''", ")", ";", "}", "else", "if", "(", "endsWith", "(", "user", ",", "parts", "[", "1", "]", "+", "'/'", ")", ")", "{", "// end part matches template with a trailing /", "endMatch", "=", "true", ";", "user", "=", "user", ".", "replace", "(", "parts", "[", "1", "]", "+", "'/'", ",", "''", ")", ";", "}", "}", "else", "{", "endMatch", "=", "true", ";", "}", "}", "// if the user contain anymore / then do not use it", "if", "(", "user", ".", "indexOf", "(", "\"/\"", ")", ">", "-", "1", ")", "endMatch", "=", "false", ";", "if", "(", "startMatch", "&&", "endMatch", ")", "{", "identity", "=", "{", "}", ";", "identity", ".", "domain", "=", "urlObj", ".", "host", ";", "identity", ".", "matchedUrl", "=", "urlStr", ";", "if", "(", "urlTemplate", ".", "indexOf", "(", "\"{username}\"", ")", ">", "-", "1", ")", "{", "identity", ".", "userName", "=", "user", ";", "identity", ".", "sgn", "=", "\"sgn://\"", "+", "urlObj", ".", "host", "+", "\"/?ident=\"", "+", "user", ";", "}", "if", "(", "urlTemplate", ".", "indexOf", "(", "\"{userid}\"", ")", ">", "-", "1", ")", "{", "identity", ".", "userId", "=", "user", ";", "identity", ".", "sgn", "=", "\"sgn://\"", "+", "urlObj", ".", "host", "+", "\"/?pk=\"", "+", "user", ";", "}", "break", ";", "}", "}", "}", "return", "identity", ";", "}" ]
find the sgn and builds the identity object
[ "find", "the", "sgn", "and", "builds", "the", "identity", "object" ]
f86a5d040d540d4f8ed4f86518b75a0e6c8855ba
https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/utilities.js#L66-L158
35,354
glennjones/elsewhere-profiles
lib/utilities.js
endsWith
function endsWith(str,test){ var lastIndex = str.lastIndexOf(test); return (lastIndex != -1) && (lastIndex + test.length == str.length); }
javascript
function endsWith(str,test){ var lastIndex = str.lastIndexOf(test); return (lastIndex != -1) && (lastIndex + test.length == str.length); }
[ "function", "endsWith", "(", "str", ",", "test", ")", "{", "var", "lastIndex", "=", "str", ".", "lastIndexOf", "(", "test", ")", ";", "return", "(", "lastIndex", "!=", "-", "1", ")", "&&", "(", "lastIndex", "+", "test", ".", "length", "==", "str", ".", "length", ")", ";", "}" ]
simple endsWith function. Use with care
[ "simple", "endsWith", "function", ".", "Use", "with", "care" ]
f86a5d040d540d4f8ed4f86518b75a0e6c8855ba
https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/utilities.js#L199-L202
35,355
glennjones/elsewhere-profiles
lib/utilities.js
isUrl
function isUrl (obj) { if(isString(obj)){ if((obj.indexOf('http://') > -1 || obj.indexOf('https://') > -1) && obj.indexOf('.') > -1) return true else return false }else{ return false; } }
javascript
function isUrl (obj) { if(isString(obj)){ if((obj.indexOf('http://') > -1 || obj.indexOf('https://') > -1) && obj.indexOf('.') > -1) return true else return false }else{ return false; } }
[ "function", "isUrl", "(", "obj", ")", "{", "if", "(", "isString", "(", "obj", ")", ")", "{", "if", "(", "(", "obj", ".", "indexOf", "(", "'http://'", ")", ">", "-", "1", "||", "obj", ".", "indexOf", "(", "'https://'", ")", ">", "-", "1", ")", "&&", "obj", ".", "indexOf", "(", "'.'", ")", ">", "-", "1", ")", "return", "true", "else", "return", "false", "}", "else", "{", "return", "false", ";", "}", "}" ]
is an object a URL - very simple version
[ "is", "an", "object", "a", "URL", "-", "very", "simple", "version" ]
f86a5d040d540d4f8ed4f86518b75a0e6c8855ba
https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/utilities.js#L227-L237
35,356
matteodelabre/midijs
lib/file/encoder/track.js
encodeTrack
function encodeTrack(track) { var events = track.getEvents(), data = [], length = events.length, i, runningStatus = null, result; for (i = 0; i < length; i += 1) { result = encodeEvent(events[i], runningStatus); runningStatus = result.runningStatus; data[i] = result.data; } return encodeChunk('MTrk', buffer.Buffer.concat(data)); }
javascript
function encodeTrack(track) { var events = track.getEvents(), data = [], length = events.length, i, runningStatus = null, result; for (i = 0; i < length; i += 1) { result = encodeEvent(events[i], runningStatus); runningStatus = result.runningStatus; data[i] = result.data; } return encodeChunk('MTrk', buffer.Buffer.concat(data)); }
[ "function", "encodeTrack", "(", "track", ")", "{", "var", "events", "=", "track", ".", "getEvents", "(", ")", ",", "data", "=", "[", "]", ",", "length", "=", "events", ".", "length", ",", "i", ",", "runningStatus", "=", "null", ",", "result", ";", "for", "(", "i", "=", "0", ";", "i", "<", "length", ";", "i", "+=", "1", ")", "{", "result", "=", "encodeEvent", "(", "events", "[", "i", "]", ",", "runningStatus", ")", ";", "runningStatus", "=", "result", ".", "runningStatus", ";", "data", "[", "i", "]", "=", "result", ".", "data", ";", "}", "return", "encodeChunk", "(", "'MTrk'", ",", "buffer", ".", "Buffer", ".", "concat", "(", "data", ")", ")", ";", "}" ]
Encode a MIDI track chunk @param {module:midijs/lib/file/track~Track} track Track to encode @return {Buffer} Encoded track
[ "Encode", "a", "MIDI", "track", "chunk" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/encoder/track.js#L13-L26
35,357
claudio-silva/grunt-angular-builder
tasks/middleware/analyzeSourceCode.js
AnalyzeSourceCodeMiddleware
function AnalyzeSourceCodeMiddleware (context) { var grunt = context.grunt; //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { var src = util.sortFilesBeforeSubfolders (filesArray.src); // Load the script files and scan them for module definitions. src.forEach (function (path) { if (!grunt.file.exists (path)) { warn ('Source file "' + path + '" not found.'); return; } // Read the script and scan it for module declarations. var script = grunt.file.read (path); /** @type {ModuleHeaderInfo[]} */ var moduleHeaders; try { moduleHeaders = sourceExtract.extractModuleHeaders (script); } catch (e) { if (typeof e === 'string') return warn (e + NL + reportErrorLocation (path)); throw e; } // Ignore irrelevant files. if (!moduleHeaders.length) { if (!filesArray.forceInclude || !grunt.file.isMatch ({matchBase: true}, filesArray.forceInclude, path)) { info ('Ignored file: %', path.cyan); return; } context.standaloneScripts.push ({ path: path, content: script }); } else moduleHeaders.forEach (function (header) { setupModuleInfo (header, script, path); }); }); }; this.trace = function (module) { /* jshint unused: vars */ // Do nothing }; this.build = function (targetScript) { /* jshint unused: vars */ // Do nothing }; //-------------------------------------------------------------------------------------------------------------------- // PRIVATE //-------------------------------------------------------------------------------------------------------------------- /** * Store information about the specified module retrieved from the given source code on the specified file. * * @param {ModuleHeaderInfo} moduleHeader * @param {string} fileContent * @param {string} filePath */ function setupModuleInfo (moduleHeader, fileContent, filePath) { // Get information about the specified module. var module = context.modules[moduleHeader.name]; // If this is the first time a specific module is mentioned, create the respective information record. if (!module) module = context.modules[moduleHeader.name] = new ModuleDef (moduleHeader.name); // Skip the file if it defines an external module. else if (module.external) return; // Reject additional attempts to redeclare a module (only appending is allowed). else if (module.head && !moduleHeader.append) fatal ('Can\'t redeclare module <cyan>%</cyan>', moduleHeader.name); // The file is appending definitions to a module declared elsewhere. if (moduleHeader.append) { // Append the file path to the paths list. if (!~module.bodyPaths.indexOf (filePath)) { module.bodies.push (fileContent); module.bodyPaths.push (filePath); } } // Otherwise, the file contains a module declaration. else { if (module.head) fatal ('Duplicate module definition: <cyan>%</cyan>', moduleHeader.name); module.head = fileContent; module.headPath = filePath; module.requires = moduleHeader.requires; } module.configFn = moduleHeader.configFn; } }
javascript
function AnalyzeSourceCodeMiddleware (context) { var grunt = context.grunt; //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { var src = util.sortFilesBeforeSubfolders (filesArray.src); // Load the script files and scan them for module definitions. src.forEach (function (path) { if (!grunt.file.exists (path)) { warn ('Source file "' + path + '" not found.'); return; } // Read the script and scan it for module declarations. var script = grunt.file.read (path); /** @type {ModuleHeaderInfo[]} */ var moduleHeaders; try { moduleHeaders = sourceExtract.extractModuleHeaders (script); } catch (e) { if (typeof e === 'string') return warn (e + NL + reportErrorLocation (path)); throw e; } // Ignore irrelevant files. if (!moduleHeaders.length) { if (!filesArray.forceInclude || !grunt.file.isMatch ({matchBase: true}, filesArray.forceInclude, path)) { info ('Ignored file: %', path.cyan); return; } context.standaloneScripts.push ({ path: path, content: script }); } else moduleHeaders.forEach (function (header) { setupModuleInfo (header, script, path); }); }); }; this.trace = function (module) { /* jshint unused: vars */ // Do nothing }; this.build = function (targetScript) { /* jshint unused: vars */ // Do nothing }; //-------------------------------------------------------------------------------------------------------------------- // PRIVATE //-------------------------------------------------------------------------------------------------------------------- /** * Store information about the specified module retrieved from the given source code on the specified file. * * @param {ModuleHeaderInfo} moduleHeader * @param {string} fileContent * @param {string} filePath */ function setupModuleInfo (moduleHeader, fileContent, filePath) { // Get information about the specified module. var module = context.modules[moduleHeader.name]; // If this is the first time a specific module is mentioned, create the respective information record. if (!module) module = context.modules[moduleHeader.name] = new ModuleDef (moduleHeader.name); // Skip the file if it defines an external module. else if (module.external) return; // Reject additional attempts to redeclare a module (only appending is allowed). else if (module.head && !moduleHeader.append) fatal ('Can\'t redeclare module <cyan>%</cyan>', moduleHeader.name); // The file is appending definitions to a module declared elsewhere. if (moduleHeader.append) { // Append the file path to the paths list. if (!~module.bodyPaths.indexOf (filePath)) { module.bodies.push (fileContent); module.bodyPaths.push (filePath); } } // Otherwise, the file contains a module declaration. else { if (module.head) fatal ('Duplicate module definition: <cyan>%</cyan>', moduleHeader.name); module.head = fileContent; module.headPath = filePath; module.requires = moduleHeader.requires; } module.configFn = moduleHeader.configFn; } }
[ "function", "AnalyzeSourceCodeMiddleware", "(", "context", ")", "{", "var", "grunt", "=", "context", ".", "grunt", ";", "//--------------------------------------------------------------------------------------------------------------------", "// PUBLIC API", "//--------------------------------------------------------------------------------------------------------------------", "this", ".", "analyze", "=", "function", "(", "filesArray", ")", "{", "var", "src", "=", "util", ".", "sortFilesBeforeSubfolders", "(", "filesArray", ".", "src", ")", ";", "// Load the script files and scan them for module definitions.", "src", ".", "forEach", "(", "function", "(", "path", ")", "{", "if", "(", "!", "grunt", ".", "file", ".", "exists", "(", "path", ")", ")", "{", "warn", "(", "'Source file \"'", "+", "path", "+", "'\" not found.'", ")", ";", "return", ";", "}", "// Read the script and scan it for module declarations.", "var", "script", "=", "grunt", ".", "file", ".", "read", "(", "path", ")", ";", "/** @type {ModuleHeaderInfo[]} */", "var", "moduleHeaders", ";", "try", "{", "moduleHeaders", "=", "sourceExtract", ".", "extractModuleHeaders", "(", "script", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "typeof", "e", "===", "'string'", ")", "return", "warn", "(", "e", "+", "NL", "+", "reportErrorLocation", "(", "path", ")", ")", ";", "throw", "e", ";", "}", "// Ignore irrelevant files.", "if", "(", "!", "moduleHeaders", ".", "length", ")", "{", "if", "(", "!", "filesArray", ".", "forceInclude", "||", "!", "grunt", ".", "file", ".", "isMatch", "(", "{", "matchBase", ":", "true", "}", ",", "filesArray", ".", "forceInclude", ",", "path", ")", ")", "{", "info", "(", "'Ignored file: %'", ",", "path", ".", "cyan", ")", ";", "return", ";", "}", "context", ".", "standaloneScripts", ".", "push", "(", "{", "path", ":", "path", ",", "content", ":", "script", "}", ")", ";", "}", "else", "moduleHeaders", ".", "forEach", "(", "function", "(", "header", ")", "{", "setupModuleInfo", "(", "header", ",", "script", ",", "path", ")", ";", "}", ")", ";", "}", ")", ";", "}", ";", "this", ".", "trace", "=", "function", "(", "module", ")", "{", "/* jshint unused: vars */", "// Do nothing", "}", ";", "this", ".", "build", "=", "function", "(", "targetScript", ")", "{", "/* jshint unused: vars */", "// Do nothing", "}", ";", "//--------------------------------------------------------------------------------------------------------------------", "// PRIVATE", "//--------------------------------------------------------------------------------------------------------------------", "/**\n * Store information about the specified module retrieved from the given source code on the specified file.\n *\n * @param {ModuleHeaderInfo} moduleHeader\n * @param {string} fileContent\n * @param {string} filePath\n */", "function", "setupModuleInfo", "(", "moduleHeader", ",", "fileContent", ",", "filePath", ")", "{", "// Get information about the specified module.", "var", "module", "=", "context", ".", "modules", "[", "moduleHeader", ".", "name", "]", ";", "// If this is the first time a specific module is mentioned, create the respective information record.", "if", "(", "!", "module", ")", "module", "=", "context", ".", "modules", "[", "moduleHeader", ".", "name", "]", "=", "new", "ModuleDef", "(", "moduleHeader", ".", "name", ")", ";", "// Skip the file if it defines an external module.", "else", "if", "(", "module", ".", "external", ")", "return", ";", "// Reject additional attempts to redeclare a module (only appending is allowed).", "else", "if", "(", "module", ".", "head", "&&", "!", "moduleHeader", ".", "append", ")", "fatal", "(", "'Can\\'t redeclare module <cyan>%</cyan>'", ",", "moduleHeader", ".", "name", ")", ";", "// The file is appending definitions to a module declared elsewhere.", "if", "(", "moduleHeader", ".", "append", ")", "{", "// Append the file path to the paths list.", "if", "(", "!", "~", "module", ".", "bodyPaths", ".", "indexOf", "(", "filePath", ")", ")", "{", "module", ".", "bodies", ".", "push", "(", "fileContent", ")", ";", "module", ".", "bodyPaths", ".", "push", "(", "filePath", ")", ";", "}", "}", "// Otherwise, the file contains a module declaration.", "else", "{", "if", "(", "module", ".", "head", ")", "fatal", "(", "'Duplicate module definition: <cyan>%</cyan>'", ",", "moduleHeader", ".", "name", ")", ";", "module", ".", "head", "=", "fileContent", ";", "module", ".", "headPath", "=", "filePath", ";", "module", ".", "requires", "=", "moduleHeader", ".", "requires", ";", "}", "module", ".", "configFn", "=", "moduleHeader", ".", "configFn", ";", "}", "}" ]
An AngularJS source code loader and analyser middleware. @constructor @implements {MiddlewareInterface} @param {Context} context The execution context for the middleware stack.
[ "An", "AngularJS", "source", "code", "loader", "and", "analyser", "middleware", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/analyzeSourceCode.js#L33-L140
35,358
JamesMessinger/json-schema-lib
lib/plugins/FileSystemPlugin.js
resolveURL
function resolveURL (args) { var from = args.from; var to = args.to; var next = args.next; if (protocolPattern.test(from) || protocolPattern.test(to)) { // It's a URL, not a filesystem path, so let some other plugin resolve it return next(); } if (from) { // The `from` path needs to be a directory, not a file. So, if the last character is NOT a // path separator, then we need to remove the filename from the path if (pathSeparators.indexOf(from[from.length - 1]) === -1) { from = path.dirname(from); } return path.resolve(from, to); } else { // Resolve the `to` path against the current working directory return path.resolve(to); } }
javascript
function resolveURL (args) { var from = args.from; var to = args.to; var next = args.next; if (protocolPattern.test(from) || protocolPattern.test(to)) { // It's a URL, not a filesystem path, so let some other plugin resolve it return next(); } if (from) { // The `from` path needs to be a directory, not a file. So, if the last character is NOT a // path separator, then we need to remove the filename from the path if (pathSeparators.indexOf(from[from.length - 1]) === -1) { from = path.dirname(from); } return path.resolve(from, to); } else { // Resolve the `to` path against the current working directory return path.resolve(to); } }
[ "function", "resolveURL", "(", "args", ")", "{", "var", "from", "=", "args", ".", "from", ";", "var", "to", "=", "args", ".", "to", ";", "var", "next", "=", "args", ".", "next", ";", "if", "(", "protocolPattern", ".", "test", "(", "from", ")", "||", "protocolPattern", ".", "test", "(", "to", ")", ")", "{", "// It's a URL, not a filesystem path, so let some other plugin resolve it", "return", "next", "(", ")", ";", "}", "if", "(", "from", ")", "{", "// The `from` path needs to be a directory, not a file. So, if the last character is NOT a", "// path separator, then we need to remove the filename from the path", "if", "(", "pathSeparators", ".", "indexOf", "(", "from", "[", "from", ".", "length", "-", "1", "]", ")", "===", "-", "1", ")", "{", "from", "=", "path", ".", "dirname", "(", "from", ")", ";", "}", "return", "path", ".", "resolve", "(", "from", ",", "to", ")", ";", "}", "else", "{", "// Resolve the `to` path against the current working directory", "return", "path", ".", "resolve", "(", "to", ")", ";", "}", "}" ]
Resolves a local filesystem path, relative to a base path. @param {?string} args.from The base path to resolve against. If unset, then the current working directory is used. @param {string} args.to The path to resolve. This may be absolute or relative. If relative, then it will be resolved against {@link args.from} @param {function} args.next Calls the next plugin, if the path is not a filesystem path. @returns {string|undefined}
[ "Resolves", "a", "local", "filesystem", "path", "relative", "to", "a", "base", "path", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/FileSystemPlugin.js#L45-L68
35,359
JamesMessinger/json-schema-lib
lib/plugins/FileSystemPlugin.js
readFileSync
function readFileSync (args) { var file = args.file; var next = args.next; if (isUnsupportedPath(file.url)) { // It's not a filesystem path, so let some other plugin handle it return next(); } var filepath = getFileSystemPath(file.url); inferFileMetadata(file); return fs.readFileSync(filepath); }
javascript
function readFileSync (args) { var file = args.file; var next = args.next; if (isUnsupportedPath(file.url)) { // It's not a filesystem path, so let some other plugin handle it return next(); } var filepath = getFileSystemPath(file.url); inferFileMetadata(file); return fs.readFileSync(filepath); }
[ "function", "readFileSync", "(", "args", ")", "{", "var", "file", "=", "args", ".", "file", ";", "var", "next", "=", "args", ".", "next", ";", "if", "(", "isUnsupportedPath", "(", "file", ".", "url", ")", ")", "{", "// It's not a filesystem path, so let some other plugin handle it", "return", "next", "(", ")", ";", "}", "var", "filepath", "=", "getFileSystemPath", "(", "file", ".", "url", ")", ";", "inferFileMetadata", "(", "file", ")", ";", "return", "fs", ".", "readFileSync", "(", "filepath", ")", ";", "}" ]
Synchronously reads a file from the local filesystem. @param {File} args.file - The {@link File} to read @param {function} args.next - Calls the next plugin, if the file is not a local filesystem file @returns {Buffer|undefined}
[ "Synchronously", "reads", "a", "file", "from", "the", "local", "filesystem", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/FileSystemPlugin.js#L77-L90
35,360
JamesMessinger/json-schema-lib
lib/plugins/FileSystemPlugin.js
inferFileMetadata
function inferFileMetadata (file) { file.mimeType = lowercase(mime.lookup(file.url) || null); file.encoding = lowercase(mime.charset(file.mimeType) || null); }
javascript
function inferFileMetadata (file) { file.mimeType = lowercase(mime.lookup(file.url) || null); file.encoding = lowercase(mime.charset(file.mimeType) || null); }
[ "function", "inferFileMetadata", "(", "file", ")", "{", "file", ".", "mimeType", "=", "lowercase", "(", "mime", ".", "lookup", "(", "file", ".", "url", ")", "||", "null", ")", ";", "file", ".", "encoding", "=", "lowercase", "(", "mime", ".", "charset", "(", "file", ".", "mimeType", ")", "||", "null", ")", ";", "}" ]
Infers the file's MIME type and encoding, based on its file extension. @param {File} file
[ "Infers", "the", "file", "s", "MIME", "type", "and", "encoding", "based", "on", "its", "file", "extension", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/FileSystemPlugin.js#L131-L134
35,361
JamesMessinger/json-schema-lib
lib/api/PluginHelper/validatePlugins.js
validatePlugins
function validatePlugins (plugins) { var type = typeOf(plugins); if (type.hasValue) { if (type.isArray) { // Make sure all the items in the array are valid plugins plugins.forEach(validatePlugin); } else { throw ono('Invalid arguments. Expected an array of plugins.'); } } }
javascript
function validatePlugins (plugins) { var type = typeOf(plugins); if (type.hasValue) { if (type.isArray) { // Make sure all the items in the array are valid plugins plugins.forEach(validatePlugin); } else { throw ono('Invalid arguments. Expected an array of plugins.'); } } }
[ "function", "validatePlugins", "(", "plugins", ")", "{", "var", "type", "=", "typeOf", "(", "plugins", ")", ";", "if", "(", "type", ".", "hasValue", ")", "{", "if", "(", "type", ".", "isArray", ")", "{", "// Make sure all the items in the array are valid plugins", "plugins", ".", "forEach", "(", "validatePlugin", ")", ";", "}", "else", "{", "throw", "ono", "(", "'Invalid arguments. Expected an array of plugins.'", ")", ";", "}", "}", "}" ]
Ensures that a user-supplied value is a valid array of plugins. An error is thrown if the value is invalid. @param {*} plugins - The user-supplied value to validate
[ "Ensures", "that", "a", "user", "-", "supplied", "value", "is", "a", "valid", "array", "of", "plugins", ".", "An", "error", "is", "thrown", "if", "the", "value", "is", "invalid", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/PluginHelper/validatePlugins.js#L15-L27
35,362
0of/chinesegen
index.js
generate
function generate (opts) { var options = opts || {}, genCount = Math.abs(options.count) >>> 0, // min/max word count in a sentence minCount = Math.abs(options.minCount) || 5, maxCount = Math.abs(options.maxCount) || 20, formater = options.format == '\\uXXXX' ? formatOutput : undefined, periods = extendPeriod(options.toleratedPeriods || ''); var avail = 0; var genHelper = function (genFn) { return formater === undefined ? genFn : function () { return formatOutput(genFn.apply(undefined, arguments)); }; }, genWords = genHelper(options.freq === true ? freqUsedWordsGen : wordsGen), wordCountFn = function () { var count = rand(minCount, maxCount); return count >= avail ? avail - 1 : count; }, genPeriod = genHelper(function () { return periods[rand(0, periods.length)]; }), genSentences = function (genEachSentenceFn) { var gen = { text: '', total: 0, sentenceCount: 0 }; while ((avail = genCount - gen.total) > 0) { gen.total += genEachSentenceFn(gen); gen.sentenceCount++; } return gen; }; return genSentences(function (gen) { var currentWordCount = wordCountFn(); gen.text += genWords(currentWordCount); gen.text += genPeriod(); return currentWordCount + 1; }); }
javascript
function generate (opts) { var options = opts || {}, genCount = Math.abs(options.count) >>> 0, // min/max word count in a sentence minCount = Math.abs(options.minCount) || 5, maxCount = Math.abs(options.maxCount) || 20, formater = options.format == '\\uXXXX' ? formatOutput : undefined, periods = extendPeriod(options.toleratedPeriods || ''); var avail = 0; var genHelper = function (genFn) { return formater === undefined ? genFn : function () { return formatOutput(genFn.apply(undefined, arguments)); }; }, genWords = genHelper(options.freq === true ? freqUsedWordsGen : wordsGen), wordCountFn = function () { var count = rand(minCount, maxCount); return count >= avail ? avail - 1 : count; }, genPeriod = genHelper(function () { return periods[rand(0, periods.length)]; }), genSentences = function (genEachSentenceFn) { var gen = { text: '', total: 0, sentenceCount: 0 }; while ((avail = genCount - gen.total) > 0) { gen.total += genEachSentenceFn(gen); gen.sentenceCount++; } return gen; }; return genSentences(function (gen) { var currentWordCount = wordCountFn(); gen.text += genWords(currentWordCount); gen.text += genPeriod(); return currentWordCount + 1; }); }
[ "function", "generate", "(", "opts", ")", "{", "var", "options", "=", "opts", "||", "{", "}", ",", "genCount", "=", "Math", ".", "abs", "(", "options", ".", "count", ")", ">>>", "0", ",", "// min/max word count in a sentence", "minCount", "=", "Math", ".", "abs", "(", "options", ".", "minCount", ")", "||", "5", ",", "maxCount", "=", "Math", ".", "abs", "(", "options", ".", "maxCount", ")", "||", "20", ",", "formater", "=", "options", ".", "format", "==", "'\\\\uXXXX'", "?", "formatOutput", ":", "undefined", ",", "periods", "=", "extendPeriod", "(", "options", ".", "toleratedPeriods", "||", "''", ")", ";", "var", "avail", "=", "0", ";", "var", "genHelper", "=", "function", "(", "genFn", ")", "{", "return", "formater", "===", "undefined", "?", "genFn", ":", "function", "(", ")", "{", "return", "formatOutput", "(", "genFn", ".", "apply", "(", "undefined", ",", "arguments", ")", ")", ";", "}", ";", "}", ",", "genWords", "=", "genHelper", "(", "options", ".", "freq", "===", "true", "?", "freqUsedWordsGen", ":", "wordsGen", ")", ",", "wordCountFn", "=", "function", "(", ")", "{", "var", "count", "=", "rand", "(", "minCount", ",", "maxCount", ")", ";", "return", "count", ">=", "avail", "?", "avail", "-", "1", ":", "count", ";", "}", ",", "genPeriod", "=", "genHelper", "(", "function", "(", ")", "{", "return", "periods", "[", "rand", "(", "0", ",", "periods", ".", "length", ")", "]", ";", "}", ")", ",", "genSentences", "=", "function", "(", "genEachSentenceFn", ")", "{", "var", "gen", "=", "{", "text", ":", "''", ",", "total", ":", "0", ",", "sentenceCount", ":", "0", "}", ";", "while", "(", "(", "avail", "=", "genCount", "-", "gen", ".", "total", ")", ">", "0", ")", "{", "gen", ".", "total", "+=", "genEachSentenceFn", "(", "gen", ")", ";", "gen", ".", "sentenceCount", "++", ";", "}", "return", "gen", ";", "}", ";", "return", "genSentences", "(", "function", "(", "gen", ")", "{", "var", "currentWordCount", "=", "wordCountFn", "(", ")", ";", "gen", ".", "text", "+=", "genWords", "(", "currentWordCount", ")", ";", "gen", ".", "text", "+=", "genPeriod", "(", ")", ";", "return", "currentWordCount", "+", "1", ";", "}", ")", ";", "}" ]
generate random paragraph in Chinese @param {Object} [opts] @param {Number} [opts.count] the total word count of the generated paragraph @param {Boolean} [opts.freq] use frequently used words @param {String} [opts.format] support '\uXXXX' @param {String} [opts.toleratedPeriods] @return {Object} {String} [text] random text {Number} [total] text total length {Number} [sentenceCount] sentence count @public
[ "generate", "random", "paragraph", "in", "Chinese" ]
fb0dd294950183243edcb83c27e249f129dc9923
https://github.com/0of/chinesegen/blob/fb0dd294950183243edcb83c27e249f129dc9923/index.js#L21-L67
35,363
0of/chinesegen
index.js
getCharAt
function getCharAt (index) { var code = this.charCodeAt(index); // BMP if (code < 0xD800 || code > 0xDFFF) { return String.fromCharCode(code); } // high surrogate if (code < 0xDC00) { // access the low surrogate var nextCode = this.charCodeAt(index + 1); if (isNaN(nextCode)) return false; if (nextCode < 0xDC00 || nextCode > 0xDFFF) return false; return String.fromCharCode(code, nextCode); } else { // low surrogate return false; } }
javascript
function getCharAt (index) { var code = this.charCodeAt(index); // BMP if (code < 0xD800 || code > 0xDFFF) { return String.fromCharCode(code); } // high surrogate if (code < 0xDC00) { // access the low surrogate var nextCode = this.charCodeAt(index + 1); if (isNaN(nextCode)) return false; if (nextCode < 0xDC00 || nextCode > 0xDFFF) return false; return String.fromCharCode(code, nextCode); } else { // low surrogate return false; } }
[ "function", "getCharAt", "(", "index", ")", "{", "var", "code", "=", "this", ".", "charCodeAt", "(", "index", ")", ";", "// BMP", "if", "(", "code", "<", "0xD800", "||", "code", ">", "0xDFFF", ")", "{", "return", "String", ".", "fromCharCode", "(", "code", ")", ";", "}", "// high surrogate", "if", "(", "code", "<", "0xDC00", ")", "{", "// access the low surrogate", "var", "nextCode", "=", "this", ".", "charCodeAt", "(", "index", "+", "1", ")", ";", "if", "(", "isNaN", "(", "nextCode", ")", ")", "return", "false", ";", "if", "(", "nextCode", "<", "0xDC00", "||", "nextCode", ">", "0xDFFF", ")", "return", "false", ";", "return", "String", ".", "fromCharCode", "(", "code", ",", "nextCode", ")", ";", "}", "else", "{", "// low surrogate", "return", "false", ";", "}", "}" ]
no bound checking return false when unknown character or iterating at the low surrogate
[ "no", "bound", "checking", "return", "false", "when", "unknown", "character", "or", "iterating", "at", "the", "low", "surrogate" ]
fb0dd294950183243edcb83c27e249f129dc9923
https://github.com/0of/chinesegen/blob/fb0dd294950183243edcb83c27e249f129dc9923/index.js#L87-L107
35,364
JamesMessinger/json-schema-lib
lib/api/File.js
File
function File (schema) { /** * The {@link Schema} that this file belongs to. * * @type {Schema} */ this.schema = schema; /** * The file's full (absolute) URL, without any hash * * @type {string} */ this.url = ''; /** * The file's data. This can be any data type, including a string, object, array, binary, etc. * * @type {*} */ this.data = undefined; /** * The file's MIME type (e.g. "application/json", "text/html", etc.), if known. * * @type {?string} */ this.mimeType = undefined; /** * The file's encoding (e.g. "utf-8", "iso-8859-2", "windows-1251", etc.), if known * * @type {?string} */ this.encoding = undefined; /** * Internal stuff. Use at your own risk! * * @private */ this[__internal] = { /** * Keeps track of the state of each file as the schema is being read. * * @type {number} */ state: 0, }; }
javascript
function File (schema) { /** * The {@link Schema} that this file belongs to. * * @type {Schema} */ this.schema = schema; /** * The file's full (absolute) URL, without any hash * * @type {string} */ this.url = ''; /** * The file's data. This can be any data type, including a string, object, array, binary, etc. * * @type {*} */ this.data = undefined; /** * The file's MIME type (e.g. "application/json", "text/html", etc.), if known. * * @type {?string} */ this.mimeType = undefined; /** * The file's encoding (e.g. "utf-8", "iso-8859-2", "windows-1251", etc.), if known * * @type {?string} */ this.encoding = undefined; /** * Internal stuff. Use at your own risk! * * @private */ this[__internal] = { /** * Keeps track of the state of each file as the schema is being read. * * @type {number} */ state: 0, }; }
[ "function", "File", "(", "schema", ")", "{", "/**\n * The {@link Schema} that this file belongs to.\n *\n * @type {Schema}\n */", "this", ".", "schema", "=", "schema", ";", "/**\n * The file's full (absolute) URL, without any hash\n *\n * @type {string}\n */", "this", ".", "url", "=", "''", ";", "/**\n * The file's data. This can be any data type, including a string, object, array, binary, etc.\n *\n * @type {*}\n */", "this", ".", "data", "=", "undefined", ";", "/**\n * The file's MIME type (e.g. \"application/json\", \"text/html\", etc.), if known.\n *\n * @type {?string}\n */", "this", ".", "mimeType", "=", "undefined", ";", "/**\n * The file's encoding (e.g. \"utf-8\", \"iso-8859-2\", \"windows-1251\", etc.), if known\n *\n * @type {?string}\n */", "this", ".", "encoding", "=", "undefined", ";", "/**\n * Internal stuff. Use at your own risk!\n *\n * @private\n */", "this", "[", "__internal", "]", "=", "{", "/**\n * Keeps track of the state of each file as the schema is being read.\n *\n * @type {number}\n */", "state", ":", "0", ",", "}", ";", "}" ]
Contains information about a file, such as its path, type, and contents. @param {Schema} schema - The JSON Schema that the file is part of @class
[ "Contains", "information", "about", "a", "file", "such", "as", "its", "path", "type", "and", "contents", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/File.js#L15-L64
35,365
beebotte/bbt_node
lib/socketio.js
authNeeded
function authNeeded () { if (args.write === true) { return true } if (args.channel.indexOf('private-') === 0) { return true } if (args.channel.indexOf('presence-') === 0) { return true } return false; }
javascript
function authNeeded () { if (args.write === true) { return true } if (args.channel.indexOf('private-') === 0) { return true } if (args.channel.indexOf('presence-') === 0) { return true } return false; }
[ "function", "authNeeded", "(", ")", "{", "if", "(", "args", ".", "write", "===", "true", ")", "{", "return", "true", "}", "if", "(", "args", ".", "channel", ".", "indexOf", "(", "'private-'", ")", "===", "0", ")", "{", "return", "true", "}", "if", "(", "args", ".", "channel", ".", "indexOf", "(", "'presence-'", ")", "===", "0", ")", "{", "return", "true", "}", "return", "false", ";", "}" ]
Authentication required for write access and for read access to private or presence resources
[ "Authentication", "required", "for", "write", "access", "and", "for", "read", "access", "to", "private", "or", "presence", "resources" ]
be3fe5d934258866b701e5f2361f219d09506180
https://github.com/beebotte/bbt_node/blob/be3fe5d934258866b701e5f2361f219d09506180/lib/socketio.js#L236-L251
35,366
claudio-silva/grunt-angular-builder
tasks/middleware/buildForeignScripts.js
BuildForeignScriptsMiddleware
function BuildForeignScriptsMiddleware (context) { //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { /* jshint unused: vars */ // Do nothing }; this.trace = function (module) { /* jshint unused: vars */ // Do nothing }; this.build = function (targetScript) { // Output the standalone scripts (if any). if (context.standaloneScripts.length) { // Debug Build if (context.options.debugBuild && context.options.debugBuild.enabled) { var rep = context.options.debugBuild.rebaseDebugUrls; context.prependOutput += (context.standaloneScripts.map (function (e) { var path = e.path.replace (MATCH_PATH_SEP, '/'); // Convert file paths to URLs. if (rep) for (var i = 0, m = rep.length; i < m; ++i) path = path.replace (rep[i].match, rep[i].replaceWith); if (path) // Ignore empty path; it means that this middleware should not output a script tag. return util.sprintf ('<script src=\"%\"></script>', path); return ''; }) .filter (function (x) {return x;}) // Remove empty paths. .join ('\\\n')); } // Release Build else if (context.options.releaseBuild && context.options.releaseBuild.enabled) { /** @type {string[]} */ var output = context.standaloneScripts.map (function (e) { return e.content; }).join (NL); util.writeFile (targetScript, output); //Note: the ensuing release/debug build step will append to the file created here. } } }; }
javascript
function BuildForeignScriptsMiddleware (context) { //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { /* jshint unused: vars */ // Do nothing }; this.trace = function (module) { /* jshint unused: vars */ // Do nothing }; this.build = function (targetScript) { // Output the standalone scripts (if any). if (context.standaloneScripts.length) { // Debug Build if (context.options.debugBuild && context.options.debugBuild.enabled) { var rep = context.options.debugBuild.rebaseDebugUrls; context.prependOutput += (context.standaloneScripts.map (function (e) { var path = e.path.replace (MATCH_PATH_SEP, '/'); // Convert file paths to URLs. if (rep) for (var i = 0, m = rep.length; i < m; ++i) path = path.replace (rep[i].match, rep[i].replaceWith); if (path) // Ignore empty path; it means that this middleware should not output a script tag. return util.sprintf ('<script src=\"%\"></script>', path); return ''; }) .filter (function (x) {return x;}) // Remove empty paths. .join ('\\\n')); } // Release Build else if (context.options.releaseBuild && context.options.releaseBuild.enabled) { /** @type {string[]} */ var output = context.standaloneScripts.map (function (e) { return e.content; }).join (NL); util.writeFile (targetScript, output); //Note: the ensuing release/debug build step will append to the file created here. } } }; }
[ "function", "BuildForeignScriptsMiddleware", "(", "context", ")", "{", "//--------------------------------------------------------------------------------------------------------------------", "// PUBLIC API", "//--------------------------------------------------------------------------------------------------------------------", "this", ".", "analyze", "=", "function", "(", "filesArray", ")", "{", "/* jshint unused: vars */", "// Do nothing", "}", ";", "this", ".", "trace", "=", "function", "(", "module", ")", "{", "/* jshint unused: vars */", "// Do nothing", "}", ";", "this", ".", "build", "=", "function", "(", "targetScript", ")", "{", "// Output the standalone scripts (if any).", "if", "(", "context", ".", "standaloneScripts", ".", "length", ")", "{", "// Debug Build", "if", "(", "context", ".", "options", ".", "debugBuild", "&&", "context", ".", "options", ".", "debugBuild", ".", "enabled", ")", "{", "var", "rep", "=", "context", ".", "options", ".", "debugBuild", ".", "rebaseDebugUrls", ";", "context", ".", "prependOutput", "+=", "(", "context", ".", "standaloneScripts", ".", "map", "(", "function", "(", "e", ")", "{", "var", "path", "=", "e", ".", "path", ".", "replace", "(", "MATCH_PATH_SEP", ",", "'/'", ")", ";", "// Convert file paths to URLs.", "if", "(", "rep", ")", "for", "(", "var", "i", "=", "0", ",", "m", "=", "rep", ".", "length", ";", "i", "<", "m", ";", "++", "i", ")", "path", "=", "path", ".", "replace", "(", "rep", "[", "i", "]", ".", "match", ",", "rep", "[", "i", "]", ".", "replaceWith", ")", ";", "if", "(", "path", ")", "// Ignore empty path; it means that this middleware should not output a script tag.", "return", "util", ".", "sprintf", "(", "'<script src=\\\"%\\\"></script>'", ",", "path", ")", ";", "return", "''", ";", "}", ")", ".", "filter", "(", "function", "(", "x", ")", "{", "return", "x", ";", "}", ")", "// Remove empty paths.", ".", "join", "(", "'\\\\\\n'", ")", ")", ";", "}", "// Release Build", "else", "if", "(", "context", ".", "options", ".", "releaseBuild", "&&", "context", ".", "options", ".", "releaseBuild", ".", "enabled", ")", "{", "/** @type {string[]} */", "var", "output", "=", "context", ".", "standaloneScripts", ".", "map", "(", "function", "(", "e", ")", "{", "return", "e", ".", "content", ";", "}", ")", ".", "join", "(", "NL", ")", ";", "util", ".", "writeFile", "(", "targetScript", ",", "output", ")", ";", "//Note: the ensuing release/debug build step will append to the file created here.", "}", "}", "}", ";", "}" ]
Builds non-angular-module scripts. On release builds, this extension saves all non-module script files required by the application into a single output file, in the correct loading order. On debug builds, it appends SCRIPT tags to the head of the html document, which will load the original source scripts in the correct order. @constructor @implements {MiddlewareInterface} @param {Context} context The execution context for the middleware stack.
[ "Builds", "non", "-", "angular", "-", "module", "scripts", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/buildForeignScripts.js#L35-L88
35,367
matteodelabre/midijs
lib/file/parser/header.js
parseHeader
function parseHeader(cursor) { var chunk, fileType, trackCount, timeDivision; try { chunk = parseChunk('MThd', cursor); } catch (e) { if (e instanceof error.MIDIParserError) { throw new error.MIDINotMIDIError(); } } fileType = chunk.readUInt16BE(); trackCount = chunk.readUInt16BE(); timeDivision = chunk.readUInt16BE(); if ((timeDivision & 0x8000) === 0) { timeDivision = timeDivision & 0x7FFF; } else { throw new error.MIDINotSupportedError( 'Expressing time in SMPTE format is not supported yet' ); } return new Header(fileType, trackCount, timeDivision); }
javascript
function parseHeader(cursor) { var chunk, fileType, trackCount, timeDivision; try { chunk = parseChunk('MThd', cursor); } catch (e) { if (e instanceof error.MIDIParserError) { throw new error.MIDINotMIDIError(); } } fileType = chunk.readUInt16BE(); trackCount = chunk.readUInt16BE(); timeDivision = chunk.readUInt16BE(); if ((timeDivision & 0x8000) === 0) { timeDivision = timeDivision & 0x7FFF; } else { throw new error.MIDINotSupportedError( 'Expressing time in SMPTE format is not supported yet' ); } return new Header(fileType, trackCount, timeDivision); }
[ "function", "parseHeader", "(", "cursor", ")", "{", "var", "chunk", ",", "fileType", ",", "trackCount", ",", "timeDivision", ";", "try", "{", "chunk", "=", "parseChunk", "(", "'MThd'", ",", "cursor", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "e", "instanceof", "error", ".", "MIDIParserError", ")", "{", "throw", "new", "error", ".", "MIDINotMIDIError", "(", ")", ";", "}", "}", "fileType", "=", "chunk", ".", "readUInt16BE", "(", ")", ";", "trackCount", "=", "chunk", ".", "readUInt16BE", "(", ")", ";", "timeDivision", "=", "chunk", ".", "readUInt16BE", "(", ")", ";", "if", "(", "(", "timeDivision", "&", "0x8000", ")", "===", "0", ")", "{", "timeDivision", "=", "timeDivision", "&", "0x7FFF", ";", "}", "else", "{", "throw", "new", "error", ".", "MIDINotSupportedError", "(", "'Expressing time in SMPTE format is not supported yet'", ")", ";", "}", "return", "new", "Header", "(", "fileType", ",", "trackCount", ",", "timeDivision", ")", ";", "}" ]
Parse a MIDI header chunk @param {module:buffercursor} cursor Buffer to parse @throws {module:midijs/lib/error~MIDINotMIDIError} If the file is not a MIDI file @throws {module:midijs/lib/error~MIDIParserError} If time is expressed in unsupported SMPTE format @return {module:midijs/lib/file/header~Header} Parsed header
[ "Parse", "a", "MIDI", "header", "chunk" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/parser/header.js#L17-L41
35,368
matteodelabre/midijs
lib/file.js
File
function File(data, callback) { stream.Duplex.call(this); this._header = new Header(); this._tracks = []; if (data && buffer.Buffer.isBuffer(data)) { this.setData(data, callback || noop); } }
javascript
function File(data, callback) { stream.Duplex.call(this); this._header = new Header(); this._tracks = []; if (data && buffer.Buffer.isBuffer(data)) { this.setData(data, callback || noop); } }
[ "function", "File", "(", "data", ",", "callback", ")", "{", "stream", ".", "Duplex", ".", "call", "(", "this", ")", ";", "this", ".", "_header", "=", "new", "Header", "(", ")", ";", "this", ".", "_tracks", "=", "[", "]", ";", "if", "(", "data", "&&", "buffer", ".", "Buffer", ".", "isBuffer", "(", "data", ")", ")", "{", "this", ".", "setData", "(", "data", ",", "callback", "||", "noop", ")", ";", "}", "}" ]
Construct a new File @class File @extends stream.Duplex @classdesc Parse and encode MIDI data @param {Buffer} [data] Shortcut for calling setData() @param {Function} [callback] Callback for setData() shortcut
[ "Construct", "a", "new", "File" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file.js#L32-L41
35,369
Skellington-Closet/skellington
lib/debug-logger.js
defaultFormatter
function defaultFormatter (message) { return `team: ${message.team} channel: ${message.channel} user: ${message.user} text: ${message.text}` }
javascript
function defaultFormatter (message) { return `team: ${message.team} channel: ${message.channel} user: ${message.user} text: ${message.text}` }
[ "function", "defaultFormatter", "(", "message", ")", "{", "return", "`", "${", "message", ".", "team", "}", "${", "message", ".", "channel", "}", "${", "message", ".", "user", "}", "${", "message", ".", "text", "}", "`", "}" ]
Default log message formatter @param message @returns {string}
[ "Default", "log", "message", "formatter" ]
fa660c0864ab13188c0b663cd57ccbcc979683f1
https://github.com/Skellington-Closet/skellington/blob/fa660c0864ab13188c0b663cd57ccbcc979683f1/lib/debug-logger.js#L42-L44
35,370
claudio-silva/grunt-angular-builder
tasks/middleware/makeReleaseBuild.js
MakeReleaseBuildMiddleware
function MakeReleaseBuildMiddleware (context) { var options = context.options.releaseBuild; /** * Grunt's verbose output API. * @type {Object} */ var verboseOut = context.grunt.log.verbose; /** @type {string[]} */ var traceOutput = []; //-------------------------------------------------------------------------------------------------------------------- // EVENTS //-------------------------------------------------------------------------------------------------------------------- context.listen (ContextEvent.ON_AFTER_ANALYZE, function () { if (options.enabled) { var space = context.verbose ? NL : ''; writeln ('%Generating the <cyan>release</cyan> build...%', space, space); scanForOptimization (context); } }); context.listen (ContextEvent.ON_BEFORE_DEPS, function (/*ModuleDef*/ module) { if (options.enabled) { if (module.nonOptimizedContainer) traceOutput.push ('(function () {\n'); } }); //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { /* jshint unused: vars */ // Do nothing }; this.trace = function (/*ModuleDef*/ module) { if (!options.enabled) return; if (module.nonOptimizedContainer) traceOutput.push ('\n}) ();'); // Fist process the head module declaration. if (!module.head) return util.warn ('Module <cyan>%</cyan> has no declaration.', module.name); var headPath = module.headPath; var head, headWasOutput = context.outputtedFiles[headPath]; if (!headWasOutput) { head = module.optimize ? optimize (module.head, headPath, module) : {status: STAT.INDENTED, data: module.head}; context.outputtedFiles[headPath] = true; } var isEmpty = headWasOutput ? true : sourceExtract.matchWhiteSpaceOrComments (head.data); outputModuleHeader (module, headWasOutput, headPath); if (!headWasOutput) { // Prevent the creation of an empty (or comments-only) self-invoking function. // In that case, the head content will be output without a wrapping closure. if (!module.bodies.length && isEmpty) { // Output the comments (if any). if (head.data.trim ()) traceOutput.push (head.data); // Output a module declaration with no definitions. traceOutput.push (sprintf ('angular.module (\'%\', %);%', module.name, util.toQuotedList (module.requires), options.moduleFooter) ); return; } } // Enclose the module contents in a self-invoking function which receives the module instance as an argument. if (module.optimize) // Begin closure. traceOutput.push ('(function (' + options.moduleVar + ') {\n'); // Insert module declaration. if (!headWasOutput) traceOutput.push (conditionalIndent (head)); outputModuleDefinitions (module, headWasOutput); // End closure. if (module.optimize) traceOutput.push (sprintf ('\n}) (angular.module (\'%\', %%));%', module.name, util.toQuotedList (module.requires), module.configFn || '', options.moduleFooter)); }; this.build = function (targetScript) { if (!options.enabled) return; if (context.prependOutput) traceOutput.unshift (context.prependOutput); if (context.appendOutput) traceOutput.push (context.appendOutput); util.writeFile (targetScript, traceOutput.join (NL)); }; //-------------------------------------------------------------------------------------------------------------------- // PRIVATE //-------------------------------------------------------------------------------------------------------------------- /** * Outputs a module information header. * * @param {ModuleDef} module * @param {boolean} headWasOutput * @param {string} headPath */ function outputModuleHeader (module, headWasOutput, headPath) { if (module.bodies.length || !headWasOutput) { traceOutput.push (LINE2, '// Module: ' + module.name, '// Optimized: ' + (module.optimize ? 'Yes' : 'No')); if (!headWasOutput) traceOutput.push ('// File: ' + headPath); else { for (var i = 0, m = module.bodies.length; i < m; ++i) { var bodyPath = module.bodyPaths[i]; // Find first body who's corresponding file was not yet output. if (!context.outputtedFiles[bodyPath]) { traceOutput.push ('// File: ' + bodyPath); break; } } } traceOutput.push (LINE2, ''); } } /** * Insert additional module definitions. * * @param {ModuleDef} module * @param {boolean} headWasOutput */ function outputModuleDefinitions (module, headWasOutput) { for (var i = 0, m = module.bodies.length; i < m; ++i) { var bodyPath = module.bodyPaths[i]; if (!bodyPath) console.log (module.name, i, module.bodies.length, module.bodyPaths); // Skip bodies who's corresponding file was already output. if (context.outputtedFiles[bodyPath]) continue; context.outputtedFiles[bodyPath] = true; var body = module.optimize ? optimize (module.bodies[i], bodyPath, module) : {status: STAT.INDENTED, data: module.bodies[i]}; if (i || !headWasOutput) traceOutput.push (LINE, '// File: ' + bodyPath, LINE, ''); traceOutput.push (conditionalIndent (body)); } } /** * Calls sourceTrans.optimize() and handles the result. * * @param {string} source * @param {string} path For error messages. * @param {ModuleDef} module * @returns {OperationResult} The transformed source code. * @throws Error Sanity check. */ function optimize (source, path, module) { var result = sourceTrans.optimize (source, module.name, options.moduleVar); var stat = sourceTrans.TRANS_STAT; switch (result.status) { case stat.OK: //---------------------------------------------------------- // Module already enclosed in a closure with no arguments. //---------------------------------------------------------- return /** @type {OperationResult} */ { status: STAT.INDENTED, data: sourceTrans.renameModuleRefExps (module, options.indent + result.data, options.moduleVar) }; case stat.NO_CLOSURE_FOUND: //---------------------------------------------------------- // Unwrapped source code. // It must be validated to make sure it's safe. //---------------------------------------------------------- if (path) verboseOut.write ('Validating ' + path.cyan + '...'); var valid = sourceTrans.validateUnwrappedCode (source); if (valid) // The code passed validation. verboseOut.ok (); else { verboseOut.writeln ('FAILED'.yellow); warnAboutGlobalCode (valid, path); // If --force, continue. } // Either the code is valid or --force was used, so process it. return /** @type {OperationResult} */ { status: STAT.OK, data: sourceTrans.renameModuleRefExps (module, source, options.moduleVar) }; case stat.RENAME_REQUIRED: //---------------------------------------------------------- // Module already enclosed in a closure, with its reference // passed in as the function's argument. //---------------------------------------------------------- /** @type {ModuleClosureInfo} */ var modInfo = result.data; if (!options.renameModuleRefs) { warn ('The module variable reference <cyan>%</cyan> doesn\'t match the preset name on the config setting ' + '<cyan>moduleVar=\'%\'</cyan>.%%%', modInfo.moduleVar, options.moduleVar, NL, reportErrorLocation (path), getExplanation ('Either rename the variable or enable <cyan>renameModuleRefs</cyan>.') ); // If --force, continue. } return /** @type {OperationResult} */ { status: STAT.OK, data: sourceTrans.renameModuleVariableRefs (modInfo.closureBody, modInfo.moduleVar, options.moduleVar) }; case stat.INVALID_DECLARATION: warn ('Wrong module declaration: <cyan>%</cyan>', result.data); // If --force, continue. break; default: throw new Error ('Optimize failed. It returned ' + JSON.stringify (result)); } // Optimization failed. Return the unaltered source code. return /** @type {OperationResult} */ {status: STAT.OK, data: source}; } /** * Returns the given text indented unless it was already indented. * @param {OperationResult} result * @return {string} */ function conditionalIndent (result) { return result.status === STAT.INDENTED ? result.data : indent (result.data, 1, options.indent); } /** * Isses a warning about problematic code found on the global scope. * @param {Object} sandbox * @param {string} path */ function warnAboutGlobalCode (sandbox, path) { var msg = csprintf ('yellow', 'Incompatible code found on the global scope!'.red + NL + (path ? reportErrorLocation (path) : '') + getExplanation ( 'This kind of code will behave differently between release and debug builds.' + NL + 'You should wrap it in a self-invoking function and/or assign global variables/functions ' + 'directly to the window object.' ) ); if (context.verbose) { var found = false; util.forEachProperty (sandbox, function (k, v) { if (!found) { found = true; msg += ' Detected globals:'.yellow + NL; } msg += (typeof v === 'function' ? ' function '.blue : ' var '.blue) + k.cyan + NL; }); } warn (msg + '>>'.yellow); } }
javascript
function MakeReleaseBuildMiddleware (context) { var options = context.options.releaseBuild; /** * Grunt's verbose output API. * @type {Object} */ var verboseOut = context.grunt.log.verbose; /** @type {string[]} */ var traceOutput = []; //-------------------------------------------------------------------------------------------------------------------- // EVENTS //-------------------------------------------------------------------------------------------------------------------- context.listen (ContextEvent.ON_AFTER_ANALYZE, function () { if (options.enabled) { var space = context.verbose ? NL : ''; writeln ('%Generating the <cyan>release</cyan> build...%', space, space); scanForOptimization (context); } }); context.listen (ContextEvent.ON_BEFORE_DEPS, function (/*ModuleDef*/ module) { if (options.enabled) { if (module.nonOptimizedContainer) traceOutput.push ('(function () {\n'); } }); //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { /* jshint unused: vars */ // Do nothing }; this.trace = function (/*ModuleDef*/ module) { if (!options.enabled) return; if (module.nonOptimizedContainer) traceOutput.push ('\n}) ();'); // Fist process the head module declaration. if (!module.head) return util.warn ('Module <cyan>%</cyan> has no declaration.', module.name); var headPath = module.headPath; var head, headWasOutput = context.outputtedFiles[headPath]; if (!headWasOutput) { head = module.optimize ? optimize (module.head, headPath, module) : {status: STAT.INDENTED, data: module.head}; context.outputtedFiles[headPath] = true; } var isEmpty = headWasOutput ? true : sourceExtract.matchWhiteSpaceOrComments (head.data); outputModuleHeader (module, headWasOutput, headPath); if (!headWasOutput) { // Prevent the creation of an empty (or comments-only) self-invoking function. // In that case, the head content will be output without a wrapping closure. if (!module.bodies.length && isEmpty) { // Output the comments (if any). if (head.data.trim ()) traceOutput.push (head.data); // Output a module declaration with no definitions. traceOutput.push (sprintf ('angular.module (\'%\', %);%', module.name, util.toQuotedList (module.requires), options.moduleFooter) ); return; } } // Enclose the module contents in a self-invoking function which receives the module instance as an argument. if (module.optimize) // Begin closure. traceOutput.push ('(function (' + options.moduleVar + ') {\n'); // Insert module declaration. if (!headWasOutput) traceOutput.push (conditionalIndent (head)); outputModuleDefinitions (module, headWasOutput); // End closure. if (module.optimize) traceOutput.push (sprintf ('\n}) (angular.module (\'%\', %%));%', module.name, util.toQuotedList (module.requires), module.configFn || '', options.moduleFooter)); }; this.build = function (targetScript) { if (!options.enabled) return; if (context.prependOutput) traceOutput.unshift (context.prependOutput); if (context.appendOutput) traceOutput.push (context.appendOutput); util.writeFile (targetScript, traceOutput.join (NL)); }; //-------------------------------------------------------------------------------------------------------------------- // PRIVATE //-------------------------------------------------------------------------------------------------------------------- /** * Outputs a module information header. * * @param {ModuleDef} module * @param {boolean} headWasOutput * @param {string} headPath */ function outputModuleHeader (module, headWasOutput, headPath) { if (module.bodies.length || !headWasOutput) { traceOutput.push (LINE2, '// Module: ' + module.name, '// Optimized: ' + (module.optimize ? 'Yes' : 'No')); if (!headWasOutput) traceOutput.push ('// File: ' + headPath); else { for (var i = 0, m = module.bodies.length; i < m; ++i) { var bodyPath = module.bodyPaths[i]; // Find first body who's corresponding file was not yet output. if (!context.outputtedFiles[bodyPath]) { traceOutput.push ('// File: ' + bodyPath); break; } } } traceOutput.push (LINE2, ''); } } /** * Insert additional module definitions. * * @param {ModuleDef} module * @param {boolean} headWasOutput */ function outputModuleDefinitions (module, headWasOutput) { for (var i = 0, m = module.bodies.length; i < m; ++i) { var bodyPath = module.bodyPaths[i]; if (!bodyPath) console.log (module.name, i, module.bodies.length, module.bodyPaths); // Skip bodies who's corresponding file was already output. if (context.outputtedFiles[bodyPath]) continue; context.outputtedFiles[bodyPath] = true; var body = module.optimize ? optimize (module.bodies[i], bodyPath, module) : {status: STAT.INDENTED, data: module.bodies[i]}; if (i || !headWasOutput) traceOutput.push (LINE, '// File: ' + bodyPath, LINE, ''); traceOutput.push (conditionalIndent (body)); } } /** * Calls sourceTrans.optimize() and handles the result. * * @param {string} source * @param {string} path For error messages. * @param {ModuleDef} module * @returns {OperationResult} The transformed source code. * @throws Error Sanity check. */ function optimize (source, path, module) { var result = sourceTrans.optimize (source, module.name, options.moduleVar); var stat = sourceTrans.TRANS_STAT; switch (result.status) { case stat.OK: //---------------------------------------------------------- // Module already enclosed in a closure with no arguments. //---------------------------------------------------------- return /** @type {OperationResult} */ { status: STAT.INDENTED, data: sourceTrans.renameModuleRefExps (module, options.indent + result.data, options.moduleVar) }; case stat.NO_CLOSURE_FOUND: //---------------------------------------------------------- // Unwrapped source code. // It must be validated to make sure it's safe. //---------------------------------------------------------- if (path) verboseOut.write ('Validating ' + path.cyan + '...'); var valid = sourceTrans.validateUnwrappedCode (source); if (valid) // The code passed validation. verboseOut.ok (); else { verboseOut.writeln ('FAILED'.yellow); warnAboutGlobalCode (valid, path); // If --force, continue. } // Either the code is valid or --force was used, so process it. return /** @type {OperationResult} */ { status: STAT.OK, data: sourceTrans.renameModuleRefExps (module, source, options.moduleVar) }; case stat.RENAME_REQUIRED: //---------------------------------------------------------- // Module already enclosed in a closure, with its reference // passed in as the function's argument. //---------------------------------------------------------- /** @type {ModuleClosureInfo} */ var modInfo = result.data; if (!options.renameModuleRefs) { warn ('The module variable reference <cyan>%</cyan> doesn\'t match the preset name on the config setting ' + '<cyan>moduleVar=\'%\'</cyan>.%%%', modInfo.moduleVar, options.moduleVar, NL, reportErrorLocation (path), getExplanation ('Either rename the variable or enable <cyan>renameModuleRefs</cyan>.') ); // If --force, continue. } return /** @type {OperationResult} */ { status: STAT.OK, data: sourceTrans.renameModuleVariableRefs (modInfo.closureBody, modInfo.moduleVar, options.moduleVar) }; case stat.INVALID_DECLARATION: warn ('Wrong module declaration: <cyan>%</cyan>', result.data); // If --force, continue. break; default: throw new Error ('Optimize failed. It returned ' + JSON.stringify (result)); } // Optimization failed. Return the unaltered source code. return /** @type {OperationResult} */ {status: STAT.OK, data: source}; } /** * Returns the given text indented unless it was already indented. * @param {OperationResult} result * @return {string} */ function conditionalIndent (result) { return result.status === STAT.INDENTED ? result.data : indent (result.data, 1, options.indent); } /** * Isses a warning about problematic code found on the global scope. * @param {Object} sandbox * @param {string} path */ function warnAboutGlobalCode (sandbox, path) { var msg = csprintf ('yellow', 'Incompatible code found on the global scope!'.red + NL + (path ? reportErrorLocation (path) : '') + getExplanation ( 'This kind of code will behave differently between release and debug builds.' + NL + 'You should wrap it in a self-invoking function and/or assign global variables/functions ' + 'directly to the window object.' ) ); if (context.verbose) { var found = false; util.forEachProperty (sandbox, function (k, v) { if (!found) { found = true; msg += ' Detected globals:'.yellow + NL; } msg += (typeof v === 'function' ? ' function '.blue : ' var '.blue) + k.cyan + NL; }); } warn (msg + '>>'.yellow); } }
[ "function", "MakeReleaseBuildMiddleware", "(", "context", ")", "{", "var", "options", "=", "context", ".", "options", ".", "releaseBuild", ";", "/**\n * Grunt's verbose output API.\n * @type {Object}\n */", "var", "verboseOut", "=", "context", ".", "grunt", ".", "log", ".", "verbose", ";", "/** @type {string[]} */", "var", "traceOutput", "=", "[", "]", ";", "//--------------------------------------------------------------------------------------------------------------------", "// EVENTS", "//--------------------------------------------------------------------------------------------------------------------", "context", ".", "listen", "(", "ContextEvent", ".", "ON_AFTER_ANALYZE", ",", "function", "(", ")", "{", "if", "(", "options", ".", "enabled", ")", "{", "var", "space", "=", "context", ".", "verbose", "?", "NL", ":", "''", ";", "writeln", "(", "'%Generating the <cyan>release</cyan> build...%'", ",", "space", ",", "space", ")", ";", "scanForOptimization", "(", "context", ")", ";", "}", "}", ")", ";", "context", ".", "listen", "(", "ContextEvent", ".", "ON_BEFORE_DEPS", ",", "function", "(", "/*ModuleDef*/", "module", ")", "{", "if", "(", "options", ".", "enabled", ")", "{", "if", "(", "module", ".", "nonOptimizedContainer", ")", "traceOutput", ".", "push", "(", "'(function () {\\n'", ")", ";", "}", "}", ")", ";", "//--------------------------------------------------------------------------------------------------------------------", "// PUBLIC API", "//--------------------------------------------------------------------------------------------------------------------", "this", ".", "analyze", "=", "function", "(", "filesArray", ")", "{", "/* jshint unused: vars */", "// Do nothing", "}", ";", "this", ".", "trace", "=", "function", "(", "/*ModuleDef*/", "module", ")", "{", "if", "(", "!", "options", ".", "enabled", ")", "return", ";", "if", "(", "module", ".", "nonOptimizedContainer", ")", "traceOutput", ".", "push", "(", "'\\n}) ();'", ")", ";", "// Fist process the head module declaration.", "if", "(", "!", "module", ".", "head", ")", "return", "util", ".", "warn", "(", "'Module <cyan>%</cyan> has no declaration.'", ",", "module", ".", "name", ")", ";", "var", "headPath", "=", "module", ".", "headPath", ";", "var", "head", ",", "headWasOutput", "=", "context", ".", "outputtedFiles", "[", "headPath", "]", ";", "if", "(", "!", "headWasOutput", ")", "{", "head", "=", "module", ".", "optimize", "?", "optimize", "(", "module", ".", "head", ",", "headPath", ",", "module", ")", ":", "{", "status", ":", "STAT", ".", "INDENTED", ",", "data", ":", "module", ".", "head", "}", ";", "context", ".", "outputtedFiles", "[", "headPath", "]", "=", "true", ";", "}", "var", "isEmpty", "=", "headWasOutput", "?", "true", ":", "sourceExtract", ".", "matchWhiteSpaceOrComments", "(", "head", ".", "data", ")", ";", "outputModuleHeader", "(", "module", ",", "headWasOutput", ",", "headPath", ")", ";", "if", "(", "!", "headWasOutput", ")", "{", "// Prevent the creation of an empty (or comments-only) self-invoking function.", "// In that case, the head content will be output without a wrapping closure.", "if", "(", "!", "module", ".", "bodies", ".", "length", "&&", "isEmpty", ")", "{", "// Output the comments (if any).", "if", "(", "head", ".", "data", ".", "trim", "(", ")", ")", "traceOutput", ".", "push", "(", "head", ".", "data", ")", ";", "// Output a module declaration with no definitions.", "traceOutput", ".", "push", "(", "sprintf", "(", "'angular.module (\\'%\\', %);%'", ",", "module", ".", "name", ",", "util", ".", "toQuotedList", "(", "module", ".", "requires", ")", ",", "options", ".", "moduleFooter", ")", ")", ";", "return", ";", "}", "}", "// Enclose the module contents in a self-invoking function which receives the module instance as an argument.", "if", "(", "module", ".", "optimize", ")", "// Begin closure.", "traceOutput", ".", "push", "(", "'(function ('", "+", "options", ".", "moduleVar", "+", "') {\\n'", ")", ";", "// Insert module declaration.", "if", "(", "!", "headWasOutput", ")", "traceOutput", ".", "push", "(", "conditionalIndent", "(", "head", ")", ")", ";", "outputModuleDefinitions", "(", "module", ",", "headWasOutput", ")", ";", "// End closure.", "if", "(", "module", ".", "optimize", ")", "traceOutput", ".", "push", "(", "sprintf", "(", "'\\n}) (angular.module (\\'%\\', %%));%'", ",", "module", ".", "name", ",", "util", ".", "toQuotedList", "(", "module", ".", "requires", ")", ",", "module", ".", "configFn", "||", "''", ",", "options", ".", "moduleFooter", ")", ")", ";", "}", ";", "this", ".", "build", "=", "function", "(", "targetScript", ")", "{", "if", "(", "!", "options", ".", "enabled", ")", "return", ";", "if", "(", "context", ".", "prependOutput", ")", "traceOutput", ".", "unshift", "(", "context", ".", "prependOutput", ")", ";", "if", "(", "context", ".", "appendOutput", ")", "traceOutput", ".", "push", "(", "context", ".", "appendOutput", ")", ";", "util", ".", "writeFile", "(", "targetScript", ",", "traceOutput", ".", "join", "(", "NL", ")", ")", ";", "}", ";", "//--------------------------------------------------------------------------------------------------------------------", "// PRIVATE", "//--------------------------------------------------------------------------------------------------------------------", "/**\n * Outputs a module information header.\n *\n * @param {ModuleDef} module\n * @param {boolean} headWasOutput\n * @param {string} headPath\n */", "function", "outputModuleHeader", "(", "module", ",", "headWasOutput", ",", "headPath", ")", "{", "if", "(", "module", ".", "bodies", ".", "length", "||", "!", "headWasOutput", ")", "{", "traceOutput", ".", "push", "(", "LINE2", ",", "'// Module: '", "+", "module", ".", "name", ",", "'// Optimized: '", "+", "(", "module", ".", "optimize", "?", "'Yes'", ":", "'No'", ")", ")", ";", "if", "(", "!", "headWasOutput", ")", "traceOutput", ".", "push", "(", "'// File: '", "+", "headPath", ")", ";", "else", "{", "for", "(", "var", "i", "=", "0", ",", "m", "=", "module", ".", "bodies", ".", "length", ";", "i", "<", "m", ";", "++", "i", ")", "{", "var", "bodyPath", "=", "module", ".", "bodyPaths", "[", "i", "]", ";", "// Find first body who's corresponding file was not yet output.", "if", "(", "!", "context", ".", "outputtedFiles", "[", "bodyPath", "]", ")", "{", "traceOutput", ".", "push", "(", "'// File: '", "+", "bodyPath", ")", ";", "break", ";", "}", "}", "}", "traceOutput", ".", "push", "(", "LINE2", ",", "''", ")", ";", "}", "}", "/**\n * Insert additional module definitions.\n *\n * @param {ModuleDef} module\n * @param {boolean} headWasOutput\n */", "function", "outputModuleDefinitions", "(", "module", ",", "headWasOutput", ")", "{", "for", "(", "var", "i", "=", "0", ",", "m", "=", "module", ".", "bodies", ".", "length", ";", "i", "<", "m", ";", "++", "i", ")", "{", "var", "bodyPath", "=", "module", ".", "bodyPaths", "[", "i", "]", ";", "if", "(", "!", "bodyPath", ")", "console", ".", "log", "(", "module", ".", "name", ",", "i", ",", "module", ".", "bodies", ".", "length", ",", "module", ".", "bodyPaths", ")", ";", "// Skip bodies who's corresponding file was already output.", "if", "(", "context", ".", "outputtedFiles", "[", "bodyPath", "]", ")", "continue", ";", "context", ".", "outputtedFiles", "[", "bodyPath", "]", "=", "true", ";", "var", "body", "=", "module", ".", "optimize", "?", "optimize", "(", "module", ".", "bodies", "[", "i", "]", ",", "bodyPath", ",", "module", ")", ":", "{", "status", ":", "STAT", ".", "INDENTED", ",", "data", ":", "module", ".", "bodies", "[", "i", "]", "}", ";", "if", "(", "i", "||", "!", "headWasOutput", ")", "traceOutput", ".", "push", "(", "LINE", ",", "'// File: '", "+", "bodyPath", ",", "LINE", ",", "''", ")", ";", "traceOutput", ".", "push", "(", "conditionalIndent", "(", "body", ")", ")", ";", "}", "}", "/**\n * Calls sourceTrans.optimize() and handles the result.\n *\n * @param {string} source\n * @param {string} path For error messages.\n * @param {ModuleDef} module\n * @returns {OperationResult} The transformed source code.\n * @throws Error Sanity check.\n */", "function", "optimize", "(", "source", ",", "path", ",", "module", ")", "{", "var", "result", "=", "sourceTrans", ".", "optimize", "(", "source", ",", "module", ".", "name", ",", "options", ".", "moduleVar", ")", ";", "var", "stat", "=", "sourceTrans", ".", "TRANS_STAT", ";", "switch", "(", "result", ".", "status", ")", "{", "case", "stat", ".", "OK", ":", "//----------------------------------------------------------", "// Module already enclosed in a closure with no arguments.", "//----------------------------------------------------------", "return", "/** @type {OperationResult} */ ", "", "status", ":", "STAT", ".", "INDENTED", ",", "data", ":", "sourceTrans", ".", "renameModuleRefExps", "(", "module", ",", "options", ".", "indent", "+", "result", ".", "data", ",", "options", ".", "moduleVar", ")", "}", ";", "case", "stat", ".", "NO_CLOSURE_FOUND", ":", "//----------------------------------------------------------", "// Unwrapped source code.", "// It must be validated to make sure it's safe.", "//----------------------------------------------------------", "if", "(", "path", ")", "verboseOut", ".", "write", "(", "'Validating '", "+", "path", ".", "cyan", "+", "'...'", ")", ";", "var", "valid", "=", "sourceTrans", ".", "validateUnwrappedCode", "(", "source", ")", ";", "if", "(", "valid", ")", "// The code passed validation.", "verboseOut", ".", "ok", "(", ")", ";", "else", "{", "verboseOut", ".", "writeln", "(", "'FAILED'", ".", "yellow", ")", ";", "warnAboutGlobalCode", "(", "valid", ",", "path", ")", ";", "// If --force, continue.", "}", "// Either the code is valid or --force was used, so process it.", "return", "/** @type {OperationResult} */ ", "", "status", ":", "STAT", ".", "OK", ",", "data", ":", "sourceTrans", ".", "renameModuleRefExps", "(", "module", ",", "source", ",", "options", ".", "moduleVar", ")", "}", ";", "case", "stat", ".", "RENAME_REQUIRED", ":", "//----------------------------------------------------------", "// Module already enclosed in a closure, with its reference", "// passed in as the function's argument.", "//----------------------------------------------------------", "/** @type {ModuleClosureInfo} */", "var", "modInfo", "=", "result", ".", "data", ";", "if", "(", "!", "options", ".", "renameModuleRefs", ")", "{", "warn", "(", "'The module variable reference <cyan>%</cyan> doesn\\'t match the preset name on the config setting '", "+", "'<cyan>moduleVar=\\'%\\'</cyan>.%%%'", ",", "modInfo", ".", "moduleVar", ",", "options", ".", "moduleVar", ",", "NL", ",", "reportErrorLocation", "(", "path", ")", ",", "getExplanation", "(", "'Either rename the variable or enable <cyan>renameModuleRefs</cyan>.'", ")", ")", ";", "// If --force, continue.", "}", "return", "/** @type {OperationResult} */ ", "", "status", ":", "STAT", ".", "OK", ",", "data", ":", "sourceTrans", ".", "renameModuleVariableRefs", "(", "modInfo", ".", "closureBody", ",", "modInfo", ".", "moduleVar", ",", "options", ".", "moduleVar", ")", "}", ";", "case", "stat", ".", "INVALID_DECLARATION", ":", "warn", "(", "'Wrong module declaration: <cyan>%</cyan>'", ",", "result", ".", "data", ")", ";", "// If --force, continue.", "break", ";", "default", ":", "throw", "new", "Error", "(", "'Optimize failed. It returned '", "+", "JSON", ".", "stringify", "(", "result", ")", ")", ";", "}", "// Optimization failed. Return the unaltered source code.", "return", "/** @type {OperationResult} */ ", "s", "tatus:", " ", "TAT.", "O", "K,", " ", "ata:", " ", "ource}", ";", "", "}", "/**\n * Returns the given text indented unless it was already indented.\n * @param {OperationResult} result\n * @return {string}\n */", "function", "conditionalIndent", "(", "result", ")", "{", "return", "result", ".", "status", "===", "STAT", ".", "INDENTED", "?", "result", ".", "data", ":", "indent", "(", "result", ".", "data", ",", "1", ",", "options", ".", "indent", ")", ";", "}", "/**\n * Isses a warning about problematic code found on the global scope.\n * @param {Object} sandbox\n * @param {string} path\n */", "function", "warnAboutGlobalCode", "(", "sandbox", ",", "path", ")", "{", "var", "msg", "=", "csprintf", "(", "'yellow'", ",", "'Incompatible code found on the global scope!'", ".", "red", "+", "NL", "+", "(", "path", "?", "reportErrorLocation", "(", "path", ")", ":", "''", ")", "+", "getExplanation", "(", "'This kind of code will behave differently between release and debug builds.'", "+", "NL", "+", "'You should wrap it in a self-invoking function and/or assign global variables/functions '", "+", "'directly to the window object.'", ")", ")", ";", "if", "(", "context", ".", "verbose", ")", "{", "var", "found", "=", "false", ";", "util", ".", "forEachProperty", "(", "sandbox", ",", "function", "(", "k", ",", "v", ")", "{", "if", "(", "!", "found", ")", "{", "found", "=", "true", ";", "msg", "+=", "' Detected globals:'", ".", "yellow", "+", "NL", ";", "}", "msg", "+=", "(", "typeof", "v", "===", "'function'", "?", "' function '", ".", "blue", ":", "' var '", ".", "blue", ")", "+", "k", ".", "cyan", "+", "NL", ";", "}", ")", ";", "}", "warn", "(", "msg", "+", "'>>'", ".", "yellow", ")", ";", "}", "}" ]
Saves all script files required by the specified module into a single output file, in the correct loading order. This is used on release builds. @constructor @implements {MiddlewareInterface} @param {Context} context The execution context for the middleware stack.
[ "Saves", "all", "script", "files", "required", "by", "the", "specified", "module", "into", "a", "single", "output", "file", "in", "the", "correct", "loading", "order", ".", "This", "is", "used", "on", "release", "builds", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/makeReleaseBuild.js#L133-L426
35,371
claudio-silva/grunt-angular-builder
tasks/middleware/makeReleaseBuild.js
outputModuleDefinitions
function outputModuleDefinitions (module, headWasOutput) { for (var i = 0, m = module.bodies.length; i < m; ++i) { var bodyPath = module.bodyPaths[i]; if (!bodyPath) console.log (module.name, i, module.bodies.length, module.bodyPaths); // Skip bodies who's corresponding file was already output. if (context.outputtedFiles[bodyPath]) continue; context.outputtedFiles[bodyPath] = true; var body = module.optimize ? optimize (module.bodies[i], bodyPath, module) : {status: STAT.INDENTED, data: module.bodies[i]}; if (i || !headWasOutput) traceOutput.push (LINE, '// File: ' + bodyPath, LINE, ''); traceOutput.push (conditionalIndent (body)); } }
javascript
function outputModuleDefinitions (module, headWasOutput) { for (var i = 0, m = module.bodies.length; i < m; ++i) { var bodyPath = module.bodyPaths[i]; if (!bodyPath) console.log (module.name, i, module.bodies.length, module.bodyPaths); // Skip bodies who's corresponding file was already output. if (context.outputtedFiles[bodyPath]) continue; context.outputtedFiles[bodyPath] = true; var body = module.optimize ? optimize (module.bodies[i], bodyPath, module) : {status: STAT.INDENTED, data: module.bodies[i]}; if (i || !headWasOutput) traceOutput.push (LINE, '// File: ' + bodyPath, LINE, ''); traceOutput.push (conditionalIndent (body)); } }
[ "function", "outputModuleDefinitions", "(", "module", ",", "headWasOutput", ")", "{", "for", "(", "var", "i", "=", "0", ",", "m", "=", "module", ".", "bodies", ".", "length", ";", "i", "<", "m", ";", "++", "i", ")", "{", "var", "bodyPath", "=", "module", ".", "bodyPaths", "[", "i", "]", ";", "if", "(", "!", "bodyPath", ")", "console", ".", "log", "(", "module", ".", "name", ",", "i", ",", "module", ".", "bodies", ".", "length", ",", "module", ".", "bodyPaths", ")", ";", "// Skip bodies who's corresponding file was already output.", "if", "(", "context", ".", "outputtedFiles", "[", "bodyPath", "]", ")", "continue", ";", "context", ".", "outputtedFiles", "[", "bodyPath", "]", "=", "true", ";", "var", "body", "=", "module", ".", "optimize", "?", "optimize", "(", "module", ".", "bodies", "[", "i", "]", ",", "bodyPath", ",", "module", ")", ":", "{", "status", ":", "STAT", ".", "INDENTED", ",", "data", ":", "module", ".", "bodies", "[", "i", "]", "}", ";", "if", "(", "i", "||", "!", "headWasOutput", ")", "traceOutput", ".", "push", "(", "LINE", ",", "'// File: '", "+", "bodyPath", ",", "LINE", ",", "''", ")", ";", "traceOutput", ".", "push", "(", "conditionalIndent", "(", "body", ")", ")", ";", "}", "}" ]
Insert additional module definitions. @param {ModuleDef} module @param {boolean} headWasOutput
[ "Insert", "additional", "module", "definitions", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/makeReleaseBuild.js#L281-L300
35,372
claudio-silva/grunt-angular-builder
tasks/middleware/makeReleaseBuild.js
conditionalIndent
function conditionalIndent (result) { return result.status === STAT.INDENTED ? result.data : indent (result.data, 1, options.indent); }
javascript
function conditionalIndent (result) { return result.status === STAT.INDENTED ? result.data : indent (result.data, 1, options.indent); }
[ "function", "conditionalIndent", "(", "result", ")", "{", "return", "result", ".", "status", "===", "STAT", ".", "INDENTED", "?", "result", ".", "data", ":", "indent", "(", "result", ".", "data", ",", "1", ",", "options", ".", "indent", ")", ";", "}" ]
Returns the given text indented unless it was already indented. @param {OperationResult} result @return {string}
[ "Returns", "the", "given", "text", "indented", "unless", "it", "was", "already", "indented", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/makeReleaseBuild.js#L393-L396
35,373
claudio-silva/grunt-angular-builder
tasks/middleware/makeReleaseBuild.js
warnAboutGlobalCode
function warnAboutGlobalCode (sandbox, path) { var msg = csprintf ('yellow', 'Incompatible code found on the global scope!'.red + NL + (path ? reportErrorLocation (path) : '') + getExplanation ( 'This kind of code will behave differently between release and debug builds.' + NL + 'You should wrap it in a self-invoking function and/or assign global variables/functions ' + 'directly to the window object.' ) ); if (context.verbose) { var found = false; util.forEachProperty (sandbox, function (k, v) { if (!found) { found = true; msg += ' Detected globals:'.yellow + NL; } msg += (typeof v === 'function' ? ' function '.blue : ' var '.blue) + k.cyan + NL; }); } warn (msg + '>>'.yellow); }
javascript
function warnAboutGlobalCode (sandbox, path) { var msg = csprintf ('yellow', 'Incompatible code found on the global scope!'.red + NL + (path ? reportErrorLocation (path) : '') + getExplanation ( 'This kind of code will behave differently between release and debug builds.' + NL + 'You should wrap it in a self-invoking function and/or assign global variables/functions ' + 'directly to the window object.' ) ); if (context.verbose) { var found = false; util.forEachProperty (sandbox, function (k, v) { if (!found) { found = true; msg += ' Detected globals:'.yellow + NL; } msg += (typeof v === 'function' ? ' function '.blue : ' var '.blue) + k.cyan + NL; }); } warn (msg + '>>'.yellow); }
[ "function", "warnAboutGlobalCode", "(", "sandbox", ",", "path", ")", "{", "var", "msg", "=", "csprintf", "(", "'yellow'", ",", "'Incompatible code found on the global scope!'", ".", "red", "+", "NL", "+", "(", "path", "?", "reportErrorLocation", "(", "path", ")", ":", "''", ")", "+", "getExplanation", "(", "'This kind of code will behave differently between release and debug builds.'", "+", "NL", "+", "'You should wrap it in a self-invoking function and/or assign global variables/functions '", "+", "'directly to the window object.'", ")", ")", ";", "if", "(", "context", ".", "verbose", ")", "{", "var", "found", "=", "false", ";", "util", ".", "forEachProperty", "(", "sandbox", ",", "function", "(", "k", ",", "v", ")", "{", "if", "(", "!", "found", ")", "{", "found", "=", "true", ";", "msg", "+=", "' Detected globals:'", ".", "yellow", "+", "NL", ";", "}", "msg", "+=", "(", "typeof", "v", "===", "'function'", "?", "' function '", ".", "blue", ":", "' var '", ".", "blue", ")", "+", "k", ".", "cyan", "+", "NL", ";", "}", ")", ";", "}", "warn", "(", "msg", "+", "'>>'", ".", "yellow", ")", ";", "}" ]
Isses a warning about problematic code found on the global scope. @param {Object} sandbox @param {string} path
[ "Isses", "a", "warning", "about", "problematic", "code", "found", "on", "the", "global", "scope", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/makeReleaseBuild.js#L403-L425
35,374
claudio-silva/grunt-angular-builder
tasks/middleware/makeReleaseBuild.js
scanForOptimization
function scanForOptimization (context) { var module, verboseOut = context.grunt.log.verbose; // Track repeated files to determine which modules can be optimized. Object.keys (context.modules).forEach (function (name) { if (context.modules.hasOwnProperty (name)) { module = context.modules[name]; if (!module.external) module.filePaths ().forEach (function (path) { if (!context.filesRefCount[path]) context.filesRefCount[path] = 1; else { verboseOut.writeln (util.csprintf ('white', 'Not optimizing <cyan>%</cyan> because it shares some/all of its files with other modules.', name)); ++context.filesRefCount[path]; module.optimize = false; } }); } }); // Determine which modules can act as containers for non-optimized sections of code. scan (context.options.mainModule, true); /** * Search for unoptimizable modules. * @param {string} moduleName * @param {boolean?} first=false Is this the root module? * @returns {boolean} `true` if the module is not optimizable. */ function scan (moduleName, first) { var module = context.modules[moduleName]; if (!module) throw new Error (sprintf ("Module '%' was not found.", moduleName)); // Ignore the module if it's external. if (module.external) return false; if (!module.optimize) { if (first) module.nonOptimizedContainer = true; disableOptimizationsForChildrenOf (module); return true; } for (var i = 0, m = module.requires.length, any = false; i < m; ++i) if (scan (module.requires[i])) //Note: scan() still must be called for ALL submodules! any = true; if (any) module.nonOptimizedContainer = true; return false; } function disableOptimizationsForChildrenOf (module) { if (module.external) return; for (var i = 0, m = module.requires.length; i < m; ++i) { var sub = context.modules[module.requires[i]]; if (sub.external) continue; if (sub.optimize) verboseOut.writeln (util.csprintf ('white', "Also disabling optimizations for <cyan>%</cyan>.", sub.name.cyan)); sub.optimize = false; disableOptimizationsForChildrenOf (sub); } } }
javascript
function scanForOptimization (context) { var module, verboseOut = context.grunt.log.verbose; // Track repeated files to determine which modules can be optimized. Object.keys (context.modules).forEach (function (name) { if (context.modules.hasOwnProperty (name)) { module = context.modules[name]; if (!module.external) module.filePaths ().forEach (function (path) { if (!context.filesRefCount[path]) context.filesRefCount[path] = 1; else { verboseOut.writeln (util.csprintf ('white', 'Not optimizing <cyan>%</cyan> because it shares some/all of its files with other modules.', name)); ++context.filesRefCount[path]; module.optimize = false; } }); } }); // Determine which modules can act as containers for non-optimized sections of code. scan (context.options.mainModule, true); /** * Search for unoptimizable modules. * @param {string} moduleName * @param {boolean?} first=false Is this the root module? * @returns {boolean} `true` if the module is not optimizable. */ function scan (moduleName, first) { var module = context.modules[moduleName]; if (!module) throw new Error (sprintf ("Module '%' was not found.", moduleName)); // Ignore the module if it's external. if (module.external) return false; if (!module.optimize) { if (first) module.nonOptimizedContainer = true; disableOptimizationsForChildrenOf (module); return true; } for (var i = 0, m = module.requires.length, any = false; i < m; ++i) if (scan (module.requires[i])) //Note: scan() still must be called for ALL submodules! any = true; if (any) module.nonOptimizedContainer = true; return false; } function disableOptimizationsForChildrenOf (module) { if (module.external) return; for (var i = 0, m = module.requires.length; i < m; ++i) { var sub = context.modules[module.requires[i]]; if (sub.external) continue; if (sub.optimize) verboseOut.writeln (util.csprintf ('white', "Also disabling optimizations for <cyan>%</cyan>.", sub.name.cyan)); sub.optimize = false; disableOptimizationsForChildrenOf (sub); } } }
[ "function", "scanForOptimization", "(", "context", ")", "{", "var", "module", ",", "verboseOut", "=", "context", ".", "grunt", ".", "log", ".", "verbose", ";", "// Track repeated files to determine which modules can be optimized.", "Object", ".", "keys", "(", "context", ".", "modules", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "if", "(", "context", ".", "modules", ".", "hasOwnProperty", "(", "name", ")", ")", "{", "module", "=", "context", ".", "modules", "[", "name", "]", ";", "if", "(", "!", "module", ".", "external", ")", "module", ".", "filePaths", "(", ")", ".", "forEach", "(", "function", "(", "path", ")", "{", "if", "(", "!", "context", ".", "filesRefCount", "[", "path", "]", ")", "context", ".", "filesRefCount", "[", "path", "]", "=", "1", ";", "else", "{", "verboseOut", ".", "writeln", "(", "util", ".", "csprintf", "(", "'white'", ",", "'Not optimizing <cyan>%</cyan> because it shares some/all of its files with other modules.'", ",", "name", ")", ")", ";", "++", "context", ".", "filesRefCount", "[", "path", "]", ";", "module", ".", "optimize", "=", "false", ";", "}", "}", ")", ";", "}", "}", ")", ";", "// Determine which modules can act as containers for non-optimized sections of code.", "scan", "(", "context", ".", "options", ".", "mainModule", ",", "true", ")", ";", "/**\n * Search for unoptimizable modules.\n * @param {string} moduleName\n * @param {boolean?} first=false Is this the root module?\n * @returns {boolean} `true` if the module is not optimizable.\n */", "function", "scan", "(", "moduleName", ",", "first", ")", "{", "var", "module", "=", "context", ".", "modules", "[", "moduleName", "]", ";", "if", "(", "!", "module", ")", "throw", "new", "Error", "(", "sprintf", "(", "\"Module '%' was not found.\"", ",", "moduleName", ")", ")", ";", "// Ignore the module if it's external.", "if", "(", "module", ".", "external", ")", "return", "false", ";", "if", "(", "!", "module", ".", "optimize", ")", "{", "if", "(", "first", ")", "module", ".", "nonOptimizedContainer", "=", "true", ";", "disableOptimizationsForChildrenOf", "(", "module", ")", ";", "return", "true", ";", "}", "for", "(", "var", "i", "=", "0", ",", "m", "=", "module", ".", "requires", ".", "length", ",", "any", "=", "false", ";", "i", "<", "m", ";", "++", "i", ")", "if", "(", "scan", "(", "module", ".", "requires", "[", "i", "]", ")", ")", "//Note: scan() still must be called for ALL submodules!", "any", "=", "true", ";", "if", "(", "any", ")", "module", ".", "nonOptimizedContainer", "=", "true", ";", "return", "false", ";", "}", "function", "disableOptimizationsForChildrenOf", "(", "module", ")", "{", "if", "(", "module", ".", "external", ")", "return", ";", "for", "(", "var", "i", "=", "0", ",", "m", "=", "module", ".", "requires", ".", "length", ";", "i", "<", "m", ";", "++", "i", ")", "{", "var", "sub", "=", "context", ".", "modules", "[", "module", ".", "requires", "[", "i", "]", "]", ";", "if", "(", "sub", ".", "external", ")", "continue", ";", "if", "(", "sub", ".", "optimize", ")", "verboseOut", ".", "writeln", "(", "util", ".", "csprintf", "(", "'white'", ",", "\"Also disabling optimizations for <cyan>%</cyan>.\"", ",", "sub", ".", "name", ".", "cyan", ")", ")", ";", "sub", ".", "optimize", "=", "false", ";", "disableOptimizationsForChildrenOf", "(", "sub", ")", ";", "}", "}", "}" ]
Determine which modules can be optimized. @param {Context} context The execution context for the middleware stack.
[ "Determine", "which", "modules", "can", "be", "optimized", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/makeReleaseBuild.js#L432-L503
35,375
claudio-silva/grunt-angular-builder
tasks/middleware/makeReleaseBuild.js
scan
function scan (moduleName, first) { var module = context.modules[moduleName]; if (!module) throw new Error (sprintf ("Module '%' was not found.", moduleName)); // Ignore the module if it's external. if (module.external) return false; if (!module.optimize) { if (first) module.nonOptimizedContainer = true; disableOptimizationsForChildrenOf (module); return true; } for (var i = 0, m = module.requires.length, any = false; i < m; ++i) if (scan (module.requires[i])) //Note: scan() still must be called for ALL submodules! any = true; if (any) module.nonOptimizedContainer = true; return false; }
javascript
function scan (moduleName, first) { var module = context.modules[moduleName]; if (!module) throw new Error (sprintf ("Module '%' was not found.", moduleName)); // Ignore the module if it's external. if (module.external) return false; if (!module.optimize) { if (first) module.nonOptimizedContainer = true; disableOptimizationsForChildrenOf (module); return true; } for (var i = 0, m = module.requires.length, any = false; i < m; ++i) if (scan (module.requires[i])) //Note: scan() still must be called for ALL submodules! any = true; if (any) module.nonOptimizedContainer = true; return false; }
[ "function", "scan", "(", "moduleName", ",", "first", ")", "{", "var", "module", "=", "context", ".", "modules", "[", "moduleName", "]", ";", "if", "(", "!", "module", ")", "throw", "new", "Error", "(", "sprintf", "(", "\"Module '%' was not found.\"", ",", "moduleName", ")", ")", ";", "// Ignore the module if it's external.", "if", "(", "module", ".", "external", ")", "return", "false", ";", "if", "(", "!", "module", ".", "optimize", ")", "{", "if", "(", "first", ")", "module", ".", "nonOptimizedContainer", "=", "true", ";", "disableOptimizationsForChildrenOf", "(", "module", ")", ";", "return", "true", ";", "}", "for", "(", "var", "i", "=", "0", ",", "m", "=", "module", ".", "requires", ".", "length", ",", "any", "=", "false", ";", "i", "<", "m", ";", "++", "i", ")", "if", "(", "scan", "(", "module", ".", "requires", "[", "i", "]", ")", ")", "//Note: scan() still must be called for ALL submodules!", "any", "=", "true", ";", "if", "(", "any", ")", "module", ".", "nonOptimizedContainer", "=", "true", ";", "return", "false", ";", "}" ]
Search for unoptimizable modules. @param {string} moduleName @param {boolean?} first=false Is this the root module? @returns {boolean} `true` if the module is not optimizable.
[ "Search", "for", "unoptimizable", "modules", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/makeReleaseBuild.js#L467-L487
35,376
JamesMessinger/json-schema-lib
lib/api/PluginManager.js
validatePriority
function validatePriority (priority) { var type = typeOf(priority); if (type.hasValue && !type.isNumber) { throw ono('Invalid arguments. Expected a priority number.'); } }
javascript
function validatePriority (priority) { var type = typeOf(priority); if (type.hasValue && !type.isNumber) { throw ono('Invalid arguments. Expected a priority number.'); } }
[ "function", "validatePriority", "(", "priority", ")", "{", "var", "type", "=", "typeOf", "(", "priority", ")", ";", "if", "(", "type", ".", "hasValue", "&&", "!", "type", ".", "isNumber", ")", "{", "throw", "ono", "(", "'Invalid arguments. Expected a priority number.'", ")", ";", "}", "}" ]
Ensures that a user-supplied value is a valid plugin priority. An error is thrown if the value is invalid. @param {*} priority - The user-supplied value to validate
[ "Ensures", "that", "a", "user", "-", "supplied", "value", "is", "a", "valid", "plugin", "priority", ".", "An", "error", "is", "thrown", "if", "the", "value", "is", "invalid", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/PluginManager.js#L64-L70
35,377
JamesMessinger/json-schema-lib
lib/util/deepAssign.js
deepAssign
function deepAssign (target, source) { var keys = Object.keys(source); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var oldValue = target[key]; var newValue = source[key]; target[key] = deepClone(newValue, oldValue); } return target; }
javascript
function deepAssign (target, source) { var keys = Object.keys(source); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var oldValue = target[key]; var newValue = source[key]; target[key] = deepClone(newValue, oldValue); } return target; }
[ "function", "deepAssign", "(", "target", ",", "source", ")", "{", "var", "keys", "=", "Object", ".", "keys", "(", "source", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "var", "key", "=", "keys", "[", "i", "]", ";", "var", "oldValue", "=", "target", "[", "key", "]", ";", "var", "newValue", "=", "source", "[", "key", "]", ";", "target", "[", "key", "]", "=", "deepClone", "(", "newValue", ",", "oldValue", ")", ";", "}", "return", "target", ";", "}" ]
Deeply assigns the properties of the source object to the target object @param {object} target @param {object} source
[ "Deeply", "assigns", "the", "properties", "of", "the", "source", "object", "to", "the", "target", "object" ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/util/deepAssign.js#L13-L25
35,378
JamesMessinger/json-schema-lib
lib/util/deepAssign.js
deepClone
function deepClone (value, oldValue) { var type = typeOf(value); var clone; if (type.isPOJO) { var oldType = typeOf(oldValue); if (oldType.isPOJO) { // Return a merged clone of the old POJO and the new POJO clone = deepAssign({}, oldValue); return deepAssign(clone, value); } else { return deepAssign({}, value); } } else if (type.isArray) { clone = []; for (var i = 0; i < value.length; i++) { clone.push(deepClone(value[i])); } } else if (type.hasValue) { // string, boolean, number, function, Date, RegExp, etc. // Just return it as-is return value; } }
javascript
function deepClone (value, oldValue) { var type = typeOf(value); var clone; if (type.isPOJO) { var oldType = typeOf(oldValue); if (oldType.isPOJO) { // Return a merged clone of the old POJO and the new POJO clone = deepAssign({}, oldValue); return deepAssign(clone, value); } else { return deepAssign({}, value); } } else if (type.isArray) { clone = []; for (var i = 0; i < value.length; i++) { clone.push(deepClone(value[i])); } } else if (type.hasValue) { // string, boolean, number, function, Date, RegExp, etc. // Just return it as-is return value; } }
[ "function", "deepClone", "(", "value", ",", "oldValue", ")", "{", "var", "type", "=", "typeOf", "(", "value", ")", ";", "var", "clone", ";", "if", "(", "type", ".", "isPOJO", ")", "{", "var", "oldType", "=", "typeOf", "(", "oldValue", ")", ";", "if", "(", "oldType", ".", "isPOJO", ")", "{", "// Return a merged clone of the old POJO and the new POJO", "clone", "=", "deepAssign", "(", "{", "}", ",", "oldValue", ")", ";", "return", "deepAssign", "(", "clone", ",", "value", ")", ";", "}", "else", "{", "return", "deepAssign", "(", "{", "}", ",", "value", ")", ";", "}", "}", "else", "if", "(", "type", ".", "isArray", ")", "{", "clone", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "value", ".", "length", ";", "i", "++", ")", "{", "clone", ".", "push", "(", "deepClone", "(", "value", "[", "i", "]", ")", ")", ";", "}", "}", "else", "if", "(", "type", ".", "hasValue", ")", "{", "// string, boolean, number, function, Date, RegExp, etc.", "// Just return it as-is", "return", "value", ";", "}", "}" ]
Returns a deep clone of the given value @param {*} value @param {*} oldValue @returns {*}
[ "Returns", "a", "deep", "clone", "of", "the", "given", "value" ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/util/deepAssign.js#L34-L60
35,379
JamesMessinger/json-schema-lib
lib/api/JsonSchemaLib/resolveFileReferences.js
crawl
function crawl (obj, file) { var type = typeOf(obj); if (!type.isPOJO && !type.isArray) { return; } if (type.isPOJO && isFileReference(obj)) { // We found a file reference, so resolve it resolveFileReference(obj.$ref, file); } // Crawl this POJO or Array, looking for nested JSON References // // NOTE: According to the spec, JSON References should not have any properties other than "$ref". // However, in practice, many schema authors DO add additional properties. Because of this, // we crawl JSON Reference objects just like normal POJOs. If the schema author has added // additional properties, then they have opted-into this non-spec-compliant behavior. var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = obj[key]; crawl(value, file); } }
javascript
function crawl (obj, file) { var type = typeOf(obj); if (!type.isPOJO && !type.isArray) { return; } if (type.isPOJO && isFileReference(obj)) { // We found a file reference, so resolve it resolveFileReference(obj.$ref, file); } // Crawl this POJO or Array, looking for nested JSON References // // NOTE: According to the spec, JSON References should not have any properties other than "$ref". // However, in practice, many schema authors DO add additional properties. Because of this, // we crawl JSON Reference objects just like normal POJOs. If the schema author has added // additional properties, then they have opted-into this non-spec-compliant behavior. var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = obj[key]; crawl(value, file); } }
[ "function", "crawl", "(", "obj", ",", "file", ")", "{", "var", "type", "=", "typeOf", "(", "obj", ")", ";", "if", "(", "!", "type", ".", "isPOJO", "&&", "!", "type", ".", "isArray", ")", "{", "return", ";", "}", "if", "(", "type", ".", "isPOJO", "&&", "isFileReference", "(", "obj", ")", ")", "{", "// We found a file reference, so resolve it", "resolveFileReference", "(", "obj", ".", "$ref", ",", "file", ")", ";", "}", "// Crawl this POJO or Array, looking for nested JSON References", "//", "// NOTE: According to the spec, JSON References should not have any properties other than \"$ref\".", "// However, in practice, many schema authors DO add additional properties. Because of this,", "// we crawl JSON Reference objects just like normal POJOs. If the schema author has added", "// additional properties, then they have opted-into this non-spec-compliant behavior.", "var", "keys", "=", "Object", ".", "keys", "(", "obj", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "var", "key", "=", "keys", "[", "i", "]", ";", "var", "value", "=", "obj", "[", "key", "]", ";", "crawl", "(", "value", ",", "file", ")", ";", "}", "}" ]
Recursively crawls the given value, and resolves any external JSON References. @param {*} obj - The value to crawl. If it's not an object or array, it will be ignored. @param {File} file - The file that the value is part of
[ "Recursively", "crawls", "the", "given", "value", "and", "resolves", "any", "external", "JSON", "References", "." ]
6a30b2be496b82eda61d050b30e64b44fa42734a
https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/JsonSchemaLib/resolveFileReferences.js#L26-L51
35,380
commenthol/markedpp
src/anchorSlugger.js
getBitbucketId
function getBitbucketId (text) { text = 'markdown-header-' + text .toLowerCase() .replace(/\\(.)/g, (_m, c) => c.charCodeAt(0)) // add escaped chars with their charcode .normalize('NFKD').replace(/[\u0300-\u036f]/g, '') .replace(/[^\w\s-]/g, '') .replace(/\s+/g, '-') // whitespace .replace(/-+/g, '-') // duplicated hyphen .replace(/^-+|-+$/g, '') // heading/ tailing hyphen return text }
javascript
function getBitbucketId (text) { text = 'markdown-header-' + text .toLowerCase() .replace(/\\(.)/g, (_m, c) => c.charCodeAt(0)) // add escaped chars with their charcode .normalize('NFKD').replace(/[\u0300-\u036f]/g, '') .replace(/[^\w\s-]/g, '') .replace(/\s+/g, '-') // whitespace .replace(/-+/g, '-') // duplicated hyphen .replace(/^-+|-+$/g, '') // heading/ tailing hyphen return text }
[ "function", "getBitbucketId", "(", "text", ")", "{", "text", "=", "'markdown-header-'", "+", "text", ".", "toLowerCase", "(", ")", ".", "replace", "(", "/", "\\\\(.)", "/", "g", ",", "(", "_m", ",", "c", ")", "=>", "c", ".", "charCodeAt", "(", "0", ")", ")", "// add escaped chars with their charcode", ".", "normalize", "(", "'NFKD'", ")", ".", "replace", "(", "/", "[\\u0300-\\u036f]", "/", "g", ",", "''", ")", ".", "replace", "(", "/", "[^\\w\\s-]", "/", "g", ",", "''", ")", ".", "replace", "(", "/", "\\s+", "/", "g", ",", "'-'", ")", "// whitespace", ".", "replace", "(", "/", "-+", "/", "g", ",", "'-'", ")", "// duplicated hyphen", ".", "replace", "(", "/", "^-+|-+$", "/", "g", ",", "''", ")", "// heading/ tailing hyphen", "return", "text", "}" ]
getBitbucketId - anchors used at bitbucket.org @private @see: https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/toc.py#L25 There seams to be some "magic" preprocessor which could not be handled here. @see: https://github.com/Python-Markdown/markdown/issues/222 If no repetition, or if the repetition is 0 then ignore. Otherwise append '_' and the number. https://groups.google.com/d/msg/bitbucket-users/XnEWbbzs5wU/Fat0UdIecZkJ
[ "getBitbucketId", "-", "anchors", "used", "at", "bitbucket", ".", "org" ]
f72db5aa2c1b858a9d5403c6103f24227d74c611
https://github.com/commenthol/markedpp/blob/f72db5aa2c1b858a9d5403c6103f24227d74c611/src/anchorSlugger.js#L64-L74
35,381
commenthol/markedpp
src/anchorSlugger.js
getPandocId
function getPandocId (text) { text = text .replace(emojiRegex(), '') // Strip emojis .toLowerCase() .trim() .replace(/%25|%/ig, '') // remove single % signs .replace(RE_ENTITIES, '') // remove xml/html entities .replace(RE_SPECIALS, '') // single chars that are removed but not [.-] .replace(/\s+/g, '-') // whitespaces .replace(/^-+|-+$/g, '') // heading/ tailing hyphen .replace(RE_CJK, '') // CJK punctuations that are removed if (/^[0-9-]+$/.test(text)) { text = 'section' } return text }
javascript
function getPandocId (text) { text = text .replace(emojiRegex(), '') // Strip emojis .toLowerCase() .trim() .replace(/%25|%/ig, '') // remove single % signs .replace(RE_ENTITIES, '') // remove xml/html entities .replace(RE_SPECIALS, '') // single chars that are removed but not [.-] .replace(/\s+/g, '-') // whitespaces .replace(/^-+|-+$/g, '') // heading/ tailing hyphen .replace(RE_CJK, '') // CJK punctuations that are removed if (/^[0-9-]+$/.test(text)) { text = 'section' } return text }
[ "function", "getPandocId", "(", "text", ")", "{", "text", "=", "text", ".", "replace", "(", "emojiRegex", "(", ")", ",", "''", ")", "// Strip emojis", ".", "toLowerCase", "(", ")", ".", "trim", "(", ")", ".", "replace", "(", "/", "%25|%", "/", "ig", ",", "''", ")", "// remove single % signs", ".", "replace", "(", "RE_ENTITIES", ",", "''", ")", "// remove xml/html entities", ".", "replace", "(", "RE_SPECIALS", ",", "''", ")", "// single chars that are removed but not [.-]", ".", "replace", "(", "/", "\\s+", "/", "g", ",", "'-'", ")", "// whitespaces", ".", "replace", "(", "/", "^-+|-+$", "/", "g", ",", "''", ")", "// heading/ tailing hyphen", ".", "replace", "(", "RE_CJK", ",", "''", ")", "// CJK punctuations that are removed", "if", "(", "/", "^[0-9-]+$", "/", ".", "test", "(", "text", ")", ")", "{", "text", "=", "'section'", "}", "return", "text", "}" ]
getPandocId - anchors used at pandoc @private
[ "getPandocId", "-", "anchors", "used", "at", "pandoc" ]
f72db5aa2c1b858a9d5403c6103f24227d74c611
https://github.com/commenthol/markedpp/blob/f72db5aa2c1b858a9d5403c6103f24227d74c611/src/anchorSlugger.js#L104-L120
35,382
commenthol/markedpp
src/anchorSlugger.js
getMarkedId
function getMarkedId (text) { return entities.decode(text) .toLowerCase() .trim() .replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~_]/g, '') .replace(/\s/g, '-') }
javascript
function getMarkedId (text) { return entities.decode(text) .toLowerCase() .trim() .replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~_]/g, '') .replace(/\s/g, '-') }
[ "function", "getMarkedId", "(", "text", ")", "{", "return", "entities", ".", "decode", "(", "text", ")", ".", "toLowerCase", "(", ")", ".", "trim", "(", ")", ".", "replace", "(", "/", "[\\u2000-\\u206F\\u2E00-\\u2E7F\\\\'!\"#$%&()*+,./:;<=>?@[\\]^`{|}~_]", "/", "g", ",", "''", ")", ".", "replace", "(", "/", "\\s", "/", "g", ",", "'-'", ")", "}" ]
getMarkedId - anchors used in `npm i marked` @private @see: https://github.com/markedjs/marked/blob/master/lib/marked.js#L1306
[ "getMarkedId", "-", "anchors", "used", "in", "npm", "i", "marked" ]
f72db5aa2c1b858a9d5403c6103f24227d74c611
https://github.com/commenthol/markedpp/blob/f72db5aa2c1b858a9d5403c6103f24227d74c611/src/anchorSlugger.js#L127-L133
35,383
commenthol/markedpp
src/anchorSlugger.js
getMarkDownItAnchorId
function getMarkDownItAnchorId (text) { text = text .replace(/^[<]|[>]$/g, '') // correct markdown format bold/url text = entities.decode(text) .toLowerCase() .trim() .replace(/\s+/g, '-') return encodeURIComponent(text) }
javascript
function getMarkDownItAnchorId (text) { text = text .replace(/^[<]|[>]$/g, '') // correct markdown format bold/url text = entities.decode(text) .toLowerCase() .trim() .replace(/\s+/g, '-') return encodeURIComponent(text) }
[ "function", "getMarkDownItAnchorId", "(", "text", ")", "{", "text", "=", "text", ".", "replace", "(", "/", "^[<]|[>]$", "/", "g", ",", "''", ")", "// correct markdown format bold/url", "text", "=", "entities", ".", "decode", "(", "text", ")", ".", "toLowerCase", "(", ")", ".", "trim", "(", ")", ".", "replace", "(", "/", "\\s+", "/", "g", ",", "'-'", ")", "return", "encodeURIComponent", "(", "text", ")", "}" ]
getMarkDownItAnchorId - anchors used with `npm i markdown-it-anchor` @private @see: https://github.com/valeriangalliat/markdown-it-anchor/blob/master/index.js#L1 If no repetition, or if the repetition is 0 then ignore. Otherwise append '_' and the number. numbering starts at 2!
[ "getMarkDownItAnchorId", "-", "anchors", "used", "with", "npm", "i", "markdown", "-", "it", "-", "anchor" ]
f72db5aa2c1b858a9d5403c6103f24227d74c611
https://github.com/commenthol/markedpp/blob/f72db5aa2c1b858a9d5403c6103f24227d74c611/src/anchorSlugger.js#L142-L150
35,384
commenthol/markedpp
src/anchorSlugger.js
slugger
function slugger (header, mode) { mode = mode || 'marked' let replace switch (mode) { case MODE.MARKED: replace = getMarkedId break case MODE.MARKDOWNIT: return getMarkDownItAnchorId(header) case MODE.GITHUB: replace = getGithubId break case MODE.GITLAB: replace = getGitlabId break case MODE.PANDOC: replace = getPandocId break case MODE.BITBUCKET: replace = getBitbucketId break case MODE.GHOST: replace = getGhostId break default: throw new Error('Unknown mode: ' + mode) } const href = replace(asciiOnlyToLowerCase(header.trim())) return encodeURI(href) }
javascript
function slugger (header, mode) { mode = mode || 'marked' let replace switch (mode) { case MODE.MARKED: replace = getMarkedId break case MODE.MARKDOWNIT: return getMarkDownItAnchorId(header) case MODE.GITHUB: replace = getGithubId break case MODE.GITLAB: replace = getGitlabId break case MODE.PANDOC: replace = getPandocId break case MODE.BITBUCKET: replace = getBitbucketId break case MODE.GHOST: replace = getGhostId break default: throw new Error('Unknown mode: ' + mode) } const href = replace(asciiOnlyToLowerCase(header.trim())) return encodeURI(href) }
[ "function", "slugger", "(", "header", ",", "mode", ")", "{", "mode", "=", "mode", "||", "'marked'", "let", "replace", "switch", "(", "mode", ")", "{", "case", "MODE", ".", "MARKED", ":", "replace", "=", "getMarkedId", "break", "case", "MODE", ".", "MARKDOWNIT", ":", "return", "getMarkDownItAnchorId", "(", "header", ")", "case", "MODE", ".", "GITHUB", ":", "replace", "=", "getGithubId", "break", "case", "MODE", ".", "GITLAB", ":", "replace", "=", "getGitlabId", "break", "case", "MODE", ".", "PANDOC", ":", "replace", "=", "getPandocId", "break", "case", "MODE", ".", "BITBUCKET", ":", "replace", "=", "getBitbucketId", "break", "case", "MODE", ".", "GHOST", ":", "replace", "=", "getGhostId", "break", "default", ":", "throw", "new", "Error", "(", "'Unknown mode: '", "+", "mode", ")", "}", "const", "href", "=", "replace", "(", "asciiOnlyToLowerCase", "(", "header", ".", "trim", "(", ")", ")", ")", "return", "encodeURI", "(", "href", ")", "}" ]
Generates an anchor for the given header and mode. @param header {String} The header to be anchored. @param mode {String} The anchor mode (github.com|nodejs.org|bitbucket.org|ghost.org|gitlab.com). @return {String} The header anchor that is compatible with the given mode.
[ "Generates", "an", "anchor", "for", "the", "given", "header", "and", "mode", "." ]
f72db5aa2c1b858a9d5403c6103f24227d74c611
https://github.com/commenthol/markedpp/blob/f72db5aa2c1b858a9d5403c6103f24227d74c611/src/anchorSlugger.js#L174-L206
35,385
Skellington-Closet/skellington
lib/help.js
registerHelpListener
function registerHelpListener (controller, helpInfo) { controller.hears('^help ' + helpInfo.command + '$', 'direct_mention,direct_message', (bot, message) => { let replyText = helpInfo.text if (typeof helpInfo.text === 'function') { let helpOpts = _.merge({botName: bot.identity.name}, _.pick(message, ['team', 'channel', 'user'])) replyText = helpInfo.text(helpOpts) } bot.reply(message, replyText) }) }
javascript
function registerHelpListener (controller, helpInfo) { controller.hears('^help ' + helpInfo.command + '$', 'direct_mention,direct_message', (bot, message) => { let replyText = helpInfo.text if (typeof helpInfo.text === 'function') { let helpOpts = _.merge({botName: bot.identity.name}, _.pick(message, ['team', 'channel', 'user'])) replyText = helpInfo.text(helpOpts) } bot.reply(message, replyText) }) }
[ "function", "registerHelpListener", "(", "controller", ",", "helpInfo", ")", "{", "controller", ".", "hears", "(", "'^help '", "+", "helpInfo", ".", "command", "+", "'$'", ",", "'direct_mention,direct_message'", ",", "(", "bot", ",", "message", ")", "=>", "{", "let", "replyText", "=", "helpInfo", ".", "text", "if", "(", "typeof", "helpInfo", ".", "text", "===", "'function'", ")", "{", "let", "helpOpts", "=", "_", ".", "merge", "(", "{", "botName", ":", "bot", ".", "identity", ".", "name", "}", ",", "_", ".", "pick", "(", "message", ",", "[", "'team'", ",", "'channel'", ",", "'user'", "]", ")", ")", "replyText", "=", "helpInfo", ".", "text", "(", "helpOpts", ")", "}", "bot", ".", "reply", "(", "message", ",", "replyText", ")", "}", ")", "}" ]
Adds a single help listener for a plugin @param controller @param helpInfo
[ "Adds", "a", "single", "help", "listener", "for", "a", "plugin" ]
fa660c0864ab13188c0b663cd57ccbcc979683f1
https://github.com/Skellington-Closet/skellington/blob/fa660c0864ab13188c0b663cd57ccbcc979683f1/lib/help.js#L40-L52
35,386
LivePersonInc/chronosjs
src/courier/PostMessageMapper.js
toEvent
function toEvent(message) { if (message) { if (message.error) { PostMessageUtilities.log("Error on message: " + message.error, "ERROR", "PostMessageMapper"); return function() { return message; }; } else { return _getMappedMethod.call(this, message); } } }
javascript
function toEvent(message) { if (message) { if (message.error) { PostMessageUtilities.log("Error on message: " + message.error, "ERROR", "PostMessageMapper"); return function() { return message; }; } else { return _getMappedMethod.call(this, message); } } }
[ "function", "toEvent", "(", "message", ")", "{", "if", "(", "message", ")", "{", "if", "(", "message", ".", "error", ")", "{", "PostMessageUtilities", ".", "log", "(", "\"Error on message: \"", "+", "message", ".", "error", ",", "\"ERROR\"", ",", "\"PostMessageMapper\"", ")", ";", "return", "function", "(", ")", "{", "return", "message", ";", "}", ";", "}", "else", "{", "return", "_getMappedMethod", ".", "call", "(", "this", ",", "message", ")", ";", "}", "}", "}" ]
Method mapping the message to the correct event on the event channel and invoking it @param {Object} message - the message to be mapped @returns {Function} the handler function to invoke on the event channel
[ "Method", "mapping", "the", "message", "to", "the", "correct", "event", "on", "the", "event", "channel", "and", "invoking", "it" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageMapper.js#L61-L73
35,387
LivePersonInc/chronosjs
src/courier/PostMessageMapper.js
toMessage
function toMessage(id, name) { return { method: { id: id, name: name, args: Array.prototype.slice.call(arguments, 2) } }; }
javascript
function toMessage(id, name) { return { method: { id: id, name: name, args: Array.prototype.slice.call(arguments, 2) } }; }
[ "function", "toMessage", "(", "id", ",", "name", ")", "{", "return", "{", "method", ":", "{", "id", ":", "id", ",", "name", ":", "name", ",", "args", ":", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "2", ")", "}", "}", ";", "}" ]
Method mapping the method call on the event aggregator to a message which can be posted @param {String} id - the id for the call @param {String} name - the name of the method optional additional method arguments @returns {Object} the mapped method
[ "Method", "mapping", "the", "method", "call", "on", "the", "event", "aggregator", "to", "a", "message", "which", "can", "be", "posted" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageMapper.js#L82-L90
35,388
LivePersonInc/chronosjs
src/courier/PostMessageMapper.js
_getMappedMethod
function _getMappedMethod(message) { var method = message && message.method; var name = method && method.name; var args = method && method.args; var eventChannel = this.eventChannel; return function() { if (eventChannel && eventChannel[name]) { return eventChannel[name].apply(eventChannel, args); } else { /* istanbul ignore next */ PostMessageUtilities.log("No channel exists", "ERROR", "PostMessageMapper"); } }; }
javascript
function _getMappedMethod(message) { var method = message && message.method; var name = method && method.name; var args = method && method.args; var eventChannel = this.eventChannel; return function() { if (eventChannel && eventChannel[name]) { return eventChannel[name].apply(eventChannel, args); } else { /* istanbul ignore next */ PostMessageUtilities.log("No channel exists", "ERROR", "PostMessageMapper"); } }; }
[ "function", "_getMappedMethod", "(", "message", ")", "{", "var", "method", "=", "message", "&&", "message", ".", "method", ";", "var", "name", "=", "method", "&&", "method", ".", "name", ";", "var", "args", "=", "method", "&&", "method", ".", "args", ";", "var", "eventChannel", "=", "this", ".", "eventChannel", ";", "return", "function", "(", ")", "{", "if", "(", "eventChannel", "&&", "eventChannel", "[", "name", "]", ")", "{", "return", "eventChannel", "[", "name", "]", ".", "apply", "(", "eventChannel", ",", "args", ")", ";", "}", "else", "{", "/* istanbul ignore next */", "PostMessageUtilities", ".", "log", "(", "\"No channel exists\"", ",", "\"ERROR\"", ",", "\"PostMessageMapper\"", ")", ";", "}", "}", ";", "}" ]
Method getting the mapped method on the event channel after which it can be invoked @param {Object} message - the message to be mapped optional additional method arguments @return {Function} the function to invoke on the event channel @private
[ "Method", "getting", "the", "mapped", "method", "on", "the", "event", "channel", "after", "which", "it", "can", "be", "invoked" ]
05631bf9323ce3eda368c1c3e9308b23e91f4d13
https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageMapper.js#L99-L114
35,389
desirepath41/visualCaptcha-npm
visualCaptcha.js
function( numberOfOptions ) { var visualCaptchaSession = this.session[ this.namespace ], imageValues = []; // Avoid the next IF failing if a string with a number is sent numberOfOptions = parseInt( numberOfOptions, 10 ); // If it's not a valid number, default to 5 if ( ! numberOfOptions || ! _.isNumber(numberOfOptions) || isNaN(numberOfOptions) ) { numberOfOptions = 5; } // Set the minimum numberOfOptions to four if ( numberOfOptions < 4 ) { numberOfOptions = 4; } // Shuffle all imageOptions this.imageOptions = _.shuffle( this.imageOptions ); // Get a random sample of X images visualCaptchaSession.images = _.sample( this.imageOptions, numberOfOptions ); // Set a random value for each of the images, to be used in the frontend visualCaptchaSession.images.forEach( function( image, index ) { var randomValue = crypto.randomBytes( 20 ).toString( 'hex' ); imageValues.push( randomValue ); visualCaptchaSession.images[ index ].value = randomValue; }); // Select a random image option, pluck current valid image option visualCaptchaSession.validImageOption = _.sample( _.without( visualCaptchaSession.images, visualCaptchaSession.validImageOption ) ); // Select a random audio option, pluck current valid audio option visualCaptchaSession.validAudioOption = _.sample( _.without( this.audioOptions, visualCaptchaSession.validAudioOption ) ); // Set random hashes for audio and image field names, and add it in the frontend data object visualCaptchaSession.frontendData = { values: imageValues, imageName: this.getValidImageOption().name, imageFieldName: crypto.randomBytes( 20 ).toString( 'hex' ), audioFieldName: crypto.randomBytes( 20 ).toString( 'hex' ) }; }
javascript
function( numberOfOptions ) { var visualCaptchaSession = this.session[ this.namespace ], imageValues = []; // Avoid the next IF failing if a string with a number is sent numberOfOptions = parseInt( numberOfOptions, 10 ); // If it's not a valid number, default to 5 if ( ! numberOfOptions || ! _.isNumber(numberOfOptions) || isNaN(numberOfOptions) ) { numberOfOptions = 5; } // Set the minimum numberOfOptions to four if ( numberOfOptions < 4 ) { numberOfOptions = 4; } // Shuffle all imageOptions this.imageOptions = _.shuffle( this.imageOptions ); // Get a random sample of X images visualCaptchaSession.images = _.sample( this.imageOptions, numberOfOptions ); // Set a random value for each of the images, to be used in the frontend visualCaptchaSession.images.forEach( function( image, index ) { var randomValue = crypto.randomBytes( 20 ).toString( 'hex' ); imageValues.push( randomValue ); visualCaptchaSession.images[ index ].value = randomValue; }); // Select a random image option, pluck current valid image option visualCaptchaSession.validImageOption = _.sample( _.without( visualCaptchaSession.images, visualCaptchaSession.validImageOption ) ); // Select a random audio option, pluck current valid audio option visualCaptchaSession.validAudioOption = _.sample( _.without( this.audioOptions, visualCaptchaSession.validAudioOption ) ); // Set random hashes for audio and image field names, and add it in the frontend data object visualCaptchaSession.frontendData = { values: imageValues, imageName: this.getValidImageOption().name, imageFieldName: crypto.randomBytes( 20 ).toString( 'hex' ), audioFieldName: crypto.randomBytes( 20 ).toString( 'hex' ) }; }
[ "function", "(", "numberOfOptions", ")", "{", "var", "visualCaptchaSession", "=", "this", ".", "session", "[", "this", ".", "namespace", "]", ",", "imageValues", "=", "[", "]", ";", "// Avoid the next IF failing if a string with a number is sent", "numberOfOptions", "=", "parseInt", "(", "numberOfOptions", ",", "10", ")", ";", "// If it's not a valid number, default to 5", "if", "(", "!", "numberOfOptions", "||", "!", "_", ".", "isNumber", "(", "numberOfOptions", ")", "||", "isNaN", "(", "numberOfOptions", ")", ")", "{", "numberOfOptions", "=", "5", ";", "}", "// Set the minimum numberOfOptions to four", "if", "(", "numberOfOptions", "<", "4", ")", "{", "numberOfOptions", "=", "4", ";", "}", "// Shuffle all imageOptions", "this", ".", "imageOptions", "=", "_", ".", "shuffle", "(", "this", ".", "imageOptions", ")", ";", "// Get a random sample of X images", "visualCaptchaSession", ".", "images", "=", "_", ".", "sample", "(", "this", ".", "imageOptions", ",", "numberOfOptions", ")", ";", "// Set a random value for each of the images, to be used in the frontend", "visualCaptchaSession", ".", "images", ".", "forEach", "(", "function", "(", "image", ",", "index", ")", "{", "var", "randomValue", "=", "crypto", ".", "randomBytes", "(", "20", ")", ".", "toString", "(", "'hex'", ")", ";", "imageValues", ".", "push", "(", "randomValue", ")", ";", "visualCaptchaSession", ".", "images", "[", "index", "]", ".", "value", "=", "randomValue", ";", "}", ")", ";", "// Select a random image option, pluck current valid image option", "visualCaptchaSession", ".", "validImageOption", "=", "_", ".", "sample", "(", "_", ".", "without", "(", "visualCaptchaSession", ".", "images", ",", "visualCaptchaSession", ".", "validImageOption", ")", ")", ";", "// Select a random audio option, pluck current valid audio option", "visualCaptchaSession", ".", "validAudioOption", "=", "_", ".", "sample", "(", "_", ".", "without", "(", "this", ".", "audioOptions", ",", "visualCaptchaSession", ".", "validAudioOption", ")", ")", ";", "// Set random hashes for audio and image field names, and add it in the frontend data object", "visualCaptchaSession", ".", "frontendData", "=", "{", "values", ":", "imageValues", ",", "imageName", ":", "this", ".", "getValidImageOption", "(", ")", ".", "name", ",", "imageFieldName", ":", "crypto", ".", "randomBytes", "(", "20", ")", ".", "toString", "(", "'hex'", ")", ",", "audioFieldName", ":", "crypto", ".", "randomBytes", "(", "20", ")", ".", "toString", "(", "'hex'", ")", "}", ";", "}" ]
Generate a new valid option @param numberOfOptions is optional. Defaults to 5
[ "Generate", "a", "new", "valid", "option" ]
f1fe570d0a9d2e56c78fea8f77fef32cd5a7471d
https://github.com/desirepath41/visualCaptcha-npm/blob/f1fe570d0a9d2e56c78fea8f77fef32cd5a7471d/visualCaptcha.js#L28-L76
35,390
desirepath41/visualCaptcha-npm
visualCaptcha.js
function( response, fileType ) { var fs = require( 'fs' ), mime = require( 'mime' ), audioOption = this.getValidAudioOption(), audioFileName = audioOption ? audioOption.path : '',// If there's no audioOption, we set the file name as empty audioFilePath = __dirname + '/audios/' + audioFileName, mimeType, stream; // If the file name is empty, we skip any work and return a 404 response if ( audioFileName ) { // We need to replace '.mp3' with '.ogg' if the fileType === 'ogg' if ( fileType === 'ogg' ) { audioFileName = audioFileName.replace( /\.mp3/gi, '.ogg' ); audioFilePath = audioFilePath.replace( /\.mp3/gi, '.ogg' ); } else { fileType = 'mp3';// This isn't doing anything, really, but I feel better with it } fs.exists( audioFilePath, function( exists ) { if ( exists ) { mimeType = mime.getType( audioFilePath ); // Set the appropriate mime type response.set( 'content-type', mimeType ); // Make sure this is not cached response.set( 'cache-control', 'no-cache, no-store, must-revalidate' ); response.set( 'pragma', 'no-cache' ); response.set( 'expires', 0 ); stream = fs.createReadStream( audioFilePath ); var responseData = []; if ( stream ) { stream.on( 'data', function( chunk ) { responseData.push( chunk ); }); stream.on( 'end', function() { if ( ! response.headerSent ) { var finalData = Buffer.concat( responseData ); response.write( finalData ); // Add some noise randomly, so audio files can't be saved and matched easily by filesize or checksum var noiseData = crypto.randomBytes(Math.round((Math.random() * 1999)) + 501).toString('hex'); response.write( noiseData ); response.end(); } }); } else { response.status( 404 ).send( 'Not Found' ); } } else { response.status( 404 ).send( 'Not Found' ); } }); } else { response.status( 404 ).send( 'Not Found' ); } }
javascript
function( response, fileType ) { var fs = require( 'fs' ), mime = require( 'mime' ), audioOption = this.getValidAudioOption(), audioFileName = audioOption ? audioOption.path : '',// If there's no audioOption, we set the file name as empty audioFilePath = __dirname + '/audios/' + audioFileName, mimeType, stream; // If the file name is empty, we skip any work and return a 404 response if ( audioFileName ) { // We need to replace '.mp3' with '.ogg' if the fileType === 'ogg' if ( fileType === 'ogg' ) { audioFileName = audioFileName.replace( /\.mp3/gi, '.ogg' ); audioFilePath = audioFilePath.replace( /\.mp3/gi, '.ogg' ); } else { fileType = 'mp3';// This isn't doing anything, really, but I feel better with it } fs.exists( audioFilePath, function( exists ) { if ( exists ) { mimeType = mime.getType( audioFilePath ); // Set the appropriate mime type response.set( 'content-type', mimeType ); // Make sure this is not cached response.set( 'cache-control', 'no-cache, no-store, must-revalidate' ); response.set( 'pragma', 'no-cache' ); response.set( 'expires', 0 ); stream = fs.createReadStream( audioFilePath ); var responseData = []; if ( stream ) { stream.on( 'data', function( chunk ) { responseData.push( chunk ); }); stream.on( 'end', function() { if ( ! response.headerSent ) { var finalData = Buffer.concat( responseData ); response.write( finalData ); // Add some noise randomly, so audio files can't be saved and matched easily by filesize or checksum var noiseData = crypto.randomBytes(Math.round((Math.random() * 1999)) + 501).toString('hex'); response.write( noiseData ); response.end(); } }); } else { response.status( 404 ).send( 'Not Found' ); } } else { response.status( 404 ).send( 'Not Found' ); } }); } else { response.status( 404 ).send( 'Not Found' ); } }
[ "function", "(", "response", ",", "fileType", ")", "{", "var", "fs", "=", "require", "(", "'fs'", ")", ",", "mime", "=", "require", "(", "'mime'", ")", ",", "audioOption", "=", "this", ".", "getValidAudioOption", "(", ")", ",", "audioFileName", "=", "audioOption", "?", "audioOption", ".", "path", ":", "''", ",", "// If there's no audioOption, we set the file name as empty", "audioFilePath", "=", "__dirname", "+", "'/audios/'", "+", "audioFileName", ",", "mimeType", ",", "stream", ";", "// If the file name is empty, we skip any work and return a 404 response", "if", "(", "audioFileName", ")", "{", "// We need to replace '.mp3' with '.ogg' if the fileType === 'ogg'", "if", "(", "fileType", "===", "'ogg'", ")", "{", "audioFileName", "=", "audioFileName", ".", "replace", "(", "/", "\\.mp3", "/", "gi", ",", "'.ogg'", ")", ";", "audioFilePath", "=", "audioFilePath", ".", "replace", "(", "/", "\\.mp3", "/", "gi", ",", "'.ogg'", ")", ";", "}", "else", "{", "fileType", "=", "'mp3'", ";", "// This isn't doing anything, really, but I feel better with it", "}", "fs", ".", "exists", "(", "audioFilePath", ",", "function", "(", "exists", ")", "{", "if", "(", "exists", ")", "{", "mimeType", "=", "mime", ".", "getType", "(", "audioFilePath", ")", ";", "// Set the appropriate mime type", "response", ".", "set", "(", "'content-type'", ",", "mimeType", ")", ";", "// Make sure this is not cached", "response", ".", "set", "(", "'cache-control'", ",", "'no-cache, no-store, must-revalidate'", ")", ";", "response", ".", "set", "(", "'pragma'", ",", "'no-cache'", ")", ";", "response", ".", "set", "(", "'expires'", ",", "0", ")", ";", "stream", "=", "fs", ".", "createReadStream", "(", "audioFilePath", ")", ";", "var", "responseData", "=", "[", "]", ";", "if", "(", "stream", ")", "{", "stream", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "responseData", ".", "push", "(", "chunk", ")", ";", "}", ")", ";", "stream", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "if", "(", "!", "response", ".", "headerSent", ")", "{", "var", "finalData", "=", "Buffer", ".", "concat", "(", "responseData", ")", ";", "response", ".", "write", "(", "finalData", ")", ";", "// Add some noise randomly, so audio files can't be saved and matched easily by filesize or checksum", "var", "noiseData", "=", "crypto", ".", "randomBytes", "(", "Math", ".", "round", "(", "(", "Math", ".", "random", "(", ")", "*", "1999", ")", ")", "+", "501", ")", ".", "toString", "(", "'hex'", ")", ";", "response", ".", "write", "(", "noiseData", ")", ";", "response", ".", "end", "(", ")", ";", "}", "}", ")", ";", "}", "else", "{", "response", ".", "status", "(", "404", ")", ".", "send", "(", "'Not Found'", ")", ";", "}", "}", "else", "{", "response", ".", "status", "(", "404", ")", ".", "send", "(", "'Not Found'", ")", ";", "}", "}", ")", ";", "}", "else", "{", "response", ".", "status", "(", "404", ")", ".", "send", "(", "'Not Found'", ")", ";", "}", "}" ]
Stream audio file @param response Node's response object @param fileType defaults to 'mp3', can also be 'ogg'
[ "Stream", "audio", "file" ]
f1fe570d0a9d2e56c78fea8f77fef32cd5a7471d
https://github.com/desirepath41/visualCaptcha-npm/blob/f1fe570d0a9d2e56c78fea8f77fef32cd5a7471d/visualCaptcha.js#L143-L204
35,391
desirepath41/visualCaptcha-npm
visualCaptcha.js
function( index, response, isRetina ) { var fs = require( 'fs' ), imageOption = this.getImageOptionAtIndex( index ), imageFileName = imageOption ? imageOption.path : '',// If there's no imageOption, we set the file name as empty imageFilePath = __dirname + '/images/' + imageFileName, mime = require( 'mime' ), mimeType, stream; // Force boolean for isRetina if ( ! isRetina ) { isRetina = false; } else { isRetina = true; } // If retina is requested, change the file name if ( isRetina ) { imageFileName = imageFileName.replace( /\.png/gi, '@2x.png' ); imageFilePath = imageFilePath.replace( /\.png/gi, '@2x.png' ); } // If the index is non-existent, the file name will be empty, same as if the options weren't generated if ( imageFileName ) { fs.exists( imageFilePath, function( exists ) { if ( exists ) { mimeType = mime.getType( imageFilePath ); // Set the appropriate mime type response.set( 'content-type', mimeType ); // Make sure this is not cached response.set( 'cache-control', 'no-cache, no-store, must-revalidate' ); response.set( 'pragma', 'no-cache' ); response.set( 'expires', 0 ); stream = fs.createReadStream( imageFilePath ); var responseData = []; if ( stream ) { stream.on( 'data', function( chunk ) { responseData.push( chunk ); }); stream.on( 'end', function() { if ( ! response.headerSent ) { var finalData = Buffer.concat( responseData ); response.write( finalData ); // Add some noise randomly, so images can't be saved and matched easily by filesize or checksum var noiseData = crypto.randomBytes(Math.round((Math.random() * 1999)) + 501).toString('hex'); response.write( noiseData ); response.end(); } }); } else { response.status( 404 ).send( 'Not Found' ); } } else { response.status( 404 ).send( 'Not Found' ); } }); } else { response.status( 404 ).send( 'Not Found' ); } }
javascript
function( index, response, isRetina ) { var fs = require( 'fs' ), imageOption = this.getImageOptionAtIndex( index ), imageFileName = imageOption ? imageOption.path : '',// If there's no imageOption, we set the file name as empty imageFilePath = __dirname + '/images/' + imageFileName, mime = require( 'mime' ), mimeType, stream; // Force boolean for isRetina if ( ! isRetina ) { isRetina = false; } else { isRetina = true; } // If retina is requested, change the file name if ( isRetina ) { imageFileName = imageFileName.replace( /\.png/gi, '@2x.png' ); imageFilePath = imageFilePath.replace( /\.png/gi, '@2x.png' ); } // If the index is non-existent, the file name will be empty, same as if the options weren't generated if ( imageFileName ) { fs.exists( imageFilePath, function( exists ) { if ( exists ) { mimeType = mime.getType( imageFilePath ); // Set the appropriate mime type response.set( 'content-type', mimeType ); // Make sure this is not cached response.set( 'cache-control', 'no-cache, no-store, must-revalidate' ); response.set( 'pragma', 'no-cache' ); response.set( 'expires', 0 ); stream = fs.createReadStream( imageFilePath ); var responseData = []; if ( stream ) { stream.on( 'data', function( chunk ) { responseData.push( chunk ); }); stream.on( 'end', function() { if ( ! response.headerSent ) { var finalData = Buffer.concat( responseData ); response.write( finalData ); // Add some noise randomly, so images can't be saved and matched easily by filesize or checksum var noiseData = crypto.randomBytes(Math.round((Math.random() * 1999)) + 501).toString('hex'); response.write( noiseData ); response.end(); } }); } else { response.status( 404 ).send( 'Not Found' ); } } else { response.status( 404 ).send( 'Not Found' ); } }); } else { response.status( 404 ).send( 'Not Found' ); } }
[ "function", "(", "index", ",", "response", ",", "isRetina", ")", "{", "var", "fs", "=", "require", "(", "'fs'", ")", ",", "imageOption", "=", "this", ".", "getImageOptionAtIndex", "(", "index", ")", ",", "imageFileName", "=", "imageOption", "?", "imageOption", ".", "path", ":", "''", ",", "// If there's no imageOption, we set the file name as empty", "imageFilePath", "=", "__dirname", "+", "'/images/'", "+", "imageFileName", ",", "mime", "=", "require", "(", "'mime'", ")", ",", "mimeType", ",", "stream", ";", "// Force boolean for isRetina", "if", "(", "!", "isRetina", ")", "{", "isRetina", "=", "false", ";", "}", "else", "{", "isRetina", "=", "true", ";", "}", "// If retina is requested, change the file name", "if", "(", "isRetina", ")", "{", "imageFileName", "=", "imageFileName", ".", "replace", "(", "/", "\\.png", "/", "gi", ",", "'@2x.png'", ")", ";", "imageFilePath", "=", "imageFilePath", ".", "replace", "(", "/", "\\.png", "/", "gi", ",", "'@2x.png'", ")", ";", "}", "// If the index is non-existent, the file name will be empty, same as if the options weren't generated", "if", "(", "imageFileName", ")", "{", "fs", ".", "exists", "(", "imageFilePath", ",", "function", "(", "exists", ")", "{", "if", "(", "exists", ")", "{", "mimeType", "=", "mime", ".", "getType", "(", "imageFilePath", ")", ";", "// Set the appropriate mime type", "response", ".", "set", "(", "'content-type'", ",", "mimeType", ")", ";", "// Make sure this is not cached", "response", ".", "set", "(", "'cache-control'", ",", "'no-cache, no-store, must-revalidate'", ")", ";", "response", ".", "set", "(", "'pragma'", ",", "'no-cache'", ")", ";", "response", ".", "set", "(", "'expires'", ",", "0", ")", ";", "stream", "=", "fs", ".", "createReadStream", "(", "imageFilePath", ")", ";", "var", "responseData", "=", "[", "]", ";", "if", "(", "stream", ")", "{", "stream", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "responseData", ".", "push", "(", "chunk", ")", ";", "}", ")", ";", "stream", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "if", "(", "!", "response", ".", "headerSent", ")", "{", "var", "finalData", "=", "Buffer", ".", "concat", "(", "responseData", ")", ";", "response", ".", "write", "(", "finalData", ")", ";", "// Add some noise randomly, so images can't be saved and matched easily by filesize or checksum", "var", "noiseData", "=", "crypto", ".", "randomBytes", "(", "Math", ".", "round", "(", "(", "Math", ".", "random", "(", ")", "*", "1999", ")", ")", "+", "501", ")", ".", "toString", "(", "'hex'", ")", ";", "response", ".", "write", "(", "noiseData", ")", ";", "response", ".", "end", "(", ")", ";", "}", "}", ")", ";", "}", "else", "{", "response", ".", "status", "(", "404", ")", ".", "send", "(", "'Not Found'", ")", ";", "}", "}", "else", "{", "response", ".", "status", "(", "404", ")", ".", "send", "(", "'Not Found'", ")", ";", "}", "}", ")", ";", "}", "else", "{", "response", ".", "status", "(", "404", ")", ".", "send", "(", "'Not Found'", ")", ";", "}", "}" ]
Stream image file given an index in the session visualCaptcha images array @param index of the image in the session images array to send @param response Node's response object @paran isRetina boolean. Defaults to false
[ "Stream", "image", "file", "given", "an", "index", "in", "the", "session", "visualCaptcha", "images", "array" ]
f1fe570d0a9d2e56c78fea8f77fef32cd5a7471d
https://github.com/desirepath41/visualCaptcha-npm/blob/f1fe570d0a9d2e56c78fea8f77fef32cd5a7471d/visualCaptcha.js#L210-L278
35,392
NebulousLabs/Nodejs-Sia
src/sia.js
connect
async function connect(address) { const running = await isRunning(address) if (!running) { throw errCouldNotConnect } return siadWrapper(address) }
javascript
async function connect(address) { const running = await isRunning(address) if (!running) { throw errCouldNotConnect } return siadWrapper(address) }
[ "async", "function", "connect", "(", "address", ")", "{", "const", "running", "=", "await", "isRunning", "(", "address", ")", "if", "(", "!", "running", ")", "{", "throw", "errCouldNotConnect", "}", "return", "siadWrapper", "(", "address", ")", "}" ]
connect connects to a running Siad at `address` and returns a siadWrapper object.
[ "connect", "connects", "to", "a", "running", "Siad", "at", "address", "and", "returns", "a", "siadWrapper", "object", "." ]
147b48b97312ab69a4cd0fc207e6bb849124a3af
https://github.com/NebulousLabs/Nodejs-Sia/blob/147b48b97312ab69a4cd0fc207e6bb849124a3af/src/sia.js#L123-L129
35,393
strues/boldr
packages/core/src/client/configBrowser.js
walk
function walk(obj, path, initializeMissing = false) { let newObj = obj; if (path) { const ar = path.split('.'); while (ar.length) { const k = ar.shift(); if (initializeMissing && obj[k] == null) { newObj[k] = {}; newObj = newObj[k]; } else if (k in newObj) { newObj = newObj[k]; } else { throw new Error(`cannot find configuration param '${path}'`); } } } return newObj; }
javascript
function walk(obj, path, initializeMissing = false) { let newObj = obj; if (path) { const ar = path.split('.'); while (ar.length) { const k = ar.shift(); if (initializeMissing && obj[k] == null) { newObj[k] = {}; newObj = newObj[k]; } else if (k in newObj) { newObj = newObj[k]; } else { throw new Error(`cannot find configuration param '${path}'`); } } } return newObj; }
[ "function", "walk", "(", "obj", ",", "path", ",", "initializeMissing", "=", "false", ")", "{", "let", "newObj", "=", "obj", ";", "if", "(", "path", ")", "{", "const", "ar", "=", "path", ".", "split", "(", "'.'", ")", ";", "while", "(", "ar", ".", "length", ")", "{", "const", "k", "=", "ar", ".", "shift", "(", ")", ";", "if", "(", "initializeMissing", "&&", "obj", "[", "k", "]", "==", "null", ")", "{", "newObj", "[", "k", "]", "=", "{", "}", ";", "newObj", "=", "newObj", "[", "k", "]", ";", "}", "else", "if", "(", "k", "in", "newObj", ")", "{", "newObj", "=", "newObj", "[", "k", "]", ";", "}", "else", "{", "throw", "new", "Error", "(", "`", "${", "path", "}", "`", ")", ";", "}", "}", "}", "return", "newObj", ";", "}" ]
Taken from convict source code.
[ "Taken", "from", "convict", "source", "code", "." ]
21f1ed9a5ed754e01c50827249e89087b788e660
https://github.com/strues/boldr/blob/21f1ed9a5ed754e01c50827249e89087b788e660/packages/core/src/client/configBrowser.js#L2-L21
35,394
Skellington-Closet/skellington
index.js
getSlackbotConfig
function getSlackbotConfig (config) { return _.defaults(config.botkit, {debug: !!config.debug}, botkitDefaults) }
javascript
function getSlackbotConfig (config) { return _.defaults(config.botkit, {debug: !!config.debug}, botkitDefaults) }
[ "function", "getSlackbotConfig", "(", "config", ")", "{", "return", "_", ".", "defaults", "(", "config", ".", "botkit", ",", "{", "debug", ":", "!", "!", "config", ".", "debug", "}", ",", "botkitDefaults", ")", "}" ]
Gets the config object for Botkit.slackbot @param config
[ "Gets", "the", "config", "object", "for", "Botkit", ".", "slackbot" ]
fa660c0864ab13188c0b663cd57ccbcc979683f1
https://github.com/Skellington-Closet/skellington/blob/fa660c0864ab13188c0b663cd57ccbcc979683f1/index.js#L54-L56
35,395
Skellington-Closet/skellington
index.js
formatConfig
function formatConfig (config) { _.defaults(config, {debug: false, plugins: []}) config.debugOptions = config.debugOptions || {} config.connectedTeams = new Set() if (!Array.isArray(config.plugins)) { config.plugins = [config.plugins] } config.scopes = _.chain(config.plugins) .map('scopes') .flatten() .concat(_.isArray(config.scopes) ? config.scopes : []) .uniq() .remove(_.isString.bind(_)) .value() config.isSlackApp = !config.slackToken if (!config.slackToken && !(config.clientId && config.clientSecret && config.port)) { logger.error(`Missing configuration. Config must include either slackToken AND/OR clientId, clientSecret, and port`) process.exit(1) } }
javascript
function formatConfig (config) { _.defaults(config, {debug: false, plugins: []}) config.debugOptions = config.debugOptions || {} config.connectedTeams = new Set() if (!Array.isArray(config.plugins)) { config.plugins = [config.plugins] } config.scopes = _.chain(config.plugins) .map('scopes') .flatten() .concat(_.isArray(config.scopes) ? config.scopes : []) .uniq() .remove(_.isString.bind(_)) .value() config.isSlackApp = !config.slackToken if (!config.slackToken && !(config.clientId && config.clientSecret && config.port)) { logger.error(`Missing configuration. Config must include either slackToken AND/OR clientId, clientSecret, and port`) process.exit(1) } }
[ "function", "formatConfig", "(", "config", ")", "{", "_", ".", "defaults", "(", "config", ",", "{", "debug", ":", "false", ",", "plugins", ":", "[", "]", "}", ")", "config", ".", "debugOptions", "=", "config", ".", "debugOptions", "||", "{", "}", "config", ".", "connectedTeams", "=", "new", "Set", "(", ")", "if", "(", "!", "Array", ".", "isArray", "(", "config", ".", "plugins", ")", ")", "{", "config", ".", "plugins", "=", "[", "config", ".", "plugins", "]", "}", "config", ".", "scopes", "=", "_", ".", "chain", "(", "config", ".", "plugins", ")", ".", "map", "(", "'scopes'", ")", ".", "flatten", "(", ")", ".", "concat", "(", "_", ".", "isArray", "(", "config", ".", "scopes", ")", "?", "config", ".", "scopes", ":", "[", "]", ")", ".", "uniq", "(", ")", ".", "remove", "(", "_", ".", "isString", ".", "bind", "(", "_", ")", ")", ".", "value", "(", ")", "config", ".", "isSlackApp", "=", "!", "config", ".", "slackToken", "if", "(", "!", "config", ".", "slackToken", "&&", "!", "(", "config", ".", "clientId", "&&", "config", ".", "clientSecret", "&&", "config", ".", "port", ")", ")", "{", "logger", ".", "error", "(", "`", "`", ")", "process", ".", "exit", "(", "1", ")", "}", "}" ]
Formats config values so they are normalized, will exit the process with an error if required config is missing @param config
[ "Formats", "config", "values", "so", "they", "are", "normalized", "will", "exit", "the", "process", "with", "an", "error", "if", "required", "config", "is", "missing" ]
fa660c0864ab13188c0b663cd57ccbcc979683f1
https://github.com/Skellington-Closet/skellington/blob/fa660c0864ab13188c0b663cd57ccbcc979683f1/index.js#L63-L87
35,396
mikolalysenko/split-polygon
clip-poly.js
lerpW
function lerpW(a, wa, b, wb) { var d = wb - wa var t = -wa / d if(t < 0.0) { t = 0.0 } else if(t > 1.0) { t = 1.0 } var ti = 1.0 - t var n = a.length var r = new Array(n) for(var i=0; i<n; ++i) { r[i] = t * a[i] + ti * b[i] } return r }
javascript
function lerpW(a, wa, b, wb) { var d = wb - wa var t = -wa / d if(t < 0.0) { t = 0.0 } else if(t > 1.0) { t = 1.0 } var ti = 1.0 - t var n = a.length var r = new Array(n) for(var i=0; i<n; ++i) { r[i] = t * a[i] + ti * b[i] } return r }
[ "function", "lerpW", "(", "a", ",", "wa", ",", "b", ",", "wb", ")", "{", "var", "d", "=", "wb", "-", "wa", "var", "t", "=", "-", "wa", "/", "d", "if", "(", "t", "<", "0.0", ")", "{", "t", "=", "0.0", "}", "else", "if", "(", "t", ">", "1.0", ")", "{", "t", "=", "1.0", "}", "var", "ti", "=", "1.0", "-", "t", "var", "n", "=", "a", ".", "length", "var", "r", "=", "new", "Array", "(", "n", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "n", ";", "++", "i", ")", "{", "r", "[", "i", "]", "=", "t", "*", "a", "[", "i", "]", "+", "ti", "*", "b", "[", "i", "]", "}", "return", "r", "}" ]
Can't do this exactly and emit a floating point result
[ "Can", "t", "do", "this", "exactly", "and", "emit", "a", "floating", "point", "result" ]
7b7a567329bde91a700553fd3889f66acd69ef5b
https://github.com/mikolalysenko/split-polygon/blob/7b7a567329bde91a700553fd3889f66acd69ef5b/clip-poly.js#L17-L32
35,397
matteodelabre/midijs
lib/connect.js
connect
function connect() { return new Promise(function (resolve, reject) { navigator.requestMIDIAccess().then(function (access) { resolve(new Driver(access)); }).catch(function () { reject(new Error('MIDI access denied')); }); }); }
javascript
function connect() { return new Promise(function (resolve, reject) { navigator.requestMIDIAccess().then(function (access) { resolve(new Driver(access)); }).catch(function () { reject(new Error('MIDI access denied')); }); }); }
[ "function", "connect", "(", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "navigator", ".", "requestMIDIAccess", "(", ")", ".", "then", "(", "function", "(", "access", ")", "{", "resolve", "(", "new", "Driver", "(", "access", ")", ")", ";", "}", ")", ".", "catch", "(", "function", "(", ")", "{", "reject", "(", "new", "Error", "(", "'MIDI access denied'", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Establish a connection to the MIDI driver @return {Promise} A connection promise
[ "Establish", "a", "connection", "to", "the", "MIDI", "driver" ]
c11d2f938125336624f5c6ef4c8c1f6cfac07d93
https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/connect.js#L13-L21
35,398
glennjones/elsewhere-profiles
lib/page.js
function(callback){ var options = this.options, cache = this.options.cache, logger = this.options.logger; if(this.url){ logger.log('fetch page: ' + this.url); // if there is a cache and it holds the url if(cache &&cache.has(this.url)){ // http status - content located elsewhere, retrieve from there this.statusCode = 305; this.requestTime = 0; this.html = cache.get(this.url); logger.log('fetched html from cache: ' + this.url); this.parse(function(){ callback(this); }) // if not get the html from the url }else{ this.startedRequest = new Date(); var self = this; var requestObj = { uri: this.url, headers: options.httpHeaders } request(requestObj, function(requestErrors, response, body){ if(!requestErrors && response.statusCode === 200){ self.endedRequest = new Date(); self.requestTime = self.endedRequest.getTime() - self.startedRequest.getTime(); logger.log('fetched html from page: ' + self.requestTime + 'ms - ' + self.url); self.statusCode = response.statusCode; self.html = body; if(cache){ cache.set(self.url, body); } self.parse(function(){ self.status = "fetched"; callback(self); }) }else{ logger.warn('error requesting page: ' + self.url); self.error = 'error requesting page: ' + self.url; self.status = "errored"; callback(); } }); } }else{ logger.warn('no url given'); this.error = 'no url given'; this.status = "errored"; callback(); } }
javascript
function(callback){ var options = this.options, cache = this.options.cache, logger = this.options.logger; if(this.url){ logger.log('fetch page: ' + this.url); // if there is a cache and it holds the url if(cache &&cache.has(this.url)){ // http status - content located elsewhere, retrieve from there this.statusCode = 305; this.requestTime = 0; this.html = cache.get(this.url); logger.log('fetched html from cache: ' + this.url); this.parse(function(){ callback(this); }) // if not get the html from the url }else{ this.startedRequest = new Date(); var self = this; var requestObj = { uri: this.url, headers: options.httpHeaders } request(requestObj, function(requestErrors, response, body){ if(!requestErrors && response.statusCode === 200){ self.endedRequest = new Date(); self.requestTime = self.endedRequest.getTime() - self.startedRequest.getTime(); logger.log('fetched html from page: ' + self.requestTime + 'ms - ' + self.url); self.statusCode = response.statusCode; self.html = body; if(cache){ cache.set(self.url, body); } self.parse(function(){ self.status = "fetched"; callback(self); }) }else{ logger.warn('error requesting page: ' + self.url); self.error = 'error requesting page: ' + self.url; self.status = "errored"; callback(); } }); } }else{ logger.warn('no url given'); this.error = 'no url given'; this.status = "errored"; callback(); } }
[ "function", "(", "callback", ")", "{", "var", "options", "=", "this", ".", "options", ",", "cache", "=", "this", ".", "options", ".", "cache", ",", "logger", "=", "this", ".", "options", ".", "logger", ";", "if", "(", "this", ".", "url", ")", "{", "logger", ".", "log", "(", "'fetch page: '", "+", "this", ".", "url", ")", ";", "// if there is a cache and it holds the url", "if", "(", "cache", "&&", "cache", ".", "has", "(", "this", ".", "url", ")", ")", "{", "// http status - content located elsewhere, retrieve from there", "this", ".", "statusCode", "=", "305", ";", "this", ".", "requestTime", "=", "0", ";", "this", ".", "html", "=", "cache", ".", "get", "(", "this", ".", "url", ")", ";", "logger", ".", "log", "(", "'fetched html from cache: '", "+", "this", ".", "url", ")", ";", "this", ".", "parse", "(", "function", "(", ")", "{", "callback", "(", "this", ")", ";", "}", ")", "// if not get the html from the url ", "}", "else", "{", "this", ".", "startedRequest", "=", "new", "Date", "(", ")", ";", "var", "self", "=", "this", ";", "var", "requestObj", "=", "{", "uri", ":", "this", ".", "url", ",", "headers", ":", "options", ".", "httpHeaders", "}", "request", "(", "requestObj", ",", "function", "(", "requestErrors", ",", "response", ",", "body", ")", "{", "if", "(", "!", "requestErrors", "&&", "response", ".", "statusCode", "===", "200", ")", "{", "self", ".", "endedRequest", "=", "new", "Date", "(", ")", ";", "self", ".", "requestTime", "=", "self", ".", "endedRequest", ".", "getTime", "(", ")", "-", "self", ".", "startedRequest", ".", "getTime", "(", ")", ";", "logger", ".", "log", "(", "'fetched html from page: '", "+", "self", ".", "requestTime", "+", "'ms - '", "+", "self", ".", "url", ")", ";", "self", ".", "statusCode", "=", "response", ".", "statusCode", ";", "self", ".", "html", "=", "body", ";", "if", "(", "cache", ")", "{", "cache", ".", "set", "(", "self", ".", "url", ",", "body", ")", ";", "}", "self", ".", "parse", "(", "function", "(", ")", "{", "self", ".", "status", "=", "\"fetched\"", ";", "callback", "(", "self", ")", ";", "}", ")", "}", "else", "{", "logger", ".", "warn", "(", "'error requesting page: '", "+", "self", ".", "url", ")", ";", "self", ".", "error", "=", "'error requesting page: '", "+", "self", ".", "url", ";", "self", ".", "status", "=", "\"errored\"", ";", "callback", "(", ")", ";", "}", "}", ")", ";", "}", "}", "else", "{", "logger", ".", "warn", "(", "'no url given'", ")", ";", "this", ".", "error", "=", "'no url given'", ";", "this", ".", "status", "=", "\"errored\"", ";", "callback", "(", ")", ";", "}", "}" ]
fetches page and loads html into object before call parse
[ "fetches", "page", "and", "loads", "html", "into", "object", "before", "call", "parse" ]
f86a5d040d540d4f8ed4f86518b75a0e6c8855ba
https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/page.js#L62-L130
35,399
glennjones/elsewhere-profiles
lib/page.js
function(callback){ var options = {},// utils.clone( this.options ), self = this; options.baseUrl = self.url; self.startedUFParse = new Date(); //console.log(self.url) try { parser.parseHtml (self.html, options, function(err, data){ //console.log( JSON.stringify(data) ); if(data){ self.profile.hCards = self.getArrayOfContentType(data, 'h-card' ); self.profile.hResumes = self.getArrayOfContentType(data, 'hresume' ); self.profile.xfn = self.getArrayOfContentType(data, 'xfn' ); } if(callback){ callback(); } }); } catch(err) { self.options.logger.warn('error parsing microformats in page: ' + self.url); self.error = err; callback(); } self.endedUFParse = new Date(); self.parseTime = self.endedUFParse.getTime() - self.startedUFParse.getTime(); self.options.logger.log('time to parse microformats in page: ' + self.parseTime + 'ms - ' + self.url); }
javascript
function(callback){ var options = {},// utils.clone( this.options ), self = this; options.baseUrl = self.url; self.startedUFParse = new Date(); //console.log(self.url) try { parser.parseHtml (self.html, options, function(err, data){ //console.log( JSON.stringify(data) ); if(data){ self.profile.hCards = self.getArrayOfContentType(data, 'h-card' ); self.profile.hResumes = self.getArrayOfContentType(data, 'hresume' ); self.profile.xfn = self.getArrayOfContentType(data, 'xfn' ); } if(callback){ callback(); } }); } catch(err) { self.options.logger.warn('error parsing microformats in page: ' + self.url); self.error = err; callback(); } self.endedUFParse = new Date(); self.parseTime = self.endedUFParse.getTime() - self.startedUFParse.getTime(); self.options.logger.log('time to parse microformats in page: ' + self.parseTime + 'ms - ' + self.url); }
[ "function", "(", "callback", ")", "{", "var", "options", "=", "{", "}", ",", "// utils.clone( this.options ),", "self", "=", "this", ";", "options", ".", "baseUrl", "=", "self", ".", "url", ";", "self", ".", "startedUFParse", "=", "new", "Date", "(", ")", ";", "//console.log(self.url)", "try", "{", "parser", ".", "parseHtml", "(", "self", ".", "html", ",", "options", ",", "function", "(", "err", ",", "data", ")", "{", "//console.log( JSON.stringify(data) );", "if", "(", "data", ")", "{", "self", ".", "profile", ".", "hCards", "=", "self", ".", "getArrayOfContentType", "(", "data", ",", "'h-card'", ")", ";", "self", ".", "profile", ".", "hResumes", "=", "self", ".", "getArrayOfContentType", "(", "data", ",", "'hresume'", ")", ";", "self", ".", "profile", ".", "xfn", "=", "self", ".", "getArrayOfContentType", "(", "data", ",", "'xfn'", ")", ";", "}", "if", "(", "callback", ")", "{", "callback", "(", ")", ";", "}", "}", ")", ";", "}", "catch", "(", "err", ")", "{", "self", ".", "options", ".", "logger", ".", "warn", "(", "'error parsing microformats in page: '", "+", "self", ".", "url", ")", ";", "self", ".", "error", "=", "err", ";", "callback", "(", ")", ";", "}", "self", ".", "endedUFParse", "=", "new", "Date", "(", ")", ";", "self", ".", "parseTime", "=", "self", ".", "endedUFParse", ".", "getTime", "(", ")", "-", "self", ".", "startedUFParse", ".", "getTime", "(", ")", ";", "self", ".", "options", ".", "logger", ".", "log", "(", "'time to parse microformats in page: '", "+", "self", ".", "parseTime", "+", "'ms - '", "+", "self", ".", "url", ")", ";", "}" ]
parses microformats from html
[ "parses", "microformats", "from", "html" ]
f86a5d040d540d4f8ed4f86518b75a0e6c8855ba
https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/page.js#L134-L170