_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q40900 | refreshProxyAccessToken | train | function refreshProxyAccessToken() {
settings.AZTokenProvider().then(function(token) {
proxyAccessToken = token;
logger.log('Refreshed proxy access token: ' + proxyAccessToken);
}, function(err) {
logger.log(err);
emitter.emit('error', 'Unable to refresh access token from AZTokenProvider');
return null;
});
} | javascript | {
"resource": ""
} |
q40901 | train | function (path, pathname, hash, uuid) {
this.actionQueue.push(this.webdriverClient.screenshot.bind(this.webdriverClient));
this.actionQueue.push(this._screenshotCb.bind(this, path, pathname, hash, uuid));
return this;
} | javascript | {
"resource": ""
} | |
q40902 | train | function (path, pathname, hash, uuid, result) {
var deferred = Q.defer();
// replace base64 metadata
var base64Data = JSON.parse(result).value.replace(/^data:image\/png;base64,/,'');
// replace placeholders
var realpath = this._replacePathPlaceholder(path + pathname);
// check if we need to add a new directory
this._recursiveMakeDirSync(realpath.substring(0, realpath.lastIndexOf('/')));
// write the screenshot
fs.writeFileSync(realpath, base64Data, 'base64');
this.events.emit('driver:message', {key: 'screenshot', value: realpath, uuid: hash, hash: hash});
deferred.resolve();
return deferred.promise;
} | javascript | {
"resource": ""
} | |
q40903 | train | function (pathname) {
pathname = pathname.replace(':browser', this.browserName);
pathname = pathname.replace(':version', this._parseBrowserVersion(this.sessionStatus.version));
pathname = pathname.replace(':timestamp', Math.round(new Date().getTime() / 1000));
pathname = pathname.replace(':osVersion', this._parseOSVersion(this.driverStatus.os.version));
pathname = pathname.replace(':os', this._parseOS(this.driverStatus.os.name));
pathname = pathname.replace(':datetime', this._parseDatetime());
pathname = pathname.replace(':date', this._parseDate());
pathname = pathname.replace(':viewport', this._parseViewport());
return pathname;
} | javascript | {
"resource": ""
} | |
q40904 | train | function (version) {
var vs = version.replace(/[^0-9\\.]/g, '');
vs = vs.replace(/\./g, '_');
return vs;
} | javascript | {
"resource": ""
} | |
q40905 | train | function () {
var date = new Date();
var dateStr = '';
var day = date.getDate();
var month = date.getMonth();
month = (month+'').length === 1 ? '0' + month : month;
day = (day+'').length === 1 ? '0' + day : day;
dateStr += month + '_';
dateStr += day + '_';
dateStr += date.getFullYear();
return dateStr;
} | javascript | {
"resource": ""
} | |
q40906 | train | function () {
var date = new Date();
var dateStr = this._parseDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
hours = (hours+'').length === 1 ? '0' + hours : hours;
minutes = (minutes+'').length === 1 ? '0' + minutes : minutes;
seconds = (seconds+'').length === 1 ? '0' + seconds : seconds;
dateStr = dateStr + '_' + hours;
dateStr = dateStr + '_' + minutes;
dateStr = dateStr + '_' + seconds;
return dateStr;
} | javascript | {
"resource": ""
} | |
q40907 | setDataRegistry | train | function setDataRegistry(data) {
assertType(data, 'object', false, 'Invalid data specified');
if (!window.__private__) window.__private__ = {};
window.__private__.dataRegistry = data;
} | javascript | {
"resource": ""
} |
q40908 | writeFile | train | function writeFile(config, isJson, callback) {
try {
fs.writeFile('./.nplintrc', isJson ? JSON.stringify(config, null, 4) : yaml.safeDump(config), callback);
} catch (e) {
return callback(e);
}
} | javascript | {
"resource": ""
} |
q40909 | train | function(moduleIds) {
for (var i = moduleIds.length; i--;) {
var moduleId = moduleIds[i],
module = getModule(moduleId);
if (module == null) {
module = _modules[moduleId] = {};
_fetchFunc(moduleId);
}
}
} | javascript | {
"resource": ""
} | |
q40910 | train | function() {
var i = 0;
while (i<_callbacks.length) {
var deps = _callbacks[i][0],
func = _callbacks[i][1],
n = 0;
while (n<deps.length) {
if (areDeepDepsDefined(deps[n])) {
deps.splice(n, 1);
}
else {
n++;
}
}
if (!deps.length) {
_callbacks.splice(i, 1);
if (func != null) {
setTimeout(func, 0);
}
}
else {
i++;
}
}
} | javascript | {
"resource": ""
} | |
q40911 | train | function(moduleId) {
var scriptEl = document.createElement('script');
scriptEl.type = 'text/javascript';
scriptEl.src = resolveModuleUri(moduleId);
var useStandard = !!scriptEl.addEventListener,
timeoutHandle;
var errorFunc = function() {
postLoadFunc(false);
};
var loadFunc = function() {
if (useStandard || (scriptEl.readyState == 'complete' || scriptEl.readyState == 'loaded')) {
postLoadFunc(getModule(moduleId).defined);
}
};
var postLoadFunc = function(loaded) {
clearTimeout(timeoutHandle);
if (useStandard) {
scriptEl.removeEventListener('load', loadFunc, false);
scriptEl.removeEventListener('error', errorFunc, false);
}
else {
scriptEl.detachEvent('onreadystatechange', loadFunc);
}
if (!loaded) {
var module = getModule(moduleId);
if (!module.defined) {
module.defined = module.error = true;
fireCallbacks();
}
}
};
if (useStandard) {
scriptEl.addEventListener('load', loadFunc, false);
scriptEl.addEventListener('error', errorFunc, false);
}
else {
scriptEl.attachEvent('onreadystatechange', loadFunc);
}
timeoutHandle = setTimeout(errorFunc, _timeoutLength);
head.appendChild(scriptEl);
} | javascript | {
"resource": ""
} | |
q40912 | copyAndOffsetMapping | train | function copyAndOffsetMapping(existingMapping) {
var column = getColumnAfter(existingMapping.generatedLine - 1, existingMapping.generatedColumn);
var newMapping = {
generated: {
line : existingMapping.generatedLine,
column: column
}
};
if (existingMapping.source) {
newMapping.source = existingMapping.source;
newMapping.original = {
line : existingMapping.originalLine,
column: existingMapping.originalColumn
};
if (existingMapping.name) {
newMapping.name = existingMapping.name;
}
}
generator.addMapping(newMapping);
} | javascript | {
"resource": ""
} |
q40913 | mentionsPredicate | train | function mentionsPredicate(str) {
// null/empty check
if (!str) {
return false;
// has @ symbol
} else if (str.indexOf('@') < 0) {
return false;
// has @ symbol as first char
} else if (str[0] !== '@') {
return false;
// contains non-word chars
} else if ((/[^\w\s]/).test(str.slice(1))) {
return false;
// if ends with @
} else if (str[str.length - 1] === '@') {
return false;
}
return true;
} | javascript | {
"resource": ""
} |
q40914 | execute | train | function execute(req, res) {
// must coerce channel to string
var len = this.state.pubsub.publish(
req.conn, '' + req.args[0], req.args[1]);
res.send(null, len);
} | javascript | {
"resource": ""
} |
q40915 | _reverseAndPrecompute | train | function _reverseAndPrecompute () {
STATE_NAME_STRICT = Object.keys(US_STATE_NAME_TO_CODE);
var territoryKeys = Object.keys(US_INHABITED_TERRITORIES_NAME_TO_CODE);
(STATE_NAME_STRICT || []).forEach(function(stateName) {
US_STATE_CODE_TO_NAME[US_STATE_NAME_TO_CODE[stateName]] = stateName;
US_CAPITAL_TO_STATE_NAME[US_STATE_NAME_TO_CAPITAL[stateName]] = stateName;
});
(territoryKeys || []).forEach(function(territoryName) {
US_INHABITED_TERRITORIES_CODE_TO_NAME[US_INHABITED_TERRITORIES_NAME_TO_CODE[territoryName]] = territoryName;
US_CAPITAL_TO_INHABITED_TERRITORY_NAME[US_INHABITED_TERRITORIES_NAME_TO_CAPITAL[territoryName]] = territoryName;
});
// Let us precompute now
STATE_CODE_STRICT = Object.keys(US_STATE_CODE_TO_NAME);
STATE_NAME_ALL = (STATE_NAME_STRICT || []).concat(territoryKeys);
STATE_CODE_ALL = (STATE_CODE_STRICT || []).concat(Object.keys(US_INHABITED_TERRITORIES_CODE_TO_NAME));
} | javascript | {
"resource": ""
} |
q40916 | isUSAState | train | function isUSAState (state, strict) {
state = state && NODE_RATIFY.isString(state) ? _toTitleCase(state) : null;
var topLevel = (US_STATE_CODE_TO_NAME[state] || US_STATE_NAME_TO_CODE[state]);
if(strict) {
return topLevel ? true : false;
} else {
return (US_INHABITED_TERRITORIES_CODE_TO_NAME[state] || US_INHABITED_TERRITORIES_NAME_TO_CODE[state] || topLevel) ? true : false;
}
} | javascript | {
"resource": ""
} |
q40917 | getStateName | train | function getStateName(searchKey, strict) {
searchKey = searchKey && NODE_RATIFY.isString(searchKey) ? _toTitleCase(searchKey) : null;
var topLevel = (US_STATE_CODE_TO_NAME[searchKey] || US_CAPITAL_TO_STATE_NAME[searchKey]);
if(strict) {
return topLevel;
} else {
return (US_INHABITED_TERRITORIES_CODE_TO_NAME[searchKey] || US_CAPITAL_TO_INHABITED_TERRITORY_NAME[searchKey] || topLevel);
}
} | javascript | {
"resource": ""
} |
q40918 | getUSPSCode | train | function getUSPSCode(searchKey, strict) {
searchKey = searchKey && NODE_RATIFY.isString(searchKey) ? _toTitleCase(searchKey) : null;
var topLevel = (US_STATE_NAME_TO_CODE[searchKey] || US_STATE_NAME_TO_CODE[US_CAPITAL_TO_STATE_NAME[searchKey]]);
if(strict) {
return topLevel;
} else {
searchKey = (searchKey === 'HagåTñA') ? 'Hagatna' : searchKey;
return (US_INHABITED_TERRITORIES_NAME_TO_CODE[searchKey] ||
US_INHABITED_TERRITORIES_NAME_TO_CODE[US_CAPITAL_TO_INHABITED_TERRITORY_NAME[searchKey]] ||
topLevel);
}
} | javascript | {
"resource": ""
} |
q40919 | getStateCapital | train | function getStateCapital(searchKey, strict) {
searchKey = searchKey && NODE_RATIFY.isString(searchKey) ? _toTitleCase(searchKey) : null;
var topLevel = (US_STATE_NAME_TO_CAPITAL[searchKey] || US_STATE_NAME_TO_CAPITAL[US_STATE_CODE_TO_NAME[searchKey]]);
if(strict) {
return topLevel;
} else {
return (US_INHABITED_TERRITORIES_NAME_TO_CAPITAL[searchKey] ||
US_INHABITED_TERRITORIES_NAME_TO_CAPITAL[US_INHABITED_TERRITORIES_CODE_TO_NAME[searchKey]] ||
topLevel);
}
} | javascript | {
"resource": ""
} |
q40920 | log | train | function log() {
var args = NS ? [chalk.bold.gray(NS)] : []
for(var i=0; i<arguments.length; i++) {
var arg = arguments[i];
args.push(chalk.cyan( typeof arg === "object" ? JSON.stringify(arg) : arg ))
// adds a separator
if(i < arguments.length-1) args.push(chalk.gray("|"));
}
if(testLog) testLog(args);
else console.log.apply(null, args)
} | javascript | {
"resource": ""
} |
q40921 | logArr | train | function logArr(arr) {
if(arguments.length > 1) {
if(!suppressWarnings) console.warn("'logArr' only supports 1 parameter. Converting to regular 'log'.");
log(Array.prototype.slice.call(arguments));
return;
}
if(! _.isArray(arr)) {
if(!suppressWarnings) console.warn("'logArr' used, but first argument was not an array. Converting to regular 'log'.");
log(arr);
return;
}
log.apply(null, arr)
} | javascript | {
"resource": ""
} |
q40922 | warn | train | function warn() {
if(suppressWarnings) return
var args = NS ? [chalk.bold.gray(NS)] : []
for(var i=0; i<arguments.length; i++) {
var arg = arguments[i];
args.push(chalk.bold.yellow.bgRed( typeof arg === "object" ? JSON.stringify(arg) : arg ))
// adds a separator
if(i < arguments.length-1) args.push(chalk.gray("|"));
}
if(testWarn) testWarn(args);
else console.warn.apply(null, args)
} | javascript | {
"resource": ""
} |
q40923 | configure | train | function configure(alg, pswd, sto) {
algorithm = alg;
password = pswd;
sessionTimeout = sto;
} | javascript | {
"resource": ""
} |
q40924 | pluginFactory | train | function pluginFactory(cache) {
// ensure cache
var internalCache = cache || {};
// create an instance of cache populater
var getCache = cacheFactory(internalCache);
// return a closure with a pluginFactory() sidecar
browserifyIncremental.pluginFactory = pluginFactory;
return browserifyIncremental;
/**
* A browserify plugin that checks incoming file context and uses cached results.
* @param {object} bundler The browserify bundler instance
* @param {object} opt An options hash
*/
function browserifyIncremental(bundler, opt) {
var isValid = bundler && (typeof bundler === 'object') &&
(typeof bundler.on === 'function') && (typeof bundler.pipeline === 'object');
if (isValid) {
bundler.on('reset', setupPipeline);
setupPipeline();
}
else {
throw new Error('Expected a browserify bundler instance')
}
/**
* Apply an interceptor to the pipeline.
*/
function setupPipeline() {
var deps = bundler.pipeline.get('deps');
deps.push(getCache(deps._streams[0].cache));
}
}
} | javascript | {
"resource": ""
} |
q40925 | setupPipeline | train | function setupPipeline() {
var deps = bundler.pipeline.get('deps');
deps.push(getCache(deps._streams[0].cache));
} | javascript | {
"resource": ""
} |
q40926 | cacheFactory | train | function cacheFactory(internalCache) {
// comparison cache will be use by getters
// since getters are persistent on the internal cache then the comparison cache also needs to be persistent
var isTestedCache = {};
/**
* Get a pipeline 'deps' stage that populates cache for incremental compile.
* Called on fully transformed row but only when there is no cache hit.
* @param {object} depsCache The cache used by module-deps
* @returns {stream.Through} a through stream
*/
return function getCacheSession(depsCache) {
// make getters for any existing values (cache is shared across instances)
for (var key in internalCache) {
defineGetterFor(depsCache, key);
}
// comparison cache needs to be reset every compile
// setting value is quicker than delete operation by an order of magnitude
for (var key in isTestedCache) {
isTestedCache[key] = false;
}
// deps stage transform
function transform(row, encoding, done) {
/* jshint validthis:true */
var filename = row.file;
var fileSource = null;
try {
fileSource = fs.readFileSync(filename).toString()
} catch (e) {}
if (fileSource !== null) {
// populate the cache (overwrite)
isTestedCache[filename] = false;
internalCache[filename] = {
input : fileSource,
output: {
id : filename,
source: row.source,
deps : merge({}, row.deps),
file : filename
}
};
}
// ensure a getter is present for this key
defineGetterFor(depsCache, filename);
// complete
this.push(row);
done();
}
return through.obj(transform);
};
/**
* Create getter on first appearance of a given key and operate through the persistent cache objects.
* However be careful not to use any closed over variables in the getter.
* @param {object} depsCache The browserify cache shared across instances
* @param {string} filename The key (file name) for the deps cache
*/
function defineGetterFor(depsCache, filename) {
// instead of making the property re-definable we instead make assignment idempotent
if (!depsCache.hasOwnProperty(filename)) {
Object.defineProperty(depsCache, filename, {get: getter});
}
// create a getter
// we need to use a getter as it is the only hook at which we can perform comparison
// the value is accessed multiple times each compile cycle but is only set at the end of the cycle
// getters will persist for the life of the internal cache so the test cache also needs to persist
function getter() {
// not found
var cached = internalCache[filename];
if (!cached) {
return undefined;
}
// we have already tested whether the cached value is valid and deleted it if not
else if (isTestedCache[filename]) {
return cached.output;
}
// test the input
else {
var isMatch = cached.input && fs.existsSync(filename) &&
(cached.input === fs.readFileSync(filename).toString());
isTestedCache[filename] = true;
internalCache[filename] = isMatch && cached;
return getter();
}
}
}
} | javascript | {
"resource": ""
} |
q40927 | defineGetterFor | train | function defineGetterFor(depsCache, filename) {
// instead of making the property re-definable we instead make assignment idempotent
if (!depsCache.hasOwnProperty(filename)) {
Object.defineProperty(depsCache, filename, {get: getter});
}
// create a getter
// we need to use a getter as it is the only hook at which we can perform comparison
// the value is accessed multiple times each compile cycle but is only set at the end of the cycle
// getters will persist for the life of the internal cache so the test cache also needs to persist
function getter() {
// not found
var cached = internalCache[filename];
if (!cached) {
return undefined;
}
// we have already tested whether the cached value is valid and deleted it if not
else if (isTestedCache[filename]) {
return cached.output;
}
// test the input
else {
var isMatch = cached.input && fs.existsSync(filename) &&
(cached.input === fs.readFileSync(filename).toString());
isTestedCache[filename] = true;
internalCache[filename] = isMatch && cached;
return getter();
}
}
} | javascript | {
"resource": ""
} |
q40928 | getter | train | function getter() {
// not found
var cached = internalCache[filename];
if (!cached) {
return undefined;
}
// we have already tested whether the cached value is valid and deleted it if not
else if (isTestedCache[filename]) {
return cached.output;
}
// test the input
else {
var isMatch = cached.input && fs.existsSync(filename) &&
(cached.input === fs.readFileSync(filename).toString());
isTestedCache[filename] = true;
internalCache[filename] = isMatch && cached;
return getter();
}
} | javascript | {
"resource": ""
} |
q40929 | getModuleConfig | train | function getModuleConfig(nameOrPath,modules) {
for (var i = 0; i < modules.length; i++) {
var config = modules[i];
if (config.options && (config.options.directory === nameOrPath || config.name === nameOrPath)) {
return config;
}
}
return null;
} | javascript | {
"resource": ""
} |
q40930 | getModules | train | function getModules(argv,modules){
if(argv.module){
var which = getModuleConfig(argv.module,modules);
if(which){
return [which];
}else{
return [];
}
}
return modules;
} | javascript | {
"resource": ""
} |
q40931 | removeNotNeededNodes | train | function removeNotNeededNodes(parentElements, newChildren, oldChildren) {
let remaining = parentElements.childNodes.length;
if (oldChildren.length !== remaining) {
console.warn(
"ZLIQ: Something other then ZLIQ has manipulated the children of the element",
parentElements,
". This can lead to sideffects. Consider using the 'isolated' attribute for this element to prevent updates."
);
}
for (; remaining > newChildren.length; remaining--) {
let childToRemove = parentElements.childNodes[remaining - 1];
parentElements.removeChild(childToRemove);
if (oldChildren.length < remaining) {
continue;
} else {
let { cycle } = oldChildren[remaining - 1];
triggerLifecycle(childToRemove, { cycle }, "removed");
}
}
} | javascript | {
"resource": ""
} |
q40932 | shouldRecycleElement | train | function shouldRecycleElement(oldElement, props, tag) {
return (
!isTextNode(oldElement) &&
oldElement.id === "" &&
!nodeTypeDiffers(oldElement, tag)
);
} | javascript | {
"resource": ""
} |
q40933 | getProvider | train | function getProvider(providerName, providerConfig) {
return _.extend({}, providerConfig.opts, {
profile: function profile(credentials, params, get, callback) {
var proof = null;
/* eslint camelcase:0 */
if (providerConfig.useProof) {
proof = {
appsecret_proof: crypto
.createHmac('sha256', this.clientSecret)
.update(credentials.token)
.digest('hex')
};
}
get(providerConfig.url, proof, function (data) {
credentials.profile = {
authType: providerName,
email: data.email,
emailLower: data.email && data.email.toLowerCase(),
emailConfirmed: data.verified,
name: {
firstName: data.given_name || '',
lastName: data.family_name || '',
displayName: data.name || ''
}
};
if (providerName === 'google') {
credentials.profile.profileImg = data.picture;
credentials.profile.googleAuthData = data;
}
else if (providerName === 'facebook') {
credentials.profile.profileImg = 'https://graph.facebook.com/' +
data.id + '/picture?width=80&height=80';
credentials.profile.fbAuthData = data;
}
return callback();
});
}
});
} | javascript | {
"resource": ""
} |
q40934 | init | train | function init(ctx) {
var server = ctx.server;
var deferred = Q.defer();
server.register({register: require('bell')}, function (err) {
if (err) {
deferred.reject(err);
return;
}
_.each(config.security.social, function (providerConfig, providerName) {
var opts = _.extend({}, config.security.cookie, {
'cookie': 'bell-' + providerName,
'clientId': providerConfig.appId,
'clientSecret': providerConfig.appSecret,
'isSecure': config.useSSL,
'forceHttps': config.useSSL,
'provider': getProvider(providerName, providerConfig)
});
server.auth.strategy(providerName, 'bell', opts);
});
deferred.resolve();
});
return deferred.promise.then(function () {
return Q.when(ctx);
});
} | javascript | {
"resource": ""
} |
q40935 | findLanguageNameFromCode | train | function findLanguageNameFromCode( languageCode ) {
var a = 0;
var b = LANGUAGES.length;
var m = b;
var item, code, name;
languageCode = languageCode.toLowerCase();
while( b - a > 1 ) {
m = Math.floor( (a + b) / 2 );
item = LANGUAGES[m];
code = item[0];
name = item[1];
if( code == languageCode ) return name;
if( languageCode < code ) b = m;
else a = m;
}
return null;
} | javascript | {
"resource": ""
} |
q40936 | train | function (db, query, callback) {
// query parameter is optional
if (!callback) {
callback = query
query = {}
}
// create a new request object
var req = {
// db name
db: db,
// authenticated url to db
db_url: url.resolve(couch_url, encodeURIComponent(db)),
// used by the update queue workers
callback: callback,
// store the query parameters
query: query
}
// make sure the request has a since parameter set
exports.updateSince(req, function (err, req) {
if (err) {
return callback(err)
}
// add the changes request to the pool
exports.addToPool(idle, req)
// queue the new request for immediate update
// exports.refreshDB(updated, idle, db)
})
} | javascript | {
"resource": ""
} | |
q40937 | registerHandler | train | function registerHandler(routeItem, headler) {
let method = routeItem.method.toLowerCase();
debug(
'Binding "%s" to path "%s" with method "%s"',
routeItem.handler, routeItem.path, method.toUpperCase()
);
headler.actionHandler = true;
components.app[method](routeItem.path, headler);
} | javascript | {
"resource": ""
} |
q40938 | routeSolver | train | function routeSolver(routeItem, handler, resolver) {
switch (typeof handler) {
case 'function':
// solve as function handler
registerHandler(routeItem, null, routeItem.handler);
break;
case 'string':
// solve as controller - action handler
resolver(routeItem, handler);
break;
default:
throw new Error('unknow route type');
}
} | javascript | {
"resource": ""
} |
q40939 | transpile | train | function transpile( sourceCode, sourceName, minify ) {
try {
const
sourceFileName = Path.basename( sourceName ),
ast = parseToAST( sourceCode ),
transfo = Babel.transformSync( sourceCode, buildOptions( sourceFileName, minify ) ),
// transfo = Babel.transformFromAstSync( ast, OPTIONS ),
transpiledCode = transfo.code;
return {
code: `${transpiledCode}\n//# sourceMappingURL=${sourceFileName}.map`,
zip: transpiledCode,
map: transfo.map,
ast
};
} catch ( ex ) {
console.warn( "================================================================================" );
console.warn( sourceCode );
console.warn( "================================================================================" );
Fatal.fire( `Babel parsing error in ${sourceName}:\n${ex}`, sourceName );
}
return null;
} | javascript | {
"resource": ""
} |
q40940 | UnorderedList | train | function UnorderedList(items) {
if (typeof items == 'string') {
items = items.split(' ');
}
this._items = items || [];
this.__defineGetter__('length', this._length);
} | javascript | {
"resource": ""
} |
q40941 | fold | train | function fold(count, buf)
{
if(!count || buf.length % 2) return buf;
var ret = buf.slice(0,buf.length/2);
for(i = 0; i < ret.length; i++) ret[i] = ret[i] ^ buf[i+ret.length];
return fold(count-1,ret);
} | javascript | {
"resource": ""
} |
q40942 | pickReverseEach | train | function pickReverseEach( reverse, node, callback ) {
var test = type.call( node, 'Undefined' ) ||
node==='false' ||
node===false ||
(
type.call( node, 'Boolean' ) &&
!node.valueOf()
);
if ( test ) {
pickReverse.call( this, reverse, true, callback );
}
else if ( type.call( node.isBoolean, 'Function' ) ) {
if ( node.isBoolean.tick ) {
}
else {
pickReverse.call( this, reverse, ( ( node.isBoolean() && !node.valueOf() ) || !node ), callback );
}
}
else {
pickReverse.call( this, reverse, !node, callback );
}
} | javascript | {
"resource": ""
} |
q40943 | processTokens | train | function processTokens(tokens, callback) {
"use strict";
var processFunctions = underscore.map(tokens, function (word) {
return function (cb) {
tokenizeWord(word, cb);
};
});
async.parallel(
processFunctions,
function (error, results) {
if (error) {
callback(error, null);
} else {
var normalizedTokens = [];
results.forEach(function (tokens) {
normalizedTokens = normalizedTokens.concat(tokens);
});
normalizedTokens.sort();
normalizedTokens = underscore.uniq(normalizedTokens, true);
callback(null, normalizedTokens);
}
}
);
} | javascript | {
"resource": ""
} |
q40944 | getRelevantStackFrom | train | function getRelevantStackFrom (stack) {
var filteredStack = [];
var relevantStack = [];
stack = stack.split('\n');
for (var i = 0; i < stack.length; i += 1) {
if (isExternalStackEntry(stack[i])) {
filteredStack.push(stack[i])
}
}
// If the filtered stack is empty, i.e. the error originated entirely from within jasmine or karma, then the whole stack
// should be relevant.
if (filteredStack.length === 0) {
filteredStack = stack
}
for (i = 0; i < filteredStack.length; i += 1) {
if (filteredStack[i]) {
relevantStack.push(filteredStack[i])
}
}
return relevantStack
} | javascript | {
"resource": ""
} |
q40945 | formatFailedStep | train | function formatFailedStep (step) {
// Safari seems to have no stack trace,
// so we just return the error message:
if (!step.stack) { return step.message }
var relevantMessage = [];
var relevantStack = [];
// Remove the message prior to processing the stack to prevent issues like
// https://github.com/karma-runner/karma-jasmine/issues/79
var stack = step.stack.replace('Error: ' + step.message, '');
var dirtyRelevantStack = getRelevantStackFrom(stack);
// PhantomJS returns multiline error message for errors coming from specs
// (for example when calling a non-existing function). This error is present
// in both `step.message` and `step.stack` at the same time, but stack seems
// preferable, so we iterate relevant stack, compare it to message:
for (var i = 0; i < dirtyRelevantStack.length; i += 1) {
if (typeof step.message === 'string' && step.message.indexOf(dirtyRelevantStack[i]) === -1) {
// Stack entry is not in the message,
// we consider it to be a relevant stack:
relevantStack.push(dirtyRelevantStack[i])
} else {
// Stack entry is already in the message,
// we consider it to be a suitable message alternative:
relevantMessage.push(dirtyRelevantStack[i])
}
}
// In most cases the above will leave us with an empty message...
if (relevantMessage.length === 0) {
// Let's reuse the original message:
relevantMessage.push(step.message);
// Now we probably have a repetition case where:
// relevantMessage: ["Expected true to be false."]
// relevantStack: ["Error: Expected true to be false.", ...]
if (relevantStack.length && relevantStack[0].indexOf(step.message) !== -1) {
// The message seems preferable, so we remove the first value from
// the stack to get rid of repetition :
relevantStack.shift()
}
}
// Example output:
// --------------------
// Chrome 40.0.2214 (Mac OS X 10.9.5) xxx should return false 1 FAILED
// Expected true to be false
// at /foo/bar/baz.spec.js:22:13
// at /foo/bar/baz.js:18:29
return relevantMessage.concat(relevantStack).join('\n')
} | javascript | {
"resource": ""
} |
q40946 | train | function (clientArguments) {
var grepRegex = /^--grep=(.*)$/;
if (Object.prototype.toString.call(clientArguments) === '[object Array]') {
var indexOfGrep = indexOf(clientArguments, '--grep');
if (indexOfGrep !== -1) {
return clientArguments[indexOfGrep + 1]
}
return map(filter(clientArguments, function (arg) {
return grepRegex.test(arg)
}), function (arg) {
return arg.replace(grepRegex, '$1')
})[0] || ''
} else if (typeof clientArguments === 'string') {
var match = /--grep=([^=]+)/.exec(clientArguments);
return match ? match[1] : ''
}
} | javascript | {
"resource": ""
} | |
q40947 | createStartFn | train | function createStartFn (karma, jasmineEnv) {
function setOption (option, set) {
if (option != null) {
set(option)
}
}
// This function will be assigned to `window.__karma__.start`:
return function () {
console.log('suman started.');
window.__suman.tsrq.resume();
// var clientConfig = karma.config || {}
// var jasmineConfig = clientConfig.jasmine || {}
//
// jasmineEnv = jasmineEnv || window.jasmine.getEnv()
//
// setOption(jasmineConfig.stopOnFailure, jasmineEnv.throwOnExpectationFailure)
// setOption(jasmineConfig.seed, jasmineEnv.seed)
// setOption(jasmineConfig.random, jasmineEnv.randomizeTests)
//
// jasmineEnv.addReporter(new KarmaReporter(karma, jasmineEnv))
// jasmineEnv.execute()
}
} | javascript | {
"resource": ""
} |
q40948 | _copy_property | train | function _copy_property(opts, key, a, b) {
debug.assert(opts).is('object');
debug.assert(key).is('string');
debug.assert(a).is('object');
debug.assert(b).is('object');
a[key] = b[key];
if(opts.cache && opts.cache._has_cursors && is.obj(b[key]) && b[key].hasOwnProperty('$id')) {
var f = opts.cache.findCursor(b, key);
if(f) {
//debug.log('Expanding cursor...');
opts.cache.addToCursor(f, a, key);
}
}
} | javascript | {
"resource": ""
} |
q40949 | merge_objects_ | train | function merge_objects_(b) {
if(is.func(b)) {
b = b();
}
debug.assert(b).is('object');
_merge_object(opts, a, b);
} | javascript | {
"resource": ""
} |
q40950 | train | function (init) {
if (!init) {
this.startAngleRad = this.yAxis.startAngleRad;
H.seriesTypes.pie.prototype.animate.call(this, init);
}
} | javascript | {
"resource": ""
} | |
q40951 | execute | train | function execute(req, res) {
this.log.notice('background saving started by pid %s', process.pid);
function onSave(err) {
/* istanbul ignore next: not prepared to mock this right now */
if(err) return this.log.warning('background save failed: %s', err.message);
this.log.notice('background saving terminated with success')
}
Persistence.save(this.state.store, this.state.conf, onSave.bind(this));
res.send(null, Constants.BGSAVE);
} | javascript | {
"resource": ""
} |
q40952 | validate | train | function validate(cmd, args, info) {
AbstractCommand.prototype.validate.apply(this, arguments);
if(Persistence.saving) throw SaveInProgress;
} | javascript | {
"resource": ""
} |
q40953 | SlowLogRecord | train | function SlowLogRecord(cmd, args) {
this._now = Date.now();
this._cmd = [cmd].concat(args);
// start timer value when command execution started
this._start = process.hrtime();
} | javascript | {
"resource": ""
} |
q40954 | isSlowerThan | train | function isSlowerThan(amount) {
// always logging
var diff = process.hrtime(this._start)
, micro = Math.round(((diff[0] * 1e9) + diff[1]) / 1e3);
if(amount === 0) return micro;
if(micro > amount) {
return micro;
}
return -1;
} | javascript | {
"resource": ""
} |
q40955 | toArray | train | function toArray(id, time) {
var o = [
id,
Math.round(this._now / 1000),
time,
this._cmd];
return o;
} | javascript | {
"resource": ""
} |
q40956 | SlowLog | train | function SlowLog(conf) {
this._conf = conf;
// log commands slower than this number of microseconds
// disabled by default
this._slowerThan = -1;
// maximum length of the slow log
this._maxLen = 128;
// set up log records array
this.reset();
// log record for the current executing command
this._record = null;
function onConfigLoad() {
this._slowerThan = conf.get(ConfigKey.SLOWLOG_LOG_SLOWER_THAN);
this._maxLen = conf.get(ConfigKey.SLOWLOG_MAX_LEN);
}
function onSlowerThan(key, value) {
this._slowerThan = value;
}
function onMaxLen(key, value) {
// minimum record length is one, if a user wishes
// to disable slow logs they should set slowlog-log-slower-than to -1
this._maxLen = Math.max(value, 1);
}
onConfigLoad = onConfigLoad.bind(this);
onSlowerThan = onSlowerThan.bind(this);
onMaxLen = onMaxLen.bind(this);
this._conf.once('load', onConfigLoad.bind(this));
this._conf.on(ConfigKey.SLOWLOG_LOG_SLOWER_THAN, onSlowerThan);
this._conf.on(ConfigKey.SLOWLOG_MAX_LEN, onMaxLen);
// bind stop here as it is called as a before
// function on the response
this.stop = this.stop.bind(this);
} | javascript | {
"resource": ""
} |
q40957 | start | train | function start(cmd, args) {
if(!this.enabled) return false;
this._record = new SlowLogRecord(cmd, args);
return this._record;
} | javascript | {
"resource": ""
} |
q40958 | stop | train | function stop() {
var time;
if(!this.enabled) return false;
time = this._record.isSlowerThan(this._slowerThan);
if(this._record && time > -1) {
this._records.unshift(this._record.toArray(id++, time));
if(this._records.length >= this._maxLen) {
this._records.pop();
}
}
} | javascript | {
"resource": ""
} |
q40959 | get | train | function get(amount) {
amount = amount !== undefined && amount >= 0 ? amount : 10;
amount = Math.min(amount, this._records.length);
return this._records.slice(0, amount);
} | javascript | {
"resource": ""
} |
q40960 | TypeDef | train | function TypeDef(arity, type, repeats) {
// arity for the parameter
this.arity = arity;
// type declarations as an array
this.type = type;
// does this value accumulate repeating declarations
this.repeats = repeats;
} | javascript | {
"resource": ""
} |
q40961 | validate | train | function validate(key, values) {
if(this.arity > 0 && values.length !== this.arity) {
throw new TypeDefError(
util.format('bad arity for \'%s\', expected %s got %s',
key, this.arity, values.length));
}
var types = Array.isArray(this.type) ? this.type : [this.type]
, i
, type
, val
, num
, coerced = []
, enumerable = false;
for(i = 0;i < types.length;i++) {
type = types[i];
val = values[i];
enumerable = Array.isArray(type);
if(enumerable) {
if(!~type.indexOf(val)) {
throw new TypeDefError(
util.format('enum error on key \'%s\', got \'%s\' expected one of %s',
key, val, type.join(', ')));
}
}
switch(type) {
case ByteSize:
val = ByteSize.parse(val);
break;
case Boolean:
if(val !== YES && val !== NO) {
throw new Error(
util.format('argument must be \'%s\' or \'%s\'', YES, NO));
}
val = val === YES ? true : false;
break;
case String:
// strings can be quoted
val = val.replace(/^"/, '').replace(/"$/, '');
break;
case Number:
num = parseInt(val);
if(isNaN(num) || !/^-?[0-9]+$/.test(val)) {
throw new TypeDefError(
util.format('number expected for \'%s\', got %s', key, val));
}
val = num;
break;
}
coerced[i] = val;
}
if(this.arity === 1 && !this.repeats) return coerced[0];
return Array.isArray(this.type) ? coerced : coerced[0];
} | javascript | {
"resource": ""
} |
q40962 | encode | train | function encode(key, value, stringify) {
var space = ' ', val = [], i, type = this.type;
function coerce(type, val) {
var out
, enumerable = Array.isArray(type);
if(enumerable) {
if(!~type.indexOf(val)) {
throw new TypeDefError(
util.format('enum error on key \'%s\', got \'%s\' expected one of %s',
key, val, type.join(', ')));
}
return '' + val;
}
switch(type) {
case ByteSize:
if(typeof val !== 'number') {
throw new TypeDefError(
util.format(
'byte size number expected for \'%s\', got %s', key, val));
}
out = ByteSize.humanize(val);
break;
case Boolean:
if(typeof val !== 'boolean') {
throw new TypeDefError(
util.format('boolean expected for \'%s\', got %s', key, val));
}
out = val === true ? YES : NO;
break;
case String:
// strings must be quoted to allow the empty string
out = '"' + val + '"';
break;
case Number:
if(typeof val !== 'number') {
throw new TypeDefError(
util.format('number expected for \'%s\', got %s', key, val));
}
// just coerce numbers to strings
out = '' + val;
break;
}
return out;
}
// simple types
if(!Array.isArray(this.type)) {
return (!stringify ? key + space : '') + coerce(this.type, value);
}
if(stringify && this.repeats) {
value.forEach(function(item) {
item.forEach(function(entry, i) {
val.push(coerce(type[i], entry));
})
});
return val.join(space);
}
for(i = 0;i < this.type.length;i++) {
if(this.arity > 1) {
// expecting value to be an array
val.push(coerce(this.type[i], value[i]));
}else{
val.push(coerce(this.type[i], value));
}
}
return key + space + val.join(space);
} | javascript | {
"resource": ""
} |
q40963 | qualityCmp | train | function qualityCmp(a, b) {
if (a.quality === b.quality) {
return 0;
} else if (a.quality < b.quality) {
return 1;
} else {
return -1;
}
} | javascript | {
"resource": ""
} |
q40964 | parseEncoding | train | function parseEncoding(s, i) {
var match = s.match(/^\s*(\S+?)\s*(?:;(.*))?$/);
if (!match) return null;
var encoding = match[1];
var q = 1;
if (match[2]) {
var params = match[2].split(';');
for (var i = 0; i < params.length; i ++) {
var p = params[i].trim().split('=');
if (p[0] === 'q') {
q = parseFloat(p[1]);
break;
}
}
}
return {
encoding: encoding,
q: q,
i: i
};
} | javascript | {
"resource": ""
} |
q40965 | getMagic | train | function getMagic() {
var mmmagic;
if (magic || magic === false) {
return magic;
}
// Get mmmagic module
mmmagic = alchemy.use('mmmagic')
if (mmmagic) {
magic = new mmmagic.Magic(mmmagic.MAGIC_MIME_TYPE);
} else {
log.error('Could not load mmmagic module');
magic = false;
}
return magic;
} | javascript | {
"resource": ""
} |
q40966 | indent | train | function indent(node) {
var next = node;
var i = 0;
while (next) {
++i;
next = next.suite || next.parent;
}
return Array(i).join(' ');
} | javascript | {
"resource": ""
} |
q40967 | route | train | function route() {
configure()
middlewares()
for (let route of config.routes) {
if (route.type === 'view')
server[route.method](route.src, (req, res) => {
res.render(`${app.root}/views/${route.dest}.twig`, {})
})
if (route.type === 'controller') {
let [path, method] = route.dest.split('::')
let controller = function () {
if (!app.controllers)
return require(`${app.root}/controllers/${path.replace('.', '/')}`)(app)
if (path.split('.').length > 1)
return app.controllers[path.split('.')[0]][path.split('.')[1]]
else
return app.controllers[path]
}()
let func = wrapper(controller[method])
if (!func)
app.drivers.logger.error('blockbase-express - wrapper', `Undefined function ${controller}${method}`)
if (route.method === 'post' || route.method === 'put')
server[route.method](route.src, upload.any(), func)
else
server[route.method](route.src, func)
}
}
errors()
} | javascript | {
"resource": ""
} |
q40968 | errors | train | function errors() {
// handling 404 errors from config.express['404_redirect'] property
if (config['404_redirect']) {
server.use(function (req, res, next) {
res.status(302)
res.writeHead(302, { 'Location': config['404_redirect'] })
res.end()
})
} else {
server.use(function (req, res, next) {
res.status(404).send({ message: 'not found' })
})
}
if (errorHandlers.length) {
for (let eh of errorHandlers) {
server.use(wrapper(eh))
}
}
//Default error handler
server.use((err, req, res, next) => {
if (!config.silent && !errorHandlers.length)
app.drivers.logger.error('Unhandled server error', err)
res.status(500)
.json({
message: err.message,
stack: process.env.NODE_ENV === 'production' ? undefined : err.stack
})
})
} | javascript | {
"resource": ""
} |
q40969 | sadd | train | function sadd(key /* member-1, member-N, req */) {
var args = slice.call(arguments, 1)
, req = typeof args[args.length-1] === 'object' ? args.pop() : null
, val = this.getKey(key, req);
if(val === undefined) {
val = new Set();
this.setKey(key, val, undefined, undefined, undefined, req);
}
return val.sadd(args);
} | javascript | {
"resource": ""
} |
q40970 | smembers | train | function smembers(key, req) {
var val = this.getKey(key, req);
if(val === undefined) return [];
return val.data;
} | javascript | {
"resource": ""
} |
q40971 | sismember | train | function sismember(key, member, req) {
var val = this.getKey(key, req);
if(val === undefined) return 0;
return val.sismember(member);
} | javascript | {
"resource": ""
} |
q40972 | spop | train | function spop(key, req) {
var val = this.getKey(key, req);
if(val === undefined) return null;
var element = val.spop();
if(val.scard() === 0) {
this.delKey(key, req);
}
return element;
} | javascript | {
"resource": ""
} |
q40973 | srem | train | function srem(key /* member-1, member-N, req */) {
var args = slice.call(arguments, 1)
, req = typeof args[args.length-1] === 'object' ? args.pop() : null
, val = this.getKey(key, req);
if(val === undefined) return 0;
var deleted = val.srem(args);
if(val.scard() === 0) {
this.delKey(key, req);
}
return deleted;
} | javascript | {
"resource": ""
} |
q40974 | smove | train | function smove(source, destination, member, req) {
var src = this.getKey(source, req)
, dest = this.getKey(destination, req);
if(src === undefined || !src.sismember(member)) return 0;
if(dest === undefined) {
dest = new Set();
this.setKey(destination, dest, undefined, undefined, undefined, req);
}
//console.dir(member);
src.delKey(member);
dest.sadd([member]);
if(src.scard() === 0) {
this.delKey(source, req);
}
return 1;
} | javascript | {
"resource": ""
} |
q40975 | sunion | train | function sunion(/* key-1, key-N, req*/) {
var args = slice.call(arguments, 0)
, req = typeof args[args.length-1] === 'object' ? args.pop() : null
, set
, src
, i;
set = new Set();
for(i = 0;i < args.length;i++) {
src = this.getKey(args[i], req);
if(src === undefined) continue;
set.sadd(src.data);
}
return set.data;
} | javascript | {
"resource": ""
} |
q40976 | sunionstore | train | function sunionstore(destination /* key-1, key-N, req*/) {
var args = slice.call(arguments, 1)
, req = typeof args[args.length-1] === 'object'
? args[args.length - 1] : null;
var list = this.sunion.apply(this, args);
if(list.length) {
this.setKey(
destination, new Set(list), undefined, undefined, undefined, req);
}
return list.length;
} | javascript | {
"resource": ""
} |
q40977 | sinter | train | function sinter(/* key-1, key-N, req*/) {
var args = slice.call(arguments, 0)
, req = typeof args[args.length-1] === 'object' ? args.pop() : null
, set = new Set()
, list
, src
, i;
for(i = 0;i < args.length;i++) {
src = this.getKey(args[i], req);
if(src === undefined) return [];
set.sadd(src.data);
}
list = set.data.slice(0);
function filter(member) {
for(i = 0;i < args.length;i++) {
src = this.getKey(args[i]);
if(!src.sismember(member)) return false;
}
return true;
}
list = list.filter(filter.bind(this));
return list;
} | javascript | {
"resource": ""
} |
q40978 | sinterstore | train | function sinterstore(destination /* key-1, key-N, req*/) {
var args = slice.call(arguments, 1)
, req = typeof args[args.length - 1] === 'object'
? args[args.length - 1] : null;
var list = this.sinter.apply(this, args);
if(list.length) {
this.setKey(
destination, new Set(list), undefined, undefined, undefined, req);
}
return list.length;
} | javascript | {
"resource": ""
} |
q40979 | sdiff | train | function sdiff(key /* key-1, key-N, req*/) {
var args = slice.call(arguments, 1)
, req = typeof args[args.length - 1] === 'object' ? args.pop() : null
, set = this.getKey(key, req)
, list
, src
, j
, i;
if(!set) return [];
list = set.data.slice(0);
for(j = 0;j < list.length;j++) {
for(i = 0;i < args.length;i++) {
src = this.getKey(args[i], req);
if(src === undefined) continue;
if(src.sismember(list[j])) {
list.splice(j, 1);
j--;
break;
}
}
}
return list;
} | javascript | {
"resource": ""
} |
q40980 | sdiffstore | train | function sdiffstore(destination /* key-1, key-N, req*/) {
var args = slice.call(arguments, 1)
, req = typeof args[args.length - 1] === 'object'
? args[args.length - 1] : null;
var list = this.sdiff.apply(this, args);
if(list.length) {
this.setKey(
destination, new Set(list), undefined, undefined, undefined, req);
}
return list.length;
} | javascript | {
"resource": ""
} |
q40981 | existence | train | function existence ( filepath ) {
var does = grunt.file.exists ( filepath );
if ( !does ) {
grunt.log.warn ( filepath + " not found." );
}
return does;
} | javascript | {
"resource": ""
} |
q40982 | clone | train | function clone(url, dir) {
_child_process2['default'].execSync('git clone ' + url, { cwd: _path2['default'].resolve(dir) });
} | javascript | {
"resource": ""
} |
q40983 | listTags | train | function listTags(localRepoDir) {
var stdout = _child_process2['default'].execSync('git tag -l', { cwd: _path2['default'].resolve(localRepoDir) });
return stdout.toString().match(/[^\r\n]+/g).filter(function (v) {
return v.length !== 0;
}).map(function (v) {
return v.trim();
});
} | javascript | {
"resource": ""
} |
q40984 | buildIndexFile | train | function buildIndexFile(isProd) {
return new Promise((resolve) => {
files.readFile(path.resolve(__dirname, ".includes/index.html"), (err, html) => {
if (err) throw err;
html = html.replace("$appDesc$", wapitisConfig.appDesc);
html = html.replace("$themeColor$", wapitisConfig.themeColor);
html = html.replace("$appName$", wapitisConfig.appName);
if (isProd) {
const quantumFile = JSON.parse(files.readFileSync(completeDistPath + "/quantum.json", "utf8"));
html = html.replace("$bundle$", `<script src="${quantumFile.bundle.relativePath}"></script>`);
files.remove(completeDistPath + "/quantum.json");
} else html = html.replace("$bundle$", '<script src="bundle.js"></script>');
files.appendFile(completeDistPath + "/index.html", html, true).then(() => resolve());
});
});
} | javascript | {
"resource": ""
} |
q40985 | getChildRegistry | train | function getChildRegistry(element, findClosest) {
assert((element === window) || (element instanceof Node) || !element, 'Invalid element specified');
assertType(findClosest, 'boolean', true, `The parameter 'findClosest', if specified, must be a boolean value`);
if (!element || element === document || element === document.body) element = window;
if (element === window) {
if (!window.__private__) window.__private__ = {};
if (window.__private__.childRegistry === undefined) window.__private__.childRegistry = {};
}
if (element.__private__ && element.__private__.childRegistry) {
return element.__private__.childRegistry;
}
else if (findClosest === true) {
return getChildRegistry(element.parentNode);
}
else {
return null;
}
} | javascript | {
"resource": ""
} |
q40986 | translate | train | function translate(cldr, locale, opts) {
if (typeof cldr === 'string') return augment(interpolate(cldr, opts));
opts = opts || {};
var pluralize = lookup(locale, cldr._format || opts.pluralFormat, plural);
if (Array.isArray(cldr)) cldr = convertArray(cldr, pluralize, opts);
validate(cldr, pluralize);
var paramsObj = {};
var cases = toFunctions(cldr, pluralize, opts, paramsObj);
var paramsKeys = Object.keys(paramsObj);
var key = cldr._plural_key ||
opts.pluralKey ||
discoverKey(paramsKeys,
opts.discoverableKeys || {'smart_count':1, 'count':1, 'length':1, 'items':1, 'total':1},
opts.defaultPluralKey || 'smart_count');
var validatePluralKey = opts.validatePluralKey !== false;
var silentValidation = !!opts.validatePluralSilent;
var decimal = number.decimal[locale] || number.decimal.en;
var toLocaleString = opts.toLocaleString !== false;
return augment(function(params) {
if (typeof params === 'number') params = convertSmartCount(params, key);
var count = parseInt(params[key], 10);
if (validatePluralKey && isNaN(count)) {
if (silentValidation) return [];
throw new Error('expected "' + key + '" to be a number. got "' + (typeof params[key]) + '".');
}
if (toLocaleString) params = formatNumbers(params, decimal);
return (cases[count] || cases[pluralize(count || 0)])(params);
}, paramsKeys);
} | javascript | {
"resource": ""
} |
q40987 | validate | train | function validate(cldr, pluralize) {
pluralize.formats.forEach(function(key) {
if (!cldr[key]) throw new Error('translation object missing required key "' + key + '"');
});
} | javascript | {
"resource": ""
} |
q40988 | toFunctions | train | function toFunctions(cldr, pluralize, opts, paramsObj) {
return Object.keys(cldr).reduce(function(acc, key) {
if (key.indexOf('_') === 0) return acc;
var value = cldr[key];
if (typeof value !== 'string') return acc;
var t = acc[key] = interpolate(value, opts);
merge(paramsObj, t.params);
return acc;
}, {});
} | javascript | {
"resource": ""
} |
q40989 | discoverKey | train | function discoverKey(arr, discoverableKeys, defaultKey) {
if (arr.length === 0) return defaultKey;
if (arr.length === 1) return arr[0];
for (var i = 0; i < arr.length; i++) {
if (discoverableKeys[arr[i]]) return arr[i];
}
return defaultKey;
} | javascript | {
"resource": ""
} |
q40990 | augment | train | function augment(fn, keys) {
keys = keys || fn.params || [];
if (!Array.isArray(keys)) keys = Object.keys(keys);
fn.params = keys;
return fn;
} | javascript | {
"resource": ""
} |
q40991 | lookup | train | function lookup(locale, format, obj) {
if (!locale) throw new Error('missing required "locale" parameter');
locale = locale.toLowerCase().replace('-', '_');
format = format || 'cardinal';
var p = obj[format];
if (!p) throw new Error('unsupported format "' + format + '"');
var fn = p[locale] || p[locale.split('_')[0]];
if (fn) return fn;
throw new Error('unsupported locale "' + locale + '"');
} | javascript | {
"resource": ""
} |
q40992 | convertArray | train | function convertArray(arr, pluralize, opts) {
if (arr.length !== pluralize.count) throw new Error('missing required length of plural formats: expected ' + pluralize.count + '; got ' + arr.length);
return pluralize.formats.reduce(function(acc, key, i) {
acc[key] = arr[i];
return acc;
}, {});
} | javascript | {
"resource": ""
} |
q40993 | formatNumbers | train | function formatNumbers(prevParams, decimal) {
var params = {}, value;
for (var k in prevParams) {
value = prevParams[k];
params[k] = typeof value === 'number' ? decimal(value) : value;
}
return params;
} | javascript | {
"resource": ""
} |
q40994 | Controller | train | function Controller (message) {
if (!(message instanceof Message)) throw new Error('message must be an instanceof Message');
if (!(this instanceof Controller)) return new Controller(message);
debug('new controller');
events.EventEmitter.call(this);
this.message = message;
this.data = this.message.data;
} | javascript | {
"resource": ""
} |
q40995 | toRgba | train | function toRgba(color, opacity = false) {
color = tinycolor(color);
if (opacity) {
color.setAlpha(calcOpacity(opacity));
}
return color.toRgbString();
} | javascript | {
"resource": ""
} |
q40996 | isEmpty | train | function isEmpty(value) {
if (Array.isArray(value)) {
// If first item in array is undefined, we assume there are no parameters
// This happens as a result of using the rest operator in a mixin
return value.length === 0 || value[0] === undefined;
}
return value === undefined;
} | javascript | {
"resource": ""
} |
q40997 | isFraction | train | function isFraction(value) {
if (typeof value !== 'string') {
return false;
}
value = value.split('/');
return value.length === 2 && value[0] % 1 === 0 && value[1] % 1 === 0;
} | javascript | {
"resource": ""
} |
q40998 | prefix | train | function prefix(value, prefix, ignored = []) {
if (prefix === false) {
return value;
}
if (ignored.includes(prefix)) {
return toDashCase(value);
}
return prefix + '-' + toDashCase(value);
} | javascript | {
"resource": ""
} |
q40999 | unit | train | function unit(value, property) {
let ignored = ['font-weight', 'opacity', 'content', 'columns', 'column-count'];
if (ignored.includes(property) || property === false || value === 0 || /\s/.test(value)) {
return value.toString();
}
if (! isUnit(value) && isNumber(value)) {
if (property === 'line-height') {
value += units.lineHeight;
} else {
value += units.default;
}
}
return value;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.