_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q23300
loadCss
train
function loadCss (css, name) { if (css) { cssLoader.insertStyleElement(document, document.head, css, name, false) } }
javascript
{ "resource": "" }
q23301
ssEnabled
train
function ssEnabled () { let support = false try { window.sessionStorage.setItem('_t', 1) window.sessionStorage.removeItem('_t') support = true } catch (e) {} return support }
javascript
{ "resource": "" }
q23302
dependArray
train
function dependArray (value) { for (let e, i = 0, l = value.length; i < l; i++) { e = value[i] e && e.__ob__ && e.__ob__.dep.depend() if (Array.isArray(e)) { dependArray(e) } } }
javascript
{ "resource": "" }
q23303
train
function () { function impl (element) { customElement.call(this, element) } impl.prototype = Object.create(customElement.prototype) return impl }
javascript
{ "resource": "" }
q23304
forwardTransitionAndCreate
train
function forwardTransitionAndCreate (shell, options) { let {sourcePageId, targetPageId, targetPageMeta, onComplete} = options let loading = getLoading(targetPageMeta, {transitionContainsHeader: shell.transitionContainsHeader}) loading.classList.add('slide-enter', 'slide-enter-active') css(loading, 'display', 'block') let headerLogoTitle let fadeHeader if (!shell.transitionContainsHeader) { headerLogoTitle = document.querySelector('.mip-shell-header-wrapper .mip-shell-header-logo-title') headerLogoTitle && headerLogoTitle.classList.add('fade-out') fadeHeader = getFadeHeader(targetPageMeta) fadeHeader.classList.add('fade-enter', 'fade-enter-active') css(fadeHeader, 'display', 'block') } whenTransitionEnds(loading, 'transition', () => { loading.classList.remove('slide-enter-to', 'slide-enter-active') if (!shell.transitionContainsHeader) { fadeHeader.classList.remove('fade-enter-to', 'fade-enter-active') } hideAllIFrames() fixRootPageScroll(shell, {sourcePageId, targetPageId}) onComplete && onComplete() let iframe = getIFrame(targetPageId) css(iframe, 'z-index', activeZIndex++) shell.afterSwitchPage(options) }) nextFrame(() => { loading.classList.add('slide-enter-to') loading.classList.remove('slide-enter') if (!shell.transitionContainsHeader) { fadeHeader.classList.add('fade-enter-to') fadeHeader.classList.remove('fade-enter') } }) }
javascript
{ "resource": "" }
q23305
backwardTransitionAndCreate
train
function backwardTransitionAndCreate (shell, options) { let { targetPageId, targetPageMeta, sourcePageId, sourcePageMeta, onComplete } = options // Goto root page, resume scroll position (Only appears in backward) let rootPageScrollPosition = 0 fixRootPageScroll(shell, {targetPageId}) if (targetPageId === window.MIP.viewer.page.pageId) { rootPageScrollPosition = shell.rootPageScrollPosition } let iframe = getIFrame(sourcePageId) // If source page is root page, skip transition if (!iframe) { document.documentElement.classList.add('mip-no-scroll') window.MIP.viewer.page.getElementsInRootPage().forEach(e => e.classList.add('hide')) onComplete && onComplete() let targetIFrame = getIFrame(targetPageId) if (targetIFrame) { activeZIndex -= 2 css(targetIFrame, 'z-index', activeZIndex++) } shell.afterSwitchPage(options) return } // Moving out only needs header, not loading body let loading = getLoading(sourcePageMeta, { onlyHeader: true, transitionContainsHeader: shell.transitionContainsHeader }) let headerLogoTitle let fadeHeader if (shell.transitionContainsHeader) { css(loading, 'display', 'block') } else { headerLogoTitle = document.querySelector('.mip-shell-header-wrapper .mip-shell-header-logo-title') headerLogoTitle && headerLogoTitle.classList.add('fade-out') fadeHeader = getFadeHeader(targetPageMeta, sourcePageMeta) css(fadeHeader, 'display', 'block') } iframe.classList.add('slide-leave', 'slide-leave-active') if (shell.transitionContainsHeader) { loading.classList.add('slide-leave', 'slide-leave-active') } else { fadeHeader.classList.add('fade-enter', 'fade-enter-active') } // trigger layout and move current iframe to correct position /* eslint-disable no-unused-expressions */ css(iframe, { opacity: 1, top: rootPageScrollPosition + 'px' }) /* eslint-enable no-unused-expressions */ whenTransitionEnds(iframe, 'transition', () => { css(iframe, { display: 'none', 'z-index': 10000, top: 0 }) iframe.classList.remove('slide-leave-to', 'slide-leave-active') if (shell.transitionContainsHeader) { loading.classList.remove('slide-leave-to', 'slide-leave-active') css(loading, 'display', 'none') } else { fadeHeader.classList.remove('fade-enter-to', 'fade-enter') } onComplete && onComplete() let targetIFrame = getIFrame(targetPageId) if (targetIFrame) { activeZIndex -= 2 css(targetIFrame, 'z-index', activeZIndex++) } shell.afterSwitchPage(options) }) nextFrame(() => { iframe.classList.add('slide-leave-to') iframe.classList.remove('slide-leave') if (shell.transitionContainsHeader) { loading.classList.add('slide-leave-to') loading.classList.remove('slide-leave') } else { fadeHeader.classList.add('fade-enter-to') fadeHeader.classList.remove('fade-enter') } }) }
javascript
{ "resource": "" }
q23306
skipTransitionAndCreate
train
function skipTransitionAndCreate (shell, options) { let {sourcePageId, targetPageId, onComplete} = options hideAllIFrames() fixRootPageScroll(shell, {sourcePageId, targetPageId}) onComplete && onComplete() let iframe = getIFrame(targetPageId) css(iframe, 'z-index', activeZIndex++) shell.afterSwitchPage(options) }
javascript
{ "resource": "" }
q23307
createBaseElementProto
train
function createBaseElementProto () { if (baseElementProto) { return baseElementProto } // Base element inherits from HTMLElement let proto = Object.create(HTMLElement.prototype) /** * Created callback of MIPElement. It will initialize the element. */ proto.createdCallback = function () { // get mip1 clazz from custom elements store let CustomElement = customElementsStore.get(this.tagName, 'mip1') this.classList.add('mip-element') /** * Viewport state * @private * @type {boolean} */ this._inViewport = false /** * Whether the element is into the viewport. * @private * @type {boolean} */ this._firstInViewport = false /** * The resources object. * @private * @type {Object} */ this._resources = resources /** * Instantiated the custom element. * @type {Object} * @public */ let customElement = this.customElement = new CustomElement(this) customElement.createdCallback() // Add first-screen element to performance. if (customElement.hasResources()) { performance.addFsElement(this) } } /** * When the element is inserted into the DOM, initialize the layout and add the element to the '_resources'. */ proto.attachedCallback = function () { // Apply layout for this. this._layout = applyLayout(this) this.customElement.attachedCallback() this._resources.add(this) } /** * When the element is removed from the DOM, remove it from '_resources'. */ proto.detachedCallback = function () { this.customElement.detachedCallback() this._resources.remove(this) performance.fsElementLoaded(this) } proto.attributeChangedCallback = function (attributeName, oldValue, newValue, namespace) { let ele = this.customElement prerender.execute(() => { ele.attributeChangedCallback(...arguments) }, this) } /** * Check whether the element is in the viewport. * * @return {boolean} */ proto.inViewport = function () { return this._inViewport } /** * Called when the element enter or exit the viewport. * * @param {boolean} inViewport whether in viewport or not * And it will call the firstInviewCallback and viewportCallback of the custom element. */ proto.viewportCallback = function (inViewport) { this._inViewport = inViewport if (!this._firstInViewport) { this._firstInViewport = true this.customElement.firstInviewCallback() } this.customElement.viewportCallback(inViewport) } /** * Check whether the building callback has been executed. * * @return {boolean} */ proto.isBuilt = function () { return this._built } /** * Check whether the element need to be rendered in advance. * * @return {boolean} */ proto.prerenderAllowed = function () { return this.customElement.prerenderAllowed() } /** * Build the element and the custom element. * This will be executed only once. */ proto.build = function () { if (this.isBuilt()) { return } // Add `try ... catch` avoid the executing build list being interrupted by errors. try { this.customElement.build() this._built = true customEmit(this, 'build') } catch (e) { customEmit(this, 'build-error', e) console.error(e) } } /** * Method of executing event actions of the custom Element * * @param {Object} action event action */ proto.executeEventAction = function (action) { this.customElement.executeEventAction(action) } /** * Called by customElement. And tell the performance that element is loaded. * @deprecated */ proto.resourcesComplete = function () { performance.fsElementLoaded(this) } baseElementProto = proto return baseElementProto }
javascript
{ "resource": "" }
q23308
createMipElementProto
train
function createMipElementProto (name) { let proto = Object.create(createBaseElementProto()) proto.name = name return proto }
javascript
{ "resource": "" }
q23309
getErrorMess
train
function getErrorMess (code, name) { let mess switch (code) { case eCode.siteExceed: mess = 'storage space need less than 4k' break case eCode.lsExceed: mess = 'Uncaught DOMException: Failed to execute setItem on Storage: Setting the value of ' + name + ' exceeded the quota at ' + window.location.href } return mess }
javascript
{ "resource": "" }
q23310
matches
train
function matches (element, selector) { if (!element || element.nodeType !== 1) { return false } return nativeMatches.call(element, selector) }
javascript
{ "resource": "" }
q23311
closestTo
train
function closestTo (element, selector, target) { let closestElement = closest(element, selector) return contains(target, closestElement) ? closestElement : null }
javascript
{ "resource": "" }
q23312
create
train
function create (str) { createTmpElement.innerHTML = str if (!createTmpElement.children.length) { return null } let children = Array.prototype.slice.call(createTmpElement.children) createTmpElement.innerHTML = '' return children.length > 1 ? children : children[0] }
javascript
{ "resource": "" }
q23313
onDocumentState
train
function onDocumentState (doc, stateFn, callback) { let ready = stateFn(doc) if (ready) { callback(doc) return } const readyListener = () => { if (!stateFn(doc)) { return } if (!ready) { ready = true callback(doc) } doc.removeEventListener('readystatechange', readyListener) } doc.addEventListener('readystatechange', readyListener) }
javascript
{ "resource": "" }
q23314
insert
train
function insert (parent, children) { if (!parent || !children) { return } let nodes = Array.prototype.slice.call(children) if (nodes.length === 0) { nodes.push(children) } for (let i = 0; i < nodes.length; i++) { if (this.contains(nodes[i], parent)) { continue } if (nodes[i] !== parent && parent.appendChild) { parent.appendChild(nodes[i]) } } }
javascript
{ "resource": "" }
q23315
prefixProperty
train
function prefixProperty (property) { property = property.replace(camelReg, (match, first, char) => (first ? char : char.toUpperCase())) if (prefixCache[property]) { return prefixCache[property] } let prop if (!(property in supportElement.style)) { for (let i = 0; i < PREFIX_TYPE.length; i++) { let prefixedProp = PREFIX_TYPE[i] + property.charAt(0).toUpperCase() + property.slice(1) if (prefixedProp in supportElement.style) { prop = prefixedProp break } } } prefixCache[property] = prop || property return prefixCache[property] }
javascript
{ "resource": "" }
q23316
unitProperty
train
function unitProperty (property, value) { if (value !== +value) { return value } if (unitCache[property]) { return value + unitCache[property] } supportElement.style[property] = 0 let propValue = supportElement.style[property] let match = propValue.match && propValue.match(UNIT_REG) if (match) { return value + (unitCache[property] = match[1]) } return value }
javascript
{ "resource": "" }
q23317
isLayoutSizeDefined
train
function isLayoutSizeDefined (layout) { return ( layout === LAYOUT.FIXED || layout === LAYOUT.FIXED_HEIGHT || layout === LAYOUT.RESPONSIVE || layout === LAYOUT.FILL || layout === LAYOUT.FLEX_ITEM || layout === LAYOUT.INTRINSIC ) }
javascript
{ "resource": "" }
q23318
checkComponents
train
function checkComponents (options) { for (const key in options.components) { const lower = key.toLowerCase() if (isBuiltInTag(lower) || config.isReservedTag(lower)) { warn( 'Do not use built-in or reserved HTML elements as component ' + 'id: ' + key ) } } }
javascript
{ "resource": "" }
q23319
lastChildElement
train
function lastChildElement (parent, callback) { for (let child = parent.lastElementChild; child; child = child.previousElementSibling) { if (callback(child)) { return child } } return null }
javascript
{ "resource": "" }
q23320
isInternalNode
train
function isInternalNode (node) { let tagName = (typeof node === 'string') ? node : node.tagName if (tagName && tagName.toLowerCase().indexOf('mip-i-') === 0) { return true } if (node.tagName && (node.hasAttribute('placeholder') || node.hasAttribute('fallback') || node.hasAttribute('overflow'))) { return true } return false }
javascript
{ "resource": "" }
q23321
touchHandler
train
function touchHandler (event) { let opt = this._opt opt.preventDefault && event.preventDefault() opt.stopPropagation && event.stopPropagation() // 如果 touchstart 没有被触发(可能被子元素的 touchstart 回调触发了 stopPropagation), // 那么后续的手势将取消计算 if (event.type !== 'touchstart' && !dataProcessor.startTime) { return } let data = dataProcessor.process(event, opt.preventX, opt.preventY) this._recognize(data) this.trigger(event.type, event, data) }
javascript
{ "resource": "" }
q23322
listenersHelp
train
function listenersHelp (element, events, handler, method) { let list = events.split(' ') for (let i = 0, len = list.length; i < len; i++) { let item = list[i] if (method === false) { element.removeEventListener(item, handler) } else { element.addEventListener(item, handler, false) } } }
javascript
{ "resource": "" }
q23323
flushWatcherQueue
train
function flushWatcherQueue () { flushing = true let watcher let id queue.sort((a, b) => a.id - b.id) for (index = 0; index < queue.length; index++) { watcher = queue[index] id = watcher.id has[id] = null watcher.run() // in dev build, check and stop circular updates. if (process.env.NODE_ENV !== 'production') { circular[id] = (circular[id] || 0) + 1 if (circular[id] > MAX_UPDATE_COUNT) { console.error( `[MIP warn]:You may have an infinite update loop in watcher with expression "${watcher.exp}"` ) break } } } resetState() }
javascript
{ "resource": "" }
q23324
createEvent
train
function createEvent (type, data) { let event = document.createEvent(specialEvents[type] || 'Event') event.initEvent(type, true, true) data && (event.data = data) return event }
javascript
{ "resource": "" }
q23325
listenOnce
train
function listenOnce (element, eventType, listener, optEvtListenerOpts) { let unlisten = listen(element, eventType, event => { unlisten() listener(event) }, optEvtListenerOpts) return unlisten }
javascript
{ "resource": "" }
q23326
loadPromise
train
function loadPromise (eleOrWindow) { if (isLoaded(eleOrWindow)) { return Promise.resolve(eleOrWindow) } let loadingPromise = new Promise((resolve, reject) => { // Listen once since IE 5/6/7 fire the onload event continuously for // animated GIFs. let {tagName} = eleOrWindow if (tagName === 'AUDIO' || tagName === 'VIDEO') { listenOnce(eleOrWindow, 'loadstart', resolve) } else { listenOnce(eleOrWindow, 'load', resolve) } // For elements, unlisten on error (don't for Windows). if (tagName) { listenOnce(eleOrWindow, 'error', reject) } }) return loadingPromise }
javascript
{ "resource": "" }
q23327
ParseArea
train
function ParseArea(obj) { if (!obj) return; if (obj.areas) { for (var i in obj.areas) { AddRideName(obj.areas[i]); ParseArea(obj.areas[i]); } } if (obj.items) { for (var j in obj.items) { AddRideName(obj.items[j]); ParseArea(obj.items[j]); } } }
javascript
{ "resource": "" }
q23328
train
function(context) { var evaluate = function(rules, createRule) { var i; rules = rules || []; for (i = 0; i < rules.length; i++) { if (typeof(rules[i]) === "function") { if (rules[i](context)) { return defaultHandleToken("named-ident")(context); } } else if (createRule && createRule(rules[i])(context.tokens)) { return defaultHandleToken("named-ident")(context); } } return false; }; return evaluate(context.language.namedIdentRules.custom) || evaluate(context.language.namedIdentRules.follows, function(ruleData) { return createProceduralRule(context.index - 1, -1, ruleData, context.language.caseInsensitive); }) || evaluate(context.language.namedIdentRules.precedes, function(ruleData) { return createProceduralRule(context.index + 1, 1, ruleData, context.language.caseInsensitive); }) || evaluate(context.language.namedIdentRules.between, function(ruleData) { return createBetweenRule(context.index, ruleData.opener, ruleData.closer, context.language.caseInsensitive); }) || defaultHandleToken("ident")(context); }
javascript
{ "resource": "" }
q23329
last
train
function last(thing) { return thing.charAt ? thing.charAt(thing.length - 1) : thing[thing.length - 1]; }
javascript
{ "resource": "" }
q23330
merge
train
function merge(defaultObject, objectToMerge) { var key; if (!objectToMerge) { return defaultObject; } for (key in objectToMerge) { defaultObject[key] = objectToMerge[key]; } return defaultObject; }
javascript
{ "resource": "" }
q23331
getNextWhile
train
function getNextWhile(tokens, index, direction, matcher) { var count = 1, token; direction = direction || 1; while (token = tokens[index + (direction * count++)]) { if (!matcher(token)) { return token; } } return undefined; }
javascript
{ "resource": "" }
q23332
createHashMap
train
function createHashMap(wordMap, boundary, caseInsensitive) { //creates a hash table where the hash is the first character of the word var newMap = { }, i, word, firstChar; for (i = 0; i < wordMap.length; i++) { word = caseInsensitive ? wordMap[i].toUpperCase() : wordMap[i]; firstChar = word.charAt(0); if (!newMap[firstChar]) { newMap[firstChar] = []; } newMap[firstChar].push({ value: word, regex: new RegExp("^" + regexEscape(word) + boundary, caseInsensitive ? "i" : "") }); } return newMap; }
javascript
{ "resource": "" }
q23333
switchToEmbeddedLanguageIfNecessary
train
function switchToEmbeddedLanguageIfNecessary(context) { var i, embeddedLanguage; for (i = 0; i < context.language.embeddedLanguages.length; i++) { if (!languages[context.language.embeddedLanguages[i].language]) { //unregistered language continue; } embeddedLanguage = clone(context.language.embeddedLanguages[i]); if (embeddedLanguage.switchTo(context)) { embeddedLanguage.oldItems = clone(context.items); context.embeddedLanguageStack.push(embeddedLanguage); context.language = languages[embeddedLanguage.language]; context.items = merge(context.items, clone(context.language.contextItems)); break; } } }
javascript
{ "resource": "" }
q23334
switchBackFromEmbeddedLanguageIfNecessary
train
function switchBackFromEmbeddedLanguageIfNecessary(context) { var current = last(context.embeddedLanguageStack), lang; if (current && current.switchBack(context)) { context.language = languages[current.parentLanguage]; lang = context.embeddedLanguageStack.pop(); //restore old items context.items = clone(lang.oldItems); lang.oldItems = {}; } }
javascript
{ "resource": "" }
q23335
highlightRecursive
train
function highlightRecursive(node) { var match, languageId, currentNodeCount, j, nodes, k, partialContext, container, codeContainer; if (this.isAlreadyHighlighted(node) || (match = this.matchSunlightNode(node)) === null) { return; } languageId = match[1]; currentNodeCount = 0; fireEvent("beforeHighlightNode", this, { node: node }); for (j = 0; j < node.childNodes.length; j++) { if (node.childNodes[j].nodeType === 3) { //text nodes partialContext = highlightText.call(this, node.childNodes[j].nodeValue, languageId, partialContext); HIGHLIGHTED_NODE_COUNT++; currentNodeCount = currentNodeCount || HIGHLIGHTED_NODE_COUNT; nodes = partialContext.getNodes(); node.replaceChild(nodes[0], node.childNodes[j]); for (k = 1; k < nodes.length; k++) { node.insertBefore(nodes[k], nodes[k - 1].nextSibling); } } else if (node.childNodes[j].nodeType === 1) { //element nodes highlightRecursive.call(this, node.childNodes[j]); } } //indicate that this node has been highlighted node.className += " " + this.options.classPrefix + "highlighted"; //if the node is block level, we put it in a container, otherwise we just leave it alone if (getComputedStyle(node, "display") === "block") { container = document.createElement("div"); container.className = this.options.classPrefix + "container"; codeContainer = document.createElement("div"); codeContainer.className = this.options.classPrefix + "code-container"; //apply max height if specified in options if (this.options.maxHeight !== false) { codeContainer.style.overflowY = "auto"; codeContainer.style.maxHeight = this.options.maxHeight + (/^\d+$/.test(this.options.maxHeight) ? "px" : ""); } container.appendChild(codeContainer); node.parentNode.insertBefore(codeContainer, node); node.parentNode.removeChild(node); codeContainer.appendChild(node); codeContainer.parentNode.insertBefore(container, codeContainer); codeContainer.parentNode.removeChild(codeContainer); container.appendChild(codeContainer); } fireEvent("afterHighlightNode", this, { container: container, codeContainer: codeContainer, node: node, count: currentNodeCount }); }
javascript
{ "resource": "" }
q23336
train
function (attr) { if (attr.indexOf('{attribution.') === -1) { return attr; } return attr.replace(/\{attribution.(\w*)\}/, function (match, attributionName) { return attributionReplacer(providers[attributionName].options.attribution); } ); }
javascript
{ "resource": "" }
q23337
train
function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) { return (p2.y - p.y) * (p1.x - p.x) > (p1.y - p.y) * (p2.x - p.x); }
javascript
{ "resource": "" }
q23338
train
function (p, p1, maxIndex, minIndex) { var points = this._originalPoints, p2, p3; minIndex = minIndex || 0; // Check all previous line segments (beside the immediately previous) for intersections for (var j = maxIndex; j > minIndex; j--) { p2 = points[j - 1]; p3 = points[j]; if (L.LineUtil.segmentsIntersect(p, p1, p2, p3)) { return true; } } return false; }
javascript
{ "resource": "" }
q23339
train
function (handler) { return [ { enabled: handler.deleteLastVertex, title: L.drawLocal.draw.toolbar.undo.title, text: L.drawLocal.draw.toolbar.undo.text, callback: handler.deleteLastVertex, context: handler }, { title: L.drawLocal.draw.toolbar.actions.title, text: L.drawLocal.draw.toolbar.actions.text, callback: this.disable, context: this } ]; }
javascript
{ "resource": "" }
q23340
train
function (providerName) { if (providerName === 'ignored') { return true; } // reduce the number of layers previewed for some providers if (providerName.startsWith('HERE') || providerName.startsWith('OpenWeatherMap') || providerName.startsWith('MapBox')) { var whitelist = [ // API threshold almost reached, disabling for now. // 'HERE.normalDay', 'OpenWeatherMap.Clouds', 'OpenWeatherMap.Pressure', 'OpenWeatherMap.Wind' ]; return whitelist.indexOf(providerName) === -1; } return false; }
javascript
{ "resource": "" }
q23341
compile
train
function compile(content, data) { return content.replace(/\${(\w+)}/gi, function (match, name) { return data[name] ? data[name] : ''; }); }
javascript
{ "resource": "" }
q23342
getFilePath
train
function getFilePath(sourcePath, filename, subDir) { if (subDir === void 0) { subDir = ''; } var filePath = filename .replace(path.resolve(sourcePath), '') .replace(path.basename(filename), ''); if (subDir) { filePath = filePath.replace(subDir + path.sep, ''); } if (/^[\/\\]/.test(filePath)) { filePath = filePath.substr(1); } return filePath.replace(/\\/g, '/'); }
javascript
{ "resource": "" }
q23343
generateIndex
train
function generateIndex(opts, files, subDir) { if (subDir === void 0) { subDir = ''; } var shouldExport = opts.export; var isES6 = opts.es6; var content = ''; var dirMap = {}; switch (opts.ext) { case 'js': content += '/* eslint-disable */\n'; break; case 'ts': content += '/* tslint:disable */\n'; break; } files.forEach(function (file) { var name = path.basename(file).split('.')[0]; var filePath = getFilePath(opts.sourcePath, file, subDir); var dir = filePath.split('/')[0]; if (dir) { if (!dirMap[dir]) { dirMap[dir] = []; if (shouldExport) { var dirName = camelcase_1.default(dir, { pascalCase: true }); content += isES6 ? "export * as " + dirName + " from './" + dir + "'\n" : "module.exports." + dirName + " = require('./" + dir + "')\n"; } else { content += isES6 ? "import './" + dir + "'\n" : "require('./" + dir + "')\n"; } } dirMap[dir].push(file); } else { if (shouldExport) { var fileName = camelcase_1.default(name, { pascalCase: true }); content += isES6 ? "export " + fileName + " from './" + filePath + name + "'\n" : "module.exports." + fileName + " = require('./" + filePath + name + "')\n"; } else { content += isES6 ? "import './" + filePath + name + "'\n" : "require('./" + filePath + name + "')\n"; } } }); fs.writeFileSync(path.join(opts.targetPath, subDir, "index." + opts.ext), content, 'utf-8'); console.log(colors.green("Generated " + (subDir ? subDir + path.sep : '') + "index." + opts.ext)); // generate subDir index.js for (var dir in dirMap) { generateIndex(opts, dirMap[dir], path.join(subDir, dir)); } }
javascript
{ "resource": "" }
q23344
getSvgoConfig
train
function getSvgoConfig(svgo) { if (!svgo) { return require('../../default/svgo'); } else if (typeof svgo === 'string') { return require(path.join(process.cwd(), svgo)); } else { return svgo; } }
javascript
{ "resource": "" }
q23345
getViewBox
train
function getViewBox(svgoResult) { var viewBoxMatch = svgoResult.data.match(/viewBox="([-\d\.]+\s[-\d\.]+\s[-\d\.]+\s[-\d\.]+)"/); var viewBox = '0 0 200 200'; if (viewBoxMatch && viewBoxMatch.length > 1) { viewBox = viewBoxMatch[1]; } else if (svgoResult.info.height && svgoResult.info.width) { viewBox = "0 0 " + svgoResult.info.width + " " + svgoResult.info.height; } return viewBox; }
javascript
{ "resource": "" }
q23346
addPid
train
function addPid(content) { var shapeReg = /<(path|rect|circle|polygon|line|polyline|ellipse)\s/gi; var id = 0; content = content.replace(shapeReg, function (match) { return match + ("pid=\"" + id++ + "\" "); }); return content; }
javascript
{ "resource": "" }
q23347
getHtmlInfo
train
function getHtmlInfo(element) { if (!element) return null; var tagName = element.tagName; if (!tagName) return null; tagName = tagName.toUpperCase(); var infos = axs.constants.TAG_TO_IMPLICIT_SEMANTIC_INFO[tagName]; if (!infos || !infos.length) return null; var defaultInfo = null; // will contain the info with no specific selector if no others match for (var i = 0, len = infos.length; i < len; i++) { var htmlInfo = infos[i]; if (htmlInfo.selector) { if (axs.browserUtils.matchSelector(element, htmlInfo.selector)) return htmlInfo; } else { defaultInfo = htmlInfo; } } return defaultInfo; }
javascript
{ "resource": "" }
q23348
getRequired
train
function getRequired(element) { var elementRole = axs.utils.getRoles(element); if (!elementRole || !elementRole.applied) return []; var appliedRole = elementRole.applied; if (!appliedRole.valid) return []; return appliedRole.details['mustcontain'] || []; }
javascript
{ "resource": "" }
q23349
tableDoesNotHaveHeaderRow
train
function tableDoesNotHaveHeaderRow(rows) { var headerRow = rows[0]; var headerCells = headerRow.children; for (var i = 0; i < headerCells.length; i++) { if (headerCells[i].tagName != 'TH') { return true; } } return false; }
javascript
{ "resource": "" }
q23350
tableDoesNotHaveHeaderColumn
train
function tableDoesNotHaveHeaderColumn(rows) { for (var i = 0; i < rows.length; i++) { if (rows[i].children[0].tagName != 'TH') { return true; } } return false; }
javascript
{ "resource": "" }
q23351
tableDoesNotHaveGridLayout
train
function tableDoesNotHaveGridLayout(rows) { var headerCells = rows[0].children; for (var i = 1; i < headerCells.length; i++) { if (headerCells[i].tagName != 'TH') { return true; } } for (var i = 1; i < rows.length; i++) { if (rows[i].children[0].tagName != 'TH') { return true; } } return false; }
javascript
{ "resource": "" }
q23352
isLayoutTable
train
function isLayoutTable(element) { if (element.childElementCount == 0) { return true; } if (element.hasAttribute('role') && element.getAttribute('role') != 'presentation') { return false; } if (element.getAttribute('role') == 'presentation') { var tableChildren = element.querySelectorAll('*') // layout tables should only contain TR and TD elements for (var i = 0; i < tableChildren.length; i++) { if (tableChildren[i].tagName != 'TR' && tableChildren[i].tagName != 'TD') { return false; } } return true; } return false; }
javascript
{ "resource": "" }
q23353
hasDirectTextDescendantXpath
train
function hasDirectTextDescendantXpath() { var selectorResults = ownerDocument.evaluate(axs.properties.TEXT_CONTENT_XPATH, element, null, XPathResult.ANY_TYPE, null); for (var resultElement = selectorResults.iterateNext(); resultElement != null; resultElement = selectorResults.iterateNext()) { if (resultElement !== element) continue; return true; } return false; }
javascript
{ "resource": "" }
q23354
train
function(auditRuleName, selectors) { if (!(auditRuleName in this.rules_)) this.rules_[auditRuleName] = {}; if (!('ignore' in this.rules_[auditRuleName])) this.rules_[auditRuleName].ignore = []; Array.prototype.push.call(this.rules_[auditRuleName].ignore, selectors); }
javascript
{ "resource": "" }
q23355
train
function(auditRuleName, severity) { if (!(auditRuleName in this.rules_)) this.rules_[auditRuleName] = {}; this.rules_[auditRuleName].severity = severity; }
javascript
{ "resource": "" }
q23356
train
function(auditRuleName, config) { if (!(auditRuleName in this.rules_)) this.rules_[auditRuleName] = {}; this.rules_[auditRuleName].config = config; }
javascript
{ "resource": "" }
q23357
train
function(auditRuleName) { if (!(auditRuleName in this.rules_)) return null; if (!('config' in this.rules_[auditRuleName])) return null; return this.rules_[auditRuleName].config; }
javascript
{ "resource": "" }
q23358
labeledByATab
train
function labeledByATab(element) { if (element.hasAttribute('aria-labelledby')) { var labelingElements = document.querySelectorAll('#' + element.getAttribute('aria-labelledby')); return labelingElements.length === 1 && labelingElements[0].getAttribute('role') === 'tab'; } return false; }
javascript
{ "resource": "" }
q23359
controlledByATab
train
function controlledByATab(element) { var controlledBy = document.querySelectorAll('[role="tab"][aria-controls="' + element.id + '"]') return element.id && (controlledBy.length === 1); }
javascript
{ "resource": "" }
q23360
arrowFnToNormalFn
train
function arrowFnToNormalFn(string) { var match = string.match(/^([\s\S]+?)=\>(\s*{)?([\s\S]*?)(}\s*)?$/); if (!match) { return string; } var args = match[1]; var body = match[3]; var needsReturn = !(match[2] && match[4]); args = args.replace(/^(\s*\(\s*)([\s\S]*?)(\s*\)\s*)$/, '$2'); if (needsReturn) { body = 'return ' + body; } return 'function(' + args + ') {' + body + '}'; }
javascript
{ "resource": "" }
q23361
extend
train
function extend(filename, async) { if (async._waterfall !== undefined) { return; } async._waterfall = async.waterfall; async.waterfall = function (_tasks, callback) { let tasks = _tasks.map(function (t) { let fn = function () { console.log("async " + filename + ": " + t.name); t.apply(t, arguments); }; return fn; }); async._waterfall(tasks, callback); }; }
javascript
{ "resource": "" }
q23362
worker
train
function worker(message) { console.log(`Processing "${message.message.data}"...`); setTimeout(() => { console.log(`Finished procesing "${message.message.data}".`); isProcessed = true; }, 30000); }
javascript
{ "resource": "" }
q23363
setGlobalEval
train
function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } }
javascript
{ "resource": "" }
q23364
signalKill
train
function signalKill(childProcess, callback) { childProcess.emit('signalKill'); if (IS_WINDOWS) { const taskkill = spawn('taskkill', ['/F', '/T', '/PID', childProcess.pid]); taskkill.on('exit', (exitStatus) => { if (exitStatus) { return callback( new Error(`Unable to forcefully terminate process ${childProcess.pid}`) ); } callback(); }); } else { childProcess.kill('SIGKILL'); process.nextTick(callback); } }
javascript
{ "resource": "" }
q23365
signalTerm
train
function signalTerm(childProcess, callback) { childProcess.emit('signalTerm'); if (IS_WINDOWS) { // On Windows, there is no such way as SIGTERM or SIGINT. The closest // thing is to interrupt the process with Ctrl+C. Under the hood, that // generates '\u0003' character on stdin of the process and if // the process listens on stdin, it's able to catch this as 'SIGINT'. // // However, that only works if user does it manually. There is no // way to do it programmatically, at least not in Node.js (and even // for C/C++, all the solutions are dirty hacks). Even if you send // the very same character to stdin of the process, it's not // recognized (the rl.on('SIGINT') event won't get triggered) // for some reason. // // The only thing Dredd is left with is a convention. So when Dredd // wants to gracefully signal to the child process it should terminate, // it sends the '\u0003' to stdin of the child. It's up to the child // to implement reading from stdin in such way it works both for // programmatic and manual Ctrl+C. childProcess.stdin.write(String.fromCharCode(ASCII_CTRL_C)); } else { childProcess.kill('SIGTERM'); } process.nextTick(callback); }
javascript
{ "resource": "" }
q23366
check
train
function check() { if (terminated) { // Successfully terminated clearTimeout(t); return callback(); } if ((Date.now() - start) < timeout) { // Still not terminated, try again signalTerm(childProcess, (err) => { if (err) { return callback(err); } t = setTimeout(check, retryDelay); }); } else { // Still not terminated and the timeout has passed, either // kill the process (force) or provide an error clearTimeout(t); if (force) { signalKill(childProcess, callback); } else { callback( new Error(`Unable to gracefully terminate process ${childProcess.pid}`) ); } } }
javascript
{ "resource": "" }
q23367
applyLoggingOptions
train
function applyLoggingOptions(config) { if (config.color === false) { logger.transports.console.colorize = false; reporterOutputLogger.transports.console.colorize = false; } // TODO https://github.com/apiaryio/dredd/issues/1346 if (config.loglevel) { const loglevel = config.loglevel.toLowerCase(); if (loglevel === 'silent') { logger.transports.console.silent = true; } else if (loglevel === 'warning') { logger.transports.console.level = 'warn'; } else if (loglevel === 'debug') { logger.transports.console.level = 'debug'; logger.transports.console.timestamp = true; } else if (['warn', 'error'].includes(loglevel)) { logger.transports.console.level = loglevel; } else { logger.transports.console.level = 'warn'; throw new Error(`The logging level '${loglevel}' is unsupported, ` + 'supported are: silent, error, warning, debug'); } } else { logger.transports.console.level = 'warn'; } }
javascript
{ "resource": "" }
q23368
performRequest
train
function performRequest(uri, transactionReq, options, callback) { if (typeof options === 'function') { [options, callback] = [{}, options]; } const logger = options.logger || defaultLogger; const request = options.request || defaultRequest; const httpOptions = Object.assign({}, options.http || {}); httpOptions.proxy = false; httpOptions.followRedirect = false; httpOptions.encoding = null; httpOptions.method = transactionReq.method; httpOptions.uri = uri; try { httpOptions.body = getBodyAsBuffer(transactionReq.body, transactionReq.bodyEncoding); httpOptions.headers = normalizeContentLengthHeader(transactionReq.headers, httpOptions.body); const protocol = httpOptions.uri.split(':')[0].toUpperCase(); logger.debug(`Performing ${protocol} request to the server under test: ` + `${httpOptions.method} ${httpOptions.uri}`); request(httpOptions, (error, response, responseBody) => { logger.debug(`Handling ${protocol} response from the server under test`); if (error) { callback(error); } else { callback(null, createTransactionResponse(response, responseBody)); } }); } catch (error) { process.nextTick(() => callback(error)); } }
javascript
{ "resource": "" }
q23369
getBodyAsBuffer
train
function getBodyAsBuffer(body, encoding) { return body instanceof Buffer ? body : Buffer.from(`${body || ''}`, normalizeBodyEncoding(encoding)); }
javascript
{ "resource": "" }
q23370
normalizeContentLengthHeader
train
function normalizeContentLengthHeader(headers, body, options = {}) { const logger = options.logger || defaultLogger; const modifiedHeaders = Object.assign({}, headers); const calculatedValue = Buffer.byteLength(body); const name = caseless(modifiedHeaders).has('Content-Length'); if (name) { const value = parseInt(modifiedHeaders[name], 10); if (value !== calculatedValue) { modifiedHeaders[name] = `${calculatedValue}`; logger.warn(`Specified Content-Length header is ${value}, but the real ` + `body length is ${calculatedValue}. Using ${calculatedValue} instead.`); } } else { modifiedHeaders['Content-Length'] = `${calculatedValue}`; } return modifiedHeaders; }
javascript
{ "resource": "" }
q23371
createTransactionResponse
train
function createTransactionResponse(response, body) { const transactionRes = { statusCode: response.statusCode, headers: Object.assign({}, response.headers), }; if (Buffer.byteLength(body || '')) { transactionRes.bodyEncoding = detectBodyEncoding(body); transactionRes.body = body.toString(transactionRes.bodyEncoding); } return transactionRes; }
javascript
{ "resource": "" }
q23372
train
function(evt) { var li = evt.target; if (li !== this) { while (li && !/li/i.test(li.nodeName)) { li = li.parentNode; } if (li && evt.button === 0) { // Only select on left click evt.preventDefault(); me.select(li, evt.target, evt); } } }
javascript
{ "resource": "" }
q23373
train
function (i) { var lis = this.ul.children; if (this.selected) { lis[this.index].setAttribute("aria-selected", "false"); } this.index = i; if (i > -1 && lis.length > 0) { lis[i].setAttribute("aria-selected", "true"); this.status.textContent = lis[i].textContent + ", list item " + (i + 1) + " of " + lis.length; this.input.setAttribute("aria-activedescendant", this.ul.id + "_item_" + this.index); // scroll to highlighted element in case parent's height is fixed this.ul.scrollTop = lis[i].offsetTop - this.ul.clientHeight + lis[i].clientHeight; $.fire(this.input, "awesomplete-highlight", { text: this.suggestions[this.index] }); } }
javascript
{ "resource": "" }
q23374
determineTitle
train
function determineTitle(title, notitle, lines, info) { var defaultTitle = '**Table of Contents** *generated with [DocToc](https://github.com/thlorenz/doctoc)*'; if (notitle) return ''; if (title) return title; return info.hasStart ? lines[info.startIdx + 2] : defaultTitle; }
javascript
{ "resource": "" }
q23375
train
function (element, closeAll) { var expanded = typeof closeAll !== 'undefined' ? closeAll : childRulesExpanded(element); if (expanded) { element.textContent = 'close all'; element.classList.remove('closed'); element.classList.add('expanded'); } else { element.textContent = 'expand all'; element.classList.remove('expanded'); element.classList.add('closed'); } }
javascript
{ "resource": "" }
q23376
resolveOrigin
train
function resolveOrigin(url) { var a = document.createElement('a'); a.href = url; var protocol = a.protocol.length > 4 ? a.protocol : window.location.protocol; var host = a.host.length ? a.port === '80' || a.port === '443' ? a.hostname : a.host : window.location.host; return a.origin || protocol + "//" + host; }
javascript
{ "resource": "" }
q23377
resolveValue
train
function resolveValue(model, property) { var unwrappedContext = typeof model[property] === 'function' ? model[property]() : model[property]; return Postmate.Promise.resolve(unwrappedContext); }
javascript
{ "resource": "" }
q23378
Postmate
train
function Postmate(_ref2) { var _ref2$container = _ref2.container, container = _ref2$container === void 0 ? typeof container !== 'undefined' ? container : document.body : _ref2$container, model = _ref2.model, url = _ref2.url, _ref2$classListArray = _ref2.classListArray, classListArray = _ref2$classListArray === void 0 ? [] : _ref2$classListArray; // eslint-disable-line no-undef this.parent = window; this.frame = document.createElement('iframe'); this.frame.classList.add.apply(this.frame.classList, classListArray); container.appendChild(this.frame); this.child = this.frame.contentWindow || this.frame.contentDocument.parentWindow; this.model = model || {}; return this.sendHandshake(url); }
javascript
{ "resource": "" }
q23379
Model
train
function Model(model) { this.child = window; this.model = model; this.parent = this.child.parent; return this.sendHandshakeReply(); }
javascript
{ "resource": "" }
q23380
train
function(profileDataGridNode) { if (!profileDataGridNode) return; this.save(); var currentNode = profileDataGridNode; var focusNode = profileDataGridNode; while (currentNode.parent && (currentNode instanceof WebInspector.ProfileDataGridNode)) { currentNode._takePropertiesFromProfileDataGridNode(profileDataGridNode); focusNode = currentNode; currentNode = currentNode.parent; if (currentNode instanceof WebInspector.ProfileDataGridNode) currentNode._keepOnlyChild(focusNode); } this.children = [focusNode]; this.totalTime = profileDataGridNode.totalTime; }
javascript
{ "resource": "" }
q23381
train
function() { if (!this._totalSize) { this._totalSize = this._isVertical ? this.contentElement.offsetWidth : this.contentElement.offsetHeight; this._totalSizeOtherDimension = this._isVertical ? this.contentElement.offsetHeight : this.contentElement.offsetWidth; } return this._totalSize * WebInspector.zoomManager.zoomFactor(); }
javascript
{ "resource": "" }
q23382
train
function(dipWidth, dipHeight, scale) { this._scale = scale; this._dipWidth = dipWidth ? Math.max(dipWidth, 1) : 0; this._dipHeight = dipHeight ? Math.max(dipHeight, 1) : 0; this._updateUI(); }
javascript
{ "resource": "" }
q23383
typeWeight
train
function typeWeight(treeElement) { var type = treeElement.type(); if (type === WebInspector.NavigatorTreeOutline.Types.Domain) { if (treeElement.titleText === WebInspector.targetManager.inspectedPageDomain()) return 1; return 2; } if (type === WebInspector.NavigatorTreeOutline.Types.FileSystem) return 3; if (type === WebInspector.NavigatorTreeOutline.Types.Folder) return 4; return 5; }
javascript
{ "resource": "" }
q23384
buildInspectorUrl
train
function buildInspectorUrl(inspectorHost, inspectorPort, debugPort, isHttps) { var host = inspectorHost == '0.0.0.0' ? '127.0.0.1' : inspectorHost; var port = inspectorPort; var protocol = isHttps ? 'https' : 'http'; var isUnixSocket = !/^\d+$/.test(port); if (isUnixSocket) { host = path.resolve(__dirname, inspectorPort); port = null; protocol = 'unix'; } var parts = { protocol: protocol, hostname: host, port: port, pathname: '/', search: '?port=' + debugPort }; return url.format(parts); }
javascript
{ "resource": "" }
q23385
buildWebSocketUrl
train
function buildWebSocketUrl(inspectorHost, inspectorPort, debugPort, isSecure) { var parts = { protocol: isSecure ? 'wss:' : 'ws:', hostname: inspectorHost == '0.0.0.0' ? '127.0.0.1' : inspectorHost, port: inspectorPort, pathname: '/', search: '?port=' + debugPort, slashes: true }; return url.format(parts); }
javascript
{ "resource": "" }
q23386
train
function() { if (!this._searchResults || !this._searchResults.length) return; var index = this._selectedSearchResult ? this._searchResults.indexOf(this._selectedSearchResult) : -1; this._jumpToSearchResult(index + 1); }
javascript
{ "resource": "" }
q23387
getSelectorFromElement
train
function getSelectorFromElement($element) { var selector = $element.data('target'), $selector = void 0; if (!selector) { selector = $element.attr('href') || ''; selector = /^#[a-z]/i.test(selector) ? selector : null; } $selector = $(selector); if ($selector.length === 0) { return $selector; } if (!$selector.data(DateTimePicker.DATA_KEY)) { $.extend({}, $selector.data(), $(this).data()); } return $selector; }
javascript
{ "resource": "" }
q23388
pass1
train
function pass1(elem) { xs[elem] = blockG.inEdges(elem).reduce(function(acc, e) { return Math.max(acc, xs[e.v] + blockG.edge(e)); }, 0); }
javascript
{ "resource": "" }
q23389
pass2
train
function pass2(elem) { var min = blockG.outEdges(elem).reduce(function(acc, e) { return Math.min(acc, xs[e.w] - blockG.edge(e)); }, Number.POSITIVE_INFINITY); var node = g.node(elem); if (min !== Number.POSITIVE_INFINITY && node.borderType !== borderType) { xs[elem] = Math.max(xs[elem], min); } }
javascript
{ "resource": "" }
q23390
train
function () { this.worker = new Worker('./js/optimizer-worker.js') this.worker.onmessage = function (event) { switch (event.data.command) { case 'optimized': Optimizer.oncomplete(event.data.id, event.data.output, event.data.saved) } } this.worker.onerror = function (event) { console.error(event) } }
javascript
{ "resource": "" }
q23391
checkFrames
train
function checkFrames(frames){ var width = frames[0].width, height = frames[0].height, duration = frames[0].duration; for(var i = 1; i < frames.length; i++){ if(frames[i].width != width) throw "Frame " + (i + 1) + " has a different width"; if(frames[i].height != height) throw "Frame " + (i + 1) + " has a different height"; if(frames[i].duration < 0 || frames[i].duration > 0x7fff) throw "Frame " + (i + 1) + " has a weird duration (must be between 0 and 32767)"; duration += frames[i].duration; } return { duration: duration, width: width, height: height }; }
javascript
{ "resource": "" }
q23392
parseWebP
train
function parseWebP(riff){ var VP8 = riff.RIFF[0].WEBP[0]; var frame_start = VP8.indexOf('\x9d\x01\x2a'); //A VP8 keyframe starts with the 0x9d012a header for(var i = 0, c = []; i < 4; i++) c[i] = VP8.charCodeAt(frame_start + 3 + i); var width, horizontal_scale, height, vertical_scale, tmp; //the code below is literally copied verbatim from the bitstream spec tmp = (c[1] << 8) | c[0]; width = tmp & 0x3FFF; horizontal_scale = tmp >> 14; tmp = (c[3] << 8) | c[2]; height = tmp & 0x3FFF; vertical_scale = tmp >> 14; return { width: width, height: height, data: VP8, riff: riff } }
javascript
{ "resource": "" }
q23393
decodeBase64WebPDataURL
train
function decodeBase64WebPDataURL(url) { if (typeof url !== "string" || !url.match(/^data:image\/webp;base64,/i)) { return false; } return window.atob(url.substring("data:image\/webp;base64,".length)); }
javascript
{ "resource": "" }
q23394
renderAsWebP
train
function renderAsWebP(canvas, quality) { var frame = canvas.toDataURL('image/webp', {quality: quality}); return decodeBase64WebPDataURL(frame); }
javascript
{ "resource": "" }
q23395
writeEBML
train
function writeEBML(buffer, bufferFileOffset, ebml) { // Is the ebml an array of sibling elements? if (Array.isArray(ebml)) { for (var i = 0; i < ebml.length; i++) { writeEBML(buffer, bufferFileOffset, ebml[i]); } // Is this some sort of raw data that we want to write directly? } else if (typeof ebml === "string") { buffer.writeString(ebml); } else if (ebml instanceof Uint8Array) { buffer.writeBytes(ebml); } else if (ebml.id){ // We're writing an EBML element ebml.offset = buffer.pos + bufferFileOffset; buffer.writeUnsignedIntBE(ebml.id); // ID field // Now we need to write the size field, so we must know the payload size: if (Array.isArray(ebml.data)) { // Writing an array of child elements. We won't try to measure the size of the children up-front var sizePos, dataBegin, dataEnd; if (ebml.size === -1) { // Write the reserved all-one-bits marker to note that the size of this element is unknown/unbounded buffer.writeByte(0xFF); } else { sizePos = buffer.pos; /* Write a dummy size field to overwrite later. 4 bytes allows an element maximum size of 256MB, * which should be plenty (we don't want to have to buffer that much data in memory at one time * anyway!) */ buffer.writeBytes([0, 0, 0, 0]); } dataBegin = buffer.pos; ebml.dataOffset = dataBegin + bufferFileOffset; writeEBML(buffer, bufferFileOffset, ebml.data); if (ebml.size !== -1) { dataEnd = buffer.pos; ebml.size = dataEnd - dataBegin; buffer.seek(sizePos); buffer.writeEBMLVarIntWidth(ebml.size, 4); // Size field buffer.seek(dataEnd); } } else if (typeof ebml.data === "string") { buffer.writeEBMLVarInt(ebml.data.length); // Size field ebml.dataOffset = buffer.pos + bufferFileOffset; buffer.writeString(ebml.data); } else if (typeof ebml.data === "number") { // Allow the caller to explicitly choose the size if they wish by supplying a size field if (!ebml.size) { ebml.size = buffer.measureUnsignedInt(ebml.data); } buffer.writeEBMLVarInt(ebml.size); // Size field ebml.dataOffset = buffer.pos + bufferFileOffset; buffer.writeUnsignedIntBE(ebml.data, ebml.size); } else if (ebml.data instanceof EBMLFloat64) { buffer.writeEBMLVarInt(8); // Size field ebml.dataOffset = buffer.pos + bufferFileOffset; buffer.writeDoubleBE(ebml.data.value); } else if (ebml.data instanceof EBMLFloat32) { buffer.writeEBMLVarInt(4); // Size field ebml.dataOffset = buffer.pos + bufferFileOffset; buffer.writeFloatBE(ebml.data.value); } else if (ebml.data instanceof Uint8Array) { buffer.writeEBMLVarInt(ebml.data.byteLength); // Size field ebml.dataOffset = buffer.pos + bufferFileOffset; buffer.writeBytes(ebml.data); } else { throw "Bad EBML datatype " + typeof ebml.data; } } else { throw "Bad EBML datatype " + typeof ebml.data; } }
javascript
{ "resource": "" }
q23396
createSeekHead
train
function createSeekHead() { var seekPositionEBMLTemplate = { "id": 0x53AC, // SeekPosition "size": 5, // Allows for 32GB video files "data": 0 // We'll overwrite this when the file is complete }, result = { "id": 0x114D9B74, // SeekHead "data": [] }; for (var name in seekPoints) { var seekPoint = seekPoints[name]; seekPoint.positionEBML = Object.create(seekPositionEBMLTemplate); result.data.push({ "id": 0x4DBB, // Seek "data": [ { "id": 0x53AB, // SeekID "data": seekPoint.id }, seekPoint.positionEBML ] }); } return result; }
javascript
{ "resource": "" }
q23397
writeHeader
train
function writeHeader() { seekHead = createSeekHead(); var ebmlHeader = { "id": 0x1a45dfa3, // EBML "data": [ { "id": 0x4286, // EBMLVersion "data": 1 }, { "id": 0x42f7, // EBMLReadVersion "data": 1 }, { "id": 0x42f2, // EBMLMaxIDLength "data": 4 }, { "id": 0x42f3, // EBMLMaxSizeLength "data": 8 }, { "id": 0x4282, // DocType "data": "webm" }, { "id": 0x4287, // DocTypeVersion "data": 2 }, { "id": 0x4285, // DocTypeReadVersion "data": 2 } ] }, segmentInfo = { "id": 0x1549a966, // Info "data": [ { "id": 0x2ad7b1, // TimecodeScale "data": 1e6 // Times will be in miliseconds (1e6 nanoseconds per step = 1ms) }, { "id": 0x4d80, // MuxingApp "data": "webm-writer-js", }, { "id": 0x5741, // WritingApp "data": "webm-writer-js" }, segmentDuration // To be filled in later ] }, tracks = { "id": 0x1654ae6b, // Tracks "data": [ { "id": 0xae, // TrackEntry "data": [ { "id": 0xd7, // TrackNumber "data": DEFAULT_TRACK_NUMBER }, { "id": 0x73c5, // TrackUID "data": DEFAULT_TRACK_NUMBER }, { "id": 0x9c, // FlagLacing "data": 0 }, { "id": 0x22b59c, // Language "data": "und" }, { "id": 0x86, // CodecID "data": "V_VP8" }, { "id": 0x258688, // CodecName "data": "VP8" }, { "id": 0x83, // TrackType "data": 1 }, { "id": 0xe0, // Video "data": [ { "id": 0xb0, // PixelWidth "data": videoWidth }, { "id": 0xba, // PixelHeight "data": videoHeight } ] } ] } ] }; ebmlSegment = { "id": 0x18538067, // Segment "size": -1, // Unbounded size "data": [ seekHead, segmentInfo, tracks, ] }; var bufferStream = new ArrayBufferDataStream(256); writeEBML(bufferStream, blobBuffer.pos, [ebmlHeader, ebmlSegment]); blobBuffer.write(bufferStream.getAsDataArray()); // Now we know where these top-level elements lie in the file: seekPoints.SegmentInfo.positionEBML.data = fileOffsetToSegmentRelative(segmentInfo.offset); seekPoints.Tracks.positionEBML.data = fileOffsetToSegmentRelative(tracks.offset); }
javascript
{ "resource": "" }
q23398
flushClusterFrameBuffer
train
function flushClusterFrameBuffer() { if (clusterFrameBuffer.length == 0) { return; } // First work out how large of a buffer we need to hold the cluster data var rawImageSize = 0; for (var i = 0; i < clusterFrameBuffer.length; i++) { rawImageSize += clusterFrameBuffer[i].frame.length; } var buffer = new ArrayBufferDataStream(rawImageSize + clusterFrameBuffer.length * 32), // Estimate 32 bytes per SimpleBlock header cluster = createCluster({ timecode: Math.round(clusterStartTime), }); for (var i = 0; i < clusterFrameBuffer.length; i++) { cluster.data.push(createKeyframeBlock(clusterFrameBuffer[i])); } writeEBML(buffer, blobBuffer.pos, cluster); blobBuffer.write(buffer.getAsDataArray()); addCuePoint(DEFAULT_TRACK_NUMBER, Math.round(clusterStartTime), cluster.offset); clusterFrameBuffer = []; clusterStartTime += clusterDuration; clusterDuration = 0; }
javascript
{ "resource": "" }
q23399
rewriteSeekHead
train
function rewriteSeekHead() { var seekHeadBuffer = new ArrayBufferDataStream(seekHead.size), oldPos = blobBuffer.pos; // Write the rewritten SeekHead element's data payload to the stream (don't need to update the id or size) writeEBML(seekHeadBuffer, seekHead.dataOffset, seekHead.data); // And write that through to the file blobBuffer.seek(seekHead.dataOffset); blobBuffer.write(seekHeadBuffer.getAsDataArray()); blobBuffer.seek(oldPos); }
javascript
{ "resource": "" }