_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q7300
train
function () { if (!codeViewer.codeActive) { return; } if (window.getSelection().empty) { window.getSelection().empty(); } else if (window.getSelection().removeAllRanges) { window.getSelection().removeAllRanges(); } }
javascript
{ "resource": "" }
q7301
train
function () { $sgCodeContainer // Has class sg-view-container. .css('bottom', -$document.outerHeight()) .addClass('anim-ready'); // Make sure the close button handles the click. $('#sg-code-close-btn').click(function (e) { e.preventDefault(); codeViewer.closeCode(); }); // Make sure the click events are handled on the HTML tab. $(codeViewer.ids.e).click(function (e) { e.preventDefault(); codeViewer.swapCode('e'); }); // Make sure the click events are handled on the Mustache tab. $(codeViewer.ids.m).click(function (e) { e.preventDefault(); codeViewer.swapCode('m'); }); }
javascript
{ "resource": "" }
q7302
train
function () { let encoded = this.responseText; // We sometimes want markup code to be in an HTML-like template language with tags delimited by stashes. // In order for js-beautify to indent such code correctly, any space between control characters #, ^, and /, and // the variable name must be removed. However, we want to add the spaces back later. // \u00A0 is   a space character not enterable by keyboard, and therefore a good delimiter. encoded = encoded.replace(/(\{\{#)(\s+)(\S+)/g, '$1$3$2\u00A0'); encoded = encoded.replace(/(\{\{\^)(\s+)(\S+)/g, '$1$3$2\u00A0'); encoded = encoded.replace(/(\{\{\/)(\s+)(\S+)/g, '$1$3$2\u00A0'); encoded = window.html_beautify(encoded, { indent_handlebars: true, indent_size: 2, wrap_line_length: 0 }); // Add back removed spaces to retain the look intended by the author. encoded = encoded.replace(/(\{\{#)(\S+)(\s+)\u00A0/g, '$1$3$2'); encoded = encoded.replace(/(\{\{\^)(\S+)(\s+)\u00A0/g, '$1$3$2'); encoded = encoded.replace(/(\{\{\/)(\S+)(\s+)\u00A0/g, '$1$3$2'); // Delete empty lines. encoded = encoded.replace(/^\s*$\n/gm, ''); // Encode with HTML entities. encoded = window.he.encode(encoded); codeViewer.encoded = encoded; if (codeViewer.tabActive === 'e') { codeViewer.activateDefaultTab('e', encoded); } }
javascript
{ "resource": "" }
q7303
train
function () { let encoded = this.responseText; encoded = window.he.encode(encoded); codeViewer.mustache = encoded; if (codeViewer.tabActive === 'm') { codeViewer.activateDefaultTab('m', encoded); } }
javascript
{ "resource": "" }
q7304
train
function (type) { if (!codeViewer.codeActive) { return; } let fill = ''; codeViewer.tabActive = type; $sgCodeTitles.removeClass('sg-code-title-active'); switch (type) { case 'e': fill = codeViewer.encoded; $sgCodeTitleHtml.addClass('sg-code-title-active'); break; case 'm': fill = codeViewer.mustache; $sgCodeTitleMustache.addClass('sg-code-title-active'); break; } $sgCodeFill.removeClass().addClass('language-markup'); $sgCodeFill.html(fill); window.Prism.highlightElement($sgCodeFill[0]); codeViewer.clearSelection(); }
javascript
{ "resource": "" }
q7305
EventJobs
train
function EventJobs (opts) { debug('EventJobs constructor'); this._publishedEvents = opts.publishedEvents || []; this._subscribedEvents = opts.subscribedEvents || []; this._name = opts.name; if (!this._name) { debug('error: name required for EventJobs'); throw new Error('name required for EventJobs'); } }
javascript
{ "resource": "" }
q7306
processFile
train
function processFile(file, filename, callback) { // Check if it matches the convention. if (path.extname(filename) === '.metadata') { // Find the name of the metadata. const name = path.basename(filename, '.metadata') // Recursively merge the meta data. const newMetadata = {} newMetadata[name] = file extend(true, metadata, newMetadata) // Remove the file since we've now processed it. delete files[filename] } callback() }
javascript
{ "resource": "" }
q7307
codify
train
function codify(object) { if (object === undefined) { return object; } else { let json = JSON.stringify(object, undefined, "\t"); // First substitue embedded double quotes with FFFF json = json.replace(/\\"/g, "\uFFFF"); // Now replace all property name quotes json = json.replace(/"([a-zA-Z_$][a-zA-Z0-9_$]+)":/g, "$1:"); // Now replace all other double quotes with single ones json = json.replace(/"/g, "'"); // And finally replace the FFFF with embedded double quotes json = json.replace(/\uFFFF/g, "\\\""); // Now remove quotes for known code variables json = json.replace(/'__dirname'/g, "__dirname"); return json; } }
javascript
{ "resource": "" }
q7308
Scope
train
function Scope(data, affix, parent) { if (data !== undefined) { this.data = data; } else { this.data = {}; } if (parent) { this.parent = parent; this.root = parent.root; } else { this.parent = undefined; this.root = this; } this.affix = affix || {}; this.ready = false; }
javascript
{ "resource": "" }
q7309
selectorValidateAndParse
train
function selectorValidateAndParse(selectorRaw_) { const selectorRaw = selectorRaw_.trim(); const bracketOpenPos = selectorRaw.indexOf('['); const bracketClosePos = selectorRaw.indexOf(']'); let indexStr; let name = selectorRaw; // Slice selectorRaw to extract name and indexStr if submitted. if (bracketOpenPos > -1) { if (bracketClosePos === selectorRaw.length - 1) { indexStr = selectorRaw.slice(bracketOpenPos + 1, bracketClosePos); name = selectorRaw.slice(0, bracketOpenPos); } else { return null; } } // Validate that name is a css selector. // eslint-disable-next-line no-useless-escape if (!/^(#|\.)?[_a-z][\w#\-\.]*$/i.test(name)) { return null; } // If indexStr if submitted, validate it is an integer. if (indexStr) { if (!/^\d+$/.test(indexStr)) { return null; } } return name; }
javascript
{ "resource": "" }
q7310
addThisDotProps
train
function addThisDotProps(path) { path.replaceWith( t.memberExpression( t.memberExpression(t.thisExpression(), t.identifier('props')), path.node ) ); }
javascript
{ "resource": "" }
q7311
isDestructuredPropsReference
train
function isDestructuredPropsReference(path) { const object = path.get('object'); if (!path.scope.hasOwnBinding(object.node.name)) { return; } const bindingValue = path.scope.bindings[object.node.name].path.get('init'); return ( (bindingValue.isMemberExpression() && bindingValue.get('object').isThisExpression() && bindingValue.get('property').isIdentifier({ name: 'props' })) || bindingValue.isThisExpression() ); }
javascript
{ "resource": "" }
q7312
isObjectMemberProperty
train
function isObjectMemberProperty(path) { return ( t.isMemberExpression(path.parent) && path.parentPath.get('property') === path ); }
javascript
{ "resource": "" }
q7313
createShadowDOM
train
function createShadowDOM(p_ComponentInstance, p_ComponentTemplate) { // retrieve the correct template from our map of previously stored templates const templateInstance = window.webComponentTemplates.get(p_ComponentTemplate); // if we are using the shadyCSS polyfill, we must initialize that now if (window.ShadyCSS) { window.ShadyCSS.prepareTemplate(templateInstance, p_ComponentTemplate); window.ShadyCSS.styleElement(p_ComponentInstance); } // create the shadow DOM root here const shadowRoot = p_ComponentInstance.attachShadow({ mode: 'open' }); shadowRoot.appendChild(templateInstance.content.cloneNode(true)); }
javascript
{ "resource": "" }
q7314
visibilityFilter
train
function visibilityFilter(state = SHOW_ALL, action = {}) { const {type, filter} = action; switch (type) { case SET_VISIBILITY_FILTER: return filter; default: return state; } }
javascript
{ "resource": "" }
q7315
Iterator
train
function Iterator(array) { // the array and current slot index are private attributes so methods that use them // are defined in the constructor var currentSlot = 0; // the slot before the first item this.toStart = function() { currentSlot = 0; // the slot before the first item }; this.toSlot = function(slot) { const size = array.length; if (slot > size) slot = size; if (slot < -size) slot = -size; if (slot < 0) slot = slot + size + 1; currentSlot = slot; }; this.toEnd = function() { currentSlot = array.length; // the slot after the last item }; this.hasPrevious = function() { return currentSlot > 0; }; this.hasNext = function() { return currentSlot < array.length; }; this.getPrevious = function() { if (!this.hasPrevious()) return; return array[--currentSlot]; }; this.getNext = function() { if (!this.hasNext()) return; return array[currentSlot++]; }; return this; }
javascript
{ "resource": "" }
q7316
StyleSheet
train
function StyleSheet(el) { /** * style/link element or selector * @cfg {HTMLElement|String} el */ /** * style/link element * @type {HTMLElement} * @property el */ if (el.el) { el = el.el; } el = this.el = Dom.get(el); // http://msdn.microsoft.com/en-us/library/ie/ms535871(v=vs.85).aspx // firefox 跨域时抛出异常 // http://msdn.microsoft.com/en-us/library/ie/ms535871(v=vs.85).aspx // firefox 跨域时抛出异常 var sheet = el.sheet || el.styleSheet; this.sheet = sheet; var cssRules = {}; this.cssRules = cssRules; var rulesName = sheet && 'cssRules' in sheet ? 'cssRules' : 'rules'; this.rulesName = rulesName; var domCssRules = sheet[rulesName]; var i, rule, selectorText, styleDeclaration; for (i = domCssRules.length - 1; i >= 0; i--) { rule = domCssRules[i]; selectorText = rule.selectorText; // 去重 // 去重 if (styleDeclaration = cssRules[selectorText]) { styleDeclaration.style.cssText += ';' + styleDeclaration.style.cssText; deleteRule(sheet, i); } else { cssRules[selectorText] = rule; } } }
javascript
{ "resource": "" }
q7317
train
function (selectorText) { var rule, css, selector, cssRules = this.cssRules; if (selectorText) { rule = cssRules[selectorText]; return rule ? rule.style.cssText : null; } else { css = []; for (selector in cssRules) { rule = cssRules[selector]; css.push(rule.selectorText + ' {' + rule.style.cssText + '}'); } return css.join('\n'); } }
javascript
{ "resource": "" }
q7318
Probability
train
function Probability(value, parameters) { abstractions.Element.call(this, utilities.types.PROBABILITY, parameters); if (value === undefined) value = 0; // default value if (!isFinite(value) || value < 0 || value > 1) { throw new utilities.Exception({ $module: '/bali/elements/Probability', $procedure: '$Probability', $exception: '$invalidParameter', $parameter: value.toString(), $text: '"An invalid probability value was passed to the constructor."' }); } // since this element is immutable the value must be read-only this.getValue = function() { return value; }; return this; }
javascript
{ "resource": "" }
q7319
boot
train
function boot() { if (config === null) { // TODO [NSTDFRZN] Be sure nested objects are frozen too config = Object.freeze(gatherConfigFromEnv()); } ee.emitAsync('booting_backing') .then(() => { ee.emit('booting'); ee.emit('booted'); }) .catch((err) => { ee.emit('error', err); // TODO [ERR2BTERR] Maybe err -> BootError(err) }); }
javascript
{ "resource": "" }
q7320
train
function (isJson, transformer) { printHelpOnExit = false; return function (value) { if (isJson) { console.log(JSON.stringify(value, null, 2)); } else if (typeof transformer === 'function') { console.log(transformer(value)); } else { console.log(value); } if (theUfo) theUfo.disconnect(); }; }
javascript
{ "resource": "" }
q7321
train
function (obj) { printHelpOnExit = false; if (_.isError(obj)) { console.error(obj); } else { console.error(`ERROR: ${obj.toString()}`); } if (theUfo) theUfo.disconnect(); process.exitCode = 1; }
javascript
{ "resource": "" }
q7322
train
function (...args) { let value = false; args.forEach((arg) => { if (value === false) { if (arg === true || (typeof arg === 'string' && arg.toLowerCase() === 'true') || arg === 1) { value = true; } } }); return value; }
javascript
{ "resource": "" }
q7323
train
function () { const options = {}; options.host = cli.ufo || process.env.LUFO_ADDRESS || ''; options.password = cli.password || process.env.LUFO_PASSWORD || undefined; options.localHost = cli.localHost || process.env.LUFO_LOCALHOST || undefined; options.localUdpPort = parseInt(cli.localUdpPort || process.env.LUFO_LOCAL_UDP, 10) || undefined; options.remoteUdpPort = parseInt(cli.remoteUdpPort || process.env.LUFO_REMOTE_UDP, 10) || undefined; options.localTcpPort = parseInt(cli.localTcpPort || process.env.LUFO_LOCAL_TCP, 10) || undefined; options.remoteTcpPort = parseInt(cli.remoteTcpPort || process.env.LUFO_REMOTE_TCP, 10) || undefined; options.immediate = parseBoolean(cli.immediate, process.env.LUFO_IMMEDIATE) || undefined; return options; }
javascript
{ "resource": "" }
q7324
train
function (action) { printHelpOnExit = false; const cliOptions = getOptions(); if (cliOptions.host) { if (net.isIPv4(cliOptions.host)) { theUfo = new Ufo(cliOptions); theUfo.connect() .then(action.bind(theUfo)) .catch(quitError); } else { quitError(`Invalid UFO IP address provided: ${cliOptions.host}.`); } } else { quitError('No UFO IP address provided.'); } }
javascript
{ "resource": "" }
q7325
ieInlineBlockHack
train
function ieInlineBlockHack(decl, i) { if (decl.prop == 'display' && decl.value == 'inline-block') { var reBefore = decl.raws.before.replace(reBLANK_LINE, '$1') insertDecl(decl, i, { raws: { before: reBefore }, prop: '*zoom', value: 1 }) insertDecl(decl, i, { raws: { before: reBefore }, prop: '*display', value: 'inline' }) } }
javascript
{ "resource": "" }
q7326
train
function (s2) { var self = this; return !!util.reduce(self.keys, function (v, k) { return v && self[k] === s2[k]; }, 1); }
javascript
{ "resource": "" }
q7327
train
function (event, ce) { var ret, self = this; ret = self.fn.call(self.context || ce.currentTarget, event, self.data); if (self.once) { //noinspection JSUnresolvedFunction ce.removeObserver(self); } return ret; }
javascript
{ "resource": "" }
q7328
train
function (event, ce) { var ret = this.simpleNotify(event, ce); // return false 等价 preventDefault + stopPropagation // return false 等价 preventDefault + stopPropagation if (ret === false) { event.halt(); } return ret; }
javascript
{ "resource": "" }
q7329
train
function (event, ce) { var self = this, _ksGroups = event._ksGroups; // handler's group does not match specified groups (at fire step) // handler's group does not match specified groups (at fire step) if (_ksGroups && (!self.groups || !self.groups.match(_ksGroups))) { return undef; } return self.notifyInternal(event, ce); }
javascript
{ "resource": "" }
q7330
Observable
train
function Observable(cfg) { var self = this; self.currentTarget = null; util.mix(self, cfg); self.reset(); /** * current event type * @cfg {String} type */ }
javascript
{ "resource": "" }
q7331
train
function (observer) { var self = this, i, observers = self.observers, len = observers.length; for (i = 0; i < len; i++) { if (observers[i] === observer) { observers.splice(i, 1); break; } } self.checkMemory(); }
javascript
{ "resource": "" }
q7332
train
function (observer) { var observers = this.observers, i; for (i = observers.length - 1; i >= 0; --i) { /* If multiple identical EventListeners are registered on the same EventTarget with the same parameters the duplicate instances are discarded. They do not cause the EventListener to be called twice and since they are discarded they do not need to be removed with the removeEventListener method. */ if (observer.equals(observers[i])) { return i; } } return -1; }
javascript
{ "resource": "" }
q7333
train
function (str, parseQueryString) { var m = str.match(URI_SPLIT_REG) || [], ret = {}; // old ie 7: return "" for unmatched regexp ... // old ie 7: return "" for unmatched regexp ... for (var part in REG_INFO) { ret[part] = m[REG_INFO[part]]; } if (ret.protocol) { ret.protocol = ret.protocol.toLowerCase(); } if (ret.hostname) { ret.hostname = ret.hostname.toLowerCase(); } var protocol = ret.protocol; if (protocol) { ret.slashes = str.lastIndexOf(protocol + '//') !== -1; } // mailto: yiminghe@gmail.com // mailto: yiminghe@gmail.com if (protocol && !needDoubleSlash(protocol.slice(0, -1))) { if (!ret.slashes) { str = str.slice(0, protocol.length) + '//' + str.slice(protocol.length); ret = url.parse(str, parseQueryString); ret.slashes = null; return ret; } } else { // http://www.g.cn // pathname => / if (ret.hostname && !ret.pathname) { ret.pathname = '/'; } } ret.path = ret.pathname; if (ret.search) { ret.path += ret.search; } ret.host = ret.hostname; if (ret.port) { ret.host = ret.hostname + ':' + ret.port; } if (ret.search) { ret.query = ret.search.substring(1); } if (parseQueryString && ret.query) { ret.query = querystring.parse(ret.query); } ret.href = url.format(ret); return ret; }
javascript
{ "resource": "" }
q7334
train
function (url, serializeArray) { var host = url.host; if (host === undef && url.hostname) { host = encodeURIComponent(url.hostname); if (url.port) { host += ':' + url.port; } } var search = url.search; var query = url.query; if (search === undef && query !== undef) { if (typeof query !== 'string') { query = querystring.stringify(query, undef, undef, serializeArray); } if (query) { search = '?' + query; } } if (search && search.charAt(0) !== '?') { search = '?' + search; } var hash = url.hash || ''; if (hash && hash.charAt(0) !== '#') { hash = '#' + hash; } var pathname = url.pathname || ''; var out = [], protocol, auth; if (protocol = url.protocol) { if (protocol.slice(0 - 1) !== ':') { protocol += ':'; } out.push(encodeSpecialChars(protocol, reDisallowedInProtocolOrAuth)); } if (host !== undef) { if (this.slashes || protocol && needDoubleSlash(protocol)) { out.push('//'); } if (auth = url.auth) { out.push(encodeSpecialChars(auth, reDisallowedInProtocolOrAuth)); out.push('@'); } out.push(host); } if (pathname) { out.push(encodeSpecialChars(pathname, reDisallowedInPathName)); } if (search) { out.push(search); } if (hash) { out.push('#' + encodeSpecialChars(hash.substring(1), reDisallowedInHash)); } return out.join(''); }
javascript
{ "resource": "" }
q7335
character
train
function character(options = {}) { let chars = options.chars || ['-', '*', '+']; if (typeof chars === 'string') { return fill(...chars.split('..'), options); } return chars; }
javascript
{ "resource": "" }
q7336
train
function (index) { var self = this; if (typeof index === 'number') { if (index >= self.length) { return null; } else { return new Node(self[index]); } } else { return new Node(index); } }
javascript
{ "resource": "" }
q7337
train
function (selector, context, index) { if (typeof context === 'number') { index = context; context = undefined; } var list = Node.all(selector, context).getDOMNodes(), ret = new Node(this); if (index === undefined) { push.apply(ret, list); } else { var args = [ index, 0 ]; args.push.apply(args, list); AP.splice.apply(ret, args); } return ret; }
javascript
{ "resource": "" }
q7338
train
function (fn, context) { var self = this; util.each(self, function (n, i) { n = new Node(n); return fn.call(context || n, n, i, self); }); return self; }
javascript
{ "resource": "" }
q7339
train
function (selector) { var ret, self = this; if (self.length > 0) { ret = Node.all(selector, self); } else { ret = new Node(); } ret.__parent = self; return ret; }
javascript
{ "resource": "" }
q7340
train
function (selector) { var self = this, all = self.all(selector), ret = all.length ? all.slice(0, 1) : null; if (ret) { ret.__parent = self; } return ret; }
javascript
{ "resource": "" }
q7341
train
function (selector, context) { // are we dealing with html string ? // TextNode 仍需要自己 new Node if (typeof selector === 'string' && (selector = util.trim(selector)) && selector.length >= 3 && util.startsWith(selector, '<') && util.endsWith(selector, '>')) { var attrs; if (context) { if (context.getDOMNode) { context = context[0]; } if (!context.nodeType) { attrs = context; context = arguments[2]; } } return new Node(selector, attrs, context); } return new Node(Dom.query(selector, context)); }
javascript
{ "resource": "" }
q7342
train
function (selector, context) { var all = Node.all(selector, context); return all.length ? all.slice(0, 1) : null; }
javascript
{ "resource": "" }
q7343
train
function () { var self = this, l = self.length, needClone = self.length > 1, originArgs = util.makeArray(arguments); var cfg = originArgs[0]; var AnimConstructor = Anim; if (cfg.to) { AnimConstructor = cfg.Anim || Anim; } else { cfg = originArgs[1]; if (cfg) { AnimConstructor = cfg.Anim || Anim; } } for (var i = 0; i < l; i++) { var elem = self[i]; var args = needClone ? util.clone(originArgs) : originArgs, arg0 = args[0]; if (arg0.to) { arg0.node = elem; new AnimConstructor(arg0).run(); } else { AnimConstructor.apply(undefined, [elem].concat(args)).run(); } } return self; }
javascript
{ "resource": "" }
q7344
train
function (end, clearQueue, queue) { var self = this; util.each(self, function (elem) { Anim.stop(elem, end, clearQueue, queue); }); return self; }
javascript
{ "resource": "" }
q7345
train
function (end, queue) { var self = this; util.each(self, function (elem) { Anim.pause(elem, queue); }); return self; }
javascript
{ "resource": "" }
q7346
train
function (end, queue) { var self = this; util.each(self, function (elem) { Anim.resume(elem, queue); }); return self; }
javascript
{ "resource": "" }
q7347
train
function () { var self = this; for (var i = 0; i < self.length; i++) { if (Anim.isRunning(self[i])) { return true; } } return false; }
javascript
{ "resource": "" }
q7348
train
function () { var self = this; for (var i = 0; i < self.length; i++) { if (Anim.isPaused(self[i])) { return true; } } return false; }
javascript
{ "resource": "" }
q7349
Exception
train
function Exception(attributes, cause) { this.stack = Error().stack; if (this.stack) this.stack = 'Exception' + this.stack.slice(5); // replace 'Error' with 'Exception' this.attributes = this.convert(attributes); this.message = this.attributes.getValue('$text').getValue(); this.cause = cause; return this; }
javascript
{ "resource": "" }
q7350
aggregate
train
function aggregate(transform) { switch (arguments.length) { case 1: return aggregate_seed_transform_selector.apply(this, [undefined, arguments[0]]); default: return aggregate_seed_transform_selector.apply(this, arguments); } }
javascript
{ "resource": "" }
q7351
any
train
function any(predicate) { predicate = typeof predicate === 'function' ? predicate : util.defaultPredicate; for (let item of this) { if (predicate(item)) return true; } return false; }
javascript
{ "resource": "" }
q7352
contains
train
function contains(item, equalityComparer) { equalityComparer = typeof equalityComparer === 'function' ? equalityComparer : util.defaultEqualityComparer; for (let i of this) { if (equalityComparer(i, item)) return true; } return false; }
javascript
{ "resource": "" }
q7353
count
train
function count(predicate) { predicate = typeof predicate === 'function' ? predicate : util.defaultPredicate; let c = 0; for (let item of this) { if (predicate(item)) c++; } return c; }
javascript
{ "resource": "" }
q7354
elementAt
train
function elementAt(index, defaultValue) { let i = 0; for (let item of this) { if (i === index) return item; i++; } return defaultValue; }
javascript
{ "resource": "" }
q7355
first
train
function first(predicate) { predicate = typeof predicate === 'function' ? predicate : util.defaultPredicate; let error = new Error('No element satisfies the condition in predicate.'); let firstElement = firstOrDefault.apply(this, [predicate, error]); if (firstElement === error) throw error; return firstElement; }
javascript
{ "resource": "" }
q7356
firstOrDefault
train
function firstOrDefault(predicate, defaultValue) { predicate = typeof predicate === 'function' ? predicate : util.defaultPredicate; for (let item of this) { if (predicate(item)) return item; } return defaultValue; }
javascript
{ "resource": "" }
q7357
last
train
function last(predicate, defaultValue) { predicate = typeof predicate === 'function' ? predicate : util.defaultPredicate; let lastValue; let found = false; for (let item of this.where(predicate)) { lastValue = item; found = true; } return found ? lastValue : defaultValue; }
javascript
{ "resource": "" }
q7358
max
train
function max(keySelector, comparer) { let itComparer = typeof comparer === 'function' ? comparer : util.defaultComparer; let itKeySelector = typeof keySelector === 'function' ? keySelector : (i) => i; let maximum = this.firstOrDefault(); for (let item of this) { maximum = itComparer(itKeySelector(item), itKeySelector(maximum)) > 0 ? item : maximum; } return maximum; }
javascript
{ "resource": "" }
q7359
min
train
function min(keySelector, comparer) { let itComparer = typeof comparer === 'function' ? comparer : util.defaultComparer; let itKeySelector = typeof keySelector === 'function' ? keySelector : (i) => i; let minimum = this.firstOrDefault(); for (let item of this) { minimum = itComparer(itKeySelector(item), itKeySelector(minimum)) < 0 ? item : minimum; } return minimum; }
javascript
{ "resource": "" }
q7360
sequenceEqual
train
function sequenceEqual(otherSequence, equalityComparer) { equalityComparer = typeof equalityComparer === 'function' ? equalityComparer : util.defaultEqualityComparer; let selfIterator = this[Symbol.iterator] ? this[Symbol.iterator]() : undefined; let otherIterator = otherSequence[Symbol.iterator] ? otherSequence[Symbol.iterator]() : undefined; if (toLinqable([selfIterator, otherIterator]).any(i => i === undefined)) return false; let selfItem; let otherItem; do { selfItem = selfIterator.next(); otherItem = otherIterator.next(); if (!equalityComparer(selfItem.value, otherItem.value)) return false; } while (!selfItem.done); return selfItem.done === otherItem.done; }
javascript
{ "resource": "" }
q7361
single
train
function single(predicate, defaultValue) { predicate = typeof predicate === 'function' ? predicate : util.defaultPredicate; let count = 0; let singleItem = undefined; for (let item of this) { if (predicate(item)) { if (singleItem === undefined) { singleItem = item; } else { throw new Error('More than one element satisfies the condition in predicate.'); } } count++; } if (singleItem === undefined && arguments.length == 2) return defaultValue; if (count === 0) throw new Error('The source sequence is empty.'); if (!singleItem) throw new Error('No element satisfies the condition in predicate.'); return singleItem; }
javascript
{ "resource": "" }
q7362
sum
train
function sum(transform) { let sum = 0; let seq = typeof transform === 'function' ? this.select(transform) : this; for (let item of seq) { sum += Number.parseFloat(item); } return sum; }
javascript
{ "resource": "" }
q7363
toMap
train
function toMap(keySelector, elementSelector) { if (!keySelector) return new Map(this); elementSelector = typeof elementSelector === 'function' ? elementSelector : i => i; let map = new Map(); for (let item of this) { let key = keySelector(item); let element = elementSelector(item); map.set(key, element); } return map; }
javascript
{ "resource": "" }
q7364
train
function(options) { if (!options) options = {}; this.initTime = options.initTime || new Date().getTime(); this.time_since_start = options.time_since_start || null; this.time = options.time || null; this.version = options.version || '0.45'; this.forcedUk25 = options.uk25 || null; if (options.protos) { this.ProtoSignature = options.protos.Networking.Envelopes.Signature; } else { throw new Error('Passing protos object is now mandatory.'); } this.utils = new Utils(); this.fields = { session_hash: options.session_hash || options.unk22 || crypto.randomBytes(16) }; }
javascript
{ "resource": "" }
q7365
train
function (calendar) { var time = calendar.getTime(); calendar = /**@type {KISSY.Date.Gregorian} @ignore*/ new GregorianCalendar(this.timezoneOffset, this.locale); calendar.setTime(time); var i, ret = [], pattern = this.pattern, len = pattern.length; for (i = 0; i < len; i++) { var comp = pattern[i]; if (comp.text) { ret.push(comp.text); } else if ('field' in comp) { ret.push(formatField(comp.field, comp.count, this.locale, calendar)); } } return ret.join(''); }
javascript
{ "resource": "" }
q7366
train
function (dateStr) { var calendar = /**@type {KISSY.Date.Gregorian} @ignore*/ new GregorianCalendar(this.timezoneOffset, this.locale), i, j, tmp = {}, obeyCount = false, dateStrLen = dateStr.length, errorIndex = -1, startIndex = 0, oldStartIndex = 0, pattern = this.pattern, len = pattern.length; loopPattern: { for (i = 0; errorIndex < 0 && i < len; i++) { var comp = pattern[i], text, textLen; oldStartIndex = startIndex; if (text = comp.text) { textLen = text.length; if (textLen + startIndex > dateStrLen) { errorIndex = startIndex; } else { for (j = 0; j < textLen; j++) { if (text.charAt(j) !== dateStr.charAt(j + startIndex)) { errorIndex = startIndex; break loopPattern; } } startIndex += textLen; } } else if ('field' in comp) { obeyCount = false; var nextComp = pattern[i + 1]; if (nextComp) { if ('field' in nextComp) { obeyCount = true; } else { var c = nextComp.text.charAt(0); if (c >= '0' && c <= '9') { obeyCount = true; } } } startIndex = parseField(calendar, dateStr, startIndex, comp.field, comp.count, this.locale, obeyCount, tmp); if (startIndex === oldStartIndex) { errorIndex = startIndex; } } } } if (errorIndex >= 0) { logger.error('error when parsing date'); logger.error(dateStr); logger.error(dateStr.substring(0, errorIndex) + '^'); return undefined; } return calendar; }
javascript
{ "resource": "" }
q7367
train
function (dateStyle, timeStyle, locale, timeZoneOffset) { locale = locale || defaultLocale; var datePattern = ''; if (dateStyle !== undefined) { datePattern = locale.datePatterns[dateStyle]; } var timePattern = ''; if (timeStyle !== undefined) { timePattern = locale.timePatterns[timeStyle]; } var pattern = datePattern; if (timePattern) { if (datePattern) { pattern = util.substitute(locale.dateTimePattern, { date: datePattern, time: timePattern }); } else { pattern = timePattern; } } return new DateTimeFormat(pattern, locale, timeZoneOffset); }
javascript
{ "resource": "" }
q7368
__fireAttrChange
train
function __fireAttrChange(self, when, name, prevVal, newVal, subAttrName, attrName, data) { attrName = attrName || name; return self.fire(whenAttrChangeEventName(when, name), util.mix({ attrName: attrName, subAttrName: subAttrName, prevVal: prevVal, newVal: newVal }, data)); }
javascript
{ "resource": "" }
q7369
train
function () { var self = this, o = {}, a, attrs = self.getAttrs(); for (a in attrs) { o[a] = self.get(a); } return o; }
javascript
{ "resource": "" }
q7370
train
function (name, attrConfig, override) { var self = this, attrs = self.getAttrs(), attr, // shadow clone cfg = util.merge(attrConfig); if (cfg.value && typeof cfg.value === 'object') { cfg.value = util.clone(cfg.value); LoggerManger.log('please use valueFn instead of value for ' + name + ' attribute', 'warn'); } if (attr = attrs[name]) { util.mix(attr, cfg, override); } else { attrs[name] = cfg; } return self; }
javascript
{ "resource": "" }
q7371
train
function (attrConfigs, initialValues) { var self = this; util.each(attrConfigs, function (attrConfig, name) { self.addAttr(name, attrConfig); }); if (initialValues) { self.set(initialValues); } return self; }
javascript
{ "resource": "" }
q7372
train
function (name) { var self = this; var __attrVals = getAttrVals(self); var __attrs = self.getAttrs(); if (self.hasAttr(name)) { delete __attrs[name]; delete __attrVals[name]; } return self; }
javascript
{ "resource": "" }
q7373
train
function (name, value, opts) { var self = this, e; if (typeof name !== 'string') { opts = value; opts = opts || {}; var all = Object(name), attrs = [], errors = []; for (name in all) { // bulk validation // if any one failed,all values are not set if ((e = validate(self, name, all[name], all)) !== undefined) { errors.push(e); } } if (errors.length) { if (opts.error) { opts.error(errors); } return FALSE; } for (name in all) { setInternal(self, name, all[name], opts, attrs); } var attrNames = [], prevVals = [], newVals = [], subAttrNames = []; util.each(attrs, function (attr) { prevVals.push(attr.prevVal); newVals.push(attr.newVal); attrNames.push(attr.attrName); subAttrNames.push(attr.subAttrName); }); if (attrNames.length) { __fireAttrChange(self, '', '*', prevVals, newVals, subAttrNames, attrNames, opts.data); } return self; } opts = opts || {}; // validator check // validator check e = validate(self, name, value); if (e !== undefined) { if (opts.error) { opts.error(e); } return FALSE; } return setInternal(self, name, value, opts); }
javascript
{ "resource": "" }
q7374
train
function (name, value) { var self = this, setValue, // if host does not have meta info corresponding to (name,value) // then register on demand in order to collect all data meta info // 一定要注册属性元数据,否则其他模块通过 _attrs 不能枚举到所有有效属性 // 因为属性在声明注册前可以直接设置值 attrConfig = ensureNonEmpty(self.getAttrs(), name), setter = attrConfig.setter; // if setter has effect // if setter has effect if (setter && (setter = normalFn(self, setter))) { setValue = setter.call(self, value, name); } if (setValue === INVALID) { return FALSE; } if (setValue !== undefined) { value = setValue; } // finally set // finally set getAttrVals(self)[name] = value; return undefined; }
javascript
{ "resource": "" }
q7375
train
function (name) { var self = this, dot = '.', path, attrVals = getAttrVals(self), attrConfig, getter, ret; if (name.indexOf(dot) !== -1) { path = name.split(dot); name = path.shift(); } attrConfig = ensureNonEmpty(self.getAttrs(), name, 1); getter = attrConfig.getter; // get user-set value or default value //user-set value takes privilege // get user-set value or default value //user-set value takes privilege ret = name in attrVals ? attrVals[name] : getDefAttrVal(self, name); // invoke getter for this attribute // invoke getter for this attribute if (getter && (getter = normalFn(self, getter))) { ret = getter.call(self, ret, name); } if (!(name in attrVals) && ret !== undefined) { attrVals[name] = ret; } if (path) { ret = getValueByPath(ret, path); } return ret; }
javascript
{ "resource": "" }
q7376
Text
train
function Text(value, parameters) { abstractions.Element.call(this, utilities.types.TEXT, parameters); value = value || ''; // default value // since this element is immutable the value must be read-only this.getValue = function() { return value; }; return this; }
javascript
{ "resource": "" }
q7377
_getEnvSpecificConfig
train
function _getEnvSpecificConfig () { const prodDefaults = { env: 'prod', url: null, debug: false, version: 'head', language: 'en', redisKey: 'CortinaBlock_', redisExpire: 600, redis: null, blocks: { title: '1.260060', megaMenu: '1.855134', secondaryMenu: '1.865038', image: '1.77257', footer: '1.202278', search: '1.77262', language: { 'en_UK': '1.77273', 'sv_SE': '1.272446' }, analytics: '1.464751', gtmAnalytics: '1.714097', gtmNoscript: '1.714099' } } const refDefaults = { env: 'ref', url: null, debug: false, version: 'head', language: 'en', redisKey: 'CortinaBlock_', redisExpire: 600, redis: null, blocks: { title: '1.260060', megaMenu: '1.855134', secondaryMenu: '1.865038', image: '1.77257', footer: '1.202278', search: '1.77262', language: { 'en_UK': '1.77273', 'sv_SE': '1.272446' }, analytics: '1.464751', gtmAnalytics: '1.714097', gtmNoscript: '1.714099' } } const devDefaults = { env: 'dev', url: null, debug: false, version: 'head', language: 'en', redisKey: 'CortinaBlock_', redisExpire: 600, redis: null, blocks: { title: '1.260060', megaMenu: '1.260064', secondaryMenu: '1.865038', image: '1.77257', footer: '1.202278', search: '1.77262', language: { 'en_UK': '1.77273', 'sv_SE': '1.272446' }, analytics: '1.464751', gtmAnalytics: '1.714097', gtmNoscript: '1.714099' } } const host = process.env['SERVER_HOST_URL'] const hostEnv = _getHostEnv(host) const cmhost = process.env['CM_HOST_URL'] const cmHostEnv = _getHostEnv(cmhost) // CM_HOST_URL is used when working with Azure if (cmHostEnv) { if (cmHostEnv === 'prod') { return prodDefaults } else if (cmHostEnv === 'ref') { return refDefaults } else { return devDefaults } } if (hostEnv && hostEnv === 'prod') { return prodDefaults } else if (hostEnv === 'ref') { return refDefaults } else { return devDefaults } }
javascript
{ "resource": "" }
q7378
_getHostEnv
train
function _getHostEnv (hostUrl) { if (hostUrl) { if (hostUrl.startsWith('https://www.kth')) { return 'prod' } else if (hostUrl.startsWith('https://www-r.referens.sys.kth') || hostUrl.startsWith('https://app-r.referens.sys.kth')) { return 'ref' } else if (hostUrl.startsWith('http://localhost')) { return 'dev' } else { return 'prod' } } }
javascript
{ "resource": "" }
q7379
_buildUrl
train
function _buildUrl (config, type, multi) { let url = config.url let language = _getLanguage(config.language) let block = multi ? config.blocks[type][language] : config.blocks[type] let version = _getVersion(config.version) return `${url}${block}?v=${version}&l=${language}` }
javascript
{ "resource": "" }
q7380
_getBlock
train
function _getBlock (config, type, multi) { const options = { uri: _buildUrl(config, type, multi) } if (config.headers) { options['headers'] = config.headers } return request.get(options).then(result => { return { blockName: type, result: result } }) }
javascript
{ "resource": "" }
q7381
_getAll
train
function _getAll (config) { return Promise.all( handleBlocks(config) ).then(function (results) { let result = {} results.forEach(function (block) { result[block.blockName] = block.result }) return result }) .catch(err => { var blockName = err.options ? err.options.uri : 'NO URI FOUND' log.error(`WARNING! NO BLOCKS WILL BE LOADED DUE TO ERROR IN ONE OF THE BLOCKS. FIX ALL BROKEN BLOCKS IMMEDIATELY. ATTEMPTED TO LOAD BLOCK: ${blockName}`) throw err }) }
javascript
{ "resource": "" }
q7382
handleBlocks
train
function handleBlocks (config) { let blocks = [] let blocksObj = config.blocks for (let i in blocksObj) { if (blocksObj.hasOwnProperty(i)) { if (isLanguage(blocksObj[i])) { blocks.push(_getBlock(config, 'language', true)) } else { blocks.push(_getBlock(config, i)) } } } return blocks }
javascript
{ "resource": "" }
q7383
_getRedisItem
train
function _getRedisItem (config) { let key = _buildRedisKey(config.redisKey, config.language) return config.redis.hgetallAsync(key) }
javascript
{ "resource": "" }
q7384
_setRedisItem
train
function _setRedisItem (config, blocks) { let key = _buildRedisKey(config.redisKey, config.language) return config.redis.hmsetAsync(key, blocks) .then(function () { return config.redis.expireAsync(key, config.redisExpire) }) .then(function () { return blocks }) }
javascript
{ "resource": "" }
q7385
_getEnvUrl
train
function _getEnvUrl (currentEnv, config) { if (currentEnv && config) { if (currentEnv === 'prod') { return config.urls.prod } else if (currentEnv === 'ref') { return config.urls.ref } else { return config.urls.dev } } }
javascript
{ "resource": "" }
q7386
Reserved
train
function Reserved(value, parameters) { abstractions.Element.call(this, utilities.types.RESERVED, parameters); if (!value || !/^[a-zA-Z][0-9a-zA-Z]*(-[0-9]+)?$/g.test(value)) { throw new utilities.Exception({ $module: '/bali/elements/Reserved', $procedure: '$Reserved', $exception: '$invalidParameter', $parameter: value.toString(), $text: '"An invalid reserved symbol value was passed to the constructor."' }); } // since this element is immutable the value must be read-only this.getValue = function() { return value; }; return this; }
javascript
{ "resource": "" }
q7387
Scope
train
function Scope(parent) { var map = Object.create(null); var api = {}; api.markAsUsed = function(k) { if (typeof k !== "string") { throw new Error("Scope keys must be strings: " + k); } if (api.hasOwnVar(k)) { map[k].used = true; return api; } if (parent) { return parent.markAsUsed(k); } throw new Error("tried to use a variable before declaration: " + k); }; api.ownUnusedVars = function() { return Object .keys(map) .filter(function(k) { return !map[k].used; }) .map(function(k) { return map[k]; }); }; api.get = function(k) { if (api.hasOwnVar(k)) { return map[k]; } if (parent) { return parent.get(k); } throw new Error("no such variable " + k); }; api.declare = function(k, v) { // v.line :: number // v.column :: number // v.used :: boolean // Underscore is not a valid variable, so don't put it in the scope. if (k === "_") { return api; } v.name = k; // TODO: Unbreak the linter so I can use this check. Redeclaring a variable is not ok, but it's currently happening due to hoisting. // if (api.hasOwnVar(k)) { // throw new Error("cannot redeclare variable " + k); // } if (api.hasOwnVar(k)) { v.used = api.get(k).used; } map[k] = v; return api; }; api.hasVar = function(k) { if (api.hasOwnVar(k)) { return true; } if (parent) { return parent.hasVar(k); } return false; }; api.hasOwnVar = function(k) { return {}.hasOwnProperty.call(map, k); }; api.ownVars = function() { return Object.keys(map); }; api.bareToString = function() { var innards = Object .keys(map) .map(function(k) { return k + ":" + (map[k].used ? "T" : "F"); }) .join(" "); var s = "{" + innards + "}"; if (parent) { return parent.bareToString() + " > " + s; } return s; }; api.toString = function() { return "#Scope[" + api.bareToString() + "]"; }; api.parent = parent; return Object.freeze(api); }
javascript
{ "resource": "" }
q7388
train
function (params, userId) { console.log('ecInterface.paymentmethod.add'); return this.request({ url: this._buildUri(this.uri, null, null, userId), method: corbel.request.method.POST, data: params }) .then(function (res) { return corbel.Services.getLocationId(res); }); }
javascript
{ "resource": "" }
q7389
train
function (params) { console.log('ecInterface.paymentmethod.update'); return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.PUT, data: params }) .then(function (res) { return corbel.Services.getLocationId(res); }); }
javascript
{ "resource": "" }
q7390
matchImmediate
train
function matchImmediate(el, match) { var matched = 1, startEl = el, relativeOp, startMatch = match; do { matched &= singleMatch(el, match); if (matched) { // advance match = match && match.prev; if (!match) { return true; } relativeOp = relativeExpr[match.nextCombinator]; el = dir(el, relativeOp.dir); if (!relativeOp.immediate) { return { // advance for non-immediate el: el, match: match }; } } else { relativeOp = relativeExpr[match.nextCombinator]; if (relativeOp.immediate) { // retreat but advance startEl return { el: dir(startEl, relativeExpr[startMatch.nextCombinator].dir), match: startMatch }; } else { // advance (before immediate match + jump unmatched) return { el: el && dir(el, relativeOp.dir), match: match }; } } } while (el); // only occur when match immediate // only occur when match immediate return { el: dir(startEl, relativeExpr[startMatch.nextCombinator].dir), match: startMatch }; }
javascript
{ "resource": "" }
q7391
findFixedMatchFromHead
train
function findFixedMatchFromHead(el, head) { var relativeOp, cur = head; do { if (!singleMatch(el, cur)) { return null; } cur = cur.prev; if (!cur) { return true; } relativeOp = relativeExpr[cur.nextCombinator]; el = dir(el, relativeOp.dir); } while (el && relativeOp.immediate); if (!el) { return null; } return { el: el, match: cur }; }
javascript
{ "resource": "" }
q7392
matchSubInternal
train
function matchSubInternal(el, match) { var matchImmediateRet = matchImmediate(el, match); if (matchImmediateRet === true) { return true; } else { el = matchImmediateRet.el; match = matchImmediateRet.match; while (el) { if (matchSub(el, match)) { return true; } el = dir(el, relativeExpr[match.nextCombinator].dir); } return false; } }
javascript
{ "resource": "" }
q7393
getVendorInfo
train
function getVendorInfo(name) { if (name.indexOf('-') !== -1) { name = name.replace(RE_DASH, upperCase); } if (name in vendorInfos) { return vendorInfos[name]; } // if already prefixed or need not to prefix // if already prefixed or need not to prefix if (!documentElementStyle || name in documentElementStyle) { vendorInfos[name] = { propertyName: name, propertyNamePrefix: '' }; } else { var upperFirstName = name.charAt(0).toUpperCase() + name.slice(1), vendorName; for (var i = 0; i < propertyPrefixesLength; i++) { var propertyNamePrefix = propertyPrefixes[i]; vendorName = propertyNamePrefix + upperFirstName; if (vendorName in documentElementStyle) { vendorInfos[name] = { propertyName: vendorName, propertyNamePrefix: propertyNamePrefix }; } } vendorInfos[name] = vendorInfos[name] || null; } return vendorInfos[name]; }
javascript
{ "resource": "" }
q7394
train
function () { if (isTransform3dSupported !== undefined) { return isTransform3dSupported; } if (!documentElement || !getVendorInfo('transform')) { isTransform3dSupported = false; } else { // https://gist.github.com/lorenzopolidori/3794226 // ie9 does not support 3d transform // http://msdn.microsoft.com/en-us/ie/ff468705 try { var el = doc.createElement('p'); var transformProperty = getVendorInfo('transform').propertyName; documentElement.insertBefore(el, documentElement.firstChild); el.style[transformProperty] = 'translate3d(1px,1px,1px)'; var computedStyle = win.getComputedStyle(el); var has3d = computedStyle.getPropertyValue(transformProperty) || computedStyle[transformProperty]; documentElement.removeChild(el); isTransform3dSupported = has3d !== undefined && has3d.length > 0 && has3d !== 'none'; } catch (e) { // https://github.com/kissyteam/kissy/issues/563 isTransform3dSupported = true; } } return isTransform3dSupported; }
javascript
{ "resource": "" }
q7395
JekyllUrl
train
function JekyllUrl (options) { options = options || {}; this.template = options.template; this.placeholders = options.placeholders; this.permalink = options.permalink; if (!this.template) { throw new Error('One of template or permalink must be supplied.'); } }
javascript
{ "resource": "" }
q7396
train
function (item, index) { var self = this, bar = self.get('bar'), selectedTab, tabItem, panelItem, barChildren = bar.get('children'), body = self.get('body'); if (typeof index === 'undefined') { index = barChildren.length; } tabItem = fromTabItemConfigToTabConfig(item); panelItem = { content: item.content }; bar.addChild(tabItem, index); selectedTab = barChildren[index]; body.addChild(panelItem, index); if (item.selected) { bar.set('selectedTab', selectedTab); body.set('selectedPanelIndex', index); } return self; }
javascript
{ "resource": "" }
q7397
train
function (index, destroy) { var self = this, bar = /** @ignore @type KISSY.Component.Control */ self.get('bar'), barCs = bar.get('children'), tab = bar.getChildAt(index), body = /** @ignore @type KISSY.Component.Control */ self.get('body'); if (tab.get('selected')) { if (barCs.length === 1) { bar.set('selectedTab', null); } else if (index === 0) { bar.set('selectedTab', bar.getChildAt(index + 1)); } else { bar.set('selectedTab', bar.getChildAt(index - 1)); } } bar.removeChild(bar.getChildAt(index), destroy); body.removeChild(body.getChildAt(index), destroy); return self; }
javascript
{ "resource": "" }
q7398
train
function (tab, destroy) { var index = util.indexOf(tab, this.get('bar').get('children')); return this.removeItemAt(index, destroy); }
javascript
{ "resource": "" }
q7399
train
function (panel, destroy) { var index = util.indexOf(panel, this.get('body').get('children')); return this.removeItemAt(index, destroy); }
javascript
{ "resource": "" }