<commit_before>/*
 * Copyright (c) 2014, Wanadev <http://www.wanadev.fr/>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   * Redistributions of source code must retain the above copyright notice, this
 *     list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright notice,
 *     this list of conditions and the following disclaimer in the documentation
 *     and/or other materials provided with the distribution.
 *   * Neither the name of Wanadev nor the names of its contributors may be used
 *     to endorse or promote products derived from this software without specific
 *     prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authored by: Fabien LOISON <http://flozz.fr/>
 */

/**
 * PhotonUI - Javascript Web User Interface.
 *
 * @module PhotonUI
 * @submodule Composite
 * @namespace photonui
 */

var photonui = photonui || {};

/**
 * Color Picker Dialog.
 *
 * wEvents:
 *
 *   * value-changed:
 *      - description: the selected color changed.
 *      - callback:    function(widget, color)
 *
 * @class ColorPickerDialog
 * @constructor
 * @extends photonui.Dialog
 */
photonui.ColorPickerDialog = photonui.Dialog.$extend({

    // Constructor
    __init__: function(params) {
        this.__widgets = {};
        this._color = new photonui.Color();

        var params = params || {};
        if (params.title == undefined) params.title = _("Select a color...");

        this._registerWEvents(["value-changed"]);

        this.$super(params);

        this._buildUi();
        this._updateProperties(["color"]);
    },

    //////////////////////////////////////////
    // Properties and Accessors             //
    //////////////////////////////////////////

    // ====== Public properties ======

    /**
     * The color.
     *
     * @property color
     * @type kzd.Color
     */
    _color: null,

    getColor: function() {
        return this._color;
    },

    setColor: function(color) {
        if (color instanceof photonui.Color) {
            if (this._color) {
                this._color.removeCallback("photonui.colorpickerdialog.value-changed::" + this.name);
            }
            this._color = color;
            this._color.registerCallback("photonui.colorpickerdialog.value-changed::" + this.name, "value-changed", this.__onColorChanged, this);
        }
        this.__onColorChanged();
    },

    //////////////////////////////////////////
    // Methods                              //
    //////////////////////////////////////////

    // ====== Public methods ======

    destroy: function() {
        this._color.removeCallback("photonui.colorpickerdialog.value-changed::" + this.name);
        this.$super();
    },

    // ====== Private methods ======

    /**
     * Make the UI.
     *
     * @method _buildUi
     * @private
     */
    _buildUi: function() {

        // == Main UI ==
        this.__widgets.hbox = new photonui.BoxLayout({orientation: "horizontal"});
        this.child = this.__widgets.hbox;

        // Color Picker
        this.__widgets.colorPicker = new photonui.ColorPicker();
        this.__widgets.hbox.addChild(this.__widgets.colorPicker);

        // Color Palette
        this.__widgets.colorPalette = new photonui.ColorPalette();
        this.__widgets.hbox.addChild(this.__widgets.colorPalette);

        // Separator
        this.__widgets.separator = new photonui.Separator({orientation: "vertical"});
        this.__widgets.hbox.addChild(this.__widgets.separator);

        this.__widgets.grid = new photonui.GridLayout();
        this.__widgets.hbox.addChild(this.__widgets.grid);

        // Red field + label
        this.__widgets.fieldRed = new photonui.Slider({
            min: 0,
            max: 255,
            decimalDigit: 0
        });

        this.__widgets.labelRed = new photonui.Label({
            text: _("Red:"),
            forInput: this.__widgets.fieldRed
        });

        this.__widgets.grid.addChild(this.__widgets.labelRed, {gridX: 0, gridY: 0, verticalExpansion: false});
        this.__widgets.grid.addChild(this.__widgets.fieldRed, {gridX: 1, gridY: 0, verticalExpansion: false});

        // Green field + label
        this.__widgets.fieldGreen = new photonui.Slider({
            min: 0,
            max: 255,
            decimalDigit: 0
        });

        this.__widgets.labelGreen = new photonui.Label({
            text: _("Green:"),
            forInput: this.__widgets.fieldGreen
        });

        this.__widgets.grid.addChild(this.__widgets.labelGreen, {gridX: 0, gridY: 1, verticalExpansion: false});
        this.__widgets.grid.addChild(this.__widgets.fieldGreen, {gridX: 1, gridY: 1, verticalExpansion: false});

        // Blue field + label
        this.__widgets.fieldBlue = new photonui.Slider({
            min: 0,
            max: 255,
            decimalDigit: 0
        });

        this.__widgets.labelBlue = new photonui.Label({
            text: _("Blue:"),
            forInput: this.__widgets.fieldBlue
        });

        this.__widgets.grid.addChild(this.__widgets.labelBlue, {gridX: 0, gridY: 2, verticalExpansion: false});
        this.__widgets.grid.addChild(this.__widgets.fieldBlue, {gridX: 1, gridY: 2, verticalExpansion: false});

        // Separator
        this.__widgets.separator2 = new photonui.Separator();
        this.__widgets.grid.addChild(this.__widgets.separator2, {gridX: 0, gridY: 3, verticalExpansion: false, gridWidth: 2});

        // Hue field + label
        this.__widgets.fieldHue = new photonui.Slider({
            min: 0,
            max: 360,
            decimalDigit: 0
        });

        this.__widgets.labelHue = new photonui.Label({
            text: _("Hue:"),
            forInput: this.__widgets.fieldHue
        });

        this.__widgets.grid.addChild(this.__widgets.labelHue, {gridX: 0, gridY: 4, verticalExpansion: false});
        this.__widgets.grid.addChild(this.__widgets.fieldHue, {gridX: 1, gridY: 4, verticalExpansion: false});

        // Saturation field + label
        this.__widgets.fieldSaturation = new photonui.Slider({
            min: 0,
            max: 100,
            decimalDigit: 0
        });

        this.__widgets.labelSaturation = new photonui.Label({
            text: _("Saturation:"),
            forInput: this.__widgets.fieldSaturation
        });

        this.__widgets.grid.addChild(this.__widgets.labelSaturation, {gridX: 0, gridY: 5, verticalExpansion: false});
        this.__widgets.grid.addChild(this.__widgets.fieldSaturation, {gridX: 1, gridY: 5, verticalExpansion: false});

        // Brightness field + label
        this.__widgets.fieldBrightness = new photonui.Slider({
            min: 0,
            max: 100,
            decimalDigit: 0
        });

        this.__widgets.labelBrightness = new photonui.Label({
            text: _("Brightness:"),
            forInput: this.__widgets.fieldBrightness
        });

        this.__widgets.grid.addChild(this.__widgets.labelBrightness, {gridX: 0, gridY: 6, verticalExpansion: false});
        this.__widgets.grid.addChild(this.__widgets.fieldBrightness, {gridX: 1, gridY: 6, verticalExpansion: false});

        // == Dialog Buttons ==
        this.__widgets.buttonOk = new photonui.Button({text: _("Ok")});
        if (photonui.FAIcon) this.__widgets.buttonOk.leftIcon = new photonui.FAIcon("fa-check");

        this.__widgets.buttonCancel = new photonui.Button({text: _("Cancel")});
        this.buttons = [this.__widgets.buttonOk, this.__widgets.buttonCancel];

        if (photonui.FAIcon) this.__widgets.buttonCancel.leftIcon = new photonui.FAIcon("fa-times");

        // == Bindings ==
        this.__widgets.colorPalette.color = this.__widgets.colorPicker.color;

        this.__widgets.colorPicker.color.registerCallback("colorpickerdialog.colorPicker.value-changed", "value-changed", function(color) {
            this.__widgets.fieldRed.value = color.red;
            this.__widgets.fieldGreen.value = color.green;
            this.__widgets.fieldBlue.value = color.blue;
            this.__widgets.fieldHue.value = color.hue;
            this.__widgets.fieldSaturation.value = color.saturation;
            this.__widgets.fieldBrightness.value = color.brightness;
        }, this);

        this.__widgets.fieldRed.registerCallback("colorpickerdialog.fieldRed.value-changed", "value-changed", function(widget, value) {
            this.__widgets.colorPicker.color.red = value;
        }, this);

        this.__widgets.fieldGreen.registerCallback("colorpickerdialog.fieldGreen.value-changed", "value-changed", function(widget, value) {
            this.__widgets.colorPicker.color.green = value;
        }, this);

        this.__widgets.fieldBlue.registerCallback("colorpickerdialog.fieldBlue.value-changed", "value-changed", function(widget, value) {
            this.__widgets.colorPicker.color.blue = value;
        }, this);

        this.__widgets.fieldHue.registerCallback("colorpickerdialog.fieldHue.value-changed", "value-changed", function(widget, value) {
            this.__widgets.colorPicker.color.hue = value;
        }, this);

        this.__widgets.fieldSaturation.registerCallback("colorpickerdialog.fieldSaturation.value-changed", "value-changed", function(widget, value) {
            this.__widgets.colorPicker.color.saturation = value;
        }, this);

        this.__widgets.fieldBrightness.registerCallback("colorpickerdialog.fieldBrightness.value-changed", "value-changed", function(widget, value) {
            this.__widgets.colorPicker.color.brightness = value;
        }, this);

        this.__widgets.buttonOk.registerCallback("colorpickerdialog.buttonOk.click", "click", this.__onValidate, this);
        this.__widgets.buttonCancel.registerCallback("colorpickerdialog.buttonCancel.click", "click", this.__onCancel, this);
        this.registerCallback("colorpickerdialog.close", "close-button-clicked", this.__onCancel, this);
    },

    //////////////////////////////////////////
    // Internal Events Callbacks            //
    //////////////////////////////////////////

    /**
     * @method __onCancel
     * @private
     */
    __onCancel: function() {
        this.__widgets.colorPicker.color.setHSB(
                this._color.hue,
                this._color.saturation,
                this._color.brightness
        );
        this.hide();
    },

    /**
     * @method __onValidate
     * @private
     */
    __onValidate: function() {
        this._color.setHSB(
                this.__widgets.colorPicker.color.hue,
                this.__widgets.colorPicker.color.saturation,
                this.__widgets.colorPicker.color.brightness
        );
        this.hide();
        this._callCallbacks("value-changed", [this.color]);
    },

    /**
     * @method __onColorChanged
     * @private
     */
    __onColorChanged: function() {
        this.__widgets.colorPicker.color.setHSB(
                this._color.hue,
                this._color.saturation,
                this._color.brightness
        );
    }
});
<commit_msg>Fin decimalDigits in ColorPickerDialog<commit_after>/*
 * Copyright (c) 2014, Wanadev <http://www.wanadev.fr/>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   * Redistributions of source code must retain the above copyright notice, this
 *     list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright notice,
 *     this list of conditions and the following disclaimer in the documentation
 *     and/or other materials provided with the distribution.
 *   * Neither the name of Wanadev nor the names of its contributors may be used
 *     to endorse or promote products derived from this software without specific
 *     prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authored by: Fabien LOISON <http://flozz.fr/>
 */

/**
 * PhotonUI - Javascript Web User Interface.
 *
 * @module PhotonUI
 * @submodule Composite
 * @namespace photonui
 */

var photonui = photonui || {};

/**
 * Color Picker Dialog.
 *
 * wEvents:
 *
 *   * value-changed:
 *      - description: the selected color changed.
 *      - callback:    function(widget, color)
 *
 * @class ColorPickerDialog
 * @constructor
 * @extends photonui.Dialog
 */
photonui.ColorPickerDialog = photonui.Dialog.$extend({

    // Constructor
    __init__: function(params) {
        this.__widgets = {};
        this._color = new photonui.Color();

        var params = params || {};
        if (params.title == undefined) params.title = _("Select a color...");

        this._registerWEvents(["value-changed"]);

        this.$super(params);

        this._buildUi();
        this._updateProperties(["color"]);
    },

    //////////////////////////////////////////
    // Properties and Accessors             //
    //////////////////////////////////////////

    // ====== Public properties ======

    /**
     * The color.
     *
     * @property color
     * @type kzd.Color
     */
    _color: null,

    getColor: function() {
        return this._color;
    },

    setColor: function(color) {
        if (color instanceof photonui.Color) {
            if (this._color) {
                this._color.removeCallback("photonui.colorpickerdialog.value-changed::" + this.name);
            }
            this._color = color;
            this._color.registerCallback("photonui.colorpickerdialog.value-changed::" + this.name, "value-changed", this.__onColorChanged, this);
        }
        this.__onColorChanged();
    },

    //////////////////////////////////////////
    // Methods                              //
    //////////////////////////////////////////

    // ====== Public methods ======

    destroy: function() {
        this._color.removeCallback("photonui.colorpickerdialog.value-changed::" + this.name);
        this.$super();
    },

    // ====== Private methods ======

    /**
     * Make the UI.
     *
     * @method _buildUi
     * @private
     */
    _buildUi: function() {

        // == Main UI ==
        this.__widgets.hbox = new photonui.BoxLayout({orientation: "horizontal"});
        this.child = this.__widgets.hbox;

        // Color Picker
        this.__widgets.colorPicker = new photonui.ColorPicker();
        this.__widgets.hbox.addChild(this.__widgets.colorPicker);

        // Color Palette
        this.__widgets.colorPalette = new photonui.ColorPalette();
        this.__widgets.hbox.addChild(this.__widgets.colorPalette);

        // Separator
        this.__widgets.separator = new photonui.Separator({orientation: "vertical"});
        this.__widgets.hbox.addChild(this.__widgets.separator);

        this.__widgets.grid = new photonui.GridLayout();
        this.__widgets.hbox.addChild(this.__widgets.grid);

        // Red field + label
        this.__widgets.fieldRed = new photonui.Slider({
            min: 0,
            max: 255,
            decimalDigits: 0
        });

        this.__widgets.labelRed = new photonui.Label({
            text: _("Red:"),
            forInput: this.__widgets.fieldRed
        });

        this.__widgets.grid.addChild(this.__widgets.labelRed, {gridX: 0, gridY: 0, verticalExpansion: false});
        this.__widgets.grid.addChild(this.__widgets.fieldRed, {gridX: 1, gridY: 0, verticalExpansion: false});

        // Green field + label
        this.__widgets.fieldGreen = new photonui.Slider({
            min: 0,
            max: 255,
            decimalDigits: 0
        });

        this.__widgets.labelGreen = new photonui.Label({
            text: _("Green:"),
            forInput: this.__widgets.fieldGreen
        });

        this.__widgets.grid.addChild(this.__widgets.labelGreen, {gridX: 0, gridY: 1, verticalExpansion: false});
        this.__widgets.grid.addChild(this.__widgets.fieldGreen, {gridX: 1, gridY: 1, verticalExpansion: false});

        // Blue field + label
        this.__widgets.fieldBlue = new photonui.Slider({
            min: 0,
            max: 255,
            decimalDigits: 0
        });

        this.__widgets.labelBlue = new photonui.Label({
            text: _("Blue:"),
            forInput: this.__widgets.fieldBlue
        });

        this.__widgets.grid.addChild(this.__widgets.labelBlue, {gridX: 0, gridY: 2, verticalExpansion: false});
        this.__widgets.grid.addChild(this.__widgets.fieldBlue, {gridX: 1, gridY: 2, verticalExpansion: false});

        // Separator
        this.__widgets.separator2 = new photonui.Separator();
        this.__widgets.grid.addChild(this.__widgets.separator2, {gridX: 0, gridY: 3, verticalExpansion: false, gridWidth: 2});

        // Hue field + label
        this.__widgets.fieldHue = new photonui.Slider({
            min: 0,
            max: 360,
            decimalDigits: 0
        });

        this.__widgets.labelHue = new photonui.Label({
            text: _("Hue:"),
            forInput: this.__widgets.fieldHue
        });

        this.__widgets.grid.addChild(this.__widgets.labelHue, {gridX: 0, gridY: 4, verticalExpansion: false});
        this.__widgets.grid.addChild(this.__widgets.fieldHue, {gridX: 1, gridY: 4, verticalExpansion: false});

        // Saturation field + label
        this.__widgets.fieldSaturation = new photonui.Slider({
            min: 0,
            max: 100,
            decimalDigits: 0
        });

        this.__widgets.labelSaturation = new photonui.Label({
            text: _("Saturation:"),
            forInput: this.__widgets.fieldSaturation
        });

        this.__widgets.grid.addChild(this.__widgets.labelSaturation, {gridX: 0, gridY: 5, verticalExpansion: false});
        this.__widgets.grid.addChild(this.__widgets.fieldSaturation, {gridX: 1, gridY: 5, verticalExpansion: false});

        // Brightness field + label
        this.__widgets.fieldBrightness = new photonui.Slider({
            min: 0,
            max: 100,
            decimalDigits: 0
        });

        this.__widgets.labelBrightness = new photonui.Label({
            text: _("Brightness:"),
            forInput: this.__widgets.fieldBrightness
        });

        this.__widgets.grid.addChild(this.__widgets.labelBrightness, {gridX: 0, gridY: 6, verticalExpansion: false});
        this.__widgets.grid.addChild(this.__widgets.fieldBrightness, {gridX: 1, gridY: 6, verticalExpansion: false});

        // == Dialog Buttons ==
        this.__widgets.buttonOk = new photonui.Button({text: _("Ok")});
        if (photonui.FAIcon) this.__widgets.buttonOk.leftIcon = new photonui.FAIcon("fa-check");

        this.__widgets.buttonCancel = new photonui.Button({text: _("Cancel")});
        this.buttons = [this.__widgets.buttonOk, this.__widgets.buttonCancel];

        if (photonui.FAIcon) this.__widgets.buttonCancel.leftIcon = new photonui.FAIcon("fa-times");

        // == Bindings ==
        this.__widgets.colorPalette.color = this.__widgets.colorPicker.color;

        this.__widgets.colorPicker.color.registerCallback("colorpickerdialog.colorPicker.value-changed", "value-changed", function(color) {
            this.__widgets.fieldRed.value = color.red;
            this.__widgets.fieldGreen.value = color.green;
            this.__widgets.fieldBlue.value = color.blue;
            this.__widgets.fieldHue.value = color.hue;
            this.__widgets.fieldSaturation.value = color.saturation;
            this.__widgets.fieldBrightness.value = color.brightness;
        }, this);

        this.__widgets.fieldRed.registerCallback("colorpickerdialog.fieldRed.value-changed", "value-changed", function(widget, value) {
            this.__widgets.colorPicker.color.red = value;
        }, this);

        this.__widgets.fieldGreen.registerCallback("colorpickerdialog.fieldGreen.value-changed", "value-changed", function(widget, value) {
            this.__widgets.colorPicker.color.green = value;
        }, this);

        this.__widgets.fieldBlue.registerCallback("colorpickerdialog.fieldBlue.value-changed", "value-changed", function(widget, value) {
            this.__widgets.colorPicker.color.blue = value;
        }, this);

        this.__widgets.fieldHue.registerCallback("colorpickerdialog.fieldHue.value-changed", "value-changed", function(widget, value) {
            this.__widgets.colorPicker.color.hue = value;
        }, this);

        this.__widgets.fieldSaturation.registerCallback("colorpickerdialog.fieldSaturation.value-changed", "value-changed", function(widget, value) {
            this.__widgets.colorPicker.color.saturation = value;
        }, this);

        this.__widgets.fieldBrightness.registerCallback("colorpickerdialog.fieldBrightness.value-changed", "value-changed", function(widget, value) {
            this.__widgets.colorPicker.color.brightness = value;
        }, this);

        this.__widgets.buttonOk.registerCallback("colorpickerdialog.buttonOk.click", "click", this.__onValidate, this);
        this.__widgets.buttonCancel.registerCallback("colorpickerdialog.buttonCancel.click", "click", this.__onCancel, this);
        this.registerCallback("colorpickerdialog.close", "close-button-clicked", this.__onCancel, this);
    },

    //////////////////////////////////////////
    // Internal Events Callbacks            //
    //////////////////////////////////////////

    /**
     * @method __onCancel
     * @private
     */
    __onCancel: function() {
        this.__widgets.colorPicker.color.setHSB(
                this._color.hue,
                this._color.saturation,
                this._color.brightness
        );
        this.hide();
    },

    /**
     * @method __onValidate
     * @private
     */
    __onValidate: function() {
        this._color.setHSB(
                this.__widgets.colorPicker.color.hue,
                this.__widgets.colorPicker.color.saturation,
                this.__widgets.colorPicker.color.brightness
        );
        this.hide();
        this._callCallbacks("value-changed", [this.color]);
    },

    /**
     * @method __onColorChanged
     * @private
     */
    __onColorChanged: function() {
        this.__widgets.colorPicker.color.setHSB(
                this._color.hue,
                this._color.saturation,
                this._color.brightness
        );
    }
});
<|endoftext|>


<commit_before>function array_unique( array ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
    // +      input by: duncan
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_unique(['Kevin','Kevin','van','Zonneveld','Kevin']);
    // *     returns 1: ['Kevin','van','Zonneveld']
    // *     example 2: array_unique({'a': 'green', 0: 'red', 'b': 'green', 1: 'blue', 2: 'red'});
    // *     returns 2: {'a': 'Kevin', 0: 'van', 1: 'Zonneveld'}

    var p, i, j, tmp_arr = array;
    for(i = tmp_arr.length; i;){
        for(p = --i; p > 0;){
            if(tmp_arr[i] === tmp_arr[--p]){
                for(j = p; --p && tmp_arr[i] === tmp_arr[p];);
                i -= tmp_arr.splice(p + 1, j - p).length;
            }
        }
    }

    return tmp_arr;
}<commit_msg>Fixed numerous bugs surfacing after improved tester<commit_after>function array_unique( array ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
    // +      input by: duncan
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_unique(['Kevin','Kevin','van','Zonneveld','Kevin']);
    // *     returns 1: ['Kevin','van','Zonneveld']
    // *     example 2: array_unique({'a': 'green', 0: 'red', 'b': 'green', 1: 'blue', 2: 'red'});
    // *     returns 2: {'a': 'green', 0: 'red', 1: 'blue'}

    var key = '', tmp_arr1 = {}, tmp_arr2 = {};
    tmp_arr1 = array;

	var __array_search = function ( needle, haystack, strict ) {
	    var strict = !!strict;
	    for(var fkey in haystack){
	        if( (strict && haystack[fkey] === needle) || (!strict && haystack[fkey] == needle) ){
	            return fkey;
	        }
	    }
	    return false;
	}

    for (key in tmp_arr1) {
        val = tmp_arr1[key];
        if (false === __array_search(val, tmp_arr2)) {
            tmp_arr2[key] = val;
        }

        delete tmp_arr1[key];
    }

    return tmp_arr2;
}<|endoftext|>


<commit_before>/**
 * Created with PyCharm.
 * User: Andrey Smirnov
 * Date: 26.10.13
 * Time: 15:07
 */

(function ($, undefined) {
    $.fn.extend({
        create_list: function (list) {
            var res = [];
            for (var i = 0; i < list.length; i++) {
                var audio = list[i];
                res.push( '

'+audio.name+'

');
            }
            var container = $('#audio_list');
            container.html(res.join(''));
            container.find('.favourite').click(function(){
               if(!$(this).hasClass('active')){
                  $(this).addClass('active');
                  var parent = $(this).closest('.song_container'),
                      mood = $('.mood-icon').attr('mood');
                  httpGet('/rate?song='+ parent.attr("song") + '&mood=' + mood + '&rating=1');
               }
            });
            container.find('.add-to-my').click(function(){
               if(!$(this).hasClass('active')){
                  $(this).addClass('active');
                  var parent = $(this).closest('.song_container');
                  VK.Api.call('audio.add', {
                     "audio_id": parent.attr("song"),
                     "owner_id": parent.attr("owner")
                  }, function (r) {
                  });
               }
            });
            container.find('.to-friends').click(function(){
               if(!$(this).hasClass('active')){
                  var parent = $(this).closest('.song_container');
                  VK.Api.call('wall.post', {
                     "friends_only": 1,
                     "message": "Эта песня подошла мне под настроение. Найти помогло приложение MoodMusic",
                     "attachments": ["audio", parent.attr("owner"), "_", parent.attr("song"), window.location].join('')
                  }, function (r) {
                  });
                  $(this).hide();
               }
            });
        }
    })
    }(jQuery));

<commit_msg>Add-button fixed<commit_after>/**
 * Created with PyCharm.
 * User: Andrey Smirnov
 * Date: 26.10.13
 * Time: 15:07
 */

(function ($, undefined) {
    $.fn.extend({
        create_list: function (list, noShow) {
            var res = [];
            for (var i = 0; i < list.length; i++) {
                var audio = list[i];
                res.push( '

');
                if (noShow!='favotite')
                    res.push( '
 	');
                res.push( '
'+audio.name+'
	');
                if (noShow!='add')
                    res.push('
 	');
                res.push( '
 	');
                res.push( '

');
            }
            var container = $('#audio_list');
            container.html(res.join(''));
            container.find('.favourite').click(function(){
               if(!$(this).hasClass('active')){
                  $(this).addClass('active');
                  var parent = $(this).closest('.song_container'),
                      mood = $('.mood-icon').attr('mood');
                  httpGet('/rate?song='+ parent.attr("song") + '&mood=' + mood + '&rating=1');
               }
            });
            container.find('.add-to-my').click(function(){
               if(!$(this).hasClass('active')){
                  $(this).addClass('active');
                  var parent = $(this).closest('.song_container');
                  VK.Api.call('audio.add', {
                     "audio_id": parent.attr("song"),
                     "owner_id": parent.attr("owner")
                  }, function (r) {
                  });
               }
            });
            container.find('.to-friends').click(function(){
               if(!$(this).hasClass('active')){
                  var parent = $(this).closest('.song_container');
                  VK.Api.call('wall.post', {
                     "friends_only": 1,
                     "message": "Эта песня подошла мне под настроение. Найти помогло приложение MoodMusic",
                     "attachments": ["audio", parent.attr("owner"), "_", parent.attr("song"), window.location].join('')
                  }, function (r) {
                  });
                  $(this).hide();
               }
            });
        }
    })
    }(jQuery));

<|endoftext|>


<commit_before>"use babel";

import { CompositeDisposable } from "atom";
import { isObservableMap, isObservableProp, isComputedProp } from "mobx";
import store, { Store } from "./../../lib/store";
import KernelTransport from "./../../lib/kernel-transport";
import Kernel from "./../../lib/kernel";
import MarkerStore from "./../../lib/store/markers";
const commutable = require("@nteract/commutable");

describe("Store initialize", () => {
  it("should correctly initialize store", () => {
    expect(store.subscriptions instanceof CompositeDisposable).toBeTruthy();
    expect(store.markers instanceof MarkerStore).toBeTruthy();
    expect(store.runningKernels).toEqual([]);
    expect(isObservableMap(store.startingKernels)).toBeTruthy();
    expect(isObservableMap(store.kernelMapping)).toBeTruthy();
    expect(isObservableProp(store, "editor")).toBeTruthy();
    expect(isObservableProp(store, "grammar")).toBeTruthy();
    expect(isComputedProp(store, "kernel")).toBeTruthy();
    expect(isComputedProp(store, "notebook")).toBeTruthy();
  });
});

describe("Store", () => {
  beforeEach(() => {
    store.subscriptions = new CompositeDisposable();
    store.startingKernels = store.kernelMapping = new Map();
    store.runningKernels = [];
    store.editor = null;
    store.grammar = null;
  });

  describe("setGrammar", () => {
    it("should set grammar", () => {
      const editor = atom.workspace.buildTextEditor();
      const grammar = editor.getGrammar();
      expect(grammar.name).toBe("Null Grammar");
      expect(store.editor).toBeNull();
      store.setGrammar(editor);
      expect(store.grammar).toEqual(grammar);
    });

    it("should set grammar to null if editor is null", () => {
      store.setGrammar(null);
      expect(store.grammar).toBeNull();
    });

    it("should set grammar to null if editor is undefined", () => {
      store.setGrammar(undefined);
      expect(store.grammar).toBeNull();
    });

    it("should set non multi language grammar", () => {
      const grammar = { scopeName: "source.python", name: "Python" };
      const editor = { getGrammar: () => grammar };

      store.setGrammar(editor);
      expect(store.grammar).toEqual(grammar);
      expect(store.grammar.name.toLowerCase()).toBe("python");
    });

    it("should set multi language grammar inside code block", () => {
      const editor = {
        getGrammar: () => {
          return { scopeName: "source.gfm", name: "GitHub Markdown" };
        },
        getCursorBufferPosition: () => {},
        scopeDescriptorForBufferPosition: () => {
          return {
            getScopesArray: () => [
              "source.gfm",
              "markup.code.python.gfm",
              "source.embedded.python"
            ]
          };
        }
      };

      const pythonGrammar = { scopeName: "source.python", name: "Python" };
      spyOn(atom.grammars, "grammarForScopeName").and.returnValue(
        pythonGrammar
      );

      store.setGrammar(editor);
      expect(store.grammar).toEqual(pythonGrammar);
      expect(store.grammar.name.toLowerCase()).toBe("python");
    });

    it("should set multi language grammar outside code block", () => {
      const grammar = { scopeName: "source.gfm", name: "GitHub Markdown" };
      const editor = {
        getGrammar: () => grammar,
        getCursorBufferPosition: () => {},
        scopeDescriptorForBufferPosition: () => {
          return {
            getScopesArray: () => ["source.gfm", "markup.code.python.gfm"]
          };
        }
      };

      store.setGrammar(editor);
      expect(store.grammar).toEqual(grammar);
      expect(store.grammar.name.toLowerCase()).toBe("github markdown");
    });
  });

  describe("startKernel", () => {
    it("should add display name to startingKernels", () => {
      const display_name = "null grammar";
      expect(store.startingKernels.get(display_name)).toBeFalsy();
      store.startKernel(display_name);
      expect(store.startingKernels.get(display_name)).toBeTruthy();
    });
  });

  describe("newKernel", () => {
    it("should store kernel", () => {
      const editor = { getGrammar: () => ({ scopeName: "source.python" }) };
      const kernel = { kernelSpec: { display_name: "Python 3" } };
      spyOn(store.startingKernels, "delete");

      store.newKernel(kernel, "foo.py", editor);
      expect(store.kernelMapping.size).toBe(1);
      expect(store.kernelMapping.get("foo.py")).toEqual(kernel);
      expect(store.runningKernels).toEqual([kernel]);
      expect(store.startingKernels.delete).toHaveBeenCalledWith("Python 3");
    });

    it("should store kernel for multilanguage file", () => {
      const editor = { getGrammar: () => ({ scopeName: "source.gfm" }) };
      const kernel = { kernelSpec: { display_name: "Python 3" } };
      const kernel2 = { kernelSpec: { display_name: "Javascript" } };
      spyOn(store.startingKernels, "delete");

      store.newKernel(kernel, "foo.md", editor, { name: "python" });
      expect(store.kernelMapping.size).toBe(1);
      expect(store.kernelMapping.get("foo.md").toJS()).toEqual(
        new Map([["python", kernel]])
      );
      expect(store.runningKernels).toEqual([kernel]);
      expect(store.startingKernels.delete).toHaveBeenCalledWith("Python 3");

      store.newKernel(kernel2, "foo.md", editor, { name: "javascript" });
      expect(store.kernelMapping.size).toBe(1);
      expect(store.kernelMapping.get("foo.md").toJS()).toEqual(
        new Map([["python", kernel], ["javascript", kernel2]])
      );

      expect(store.runningKernels).toEqual([kernel, kernel2]);
      expect(store.startingKernels.delete).toHaveBeenCalledWith("Javascript");
    });
  });

  describe("deleteKernel", () => {
    it("should delete kernel", () => {
      const kernel1 = new Kernel(
        new KernelTransport(
          {
            display_name: "Python 3",
            language: "python"
          },
          { name: "python" }
        )
      );
      const kernel2 = new Kernel(
        new KernelTransport(
          {
            display_name: "Python 3",
            language: "python"
          },
          { name: "python" }
        )
      );
      const kernel3 = new Kernel(
        new KernelTransport(
          {
            display_name: "JS",
            language: "Javascript"
          },
          { name: "javascript" }
        )
      );

      store.runningKernels = [kernel1, kernel2, kernel3];
      store.kernelMapping = new Map([
        ["foo.py", kernel1],
        ["bar.py", kernel1],
        ["baz.py", kernel2],
        ["foo.md", new Map([["python", kernel1], ["javascript", kernel3]])]
      ]);

      const kernelFiles = new Set(["foo.py", "bar.py", "foo.md"]);
      expect(new Set(store.getFilesForKernel(kernel1))).toEqual(kernelFiles);
      expect(store.kernelMapping.size).toBe(4);
      store.deleteKernel(kernel1);
      expect(store.kernelMapping.size).toBe(2);
      expect(store.kernelMapping.get("baz.py")).toEqual(kernel2);
      expect(store.kernelMapping.get("foo.md").toJS()).toEqual(
        new Map([["javascript", kernel3]])
      );
      expect(store.runningKernels).toEqual([kernel2, kernel3]);
    });
  });

  describe("getFilesForKernel", () => {
    it("should return files related to kernel", () => {
      const kernel1 = new Kernel(
        new KernelTransport(
          {
            display_name: "Python 3",
            language: "python"
          },
          { name: "python" }
        )
      );
      const kernel2 = new Kernel(
        new KernelTransport(
          {
            display_name: "Python 3",
            language: "python"
          },
          { name: "python" }
        )
      );

      const kernel3 = new Kernel(
        new KernelTransport(
          {
            display_name: "JS",
            language: "Javascript"
          },
          { name: "javascript" }
        )
      );

      store.kernelMapping = new Map([
        ["foo.py", kernel1],
        ["bar.py", kernel1],
        ["baz.py", kernel2],
        ["foo.md", new Map([["python", kernel1], ["javascript", kernel2]])]
      ]);

      expect(store.getFilesForKernel(kernel1)).toEqual([
        "foo.py",
        "bar.py",
        "foo.md"
      ]);
    });
  });

  describe("updateEditor", () => {
    it("should update editor", () => {
      spyOn(store, "setGrammar").and.callThrough();
      expect(store.editor).toBeNull();
      const editor = atom.workspace.buildTextEditor();
      store.updateEditor(editor);
      expect(store.editor).toBe(editor);
      expect(store.setGrammar).toHaveBeenCalledWith(editor);
      expect(store.grammar).toEqual(editor.getGrammar());
      expect(store.grammar.name.toLowerCase()).toBe("null grammar");
    });
  });

  describe("dispose", () => {
    it("should dispose kernels and subscriptions", () => {
      spyOn(store.subscriptions, "dispose");
      spyOn(store.markers, "clear");
      const kernel1 = jasmine.createSpyObj("kernel1", ["destroy"]);
      const kernel2 = jasmine.createSpyObj("kernel2", ["destroy"]);
      store.runningKernels = [kernel1, kernel2];
      store.dispose();
      expect(store.runningKernels.length).toEqual(0);
      expect(store.kernelMapping.size).toBe(0);
      expect(kernel1.destroy).toHaveBeenCalled();
      expect(kernel2.destroy).toHaveBeenCalled();
      expect(store.subscriptions.dispose).toHaveBeenCalled();
      expect(store.markers.clear).toHaveBeenCalled();
    });
  });

  describe("get filePath", () => {
    it("should return null if no editor", () => {
      expect(store.filePath).toBeNull();
    });

    it("should return file path", () => {
      store.editor = { getPath: () => "foo.py" };
      expect(store.filePath).toBe("foo.py");
    });
  });

  describe("get notebook", () => {
    // runAsync is borrowed and modified from link below.
    // https://github.com/jasmine/jasmine/issues/923#issuecomment-169634461
    // This is duplicated from code-manager-spec.js
    function waitAsync(fn) {
      return done => {
        fn().then(done, function rejected(e) {
          fail(e);
          done();
        });
      };
    }
    let editor;
    beforeEach(
      waitAsync(async () => {
        editor = atom.workspace.buildTextEditor();
        await atom.packages.activatePackage("language-python");
        editor.setGrammar(atom.grammars.grammarForScopeName("source.python"));
      })
    );

    it("should return null if no editor", () => {
      expect(store.notebook).toBeNull();
    });

    it("should return a single cell notebook for empty file", () => {
      store.updateEditor(editor);
      // Build a notebook with one code cell.
      let codeCell = commutable.emptyCodeCell.set("source", "");
      const nb = commutable.appendCellToNotebook(
        commutable.emptyNotebook,
        codeCell
      );
      expect(store.notebook).toEqual(commutable.toJS(nb));
    });

    it("should return a fully-fledged notebook when the file isn't empty", () => {
      const source1 = 'print("Hola World! I <3 ZMQ!")\n';
      const source2 = "2 + 2\n";
      editor.insertText("# %%\n");
      editor.insertText(source1);
      editor.insertText("# %%\n");
      editor.insertText(source2);
      store.updateEditor(editor);
      // Build a notebook with these two cells.
      const codeCell1 = commutable.emptyCodeCell.set("source", source1);
      const codeCell2 = commutable.emptyCodeCell.set("source", source2);
      // The outputted notebook will have three cells because currently a cell
      // is always created before the first `# %%`
      let nb = commutable.appendCellToNotebook(
        commutable.monocellNotebook,
        codeCell1
      );
      nb = commutable.appendCellToNotebook(nb, codeCell2);
      expect(store.notebook).toEqual(commutable.toJS(nb));
    });
  });

  describe("get kernel", () => {
    it("should return null if no editor", () => {
      expect(store.kernel).toBeNull();
    });

    it("should return null if editor isn't saved", () => {
      store.editor = { getPath: () => {} };
      expect(store.kernel).toBeNull();
    });

    it("should return kernel", () => {
      store.editor = { getPath: () => "foo.py" };
      const kernel = new Kernel(
        new KernelTransport({
          display_name: "Python 3",
          language: "python"
        })
      );
      store.kernelMapping = new Map([["foo.py", kernel]]);
      expect(store.kernel).toEqual(kernel);
    });

    it("should return null if no kernel for file", () => {
      store.editor = { getPath: () => "foo.py" };
      const kernel = new Kernel(
        new KernelTransport({
          display_name: "Python 3",
          language: "python"
        })
      );
      store.kernelMapping = new Map([["bar.py", kernel]]);
      expect(store.kernel).toBeUndefined();
    });

    it("should return the correct kernel for multilanguage files", () => {
      store.editor = { getPath: () => "foo.md" };
      const kernel = new Kernel(
        new KernelTransport({
          display_name: "Python 3",
          language: "python"
        })
      );
      store.kernelMapping = new Map([
        ["foo.md", new Map([["python", kernel]])]
      ]);
      store.grammar = { name: "python" };
      expect(store.kernel).toEqual(kernel);
    });
  });

  describe("global mode", () => {
    let mockStore, kernelSpec, grammar, editor1, editor2, kernel1;

    beforeEach(() => {
      atom.config.set("Hydrogen.globalMode", true);
      mockStore = new Store();
      kernelSpec = { language: "python", display_name: "Python 3" };
      grammar = {
        scopeName: "source.python",
        name: "Python"
      };

      editor1 = atom.workspace.buildTextEditor();
      editor2 = atom.workspace.buildTextEditor();
      spyOn(editor1, "getPath").and.returnValue("foo.py");
      spyOn(editor2, "getPath").and.returnValue("bar.py");
      spyOn(editor1, "getGrammar").and.returnValue(grammar);
      spyOn(editor2, "getGrammar").and.returnValue(grammar);
      kernel1 = new Kernel(new KernelTransport(kernelSpec, grammar));
    });

    afterEach(() => {
      atom.config.set("Hydrogen.globalMode", false);
    });

    it("should use the same kernel if two files have the same grammar", () => {
      mockStore.updateEditor(editor1);
      mockStore.newKernel(kernel1, editor1.getPath(), editor1);
      expect(mockStore.kernel).toEqual(kernel1);

      mockStore.updateEditor(editor2);
      expect(mockStore.kernel).toEqual(kernel1);

      // store should still keep track of all filePaths
      expect(mockStore.filePaths).toEqual(["foo.py", "bar.py"]);
      expect(mockStore.getFilesForKernel(mockStore.kernel)).toEqual([
        "foo.py",
        "bar.py"
      ]);
    });
  });
});
<commit_msg>Add markdown export test<commit_after>"use babel";

import { CompositeDisposable } from "atom";
import { isObservableMap, isObservableProp, isComputedProp } from "mobx";
import store, { Store } from "./../../lib/store";
import KernelTransport from "./../../lib/kernel-transport";
import Kernel from "./../../lib/kernel";
import MarkerStore from "./../../lib/store/markers";
const commutable = require("@nteract/commutable");

describe("Store initialize", () => {
  it("should correctly initialize store", () => {
    expect(store.subscriptions instanceof CompositeDisposable).toBeTruthy();
    expect(store.markers instanceof MarkerStore).toBeTruthy();
    expect(store.runningKernels).toEqual([]);
    expect(isObservableMap(store.startingKernels)).toBeTruthy();
    expect(isObservableMap(store.kernelMapping)).toBeTruthy();
    expect(isObservableProp(store, "editor")).toBeTruthy();
    expect(isObservableProp(store, "grammar")).toBeTruthy();
    expect(isComputedProp(store, "kernel")).toBeTruthy();
    expect(isComputedProp(store, "notebook")).toBeTruthy();
  });
});

describe("Store", () => {
  beforeEach(() => {
    store.subscriptions = new CompositeDisposable();
    store.startingKernels = store.kernelMapping = new Map();
    store.runningKernels = [];
    store.editor = null;
    store.grammar = null;
  });

  describe("setGrammar", () => {
    it("should set grammar", () => {
      const editor = atom.workspace.buildTextEditor();
      const grammar = editor.getGrammar();
      expect(grammar.name).toBe("Null Grammar");
      expect(store.editor).toBeNull();
      store.setGrammar(editor);
      expect(store.grammar).toEqual(grammar);
    });

    it("should set grammar to null if editor is null", () => {
      store.setGrammar(null);
      expect(store.grammar).toBeNull();
    });

    it("should set grammar to null if editor is undefined", () => {
      store.setGrammar(undefined);
      expect(store.grammar).toBeNull();
    });

    it("should set non multi language grammar", () => {
      const grammar = { scopeName: "source.python", name: "Python" };
      const editor = { getGrammar: () => grammar };

      store.setGrammar(editor);
      expect(store.grammar).toEqual(grammar);
      expect(store.grammar.name.toLowerCase()).toBe("python");
    });

    it("should set multi language grammar inside code block", () => {
      const editor = {
        getGrammar: () => {
          return { scopeName: "source.gfm", name: "GitHub Markdown" };
        },
        getCursorBufferPosition: () => {},
        scopeDescriptorForBufferPosition: () => {
          return {
            getScopesArray: () => [
              "source.gfm",
              "markup.code.python.gfm",
              "source.embedded.python"
            ]
          };
        }
      };

      const pythonGrammar = { scopeName: "source.python", name: "Python" };
      spyOn(atom.grammars, "grammarForScopeName").and.returnValue(
        pythonGrammar
      );

      store.setGrammar(editor);
      expect(store.grammar).toEqual(pythonGrammar);
      expect(store.grammar.name.toLowerCase()).toBe("python");
    });

    it("should set multi language grammar outside code block", () => {
      const grammar = { scopeName: "source.gfm", name: "GitHub Markdown" };
      const editor = {
        getGrammar: () => grammar,
        getCursorBufferPosition: () => {},
        scopeDescriptorForBufferPosition: () => {
          return {
            getScopesArray: () => ["source.gfm", "markup.code.python.gfm"]
          };
        }
      };

      store.setGrammar(editor);
      expect(store.grammar).toEqual(grammar);
      expect(store.grammar.name.toLowerCase()).toBe("github markdown");
    });
  });

  describe("startKernel", () => {
    it("should add display name to startingKernels", () => {
      const display_name = "null grammar";
      expect(store.startingKernels.get(display_name)).toBeFalsy();
      store.startKernel(display_name);
      expect(store.startingKernels.get(display_name)).toBeTruthy();
    });
  });

  describe("newKernel", () => {
    it("should store kernel", () => {
      const editor = { getGrammar: () => ({ scopeName: "source.python" }) };
      const kernel = { kernelSpec: { display_name: "Python 3" } };
      spyOn(store.startingKernels, "delete");

      store.newKernel(kernel, "foo.py", editor);
      expect(store.kernelMapping.size).toBe(1);
      expect(store.kernelMapping.get("foo.py")).toEqual(kernel);
      expect(store.runningKernels).toEqual([kernel]);
      expect(store.startingKernels.delete).toHaveBeenCalledWith("Python 3");
    });

    it("should store kernel for multilanguage file", () => {
      const editor = { getGrammar: () => ({ scopeName: "source.gfm" }) };
      const kernel = { kernelSpec: { display_name: "Python 3" } };
      const kernel2 = { kernelSpec: { display_name: "Javascript" } };
      spyOn(store.startingKernels, "delete");

      store.newKernel(kernel, "foo.md", editor, { name: "python" });
      expect(store.kernelMapping.size).toBe(1);
      expect(store.kernelMapping.get("foo.md").toJS()).toEqual(
        new Map([["python", kernel]])
      );
      expect(store.runningKernels).toEqual([kernel]);
      expect(store.startingKernels.delete).toHaveBeenCalledWith("Python 3");

      store.newKernel(kernel2, "foo.md", editor, { name: "javascript" });
      expect(store.kernelMapping.size).toBe(1);
      expect(store.kernelMapping.get("foo.md").toJS()).toEqual(
        new Map([["python", kernel], ["javascript", kernel2]])
      );

      expect(store.runningKernels).toEqual([kernel, kernel2]);
      expect(store.startingKernels.delete).toHaveBeenCalledWith("Javascript");
    });
  });

  describe("deleteKernel", () => {
    it("should delete kernel", () => {
      const kernel1 = new Kernel(
        new KernelTransport(
          {
            display_name: "Python 3",
            language: "python"
          },
          { name: "python" }
        )
      );
      const kernel2 = new Kernel(
        new KernelTransport(
          {
            display_name: "Python 3",
            language: "python"
          },
          { name: "python" }
        )
      );
      const kernel3 = new Kernel(
        new KernelTransport(
          {
            display_name: "JS",
            language: "Javascript"
          },
          { name: "javascript" }
        )
      );

      store.runningKernels = [kernel1, kernel2, kernel3];
      store.kernelMapping = new Map([
        ["foo.py", kernel1],
        ["bar.py", kernel1],
        ["baz.py", kernel2],
        ["foo.md", new Map([["python", kernel1], ["javascript", kernel3]])]
      ]);

      const kernelFiles = new Set(["foo.py", "bar.py", "foo.md"]);
      expect(new Set(store.getFilesForKernel(kernel1))).toEqual(kernelFiles);
      expect(store.kernelMapping.size).toBe(4);
      store.deleteKernel(kernel1);
      expect(store.kernelMapping.size).toBe(2);
      expect(store.kernelMapping.get("baz.py")).toEqual(kernel2);
      expect(store.kernelMapping.get("foo.md").toJS()).toEqual(
        new Map([["javascript", kernel3]])
      );
      expect(store.runningKernels).toEqual([kernel2, kernel3]);
    });
  });

  describe("getFilesForKernel", () => {
    it("should return files related to kernel", () => {
      const kernel1 = new Kernel(
        new KernelTransport(
          {
            display_name: "Python 3",
            language: "python"
          },
          { name: "python" }
        )
      );
      const kernel2 = new Kernel(
        new KernelTransport(
          {
            display_name: "Python 3",
            language: "python"
          },
          { name: "python" }
        )
      );

      const kernel3 = new Kernel(
        new KernelTransport(
          {
            display_name: "JS",
            language: "Javascript"
          },
          { name: "javascript" }
        )
      );

      store.kernelMapping = new Map([
        ["foo.py", kernel1],
        ["bar.py", kernel1],
        ["baz.py", kernel2],
        ["foo.md", new Map([["python", kernel1], ["javascript", kernel2]])]
      ]);

      expect(store.getFilesForKernel(kernel1)).toEqual([
        "foo.py",
        "bar.py",
        "foo.md"
      ]);
    });
  });

  describe("updateEditor", () => {
    it("should update editor", () => {
      spyOn(store, "setGrammar").and.callThrough();
      expect(store.editor).toBeNull();
      const editor = atom.workspace.buildTextEditor();
      store.updateEditor(editor);
      expect(store.editor).toBe(editor);
      expect(store.setGrammar).toHaveBeenCalledWith(editor);
      expect(store.grammar).toEqual(editor.getGrammar());
      expect(store.grammar.name.toLowerCase()).toBe("null grammar");
    });
  });

  describe("dispose", () => {
    it("should dispose kernels and subscriptions", () => {
      spyOn(store.subscriptions, "dispose");
      spyOn(store.markers, "clear");
      const kernel1 = jasmine.createSpyObj("kernel1", ["destroy"]);
      const kernel2 = jasmine.createSpyObj("kernel2", ["destroy"]);
      store.runningKernels = [kernel1, kernel2];
      store.dispose();
      expect(store.runningKernels.length).toEqual(0);
      expect(store.kernelMapping.size).toBe(0);
      expect(kernel1.destroy).toHaveBeenCalled();
      expect(kernel2.destroy).toHaveBeenCalled();
      expect(store.subscriptions.dispose).toHaveBeenCalled();
      expect(store.markers.clear).toHaveBeenCalled();
    });
  });

  describe("get filePath", () => {
    it("should return null if no editor", () => {
      expect(store.filePath).toBeNull();
    });

    it("should return file path", () => {
      store.editor = { getPath: () => "foo.py" };
      expect(store.filePath).toBe("foo.py");
    });
  });

  describe("get notebook", () => {
    // runAsync is borrowed and modified from link below.
    // https://github.com/jasmine/jasmine/issues/923#issuecomment-169634461
    // This is duplicated from code-manager-spec.js
    function waitAsync(fn) {
      return done => {
        fn().then(done, function rejected(e) {
          fail(e);
          done();
        });
      };
    }
    let editor;
    beforeEach(
      waitAsync(async () => {
        editor = atom.workspace.buildTextEditor();
        await atom.packages.activatePackage("language-python");
        editor.setGrammar(atom.grammars.grammarForScopeName("source.python"));
      })
    );

    it("should return null if no editor", () => {
      expect(store.notebook).toBeNull();
    });

    it("should return a single cell notebook for empty file", () => {
      store.updateEditor(editor);
      // Build a notebook with one code cell.
      let codeCell = commutable.emptyCodeCell.set("source", "");
      const nb = commutable.appendCellToNotebook(
        commutable.emptyNotebook,
        codeCell
      );
      expect(store.notebook).toEqual(commutable.toJS(nb));
    });

    it("should return a fully-fledged notebook when the file isn't empty", () => {
      const source1 = 'print("Hola World! I <3 ZMQ!")\n';
      const source2 = "2 + 2\n";
      editor.setText(`# %%\n${source1}# %%\n${source2}`);
      store.updateEditor(editor);
      const codeCell1 = commutable.emptyCodeCell.set("source", source1);
      const codeCell2 = commutable.emptyCodeCell.set("source", source2);
      // The outputted notebook will have three cells because currently a cell
      // is always created before the first `# %%`
      let nb = commutable.appendCellToNotebook(
        commutable.monocellNotebook,
        codeCell1
      );
      nb = commutable.appendCellToNotebook(nb, codeCell2);
      expect(store.notebook).toEqual(commutable.toJS(nb));
    });

    it("should export markdown to markdown cells", () => {
      const source1 = 'print("Hola World! I <3 ZMQ!")\n';
      const source2 = "2 + 2\n";
      editor.setText(`# %%\n${source1}# %% markdown\n${source2}`);
      store.updateEditor(editor);
      const codeCell = commutable.emptyCodeCell.set("source", source1);
      const markdownCell = commutable.emptyMarkdownCell.set("source", source2);
      // The outputted notebook will have three cells because currently a cell
      // is always created before the first `# %%`
      let nb = commutable.appendCellToNotebook(
        commutable.monocellNotebook,
        codeCell
      );
      nb = commutable.appendCellToNotebook(nb, markdownCell);
      expect(store.notebook).toEqual(commutable.toJS(nb));
    });
  });

  describe("get kernel", () => {
    it("should return null if no editor", () => {
      expect(store.kernel).toBeNull();
    });

    it("should return null if editor isn't saved", () => {
      store.editor = { getPath: () => {} };
      expect(store.kernel).toBeNull();
    });

    it("should return kernel", () => {
      store.editor = { getPath: () => "foo.py" };
      const kernel = new Kernel(
        new KernelTransport({
          display_name: "Python 3",
          language: "python"
        })
      );
      store.kernelMapping = new Map([["foo.py", kernel]]);
      expect(store.kernel).toEqual(kernel);
    });

    it("should return null if no kernel for file", () => {
      store.editor = { getPath: () => "foo.py" };
      const kernel = new Kernel(
        new KernelTransport({
          display_name: "Python 3",
          language: "python"
        })
      );
      store.kernelMapping = new Map([["bar.py", kernel]]);
      expect(store.kernel).toBeUndefined();
    });

    it("should return the correct kernel for multilanguage files", () => {
      store.editor = { getPath: () => "foo.md" };
      const kernel = new Kernel(
        new KernelTransport({
          display_name: "Python 3",
          language: "python"
        })
      );
      store.kernelMapping = new Map([
        ["foo.md", new Map([["python", kernel]])]
      ]);
      store.grammar = { name: "python" };
      expect(store.kernel).toEqual(kernel);
    });
  });

  describe("global mode", () => {
    let mockStore, kernelSpec, grammar, editor1, editor2, kernel1;

    beforeEach(() => {
      atom.config.set("Hydrogen.globalMode", true);
      mockStore = new Store();
      kernelSpec = { language: "python", display_name: "Python 3" };
      grammar = {
        scopeName: "source.python",
        name: "Python"
      };

      editor1 = atom.workspace.buildTextEditor();
      editor2 = atom.workspace.buildTextEditor();
      spyOn(editor1, "getPath").and.returnValue("foo.py");
      spyOn(editor2, "getPath").and.returnValue("bar.py");
      spyOn(editor1, "getGrammar").and.returnValue(grammar);
      spyOn(editor2, "getGrammar").and.returnValue(grammar);
      kernel1 = new Kernel(new KernelTransport(kernelSpec, grammar));
    });

    afterEach(() => {
      atom.config.set("Hydrogen.globalMode", false);
    });

    it("should use the same kernel if two files have the same grammar", () => {
      mockStore.updateEditor(editor1);
      mockStore.newKernel(kernel1, editor1.getPath(), editor1);
      expect(mockStore.kernel).toEqual(kernel1);

      mockStore.updateEditor(editor2);
      expect(mockStore.kernel).toEqual(kernel1);

      // store should still keep track of all filePaths
      expect(mockStore.filePaths).toEqual(["foo.py", "bar.py"]);
      expect(mockStore.getFilesForKernel(mockStore.kernel)).toEqual([
        "foo.py",
        "bar.py"
      ]);
    });
  });
});
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2009 Apple, Inc. and contributors.
// License:   Licened under MIT license (see license.js)
// ==========================================================================
/*globals module ok equals same test MyApp */

// test parsing of query string
var store, storeKey, rec1, rec2, rec3, rec4, rec5, MyApp, q;
module("SC.Query comparison of records", {
  setup: function() {
    // setup dummy app and store
    MyApp = SC.Object.create({
      store: SC.Store.create()
    });

    // setup a dummy model
    MyApp.Foo = SC.Record.extend({});

    // load some data
    MyApp.store.loadRecords(MyApp.Foo, [
      { guid: 1, firstName: "John", lastName: "Doe", year: 1974 },
      { guid: 2, firstName: "Jane", lastName: "Doe", year: 1975 },
      { guid: 3, firstName: "Emily", lastName: "Parker", year: 1975, active: null },
      { guid: 4, firstName: "Johnny", lastName: "Cash", active: false },
      { guid: 5, firstName: "Bert", lastName: "Berthold", active: true }
    ]);

    rec1 = MyApp.store.find(MyApp.Foo,1);
    rec2 = MyApp.store.find(MyApp.Foo,2);
    rec3 = MyApp.store.find(MyApp.Foo,3);
    rec4 = MyApp.store.find(MyApp.Foo,4);
    rec5 = MyApp.store.find(MyApp.Foo,5);

    q = SC.Query.create();
  }
});

// ..........................................................
// TESTS
//

test("parseQuery should work with conditions = null", function(){
  q.parseQuery();
});

test("building the order", function() {
  // undefined orderBy
  q.orderBy = null;
  q.parseQuery();
  equals(q.order.length, 0, 'order should be empty');

  // empty orderBy
  q.orderBy = "";
  q.parseQuery();
  equals(q.order.length, 0, 'order should be empty');

  // single property
  q.orderBy = "firstName";
  q.parseQuery();
  equals(q.order[0].propertyName,'firstName', 'propertyName should be firstName');

  // more properties
  q.orderBy = "lastName, firstName";
  q.parseQuery();
  equals(q.order[0].propertyName,'lastName', 'propertyName should be lastName');
  equals(q.order[1].propertyName,'firstName', 'propertyName should be firstName');

  // more properties with direction
  q.orderBy = "lastName, firstName, year DESC";
  q.parseQuery();
  equals(q.order[0].propertyName,'lastName', 'propertyName should be lastName');
  ok(!q.order[0].descending, 'descending should be false');
  equals(q.order[1].propertyName,'firstName', 'propertyName should be firstName');
  ok(!q.order[1].descending, 'descending should be false');
  equals(q.order[2].propertyName,'year', 'propertyName should be year');
  ok(q.order[2].descending, 'descending should be true');
});

test("no order should result in comparison by guid", function() {
  q.orderBy = null;
  q.parseQuery();
  equals(q.compare(rec1,rec2), -1, 'guid 1 should be before guid 2');
});

test("comparing non existant properties", function() {
  q.orderBy = "year";
  q.parseQuery();
  equals(q.compare(rec5,rec1), -1, 'null should be before 1974');
});

test("comparing null and boolean properties", function() {
  q.orderBy = "active";
  q.parseQuery();
  equals(q.compare(rec3,rec4), -1, 'null should be before false');
  equals(q.compare(rec4,rec5), -1, 'false should be before true');
});

test("comparing number properties", function() {
  q.orderBy = "year";
  q.parseQuery();
  equals(q.compare(rec1,rec2), -1, '1974 should be before 1975');

  q.orderBy = "year DESC";
  q.parseQuery();
  equals(q.compare(rec1,rec2), 1, '1974 should be after 1975 with DESC');
});

test("comparing string properties", function() {
  q.orderBy = "firstName";
  q.parseQuery();
  equals(q.compare(rec1,rec2), 1, 'John should be after Jane');

  q.orderBy = "firstName DESC";
  q.parseQuery();
  equals(q.compare(rec1,rec2), -1, 'John should be before Jane with DESC');
});

test("comparing by equal properties should use guid for order", function() {
  q.orderBy = "lastName";
  q.parseQuery();
  equals(q.compare(rec1,rec2), -1, 'guid 1 should be before guid 2')
});<commit_msg>fixed a js syntx error in a unit test<commit_after>// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2009 Apple, Inc. and contributors.
// License:   Licened under MIT license (see license.js)
// ==========================================================================
/*globals module ok equals same test MyApp */

// test parsing of query string
var store, storeKey, rec1, rec2, rec3, rec4, rec5, MyApp, q;
module("SC.Query comparison of records", {
  setup: function() {
    // setup dummy app and store
    MyApp = SC.Object.create({
      store: SC.Store.create()
    });

    // setup a dummy model
    MyApp.Foo = SC.Record.extend({});

    // load some data
    MyApp.store.loadRecords(MyApp.Foo, [
      { guid: 1, firstName: "John", lastName: "Doe", year: 1974 },
      { guid: 2, firstName: "Jane", lastName: "Doe", year: 1975 },
      { guid: 3, firstName: "Emily", lastName: "Parker", year: 1975, active: null },
      { guid: 4, firstName: "Johnny", lastName: "Cash", active: false },
      { guid: 5, firstName: "Bert", lastName: "Berthold", active: true }
    ]);

    rec1 = MyApp.store.find(MyApp.Foo,1);
    rec2 = MyApp.store.find(MyApp.Foo,2);
    rec3 = MyApp.store.find(MyApp.Foo,3);
    rec4 = MyApp.store.find(MyApp.Foo,4);
    rec5 = MyApp.store.find(MyApp.Foo,5);

    q = SC.Query.create();
  }
});

// ..........................................................
// TESTS
//

test("parseQuery should work with conditions = null", function(){
  q.parseQuery();
});

test("building the order", function() {
  // undefined orderBy
  q.orderBy = null;
  q.parseQuery();
  equals(q.order.length, 0, 'order should be empty');

  // empty orderBy
  q.orderBy = "";
  q.parseQuery();
  equals(q.order.length, 0, 'order should be empty');

  // single property
  q.orderBy = "firstName";
  q.parseQuery();
  equals(q.order[0].propertyName,'firstName', 'propertyName should be firstName');

  // more properties
  q.orderBy = "lastName, firstName";
  q.parseQuery();
  equals(q.order[0].propertyName,'lastName', 'propertyName should be lastName');
  equals(q.order[1].propertyName,'firstName', 'propertyName should be firstName');

  // more properties with direction
  q.orderBy = "lastName, firstName, year DESC";
  q.parseQuery();
  equals(q.order[0].propertyName,'lastName', 'propertyName should be lastName');
  ok(!q.order[0].descending, 'descending should be false');
  equals(q.order[1].propertyName,'firstName', 'propertyName should be firstName');
  ok(!q.order[1].descending, 'descending should be false');
  equals(q.order[2].propertyName,'year', 'propertyName should be year');
  ok(q.order[2].descending, 'descending should be true');
});

test("no order should result in comparison by guid", function() {
  q.orderBy = null;
  q.parseQuery();
  equals(q.compare(rec1,rec2), -1, 'guid 1 should be before guid 2');
});

test("comparing non existant properties", function() {
  q.orderBy = "year";
  q.parseQuery();
  equals(q.compare(rec5,rec1), -1, 'null should be before 1974');
});

test("comparing null and boolean properties", function() {
  q.orderBy = "active";
  q.parseQuery();
  equals(q.compare(rec3,rec4), -1, 'null should be before false');
  equals(q.compare(rec4,rec5), -1, 'false should be before true');
});

test("comparing number properties", function() {
  q.orderBy = "year";
  q.parseQuery();
  equals(q.compare(rec1,rec2), -1, '1974 should be before 1975');

  q.orderBy = "year DESC";
  q.parseQuery();
  equals(q.compare(rec1,rec2), 1, '1974 should be after 1975 with DESC');
});

test("comparing string properties", function() {
  q.orderBy = "firstName";
  q.parseQuery();
  equals(q.compare(rec1,rec2), 1, 'John should be after Jane');

  q.orderBy = "firstName DESC";
  q.parseQuery();
  equals(q.compare(rec1,rec2), -1, 'John should be before Jane with DESC');
});

test("comparing by equal properties should use guid for order", function() {
  q.orderBy = "lastName";
  q.parseQuery();
  equals(q.compare(rec1,rec2), -1, 'guid 1 should be before guid 2');
});<|endoftext|>


<commit_before>var O = require('./output.js');

module.exports.output = O.makeOutput(
  'output-crime-burst-central-london', // name

  'monitor the crime stats from central London. Trigger when there is a burst ' +
  'of 10 percents over the 6 months preceding the time of the check.', // description

  ['police-uk'], // array containing the names of datasources used by output

  function check(datasourcesDict, callback) {
    // check that all the datasources that we need are here.
    for (var i = 0; i < this.sources.length; i++) {
      if (!(this.sources[i] in datasourcesDict)) {
        callback("Datasource '" + sources[i] + "' not found in " + datasourcesDict);
        return;
      }
    }

    var police_uk = datasourcesDict['police-uk'];
    var to = new Date(Date.now());
    var from = new Date(to);
    from.setMonth(from.getMonth() - 5); // query data for the past 6 months.

    // TODO that's just for the example. There should a nice way to input these
    // from a GUI.
    var lat = 51.529251355189885;
    var lng = -0.1490020751953125;

    police_uk.getData(from, to, lat, lng, processStats);

    function processStats(crimeStats) {
      // compute the total amount of crime for each crime
      var totCrimes = [];
      for (var i = 0; i < crimeStats.length; i++) {
        var totalCrime = 0;
        var types = Object.keys(crimeStats[i]);
        for (var t = 0; t < types.length; t++) {
          totalCrime += crimeStats[i][t];
        }
        totCrimes.push(totalCrime);
      }

      // compute the average of crimes per month
      var avg = 0;
      for (var m = 0; m < totCrimes.length; m++) {
        avg += totCrimes[m];
      }
      avg /= totCrimes.length;

      var dif = (totCrimes[totCrimes.length - 1] / avg * 100) - 100;

      // TODO that 10 percents also are here for the sake of the example and
      // should be parametrized somehow.
      if (Math.abs(dif) >= 10) {
        callback(undefined, dif);
      }
    }
  }
);

<commit_msg>hardcoded date + add -10 percent as an alert<commit_after>var O = require('./output.js');

module.exports.output = O.makeOutput(
  'output-crime-burst-central-london', // name

  'monitor the crime stats from central London. Trigger when there is a burst ' +
  'of 10 percents over the 6 months preceding the time of the check.', // description

  ['police-uk'], // array containing the names of datasources used by output

  function check(datasourcesDict, callback) {
    // check that all the datasources that we need are here.
    for (var i = 0; i < this.sources.length; i++) {
      if (!(this.sources[i] in datasourcesDict)) {
        callback("Datasource '" + sources[i] + "' not found in " + datasourcesDict);
        return;
      }
    }

    var police_uk = datasourcesDict['police-uk'];
    var to = new Date("2014-06-01");
    var from = new Date(to);
    from.setMonth(from.getMonth() - 5); // query data for the past 6 months.

    // TODO that's just for the example. There should a nice way to input these
    // from a GUI.
    var lat = 51.529251355189885;
    var lng = -0.1490020751953125;

    police_uk.getData(from, to, lat, lng, processStats);

    function processStats(crimeStats) {
      // compute the total amount of crime for each crime
      var totCrimes = [];
      for (var i = 0; i < crimeStats.length; i++) {
        var totalCrime = 0;
        var types = Object.keys(crimeStats[i]);
        for (var t = 0; t < types.length; t++) {
          totalCrime += crimeStats[i][t];
        }
        totCrimes.push(totalCrime);
      }

      // compute the average of crimes per month
      var avg = 0;
      for (var m = 0; m < totCrimes.length; m++) {
        avg += totCrimes[m];
      }
      avg /= totCrimes.length;

      var dif = (totCrimes[totCrimes.length - 1] / avg * 100) - 100;

      // TODO that 10 percents also are here for the sake of the example and
      // should be parametrized somehow.
      if (Math.abs(dif) >= 10 || Math.abs(dif) <= -10) {
        callback(undefined, dif);
      }
    }
  }
);

<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import TextField from 'material-ui/TextField'
import IconButton from 'material-ui/IconButton'
import Visibility from 'material-ui/svg-icons/action/visibility'
import VisibilityOff from 'material-ui/svg-icons/action/visibility-off'
import transitions from 'material-ui/styles/transitions'
import {fade} from 'material-ui/utils/colorManipulator'

const getStyles = (props, context, state) => {
  const {
    baseTheme,
    textField: {
      floatingLabelColor,
      focusColor,
      textColor,
      disabledTextColor,
      backgroundColor,
      hintColor,
      errorColor,
    },
  } = context.muiTheme

  const styles = {
    root: {
      display: 'flex',
      width: props.fullWidth ? '100%' : null
    },
    inputContainer: {
      flex: 1
    },
    input: {
      width: '100%',
      paddingRight: 56
    },
    hint: {
      position: 'relative',
      bottom: 2,
      fontSize: 12,
      lineHeight: '12px',
      color: props.errorText ? errorColor : fade(disabledTextColor, 0.5),
      transition: transitions.easeOut(),
    },
    error: {
      color: errorColor
    },
    visibilityButton: {
      margin: '22px 0 0 8px',
      width: 48,
      height: 48,
      padding: 12
    },
    visibilityIcon: {
      opacity: !props.disabled && state.focused ? 0.54 : 0.38,
      width: 24,
      height: 24
    }
  }

  return styles
}

class PasswordField extends React.Component {
  static contextTypes = {
    muiTheme: PropTypes.object.isRequired,
  }

  constructor (props) {
    super(props)
    this.state = {
      focused: false,
      visible: props.visible
    }
  }

  componentWillReceiveProps (nextProps) {
    if (nextProps.visible !== this.props.visible) {
      this.setState({
        visible: nextProps.visible
      })
    }
  }

  toggleVisibility () {
    this.setState({
      visible: !this.state.visible
    })
  }

  handleInputFocus (event) {
    this.setState({ focused: true })
    if (this.props.onFocus) {
      this.props.onFocus(event)
    }
  }

  handleInputBlur (event) {
    this.setState({ focused: false })
    if (this.props.onBlur) {
      this.props.onBlur(event)
    }
  }

  render () {
    const {
      disableButton,
      hintText,
      errorText,
      errorStyle,
      textFieldStyle,
      style,
      type,
      fullWidth,
      ...other
    } = this.props

    const {
      visible
    } = this.state

    const styles = getStyles(this.props, this.context, this.state)

    const { prepareStyles } = this.context.muiTheme
    const actualErrorText = errorText ? errorText : hintText

    return (

          <TextField
            {...other}
            errorStyle={{...styles.error, ...errorStyle}}
            errorText={errorText}
            hintText={null}
            style={{ ...styles.input, ...textFieldStyle }}
            type={visible ? 'text' : 'password'}
            onFocus={(event) => this.handleInputFocus(event)}
            onBlur={(event) => this.handleInputBlur(event)}
          />
          {hintText && !errorText ?
{actualErrorText}
 : null}

        <IconButton
          onTouchTap={() => this.toggleVisibility()}
          iconStyle={styles.visibilityIcon}
          style={styles.visibilityButton}
          disabled={disableButton || other.disabled}
        >
          {visible ? <Visibility /> : <VisibilityOff />}
        </IconButton>

    )
  }
}

if (process.env.NODE_ENV !== 'production') {
  PasswordField.propTypes = {
    ...TextField.propTypes,
    disableButton: PropTypes.bool,
    visible: PropTypes.bool,
    textFieldStyle: PropTypes.object
  }
  delete PasswordField.propTypes.multiLine
  delete PasswordField.propTypes.type
}

export default PasswordField
<commit_msg>Set tabIndex to -1 on IconButton to skip tabbing to visibility button<commit_after>import React, { PropTypes } from 'react'
import TextField from 'material-ui/TextField'
import IconButton from 'material-ui/IconButton'
import Visibility from 'material-ui/svg-icons/action/visibility'
import VisibilityOff from 'material-ui/svg-icons/action/visibility-off'
import transitions from 'material-ui/styles/transitions'
import {fade} from 'material-ui/utils/colorManipulator'

const getStyles = (props, context, state) => {
  const {
    baseTheme,
    textField: {
      floatingLabelColor,
      focusColor,
      textColor,
      disabledTextColor,
      backgroundColor,
      hintColor,
      errorColor,
    },
  } = context.muiTheme

  const styles = {
    root: {
      display: 'flex',
      width: props.fullWidth ? '100%' : null
    },
    inputContainer: {
      flex: 1
    },
    input: {
      width: '100%',
      paddingRight: 56
    },
    hint: {
      position: 'relative',
      bottom: 2,
      fontSize: 12,
      lineHeight: '12px',
      color: props.errorText ? errorColor : fade(disabledTextColor, 0.5),
      transition: transitions.easeOut(),
    },
    error: {
      color: errorColor
    },
    visibilityButton: {
      margin: '22px 0 0 8px',
      width: 48,
      height: 48,
      padding: 12
    },
    visibilityIcon: {
      opacity: !props.disabled && state.focused ? 0.54 : 0.38,
      width: 24,
      height: 24
    }
  }

  return styles
}

class PasswordField extends React.Component {
  static contextTypes = {
    muiTheme: PropTypes.object.isRequired,
  }

  constructor (props) {
    super(props)
    this.state = {
      focused: false,
      visible: props.visible
    }
  }

  componentWillReceiveProps (nextProps) {
    if (nextProps.visible !== this.props.visible) {
      this.setState({
        visible: nextProps.visible
      })
    }
  }

  toggleVisibility () {
    this.setState({
      visible: !this.state.visible
    })
  }

  handleInputFocus (event) {
    this.setState({ focused: true })
    if (this.props.onFocus) {
      this.props.onFocus(event)
    }
  }

  handleInputBlur (event) {
    this.setState({ focused: false })
    if (this.props.onBlur) {
      this.props.onBlur(event)
    }
  }

  render () {
    const {
      disableButton,
      hintText,
      errorText,
      errorStyle,
      textFieldStyle,
      style,
      type,
      fullWidth,
      ...other
    } = this.props

    const {
      visible
    } = this.state

    const styles = getStyles(this.props, this.context, this.state)

    const { prepareStyles } = this.context.muiTheme
    const actualErrorText = errorText ? errorText : hintText

    return (

          <TextField
            {...other}
            errorStyle={{...styles.error, ...errorStyle}}
            errorText={errorText}
            hintText={null}
            style={{ ...styles.input, ...textFieldStyle }}
            type={visible ? 'text' : 'password'}
            onFocus={(event) => this.handleInputFocus(event)}
            onBlur={(event) => this.handleInputBlur(event)}
          />
          {hintText && !errorText ?
{actualErrorText}
 : null}

        <IconButton
          onTouchTap={() => this.toggleVisibility()}
          iconStyle={styles.visibilityIcon}
          style={styles.visibilityButton}
          disabled={disableButton || other.disabled}
          tabIndex={-1}
        >
          {visible ? <Visibility /> : <VisibilityOff />}
        </IconButton>

    )
  }
}

if (process.env.NODE_ENV !== 'production') {
  PasswordField.propTypes = {
    ...TextField.propTypes,
    disableButton: PropTypes.bool,
    visible: PropTypes.bool,
    textFieldStyle: PropTypes.object
  }
  delete PasswordField.propTypes.multiLine
  delete PasswordField.propTypes.type
}

export default PasswordField
<|endoftext|>


<commit_before>const lib = require('lib')({token: process.env.STDLIB_TOKEN});

/**
* /hello
*
*   Basic "Hello World" command.
*   All Commands use this template, simply create additional files with
*   different names to add commands.
*
*   See https://api.slack.com/slash-commands for more details.
*
* @param {string} user The user id of the user that invoked this command (name is usable as well)
* @param {string} channel The channel id the command was executed in (name is usable as well)
* @param {string} text The text contents of the command
* @param {object} command The full Slack command object
* @param {string} botToken The bot token for the Slack bot you have activated
* @returns {object}
*/
module.exports = (user, channel, text = '', command = {}, botToken = null, callback) => {

  var team = {
    dennis: 'U0545PDQ3',
    rodrigo: 'U0DU10LAU',
    roger: 'U75RRPETH',
    alejandro: 'U0408Q8R0',
    amec: 'U707X17U3',
    emily: 'U6XAQ854Y'
  }

  if(Object.values(team).indexOf(user) > -1){

    if(!team[text]) {
      callback(null, {
        response_type: 'ephemeral',
        text: `Hey <@${user}> here is the info for ${text}'s sever:`
      });
    } else {
      callback(null, {
        response_type: 'ephemeral',
        text: `Sorry <@${user}> I don't know about the ${text} sever`
      });
    }
  } else {
    callback(null, {
      response_type: 'ephemeral',
      text: `Sorry, this command is exclusive to the XMPie team.`
    });
  }

};
<commit_msg>fix dumb error<commit_after>const lib = require('lib')({token: process.env.STDLIB_TOKEN});

/**
* /hello
*
*   Basic "Hello World" command.
*   All Commands use this template, simply create additional files with
*   different names to add commands.
*
*   See https://api.slack.com/slash-commands for more details.
*
* @param {string} user The user id of the user that invoked this command (name is usable as well)
* @param {string} channel The channel id the command was executed in (name is usable as well)
* @param {string} text The text contents of the command
* @param {object} command The full Slack command object
* @param {string} botToken The bot token for the Slack bot you have activated
* @returns {object}
*/
module.exports = (user, channel, text = '', command = {}, botToken = null, callback) => {

  var team = {
    dennis: 'U0545PDQ3',
    rodrigo: 'U0DU10LAU',
    roger: 'U75RRPETH',
    alejandro: 'U0408Q8R0',
    amec: 'U707X17U3',
    emily: 'U6XAQ854Y'
  }

  if(Object.values(team).indexOf(user) > -1){

    if(team[text]) {
      callback(null, {
        response_type: 'ephemeral',
        text: `Hey <@${user}> here is the info for ${text}'s sever:`
      });
    } else {
      callback(null, {
        response_type: 'ephemeral',
        text: `Sorry <@${user}> I don't know about the ${text} sever`
      });
    }
  } else {
    callback(null, {
      response_type: 'ephemeral',
      text: `Sorry, this command is exclusive to the XMPie team.`
    });
  }

};
<|endoftext|>


<commit_before>
/**
 * @class UI.Button
 * @extends {UI.Control}
 * @type {Class}
 */
UI.Button = new Class({

	Extends: UI.Control,

	name: 'button',

	options: {
		name: 'button',
		type: null, // push, file
		element: {
			tag: 'button'
		},
		binding: {
			_list: ['element'],
			element: {
				'element.mousedown': '_onElementMouseDown',
				'element.click': '_onElementClick',
				'element.dblclick': '_onElementClick'
			}
		}
	},

	set: function() {},

	/**
	 * [_initElement description]
	 * @return {[type]} [description]
	 */
	_initElement: function(){
		this.parent();
		var opts = this.options,
			type = opts.type;

		opts.text = opts.text || opts.n;

		if (type === null)
			type = 'icon-text';

/*		if (opts.text && type != 'icon')
			this.element.set('html', opts.text);*/
		//var text = opts.type.match(/text/g);

		if (opts.name)
			this.element.set('data-name', opts.name);

		//_log('title', this.element,  opts.text);
		this.element.set('title', opts.text);

		if (opts.icon)
			this._initIcon(type);

		if (opts.text)
			this._initText(type);

		this._initClass();

		if (this.options.clss)
			this.element.addClass(this.options.clss);

	},

	/**
	 * [_initIcon description]
	 * @param  {[type]} type [description]
	 * @return {[type]}      [description]
	 */
	_initIcon: function(type) {
		var opts = this.options;

		var tag = 'span';

		var prop = {
			'class': 'button-icon'
		};

		this.icon = new Element(tag, prop).inject(this.element);

		var klss = opts.icon.replace("icon-", "fa-");

		this.icon.addClass('fa');
		this.icon.addClass(klss);
	},

	/**
	 * [_initText description]
	 * @param  {[type]} type [description]
	 * @return {[type]}      [description]
	 */
	_initText: function(type) {
		var opts = this.options;

		var tag = 'span';

		var pos = 'bottom';
		if (type == 'text-icon')
			pos = 'top';

		this.text = new Element(tag, {
			'class': 'button-text',
			'html': opts.text
		}).inject(this.element, pos);

	},

	/**
	 * [_initClass description]
	 * @return {[type]} [description]
	 */
	_initClass: function() {
		var opts = this.options;
		//_log(this.name);

		if (this.options.klss)
			this.element.addClass('button-'+opts.klss);

		if (this.options.type)
			this.element.addClass('type-' + this.options.type);

		this.element.addClass(opts.prefix + this.name);
	},

	/**
	 * [_onElementMouseDown description]
	 * @param  {event} e [description]
	 * @return {[type]}   [description]
	 */
	_onElementMouseDown: function(e) {
		e.stop();

		var x = e.event.layerX;
		var y = e.event.layerY;
		console.log('mousedown', x, y);

		var inner = new Element('span', {
			class: 'button-force',
			styles: {
				left: x,
				top: y,
			}
		}).inject(this.element);

		this._initReaction(inner, x, y);

		this.fireEvent('mousedown');
	},

	/**
	 * [_initEffect description]
	 * @param  {[type]} inner [description]
	 * @param  {[type]} x     [description]
	 * @param  {[type]} y     [description]
	 * @return {[type]}       [description]
	 */
	_initReaction: function(inner, x, y) {

		var fx = new Fx.Morph(inner, {
		    //duration: 'long',
		    transition: Fx.Transitions.Sine.easeOut
		});

		fx.start({
		    height: '100%',
		    width: '100%',
		    left: 0,
		    top: 0,
		   	opacity: 0
		});
	},

	/**
	 * [_onElementMouseDown description]
	 * @param  {event} e [description]
	 * @return {[type]}   [description]
	 */
	_onElementClick: function(e) {
		var opts = this.options;
		e.stopPropagation();
		if (opts.emit && this.state != 'disabled')
			this.fireEvent(opts.emit);
			this.fireEvent('press', opts.emit);
			this.fireEvent('pressed', opts.emit);

		if (opts.call && this.state != 'disabled')
			opts.call();
	},

	/**
	 * [_onElementMouseUp description]
	 * @return {[type]} [description]
	 */
	_onElementMouseUp: function(){
		var opts = this.options;
		if (this.options.type == 'check') {
			if (this.state == 'checked')
				this.setState(null);
			else this.setState('checked');
		}
	}
});

<commit_msg>Work on planning app<commit_after>
/**
 * @class UI.Button
 * @extends {UI.Control}
 * @type {Class}
 */
UI.Button = new Class({

	Extends: UI.Control,

	name: 'button',

	options: {
		name: 'button',
		type: null, // push, file
		element: {
			tag: 'button'
		},
		binding: {
			_list: ['element'],
			element: {
				'element.click': '_onElementClick',
				'element.dblclick': '_onElementClick',
				'element.mousedown': '_onElementMouseDown',
				'element.mouseup': '_onElementMouseUp'

			}
		}
	},

	set: function() {},

	/**
	 * [_initElement description]
	 * @return {[type]} [description]
	 */
	_initElement: function(){
		this.parent();
		var opts = this.options,
			type = opts.type;

		opts.text = opts.text || opts.n;

		if (type === null)
			type = 'icon-text';

/*		if (opts.text && type != 'icon')
			this.element.set('html', opts.text);*/
		//var text = opts.type.match(/text/g);

		if (opts.name)
			this.element.set('data-name', opts.name);

		//_log('title', this.element,  opts.text);
		this.element.set('title', opts.text);

		if (opts.icon)
			this._initIcon(type);

		if (opts.text)
			this._initText(type);

		this._initClass();
	},

	/**
	 * [_initIcon description]
	 * @param  {[type]} type [description]
	 * @return {[type]}      [description]
	 */
	_initIcon: function(type) {
		var opts = this.options;

		var tag = 'span';

		var prop = {
			'class': 'button-icon'
		};

		this.icon = new Element(tag, prop).inject(this.element);

		var klss = opts.icon.replace("icon-", "fa-");

		this.icon.addClass('fa');
		this.icon.addClass(klss);
	},

	/**
	 * [_initText description]
	 * @param  {[type]} type [description]
	 * @return {[type]}      [description]
	 */
	_initText: function(type) {
		var opts = this.options;

		var tag = 'span';

		var pos = 'bottom';
		if (type == 'text-icon')
			pos = 'top';

		this.text = new Element(tag, {
			'class': 'button-text',
			'html': opts.text
		}).inject(this.element, pos);

	},

	/**
	 * [_initClass description]
	 * @return {[type]} [description]
	 */
	_initClass: function() {
		var opts = this.options;
		//_log(this.name);

		if (this.options.klss)
			this.element.addClass('button-'+opts.klss);

		if (this.options.type)
			this.element.addClass('type-' + this.options.type);

		this.element.addClass(opts.prefix + this.name);

		if (this.options.clss)
			this.element.addClass(this.options.clss);
	},

	/**
	 * [_onElementMouseDown description]
	 * @param  {event} e [description]
	 * @return {[type]}   [description]
	 */
	_onElementMouseDown: function(e) {

		e.stop();

		var x = e.event.layerX;
		var y = e.event.layerY;
		console.log('mousedown', x, y);

		this.coord = this.element.getCoordinates();

		this.react = new Element('span', {
			class: 'button-reaction',
			styles: {
				left: x,
				top: y,

			}
		}).inject(this.element);

		this._initReaction(this.react, x, y);

		this.fireEvent('mousedown');
	},

	/**
	 * [_initEffect description]
	 * @param  {[type]} inner [description]
	 * @param  {[type]} x     [description]
	 * @param  {[type]} y     [description]
	 * @return {[type]}       [description]
	 */
	_initReaction: function(inner, x, y) {

		var size = this.coord.height;

		if (this.coord.width > size)
			size = this.coord.width;

		var fx = new Fx.Morph(inner, {
		    //duration: 'long',
		    transition: Fx.Transitions.Sine.easeOut
		});

		fx.start({
		    height: size,
		    width: size,
		    left: 0,
		    top: 0,
		   	opacity: 0
		});

		(function() {
			inner.destroy();
		}).delay(1000);
	},

	/**
	 * [_onElementMouseDown description]
	 * @param  {event} e [description]
	 * @return {[type]}   [description]
	 */
	_onElementClick: function(e) {
		var opts = this.options;
		e.stopPropagation();
		if (opts.emit && this.state != 'disabled')
			this.fireEvent(opts.emit);
			this.fireEvent('press', opts.emit);
			this.fireEvent('pressed', opts.emit);

		if (opts.call && this.state != 'disabled')
			opts.call();
	},

	/**
	 * [_onElementMouseUp description]
	 * @return {[type]} [description]
	 */
	_onElementMouseUp: function(){
		var opts = this.options;
		if (this.options.type == 'check') {
			if (this.state == 'checked')
				this.setState(null);
			else this.setState('checked');
		}

		//this.react.destroy();
	}
});

<|endoftext|>


<commit_before>import React from 'react';
import formatCurrency from '../../lib/format_currency';
import Media from '../../components/Media';
import Metric from '../../components/Metric';

export default class PublicGroupWhyJoin extends React.Component {
  render() {
    const {
      group,
      i18n,
      expenses
    } = this.props;

    const whyJoinText = group.whyJoin || i18n.getString('becomeMemberText');

    return (

              <Media group={group} />

              {i18n.getString('becomeMemberTitle')}

{whyJoinText}

              <Metric label={i18n.getString('fundsAvailable')}
                value={ formatCurrency(group.balance/100, group.currency, { precision: 0 }) }
                className='flex-auto pr2' />

              {(expenses.length > 0) && (

                  {i18n.getString('howWeSpend')}

              )}

    );
  }
}
<commit_msg>added support for markdown for group.whyJoin (#311)<commit_after>import React from 'react';
import formatCurrency from '../../lib/format_currency';
import Media from '../../components/Media';
import Metric from '../../components/Metric';
import Markdown from '../../components/Markdown';

export default class PublicGroupWhyJoin extends React.Component {
  render() {
    const {
      group,
      i18n,
      expenses
    } = this.props;

    const whyJoinText = group.whyJoin || i18n.getString('becomeMemberText');

    return (

              <Media group={group} />

              {i18n.getString('becomeMemberTitle')}
              <Markdown className='PublicGroup-font-17 mt3' value={whyJoinText} />

              <Metric label={i18n.getString('fundsAvailable')}
                value={ formatCurrency(group.balance/100, group.currency, { precision: 0 }) }
                className='flex-auto pr2' />

              {(expenses.length > 0) && (

                  {i18n.getString('howWeSpend')}

              )}

    );
  }
}
<|endoftext|>