_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q62000
createItemString
test
function createItemString(data, limit) { var count = 0; var hasMore = false; if ((0, _isSafeInteger2['default'])(data.size)) { count = data.size; } else { for (var _iterator = data, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3['default'])(_iterator);;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var entry = _ref; // eslint-disable-line no-unused-vars if (limit && count + 1 > limit) { hasMore = true; break; } count += 1; } } return '' + (hasMore ? '>' : '') + count + ' ' + (count !== 1 ? 'entries' : 'entry'); }
javascript
{ "resource": "" }
q62001
kw
test
function kw(name, options = {}) { options.keyword = name return keywords[name] = new TokenType(name, options) }
javascript
{ "resource": "" }
q62002
isInAstralSet
test
function isInAstralSet(code, set) { let pos = 0x10000 for (let i = 0; i < set.length; i += 2) { pos += set[i] if (pos > code) return false pos += set[i + 1] if (pos >= code) return true } }
javascript
{ "resource": "" }
q62003
transformMetadata
test
function transformMetadata(metadata) { const namesRegEx = new RegExp( metadata.tokens.map(token => token.name).join('|'), 'g' ); const replaceMap = {}; metadata.tokens.map(token => { replaceMap[token.name] = formatTokenName(token.name); }); metadata.tokens.forEach((token, i) => { // interactive01 to `$interactive-01` if (token.role) { token.role.forEach((role, j) => { metadata.tokens[i].role[j] = role.replace(namesRegEx, match => { return '`$' + replaceMap[match] + '`'; }); }); } // brand01 to brand-01 if (token.alias) { token.alias = formatTokenName(token.alias); } }); return metadata; }
javascript
{ "resource": "" }
q62004
findPackageFor
test
async function findPackageFor(filepath) { let directory = filepath; while (directory !== '/') { const directoryToSearch = path.dirname(directory); const files = await fs.readdir(directoryToSearch); if (files.indexOf('package.json') !== -1) { const packageJson = await fs.readJson( path.join(directoryToSearch, 'package.json') ); return packageJson.name; } directory = path.resolve(directory, '..'); } throw new Error(`Unable to find package for: ${filepath}`); }
javascript
{ "resource": "" }
q62005
svgToggleClass
test
function svgToggleClass(svg, name, forceAdd) { const list = svg .getAttribute('class') .trim() .split(/\s+/); const uniqueList = Object.keys(list.reduce((o, item) => Object.assign(o, { [item]: 1 }), {})); const index = uniqueList.indexOf(name); const found = index >= 0; const add = forceAdd === undefined ? !found : forceAdd; if (found === !add) { if (add) { uniqueList.push(name); } else { uniqueList.splice(index, 1); } svg.setAttribute('class', uniqueList.join(' ')); } }
javascript
{ "resource": "" }
q62006
flatMapAsync
test
async function flatMapAsync(source, mapFn) { const results = await Promise.all(source.map(mapFn)); return results.reduce((acc, result) => acc.concat(result), []); }
javascript
{ "resource": "" }
q62007
createJson
test
async function createJson(sourceDir, config) { config = config || {}; return sassdoc.parse(sourceDir, config).then( data => { return data; }, err => { console.error(err); } ); }
javascript
{ "resource": "" }
q62008
dedupeArray
test
function dedupeArray(arr) { return arr.reduce( (p, item) => { const type = item.type || item.context.type; const name = item.name || item.context.name; const id = [type, name].join('|'); if (p.temp.indexOf(id) === -1) { p.out.push(item); p.temp.push(id); } return p; }, { temp: [], out: [] } ).out; }
javascript
{ "resource": "" }
q62009
createMarkdown
test
async function createMarkdown(sourceDir, config) { config = config || {}; return sassdoc.parse(sourceDir, config).then( data => { let markdownFile = ''; const documentedItems = data.filter( (item, index) => item.access === 'public' || item.access === 'private' ); markdownFile += `# Sass API | Mark | Description | | --- | --- | | ✅ | Public functions, mixins, placeholders, and variables | | ❌ | Private items - not supported outside package's build | | ⚠️ | Deprecated items - may not be available in future releases | <!-- toc --> <!-- tocstop -->`; let currentGroup = ''; documentedItems.forEach(item => { const itemGroup = createGroupName(item.group); if (itemGroup !== currentGroup) { markdownFile += `\n\n## ${itemGroup}`; currentGroup = itemGroup; } markdownFile += createMarkdownItem(item); }); return prettier.format( toc.insert(markdownFile, { slugify }), prettierOptions ); }, err => { console.error(err); } ); }
javascript
{ "resource": "" }
q62010
flattenOptions
test
function flattenOptions(options) { const o = {}; // eslint-disable-next-line guard-for-in, no-restricted-syntax for (const key in options) { o[key] = options[key]; } return o; }
javascript
{ "resource": "" }
q62011
append
test
function append(str, prefix = '') { const item = document.createElement('li'); item.textContent = prefix + str; list.appendChild(item); }
javascript
{ "resource": "" }
q62012
multiresNodeSort
test
function multiresNodeSort(a, b) { // Base tiles are always first if (a.level == 1 && b.level != 1) { return -1; } if (b. level == 1 && a.level != 1) { return 1; } // Higher timestamp first return b.timestamp - a.timestamp; }
javascript
{ "resource": "" }
q62013
multiresNodeRenderSort
test
function multiresNodeRenderSort(a, b) { // Lower zoom levels first if (a.level != b.level) { return a.level - b.level; } // Lower distance from center first return a.diff - b.diff; }
javascript
{ "resource": "" }
q62014
multiresDraw
test
function multiresDraw() { if (!program.drawInProgress) { program.drawInProgress = true; gl.clear(gl.COLOR_BUFFER_BIT); for ( var i = 0; i < program.currentNodes.length; i++ ) { if (program.currentNodes[i].textureLoaded > 1) { //var color = program.currentNodes[i].color; //gl.uniform4f(program.colorUniform, color[0], color[1], color[2], 1.0); // Bind vertex buffer and pass vertices to WebGL gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertBuf); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(program.currentNodes[i].vertices), gl.STATIC_DRAW); gl.vertexAttribPointer(program.vertPosLocation, 3, gl.FLOAT, false, 0, 0); // Prep for texture gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertTexCoordBuf); gl.vertexAttribPointer(program.texCoordLocation, 2, gl.FLOAT, false, 0, 0); // Bind texture and draw tile gl.bindTexture(gl.TEXTURE_2D, program.currentNodes[i].texture); // Bind program.currentNodes[i].texture to TEXTURE0 gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0); } } program.drawInProgress = false; } }
javascript
{ "resource": "" }
q62015
MultiresNode
test
function MultiresNode(vertices, side, level, x, y, path) { this.vertices = vertices; this.side = side; this.level = level; this.x = x; this.y = y; this.path = path.replace('%s',side).replace('%l',level).replace('%x',x).replace('%y',y); }
javascript
{ "resource": "" }
q62016
rotateMatrix
test
function rotateMatrix(m, angle, axis) { var s = Math.sin(angle); var c = Math.cos(angle); if (axis == 'x') { return [ m[0], c*m[1] + s*m[2], c*m[2] - s*m[1], m[3], c*m[4] + s*m[5], c*m[5] - s*m[4], m[6], c*m[7] + s*m[8], c*m[8] - s*m[7] ]; } if (axis == 'y') { return [ c*m[0] - s*m[2], m[1], c*m[2] + s*m[0], c*m[3] - s*m[5], m[4], c*m[5] + s*m[3], c*m[6] - s*m[8], m[7], c*m[8] + s*m[6] ]; } if (axis == 'z') { return [ c*m[0] + s*m[1], c*m[1] - s*m[0], m[2], c*m[3] + s*m[4], c*m[4] - s*m[3], m[5], c*m[6] + s*m[7], c*m[7] - s*m[6], m[8] ]; } }
javascript
{ "resource": "" }
q62017
makeMatrix4
test
function makeMatrix4(m) { return [ m[0], m[1], m[2], 0, m[3], m[4], m[5], 0, m[6], m[7], m[8], 0, 0, 0, 0, 1 ]; }
javascript
{ "resource": "" }
q62018
makePersp
test
function makePersp(hfov, aspect, znear, zfar) { var fovy = 2 * Math.atan(Math.tan(hfov/2) * gl.drawingBufferHeight / gl.drawingBufferWidth); var f = 1 / Math.tan(fovy/2); return [ f/aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, (zfar+znear)/(znear-zfar), (2*zfar*znear)/(znear-zfar), 0, 0, -1, 0 ]; }
javascript
{ "resource": "" }
q62019
processLoadedTexture
test
function processLoadedTexture(img, tex) { gl.bindTexture(gl.TEXTURE_2D, tex); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, img); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.bindTexture(gl.TEXTURE_2D, null); }
javascript
{ "resource": "" }
q62020
checkZoom
test
function checkZoom(hfov) { // Find optimal level var newLevel = 1; while ( newLevel < image.maxLevel && gl.drawingBufferWidth > image.tileResolution * Math.pow(2, newLevel - 1) * Math.tan(hfov / 2) * 0.707 ) { newLevel++; } // Apply change program.level = newLevel; }
javascript
{ "resource": "" }
q62021
rotatePersp
test
function rotatePersp(p, r) { return [ p[ 0]*r[0], p[ 0]*r[1], p[ 0]*r[ 2], 0, p[ 5]*r[4], p[ 5]*r[5], p[ 5]*r[ 6], 0, p[10]*r[8], p[10]*r[9], p[10]*r[10], p[11], -r[8], -r[9], -r[10], 0 ]; }
javascript
{ "resource": "" }
q62022
checkInView
test
function checkInView(m, v) { var vpp = applyRotPerspToVec(m, v); var winX = vpp[0]*vpp[3]; var winY = vpp[1]*vpp[3]; var winZ = vpp[2]*vpp[3]; var ret = [0, 0, 0]; if ( winX < -1 ) ret[0] = -1; if ( winX > 1 ) ret[0] = 1; if ( winY < -1 ) ret[1] = -1; if ( winY > 1 ) ret[1] = 1; if ( winZ < -1 || winZ > 1 ) ret[2] = 1; return ret; }
javascript
{ "resource": "" }
q62023
onImageLoad
test
function onImageLoad() { if (!renderer) renderer = new libpannellum.renderer(renderContainer); // Only add event listeners once if (!listenersAdded) { listenersAdded = true; dragFix.addEventListener('mousedown', onDocumentMouseDown, false); document.addEventListener('mousemove', onDocumentMouseMove, false); document.addEventListener('mouseup', onDocumentMouseUp, false); if (config.mouseZoom) { uiContainer.addEventListener('mousewheel', onDocumentMouseWheel, false); uiContainer.addEventListener('DOMMouseScroll', onDocumentMouseWheel, false); } if (config.doubleClickZoom) { dragFix.addEventListener('dblclick', onDocumentDoubleClick, false); } container.addEventListener('mozfullscreenchange', onFullScreenChange, false); container.addEventListener('webkitfullscreenchange', onFullScreenChange, false); container.addEventListener('msfullscreenchange', onFullScreenChange, false); container.addEventListener('fullscreenchange', onFullScreenChange, false); window.addEventListener('resize', onDocumentResize, false); window.addEventListener('orientationchange', onDocumentResize, false); if (!config.disableKeyboardCtrl) { container.addEventListener('keydown', onDocumentKeyPress, false); container.addEventListener('keyup', onDocumentKeyUp, false); container.addEventListener('blur', clearKeys, false); } document.addEventListener('mouseleave', onDocumentMouseUp, false); if (document.documentElement.style.pointerAction === '' && document.documentElement.style.touchAction === '') { dragFix.addEventListener('pointerdown', onDocumentPointerDown, false); dragFix.addEventListener('pointermove', onDocumentPointerMove, false); dragFix.addEventListener('pointerup', onDocumentPointerUp, false); dragFix.addEventListener('pointerleave', onDocumentPointerUp, false); } else { dragFix.addEventListener('touchstart', onDocumentTouchStart, false); dragFix.addEventListener('touchmove', onDocumentTouchMove, false); dragFix.addEventListener('touchend', onDocumentTouchEnd, false); } // Deal with MS pointer events if (window.navigator.pointerEnabled) container.style.touchAction = 'none'; } renderInit(); setHfov(config.hfov); // possibly adapt hfov after configuration and canvas is complete; prevents empty space on top or bottom by zomming out too much setTimeout(function(){isTimedOut = true;}, 500); }
javascript
{ "resource": "" }
q62024
test
function(tag) { var result; if (xmpData.indexOf(tag + '="') >= 0) { result = xmpData.substring(xmpData.indexOf(tag + '="') + tag.length + 2); result = result.substring(0, result.indexOf('"')); } else if (xmpData.indexOf(tag + '>') >= 0) { result = xmpData.substring(xmpData.indexOf(tag + '>') + tag.length + 1); result = result.substring(0, result.indexOf('<')); } if (result !== undefined) { return Number(result); } return null; }
javascript
{ "resource": "" }
q62025
anError
test
function anError(errorMsg) { if (errorMsg === undefined) errorMsg = config.strings.genericWebGLError; infoDisplay.errorMsg.innerHTML = '<p>' + errorMsg + '</p>'; controls.load.style.display = 'none'; infoDisplay.load.box.style.display = 'none'; infoDisplay.errorMsg.style.display = 'table'; error = true; renderContainer.style.display = 'none'; fireEvent('error', errorMsg); }
javascript
{ "resource": "" }
q62026
clearError
test
function clearError() { if (error) { infoDisplay.load.box.style.display = 'none'; infoDisplay.errorMsg.style.display = 'none'; error = false; fireEvent('errorcleared'); } }
javascript
{ "resource": "" }
q62027
aboutMessage
test
function aboutMessage(event) { var pos = mousePosition(event); aboutMsg.style.left = pos.x + 'px'; aboutMsg.style.top = pos.y + 'px'; clearTimeout(aboutMessage.t1); clearTimeout(aboutMessage.t2); aboutMsg.style.display = 'block'; aboutMsg.style.opacity = 1; aboutMessage.t1 = setTimeout(function() {aboutMsg.style.opacity = 0;}, 2000); aboutMessage.t2 = setTimeout(function() {aboutMsg.style.display = 'none';}, 2500); event.preventDefault(); }
javascript
{ "resource": "" }
q62028
mousePosition
test
function mousePosition(event) { var bounds = container.getBoundingClientRect(); var pos = {}; // pageX / pageY needed for iOS pos.x = (event.clientX || event.pageX) - bounds.left; pos.y = (event.clientY || event.pageY) - bounds.top; return pos; }
javascript
{ "resource": "" }
q62029
onDocumentMouseDown
test
function onDocumentMouseDown(event) { // Override default action event.preventDefault(); // But not all of it container.focus(); // Only do something if the panorama is loaded if (!loaded || !config.draggable) { return; } // Calculate mouse position relative to top left of viewer container var pos = mousePosition(event); // Log pitch / yaw of mouse click when debugging / placing hot spots if (config.hotSpotDebug) { var coords = mouseEventToCoords(event); console.log('Pitch: ' + coords[0] + ', Yaw: ' + coords[1] + ', Center Pitch: ' + config.pitch + ', Center Yaw: ' + config.yaw + ', HFOV: ' + config.hfov); } // Turn off auto-rotation if enabled stopAnimation(); stopOrientation(); config.roll = 0; speed.hfov = 0; isUserInteracting = true; latestInteraction = Date.now(); onPointerDownPointerX = pos.x; onPointerDownPointerY = pos.y; onPointerDownYaw = config.yaw; onPointerDownPitch = config.pitch; uiContainer.classList.add('pnlm-grabbing'); uiContainer.classList.remove('pnlm-grab'); fireEvent('mousedown', event); animateInit(); }
javascript
{ "resource": "" }
q62030
onDocumentDoubleClick
test
function onDocumentDoubleClick(event) { if (config.minHfov === config.hfov) { _this.setHfov(origHfov, 1000); } else { var coords = mouseEventToCoords(event); _this.lookAt(coords[0], coords[1], config.minHfov, 1000); } }
javascript
{ "resource": "" }
q62031
mouseEventToCoords
test
function mouseEventToCoords(event) { var pos = mousePosition(event); var canvas = renderer.getCanvas(); var canvasWidth = canvas.clientWidth, canvasHeight = canvas.clientHeight; var x = pos.x / canvasWidth * 2 - 1; var y = (1 - pos.y / canvasHeight * 2) * canvasHeight / canvasWidth; var focal = 1 / Math.tan(config.hfov * Math.PI / 360); var s = Math.sin(config.pitch * Math.PI / 180); var c = Math.cos(config.pitch * Math.PI / 180); var a = focal * c - y * s; var root = Math.sqrt(x*x + a*a); var pitch = Math.atan((y * c + focal * s) / root) * 180 / Math.PI; var yaw = Math.atan2(x / root, a / root) * 180 / Math.PI + config.yaw; if (yaw < -180) yaw += 360; if (yaw > 180) yaw -= 360; return [pitch, yaw]; }
javascript
{ "resource": "" }
q62032
onDocumentMouseMove
test
function onDocumentMouseMove(event) { if (isUserInteracting && loaded) { latestInteraction = Date.now(); var canvas = renderer.getCanvas(); var canvasWidth = canvas.clientWidth, canvasHeight = canvas.clientHeight; var pos = mousePosition(event); //TODO: This still isn't quite right var yaw = ((Math.atan(onPointerDownPointerX / canvasWidth * 2 - 1) - Math.atan(pos.x / canvasWidth * 2 - 1)) * 180 / Math.PI * config.hfov / 90) + onPointerDownYaw; speed.yaw = (yaw - config.yaw) % 360 * 0.2; config.yaw = yaw; var vfov = 2 * Math.atan(Math.tan(config.hfov/360*Math.PI) * canvasHeight / canvasWidth) * 180 / Math.PI; var pitch = ((Math.atan(pos.y / canvasHeight * 2 - 1) - Math.atan(onPointerDownPointerY / canvasHeight * 2 - 1)) * 180 / Math.PI * vfov / 90) + onPointerDownPitch; speed.pitch = (pitch - config.pitch) * 0.2; config.pitch = pitch; } }
javascript
{ "resource": "" }
q62033
onDocumentMouseUp
test
function onDocumentMouseUp(event) { if (!isUserInteracting) { return; } isUserInteracting = false; if (Date.now() - latestInteraction > 15) { // Prevents jump when user rapidly moves mouse, stops, and then // releases the mouse button speed.pitch = speed.yaw = 0; } uiContainer.classList.add('pnlm-grab'); uiContainer.classList.remove('pnlm-grabbing'); latestInteraction = Date.now(); fireEvent('mouseup', event); }
javascript
{ "resource": "" }
q62034
onDocumentTouchStart
test
function onDocumentTouchStart(event) { // Only do something if the panorama is loaded if (!loaded || !config.draggable) { return; } // Turn off auto-rotation if enabled stopAnimation(); stopOrientation(); config.roll = 0; speed.hfov = 0; // Calculate touch position relative to top left of viewer container var pos0 = mousePosition(event.targetTouches[0]); onPointerDownPointerX = pos0.x; onPointerDownPointerY = pos0.y; if (event.targetTouches.length == 2) { // Down pointer is the center of the two fingers var pos1 = mousePosition(event.targetTouches[1]); onPointerDownPointerX += (pos1.x - pos0.x) * 0.5; onPointerDownPointerY += (pos1.y - pos0.y) * 0.5; onPointerDownPointerDist = Math.sqrt((pos0.x - pos1.x) * (pos0.x - pos1.x) + (pos0.y - pos1.y) * (pos0.y - pos1.y)); } isUserInteracting = true; latestInteraction = Date.now(); onPointerDownYaw = config.yaw; onPointerDownPitch = config.pitch; fireEvent('touchstart', event); animateInit(); }
javascript
{ "resource": "" }
q62035
onDocumentTouchMove
test
function onDocumentTouchMove(event) { if (!config.draggable) { return; } // Override default action event.preventDefault(); if (loaded) { latestInteraction = Date.now(); } if (isUserInteracting && loaded) { var pos0 = mousePosition(event.targetTouches[0]); var clientX = pos0.x; var clientY = pos0.y; if (event.targetTouches.length == 2 && onPointerDownPointerDist != -1) { var pos1 = mousePosition(event.targetTouches[1]); clientX += (pos1.x - pos0.x) * 0.5; clientY += (pos1.y - pos0.y) * 0.5; var clientDist = Math.sqrt((pos0.x - pos1.x) * (pos0.x - pos1.x) + (pos0.y - pos1.y) * (pos0.y - pos1.y)); setHfov(config.hfov + (onPointerDownPointerDist - clientDist) * 0.1); onPointerDownPointerDist = clientDist; } // The smaller the config.hfov value (the more zoomed-in the user is), the faster // yaw/pitch are perceived to change on one-finger touchmove (panning) events and vice versa. // To improve usability at both small and large zoom levels (config.hfov values) // we introduce a dynamic pan speed coefficient. // // Currently this seems to *roughly* keep initial drag/pan start position close to // the user's finger while panning regardless of zoom level / config.hfov value. var touchmovePanSpeedCoeff = (config.hfov / 360) * config.touchPanSpeedCoeffFactor; var yaw = (onPointerDownPointerX - clientX) * touchmovePanSpeedCoeff + onPointerDownYaw; speed.yaw = (yaw - config.yaw) % 360 * 0.2; config.yaw = yaw; var pitch = (clientY - onPointerDownPointerY) * touchmovePanSpeedCoeff + onPointerDownPitch; speed.pitch = (pitch - config.pitch) * 0.2; config.pitch = pitch; } }
javascript
{ "resource": "" }
q62036
onDocumentMouseWheel
test
function onDocumentMouseWheel(event) { // Only do something if the panorama is loaded and mouse wheel zoom is enabled if (!loaded || (config.mouseZoom == 'fullscreenonly' && !fullscreenActive)) { return; } event.preventDefault(); // Turn off auto-rotation if enabled stopAnimation(); latestInteraction = Date.now(); if (event.wheelDeltaY) { // WebKit setHfov(config.hfov - event.wheelDeltaY * 0.05); speed.hfov = event.wheelDelta < 0 ? 1 : -1; } else if (event.wheelDelta) { // Opera / Explorer 9 setHfov(config.hfov - event.wheelDelta * 0.05); speed.hfov = event.wheelDelta < 0 ? 1 : -1; } else if (event.detail) { // Firefox setHfov(config.hfov + event.detail * 1.5); speed.hfov = event.detail > 0 ? 1 : -1; } animateInit(); }
javascript
{ "resource": "" }
q62037
onDocumentKeyPress
test
function onDocumentKeyPress(event) { // Turn off auto-rotation if enabled stopAnimation(); latestInteraction = Date.now(); stopOrientation(); config.roll = 0; // Record key pressed var keynumber = event.which || event.keycode; // Override default action for keys that are used if (config.capturedKeyNumbers.indexOf(keynumber) < 0) return; event.preventDefault(); // If escape key is pressed if (keynumber == 27) { // If in fullscreen mode if (fullscreenActive) { toggleFullscreen(); } } else { // Change key changeKey(keynumber, true); } }
javascript
{ "resource": "" }
q62038
onDocumentKeyUp
test
function onDocumentKeyUp(event) { // Record key pressed var keynumber = event.which || event.keycode; // Override default action for keys that are used if (config.capturedKeyNumbers.indexOf(keynumber) < 0) return; event.preventDefault(); // Change key changeKey(keynumber, false); }
javascript
{ "resource": "" }
q62039
changeKey
test
function changeKey(keynumber, value) { var keyChanged = false; switch(keynumber) { // If minus key is released case 109: case 189: case 17: case 173: if (keysDown[0] != value) { keyChanged = true; } keysDown[0] = value; break; // If plus key is released case 107: case 187: case 16: case 61: if (keysDown[1] != value) { keyChanged = true; } keysDown[1] = value; break; // If up arrow is released case 38: if (keysDown[2] != value) { keyChanged = true; } keysDown[2] = value; break; // If "w" is released case 87: if (keysDown[6] != value) { keyChanged = true; } keysDown[6] = value; break; // If down arrow is released case 40: if (keysDown[3] != value) { keyChanged = true; } keysDown[3] = value; break; // If "s" is released case 83: if (keysDown[7] != value) { keyChanged = true; } keysDown[7] = value; break; // If left arrow is released case 37: if (keysDown[4] != value) { keyChanged = true; } keysDown[4] = value; break; // If "a" is released case 65: if (keysDown[8] != value) { keyChanged = true; } keysDown[8] = value; break; // If right arrow is released case 39: if (keysDown[5] != value) { keyChanged = true; } keysDown[5] = value; break; // If "d" is released case 68: if (keysDown[9] != value) { keyChanged = true; } keysDown[9] = value; } if (keyChanged && value) { if (typeof performance !== 'undefined' && performance.now()) { prevTime = performance.now(); } else { prevTime = Date.now(); } animateInit(); } }
javascript
{ "resource": "" }
q62040
animateMove
test
function animateMove(axis) { var t = animatedMove[axis]; var normTime = Math.min(1, Math.max((Date.now() - t.startTime) / 1000 / (t.duration / 1000), 0)); var result = t.startPosition + config.animationTimingFunction(normTime) * (t.endPosition - t.startPosition); if ((t.endPosition > t.startPosition && result >= t.endPosition) || (t.endPosition < t.startPosition && result <= t.endPosition) || t.endPosition === t.startPosition) { result = t.endPosition; speed[axis] = 0; delete animatedMove[axis]; } config[axis] = result; }
javascript
{ "resource": "" }
q62041
animate
test
function animate() { render(); if (autoRotateStart) clearTimeout(autoRotateStart); if (isUserInteracting || orientation === true) { requestAnimationFrame(animate); } else if (keysDown[0] || keysDown[1] || keysDown[2] || keysDown[3] || keysDown[4] || keysDown[5] || keysDown[6] || keysDown[7] || keysDown[8] || keysDown[9] || config.autoRotate || animatedMove.pitch || animatedMove.yaw || animatedMove.hfov || Math.abs(speed.yaw) > 0.01 || Math.abs(speed.pitch) > 0.01 || Math.abs(speed.hfov) > 0.01) { keyRepeat(); if (config.autoRotateInactivityDelay >= 0 && autoRotateSpeed && Date.now() - latestInteraction > config.autoRotateInactivityDelay && !config.autoRotate) { config.autoRotate = autoRotateSpeed; _this.lookAt(origPitch, undefined, origHfov, 3000); } requestAnimationFrame(animate); } else if (renderer && (renderer.isLoading() || (config.dynamic === true && update))) { requestAnimationFrame(animate); } else { fireEvent('animatefinished', {pitch: _this.getPitch(), yaw: _this.getYaw(), hfov: _this.getHfov()}); animating = false; prevTime = undefined; var autoRotateStartTime = config.autoRotateInactivityDelay - (Date.now() - latestInteraction); if (autoRotateStartTime > 0) { autoRotateStart = setTimeout(function() { config.autoRotate = autoRotateSpeed; _this.lookAt(origPitch, undefined, origHfov, 3000); animateInit(); }, autoRotateStartTime); } else if (config.autoRotateInactivityDelay >= 0 && autoRotateSpeed) { config.autoRotate = autoRotateSpeed; _this.lookAt(origPitch, undefined, origHfov, 3000); animateInit(); } } }
javascript
{ "resource": "" }
q62042
taitBryanToQuaternion
test
function taitBryanToQuaternion(alpha, beta, gamma) { var r = [beta ? beta * Math.PI / 180 / 2 : 0, gamma ? gamma * Math.PI / 180 / 2 : 0, alpha ? alpha * Math.PI / 180 / 2 : 0]; var c = [Math.cos(r[0]), Math.cos(r[1]), Math.cos(r[2])], s = [Math.sin(r[0]), Math.sin(r[1]), Math.sin(r[2])]; return new Quaternion(c[0]*c[1]*c[2] - s[0]*s[1]*s[2], s[0]*c[1]*c[2] - c[0]*s[1]*s[2], c[0]*s[1]*c[2] + s[0]*c[1]*s[2], c[0]*c[1]*s[2] + s[0]*s[1]*c[2]); }
javascript
{ "resource": "" }
q62043
computeQuaternion
test
function computeQuaternion(alpha, beta, gamma) { // Convert Tait-Bryan angles to quaternion var quaternion = taitBryanToQuaternion(alpha, beta, gamma); // Apply world transform quaternion = quaternion.multiply(new Quaternion(Math.sqrt(0.5), -Math.sqrt(0.5), 0, 0)); // Apply screen transform var angle = window.orientation ? -window.orientation * Math.PI / 180 / 2 : 0; return quaternion.multiply(new Quaternion(Math.cos(angle), 0, -Math.sin(angle), 0)); }
javascript
{ "resource": "" }
q62044
orientationListener
test
function orientationListener(e) { var q = computeQuaternion(e.alpha, e.beta, e.gamma).toEulerAngles(); if (typeof(orientation) == 'number' && orientation < 10) { // This kludge is necessary because iOS sometimes provides a few stale // device orientation events when the listener is removed and then // readded. Thus, we skip the first 10 events to prevent this from // causing problems. orientation += 1; } else if (orientation === 10) { // Record starting yaw to prevent jumping orientationYawOffset = q[2] / Math.PI * 180 + config.yaw; orientation = true; requestAnimationFrame(animate); } else { config.pitch = q[0] / Math.PI * 180; config.roll = -q[1] / Math.PI * 180; config.yaw = -q[2] / Math.PI * 180 + orientationYawOffset; } }
javascript
{ "resource": "" }
q62045
renderInit
test
function renderInit() { try { var params = {}; if (config.horizonPitch !== undefined) params.horizonPitch = config.horizonPitch * Math.PI / 180; if (config.horizonRoll !== undefined) params.horizonRoll = config.horizonRoll * Math.PI / 180; if (config.backgroundColor !== undefined) params.backgroundColor = config.backgroundColor; renderer.init(panoImage, config.type, config.dynamic, config.haov * Math.PI / 180, config.vaov * Math.PI / 180, config.vOffset * Math.PI / 180, renderInitCallback, params); if (config.dynamic !== true) { // Allow image to be garbage collected panoImage = undefined; } } catch(event) { // Panorama not loaded // Display error if there is a bad texture if (event.type == 'webgl error' || event.type == 'no webgl') { anError(); } else if (event.type == 'webgl size error') { anError(config.strings.textureSizeError.replace('%s', event.width).replace('%s', event.maxWidth)); } else { anError(config.strings.unknownError); throw event; } } }
javascript
{ "resource": "" }
q62046
renderInitCallback
test
function renderInitCallback() { // Fade if specified if (config.sceneFadeDuration && renderer.fadeImg !== undefined) { renderer.fadeImg.style.opacity = 0; // Remove image var fadeImg = renderer.fadeImg; delete renderer.fadeImg; setTimeout(function() { renderContainer.removeChild(fadeImg); fireEvent('scenechangefadedone'); }, config.sceneFadeDuration); } // Show compass if applicable if (config.compass) { compass.style.display = 'inline'; } else { compass.style.display = 'none'; } // Show hotspots createHotSpots(); // Hide loading display infoDisplay.load.box.style.display = 'none'; if (preview !== undefined) { renderContainer.removeChild(preview); preview = undefined; } loaded = true; fireEvent('load'); animateInit(); }
javascript
{ "resource": "" }
q62047
createHotSpots
test
function createHotSpots() { if (hotspotsCreated) return; if (!config.hotSpots) { config.hotSpots = []; } else { // Sort by pitch so tooltip is never obscured by another hot spot config.hotSpots = config.hotSpots.sort(function(a, b) { return a.pitch < b.pitch; }); config.hotSpots.forEach(createHotSpot); } hotspotsCreated = true; renderHotSpots(); }
javascript
{ "resource": "" }
q62048
destroyHotSpots
test
function destroyHotSpots() { var hs = config.hotSpots; hotspotsCreated = false; delete config.hotSpots; if (hs) { for (var i = 0; i < hs.length; i++) { var current = hs[i].div; if (current) { while (current.parentNode && current.parentNode != renderContainer) { current = current.parentNode; } renderContainer.removeChild(current); } delete hs[i].div; } } }
javascript
{ "resource": "" }
q62049
renderHotSpot
test
function renderHotSpot(hs) { var hsPitchSin = Math.sin(hs.pitch * Math.PI / 180), hsPitchCos = Math.cos(hs.pitch * Math.PI / 180), configPitchSin = Math.sin(config.pitch * Math.PI / 180), configPitchCos = Math.cos(config.pitch * Math.PI / 180), yawCos = Math.cos((-hs.yaw + config.yaw) * Math.PI / 180); var z = hsPitchSin * configPitchSin + hsPitchCos * yawCos * configPitchCos; if ((hs.yaw <= 90 && hs.yaw > -90 && z <= 0) || ((hs.yaw > 90 || hs.yaw <= -90) && z <= 0)) { hs.div.style.visibility = 'hidden'; } else { var yawSin = Math.sin((-hs.yaw + config.yaw) * Math.PI / 180), hfovTan = Math.tan(config.hfov * Math.PI / 360); hs.div.style.visibility = 'visible'; // Subpixel rendering doesn't work in Firefox // https://bugzilla.mozilla.org/show_bug.cgi?id=739176 var canvas = renderer.getCanvas(), canvasWidth = canvas.clientWidth, canvasHeight = canvas.clientHeight; var coord = [-canvasWidth / hfovTan * yawSin * hsPitchCos / z / 2, -canvasWidth / hfovTan * (hsPitchSin * configPitchCos - hsPitchCos * yawCos * configPitchSin) / z / 2]; // Apply roll var rollSin = Math.sin(config.roll * Math.PI / 180), rollCos = Math.cos(config.roll * Math.PI / 180); coord = [coord[0] * rollCos - coord[1] * rollSin, coord[0] * rollSin + coord[1] * rollCos]; // Apply transform coord[0] += (canvasWidth - hs.div.offsetWidth) / 2; coord[1] += (canvasHeight - hs.div.offsetHeight) / 2; var transform = 'translate(' + coord[0] + 'px, ' + coord[1] + 'px) translateZ(9999px) rotate(' + config.roll + 'deg)'; hs.div.style.webkitTransform = transform; hs.div.style.MozTransform = transform; hs.div.style.transform = transform; } }
javascript
{ "resource": "" }
q62050
mergeConfig
test
function mergeConfig(sceneId) { config = {}; var k, s; var photoSphereExcludes = ['haov', 'vaov', 'vOffset', 'northOffset', 'horizonPitch', 'horizonRoll']; specifiedPhotoSphereExcludes = []; // Merge default config for (k in defaultConfig) { if (defaultConfig.hasOwnProperty(k)) { config[k] = defaultConfig[k]; } } // Merge default scene config for (k in initialConfig.default) { if (initialConfig.default.hasOwnProperty(k)) { if (k == 'strings') { for (s in initialConfig.default.strings) { if (initialConfig.default.strings.hasOwnProperty(s)) { config.strings[s] = escapeHTML(initialConfig.default.strings[s]); } } } else { config[k] = initialConfig.default[k]; if (photoSphereExcludes.indexOf(k) >= 0) { specifiedPhotoSphereExcludes.push(k); } } } } // Merge current scene config if ((sceneId !== null) && (sceneId !== '') && (initialConfig.scenes) && (initialConfig.scenes[sceneId])) { var scene = initialConfig.scenes[sceneId]; for (k in scene) { if (scene.hasOwnProperty(k)) { if (k == 'strings') { for (s in scene.strings) { if (scene.strings.hasOwnProperty(s)) { config.strings[s] = escapeHTML(scene.strings[s]); } } } else { config[k] = scene[k]; if (photoSphereExcludes.indexOf(k) >= 0) { specifiedPhotoSphereExcludes.push(k); } } } } config.scene = sceneId; } // Merge initial config for (k in initialConfig) { if (initialConfig.hasOwnProperty(k)) { if (k == 'strings') { for (s in initialConfig.strings) { if (initialConfig.strings.hasOwnProperty(s)) { config.strings[s] = escapeHTML(initialConfig.strings[s]); } } } else { config[k] = initialConfig[k]; if (photoSphereExcludes.indexOf(k) >= 0) { specifiedPhotoSphereExcludes.push(k); } } } } }
javascript
{ "resource": "" }
q62051
toggleFullscreen
test
function toggleFullscreen() { if (loaded && !error) { if (!fullscreenActive) { try { if (container.requestFullscreen) { container.requestFullscreen(); } else if (container.mozRequestFullScreen) { container.mozRequestFullScreen(); } else if (container.msRequestFullscreen) { container.msRequestFullscreen(); } else { container.webkitRequestFullScreen(); } } catch(event) { // Fullscreen doesn't work } } else { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } } } }
javascript
{ "resource": "" }
q62052
onFullScreenChange
test
function onFullScreenChange(resize) { if (document.fullscreenElement || document.fullscreen || document.mozFullScreen || document.webkitIsFullScreen || document.msFullscreenElement) { controls.fullscreen.classList.add('pnlm-fullscreen-toggle-button-active'); fullscreenActive = true; } else { controls.fullscreen.classList.remove('pnlm-fullscreen-toggle-button-active'); fullscreenActive = false; } if (resize !== 'resize') fireEvent('fullscreenchange', fullscreenActive); // Resize renderer (deal with browser quirks and fixes #155) renderer.resize(); setHfov(config.hfov); animateInit(); }
javascript
{ "resource": "" }
q62053
constrainHfov
test
function constrainHfov(hfov) { // Keep field of view within bounds var minHfov = config.minHfov; if (config.type == 'multires' && renderer && config.multiResMinHfov) { minHfov = Math.min(minHfov, renderer.getCanvas().width / (config.multiRes.cubeResolution / 90 * 0.9)); } if (minHfov > config.maxHfov) { // Don't change view if bounds don't make sense console.log('HFOV bounds do not make sense (minHfov > maxHfov).') return config.hfov; } var newHfov = config.hfov; if (hfov < minHfov) { newHfov = minHfov; } else if (hfov > config.maxHfov) { newHfov = config.maxHfov; } else { newHfov = hfov; } // Optionally avoid showing background (empty space) on top or bottom by adapting newHfov if (config.avoidShowingBackground && renderer) { var canvas = renderer.getCanvas(); newHfov = Math.min(newHfov, Math.atan(Math.tan((config.maxPitch - config.minPitch) / 360 * Math.PI) / canvas.height * canvas.width) * 360 / Math.PI); } return newHfov; }
javascript
{ "resource": "" }
q62054
stopAnimation
test
function stopAnimation() { animatedMove = {}; autoRotateSpeed = config.autoRotate ? config.autoRotate : autoRotateSpeed; config.autoRotate = false; }
javascript
{ "resource": "" }
q62055
load
test
function load() { // Since WebGL error handling is very general, first we clear any error box // since it is a new scene and the error from previous maybe because of lacking // memory etc and not because of a lack of WebGL support etc clearError(); loaded = false; controls.load.style.display = 'none'; infoDisplay.load.box.style.display = 'inline'; init(); }
javascript
{ "resource": "" }
q62056
loadScene
test
function loadScene(sceneId, targetPitch, targetYaw, targetHfov, fadeDone) { loaded = false; animatedMove = {}; // Set up fade if specified var fadeImg, workingPitch, workingYaw, workingHfov; if (config.sceneFadeDuration && !fadeDone) { var data = renderer.render(config.pitch * Math.PI / 180, config.yaw * Math.PI / 180, config.hfov * Math.PI / 180, {returnImage: true}); if (data !== undefined) { fadeImg = new Image(); fadeImg.className = 'pnlm-fade-img'; fadeImg.style.transition = 'opacity ' + (config.sceneFadeDuration / 1000) + 's'; fadeImg.style.width = '100%'; fadeImg.style.height = '100%'; fadeImg.onload = function() { loadScene(sceneId, targetPitch, targetYaw, targetHfov, true); }; fadeImg.src = data; renderContainer.appendChild(fadeImg); renderer.fadeImg = fadeImg; return; } } // Set new pointing if (targetPitch === 'same') { workingPitch = config.pitch; } else { workingPitch = targetPitch; } if (targetYaw === 'same') { workingYaw = config.yaw; } else if (targetYaw === 'sameAzimuth') { workingYaw = config.yaw + (config.northOffset || 0) - (initialConfig.scenes[sceneId].northOffset || 0); } else { workingYaw = targetYaw; } if (targetHfov === 'same') { workingHfov = config.hfov; } else { workingHfov = targetHfov; } // Destroy hot spots from previous scene destroyHotSpots(); // Create the new config for the scene mergeConfig(sceneId); // Stop motion speed.yaw = speed.pitch = speed.hfov = 0; // Reload scene processOptions(); if (workingPitch !== undefined) { config.pitch = workingPitch; } if (workingYaw !== undefined) { config.yaw = workingYaw; } if (workingHfov !== undefined) { config.hfov = workingHfov; } fireEvent('scenechange', sceneId); load(); // Properly handle switching to dynamic scenes update = config.dynamicUpdate === true; if (config.dynamic) { panoImage = config.panorama; onImageLoad(); } }
javascript
{ "resource": "" }
q62057
stopOrientation
test
function stopOrientation() { window.removeEventListener('deviceorientation', orientationListener); controls.orientation.classList.remove('pnlm-orientation-button-active'); orientation = false; }
javascript
{ "resource": "" }
q62058
fireEvent
test
function fireEvent(type) { if (type in externalEventListeners) { // Reverse iteration is useful, if event listener is removed inside its definition for (var i = externalEventListeners[type].length; i > 0; i--) { externalEventListeners[type][externalEventListeners[type].length - i].apply(null, [].slice.call(arguments, 1)); } } }
javascript
{ "resource": "" }
q62059
test
function(latchFunction, optional_timeoutMessage, optional_timeout) { jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments); }
javascript
{ "resource": "" }
q62060
$getMouseOffset
test
function $getMouseOffset(target, ev){ ev = ev || _window.event; var docPos = $getPosition(target); var mousePos = $mouseCoords(ev); return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y}; }
javascript
{ "resource": "" }
q62061
test
function(val, flags){ number_check(val) if(! flags.precision){ if(! flags.decimal_point){ flags.precision = 6 }else{ flags.precision = 0 } }else{ flags.precision = parseInt(flags.precision, 10) validate_precision(flags.precision) } return parseFloat(val) }
javascript
{ "resource": "" }
q62062
test
function(self, other){ if(_b_.isinstance(other, int)) { if(other.__class__ === $B.long_int){ return $B.long_int.__sub__($B.long_int.$factory(self), $B.long_int.$factory(other)) } other = int_value(other) if(self > $B.max_int32 || self < $B.min_int32 || other > $B.max_int32 || other < $B.min_int32){ return $B.long_int.__sub__($B.long_int.$factory(self), $B.long_int.$factory(other)) } return self - other } if(_b_.isinstance(other, _b_.bool)){return self - other} var rsub = $B.$getattr(other, "__rsub__", _b_.None) if(rsub !== _b_.None){return rsub(self)} $err("-", other) }
javascript
{ "resource": "" }
q62063
test
function(self, other){ if(_b_.isinstance(other, int)){ other = int_value(other) if(typeof other == "number"){ var res = self.valueOf() - other.valueOf() if(res > $B.min_int && res < $B.max_int){return res} else{return $B.long_int.__sub__($B.long_int.$factory(self), $B.long_int.$factory(other))} }else if(typeof other == "boolean"){ return other ? self - 1 : self }else{ return $B.long_int.__sub__($B.long_int.$factory(self), $B.long_int.$factory(other)) } } if(_b_.isinstance(other, _b_.float)){ return new Number(self - other) } if(_b_.isinstance(other, _b_.complex)){ return $B.make_complex(self - other.$real, -other.$imag) } if(_b_.isinstance(other, _b_.bool)){ var bool_value = 0; if(other.valueOf()){bool_value = 1} return self - bool_value } if(_b_.isinstance(other, _b_.complex)){ return $B.make_complex(self.valueOf() - other.$real, other.$imag) } var rsub = $B.$getattr(other, "__rsub__", _b_.None) if(rsub !== _b_.None){return rsub(self)} throw $err("-", other) }
javascript
{ "resource": "" }
q62064
inlineResourcesFromString
test
function inlineResourcesFromString(content, urlResolver) { // Curry through the inlining functions. return [ inlineTemplate, inlineStyle, removeModuleId ].reduce((content, fn) => fn(content, urlResolver), content); }
javascript
{ "resource": "" }
q62065
buildSass
test
function buildSass(content, sourceFile) { try { const result = sass.renderSync({ data: content, file: sourceFile, importer: tildeImporter }); return result.css.toString() } catch (e) { console.error('\x1b[41m'); console.error('at ' + sourceFile + ':' + e.line + ":" + e.column); console.error(e.formatted); console.error('\x1b[0m'); return ""; } }
javascript
{ "resource": "" }
q62066
FormioResourceRoutes
test
function FormioResourceRoutes(config) { config = config || {}; return [ { path: '', component: config.index || index_component_1.FormioResourceIndexComponent }, { path: 'new', component: config.create || create_component_1.FormioResourceCreateComponent }, { path: ':id', component: config.resource || resource_component_1.FormioResourceComponent, children: [ { path: '', redirectTo: 'view', pathMatch: 'full' }, { path: 'view', component: config.view || view_component_1.FormioResourceViewComponent }, { path: 'edit', component: config.edit || edit_component_1.FormioResourceEditComponent }, { path: 'delete', component: config.delete || delete_component_1.FormioResourceDeleteComponent } ] } ]; }
javascript
{ "resource": "" }
q62067
BaseProducer
test
function BaseProducer (client, options, defaultPartitionerType, customPartitioner) { EventEmitter.call(this); options = options || {}; this.ready = false; this.client = client; this.requireAcks = options.requireAcks === undefined ? DEFAULTS.requireAcks : options.requireAcks; this.ackTimeoutMs = options.ackTimeoutMs === undefined ? DEFAULTS.ackTimeoutMs : options.ackTimeoutMs; if (customPartitioner !== undefined && options.partitionerType !== PARTITIONER_TYPES.custom) { throw new Error('Partitioner Type must be custom if providing a customPartitioner.'); } else if (customPartitioner === undefined && options.partitionerType === PARTITIONER_TYPES.custom) { throw new Error('No customer partitioner defined'); } var partitionerType = PARTITIONER_MAP[options.partitionerType] || PARTITIONER_MAP[defaultPartitionerType]; // eslint-disable-next-line this.partitioner = new partitionerType(customPartitioner); this.connect(); }
javascript
{ "resource": "" }
q62068
Context
test
function Context (options) { if (!options) options = { body: '', hostname: '' }; const body = options.body; const href = 'http://' + options.hostname + '/'; const cache = Object.create(null); const keys = []; this.atob = function (str) { return Buffer.from(str, 'base64').toString('binary'); }; // Used for eval during onRedirectChallenge this.location = { reload: function () {} }; this.document = { createElement: function () { return { firstChild: { href: href } }; }, getElementById: function (id) { if (keys.indexOf(id) === -1) { const re = new RegExp(' id=[\'"]?' + id + '[^>]*>([^<]*)'); const match = body.match(re); keys.push(id); cache[id] = match === null ? match : { innerHTML: match[1] }; } return cache[id]; } }; }
javascript
{ "resource": "" }
q62069
alternative
test
function alternative (options, { captcha: { url, siteKey } }) { // Here you do some magic with the siteKey provided by cloudscraper console.error('The url is "' + url + '"'); console.error('The site key is "' + siteKey + '"'); return Promise.reject(new Error('This is a dummy function')); }
javascript
{ "resource": "" }
q62070
performRequest
test
function performRequest (options, isFirstRequest) { // This should be the default export of either request or request-promise. const requester = options.requester; // Note that request is always an instanceof ReadableStream, EventEmitter // If the requester is request-promise, it is also thenable. const request = requester(options); // We must define the host header ourselves to preserve case and order. if (request.getHeader('host') === HOST) { request.setHeader('host', request.uri.host); } // If the requester is not request-promise, ensure we get a callback. if (typeof request.callback !== 'function') { throw new TypeError('Expected a callback function, got ' + typeof (request.callback) + ' instead.'); } // We only need the callback from the first request. // The other callbacks can be safely ignored. if (isFirstRequest) { // This should be a user supplied callback or request-promise's callback. // The callback is always wrapped/bound to the request instance. options.callback = request.callback; } request.removeAllListeners('error') .once('error', function (error) { onRequestResponse(options, error); }); request.removeAllListeners('complete') .once('complete', function (response, body) { onRequestResponse(options, null, response, body); }); // Indicate that this is a cloudscraper request request.cloudscraper = true; return request; }
javascript
{ "resource": "" }
q62071
onRequestResponse
test
function onRequestResponse (options, error, response, body) { const callback = options.callback; // Encoding is null so body should be a buffer object if (error || !body || !body.toString) { // Pure request error (bad connection, wrong url, etc) return callback(new RequestError(error, options, response)); } response.responseStartTime = Date.now(); response.isCloudflare = /^cloudflare/i.test('' + response.caseless.get('server')); response.isHTML = /text\/html/i.test('' + response.caseless.get('content-type')); // If body isn't a buffer, this is a custom response body. if (!Buffer.isBuffer(body)) { return callback(null, response, body); } // Decompress brotli compressed responses if (/\bbr\b/i.test('' + response.caseless.get('content-encoding'))) { if (!brotli.isAvailable) { const cause = 'Received a Brotli compressed response. Please install brotli'; return callback(new RequestError(cause, options, response)); } response.body = body = brotli.decompress(body); } if (response.isCloudflare && response.isHTML) { onCloudflareResponse(options, response, body); } else { onRequestComplete(options, response, body); } }
javascript
{ "resource": "" }
q62072
onCaptcha
test
function onCaptcha (options, response, body) { const callback = options.callback; // UDF that has the responsibility of returning control back to cloudscraper const handler = options.onCaptcha; // The form data to send back to Cloudflare const payload = { /* s, g-re-captcha-response */ }; let cause; let match; match = body.match(/<form(?: [^<>]*)? id=["']?challenge-form['"]?(?: [^<>]*)?>([\S\s]*?)<\/form>/); if (!match) { cause = 'Challenge form extraction failed'; return callback(new ParserError(cause, options, response)); } // Defining response.challengeForm for debugging purposes const form = response.challengeForm = match[1]; match = form.match(/\/recaptcha\/api\/fallback\?k=([^\s"'<>]*)/); if (!match) { // The site key wasn't inside the form so search the entire document match = body.match(/data-sitekey=["']?([^\s"'<>]*)/); if (!match) { cause = 'Unable to find the reCAPTCHA site key'; return callback(new ParserError(cause, options, response)); } } // Everything that is needed to solve the reCAPTCHA response.captcha = { url: response.request.uri.href, siteKey: match[1], form: payload }; // Adding formData match = form.match(/<input(?: [^<>]*)? name=[^<>]+>/g); if (!match) { cause = 'Challenge form is missing inputs'; return callback(new ParserError(cause, options, response)); } const inputs = match; // Only adding inputs that have both a name and value defined for (let name, value, i = 0; i < inputs.length; i++) { name = inputs[i].match(/name=["']?([^\s"'<>]*)/); if (name) { value = inputs[i].match(/value=["']?([^\s"'<>]*)/); if (value) { payload[name[1]] = value[1]; } } } // Sanity check if (!payload['s']) { cause = 'Challenge form is missing secret input'; return callback(new ParserError(cause, options, response)); } // The callback used to green light form submission const submit = function (error) { if (error) { // Pass an user defined error back to the original request call return callback(new CaptchaError(error, options, response)); } onSubmitCaptcha(options, response, body); }; // This seems like an okay-ish API (fewer arguments to the handler) response.captcha.submit = submit; // We're handing control over to the user now. const thenable = handler(options, response, body); // Handle the case where the user returns a promise if (thenable && typeof thenable.then === 'function') { // eslint-disable-next-line promise/catch-or-return thenable.then(submit, function (error) { if (!error) { // The user broke their promise with a falsy error submit(new Error('Falsy error')); } else { submit(error); } }); } }
javascript
{ "resource": "" }
q62073
test
function (error) { if (error) { // Pass an user defined error back to the original request call return callback(new CaptchaError(error, options, response)); } onSubmitCaptcha(options, response, body); }
javascript
{ "resource": "" }
q62074
assets
test
function assets(userOptions = {}) { const options = { ...defaults, ...userOptions, }; return (files, metalsmith, cb) => { const src = metalsmith.path(options.source); const dest = options.destination; // copied almost line for line from https://github.com/segmentio/metalsmith/blob/master/lib/index.js readdir(src, (readDirError, arr) => { if (readDirError) { cb(readDirError); return; } each(arr, read, err => cb(err, files)); }); function read(file, done) { const name = path.join(dest, path.relative(src, file)); fs.stat(file, (statError, stats) => { if (statError) { done(statError); return; } fs.readFile(file, (err, buffer) => { if (err) { done(err); return; } const newFile = {}; newFile.contents = buffer; newFile.stats = stats; newFile.mode = mode(stats).toOctal(); files[name] = newFile; done(); }); }); } }; }
javascript
{ "resource": "" }
q62075
getStartStopBoundaries
test
function getStartStopBoundaries(parent, sidebar, topOffset) { const bbox = parent.getBoundingClientRect(); const sidebarBbox = sidebar.getBoundingClientRect(); const bodyBbox = document.body.getBoundingClientRect(); const containerAbsoluteTop = bbox.top - bodyBbox.top; const sidebarAbsoluteTop = sidebarBbox.top - bodyBbox.top; const marginTop = sidebarAbsoluteTop - containerAbsoluteTop; const start = containerAbsoluteTop - topOffset; const stop = bbox.height + containerAbsoluteTop - sidebarBbox.height - marginTop - topOffset; return { start, stop, }; }
javascript
{ "resource": "" }
q62076
around
test
function around (obj, method, fn) { var old = obj[method] obj[method] = function () { var args = new Array(arguments.length) for (var i = 0; i < args.length; i++) args[i] = arguments[i] return fn.call(this, old, args) } }
javascript
{ "resource": "" }
q62077
before
test
function before (obj, method, fn) { var old = obj[method] obj[method] = function () { fn.call(this) old.apply(this, arguments) } }
javascript
{ "resource": "" }
q62078
copyTemplate
test
function copyTemplate (from, to) { write(to, fs.readFileSync(path.join(TEMPLATE_DIR, from), 'utf-8')) }
javascript
{ "resource": "" }
q62079
copyTemplateMulti
test
function copyTemplateMulti (fromDir, toDir, nameGlob) { fs.readdirSync(path.join(TEMPLATE_DIR, fromDir)) .filter(minimatch.filter(nameGlob, { matchBase: true })) .forEach(function (name) { copyTemplate(path.join(fromDir, name), path.join(toDir, name)) }) }
javascript
{ "resource": "" }
q62080
createAppName
test
function createAppName (pathName) { return path.basename(pathName) .replace(/[^A-Za-z0-9.-]+/g, '-') .replace(/^[-_.]+|-+$/g, '') .toLowerCase() }
javascript
{ "resource": "" }
q62081
emptyDirectory
test
function emptyDirectory (dir, fn) { fs.readdir(dir, function (err, files) { if (err && err.code !== 'ENOENT') throw err fn(!files || !files.length) }) }
javascript
{ "resource": "" }
q62082
exit
test
function exit (code) { // flush output for Node.js Windows pipe bug // https://github.com/joyent/node/issues/6247 is just one bug example // https://github.com/visionmedia/mocha/issues/333 has a good discussion function done () { if (!(draining--)) _exit(code) } var draining = 0 var streams = [process.stdout, process.stderr] exit.exited = true streams.forEach(function (stream) { // submit empty write request and wait for completion draining += 1 stream.write('', done) }) done() }
javascript
{ "resource": "" }
q62083
loadTemplate
test
function loadTemplate (name) { var contents = fs.readFileSync(path.join(__dirname, '..', 'templates', (name + '.ejs')), 'utf-8') var locals = Object.create(null) function render () { return ejs.render(contents, locals, { escape: util.inspect }) } return { locals: locals, render: render } }
javascript
{ "resource": "" }
q62084
main
test
function main () { // Path var destinationPath = program.args.shift() || '.' // App name var appName = createAppName(path.resolve(destinationPath)) || 'hello-world' // View engine if (program.view === true) { if (program.ejs) program.view = 'ejs' if (program.hbs) program.view = 'hbs' if (program.hogan) program.view = 'hjs' if (program.pug) program.view = 'pug' } // Default view engine if (program.view === true) { warning('the default view engine will not be jade in future releases\n' + "use `--view=jade' or `--help' for additional options") program.view = 'jade' } // Generate application emptyDirectory(destinationPath, function (empty) { if (empty || program.force) { createApplication(appName, destinationPath) } else { confirm('destination is not empty, continue? [y/N] ', function (ok) { if (ok) { process.stdin.destroy() createApplication(appName, destinationPath) } else { console.error('aborting') exit(1) } }) } }) }
javascript
{ "resource": "" }
q62085
mkdir
test
function mkdir (base, dir) { var loc = path.join(base, dir) console.log(' \x1b[36mcreate\x1b[0m : ' + loc + path.sep) mkdirp.sync(loc, MODE_0755) }
javascript
{ "resource": "" }
q62086
renamedOption
test
function renamedOption (originalName, newName) { return function (val) { warning(util.format("option `%s' has been renamed to `%s'", originalName, newName)) return val } }
javascript
{ "resource": "" }
q62087
warning
test
function warning (message) { console.error() message.split('\n').forEach(function (line) { console.error(' warning: %s', line) }) console.error() }
javascript
{ "resource": "" }
q62088
write
test
function write (file, str, mode) { fs.writeFileSync(file, str, { mode: mode || MODE_0666 }) console.log(' \x1b[36mcreate\x1b[0m : ' + file) }
javascript
{ "resource": "" }
q62089
bind_d3
test
function bind_d3(f, context) { return function() { var args = [this].concat([].slice.call(arguments)) // convert argument to array f.apply(context, args) } }
javascript
{ "resource": "" }
q62090
adjustOptions
test
function adjustOptions(options) { const directory = process.cwd(); const configPath = getWebpackConfigPath(directory, options.config); const haulOptions = getHaulConfig(configPath, logger); if (haulOptions.platforms) { const platformOption = command.options && command.options.find(_ => _.name === 'platform'); if (platformOption) { platformOption.choices = []; for (const platformName in haulOptions.platforms) { if ( Object.prototype.hasOwnProperty.call( haulOptions.platforms, platformName ) ) { if (platformOption.choices) { platformOption.choices.push({ value: platformName, description: `Builds ${haulOptions.platforms[ platformName ]} bundle`, }); } } } } } }
javascript
{ "resource": "" }
q62091
devToolsMiddleware
test
function devToolsMiddleware(debuggerProxy) { return (req, res, next) => { switch (req.cleanPath) { /** * Request for the debugger frontend */ case '/debugger-ui/': case '/debugger-ui': { const readStream = fs.createReadStream( path.join(__dirname, '../assets/debugger.html') ); res.writeHead(200, { 'Content-Type': 'text/html' }); readStream.pipe(res); break; } /** * Request for the debugger worker */ case '/debugger-ui/debuggerWorker.js': case '/debuggerWorker.js': { const readStream = fs.createReadStream( path.join(__dirname, '../assets/debuggerWorker.js') ); res.writeHead(200, { 'Content-Type': 'application/javascript' }); readStream.pipe(res); break; } /** * Request for (maybe) launching devtools */ case '/launch-js-devtools': { if (!debuggerProxy.isDebuggerConnected()) { launchBrowser(`http://localhost:${req.socket.localPort}/debugger-ui`); } res.end('OK'); break; } default: next(); } }; }
javascript
{ "resource": "" }
q62092
onLoad
test
function onLoad(event) { // Prepare the render pass. event.demo.renderPass.camera = event.demo.camera; document.getElementById("viewport").children[0].style.display = "none"; }
javascript
{ "resource": "" }
q62093
prefixSubstrings
test
function prefixSubstrings(prefix, substrings, strings) { let prefixed, regExp; for(const substring of substrings) { prefixed = "$1" + prefix + substring.charAt(0).toUpperCase() + substring.slice(1); regExp = new RegExp("([^\\.])(\\b" + substring + "\\b)", "g"); for(const entry of strings.entries()) { if(entry[1] !== null) { strings.set(entry[0], entry[1].replace(regExp, prefixed)); } } } }
javascript
{ "resource": "" }
q62094
createCanvas
test
function createCanvas(width, height, data, channels) { const canvas = document.createElementNS("http://www.w3.org/1999/xhtml", "canvas"); const context = canvas.getContext("2d"); const imageData = context.createImageData(width, height); const target = imageData.data; let x, y; let i, j; for(y = 0; y < height; ++y) { for(x = 0; x < width; ++x) { i = (y * width + x) * 4; j = (y * width + x) * channels; target[i] = (channels > 0) ? data[j] : 0; target[i + 1] = (channels > 1) ? data[j + 1] : 0; target[i + 2] = (channels > 2) ? data[j + 2] : 0; target[i + 3] = (channels > 3) ? data[j + 3] : 255; } } canvas.width = width; canvas.height = height; context.putImageData(imageData, 0, 0); return canvas; }
javascript
{ "resource": "" }
q62095
smoothArea
test
function smoothArea(d, b) { const a1 = b.min; const a2 = b.max; const b1X = Math.sqrt(a1.x * 2.0) * 0.5; const b1Y = Math.sqrt(a1.y * 2.0) * 0.5; const b2X = Math.sqrt(a2.x * 2.0) * 0.5; const b2Y = Math.sqrt(a2.y * 2.0) * 0.5; const p = saturate(d / SMOOTH_MAX_DISTANCE); a1.set(lerp(b1X, a1.x, p), lerp(b1Y, a1.y, p)); a2.set(lerp(b2X, a2.x, p), lerp(b2Y, a2.y, p)); return b; }
javascript
{ "resource": "" }
q62096
calculateDiagonalAreaForPixel
test
function calculateDiagonalAreaForPixel(p1, p2, pX, pY) { let a; let x, y; let offsetX, offsetY; for(a = 0, y = 0; y < DIAGONAL_SAMPLES; ++y) { for(x = 0; x < DIAGONAL_SAMPLES; ++x) { offsetX = x / (DIAGONAL_SAMPLES - 1.0); offsetY = y / (DIAGONAL_SAMPLES - 1.0); if(isInsideArea(p1, p2, pX + offsetX, pY + offsetY)) { ++a; } } } return a / (DIAGONAL_SAMPLES * DIAGONAL_SAMPLES); }
javascript
{ "resource": "" }
q62097
calculateDiagonalArea
test
function calculateDiagonalArea(pattern, p1, p2, left, offset, result) { const e = diagonalEdges[pattern]; const e1 = e[0]; const e2 = e[1]; if(e1 > 0) { p1.x += offset[0]; p1.y += offset[1]; } if(e2 > 0) { p2.x += offset[0]; p2.y += offset[1]; } return result.set( 1.0 - calculateDiagonalAreaForPixel(p1, p2, 1.0 + left, 0.0 + left), calculateDiagonalAreaForPixel(p1, p2, 1.0 + left, 1.0 + left) ); }
javascript
{ "resource": "" }
q62098
generatePatterns
test
function generatePatterns(patterns, offset, orthogonal) { const result = new Vector2(); let i, l; let x, y; let c; let pattern; let data, size; for(i = 0, l = patterns.length; i < l; ++i) { pattern = patterns[i]; data = pattern.data; size = pattern.width; for(y = 0; y < size; ++y) { for(x = 0; x < size; ++x) { if(orthogonal) { calculateOrthogonalAreaForPattern(i, x, y, offset, result); } else { calculateDiagonalAreaForPattern(i, x, y, offset, result); } c = (y * size + x) * 2; data[c] = result.x * 255; data[c + 1] = result.y * 255; } } } }
javascript
{ "resource": "" }
q62099
assemble
test
function assemble(base, patterns, edges, size, orthogonal, target) { const p = new Vector2(); const dstData = target.data; const dstWidth = target.width; let i, l; let x, y; let c, d; let edge; let pattern; let srcData, srcWidth; for(i = 0, l = patterns.length; i < l; ++i) { edge = edges[i]; pattern = patterns[i]; srcData = pattern.data; srcWidth = pattern.width; for(y = 0; y < size; ++y) { for(x = 0; x < size; ++x) { p.fromArray(edge).multiplyScalar(size); p.add(base); p.x += x; p.y += y; c = (p.y * dstWidth + p.x) * 2; /* The texture coordinates of orthogonal patterns are compressed quadratically to reach longer distances for a given texture size. */ d = orthogonal ? ((y * y * srcWidth + x * x) * 2) : ((y * srcWidth + x) * 2); dstData[c] = srcData[d]; dstData[c + 1] = srcData[d + 1]; } } } }
javascript
{ "resource": "" }