_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q49800
setHeadersFromArray
train
function setHeadersFromArray (res, headers) { for (var i = 0; i < headers.length; i++) { res.setHeader(headers[i][0], headers[i][1]) } }
javascript
{ "resource": "" }
q49801
setHeadersFromObject
train
function setHeadersFromObject (res, headers) { var keys = Object.keys(headers) for (var i = 0; i < keys.length; i++) { var k = keys[i] if (k) res.setHeader(k, headers[k]) } }
javascript
{ "resource": "" }
q49802
setWriteHeadHeaders
train
function setWriteHeadHeaders (statusCode) { var length = arguments.length var headerIndex = length > 1 && typeof arguments[1] === 'string' ? 2 : 1 var headers = length >= headerIndex + 1 ? arguments[headerIndex] : undefined this.statusCode = statusCode if (Array.isArray(headers)) { // handle array case setHeadersFromArray(this, headers) } else if (headers) { // handle object case setHeadersFromObject(this, headers) } // copy leading arguments var args = new Array(Math.min(length, headerIndex)) for (var i = 0; i < args.length; i++) { args[i] = arguments[i] } return args }
javascript
{ "resource": "" }
q49803
_getVideo
train
function _getVideo(element) { var videoElement = null; if (element.tagName === 'VIDEO') { videoElement = element; } else { var videos = element.getElementsByTagName('video'); if (videos[0]) { videoElement = videos[0]; } } return videoElement; }
javascript
{ "resource": "" }
q49804
videoEnterFullscreen
train
function videoEnterFullscreen(element) { var videoElement = _getVideo(element); if (videoElement && videoElement.webkitEnterFullscreen) { try { if (videoElement.readyState < videoElement.HAVE_METADATA) { videoElement.addEventListener('loadedmetadata', function onMetadataLoaded() { videoElement.removeEventListener('loadedmetadata', onMetadataLoaded, false); videoElement.webkitEnterFullscreen(); hasControls = !!videoElement.getAttribute('controls'); }, false); videoElement.load(); } else { videoElement.webkitEnterFullscreen(); hasControls = !!videoElement.getAttribute('controls'); } lastVideoElement = videoElement; } catch (err) { return callOnError('not_supported', element); } return true; } return callOnError(fn.request === undefined ? 'not_supported' : 'not_enabled', element); }
javascript
{ "resource": "" }
q49805
train
function(reason, element) { if (elements.length > 0) { var obj = elements.pop(); element = element || obj.element; obj.error.call(element, reason); bigscreen.onerror(element, reason); } }
javascript
{ "resource": "" }
q49806
gcd
train
function gcd(a, b) { var t; while (b) { t = a; a = b; b = t % b; } return Math.abs(a); }
javascript
{ "resource": "" }
q49807
train
function(a, b) { // gcd = a * s + b * t var s = 0, t = 1, u = 1, v = 0; while (a !== 0) { var q = b / a | 0, r = b % a; var m = s - u * q, n = t - v * q; b = a; a = r; s = u; t = v; u = m; v = n; } return [b /* gcd*/, s, t]; }
javascript
{ "resource": "" }
q49808
keyUnion
train
function keyUnion(a, b) { var k = {}; for (var i in a) { k[i] = 1; } for (var i in b) { k[i] = 1; } return k; }
javascript
{ "resource": "" }
q49809
degree
train
function degree(x) { var i = Number.NEGATIVE_INFINITY; for (var k in x) { if (!FIELD['empty'](x[k])) i = Math.max(k, i); } return i; }
javascript
{ "resource": "" }
q49810
train
function(x, y) { var r = {}; var i = degree(x); var j = degree(y); var trace = []; while (i >= j) { var tmp = r[i - j] = FIELD['div'](x[i] || 0, y[j] || 0); for (var k in y) { x[+k + i - j] = FIELD['sub'](x[+k + i - j] || 0, FIELD['mul'](y[k] || 0, tmp)); } if (Polynomial['trace'] !== null) { var tr = {}; for (var k in y) { tr[+k + i - j] = FIELD['mul'](y[k] || 0, tmp); } trace.push(new Polynomial(tr)); } i = degree(x); } // Add rest if (Polynomial['trace'] !== null) { trace.push(new Polynomial(x)); Polynomial['trace'] = trace; } return r; }
javascript
{ "resource": "" }
q49811
train
function(x) { var ret = {}; if (x === null || x === undefined) { x = 0; } switch (typeof x) { case "object": if (x['coeff']) { x = x['coeff']; } if (Fraction && x instanceof Fraction || Complex && x instanceof Complex || Quaternion && x instanceof Quaternion) { ret[0] = x; } else // Handles Arrays the same way for (var i in x) { if (!FIELD['empty'](x[i])) { ret[i] = FIELD['parse'](x[i]); } } return ret; case "number": return {'0': FIELD['parse'](x)}; case "string": var tmp; while (null !== (tmp = STR_REGEXP['exec'](x))) { var num = 1; var exp = 1; if (tmp[4] !== undefined) { num = tmp[4]; exp = 0; } else if (tmp[2] !== undefined) { num = tmp[2]; } num = parseExp(tmp[1], num); // Parse exponent if (tmp[3] !== undefined) { exp = parseInt(tmp[3], 10); } if (ret[exp] === undefined) { ret[exp] = num; } else { ret[exp] = FIELD['add'](ret[exp], num); } } return ret; } throw "Invalid Param"; }
javascript
{ "resource": "" }
q49812
train
function(fn) { /** * The actual to string function * * @returns {string|null} */ var Str = function() { var poly = this['coeff']; var keys = []; for (var i in poly) { keys.push(+i); } if (keys.length === 0) return "0"; keys.sort(function(a, b) { return a - b; }); var str = ""; for (var k = keys.length; k--; ) { var i = keys[k]; var cur = poly[i]; var val = cur; if (val === null || val === undefined) continue; if (Complex && val instanceof Complex) { // Add real part if (val['re'] !== 0) { if (str !== "" && val['re'] > 0) { str += "+"; } if (val['re'] === -1 && i !== 0) { str += "-"; } else if (val['re'] !== 1 || i === 0) { str += val['re']; } // Add exponent if necessary, no DRY, let's feed gzip if (i === 1) str += "x"; else if (i !== 0) str += "x^" + i; } // Add imaginary part if (val['im'] !== 0) { if (str !== "" && val['im'] > 0) { str += "+"; } if (val['im'] === -1) { str += "-"; } else if (val['im'] !== 1) { str += val['im']; } str += "i"; // Add exponent if necessary, no DRY, let's feed gzip if (i === 1) str += "x"; else if (i !== 0) str += "x^" + i; } } else { val = val.valueOf(); // Skip if it's zero if (val === 0) continue; // Separate by + if (str !== "" && val > 0) { str += "+"; } if (val === -1 && i !== 0) str += "-"; else // Add number if it's not a "1" or the first position if (val !== 1 || i === 0) str += cur[fn] ? cur[fn]() : cur['toString'](); // Add exponent if necessary, no DRY, let's feed gzip if (i === 1) str += "x"; else if (i !== 0) str += "x^" + i; } } if (str === "") return cur[fn] ? cur[fn]() : cur['toString'](); return str; }; return Str; }
javascript
{ "resource": "" }
q49813
factor
train
function factor(P) { var xn = 1; var F = Polynomial(P); // f(x) var f = F['derive'](); // f'(x) var res = []; do { var prev, xn = Polynomial(1).coeff[0]; var k = 0; do { prev = xn; //xn = FIELD['sub'](xn, FIELD.div(F.result(xn), f.result(xn))); xn = xn.sub(F.result(xn).div(f.result(xn))); } while (k++ === 0 || Math.abs(xn.valueOf() - prev.valueOf()) > 1e-8); var p = Polynomial("x").sub(xn); // x-x0 F = F.div(p); f = F.derive(); res.push(xn); } while (f.degree() >= 0); return res; }
javascript
{ "resource": "" }
q49814
serveapp
train
function serveapp (directory) { /* istanbul ignore next */ return async function serveEmberAPP (ctx, next) { await next(); if (!ctx.body) { await ctx.render(directory); } }; }
javascript
{ "resource": "" }
q49815
EvalRoute
train
function EvalRoute (ctx, next) { let router = this; let matched = router.match(router.opts.routerPath || ctx.routerPath || ctx.path, ctx.method); /* istanbul ignore else */ if (ctx.matched) { ctx.matched.push.apply(ctx.matched, matched.path); } else { ctx.matched = matched.path; } if (matched.route) { return this.middleware()(ctx, next); } else { return Promise.resolve('koaton-no-route'); } }
javascript
{ "resource": "" }
q49816
handle
train
function handle (fn) { return function (...args) { return new Promise((resolve) => { fn.bind(this)(...args, function (err, result) { /* istanbul ignore if */ if (err) { debug(err); } else { resolve(result); } }); }); }; }
javascript
{ "resource": "" }
q49817
DeepDevOrProd
train
function DeepDevOrProd (object, prop) { let target = object[prop]; if (Object.keys(target).indexOf('dev') === -1 && typeof target === 'object') { for (const deep of Object.keys(target)) { DeepDevOrProd(object[prop], deep); } } else { if (Object.keys(target).indexOf('dev') === -1) { object[prop] = target; } else { object[prop] = isDev ? target.dev : /* istanbul ignore next */ target.prod; } } }
javascript
{ "resource": "" }
q49818
handlebars
train
function handlebars () { const Handlebars = require(ProyPath('node_modules', 'handlebars')); const layouts = require(ProyPath('node_modules', 'handlebars-layouts')); Handlebars.registerHelper(layouts(Handlebars)); Handlebars.registerHelper('link', function (url, helper) { return makeLink(helper.data.root, url, helper.fn); }); // Bundles Handlebars.registerHelper('bundle', function (bundle) { if (Kmetadata.bundles[bundle] === undefined) { return ''; } return Kmetadata.bundles[bundle].toString(); }); // Localition Handlebars.registerHelper('i18n', _i18n); Handlebars.registerHelper('t', translate); const layoutFiles = glob(ProyPath('views', 'layouts', '*.handlebars')).concat(glob(ProyPath('koaton_modules', '**', 'views', 'layouts', '*.handlebars'))); for (const file of layoutFiles) { Handlebars.registerPartial(basename(file).replace('.handlebars', ''), fs.readFileSync(file, 'utf8')); } return Handlebars; }
javascript
{ "resource": "" }
q49819
findmodel
train
async function findmodel (ctx, next) { let pmodel = ctx.request.url.split('?')[0].split('/')[1]; ctx.model = ctx.db[pmodel]; ctx.state.model = ctx.state.db[pmodel]; await next(); }
javascript
{ "resource": "" }
q49820
protect
train
async function protect (ctx, next) { if (ctx.isAuthenticated()) { await next(); } else { await passport.authenticate('bearer', { session: false }, async function (err, user) { // console.log(err, user); /* istanbul ignore if */ if (err) { throw err; } if (user === false) { ctx.body = null; ctx.status = 401; } else { ctx.state.user = user; await next(); } })(ctx); } }
javascript
{ "resource": "" }
q49821
makerelation
train
function makerelation (model, relation) { let options = { as: relation.As, foreignKey: relation.key }; let target = exp.databases[inflector.pluralize(relation.Children)]; if (relation.Rel !== 'manyToMany') { exp.databases[model][relation.Rel](target, options); } else { exp.databases[model].prototype.many2many = exp.databases[model].prototype.many2many || {}; exp.databases[model].prototype.many2many[relation.Parent] = function (id, id2) { if (id && id2) { return exp.databases[relation.Children].findcre({ [`${model}ID`]: id, [`${relation.Parent}ID`]: id2 }); } return exp.databases[relation.Children].find({ where: { [`${model}ID`]: id } }).then(records => { let all = []; for (const record of records) { all.push(exp.databases[relation.Parent].findById(record[`${relation.Parent}ID`])); } return Promise.all(all); }); }; } }
javascript
{ "resource": "" }
q49822
createUser
train
async function createUser (username, password, /* istanbul ignore next */ body = {}) { const user = await getUser(username, password); body[configuration.security.username] = username; body[configuration.security.password] = await hash(password, 5); if (user === null) { return AuthModel.create(body); } else { return Promise.resolve({ error: 'User Already Extis' }); } }
javascript
{ "resource": "" }
q49823
deepRegister
train
function deepRegister(r) { r.keys().forEach(key => { const component = r(key) registry.register(component.default, component.registryName) }) }
javascript
{ "resource": "" }
q49824
repeat
train
function repeat (string, width) { var result = '' var n = width do { if (n % 2) { result += string } n = Math.floor(n / 2) /* eslint no-self-assign: 0 */ string += string } while (n && stringWidth(result) < width) return wideTruncate(result, width) }
javascript
{ "resource": "" }
q49825
compile
train
function compile(inFile, outFile, sourceMap, cb) { console.log('Compiling ' + inFile + ' to ' + outFile); var outStream = fs.createWriteStream(outFile, 'utf8'); outStream.on('close', cb); browserify({debug: true}) .require(inFile, { entry: true }) .bundle() .pipe(exorcist(sourceMap)) .pipe(outStream); }
javascript
{ "resource": "" }
q49826
Hebcal
train
function Hebcal(year, month) { var me = this; // whenever this is done, it is for optimizations. if (!year) { year = (new HDate())[getFullYear](); // this year; } if (typeof year !== 'number') { throw new TE('year to Hebcal() is not a number'); } me.year = year; if (month) { if (typeof month == 'string') { month = c.monthFromName(month); } if (typeof month == 'number') { month = [month]; } if (Array.isArray(month)) { me.months = month[map](function(i){ var m = new Month(i, year); defProp(m, '__year', { configurable: true, writable: true, value: me }); return m; }); me.holidays = holidays.year(year); } else { throw new TE('month to Hebcal is not a valid type'); } } else { return new Hebcal(year, c.range(1, c.MONTH_CNT(year))); } me[length] = c.daysInYear(year); defProp(me, 'il', getset(function() { return me[getMonth](1).il; }, function(il) { me.months.forEach(function(m){ m.il = il; }); })); defProp(me, 'lat', getset(function() { return me[getMonth](1).lat; }, function(lat) { me.months.forEach(function(m){ m.lat = lat; }); })); defProp(me, 'long', getset(function() { return me[getMonth](1).long; }, function(lon) { me.months.forEach(function(m){ m.long = lon; }); })); }
javascript
{ "resource": "" }
q49827
abs
train
function abs(year, absDate) { // find the first saturday on or after today's date absDate = c.dayOnOrBefore(6, absDate + 6); var weekNum = (absDate - year.first_saturday) / 7; var index = year.theSedraArray[weekNum]; if (undefined === index) { return abs(new Sedra(year.year + 1, year.il), absDate); // must be next year } if (typeof index == 'object') { // Shabbat has a chag. Return a description return {parsha: [index], chag: true}; } if (index >= 0) { return {parsha: [parshiot[index]], chag: false}; } index = D(index); // undouble the parsha return {parsha: [parshiot[index], parshiot[index + 1]], chag: false}; }
javascript
{ "resource": "" }
q49828
train
function(stack, done, opts) { var lines; var line; var mapForUri = {}; var rows = {}; var fields; var uri; var expected_fields; var regex; var skip_lines; var fetcher = new Fetcher(opts); if (isChromeOrEdge() || isIE11Plus()) { regex = /^ +at.+\((.*):([0-9]+):([0-9]+)/; expected_fields = 4; // (skip first line containing exception message) skip_lines = 1; } else if (isFirefox() || isSafari()) { regex = /@(.*):([0-9]+):([0-9]+)/; expected_fields = 4; skip_lines = 0; } else { throw new Error("unknown browser :("); } lines = stack.split("\n").slice(skip_lines); for (var i=0; i < lines.length; i++) { line = lines[i]; if ( opts && opts.filter && !opts.filter(line) ) continue; fields = line.match(regex); if (fields && fields.length === expected_fields) { rows[i] = fields; uri = fields[1]; if (!uri.match(/<anonymous>/)) { fetcher.fetchScript(uri); } } } fetcher.sem.whenReady(function() { var result = processSourceMaps(lines, rows, fetcher.mapForUri); done(result); }); }
javascript
{ "resource": "" }
q49829
handleResponse
train
function handleResponse(conn, cb, opts) { opts = opts || {}; return function(err, result) { pool.release(conn); if (err) { return cb && cb(err); } if (opts.parse) { if (result && opts.compress) { return zlib.gunzip(result, opts.compress.params || {}, function (gzErr, gzResult) { if (gzErr) { return cb && cb(gzErr); } try { gzResult = JSON.parse(gzResult); } catch (e) { return cb && cb(e); } return cb && cb(null, gzResult); }); } try { result = JSON.parse(result); } catch (e) { return cb && cb(e); } } return cb && cb(null, result); }; }
javascript
{ "resource": "" }
q49830
getFromUrl
train
function getFromUrl(args) { if (!args || typeof args.url !== 'string') { return args; } try { var options = redisUrl.parse(args.url); // make a clone so we don't change input args return applyOptionsToArgs(args, options); } catch (e) { //url is unparsable so returning original return args; } }
javascript
{ "resource": "" }
q49831
cloneArgs
train
function cloneArgs(args) { var newArgs = {}; for(var key in args){ if (key && args.hasOwnProperty(key)) { newArgs[key] = args[key]; } } newArgs.isCacheableValue = args.isCacheableValue && args.isCacheableValue.bind(newArgs); return newArgs; }
javascript
{ "resource": "" }
q49832
applyOptionsToArgs
train
function applyOptionsToArgs(args, options) { var newArgs = cloneArgs(args); newArgs.host = options.hostname; newArgs.port = parseInt(options.port, 10); newArgs.db = parseInt(options.database, 10); newArgs.auth_pass = options.password; newArgs.password = options.password; if(options.query && options.query.ttl){ newArgs.ttl = parseInt(options.query.ttl, 10); } return newArgs; }
javascript
{ "resource": "" }
q49833
persist
train
function persist(pErr, pVal) { if (pErr) { return cb(pErr); } if (ttl) { conn.setex(key, ttl, pVal, handleResponse(conn, cb)); } else { conn.set(key, pVal, handleResponse(conn, cb)); } }
javascript
{ "resource": "" }
q49834
copyScript
train
function copyScript (script) { fs.copySync(path.join(__dirname, script), path.join(appScriptsPath, script)) }
javascript
{ "resource": "" }
q49835
decode
train
function decode(s) { if (s) { s = s.toString().replace(re.pluses, '%20'); s = decodeURIComponent(s); } return s; }
javascript
{ "resource": "" }
q49836
parseUri
train
function parseUri(str) { var parser = re.uri_parser; var parserKeys = ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "isColonUri", "relative", "path", "directory", "file", "query", "anchor"]; var m = parser.exec(str || ''); var parts = {}; parserKeys.forEach(function(key, i) { parts[key] = m[i] || ''; }); return parts; }
javascript
{ "resource": "" }
q49837
Uri
train
function Uri(str) { this.uriParts = parseUri(str); this.queryPairs = parseQuery(this.uriParts.query); this.hasAuthorityPrefixUserPref = null; }
javascript
{ "resource": "" }
q49838
LokiStore
train
function LokiStore (options) { if (!(this instanceof LokiStore)) { throw new TypeError('Cannot call LokiStore constructor as a function') } let self = this // Parse options options = options || {} Store.call(this, options) this.autosave = options.autosave !== false this.storePath = options.path || './session-store.db' this.ttl = options.ttl || 1209600 if (this.ttl === 0) { this.ttl = null } // Initialize Loki.js this.client = new Loki(this.storePath, { env: 'NODEJS', autosave: self.autosave, autosaveInterval: 5000 }) // Setup error logging if (options.logErrors) { if (typeof options.logErrors !== 'function') { options.logErrors = function (err) { console.error('Warning: connect-loki reported a client error: ' + err) } } this.logger = options.logErrors } else { this.logger = _.noop } // Get / Create collection this.client.loadDatabase({}, () => { self.collection = self.client.getCollection('Sessions') if (_.isNil(self.collection)) { self.collection = self.client.addCollection('Sessions', { indices: ['sid'], ttlInterval: self.ttl }) } self.collection.on('error', (err) => { return self.logger(err) }) self.emit('connect') }) }
javascript
{ "resource": "" }
q49839
train
function(data) { // parse basic info from the dom item var item = { link: data.id, text: data.textContent || data.innerText, parent: '' }; // build type identifier var level = data.tagName; for (var i = 0; i < data.classList.length; i++) { level += ',' + data.classList[i]; } // here be dragons var stacksize = stack.length; if (stacksize === 0) { // we are at the top level and will stay there stack.push(level); } else if (level !== stack[stacksize - 1]) { // traverse the ancestry, looking for a match for (var j = stacksize - 1; j >= 0; j--) { if (level == stack[j]) { break; // found an ancestor } } if (j < 0) { // this is a new submenu item, lets push the stack stack.push(level); item.push = true; parentstack.push(lastitem); } else { // we are either a sibling or higher up the tree, // lets pop the stack if needed item.pop = stacksize - 1 - j; while (stack.length > j + 1) { stack.pop(); parentstack.pop(); } } } // if we have a parent, lets record it if(parentstack.length > 0) { item.parent= parentstack[parentstack.length-1]; } // for next iteration lastitem= item.link; return item; }
javascript
{ "resource": "" }
q49840
train
function (translationId) { var deferred = $q.defer(); var regardless = function (value) { results[translationId] = value; deferred.resolve([translationId, value]); }; // we don't care whether the promise was resolved or rejected; just store the values $translate(translationId, interpolateParams, interpolationId, defaultTranslationText).then(regardless, regardless); return deferred.promise; }
javascript
{ "resource": "" }
q49841
isFlippable
train
function isFlippable(node, prevNode) { if (node.type == 'comment') { return false; } if (prevNode && prevNode.type == 'comment') { return !RE_NOFLIP.test(prevNode.comment); } return true; }
javascript
{ "resource": "" }
q49842
isReplaceable
train
function isReplaceable(node, prevNode) { if (node.type == 'comment') { return false; } if (prevNode && prevNode.type == 'comment') { return RE_REPLACE.test(prevNode.comment); } return false; }
javascript
{ "resource": "" }
q49843
flip
train
function flip(str, options) { if (typeof str != 'string') { throw new Error('input is not a String.'); } var node = css.parse(str, options); flipNode(node.stylesheet); return css.stringify(node, options); }
javascript
{ "resource": "" }
q49844
transition
train
function transition(value) { var RE_PROP = /^\s*([a-zA-z\-]+)/; var parts = value.split(/\s*,\s*/); return parts.map(function (part) { // extract the property if the value is for the `transition` shorthand if (RE_PROP.test(part)) { var prop = part.match(RE_PROP)[1]; var newProp = flipProperty(prop); part = part.replace(RE_PROP, newProp); } return part; }).join(', '); }
javascript
{ "resource": "" }
q49845
flipProperty
train
function flipProperty(prop) { var normalizedProperty = prop.toLowerCase(); return PROPERTIES.hasOwnProperty(normalizedProperty) ? PROPERTIES[normalizedProperty] : prop; }
javascript
{ "resource": "" }
q49846
flipCorners
train
function flipCorners(value) { var elements = value.split(/\s+/); if (!elements) { return value; } switch (elements.length) { // 5px 10px 15px 20px => 10px 5px 20px 15px case 4: return [elements[1], elements[0], elements[3], elements[2]].join(' '); // 5px 10px 20px => 10px 5px 10px 20px case 3: return [elements[1], elements[0], elements[1], elements[2]].join(' '); // 5px 10px => 10px 5px case 2: return [elements[1], elements[0]].join(' '); } return value; }
javascript
{ "resource": "" }
q49847
flipValueOf
train
function flipValueOf(prop, value) { var RE_IMPORTANT = /\s*!important/; var RE_PREFIX = /^-[a-zA-Z]+-/; // find normalized property name (removing any vendor prefixes) var normalizedProperty = prop.toLowerCase().trim(); normalizedProperty = (RE_PREFIX.test(normalizedProperty) ? normalizedProperty.split(RE_PREFIX)[1] : normalizedProperty); var flipFn = VALUES.hasOwnProperty(normalizedProperty) ? VALUES[normalizedProperty] : false; if (!flipFn) { return value; } var important = value.match(RE_IMPORTANT); var newValue = flipFn(value.replace(RE_IMPORTANT, '').trim(), prop); if (important && !RE_IMPORTANT.test(newValue)) { newValue += important[0]; } return newValue; }
javascript
{ "resource": "" }
q49848
flipShadow
train
function flipShadow(value) { var elements = value.split(/\s+/); if (!elements) { return value; } var inset = (elements[0] == 'inset') ? elements.shift() + ' ' : ''; var property = elements[0].match(/^([-+]?\d+)(\w*)$/); if (!property) { return value; } return inset + [(-1 * +property[1]) + property[2]] .concat(elements.splice(1)).join(' '); }
javascript
{ "resource": "" }
q49849
train
function(state1, state2) { // if state1 is undefined, return state2 + isEqual=false and velocity=0 as delta if(!state1 || !state2) return angular.extend( {isEqual: false, velocityX: 0, velocityY: 0}, state2 ); // calculate delta of state1 and state2 var delta= { posX: state2.posX - state1.posX, posY: state2.posY - state1.posY, width: state2.width - state1.width, height: state2.height - state1.height, maxWidth: state2.maxWidth - state1.maxWidth, maxHeight: state2.maxHeight - state1.maxHeight, }; // add velocity information if(state2.width > 0) delta.velocityX= delta.posX / state2.width; if(state2.height > 0) delta.velocityY= delta.posY / state2.height; // if any property is not 0, the delta is not zero delta.isEqual= !( delta.posX !== 0 || delta.posY !== 0 || delta.width !== 0 || delta.height !== 0 || delta.maxWidth !== 0 || delta.maxHeight !== 0 ); return delta; }
javascript
{ "resource": "" }
q49850
get
train
function get(src) { var defer = $q.defer(); _checkImgCacheReady() .then(function() { ImgCache.isCached(src, function(path, success) { if (success) { defer.resolve(path); } else { defer.reject(); } }, defer.reject); }) .catch(defer.reject); return defer.promise; }
javascript
{ "resource": "" }
q49851
remove
train
function remove(src) { var defer = $q.defer(); _checkImgCacheReady() .then(function() { ImgCache.isCached(src, function(path, success) { ImgCache.removeFile(src, function() { defer.resolve(); }, defer.reject); }, defer.reject); }) .catch(defer.reject); return defer.promise; }
javascript
{ "resource": "" }
q49852
checkCacheStatus
train
function checkCacheStatus(src) { var defer = $q.defer(); _checkImgCacheReady() .then(function() { ImgCache.isCached(src, function(path, success) { if (success) { defer.resolve(path); } else { ImgCache.cacheFile(src, function() { ImgCache.isCached(src, function(path, success) { defer.resolve(path); }, defer.reject); }, defer.reject); } }, defer.reject); }) .catch(defer.reject); return defer.promise; }
javascript
{ "resource": "" }
q49853
checkBgCacheStatus
train
function checkBgCacheStatus(element) { var defer = $q.defer(); _checkImgCacheReady() .then(function() { ImgCache.isBackgroundCached(element, function(path, success) { if (success) { defer.resolve(path); } else { ImgCache.cacheBackground(element, function() { ImgCache.isBackgroundCached(element, function(path, success) { defer.resolve(path); }, defer.reject); }, defer.reject); } }, defer.reject); }) .catch(defer.reject); return defer.promise; }
javascript
{ "resource": "" }
q49854
clearCache
train
function clearCache() { var defer = $q.defer(); _checkImgCacheReady() .then(function() { ImgCache.clearCache(defer.resolve, defer.reject); }) .catch(defer.reject); return defer.promise; }
javascript
{ "resource": "" }
q49855
getCacheSize
train
function getCacheSize() { var defer = $q.defer(); _checkImgCacheReady() .then(function() { defer.resolve(ImgCache.getCurrentSize()); }) .catch(defer.reject); return defer.promise; }
javascript
{ "resource": "" }
q49856
_checkImgCacheReady
train
function _checkImgCacheReady() { var defer = $q.defer(); if (ImgCache.ready) { defer.resolve(); } else{ document.addEventListener('ImgCacheReady', function() { // eslint-disable-line defer.resolve(); }, false); } return defer.promise; }
javascript
{ "resource": "" }
q49857
randomString
train
function randomString(length) { var bits = 36, tmp, out = ""; while (out.length < length) { tmp = Math.random().toString(bits).slice(2); out += tmp.slice(0, Math.min(tmp.length, (length - out.length))); } return out.toUpperCase(); }
javascript
{ "resource": "" }
q49858
logtap
train
function logtap(logger, message, data) { data = _.clone(data); if (data.payload_binary) { data.payload_binary = '... (' + data.payload_binary.length + ' bytes)'; } logger.debug(message, data); }
javascript
{ "resource": "" }
q49859
train
function(message) { if (message.namespace === data.namespace && message.data.requestId === data.data.requestId) { if (timer) { clearTimeout(timer); } self.removeListener('message', answer); self.removeListener('disconnect', cancel); cb(null, message); } }
javascript
{ "resource": "" }
q49860
getPathHostName
train
function getPathHostName(origin, path) { const pathOverride = { '/oauth/userinfo': `https://${origin}.battle.net`, }; return Object.prototype.hasOwnProperty.call(pathOverride, path) ? pathOverride[path] : endpoints[origin].hostname; }
javascript
{ "resource": "" }
q49861
getEndpoint
train
function getEndpoint(origin, locale, path) { const validOrigin = Object.prototype.hasOwnProperty.call(endpoints, origin) ? origin : 'us'; const endpoint = endpoints[validOrigin]; return Object.assign( {}, { origin: validOrigin }, { hostname: origin === 'cn' ? endpoint.hostname : getPathHostName(validOrigin, path) }, { locale: endpoint.locales.find(item => item === locale) || endpoint.defaultLocale }, ); }
javascript
{ "resource": "" }
q49862
Blizzard
train
function Blizzard(args, instance) { const { key, secret, token } = args; const { origin, locale } = endpoints.getEndpoint(args.origin, args.locale); this.version = pkg.version; this.defaults = { origin, locale, key, secret, token, }; this.axios = axios.create(instance); /** * Account API methods. * * @member {Object} * @see {@link lib/account} */ this.account = new Account(this); /** * Profile API methods. * * @member {Object} * @see {@link lib/profile} */ this.profile = new Profile(this); /** * Diablo 3 API methods. * * @member {Object} * @see {@link lib/d3} */ this.d3 = new Diablo3(this); /** * Starcraft 2 API methods. * * @member {Object} * @see {@link lib/sc2} */ this.sc2 = new Starcraft2(this); /** * World of Warcraft API methods. * * @member {Object} * @see {@link lib/wow} */ this.wow = new WorldOfWarcraft(this); }
javascript
{ "resource": "" }
q49863
unescape
train
function unescape(str, type) { if (!isString(str)) return ''; var chars = charSets[type || 'default']; var regex = toRegex(type, chars); return str.replace(regex, function(m) { return chars[m]; }); }
javascript
{ "resource": "" }
q49864
roundToStepRatio
train
function roundToStepRatio (value, stepRatio) { const stepRatioDecimals = calculateDecimals(stepRatio); const stepDecimalsMultiplier = Math.pow(10, stepRatioDecimals); value = Math.round(value / stepRatio) * stepRatio; return Math.round(value * stepDecimalsMultiplier) / stepDecimalsMultiplier; }
javascript
{ "resource": "" }
q49865
findSameInArray
train
function findSameInArray (array, compareIndex) { const sliders = []; array.forEach((value, index) => { if (value === array[compareIndex]) { sliders.push(index); } }); return sliders; }
javascript
{ "resource": "" }
q49866
findClosestValue
train
function findClosestValue (values, lookupVal) { let diff = 1; let id = 0; values.forEach((value, index) => { const actualDiff = Math.abs(value - lookupVal); if (actualDiff < diff) { id = index; diff = actualDiff; } }); return id; }
javascript
{ "resource": "" }
q49867
roundToStep
train
function roundToStep (value, step) { const stepDecimals = calculateDecimals(step); const stepDecimalsMultiplier = Math.pow(10, stepDecimals); value = Math.round(value / step) * step; return Math.round(value * stepDecimalsMultiplier) / stepDecimalsMultiplier; }
javascript
{ "resource": "" }
q49868
train
function(lock) { lock.acquire = function(key, fn) { Lock._acquiredLocks[lock._id] = lock; lock._locked = true; lock._key = key; return client.setAsync(key, lock._id).nodeify(fn); }; }
javascript
{ "resource": "" }
q49869
Tokenizer
train
function Tokenizer( regex, token ) { var matches = [], index = 0; /** * Add a match. * * @private * @param {string} match Matched string * @return {string} Token to leave in the matched string's place */ function tokenizeCallback( match ) { matches.push( match ); return token; } /** * Get a match. * * @private * @return {string} Original matched string to restore */ function detokenizeCallback() { return matches[ index++ ]; } return { /** * Replace matching strings with tokens. * * @param {string} str String to tokenize * @return {string} Tokenized string */ tokenize: function ( str ) { return str.replace( regex, tokenizeCallback ); }, /** * Restores tokens to their original values. * * @param {string} str String previously run through tokenize() * @return {string} Original string */ detokenize: function ( str ) { return str.replace( new RegExp( '(' + token + ')', 'g' ), detokenizeCallback ); } }; }
javascript
{ "resource": "" }
q49870
CSSJanus
train
function CSSJanus() { var // Tokens temporaryToken = '`TMP`', noFlipSingleToken = '`NOFLIP_SINGLE`', noFlipClassToken = '`NOFLIP_CLASS`', commentToken = '`COMMENT`', // Patterns nonAsciiPattern = '[^\\u0020-\\u007e]', unicodePattern = '(?:(?:\\\\[0-9a-f]{1,6})(?:\\r\\n|\\s)?)', numPattern = '(?:[0-9]*\\.[0-9]+|[0-9]+)', unitPattern = '(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)', directionPattern = 'direction\\s*:\\s*', urlSpecialCharsPattern = '[!#$%&*-~]', validAfterUriCharsPattern = '[\'"]?\\s*', nonLetterPattern = '(^|[^a-zA-Z])', charsWithinSelectorPattern = '[^\\}]*?', noFlipPattern = '\\/\\*\\!?\\s*@noflip\\s*\\*\\/', commentPattern = '\\/\\*[^*]*\\*+([^\\/*][^*]*\\*+)*\\/', escapePattern = '(?:' + unicodePattern + '|\\\\[^\\r\\n\\f0-9a-f])', nmstartPattern = '(?:[_a-z]|' + nonAsciiPattern + '|' + escapePattern + ')', nmcharPattern = '(?:[_a-z0-9-]|' + nonAsciiPattern + '|' + escapePattern + ')', identPattern = '-?' + nmstartPattern + nmcharPattern + '*', quantPattern = numPattern + '(?:\\s*' + unitPattern + '|' + identPattern + ')?', signedQuantPattern = '((?:-?' + quantPattern + ')|(?:inherit|auto))', fourNotationQuantPropsPattern = '((?:margin|padding|border-width)\\s*:\\s*)', fourNotationColorPropsPattern = '((?:-color|border-style)\\s*:\\s*)', colorPattern = '(#?' + nmcharPattern + '+|(?:rgba?|hsla?)\\([ \\d.,%-]+\\))', urlCharsPattern = '(?:' + urlSpecialCharsPattern + '|' + nonAsciiPattern + '|' + escapePattern + ')*', lookAheadNotLetterPattern = '(?![a-zA-Z])', lookAheadNotOpenBracePattern = '(?!(' + nmcharPattern + '|\\r?\\n|\\s|#|\\:|\\.|\\,|\\+|>|\\(|\\)|\\[|\\]|=|\\*=|~=|\\^=|\'[^\']*\'])*?{)', lookAheadNotClosingParenPattern = '(?!' + urlCharsPattern + '?' + validAfterUriCharsPattern + '\\))', lookAheadForClosingParenPattern = '(?=' + urlCharsPattern + '?' + validAfterUriCharsPattern + '\\))', suffixPattern = '(\\s*(?:!important\\s*)?[;}])', // Regular expressions temporaryTokenRegExp = new RegExp( '`TMP`', 'g' ), commentRegExp = new RegExp( commentPattern, 'gi' ), noFlipSingleRegExp = new RegExp( '(' + noFlipPattern + lookAheadNotOpenBracePattern + '[^;}]+;?)', 'gi' ), noFlipClassRegExp = new RegExp( '(' + noFlipPattern + charsWithinSelectorPattern + '})', 'gi' ), directionLtrRegExp = new RegExp( '(' + directionPattern + ')ltr', 'gi' ), directionRtlRegExp = new RegExp( '(' + directionPattern + ')rtl', 'gi' ), leftRegExp = new RegExp( nonLetterPattern + '(left)' + lookAheadNotLetterPattern + lookAheadNotClosingParenPattern + lookAheadNotOpenBracePattern, 'gi' ), rightRegExp = new RegExp( nonLetterPattern + '(right)' + lookAheadNotLetterPattern + lookAheadNotClosingParenPattern + lookAheadNotOpenBracePattern, 'gi' ), leftInUrlRegExp = new RegExp( nonLetterPattern + '(left)' + lookAheadForClosingParenPattern, 'gi' ), rightInUrlRegExp = new RegExp( nonLetterPattern + '(right)' + lookAheadForClosingParenPattern, 'gi' ), ltrInUrlRegExp = new RegExp( nonLetterPattern + '(ltr)' + lookAheadForClosingParenPattern, 'gi' ), rtlInUrlRegExp = new RegExp( nonLetterPattern + '(rtl)' + lookAheadForClosingParenPattern, 'gi' ), cursorEastRegExp = new RegExp( nonLetterPattern + '([ns]?)e-resize', 'gi' ), cursorWestRegExp = new RegExp( nonLetterPattern + '([ns]?)w-resize', 'gi' ), fourNotationQuantRegExp = new RegExp( fourNotationQuantPropsPattern + signedQuantPattern + '(\\s+)' + signedQuantPattern + '(\\s+)' + signedQuantPattern + '(\\s+)' + signedQuantPattern + suffixPattern, 'gi' ), fourNotationColorRegExp = new RegExp( fourNotationColorPropsPattern + colorPattern + '(\\s+)' + colorPattern + '(\\s+)' + colorPattern + '(\\s+)' + colorPattern + suffixPattern, 'gi' ), bgHorizontalPercentageRegExp = new RegExp( '(background(?:-position)?\\s*:\\s*(?:[^:;}\\s]+\\s+)*?)(' + quantPattern + ')', 'gi' ), bgHorizontalPercentageXRegExp = new RegExp( '(background-position-x\\s*:\\s*)(-?' + numPattern + '%)', 'gi' ), // border-radius: <length or percentage>{1,4} [optional: / <length or percentage>{1,4} ] borderRadiusRegExp = new RegExp( '(border-radius\\s*:\\s*)' + signedQuantPattern + '(?:(?:\\s+' + signedQuantPattern + ')(?:\\s+' + signedQuantPattern + ')?(?:\\s+' + signedQuantPattern + ')?)?' + '(?:(?:(?:\\s*\\/\\s*)' + signedQuantPattern + ')(?:\\s+' + signedQuantPattern + ')?(?:\\s+' + signedQuantPattern + ')?(?:\\s+' + signedQuantPattern + ')?)?' + suffixPattern, 'gi' ), boxShadowRegExp = new RegExp( '(box-shadow\\s*:\\s*(?:inset\\s*)?)' + signedQuantPattern, 'gi' ), textShadow1RegExp = new RegExp( '(text-shadow\\s*:\\s*)' + signedQuantPattern + '(\\s*)' + colorPattern, 'gi' ), textShadow2RegExp = new RegExp( '(text-shadow\\s*:\\s*)' + colorPattern + '(\\s*)' + signedQuantPattern, 'gi' ), textShadow3RegExp = new RegExp( '(text-shadow\\s*:\\s*)' + signedQuantPattern, 'gi' ), translateXRegExp = new RegExp( '(transform\\s*:[^;}]*)(translateX\\s*\\(\\s*)' + signedQuantPattern + '(\\s*\\))', 'gi' ), translateRegExp = new RegExp( '(transform\\s*:[^;}]*)(translate\\s*\\(\\s*)' + signedQuantPattern + '((?:\\s*,\\s*' + signedQuantPattern + '){0,2}\\s*\\))', 'gi' ); /** * Invert the horizontal value of a background position property. * * @private * @param {string} match Matched property * @param {string} pre Text before value * @param {string} value Horizontal value * @return {string} Inverted property */ function calculateNewBackgroundPosition( match, pre, value ) { var idx, len; if ( value.slice( -1 ) === '%' ) { idx = value.indexOf( '.' ); if ( idx !== -1 ) { // Two off, one for the "%" at the end, one for the dot itself len = value.length - idx - 2; value = 100 - parseFloat( value ); value = value.toFixed( len ) + '%'; } else { value = 100 - parseFloat( value ) + '%'; } } return pre + value; } /** * Invert a set of border radius values. * * @private * @param {Array} values Matched values * @return {string} Inverted values */ function flipBorderRadiusValues( values ) { switch ( values.length ) { case 4: values = [ values[ 1 ], values[ 0 ], values[ 3 ], values[ 2 ] ]; break; case 3: values = [ values[ 1 ], values[ 0 ], values[ 1 ], values[ 2 ] ]; break; case 2: values = [ values[ 1 ], values[ 0 ] ]; break; case 1: values = [ values[ 0 ] ]; break; } return values.join( ' ' ); } /** * Invert a set of border radius values. * * @private * @param {string} match Matched property * @param {string} pre Text before value * @param {string} [firstGroup1] * @param {string} [firstGroup2] * @param {string} [firstGroup3] * @param {string} [firstGroup4] * @param {string} [secondGroup1] * @param {string} [secondGroup2] * @param {string} [secondGroup3] * @param {string} [secondGroup4] * @param {string} [post] Text after value * @return {string} Inverted property */ function calculateNewBorderRadius( match, pre ) { var values, args = [].slice.call( arguments ), firstGroup = args.slice( 2, 6 ).filter( function ( val ) { return val; } ), secondGroup = args.slice( 6, 10 ).filter( function ( val ) { return val; } ), post = args[ 10 ] || ''; if ( secondGroup.length ) { values = flipBorderRadiusValues( firstGroup ) + ' / ' + flipBorderRadiusValues( secondGroup ); } else { values = flipBorderRadiusValues( firstGroup ); } return pre + values + post; } /** * Flip the sign of a CSS value, possibly with a unit. * * We can't just negate the value with unary minus due to the units. * * @private * @param {string} value * @return {string} */ function flipSign( value ) { if ( parseFloat( value ) === 0 ) { // Don't mangle zeroes return value; } if ( value[ 0 ] === '-' ) { return value.slice( 1 ); } return '-' + value; } /** * @private * @param {string} match * @param {string} property * @param {string} offset * @return {string} */ function calculateNewShadow( match, property, offset ) { return property + flipSign( offset ); } /** * @private * @param {string} match * @param {string} property * @param {string} prefix * @param {string} offset * @param {string} suffix * @return {string} */ function calculateNewTranslate( match, property, prefix, offset, suffix ) { return property + prefix + flipSign( offset ) + suffix; } /** * @private * @param {string} match * @param {string} property * @param {string} color * @param {string} space * @param {string} offset * @return {string} */ function calculateNewFourTextShadow( match, property, color, space, offset ) { return property + color + space + flipSign( offset ); } return { /** * Transform a left-to-right stylesheet to right-to-left. * * @param {string} css Stylesheet to transform * @param {Object} options Options * @param {boolean} [options.transformDirInUrl=false] Transform directions in URLs (e.g. 'ltr', 'rtl') * @param {boolean} [options.transformEdgeInUrl=false] Transform edges in URLs (e.g. 'left', 'right') * @return {string} Transformed stylesheet */ 'transform': function ( css, options ) { // eslint-disable-line quote-props, (for closure compiler) // Tokenizers var noFlipSingleTokenizer = new Tokenizer( noFlipSingleRegExp, noFlipSingleToken ), noFlipClassTokenizer = new Tokenizer( noFlipClassRegExp, noFlipClassToken ), commentTokenizer = new Tokenizer( commentRegExp, commentToken ); // Tokenize css = commentTokenizer.tokenize( noFlipClassTokenizer.tokenize( noFlipSingleTokenizer.tokenize( // We wrap tokens in ` , not ~ like the original implementation does. // This was done because ` is not a legal character in CSS and can only // occur in URLs, where we escape it to %60 before inserting our tokens. css.replace( '`', '%60' ) ) ) ); // Transform URLs if ( options.transformDirInUrl ) { // Replace 'ltr' with 'rtl' and vice versa in background URLs css = css .replace( ltrInUrlRegExp, '$1' + temporaryToken ) .replace( rtlInUrlRegExp, '$1ltr' ) .replace( temporaryTokenRegExp, 'rtl' ); } if ( options.transformEdgeInUrl ) { // Replace 'left' with 'right' and vice versa in background URLs css = css .replace( leftInUrlRegExp, '$1' + temporaryToken ) .replace( rightInUrlRegExp, '$1left' ) .replace( temporaryTokenRegExp, 'right' ); } // Transform rules css = css // Replace direction: ltr; with direction: rtl; and vice versa. .replace( directionLtrRegExp, '$1' + temporaryToken ) .replace( directionRtlRegExp, '$1ltr' ) .replace( temporaryTokenRegExp, 'rtl' ) // Flip rules like left: , padding-right: , etc. .replace( leftRegExp, '$1' + temporaryToken ) .replace( rightRegExp, '$1left' ) .replace( temporaryTokenRegExp, 'right' ) // Flip East and West in rules like cursor: nw-resize; .replace( cursorEastRegExp, '$1$2' + temporaryToken ) .replace( cursorWestRegExp, '$1$2e-resize' ) .replace( temporaryTokenRegExp, 'w-resize' ) // Border radius .replace( borderRadiusRegExp, calculateNewBorderRadius ) // Shadows .replace( boxShadowRegExp, calculateNewShadow ) .replace( textShadow1RegExp, calculateNewFourTextShadow ) .replace( textShadow2RegExp, calculateNewFourTextShadow ) .replace( textShadow3RegExp, calculateNewShadow ) // Translate .replace( translateXRegExp, calculateNewTranslate ) .replace( translateRegExp, calculateNewTranslate ) // Swap the second and fourth parts in four-part notation rules // like padding: 1px 2px 3px 4px; .replace( fourNotationQuantRegExp, '$1$2$3$8$5$6$7$4$9' ) .replace( fourNotationColorRegExp, '$1$2$3$8$5$6$7$4$9' ) // Flip horizontal background percentages .replace( bgHorizontalPercentageRegExp, calculateNewBackgroundPosition ) .replace( bgHorizontalPercentageXRegExp, calculateNewBackgroundPosition ); // Detokenize css = noFlipSingleTokenizer.detokenize( noFlipClassTokenizer.detokenize( commentTokenizer.detokenize( css ) ) ); return css; } }; }
javascript
{ "resource": "" }
q49871
calculateNewBackgroundPosition
train
function calculateNewBackgroundPosition( match, pre, value ) { var idx, len; if ( value.slice( -1 ) === '%' ) { idx = value.indexOf( '.' ); if ( idx !== -1 ) { // Two off, one for the "%" at the end, one for the dot itself len = value.length - idx - 2; value = 100 - parseFloat( value ); value = value.toFixed( len ) + '%'; } else { value = 100 - parseFloat( value ) + '%'; } } return pre + value; }
javascript
{ "resource": "" }
q49872
train
function ( css, options ) { // eslint-disable-line quote-props, (for closure compiler) // Tokenizers var noFlipSingleTokenizer = new Tokenizer( noFlipSingleRegExp, noFlipSingleToken ), noFlipClassTokenizer = new Tokenizer( noFlipClassRegExp, noFlipClassToken ), commentTokenizer = new Tokenizer( commentRegExp, commentToken ); // Tokenize css = commentTokenizer.tokenize( noFlipClassTokenizer.tokenize( noFlipSingleTokenizer.tokenize( // We wrap tokens in ` , not ~ like the original implementation does. // This was done because ` is not a legal character in CSS and can only // occur in URLs, where we escape it to %60 before inserting our tokens. css.replace( '`', '%60' ) ) ) ); // Transform URLs if ( options.transformDirInUrl ) { // Replace 'ltr' with 'rtl' and vice versa in background URLs css = css .replace( ltrInUrlRegExp, '$1' + temporaryToken ) .replace( rtlInUrlRegExp, '$1ltr' ) .replace( temporaryTokenRegExp, 'rtl' ); } if ( options.transformEdgeInUrl ) { // Replace 'left' with 'right' and vice versa in background URLs css = css .replace( leftInUrlRegExp, '$1' + temporaryToken ) .replace( rightInUrlRegExp, '$1left' ) .replace( temporaryTokenRegExp, 'right' ); } // Transform rules css = css // Replace direction: ltr; with direction: rtl; and vice versa. .replace( directionLtrRegExp, '$1' + temporaryToken ) .replace( directionRtlRegExp, '$1ltr' ) .replace( temporaryTokenRegExp, 'rtl' ) // Flip rules like left: , padding-right: , etc. .replace( leftRegExp, '$1' + temporaryToken ) .replace( rightRegExp, '$1left' ) .replace( temporaryTokenRegExp, 'right' ) // Flip East and West in rules like cursor: nw-resize; .replace( cursorEastRegExp, '$1$2' + temporaryToken ) .replace( cursorWestRegExp, '$1$2e-resize' ) .replace( temporaryTokenRegExp, 'w-resize' ) // Border radius .replace( borderRadiusRegExp, calculateNewBorderRadius ) // Shadows .replace( boxShadowRegExp, calculateNewShadow ) .replace( textShadow1RegExp, calculateNewFourTextShadow ) .replace( textShadow2RegExp, calculateNewFourTextShadow ) .replace( textShadow3RegExp, calculateNewShadow ) // Translate .replace( translateXRegExp, calculateNewTranslate ) .replace( translateRegExp, calculateNewTranslate ) // Swap the second and fourth parts in four-part notation rules // like padding: 1px 2px 3px 4px; .replace( fourNotationQuantRegExp, '$1$2$3$8$5$6$7$4$9' ) .replace( fourNotationColorRegExp, '$1$2$3$8$5$6$7$4$9' ) // Flip horizontal background percentages .replace( bgHorizontalPercentageRegExp, calculateNewBackgroundPosition ) .replace( bgHorizontalPercentageXRegExp, calculateNewBackgroundPosition ); // Detokenize css = noFlipSingleTokenizer.detokenize( noFlipClassTokenizer.detokenize( commentTokenizer.detokenize( css ) ) ); return css; }
javascript
{ "resource": "" }
q49873
tryToSplit
train
function tryToSplit(value) { if (value.match(HAS_SEMICOLON_SEPARATOR)) { value = value.replace(/\\,/g, ','); return splitValue(value, ';'); } else if (value.match(HAS_COMMA_SEPARATOR)) { value = value.replace(/\\;/g, ';'); return splitValue(value, ','); } else { return value .replace(/\\,/g, ',') .replace(/\\;/g, ';'); } }
javascript
{ "resource": "" }
q49874
convert
train
function convert (message) { const obj = {} const lines = message.toString().trim().split('\r\n') if (lines && lines[0]) { obj.status = lines[0] for (const line of lines) { const fields = line.split(': ') if (fields.length === 2) { obj[fields[0].toLowerCase()] = fields[1] } } } return obj }
javascript
{ "resource": "" }
q49875
keyOptions
train
function keyOptions (key, options) { const _key = options._key == null ? key : options._key + '.' + key return Object.assign({}, options, { _key: _key }) }
javascript
{ "resource": "" }
q49876
idOptions
train
function idOptions (id, options) { const _key = options._key == null ? '[' + id + ']' : options._key + '[' + id + ']' return Object.assign({}, options, { _key: _key }) }
javascript
{ "resource": "" }
q49877
tweakWebpackConfig
train
function tweakWebpackConfig(module) { const { default: webpackConfig = module } = module; const config = handleWebpackConfig(webpackConfig); if (!config) { throw new Error( 'Not found webpack configuration. For multiple configurations in single file you must provide config with target "node".' ); } const hmrClientEntry = require.resolve('./HmrClient'); const addHmrClientEntry = (entry, entryOwner) => { const owner = entryOwner; if (Array.isArray(owner[entry])) { owner[entry].splice(-1, 0, hmrClientEntry); } else if (typeof owner[entry] === 'string') { owner[entry] = [hmrClientEntry, owner[entry]]; } else if (typeof owner[entry] === 'function') { // Call function and try again with function result. owner[entry] = owner[entry](); addHmrClientEntry(entry, owner); } else if (typeof owner[entry] === 'object') { Object.getOwnPropertyNames(owner[entry]).forEach(name => addHmrClientEntry(name, owner[entry]) ); } }; // Add HmrClient to every entries. addHmrClientEntry('entry', config); if (!config.plugins) { config.plugins = []; } // Add source-map support if configured. if (config.devtool && config.devtool.indexOf('source-map') >= 0) { config.plugins.push( new webpack.BannerPlugin({ banner: `;require('${require .resolve('source-map-support') .replace(/\\/g, '/')}').install();`, raw: true, entryOnly: false, }) ); } // Enable HMR globally if not. if (!config.plugins.find(p => p instanceof webpack.HotModuleReplacementPlugin)) { config.plugins.push(new webpack.HotModuleReplacementPlugin()); } return config; }
javascript
{ "resource": "" }
q49878
buildExcludeCheck
train
function buildExcludeCheck (transpileDependencies = []) { const dependencyChecks = transpileDependencies.map((dependency) => ( new RegExp(`node_modules.${dependency}`) )) // see: https://webpack.js.org/configuration/module/#condition return function (assetPath) { const shouldTranspile = dependencyChecks .reduce((result, check) => result || assetPath.match(check), false) if (shouldTranspile) { return false } return !!assetPath.match(/node_modules/) } }
javascript
{ "resource": "" }
q49879
vimeo
train
function vimeo(str) { if (str.indexOf('#') > -1) { str = str.split('#')[0]; } if (str.indexOf('?') > -1 && str.indexOf('clip_id=') === -1) { str = str.split('?')[0]; } var id; var arr; if (/https?:\/\/vimeo\.com\/[0-9]+$|https?:\/\/player\.vimeo\.com\/video\/[0-9]+$|https?:\/\/vimeo\.com\/channels|groups|album/igm.test(str)) { arr = str.split('/'); if (arr && arr.length) { id = arr.pop(); } } else if (/clip_id=/igm.test(str)) { arr = str.split('clip_id='); if (arr && arr.length) { id = arr[1].split('&')[0]; } } return id; }
javascript
{ "resource": "" }
q49880
vine
train
function vine(str) { var regex = /https:\/\/vine\.co\/v\/([a-zA-Z0-9]*)\/?/; var matches = regex.exec(str); return matches && matches[1]; }
javascript
{ "resource": "" }
q49881
youtube
train
function youtube(str) { // shortcode var shortcode = /youtube:\/\/|https?:\/\/youtu\.be\//g; if (shortcode.test(str)) { var shortcodeid = str.split(shortcode)[1]; return stripParameters(shortcodeid); } // /v/ or /vi/ var inlinev = /\/v\/|\/vi\//g; if (inlinev.test(str)) { var inlineid = str.split(inlinev)[1]; return stripParameters(inlineid); } // v= or vi= var parameterv = /v=|vi=/g; if (parameterv.test(str)) { var arr = str.split(parameterv); return arr[1].split('&')[0]; } // v= or vi= var parameterwebp = /\/an_webp\//g; if (parameterwebp.test(str)) { var webp = str.split(parameterwebp)[1]; return stripParameters(webp); } // embed var embedreg = /\/embed\//g; if (embedreg.test(str)) { var embedid = str.split(embedreg)[1]; return stripParameters(embedid); } // user var userreg = /\/user\/(?!.*videos)/g; if (userreg.test(str)) { var elements = str.split('/'); return stripParameters(elements.pop()); } // attribution_link var attrreg = /\/attribution_link\?.*v%3D([^%&]*)(%26|&|$)/; if (attrreg.test(str)) { return str.match(attrreg)[1]; } }
javascript
{ "resource": "" }
q49882
videopress
train
function videopress(str) { var idRegex; if (str.indexOf('embed') > -1) { idRegex = /embed\/(\w{8})/; return str.match(idRegex)[1]; } idRegex = /\/v\/(\w{8})/; var match = str.match(idRegex); if (match && match.length > 0) { return str.match(idRegex)[1]; } return undefined; }
javascript
{ "resource": "" }
q49883
train
function (name) { (Array.isArray(this._pending) ? this._pending : (this._pending = [])).push(arguments); this.emit(DISPATCHQUEUE_EVENT, name); }
javascript
{ "resource": "" }
q49884
train
function() { const packages = [ { name: 'ember-auto-import', target: getDependencyVersion(pkg, 'ember-auto-import'), }, { name: 'react', target: getPeerDependencyVersion(pkg, 'react'), }, { name: 'react-dom', target: getPeerDependencyVersion(pkg, 'react-dom'), }, ]; return this.addPackagesToProject(packages); }
javascript
{ "resource": "" }
q49885
train
function () { this.input = new YASMIJ.Input(); this.output = new YASMIJ.Output(); this.tableau = new YASMIJ.Tableau(); this.state = null; }
javascript
{ "resource": "" }
q49886
train
function(msg){ var logs = document.getElementById("logs"); logs.innerHTML += Funcs.util.getTimeStamp() + ": " + msg + "\n"; }
javascript
{ "resource": "" }
q49887
train
function(){ return { type : document.getElementById("problemType").value, objective : document.getElementById("problemObjective").value, constraints : $(".input_constraint").filter(function(){ return /\w/.test( $(this).val() ); }).map(function(){ return $(this).val(); }).toArray() }; }
javascript
{ "resource": "" }
q49888
react
train
function react(h) { var node = h && h('div') return Boolean( node && ('_owner' in node || '_store' in node) && node.key === null ) }
javascript
{ "resource": "" }
q49889
crawl
train
function crawl(callback, callbackArg, options) { options || (options = {}); if (callback == 'custom') { var isCustom = true; } else { isCustom = false; callback = filters[callback]; } var data, index, pool, pooled, queue, separator, roots = defaultRoots.slice(), object = options.object, path = options.path, result = []; // Resolve object roots. if (object) { // Resolve `undefined` path. if (path == null) { path = _.result(_.find(roots, { 'object': object }), 'path') || '<object>'; } roots = [{ 'object': object, 'path': path }]; } // Crawl all root objects. while ((data = roots.pop())) { index = 0; object = data.object; path = data.path; data = { 'object': object, 'path': path, 'pool': [object] }; queue = []; // A non-recursive solution to avoid call stack limits. // See http://www.jslab.dk/articles/non.recursive.preorder.traversal.part4 // for more details. do { object = data.object; path = data.path; separator = path ? '.' : ''; forOwn(object, function(value, key) { // IE may throw errors coercing properties like `window.external` or `window.navigator`. try { // Inspect objects. if (_.isPlainObject(value)) { // Clone current pool per prop on the current `object` to avoid // sibling properties from polluting each others object pools. pool = data.pool.slice(); // Check if already pooled (prevents infinite loops when handling circular references). pooled = _.find(pool, function(data) { return value == data.object; }); // Add to the "call" queue. if (!pooled) { pool.push({ 'object': value, 'path': path + separator + key, 'pool': pool }); queue.push(_.last(pool)); } } // If filter passed, log it. if ( isCustom ? callbackArg.call(data, value, key, object) : callback(callbackArg, key, object) ) { value = [ path + separator + key + ' -> (' + (pooled ? '<' + pooled.path + '>' : getKindOf(value).toLowerCase()) + ')', value ]; result.push(value); log('text', value[0], value[1]); } } catch(e) {} }); } while ((data = queue[index++])); } return result; }
javascript
{ "resource": "" }
q49890
log
train
function log() { var defaultCount = 2, console = isHostType(context, 'console') && context.console, document = isHostType(context, 'document') && context.document, phantom = isHostType(context, 'phantom') && context.phantom, JSON = isHostType(context, 'JSON') && _.isFunction(context.JSON && context.JSON.stringify) && context.JSON; // Lazy define `log`. log = function(type, message, value) { var argCount = defaultCount, method = 'log'; if (type == 'error') { argCount = 1; if (isHostType(console, type)) { method = type; } else { message = type + ': ' + message; } } // Avoid logging if in debug mode and running from the CLI. if (!isDebug || (document && !phantom)) { // Because `console.log` is a host method we don't assume `apply` exists. if (argCount < 2) { if (JSON) { value = [JSON.stringify(value), value]; value = value[0] == 'null' ? value[1] : value[0]; } console[method](message + (type == 'error' ? '' : ' ' + value)); } else { console[method](message, value); } } }; // For Rhino or RingoJS. if (!console && !document && _.isFunction(context.print)) { console = { 'log': print }; } // Use noop for no log support. if (!isHostType(console, 'log')) { log = function() {}; } // Avoid Safari 2 crash bug when passing more than 1 argument. else if (console.log.length == 1) { defaultCount = 1; } return log.apply(null, arguments); }
javascript
{ "resource": "" }
q49891
train
function(key, value, expiration) { // set item var ret = this._storage.setItem(key, value); // set expiration timestamp (only if defined) if (expiration) { this.updateExpiration(key, expiration); } // return set value return value return ret; }
javascript
{ "resource": "" }
q49892
train
function(key) { // get value and time left var ret = { value: this._storage.getItem(key), timeLeft: this.getTimeLeft(key), }; // set if expired ret.isExpired = ret.timeLeft !== null && ret.timeLeft <= 0; // return data return ret; }
javascript
{ "resource": "" }
q49893
train
function(key) { // try to fetch expiration time for key var expireTime = parseInt(this._storage.getItem(this._expiration_key_prefix + key)); // if got expiration time return how much left to live if (expireTime && !isNaN(expireTime)) { return expireTime - this.getTimestamp(); } // if don't have expiration time return null return null; }
javascript
{ "resource": "" }
q49894
train
function(key, val, expiration) { // special case - make sure not undefined, because it would just write "undefined" and crash on reading. if (val === undefined) { throw new Error("Cannot set undefined value as JSON!"); } // set stringified value return this.setItem(key, JSON.stringify(val), expiration); }
javascript
{ "resource": "" }
q49895
train
function(key) { // get value var val = this.getItem(key); // if null, return null if (val === null) { return null; } // parse and return value return JSON.parse(val); }
javascript
{ "resource": "" }
q49896
train
function(callback) { // first check if storage define a 'keys()' function. if it does, use it if (typeof this._storage.keys === "function") { var keys = this._storage.keys(); for (var i = 0; i < keys.length; ++i) { callback(keys[i]); } } // if not supported try to use object.keys else if (typeof Object === "function" && Object.keys) { var keys = Object.keys(this._storage); for (var i = 0; i < keys.length; ++i) { callback(keys[i]); } } // if not supported try to use iteration via length else if (this._storage.length !== undefined && typeof this._storage.key === "function") { // first build keys array, so this function will be delete-safe (eg if callback remove keys it won't cause problems due to index change) var keys = []; for (var i = 0, len = this._storage.length; i < len; ++i) { keys.push(this._storage.key(i)); } // now actually iterate keys for (var i = 0; i < keys.length; ++i) { callback(keys[i]); } } // if both methods above didn't work, iterate on all keys in storage class hoping for the best.. else { for (var storageKey in this._storage) { callback(storageKey); } } }
javascript
{ "resource": "" }
q49897
ContextController
train
function ContextController(context) { const _t = this; this._view = null; this.context = context; /** * @package * @type {!Array.<ZxQuery>} **/ this._fieldCache = []; // Interface methods /** @type {function} */ this.init = null; /** @type {function} */ this.create = null; /** @type {function} */ this.update = null; /** @type {function} */ this.destroy = null; /** * @protected * @type {!Array.<Element>} * */ this._childNodes = []; /** @type {function} */ this.saveView = function() { this.restoreView(); this.view().children().each(function(i, el) { _t._childNodes.push(el); }); }; this.restoreView = function() { if (this._childNodes.length > 0) { _t.view().html(''); z$.each(_t._childNodes, function(i, el) { _t.view().append(el); }); this._childNodes.length = 0; } }; this.on = function(eventPath, handler) { this.addEvent(eventPath, handler); return this; }; /** @protected */ this.mapEvent = function(eventMap, target, eventPath, handler) { if (target != null) { target.off(eventPath, this.eventRouter); eventMap[eventPath] = handler; target.on(eventPath, this.eventRouter); } else { // TODO: should report missing target } }; /** @protected */ this.eventRouter = function(e) { const v = _t.view(); if (typeof context._behaviorMap[e.type] === 'function') { context._behaviorMap[e.type].call(v, e, e.detail, v); } if (typeof context._eventMap[e.type] === 'function') { context._eventMap[e.type].call(v, e, e.detail, v); } // TODO: else-> should report anomaly }; // create event map from context options const options = context.options(); let handler = null; if (options.on != null) { for (let ep in options.on) { if (options.on.hasOwnProperty(ep)) { handler = options.on[ep]; _t.addEvent(ep, handler); } } } // create behavior map from context options if (options.behavior != null) { for (let bp in options.behavior) { if (options.behavior.hasOwnProperty(bp)) { handler = options.behavior[bp]; _t.addBehavior(bp, handler); } } } context.controller().call(this, this); return this; }
javascript
{ "resource": "" }
q49898
TaskQueue
train
function TaskQueue(listener) { const _t = this; _t._worker = null; _t._taskList = []; _t._requests = []; if (listener == null) { listener = function() { }; } _t.taskQueue = function(tid, fn, pri) { _t._taskList.push({ tid: tid, fn: fn, status: 0, priority: pri, step: function(tid) { // var _h = this; // _h.tid = tid; _log.t(tid, 'load:step'); listener(_t, 'load:step', { task: tid }); }, end: function() { this.status = 2; let _h = this; _log.t(_h.tid, 'load:next', 'timer:task:stop'); listener(_t, 'load:next', { task: _h.tid }); _t._taskList.splice(this.index, 1); _t.taskCheck(); if (this._callback != null) { this._callback.call(this); } }, callback: function(callback) { this._callback = callback; } }); _log.t(tid, 'task added', pri, 'priority'); _t._taskList.sort(function(a, b) { return (a.priority > b.priority) ? 1 : ((b.priority > a.priority) ? -1 : 0); } ); _t.taskCheck(); }; _t.taskCheck = function() { for (let i = 0; i < _t._taskList.length; i++) { if (_t._taskList[i].status === 0) { _t._taskList[i].status = 1; _log.t(_t._taskList[i].tid, 'load:begin', 'timer:task:start'); listener(_t, 'load:begin', { task: _t._taskList[i].tid }); _t._taskList[i].index = i; (_t._taskList[i].fn).call(_t._taskList[i]); return; } else if (_t._taskList[i].status === 1) { // currently running return; } else if (_t._taskList[i].status === 2) { // TODO: _!!!-! return; } } _log.t('load:end'); listener(_t, 'load:end'); }; }
javascript
{ "resource": "" }
q49899
ZxQuery
train
function ZxQuery(element) { /** @protected */ this._selection = []; if (typeof element === 'undefined') { element = document.documentElement; } if (element instanceof ZxQuery) { return element; } else if (element instanceof HTMLCollection || element instanceof NodeList) { const list = this._selection = []; z$.each(element, function(i, el) { list.push(el); }); } else if (Array.isArray(element)) { this._selection = element; } else if (element === window || element instanceof HTMLElement || element instanceof Node) { this._selection = [element]; } else if (typeof element === 'string') { this._selection = document.documentElement.querySelectorAll(element); } else if (element !== null) { // if (typeof element === 'string') { _log.e('ZxQuery cannot wrap object of this type.', (typeof element), element); throw new Error('ZxQuery cannot wrap object of this type.'); } return this; }
javascript
{ "resource": "" }