_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q26500
WorldRenderer
train
function WorldRenderer(params) { this.init_(params.hideFullscreenButton); this.sphereRenderer = new SphereRenderer(this.scene); this.hotspotRenderer = new HotspotRenderer(this); this.hotspotRenderer.on('focus', this.onHotspotFocus_.bind(this)); this.hotspotRenderer.on('blur', this.onHotspotBlur_.bind(this)); this.reticleRenderer = new ReticleRenderer(this.camera); // Get the VR Display as soon as we initialize. navigator.getVRDisplays().then(function(displays) { if (displays.length > 0) { this.vrDisplay = displays[0]; } }.bind(this)); }
javascript
{ "resource": "" }
q26501
Player
train
function Player(selector, contentInfo) { // Create a VR View iframe depending on the parameters. var iframe = this.createIframe_(contentInfo); this.iframe = iframe; var parentEl = document.querySelector(selector); parentEl.appendChild(iframe); // Make a sender as well, for relying commands to the child IFrame. this.sender = new IFrameMessageSender(iframe); // Listen to messages from the IFrame. window.addEventListener('message', this.onMessage_.bind(this), false); // Expose a public .isPaused attribute. this.isPaused = false; // Expose a public .isMuted attribute. this.isMuted = false; if (typeof contentInfo.muted !== 'undefined') { this.isMuted = contentInfo.muted; } // Other public attributes this.currentTime = 0; this.duration = 0; this.volume = contentInfo.volume != undefined ? contentInfo.volume : 1; if (Util.isIOS()) { this.injectFullscreenStylesheet_(); } }
javascript
{ "resource": "" }
q26502
HotspotRenderer
train
function HotspotRenderer(worldRenderer) { this.worldRenderer = worldRenderer; this.scene = worldRenderer.scene; // Note: this event must be added to document.body and not to window for it to // work inside iOS iframes. var body = document.body; // Bind events for hotspot interaction. if (!Util.isMobile()) { // Only enable mouse events on desktop. body.addEventListener('mousedown', this.onMouseDown_.bind(this), false); body.addEventListener('mousemove', this.onMouseMove_.bind(this), false); body.addEventListener('mouseup', this.onMouseUp_.bind(this), false); } body.addEventListener('touchstart', this.onTouchStart_.bind(this), false); body.addEventListener('touchend', this.onTouchEnd_.bind(this), false); // Add a placeholder for hotspots. this.hotspotRoot = new THREE.Object3D(); // Align the center with the center of the camera too. this.hotspotRoot.rotation.y = Math.PI / 2; this.scene.add(this.hotspotRoot); // All hotspot IDs. this.hotspots = {}; // Currently selected hotspots. this.selectedHotspots = {}; // Hotspots that the last touchstart / mousedown event happened for. this.downHotspots = {}; // For raycasting. Initialize mouse to be off screen initially. this.pointer = new THREE.Vector2(1, 1); this.raycaster = new THREE.Raycaster(); }
javascript
{ "resource": "" }
q26503
SceneInfo
train
function SceneInfo(opt_params) { var params = opt_params || {}; params.player = { loop: opt_params.loop, volume: opt_params.volume, muted: opt_params.muted }; this.image = params.image !== undefined ? encodeURI(params.image) : undefined; this.preview = params.preview !== undefined ? encodeURI(params.preview) : undefined; this.video = params.video !== undefined ? encodeURI(params.video) : undefined; this.defaultYaw = THREE.Math.degToRad(params.defaultYaw || 0); this.isStereo = Util.parseBoolean(params.isStereo); this.isYawOnly = Util.parseBoolean(params.isYawOnly); this.isDebug = Util.parseBoolean(params.isDebug); this.isVROff = Util.parseBoolean(params.isVROff); this.isAutopanOff = Util.parseBoolean(params.isAutopanOff); this.loop = Util.parseBoolean(params.player.loop); this.volume = parseFloat( params.player.volume ? params.player.volume : '1'); this.muted = Util.parseBoolean(params.player.muted); this.hideFullscreenButton = Util.parseBoolean(params.hideFullscreenButton); }
javascript
{ "resource": "" }
q26504
cookieSession
train
function cookieSession (options) { var opts = options || {} // cookie name var name = opts.name || 'session' // secrets var keys = opts.keys if (!keys && opts.secret) keys = [opts.secret] // defaults if (opts.overwrite == null) opts.overwrite = true if (opts.httpOnly == null) opts.httpOnly = true if (opts.signed == null) opts.signed = true if (!keys && opts.signed) throw new Error('.keys required.') debug('session options %j', opts) return function _cookieSession (req, res, next) { var cookies = new Cookies(req, res, { keys: keys }) var sess // to pass to Session() req.sessionCookies = cookies req.sessionOptions = Object.create(opts) req.sessionKey = name // define req.session getter / setter Object.defineProperty(req, 'session', { configurable: true, enumerable: true, get: getSession, set: setSession }) function getSession () { // already retrieved if (sess) { return sess } // unset if (sess === false) { return null } // get or create session return (sess = tryGetSession(req) || createSession(req)) } function setSession (val) { if (val == null) { // unset session sess = false return val } if (typeof val === 'object') { // create a new session sess = Session.create(this, val) return sess } throw new Error('req.session can only be set as null or an object.') } onHeaders(res, function setHeaders () { if (sess === undefined) { // not accessed return } try { if (sess === false) { // remove cookies.set(name, '', req.sessionOptions) } else if ((!sess.isNew || sess.isPopulated) && sess.isChanged) { // save populated or non-new changed session sess.save() } } catch (e) { debug('error saving session %s', e.message) } }) next() } }
javascript
{ "resource": "" }
q26505
Session
train
function Session (ctx, obj) { Object.defineProperty(this, '_ctx', { value: ctx }) if (obj) { for (var key in obj) { this[key] = obj[key] } } }
javascript
{ "resource": "" }
q26506
decode
train
function decode (string) { var body = Buffer.from(string, 'base64').toString('utf8') return JSON.parse(body) }
javascript
{ "resource": "" }
q26507
encode
train
function encode (body) { var str = JSON.stringify(body) return Buffer.from(str).toString('base64') }
javascript
{ "resource": "" }
q26508
tryGetSession
train
function tryGetSession (req) { var cookies = req.sessionCookies var name = req.sessionKey var opts = req.sessionOptions var str = cookies.get(name, opts) if (!str) { return undefined } debug('parse %s', str) try { return Session.deserialize(req, str) } catch (err) { return undefined } }
javascript
{ "resource": "" }
q26509
train
function() { $this.text($this.data('counterup-nums').shift()); if ($this.data('counterup-nums').length) { setTimeout($this.data('counterup-func'), $settings.delay); } else { delete $this.data('counterup-nums'); $this.data('counterup-nums', null); $this.data('counterup-func', null); } }
javascript
{ "resource": "" }
q26510
destroyEditOverlay
train
function destroyEditOverlay() { if (overlay) { overlay.parentNode.removeChild(overlay); overlay = null; } document.removeEventListener('click', handleDocumentClick); document.removeEventListener('keyup', handleDocumentKeyup); document.removeEventListener('mousedown', handleDocumentMousedown); document.removeEventListener('mousemove', handleDocumentMousemove); document.removeEventListener('mouseup', handleDocumentMouseup); enableUserSelect(); }
javascript
{ "resource": "" }
q26511
deleteAnnotation
train
function deleteAnnotation() { if (!overlay) { return; } let annotationId = overlay.getAttribute('data-target-id'); let nodes = document.querySelectorAll(`[data-pdf-annotate-id="${annotationId}"]`); let svg = overlay.parentNode.querySelector('svg.annotationLayer'); let { documentId } = getMetadata(svg); [...nodes].forEach((n) => { n.parentNode.removeChild(n); }); PDFJSAnnotate.getStoreAdapter().deleteAnnotation(documentId, annotationId); destroyEditOverlay(); }
javascript
{ "resource": "" }
q26512
handleDocumentClick
train
function handleDocumentClick(e) { if (!findSVGAtPoint(e.clientX, e.clientY)) { return; } // Remove current overlay let overlay = document.getElementById('pdf-annotate-edit-overlay'); if (overlay) { if (isDragging || e.target === overlay) { return; } destroyEditOverlay(); } }
javascript
{ "resource": "" }
q26513
saveText
train
function saveText() { if (input.value.trim().length > 0) { let clientX = parseInt(input.style.left, 10); let clientY = parseInt(input.style.top, 10); let svg = findSVGAtPoint(clientX, clientY); if (!svg) { return; } let { documentId, pageNumber } = getMetadata(svg); let rect = svg.getBoundingClientRect(); let annotation = Object.assign({ type: 'textbox', size: _textSize, color: _textColor, content: input.value.trim() }, scaleDown(svg, { x: clientX - rect.left, y: clientY - rect.top, width: input.offsetWidth, height: input.offsetHeight }) ); PDFJSAnnotate.getStoreAdapter().addAnnotation(documentId, pageNumber, annotation) .then((annotation) => { appendChild(svg, annotation); }); } closeInput(); }
javascript
{ "resource": "" }
q26514
closeInput
train
function closeInput() { if (input) { input.removeEventListener('blur', handleInputBlur); input.removeEventListener('keyup', handleInputKeyup); document.body.removeChild(input); input = null; } }
javascript
{ "resource": "" }
q26515
transform
train
function transform(node, viewport) { let trans = getTranslation(viewport); // Let SVG natively transform the element node.setAttribute('transform', `scale(${viewport.scale}) rotate(${viewport.rotation}) translate(${trans.x}, ${trans.y})`); // Manually adjust x/y for nested SVG nodes if (!isFirefox && node.nodeName.toLowerCase() === 'svg') { node.setAttribute('x', parseInt(node.getAttribute('x'), 10) * viewport.scale); node.setAttribute('y', parseInt(node.getAttribute('y'), 10) * viewport.scale); let x = parseInt(node.getAttribute('x', 10)); let y = parseInt(node.getAttribute('y', 10)); let width = parseInt(node.getAttribute('width'), 10); let height = parseInt(node.getAttribute('height'), 10); let path = node.querySelector('path'); let svg = path.parentNode; // Scale width/height [node, svg, path, node.querySelector('rect')].forEach((n) => { n.setAttribute('width', parseInt(n.getAttribute('width'), 10) * viewport.scale); n.setAttribute('height', parseInt(n.getAttribute('height'), 10) * viewport.scale); }); // Transform path but keep scale at 100% since it will be handled natively transform(path, objectAssign({}, viewport, { scale: 1 })); switch(viewport.rotation % 360) { case 90: node.setAttribute('x', viewport.width - y - width); node.setAttribute('y', x); svg.setAttribute('x', 1); svg.setAttribute('y', 0); break; case 180: node.setAttribute('x', viewport.width - x - width); node.setAttribute('y', viewport.height - y - height); svg.setAttribute('y', 2); break; case 270: node.setAttribute('x', y); node.setAttribute('y', viewport.height - x - height); svg.setAttribute('x', -1); svg.setAttribute('y', 0); break; } } return node; }
javascript
{ "resource": "" }
q26516
scalePage
train
function scalePage(pageNumber, viewport, context) { let page = document.getElementById(`pageContainer${pageNumber}`); let canvas = page.querySelector('.canvasWrapper canvas'); let svg = page.querySelector('.annotationLayer'); let wrapper = page.querySelector('.canvasWrapper'); let textLayer = page.querySelector('.textLayer'); let outputScale = getOutputScale(context); let transform = !outputScale.scaled ? null : [outputScale.sx, 0, 0, outputScale.sy, 0, 0]; let sfx = approximateFraction(outputScale.sx); let sfy = approximateFraction(outputScale.sy); // Adjust width/height for scale page.style.visibility = ''; canvas.width = roundToDivide(viewport.width * outputScale.sx, sfx[0]); canvas.height = roundToDivide(viewport.height * outputScale.sy, sfy[0]); canvas.style.width = roundToDivide(viewport.width, sfx[1]) + 'px'; canvas.style.height = roundToDivide(viewport.height, sfx[1]) + 'px'; svg.setAttribute('width', viewport.width); svg.setAttribute('height', viewport.height); svg.style.width = `${viewport.width}px`; svg.style.height = `${viewport.height}px`; page.style.width = `${viewport.width}px`; page.style.height = `${viewport.height}px`; wrapper.style.width = `${viewport.width}px`; wrapper.style.height = `${viewport.height}px`; textLayer.style.width = `${viewport.width}px`; textLayer.style.height = `${viewport.height}px`; return transform; }
javascript
{ "resource": "" }
q26517
textLayerElementFromPoint
train
function textLayerElementFromPoint(x, y, pageNumber) { let svg = document.querySelector(`svg[data-pdf-annotate-page="${pageNumber}"]`); let rect = svg.getBoundingClientRect(); y = scaleUp(svg, {y}).y + rect.top; x = scaleUp(svg, {x}).x + rect.left; return [...svg.parentNode.querySelectorAll('.textLayer [data-canvas-width]')].filter((el) => { return pointIntersectsRect(x, y, el.getBoundingClientRect()); })[0]; }
javascript
{ "resource": "" }
q26518
savePoint
train
function savePoint(x, y) { let svg = findSVGAtPoint(x, y); if (!svg) { return; } let rect = svg.getBoundingClientRect(); let point = scaleDown(svg, { x: x - rect.left, y: y - rect.top }); lines.push([point.x, point.y]); if (lines.length <= 1) { return; } if (path) { svg.removeChild(path); } path = appendChild(svg, { type: 'drawing', color: _penColor, width: _penSize, lines }); }
javascript
{ "resource": "" }
q26519
sortByLinePoint
train
function sortByLinePoint(a, b) { let lineA = a.lines[0]; let lineB = b.lines[0]; return sortByPoint( {x: lineA[0], y: lineA[1]}, {x: lineB[0], y: lineB[1]} ); }
javascript
{ "resource": "" }
q26520
savePoint
train
function savePoint() { if (input.value.trim().length > 0) { let clientX = parseInt(input.style.left, 10); let clientY = parseInt(input.style.top, 10); let content = input.value.trim(); let svg = findSVGAtPoint(clientX, clientY); if (!svg) { return; } let rect = svg.getBoundingClientRect(); let { documentId, pageNumber } = getMetadata(svg); let annotation = Object.assign({ type: 'point' }, scaleDown(svg, { x: clientX - rect.left, y: clientY - rect.top }) ); PDFJSAnnotate.getStoreAdapter().addAnnotation(documentId, pageNumber, annotation) .then((annotation) => { PDFJSAnnotate.getStoreAdapter().addComment( documentId, annotation.uuid, content ); appendChild(svg, annotation); }); } closeInput(); }
javascript
{ "resource": "" }
q26521
binarySearchFirstItem
train
function binarySearchFirstItem(items, condition) { var minIndex = 0; var maxIndex = items.length - 1; if (items.length === 0 || !condition(items[maxIndex])) { return items.length; } if (condition(items[minIndex])) { return minIndex; } while (minIndex < maxIndex) { var currentIndex = (minIndex + maxIndex) >> 1; var currentItem = items[currentIndex]; if (condition(currentItem)) { maxIndex = currentIndex; } else { minIndex = currentIndex + 1; } } return minIndex; /* === maxIndex */ }
javascript
{ "resource": "" }
q26522
PDFRenderingQueue_renderView
train
function PDFRenderingQueue_renderView(view) { var state = view.renderingState; switch (state) { case RenderingStates.FINISHED: return false; case RenderingStates.PAUSED: this.highestPriorityPage = view.renderingId; view.resume(); break; case RenderingStates.RUNNING: this.highestPriorityPage = view.renderingId; break; case RenderingStates.INITIAL: this.highestPriorityPage = view.renderingId; var continueRendering = function () { this.renderHighestPriority(); }.bind(this); view.draw().then(continueRendering, continueRendering); break; } return true; }
javascript
{ "resource": "" }
q26523
reorderAnnotationsByType
train
function reorderAnnotationsByType(documentId, pageNumber, type) { PDFJSAnnotate.getStoreAdapter().getAnnotations(documentId, pageNumber) .then((annotations) => { return annotations.annotations.filter((a) => { return a.type === type; }); }) .then((annotations) => { annotations.forEach((a) => { removeAnnotation(documentId, a.uuid); }); return annotations; }) .then(renderScreenReaderHints); }
javascript
{ "resource": "" }
q26524
insertComment
train
function insertComment(documentId, annotationId, comment) { let list = document.querySelector(`pdf-annotate-screenreader-comment-list-${annotationId}`); let promise; if (!list) { promise = renderScreenReaderComments(documentId, annotationId, []).then(() => { list = document.querySelector(`pdf-annotate-screenreader-comment-list-${annotationId}`); return true; }); } else { promise = Promise.resolve(true); } promise.then(() => { insertScreenReaderComment(comment); }); }
javascript
{ "resource": "" }
q26525
removeElementById
train
function removeElementById(elementId) { let el = document.getElementById(elementId); if (el) { el.parentNode.removeChild(el); } }
javascript
{ "resource": "" }
q26526
getSelectionRects
train
function getSelectionRects() { try { let selection = window.getSelection(); let range = selection.getRangeAt(0); let rects = range.getClientRects(); if (rects.length > 0 && rects[0].width > 0 && rects[0].height > 0) { return rects; } } catch (e) {} return null; }
javascript
{ "resource": "" }
q26527
saveRect
train
function saveRect(type, rects, color) { let svg = findSVGAtPoint(rects[0].left, rects[0].top); let node; let annotation; if (!svg) { return; } let boundingRect = svg.getBoundingClientRect(); if (!color) { if (type === 'highlight') { color = 'FFFF00'; } else if (type === 'strikeout') { color = 'FF0000'; } } // Initialize the annotation annotation = { type, color, rectangles: [...rects].map((r) => { let offset = 0; if (type === 'strikeout') { offset = r.height / 2; } return scaleDown(svg, { y: (r.top + offset) - boundingRect.top, x: r.left - boundingRect.left, width: r.width, height: r.height }); }).filter((r) => r.width > 0 && r.height > 0 && r.x > -1 && r.y > -1) }; // Short circuit if no rectangles exist if (annotation.rectangles.length === 0) { return; } // Special treatment for area as it only supports a single rect if (type === 'area') { let rect = annotation.rectangles[0]; delete annotation.rectangles; annotation.x = rect.x; annotation.y = rect.y; annotation.width = rect.width; annotation.height = rect.height; } let { documentId, pageNumber } = getMetadata(svg); // Add the annotation PDFJSAnnotate.getStoreAdapter().addAnnotation(documentId, pageNumber, annotation) .then((annotation) => { appendChild(svg, annotation); }); }
javascript
{ "resource": "" }
q26528
redraw
train
function redraw(fitties) { // getting info from the DOM at this point should not trigger a reflow, let's gather as much intel as possible before triggering a reflow // check if styles of all fitties have been computed fitties.filter(function (f) { return !f.styleComputed; }).forEach(function (f) { f.styleComputed = computeStyle(f); }); // restyle elements that require pre-styling, this triggers a reflow, please try to prevent by adding CSS rules (see docs) fitties.filter(shouldPreStyle).forEach(applyStyle); // we now determine which fitties should be redrawn var fittiesToRedraw = fitties.filter(shouldRedraw); // we calculate final styles for these fitties fittiesToRedraw.forEach(calculateStyles); // now we apply the calculated styles from our previous loop fittiesToRedraw.forEach(function (f) { applyStyle(f); markAsClean(f); }); // now we dispatch events for all restyled fitties fittiesToRedraw.forEach(dispatchFitEvent); }
javascript
{ "resource": "" }
q26529
shouldRedraw
train
function shouldRedraw(f) { return f.dirty !== DrawState.DIRTY_LAYOUT || f.dirty === DrawState.DIRTY_LAYOUT && f.element.parentNode.clientWidth !== f.availableWidth; }
javascript
{ "resource": "" }
q26530
computeStyle
train
function computeStyle(f) { // get style properties var style = w.getComputedStyle(f.element, null); // get current font size in pixels (if we already calculated it, use the calculated version) f.currentFontSize = parseInt(style.getPropertyValue('font-size'), 10); // get display type and wrap mode f.display = style.getPropertyValue('display'); f.whiteSpace = style.getPropertyValue('white-space'); }
javascript
{ "resource": "" }
q26531
shouldPreStyle
train
function shouldPreStyle(f) { var preStyle = false; // if we already tested for prestyling we don't have to do it again if (f.preStyleTestCompleted) { return false; } // should have an inline style, if not, apply if (!/inline-/.test(f.display)) { preStyle = true; f.display = 'inline-block'; } // to correctly calculate dimensions the element should have whiteSpace set to nowrap if (f.whiteSpace !== 'nowrap') { preStyle = true; f.whiteSpace = 'nowrap'; } // we don't have to do this twice f.preStyleTestCompleted = true; return preStyle; }
javascript
{ "resource": "" }
q26532
applyStyle
train
function applyStyle(f) { // remember original style, we need this to restore the fitty style when unsubscribing if (!f.originalStyle) { f.originalStyle = f.element.getAttribute('style') || ''; } // set the new style to the original style plus the fitty styles f.element.style.cssText = f.originalStyle + ';white-space:' + f.whiteSpace + ';display:' + f.display + ';font-size:' + f.currentFontSize + 'px'; }
javascript
{ "resource": "" }
q26533
dispatchFitEvent
train
function dispatchFitEvent(f) { f.element.dispatchEvent(new CustomEvent('fit', { detail: { oldValue: f.previousFontSize, newValue: f.currentFontSize, scaleFactor: f.currentFontSize / f.previousFontSize } })); }
javascript
{ "resource": "" }
q26534
subscribe
train
function subscribe(f) { // this is a new fitty so we need to validate if it's styles are in order f.newbie = true; // because it's a new fitty it should also be dirty, we want it to redraw on the first loop f.dirty = true; // we want to be able to update this fitty fitties.push(f); }
javascript
{ "resource": "" }
q26535
unsubscribe
train
function unsubscribe(f) { return function () { // remove from fitties array fitties = fitties.filter(function (_) { return _.element !== f.element; }); // stop observing DOM if (f.observeMutations) { f.observer.disconnect(); } // reset font size to inherited size f.element.style.cssText = f.originalStyle; }; }
javascript
{ "resource": "" }
q26536
fittyCreate
train
function fittyCreate(elements, options) { // set options object var fittyOptions = _extends({}, defaultOptions, options); // create fitties var publicFitties = elements.map(function (element) { // create fitty instance var f = _extends({}, fittyOptions, { // internal options for this fitty element: element }); // register this fitty subscribe(f); // should we observe DOM mutations observeMutations(f); // expose API return { element: element, fit: fit(f, DrawState.DIRTY), unsubscribe: unsubscribe(f) }; }); // call redraw on newly initiated fitties requestRedraw(); // expose fitties return publicFitties; }
javascript
{ "resource": "" }
q26537
fitty
train
function fitty(target) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; // if target is a string return typeof target === 'string' ? // treat it as a querySelector fittyCreate(toArray(document.querySelectorAll(target)), options) : // create single fitty fittyCreate([target], options)[0]; }
javascript
{ "resource": "" }
q26538
loadFormatters
train
function loadFormatters(){ var arrFiles = glob.sync('./formatters/*.js', { 'cwd': __dirname, 'dot': false, 'nodir': true, 'strict': false, 'silent': true }); var mapFormatters = {}; arrFiles.forEach(function(file){ var fileInfo = path.parse(file); var formatterPath = path.resolve(__dirname, file); mapFormatters[fileInfo.name] = require(formatterPath); }); return mapFormatters; }
javascript
{ "resource": "" }
q26539
train
function(constructor, obj, pluginName) { // if it's not already bridged if (!obj[pluginName]) { var fn = function() {}; fn.prototype = constructor; var pluginInstance = new fn(); // the _init method has to exist in instance constructors but might be missing // in core constructors if (pluginInstance.__init) { pluginInstance.__init(obj); } $.each(constructor, function(methodName, fn) { // don't proxy "private" methods, only "protected" and public ones if (methodName.indexOf('__') != 0) { // if the method does not exist yet if (!obj[methodName]) { obj[methodName] = function() { return pluginInstance[methodName].apply(pluginInstance, Array.prototype.slice.apply(arguments)); }; // remember to which plugin this method corresponds (several plugins may // have methods of the same name, we need to be sure) obj[methodName].bridged = pluginInstance; } else if (defaults.debug) { console.log('The '+ methodName +' method of the '+ pluginName +' plugin conflicts with another plugin or native methods'); } } }); obj[pluginName] = pluginInstance; } return this; }
javascript
{ "resource": "" }
q26540
train
function() { var args = Array.prototype.slice.apply(arguments); if (typeof args[0] == 'string') { args[0] = { type: args[0] }; } // note: the order of emitters matters this.__$emitterPrivate.trigger.apply(this.__$emitterPrivate, args); this.__$emitterPublic.trigger.apply(this.__$emitterPublic, args); return this; }
javascript
{ "resource": "" }
q26541
train
function(selector) { var instances = [], sel = selector || '.tooltipstered'; $(sel).each(function() { var $this = $(this), ns = $this.data('tooltipster-ns'); if (ns) { $.each(ns, function(i, namespace) { instances.push($this.data(namespace)); }); } }); return instances; }
javascript
{ "resource": "" }
q26542
train
function() { var self = this, $el = self._$tooltip.find('.tooltipster-content'), formattedContent = self.__Content, format = function(content) { formattedContent = content; }; self._trigger({ type: 'format', content: self.__Content, format: format }); if (self.__options.functionFormat) { formattedContent = self.__options.functionFormat.call( self, self, { origin: self._$origin[0] }, self.__Content ); } if (typeof formattedContent === 'string' && !self.__options.contentAsHTML) { $el.text(formattedContent); } else { $el .empty() .append(formattedContent); } return self; }
javascript
{ "resource": "" }
q26543
train
function(content) { // clone if asked. Cloning the object makes sure that each instance has its // own version of the content (in case a same object were provided for several // instances) // reminder: typeof null === object if (content instanceof $ && this.__options.contentCloning) { content = content.clone(true); } this.__Content = content; this._trigger({ type: 'updated', content: content }); return this; }
javascript
{ "resource": "" }
q26544
train
function(r) { geo.origin.size.height = r.height, geo.origin.windowOffset.left = r.left, geo.origin.windowOffset.top = r.top, geo.origin.size.width = r.width }
javascript
{ "resource": "" }
q26545
train
function() { if (typeof this.__options.animationDuration == 'number') { this.__options.animationDuration = [this.__options.animationDuration, this.__options.animationDuration]; } if (typeof this.__options.delay == 'number') { this.__options.delay = [this.__options.delay, this.__options.delay]; } if (typeof this.__options.delayTouch == 'number') { this.__options.delayTouch = [this.__options.delayTouch, this.__options.delayTouch]; } if (typeof this.__options.theme == 'string') { this.__options.theme = [this.__options.theme]; } // determine the future parent if (this.__options.parent === null) { this.__options.parent = $(env.window.document.body); } else if (typeof this.__options.parent == 'string') { this.__options.parent = $(this.__options.parent); } if (this.__options.trigger == 'hover') { this.__options.triggerOpen = { mouseenter: true, touchstart: true }; this.__options.triggerClose = { mouseleave: true, originClick: true, touchleave: true }; } else if (this.__options.trigger == 'click') { this.__options.triggerOpen = { click: true, tap: true }; this.__options.triggerClose = { click: true, tap: true }; } // for the plugins this._trigger('options'); return this; }
javascript
{ "resource": "" }
q26546
train
function() { var self = this; // in case the selfDestruction option has been changed by a method call if (self.__options.selfDestruction) { // the GC task self.__garbageCollector = setInterval(function() { var now = new Date().getTime(); // forget the old events self.__touchEvents = $.grep(self.__touchEvents, function(event, i) { // 1 minute return now - event.time > 60000; }); // auto-destruct if the origin is gone if (!bodyContains(self._$origin)) { self.close(function(){ self.destroy(); }); } }, 20000); } else { clearInterval(self.__garbageCollector); } return self; }
javascript
{ "resource": "" }
q26547
train
function() { // there is only one possible open timeout: the delayed opening // when the mouseenter/touchstart open triggers are used clearTimeout(this.__timeouts.open); this.__timeouts.open = null; // ... but several close timeouts: the delayed closing when the // mouseleave close trigger is used and the timer option $.each(this.__timeouts.close, function(i, timeout) { clearTimeout(timeout); }); this.__timeouts.close = []; return this; }
javascript
{ "resource": "" }
q26548
train
function(pluginName, defaultOptions) { var self = this, options = $.extend(true, {}, defaultOptions); // if the plugin options were isolated in a property named after the // plugin, use them (prevents conflicts with other plugins) var pluginOptions = self.__options[pluginName]; // if not, try to get them as regular options if (!pluginOptions){ pluginOptions = {}; $.each(defaultOptions, function(optionName, value) { var o = self.__options[optionName]; if (o !== undefined) { pluginOptions[optionName] = o; } }); } // let's merge the default options and the ones that were provided. We'd want // to do a deep copy but not let jQuery merge arrays, so we'll do a shallow // extend on two levels, that will be enough if options are not more than 1 // level deep $.each(options, function(optionName, value) { if (pluginOptions[optionName] !== undefined) { if (( typeof value == 'object' && !(value instanceof Array) && value != null ) && ( typeof pluginOptions[optionName] == 'object' && !(pluginOptions[optionName] instanceof Array) && pluginOptions[optionName] != null ) ) { $.extend(options[optionName], pluginOptions[optionName]); } else { options[optionName] = pluginOptions[optionName]; } } }); return options; }
javascript
{ "resource": "" }
q26549
train
function(pluginName) { var plugin = $.tooltipster._plugin(pluginName); if (plugin) { // if there is a constructor for instances if (plugin.instance) { // proxy non-private methods on the instance to allow new instance methods $.tooltipster.__bridge(plugin.instance, this, plugin.name); } } else { throw new Error('The "'+ pluginName +'" plugin is not defined'); } return this; }
javascript
{ "resource": "" }
q26550
train
function(event) { var isEmulated = false, now = new Date().getTime(); for (var i = this.__touchEvents.length - 1; i >= 0; i--) { var e = this.__touchEvents[i]; // delay, in milliseconds. It's supposed to be 300ms in // most browsers (350ms on iOS) to allow a double tap but // can be less (check out FastClick for more info) if (now - e.time < 500) { if (e.target === event.target) { isEmulated = true; } } else { break; } } return isEmulated; }
javascript
{ "resource": "" }
q26551
train
function(event) { return ( (this._touchIsTouchEvent(event) && !this._touchSwiped(event.target)) || (!this._touchIsTouchEvent(event) && !this._touchIsEmulatedEvent(event)) ); }
javascript
{ "resource": "" }
q26552
train
function(event) { if (this._touchIsTouchEvent(event)) { event.time = new Date().getTime(); this.__touchEvents.push(event); } return this; }
javascript
{ "resource": "" }
q26553
train
function(target) { var swiped = false; for (var i = this.__touchEvents.length - 1; i >= 0; i--) { var e = this.__touchEvents[i]; if (e.type == 'touchmove') { swiped = true; break; } else if ( e.type == 'touchstart' && target === e.target ) { break; } } return swiped; }
javascript
{ "resource": "" }
q26554
train
function() { var args = Array.prototype.slice.apply(arguments); if (typeof args[0] == 'string') { args[0] = { type: args[0] }; } // add properties to the event args[0].instance = this; args[0].origin = this._$origin ? this._$origin[0] : null; args[0].tooltip = this._$tooltip ? this._$tooltip[0] : null; // note: the order of emitters matters this.__$emitterPrivate.trigger.apply(this.__$emitterPrivate, args); $.tooltipster._trigger.apply($.tooltipster, args); this.__$emitterPublic.trigger.apply(this.__$emitterPublic, args); return this; }
javascript
{ "resource": "" }
q26555
train
function(pluginName) { var self = this; // if the plugin has been activated on this instance if (self[pluginName]) { var plugin = $.tooltipster._plugin(pluginName); // if there is a constructor for instances if (plugin.instance) { // unbridge $.each(plugin.instance, function(methodName, fn) { // if the method exists (privates methods do not) and comes indeed from // this plugin (may be missing or come from a conflicting plugin). if ( self[methodName] && self[methodName].bridged === self[pluginName] ) { delete self[methodName]; } }); } // destroy the plugin if (self[pluginName].__destroy) { self[pluginName].__destroy(); } // remove the reference to the plugin instance delete self[pluginName]; } return self; }
javascript
{ "resource": "" }
q26556
train
function(content) { var self = this; // getter method if (content === undefined) { return self.__Content; } // setter method else { if (!self.__destroyed) { // change the content self.__contentSet(content); if (self.__Content !== null) { // update the tooltip if it is open if (self.__state !== 'closed') { // reset the content in the tooltip self.__contentInsert(); // reposition and resize the tooltip self.reposition(); // if we want to play a little animation showing the content changed if (self.__options.updateAnimation) { if (env.hasTransitions) { // keep the reference in the local scope var animation = self.__options.updateAnimation; self._$tooltip.addClass('tooltipster-update-'+ animation); // remove the class after a while. The actual duration of the // update animation may be shorter, it's set in the CSS rules setTimeout(function() { if (self.__state != 'closed') { self._$tooltip.removeClass('tooltipster-update-'+ animation); } }, 1000); } else { self._$tooltip.fadeTo(200, 0.5, function() { if (self.__state != 'closed') { self._$tooltip.fadeTo(200, 1); } }); } } } } else { self._close(); } } else { self.__destroyError(); } return self; } }
javascript
{ "resource": "" }
q26557
train
function() { var self = this; if (!self.__destroyed) { if(self.__state != 'closed'){ // no closing delay self.option('animationDuration', 0) // force closing ._close(null, null, true); } else { // there might be an open timeout still running self.__timeoutsClear(); } // send event self._trigger('destroy'); self.__destroyed = true; self._$origin .removeData(self.__namespace) // remove the open trigger listeners .off('.'+ self.__namespace +'-triggerOpen'); // remove the touch listener $(env.window.document.body).off('.' + self.__namespace +'-triggerOpen'); var ns = self._$origin.data('tooltipster-ns'); // if the origin has been removed from DOM, its data may // well have been destroyed in the process and there would // be nothing to clean up or restore if (ns) { // if there are no more tooltips on this element if (ns.length === 1) { // optional restoration of a title attribute var title = null; if (self.__options.restoration == 'previous') { title = self._$origin.data('tooltipster-initialTitle'); } else if (self.__options.restoration == 'current') { // old school technique to stringify when outerHTML is not supported title = (typeof self.__Content == 'string') ? self.__Content : $('<div></div>').append(self.__Content).html(); } if (title) { self._$origin.attr('title', title); } // final cleaning self._$origin.removeClass('tooltipstered'); self._$origin .removeData('tooltipster-ns') .removeData('tooltipster-initialTitle'); } else { // remove the instance namespace from the list of namespaces of // tooltips present on the element ns = $.grep(ns, function(el, i) { return el !== self.__namespace; }); self._$origin.data('tooltipster-ns', ns); } } // last event self._trigger('destroyed'); // unbind private and public event listeners self._off(); self.off(); // remove external references, just in case self.__Content = null; self.__$emitterPrivate = null; self.__$emitterPublic = null; self.__options.parent = null; self._$origin = null; self._$tooltip = null; // make sure the object is no longer referenced in there to prevent // memory leaks $.tooltipster.__instancesLatestArr = $.grep($.tooltipster.__instancesLatestArr, function(el, i) { return self !== el; }); clearInterval(self.__garbageCollector); } else { self.__destroyError(); } // we return the scope rather than true so that the call to // .tooltipster('destroy') actually returns the matched elements // and applies to all of them return self; }
javascript
{ "resource": "" }
q26558
train
function(o, val) { // getter if (val === undefined) { return this.__options[o]; } // setter else { if (!this.__destroyed) { // change value this.__options[o] = val; // format this.__optionsFormat(); // re-prepare the triggers if needed if ($.inArray(o, ['trigger', 'triggerClose', 'triggerOpen']) >= 0) { this.__prepareOrigin(); } if (o === 'selfDestruction') { this.__prepareGC(); } } else { this.__destroyError(); } return this; } }
javascript
{ "resource": "" }
q26559
train
function() { if (!this.__destroyed) { this.__$emitterPublic.triggerHandler.apply(this.__$emitterPublic, Array.prototype.slice.apply(arguments)); } else { this.__destroyError(); } return this; }
javascript
{ "resource": "" }
q26560
train
function() { this.__forceRedraw(); var tooltipBcr = this.__$tooltip[0].getBoundingClientRect(), result = { size: { // bcr.width/height are not defined in IE8- but in this // case, bcr.right/bottom will have the same value // except in iOS 8+ where tooltipBcr.bottom/right are wrong // after scrolling for reasons yet to be determined. // tooltipBcr.top/left might not be 0, see issue #514 height: tooltipBcr.height || (tooltipBcr.bottom - tooltipBcr.top), width: tooltipBcr.width || (tooltipBcr.right - tooltipBcr.left) }}; if (this.constraints) { // note: we used to use offsetWidth instead of boundingRectClient but // it returned rounded values, causing issues with sub-pixel layouts. // note2: noticed that the bcrWidth of text content of a div was once // greater than the bcrWidth of its container by 1px, causing the final // tooltip box to be too small for its content. However, evaluating // their widths one against the other (below) surprisingly returned // equality. Happened only once in Chrome 48, was not able to reproduce // => just having fun with float position values... var $content = this.__$tooltip.find('.tooltipster-content'), height = this.__$tooltip.outerHeight(), contentBcr = $content[0].getBoundingClientRect(), fits = { height: height <= this.constraints.height, width: ( // this condition accounts for min-width property that // may apply tooltipBcr.width <= this.constraints.width // the -1 is here because scrollWidth actually returns // a rounded value, and may be greater than bcr.width if // it was rounded up. This may cause an issue for contents // which actually really overflow by 1px or so, but that // should be rare. Not sure how to solve this efficiently. // See http://blogs.msdn.com/b/ie/archive/2012/02/17/sub-pixel-rendering-and-the-css-object-model.aspx && contentBcr.width >= $content[0].scrollWidth - 1 ) }; result.fits = fits.height && fits.width; } // old versions of IE get the width wrong for some reason and it causes // the text to be broken to a new line, so we round it up. If the width // is the width of the screen though, we can assume it is accurate. if ( env.IE && env.IE <= 11 && result.size.width !== env.window.document.documentElement.clientWidth ) { result.size.width = Math.ceil(result.size.width) + 1; } return result; }
javascript
{ "resource": "" }
q26561
areEqual
train
function areEqual(a,b) { var same = true; $.each(a, function(i, _) { if (b[i] === undefined || a[i] !== b[i]) { same = false; return false; } }); return same; }
javascript
{ "resource": "" }
q26562
bodyContains
train
function bodyContains($obj) { var id = $obj.attr('id'), el = id ? env.window.document.getElementById(id) : null; // must also check that the element with the id is the one we want return el ? el === $obj[0] : $.contains(env.window.document.body, $obj[0]); }
javascript
{ "resource": "" }
q26563
train
function() { return { // if the tooltip should display an arrow that points to the origin arrow: true, // the distance in pixels between the tooltip and the origin distance: 6, // allows to easily change the position of the tooltip functionPosition: null, maxWidth: null, // used to accomodate the arrow of tooltip if there is one. // First to make sure that the arrow target is not too close // to the edge of the tooltip, so the arrow does not overflow // the tooltip. Secondly when we reposition the tooltip to // make sure that it's positioned in such a way that the arrow is // still pointing at the target (and not a few pixels beyond it). // It should be equal to or greater than half the width of // the arrow (by width we mean the size of the side which touches // the side of the tooltip). minIntersection: 16, minWidth: 0, // deprecated in 4.0.0. Listed for _optionsExtract to pick it up position: null, side: 'top', // set to false to position the tooltip relatively to the document rather // than the window when we open it viewportAware: true }; }
javascript
{ "resource": "" }
q26564
train
function() { // detach our content object first, so the next jQuery's remove() // call does not unbind its event handlers if (this.__instance.content() instanceof $) { this.__instance.content().detach(); } // remove the tooltip from the DOM this.__instance._$tooltip.remove(); this.__instance._$tooltip = null; }
javascript
{ "resource": "" }
q26565
train
function() { // note: we wrap with a .tooltipster-box div to be able to set a margin on it // (.tooltipster-base must not have one) var $html = $( '<div class="tooltipster-base tooltipster-sidetip">' + '<div class="tooltipster-box">' + '<div class="tooltipster-content"></div>' + '</div>' + '<div class="tooltipster-arrow">' + '<div class="tooltipster-arrow-uncropped">' + '<div class="tooltipster-arrow-border"></div>' + '<div class="tooltipster-arrow-background"></div>' + '</div>' + '</div>' + '</div>' ); // hide arrow if asked if (!this.__options.arrow) { $html .find('.tooltipster-box') .css('margin', 0) .end() .find('.tooltipster-arrow') .hide(); } // apply min/max width if asked if (this.__options.minWidth) { $html.css('min-width', this.__options.minWidth + 'px'); } if (this.__options.maxWidth) { $html.css('max-width', this.__options.maxWidth + 'px'); } this.__instance._$tooltip = $html; // tell the instance that the tooltip element has been created this.__instance._trigger('created'); }
javascript
{ "resource": "" }
q26566
train
function(instance, helper, data){ // this function is pretty dumb and does not check if there is actually // enough space available around the tooltip to move it, it just makes it // snap to the grid. You might want to do something smarter in your app! var gridBcr = $('#demo-position-grid')[0].getBoundingClientRect(), arrowSize = parseInt($(helper.tooltipClone).find('.tooltipster-box').css('margin-left')); // override these data.coord = { // move the tooltip so the arrow overflows the grid left: gridBcr.left - arrowSize, top: gridBcr.top }; return data; }
javascript
{ "resource": "" }
q26567
isWriteable
train
function isWriteable(file) { let writePermission = true; try { const __fd = fs.openSync(file, 'a'); fs.closeSync(__fd); } catch (e) { /* istanbul ignore next */ writePermission = false; } return writePermission; }
javascript
{ "resource": "" }
q26568
print
train
function print() { var parts = String(out).split('\n'); /* istanbul ignore next */ if (parts.length > 1) { out = parts.pop(); var logging = String(parts.join('\n')).replace(/\r\r/g, '\r'); slf.log(logging); } /* istanbul ignore next */ if (closed === false) { setTimeout(function () { print(); }, 50); } }
javascript
{ "resource": "" }
q26569
file
train
function file(path, options) { try { try { fs.lstatSync(path); } catch (e) { // If the file doesn't exist and // the user doesn't want to create it, // we have no purpose in life. Goodbye. if (options.create === false) { throw new Error(e); } else { fs.closeSync(fs.openSync(path, 'wx')); } } var stat = fs.statSync(path); var dateToSet = options.date ? Date.create(options.date) : new Date(); if (String(dateToSet) === 'Invalid Date') { throw new Error('touch: invalid date format ' + options.date); } // If -m, keep access time current. var atime = options.m === true ? new Date(stat.atime) : dateToSet; // If -a, keep mod time to current. var mtime = options.a === true ? new Date(stat.mtime) : dateToSet; if (options.reference !== undefined) { var reference = void 0; try { reference = fs.statSync(options.reference); } catch (e) { throw new Error('touch: failed to get attributes of ' + options.reference + ': No such file or directory'); } atime = options.m === true ? atime : reference.atime; mtime = options.a === true ? mtime : reference.mtime; } fs.utimesSync(path, atime, mtime); fs.utimesSync(path, atime, mtime); } catch (e) { throw new Error(e); } }
javascript
{ "resource": "" }
q26570
error
train
function error(path, e) { var status = void 0; var stdout = void 0; if (e.code === 'ENOENT' && e.syscall === 'scandir') { status = 1; stdout = 'ls: cannot access ' + path + ': No such file or directory'; } else { status = 2; stdout = e.stack; } ls.self.log(stdout); return { status: status, stdout: stdout }; }
javascript
{ "resource": "" }
q26571
execDirRecursive
train
function execDirRecursive(path, options) { var self = this; var results = []; walkDirRecursive(path, function (pth) { var result = self.execDir(pth, options); results.push(result); }); return results; }
javascript
{ "resource": "" }
q26572
execDir
train
function execDir(path, options) { var rawFiles = []; function pushFile(file, data) { rawFiles.push({ file: file, data: data }); } // Add in implied current and parent dirs. pushFile('.', fs.statSync('.')); pushFile('..', fs.statSync('..')); // Walk the passed in directory, // pushing the results into `rawFiles`. walkDir(path, pushFile, ls.error); var o = ls.execLsOnFiles(path, rawFiles, options); o.path = path; return o; }
javascript
{ "resource": "" }
q26573
formatAll
train
function formatAll(results, options, showName) { var stdout = ''; if (showName) { for (var i = 0; i < results.length; ++i) { stdout += results[i].path + ':\n'; if (options.l) { stdout += 'total ' + results[i].size + '\n'; } stdout += results[i].results; if (i !== results.length - 1) { stdout += '\n\n'; } } } else if (results.length === 1) { if (options.l && !options.x) { stdout += 'total ' + results[0].size + '\n'; } stdout += results[0].results; } return stdout; }
javascript
{ "resource": "" }
q26574
train
function() { var parser = new(window.UAParser || exports.UAParser); browserData = parser.getResult(); fontDetective = new Detector(); return this; }
javascript
{ "resource": "" }
q26575
train
function() { var bar = '|'; var userAgent = browserData.ua; var screenPrint = this.getScreenPrint(); var pluginList = this.getPlugins(); var fontList = this.getFonts(); var localStorage = this.isLocalStorage(); var sessionStorage = this.isSessionStorage(); var timeZone = this.getTimeZone(); var language = this.getLanguage(); var systemLanguage = this.getSystemLanguage(); var cookies = this.isCookie(); var canvasPrint = this.getCanvasPrint(); var key = userAgent + bar + screenPrint + bar + pluginList + bar + fontList + bar + localStorage + bar + sessionStorage + bar + timeZone + bar + language + bar + systemLanguage + bar + cookies + bar + canvasPrint; var seed = 256; return murmurhash3_32_gc(key, seed); }
javascript
{ "resource": "" }
q26576
train
function() { var bar = '|'; var key = ""; for (var i = 0; i < arguments.length; i++) { key += arguments[i] + bar; } return murmurhash3_32_gc(key, 256); }
javascript
{ "resource": "" }
q26577
train
function() { // detectmobilebrowsers.com JavaScript Mobile Detection Script var dataString = browserData.ua || navigator.vendor || window.opera; return (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(dataString) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(dataString.substr(0, 4))); }
javascript
{ "resource": "" }
q26578
train
function() { var pluginsList = ""; for (var i = 0; i < navigator.plugins.length; i++) { if (i == navigator.plugins.length - 1) { pluginsList += navigator.plugins[i].name; } else { pluginsList += navigator.plugins[i].name + ", "; } } return pluginsList; }
javascript
{ "resource": "" }
q26579
train
function() { var mimeTypeList = ""; for (var i = 0; i < navigator.mimeTypes.length; i++) { if (i == navigator.mimeTypes.length - 1) { mimeTypeList += navigator.mimeTypes[i].description; } else { mimeTypeList += navigator.mimeTypes[i].description + ", "; } } return mimeTypeList; }
javascript
{ "resource": "" }
q26580
train
function() { // create a canvas element var canvas = document.createElement('canvas'); // define a context var that will be used for browsers with canvas support var ctx; // try/catch for older browsers that don't support the canvas element try { // attempt to give ctx a 2d canvas context value ctx = canvas.getContext('2d'); } catch (e) { // return empty string if canvas element not supported return ""; } // https://www.browserleaks.com/canvas#how-does-it-work // Text with lowercase/uppercase/punctuation symbols var txt = 'ClientJS,org <canvas> 1.0'; ctx.textBaseline = "top"; // The most common type ctx.font = "14px 'Arial'"; ctx.textBaseline = "alphabetic"; ctx.fillStyle = "#f60"; ctx.fillRect(125, 1, 62, 20); // Some tricks for color mixing to increase the difference in rendering ctx.fillStyle = "#069"; ctx.fillText(txt, 2, 15); ctx.fillStyle = "rgba(102, 204, 0, 0.7)"; ctx.fillText(txt, 4, 17); return canvas.toDataURL(); }
javascript
{ "resource": "" }
q26581
createToken
train
function createToken(options) { const newToken = chevrotain.createToken(options) allTokens.push(newToken) return newToken }
javascript
{ "resource": "" }
q26582
minimizeCst
train
function minimizeCst(cstElement) { // tokenType idx is auto generated, can't assert over it if (cstElement.tokenType) { delete cstElement.tokenType } // CstNode if (cstElement.children !== undefined) { cstElement.children = _.omitBy(cstElement.children, _.isEmpty) _.forEach(cstElement.children, childArr => { _.forEach(childArr, minimizeCst) }) } return cstElement }
javascript
{ "resource": "" }
q26583
toOriginalText
train
function toOriginalText(item) { if (_.has(item, "tokenName")) { return item.tokenName } else if (item instanceof Rule) { return item.name } else if (_.isString(item)) { return item } else if (_.has(item, "toRule")) { return item.definition.orgText } else { throw Error(`Unexpected Argument type ${item}`) } }
javascript
{ "resource": "" }
q26584
nextRight
train
function nextRight(v) { var children = v.children; return children ? children[children.length - 1] : v.t; }
javascript
{ "resource": "" }
q26585
firstWalk
train
function firstWalk(v) { var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null; if (children) { executeShifts(v); var midpoint = (children[0].z + children[children.length - 1].z) / 2; if (w) { v.z = w.z + separation(v._, w._); v.m = v.z - midpoint; } else { v.z = midpoint; } } else if (w) { v.z = w.z + separation(v._, w._); } v.parent.A = apportion(v, w, v.parent.A || siblings[0]); }
javascript
{ "resource": "" }
q26586
train
function(name, theme) { name != null && theme != null && (App.settings.themes[name] = theme); delete App.vars.cache.themeKeys; return this; }
javascript
{ "resource": "" }
q26587
train
function(src, el) { //todo: use jquery fallback if available for all QSA references var nodes = DOM.getNodeArray(el); nodes.forEach(function (node) { var img = DOM.newEl('img'); var domProps = {}; domProps[App.setup.dataAttr] = src; DOM.setAttr(img, domProps); node.appendChild(img); }); return this; }
javascript
{ "resource": "" }
q26588
train
function(el, value) { if (el.holderData) { el.holderData.resizeUpdate = !!value; if (el.holderData.resizeUpdate) { updateResizableElements(el); } } }
javascript
{ "resource": "" }
q26589
prepareImageElement
train
function prepareImageElement(options, engineSettings, src, el) { var holderFlags = parseURL(src.substr(src.lastIndexOf(options.domain)), options); if (holderFlags) { prepareDOMElement({ mode: null, el: el, flags: holderFlags, engineSettings: engineSettings }); } }
javascript
{ "resource": "" }
q26590
render
train
function render(renderSettings) { var image = null; var mode = renderSettings.mode; var el = renderSettings.el; var holderSettings = renderSettings.holderSettings; var engineSettings = renderSettings.engineSettings; switch (engineSettings.renderer) { case 'svg': if (!App.setup.supportsSVG) return; break; case 'canvas': if (!App.setup.supportsCanvas) return; break; default: return; } //todo: move generation of scene up to flag generation to reduce extra object creation var scene = { width: holderSettings.dimensions.width, height: holderSettings.dimensions.height, theme: holderSettings.theme, flags: holderSettings.flags }; var sceneGraph = buildSceneGraph(scene); function getRenderedImage() { var image = null; switch (engineSettings.renderer) { case 'canvas': image = sgCanvasRenderer(sceneGraph, renderSettings); break; case 'svg': image = svgRenderer(sceneGraph, renderSettings); break; default: throw 'Holder: invalid renderer: ' + engineSettings.renderer; } return image; } image = getRenderedImage(); if (image == null) { throw 'Holder: couldn\'t render placeholder'; } //todo: add <object> canvas rendering if (mode == 'background') { el.style.backgroundImage = 'url(' + image + ')'; if (!engineSettings.noBackgroundSize) { el.style.backgroundSize = scene.width + 'px ' + scene.height + 'px'; } } else { if (el.nodeName.toLowerCase() === 'img') { DOM.setAttr(el, { 'src': image }); } else if (el.nodeName.toLowerCase() === 'object') { DOM.setAttr(el, { 'data': image, 'type': 'image/svg+xml' }); } if (engineSettings.reRender) { global.setTimeout(function () { var image = getRenderedImage(); if (image == null) { throw 'Holder: couldn\'t render placeholder'; } //todo: refactor this code into a function if (el.nodeName.toLowerCase() === 'img') { DOM.setAttr(el, { 'src': image }); } else if (el.nodeName.toLowerCase() === 'object') { DOM.setAttr(el, { 'data': image, 'type': 'image/svg+xml' }); } }, 150); } } //todo: account for re-rendering DOM.setAttr(el, { 'data-holder-rendered': true }); }
javascript
{ "resource": "" }
q26591
textSize
train
function textSize(width, height, fontSize, scale) { var stageWidth = parseInt(width, 10); var stageHeight = parseInt(height, 10); var bigSide = Math.max(stageWidth, stageHeight); var smallSide = Math.min(stageWidth, stageHeight); var newHeight = 0.8 * Math.min(smallSide, bigSide * scale); return Math.round(Math.max(fontSize, newHeight)); }
javascript
{ "resource": "" }
q26592
setInitialDimensions
train
function setInitialDimensions(el) { if (el.holderData) { var dimensions = dimensionCheck(el); if (dimensions) { var flags = el.holderData.flags; var fluidConfig = { fluidHeight: flags.dimensions.height.slice(-1) == '%', fluidWidth: flags.dimensions.width.slice(-1) == '%', mode: null, initialDimensions: dimensions }; if (fluidConfig.fluidWidth && !fluidConfig.fluidHeight) { fluidConfig.mode = 'width'; fluidConfig.ratio = fluidConfig.initialDimensions.width / parseFloat(flags.dimensions.height); } else if (!fluidConfig.fluidWidth && fluidConfig.fluidHeight) { fluidConfig.mode = 'height'; fluidConfig.ratio = parseFloat(flags.dimensions.width) / fluidConfig.initialDimensions.height; } el.holderData.fluidConfig = fluidConfig; } else { setInvisible(el); } } }
javascript
{ "resource": "" }
q26593
visibilityCheck
train
function visibilityCheck() { var renderableImages = []; var keys = Object.keys(App.vars.invisibleImages); var el; keys.forEach(function (key) { el = App.vars.invisibleImages[key]; if (dimensionCheck(el) && el.nodeName.toLowerCase() == 'img') { renderableImages.push(el); delete App.vars.invisibleImages[key]; } }); if (renderableImages.length) { Holder.run({ images: renderableImages }); } // Done to prevent 100% CPU usage via aggressive calling of requestAnimationFrame setTimeout(function () { global.requestAnimationFrame(visibilityCheck); }, 10); }
javascript
{ "resource": "" }
q26594
startVisibilityCheck
train
function startVisibilityCheck() { if (!App.vars.visibilityCheckStarted) { global.requestAnimationFrame(visibilityCheck); App.vars.visibilityCheckStarted = true; } }
javascript
{ "resource": "" }
q26595
setInvisible
train
function setInvisible(el) { if (!el.holderData.invisibleId) { App.vars.invisibleId += 1; App.vars.invisibleImages['i' + App.vars.invisibleId] = el; el.holderData.invisibleId = App.vars.invisibleId; } }
javascript
{ "resource": "" }
q26596
debounce
train
function debounce(fn) { if (!App.vars.debounceTimer) fn.call(this); if (App.vars.debounceTimer) global.clearTimeout(App.vars.debounceTimer); App.vars.debounceTimer = global.setTimeout(function() { App.vars.debounceTimer = null; fn.call(this); }, App.setup.debounce); }
javascript
{ "resource": "" }
q26597
completed
train
function completed( event ) { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( w3c || event.type === LOAD || doc[READYSTATE] === COMPLETE ) { detach(); ready(); } }
javascript
{ "resource": "" }
q26598
detach
train
function detach() { if ( w3c ) { doc[REMOVEEVENTLISTENER]( DOMCONTENTLOADED, completed, FALSE ); win[REMOVEEVENTLISTENER]( LOAD, completed, FALSE ); } else { doc[DETACHEVENT]( ONREADYSTATECHANGE, completed ); win[DETACHEVENT]( ONLOAD, completed ); } }
javascript
{ "resource": "" }
q26599
usesScopeName
train
function usesScopeName(scopeNames, node) { function usesScope(root) { return usesScopeName(scopeNames, root) } if (_.isEmpty(scopeNames)) { return false } // rt-if="x" if (node.type === 'Identifier') { return _.includes(scopeNames, node.name) } // rt-if="e({key1: value1})" if (node.type === 'Property') { return usesScope(node.value) } // rt-if="e.x" or rt-if="e1[e2]" if (node.type === 'MemberExpression') { return node.computed ? usesScope(node.object) || usesScope(node.property) : usesScope(node.object) } // rt-if="!e" if (node.type === 'UnaryExpression') { return usesScope(node.argument) } // rt-if="e1 || e2" or rt-if="e1 | e2" if (node.type === 'LogicalExpression' || node.type === 'BinaryExpression') { return usesScope(node.left) || usesScope(node.right) } // rt-if="e1(e2, ... eN)" if (node.type === 'CallExpression') { return usesScope(node.callee) || _.some(node.arguments, usesScope) } // rt-if="f({e1: e2})" if (node.type === 'ObjectExpression') { return _.some(node.properties, usesScope) } // rt-if="e1[e2]" if (node.type === 'ArrayExpression') { return _.some(node.elements, usesScope) } return false }
javascript
{ "resource": "" }