_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q24600
RenderingGroup
train
function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) { if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; } if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; } if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; } this.index = index; this._opaqueSubMeshes = new BABYLON.SmartArray(256); this._transparentSubMeshes = new BABYLON.SmartArray(256); this._alphaTestSubMeshes = new BABYLON.SmartArray(256); this._depthOnlySubMeshes = new BABYLON.SmartArray(256); this._particleSystems = new BABYLON.SmartArray(256); this._spriteManagers = new BABYLON.SmartArray(256); this._edgesRenderers = new BABYLON.SmartArray(16); this._scene = scene; this.opaqueSortCompareFn = opaqueSortCompareFn; this.alphaTestSortCompareFn = alphaTestSortCompareFn; this.transparentSortCompareFn = transparentSortCompareFn; }
javascript
{ "resource": "" }
q24601
UniformBuffer
train
function UniformBuffer(engine, data, dynamic) { this._engine = engine; this._noUBO = !engine.supportsUniformBuffers; this._dynamic = dynamic; this._data = data || []; this._uniformLocations = {}; this._uniformSizes = {}; this._uniformLocationPointer = 0; this._needSync = false; if (this._noUBO) { this.updateMatrix3x3 = this._updateMatrix3x3ForEffect; this.updateMatrix2x2 = this._updateMatrix2x2ForEffect; this.updateFloat = this._updateFloatForEffect; this.updateFloat2 = this._updateFloat2ForEffect; this.updateFloat3 = this._updateFloat3ForEffect; this.updateFloat4 = this._updateFloat4ForEffect; this.updateMatrix = this._updateMatrixForEffect; this.updateVector3 = this._updateVector3ForEffect; this.updateVector4 = this._updateVector4ForEffect; this.updateColor3 = this._updateColor3ForEffect; this.updateColor4 = this._updateColor4ForEffect; } else { this._engine._uniformBuffers.push(this); this.updateMatrix3x3 = this._updateMatrix3x3ForUniform; this.updateMatrix2x2 = this._updateMatrix2x2ForUniform; this.updateFloat = this._updateFloatForUniform; this.updateFloat2 = this._updateFloat2ForUniform; this.updateFloat3 = this._updateFloat3ForUniform; this.updateFloat4 = this._updateFloat4ForUniform; this.updateMatrix = this._updateMatrixForUniform; this.updateVector3 = this._updateVector3ForUniform; this.updateVector4 = this._updateVector4ForUniform; this.updateColor3 = this._updateColor3ForUniform; this.updateColor4 = this._updateColor4ForUniform; } }
javascript
{ "resource": "" }
q24602
ColorGradingTexture
train
function ColorGradingTexture(url, scene) { var _this = _super.call(this, scene) || this; if (!url) { return _this; } _this._textureMatrix = BABYLON.Matrix.Identity(); _this.name = url; _this.url = url; _this.hasAlpha = false; _this.isCube = false; _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE; _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; _this.anisotropicFilteringLevel = 1; _this._texture = _this._getFromCache(url, true); if (!_this._texture) { if (!scene.useDelayedTextureLoading) { _this.loadTexture(); } else { _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED; } } return _this; }
javascript
{ "resource": "" }
q24603
train
function (value) { if (this._transparencyMode === value) { return; } this._transparencyMode = value; if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) { this._forceAlphaTest = true; } else { this._forceAlphaTest = false; } this._markAllSubMeshesAsTexturesDirty(); }
javascript
{ "resource": "" }
q24604
PBRMetallicRoughnessMaterial
train
function PBRMetallicRoughnessMaterial(name, scene) { var _this = _super.call(this, name, scene) || this; _this._useRoughnessFromMetallicTextureAlpha = false; _this._useRoughnessFromMetallicTextureGreen = true; _this._useMetallnessFromMetallicTextureBlue = true; return _this; }
javascript
{ "resource": "" }
q24605
PBRSpecularGlossinessMaterial
train
function PBRSpecularGlossinessMaterial(name, scene) { var _this = _super.call(this, name, scene) || this; _this._useMicroSurfaceFromReflectivityMapAlpha = true; return _this; }
javascript
{ "resource": "" }
q24606
train
function (value) { var previousNeedCube = this.needCube(); this._direction = value; if (this.needCube() !== previousNeedCube && this._shadowGenerator) { this._shadowGenerator.recreateShadowMap(); } }
javascript
{ "resource": "" }
q24607
train
function () { for (var index = 0; index < this.actions.length; index++) { var action = this.actions[index]; if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) { return true; } } return false; }
javascript
{ "resource": "" }
q24608
train
function () { for (var t in ActionManager.Triggers) { if (ActionManager.Triggers.hasOwnProperty(t)) { var t_int = parseInt(t); if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) { return true; } } } return false; }
javascript
{ "resource": "" }
q24609
train
function (name, params) { var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype); newInstance.constructor.apply(newInstance, params); return newInstance; }
javascript
{ "resource": "" }
q24610
train
function (value) { if (this._intersectionThreshold === value) { return; } this._intersectionThreshold = value; if (this.geometry) { this.geometry.boundingBias = new BABYLON.Vector2(0, value); } }
javascript
{ "resource": "" }
q24611
getChildByName
train
function getChildByName(node, name) { return node.getChildMeshes(false, function (n) { return n.name === name; })[0]; }
javascript
{ "resource": "" }
q24612
getImmediateChildByName
train
function getImmediateChildByName(node, name) { return node.getChildMeshes(true, function (n) { return n.name == name; })[0]; }
javascript
{ "resource": "" }
q24613
train
function (subMesh) { var mesh = subMesh.getRenderingMesh(); if (_this._meshExcluded(mesh)) { return; } var scene = mesh.getScene(); var engine = scene.getEngine(); // Culling engine.setState(subMesh.getMaterial().backFaceCulling); // Managing instances var batch = mesh._getInstancesRenderList(subMesh._id); if (batch.mustReturn) { return; } var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null); if (_this.isReady(subMesh, hardwareInstancedRendering)) { var effect = _this._volumetricLightScatteringPass; if (mesh === _this.mesh) { if (subMesh.effect) { effect = subMesh.effect; } else { effect = subMesh.getMaterial().getEffect(); } } engine.enableEffect(effect); mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode); if (mesh === _this.mesh) { subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh); } else { var material = subMesh.getMaterial(); _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix()); // Alpha test if (material && material.needAlphaTesting()) { var alphaTexture = material.getAlphaTestTexture(); _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture); if (alphaTexture) { _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix()); } } // Bones if (mesh.useBones && mesh.computeBonesUsingShaders) { _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh)); } } // Draw mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); }); } }
javascript
{ "resource": "" }
q24614
train
function (v) { if (this._idealKernel === v) { return; } v = Math.max(v, 1); this._idealKernel = v; this._kernel = this._nearestBestKernel(v); this._updateParameters(); }
javascript
{ "resource": "" }
q24615
HDRCubeTexture
train
function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) { if (noMipmap === void 0) { noMipmap = false; } if (generateHarmonics === void 0) { generateHarmonics = true; } if (useInGammaSpace === void 0) { useInGammaSpace = false; } if (usePMREMGenerator === void 0) { usePMREMGenerator = false; } if (onLoad === void 0) { onLoad = null; } if (onError === void 0) { onError = null; } var _this = _super.call(this, scene) || this; _this._useInGammaSpace = false; _this._generateHarmonics = true; _this._isBABYLONPreprocessed = false; _this._onLoad = null; _this._onError = null; /** * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully. */ _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE; /** * Specifies wether the texture has been generated through the PMREMGenerator tool. * This is usefull at run time to apply the good shader. */ _this.isPMREM = false; _this._isBlocking = true; if (!url) { return _this; } _this.name = url; _this.url = url; _this.hasAlpha = false; _this.isCube = true; _this._textureMatrix = BABYLON.Matrix.Identity(); _this._onLoad = onLoad; _this._onError = onError; _this.gammaSpace = false; if (size) { _this._isBABYLONPreprocessed = false; _this._noMipmap = noMipmap; _this._size = size; _this._useInGammaSpace = useInGammaSpace; _this._usePMREMGenerator = usePMREMGenerator && scene.getEngine().getCaps().textureLOD && _this.getScene().getEngine().getCaps().textureFloat && !_this._useInGammaSpace; } else { _this._isBABYLONPreprocessed = true; _this._noMipmap = false; _this._useInGammaSpace = false; _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD && _this.getScene().getEngine().getCaps().textureFloat && !_this._useInGammaSpace; } _this.isPMREM = _this._usePMREMGenerator; _this._texture = _this._getFromCache(url, _this._noMipmap); if (!_this._texture) { if (!scene.useDelayedTextureLoading) { _this.loadTexture(); } else { _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED; } } return _this; }
javascript
{ "resource": "" }
q24616
zOrder
train
function zOrder(x, y, minX, minY, size) { // coords are transformed into non-negative 15-bit integer range x = 32767 * (x - minX) / size; y = 32767 * (y - minY) / size; x = (x | (x << 8)) & 0x00FF00FF; x = (x | (x << 4)) & 0x0F0F0F0F; x = (x | (x << 2)) & 0x33333333; x = (x | (x << 1)) & 0x55555555; y = (y | (y << 8)) & 0x00FF00FF; y = (y | (y << 4)) & 0x0F0F0F0F; y = (y | (y << 2)) & 0x33333333; y = (y | (y << 1)) & 0x55555555; return x | (y << 1); }
javascript
{ "resource": "" }
q24617
DynamicFloatArray
train
function DynamicFloatArray(stride, initialElementCount) { this.compareValueOffset = null; this.sortingAscending = true; this._stride = stride; this.buffer = new Float32Array(stride * initialElementCount); this._lastUsed = 0; this._firstFree = 0; this._allEntries = new Array(initialElementCount); this._freeEntries = new Array(initialElementCount); for (var i = 0; i < initialElementCount; i++) { var element = new DynamicFloatArrayElementInfo(); element.offset = i * stride; this._allEntries[i] = element; this._freeEntries[initialElementCount - i - 1] = element; } }
javascript
{ "resource": "" }
q24618
EdgesRenderer
train
function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) { if (epsilon === void 0) { epsilon = 0.95; } if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; } this.edgesWidthScalerForOrthographic = 1000.0; this.edgesWidthScalerForPerspective = 50.0; this._linesPositions = new Array(); this._linesNormals = new Array(); this._linesIndices = new Array(); this._buffers = {}; this._checkVerticesInsteadOfIndices = false; this._source = source; this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices; this._epsilon = epsilon; this._prepareRessources(); this._generateEdgesLines(); }
javascript
{ "resource": "" }
q24619
HighlightLayer
train
function HighlightLayer(name, scene, options) { this.name = name; this._vertexBuffers = {}; this._mainTextureDesiredSize = { width: 0, height: 0 }; this._meshes = {}; this._maxSize = 0; this._shouldRender = false; this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++; this._excludedMeshes = {}; /** * Specifies whether or not the inner glow is ACTIVE in the layer. */ this.innerGlow = true; /** * Specifies whether or not the outer glow is ACTIVE in the layer. */ this.outerGlow = true; /** * Specifies wether the highlight layer is enabled or not. */ this.isEnabled = true; /** * An event triggered when the highlight layer has been disposed. * @type {BABYLON.Observable} */ this.onDisposeObservable = new BABYLON.Observable(); /** * An event triggered when the highlight layer is about rendering the main texture with the glowy parts. * @type {BABYLON.Observable} */ this.onBeforeRenderMainTextureObservable = new BABYLON.Observable(); /** * An event triggered when the highlight layer is being blurred. * @type {BABYLON.Observable} */ this.onBeforeBlurObservable = new BABYLON.Observable(); /** * An event triggered when the highlight layer has been blurred. * @type {BABYLON.Observable} */ this.onAfterBlurObservable = new BABYLON.Observable(); /** * An event triggered when the glowing blurred texture is being merged in the scene. * @type {BABYLON.Observable} */ this.onBeforeComposeObservable = new BABYLON.Observable(); /** * An event triggered when the glowing blurred texture has been merged in the scene. * @type {BABYLON.Observable} */ this.onAfterComposeObservable = new BABYLON.Observable(); /** * An event triggered when the highlight layer changes its size. * @type {BABYLON.Observable} */ this.onSizeChangedObservable = new BABYLON.Observable(); this._scene = scene || BABYLON.Engine.LastCreatedScene; var engine = scene.getEngine(); this._engine = engine; this._maxSize = this._engine.getCaps().maxTextureSize; this._scene.highlightLayers.push(this); // Warn on stencil. if (!this._engine.isStencilEnable) { BABYLON.Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }"); } // Adapt options this._options = options || { mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE }; this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5; this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0; this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1; this._options.blurVerticalSize = this._options.blurVerticalSize || 1; this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE; // VBO var vertices = []; vertices.push(1, 1); vertices.push(-1, 1); vertices.push(-1, -1); vertices.push(1, -1); var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2); this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer; this._createIndexBuffer(); // Effect this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], ""); // Render target this.setMainTextureSize(); // Create Textures and post processes this.createTextureAndPostProcesses(); }
javascript
{ "resource": "" }
q24620
RectPackingMap
train
function RectPackingMap(size, margin) { if (margin === void 0) { margin = 0; } var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this; _this._margin = margin; _this._root = _this; return _this; }
javascript
{ "resource": "" }
q24621
train
function () { return this._attachedCamera.inertialAlphaOffset !== 0 || this._attachedCamera.inertialBetaOffset !== 0 || this._attachedCamera.inertialRadiusOffset !== 0 || this._attachedCamera.inertialPanningX !== 0 || this._attachedCamera.inertialPanningY !== 0 || this._isPointerDown; }
javascript
{ "resource": "" }
q24622
train
function (value) { var _this = this; if (this._autoTransitionRange === value) { return; } this._autoTransitionRange = value; var camera = this._attachedCamera; if (value) { this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) { if (!mesh) { return; } mesh.computeWorldMatrix(true); var diagonal = mesh.getBoundingInfo().diagonalLength; _this.lowerRadiusTransitionRange = diagonal * 0.05; _this.upperRadiusTransitionRange = diagonal * 0.05; }); } else if (this._onMeshTargetChangedObserver) { camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver); } }
javascript
{ "resource": "" }
q24623
drawScene
train
function drawScene() { // Clear the canvas before we start drawing on it. gl.clearColor(0, 0, 0, 1); gl.clearDepth(1.0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); // Establish the perspective with which we want to view the // scene. Our field of view is 45 degrees, with a width/height // ratio of 640:480, and we only want to see objects between 0.1 units // and 100 units away from the camera. perspectiveMatrix = makePerspective(45, 640.0/480.0, 0.1, 100.0); // Set the drawing position to the "identity" point, which is // the center of the scene. loadIdentity(); // Now move the drawing position a bit to where we want to start // drawing the cube. mvTranslate([-0.0, 0.0, -6.0]); // Save the current matrix, then rotate before we draw. mvPushMatrix(); mvRotate(cubeRotation, [1, 0, 1]); mvTranslate([cubeXOffset, cubeYOffset, cubeZOffset]); // Draw the cube by binding the array buffer to the cube's vertices // array, setting attributes, and pushing it to GL. gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesBuffer); gl.vertexAttribPointer(vertexPositionAttribute, 3, gl.FLOAT, false, 0, 0); // Draw the cube. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVerticesIndexBuffer); setMatrixUniforms(); var pUniform = gl.getUniformLocation(shaderProgram, "uniformArray"); gl.uniform2fv(pUniform, new Float32Array([1,0.2,0.4,1])); gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_SHORT, 0); // Restore the original matrix mvPopMatrix(); // Update the rotation for the next draw, if it's time to do so. var currentTime = (new Date).getTime(); if (lastCubeUpdateTime) { var delta = currentTime - lastCubeUpdateTime; cubeRotation += (30 * delta) / 1000.0; cubeXOffset += xIncValue * ((30 * delta) / 1000.0); cubeYOffset += yIncValue * ((30 * delta) / 1000.0); cubeZOffset += zIncValue * ((30 * delta) / 1000.0); if (Math.abs(cubeYOffset) > 2.5) { xIncValue = -xIncValue; yIncValue = -yIncValue; zIncValue = -zIncValue; } } lastCubeUpdateTime = currentTime; window.requestAnimationFrame(function() { drawScene(); }); }
javascript
{ "resource": "" }
q24624
initShaders
train
function initShaders() { var fragmentShader = getShader(gl, fragmentShaderSource, false); var vertexShader = getShader(gl, vertexShaderSource, true); // Create the shader program shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertexShader); gl.attachShader(shaderProgram, fragmentShader); gl.linkProgram(shaderProgram); // If creating the shader program failed, alert if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { alert("Unable to initialize the shader program: " + gl.getProgramInfoLog(shader)); } gl.useProgram(shaderProgram); vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition"); gl.enableVertexAttribArray(vertexPositionAttribute); }
javascript
{ "resource": "" }
q24625
createHttpTaskWithToken
train
async function createHttpTaskWithToken( project, location, queue, url, email, payload, inSeconds ) { // [START cloud_tasks_create_http_task_with_token] // Imports the Google Cloud Tasks library. const {v2beta3} = require('@google-cloud/tasks'); // Instantiates a client. const client = new v2beta3.CloudTasksClient(); // TODO(developer): Uncomment these lines and replace with your values. // const project = 'my-project-id'; // const queue = 'my-appengine-queue'; // const location = 'us-central1'; // const url = 'https://<project-id>.appspot.com/log_payload' // const email = 'client@<project-id>.iam.gserviceaccount.com' // const options = {payload: 'hello'}; // Construct the fully qualified queue name. const parent = client.queuePath(project, location, queue); const task = { httpRequest: { httpMethod: 'POST', url, //The full url path that the request will be sent to. oidcToken: { serviceAccountEmail: email, }, }, }; if (payload) { task.httpRequest.body = Buffer.from(payload).toString('base64'); } if (inSeconds) { task.scheduleTime = { seconds: inSeconds + Date.now() / 1000, }; } const request = { parent: parent, task: task, }; console.log('Sending task:'); console.log(task); // Send create task request. const [response] = await client.createTask(request); const name = response.name; console.log(`Created task ${name}`); // [END cloud_tasks_create_http_task_with_token] }
javascript
{ "resource": "" }
q24626
createQueue
train
async function createQueue( project = 'my-project-id', // Your GCP Project id queue = 'my-appengine-queue', // Name of the Queue to create location = 'us-central1' // The GCP region in which to create the queue ) { // Imports the Google Cloud Tasks library. const cloudTasks = require('@google-cloud/tasks'); // Instantiates a client. const client = new cloudTasks.CloudTasksClient(); // Send create queue request. const [response] = await client.createQueue({ // The fully qualified path to the location where the queue is created parent: client.locationPath(project, location), queue: { // The fully qualified path to the queue name: client.queuePath(project, location, queue), appEngineHttpQueue: { appEngineRoutingOverride: { // The App Engine service that will receive the tasks. service: 'default', }, }, }, }); console.log(`Created queue ${response.name}`); }
javascript
{ "resource": "" }
q24627
deleteQueue
train
async function deleteQueue( project = 'my-project-id', // Your GCP Project id queue = 'my-appengine-queue', // Name of the Queue to delete location = 'us-central1' // The GCP region in which to delete the queue ) { // Imports the Google Cloud Tasks library. const cloudTasks = require('@google-cloud/tasks'); // Instantiates a client. const client = new cloudTasks.CloudTasksClient(); // Get the fully qualified path to the queue const name = client.queuePath(project, location, queue); // Send delete queue request. await client.deleteQueue({name}); console.log(`Deleted queue '${queue}'.`); }
javascript
{ "resource": "" }
q24628
getColspanNum
train
function getColspanNum(data = [], num = 1) { let childs = []; for (let i = 0; i < data.length; i += 1) { if (data[i].children) { childs = childs.concat(data[i].children); } } if (childs && childs.length > 0) { num = getColspanNum(childs, num + 1); } return num; }
javascript
{ "resource": "" }
q24629
getRowspanNum
train
function getRowspanNum(data = [], child = []) { let childs = []; for (let i = 0; i < data.length; i += 1) { if (!data[i].children) { childs.push(data[i]); } else if (data[i].children && data[i].children.length > 0) { childs = childs.concat(getRowspanNum(data[i].children, child)); } } return childs; }
javascript
{ "resource": "" }
q24630
getSectionName
train
function getSectionName(article) { const { tiles } = article; if (!tiles) { return null; } const slices = tiles.reduce((acc, tile) => { acc.push(...tile.slices); return acc; }, []); const sections = slices.reduce((acc, slice) => { acc.push(...slice.sections); return acc; }, []); const titles = sections.map(section => section.title); if (titles.length === 0) { return null; } const nonNews = titles.filter(title => title !== "News"); return nonNews.length ? nonNews[0] : "News"; }
javascript
{ "resource": "" }
q24631
str_serialize
train
function str_serialize(result, key, value) { // encode newlines as \r\n cause the html spec says so value = value.replace(/(\r)?\n/g, '\r\n'); value = encodeURIComponent(value); // spaces should be '+' rather than '%20'. value = value.replace(/%20/g, '+'); return result + (result ? '&' : '') + encodeURIComponent(key) + '=' + value; }
javascript
{ "resource": "" }
q24632
sendBeacon
train
function sendBeacon(url, callback){ var self = this, img = document.createElement('img'), loaded = false; img.onload = function() { loaded = true; if ('naturalHeight' in this) { if (this.naturalHeight + this.naturalWidth === 0) { this.onerror(); return; } } else if (this.width + this.height === 0) { this.onerror(); return; } if (callback) { callback.call(self); } }; img.onerror = function() { loaded = true; if (callback) { callback.call(self, 'An error occurred!', null); } }; img.src = url + '&c=clv1'; }
javascript
{ "resource": "" }
q24633
mapNode
train
function mapNode(visitor) { const nodeMapper = node => { if (node == null) { return node; } const mappingFunction = (() => { if ('*' in visitor && typeof visitor['*'] === 'function') { return visitor['*']; } if (node.Type in visitor && typeof visitor[node.Type] === 'function') { return visitor[node.Type]; } return identity; })(); if (mappingFunction.length === 2) { return mappingFunction(node, nodeMapper); } const mappedNode = mappingFunction(node); const params = mappedNode.params.map(nodeMapper); return extend(mappedNode, { params }); }; return nodeMapper; }
javascript
{ "resource": "" }
q24634
makeLexer
train
function makeLexer() { const mooLexer = moo.compile(tokens); return { current: null, lines: [], get line() { return mooLexer.line; }, get col() { return mooLexer.col; }, save() { return mooLexer.save(); }, reset(chunk, info) { this.lines = chunk.split('\n'); return mooLexer.reset(chunk, info); }, next() { // It's a cruel and unusual punishment to implement comments with nearly let token = mooLexer.next(); // Drop all comment tokens found while (token && token.type === 'comment') { token = mooLexer.next(); } this.current = token; return this.current; }, formatError(token) { return mooLexer.formatError(token); }, has(name) { return mooLexer.has(name); }, }; }
javascript
{ "resource": "" }
q24635
parseImports
train
function parseImports(ast, compiler) { const imports = {}; let hasMemory = false; compiler.walkNode({ Import(node, _) { // Import nodes consist of field and a string literal node const [fields, module] = node.params; if (imports[module.value] == null) { imports[module.value] = []; } compiler.walkNode({ Pair(pair, __) { // Import pairs consist of identifier and type const [identifier, type] = pair.params; imports[module.value] = Array.from( new Set(imports[module.value].concat(identifier.value)) ); if (type.value === "Memory") { hasMemory = true; } }, })(fields); }, })(ast); return [imports, hasMemory]; }
javascript
{ "resource": "" }
q24636
buildTree
train
function buildTree(index, api) { const modules = {}; const dependency = (module, parent) => { const filepath = api.resolve(module, parent); if (modules[filepath] != null) { return modules[filepath]; } const src = api.getFileContents(module, parent, "utf8"); const basic = api.parser(src); const [nestedImports, hasMemory] = parseImports(basic, api); const deps = {}; Object.keys(nestedImports).forEach(mod => { if (mod.indexOf(".") === 0) { const dep = dependency(mod, filepath); deps[mod] = dep; } }); const patched = inferImportTypes(basic, deps, api); const ast = api.semantics(patched); api.validate(ast, { lines: src.split("\n"), filename: module.split("/").pop(), }); const result = { ast, deps, filepath, hasMemory, }; modules[filepath] = result; return result; }; const root = dependency(index, null); return { root, modules, }; }
javascript
{ "resource": "" }
q24637
build
train
function build(importsObj, tree) { const modules = {}; const instantiate = filepath => { if (modules[filepath] != null) { return modules[filepath]; } const mod = tree.modules[filepath]; const promise = Promise.all( Object.entries(mod.deps).map(([key, dep]) => { return instantiate(dep.filepath).then(result => [key, result]); }) ) .then(importsMap => { const imports = importsMap.reduce((acc, [key, module]) => { acc[key] = module.instance.exports; return acc; }, {}); return WebAssembly.instantiate( tree.opcodes[filepath], Object.assign({}, imports, importsObj) ); }) .catch(e => { // TODO: do some logging here throw e; }); modules[filepath] = promise; return promise; }; modules[tree.root.filepath] = instantiate(tree.root.filepath); return modules[tree.root.filepath]; }
javascript
{ "resource": "" }
q24638
_getHost
train
function _getHost (fauxton_ip) { if (fauxton_ip) { return fauxton_ip; } //making some assumptions here const interfaces = os.networkInterfaces(); const eth0 = interfaces[Object.keys(interfaces)[1]]; return eth0.find(function (item) { return item.family === 'IPv4'; }).address; }
javascript
{ "resource": "" }
q24639
train
function (options) { options = Object.assign({ msg: 'Notification Event Triggered!', type: 'info', escape: true, clear: false }, options); if (FauxtonAPI.reduxDispatch) { FauxtonAPI.reduxDispatch({ type: 'ADD_NOTIFICATION', options: { info: options } }); } }
javascript
{ "resource": "" }
q24640
train
function (carousel) { /** * Reference to the core. * @protected * @type {Owl} */ this.owl = carousel; /** * All DOM elements for thumbnails * @protected * @type {Object} */ this._thumbcontent = []; /** * Instance identiefier * @type {number} * @private */ this._identifier = 0; /** * Return current item regardless of clones * @protected * @type {Object} */ this.owl_currentitem = this.owl.options.startPosition; /** * The carousel element. * @type {jQuery} */ this.$element = this.owl.$element; /** * All event handlers. * @protected * @type {Object} */ this._handlers = { 'prepared.owl.carousel': $.proxy(function (e) { if (e.namespace && this.owl.options.thumbs && !this.owl.options.thumbImage && !this.owl.options.thumbsPrerendered && !this.owl.options.thumbImage) { if ($(e.content).find('[data-thumb]').attr('data-thumb') !== undefined) { this._thumbcontent.push($(e.content).find('[data-thumb]').attr('data-thumb')); } } else if (e.namespace && this.owl.options.thumbs && this.owl.options.thumbImage) { var innerImage = $(e.content).find('img'); this._thumbcontent.push(innerImage); } }, this), 'initialized.owl.carousel': $.proxy(function (e) { if (e.namespace && this.owl.options.thumbs) { this.render(); this.listen(); this._identifier = this.owl.$element.data('slider-id'); this.setActive(); } }, this), 'changed.owl.carousel': $.proxy(function (e) { if (e.namespace && e.property.name === 'position' && this.owl.options.thumbs) { this._identifier = this.owl.$element.data('slider-id'); this.setActive(); } }, this) }; // set default options this.owl.options = $.extend({}, Thumbs.Defaults, this.owl.options); // register the event handlers this.owl.$element.on(this._handlers); }
javascript
{ "resource": "" }
q24641
showWarning
train
function showWarning() { var method = showWarning.caller.name; if (!configurations.areTestsRunnning()) { console.warn('This method (' + method + ') is deprecated and its going to be removed on next versions'); } }
javascript
{ "resource": "" }
q24642
sandboxMode
train
function sandboxMode(enabled) { showWarning(); configurations.sandbox = (enabled !== undefined) ? (enabled === true) : configurations.sandbox; }
javascript
{ "resource": "" }
q24643
getAccessToken
train
function getAccessToken() { var callback = preConditions.getCallback(arguments[arguments.length - 1]); showWarning(); return requestManager.generateAccessToken(callback); }
javascript
{ "resource": "" }
q24644
createPreference
train
function createPreference(preferences) { var callback = preConditions.getCallback(arguments[arguments.length - 1]); showWarning(); return preferencesModule.create(preferences, callback); }
javascript
{ "resource": "" }
q24645
getPreference
train
function getPreference(id) { var callback = preConditions.getCallback(arguments[arguments.length - 1]); showWarning(); return preferencesModule.get(id, callback); }
javascript
{ "resource": "" }
q24646
createPreapprovalPayment
train
function createPreapprovalPayment(preapproval) { var callback = preConditions.getCallback(arguments[arguments.length - 1]); showWarning(); return preapprovalModule.create(preapproval, callback); }
javascript
{ "resource": "" }
q24647
getPreapprovalPayment
train
function getPreapprovalPayment(id) { var callback = preConditions.getCallback(arguments[arguments.length - 1]); showWarning(); return preapprovalModule.get(id, callback); }
javascript
{ "resource": "" }
q24648
cancelPreapprovalPayment
train
function cancelPreapprovalPayment(id) { var callback = preConditions.getCallback(arguments[arguments.length - 1]); showWarning(); return preapprovalModule.update({ id: id, status: 'cancelled' }, callback); }
javascript
{ "resource": "" }
q24649
train
function (resolve, reject, callback) { callback = preConditions.getCallback(callback); return requestManager.generateAccessToken().then(function () { return requestManager.exec(execOptions); }).then(function (response) { resolve(response); return callback.apply(null, [null, response]); }).catch(function (err) { reject(err); return callback.apply(null, [err, null]); }); }
javascript
{ "resource": "" }
q24650
setCSS
train
function setCSS(el, properties) { var key; for (key in properties) { if (properties.hasOwnProperty(key)) { el.style[key] = properties[key]; } } }
javascript
{ "resource": "" }
q24651
bulkUpdateCSS
train
function bulkUpdateCSS(data, callback) { executeNextFrame(function () { var i, item; for (i = 0; i < data.length; i++) { item = data[i]; setCSS(item.el, item.css); } // Run optional callback if (typeof callback === 'function') { executeNextFrame(callback); } }); }
javascript
{ "resource": "" }
q24652
getData
train
function getData(el, attr, isInt, prefix) { if (prefix === undefined) { prefix = 'wookmark-'; } var val = el.getAttribute('data-' + prefix + attr); if (isInt === true) { return parseInt(val, 10); } return val; }
javascript
{ "resource": "" }
q24653
setData
train
function setData(el, attr, val, prefix) { if (prefix === undefined) { prefix = 'wookmark-'; } el.setAttribute('data-' + prefix + attr, val); }
javascript
{ "resource": "" }
q24654
removeDuplicates
train
function removeDuplicates(items) { var temp = {}, result = [], x, i = items.length; while (i--) { x = getData(items[i], 'id', true); if (!temp.hasOwnProperty(x)) { temp[x] = 1; result.push(items[i]); } } return result; }
javascript
{ "resource": "" }
q24655
indexOf
train
function indexOf(items, item) { var len = items.length, i; for (i = 0; i < len; i++) { if (items[i] === item) { return i; } } return -1; }
javascript
{ "resource": "" }
q24656
renderCLI
train
function renderCLI ({ url, status, time, size }) { return logUpdate(boxen( `${chalk.bgBlue.black(' HEML ')}\n\n` + `- ${chalk.bold('Preview:')} ${url}\n` + `- ${chalk.bold('Status:')} ${status}\n` + `- ${chalk.bold('Compile time:')} ${time}ms\n` + `- ${chalk.bold('Total size:')} ${size}`, { padding: 1, margin: 1 })) }
javascript
{ "resource": "" }
q24657
startDevServer
train
function startDevServer (directory, port = 3000) { let url const app = express() const { reload } = reloadServer(app) let preview = '' app.get('/', (req, res) => res.send(preview)) app.use(express.static(directory)) function update ({ html, errors, metadata }) { let status = errors.length ? chalk.red('failed') : chalk.green('success') preview = errors.length ? buildErrorPage(errors) : html.replace('</body>', '<script src="/reload/reload.js"></script></body>') renderCLI({ url, status, time: metadata.time, size: metadata.size }) reload() } return new Promise((resolve, reject) => { getPort({ port }).then((availablePort) => { url = `http://localhost:${availablePort}` app.listen(availablePort, () => resolve({ update, url, app })) }) process.on('uncaughtException', reject) }) }
javascript
{ "resource": "" }
q24658
heml
train
async function heml (contents, options = {}) { const results = {} const { beautify: beautifyOptions = {}, validate: validateOption = 'soft' } = options options.elements = flattenDeep(toArray(coreElements).concat(options.elements || [])) /** parse it ✂️ */ const $heml = parse(contents, options) /** validate it 🕵 */ const errors = validate($heml, options) if (validateOption.toLowerCase() === 'strict' && errors.length > 0) { throw errors[0] } if (validateOption.toLowerCase() === 'soft') { results.errors = errors } /** render it 🤖 */ const { $: $html, metadata } = await render($heml, options) /** inline it ✍️ */ inline($html, options) /** beautify it 💅 */ results.html = condition.replace(beautify($html.html(), { indent_size: 2, indent_inner_html: true, preserve_newlines: false, extra_liners: [], ...beautifyOptions })) /** final touches 👌 */ metadata.size = `${(byteLength(results.html) / 1024).toFixed(2)}kb` results.metadata = metadata /** send it back 🎉 */ return results }
javascript
{ "resource": "" }
q24659
replaceElementTagMentions
train
function replaceElementTagMentions (element, selector) { const processor = selectorParser((selectors) => { let nodesToReplace = [] /** * looping breaks if we replace dynamically * so instead collect an array of nodes to swap and do it at the end */ selectors.walk((node) => { if (node.value === element.tag && node.type === 'tag') { nodesToReplace.push(node) } }) nodesToReplace.forEach((node) => node.replaceWith(element.pseudos.root)) }) return processor.process(selector).result }
javascript
{ "resource": "" }
q24660
replaceElementPseudoMentions
train
function replaceElementPseudoMentions (element, selector) { const processor = selectorParser((selectors) => { let nodesToReplace = [] /** * looping breaks if we replace dynamically * so instead collect an array of nodes to swap and do it at the end */ selectors.each((selector) => { let onElementTag = false selector.each((node) => { if (node.type === 'tag' && node.value === element.tag) { onElementTag = true } else if (node.type === 'combinator') { onElementTag = false } else if (node.type === 'pseudo' && onElementTag) { const matchedPseudos = Object.entries(element.pseudos).filter(([ pseudo ]) => { return node.value.replace(/::?/, '') === pseudo }) if (matchedPseudos.length > 0) { const [, value] = matchedPseudos[0] nodesToReplace.push({ node, value }) } } }) }) nodesToReplace.forEach(({ node, value }) => node.replaceWith(` ${value}`)) }) return processor.process(selector).result }
javascript
{ "resource": "" }
q24661
expandElementRule
train
function expandElementRule (element, selectors = [], originalRule) { /** early return if we don't have any selectors */ if (selectors.length === 0) return [] let usedProps = [] let expandedRules = [] let defaultRules = [] /** create the base rule */ const baseRule = originalRule.clone() baseRule.selectors = selectors baseRule.selector = replaceElementTagMentions(element, baseRule.selector) /** create postcss rules for each element rule */ for (const [ ruleSelector, ruleDecls ] of Object.entries(element.rules)) { const isRoot = element.pseudos.root === ruleSelector const isDefault = element.defaults.includes(ruleSelector) const expandedRule = baseRule.clone() /** gather all rules that get decls be default */ if (isDefault) { defaultRules.push(expandedRule) } /** map all the selectors to target this rule selector */ if (!isRoot) { expandedRule.selectors = expandedRule.selectors.map((selector) => `${selector} ${ruleSelector}`) } /** strip any non whitelisted props, run tranforms, gather used props */ expandedRule.walkDecls((decl) => { const matchedRuleDecls = ruleDecls.filter(({ prop }) => prop.test(decl.prop)) if (matchedRuleDecls.length === 0) { return decl.remove() } usedProps.push(decl.prop) matchedRuleDecls.forEach(({ transform }) => transform(decl, originalRule)) }) expandedRules.push(expandedRule) } baseRule.walkDecls((decl) => { if (!usedProps.includes(decl.prop)) { defaultRules.forEach((defaultRule) => defaultRule.prepend(decl.clone())) } }) return expandedRules }
javascript
{ "resource": "" }
q24662
preRenderElements
train
async function preRenderElements (elements, globals) { for (let element of elements) { await element.preRender(globals) } }
javascript
{ "resource": "" }
q24663
postRenderElements
train
async function postRenderElements (elements, globals) { for (let element of elements) { await element.postRender(globals) } }
javascript
{ "resource": "" }
q24664
renderElements
train
async function renderElements (elements, globals) { const { $ } = globals const elementMap = keyBy(elements, 'tagName') const metaTagNames = filter(elements, { parent: [ 'head' ] }).map(({ tagName }) => tagName) const nonMetaTagNames = difference(elements.map(({ tagName }) => tagName), metaTagNames) const $nodes = [ ...$.findNodes(metaTagNames), /** Render the meta elements first to last */ ...$.findNodes(nonMetaTagNames).reverse() /** Render the elements last to first/outside to inside */ ] for (let $node of $nodes) { const element = elementMap[$node.prop('tagName').toLowerCase()] const contents = $node.html() const attrs = $node[0].attribs const renderedValue = await Promise.resolve(renderElement(element, attrs, contents)) $node.replaceWith(renderedValue.trim()) } }
javascript
{ "resource": "" }
q24665
findAtDecl
train
function findAtDecl (decls, prop) { const foundDecls = decls.filter((decl) => { return (isPlainObject(decl) && Object.keys(decl).length > 0 && Object.keys(decl)[0] === `@${prop}`) || decl === `@${prop}` }) if (foundDecls.length === 0) { return } const decl = foundDecls[0] return isPlainObject(decl) ? Object.values(decl)[0] : true }
javascript
{ "resource": "" }
q24666
toRegExp
train
function toRegExp (string) { if (isString(string) && string.startsWith('/') && string.lastIndexOf('/') !== 0) { const pattern = string.substr(1, string.lastIndexOf('/') - 1) const opts = string.substr(string.lastIndexOf('/') + 1).toLowerCase() return new RegExp(pattern, opts.includes('i') ? opts : `${opts}i`) } if (isString(string)) { return new RegExp(`^${escapeRegExp(string)}$`, 'i') } return string }
javascript
{ "resource": "" }
q24667
targetsTag
train
function targetsTag (selector) { const selectors = simpleSelectorParser.process(selector).res return selectors.filter((selector) => { let selectorNodes = selector.nodes.concat([]).reverse() // clone the array for (const node of selectorNodes) { if (node.type === 'cominator') { break } if (node.type === 'tag') { return true } } return false }).length > 0 }
javascript
{ "resource": "" }
q24668
targetsElementPseudo
train
function targetsElementPseudo (element, selector) { const selectors = simpleSelectorParser.process(selector).res return selectors.filter((selector) => { let selectorNodes = selector.nodes.concat([]).reverse() // clone the array for (const node of selectorNodes) { if (node.type === 'cominator') { break } if (node.type === 'pseudo' && node.value.replace(/::?/, '') in element.pseudos) { return true } if (node.type === 'tag' && node.value === element.tag) { break } } return false }).length > 0 }
javascript
{ "resource": "" }
q24669
appendElementSelector
train
function appendElementSelector (element, selector) { const processor = selectorParser((selectors) => { let combinatorNode = null /** * looping breaks if we insert dynamically */ selectors.each((selector) => { const elementNode = selectorParser.tag({ value: element.tag }) selector.walk((node) => { if (node.type === 'combinator') { combinatorNode = node } }) if (combinatorNode) { selector.insertAfter(combinatorNode, elementNode) } else { selector.prepend(elementNode) } }) }) return processor.process(selector).result }
javascript
{ "resource": "" }
q24670
inlineMargins
train
function inlineMargins ($) { $('table[style*=margin]').toNodes().forEach(($el) => { const { left, right } = getSideMargins($el.attr('style')) if (left === 'auto' && right === 'auto') { $el.attr('align', 'center') } else if (left === 'auto' && right !== 'auto') { $el.attr('align', 'right') } else if (left !== 'auto') { $el.attr('align', 'left') } }) }
javascript
{ "resource": "" }
q24671
getSideMargins
train
function getSideMargins (style) { const margins = compact(style.split(';')).map((decl) => { const split = decl.split(':') return { prop: first(split).trim().toLowerCase(), value: last(split).trim().toLowerCase() } }).filter(({ prop, value }) => prop.indexOf('margin') === 0) let left = 0 let right = 0 margins.forEach(({ prop, value }) => { if (prop === 'margin-left') { left = value return } if (prop === 'margin-right') { right = value return } if (prop === 'margin') { const values = value.split(' ').map((i) => i.trim()) switch (values.length) { case 1: right = first(values) left = first(values) break case 2: right = last(values) left = last(values) break case 3: right = nth(values, 1) left = nth(values, 1) break default: right = nth(values, 1) left = nth(values, 3) break } } }) return { left, right } }
javascript
{ "resource": "" }
q24672
createTextElement
train
function createTextElement (name, element = {}) { let classToAdd = '' const Tag = name if (/^h\d$/i.test(name)) { classToAdd = 'header' } else { classToAdd = 'text' } return createElement(name, merge({ attrs: true, rules: { [`.${name}.${classToAdd}`]: [ { '@pseudo': 'root' }, '@default', { display: transforms.trueHide() }, margin, background, border, borderRadius, text, font ] }, render (attrs, contents) { attrs.class += ` ${classToAdd} ${name}` return <Tag {...attrs}>{contents}</Tag> } }, element)) }
javascript
{ "resource": "" }
q24673
sumShards
train
function sumShards(store, cb) { exports.lazy(store.metaDb.createValueStream(), cb) .map(function(stream) { return stream.Shards.filter(function(shard) { return shard.SequenceNumberRange.EndingSequenceNumber == null }).length }) .sum(function(sum) { return cb(null, sum) }) }
javascript
{ "resource": "" }
q24674
onActFinished
train
function onActFinished(context, next) { const msg = context.response.payload // pass to act context if (msg) { context.request$ = msg.request || {} context.trace$ = msg.trace || {} context.meta$ = msg.meta || {} } // calculate request duration const now = Util.nowHrTime() const diff = now - context.trace$.timestamp context.trace$.duration = diff if (context._config.traceLog) { context.log = context.log.child({ tag: context._config.tag, requestId: context.request$.id, parentSpanId: context.trace$.parentSpanId, traceId: context.trace$.traceId, spanId: context.trace$.spanId }) context.log.info( { pattern: context.trace$.method, responseTime: context.trace$.duration }, 'Request completed' ) } else { context.log.info( { requestId: context.request$.id, pattern: context.trace$.method, responseTime: context.trace$.duration }, 'Request completed' ) } next() }
javascript
{ "resource": "" }
q24675
print
train
function print(tableContent) { for (let i = 0; i < tableContent.length; i += 1) { console.log(`dim: ${tableContent[i].qValue[0].qText} val: ${tableContent[i].qValue[1].qText}`); } }
javascript
{ "resource": "" }
q24676
emptyObject
train
function emptyObject(obj) { Object.keys(obj).forEach((key) => { const config = Object.getOwnPropertyDescriptor(obj, key); if (config.configurable && !isSpecialProperty(obj, key)) { delete obj[key]; } }); }
javascript
{ "resource": "" }
q24677
compare
train
function compare(a, b) { let isIdentical = true; if (isObject(a) && isObject(b)) { if (Object.keys(a).length !== Object.keys(b).length) { return false; } Object.keys(a).forEach((key) => { if (!compare(a[key], b[key])) { isIdentical = false; } }); return isIdentical; } if (isArray(a) && isArray(b)) { if (a.length !== b.length) { return false; } for (let i = 0, l = a.length; i < l; i += 1) { if (!compare(a[i], b[i])) { return false; } } return true; } return a === b; }
javascript
{ "resource": "" }
q24678
patchArray
train
function patchArray(original, newA, basePath) { let patches = []; const oldA = original.slice(); let tmpIdx = -1; function findIndex(a, id, idx) { if (a[idx] && isUndef(a[idx].qInfo)) { return null; } if (a[idx] && a[idx].qInfo.qId === id) { // shortcut if identical return idx; } for (let ii = 0, ll = a.length; ii < ll; ii += 1) { if (a[ii] && a[ii].qInfo.qId === id) { return ii; } } return -1; } if (compare(newA, oldA)) { // array is unchanged return patches; } if (!isUndef(newA[0]) && isUndef(newA[0].qInfo)) { // we cannot create patches without unique identifiers, replace array... patches.push({ op: 'replace', path: basePath, value: newA, }); return patches; } for (let i = oldA.length - 1; i >= 0; i -= 1) { tmpIdx = findIndex(newA, oldA[i].qInfo && oldA[i].qInfo.qId, i); if (tmpIdx === -1) { patches.push({ op: 'remove', path: `${basePath}/${i}`, }); oldA.splice(i, 1); } else { patches = patches.concat(JSONPatch.generate(oldA[i], newA[tmpIdx], `${basePath}/${i}`)); } } for (let i = 0, l = newA.length; i < l; i += 1) { tmpIdx = findIndex(oldA, newA[i].qInfo && newA[i].qInfo.qId); if (tmpIdx === -1) { patches.push({ op: 'add', path: `${basePath}/${i}`, value: newA[i], }); oldA.splice(i, 0, newA[i]); } else if (tmpIdx !== i) { patches.push({ op: 'move', path: `${basePath}/${i}`, from: `${basePath}/${tmpIdx}`, }); oldA.splice(i, 0, oldA.splice(tmpIdx, 1)[0]); } } return patches; }
javascript
{ "resource": "" }
q24679
Eth
train
function Eth(cprovider, options) { if (!(this instanceof Eth)) { throw new Error('[ethjs] the Eth object requires you construct it with the "new" flag (i.e. `const eth = new Eth(...);`).'); } const self = this; self.options = options || {}; const query = new EthQuery(cprovider, self.options.query); Object.keys(Object.getPrototypeOf(query)).forEach((methodName) => { self[methodName] = (...args) => query[methodName].apply(query, args); }); self.filter = new EthFilter(query, self.options.query); self.contract = new EthContract(query, self.options.query); self.currentProvider = query.rpc.currentProvider; self.setProvider = query.setProvider; self.getTransactionSuccess = getTransactionSuccess(self); }
javascript
{ "resource": "" }
q24680
generateJsdocConfig
train
async function generateJsdocConfig({targetPath, tmpPath, namespace, projectName, version, variants}) { // Backlash needs to be escaped as double-backslash // This is not only relevant for win32 paths but also for // Unix directory names that contain a backslash in their name const backslashRegex = /\\/g; // Resolve path to this script to get the path to the JSDoc extensions folder const jsdocPath = path.normalize(__dirname); const pluginPath = path.join(jsdocPath, "lib", "ui5", "plugin.js").replace(backslashRegex, "\\\\"); const templatePath = path.join(jsdocPath, "lib", "ui5", "template").replace(backslashRegex, "\\\\"); const destinationPath = path.normalize(tmpPath).replace(backslashRegex, "\\\\"); const jsapiFilePath = path.join(targetPath, "libraries", projectName + ".js").replace(backslashRegex, "\\\\"); const apiJsonFolderPath = path.join(tmpPath, "dependency-apis").replace(backslashRegex, "\\\\"); const apiJsonFilePath = path.join(targetPath, "test-resources", path.normalize(namespace), "designtime", "api.json") .replace(backslashRegex, "\\\\"); const config = `{ "plugins": ["${pluginPath}"], "opts": { "recurse": true, "lenient": true, "template": "${templatePath}", "ui5": { "saveSymbols": true }, "destination": "${destinationPath}" }, "templates": { "ui5": { "variants": ${JSON.stringify(variants)}, "version": "${version}", "jsapiFile": "${jsapiFilePath}", "apiJsonFolder": "${apiJsonFolderPath}", "apiJsonFile": "${apiJsonFilePath}" } } }`; return config; }
javascript
{ "resource": "" }
q24681
writeJsdocConfig
train
async function writeJsdocConfig(targetDirPath, config) { const configPath = path.join(targetDirPath, "jsdoc-config.json"); await writeFile(configPath, config); return configPath; }
javascript
{ "resource": "" }
q24682
buildJsdoc
train
async function buildJsdoc({sourcePath, configPath}) { const args = [ require.resolve("jsdoc/jsdoc"), "-c", configPath, "--verbose", sourcePath ]; return new Promise((resolve, reject) => { const child = spawn("node", args, { stdio: ["ignore", "ignore", process.stderr] }); child.on("close", function(code) { if (code === 0 || code === 1) { resolve(); } else { reject(new Error(`JSDoc child process closed with code ${code}`)); } }); }); }
javascript
{ "resource": "" }
q24683
fromUI5LegacyName
train
function fromUI5LegacyName(name, suffix) { // UI5 only supports a few names with dots in them, anything else will be converted to slashes if ( name.startsWith("sap.ui.thirdparty.jquery.jquery-") ) { name = "sap/ui/thirdparty/jquery/jquery-" + name.slice("sap.ui.thirdparty.jquery.jquery-".length); } else if ( name.startsWith("jquery.sap.") || name.startsWith("jquery-") ) { // do nothing } else { name = name.replace(/\./g, "/"); } return name + (suffix || ".js"); }
javascript
{ "resource": "" }
q24684
addType
train
function addType(typeName, type) { if (types[typeName]) { throw new Error("Type already registered '" + typeName + "'"); } types[typeName] = type; }
javascript
{ "resource": "" }
q24685
train
async function({workspace, dependencies, options} = {}) { if (!options || !options.projectName || !options.namespace || !options.version || !options.pattern) { throw new Error("[generateJsdoc]: One or more mandatory options not provided"); } const {sourcePath: resourcePath, targetPath, tmpPath} = await generateJsdoc._createTmpDirs(options.projectName); const [writtenResourcesCount] = await Promise.all([ generateJsdoc._writeResourcesToDir({ workspace, pattern: options.pattern, targetPath: resourcePath }), generateJsdoc._writeDependencyApisToDir({ dependencies, targetPath: path.posix.join(tmpPath, "dependency-apis") }) ]); if (writtenResourcesCount === 0) { log.info(`Failed to find any input resources for project ${options.projectName} using pattern ` + `${options.pattern}. Skipping JSDoc generation...`); return; } const createdResources = await jsdocGenerator({ sourcePath: resourcePath, targetPath, tmpPath, options: { projectName: options.projectName, namespace: options.namespace, version: options.version, variants: ["apijson"] } }); await Promise.all(createdResources.map((resource) => { return workspace.write(resource); })); }
javascript
{ "resource": "" }
q24686
createTmpDirs
train
async function createTmpDirs(projectName) { const {path: tmpDirPath} = await createTmpDir(projectName); const sourcePath = path.join(tmpDirPath, "src"); // dir will be created by writing project resources below await makeDir(sourcePath, {fs}); const targetPath = path.join(tmpDirPath, "target"); // dir will be created by jsdoc itself await makeDir(targetPath, {fs}); const tmpPath = path.join(tmpDirPath, "tmp"); // dir needs to be created by us await makeDir(tmpPath, {fs}); return { sourcePath, targetPath, tmpPath }; }
javascript
{ "resource": "" }
q24687
createTmpDir
train
function createTmpDir(projectName, keep = false) { // Remove all non alpha-num characters from project name const sanitizedProjectName = projectName.replace(/[^A-Za-z0-9]/g, ""); return new Promise((resolve, reject) => { tmp.dir({ prefix: `ui5-tooling-tmp-jsdoc-${sanitizedProjectName}-`, keep, unsafeCleanup: true }, (err, path) => { if (err) { reject(err); return; } resolve({ path }); }); }); }
javascript
{ "resource": "" }
q24688
writeResourcesToDir
train
async function writeResourcesToDir({workspace, pattern, targetPath}) { const fsTarget = resourceFactory.createAdapter({ fsBasePath: targetPath, virBasePath: "/resources/" }); let allResources; if (workspace.byGlobSource) { // API only available on duplex collections allResources = await workspace.byGlobSource(pattern); } else { allResources = await workspace.byGlob(pattern); } // write all resources to the tmp folder await Promise.all(allResources.map((resource) => fsTarget.write(resource))); return allResources.length; }
javascript
{ "resource": "" }
q24689
writeDependencyApisToDir
train
async function writeDependencyApisToDir({dependencies, targetPath}) { const depApis = await dependencies.byGlob("/test-resources/**/designtime/api.json"); // Clone resources before changing their path const apis = await Promise.all(depApis.map((resource) => resource.clone())); for (let i = 0; i < apis.length; i++) { apis[i].setPath(`/api-${i}.json`); } const fsTarget = resourceFactory.createAdapter({ fsBasePath: targetPath, virBasePath: "/" }); await Promise.all(apis.map((resource) => fsTarget.write(resource))); return apis.length; }
javascript
{ "resource": "" }
q24690
getElapsedTime
train
function getElapsedTime(startTime) { const prettyHrtime = require("pretty-hrtime"); const timeDiff = process.hrtime(startTime); return prettyHrtime(timeDiff); }
javascript
{ "resource": "" }
q24691
composeTaskList
train
function composeTaskList({dev, selfContained, jsdoc, includedTasks, excludedTasks}) { let selectedTasks = Object.keys(definedTasks).reduce((list, key) => { list[key] = true; return list; }, {}); // Exclude non default tasks selectedTasks.generateManifestBundle = false; selectedTasks.generateStandaloneAppBundle = false; selectedTasks.transformBootstrapHtml = false; selectedTasks.generateJsdoc = false; selectedTasks.executeJsdocSdkTransformation = false; selectedTasks.generateCachebusterInfo = false; selectedTasks.generateApiIndex = false; if (selfContained) { // No preloads, bundle only selectedTasks.generateComponentPreload = false; selectedTasks.generateStandaloneAppBundle = true; selectedTasks.transformBootstrapHtml = true; selectedTasks.generateLibraryPreload = false; } if (jsdoc) { // Include JSDoc tasks selectedTasks.generateJsdoc = true; selectedTasks.executeJsdocSdkTransformation = true; selectedTasks.generateApiIndex = true; // Include theme build as required for SDK selectedTasks.buildThemes = true; // Exclude all tasks not relevant to JSDoc generation selectedTasks.replaceCopyright = false; selectedTasks.replaceVersion = false; selectedTasks.generateComponentPreload = false; selectedTasks.generateLibraryPreload = false; selectedTasks.generateLibraryManifest = false; selectedTasks.createDebugFiles = false; selectedTasks.uglify = false; selectedTasks.generateFlexChangesBundle = false; selectedTasks.generateManifestBundle = false; } // Only run essential tasks in development mode, it is not desired to run time consuming tasks during development. if (dev) { // Overwrite all other tasks with noop promise Object.keys(selectedTasks).forEach((key) => { if (devTasks.indexOf(key) === -1) { selectedTasks[key] = false; } }); } // Exclude tasks for (let i = 0; i < excludedTasks.length; i++) { const taskName = excludedTasks[i]; if (taskName === "*") { Object.keys(selectedTasks).forEach((sKey) => { selectedTasks[sKey] = false; }); break; } if (selectedTasks[taskName] !== false) { selectedTasks[taskName] = false; } } // Include tasks for (let i = 0; i < includedTasks.length; i++) { const taskName = includedTasks[i]; if (taskName === "*") { Object.keys(selectedTasks).forEach((sKey) => { selectedTasks[sKey] = true; }); break; } if (selectedTasks[taskName] === false) { selectedTasks[taskName] = true; } } // Filter only for tasks that will be executed selectedTasks = Object.keys(selectedTasks).filter((task) => selectedTasks[task]); return selectedTasks; }
javascript
{ "resource": "" }
q24692
registrationIds
train
function registrationIds() { const ids = []; for (const regid of findChildren(sapFioriAppData, "registrationId")) { ids.push(regid._); } return ids.length > 0 ? ids : undefined; }
javascript
{ "resource": "" }
q24693
createDependencyGraph
train
function createDependencyGraph(pool, moduleNames, indegreeOnly) { const graph = Object.create(null); const promises = moduleNames.map( (moduleName) => { return pool.getModuleInfo(moduleName). then( (module) => { let node = graph[moduleName]; if ( node == null ) { node = new GraphNode(moduleName, indegreeOnly); graph[moduleName] = node; } const p = module.dependencies.map( function(dep) { if ( module.isConditionalDependency(dep) ) { return; } return pool.getModuleInfo(dep).then( (depModule) => { if ( moduleNames.indexOf(dep) >= 0 ) { let depNode = graph[dep]; if ( depNode == null ) { depNode = new GraphNode(dep, indegreeOnly); graph[dep] = depNode; } node.outgoing.push(depNode); if ( indegreeOnly ) { depNode.indegree++; } else { depNode.incoming.push(node); } } }, (erro) => null); }); return Promise.all(p); }, (err) => { log.error("module %s not found in pool", moduleName); }); }); return Promise.all(promises).then(function() { // if ( trace.isTrace() ) trace.trace("initial module dependency graph: %s", dumpGraph(graph, moduleNames)); return graph; }); }
javascript
{ "resource": "" }
q24694
isString
train
function isString(node, literal) { if ( node == null || node.type !== Syntax.Literal || typeof node.value !== "string" ) { return false; } return literal == null ? true : node.value === literal; }
javascript
{ "resource": "" }
q24695
getStringArray
train
function getStringArray(array, skipNonStringLiterals) { return array.elements.reduce( (result, item) => { if ( isString(item) ) { result.push(item.value); } else if ( !skipNonStringLiterals ) { throw new TypeError("array element is not a string literal:" + item.type); } return result; }, []); }
javascript
{ "resource": "" }
q24696
copyFile
train
function copyFile(remotePath, targetRemotePath, options) { const copyOptions = merge(baseOptions, options || {}); return copy.copyFile(remotePath, targetRemotePath, copyOptions); }
javascript
{ "resource": "" }
q24697
createReadStream
train
function createReadStream(remoteFilename, options) { const createOptions = merge(baseOptions, options || {}); return createStream.createReadStream(remoteFilename, createOptions); }
javascript
{ "resource": "" }
q24698
createWriteStream
train
function createWriteStream(remoteFilename, options) { const createOptions = merge(baseOptions, options || {}); return createStream.createWriteStream(remoteFilename, createOptions); }
javascript
{ "resource": "" }
q24699
deleteFile
train
function deleteFile(remotePath, options) { const deleteOptions = merge(baseOptions, options || {}); return deletion.deleteFile(remotePath, deleteOptions); }
javascript
{ "resource": "" }