<commit_before>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2022 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

var CanvasPool = require('../display/canvas/CanvasPool');
var Class = require('../utils/Class');
var IsSizePowerOfTwo = require('../math/pow2/IsSizePowerOfTwo');
var ScaleModes = require('../renderer/ScaleModes');

/**
 * @classdesc
 * A Texture Source is the encapsulation of the actual source data for a Texture.
 *
 * This is typically an Image Element, loaded from the file system or network, a Canvas Element or a Video Element.
 *
 * A Texture can contain multiple Texture Sources, which only happens when a multi-atlas is loaded.
 *
 * @class TextureSource
 * @memberof Phaser.Textures
 * @constructor
 * @since 3.0.0
 *
 * @param {Phaser.Textures.Texture} texture - The Texture this TextureSource belongs to.
 * @param {(HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|Phaser.GameObjects.RenderTexture|WebGLTexture|Phaser.Types.Textures.CompressedTextureData|Phaser.Textures.DynamicTexture)} source - The source image data.
 * @param {number} [width] - Optional width of the source image. If not given it's derived from the source itself.
 * @param {number} [height] - Optional height of the source image. If not given it's derived from the source itself.
 * @param {boolean} [flipY=false] - Sets the `UNPACK_FLIP_Y_WEBGL` flag the WebGL Texture uses during upload.
 */
var TextureSource = new Class({

    initialize:

    function TextureSource (texture, source, width, height, flipY)
    {
        if (flipY === undefined) { flipY = false; }

        var game = texture.manager.game;

        /**
         * A reference to the Canvas or WebGL Renderer.
         *
         * @name Phaser.Textures.TextureSource#renderer
         * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)}
         * @since 3.7.0
         */
        this.renderer = game.renderer;

        /**
         * The Texture this TextureSource instance belongs to.
         *
         * @name Phaser.Textures.TextureSource#texture
         * @type {Phaser.Textures.Texture}
         * @since 3.0.0
         */
        this.texture = texture;

        /**
         * The source of the image data.
         *
         * This is either an Image Element, a Canvas Element, a Video Element, a RenderTexture or a WebGLTexture.
         *
         * In Phaser 3.60 and above it can also be a Compressed Texture data object.
         *
         * @name Phaser.Textures.TextureSource#source
         * @type {(HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|Phaser.GameObjects.RenderTexture|WebGLTexture|Phaser.Types.Textures.CompressedTextureData|Phaser.Textures.DynamicTexture)}
         * @since 3.12.0
         */
        this.source = source;

        /**
         * The image data.
         *
         * This is either an Image element, Canvas element or a Video Element.
         *
         * @name Phaser.Textures.TextureSource#image
         * @type {(HTMLImageElement|HTMLCanvasElement|HTMLVideoElement)}
         * @since 3.0.0
         */
        this.image = (source.compressed) ? null : source;

        /**
         * Holds the compressed textured algorithm, or `null` if it's not a compressed texture.
         *
         * Prior to Phaser 3.60 this value always held `null`.
         *
         * @name Phaser.Textures.TextureSource#compressionAlgorithm
         * @type {number}
         * @default null
         * @since 3.0.0
         */
        this.compressionAlgorithm = (source.compressed) ? source.format : null;

        /**
         * The resolution of the source image.
         *
         * @name Phaser.Textures.TextureSource#resolution
         * @type {number}
         * @default 1
         * @since 3.0.0
         */
        this.resolution = 1;

        /**
         * The width of the source image. If not specified in the constructor it will check
         * the `naturalWidth` and then `width` properties of the source image.
         *
         * @name Phaser.Textures.TextureSource#width
         * @type {number}
         * @since 3.0.0
         */
        this.width = width || source.naturalWidth || source.videoWidth || source.width || 0;

        /**
         * The height of the source image. If not specified in the constructor it will check
         * the `naturalHeight` and then `height` properties of the source image.
         *
         * @name Phaser.Textures.TextureSource#height
         * @type {number}
         * @since 3.0.0
         */
        this.height = height || source.naturalHeight || source.videoHeight || source.height || 0;

        /**
         * The Scale Mode the image will use when rendering.
         * Either Linear or Nearest.
         *
         * @name Phaser.Textures.TextureSource#scaleMode
         * @type {number}
         * @since 3.0.0
         */
        this.scaleMode = ScaleModes.DEFAULT;

        /**
         * Is the source image a Canvas Element?
         *
         * @name Phaser.Textures.TextureSource#isCanvas
         * @type {boolean}
         * @since 3.0.0
         */
        this.isCanvas = (source instanceof HTMLCanvasElement);

        /**
         * Is the source image a Video Element?
         *
         * @name Phaser.Textures.TextureSource#isVideo
         * @type {boolean}
         * @since 3.20.0
         */
        this.isVideo = (window.hasOwnProperty('HTMLVideoElement') && source instanceof HTMLVideoElement);

        /**
         * Is the source image a Render Texture?
         *
         * @name Phaser.Textures.TextureSource#isRenderTexture
         * @type {boolean}
         * @since 3.12.0
         */
        this.isRenderTexture = (source.type === 'RenderTexture' || source.type === 'DynamicTexture');

        /**
         * Is the source image a WebGLTexture?
         *
         * @name Phaser.Textures.TextureSource#isGLTexture
         * @type {boolean}
         * @since 3.19.0
         */
        this.isGLTexture = (window.hasOwnProperty('WebGLTexture') && source instanceof WebGLTexture);

        /**
         * Are the source image dimensions a power of two?
         *
         * @name Phaser.Textures.TextureSource#isPowerOf2
         * @type {boolean}
         * @since 3.0.0
         */
        this.isPowerOf2 = IsSizePowerOfTwo(this.width, this.height);

        /**
         * The WebGL Texture of the source image. If this TextureSource is driven from a WebGLTexture
         * already, then this is a reference to that WebGLTexture.
         *
         * @name Phaser.Textures.TextureSource#glTexture
         * @type {?WebGLTexture}
         * @default null
         * @since 3.0.0
         */
        this.glTexture = null;

        /**
         * Sets the `UNPACK_FLIP_Y_WEBGL` flag the WebGL Texture uses during upload.
         *
         * @name Phaser.Textures.TextureSource#flipY
         * @type {boolean}
         * @since 3.20.0
         */
        this.flipY = flipY;

        this.init(game);
    },

    /**
     * Creates a WebGL Texture, if required, and sets the Texture filter mode.
     *
     * @method Phaser.Textures.TextureSource#init
     * @since 3.0.0
     *
     * @param {Phaser.Game} game - A reference to the Phaser Game instance.
     */
    init: function (game)
    {
        var renderer = this.renderer;

        if (renderer)
        {
            var source = this.source;

            if (renderer.gl)
            {
                var image = this.image;
                var flipY = this.flipY;
                var width = this.width;
                var height = this.height;
                var scaleMode = this.scaleMode;

                if (this.isCanvas)
                {
                    this.glTexture = renderer.createCanvasTexture(image, false, flipY);
                }
                else if (this.isVideo)
                {
                    this.glTexture = renderer.createVideoTexture(image, false, flipY);
                }
                else if (this.isRenderTexture)
                {
                    this.glTexture = renderer.createTextureFromSource(null, width, height, scaleMode);
                }
                else if (this.isGLTexture)
                {
                    this.glTexture = source;
                }
                else if (this.compressionAlgorithm)
                {
                    this.glTexture = renderer.createTextureFromSource(source);
                }
                else
                {
                    this.glTexture = renderer.createTextureFromSource(image, width, height, scaleMode);
                }
            }
            else if (this.isRenderTexture)
            {
                this.image = source.canvas;
            }
        }

        if (!game.config.antialias)
        {
            this.setFilter(1);
        }
    },

    /**
     * Sets the Filter Mode for this Texture.
     *
     * The mode can be either Linear, the default, or Nearest.
     *
     * For pixel-art you should use Nearest.
     *
     * @method Phaser.Textures.TextureSource#setFilter
     * @since 3.0.0
     *
     * @param {Phaser.Textures.FilterMode} filterMode - The Filter Mode.
     */
    setFilter: function (filterMode)
    {
        if (this.renderer.gl)
        {
            this.renderer.setTextureFilter(this.glTexture, filterMode);
        }

        this.scaleMode = filterMode;
    },

    /**
     * Sets the `UNPACK_FLIP_Y_WEBGL` flag for the WebGL Texture during texture upload.
     *
     * @method Phaser.Textures.TextureSource#setFlipY
     * @since 3.20.0
     *
     * @param {boolean} [value=true] - Should the WebGL Texture be flipped on the Y axis on texture upload or not?
     */
    setFlipY: function (value)
    {
        if (value === undefined) { value = true; }

        this.flipY = value;

        return this;
    },

    /**
     * If this TextureSource is backed by a Canvas and is running under WebGL,
     * it updates the WebGLTexture using the canvas data.
     *
     * @method Phaser.Textures.TextureSource#update
     * @since 3.7.0
     */
    update: function ()
    {
        var gl = this.renderer.gl;

        if (gl && this.isCanvas)
        {
            this.glTexture = this.renderer.updateCanvasTexture(this.image, this.glTexture, this.flipY);
        }
        else if (gl && this.isVideo)
        {
            this.glTexture = this.renderer.updateVideoTexture(this.image, this.glTexture, this.flipY);
        }
    },

    /**
     * Destroys this Texture Source and nulls the references.
     *
     * @method Phaser.Textures.TextureSource#destroy
     * @since 3.0.0
     */
    destroy: function ()
    {
        if (this.glTexture)
        {
            this.renderer.deleteTexture(this.glTexture, true);
        }

        if (this.isCanvas)
        {
            CanvasPool.remove(this.image);
        }

        this.renderer = null;
        this.texture = null;
        this.source = null;
        this.image = null;
        this.glTexture = null;
    }

});

module.exports = TextureSource;
<commit_msg>Update TextureSource.js<commit_after>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2022 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

var CanvasPool = require('../display/canvas/CanvasPool');
var Class = require('../utils/Class');
var IsSizePowerOfTwo = require('../math/pow2/IsSizePowerOfTwo');
var ScaleModes = require('../renderer/ScaleModes');

/**
 * @classdesc
 * A Texture Source is the encapsulation of the actual source data for a Texture.
 *
 * This is typically an Image Element, loaded from the file system or network, a Canvas Element or a Video Element.
 *
 * A Texture can contain multiple Texture Sources, which only happens when a multi-atlas is loaded.
 *
 * @class TextureSource
 * @memberof Phaser.Textures
 * @constructor
 * @since 3.0.0
 *
 * @param {Phaser.Textures.Texture} texture - The Texture this TextureSource belongs to.
 * @param {(HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|Phaser.GameObjects.RenderTexture|WebGLTexture|Phaser.Types.Textures.CompressedTextureData|Phaser.Textures.DynamicTexture)} source - The source image data.
 * @param {number} [width] - Optional width of the source image. If not given it's derived from the source itself.
 * @param {number} [height] - Optional height of the source image. If not given it's derived from the source itself.
 * @param {boolean} [flipY=false] - Sets the `UNPACK_FLIP_Y_WEBGL` flag the WebGL Texture uses during upload.
 */
var TextureSource = new Class({

    initialize:

    function TextureSource (texture, source, width, height, flipY)
    {
        if (flipY === undefined) { flipY = false; }

        var game = texture.manager.game;

        /**
         * A reference to the Canvas or WebGL Renderer.
         *
         * @name Phaser.Textures.TextureSource#renderer
         * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)}
         * @since 3.7.0
         */
        this.renderer = game.renderer;

        /**
         * The Texture this TextureSource instance belongs to.
         *
         * @name Phaser.Textures.TextureSource#texture
         * @type {Phaser.Textures.Texture}
         * @since 3.0.0
         */
        this.texture = texture;

        /**
         * The source of the image data.
         *
         * This is either an Image Element, a Canvas Element, a Video Element, a RenderTexture or a WebGLTexture.
         *
         * In Phaser 3.60 and above it can also be a Compressed Texture data object.
         *
         * @name Phaser.Textures.TextureSource#source
         * @type {(HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|Phaser.GameObjects.RenderTexture|WebGLTexture|Phaser.Types.Textures.CompressedTextureData|Phaser.Textures.DynamicTexture)}
         * @since 3.12.0
         */
        this.source = source;

        /**
         * The image data.
         *
         * This is either an Image element, Canvas element or a Video Element.
         *
         * @name Phaser.Textures.TextureSource#image
         * @type {(HTMLImageElement|HTMLCanvasElement|HTMLVideoElement)}
         * @since 3.0.0
         */
        this.image = (source.compressed) ? null : source;

        /**
         * Holds the compressed textured algorithm, or `null` if it's not a compressed texture.
         *
         * Prior to Phaser 3.60 this value always held `null`.
         *
         * @name Phaser.Textures.TextureSource#compressionAlgorithm
         * @type {number}
         * @default null
         * @since 3.0.0
         */
        this.compressionAlgorithm = (source.compressed) ? source.format : null;

        /**
         * The resolution of the source image.
         *
         * @name Phaser.Textures.TextureSource#resolution
         * @type {number}
         * @default 1
         * @since 3.0.0
         */
        this.resolution = 1;

        /**
         * The width of the source image. If not specified in the constructor it will check
         * the `naturalWidth` and then `width` properties of the source image.
         *
         * @name Phaser.Textures.TextureSource#width
         * @type {number}
         * @since 3.0.0
         */
        this.width = width || source.naturalWidth || source.videoWidth || source.width || 0;

        /**
         * The height of the source image. If not specified in the constructor it will check
         * the `naturalHeight` and then `height` properties of the source image.
         *
         * @name Phaser.Textures.TextureSource#height
         * @type {number}
         * @since 3.0.0
         */
        this.height = height || source.naturalHeight || source.videoHeight || source.height || 0;

        /**
         * The Scale Mode the image will use when rendering.
         * Either Linear or Nearest.
         *
         * @name Phaser.Textures.TextureSource#scaleMode
         * @type {number}
         * @since 3.0.0
         */
        this.scaleMode = ScaleModes.DEFAULT;

        /**
         * Is the source image a Canvas Element?
         *
         * @name Phaser.Textures.TextureSource#isCanvas
         * @type {boolean}
         * @since 3.0.0
         */
        this.isCanvas = (source instanceof HTMLCanvasElement);

        /**
         * Is the source image a Video Element?
         *
         * @name Phaser.Textures.TextureSource#isVideo
         * @type {boolean}
         * @since 3.20.0
         */
        this.isVideo = (window.hasOwnProperty('HTMLVideoElement') && source instanceof HTMLVideoElement);

        /**
         * Is the source image a Render Texture?
         *
         * @name Phaser.Textures.TextureSource#isRenderTexture
         * @type {boolean}
         * @since 3.12.0
         */
        this.isRenderTexture = (source.type === 'RenderTexture' || source.type === 'DynamicTexture');

        /**
         * Is the source image a WebGLTexture?
         *
         * @name Phaser.Textures.TextureSource#isGLTexture
         * @type {boolean}
         * @since 3.19.0
         */
        this.isGLTexture = (window.hasOwnProperty('WebGLTexture') && source instanceof WebGLTexture);

        /**
         * Are the source image dimensions a power of two?
         *
         * @name Phaser.Textures.TextureSource#isPowerOf2
         * @type {boolean}
         * @since 3.0.0
         */
        this.isPowerOf2 = IsSizePowerOfTwo(this.width, this.height);

        /**
         * The WebGL Texture of the source image. If this TextureSource is driven from a WebGLTexture
         * already, then this is a reference to that WebGLTexture.
         *
         * @name Phaser.Textures.TextureSource#glTexture
         * @type {?WebGLTexture}
         * @default null
         * @since 3.0.0
         */
        this.glTexture = null;

        /**
         * Sets the `UNPACK_FLIP_Y_WEBGL` flag the WebGL Texture uses during upload.
         *
         * @name Phaser.Textures.TextureSource#flipY
         * @type {boolean}
         * @since 3.20.0
         */
        this.flipY = flipY;

        this.init(game);
    },

    /**
     * Creates a WebGL Texture, if required, and sets the Texture filter mode.
     *
     * @method Phaser.Textures.TextureSource#init
     * @since 3.0.0
     *
     * @param {Phaser.Game} game - A reference to the Phaser Game instance.
     */
    init: function (game)
    {
        var renderer = this.renderer;

        if (renderer)
        {
            var source = this.source;

            if (renderer.gl)
            {
                var image = this.image;
                var flipY = this.flipY;
                var width = this.width;
                var height = this.height;
                var scaleMode = this.scaleMode;

                if (this.isCanvas)
                {
                    this.glTexture = renderer.createCanvasTexture(image, false, flipY);
                }
                else if (this.isVideo)
                {
                    this.glTexture = renderer.createVideoTexture(image, false, flipY);
                }
                else if (this.isRenderTexture)
                {
                    this.glTexture = renderer.createTextureFromSource(null, width, height, scaleMode);
                }
                else if (this.isGLTexture)
                {
                    this.glTexture = source;
                }
                else if (this.compressionAlgorithm)
                {
                    this.glTexture = renderer.createTextureFromSource(source);
                }
                else
                {
                    this.glTexture = renderer.createTextureFromSource(image, width, height, scaleMode);
                }
            }
            else if (this.isRenderTexture)
            {
                this.image = source.canvas;
            }
        }

        if (!game.config.antialias)
        {
            this.setFilter(1);
        }
    },

    /**
     * Sets the Filter Mode for this Texture.
     *
     * The mode can be either Linear, the default, or Nearest.
     *
     * For pixel-art you should use Nearest.
     *
     * @method Phaser.Textures.TextureSource#setFilter
     * @since 3.0.0
     *
     * @param {Phaser.Textures.FilterMode} filterMode - The Filter Mode.
     */
    setFilter: function (filterMode)
    {
        if (this.renderer.gl)
        {
            this.renderer.setTextureFilter(this.glTexture, filterMode);
        }

        this.scaleMode = filterMode;
    },

    /**
     * Sets the `UNPACK_FLIP_Y_WEBGL` flag for the WebGL Texture during texture upload.
     *
     * @method Phaser.Textures.TextureSource#setFlipY
     * @since 3.20.0
     *
     * @param {boolean} [value=true] - Should the WebGL Texture be flipped on the Y axis on texture upload or not?
     */
    setFlipY: function (value)
    {
        if (value === undefined) { value = true; }

        this.flipY = value;

        return this;
    },

    /**
     * If this TextureSource is backed by a Canvas and is running under WebGL,
     * it updates the WebGLTexture using the canvas data.
     *
     * @method Phaser.Textures.TextureSource#update
     * @since 3.7.0
     */
    update: function ()
    {
        var renderer = this.renderer;
        var image = this.image;
        var flipY = this.flipY;
        var gl = renderer.gl;

        if (gl && this.isCanvas)
        {
            this.glTexture = renderer.updateCanvasTexture(image, this.glTexture, flipY);
        }
        else if (gl && this.isVideo)
        {
            this.glTexture = renderer.updateVideoTexture(image, this.glTexture, flipY);
        }
    },

    /**
     * Destroys this Texture Source and nulls the references.
     *
     * @method Phaser.Textures.TextureSource#destroy
     * @since 3.0.0
     */
    destroy: function ()
    {
        if (this.glTexture)
        {
            this.renderer.deleteTexture(this.glTexture, true);
        }

        if (this.isCanvas)
        {
            CanvasPool.remove(this.image);
        }

        this.renderer = null;
        this.texture = null;
        this.source = null;
        this.image = null;
        this.glTexture = null;
    }

});

module.exports = TextureSource;
<|endoftext|>


<commit_before>'use strict';

// Declare app level module with routes
var app = angular.module('fabLab', [], function($routeProvider) {
    $routeProvider.when('/',
        {
            templateUrl: 'partials/main.html',
            controller: MainCtrl
        });

    $routeProvider.when('/about',
        {
            templateUrl: 'partials/about.html'
        });

    $routeProvider.when('/:machine',
        {
            templateUrl: 'partials/details.html',
            controller: MachineCtrl
        });

    $routeProvider.otherwise(
        {
            redirectTo: '/'
        });
});<commit_msg>added funtions for checking validity of part details and to reset the current parts<commit_after>'use strict';

// Declare app level module with routes
var app = angular.module('fabLab', [], function($routeProvider) {
        $routeProvider.when('/',
            {
                templateUrl: 'partials/main.html',
                controller: MainCtrl
            });

        $routeProvider.when('/about',
            {
                templateUrl: 'partials/about.html'
            });

        $routeProvider.when('/:machine',
            {
                templateUrl: 'partials/details.html',
                controller: MachineCtrl
            });

        $routeProvider.otherwise(
            {
                redirectTo: '/'
            });
    }),
    alert = '
Uh-oh! You missed # part$!
';

function checkSubmit(){
    var parts = $('.part-group'),
        partsLength = parts.length,
        filledPartsLength = parts.has('.ui-state-highlight').length,
        partAlert = '',
        numCorrect = 0,
        percent = 0,
        cssClass = '',
        bad = [':O', ':(', '(O.O)', 'ಠ╭╮ಠ', 'ರ_ರ', 'you should probably try again'],
        medium = ['maybe next time you\'ll get it'],
        good = [':)', '(^∇^)', '◕‿◕', '☺', 'very good!'],
        message = '';

    if ($('.alert-error')) {
        $('.alert-error').remove();
    }

    if (filledPartsLength < partsLength) {
        //Fill in the number of unfilled parts and add an 's' if the number is not 1
        partAlert = $(alert.replace('#', (partsLength - filledPartsLength)).replace('$', (partsLength - filledPartsLength) !== 1 ? 's' : ''));

        $('.details').prepend(partAlert);
        return;
    }

    for (var i = 0, currPart; i < partsLength; i++) {
        currPart = parts.eq(i);

        if (currPart.data('part-id') === currPart.children().eq(0).data('part-id')) {
            numCorrect++;
        }
    }

    percent = (numCorrect / partsLength) * 100;

    switch(true) {
    // [0, 60] is red
    case (percent >= 0 && percent <= 60):
        cssClass = 'text-error';
        message = bad[Math.floor(Math.random() * bad.length)];
        break;

    // (60, 90) is yellow
    case (percent > 60 && percent < 90):
        cssClass = 'text-warning';
        message = medium[Math.floor(Math.random() * medium.length)];
        break;

    // [90, 100] is green
    default:
        cssClass = 'text-success';
        message = good[Math.floor(Math.random() * good.length)];
    }

    //console.log('correct:', numCorrect, 'total:', partsLength);

    $('#check-parts').find('.score').removeClass().addClass('score ' + cssClass).html('You got ' + numCorrect + ' out of ' + partsLength + ' correct, that\'s ' + percent.toFixed(2) + '%... ' + message);
}

function resetParts() {
    var partsList = $('.parts-list'),
        partDrops = $('.part-drop');

    if ($('.alert-error')) {
        $('.alert-error').remove();
    }

    $('#check-parts').find('.score').html('').removeClass().addClass('score');

    partsList.children().each(function(){
        $(this).data('dropped', false).draggable('enable').removeClass('ui-state-disabled');
    });

    partDrops.each(function(){
        $(this).removeData('part-id').text('').removeClass('ui-state-highlight');
    });

    //console.log('machine reset!');
}

<|endoftext|>


<commit_before>import parser from './parser/javascript.js';
import Snap from 'snapsvg';
import Q from 'q';

export default class Regexper {
  constructor(root) {
    this.root = root;
    this.form = root.querySelector('#regexp-form');
    this.field = root.querySelector('#regexp-input');
    this.error = root.querySelector('#error');
    this.permalink = root.querySelector('a[data-glyph="link-intact"]');
    this.download = root.querySelector('a[data-glyph="data-transfer-download"]');
    this.svg = root.querySelector('#regexp-render svg');

    this.padding = 10;
    this.snap = Snap(this.svg);
  }

  keypressListener(event) {
    if (event.shiftKey && event.keyCode === 13) {
      event.preventDefault();
      this.form.dispatchEvent(new Event('submit'));
    }
  }

  submitListener(event) {
    event.preventDefault();

    location.hash = this.field.value;
  }

  hashchangeListener() {
    var expression = decodeURIComponent(location.hash.slice(1));

    if (expression !== '') {
      this.field.value = expression;

      this.setState('is-loading');

      this.renderRegexp(expression.replace(/[\r\n]/g, ''))
        .then((() => {
          this.setState('has-results');
          this.updateLinks();
        }).bind(this), this.showError.bind(this));
    }
  }

  bindListeners() {
    this.field.addEventListener('keypress', this.keypressListener.bind(this));

    this.form.addEventListener('submit', this.submitListener.bind(this));

    window.addEventListener('hashchange', this.hashchangeListener.bind(this));
  }

  setState(state) {
    var classList = this.root.classList;

    classList.remove('is-loading', 'has-results', 'has-error');
    classList.add(state);
  }

  showError(message) {
    this.setState('has-error');
    this.error.innerHTML = '';
    this.error.appendChild(document.createTextNode(message));
  }

  updateLinks() {
    var blob, url;

    blob = new Blob([svg.outerHTML], { type: 'image/svg+xml' });
    url = URL.createObjectURL(blob);

    this.download.setAttribute('href', url);
    this.permalink.setAttribute('href', location);
  }

  renderSvg(snap, expression) {
    var result;

    snap.selectAll('g').remove();

    result = parser.parse(expression);
    result.container = snap.group();
    result.render();

    return result;
  }

  positionSvg(snap, parsed) {
    var box;

    parsed.position();

    box = parsed.container.getBBox();
    parsed.container.transform(Snap.matrix()
      .translate(this.padding - box.x, this.padding - box.y));
    snap.attr({
      width: box.width + this.padding * 2,
      height: box.height + this.padding * 2
    });
  }

  renderRegexp(expression) {
    var padding = this.padding,
        snap = Snap(this.svg),
        promise;

    promise = Q.promise(((resolve, reject, notify) => {
      resolve(this.renderSvg(snap, expression));
    }).bind(this));

    promise.then(this.positionSvg.bind(this, snap));

    return promise;
  }
}
<commit_msg>Refactoring rendering code to allow the loader to show<commit_after>import parser from './parser/javascript.js';
import Snap from 'snapsvg';
import Q from 'q';

export default class Regexper {
  constructor(root) {
    this.root = root;
    this.form = root.querySelector('#regexp-form');
    this.field = root.querySelector('#regexp-input');
    this.error = root.querySelector('#error');
    this.permalink = root.querySelector('a[data-glyph="link-intact"]');
    this.download = root.querySelector('a[data-glyph="data-transfer-download"]');
    this.svg = root.querySelector('#regexp-render svg');

    this.padding = 10;
    this.snap = Snap(this.svg);
  }

  keypressListener(event) {
    if (event.shiftKey && event.keyCode === 13) {
      event.preventDefault();
      this.form.dispatchEvent(new Event('submit'));
    }
  }

  submitListener(event) {
    event.preventDefault();

    location.hash = this.field.value;
  }

  hashchangeListener() {
    var expression = decodeURIComponent(location.hash.slice(1));

    if (expression !== '') {
      this.field.value = expression;

      this.setState('is-loading');

      this.renderRegexp(expression.replace(/[\r\n]/g, ''))
        .then((() => {
          this.setState('has-results');
          this.updateLinks();
        }).bind(this), this.showError.bind(this));
    }
  }

  bindListeners() {
    this.field.addEventListener('keypress', this.keypressListener.bind(this));

    this.form.addEventListener('submit', this.submitListener.bind(this));

    window.addEventListener('hashchange', this.hashchangeListener.bind(this));
  }

  setState(state) {
    var classList = this.root.classList;

    classList.remove('is-loading', 'has-results', 'has-error');
    classList.add(state);
  }

  showError(message) {
    this.setState('has-error');
    this.error.innerHTML = '';
    this.error.appendChild(document.createTextNode(message));
  }

  updateLinks() {
    var blob, url;

    blob = new Blob([this.svg.outerHTML], { type: 'image/svg+xml' });
    url = URL.createObjectURL(blob);

    this.download.setAttribute('href', url);
    this.permalink.setAttribute('href', location);
  }

  renderSvg(snap, expression) {
    var deferred = Q.defer(),
        result;

    snap.selectAll('g').remove();

    setTimeout(() => {
      try {
        result = parser.parse(expression);
      }
      catch(e) {
        deferred.reject(e);
      }

      if (result) {
        result.container = snap.group();
        result.render();
        deferred.resolve(result);
      }
    });

    return deferred.promise;
  }

  positionSvg(snap, parsed) {
    var box;

    parsed.position();

    box = parsed.container.getBBox();
    parsed.container.transform(Snap.matrix()
      .translate(this.padding - box.x, this.padding - box.y));
    snap.attr({
      width: box.width + this.padding * 2,
      height: box.height + this.padding * 2
    });
  }

  renderRegexp(expression) {
    var padding = this.padding,
        snap = Snap(this.svg);

    return this.renderSvg(snap, expression)
      .then(this.positionSvg.bind(this, snap));
  }
}
<|endoftext|>


<commit_before>window.App = {};
App.refreshTime = 2000;
App.oldStats = {};
App.newStats = {};

App.getStats = function(){
	$.getJSON("/stats", function(data){
		App.oldStats = App.newStats;
		App.newStats = data;
	})
}

App.calcHitRatio = function(){
	hitRatio = (App.newStats.cache_hit.value*100)/App.newStats.client_req.value;
	return hitRatio;
}

App.updateHitRatio = function(){
	$("#hit-ratio").html("
"+App.calcHitRatio()+"
");
}

App.updateData = function(){
	App.getStats();
	App.updateHitRatio();
}

$(function(){

	setInterval(App.updateData,App.refreshTime);

});
<commit_msg>first commit<commit_after>window.App = {};
App.refreshTime = 2000;
App.oldStats = {};
App.newStats = {};

App.getStats = function(){
	$.getJSON("/stats", function(data){
		App.oldStats = App.newStats;
		App.newStats = data;
	})
}

App.calcHitRatio = function(){
	delta_client_req = App.newStats.client_req.value - App.oldStats.client_req.value;
	delta_cache_hit = App.newStats.cache_hit.value - App.oldStats.cache_hit.value;
	hitRatio = (delta_cache_hit*100)/delta_client_req.value;
	return hitRatio;
}

App.updateHitRatio = function(){
	$("#hit-ratio").html("
"+App.calcHitRatio()+"
");
}

App.updateData = function(){
	App.getStats();
	App.updateHitRatio();
}

$(function(){

	setInterval(App.updateData,App.refreshTime);

});
<|endoftext|>


<commit_before>$(document).ready(function(){
	$('.card').addClass('onload');
});<commit_msg>some sort of fade<commit_after>$(document).ready(function(){
	setTimeout(function() {
    $('.card').addClass('onload');
  }, 100);
});
<|endoftext|>


<commit_before>var data = JSON.parse(document.getElementById('test').innerHTML);
var songsWrapper  = document.getElementById('songs-wrapper');
var audioElement = document.getElementById('player');
var queueList = document.getElementById('queue-list');

var filterAddr = function(obj) {
    if(obj.addr == '15iuRwGSiUTknHJtoP4CJ3dHUr8T4vQuaE') {
        return true;
    }
    else {
        return false;
    }
}

var handleSong = function(blockChainData) {
    var dataArray = blockChainData.x.out.filter(filterAddr);
    var value = dataArray[0].value;
    var id = value.toString().slice(-3);

    var songElement = document.querySelector('[data-song-id="' + id +'"]');
    addToQueue(songElement);
}

var addToQueue = function(song) {
    var emptyList = queueList.children.length == 0;
    var item = document.createElement('a');
    item.className = 'mdl-navigation__link';

    item.setAttribute('data-url', song.getAttribute('data-song-url'));
    item.textContent = song.getAttribute('title');

    queueList.appendChild(item);

    if(emptyList) {
        playNext();
    }
}

var removePlayed = function() {
    if (queueList.children.length !== 0) {
        queueList.removeChild(queueList.children[0]);
    }
}

var playNextOrShuffle = function() {
    if (queueList.children.length == 0) {
        playShuffle();
    }
    else {
        playNext();
    }
}

var playShuffle = function() {
    var rand = Math.floor(Math.random() * data.length);

    audioElement.src = data[rand].url;
    audioElement.oncanplay = function() {
        setTimeout(function() {
            audioElement.play()
        }, 1000);
    }
}

var playNext = function() {
    audioElement.src = queueList.children[0].getAttribute('data-url');
    audioElement.play();
}

data.map(function(songData, index) {
    var songWrap = document.createElement('div')
    var song  = document.createElement('div');
    var header = document.createElement('div');
    var title = document.createElement('h2');
    var qr = document.createElement('div');
    var meta = document.createElement('p');

    songWrap.className = 'mdl-cell mdl-cell--3-col'
    song.className = 'mdl-card mdl-shadow--2dp';
    header.className = 'mdl-card__title';
    title.className = 'mdl-card__title-text';
    qr.className = 'mdl-card__media';
    meta.className = 'mdl-card__supporting-text';

    var count = index + 1;
    var songId = count.toString(10);

    if(songId.length < 2) {
        songId = '0' + songId;
    }
    if(songId.length < 3) {
        songId = '0' + songId;
    }

    title.textContent = songData.title + ' - ' + songData.artist;
    song.setAttribute('title', songData.title + ' - ' + songData.artist);
    song.setAttribute('data-song-id', songId);
    song.setAttribute('data-song-url', songData.url);
    new QRCode(qr, {
        text: 'bitcoin:15iuRwGSiUTknHJtoP4CJ3dHUr8T4vQuaE?amount=0.00010' + songId + '&message=Jukebox',
        correctLevel : QRCode.CorrectLevel.L
    });
    meta.textContent = 'Duration: ' + songData.duration;

    header.appendChild(title);
    song.appendChild(header);
    song.appendChild(qr);
    song.appendChild(meta);
    songWrap.appendChild(song);

    songsWrapper.appendChild(songWrap);
});

playNextOrShuffle();

audioElement.addEventListener('ended', function() {
    removePlayed();
    playNextOrShuffle();
}, false);

var ws = new WebSocket('wss://ws.blockchain.info/inv');
ws.onopen = function() {
    ws.send(JSON.stringify({'op':'addr_sub', 'addr':'15iuRwGSiUTknHJtoP4CJ3dHUr8T4vQuaE'}))
    ws.onmessage = function(event) {
        console.log(JSON.parse(event.data));
        handleSong(JSON.parse(event.data));
    }
}
<commit_msg>try refreshing websocket<commit_after>var data = JSON.parse(document.getElementById('test').innerHTML);
var songsWrapper  = document.getElementById('songs-wrapper');
var audioElement = document.getElementById('player');
var queueList = document.getElementById('queue-list');

var filterAddr = function(obj) {
    if(obj.addr == '15iuRwGSiUTknHJtoP4CJ3dHUr8T4vQuaE') {
        return true;
    }
    else {
        return false;
    }
}

var handleSong = function(blockChainData) {
    var dataArray = blockChainData.x.out.filter(filterAddr);
    var value = dataArray[0].value;
    var id = value.toString().slice(-3);

    var songElement = document.querySelector('[data-song-id="' + id +'"]');
    addToQueue(songElement);
}

var addToQueue = function(song) {
    var emptyList = queueList.children.length == 0;
    var item = document.createElement('a');
    item.className = 'mdl-navigation__link';

    item.setAttribute('data-url', song.getAttribute('data-song-url'));
    item.textContent = song.getAttribute('title');

    queueList.appendChild(item);

    if(emptyList) {
        playNext();
    }
}

var removePlayed = function() {
    if (queueList.children.length !== 0) {
        queueList.removeChild(queueList.children[0]);
    }
}

var playNextOrShuffle = function() {
    if (queueList.children.length == 0) {
        playShuffle();
    }
    else {
        playNext();
    }
}

var playShuffle = function() {
    var rand = Math.floor(Math.random() * data.length);

    audioElement.src = data[rand].url;
    audioElement.oncanplay = function() {
        setTimeout(function() {
            audioElement.play()
        }, 1000);
    }
}

var playNext = function() {
    audioElement.src = queueList.children[0].getAttribute('data-url');
    audioElement.play();
}

data.map(function(songData, index) {
    var songWrap = document.createElement('div')
    var song  = document.createElement('div');
    var header = document.createElement('div');
    var title = document.createElement('h2');
    var qr = document.createElement('div');
    var meta = document.createElement('p');

    songWrap.className = 'mdl-cell mdl-cell--3-col'
    song.className = 'mdl-card mdl-shadow--2dp';
    header.className = 'mdl-card__title';
    title.className = 'mdl-card__title-text';
    qr.className = 'mdl-card__media';
    meta.className = 'mdl-card__supporting-text';

    var count = index + 1;
    var songId = count.toString(10);

    if(songId.length < 2) {
        songId = '0' + songId;
    }
    if(songId.length < 3) {
        songId = '0' + songId;
    }

    title.textContent = songData.title + ' - ' + songData.artist;
    song.setAttribute('title', songData.title + ' - ' + songData.artist);
    song.setAttribute('data-song-id', songId);
    song.setAttribute('data-song-url', songData.url);
    new QRCode(qr, {
        text: 'bitcoin:15iuRwGSiUTknHJtoP4CJ3dHUr8T4vQuaE?amount=0.00010' + songId + '&message=Jukebox',
        correctLevel : QRCode.CorrectLevel.L
    });
    meta.textContent = 'Duration: ' + songData.duration;

    header.appendChild(title);
    song.appendChild(header);
    song.appendChild(qr);
    song.appendChild(meta);
    songWrap.appendChild(song);

    songsWrapper.appendChild(songWrap);
});

playNextOrShuffle();

audioElement.addEventListener('ended', function() {
    removePlayed();
    playNextOrShuffle();
}, false);

var ws = new WebSocket('wss://ws.blockchain.info/inv');
ws.onopen = function() {
    setInterval(function() {
        ws.send(JSON.stringify({'op':'addr_sub', 'addr':'15iuRwGSiUTknHJtoP4CJ3dHUr8T4vQuaE'}))
    }, 60000);
    ws.onmessage = function(event) {
        console.log(JSON.parse(event.data));
        handleSong(JSON.parse(event.data));
    }
}
<|endoftext|>


<commit_before>
'use strict'

var photoArray; //array of photo objects that carry the path and the vote tally, perhaps the name, too
[{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]

var Photo = function(fileLocation) { //constructor
	this.path = fileLocation;
	this.votes = 1;
	this.index = [];
}

var photo1 = new Photo('img/cat1.jpg');
var photo2 = new Photo('img/cat2.jpg');
var photo3 = new Photo('img/cat3.jpg');
var photo4 = new Photo('img/cat4.jpg');
var photo5 = new Photo('img/cat5.jpg');
var photo6 = new Photo('img/cat6.jpg');
var photo7 = new Photo('img/cat7.jpg');
var photo8 = new Photo('img/cat8.jpg');
var photo9 = new Photo('img/cat9.jpg');
var photo10 = new Photo('img/cat10.jpg');
var photo11= new Photo('img/cat11.jpg');
var photo12 = new Photo('img/cat12.jpg');
var photo13 = new Photo('img/cat13.jpg');
var photo14 = new Photo('img/cat14.jpg');

var Tracker = function() {
	this.leftPhoto
	this.rightPhoto

}

Photo.prototype.highlight = function() {
	var getPhoto = document.getElementById('photos');
	newDiv.id = this.fileLocation;

};

Tracker.prototype.waitingForVote = function() {
	//receive click
	//increment vote count
	//event Listener on each photo
	//highlight()?
	//drawTheChart()?
	//giveUserOptionToVoteAgain()?

};

Tracker.prototype.getRandomInt = function() {
	return Math.floor(Math.random() * (this.Photo);

};

Tracker.prototype.displayPhotos = function() {
	//display random photos
	//prevent same photo displayed for both choices
	//if photo1 === photo2 then re-roll
}

Tracker.prototype.waitingForVote = function() {
	action1()
	action2()
	action3()
}

Tracker.prototype.displayWinner = function() {
	action4()
	action5()
	action6()
}

//some 'document.getElementById' variables to access and manipulate document<commit_msg>ready to turn in<commit_after>
'use strict'

var photoArray; //array of photo objects that carry the path and the vote tally, perhaps the name, too
[{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]

var Photo = function(fileLocation) { //constructor
	this.path = fileLocation;
	this.votes = 1;
	this.index = [];
}

// Hella photos
var photo1 = new Photo('img/cat1.jpg');
var photo2 = new Photo('img/cat2.jpg');
var photo3 = new Photo('img/cat3.jpg');
var photo4 = new Photo('img/cat4.jpg');
var photo5 = new Photo('img/cat5.jpg');
var photo6 = new Photo('img/cat6.jpg');
var photo7 = new Photo('img/cat7.jpg');
var photo8 = new Photo('img/cat8.jpg');
var photo9 = new Photo('img/cat9.jpg');
var photo10 = new Photo('img/cat10.jpg');
var photo11= new Photo('img/cat11.jpg');
var photo12 = new Photo('img/cat12.jpg');
var photo13 = new Photo('img/cat13.jpg');
var photo14 = new Photo('img/cat14.jpg');

var Tracker = function() {
	this.leftPhoto
	this.rightPhoto

}

Photo.prototype.highlight = function() {
	var getPhoto = document.getElementById('photos');
	newDiv.id = this.fileLocation;

};

Tracker.prototype.waitingForVote = function() {
	//receive click
	//increment vote count
	//event Listener on each photo
	//highlight()?
	//drawTheChart()?
	//giveUserOptionToVoteAgain()?

};

Tracker.prototype.getRandomInt = function() {
	return Math.floor(Math.random() * (this.Photo);

};

Tracker.prototype.displayPhotos = function() {
	//display random photos
	//prevent same photo displayed for both choices
	//if photo1 === photo2 then re-roll
}

Tracker.prototype.waitingForVote = function() {
	action1()
	action2()
	action3()
}

Tracker.prototype.displayWinner = function() {
	action4()
	action5()
	action6()
}

//some 'document.getElementById' variables to access and manipulate document<|endoftext|>


<commit_before>var objLinkList = [
            { href: "#blogs", linkText: "Blogs" },
            { href: "#herramientas", linkText: "Herramientas" },
            { href: "#frameworks", linkText: "Frameworks" }
        ];
var objBlogs =  [
    {
        url: "https://css-tricks.com/",
        linkText: "css-tricks",
        text: "Indudablemente una de las webs número uno de consulta para un frontend. Artículos y tutoriales de calidad y un buen número de snippets."
    },
    {
        url: "https://www.smashingmagazine.com/",
        linkText: "Smashing Magazine",
        text: "Todo un referente en el mundo de la web. Código, diseño, mobile, UX ... etc. Publican libros con colecciones de sus artículos más interesantes."
    },
    {
        url: "https://www.sitepoint.com/",
        linkText: "Site Point",
        text: "Artículos meticulosos de gran calidad, podcast, libros y cursos (a veces gratis). También imprescindible."
    },
    {
        url: "https://scotch.io/",
        linkText: "Scotch.io",
        text: "Tutoriales excelentes sobre el mundo frontend y backend javascript. Disponen de cursos free y premium. ¡¡No perdérselo!!"
    },
    {
        url: "https://davidwalsh.name/",
        linkText: "David Walsh Blog",
        text: "log del gurú JavaScript David Walsh. Conviene seguirle y leer sus interesantes artículos. No solo habla de JavaScript, también aborda otras tecnologías web."
    },
    {
        url: "http://alistapart.com/articles",
        linkText: "A List Apart",
        text: "Artículos de todo lo relacionado con la web. Son artículos de una calidad tan extraordinaria que algunos son un referente."
    },
    {
        url: "https://webmasters.googleblog.com/",
        linkText: "Google Webmaster Blog",
        text: "No puede faltar el blog oficial de Google para webmasters."
    },
    {
        url: "http://lea.verou.me/",
        linkText: "Lea Verou",
        text: "La gran Lea Verou. Proyectos, charlas, artículos. Una eminencia en el CSS."
    },
    {
        url: "http://wesbos.com/blog/",
        linkText: "Web Bos",
        text: "Artículos, videos y tutoriales"
    },
    {
        url: "http://www.developerdrive.com/",
        linkText: "Developer Drive",
        text: "Artículos sobre todo tipo de tecnología de desarrollo web."
    },
    {
        url: "http://www.cssportal.com/",
        linkText: "CSS Portal",
        text: "Snippets, generadores y herramientas para desarrollar en CSS."
    },
    {
        url: "http://www.elmaquetadorweb.com/",
        linkText: "El maquetador web",
        text: "Excelente blog mantenido por Javi Luna y Pedro Marín donde nos cuentan muchos trucos en esto del CSS. Me encanta el nombre de maquetador, término en desuso hoy en día.  ;D"
    },
    {
        url: "https://toddmotto.com/",
        linkText: "Todd Motto",
        text: "Artículos y tutoriales sobre JavaScript, Angular y Typescript. Dispone de muy buenos cursos en premium."
    },
    {
        url: "http://valhead.com/blog/",
        linkText: "Val Head Blog",
        text: "Artículos y tutoriales de una especialista en animaciones CSS web."
    },
    {
        url: "https://codyhouse.co/",
        linkText: "Cody House",
        text: "Colecciones gratuitas de snippets de HTML, CSS y JavaScript. También disponen de cursos premium."
    },
    {
        url: "http://www.kylejlarson.com/blog/ ",
        linkText: "kyle J. Larson",
        text: "Buenos consejos para el diseño web."
    },
    {
        url: "http://www.naderdabit.me/#/",
        linkText: "Nader Dabit",
        text: "Tutoriales sobre ReactJS, Angular, NPM ."
    },
    {
        url: "http://mrbool.com/",
        linkText: "Mr. Bool",
        text: "Tutoriales y cursos. ES6, Node+NPM, Ionic, Angular, NoSQL."
    },
    {
        url: "http://www.marketingenredes.com/",
        linkText: "Marketing en redes",
        text: "Sin unos buenos consejos como estos de maketing digital, no somos nadie."
    }
];

var siteNavigation = new Vue({
    el: "#site-navigation",
    data: {
        linkList: objLinkList
    }
});
var blogs = new Vue({
    el: '#blogs',
    data: {
        sectionTitle: "Blogs",
        aryBlogs: objBlogs
    }
});
var footer = new Vue({
  el: '#footer',
  data: {
    copyright: 'Copyright © ' + new Date().getFullYear() + ' Aitor Alejandro Herrera. MIT License'
  }
});
<commit_msg>Marketing en redes<commit_after>var objLinkList = [
            { href: "#blogs", linkText: "Blogs" },
            { href: "#herramientas", linkText: "Herramientas" },
            { href: "#frameworks", linkText: "Frameworks" }
        ];
var objBlogs =  [
    {
        url: "https://css-tricks.com/",
        linkText: "css-tricks",
        text: "Indudablemente una de las webs número uno de consulta para un frontend. Artículos y tutoriales de calidad y un buen número de snippets."
    },
    {
        url: "https://www.smashingmagazine.com/",
        linkText: "Smashing Magazine",
        text: "Todo un referente en el mundo de la web. Código, diseño, mobile, UX ... etc. Publican libros con colecciones de sus artículos más interesantes."
    },
    {
        url: "https://www.sitepoint.com/",
        linkText: "Site Point",
        text: "Artículos meticulosos de gran calidad, podcast, libros y cursos (a veces gratis). También imprescindible."
    },
    {
        url: "https://scotch.io/",
        linkText: "Scotch.io",
        text: "Tutoriales excelentes sobre el mundo frontend y backend javascript. Disponen de cursos free y premium. ¡¡No perdérselo!!"
    },
    {
        url: "https://davidwalsh.name/",
        linkText: "David Walsh Blog",
        text: "log del gurú JavaScript David Walsh. Conviene seguirle y leer sus interesantes artículos. No solo habla de JavaScript, también aborda otras tecnologías web."
    },
    {
        url: "http://alistapart.com/articles",
        linkText: "A List Apart",
        text: "Artículos de todo lo relacionado con la web. Son artículos de una calidad tan extraordinaria que algunos son un referente."
    },
    {
        url: "https://webmasters.googleblog.com/",
        linkText: "Google Webmaster Blog",
        text: "No puede faltar el blog oficial de Google para webmasters."
    },
    {
        url: "http://lea.verou.me/",
        linkText: "Lea Verou",
        text: "La gran Lea Verou. Proyectos, charlas, artículos. Una eminencia en el CSS."
    },
    {
        url: "http://wesbos.com/blog/",
        linkText: "Web Bos",
        text: "Artículos, videos y tutoriales"
    },
    {
        url: "http://www.developerdrive.com/",
        linkText: "Developer Drive",
        text: "Artículos sobre todo tipo de tecnología de desarrollo web."
    },
    {
        url: "http://www.cssportal.com/",
        linkText: "CSS Portal",
        text: "Snippets, generadores y herramientas para desarrollar en CSS."
    },
    {
        url: "http://www.elmaquetadorweb.com/",
        linkText: "El maquetador web",
        text: "Excelente blog mantenido por Javi Luna y Pedro Marín donde nos cuentan muchos trucos en esto del CSS. Me encanta el nombre de maquetador, término en desuso hoy en día.  ;D"
    },
    {
        url: "https://toddmotto.com/",
        linkText: "Todd Motto",
        text: "Artículos y tutoriales sobre JavaScript, Angular y Typescript. Dispone de muy buenos cursos en premium."
    },
    {
        url: "http://valhead.com/blog/",
        linkText: "Val Head Blog",
        text: "Artículos y tutoriales de una especialista en animaciones CSS web."
    },
    {
        url: "https://codyhouse.co/",
        linkText: "Cody House",
        text: "Colecciones gratuitas de snippets de HTML, CSS y JavaScript. También disponen de cursos premium."
    },
    {
        url: "http://www.kylejlarson.com/blog/ ",
        linkText: "kyle J. Larson",
        text: "Buenos consejos para el diseño web."
    },
    {
        url: "http://www.naderdabit.me/#/",
        linkText: "Nader Dabit",
        text: "Tutoriales sobre ReactJS, Angular, NPM ."
    },
    {
        url: "http://mrbool.com/",
        linkText: "Mr. Bool",
        text: "Tutoriales y cursos. ES6, Node+NPM, Ionic, Angular, NoSQL."
    },
    {
        url: "http://www.marketingenredes.com/",
        linkText: "Marketing en redes",
        text: "Sin unos buenos consejos como estos de marketing digital, no somos nadie."
    }
];

var siteNavigation = new Vue({
    el: "#site-navigation",
    data: {
        linkList: objLinkList
    }
});
var blogs = new Vue({
    el: '#blogs',
    data: {
        sectionTitle: "Blogs",
        aryBlogs: objBlogs
    }
});
var footer = new Vue({
  el: '#footer',
  data: {
    copyright: 'Copyright © ' + new Date().getFullYear() + ' Aitor Alejandro Herrera. MIT License'
  }
});
<|endoftext|>


<commit_before>var markdown = require('markdown').markdown;
var React = require('react');
var Dispatchr = require('dispatchr')();
var createStore = require('dispatchr/utils/createStore');

var ContentStore = createStore({
	storeName: 'ContentStore',
	initialize: function() {
		this.currentContent = ["#Hello world!", "Welcome to **markdown**"].join("\n\n");
	},
	handlers: {
		'CONTENT_CHANGED': 'onContentChanged',
		'FILE_LOADED': 'onContentChanged'
	},
	onContentChanged: function(payload) {
		this.currentContent = payload.content;
		this.emitChange();
	},
	getCurrentContent: function() {
		return this.currentContent;
	},
	dehydrate: function() {
		return { currentContent: this.currentContent }
	},
	rehydrate: function(state) {
		this.currentContent = state.currentContent;
		this.emitChange();
	}
});

var EventStore = createStore({
	storeName: 'EventStore',
	initialize: function() {
		this.events = [];
	},
	handlers: {
		'default': 'trackEvent'
	},
	trackEvent: function(payload, eventName) {
		this.events.push({
			name: eventName,
			payload: payload
		});
		this.emitChange();
	},
	getEvents: function() {
		return this.events;
	}
});

Dispatchr.registerStore(ContentStore);
Dispatchr.registerStore(EventStore);

var context = {};
var dispatcher = new Dispatchr(context);

var EditorActions = {
	changeContent: function(newContent) {
		dispatcher.dispatch('CONTENT_CHANGED', {
			content: newContent
		});
	},
	loadFile: function(filename, newContent) {
		dispatcher.dispatch('FILE_LOADED', {
			filename: filename,
			content: newContent
		});
	}
};

var StoreListenerMixin = function(storeName) {
	return {
		componentDidMount: function() {
			dispatcher.getStore(storeName).addChangeListener(this._onChange);
		},
		componentWillUnmount: function() {
			dispatcher.getStore(storeName).removeChangeListener(this._onChange);
		},
		_onChange: function() {
			this.setState(this.getInitialState());
		},
		getInitialState: function() {
			return this._stateFromStore(dispatcher.getStore(storeName));
		},
	}
};
var ContentStoreListenerMixin = StoreListenerMixin('ContentStore');
var EventStoreListenerMixin = StoreListenerMixin('EventStore');

var SimpleEditor = React.createClass({
	mixins: [ContentStoreListenerMixin],
	_stateFromStore: function(store) {
		return { value: store.getCurrentContent() }
	},
	handleChange: function(event) {
		EditorActions.changeContent(event.target.value);
	},
	render: function() {
		return (

Input

				<textarea onChange={this.handleChange} value={this.state.value}></textarea>

		);
	}
});

var SimplePreview = React.createClass({
	mixins: [ContentStoreListenerMixin],
	_stateFromStore: function(store) {
		return { html: markdown.toHTML(store.getCurrentContent()) }
	},
	render: function() {
		return (

Preview

		);
	}
});

var FileManager = React.createClass({
	mixins: [ContentStoreListenerMixin],
	_stateFromStore: function(store) {
		return { markdown: store.getCurrentContent() }
	},
	handleUpload: function(event) {
		var reader = new FileReader();
		var file = event.target.files[0];

		reader.onload = function() {
			EditorActions.loadFile(file.name, this.result);
		};
		reader.readAsText(file);
	},
	handleDownload: function(event) {
		// For a wider range of compatibility, see https://github.com/eligrey/FileSaver.js
		var blob = new Blob([this.state.markdown], {
			type: "text/markdown;charset=utf-8;"
		});
		var fileURL = window.URL.createObjectURL(blob); // window.URL.revokeObjectURL(fileURL);
		event.target.setAttribute('download', window.prompt('Please enter the filename', 'simple-text.md'));
		event.target.setAttribute('href', fileURL);
	},
	render: function() {
		return (

<input type="file" name="file-uploader" onChange={ this.handleUpload } />

Download Mardown file

		);
	}
});

var DebugBar = React.createClass({
	mixins: [EventStoreListenerMixin],
	_stateFromStore: function(store) {
		return { eventCount: store.getEvents().length }
	},
	componentDidMount: function() {
		this.initialState = dispatcher.dehydrate();
	},

	handleDownloadState: function() {
		var currentAppState = JSON.stringify(dispatcher.dehydrate());
		var fileURL = window.URL.createObjectURL(new Blob(
			[currentAppState],
			{ type: "text/json;charset=utf-8;"}
		));
		var nowSuffix = new Date(Date.now()).toLocaleString();
		event.target.setAttribute('download', 'simple-editor-state-' + nowSuffix);
		event.target.setAttribute('href', fileURL);
	},
	handleUploadState: function(event) {
		var reader = new FileReader();
		reader.onload = function() {
			dispatcher.rehydrate(JSON.parse(this.result));
		};
		reader.readAsText(event.target.files[0]);
	},

	handleDownloadHistory: function() {
		var currentAppHistory = {
			initialState: this.initialState,
			events: dispatcher.getStore('EventStore').getEvents()
		};
		var fileURL = window.URL.createObjectURL(new Blob(
			[JSON.stringify(currentAppHistory)],
			{ type: "text/json;charset=utf-8;"}
		));
		var nowSuffix = new Date(Date.now()).toLocaleString();
		event.target.setAttribute('download', 'simple-editor-history-' + nowSuffix);
		event.target.setAttribute('href', fileURL);
	},
	handleUploadHistory: function(event) {
		var reader = new FileReader();
		reader.onload = function() {
			var HISTORY_SPEED_IN_MS = 100;
			var history = JSON.parse(this.result);
			console.debug('rebuilding interface from history...');
			console.debug('... back to initial state');
			dispatcher.rehydrate(history.initialState);

			window.setTimeout(function applyNextEvent() {
				var eventToApply = history.events.shift();
				console.debug('... applying next event - left: ' + history.events.length);
				dispatcher.dispatch(eventToApply.name, eventToApply.payload);

				if (history.events.length) {
					window.setTimeout(applyNextEvent, HISTORY_SPEED_IN_MS);
				}
			}, HISTORY_SPEED_IN_MS);
		};
		reader.readAsText(event.target.files[0]);
	},

	render: function() {
		return (

					DEBUG BAR
					- {this.state.eventCount} events tracked

					<input type="file" onChange={ this.handleUploadState } />
					- Download current state

					<input type="file" onChange={ this.handleUploadHistory } />
					- Download actions history

		);
	}
});

var SimpleEditorWindow = React.createClass({
	render: function() {
		return (

				<DebugBar />
				<FileManager />
				<SimpleEditor />
				<SimplePreview />

		);
	}
});

React.render(
	<SimpleEditorWindow />,
	document.getElementById('editor')
);<commit_msg>Refactored upload / download implamentation into components<commit_after>var markdown = require('markdown').markdown;
var React = require('react');
var Dispatchr = require('dispatchr')();
var createStore = require('dispatchr/utils/createStore');

var ContentStore = createStore({
	storeName: 'ContentStore',
	initialize: function() {
		this.currentContent = ["#Hello world!", "Welcome to **markdown**"].join("\n\n");
	},
	handlers: {
		'CONTENT_CHANGED': 'onContentChanged',
		'FILE_LOADED': 'onContentChanged'
	},
	onContentChanged: function(payload) {
		this.currentContent = payload.content;
		this.emitChange();
	},
	getCurrentContent: function() {
		return this.currentContent;
	},
	dehydrate: function() {
		return { currentContent: this.currentContent }
	},
	rehydrate: function(state) {
		this.currentContent = state.currentContent;
		this.emitChange();
	}
});

var EventStore = createStore({
	storeName: 'EventStore',
	initialize: function() {
		this.events = [];
	},
	handlers: {
		'default': 'trackEvent'
	},
	trackEvent: function(payload, eventName) {
		this.events.push({
			name: eventName,
			payload: payload
		});
		this.emitChange();
	},
	getEvents: function() {
		return this.events;
	}
});

Dispatchr.registerStore(ContentStore);
Dispatchr.registerStore(EventStore);

var context = {};
var dispatcher = new Dispatchr(context);

var EditorActions = {
	changeContent: function(newContent) {
		dispatcher.dispatch('CONTENT_CHANGED', {
			content: newContent
		});
	},
	loadFile: function(filename, newContent) {
		dispatcher.dispatch('FILE_LOADED', {
			filename: filename,
			content: newContent
		});
	}
};

var StoreListenerMixin = function(storeName) {
	return {
		componentDidMount: function() {
			dispatcher.getStore(storeName).addChangeListener(this._onChange);
		},
		componentWillUnmount: function() {
			dispatcher.getStore(storeName).removeChangeListener(this._onChange);
		},
		_onChange: function() {
			this.setState(this.getInitialState());
		},
		getInitialState: function() {
			return this._stateFromStore(dispatcher.getStore(storeName));
		},
	}
};
var ContentStoreListenerMixin = StoreListenerMixin('ContentStore');
var EventStoreListenerMixin = StoreListenerMixin('EventStore');

var SimpleEditor = React.createClass({
	mixins: [ContentStoreListenerMixin],
	_stateFromStore: function(store) {
		return { value: store.getCurrentContent() }
	},
	handleChange: function(event) {
		EditorActions.changeContent(event.target.value);
	},
	render: function() {
		return (

Input

				<textarea onChange={this.handleChange} value={this.state.value}></textarea>

		);
	}
});

var SimplePreview = React.createClass({
	mixins: [ContentStoreListenerMixin],
	_stateFromStore: function(store) {
		return { html: markdown.toHTML(store.getCurrentContent()) }
	},
	render: function() {
		return (

Preview

		);
	}
});

var FileUploader = React.createClass({
	handleUpload: function(event) {
		var onUploadCallback = this.props.onUpload;
		var reader = new FileReader();
		var file = event.target.files[0];

		reader.onload = function() {
			onUploadCallback(file.name, this.result);
		};
		reader.readAsText(file);
	},
	render: function() {
		return (
			<input type="file" onChange={ this.handleUpload } />
		);
	}
});

var FileDownloader = React.createClass({
	// For a wider range of compatibility, see https://github.com/eligrey/FileSaver.js
	handleDownload: function(event) {
		var fileData = this.props.getFileData();
		var blob = new Blob(
			[fileData.content],
			{ type: fileData.type }
		);
		var fileURL = window.URL.createObjectURL(blob); // consider also using `window.URL.revokeObjectURL(fileURL);` to prevent memory leaks
		event.target.setAttribute('download', fileData.name);
		event.target.setAttribute('href', fileURL);
	},
	render: function() {
		return (
			{ this.props.label }
		);
	}
});

var FileManager = React.createClass({
	mixins: [ContentStoreListenerMixin],
	_stateFromStore: function(store) {
		return { markdown: store.getCurrentContent() }
	},
	handleContentUpload: function(filename, content) {
		EditorActions.loadFile(filename, content);
	},
	downloadedFileData: function() {
		return {
			content: this.state.markdown,
			type: "text/markdown;charset=utf-8;",
			name: window.prompt('Please enter the filename', 'simple-text.md')
		};
	},
	render: function() {
		return (

				<FileUploader onUpload={ this.handleContentUpload } />
				- <FileDownloader getFileData={ this.downloadedFileData } label="Download Mardown file" />

		);
	}
});

var DebugBar = React.createClass({
	mixins: [EventStoreListenerMixin],
	_stateFromStore: function(store) {
		return { eventCount: store.getEvents().length }
	},
	componentDidMount: function() {
		this.initialState = dispatcher.dehydrate();
	},

	downloadedStateData: function() {
		return {
			content: JSON.stringify(dispatcher.dehydrate()),
			type: "text/json;charset=utf-8;",
			name: 'simple-editor-state-' + new Date(Date.now()).toLocaleString()
		}
	},
	handleUploadState: function(filename, content) {
		dispatcher.rehydrate(JSON.parse(content));
	},

	downloadedHistoryData: function() {
		var currentAppHistory = {
			initialState: this.initialState,
			events: dispatcher.getStore('EventStore').getEvents()
		};
		return {
			content: JSON.stringify(currentAppHistory),
			type: "text/json;charset=utf-8;",
			name: 'simple-editor-history-' + new Date(Date.now()).toLocaleString()
		}
	},
	handleUploadHistory: function(filename, content) {
		var HISTORY_SPEED_IN_MS = 100;
		var history = JSON.parse(content);
		console.debug('rebuilding interface from history contained in "' + filename + '"...');
		console.debug('... back to initial state');
		dispatcher.rehydrate(history.initialState);

		(function applyNextEvent() {
			var eventToApply = history.events.shift();
			console.debug('... applying next event - remaining: ' + history.events.length);
			dispatcher.dispatch(eventToApply.name, eventToApply.payload);

			if (history.events.length) {
				window.setTimeout(applyNextEvent, HISTORY_SPEED_IN_MS);
			} else {
				console.debug('that\'s all folks!');
			}
		})();
	},

	render: function() {
		return (

					DEBUG BAR
					- {this.state.eventCount} events tracked

					<FileUploader onUpload={ this.handleUploadState } />
					- <FileDownloader getFileData={ this.downloadedStateData } label="Download current application state" />

					<FileUploader onUpload={ this.handleUploadHistory } />
					- <FileDownloader getFileData={ this.downloadedHistoryData } label="Download application history" />

		);
	}
});

var SimpleEditorWindow = React.createClass({
	render: function() {
		return (

				<DebugBar />
				<FileManager />
				<SimpleEditor />
				<SimplePreview />

		);
	}
});

React.render(
	<SimpleEditorWindow />,
	document.getElementById('editor')
);<|endoftext|>


<commit_before>/* ****** MODEL ******** */

var neighborhoodSpots = [
		{
			title: "Saggio",
			phone: "212-795-3080",
			location: {lat: 40.851473, lng: -73.939588},
			type: "Restaurant",
//			label: "Restaurant"
		},
    	{
    		title: "Mambi Steakhouse",
    		phone: "212-928-9796",
    		location: {lat: 40.84772, lng: -73.938251},
    		type: "Restaurant"
    	},
    	{
    		title: "Planet Fitness",
    		phone: "646-216-3150",
    		location: {lat: 40.847326, lng: -73.937638},
    		type: "Gym",
    //		label:"Gym"
    	},
    	{
    		title: "Le Cheile",
    		phone: "212-740-3111",
    		location: {lat: 40.851495, lng: -73.939988},
    		type: "Restaurant"
    	},
    	{
    		title: "Elite Cleaners",
    		phone: "212-927-5872",
    		location: {lat: 40.843097, lng: -73.939438},
    		type: "Dry Cleaners",
    //		label: "Dry Cleaners"
    	},
    	{
    		title: "Columbia Wine Co",
    		phone: "212-543-2633",
    		location: {lat: 40.842125, lng: -73.939272},
    		type: "Liquor Store",
    //		label: "Liquor Store"
    	}
	]

	//****** VIEW ******** //

var listView = function(data) {
	this.title = ko.observable(data.title);
	this.location = ko.observable(data.location);
	this.type = ko.observable(data.type);
}

// ****** VIEWMODEL ******** //

var ViewModel = function() {
	var self = this;

	this.places = ko.observableArray([]);

	neighborhoodSpots.forEach(function(locationItem) {
		self.places.push(new listView(locationItem));
	});

	this.selectedType = ko.observable();
	this.clearFilter = function() {
		this.selectedType(null)
	}
}

ko.applyBindings(new ViewModel());

// ******** MAP ******** //

var map;

// Create empty arry to push markers into.
var markers = [];

// Get that map going in the map div!
// Thanks to Google Maps API for the super helpful documentation, course, and instructions!
var initMap = function() {
	map = new google.maps.Map(document.getElementById('map'), {
		center: {lat: 40.843436, lng: -73.934794},
		zoom: 14
	});

	var mapInfoWindow = new google.maps.InfoWindow();

	var defaultIcon = makeMarkerIcon('ff2d00');

	var highlightedIcon = makeMarkerIcon('631504');

	// loop through neighborhoodSpots array to make markers.
	for (var i = 0; i < neighborhoodSpots.length; i++) {
		var title = neighborhoodSpots[i].title;
		var position = neighborhoodSpots[i].location;

		var marker = new google.maps.Marker({
			map: map,
			position: position,
			title: title,
			icon: defaultIcon,
			id: i
		});

	// Push markers to markers[] array.
	markers.push(marker);

	//Open info window on click.
	marker.addListener("click", function() {
		fillInfoWindow(this, mapInfoWindow);
	});

	// Change marker color when mouse hovers over marker.
	marker.addListener("mouseover", function() {
		this.setIcon(highlightedIcon);
	});

	// Use default color when not hovering over marker.
	marker.addListener("mouseout", function() {
		this.setIcon(defaultIcon);
	});
	}

function fillInfoWindow(marker, infowindow) {
	// Check if marker's window is already open.
	if (infowindow.marker != marker) {
		// Clear infowindow
		infowindow.setContent('');
		infowindow.marker = marker;
		// Open  infowinow
		infowindow.open(map, marker)

		// Close infowindow on click
		infowindow.addListener('closeclick', function() {
			infowindow.marker(null);
		});

		infowindow.setContent("
" + marker.title + "
")

	}
}

		// This function takes in a color, and then creates a new marker
       // icon of that color. The icon will be 21px wide by 34px high, have an
      // origin of 0, 0 and be anchored at 10, 34. Again, thank you Google API for the help.
      function makeMarkerIcon(markerColor) {
        var markerImage = new google.maps.MarkerImage(
          "https://chart.googleapis.com/chart?chst=d_map_spin&chld=1.15|0|" + markerColor +
          "|40|_|%E2%80%A2",
          new google.maps.Size(21, 34),
          new google.maps.Point(0, 0),
          new google.maps.Point(10, 34),
          new google.maps.Size(21,34));
        return markerImage;
      }

};<commit_msg>add phone to infowindo<commit_after>/* ****** MODEL ******** */

var neighborhoodSpots = [
		{
			title: "Saggio",
			phone: "212-795-3080",
			location: {lat: 40.851473, lng: -73.939588},
			type: "Restaurant",
//			label: "Restaurant"
		},
    	{
    		title: "Mambi Steakhouse",
    		phone: "212-928-9796",
    		location: {lat: 40.84772, lng: -73.938251},
    		type: "Restaurant"
    	},
    	{
    		title: "Planet Fitness",
    		phone: "646-216-3150",
    		location: {lat: 40.847326, lng: -73.937638},
    		type: "Gym",
    //		label:"Gym"
    	},
    	{
    		title: "Le Cheile",
    		phone: "212-740-3111",
    		location: {lat: 40.851495, lng: -73.939988},
    		type: "Restaurant"
    	},
    	{
    		title: "Elite Cleaners",
    		phone: "212-927-5872",
    		location: {lat: 40.843097, lng: -73.939438},
    		type: "Dry Cleaners",
    //		label: "Dry Cleaners"
    	},
    	{
    		title: "Columbia Wine Co",
    		phone: "212-543-2633",
    		location: {lat: 40.842125, lng: -73.939272},
    		type: "Liquor Store",
    //		label: "Liquor Store"
    	}
	]

	//****** VIEW ******** //

var listView = function(data) {
	this.title = ko.observable(data.title);
	this.location = ko.observable(data.location);
	this.type = ko.observable(data.type);
}

// ****** VIEWMODEL ******** //

var ViewModel = function() {
	var self = this;

	this.places = ko.observableArray([]);

	neighborhoodSpots.forEach(function(locationItem) {
		self.places.push(new listView(locationItem));
	});

	this.selectedType = ko.observable();
	this.clearFilter = function() {
		this.selectedType(null)
	}
}

ko.applyBindings(new ViewModel());

// ******** MAP ******** //

var map;

// Create empty arry to push markers into.
var markers = [];

// Get that map going in the map div!
// Thanks to Google Maps API for the super helpful documentation, course, and instructions!
var initMap = function() {
	map = new google.maps.Map(document.getElementById('map'), {
		center: {lat: 40.843436, lng: -73.934794},
		zoom: 14
	});

	var mapInfoWindow = new google.maps.InfoWindow();

	var defaultIcon = makeMarkerIcon('ff2d00');

	var highlightedIcon = makeMarkerIcon('631504');

	// loop through neighborhoodSpots array to make markers.
	for (var i = 0; i < neighborhoodSpots.length; i++) {
		var title = neighborhoodSpots[i].title;
		var position = neighborhoodSpots[i].location;

		var marker = new google.maps.Marker({
			map: map,
			position: position,
			title: title,
			icon: defaultIcon,
			id: i
		});

	// Push markers to markers[] array.
	markers.push(marker);

	//Open info window on click.
	marker.addListener("click", function() {
		fillInfoWindow(this, mapInfoWindow);
	});

	// Change marker color when mouse hovers over marker.
	marker.addListener("mouseover", function() {
		this.setIcon(highlightedIcon);
	});

	// Use default color when not hovering over marker.
	marker.addListener("mouseout", function() {
		this.setIcon(defaultIcon);
	});
	}

function fillInfoWindow(marker, infowindow) {
	// Check if marker's window is already open.
	if (infowindow.marker != marker) {
		// Clear infowindow
		infowindow.setContent('');
		infowindow.marker = marker;
		// Open  infowinow
		infowindow.open(map, marker)

		// Close infowindow on click
		infowindow.addListener('closeclick', function() {
			infowindow.marker(null);
		});

		infowindow.setContent("
" + marker.title + "

" + marker.phone + "
")

	}
}

		// This function takes in a color, and then creates a new marker
       // icon of that color. The icon will be 21px wide by 34px high, have an
      // origin of 0, 0 and be anchored at 10, 34. Again, thank you Google API for the help.
      function makeMarkerIcon(markerColor) {
        var markerImage = new google.maps.MarkerImage(
          "https://chart.googleapis.com/chart?chst=d_map_spin&chld=1.15|0|" + markerColor +
          "|40|_|%E2%80%A2",
          new google.maps.Size(21, 34),
          new google.maps.Point(0, 0),
          new google.maps.Point(10, 34),
          new google.maps.Size(21,34));
        return markerImage;
      }

};<|endoftext|>


<commit_before>/**
 * JS for RMC
 */

var $, jQuery = window.jQuery;

/**
 * Log function
 *
 * usage: log('inside coolFunc',this,arguments);
 * source: http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
 */
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};

$(function() {

  "use strict";

  var breakpoint = 960;

  var supportsOrientationChange = 'onorientationchange' in window,
      orientationEvent = supportsOrientationChange ? 'orientationchange' : 'resize';

  /**
   *   Returns a function, that, as long as it continues to be invoked, will not
   *   be triggered. The function will be called after it stops being called for
   *   N milliseconds. If `immediate` is passed, trigger the function on the
   *   leading edge, instead of the trailing. Copied from underscores.js.
   */
  function debounce(func, wait, immediate) {
    var timeout;
    return function() {
      var context = this, args = arguments;
      var later = function() {
        timeout = null;
        if (!immediate) func.apply(context, args);
      };
      var callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) func.apply(context, args);
    };
  }

  var homeSlider = $('#hero-slider').bxSlider({
    auto: true,
    easing: 'ease-in-out',
    mode: 'fade',
    pager: false,
    pause: 6000,
    speed: 800,
    onSliderLoad: function() {
      $('.bkgd-slider').css({'opacity': 1});
    }
  });

  $(window).on(orientationEvent,  debounce(function() {

    if (homeSlider.length) {
      homeSlider.reloadSlider();
    }
  }, 250)).trigger(orientationEvent);

}(jQuery));

<commit_msg>update name<commit_after>/**
 * JS for Rhapsody
 */

var $, jQuery = window.jQuery;

/**
 * Log function
 *
 * usage: log('inside coolFunc',this,arguments);
 * source: http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
 */
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};

$(function() {

  "use strict";

  var breakpoint = 960;

  var supportsOrientationChange = 'onorientationchange' in window,
      orientationEvent = supportsOrientationChange ? 'orientationchange' : 'resize';

  /**
   *   Returns a function, that, as long as it continues to be invoked, will not
   *   be triggered. The function will be called after it stops being called for
   *   N milliseconds. If `immediate` is passed, trigger the function on the
   *   leading edge, instead of the trailing. Copied from underscores.js.
   */
  function debounce(func, wait, immediate) {
    var timeout;
    return function() {
      var context = this, args = arguments;
      var later = function() {
        timeout = null;
        if (!immediate) func.apply(context, args);
      };
      var callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) func.apply(context, args);
    };
  }

  var homeSlider = $('#hero-slider').bxSlider({
    auto: true,
    easing: 'ease-in-out',
    mode: 'fade',
    pager: false,
    pause: 6000,
    speed: 800,
    onSliderLoad: function() {
      $('.bkgd-slider').css({'opacity': 1});
    }
  });

  $(window).on(orientationEvent,  debounce(function() {

    if (homeSlider.length) {
      homeSlider.reloadSlider();
    }
  }, 250)).trigger(orientationEvent);

}(jQuery));

<|endoftext|>


<commit_before>    var app = angular.module('starter', ["ui.router"]);
    app.config(function($stateProvider, $urlRouterProvider){

      // For any unmatched url, send to /route1
      $urlRouterProvider.otherwise("/home");

      $stateProvider
        .state('home', {
            url: "/home",
            templateUrl: "templates/home.html"
        })

        .state('reader', {
            url: "/reader",
            templateUrl: "templates/reader.html"
        })

        .state('author', {
            url: "/author/:id",
            templateUrl: "templates/author.html",
            controller: 'AuthorCtrl'
        });
    });

app.controller('AuthorCtrl', function($scope, publications, pdf_files, $stateParams){
		$scope.publications = publications.getPublications();

        /*
		if ($stateParams.id != ""){
			var currentPublication = pdf_files.showPDF(publications.getEntryById($stateParams.id).url);
        }
    */
        // -----------NEW---------
        if($stateParams.id != ""){

            //
            // handles display of files regarding filetype peculiarities
            //
            switch(publications.getContentById($stateParams.id).type){
                case '.pdf':
                    _setAllFalse;
                    var currentContent = pdf_files.showPDF(publications.getContentById($stateParams.id).url);
                    publications.getContentById($stateParams.id).show = true;
                    break;
                case '.jpg':
                    _setAllFalse;
                    var currentContent = publications.getContentById($stateParams.id).show = true;
                    break;
            }

        }

        // sets .show-Attribute of all files to false
        var _setAllFalse = function(){
             for(file in publications.getPublications().content){
                        publications.getPublications().content[file].show = false;
                    }
        };

});

app.controller('ReaderCtrl', function($scope){

});

app.controller('HomeCtrl', function($scope){

});<commit_msg>Add Display .jpg in browser - display of pdf needs to be fixed<commit_after>    var app = angular.module('starter', ["ui.router"]);
    app.config(function($stateProvider, $urlRouterProvider){

      // For any unmatched url, send to /route1
      $urlRouterProvider.otherwise("/home");

      $stateProvider
        .state('home', {
            url: "/home",
            templateUrl: "templates/home.html"
        })

        .state('reader', {
            url: "/reader",
            templateUrl: "templates/reader.html"
        })

        .state('author', {
            url: "/author/:id",
            templateUrl: "templates/author.html",
            controller: 'AuthorCtrl'
        });
    });

app.controller('AuthorCtrl', function($scope, publications, pdf_files, $stateParams){
		$scope.publications = publications.getPublications();

        /*
		if ($stateParams.id != ""){
			var currentPublication = pdf_files.showPDF(publications.getEntryById($stateParams.id).url);
        }
    */
        // -----------NEW---------
        if($stateParams.id != ""){

            //
            // handles display of files regarding filetype peculiarities
            //
            switch(publications.getContentById($stateParams.id).type){
                case '.pdf':
                    _setAllFalse();
                    publications.getContentById($stateParams.id).show = true;
                    var currentContent = pdf_files.showPDF(publications.getContentById($stateParams.id).url);
                    break;
                case '.jpg':
                    _setAllFalse();
                    var currentContent = publications.getContentById($stateParams.id).show = true;
                    break;
            }

        }

        // sets .show-Attribute of all files to false
        function _setAllFalse(){
             for(file in publications.getPublications().content){
                        publications.getPublications().content[file].show = false;
                    }
        };

});

app.controller('ReaderCtrl', function($scope){

});

app.controller('HomeCtrl', function($scope){

});<|endoftext|>


<commit_before>function encrypt(text, pass) {
  //console.log('pass:' + pass + ' encrypt IN:' + text);
  var key = Sha256.hash(pass);
  var encrypted = Aes.Ctr.encrypt(text, key, 256);
  //console.log('encrypt OUT:' + encrypted);
  return encrypted;
}

function decrypt (text, pass) {
  //console.log('pass:' + pass + ' decrypt IN:' + text);
  var key = Sha256.hash(pass);
  var decrypted = Aes.Ctr.decrypt(text, key, 256);
  //console.log('decrypt OUT:' + decrypted);
  return decrypted;
}

function backToTop() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
}

function passwordsMatch() {
  console.log("passwordsMatch()");

  if( $('#password').val() == $('#password2').val() ) {

    $('#passGroup').removeClass("has-error");
    $('#passwordError').addClass("hidden");

    return true;
  }

  $('#passGroup').addClass("has-error");
  $('#passwordError').removeClass("hidden");

  backToTop();

  return false;
}

function onMessageChange() {
    console.log("onMessageChange()");
    var m = $('#message');

    $("#count").text( m.val().length  );

    m.autosize({ append: '\n'});
    m.trigger('autosize.resize');
}

function messageUpdated() {
  $('#message').select();
  onMessageChange();
}

function clearMessage() {
  $('#message').val('');
  onMessageChange();
}

function pageEncrypt() {
  console.log("pageEncrypt()");
  if ( passwordsMatch() ) {
    $('#message').val( encrypt( $('#message').val(), $('#password').val() ) );
    messageUpdated();
  }
}

function pageDecrypt() {
  console.log("pageDecrypt()");
  if( passwordsMatch() ) {
    $('#message').val( decrypt( $('#message').val(), $('#password').val() ) );
    messageUpdated();
  }
}

$( function() {

  $("#message").change( onMessageChange );
  $("#message").keyup( onMessageChange );

  $('#encrypt').click( pageEncrypt );
  $('#decrypt').click( pageDecrypt );

  $('#backToTop').click( backToTop );
  $('#reset').click( clearMessage );

  onMessageChange();

  $('#splashscreen').delay( 1000 ).fadeOut('slow');

  options = {
    success: function(files) {
        // name, link, bytes, icon, thumbnailLink
        alert("Here's the file link: " + files[0].link)
        ${'#message').val ( files[0].bytes );
    },
    cancel: function() {

    },
    linkType: "direct", // or "direct"
    multiselect: false, // or true
    extensions: ['.md', '.txt', '.markdown', '.rsa'],
  };

  var button = Dropbox.createChooseButton(options);
  document.getElementById("container").appendChild(button);

  console.log('Page loaded');
});
<commit_msg>Update app.js<commit_after>function encrypt(text, pass) {
  //console.log('pass:' + pass + ' encrypt IN:' + text);
  var key = Sha256.hash(pass);
  var encrypted = Aes.Ctr.encrypt(text, key, 256);
  //console.log('encrypt OUT:' + encrypted);
  return encrypted;
}

function decrypt (text, pass) {
  //console.log('pass:' + pass + ' decrypt IN:' + text);
  var key = Sha256.hash(pass);
  var decrypted = Aes.Ctr.decrypt(text, key, 256);
  //console.log('decrypt OUT:' + decrypted);
  return decrypted;
}

function backToTop() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
}

function passwordsMatch() {
  console.log("passwordsMatch()");

  if( $('#password').val() == $('#password2').val() ) {

    $('#passGroup').removeClass("has-error");
    $('#passwordError').addClass("hidden");

    return true;
  }

  $('#passGroup').addClass("has-error");
  $('#passwordError').removeClass("hidden");

  backToTop();

  return false;
}

function onMessageChange() {
    console.log("onMessageChange()");
    var m = $('#message');

    $("#count").text( m.val().length  );

    m.autosize({ append: '\n'});
    m.trigger('autosize.resize');
}

function messageUpdated() {
  $('#message').select();
  onMessageChange();
}

function clearMessage() {
  $('#message').val('');
  onMessageChange();
}

function pageEncrypt() {
  console.log("pageEncrypt()");
  if ( passwordsMatch() ) {
    $('#message').val( encrypt( $('#message').val(), $('#password').val() ) );
    messageUpdated();
  }
}

function pageDecrypt() {
  console.log("pageDecrypt()");
  if( passwordsMatch() ) {
    $('#message').val( decrypt( $('#message').val(), $('#password').val() ) );
    messageUpdated();
  }
}

$( function() {

  $("#message").change( onMessageChange );
  $("#message").keyup( onMessageChange );

  $('#encrypt').click( pageEncrypt );
  $('#decrypt').click( pageDecrypt );

  $('#backToTop').click( backToTop );
  $('#reset').click( clearMessage );

  onMessageChange();

  $('#splashscreen').delay( 1000 ).fadeOut('slow');

  options = {
    success: function(files) {
        // name, link, bytes, icon, thumbnailLink
        alert("Here's the file link: " + files[0].link)
        $('#message').val( files[0].bytes );
    },
    cancel: function() {

    },
    linkType: "direct", // or "direct"
    multiselect: false, // or true
    extensions: ['.md', '.txt', '.markdown', '.rsa'],
  };

  var button = Dropbox.createChooseButton(options);
  document.getElementById("container").appendChild(button);

  console.log('Page loaded');
});
<|endoftext|>


<commit_before>$(function() {
  var Photo = function(path) {
    this.path = path;
    this.votes = 1;
  }

  Photo.prototype.vote = function() {
    return ++this.votes;
  }

  var Tracker = function() {
    this.photos = [];

    var xhr = $.ajax({
      dataType: 'json',
      headers: { Authorization: 'Client-ID 8d7a417fb5ee534' },
      url: 'https://api.imgur.com/3/album/DDoWy',
      context: this
    });

    xhr.done(function(response) {
      if (response.status === 200) {
        var images = response.data.images;

        for (var i = 0; i < images.length; i++) {
          this.photos.push(new Photo(images[i].link));
        }

        this.voting();
      }
    });

    var context = $('#middle')[0].getContext('2d');
    this.chart = new Chart(context).Doughnut([
      {
        value: 1,
        color: '#e74c3c',
        highlight: '#c0392b',
        label: 'Red'
      },
      {
        value: 1,
        color: '#3498db',
        highlight: '#2980b9',
        label: 'Blue'
      }
    ]);

    this.$left = $('#left');
    this.$right = $('#right');
    this.$winner = $('#winner');
    this.$next = $('#next');
  }

  Tracker.prototype.isVoting = function() {
    return this.state === 'voting';
  }

  Tracker.prototype.isProclaiming = function() {
    return this.state === 'proclaiming';
  }

  Tracker.prototype.voting = function() {
    this.state = 'voting';
    this.selectKittens();
    this.drawKittens();
    this.resetResults();
    this.updateChart();
  }

  Tracker.prototype.proclaiming = function(winner) {
    this.state = 'proclaiming';
    this.declareResults(this.castVote(winner));
    this.updateChart();
  }

  Tracker.prototype.getRandomInt = function(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
  }

  Tracker.prototype.selectKittens = function() {
    var left = this.getRandomInt(0, this.photos.length);
    var right = this.getRandomInt(0, this.photos.length);

    while (left === right) {
      right = this.getRandomInt(0, this.photos.length);
    }

    this.left = this.photos[left];
    this.right = this.photos[right];
  }

  Tracker.prototype.drawKittens = function() {
    this.$left.css({
      cursor: 'pointer',
      borderColor: '#3498db',
      backgroundImage: 'url(' + this.left.path + ')'
    });

    this.$right.css({
      cursor: 'pointer',
      borderColor: '#e74c3c',
      backgroundImage: 'url(' + this.right.path + ')'
    });
  }

  Tracker.prototype.updateChart = function() {
    this.chart.segments[1].value = this.left.votes;
    this.chart.segments[0].value = this.right.votes;
    this.chart.update();
  }

  Tracker.prototype.resetResults = function() {
    this.$winner.css('display', 'none');
    this.$next.css('display', 'none');
  }

  Tracker.prototype.castVote = function(winner) {
    if (winner === 'left') {
      this.left.vote();

      this.$left.css({
        cursor: 'auto',
        borderColor: '#3498db'
      });

      this.$right.css({
        cursor: 'auto',
        borderColor: 'white'
      });

      return 'Blue wins!';
    } else {
      this.right.vote();

      this.$right.css({
        cursor: 'auto',
        borderColor: '#e74c3c'
      });

      this.$left.css({
        cursor: 'auto',
        borderColor: 'white'
      });

      return 'Red wins!';
    }
  }

  Tracker.prototype.declareResults = function(message) {
    this.$winner.css({
      display: 'block',
      textContent: message
    });

    this.$next.css('display', 'inline-block');
  }

  var tracker = new Tracker();

  var vote = function() {
    if (tracker.isProclaiming()) {
      return;
    }

    tracker.proclaiming(this.id);
  }

  var declare = function() {
    if (tracker.isVoting()) {
      return;
    }

    tracker.voting();
  }

  $('#left, #right').on('click', vote);
  $('#next').on('click', declare);
});
<commit_msg>deleting duplicate js folder<commit_after><|endoftext|>