_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q25800 | train | function( element ) {
var i;
element = $.getElement( element );
i = getOverlayIndex( this.currentOverlays, element );
if ( i >= 0 ) {
this.currentOverlays[ i ].destroy();
this.currentOverlays.splice( i, 1 );
THIS[ this.hash ].forceRedraw = true;
/**
* Raised when an overlay is removed from the viewer
* (see {@link OpenSeadragon.Viewer#removeOverlay}).
*
* @event remove-overlay
* @memberof OpenSeadragon.Viewer
* @type {object}
* @property {OpenSeadragon.Viewer} eventSource - A reference to the
* Viewer which raised the event.
* @property {Element} element - The overlay element.
* @property {?Object} userData - Arbitrary subscriber-defined object.
*/
this.raiseEvent( 'remove-overlay', {
element: element
});
}
return this;
} | javascript | {
"resource": ""
} | |
q25801 | train | function() {
while ( this.currentOverlays.length > 0 ) {
this.currentOverlays.pop().destroy();
}
THIS[ this.hash ].forceRedraw = true;
/**
* Raised when all overlays are removed from the viewer (see {@link OpenSeadragon.Drawer#clearOverlays}).
*
* @event clear-overlay
* @memberof OpenSeadragon.Viewer
* @type {object}
* @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.
* @property {?Object} userData - Arbitrary subscriber-defined object.
*/
this.raiseEvent( 'clear-overlay', {} );
return this;
} | javascript | {
"resource": ""
} | |
q25802 | train | function( element ) {
var i;
element = $.getElement( element );
i = getOverlayIndex( this.currentOverlays, element );
if (i >= 0) {
return this.currentOverlays[i];
} else {
return null;
}
} | javascript | {
"resource": ""
} | |
q25803 | train | function( page ) {
if ( this.nextButton ) {
if(!this.tileSources || this.tileSources.length - 1 === page) {
//Disable next button
if ( !this.navPrevNextWrap ) {
this.nextButton.disable();
}
} else {
this.nextButton.enable();
}
}
if ( this.previousButton ) {
if ( page > 0 ) {
//Enable previous button
this.previousButton.enable();
} else {
if ( !this.navPrevNextWrap ) {
this.previousButton.disable();
}
}
}
} | javascript | {
"resource": ""
} | |
q25804 | train | function ( message ) {
this._hideMessage();
var div = $.makeNeutralElement( "div" );
div.appendChild( document.createTextNode( message ) );
this.messageDiv = $.makeCenteredNode( div );
$.addClass(this.messageDiv, "openseadragon-message");
this.container.appendChild( this.messageDiv );
} | javascript | {
"resource": ""
} | |
q25805 | train | function() {
this.showReferenceStrip = true;
if (this.sequenceMode) {
if (this.referenceStrip) {
return;
}
if (this.tileSources.length && this.tileSources.length > 1) {
this.referenceStrip = new $.ReferenceStrip({
id: this.referenceStripElement,
position: this.referenceStripPosition,
sizeRatio: this.referenceStripSizeRatio,
scroll: this.referenceStripScroll,
height: this.referenceStripHeight,
width: this.referenceStripWidth,
tileSources: this.tileSources,
prefixUrl: this.prefixUrl,
viewer: this
});
this.referenceStrip.setFocus( this._sequenceIndex );
}
} else {
$.console.warn('Attempting to display a reference strip while "sequenceMode" is off.');
}
} | javascript | {
"resource": ""
} | |
q25806 | beginControlsAutoHide | train | function beginControlsAutoHide( viewer ) {
if ( !viewer.autoHideControls ) {
return;
}
viewer.controlsShouldFade = true;
viewer.controlsFadeBeginTime =
$.now() +
viewer.controlsFadeDelay;
window.setTimeout( function(){
scheduleControlsFade( viewer );
}, viewer.controlsFadeDelay );
} | javascript | {
"resource": ""
} |
q25807 | updateControlsFade | train | function updateControlsFade( viewer ) {
var currentTime,
deltaTime,
opacity,
i;
if ( viewer.controlsShouldFade ) {
currentTime = $.now();
deltaTime = currentTime - viewer.controlsFadeBeginTime;
opacity = 1.0 - deltaTime / viewer.controlsFadeLength;
opacity = Math.min( 1.0, opacity );
opacity = Math.max( 0.0, opacity );
for ( i = viewer.controls.length - 1; i >= 0; i--) {
if (viewer.controls[ i ].autoFade) {
viewer.controls[ i ].setOpacity( opacity );
}
}
if ( opacity > 0 ) {
// fade again
scheduleControlsFade( viewer );
}
}
} | javascript | {
"resource": ""
} |
q25808 | abortControlsAutoHide | train | function abortControlsAutoHide( viewer ) {
var i;
viewer.controlsShouldFade = false;
for ( i = viewer.controls.length - 1; i >= 0; i-- ) {
viewer.controls[ i ].setOpacity( 1.0 );
}
} | javascript | {
"resource": ""
} |
q25809 | train | function () {
var i;
stopTracking( this );
this.element = null;
for ( i = 0; i < MOUSETRACKERS.length; i++ ) {
if ( MOUSETRACKERS[ i ] === this ) {
MOUSETRACKERS.splice( i, 1 );
break;
}
}
THIS[ this.hash ] = null;
delete THIS[ this.hash ];
} | javascript | {
"resource": ""
} | |
q25810 | train | function () {
var delegate = THIS[ this.hash ],
i,
len = delegate.activePointersLists.length,
count = 0;
for ( i = 0; i < len; i++ ) {
count += delegate.activePointersLists[ i ].getLength();
}
return count;
} | javascript | {
"resource": ""
} | |
q25811 | train | function ( tracker, gPoint ) {
return tracker.hash.toString() + gPoint.type + gPoint.id.toString();
} | javascript | {
"resource": ""
} | |
q25812 | train | function () {
var i,
len = trackerPoints.length,
trackPoint,
gPoint,
now = $.now(),
elapsedTime,
distance,
speed;
elapsedTime = now - lastTime;
lastTime = now;
for ( i = 0; i < len; i++ ) {
trackPoint = trackerPoints[ i ];
gPoint = trackPoint.gPoint;
// Math.atan2 gives us just what we need for a velocity vector, as we can simply
// use cos()/sin() to extract the x/y velocity components.
gPoint.direction = Math.atan2( gPoint.currentPos.y - trackPoint.lastPos.y, gPoint.currentPos.x - trackPoint.lastPos.x );
// speed = distance / elapsed time
distance = trackPoint.lastPos.distanceTo( gPoint.currentPos );
trackPoint.lastPos = gPoint.currentPos;
speed = 1000 * distance / ( elapsedTime + 1 );
// Simple biased average, favors the most recent speed computation. Smooths out erratic gestures a bit.
gPoint.speed = 0.75 * speed + 0.25 * gPoint.speed;
}
} | javascript | {
"resource": ""
} | |
q25813 | train | function ( tracker, gPoint ) {
var guid = _generateGuid( tracker, gPoint );
trackerPoints.push(
{
guid: guid,
gPoint: gPoint,
lastPos: gPoint.currentPos
} );
// Only fire up the interval timer when there's gesture pointers to track
if ( trackerPoints.length === 1 ) {
lastTime = $.now();
intervalId = window.setInterval( _doTracking, 50 );
}
} | javascript | {
"resource": ""
} | |
q25814 | train | function ( tracker, gPoint ) {
var guid = _generateGuid( tracker, gPoint ),
i,
len = trackerPoints.length;
for ( i = 0; i < len; i++ ) {
if ( trackerPoints[ i ].guid === guid ) {
trackerPoints.splice( i, 1 );
// Only run the interval timer if theres gesture pointers to track
len--;
if ( len === 0 ) {
window.clearInterval( intervalId );
}
break;
}
}
} | javascript | {
"resource": ""
} | |
q25815 | startTracking | train | function startTracking( tracker ) {
var delegate = THIS[ tracker.hash ],
event,
i;
if ( !delegate.tracking ) {
for ( i = 0; i < $.MouseTracker.subscribeEvents.length; i++ ) {
event = $.MouseTracker.subscribeEvents[ i ];
$.addEvent(
tracker.element,
event,
delegate[ event ],
false
);
}
clearTrackedPointers( tracker );
delegate.tracking = true;
}
} | javascript | {
"resource": ""
} |
q25816 | stopTracking | train | function stopTracking( tracker ) {
var delegate = THIS[ tracker.hash ],
event,
i;
if ( delegate.tracking ) {
for ( i = 0; i < $.MouseTracker.subscribeEvents.length; i++ ) {
event = $.MouseTracker.subscribeEvents[ i ];
$.removeEvent(
tracker.element,
event,
delegate[ event ],
false
);
}
clearTrackedPointers( tracker );
delegate.tracking = false;
}
} | javascript | {
"resource": ""
} |
q25817 | capturePointer | train | function capturePointer( tracker, pointerType, pointerCount ) {
var pointsList = tracker.getActivePointersListByType( pointerType ),
eventParams;
pointsList.captureCount += (pointerCount || 1);
if ( pointsList.captureCount === 1 ) {
if ( $.Browser.vendor === $.BROWSERS.IE && $.Browser.version < 9 ) {
tracker.element.setCapture( true );
} else {
eventParams = getCaptureEventParams( tracker, $.MouseTracker.havePointerEvents ? 'pointerevent' : pointerType );
// We emulate mouse capture by hanging listeners on the document object.
// (Note we listen on the capture phase so the captured handlers will get called first)
// eslint-disable-next-line no-use-before-define
if (isInIframe && canAccessEvents(window.top)) {
$.addEvent(
window.top,
eventParams.upName,
eventParams.upHandler,
true
);
}
$.addEvent(
$.MouseTracker.captureElement,
eventParams.upName,
eventParams.upHandler,
true
);
$.addEvent(
$.MouseTracker.captureElement,
eventParams.moveName,
eventParams.moveHandler,
true
);
}
}
} | javascript | {
"resource": ""
} |
q25818 | onMouseWheel | train | function onMouseWheel( tracker, event ) {
event = $.getEvent( event );
// Simulate a 'wheel' event
var simulatedEvent = {
target: event.target || event.srcElement,
type: "wheel",
shiftKey: event.shiftKey || false,
clientX: event.clientX,
clientY: event.clientY,
pageX: event.pageX ? event.pageX : event.clientX,
pageY: event.pageY ? event.pageY : event.clientY,
deltaMode: event.type == "MozMousePixelScroll" ? 0 : 1, // 0=pixel, 1=line, 2=page
deltaX: 0,
deltaZ: 0
};
// Calculate deltaY
if ( $.MouseTracker.wheelEventName == "mousewheel" ) {
simulatedEvent.deltaY = -event.wheelDelta / $.DEFAULT_SETTINGS.pixelsPerWheelLine;
} else {
simulatedEvent.deltaY = event.detail;
}
handleWheelEvent( tracker, simulatedEvent, event );
} | javascript | {
"resource": ""
} |
q25819 | train | function( container ) {
if (!this.cacheImageRecord) {
$.console.warn(
'[Tile.drawHTML] attempting to draw tile %s when it\'s not cached',
this.toString());
return;
}
if ( !this.loaded ) {
$.console.warn(
"Attempting to draw tile %s when it's not yet loaded.",
this.toString()
);
return;
}
//EXPERIMENTAL - trying to figure out how to scale the container
// content during animation of the container size.
if ( !this.element ) {
this.element = $.makeNeutralElement( "div" );
this.imgElement = this.cacheImageRecord.getImage().cloneNode();
this.imgElement.style.msInterpolationMode = "nearest-neighbor";
this.imgElement.style.width = "100%";
this.imgElement.style.height = "100%";
this.style = this.element.style;
this.style.position = "absolute";
}
if ( this.element.parentNode != container ) {
container.appendChild( this.element );
}
if ( this.imgElement.parentNode != this.element ) {
this.element.appendChild( this.imgElement );
}
this.style.top = this.position.y + "px";
this.style.left = this.position.x + "px";
this.style.height = this.size.y + "px";
this.style.width = this.size.x + "px";
$.setElementOpacity( this.element, this.opacity );
} | javascript | {
"resource": ""
} | |
q25820 | train | function( context, drawingHandler, scale, translate ) {
var position = this.position.times($.pixelDensityRatio),
size = this.size.times($.pixelDensityRatio),
rendered;
if (!this.context2D && !this.cacheImageRecord) {
$.console.warn(
'[Tile.drawCanvas] attempting to draw tile %s when it\'s not cached',
this.toString());
return;
}
rendered = this.context2D || this.cacheImageRecord.getRenderedContext();
if ( !this.loaded || !rendered ){
$.console.warn(
"Attempting to draw tile %s when it's not yet loaded.",
this.toString()
);
return;
}
context.save();
context.globalAlpha = this.opacity;
if (typeof scale === 'number' && scale !== 1) {
// draw tile at a different scale
position = position.times(scale);
size = size.times(scale);
}
if (translate instanceof $.Point) {
// shift tile position slightly
position = position.plus(translate);
}
//if we are supposed to be rendering fully opaque rectangle,
//ie its done fading or fading is turned off, and if we are drawing
//an image with an alpha channel, then the only way
//to avoid seeing the tile underneath is to clear the rectangle
if (context.globalAlpha === 1 && this._hasTransparencyChannel()) {
//clearing only the inside of the rectangle occupied
//by the png prevents edge flikering
context.clearRect(
position.x,
position.y,
size.x,
size.y
);
}
// This gives the application a chance to make image manipulation
// changes as we are rendering the image
drawingHandler({context: context, tile: this, rendered: rendered});
var sourceWidth, sourceHeight;
if (this.sourceBounds) {
sourceWidth = Math.min(this.sourceBounds.width, rendered.canvas.width);
sourceHeight = Math.min(this.sourceBounds.height, rendered.canvas.height);
} else {
sourceWidth = rendered.canvas.width;
sourceHeight = rendered.canvas.height;
}
context.drawImage(
rendered.canvas,
0,
0,
sourceWidth,
sourceHeight,
position.x,
position.y,
size.x,
size.y
);
context.restore();
} | javascript | {
"resource": ""
} | |
q25821 | train | function() {
var context;
if (this.cacheImageRecord) {
context = this.cacheImageRecord.getRenderedContext();
} else if (this.context2D) {
context = this.context2D;
} else {
$.console.warn(
'[Tile.drawCanvas] attempting to get tile scale %s when tile\'s not cached',
this.toString());
return 1;
}
return context.canvas.width / (this.size.x * $.pixelDensityRatio);
} | javascript | {
"resource": ""
} | |
q25822 | train | function(scale, canvasSize, sketchCanvasSize) {
// The translation vector must have positive values, otherwise the image goes a bit off
// the sketch canvas to the top and left and we must use negative coordinates to repaint it
// to the main canvas. In that case, some browsers throw:
// INDEX_SIZE_ERR: DOM Exception 1: Index or size was negative, or greater than the allowed value.
var x = Math.max(1, Math.ceil((sketchCanvasSize.x - canvasSize.x) / 2));
var y = Math.max(1, Math.ceil((sketchCanvasSize.y - canvasSize.y) / 2));
return new $.Point(x, y).minus(
this.position
.times($.pixelDensityRatio)
.times(scale || 1)
.apply(function(x) {
return x % 1;
})
);
} | javascript | {
"resource": ""
} | |
q25823 | train | function() {
if ( this.imgElement && this.imgElement.parentNode ) {
this.imgElement.parentNode.removeChild( this.imgElement );
}
if ( this.element && this.element.parentNode ) {
this.element.parentNode.removeChild( this.element );
}
this.element = null;
this.imgElement = null;
this.loaded = false;
this.loading = false;
} | javascript | {
"resource": ""
} | |
q25824 | train | function( item, options ) {
$.console.assert(item, "[World.addItem] item is required");
$.console.assert(item instanceof $.TiledImage, "[World.addItem] only TiledImages supported at this time");
options = options || {};
if (options.index !== undefined) {
var index = Math.max(0, Math.min(this._items.length, options.index));
this._items.splice(index, 0, item);
} else {
this._items.push( item );
}
if (this._autoRefigureSizes) {
this._figureSizes();
} else {
this._needsSizesFigured = true;
}
this._needsDraw = true;
item.addHandler('bounds-change', this._delegatedFigureSizes);
item.addHandler('clip-change', this._delegatedFigureSizes);
/**
* Raised when an item is added to the World.
* @event add-item
* @memberOf OpenSeadragon.World
* @type {object}
* @property {OpenSeadragon.Viewer} eventSource - A reference to the World which raised the event.
* @property {OpenSeadragon.TiledImage} item - The item that has been added.
* @property {?Object} userData - Arbitrary subscriber-defined object.
*/
this.raiseEvent( 'add-item', {
item: item
} );
} | javascript | {
"resource": ""
} | |
q25825 | train | function( item, index ) {
$.console.assert(item, "[World.setItemIndex] item is required");
$.console.assert(index !== undefined, "[World.setItemIndex] index is required");
var oldIndex = this.getIndexOfItem( item );
if ( index >= this._items.length ) {
throw new Error( "Index bigger than number of layers." );
}
if ( index === oldIndex || oldIndex === -1 ) {
return;
}
this._items.splice( oldIndex, 1 );
this._items.splice( index, 0, item );
this._needsDraw = true;
/**
* Raised when the order of the indexes has been changed.
* @event item-index-change
* @memberOf OpenSeadragon.World
* @type {object}
* @property {OpenSeadragon.World} eventSource - A reference to the World which raised the event.
* @property {OpenSeadragon.TiledImage} item - The item whose index has
* been changed
* @property {Number} previousIndex - The previous index of the item
* @property {Number} newIndex - The new index of the item
* @property {?Object} userData - Arbitrary subscriber-defined object.
*/
this.raiseEvent( 'item-index-change', {
item: item,
previousIndex: oldIndex,
newIndex: index
} );
} | javascript | {
"resource": ""
} | |
q25826 | train | function() {
// We need to make sure any pending images are canceled so the world items don't get messed up
this.viewer._cancelPendingImages();
var item;
var i;
for (i = 0; i < this._items.length; i++) {
item = this._items[i];
item.removeHandler('bounds-change', this._delegatedFigureSizes);
item.removeHandler('clip-change', this._delegatedFigureSizes);
item.destroy();
}
var removedItems = this._items;
this._items = [];
this._figureSizes();
this._needsDraw = true;
for (i = 0; i < removedItems.length; i++) {
item = removedItems[i];
this._raiseRemoveItem(item);
}
} | javascript | {
"resource": ""
} | |
q25827 | train | function() {
for ( var i = 0; i < this._items.length; i++ ) {
this._items[i].draw();
}
this._needsDraw = false;
} | javascript | {
"resource": ""
} | |
q25828 | train | function(options) {
options = options || {};
var immediately = options.immediately || false;
var layout = options.layout || $.DEFAULT_SETTINGS.collectionLayout;
var rows = options.rows || $.DEFAULT_SETTINGS.collectionRows;
var columns = options.columns || $.DEFAULT_SETTINGS.collectionColumns;
var tileSize = options.tileSize || $.DEFAULT_SETTINGS.collectionTileSize;
var tileMargin = options.tileMargin || $.DEFAULT_SETTINGS.collectionTileMargin;
var increment = tileSize + tileMargin;
var wrap;
if (!options.rows && columns) {
wrap = columns;
} else {
wrap = Math.ceil(this._items.length / rows);
}
var x = 0;
var y = 0;
var item, box, width, height, position;
this.setAutoRefigureSizes(false);
for (var i = 0; i < this._items.length; i++) {
if (i && (i % wrap) === 0) {
if (layout === 'horizontal') {
y += increment;
x = 0;
} else {
x += increment;
y = 0;
}
}
item = this._items[i];
box = item.getBounds();
if (box.width > box.height) {
width = tileSize;
} else {
width = tileSize * (box.width / box.height);
}
height = width * (box.height / box.width);
position = new $.Point(x + ((tileSize - width) / 2),
y + ((tileSize - height) / 2));
item.setPosition(position, immediately);
item.setWidth(width, immediately);
if (layout === 'horizontal') {
x += increment;
} else {
y += increment;
}
}
this.setAutoRefigureSizes(true);
} | javascript | {
"resource": ""
} | |
q25829 | train | function(position, size) {
var properties = $.Placement.properties[this.placement];
if (!properties) {
return;
}
if (properties.isHorizontallyCentered) {
position.x -= size.x / 2;
} else if (properties.isRight) {
position.x -= size.x;
}
if (properties.isVerticallyCentered) {
position.y -= size.y / 2;
} else if (properties.isBottom) {
position.y -= size.y;
}
} | javascript | {
"resource": ""
} | |
q25830 | train | function(location, placement) {
var options = $.isPlainObject(location) ? location : {
location: location,
placement: placement
};
this._init({
location: options.location || this.location,
placement: options.placement !== undefined ?
options.placement : this.placement,
onDraw: options.onDraw || this.onDraw,
checkResize: options.checkResize || this.checkResize,
width: options.width !== undefined ? options.width : this.width,
height: options.height !== undefined ? options.height : this.height,
rotationMode: options.rotationMode || this.rotationMode
});
} | javascript | {
"resource": ""
} | |
q25831 | train | function(viewport) {
$.console.assert(viewport,
'A viewport must now be passed to Overlay.getBounds.');
var width = this.width;
var height = this.height;
if (width === null || height === null) {
var size = viewport.deltaPointsFromPixelsNoRotate(this.size, true);
if (width === null) {
width = size.x;
}
if (height === null) {
height = size.y;
}
}
var location = this.location.clone();
this.adjust(location, new $.Point(width, height));
return this._adjustBoundsForRotation(
viewport, new $.Rect(location.x, location.y, width, height));
} | javascript | {
"resource": ""
} | |
q25832 | train | function() {
if (this.miniViewers) {
for (var key in this.miniViewers) {
this.miniViewers[key].destroy();
}
}
if (this.element) {
this.element.parentNode.removeChild(this.element);
}
} | javascript | {
"resource": ""
} | |
q25833 | train | function(contentSize) {
$.console.assert(contentSize, "[Viewport.resetContentSize] contentSize is required");
$.console.assert(contentSize instanceof $.Point, "[Viewport.resetContentSize] contentSize must be an OpenSeadragon.Point");
$.console.assert(contentSize.x > 0, "[Viewport.resetContentSize] contentSize.x must be greater than 0");
$.console.assert(contentSize.y > 0, "[Viewport.resetContentSize] contentSize.y must be greater than 0");
this._setContentBounds(new $.Rect(0, 0, 1, contentSize.y / contentSize.x), contentSize.x);
return this;
} | javascript | {
"resource": ""
} | |
q25834 | train | function(bounds, contentFactor) {
$.console.assert(bounds, "[Viewport._setContentBounds] bounds is required");
$.console.assert(bounds instanceof $.Rect, "[Viewport._setContentBounds] bounds must be an OpenSeadragon.Rect");
$.console.assert(bounds.width > 0, "[Viewport._setContentBounds] bounds.width must be greater than 0");
$.console.assert(bounds.height > 0, "[Viewport._setContentBounds] bounds.height must be greater than 0");
this._contentBoundsNoRotate = bounds.clone();
this._contentSizeNoRotate = this._contentBoundsNoRotate.getSize().times(
contentFactor);
this._contentBounds = bounds.rotate(this.degrees).getBoundingBox();
this._contentSize = this._contentBounds.getSize().times(contentFactor);
this._contentAspectRatio = this._contentSize.x / this._contentSize.y;
if (this.viewer) {
/**
* Raised when the viewer's content size or home bounds are reset
* (see {@link OpenSeadragon.Viewport#resetContentSize}).
*
* @event reset-size
* @memberof OpenSeadragon.Viewer
* @type {object}
* @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.
* @property {OpenSeadragon.Point} contentSize
* @property {OpenSeadragon.Rect} contentBounds - Content bounds.
* @property {OpenSeadragon.Rect} homeBounds - Content bounds.
* Deprecated use contentBounds instead.
* @property {Number} contentFactor
* @property {?Object} userData - Arbitrary subscriber-defined object.
*/
this.viewer.raiseEvent('reset-size', {
contentSize: this._contentSizeNoRotate.clone(),
contentFactor: contentFactor,
homeBounds: this._contentBoundsNoRotate.clone(),
contentBounds: this._contentBounds.clone()
});
}
} | javascript | {
"resource": ""
} | |
q25835 | train | function() {
if (this.defaultZoomLevel) {
return this.defaultZoomLevel;
}
var aspectFactor = this._contentAspectRatio / this.getAspectRatio();
var output;
if (this.homeFillsViewer) { // fill the viewer and clip the image
output = aspectFactor >= 1 ? aspectFactor : 1;
} else {
output = aspectFactor >= 1 ? 1 : aspectFactor;
}
return output / this._contentBounds.width;
} | javascript | {
"resource": ""
} | |
q25836 | train | function(margins) {
$.console.assert($.type(margins) === 'object', '[Viewport.setMargins] margins must be an object');
this._margins = $.extend({
left: 0,
top: 0,
right: 0,
bottom: 0
}, margins);
this._updateContainerInnerSize();
if (this.viewer) {
this.viewer.forceRedraw();
}
} | javascript | {
"resource": ""
} | |
q25837 | train | function(immediately) {
var actualZoom = this.getZoom();
var constrainedZoom = this._applyZoomConstraints(actualZoom);
if (actualZoom !== constrainedZoom) {
this.zoomTo(constrainedZoom, this.zoomPoint, immediately);
}
var bounds = this.getBoundsNoRotate();
var constrainedBounds = this._applyBoundaryConstraints(bounds);
this._raiseConstraintsEvent(immediately);
if (bounds.x !== constrainedBounds.x ||
bounds.y !== constrainedBounds.y ||
immediately) {
this.fitBounds(
constrainedBounds.rotate(-this.getRotation()),
immediately);
}
return this;
} | javascript | {
"resource": ""
} | |
q25838 | train | function(immediately) {
var box = new $.Rect(
this._contentBounds.x,
this._contentBounds.y + (this._contentBounds.height / 2),
this._contentBounds.width,
0);
return this.fitBounds(box, immediately);
} | javascript | {
"resource": ""
} | |
q25839 | train | function(current) {
var bounds,
constrainedBounds;
bounds = this.getBounds(current);
constrainedBounds = this._applyBoundaryConstraints(bounds);
return constrainedBounds;
} | javascript | {
"resource": ""
} | |
q25840 | train | function(zoom, refPoint, immediately) {
var _this = this;
this.zoomPoint = refPoint instanceof $.Point &&
!isNaN(refPoint.x) &&
!isNaN(refPoint.y) ?
refPoint :
null;
if (immediately) {
this._adjustCenterSpringsForZoomPoint(function() {
_this.zoomSpring.resetTo(zoom);
});
} else {
this.zoomSpring.springTo(zoom);
}
if (this.viewer) {
/**
* Raised when the viewport zoom level changes (see {@link OpenSeadragon.Viewport#zoomBy} and {@link OpenSeadragon.Viewport#zoomTo}).
*
* @event zoom
* @memberof OpenSeadragon.Viewer
* @type {object}
* @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.
* @property {Number} zoom
* @property {OpenSeadragon.Point} refPoint
* @property {Boolean} immediately
* @property {?Object} userData - Arbitrary subscriber-defined object.
*/
this.viewer.raiseEvent('zoom', {
zoom: zoom,
refPoint: refPoint,
immediately: immediately
});
}
return this;
} | javascript | {
"resource": ""
} | |
q25841 | train | function(degrees) {
if (!this.viewer || !this.viewer.drawer.canRotate()) {
return this;
}
this.degrees = $.positiveModulo(degrees, 360);
this._setContentBounds(
this.viewer.world.getHomeBounds(),
this.viewer.world.getContentFactor());
this.viewer.forceRedraw();
/**
* Raised when rotation has been changed.
*
* @event rotate
* @memberof OpenSeadragon.Viewer
* @type {object}
* @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.
* @property {Number} degrees - The number of degrees the rotation was set to.
* @property {?Object} userData - Arbitrary subscriber-defined object.
*/
this.viewer.raiseEvent('rotate', {"degrees": degrees});
return this;
} | javascript | {
"resource": ""
} | |
q25842 | train | function(pixel, current) {
var bounds = this.getBoundsNoRotate(current);
return pixel.minus(
new $.Point(this._margins.left, this._margins.top)
).divide(
this._containerInnerSize.x / bounds.width
).plus(
bounds.getTopLeft()
);
} | javascript | {
"resource": ""
} | |
q25843 | train | function(rectangle) {
return $.Rect.fromSummits(
this.pointFromPixel(rectangle.getTopLeft(), true),
this.pointFromPixel(rectangle.getTopRight(), true),
this.pointFromPixel(rectangle.getBottomLeft(), true)
);
} | javascript | {
"resource": ""
} | |
q25844 | train | function(rectangle) {
return $.Rect.fromSummits(
this.pixelFromPoint(rectangle.getTopLeft(), true),
this.pixelFromPoint(rectangle.getTopRight(), true),
this.pixelFromPoint(rectangle.getBottomLeft(), true)
);
} | javascript | {
"resource": ""
} | |
q25845 | train | function(point) {
$.console.assert(this.viewer,
"[Viewport.viewportToWindowCoordinates] the viewport must have a viewer.");
var viewerCoordinates = this.viewportToViewerElementCoordinates(point);
return viewerCoordinates.plus(
$.getElementPosition(this.viewer.element));
} | javascript | {
"resource": ""
} | |
q25846 | train | function( state ) {
if ( this.flipped === state ) {
return this;
}
this.flipped = state;
if(this.viewer.navigator){
this.viewer.navigator.setFlip(this.getFlip());
}
this.viewer.forceRedraw();
/**
* Raised when flip state has been changed.
*
* @event flip
* @memberof OpenSeadragon.Viewer
* @type {object}
* @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.
* @property {Number} flipped - The flip state after this change.
* @property {?Object} userData - Arbitrary subscriber-defined object.
*/
this.viewer.raiseEvent('flip', {"flipped": state});
return this;
} | javascript | {
"resource": ""
} | |
q25847 | train | function (level, x, y) {
var url = null;
if (level >= this.minLevel && level <= this.maxLevel) {
url = this.levels[level].url;
}
return url;
} | javascript | {
"resource": ""
} | |
q25848 | train | function (level, x, y) {
var context = null;
if (level >= this.minLevel && level <= this.maxLevel) {
context = this.levels[level].context2D;
}
return context;
} | javascript | {
"resource": ""
} | |
q25849 | train | function(){
var self = this;
var selfAbort = this.abort;
this.image = new Image();
this.image.onload = function(){
self.finish(true);
};
this.image.onabort = this.image.onerror = function() {
self.errorMsg = "Image load aborted";
self.finish(false);
};
this.jobId = window.setTimeout(function(){
self.errorMsg = "Image load exceeded timeout (" + self.timeout + " ms)";
self.finish(false);
}, this.timeout);
// Load the tile with an AJAX request if the loadWithAjax option is
// set. Otherwise load the image by setting the source proprety of the image object.
if (this.loadWithAjax) {
this.request = $.makeAjaxRequest({
url: this.src,
withCredentials: this.ajaxWithCredentials,
headers: this.ajaxHeaders,
responseType: "arraybuffer",
success: function(request) {
var blb;
// Make the raw data into a blob.
// BlobBuilder fallback adapted from
// http://stackoverflow.com/questions/15293694/blob-constructor-browser-compatibility
try {
blb = new window.Blob([request.response]);
} catch (e) {
var BlobBuilder = (
window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder ||
window.MSBlobBuilder
);
if (e.name === 'TypeError' && BlobBuilder) {
var bb = new BlobBuilder();
bb.append(request.response);
blb = bb.getBlob();
}
}
// If the blob is empty for some reason consider the image load a failure.
if (blb.size === 0) {
self.errorMsg = "Empty image response.";
self.finish(false);
}
// Create a URL for the blob data and make it the source of the image object.
// This will still trigger Image.onload to indicate a successful tile load.
var url = (window.URL || window.webkitURL).createObjectURL(blb);
self.image.src = url;
},
error: function(request) {
self.errorMsg = "Image load aborted - XHR error";
self.finish(false);
}
});
// Provide a function to properly abort the request.
this.abort = function() {
self.request.abort();
// Call the existing abort function if available
if (typeof selfAbort === "function") {
selfAbort();
}
};
} else {
if (this.crossOriginPolicy !== false) {
this.image.crossOrigin = this.crossOriginPolicy;
}
this.image.src = this.src;
}
} | javascript | {
"resource": ""
} | |
q25850 | train | function(options) {
var _this = this,
complete = function(job) {
completeJob(_this, job, options.callback);
},
jobOptions = {
src: options.src,
loadWithAjax: options.loadWithAjax,
ajaxHeaders: options.loadWithAjax ? options.ajaxHeaders : null,
crossOriginPolicy: options.crossOriginPolicy,
ajaxWithCredentials: options.ajaxWithCredentials,
callback: complete,
abort: options.abort,
timeout: this.timeout
},
newJob = new ImageJob(jobOptions);
if ( !this.jobLimit || this.jobsInProgress < this.jobLimit ) {
newJob.start();
this.jobsInProgress++;
}
else {
this.jobQueue.push( newJob );
}
} | javascript | {
"resource": ""
} | |
q25851 | train | function() {
for( var i = 0; i < this.jobQueue.length; i++ ) {
var job = this.jobQueue[i];
if ( typeof job.abort === "function" ) {
job.abort();
}
}
this.jobQueue = [];
} | javascript | {
"resource": ""
} | |
q25852 | completeJob | train | function completeJob(loader, job, callback) {
var nextJob;
loader.jobsInProgress--;
if ((!loader.jobLimit || loader.jobsInProgress < loader.jobLimit) && loader.jobQueue.length > 0) {
nextJob = loader.jobQueue.shift();
nextJob.start();
loader.jobsInProgress++;
}
callback(job.image, job.errorMsg, job.request);
} | javascript | {
"resource": ""
} |
q25853 | train | function( level ) {
if(this.emulateLegacyImagePyramid) {
return $.TileSource.prototype.getTileWidth.call(this, level);
}
var scaleFactor = Math.pow(2, this.maxLevel - level);
if (this.tileSizePerScaleFactor && this.tileSizePerScaleFactor[scaleFactor]) {
return this.tileSizePerScaleFactor[scaleFactor].width;
}
return this._tileWidth;
} | javascript | {
"resource": ""
} | |
q25854 | train | function( level ) {
if(this.emulateLegacyImagePyramid) {
return $.TileSource.prototype.getTileHeight.call(this, level);
}
var scaleFactor = Math.pow(2, this.maxLevel - level);
if (this.tileSizePerScaleFactor && this.tileSizePerScaleFactor[scaleFactor]) {
return this.tileSizePerScaleFactor[scaleFactor].height;
}
return this._tileHeight;
} | javascript | {
"resource": ""
} | |
q25855 | train | function( level, x, y ){
if(this.emulateLegacyImagePyramid) {
var url = null;
if ( this.levels.length > 0 && level >= this.minLevel && level <= this.maxLevel ) {
url = this.levels[ level ].url;
}
return url;
}
//# constants
var IIIF_ROTATION = '0',
//## get the scale (level as a decimal)
scale = Math.pow( 0.5, this.maxLevel - level ),
//# image dimensions at this level
levelWidth = Math.ceil( this.width * scale ),
levelHeight = Math.ceil( this.height * scale ),
//## iiif region
tileWidth,
tileHeight,
iiifTileSizeWidth,
iiifTileSizeHeight,
iiifRegion,
iiifTileX,
iiifTileY,
iiifTileW,
iiifTileH,
iiifSize,
iiifSizeW,
iiifQuality,
uri,
isv1;
tileWidth = this.getTileWidth(level);
tileHeight = this.getTileHeight(level);
iiifTileSizeWidth = Math.ceil( tileWidth / scale );
iiifTileSizeHeight = Math.ceil( tileHeight / scale );
isv1 = ( this['@context'].indexOf('/1.0/context.json') > -1 ||
this['@context'].indexOf('/1.1/context.json') > -1 ||
this['@context'].indexOf('/1/context.json') > -1 );
if (isv1) {
iiifQuality = "native." + this.tileFormat;
} else {
iiifQuality = "default." + this.tileFormat;
}
if ( levelWidth < tileWidth && levelHeight < tileHeight ){
if ( isv1 || levelWidth !== this.width ) {
iiifSize = levelWidth + ",";
} else {
iiifSize = "max";
}
iiifRegion = 'full';
} else {
iiifTileX = x * iiifTileSizeWidth;
iiifTileY = y * iiifTileSizeHeight;
iiifTileW = Math.min( iiifTileSizeWidth, this.width - iiifTileX );
iiifTileH = Math.min( iiifTileSizeHeight, this.height - iiifTileY );
if ( x === 0 && y === 0 && iiifTileW === this.width && iiifTileH === this.height ) {
iiifRegion = "full";
} else {
iiifRegion = [ iiifTileX, iiifTileY, iiifTileW, iiifTileH ].join( ',' );
}
iiifSizeW = Math.ceil( iiifTileW * scale );
if ( (!isv1) && iiifSizeW === this.width ) {
iiifSize = "max";
} else {
iiifSize = iiifSizeW + ",";
}
}
uri = [ this['@id'], iiifRegion, iiifSize, IIIF_ROTATION, iiifQuality ].join( '/' );
return uri;
} | javascript | {
"resource": ""
} | |
q25856 | canBeTiled | train | function canBeTiled ( profile ) {
var level0Profiles = [
"http://library.stanford.edu/iiif/image-api/compliance.html#level0",
"http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level0",
"http://iiif.io/api/image/2/level0.json"
];
var isLevel0 = (level0Profiles.indexOf(profile[0]) !== -1);
var hasSizeByW = false;
if ( profile.length > 1 && profile[1].supports ) {
hasSizeByW = profile[1].supports.indexOf( "sizeByW" ) !== -1;
}
return !isLevel0 || hasSizeByW;
} | javascript | {
"resource": ""
} |
q25857 | train | function ( eventName, handler, userData ) {
var events = this.events[ eventName ];
if ( !events ) {
this.events[ eventName ] = events = [];
}
if ( handler && $.isFunction( handler ) ) {
events[ events.length ] = { handler: handler, userData: userData || null };
}
} | javascript | {
"resource": ""
} | |
q25858 | train | function ( eventName, handler ) {
var events = this.events[ eventName ],
handlers = [],
i;
if ( !events ) {
return;
}
if ( $.isArray( events ) ) {
for ( i = 0; i < events.length; i++ ) {
if ( events[i].handler !== handler ) {
handlers.push( events[ i ] );
}
}
this.events[ eventName ] = handlers;
}
} | javascript | {
"resource": ""
} | |
q25859 | train | function ( eventName ) {
var events = this.events[ eventName ];
if ( !events || !events.length ) {
return null;
}
events = events.length === 1 ?
[ events[ 0 ] ] :
Array.apply( null, events );
return function ( source, args ) {
var i,
length = events.length;
for ( i = 0; i < length; i++ ) {
if ( events[ i ] ) {
args.eventSource = source;
args.userData = events[ i ].userData;
events[ i ].handler( args );
}
}
};
} | javascript | {
"resource": ""
} | |
q25860 | train | function( eventName, eventArgs ) {
//uncomment if you want to get a log of all events
//$.console.log( eventName );
var handler = this.getHandler( eventName );
if ( handler ) {
if ( !eventArgs ) {
eventArgs = {};
}
handler( this, eventArgs );
}
} | javascript | {
"resource": ""
} | |
q25861 | createDocgen | train | async function createDocgen() {
const customPropTypes = await getCustomPropTypes();
const components = await getDocumentableComponents();
const propTypesDatabase = getPropTypeLinks(components);
const docgens = await Promise.all(components.map(c => createComponentsDocgen(c, customPropTypes)));
const database = docgens.reduce((db, { group, docgens }) => {
if (NESTED_GROUPS.indexOf(group) !== -1) {
db[group] = docgens.reduce((entry, docgen) => {
let name = kebabCase(docgen.component);
if (!name.endsWith('ss')) {
name = pluralize(name);
}
if (name.match(/selection-control-group/)) {
entry[name.replace(/-group/, '')].push(docgen);
} else {
entry[name.replace(/-(pickers|progress)/, '')] = [docgen];
}
return entry;
}, {});
} else {
db[group] = docgens;
}
return db;
}, {});
await writeFile(DOCGEN_DATABASE, JSON.stringify(database), 'UTF-8');
console.log(`Wrote docgen database to \`${DOCGEN_DATABASE}\``);
await writeFile(PROP_TYPE_DATABASE, JSON.stringify(propTypesDatabase), 'UTF-8');
console.log(`Wrote docgen database to \`${PROP_TYPE_DATABASE}\``);
} | javascript | {
"resource": ""
} |
q25862 | findLink | train | function findLink(ref) {
if (lastLink.indexOf(ref) !== -1) {
return lastLink;
}
lastLink = '';
routes.some((link) => {
if (link.indexOf(ref) !== -1) {
lastLink = link;
}
return lastLink;
});
return lastLink;
} | javascript | {
"resource": ""
} |
q25863 | githubProxy | train | async function githubProxy(req, res) {
const response = await fetchGithub(req.url, { headers });
setHeader(RATE_LIMIT, res, response);
setHeader(RATE_REMAINING, res, response);
setHeader(RATE_RESET, res, response);
if (response.ok) {
const json = await response.json();
res.json(json);
} else if (response.status === FORBIDDEN) {
const json = await response.json();
res.status(FORBIDDEN).json(json);
} else {
res.status(response.status).send(response.statusText);
}
} | javascript | {
"resource": ""
} |
q25864 | headerQuickLinkReplacer | train | function headerQuickLinkReplacer(fullMatch, openingTag, headerId, remainingHtml, headerText) {
const link = makeLink(headerId, headerText);
return `${openingTag} class="quick-link quick-link__container">${link}${remainingHtml}`;
} | javascript | {
"resource": ""
} |
q25865 | requiredByAllControls | train | function requiredByAllControls(validator) {
return function validate(props, propName, component, ...others) {
let err = validator(props, propName, component, ...others);
if (!err && typeof props[propName] === 'undefined') {
const invalids = props.controls.filter(c => !c[propName]).map((_, i) => i);
if (invalids.length) {
const invalidPrefix = invalids.length === props.controls.length
? 'All `controls`'
: `The \`controls\` at indexes \`${invalids.join('`, `')}\``;
const invalidMsg = `${invalidPrefix} are missing the \`${propName}\` prop.`;
err = new Error(
`The \`${propName}\` prop is required to make \`${component}\` accessible for users of ` +
`assistive technologies such as screen readers. Either add the \`${propName}\` to the \`${component}\` ` +
`or add the \`${propName}\` to each \`control\` in the \`controls\` prop. ${invalidMsg}`
);
}
}
return err;
};
} | javascript | {
"resource": ""
} |
q25866 | getBuildProperty | train | function getBuildProperty(project, property) {
const firstTarget = project.getFirstTarget().firstTarget;
const configurationList = project.pbxXCConfigurationList()[
firstTarget.buildConfigurationList
];
const defaultBuildConfiguration = configurationList.buildConfigurations.reduce(
(acc, config) => {
const buildSection = project.pbxXCBuildConfigurationSection()[
config.value
];
return buildSection.name ===
configurationList.defaultConfigurationName
? buildSection
: acc;
},
configurationList.buildConfigurations[0]
);
return defaultBuildConfiguration.buildSettings[property];
} | javascript | {
"resource": ""
} |
q25867 | getTargetAttributes | train | function getTargetAttributes(project, target) {
var attributes = project.getFirstProject()['firstProject']['attributes'];
target = target || project.getFirstTarget();
if (attributes['TargetAttributes'] === undefined) {
attributes['TargetAttributes'] = {};
}
if (attributes['TargetAttributes'][target.uuid] === undefined) {
attributes['TargetAttributes'][target.uuid] = {};
}
return attributes['TargetAttributes'][target.uuid];
} | javascript | {
"resource": ""
} |
q25868 | dup | train | function dup( text, count ) {
let result = "";
for ( let i = 1; i <= count; i++ ) result += text;
return result;
} | javascript | {
"resource": ""
} |
q25869 | reportUndefinedRules | train | function reportUndefinedRules( ast, session, options ) {
const check = session.buildVisitor( {
rule_ref( node ) {
if ( ! ast.findRule( node.name ) ) {
session.error(
`Rule "${ node.name }" is not defined.`,
node.location
);
}
}
} );
check( ast );
options.allowedStartRules.forEach( rule => {
if ( ! ast.findRule( rule ) ) {
session.error( `Start rule "${ rule }" is not defined.` );
}
} );
} | javascript | {
"resource": ""
} |
q25870 | calcReportFailures | train | function calcReportFailures( ast, session, options ) {
// By default, not report failures for rules...
ast.rules.forEach( rule => {
rule.reportFailures = false;
} );
// ...but report for start rules, because in that context report failures
// always enabled
const changedRules = options.allowedStartRules.map( name => {
const rule = ast.findRule( name );
rule.reportFailures = true;
return rule;
} );
const calc = session.buildVisitor( {
rule( node ) {
calc( node.expression );
},
// Because all rules already by default marked as not report any failures
// just break AST traversing when we need mark all referenced rules from
// this sub-AST as always not report anything (of course if it not be
// already marked as report failures).
named() {},
rule_ref( node ) {
const rule = ast.findRule( node.name );
// This function only called when rule can report failures. If so, we
// need recalculate all rules that referenced from it. But do not do
// this twice - if rule is already marked, it was in `changedRules`.
if ( ! rule.reportFailures ) {
rule.reportFailures = true;
changedRules.push( rule );
}
}
} );
while ( changedRules.length > 0 ) {
calc( changedRules.pop() );
}
} | javascript | {
"resource": ""
} |
q25871 | reportDuplicateLabels | train | function reportDuplicateLabels( ast, session ) {
let check;
function checkExpressionWithClonedEnv( node, env ) {
check( node.expression, util.clone( env ) );
}
check = session.buildVisitor( {
rule( node ) {
check( node.expression, {} );
},
choice( node, env ) {
node.alternatives.forEach( alternative => {
check( alternative, util.clone( env ) );
} );
},
action: checkExpressionWithClonedEnv,
labeled( node, env ) {
const label = node.label;
if ( label && __hasOwnProperty.call( env, label ) ) {
const start = env[ label ].start;
session.error(
`Label "${ label }" is already defined at line ${ start.line }, column ${ start.column }.`,
node.location
);
}
check( node.expression, env );
if ( label ) env[ label ] = node.location;
},
text: checkExpressionWithClonedEnv,
simple_and: checkExpressionWithClonedEnv,
simple_not: checkExpressionWithClonedEnv,
optional: checkExpressionWithClonedEnv,
zero_or_more: checkExpressionWithClonedEnv,
one_or_more: checkExpressionWithClonedEnv,
group: checkExpressionWithClonedEnv
} );
check( ast );
} | javascript | {
"resource": ""
} |
q25872 | evalModule | train | function evalModule( source, context ) {
const argumentKeys = Object.keys( context );
const argumentValues = argumentKeys.map( argument => context[ argument ] );
const sandbox = { exports: {} };
argumentKeys.push( "module", "exports", source );
argumentValues.push( sandbox, sandbox.exports );
Function( ...argumentKeys )( ...argumentValues );
return sandbox.exports;
} | javascript | {
"resource": ""
} |
q25873 | createNode | train | function createNode( type, details ) {
const node = new ast.Node( type, location() );
if ( details === null ) return node;
util.extend( node, details );
return util.enforceFastProperties( node );
} | javascript | {
"resource": ""
} |
q25874 | addComment | train | function addComment( text, multiline ) {
if ( options.extractComments ) {
const loc = location();
comments[ loc.start.offset ] = {
text: text,
multiline: multiline,
location: loc,
};
}
return text;
} | javascript | {
"resource": ""
} |
q25875 | reportDuplicateRules | train | function reportDuplicateRules( ast, session ) {
const rules = {};
const check = session.buildVisitor( {
rule( node ) {
const name = node.name;
if ( __hasOwnProperty.call( rules, name ) ) {
const start = rules[ name ].start;
session.error(
`Rule "${ name }" is already defined at line ${ start.line }, column ${ start.column }.`,
node.location
);
}
rules[ node.name ] = node.location;
}
} );
check( ast );
} | javascript | {
"resource": ""
} |
q25876 | reportUnusedRules | train | function reportUnusedRules( ast, session, options ) {
const used = {};
function yes( node ) {
used[ node.name || node ] = true;
}
options.allowedStartRules.forEach( yes );
session.buildVisitor( { rule_ref: yes } )( ast );
ast.rules.forEach( rule => {
if ( used[ rule.name ] !== true ) {
session.warn(
`Rule "${ rule.name }" is not referenced.`,
rule.location
);
}
} );
} | javascript | {
"resource": ""
} |
q25877 | W3CWebSocket | train | function W3CWebSocket(uri, protocols) {
var native_instance;
if (protocols) {
native_instance = new NativeWebSocket(uri, protocols);
}
else {
native_instance = new NativeWebSocket(uri);
}
/**
* 'native_instance' is an instance of nativeWebSocket (the browser's WebSocket
* class). Since it is an Object it will be returned as it is when creating an
* instance of W3CWebSocket via 'new W3CWebSocket()'.
*
* ECMAScript 5: http://bclary.com/2004/11/07/#a-13.2.2
*/
return native_instance;
} | javascript | {
"resource": ""
} |
q25878 | WebSocketFrame | train | function WebSocketFrame(maskBytes, frameHeader, config) {
this.maskBytes = maskBytes;
this.frameHeader = frameHeader;
this.config = config;
this.maxReceivedFrameSize = config.maxReceivedFrameSize;
this.protocolError = false;
this.frameTooLarge = false;
this.invalidCloseFrameLength = false;
this.parseState = DECODE_HEADER;
this.closeStatus = -1;
} | javascript | {
"resource": ""
} |
q25879 | train | function() {
var EPS = 0.000001;
this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
return this;
} | javascript | {
"resource": ""
} | |
q25880 | extractFromCache | train | function extractFromCache ( cache ) {
var values = [];
for ( var key in cache ) {
var data = cache[ key ];
delete data.metadata;
values.push( data );
}
return values;
} | javascript | {
"resource": ""
} |
q25881 | train | function() {
var actions = this._actions,
nActions = this._nActiveActions,
bindings = this._bindings,
nBindings = this._nActiveBindings;
this._nActiveActions = 0;
this._nActiveBindings = 0;
for ( var i = 0; i !== nActions; ++ i ) {
actions[ i ].reset();
}
for ( var i = 0; i !== nBindings; ++ i ) {
bindings[ i ].useCount = 0;
}
return this;
} | javascript | {
"resource": ""
} | |
q25882 | train | function( clip ) {
var actions = this._actions,
clipUuid = clip.uuid,
actionsByClip = this._actionsByClip,
actionsForClip = actionsByClip[ clipUuid ];
if ( actionsForClip !== undefined ) {
// note: just calling _removeInactiveAction would mess up the
// iteration state and also require updating the state we can
// just throw away
var actionsToRemove = actionsForClip.knownActions;
for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
var action = actionsToRemove[ i ];
this._deactivateAction( action );
var cacheIndex = action._cacheIndex,
lastInactiveAction = actions[ actions.length - 1 ];
action._cacheIndex = null;
action._byClipCacheIndex = null;
lastInactiveAction._cacheIndex = cacheIndex;
actions[ cacheIndex ] = lastInactiveAction;
actions.pop();
this._removeInactiveBindingsForAction( action );
}
delete actionsByClip[ clipUuid ];
}
} | javascript | {
"resource": ""
} | |
q25883 | train | function( root ) {
var rootUuid = root.uuid,
actionsByClip = this._actionsByClip;
for ( var clipUuid in actionsByClip ) {
var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
action = actionByRoot[ rootUuid ];
if ( action !== undefined ) {
this._deactivateAction( action );
this._removeInactiveAction( action );
}
}
var bindingsByRoot = this._bindingsByRootAndName,
bindingByName = bindingsByRoot[ rootUuid ];
if ( bindingByName !== undefined ) {
for ( var trackName in bindingByName ) {
var binding = bindingByName[ trackName ];
binding.restoreOriginalState();
this._removeInactiveBinding( binding );
}
}
} | javascript | {
"resource": ""
} | |
q25884 | train | function( clip, optionalRoot ) {
var action = this.existingAction( clip, optionalRoot );
if ( action !== null ) {
this._deactivateAction( action );
this._removeInactiveAction( action );
}
} | javascript | {
"resource": ""
} | |
q25885 | train | function( binding, rootUuid, trackName ) {
var bindingsByRoot = this._bindingsByRootAndName,
bindingByName = bindingsByRoot[ rootUuid ],
bindings = this._bindings;
if ( bindingByName === undefined ) {
bindingByName = {};
bindingsByRoot[ rootUuid ] = bindingByName;
}
bindingByName[ trackName ] = binding;
binding._cacheIndex = bindings.length;
bindings.push( binding );
} | javascript | {
"resource": ""
} | |
q25886 | train | function() {
var interpolants = this._controlInterpolants,
lastActiveIndex = this._nActiveControlInterpolants ++,
interpolant = interpolants[ lastActiveIndex ];
if ( interpolant === undefined ) {
interpolant = new THREE.LinearInterpolant(
new Float32Array( 2 ), new Float32Array( 2 ),
1, this._controlInterpolantsResultBuffer );
interpolant.__cacheIndex = lastActiveIndex;
interpolants[ lastActiveIndex ] = interpolant;
}
return interpolant;
} | javascript | {
"resource": ""
} | |
q25887 | train | function( var_args ) {
var objects = this._objects,
nObjects = objects.length,
nCachedObjects = this.nCachedObjects_,
indicesByUUID = this._indicesByUUID,
bindings = this._bindings,
nBindings = bindings.length;
for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
var object = arguments[ i ],
uuid = object.uuid,
index = indicesByUUID[ uuid ];
if ( index !== undefined ) {
delete indicesByUUID[ uuid ];
if ( index < nCachedObjects ) {
// object is cached, shrink the CACHED region
var firstActiveIndex = -- nCachedObjects,
lastCachedObject = objects[ firstActiveIndex ],
lastIndex = -- nObjects,
lastObject = objects[ lastIndex ];
// last cached object takes this object's place
indicesByUUID[ lastCachedObject.uuid ] = index;
objects[ index ] = lastCachedObject;
// last object goes to the activated slot and pop
indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
objects[ firstActiveIndex ] = lastObject;
objects.pop();
// accounting is done, now do the same for all bindings
for ( var j = 0, m = nBindings; j !== m; ++ j ) {
var bindingsForPath = bindings[ j ],
lastCached = bindingsForPath[ firstActiveIndex ],
last = bindingsForPath[ lastIndex ];
bindingsForPath[ index ] = lastCached;
bindingsForPath[ firstActiveIndex ] = last;
bindingsForPath.pop();
}
} else {
// object is active, just swap with the last and pop
var lastIndex = -- nObjects,
lastObject = objects[ lastIndex ];
indicesByUUID[ lastObject.uuid ] = index;
objects[ index ] = lastObject;
objects.pop();
// accounting is done, now do the same for all bindings
for ( var j = 0, m = nBindings; j !== m; ++ j ) {
var bindingsForPath = bindings[ j ];
bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
bindingsForPath.pop();
}
} // cached or active
} // if object is known
} // for arguments
this.nCachedObjects_ = nCachedObjects;
} | javascript | {
"resource": ""
} | |
q25888 | train | function( array, type, forceClone ) {
if ( ! array || // let 'undefined' and 'null' pass
! forceClone && array.constructor === type ) return array;
if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
return new type( array ); // create typed array
}
return Array.prototype.slice.call( array ); // create Array
} | javascript | {
"resource": ""
} | |
q25889 | train | function( times ) {
function compareTime( i, j ) {
return times[ i ] - times[ j ];
}
var n = times.length;
var result = new Array( n );
for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
result.sort( compareTime );
return result;
} | javascript | {
"resource": ""
} | |
q25890 | train | function( values, stride, order ) {
var nValues = values.length;
var result = new values.constructor( nValues );
for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
var srcOffset = order[ i ] * stride;
for ( var j = 0; j !== stride; ++ j ) {
result[ dstOffset ++ ] = values[ srcOffset + j ];
}
}
return result;
} | javascript | {
"resource": ""
} | |
q25891 | train | function( jsonKeys, times, values, valuePropertyName ) {
var i = 1, key = jsonKeys[ 0 ];
while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
key = jsonKeys[ i ++ ];
}
if ( key === undefined ) return; // no data
var value = key[ valuePropertyName ];
if ( value === undefined ) return; // no data
if ( Array.isArray( value ) ) {
do {
value = key[ valuePropertyName ];
if ( value !== undefined ) {
times.push( key.time );
values.push.apply( values, value ); // push all elements
}
key = jsonKeys[ i ++ ];
} while ( key !== undefined );
} else if ( value.toArray !== undefined ) {
// ...assume THREE.Math-ish
do {
value = key[ valuePropertyName ];
if ( value !== undefined ) {
times.push( key.time );
value.toArray( values, values.length );
}
key = jsonKeys[ i ++ ];
} while ( key !== undefined );
} else {
// otherwise push as-is
do {
value = key[ valuePropertyName ];
if ( value !== undefined ) {
times.push( key.time );
values.push( value );
}
key = jsonKeys[ i ++ ];
} while ( key !== undefined );
}
} | javascript | {
"resource": ""
} | |
q25892 | train | function( timeOffset ) {
if( timeOffset !== 0.0 ) {
var times = this.times;
for( var i = 0, n = times.length; i !== n; ++ i ) {
times[ i ] += timeOffset;
}
}
return this;
} | javascript | {
"resource": ""
} | |
q25893 | train | function() {
var binding = this.binding;
var buffer = this.buffer,
stride = this.valueSize,
originalValueOffset = stride * 3;
binding.getValue( buffer, originalValueOffset );
// accu[0..1] := orig -- initially detect changes against the original
for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
}
this.cumulativeWeight = 0;
} | javascript | {
"resource": ""
} | |
q25894 | train | function ( focalLength ) {
// see http://www.bobatkins.com/photography/technical/field_of_view.html
var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
this.fov = THREE.Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
this.updateProjectionMatrix();
} | javascript | {
"resource": ""
} | |
q25895 | train | function ( t, p0, p1, p2, p3 ) {
return - 3 * p0 * ( 1 - t ) * ( 1 - t ) +
3 * p1 * ( 1 - t ) * ( 1 - t ) - 6 * t * p1 * ( 1 - t ) +
6 * t * p2 * ( 1 - t ) - 3 * t * t * p2 +
3 * t * t * p3;
} | javascript | {
"resource": ""
} | |
q25896 | train | function ( contour ) {
var n = contour.length;
var a = 0.0;
for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
}
return a * 0.5;
} | javascript | {
"resource": ""
} | |
q25897 | train | function( t ) {
var delta = 0.0001;
var t1 = t - delta;
var t2 = t + delta;
// Capping in case of danger
if ( t1 < 0 ) t1 = 0;
if ( t2 > 1 ) t2 = 1;
var pt1 = this.getPoint( t1 );
var pt2 = this.getPoint( t2 );
var vec = pt2.clone().sub( pt1 );
return vec.normalize();
} | javascript | {
"resource": ""
} | |
q25898 | calculatePositionOnCurve | train | function calculatePositionOnCurve( u, p, q, radius, position ) {
var cu = Math.cos( u );
var su = Math.sin( u );
var quOverP = q / p * u;
var cs = Math.cos( quOverP );
position.x = radius * ( 2 + cs ) * 0.5 * cu;
position.y = radius * ( 2 + cs ) * su * 0.5;
position.z = radius * Math.sin( quOverP ) * 0.5;
} | javascript | {
"resource": ""
} |
q25899 | subdivide | train | function subdivide( face, detail ) {
var cols = Math.pow( 2, detail );
var a = prepare( that.vertices[ face.a ] );
var b = prepare( that.vertices[ face.b ] );
var c = prepare( that.vertices[ face.c ] );
var v = [];
// Construct all of the vertices for this subdivision.
for ( var i = 0 ; i <= cols; i ++ ) {
v[ i ] = [];
var aj = prepare( a.clone().lerp( c, i / cols ) );
var bj = prepare( b.clone().lerp( c, i / cols ) );
var rows = cols - i;
for ( var j = 0; j <= rows; j ++ ) {
if ( j === 0 && i === cols ) {
v[ i ][ j ] = aj;
} else {
v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
}
}
}
// Construct all of the faces.
for ( var i = 0; i < cols ; i ++ ) {
for ( var j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
var k = Math.floor( j / 2 );
if ( j % 2 === 0 ) {
make(
v[ i ][ k + 1 ],
v[ i + 1 ][ k ],
v[ i ][ k ]
);
} else {
make(
v[ i ][ k + 1 ],
v[ i + 1 ][ k + 1 ],
v[ i + 1 ][ k ]
);
}
}
}
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.