_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 27
233k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q1000
|
train
|
function () {
var me = this;
if (!me._dataInPromise) {
me._dataInPromise = new Promise(function (resolve) {
me._dataInResolve = resolve;
}).then(function (data) {
delete me._dataInPromise;
|
javascript
|
{
"resource": ""
}
|
|
q1001
|
train
|
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;
|
javascript
|
{
"resource": ""
}
|
|
q1002
|
_gpfXmlCheckDefinableNamespacePrefixName
|
train
|
function _gpfXmlCheckDefinableNamespacePrefixName(name) {
_gpfXmlCheckValidNamespacePrefixName(name);
_gpfXmlCheckNoXmlns(name);
if
|
javascript
|
{
"resource": ""
}
|
q1003
|
_gpfInterfacesPromisify
|
train
|
function _gpfInterfacesPromisify(interfaceSpecifier) {
return function (object) {
var iInterfaceImpl = _gpfInterfaceQuery(interfaceSpecifier, object);
|
javascript
|
{
"resource": ""
}
|
q1004
|
_gpfAttributesDecorator
|
train
|
function _gpfAttributesDecorator() {
var attributes = _gpfArraySlice(arguments);
return function (ClassConstructor, member) {
if (!_gpfIsClass(ClassConstructor)) {
gpf.Error.es6classOnly();
}
|
javascript
|
{
"resource": ""
}
|
q1005
|
parseBuild
|
train
|
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
|
javascript
|
{
"resource": ""
}
|
q1006
|
getFileFactoryOptions
|
train
|
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) {
|
javascript
|
{
"resource": ""
}
|
q1007
|
getBuildFactory
|
train
|
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:
|
javascript
|
{
"resource": ""
}
|
q1008
|
parseChildInputpaths
|
train
|
function parseChildInputpaths(build) {
function parse(build) {
let inputpaths = [];
build.forEach(build => {
inputpaths = inputpaths.concat(build.inputpaths, build.builds
|
javascript
|
{
"resource": ""
}
|
q1009
|
isAppServer
|
train
|
function isAppServer(inputpaths, serverConfig) {
// Test if 'p' is in 'dirs'
function contains(dirs, p) {
if (!Array.isArray(dirs)) dirs =
|
javascript
|
{
"resource": ""
}
|
q1010
|
contains
|
train
|
function contains(dirs, p) {
if (!Array.isArray(dirs)) dirs = [dirs];
return dirs.some(dir
|
javascript
|
{
"resource": ""
}
|
q1011
|
createTemplateValue
|
train
|
function createTemplateValue(start, end) {
var value = "";
while (start <= end) {
if (tokens[start].value) {
value += tokens[start].value;
} else
|
javascript
|
{
"resource": ""
}
|
q1012
|
replaceWithTemplateType
|
train
|
function replaceWithTemplateType(start, end) {
var templateToken = {
type: "Template",
value: createTemplateValue(start, end),
start: tokens[start].start,
|
javascript
|
{
"resource": ""
}
|
q1013
|
_gpfBuildMimeTypeFromMappings
|
train
|
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) {
|
javascript
|
{
"resource": ""
}
|
q1014
|
resolvePath
|
train
|
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);
|
javascript
|
{
"resource": ""
}
|
q1015
|
resolveName
|
train
|
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
|
javascript
|
{
"resource": ""
}
|
q1016
|
resolveId
|
train
|
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);
|
javascript
|
{
"resource": ""
}
|
q1017
|
resolveNodeModules
|
train
|
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;
|
javascript
|
{
"resource": ""
}
|
q1018
|
_gpfIsImplementedBy
|
train
|
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) {
|
javascript
|
{
"resource": ""
}
|
q1019
|
_wrapQueryInterface
|
train
|
function _wrapQueryInterface (orgQueryInterface) {
return function (interfaceDefinition) {
/*eslint-disable no-invalid-this*/
_gpfIgnore(interfaceDefinition);
var result = _queryInterface.apply(this, arguments);
if (null === result) {
|
javascript
|
{
"resource": ""
}
|
q1020
|
generatePathString
|
train
|
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)
|
javascript
|
{
"resource": ""
}
|
q1021
|
loadPluginsForType
|
train
|
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
|
javascript
|
{
"resource": ""
}
|
q1022
|
extractDependencyIds
|
train
|
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
|
javascript
|
{
"resource": ""
}
|
q1023
|
resolveDependencyPaths
|
train
|
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) {
|
javascript
|
{
"resource": ""
}
|
q1024
|
resolvePluginsForBrowsers
|
train
|
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] ||
|
javascript
|
{
"resource": ""
}
|
q1025
|
_send
|
train
|
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) {
|
javascript
|
{
"resource": ""
}
|
q1026
|
_endBatch
|
train
|
function _endBatch() {
--_batch;
_cometd._debug('Ending batch, depth', _batch);
if (_batch < 0) {
|
javascript
|
{
"resource": ""
}
|
q1027
|
_connect
|
train
|
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) {
|
javascript
|
{
"resource": ""
}
|
q1028
|
_handshake
|
train
|
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
}
|
javascript
|
{
"resource": ""
}
|
q1029
|
retro
|
train
|
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
|
javascript
|
{
"resource": ""
}
|
q1030
|
_gpfEnumeratorEach
|
train
|
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) {
|
javascript
|
{
"resource": ""
}
|
q1031
|
_gpfArrayEnumerator
|
train
|
function _gpfArrayEnumerator (array) {
var pos = -1;
return {
reset: function () {
pos = -1;
},
moveNext: function (eventsHandler) {
var result;
++pos;
result = pos < array.length;
if (!result &&
|
javascript
|
{
"resource": ""
}
|
q1032
|
_buildEnumeratorOnObjectArray
|
train
|
function _buildEnumeratorOnObjectArray (object) {
var attributes = new _gpfA.Map(object).filter(_gpfA.EnumerableAttribute),
members
|
javascript
|
{
"resource": ""
}
|
q1033
|
train
|
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) {
|
javascript
|
{
"resource": ""
}
|
|
q1034
|
render
|
train
|
function render(lexed) {
// Options to parser
var options = Object.create(kramed.defaults);
options.renderer = renderer();
if(!lexed.links) {
|
javascript
|
{
"resource": ""
}
|
q1035
|
_gpfSkipPad
|
train
|
function _gpfSkipPad (text, pad) {
var idx = 0;
while (idx < text.length && -1
|
javascript
|
{
"resource": ""
}
|
q1036
|
_gpfFromBaseANY
|
train
|
function _gpfFromBaseANY (base, text, pad) {
var baseLength = base.length,
result = 0,
idx = _gpfSkipPad(text, pad || base.charAt(0));
while (idx < text.length) {
|
javascript
|
{
"resource": ""
}
|
q1037
|
_gpfPow2
|
train
|
function _gpfPow2 (n) {
var result = _gpfPow2[n];
if (result) {
return result;
}
|
javascript
|
{
"resource": ""
}
|
q1038
|
train
|
function (value, length, pad) {
return _gpfToBaseANY(_gpfB16, value,
|
javascript
|
{
"resource": ""
}
|
|
q1039
|
train
|
function (value, length, pad) {
return _gpfToBaseANY(_gpfB64, value,
|
javascript
|
{
"resource": ""
}
|
|
q1040
|
connectUser
|
train
|
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');
|
javascript
|
{
"resource": ""
}
|
q1041
|
printWeatherForecast
|
train
|
function printWeatherForecast() {
return weather
.dailyForecast('Kiev')
|
javascript
|
{
"resource": ""
}
|
q1042
|
_class
|
train
|
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,
|
javascript
|
{
"resource": ""
}
|
q1043
|
train
|
function (partStatistics) {
this.count += partStatistics.count;
this.tested
|
javascript
|
{
"resource": ""
}
|
|
q1044
|
train
|
function (count, total, rounded) {
var scale;
if (rounded) {
scale = this._0digitsScale;
} else {
scale = this._2digitsScale;
}
|
javascript
|
{
"resource": ""
}
|
|
q1045
|
train
|
function (numberOfCalls, branchDefinition) {
["if", "else"].forEach(function (label, index) {
++this.count;
|
javascript
|
{
"resource": ""
}
|
|
q1046
|
train
|
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],
|
javascript
|
{
"resource": ""
}
|
|
q1047
|
train
|
function () {
this._files = {};
this._global = new _File();
Object.keys(this._data).forEach(function (fileName) {
var fileCoverage = this._computeFileCoverage(fileName);
|
javascript
|
{
"resource": ""
}
|
|
q1048
|
find
|
train
|
function find(id) {
let filepath = '';
if ('string' == typeof id) {
try {
// Resolve relative to buddy package
filepath = require.resolve(id);
} catch (err) {
|
javascript
|
{
"resource": ""
}
|
q1049
|
install
|
train
|
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(' ')}`;
|
javascript
|
{
"resource": ""
}
|
q1050
|
_filter
|
train
|
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) {
|
javascript
|
{
"resource": ""
}
|
q1051
|
_select
|
train
|
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 = [];
|
javascript
|
{
"resource": ""
}
|
q1052
|
_gpfDefineCore
|
train
|
function _gpfDefineCore (name, Super, definition) {
var NewClass = _gpfDefineFactory(name, Super, definition);
|
javascript
|
{
"resource": ""
}
|
q1053
|
_gpfDefineProcessParamsAndCallCore
|
train
|
function _gpfDefineProcessParamsAndCallCore (params, processFunction)
|
javascript
|
{
"resource": ""
}
|
q1054
|
parseLine
|
train
|
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) {
|
javascript
|
{
"resource": ""
}
|
q1055
|
onComplete
|
train
|
function onComplete(commands) {
const content = commands.commands.map((command) => command.replyText)
.filter((text) => (text || '').trim())
.join('\n\n---\n\n');
|
javascript
|
{
"resource": ""
}
|
q1056
|
onError
|
train
|
function onError(reason, commands) {
if (typeof reason !== 'string' && typeof reason.message === 'string') {
|
javascript
|
{
"resource": ""
}
|
q1057
|
defaultHandler
|
train
|
function defaultHandler(command) {
debug(`executing default handler for unrecognized command ${command.commandText}`);
if (!command.mention) {
|
javascript
|
{
"resource": ""
}
|
q1058
|
cmdHelp
|
train
|
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);
|
javascript
|
{
"resource": ""
}
|
q1059
|
getCommandHelps
|
train
|
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();
|
javascript
|
{
"resource": ""
}
|
q1060
|
checkAvailable
|
train
|
function checkAvailable(map, command, logType, logMsg) {
if (map[command]) {
const prefix = logType === 'error' ? 'ERROR' : 'WARNING';
forum.emit(logType,
|
javascript
|
{
"resource": ""
}
|
q1061
|
threeParts
|
train
|
function threeParts(before, item1, defaultItem1, middle, item2, after) {
item2 = stringify(item2);
item1 = stringify(item1);
if (!item2) {
|
javascript
|
{
"resource": ""
}
|
q1062
|
train
|
function (state, char) {
gpf.interfaces.ignoreParameter(state);
gpf.interfaces.ignoreParameter(char);
|
javascript
|
{
"resource": ""
}
|
|
q1063
|
train
|
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);
|
javascript
|
{
"resource": ""
}
|
|
q1064
|
train
|
function (pos) {
if (this._choice) {
if (undefined === pos) {
pos = this._items.length - 1;
}
|
javascript
|
{
"resource": ""
}
|
|
q1065
|
train
|
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;
|
javascript
|
{
"resource": ""
}
|
|
q1066
|
train
|
function (char) {
var
parsedItem = this._lastItem();
if ("*" === char) {
parsedItem._min = 0;
parsedItem._max =
|
javascript
|
{
"resource": ""
}
|
|
q1067
|
train
|
function (items) {
var
idx;
idx = items.length;
while (idx--) {
|
javascript
|
{
"resource": ""
}
|
|
q1068
|
train
|
function (item, state) {
state.count = 0;
state.sub =
|
javascript
|
{
"resource": ""
}
|
|
q1069
|
train
|
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);
|
javascript
|
{
"resource": ""
}
|
|
q1070
|
train
|
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;
|
javascript
|
{
"resource": ""
}
|
|
q1071
|
train
|
function (pattern) {
var
parser = new PatternParser();
parser.parse(pattern, null);
|
javascript
|
{
"resource": ""
}
|
|
q1072
|
_gpfNodeBuffer2JsArray
|
train
|
function _gpfNodeBuffer2JsArray (buffer) {
var result = [],
len = buffer.length,
idx;
for (idx = 0; idx
|
javascript
|
{
"resource": ""
}
|
q1073
|
train
|
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,
|
javascript
|
{
"resource": ""
}
|
|
q1074
|
train
|
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) {
|
javascript
|
{
"resource": ""
}
|
|
q1075
|
train
|
function (input, encoding) {
var module = _gpfEncodings[encoding];
if (undefined ===
|
javascript
|
{
"resource": ""
}
|
|
q1076
|
_gpfPathMatchApply
|
train
|
function _gpfPathMatchApply (pathMatcher) {
/*jshint validthis:true*/
if (pathMatcher.match(this.parts)) {
this.result = !pathMatcher.negative;
|
javascript
|
{
"resource": ""
}
|
q1077
|
_gpfPathMatch
|
train
|
function _gpfPathMatch (pattern, path) {
var parts = _gpfPathDecompose(path),
matchers = _gpfPathMatchCompilePatterns(pattern),
scope = {
|
javascript
|
{
"resource": ""
}
|
q1078
|
train
|
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
|
javascript
|
{
"resource": ""
}
|
|
q1079
|
train
|
function (context) {
var parts = context.parts,
startPos = context.startPos,
endPos = parts.length - 1,
array = this.end,
len = array.length,
idx;
for (idx = 0; idx <
|
javascript
|
{
"resource": ""
}
|
|
q1080
|
train
|
function (parts) {
var result,
context = {
parts: parts,
|
javascript
|
{
"resource": ""
}
|
|
q1081
|
renameRootDeclarations
|
train
|
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);
|
javascript
|
{
"resource": ""
}
|
q1082
|
shouldRenameDeclaration
|
train
|
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
|
javascript
|
{
"resource": ""
}
|
q1083
|
getDeclarationParent
|
train
|
function getDeclarationParent(path) {
do {
if (
path.isFunctionDeclaration() ||
path.isVariableDeclaration() ||
|
javascript
|
{
"resource": ""
}
|
q1084
|
isPropertyOrKey
|
train
|
function isPropertyOrKey(path) {
return path.parentPath.get('key')
|
javascript
|
{
"resource": ""
}
|
q1085
|
transform
|
train
|
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
|
javascript
|
{
"resource": ""
}
|
q1086
|
keys
|
train
|
function keys(path, opts) {
let env = toUnderscore(path);
if (!opts.caseSensitive) {
env = env.toUpperCase();
return Object.keys(process.env).filter(key =>
|
javascript
|
{
"resource": ""
}
|
q1087
|
get
|
train
|
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 {
|
javascript
|
{
"resource": ""
}
|
q1088
|
set
|
train
|
function set(path, value, opts) {
if (typeof opts === 'undefined') {
opts = {};
}
let env = toUnderscore(path);
if (!opts.caseSensitive) {
|
javascript
|
{
"resource": ""
}
|
q1089
|
del
|
train
|
function del(path, opts) {
if (typeof opts === 'undefined') {
|
javascript
|
{
"resource": ""
}
|
q1090
|
copyFiles
|
train
|
function copyFiles (inSrc, outSrc, files) {
return new Promise((res, rej) => {
for (const file of files)
|
javascript
|
{
"resource": ""
}
|
q1091
|
checkModule
|
train
|
function checkModule(pth, cb) {
checkStrider(pth, function(err, config){
if (err) return cb(err);
if (config){
config.dir = pth;
return cb(null, config);
|
javascript
|
{
"resource": ""
}
|
q1092
|
readDirAbs
|
train
|
function readDirAbs(dir, cb) {
fs.readdir(dir, function(err, entries) {
if (err || !entries) {
return cb(err, null);
}
var items = [];
|
javascript
|
{
"resource": ""
}
|
q1093
|
readDirsParallel
|
train
|
function readDirsParallel(dirs, cb) {
var funcs = [];
dirs.forEach(function(dir) {
funcs.push(readDirAbs.bind(null, dir));
});
async.parallel(funcs, function(err, results) {
if (err) {
|
javascript
|
{
"resource": ""
}
|
q1094
|
readDirs
|
train
|
function readDirs(dir, cb) {
// find top-level module dirs
if (Array.isArray(dir)) {
// dir is a list of paths
readDirsParallel(dir, cb);
|
javascript
|
{
"resource": ""
}
|
q1095
|
factory
|
train
|
function factory(pkg, location) {
const isProd = process.env.NODE_ENV === "production";
return [
configure(pkg, location, "development", "module"),
isProd && configure(pkg,
|
javascript
|
{
"resource": ""
}
|
q1096
|
train
|
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) {
|
javascript
|
{
"resource": ""
}
|
|
q1097
|
train
|
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
|
javascript
|
{
"resource": ""
}
|
|
q1098
|
train
|
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,
|
javascript
|
{
"resource": ""
}
|
|
q1099
|
train
|
function(depName, depLoad){
var parsed = baseHelpers.parseModuleName(depLoad.name);
var res;
if( parsed.packageName !== "can-util" ) {
res = baseNormalize.apply(this, arguments);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.