<commit_before>var CONST = require('../const');

/**
 * @namespace PIXI
 */
var utils = module.exports = {
    _uid: 0,
    _saidHello: false,

    PolyK:          require('./PolyK'),
    EventData:      require('./EventData'),
    eventTarget:    require('./eventTarget'),
    pluginTarget:   require('./pluginTarget'),

    /**
     * Gets the next uuid
     *
     * @return {number} The next uuid to use.
     */
    uuid: function ()
    {
        return ++utils._uid;
    },

    /**
     * Converts a hex color number to an [R, G, B] array
     *
     * @param hex {number}
     * @return {number[]} An array representing the [R, G, B] of the color.
     */
    hex2rgb: function (hex, out)
    {
        out = out || [];

        out[0] = (hex >> 16 & 0xFF) / 255;
        out[1] = (hex >> 8 & 0xFF) / 255;
        out[2] = (hex & 0xFF) / 255;

        return out;
    },

    /**
     * Converts a hex color number to a string.
     *
     * @param hex {number}
     * @return {string} The string color.
     */
    hex2string: function (hex)
    {
        hex = hex.toString(16);
        hex = '000000'.substr(0, 6 - hex.length) + hex;

        return '#' + hex;
    },

    /**
     * Converts a color as an [R, G, B] array to a hex number
     *
     * @param rgb {number[]}
     * @return {number} The color number
     */
    rgb2hex: function (rgb)
    {
        return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255);
    },

    /**
     * Checks whether the Canvas BlendModes are supported by the current browser
     *
     * @return {boolean} whether they are supported
     */
    canUseNewCanvasBlendModes: function ()
    {
        if (typeof document === 'undefined')
        {
            return false;
        }

        var canvas = document.createElement('canvas'),
            context = canvas.getContext('2d');

        canvas.width = 1;
        canvas.height = 1;

        context.fillStyle = '#000';
        context.fillRect(0, 0, 1, 1);

        context.globalCompositeOperation = 'multiply';

        context.fillStyle = '#fff';
        context.fillRect(0, 0, 1, 1);

        return context.getImageData(0,0,1,1).data[0] === 0;
    },

    /**
     * Given a number, this function returns the closest number that is a power of two
     * this function is taken from Starling Framework as its pretty neat ;)
     *
     * @param number {number}
     * @return {number} the closest number that is a power of two
     */
    getNextPowerOfTwo: function (number)
    {
        // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two
        if (number > 0 && (number & (number - 1)) === 0)
        {
            return number;
        }
        else
        {
            var result = 1;

            while (result < number)
            {
                result <<= 1;
            }

            return result;
        }
    },

    /**
     * checks if the given width and height make a power of two rectangle
     *
     * @param width {number}
     * @param height {number}
     * @return {boolean}
     */
    isPowerOfTwo: function (width, height)
    {
        return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0);
    },

    /**
     * Logs out the version and renderer information for this running instance of PIXI.
     * If you don't want to see this message you can set `PIXI.utils._saidHello = true;`
     * so the library thinks it already said it. Keep in mind that doing that will forever
     * makes you a jerk face.
     *
     * @param {string} type - The string renderer type to log.
     * @constant
     * @static
     */
    sayHello: function (type)
    {
        if (utils._saidHello)
        {
            return;
        }

        if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
        {
            var args = [
                '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + '  %c ' + ' %c ' + ' http://www.pixijs.com/  %c %c ♥%c♥%c♥ ',
                'background: #ff66a5',
                'background: #ff66a5',
                'color: #ff66a5; background: #030307;',
                'background: #ff66a5',
                'background: #ffc3dc',
                'background: #ff66a5',
                'color: #ff2424; background: #fff',
                'color: #ff2424; background: #fff',
                'color: #ff2424; background: #fff'
            ];

            console.log.apply(console, args); //jshint ignore:line
        }
        else if (window.console)
        {
            console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line
        }

        utils._saidHello = true;
    },

    // TODO: refactor out this
    TextureCache: {},
    BaseTextureCache: {}
};
<commit_msg>remove a todo<commit_after>var CONST = require('../const');

/**
 * @namespace PIXI
 */
var utils = module.exports = {
    _uid: 0,
    _saidHello: false,

    PolyK:          require('./PolyK'),
    EventData:      require('./EventData'),
    eventTarget:    require('./eventTarget'),
    pluginTarget:   require('./pluginTarget'),

    /**
     * Gets the next uuid
     *
     * @return {number} The next uuid to use.
     */
    uuid: function ()
    {
        return ++utils._uid;
    },

    /**
     * Converts a hex color number to an [R, G, B] array
     *
     * @param hex {number}
     * @return {number[]} An array representing the [R, G, B] of the color.
     */
    hex2rgb: function (hex, out)
    {
        out = out || [];

        out[0] = (hex >> 16 & 0xFF) / 255;
        out[1] = (hex >> 8 & 0xFF) / 255;
        out[2] = (hex & 0xFF) / 255;

        return out;
    },

    /**
     * Converts a hex color number to a string.
     *
     * @param hex {number}
     * @return {string} The string color.
     */
    hex2string: function (hex)
    {
        hex = hex.toString(16);
        hex = '000000'.substr(0, 6 - hex.length) + hex;

        return '#' + hex;
    },

    /**
     * Converts a color as an [R, G, B] array to a hex number
     *
     * @param rgb {number[]}
     * @return {number} The color number
     */
    rgb2hex: function (rgb)
    {
        return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255);
    },

    /**
     * Checks whether the Canvas BlendModes are supported by the current browser
     *
     * @return {boolean} whether they are supported
     */
    canUseNewCanvasBlendModes: function ()
    {
        if (typeof document === 'undefined')
        {
            return false;
        }

        var canvas = document.createElement('canvas'),
            context = canvas.getContext('2d');

        canvas.width = 1;
        canvas.height = 1;

        context.fillStyle = '#000';
        context.fillRect(0, 0, 1, 1);

        context.globalCompositeOperation = 'multiply';

        context.fillStyle = '#fff';
        context.fillRect(0, 0, 1, 1);

        return context.getImageData(0,0,1,1).data[0] === 0;
    },

    /**
     * Given a number, this function returns the closest number that is a power of two
     * this function is taken from Starling Framework as its pretty neat ;)
     *
     * @param number {number}
     * @return {number} the closest number that is a power of two
     */
    getNextPowerOfTwo: function (number)
    {
        // see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two
        if (number > 0 && (number & (number - 1)) === 0)
        {
            return number;
        }
        else
        {
            var result = 1;

            while (result < number)
            {
                result <<= 1;
            }

            return result;
        }
    },

    /**
     * checks if the given width and height make a power of two rectangle
     *
     * @param width {number}
     * @param height {number}
     * @return {boolean}
     */
    isPowerOfTwo: function (width, height)
    {
        return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0);
    },

    /**
     * Logs out the version and renderer information for this running instance of PIXI.
     * If you don't want to see this message you can set `PIXI.utils._saidHello = true;`
     * so the library thinks it already said it. Keep in mind that doing that will forever
     * makes you a jerk face.
     *
     * @param {string} type - The string renderer type to log.
     * @constant
     * @static
     */
    sayHello: function (type)
    {
        if (utils._saidHello)
        {
            return;
        }

        if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
        {
            var args = [
                '%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + '  %c ' + ' %c ' + ' http://www.pixijs.com/  %c %c ♥%c♥%c♥ ',
                'background: #ff66a5',
                'background: #ff66a5',
                'color: #ff66a5; background: #030307;',
                'background: #ff66a5',
                'background: #ffc3dc',
                'background: #ff66a5',
                'color: #ff2424; background: #fff',
                'color: #ff2424; background: #fff',
                'color: #ff2424; background: #fff'
            ];

            console.log.apply(console, args); //jshint ignore:line
        }
        else if (window.console)
        {
            console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line
        }

        utils._saidHello = true;
    },

    TextureCache: {},
    BaseTextureCache: {}
};
<|endoftext|>


<commit_before>dojo.provide("dojox.mobile.tests.doh.module");

try{
	doh.registerUrl("dojox.mobile.tests.doh.Button", dojo.moduleUrl("dojox.mobile", "tests/doh/Button.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.Button", dojo.moduleUrl("dojox.mobile", "tests/doh/Button_Programmatic.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.DatePickerIso", dojo.moduleUrl("dojox.mobile", "tests/doh/DatePickerIso.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.EdgeToEdgeCategory", dojo.moduleUrl("dojox.mobile", "tests/doh/EdgeToEdgeCategory.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.EdgeToEdgeDataList", dojo.moduleUrl("dojox.mobile", "tests/doh/EdgeToEdgeDataList.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.EdgeToEdgeDataList", dojo.moduleUrl("dojox.mobile", "tests/doh/EdgeToEdgeDataList_Programmatic.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.EdgeToEdgeStoreList", dojo.moduleUrl("dojox.mobile", "tests/doh/EdgeToEdgeStoreList.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.EdgeToEdgeStoreList", dojo.moduleUrl("dojox.mobile", "tests/doh/EdgeToEdgeStoreList_Programmatic.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.Heading", dojo.moduleUrl("dojox.mobile", "tests/doh/Heading.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.Heading", dojo.moduleUrl("dojox.mobile", "tests/doh/Heading2.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.Heading", dojo.moduleUrl("dojox.mobile", "tests/doh/Heading_Programmatic.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.Heading", dojo.moduleUrl("dojox.mobile", "tests/doh/Heading2_Programmatic.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.IconContainer", dojo.moduleUrl("dojox.mobile", "tests/doh/IconContainer.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.IconContainer", dojo.moduleUrl("dojox.mobile", "tests/doh/IconContainer2.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.IconContainer", dojo.moduleUrl("dojox.mobile", "tests/doh/IconContainer3.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.IconContainer", dojo.moduleUrl("dojox.mobile", "tests/doh/IconContainer_Programmatic.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.IconContainer", dojo.moduleUrl("dojox.mobile", "tests/doh/View.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.RoundRectList", dojo.moduleUrl("dojox.mobile", "tests/doh/RoundRect.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.ListItem", dojo.moduleUrl("dojox.mobile", "tests/doh/ListItem.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.ListItem", dojo.moduleUrl("dojox.mobile", "tests/doh/ListItem2.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.ListItem", dojo.moduleUrl("dojox.mobile", "tests/doh/ListItem_Programmatic.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.ListItem", dojo.moduleUrl("dojox.mobile", "tests/doh/ListItem2_Programmatic.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.Progress-indicator", dojo.moduleUrl("dojox.mobile", "tests/doh/progress-indicator.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.RoundRect", dojo.moduleUrl("dojox.mobile", "tests/doh/RoundRect.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.RoundRect", dojo.moduleUrl("dojox.mobile", "tests/doh/RoundRect_Programmatic.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.RoundRectDataList", dojo.moduleUrl("dojox.mobile", "tests/doh/RoundRectDataList.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.RoundRectDataList", dojo.moduleUrl("dojox.mobile", "tests/doh/RoundRectDataList_Programmatic.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.RoundRectStoreList", dojo.moduleUrl("dojox.mobile", "tests/doh/RoundRectStoreList.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.RoundRectStoreList", dojo.moduleUrl("dojox.mobile", "tests/doh/RoundRectStoreList_Programmatic.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.RoundRectList", dojo.moduleUrl("dojox.mobile", "tests/doh/RoundRectList.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.Switch", dojo.moduleUrl("dojox.mobile", "tests/doh/Switch.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.Switch", dojo.moduleUrl("dojox.mobile", "tests/doh/Switch_Programmatic.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.TabBar", dojo.moduleUrl("dojox.mobile", "tests/doh/TabBar.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.TabBar", dojo.moduleUrl("dojox.mobile", "tests/doh/TabBar_Programmatic.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.ToolBarButton", dojo.moduleUrl("dojox.mobile", "tests/doh/ToolBarButton.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.ToolBarButton", dojo.moduleUrl("dojox.mobile", "tests/doh/ToolBarButton_Programmatic.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.ToolBarButton", dojo.moduleUrl("dojox.mobile", "tests/doh/ToolBarButtonSetter.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.View", dojo.moduleUrl("dojox.mobile", "tests/doh/View.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.View", dojo.moduleUrl("dojox.mobile", "tests/doh/View_Programmatic.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.View", dojo.moduleUrl("dojox.mobile", "tests/doh/View2_Programmatic.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.View", dojo.moduleUrl("dojox.mobile", "tests/doh/View3_Programmatic.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.View", dojo.moduleUrl("dojox.mobile", "tests/doh/View-demo.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.URLProperty", dojo.moduleUrl("dojox.mobile", "tests/doh/TestURLProp.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.URLProperty", dojo.moduleUrl("dojox.mobile", "tests/doh/TestURLProp2.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.SpinWheel", dojo.moduleUrl("dojox.mobile", "tests/doh/SpinWheel_Programmatic.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.SpinWheelDatePicker", dojo.moduleUrl("dojox.mobile", "tests/doh/SpinWheelDatePicker.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.ValuePickerDatePicker", dojo.moduleUrl("dojox.mobile", "tests/doh/ValuePickerDatePicker.html"),999999);

	doh.registerUrl("dojox.mobile.tests.doh.Button", dojo.moduleUrl("dojox.mobile", "tests/doh/ButtonTests.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.CheckBox", dojo.moduleUrl("dojox.mobile", "tests/doh/CheckBoxTests.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.ComboBoxTests", dojo.moduleUrl("dojox.mobile", "tests/doh/ComboBoxTests.html"),999999);
	if(!dojo.isIE){
		doh.registerUrl("dojox.mobile.tests.doh.ContentPane", dojo.moduleUrl("dojox.mobile", "tests/doh/ContentPaneTests.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.EdgeToEdgeDataList", dojo.moduleUrl("dojox.mobile", "tests/doh/EdgeToEdgeDataListTests.html"),999999);
	}
	doh.registerUrl("dojox.mobile.tests.doh.EdgeToEdgeCategory", dojo.moduleUrl("dojox.mobile", "tests/doh/EdgeToEdgeCategoryTests.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.EdgeToEdgeList", dojo.moduleUrl("dojox.mobile", "tests/doh/EdgeToEdgeListTests.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.ExpandingTextArea", dojo.moduleUrl("dojox.mobile", "tests/doh/ExpandingTextAreaTests.html"),999999);
	if(!dojo.isIE){
		doh.registerUrl("dojox.mobile.tests.doh.FixedSplitter", dojo.moduleUrl("dojox.mobile", "tests/doh/FixedSplitterTests1.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.FixedSplitter", dojo.moduleUrl("dojox.mobile", "tests/doh/FixedSplitterTests2.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.FixedSplitter", dojo.moduleUrl("dojox.mobile", "tests/doh/FixedSplitterTests3.html"),999999);
	}
	doh.registerUrl("dojox.mobile.tests.doh.Heading", dojo.moduleUrl("dojox.mobile", "tests/doh/HeadingTests.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.IconContainer", dojo.moduleUrl("dojox.mobile", "tests/doh/IconContainerTests.html"),999999);
	if(!dojo.isIE){
		doh.registerUrl("dojox.mobile.tests.doh.ListItem", dojo.moduleUrl("dojox.mobile", "tests/doh/ListItemTests1.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.ListItem", dojo.moduleUrl("dojox.mobile", "tests/doh/ListItemTests2.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.PageIndicator", dojo.moduleUrl("dojox.mobile", "tests/doh/PageIndicatorTests1.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.PageIndicator", dojo.moduleUrl("dojox.mobile", "tests/doh/PageIndicatorTests2.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.PageIndicator", dojo.moduleUrl("dojox.mobile", "tests/doh/PageIndicatorTests3.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.RoundRectDataList", dojo.moduleUrl("dojox.mobile", "tests/doh/RoundRectDataListTests.html"),999999);
	}
	doh.registerUrl("dojox.mobile.tests.doh.RadioButton", dojo.moduleUrl("dojox.mobile", "tests/doh/RadioButtonTests.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.RoundRectList", dojo.moduleUrl("dojox.mobile", "tests/doh/RoundRectListTests.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.TextArea", dojo.moduleUrl("dojox.mobile", "tests/doh/TextAreaTests.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.TextBox", dojo.moduleUrl("dojox.mobile", "tests/doh/TextBoxTests.html"),999999);
	if(!dojo.isIE){
		doh.registerUrl("dojox.mobile.tests.doh.TabBar", dojo.moduleUrl("dojox.mobile", "tests/doh/TabBarTests.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.SwapView", dojo.moduleUrl("dojox.mobile", "tests/doh/SwapViewTests1.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.SwapView", dojo.moduleUrl("dojox.mobile", "tests/doh/SwapViewTests2.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.SwapView", dojo.moduleUrl("dojox.mobile", "tests/doh/SwapViewTests3.html"),999999);
	}
	doh.registerUrl("dojox.mobile.tests.doh.Slider", dojo.moduleUrl("dojox.mobile", "tests/doh/SliderTests.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.Switch", dojo.moduleUrl("dojox.mobile", "tests/doh/SwitchTests.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.FilteredListTests", dojo.moduleUrl("dojox.mobile", "tests/doh/FilteredListTests.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.TemplatedWidgetsTests", dojo.moduleUrl("dojox.mobile", "tests/doh/TemplatedWidgetsTests.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.MblCSS3TransitionTests", dojo.moduleUrl("dojox.mobile", "tests/doh/MblCSS3TransitionTests.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.CustomFixedBarsTests", dojo.moduleUrl("dojox.mobile", "tests/doh/CustomFixedBarsTests.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.HeadingFixedBarsTests", dojo.moduleUrl("dojox.mobile", "tests/doh/HeadingFixedBarsTests.html"),999999);
	doh.registerUrl("dojox.mobile.tests.doh.LongListMixin", dojo.moduleUrl("dojox.mobile", "tests/doh/LongListMixin.html"),999999);
}catch(e){
	doh.debug(e);
}

<commit_msg>restructure and move to AMD module.js. Thanks Sebastien Bruno (IBM, CCLA).<commit_after>define(["doh/runner", "dojo/sniff", "require"], function(doh, has, require){
	try{
		doh.registerUrl("dojox.mobile.tests.doh.Button", require.toUrl("./Button.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.Button", require.toUrl("./Button_Programmatic.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.DatePickerIso", require.toUrl("./DatePickerIso.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.EdgeToEdgeCategory", require.toUrl("./EdgeToEdgeCategory.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.EdgeToEdgeDataList", require.toUrl("./EdgeToEdgeDataList.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.EdgeToEdgeDataList", require.toUrl("./EdgeToEdgeDataList_Programmatic.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.EdgeToEdgeStoreList", require.toUrl("./EdgeToEdgeStoreList.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.EdgeToEdgeStoreList", require.toUrl("./EdgeToEdgeStoreList_Programmatic.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.Heading", require.toUrl("./Heading.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.Heading", require.toUrl("./Heading2.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.Heading", require.toUrl("./Heading_Programmatic.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.Heading", require.toUrl("./Heading2_Programmatic.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.IconContainer", require.toUrl("./IconContainer.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.IconContainer", require.toUrl("./IconContainer2.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.IconContainer", require.toUrl("./IconContainer3.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.IconContainer", require.toUrl("./IconContainer_Programmatic.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.IconContainer", require.toUrl("./View.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.RoundRectList", require.toUrl("./RoundRect.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.ListItem", require.toUrl("./ListItem.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.ListItem", require.toUrl("./ListItem2.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.ListItem", require.toUrl("./ListItem_Programmatic.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.ListItem", require.toUrl("./ListItem2_Programmatic.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.Progress-indicator", require.toUrl("./progress-indicator.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.RoundRect", require.toUrl("./RoundRect.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.RoundRect", require.toUrl("./RoundRect_Programmatic.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.RoundRectDataList", require.toUrl("./RoundRectDataList.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.RoundRectDataList", require.toUrl("./RoundRectDataList_Programmatic.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.RoundRectStoreList", require.toUrl("./RoundRectStoreList.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.RoundRectStoreList", require.toUrl("./RoundRectStoreList_Programmatic.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.RoundRectList", require.toUrl("./RoundRectList.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.Switch", require.toUrl("./Switch.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.Switch", require.toUrl("./Switch_Programmatic.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.TabBar", require.toUrl("./TabBar.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.TabBar", require.toUrl("./TabBar_Programmatic.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.ToolBarButton", require.toUrl("./ToolBarButton.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.ToolBarButton", require.toUrl("./ToolBarButton_Programmatic.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.ToolBarButton", require.toUrl("./ToolBarButtonSetter.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.View", require.toUrl("./View.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.View", require.toUrl("./View_Programmatic.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.View", require.toUrl("./View2_Programmatic.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.View", require.toUrl("./View3_Programmatic.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.View", require.toUrl("./View-demo.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.URLProperty", require.toUrl("./TestURLProp.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.URLProperty", require.toUrl("./TestURLProp2.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.SpinWheel", require.toUrl("./SpinWheel_Programmatic.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.SpinWheelDatePicker", require.toUrl("./SpinWheelDatePicker.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.ValuePickerDatePicker", require.toUrl("./ValuePickerDatePicker.html"),999999);

		doh.registerUrl("dojox.mobile.tests.doh.Button", require.toUrl("./ButtonTests.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.CheckBox", require.toUrl("./CheckBoxTests.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.ComboBoxTests", require.toUrl("./ComboBoxTests.html"),999999);
		if(!has("ie")){
			doh.registerUrl("dojox.mobile.tests.doh.ContentPane", require.toUrl("./ContentPaneTests.html"),999999);
			doh.registerUrl("dojox.mobile.tests.doh.EdgeToEdgeDataList", require.toUrl("./EdgeToEdgeDataListTests.html"),999999);
		}
		doh.registerUrl("dojox.mobile.tests.doh.EdgeToEdgeCategory", require.toUrl("./EdgeToEdgeCategoryTests.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.EdgeToEdgeList", require.toUrl("./EdgeToEdgeListTests.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.ExpandingTextArea", require.toUrl("./ExpandingTextAreaTests.html"),999999);
		if(!has("ie")){
			doh.registerUrl("dojox.mobile.tests.doh.FixedSplitter", require.toUrl("./FixedSplitterTests1.html"),999999);
			doh.registerUrl("dojox.mobile.tests.doh.FixedSplitter", require.toUrl("./FixedSplitterTests2.html"),999999);
			doh.registerUrl("dojox.mobile.tests.doh.FixedSplitter", require.toUrl("./FixedSplitterTests3.html"),999999);
		}
		doh.registerUrl("dojox.mobile.tests.doh.Heading", require.toUrl("./HeadingTests.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.IconContainer", require.toUrl("./IconContainerTests.html"),999999);
		if(!has("ie")){
			doh.registerUrl("dojox.mobile.tests.doh.ListItem", require.toUrl("./ListItemTests1.html"),999999);
			doh.registerUrl("dojox.mobile.tests.doh.ListItem", require.toUrl("./ListItemTests2.html"),999999);
			doh.registerUrl("dojox.mobile.tests.doh.PageIndicator", require.toUrl("./PageIndicatorTests1.html"),999999);
			doh.registerUrl("dojox.mobile.tests.doh.PageIndicator", require.toUrl("./PageIndicatorTests2.html"),999999);
			doh.registerUrl("dojox.mobile.tests.doh.PageIndicator", require.toUrl("./PageIndicatorTests3.html"),999999);
			doh.registerUrl("dojox.mobile.tests.doh.RoundRectDataList", require.toUrl("./RoundRectDataListTests.html"),999999);
		}
		doh.registerUrl("dojox.mobile.tests.doh.RadioButton", require.toUrl("./RadioButtonTests.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.RoundRectList", require.toUrl("./RoundRectListTests.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.TextArea", require.toUrl("./TextAreaTests.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.TextBox", require.toUrl("./TextBoxTests.html"),999999);
		if(!has("ie")){
			doh.registerUrl("dojox.mobile.tests.doh.TabBar", require.toUrl("./TabBarTests.html"),999999);
			doh.registerUrl("dojox.mobile.tests.doh.SwapView", require.toUrl("./SwapViewTests1.html"),999999);
			doh.registerUrl("dojox.mobile.tests.doh.SwapView", require.toUrl("./SwapViewTests2.html"),999999);
			doh.registerUrl("dojox.mobile.tests.doh.SwapView", require.toUrl("./SwapViewTests3.html"),999999);
		}
		doh.registerUrl("dojox.mobile.tests.doh.Slider", require.toUrl("./SliderTests.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.Switch", require.toUrl("./SwitchTests.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.FilteredListTests", require.toUrl("./FilteredListTests.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.TemplatedWidgetsTests", require.toUrl("./TemplatedWidgetsTests.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.MblCSS3TransitionTests", require.toUrl("./MblCSS3TransitionTests.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.CustomFixedBarsTests", require.toUrl("./CustomFixedBarsTests.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.HeadingFixedBarsTests", require.toUrl("./HeadingFixedBarsTests.html"),999999);
		doh.registerUrl("dojox.mobile.tests.doh.LongListMixin", require.toUrl("./LongListMixin.html"),999999);
	}catch(e){
		doh.debug(e);
	}
});<|endoftext|>


<commit_before>/*
 * @name 点画(Pointillism)
 * @description 作者：Dan Shiffman。
 * 鼠标水平位置控制点的大小，由左到右对应由小到大的点。
 * 通过带有原图像素颜色的椭圆创建出一副简单的点画。
 *
要在本地运行此范例，您需要一个图像文件，并运行在
 * 本地伺服器上。

 */
// 声明变量'img', 'smallPoint', 'largePoing'
let img;
let smallPoint, largePoint;

function preload() {
  // 加载图像
  img = loadImage('assets/moonwalk.jpg');
}

function setup() {
  createCanvas(720, 400);
  // 设置最小点宽度为 4，最大点宽度为 40
  smallPoint = 4;
  largePoint = 40;
  imageMode(CENTER);
  noStroke();
  // 设置背景颜色为白色
  background(255);
  img.loadPixels();
}

function draw() {
  // map() 函数根据鼠标水平位置，
  // 将其在[0, 画布宽度] 的数值对应到[最小点宽度, 最大点宽度] ([4,40]) 之中，
  // 对应的数值即为点的大小
  let pointillize = map(mouseX, 0, width, smallPoint, largePoint);
  // 随机生成坐标(x, y)
  let x = floor(random(img.width));
  let y = floor(random(img.height));
  // 得到图像中坐标(x, y) 的颜色
  let pix = img.get(x, y);
  // fill(灰度值，透明度值)
  fill(pix, 128);
  ellipse(x, y, pointillize, pointillize);
}
<commit_msg>Update src/data/examples/zh-Hans/05_Image/05_Pointillism.js<commit_after>/*
 * @name 点画(Pointillism)
 * @description 作者：Dan Shiffman。
 * 鼠标水平位置控制点的大小，由左到右对应由小到大的点。
 * 通过带有原图像素颜色的椭圆创建出一副简单的点画。
 *
要在本地运行此范例，您需要一个图像文件，并运行在
 * 本地伺服器上。

 */
// 声明变量'img', 'smallPoint', 'largePoing'
let img;
let smallPoint, largePoint;

function preload() {
  // 加载图像
  img = loadImage('assets/moonwalk.jpg');
}

function setup() {
  createCanvas(720, 400);
  // 设置最小点宽度为 4，最大点宽度为 40
  smallPoint = 4;
  largePoint = 40;
  imageMode(CENTER);
  noStroke();
  // 设置背景颜色为白色
  background(255);
  img.loadPixels();
}

function draw() {
  // map() 函数根据鼠标水平位置，
  // 将其在 [0, 画布宽度] 的数值对应到 [最小点宽度, 最大点宽度] ([4,40]) 之中，
  // 对应的数值即为点的大小
  let pointillize = map(mouseX, 0, width, smallPoint, largePoint);
  // 随机生成坐标(x, y)
  let x = floor(random(img.width));
  let y = floor(random(img.height));
  // 得到图像中坐标(x, y) 的颜色
  let pix = img.get(x, y);
  // fill(灰度值，透明度值)
  fill(pix, 128);
  ellipse(x, y, pointillize, pointillize);
}
<|endoftext|>


<commit_before>odoo.define("base_import_map.map", function(require) {
    "use strict";

    var ControlPanelMixin = require("web.ControlPanelMixin");
    var BaseImport = require("base_import.import");
    var core = require("web.core");

    var QWeb = core.qweb;
    var _lt = core._lt;
    var _t = core._t;

    BaseImport.DataImport.include({
        init: function() {
            // Assign a new array instead of pushing values to the
            // original one, because otherwise we would change the
            // prototype array, meaning that each time 'init' is called
            // the values are pushed again, resulting in duplicate entries
            this.opts = this.opts.concat([
                {name: "settings", label: _lt("Settings:"), value: ""},
                {name: "save_settings", label: _lt("Save settings:"), value: ""},
                {name: "file_read_hook", label: _lt("File read hook:"), value: ""},
            ]);
            this._super.apply(this, arguments);
        },
        start: function() {
            var self = this;
            this.setup_settings_picker();
            this._super();
        },
        setup_settings_picker: function() {
            var self = this;
            self._rpc({
                model: "base_import_map.map",
                method: "search_read",
                args: [[["model", "=", this.res_model]], ["name"]],
            }).then(function(res) {
                var suggestions = [];
                if (res) {
                    res.forEach(function(item) {
                        suggestions.push({id: item.id, text: item.name});
                    });
                } else {
                    suggestions.push({id: "None", text: _t("None")});
                }
                self.$("input.oe_import_settings").select2({
                    width: "160px",
                    query: function(q) {
                        if (q.term) {
                            suggestions.unshift({id: q.term, text: q.term});
                        }
                        q.callback({results: suggestions});
                    },
                    initSelection: function(e, c) {
                        return c({id: "None", text: _t("None")});
                    },
                });
            });
        },
    });
});
<commit_msg>:green_heart: base_import_map/static/src/js/base_import_map<commit_after>odoo.define("base_import_map.map", function(require) {
    "use strict";

    var BaseImport = require("base_import.import");
    var core = require("web.core");

    var _lt = core._lt;
    var _t = core._t;

    BaseImport.DataImport.include({
        init: function() {
            // Assign a new array instead of pushing values to the
            // original one, because otherwise we would change the
            // prototype array, meaning that each time 'init' is called
            // the values are pushed again, resulting in duplicate entries
            this.opts = this.opts.concat([
                {name: "settings", label: _lt("Settings:"), value: ""},
                {name: "save_settings", label: _lt("Save settings:"), value: ""},
                {name: "file_read_hook", label: _lt("File read hook:"), value: ""},
            ]);
            this._super.apply(this, arguments);
        },
        start: function() {
            this.setup_settings_picker();
            this._super();
        },
        setup_settings_picker: function() {
            var self = this;
            self._rpc({
                model: "base_import_map.map",
                method: "search_read",
                args: [[["model", "=", this.res_model]], ["name"]],
            }).then(function(res) {
                var suggestions = [];
                if (res) {
                    res.forEach(function(item) {
                        suggestions.push({id: item.id, text: item.name});
                    });
                } else {
                    suggestions.push({id: "None", text: _t("None")});
                }
                self.$("input.oe_import_settings").select2({
                    width: "160px",
                    query: function(q) {
                        if (q.term) {
                            suggestions.unshift({id: q.term, text: q.term});
                        }
                        q.callback({results: suggestions});
                    },
                    initSelection: function(e, c) {
                        return c({id: "None", text: _t("None")});
                    },
                });
            });
        },
    });
});
<|endoftext|>


<commit_before>import { get } from 'lodash';

/**
 * Utility functions to make DOM manipulation easier.
 */

const NODE_TYPE = {
  ELEMENT_NODE: 1,
  TEXT_NODE: 3
};

export default function dom(el) {

  return {

    get el() {
      return el;
    },
    /**
     * Adds class to element.
     * @param {string} className
     */
    addClass(className) {
      if (el.classList) {
        el.classList.add(className);
      } else {
        el.className += ' ' + className;
      }
    },

    /**
     * Removes class from element.
     * @param {string} className
     */
    removeClass(className) {
      if (el.classList) {
        el.classList.remove(className);
      } else {
        el.className = el.className.replace(
          new RegExp('(^|\\b)' + className + '(\\b|$)', 'gi'), ' '
        );
      }
    },

    /**
     * Prepends child nodes to base element.
     * @param {Node[]} nodesToPrepend
     */
    prepend(nodesToPrepend) {
      var nodes = Array.prototype.slice.call(nodesToPrepend),
        i = nodes.length;

      while (i--) {
        el.insertBefore(nodes[i], el.firstChild);
      }
    },

    /**
     * Appends child nodes to base element.
     * @param {Node[]} nodesToAppend
     */
    append(nodesToAppend) {
      var nodes = Array.prototype.slice.call(nodesToAppend);

      for (var i = 0, len = nodes.length; i < len; ++i) {
        el.appendChild(nodes[i]);
      }
    },

    /**
     * Inserts base element after refEl.
     * @param {Node} refEl - node after which base element will be inserted
     * @returns {Node} - inserted element
     */
    insertAfter(refEl) {
      return refEl.parentNode.insertBefore(el, refEl.nextSibling);
    },

    /**
     * Inserts base element before refEl.
     * @param {Node} refEl - node before which base element will be inserted
     * @returns {Node} - inserted element
     */
    insertBefore(refEl) {
      return refEl.parentNode.insertBefore(el, refEl);
    },

    /**
     * Removes base element from DOM.
     */
    remove() {
      el.parentNode.removeChild(el);
      el = null;
    },

    /**
     * Returns true if base element contains given child.
     * @param {Node|HTMLElement} child
     * @returns {boolean}
     */
    contains(child) {
      return el !== child && el.contains(child);
    },

    /**
     * Wraps base element in wrapper element.
     * @param {HTMLElement} wrapper
     * @returns {HTMLElement} wrapper element
     */
    wrap(wrapper) {
      if (el.parentNode) {
        el.parentNode.insertBefore(wrapper, el);
      }

      wrapper.appendChild(el);
      return wrapper;
    },

    /**
     * Unwraps base element.
     * @returns {Node[]} - child nodes of unwrapped element.
     */
    unwrap() {
      var nodes = Array.prototype.slice.call(el.childNodes),
        wrapper;

      nodes.forEach(function (node) {
        wrapper = node.parentNode;
        dom(node).insertBefore(node.parentNode);
        dom(wrapper).remove();
      });

      return nodes;
    },

    /**
     * Returns array of base element parents.
     * @returns {HTMLElement[]}
     */
    parents() {
      var parent, path = [];
      while (!!(parent = el.parentNode)) {
        path.push(parent);
        el = parent;
      }
      return path;
    },

    /**
     * Normalizes text nodes within base element, ie. merges sibling text nodes and assures that every
     * element node has only one text node.
     * It should does the same as standard element.normalize, but IE implements it incorrectly.
     */
    normalizeTextNodes() {
      if (!el) {
        return;
      }

      if (el.nodeType === NODE_TYPE.TEXT_NODE) {
        while (el.nextSibling && el.nextSibling.nodeType === NODE_TYPE.TEXT_NODE) {
          el.nodeValue += el.nextSibling.nodeValue;
          el.parentNode.removeChild(el.nextSibling);
        }
      } else {
        dom(el.firstChild).normalizeTextNodes();
      }
      dom(el.nextSibling).normalizeTextNodes();
    },

    /**
     * Returns element background color.
     * @returns {CSSStyleDeclaration.backgroundColor}
     */
    color() {
      return get(el, 'style.backgroundColor');
    },

    /**
     * Creates dom element from given html string.
     * @param {string} html
     * @returns {NodeList}
     */
    fromHTML(html) {
      var div = document.createElement('div');
      div.innerHTML = html;
      return div.childNodes;
    },

    /**
     * Returns first range of the window of base element.
     * @returns {Range}
     */
    getRange() {
      var selection = dom(el).getSelection(),
        range;

      if (selection.rangeCount > 0) {
        range = selection.getRangeAt(0);
      }

      return range;
    },

    /**
     * Removes all ranges of the window of base element.
     */
    removeAllRanges() {
      var selection = dom(el).getSelection();
      selection.removeAllRanges();
    },

    /**
     * Returns selection object of the window of base element.
     * @returns {Selection}
     */
    getSelection() {
      return dom(el).getWindow().getSelection();
    },

    /**
     * Returns window of the base element.
     * @returns {Window}
     */
    getWindow() {
      return dom(el).getDocument().defaultView;
    },

    /**
     * Returns document of the base element.
     * @returns {HTMLDocument}
     */
    getDocument() {
      // if ownerDocument is null then el is the document itself.
      return el.ownerDocument || el;
    },

    matches(selector) {
      const method = el.matches || el.mozMatchesSelector || el.msMatchesSelector || el.oMatchesSelector || el.webkitMatchesSelector;
      return (method != null ? method.call(el, selector) : undefined);
    },

    isParent(parent, options) {
      if (options == null) { options = { matchSame: true }; }
      if (!parent) { return false; }
      if (options.matchSame && (parent === el)) { return true; }
      let node = el.parentNode;
      while (node) {
        if (node === parent) { return true; }
        node = node.parentNode;
      }
      return false;
    },

    closest(selector) {
      if (this.matches(selector)) {
        return el;
      } else {
        return el.parentNode ? dom(el.parentNode).closest(selector) : null;
      }
    },

    farthest(selector) {
      const thisMatches = this.matches(selector);

      if (el.parentNode && thisMatches) {
        return dom(el.parentNode).farthest(selector) || el;
      } else if (el.parentNode) {
        return dom(el.parentNode).farthest(selector);
      } else {
        return thisMatches ? el : null;
      }
    },

  };

}

export function read_csrf() {
  const meta = document.querySelector('meta[name=csrf-token]');
  return meta ? meta.getAttribute('content') : '';
}

export function readBootstrapData(root = document) {
  const el = root.querySelector('#tutor-boostrap-data');
  if (el) {
    el.parentNode.removeChild(el);
    return JSON.parse(el.textContent);
  } else {
    return {};
  }
}
<commit_msg>fix isParent so it iterates up the passed node<commit_after>import { get } from 'lodash';

/**
 * Utility functions to make DOM manipulation easier.
 */

const NODE_TYPE = {
  ELEMENT_NODE: 1,
  TEXT_NODE: 3
};

export default function dom(el) {

  return {

    get el() {
      return el;
    },
    /**
     * Adds class to element.
     * @param {string} className
     */
    addClass(className) {
      if (el.classList) {
        el.classList.add(className);
      } else {
        el.className += ' ' + className;
      }
    },

    /**
     * Removes class from element.
     * @param {string} className
     */
    removeClass(className) {
      if (el.classList) {
        el.classList.remove(className);
      } else {
        el.className = el.className.replace(
          new RegExp('(^|\\b)' + className + '(\\b|$)', 'gi'), ' '
        );
      }
    },

    /**
     * Prepends child nodes to base element.
     * @param {Node[]} nodesToPrepend
     */
    prepend(nodesToPrepend) {
      var nodes = Array.prototype.slice.call(nodesToPrepend),
        i = nodes.length;

      while (i--) {
        el.insertBefore(nodes[i], el.firstChild);
      }
    },

    /**
     * Appends child nodes to base element.
     * @param {Node[]} nodesToAppend
     */
    append(nodesToAppend) {
      var nodes = Array.prototype.slice.call(nodesToAppend);

      for (var i = 0, len = nodes.length; i < len; ++i) {
        el.appendChild(nodes[i]);
      }
    },

    /**
     * Inserts base element after refEl.
     * @param {Node} refEl - node after which base element will be inserted
     * @returns {Node} - inserted element
     */
    insertAfter(refEl) {
      return refEl.parentNode.insertBefore(el, refEl.nextSibling);
    },

    /**
     * Inserts base element before refEl.
     * @param {Node} refEl - node before which base element will be inserted
     * @returns {Node} - inserted element
     */
    insertBefore(refEl) {
      return refEl.parentNode.insertBefore(el, refEl);
    },

    /**
     * Removes base element from DOM.
     */
    remove() {
      el.parentNode.removeChild(el);
      el = null;
    },

    /**
     * Returns true if base element contains given child.
     * @param {Node|HTMLElement} child
     * @returns {boolean}
     */
    contains(child) {
      return el !== child && el.contains(child);
    },

    /**
     * Wraps base element in wrapper element.
     * @param {HTMLElement} wrapper
     * @returns {HTMLElement} wrapper element
     */
    wrap(wrapper) {
      if (el.parentNode) {
        el.parentNode.insertBefore(wrapper, el);
      }

      wrapper.appendChild(el);
      return wrapper;
    },

    /**
     * Unwraps base element.
     * @returns {Node[]} - child nodes of unwrapped element.
     */
    unwrap() {
      var nodes = Array.prototype.slice.call(el.childNodes),
        wrapper;

      nodes.forEach(function (node) {
        wrapper = node.parentNode;
        dom(node).insertBefore(node.parentNode);
        dom(wrapper).remove();
      });

      return nodes;
    },

    /**
     * Returns array of base element parents.
     * @returns {HTMLElement[]}
     */
    parents() {
      var parent, path = [];
      while (!!(parent = el.parentNode)) {
        path.push(parent);
        el = parent;
      }
      return path;
    },

    /**
     * Normalizes text nodes within base element, ie. merges sibling text nodes and assures that every
     * element node has only one text node.
     * It should does the same as standard element.normalize, but IE implements it incorrectly.
     */
    normalizeTextNodes() {
      if (!el) {
        return;
      }

      if (el.nodeType === NODE_TYPE.TEXT_NODE) {
        while (el.nextSibling && el.nextSibling.nodeType === NODE_TYPE.TEXT_NODE) {
          el.nodeValue += el.nextSibling.nodeValue;
          el.parentNode.removeChild(el.nextSibling);
        }
      } else {
        dom(el.firstChild).normalizeTextNodes();
      }
      dom(el.nextSibling).normalizeTextNodes();
    },

    /**
     * Returns element background color.
     * @returns {CSSStyleDeclaration.backgroundColor}
     */
    color() {
      return get(el, 'style.backgroundColor');
    },

    /**
     * Creates dom element from given html string.
     * @param {string} html
     * @returns {NodeList}
     */
    fromHTML(html) {
      var div = document.createElement('div');
      div.innerHTML = html;
      return div.childNodes;
    },

    /**
     * Returns first range of the window of base element.
     * @returns {Range}
     */
    getRange() {
      var selection = dom(el).getSelection(),
        range;

      if (selection.rangeCount > 0) {
        range = selection.getRangeAt(0);
      }

      return range;
    },

    /**
     * Removes all ranges of the window of base element.
     */
    removeAllRanges() {
      var selection = dom(el).getSelection();
      selection.removeAllRanges();
    },

    /**
     * Returns selection object of the window of base element.
     * @returns {Selection}
     */
    getSelection() {
      return dom(el).getWindow().getSelection();
    },

    /**
     * Returns window of the base element.
     * @returns {Window}
     */
    getWindow() {
      return dom(el).getDocument().defaultView;
    },

    /**
     * Returns document of the base element.
     * @returns {HTMLDocument}
     */
    getDocument() {
      // if ownerDocument is null then el is the document itself.
      return el.ownerDocument || el;
    },

    matches(selector) {
      const method = el.matches || el.mozMatchesSelector || el.msMatchesSelector || el.oMatchesSelector || el.webkitMatchesSelector;
      return (method != null ? method.call(el, selector) : undefined);
    },

    isParent(node, options) {
      if (options == null) { options = { matchSame: true }; }
      if (!parent) { return false; }
      if (options.matchSame && (node === el)) { return true; }
      node = node.parentNode;
      while (node) {
        if (node === el) { return true; }
        node = node.parentNode;
      }
      return false;
    },

    closest(selector) {
      if (this.matches(selector)) {
        return el;
      } else {
        return el.parentNode ? dom(el.parentNode).closest(selector) : null;
      }
    },

    farthest(selector) {
      const thisMatches = this.matches(selector);

      if (el.parentNode && thisMatches) {
        return dom(el.parentNode).farthest(selector) || el;
      } else if (el.parentNode) {
        return dom(el.parentNode).farthest(selector);
      } else {
        return thisMatches ? el : null;
      }
    },

  };

}

export function read_csrf() {
  const meta = document.querySelector('meta[name=csrf-token]');
  return meta ? meta.getAttribute('content') : '';
}

export function readBootstrapData(root = document) {
  const el = root.querySelector('#tutor-boostrap-data');
  if (el) {
    el.parentNode.removeChild(el);
    return JSON.parse(el.textContent);
  } else {
    return {};
  }
}
<|endoftext|>


<commit_before>import ListFormRoute from 'ember-flexberry/routes/list-form';
import ListFormRouteOperationsIndicationMixin from 'dummy/mixins/list-form-route-operations-indication';

export default ListFormRoute.extend(ListFormRouteOperationsIndicationMixin, {
  /**
   Name of model projection to be used as record's properties limitation.

   @property modelProjection
   @type String
   @default 'SuggestionL'
   */
  modelProjection: 'SuggestionL',

  /**
  developerUserSettings.
  Format:
  {
  <componentName>: {
    <settingName>: {
        colsOrder: [ { propName :<colName>, hide: true|false }, ... ],
        sorting: [{ propName: <colName>, direction: "asc"|"desc" }, ... ],
        colsWidths: [ <colName>:<colWidth>, ... ],
      },
      ...
    },
    ...
  }
  For default userSetting use empty name ('').
  <componentName> may contain any of properties: colsOrder, sorting, colsWidth or being empty.

  @property developerUserSettings
  @type Object
  @default {}
  */
  developerUserSettings: {
    SuggestionObjectListView: {
      'DEFAULT': {
        'columnWidths': [{ 'propName': 'OlvRowToolbar', 'fixed': true, 'width': 86 }, { 'propName': 'OlvRowMenu', 'fixed': true, 'width': 68 }]
      }
    }
  },

  /**
    Name of model to be used as list's records types.

    @property modelName
    @type String
    @default 'ember-flexberry-dummy-suggestion'
   */
  modelName: 'ember-flexberry-dummy-suggestion',

  /**
    This method will be invoked always when load operation completed,
    regardless of load promise's state (was it fulfilled or rejected).

    @method onModelLoadingAlways.
    @param {Object} data Data about completed load operation.
   */
  onModelLoadingAlways(data) {
    let loadCount = this.get('controller.loadCount') + 1;
    this.set('controller.loadCount', loadCount);
  },
});
<commit_msg>Correct mistake<commit_after>import ListFormRoute from 'ember-flexberry/routes/list-form';
import ListFormRouteOperationsIndicationMixin from 'dummy/mixins/list-form-route-operations-indication';

export default ListFormRoute.extend(ListFormRouteOperationsIndicationMixin, {
  /**
   Name of model projection to be used as record's properties limitation.

   @property modelProjection
   @type String
   @default 'SuggestionL'
   */
  modelProjection: 'SuggestionL',

  /**
  developerUserSettings.
  Format:
  {
  <componentName>: {
    <settingName>: {
        colsOrder: [ { propName :<colName>, hide: true|false }, ... ],
        sorting: [{ propName: <colName>, direction: "asc"|"desc" }, ... ],
        colsWidths: [ <colName>:<colWidth>, ... ],
      },
      ...
    },
    ...
  }
  For default userSetting use empty name ('').
  <componentName> may contain any of properties: colsOrder, sorting, colsWidth or being empty.

  @property developerUserSettings
  @type Object
  @default {}
  */
  developerUserSettings: {
    SuggestionObjectListView: {
      'DEFAULT': {
        'columnWidths': [{ 'propName': 'OlvRowToolbar', 'fixed': true, 'width': 86 }, { 'propName': 'OlvRowMenu', 'fixed': true, 'width': 68 }]
      }
    }
  },

  /**
    Name of model to be used as list's records types.

    @property modelName
    @type String
    @default 'ember-flexberry-dummy-suggestion'
   */
  modelName: 'ember-flexberry-dummy-suggestion',

  /**
    This method will be invoked always when load operation completed,
    regardless of load promise's state (was it fulfilled or rejected).

    @method onModelLoadingAlways.
    @param {Object} data Data about completed load operation.
   */
  onModelLoadingAlways(data) {
    let loadCount = this.get('controller.loadCount') + 1;
    this.set('controller.loadCount', loadCount);
  },
});
<|endoftext|>


<commit_before>// This file cannot be Coffeescript because it loads before the
// Coffeescript interpreter. Note that it runs in both browser and
// renderer processes.

var ErrorLogger, _, fs, path, app, os, remote;
os = require('os');
fs = require('fs-plus');
path = require('path');
let ipcRenderer = null;
if (process.type === 'renderer') {
  ipcRenderer = require('electron').ipcRenderer;
  remote = require('electron').remote;
  app = remote.app;
} else {
  app = require('electron').app;
}

var crashReporter = require('electron').crashReporter

// A globally available ErrorLogger that can report errors to various
// sources and enhance error functionality.
//
// This runs in both the backend browser process and each and every
// renderer process.
//
// This is available as `global.errorLogger` in the backend browser
// process.
//
// It is available at `NylasEnv.errorLogger` in each renderer process.
// You should almost always use `NylasEnv.reportError` in the renderer
// processes instead of manually accessing the `errorLogger`
//
// The errorLogger will report errors to a log file as well as to 3rd
// party reporting services if enabled.
module.exports = ErrorLogger = (function() {

  function ErrorLogger(args) {
    this.reportError = this.reportError.bind(this)
    this.inSpecMode = args.inSpecMode
    this.inDevMode = args.inDevMode
    this.resourcePath = args.resourcePath

    this._startCrashReporter()

    this._extendErrorObject()

    this._extendNativeConsole()

    this.extensions = this._setupErrorLoggerExtensions(args)

    if (this.inSpecMode) { return }

    this._cleanOldLogFiles();
    this._setupNewLogFile();
    this._hookProcessOutputsToLogFile();
  }

  /////////////////////////////////////////////////////////////////////
  /////////////////////////// PUBLIC METHODS //////////////////////////
  /////////////////////////////////////////////////////////////////////

  ErrorLogger.prototype.reportError = function(error, extra) {
    if (!error) { error = {stack: ""} }
    this._appendLog(error.stack)
    if (extra) { this._appendLog(extra) }
    if (process.type === "renderer") {
      var errorJSON = JSON.stringify(error);

      /**
       * We synchronously send all errors to the backend main process.
       *
       * This is important because errors can frequently happen right
       * before a renderer window is closing. Since error reporting hits
       * APIs and is asynchronous it's possible for the window to be
       * destroyed before the report makes it.
       *
       * This is a rare use of `sendSync` to ensure the command has made
       * it before the window closes.
       */
      ipcRenderer.sendSync("report-error", {errorJSON: errorJSON, extra: JSON.stringify(extra)})

    } else {
      var nslog = require('nslog');

      this._notifyExtensions("reportError", error, extra)
      nslog(error.stack)
    }
  }

  ErrorLogger.prototype.openLogs = function() {
    var shell = require('electron').shell;
    shell.openItem(this._logPath());
  };

  ErrorLogger.prototype.apiDebug = function(error) {
    this._appendLog(error, error.statusCode, error.message);
    this._notifyExtensions("onDidLogAPIError", error);
  }

  /////////////////////////////////////////////////////////////////////
  ////////////////////////// PRIVATE METHODS //////////////////////////
  /////////////////////////////////////////////////////////////////////

  ErrorLogger.prototype._startCrashReporter = function(args) {
    crashReporter.start({
      productName: 'Nylas Mail',
      companyName: 'Nylas',
      submitURL: 'https://electron-crash-report-server.herokuapp.com/',
      autoSubmit: true,
    })
  }

  ErrorLogger.prototype._extendNativeConsole = function(args) {
    console.debug = this._consoleDebug.bind(this)

    if (process.type === 'browser' && process.platform === 'darwin') {
      var nslog = require('nslog');
      console.log = nslog;
      console.error = nslog;
    }
  }

  // globally define Error.toJSON. This allows us to pass errors via IPC
  // and through the Action Bridge. Note:they are not re-inflated into
  // Error objects automatically.
  ErrorLogger.prototype._extendErrorObject = function(args) {
    Object.defineProperty(Error.prototype, 'toJSON', {
      value: function () {
        var alt = {};

        Object.getOwnPropertyNames(this).forEach(function (key) {
          alt[key] = this[key];
        }, this);

        return alt;
      },
      configurable: true
    });
  }

  ErrorLogger.prototype._setupErrorLoggerExtensions = function(args) {
    var extension, extensionConstructor, extensionPath, extensions, extensionsPath, i, len, ref;
    if (args == null) {
      args = {};
    }
    extensions = [];
    extensionsPath = path.join(args.resourcePath, 'src', 'error-logger-extensions');
    ref = fs.listSync(extensionsPath);
    for (i = 0, len = ref.length; i < len; i++) {
      extensionPath = ref[i];
      if (path.basename(extensionPath)[0] === '.') {
        continue;
      }
      extensionConstructor = require(extensionPath);
      if (!(typeof extensionConstructor === "function")) {
        throw new Error("Logger Extensions must return an extension constructor");
      }
      extension = new extensionConstructor({
        inSpecMode: args.inSpecMode,
        inDevMode: args.inDevMode,
        resourcePath: args.resourcePath
      });
      extensions.push(extension);
    }
    return extensions;
  };

  ErrorLogger.prototype._logPath = function() {
    var tmpPath = app.getPath('temp');

    var logpid = process.pid;
    if (process.type === 'renderer') {
      logpid = remote.process.pid + "." +  process.pid;
    }
    return path.join(tmpPath, 'Nylas-Mail-' + logpid + '.log');
  }

  // If we're the browser process, remove log files that are more than
  // two days old. These log files get pretty big because we're logging
  // so verbosely.
  ErrorLogger.prototype._cleanOldLogFiles = function() {
    if (process.type === 'browser') {
      var tmpPath = app.getPath('temp');
      fs.readdir(tmpPath, function(err, files) {
        if (err) {
          console.error(err);
          return;
        }

        var logFilter = new RegExp("Nylas-Mail-[.0-9]*.log$");
        files.forEach(function(file) {
          if (logFilter.test(file) === true) {
            var filepath = path.join(tmpPath, file);
            fs.stat(filepath, function(err, stats) {
              if (!err && stats) {
                var lastModified = new Date(stats['mtime']);
                var fileAge = Date.now() - lastModified.getTime();
                if (fileAge > (1000 * 60 * 60 * 24 * 2)) { // two days
                  fs.unlink(filepath);
                }
              }
            });
          }
        });
      });
    }
  }

  ErrorLogger.prototype._setupNewLogFile = function() {
    // Open a file write stream to log output from this process
    console.log("Streaming log data to "+this._logPath());

    this.loghost = os.hostname();
    this.logstream = fs.createWriteStream(this._logPath(), {
      flags: 'a',
      encoding: 'utf8',
      fd: null,
      mode: 666,
    });
  }

  ErrorLogger.prototype._hookProcessOutputsToLogFile = function() {
    var self = this;
    // Override stdout and stderr to pipe their output to the file
    // in addition to calling through to the existing implementation
    function hook_process_output(channel, callback) {
      var old_write = process[channel].write;
      process[channel].write = (function(write) {
          return function(string, encoding, fd) {
              write.apply(process[channel], arguments)
              callback(string, encoding, fd)
          }
      })(process[channel].write)

      // Return a function that can be used to undo this change
      return function() {
        process[channel].write = old_write
      };
    }

    hook_process_output('stdout', function(string, encoding, fd) {
      self._appendLog.apply(self, [string]);
    });
    hook_process_output('stderr', function(string, encoding, fd) {
      self._appendLog.apply(self, [string]);
    });
  }

  ErrorLogger.prototype._notifyExtensions = function() {
    var command, args;
    command = arguments[0]
    args = 2 <= arguments.length ? Array.prototype.slice.call(arguments, 1) : [];
    for (var i=0; i < this.extensions.length; i++) {
      const extension = this.extensions[i]
      extension[command].apply(this, args);
    }
  }

  // Create a new console.debug option, which takes `true` (print)
  // or `false`, don't print in console as the first parameter.
  // This makes it easy for developers to turn on and off
  // "verbose console" mode.
  ErrorLogger.prototype._consoleDebug = function() {
    var args = [];
    var showIt = arguments[0];
    for (var ii = 1; ii < arguments.length; ii++) {
      args.push(arguments[ii]);
    }
    if ((this.inDevMode === true) && (showIt === true)) {
      console.log.apply(console, args);
    }
    this._appendLog.apply(this, [args]);
  }

  ErrorLogger.prototype._appendLog = function(obj) {
    if (this.inSpecMode) { return };

    try {
      var message = JSON.stringify({
        host: this.loghost,
        timestamp: (new Date()).toISOString(),
        payload: obj
      })+"\n";

      this.logstream.write(message, 'utf8', function (err) {
        if (err) {
          console.error("ErrorLogger: Unable to write to the log stream!" + err.toString());
        }
      });
    } catch (err) {
      console.error("ErrorLogger: Unable to write to the log stream." + err.toString());
    }
  };

  return ErrorLogger;

})();
<commit_msg>fix(spec) Never report errors in spec mode<commit_after>// This file cannot be Coffeescript because it loads before the
// Coffeescript interpreter. Note that it runs in both browser and
// renderer processes.

var ErrorLogger, _, fs, path, app, os, remote;
os = require('os');
fs = require('fs-plus');
path = require('path');
let ipcRenderer = null;
if (process.type === 'renderer') {
  ipcRenderer = require('electron').ipcRenderer;
  remote = require('electron').remote;
  app = remote.app;
} else {
  app = require('electron').app;
}

var crashReporter = require('electron').crashReporter

// A globally available ErrorLogger that can report errors to various
// sources and enhance error functionality.
//
// This runs in both the backend browser process and each and every
// renderer process.
//
// This is available as `global.errorLogger` in the backend browser
// process.
//
// It is available at `NylasEnv.errorLogger` in each renderer process.
// You should almost always use `NylasEnv.reportError` in the renderer
// processes instead of manually accessing the `errorLogger`
//
// The errorLogger will report errors to a log file as well as to 3rd
// party reporting services if enabled.
module.exports = ErrorLogger = (function() {

  function ErrorLogger(args) {
    this.reportError = this.reportError.bind(this)
    this.inSpecMode = args.inSpecMode
    this.inDevMode = args.inDevMode
    this.resourcePath = args.resourcePath

    this._startCrashReporter()

    this._extendErrorObject()

    this._extendNativeConsole()

    this.extensions = this._setupErrorLoggerExtensions(args)

    if (this.inSpecMode) { return }

    this._cleanOldLogFiles();
    this._setupNewLogFile();
    this._hookProcessOutputsToLogFile();
  }

  /////////////////////////////////////////////////////////////////////
  /////////////////////////// PUBLIC METHODS //////////////////////////
  /////////////////////////////////////////////////////////////////////

  ErrorLogger.prototype.reportError = function(error, extra = {}) {
    if (this.inSpecMode) { return }
    if (!error) { error = {stack: ""} }
    this._appendLog(error.stack)
    if (extra) { this._appendLog(extra) }
    if (process.type === "renderer") {
      var errorJSON = JSON.stringify(error);

      /**
       * We synchronously send all errors to the backend main process.
       *
       * This is important because errors can frequently happen right
       * before a renderer window is closing. Since error reporting hits
       * APIs and is asynchronous it's possible for the window to be
       * destroyed before the report makes it.
       *
       * This is a rare use of `sendSync` to ensure the command has made
       * it before the window closes.
       */
      ipcRenderer.sendSync("report-error", {errorJSON: errorJSON, extra: JSON.stringify(extra)})

    } else {
      var nslog = require('nslog');

      this._notifyExtensions("reportError", error, extra)
      nslog(error.stack)
    }
  }

  ErrorLogger.prototype.openLogs = function() {
    var shell = require('electron').shell;
    shell.openItem(this._logPath());
  };

  ErrorLogger.prototype.apiDebug = function(error) {
    this._appendLog(error, error.statusCode, error.message);
    this._notifyExtensions("onDidLogAPIError", error);
  }

  /////////////////////////////////////////////////////////////////////
  ////////////////////////// PRIVATE METHODS //////////////////////////
  /////////////////////////////////////////////////////////////////////

  ErrorLogger.prototype._startCrashReporter = function(args) {
    crashReporter.start({
      productName: 'Nylas Mail',
      companyName: 'Nylas',
      submitURL: 'https://electron-crash-report-server.herokuapp.com/',
      autoSubmit: true,
    })
  }

  ErrorLogger.prototype._extendNativeConsole = function(args) {
    console.debug = this._consoleDebug.bind(this)

    if (process.type === 'browser' && process.platform === 'darwin') {
      var nslog = require('nslog');
      console.log = nslog;
      console.error = nslog;
    }
  }

  // globally define Error.toJSON. This allows us to pass errors via IPC
  // and through the Action Bridge. Note:they are not re-inflated into
  // Error objects automatically.
  ErrorLogger.prototype._extendErrorObject = function(args) {
    Object.defineProperty(Error.prototype, 'toJSON', {
      value: function () {
        var alt = {};

        Object.getOwnPropertyNames(this).forEach(function (key) {
          alt[key] = this[key];
        }, this);

        return alt;
      },
      configurable: true
    });
  }

  ErrorLogger.prototype._setupErrorLoggerExtensions = function(args) {
    var extension, extensionConstructor, extensionPath, extensions, extensionsPath, i, len, ref;
    if (args == null) {
      args = {};
    }
    extensions = [];
    extensionsPath = path.join(args.resourcePath, 'src', 'error-logger-extensions');
    ref = fs.listSync(extensionsPath);
    for (i = 0, len = ref.length; i < len; i++) {
      extensionPath = ref[i];
      if (path.basename(extensionPath)[0] === '.') {
        continue;
      }
      extensionConstructor = require(extensionPath);
      if (!(typeof extensionConstructor === "function")) {
        throw new Error("Logger Extensions must return an extension constructor");
      }
      extension = new extensionConstructor({
        inSpecMode: args.inSpecMode,
        inDevMode: args.inDevMode,
        resourcePath: args.resourcePath
      });
      extensions.push(extension);
    }
    return extensions;
  };

  ErrorLogger.prototype._logPath = function() {
    var tmpPath = app.getPath('temp');

    var logpid = process.pid;
    if (process.type === 'renderer') {
      logpid = remote.process.pid + "." +  process.pid;
    }
    return path.join(tmpPath, 'Nylas-Mail-' + logpid + '.log');
  }

  // If we're the browser process, remove log files that are more than
  // two days old. These log files get pretty big because we're logging
  // so verbosely.
  ErrorLogger.prototype._cleanOldLogFiles = function() {
    if (process.type === 'browser') {
      var tmpPath = app.getPath('temp');
      fs.readdir(tmpPath, function(err, files) {
        if (err) {
          console.error(err);
          return;
        }

        var logFilter = new RegExp("Nylas-Mail-[.0-9]*.log$");
        files.forEach(function(file) {
          if (logFilter.test(file) === true) {
            var filepath = path.join(tmpPath, file);
            fs.stat(filepath, function(err, stats) {
              if (!err && stats) {
                var lastModified = new Date(stats['mtime']);
                var fileAge = Date.now() - lastModified.getTime();
                if (fileAge > (1000 * 60 * 60 * 24 * 2)) { // two days
                  fs.unlink(filepath);
                }
              }
            });
          }
        });
      });
    }
  }

  ErrorLogger.prototype._setupNewLogFile = function() {
    // Open a file write stream to log output from this process
    console.log("Streaming log data to "+this._logPath());

    this.loghost = os.hostname();
    this.logstream = fs.createWriteStream(this._logPath(), {
      flags: 'a',
      encoding: 'utf8',
      fd: null,
      mode: 666,
    });
  }

  ErrorLogger.prototype._hookProcessOutputsToLogFile = function() {
    var self = this;
    // Override stdout and stderr to pipe their output to the file
    // in addition to calling through to the existing implementation
    function hook_process_output(channel, callback) {
      var old_write = process[channel].write;
      process[channel].write = (function(write) {
          return function(string, encoding, fd) {
              write.apply(process[channel], arguments)
              callback(string, encoding, fd)
          }
      })(process[channel].write)

      // Return a function that can be used to undo this change
      return function() {
        process[channel].write = old_write
      };
    }

    hook_process_output('stdout', function(string, encoding, fd) {
      self._appendLog.apply(self, [string]);
    });
    hook_process_output('stderr', function(string, encoding, fd) {
      self._appendLog.apply(self, [string]);
    });
  }

  ErrorLogger.prototype._notifyExtensions = function() {
    var command, args;
    command = arguments[0]
    args = 2 <= arguments.length ? Array.prototype.slice.call(arguments, 1) : [];
    for (var i=0; i < this.extensions.length; i++) {
      const extension = this.extensions[i]
      extension[command].apply(this, args);
    }
  }

  // Create a new console.debug option, which takes `true` (print)
  // or `false`, don't print in console as the first parameter.
  // This makes it easy for developers to turn on and off
  // "verbose console" mode.
  ErrorLogger.prototype._consoleDebug = function() {
    var args = [];
    var showIt = arguments[0];
    for (var ii = 1; ii < arguments.length; ii++) {
      args.push(arguments[ii]);
    }
    if ((this.inDevMode === true) && (showIt === true)) {
      console.log.apply(console, args);
    }
    this._appendLog.apply(this, [args]);
  }

  ErrorLogger.prototype._appendLog = function(obj) {
    if (this.inSpecMode) { return };

    try {
      var message = JSON.stringify({
        host: this.loghost,
        timestamp: (new Date()).toISOString(),
        payload: obj
      })+"\n";

      this.logstream.write(message, 'utf8', function (err) {
        if (err) {
          console.error("ErrorLogger: Unable to write to the log stream!" + err.toString());
        }
      });
    } catch (err) {
      console.error("ErrorLogger: Unable to write to the log stream." + err.toString());
    }
  };

  return ErrorLogger;

})();
<|endoftext|>


<commit_before>import macro from 'vtk.js/Sources/macros';
import vtkCompositeMouseManipulator from 'vtk.js/Sources/Interaction/Manipulators/CompositeMouseManipulator';

// ----------------------------------------------------------------------------
// vtkMouseRangeManipulator methods
// ----------------------------------------------------------------------------

function vtkMouseRangeManipulator(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkMouseRangeManipulator');

  // Keep track of delta that is below the value
  // of one step to progressively increment it
  const incrementalDelta = new Map();

  // Internal methods
  //-------------------------------------------------------------------------
  function scaleDeltaToRange(listener, normalizedDelta) {
    return (
      normalizedDelta * ((listener.max - listener.min) / (listener.step + 1))
    );
  }

  //-------------------------------------------------------------------------
  function processDelta(listener, delta) {
    const oldValue = listener.getValue();

    // Apply scale and cached delta to current delta
    const newDelta = delta * listener.scale + incrementalDelta.get(listener);
    let value = oldValue + newDelta;

    // Compute new value based on step
    const difference = value - listener.min;
    const stepsToDifference = Math.round(difference / listener.step);
    value = listener.min + listener.step * stepsToDifference;
    value = Math.max(value, listener.min);
    value = Math.min(value, listener.max);

    if (value !== oldValue) {
      // Update value
      listener.setValue(value);
      incrementalDelta.set(listener, 0);
    } else if (
      (value === listener.min && newDelta < 0) ||
      (value === listener.max && newDelta > 0)
    ) {
      // Do not allow incremental delta to go past range
      incrementalDelta.set(listener, 0);
    } else {
      // Store delta for the next iteration
      incrementalDelta.set(listener, newDelta);
    }
  }

  // Public API methods

  // min:number = minimum allowable value
  // max:number = maximum allowable value
  // step:number = value per step -- smaller = more steps over a given distance, larger = fewer steps over a given distance
  // getValue:fn = function that returns current value
  // setValue:fn = function to set value
  // scale:number = scale value is applied to mouse event to allow users accelerate or decelerate delta without emitting more events
  //-------------------------------------------------------------------------
  publicAPI.setHorizontalListener = (
    min,
    max,
    step,
    getValue,
    setValue,
    scale = 1
  ) => {
    const getFn = Number.isFinite(getValue) ? () => getValue : getValue;
    model.horizontalListener = {
      min,
      max,
      step,
      getValue: getFn,
      setValue,
      scale,
    };
    incrementalDelta.set(model.horizontalListener, 0);
    publicAPI.modified();
  };

  //-------------------------------------------------------------------------
  publicAPI.setVerticalListener = (
    min,
    max,
    step,
    getValue,
    setValue,
    scale = 1
  ) => {
    const getFn = Number.isFinite(getValue) ? () => getValue : getValue;
    model.verticalListener = {
      min,
      max,
      step,
      getValue: getFn,
      setValue,
      scale,
    };
    incrementalDelta.set(model.verticalListener, 0);
    publicAPI.modified();
  };

  //-------------------------------------------------------------------------
  publicAPI.setScrollListener = (
    min,
    max,
    step,
    getValue,
    setValue,
    scale = 1
  ) => {
    const getFn = Number.isFinite(getValue) ? () => getValue : getValue;
    model.scrollListener = { min, max, step, getValue: getFn, setValue, scale };
    incrementalDelta.set(model.scrollListener, 0);
    publicAPI.modified();
  };

  //-------------------------------------------------------------------------
  publicAPI.removeHorizontalListener = () => {
    if (model.verticalListener) {
      incrementalDelta.delete(model.verticalListener);
      delete model.verticalListener;
      publicAPI.modified();
    }
  };

  //-------------------------------------------------------------------------
  publicAPI.removeVerticalListener = () => {
    if (model.horizontalListener) {
      incrementalDelta.delete(model.horizontalListener);
      delete model.horizontalListener;
      publicAPI.modified();
    }
  };

  //-------------------------------------------------------------------------
  publicAPI.removeScrollListener = () => {
    if (model.scrollListener) {
      incrementalDelta.delete(model.scrollListener);
      delete model.scrollListener;
      publicAPI.modified();
    }
  };

  //-------------------------------------------------------------------------
  publicAPI.removeAllListeners = () => {
    publicAPI.removeHorizontalListener();
    publicAPI.removeVerticalListener();
    publicAPI.removeScrollListener();
  };

  //-------------------------------------------------------------------------
  publicAPI.onButtonDown = (interactor, renderer, position) => {
    model.previousPosition = position;
    const glRenderWindow = interactor.getView();
    // Ratio is the dom size vs renderwindow size
    const ratio =
      glRenderWindow.getContainerSize()[0] / glRenderWindow.getSize()[0];
    // Get proper pixel range used by viewport in rw size space
    const size = glRenderWindow.getViewportSize(renderer);
    // rescale size to match mouse event position
    model.containerSize = size.map((v) => v * ratio);

    if (model.usePointerLock && !interactor.isPointerLocked()) {
      interactor.requestPointerLock();
      publicAPI.startPointerLockInteraction(interactor);
    }
  };

  publicAPI.onButtonUp = () => {
    document.exitPointerLock();
  };

  publicAPI.bindEvents = (container) => {
    document.addEventListener(
      'pointerlockchange',
      publicAPI.handlePointerLockChange
    );
  };

  //--------------------------------------------------------------------------

  publicAPI.startPointerLockInteraction = (interactor) => {
    // TODO: at some point, this should perhaps be done in
    // RenderWindowInteractor instead of here.
    // We need to hook into mousemove directly for two reasons:
    // 1. We need to keep receiving mouse move events after the mouse button
    //    is released. This is currently not possible with
    //    vtkInteractorStyleManipulator.
    // 2. Since the mouse is stationary in pointer lock mode, we need the
    //    event.movementX and event.movementY info, which are not currently
    //    passed via interactor.onMouseMove.
    document.addEventListener('mousemove', publicAPI.onPointerLockMove);

    let subscription = null;
    const endInteraction = () => {
      document.removeEventListener('mousemove', publicAPI.onPointerLockMove);
      subscription?.unsubscribe();
    };
    subscription = interactor?.onEndPointerLock(endInteraction);
  };

  publicAPI.onPointerLockMove = (e) => {
    model.previousPosition.x += e.movementX;
    model.previousPosition.y += e.movementY;

    publicAPI.onMouseMove(null, null, model.previousPosition);
  };

  publicAPI.exitPointerLock = () => document.exitPointerLock();

  publicAPI.isPointerLocked = () => !!document.pointerLockElement;

  publicAPI.handlePointerLockChange = () => {
    if (publicAPI.isPointerLocked()) {
      publicAPI.startPointerLockEvent();
    } else {
      publicAPI.endPointerLockEvent();
    }
  };

  //-------------------------------------------------------------------------
  publicAPI.onMouseMove = (interactor, renderer, position) => {
    if (!model.verticalListener && !model.horizontalListener) {
      return;
    }
    if (!position) {
      return;
    }

    if (model.horizontalListener) {
      const dxNorm =
        (position.x - model.previousPosition.x) / model.containerSize[0];
      const dx = scaleDeltaToRange(model.horizontalListener, dxNorm);
      processDelta(model.horizontalListener, dx);
    }
    if (model.verticalListener) {
      const dyNorm =
        (position.y - model.previousPosition.y) / model.containerSize[1];
      const dy = scaleDeltaToRange(model.verticalListener, dyNorm);
      processDelta(model.verticalListener, dy);
    }

    model.previousPosition = position;
  };

  //-------------------------------------------------------------------------
  publicAPI.onScroll = (interactor, renderer, delta) => {
    if (!model.scrollListener || !delta) {
      return;
    }
    processDelta(model.scrollListener, delta * model.scrollListener.step);
  };
  publicAPI.onStartScroll = publicAPI.onScroll;
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  horizontalListener: null,
  verticalListener: null,
  scrollListener: null,
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Inheritance
  macro.obj(publicAPI, model);
  vtkCompositeMouseManipulator.extend(publicAPI, model, initialValues);

  // Object specific methods
  vtkMouseRangeManipulator(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(
  extend,
  'vtkMouseRangeManipulator'
);

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<commit_msg>refactor: use publicAPI.exitPointerLock<commit_after>import macro from 'vtk.js/Sources/macros';
import vtkCompositeMouseManipulator from 'vtk.js/Sources/Interaction/Manipulators/CompositeMouseManipulator';

// ----------------------------------------------------------------------------
// vtkMouseRangeManipulator methods
// ----------------------------------------------------------------------------

function vtkMouseRangeManipulator(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkMouseRangeManipulator');

  // Keep track of delta that is below the value
  // of one step to progressively increment it
  const incrementalDelta = new Map();

  // Internal methods
  //-------------------------------------------------------------------------
  function scaleDeltaToRange(listener, normalizedDelta) {
    return (
      normalizedDelta * ((listener.max - listener.min) / (listener.step + 1))
    );
  }

  //-------------------------------------------------------------------------
  function processDelta(listener, delta) {
    const oldValue = listener.getValue();

    // Apply scale and cached delta to current delta
    const newDelta = delta * listener.scale + incrementalDelta.get(listener);
    let value = oldValue + newDelta;

    // Compute new value based on step
    const difference = value - listener.min;
    const stepsToDifference = Math.round(difference / listener.step);
    value = listener.min + listener.step * stepsToDifference;
    value = Math.max(value, listener.min);
    value = Math.min(value, listener.max);

    if (value !== oldValue) {
      // Update value
      listener.setValue(value);
      incrementalDelta.set(listener, 0);
    } else if (
      (value === listener.min && newDelta < 0) ||
      (value === listener.max && newDelta > 0)
    ) {
      // Do not allow incremental delta to go past range
      incrementalDelta.set(listener, 0);
    } else {
      // Store delta for the next iteration
      incrementalDelta.set(listener, newDelta);
    }
  }

  // Public API methods

  // min:number = minimum allowable value
  // max:number = maximum allowable value
  // step:number = value per step -- smaller = more steps over a given distance, larger = fewer steps over a given distance
  // getValue:fn = function that returns current value
  // setValue:fn = function to set value
  // scale:number = scale value is applied to mouse event to allow users accelerate or decelerate delta without emitting more events
  //-------------------------------------------------------------------------
  publicAPI.setHorizontalListener = (
    min,
    max,
    step,
    getValue,
    setValue,
    scale = 1
  ) => {
    const getFn = Number.isFinite(getValue) ? () => getValue : getValue;
    model.horizontalListener = {
      min,
      max,
      step,
      getValue: getFn,
      setValue,
      scale,
    };
    incrementalDelta.set(model.horizontalListener, 0);
    publicAPI.modified();
  };

  //-------------------------------------------------------------------------
  publicAPI.setVerticalListener = (
    min,
    max,
    step,
    getValue,
    setValue,
    scale = 1
  ) => {
    const getFn = Number.isFinite(getValue) ? () => getValue : getValue;
    model.verticalListener = {
      min,
      max,
      step,
      getValue: getFn,
      setValue,
      scale,
    };
    incrementalDelta.set(model.verticalListener, 0);
    publicAPI.modified();
  };

  //-------------------------------------------------------------------------
  publicAPI.setScrollListener = (
    min,
    max,
    step,
    getValue,
    setValue,
    scale = 1
  ) => {
    const getFn = Number.isFinite(getValue) ? () => getValue : getValue;
    model.scrollListener = { min, max, step, getValue: getFn, setValue, scale };
    incrementalDelta.set(model.scrollListener, 0);
    publicAPI.modified();
  };

  //-------------------------------------------------------------------------
  publicAPI.removeHorizontalListener = () => {
    if (model.verticalListener) {
      incrementalDelta.delete(model.verticalListener);
      delete model.verticalListener;
      publicAPI.modified();
    }
  };

  //-------------------------------------------------------------------------
  publicAPI.removeVerticalListener = () => {
    if (model.horizontalListener) {
      incrementalDelta.delete(model.horizontalListener);
      delete model.horizontalListener;
      publicAPI.modified();
    }
  };

  //-------------------------------------------------------------------------
  publicAPI.removeScrollListener = () => {
    if (model.scrollListener) {
      incrementalDelta.delete(model.scrollListener);
      delete model.scrollListener;
      publicAPI.modified();
    }
  };

  //-------------------------------------------------------------------------
  publicAPI.removeAllListeners = () => {
    publicAPI.removeHorizontalListener();
    publicAPI.removeVerticalListener();
    publicAPI.removeScrollListener();
  };

  //-------------------------------------------------------------------------
  publicAPI.onButtonDown = (interactor, renderer, position) => {
    model.previousPosition = position;
    const glRenderWindow = interactor.getView();
    // Ratio is the dom size vs renderwindow size
    const ratio =
      glRenderWindow.getContainerSize()[0] / glRenderWindow.getSize()[0];
    // Get proper pixel range used by viewport in rw size space
    const size = glRenderWindow.getViewportSize(renderer);
    // rescale size to match mouse event position
    model.containerSize = size.map((v) => v * ratio);

    if (model.usePointerLock && !interactor.isPointerLocked()) {
      interactor.requestPointerLock();
      publicAPI.startPointerLockInteraction(interactor);
    }
  };

  publicAPI.onButtonUp = () => {
    publicAPI.exitPointerLock();
  };

  publicAPI.bindEvents = (container) => {
    document.addEventListener(
      'pointerlockchange',
      publicAPI.handlePointerLockChange
    );
  };

  //--------------------------------------------------------------------------

  publicAPI.startPointerLockInteraction = (interactor) => {
    // TODO: at some point, this should perhaps be done in
    // RenderWindowInteractor instead of here.
    // We need to hook into mousemove directly for two reasons:
    // 1. We need to keep receiving mouse move events after the mouse button
    //    is released. This is currently not possible with
    //    vtkInteractorStyleManipulator.
    // 2. Since the mouse is stationary in pointer lock mode, we need the
    //    event.movementX and event.movementY info, which are not currently
    //    passed via interactor.onMouseMove.
    document.addEventListener('mousemove', publicAPI.onPointerLockMove);

    let subscription = null;
    const endInteraction = () => {
      document.removeEventListener('mousemove', publicAPI.onPointerLockMove);
      subscription?.unsubscribe();
    };
    subscription = interactor?.onEndPointerLock(endInteraction);
  };

  publicAPI.onPointerLockMove = (e) => {
    model.previousPosition.x += e.movementX;
    model.previousPosition.y += e.movementY;

    publicAPI.onMouseMove(null, null, model.previousPosition);
  };

  publicAPI.exitPointerLock = () => document.exitPointerLock();

  publicAPI.isPointerLocked = () => !!document.pointerLockElement;

  publicAPI.handlePointerLockChange = () => {
    if (publicAPI.isPointerLocked()) {
      publicAPI.startPointerLockEvent();
    } else {
      publicAPI.endPointerLockEvent();
    }
  };

  //-------------------------------------------------------------------------
  publicAPI.onMouseMove = (interactor, renderer, position) => {
    if (!model.verticalListener && !model.horizontalListener) {
      return;
    }
    if (!position) {
      return;
    }

    if (model.horizontalListener) {
      const dxNorm =
        (position.x - model.previousPosition.x) / model.containerSize[0];
      const dx = scaleDeltaToRange(model.horizontalListener, dxNorm);
      processDelta(model.horizontalListener, dx);
    }
    if (model.verticalListener) {
      const dyNorm =
        (position.y - model.previousPosition.y) / model.containerSize[1];
      const dy = scaleDeltaToRange(model.verticalListener, dyNorm);
      processDelta(model.verticalListener, dy);
    }

    model.previousPosition = position;
  };

  //-------------------------------------------------------------------------
  publicAPI.onScroll = (interactor, renderer, delta) => {
    if (!model.scrollListener || !delta) {
      return;
    }
    processDelta(model.scrollListener, delta * model.scrollListener.step);
  };
  publicAPI.onStartScroll = publicAPI.onScroll;
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  horizontalListener: null,
  verticalListener: null,
  scrollListener: null,
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Inheritance
  macro.obj(publicAPI, model);
  vtkCompositeMouseManipulator.extend(publicAPI, model, initialValues);

  // Object specific methods
  vtkMouseRangeManipulator(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(
  extend,
  'vtkMouseRangeManipulator'
);

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<|endoftext|>


<commit_before>'use strict';

/**
This object contains a few constants and helper functions related to error
message handling.
*/
treeherder.factory('ThModelErrors', [function() {
    // Generic error message when we encounter 401 status codes from the
    // server.
    var AUTH_ERROR_MSG = 'Please login to Treeherder using Persona to ' +
                         'complete this action';

    return {
        /**
        Helper method for constructing an error message from the server side.

        @param {Error} e error object from the server http response.
        @param {String} default error message to use by default one cannot be
                                found in the error object.
        */
        format: function(e, message) {
            // If there is nothing in the server message return default...
            if (!e || !e.data) {
                return message;
            }

            switch (e.status) {
                case 401:
                case 403:
                    // If we failed to authenticate for some reason return a nicer
                    // error message.
                    return AUTH_ERROR_MSG;
                default:
                    return message + ':' + e.data.detail;
            }
        }
    };
}]);

<commit_msg>Bug 1290082 - Make ThModelErrors use HTTP status code if no API message<commit_after>'use strict';

/**
This object contains a few constants and helper functions related to error
message handling.
*/
treeherder.factory('ThModelErrors', [function() {
    // Generic error message when we encounter 401 status codes from the
    // server.
    var AUTH_ERROR_MSG = 'Please login to Treeherder using Persona to ' +
                         'complete this action';

    return {
        /**
        Helper method for constructing an error message from the server side.

        @param {Error} e error object from the server http response.
        @param {String} default error message to use by default one cannot be
                                found in the error object.
        */
        format: function(e, message) {
            // If we failed to authenticate for some reason return a nicer error message.
            if (e.status === 401 || e.status === 403) {
                return AUTH_ERROR_MSG;
            }

            // If there is nothing in the server message use the HTTP response status.
            var errorMessage = e.data.detail || e.status + ' ' + e.statusText;
            return message + ': ' + errorMessage;
        }
    };
}]);

<|endoftext|>


<commit_before>/*
* jQuery Searchable - v0.1.1
* Search rows in a table.
* http://kylebjohnson.me
*
* Made by Kyle B. Johnson
* Under MIT License
*/
(function( $ ) {
  $.fn.searchable = function(options) {

    var settings = $.extend({}, {
      search_class: '',
      search_placeholder: "search",
    }, options);

    return this.each(function() {

      var search_id = this.id + '_search';

      jQuery('<input/>', {
        id: search_id,
        class: settings.search_class,
        placeholder: settings.placeholder,
      }).insertBefore( $(this) );

      $( '#' + search_id ).keypress(function() {
        var search = $( this ).val();
        $('tbody tr').show();
        if(search) {
          $("tbody tr:not(:contains('" + search + "'))").hide();
        }
      });

    });

  };
}( jQuery ));
<commit_msg>make jquery :contains case-insensative for table search plugin<commit_after>/*
* jQuery Searchable - v0.1.1
* Search rows in a table.
* http://kylebjohnson.me
*
* Made by Kyle B. Johnson
* Under MIT License
*/
(function( $ ) {
  $.fn.searchable = function(options) {

    var settings = $.extend({}, {
      search_class: '',
      search_placeholder: "search",
    }, options);

    //Make jQuery :contains Case-Insensitive
    //http://css-tricks.com/snippets/jquery/make-jquery-contains-case-insensitive/
  $.expr[":"].contains = $.expr.createPseudo(function(arg) {
    return function( elem ) {
      return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
  });

    return this.each(function() {

      var search_id = this.id + '_search';

      jQuery('<input/>', {
        id: search_id,
        class: settings.search_class,
        placeholder: settings.placeholder,
      }).insertBefore( $(this) );

      $( '#' + search_id ).keypress(function() {
        var search = $( this ).val();
        $('tbody tr').show();
        if(search) {
          $("tbody tr:not(:contains('" + search + "'))").hide();
        }
      });

    });

  };
}( jQuery ));<|endoftext|>


<commit_before>const joi = require('joi')

module.exports = joi.object().keys({
  controllers: joi.object().required(),
  models: joi.object().required(),
  policies: joi.object().required(),
  services: joi.object().required()
})

<commit_msg>Add optional config to api, to make hmvc easier.<commit_after>const joi = require('joi')

module.exports = joi.object().keys({
  controllers: joi.object().required(),
  models: joi.object().required(),
  policies: joi.object().required(),
  services: joi.object().required(),
  config: joi.object().optional()
})
<|endoftext|>