_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q26600
parseScopeSyntax
train
function parseScopeSyntax(text) { // the regex below was built using the following pseudo-code: // double_quoted_string = `"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"` // single_quoted_string = `'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'` // text_out_of_quotes = `[^"']*?` // expr_parts = double_quoted_string + "|" + single_quoted_string + "|" + text_out_of_quotes // expression = zeroOrMore(nonCapture(expr_parts)) + "?" // id = "[$_a-zA-Z]+[$_a-zA-Z0-9]*" // as = " as" + OneOrMore(" ") // optional_spaces = zeroOrMore(" ") // semicolon = nonCapture(or(text(";"), "$")) // // regex = capture(expression) + as + capture(id) + optional_spaces + semicolon + optional_spaces const regex = RegExp("((?:(?:\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"|'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'|[^\"']*?))*?) as(?: )+([$_a-zA-Z]+[$_a-zA-Z0-9]*)(?: )*(?:;|$)(?: )*", 'g') const res = [] do { const idx = regex.lastIndex const match = regex.exec(text) if (regex.lastIndex === idx || match === null) { throw text.substr(idx) } if (match.index === regex.lastIndex) { regex.lastIndex++ } res.push({expression: match[1].trim(), identifier: match[2]}) } while (regex.lastIndex < text.length) return res }
javascript
{ "resource": "" }
q26601
execute
train
function execute(args) { try { const currentOptions = options.parse(args) return executeOptions(currentOptions) } catch (error) { console.error(error.message) return 1 } }
javascript
{ "resource": "" }
q26602
getJsonBufferPadded
train
function getJsonBufferPadded(json) { let string = JSON.stringify(json); const boundary = 4; const byteLength = Buffer.byteLength(string); const remainder = byteLength % boundary; const padding = (remainder === 0) ? 0 : boundary - remainder; let whitespace = ''; for (let i = 0; i < padding; ++i) { whitespace += ' '; } string += whitespace; return Buffer.from(string); }
javascript
{ "resource": "" }
q26603
readLines
train
function readLines(path, callback) { return new Promise(function(resolve, reject) { const stream = fsExtra.createReadStream(path); stream.on('error', reject); stream.on('end', resolve); const lineReader = readline.createInterface({ input : stream }); lineReader.on('line', callback); }); }
javascript
{ "resource": "" }
q26604
gltfToGlb
train
function gltfToGlb(gltf, binaryBuffer) { const buffer = gltf.buffers[0]; if (defined(buffer.uri)) { binaryBuffer = Buffer.alloc(0); } // Create padded binary scene string const jsonBuffer = getJsonBufferPadded(gltf); // Allocate buffer (Global header) + (JSON chunk header) + (JSON chunk) + (Binary chunk header) + (Binary chunk) const glbLength = 12 + 8 + jsonBuffer.length + 8 + binaryBuffer.length; const glb = Buffer.alloc(glbLength); // Write binary glTF header (magic, version, length) let byteOffset = 0; glb.writeUInt32LE(0x46546C67, byteOffset); byteOffset += 4; glb.writeUInt32LE(2, byteOffset); byteOffset += 4; glb.writeUInt32LE(glbLength, byteOffset); byteOffset += 4; // Write JSON Chunk header (length, type) glb.writeUInt32LE(jsonBuffer.length, byteOffset); byteOffset += 4; glb.writeUInt32LE(0x4E4F534A, byteOffset); // JSON byteOffset += 4; // Write JSON Chunk jsonBuffer.copy(glb, byteOffset); byteOffset += jsonBuffer.length; // Write Binary Chunk header (length, type) glb.writeUInt32LE(binaryBuffer.length, byteOffset); byteOffset += 4; glb.writeUInt32LE(0x004E4942, byteOffset); // BIN byteOffset += 4; // Write Binary Chunk binaryBuffer.copy(glb, byteOffset); return glb; }
javascript
{ "resource": "" }
q26605
obj2gltf
train
function obj2gltf(objPath, options) { const defaults = obj2gltf.defaults; options = defaultValue(options, {}); options.binary = defaultValue(options.binary, defaults.binary); options.separate = defaultValue(options.separate, defaults.separate); options.separateTextures = defaultValue(options.separateTextures, defaults.separateTextures) || options.separate; options.checkTransparency = defaultValue(options.checkTransparency, defaults.checkTransparency); options.secure = defaultValue(options.secure, defaults.secure); options.packOcclusion = defaultValue(options.packOcclusion, defaults.packOcclusion); options.metallicRoughness = defaultValue(options.metallicRoughness, defaults.metallicRoughness); options.specularGlossiness = defaultValue(options.specularGlossiness, defaults.specularGlossiness); options.unlit = defaultValue(options.unlit, defaults.unlit); options.overridingTextures = defaultValue(options.overridingTextures, defaultValue.EMPTY_OBJECT); options.logger = defaultValue(options.logger, getDefaultLogger()); options.writer = defaultValue(options.writer, getDefaultWriter(options.outputDirectory)); if (!defined(objPath)) { throw new DeveloperError('objPath is required'); } if (options.separateTextures && !defined(options.writer)) { throw new DeveloperError('Either options.writer or options.outputDirectory must be defined when writing separate resources.'); } if (options.metallicRoughness + options.specularGlossiness + options.unlit > 1) { throw new DeveloperError('Only one material type may be set from [metallicRoughness, specularGlossiness, unlit].'); } if (defined(options.overridingTextures.metallicRoughnessOcclusionTexture) && defined(options.overridingTextures.specularGlossinessTexture)) { throw new DeveloperError('metallicRoughnessOcclusionTexture and specularGlossinessTexture cannot both be defined.'); } if (defined(options.overridingTextures.metallicRoughnessOcclusionTexture)) { options.metallicRoughness = true; options.specularGlossiness = false; options.packOcclusion = true; } if (defined(options.overridingTextures.specularGlossinessTexture)) { options.metallicRoughness = false; options.specularGlossiness = true; } return loadObj(objPath, options) .then(function(objData) { return createGltf(objData, options); }) .then(function(gltf) { return writeGltf(gltf, options); }); }
javascript
{ "resource": "" }
q26606
loadTexture
train
function loadTexture(texturePath, options) { options = defaultValue(options, {}); options.checkTransparency = defaultValue(options.checkTransparency, false); options.decode = defaultValue(options.decode, false); return fsExtra.readFile(texturePath) .then(function(source) { const name = path.basename(texturePath, path.extname(texturePath)); const extension = path.extname(texturePath).toLowerCase(); const texture = new Texture(); texture.source = source; texture.name = name; texture.extension = extension; texture.path = texturePath; let decodePromise; if (extension === '.png') { decodePromise = decodePng(texture, options); } else if (extension === '.jpg' || extension === '.jpeg') { decodePromise = decodeJpeg(texture, options); } if (defined(decodePromise)) { return decodePromise.thenReturn(texture); } return texture; }); }
javascript
{ "resource": "" }
q26607
Texture
train
function Texture() { this.transparent = false; this.source = undefined; this.name = undefined; this.extension = undefined; this.path = undefined; this.pixels = undefined; this.width = undefined; this.height = undefined; }
javascript
{ "resource": "" }
q26608
getBufferPadded
train
function getBufferPadded(buffer) { const boundary = 4; const byteLength = buffer.length; const remainder = byteLength % boundary; if (remainder === 0) { return buffer; } const padding = (remainder === 0) ? 0 : boundary - remainder; const emptyBuffer = Buffer.alloc(padding); return Buffer.concat([buffer, emptyBuffer]); }
javascript
{ "resource": "" }
q26609
createGltf
train
function createGltf(objData, options) { const nodes = objData.nodes; let materials = objData.materials; const name = objData.name; // Split materials used by primitives with different types of attributes materials = splitIncompatibleMaterials(nodes, materials, options); const gltf = { accessors : [], asset : {}, buffers : [], bufferViews : [], extensionsUsed : [], extensionsRequired : [], images : [], materials : [], meshes : [], nodes : [], samplers : [], scene : 0, scenes : [], textures : [] }; gltf.asset = { generator : 'obj2gltf', version: '2.0' }; gltf.scenes.push({ nodes : [] }); const bufferState = { positionBuffers : [], normalBuffers : [], uvBuffers : [], indexBuffers : [], positionAccessors : [], normalAccessors : [], uvAccessors : [], indexAccessors : [] }; const uint32Indices = requiresUint32Indices(nodes); const nodesLength = nodes.length; for (let i = 0; i < nodesLength; ++i) { const node = nodes[i]; const meshes = node.meshes; const meshesLength = meshes.length; if (meshesLength === 1) { const meshIndex = addMesh(gltf, materials, bufferState, uint32Indices, meshes[0], options); addNode(gltf, node.name, meshIndex, undefined); } else { // Add meshes as child nodes const parentIndex = addNode(gltf, node.name); for (let j = 0; j < meshesLength; ++j) { const mesh = meshes[j]; const meshIndex = addMesh(gltf, materials, bufferState, uint32Indices, mesh, options); addNode(gltf, mesh.name, meshIndex, parentIndex); } } } if (gltf.images.length > 0) { gltf.samplers.push({ magFilter : WebGLConstants.LINEAR, minFilter : WebGLConstants.NEAREST_MIPMAP_LINEAR, wrapS : WebGLConstants.REPEAT, wrapT : WebGLConstants.REPEAT }); } addBuffers(gltf, bufferState, name, options.separate); if (options.specularGlossiness) { gltf.extensionsUsed.push('KHR_materials_pbrSpecularGlossiness'); gltf.extensionsRequired.push('KHR_materials_pbrSpecularGlossiness'); } if (options.unlit) { gltf.extensionsUsed.push('KHR_materials_unlit'); gltf.extensionsRequired.push('KHR_materials_unlit'); } return gltf; }
javascript
{ "resource": "" }
q26610
writeGltf
train
function writeGltf(gltf, options) { return encodeTextures(gltf) .then(function() { const binary = options.binary; const separate = options.separate; const separateTextures = options.separateTextures; const promises = []; if (separateTextures) { promises.push(writeSeparateTextures(gltf, options)); } else { writeEmbeddedTextures(gltf); } if (separate) { promises.push(writeSeparateBuffers(gltf, options)); } else if (!binary) { writeEmbeddedBuffer(gltf); } const binaryBuffer = gltf.buffers[0].extras._obj2gltf.source; return Promise.all(promises) .then(function() { deleteExtras(gltf); removeEmpty(gltf); if (binary) { return gltfToGlb(gltf, binaryBuffer); } return gltf; }); }); }
javascript
{ "resource": "" }
q26611
ls
train
function ls (onEnd) { const FN = require('fstream-npm') const color = require('chalk') const glob = require('glob') const exclude = require('lodash.difference') const included = [ ] const all = glob.sync('**/**', { ignore : [ 'node_modules/**/**' ], nodir : true }) FN({ path: process.cwd() }) .on('child', function (e) { included.push(e._path.replace(e.root.path + '/', '')) }) .on('end', function () { const excluded = exclude(all, included) console.info(color.magenta('\n\nWILL BE PUBLISHED\n')) console.info(color.green(included.join('\n'))) console.info(color.magenta('\n\nWON\'T BE PUBLISHED\n')) console.info(color.red(excluded.join('\n'))) console.info('\n\nYou can use .npmignore and the "files" field of package.json to manage these files.') console.info('See https://docs.npmjs.com/misc/developers#keeping-files-out-of-your-package\n') if (typeof onEnd === 'function') { onEnd({ included : included, excluded : excluded }) } }) }
javascript
{ "resource": "" }
q26612
createBitbucketEnterpriseCommitLink
train
function createBitbucketEnterpriseCommitLink () { const pkg = require(process.cwd() + '/package') const repository = pkg.repository.url return function (commit) { const commitStr = commit.substring(0,8) return repository ? `[${commitStr}](${repository}/commits/${commitStr})` : commitStr } }
javascript
{ "resource": "" }
q26613
writeChangelog
train
function writeChangelog (options, done) { options.repoType = options.repoType || 'github' log('Using repo type: ', colors.magenta(options.repoType)) const pkg = require(process.cwd() + '/package') const opts = { log: log, repository: pkg.repository.url, version: options.version } // Github uses "commit", Bitbucket Enterprise uses "commits" if (options.repoType === 'bitbucket') { opts.commitLink = createBitbucketEnterpriseCommitLink() } return require('nf-conventional-changelog')(opts, function (err, clog) { if (err) { throw new Error(err) } else { require('fs').writeFileSync(process.cwd() + '/CHANGELOG.md', clog) return done && typeof done === 'function' && done() } }) }
javascript
{ "resource": "" }
q26614
caller
train
function caller() { const returnedArgs = Array.prototype.slice.call(arguments) const fn = returnedArgs.shift() const self = this return wrapPromise(function (resolve, reject) { returnedArgs.push(function (err, args) { if (err) { reject(err) return } resolve(args) }) fn.apply(self, returnedArgs) }) }
javascript
{ "resource": "" }
q26615
defaultWorkerPolicies
train
function defaultWorkerPolicies(version, workspaceSid, workerSid) { var activities = new Policy({ url: _.join([TASKROUTER_BASE_URL, version, 'Workspaces', workspaceSid, 'Activities'], '/'), method: 'GET', allow: true }); var tasks = new Policy({ url: _.join([TASKROUTER_BASE_URL, version, 'Workspaces', workspaceSid, 'Tasks', '**'], '/'), method: 'GET', allow: true }); var reservations = new Policy({ url: _.join( [TASKROUTER_BASE_URL, version, 'Workspaces', workspaceSid, 'Workers', workerSid, 'Reservations', '**'], '/' ), method: 'GET', allow: true }); var workerFetch = new Policy({ url: _.join([TASKROUTER_BASE_URL, version, 'Workspaces', workspaceSid, 'Workers', workerSid], '/'), method: 'GET', allow: true }); return [activities, tasks, reservations, workerFetch]; }
javascript
{ "resource": "" }
q26616
defaultEventBridgePolicies
train
function defaultEventBridgePolicies(accountSid, channelId) { var url = _.join([EVENT_URL_BASE, accountSid, channelId], '/'); return [ new Policy({ url: url, method: 'GET', allow: true }), new Policy({ url: url, method: 'POST', allow: true }) ]; }
javascript
{ "resource": "" }
q26617
workspacesUrl
train
function workspacesUrl(workspaceSid) { return _.join( _.filter([TASKROUTER_BASE_URL, TASKROUTER_VERSION, 'Workspaces', workspaceSid], _.isString), '/' ); }
javascript
{ "resource": "" }
q26618
taskQueuesUrl
train
function taskQueuesUrl(workspaceSid, taskQueueSid) { return _.join( _.filter([workspacesUrl(workspaceSid), 'TaskQueues', taskQueueSid], _.isString), '/' ); }
javascript
{ "resource": "" }
q26619
tasksUrl
train
function tasksUrl(workspaceSid, taskSid) { return _.join( _.filter([workspacesUrl(workspaceSid), 'Tasks', taskSid], _.isString), '/' ); }
javascript
{ "resource": "" }
q26620
activitiesUrl
train
function activitiesUrl(workspaceSid, activitySid) { return _.join( _.filter([workspacesUrl(workspaceSid), 'Activities', activitySid], _.isString), '/' ); }
javascript
{ "resource": "" }
q26621
workersUrl
train
function workersUrl(workspaceSid, workerSid) { return _.join( _.filter([workspacesUrl(workspaceSid), 'Workers', workerSid], _.isString), '/' ); }
javascript
{ "resource": "" }
q26622
reservationsUrl
train
function reservationsUrl(workspaceSid, workerSid, reservationSid) { return _.join( _.filter([workersUrl(workspaceSid, workerSid), 'Reservations', reservationSid], _.isString), '/' ); }
javascript
{ "resource": "" }
q26623
Policy
train
function Policy(options) { options = options || {}; this.url = options.url; this.method = options.method || 'GET'; this.queryFilter = options.queryFilter || {}; this.postFilter = options.postFilter || {}; this.allow = options.allow || true; }
javascript
{ "resource": "" }
q26624
getExpectedTwilioSignature
train
function getExpectedTwilioSignature(authToken, url, params) { if (url.indexOf('bodySHA256') != -1) params = {}; var data = Object.keys(params) .sort() .reduce((acc, key) => acc + key + params[key], url); return crypto .createHmac('sha1', authToken) .update(Buffer.from(data, 'utf-8')) .digest('base64'); }
javascript
{ "resource": "" }
q26625
validateRequest
train
function validateRequest(authToken, twilioHeader, url, params) { var expectedSignature = getExpectedTwilioSignature(authToken, url, params); return scmp(Buffer.from(twilioHeader), Buffer.from(expectedSignature)); }
javascript
{ "resource": "" }
q26626
validateRequestWithBody
train
function validateRequestWithBody(authToken, twilioHeader, requestUrl, body) { var urlObject = new url.URL(requestUrl); return validateRequest(authToken, twilioHeader, requestUrl, {}) && validateBody(body, urlObject.searchParams.get('bodySHA256')); }
javascript
{ "resource": "" }
q26627
getTruncatedOptions
train
function getTruncatedOptions(options, maxResults) { if (!maxResults || maxResults >= options.length) { return options; } return options.slice(0, maxResults); }
javascript
{ "resource": "" }
q26628
gpmMouse
train
function gpmMouse( mode ) { var self = this ; if ( this.root.gpmHandler ) { this.root.gpmHandler.close() ; this.root.gpmHandler = undefined ; } if ( ! mode ) { //console.log( '>>>>> off <<<<<' ) ; return ; } this.root.gpmHandler = gpm.createHandler( { stdin: this.root.stdin , raw: false , mode: mode } ) ; //console.log( '>>>>>' , mode , '<<<<<' ) ; // Simply re-emit event this.root.gpmHandler.on( 'mouse' , ( name , data ) => { self.root.emit( 'mouse' , name , data ) ; } ) ; this.root.gpmHandler.on( 'error' , ( /* error */ ) => { //console.log( 'mouseDrag error:' , error ) ; } ) ; }
javascript
{ "resource": "" }
q26629
TextBuffer
train
function TextBuffer( options = {} ) { this.ScreenBuffer = options.ScreenBuffer || ( options.dst && options.dst.constructor ) || termkit.ScreenBuffer ; // a screenBuffer this.dst = options.dst ; // virtually infinity by default this.width = options.width || Infinity ; this.height = options.height || Infinity ; this.x = options.x !== undefined ? options.x : 0 ; this.y = options.y !== undefined ? options.y : 0 ; this.cx = 0 ; this.cy = 0 ; this.emptyCellAttr = this.ScreenBuffer.prototype.DEFAULT_ATTR ; this.hidden = false ; this.tabWidth = options.tabWidth || 4 ; this.forceInBound = !! options.forceInBound ; this.wrap = !! options.wrap ; this.lineWrapping = options.lineWrapping || false ; this.buffer = [ [] ] ; this.stateMachine = options.stateMachine || null ; if ( options.hidden ) { this.setHidden( options.hidden ) ; } }
javascript
{ "resource": "" }
q26630
onResize
train
function onResize() { if ( this.stdout.columns && this.stdout.rows ) { this.width = this.stdout.columns ; this.height = this.stdout.rows ; } this.emit( 'resize' , this.width , this.height ) ; }
javascript
{ "resource": "" }
q26631
parseValueOfType
train
function parseValueOfType(value, type, options) { switch (type) { case String: return { value } case Number: case 'Integer': case Integer: // The global isFinite() function determines // whether the passed value is a finite number. // If needed, the parameter is first converted to a number. if (!isFinite(value)) { return { error: 'invalid' } } if (type === Integer && !isInteger(value)) { return { error: 'invalid' } } // Convert strings to numbers. // Just an additional feature. // Won't happen when called from `readXlsx()`. if (typeof value === 'string') { value = parseFloat(value) } return { value } case 'URL': case URL: if (!isURL(value)) { return { error: 'invalid' } } return { value } case 'Email': case Email: if (!isEmail(value)) { return { error: 'invalid' } } return { value } case Date: // XLSX has no specific format for dates. // Sometimes a date can be heuristically detected. // https://github.com/catamphetamine/read-excel-file/issues/3#issuecomment-395770777 if (value instanceof Date) { return { value } } if (typeof value === 'number') { if (!isFinite(value)) { return { error: 'invalid' } } value = parseInt(value) const date = parseDate(value, options.properties) if (!date) { return { error: 'invalid' } } return { value: date } } return { error: 'invalid' } case Boolean: if (typeof value === 'boolean') { return { value } } return { error: 'invalid' } default: throw new Error(`Unknown schema type: ${type && type.name || type}`) } }
javascript
{ "resource": "" }
q26632
MergeRowsWithHeaders
train
function MergeRowsWithHeaders(obj1, obj2) { for(var p in obj2){ if(obj1[p] instanceof Array && obj1[p] instanceof Array){ obj1[p] = obj1[p].concat(obj2[p]) } else { obj1[p] = obj2[p] } } return obj1; }
javascript
{ "resource": "" }
q26633
parse
train
function parse() { var self = this var value = String(self.file) var start = {line: 1, column: 1, offset: 0} var content = xtend(start) var node // Clean non-unix newlines: `\r\n` and `\r` are all changed to `\n`. // This should not affect positional information. value = value.replace(lineBreaksExpression, lineFeed) // BOM. if (value.charCodeAt(0) === 0xfeff) { value = value.slice(1) content.column++ content.offset++ } node = { type: 'root', children: self.tokenizeBlock(value, content), position: {start: start, end: self.eof || xtend(start)} } if (!self.options.position) { removePosition(node, true) } return node }
javascript
{ "resource": "" }
q26634
alignment
train
function alignment(value, index) { var start = value.lastIndexOf(lineFeed, index) var end = value.indexOf(lineFeed, index) var char end = end === -1 ? value.length : end while (++start < end) { char = value.charAt(start) if ( char !== colon && char !== dash && char !== space && char !== verticalBar ) { return false } } return true }
javascript
{ "resource": "" }
q26635
protocol
train
function protocol(value) { var val = value.slice(-6).toLowerCase() return val === mailto || val.slice(-5) === https || val.slice(-4) === http }
javascript
{ "resource": "" }
q26636
Compiler
train
function Compiler(tree, file) { this.inLink = false this.inTable = false this.tree = tree this.file = file this.options = xtend(this.options) this.setOptions({}) }
javascript
{ "resource": "" }
q26637
pedanticListItem
train
function pedanticListItem(ctx, value, position) { var offsets = ctx.offset var line = position.line // Remove the list-item’s bullet. value = value.replace(pedanticBulletExpression, replacer) // The initial line was also matched by the below, so we reset the `line`. line = position.line return value.replace(initialIndentExpression, replacer) // A simple replacer which removed all matches, and adds their length to // `offset`. function replacer($0) { offsets[line] = (offsets[line] || 0) + $0.length line++ return '' } }
javascript
{ "resource": "" }
q26638
normalListItem
train
function normalListItem(ctx, value, position) { var offsets = ctx.offset var line = position.line var max var bullet var rest var lines var trimmedLines var index var length // Remove the list-item’s bullet. value = value.replace(bulletExpression, replacer) lines = value.split(lineFeed) trimmedLines = removeIndent(value, getIndent(max).indent).split(lineFeed) // We replaced the initial bullet with something else above, which was used // to trick `removeIndentation` into removing some more characters when // possible. However, that could result in the initial line to be stripped // more than it should be. trimmedLines[0] = rest offsets[line] = (offsets[line] || 0) + bullet.length line++ index = 0 length = lines.length while (++index < length) { offsets[line] = (offsets[line] || 0) + lines[index].length - trimmedLines[index].length line++ } return trimmedLines.join(lineFeed) function replacer($0, $1, $2, $3, $4) { bullet = $1 + $2 + $3 rest = $4 // Make sure that the first nine numbered list items can indent with an // extra space. That is, when the bullet did not receive an extra final // space. if (Number($2) < 10 && bullet.length % 2 === 1) { $2 = space + $2 } max = $1 + repeat(space, $2.length) + $3 return max + rest } }
javascript
{ "resource": "" }
q26639
indentation
train
function indentation(value) { var index = 0 var indent = 0 var character = value.charAt(index) var stops = {} var size while (character === tab || character === space) { size = character === tab ? tabSize : spaceSize indent += size if (size > 1) { indent = Math.floor(indent / size) * size } stops[indent] = index character = value.charAt(++index) } return {indent: indent, stops: stops} }
javascript
{ "resource": "" }
q26640
all
train
function all(parent) { var self = this var children = parent.children var length = children.length var results = [] var index = -1 while (++index < length) { results[index] = self.visit(children[index], parent) } return results }
javascript
{ "resource": "" }
q26641
factory
train
function factory(ctx, key) { return unescape // De-escape a string using the expression at `key` in `ctx`. function unescape(value) { var prev = 0 var index = value.indexOf(backslash) var escape = ctx[key] var queue = [] var character while (index !== -1) { queue.push(value.slice(prev, index)) prev = index + 1 character = value.charAt(prev) // If the following character is not a valid escape, add the slash. if (!character || escape.indexOf(character) === -1) { queue.push(backslash) } index = value.indexOf(backslash, prev + 1) } queue.push(value.slice(prev)) return queue.join('') } }
javascript
{ "resource": "" }
q26642
paragraph
train
function paragraph(eat, value, silent) { var self = this var settings = self.options var commonmark = settings.commonmark var gfm = settings.gfm var tokenizers = self.blockTokenizers var interruptors = self.interruptParagraph var index = value.indexOf(lineFeed) var length = value.length var position var subvalue var character var size var now while (index < length) { // Eat everything if there’s no following newline. if (index === -1) { index = length break } // Stop if the next character is NEWLINE. if (value.charAt(index + 1) === lineFeed) { break } // In commonmark-mode, following indented lines are part of the paragraph. if (commonmark) { size = 0 position = index + 1 while (position < length) { character = value.charAt(position) if (character === tab) { size = tabSize break } else if (character === space) { size++ } else { break } position++ } if (size >= tabSize && character !== lineFeed) { index = value.indexOf(lineFeed, index + 1) continue } } subvalue = value.slice(index + 1) // Check if the following code contains a possible block. if (interrupt(interruptors, tokenizers, self, [eat, subvalue, true])) { break } // Break if the following line starts a list, when already in a list, or // when in commonmark, or when in gfm mode and the bullet is *not* numeric. if ( tokenizers.list.call(self, eat, subvalue, true) && (self.inList || commonmark || (gfm && !decimal(trim.left(subvalue).charAt(0)))) ) { break } position = index index = value.indexOf(lineFeed, index + 1) if (index !== -1 && trim(value.slice(position, index)) === '') { index = position break } } subvalue = value.slice(0, index) if (trim(subvalue) === '') { eat(subvalue) return null } /* istanbul ignore if - never used (yet) */ if (silent) { return true } now = eat.now() subvalue = trimTrailingLines(subvalue) return eat(subvalue)({ type: 'paragraph', children: self.tokenizeInline(subvalue, now) }) }
javascript
{ "resource": "" }
q26643
keys
train
function keys(value) { var result = [] var key for (key in value) { result.push(key) } return result }
javascript
{ "resource": "" }
q26644
updatePosition
train
function updatePosition(subvalue) { var lastIndex = -1 var index = subvalue.indexOf('\n') while (index !== -1) { line++ lastIndex = index index = subvalue.indexOf('\n', index + 1) } if (lastIndex === -1) { column += subvalue.length } else { column = subvalue.length - lastIndex } if (line in offset) { if (lastIndex !== -1) { column += offset[line] } else if (column <= offset[line]) { column = offset[line] + 1 } } }
javascript
{ "resource": "" }
q26645
now
train
function now() { var pos = {line: line, column: column} pos.offset = self.toOffset(pos) return pos }
javascript
{ "resource": "" }
q26646
add
train
function add(node, parent) { var children = parent ? parent.children : tokens var prev = children[children.length - 1] var fn if ( prev && node.type === prev.type && (node.type === 'text' || node.type === 'blockquote') && mergeable(prev) && mergeable(node) ) { fn = node.type === 'text' ? mergeText : mergeBlockquote node = fn.call(self, prev, node) } if (node !== prev) { children.push(node) } if (self.atStart && tokens.length !== 0) { self.exitStart() } return node }
javascript
{ "resource": "" }
q26647
eat
train
function eat(subvalue) { var indent = getOffset() var pos = position() var current = now() validateEat(subvalue) apply.reset = reset reset.test = test apply.test = test value = value.substring(subvalue.length) updatePosition(subvalue) indent = indent() return apply // Add the given arguments, add `position` to the returned node, and // return the node. function apply(node, parent) { return pos(add(pos(node), parent), indent) } // Functions just like apply, but resets the content: the line and // column are reversed, and the eaten value is re-added. This is // useful for nodes with a single type of content, such as lists and // tables. See `apply` above for what parameters are expected. function reset() { var node = apply.apply(null, arguments) line = current.line column = current.column value = subvalue + value return node } // Test the position, after eating, and reverse to a not-eaten state. function test() { var result = pos({}) line = current.line column = current.column value = subvalue + value return result.position } }
javascript
{ "resource": "" }
q26648
mergeable
train
function mergeable(node) { var start var end if (node.type !== 'text' || !node.position) { return true } start = node.position.start end = node.position.end // Only merge nodes which occupy the same size as their `value`. return ( start.line !== end.line || end.column - start.column === node.value.length ) }
javascript
{ "resource": "" }
q26649
factory
train
function factory(ctx) { decoder.raw = decodeRaw return decoder // Normalize `position` to add an `indent`. function normalize(position) { var offsets = ctx.offset var line = position.line var result = [] while (++line) { if (!(line in offsets)) { break } result.push((offsets[line] || 0) + 1) } return {start: position, indent: result} } // Decode `value` (at `position`) into text-nodes. function decoder(value, position, handler) { entities(value, { position: normalize(position), warning: handleWarning, text: handler, reference: handler, textContext: ctx, referenceContext: ctx }) } // Decode `value` (at `position`) into a string. function decodeRaw(value, position, options) { return entities( value, xtend(options, {position: normalize(position), warning: handleWarning}) ) } // Handle a warning. // See <https://github.com/wooorm/parse-entities> for the warnings. function handleWarning(reason, position, code) { if (code !== 3) { ctx.file.message(reason, position) } } }
javascript
{ "resource": "" }
q26650
normalize
train
function normalize(position) { var offsets = ctx.offset var line = position.line var result = [] while (++line) { if (!(line in offsets)) { break } result.push((offsets[line] || 0) + 1) } return {start: position, indent: result} }
javascript
{ "resource": "" }
q26651
setOptions
train
function setOptions(options) { var self = this var current = self.options var ruleRepetition var key if (options == null) { options = {} } else if (typeof options === 'object') { options = xtend(options) } else { throw new Error('Invalid value `' + options + '` for setting `options`') } for (key in defaults) { validate[typeof defaults[key]](options, key, current[key], maps[key]) } ruleRepetition = options.ruleRepetition if (ruleRepetition && ruleRepetition < 3) { raise(ruleRepetition, 'options.ruleRepetition') } self.encode = encodeFactory(String(options.entities)) self.escape = escapeFactory(options) self.options = options return self }
javascript
{ "resource": "" }
q26652
encodeFactory
train
function encodeFactory(type) { var options = {} if (type === 'false') { return identity } if (type === 'true') { options.useNamedReferences = true } if (type === 'escape') { options.escapeOnly = true options.useNamedReferences = true } return wrapped // Encode HTML entities using the bound options. function wrapped(value) { return encode(value, options) } }
javascript
{ "resource": "" }
q26653
getLocaleDateTimeFormat
train
function getLocaleDateTimeFormat(locale, width) { var data = findLocaleData(locale); var dateTimeFormatData = data[12 /* DateTimeFormat */]; return getLastDefinedValue(dateTimeFormatData, width); }
javascript
{ "resource": "" }
q26654
getLastDefinedValue
train
function getLastDefinedValue(data, index) { for (var i = index; i > -1; i--) { if (typeof data[i] !== 'undefined') { return data[i]; } } throw new Error('Locale data API: locale data undefined'); }
javascript
{ "resource": "" }
q26655
findLocaleData
train
function findLocaleData(locale) { var normalizedLocale = locale.toLowerCase().replace(/_/g, '-'); var match = LOCALE_DATA[normalizedLocale]; if (match) { return match; } // let's try to find a parent locale var parentLocale = normalizedLocale.split('-')[0]; match = LOCALE_DATA[parentLocale]; if (match) { return match; } if (parentLocale === 'en') { return localeEn; } throw new Error("Missing locale data for the locale \"" + locale + "\"."); }
javascript
{ "resource": "" }
q26656
getNumberOfCurrencyDigits
train
function getNumberOfCurrencyDigits(code) { var digits; var currency = CURRENCIES_EN[code]; if (currency) { digits = currency[2 /* NbOfDigits */]; } return typeof digits === 'number' ? digits : DEFAULT_NB_OF_CURRENCY_DIGITS; }
javascript
{ "resource": "" }
q26657
dateStrGetter
train
function dateStrGetter(name, width, form, extended) { if (form === void 0) { form = FormStyle.Format; } if (extended === void 0) { extended = false; } return function (date, locale) { return getDateTranslation(date, locale, name, width, form, extended); }; }
javascript
{ "resource": "" }
q26658
toDate
train
function toDate(value) { if (isDate(value)) { return value; } if (typeof value === 'number' && !isNaN(value)) { return new Date(value); } if (typeof value === 'string') { value = value.trim(); var parsedNb = parseFloat(value); // any string that only contains numbers, like "1234" but not like "1234hello" if (!isNaN(value - parsedNb)) { return new Date(parsedNb); } if (/^(\d{4}-\d{1,2}-\d{1,2})$/.test(value)) { /* For ISO Strings without time the day, month and year must be extracted from the ISO String before Date creation to avoid time offset and errors in the new Date. If we only replace '-' with ',' in the ISO String ("2015,01,01"), and try to create a new date, some browsers (e.g. IE 9) will throw an invalid Date error. If we leave the '-' ("2015-01-01") and try to create a new Date("2015-01-01") the timeoffset is applied. Note: ISO months are 0 for January, 1 for February, ... */ var _a = Object(tslib__WEBPACK_IMPORTED_MODULE_1__["__read"])(value.split('-').map(function (val) { return +val; }), 3), y = _a[0], m = _a[1], d = _a[2]; return new Date(y, m - 1, d); } var match = void 0; if (match = value.match(ISO8601_DATE_REGEX)) { return isoStringToDate(match); } } var date = new Date(value); if (!isDate(date)) { throw new Error("Unable to convert \"" + value + "\" into a date"); } return date; }
javascript
{ "resource": "" }
q26659
toPercent
train
function toPercent(parsedNumber) { // if the number is 0, don't do anything if (parsedNumber.digits[0] === 0) { return parsedNumber; } // Getting the current number of decimals var fractionLen = parsedNumber.digits.length - parsedNumber.integerLen; if (parsedNumber.exponent) { parsedNumber.exponent += 2; } else { if (fractionLen === 0) { parsedNumber.digits.push(0, 0); } else if (fractionLen === 1) { parsedNumber.digits.push(0); } parsedNumber.integerLen += 2; } return parsedNumber; }
javascript
{ "resource": "" }
q26660
HttpHeaderResponse
train
function HttpHeaderResponse(init) { if (init === void 0) { init = {}; } var _this = _super.call(this, init) || this; _this.type = HttpEventType.ResponseHeader; return _this; }
javascript
{ "resource": "" }
q26661
HttpResponse
train
function HttpResponse(init) { if (init === void 0) { init = {}; } var _this = _super.call(this, init) || this; _this.type = HttpEventType.Response; _this.body = init.body !== undefined ? init.body : null; return _this; }
javascript
{ "resource": "" }
q26662
getResponseUrl
train
function getResponseUrl(xhr) { if ('responseURL' in xhr && xhr.responseURL) { return xhr.responseURL; } if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) { return xhr.getResponseHeader('X-Request-URL'); } return null; }
javascript
{ "resource": "" }
q26663
train
function () { if (headerResponse !== null) { return headerResponse; } // Read status and normalize an IE9 bug (http://bugs.jquery.com/ticket/1450). var status = xhr.status === 1223 ? 204 : xhr.status; var statusText = xhr.statusText || 'OK'; // Parse headers from XMLHttpRequest - this step is lazy. var headers = new HttpHeaders(xhr.getAllResponseHeaders()); // Read the response URL from the XMLHttpResponse instance and fall back on the // request URL. var url = getResponseUrl(xhr) || req.url; // Construct the HttpHeaderResponse and memoize it. headerResponse = new HttpHeaderResponse({ headers: headers, status: status, statusText: statusText, url: url }); return headerResponse; }
javascript
{ "resource": "" }
q26664
train
function () { // Read response state from the memoized partial data. var _a = partialFromXhr(), headers = _a.headers, status = _a.status, statusText = _a.statusText, url = _a.url; // The body will be read out if present. var body = null; if (status !== 204) { // Use XMLHttpRequest.response if set, responseText otherwise. body = (typeof xhr.response === 'undefined') ? xhr.responseText : xhr.response; } // Normalize another potential bug (this one comes from CORS). if (status === 0) { status = !!body ? 200 : 0; } // ok determines whether the response will be transmitted on the event or // error channel. Unsuccessful status codes (not 2xx) will always be errors, // but a successful status code can still result in an error if the user // asked for JSON data and the body cannot be parsed as such. var ok = status >= 200 && status < 300; // Check whether the body needs to be parsed as JSON (in many cases the browser // will have done that already). if (req.responseType === 'json' && typeof body === 'string') { // Save the original body, before attempting XSSI prefix stripping. var originalBody = body; body = body.replace(XSSI_PREFIX, ''); try { // Attempt the parse. If it fails, a parse error should be delivered to the user. body = body !== '' ? JSON.parse(body) : null; } catch (error) { // Since the JSON.parse failed, it's reasonable to assume this might not have been a // JSON response. Restore the original body (including any XSSI prefix) to deliver // a better error response. body = originalBody; // If this was an error request to begin with, leave it as a string, it probably // just isn't JSON. Otherwise, deliver the parsing error to the user. if (ok) { // Even though the response status was 2xx, this is still an error. ok = false; // The parse error contains the text of the body that failed to parse. body = { error: error, text: body }; } } } if (ok) { // A successful response is delivered on the event stream. observer.next(new HttpResponse({ body: body, headers: headers, status: status, statusText: statusText, url: url || undefined, })); // The full body has been received and delivered, no further events // are possible. This request is complete. observer.complete(); } else { // An unsuccessful request is delivered on the error channel. observer.error(new HttpErrorResponse({ // The error in this case is the response body (error from the server). error: body, headers: headers, status: status, statusText: statusText, url: url || undefined, })); } }
javascript
{ "resource": "" }
q26665
train
function (error) { var res = new HttpErrorResponse({ error: error, status: xhr.status || 0, statusText: xhr.statusText || 'Unknown Error', }); observer.error(res); }
javascript
{ "resource": "" }
q26666
train
function (event) { // Send the HttpResponseHeaders event if it hasn't been sent already. if (!sentHeaders) { observer.next(partialFromXhr()); sentHeaders = true; } // Start building the download progress event to deliver on the response // event stream. var progressEvent = { type: HttpEventType.DownloadProgress, loaded: event.loaded, }; // Set the total number of bytes in the event if it's available. if (event.lengthComputable) { progressEvent.total = event.total; } // If the request was for text content and a partial response is // available on XMLHttpRequest, include it in the progress event // to allow for streaming reads. if (req.responseType === 'text' && !!xhr.responseText) { progressEvent.partialText = xhr.responseText; } // Finally, fire the event. observer.next(progressEvent); }
javascript
{ "resource": "" }
q26667
train
function (event) { // Upload progress events are simpler. Begin building the progress // event. var progress = { type: HttpEventType.UploadProgress, loaded: event.loaded, }; // If the total number of bytes being uploaded is available, include // it. if (event.lengthComputable) { progress.total = event.total; } // Send the event. observer.next(progress); }
javascript
{ "resource": "" }
q26668
defineInjector
train
function defineInjector(options) { return { factory: options.factory, providers: options.providers || [], imports: options.imports || [], }; }
javascript
{ "resource": "" }
q26669
resolveForwardRef
train
function resolveForwardRef(type) { if (typeof type === 'function' && type.hasOwnProperty('__forward_ref__') && type.__forward_ref__ === forwardRef) { return type(); } else { return type; } }
javascript
{ "resource": "" }
q26670
resolveReflectiveProvider
train
function resolveReflectiveProvider(provider) { return new ResolvedReflectiveProvider_(ReflectiveKey.get(provider.provide), [resolveReflectiveFactory(provider)], provider.multi || false); }
javascript
{ "resource": "" }
q26671
EventEmitter
train
function EventEmitter(isAsync) { if (isAsync === void 0) { isAsync = false; } var _this = _super.call(this) || this; _this.__isAsync = isAsync; return _this; }
javascript
{ "resource": "" }
q26672
registerModuleFactory
train
function registerModuleFactory(id, factory) { var existing = moduleFactories.get(id); if (existing) { throw new Error("Duplicate module registered for " + id + " - " + existing.moduleType.name + " vs " + factory.moduleType.name); } moduleFactories.set(id, factory); }
javascript
{ "resource": "" }
q26673
shouldCallLifecycleInitHook
train
function shouldCallLifecycleInitHook(view, initState, index) { if ((view.state & 1792 /* InitState_Mask */) === initState && view.initIndex <= index) { view.initIndex = index + 1; return true; } return false; }
javascript
{ "resource": "" }
q26674
viewParentEl
train
function viewParentEl(view) { var parentView = view.parent; if (parentView) { return view.parentNodeDef.parent; } else { return null; } }
javascript
{ "resource": "" }
q26675
queueLifecycleHooks
train
function queueLifecycleHooks(flags, tView) { if (tView.firstTemplatePass) { var start = flags >> 14 /* DirectiveStartingIndexShift */; var count = flags & 4095 /* DirectiveCountMask */; var end = start + count; // It's necessary to loop through the directives at elementEnd() (rather than processing in // directiveCreate) so we can preserve the current hook order. Content, view, and destroy // hooks for projected components and directives must be called *before* their hosts. for (var i = start; i < end; i++) { var def = tView.directives[i]; queueContentHooks(def, tView, i); queueViewHooks(def, tView, i); queueDestroyHooks(def, tView, i); } } }
javascript
{ "resource": "" }
q26676
queueContentHooks
train
function queueContentHooks(def, tView, i) { if (def.afterContentInit) { (tView.contentHooks || (tView.contentHooks = [])).push(i, def.afterContentInit); } if (def.afterContentChecked) { (tView.contentHooks || (tView.contentHooks = [])).push(i, def.afterContentChecked); (tView.contentCheckHooks || (tView.contentCheckHooks = [])).push(i, def.afterContentChecked); } }
javascript
{ "resource": "" }
q26677
queueViewHooks
train
function queueViewHooks(def, tView, i) { if (def.afterViewInit) { (tView.viewHooks || (tView.viewHooks = [])).push(i, def.afterViewInit); } if (def.afterViewChecked) { (tView.viewHooks || (tView.viewHooks = [])).push(i, def.afterViewChecked); (tView.viewCheckHooks || (tView.viewCheckHooks = [])).push(i, def.afterViewChecked); } }
javascript
{ "resource": "" }
q26678
queueDestroyHooks
train
function queueDestroyHooks(def, tView, i) { if (def.onDestroy != null) { (tView.destroyHooks || (tView.destroyHooks = [])).push(i, def.onDestroy); } }
javascript
{ "resource": "" }
q26679
executeInitHooks
train
function executeInitHooks(currentView, tView, creationMode) { if (currentView[FLAGS] & 16 /* RunInit */) { executeHooks(currentView[DIRECTIVES], tView.initHooks, tView.checkHooks, creationMode); currentView[FLAGS] &= ~16 /* RunInit */; } }
javascript
{ "resource": "" }
q26680
executeHooks
train
function executeHooks(data, allHooks, checkHooks, creationMode) { var hooksToCall = creationMode ? allHooks : checkHooks; if (hooksToCall) { callHooks(data, hooksToCall); } }
javascript
{ "resource": "" }
q26681
throwErrorIfNoChangesMode
train
function throwErrorIfNoChangesMode(creationMode, checkNoChangesMode, oldValue, currValue) { if (checkNoChangesMode) { var msg = "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '" + oldValue + "'. Current value: '" + currValue + "'."; if (creationMode) { msg += " It seems like the view has been created after its parent and its children have been dirty checked." + " Has it been created in a change detection hook ?"; } // TODO: include debug context throw new Error(msg); } }
javascript
{ "resource": "" }
q26682
flatten$1
train
function flatten$1(list) { var result = []; var i = 0; while (i < list.length) { var item = list[i]; if (Array.isArray(item)) { if (item.length > 0) { list = item.concat(list.slice(i + 1)); i = 0; } else { i++; } } else { result.push(item); i++; } } return result; }
javascript
{ "resource": "" }
q26683
loadInternal
train
function loadInternal(index, arr) { ngDevMode && assertDataInRangeInternal(index + HEADER_OFFSET, arr); return arr[index + HEADER_OFFSET]; }
javascript
{ "resource": "" }
q26684
getChildLNode
train
function getChildLNode(node) { if (node.tNode.child) { var viewData = node.tNode.type === 2 /* View */ ? node.data : node.view; return readElementValue(viewData[node.tNode.child.index]); } return null; }
javascript
{ "resource": "" }
q26685
walkLNodeTree
train
function walkLNodeTree(startingNode, rootNode, action, renderer, renderParentNode, beforeNode) { var node = startingNode; var projectionNodeIndex = -1; while (node) { var nextNode = null; var parent_1 = renderParentNode ? renderParentNode.native : null; var nodeType = node.tNode.type; if (nodeType === 3 /* Element */) { // Execute the action executeNodeAction(action, renderer, parent_1, node.native, beforeNode); if (node.dynamicLContainerNode) { executeNodeAction(action, renderer, parent_1, node.dynamicLContainerNode.native, beforeNode); } } else if (nodeType === 0 /* Container */) { executeNodeAction(action, renderer, parent_1, node.native, beforeNode); var lContainerNode = node; var childContainerData = lContainerNode.dynamicLContainerNode ? lContainerNode.dynamicLContainerNode.data : lContainerNode.data; if (renderParentNode) { childContainerData[RENDER_PARENT] = renderParentNode; } nextNode = childContainerData[VIEWS].length ? getChildLNode(childContainerData[VIEWS][0]) : null; if (nextNode) { // When the walker enters a container, then the beforeNode has to become the local native // comment node. beforeNode = lContainerNode.dynamicLContainerNode ? lContainerNode.dynamicLContainerNode.native : lContainerNode.native; } } else if (nodeType === 1 /* Projection */) { var componentHost = findComponentHost(node.view); var head = componentHost.tNode.projection[node.tNode.projection]; projectionNodeStack[++projectionNodeIndex] = node; nextNode = head ? componentHost.data[PARENT][head.index] : null; } else { // Otherwise look at the first child nextNode = getChildLNode(node); } if (nextNode === null) { nextNode = getNextLNode(node); // this last node was projected, we need to get back down to its projection node if (nextNode === null && (node.tNode.flags & 8192 /* isProjected */)) { nextNode = getNextLNode(projectionNodeStack[projectionNodeIndex--]); } /** * Find the next node in the LNode tree, taking into account the place where a node is * projected (in the shadow DOM) rather than where it comes from (in the light DOM). * * If there is no sibling node, then it goes to the next sibling of the parent node... * until it reaches rootNode (at which point null is returned). */ while (node && !nextNode) { node = getParentLNode(node); if (node === null || node === rootNode) return null; // When exiting a container, the beforeNode must be restored to the previous value if (!node.tNode.next && nodeType === 0 /* Container */) { beforeNode = node.native; } nextNode = getNextLNode(node); } } node = nextNode; } }
javascript
{ "resource": "" }
q26686
destroyViewTree
train
function destroyViewTree(rootView) { // If the view has no children, we can clean it up and return early. if (rootView[TVIEW].childIndex === -1) { return cleanUpView(rootView); } var viewOrContainer = getLViewChild(rootView); while (viewOrContainer) { var next = null; if (viewOrContainer.length >= HEADER_OFFSET) { // If LViewData, traverse down to child. var view = viewOrContainer; if (view[TVIEW].childIndex > -1) next = getLViewChild(view); } else { // If container, traverse down to its first LViewData. var container = viewOrContainer; if (container[VIEWS].length) next = container[VIEWS][0].data; } if (next == null) { // Only clean up view when moving to the side or up, as destroy hooks // should be called in order from the bottom up. while (viewOrContainer && !viewOrContainer[NEXT] && viewOrContainer !== rootView) { cleanUpView(viewOrContainer); viewOrContainer = getParentState(viewOrContainer, rootView); } cleanUpView(viewOrContainer || rootView); next = viewOrContainer && viewOrContainer[NEXT]; } viewOrContainer = next; } }
javascript
{ "resource": "" }
q26687
insertView
train
function insertView(container, viewNode, index) { var state = container.data; var views = state[VIEWS]; var lView = viewNode.data; if (index > 0) { // This is a new view, we need to add it to the children. views[index - 1].data[NEXT] = lView; } if (index < views.length) { lView[NEXT] = views[index].data; views.splice(index, 0, viewNode); } else { views.push(viewNode); lView[NEXT] = null; } // Dynamically inserted views need a reference to their parent container'S host so it's // possible to jump from a view to its container's next when walking the node tree. if (viewNode.tNode.index === -1) { lView[CONTAINER_INDEX] = container.tNode.parent.index; viewNode.view = container.view; } // Notify query that a new view has been added if (lView[QUERIES]) { lView[QUERIES].insertView(index); } // Sets the attached flag lView[FLAGS] |= 8 /* Attached */; return viewNode; }
javascript
{ "resource": "" }
q26688
detachView
train
function detachView(container, removeIndex) { var views = container.data[VIEWS]; var viewNode = views[removeIndex]; if (removeIndex > 0) { views[removeIndex - 1].data[NEXT] = viewNode.data[NEXT]; } views.splice(removeIndex, 1); if (!container.tNode.detached) { addRemoveViewFromContainer(container, viewNode, false); } // Notify query that view has been removed var removedLView = viewNode.data; if (removedLView[QUERIES]) { removedLView[QUERIES].removeView(); } removedLView[CONTAINER_INDEX] = -1; viewNode.view = null; // Unsets the attached flag viewNode.data[FLAGS] &= ~8 /* Attached */; return viewNode; }
javascript
{ "resource": "" }
q26689
removeView
train
function removeView(container, removeIndex) { var viewNode = container.data[VIEWS][removeIndex]; detachView(container, removeIndex); destroyLView(viewNode.data); return viewNode; }
javascript
{ "resource": "" }
q26690
getLViewChild
train
function getLViewChild(viewData) { if (viewData[TVIEW].childIndex === -1) return null; var hostNode = viewData[viewData[TVIEW].childIndex]; return hostNode.data ? hostNode.data : hostNode.dynamicLContainerNode.data; }
javascript
{ "resource": "" }
q26691
getParentState
train
function getParentState(state, rootView) { var node; if ((node = state[HOST_NODE]) && node.tNode.type === 2 /* View */) { // if it's an embedded view, the state needs to go up to the container, in case the // container has a next return getParentLNode(node).data; } else { // otherwise, use parent view for containers or component views return state[PARENT] === rootView ? null : state[PARENT]; } }
javascript
{ "resource": "" }
q26692
cleanUpView
train
function cleanUpView(viewOrContainer) { if (viewOrContainer[TVIEW]) { var view = viewOrContainer; removeListeners(view); executeOnDestroys(view); executePipeOnDestroys(view); // For component views only, the local renderer is destroyed as clean up time. if (view[TVIEW].id === -1 && isProceduralRenderer(view[RENDERER])) { ngDevMode && ngDevMode.rendererDestroy++; view[RENDERER].destroy(); } } }
javascript
{ "resource": "" }
q26693
removeListeners
train
function removeListeners(viewData) { var cleanup = viewData[TVIEW].cleanup; if (cleanup != null) { for (var i = 0; i < cleanup.length - 1; i += 2) { if (typeof cleanup[i] === 'string') { // This is a listener with the native renderer var native = readElementValue(viewData[cleanup[i + 1]]).native; var listener = viewData[CLEANUP][cleanup[i + 2]]; native.removeEventListener(cleanup[i], listener, cleanup[i + 3]); i += 2; } else if (typeof cleanup[i] === 'number') { // This is a listener with renderer2 (cleanup fn can be found by index) var cleanupFn = viewData[CLEANUP][cleanup[i]]; cleanupFn(); } else { // This is a cleanup function that is grouped with the index of its context var context = viewData[CLEANUP][cleanup[i + 1]]; cleanup[i].call(context); } } viewData[CLEANUP] = null; } }
javascript
{ "resource": "" }
q26694
executeOnDestroys
train
function executeOnDestroys(view) { var tView = view[TVIEW]; var destroyHooks; if (tView != null && (destroyHooks = tView.destroyHooks) != null) { callHooks(view[DIRECTIVES], destroyHooks); } }
javascript
{ "resource": "" }
q26695
executePipeOnDestroys
train
function executePipeOnDestroys(viewData) { var pipeDestroyHooks = viewData[TVIEW] && viewData[TVIEW].pipeDestroyHooks; if (pipeDestroyHooks) { callHooks(viewData, pipeDestroyHooks); } }
javascript
{ "resource": "" }
q26696
canInsertNativeNode
train
function canInsertNativeNode(parent, currentView) { // We can only insert into a Component or View. Any other type should be an Error. ngDevMode && assertNodeOfPossibleTypes(parent, 3 /* Element */, 2 /* View */); if (parent.tNode.type === 3 /* Element */) { // Parent is an element. if (parent.view !== currentView) { // If the Parent view is not the same as current view than we are inserting across // Views. This happens when we insert a root element of the component view into // the component host element and it should always be eager. return true; } // Parent elements can be a component which may have projection. if (parent.data === null) { // Parent is a regular non-component element. We should eagerly insert into it // since we know that this relationship will never be broken. return true; } else { // Parent is a Component. Component's content nodes are not inserted immediately // because they will be projected, and so doing insert at this point would be wasteful. // Since the projection would than move it to its final destination. return false; } } else { // Parent is a View. ngDevMode && assertNodeType(parent, 2 /* View */); // Because we are inserting into a `View` the `View` may be disconnected. var grandParentContainer = getParentLNode(parent); if (grandParentContainer == null) { // The `View` is not inserted into a `Container` we have to delay insertion. return false; } ngDevMode && assertNodeType(grandParentContainer, 0 /* Container */); if (grandParentContainer.data[RENDER_PARENT] == null) { // The parent `Container` itself is disconnected. So we have to delay. return false; } else { // The parent `Container` is in inserted state, so we can eagerly insert into // this location. return true; } } }
javascript
{ "resource": "" }
q26697
appendChild
train
function appendChild(parent, child, currentView) { if (child !== null && canInsertNativeNode(parent, currentView)) { var renderer = currentView[RENDERER]; if (parent.tNode.type === 2 /* View */) { var container = getParentLNode(parent); var renderParent = container.data[RENDER_PARENT]; var views = container.data[VIEWS]; var index = views.indexOf(parent); var beforeNode = index + 1 < views.length ? (getChildLNode(views[index + 1])).native : container.native; isProceduralRenderer(renderer) ? renderer.insertBefore(renderParent.native, child, beforeNode) : renderParent.native.insertBefore(child, beforeNode, true); } else { isProceduralRenderer(renderer) ? renderer.appendChild(parent.native, child) : parent.native.appendChild(child); } return true; } return false; }
javascript
{ "resource": "" }
q26698
removeChild
train
function removeChild(parent, child, currentView) { if (child !== null && canInsertNativeNode(parent, currentView)) { // We only remove the element if not in View or not projected. var renderer = currentView[RENDERER]; isProceduralRenderer(renderer) ? renderer.removeChild(parent.native, child) : parent.native.removeChild(child); return true; } return false; }
javascript
{ "resource": "" }
q26699
appendProjectedNode
train
function appendProjectedNode(node, currentParent, currentView, renderParent) { appendChild(currentParent, node.native, currentView); if (node.tNode.type === 0 /* Container */) { // The node we are adding is a container and we are adding it to an element which // is not a component (no more re-projection). // Alternatively a container is projected at the root of a component's template // and can't be re-projected (as not content of any component). // Assign the final projection location in those cases. var lContainer = node.data; lContainer[RENDER_PARENT] = renderParent; var views = lContainer[VIEWS]; for (var i = 0; i < views.length; i++) { addRemoveViewFromContainer(node, views[i], true, node.native); } } if (node.dynamicLContainerNode) { node.dynamicLContainerNode.data[RENDER_PARENT] = renderParent; appendChild(currentParent, node.dynamicLContainerNode.native, currentView); } }
javascript
{ "resource": "" }