_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q27900 | reportInferrableType | train | function reportInferrableType(node, typeNode, initNode) {
if (!typeNode || !initNode || !typeNode.typeAnnotation) {
return;
}
if (!isInferrable(typeNode, initNode)) {
return;
}
const typeMap = {
TSBooleanKeyword: "boolean",
TSNumberKeyword: "number",
TSStringKeyword: "string",
};
const type = typeMap[typeNode.typeAnnotation.type];
context.report({
node,
message:
"Type {{type}} trivially inferred from a {{type}} literal, remove type annotation.",
data: {
type,
},
fix: fixer => fixer.remove(typeNode),
});
} | javascript | {
"resource": ""
} |
q27901 | checkMemberSeparatorStyle | train | function checkMemberSeparatorStyle(node) {
const isInterface = node.type === "TSInterfaceBody";
const isSingleLine = node.loc.start.line === node.loc.end.line;
const members = isInterface ? node.body : node.members;
const typeOpts = isInterface
? interfaceOptions
: typeLiteralOptions;
const opts = isSingleLine
? typeOpts.singleline
: typeOpts.multiline;
members.forEach((member, index) => {
checkLastToken(member, opts, index === members.length - 1);
});
} | javascript | {
"resource": ""
} |
q27902 | deepMerge | train | function deepMerge(first = {}, second = {}) {
// get the unique set of keys across both objects
const keys = new Set(Object.keys(first).concat(Object.keys(second)));
return Array.from(keys).reduce((acc, key) => {
const firstHasKey = key in first;
const secondHasKey = key in second;
if (firstHasKey && secondHasKey) {
if (isObjectNotArray(first[key]) && isObjectNotArray(second[key])) {
// object type
acc[key] = deepMerge(first[key], second[key]);
} else {
// value type
acc[key] = second[key];
}
} else if (firstHasKey) {
acc[key] = first[key];
} else {
acc[key] = second[key];
}
return acc;
}, {});
} | javascript | {
"resource": ""
} |
q27903 | generate | train | function generate() {
// replace this with Object.entries when node > 8
const allRules = requireIndex(path.resolve(__dirname, "../lib/rules"));
const rules = Object.keys(allRules)
.filter(key => !!allRules[key].meta.docs.recommended)
.reduce((config, key) => {
// having this here is just for output niceness (the keys will be ordered)
if (bannedRecommendedRules.has(key)) {
console.log(key.padEnd(MAX_RULE_NAME_LENGTH), "= off");
config[key] = "off";
}
const ruleName = `typescript/${key}`;
const setting = allRules[key].meta.docs.recommended;
if (!["error", "warn"].includes(setting)) {
console.log(`ERR! Invalid level for rule ${key}: "${setting}"`);
// Don't want to throw an error since ^ explains what happened.
// eslint-disable-next-line no-process-exit
process.exit(1);
}
console.log(ruleName.padEnd(MAX_RULE_NAME_LENGTH), "=", setting);
config[ruleName] = setting;
return config;
}, {});
const filePath = path.resolve(__dirname, "../lib/configs/recommended.json");
const recommendedConfig = {
parser: "eslint-plugin-typescript/parser",
parserOptions: {
sourceType: "module",
},
plugins: ["typescript"],
rules,
};
fs.writeFileSync(
filePath,
`${JSON.stringify(recommendedConfig, null, 4)}\n`
);
} | javascript | {
"resource": ""
} |
q27904 | checkBodyForOverloadMethods | train | function checkBodyForOverloadMethods(node) {
const members = node.body || node.members;
if (members) {
let name;
let index;
let lastName;
const seen = [];
members.forEach(member => {
name = getMemberName(member);
index = seen.indexOf(name);
if (index > -1 && lastName !== name) {
context.report({
node: member,
messageId: "adjacentSignature",
data: {
name,
},
});
} else if (name && index === -1) {
seen.push(name);
}
lastName = name;
});
}
} | javascript | {
"resource": ""
} |
q27905 | markThisParameterAsUsed | train | function markThisParameterAsUsed(node) {
if (node.name) {
const variable = context
.getScope()
.variables.find(scopeVar => scopeVar.name === node.name);
if (variable) {
variable.eslintUsed = true;
}
}
} | javascript | {
"resource": ""
} |
q27906 | TSPropertySignatureToProperty | train | function TSPropertySignatureToProperty(node, type = "Property") {
return {
type,
key: node.key,
value: node.value || node.typeAnnotation,
// Property flags
computed: false,
method: false,
kind: "init",
// this will stop eslint from interrogating the type literal
shorthand: true,
// location data
parent: node.parent,
range: node.range,
loc: node.loc,
};
} | javascript | {
"resource": ""
} |
q27907 | checkPropertyAccessibilityModifier | train | function checkPropertyAccessibilityModifier(classProperty) {
if (
!classProperty.accessibility &&
util.isTypescript(context.getFilename())
) {
context.report({
node: classProperty,
message:
"Missing accessibility modifier on class property {{name}}.",
data: {
name: classProperty.key.name,
},
});
}
} | javascript | {
"resource": ""
} |
q27908 | isSimpleType | train | function isSimpleType(node) {
switch (node.type) {
case "Identifier":
case "TSAnyKeyword":
case "TSBooleanKeyword":
case "TSNeverKeyword":
case "TSNumberKeyword":
case "TSObjectKeyword":
case "TSStringKeyword":
case "TSSymbolKeyword":
case "TSUnknownKeyword":
case "TSVoidKeyword":
case "TSNullKeyword":
case "TSArrayType":
case "TSUndefinedKeyword":
case "TSThisType":
case "TSQualifiedName":
return true;
case "TSTypeReference":
if (
node.typeName &&
node.typeName.type === "Identifier" &&
node.typeName.name === "Array"
) {
if (!node.typeParameters) {
return true;
}
if (node.typeParameters.params.length === 1) {
return isSimpleType(node.typeParameters.params[0]);
}
} else {
if (node.typeParameters) {
return false;
}
return isSimpleType(node.typeName);
}
return false;
default:
return false;
}
} | javascript | {
"resource": ""
} |
q27909 | typeNeedsParentheses | train | function typeNeedsParentheses(node) {
if (node.type === "TSTypeReference") {
switch (node.typeName.type) {
case "TSUnionType":
case "TSFunctionType":
case "TSIntersectionType":
case "TSTypeOperator":
return true;
default:
return false;
}
}
return false;
} | javascript | {
"resource": ""
} |
q27910 | requireWhitespaceBefore | train | function requireWhitespaceBefore(node) {
const prevToken = sourceCode.getTokenBefore(node);
if (node.range[0] - prevToken.range[1] > 0) {
return false;
}
return prevToken.type === "Identifier";
} | javascript | {
"resource": ""
} |
q27911 | parseOptions | train | function parseOptions(options) {
let functions = true;
let classes = true;
let variables = true;
let typedefs = true;
if (typeof options === "string") {
functions = options !== "nofunc";
} else if (typeof options === "object" && options !== null) {
functions = options.functions !== false;
classes = options.classes !== false;
variables = options.variables !== false;
typedefs = options.typedefs !== false;
}
return { functions, classes, variables, typedefs };
} | javascript | {
"resource": ""
} |
q27912 | split | train | function split(str, separator) {
separator = separator || '';
if (_.isString(str)) {
return str.split(separator);
} else {
return str;
}
} | javascript | {
"resource": ""
} |
q27913 | padding | train | function padding(size,ch){
var str = '';
if(!ch && ch !== 0){
ch = ' ';
}
while(size !== 0){
if(size & 1 === 1){
str += ch;
}
ch += ch;
size >>>= 1;
}
return str;
} | javascript | {
"resource": ""
} |
q27914 | debounce | train | function debounce(handler, delay) {
if (!handler){
return;
}
if (!delay) {
delay = 300;
}
return _.debounce(handler, delay);
} | javascript | {
"resource": ""
} |
q27915 | append | train | function append(str, postfix) {
if (!str && str !== 0) {
str = '';
} else {
str = str.toString();
}
return str + postfix;
} | javascript | {
"resource": ""
} |
q27916 | prepend | train | function prepend(str, prefix) {
if (!str && str !== 0) {
str = '';
} else {
str = str.toString();
}
return prefix + str;
} | javascript | {
"resource": ""
} |
q27917 | reverse | train | function reverse(collection) {
if (typeof collection === 'string') {
return collection.split('').reverse().join('');
}
if(_.isArray(collection)){
return collection.concat().reverse();
}
return collection;
} | javascript | {
"resource": ""
} |
q27918 | transCalc | train | function transCalc(transFrom, transTo, progress) {
var res={};
for(var i in transFrom) {
switch(i) {
case 'rotate':
res[i]=[0,0,0];
for(var j=0;j<3;j++) {
res[i][j]=transFrom[i][j]+(transTo[i][j]-transFrom[i][j])*progress;
}
break;
}
}
return res;
} | javascript | {
"resource": ""
} |
q27919 | curveCalc | train | function curveCalc(curveFrom, curveTo, progress) {
var curve=[];
for(var i=0,len1=curveFrom.length;i<len1;i++) {
curve.push([curveFrom[i][0]]);
for(var j=1,len2=curveFrom[i].length;j<len2;j++) {
curve[i].push(curveFrom[i][j]+(curveTo[i][j]-curveFrom[i][j])*progress);
}
}
return curve;
} | javascript | {
"resource": ""
} |
q27920 | initialize | train | function initialize(passport) {
const middleware = promisify(_initialize(passport))
return function passportInitialize(ctx, next) {
// koa <-> connect compatibility:
const userProperty = passport._userProperty || 'user'
// check ctx.req has the userProperty
if (!ctx.req.hasOwnProperty(userProperty)) {
Object.defineProperty(ctx.req, userProperty, {
enumerable: true,
get: function() {
return ctx.state[userProperty]
},
set: function(val) {
ctx.state[userProperty] = val
}
})
}
// create mock object for express' req object
const req = createReqMock(ctx, userProperty)
// add Promise-based login method
const login = req.login
ctx.login = ctx.logIn = function(user, options) {
return new Promise((resolve, reject) => {
login.call(req, user, options, err => {
if (err) reject(err)
else resolve()
})
})
}
// add aliases for passport's request extensions to Koa's context
ctx.logout = ctx.logOut = req.logout.bind(req)
ctx.isAuthenticated = req.isAuthenticated.bind(req)
ctx.isUnauthenticated = req.isUnauthenticated.bind(req)
return middleware(req, ctx).then(function() {
return next()
})
}
} | javascript | {
"resource": ""
} |
q27921 | authenticate | train | function authenticate(passport, name, options, callback) {
// normalize arguments
if (typeof options === 'function') {
callback = options
options = {}
}
options = options || {}
if (callback) {
// When the callback is set, neither `next`, `res.redirect` or `res.end`
// are called. That is, a workaround to catch the `callback` is required.
// The `passportAuthenticate()` method below will therefore set
// `callback.resolve` and `callback.reject`. Then, once the authentication
// finishes, the modified callback calls the original one and afterwards
// triggers either `callback.resolve` or `callback.reject` to inform
// `passportAuthenticate()` that we are ready.
const _callback = callback
callback = function(err, user, info, status) {
try {
Promise.resolve(_callback(err, user, info, status))
.then(() => callback.resolve(false))
.catch(err => callback.reject(err))
} catch (err) {
callback.reject(err)
}
}
}
const middleware = promisify(_authenticate(passport, name, options, callback))
return function passportAuthenticate(ctx, next) {
// this functions wraps the connect middleware
// to catch `next`, `res.redirect` and `res.end` calls
const p = new Promise((resolve, reject) => {
// mock the `req` object
const req = createReqMock(ctx, options.assignProperty || passport._userProperty || 'user')
function setBodyAndResolve(content) {
if (content) ctx.body = content
resolve(false)
}
// mock the `res` object
const res = {
redirect: function(url) {
ctx.redirect(url)
resolve(false)
},
set: ctx.set.bind(ctx),
setHeader: ctx.set.bind(ctx),
end: setBodyAndResolve,
send: setBodyAndResolve,
set statusCode(status) {
ctx.status = status
},
get statusCode() {
return ctx.status
}
}
req.res = res
// update the custom callback above
if (callback) {
callback.resolve = resolve
callback.reject = reject
}
// call the connect middleware
middleware(req, res).then(resolve, reject)
})
return p.then(cont => {
// cont equals `false` when `res.redirect` or `res.end` got called
// in this case, call next to continue through Koa's middleware stack
if (cont !== false) {
return next()
}
})
}
} | javascript | {
"resource": ""
} |
q27922 | authorize | train | function authorize(passport, name, options, callback) {
options = options || {}
options.assignProperty = 'account'
return authenticate(passport, name, options, callback)
} | javascript | {
"resource": ""
} |
q27923 | getObject | train | function getObject(ctx, key) {
if (ctx.state && (key in ctx.state)) {
return ctx.state
}
if (key in ctx.request) {
return ctx.request
}
if (key in ctx.req) {
return ctx.req
}
if (key in ctx) {
return ctx
}
return undefined
} | javascript | {
"resource": ""
} |
q27924 | Core | train | function Core(el, options) {
var editor;
this.el = el;
this.$el = $(el);
this.templates = window.MediumInsert.Templates;
if (options) {
// Fix #142
// Avoid deep copying editor object, because since v2.3.0 it contains circular references which causes jQuery.extend to break
// Instead copy editor object to this.options manually
editor = options.editor;
options.editor = null;
}
this.options = $.extend(true, {}, defaults, options);
this.options.editor = editor;
if (options) {
options.editor = editor; // Restore original object definition
}
this._defaults = defaults;
this._name = pluginName;
// Extend editor's functions
if (this.options && this.options.editor) {
if (this.options.editor._serialize === undefined) {
this.options.editor._serialize = this.options.editor.serialize;
}
if (this.options.editor._destroy === undefined) {
this.options.editor._destroy = this.options.editor.destroy;
}
if (this.options.editor._setup === undefined) {
this.options.editor._setup = this.options.editor.setup;
}
this.options.editor._hideInsertButtons = this.hideButtons;
this.options.editor.serialize = this.editorSerialize;
this.options.editor.destroy = this.editorDestroy;
this.options.editor.setup = this.editorSetup;
if (this.options.editor.getExtensionByName('placeholder') !== undefined) {
this.options.editor.getExtensionByName('placeholder').updatePlaceholder = this.editorUpdatePlaceholder;
}
}
} | javascript | {
"resource": ""
} |
q27925 | placeCaret | train | function placeCaret(el, position) {
var range, sel;
range = document.createRange();
sel = window.getSelection();
range.setStart(el.childNodes[0], position);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
} | javascript | {
"resource": ""
} |
q27926 | isCached | train | function isCached(config) {
var cache;
var defaultCache = $cacheFactory.get('$http');
var defaults = $httpProvider.defaults;
// Choose the proper cache source. Borrowed from angular: $http service
if ((config.cache || defaults.cache) && config.cache !== false &&
(config.method === 'GET' || config.method === 'JSONP')) {
cache = angular.isObject(config.cache) ? config.cache
: angular.isObject(defaults.cache) ? defaults.cache
: defaultCache;
}
var cached = cache !== undefined ?
cache.get(config.url) !== undefined : false;
if (config.cached !== undefined && cached !== config.cached) {
return config.cached;
}
config.cached = cached;
return cached;
} | javascript | {
"resource": ""
} |
q27927 | _start | train | function _start() {
if (!$animate) {
$animate = $injector.get('$animate');
}
$timeout.cancel(completeTimeout);
// do not continually broadcast the started event:
if (started) {
return;
}
var document = $document[0];
var parent = document.querySelector ?
document.querySelector($parentSelector)
: $document.find($parentSelector)[0]
;
if (! parent) {
parent = document.getElementsByTagName('body')[0];
}
var $parent = angular.element(parent);
var $after = parent.lastChild && angular.element(parent.lastChild);
$rootScope.$broadcast('cfpLoadingBar:started');
started = true;
if (includeBar) {
$animate.enter(loadingBarContainer, $parent, $after);
}
if (includeSpinner) {
$animate.enter(spinner, $parent, loadingBarContainer);
}
_set(startSize);
} | javascript | {
"resource": ""
} |
q27928 | _set | train | function _set(n) {
if (!started) {
return;
}
var pct = (n * 100) + '%';
loadingBar.css('width', pct);
status = n;
// increment loadingbar to give the illusion that there is always
// progress but make sure to cancel the previous timeouts so we don't
// have multiple incs running at the same time.
if (autoIncrement) {
$timeout.cancel(incTimeout);
incTimeout = $timeout(function() {
_inc();
}, 250);
}
} | javascript | {
"resource": ""
} |
q27929 | _inc | train | function _inc() {
if (_status() >= 1) {
return;
}
var rnd = 0;
// TODO: do this mathmatically instead of through conditions
var stat = _status();
if (stat >= 0 && stat < 0.25) {
// Start out between 3 - 6% increments
rnd = (Math.random() * (5 - 3 + 1) + 3) / 100;
} else if (stat >= 0.25 && stat < 0.65) {
// increment between 0 - 3%
rnd = (Math.random() * 3) / 100;
} else if (stat >= 0.65 && stat < 0.9) {
// increment between 0 - 2%
rnd = (Math.random() * 2) / 100;
} else if (stat >= 0.9 && stat < 0.99) {
// finally, increment it .5 %
rnd = 0.005;
} else {
// after 99%, don't increment:
rnd = 0;
}
var pct = _status() + rnd;
_set(pct);
} | javascript | {
"resource": ""
} |
q27930 | eatNargs | train | function eatNargs (i, key, args) {
var ii
const toEat = checkAllAliases(key, flags.nargs)
// nargs will not consume flag arguments, e.g., -abc, --foo,
// and terminates when one is observed.
var available = 0
for (ii = i + 1; ii < args.length; ii++) {
if (!args[ii].match(/^-[^0-9]/)) available++
else break
}
if (available < toEat) error = Error(__('Not enough arguments following: %s', key))
const consumed = Math.min(available, toEat)
for (ii = i + 1; ii < (consumed + i + 1); ii++) {
setArg(key, args[ii])
}
return (i + consumed)
} | javascript | {
"resource": ""
} |
q27931 | setConfig | train | function setConfig (argv) {
var configLookup = {}
// expand defaults/aliases, in-case any happen to reference
// the config.json file.
applyDefaultsAndAliases(configLookup, flags.aliases, defaults)
Object.keys(flags.configs).forEach(function (configKey) {
var configPath = argv[configKey] || configLookup[configKey]
if (configPath) {
try {
var config = null
var resolvedConfigPath = path.resolve(process.cwd(), configPath)
if (typeof flags.configs[configKey] === 'function') {
try {
config = flags.configs[configKey](resolvedConfigPath)
} catch (e) {
config = e
}
if (config instanceof Error) {
error = config
return
}
} else {
config = require(resolvedConfigPath)
}
setConfigObject(config)
} catch (ex) {
if (argv[configKey]) error = Error(__('Invalid JSON config file: %s', configPath))
}
}
})
} | javascript | {
"resource": ""
} |
q27932 | setConfigObject | train | function setConfigObject (config, prev) {
Object.keys(config).forEach(function (key) {
var value = config[key]
var fullKey = prev ? prev + '.' + key : key
// if the value is an inner object and we have dot-notation
// enabled, treat inner objects in config the same as
// heavily nested dot notations (foo.bar.apple).
if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) {
// if the value is an object but not an array, check nested object
setConfigObject(value, fullKey)
} else {
// setting arguments via CLI takes precedence over
// values within the config file.
if (!hasKey(argv, fullKey.split('.')) || (flags.defaulted[fullKey]) || (flags.arrays[fullKey] && configuration['combine-arrays'])) {
setArg(fullKey, value)
}
}
})
} | javascript | {
"resource": ""
} |
q27933 | defaultValue | train | function defaultValue (key) {
if (!checkAllAliases(key, flags.bools) &&
!checkAllAliases(key, flags.counts) &&
`${key}` in defaults) {
return defaults[key]
} else {
return defaultForType(guessType(key))
}
} | javascript | {
"resource": ""
} |
q27934 | guessType | train | function guessType (key) {
var type = 'boolean'
if (checkAllAliases(key, flags.strings)) type = 'string'
else if (checkAllAliases(key, flags.numbers)) type = 'number'
else if (checkAllAliases(key, flags.arrays)) type = 'array'
return type
} | javascript | {
"resource": ""
} |
q27935 | combineAliases | train | function combineAliases (aliases) {
var aliasArrays = []
var change = true
var combined = {}
// turn alias lookup hash {key: ['alias1', 'alias2']} into
// a simple array ['key', 'alias1', 'alias2']
Object.keys(aliases).forEach(function (key) {
aliasArrays.push(
[].concat(aliases[key], key)
)
})
// combine arrays until zero changes are
// made in an iteration.
while (change) {
change = false
for (var i = 0; i < aliasArrays.length; i++) {
for (var ii = i + 1; ii < aliasArrays.length; ii++) {
var intersect = aliasArrays[i].filter(function (v) {
return aliasArrays[ii].indexOf(v) !== -1
})
if (intersect.length) {
aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii])
aliasArrays.splice(ii, 1)
change = true
break
}
}
}
}
// map arrays back to the hash-lookup (de-dupe while
// we're at it).
aliasArrays.forEach(function (aliasArray) {
aliasArray = aliasArray.filter(function (v, i, self) {
return self.indexOf(v) === i
})
combined[aliasArray.pop()] = aliasArray
})
return combined
} | javascript | {
"resource": ""
} |
q27936 | OAuth2Strategy | train | function OAuth2Strategy(options, verify) {
if (typeof options == 'function') {
verify = options;
options = undefined;
}
options = options || {};
if (!verify) { throw new TypeError('OAuth2Strategy requires a verify callback'); }
if (!options.authorizationURL) { throw new TypeError('OAuth2Strategy requires a authorizationURL option'); }
if (!options.tokenURL) { throw new TypeError('OAuth2Strategy requires a tokenURL option'); }
if (!options.clientID) { throw new TypeError('OAuth2Strategy requires a clientID option'); }
passport.Strategy.call(this);
this.name = 'oauth2';
this._verify = verify;
// NOTE: The _oauth2 property is considered "protected". Subclasses are
// allowed to use it when making protected resource requests to retrieve
// the user profile.
this._oauth2 = new OAuth2(options.clientID, options.clientSecret,
'', options.authorizationURL, options.tokenURL, options.customHeaders);
this._callbackURL = options.callbackURL;
this._scope = options.scope;
this._scopeSeparator = options.scopeSeparator || ' ';
this._pkceMethod = (options.pkce === true) ? 'S256' : options.pkce;
this._key = options.sessionKey || ('oauth2:' + url.parse(options.authorizationURL).hostname);
if (options.store) {
this._stateStore = options.store;
} else {
if (options.state) {
this._stateStore = options.pkce ? new PKCESessionStateStore({ key: this._key }) : new SessionStateStore({ key: this._key });
} else {
if (options.pkce) { throw new TypeError('OAuth2Strategy requires `state: true` option when PKCE is enabled'); }
this._stateStore = new NullStateStore();
}
}
this._trustProxy = options.proxy;
this._passReqToCallback = options.passReqToCallback;
this._skipUserProfile = (options.skipUserProfile === undefined) ? false : options.skipUserProfile;
} | javascript | {
"resource": ""
} |
q27937 | composeThen | train | function composeThen(req, res, ...mws) {
return new Promise((resolve, reject) => {
compose(...mws)(req, res, err => {
if (err) {
/* istanbul ignore next */
if (err instanceof MoleculerError)
return reject(err);
/* istanbul ignore next */
if (err instanceof Error)
return reject(new MoleculerError(err.message, err.code || err.status, err.type)); // TODO err.stack
/* istanbul ignore next */
return reject(new MoleculerError(err));
}
resolve();
});
});
} | javascript | {
"resource": ""
} |
q27938 | generateETag | train | function generateETag(body, opt) {
if (_.isFunction(opt))
return opt.call(this, body);
let buf = !Buffer.isBuffer(body)
? Buffer.from(body)
: body;
return etag(buf, (opt === true || opt === "weak") ? { weak: true } : null);
} | javascript | {
"resource": ""
} |
q27939 | isFresh | train | function isFresh(req, res) {
if ((res.statusCode >= 200 && res.statusCode < 300) || 304 === res.statusCode) {
return fresh(req.headers, {
"etag": res.getHeader("ETag"),
"last-modified": res.getHeader("Last-Modified")
});
}
return false;
} | javascript | {
"resource": ""
} |
q27940 | addClass | train | function addClass(node, name) {
if (hasClass(node, name)) {
return;
}
if (node.classList) {
node.classList.add(name);
} else {
node.className += " " + name;
}
} | javascript | {
"resource": ""
} |
q27941 | removeClass | train | function removeClass(node, name) {
var c = name.split(' ');
if (c.length > 1) {
each(c, function (cl) {
removeClass(node, cl);
});
return;
}
if (node.classList) {
node.classList.remove(name);
} else {
node.className = node.className.replace(name, "");
}
} | javascript | {
"resource": ""
} |
q27942 | createHTML | train | function createHTML(htmlStr) {
var frag = document.createDocumentFragment(),
temp = document.createElement('div');
temp.innerHTML = htmlStr;
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
return frag;
} | javascript | {
"resource": ""
} |
q27943 | getClosest | train | function getClosest(elem, selector) {
while (elem !== document.body) {
elem = elem.parentElement;
var matches = typeof elem.matches == 'function' ? elem.matches(selector) : elem.msMatchesSelector(selector);
if (matches) return elem;
}
} | javascript | {
"resource": ""
} |
q27944 | youtubeApiHandle | train | function youtubeApiHandle() {
for (var i = 0; i < YTTemp.length; i++) {
var iframe = YTTemp[i];
var player = new YT.Player(iframe);
videoPlayers[iframe.id] = player;
}
} | javascript | {
"resource": ""
} |
q27945 | waitUntil | train | function waitUntil(check, onComplete, delay, timeout) {
if (check()) {
onComplete();
return;
}
if (!delay) delay = 100;
var timeoutPointer = void 0;
var intervalPointer = setInterval(function () {
if (!check()) return;
clearInterval(intervalPointer);
if (timeoutPointer) clearTimeout(timeoutPointer);
onComplete();
}, delay);
if (timeout) timeoutPointer = setTimeout(function () {
clearInterval(intervalPointer);
}, timeout);
} | javascript | {
"resource": ""
} |
q27946 | setInlineContent | train | function setInlineContent(slide, data, callback) {
var slideMedia = slide.querySelector('.gslide-media');
var hash = data.href.split('#').pop().trim();
var div = document.getElementById(hash);
if (!div) {
return false;
}
var cloned = div.cloneNode(true);
cloned.style.height = data.height + 'px';
cloned.style.maxWidth = data.width + 'px';
addClass(cloned, 'ginlined-content');
slideMedia.appendChild(cloned);
if (utils.isFunction(callback)) {
callback();
}
return;
} | javascript | {
"resource": ""
} |
q27947 | getSourceType | train | function getSourceType(url) {
var origin = url;
url = url.toLowerCase();
if (url.match(/\.(jpeg|jpg|gif|png|apn|webp|svg)$/) !== null) {
return 'image';
}
if (url.match(/(youtube\.com|youtube-nocookie\.com)\/watch\?v=([a-zA-Z0-9\-_]+)/) || url.match(/youtu\.be\/([a-zA-Z0-9\-_]+)/)) {
return 'video';
}
if (url.match(/vimeo\.com\/([0-9]*)/)) {
return 'video';
}
if (url.match(/\.(mp4|ogg|webm)$/) !== null) {
return 'video';
}
// Check if inline content
if (url.indexOf("#") > -1) {
var hash = origin.split('#').pop();
if (hash.trim() !== '') {
return 'inline';
}
}
// Ajax
if (url.includes("gajax=true")) {
return 'ajax';
}
return 'external';
} | javascript | {
"resource": ""
} |
q27948 | keyboardNavigation | train | function keyboardNavigation() {
var _this3 = this;
if (this.events.hasOwnProperty('keyboard')) {
return false;
}
this.events['keyboard'] = addEvent('keydown', {
onElement: window,
withCallback: function withCallback(event, target) {
event = event || window.event;
var key = event.keyCode;
if (key == 39) _this3.nextSlide();
if (key == 37) _this3.prevSlide();
if (key == 27) _this3.close();
}
});
} | javascript | {
"resource": ""
} |
q27949 | getNodeEvents | train | function getNodeEvents(node, name = null, fn = null) {
const cache = (node[uid] = node[uid] || []);
const data = { all: cache, evt: null, found: null};
if (name && fn && utils.size(cache) > 0) {
each(cache, (cl, i) => {
if (cl.eventName == name && cl.fn.toString() == fn.toString()) {
data.found = true;
data.evt = i;
return false;
}
})
}
return data;
} | javascript | {
"resource": ""
} |
q27950 | addEvent | train | function addEvent(eventName, {
onElement,
withCallback,
avoidDuplicate = true,
once = false,
useCapture = false} = { }, thisArg) {
let element = onElement || []
if (utils.isString(element)) {
element = document.querySelectorAll(element)
}
function handler(event) {
if (utils.isFunction(withCallback)) {
withCallback.call(thisArg, event, this)
}
if (once) {
handler.destroy();
}
}
handler.destroy = function() {
each(element, (el) => {
const events = getNodeEvents(el, eventName, handler);
if (events.found) { events.all.splice(events.evt, 1); }
if (el.removeEventListener) el.removeEventListener(eventName, handler, useCapture)
})
}
each(element, (el) => {
const events = getNodeEvents(el, eventName, handler);
if (el.addEventListener && (avoidDuplicate && !events.found) || !avoidDuplicate) {
el.addEventListener(eventName, handler, useCapture)
events.all.push({ eventName: eventName, fn: handler});
}
})
return handler
} | javascript | {
"resource": ""
} |
q27951 | whichTransitionEvent | train | function whichTransitionEvent() {
let t,
el = document.createElement("fakeelement");
const transitions = {
transition: "transitionend",
OTransition: "oTransitionEnd",
MozTransition: "transitionend",
WebkitTransition: "webkitTransitionEnd"
};
for (t in transitions) {
if (el.style[t] !== undefined) {
return transitions[t];
}
}
} | javascript | {
"resource": ""
} |
q27952 | getSlideData | train | function getSlideData(element = null, settings) {
let data = {
href: '',
title: '',
type: '',
description: '',
descPosition: 'bottom',
effect: '',
node: element
};
if (utils.isObject(element) && !utils.isNode(element)){
return extend(data, element);
}
let url = '';
let config = element.getAttribute('data-glightbox')
let nodeType = element.nodeName.toLowerCase();
if (nodeType === 'a')
url = element.href;
if (nodeType === 'img')
url = element.src;
data.href = url;
each(data, (val, key) => {
if (utils.has(settings, key)) {
data[key] = settings[key];
}
const nodeData = element.dataset[key];
if (!utils.isNil(nodeData)) {
data[key] = nodeData;
}
});
if (!data.type) {
data.type = getSourceType(url);
}
if (!utils.isNil(config)) {
let cleanKeys = [];
each(data, (v, k) => {
cleanKeys.push(';\\s?' + k);
})
cleanKeys = cleanKeys.join('\\s?:|');
if (config.trim() !== '') {
each(data, (val, key) => {
const str = config;
const match = '\s?' + key + '\s?:\s?(.*?)(' + cleanKeys + '\s?:|$)';
const regex = new RegExp(match);
const matches = str.match(regex);
if (matches && matches.length && matches[1]) {
const value = matches[1].trim().replace(/;\s*$/, '');
data[key] = value;
}
});
}
} else {
if (nodeType == 'a') {
let title = element.title
if (!utils.isNil(title) && title !== '') data.title = title;
}
if (nodeType == 'img') {
let alt = element.alt
if (!utils.isNil(alt) && alt !== '') data.title = alt;
}
let desc = element.getAttribute('data-description')
if (!utils.isNil(desc) && desc !== '') data.description = desc;
}
let nodeDesc = element.querySelector('.glightbox-desc')
if (nodeDesc) {
data.description = nodeDesc.innerHTML;
}
const defaultWith = (data.type == 'video' ? settings.videosWidth : settings.width);
const defaultHeight = (data.type == 'video' ? settings.videosHeight : settings.height);
data.width = (utils.has(data, 'width') ? data.width : defaultWith);
data.height = (utils.has(data, 'height') ? data.height : defaultHeight);
return data;
} | javascript | {
"resource": ""
} |
q27953 | createIframe | train | function createIframe(config) {
let { url, width, height, allow, callback, appendTo } = config;
let iframe = document.createElement('iframe');
let winWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
iframe.className = 'vimeo-video gvideo';
iframe.src = url;
if (height) {
if (isMobile && winWidth < 767) {
iframe.style.height = ''
} else {
iframe.style.height = `${height}px`
}
}
if (width) {
iframe.style.width = `${width}px`
}
if (allow) {
iframe.setAttribute('allow', allow)
}
iframe.onload = function() {
addClass(iframe, 'iframe-ready');
if (utils.isFunction(callback)) {
callback()
}
};
if (appendTo) {
appendTo.appendChild(iframe);
}
return iframe;
} | javascript | {
"resource": ""
} |
q27954 | getYoutubeID | train | function getYoutubeID(url) {
let videoID = '';
url = url.replace(/(>|<)/gi, '').split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
if (url[2] !== undefined) {
videoID = url[2].split(/[^0-9a-z_\-]/i);
videoID = videoID[0];
} else {
videoID = url;
}
return videoID;
} | javascript | {
"resource": ""
} |
q27955 | injectVideoApi | train | function injectVideoApi(url, callback) {
if (utils.isNil(url)) {
console.error('Inject videos api error');
return;
}
let found = document.querySelectorAll('script[src="' + url + '"]')
if (utils.isNil(found) || found.length == 0) {
let script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.onload = () => {
if (utils.isFunction(callback)) callback();
};
document.body.appendChild(script);
return false;
}
if (utils.isFunction(callback)) callback();
} | javascript | {
"resource": ""
} |
q27956 | parseUrlParams | train | function parseUrlParams(params) {
let qs = '';
let i = 0;
each(params, (val, key) => {
if (i > 0) {
qs += '&';
}
qs += key + '=' + val;
i += 1;
})
return qs;
} | javascript | {
"resource": ""
} |
q27957 | getByIdQuery | train | function getByIdQuery(modelInstance) {
const modelClass = modelInstance.getClass();
const { idAttribute, modelName } = modelClass;
return {
table: modelName,
clauses: [
{
type: FILTER,
payload: {
[idAttribute]: modelInstance.getId(),
},
},
],
};
} | javascript | {
"resource": ""
} |
q27958 | attrDescriptor | train | function attrDescriptor(fieldName) {
return {
get() {
return this._fields[fieldName];
},
set(value) {
return this.set(fieldName, value);
},
enumerable: true,
configurable: true,
};
} | javascript | {
"resource": ""
} |
q27959 | manyToManyDescriptor | train | function manyToManyDescriptor(
declaredFromModelName,
declaredToModelName,
throughModelName,
throughFields,
reverse
) {
return {
get() {
const {
session: {
[declaredFromModelName]: DeclaredFromModel,
[declaredToModelName]: DeclaredToModel,
[throughModelName]: ThroughModel,
},
} = this.getClass();
const ThisModel = reverse
? DeclaredToModel
: DeclaredFromModel;
const OtherModel = reverse
? DeclaredFromModel
: DeclaredToModel;
const thisReferencingField = reverse
? throughFields.to
: throughFields.from;
const otherReferencingField = reverse
? throughFields.from
: throughFields.to;
const thisId = this.getId();
const throughQs = ThroughModel.filter({
[thisReferencingField]: thisId,
});
/**
* all IDs of instances of the other model that are
* referenced by any instance of the current model
*/
const referencedOtherIds = new Set(
throughQs
.toRefArray()
.map(obj => obj[otherReferencingField])
);
/**
* selects all instances of other model that are referenced
* by any instance of the current model
*/
const qs = OtherModel.filter(otherModelInstance => (
referencedOtherIds.has(
otherModelInstance[OtherModel.idAttribute]
)
));
/**
* Allows adding OtherModel instances to be referenced by the current instance.
*
* E.g. Book.first().authors.add(1, 2) would add the authors with IDs 1 and 2
* to the first book's list of referenced authors.
*
* @return undefined
*/
qs.add = function add(...entities) {
const idsToAdd = new Set(
entities.map(normalizeEntity)
);
const existingQs = throughQs.filter(through => (
idsToAdd.has(through[otherReferencingField])
));
if (existingQs.exists()) {
const existingIds = existingQs
.toRefArray()
.map(through => through[otherReferencingField]);
throw new Error(`Tried to add already existing ${OtherModel.modelName} id(s) ${existingIds} to the ${ThisModel.modelName} instance with id ${thisId}`);
}
idsToAdd.forEach((id) => {
ThroughModel.create({
[otherReferencingField]: id,
[thisReferencingField]: thisId,
});
});
};
/**
* Removes references to all OtherModel instances from the current model.
*
* E.g. Book.first().authors.clear() would cause the first book's list
* of referenced authors to become empty.
*
* @return undefined
*/
qs.clear = function clear() {
throughQs.delete();
};
/**
* Removes references to all passed OtherModel instances from the current model.
*
* E.g. Book.first().authors.remove(1, 2) would cause the authors with
* IDs 1 and 2 to no longer be referenced by the first book.
*
* @return undefined
*/
qs.remove = function remove(...entities) {
const idsToRemove = new Set(
entities.map(normalizeEntity)
);
const entitiesToDelete = throughQs.filter(
through => idsToRemove.has(through[otherReferencingField])
);
if (entitiesToDelete.count() !== idsToRemove.size) {
// Tried deleting non-existing entities.
const entitiesToDeleteIds = entitiesToDelete
.toRefArray()
.map(through => through[otherReferencingField]);
const unexistingIds = [...idsToRemove].filter(
id => !entitiesToDeleteIds.includes(id)
);
throw new Error(`Tried to delete non-existing ${OtherModel.modelName} id(s) ${unexistingIds} from the ${ThisModel.modelName} instance with id ${thisId}`);
}
entitiesToDelete.delete();
};
return qs;
},
set() {
throw new Error('Tried setting a M2M field. Please use the related QuerySet methods add, remove and clear.');
},
};
} | javascript | {
"resource": ""
} |
q27960 | normalizeEntity | train | function normalizeEntity(entity) {
if (entity !== null &&
typeof entity !== 'undefined' &&
typeof entity.getId === 'function') {
return entity.getId();
}
return entity;
} | javascript | {
"resource": ""
} |
q27961 | idSequencer | train | function idSequencer(_currMax, userPassedId) {
let currMax = _currMax;
let newMax;
let newId;
if (currMax === undefined) {
currMax = -1;
}
if (userPassedId === undefined) {
newMax = currMax + 1;
newId = newMax;
} else {
newMax = Math.max(currMax + 1, userPassedId);
newId = userPassedId;
}
return [
newMax, // new max id
newId, // id to use for row creation
];
} | javascript | {
"resource": ""
} |
q27962 | train | function (host, port) {
this.name = 'AVTransport'
this.host = host
this.port = port || 1400
this.controlURL = '/MediaRenderer/AVTransport/Control'
this.eventSubURL = '/MediaRenderer/AVTransport/Event'
this.SCPDURL = '/xml/AVTransport1.xml'
} | javascript | {
"resource": ""
} | |
q27963 | train | function (options) {
this.name = options.name
this.host = options.host
this.port = options.port || 1400
this.controlURL = options.controlURL
this.eventSubURL = options.eventSubURL
this.SCPDURL = options.SCPDURL
return this
} | javascript | {
"resource": ""
} | |
q27964 | Sonos | train | function Sonos (host, port, options) {
this.host = host
this.port = port || 1400
this.options = options || {}
if (!this.options.endpoints) this.options.endpoints = {}
if (!this.options.endpoints.transport) this.options.endpoints.transport = TRANSPORT_ENDPOINT
if (!this.options.endpoints.rendering) this.options.endpoints.rendering = RENDERING_ENDPOINT
if (!this.options.endpoints.device) this.options.endpoints.device = DEVICE_ENDPOINT
this.options.spotify = this.options.spotify || {}
this.options.spotify.region = this.options.spotify.region || SpotifyRegion.US
// Attach to newListener event
var self = this
var implicitListen = async function (event, listener) {
if (event === 'newListener') return
self.removeListener('newListener', implicitListen)
return Listener.subscribeTo(self).catch(err => {
debug('Error subscribing to listener %j', err)
})
}
this.on('newListener', implicitListen)
// Maybe stop the eventListener once last listener is removed?
} | javascript | {
"resource": ""
} |
q27965 | repeat | train | function repeat(string, times = 1) {
let result = "";
let round = times;
while (round--) {
result += string;
}
return result;
} | javascript | {
"resource": ""
} |
q27966 | toQueryStringWithOptions | train | function toQueryStringWithOptions(obj, opts) {
opts = opts || {};
if (isUndefined(opts.separator)) {
opts.separator = '_';
}
return toQueryString(obj, opts.deep, opts.transform, opts.prefix || '', opts.separator);
} | javascript | {
"resource": ""
} |
q27967 | fromQueryStringWithOptions | train | function fromQueryStringWithOptions(obj, opts) {
var str = String(obj || '').replace(/^.*?\?/, ''), result = {}, auto;
opts = opts || {};
if (str) {
forEach(str.split('&'), function(p) {
var split = p.split('=');
var key = decodeURIComponent(split[0]);
var val = split.length === 2 ? decodeURIComponent(split[1]) : '';
auto = opts.auto !== false;
parseQueryComponent(result, key, val, opts.deep, auto, opts.separator, opts.transform);
});
}
return result;
} | javascript | {
"resource": ""
} |
q27968 | iterateOverKeys | train | function iterateOverKeys(getFn, obj, fn, hidden) {
var keys = getFn(obj), desc;
for (var i = 0, key; key = keys[i]; i++) {
desc = getOwnPropertyDescriptor(obj, key);
if (desc.enumerable || hidden) {
fn(obj[key], key);
}
}
} | javascript | {
"resource": ""
} |
q27969 | collectArguments | train | function collectArguments() {
var args = arguments, i = args.length, arr = new Array(i);
while (i--) {
arr[i] = args[i];
}
return arr;
} | javascript | {
"resource": ""
} |
q27970 | getSplitModule | train | function getSplitModule(content, constraints) {
var src = '', lastIdx = 0, currentNamespace;
content.replace(/\/\*\*\* @namespace (\w+) \*\*\*\/\n|$/g, function(match, nextNamespace, idx) {
if (!currentNamespace || constraints[currentNamespace]) {
src += content.slice(lastIdx, idx);
}
currentNamespace = (nextNamespace || '').toLowerCase();
lastIdx = idx;
});
return src;
} | javascript | {
"resource": ""
} |
q27971 | addFixes | train | function addFixes() {
var match = fnPackage.name.match(/^build(\w+)Fix$/);
if (match) {
addSugarFix(match[1], fnPackage);
fnPackage.dependencies.push(fnCallName);
fnPackage.postAssigns = findVarAssignments(fnPackage.node.body.body, true);
}
} | javascript | {
"resource": ""
} |
q27972 | transposeDependencies | train | function transposeDependencies() {
sourcePackages.forEach(function(p) {
if (p.name === fnCallName) {
// Do not transpose the call package itself. After this loop
// there should be only one dependency on the build function anymore.
return;
}
var index = p.dependencies.indexOf(fnName);
if (index !== -1) {
p.dependencies.splice(index, 1, fnCallName);
}
});
} | javascript | {
"resource": ""
} |
q27973 | transposeVarDependencies | train | function transposeVarDependencies() {
var map = {};
sourcePackages.forEach(function(p) {
if (p.vars) {
p.vars.forEach(function(v) {
map[v] = p.name;
});
}
});
sourcePackages.forEach(function(p) {
var deps = [];
var varDeps = [];
p.dependencies.forEach(function(d) {
var normalized = map[d] || d;
if (deps.indexOf(normalized) === -1) {
deps.push(normalized);
}
if (d in map) {
varDeps.push(d);
}
});
p.dependencies = deps;
if (varDeps.length) {
p.varDependencies = varDeps;
}
});
} | javascript | {
"resource": ""
} |
q27974 | getDirectRequires | train | function getDirectRequires(p) {
return p.dependencies.filter(function(d) {
return DIRECT_REQUIRES_REG.test(d);
}).map(function(d) {
return "require('"+ getDependencyPath(d, p) +"');";
}).join('\n');
} | javascript | {
"resource": ""
} |
q27975 | bundleCircularDependencies | train | function bundleCircularDependencies() {
function findCircular(deps, chain) {
for (var i = 0, startIndex, c, p; i < deps.length; i++) {
// Only top level dependencies will be included in the chain.
p = sourcePackages.findByDependencyName(deps[i]);
if (!p) {
continue;
}
startIndex = chain.indexOf(p.name);
if (startIndex !== -1) {
return chain.slice(startIndex);
} else {
c = findCircular(p.dependencies, chain.concat(p.name));
if (c) {
return c;
}
}
}
}
function bundleCircular(chain) {
// Sort the chain so that all packages are
// bundled into the first found in the source.
chain = sortChain(chain);
var target = sourcePackages.findByDependencyName(chain[0]);
delete target.comments;
chain.slice(1).forEach(function(n) {
var src = sourcePackages.findByDependencyName(n);
target.body += '\n\n' + src.body;
target.bodyWithComments += '\n\n' + src.bodyWithComments;
bundleArray(target, src, 'dependencies', true);
bundleArray(target, src, 'varDependencies', true);
bundleArray(target, src, 'vars');
bundleMap(target, src, 'assigns');
updateExternalDependencies(src.name, target.name);
if (src.type === 'build' && (!target.vars || !target.vars.length)) {
// A build function that is having it's call block being bundled
// into it can also take on the type "build". This generally means
// that it has no exports. However don't do this if the function is
// building up variables, in which case it will have a "vars".
target.type = 'build';
}
removePackage(src);
});
}
function sortChain(chain) {
return chain.sort(function(a, b) {
return getPackageIndexByName(a) - getPackageIndexByName(b);
});
}
function getPackageIndexByName(name) {
return sourcePackages.findIndex(function(p) {
return p.name === name;
});
}
// Bundle all dependencies from the source into the target,
// but only after removing the circular dependency itself.
function bundleArray(target, src, name, notSelf) {
var srcValues, targetValues;
if (src[name]) {
srcValues = src[name] || [];
targetValues = target[name] || [];
target[name] = uniq(targetValues.concat(srcValues.filter(function(d) {
return !notSelf || d !== target.name;
})));
}
}
function bundleMap(target, src, name) {
if (src[name]) {
target[name] = target[name] || {};
merge(target[name], src[name]);
}
}
// Update all packages pointing to the old package.
function updateExternalDependencies(oldName, newName) {
sourcePackages.forEach(function(p) {
var index = p.dependencies.indexOf(oldName);
if (index !== -1) {
if (p.name === newName || p.dependencies.indexOf(newName) !== -1) {
// If the package has the same name as the one we are trying to
// update to, then we are trying to update the package to point
// to itself as a dependency, which isn't possible so just remove
// the old dependency. Alternatively, if the package already has
// the new name, then we can simply remove the old one and move on.
p.dependencies.splice(index, 1);
} else {
// If the package is NOT trying to update to itself and does NOT
// have the new dependency already, then add it in place of the
// old one.
p.dependencies.splice(index, 1, newName);
}
}
});
}
function removePackage(p) {
var index = sourcePackages.indexOf(p);
sourcePackages.splice(index, 1);
}
sourcePackages.forEach(function(p) {
var chain = findCircular(p.dependencies, []);
if (chain) {
bundleCircular(chain);
}
});
} | javascript | {
"resource": ""
} |
q27976 | bundleArray | train | function bundleArray(target, src, name, notSelf) {
var srcValues, targetValues;
if (src[name]) {
srcValues = src[name] || [];
targetValues = target[name] || [];
target[name] = uniq(targetValues.concat(srcValues.filter(function(d) {
return !notSelf || d !== target.name;
})));
}
} | javascript | {
"resource": ""
} |
q27977 | updateExternalDependencies | train | function updateExternalDependencies(oldName, newName) {
sourcePackages.forEach(function(p) {
var index = p.dependencies.indexOf(oldName);
if (index !== -1) {
if (p.name === newName || p.dependencies.indexOf(newName) !== -1) {
// If the package has the same name as the one we are trying to
// update to, then we are trying to update the package to point
// to itself as a dependency, which isn't possible so just remove
// the old dependency. Alternatively, if the package already has
// the new name, then we can simply remove the old one and move on.
p.dependencies.splice(index, 1);
} else {
// If the package is NOT trying to update to itself and does NOT
// have the new dependency already, then add it in place of the
// old one.
p.dependencies.splice(index, 1, newName);
}
}
});
} | javascript | {
"resource": ""
} |
q27978 | unpackMethodSets | train | function unpackMethodSets(methods) {
var result = [];
methods.forEach(function(method) {
if (method.set) {
method.set.forEach(function(name) {
var setMethod = clone(method);
setMethod.name = name;
result.push(setMethod);
});
} else {
result.push(method);
}
});
return result;
} | javascript | {
"resource": ""
} |
q27979 | getAlternateTypes | train | function getAlternateTypes(method) {
var types = [];
function process(arr) {
if (arr) {
arr.forEach(function(obj) {
if (obj.type) {
var split = obj.type.split('|');
if (split.length > 1) {
types = types.concat(split);
}
}
});
}
}
process(method.params);
process(method.options);
return types;
} | javascript | {
"resource": ""
} |
q27980 | callDateSetWithWeek | train | function callDateSetWithWeek(d, method, value, safe) {
if (method === 'ISOWeek') {
setISOWeekNumber(d, value);
} else {
callDateSet(d, method, value, safe);
}
} | javascript | {
"resource": ""
} |
q27981 | iterateOverDateUnits | train | function iterateOverDateUnits(fn, startIndex, endIndex) {
endIndex = endIndex || 0;
if (isUndefined(startIndex)) {
startIndex = YEAR_INDEX;
}
for (var index = startIndex; index >= endIndex; index--) {
if (fn(DateUnits[index], index) === false) {
break;
}
}
} | javascript | {
"resource": ""
} |
q27982 | iterateOverDateParams | train | function iterateOverDateParams(params, fn, startIndex, endIndex) {
function run(name, unit, i) {
var val = getDateParam(params, name);
if (isDefined(val)) {
fn(name, val, unit, i);
}
}
iterateOverDateUnits(function (unit, i) {
var result = run(unit.name, unit, i);
if (result !== false && i === DAY_INDEX) {
// Check for "weekday", which has a distinct meaning
// in the context of setting a date, but has the same
// meaning as "day" as a unit of time.
result = run('weekday', unit, i);
}
return result;
}, startIndex, endIndex);
} | javascript | {
"resource": ""
} |
q27983 | setISOWeekNumber | train | function setISOWeekNumber(d, num) {
if (isNumber(num)) {
// Intentionally avoiding updateDate here to prevent circular dependencies.
var isoWeek = cloneDate(d), dow = getWeekday(d);
moveToFirstDayOfWeekYear(isoWeek, ISO_FIRST_DAY_OF_WEEK, ISO_FIRST_DAY_OF_WEEK_YEAR);
setDate(isoWeek, getDate(isoWeek) + 7 * (num - 1));
setYear(d, getYear(isoWeek));
setMonth(d, getMonth(isoWeek));
setDate(d, getDate(isoWeek));
setWeekday(d, dow || 7);
}
return d.getTime();
} | javascript | {
"resource": ""
} |
q27984 | getWeekYear | train | function getWeekYear(d, localeCode, iso) {
var year, month, firstDayOfWeek, firstDayOfWeekYear, week, loc;
year = getYear(d);
month = getMonth(d);
if (month === 0 || month === 11) {
if (!iso) {
loc = localeManager.get(localeCode);
firstDayOfWeek = loc.getFirstDayOfWeek(localeCode);
firstDayOfWeekYear = loc.getFirstDayOfWeekYear(localeCode);
}
week = getWeekNumber(d, false, firstDayOfWeek, firstDayOfWeekYear);
if (month === 0 && week === 0) {
year -= 1;
} else if (month === 11 && week === 1) {
year += 1;
}
}
return year;
} | javascript | {
"resource": ""
} |
q27985 | getAdjustedUnit | train | function getAdjustedUnit(ms, fn) {
var unitIndex = 0, value = 0;
iterateOverDateUnits(function(unit, i) {
value = abs(fn(unit));
if (value >= 1) {
unitIndex = i;
return false;
}
});
return [value, unitIndex, ms];
} | javascript | {
"resource": ""
} |
q27986 | getAdjustedUnitForNumber | train | function getAdjustedUnitForNumber(ms) {
return getAdjustedUnit(ms, function(unit) {
return trunc(withPrecision(ms / unit.multiplier, 1));
});
} | javascript | {
"resource": ""
} |
q27987 | cloneDateByFlag | train | function cloneDateByFlag(d, clone) {
if (_utc(d) && !isDefined(optFromUTC)) {
optFromUTC = true;
}
if (_utc(d) && !isDefined(optSetUTC)) {
optSetUTC = true;
}
if (clone) {
d = new Date(d.getTime());
}
return d;
} | javascript | {
"resource": ""
} |
q27988 | arraySafeConcat | train | function arraySafeConcat(arr, arg) {
var result = arrayClone(arr), len = result.length, arr2;
arr2 = isArray(arg) ? arg : [arg];
result.length += arr2.length;
forEach(arr2, function(el, i) {
result[len + i] = el;
});
return result;
} | javascript | {
"resource": ""
} |
q27989 | runGlobalMatch | train | function runGlobalMatch(str, reg) {
var result = [], match, lastLastIndex;
while ((match = reg.exec(str)) != null) {
if (reg.lastIndex === lastLastIndex) {
reg.lastIndex += 1;
} else {
result.push(match[0]);
}
lastLastIndex = reg.lastIndex;
}
return result;
} | javascript | {
"resource": ""
} |
q27990 | sliceArrayFromRight | train | function sliceArrayFromRight(arr, startIndex, loop) {
if (!loop) {
startIndex += 1;
arr = arr.slice(0, max(0, startIndex));
}
return arr;
} | javascript | {
"resource": ""
} |
q27991 | defineOnPrototype | train | function defineOnPrototype(ctor, methods) {
var proto = ctor.prototype;
forEachProperty(methods, function(val, key) {
proto[key] = val;
});
} | javascript | {
"resource": ""
} |
q27992 | coercePositiveInteger | train | function coercePositiveInteger(n) {
n = +n || 0;
if (n < 0 || !isNumber(n) || !isFinite(n)) {
throw new RangeError('Invalid number');
}
return trunc(n);
} | javascript | {
"resource": ""
} |
q27993 | getMatcher | train | function getMatcher(f) {
if (!isPrimitive(f)) {
var className = classToString(f);
if (isRegExp(f, className)) {
return regexMatcher(f);
} else if (isDate(f, className)) {
return dateMatcher(f);
} else if (isFunction(f, className)) {
return functionMatcher(f);
} else if (isPlainObject(f, className)) {
return fuzzyMatcher(f);
}
}
// Default is standard isEqual
return defaultMatcher(f);
} | javascript | {
"resource": ""
} |
q27994 | handleArrayIndexRange | train | function handleArrayIndexRange(obj, key, any, val) {
var match, start, end, leading, trailing, arr, set;
match = key.match(PROPERTY_RANGE_REG);
if (!match) {
return;
}
set = isDefined(val);
leading = match[1];
if (leading) {
arr = handleDeepProperty(obj, leading, any, false, set ? true : false, true);
} else {
arr = obj;
}
assertArray(arr);
trailing = match[4];
start = match[2] ? +match[2] : 0;
end = match[3] ? +match[3] : arr.length;
// A range of 0..1 is inclusive, so we need to add 1 to the end. If this
// pushes the index from -1 to 0, then set it to the full length of the
// array, otherwise it will return nothing.
end = end === -1 ? arr.length : end + 1;
if (set) {
for (var i = start; i < end; i++) {
handleDeepProperty(arr, i + trailing, any, false, true, false, val);
}
} else {
arr = arr.slice(start, end);
// If there are trailing properties, then they need to be mapped for each
// element in the array.
if (trailing) {
if (trailing.charAt(0) === HALF_WIDTH_PERIOD) {
// Need to chomp the period if one is trailing after the range. We
// can't do this at the regex level because it will be required if
// we're setting the value as it needs to be concatentated together
// with the array index to be set.
trailing = trailing.slice(1);
}
return map(arr, function(el) {
return handleDeepProperty(el, trailing);
});
}
}
return arr;
} | javascript | {
"resource": ""
} |
q27995 | coercePrimitiveToObject | train | function coercePrimitiveToObject(obj) {
if (isPrimitive(obj)) {
obj = Object(obj);
}
// istanbul ignore next
if (NO_KEYS_IN_STRING_OBJECTS && isString(obj)) {
forceStringCoercion(obj);
}
return obj;
} | javascript | {
"resource": ""
} |
q27996 | forceStringCoercion | train | function forceStringCoercion(obj) {
var i = 0, chr;
while (chr = obj.charAt(i)) {
obj[i++] = chr;
}
} | javascript | {
"resource": ""
} |
q27997 | isEqual | train | function isEqual(a, b, stack) {
var aClass, bClass;
if (a === b) {
// Return quickly up front when matched by reference,
// but be careful about 0 !== -0.
return a !== 0 || 1 / a === 1 / b;
}
aClass = classToString(a);
bClass = classToString(b);
if (aClass !== bClass) {
return false;
}
if (isSerializable(a, aClass) && isSerializable(b, bClass)) {
return objectIsEqual(a, b, aClass, stack);
} else if (isSet(a, aClass) && isSet(b, bClass)) {
return a.size === b.size && isEqual(setToArray(a), setToArray(b), stack);
} else if (isMap(a, aClass) && isMap(b, bClass)) {
return a.size === b.size && isEqual(mapToArray(a), mapToArray(b), stack);
} else if (isError(a, aClass) && isError(b, bClass)) {
return a.toString() === b.toString();
}
return false;
} | javascript | {
"resource": ""
} |
q27998 | serializeInternal | train | function serializeInternal(obj, refs, stack) {
var type = typeof obj, sign = '', className, value, ref;
// Return up front on
if (1 / obj === -Infinity) {
sign = '-';
}
// Return quickly for primitives to save cycles
if (isPrimitive(obj, type) && !isRealNaN(obj)) {
return type + sign + obj;
}
className = classToString(obj);
if (!isSerializable(obj, className)) {
ref = indexOf(refs, obj);
if (ref === -1) {
ref = refs.length;
refs.push(obj);
}
return ref;
} else if (isObjectType(obj)) {
value = serializeDeep(obj, refs, stack) + obj.toString();
} else if (obj.valueOf) {
value = obj.valueOf();
}
return type + className + sign + value;
} | javascript | {
"resource": ""
} |
q27999 | stringToNumber | train | function stringToNumber(str, base) {
var sanitized, isDecimal;
sanitized = str.replace(fullWidthNumberReg, function(chr) {
var replacement = getOwn(fullWidthNumberMap, chr);
if (replacement === HALF_WIDTH_PERIOD) {
isDecimal = true;
}
return replacement;
});
return isDecimal ? parseFloat(sanitized) : parseInt(sanitized, base || 10);
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.