<commit_before>/**
 * @author Mat Groves http://matgroves.com/
 */

/**
 * A tiling sprite is a fast way of rendering a tiling image
 *
 * @class TilingSprite
 * @extends Sprite
 * @constructor
 * @param texture {Texture} the texture of the tiling sprite
 * @param width {Number}  the width of the tiling sprite
 * @param height {Number} the height of the tiling sprite
 */
PIXI.TilingSprite = function(texture, width, height)
{
    PIXI.Sprite.call( this, texture);

    /**
     * The with of the tiling sprite
     *
     * @property width
     * @type Number
     */
    this._width = width || 128;

    /**
     * The height of the tiling sprite
     *
     * @property height
     * @type Number
     */
    this._height = height || 128;

    /**
     * The scaling of the image that is being tiled
     *
     * @property tileScale
     * @type Point
     */
    this.tileScale = new PIXI.Point(1, 1);

    /**
     * A point that represents the scale of the texture object
     *
     * @property tileScaleOffset
     * @type Point
     */
    this.tileScaleOffset = new PIXI.Point(1, 1);

    /**
     * The offset position of the image that is being tiled
     *
     * @property tilePosition
     * @type Point
     */
    this.tilePosition = new PIXI.Point();

    /**
     * Whether this sprite is renderable or not
     *
     * @property renderable
     * @type Boolean
     * @default true
     */
    this.renderable = true;

    /**
     * The tint applied to the sprite. This is a hex value
     *
     * @property tint
     * @type Number
     * @default 0xFFFFFF
     */
    this.tint = 0xFFFFFF;

    /**
     * The blend mode to be applied to the sprite
     *
     * @property blendMode
     * @type Number
     * @default PIXI.blendModes.NORMAL;
     */
    this.blendMode = PIXI.blendModes.NORMAL;

    /**
     * The CanvasBuffer object that the tiled texture is drawn to.
     *
     * @property canvasBuffer
     * @type PIXI.CanvasBuffer
     */
    this.canvasBuffer = null;

    /**
     * An internal Texture object that holds the tiling texture that was generated from TilingSprite.texture.
     *
     * @property tilingTexture
     * @type PIXI.Texture
     */
    this.tilingTexture = null;

    /**
     * The Context fill pattern that is used to draw the TilingSprite in Canvas mode only (will be null in WebGL).
     *
     * @property tilePattern
     * @type PIXI.Texture
     */
    this.tilePattern = null;

    /**
     * If true the TilingSprite will run generateTexture on its **next** render pass.
     * This is set by the likes of Phaser.LoadTexture.setFrame.
     *
     * @property refreshTexture
     * @type Boolean
     * @default true
     */
    this.refreshTexture = true;

    this.frameWidth = 0;
    this.frameHeight = 0;

};

PIXI.TilingSprite.prototype = Object.create(PIXI.Sprite.prototype);
PIXI.TilingSprite.prototype.constructor = PIXI.TilingSprite;

PIXI.TilingSprite.prototype.setTexture = function(texture)
{
    if (this.texture !== texture)
    {
        this.texture = texture;
        this.refreshTexture = true;
        this.cachedTint = 0xFFFFFF;
    }

};

/**
* Renders the object using the WebGL renderer
*
* @method _renderWebGL
* @param renderSession {RenderSession}
* @private
*/
PIXI.TilingSprite.prototype._renderWebGL = function(renderSession)
{
    if (this.visible === false || this.alpha === 0)
    {
        return;
    }

    if (this._mask)
    {
        renderSession.spriteBatch.stop();
        renderSession.maskManager.pushMask(this.mask, renderSession);
        renderSession.spriteBatch.start();
    }

    if (this._filters)
    {
        renderSession.spriteBatch.flush();
        renderSession.filterManager.pushFilter(this._filterBlock);
    }

    if (this.refreshTexture)
    {
        this.generateTilingTexture(true);

        if (this.tilingTexture)
        {
            if (this.tilingTexture.needsUpdate)
            {
                renderSession.renderer.updateTexture(this.tilingTexture.baseTexture);
                this.tilingTexture.needsUpdate = false;
            }
        }
        else
        {
            return;
        }
    }

    renderSession.spriteBatch.renderTilingSprite(this);

    for (var i = 0; i < this.children.length; i++)
    {
        this.children[i]._renderWebGL(renderSession);
    }

    renderSession.spriteBatch.stop();

    if (this._filters)
    {
        renderSession.filterManager.popFilter();
    }

    if (this._mask)
    {
        renderSession.maskManager.popMask(this._mask, renderSession);
    }

    renderSession.spriteBatch.start();

};

/**
* Renders the object using the Canvas renderer
*
* @method _renderCanvas
* @param renderSession {RenderSession}
* @private
*/
PIXI.TilingSprite.prototype._renderCanvas = function(renderSession)
{
    if (this.visible === false || this.alpha === 0)
    {
        return;
    }

    var context = renderSession.context;

    if (this._mask)
    {
        renderSession.maskManager.pushMask(this._mask, renderSession);
    }

    context.globalAlpha = this.worldAlpha;

    var wt = this.worldTransform;
    var resolution = renderSession.resolution;

    context.setTransform(wt.a * resolution,
                         wt.b * resolution,
                         wt.c * resolution,
                         wt.d * resolution,
                         wt.tx * resolution,
                         wt.ty * resolution);

    if (this.refreshTexture)
    {
        this.generateTilingTexture(false);

        if (this.tilingTexture)
        {
            this.tilePattern = context.createPattern(this.tilingTexture.baseTexture.source, 'repeat');
        }
        else
        {
            return;
        }
    }

    var sessionBlendMode = renderSession.currentBlendMode;

    //  Check blend mode
    if (this.blendMode !== renderSession.currentBlendMode)
    {
        renderSession.currentBlendMode = this.blendMode;
        context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode];
    }

    var tilePosition = this.tilePosition;
    var tileScale = this.tileScale;

    tilePosition.x %= this.tilingTexture.baseTexture.width;
    tilePosition.y %= this.tilingTexture.baseTexture.height;

    //  Translate
    context.scale(tileScale.x, tileScale.y);
    context.translate(tilePosition.x + (this.anchor.x * -this._width), tilePosition.y + (this.anchor.y * -this._height));

    context.fillStyle = this.tilePattern;

    var tx = -tilePosition.x;
    var ty = -tilePosition.y;
    var tw = this._width / tileScale.x;
    var th = this._height / tileScale.y;

    //  Allow for pixel rounding
    if (renderSession.roundPixels)
    {
        tx | 0;
        ty | 0;
        tw | 0;
        th | 0;
    }

    context.fillRect(tx, ty, tw, th);

    //  Translate back again
    context.scale(1 / tileScale.x, 1 / tileScale.y);
    context.translate(-tilePosition.x + (this.anchor.x * this._width), -tilePosition.y + (this.anchor.y * this._height));

    if (this._mask)
    {
        renderSession.maskManager.popMask(renderSession);
    }

    for (var i = 0; i < this.children.length; i++)
    {
        this.children[i]._renderCanvas(renderSession);
    }

    //  Reset blend mode
    if (sessionBlendMode !== this.blendMode)
    {
        renderSession.currentBlendMode = sessionBlendMode;
        context.globalCompositeOperation = PIXI.blendModesCanvas[sessionBlendMode];
    }

};

/**
 * When the texture is updated, this event will fire to update the scale and frame
 *
 * @method onTextureUpdate
 * @param event
 * @private
 */
PIXI.TilingSprite.prototype.onTextureUpdate = function()
{
   // overriding the sprite version of this!
};

/**
*
* @method generateTilingTexture
*
* @param forcePowerOfTwo {Boolean} Whether we want to force the texture to be a power of two
*/
PIXI.TilingSprite.prototype.generateTilingTexture = function(forcePowerOfTwo)
{
    if (!this.texture.baseTexture.hasLoaded)
    {
        return;
    }

    var texture = this.texture;
    var frame = texture.frame;

    var targetWidth = this._frame.sourceSizeW;
    var targetHeight = this._frame.sourceSizeH;

    var dx = 0;
    var dy = 0;

    if (this._frame.trimmed)
    {
        dx = this._frame.spriteSourceSizeX;
        dy = this._frame.spriteSourceSizeY;
    }

    if (forcePowerOfTwo)
    {
        targetWidth = PIXI.getNextPowerOfTwo(targetWidth);
        targetHeight = PIXI.getNextPowerOfTwo(targetHeight);
    }

    if (this.canvasBuffer)
    {
        this.canvasBuffer.resize(targetWidth, targetHeight);
        this.tilingTexture.baseTexture.width = targetWidth;
        this.tilingTexture.baseTexture.height = targetHeight;
        this.tilingTexture.needsUpdate = true;
    }
    else
    {
        this.canvasBuffer = new PIXI.CanvasBuffer(targetWidth, targetHeight);
        this.tilingTexture = PIXI.Texture.fromCanvas(this.canvasBuffer.canvas);
        this.tilingTexture.isTiling = true;
        this.tilingTexture.needsUpdate = true;
    }

    //  Debug
    this.canvasBuffer.context.strokeStyle = 'rgb(0,255,0)';
    this.canvasBuffer.context.strokeRect(0, 0, targetWidth, targetHeight);

    this.canvasBuffer.context.drawImage(texture.baseTexture.source,
                           texture.crop.x,
                           texture.crop.y,
                           texture.crop.width,
                           texture.crop.height,
                           dx,
                           dy,
                           texture.crop.width,
                           texture.crop.height);

    this.tileScaleOffset.x = frame.width / targetWidth;
    this.tileScaleOffset.y = frame.height / targetHeight;

    this.refreshTexture = false;

    this.tilingTexture.baseTexture._powerOf2 = true;

};

/**
* Returns the framing rectangle of the sprite as a PIXI.Rectangle object
*
* @method getBounds
* @return {Rectangle} the framing rectangle
*/
PIXI.TilingSprite.prototype.getBounds = function()
{
    var width = this._width;
    var height = this._height;

    var w0 = width * (1-this.anchor.x);
    var w1 = width * -this.anchor.x;

    var h0 = height * (1-this.anchor.y);
    var h1 = height * -this.anchor.y;

    var worldTransform = this.worldTransform;

    var a = worldTransform.a;
    var b = worldTransform.b;
    var c = worldTransform.c;
    var d = worldTransform.d;
    var tx = worldTransform.tx;
    var ty = worldTransform.ty;

    var x1 = a * w1 + c * h1 + tx;
    var y1 = d * h1 + b * w1 + ty;

    var x2 = a * w0 + c * h1 + tx;
    var y2 = d * h1 + b * w0 + ty;

    var x3 = a * w0 + c * h0 + tx;
    var y3 = d * h0 + b * w0 + ty;

    var x4 =  a * w1 + c * h0 + tx;
    var y4 =  d * h0 + b * w1 + ty;

    var maxX = -Infinity;
    var maxY = -Infinity;

    var minX = Infinity;
    var minY = Infinity;

    minX = x1 < minX ? x1 : minX;
    minX = x2 < minX ? x2 : minX;
    minX = x3 < minX ? x3 : minX;
    minX = x4 < minX ? x4 : minX;

    minY = y1 < minY ? y1 : minY;
    minY = y2 < minY ? y2 : minY;
    minY = y3 < minY ? y3 : minY;
    minY = y4 < minY ? y4 : minY;

    maxX = x1 > maxX ? x1 : maxX;
    maxX = x2 > maxX ? x2 : maxX;
    maxX = x3 > maxX ? x3 : maxX;
    maxX = x4 > maxX ? x4 : maxX;

    maxY = y1 > maxY ? y1 : maxY;
    maxY = y2 > maxY ? y2 : maxY;
    maxY = y3 > maxY ? y3 : maxY;
    maxY = y4 > maxY ? y4 : maxY;

    var bounds = this._bounds;

    bounds.x = minX;
    bounds.width = maxX - minX;

    bounds.y = minY;
    bounds.height = maxY - minY;

    // store a reference so that if this function gets called again in the render cycle we do not have to recalculate
    this._currentBounds = bounds;

    return bounds;
};

PIXI.TilingSprite.prototype.destroy = function () {

    PIXI.Sprite.prototype.destroy.call(this);

    this.tileScale = null;
    this.tileScaleOffset = null;
    this.tilePosition = null;

    if (this.tilingTexture)
    {
        this.tilingTexture.destroy(true);
        this.tilingTexture = null;
    }

};

/**
 * The width of the sprite, setting this will actually modify the scale to achieve the value set
 *
 * @property width
 * @type Number
 */
Object.defineProperty(PIXI.TilingSprite.prototype, 'width', {

    get: function() {
        return this._width;
    },

    set: function(value) {
        this._width = value;
    }

});

/**
 * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set
 *
 * @property height
 * @type Number
 */
Object.defineProperty(PIXI.TilingSprite.prototype, 'height', {

    get: function() {
        return  this._height;
    },

    set: function(value) {
        this._height = value;
    }

});
<commit_msg>Added textureDebug boolean - allows you to visually debug the generated texture a TilingSprite creates.<commit_after>/**
 * @author Mat Groves http://matgroves.com/
 */

/**
 * A tiling sprite is a fast way of rendering a tiling image
 *
 * @class TilingSprite
 * @extends Sprite
 * @constructor
 * @param texture {Texture} the texture of the tiling sprite
 * @param width {Number}  the width of the tiling sprite
 * @param height {Number} the height of the tiling sprite
 */
PIXI.TilingSprite = function(texture, width, height)
{
    PIXI.Sprite.call( this, texture);

    /**
     * The with of the tiling sprite
     *
     * @property width
     * @type Number
     */
    this._width = width || 128;

    /**
     * The height of the tiling sprite
     *
     * @property height
     * @type Number
     */
    this._height = height || 128;

    /**
     * The scaling of the image that is being tiled
     *
     * @property tileScale
     * @type Point
     */
    this.tileScale = new PIXI.Point(1, 1);

    /**
     * A point that represents the scale of the texture object
     *
     * @property tileScaleOffset
     * @type Point
     */
    this.tileScaleOffset = new PIXI.Point(1, 1);

    /**
     * The offset position of the image that is being tiled
     *
     * @property tilePosition
     * @type Point
     */
    this.tilePosition = new PIXI.Point();

    /**
     * Whether this sprite is renderable or not
     *
     * @property renderable
     * @type Boolean
     * @default true
     */
    this.renderable = true;

    /**
     * The tint applied to the sprite. This is a hex value
     *
     * @property tint
     * @type Number
     * @default 0xFFFFFF
     */
    this.tint = 0xFFFFFF;

    /**
     * If enabled a green rectangle will be drawn behind the generated tiling texture, allowing you to visually
     * debug the texture being used.
     *
     * @property textureDebug
     * @type Boolean
     */
    this.textureDebug = false;

    /**
     * The blend mode to be applied to the sprite
     *
     * @property blendMode
     * @type Number
     * @default PIXI.blendModes.NORMAL;
     */
    this.blendMode = PIXI.blendModes.NORMAL;

    /**
     * The CanvasBuffer object that the tiled texture is drawn to.
     *
     * @property canvasBuffer
     * @type PIXI.CanvasBuffer
     */
    this.canvasBuffer = null;

    /**
     * An internal Texture object that holds the tiling texture that was generated from TilingSprite.texture.
     *
     * @property tilingTexture
     * @type PIXI.Texture
     */
    this.tilingTexture = null;

    /**
     * The Context fill pattern that is used to draw the TilingSprite in Canvas mode only (will be null in WebGL).
     *
     * @property tilePattern
     * @type PIXI.Texture
     */
    this.tilePattern = null;

    /**
     * If true the TilingSprite will run generateTexture on its **next** render pass.
     * This is set by the likes of Phaser.LoadTexture.setFrame.
     *
     * @property refreshTexture
     * @type Boolean
     * @default true
     */
    this.refreshTexture = true;

    this.frameWidth = 0;
    this.frameHeight = 0;

};

PIXI.TilingSprite.prototype = Object.create(PIXI.Sprite.prototype);
PIXI.TilingSprite.prototype.constructor = PIXI.TilingSprite;

PIXI.TilingSprite.prototype.setTexture = function(texture)
{
    if (this.texture !== texture)
    {
        this.texture = texture;
        this.refreshTexture = true;
        this.cachedTint = 0xFFFFFF;
    }

};

/**
* Renders the object using the WebGL renderer
*
* @method _renderWebGL
* @param renderSession {RenderSession}
* @private
*/
PIXI.TilingSprite.prototype._renderWebGL = function(renderSession)
{
    if (this.visible === false || this.alpha === 0)
    {
        return;
    }

    if (this._mask)
    {
        renderSession.spriteBatch.stop();
        renderSession.maskManager.pushMask(this.mask, renderSession);
        renderSession.spriteBatch.start();
    }

    if (this._filters)
    {
        renderSession.spriteBatch.flush();
        renderSession.filterManager.pushFilter(this._filterBlock);
    }

    if (this.refreshTexture)
    {
        this.generateTilingTexture(true);

        if (this.tilingTexture)
        {
            if (this.tilingTexture.needsUpdate)
            {
                renderSession.renderer.updateTexture(this.tilingTexture.baseTexture);
                this.tilingTexture.needsUpdate = false;
            }
        }
        else
        {
            return;
        }
    }

    renderSession.spriteBatch.renderTilingSprite(this);

    for (var i = 0; i < this.children.length; i++)
    {
        this.children[i]._renderWebGL(renderSession);
    }

    renderSession.spriteBatch.stop();

    if (this._filters)
    {
        renderSession.filterManager.popFilter();
    }

    if (this._mask)
    {
        renderSession.maskManager.popMask(this._mask, renderSession);
    }

    renderSession.spriteBatch.start();

};

/**
* Renders the object using the Canvas renderer
*
* @method _renderCanvas
* @param renderSession {RenderSession}
* @private
*/
PIXI.TilingSprite.prototype._renderCanvas = function(renderSession)
{
    if (this.visible === false || this.alpha === 0)
    {
        return;
    }

    var context = renderSession.context;

    if (this._mask)
    {
        renderSession.maskManager.pushMask(this._mask, renderSession);
    }

    context.globalAlpha = this.worldAlpha;

    var wt = this.worldTransform;
    var resolution = renderSession.resolution;

    context.setTransform(wt.a * resolution,
                         wt.b * resolution,
                         wt.c * resolution,
                         wt.d * resolution,
                         wt.tx * resolution,
                         wt.ty * resolution);

    if (this.refreshTexture)
    {
        this.generateTilingTexture(false);

        if (this.tilingTexture)
        {
            this.tilePattern = context.createPattern(this.tilingTexture.baseTexture.source, 'repeat');
        }
        else
        {
            return;
        }
    }

    var sessionBlendMode = renderSession.currentBlendMode;

    //  Check blend mode
    if (this.blendMode !== renderSession.currentBlendMode)
    {
        renderSession.currentBlendMode = this.blendMode;
        context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode];
    }

    var tilePosition = this.tilePosition;
    var tileScale = this.tileScale;

    tilePosition.x %= this.tilingTexture.baseTexture.width;
    tilePosition.y %= this.tilingTexture.baseTexture.height;

    //  Translate
    context.scale(tileScale.x, tileScale.y);
    context.translate(tilePosition.x + (this.anchor.x * -this._width), tilePosition.y + (this.anchor.y * -this._height));

    context.fillStyle = this.tilePattern;

    var tx = -tilePosition.x;
    var ty = -tilePosition.y;
    var tw = this._width / tileScale.x;
    var th = this._height / tileScale.y;

    //  Allow for pixel rounding
    if (renderSession.roundPixels)
    {
        tx | 0;
        ty | 0;
        tw | 0;
        th | 0;
    }

    context.fillRect(tx, ty, tw, th);

    //  Translate back again
    context.scale(1 / tileScale.x, 1 / tileScale.y);
    context.translate(-tilePosition.x + (this.anchor.x * this._width), -tilePosition.y + (this.anchor.y * this._height));

    if (this._mask)
    {
        renderSession.maskManager.popMask(renderSession);
    }

    for (var i = 0; i < this.children.length; i++)
    {
        this.children[i]._renderCanvas(renderSession);
    }

    //  Reset blend mode
    if (sessionBlendMode !== this.blendMode)
    {
        renderSession.currentBlendMode = sessionBlendMode;
        context.globalCompositeOperation = PIXI.blendModesCanvas[sessionBlendMode];
    }

};

/**
 * When the texture is updated, this event will fire to update the scale and frame
 *
 * @method onTextureUpdate
 * @param event
 * @private
 */
PIXI.TilingSprite.prototype.onTextureUpdate = function()
{
   // overriding the sprite version of this!
};

/**
*
* @method generateTilingTexture
*
* @param forcePowerOfTwo {Boolean} Whether we want to force the texture to be a power of two
*/
PIXI.TilingSprite.prototype.generateTilingTexture = function(forcePowerOfTwo)
{
    if (!this.texture.baseTexture.hasLoaded)
    {
        return;
    }

    var texture = this.texture;
    var frame = texture.frame;

    var targetWidth = this._frame.sourceSizeW;
    var targetHeight = this._frame.sourceSizeH;

    var dx = 0;
    var dy = 0;

    if (this._frame.trimmed)
    {
        dx = this._frame.spriteSourceSizeX;
        dy = this._frame.spriteSourceSizeY;
    }

    if (forcePowerOfTwo)
    {
        targetWidth = PIXI.getNextPowerOfTwo(targetWidth);
        targetHeight = PIXI.getNextPowerOfTwo(targetHeight);
    }

    if (this.canvasBuffer)
    {
        this.canvasBuffer.resize(targetWidth, targetHeight);
        this.tilingTexture.baseTexture.width = targetWidth;
        this.tilingTexture.baseTexture.height = targetHeight;
        this.tilingTexture.needsUpdate = true;
    }
    else
    {
        this.canvasBuffer = new PIXI.CanvasBuffer(targetWidth, targetHeight);
        this.tilingTexture = PIXI.Texture.fromCanvas(this.canvasBuffer.canvas);
        this.tilingTexture.isTiling = true;
        this.tilingTexture.needsUpdate = true;
    }

    if (this.textureDebug)
    {
        this.canvasBuffer.context.strokeStyle = '#00ff00';
        this.canvasBuffer.context.strokeRect(0, 0, targetWidth, targetHeight);
    }

    this.canvasBuffer.context.drawImage(texture.baseTexture.source,
                           texture.crop.x,
                           texture.crop.y,
                           texture.crop.width,
                           texture.crop.height,
                           dx,
                           dy,
                           texture.crop.width,
                           texture.crop.height);

    this.tileScaleOffset.x = frame.width / targetWidth;
    this.tileScaleOffset.y = frame.height / targetHeight;

    this.refreshTexture = false;

    this.tilingTexture.baseTexture._powerOf2 = true;

};

/**
* Returns the framing rectangle of the sprite as a PIXI.Rectangle object
*
* @method getBounds
* @return {Rectangle} the framing rectangle
*/
PIXI.TilingSprite.prototype.getBounds = function()
{
    var width = this._width;
    var height = this._height;

    var w0 = width * (1-this.anchor.x);
    var w1 = width * -this.anchor.x;

    var h0 = height * (1-this.anchor.y);
    var h1 = height * -this.anchor.y;

    var worldTransform = this.worldTransform;

    var a = worldTransform.a;
    var b = worldTransform.b;
    var c = worldTransform.c;
    var d = worldTransform.d;
    var tx = worldTransform.tx;
    var ty = worldTransform.ty;

    var x1 = a * w1 + c * h1 + tx;
    var y1 = d * h1 + b * w1 + ty;

    var x2 = a * w0 + c * h1 + tx;
    var y2 = d * h1 + b * w0 + ty;

    var x3 = a * w0 + c * h0 + tx;
    var y3 = d * h0 + b * w0 + ty;

    var x4 =  a * w1 + c * h0 + tx;
    var y4 =  d * h0 + b * w1 + ty;

    var maxX = -Infinity;
    var maxY = -Infinity;

    var minX = Infinity;
    var minY = Infinity;

    minX = x1 < minX ? x1 : minX;
    minX = x2 < minX ? x2 : minX;
    minX = x3 < minX ? x3 : minX;
    minX = x4 < minX ? x4 : minX;

    minY = y1 < minY ? y1 : minY;
    minY = y2 < minY ? y2 : minY;
    minY = y3 < minY ? y3 : minY;
    minY = y4 < minY ? y4 : minY;

    maxX = x1 > maxX ? x1 : maxX;
    maxX = x2 > maxX ? x2 : maxX;
    maxX = x3 > maxX ? x3 : maxX;
    maxX = x4 > maxX ? x4 : maxX;

    maxY = y1 > maxY ? y1 : maxY;
    maxY = y2 > maxY ? y2 : maxY;
    maxY = y3 > maxY ? y3 : maxY;
    maxY = y4 > maxY ? y4 : maxY;

    var bounds = this._bounds;

    bounds.x = minX;
    bounds.width = maxX - minX;

    bounds.y = minY;
    bounds.height = maxY - minY;

    // store a reference so that if this function gets called again in the render cycle we do not have to recalculate
    this._currentBounds = bounds;

    return bounds;
};

PIXI.TilingSprite.prototype.destroy = function () {

    PIXI.Sprite.prototype.destroy.call(this);

    this.tileScale = null;
    this.tileScaleOffset = null;
    this.tilePosition = null;

    if (this.tilingTexture)
    {
        this.tilingTexture.destroy(true);
        this.tilingTexture = null;
    }

};

/**
 * The width of the sprite, setting this will actually modify the scale to achieve the value set
 *
 * @property width
 * @type Number
 */
Object.defineProperty(PIXI.TilingSprite.prototype, 'width', {

    get: function() {
        return this._width;
    },

    set: function(value) {
        this._width = value;
    }

});

/**
 * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set
 *
 * @property height
 * @type Number
 */
Object.defineProperty(PIXI.TilingSprite.prototype, 'height', {

    get: function() {
        return  this._height;
    },

    set: function(value) {
        this._height = value;
    }

});
<|endoftext|>


<commit_before>(function() {
  var load;

  load = function() {
    var el;
    el = document.querySelector(INSTALL_OPTIONS.location.selector);
    if (!el) {
      return;
    }
    el.innerHTML = Typist.renderVariants(el.textContent, INSTALL_OPTIONS.variants);
    return new Typist(el, {
      letterInterval: 60,
      textInterval: 3000
    });
  };

  this.TypistInstallHelper = {
    init: function() {
      if (document.readyState === 'LOADING') {
        return window.addEventListener('DOMContentInteractive', load);
      } else {
        return load();
      }
    }
  };

}).call(this);
<commit_msg>Rebuild<commit_after>(function() {
  var load;

  load = function() {
    var el;
    el = document.querySelector(INSTALL_OPTIONS.location);
    if (!el) {
      return;
    }
    el.innerHTML = Typist.renderVariants(el.textContent, INSTALL_OPTIONS.variants);
    return new Typist(el.querySelector('.typist-element'), {
      letterInterval: 60,
      textInterval: 3000
    });
  };

  this.TypistInstallHelper = {
    init: function() {
      if (document.readyState === 'LOADING') {
        return window.addEventListener('DOMContentInteractive', load);
      } else {
        return load();
      }
    }
  };

}).call(this);
<|endoftext|>


<commit_before>
aleph.controller('EntitiesReviewCtrl', ['$scope', '$route', '$location', '$http', '$timeout', 'Collection', 'Entity', 'Metadata', 'Authz', 'Title',
    function($scope, $route, $location, $http, $timeout, Collection, Entity, Metadata, Authz, Title) {

  $scope.reportLoading(true);
  $scope.entity = null;
  $scope.empty = false;
  $scope.schemata = {};
  $scope.duplicateOptions = [];
  Title.set("Review entities", "entities");

  var entityCache = [],
      entitySkipIds = [],
      entityCacheDfd = null;

  var loadCachedEntity = function() {
    Metadata.get().then(function(metadata) {
      $scope.schemata = metadata.schemata;
      $scope.entity = entityCache.splice(0, 1)[0];
      Title.set("Review: " + $scope.entity.name, "entities");
      $scope.entity.jurisdiction_code = $scope.entity.jurisdiction_code || null;
      $scope.reportLoading(false);
      $http.get('/api/1/entities/' + $scope.entity.id + '/similar').then(function(res) {
        $scope.duplicateOptions = res.data.results;
        $scope.reportLoading(false);
      });
    });
  };

  var loadNext = function() {
    // console.log("Cache size:", entityCache.length);

    if ($scope.entity == null) {
      if (entityCache.length) {
        loadCachedEntity();
      } else if ($scope.empty) {
        $scope.reportLoading(false);
      }
    }

    $timeout(function() {
      if (!entityCacheDfd && !$scope.empty && entityCache.length < 22) {
        var params = {params: {skip: entitySkipIds.slice(entitySkipIds.length - 50)}}
        entityCacheDfd = $http.get('/api/1/entities/_pending', params);
        entityCacheDfd.then(function(res) {
          for (var i in res.data.results) {
            var ent = res.data.results[i];
            entitySkipIds.push(ent.id);
            entityCache.push(ent);
          }
          if (res.data.total == 0) {
            $scope.empty = true;
          }
          entityCacheDfd = null;
          loadNext();
        });
      }
    });
  };

  var triggerDone = function() {
    $scope.reportLoading(true);
    $scope.entity = null;
    loadNext();
  };

  $scope.activate = function() {
    if (!$scope.entity.id) {
      return;
    }
    var entity = angular.copy($scope.entity);
    entity.state = 'active';
    $http.post('/api/1/entities/' + entity.id, entity);
    triggerDone();
  };

  $scope.delete = function() {
    if (!$scope.entity.id) {
      return;
    }
    var url = '/api/1/entities/' + $scope.entity.id;
    $http.delete(url)
    triggerDone();
  };

  $scope.mergeDuplicate = function(dup) {
    var url = '/api/1/entities/' +  dup.id + '/merge/' + $scope.entity.id;
    $http.delete(url);
    triggerDone();
  };

  $scope.editDuplicate = function(dup) {
    Entity.edit(dup.id);
  };

  $scope.$on('key-pressed', function(e, k) {
    if (k == 65) {
      $scope.activate();
    }
    if (k == 68) {
      $scope.delete();
    }
    if (k == 77 && $scope.duplicateOptions.length) {
      $scope.mergeDuplicate($scope.duplicateOptions[0]);
    }
  });

  loadNext();

}]);
<commit_msg>Hide until suggestions are in. <commit_after>
aleph.controller('EntitiesReviewCtrl', ['$scope', '$route', '$location', '$http', '$timeout', 'Collection', 'Entity', 'Metadata', 'Authz', 'Title',
    function($scope, $route, $location, $http, $timeout, Collection, Entity, Metadata, Authz, Title) {

  $scope.reportLoading(true);
  $scope.entity = null;
  $scope.empty = false;
  $scope.schemata = {};
  $scope.duplicateOptions = [];
  Title.set("Review entities", "entities");

  var entityCache = [],
      entitySkipIds = [],
      entityCacheDfd = null;

  var loadCachedEntity = function() {
    Metadata.get().then(function(metadata) {
      $scope.schemata = metadata.schemata;
      $scope.entity = entityCache.splice(0, 1)[0];
      Title.set("Review: " + $scope.entity.name, "entities");
      $scope.entity.jurisdiction_code = $scope.entity.jurisdiction_code || null;
      $http.get('/api/1/entities/' + $scope.entity.id + '/similar').then(function(res) {
        $scope.duplicateOptions = res.data.results;
        $scope.reportLoading(false);
      });
    });
  };

  var loadNext = function() {
    // console.log("Cache size:", entityCache.length);

    if ($scope.entity == null) {
      if (entityCache.length) {
        loadCachedEntity();
      } else if ($scope.empty) {
        $scope.reportLoading(false);
      }
    }

    $timeout(function() {
      if (!entityCacheDfd && !$scope.empty && entityCache.length < 22) {
        var params = {params: {skip: entitySkipIds.slice(entitySkipIds.length - 50)}}
        entityCacheDfd = $http.get('/api/1/entities/_pending', params);
        entityCacheDfd.then(function(res) {
          for (var i in res.data.results) {
            var ent = res.data.results[i];
            entitySkipIds.push(ent.id);
            entityCache.push(ent);
          }
          if (res.data.total == 0) {
            $scope.empty = true;
          }
          entityCacheDfd = null;
          loadNext();
        });
      }
    });
  };

  var triggerDone = function() {
    $scope.reportLoading(true);
    $scope.entity = null;
    loadNext();
  };

  $scope.activate = function() {
    if (!$scope.entity.id) {
      return;
    }
    var entity = angular.copy($scope.entity);
    entity.state = 'active';
    $http.post('/api/1/entities/' + entity.id, entity);
    triggerDone();
  };

  $scope.delete = function() {
    if (!$scope.entity.id) {
      return;
    }
    var url = '/api/1/entities/' + $scope.entity.id;
    $http.delete(url)
    triggerDone();
  };

  $scope.mergeDuplicate = function(dup) {
    var url = '/api/1/entities/' +  dup.id + '/merge/' + $scope.entity.id;
    $http.delete(url);
    triggerDone();
  };

  $scope.editDuplicate = function(dup) {
    Entity.edit(dup.id);
  };

  $scope.$on('key-pressed', function(e, k) {
    if (k == 65) {
      $scope.activate();
    }
    if (k == 68) {
      $scope.delete();
    }
    if (k == 77 && $scope.duplicateOptions.length) {
      $scope.mergeDuplicate($scope.duplicateOptions[0]);
    }
  });

  loadNext();

}]);
<|endoftext|>


<commit_before>var p = Ent.Project.create('bolt-loader', 'external');
p.setVersion(1, 0, 0);
p.setConfig({
    command: ["make"],
    dist: "gen",
    distInclude: "**/*"
});

<commit_msg>version bump<commit_after>var p = Ent.Project.create('bolt-loader', 'external');
p.setVersion(1, 1, 0);
p.setConfig({
    command: ["make"],
    dist: "gen",
    distInclude: "**/*"
});

<|endoftext|>


<commit_before>// generate schema:

var
    async = require('async'),
    _ = require('underscore');

var db = require('./db');

var keys = _.map(db, function(value, key) {
    return key;
});

console.log('\n-- generating sqls...\n');

var arr = [];

_.each(keys.sort(), function(key, list) {
    if (key=='sequelize' || key=='next_id')
        return;
    arr.push(function(callback) {
        console.log('\n-- generate model: ' + key + '\n');
        db[key].sync({ logging: console.log }).complete(function() {
            callback(null, key);
        });
    });
});

async.series(arr, function(err, results) {
    console.log('\n--Done.');
});
<commit_msg>add test user<commit_after>// generate schema:

var
    async = require('async'),
    _ = require('underscore');

var db = require('./db');

var keys = _.map(db, function(value, key) {
    return key;
});

console.log('\n-- generating sqls...\n');

var arr = [];

_.each(keys.sort(), function(key, list) {
    if (key=='sequelize' || key=='next_id')
        return;
    arr.push(function(callback) {
        console.log('\n-- generate model: ' + key + '\n');
        db[key].sync({ logging: console.log }).complete(function() {
            callback(null, key);
        });
    });
});

async.series(arr, function(err, results) {
    console.log('\n-- init test user...\n');
    console.log('\ninsert into t_user (id, role, name, email, passwd, verified, binds, image_url, locked_util, created_at, updated_at, version) values (\'00139454282989205c050f069414434a3588177998dcf73000\', 0, \'Admin\', \'admin@itranswarp.com\', \'e8f98b1676572cd24c753c331aa6b02e\', 1, \'\', \'http://about:blank\', 0, 1394542829892, 1394542829892, 0);');
    console.log('\n--Done.\n');
});
<|endoftext|>


<commit_before>/**
 * View Description
 *
 * @langversion JavaScript
 *
 * @author
 * @since
 */

var View     = require('core/View');
var template = require('templates/homeViewTemplate');
var Event    = require('events/Event');
var Router   = require('routers/ApplicationRouter');
var Collection = require('core/Collection');

var HomeView = View.extend({

  	/*
   	 * @private
	 */
	id: 'home-view',
	/*
   	 * @private
   	*/
	template: template,

	//--------------------------------------
  	//+ INHERITED / OVERRIDES
  	//--------------------------------------

	/*
	 * @private
	 */

	initialize: function() {
		_.bindAll( this );

	},

	/*
	 * @private
	 */

	events: {

		'click .btn.btn-default.btn-xs'	:		'onTriggerNodeClick',
		'click .breadcrumb-click'	:		'onBreadcrumbClick'
	},

	render: function() {

		// var route = new Router();
  //   		route.navigate("api/getnarrowerconcepts/node", {trigger:true});

      var tree = new Collection();
      tree.url = 'api/test';
      tree.fetch({
        success: function(response,xhr) {
             console.log("Inside success");
             console.log(response);
        },
        error: function (errorResponse) {
            console.log(errorResponse)
        }
     });

		this.$el.html( this.template(
		{
		'relatedList': [
		{
		'name':'related1',
		'id': 'idd1'
		},
		{
		'name':'related2',
				'id': 'idd2'
		},
		{
		'name':'related3',
		'id': 'idd3'
		}
		],
		'breadcrumb': [
		{
		'name':'node1',
		'id': 'node13'
		},
		{
		'name':'node2',
		'id': 'node125'
		},
		{
		'name':'node3',
		'id': 'node165'
		}
		],

		}));

		return this;
	},
	initSearchBox: function(){

                            // sURL = HMP.core.getCallURL('users_json');
                            sURL = '/api'
                            $("#selector").select2({
                                width: '80%',
                                placeholder: "Search ...",
                                allowClear: true,
                                minimumInputLength: 1,
                                ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
                                    url: sURL,
                                    cache: true,
                                    dataType : 'json',
                                    data: function (term, page) {
                                        return {
                                            q: term
                                        };
                                    },
                                    results: function (data, page) {
                                        return {
                                            results: data
                                        };
                                    }
                                },
                                formatResult: function(item) {
                                    return "aaa";
                                },
                                formatSelection: function(item) {
                                    return "bbbb";
                                },
                                id: function (obj) {
                                  return "aaaa";
                                },
                                dropdownCssClass: "bigdrop"
                                // escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
                            });

	},

	//--------------------------------------
	//+ PUBLIC METHODS / GETTERS / SETTERS
	//--------------------------------------

	//--------------------------------------
	//+ EVENT HANDLERS
	//--------------------------------------

	onTriggerNodeClick: function () {

	    alert('trigger test');
	},

	onBreadcrumbClick: function (e) {

	    e.stopImmediatePropagation();

	    var dataId = $(e.currentTarget).data('id');
	    // var id = clickedEl.attr("id");
	    // $('#'+e.target.id).trigger('click');

	    console.log(dataId);
	    $('#'+dataId).trigger('click');

	    //e.preventDefault();
	    //e.stopImmediatePropagation();

	}

	//--------------------------------------
	//+ PRIVATE AND PROTECTED METHODS
	//--------------------------------------

});

module.exports = HomeView;

<commit_msg>testing parsing 3<commit_after>/**
 * View Description
 *
 * @langversion JavaScript
 *
 * @author
 * @since
 */

var View     = require('core/View');
var template = require('templates/homeViewTemplate');
var Event    = require('events/Event');
var Router   = require('routers/ApplicationRouter');
var Collection = require('core/Collection');

var HomeView = View.extend({

  	/*
   	 * @private
	 */
	id: 'home-view',
	/*
   	 * @private
   	*/
	template: template,

	//--------------------------------------
  	//+ INHERITED / OVERRIDES
  	//--------------------------------------

	/*
	 * @private
	 */

	initialize: function() {
		_.bindAll( this );

	},

	/*
	 * @private
	 */

	events: {

		'click .btn.btn-default.btn-xs'	:		'onTriggerNodeClick',
		'click .breadcrumb-click'	:		'onBreadcrumbClick'
	},

	render: function() {

		// var route = new Router();
  //   		route.navigate("api/getnarrowerconcepts/node", {trigger:true});

      var tree = new Collection();
      tree.url = 'api/getnarrowerconcepts/c_1521';
      tree.fetch({
        success: function(response,xhr) {
             console.log("Inside success");
             console.log(response);
        },
        error: function (errorResponse) {
            console.log(errorResponse)
        }
     });

		this.$el.html( this.template(
		{
		'relatedList': [ +
            response.related +
		// {
		// 'name':'related1',
		// 'id': 'idd1'
		// },
		// {
		// 'name':'related2',
		// 		'id': 'idd2'
		// },
		// {
		// 'name':'related3',
		// 'id': 'idd3'
		// }
		// ],
		// 'breadcrumb': [
		// {
		// 'name':'node1',
		// 'id': 'node13'
		// },
		// {
		// 'name':'node2',
		// 'id': 'node125'
		// },
		// {
		// 'name':'node3',
		// 'id': 'node165'
		// }
		],

		}));

		return this;
	},
	initSearchBox: function(){

                            // sURL = HMP.core.getCallURL('users_json');
                            sURL = '/api'
                            $("#selector").select2({
                                width: '80%',
                                placeholder: "Search ...",
                                allowClear: true,
                                minimumInputLength: 1,
                                ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
                                    url: sURL,
                                    cache: true,
                                    dataType : 'json',
                                    data: function (term, page) {
                                        return {
                                            q: term
                                        };
                                    },
                                    results: function (data, page) {
                                        return {
                                            results: data
                                        };
                                    }
                                },
                                formatResult: function(item) {
                                    return "aaa";
                                },
                                formatSelection: function(item) {
                                    return "bbbb";
                                },
                                id: function (obj) {
                                  return "aaaa";
                                },
                                dropdownCssClass: "bigdrop"
                                // escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
                            });

	},

	//--------------------------------------
	//+ PUBLIC METHODS / GETTERS / SETTERS
	//--------------------------------------

	//--------------------------------------
	//+ EVENT HANDLERS
	//--------------------------------------

	onTriggerNodeClick: function () {

	    alert('trigger test');
	},

	onBreadcrumbClick: function (e) {

	    e.stopImmediatePropagation();

	    var dataId = $(e.currentTarget).data('id');
	    // var id = clickedEl.attr("id");
	    // $('#'+e.target.id).trigger('click');

	    console.log(dataId);
	    $('#'+dataId).trigger('click');

	    //e.preventDefault();
	    //e.stopImmediatePropagation();

	}

	//--------------------------------------
	//+ PRIVATE AND PROTECTED METHODS
	//--------------------------------------

});

module.exports = HomeView;

<|endoftext|>


<commit_before>/* jshint ignore:start */
'use strict';

var testHelper = require('../../../common/tests/test-helper');
var setupFile = require('./decision-setup');

var dashboardPage = require('../pages/dashboard');
var decisionsPage = require('../pages/decisions');
var definitionPage = require('../pages/decision-definition');
var instancePage = require('../pages/decision-instance');

describe.only('Cockpit Decision Instance Spec', function() {

  describe('page navigation', function() {

    before(function() {
      return testHelper(setupFile.setup1, function() {

        dashboardPage.navigateToWebapp('Cockpit');
        dashboardPage.authentication.userLogin('admin', 'admin');
        dashboardPage.goToSection('Decisions');
      });
    });

    it('should go to decision definition view', function() {

      // given
      decisionsPage.deployedDecisionsList.decisionName(0).then(function(decisionName) {

        // when
        decisionsPage.deployedDecisionsList.selectDecision(0).then(function() {

          // then
          expect(dashboardPage.breadcrumb.activeCrumb().getText()).to.eventually.eql(decisionName);
        });
      })
    });

    it('should go to process instance view', function() {

      // given
      definitionPage.decisionInstancesTab.instanceId(0).then(function(instanceId) {

        // when
        definitionPage.decisionInstancesTab.selectInstanceId(0).then(function() {

          // then
          expect(instancePage.information.instanceId()).to.eventually.eql(instanceId);
          expect(dashboardPage.breadcrumb.activeCrumb().getText()).to.eventually.eql(instanceId);
        });
      });
    });

  });

  describe('table interaction', function() {

    before(function() {
      return testHelper(setupFile.setup1, function() {

        dashboardPage.navigateToWebapp('Cockpit');
        dashboardPage.authentication.userLogin('admin', 'admin');
        dashboardPage.goToSection('Decisions');
      });
    });

    it('should display decision table', function() {

      // when
      decisionsPage.deployedDecisionsList.selectDecision(0);
      definitionPage.decisionInstancesTab.selectInstanceId(0);

      // then
      expect(instancePage.table.tableElement().isDisplayed()).to.eventually.be.true;
    });

    it('should highlight fired rules', function() {
      expect(instancePage.table.row(0).getAttribute('class')).to.eventually.contain('fired');
    });

    it('should show the inputs on the table', function() {
      expect(instancePage.table.labelRow().getInputText(0)).to.eventually.eql('Invoice Amount = 100');
      expect(instancePage.table.labelRow().getInputText(1)).to.eventually.eql('Invoice Category = travelExpenses');
    });

    it('should show the outputs on the table', function() {
      expect(instancePage.table.ruleRow(0).getCellText(3)).to.eventually.eql('"accounting" = accounting');
    });

  });

  describe('in-/outputs', function() {

    before(function() {
      return testHelper(setupFile.setup1, function() {

        dashboardPage.navigateToWebapp('Cockpit');
        dashboardPage.authentication.userLogin('admin', 'admin');
        dashboardPage.goToSection('Decisions');
      });
    });

    it('should go to decision instance view', function() {
      // when
      decisionsPage.deployedDecisionsList.selectDecision(0);

      definitionPage.decisionInstancesTab.instanceId(0).then(function(instanceId) {
        definitionPage.decisionInstancesTab.selectInstanceId(0);

        // then
        expect(dashboardPage.breadcrumb.activeCrumb().getText()).to.eventually.eql(instanceId);
      });
    });

    it('show inputs for the decision instance', function() {

      // when
      instancePage.inputsTab.selectTab();

      // then
      expect(instancePage.inputsTab.variableValue(0)).to.eventually.eql('100');
    });

    it('show outputs for the decision instance', function() {

      // when
      instancePage.outputsTab.selectTab();

      // then
      expect(instancePage.outputsTab.variableValue(0)).to.eventually.eql('accounting');
    });

  });

  describe('in-/outputs without clause name', function() {

    before(function() {
      return testHelper(setupFile.setup3, function() {

        dashboardPage.navigateToWebapp('Cockpit');
        dashboardPage.authentication.userLogin('admin', 'admin');
        dashboardPage.goToSection('Decisions');
      });
    });

    it('should go to decision instance view', function() {
      // when
      decisionsPage.deployedDecisionsList.selectDecision(0);

      definitionPage.decisionInstancesTab.instanceId(0).then(function(instanceId) {
        definitionPage.decisionInstancesTab.selectInstanceId(0);

        // then
        expect(dashboardPage.breadcrumb.activeCrumb().getText()).to.eventually.eql(instanceId);
      });
    });

    it('show inputs clause id', function() {

      // when
      instancePage.inputsTab.selectTab();

      // then
      expect(instancePage.inputsTab.variableName(0)).to.eventually.eql('clause1');
    });

    it('show outputs clause id', function() {

      // when
      instancePage.outputsTab.selectTab();

      // then
      expect(instancePage.outputsTab.variableName(0)).to.eventually.eql('clause3');
    });

  });

  describe('actions', function() {

    describe('navigate to process instance', function() {

      before(function() {
        return testHelper(setupFile.setup1, function() {

          dashboardPage.navigateToWebapp('Cockpit');
          dashboardPage.authentication.userLogin('admin', 'admin');
          dashboardPage.goToSection('Decisions');
        });
      });

      it('go to decision instance view', function() {

        // when
        decisionsPage.deployedDecisionsList.selectDecision(0);
        definitionPage.decisionInstancesTab.selectInstanceId(0);
      });

      it('go to the process instance page', function() {

        // when
        instancePage.gotoProcessInstanceAction.gotoProcessInstance();

        // then
        expect(browser.getCurrentUrl()).to.eventually.contain('#/process-instance/');
      });

    });

    describe('navigation action', function() {

      before(function() {
        return testHelper(setupFile.setup4, function() {

          dashboardPage.navigateToWebapp('Cockpit');
          dashboardPage.authentication.userLogin('admin', 'admin');
          dashboardPage.goToSection('Decisions');
          decisionsPage.deployedDecisionsList.selectDecision(0);
          definitionPage.decisionInstancesTab.selectInstanceId(0);
        });
      });

      it('is not displayed', function() {

        // then
        expect(instancePage.gotoProcessInstanceAction.gotoProcessInstanceButton().isDisplayed()).to.eventually.eql(false);
      });

    });

  });

  describe.skip('multi tenancy', function() {

    before(function() {
      return testHelper(setupFile.multiTenancySetup, function() {

        dashboardPage.navigateToWebapp('Cockpit');
        dashboardPage.authentication.userLogin('admin', 'admin');
      });
    });

    it.skip('should not display tenant id of instance if not exists', function() {

      // given
      dashboardPage.goToSection('Decisions');

      // when
      // HEADS UP, you cannot rely on the table sorting in cockpit! Test skipped due to CAM-6007
      decisionsPage.deployedDecisionsList.selectDecision(0);
      definitionPage.decisionInstancesTab.selectInstanceId(0);

      // then
      expect(instancePage.information.tenantId()).to.eventually.contain('tenant1');
    });

    it.skip('should display tenant id of instance', function() {

      // given
      dashboardPage.navigateToWebapp('Cockpit');
      dashboardPage.goToSection('Decisions');

      // when
      // HEADS UP, you cannot rely on the table sorting in cockpit! Test skipped due to CAM-6007
      decisionsPage.deployedDecisionsList.selectDecision(1);
      definitionPage.decisionInstancesTab.selectInstanceId(0);

      // then
      expect(instancePage.information.tenantId()).to.eventually.contain('tenant1');
    });

  });

});
<commit_msg>chore(cockpit test): enable decision multi tenancy test<commit_after>/* jshint ignore:start */
'use strict';

var testHelper = require('../../../common/tests/test-helper');
var setupFile = require('./decision-setup');

var dashboardPage = require('../pages/dashboard');
var decisionsPage = require('../pages/decisions');
var definitionPage = require('../pages/decision-definition');
var instancePage = require('../pages/decision-instance');

describe('Cockpit Decision Instance Spec', function() {

  describe('page navigation', function() {

    before(function() {
      return testHelper(setupFile.setup1, function() {

        dashboardPage.navigateToWebapp('Cockpit');
        dashboardPage.authentication.userLogin('admin', 'admin');
        dashboardPage.goToSection('Decisions');
      });
    });

    it('should go to decision definition view', function() {

      // given
      decisionsPage.deployedDecisionsList.decisionName(0).then(function(decisionName) {

        // when
        decisionsPage.deployedDecisionsList.selectDecision(0).then(function() {

          // then
          expect(dashboardPage.breadcrumb.activeCrumb().getText()).to.eventually.eql(decisionName);
        });
      })
    });

    it('should go to process instance view', function() {

      // given
      definitionPage.decisionInstancesTab.instanceId(0).then(function(instanceId) {

        // when
        definitionPage.decisionInstancesTab.selectInstanceId(0).then(function() {

          // then
          expect(instancePage.information.instanceId()).to.eventually.eql(instanceId);
          expect(dashboardPage.breadcrumb.activeCrumb().getText()).to.eventually.eql(instanceId);
        });
      });
    });

  });

  describe('table interaction', function() {

    before(function() {
      return testHelper(setupFile.setup1, function() {

        dashboardPage.navigateToWebapp('Cockpit');
        dashboardPage.authentication.userLogin('admin', 'admin');
        dashboardPage.goToSection('Decisions');
      });
    });

    it('should display decision table', function() {

      // when
      decisionsPage.deployedDecisionsList.selectDecision(0);
      definitionPage.decisionInstancesTab.selectInstanceId(0);

      // then
      expect(instancePage.table.tableElement().isDisplayed()).to.eventually.be.true;
    });

    it('should highlight fired rules', function() {
      expect(instancePage.table.row(0).getAttribute('class')).to.eventually.contain('fired');
    });

    it('should show the inputs on the table', function() {
      expect(instancePage.table.labelRow().getInputText(0)).to.eventually.eql('Invoice Amount = 100');
      expect(instancePage.table.labelRow().getInputText(1)).to.eventually.eql('Invoice Category = travelExpenses');
    });

    it('should show the outputs on the table', function() {
      expect(instancePage.table.ruleRow(0).getCellText(3)).to.eventually.eql('"accounting" = accounting');
    });

  });

  describe('in-/outputs', function() {

    before(function() {
      return testHelper(setupFile.setup1, function() {

        dashboardPage.navigateToWebapp('Cockpit');
        dashboardPage.authentication.userLogin('admin', 'admin');
        dashboardPage.goToSection('Decisions');
      });
    });

    it('should go to decision instance view', function() {
      // when
      decisionsPage.deployedDecisionsList.selectDecision(0);

      definitionPage.decisionInstancesTab.instanceId(0).then(function(instanceId) {
        definitionPage.decisionInstancesTab.selectInstanceId(0);

        // then
        expect(dashboardPage.breadcrumb.activeCrumb().getText()).to.eventually.eql(instanceId);
      });
    });

    it('show inputs for the decision instance', function() {

      // when
      instancePage.inputsTab.selectTab();

      // then
      expect(instancePage.inputsTab.variableValue(0)).to.eventually.eql('100');
    });

    it('show outputs for the decision instance', function() {

      // when
      instancePage.outputsTab.selectTab();

      // then
      expect(instancePage.outputsTab.variableValue(0)).to.eventually.eql('accounting');
    });

  });

  describe('in-/outputs without clause name', function() {

    before(function() {
      return testHelper(setupFile.setup3, function() {

        dashboardPage.navigateToWebapp('Cockpit');
        dashboardPage.authentication.userLogin('admin', 'admin');
        dashboardPage.goToSection('Decisions');
      });
    });

    it('should go to decision instance view', function() {
      // when
      decisionsPage.deployedDecisionsList.selectDecision(0);

      definitionPage.decisionInstancesTab.instanceId(0).then(function(instanceId) {
        definitionPage.decisionInstancesTab.selectInstanceId(0);

        // then
        expect(dashboardPage.breadcrumb.activeCrumb().getText()).to.eventually.eql(instanceId);
      });
    });

    it('show inputs clause id', function() {

      // when
      instancePage.inputsTab.selectTab();

      // then
      expect(instancePage.inputsTab.variableName(0)).to.eventually.eql('clause1');
    });

    it('show outputs clause id', function() {

      // when
      instancePage.outputsTab.selectTab();

      // then
      expect(instancePage.outputsTab.variableName(0)).to.eventually.eql('clause3');
    });

  });

  describe('actions', function() {

    describe('navigate to process instance', function() {

      before(function() {
        return testHelper(setupFile.setup1, function() {

          dashboardPage.navigateToWebapp('Cockpit');
          dashboardPage.authentication.userLogin('admin', 'admin');
          dashboardPage.goToSection('Decisions');
        });
      });

      it('go to decision instance view', function() {

        // when
        decisionsPage.deployedDecisionsList.selectDecision(0);
        definitionPage.decisionInstancesTab.selectInstanceId(0);
      });

      it('go to the process instance page', function() {

        // when
        instancePage.gotoProcessInstanceAction.gotoProcessInstance();

        // then
        expect(browser.getCurrentUrl()).to.eventually.contain('#/process-instance/');
      });

    });

    describe('navigation action', function() {

      before(function() {
        return testHelper(setupFile.setup4, function() {

          dashboardPage.navigateToWebapp('Cockpit');
          dashboardPage.authentication.userLogin('admin', 'admin');
          dashboardPage.goToSection('Decisions');
          decisionsPage.deployedDecisionsList.selectDecision(0);
          definitionPage.decisionInstancesTab.selectInstanceId(0);
        });
      });

      it('is not displayed', function() {

        // then
        expect(instancePage.gotoProcessInstanceAction.gotoProcessInstanceButton().isDisplayed()).to.eventually.eql(false);
      });

    });

  });

  describe('multi tenancy', function() {

    before(function() {
      return testHelper(setupFile.multiTenancySetup, function() {

        dashboardPage.navigateToWebapp('Cockpit');
        dashboardPage.authentication.userLogin('admin', 'admin');
      });
    });

    it('should not display tenant id of instance if not exists', function() {

      // given
      dashboardPage.goToSection('Decisions');

      // when
      decisionsPage.deployedDecisionsList.selectDecision(0);
      definitionPage.decisionInstancesTab.selectInstanceId(0);

      // then
      expect(instancePage.information.tenantId()).to.eventually.contain('null');
    });

    it('should display tenant id of instance', function() {

      // given
      dashboardPage.navigateToWebapp('Cockpit');
      dashboardPage.goToSection('Decisions');

      // when
      decisionsPage.deployedDecisionsList.selectDecision(1);
      definitionPage.decisionInstancesTab.selectInstanceId(0);

      // then
      expect(instancePage.information.tenantId()).to.eventually.contain('tenant1');
    });

  });

});
<|endoftext|>


<commit_before><commit_msg>transport fix<commit_after><|endoftext|>


<commit_before>import React from 'react';
import Relay from 'react-relay';
import PropTypes from 'prop-types';

import Octicon from '../../views/octicon';

export class Commit extends React.Component {
  static propTypes = {
    item: PropTypes.object.isRequired,
  }

  render() {
    const commit = this.props.item;
    return (

        <Octicon className="pre-timeline-item-icon" icon="git-commit" />

        {commit.oid.slice(0, 8)}

    );
  }
}

export default Relay.createContainer(Commit, {
  fragments: {
    item: () => Relay.QL`
      fragment on Commit {
        author {
          name avatarUrl
          user {
            login
          }
        }
        oid messageHeadline messageHeadlineHTML
      }
    `,
  },
});
<commit_msg>Render committer<commit_after>import React from 'react';
import Relay from 'react-relay';
import PropTypes from 'prop-types';

import Octicon from '../../views/octicon';

export class Commit extends React.Component {
  static propTypes = {
    item: PropTypes.object.isRequired,
  }

  renderCommitter(commit) {
    if (!commit.authoredByCommitter) {
      return (

      );
    }
    return null;
  }
  render() {
    const commit = this.props.item;
    return (

        <Octicon className="pre-timeline-item-icon" icon="git-commit" />

        {this.renderCommitter(commit)}

        {commit.oid.slice(0, 8)}

    );
  }
}

export default Relay.createContainer(Commit, {
  fragments: {
    item: () => Relay.QL`
      fragment on Commit {
        author {
          name avatarUrl
          user {
            login
          }
        }
        committer {
          name avatarUrl
          user {
            login
          }
        }
        authoredByCommitter
        oid messageHeadline messageHeadlineHTML
      }
    `,
  },
});
<|endoftext|>


<commit_before>import { assert } from 'ember-debug';
import EmberObject from '../system/object';
import Mixin from '../mixins/controller';
import { createInjectionHelper } from '../inject';
import { deprecateUnderscoreActions } from '../mixins/action_handler';

/**
@module ember
@submodule ember-runtime
*/

/**
  @class Controller
  @namespace Ember
  @extends Ember.Object
  @uses Ember.ControllerMixin
  @public
*/
const Controller = EmberObject.extend(Mixin);

deprecateUnderscoreActions(Controller);

function controllerInjectionHelper(factory) {
  assert(
    'Defining an injected controller property on a ' +
    'non-controller is not allowed.',
    Mixin.detect(factory.PrototypeMixin)
  );
}

/**
  Creates a property that lazily looks up another controller in the container.
  Can only be used when defining another controller.

  Example:

  ```app/controllers/post.js
  import Controller, {
    inject as controller
  } from '@ember/controller';

  export default Controller.extend({
    posts: controller()
  });
  ```

  This example will create a `posts` property on the `post` controller that
  looks up the `posts` controller in the container, making it easy to
  reference other controllers. This is functionally equivalent to:

  ```app/controllers/post.js
  import Controller from '@ember/controller';
  import { alias } from '@ember/object/computed';

  export default Controller.extend({
    needs: 'posts',
    posts: alias('controllers.posts')
  });
  ```

  @method controller
  @since 1.10.0
  @for Ember.inject
  @param {String} name (optional) name of the controller to inject, defaults
         to the property's name
  @return {Ember.InjectedProperty} injection descriptor instance
  @public
*/
createInjectionHelper('controller', controllerInjectionHelper);

export default Controller;
<commit_msg>[DOC release] Remove controller needs from docs<commit_after>import { assert } from 'ember-debug';
import EmberObject from '../system/object';
import Mixin from '../mixins/controller';
import { createInjectionHelper } from '../inject';
import { deprecateUnderscoreActions } from '../mixins/action_handler';

/**
@module ember
@submodule ember-runtime
*/

/**
  @class Controller
  @namespace Ember
  @extends Ember.Object
  @uses Ember.ControllerMixin
  @public
*/
const Controller = EmberObject.extend(Mixin);

deprecateUnderscoreActions(Controller);

function controllerInjectionHelper(factory) {
  assert(
    'Defining an injected controller property on a ' +
    'non-controller is not allowed.',
    Mixin.detect(factory.PrototypeMixin)
  );
}

/**
  Creates a property that lazily looks up another controller in the container.
  Can only be used when defining another controller.

  Example:

  ```app/controllers/post.js
  import Controller, {
    inject as controller
  } from '@ember/controller';

  export default Controller.extend({
    posts: controller()
  });
  ```

  This example will create a `posts` property on the `post` controller that
  looks up the `posts` controller in the container, making it easy to
  reference other controllers.

  @method controller
  @since 1.10.0
  @for Ember.inject
  @param {String} name (optional) name of the controller to inject, defaults
         to the property's name
  @return {Ember.InjectedProperty} injection descriptor instance
  @public
*/
createInjectionHelper('controller', controllerInjectionHelper);

export default Controller;
<|endoftext|>


<commit_before>/*
 * vim: ts=4:sw=4:expandtab
 */
(function () {
    'use strict';
    window.Whisper = window.Whisper || {};

    var CheckboxView = Whisper.View.extend({
        initialize: function(options) {
            this.name = options.name;
            this.defaultValue = options.defaultValue;
            this.populate();
        },
        events: {
            'change': 'change'
        },
        change: function(e) {
            var value = e.target.checked;
            storage.put(this.name, value);
            console.log(this.name, 'changed to', value);
        },
        populate: function() {
            var value = storage.get(this.name, this.defaultValue);
            this.$('input').prop('checked', !!value);
        },
    });
    var RadioButtonGroupView = Whisper.View.extend({
        initialize: function(options) {
            this.name = options.name;
            this.defaultValue = options.defaultValue;
            this.populate();
        },
        events: {
            'change': 'change'
        },
        change: function(e) {
            var value = this.$(e.target).val();
            storage.put(this.name, value);
            console.log(this.name, 'changed to', value);
            this.$el.trigger('change-theme');
        },
        populate: function() {
            var value = storage.get(this.name, this.defaultValue);
            this.$('#' + this.name + '-' + value).attr('checked', 'checked');
        },
    });
    Whisper.SettingsView = Whisper.View.extend({
        className: 'settings modal expand',
        templateName: 'settings',
        initialize: function() {
            this.render();
            new RadioButtonGroupView({
                el: this.$('.notification-settings'),
                defaultValue: 'message',
                name: 'notification-setting'
            });
            new RadioButtonGroupView({
                el: this.$('.theme-settings'),
                defaultValue: 'message',
                name: 'theme-setting'
            });
            new CheckboxView({
                el: this.$('.safety-numbers-settings'),
                defaultValue: true,
                name: 'safety-numbers-approval'
            });
            if (textsecure.storage.user.getDeviceId() != '1') {
                var syncView = new SyncView().render();
                this.$('.content').append(syncView.el);
            }
        },
        events: {
            'click .close': 'remove'
        },
        render_attributes: function() {
            return {
              notifications: i18n('notifications'),
              notificationSettingsDialog: i18n('notificationSettingsDialog'),
              settings: i18n('settings'),
              disableNotifications: i18n('disableNotifications'),
              nameAndMessage: i18n('nameAndMessage'),
              noNameOrMessage: i18n('noNameOrMessage'),
              nameOnly: i18n('nameOnly'),
              safetyNumbersSettingDescription: i18n('safetyNumbersSettingDescription'),
              safetyNumbersSettingHeader: i18n('safetyNumbersSettingHeader'),
            };
        }
    });

    var SyncView = Whisper.View.extend({
        templateName: 'syncSettings',
        className: 'syncSettings',
        events: {
            'click .sync': 'sync'
        },
        enable: function() {
            this.$('.sync').text(i18n('syncNow'));
            this.$('.sync').removeAttr('disabled');
        },
        disable: function() {
            this.$('.sync').attr('disabled', 'disabled');
            this.$('.sync').text(i18n('syncing'));
        },
        onsuccess: function() {
            storage.put('synced_at', Date.now());
            console.log('sync successful');
            this.enable();
            this.render();
        },
        ontimeout: function() {
            console.log('sync timed out');
            this.$('.synced_at').hide();
            this.$('.sync_failed').show();
            this.enable();
        },
        sync: function() {
            this.$('.sync_failed').hide();
            if (textsecure.storage.user.getDeviceId() != '1') {
                this.disable();
                var syncRequest = window.getSyncRequest();
                syncRequest.addEventListener('success', this.onsuccess.bind(this));
                syncRequest.addEventListener('timeout', this.ontimeout.bind(this));
            } else {
                console.log("Tried to sync from device 1");
            }
        },
        render_attributes: function() {
            var attrs = {
                sync: i18n('sync'),
                syncNow: i18n('syncNow'),
                syncExplanation: i18n('syncExplanation'),
                syncFailed: i18n('syncFailed')
            };
            var date = storage.get('synced_at');
            if (date) {
                date = new Date(date);
                attrs.lastSynced = i18n('lastSynced');
                attrs.syncDate = date.toLocaleDateString();
                attrs.syncTime = date.toLocaleTimeString();
            }
            return attrs;
        }
    });
})();
<commit_msg>Fixed bug920<commit_after>/*
 * vim: ts=4:sw=4:expandtab
 */
(function () {
    'use strict';
    window.Whisper = window.Whisper || {};

    var CheckboxView = Whisper.View.extend({
        initialize: function(options) {
            this.name = options.name;
            this.defaultValue = options.defaultValue;
            this.populate();
        },
        events: {
            'change': 'change'
        },
        change: function(e) {
            var value = e.target.checked;
            storage.put(this.name, value);
            console.log(this.name, 'changed to', value);
        },
        populate: function() {
            var value = storage.get(this.name, this.defaultValue);
            this.$('input').prop('checked', !!value);
        },
    });
    var RadioButtonGroupView = Whisper.View.extend({
        initialize: function(options) {
            this.name = options.name;
            this.defaultValue = options.defaultValue;
            this.populate();
        },
        events: {
            'change': 'change'
        },
        change: function(e) {
            var value = this.$(e.target).val();
            storage.put(this.name, value);
            console.log(this.name, 'changed to', value);
            this.$el.trigger('change-theme');
        },
        populate: function() {
            var value = storage.get(this.name, this.defaultValue);
            this.$('#' + this.name + '-' + value).attr('checked', 'checked');
        },
    });
    Whisper.SettingsView = Whisper.View.extend({
        className: 'settings modal expand',
        templateName: 'settings',
        initialize: function() {
            this.render();
            new RadioButtonGroupView({
                el: this.$('.notification-settings'),
                defaultValue: 'message',
                name: 'notification-setting'
            });
            new RadioButtonGroupView({
                el: this.$('.theme-settings'),
                defaultValue: 'android',
                name: 'theme-setting'
            });
            new CheckboxView({
                el: this.$('.safety-numbers-settings'),
                defaultValue: true,
                name: 'safety-numbers-approval'
            });
            if (textsecure.storage.user.getDeviceId() != '1') {
                var syncView = new SyncView().render();
                this.$('.content').append(syncView.el);
            }
        },
        events: {
            'click .close': 'remove'
        },
        render_attributes: function() {
            return {
              notifications: i18n('notifications'),
              notificationSettingsDialog: i18n('notificationSettingsDialog'),
              settings: i18n('settings'),
              disableNotifications: i18n('disableNotifications'),
              nameAndMessage: i18n('nameAndMessage'),
              noNameOrMessage: i18n('noNameOrMessage'),
              nameOnly: i18n('nameOnly'),
              safetyNumbersSettingDescription: i18n('safetyNumbersSettingDescription'),
              safetyNumbersSettingHeader: i18n('safetyNumbersSettingHeader'),
            };
        }
    });

    var SyncView = Whisper.View.extend({
        templateName: 'syncSettings',
        className: 'syncSettings',
        events: {
            'click .sync': 'sync'
        },
        enable: function() {
            this.$('.sync').text(i18n('syncNow'));
            this.$('.sync').removeAttr('disabled');
        },
        disable: function() {
            this.$('.sync').attr('disabled', 'disabled');
            this.$('.sync').text(i18n('syncing'));
        },
        onsuccess: function() {
            storage.put('synced_at', Date.now());
            console.log('sync successful');
            this.enable();
            this.render();
        },
        ontimeout: function() {
            console.log('sync timed out');
            this.$('.synced_at').hide();
            this.$('.sync_failed').show();
            this.enable();
        },
        sync: function() {
            this.$('.sync_failed').hide();
            if (textsecure.storage.user.getDeviceId() != '1') {
                this.disable();
                var syncRequest = window.getSyncRequest();
                syncRequest.addEventListener('success', this.onsuccess.bind(this));
                syncRequest.addEventListener('timeout', this.ontimeout.bind(this));
            } else {
                console.log("Tried to sync from device 1");
            }
        },
        render_attributes: function() {
            var attrs = {
                sync: i18n('sync'),
                syncNow: i18n('syncNow'),
                syncExplanation: i18n('syncExplanation'),
                syncFailed: i18n('syncFailed')
            };
            var date = storage.get('synced_at');
            if (date) {
                date = new Date(date);
                attrs.lastSynced = i18n('lastSynced');
                attrs.syncDate = date.toLocaleDateString();
                attrs.syncTime = date.toLocaleTimeString();
            }
            return attrs;
        }
    });
})();
<|endoftext|>


<commit_before>"use strict";
/*global alert: true, ODSA */
/*global sweep */
(function ($) {
  var comp = function(a, b) {
    return a - b;
  };

    function Bintree(jsav, xrange, yrange) {

    var tree;
    var root;

    tree = jsav.ds.bintree({nodegap: 10});
    root = tree.root('');
    root.leaf = true;
    root.level = 0;
    //tree.root(root);

    var newL1  = tree.newNode('');
    var newR1 = tree.newNode('');
    newL1.leaf = newR1.leaf = true;
    newR1.empty = newL1.empty = true;
    root.left(newL1);
    root.right(newR1);

    // DON't FORGET THIS!!!
    tree.layout();

    this.isEmpty = function () {
      console.log("Bintree isEmpty test: ", !root.left() && !root.right());
      return (!root.left() && !root.right());
    }

    // returns a node!
    this.insert = function(rt, INx, INy, INrec, Bx, By, Bwid, Bhgt, level) {

      jsav.step();
      tree.layout();
      console.log("Bintree insert: ", INrec);

      if (rt.leaf == true && rt.empty == true) {
        console.log("insert: encountered empty leaf node: insert data and return")
        jsav.umsg("Insert: Encountered an empty leaf node: Now insert data and return!");
        var temp = tree.newNode(INRec);
        temp.x = INx;
        temp.y = INy;

        jsav.step();
        return temp;
      }

      if (rt.leaf == true) {
        var temp = tree.newNode('');
        var newLeft  = tree.newNode('');
        var newRight = tree.newNode('');
        newLeft.leaf = newRight.leaf = true;
        newRight.empty = newLeft.empty = true;
        temp.setLeftNode(newLeft);
        temp.setRightNode(newRight);
        rt = insert(temp, rt.x, rt.y, rt.value(), Bx, By, Bwid, Bhgt, level);

        // NO Return: Rolls through to next if statement
      }

      // If here, we have an internal node to insert into
    if (level % 2 == 0) // Branch on X
    {
      if (rt.x < (Bx + Bwid/2)) // Insert left
      {
        rt.left(insert(rt.left(), INx, INy, INrec, Bx, By, Bwid/2, Bhgt, level+1));
      }
      else
      {
        rt.right(insert(rt.right(), INx, INy, INrec, Bx + Bwid/2, By, Bwid/2, Bhgt, level+1));
      }
    }

    else // Branch on Y
    {
      if (rt.y < (By + Bhgt/2)) // Insert left
      {
        rt.left(insert(rt.left(), INx, INy, INrec, Bx, By, Bwid, Bhgt/2, level+1));
      }
      else
      {
        rt.right(insert(rt.right(), INx, INy, INrec, Bx, By + Bhgt/2, Bwid, Bhgt/2, level+1));
      }
    }

    tree.layout();
    return rt;

    } // insert

    this.delete = function(BINnode rt, INx, INy, Bx, By, Bwid, Bhgt, level) {
      console.assert( !(rt.leaf == true && rt.empty == true), "Cannot be an empty leaf during delete");

      if (rt.leaf) {
        if (rt.x == INx && rt.y == INy)
        {
          var temp = tree.newNode('');
          temp.leaf = true;
          temp.empty = true;
          return temp;
        }
        // else ERROR: THIS IS IMPOSSIBLE;
      }

      // We have an internal node
      if (level % 2 == 0) // Branch on X
      {
        if (INx < (Bx + Bwid/2)) // Insert left
        {
          rt.left(delete(rt.left(), INx, INy, Bx, By, Bwid/2, Bhgt, level+1));
        }
        else
        {
          rt.right(delete(rt.right(), INx, INy, Bx + Bwid/2, By, Bwid/2, Bhgt, level+1));
        }
      }

      else // Branch on Y
      {
        if (INy < (By + Bhgt/2)) // Insert left
        {
          rt.left(delete(rt.left(), INx, INy, Bx, By, Bwid, Bhgt/2, level+1));
        }
        else
          rt.right(delete(rt.right(), INx, INy, Bx, By + Bhgt/2, Bwid, Bhgt/2, level+1));
      }

      tree.layout();

      // Now, check to see if there should be a merge
      if ((rt.left().leaf == true && rt.left().empty == true) && (rt.right().leaf))
      {
        return rt.right();
      }
      if ((rt.left().leaf) && (rt.right().leaf && rt.left.empty))
      {
        return rt.left();
      }
      // Otherwise, return just the rt subtree without a merge
      return rt;
}

  } // bintree

  var arr;

  // check query parameters from URL
  var params = JSAV.utils.getQueryParameter();
  if ("increments" in params) { // set value of increments if it is a param
    $('#increments').val(params.increments).prop("disabled", true);
  }

  // create a new settings panel and specify the link to show it
  var settings = new JSAV.utils.Settings($(".jsavsettings"));
  // add the layout setting preference
  var arrayLayout = settings.add("layout",
    {"type": "select", "options": {"bar": "Bar", "array": "Array"},
     "label": "Array layout: ", "value": "bar"});

  // Initialize the arraysize dropdown list
  ODSA.AV.initArraySize(5, 16, 8);

  // Process help button: Give a full help page for this activity
  // We might give them another HTML page to look at.
  function help() {
    window.open("bintreeHelpAV.html", 'helpwindow');
  }

  // Process About button: Pop up a message with an Alert
  function about() {
    alert("Bintree Visualization\nWritten by Anthony Rinaldi and Cliff Shaffer\nCreated as part of the OpenDSA hypertextbook project\nFor more information, see http://algoviz.org/OpenDSA\nSource and development history available at\nhttps://github.com/cashaffer/OpenDSA\nCompiled with JSAV library version " + JSAV.version());
  }

  // Execute the "Run" button function
  function runIt() {

    ODSA.AV.reset(true);

    var jsav = new JSAV($('.avcontainer'));

    jsav.umsg("Let's get started");
    var bint = new Bintree(jsav);
    bint.isEmpty();
    jsav.displayInit();

  jsav.step();

    // Setup the tree
    jsav.umsg("Step 1: insert node with value \"A\" @ 10, 10");
  // rt, INx, INy, INrec, Bx, By, Bwid, Bhgt, level
    bint.insert(bint.root, 10, 10, "A", 100, 100, 200, 200, 0);
    bint.isEmpty();

    jsav.step();

  // Done
    jsav.umsg("All Done!");

    jsav.recorded(); // mark the end

  }

  // Connect action callbacks to the HTML entities
  $('#help').click(help);
  $('#about').click(about);
  $('#run').click(runIt);
  $('#reset').click(ODSA.AV.reset);

}(jQuery));<commit_msg>Incrimental changes and minor fixes on bintree algorithm<commit_after>"use strict";
/*global alert: true, ODSA */
/*global sweep */
(function ($) {
  var comp = function(a, b) {
    return a - b;
  };

  function Bintree(jsav, xrange, yrange) {

    var tree;
    var root;

    tree = jsav.ds.bintree({nodegap: 10});
    root = tree.root('');
    root.leaf = true;
    root.empty = true;
    root.level = 0;

    // The bintree starts with a root node, and two empty leafnodes
    var newL1  = tree.newNode('');
    var newR1 = tree.newNode('');
    newL1.leaf = newR1.leaf = true;
    newR1.empty = newL1.empty = true;
    root.left(newL1);
    root.right(newR1);

    // DON't FORGET THIS!!!
    tree.layout();

    this.isEmpty = function () {
      var returning = (root.left().empty && root.left().leaf && root.right().empty && root.right().leaf);
      console.log("Bintree isEmpty test: ", returning);
      return (returning);
    }

    // returns a node!
    this.insert = function(rt, INx, INy, INrec, Bx, By, Bwid, Bhgt, level) {

      jsav.step();
      tree.layout();
      console.log("Bintree insert: ", INrec);

      console.assert(rt != null, "rt not defined");

      if (rt.leaf == true && rt.empty == true) {
        console.log("insert: encountered empty leaf node: insert data and return")
        jsav.umsg("Insert: Encountered an empty leaf node: Now insert data and return!");
        var temp = tree.newNode(INRec);
        temp.x = INx;
        temp.y = INy;

        jsav.step();
        return temp;
      }

      if (rt.leaf == true) {
        var temp = tree.newNode('');
        var newLeft  = tree.newNode('');
        var newRight = tree.newNode('');
        newLeft.leaf = newRight.leaf = true;
        newRight.empty = newLeft.empty = true;
        temp.setLeftNode(newLeft);
        temp.setRightNode(newRight);
        rt = insert(temp, rt.x, rt.y, rt.value(), Bx, By, Bwid, Bhgt, level);

        // NO Return: Rolls through to next if statement
      }

      // If here, we have an internal node to insert into
      if (level % 2 == 0) // Branch on X
      {
        if (rt.x < (Bx + Bwid/2)) // Insert left
        {
          rt.left(insert(rt.left(), INx, INy, INrec, Bx, By, Bwid/2, Bhgt, level+1));
        }
        else
        {
          rt.right(insert(rt.right(), INx, INy, INrec, Bx + Bwid/2, By, Bwid/2, Bhgt, level+1));
        }
      }

      else // Branch on Y
      {
        if (rt.y < (By + Bhgt/2)) // Insert left
        {
          rt.left(insert(rt.left(), INx, INy, INrec, Bx, By, Bwid, Bhgt/2, level+1));
        }
        else
        {
          rt.right(insert(rt.right(), INx, INy, INrec, Bx, By + Bhgt/2, Bwid, Bhgt/2, level+1));
        }
      }

      tree.layout();
      return rt;
    } // insert

    this.delete = function (rt, INx, INy, Bx, By, Bwid, Bhgt, level) {
      console.assert( !(rt.leaf == true && rt.empty == true), "Cannot be an empty leaf during delete");

      if (rt.leaf) {
        if (rt.x == INx && rt.y == INy)
        {
          var temp = tree.newNode('');
          temp.leaf = true;
          temp.empty = true;
          return temp;
        }
        // else ERROR: THIS IS IMPOSSIBLE;
      }

      // We have an internal node
      if (level % 2 == 0) // Branch on X
      {
        if (INx < (Bx + Bwid/2)) // Insert left
        {
          rt.left(delete(rt.left(), INx, INy, Bx, By, Bwid/2, Bhgt, level+1));
        }
        else
        {
          rt.right(delete(rt.right(), INx, INy, Bx + Bwid/2, By, Bwid/2, Bhgt, level+1));
        }
      }

      else // Branch on Y
      {
        if (INy < (By + Bhgt/2)) // Insert left
        {
          rt.left(delete(rt.left(), INx, INy, Bx, By, Bwid, Bhgt/2, level+1));
        }
        else
          rt.right(delete(rt.right(), INx, INy, Bx, By + Bhgt/2, Bwid, Bhgt/2, level+1));
      }

      tree.layout();

      // Now, check to see if there should be a merge
      if ((rt.left().leaf == true && rt.left().empty == true) && (rt.right().leaf))
      {
        return rt.right();
      }
      if ((rt.left().leaf) && (rt.right().leaf && rt.left.empty))
      {
        return rt.left();
      }

      // Otherwise, return just the rt subtree without a merge
      return rt;

    } // delete

  } // bintree

  var arr;

  // check query parameters from URL
  var params = JSAV.utils.getQueryParameter();
  if ("increments" in params) { // set value of increments if it is a param
    $('#increments').val(params.increments).prop("disabled", true);
  }

  // create a new settings panel and specify the link to show it
  var settings = new JSAV.utils.Settings($(".jsavsettings"));
  // add the layout setting preference
  var arrayLayout = settings.add("layout",
    {"type": "select", "options": {"bar": "Bar", "array": "Array"},
     "label": "Array layout: ", "value": "bar"});

  // Initialize the arraysize dropdown list
  ODSA.AV.initArraySize(5, 16, 8);

  // Process help button: Give a full help page for this activity
  // We might give them another HTML page to look at.
  function help() {
    window.open("bintreeHelpAV.html", 'helpwindow');
  }

  // Process About button: Pop up a message with an Alert
  function about() {
    alert("Bintree Visualization\nWritten by Anthony Rinaldi and Cliff Shaffer\nCreated as part of the OpenDSA hypertextbook project\nFor more information, see http://algoviz.org/OpenDSA\nSource and development history available at\nhttps://github.com/cashaffer/OpenDSA\nCompiled with JSAV library version " + JSAV.version());
  }

  // Execute the "Run" button function
  function runIt() {

    ODSA.AV.reset(true);

    var jsav = new JSAV($('.avcontainer'));

    jsav.umsg("Let's get started");
    var bint = new Bintree(jsav);
    bint.isEmpty();
    jsav.displayInit();

    jsav.step();

    // Setup the tree
    jsav.umsg("Step 1: insert node with value \"A\" @ 10, 10");
    // rt, INx, INy, INrec, Bx, By, Bwid, Bhgt, level
    bint.insert(bint.root, 10, 10, "A", 100, 100, 200, 200, 0);
    bint.isEmpty();

    jsav.step();

  // Done
    jsav.umsg("All Done!");

    jsav.recorded(); // mark the end

  }

  // Connect action callbacks to the HTML entities
  $('#help').click(help);
  $('#about').click(about);
  $('#run').click(runIt);
  $('#reset').click(ODSA.AV.reset);

}(jQuery));<|endoftext|>


<commit_before>// Accessory Page JS
function clearTabContent(tab){
	tab.innerText = '';
}

function getJSON(url, callback) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'json';
    xhr.onload = () => {
        const status = xhr.status;
        if (status === 200) {
            callback(null, xhr.response);
        } else {
            callback(status);
        }
    };
    xhr.send(null);
}

function createHTML(data) {
	const container = document.createElement('div');

	const tabTitle = document.createElement('span');
	tabTitle.className = 'product-title';
	tabTitle.innerText = data.header;
	container.append(tabTitle);

	const ulElement = document.createElement('ul');
	ulElement.className = 'accessorytab';

	// for loop start point
	for(let i = 0; i < data.items.length; i++) {
	let cardLink = document.createElement('a');
	cardLink.target='_blank';
	cardLink.href = data.items[i].itemLink;

	let liElement = document.createElement('li');
	liElement.className = 'accessorytab';

	let liImage = document.createElement('img');
	liImage.src = data.items[i].itemImg;
	liElement.append(liImage);
	liElement.append(data.items[i].itemName);

	cardLink.append(liElement);
	ulElement.append(cardLink);
	}
	// for loop end point

	container.append(ulElement);
	return container;
}

const accessoryTabContent = document.querySelector('#Things') || document.querySelector('#Accessories') || document.querySelector('#Housing');

if(accessoryTabContent){
	let tabContent = accessoryTabContent.innerText;
	tabContent = tabContent.split('.')[1];
	tabContent = tabContent.split('%%')[0];
	console.log(tabContent);
	let requestURL = '';
	switch(tabContent) {
		case 'LEDRopeLightAccessories':
			console.log('rope light accessories');
			requestURL = 'http://www.affordablequalitylighting.com/template/LEDRopeLightAccessories.json';
			getJSON(requestURL, (error, data) => {
				if (error) {
					console.log(error);
				}
				clearTabContent(accessoryTabContent);
				console.log(data);
				const newContent = createHTML(data);
				accessoryTabContent.append(newContent);
			});
			break;
		case 'OutdoorAccessories':
			console.log('outdoor accessories');
			requestURL = 'http://www.affordablequalitylighting.com/template/outdoorAccessories.json';
			getJSON(requestURL, (error, data) => {
				clearTabContent(accessoryTabContent);
				console.log(data);

				const newContent = createHTML(data);
				console.log(newContent);
				accessoryTabContent.append(newContent);
			});
			break;
		case '':
			console.log('underwater accessories');
			break;
		case '12VRopeLightAccessories':
			console.log('low voltage rope light accessories');
			break;
		case '120V4FluorescentHousings':
			requestURL = 'https://www.affordablequalitylighting.com/dav/template/120V4FluorescentHousings.json';
			getJSON(requestURL, (error, data) => {
				clearTabContent(accessoryTabContent);
				console.log(data);
				const newContent = createHTML(data);
				console.log(newContent);
				accessoryTabContent.append(newContent);
			});
			break;
		case '120V4FluorescentTrim':
			requestURL = 'http://www.affordablequalitylighting.com/template/120V4FluorescentTrims.json';
			getJSON(requestURL, (error, data) => {
				clearTabContent(accessoryTabContent);
				const newContent = createHTML(data);
				accessoryTabContent.append(newContent);
			});
			break;
		case '120V4Housing':
			console.log('120V 4 Housing');
			requestURL = 'http://www.affordablequalitylighting.com/template/120V4Housing.json';
			getJSON(requestURL, (error, data) => {
				clearTabContent(accessoryTabContent);
				const newContent = createHTML(data);
				accessoryTabContent.append(newContent);
			});
			break;
		case '120V5Housing':
			requestURL = 'http://www.affordablequalitylighting.com/template/120V5Housing.json';
			getJSON(requestURL, (error, data) => {
				clearTabContent(accessoryTabContent);
				const newContent = createHTML(data);
				accessoryTabContent.append(newContent);
			});
			break;
		case '120V6FluorescentHousing':
			requestURL = 'http://www.affordablequalitylighting.com/template/120V6FluorescentHousing.json';
			getJSON(requestURL, (error, data) => {
				clearTabContent(accessoryTabContent);
				const newContent = createHTML(data);
				accessoryTabContent.append(newContent);
			});
			break;
		default:
			console.log('no accessories');
	}
}
<commit_msg>added additional accessory panel routes<commit_after>// Accessory Page JS
function clearTabContent(tab){
	tab.innerText = '';
}

function getJSON(url, callback) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'json';
    xhr.onload = () => {
        const status = xhr.status;
        if (status === 200) {
            callback(null, xhr.response);
        } else {
            callback(status);
        }
    };
    xhr.send(null);
}

function createHTML(data) {
	const container = document.createElement('div');

	const tabTitle = document.createElement('span');
	tabTitle.className = 'product-title';
	tabTitle.innerText = data.header;
	container.append(tabTitle);

	const ulElement = document.createElement('ul');
	ulElement.className = 'accessorytab';

	// for loop start point
	for(let i = 0; i < data.items.length; i++) {
	let cardLink = document.createElement('a');
	cardLink.target='_blank';
	cardLink.href = data.items[i].itemLink;

	let liElement = document.createElement('li');
	liElement.className = 'accessorytab';

	let liImage = document.createElement('img');
	liImage.src = data.items[i].itemImg;
	liElement.append(liImage);
	liElement.append(data.items[i].itemName);

	cardLink.append(liElement);
	ulElement.append(cardLink);
	}
	// for loop end point

	container.append(ulElement);
	return container;
}

const accessoryTabContent = document.querySelector('#Things') || document.querySelector('#Accessories') || document.querySelector('#Housing');

if(accessoryTabContent){
	let tabContent = accessoryTabContent.innerText;
	tabContent = tabContent.split('.')[1];
	tabContent = tabContent.split('%%')[0];
	console.log(tabContent);
	let requestURL = '';
	switch(tabContent) {
		case 'LEDRopeLightAccessories':
			console.log('rope light accessories');
			requestURL = 'http://www.affordablequalitylighting.com/template/LEDRopeLightAccessories.json';
			getJSON(requestURL, (error, data) => {
				if (error) {
					console.log(error);
				}
				clearTabContent(accessoryTabContent);
				console.log(data);
				const newContent = createHTML(data);
				accessoryTabContent.append(newContent);
			});
			break;
		case 'OutdoorAccessories':
			console.log('outdoor accessories');
			requestURL = 'http://www.affordablequalitylighting.com/template/outdoorAccessories.json';
			getJSON(requestURL, (error, data) => {
				clearTabContent(accessoryTabContent);
				console.log(data);

				const newContent = createHTML(data);
				console.log(newContent);
				accessoryTabContent.append(newContent);
			});
			break;
		case '120V4FluorescentHousings':
			requestURL = 'https://www.affordablequalitylighting.com/dav/template/120V4FluorescentHousings.json';
			getJSON(requestURL, (error, data) => {
				clearTabContent(accessoryTabContent);
				console.log(data);
				const newContent = createHTML(data);
				console.log(newContent);
				accessoryTabContent.append(newContent);
			});
			break;
		case '120V4FluorescentTrim':
			requestURL = 'http://www.affordablequalitylighting.com/template/120V4FluorescentTrims.json';
			getJSON(requestURL, (error, data) => {
				clearTabContent(accessoryTabContent);
				const newContent = createHTML(data);
				accessoryTabContent.append(newContent);
			});
			break;
		case '120V4Housing':
			console.log('120V 4 Housing');
			requestURL = 'http://www.affordablequalitylighting.com/template/120V4Housing.json';
			getJSON(requestURL, (error, data) => {
				clearTabContent(accessoryTabContent);
				const newContent = createHTML(data);
				accessoryTabContent.append(newContent);
			});
			break;
		case '120V5Housing':
			requestURL = 'http://www.affordablequalitylighting.com/template/120V5Housing.json';
			getJSON(requestURL, (error, data) => {
				clearTabContent(accessoryTabContent);
				const newContent = createHTML(data);
				accessoryTabContent.append(newContent);
			});
			break;
		case '120V6FluorescentHousing':
			requestURL = 'http://www.affordablequalitylighting.com/template/120V6FluorescentHousing.json';
			getJSON(requestURL, (error, data) => {
				clearTabContent(accessoryTabContent);
				const newContent = createHTML(data);
				accessoryTabContent.append(newContent);
			});
			break;
		case '120V6FluorescentTrim':
			requestURL = 'http://www.affordablequalitylighting.com/template/120V6FluorescentTrim.json';
			getJSON(requestURL, (error, data) => {
				clearTabContent(accessoryTabContent);
				const newContent = createHTML(data);
				accessoryTabContent.append(newContent);
			});
			break;
		case '120V6Housing':
			requestURL = 'http://www.affordablequalitylighting.com/template/120V6Housing.json';
			getJSON(requestURL, (error, data) => {
				clearTabContent(accessoryTabContent);
				const newContent = createHTML(data);
				accessoryTabContent.append(newContent);
			});
			break;
		case '120V6SlopedHousing':
			requestURL = 'http://www.affordablequalitylighting.com/template/120V6SlopedHousing.json';
			getJSON(requestURL, (error, data) => {
				clearTabContent(accessoryTabContent);
				const newContent = createHTML(data);
				accessoryTabContent.append(newContent);
			});
			break;
		case '120V6SlopedTrim':
			requestURL = 'http://www.affordablequalitylighting.com/template/120V6SlopedTrim.json';
			getJSON(requestURL, (error, data) => {
				clearTabContent(accessoryTabContent);
				const newContent = createHTML(data);
				accessoryTabContent.append(newContent);
			});
			break;
		case '120V6Trim':
			requestURL = 'http://www.affordablequalitylighting.com/template/120V6Trim.json';
			getJSON(requestURL, (error, data) => {
				clearTabContent(accessoryTabContent);
				const newContent = createHTML(data);
				accessoryTabContent.append(newContent);
			});
			break;

		default:
			console.log('no accessories');
	}
}
<|endoftext|>