_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q31300 | excludeElements | train | function excludeElements(exclude) {
return Array.isArray(exclude) ? exclude.forEach(function(selector) {
// Use querySelectorAll to hide all dom element with the specified selector
var selectorAll = document.querySelectorAll(selector);
if(selectorAll.length) {
// Interate through NodeList
for(var i = 0; i < selectorAll.length; i++) {
selectorAll.item(i).style.visibility = 'hidden';
}
}
}) : false;
} | javascript | {
"resource": ""
} |
q31301 | screenshot | train | function screenshot(name, options) {
var options = options || {};
var newPath = path;
// options to override
if(options.selector) { selector = options.selector; }
if(options.path) { newPath = path + '/' + options.path; }
if(Array.isArray(options.exclude)) { exclude = exclude.concat(options.exclude); }
// Check if in phantomjs browser and PhantomScreenshot exists
if(window.callPhantom && window.PhantomScreenshot) {
asyncScreenshot(name, newPath);
}
} | javascript | {
"resource": ""
} |
q31302 | PathPattern | train | function PathPattern(options) {
// The route string are compiled to a regexp (if it isn't already)
this.regexp = options.regexp;
// The query parameters specified in the path part of the route
this.params = options.params;
// The original routestring (optional)
this.routeString = options.routeString;
} | javascript | {
"resource": ""
} |
q31303 | detectWebEnvironment | train | function detectWebEnvironment(environments) {
// If the given environment is just a Closure, we will defer the environment check
// to the Closure the developer has provided, which allows them to totally swap
// the webs environment detection logic with their own custom Closure's code.
if (typeof environments === 'function') {
return environments()
}
var hosts;
for (var environment in environments) {
hosts = environments[environment];
// To determine the current environment, we'll simply iterate through the possible
// environments and look for the host that matches the host for this request we
// are currently processing here, then return back these environment's names.
hosts = helper.parseObject(hosts);
var k, host;
for (k in hosts) {
host = hosts[k];
if (isMachine(host)) return environment;
}
}
return 'production';
} | javascript | {
"resource": ""
} |
q31304 | train | function(ul) {
var prevLevel = {level: -1, index: -1, parent: -1, val: ''};
var levelParent = {0: -1};
tocList = ul.children("li");
tocList.each(function(i) {
var me = $(this).removeClass("toc-active");
var currentLevel = parseInt(me.attr('class').trim().slice(-1));
if (currentLevel > prevLevel.level) {
currentParent = prevLevel.index;
} else if (currentLevel == prevLevel.level) {
currentParent = prevLevel.parent;
} else if (currentLevel < prevLevel.level) {
currentParent = levelParent[currentLevel] || prevLevel.parent;
}
levelParent[currentLevel] = currentParent;
var currentVal = $('a', this).text().trim().toLowerCase();
treeObject[i] = {
val: currentVal,
level: currentLevel,
parent: currentParent
}
prevLevel = {index: i, val: currentVal, level: currentLevel, parent: currentParent};
});
} | javascript | {
"resource": ""
} | |
q31305 | train | function(key) {
var me = treeObject[key];
if (me.parent > -1) {
$(tocList[me.parent]).show();
showParents(me.parent);
}
} | javascript | {
"resource": ""
} | |
q31306 | train | function(searchVal) {
searchVal = searchVal.trim().toLowerCase();
for (var key in treeObject) {
var me = treeObject[key];
if (me.val.indexOf(searchVal) !== -1 || searchVal.length == 0) {
$(tocList[key]).show();
if ($(tocList[me.parent]).is(":hidden")) {
showParents(key);
}
} else {
$(tocList[key]).hide();
}
}
} | javascript | {
"resource": ""
} | |
q31307 | encode | train | function encode(source, label) {
if (!Buffer.isBuffer(source)) {
throw new TypeError('Argument `source` should be a Buffer.')
}
if (typeof label !== 'string') {
throw new TypeError('Argument `label` should be a string in upper case.')
}
const prefix = before + ' ' + label + endline
const suffix = after + ' ' + label + endline
const body = source.toString('base64').replace(/(.{64})/g, '$1\r\n')
return [prefix, body, suffix].join('\r\n')
} | javascript | {
"resource": ""
} |
q31308 | decode | train | function decode(pem) {
if (Buffer.isBuffer(pem)) {
pem = pem.toString('ascii')
}
const lines = pem.trim().split('\n')
if (lines.length < 3) {
throw new Error('Invalid PEM data.')
}
const match = header.exec(lines[0])
if (match === null) {
throw new Error('Invalid label.')
}
const label = match[1]
let i = 1
for (; i < lines.length; ++i) {
if (lines[i].startsWith(after)) {
break
}
}
const footer = new RegExp(`^${after} ${label}${endline}\r?\n?$`)
if (footer.exec(lines[i]) === null) {
throw new Error('Invalid end of file.')
}
const body = lines.slice(1, i).join('\n').replace(/\r?\n/g, '')
return Buffer.from(body, 'base64')
} | javascript | {
"resource": ""
} |
q31309 | Browser | train | function Browser ( opts ){
opts = opts || {};
// Members
this.headers = _.defaults({}, headers, opts.headers );
this.proxy = opts.proxy;
this.jar = opts.jar || request.jar();
} | javascript | {
"resource": ""
} |
q31310 | dev | train | function dev() {
return function logger(ctx, next) {
// request
const start = new Date();
/* eslint no-console: 0 */
console.log(` ${chalk.gray('<--')} ${chalk.bold(ctx.method)} ${chalk.gray(ctx.originalUrl)}`);
// calculate the length of a streaming response
// by intercepting the stream with a counter.
// only necessary if a content-length header is currently not set.
const length = ctx.response.length;
const body = ctx.body;
let counter;
if ((length === null || length === undefined) && body && body.readable) {
/* eslint no-param-reassign: 0 */
ctx.body = body
.pipe(counter = new Counter())
.on('error', ctx.onerror);
}
// log when the response is finished or closed,
// whichever happens first.
const res = ctx.res;
const onfinish = done.bind(null, 'finish');
const onclose = done.bind(null, 'close');
/* eslint no-use-before-define: 0 */
function done(event) {
res.removeListener('finish', onfinish);
res.removeListener('close', onclose);
log(ctx, start, counter ? counter.length : length, null, event);
}
res.once('finish', onfinish);
res.once('close', onclose);
return next();
};
} | javascript | {
"resource": ""
} |
q31311 | time | train | function time(start) {
let delta = new Date() - start;
delta = delta < 10000 ? `${delta}ms` : `${Math.round(delta / 1000)}s`;
return humanize(delta);
} | javascript | {
"resource": ""
} |
q31312 | isSea | train | function isSea(lat, lng) {
if (landLookup === null) {
const map = getMap();
landLookup = new GeoJsonLookup(map);
}
return landLookup.hasContainers({type: 'Point', coordinates: [lng, lat]});
} | javascript | {
"resource": ""
} |
q31313 | getRange | train | function getRange(node) {
if (isScope(node)) {
return node.nodes
.map(getRange)
.reduce(reduceRanges);
} else if (node.type === 'rule') {
return specificity.calculate(node.selector)
.map(result => {
return result.specificity.split(',').map(v => Number(v));
})
.reduce(reduceRange, Object.assign({}, DEFAULT_RANGE));
}
return null;
} | javascript | {
"resource": ""
} |
q31314 | init | train | function init(defaultLocale, defaultLocaleAssetUrl, defaultCurrency) {
// Store default/initial settings.
_defaultLocale = defaultLocale;
_defaultLocaleAssetUrl = defaultLocaleAssetUrl;
_defaultCurrency = defaultCurrency;
// Store default currency against the Currency object.
Currency.currentCurrency = _defaultCurrency;
// See if we have a saved locale in our cookie that's different to our current one. If so, translate to it.
var cookieLocale = localeCookie.read();
if(cookieLocale && cookieLocale.length && (cookieLocale != _defaultLocale)) {
translate(cookieLocale);
}
// See if we have a saved currency in our cookie that's different to our current one. If so, convert to it.
var cookieCurrency = Currency.cookie.read();
if(cookieCurrency && cookieCurrency.length && (cookieCurrency != _defaultCurrency)) {
convert(cookieCurrency);
}
// Create event listeners.
$(document).on('change', '[data-change="locale"]', localeChangedHandler);
$(document).on('change', '[data-change="currency"]', currencyChangedHandler);
$(document).on('click', '[data-toggle="currency"]', currencyToggledHandler);
} | javascript | {
"resource": ""
} |
q31315 | translateElement | train | function translateElement(element, locale) {
var $element = $(element),
keyPath = $element.data('translate');
var translation = getTranslation(keyPath, locale);
if(translation) {
$(element).text(translation);
}
} | javascript | {
"resource": ""
} |
q31316 | translate | train | function translate(locale) {
// Check to see if we have the locale translation data available. If not, fetch it via Ajax.
if(_locales[locale] === undefined) {
$.getJSON(getLocaleAssetUrl(locale), function (localeData) {
// Store the returned locale data.
_locales[locale] = localeData;
// Try to perform translation again.
translate(locale);
});
return;
}
// Translate elements to the given locale.
$('[data-translate]').each(function(i, element) {
translateElement(element, locale);
});
// Save the chosen locale in a cookie.
localeCookie.write(locale);
} | javascript | {
"resource": ""
} |
q31317 | convert | train | function convert(currency) {
// Store the current currency.
var oldCurrency = Currency.currentCurrency;
// Call convertAll with all possible formats. Currency.currentCurrency will be set as a side effect.
Currency.convertAll(Currency.currentCurrency, currency, '[data-convert="money"]', 'money_format');
Currency.convertAll(Currency.currentCurrency, currency, '[data-convert="money_with_currency"]', 'money_with_currency_format');
Currency.convertAll(Currency.currentCurrency, currency, '[data-convert="money_without_currency"]', 'money_without_currency_format');
// Save the chosen currency in a cookie.
Currency.cookie.write(currency);
// If there was a change in currency, fire the currency changed event.
if(oldCurrency != currency) {
$(document).trigger('currency.changed', [oldCurrency, currency]);
}
} | javascript | {
"resource": ""
} |
q31318 | Factory | train | function Factory(name, model, attributes) {
this.name = name;
this.model = model;
this.attributes = attributes;
} | javascript | {
"resource": ""
} |
q31319 | train | function(name, model, attributes) {
if (name != null && model == null && attributes == null) return factories[name];
if (model == null) return;
if (attributes == null) attributes = {};
factories[name] = new Factory(name, model, attributes);
} | javascript | {
"resource": ""
} | |
q31320 | train | function(attr, lazyContext) {
var resolved;
if (helpers.isArray(attr)) {
resolved = helpers.map(attr, function(item) {
return resolve(item, lazyContext);
});
} else if (helpers.isFunction(attr)) {
if (attr._lazy === true) {
if (lazyContext != null) resolved = attr(lazyContext);
} else {
resolved = attr();
}
} else if (helpers.isObject(attr)) {
resolved = {};
helpers.each(attr, function(value, key) {
resolved[key] = resolve(value, lazyContext);
});
} else {
resolved = attr;
}
return resolved;
} | javascript | {
"resource": ""
} | |
q31321 | train | function(name, overrides) {
var factory = factories[name], resolved;
if (overrides == null) overrides = {};
if (factory == null) return;
// resolve "eager" properties first and leave lazy ones for a second pass
var resolved = resolve(factory.attributes);
// pass already resolved attributes as context to the second pass
resolved = resolve(factory.attributes, resolved);
// apply overrides
helpers.each(overrides, function(value, key) {
resolved[key] = value;
});
return new factory.model(resolved);
} | javascript | {
"resource": ""
} | |
q31322 | train | function(name, arg1, arg2) {
var overrides, done, model;
if (helpers.isObject(arg1)) {
overrides = arg1;
done = arg2;
}
if (helpers.isFunction(arg1)) {
overrides = {};
done = arg1;
}
model = make(name, overrides);
if (model != null) model.save(done);
return model;
} | javascript | {
"resource": ""
} | |
q31323 | train | function(name, fn) {
if (name == null || fn == null) return;
generatorStore[name] = function() {
var args = [].slice.call(arguments);
return function() {
return fn.apply(fn, args);
};
};
} | javascript | {
"resource": ""
} | |
q31324 | maybeSkip | train | function maybeSkip(path) {
if(path.__jsdoc_to_assert_checked__) {
return true;
}
const {node} = path;
if (node.leadingComments != null && node.leadingComments.length > 0) {
return false;
}
return true;
} | javascript | {
"resource": ""
} |
q31325 | getBlockName | train | function getBlockName(node, lookup, prefix) {
let depth = prefix.length > 1 ? prefix.length : 0;
// NB don’t walk up to root node, stay at first root child in case of
// too deep prefix
while (node.parent && node.parent.parent && depth--) {
node = node.parent;
}
return lookup.get(node) || '';
} | javascript | {
"resource": ""
} |
q31326 | pluginFolder | train | function pluginFolder () {
const path = sketchtoolExec('show plugins');
invariant(path, 'Plugin folder not found!');
invariant(fs.existsSync(path), `Plugin folder does not exist at ${path}!`);
return path;
} | javascript | {
"resource": ""
} |
q31327 | runPluginWithIdentifier | train | function runPluginWithIdentifier (pluginName, identifier, options = {}) {
const pluginFolderPath = options.dir || pluginFolder();
// Append `.sketchplugin` if not passed in with the plugin name
if (!pluginName.endsWith('.sketchplugin')) {
pluginName += '.sketchplugin';
}
const pluginPath = `${pluginFolderPath}/${pluginName}`;
// Check if the plugin actually exists before running anything!
const exists = fs.existsSync(pluginPath);
invariant(
exists,
`Plugin '${pluginPath}' not found! Cannot run plugin command!`
);
let args = '';
if (options.context) {
args += `--context='${JSON.stringify(options.context)}' `;
}
sketchtoolExec(`run ${escape(pluginPath)} ${identifier} ${args}`);
} | javascript | {
"resource": ""
} |
q31328 | list | train | function list (type, filePath) {
invariant(
ALLOWED_LIST_TYPES.includes(type),
`Type '${type}' is not supported by sketchtool`
);
return JSON.parse(sketchtoolExec(`list ${type} ${escape(filePath)}`));
} | javascript | {
"resource": ""
} |
q31329 | train | function (options) {
this._oauth = new OAuth.OAuth(
endpoints.requestToken,
endpoints.accessToken,
options.consumerKey,
options.consumerSecret,
'1.0',
options.callbackUrl,
'HMAC-SHA1'
);
// Store authenticated access if it exists
if (options.accessToken) {
this.accessToken = options.accessToken;
this.accessTokenSecret = options.accessTokenSecret;
}
// Store a user ID if it exists
if (options.userID) {
this.userID = options.userID;
}
} | javascript | {
"resource": ""
} | |
q31330 | CBObserver | train | function CBObserver() {
var EVENT = 'interval',
watched = [],
listeners = [],
intervals = {},
self = this;
/**
* Watch a circuit breaker
*
* @param {CircuitBreaker} cb - The circuit breaker on which we'll listen the 'interval' event.
*/
this.watch = function(cb) {
if (watched.indexOf(cb) > -1) {
return;
}
watched.push(cb);
var name = cb.getName();
if (!(name in intervals)) {
intervals[name] = [];
}
var listener = buildOnInterval(name);
listeners.push(listener);
cb.on(EVENT, listener);
};
/**
* Stop watching this circuit breaker
*
* @param {CircuitBreaker} cb
*/
this.unwatch = function(cb) {
var index = watched.indexOf(cb);
if (index > -1) {
watched.splice(index, 1);
var arr = listeners.splice(index, 1);
cb.removeListener(EVENT, arr[0]);
}
};
function buildOnInterval(cb) {
return function(interval) {
intervals[cb].push(interval);
emitIfNecessary();
};
}
function emitIfNecessary() {
for (var name in intervals) {
var cnt = intervals[name].length;
if (cnt > 1) {
doEmit();
return;
} else if (cnt === 0) {
return false;
}
}
doEmit();
}
function doEmit() {
var data = intervals;
intervals = {};
for (var name in data) {
intervals[name] = [];
}
/**
* Batch event. The keys of the object are the names of the circuit breakers.
* The values of the object are arrays of {@link CircuitBreaker#event:interval}.
*
* @event CBObserver#batch
* @type object
*/
self.emit('batch', data);
}
} | javascript | {
"resource": ""
} |
q31331 | findRepeater | train | function findRepeater(node) {
while (node) {
if (node.repeat) {
return node.repeat;
}
node = node.parent;
}
} | javascript | {
"resource": ""
} |
q31332 | replaceNumbering | train | function replaceNumbering(str, value, count) {
// replace numbering in strings only: skip explicit wrappers that could
// contain unescaped numbering tokens
if (typeof str === 'string') {
const ranges = getNumberingRanges(str);
return replaceNumberingRanges(str, ranges, value, count);
}
return str;
} | javascript | {
"resource": ""
} |
q31333 | unescapeString | train | function unescapeString(str) {
let i = 0, result = '';
const len = str.length;
while (i < len) {
const ch = str[i++];
result += (ch === '\\') ? (str[i++] || '') : ch;
}
return result;
} | javascript | {
"resource": ""
} |
q31334 | insertContentIntoPlaceholder | train | function insertContentIntoPlaceholder(node, content) {
const state = {replaced: false};
node.value = replacePlaceholder(node.value, content, state);
node.attributes.forEach(attr => {
if (attr.value) {
node.setAttribute(attr.name, replacePlaceholder(attr.value, content, state));
}
});
return state.replaced;
} | javascript | {
"resource": ""
} |
q31335 | replacePlaceholder | train | function replacePlaceholder(str, value, _state) {
if (typeof str === 'string') {
const ranges = findUnescapedTokens(str, placeholder);
if (ranges.length) {
if (_state) {
_state.replaced = true;
}
str = replaceRanges(str, ranges, value);
}
}
return str;
} | javascript | {
"resource": ""
} |
q31336 | setNodeContent | train | function setNodeContent(node, content) {
// find caret position and replace it with content, if possible
if (node.value) {
const ranges = findUnescapedTokens(node.value, caret);
if (ranges.length) {
node.value = replaceRanges(node.value, ranges, content);
return;
}
}
if ((node.name && node.name.toLowerCase() === 'a') || node.hasAttribute('href')) {
// special case: inserting content into `<a>` tag
if (reUrl.test(content)) {
node.setAttribute('href', (reProto.test(content) ? '' : 'http://') + content);
} else if (reEmail.test(content)) {
node.setAttribute('href', 'mailto:' + content);
}
}
node.value = content;
} | javascript | {
"resource": ""
} |
q31337 | NpmSubmodulePlugin | train | function NpmSubmodulePlugin(options) {
// initialize instance variables
this.commands = options.commands ? options.commands : [];
this.autoInstall = options.autoInstall ? options.autoInstall : false;
this.logger = options.logger ? options.logger : console.log;
this.path = 'node_modules' + path.sep + options.module;
this.spawnSyncOptions = {
stdio: ['ignore', 'pipe', 'inherit'],
cwd: this.path
};
} | javascript | {
"resource": ""
} |
q31338 | parseGitUrl | train | function parseGitUrl(giturl) {
var ref, uri, fileParts, filepath;
if (!checkGitUrl(giturl)) return null;
giturl = giturl.slice(GIT_PREFIX.length);
uri = new URI(giturl);
ref = uri.fragment() || 'master';
uri.fragment(null);
// Extract file inside the repo (after the .git)
fileParts =uri.path().split('.git');
filepath = fileParts.length > 1? fileParts.slice(1).join('.git') : '';
if (filepath[0] == '/') filepath = filepath.slice(1);
// Recreate pathname without the real filename
uri.path(_.first(fileParts)+'.git');
return {
host: uri.toString(),
ref: ref || 'master',
filepath: filepath
};
} | javascript | {
"resource": ""
} |
q31339 | cloneGitRepo | train | function cloneGitRepo(host, ref) {
var isBranch = false;
ref = ref || 'master';
if (!validateSha(ref)) isBranch = true;
return Q()
// Create temporary folder to store git repos
.then(function() {
if (GIT_TMP) return;
return fs.tmp.dir()
.then(function(_tmp) {
GIT_TMP = _tmp;
});
})
// Return or clone the git repo
.then(function() {
// Unique ID for repo/ref combinaison
var repoId = crc.crc32(host+'#'+ref).toString(16);
// Absolute path to the folder
var repoPath = path.resolve(GIT_TMP, repoId);
return fs.exists(repoPath)
.then(function(doExists) {
if (doExists) return;
// Clone repo
return exec('git clone '+host+' '+repoPath)
.then(function() {
return exec('git checkout '+ref, { cwd: repoPath });
});
})
.thenResolve(repoPath);
});
} | javascript | {
"resource": ""
} |
q31340 | resolveFileFromGit | train | function resolveFileFromGit(giturl) {
if (_.isString(giturl)) giturl = parseGitUrl(giturl);
if (!giturl) return Q(null);
// Clone or get from cache
return cloneGitRepo(giturl.host, giturl.ref)
.then(function(repo) {
// Resolve relative path
return path.resolve(repo, giturl.filepath);
});
} | javascript | {
"resource": ""
} |
q31341 | resolveGitRoot | train | function resolveGitRoot(filepath) {
var relativeToGit, repoId;
// No git repo cloned, or file is not in a git repository
if (!GIT_TMP || !pathUtil.isInRoot(GIT_TMP, filepath)) return null;
// Extract first directory (is the repo id)
relativeToGit = path.relative(GIT_TMP, filepath);
repoId = _.first(relativeToGit.split(path.sep));
if (!repoId) return;
// Return an absolute file
return path.resolve(GIT_TMP, repoId);
} | javascript | {
"resource": ""
} |
q31342 | train | function(config) {
var hasParams = (typeof config.params === 'object');
var hasFiles = _.isArray(config.attachments);
if('GET' === config.method) {
if(hasParams) {
config.url = addParams(config.url, config.params);
}
if (hasFiles) {
throw new Error("Cannot upload files with a GET request");
}
} else if('POST' === config.method) {
if(typeof config.postData !== "undefined") {
// We have raw POST data to send up so we give it no further treatment.
config.params = config.postData;
} else if (hasFiles) {
if (hasParams) {
config.paramMap = _.clone(config.params);
_.each(config.paramMap, function (num, key) {
var value = config.paramMap[key];
if (value === null) {
delete config.paramMap[key];
}
});
delete config.params;
_.each(config.attachments, function (filestats) {
api.normalizeAPI({
'string': {
mandatory: ['name'],
oneOf: ['filename', 'fileArea', 'filePath'],
optional: ['contentType', 'name']
}
}, filestats);
});
}
} else if(hasParams) {
// We have a bunch of key/values, so we need to encode each of them.
// A string like a posted form is created. e.g. "param1key=param1value¶m2key=param2value"
var paramsWithQuestion = addParams('', config.params);
config.params = paramsWithQuestion.substring(1); // Lop off the '?' at the head
}
}
} | javascript | {
"resource": ""
} | |
q31343 | calculProgress | train | function calculProgress(navigation, current) {
var n = _.size(navigation);
var percent = 0, prevPercent = 0, currentChapter = null;
var done = true;
var chapters = _.chain(navigation)
// Transform as array
.map(function(nav, path) {
nav.path = path;
return nav;
})
// Sort entries
.sortBy(function(nav) {
return nav.index;
})
.map(function(nav, i) {
// Calcul percent
nav.percent = (i * 100) / Math.max((n - 1), 1);
// Is it done
nav.done = done;
if (nav.path == current) {
currentChapter = nav;
percent = nav.percent;
done = false;
} else if (done) {
prevPercent = nav.percent;
}
return nav;
})
.value();
return {
// Previous percent
prevPercent: prevPercent,
// Current percent
percent: percent,
// List of chapter with progress
chapters: chapters,
// Current chapter
current: currentChapter
};
} | javascript | {
"resource": ""
} |
q31344 | animate | train | function animate(source, target, options) {
var start = Object.create(null)
var diff = Object.create(null)
options = options || {}
// We let clients specify their own easing function
var easing = (typeof options.easing === 'function') ? options.easing : animations[options.easing]
// if nothing is specified, default to ease (similar to CSS animations)
if (!easing) {
if (options.easing) {
console.warn('Unknown easing function in amator: ' + options.easing);
}
easing = animations.ease
}
var step = typeof options.step === 'function' ? options.step : noop
var done = typeof options.done === 'function' ? options.done : noop
var scheduler = getScheduler(options.scheduler)
var keys = Object.keys(target)
keys.forEach(function(key) {
start[key] = source[key]
diff[key] = target[key] - source[key]
})
var durationInMs = typeof options.duration === 'number' ? options.duration : 400
var durationInFrames = Math.max(1, durationInMs * 0.06) // 0.06 because 60 frames pers 1,000 ms
var previousAnimationId
var frame = 0
previousAnimationId = scheduler.next(loop)
return {
cancel: cancel
}
function cancel() {
scheduler.cancel(previousAnimationId)
previousAnimationId = 0
}
function loop() {
var t = easing(frame/durationInFrames)
frame += 1
setValues(t)
if (frame <= durationInFrames) {
previousAnimationId = scheduler.next(loop)
step(source)
} else {
previousAnimationId = 0
setTimeout(function() { done(source) }, 0)
}
}
function setValues(t) {
keys.forEach(function(key) {
source[key] = diff[key] * t + start[key]
})
}
} | javascript | {
"resource": ""
} |
q31345 | getFields | train | function getFields(def, obj) {
var a = {};
// if not an object, return the value
if (!_.isObject(obj)) {
return obj;
}
// check for type override
var defType = _.get(obj, 'attributes.xsi:type') || _.get(obj, 'attributes.type');
defType = defType ? defType.replace(/^vim25\:/i, '') : null;
// if there is a type override and it is a valid type, set the def to that type
// and add the type to the attributes
if (defType && _.has(_client.types, defType)) {
def = _client.types[defType]();
a.attributes = {
'xsi:type': defType
};
}
// loop through each field in the type definition and look for fields
// that were supplied by the user
_.forEach(def, function(v, k) {
if (_.has(obj, k)) {
if (Array.isArray(obj[k])) {
a[k] = _.map(obj[k], function(o) {
return getFields(v, o);
});
}
else if (_.isObject(v) && _.isObject(obj[k])) {
a[k] = getFields(v, obj[k]);
}
else {
a[k] = obj[k];
}
}
});
// return the new arguments object
return a;
} | javascript | {
"resource": ""
} |
q31346 | sortArgs | train | function sortArgs(method, args) {
// get the method definition
var def = _.get(_client.types, method.replace(/\_Task$/i, '') + 'RequestType');
// if found create the definition by calling its function
if (def) {
return getFields(def(), args);
}
return args;
} | javascript | {
"resource": ""
} |
q31347 | train | function(resolve, reject) {
var fn = _client.client.VimService.VimPort[name];
fn(args, function(err, result, raw, soapHeader) {
if (err) {
// emit an error and handle the error
_client.emit('method.error', err);
_client.errorHandler(err, name, args, resolve, reject);
}
else {
_client.retry = 0;
// emit an event and resolve the output
_client.emit('method.result', result);
resolve(_.get(result, 'returnval'));
}
});
} | javascript | {
"resource": ""
} | |
q31348 | getUpdates | train | function getUpdates() {
return _client.method('WaitForUpdatesEx', {
_this: _client._updatesCollector,
version: _client._updatesVersion,
options: {
maxWaitSeconds: 0
}
})
.then(function(set) {
if (set) {
// update the version
_client._updatesVersion = set.version;
// get only the updates
var updates = [];
var filterSet = _.get(set, 'filterSet');
filterSet = Array.isArray(filterSet) ? filterSet : [filterSet];
// loop through the filter sets
_.forEach(filterSet, function(f) {
var objectSet = _.get(f, 'objectSet');
objectSet = Array.isArray(objectSet) ? objectSet : [objectSet];
// format the objects
_.forEach(objectSet, function(u) {
u.obj = {
type: _.get(u, 'obj.attributes.type'),
id: _.get(u, 'obj.$value')
};
// make the change set an array
u.changeSet = Array.isArray(u.changeSet) ? u.changeSet : [u.changeSet];
// update change set
_.forEach(u.changeSet, function(c) {
c.val = _.get(c, 'val.$value');
});
// push the update
updates.push(u);
});
});
// emit the results
_client.emit('updates', updates);
}
});
} | javascript | {
"resource": ""
} |
q31349 | wrapComplete | train | function wrapComplete(instance, options) {
var complete = options.complete;
options.complete = function(response) {
if ( _.isFunction( complete ) ) {
complete.call( this, instance, response, options );
}
};
} | javascript | {
"resource": ""
} |
q31350 | putItem | train | function putItem(model, options) {
options || ( options = {} );
if ( options.serializeDates !== false ) {
// If serializeDates is NOT `false`, use `true` by default.
options.serializeDates = true;
}
var newKey, // If the model `isNew`, a new key is generated.
request,
hashName, // Name of the hash attribute.
rangeName, // Name of the range attribute.
keyPromise,
deferred = new _.Deferred(),
/**
* Container object to store the attributes that are changed as part of saving the model.
*/
changed = {},
/**
* Parameters to use in the DynamoDB PutItem request
*/
params = {
/**
* Convert the model into an object.
* If `options.serializeDates` is `true`, `Date` values are converted into strings.
*/
Item: model.toJSON( options ),
TableName: model._tableName()
};
if ( model.isNew() ) { // If the model is new, a new key attribute(s) must be generated
hashName = _.result( model, 'hashAttribute' ) || _.result( model, 'idAttribute' );
rangeName = _.result( model, 'rangeAttribute' );
/**
* Convenience method to set the `newKey` attribute(s), once it's generated.
*/
function setNewKey(_newKey) {
if ( rangeName ) {
/**
* If the model has a range attribute, _newKey must be an object that contains
* the hash and range attributes.
*/
_.extend( changed, _newKey );
} else {
/**
* If the model doesn't have a range attribute, _newKey must be the value of the hash attribute.
*/
changed[ hashName ] = _newKey;
}
// Add the new key attribute(s) to the Item to be sent to DynamoDB
_.extend( params.Item, options.serializeDates === true ? serializeAllDates( model, _.clone( changed ) ) : changed );
}
// Generate new key attribute(s)
newKey = model.newKey( options );
if ( isPromise( newKey ) ) {
/**
* If `newKey` is a promise, wait until it's resolved to execute `setNewKey`
* and assign the resulting promise to `keyPromise`.
*/
keyPromise = newKey.then( setNewKey );
} else {
// If `newKey` is NOT a promise, call `setNewKey` right away.
setNewKey( newKey );
}
}
wrapComplete( model, options );
_.extend( params, options.dynamodb );
request = dynamo().putItem( params );
request.on('complete', function (response) {
var ctx = options.context || model;
if ( response.error ) {
deferred.rejectWith( ctx, [ response, options ] );
} else {
/**
* Backbone's "internal" success callback takes the changed attributes as the first argument.
* Make the entire AWS `response` available as `options.awsResponse`.
*/
options.awsResponse = response;
deferred.resolveWith( ctx, [ changed, options ] );
}
});
if ( !keyPromise ) {
// If there's no `keyPromise`, send the request right away.
request.send();
} else {
// If there's a `keyPromise`, wait until it is "done" before sending the request.
keyPromise.done(function () {
request.send();
}).fail(function () {
var ctx = options.context || model;
deferred.rejectWith( ctx, arguments );
});
}
deferred.done( options.success ).fail( options.error ).always( options.complete );
return deferred.promise( request );
} | javascript | {
"resource": ""
} |
q31351 | deleteItem | train | function deleteItem(model, options) {
var request,
deferred = new _.Deferred(),
params = {
Key: key.call( model ),
TableName: model._tableName()
};
options || ( options = {} );
wrapComplete( model, options );
_.extend( params, options.dynamodb );
if ( options.serializeDates !== false ) {
// If the hash and/or range attributes are `Date` instance they must be serialized before sending the request.
serializeAllDates( model, params.Key );
}
request = dynamo().deleteItem( params );
request.on('complete', function (response) {
var ctx = options.context || model;
if ( response.error ) {
deferred.rejectWith( ctx, [ response, options ] );
} else {
deferred.resolveWith( ctx, [ response, options ] );
}
});
request.send();
deferred.done( options.success ).fail( options.error ).always( options.complete );
return deferred.promise( request );
} | javascript | {
"resource": ""
} |
q31352 | fetchCollection | train | function fetchCollection(collection, options) {
options || ( options = {} );
var request,
deferred = new _.Deferred(),
// Determine the type of request: Query or Scan. Default is Scan.
fetchType = options.query ? 'query' : 'scan',
params = { TableName: collection._tableName() };
wrapComplete( collection, options );
_.extend( params, options[ fetchType ], options.dynamodb );
// Create the Query or Scan request
request = dynamo()[ fetchType ]( params );
request.on('complete', function (response) {
var dummyModel,
ctx = options.context || collection;
if ( response.error ) {
deferred.rejectWith( ctx, [ response, options ] );
} else {
/**
* Backbone's "internal" success callback takes an array of models/objects as the first argument.
* Make the entire AWS `response` available as `options.awsResponse`.
* `Date` attributes are deserialized here.
*/
options.awsResponse = response;
dummyModel = new collection.model();
_.each(response.data.Items, function (item) {
deserializeAllDates( dummyModel, item );
});
deferred.resolveWith( ctx, [ response.data.Items, options ] );
}
});
request.send();
deferred.done( options.success ).fail( options.error ).always( options.complete );
return deferred.promise( request );
} | javascript | {
"resource": ""
} |
q31353 | serializeAllDates | train | function serializeAllDates(model, json) {
_.each(json, function (value, name) {
if ( _.isDate( value ) ) {
json[ name ] = model.serializeDate( name, value );
} else if ( !isScalar( value ) && !isBackboneInstance( value ) && isRecursive( value ) ) {
serializeAllDates( model, value );
}
});
return json;
} | javascript | {
"resource": ""
} |
q31354 | deserializeAllDates | train | function deserializeAllDates(model, json) {
_.each(json, function (value, name) {
if ( !_.isDate( value ) && !isBackboneInstance( value ) ) {
if ( _.isString( value ) && model.isSerializedDate( name, value ) ) {
json[ name ] = model.deserializeDate( name, value );
} else if ( !isScalar( value ) && isRecursive( value ) ) {
deserializeAllDates( model, value );
}
}
});
return json;
} | javascript | {
"resource": ""
} |
q31355 | _tableName | train | function _tableName() {
if ( this.tableName ) {
return _.result( this, 'tableName' );
}
var urlAttributeName = this instanceof Backbone.DynamoDB.Model ? 'urlRoot' : 'url',
table = _.result( this, urlAttributeName ).replace( /^\//, '' );
return table.charAt( 0 ).toUpperCase() + table.substr( 1 );
} | javascript | {
"resource": ""
} |
q31356 | train | function() {
var hashKey = _.result( this, 'hashAttribute' ) || _.result( this, 'idAttribute' ),
rangeKey = _.result( this, 'rangeAttribute' ),
hashValue = this.get( hashKey ),
rangeValue = rangeKey ? this.get( rangeKey ) : null;
return hashValue == null || ( rangeKey && rangeValue == null );
} | javascript | {
"resource": ""
} | |
q31357 | train | function (dynamoDbParams, options) {
var _options = { query: dynamoDbParams };
_.extend( _options, options );
return this.fetch( _options );
} | javascript | {
"resource": ""
} | |
q31358 | train | function (dynamoDbParams, options) {
var _options = { scan: dynamoDbParams };
_.extend( _options, options );
return this.fetch( _options );
} | javascript | {
"resource": ""
} | |
q31359 | train | function (jsName, methodName) {
return function () {
var args = slice.call(arguments, 0);
var i = 0, max, arg, util, id, exportable;
for (max=args.length; i<max; i++) {
arg = args[i];
if (arg.kirin_bridgeUtils) {
util = arg.kirin_bridgeUtils;
util.fillInDefaults(arg);
util.validate(arg);
exportable = util.createExportableObject(arg);
if (util.hasCallbacks(arg)) {
// TODO stash the original object some place where we can use it for callbacks later.
id = tokenGenerator(jsName, methodName);
exportable.__id = id;
nativeAccessibleJavascriptObjects[id] = arg;
}
args[i] = exportable;
} else if (typeof arg === 'function') {
console.error("OMG WE'RE WRAPPING AN ERRANT FUNCTION");
args[i] = wrapCallback(arg, jsName, methodName);
}
}
args.unshift(jsName + "." + methodName);
return Native.exec.apply(null, args);
};
} | javascript | {
"resource": ""
} | |
q31360 | handleError | train | function handleError(during, e) {
/*
* {
"message": "Can't find variable: cardObject",
"line": 505,
"sourceId": 250182872,
"sourceURL": "file:///Users/james/Library/Application%20Support/iPhone%20Simulator/4.3.2/Applications/ADE774FF-B033-46A2-9CBA-DD362196E1F7/Moo.app/generated-javascript//src/controller/CardController.js",
"expressionBeginOffset": 22187,
"expressionCaretOffset": 22197,
"expressionEndOffset": 22197
}
*/
console.error("-------------------------------------------------");
console.error("Exception found " + during);
console.error("Message: " + e.message);
console.error("at : " + e.line);
var filename = e.sourceURL || "unknown";
/*jshint regexp:false*/
filename = filename.replace(/.*generated-javascript\//, "");
/*jshint regexp:true*/
console.error("file : " + filename);
console.error("url : " + e.sourceURL);
var stack = e.stack || e.stacktrace;
if (stack) {
console.error(stack);
} else {
console.log("No stack trace");
}
} | javascript | {
"resource": ""
} |
q31361 | resolveModule | train | function resolveModule(moduleName) {
if (loadedObjects[moduleName]) {
return loadedObjects[moduleName];
}
var aModule, anObject, MyModule;
if (gwtClasses) {
aModule = gwtClasses[moduleName];
}
if (!aModule) {
try {
aModule = myRequire(moduleName);
} catch (e) {
// we don't need to do anymore,
// as require will have reported the problem
}
}
if (aModule) {
if (typeof aModule === 'function') {
MyModule = aModule;
anObject = new MyModule();
} else {
anObject = aModule;
}
loadedObjects[moduleName] = anObject;
return anObject;
}
// we've tried require, and gwt modules.
// require() will have reported the error already.
//throw new Error("Cannot load module " + moduleName);
} | javascript | {
"resource": ""
} |
q31362 | traversalSpec | train | function traversalSpec(args) {
return {
attributes: {
'xsi:type': 'TraversalSpec'
},
type: args.listSpec.type,
path: args.listSpec.path,
skip: false
};
} | javascript | {
"resource": ""
} |
q31363 | objectSpec | train | function objectSpec(args) {
var set = [];
if (!args.id) {
// create a base object
var spec = { attributes: { 'xsi:type': 'ObjectSpec' } };
// check for containerview
if (args.listSpec.type === 'ContainerView' && args.containerView) {
spec.obj = args.containerView;
}
else {
spec.obj = util.moRef(args.listSpec.type, args.listSpec.id);
}
// set the skip and select set
spec.skip = (typeof(args.skip) === 'boolean') ? args.skip : true;
spec.selectSet = selectionSpec(args);
// push the object
set.push(spec);
}
else {
// ensure args.id is an array of ids even if there is only one id
args.id = Array.isArray(args.id) ? args.id : [args.id];
// loop through each if and create an object spec
_.forEach(args.id, function(id) {
set.push({
attributes: {
'xsi:type': 'ObjectSpec',
},
obj: util.moRef(args.type, id)
});
});
}
// return the specSet
return set;
} | javascript | {
"resource": ""
} |
q31364 | propertySpec | train | function propertySpec(args) {
// create a basic specification
var spec = {
attributes: {
'xsi:type': 'PropertySpec'
},
type: args.type
};
// if an array of properties was passed, validate the properties
if (Array.isArray(args.properties) && args.properties.length > 0) {
var validPaths = util.filterValidPaths(args.type, args.properties, args.apiVersion);
if (validPaths.length > 0) {
spec.pathSet = validPaths;
}
}
// if the properties is a string literal "all"
else if (args.properties === 'all') {
spec.all = true;
}
// return the specification
return [spec];
} | javascript | {
"resource": ""
} |
q31365 | isInActiveContentEditable | train | function isInActiveContentEditable(node) {
while (node) {
if ( node.getAttribute &&
node.getAttribute("contenteditable") &&
node.getAttribute("contenteditable").toUpperCase() === "TRUE" ) {
return true
}
node = node.parentNode
}
return false
} | javascript | {
"resource": ""
} |
q31366 | connectedToTheDom | train | function connectedToTheDom(node) {
// IE does not have contains method on document element, only body
var container = node.ownerDocument.contains ? node.ownerDocument : node.ownerDocument.body;
return container.contains(node);
} | javascript | {
"resource": ""
} |
q31367 | sign | train | function sign(value, pow) {
const msb = 1 << pow;
if ((value & msb) === 0) {
return value;
}
let neg = -1 * (value & msb);
neg += (value & (msb - 1));
return neg;
} | javascript | {
"resource": ""
} |
q31368 | renderDom | train | function renderDom($, dom, options) {
if (!dom && $._root && $._root.children) {
dom = $._root.children;
}
options = options|| dom.options || $._options;
return domSerializer(dom, options);
} | javascript | {
"resource": ""
} |
q31369 | convertImages | train | function convertImages(images, options) {
if (!options.convertImages) return Q();
var downloaded = [];
options.book.log.debug.ln('convert ', images.length, 'images to png');
return batch.execEach(images, {
max: 100,
fn: function(image) {
var imgin = path.resolve(options.book.options.output, image.source);
return Q()
// Write image if need to be download
.then(function() {
if (!image.origin && !_.contains(downloaded, image.origin)) return;
options.book.log.debug('download image', image.origin, '...');
downloaded.push(image.origin);
return options.book.log.debug.promise(fs.writeStream(imgin, request(image.origin)))
.fail(function(err) {
if (!_.isError(err)) err = new Error(err);
err.message = 'Fail downloading '+image.origin+': '+err.message;
throw err;
});
})
// Write svg if content
.then(function() {
if (!image.content) return;
return fs.writeFile(imgin, image.content);
})
// Convert
.then(function() {
if (!image.dest) return;
var imgout = path.resolve(options.book.options.output, image.dest);
options.book.log.debug('convert image', image.source, 'to', image.dest, '...');
return options.book.log.debug.promise(imgUtils.convertSVG(imgin, imgout));
});
}
})
.then(function() {
options.book.log.debug.ok(images.length+' images converted with success');
});
} | javascript | {
"resource": ""
} |
q31370 | normalizePage | train | function normalizePage(sections, options) {
options = _.defaults(options || {}, {
// Current book
book: null,
// Do we need to convert svg?
convertImages: false,
// Current file path
input: '.',
// Navigation to use to transform path
navigation: {},
// Directory parent of the file currently in rendering process
base: './',
// Directory parent from the html output
output: './',
// Glossary terms
glossary: []
});
// List of images to convert
var toConvert = [];
sections = _.map(sections, function(section) {
if (section.type != 'normal') return section;
var out = normalizeHtml(section.content, options);
toConvert = toConvert.concat(out.images);
section.content = out.html;
return section;
});
return Q()
.then(function() {
toConvert = _.uniq(toConvert, 'source');
return convertImages(toConvert, options);
})
.thenResolve(sections);
} | javascript | {
"resource": ""
} |
q31371 | execEach | train | function execEach(items, options) {
if (_.size(items) === 0) return Q();
var concurrents = 0, d = Q.defer(), pending = [];
options = _.defaults(options || {}, {
max: 100,
fn: function() {}
});
function startItem(item, i) {
if (concurrents >= options.max) {
pending.push([item, i]);
return;
}
concurrents++;
Q()
.then(function() {
return options.fn(item, i);
})
.then(function() {
concurrents--;
// Next pending
var next = pending.shift();
if (concurrents === 0 && !next) {
d.resolve();
} else if (next) {
startItem.apply(null, next);
}
})
.fail(function(err) {
pending = [];
d.reject(err);
});
}
_.each(items, startItem);
return d.promise;
} | javascript | {
"resource": ""
} |
q31372 | train | function(filepath, source) {
var parser = parsers.get(path.extname(filepath));
var type = parser? parser.name : null;
return that.applyShortcuts(type, source);
} | javascript | {
"resource": ""
} | |
q31373 | createDropdownMenu | train | function createDropdownMenu(dropdown) {
var $menu = $('<div>', {
'class': 'dropdown-menu',
'html': '<div class="dropdown-caret"><span class="caret-outer"></span><span class="caret-inner"></span></div>'
});
if (_.isString(dropdown)) {
$menu.append(dropdown);
} else {
var groups = _.map(dropdown, function(group) {
if (_.isArray(group)) return group;
else return [group];
});
// Create buttons groups
_.each(groups, function(group) {
var $group = $('<div>', {
'class': 'buttons'
});
var sizeClass = 'size-'+group.length;
// Append buttons
_.each(group, function(btn) {
btn = _.defaults(btn || {}, {
text: '',
className: '',
onClick: defaultOnClick
});
var $btn = $('<button>', {
'class': 'button '+sizeClass+' '+btn.className,
'text': btn.text
});
$btn.click(btn.onClick);
$group.append($btn);
});
$menu.append($group);
});
}
return $menu;
} | javascript | {
"resource": ""
} |
q31374 | createButton | train | function createButton(opts) {
opts = _.defaults(opts || {}, {
// Aria label for the button
label: '',
// Icon to show
icon: '',
// Inner text
text: '',
// Right or left position
position: 'left',
// Other class name to add to the button
className: '',
// Triggered when user click on the button
onClick: defaultOnClick,
// Button is a dropdown
dropdown: null,
// Position in the toolbar
index: null
});
buttons.push(opts);
updateButton(opts);
} | javascript | {
"resource": ""
} |
q31375 | updateButton | train | function updateButton(opts) {
var $result;
var $toolbar = $('.book-header');
var $title = $toolbar.find('h1');
// Build class name
var positionClass = 'pull-'+opts.position;
// Create button
var $btn = $('<a>', {
'class': 'btn',
'text': opts.text? ' ' + opts.text : '',
'aria-label': opts.label,
'href': '#'
});
// Bind click
$btn.click(opts.onClick);
// Prepend icon
if (opts.icon) {
$('<i>', {
'class': opts.icon
}).prependTo($btn);
}
// Prepare dropdown
if (opts.dropdown) {
var $container = $('<div>', {
'class': 'dropdown '+positionClass+' '+opts.className
});
// Add button to container
$btn.addClass('toggle-dropdown');
$container.append($btn);
// Create inner menu
var $menu = createDropdownMenu(opts.dropdown);
// Menu position
$menu.addClass('dropdown-'+(opts.position == 'right'? 'left' : 'right'));
$container.append($menu);
$result = $container;
} else {
$btn.addClass(positionClass);
$btn.addClass(opts.className);
$result = $btn;
}
$result.addClass('js-toolbar-action');
if (_.isNumber(opts.index) && opts.index >= 0) {
insertAt($toolbar, '.btn, .dropdown, h1', opts.index, $result);
} else {
$result.insertBefore($title);
}
} | javascript | {
"resource": ""
} |
q31376 | argsToObject | train | function argsToObject(args) {
var options = {};
options.address = args.shift();
options.output = args.shift();
// Pair two arguments, while transforming the key to camelCase
for (i = 0; i < args.length; i = i + 2) {
options[toCamelCase(args[i].substr(2))] = args[i + 1];
}
return options;
} | javascript | {
"resource": ""
} |
q31377 | getParent | train | function getParent(type, id, parentType, root) {
return _client.retrieve({
type: type,
id: id,
properties: ['parent']
})
.then(function(obj) {
if (obj.length > 0) {
obj = _.first(obj);
type = _.get(obj, 'parent.type');
id = _.get(obj, 'parent.id');
// if there is no parent type or id, the parent could not be found, throw an error
if (!type || !id) {
throw {
errorCode: 404,
message: 'could not find parent type'
};
}
// if the parent is a match
if (type === parentType) {
// if a root search, keep looking for parent objects of the same type
if (root === true) {
return _client.retrieve({
type: type,
id: id,
properties: ['parent']
})
.then(function(parent) {
if (_.get(parent, 'parent.type') === parentType) {
return getParent(type, id, parentType, root);
}
return {
id: id,
type: parentType
};
});
}
return {
id: id,
type: parentType
};
}
return getParent(type, id, parentType, root);
}
throw {
errorCode: 404,
message: 'Object not found'
};
});
} | javascript | {
"resource": ""
} |
q31378 | isDefaultPlugin | train | function isDefaultPlugin(name, version) {
if (!_.contains(DEFAULT_PLUGINS, name)) return false;
try {
var pluginPkg = require('gitbook-plugin-'+name+'/package.json');
return semver.satisfies(pluginPkg.version, version || '*');
} catch(e) {
return false;
}
} | javascript | {
"resource": ""
} |
q31379 | normalizePluginsList | train | function normalizePluginsList(plugins, addDefaults) {
// Normalize list to an array
plugins = _.isString(plugins) ? plugins.split(',') : (plugins || []);
// Remove empty parts
plugins = _.compact(plugins);
// Divide as {name, version} to handle format like 'myplugin@1.0.0'
plugins = _.map(plugins, function(plugin) {
if (plugin.name) return plugin;
var parts = plugin.split('@');
var name = parts[0];
var version = parts[1];
return {
'name': name,
'version': version, // optional
'isDefault': isDefaultPlugin(name, version)
};
});
// List plugins to remove
var toremove = _.chain(plugins)
.filter(function(plugin) {
return plugin.name.length > 0 && plugin.name[0] == '-';
})
.map(function(plugin) {
return plugin.name.slice(1);
})
.value();
// Merge with defaults
if (addDefaults !== false) {
_.each(DEFAULT_PLUGINS, function(plugin) {
if (_.find(plugins, { name: plugin })) {
return;
}
plugins.push({
'name': plugin,
'isDefault': true
});
});
}
// Remove plugin that start with '-'
plugins = _.filter(plugins, function(plugin) {
return !_.contains(toremove, plugin.name) && !(plugin.name.length > 0 && plugin.name[0] == '-');
});
// Remove duplicates
plugins = _.uniq(plugins, 'name');
return plugins;
} | javascript | {
"resource": ""
} |
q31380 | getFiles | train | function getFiles () {
const FUCK_ENV = process.env.FUCK_ENV
|| process.env.npm_package_config_FUCK_ENV
|| FUCK_ENV_DEFAULT
return FUCK_ENV.split(',').map(file => path.resolve(root, file))
} | javascript | {
"resource": ""
} |
q31381 | formatValue | train | function formatValue(value) {
var out;
var type = util.sType(value);
// if there is a type, check all sub items for types
if (_.has(value, 'attributes.type') && _.has(value, '$value') && _.keys(value).length === 2) {
out = util.moRef(value);
}
else if (type) {
if (util.isArray(value)) {
out = [];
var subtype = type;
if (subtype.match(/^ArrayOf/)) {
subtype = subtype.replace(/^ArrayOf/, '');
if (!Array.isArray(_.get(value, subtype)) && value[subtype]) {
value[subtype] = [value[subtype]];
}
}
_.forEach(value[_.keys(value)[1]], function(obj) {
out.push(formatValue(obj));
});
}
else if (util.isBoolean(value)) {
// check for valid true values, otherwise false
if (_.includes(['1', 'true'], _.lowerCase(value.$value))) {
out = true;
}
else {
out = false;
}
}
else if (util.isInt(value)) {
out = Number(value.$value);
}
else if (_.has(value, '$value')) {
out = value.$value;
}
else {
out = formatValue(_.omit(value, 'attributes'));
}
}
else if (Array.isArray(value)) {
out = [];
_.forEach(value, function(val) {
if (util.sType(val) || util.isArray(val) || util.hasKeys(val)) {
out.push(formatValue(val));
}
else {
out.push(cast(val));
}
});
}
else if (util.hasKeys(value)) {
out = {};
_.forEach(value, function(val, key) {
if (util.sType(val) || util.isArray(val) || util.hasKeys(val)) {
out[key] = formatValue(val);
}
else {
out[key] = cast(val);
}
});
}
else {
out = cast(value);
}
return out;
} | javascript | {
"resource": ""
} |
q31382 | formatProp | train | function formatProp(obj) {
var out = {};
var props = _.get(obj, 'propSet');
var moRef = _.has(obj, 'obj') ? util.moRef(obj.obj) : util.moRef(obj);
out.id = moRef.id;
out.type = moRef.type;
// loop through the propSet
if (Array.isArray(props)) {
_.forEach(props, function(prop) {
out[prop.name] = formatValue(prop.val);
});
}
else if (_.has(props, 'name')) {
out[props.name] = formatValue(props.val);
}
return out;
} | javascript | {
"resource": ""
} |
q31383 | expandFields | train | function expandFields(obj) {
var out = {};
_.forEach(obj, function(val, key) {
if (_.includes(key, '.')) {
_.set(out, key, val);
}
else {
out[key] = val;
}
});
return out;
} | javascript | {
"resource": ""
} |
q31384 | format | train | function format(response) {
var newObj = [];
var objects = _.get(response, 'objects') || response;
if (objects) {
// check if objects is an array
if (Array.isArray(objects)) {
_.forEach(objects, function(obj) {
newObj.push(expandFields(formatProp(obj)));
});
}
else {
newObj = expandFields(formatProp(objects));
}
return newObj;
}
// if no objects return the raw response
return response;
} | javascript | {
"resource": ""
} |
q31385 | filterSummary | train | function filterSummary(paths) {
var $summary = $('.book-summary');
$summary.find('li').each(function() {
var path = $(this).data('path');
var st = paths == null || _.contains(paths, path);
$(this).toggle(st);
if (st) $(this).parents('li').show();
});
} | javascript | {
"resource": ""
} |
q31386 | setOperations | train | function setOperations(operations, portType) {
_.forEach(portType.childNodes, node => {
if (node.localName === 'operation') {
operations[node.getAttribute('name')] = node;
}
});
} | javascript | {
"resource": ""
} |
q31387 | getUniqueFilename | train | function getUniqueFilename(base, filename) {
if (!filename) {
filename = base;
base = '/';
}
filename = path.resolve(base, filename);
var ext = path.extname(filename);
filename = path.join(path.dirname(filename), path.basename(filename, ext));
var _filename = filename+ext;
var i = 0;
while (fs.existsSync(filename)) {
_filename = filename+'_'+i+ext;
i = i + 1;
}
return path.relative(base, _filename);
} | javascript | {
"resource": ""
} |
q31388 | listFiles | train | function listFiles(root, options) {
options = _.defaults(options || {}, {
ignoreFiles: [],
ignoreRules: []
});
var d = Q.defer();
// Our list of files
var files = [];
var ig = Ignore({
path: root,
ignoreFiles: options.ignoreFiles
});
// Add extra rules to ignore common folders
ig.addIgnoreRules(options.ignoreRules, '__custom_stuff');
// Push each file to our list
ig.on('child', function (c) {
files.push(
c.path.substr(c.root.path.length + 1) + (c.props.Directory === true ? '/' : '')
);
});
ig.on('end', function() {
// Normalize paths on Windows
if(process.platform === 'win32') {
return d.resolve(files.map(function(file) {
return file.replace(/\\/g, '/');
}));
}
// Simply return paths otherwise
return d.resolve(files);
});
ig.on('error', d.reject);
return d.promise;
} | javascript | {
"resource": ""
} |
q31389 | cleanFolder | train | function cleanFolder(root) {
if (!fs.existsSync(root)) return fsUtils.mkdirp(root);
return listFiles(root, {
ignoreFiles: [],
ignoreRules: [
// Skip Git and SVN stuff
'.git/',
'.svn/'
]
})
.then(function(files) {
var d = Q.defer();
_.reduce(files, function(prev, file, i) {
return prev.then(function() {
var _file = path.join(root, file);
d.notify({
i: i+1,
count: files.length,
file: _file
});
return fsUtils.remove(_file);
});
}, Q())
.then(function() {
d.resolve();
}, function(err) {
d.reject(err);
});
return d.promise;
});
} | javascript | {
"resource": ""
} |
q31390 | validateMethod | train | function validateMethod (method) {
if (!method) {
return option.some('HTTP method is not specified')
}
if (typeof method !== 'string') {
return option.some('HTTP method should be type of string')
}
if (supportedMethods.indexOf(method.toUpperCase()) < 0) {
return option.some(`Http method ${method} is not supported`)
}
return option.none
} | javascript | {
"resource": ""
} |
q31391 | validateUrl | train | function validateUrl (url) {
if (!url) {
return option.some('Url is not specified')
}
if (typeof url !== 'string') {
return option.some('Url should be type of string')
}
return option.none
} | javascript | {
"resource": ""
} |
q31392 | validateHeader | train | function validateHeader (key, value) {
if (typeof key !== 'string' || typeof value !== 'string')
return option.some(`Parts of header ${key}:${value} must be strings`)
return option.none
} | javascript | {
"resource": ""
} |
q31393 | validateResponseType | train | function validateResponseType (type) {
if (validTypes.indexOf(type) < 0)
return option.some(`Response content type ${type} is not supported`)
return option.none
} | javascript | {
"resource": ""
} |
q31394 | getResults | train | function getResults(result, objects) {
// if there are no results, resolve an empty array
if (!result) {
return new Promise(function(resolve, reject) {
resolve([]);
});
}
// if the result object is undefined or not an array, make it one
result.objects = result.objects || [];
result.objects = Array.isArray(result.objects) ? result.objects : [result.objects];
objects = _.union(objects, result.objects);
// if the result has a token, there are more results, continue to get them
if (result.token) {
return _client.method('ContinueRetrievePropertiesEx', {
_this: _client._sc.propertyCollector,
token: result.token
})
.then(function(results) {
return getResults(results, objects);
});
}
// if there are no more results, return the formatted results
else {
return new Promise(function(resolve, reject) {
resolve(env.format(objects));
});
}
} | javascript | {
"resource": ""
} |
q31395 | ins | train | function ins(parent /* child1, child2, ... */) {
for (let i = 1, n = arguments.length; i < n; i++) {
parent.appendChild(arguments[i]);
}
return parent;
} | javascript | {
"resource": ""
} |
q31396 | train | function() {
let el = this.el;
if (el) {
clearTimeout(this.timeout);
if (el.parentNode) el.parentNode.removeChild(el);
this.el = null;
}
return this;
} | javascript | {
"resource": ""
} | |
q31397 | moRef | train | function moRef(type, id) {
if (type && id) {
return {
attributes: {
type: type
},
"$value": id
};
}
else if (typeof(type) === 'object') {
return {
id: _.get(type, '$value'),
type: _.get(type, 'attributes.type') || _.get(type, 'attributes.xsi:type')
};
}
return null;
} | javascript | {
"resource": ""
} |
q31398 | isArray | train | function isArray(obj) {
var type = sType(obj);
return (Array.isArray(obj) || (typeof(type) === 'string' && type.substring(0, 5) === 'Array'));
} | javascript | {
"resource": ""
} |
q31399 | isBoolean | train | function isBoolean(obj) {
var type = sType(obj);
return (_.has(obj, '$value') && (type === 'xsd:boolean' || type === 'boolean'));
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.