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
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
ArnaudBuchholz/gpf-js
build/gpf-debug.js
function () { var me = this; if (!me._dataInPromise) { me._dataInPromise = new Promise(function (resolve) { me._dataInResolve = resolve; }).then(function (data) { delete me._dataInPromise; delete me._dataInResolve; return data; }); } return me._dataInPromise; }
javascript
function () { var me = this; if (!me._dataInPromise) { me._dataInPromise = new Promise(function (resolve) { me._dataInResolve = resolve; }).then(function (data) { delete me._dataInPromise; delete me._dataInResolve; return data; }); } return me._dataInPromise; }
[ "function", "(", ")", "{", "var", "me", "=", "this", ";", "if", "(", "!", "me", ".", "_dataInPromise", ")", "{", "me", ".", "_dataInPromise", "=", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "me", ".", "_dataInResolve", "=", "resolve", ";", "}", ")", ".", "then", "(", "function", "(", "data", ")", "{", "delete", "me", ".", "_dataInPromise", ";", "delete", "me", ".", "_dataInResolve", ";", "return", "data", ";", "}", ")", ";", "}", "return", "me", ".", "_dataInPromise", ";", "}" ]
Wait until data was written to this stream @return {Promise} Resolved when a data as been written to this stream @since 0.2.5
[ "Wait", "until", "data", "was", "written", "to", "this", "stream" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/build/gpf-debug.js#L7459-L7471
train
ArnaudBuchholz/gpf-js
build/gpf-debug.js
function (data) { var me = this; me._waitForData(); me._dataInResolve(data); return new Promise(function (resolve, reject) { me._dataOutResolve = resolve; me._dataOutReject = reject; }).then(function (value) { delete me._dataOutResolve; delete me._dataOutReject; return value; }, function (reason) { delete me._dataOutResolve; delete me._dataOutReject; return Promise.reject(reason); }); }
javascript
function (data) { var me = this; me._waitForData(); me._dataInResolve(data); return new Promise(function (resolve, reject) { me._dataOutResolve = resolve; me._dataOutReject = reject; }).then(function (value) { delete me._dataOutResolve; delete me._dataOutReject; return value; }, function (reason) { delete me._dataOutResolve; delete me._dataOutReject; return Promise.reject(reason); }); }
[ "function", "(", "data", ")", "{", "var", "me", "=", "this", ";", "me", ".", "_waitForData", "(", ")", ";", "me", ".", "_dataInResolve", "(", "data", ")", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "me", ".", "_dataOutResolve", "=", "resolve", ";", "me", ".", "_dataOutReject", "=", "reject", ";", "}", ")", ".", "then", "(", "function", "(", "value", ")", "{", "delete", "me", ".", "_dataOutResolve", ";", "delete", "me", ".", "_dataOutReject", ";", "return", "value", ";", "}", ",", "function", "(", "reason", ")", "{", "delete", "me", ".", "_dataOutResolve", ";", "delete", "me", ".", "_dataOutReject", ";", "return", "Promise", ".", "reject", "(", "reason", ")", ";", "}", ")", ";", "}" ]
Waits for the read API to write it out @param {*} data Data to write @return {Promise} Resolved when write operation has been done on output @protected @since 0.2.5
[ "Waits", "for", "the", "read", "API", "to", "write", "it", "out" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/build/gpf-debug.js#L7480-L7496
train
ArnaudBuchholz/gpf-js
build/gpf-debug.js
_gpfXmlCheckDefinableNamespacePrefixName
function _gpfXmlCheckDefinableNamespacePrefixName(name) { _gpfXmlCheckValidNamespacePrefixName(name); _gpfXmlCheckNoXmlns(name); if (name === "xml") { gpf.Error.invalidXmlUseOfPrefixXml(); } }
javascript
function _gpfXmlCheckDefinableNamespacePrefixName(name) { _gpfXmlCheckValidNamespacePrefixName(name); _gpfXmlCheckNoXmlns(name); if (name === "xml") { gpf.Error.invalidXmlUseOfPrefixXml(); } }
[ "function", "_gpfXmlCheckDefinableNamespacePrefixName", "(", "name", ")", "{", "_gpfXmlCheckValidNamespacePrefixName", "(", "name", ")", ";", "_gpfXmlCheckNoXmlns", "(", "name", ")", ";", "if", "(", "name", "===", "\"xml\"", ")", "{", "gpf", ".", "Error", ".", "invalidXmlUseOfPrefixXml", "(", ")", ";", "}", "}" ]
Check if the given XML namespace prefix name can be defined @param {String} name Namespace prefix name to check @throws {gpf.Error.InvalidXmlNamespacePrefix} @throws {gpf.Error.InvalidXmlUseOfPrefixXmlns} @throws {gpf.Error.InvalidXmlUseOfPrefixXml} @since 0.2.7
[ "Check", "if", "the", "given", "XML", "namespace", "prefix", "name", "can", "be", "defined" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/build/gpf-debug.js#L7778-L7784
train
ArnaudBuchholz/gpf-js
build/gpf-debug.js
_gpfInterfacesPromisify
function _gpfInterfacesPromisify(interfaceSpecifier) { return function (object) { var iInterfaceImpl = _gpfInterfaceQuery(interfaceSpecifier, object); if (!iInterfaceImpl) { gpf.Error.interfaceExpected({ name: _gpfGetFunctionName(interfaceSpecifier) }); } return _gpfInterfacesWrap(iInterfaceImpl, interfaceSpecifier, Promise.resolve()); }; }
javascript
function _gpfInterfacesPromisify(interfaceSpecifier) { return function (object) { var iInterfaceImpl = _gpfInterfaceQuery(interfaceSpecifier, object); if (!iInterfaceImpl) { gpf.Error.interfaceExpected({ name: _gpfGetFunctionName(interfaceSpecifier) }); } return _gpfInterfacesWrap(iInterfaceImpl, interfaceSpecifier, Promise.resolve()); }; }
[ "function", "_gpfInterfacesPromisify", "(", "interfaceSpecifier", ")", "{", "return", "function", "(", "object", ")", "{", "var", "iInterfaceImpl", "=", "_gpfInterfaceQuery", "(", "interfaceSpecifier", ",", "object", ")", ";", "if", "(", "!", "iInterfaceImpl", ")", "{", "gpf", ".", "Error", ".", "interfaceExpected", "(", "{", "name", ":", "_gpfGetFunctionName", "(", "interfaceSpecifier", ")", "}", ")", ";", "}", "return", "_gpfInterfacesWrap", "(", "iInterfaceImpl", ",", "interfaceSpecifier", ",", "Promise", ".", "resolve", "(", ")", ")", ";", "}", ";", "}" ]
Build promisified interface wrapper @param {Function} interfaceSpecifier Reference interface @return {Function} Interface Wrapper constructor @since 0.2.8
[ "Build", "promisified", "interface", "wrapper" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/build/gpf-debug.js#L7807-L7815
train
ArnaudBuchholz/gpf-js
build/gpf-debug.js
_gpfAttributesDecorator
function _gpfAttributesDecorator() { var attributes = _gpfArraySlice(arguments); return function (ClassConstructor, member) { if (!_gpfIsClass(ClassConstructor)) { gpf.Error.es6classOnly(); } _gpfAttributesDecoratorAddAttributes(_gpfDefineClassImport(ClassConstructor), member, attributes); }; }
javascript
function _gpfAttributesDecorator() { var attributes = _gpfArraySlice(arguments); return function (ClassConstructor, member) { if (!_gpfIsClass(ClassConstructor)) { gpf.Error.es6classOnly(); } _gpfAttributesDecoratorAddAttributes(_gpfDefineClassImport(ClassConstructor), member, attributes); }; }
[ "function", "_gpfAttributesDecorator", "(", ")", "{", "var", "attributes", "=", "_gpfArraySlice", "(", "arguments", ")", ";", "return", "function", "(", "ClassConstructor", ",", "member", ")", "{", "if", "(", "!", "_gpfIsClass", "(", "ClassConstructor", ")", ")", "{", "gpf", ".", "Error", ".", "es6classOnly", "(", ")", ";", "}", "_gpfAttributesDecoratorAddAttributes", "(", "_gpfDefineClassImport", "(", "ClassConstructor", ")", ",", "member", ",", "attributes", ")", ";", "}", ";", "}" ]
Bridge ES6 decorators with attributes @param {...gpf.attributes.Attribute} attribute Attributes to add @return {Function} decorator function @throws {gpf.Error.InvalidParameter} @since 0.2.9
[ "Bridge", "ES6", "decorators", "with", "attributes" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/build/gpf-debug.js#L8646-L8654
train
popeindustries/buddy
lib/config/buildParser.js
parseBuild
function parseBuild(builds, fileExtensions, fileFactory, npmModulepaths, runtimeOptions, serverConfig, parent, level) { if (!parent) { numBuilds = 0; level = 1; } // Deprecate sources if ('sources' in builds) { warn(DEPRECATED_SOURCES, 1); } // Deprecate targets if ('targets' in builds) { warn(DEPRECATED_VERSION, 1); builds = builds.targets; } // Support basic mode with single build target if (!Array.isArray(builds)) builds = [builds]; return builds.reduce( (builds, buildConfig) => { const childBuilds = buildConfig.build || buildConfig.children; const options = buildConfig.options; const version = buildConfig.version; delete buildConfig.build; delete buildConfig.options; delete buildConfig.version; // Deprecate old formats if ('js' in buildConfig || 'css' in buildConfig || 'html' in buildConfig || 'targets' in buildConfig) { warn(DEPRECATED_VERSION); return builds; } // Deprecate aliases if (buildConfig.alias) warn(DEPRECATED_ALIAS, 1); // Deprecate modular if ('modular' in buildConfig) warn(DEPRECATED_MODULAR, 1); // Deprecate sources if (buildConfig.sources) warn(DEPRECATED_SOURCES, 1); if (buildConfig.bootstrap == null) buildConfig.bootstrap = true; if (buildConfig.label == null) buildConfig.label = ''; if (buildConfig.bundle == null || buildConfig.modular) buildConfig.bundle = true; buildConfig.batch = false; buildConfig.boilerplate = true; buildConfig.index = ++numBuilds; buildConfig.level = level; buildConfig.parent = parent; buildConfig.runtimeOptions = runtimeOptions; buildConfig.watchOnly = !buildConfig.output; parseInputOutput(buildConfig, fileExtensions, runtimeOptions); // Ignore build targets with nulled input (no grep match) if (!('input' in buildConfig && buildConfig.input != null)) return builds; const build = buildFactory(buildConfig); const caches = parent ? { fileCache: parent.fileCache, resolverCache: parent.resolverCache } : cache.createCaches(runtimeOptions.watch); build.browser = parent ? parent.browser : buildPlugins.isBrowserEnvironment(version); build.fileCache = caches.fileCache; build.resolverCache = caches.resolverCache; build.fileFactoryOptions = getFileFactoryOptions(build, parent, version, options, { fileExtensions, fileFactory, npmModulepaths, runtimeOptions, sourceroot: serverConfig.sourceroot, webroot: serverConfig.webroot }); build.fileFactory = build.fileFactoryOptions.fileFactory; // Flag as app server target build.isAppServer = isAppServer(build.inputpaths, serverConfig); // Traverse child build targets if (childBuilds) { build.builds = parseBuild( childBuilds, fileExtensions, fileFactory, npmModulepaths, runtimeOptions, serverConfig, build, level + 1 ); parseChildInputpaths(build); } builds.push(build); return builds; }, [] ); }
javascript
function parseBuild(builds, fileExtensions, fileFactory, npmModulepaths, runtimeOptions, serverConfig, parent, level) { if (!parent) { numBuilds = 0; level = 1; } // Deprecate sources if ('sources' in builds) { warn(DEPRECATED_SOURCES, 1); } // Deprecate targets if ('targets' in builds) { warn(DEPRECATED_VERSION, 1); builds = builds.targets; } // Support basic mode with single build target if (!Array.isArray(builds)) builds = [builds]; return builds.reduce( (builds, buildConfig) => { const childBuilds = buildConfig.build || buildConfig.children; const options = buildConfig.options; const version = buildConfig.version; delete buildConfig.build; delete buildConfig.options; delete buildConfig.version; // Deprecate old formats if ('js' in buildConfig || 'css' in buildConfig || 'html' in buildConfig || 'targets' in buildConfig) { warn(DEPRECATED_VERSION); return builds; } // Deprecate aliases if (buildConfig.alias) warn(DEPRECATED_ALIAS, 1); // Deprecate modular if ('modular' in buildConfig) warn(DEPRECATED_MODULAR, 1); // Deprecate sources if (buildConfig.sources) warn(DEPRECATED_SOURCES, 1); if (buildConfig.bootstrap == null) buildConfig.bootstrap = true; if (buildConfig.label == null) buildConfig.label = ''; if (buildConfig.bundle == null || buildConfig.modular) buildConfig.bundle = true; buildConfig.batch = false; buildConfig.boilerplate = true; buildConfig.index = ++numBuilds; buildConfig.level = level; buildConfig.parent = parent; buildConfig.runtimeOptions = runtimeOptions; buildConfig.watchOnly = !buildConfig.output; parseInputOutput(buildConfig, fileExtensions, runtimeOptions); // Ignore build targets with nulled input (no grep match) if (!('input' in buildConfig && buildConfig.input != null)) return builds; const build = buildFactory(buildConfig); const caches = parent ? { fileCache: parent.fileCache, resolverCache: parent.resolverCache } : cache.createCaches(runtimeOptions.watch); build.browser = parent ? parent.browser : buildPlugins.isBrowserEnvironment(version); build.fileCache = caches.fileCache; build.resolverCache = caches.resolverCache; build.fileFactoryOptions = getFileFactoryOptions(build, parent, version, options, { fileExtensions, fileFactory, npmModulepaths, runtimeOptions, sourceroot: serverConfig.sourceroot, webroot: serverConfig.webroot }); build.fileFactory = build.fileFactoryOptions.fileFactory; // Flag as app server target build.isAppServer = isAppServer(build.inputpaths, serverConfig); // Traverse child build targets if (childBuilds) { build.builds = parseBuild( childBuilds, fileExtensions, fileFactory, npmModulepaths, runtimeOptions, serverConfig, build, level + 1 ); parseChildInputpaths(build); } builds.push(build); return builds; }, [] ); }
[ "function", "parseBuild", "(", "builds", ",", "fileExtensions", ",", "fileFactory", ",", "npmModulepaths", ",", "runtimeOptions", ",", "serverConfig", ",", "parent", ",", "level", ")", "{", "if", "(", "!", "parent", ")", "{", "numBuilds", "=", "0", ";", "level", "=", "1", ";", "}", "if", "(", "'sources'", "in", "builds", ")", "{", "warn", "(", "DEPRECATED_SOURCES", ",", "1", ")", ";", "}", "if", "(", "'targets'", "in", "builds", ")", "{", "warn", "(", "DEPRECATED_VERSION", ",", "1", ")", ";", "builds", "=", "builds", ".", "targets", ";", "}", "if", "(", "!", "Array", ".", "isArray", "(", "builds", ")", ")", "builds", "=", "[", "builds", "]", ";", "return", "builds", ".", "reduce", "(", "(", "builds", ",", "buildConfig", ")", "=>", "{", "const", "childBuilds", "=", "buildConfig", ".", "build", "||", "buildConfig", ".", "children", ";", "const", "options", "=", "buildConfig", ".", "options", ";", "const", "version", "=", "buildConfig", ".", "version", ";", "delete", "buildConfig", ".", "build", ";", "delete", "buildConfig", ".", "options", ";", "delete", "buildConfig", ".", "version", ";", "if", "(", "'js'", "in", "buildConfig", "||", "'css'", "in", "buildConfig", "||", "'html'", "in", "buildConfig", "||", "'targets'", "in", "buildConfig", ")", "{", "warn", "(", "DEPRECATED_VERSION", ")", ";", "return", "builds", ";", "}", "if", "(", "buildConfig", ".", "alias", ")", "warn", "(", "DEPRECATED_ALIAS", ",", "1", ")", ";", "if", "(", "'modular'", "in", "buildConfig", ")", "warn", "(", "DEPRECATED_MODULAR", ",", "1", ")", ";", "if", "(", "buildConfig", ".", "sources", ")", "warn", "(", "DEPRECATED_SOURCES", ",", "1", ")", ";", "if", "(", "buildConfig", ".", "bootstrap", "==", "null", ")", "buildConfig", ".", "bootstrap", "=", "true", ";", "if", "(", "buildConfig", ".", "label", "==", "null", ")", "buildConfig", ".", "label", "=", "''", ";", "if", "(", "buildConfig", ".", "bundle", "==", "null", "||", "buildConfig", ".", "modular", ")", "buildConfig", ".", "bundle", "=", "true", ";", "buildConfig", ".", "batch", "=", "false", ";", "buildConfig", ".", "boilerplate", "=", "true", ";", "buildConfig", ".", "index", "=", "++", "numBuilds", ";", "buildConfig", ".", "level", "=", "level", ";", "buildConfig", ".", "parent", "=", "parent", ";", "buildConfig", ".", "runtimeOptions", "=", "runtimeOptions", ";", "buildConfig", ".", "watchOnly", "=", "!", "buildConfig", ".", "output", ";", "parseInputOutput", "(", "buildConfig", ",", "fileExtensions", ",", "runtimeOptions", ")", ";", "if", "(", "!", "(", "'input'", "in", "buildConfig", "&&", "buildConfig", ".", "input", "!=", "null", ")", ")", "return", "builds", ";", "const", "build", "=", "buildFactory", "(", "buildConfig", ")", ";", "const", "caches", "=", "parent", "?", "{", "fileCache", ":", "parent", ".", "fileCache", ",", "resolverCache", ":", "parent", ".", "resolverCache", "}", ":", "cache", ".", "createCaches", "(", "runtimeOptions", ".", "watch", ")", ";", "build", ".", "browser", "=", "parent", "?", "parent", ".", "browser", ":", "buildPlugins", ".", "isBrowserEnvironment", "(", "version", ")", ";", "build", ".", "fileCache", "=", "caches", ".", "fileCache", ";", "build", ".", "resolverCache", "=", "caches", ".", "resolverCache", ";", "build", ".", "fileFactoryOptions", "=", "getFileFactoryOptions", "(", "build", ",", "parent", ",", "version", ",", "options", ",", "{", "fileExtensions", ",", "fileFactory", ",", "npmModulepaths", ",", "runtimeOptions", ",", "sourceroot", ":", "serverConfig", ".", "sourceroot", ",", "webroot", ":", "serverConfig", ".", "webroot", "}", ")", ";", "build", ".", "fileFactory", "=", "build", ".", "fileFactoryOptions", ".", "fileFactory", ";", "build", ".", "isAppServer", "=", "isAppServer", "(", "build", ".", "inputpaths", ",", "serverConfig", ")", ";", "if", "(", "childBuilds", ")", "{", "build", ".", "builds", "=", "parseBuild", "(", "childBuilds", ",", "fileExtensions", ",", "fileFactory", ",", "npmModulepaths", ",", "runtimeOptions", ",", "serverConfig", ",", "build", ",", "level", "+", "1", ")", ";", "parseChildInputpaths", "(", "build", ")", ";", "}", "builds", ".", "push", "(", "build", ")", ";", "return", "builds", ";", "}", ",", "[", "]", ")", ";", "}" ]
Parse and validate build targets @param {Array} builds @param {Object} fileExtensions @param {Function} fileFactory @param {Array} npmModulepaths @param {Object} runtimeOptions @param {Object} serverConfig @param {Object} [parent] @param {Number} [level] @returns {Array}
[ "Parse", "and", "validate", "build", "targets" ]
c38afc2e6915743eb6cfcf5aba59a8699142c7a5
https://github.com/popeindustries/buddy/blob/c38afc2e6915743eb6cfcf5aba59a8699142c7a5/lib/config/buildParser.js#L54-L151
train
popeindustries/buddy
lib/config/buildParser.js
getFileFactoryOptions
function getFileFactoryOptions(build, parent, version, options, fileFactoryOptions) { const { fileFactory, runtimeOptions } = fileFactoryOptions; const hasPlugins = parent ? !!(options || version) : true; const needsPlugins = 'input' in build && build.input != null && !build.watchOnly; fileFactoryOptions.browser = build.browser; fileFactoryOptions.buildFactory = getBuildFactory(build); fileFactoryOptions.bundle = build.bundle; fileFactoryOptions.fileCache = build.fileCache; fileFactoryOptions.level = build.level + 2; fileFactoryOptions.pluginOptions = {}; fileFactoryOptions.resolverCache = build.resolverCache; // Only load plugins for active output builds if (needsPlugins) { // Use parent's if none defined fileFactoryOptions.pluginOptions = hasPlugins ? buildPlugins.load(build.type, options, version, runtimeOptions.compress) : parent.fileFactoryOptions.pluginOptions; } // Overwrite fileFactory function with memoized options fileFactoryOptions.fileFactory = function createFile(filepath) { return fileFactory(filepath, fileFactoryOptions); }; return fileFactoryOptions; }
javascript
function getFileFactoryOptions(build, parent, version, options, fileFactoryOptions) { const { fileFactory, runtimeOptions } = fileFactoryOptions; const hasPlugins = parent ? !!(options || version) : true; const needsPlugins = 'input' in build && build.input != null && !build.watchOnly; fileFactoryOptions.browser = build.browser; fileFactoryOptions.buildFactory = getBuildFactory(build); fileFactoryOptions.bundle = build.bundle; fileFactoryOptions.fileCache = build.fileCache; fileFactoryOptions.level = build.level + 2; fileFactoryOptions.pluginOptions = {}; fileFactoryOptions.resolverCache = build.resolverCache; // Only load plugins for active output builds if (needsPlugins) { // Use parent's if none defined fileFactoryOptions.pluginOptions = hasPlugins ? buildPlugins.load(build.type, options, version, runtimeOptions.compress) : parent.fileFactoryOptions.pluginOptions; } // Overwrite fileFactory function with memoized options fileFactoryOptions.fileFactory = function createFile(filepath) { return fileFactory(filepath, fileFactoryOptions); }; return fileFactoryOptions; }
[ "function", "getFileFactoryOptions", "(", "build", ",", "parent", ",", "version", ",", "options", ",", "fileFactoryOptions", ")", "{", "const", "{", "fileFactory", ",", "runtimeOptions", "}", "=", "fileFactoryOptions", ";", "const", "hasPlugins", "=", "parent", "?", "!", "!", "(", "options", "||", "version", ")", ":", "true", ";", "const", "needsPlugins", "=", "'input'", "in", "build", "&&", "build", ".", "input", "!=", "null", "&&", "!", "build", ".", "watchOnly", ";", "fileFactoryOptions", ".", "browser", "=", "build", ".", "browser", ";", "fileFactoryOptions", ".", "buildFactory", "=", "getBuildFactory", "(", "build", ")", ";", "fileFactoryOptions", ".", "bundle", "=", "build", ".", "bundle", ";", "fileFactoryOptions", ".", "fileCache", "=", "build", ".", "fileCache", ";", "fileFactoryOptions", ".", "level", "=", "build", ".", "level", "+", "2", ";", "fileFactoryOptions", ".", "pluginOptions", "=", "{", "}", ";", "fileFactoryOptions", ".", "resolverCache", "=", "build", ".", "resolverCache", ";", "if", "(", "needsPlugins", ")", "{", "fileFactoryOptions", ".", "pluginOptions", "=", "hasPlugins", "?", "buildPlugins", ".", "load", "(", "build", ".", "type", ",", "options", ",", "version", ",", "runtimeOptions", ".", "compress", ")", ":", "parent", ".", "fileFactoryOptions", ".", "pluginOptions", ";", "}", "fileFactoryOptions", ".", "fileFactory", "=", "function", "createFile", "(", "filepath", ")", "{", "return", "fileFactory", "(", "filepath", ",", "fileFactoryOptions", ")", ";", "}", ";", "return", "fileFactoryOptions", ";", "}" ]
Retrieve file factory options for 'build' @param {Build} build @param {Build} [parent] @param {Object} version @param {Object} options @param {Object} fileFactoryOptions @returns {Function}
[ "Retrieve", "file", "factory", "options", "for", "build" ]
c38afc2e6915743eb6cfcf5aba59a8699142c7a5
https://github.com/popeindustries/buddy/blob/c38afc2e6915743eb6cfcf5aba59a8699142c7a5/lib/config/buildParser.js#L162-L189
train
popeindustries/buddy
lib/config/buildParser.js
getBuildFactory
function getBuildFactory(build) { return function createBuild(inputpath, outputname) { const input = path.relative(process.cwd(), inputpath); let parent = build; if (!parent.builds.some(build => build.input == input)) { const outputpath = path.join(path.dirname(parent.outputpaths[0]), outputname); const buildConfig = { batch: parent.batch, boilerplate: false, bootstrap: false, browser: parent.browser, bundle: parent.bundle, fileCache: parent.fileCache, index: ++numBuilds, input, inputpaths: [inputpath], isAppServer: false, isDynamicBuild: true, label: '', level: parent.level + 1, output: path.relative(process.cwd(), path.dirname(outputpath)), outputpaths: [outputpath], parent, resolverCache: parent.resolverCache, runtimeOptions: parent.runtimeOptions, type: parent.type, watchOnly: parent.watchOnly }; const build = buildFactory(buildConfig); build.fileFactoryOptions = getFileFactoryOptions( build, parent, null, null, Object.assign({}, parent.fileFactoryOptions) ); build.fileFactory = build.fileFactoryOptions.fileFactory; parent.builds.push(build); parent.childInputpaths.push(inputpath); } // Find root build while (parent.parent) parent = parent.parent; parent.processFilesOptions.importBoilerplate = true; }; }
javascript
function getBuildFactory(build) { return function createBuild(inputpath, outputname) { const input = path.relative(process.cwd(), inputpath); let parent = build; if (!parent.builds.some(build => build.input == input)) { const outputpath = path.join(path.dirname(parent.outputpaths[0]), outputname); const buildConfig = { batch: parent.batch, boilerplate: false, bootstrap: false, browser: parent.browser, bundle: parent.bundle, fileCache: parent.fileCache, index: ++numBuilds, input, inputpaths: [inputpath], isAppServer: false, isDynamicBuild: true, label: '', level: parent.level + 1, output: path.relative(process.cwd(), path.dirname(outputpath)), outputpaths: [outputpath], parent, resolverCache: parent.resolverCache, runtimeOptions: parent.runtimeOptions, type: parent.type, watchOnly: parent.watchOnly }; const build = buildFactory(buildConfig); build.fileFactoryOptions = getFileFactoryOptions( build, parent, null, null, Object.assign({}, parent.fileFactoryOptions) ); build.fileFactory = build.fileFactoryOptions.fileFactory; parent.builds.push(build); parent.childInputpaths.push(inputpath); } // Find root build while (parent.parent) parent = parent.parent; parent.processFilesOptions.importBoilerplate = true; }; }
[ "function", "getBuildFactory", "(", "build", ")", "{", "return", "function", "createBuild", "(", "inputpath", ",", "outputname", ")", "{", "const", "input", "=", "path", ".", "relative", "(", "process", ".", "cwd", "(", ")", ",", "inputpath", ")", ";", "let", "parent", "=", "build", ";", "if", "(", "!", "parent", ".", "builds", ".", "some", "(", "build", "=>", "build", ".", "input", "==", "input", ")", ")", "{", "const", "outputpath", "=", "path", ".", "join", "(", "path", ".", "dirname", "(", "parent", ".", "outputpaths", "[", "0", "]", ")", ",", "outputname", ")", ";", "const", "buildConfig", "=", "{", "batch", ":", "parent", ".", "batch", ",", "boilerplate", ":", "false", ",", "bootstrap", ":", "false", ",", "browser", ":", "parent", ".", "browser", ",", "bundle", ":", "parent", ".", "bundle", ",", "fileCache", ":", "parent", ".", "fileCache", ",", "index", ":", "++", "numBuilds", ",", "input", ",", "inputpaths", ":", "[", "inputpath", "]", ",", "isAppServer", ":", "false", ",", "isDynamicBuild", ":", "true", ",", "label", ":", "''", ",", "level", ":", "parent", ".", "level", "+", "1", ",", "output", ":", "path", ".", "relative", "(", "process", ".", "cwd", "(", ")", ",", "path", ".", "dirname", "(", "outputpath", ")", ")", ",", "outputpaths", ":", "[", "outputpath", "]", ",", "parent", ",", "resolverCache", ":", "parent", ".", "resolverCache", ",", "runtimeOptions", ":", "parent", ".", "runtimeOptions", ",", "type", ":", "parent", ".", "type", ",", "watchOnly", ":", "parent", ".", "watchOnly", "}", ";", "const", "build", "=", "buildFactory", "(", "buildConfig", ")", ";", "build", ".", "fileFactoryOptions", "=", "getFileFactoryOptions", "(", "build", ",", "parent", ",", "null", ",", "null", ",", "Object", ".", "assign", "(", "{", "}", ",", "parent", ".", "fileFactoryOptions", ")", ")", ";", "build", ".", "fileFactory", "=", "build", ".", "fileFactoryOptions", ".", "fileFactory", ";", "parent", ".", "builds", ".", "push", "(", "build", ")", ";", "parent", ".", "childInputpaths", ".", "push", "(", "inputpath", ")", ";", "}", "while", "(", "parent", ".", "parent", ")", "parent", "=", "parent", ".", "parent", ";", "parent", ".", "processFilesOptions", ".", "importBoilerplate", "=", "true", ";", "}", ";", "}" ]
Retrieve build factory for 'build' @param {Object} build @returns {Function}
[ "Retrieve", "build", "factory", "for", "build" ]
c38afc2e6915743eb6cfcf5aba59a8699142c7a5
https://github.com/popeindustries/buddy/blob/c38afc2e6915743eb6cfcf5aba59a8699142c7a5/lib/config/buildParser.js#L196-L244
train
popeindustries/buddy
lib/config/buildParser.js
parseChildInputpaths
function parseChildInputpaths(build) { function parse(build) { let inputpaths = []; build.forEach(build => { inputpaths = inputpaths.concat(build.inputpaths, build.builds ? parse(build.builds) : []); }); return inputpaths; } build.childInputpaths = parse(build.builds); }
javascript
function parseChildInputpaths(build) { function parse(build) { let inputpaths = []; build.forEach(build => { inputpaths = inputpaths.concat(build.inputpaths, build.builds ? parse(build.builds) : []); }); return inputpaths; } build.childInputpaths = parse(build.builds); }
[ "function", "parseChildInputpaths", "(", "build", ")", "{", "function", "parse", "(", "build", ")", "{", "let", "inputpaths", "=", "[", "]", ";", "build", ".", "forEach", "(", "build", "=>", "{", "inputpaths", "=", "inputpaths", ".", "concat", "(", "build", ".", "inputpaths", ",", "build", ".", "builds", "?", "parse", "(", "build", ".", "builds", ")", ":", "[", "]", ")", ";", "}", ")", ";", "return", "inputpaths", ";", "}", "build", ".", "childInputpaths", "=", "parse", "(", "build", ".", "builds", ")", ";", "}" ]
Parse nested child input paths @param {Build} build
[ "Parse", "nested", "child", "input", "paths" ]
c38afc2e6915743eb6cfcf5aba59a8699142c7a5
https://github.com/popeindustries/buddy/blob/c38afc2e6915743eb6cfcf5aba59a8699142c7a5/lib/config/buildParser.js#L425-L437
train
popeindustries/buddy
lib/config/buildParser.js
isAppServer
function isAppServer(inputpaths, serverConfig) { // Test if 'p' is in 'dirs' function contains(dirs, p) { if (!Array.isArray(dirs)) dirs = [dirs]; return dirs.some(dir => { return indir(dir, p); }); } return serverConfig != undefined && serverConfig.file != undefined && contains(inputpaths, serverConfig.file); }
javascript
function isAppServer(inputpaths, serverConfig) { // Test if 'p' is in 'dirs' function contains(dirs, p) { if (!Array.isArray(dirs)) dirs = [dirs]; return dirs.some(dir => { return indir(dir, p); }); } return serverConfig != undefined && serverConfig.file != undefined && contains(inputpaths, serverConfig.file); }
[ "function", "isAppServer", "(", "inputpaths", ",", "serverConfig", ")", "{", "function", "contains", "(", "dirs", ",", "p", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "dirs", ")", ")", "dirs", "=", "[", "dirs", "]", ";", "return", "dirs", ".", "some", "(", "dir", "=>", "{", "return", "indir", "(", "dir", ",", "p", ")", ";", "}", ")", ";", "}", "return", "serverConfig", "!=", "undefined", "&&", "serverConfig", ".", "file", "!=", "undefined", "&&", "contains", "(", "inputpaths", ",", "serverConfig", ".", "file", ")", ";", "}" ]
Determine if 'inputpaths' contain server file @param {Array} inputpaths @param {Object} serverConfig @returns {Boolean}
[ "Determine", "if", "inputpaths", "contain", "server", "file" ]
c38afc2e6915743eb6cfcf5aba59a8699142c7a5
https://github.com/popeindustries/buddy/blob/c38afc2e6915743eb6cfcf5aba59a8699142c7a5/lib/config/buildParser.js#L445-L455
train
popeindustries/buddy
lib/config/buildParser.js
contains
function contains(dirs, p) { if (!Array.isArray(dirs)) dirs = [dirs]; return dirs.some(dir => { return indir(dir, p); }); }
javascript
function contains(dirs, p) { if (!Array.isArray(dirs)) dirs = [dirs]; return dirs.some(dir => { return indir(dir, p); }); }
[ "function", "contains", "(", "dirs", ",", "p", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "dirs", ")", ")", "dirs", "=", "[", "dirs", "]", ";", "return", "dirs", ".", "some", "(", "dir", "=>", "{", "return", "indir", "(", "dir", ",", "p", ")", ";", "}", ")", ";", "}" ]
Test if 'p' is in 'dirs'
[ "Test", "if", "p", "is", "in", "dirs" ]
c38afc2e6915743eb6cfcf5aba59a8699142c7a5
https://github.com/popeindustries/buddy/blob/c38afc2e6915743eb6cfcf5aba59a8699142c7a5/lib/config/buildParser.js#L447-L452
train
babel/acorn-to-esprima
src/convertTemplateType.js
createTemplateValue
function createTemplateValue(start, end) { var value = ""; while (start <= end) { if (tokens[start].value) { value += tokens[start].value; } else if (tokens[start].type !== tt.template) { value += tokens[start].type.label; } start++; } return value; }
javascript
function createTemplateValue(start, end) { var value = ""; while (start <= end) { if (tokens[start].value) { value += tokens[start].value; } else if (tokens[start].type !== tt.template) { value += tokens[start].type.label; } start++; } return value; }
[ "function", "createTemplateValue", "(", "start", ",", "end", ")", "{", "var", "value", "=", "\"\"", ";", "while", "(", "start", "<=", "end", ")", "{", "if", "(", "tokens", "[", "start", "]", ".", "value", ")", "{", "value", "+=", "tokens", "[", "start", "]", ".", "value", ";", "}", "else", "if", "(", "tokens", "[", "start", "]", ".", "type", "!==", "tt", ".", "template", ")", "{", "value", "+=", "tokens", "[", "start", "]", ".", "type", ".", "label", ";", "}", "start", "++", ";", "}", "return", "value", ";", "}" ]
append the values between start and end
[ "append", "the", "values", "between", "start", "and", "end" ]
b20845f56af9a02b4e7ae45a97a53702e480ec34
https://github.com/babel/acorn-to-esprima/blob/b20845f56af9a02b4e7ae45a97a53702e480ec34/src/convertTemplateType.js#L23-L34
train
babel/acorn-to-esprima
src/convertTemplateType.js
replaceWithTemplateType
function replaceWithTemplateType(start, end) { var templateToken = { type: "Template", value: createTemplateValue(start, end), start: tokens[start].start, end: tokens[end].end, loc: { start: tokens[start].loc.start, end: tokens[end].loc.end } }; // put new token in place of old tokens tokens.splice(start, end - start + 1, templateToken); }
javascript
function replaceWithTemplateType(start, end) { var templateToken = { type: "Template", value: createTemplateValue(start, end), start: tokens[start].start, end: tokens[end].end, loc: { start: tokens[start].loc.start, end: tokens[end].loc.end } }; // put new token in place of old tokens tokens.splice(start, end - start + 1, templateToken); }
[ "function", "replaceWithTemplateType", "(", "start", ",", "end", ")", "{", "var", "templateToken", "=", "{", "type", ":", "\"Template\"", ",", "value", ":", "createTemplateValue", "(", "start", ",", "end", ")", ",", "start", ":", "tokens", "[", "start", "]", ".", "start", ",", "end", ":", "tokens", "[", "end", "]", ".", "end", ",", "loc", ":", "{", "start", ":", "tokens", "[", "start", "]", ".", "loc", ".", "start", ",", "end", ":", "tokens", "[", "end", "]", ".", "loc", ".", "end", "}", "}", ";", "tokens", ".", "splice", "(", "start", ",", "end", "-", "start", "+", "1", ",", "templateToken", ")", ";", "}" ]
create Template token
[ "create", "Template", "token" ]
b20845f56af9a02b4e7ae45a97a53702e480ec34
https://github.com/babel/acorn-to-esprima/blob/b20845f56af9a02b4e7ae45a97a53702e480ec34/src/convertTemplateType.js#L37-L51
train
ArnaudBuchholz/gpf-js
lost+found/src/mimetype.js
_gpfBuildMimeTypeFromMappings
function _gpfBuildMimeTypeFromMappings (path, mappings) { _gpfObjectForEach(mappings, function (extensions, key) { var mimeType = path + key; if (0 === extensions) { _createMimeTypeExtensionMapping(mimeType, "." + key); } else if ("string" === typeof extensions) { extensions.split(",").forEach(function (extension) { _createMimeTypeExtensionMapping(mimeType, "." + extension); }); } else { // Assuming extensions is an object _gpfBuildMimeTypeFromMappings(mimeType + "/", extensions); } }); }
javascript
function _gpfBuildMimeTypeFromMappings (path, mappings) { _gpfObjectForEach(mappings, function (extensions, key) { var mimeType = path + key; if (0 === extensions) { _createMimeTypeExtensionMapping(mimeType, "." + key); } else if ("string" === typeof extensions) { extensions.split(",").forEach(function (extension) { _createMimeTypeExtensionMapping(mimeType, "." + extension); }); } else { // Assuming extensions is an object _gpfBuildMimeTypeFromMappings(mimeType + "/", extensions); } }); }
[ "function", "_gpfBuildMimeTypeFromMappings", "(", "path", ",", "mappings", ")", "{", "_gpfObjectForEach", "(", "mappings", ",", "function", "(", "extensions", ",", "key", ")", "{", "var", "mimeType", "=", "path", "+", "key", ";", "if", "(", "0", "===", "extensions", ")", "{", "_createMimeTypeExtensionMapping", "(", "mimeType", ",", "\".\"", "+", "key", ")", ";", "}", "else", "if", "(", "\"string\"", "===", "typeof", "extensions", ")", "{", "extensions", ".", "split", "(", "\",\"", ")", ".", "forEach", "(", "function", "(", "extension", ")", "{", "_createMimeTypeExtensionMapping", "(", "mimeType", ",", "\".\"", "+", "extension", ")", ";", "}", ")", ";", "}", "else", "{", "_gpfBuildMimeTypeFromMappings", "(", "mimeType", "+", "\"/\"", ",", "extensions", ")", ";", "}", "}", ")", ";", "}" ]
Recursive function that fills _gpfMimeTypesToExtension & _gpfMimeTypesFromExtension @param {String} path @param {Object} mappings @private
[ "Recursive", "function", "that", "fills", "_gpfMimeTypesToExtension", "&", "_gpfMimeTypesFromExtension" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/mimetype.js#L60-L75
train
popeindustries/buddy
lib/resolver/package.js
resolvePath
function resolvePath(filepath) { filepath = filepath.replace(RE_TRAILING, ''); const cwd = process.cwd(); const npmPackage = filepath.includes('node_modules'); // Find nearest node_modules directory if (npmPackage) { const parts = filepath.split(path.sep); let idx = parts.lastIndexOf('node_modules'); if (idx < parts.length - 1) idx += 2; // Handle scoped if (parts[idx - 1].charAt(0) == '@') idx++; const dir = parts.slice(0, idx).join(path.sep); // Installed packages must have manifest, otherwise continue if (exists(path.join(dir, 'package.json'))) return dir; } // Find nearest directory with node_modules subdirectory if (filepath.includes(cwd)) { let depth = maxFileSystemDepth; let dir = filepath; let parent = ''; while (true) { parent = path.dirname(dir); // Stop if we hit max file system depth or root // Convert to lowercase to fix problems on Windows if (!--depth || parent.toLowerCase() === dir.toLowerCase()) { break; } // Stop at nearest directory with node_modules or cwd if (dir == cwd || exists(path.resolve(dir, 'node_modules'))) return dir; // Walk dir = parent; } } // Return project directory if file isn't a project file return cwd; }
javascript
function resolvePath(filepath) { filepath = filepath.replace(RE_TRAILING, ''); const cwd = process.cwd(); const npmPackage = filepath.includes('node_modules'); // Find nearest node_modules directory if (npmPackage) { const parts = filepath.split(path.sep); let idx = parts.lastIndexOf('node_modules'); if (idx < parts.length - 1) idx += 2; // Handle scoped if (parts[idx - 1].charAt(0) == '@') idx++; const dir = parts.slice(0, idx).join(path.sep); // Installed packages must have manifest, otherwise continue if (exists(path.join(dir, 'package.json'))) return dir; } // Find nearest directory with node_modules subdirectory if (filepath.includes(cwd)) { let depth = maxFileSystemDepth; let dir = filepath; let parent = ''; while (true) { parent = path.dirname(dir); // Stop if we hit max file system depth or root // Convert to lowercase to fix problems on Windows if (!--depth || parent.toLowerCase() === dir.toLowerCase()) { break; } // Stop at nearest directory with node_modules or cwd if (dir == cwd || exists(path.resolve(dir, 'node_modules'))) return dir; // Walk dir = parent; } } // Return project directory if file isn't a project file return cwd; }
[ "function", "resolvePath", "(", "filepath", ")", "{", "filepath", "=", "filepath", ".", "replace", "(", "RE_TRAILING", ",", "''", ")", ";", "const", "cwd", "=", "process", ".", "cwd", "(", ")", ";", "const", "npmPackage", "=", "filepath", ".", "includes", "(", "'node_modules'", ")", ";", "if", "(", "npmPackage", ")", "{", "const", "parts", "=", "filepath", ".", "split", "(", "path", ".", "sep", ")", ";", "let", "idx", "=", "parts", ".", "lastIndexOf", "(", "'node_modules'", ")", ";", "if", "(", "idx", "<", "parts", ".", "length", "-", "1", ")", "idx", "+=", "2", ";", "if", "(", "parts", "[", "idx", "-", "1", "]", ".", "charAt", "(", "0", ")", "==", "'@'", ")", "idx", "++", ";", "const", "dir", "=", "parts", ".", "slice", "(", "0", ",", "idx", ")", ".", "join", "(", "path", ".", "sep", ")", ";", "if", "(", "exists", "(", "path", ".", "join", "(", "dir", ",", "'package.json'", ")", ")", ")", "return", "dir", ";", "}", "if", "(", "filepath", ".", "includes", "(", "cwd", ")", ")", "{", "let", "depth", "=", "maxFileSystemDepth", ";", "let", "dir", "=", "filepath", ";", "let", "parent", "=", "''", ";", "while", "(", "true", ")", "{", "parent", "=", "path", ".", "dirname", "(", "dir", ")", ";", "if", "(", "!", "--", "depth", "||", "parent", ".", "toLowerCase", "(", ")", "===", "dir", ".", "toLowerCase", "(", ")", ")", "{", "break", ";", "}", "if", "(", "dir", "==", "cwd", "||", "exists", "(", "path", ".", "resolve", "(", "dir", ",", "'node_modules'", ")", ")", ")", "return", "dir", ";", "dir", "=", "parent", ";", "}", "}", "return", "cwd", ";", "}" ]
Resolve package path from 'filepath' @param {String} filepath @returns {String}
[ "Resolve", "package", "path", "from", "filepath" ]
c38afc2e6915743eb6cfcf5aba59a8699142c7a5
https://github.com/popeindustries/buddy/blob/c38afc2e6915743eb6cfcf5aba59a8699142c7a5/lib/resolver/package.js#L124-L168
train
popeindustries/buddy
lib/resolver/package.js
resolveName
function resolveName(pkgpath) { pkgpath = pkgpath.replace(RE_TRAILING, ''); const cwd = process.cwd(); const parts = pkgpath.split(path.sep); const len = parts.length; let idx = 1; // Handle packages nested under root if (!pkgpath.includes('node_modules') && cwd != pkgpath) { // Increase by distance from root idx += path.relative(cwd, pkgpath).split(path.sep).length; // Handle scoped node_modules } else if (parts[len - 2].charAt(0) == '@') { idx = 2; } return parts.slice(len - idx).join(path.sep); }
javascript
function resolveName(pkgpath) { pkgpath = pkgpath.replace(RE_TRAILING, ''); const cwd = process.cwd(); const parts = pkgpath.split(path.sep); const len = parts.length; let idx = 1; // Handle packages nested under root if (!pkgpath.includes('node_modules') && cwd != pkgpath) { // Increase by distance from root idx += path.relative(cwd, pkgpath).split(path.sep).length; // Handle scoped node_modules } else if (parts[len - 2].charAt(0) == '@') { idx = 2; } return parts.slice(len - idx).join(path.sep); }
[ "function", "resolveName", "(", "pkgpath", ")", "{", "pkgpath", "=", "pkgpath", ".", "replace", "(", "RE_TRAILING", ",", "''", ")", ";", "const", "cwd", "=", "process", ".", "cwd", "(", ")", ";", "const", "parts", "=", "pkgpath", ".", "split", "(", "path", ".", "sep", ")", ";", "const", "len", "=", "parts", ".", "length", ";", "let", "idx", "=", "1", ";", "if", "(", "!", "pkgpath", ".", "includes", "(", "'node_modules'", ")", "&&", "cwd", "!=", "pkgpath", ")", "{", "idx", "+=", "path", ".", "relative", "(", "cwd", ",", "pkgpath", ")", ".", "split", "(", "path", ".", "sep", ")", ".", "length", ";", "}", "else", "if", "(", "parts", "[", "len", "-", "2", "]", ".", "charAt", "(", "0", ")", "==", "'@'", ")", "{", "idx", "=", "2", ";", "}", "return", "parts", ".", "slice", "(", "len", "-", "idx", ")", ".", "join", "(", "path", ".", "sep", ")", ";", "}" ]
Resolve package name from 'pkgpath' @param {String} pkgpath @returns {String}
[ "Resolve", "package", "name", "from", "pkgpath" ]
c38afc2e6915743eb6cfcf5aba59a8699142c7a5
https://github.com/popeindustries/buddy/blob/c38afc2e6915743eb6cfcf5aba59a8699142c7a5/lib/resolver/package.js#L175-L194
train
popeindustries/buddy
lib/resolver/package.js
resolveId
function resolveId(details, filepath) { let id = ''; if ('string' == typeof filepath) { // Only version if more than one package const version = details.id.includes(versionDelimiter) ? versionDelimiter + details.version : ''; const versioned = (id, stripExtension) => { // Strip extension if (stripExtension) id = id.replace(path.extname(id), ''); return (process.platform == 'win32' ? id.replace(/\\/g, '/') : id) + version; }; // Resolve aliases id = alias.resolve(filepath, details.aliases); // Ignore disabled (false) id = id || filepath; // Return if resolved id if (!isFilepath(id)) return versioned(id, false); // Resolve alias to id (also handles main => id) id = alias.resolveReverse(id, details.aliases); // Return if resolved id if (!isFilepath(id)) return versioned(id, false); // Resolve ids from project root if nested project package const pkgpath = details.isNestedProjectPackage ? process.cwd() : // Resolve ids from node_modules root if npm package details.isNpmPackage ? details.dirname : details.pkgpath; [...details.paths, pkgpath].some(sourcepath => { if (filepath.includes(sourcepath)) { id = path.relative(sourcepath, filepath); return true; } }); return versioned(id, true); } return id; }
javascript
function resolveId(details, filepath) { let id = ''; if ('string' == typeof filepath) { // Only version if more than one package const version = details.id.includes(versionDelimiter) ? versionDelimiter + details.version : ''; const versioned = (id, stripExtension) => { // Strip extension if (stripExtension) id = id.replace(path.extname(id), ''); return (process.platform == 'win32' ? id.replace(/\\/g, '/') : id) + version; }; // Resolve aliases id = alias.resolve(filepath, details.aliases); // Ignore disabled (false) id = id || filepath; // Return if resolved id if (!isFilepath(id)) return versioned(id, false); // Resolve alias to id (also handles main => id) id = alias.resolveReverse(id, details.aliases); // Return if resolved id if (!isFilepath(id)) return versioned(id, false); // Resolve ids from project root if nested project package const pkgpath = details.isNestedProjectPackage ? process.cwd() : // Resolve ids from node_modules root if npm package details.isNpmPackage ? details.dirname : details.pkgpath; [...details.paths, pkgpath].some(sourcepath => { if (filepath.includes(sourcepath)) { id = path.relative(sourcepath, filepath); return true; } }); return versioned(id, true); } return id; }
[ "function", "resolveId", "(", "details", ",", "filepath", ")", "{", "let", "id", "=", "''", ";", "if", "(", "'string'", "==", "typeof", "filepath", ")", "{", "const", "version", "=", "details", ".", "id", ".", "includes", "(", "versionDelimiter", ")", "?", "versionDelimiter", "+", "details", ".", "version", ":", "''", ";", "const", "versioned", "=", "(", "id", ",", "stripExtension", ")", "=>", "{", "if", "(", "stripExtension", ")", "id", "=", "id", ".", "replace", "(", "path", ".", "extname", "(", "id", ")", ",", "''", ")", ";", "return", "(", "process", ".", "platform", "==", "'win32'", "?", "id", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "'/'", ")", ":", "id", ")", "+", "version", ";", "}", ";", "id", "=", "alias", ".", "resolve", "(", "filepath", ",", "details", ".", "aliases", ")", ";", "id", "=", "id", "||", "filepath", ";", "if", "(", "!", "isFilepath", "(", "id", ")", ")", "return", "versioned", "(", "id", ",", "false", ")", ";", "id", "=", "alias", ".", "resolveReverse", "(", "id", ",", "details", ".", "aliases", ")", ";", "if", "(", "!", "isFilepath", "(", "id", ")", ")", "return", "versioned", "(", "id", ",", "false", ")", ";", "const", "pkgpath", "=", "details", ".", "isNestedProjectPackage", "?", "process", ".", "cwd", "(", ")", ":", "details", ".", "isNpmPackage", "?", "details", ".", "dirname", ":", "details", ".", "pkgpath", ";", "[", "...", "details", ".", "paths", ",", "pkgpath", "]", ".", "some", "(", "sourcepath", "=>", "{", "if", "(", "filepath", ".", "includes", "(", "sourcepath", ")", ")", "{", "id", "=", "path", ".", "relative", "(", "sourcepath", ",", "filepath", ")", ";", "return", "true", ";", "}", "}", ")", ";", "return", "versioned", "(", "id", ",", "true", ")", ";", "}", "return", "id", ";", "}" ]
Resolve id for 'filepath' @param {Object} details @param {String} filepath @returns {String}
[ "Resolve", "id", "for", "filepath" ]
c38afc2e6915743eb6cfcf5aba59a8699142c7a5
https://github.com/popeindustries/buddy/blob/c38afc2e6915743eb6cfcf5aba59a8699142c7a5/lib/resolver/package.js#L202-L242
train
popeindustries/buddy
lib/resolver/package.js
resolveNodeModules
function resolveNodeModules(pkgpath) { let dir = pkgpath; let dirs = []; let depth = maxFileSystemDepth; let parent; let nodeModulespath; while (true) { parent = path.dirname(dir); // Stop if we hit max file system depth or root // Convert to lowercase to fix problems on Windows if (!--depth || parent.toLowerCase() === dir.toLowerCase()) { break; } nodeModulespath = path.resolve(dir, 'node_modules'); if (exists(nodeModulespath)) dirs.push(nodeModulespath); // Walk dir = parent; } return dirs; }
javascript
function resolveNodeModules(pkgpath) { let dir = pkgpath; let dirs = []; let depth = maxFileSystemDepth; let parent; let nodeModulespath; while (true) { parent = path.dirname(dir); // Stop if we hit max file system depth or root // Convert to lowercase to fix problems on Windows if (!--depth || parent.toLowerCase() === dir.toLowerCase()) { break; } nodeModulespath = path.resolve(dir, 'node_modules'); if (exists(nodeModulespath)) dirs.push(nodeModulespath); // Walk dir = parent; } return dirs; }
[ "function", "resolveNodeModules", "(", "pkgpath", ")", "{", "let", "dir", "=", "pkgpath", ";", "let", "dirs", "=", "[", "]", ";", "let", "depth", "=", "maxFileSystemDepth", ";", "let", "parent", ";", "let", "nodeModulespath", ";", "while", "(", "true", ")", "{", "parent", "=", "path", ".", "dirname", "(", "dir", ")", ";", "if", "(", "!", "--", "depth", "||", "parent", ".", "toLowerCase", "(", ")", "===", "dir", ".", "toLowerCase", "(", ")", ")", "{", "break", ";", "}", "nodeModulespath", "=", "path", ".", "resolve", "(", "dir", ",", "'node_modules'", ")", ";", "if", "(", "exists", "(", "nodeModulespath", ")", ")", "dirs", ".", "push", "(", "nodeModulespath", ")", ";", "dir", "=", "parent", ";", "}", "return", "dirs", ";", "}" ]
Gather all node_modules directories reachable from 'pkgpath' @param {String} pkgpath @returns {Array}
[ "Gather", "all", "node_modules", "directories", "reachable", "from", "pkgpath" ]
c38afc2e6915743eb6cfcf5aba59a8699142c7a5
https://github.com/popeindustries/buddy/blob/c38afc2e6915743eb6cfcf5aba59a8699142c7a5/lib/resolver/package.js#L249-L273
train
ArnaudBuchholz/gpf-js
lost+found/src/interfaces_.js
_gpfIsImplementedBy
function _gpfIsImplementedBy (inspectedObject, interfaceDefinition) { var member, memberReference, memberValue, memberType; /* * IMPORTANT note: we test the object itself (i.e. own members and the prototype). * That's why the hasOwnProperty is skipped */ /*jslint forin:true*/ for (member in interfaceDefinition.prototype) { if ("constructor" === member) { // Object continue; } memberReference = interfaceDefinition.prototype[member]; memberValue = inspectedObject[member]; memberType = typeof memberValue; if (typeof memberReference !== memberType) { return false; } if ("function" === memberType && memberReference.length !== memberValue.length) { return false; } } return true; }
javascript
function _gpfIsImplementedBy (inspectedObject, interfaceDefinition) { var member, memberReference, memberValue, memberType; /* * IMPORTANT note: we test the object itself (i.e. own members and the prototype). * That's why the hasOwnProperty is skipped */ /*jslint forin:true*/ for (member in interfaceDefinition.prototype) { if ("constructor" === member) { // Object continue; } memberReference = interfaceDefinition.prototype[member]; memberValue = inspectedObject[member]; memberType = typeof memberValue; if (typeof memberReference !== memberType) { return false; } if ("function" === memberType && memberReference.length !== memberValue.length) { return false; } } return true; }
[ "function", "_gpfIsImplementedBy", "(", "inspectedObject", ",", "interfaceDefinition", ")", "{", "var", "member", ",", "memberReference", ",", "memberValue", ",", "memberType", ";", "for", "(", "member", "in", "interfaceDefinition", ".", "prototype", ")", "{", "if", "(", "\"constructor\"", "===", "member", ")", "{", "continue", ";", "}", "memberReference", "=", "interfaceDefinition", ".", "prototype", "[", "member", "]", ";", "memberValue", "=", "inspectedObject", "[", "member", "]", ";", "memberType", "=", "typeof", "memberValue", ";", "if", "(", "typeof", "memberReference", "!==", "memberType", ")", "{", "return", "false", ";", "}", "if", "(", "\"function\"", "===", "memberType", "&&", "memberReference", ".", "length", "!==", "memberValue", ".", "length", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Verify that the object implements the current interface @param {Object} inspectedObject Object (or class) to inspect @param {gpf.interfaces.Interface} interfaceDefinition Reference interface @return {Boolean} True if implemented
[ "Verify", "that", "the", "object", "implements", "the", "current", "interface" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/interfaces_.js#L31-L56
train
ArnaudBuchholz/gpf-js
lost+found/src/interfaces_.js
_wrapQueryInterface
function _wrapQueryInterface (orgQueryInterface) { return function (interfaceDefinition) { /*eslint-disable no-invalid-this*/ _gpfIgnore(interfaceDefinition); var result = _queryInterface.apply(this, arguments); if (null === result) { result = orgQueryInterface.apply(this, arguments); } return result; /*eslint-enable no-invalid-this*/ }; }
javascript
function _wrapQueryInterface (orgQueryInterface) { return function (interfaceDefinition) { /*eslint-disable no-invalid-this*/ _gpfIgnore(interfaceDefinition); var result = _queryInterface.apply(this, arguments); if (null === result) { result = orgQueryInterface.apply(this, arguments); } return result; /*eslint-enable no-invalid-this*/ }; }
[ "function", "_wrapQueryInterface", "(", "orgQueryInterface", ")", "{", "return", "function", "(", "interfaceDefinition", ")", "{", "_gpfIgnore", "(", "interfaceDefinition", ")", ";", "var", "result", "=", "_queryInterface", ".", "apply", "(", "this", ",", "arguments", ")", ";", "if", "(", "null", "===", "result", ")", "{", "result", "=", "orgQueryInterface", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", "return", "result", ";", "}", ";", "}" ]
Creates a wrapper calling _queryInterface and, if no result is built, the original one defined in the object prototype @param {Function} orgQueryInterface Interface to retreive @return {Function} Default queryInterface implementation @gpf:closure
[ "Creates", "a", "wrapper", "calling", "_queryInterface", "and", "if", "no", "result", "is", "built", "the", "original", "one", "defined", "in", "the", "object", "prototype" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/interfaces_.js#L238-L249
train
popeindustries/buddy
lib/build.js
generatePathString
function generatePathString(paths) { let pathString = ''; if (!paths || !paths.length) return pathString; if (paths.length > 1) { pathString = paths.map(pathItem => filepathName(pathItem)); // Trim long lists if (pathString.length > maxInputStringLength) { const remainder = pathString.length - maxInputStringLength; pathString = `${pathString .slice(0, maxInputStringLength) .join(', ')} ...and ${remainder} other${remainder > 1 ? 's' : ''}`; } else { pathString = pathString.join(', '); } } else { pathString = filepathName(paths[0]); } return pathString; }
javascript
function generatePathString(paths) { let pathString = ''; if (!paths || !paths.length) return pathString; if (paths.length > 1) { pathString = paths.map(pathItem => filepathName(pathItem)); // Trim long lists if (pathString.length > maxInputStringLength) { const remainder = pathString.length - maxInputStringLength; pathString = `${pathString .slice(0, maxInputStringLength) .join(', ')} ...and ${remainder} other${remainder > 1 ? 's' : ''}`; } else { pathString = pathString.join(', '); } } else { pathString = filepathName(paths[0]); } return pathString; }
[ "function", "generatePathString", "(", "paths", ")", "{", "let", "pathString", "=", "''", ";", "if", "(", "!", "paths", "||", "!", "paths", ".", "length", ")", "return", "pathString", ";", "if", "(", "paths", ".", "length", ">", "1", ")", "{", "pathString", "=", "paths", ".", "map", "(", "pathItem", "=>", "filepathName", "(", "pathItem", ")", ")", ";", "if", "(", "pathString", ".", "length", ">", "maxInputStringLength", ")", "{", "const", "remainder", "=", "pathString", ".", "length", "-", "maxInputStringLength", ";", "pathString", "=", "`", "${", "pathString", ".", "slice", "(", "0", ",", "maxInputStringLength", ")", ".", "join", "(", "', '", ")", "}", "${", "remainder", "}", "${", "remainder", ">", "1", "?", "'s'", ":", "''", "}", "`", ";", "}", "else", "{", "pathString", "=", "pathString", ".", "join", "(", "', '", ")", ";", "}", "}", "else", "{", "pathString", "=", "filepathName", "(", "paths", "[", "0", "]", ")", ";", "}", "return", "pathString", ";", "}" ]
Generate path string for 'paths' @param {Array} paths @returns {String}
[ "Generate", "path", "string", "for", "paths" ]
c38afc2e6915743eb6cfcf5aba59a8699142c7a5
https://github.com/popeindustries/buddy/blob/c38afc2e6915743eb6cfcf5aba59a8699142c7a5/lib/build.js#L544-L566
train
popeindustries/buddy
lib/config/buildPlugins.js
loadPluginsForType
function loadPluginsForType(type, options, version, compress) { // Start with default if available let plugins = type in allPlugins && allPlugins[type].default ? allPlugins[type].default.slice() : []; // Add plugins based on version presets plugins = version.reduce((plugins, preset) => { let presetPlugins; if ('string' == typeof preset) { preset = preset.toLowerCase(); // Ignore generic if (RE_GENERIC_VERSION.test(preset)) return plugins; // Skip if babel version and type is postcss if (type == 'postcss' && preset in allPlugins.babel) return plugins; presetPlugins = allPlugins[type][preset]; // Try and parse with browserslist if no match if (!presetPlugins) preset = { browsers: [preset] }; } // Handle object ({ chrome: 5 }, { browsers: ['last 3'] }) if (!presetPlugins && 'string' != typeof preset) { const key = Object.keys(preset)[0]; const value = preset[key]; if (key == 'browsers' && Array.isArray(value)) { if (type == 'postcss') { // Add Autoprefixer and pass-through presetPlugins = [['autoprefixer', preset]]; } else if (type == 'babel') { try { // Add Babel plugins based on Autoprefixer-style config presetPlugins = resolvePluginsForBrowsers( browserslist(value).map(browser => { const [name, version] = browser.split(' '); return { [name]: version }; }) ); } catch (err) { /* invalid browserslist value */ } } } else { // See if concated key+value exists already presetPlugins = allPlugins[type][(key + value).toLowerCase()] || (type == 'babel' && resolvePluginsForBrowsers(preset)); } } if (!presetPlugins) warn(`unable to resolve plugins for ${strong(preset)} version`, 1); return unique(plugins.concat(presetPlugins || [])); }, plugins); // Add compression plugins if (compress && type in allPlugins && allPlugins[type].compress) { plugins.push(...allPlugins[type].compress); } // Add plugins defined in build (add before current plugins, but preserve order) for (let i = options.plugins.length - 1; i >= 0; i--) { const plugin = options.plugins[i]; const pluginName = Array.isArray(plugin) ? plugin[0] : plugin; let exists = false; plugins.some((existingPlugin, idx) => { const existingPluginName = Array.isArray(existingPlugin) ? existingPlugin[0] : existingPlugin; // Overwrite if exists if (pluginName == existingPluginName) { plugins[idx] = plugin; exists = true; } return exists; }); if (!exists) plugins.unshift(plugin); } options.plugins = plugins; // Store hash of plugin names options.fingerprint = md5(JSON.stringify(options)); // Install missing dependencies dependencies.install(extractDependencyIds(options)); resolveDependencyPaths(options); }
javascript
function loadPluginsForType(type, options, version, compress) { // Start with default if available let plugins = type in allPlugins && allPlugins[type].default ? allPlugins[type].default.slice() : []; // Add plugins based on version presets plugins = version.reduce((plugins, preset) => { let presetPlugins; if ('string' == typeof preset) { preset = preset.toLowerCase(); // Ignore generic if (RE_GENERIC_VERSION.test(preset)) return plugins; // Skip if babel version and type is postcss if (type == 'postcss' && preset in allPlugins.babel) return plugins; presetPlugins = allPlugins[type][preset]; // Try and parse with browserslist if no match if (!presetPlugins) preset = { browsers: [preset] }; } // Handle object ({ chrome: 5 }, { browsers: ['last 3'] }) if (!presetPlugins && 'string' != typeof preset) { const key = Object.keys(preset)[0]; const value = preset[key]; if (key == 'browsers' && Array.isArray(value)) { if (type == 'postcss') { // Add Autoprefixer and pass-through presetPlugins = [['autoprefixer', preset]]; } else if (type == 'babel') { try { // Add Babel plugins based on Autoprefixer-style config presetPlugins = resolvePluginsForBrowsers( browserslist(value).map(browser => { const [name, version] = browser.split(' '); return { [name]: version }; }) ); } catch (err) { /* invalid browserslist value */ } } } else { // See if concated key+value exists already presetPlugins = allPlugins[type][(key + value).toLowerCase()] || (type == 'babel' && resolvePluginsForBrowsers(preset)); } } if (!presetPlugins) warn(`unable to resolve plugins for ${strong(preset)} version`, 1); return unique(plugins.concat(presetPlugins || [])); }, plugins); // Add compression plugins if (compress && type in allPlugins && allPlugins[type].compress) { plugins.push(...allPlugins[type].compress); } // Add plugins defined in build (add before current plugins, but preserve order) for (let i = options.plugins.length - 1; i >= 0; i--) { const plugin = options.plugins[i]; const pluginName = Array.isArray(plugin) ? plugin[0] : plugin; let exists = false; plugins.some((existingPlugin, idx) => { const existingPluginName = Array.isArray(existingPlugin) ? existingPlugin[0] : existingPlugin; // Overwrite if exists if (pluginName == existingPluginName) { plugins[idx] = plugin; exists = true; } return exists; }); if (!exists) plugins.unshift(plugin); } options.plugins = plugins; // Store hash of plugin names options.fingerprint = md5(JSON.stringify(options)); // Install missing dependencies dependencies.install(extractDependencyIds(options)); resolveDependencyPaths(options); }
[ "function", "loadPluginsForType", "(", "type", ",", "options", ",", "version", ",", "compress", ")", "{", "let", "plugins", "=", "type", "in", "allPlugins", "&&", "allPlugins", "[", "type", "]", ".", "default", "?", "allPlugins", "[", "type", "]", ".", "default", ".", "slice", "(", ")", ":", "[", "]", ";", "plugins", "=", "version", ".", "reduce", "(", "(", "plugins", ",", "preset", ")", "=>", "{", "let", "presetPlugins", ";", "if", "(", "'string'", "==", "typeof", "preset", ")", "{", "preset", "=", "preset", ".", "toLowerCase", "(", ")", ";", "if", "(", "RE_GENERIC_VERSION", ".", "test", "(", "preset", ")", ")", "return", "plugins", ";", "if", "(", "type", "==", "'postcss'", "&&", "preset", "in", "allPlugins", ".", "babel", ")", "return", "plugins", ";", "presetPlugins", "=", "allPlugins", "[", "type", "]", "[", "preset", "]", ";", "if", "(", "!", "presetPlugins", ")", "preset", "=", "{", "browsers", ":", "[", "preset", "]", "}", ";", "}", "if", "(", "!", "presetPlugins", "&&", "'string'", "!=", "typeof", "preset", ")", "{", "const", "key", "=", "Object", ".", "keys", "(", "preset", ")", "[", "0", "]", ";", "const", "value", "=", "preset", "[", "key", "]", ";", "if", "(", "key", "==", "'browsers'", "&&", "Array", ".", "isArray", "(", "value", ")", ")", "{", "if", "(", "type", "==", "'postcss'", ")", "{", "presetPlugins", "=", "[", "[", "'autoprefixer'", ",", "preset", "]", "]", ";", "}", "else", "if", "(", "type", "==", "'babel'", ")", "{", "try", "{", "presetPlugins", "=", "resolvePluginsForBrowsers", "(", "browserslist", "(", "value", ")", ".", "map", "(", "browser", "=>", "{", "const", "[", "name", ",", "version", "]", "=", "browser", ".", "split", "(", "' '", ")", ";", "return", "{", "[", "name", "]", ":", "version", "}", ";", "}", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "}", "}", "}", "else", "{", "presetPlugins", "=", "allPlugins", "[", "type", "]", "[", "(", "key", "+", "value", ")", ".", "toLowerCase", "(", ")", "]", "||", "(", "type", "==", "'babel'", "&&", "resolvePluginsForBrowsers", "(", "preset", ")", ")", ";", "}", "}", "if", "(", "!", "presetPlugins", ")", "warn", "(", "`", "${", "strong", "(", "preset", ")", "}", "`", ",", "1", ")", ";", "return", "unique", "(", "plugins", ".", "concat", "(", "presetPlugins", "||", "[", "]", ")", ")", ";", "}", ",", "plugins", ")", ";", "if", "(", "compress", "&&", "type", "in", "allPlugins", "&&", "allPlugins", "[", "type", "]", ".", "compress", ")", "{", "plugins", ".", "push", "(", "...", "allPlugins", "[", "type", "]", ".", "compress", ")", ";", "}", "for", "(", "let", "i", "=", "options", ".", "plugins", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "const", "plugin", "=", "options", ".", "plugins", "[", "i", "]", ";", "const", "pluginName", "=", "Array", ".", "isArray", "(", "plugin", ")", "?", "plugin", "[", "0", "]", ":", "plugin", ";", "let", "exists", "=", "false", ";", "plugins", ".", "some", "(", "(", "existingPlugin", ",", "idx", ")", "=>", "{", "const", "existingPluginName", "=", "Array", ".", "isArray", "(", "existingPlugin", ")", "?", "existingPlugin", "[", "0", "]", ":", "existingPlugin", ";", "if", "(", "pluginName", "==", "existingPluginName", ")", "{", "plugins", "[", "idx", "]", "=", "plugin", ";", "exists", "=", "true", ";", "}", "return", "exists", ";", "}", ")", ";", "if", "(", "!", "exists", ")", "plugins", ".", "unshift", "(", "plugin", ")", ";", "}", "options", ".", "plugins", "=", "plugins", ";", "options", ".", "fingerprint", "=", "md5", "(", "JSON", ".", "stringify", "(", "options", ")", ")", ";", "dependencies", ".", "install", "(", "extractDependencyIds", "(", "options", ")", ")", ";", "resolveDependencyPaths", "(", "options", ")", ";", "}" ]
Load plugins for 'type' @param {String} type @param {Object} options @param {Array} version @param {Boolean} compress
[ "Load", "plugins", "for", "type" ]
c38afc2e6915743eb6cfcf5aba59a8699142c7a5
https://github.com/popeindustries/buddy/blob/c38afc2e6915743eb6cfcf5aba59a8699142c7a5/lib/config/buildPlugins.js#L154-L240
train
popeindustries/buddy
lib/config/buildPlugins.js
extractDependencyIds
function extractDependencyIds(options) { const dependencies = []; function extract(items) { // Invalid if not Array if (Array.isArray(items)) { items.reduce((dependencies, item) => { // Items can be Array with depedency as first param const dep = Array.isArray(item) ? item[0] : item; // Only gather string references, not functions/modules if ('string' == typeof dep) dependencies.push(dep); return dependencies; }, dependencies); } } if (options.plugins) extract(options.plugins); if (options.presets) extract(options.presets); return dependencies; }
javascript
function extractDependencyIds(options) { const dependencies = []; function extract(items) { // Invalid if not Array if (Array.isArray(items)) { items.reduce((dependencies, item) => { // Items can be Array with depedency as first param const dep = Array.isArray(item) ? item[0] : item; // Only gather string references, not functions/modules if ('string' == typeof dep) dependencies.push(dep); return dependencies; }, dependencies); } } if (options.plugins) extract(options.plugins); if (options.presets) extract(options.presets); return dependencies; }
[ "function", "extractDependencyIds", "(", "options", ")", "{", "const", "dependencies", "=", "[", "]", ";", "function", "extract", "(", "items", ")", "{", "if", "(", "Array", ".", "isArray", "(", "items", ")", ")", "{", "items", ".", "reduce", "(", "(", "dependencies", ",", "item", ")", "=>", "{", "const", "dep", "=", "Array", ".", "isArray", "(", "item", ")", "?", "item", "[", "0", "]", ":", "item", ";", "if", "(", "'string'", "==", "typeof", "dep", ")", "dependencies", ".", "push", "(", "dep", ")", ";", "return", "dependencies", ";", "}", ",", "dependencies", ")", ";", "}", "}", "if", "(", "options", ".", "plugins", ")", "extract", "(", "options", ".", "plugins", ")", ";", "if", "(", "options", ".", "presets", ")", "extract", "(", "options", ".", "presets", ")", ";", "return", "dependencies", ";", "}" ]
Extract dependency ids from 'options' @param {Object} options @returns {Array}
[ "Extract", "dependency", "ids", "from", "options" ]
c38afc2e6915743eb6cfcf5aba59a8699142c7a5
https://github.com/popeindustries/buddy/blob/c38afc2e6915743eb6cfcf5aba59a8699142c7a5/lib/config/buildPlugins.js#L247-L268
train
popeindustries/buddy
lib/config/buildPlugins.js
resolveDependencyPaths
function resolveDependencyPaths(options) { function init(items) { // Invalid if not Array if (Array.isArray(items)) { items.forEach((item, idx, items) => { const isArray = Array.isArray(item); const id = isArray ? item[0] : item; // Ignore already resolved if ('string' == typeof id) { const filepath = dependencies.find(id); if (!filepath) return warn(`unable to load plugin ${strong(id)}`, 1); if (isArray) { item[0] = require(filepath); } else { items[idx] = require(filepath); } } }); } } if (options.plugins) init(options.plugins); if (options.presets) init(options.presets); }
javascript
function resolveDependencyPaths(options) { function init(items) { // Invalid if not Array if (Array.isArray(items)) { items.forEach((item, idx, items) => { const isArray = Array.isArray(item); const id = isArray ? item[0] : item; // Ignore already resolved if ('string' == typeof id) { const filepath = dependencies.find(id); if (!filepath) return warn(`unable to load plugin ${strong(id)}`, 1); if (isArray) { item[0] = require(filepath); } else { items[idx] = require(filepath); } } }); } } if (options.plugins) init(options.plugins); if (options.presets) init(options.presets); }
[ "function", "resolveDependencyPaths", "(", "options", ")", "{", "function", "init", "(", "items", ")", "{", "if", "(", "Array", ".", "isArray", "(", "items", ")", ")", "{", "items", ".", "forEach", "(", "(", "item", ",", "idx", ",", "items", ")", "=>", "{", "const", "isArray", "=", "Array", ".", "isArray", "(", "item", ")", ";", "const", "id", "=", "isArray", "?", "item", "[", "0", "]", ":", "item", ";", "if", "(", "'string'", "==", "typeof", "id", ")", "{", "const", "filepath", "=", "dependencies", ".", "find", "(", "id", ")", ";", "if", "(", "!", "filepath", ")", "return", "warn", "(", "`", "${", "strong", "(", "id", ")", "}", "`", ",", "1", ")", ";", "if", "(", "isArray", ")", "{", "item", "[", "0", "]", "=", "require", "(", "filepath", ")", ";", "}", "else", "{", "items", "[", "idx", "]", "=", "require", "(", "filepath", ")", ";", "}", "}", "}", ")", ";", "}", "}", "if", "(", "options", ".", "plugins", ")", "init", "(", "options", ".", "plugins", ")", ";", "if", "(", "options", ".", "presets", ")", "init", "(", "options", ".", "presets", ")", ";", "}" ]
Resolve dependency paths in 'options' to modules @param {Object} options
[ "Resolve", "dependency", "paths", "in", "options", "to", "modules" ]
c38afc2e6915743eb6cfcf5aba59a8699142c7a5
https://github.com/popeindustries/buddy/blob/c38afc2e6915743eb6cfcf5aba59a8699142c7a5/lib/config/buildPlugins.js#L274-L300
train
popeindustries/buddy
lib/config/buildPlugins.js
resolvePluginsForBrowsers
function resolvePluginsForBrowsers(browsers) { const plugins = []; if (!Array.isArray(browsers)) browsers = [browsers]; browsers.forEach(browser => { const name = Object.keys(browser)[0]; const version = browser[name]; for (const pluginName in babelPluginsByEnvironmentVersion) { if ( !babelPluginsByEnvironmentVersion[pluginName][name] || babelPluginsByEnvironmentVersion[pluginName][name] > version ) { plugins.push(`babel-plugin-${pluginName}`); } } }); return plugins; }
javascript
function resolvePluginsForBrowsers(browsers) { const plugins = []; if (!Array.isArray(browsers)) browsers = [browsers]; browsers.forEach(browser => { const name = Object.keys(browser)[0]; const version = browser[name]; for (const pluginName in babelPluginsByEnvironmentVersion) { if ( !babelPluginsByEnvironmentVersion[pluginName][name] || babelPluginsByEnvironmentVersion[pluginName][name] > version ) { plugins.push(`babel-plugin-${pluginName}`); } } }); return plugins; }
[ "function", "resolvePluginsForBrowsers", "(", "browsers", ")", "{", "const", "plugins", "=", "[", "]", ";", "if", "(", "!", "Array", ".", "isArray", "(", "browsers", ")", ")", "browsers", "=", "[", "browsers", "]", ";", "browsers", ".", "forEach", "(", "browser", "=>", "{", "const", "name", "=", "Object", ".", "keys", "(", "browser", ")", "[", "0", "]", ";", "const", "version", "=", "browser", "[", "name", "]", ";", "for", "(", "const", "pluginName", "in", "babelPluginsByEnvironmentVersion", ")", "{", "if", "(", "!", "babelPluginsByEnvironmentVersion", "[", "pluginName", "]", "[", "name", "]", "||", "babelPluginsByEnvironmentVersion", "[", "pluginName", "]", "[", "name", "]", ">", "version", ")", "{", "plugins", ".", "push", "(", "`", "${", "pluginName", "}", "`", ")", ";", "}", "}", "}", ")", ";", "return", "plugins", ";", "}" ]
Resolve Babel plugins for all 'browsers' @param {Array} browsers @returns {Array}
[ "Resolve", "Babel", "plugins", "for", "all", "browsers" ]
c38afc2e6915743eb6cfcf5aba59a8699142c7a5
https://github.com/popeindustries/buddy/blob/c38afc2e6915743eb6cfcf5aba59a8699142c7a5/lib/config/buildPlugins.js#L307-L327
train
zetapush/zetapush
packages/cometd/lib/CometD.js
_send
function _send(sync, messages, metaConnect, extraPath) { // We must be sure that the messages have a clientId. // This is not guaranteed since the handshake may take time to return // (and hence the clientId is not known yet) and the application // may create other messages. for (var i = 0; i < messages.length; ++i) { var message = messages[i]; var messageId = message.id; if (_clientId) { message.clientId = _clientId; } message = _applyOutgoingExtensions(message); if (message !== undefined && message !== null) { // Extensions may have modified the message id, but we need to own it. message.id = messageId; messages[i] = message; } else { delete _callbacks[messageId]; messages.splice(i--, 1); } } if (messages.length === 0) { return; } var url = _cometd.getURL(); if (_config.appendMessageTypeToURL) { // If url does not end with '/', then append it if (!url.match(/\/$/)) { url = url + '/'; } if (extraPath) { url = url + extraPath; } } var envelope = { url: url, sync: sync, messages: messages, onSuccess: function(rcvdMessages) { try { _handleMessages.call(_cometd, rcvdMessages); } catch (x) { _cometd._info('Exception during handling of messages', x); } }, onFailure: function(conduit, messages, failure) { try { var transport = _cometd.getTransport(); failure.connectionType = transport ? transport.getType() : "unknown"; _handleFailure.call(_cometd, conduit, messages, failure); } catch (x) { _cometd._info('Exception during handling of failure', x); } } }; _cometd._debug('Send', envelope); _transport.send(envelope, metaConnect); }
javascript
function _send(sync, messages, metaConnect, extraPath) { // We must be sure that the messages have a clientId. // This is not guaranteed since the handshake may take time to return // (and hence the clientId is not known yet) and the application // may create other messages. for (var i = 0; i < messages.length; ++i) { var message = messages[i]; var messageId = message.id; if (_clientId) { message.clientId = _clientId; } message = _applyOutgoingExtensions(message); if (message !== undefined && message !== null) { // Extensions may have modified the message id, but we need to own it. message.id = messageId; messages[i] = message; } else { delete _callbacks[messageId]; messages.splice(i--, 1); } } if (messages.length === 0) { return; } var url = _cometd.getURL(); if (_config.appendMessageTypeToURL) { // If url does not end with '/', then append it if (!url.match(/\/$/)) { url = url + '/'; } if (extraPath) { url = url + extraPath; } } var envelope = { url: url, sync: sync, messages: messages, onSuccess: function(rcvdMessages) { try { _handleMessages.call(_cometd, rcvdMessages); } catch (x) { _cometd._info('Exception during handling of messages', x); } }, onFailure: function(conduit, messages, failure) { try { var transport = _cometd.getTransport(); failure.connectionType = transport ? transport.getType() : "unknown"; _handleFailure.call(_cometd, conduit, messages, failure); } catch (x) { _cometd._info('Exception during handling of failure', x); } } }; _cometd._debug('Send', envelope); _transport.send(envelope, metaConnect); }
[ "function", "_send", "(", "sync", ",", "messages", ",", "metaConnect", ",", "extraPath", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "messages", ".", "length", ";", "++", "i", ")", "{", "var", "message", "=", "messages", "[", "i", "]", ";", "var", "messageId", "=", "message", ".", "id", ";", "if", "(", "_clientId", ")", "{", "message", ".", "clientId", "=", "_clientId", ";", "}", "message", "=", "_applyOutgoingExtensions", "(", "message", ")", ";", "if", "(", "message", "!==", "undefined", "&&", "message", "!==", "null", ")", "{", "message", ".", "id", "=", "messageId", ";", "messages", "[", "i", "]", "=", "message", ";", "}", "else", "{", "delete", "_callbacks", "[", "messageId", "]", ";", "messages", ".", "splice", "(", "i", "--", ",", "1", ")", ";", "}", "}", "if", "(", "messages", ".", "length", "===", "0", ")", "{", "return", ";", "}", "var", "url", "=", "_cometd", ".", "getURL", "(", ")", ";", "if", "(", "_config", ".", "appendMessageTypeToURL", ")", "{", "if", "(", "!", "url", ".", "match", "(", "/", "\\/$", "/", ")", ")", "{", "url", "=", "url", "+", "'/'", ";", "}", "if", "(", "extraPath", ")", "{", "url", "=", "url", "+", "extraPath", ";", "}", "}", "var", "envelope", "=", "{", "url", ":", "url", ",", "sync", ":", "sync", ",", "messages", ":", "messages", ",", "onSuccess", ":", "function", "(", "rcvdMessages", ")", "{", "try", "{", "_handleMessages", ".", "call", "(", "_cometd", ",", "rcvdMessages", ")", ";", "}", "catch", "(", "x", ")", "{", "_cometd", ".", "_info", "(", "'Exception during handling of messages'", ",", "x", ")", ";", "}", "}", ",", "onFailure", ":", "function", "(", "conduit", ",", "messages", ",", "failure", ")", "{", "try", "{", "var", "transport", "=", "_cometd", ".", "getTransport", "(", ")", ";", "failure", ".", "connectionType", "=", "transport", "?", "transport", ".", "getType", "(", ")", ":", "\"unknown\"", ";", "_handleFailure", ".", "call", "(", "_cometd", ",", "conduit", ",", "messages", ",", "failure", ")", ";", "}", "catch", "(", "x", ")", "{", "_cometd", ".", "_info", "(", "'Exception during handling of failure'", ",", "x", ")", ";", "}", "}", "}", ";", "_cometd", ".", "_debug", "(", "'Send'", ",", "envelope", ")", ";", "_transport", ".", "send", "(", "envelope", ",", "metaConnect", ")", ";", "}" ]
Delivers the messages to the CometD server @param sync whether the send is synchronous @param messages the array of messages to send @param metaConnect true if this send is on /meta/connect @param extraPath an extra path to append to the Bayeux server URL
[ "Delivers", "the", "messages", "to", "the", "CometD", "server" ]
ad3383b8e332050eaecd55be9bdff6cf76db699e
https://github.com/zetapush/zetapush/blob/ad3383b8e332050eaecd55be9bdff6cf76db699e/packages/cometd/lib/CometD.js#L420-L482
train
zetapush/zetapush
packages/cometd/lib/CometD.js
_endBatch
function _endBatch() { --_batch; _cometd._debug('Ending batch, depth', _batch); if (_batch < 0) { throw 'Calls to startBatch() and endBatch() are not paired'; } if (_batch === 0 && !_isDisconnected() && !_internalBatch) { _flushBatch(); } }
javascript
function _endBatch() { --_batch; _cometd._debug('Ending batch, depth', _batch); if (_batch < 0) { throw 'Calls to startBatch() and endBatch() are not paired'; } if (_batch === 0 && !_isDisconnected() && !_internalBatch) { _flushBatch(); } }
[ "function", "_endBatch", "(", ")", "{", "--", "_batch", ";", "_cometd", ".", "_debug", "(", "'Ending batch, depth'", ",", "_batch", ")", ";", "if", "(", "_batch", "<", "0", ")", "{", "throw", "'Calls to startBatch() and endBatch() are not paired'", ";", "}", "if", "(", "_batch", "===", "0", "&&", "!", "_isDisconnected", "(", ")", "&&", "!", "_internalBatch", ")", "{", "_flushBatch", "(", ")", ";", "}", "}" ]
Ends the batch of messages to be sent in a single request, optionally sending messages present in the message queue depending on the given argument. @see #_startBatch()
[ "Ends", "the", "batch", "of", "messages", "to", "be", "sent", "in", "a", "single", "request", "optionally", "sending", "messages", "present", "in", "the", "message", "queue", "depending", "on", "the", "given", "argument", "." ]
ad3383b8e332050eaecd55be9bdff6cf76db699e
https://github.com/zetapush/zetapush/blob/ad3383b8e332050eaecd55be9bdff6cf76db699e/packages/cometd/lib/CometD.js#L535-L545
train
zetapush/zetapush
packages/cometd/lib/CometD.js
_connect
function _connect() { if (!_isDisconnected()) { var bayeuxMessage = { id: _nextMessageId(), channel: '/meta/connect', connectionType: _transport.getType() }; // In case of reload or temporary loss of connection // we want the next successful connect to return immediately // instead of being held by the server, so that connect listeners // can be notified that the connection has been re-established if (!_connected) { bayeuxMessage.advice = { timeout: 0 }; } _setStatus('connecting'); _cometd._debug('Connect sent', bayeuxMessage); _send(false, [bayeuxMessage], true, 'connect'); _setStatus('connected'); } }
javascript
function _connect() { if (!_isDisconnected()) { var bayeuxMessage = { id: _nextMessageId(), channel: '/meta/connect', connectionType: _transport.getType() }; // In case of reload or temporary loss of connection // we want the next successful connect to return immediately // instead of being held by the server, so that connect listeners // can be notified that the connection has been re-established if (!_connected) { bayeuxMessage.advice = { timeout: 0 }; } _setStatus('connecting'); _cometd._debug('Connect sent', bayeuxMessage); _send(false, [bayeuxMessage], true, 'connect'); _setStatus('connected'); } }
[ "function", "_connect", "(", ")", "{", "if", "(", "!", "_isDisconnected", "(", ")", ")", "{", "var", "bayeuxMessage", "=", "{", "id", ":", "_nextMessageId", "(", ")", ",", "channel", ":", "'/meta/connect'", ",", "connectionType", ":", "_transport", ".", "getType", "(", ")", "}", ";", "if", "(", "!", "_connected", ")", "{", "bayeuxMessage", ".", "advice", "=", "{", "timeout", ":", "0", "}", ";", "}", "_setStatus", "(", "'connecting'", ")", ";", "_cometd", ".", "_debug", "(", "'Connect sent'", ",", "bayeuxMessage", ")", ";", "_send", "(", "false", ",", "[", "bayeuxMessage", "]", ",", "true", ",", "'connect'", ")", ";", "_setStatus", "(", "'connected'", ")", ";", "}", "}" ]
Sends the connect message
[ "Sends", "the", "connect", "message" ]
ad3383b8e332050eaecd55be9bdff6cf76db699e
https://github.com/zetapush/zetapush/blob/ad3383b8e332050eaecd55be9bdff6cf76db699e/packages/cometd/lib/CometD.js#L550-L571
train
zetapush/zetapush
packages/cometd/lib/CometD.js
_handshake
function _handshake(handshakeProps, handshakeCallback) { if (_isFunction(handshakeProps)) { handshakeCallback = handshakeProps; handshakeProps = undefined; } _clientId = null; _clearSubscriptions(); // Reset the transports if we're not retrying the handshake if (_isDisconnected()) { _transports.reset(true); _updateAdvice(_config.advice); } else { // We are retrying the handshake, either because another handshake failed // and we're backing off, or because the server timed us out and asks us to // re-handshake: in both cases, make sure that if the handshake succeeds // the next action is a connect. _updateAdvice(_cometd._mixin(false, _advice, {reconnect: 'retry'})); } _batch = 0; // Mark the start of an internal batch. // This is needed because handshake and connect are async. // It may happen that the application calls init() then subscribe() // and the subscribe message is sent before the connect message, if // the subscribe message is not held until the connect message is sent. // So here we start a batch to hold temporarily any message until // the connection is fully established. _internalBatch = true; // Save the properties provided by the user, so that // we can reuse them during automatic re-handshake _handshakeProps = handshakeProps; _handshakeCallback = handshakeCallback; var version = '1.0'; // Figure out the transports to send to the server var url = _cometd.getURL(); var transportTypes = _transports.findTransportTypes(version, _crossDomain, url); var bayeuxMessage = { id: _nextMessageId(), version: version, minimumVersion: version, channel: '/meta/handshake', supportedConnectionTypes: transportTypes, advice: { timeout: _advice.timeout, interval: _advice.interval } }; // Do not allow the user to override important fields. var message = _cometd._mixin(false, {}, _handshakeProps, bayeuxMessage); // Save the callback. _cometd._putCallback(message.id, handshakeCallback); // Pick up the first available transport as initial transport // since we don't know if the server supports it if (!_transport) { _transport = _transports.negotiateTransport(transportTypes, version, _crossDomain, url); if (!_transport) { var failure = 'Could not find initial transport among: ' + _transports.getTransportTypes(); _cometd._warn(failure); throw failure; } } _cometd._debug('Initial transport is', _transport.getType()); // We started a batch to hold the application messages, // so here we must bypass it and send immediately. _setStatus('handshaking'); _cometd._debug('Handshake sent', message); _send(false, [message], false, 'handshake'); }
javascript
function _handshake(handshakeProps, handshakeCallback) { if (_isFunction(handshakeProps)) { handshakeCallback = handshakeProps; handshakeProps = undefined; } _clientId = null; _clearSubscriptions(); // Reset the transports if we're not retrying the handshake if (_isDisconnected()) { _transports.reset(true); _updateAdvice(_config.advice); } else { // We are retrying the handshake, either because another handshake failed // and we're backing off, or because the server timed us out and asks us to // re-handshake: in both cases, make sure that if the handshake succeeds // the next action is a connect. _updateAdvice(_cometd._mixin(false, _advice, {reconnect: 'retry'})); } _batch = 0; // Mark the start of an internal batch. // This is needed because handshake and connect are async. // It may happen that the application calls init() then subscribe() // and the subscribe message is sent before the connect message, if // the subscribe message is not held until the connect message is sent. // So here we start a batch to hold temporarily any message until // the connection is fully established. _internalBatch = true; // Save the properties provided by the user, so that // we can reuse them during automatic re-handshake _handshakeProps = handshakeProps; _handshakeCallback = handshakeCallback; var version = '1.0'; // Figure out the transports to send to the server var url = _cometd.getURL(); var transportTypes = _transports.findTransportTypes(version, _crossDomain, url); var bayeuxMessage = { id: _nextMessageId(), version: version, minimumVersion: version, channel: '/meta/handshake', supportedConnectionTypes: transportTypes, advice: { timeout: _advice.timeout, interval: _advice.interval } }; // Do not allow the user to override important fields. var message = _cometd._mixin(false, {}, _handshakeProps, bayeuxMessage); // Save the callback. _cometd._putCallback(message.id, handshakeCallback); // Pick up the first available transport as initial transport // since we don't know if the server supports it if (!_transport) { _transport = _transports.negotiateTransport(transportTypes, version, _crossDomain, url); if (!_transport) { var failure = 'Could not find initial transport among: ' + _transports.getTransportTypes(); _cometd._warn(failure); throw failure; } } _cometd._debug('Initial transport is', _transport.getType()); // We started a batch to hold the application messages, // so here we must bypass it and send immediately. _setStatus('handshaking'); _cometd._debug('Handshake sent', message); _send(false, [message], false, 'handshake'); }
[ "function", "_handshake", "(", "handshakeProps", ",", "handshakeCallback", ")", "{", "if", "(", "_isFunction", "(", "handshakeProps", ")", ")", "{", "handshakeCallback", "=", "handshakeProps", ";", "handshakeProps", "=", "undefined", ";", "}", "_clientId", "=", "null", ";", "_clearSubscriptions", "(", ")", ";", "if", "(", "_isDisconnected", "(", ")", ")", "{", "_transports", ".", "reset", "(", "true", ")", ";", "_updateAdvice", "(", "_config", ".", "advice", ")", ";", "}", "else", "{", "_updateAdvice", "(", "_cometd", ".", "_mixin", "(", "false", ",", "_advice", ",", "{", "reconnect", ":", "'retry'", "}", ")", ")", ";", "}", "_batch", "=", "0", ";", "_internalBatch", "=", "true", ";", "_handshakeProps", "=", "handshakeProps", ";", "_handshakeCallback", "=", "handshakeCallback", ";", "var", "version", "=", "'1.0'", ";", "var", "url", "=", "_cometd", ".", "getURL", "(", ")", ";", "var", "transportTypes", "=", "_transports", ".", "findTransportTypes", "(", "version", ",", "_crossDomain", ",", "url", ")", ";", "var", "bayeuxMessage", "=", "{", "id", ":", "_nextMessageId", "(", ")", ",", "version", ":", "version", ",", "minimumVersion", ":", "version", ",", "channel", ":", "'/meta/handshake'", ",", "supportedConnectionTypes", ":", "transportTypes", ",", "advice", ":", "{", "timeout", ":", "_advice", ".", "timeout", ",", "interval", ":", "_advice", ".", "interval", "}", "}", ";", "var", "message", "=", "_cometd", ".", "_mixin", "(", "false", ",", "{", "}", ",", "_handshakeProps", ",", "bayeuxMessage", ")", ";", "_cometd", ".", "_putCallback", "(", "message", ".", "id", ",", "handshakeCallback", ")", ";", "if", "(", "!", "_transport", ")", "{", "_transport", "=", "_transports", ".", "negotiateTransport", "(", "transportTypes", ",", "version", ",", "_crossDomain", ",", "url", ")", ";", "if", "(", "!", "_transport", ")", "{", "var", "failure", "=", "'Could not find initial transport among: '", "+", "_transports", ".", "getTransportTypes", "(", ")", ";", "_cometd", ".", "_warn", "(", "failure", ")", ";", "throw", "failure", ";", "}", "}", "_cometd", ".", "_debug", "(", "'Initial transport is'", ",", "_transport", ".", "getType", "(", ")", ")", ";", "_setStatus", "(", "'handshaking'", ")", ";", "_cometd", ".", "_debug", "(", "'Handshake sent'", ",", "message", ")", ";", "_send", "(", "false", ",", "[", "message", "]", ",", "false", ",", "'handshake'", ")", ";", "}" ]
Sends the initial handshake message
[ "Sends", "the", "initial", "handshake", "message" ]
ad3383b8e332050eaecd55be9bdff6cf76db699e
https://github.com/zetapush/zetapush/blob/ad3383b8e332050eaecd55be9bdff6cf76db699e/packages/cometd/lib/CometD.js#L623-L702
train
GitbookIO/plugin-quizzes
lib/retro.js
retro
function retro(content) { // Lex incoming markdown file var lexed = lex(content); // Break it into sections var newSections = sections.split(lexed) .map(function(section) { // Leave non quiz sections untouched if(!isQuiz(section)) { return section; } // Convert old section to new format return retroSection(section); }); // Bring sections back together into a list of lexed nodes var newLexed = sections.join(newSections); // Render back to markdown return render(newLexed); }
javascript
function retro(content) { // Lex incoming markdown file var lexed = lex(content); // Break it into sections var newSections = sections.split(lexed) .map(function(section) { // Leave non quiz sections untouched if(!isQuiz(section)) { return section; } // Convert old section to new format return retroSection(section); }); // Bring sections back together into a list of lexed nodes var newLexed = sections.join(newSections); // Render back to markdown return render(newLexed); }
[ "function", "retro", "(", "content", ")", "{", "var", "lexed", "=", "lex", "(", "content", ")", ";", "var", "newSections", "=", "sections", ".", "split", "(", "lexed", ")", ".", "map", "(", "function", "(", "section", ")", "{", "if", "(", "!", "isQuiz", "(", "section", ")", ")", "{", "return", "section", ";", "}", "return", "retroSection", "(", "section", ")", ";", "}", ")", ";", "var", "newLexed", "=", "sections", ".", "join", "(", "newSections", ")", ";", "return", "render", "(", "newLexed", ")", ";", "}" ]
retro takes an input markdown file and outputs a new markdown file converting in the process old quizs to new ones
[ "retro", "takes", "an", "input", "markdown", "file", "and", "outputs", "a", "new", "markdown", "file", "converting", "in", "the", "process", "old", "quizs", "to", "new", "ones" ]
02a54e4149454c77c9e5cbbe9e938c7b4684ddaf
https://github.com/GitbookIO/plugin-quizzes/blob/02a54e4149454c77c9e5cbbe9e938c7b4684ddaf/lib/retro.js#L57-L77
train
ArnaudBuchholz/gpf-js
lost+found/src/interfaces/enumerator_.js
_gpfEnumeratorEach
function _gpfEnumeratorEach (enumerator, callback, eventsHandler) { var iEnumerator = _gpfI.query(enumerator, _gpfI.IEnumerator), process; function end (event) { _gpfEventsFire.call(enumerator, event, {}, eventsHandler); } if (1 < callback.length) { process = function (event) { if (gpf.events.EVENT_CONTINUE === event.type) { if (!iEnumerator.moveNext(process)) { return; } } else if (gpf.events.EVENT_STOP === event.type) { return end(gpf.events.EVENT_STOPPED); } else if (gpf.events.EVENT_DATA !== event.type) { return end(event.type); } callback(iEnumerator.current(), process); }; if (iEnumerator.moveNext(process)) { callback(iEnumerator.current(), process); } } else { process = function (event) { if (gpf.events.EVENT_DATA !== event.type) { return end(event); } do { callback(iEnumerator.current()); } while (iEnumerator.moveNext(process)); }; while (iEnumerator.moveNext(process)) { callback(iEnumerator.current()); } } }
javascript
function _gpfEnumeratorEach (enumerator, callback, eventsHandler) { var iEnumerator = _gpfI.query(enumerator, _gpfI.IEnumerator), process; function end (event) { _gpfEventsFire.call(enumerator, event, {}, eventsHandler); } if (1 < callback.length) { process = function (event) { if (gpf.events.EVENT_CONTINUE === event.type) { if (!iEnumerator.moveNext(process)) { return; } } else if (gpf.events.EVENT_STOP === event.type) { return end(gpf.events.EVENT_STOPPED); } else if (gpf.events.EVENT_DATA !== event.type) { return end(event.type); } callback(iEnumerator.current(), process); }; if (iEnumerator.moveNext(process)) { callback(iEnumerator.current(), process); } } else { process = function (event) { if (gpf.events.EVENT_DATA !== event.type) { return end(event); } do { callback(iEnumerator.current()); } while (iEnumerator.moveNext(process)); }; while (iEnumerator.moveNext(process)) { callback(iEnumerator.current()); } } }
[ "function", "_gpfEnumeratorEach", "(", "enumerator", ",", "callback", ",", "eventsHandler", ")", "{", "var", "iEnumerator", "=", "_gpfI", ".", "query", "(", "enumerator", ",", "_gpfI", ".", "IEnumerator", ")", ",", "process", ";", "function", "end", "(", "event", ")", "{", "_gpfEventsFire", ".", "call", "(", "enumerator", ",", "event", ",", "{", "}", ",", "eventsHandler", ")", ";", "}", "if", "(", "1", "<", "callback", ".", "length", ")", "{", "process", "=", "function", "(", "event", ")", "{", "if", "(", "gpf", ".", "events", ".", "EVENT_CONTINUE", "===", "event", ".", "type", ")", "{", "if", "(", "!", "iEnumerator", ".", "moveNext", "(", "process", ")", ")", "{", "return", ";", "}", "}", "else", "if", "(", "gpf", ".", "events", ".", "EVENT_STOP", "===", "event", ".", "type", ")", "{", "return", "end", "(", "gpf", ".", "events", ".", "EVENT_STOPPED", ")", ";", "}", "else", "if", "(", "gpf", ".", "events", ".", "EVENT_DATA", "!==", "event", ".", "type", ")", "{", "return", "end", "(", "event", ".", "type", ")", ";", "}", "callback", "(", "iEnumerator", ".", "current", "(", ")", ",", "process", ")", ";", "}", ";", "if", "(", "iEnumerator", ".", "moveNext", "(", "process", ")", ")", "{", "callback", "(", "iEnumerator", ".", "current", "(", ")", ",", "process", ")", ";", "}", "}", "else", "{", "process", "=", "function", "(", "event", ")", "{", "if", "(", "gpf", ".", "events", ".", "EVENT_DATA", "!==", "event", ".", "type", ")", "{", "return", "end", "(", "event", ")", ";", "}", "do", "{", "callback", "(", "iEnumerator", ".", "current", "(", ")", ")", ";", "}", "while", "(", "iEnumerator", ".", "moveNext", "(", "process", ")", ")", ";", "}", ";", "while", "(", "iEnumerator", ".", "moveNext", "(", "process", ")", ")", "{", "callback", "(", "iEnumerator", ".", "current", "(", ")", ")", ";", "}", "}", "}" ]
Enumerates all elements of the enumerator and call the callback function. NOTE: reset is *not* called. NOTE: if an error occurs during the enumeration, the process stops @param {gpf.interfaces.IEnumerator} enumerator @param {Function} callback receive each item of the enumerator, signature is either: - {*} element or - {*} element - {gpf.events.Handler} eventsHandler If the signature supports two parameter, the last one will be used to control the iteration. The callback function has to trigger - gpf.events.EVENT_CONTINUE - gpf.events.EVENT_STOP @param {gpf.events.Handler} eventsHandler @event gpf.events.EVENT_END_OF_DATA No more data is available, the each function terminated @event gpf.events.EVENT_STOPPED The processing function requested to stop enumeration TODO how to put attributes on static members? TODO secure callback to throw an ERROR event if any exception occur "[each]": [gpf.$ClassEventHandler()],
[ "Enumerates", "all", "elements", "of", "the", "enumerator", "and", "call", "the", "callback", "function", "." ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/interfaces/enumerator_.js#L53-L89
train
ArnaudBuchholz/gpf-js
lost+found/src/interfaces/enumerator_.js
_gpfArrayEnumerator
function _gpfArrayEnumerator (array) { var pos = -1; return { reset: function () { pos = -1; }, moveNext: function (eventsHandler) { var result; ++pos; result = pos < array.length; if (!result && eventsHandler) { _gpfEventsFire.call(this, _GPF_EVENT_END_OF_DATA, {}, eventsHandler); } return result; }, current: function () { return array[pos]; } }; }
javascript
function _gpfArrayEnumerator (array) { var pos = -1; return { reset: function () { pos = -1; }, moveNext: function (eventsHandler) { var result; ++pos; result = pos < array.length; if (!result && eventsHandler) { _gpfEventsFire.call(this, _GPF_EVENT_END_OF_DATA, {}, eventsHandler); } return result; }, current: function () { return array[pos]; } }; }
[ "function", "_gpfArrayEnumerator", "(", "array", ")", "{", "var", "pos", "=", "-", "1", ";", "return", "{", "reset", ":", "function", "(", ")", "{", "pos", "=", "-", "1", ";", "}", ",", "moveNext", ":", "function", "(", "eventsHandler", ")", "{", "var", "result", ";", "++", "pos", ";", "result", "=", "pos", "<", "array", ".", "length", ";", "if", "(", "!", "result", "&&", "eventsHandler", ")", "{", "_gpfEventsFire", ".", "call", "(", "this", ",", "_GPF_EVENT_END_OF_DATA", ",", "{", "}", ",", "eventsHandler", ")", ";", "}", "return", "result", ";", "}", ",", "current", ":", "function", "(", ")", "{", "return", "array", "[", "pos", "]", ";", "}", "}", ";", "}" ]
Builds an enumerable interface based on an array @param {Object[]} array Base of the enumeration @return {Object} Object implementing the IEnumerable interface
[ "Builds", "an", "enumerable", "interface", "based", "on", "an", "array" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/interfaces/enumerator_.js#L97-L116
train
ArnaudBuchholz/gpf-js
lost+found/src/interfaces/enumerator_.js
_buildEnumeratorOnObjectArray
function _buildEnumeratorOnObjectArray (object) { var attributes = new _gpfA.Map(object).filter(_gpfA.EnumerableAttribute), members = attributes.getMembers(); return _gpfArrayEnumerator(object[members[0]]); }
javascript
function _buildEnumeratorOnObjectArray (object) { var attributes = new _gpfA.Map(object).filter(_gpfA.EnumerableAttribute), members = attributes.getMembers(); return _gpfArrayEnumerator(object[members[0]]); }
[ "function", "_buildEnumeratorOnObjectArray", "(", "object", ")", "{", "var", "attributes", "=", "new", "_gpfA", ".", "Map", "(", "object", ")", ".", "filter", "(", "_gpfA", ".", "EnumerableAttribute", ")", ",", "members", "=", "attributes", ".", "getMembers", "(", ")", ";", "return", "_gpfArrayEnumerator", "(", "object", "[", "members", "[", "0", "]", "]", ")", ";", "}" ]
Interface builder that connects to the EnumerableAttribute attribute @param {Object} object @return {Object} Object implementing the IEnumerable interface
[ "Interface", "builder", "that", "connects", "to", "the", "EnumerableAttribute", "attribute" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/interfaces/enumerator_.js#L183-L187
train
ArnaudBuchholz/gpf-js
lost+found/src/attributes/attributes.js
function (objPrototype) { var me = this, statics = _gpfA.AttrConstraintAttribute, originalAlterPrototype = statics.originalAlterPrototype, attributes = new _gpfA.Map(me); // Get constraints set for THIS attribute attributes.filter(_gpfAttrConstraint).forEach(function (constraintAttributes) { constraintAttributes.forEach(function (attribute) { attribute._check(me, objPrototype); }); }); // OK, call _alterPrototype me[originalAlterPrototype](objPrototype); }
javascript
function (objPrototype) { var me = this, statics = _gpfA.AttrConstraintAttribute, originalAlterPrototype = statics.originalAlterPrototype, attributes = new _gpfA.Map(me); // Get constraints set for THIS attribute attributes.filter(_gpfAttrConstraint).forEach(function (constraintAttributes) { constraintAttributes.forEach(function (attribute) { attribute._check(me, objPrototype); }); }); // OK, call _alterPrototype me[originalAlterPrototype](objPrototype); }
[ "function", "(", "objPrototype", ")", "{", "var", "me", "=", "this", ",", "statics", "=", "_gpfA", ".", "AttrConstraintAttribute", ",", "originalAlterPrototype", "=", "statics", ".", "originalAlterPrototype", ",", "attributes", "=", "new", "_gpfA", ".", "Map", "(", "me", ")", ";", "attributes", ".", "filter", "(", "_gpfAttrConstraint", ")", ".", "forEach", "(", "function", "(", "constraintAttributes", ")", "{", "constraintAttributes", ".", "forEach", "(", "function", "(", "attribute", ")", "{", "attribute", ".", "_check", "(", "me", ",", "objPrototype", ")", ";", "}", ")", ";", "}", ")", ";", "me", "[", "originalAlterPrototype", "]", "(", "objPrototype", ")", ";", "}" ]
Check that all attribute constraints are respected before calling the original _alterPrototype @param {Object} objPrototype @this {gpf.attributes.Attribute} the child class attribute
[ "Check", "that", "all", "attribute", "constraints", "are", "respected", "before", "calling", "the", "original", "_alterPrototype" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/attributes/attributes.js#L108-L121
train
GitbookIO/plugin-quizzes
lib/section2obj.js
render
function render(lexed) { // Options to parser var options = Object.create(kramed.defaults); options.renderer = renderer(); if(!lexed.links) { lexed.links = {}; } return kramed.parser(lexed, options); }
javascript
function render(lexed) { // Options to parser var options = Object.create(kramed.defaults); options.renderer = renderer(); if(!lexed.links) { lexed.links = {}; } return kramed.parser(lexed, options); }
[ "function", "render", "(", "lexed", ")", "{", "var", "options", "=", "Object", ".", "create", "(", "kramed", ".", "defaults", ")", ";", "options", ".", "renderer", "=", "renderer", "(", ")", ";", "if", "(", "!", "lexed", ".", "links", ")", "{", "lexed", ".", "links", "=", "{", "}", ";", "}", "return", "kramed", ".", "parser", "(", "lexed", ",", "options", ")", ";", "}" ]
Render a section using our custom renderer
[ "Render", "a", "section", "using", "our", "custom", "renderer" ]
02a54e4149454c77c9e5cbbe9e938c7b4684ddaf
https://github.com/GitbookIO/plugin-quizzes/blob/02a54e4149454c77c9e5cbbe9e938c7b4684ddaf/lib/section2obj.js#L7-L17
train
ArnaudBuchholz/gpf-js
lost+found/src/bin.js
_gpfSkipPad
function _gpfSkipPad (text, pad) { var idx = 0; while (idx < text.length && -1 !== pad.indexOf(text.charAt(idx))) { ++idx; } return idx; }
javascript
function _gpfSkipPad (text, pad) { var idx = 0; while (idx < text.length && -1 !== pad.indexOf(text.charAt(idx))) { ++idx; } return idx; }
[ "function", "_gpfSkipPad", "(", "text", ",", "pad", ")", "{", "var", "idx", "=", "0", ";", "while", "(", "idx", "<", "text", ".", "length", "&&", "-", "1", "!==", "pad", ".", "indexOf", "(", "text", ".", "charAt", "(", "idx", ")", ")", ")", "{", "++", "idx", ";", "}", "return", "idx", ";", "}" ]
region _gpfFromBaseANY Skip initial padding characters
[ "region", "_gpfFromBaseANY", "Skip", "initial", "padding", "characters" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/bin.js#L107-L113
train
ArnaudBuchholz/gpf-js
lost+found/src/bin.js
_gpfFromBaseANY
function _gpfFromBaseANY (base, text, pad) { var baseLength = base.length, result = 0, idx = _gpfSkipPad(text, pad || base.charAt(0)); while (idx < text.length) { result = baseLength * result + base.indexOf(text.charAt(idx++)); } return result; }
javascript
function _gpfFromBaseANY (base, text, pad) { var baseLength = base.length, result = 0, idx = _gpfSkipPad(text, pad || base.charAt(0)); while (idx < text.length) { result = baseLength * result + base.indexOf(text.charAt(idx++)); } return result; }
[ "function", "_gpfFromBaseANY", "(", "base", ",", "text", ",", "pad", ")", "{", "var", "baseLength", "=", "base", ".", "length", ",", "result", "=", "0", ",", "idx", "=", "_gpfSkipPad", "(", "text", ",", "pad", "||", "base", ".", "charAt", "(", "0", ")", ")", ";", "while", "(", "idx", "<", "text", ".", "length", ")", "{", "result", "=", "baseLength", "*", "result", "+", "base", ".", "indexOf", "(", "text", ".", "charAt", "(", "idx", "++", ")", ")", ";", "}", "return", "result", ";", "}" ]
Decodes the text value using the specified base. @param {String} base @param {String} text @param {String} [pad=base.charAt(0)] pad @return {Number}
[ "Decodes", "the", "text", "value", "using", "the", "specified", "base", "." ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/bin.js#L123-L131
train
ArnaudBuchholz/gpf-js
lost+found/src/bin.js
_gpfPow2
function _gpfPow2 (n) { var result = _gpfPow2[n]; if (result) { return result; } result = _gpfComputePow2(n); _gpfPow2[n] = result; return result; }
javascript
function _gpfPow2 (n) { var result = _gpfPow2[n]; if (result) { return result; } result = _gpfComputePow2(n); _gpfPow2[n] = result; return result; }
[ "function", "_gpfPow2", "(", "n", ")", "{", "var", "result", "=", "_gpfPow2", "[", "n", "]", ";", "if", "(", "result", ")", "{", "return", "result", ";", "}", "result", "=", "_gpfComputePow2", "(", "n", ")", ";", "_gpfPow2", "[", "n", "]", "=", "result", ";", "return", "result", ";", "}" ]
Gives the power of 2 @param {Number} n the power to get @return {Number}
[ "Gives", "the", "power", "of", "2" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/bin.js#L161-L169
train
ArnaudBuchholz/gpf-js
lost+found/src/bin.js
function (value, length, pad) { return _gpfToBaseANY(_gpfB16, value, { length: length, pad: pad }); }
javascript
function (value, length, pad) { return _gpfToBaseANY(_gpfB16, value, { length: length, pad: pad }); }
[ "function", "(", "value", ",", "length", ",", "pad", ")", "{", "return", "_gpfToBaseANY", "(", "_gpfB16", ",", "value", ",", "{", "length", ":", "length", ",", "pad", ":", "pad", "}", ")", ";", "}" ]
Returns the hexadecimal encoding of value. @param {Number} value @param {Number} length of encoding @param {String} [pad="0"] pad @return {String}
[ "Returns", "the", "hexadecimal", "encoding", "of", "value", "." ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/bin.js#L220-L225
train
ArnaudBuchholz/gpf-js
lost+found/src/bin.js
function (value, length, pad) { return _gpfToBaseANY(_gpfB64, value, { length: length, pad: pad }); }
javascript
function (value, length, pad) { return _gpfToBaseANY(_gpfB64, value, { length: length, pad: pad }); }
[ "function", "(", "value", ",", "length", ",", "pad", ")", "{", "return", "_gpfToBaseANY", "(", "_gpfB64", ",", "value", ",", "{", "length", ":", "length", ",", "pad", ":", "pad", "}", ")", ";", "}" ]
Returns the base 64 encoding of value. @param {Number} value @param {Number} length of encoding @param {String} [pad="0"] pad @return {String}
[ "Returns", "the", "base", "64", "encoding", "of", "value", "." ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/bin.js#L246-L251
train
zetapush/zetapush
packages/user-management/samples/standard-user-workflow/front/js/login.js
connectUser
async function connectUser(form) { if (!form.login.value || !form.password.value) { document.getElementById('login-errors').innerHTML += `<p>Login and password are required</p>`; return; } await client.setCredentials({ login: form.login.value, password: form.password.value }); client .connect() .then(() => { displayMessage('Login success', 'Welcome to wonderful service', 'is-success'); goTo('home'); }) .catch((e) => { displayMessage( 'Login failed', 'Your account is not validated, have you clicked on the link in the email ?', 'is-warning' ); }); }
javascript
async function connectUser(form) { if (!form.login.value || !form.password.value) { document.getElementById('login-errors').innerHTML += `<p>Login and password are required</p>`; return; } await client.setCredentials({ login: form.login.value, password: form.password.value }); client .connect() .then(() => { displayMessage('Login success', 'Welcome to wonderful service', 'is-success'); goTo('home'); }) .catch((e) => { displayMessage( 'Login failed', 'Your account is not validated, have you clicked on the link in the email ?', 'is-warning' ); }); }
[ "async", "function", "connectUser", "(", "form", ")", "{", "if", "(", "!", "form", ".", "login", ".", "value", "||", "!", "form", ".", "password", ".", "value", ")", "{", "document", ".", "getElementById", "(", "'login-errors'", ")", ".", "innerHTML", "+=", "`", "`", ";", "return", ";", "}", "await", "client", ".", "setCredentials", "(", "{", "login", ":", "form", ".", "login", ".", "value", ",", "password", ":", "form", ".", "password", ".", "value", "}", ")", ";", "client", ".", "connect", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "displayMessage", "(", "'Login success'", ",", "'Welcome to wonderful service'", ",", "'is-success'", ")", ";", "goTo", "(", "'home'", ")", ";", "}", ")", ".", "catch", "(", "(", "e", ")", "=>", "{", "displayMessage", "(", "'Login failed'", ",", "'Your account is not validated, have you clicked on the link in the email ?'", ",", "'is-warning'", ")", ";", "}", ")", ";", "}" ]
Launch the connection of the user into the application
[ "Launch", "the", "connection", "of", "the", "user", "into", "the", "application" ]
ad3383b8e332050eaecd55be9bdff6cf76db699e
https://github.com/zetapush/zetapush/blob/ad3383b8e332050eaecd55be9bdff6cf76db699e/packages/user-management/samples/standard-user-workflow/front/js/login.js#L4-L24
train
tuchk4/bivrost
example/weather-axios-tcomb/index.js
printWeatherForecast
function printWeatherForecast() { return weather .dailyForecast('Kiev') .then(forecast => console.log('WEATHER FORECAST:', forecast)) .catch(error => console.error(error)); }
javascript
function printWeatherForecast() { return weather .dailyForecast('Kiev') .then(forecast => console.log('WEATHER FORECAST:', forecast)) .catch(error => console.error(error)); }
[ "function", "printWeatherForecast", "(", ")", "{", "return", "weather", ".", "dailyForecast", "(", "'Kiev'", ")", ".", "then", "(", "forecast", "=>", "console", ".", "log", "(", "'WEATHER FORECAST:'", ",", "forecast", ")", ")", ".", "catch", "(", "error", "=>", "console", ".", "error", "(", "error", ")", ")", ";", "}" ]
call datasource methods
[ "call", "datasource", "methods" ]
f6d6d5973bee77c02ee050dd34ed19a5f96b0a42
https://github.com/tuchk4/bivrost/blob/f6d6d5973bee77c02ee050dd34ed19a5f96b0a42/example/weather-axios-tcomb/index.js#L59-L64
train
ArnaudBuchholz/gpf-js
make/coverage.js
_class
function _class (Constructor, members, Base) { var ResultConstructor; if (Base) { ResultConstructor = function () { Base.apply(this, arguments); Constructor.apply(this, arguments); }; ResultConstructor.prototype = new Base(); } else { ResultConstructor = function () { Constructor.apply(this, arguments); }; } if (members) { Object.keys(members).forEach(function (memberName) { ResultConstructor.prototype[memberName] = members[memberName]; }); } return ResultConstructor; }
javascript
function _class (Constructor, members, Base) { var ResultConstructor; if (Base) { ResultConstructor = function () { Base.apply(this, arguments); Constructor.apply(this, arguments); }; ResultConstructor.prototype = new Base(); } else { ResultConstructor = function () { Constructor.apply(this, arguments); }; } if (members) { Object.keys(members).forEach(function (memberName) { ResultConstructor.prototype[memberName] = members[memberName]; }); } return ResultConstructor; }
[ "function", "_class", "(", "Constructor", ",", "members", ",", "Base", ")", "{", "var", "ResultConstructor", ";", "if", "(", "Base", ")", "{", "ResultConstructor", "=", "function", "(", ")", "{", "Base", ".", "apply", "(", "this", ",", "arguments", ")", ";", "Constructor", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", ";", "ResultConstructor", ".", "prototype", "=", "new", "Base", "(", ")", ";", "}", "else", "{", "ResultConstructor", "=", "function", "(", ")", "{", "Constructor", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", ";", "}", "if", "(", "members", ")", "{", "Object", ".", "keys", "(", "members", ")", ".", "forEach", "(", "function", "(", "memberName", ")", "{", "ResultConstructor", ".", "prototype", "[", "memberName", "]", "=", "members", "[", "memberName", "]", ";", "}", ")", ";", "}", "return", "ResultConstructor", ";", "}" ]
Simple class helper @param {Function} Constructor Constructor function @param {Object} members Members dictionary @param {Function} [Base] Base class @return {Function} New class constructor @private
[ "Simple", "class", "helper" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/make/coverage.js#L16-L35
train
ArnaudBuchholz/gpf-js
make/coverage.js
function (partStatistics) { this.count += partStatistics.count; this.tested += partStatistics.tested; this.ignored += partStatistics.ignored; }
javascript
function (partStatistics) { this.count += partStatistics.count; this.tested += partStatistics.tested; this.ignored += partStatistics.ignored; }
[ "function", "(", "partStatistics", ")", "{", "this", ".", "count", "+=", "partStatistics", ".", "count", ";", "this", ".", "tested", "+=", "partStatistics", ".", "tested", ";", "this", ".", "ignored", "+=", "partStatistics", ".", "ignored", ";", "}" ]
Adds information from another part statistics @param {CoverageReport.PartStatistics} partStatistics Statistics to add
[ "Adds", "information", "from", "another", "part", "statistics" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/make/coverage.js#L85-L89
train
ArnaudBuchholz/gpf-js
make/coverage.js
function (count, total, rounded) { var scale; if (rounded) { scale = this._0digitsScale; } else { scale = this._2digitsScale; } return Math.floor(this._percentage * scale * count / total) / scale; }
javascript
function (count, total, rounded) { var scale; if (rounded) { scale = this._0digitsScale; } else { scale = this._2digitsScale; } return Math.floor(this._percentage * scale * count / total) / scale; }
[ "function", "(", "count", ",", "total", ",", "rounded", ")", "{", "var", "scale", ";", "if", "(", "rounded", ")", "{", "scale", "=", "this", ".", "_0digitsScale", ";", "}", "else", "{", "scale", "=", "this", ".", "_2digitsScale", ";", "}", "return", "Math", ".", "floor", "(", "this", ".", "_percentage", "*", "scale", "*", "count", "/", "total", ")", "/", "scale", ";", "}" ]
Generates percent value
[ "Generates", "percent", "value" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/make/coverage.js#L96-L104
train
ArnaudBuchholz/gpf-js
make/coverage.js
function (numberOfCalls, branchDefinition) { ["if", "else"].forEach(function (label, index) { ++this.count; this._testedOrIgnored(numberOfCalls[index], branchDefinition.locations[index]); }, this); }
javascript
function (numberOfCalls, branchDefinition) { ["if", "else"].forEach(function (label, index) { ++this.count; this._testedOrIgnored(numberOfCalls[index], branchDefinition.locations[index]); }, this); }
[ "function", "(", "numberOfCalls", ",", "branchDefinition", ")", "{", "[", "\"if\"", ",", "\"else\"", "]", ".", "forEach", "(", "function", "(", "label", ",", "index", ")", "{", "++", "this", ".", "count", ";", "this", ".", "_testedOrIgnored", "(", "numberOfCalls", "[", "index", "]", ",", "branchDefinition", ".", "locations", "[", "index", "]", ")", ";", "}", ",", "this", ")", ";", "}" ]
Branch-specific coverage processing @param {Number[]} numberOfCalls Number of calls extracted from the coverage report (one per branch) @param {Object} branchDefinition Branch definition locations array will used to fetch skip property of each branch
[ "Branch", "-", "specific", "coverage", "processing" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/make/coverage.js#L163-L168
train
ArnaudBuchholz/gpf-js
make/coverage.js
function (fileName) { var result = new _File(fileName), fileData = this._data[fileName]; [{ type: "statements", data: "s", map: "statementMap" }, { type: "functions", data: "f", map: "fnMap" }, { type: "branches", data: "b", map: "branchMap" }].forEach(function (part) { var map = fileData[part.map], data = fileData[part.data], statistics = result[part.type], index = 1; while (undefined !== data[index]) { statistics.processCoverage(data[index], map[index]); ++index; } }); return result; }
javascript
function (fileName) { var result = new _File(fileName), fileData = this._data[fileName]; [{ type: "statements", data: "s", map: "statementMap" }, { type: "functions", data: "f", map: "fnMap" }, { type: "branches", data: "b", map: "branchMap" }].forEach(function (part) { var map = fileData[part.map], data = fileData[part.data], statistics = result[part.type], index = 1; while (undefined !== data[index]) { statistics.processCoverage(data[index], map[index]); ++index; } }); return result; }
[ "function", "(", "fileName", ")", "{", "var", "result", "=", "new", "_File", "(", "fileName", ")", ",", "fileData", "=", "this", ".", "_data", "[", "fileName", "]", ";", "[", "{", "type", ":", "\"statements\"", ",", "data", ":", "\"s\"", ",", "map", ":", "\"statementMap\"", "}", ",", "{", "type", ":", "\"functions\"", ",", "data", ":", "\"f\"", ",", "map", ":", "\"fnMap\"", "}", ",", "{", "type", ":", "\"branches\"", ",", "data", ":", "\"b\"", ",", "map", ":", "\"branchMap\"", "}", "]", ".", "forEach", "(", "function", "(", "part", ")", "{", "var", "map", "=", "fileData", "[", "part", ".", "map", "]", ",", "data", "=", "fileData", "[", "part", ".", "data", "]", ",", "statistics", "=", "result", "[", "part", ".", "type", "]", ",", "index", "=", "1", ";", "while", "(", "undefined", "!==", "data", "[", "index", "]", ")", "{", "statistics", ".", "processCoverage", "(", "data", "[", "index", "]", ",", "map", "[", "index", "]", ")", ";", "++", "index", ";", "}", "}", ")", ";", "return", "result", ";", "}" ]
Compute coverage for one file @param {String} fileName File name @return {CoverageReport.File} Coverage for one file
[ "Compute", "coverage", "for", "one", "file" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/make/coverage.js#L248-L274
train
ArnaudBuchholz/gpf-js
make/coverage.js
function () { this._files = {}; this._global = new _File(); Object.keys(this._data).forEach(function (fileName) { var fileCoverage = this._computeFileCoverage(fileName); this._files[fileCoverage.name] = fileCoverage; this._global.statements.add(fileCoverage.statements); this._global.functions.add(fileCoverage.functions); this._global.branches.add(fileCoverage.branches); }, this); }
javascript
function () { this._files = {}; this._global = new _File(); Object.keys(this._data).forEach(function (fileName) { var fileCoverage = this._computeFileCoverage(fileName); this._files[fileCoverage.name] = fileCoverage; this._global.statements.add(fileCoverage.statements); this._global.functions.add(fileCoverage.functions); this._global.branches.add(fileCoverage.branches); }, this); }
[ "function", "(", ")", "{", "this", ".", "_files", "=", "{", "}", ";", "this", ".", "_global", "=", "new", "_File", "(", ")", ";", "Object", ".", "keys", "(", "this", ".", "_data", ")", ".", "forEach", "(", "function", "(", "fileName", ")", "{", "var", "fileCoverage", "=", "this", ".", "_computeFileCoverage", "(", "fileName", ")", ";", "this", ".", "_files", "[", "fileCoverage", ".", "name", "]", "=", "fileCoverage", ";", "this", ".", "_global", ".", "statements", ".", "add", "(", "fileCoverage", ".", "statements", ")", ";", "this", ".", "_global", ".", "functions", ".", "add", "(", "fileCoverage", ".", "functions", ")", ";", "this", ".", "_global", ".", "branches", ".", "add", "(", "fileCoverage", ".", "branches", ")", ";", "}", ",", "this", ")", ";", "}" ]
Compute all coverages
[ "Compute", "all", "coverages" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/make/coverage.js#L277-L287
train
popeindustries/buddy
lib/config/dependencies.js
find
function find(id) { let filepath = ''; if ('string' == typeof id) { try { // Resolve relative to buddy package filepath = require.resolve(id); } catch (err) { // Resolve relative to project package filepath = resolve(path.resolve('package.json'), id); } } return filepath; }
javascript
function find(id) { let filepath = ''; if ('string' == typeof id) { try { // Resolve relative to buddy package filepath = require.resolve(id); } catch (err) { // Resolve relative to project package filepath = resolve(path.resolve('package.json'), id); } } return filepath; }
[ "function", "find", "(", "id", ")", "{", "let", "filepath", "=", "''", ";", "if", "(", "'string'", "==", "typeof", "id", ")", "{", "try", "{", "filepath", "=", "require", ".", "resolve", "(", "id", ")", ";", "}", "catch", "(", "err", ")", "{", "filepath", "=", "resolve", "(", "path", ".", "resolve", "(", "'package.json'", ")", ",", "id", ")", ";", "}", "}", "return", "filepath", ";", "}" ]
Resolve dependency filepath from 'id' @param {String} id @returns {String}
[ "Resolve", "dependency", "filepath", "from", "id" ]
c38afc2e6915743eb6cfcf5aba59a8699142c7a5
https://github.com/popeindustries/buddy/blob/c38afc2e6915743eb6cfcf5aba59a8699142c7a5/lib/config/dependencies.js#L21-L35
train
popeindustries/buddy
lib/config/dependencies.js
install
function install(ids) { if (!ids || !ids.length) return; const missingDependencies = ids.filter(id => find(id) == ''); if (missingDependencies.length) { try { const cmd = useNPM ? `npm --save-dev --save-exact install ${missingDependencies.join(' ')}` : `yarn add --dev --exact ${missingDependencies.join(' ')}`; print('installing the following missing dependencies:', 0); missingDependencies.forEach(id => { print(strong(id), 1); }); exec(cmd); } catch (err) { error(err); } } }
javascript
function install(ids) { if (!ids || !ids.length) return; const missingDependencies = ids.filter(id => find(id) == ''); if (missingDependencies.length) { try { const cmd = useNPM ? `npm --save-dev --save-exact install ${missingDependencies.join(' ')}` : `yarn add --dev --exact ${missingDependencies.join(' ')}`; print('installing the following missing dependencies:', 0); missingDependencies.forEach(id => { print(strong(id), 1); }); exec(cmd); } catch (err) { error(err); } } }
[ "function", "install", "(", "ids", ")", "{", "if", "(", "!", "ids", "||", "!", "ids", ".", "length", ")", "return", ";", "const", "missingDependencies", "=", "ids", ".", "filter", "(", "id", "=>", "find", "(", "id", ")", "==", "''", ")", ";", "if", "(", "missingDependencies", ".", "length", ")", "{", "try", "{", "const", "cmd", "=", "useNPM", "?", "`", "${", "missingDependencies", ".", "join", "(", "' '", ")", "}", "`", ":", "`", "${", "missingDependencies", ".", "join", "(", "' '", ")", "}", "`", ";", "print", "(", "'installing the following missing dependencies:'", ",", "0", ")", ";", "missingDependencies", ".", "forEach", "(", "id", "=>", "{", "print", "(", "strong", "(", "id", ")", ",", "1", ")", ";", "}", ")", ";", "exec", "(", "cmd", ")", ";", "}", "catch", "(", "err", ")", "{", "error", "(", "err", ")", ";", "}", "}", "}" ]
Install dependencies based on 'ids' @param {Array} ids
[ "Install", "dependencies", "based", "on", "ids" ]
c38afc2e6915743eb6cfcf5aba59a8699142c7a5
https://github.com/popeindustries/buddy/blob/c38afc2e6915743eb6cfcf5aba59a8699142c7a5/lib/config/dependencies.js#L41-L61
train
ArnaudBuchholz/gpf-js
lost+found/src/xpath.js
_filter
function _filter (node, expr, resultSet) { var selectedNodes, conditions, type, idx, condition; if (expr.and) { conditions = expr.and; type = 0; } else if (expr.or) { conditions = expr.or; type = 1; } for (idx = 0; idx < conditions.length; ++idx) { condition = conditions[idx]; if (condition.and || condition.or) { selectedNodes = []; _filter(node, condition, selectedNodes); } else { selectedNodes = _select(node, condition); } if (0 === type && selectedNodes.length === 0) { return; } if (1 === type && selectedNodes.length !== 0) { resultSet.push(node); return; } } if (0 === type) { resultSet.push(node); } }
javascript
function _filter (node, expr, resultSet) { var selectedNodes, conditions, type, idx, condition; if (expr.and) { conditions = expr.and; type = 0; } else if (expr.or) { conditions = expr.or; type = 1; } for (idx = 0; idx < conditions.length; ++idx) { condition = conditions[idx]; if (condition.and || condition.or) { selectedNodes = []; _filter(node, condition, selectedNodes); } else { selectedNodes = _select(node, condition); } if (0 === type && selectedNodes.length === 0) { return; } if (1 === type && selectedNodes.length !== 0) { resultSet.push(node); return; } } if (0 === type) { resultSet.push(node); } }
[ "function", "_filter", "(", "node", ",", "expr", ",", "resultSet", ")", "{", "var", "selectedNodes", ",", "conditions", ",", "type", ",", "idx", ",", "condition", ";", "if", "(", "expr", ".", "and", ")", "{", "conditions", "=", "expr", ".", "and", ";", "type", "=", "0", ";", "}", "else", "if", "(", "expr", ".", "or", ")", "{", "conditions", "=", "expr", ".", "or", ";", "type", "=", "1", ";", "}", "for", "(", "idx", "=", "0", ";", "idx", "<", "conditions", ".", "length", ";", "++", "idx", ")", "{", "condition", "=", "conditions", "[", "idx", "]", ";", "if", "(", "condition", ".", "and", "||", "condition", ".", "or", ")", "{", "selectedNodes", "=", "[", "]", ";", "_filter", "(", "node", ",", "condition", ",", "selectedNodes", ")", ";", "}", "else", "{", "selectedNodes", "=", "_select", "(", "node", ",", "condition", ")", ";", "}", "if", "(", "0", "===", "type", "&&", "selectedNodes", ".", "length", "===", "0", ")", "{", "return", ";", "}", "if", "(", "1", "===", "type", "&&", "selectedNodes", ".", "length", "!==", "0", ")", "{", "resultSet", ".", "push", "(", "node", ")", ";", "return", ";", "}", "}", "if", "(", "0", "===", "type", ")", "{", "resultSet", ".", "push", "(", "node", ")", ";", "}", "}" ]
Apply the filter expression on the node @param {gpf.xml.IXmlConstNode} node @param {Object} expr @param {gpf.xml.IXmlConstNode[]} resultSet @private
[ "Apply", "the", "filter", "expression", "on", "the", "node" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/xpath.js#L169-L202
train
ArnaudBuchholz/gpf-js
lost+found/src/xpath.js
_select
function _select (node, expr) { var resultSet, nodeSet = [node]; while (expr) { resultSet = []; _test(nodeSet, expr, resultSet); if (0 === resultSet.length) { return []; } nodeSet = resultSet; if (expr.filter) { resultSet = []; _each(nodeSet, _filter, expr.filter, resultSet); if (0 === resultSet.length) { return []; } nodeSet = resultSet; } expr = expr.then; } return resultSet; }
javascript
function _select (node, expr) { var resultSet, nodeSet = [node]; while (expr) { resultSet = []; _test(nodeSet, expr, resultSet); if (0 === resultSet.length) { return []; } nodeSet = resultSet; if (expr.filter) { resultSet = []; _each(nodeSet, _filter, expr.filter, resultSet); if (0 === resultSet.length) { return []; } nodeSet = resultSet; } expr = expr.then; } return resultSet; }
[ "function", "_select", "(", "node", ",", "expr", ")", "{", "var", "resultSet", ",", "nodeSet", "=", "[", "node", "]", ";", "while", "(", "expr", ")", "{", "resultSet", "=", "[", "]", ";", "_test", "(", "nodeSet", ",", "expr", ",", "resultSet", ")", ";", "if", "(", "0", "===", "resultSet", ".", "length", ")", "{", "return", "[", "]", ";", "}", "nodeSet", "=", "resultSet", ";", "if", "(", "expr", ".", "filter", ")", "{", "resultSet", "=", "[", "]", ";", "_each", "(", "nodeSet", ",", "_filter", ",", "expr", ".", "filter", ",", "resultSet", ")", ";", "if", "(", "0", "===", "resultSet", ".", "length", ")", "{", "return", "[", "]", ";", "}", "nodeSet", "=", "resultSet", ";", "}", "expr", "=", "expr", ".", "then", ";", "}", "return", "resultSet", ";", "}" ]
Select the expression on the current node @param {gpf.xml.IXmlConstNode} node @param {Object} expr @private
[ "Select", "the", "expression", "on", "the", "current", "node" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/xpath.js#L211-L233
train
ArnaudBuchholz/gpf-js
lost+found/src/define_.js
_gpfDefineCore
function _gpfDefineCore (name, Super, definition) { var NewClass = _gpfDefineFactory(name, Super, definition); _gpfDefineUpdateContext(name, NewClass); return NewClass; }
javascript
function _gpfDefineCore (name, Super, definition) { var NewClass = _gpfDefineFactory(name, Super, definition); _gpfDefineUpdateContext(name, NewClass); return NewClass; }
[ "function", "_gpfDefineCore", "(", "name", ",", "Super", ",", "definition", ")", "{", "var", "NewClass", "=", "_gpfDefineFactory", "(", "name", ",", "Super", ",", "definition", ")", ";", "_gpfDefineUpdateContext", "(", "name", ",", "NewClass", ")", ";", "return", "NewClass", ";", "}" ]
Defines a new class by setting a contextual name @param {String} name New class contextual name @param {Function} Super Super class @param {Object} definition Class definition @return {Function} New class constructor
[ "Defines", "a", "new", "class", "by", "setting", "a", "contextual", "name" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/define_.js#L33-L37
train
ArnaudBuchholz/gpf-js
lost+found/src/define_.js
_gpfDefineProcessParamsAndCallCore
function _gpfDefineProcessParamsAndCallCore (params, processFunction) { processFunction("", Object, params); return _gpfDefineCore.apply(null, params); }
javascript
function _gpfDefineProcessParamsAndCallCore (params, processFunction) { processFunction("", Object, params); return _gpfDefineCore.apply(null, params); }
[ "function", "_gpfDefineProcessParamsAndCallCore", "(", "params", ",", "processFunction", ")", "{", "processFunction", "(", "\"\"", ",", "Object", ",", "params", ")", ";", "return", "_gpfDefineCore", ".", "apply", "(", "null", ",", "params", ")", ";", "}" ]
Apply the processing function and call _gpfDefineCore
[ "Apply", "the", "processing", "function", "and", "call", "_gpfDefineCore" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/define_.js#L40-L43
train
SockDrawer/SockBot
lib/commands.js
parseLine
function parseLine(line) { let args, mention, commandText; if (new RegExp(`^@${forum.username}\\s\\S{3,}(\\s|$)`, 'i').test(line)) { args = line.split(/\s+/); args.shift(); commandText = args.shift(); mention = true; } else if (/^!\w\S{2,}(\s|$)/.test(line)) { args = line.split(/\s+/); commandText = args.shift().substring(1); mention = false; } if (commandText) { return { commandText: commandText, command: commandText.toLowerCase(), args: args, line: line, mention: mention }; } return null; }
javascript
function parseLine(line) { let args, mention, commandText; if (new RegExp(`^@${forum.username}\\s\\S{3,}(\\s|$)`, 'i').test(line)) { args = line.split(/\s+/); args.shift(); commandText = args.shift(); mention = true; } else if (/^!\w\S{2,}(\s|$)/.test(line)) { args = line.split(/\s+/); commandText = args.shift().substring(1); mention = false; } if (commandText) { return { commandText: commandText, command: commandText.toLowerCase(), args: args, line: line, mention: mention }; } return null; }
[ "function", "parseLine", "(", "line", ")", "{", "let", "args", ",", "mention", ",", "commandText", ";", "if", "(", "new", "RegExp", "(", "`", "${", "forum", ".", "username", "}", "\\\\", "\\\\", "\\\\", "`", ",", "'i'", ")", ".", "test", "(", "line", ")", ")", "{", "args", "=", "line", ".", "split", "(", "/", "\\s+", "/", ")", ";", "args", ".", "shift", "(", ")", ";", "commandText", "=", "args", ".", "shift", "(", ")", ";", "mention", "=", "true", ";", "}", "else", "if", "(", "/", "^!\\w\\S{2,}(\\s|$)", "/", ".", "test", "(", "line", ")", ")", "{", "args", "=", "line", ".", "split", "(", "/", "\\s+", "/", ")", ";", "commandText", "=", "args", ".", "shift", "(", ")", ".", "substring", "(", "1", ")", ";", "mention", "=", "false", ";", "}", "if", "(", "commandText", ")", "{", "return", "{", "commandText", ":", "commandText", ",", "command", ":", "commandText", ".", "toLowerCase", "(", ")", ",", "args", ":", "args", ",", "line", ":", "line", ",", "mention", ":", "mention", "}", ";", "}", "return", "null", ";", "}" ]
Parse command definitions from a line of text @private @param {string} line Text to parse @returns {object} Parsed command definition
[ "Parse", "command", "definitions", "from", "a", "line", "of", "text" ]
043f7e9aa9ec12250889fd825ddcf86709b095a3
https://github.com/SockDrawer/SockBot/blob/043f7e9aa9ec12250889fd825ddcf86709b095a3/lib/commands.js#L641-L663
train
SockDrawer/SockBot
lib/commands.js
onComplete
function onComplete(commands) { const content = commands.commands.map((command) => command.replyText) .filter((text) => (text || '').trim()) .join('\n\n---\n\n'); if (!content) { return Promise.resolve(); } return commands._replyFn(content); }
javascript
function onComplete(commands) { const content = commands.commands.map((command) => command.replyText) .filter((text) => (text || '').trim()) .join('\n\n---\n\n'); if (!content) { return Promise.resolve(); } return commands._replyFn(content); }
[ "function", "onComplete", "(", "commands", ")", "{", "const", "content", "=", "commands", ".", "commands", ".", "map", "(", "(", "command", ")", "=>", "command", ".", "replyText", ")", ".", "filter", "(", "(", "text", ")", "=>", "(", "text", "||", "''", ")", ".", "trim", "(", ")", ")", ".", "join", "(", "'\\n\\n---\\n\\n'", ")", ";", "\\n", "\\n", "}" ]
Handle Commands object once execution is complete. Post a reply if `replyText` of any contained command is non empty @private @param {Commands} commands Commands that have completed execution @returns {Promise} Resolves when after execution processing is complete
[ "Handle", "Commands", "object", "once", "execution", "is", "complete", "." ]
043f7e9aa9ec12250889fd825ddcf86709b095a3
https://github.com/SockDrawer/SockBot/blob/043f7e9aa9ec12250889fd825ddcf86709b095a3/lib/commands.js#L675-L683
train
SockDrawer/SockBot
lib/commands.js
onError
function onError(reason, commands) { if (typeof reason !== 'string' && typeof reason.message === 'string') { reason = reason.message; } return commands._replyFn(`An unexpected error \`${reason}\` occured and your commands could not be processed!`); }
javascript
function onError(reason, commands) { if (typeof reason !== 'string' && typeof reason.message === 'string') { reason = reason.message; } return commands._replyFn(`An unexpected error \`${reason}\` occured and your commands could not be processed!`); }
[ "function", "onError", "(", "reason", ",", "commands", ")", "{", "if", "(", "typeof", "reason", "!==", "'string'", "&&", "typeof", "reason", ".", "message", "===", "'string'", ")", "{", "reason", "=", "reason", ".", "message", ";", "}", "return", "commands", ".", "_replyFn", "(", "`", "\\`", "${", "reason", "}", "\\`", "`", ")", ";", "}" ]
Handle Commands object that error'd durring execution Post an error message in reply to post @private @param {string} reason Error Reason @param {Commands} commands Commands that errored @returns {Promise} Resolves after onError steps have completed
[ "Handle", "Commands", "object", "that", "error", "d", "durring", "execution" ]
043f7e9aa9ec12250889fd825ddcf86709b095a3
https://github.com/SockDrawer/SockBot/blob/043f7e9aa9ec12250889fd825ddcf86709b095a3/lib/commands.js#L696-L701
train
SockDrawer/SockBot
lib/commands.js
defaultHandler
function defaultHandler(command) { debug(`executing default handler for unrecognized command ${command.commandText}`); if (!command.mention) { command.reply(`Command \`${command.command}\` is not recognized`); } return Promise.resolve(); }
javascript
function defaultHandler(command) { debug(`executing default handler for unrecognized command ${command.commandText}`); if (!command.mention) { command.reply(`Command \`${command.command}\` is not recognized`); } return Promise.resolve(); }
[ "function", "defaultHandler", "(", "command", ")", "{", "debug", "(", "`", "${", "command", ".", "commandText", "}", "`", ")", ";", "if", "(", "!", "command", ".", "mention", ")", "{", "command", ".", "reply", "(", "`", "\\`", "${", "command", ".", "command", "}", "\\`", "`", ")", ";", "}", "return", "Promise", ".", "resolve", "(", ")", ";", "}" ]
Default Handler for unknown commands Post an error reply only if command is not a mention command @private @param {Command} command Unknown Command @returns {Promise} Resolves after action is taken
[ "Default", "Handler", "for", "unknown", "commands" ]
043f7e9aa9ec12250889fd825ddcf86709b095a3
https://github.com/SockDrawer/SockBot/blob/043f7e9aa9ec12250889fd825ddcf86709b095a3/lib/commands.js#L729-L735
train
SockDrawer/SockBot
lib/commands.js
cmdHelp
function cmdHelp(command) { let ext = ''; if (command.args && command.args.length > 0) { ext = command.args.join(' '); } if (ext && helpTopics[ext]) { const txt = `Help topic for \`${ext}\`\n\n${helpTopics[ext]}` + '\n\nIssue the `help` command without any parameters to see all available commands'; command.reply(txt); } else { const help = `${getCommandHelps()}\n\n\\* Help topic available.\n\nIssue the \`help\` command with an ` + 'available help topic as a parameter to read additonal help'; command.reply(help); } return Promise.resolve(); }
javascript
function cmdHelp(command) { let ext = ''; if (command.args && command.args.length > 0) { ext = command.args.join(' '); } if (ext && helpTopics[ext]) { const txt = `Help topic for \`${ext}\`\n\n${helpTopics[ext]}` + '\n\nIssue the `help` command without any parameters to see all available commands'; command.reply(txt); } else { const help = `${getCommandHelps()}\n\n\\* Help topic available.\n\nIssue the \`help\` command with an ` + 'available help topic as a parameter to read additonal help'; command.reply(help); } return Promise.resolve(); }
[ "function", "cmdHelp", "(", "command", ")", "{", "let", "ext", "=", "''", ";", "if", "(", "command", ".", "args", "&&", "command", ".", "args", ".", "length", ">", "0", ")", "{", "ext", "=", "command", ".", "args", ".", "join", "(", "' '", ")", ";", "}", "if", "(", "ext", "&&", "helpTopics", "[", "ext", "]", ")", "{", "const", "txt", "=", "`", "\\`", "${", "ext", "}", "\\`", "\\n", "\\n", "${", "helpTopics", "[", "ext", "]", "}", "`", "+", "'\\n\\nIssue the `help` command without any parameters to see all available commands'", ";", "\\n", "}", "else", "\\n", "command", ".", "reply", "(", "txt", ")", ";", "}" ]
Reply with help to the command !help @private @param {command} command help command @returns {Promise} Resolves after help text is generated
[ "Reply", "with", "help", "to", "the", "command", "!help" ]
043f7e9aa9ec12250889fd825ddcf86709b095a3
https://github.com/SockDrawer/SockBot/blob/043f7e9aa9ec12250889fd825ddcf86709b095a3/lib/commands.js#L745-L761
train
SockDrawer/SockBot
lib/commands.js
getCommandHelps
function getCommandHelps() { const cmds = {}, topics = {}, result = ['Registered commands:']; let keys = {}; Object.keys(handlers).map((key) => { keys[key] = 1; }); Object.keys(helpTopics).map((key) => { keys[key] = 1; }); Object.keys(keys).map((key) => { if (handlers[key]) { cmds[key] = handlers[key].help; if (helpTopics[key]) { cmds[key] += ' *'; } } else { topics[key] = 'Extended help topic'; } }); keys = Object.keys(cmds); keys.sort(); keys.forEach((cmd) => result.push(`${cmd}: ${cmds[cmd]}`)); keys = Object.keys(topics); if (keys.length) { result.push(''); result.push('Help Topics:'); keys.sort(); keys.forEach((topic) => result.push(`${topic}: ${topics[topic]}`)); } return result.join('\n'); }
javascript
function getCommandHelps() { const cmds = {}, topics = {}, result = ['Registered commands:']; let keys = {}; Object.keys(handlers).map((key) => { keys[key] = 1; }); Object.keys(helpTopics).map((key) => { keys[key] = 1; }); Object.keys(keys).map((key) => { if (handlers[key]) { cmds[key] = handlers[key].help; if (helpTopics[key]) { cmds[key] += ' *'; } } else { topics[key] = 'Extended help topic'; } }); keys = Object.keys(cmds); keys.sort(); keys.forEach((cmd) => result.push(`${cmd}: ${cmds[cmd]}`)); keys = Object.keys(topics); if (keys.length) { result.push(''); result.push('Help Topics:'); keys.sort(); keys.forEach((topic) => result.push(`${topic}: ${topics[topic]}`)); } return result.join('\n'); }
[ "function", "getCommandHelps", "(", ")", "{", "const", "cmds", "=", "{", "}", ",", "topics", "=", "{", "}", ",", "result", "=", "[", "'Registered commands:'", "]", ";", "let", "keys", "=", "{", "}", ";", "Object", ".", "keys", "(", "handlers", ")", ".", "map", "(", "(", "key", ")", "=>", "{", "keys", "[", "key", "]", "=", "1", ";", "}", ")", ";", "Object", ".", "keys", "(", "helpTopics", ")", ".", "map", "(", "(", "key", ")", "=>", "{", "keys", "[", "key", "]", "=", "1", ";", "}", ")", ";", "Object", ".", "keys", "(", "keys", ")", ".", "map", "(", "(", "key", ")", "=>", "{", "if", "(", "handlers", "[", "key", "]", ")", "{", "cmds", "[", "key", "]", "=", "handlers", "[", "key", "]", ".", "help", ";", "if", "(", "helpTopics", "[", "key", "]", ")", "{", "cmds", "[", "key", "]", "+=", "' *'", ";", "}", "}", "else", "{", "topics", "[", "key", "]", "=", "'Extended help topic'", ";", "}", "}", ")", ";", "keys", "=", "Object", ".", "keys", "(", "cmds", ")", ";", "keys", ".", "sort", "(", ")", ";", "keys", ".", "forEach", "(", "(", "cmd", ")", "=>", "result", ".", "push", "(", "`", "${", "cmd", "}", "${", "cmds", "[", "cmd", "]", "}", "`", ")", ")", ";", "keys", "=", "Object", ".", "keys", "(", "topics", ")", ";", "if", "(", "keys", ".", "length", ")", "{", "result", ".", "push", "(", "''", ")", ";", "result", ".", "push", "(", "'Help Topics:'", ")", ";", "keys", ".", "sort", "(", ")", ";", "keys", ".", "forEach", "(", "(", "topic", ")", "=>", "result", ".", "push", "(", "`", "${", "topic", "}", "${", "topics", "[", "topic", "]", "}", "`", ")", ")", ";", "}", "return", "result", ".", "join", "(", "'\\n'", ")", ";", "}" ]
Get help text for commands @private @returns {string} Command help text
[ "Get", "help", "text", "for", "commands" ]
043f7e9aa9ec12250889fd825ddcf86709b095a3
https://github.com/SockDrawer/SockBot/blob/043f7e9aa9ec12250889fd825ddcf86709b095a3/lib/commands.js#L770-L802
train
SockDrawer/SockBot
lib/commands.js
checkAvailable
function checkAvailable(map, command, logType, logMsg) { if (map[command]) { const prefix = logType === 'error' ? 'ERROR' : 'WARNING'; forum.emit(logType, `${prefix}, ${command} is already registered: ${logMsg}`); return false; } return true; }
javascript
function checkAvailable(map, command, logType, logMsg) { if (map[command]) { const prefix = logType === 'error' ? 'ERROR' : 'WARNING'; forum.emit(logType, `${prefix}, ${command} is already registered: ${logMsg}`); return false; } return true; }
[ "function", "checkAvailable", "(", "map", ",", "command", ",", "logType", ",", "logMsg", ")", "{", "if", "(", "map", "[", "command", "]", ")", "{", "const", "prefix", "=", "logType", "===", "'error'", "?", "'ERROR'", ":", "'WARNING'", ";", "forum", ".", "emit", "(", "logType", ",", "`", "${", "prefix", "}", "${", "command", "}", "${", "logMsg", "}", "`", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Check the availability of a command @param {object} map A map of commands to check availability against @param {string} command Name of command to check @param {string} logType Type of log to log if command isn't available @param {string} logMsg Message to log if command is not available @returns {boolean} True if available, false otherwise
[ "Check", "the", "availability", "of", "a", "command" ]
043f7e9aa9ec12250889fd825ddcf86709b095a3
https://github.com/SockDrawer/SockBot/blob/043f7e9aa9ec12250889fd825ddcf86709b095a3/lib/commands.js#L813-L820
train
SockDrawer/SockBot
providers/nodebb/format.js
threeParts
function threeParts(before, item1, defaultItem1, middle, item2, after) { item2 = stringify(item2); item1 = stringify(item1); if (!item2) { return ''; } return before + (item1 || defaultItem1) + middle + item2 + after; }
javascript
function threeParts(before, item1, defaultItem1, middle, item2, after) { item2 = stringify(item2); item1 = stringify(item1); if (!item2) { return ''; } return before + (item1 || defaultItem1) + middle + item2 + after; }
[ "function", "threeParts", "(", "before", ",", "item1", ",", "defaultItem1", ",", "middle", ",", "item2", ",", "after", ")", "{", "item2", "=", "stringify", "(", "item2", ")", ";", "item1", "=", "stringify", "(", "item1", ")", ";", "if", "(", "!", "item2", ")", "{", "return", "''", ";", "}", "return", "before", "+", "(", "item1", "||", "defaultItem1", ")", "+", "middle", "+", "item2", "+", "after", ";", "}" ]
Construct a result consisting of two data points in three parts @private @param {string} before Prefix @param {*} item1 First part @param {string} defaultItem1 Value to use for item1 when item1 is falsy @param {string} middle part to go between item1 and item2 @param {*} item2 Second Part @param {string} after Suffix @returns {string} Formatted thing
[ "Construct", "a", "result", "consisting", "of", "two", "data", "points", "in", "three", "parts" ]
043f7e9aa9ec12250889fd825ddcf86709b095a3
https://github.com/SockDrawer/SockBot/blob/043f7e9aa9ec12250889fd825ddcf86709b095a3/providers/nodebb/format.js#L117-L124
train
ArnaudBuchholz/gpf-js
lost+found/src/pattern.js
function (state, char) { gpf.interfaces.ignoreParameter(state); gpf.interfaces.ignoreParameter(char); gpf.Error.abstract(); // return -1; }
javascript
function (state, char) { gpf.interfaces.ignoreParameter(state); gpf.interfaces.ignoreParameter(char); gpf.Error.abstract(); // return -1; }
[ "function", "(", "state", ",", "char", ")", "{", "gpf", ".", "interfaces", ".", "ignoreParameter", "(", "state", ")", ";", "gpf", ".", "interfaces", ".", "ignoreParameter", "(", "char", ")", ";", "gpf", ".", "Error", ".", "abstract", "(", ")", ";", "}" ]
item evaluation with a character @param {Object} state Free structure containing current state @param {String} char character to test the pattern with @return {Number} Matching result, see PatternItem.WRITE_xxx @abstract
[ "item", "evaluation", "with", "a", "character" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/pattern.js#L187-L192
train
ArnaudBuchholz/gpf-js
lost+found/src/pattern.js
function (char, chars) { var first, last; if ("^" === char) { this._exc = []; } else if ("]" === char) { if (this._inRange) { gpf.Error.patternInvalidSyntax(); } return true; } else if ("-" === char) { if (this._inRange || 0 === chars.length) { gpf.Error.patternInvalidSyntax(); } this._inRange = true; } else { if (this._inRange) { first = chars[chars.length - 1].charCodeAt(0); last = char.charCodeAt(0); while (--last > first) { chars.push(String.fromCharCode(last)); } chars.push(char); delete this._inRange; } else { // First char of a range chars.push(char); } } return false; }
javascript
function (char, chars) { var first, last; if ("^" === char) { this._exc = []; } else if ("]" === char) { if (this._inRange) { gpf.Error.patternInvalidSyntax(); } return true; } else if ("-" === char) { if (this._inRange || 0 === chars.length) { gpf.Error.patternInvalidSyntax(); } this._inRange = true; } else { if (this._inRange) { first = chars[chars.length - 1].charCodeAt(0); last = char.charCodeAt(0); while (--last > first) { chars.push(String.fromCharCode(last)); } chars.push(char); delete this._inRange; } else { // First char of a range chars.push(char); } } return false; }
[ "function", "(", "char", ",", "chars", ")", "{", "var", "first", ",", "last", ";", "if", "(", "\"^\"", "===", "char", ")", "{", "this", ".", "_exc", "=", "[", "]", ";", "}", "else", "if", "(", "\"]\"", "===", "char", ")", "{", "if", "(", "this", ".", "_inRange", ")", "{", "gpf", ".", "Error", ".", "patternInvalidSyntax", "(", ")", ";", "}", "return", "true", ";", "}", "else", "if", "(", "\"-\"", "===", "char", ")", "{", "if", "(", "this", ".", "_inRange", "||", "0", "===", "chars", ".", "length", ")", "{", "gpf", ".", "Error", ".", "patternInvalidSyntax", "(", ")", ";", "}", "this", ".", "_inRange", "=", "true", ";", "}", "else", "{", "if", "(", "this", ".", "_inRange", ")", "{", "first", "=", "chars", "[", "chars", ".", "length", "-", "1", "]", ".", "charCodeAt", "(", "0", ")", ";", "last", "=", "char", ".", "charCodeAt", "(", "0", ")", ";", "while", "(", "--", "last", ">", "first", ")", "{", "chars", ".", "push", "(", "String", ".", "fromCharCode", "(", "last", ")", ")", ";", "}", "chars", ".", "push", "(", "char", ")", ";", "delete", "this", ".", "_inRange", ";", "}", "else", "{", "chars", ".", "push", "(", "char", ")", ";", "}", "}", "return", "false", ";", "}" ]
Reduce the cyclomatic complexity of parse @param {String} char Character to parse @param {String[]} chars Character array of already parsed chars @return {Boolean} True means PARSE_PROCESSED_EOP, otherwise PARSE_PROCESSED is returned
[ "Reduce", "the", "cyclomatic", "complexity", "of", "parse" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/pattern.js#L309-L340
train
ArnaudBuchholz/gpf-js
lost+found/src/pattern.js
function (pos) { if (this._choice) { if (undefined === pos) { pos = this._items.length - 1; } return this._items[pos]; } return this._items; }
javascript
function (pos) { if (this._choice) { if (undefined === pos) { pos = this._items.length - 1; } return this._items[pos]; } return this._items; }
[ "function", "(", "pos", ")", "{", "if", "(", "this", ".", "_choice", ")", "{", "if", "(", "undefined", "===", "pos", ")", "{", "pos", "=", "this", ".", "_items", ".", "length", "-", "1", ";", "}", "return", "this", ".", "_items", "[", "pos", "]", ";", "}", "return", "this", ".", "_items", ";", "}" ]
Get the current list of items @param {Number} [pos=undefined] When choices, get the items at the given position (last one when undefined). Ignored otherwise. @return {PatternItem[]} @private
[ "Get", "the", "current", "list", "of", "items" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/pattern.js#L469-L477
train
ArnaudBuchholz/gpf-js
lost+found/src/pattern.js
function (char) { var parsedItem = this._parsedItem, result; if (parsedItem) { result = parsedItem.parse(char); if (bitTest(result, PatternItem.PARSE_END_OF_PATTERN)) { parsedItem.finalize(); this._parsedItem = null; // Remove the flag result = bitClear(result, PatternItem.PARSE_END_OF_PATTERN); } } else { result = 0; } return result; }
javascript
function (char) { var parsedItem = this._parsedItem, result; if (parsedItem) { result = parsedItem.parse(char); if (bitTest(result, PatternItem.PARSE_END_OF_PATTERN)) { parsedItem.finalize(); this._parsedItem = null; // Remove the flag result = bitClear(result, PatternItem.PARSE_END_OF_PATTERN); } } else { result = 0; } return result; }
[ "function", "(", "char", ")", "{", "var", "parsedItem", "=", "this", ".", "_parsedItem", ",", "result", ";", "if", "(", "parsedItem", ")", "{", "result", "=", "parsedItem", ".", "parse", "(", "char", ")", ";", "if", "(", "bitTest", "(", "result", ",", "PatternItem", ".", "PARSE_END_OF_PATTERN", ")", ")", "{", "parsedItem", ".", "finalize", "(", ")", ";", "this", ".", "_parsedItem", "=", "null", ";", "result", "=", "bitClear", "(", "result", ",", "PatternItem", ".", "PARSE_END_OF_PATTERN", ")", ";", "}", "}", "else", "{", "result", "=", "0", ";", "}", "return", "result", ";", "}" ]
Reduce the cyclomatic complexity of parse Process current item @param {String} char @return {Number} @private
[ "Reduce", "the", "cyclomatic", "complexity", "of", "parse", "Process", "current", "item" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/pattern.js#L512-L529
train
ArnaudBuchholz/gpf-js
lost+found/src/pattern.js
function (char) { var parsedItem = this._lastItem(); if ("*" === char) { parsedItem._min = 0; parsedItem._max = 0; } else if ("+" === char) { parsedItem._max = 0; } else if ("?" === char) { parsedItem._min = 0; } return PatternItem.PARSE_PROCESSED; }
javascript
function (char) { var parsedItem = this._lastItem(); if ("*" === char) { parsedItem._min = 0; parsedItem._max = 0; } else if ("+" === char) { parsedItem._max = 0; } else if ("?" === char) { parsedItem._min = 0; } return PatternItem.PARSE_PROCESSED; }
[ "function", "(", "char", ")", "{", "var", "parsedItem", "=", "this", ".", "_lastItem", "(", ")", ";", "if", "(", "\"*\"", "===", "char", ")", "{", "parsedItem", ".", "_min", "=", "0", ";", "parsedItem", ".", "_max", "=", "0", ";", "}", "else", "if", "(", "\"+\"", "===", "char", ")", "{", "parsedItem", ".", "_max", "=", "0", ";", "}", "else", "if", "(", "\"?\"", "===", "char", ")", "{", "parsedItem", ".", "_min", "=", "0", ";", "}", "return", "PatternItem", ".", "PARSE_PROCESSED", ";", "}" ]
Reduce the cyclomatic complexity of parse Process quantification char @param {String} char @return {Number} @private
[ "Reduce", "the", "cyclomatic", "complexity", "of", "parse", "Process", "quantification", "char" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/pattern.js#L539-L551
train
ArnaudBuchholz/gpf-js
lost+found/src/pattern.js
function (items) { var idx; idx = items.length; while (idx--) { if (0 !== items[idx].min()) { ++idx; break; } } return idx; }
javascript
function (items) { var idx; idx = items.length; while (idx--) { if (0 !== items[idx].min()) { ++idx; break; } } return idx; }
[ "function", "(", "items", ")", "{", "var", "idx", ";", "idx", "=", "items", ".", "length", ";", "while", "(", "idx", "--", ")", "{", "if", "(", "0", "!==", "items", "[", "idx", "]", ".", "min", "(", ")", ")", "{", "++", "idx", ";", "break", ";", "}", "}", "return", "idx", ";", "}" ]
Return the position from which all items can be optional @param {PatterItem[]} items @return {Number} @private
[ "Return", "the", "position", "from", "which", "all", "items", "can", "be", "optional" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/pattern.js#L560-L571
train
ArnaudBuchholz/gpf-js
lost+found/src/pattern.js
function (item, state) { state.count = 0; state.sub = {}; item.reset(state.sub); }
javascript
function (item, state) { state.count = 0; state.sub = {}; item.reset(state.sub); }
[ "function", "(", "item", ",", "state", ")", "{", "state", ".", "count", "=", "0", ";", "state", ".", "sub", "=", "{", "}", ";", "item", ".", "reset", "(", "state", ".", "sub", ")", ";", "}" ]
Reset for the provided item @param {PatternItem} item @param {Object} state @private
[ "Reset", "for", "the", "provided", "item" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/pattern.js#L580-L584
train
ArnaudBuchholz/gpf-js
lost+found/src/pattern.js
function (item, state, char) { if (state.count < item.min() // Not enough match // or at least two characters went through || state.length > state.matchingLength + 1) { // Terminal error return PatternItem.WRITE_NO_MATCH; } item = this._getItem(state, state.index + 1); if (null === item) { return PatternItem.WRITE_NO_MATCH; } ++state.index; this._reset(item, state); return this.write(state, char); // Try with this one }
javascript
function (item, state, char) { if (state.count < item.min() // Not enough match // or at least two characters went through || state.length > state.matchingLength + 1) { // Terminal error return PatternItem.WRITE_NO_MATCH; } item = this._getItem(state, state.index + 1); if (null === item) { return PatternItem.WRITE_NO_MATCH; } ++state.index; this._reset(item, state); return this.write(state, char); // Try with this one }
[ "function", "(", "item", ",", "state", ",", "char", ")", "{", "if", "(", "state", ".", "count", "<", "item", ".", "min", "(", ")", "||", "state", ".", "length", ">", "state", ".", "matchingLength", "+", "1", ")", "{", "return", "PatternItem", ".", "WRITE_NO_MATCH", ";", "}", "item", "=", "this", ".", "_getItem", "(", "state", ",", "state", ".", "index", "+", "1", ")", ";", "if", "(", "null", "===", "item", ")", "{", "return", "PatternItem", ".", "WRITE_NO_MATCH", ";", "}", "++", "state", ".", "index", ";", "this", ".", "_reset", "(", "item", ",", "state", ")", ";", "return", "this", ".", "write", "(", "state", ",", "char", ")", ";", "}" ]
Handles situation when current item does not match on char @param {PatternItem} item @param {Object} state @param {String} char @return {Number} write result @private
[ "Handles", "situation", "when", "current", "item", "does", "not", "match", "on", "char" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/pattern.js#L611-L625
train
ArnaudBuchholz/gpf-js
lost+found/src/pattern.js
function (item, state) { var nextItem = this._getItem(state, state.index + 1), optional; if (this._choice && -1 < state.choice) { optional = this._optionals[state.choice]; } else { optional = this._optionals[0]; } ++state.count; if (0 === item.max()) { // Unlimited this._reset(item, state); if (null !== nextItem && optional > state.index) { return PatternItem.WRITE_NEED_DATA; } else { // Last (or equivalent) so... return PatternItem.WRITE_MATCH; } } else if (state.count === item.max()) { if (null === nextItem) { return PatternItem.WRITE_FINAL_MATCH; } ++state.index; this._reset(nextItem, state); if (optional <= state.index) { return PatternItem.WRITE_MATCH; } } return PatternItem.WRITE_NEED_DATA; }
javascript
function (item, state) { var nextItem = this._getItem(state, state.index + 1), optional; if (this._choice && -1 < state.choice) { optional = this._optionals[state.choice]; } else { optional = this._optionals[0]; } ++state.count; if (0 === item.max()) { // Unlimited this._reset(item, state); if (null !== nextItem && optional > state.index) { return PatternItem.WRITE_NEED_DATA; } else { // Last (or equivalent) so... return PatternItem.WRITE_MATCH; } } else if (state.count === item.max()) { if (null === nextItem) { return PatternItem.WRITE_FINAL_MATCH; } ++state.index; this._reset(nextItem, state); if (optional <= state.index) { return PatternItem.WRITE_MATCH; } } return PatternItem.WRITE_NEED_DATA; }
[ "function", "(", "item", ",", "state", ")", "{", "var", "nextItem", "=", "this", ".", "_getItem", "(", "state", ",", "state", ".", "index", "+", "1", ")", ",", "optional", ";", "if", "(", "this", ".", "_choice", "&&", "-", "1", "<", "state", ".", "choice", ")", "{", "optional", "=", "this", ".", "_optionals", "[", "state", ".", "choice", "]", ";", "}", "else", "{", "optional", "=", "this", ".", "_optionals", "[", "0", "]", ";", "}", "++", "state", ".", "count", ";", "if", "(", "0", "===", "item", ".", "max", "(", ")", ")", "{", "this", ".", "_reset", "(", "item", ",", "state", ")", ";", "if", "(", "null", "!==", "nextItem", "&&", "optional", ">", "state", ".", "index", ")", "{", "return", "PatternItem", ".", "WRITE_NEED_DATA", ";", "}", "else", "{", "return", "PatternItem", ".", "WRITE_MATCH", ";", "}", "}", "else", "if", "(", "state", ".", "count", "===", "item", ".", "max", "(", ")", ")", "{", "if", "(", "null", "===", "nextItem", ")", "{", "return", "PatternItem", ".", "WRITE_FINAL_MATCH", ";", "}", "++", "state", ".", "index", ";", "this", ".", "_reset", "(", "nextItem", ",", "state", ")", ";", "if", "(", "optional", "<=", "state", ".", "index", ")", "{", "return", "PatternItem", ".", "WRITE_MATCH", ";", "}", "}", "return", "PatternItem", ".", "WRITE_NEED_DATA", ";", "}" ]
Handles situation when current item matches on char @param {PatternItem} item @return {Number} write result @private
[ "Handles", "situation", "when", "current", "item", "matches", "on", "char" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/pattern.js#L634-L664
train
ArnaudBuchholz/gpf-js
lost+found/src/pattern.js
function (pattern) { var parser = new PatternParser(); parser.parse(pattern, null); this._patternItem = parser.patternItem(); }
javascript
function (pattern) { var parser = new PatternParser(); parser.parse(pattern, null); this._patternItem = parser.patternItem(); }
[ "function", "(", "pattern", ")", "{", "var", "parser", "=", "new", "PatternParser", "(", ")", ";", "parser", ".", "parse", "(", "pattern", ",", "null", ")", ";", "this", ".", "_patternItem", "=", "parser", ".", "patternItem", "(", ")", ";", "}" ]
Constructor, check and compile the pattern @param {String} pattern
[ "Constructor", "check", "and", "compile", "the", "pattern" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/pattern.js#L1036-L1041
train
ArnaudBuchholz/gpf-js
lost+found/src/base.js
_gpfNodeBuffer2JsArray
function _gpfNodeBuffer2JsArray (buffer) { var result = [], len = buffer.length, idx; for (idx = 0; idx < len; ++idx) { result.push(buffer.readUInt8(idx)); } return result; }
javascript
function _gpfNodeBuffer2JsArray (buffer) { var result = [], len = buffer.length, idx; for (idx = 0; idx < len; ++idx) { result.push(buffer.readUInt8(idx)); } return result; }
[ "function", "_gpfNodeBuffer2JsArray", "(", "buffer", ")", "{", "var", "result", "=", "[", "]", ",", "len", "=", "buffer", ".", "length", ",", "idx", ";", "for", "(", "idx", "=", "0", ";", "idx", "<", "len", ";", "++", "idx", ")", "{", "result", ".", "push", "(", "buffer", ".", "readUInt8", "(", "idx", ")", ")", ";", "}", "return", "result", ";", "}" ]
region NodeJS helpers Converts a NodeJS buffer into a native array containing unsigned bytes @param {Buffer} buffer @return {Number[]}
[ "region", "NodeJS", "helpers", "Converts", "a", "NodeJS", "buffer", "into", "a", "native", "array", "containing", "unsigned", "bytes" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/base.js#L57-L65
train
ArnaudBuchholz/gpf-js
lost+found/src/websvr.js
function (statusCode, text) { var resp = this._response; resp.writeHead(statusCode, {"Content-Type": "text/plain"}); resp.write([ "port : " + this._options.port, "method : " + this._request.method, "url : " + this._request.url, "root : " + this._options.root, "path : " + this._filePath, "headers : " + JSON.stringify(this._request.headers, null, "\t\t"), text ].join("\n")); resp.end(); }
javascript
function (statusCode, text) { var resp = this._response; resp.writeHead(statusCode, {"Content-Type": "text/plain"}); resp.write([ "port : " + this._options.port, "method : " + this._request.method, "url : " + this._request.url, "root : " + this._options.root, "path : " + this._filePath, "headers : " + JSON.stringify(this._request.headers, null, "\t\t"), text ].join("\n")); resp.end(); }
[ "function", "(", "statusCode", ",", "text", ")", "{", "var", "resp", "=", "this", ".", "_response", ";", "resp", ".", "writeHead", "(", "statusCode", ",", "{", "\"Content-Type\"", ":", "\"text/plain\"", "}", ")", ";", "resp", ".", "write", "(", "[", "\"port : \"", "+", "this", ".", "_options", ".", "port", ",", "\"method : \"", "+", "this", ".", "_request", ".", "method", ",", "\"url : \"", "+", "this", ".", "_request", ".", "url", ",", "\"root : \"", "+", "this", ".", "_options", ".", "root", ",", "\"path : \"", "+", "this", ".", "_filePath", ",", "\"headers : \"", "+", "JSON", ".", "stringify", "(", "this", ".", "_request", ".", "headers", ",", "null", ",", "\"\\t\\t\"", ")", ",", "\\t", "]", ".", "\\t", "text", ")", ";", "join", "}" ]
Generates a PLAIN response to the server @param {Number} statusCode @param {String} text
[ "Generates", "a", "PLAIN", "response", "to", "the", "server" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/websvr.js#L203-L217
train
ArnaudBuchholz/gpf-js
lost+found/src/websvr.js
function (filePath) { var me = this, extName = _path.extname(filePath).toLowerCase(), size, stream; _fs.stat(filePath, function (err, stats) { var mimeType; if (err) { me._response.plain(500, "Unable to access file (" + err + ")"); return; } if (stats.isDirectory()) { me._response.plain(200, "Directory."); return; } else if (!stats.isFile()) { me._response.plain(200, "Not a file."); return; } size = stats.size; mimeType = gpf.http.getMimeType(extName); if (me._options.verbose) { console.log("\tMime type : " + mimeType); console.log("\tFile size : " + size); } me._response.writeHead(200, { "content-type": mimeType, "content-length": size }); stream = _fs.createReadStream(filePath); //stream.on("data", function (chunk) { // if (!me._response.write(chunk)) { // stream.pause(); // me._response.once("drain", function () { // stream.resume(); // }); // } //}); stream.on("end", function () { if (me._options.verbose) { console.log("\tEnd t+: " + ((new Date()) - me._startTimeStamp) + "ms"); } me._response.statusCode = 200; me._response.end(); }); stream.pipe(me._response); }); }
javascript
function (filePath) { var me = this, extName = _path.extname(filePath).toLowerCase(), size, stream; _fs.stat(filePath, function (err, stats) { var mimeType; if (err) { me._response.plain(500, "Unable to access file (" + err + ")"); return; } if (stats.isDirectory()) { me._response.plain(200, "Directory."); return; } else if (!stats.isFile()) { me._response.plain(200, "Not a file."); return; } size = stats.size; mimeType = gpf.http.getMimeType(extName); if (me._options.verbose) { console.log("\tMime type : " + mimeType); console.log("\tFile size : " + size); } me._response.writeHead(200, { "content-type": mimeType, "content-length": size }); stream = _fs.createReadStream(filePath); //stream.on("data", function (chunk) { // if (!me._response.write(chunk)) { // stream.pause(); // me._response.once("drain", function () { // stream.resume(); // }); // } //}); stream.on("end", function () { if (me._options.verbose) { console.log("\tEnd t+: " + ((new Date()) - me._startTimeStamp) + "ms"); } me._response.statusCode = 200; me._response.end(); }); stream.pipe(me._response); }); }
[ "function", "(", "filePath", ")", "{", "var", "me", "=", "this", ",", "extName", "=", "_path", ".", "extname", "(", "filePath", ")", ".", "toLowerCase", "(", ")", ",", "size", ",", "stream", ";", "_fs", ".", "stat", "(", "filePath", ",", "function", "(", "err", ",", "stats", ")", "{", "var", "mimeType", ";", "if", "(", "err", ")", "{", "me", ".", "_response", ".", "plain", "(", "500", ",", "\"Unable to access file (\"", "+", "err", "+", "\")\"", ")", ";", "return", ";", "}", "if", "(", "stats", ".", "isDirectory", "(", ")", ")", "{", "me", ".", "_response", ".", "plain", "(", "200", ",", "\"Directory.\"", ")", ";", "return", ";", "}", "else", "if", "(", "!", "stats", ".", "isFile", "(", ")", ")", "{", "me", ".", "_response", ".", "plain", "(", "200", ",", "\"Not a file.\"", ")", ";", "return", ";", "}", "size", "=", "stats", ".", "size", ";", "mimeType", "=", "gpf", ".", "http", ".", "getMimeType", "(", "extName", ")", ";", "if", "(", "me", ".", "_options", ".", "verbose", ")", "{", "console", ".", "log", "(", "\"\\tMime type : \"", "+", "\\t", ")", ";", "mimeType", "}", "console", ".", "log", "(", "\"\\tFile size : \"", "+", "\\t", ")", ";", "size", "me", ".", "_response", ".", "writeHead", "(", "200", ",", "{", "\"content-type\"", ":", "mimeType", ",", "\"content-length\"", ":", "size", "}", ")", ";", "stream", "=", "_fs", ".", "createReadStream", "(", "filePath", ")", ";", "}", ")", ";", "}" ]
Generates a response that contains the specified file @param {String} filePath @private
[ "Generates", "a", "response", "that", "contains", "the", "specified", "file" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/websvr.js#L225-L275
train
ArnaudBuchholz/gpf-js
lost+found/src/encoding.js
function (input, encoding) { var module = _gpfEncodings[encoding]; if (undefined === module) { gpf.Error.encodingNotSupported(); } return new EncoderStream(module[0], input); }
javascript
function (input, encoding) { var module = _gpfEncodings[encoding]; if (undefined === module) { gpf.Error.encodingNotSupported(); } return new EncoderStream(module[0], input); }
[ "function", "(", "input", ",", "encoding", ")", "{", "var", "module", "=", "_gpfEncodings", "[", "encoding", "]", ";", "if", "(", "undefined", "===", "module", ")", "{", "gpf", ".", "Error", ".", "encodingNotSupported", "(", ")", ";", "}", "return", "new", "EncoderStream", "(", "module", "[", "0", "]", ",", "input", ")", ";", "}" ]
Create a encoder to convert an input text stream into an output binary buffer. @param {gpf.interfaces.IReadableStream} input @param {String} encoding @return {gpf.interfaces.IReadableStream}
[ "Create", "a", "encoder", "to", "convert", "an", "input", "text", "stream", "into", "an", "output", "binary", "buffer", "." ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/encoding.js#L145-L151
train
ArnaudBuchholz/gpf-js
lost+found/src/path/matcher.js
_gpfPathMatchApply
function _gpfPathMatchApply (pathMatcher) { /*jshint validthis:true*/ if (pathMatcher.match(this.parts)) { this.result = !pathMatcher.negative; return false; // Stop the main loop } return _gpfPathMatchAfterApplyNonMatching.call(this, pathMatcher); }
javascript
function _gpfPathMatchApply (pathMatcher) { /*jshint validthis:true*/ if (pathMatcher.match(this.parts)) { this.result = !pathMatcher.negative; return false; // Stop the main loop } return _gpfPathMatchAfterApplyNonMatching.call(this, pathMatcher); }
[ "function", "_gpfPathMatchApply", "(", "pathMatcher", ")", "{", "if", "(", "pathMatcher", ".", "match", "(", "this", ".", "parts", ")", ")", "{", "this", ".", "result", "=", "!", "pathMatcher", ".", "negative", ";", "return", "false", ";", "}", "return", "_gpfPathMatchAfterApplyNonMatching", ".", "call", "(", "this", ",", "pathMatcher", ")", ";", "}" ]
Match a path item @param pathMatcher @this An object containing - {String[]} parts the path being tested split in parts - {Boolean} [result=undefined] result the result
[ "Match", "a", "path", "item" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/path/matcher.js#L124-L131
train
ArnaudBuchholz/gpf-js
lost+found/src/path/matcher.js
_gpfPathMatch
function _gpfPathMatch (pattern, path) { var parts = _gpfPathDecompose(path), matchers = _gpfPathMatchCompilePatterns(pattern), scope = { parts: parts }; matchers.every(_gpfPathMatchApply, scope); return scope.result; }
javascript
function _gpfPathMatch (pattern, path) { var parts = _gpfPathDecompose(path), matchers = _gpfPathMatchCompilePatterns(pattern), scope = { parts: parts }; matchers.every(_gpfPathMatchApply, scope); return scope.result; }
[ "function", "_gpfPathMatch", "(", "pattern", ",", "path", ")", "{", "var", "parts", "=", "_gpfPathDecompose", "(", "path", ")", ",", "matchers", "=", "_gpfPathMatchCompilePatterns", "(", "pattern", ")", ",", "scope", "=", "{", "parts", ":", "parts", "}", ";", "matchers", ".", "every", "(", "_gpfPathMatchApply", ",", "scope", ")", ";", "return", "scope", ".", "result", ";", "}" ]
Match the pattern with the path @param {Array|String} pattern @param {String} path @return {Boolean|undefined}
[ "Match", "the", "pattern", "with", "the", "path" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/path/matcher.js#L139-L147
train
ArnaudBuchholz/gpf-js
lost+found/src/path/matcher.js
function (context) { var parts = context.parts, partsLen = parts.length, startPos = context.startPos, array = this.start, len = array.length, idx; for (idx = 0; idx < len; ++idx) { if (this._matchName(array[idx], parts[startPos])) { if (++startPos >= partsLen) { // Match if last part of the start and no end if (idx === len - 1 && !this.end) { return _GPF_PATHMATCH_OK; } return _GPF_PATHMATCH_KO; } } else { return _GPF_PATHMATCH_KO; } } context.startPos = startPos; return _GPF_PATHMATCH_UNKNOWN; }
javascript
function (context) { var parts = context.parts, partsLen = parts.length, startPos = context.startPos, array = this.start, len = array.length, idx; for (idx = 0; idx < len; ++idx) { if (this._matchName(array[idx], parts[startPos])) { if (++startPos >= partsLen) { // Match if last part of the start and no end if (idx === len - 1 && !this.end) { return _GPF_PATHMATCH_OK; } return _GPF_PATHMATCH_KO; } } else { return _GPF_PATHMATCH_KO; } } context.startPos = startPos; return _GPF_PATHMATCH_UNKNOWN; }
[ "function", "(", "context", ")", "{", "var", "parts", "=", "context", ".", "parts", ",", "partsLen", "=", "parts", ".", "length", ",", "startPos", "=", "context", ".", "startPos", ",", "array", "=", "this", ".", "start", ",", "len", "=", "array", ".", "length", ",", "idx", ";", "for", "(", "idx", "=", "0", ";", "idx", "<", "len", ";", "++", "idx", ")", "{", "if", "(", "this", ".", "_matchName", "(", "array", "[", "idx", "]", ",", "parts", "[", "startPos", "]", ")", ")", "{", "if", "(", "++", "startPos", ">=", "partsLen", ")", "{", "if", "(", "idx", "===", "len", "-", "1", "&&", "!", "this", ".", "end", ")", "{", "return", "_GPF_PATHMATCH_OK", ";", "}", "return", "_GPF_PATHMATCH_KO", ";", "}", "}", "else", "{", "return", "_GPF_PATHMATCH_KO", ";", "}", "}", "context", ".", "startPos", "=", "startPos", ";", "return", "_GPF_PATHMATCH_UNKNOWN", ";", "}" ]
Match using this.start
[ "Match", "using", "this", ".", "start" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/path/matcher.js#L227-L249
train
ArnaudBuchholz/gpf-js
lost+found/src/path/matcher.js
function (context) { var parts = context.parts, startPos = context.startPos, endPos = parts.length - 1, array = this.end, len = array.length, idx; for (idx = 0; idx < len; ++idx) { if (-1 < endPos && this._matchName(array[idx], parts[endPos])) { if (endPos-- < startPos) { return _GPF_PATHMATCH_KO; } } else { return _GPF_PATHMATCH_KO; } } return _GPF_PATHMATCH_UNKNOWN; }
javascript
function (context) { var parts = context.parts, startPos = context.startPos, endPos = parts.length - 1, array = this.end, len = array.length, idx; for (idx = 0; idx < len; ++idx) { if (-1 < endPos && this._matchName(array[idx], parts[endPos])) { if (endPos-- < startPos) { return _GPF_PATHMATCH_KO; } } else { return _GPF_PATHMATCH_KO; } } return _GPF_PATHMATCH_UNKNOWN; }
[ "function", "(", "context", ")", "{", "var", "parts", "=", "context", ".", "parts", ",", "startPos", "=", "context", ".", "startPos", ",", "endPos", "=", "parts", ".", "length", "-", "1", ",", "array", "=", "this", ".", "end", ",", "len", "=", "array", ".", "length", ",", "idx", ";", "for", "(", "idx", "=", "0", ";", "idx", "<", "len", ";", "++", "idx", ")", "{", "if", "(", "-", "1", "<", "endPos", "&&", "this", ".", "_matchName", "(", "array", "[", "idx", "]", ",", "parts", "[", "endPos", "]", ")", ")", "{", "if", "(", "endPos", "--", "<", "startPos", ")", "{", "return", "_GPF_PATHMATCH_KO", ";", "}", "}", "else", "{", "return", "_GPF_PATHMATCH_KO", ";", "}", "}", "return", "_GPF_PATHMATCH_UNKNOWN", ";", "}" ]
Match using this.end
[ "Match", "using", "this", ".", "end" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/path/matcher.js#L260-L277
train
ArnaudBuchholz/gpf-js
lost+found/src/path/matcher.js
function (parts) { var result, context = { parts: parts, startPos: 0 }; result = this._matchStart(context) || this._matchEnd(context); return result !== _GPF_PATHMATCH_KO; }
javascript
function (parts) { var result, context = { parts: parts, startPos: 0 }; result = this._matchStart(context) || this._matchEnd(context); return result !== _GPF_PATHMATCH_KO; }
[ "function", "(", "parts", ")", "{", "var", "result", ",", "context", "=", "{", "parts", ":", "parts", ",", "startPos", ":", "0", "}", ";", "result", "=", "this", ".", "_matchStart", "(", "context", ")", "||", "this", ".", "_matchEnd", "(", "context", ")", ";", "return", "result", "!==", "_GPF_PATHMATCH_KO", ";", "}" ]
Matches the provided path @param {String[]} parts @return {Boolean}
[ "Matches", "the", "provided", "path" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/path/matcher.js#L285-L293
train
popeindustries/buddy
lib/plugins/js/babel-plugin-transform-flatten.js
renameRootDeclarations
function renameRootDeclarations(path, namespace) { const { scope } = path; const oldName = path.node.name; const rootScope = scope.getProgramParent(); const isRootScope = scope === rootScope; const newName = `${namespace}${oldName}`; let binding = scope.getBinding(oldName); if (binding) { if (!path.isReferenced() && shouldRenameDeclaration(oldName, path, binding, rootScope)) { path.node.name = newName; if (!isRootScope) { const declarationParent = getDeclarationParent(path); // Function declaration defines own scope, so switch to parent if (declarationParent.isFunctionDeclaration()) { binding = declarationParent.scope.parent.getBinding(oldName); } } // Handle references if (binding.referenced) { binding.referencePaths.forEach(path => { path.node.name = newName; }); } } } }
javascript
function renameRootDeclarations(path, namespace) { const { scope } = path; const oldName = path.node.name; const rootScope = scope.getProgramParent(); const isRootScope = scope === rootScope; const newName = `${namespace}${oldName}`; let binding = scope.getBinding(oldName); if (binding) { if (!path.isReferenced() && shouldRenameDeclaration(oldName, path, binding, rootScope)) { path.node.name = newName; if (!isRootScope) { const declarationParent = getDeclarationParent(path); // Function declaration defines own scope, so switch to parent if (declarationParent.isFunctionDeclaration()) { binding = declarationParent.scope.parent.getBinding(oldName); } } // Handle references if (binding.referenced) { binding.referencePaths.forEach(path => { path.node.name = newName; }); } } } }
[ "function", "renameRootDeclarations", "(", "path", ",", "namespace", ")", "{", "const", "{", "scope", "}", "=", "path", ";", "const", "oldName", "=", "path", ".", "node", ".", "name", ";", "const", "rootScope", "=", "scope", ".", "getProgramParent", "(", ")", ";", "const", "isRootScope", "=", "scope", "===", "rootScope", ";", "const", "newName", "=", "`", "${", "namespace", "}", "${", "oldName", "}", "`", ";", "let", "binding", "=", "scope", ".", "getBinding", "(", "oldName", ")", ";", "if", "(", "binding", ")", "{", "if", "(", "!", "path", ".", "isReferenced", "(", ")", "&&", "shouldRenameDeclaration", "(", "oldName", ",", "path", ",", "binding", ",", "rootScope", ")", ")", "{", "path", ".", "node", ".", "name", "=", "newName", ";", "if", "(", "!", "isRootScope", ")", "{", "const", "declarationParent", "=", "getDeclarationParent", "(", "path", ")", ";", "if", "(", "declarationParent", ".", "isFunctionDeclaration", "(", ")", ")", "{", "binding", "=", "declarationParent", ".", "scope", ".", "parent", ".", "getBinding", "(", "oldName", ")", ";", "}", "}", "if", "(", "binding", ".", "referenced", ")", "{", "binding", ".", "referencePaths", ".", "forEach", "(", "path", "=>", "{", "path", ".", "node", ".", "name", "=", "newName", ";", "}", ")", ";", "}", "}", "}", "}" ]
Rename declarations and references in global scope @param {NodePath} path @param {String} namespace
[ "Rename", "declarations", "and", "references", "in", "global", "scope" ]
c38afc2e6915743eb6cfcf5aba59a8699142c7a5
https://github.com/popeindustries/buddy/blob/c38afc2e6915743eb6cfcf5aba59a8699142c7a5/lib/plugins/js/babel-plugin-transform-flatten.js#L64-L91
train
popeindustries/buddy
lib/plugins/js/babel-plugin-transform-flatten.js
shouldRenameDeclaration
function shouldRenameDeclaration(name, path, binding, rootScope) { const isRootScope = path.scope === rootScope; const isGlobal = isRootScope && name in rootScope.globals; const program = rootScope.path; if (isGlobal) return false; if (!isRootScope) { const functionParent = path.getFunctionParent(); const declarationParent = getDeclarationParent(path); // Bail if not a declaration or is property/key of object if (!declarationParent || isPropertyOrKey(path)) return false; if (declarationParent.isBlockScoped()) { // Handle function declaration (which defines it's own scope) if (declarationParent.isFunctionDeclaration()) { return declarationParent.parentPath.scope === rootScope && declarationParent.node.id === path.node; } // Skip let/const in block scope return false; // Handle re-assignment of root bound declaration (ignore function expressions) } else if (declarationParent.isAssignmentExpression() && !path.parentPath.isFunctionExpression()) { const declarationBinding = declarationParent.scope.getBinding(name); return declarationBinding ? declarationBinding.scope === rootScope : false; // Skip if in function scope } else if (functionParent !== program) { return false; } } // Skip if property or key of object return !isPropertyOrKey(path); }
javascript
function shouldRenameDeclaration(name, path, binding, rootScope) { const isRootScope = path.scope === rootScope; const isGlobal = isRootScope && name in rootScope.globals; const program = rootScope.path; if (isGlobal) return false; if (!isRootScope) { const functionParent = path.getFunctionParent(); const declarationParent = getDeclarationParent(path); // Bail if not a declaration or is property/key of object if (!declarationParent || isPropertyOrKey(path)) return false; if (declarationParent.isBlockScoped()) { // Handle function declaration (which defines it's own scope) if (declarationParent.isFunctionDeclaration()) { return declarationParent.parentPath.scope === rootScope && declarationParent.node.id === path.node; } // Skip let/const in block scope return false; // Handle re-assignment of root bound declaration (ignore function expressions) } else if (declarationParent.isAssignmentExpression() && !path.parentPath.isFunctionExpression()) { const declarationBinding = declarationParent.scope.getBinding(name); return declarationBinding ? declarationBinding.scope === rootScope : false; // Skip if in function scope } else if (functionParent !== program) { return false; } } // Skip if property or key of object return !isPropertyOrKey(path); }
[ "function", "shouldRenameDeclaration", "(", "name", ",", "path", ",", "binding", ",", "rootScope", ")", "{", "const", "isRootScope", "=", "path", ".", "scope", "===", "rootScope", ";", "const", "isGlobal", "=", "isRootScope", "&&", "name", "in", "rootScope", ".", "globals", ";", "const", "program", "=", "rootScope", ".", "path", ";", "if", "(", "isGlobal", ")", "return", "false", ";", "if", "(", "!", "isRootScope", ")", "{", "const", "functionParent", "=", "path", ".", "getFunctionParent", "(", ")", ";", "const", "declarationParent", "=", "getDeclarationParent", "(", "path", ")", ";", "if", "(", "!", "declarationParent", "||", "isPropertyOrKey", "(", "path", ")", ")", "return", "false", ";", "if", "(", "declarationParent", ".", "isBlockScoped", "(", ")", ")", "{", "if", "(", "declarationParent", ".", "isFunctionDeclaration", "(", ")", ")", "{", "return", "declarationParent", ".", "parentPath", ".", "scope", "===", "rootScope", "&&", "declarationParent", ".", "node", ".", "id", "===", "path", ".", "node", ";", "}", "return", "false", ";", "}", "else", "if", "(", "declarationParent", ".", "isAssignmentExpression", "(", ")", "&&", "!", "path", ".", "parentPath", ".", "isFunctionExpression", "(", ")", ")", "{", "const", "declarationBinding", "=", "declarationParent", ".", "scope", ".", "getBinding", "(", "name", ")", ";", "return", "declarationBinding", "?", "declarationBinding", ".", "scope", "===", "rootScope", ":", "false", ";", "}", "else", "if", "(", "functionParent", "!==", "program", ")", "{", "return", "false", ";", "}", "}", "return", "!", "isPropertyOrKey", "(", "path", ")", ";", "}" ]
Determine if declaration 'path' should be renamed @param {String} name @param {NodePath} path @param {Binding} binding @param {Scope} rootScope @returns {Boolean}
[ "Determine", "if", "declaration", "path", "should", "be", "renamed" ]
c38afc2e6915743eb6cfcf5aba59a8699142c7a5
https://github.com/popeindustries/buddy/blob/c38afc2e6915743eb6cfcf5aba59a8699142c7a5/lib/plugins/js/babel-plugin-transform-flatten.js#L101-L135
train
popeindustries/buddy
lib/plugins/js/babel-plugin-transform-flatten.js
getDeclarationParent
function getDeclarationParent(path) { do { if ( path.isFunctionDeclaration() || path.isVariableDeclaration() || path.isClassDeclaration() || path.isAssignmentExpression() ) { return path; } } while ((path = path.parentPath)); }
javascript
function getDeclarationParent(path) { do { if ( path.isFunctionDeclaration() || path.isVariableDeclaration() || path.isClassDeclaration() || path.isAssignmentExpression() ) { return path; } } while ((path = path.parentPath)); }
[ "function", "getDeclarationParent", "(", "path", ")", "{", "do", "{", "if", "(", "path", ".", "isFunctionDeclaration", "(", ")", "||", "path", ".", "isVariableDeclaration", "(", ")", "||", "path", ".", "isClassDeclaration", "(", ")", "||", "path", ".", "isAssignmentExpression", "(", ")", ")", "{", "return", "path", ";", "}", "}", "while", "(", "(", "path", "=", "path", ".", "parentPath", ")", ")", ";", "}" ]
Retrieve declaration parent for 'path' @param {NodePath} path @returns {NodePath}
[ "Retrieve", "declaration", "parent", "for", "path" ]
c38afc2e6915743eb6cfcf5aba59a8699142c7a5
https://github.com/popeindustries/buddy/blob/c38afc2e6915743eb6cfcf5aba59a8699142c7a5/lib/plugins/js/babel-plugin-transform-flatten.js#L142-L153
train
popeindustries/buddy
lib/plugins/js/babel-plugin-transform-flatten.js
isPropertyOrKey
function isPropertyOrKey(path) { return path.parentPath.get('key') === path || path.parentPath.get('property') === path; }
javascript
function isPropertyOrKey(path) { return path.parentPath.get('key') === path || path.parentPath.get('property') === path; }
[ "function", "isPropertyOrKey", "(", "path", ")", "{", "return", "path", ".", "parentPath", ".", "get", "(", "'key'", ")", "===", "path", "||", "path", ".", "parentPath", ".", "get", "(", "'property'", ")", "===", "path", ";", "}" ]
Determine if 'path' is an key or property of another object @param {NodePath} path @returns {Boolean}
[ "Determine", "if", "path", "is", "an", "key", "or", "property", "of", "another", "object" ]
c38afc2e6915743eb6cfcf5aba59a8699142c7a5
https://github.com/popeindustries/buddy/blob/c38afc2e6915743eb6cfcf5aba59a8699142c7a5/lib/plugins/js/babel-plugin-transform-flatten.js#L160-L162
train
simonepri/env-dot-prop
index.js
transform
function transform(str, from, to) { let out = ''; const escaped = '\\' + to; for (let i = 0; i < str.length; i++) { if (str[i] === to) { out += escaped; } else if (str[i] === from) { out += to; } else if (str[i] === '\\' && i + 1 < str.length && str[i + 1] === from) { out += from; i++; } else { out += str[i]; } } return out; }
javascript
function transform(str, from, to) { let out = ''; const escaped = '\\' + to; for (let i = 0; i < str.length; i++) { if (str[i] === to) { out += escaped; } else if (str[i] === from) { out += to; } else if (str[i] === '\\' && i + 1 < str.length && str[i + 1] === from) { out += from; i++; } else { out += str[i]; } } return out; }
[ "function", "transform", "(", "str", ",", "from", ",", "to", ")", "{", "let", "out", "=", "''", ";", "const", "escaped", "=", "'\\\\'", "+", "\\\\", ";", "to", "for", "(", "let", "i", "=", "0", ";", "i", "<", "str", ".", "length", ";", "i", "++", ")", "{", "if", "(", "str", "[", "i", "]", "===", "to", ")", "{", "out", "+=", "escaped", ";", "}", "else", "if", "(", "str", "[", "i", "]", "===", "from", ")", "{", "out", "+=", "to", ";", "}", "else", "if", "(", "str", "[", "i", "]", "===", "'\\\\'", "&&", "\\\\", "&&", "i", "+", "1", "<", "str", ".", "length", ")", "str", "[", "i", "+", "1", "]", "===", "from", "else", "{", "out", "+=", "from", ";", "i", "++", ";", "}", "}", "}" ]
Replace a character in the string provided taking care of the escaped chars. @private @param {string} str A string. @param {from} from A character. @param {to} to A character. @return {string} A new string with the character replaced.
[ "Replace", "a", "character", "in", "the", "string", "provided", "taking", "care", "of", "the", "escaped", "chars", "." ]
18ef00d8f98df55430cf6331f227acc83855a6fc
https://github.com/simonepri/env-dot-prop/blob/18ef00d8f98df55430cf6331f227acc83855a6fc/index.js#L13-L30
train
simonepri/env-dot-prop
index.js
keys
function keys(path, opts) { let env = toUnderscore(path); if (!opts.caseSensitive) { env = env.toUpperCase(); return Object.keys(process.env).filter(key => key.toUpperCase().startsWith(env) ); } return Object.keys(process.env).filter(key => key.startsWith(env)); }
javascript
function keys(path, opts) { let env = toUnderscore(path); if (!opts.caseSensitive) { env = env.toUpperCase(); return Object.keys(process.env).filter(key => key.toUpperCase().startsWith(env) ); } return Object.keys(process.env).filter(key => key.startsWith(env)); }
[ "function", "keys", "(", "path", ",", "opts", ")", "{", "let", "env", "=", "toUnderscore", "(", "path", ")", ";", "if", "(", "!", "opts", ".", "caseSensitive", ")", "{", "env", "=", "env", ".", "toUpperCase", "(", ")", ";", "return", "Object", ".", "keys", "(", "process", ".", "env", ")", ".", "filter", "(", "key", "=>", "key", ".", "toUpperCase", "(", ")", ".", "startsWith", "(", "env", ")", ")", ";", "}", "return", "Object", ".", "keys", "(", "process", ".", "env", ")", ".", "filter", "(", "key", "=>", "key", ".", "startsWith", "(", "env", ")", ")", ";", "}" ]
Return a list of environment variables that matches the path provided. @private @param {string} path A string separated by dots. @param {Object} [opts] Additional options. @return {string[]} An array of environment variables.
[ "Return", "a", "list", "of", "environment", "variables", "that", "matches", "the", "path", "provided", "." ]
18ef00d8f98df55430cf6331f227acc83855a6fc
https://github.com/simonepri/env-dot-prop/blob/18ef00d8f98df55430cf6331f227acc83855a6fc/index.js#L59-L69
train
simonepri/env-dot-prop
index.js
get
function get(path, defaultValue, opts) { let obj; const args = [].slice.call(arguments); path = args.shift(); if (typeof args[args.length - 1] === 'object') { opts = args.pop(); } else { opts = {}; } defaultValue = args.pop(); keys(path, opts) .sort((a, b) => a.length - b.length) .forEach(key => { let dotp = toDot(key, opts); if (!opts.caseSensitive) { dotp = dotp.toLowerCase(); } const val = parse(process.env[key], opts); if (dotp === '') { obj = val; } else { if (typeof obj !== 'object') { obj = {}; } dotProp.set(obj, dotp, val); } }); let prefix = path; if (!opts.caseSensitive) { prefix = prefix.toLowerCase(); } if (path === '') { return obj; } return dotProp.get(obj, prefix, defaultValue); }
javascript
function get(path, defaultValue, opts) { let obj; const args = [].slice.call(arguments); path = args.shift(); if (typeof args[args.length - 1] === 'object') { opts = args.pop(); } else { opts = {}; } defaultValue = args.pop(); keys(path, opts) .sort((a, b) => a.length - b.length) .forEach(key => { let dotp = toDot(key, opts); if (!opts.caseSensitive) { dotp = dotp.toLowerCase(); } const val = parse(process.env[key], opts); if (dotp === '') { obj = val; } else { if (typeof obj !== 'object') { obj = {}; } dotProp.set(obj, dotp, val); } }); let prefix = path; if (!opts.caseSensitive) { prefix = prefix.toLowerCase(); } if (path === '') { return obj; } return dotProp.get(obj, prefix, defaultValue); }
[ "function", "get", "(", "path", ",", "defaultValue", ",", "opts", ")", "{", "let", "obj", ";", "const", "args", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ")", ";", "path", "=", "args", ".", "shift", "(", ")", ";", "if", "(", "typeof", "args", "[", "args", ".", "length", "-", "1", "]", "===", "'object'", ")", "{", "opts", "=", "args", ".", "pop", "(", ")", ";", "}", "else", "{", "opts", "=", "{", "}", ";", "}", "defaultValue", "=", "args", ".", "pop", "(", ")", ";", "keys", "(", "path", ",", "opts", ")", ".", "sort", "(", "(", "a", ",", "b", ")", "=>", "a", ".", "length", "-", "b", ".", "length", ")", ".", "forEach", "(", "key", "=>", "{", "let", "dotp", "=", "toDot", "(", "key", ",", "opts", ")", ";", "if", "(", "!", "opts", ".", "caseSensitive", ")", "{", "dotp", "=", "dotp", ".", "toLowerCase", "(", ")", ";", "}", "const", "val", "=", "parse", "(", "process", ".", "env", "[", "key", "]", ",", "opts", ")", ";", "if", "(", "dotp", "===", "''", ")", "{", "obj", "=", "val", ";", "}", "else", "{", "if", "(", "typeof", "obj", "!==", "'object'", ")", "{", "obj", "=", "{", "}", ";", "}", "dotProp", ".", "set", "(", "obj", ",", "dotp", ",", "val", ")", ";", "}", "}", ")", ";", "let", "prefix", "=", "path", ";", "if", "(", "!", "opts", ".", "caseSensitive", ")", "{", "prefix", "=", "prefix", ".", "toLowerCase", "(", ")", ";", "}", "if", "(", "path", "===", "''", ")", "{", "return", "obj", ";", "}", "return", "dotProp", ".", "get", "(", "obj", ",", "prefix", ",", "defaultValue", ")", ";", "}" ]
Gets the values of environment variables at the path specified. @public @param {string} path Dot separated path. @param {any} [defaultValue=undefined] Default value to return if there is not any environment variable that matches the path provided. @param {Object} [opts] Additional options. @param {boolean} [opts.parse=false] If true the value retrieved is converted to the proper type. @param {boolean} [opts.caseSensitive=false] If true no case conversion will be performed from the dot path provided to the env key search. Eg: 'tesT.kEy' will look for tesT_kEy environment variable instead of TEST_KEY. @return {any} The values of environment variables associated with the path specified.
[ "Gets", "the", "values", "of", "environment", "variables", "at", "the", "path", "specified", "." ]
18ef00d8f98df55430cf6331f227acc83855a6fc
https://github.com/simonepri/env-dot-prop/blob/18ef00d8f98df55430cf6331f227acc83855a6fc/index.js#L117-L154
train
simonepri/env-dot-prop
index.js
set
function set(path, value, opts) { if (typeof opts === 'undefined') { opts = {}; } let env = toUnderscore(path); if (!opts.caseSensitive) { env = env.toUpperCase(); } del(path, opts); process.env[env] = stringify(value, opts); }
javascript
function set(path, value, opts) { if (typeof opts === 'undefined') { opts = {}; } let env = toUnderscore(path); if (!opts.caseSensitive) { env = env.toUpperCase(); } del(path, opts); process.env[env] = stringify(value, opts); }
[ "function", "set", "(", "path", ",", "value", ",", "opts", ")", "{", "if", "(", "typeof", "opts", "===", "'undefined'", ")", "{", "opts", "=", "{", "}", ";", "}", "let", "env", "=", "toUnderscore", "(", "path", ")", ";", "if", "(", "!", "opts", ".", "caseSensitive", ")", "{", "env", "=", "env", ".", "toUpperCase", "(", ")", ";", "}", "del", "(", "path", ",", "opts", ")", ";", "process", ".", "env", "[", "env", "]", "=", "stringify", "(", "value", ",", "opts", ")", ";", "}" ]
Sets an env key at the path specified. If nested keys are present they will be deleted. @public @param {string} path Dot separated path. @param {string} value Value to set. @param {object} [opts] Additional options. @param {boolean} [opts.stringify=false] If true the value provided is converted to string. @param {boolean} [opts.caseSensitive=false] If true no case conversion is performed from the dot path provided to the env key search. Eg: 'tesT.kEy' will look for tesT_kEy environment variable instead of TEST_KEY.
[ "Sets", "an", "env", "key", "at", "the", "path", "specified", ".", "If", "nested", "keys", "are", "present", "they", "will", "be", "deleted", "." ]
18ef00d8f98df55430cf6331f227acc83855a6fc
https://github.com/simonepri/env-dot-prop/blob/18ef00d8f98df55430cf6331f227acc83855a6fc/index.js#L169-L181
train
simonepri/env-dot-prop
index.js
del
function del(path, opts) { if (typeof opts === 'undefined') { opts = {}; } keys(path, opts).forEach(key => delete process.env[key]); }
javascript
function del(path, opts) { if (typeof opts === 'undefined') { opts = {}; } keys(path, opts).forEach(key => delete process.env[key]); }
[ "function", "del", "(", "path", ",", "opts", ")", "{", "if", "(", "typeof", "opts", "===", "'undefined'", ")", "{", "opts", "=", "{", "}", ";", "}", "keys", "(", "path", ",", "opts", ")", ".", "forEach", "(", "key", "=>", "delete", "process", ".", "env", "[", "key", "]", ")", ";", "}" ]
Deletes an env key at the path specified. If nested keys are present they will be deleted too. @public @param {string} path A dot separated path. @param {object} [opts] Additional options. @param {boolean} [opts.caseSensitive=false] If true no case conversion is performed from the dot path provided to the env key search. Eg: 'tesT.kEy' will look for tesT_kEy environment variable instead of TEST_KEY.
[ "Deletes", "an", "env", "key", "at", "the", "path", "specified", ".", "If", "nested", "keys", "are", "present", "they", "will", "be", "deleted", "too", "." ]
18ef00d8f98df55430cf6331f227acc83855a6fc
https://github.com/simonepri/env-dot-prop/blob/18ef00d8f98df55430cf6331f227acc83855a6fc/index.js#L193-L199
train
andreasbm/web-config
post-build.js
copyFiles
function copyFiles (inSrc, outSrc, files) { return new Promise((res, rej) => { for (const file of files) { copySync(`./${inSrc}/${file}`, `./${outSrc}/${file}`); } res(); }); }
javascript
function copyFiles (inSrc, outSrc, files) { return new Promise((res, rej) => { for (const file of files) { copySync(`./${inSrc}/${file}`, `./${outSrc}/${file}`); } res(); }); }
[ "function", "copyFiles", "(", "inSrc", ",", "outSrc", ",", "files", ")", "{", "return", "new", "Promise", "(", "(", "res", ",", "rej", ")", "=>", "{", "for", "(", "const", "file", "of", "files", ")", "{", "copySync", "(", "`", "${", "inSrc", "}", "${", "file", "}", "`", ",", "`", "${", "outSrc", "}", "${", "file", "}", "`", ")", ";", "}", "res", "(", ")", ";", "}", ")", ";", "}" ]
Copies an array of files. @param inSrc @param outSrc @param files @returns {Promise<void>}
[ "Copies", "an", "array", "of", "files", "." ]
49199f17d75d5e542f526d21e3db57f4b6f9362f
https://github.com/andreasbm/web-config/blob/49199f17d75d5e542f526d21e3db57f4b6f9362f/post-build.js#L39-L46
train
Strider-CD/strider-extension-loader
lib/utils.js
checkModule
function checkModule(pth, cb) { checkStrider(pth, function(err, config){ if (err) return cb(err); if (config){ config.dir = pth; return cb(null, config); } checkPackageJson(pth, function(err, config){ if (err) return cb(err); if (config){ config.dir = pth; return cb(null, config); } return cb(null, false); }); }); }
javascript
function checkModule(pth, cb) { checkStrider(pth, function(err, config){ if (err) return cb(err); if (config){ config.dir = pth; return cb(null, config); } checkPackageJson(pth, function(err, config){ if (err) return cb(err); if (config){ config.dir = pth; return cb(null, config); } return cb(null, false); }); }); }
[ "function", "checkModule", "(", "pth", ",", "cb", ")", "{", "checkStrider", "(", "pth", ",", "function", "(", "err", ",", "config", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "if", "(", "config", ")", "{", "config", ".", "dir", "=", "pth", ";", "return", "cb", "(", "null", ",", "config", ")", ";", "}", "checkPackageJson", "(", "pth", ",", "function", "(", "err", ",", "config", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "if", "(", "config", ")", "{", "config", ".", "dir", "=", "pth", ";", "return", "cb", "(", "null", ",", "config", ")", ";", "}", "return", "cb", "(", "null", ",", "false", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
check for strider extension config in either strider.json or package.json
[ "check", "for", "strider", "extension", "config", "in", "either", "strider", ".", "json", "or", "package", ".", "json" ]
d2cd853129c2c163ccccc1f7969be0c8956e43f0
https://github.com/Strider-CD/strider-extension-loader/blob/d2cd853129c2c163ccccc1f7969be0c8956e43f0/lib/utils.js#L121-L137
train
Strider-CD/strider-extension-loader
lib/utils.js
readDirAbs
function readDirAbs(dir, cb) { fs.readdir(dir, function(err, entries) { if (err || !entries) { return cb(err, null); } var items = []; entries.forEach(function(entry) { items.push(path.join(dir, entry)); }); return cb(null, items); }); }
javascript
function readDirAbs(dir, cb) { fs.readdir(dir, function(err, entries) { if (err || !entries) { return cb(err, null); } var items = []; entries.forEach(function(entry) { items.push(path.join(dir, entry)); }); return cb(null, items); }); }
[ "function", "readDirAbs", "(", "dir", ",", "cb", ")", "{", "fs", ".", "readdir", "(", "dir", ",", "function", "(", "err", ",", "entries", ")", "{", "if", "(", "err", "||", "!", "entries", ")", "{", "return", "cb", "(", "err", ",", "null", ")", ";", "}", "var", "items", "=", "[", "]", ";", "entries", ".", "forEach", "(", "function", "(", "entry", ")", "{", "items", ".", "push", "(", "path", ".", "join", "(", "dir", ",", "entry", ")", ")", ";", "}", ")", ";", "return", "cb", "(", "null", ",", "items", ")", ";", "}", ")", ";", "}" ]
return abs paths
[ "return", "abs", "paths" ]
d2cd853129c2c163ccccc1f7969be0c8956e43f0
https://github.com/Strider-CD/strider-extension-loader/blob/d2cd853129c2c163ccccc1f7969be0c8956e43f0/lib/utils.js#L140-L151
train
Strider-CD/strider-extension-loader
lib/utils.js
readDirsParallel
function readDirsParallel(dirs, cb) { var funcs = []; dirs.forEach(function(dir) { funcs.push(readDirAbs.bind(null, dir)); }); async.parallel(funcs, function(err, results) { if (err) { return cb(err, null); } // Flatten results and return var flat = [].concat.apply([], results); cb(null, flat); } ); }
javascript
function readDirsParallel(dirs, cb) { var funcs = []; dirs.forEach(function(dir) { funcs.push(readDirAbs.bind(null, dir)); }); async.parallel(funcs, function(err, results) { if (err) { return cb(err, null); } // Flatten results and return var flat = [].concat.apply([], results); cb(null, flat); } ); }
[ "function", "readDirsParallel", "(", "dirs", ",", "cb", ")", "{", "var", "funcs", "=", "[", "]", ";", "dirs", ".", "forEach", "(", "function", "(", "dir", ")", "{", "funcs", ".", "push", "(", "readDirAbs", ".", "bind", "(", "null", ",", "dir", ")", ")", ";", "}", ")", ";", "async", ".", "parallel", "(", "funcs", ",", "function", "(", "err", ",", "results", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ",", "null", ")", ";", "}", "var", "flat", "=", "[", "]", ".", "concat", ".", "apply", "(", "[", "]", ",", "results", ")", ";", "cb", "(", "null", ",", "flat", ")", ";", "}", ")", ";", "}" ]
fs.readdir list of paths in parallel. used when `dir` arg is an array.
[ "fs", ".", "readdir", "list", "of", "paths", "in", "parallel", ".", "used", "when", "dir", "arg", "is", "an", "array", "." ]
d2cd853129c2c163ccccc1f7969be0c8956e43f0
https://github.com/Strider-CD/strider-extension-loader/blob/d2cd853129c2c163ccccc1f7969be0c8956e43f0/lib/utils.js#L155-L169
train
Strider-CD/strider-extension-loader
lib/utils.js
readDirs
function readDirs(dir, cb) { // find top-level module dirs if (Array.isArray(dir)) { // dir is a list of paths readDirsParallel(dir, cb); } else { // dir is a single path value readDirAbs(dir, cb); } }
javascript
function readDirs(dir, cb) { // find top-level module dirs if (Array.isArray(dir)) { // dir is a list of paths readDirsParallel(dir, cb); } else { // dir is a single path value readDirAbs(dir, cb); } }
[ "function", "readDirs", "(", "dir", ",", "cb", ")", "{", "if", "(", "Array", ".", "isArray", "(", "dir", ")", ")", "{", "readDirsParallel", "(", "dir", ",", "cb", ")", ";", "}", "else", "{", "readDirAbs", "(", "dir", ",", "cb", ")", ";", "}", "}" ]
Get the contents of one or more directories if dir is an array, do this in parrallel.
[ "Get", "the", "contents", "of", "one", "or", "more", "directories", "if", "dir", "is", "an", "array", "do", "this", "in", "parrallel", "." ]
d2cd853129c2c163ccccc1f7969be0c8956e43f0
https://github.com/Strider-CD/strider-extension-loader/blob/d2cd853129c2c163ccccc1f7969be0c8956e43f0/lib/utils.js#L173-L182
train
Vericus/slate-kit
support/rollup/factory.js
factory
function factory(pkg, location) { const isProd = process.env.NODE_ENV === "production"; return [ configure(pkg, location, "development", "module"), isProd && configure(pkg, location, "development", "umd"), isProd && configure(pkg, location, "production", "umd") ].filter(Boolean); }
javascript
function factory(pkg, location) { const isProd = process.env.NODE_ENV === "production"; return [ configure(pkg, location, "development", "module"), isProd && configure(pkg, location, "development", "umd"), isProd && configure(pkg, location, "production", "umd") ].filter(Boolean); }
[ "function", "factory", "(", "pkg", ",", "location", ")", "{", "const", "isProd", "=", "process", ".", "env", ".", "NODE_ENV", "===", "\"production\"", ";", "return", "[", "configure", "(", "pkg", ",", "location", ",", "\"development\"", ",", "\"module\"", ")", ",", "isProd", "&&", "configure", "(", "pkg", ",", "location", ",", "\"development\"", ",", "\"umd\"", ")", ",", "isProd", "&&", "configure", "(", "pkg", ",", "location", ",", "\"production\"", ",", "\"umd\"", ")", "]", ".", "filter", "(", "Boolean", ")", ";", "}" ]
Return a Rollup configuration for a `pkg`. @return {Array}
[ "Return", "a", "Rollup", "configuration", "for", "a", "pkg", "." ]
cb3be00e5068844917d51e5af9f503d6ce71d470
https://github.com/Vericus/slate-kit/blob/cb3be00e5068844917d51e5af9f503d6ce71d470/support/rollup/factory.js#L194-L201
train
Strider-CD/strider-extension-loader
lib/index.js
function (dirs, done) { var self = this; utils.findExtensions(dirs, function (err, extensions) { if (err) return done(err); for (var i = 0; i < extensions.length; i++) { extensions[i].type = extensions[i].type || 'basic'; extensions[i].id = extensions[i].id.toLowerCase(); if (RESERVED.indexOf(extensions[i].id) !== -1) { return done(new Error('Extension id "' + extensions[i].id + '" is reserved. Your plugins are misconfigured.')); } if (self.ids[extensions[i].id]) { // XXX should we die hard, ignore, or warn? return done(new Error('Duplicate extension id! Your plugins are misconfigured.')); } self.ids[extensions[i].id] = true; self.extensions[extensions[i].type][extensions[i].id] = extensions[i]; } done(); }); }
javascript
function (dirs, done) { var self = this; utils.findExtensions(dirs, function (err, extensions) { if (err) return done(err); for (var i = 0; i < extensions.length; i++) { extensions[i].type = extensions[i].type || 'basic'; extensions[i].id = extensions[i].id.toLowerCase(); if (RESERVED.indexOf(extensions[i].id) !== -1) { return done(new Error('Extension id "' + extensions[i].id + '" is reserved. Your plugins are misconfigured.')); } if (self.ids[extensions[i].id]) { // XXX should we die hard, ignore, or warn? return done(new Error('Duplicate extension id! Your plugins are misconfigured.')); } self.ids[extensions[i].id] = true; self.extensions[extensions[i].type][extensions[i].id] = extensions[i]; } done(); }); }
[ "function", "(", "dirs", ",", "done", ")", "{", "var", "self", "=", "this", ";", "utils", ".", "findExtensions", "(", "dirs", ",", "function", "(", "err", ",", "extensions", ")", "{", "if", "(", "err", ")", "return", "done", "(", "err", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "extensions", ".", "length", ";", "i", "++", ")", "{", "extensions", "[", "i", "]", ".", "type", "=", "extensions", "[", "i", "]", ".", "type", "||", "'basic'", ";", "extensions", "[", "i", "]", ".", "id", "=", "extensions", "[", "i", "]", ".", "id", ".", "toLowerCase", "(", ")", ";", "if", "(", "RESERVED", ".", "indexOf", "(", "extensions", "[", "i", "]", ".", "id", ")", "!==", "-", "1", ")", "{", "return", "done", "(", "new", "Error", "(", "'Extension id \"'", "+", "extensions", "[", "i", "]", ".", "id", "+", "'\" is reserved. Your plugins are misconfigured.'", ")", ")", ";", "}", "if", "(", "self", ".", "ids", "[", "extensions", "[", "i", "]", ".", "id", "]", ")", "{", "return", "done", "(", "new", "Error", "(", "'Duplicate extension id! Your plugins are misconfigured.'", ")", ")", ";", "}", "self", ".", "ids", "[", "extensions", "[", "i", "]", ".", "id", "]", "=", "true", ";", "self", ".", "extensions", "[", "extensions", "[", "i", "]", ".", "type", "]", "[", "extensions", "[", "i", "]", ".", "id", "]", "=", "extensions", "[", "i", "]", ";", "}", "done", "(", ")", ";", "}", ")", ";", "}" ]
find all extensions in dirs and organize them by type load from `strider.json` or package.json's `strider` section
[ "find", "all", "extensions", "in", "dirs", "and", "organize", "them", "by", "type", "load", "from", "strider", ".", "json", "or", "package", ".", "json", "s", "strider", "section" ]
d2cd853129c2c163ccccc1f7969be0c8956e43f0
https://github.com/Strider-CD/strider-extension-loader/blob/d2cd853129c2c163ccccc1f7969be0c8956e43f0/lib/index.js#L47-L67
train
canjs/can-set
src/compare.js
function( a, b, aParent, bParent, parentProp, compares, options ){ var bType = typeof b; var hasAdditionalProp = false; if(bType === 'object' || bType === 'function') { var aCopy = assign({}, a); if(options.deep === false) { options.deep = -1; } // Check that everything in B is the same as whats in A, or // isn't in A. for (var prop in b) { var compare = compares[prop] === undefined ? compares['*'] : compares[prop]; // run the comparison no matter what var compareResult = loop(a[prop], b[prop], a, b, prop, compare, options ); // if there wasn't a prop (and we didn't run through a compare) if(compareResult === h.ignoreType) { // do nothing } else if(!(prop in a) || options.performedDifference ) { hasAdditionalProp = true; } else if(!compareResult) { return false; } delete aCopy[prop]; } // go through aCopy props ... if there is no compare .. return false for (prop in aCopy) { if (compares[prop] === undefined || !loop(a[prop], undefined, a, b, prop, compares[prop], options) ) { return false; } } return hasAdditionalProp; } }
javascript
function( a, b, aParent, bParent, parentProp, compares, options ){ var bType = typeof b; var hasAdditionalProp = false; if(bType === 'object' || bType === 'function') { var aCopy = assign({}, a); if(options.deep === false) { options.deep = -1; } // Check that everything in B is the same as whats in A, or // isn't in A. for (var prop in b) { var compare = compares[prop] === undefined ? compares['*'] : compares[prop]; // run the comparison no matter what var compareResult = loop(a[prop], b[prop], a, b, prop, compare, options ); // if there wasn't a prop (and we didn't run through a compare) if(compareResult === h.ignoreType) { // do nothing } else if(!(prop in a) || options.performedDifference ) { hasAdditionalProp = true; } else if(!compareResult) { return false; } delete aCopy[prop]; } // go through aCopy props ... if there is no compare .. return false for (prop in aCopy) { if (compares[prop] === undefined || !loop(a[prop], undefined, a, b, prop, compares[prop], options) ) { return false; } } return hasAdditionalProp; } }
[ "function", "(", "a", ",", "b", ",", "aParent", ",", "bParent", ",", "parentProp", ",", "compares", ",", "options", ")", "{", "var", "bType", "=", "typeof", "b", ";", "var", "hasAdditionalProp", "=", "false", ";", "if", "(", "bType", "===", "'object'", "||", "bType", "===", "'function'", ")", "{", "var", "aCopy", "=", "assign", "(", "{", "}", ",", "a", ")", ";", "if", "(", "options", ".", "deep", "===", "false", ")", "{", "options", ".", "deep", "=", "-", "1", ";", "}", "for", "(", "var", "prop", "in", "b", ")", "{", "var", "compare", "=", "compares", "[", "prop", "]", "===", "undefined", "?", "compares", "[", "'*'", "]", ":", "compares", "[", "prop", "]", ";", "var", "compareResult", "=", "loop", "(", "a", "[", "prop", "]", ",", "b", "[", "prop", "]", ",", "a", ",", "b", ",", "prop", ",", "compare", ",", "options", ")", ";", "if", "(", "compareResult", "===", "h", ".", "ignoreType", ")", "{", "}", "else", "if", "(", "!", "(", "prop", "in", "a", ")", "||", "options", ".", "performedDifference", ")", "{", "hasAdditionalProp", "=", "true", ";", "}", "else", "if", "(", "!", "compareResult", ")", "{", "return", "false", ";", "}", "delete", "aCopy", "[", "prop", "]", ";", "}", "for", "(", "prop", "in", "aCopy", ")", "{", "if", "(", "compares", "[", "prop", "]", "===", "undefined", "||", "!", "loop", "(", "a", "[", "prop", "]", ",", "undefined", ",", "a", ",", "b", ",", "prop", ",", "compares", "[", "prop", "]", ",", "options", ")", ")", "{", "return", "false", ";", "}", "}", "return", "hasAdditionalProp", ";", "}", "}" ]
returns true if A is superset of B A is a superset if it has fewer properties
[ "returns", "true", "if", "A", "is", "superset", "of", "B", "A", "is", "a", "superset", "if", "it", "has", "fewer", "properties" ]
d7123f41fdadc103a2b2bac99bb05a6537af307a
https://github.com/canjs/can-set/blob/d7123f41fdadc103a2b2bac99bb05a6537af307a/src/compare.js#L232-L265
train
canjs/can-set
src/compare.js
function(a, b, aParent, bParent, prop, compares, options){ // if everything is the same OR doesn't have a property on the left or right (only) // and union values options.result = {}; options.performedUnion = 0; options.checks = [ compareHelpers.unionComparesType, addToResult(compareHelpers.equalBasicTypes, "equalBasicTypes"), addToResult(compareHelpers.unionArrayLike, "unionArrayLike"), addResultsToNewObject(compareHelpers.unionObject, "unionObject") ]; options.getUnions = []; options["default"] = false; var res = loop(a, b, aParent, bParent, prop, compares, options); if(res === true) { return options.result; } return false; }
javascript
function(a, b, aParent, bParent, prop, compares, options){ // if everything is the same OR doesn't have a property on the left or right (only) // and union values options.result = {}; options.performedUnion = 0; options.checks = [ compareHelpers.unionComparesType, addToResult(compareHelpers.equalBasicTypes, "equalBasicTypes"), addToResult(compareHelpers.unionArrayLike, "unionArrayLike"), addResultsToNewObject(compareHelpers.unionObject, "unionObject") ]; options.getUnions = []; options["default"] = false; var res = loop(a, b, aParent, bParent, prop, compares, options); if(res === true) { return options.result; } return false; }
[ "function", "(", "a", ",", "b", ",", "aParent", ",", "bParent", ",", "prop", ",", "compares", ",", "options", ")", "{", "options", ".", "result", "=", "{", "}", ";", "options", ".", "performedUnion", "=", "0", ";", "options", ".", "checks", "=", "[", "compareHelpers", ".", "unionComparesType", ",", "addToResult", "(", "compareHelpers", ".", "equalBasicTypes", ",", "\"equalBasicTypes\"", ")", ",", "addToResult", "(", "compareHelpers", ".", "unionArrayLike", ",", "\"unionArrayLike\"", ")", ",", "addResultsToNewObject", "(", "compareHelpers", ".", "unionObject", ",", "\"unionObject\"", ")", "]", ";", "options", ".", "getUnions", "=", "[", "]", ";", "options", "[", "\"default\"", "]", "=", "false", ";", "var", "res", "=", "loop", "(", "a", ",", "b", ",", "aParent", ",", "bParent", ",", "prop", ",", "compares", ",", "options", ")", ";", "if", "(", "res", "===", "true", ")", "{", "return", "options", ".", "result", ";", "}", "return", "false", ";", "}" ]
A u B
[ "A", "u", "B" ]
d7123f41fdadc103a2b2bac99bb05a6537af307a
https://github.com/canjs/can-set/blob/d7123f41fdadc103a2b2bac99bb05a6537af307a/src/compare.js#L347-L367
train
canjs/can-set
build.js
function(depName, depLoad){ var parsed = baseHelpers.parseModuleName(depLoad.name); var res; if( parsed.packageName !== "can-util" ) { res = baseNormalize.apply(this, arguments); } else { res = "set-"+parsed.packageName+"/"+parsed.modulePath } return res; }
javascript
function(depName, depLoad){ var parsed = baseHelpers.parseModuleName(depLoad.name); var res; if( parsed.packageName !== "can-util" ) { res = baseNormalize.apply(this, arguments); } else { res = "set-"+parsed.packageName+"/"+parsed.modulePath } return res; }
[ "function", "(", "depName", ",", "depLoad", ")", "{", "var", "parsed", "=", "baseHelpers", ".", "parseModuleName", "(", "depLoad", ".", "name", ")", ";", "var", "res", ";", "if", "(", "parsed", ".", "packageName", "!==", "\"can-util\"", ")", "{", "res", "=", "baseNormalize", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", "else", "{", "res", "=", "\"set-\"", "+", "parsed", ".", "packageName", "+", "\"/\"", "+", "parsed", ".", "modulePath", "}", "return", "res", ";", "}" ]
makes sure can-set and can-connect are namespaced so there's no collision
[ "makes", "sure", "can", "-", "set", "and", "can", "-", "connect", "are", "namespaced", "so", "there", "s", "no", "collision" ]
d7123f41fdadc103a2b2bac99bb05a6537af307a
https://github.com/canjs/can-set/blob/d7123f41fdadc103a2b2bac99bb05a6537af307a/build.js#L24-L33
train