<commit_before>/**
    PublicUserJobTitle model, relationship between an user and a
    job title and the main data attached to that relation for
    public access (internal fields avoided) and additional
    useful job title info (shortcut to job title names for convenience).

    The model has optional properties that link
    to other model information related to a specific jobTitle
    for convenience when querying a wider set of information
    and keep it organized under this model instances.
**/
'use strict';

var ko = require('knockout');
var numeral = require('numeral');
var Model = require('./Model'),
    PublicUserRating = require('./PublicUserRating'),
    PublicUserVerificationsSummary = require('./PublicUserVerificationsSummary'),
    Address = require('./Address'),
    WorkPhoto = require('./WorkPhoto'),
    PublicUserJobTitleServiceAttributes = require('./PublicUserJobTitleServiceAttributes'),
    ServiceProfessionalService = require('./ServiceProfessionalService'),
    UserVerification = require('./UserVerification'),
    UserLicenseCertification = require('./UserLicenseCertification');

function PublicUserJobTitle(values) {

    Model(this);

    this.model.defProperties({
        userID: 0,
        jobTitleID: 0,
        intro: null,
        cancellationPolicyID: 0,
        instantBooking: false,
        jobTitleSingularName: '',
        jobTitlePluralName: '',

        rating: { Model: PublicUserRating },
        verificationsSummary: { Model: PublicUserVerificationsSummary },
        serviceAddresses: {
            Model: Address,
            isArray: true
        },
        services: {
            Model: ServiceProfessionalService,
            isArray: true
        },
        serviceAttributes: {
            Model: PublicUserJobTitleServiceAttributes
        },
        workPhotos: {
            Model: WorkPhoto,
            isArray: true
        },
        verifications: {
            Model: UserVerification,
            isArray: true
        },
        licensesCertifications: {
            Model: UserLicenseCertification,
            isArray: true
        }
    }, values);

    this.model.defID(['userID', 'jobTitleID']);

    var findMinValue = function(services) {
        var s = services,
            maxValue = { price: Number.MAX_VALUE };

        if (s.length === 0) return null;

        var minValue = s.reduce(function(last, serv) {
            return ((serv.priceRate() !== null) && serv.priceRate() < last.price) ? {
                price: serv.priceRate(),
                unit: serv.priceRateUnit()
            } : ((serv.price() !== null) && serv.price() < last.price) ? {
                price: serv.price(),
                unit: null
            } : last;
        }, maxValue);

        return minValue === maxValue ? null : minValue;
    };

    this.minServiceValue = ko.pureComputed(function() {
        var price = findMinValue(this.services());
        if (!price) {
            return '';
        }
        else if (price.unit) {
            return numeral(price.price).format('$0') + '/' + price.unit;
        }
        else {
            return numeral(price.price).format('$0.00');
        }
    }, this);

    this.clientSpecificServices = function() {
        return this.services().filter(function(service) {
            return service.isClientSpecific();
        });
    };

    this.publicServices = function() {
        return this.services().filter(function(service) {
            return !service.isClientSpecific();
        });
    };

    /**
     * @returns true if there are any service attributes with this job title
     */
    this.hasServiceAttributes = function() {
        return !!(this.serviceAttributes() && this.serviceAttributes().hasAttributes());
    };

    /**
     * @returns true if there is any intro text
     */
    this.hasIntro = function() {
        return !!this.intro();
    };
}

module.exports = PublicUserJobTitle;
<commit_msg>PublicUserJobTitle includes isActive field from API #437<commit_after>/**
    PublicUserJobTitle model, relationship between an user and a
    job title and the main data attached to that relation for
    public access (internal fields avoided) and additional
    useful job title info (shortcut to job title names for convenience).

    The model has optional properties that link
    to other model information related to a specific jobTitle
    for convenience when querying a wider set of information
    and keep it organized under this model instances.
**/
'use strict';

var ko = require('knockout');
var numeral = require('numeral');
var Model = require('./Model'),
    PublicUserRating = require('./PublicUserRating'),
    PublicUserVerificationsSummary = require('./PublicUserVerificationsSummary'),
    Address = require('./Address'),
    WorkPhoto = require('./WorkPhoto'),
    PublicUserJobTitleServiceAttributes = require('./PublicUserJobTitleServiceAttributes'),
    ServiceProfessionalService = require('./ServiceProfessionalService'),
    UserVerification = require('./UserVerification'),
    UserLicenseCertification = require('./UserLicenseCertification');

function PublicUserJobTitle(values) {

    Model(this);

    this.model.defProperties({
        userID: 0,
        jobTitleID: 0,
        intro: null,
        cancellationPolicyID: 0,
        instantBooking: false,
        isActive: false,
        jobTitleSingularName: '',
        jobTitlePluralName: '',

        rating: { Model: PublicUserRating },
        verificationsSummary: { Model: PublicUserVerificationsSummary },
        serviceAddresses: {
            Model: Address,
            isArray: true
        },
        services: {
            Model: ServiceProfessionalService,
            isArray: true
        },
        serviceAttributes: {
            Model: PublicUserJobTitleServiceAttributes
        },
        workPhotos: {
            Model: WorkPhoto,
            isArray: true
        },
        verifications: {
            Model: UserVerification,
            isArray: true
        },
        licensesCertifications: {
            Model: UserLicenseCertification,
            isArray: true
        }
    }, values);

    this.model.defID(['userID', 'jobTitleID']);

    var findMinValue = function(services) {
        var s = services,
            maxValue = { price: Number.MAX_VALUE };

        if (s.length === 0) return null;

        var minValue = s.reduce(function(last, serv) {
            return ((serv.priceRate() !== null) && serv.priceRate() < last.price) ? {
                price: serv.priceRate(),
                unit: serv.priceRateUnit()
            } : ((serv.price() !== null) && serv.price() < last.price) ? {
                price: serv.price(),
                unit: null
            } : last;
        }, maxValue);

        return minValue === maxValue ? null : minValue;
    };

    this.minServiceValue = ko.pureComputed(function() {
        var price = findMinValue(this.services());
        if (!price) {
            return '';
        }
        else if (price.unit) {
            return numeral(price.price).format('$0') + '/' + price.unit;
        }
        else {
            return numeral(price.price).format('$0.00');
        }
    }, this);

    this.clientSpecificServices = function() {
        return this.services().filter(function(service) {
            return service.isClientSpecific();
        });
    };

    this.publicServices = function() {
        return this.services().filter(function(service) {
            return !service.isClientSpecific();
        });
    };

    /**
     * @returns true if there are any service attributes with this job title
     */
    this.hasServiceAttributes = function() {
        return !!(this.serviceAttributes() && this.serviceAttributes().hasAttributes());
    };

    /**
     * @returns true if there is any intro text
     */
    this.hasIntro = function() {
        return !!this.intro();
    };
}

module.exports = PublicUserJobTitle;
<|endoftext|>


<commit_before>/**
* @class
*/
OpenLayers.Marker = Class.create();
OpenLayers.Marker.prototype = {

    /** @type OpenLayers.Icon */
    icon: null,

    /** location of object
    * @type OpenLayers.LonLat */
    lonlat: null,

    /** @type OpenLayers.Events*/
    events: null,

    /** @type OpenLayers.Map */
    map: null,

    /**
    * @constructor
    *
    * @param {OpenLayers.Icon} icon
    * @param {OpenLayers.LonLat lonlat
    */
    initialize: function(lonlat, icon) {
        this.lonlat = lonlat;
        this.icon = (icon) ? icon : OpenLayers.Marker.defaultIcon();

        this.events = new OpenLayers.Events(this, this.icon.imageDiv, null);
    },

    destroy: function() {
        this.map = null;

        // code to remove HTMLImage will go here
        //  I realize now that it was not a good
        //  idea to give OpenLayers.Icon the
        //  'imageDiv' property.. that should be
        //  here. This is on my hot-list to fix
    },

    /**
    * @param {OpenLayers.Pixel} px
    *
    * @return A new DOM Image with this markers icon set at the
    *         location passed-in
    * @type DOMElement
    */
    draw: function(px) {
        return this.icon.draw(px);
    },

    /**
    * @param {OpenLayers.Pixel} px
    */
    moveTo: function (px) {
        if ((px != null) && (this.icon != null)) {
            this.icon.moveTo(px);
        }
    },

    /**
     * @param {float} inflate
     */
    inflate: function(inflate) {
        if (this.icon) {
            var newSize = new OpenLayers.Size(this.icon.size.w * inflate,
                                              this.icon.size.h * inflate);
            this.icon.setSize(newSize);
        }
    },

    /** @final @type String */
    CLASS_NAME: "OpenLayers.Marker"
};

/**
 * @returns A default OpenLayers.Icon to use for a marker
 * @type OpenLayers.Icon
 */
OpenLayers.Marker.defaultIcon = function() {
    var url = OpenLayers.Util.getImagesLocation() + "marker.png";
    var size = new OpenLayers.Size(21, 25);
    var calculateOffset = function(size) {
                    return new OpenLayers.Pixel(-(size.w/2), -size.h);
                 };

    return new OpenLayers.Icon(url, size, null, calculateOffset);
};

<commit_msg>destroy icon on destroy<commit_after>/**
* @class
*/
OpenLayers.Marker = Class.create();
OpenLayers.Marker.prototype = {

    /** @type OpenLayers.Icon */
    icon: null,

    /** location of object
    * @type OpenLayers.LonLat */
    lonlat: null,

    /** @type OpenLayers.Events*/
    events: null,

    /** @type OpenLayers.Map */
    map: null,

    /**
    * @constructor
    *
    * @param {OpenLayers.Icon} icon
    * @param {OpenLayers.LonLat lonlat
    */
    initialize: function(lonlat, icon) {
        this.lonlat = lonlat;
        this.icon = (icon) ? icon : OpenLayers.Marker.defaultIcon();

        this.events = new OpenLayers.Events(this, this.icon.imageDiv, null);
    },

    destroy: function() {
        this.map = null;

        if (this.icon != null) {
            this.icon.destroy();
            this.icon = null;
        }
    },

    /**
    * @param {OpenLayers.Pixel} px
    *
    * @return A new DOM Image with this markers icon set at the
    *         location passed-in
    * @type DOMElement
    */
    draw: function(px) {
        return this.icon.draw(px);
    },

    /**
    * @param {OpenLayers.Pixel} px
    */
    moveTo: function (px) {
        if ((px != null) && (this.icon != null)) {
            this.icon.moveTo(px);
        }
    },

    /**
     * @param {float} inflate
     */
    inflate: function(inflate) {
        if (this.icon) {
            var newSize = new OpenLayers.Size(this.icon.size.w * inflate,
                                              this.icon.size.h * inflate);
            this.icon.setSize(newSize);
        }
    },

    /** @final @type String */
    CLASS_NAME: "OpenLayers.Marker"
};

/**
 * @returns A default OpenLayers.Icon to use for a marker
 * @type OpenLayers.Icon
 */
OpenLayers.Marker.defaultIcon = function() {
    var url = OpenLayers.Util.getImagesLocation() + "marker.png";
    var size = new OpenLayers.Size(21, 25);
    var calculateOffset = function(size) {
                    return new OpenLayers.Pixel(-(size.w/2), -size.h);
                 };

    return new OpenLayers.Icon(url, size, null, calculateOffset);
};

<|endoftext|>


<commit_before>/**
 * @param {Object} $ - Global jQuery object
 */
(function ($) {
    'use strict';

    /**
     * BUIC listingpart widget.
     *
     * tbody inside a listing widget.
     *
     * @license http://opensource.org/licenses/mit-license.php MIT License
     * @author rarila
     *
     * @class buicListingPart
     * @memberOf jQuery.widget.bolt
     */
    $.widget('bolt.buicListingPart', /** @lends jQuery.widget.bolt.buicListingPart.prototype */ {
        /**
         * The constructor of the listingpart widget.
         *
         * @private
         */
        _create: function () {
            var self = this;

            // Private properties
            this.listing = this.element.closest(':bolt-buicListing');
            this.toolbar = this.element.find('tr.selectiontoolbar');
            this.toolbarCount = this.toolbar.find('div.count');
            this.menu = this.element.find('tr.header th.menu');
            this.menuOnlyOnSelection = this.menu.find('li:not(.select-all)');
            this.menuSelectionCount = this.menu.find('li.dropdown-header');
            this.menuSelectionCountTemplate = this.menuSelectionCount.text();
            this.selectedIds = [];

            // Select all/none rows from menu.
            this.menu.find('li.select-all, li.select-none').on('click', function () {
                var set = $(this).hasClass('select-all');

                self.element.find('td input:checkbox[name="checkRow"]').each(function () {
                    this.checked = set;
                    self._update(this);
                });
            });

            // On check/unchecking a row selector.
            this.element.find('td input:checkbox[name="checkRow"]').on('click', function () {
                self._update(this);
            });

            // Record toolbar actions.
            this.toolbar.find('button[data-stb-cmd^="record:"]').on('click', function () {
                self._modifyRecords(
                    $(this).data('stb-cmd'),
                    self.selectedIds,
                    $(this).html()
                );
            });

            // Record row edit button actions.
            this.element.find('a[data-listing-cmd^="record:"]').on('click', function () {
                self._modifyRecords(
                    $(this).data('listing-cmd'),
                    [$(this).parents('tr').attr('id').substr(5)],
                    $(this).html()
                );
            });
        },

        /**
         * Tells the listing to modify selected records.
         *
         * @private
         * @param {string} action - Command to execute.
         * @param {array} ids - Checkbox clicked.
         * @param {string} buttonText - Button text to be displayed on ok button.
         */
        _modifyRecords: function (action, ids, buttonText) {
            if (ids.length > 0) {
                this.listing.buicListing('modifyRecords', action.replace(/^record:/, ''), ids, buttonText);
            }
        },

        /**
         * Update row, toolbar and menu on checkbox status change.
         *
         * @private
         * @param {object} checkbox - Checkbox clicked.
         */
        _update: function (checkbox) {
            var row = $(checkbox).closest('tr'),
                id = row.attr('id').substr(5),
                count;

            if (checkbox.checked) {
                this.selectedIds.push(id);
                row.addClass('row-selected');
            } else {
                this.selectedIds.splice(this.selectedIds.indexOf(id), 1);
                row.removeClass('row-selected');
            }
            count = this.selectedIds.length;

            // Show/hide toolbar & menu entries.
            if (count) {
                this.toolbar.removeClass('hidden');
                this.menuOnlyOnSelection.removeClass('hidden');
            } else {
                this.toolbar.addClass('hidden');
                this.menuOnlyOnSelection.addClass('hidden');
            }
            // Update selection count display.
            this.toolbarCount.text(count);
            // Update menuselection count display.
            this.menuSelectionCount.text(this.menuSelectionCountTemplate.replace('(#)', '(' + count + ')'));
        }
    });
})(jQuery);
<commit_msg>Only adding record to the list, if it wasn't already selected before.<commit_after>/**
 * @param {Object} $ - Global jQuery object
 */
(function ($) {
    'use strict';

    /**
     * BUIC listingpart widget.
     *
     * tbody inside a listing widget.
     *
     * @license http://opensource.org/licenses/mit-license.php MIT License
     * @author rarila
     *
     * @class buicListingPart
     * @memberOf jQuery.widget.bolt
     */
    $.widget('bolt.buicListingPart', /** @lends jQuery.widget.bolt.buicListingPart.prototype */ {
        /**
         * The constructor of the listingpart widget.
         *
         * @private
         */
        _create: function () {
            var self = this;

            // Private properties
            this.listing = this.element.closest(':bolt-buicListing');
            this.toolbar = this.element.find('tr.selectiontoolbar');
            this.toolbarCount = this.toolbar.find('div.count');
            this.menu = this.element.find('tr.header th.menu');
            this.menuOnlyOnSelection = this.menu.find('li:not(.select-all)');
            this.menuSelectionCount = this.menu.find('li.dropdown-header');
            this.menuSelectionCountTemplate = this.menuSelectionCount.text();
            this.selectedIds = [];

            // Select all/none rows from menu.
            this.menu.find('li.select-all, li.select-none').on('click', function () {
                var set = $(this).hasClass('select-all');

                self.element.find('td input:checkbox[name="checkRow"]').each(function () {
                    this.checked = set;
                    self._update(this);
                });
            });

            // On check/unchecking a row selector.
            this.element.find('td input:checkbox[name="checkRow"]').on('click', function () {
                self._update(this);
            });

            // Record toolbar actions.
            this.toolbar.find('button[data-stb-cmd^="record:"]').on('click', function () {
                self._modifyRecords(
                    $(this).data('stb-cmd'),
                    self.selectedIds,
                    $(this).html()
                );
            });

            // Record row edit button actions.
            this.element.find('a[data-listing-cmd^="record:"]').on('click', function () {
                self._modifyRecords(
                    $(this).data('listing-cmd'),
                    [$(this).parents('tr').attr('id').substr(5)],
                    $(this).html()
                );
            });
        },

        /**
         * Tells the listing to modify selected records.
         *
         * @private
         * @param {string} action - Command to execute.
         * @param {array} ids - Checkbox clicked.
         * @param {string} buttonText - Button text to be displayed on ok button.
         */
        _modifyRecords: function (action, ids, buttonText) {
            if (ids.length > 0) {
                this.listing.buicListing('modifyRecords', action.replace(/^record:/, ''), ids, buttonText);
            }
        },

        /**
         * Update row, toolbar and menu on checkbox status change.
         *
         * @private
         * @param {object} checkbox - Checkbox clicked.
         */
        _update: function (checkbox) {
            var row = $(checkbox).closest('tr'),
                id = row.attr('id').substr(5),
                count;

            if (checkbox.checked) {
                // Only add the item, if it's not already in the list.
                if (this.selectedIds.indexOf(id) === -1) {
                    this.selectedIds.push(id);
                }
                row.addClass('row-selected');
            } else {
                this.selectedIds.splice(this.selectedIds.indexOf(id), 1);
                row.removeClass('row-selected');
            }
            count = this.selectedIds.length;

            // Show/hide toolbar & menu entries.
            if (count) {
                this.toolbar.removeClass('hidden');
                this.menuOnlyOnSelection.removeClass('hidden');
            } else {
                this.toolbar.addClass('hidden');
                this.menuOnlyOnSelection.addClass('hidden');
            }
            // Update selection count display.
            this.toolbarCount.text(count);
            // Update menuselection count display.
            this.menuSelectionCount.text(this.menuSelectionCountTemplate.replace('(#)', '(' + count + ')'));
        }
    });
})(jQuery);
<|endoftext|>


<commit_before>/*
Licensed under The MIT License
==============================

Copyright (c) 2009 - 2010 Fireworks Technology Projects Inc.
[www.fireworksproject.com](http://www.fireworksproject.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */

/*jslint
onevar: true,
undef: true,
nomen: true,
eqeqeq: true,
plusplus: true,
bitwise: true,
strict: true,
immed: true */

/*members get_item, id, import, parse, require, set_item, stringify,
    utils
*/

/*global
Components: false,
JSON: false
*/

"use strict";

// For Mozilla JavaScript modules system.
var EXPORTED_SYMBOLS = ["exports"];

// If we are in the Mozilla module system we need to add some boilerplate to be
// CommonJS complient. This is obviously an ugly hack to allow integration with
// legacy code that uses the Mozilla module system.
if (Components) {
  var require = Components.utils.import(
        "resource://crownconstruction/modules/boot.js", null).require;
  var exports = {};
  var module = {id: "cache"};
}

var CACHE = {};
exports.set_item = function set_item(key, value) {
  CACHE[key] = value;
  return value;
};

exports.get_item = function get_item(key) {
  return JSON.parse(JSON.stringify(CACHE[key]));
};

<commit_msg>Improvement for cache module.<commit_after>/*
Licensed under The MIT License
==============================

Copyright (c) 2009 - 2010 Fireworks Technology Projects Inc.
[www.fireworksproject.com](http://www.fireworksproject.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */

/*jslint
onevar: true,
undef: true,
nomen: true,
eqeqeq: true,
plusplus: true,
bitwise: true,
strict: true,
immed: true */

/*members get_item, id, import, parse, require, set_item, stringify,
    utils
*/

/*global
Components: false,
JSON: false
*/

"use strict";

// For Mozilla JavaScript modules system.
var EXPORTED_SYMBOLS = ["exports"];

// If we are in the Mozilla module system we need to add some boilerplate to be
// CommonJS complient. This is obviously an ugly hack to allow integration with
// legacy code that uses the Mozilla module system.
if (Components) {
  var require = Components.utils.import(
        "resource://crownconstruction/modules/boot.js", null).require;
  var exports = {};
  var module = {id: "cache"};
}

var CACHE = {};
exports.set_item = function set_item(key, value) {
  CACHE[key] = value;
  return value;
};

exports.get_item = function get_item(key) {
  return ((!CACHE[key] || typeof CACHE[key] !== "object") ?
               CACHE[key] :
               JSON.parse(JSON.stringify(CACHE[key])));
};

<|endoftext|>


<commit_before>function hasChanged(source, target) {
  const sourceKeys = Object.keys(source);
  const targetKeys = Object.keys(target);

  if (sourceKeys.length !== targetKeys.length) {
    return true;
  } else {
    return sourceKeys.some((sourceKey) => {
      return source[sourceKey] !== target[sourceKey];
    })
  }
}

export default hasChanged;
<commit_msg>Allow hasChanged to handle null and undefined values<commit_after>function hasChanged(source, target) {
  if (!source) {
    return !!target;
  } else if (!target) {
    return !!source;
  }

  const sourceKeys = Object.keys(source);
  const targetKeys = Object.keys(target);

  if (sourceKeys.length !== targetKeys.length) {
    return true;
  } else {
    return sourceKeys.some((sourceKey) => {
      return source[sourceKey] !== target[sourceKey];
    })
  }
}

export default hasChanged;
<|endoftext|>


<commit_before>/**
 * New Relic agent configuration.
 *
 * See lib/config.defaults.js in the agent distribution for a more complete
 * description of configuration variables and their potential values.
 */
exports.config = {
  /**
   * Default to disabled to help non-newrelic users.
   */
  agent_enabled: false,
  /**
   * Array of application names.
   */
  app_name: ['A WebMention Endpoint'],
  logging: {
    /**
     * Level at which to log. 'trace' is most useful to New Relic when diagnosing
     * issues with the agent, 'info' and higher will impose the least overhead on
     * production applications.
     */
    level: 'info'
  },
  rules: {
    /**
     * Ensures that the EventSource endpoint doesn't dominate the response time metrics
     */
    ignore: [
      '^/api/mentions/live'
    ]
  },
  capture_params: true
};
<commit_msg>Upgrade a NewRelic setting<commit_after>/**
 * New Relic agent configuration.
 *
 * See lib/config.defaults.js in the agent distribution for a more complete
 * description of configuration variables and their potential values.
 */
exports.config = {
  /**
   * Default to disabled to help non-newrelic users.
   */
  agent_enabled: false,
  /**
   * Array of application names.
   */
  app_name: ['A WebMention Endpoint'],
  logging: {
    /**
     * Level at which to log. 'trace' is most useful to New Relic when diagnosing
     * issues with the agent, 'info' and higher will impose the least overhead on
     * production applications.
     */
    level: 'info'
  },
  rules: {
    /**
     * Ensures that the EventSource endpoint doesn't dominate the response time metrics
     */
    ignore: [
      '^/api/mentions/live'
    ]
  },
  attributes: {
    enabled: true
  }
};
<|endoftext|>


<commit_before>/* @flow */
import { Platform } from 'react-native';
import { BORDER_COLOR, BRAND_COLOR, CONTROL_SIZE, NAVBAR_SIZE, SPACING } from './';
import utilityStyles from './utilityStyles';

type Props = {
  color: string,
  backgroundColor: string,
  borderColor: string,
  cardColor: string,
  dividerColor: string,
};

export default ({ color, backgroundColor, borderColor, cardColor, dividerColor }: Props) => ({
  ...utilityStyles,
  text: {
    fontSize: 16,
  },
  color: {
    color,
  },
  backgroundColor: {
    backgroundColor,
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  input: {
    color,
    ...Platform.select({
      ios: {
        borderWidth: 1,
        borderColor: BORDER_COLOR,
        borderRadius: 2,
        padding: 8,
      },
    }),
  },
  realmInput: {
    color,
    padding: 0,
    fontSize: 20,
  },
  realmPlaceholder: {
    opacity: 0.75,
  },
  realmInputEmpty: {
    width: 1,
  },
  topicInput: {
    borderWidth: 0,
    borderRadius: 5,
    backgroundColor,
    marginTop: 5,
    padding: 5,
  },
  composeTextInput: {
    borderWidth: 0,
    borderRadius: 5,
    backgroundColor,
    color,
    fontSize: 15,
    marginTop: 5,
    marginBottom: 5,
    padding: 5,
  },
  background: {
    backgroundColor,
  },
  label: {
    color,
    fontSize: 15,
  },
  icon: {
    color,
    width: 24,
    height: 24,
    margin: 8,
    fontSize: 24,
    textAlign: 'center',
  },
  settingsIcon: {
    marginLeft: 8,
    marginRight: 16,
  },
  item: {
    flex: 1,
    flexBasis: CONTROL_SIZE,
    flexDirection: 'row',
    alignItems: 'center',
  },
  screen: {
    flex: 1,
    flexDirection: 'column',
    // alignItems: 'stretch',
    backgroundColor,
  },
  flexed: {
    flex: 1,
  },
  flexedLeftAlign: {
    flex: 1,
    justifyContent: 'flex-start',
  },
  messageList: {
    flex: 1,
  },
  webview: {
    borderWidth: 0,
    backgroundColor,
  },
  rightItem: {
    marginLeft: 'auto',
  },
  screenWrapper: {
    flex: 1,
    padding: 8,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'stretch',
  },
  link: {
    marginTop: 10,
    fontSize: 15,
    color: BRAND_COLOR,
    textAlign: 'right',
  },
  optionRow: {
    flexDirection: 'row',
    justifyContent: 'flex-start',
    alignItems: 'center',
    padding: SPACING,
    backgroundColor,
  },
  divider: {
    borderBottomWidth: 1,
    borderBottomColor: dividerColor,
  },
  navigationCard: {
    backgroundColor,
    shadowColor: 'transparent',
  },
  container: {
    flex: 1,
    padding: 16,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'stretch',
  },
  center: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  heading2: {
    fontSize: 20,
  },
  field: {
    flex: 1,
    flexDirection: 'row',
    height: CONTROL_SIZE,
    marginTop: 5,
    marginBottom: 5,
  },
  disabled: {
    backgroundColor: '#ddd',
    color: '#333',
  },
  marginBottom: {
    marginBottom: 10,
  },
  navBar: {
    backgroundColor,
    borderColor,
    flexDirection: 'row',
    height: NAVBAR_SIZE,
    alignItems: 'center',
    justifyContent: 'space-between',
    borderBottomWidth: 1,
  },
  navWrapper: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'flex-start',
  },
  navTitle: {
    color: BRAND_COLOR,
    textAlign: 'left',
    fontSize: 20,
    paddingLeft: 8,
  },
  navSubtitle: {
    fontSize: 13,
    opacity: 0.8,
  },
  composeBox: {
    flexDirection: 'row',
    backgroundColor: 'rgba(127, 127, 127, 0.1)',
    borderTopColor: borderColor,
  },
  subheader: {
    flex: 1,
    flexBasis: 20,
    paddingBottom: 4,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  username: {
    flex: 1,
    fontWeight: 'bold',
    fontSize: 16,
    lineHeight: 16,
  },
  cardView: {
    backgroundColor: cardColor,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    elevation: 2,
  },
  lineSeparator: {
    height: 1,
    backgroundColor: cardColor,
    margin: 4,
  },
  floatingView: {
    position: 'absolute',
    width: '100%',
  },
});
<commit_msg>ui: Add listItem common style<commit_after>/* @flow */
import { Platform } from 'react-native';
import { BORDER_COLOR, BRAND_COLOR, CONTROL_SIZE, NAVBAR_SIZE, SPACING, HALF_SPACING } from './';
import utilityStyles from './utilityStyles';

type Props = {
  color: string,
  backgroundColor: string,
  borderColor: string,
  cardColor: string,
  dividerColor: string,
};

export default ({ color, backgroundColor, borderColor, cardColor, dividerColor }: Props) => ({
  ...utilityStyles,
  text: {
    fontSize: 16,
  },
  color: {
    color,
  },
  backgroundColor: {
    backgroundColor,
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  input: {
    color,
    ...Platform.select({
      ios: {
        borderWidth: 1,
        borderColor: BORDER_COLOR,
        borderRadius: 2,
        padding: 8,
      },
    }),
  },
  realmInput: {
    color,
    padding: 0,
    fontSize: 20,
  },
  realmPlaceholder: {
    opacity: 0.75,
  },
  realmInputEmpty: {
    width: 1,
  },
  topicInput: {
    borderWidth: 0,
    borderRadius: 5,
    backgroundColor,
    marginTop: 5,
    padding: 5,
  },
  composeTextInput: {
    borderWidth: 0,
    borderRadius: 5,
    backgroundColor,
    color,
    fontSize: 15,
    marginTop: 5,
    marginBottom: 5,
    padding: 5,
  },
  background: {
    backgroundColor,
  },
  label: {
    color,
    fontSize: 15,
  },
  icon: {
    color,
    width: 24,
    height: 24,
    margin: 8,
    fontSize: 24,
    textAlign: 'center',
  },
  settingsIcon: {
    marginLeft: 8,
    marginRight: 16,
  },
  item: {
    flex: 1,
    flexBasis: CONTROL_SIZE,
    flexDirection: 'row',
    alignItems: 'center',
  },
  listItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingTop: HALF_SPACING,
    paddingBottom: HALF_SPACING,
    paddingLeft: SPACING,
    paddingRight: SPACING,
  },
  screen: {
    flex: 1,
    flexDirection: 'column',
    // alignItems: 'stretch',
    backgroundColor,
  },
  flexed: {
    flex: 1,
  },
  flexedLeftAlign: {
    flex: 1,
    justifyContent: 'flex-start',
  },
  messageList: {
    flex: 1,
  },
  webview: {
    borderWidth: 0,
    backgroundColor,
  },
  rightItem: {
    marginLeft: 'auto',
  },
  screenWrapper: {
    flex: 1,
    padding: 8,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'stretch',
  },
  link: {
    marginTop: 10,
    fontSize: 15,
    color: BRAND_COLOR,
    textAlign: 'right',
  },
  optionRow: {
    flexDirection: 'row',
    justifyContent: 'flex-start',
    alignItems: 'center',
    padding: SPACING,
    backgroundColor,
  },
  divider: {
    borderBottomWidth: 1,
    borderBottomColor: dividerColor,
  },
  navigationCard: {
    backgroundColor,
    shadowColor: 'transparent',
  },
  container: {
    flex: 1,
    padding: 16,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'stretch',
  },
  center: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  heading2: {
    fontSize: 20,
  },
  field: {
    flex: 1,
    flexDirection: 'row',
    height: CONTROL_SIZE,
    marginTop: 5,
    marginBottom: 5,
  },
  disabled: {
    backgroundColor: '#ddd',
    color: '#333',
  },
  marginBottom: {
    marginBottom: 10,
  },
  navBar: {
    backgroundColor,
    borderColor,
    flexDirection: 'row',
    height: NAVBAR_SIZE,
    alignItems: 'center',
    justifyContent: 'space-between',
    borderBottomWidth: 1,
  },
  navWrapper: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'flex-start',
  },
  navTitle: {
    color: BRAND_COLOR,
    textAlign: 'left',
    fontSize: 20,
    paddingLeft: 8,
  },
  navSubtitle: {
    fontSize: 13,
    opacity: 0.8,
  },
  composeBox: {
    flexDirection: 'row',
    backgroundColor: 'rgba(127, 127, 127, 0.1)',
    borderTopColor: borderColor,
  },
  subheader: {
    flex: 1,
    flexBasis: 20,
    paddingBottom: 4,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  username: {
    flex: 1,
    fontWeight: 'bold',
    fontSize: 16,
    lineHeight: 16,
  },
  cardView: {
    backgroundColor: cardColor,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    elevation: 2,
  },
  lineSeparator: {
    height: 1,
    backgroundColor: cardColor,
    margin: 4,
  },
  floatingView: {
    position: 'absolute',
    width: '100%',
  },
});
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
<commit_msg>incluir js de bootstrap<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap
//= require_tree .
<|endoftext|>


<commit_before>define(function(require, exports, module) {
    var ScrollView = require('famous/views/Scrollview');

    function InfiniteScrollView(options) {
        ScrollView.apply(this, arguments);

        if (this.options.offset)
            this.setOffset(this.options.offset);

        _monitor.call(this);
    }

    InfiniteScrollView.prototype = Object.create(ScrollView.prototype);
    InfiniteScrollView.prototype.constructor = InfiniteScrollView;

    InfiniteScrollView.DEFAULT_OPTIONS = {};

    InfiniteScrollView.prototype.setOffset = function(o) {
        this.offset = o;
    }

    InfiniteScrollView.prototype._setContentSize = function() {
        var node = this._node;
        this.contentSize = 0;
        for(var i in node._.array) {
            this.contentSize += node._.array[i].getSize()[1];
        }
    }

    InfiniteScrollView.prototype.disable = function() {
        this.infiniteScrollDisabled = true;
    }

    InfiniteScrollView.prototype.enable = function() {
        this._setContentSize();
        this.infiniteScrollDisabled = false;
    }

    function _monitor() {
        this.sync.on('start',function(data) {
            this._setContentSize();
        }.bind(this));

        this.sync.on('update',function(data) {
            if (!this.infiniteScrollDisabled && this._scroller._position + Math.abs(this._pageSpringPosition) + this.getSize()[1] >= this.contentSize - this.offset) {
                this._eventOutput.emit('infiniteScroll');
            }
        }.bind(this));
    }

    module.exports = InfiniteScrollView;
});
<commit_msg>getSize was returning null in some cases<commit_after>define(function(require, exports, module) {
    var ScrollView = require('famous/views/Scrollview');

    function InfiniteScrollView(options) {
        ScrollView.apply(this, arguments);

        if (this.options.offset)
            this.setOffset(this.options.offset);

        _monitor.call(this);
    }

    InfiniteScrollView.prototype = Object.create(ScrollView.prototype);
    InfiniteScrollView.prototype.constructor = InfiniteScrollView;

    InfiniteScrollView.DEFAULT_OPTIONS = {};

    InfiniteScrollView.prototype.setOffset = function(o) {
        this.offset = o;
    }

    InfiniteScrollView.prototype._setContentSize = function() {
        var node = this._node;
        this.contentSize = 0;
        for(var i in node._.array) {
            this.contentSize += node._.array[i].size[1];
        }
    }

    InfiniteScrollView.prototype.disable = function() {
        this.infiniteScrollDisabled = true;
    }

    InfiniteScrollView.prototype.enable = function() {
        this._setContentSize();
        this.infiniteScrollDisabled = false;
    }

    function _monitor() {
        this.sync.on('start',function(data) {
            this._setContentSize();
        }.bind(this));

        this.sync.on('update',function(data) {
            if (!this.infiniteScrollDisabled && this._scroller._position + Math.abs(this._pageSpringPosition) + this.getSize()[1] >= this.contentSize - this.offset) {
                this._eventOutput.emit('infiniteScroll');
            }
        }.bind(this));
    }

    module.exports = InfiniteScrollView;
});
<|endoftext|>


<commit_before>function renderStage(stage, ctx) {
  // All the visitors close over this class to do instance testing.
  const MovieClipClass = avm2.systemDomain.getClass("flash.display.MovieClip");
  const ContainerClass = avm2.systemDomain.getClass("flash.display.DisplayObjectContainer");
  const InteractiveClass = avm2.systemDomain.getClass("flash.display.InteractiveObject");

  function visitContainer(container, visitor, interactiveParent) {
    var children = container._children;
    visitor.childrenStart(container);
    for (var i = 0, n = children.length; i < n; i++) {
      var child = children[i];
      if (child) {
        var isContainer = ContainerClass.isInstanceOf(child) || child._isContainer;

        if (InteractiveClass.isInstanceOf(child)) {
          if (!interactiveParent || interactiveParent._mouseChildren)
            interactiveParent = child;
        }

        visitor.visit(child, isContainer, interactiveParent);

        if (isContainer)
          visitContainer(child, visitor, interactiveParent);
      }
    }
    visitor.childrenEnd(container);
  }

  function EnterFrameVisitor() {
  }
  EnterFrameVisitor.prototype = {
    childrenStart: function() {},
    childrenEnd: function() {},
    visit: function (obj) {
      if (MovieClipClass.isInstanceOf(obj)) {
        if (obj.isPlaying()) {
          var currentFrame = obj._currentFrame;

          obj.nextFrame();

          if (obj._currentFrame !== currentFrame)
            obj._scriptExecutionPending = true;
        }
        obj.dispatchEvent(new flash.events.Event("enterFrame"));
      }
    }
  };

  function ExitFrameVisitor() {
  }
  ExitFrameVisitor.prototype = {
    childrenStart: function() {},
    childrenEnd: function() {},
    visit: function (obj) {
      if (MovieClipClass.isInstanceOf(obj)) {
        obj.dispatchEvent(new flash.events.Event("exitFrame"));
      }
    }
  };

  function RenderVisitor(ctx) {
    this.depth = 0;
    this.ctx = ctx;
  }
  RenderVisitor.prototype = {
    childrenStart: function(parent) {
      if (this.depth == 0) {
        var ctx = this.ctx;
        var stage = parent;
        var frameWidth = ctx.canvas.width;
        var frameHeight = ctx.canvas.height;

        var scaleX = frameWidth / stage._stageWidth;
        var scaleY = frameHeight / stage._stageHeight;

        var scale = Math.min(scaleX, scaleY);
        var offsetX = (frameWidth - scale * stage.stageWidth) / 2;
        var offsetY = (frameHeight - scale * stage.stageHeight) / 2;

        ctx.clearRect(0, 0, frameWidth, frameHeight);
        ctx.save();
        ctx.translate(offsetX, offsetY);
        ctx.scale(scale, scale);

        ctx.canvas.currentTransform = {
          scale: scale,
          offsetX: offsetX,
          offsetY: offsetY
        };
      }
      this.depth++;

      // TODO move into separate visitor?
      if (MovieClipClass.isInstanceOf(parent) && parent._scriptExecutionPending) {
        parent._callFrame(parent.currentFrame);
        parent._scriptExecutionPending = false;
      }
    },
    childrenEnd: function(parent) {
      this.depth--;
      this.ctx.restore();
    },
    visit: function (child, isContainer, interactiveParent) {
      var hitTest = false;
      var hitTestShape = false;

      if (interactiveParent) {
        var pt = new flash.geom.Point(stage._mouseX, stage._mouseY);
        child._applyCurrentInverseTransform(pt, child._parent);

        if (child._hitArea)
          hitTest = child._hitArea._hitTest(true, pt.x, pt.y, true);

        if (!hitTest)
          hitTestShape = true;
      }

      var ctx = this.ctx;
      ctx.save();

      var m = child._currentTransform;
      ctx.transform(m.a, m.b, m.c, m.d, m.tx, m.ty);

      var cxform = child._cxform;
      if (cxform) {
        // We only support alpha channel transformation for now
        ctx.globalAlpha = (ctx.globalAlpha * cxform.alphaMultiplier + cxform.alphaOffset) / 256;
      }

      if (child._graphics) {
        var graphics = child._graphics;

        var scale = graphics._scale;
        if (scale !== 1)
          ctx.scale(scale, scale);

        var subpaths = graphics._subpaths;
        for (var j = 0, o = subpaths.length; j < o; j++) {
          var path = subpaths[j];
          if (path.fillStyle) {
            ctx.fillStyle = path.fillStyle;
            if (path.fillTransform) {
              var m = path.fillTransform;
              path.__draw__(ctx);
              ctx.save();
              ctx.transform(m.a, m.b, m.c, m.d, m.tx, m.ty);
              ctx.fill();
              ctx.restore();
            } else {
              ctx.fill(path);
            }
          }
          if (path.strokeStyle) {
            ctx.strokeStyle = path.strokeStyle;
            var drawingStyles = path.drawingStyles;
            for (var prop in drawingStyles)
              ctx[prop] = drawingStyles[prop];
            ctx.stroke(path);
          }

          if (hitTestShape && ctx.isPointInPath(pt.x, pt.y) ||
              (ctx.mozIsPointInStroke && ctx.mozIsPointInStroke(pt.x, pt.y)))
            hitTest = true;
        }
      }

      if (child.draw) {
        child.draw(ctx, child.ratio);
      }

      if (!isContainer) {
        // letting the container to restore transforms after all children are painted
        ctx.restore();
      }

      if (interactiveParent && hitTest) {
        if (interactiveParent._mouseOver) {
          interactiveParent.dispatchEvent(new flash.events.MouseEvent('mouseMove'));
        } else {
          interactiveParent._mouseOver = true;
          interactiveParent.dispatchEvent(new flash.events.MouseEvent('mouseOver'));
        }

        stage._clickTarget = interactiveParent;
      } else {
        if (interactiveParent._mouseOver) {
          interactiveParent._mouseOver = false;
          interactiveParent.dispatchEvent(new flash.events.MouseEvent('mouseOut'));
        }

        if (stage._mouseTarget === interactiveParent)
          stage._clickTarget = null;
      }
    }
  };

  var frameTime = 0;
  var maxDelay = 1000 / stage.frameRate;

  ctx.mozFillRule = 'evenodd';

  var requestAnimationFrame = window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame;

  var FPS = (function () {
    var width = Math.max(ctx.canvas.width / 5, 100);
    var height = width / 8;
    var sampleWidth = 2;
    var sampleCount = width / (sampleWidth + 1);
    var last = null;
    var samples = [];
    var max = 0;

    return {
      tick: function () {
        var curr = new Date();
        if (last) {
          if (samples.length > sampleCount) {
            samples.shift();
          }
          var elapsed = curr - last;
          samples.push(elapsed);
          var sum = 0;
          for (var i = 0; i < samples.length; i++) {
            sum += samples[i];
            max = Math.max(max, samples[i]);
          }
          var avg = sum / samples.length;
          var xOffset = ctx.canvas.width - width;
          var yOffset = height;
          for (var i = 0; i < samples.length; i++) {
            var scaledSample = (samples[i] / (2 * avg));
            ctx.fillRect(xOffset + i * (sampleWidth + 1), yOffset, sampleWidth, - scaledSample * height);
          }
          ctx.font = "6pt Verdana";
          ctx.fillText("FPS: " + (1000 / avg).toFixed(2), xOffset, height + 15);
        }
        last = curr;
      }
    };
  })();

  (function draw() {
    var now = +new Date;
    if (now - frameTime >= maxDelay) {
      frameTime = now;
      visitContainer(stage, new EnterFrameVisitor());
      visitContainer(stage, new RenderVisitor(ctx));
      visitContainer(stage, new ExitFrameVisitor());
      FPS.tick();
    }
    requestAnimationFrame(draw);
  })();
}
<commit_msg>Small optimizations to the renderer.<commit_after>function renderStage(stage, ctx) {
  // All the visitors close over this class to do instance testing.
  const MovieClipClass = avm2.systemDomain.getClass("flash.display.MovieClip");
  const InteractiveClass = avm2.systemDomain.getClass("flash.display.InteractiveObject");

  function visitContainer(container, visitor, interactiveParent) {
    var children = container._children;
    visitor.childrenStart(container);
    for (var i = 0, n = children.length; i < n; i++) {
      var child = children[i];
      if (child) {
        var isContainer = child._children.length;

        if (InteractiveClass.isInstanceOf(child)) {
          if (!interactiveParent || interactiveParent._mouseChildren)
            interactiveParent = child;
        }

        visitor.visit(child, isContainer, interactiveParent);

        if (isContainer)
          visitContainer(child, visitor, interactiveParent);
      }
    }
    visitor.childrenEnd(container);
  }

  function EnterFrameVisitor() {
  }
  EnterFrameVisitor.prototype = {
    childrenStart: function() {},
    childrenEnd: function() {},
    visit: function (obj) {
      if (MovieClipClass.isInstanceOf(obj)) {
        if (obj.isPlaying()) {
          var currentFrame = obj._currentFrame;

          obj.nextFrame();

          if (obj._currentFrame !== currentFrame)
            obj._scriptExecutionPending = true;
        }
        obj.dispatchEvent(new flash.events.Event("enterFrame"));
      }
    }
  };

  function ExitFrameVisitor() {
  }
  ExitFrameVisitor.prototype = {
    childrenStart: function() {},
    childrenEnd: function() {},
    visit: function (obj) {
      if (MovieClipClass.isInstanceOf(obj)) {
        obj.dispatchEvent(new flash.events.Event("exitFrame"));
      }
    }
  };

  function RenderVisitor(ctx) {
    this.depth = 0;
    this.ctx = ctx;
  }
  RenderVisitor.prototype = {
    childrenStart: function(parent) {
      if (this.depth == 0) {
        var ctx = this.ctx;
        var stage = parent;
        var frameWidth = ctx.canvas.width;
        var frameHeight = ctx.canvas.height;

        var scaleX = frameWidth / stage._stageWidth;
        var scaleY = frameHeight / stage._stageHeight;

        var scale = Math.min(scaleX, scaleY);
        var offsetX = (frameWidth - scale * stage.stageWidth) / 2;
        var offsetY = (frameHeight - scale * stage.stageHeight) / 2;

        ctx.clearRect(0, 0, frameWidth, frameHeight);
        ctx.save();
        ctx.translate(offsetX, offsetY);
        ctx.scale(scale, scale);

        ctx.canvas.currentTransform = {
          scale: scale,
          offsetX: offsetX,
          offsetY: offsetY
        };
      }
      this.depth++;

      // TODO move into separate visitor?
      if (MovieClipClass.isInstanceOf(parent) && parent._scriptExecutionPending) {
        parent._callFrame(parent.currentFrame);
        parent._scriptExecutionPending = false;
      }
    },
    childrenEnd: function(parent) {
      this.depth--;
      this.ctx.restore();
    },
    visit: function (child, isContainer, interactiveParent) {
      var hitTest = false;
      var hitTestShape = false;

      if (interactiveParent) {
        var pt = new flash.geom.Point(stage._mouseX, stage._mouseY);
        child._applyCurrentInverseTransform(pt, child._parent);

        if (child._hitArea)
          hitTest = child._hitArea._hitTest(true, pt.x, pt.y, true);

        if (!hitTest)
          hitTestShape = true;
      }

      var ctx = this.ctx;
      ctx.save();

      var m = child._currentTransform;
      ctx.transform(m.a, m.b, m.c, m.d, m.tx, m.ty);

      var cxform = child._cxform;
      if (cxform) {
        // We only support alpha channel transformation for now
        ctx.globalAlpha = (ctx.globalAlpha * cxform.alphaMultiplier + cxform.alphaOffset) / 256;
      }

      if (child._graphics) {
        var graphics = child._graphics;

        var scale = graphics._scale;
        if (scale !== 1)
          ctx.scale(scale, scale);

        var subpaths = graphics._subpaths;
        for (var j = 0, o = subpaths.length; j < o; j++) {
          var path = subpaths[j];
          if (path.fillStyle) {
            ctx.fillStyle = path.fillStyle;
            if (path.fillTransform) {
              var m = path.fillTransform;
              path.__draw__(ctx);
              ctx.save();
              ctx.transform(m.a, m.b, m.c, m.d, m.tx, m.ty);
              ctx.fill();
              ctx.restore();
            } else {
              ctx.fill(path);
            }
          }
          if (path.strokeStyle) {
            ctx.strokeStyle = path.strokeStyle;
            var drawingStyles = path.drawingStyles;
            for (var prop in drawingStyles)
              ctx[prop] = drawingStyles[prop];
            ctx.stroke(path);
          }

          if (hitTestShape && ctx.isPointInPath(pt.x, pt.y) ||
              (ctx.mozIsPointInStroke && ctx.mozIsPointInStroke(pt.x, pt.y)))
            hitTest = true;
        }
      }

      if (child.draw) {
        child.draw(ctx, child.ratio);
      }

      if (!isContainer) {
        // letting the container to restore transforms after all children are painted
        ctx.restore();
      }

      if (interactiveParent && hitTest) {
        if (interactiveParent._mouseOver) {
          interactiveParent.dispatchEvent(new flash.events.MouseEvent('mouseMove'));
        } else {
          interactiveParent._mouseOver = true;
          interactiveParent.dispatchEvent(new flash.events.MouseEvent('mouseOver'));
        }

        stage._clickTarget = interactiveParent;
      } else {
        if (interactiveParent._mouseOver) {
          interactiveParent._mouseOver = false;
          interactiveParent.dispatchEvent(new flash.events.MouseEvent('mouseOut'));
        }

        if (stage._mouseTarget === interactiveParent)
          stage._clickTarget = null;
      }
    }
  };

  var frameTime = 0;
  var maxDelay = 1000 / stage.frameRate;

  ctx.mozFillRule = 'evenodd';

  var requestAnimationFrame = window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame;

  var FPS = (function () {
    var width = Math.max(ctx.canvas.width / 5, 100);
    var height = width / 8;
    var sampleWidth = 2;
    var sampleCount = width / (sampleWidth + 1);
    var last = null;
    var samples = [];
    var max = 0;

    return {
      tick: function () {
        var curr = new Date();
        if (last) {
          if (samples.length > sampleCount) {
            samples.shift();
          }
          var elapsed = curr - last;
          samples.push(elapsed);
          var sum = 0;
          for (var i = 0; i < samples.length; i++) {
            sum += samples[i];
            max = Math.max(max, samples[i]);
          }
          var avg = sum / samples.length;
          var xOffset = ctx.canvas.width - width;
          var yOffset = height;
          for (var i = 0; i < samples.length; i++) {
            var scaledSample = (samples[i] / (2 * avg));
            ctx.fillRect(xOffset + i * (sampleWidth + 1), yOffset, sampleWidth, - scaledSample * height);
          }
          ctx.font = "6pt Verdana";
          ctx.fillText("FPS: " + (1000 / avg).toFixed(2), xOffset, height + 15);
        }
        last = curr;
      }
    };
  })();

  (function draw() {
    var now = +new Date;
    if (now - frameTime >= maxDelay) {
      frameTime = now;
      visitContainer(stage, new EnterFrameVisitor());
      visitContainer(stage, new RenderVisitor(ctx));
      visitContainer(stage, new ExitFrameVisitor());
      FPS.tick();
    }
    requestAnimationFrame(draw);
  })();
}
<|endoftext|>


<commit_before>/*!
 * Copyright 2015 Comcast Cable Communications Management, LLC
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

 (function(root, factory) {
  if(typeof define === 'function' && define.amd) {
    // For Require.js
    define('surfnperf/resource-timing', ['surfnperf'], factory);
  } else if(typeof exports === 'object') {
    // For Browserify
    module.exports = factory(require('surfnperf'));
  } else {
    // Browser global if not using Require.js or Browserify
    root.surfnperfRT = factory(root.surfnperf);
  }
}(this, function(surfnperf) {
  /**
   * Date.now() shim for older browsers
   */
  if(!Date.now) {
    Date.now = function now() {
      return new Date().getTime();
    };
  }

  var defaults = function(o, d) {
      for(var prop in d) {
        if(!o.hasOwnProperty(prop)) {
          o[prop] = d[prop];
        }
      }
    },
    contains = function(array, value) {
      if(Array.prototype.indexOf) {
        return array.indexOf(value) != -1;
      } else {
        var i, length = array.length;
        for(i = 0; i < length; i++) {
          if(array[i] === value) {
            return true;
          }
        }
        return false;
      }
    };

  /**
   * Frontend Web Performance Data Gathering
   *
   * @class SurfNPerf
   */
  var SurfNPerfRT = function() {
      this._data = {
        custom: {},
        marks: {},
        highResMarks: {},
        events: {}
      };

      this._navigationTiming = null;
      this._highResTime = null;
      this._userTiming = null;

      this._navigationTimingEvents = {
        a: ["navigationStart", "unloadEventEnd", "unloadEventStart", "redirectStart", "redirectEnd", "fetchStart", "domainLookupStart", "domainLookupEnd", "connectStart", "secureConnectionStart", "connectEnd", "requestStart", "responseStart", "responseEnd", "domLoading"],
        b: ["domInteractive", "domContentLoadedEventStart", "domContentLoadedEventEnd", "domComplete", "loadEventStart", "loadEventEnd"]
      };

      this.initialize();
    },
    SNPRTProto = SurfNPerfRT.prototype;

  SNPRTProto.getOrigins = function(options) {

  };

  SNPRTProto.getResourcesFromOrigin = function(origin) {

  };

  SNPRTProto.isBufferFull = function() {

  };

  SNPRTProto._nameExtend = function(name) {
    if(name.charAt(0) == '/') {
      return "http://" + window.location.hostname + name;
    } else {
      return name;
    }
  };

  SNPRTProto.duration = function(name, eventA, eventB, options) {
    name = this._nameExtend(name);

  };

  SNPRTProto.getResource = function(name) {
    name = this._nameExtend(name);

    return window.performance.getEntriesByName(name, "resource")[0]
  };

  SNPRTProto.start = function(name, options) {
    name = this._nameExtend(name);

    var resource = this.getResource(name);
    if(resource == undefined) {
      return undefined;
    }
    var start = resource.startTime;
    if(options != null && options.hasOwnProperty("decimalPlaces")) {
      start = start.toFixed(options["decimalPlaces"]);
    }
    return start;
  };

  SNPRTProto.end = function(name, options) {
    name = this._nameExtend(name);

    var resource = this.getResource(name);
    if(resource == undefined) {
      return undefined;
    }
    var end = resource.responseEnd;
    if(options != null && options.hasOwnProperty("decimalPlaces")) {
      end = end.toFixed(options["decimalPlaces"]);
    }
    return end;
  };

  SNPRTProto.getFullRequestLoadTime = function(name, options) {
    name = this._nameExtend(name);

  };

  SNPRTProto.getNetworkTime = function(name, options) {
    name = this._nameExtend(name);

  };

  SNPRTProto.getServerTime = function(name, options) {
    name = this._nameExtend(name);

  };

  SNPRTProto.getBlockingTime = function(name, options) {
    name = this._nameExtend(name);

  };
}));<commit_msg>some functions<commit_after>/*!
 * Copyright 2015 Comcast Cable Communications Management, LLC
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

 (function(root, factory) {
  if(typeof define === 'function' && define.amd) {
    // For Require.js
    define('surfnperf/resource-timing', ['surfnperf'], factory);
  } else if(typeof exports === 'object') {
    // For Browserify
    module.exports = factory(require('surfnperf'));
  } else {
    // Browser global if not using Require.js or Browserify
    root.surfnperfRT = factory(root.surfnperf);
  }
}(this, function(surfnperf) {
  /**
   * Date.now() shim for older browsers
   */
  if(!Date.now) {
    Date.now = function now() {
      return new Date().getTime();
    };
  }

  var defaults = function(o, d) {
      for(var prop in d) {
        if(!o.hasOwnProperty(prop)) {
          o[prop] = d[prop];
        }
      }
    },
    contains = function(array, value) {
      if(Array.prototype.indexOf) {
        return array.indexOf(value) != -1;
      } else {
        var i, length = array.length;
        for(i = 0; i < length; i++) {
          if(array[i] === value) {
            return true;
          }
        }
        return false;
      }
    };

  /**
   * Frontend Web Performance Data Gathering
   *
   * @class SurfNPerf
   */
  var SurfNPerfRT = function() {
      this._data = {
        custom: {},
        marks: {},
        highResMarks: {},
        events: {}
      };

      this._navigationTiming = null;
      this._highResTime = null;
      this._userTiming = null;

      this._navigationTimingEvents = {
        a: ["navigationStart", "unloadEventEnd", "unloadEventStart", "redirectStart", "redirectEnd", "fetchStart", "domainLookupStart", "domainLookupEnd", "connectStart", "secureConnectionStart", "connectEnd", "requestStart", "responseStart", "responseEnd", "domLoading"],
        b: ["domInteractive", "domContentLoadedEventStart", "domContentLoadedEventEnd", "domComplete", "loadEventStart", "loadEventEnd"]
      };

      this.initialize();
    },
    SNPRTProto = SurfNPerfRT.prototype;

  SNPRTProto.getOrigins = function(options) {
    if(window.performance.getEntriesByType) {

    } else {
      return null;
    }
  };

  SNPRTProto.getResourcesFromOrigin = function(origin) {
    if(window.performance.getEntriesByType) {

    } else {
      return null;
    }
  };

  SNPRTProto.isBufferFull = function() {
    if(window.performance.getEntriesByType) {
      if(performance.onresourcetimingbufferfull) {
        return true;
      } else {
        return false;
      }
    } else {
      return null;
    }
  };

  SNPRTProto._nameExtend = function(name) {
    if(name.charAt(0) == '/') {
      return "http://" + window.location.hostname + name;
    } else {
      return name;
    }
  };

  SNPProto._round = function(n, options) {
    options = options || {};
    var dp = options.decimalPlaces || 0;
    n = +(n);
    return n.toFixed ? +(n).toFixed(dp) : n;
  };

  SNPRTProto.duration = function(name, eventA, eventB, options) {
    name = this._nameExtend(name);

  };

  SNPRTProto.getResource = function(name) {
    name = this._nameExtend(name);

    return window.performance.getEntriesByName(name, "resource")[0]
  };

  SNPRTProto.start = function(name, options) {
    name = this._nameExtend(name);

    var resource = this.getResource(name);
    if(resource == undefined) {
      return undefined;
    }
    var start = resource.startTime;
    if(options != null && options.hasOwnProperty("decimalPlaces")) {
      start = start.toFixed(options["decimalPlaces"]);
    }
    return start;
  };

  SNPRTProto.end = function(name, options) {
    name = this._nameExtend(name);

    var resource = this.getResource(name);
    if(resource == undefined) {
      return undefined;
    }
    var end = resource.responseEnd;
    if(options != null && options.hasOwnProperty("decimalPlaces")) {
      end = end.toFixed(options["decimalPlaces"]);
    }
    return end;
  };

  SNPRTProto.getFullRequestLoadTime = function(name, options) {
    name = this._nameExtend(name);

    return this._round(this.getResource(name).duration, options);

  };

  SNPRTProto.getNetworkTime = function(name, options) {
    name = this._nameExtend(name);

  };

  SNPRTProto.getServerTime = function(name, options) {
    name = this._nameExtend(name);

  };

  SNPRTProto.getBlockingTime = function(name, options) {
    name = this._nameExtend(name);

  };
}));<|endoftext|>


<commit_before>import * as _ from "../deps/underscore-esm.js"
//
// Super-simple class implementation
//
// Example usage:
//
// BiwaScheme.Foo = BiwaScheme.Class.create({
//   initialize: function(a){
//     this.a = a;
//   },
//
//   toString: function(){
//     return "foo[" + this.a + "]";
//   }
// });
//
// BiwaScheme.Bar = BiwaScheme.Class.extend(new BiwaScheme.Foo("hello1"), {
//   initialize: function(b){
//     this.b = b;
//   },
//
//   printEverything: function(){
//     console.log("a = ", this.a, "b = ", this.b);
//   },
//
//   toString: function(){
//     return "bar[" + this.b + "]";
//   }
// });

const Class = {
  create: function(methods) {
    var klass = function(){ this.initialize.apply(this, arguments); };
    _.extend(klass.prototype, methods);
    return klass;
  },

  extend: function(parent, methods) {
    var klass = function(){ this.initialize.apply(this, arguments); };
    klass.prototype = parent;
    _.extend(klass.prototype, methods);
    return klass;
  }
};

// Update the given method to memoized version.
//
// - klass : a class defined by BiwaScheme.Class.create
// - name_or_names : method name (a string or an array of strings)
//
// Example
//
//   // Given this method
//   BiwaScheme.Enumeration.EnumType = ...
//     universe: function(){
//       return ...
//     }
//   ...
//   // Memoize
//   BiwaScheme.Class.memoize(BiwaScheme.Enumeration.EnumType,
//                            "_universe");
//
//   // Equal to:
//   BiwaScheme.Enumeration.EnumType = ...
//     universe: function(){
//       if(!this.hasOwnProperty("cached_universe")){
//         this.cached_universe = this.compute_universe();
//       }
//       return this.cached_universe;
//     },
//     compute_universe: function(){
//       // Original function, renamed to compute_*
//       return ...
//     }
//   ...
Class.memoize = function(klass, name_or_names){
  var proto = klass.prototype;
  var names = _.isArray(name_or_names) ? name_or_names : [name_or_names];

  _.each(names, function(name){
    // Copy original function foo as 'compute_foo'
    proto["compute_"+name] = proto[name];

    // Define memoizing version
    proto[name] = function(/*arguments*/){
      if(!this.hasOwnProperty("cached_"+name)){
        this["cached_"+name] = this["compute_"+name].apply(this, _.toArray(arguments));
      }
      return this["cached_"+name];
    }
  });
}

export default Class;
<commit_msg>cleanup: Remove class.js<commit_after><|endoftext|>


<commit_before><commit_msg>release<commit_after><|endoftext|>


<commit_before>// `Vector` represents a 2D vector. It can be used for positions, velocities and accelerations.
var Vector = exports.Vector = {

	// Initialize the vector. `x` and `y` are `0` by default.
	init: function (x, y) {
		this.x = x || 0;
		this.y = y || 0;

		return this;   // method chaining
	},

	// Set `x` and `y` to `0`.
	reset: function () {
		this.x = this.y = 0;

		return this;   // method chaining
	},

	// Add to the vector. Either one `Vector` object or two raw values `x` and `y` can be passed.
	add: function (x, y) {
		if (arguments.length >= 2) {   // assuming two raw values
			this.x += x;
			this.y += y;
		} else if (arguments.length === 1 && arguments[0]) {   // assuming one `Vector` object
			this.x += x.x;
			this.y += x.y;
		}

		return this;   // method chaining
	},

	// Subtract from the vector. Either one `Vector` object or two raw values `x` and `y` can be passed.
	substract: function (x, y) {
		if (arguments.length >= 2) {   // assuming two raw values
			this.x -= x;
			this.y -= y;
		} else if (arguments.length === 1 && arguments[0]) {   // assuming one `Vector` object
			this.x -= x.x;
			this.y -= x.y;
		}

		return this;   // method chaining
	},

	// Do a scalar multiplication with the vector. Either one factor or a `Vector` object with two factors for `x` and `y` can be passed.
	multiply: function (vector) {
		if (typeof vector === 'number') {
			this.x *= vector;
			this.y *= vector;
		if (typeof vector.x === 'number' && typeof vector.x === 'number') {
			this.x *= vector.x;
			this.y *= vector.y;
		}

		return this;   // method chaining
	},

	// Compute the vector's angle in radians.
	angle: function () {
		return Math.atan2(this.y, this.x);
	},

	// Compute the vector's length.
	length: function () {
		return Math.sqrt(this.x * this.x + this.y * this.y);
	},

	// Return a new `Vector` object with the same values.
	clone: function () {
		return new Vector(this.x, this.y);
	},

	// Create a new `Vector` object using a direction (`angle`) and a `length`.
	fromAngle: function (angle, length) {
		length = typeof length === 'number' ? length : 1;
		return v(Math.cos(angle) * length, Math.sin(angle) * length);
	}

};

// Export a shorthand.
var v = exports.v = function (x, y) {
	return inherit(Vector)
	.init(x, y);
};
<commit_msg>`src/02-Vector.js`: small bugfix<commit_after>// `Vector` represents a 2D vector. It can be used for positions, velocities and accelerations.
var Vector = exports.Vector = {

	// Initialize the vector. `x` and `y` are `0` by default.
	init: function (x, y) {
		this.x = x || 0;
		this.y = y || 0;

		return this;   // method chaining
	},

	// Set `x` and `y` to `0`.
	reset: function () {
		this.x = this.y = 0;

		return this;   // method chaining
	},

	// Add to the vector. Either one `Vector` object or two raw values `x` and `y` can be passed.
	add: function (x, y) {
		if (arguments.length >= 2) {   // assuming two raw values
			this.x += x;
			this.y += y;
		} else if (arguments.length === 1 && arguments[0]) {   // assuming one `Vector` object
			this.x += x.x;
			this.y += x.y;
		}

		return this;   // method chaining
	},

	// Subtract from the vector. Either one `Vector` object or two raw values `x` and `y` can be passed.
	substract: function (x, y) {
		if (arguments.length >= 2) {   // assuming two raw values
			this.x -= x;
			this.y -= y;
		} else if (arguments.length === 1 && arguments[0]) {   // assuming one `Vector` object
			this.x -= x.x;
			this.y -= x.y;
		}

		return this;   // method chaining
	},

	// Do a scalar multiplication with the vector. Either one factor or a `Vector` object with two factors for `x` and `y` can be passed.
	multiply: function (vector) {
		if (typeof vector === 'number') {
			this.x *= vector;
			this.y *= vector;
		} else if (typeof vector.x === 'number' && typeof vector.x === 'number') {
			this.x *= vector.x;
			this.y *= vector.y;
		}

		return this;   // method chaining
	},

	// Compute the vector's angle in radians.
	angle: function () {
		return Math.atan2(this.y, this.x);
	},

	// Compute the vector's length.
	length: function () {
		return Math.sqrt(this.x * this.x + this.y * this.y);
	},

	// Return a new `Vector` object with the same values.
	clone: function () {
		return new Vector(this.x, this.y);
	},

	// Create a new `Vector` object using a direction (`angle`) and a `length`.
	fromAngle: function (angle, length) {
		length = typeof length === 'number' ? length : 1;
		return v(Math.cos(angle) * length, Math.sin(angle) * length);
	}

};

// Export a shorthand.
var v = exports.v = function (x, y) {
	return inherit(Vector)
	.init(x, y);
};
<|endoftext|>


<commit_before>/**

  Bundler.js

  Wrapper for module bundling: currently uses webpack.

  Statics
  • fromFile

  Class
  • construtor
  • get

**/

//
//  Dependencies
//

var Utils        = require("./utils"),
    Promise      = require("bluebird"),
    path         = require("path"),
    webpack      = require("webpack"),
    readFile     = Promise.promisify(global.fs.readFile.bind(global.fs));

/**

  Wraps a webpack instance, writing to in-memory file system.

  options
  • <String>  entry              : input file
  • <String>  filename           : output filename
  • <Boolean> [compile=true]     : compile upon instantiation
  • <Boolean> [watch=true]       : watch for recompilation
  • <String>  [path="/scripts"]  : in-memory path

  @param {Object} options
  @returns {Bundler} Instance of this class

**/

var Bundler = module.exports = function(options) {

  // Determine which extensions to look for
  var exts = Utils.readDirectory(path.join(options.entry, "..")).reduce(function(arr, file) {
    if (-1 === arr.indexOf(file.ext)) arr.push(file.ext);
    return arr;
  }, []).concat([""]);

  // Set up defaults
  options = Object.assign({ compile: true, watch : true, path : "/scripts/" }, options);

  // Configure
  this.config = {
    entry      : options.entry,
    output     : {
      path     : options.path,
      filename : options.filename
    },
    module     : {
      loaders  : [ { test: /.+/, loader: "superloader" } ]
    },
    resolve    : { extensions: exts }
  };

  // Store path
  this.path = path.join(this.config.output.path, options.filename);

  // Set up bundler with in-memory file sysstem
  this.bundler = webpack(this.config);
  this.bundler.outputFileSystem = global.fs;

  // Bind functions
  this.get = this.get.bind(this);
  this.compile = Promise.promisify(this.bundler.run.bind(this.bundler));

  // Optionally compile
  if (options.compile) this.compile();

  // Set up watch (it already updates)
  if (options.watch) this.bundler.watch({}, function(err, stats) {
    global.server.reload(this.path);
  }.bind(this));

};

/**

  Reads the most recently compiled version of a file from in-memory file system.

  @returns {String} Compiled file.

**/

Bundler.prototype.get = function() {
  return readFile(this.path, "utf8");
};

/**

  Creates a bundler from a file, modifies file for proper routing.

  @param {File} file Modified file object, as returned by Utils#mapFiles
  @param {String} type Type of the output file

**/

Bundler.fromFile = function(file, type) {
  file.folder = "";
  file.name = file.dir.replace(Utils.makePathAbsolute(file.basePath), "").slice(1);
  return new Bundler({ entry : file.path, filename : file.name + "." + type });
};
<commit_msg>Bundler: utilizes Utils#uniqueExtensions<commit_after>/**

  Bundler.js

  Wrapper for module bundling: currently uses webpack.

  Statics
  • fromFile

  Class
  • construtor
  • get

**/

//
//  Dependencies
//

var Utils        = require("./utils"),
    Promise      = require("bluebird"),
    path         = require("path"),
    webpack      = require("webpack"),
    readFile     = Promise.promisify(global.fs.readFile.bind(global.fs));

/**

  Wraps a webpack instance, writing to in-memory file system.

  options
  • <String>  entry              : input file
  • <String>  filename           : output filename
  • <Boolean> [compile=true]     : compile upon instantiation
  • <Boolean> [watch=true]       : watch for recompilation
  • <String>  [path="/scripts"]  : in-memory path

  @param {Object} options
  @returns {Bundler} Instance of this class

**/

var Bundler = module.exports = function(options) {

  // Determine which extensions to look for
  var exts = Utils.uniqueExtensions(path.join(options.entry, "..")).concat([""]);

  // Set up defaults
  options = Object.assign({ compile: true, watch : true, path : "/scripts/" }, options);

  // Configure
  this.config = {
    entry      : options.entry,
    output     : {
      path     : options.path,
      filename : options.filename
    },
    module     : {
      loaders  : [ { test: /.+/, loader: "superloader" } ]
    },
    resolve    : { extensions: exts }
  };

  // Store path
  this.path = path.join(this.config.output.path, options.filename);

  // Set up bundler with in-memory file sysstem
  this.bundler = webpack(this.config);
  this.bundler.outputFileSystem = global.fs;

  // Bind functions
  this.get = this.get.bind(this);
  this.compile = Promise.promisify(this.bundler.run.bind(this.bundler));

  // Optionally compile
  if (options.compile) this.compile();

  // Set up watch (it already updates)
  if (options.watch) this.bundler.watch({}, function(err, stats) {
    global.server.reload(this.path);
  }.bind(this));

};

/**

  Reads the most recently compiled version of a file from in-memory file system.

  @returns {String} Compiled file.

**/

Bundler.prototype.get = function() {
  return readFile(this.path, "utf8");
};

/**

  Creates a bundler from a file, modifies file for proper routing.

  @param {File} file Modified file object, as returned by Utils#mapFiles
  @param {String} type Type of the output file

**/

Bundler.fromFile = function(file, type) {
  file.folder = "";
  file.name = file.dir.replace(Utils.makePathAbsolute(file.basePath), "").slice(1);
  return new Bundler({ entry : file.path, filename : file.name + "." + type });
};
<|endoftext|>


<commit_before>'use strict';
goog.provide('session');

/*jshint unused:false*/
goog.require('goog.json');
goog.require('utils');
goog.require('safejson');
goog.require('storage');

/**
 * @param {storage} storage
 * @param {boolean=} first
 * @return {Object}
 */
session.get = function(storage, first) {
	var sessionString = first ? 'branch_session_first' : 'branch_session';
	try {
		var data = safejson.parse(storage.get(sessionString, first)) || null;
		return utils.decodeBFPs(data);
	}
	catch (e) {
		return null;
	}
};

/**
 * @param {storage} storage
 * @param {Object} data
 * @param {boolean=} first
 */
session.set = function(storage, data, first) {
	data = utils.encodeBFPs(data);
	storage.set('branch_session', goog.json.serialize(data));
	if (first) {
		storage.set('branch_session_first', goog.json.serialize(data), true);
	}
};

/**
 * @param {storage} storage
 * @param {Object} newData
 */
session.update = function(storage, newData) {
	if (!newData) {
		return;
	}
	var currentData = session.get(storage) || {};
	var data = goog.json.serialize(utils.encodeBFPs(utils.merge(currentData, newData)));
	storage.set('branch_session', data);
};

/**
 * Patches a field in localStorage or sessionStorage or both.
 * @param {storage} storage
 * @param {Object} data
 * @param {boolean=} updateLocalStorage
 * @param {boolean=} removeNull delete null or undefined entries instead of inserting
 */
session.patch = function(storage, data, updateLocalStorage, removeNull) {
	var merge = function(source, patch) {
		return utils.encodeBFPs(utils.merge(goog.json.parse(source), patch, removeNull));
	};

	var session = storage.get('branch_session', false) || {};
	storage.set('branch_session', goog.json.serialize(merge(session, data)));

	if (updateLocalStorage) {
		var sessionFirst = storage.get('branch_session_first', true) || {};
		storage.set('branch_session_first', goog.json.serialize(merge(sessionFirst, data)), true);
	}
};
<commit_msg>INTENG-11116: Fix unsafe eval error (#755)<commit_after>'use strict';
goog.provide('session');

/*jshint unused:false*/
goog.require('goog.json');
goog.require('utils');
goog.require('safejson');
goog.require('storage');

/**
 * @param {storage} storage
 * @param {boolean=} first
 * @return {Object}
 */
session.get = function(storage, first) {
	var sessionString = first ? 'branch_session_first' : 'branch_session';
	try {
		var data = safejson.parse(storage.get(sessionString, first)) || null;
		return utils.decodeBFPs(data);
	}
	catch (e) {
		return null;
	}
};

/**
 * @param {storage} storage
 * @param {Object} data
 * @param {boolean=} first
 */
session.set = function(storage, data, first) {
	data = utils.encodeBFPs(data);
	storage.set('branch_session', goog.json.serialize(data));
	if (first) {
		storage.set('branch_session_first', goog.json.serialize(data), true);
	}
};

/**
 * @param {storage} storage
 * @param {Object} newData
 */
session.update = function(storage, newData) {
	if (!newData) {
		return;
	}
	var currentData = session.get(storage) || {};
	var data = goog.json.serialize(utils.encodeBFPs(utils.merge(currentData, newData)));
	storage.set('branch_session', data);
};

/**
 * Patches a field in localStorage or sessionStorage or both.
 * @param {storage} storage
 * @param {Object} data
 * @param {boolean=} updateLocalStorage
 * @param {boolean=} removeNull delete null or undefined entries instead of inserting
 */
session.patch = function(storage, data, updateLocalStorage, removeNull) {
	var merge = function(source, patch) {
		return utils.encodeBFPs(utils.merge(safejson.parse(source), patch, removeNull));
	};

	var session = storage.get('branch_session', false) || {};
	storage.set('branch_session', goog.json.serialize(merge(session, data)));

	if (updateLocalStorage) {
		var sessionFirst = storage.get('branch_session_first', true) || {};
		storage.set('branch_session_first', goog.json.serialize(merge(sessionFirst, data)), true);
	}
};
<|endoftext|>


<commit_before>window.ExcerptViewer = function(mapElementID, excerptApiUrl, disableZoom) {
    this.excerptApiUrl = excerptApiUrl;
    this.currentLayer = null;

    if (disableZoom) {
        var map = L.map(mapElementID, {zoomControl: false}).setView([0, 0], 2);
        map.dragging.disable();
        map.touchZoom.disable();
        map.doubleClickZoom.disable();
        map.scrollWheelZoom.disable();
        map.keyboard.disable();
        this.map = map;
    } else {
        this.map = L.map(mapElementID).setView([0, 0], 2);
    }

    L.control.scale().addTo(this.map);
    // add an OpenStreetMap tile layer
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo(this.map);

    this._handleCountryOrBBox = function (layer){
        if (this.currentLayer !== null) {
            this.map.removeLayer(this.currentLayer);
        }

        this.currentLayer = layer;
        this.map.addLayer(layer);
    }.bind(this);

    this.showExcerptOnMap = function(ID) {
        L.geoJson.ajax(this.excerptApiUrl.replace('{ID}', ID)).on('data:loaded', function(event) {
            // We are certain that there is only one layer on this feature, because our API provides it so.
            var color = event.target.getLayers()[0].feature.properties.color || 'red';
            var layer = event.target;
            this._handleCountryOrBBox(layer);
            this.map.fitBounds(layer.getBounds());
            layer.setStyle({
                color: color,
                fillOpacity: 0.15
            });
        }.bind(this)).on('data:loading', function(){
            this.map.spin(true);
        }.bind(this)).on('data:loaded', function(){
            this.map.spin(false);
        }.bind(this));
    }.bind(this);
};
<commit_msg>allow zoom only through zoom controls<commit_after>window.ExcerptViewer = function(mapElementID, excerptApiUrl, disableZoom) {
    this.excerptApiUrl = excerptApiUrl;
    this.currentLayer = null;

    if (disableZoom) {
        var map = L.map(mapElementID, {zoomControl: true}).setView([0, 0], 2);
        map.dragging.disable();
        map.touchZoom.disable();
        map.doubleClickZoom.disable();
        map.scrollWheelZoom.disable();
        map.keyboard.disable();
        this.map = map;
    } else {
        this.map = L.map(mapElementID).setView([0, 0], 2);
    }

    L.control.scale().addTo(this.map);
    // add an OpenStreetMap tile layer
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo(this.map);

    this._handleCountryOrBBox = function (layer){
        if (this.currentLayer !== null) {
            this.map.removeLayer(this.currentLayer);
        }

        this.currentLayer = layer;
        this.map.addLayer(layer);
    }.bind(this);

    this.showExcerptOnMap = function(ID) {
        L.geoJson.ajax(this.excerptApiUrl.replace('{ID}', ID)).on('data:loaded', function(event) {
            // We are certain that there is only one layer on this feature, because our API provides it so.
            var color = event.target.getLayers()[0].feature.properties.color || 'red';
            var layer = event.target;
            this._handleCountryOrBBox(layer);
            this.map.fitBounds(layer.getBounds());
            layer.setStyle({
                color: color,
                fillOpacity: 0.15
            });
        }.bind(this)).on('data:loading', function(){
            this.map.spin(true);
        }.bind(this)).on('data:loaded', function(){
            this.map.spin(false);
        }.bind(this));
    }.bind(this);
};
<|endoftext|>


<commit_before>angular.scenario.dsl.browser = {
  navigateTo: function(url){
    var location = this.location;
    return $scenario.addFuture('Navigate to: ' + url, function(done){
      var self = this;
      this.testFrame.load(function(){
        self.testFrame.unbind();
        self.testWindow = self.testFrame[0].contentWindow;
        self.testDocument = self.jQuery(self.testWindow.document);
        self.$browser = self.testWindow.angular.service.$browser();
        self.notifyWhenNoOutstandingRequests =
          bind(self.$browser, self.$browser.notifyWhenNoOutstandingRequests);
        self.notifyWhenNoOutstandingRequests(done);
      });
      if (this.testFrame.attr('src') == url) {
        this.testFrame[0].contentWindow.location.reload();
      } else {
        this.testFrame.attr('src', url);
        location.setLocation(url);
      }
    });
  },
  location: {
    href: "",
    hash: "",
    toEqual: function(url) {
      return (this.hash == "" ? (url == this.href) :
        (url == (this.href + "/#/" + this.hash)));
    },
    setLocation: function(url) {
      var urlParts = url.split("/#/");
      this.href = urlParts[0] || "";
      this.hash = urlParts[1] || "";
    }
  }
};

angular.scenario.dsl.input = function(selector) {
  var namePrefix = "input '" + selector + "'";
  return {
    enter: function(value) {
      return $scenario.addFuture(namePrefix + " enter '" + value + "'", function(done) {
        var input = this.testDocument.find('input[name=' + selector + ']');
        input.val(value);
        this.testWindow.angular.element(input[0]).trigger('change');
        done();
      });
    },
    select: function(value) {
      return $scenario.addFuture(namePrefix + " select '" + value + "'", function(done) {
        var input = this.testDocument.
          find(':radio[name$=@' + selector + '][value=' + value + ']');
        jqLiteWrap(input[0]).trigger('click');
        input[0].checked = true;
        done();
      });
    }
  };
},

angular.scenario.dsl.NG_BIND_PATTERN =/\{\{[^\}]+\}\}/;

angular.scenario.dsl.repeater = function(selector) {
  var namePrefix = "repeater '" + selector + "'";
  return {
    count: function() {
      return $scenario.addFuture(namePrefix + ' count', function(done) {
          done(this.testDocument.find(selector).size());
      });
    },
    collect: function(collectSelector) {
      return $scenario.addFuture(
          namePrefix + " collect '" + collectSelector + "'",
          function(done) {
        var self = this;
        var doCollect = bind(this, function() {
          var repeaterArray = [], ngBindPattern;
          var startIndex = collectSelector.search(
              angular.scenario.dsl.NG_BIND_PATTERN);
          if (startIndex >= 0) {
            ngBindPattern = collectSelector.substring(
                startIndex + 2, collectSelector.length - 2);
            collectSelector = '*';

          }
          this.testDocument.find(selector).each(function() {
            var element = self.jQuery(this);
            element.find(collectSelector).
              each(function() {
                var foundElem = self.jQuery(this);
                if (foundElem.attr('ng:bind') == ngBindPattern) {
                  repeaterArray.push(foundElem.text());
                }
            });
          });
          return repeaterArray;
        });
        done(doCollect());
      });
    }
  };
};

angular.scenario.dsl.element = function(selector) {
  var namePrefix = "Element '" + selector + "'";
  var futureJquery = {};
  for (key in _jQuery.fn) {
    (function(){
      var jqFnName = key;
      var jqFn = _jQuery.fn[key];
      futureJquery[key] = function() {
        var jqArgs = arguments;
        return $scenario.addFuture(namePrefix + "." + jqFnName + "()",
                function(done) {
          var self = this, repeaterArray = [], ngBindPattern;
          var startIndex = selector.search(angular.scenario.dsl.NG_BIND_PATTERN);
          if (startIndex >= 0) {
            ngBindPattern = selector.substring(startIndex + 2, selector.length - 2);
            var element = this.testDocument.find('*').filter(function() {
              return self.jQuery(this).attr('ng:bind') == ngBindPattern;
            });
            done(jqFn.apply(element, jqArgs));
          } else {
            done(jqFn.apply(this.testDocument.find(selector), jqArgs));
          }
        });
      };
    })();
  }
  return futureJquery;
};
<commit_msg>Fix issue with jquery not being visible in production<commit_after>angular.scenario.dsl.browser = {
  navigateTo: function(url){
    var location = this.location;
    return $scenario.addFuture('Navigate to: ' + url, function(done){
      var self = this;
      this.testFrame.load(function(){
        self.testFrame.unbind();
        self.testWindow = self.testFrame[0].contentWindow;
        self.testDocument = self.jQuery(self.testWindow.document);
        self.$browser = self.testWindow.angular.service.$browser();
        self.notifyWhenNoOutstandingRequests =
          bind(self.$browser, self.$browser.notifyWhenNoOutstandingRequests);
        self.notifyWhenNoOutstandingRequests(done);
      });
      if (this.testFrame.attr('src') == url) {
        this.testFrame[0].contentWindow.location.reload();
      } else {
        this.testFrame.attr('src', url);
        location.setLocation(url);
      }
    });
  },
  location: {
    href: "",
    hash: "",
    toEqual: function(url) {
      return (this.hash == "" ? (url == this.href) :
        (url == (this.href + "/#/" + this.hash)));
    },
    setLocation: function(url) {
      var urlParts = url.split("/#/");
      this.href = urlParts[0] || "";
      this.hash = urlParts[1] || "";
    }
  }
};

angular.scenario.dsl.input = function(selector) {
  var namePrefix = "input '" + selector + "'";
  return {
    enter: function(value) {
      return $scenario.addFuture(namePrefix + " enter '" + value + "'", function(done) {
        var input = this.testDocument.find('input[name=' + selector + ']');
        input.val(value);
        this.testWindow.angular.element(input[0]).trigger('change');
        done();
      });
    },
    select: function(value) {
      return $scenario.addFuture(namePrefix + " select '" + value + "'", function(done) {
        var input = this.testDocument.
          find(':radio[name$=@' + selector + '][value=' + value + ']');
        jqLiteWrap(input[0]).trigger('click');
        input[0].checked = true;
        done();
      });
    }
  };
},

angular.scenario.dsl.NG_BIND_PATTERN =/\{\{[^\}]+\}\}/;

angular.scenario.dsl.repeater = function(selector) {
  var namePrefix = "repeater '" + selector + "'";
  return {
    count: function() {
      return $scenario.addFuture(namePrefix + ' count', function(done) {
          done(this.testDocument.find(selector).size());
      });
    },
    collect: function(collectSelector) {
      return $scenario.addFuture(
          namePrefix + " collect '" + collectSelector + "'",
          function(done) {
        var self = this;
        var doCollect = bind(this, function() {
          var repeaterArray = [], ngBindPattern;
          var startIndex = collectSelector.search(
              angular.scenario.dsl.NG_BIND_PATTERN);
          if (startIndex >= 0) {
            ngBindPattern = collectSelector.substring(
                startIndex + 2, collectSelector.length - 2);
            collectSelector = '*';

          }
          this.testDocument.find(selector).each(function() {
            var element = self.jQuery(this);
            element.find(collectSelector).
              each(function() {
                var foundElem = self.jQuery(this);
                if (foundElem.attr('ng:bind') == ngBindPattern) {
                  repeaterArray.push(foundElem.text());
                }
            });
          });
          return repeaterArray;
        });
        done(doCollect());
      });
    }
  };
};

angular.scenario.dsl.element = function(selector) {
  var namePrefix = "Element '" + selector + "'";
  var futureJquery = {};
  for (key in (jQuery || _jQuery).fn) {
    (function(){
      var jqFnName = key;
      var jqFn = (jQuery || _jQuery).fn[key];
      futureJquery[key] = function() {
        var jqArgs = arguments;
        return $scenario.addFuture(namePrefix + "." + jqFnName + "()",
                function(done) {
          var self = this, repeaterArray = [], ngBindPattern;
          var startIndex = selector.search(angular.scenario.dsl.NG_BIND_PATTERN);
          if (startIndex >= 0) {
            ngBindPattern = selector.substring(startIndex + 2, selector.length - 2);
            var element = this.testDocument.find('*').filter(function() {
              return self.jQuery(this).attr('ng:bind') == ngBindPattern;
            });
            done(jqFn.apply(element, jqArgs));
          } else {
            done(jqFn.apply(this.testDocument.find(selector), jqArgs));
          }
        });
      };
    })();
  }
  return futureJquery;
};
<|endoftext|>