<commit_before>/*
 * The main JavaScript file for the Spiffy UI framework
 */

spiffyui = {

    /*
     * These four functions are for showing different kinds of messages
     * in the general page UI.  They are accessor methods for implementations
     * in MessageUtil.java.  They are bound in that same class.
     */
    showFatalError: null,
    showError: null,
    showWarning: null,
    showMessage: null,

    autoloadCSS: true,
    autoloadHTML: true,

    /**
     * Gets a string of the date formatted into the short date
     * format in the current locale.
     */
    getDate: function(/*int*/ epoch) {
        var dateVal = new Date(epoch);
        return dateVal.toString(Date.CultureInfo.formatPatterns.shortDate);
    },

    /**
     * Gets a string of the date formatted into the long date
     * format in the current locale.
     */
    getLongDate: function(/*int*/ epoch) {
        var dateVal = new Date(epoch);
        return dateVal.toString(Date.CultureInfo.formatPatterns.longDate);
    },

    /**
     * Gets a string of the date formatted into the month day
     * format in the current locale. If abbrev = true, the use the
     * abbreviation for month.
     */
    getMonthDay: function(/*int*/ epoch, /*boolean*/ abbrev) {
        var dateVal = new Date(epoch);
        var dateFormat = Date.CultureInfo.formatPatterns.monthDay;
        if (abbrev) {
            dateFormat = dateFormat.replace("MMMM", "MMM");
        }
        return dateVal.toString(dateFormat);
    },

    /**
     * Gets a string of the time formatted into the short time
     * format in the current locale.
     */
    getShortTime: function(/*int*/ epoch) {
        var dateVal = new Date(epoch);
        return spiffyui.midnightWorkaround(dateVal.toString(Date.CultureInfo.formatPatterns.shortTime));
    },

    /**
     * Gets a string of the time at the hour or half hour or
     * rounded up to the nearest half hour
     * and formatted into the short time format in the current
     * locale.
     */
    getShortTimeRounded: function(/*int*/ epoch) {
        var dateVal = new Date(epoch);
        var min = dateVal.getMinutes();
        if (min > 0) {
	        if (min < 30) {
	            dateVal.setMinutes(30);
	        } else if (min > 30) {
	            dateVal.setMinutes(0);
	            dateVal.setHours(dateVal.getHours() + 1);
	        }
        }

        return spiffyui.midnightWorkaround(dateVal.toString(Date.CultureInfo.formatPatterns.shortTime));
    },

    /**
     * 12 AM is showing up as 0 AM, which is a bug in date.js, who is already aware of the problem.
     * http://groups.google.com/group/datejs/browse_thread/thread/2d4f5d46916920a6/5e2106f2f911ea93?lnk=gst&q=0+AM#5e2106f2f911ea93
     * Since we're still seeing the problem, applying hackito.
     */
    midnightWorkaround: function (/*String*/ formattedString) {
        if (formattedString.indexOf("0:") === 0 && formattedString.indexOf("AM") == 5) {
            formattedString = formattedString.substring(2);
            formattedString = "12:" + formattedString;
        }
        return formattedString;
    },

    /**
     * Gets a string of the date time formatted into the full date time
     * format in the current locale.
     */
    getDateTime: function(/*int*/ epoch) {
        var dateVal = new Date(epoch);
        return dateVal.toString(Date.CultureInfo.formatPatterns.fullDateTime);
    },

    /**
     * This is a helper function that gets a Date object from a time
     * string like 11:30pm.  This is just used in JSDateUtil and
     * shouldn't be used anywhere else.
     */
    getDateFromShortTime: function(/*string*/ formattedTime) {

         /*
            The date.js library has a bug where it gives the wrong
            24 hour value for 12AM and 12PM.  I've filed a bug report,
            but we still need to work aorund the issue.  Hackito
            ergo sum.
          */
         if (formattedTime === "12:00 PM") {
             formattedTime = "12:00 AM";
         } else if (formattedTime === "12:30 PM") {
             formattedTime = "12:30 AM";
         } else if (formattedTime === "12:00 AM") {
             formattedTime = "12:00 PM";
         } else if (formattedTime === "12:30 AM") {
             formattedTime = "12:30 PM";
         }

        /*
           We want to make the Date class parse our time, but it does
           like to parse time without the date so we put a bogus date
           in front of it because we are just interested in the hours
           and minutes.
         */
        var date = Date.parseExact(new Date().toString("yyyy-mm-dd") + " " + formattedTime,
                                   "yyyy-mm-dd " + Date.CultureInfo.formatPatterns.shortTime);
        return date;
    },
    /**
     * Gets a date that is set to the current date. The time is set to the start of the day (00:00 or 12:00 AM).
     */

    getToday: function() {
        return Date.today().getTime();
    },
    /**
     * Adds the 1 day to today.
     */
    nextDay: function() {
        return Date.today().add(1).days().getTime();
    },

    /**
     * Adds the specified number of units to the epochDate and returns the new epochDate
     */
    dateAdd: function(/*int*/ epochDate, /*int*/amt, /*String*/unit) {
        var date = new Date(epochDate);
        if (unit == "WEEK") {
            return date.addWeeks(amt).getTime();
        } else if (unit == "MONTH") {
            return date.addMonths(amt).getTime();
        } else if (unit == "HOUR") {
            return date.addHours(amt).getTime();
        } else if (unit == "MINUTE") {
            return date.addMinutes(amt).getTime();
        } else if (unit == "SECOND") {
            return date.addSeconds(amt).getTime();
        } else if (unit == "YEAR") {
            return date.addHours(amt).getTime();
        } else {
            return date.add(amt).days().getTime();
        }
    },
    /**
     * Gets the epoch string (milliseconds since 1970) from a date.
     */
    getEpoch: function(/*date string*/ formattedDate) {
        var epochObj = new Date(formattedDate);
        return epochObj.getTime();
    },

    /**
     * Format the ID for a JQuery selector.  This function adds a pound
     * sign to the beginning of the string if there isn't on already
     */
    formatId: function(/*string*/ id) {
         if (id.indexOf('#') === 0) {
             return id;
         } else {
             return '#' + id;
         }
    },

    init: function() {

        if (spiffyui.autoloadHTML) {

            /*
             * We start by adding the HTML tags our CSS depends on
             */
            jQuery('script:last').after(
                '

' +
                '
' +
                    '
' +
                        '

' +
                        '
' +
                            '

' +
                            '
' +
                                '

' +
                            '
' +
                            '

' +
                        '
' +
                        '

' +
                    '
' +
                '
' +
                '

');
        }

        if (spiffyui.autoloadCSS) {
            /*
             * Almost all of our CSS is in spiffyui.css, but there are always a few
             * tweaks you need to add for IE.  This special style sheet is added only
             * if the browser is IE and contains just those tweaks.
             */
            if (navigator.appName == 'Microsoft Internet Explorer') {
                jQuery("head").prepend("<link>");
                css = $("head").children(":first");
                css.attr({
                    rel:  "stylesheet",
                    type: "text/css",
                    href: "spiffyui.ie.css"
                });
            }

            /*
             * Now we add the spiffyui.min.css file.  If the URL ends with -debug.html
             * then we'll add the uncompressed version.  We add these files dynamically
             * so users of the framework have less to add to their page and because IE8
             * give precedence to files loaded in the page over those added with JavaScript
             * and we can't do that because we override styles in spiffyui.ie.css.
             */
            if (window.location.href.substr(-11) === "-debug.html") {
                jQuery("head").prepend("<link>");
                css = $("head").children(":first");
                css.attr({
                    rel:  "stylesheet",
                    type: "text/css",
                    href: "spiffyui.css"
                });
            } else {
                jQuery("head").prepend("<link>");
                css = $("head").children(":first");
                css.attr({
                    rel:  "stylesheet",
                    type: "text/css",
                    href: "spiffyui.min.css"
                });
            }
        }
    }

};

jQuery(document).ready(function() {
    spiffyui.init();
});
<commit_msg>We are now properly adding the HTML tags to the end of the body.<commit_after>/*
 * The main JavaScript file for the Spiffy UI framework
 */

spiffyui = {

    /*
     * These four functions are for showing different kinds of messages
     * in the general page UI.  They are accessor methods for implementations
     * in MessageUtil.java.  They are bound in that same class.
     */
    showFatalError: null,
    showError: null,
    showWarning: null,
    showMessage: null,

    autoloadCSS: true,
    autoloadHTML: true,

    /**
     * Gets a string of the date formatted into the short date
     * format in the current locale.
     */
    getDate: function(/*int*/ epoch) {
        var dateVal = new Date(epoch);
        return dateVal.toString(Date.CultureInfo.formatPatterns.shortDate);
    },

    /**
     * Gets a string of the date formatted into the long date
     * format in the current locale.
     */
    getLongDate: function(/*int*/ epoch) {
        var dateVal = new Date(epoch);
        return dateVal.toString(Date.CultureInfo.formatPatterns.longDate);
    },

    /**
     * Gets a string of the date formatted into the month day
     * format in the current locale. If abbrev = true, the use the
     * abbreviation for month.
     */
    getMonthDay: function(/*int*/ epoch, /*boolean*/ abbrev) {
        var dateVal = new Date(epoch);
        var dateFormat = Date.CultureInfo.formatPatterns.monthDay;
        if (abbrev) {
            dateFormat = dateFormat.replace("MMMM", "MMM");
        }
        return dateVal.toString(dateFormat);
    },

    /**
     * Gets a string of the time formatted into the short time
     * format in the current locale.
     */
    getShortTime: function(/*int*/ epoch) {
        var dateVal = new Date(epoch);
        return spiffyui.midnightWorkaround(dateVal.toString(Date.CultureInfo.formatPatterns.shortTime));
    },

    /**
     * Gets a string of the time at the hour or half hour or
     * rounded up to the nearest half hour
     * and formatted into the short time format in the current
     * locale.
     */
    getShortTimeRounded: function(/*int*/ epoch) {
        var dateVal = new Date(epoch);
        var min = dateVal.getMinutes();
        if (min > 0) {
	        if (min < 30) {
	            dateVal.setMinutes(30);
	        } else if (min > 30) {
	            dateVal.setMinutes(0);
	            dateVal.setHours(dateVal.getHours() + 1);
	        }
        }

        return spiffyui.midnightWorkaround(dateVal.toString(Date.CultureInfo.formatPatterns.shortTime));
    },

    /**
     * 12 AM is showing up as 0 AM, which is a bug in date.js, who is already aware of the problem.
     * http://groups.google.com/group/datejs/browse_thread/thread/2d4f5d46916920a6/5e2106f2f911ea93?lnk=gst&q=0+AM#5e2106f2f911ea93
     * Since we're still seeing the problem, applying hackito.
     */
    midnightWorkaround: function (/*String*/ formattedString) {
        if (formattedString.indexOf("0:") === 0 && formattedString.indexOf("AM") == 5) {
            formattedString = formattedString.substring(2);
            formattedString = "12:" + formattedString;
        }
        return formattedString;
    },

    /**
     * Gets a string of the date time formatted into the full date time
     * format in the current locale.
     */
    getDateTime: function(/*int*/ epoch) {
        var dateVal = new Date(epoch);
        return dateVal.toString(Date.CultureInfo.formatPatterns.fullDateTime);
    },

    /**
     * This is a helper function that gets a Date object from a time
     * string like 11:30pm.  This is just used in JSDateUtil and
     * shouldn't be used anywhere else.
     */
    getDateFromShortTime: function(/*string*/ formattedTime) {

         /*
            The date.js library has a bug where it gives the wrong
            24 hour value for 12AM and 12PM.  I've filed a bug report,
            but we still need to work aorund the issue.  Hackito
            ergo sum.
          */
         if (formattedTime === "12:00 PM") {
             formattedTime = "12:00 AM";
         } else if (formattedTime === "12:30 PM") {
             formattedTime = "12:30 AM";
         } else if (formattedTime === "12:00 AM") {
             formattedTime = "12:00 PM";
         } else if (formattedTime === "12:30 AM") {
             formattedTime = "12:30 PM";
         }

        /*
           We want to make the Date class parse our time, but it does
           like to parse time without the date so we put a bogus date
           in front of it because we are just interested in the hours
           and minutes.
         */
        var date = Date.parseExact(new Date().toString("yyyy-mm-dd") + " " + formattedTime,
                                   "yyyy-mm-dd " + Date.CultureInfo.formatPatterns.shortTime);
        return date;
    },
    /**
     * Gets a date that is set to the current date. The time is set to the start of the day (00:00 or 12:00 AM).
     */

    getToday: function() {
        return Date.today().getTime();
    },
    /**
     * Adds the 1 day to today.
     */
    nextDay: function() {
        return Date.today().add(1).days().getTime();
    },

    /**
     * Adds the specified number of units to the epochDate and returns the new epochDate
     */
    dateAdd: function(/*int*/ epochDate, /*int*/amt, /*String*/unit) {
        var date = new Date(epochDate);
        if (unit == "WEEK") {
            return date.addWeeks(amt).getTime();
        } else if (unit == "MONTH") {
            return date.addMonths(amt).getTime();
        } else if (unit == "HOUR") {
            return date.addHours(amt).getTime();
        } else if (unit == "MINUTE") {
            return date.addMinutes(amt).getTime();
        } else if (unit == "SECOND") {
            return date.addSeconds(amt).getTime();
        } else if (unit == "YEAR") {
            return date.addHours(amt).getTime();
        } else {
            return date.add(amt).days().getTime();
        }
    },
    /**
     * Gets the epoch string (milliseconds since 1970) from a date.
     */
    getEpoch: function(/*date string*/ formattedDate) {
        var epochObj = new Date(formattedDate);
        return epochObj.getTime();
    },

    /**
     * Format the ID for a JQuery selector.  This function adds a pound
     * sign to the beginning of the string if there isn't on already
     */
    formatId: function(/*string*/ id) {
         if (id.indexOf('#') === 0) {
             return id;
         } else {
             return '#' + id;
         }
    },

    init: function() {

        if (spiffyui.autoloadHTML) {

            /*
             * We start by adding the HTML tags our CSS depends on
             */
            jQuery('body').append(
                '

' +
                '
' +
                    '
' +
                        '

' +
                        '
' +
                            '

' +
                            '
' +
                                '

' +
                            '
' +
                            '

' +
                        '
' +
                        '

' +
                    '
' +
                '
' +
                '

');
        }

        if (spiffyui.autoloadCSS) {
            /*
             * Almost all of our CSS is in spiffyui.css, but there are always a few
             * tweaks you need to add for IE.  This special style sheet is added only
             * if the browser is IE and contains just those tweaks.
             */
            if (navigator.appName == 'Microsoft Internet Explorer') {
                jQuery("head").prepend("<link>");
                css = $("head").children(":first");
                css.attr({
                    rel:  "stylesheet",
                    type: "text/css",
                    href: "spiffyui.ie.css"
                });
            }

            /*
             * Now we add the spiffyui.min.css file.  If the URL ends with -debug.html
             * then we'll add the uncompressed version.  We add these files dynamically
             * so users of the framework have less to add to their page and because IE8
             * give precedence to files loaded in the page over those added with JavaScript
             * and we can't do that because we override styles in spiffyui.ie.css.
             */
            if (window.location.href.substr(-11) === "-debug.html") {
                jQuery("head").prepend("<link>");
                css = $("head").children(":first");
                css.attr({
                    rel:  "stylesheet",
                    type: "text/css",
                    href: "spiffyui.css"
                });
            } else {
                jQuery("head").prepend("<link>");
                css = $("head").children(":first");
                css.attr({
                    rel:  "stylesheet",
                    type: "text/css",
                    href: "spiffyui.min.css"
                });
            }
        }
    }

};

jQuery(document).ready(function() {
    spiffyui.init();
});
<|endoftext|>


<commit_before>Ext.require(['Ext.data.*', 'Ext.grid.*']);

Ext.Ajax.defaultHeaders = {
    'Accept': 'application/json'
};

Ext.onReady(function() {

	// ================================================================================
	// Keyspace
	// ================================================================================
    Ext.define('Keyspace', {
        extend: 'Ext.data.Model',
        fields: ['keyspace', 'columnFamily'],
        proxy: {
            type: 'rest',
            url: '/keyspaces'
        }
    });

    var keyspaces = Ext.create('Ext.data.Store', {
        model: 'Keyspace',
        autoLoad: true,
        sorters: ['keyspace', 'columnFamily'],
        groupField: 'keyspace',
    });

    var keyspaceGroupingFeature = Ext.create('Ext.grid.feature.Grouping', {
        groupHeaderTpl: '{name} ({rows.length})'
    });

    var keyspacesGrid = Ext.create('Ext.grid.Panel', {
        title: 'Keyspaces',
        region: 'west',
        xtype: 'gridpanel',
        width: 200,
        margins: '5 0 0 5',
        collapsible: true,
        // make collapsible
        id: 'west-region-container',
        layout: 'fit',
        store: keyspaces,
        sm: Ext.create('Ext.selection.RowModel').setSelectionMode('SINGLE'),
        features: [keyspaceGroupingFeature],
        columns: [{
            text: 'ColumnFamily',
            flex: 1,
            dataIndex: 'columnFamily'
        }],
        listeners: {
            itemclick: function(vie, record) {
				alert(record.raw["columnFamily"]);
                console.info(record.raw["columnFamily"]);
                console.info(record.raw["keyspace"]);
            }
        }
    });

	// ================================================================================
	// Column Family
	// ================================================================================
    Ext.define('ColumnFamily', {
        extend: 'Ext.data.Model',
        fields: ['row', 'column', 'value'],
        proxy: {
            type: 'rest',
            url: '/keyspaces/datastore/pets/'
        }
    });

    var columnFamily = Ext.create('Ext.data.Store', {
        model: 'ColumnFamily',
        autoLoad: true,
        sorters: ['row', 'column'],
        groupField: 'row',
    });

    var rowGroupingFeature = Ext.create('Ext.grid.feature.Grouping', {
        groupHeaderTpl: '{name} ({rows.length})'
    });

    var columnFamilyGrid = Ext.create('Ext.grid.Panel', {
        title: 'Column Family',
        region: 'center',
        xtype: 'gridpanel',
        margins: '5 5 0 0',
        collapsible: true,
        // make collapsible
        layout: 'fit',
        store: columnFamily,
        sm: Ext.create('Ext.selection.RowModel').setSelectionMode('SINGLE'),
        features: [rowGroupingFeature],
        columns: [{
            text: 'Column',
            flex: 1,
            dataIndex: 'column'
        },
        {
            text: 'Value',
			flex: 1,
            dataIndex: 'value'
        }]
    });

	// ================================================================================
	// Main Viewport
	// ================================================================================

    Ext.create('Ext.Viewport', {
        title: 'Border Layout',
        layout: 'border',
        fullscreen: true,
        items: [{
            title: 'CQL... Coming soon.',
            region: 'south',
            // position for region
            xtype: 'panel',
            height: 100,
            split: true,
            // enable resizing
            margins: '0 5 5 5'
        },
        keyspacesGrid,
        columnFamilyGrid],
        renderTo: Ext.getBody()
    });

});
<commit_msg>Now able to switch between column families.<commit_after>Ext.require(['Ext.data.*', 'Ext.grid.*']);

Ext.Ajax.defaultHeaders = {
    'Accept': 'application/json'
};

Ext.onReady(function() {

	// ================================================================================
	// Column Family
	// ================================================================================
    Ext.define('ColumnFamily', {
        extend: 'Ext.data.Model',
        fields: ['row', 'column', 'value'],
        proxy: {
            type: 'ajax',
            url: '/keyspaces/datastore/pets/'
        }
    });

    var columnFamily = Ext.create('Ext.data.Store', {
        model: 'ColumnFamily',
        autoLoad: true,
        sorters: ['row', 'column'],
        groupField: 'row',
    });

    var rowGroupingFeature = Ext.create('Ext.grid.feature.Grouping', {
        groupHeaderTpl: '{name} ({rows.length})'
    });

    var columnFamilyGrid = Ext.create('Ext.grid.Panel', {
        title: 'Column Family',
        region: 'center',
        xtype: 'gridpanel',
        margins: '5 5 0 0',
        collapsible: true,
        // make collapsible
        layout: 'fit',
        store: columnFamily,
        sm: Ext.create('Ext.selection.RowModel').setSelectionMode('SINGLE'),
        features: [rowGroupingFeature],
        columns: [{
            text: 'Column',
            flex: 1,
            dataIndex: 'column'
        },
        {
            text: 'Value',
			flex: 1,
            dataIndex: 'value'
        }]
    });

	// ================================================================================
	// Keyspace
	// ================================================================================
    Ext.define('Keyspace', {
        extend: 'Ext.data.Model',
        fields: ['keyspace', 'columnFamily'],
        proxy: {
            type: 'rest',
            url: '/keyspaces'
        }
    });

    var keyspaces = Ext.create('Ext.data.Store', {
        model: 'Keyspace',
        autoLoad: true,
        sorters: ['keyspace', 'columnFamily'],
        groupField: 'keyspace',
    });

    var keyspaceGroupingFeature = Ext.create('Ext.grid.feature.Grouping', {
        groupHeaderTpl: '{name} ({rows.length})'
    });

    var keyspacesGrid = Ext.create('Ext.grid.Panel', {
        title: 'Keyspaces',
        region: 'west',
        xtype: 'gridpanel',
        width: 200,
        margins: '5 0 0 5',
        collapsible: true,
        // make collapsible
        id: 'west-region-container',
        layout: 'fit',
        store: keyspaces,
        sm: Ext.create('Ext.selection.RowModel').setSelectionMode('SINGLE'),
        features: [keyspaceGroupingFeature],
        columns: [{
            text: 'ColumnFamily',
            flex: 1,
            dataIndex: 'columnFamily'
        }],
        listeners: {
            itemclick: function(vie, record) {
				cfUrl = "keyspaces/" + record.raw["keyspace"] + "/" + record.raw["columnFamily"] + "/"
                console.info("Fetching [" + cfUrl + "]");
				ColumnFamily.proxy.url = cfUrl;
				columnFamily.load();

            }
        }
    });

	// ================================================================================
	// Main Viewport
	// ================================================================================

    Ext.create('Ext.Viewport', {
        title: 'Border Layout',
        layout: 'border',
        fullscreen: true,
        items: [{
            title: 'CQL... Coming soon.',
            region: 'south',
            // position for region
            xtype: 'panel',
            height: 100,
            split: true,
            // enable resizing
            margins: '0 5 5 5'
        },
        keyspacesGrid,
        columnFamilyGrid],
        renderTo: Ext.getBody()
    });

});
<|endoftext|>


<commit_before>import installer from 'electron-installer-debian';
import path from 'path';
import pify from 'pify';

import { ensureFile } from '../../util/ensure-output';
import configFn from '../../util/config-fn';

function debianArch(nodeArch) {
  switch (nodeArch) {
    case 'ia32': return 'i386';
    case 'x64': return 'amd64';
    case 'armv7l': return 'armhf';
    case 'arm': return 'armel';
    default: return nodeArch;
  }
}

export default async (dir, appName, targetArch, forgeConfig, packageJSON) => { // eslint-disable-line
  const arch = debianArch(targetArch);
  const outPath = path.resolve(dir, '../make', `${packageJSON.name}_${packageJSON.version}_${arch}.deb`);

  await ensureFile(outPath);
  const debianDefaults = {
    arch,
    dest: path.dirname(outPath),
    src: dir,
  };
  const debianConfig = Object.assign({}, configFn(forgeConfig.electronInstallerDebian, targetArch), debianDefaults);

  await pify(installer)(debianConfig);
  return [outPath];
};
<commit_msg>feat(maker): declare deb maker support for darwin & linux platforms<commit_after>import installer from 'electron-installer-debian';
import path from 'path';
import pify from 'pify';

import { ensureFile } from '../../util/ensure-output';
import configFn from '../../util/config-fn';

function debianArch(nodeArch) {
  switch (nodeArch) {
    case 'ia32': return 'i386';
    case 'x64': return 'amd64';
    case 'armv7l': return 'armhf';
    case 'arm': return 'armel';
    default: return nodeArch;
  }
}

export const supportedPlatforms = [
  'darwin',
  'linux',
];

export default async (dir, appName, targetArch, forgeConfig, packageJSON) => { // eslint-disable-line
  const arch = debianArch(targetArch);
  const outPath = path.resolve(dir, '../make', `${packageJSON.name}_${packageJSON.version}_${arch}.deb`);

  await ensureFile(outPath);
  const debianDefaults = {
    arch,
    dest: path.dirname(outPath),
    src: dir,
  };
  const debianConfig = Object.assign({}, configFn(forgeConfig.electronInstallerDebian, targetArch), debianDefaults);

  await pify(installer)(debianConfig);
  return [outPath];
};
<|endoftext|>


<commit_before>var  Body = function (x, y, width, height, world) {
	var self = this;
	self.x 		= 	x;
	self.y 		= 	y;
	self.width 	= 	width;
	self.height	= 	height;

	self.widthInTiles = Math.floor(width / world.tileSize);
	self.heightInTiles = Math.floor(height / world.tileSize);

	self.xTile = Math.floor(self.x / world.tileSize);
	self.yTile = Math.floor(self.y / world.tileSize);

	self.rectColor = "#000";

	//must be set explicitly
	self.hasGravity		=	false;
	self.hasCollision	=	false;

	 self.resetTileWeights = function(){
		for(let i = 0; i < self.widthInTiles; i++){
			for(let j = 0; j < self.heightInTiles; j++){
				try{
					world.tiles[[self.xTile+i,self.yTile+j]].weight = 1;
				}catch(e){
					//TODO
						console.log(e.message);
				}
			}
		}
	}
	self.setPosition = function (x, y) {
		//reseting previous tile
		self.resetTileWeights();
		self.x = x;
		self.y = y;
		self.xTile = Math.floor(self.x / world.tileSize);
		self.yTile = Math.floor(self.y / world.tileSize);
	}

	self.sprites = [];
	self.currentSprite;

	self.removeFromWorld = function(){
		world.removeBuffer.push(self);
	}

	self.setCurrentSprite = function (index) {
		self.currentSprite = self.sprites[index];
	}

	self.isIntersect = function (otherBody, log) {
		//IMP: canvas is represented as being in the 4th Quadrant, so y is -ve
		if (log === true) {
			console.log(otherBody);
		}

		var xLeft 	= 	self.x;
		var yTop	=	-self.y;

		var xRight		= 	self.x + self.width;
		var yBottom		=	-(self.y + self.height);

		var otherBodyXLeft	=	otherBody.x;
		var otherBodyYTop	=	-otherBody.y;

		var otherBodyXRight		=	otherBody.x + otherBody.width;
		var otherBodyYBottom	=	-(otherBody.y + otherBody.height);

		if (xLeft > otherBodyXRight || otherBodyXLeft > xRight) {
			return false;
		}

		if (yBottom > otherBodyYTop || otherBodyYBottom > yTop) {
			return false;
		}

		return true;
	}

	self.getTransform = function () {
		return {
			x:	self.xTile,
			y:	self.yTile,
			height:	self.height,
			width:	self.width
		}
	}

	self.isMoving = false;
	self.destinationX = 0;
	self.destinationY = 0;

	self.stepX = 0;
	self.stepY = 0;

	self.speed = 1;

	self.destBody = null;
	self.path = [];

	self.pathFinder = (new Pathfinder(world)).findPath

	var nextTile = undefined;
	self.move = function(x, y){
		if(!self.isMoving){
			self.xTile = Math.floor(self.x / world.tileSize);
			self.yTile = Math.floor(self.y / world.tileSize);

			//handle edge cases #puns
			if(x < 0) x = 0;
			if(y < 0) x = 0;
			if(x >= world.widthInTiles) x = world.widthInTiles-1;
			if(y >= world.heightInTiles) y = world.heightInTiles-1;

			self.path = self.pathFinder(world.tiles[[self.xTile,self.yTile]],world.tiles[[x,y]]);
			self.destBody = new Body(x*world.tileSize, y*world.tileSize, world.tileSize, world.tileSize, world);
			self.isMoving = true;
		} else{
			if(self.path.length <= 0){
				self.isMoving = false;
				self.destBody = undefined;
				return;
			}
		}

		if(world.currentFrame % self.speed === 0){
			var nextTile = self.path.pop();
			if(nextTile === undefined) return;
			self.setPosition(nextTile.x*world.tileSize, nextTile.y*world.tileSize);
		}else{
			//interpolation
			if(self.x < self.path[self.path.length-1].x*world.tileSize){
				self.setPosition(self.x + world.tileSize/self.speed, self.y);
			}
			else if(self.x > self.path[self.path.length-1].x*world.tileSize){
				self.setPosition(self.x - world.tileSize/self.speed, self.y);
			}
			if(self.y < self.path[self.path.length-1].y*world.tileSize){
				self.setPosition(self.x, self.y + world.tileSize/self.speed);
			}
			else if(self.y > self.path[self.path.length-1].y*world.tileSize){
				self.setPosition(self.x, self.y - world.tileSize/self.speed);
			}
		}
	}
}
<commit_msg>fixed bug in interpolation when path length is zero<commit_after>var  Body = function (x, y, width, height, world) {
	var self = this;
	self.x 		= 	x;
	self.y 		= 	y;
	self.width 	= 	width;
	self.height	= 	height;

	self.widthInTiles = Math.floor(width / world.tileSize);
	self.heightInTiles = Math.floor(height / world.tileSize);

	self.xTile = Math.floor(self.x / world.tileSize);
	self.yTile = Math.floor(self.y / world.tileSize);

	self.rectColor = "#000";

	//must be set explicitly
	self.hasGravity		=	false;
	self.hasCollision	=	false;

	 self.resetTileWeights = function(){
		for(let i = 0; i < self.widthInTiles; i++){
			for(let j = 0; j < self.heightInTiles; j++){
				try{
					world.tiles[[self.xTile+i,self.yTile+j]].weight = 1;
				}catch(e){
					//TODO
						console.log(e.message);
				}
			}
		}
	}
	self.setPosition = function (x, y) {
		//reseting previous tile
		self.resetTileWeights();
		self.x = x;
		self.y = y;
		self.xTile = Math.floor(self.x / world.tileSize);
		self.yTile = Math.floor(self.y / world.tileSize);
	}

	self.sprites = [];
	self.currentSprite;

	self.removeFromWorld = function(){
		world.removeBuffer.push(self);
	}

	self.setCurrentSprite = function (index) {
		self.currentSprite = self.sprites[index];
	}

	self.isIntersect = function (otherBody, log) {
		//IMP: canvas is represented as being in the 4th Quadrant, so y is -ve
		if (log === true) {
			console.log(otherBody);
		}

		var xLeft 	= 	self.x;
		var yTop	=	-self.y;

		var xRight		= 	self.x + self.width;
		var yBottom		=	-(self.y + self.height);

		var otherBodyXLeft	=	otherBody.x;
		var otherBodyYTop	=	-otherBody.y;

		var otherBodyXRight		=	otherBody.x + otherBody.width;
		var otherBodyYBottom	=	-(otherBody.y + otherBody.height);

		if (xLeft > otherBodyXRight || otherBodyXLeft > xRight) {
			return false;
		}

		if (yBottom > otherBodyYTop || otherBodyYBottom > yTop) {
			return false;
		}

		return true;
	}

	self.getTransform = function () {
		return {
			x:	self.xTile,
			y:	self.yTile,
			height:	self.height,
			width:	self.width
		}
	}

	self.isMoving = false;
	self.destinationX = 0;
	self.destinationY = 0;

	self.stepX = 0;
	self.stepY = 0;

	self.speed = 1;

	self.destBody = null;
	self.path = [];

	self.pathFinder = (new Pathfinder(world)).findPath

	var nextTile = undefined;
	self.move = function(x, y){
		if(!self.isMoving){
			self.xTile = Math.floor(self.x / world.tileSize);
			self.yTile = Math.floor(self.y / world.tileSize);

			//handle edge cases #puns
			if(x < 0) x = 0;
			if(y < 0) x = 0;
			if(x >= world.widthInTiles) x = world.widthInTiles-1;
			if(y >= world.heightInTiles) y = world.heightInTiles-1;

			self.path = self.pathFinder(world.tiles[[self.xTile,self.yTile]],world.tiles[[x,y]]);
			self.destBody = new Body(x*world.tileSize, y*world.tileSize, world.tileSize, world.tileSize, world);
			self.isMoving = true;
		} else{
			if(self.path.length <= 0){
				self.isMoving = false;
				self.destBody = undefined;
				return;
			}
		}

		if(world.currentFrame % self.speed === 0){
			var nextTile = self.path.pop();
			if(nextTile === undefined) return;
			self.setPosition(nextTile.x*world.tileSize, nextTile.y*world.tileSize);
		}else{
			//interpolation
			if(self.path.length > 0){
				if(self.x < self.path[self.path.length-1].x*world.tileSize){
					self.setPosition(self.x + world.tileSize/self.speed, self.y);
				}
				else if(self.x > self.path[self.path.length-1].x*world.tileSize){
					self.setPosition(self.x - world.tileSize/self.speed, self.y);
				}
				if(self.y < self.path[self.path.length-1].y*world.tileSize){
					self.setPosition(self.x, self.y + world.tileSize/self.speed);
				}
				else if(self.y > self.path[self.path.length-1].y*world.tileSize){
					self.setPosition(self.x, self.y - world.tileSize/self.speed);
				}
			}
		}
	}
}
<|endoftext|>


<commit_before>;(function(window, define) {

  var boundVals = {};
  var ATTR_NAME = 'data-bond';

  var Bond = function(varName, initialValue) {

    if (boundVals[varName]) {
      console.warn('Bond: Duplicate name detected: ' + varName);
    }

    boundVals[varName] = (function() {
      var __val = null;
      var observers = [];

      var updateDOM = function(val) {
        observers.forEach(function(obs) {
          if (obs.tagName === 'INPUT') {
            obs.value = __val;
          } else {
            obs.innerHTML = __val;
          }
        });
      };

      var obj = {
        get: function() {
          return __val;
        },
        set: function(val) {
          __val = val;
          updateDOM();
        }
      };

      // Attach event listeners
      var elements = document.querySelectorAll('[' + ATTR_NAME + '="' + varName + '"]');
      for (var i = 0; i < elements.length; i++) {
        if (elements[i].tagName === 'INPUT') {
          elements[i].addEventListener('input', function(e) {
            obj.set(e.target.value);
          });
        }
        observers.push(elements[i]);
      }

      obj.set(initialValue);

      Object.freeze(obj);

      return obj;
    })();

    return boundVals[varName];
  };

  if (typeof define === 'function' && define.amd !== undefined) {
    define(function () {
      return Bond;
    });
  } else if (typeof module !== 'undefined' && module.exports) {
    module.exports = Bond;
  } else {
    window.Bond = Bond;
  }

})(this, this.define);

<commit_msg>Limit 'boundVals' use, add comments<commit_after>/*
 * Bond.js
 * Simple two-way data binding library for the browser
 *
 * Author: Thameera Senanayaka
 */

;(function(window, define) {

  var boundVals = {};
  var ATTR_NAME = 'data-bond';

  var Bond = function(varName, initialValue) {

    // Duplicate check
    if (boundVals[varName]) {
      console.warn('Bond: Duplicate name detected: ' + varName);
    }

    boundVals[varName] = 1;

    var newBond = (function() {
      var __val = null;
      var observers = [];

      // Updates all DOM elements bound to the current Bond
      var updateDOM = function(val) {
        observers.forEach(function(obs) {
          if (obs.tagName === 'INPUT') {
            obs.value = __val;
          } else {
            obs.innerHTML = __val;
          }
        });
      };

      // Bond object
      var obj = {
        get: function() {
          return __val;
        },
        set: function(val) {
          __val = val;
          updateDOM();
        }
      };

      // Find DOM elements bound to current bond ("observers")
      var elements = document.querySelectorAll('[' + ATTR_NAME + '="' + varName + '"]');
      for (var i = 0; i < elements.length; i++) {
        // Attach event listers to input elements
        if (elements[i].tagName === 'INPUT') {
          elements[i].addEventListener('input', function(e) {
            obj.set(e.target.value);
          });
        }
        observers.push(elements[i]);
      }

      // Set the optional initial value
      obj.set(initialValue);

      // Make the attributes unmodifiable
      Object.freeze(obj);

      return obj;
    })();

    return newBond;
  };

  // Expose to AMD, CommonJS or as a global
  if (typeof define === 'function' && define.amd !== undefined) {
    define(function () {
      return Bond;
    });
  } else if (typeof module !== 'undefined' && module.exports) {
    module.exports = Bond;
  } else {
    window.Bond = Bond;
  }

})(this, this.define);

<|endoftext|>


<commit_before>'use strict'

const fastq = require('fastq')
const EE = require('events').EventEmitter
const inherits = require('util').inherits
const Plugin = require('./plugin')

function wrap (server, opts, instance) {
  const expose = opts.expose || {}
  const useKey = expose.use || 'use'
  const afterKey = expose.after || 'after'
  const readyKey = expose.ready || 'ready'
  const onCloseKey = expose.onClose || 'onClose'
  const closeKey = expose.close || 'close'

  if (server[useKey]) {
    throw new Error(useKey + '() is already defined, specify an expose option')
  }

  if (server[afterKey]) {
    throw new Error(afterKey + '() is already defined, specify an expose option')
  }

  if (server[readyKey]) {
    throw new Error(readyKey + '() is already defined, specify an expose option')
  }

  server[useKey] = function (a, b, c) {
    instance.use(a, b, c)
    return this
  }

  server[afterKey] = function (func) {
    instance.after(encapsulateThreeParamServer(func, this, true))
    return this
  }

  server[readyKey] = function (func) {
    instance.ready(encapsulateThreeParamServer(func, this, true))
    return this
  }

  server[onCloseKey] = function (func) {
    instance.onClose(encapsulateTwoParamServer(func, this))
    return this
  }

  server[closeKey] = function (func) {
    instance.close(encapsulateThreeParamServer(func, this))
    return this
  }
}

function Boot (server, opts, done) {
  if (typeof server === 'function' && arguments.length === 1) {
    done = server
    opts = {}
    server = null
  }

  if (typeof opts === 'function') {
    done = opts
    opts = {}
  }

  opts = opts || {}

  if (!(this instanceof Boot)) {
    const instance = new Boot(server, opts, done)

    if (server) {
      wrap(server, opts, instance)
    }

    return instance
  }

  server = server || this

  this._server = server
  this._current = []
  this._error = null

  if (done) {
    this.once('start', done)
  }

  this._readyQ = fastq(this, callWithCbOrNextTick, 1)
  this._readyQ.pause()
  this._readyQ.drain = () => {
    this.emit('start')
  }

  this._closeQ = fastq(this, closeWithCbOrNextTick, 1)
  this._closeQ.pause()
  this._closeQ.drain = () => {
    this.emit('close')
  }
  this._thereIsCloseCb = false

  // we init, because we need to emit "start" if no use is called
  this._init()
}

inherits(Boot, EE)

// create the root node upon to hold each subsequent call to use()
// the root node is responsible for emitting 'start'
Boot.prototype._init = function () {
  if (this._current.length === 0) {
    const main = new Plugin(this, (s, opts, done) => {
      // we need to wait any call to use() to happen
      process.nextTick(done)
    }, {}, noop)
    Plugin.loadPlugin.call(this, main, (err) => {
      if (err) {
        this._error = err
        if (this._readyQ.length() === 0) {
          throw err
        }
      } else {
        this._readyQ.resume()
      }
    })
  }
}

// allows to override the instance of a server, given a plugin
Boot.prototype.override = function (server, func, opts) {
  return server
}

// load a plugin
Boot.prototype.use = function (plugin, opts, callback) {
  if (typeof opts === 'function') {
    callback = opts
    opts = null
  }

  if (typeof plugin === 'function') {
    this._addPlugin(plugin, opts, callback)
  } else if (Array.isArray(plugin)) {
    for (var i = 0; i < plugin.length; i++) {
      this._addPlugin(plugin[i], opts, callback)
    }
  } else {
    throw new Error('plugin must be a function')
  }

  return this
}

Boot.prototype._addPlugin = function (plugin, opts, callback) {
  if (typeof plugin !== 'function') {
    throw new Error('plugin must be a function')
  }
  opts = opts || {}
  callback = callback || null

  // we reinit, if use is called after emitting start once
  this._init()

  // we always add plugins to load at the current element
  const current = this._current[0]

  const obj = new Plugin(this, plugin, opts, callback)

  // we add the plugin to be loaded at the end of the current queue
  current.q.push(obj, (err) => {
    if (err) {
      this._error = err
    }
  })
}

Boot.prototype.after = function (func, cb) {
  this.use(_after.bind(this), cb)

  function _after (s, opts, done) {
    callWithCbOrNextTick.call(
      this,
      encapsulateThreeParamAvvio(func, this),
      done
    )
  }

  return this
}

Boot.prototype.onClose = function (func) {
  this._closeQ.unshift(
    encapsulateTwoParamAvvio(func, this),
    callback.bind(this)
  )

  function callback (err) {
    if (err) this._error = err
  }

  return this
}

Boot.prototype.close = function (func) {
  this._error = null
  if (func) {
    this._closeQ.push(encapsulateThreeParamAvvio(func, this))
    this._thereIsCloseCb = true
  }
  process.nextTick(this._closeQ.resume.bind(this._closeQ))
}

Boot.prototype.ready = function (func) {
  this._readyQ.push(encapsulateThreeParamAvvio(func, this))
  return this
}

function noop () {}

function callWithCbOrNextTick (func, cb, context) {
  var err = this._error

  // with this the error will appear just in the next after/ready callback
  this._error = null
  func(err, cb)
}

function closeWithCbOrNextTick (func, cb, context) {
  context = this._server
  if (this._closeQ.length() === 0 && this._thereIsCloseCb) {
    func(this._error, cb)
  } else {
    func(context, cb)
  }
}

function encapsulateTwoParamAvvio (func, that) {
  return _encapsulateTwoParam.bind(that)
  function _encapsulateTwoParam (context, cb) {
    if (func.length === 0 || func.length === 1) {
      func(this._server)
      process.nextTick(cb)
    } else {
      func(this._server, cb)
    }
  }
}

function encapsulateTwoParamServer (func, that) {
  return _encapsulateTwoParam.bind(that)
  function _encapsulateTwoParam (context, cb) {
    if (func.length === 0 || func.length === 1) {
      func(this)
      process.nextTick(cb)
    } else {
      func(this, cb)
    }
  }
}

function encapsulateThreeParamAvvio (func, that, useContext) {
  return _encapsulateThreeParam.bind(that)
  function _encapsulateThreeParam (err, cb) {
    if (func.length === 0 || func.length === 1) {
      func(err)
      process.nextTick(cb)
    } else if (func.length === 2) {
      func(err, cb)
    } else {
      func(err, this._server, cb)
    }
  }
}

function encapsulateThreeParamServer (func, that, useContext) {
  return _encapsulateThreeParam.bind(that)
  function _encapsulateThreeParam (err, cb) {
    if (func.length === 0 || func.length === 1) {
      func(err)
      process.nextTick(cb)
    } else if (func.length === 2) {
      func(err, cb)
    } else {
      func(err, this, cb)
    }
  }
}

module.exports = Boot
module.exports.express = function (app) {
  return Boot(app, {
    expose: {
      use: 'load'
    }
  })
}
<commit_msg>Provide encapsulation only if initialized with a server<commit_after>'use strict'

const fastq = require('fastq')
const EE = require('events').EventEmitter
const inherits = require('util').inherits
const Plugin = require('./plugin')

function wrap (server, opts, instance) {
  const expose = opts.expose || {}
  const useKey = expose.use || 'use'
  const afterKey = expose.after || 'after'
  const readyKey = expose.ready || 'ready'
  const onCloseKey = expose.onClose || 'onClose'
  const closeKey = expose.close || 'close'

  if (server[useKey]) {
    throw new Error(useKey + '() is already defined, specify an expose option')
  }

  if (server[afterKey]) {
    throw new Error(afterKey + '() is already defined, specify an expose option')
  }

  if (server[readyKey]) {
    throw new Error(readyKey + '() is already defined, specify an expose option')
  }

  server[useKey] = function (a, b, c) {
    instance.use(a, b, c)
    return this
  }

  server[afterKey] = function (func) {
    instance.after(encapsulateThreeParam(func, this))
    return this
  }

  server[readyKey] = function (func) {
    instance.ready(encapsulateThreeParam(func, this))
    return this
  }

  server[onCloseKey] = function (func) {
    instance.onClose(encapsulateTwoParam(func, this))
    return this
  }

  server[closeKey] = function (func) {
    instance.close(encapsulateThreeParam(func, this))
    return this
  }
}

function Boot (server, opts, done) {
  if (typeof server === 'function' && arguments.length === 1) {
    done = server
    opts = {}
    server = null
  }

  if (typeof opts === 'function') {
    done = opts
    opts = {}
  }

  opts = opts || {}

  if (!(this instanceof Boot)) {
    const instance = new Boot(server, opts, done)

    if (server) {
      wrap(server, opts, instance)
    }

    return instance
  }

  server = server || this

  this._server = server
  this._current = []
  this._error = null

  if (done) {
    this.once('start', done)
  }

  this._readyQ = fastq(this, callWithCbOrNextTick, 1)
  this._readyQ.pause()
  this._readyQ.drain = () => {
    this.emit('start')
  }

  this._closeQ = fastq(this, closeWithCbOrNextTick, 1)
  this._closeQ.pause()
  this._closeQ.drain = () => {
    this.emit('close')
  }
  this._thereIsCloseCb = false

  // we init, because we need to emit "start" if no use is called
  this._init()
}

inherits(Boot, EE)

// create the root node upon to hold each subsequent call to use()
// the root node is responsible for emitting 'start'
Boot.prototype._init = function () {
  if (this._current.length === 0) {
    const main = new Plugin(this, (s, opts, done) => {
      // we need to wait any call to use() to happen
      process.nextTick(done)
    }, {}, noop)
    Plugin.loadPlugin.call(this, main, (err) => {
      if (err) {
        this._error = err
        if (this._readyQ.length() === 0) {
          throw err
        }
      } else {
        this._readyQ.resume()
      }
    })
  }
}

// allows to override the instance of a server, given a plugin
Boot.prototype.override = function (server, func, opts) {
  return server
}

// load a plugin
Boot.prototype.use = function (plugin, opts, callback) {
  if (typeof opts === 'function') {
    callback = opts
    opts = null
  }

  if (typeof plugin === 'function') {
    this._addPlugin(plugin, opts, callback)
  } else if (Array.isArray(plugin)) {
    for (var i = 0; i < plugin.length; i++) {
      this._addPlugin(plugin[i], opts, callback)
    }
  } else {
    throw new Error('plugin must be a function')
  }

  return this
}

Boot.prototype._addPlugin = function (plugin, opts, callback) {
  if (typeof plugin !== 'function') {
    throw new Error('plugin must be a function')
  }
  opts = opts || {}
  callback = callback || null

  // we reinit, if use is called after emitting start once
  this._init()

  // we always add plugins to load at the current element
  const current = this._current[0]

  const obj = new Plugin(this, plugin, opts, callback)

  // we add the plugin to be loaded at the end of the current queue
  current.q.push(obj, (err) => {
    if (err) {
      this._error = err
    }
  })
}

Boot.prototype.after = function (func, cb) {
  this.use(_after.bind(this), cb)

  function _after (s, opts, done) {
    callWithCbOrNextTick.call(this, func, done)
  }

  return this
}

Boot.prototype.onClose = function (func) {
  this._closeQ.unshift(func, callback.bind(this))

  function callback (err) {
    if (err) this._error = err
  }

  return this
}

Boot.prototype.close = function (func) {
  this._error = null
  if (func) {
    this._closeQ.push(func)
    this._thereIsCloseCb = true
  }
  process.nextTick(this._closeQ.resume.bind(this._closeQ))
}

Boot.prototype.ready = function (func) {
  this._readyQ.push(func)
  return this
}

function noop () {}

function callWithCbOrNextTick (func, cb, context) {
  context = this._server
  var err = this._error

  // with this the error will appear just in the next after/ready callback
  this._error = null

  if (func.length === 0 || func.length === 1) {
    func(err)
    process.nextTick(cb)
  } else if (func.length === 2) {
    func(err, cb)
  } else {
    func(err, context, cb)
  }
}

function closeWithCbOrNextTick (func, cb, context) {
  context = this._server
  if (this._closeQ.length() === 0 && this._thereIsCloseCb) {
    if (func.length === 0 || func.length === 1) {
      func(this._error)
      process.nextTick(cb)
    } else if (func.length === 2) {
      func(this._error, cb)
    } else {
      func(this._error, context, cb)
    }
  } else {
    if (func.length === 0 || func.length === 1) {
      func(context)
      process.nextTick(cb)
    } else {
      func(context, cb)
    }
  }
}

function encapsulateTwoParam (func, that) {
  return _encapsulateTwoParam.bind(that)
  function _encapsulateTwoParam (context, cb) {
    if (func.length === 0 || func.length === 1) {
      func(this)
      process.nextTick(cb)
    } else {
      func(this, cb)
    }
  }
}

function encapsulateThreeParam (func, that, useContext) {
  return _encapsulateThreeParam.bind(that)
  function _encapsulateThreeParam (err, cb) {
    if (func.length === 0 || func.length === 1) {
      func(err)
      process.nextTick(cb)
    } else if (func.length === 2) {
      func(err, cb)
    } else {
      func(err, this, cb)
    }
  }
}

module.exports = Boot
module.exports.express = function (app) {
  return Boot(app, {
    expose: {
      use: 'load'
    }
  })
}
<|endoftext|>


<commit_before>var calculator = {};

calculator.roles = {
    "escort":{canbe:["escort", "townsupport", "randomtown", "any"], unique:false},
    "transporter":{canbe:["transporter", "townsupport", "randomtown", "any"], unique:false},
    "mayor":{canbe:["mayor", "townsupport", "randomtown", "any"], unique:true},
    "medium":{canbe:["medium", "townsupport", "randomtown", "any"], unique:false},
    "retributionist":{canbe:["retributionist", "townsupport", "randomtown", "any"], unique:true},
    "investigator":{canbe:["investigator", "towninvestigative", "randomtown", "any"], unique:false},
    "spy":{canbe:["spy", "towninvestigative", "randomtown", "any"], unique:false},
    "lookout":{canbe:["lookout", "towninvestigative", "randomtown", "any"], unique:false},
    "sheriff":{canbe:["sheriff", "towninvestigative", "randomtown", "any"], unique:false},
    "bodyguard":{canbe:["bodyguard", "townprotective", "randomtown", "any"], unique:false},
    "doctor":{canbe:["doctor", "townprotective", "randomtown", "any"], unique:false},
    "jailor":{canbe:["jailor", "townprotective", "randomtown", "any"], unique:true},
    "veteran":{canbe:["veteran", "townkilling", "randomtown", "any"], unique:false},
    "vigilante":{canbe:["vigilante", "townkilling", "randomtown", "any"], unique:false},
    "framer":{canbe:["framer", "mafiadeception", "randommafia", "any"], unique:false},
    "disguiser":{canbe:["disguiser", "mafiadeception", "randommafia", "any"], unique:false},
    "janitor":{canbe:["janitor", "mafiadeception", "randommafia", "any"], unique:false},
    "forger":{canbe:["forger", "mafiadeception", "randommafia", "any"], unique:false},
    "blackmailer":{canbe:["blackmailer", "mafiasupport", "randommafia", "any"], unique:false},
    "consigliere":{canbe:["consigliere", "mafiasupport", "randommafia", "any"], unique:false},
    "consort":{canbe:["consort", "mafiasupport", "randommafia", "any"],  unique:false},
    "godfather":{canbe:["godfather", "mafiakilling", "randommafia", "any"], unique:true},
    "mafioso":{canbe:["mafioso", "mafiakilling", "randommafia", "any"], unique:true},
    "arsonist":{canbe:["arsonist", "neutralkilling", "randomneutral", "any"], unique:false},
    "serialKiller":{canbe:["serialKiller", "neutralkilling", "randomneutral", "any"], unique:false},
    "werewolf":{canbe:["werewolf", "neutralkilling", "randomneutral", "any"], unique:true},
    "executioner":{canbe:["executioner", "neutralevil", "randomneutral", "any"], unique:false},
    "jester":{canbe:["jester", "neutralevil", "randomneutral", "any"], unique:false},
    "witch":{canbe:["witch", "neutralevil", "randomneutral", "any"], unique:false},
    "amnesiac":{canbe:["amnesiac", "neutralbenign", "randomneutral", "any"], unique:false},
    "survivor":{canbe:["survivor", "neutralbenign", "randomneutral", "any"], unique:false}

};

calculator.roleClasses = {
    "townKilling":["vigilante", "veteran", "jailor"],
    "townProtective":["doctor", "bodyguard"],
    "townSupport":["escort", "transporter", "mayor", "medium", "retributionist"],
    "townInvestigative":["sheriff", "investigator", "lookout", "spy"],
    "mafiaDeception":["framer", "forger", "disguiser", "janitor"],
    "mafiaSupport":["blackmailer", "consigliere", "consort"],
    "mafiaKilling":["godfather", "mafioso"],
    "neutralKilling":["werewolf", "arsonist", "serialkiller"],
    "neutralBenign":["amnesiac", "survivor"],
    "neutralEvil":["executioner", "jester", 'witch']
};

calculator.gameModes = {
	"classic":["sheriff", "doctor", "investigator", "jailor", "medium", "godfather",
	"framer", "executioner", "escort", "mafioso", "lookout", "serialkiller",
	"townkilling", "jester", "randomtown"],
	"ranked":["jailor", "towninvestigative", "towninvestigative", "townsupport",
	"townsupport", "townprotective", "townkilling", "randomtown", "godfather",
	"mafioso", "randommafia", "neutralkilling", "neutralevil", "neutralbenign",
	"any"],
	"custom":[]
};

calculator.setup = function() {
    l = [];
    for (i = 1; i < 16; i++) {
        l.push($("#" + i));
    }
    calculator.people = l;
}

calculator.run = function() {
    // remove all warnings
    this.clearWarnings();
    // reset the pool
// remove all verified rules from pool
// count claims against pool
// look for roles that extend into RT, and any
// highlight roles based on dnager
};

calculator.clearWarnings = function(){
	calculator.people.forEach(function(e){e.attr('class', '')});
};<commit_msg>function clean up<commit_after>var calculator = {};

calculator.roles = {
    "escort":{canbe:["escort", "townsupport", "randomtown", "any"], unique:false},
    "transporter":{canbe:["transporter", "townsupport", "randomtown", "any"], unique:false},
    "mayor":{canbe:["mayor", "townsupport", "randomtown", "any"], unique:true},
    "medium":{canbe:["medium", "townsupport", "randomtown", "any"], unique:false},
    "retributionist":{canbe:["retributionist", "townsupport", "randomtown", "any"], unique:true},
    "investigator":{canbe:["investigator", "towninvestigative", "randomtown", "any"], unique:false},
    "spy":{canbe:["spy", "towninvestigative", "randomtown", "any"], unique:false},
    "lookout":{canbe:["lookout", "towninvestigative", "randomtown", "any"], unique:false},
    "sheriff":{canbe:["sheriff", "towninvestigative", "randomtown", "any"], unique:false},
    "bodyguard":{canbe:["bodyguard", "townprotective", "randomtown", "any"], unique:false},
    "doctor":{canbe:["doctor", "townprotective", "randomtown", "any"], unique:false},
    "jailor":{canbe:["jailor", "townprotective", "randomtown", "any"], unique:true},
    "veteran":{canbe:["veteran", "townkilling", "randomtown", "any"], unique:false},
    "vigilante":{canbe:["vigilante", "townkilling", "randomtown", "any"], unique:false},
    "framer":{canbe:["framer", "mafiadeception", "randommafia", "any"], unique:false},
    "disguiser":{canbe:["disguiser", "mafiadeception", "randommafia", "any"], unique:false},
    "janitor":{canbe:["janitor", "mafiadeception", "randommafia", "any"], unique:false},
    "forger":{canbe:["forger", "mafiadeception", "randommafia", "any"], unique:false},
    "blackmailer":{canbe:["blackmailer", "mafiasupport", "randommafia", "any"], unique:false},
    "consigliere":{canbe:["consigliere", "mafiasupport", "randommafia", "any"], unique:false},
    "consort":{canbe:["consort", "mafiasupport", "randommafia", "any"],  unique:false},
    "godfather":{canbe:["godfather", "mafiakilling", "randommafia", "any"], unique:true},
    "mafioso":{canbe:["mafioso", "mafiakilling", "randommafia", "any"], unique:true},
    "arsonist":{canbe:["arsonist", "neutralkilling", "randomneutral", "any"], unique:false},
    "serialKiller":{canbe:["serialKiller", "neutralkilling", "randomneutral", "any"], unique:false},
    "werewolf":{canbe:["werewolf", "neutralkilling", "randomneutral", "any"], unique:true},
    "executioner":{canbe:["executioner", "neutralevil", "randomneutral", "any"], unique:false},
    "jester":{canbe:["jester", "neutralevil", "randomneutral", "any"], unique:false},
    "witch":{canbe:["witch", "neutralevil", "randomneutral", "any"], unique:false},
    "amnesiac":{canbe:["amnesiac", "neutralbenign", "randomneutral", "any"], unique:false},
    "survivor":{canbe:["survivor", "neutralbenign", "randomneutral", "any"], unique:false}

};

calculator.roleClasses = {
    "townKilling":["vigilante", "veteran", "jailor"],
    "townProtective":["doctor", "bodyguard"],
    "townSupport":["escort", "transporter", "mayor", "medium", "retributionist"],
    "townInvestigative":["sheriff", "investigator", "lookout", "spy"],
    "mafiaDeception":["framer", "forger", "disguiser", "janitor"],
    "mafiaSupport":["blackmailer", "consigliere", "consort"],
    "mafiaKilling":["godfather", "mafioso"],
    "neutralKilling":["werewolf", "arsonist", "serialkiller"],
    "neutralBenign":["amnesiac", "survivor"],
    "neutralEvil":["executioner", "jester", 'witch']
};

calculator.gameModes = {
	"classic":["sheriff", "doctor", "investigator", "jailor", "medium", "godfather",
	"framer", "executioner", "escort", "mafioso", "lookout", "serialkiller",
	"townkilling", "jester", "randomtown"],
	"ranked":["jailor", "towninvestigative", "towninvestigative", "townsupport",
	"townsupport", "townprotective", "townkilling", "randomtown", "godfather",
	"mafioso", "randommafia", "neutralkilling", "neutralevil", "neutralbenign",
	"any"],
	"custom":[]
};

calculator.setup = function() {
    l = [];
    for (i = 1; i < 16; i++) {
        l.push($("#" + i));
    }
    calculator.people = l;
}

calculator.run = function() {
    // remove all warnings
    this.clearWarnings();
    // reset the pool
// remove all verified rules from pool
// count claims against pool
// look for roles that extend into RT, and any
// highlight roles based on dnager
};

calculator.clearWarnings = function(){
	calculator.people.forEach(function(e){
        e.attr('class', '');
    });
};<|endoftext|>


<commit_before>(function(timbre) {
    "use strict";

    var timevalue = timbre.utils.timevalue;

    function Envelope(samplerate) {
        this.samplerate = samplerate || 44100;
        this.table  = [];
        this.level  = ZERO;
        this.status = StatusWait;
        this.curve  = "linear";
        this.step   = 1;
        this.releaseNode = null;
        this.loopNode    = null;
        this.emit = null;

        this._endLevel   = ZERO;
        this._initLevel  = ZERO;
        this._curveType  = CurveTypeLin;
        this._curveValue = 0;
        this._defaultCurveType = CurveTypeLin;
        this._table      = [];
        this._index      = 0;
        this._counter    = 0;
        this._grow   = 0;

        this._a2 = 0;
        this._b1 = 0;
        this._y1 = 0;
        this._y2 = 0;
    }

    var ZERO           = Envelope.ZERO = 1e-6;
    var CurveTypeStep  = Envelope.CurveTypeStep  = 0;
    var CurveTypeLin   = Envelope.CurveTypeLin   = 1;
    var CurveTypeExp   = Envelope.CurveTypeExp   = 2;
    var CurveTypeSin   = Envelope.CurveTypeSin   = 3;
    var CurveTypeWel   = Envelope.CurveTypeWel   = 4;
    var CurveTypeCurve = Envelope.CurveTypeCurve = 5;
    var CurveTypeSqr   = Envelope.CurveTypeSqr   = 6;
    var CurveTypeCub   = Envelope.CurveTypeCub   = 7;

    var StatusWait    = Envelope.StatusWait    = 0;
    var StatusGate    = Envelope.StatusGate    = 1;
    var StatusSustain = Envelope.StatusSustain = 2;
    var StatusRelease = Envelope.StatusRelease = 3;
    var StatusEnd     = Envelope.StatusEnd     = 4;

    var CurveTypeDict = {
        lin:CurveTypeLin, linear     :CurveTypeLin,
        exp:CurveTypeExp, exponential:CurveTypeExp,
        sin:CurveTypeSin, sine       :CurveTypeSin,
        wel:CurveTypeWel, welch      :CurveTypeWel,
        sqr:CurveTypeSqr, squared    :CurveTypeSqr,
        cub:CurveTypeCub, cubed      :CurveTypeCub
    };

    var $ = Envelope.prototype;

    $.clone = function() {
        var new_instance = new Envelope(this.samplerate);
        new_instance.setTable(this.table);
        new_instance.setCurve(this.curve);
        if (this.releaseNode !== null) {
            new_instance.setReleaseNode(this.releaseNode + 1);
        }
        if (this.loopNode !== null) {
            new_instance.setLoopNode(this.loopNode + 1);
        }
        return new_instance;
    };
    $.setTable = function(value) {
        if (Array.isArray(value)) {
            this.table = value;
            this._buildTable(value);
            this.level = this._initLevel;
        }
    };
    $.setCurve = function(value) {
        if (typeof value === "number")  {
            this._defaultCurveType = CurveTypeCurve;
            this._curveValue = value;
            this.curve = value;
        } else {
            this._defaultCurveType = CurveTypeDict[value] || null;
            this.curve = value;
        }
    };
    $.setReleaseNode = function(value) {
        if (typeof value === "number" && value > 0) {
            this.releaseNode = value - 1;
        }
    };
    $.setLoopNode = function(value) {
        if (typeof value === "number" && value > 0) {
            this.loopNode = value - 1;
        }
    };
    $.reset = function() {
        this.level = this._endLevel = this._initLevel;
        this._index   = 0;
        this._counter = 0;
        this._curveType  = CurveTypeStep;
        this._grow   = 0;
        this.status = StatusWait;
    };
    $.release = function() {
        this._counter = 0;
        this.status = StatusRelease;
    };
    $.getInfo = function(sustainTime) {
        var table = this._table;
        var i, imax;
        var totalDuration    = 0;
        var loopBeginTime    = Infinity;
        var releaseBeginTime = Infinity;
        var isEndlessLoop    = false;
        for (i = 0, imax = table.length; i < imax; ++i) {
            if (this.loopNode === i) {
                loopBeginTime = totalDuration;
            }
            if (this.releaseNode === i) {
                totalDuration += sustainTime;
                releaseBeginTime = totalDuration;
            }

            var items = table[i];
            if (Array.isArray(items)) {
                totalDuration += items[1];
            }
        }
        if (loopBeginTime !== Infinity && releaseBeginTime === Infinity) {
            totalDuration += sustainTime;
            isEndlessLoop = true;
        }

        return {
            totalDuration   : totalDuration,
            loopBeginTime   : loopBeginTime,
            releaseBeginTime: releaseBeginTime,
            isEndlessLoop   : isEndlessLoop
        };
    };
    $.next = function() {
        var n = this.step;
        var samplerate = this.samplerate;
        var status  = this.status;
        var index   = this._index;
        var table   = this._table;
        var endLevel = this._endLevel;
        var curveType   = this._curveType;
        var curveValue = this._curveValue;
        var defaultCurveType = this._defaultCurveType;
        var level   = this.level;
        var grow    = this._grow;
        var loopNode    = this.loopNode;
        var releaseNode = this.releaseNode;
        var counter = this._counter;
        var w, items, time;
        var a1;
        var a2 = this._a2;
        var b1 = this._b1;
        var y0;
        var y1 = this._y1;
        var y2 = this._y2;
        var emit = null;

        switch (status) {
        case StatusWait:
        case StatusEnd:
            break;
        case StatusGate:
        case StatusRelease:
            while (counter <= 0) {
                if (index >= table.length) {
                    if (status === StatusGate && loopNode !== null) {
                        index = loopNode;
                        continue;
                    }
                    status    = StatusEnd;
                    counter   = Infinity;
                    curveType = CurveTypeStep;
                    emit      = "ended";
                    continue;
                } else if (status === StatusGate && index === releaseNode) {
                    if (this.loopNode !== null && loopNode < releaseNode) {
                        index = loopNode;
                        continue;
                    }
                    status    = StatusSustain;
                    counter   = Infinity;
                    curveType = CurveTypeStep;
                    emit      = "sustained";
                    continue;
                }
                items = table[index++];

                endLevel = items[0];
                if (items[2] === null) {
                    curveType = defaultCurveType;
                } else {
                    curveType = items[2];
                }
                if (curveType === CurveTypeCurve) {
                    curveValue = items[3];
                    if (Math.abs(curveValue) < 0.001) {
                        curveType = CurveTypeLin;
                    }
                }

                time = items[1];

                counter = ((time * 0.001 * samplerate) / n)|0;
                if (counter < 1) {
                    counter = 1;
                }

                switch (curveType) {
                case CurveTypeStep:
                    level = endLevel;
                    break;
                case CurveTypeLin:
                    grow = (endLevel - level) / counter;
                    break;
                case CurveTypeExp:
                    grow = Math.pow(
                        endLevel / level, 1 / counter
                    );
                    break;
                case CurveTypeSin:
                    w = Math.PI / counter;
                    a2 = (endLevel + level) * 0.5;
                    b1 = 2 * Math.cos(w);
                    y1 = (endLevel - level) * 0.5;
                    y2 = y1 * Math.sin(Math.PI * 0.5 - w);
                    level = a2 - y1;
                    break;
                case CurveTypeWel:
                    w = (Math.PI * 0.5) / counter;
                    b1 = 2 * Math.cos(w);
                    if (endLevel >= level) {
                        a2 = level;
                        y1 = 0;
                        y2 = -Math.sin(w) * (endLevel - level);
                    } else {
                        a2 = endLevel;
                        y1 = level - endLevel;
                        y2 = Math.cos(w) * (level - endLevel);
                    }
                    level = a2 + y1;
                    break;
                case CurveTypeCurve:
                    a1 = (endLevel - level) / (1.0 - Math.exp(curveValue));
                    a2 = level + a1;
                    b1 = a1;
                    grow = Math.exp(curveValue / counter);
                    break;
                case CurveTypeSqr:
                    y1 = Math.sqrt(level);
                    y2 = Math.sqrt(endLevel);
                    grow = (y2 - y1) / counter;
                    break;
                case CurveTypeCub:
                    y1 = Math.pow(level   , 0.33333333);
                    y2 = Math.pow(endLevel, 0.33333333);
                    grow = (y2 - y1) / counter;
                    break;
                }
            }
            break;
        }

        switch (curveType) {
        case CurveTypeStep:
            level = endLevel;
            break;
        case CurveTypeLin:
            level += grow;
            break;
        case CurveTypeExp:
            level *= grow;
            break;
        case CurveTypeSin:
            y0 = b1 * y1 - y2;
            level = a2 - y0;
            y2  = y1;
            y1  = y0;
            break;
        case CurveTypeWel:
            y0 = b1 * y1 - y2;
            level = a2 + y0;
            y2  = y1;
            y1  = y0;
            break;
        case CurveTypeCurve:
            b1 *= grow;
            level = a2 - b1;
            break;
        case CurveTypeSqr:
            y1 += grow;
            level = y1 * y1;
            break;
        case CurveTypeCub:
            y1 += grow;
            level = y1 * y1 * y1;
            break;
        }
        this.level = level || ZERO;

        this.status = status;
        this.emit   = emit;

        this._index = index;
        this._grow  = grow;
        this._endLevel  = endLevel;
        this._curveType = curveType;
        this._counter   = counter - 1;
        this._a2 = a2;
        this._b1 = b1;
        this._y1 = y1;
        this._y2 = y2;

        return this.level;
    };
    $._buildTable = function(list) {
        if (list.length === 0) {
            this._initLevel = ZERO;
            this._table     = [];
            return;
        }

        this._initLevel = list[0] || ZERO;
        this._table     = [];

        var table = this._table;
        var level, time, curveType, curveValue;
        for (var i = 1, imax = list.length; i < imax; ++i) {
            level = list[i][0] || ZERO;
            time  = list[i][1];
            curveType = list[i][2];

            if (typeof time !== "number") {
                if (typeof time === "string") {
                    time = timevalue(time);
                } else {
                    time = 10;
                }
            }
            if (time < 10) {
                time = 10;
            }

            if (typeof curveType === "number") {
                curveValue = curveType;
                curveType  = CurveTypeCurve;
            } else {
                curveType  = CurveTypeDict[curveType] || null;
                curveValue = 0;
            }
            table.push([level, time, curveType, curveValue]);
        }
    };

    timbre.modules.Envelope = Envelope;

})(timbre);
<commit_msg>fix envelope.reset()<commit_after>(function(timbre) {
    "use strict";

    var timevalue = timbre.utils.timevalue;

    function Envelope(samplerate) {
        this.samplerate = samplerate || 44100;
        this.table  = [];
        this.level  = ZERO;
        this.status = StatusWait;
        this.curve  = "linear";
        this.step   = 1;
        this.releaseNode = null;
        this.loopNode    = null;
        this.emit = null;

        this._endLevel   = ZERO;
        this._initLevel  = ZERO;
        this._curveType  = CurveTypeLin;
        this._curveValue = 0;
        this._defaultCurveType = CurveTypeLin;
        this._table      = [];
        this._index      = 0;
        this._counter    = 0;
        this._grow   = 0;

        this._a2 = 0;
        this._b1 = 0;
        this._y1 = 0;
        this._y2 = 0;
    }

    var ZERO           = Envelope.ZERO = 1e-6;
    var CurveTypeStep  = Envelope.CurveTypeStep  = 0;
    var CurveTypeLin   = Envelope.CurveTypeLin   = 1;
    var CurveTypeExp   = Envelope.CurveTypeExp   = 2;
    var CurveTypeSin   = Envelope.CurveTypeSin   = 3;
    var CurveTypeWel   = Envelope.CurveTypeWel   = 4;
    var CurveTypeCurve = Envelope.CurveTypeCurve = 5;
    var CurveTypeSqr   = Envelope.CurveTypeSqr   = 6;
    var CurveTypeCub   = Envelope.CurveTypeCub   = 7;

    var StatusWait    = Envelope.StatusWait    = 0;
    var StatusGate    = Envelope.StatusGate    = 1;
    var StatusSustain = Envelope.StatusSustain = 2;
    var StatusRelease = Envelope.StatusRelease = 3;
    var StatusEnd     = Envelope.StatusEnd     = 4;

    var CurveTypeDict = {
        lin:CurveTypeLin, linear     :CurveTypeLin,
        exp:CurveTypeExp, exponential:CurveTypeExp,
        sin:CurveTypeSin, sine       :CurveTypeSin,
        wel:CurveTypeWel, welch      :CurveTypeWel,
        sqr:CurveTypeSqr, squared    :CurveTypeSqr,
        cub:CurveTypeCub, cubed      :CurveTypeCub
    };

    var $ = Envelope.prototype;

    $.clone = function() {
        var new_instance = new Envelope(this.samplerate);
        new_instance.setTable(this.table);
        new_instance.setCurve(this.curve);
        if (this.releaseNode !== null) {
            new_instance.setReleaseNode(this.releaseNode + 1);
        }
        if (this.loopNode !== null) {
            new_instance.setLoopNode(this.loopNode + 1);
        }
        return new_instance;
    };
    $.setTable = function(value) {
        if (Array.isArray(value)) {
            this.table = value;
            this._buildTable(value);
            this.level = this._initLevel;
        }
    };
    $.setCurve = function(value) {
        if (typeof value === "number")  {
            this._defaultCurveType = CurveTypeCurve;
            this._curveValue = value;
            this.curve = value;
        } else {
            this._defaultCurveType = CurveTypeDict[value] || null;
            this.curve = value;
        }
    };
    $.setReleaseNode = function(value) {
        if (typeof value === "number" && value > 0) {
            this.releaseNode = value - 1;
        }
    };
    $.setLoopNode = function(value) {
        if (typeof value === "number" && value > 0) {
            this.loopNode = value - 1;
        }
    };
    $.reset = function() {
        this._index   = 0;
        this._counter = 0;
        this._curveType  = CurveTypeStep;
        this._grow   = 0;
        this.status = StatusWait;
    };
    $.release = function() {
        this._counter = 0;
        this.status = StatusRelease;
    };
    $.getInfo = function(sustainTime) {
        var table = this._table;
        var i, imax;
        var totalDuration    = 0;
        var loopBeginTime    = Infinity;
        var releaseBeginTime = Infinity;
        var isEndlessLoop    = false;
        for (i = 0, imax = table.length; i < imax; ++i) {
            if (this.loopNode === i) {
                loopBeginTime = totalDuration;
            }
            if (this.releaseNode === i) {
                totalDuration += sustainTime;
                releaseBeginTime = totalDuration;
            }

            var items = table[i];
            if (Array.isArray(items)) {
                totalDuration += items[1];
            }
        }
        if (loopBeginTime !== Infinity && releaseBeginTime === Infinity) {
            totalDuration += sustainTime;
            isEndlessLoop = true;
        }

        return {
            totalDuration   : totalDuration,
            loopBeginTime   : loopBeginTime,
            releaseBeginTime: releaseBeginTime,
            isEndlessLoop   : isEndlessLoop
        };
    };
    $.next = function() {
        var n = this.step;
        var samplerate = this.samplerate;
        var status  = this.status;
        var index   = this._index;
        var table   = this._table;
        var endLevel = this._endLevel;
        var curveType   = this._curveType;
        var curveValue = this._curveValue;
        var defaultCurveType = this._defaultCurveType;
        var level   = this.level;
        var grow    = this._grow;
        var loopNode    = this.loopNode;
        var releaseNode = this.releaseNode;
        var counter = this._counter;
        var w, items, time;
        var a1;
        var a2 = this._a2;
        var b1 = this._b1;
        var y0;
        var y1 = this._y1;
        var y2 = this._y2;
        var emit = null;

        switch (status) {
        case StatusWait:
        case StatusEnd:
            break;
        case StatusGate:
        case StatusRelease:
            while (counter <= 0) {
                if (index >= table.length) {
                    if (status === StatusGate && loopNode !== null) {
                        index = loopNode;
                        continue;
                    }
                    status    = StatusEnd;
                    counter   = Infinity;
                    curveType = CurveTypeStep;
                    emit      = "ended";
                    continue;
                } else if (status === StatusGate && index === releaseNode) {
                    if (this.loopNode !== null && loopNode < releaseNode) {
                        index = loopNode;
                        continue;
                    }
                    status    = StatusSustain;
                    counter   = Infinity;
                    curveType = CurveTypeStep;
                    emit      = "sustained";
                    continue;
                }
                items = table[index++];

                endLevel = items[0];
                if (items[2] === null) {
                    curveType = defaultCurveType;
                } else {
                    curveType = items[2];
                }
                if (curveType === CurveTypeCurve) {
                    curveValue = items[3];
                    if (Math.abs(curveValue) < 0.001) {
                        curveType = CurveTypeLin;
                    }
                }

                time = items[1];

                counter = ((time * 0.001 * samplerate) / n)|0;
                if (counter < 1) {
                    counter = 1;
                }

                switch (curveType) {
                case CurveTypeStep:
                    level = endLevel;
                    break;
                case CurveTypeLin:
                    grow = (endLevel - level) / counter;
                    break;
                case CurveTypeExp:
                    grow = Math.pow(
                        endLevel / level, 1 / counter
                    );
                    break;
                case CurveTypeSin:
                    w = Math.PI / counter;
                    a2 = (endLevel + level) * 0.5;
                    b1 = 2 * Math.cos(w);
                    y1 = (endLevel - level) * 0.5;
                    y2 = y1 * Math.sin(Math.PI * 0.5 - w);
                    level = a2 - y1;
                    break;
                case CurveTypeWel:
                    w = (Math.PI * 0.5) / counter;
                    b1 = 2 * Math.cos(w);
                    if (endLevel >= level) {
                        a2 = level;
                        y1 = 0;
                        y2 = -Math.sin(w) * (endLevel - level);
                    } else {
                        a2 = endLevel;
                        y1 = level - endLevel;
                        y2 = Math.cos(w) * (level - endLevel);
                    }
                    level = a2 + y1;
                    break;
                case CurveTypeCurve:
                    a1 = (endLevel - level) / (1.0 - Math.exp(curveValue));
                    a2 = level + a1;
                    b1 = a1;
                    grow = Math.exp(curveValue / counter);
                    break;
                case CurveTypeSqr:
                    y1 = Math.sqrt(level);
                    y2 = Math.sqrt(endLevel);
                    grow = (y2 - y1) / counter;
                    break;
                case CurveTypeCub:
                    y1 = Math.pow(level   , 0.33333333);
                    y2 = Math.pow(endLevel, 0.33333333);
                    grow = (y2 - y1) / counter;
                    break;
                }
            }
            break;
        }

        switch (curveType) {
        case CurveTypeStep:
            level = endLevel;
            break;
        case CurveTypeLin:
            level += grow;
            break;
        case CurveTypeExp:
            level *= grow;
            break;
        case CurveTypeSin:
            y0 = b1 * y1 - y2;
            level = a2 - y0;
            y2  = y1;
            y1  = y0;
            break;
        case CurveTypeWel:
            y0 = b1 * y1 - y2;
            level = a2 + y0;
            y2  = y1;
            y1  = y0;
            break;
        case CurveTypeCurve:
            b1 *= grow;
            level = a2 - b1;
            break;
        case CurveTypeSqr:
            y1 += grow;
            level = y1 * y1;
            break;
        case CurveTypeCub:
            y1 += grow;
            level = y1 * y1 * y1;
            break;
        }
        this.level = level || ZERO;

        this.status = status;
        this.emit   = emit;

        this._index = index;
        this._grow  = grow;
        this._endLevel  = endLevel;
        this._curveType = curveType;
        this._counter   = counter - 1;
        this._a2 = a2;
        this._b1 = b1;
        this._y1 = y1;
        this._y2 = y2;

        return this.level;
    };
    $._buildTable = function(list) {
        if (list.length === 0) {
            this._initLevel = ZERO;
            this._table     = [];
            return;
        }

        this._initLevel = list[0] || ZERO;
        this._table     = [];

        var table = this._table;
        var level, time, curveType, curveValue;
        for (var i = 1, imax = list.length; i < imax; ++i) {
            level = list[i][0] || ZERO;
            time  = list[i][1];
            curveType = list[i][2];

            if (typeof time !== "number") {
                if (typeof time === "string") {
                    time = timevalue(time);
                } else {
                    time = 10;
                }
            }
            if (time < 10) {
                time = 10;
            }

            if (typeof curveType === "number") {
                curveValue = curveType;
                curveType  = CurveTypeCurve;
            } else {
                curveType  = CurveTypeDict[curveType] || null;
                curveValue = 0;
            }
            table.push([level, time, curveType, curveValue]);
        }
    };

    timbre.modules.Envelope = Envelope;

})(timbre);
<|endoftext|>


<commit_before>//variable for the groups of chosenDojo selector
var group_code = [];
//Initial value for region
region='AK'
//main function
function main() {
    $('#tabs').tabs();
    google.load('visualization', '1', {packages: ['geochart']});
    google.setOnLoadCallback(googleReady(region));
    var commodities_select=[];
    dojo.ready(chosenDojo);
}

//Function to launch the googleAPI
function googleReady(region) {
    init_import_export();
    init_hscodes();
    worldMap(region);
    usaMap();
}

//Function to configure options of chosen-dojo commodities selector and fill in the data to select dynamically
function chosenDojo() {
        //Text to display when hovering the languages in map
        for(var i=0; i<commodities.hscodes.length; ++i) {
            //If it is a group code
            if (commodities.hscodes[i].code == 0) {
                group_code.push('<optgroup label= \u0022' + commodities.hscodes[i].group + ' ' + commodities.hscodes[i].commodity +'\u0022>');
            }
            //If it is a two digit code
            else {
                //if (commodities.hscodes[i].code == 2) {
                    //We set the groups
                    var group = parseInt(commodities.hscodes[i].group.substring(0,2))
                    //Group 1
                    if (group<6) {
                        var text = group_code[0] + '<option>' + commodities.hscodes[i].group + ' ' + commodities.hscodes[i].commodity + '<option>'
                        group_code[0]=text
                    }
                  //Group 2
                    if (group>5 && group <16) {
                        var text = group_code[1] + '<option>' + commodities.hscodes[i].group + ' ' + commodities.hscodes[i].commodity + '<option>'
                        group_code[1]=text
                    }
                    //Group 3
                    if (group>15 && group <25) {
                        var text = group_code[2] + '<option>' + commodities.hscodes[i].group + ' ' + commodities.hscodes[i].commodity + '<option>'
                        group_code[2]=text
                    }
                    //Group 4
                    if (group>24 && group <28) {
                        var text = group_code[3] + '<option>' + commodities.hscodes[i].group + ' ' + commodities.hscodes[i].commodity + '<option>'
                        group_code[3]=text
                    }
                    //Group 5
                    if (group>27 && group <39) {
                        var text = group_code[4] + '<option>' + commodities.hscodes[i].group + ' ' + commodities.hscodes[i].commodity + '<option>'
                        group_code[4]=text
                    }
                    //Group 6
                    if (group>38 && group <40) {
                        var text = group_code[5] + '<option>' + commodities.hscodes[i].group + ' ' + commodities.hscodes[i].commodity + '<option>'
                        group_code[5]=text
                    }
                    //Group 7
                    if (group>39 && group <44) {
                        var text = group_code[6] + '<option>' + commodities.hscodes[i].group + ' ' + commodities.hscodes[i].commodity + '<option>'
                        group_code[6]=text
                    }
                    //Group 8
                    if (group>43 && group <50) {
                        var text = group_code[7] + '<option>' + commodities.hscodes[i].group + ' ' + commodities.hscodes[i].commodity + '<option>'
                        group_code[7]=text
                    }
                    //Group 9
                    if (group>49 && group <64) {
                        var text = group_code[8] + '<option>' + commodities.hscodes[i].group + ' ' + commodities.hscodes[i].commodity + '<option>'
                        group_code[8]=text
                    }
                    //Group 10
                    if (group>63 && group <68) {
                        var text = group_code[9] + '<option>' + commodities.hscodes[i].group + ' ' + commodities.hscodes[i].commodity + '<option>'
                        group_code[9]=text
                    }
                    //Group 11
                    if (group>67 && group <72) {
                        var text = group_code[10] + '<option>' + commodities.hscodes[i].group + ' ' + commodities.hscodes[i].commodity + '<option>'
                        group_code[10]=text
                    }
                    //Group 12
                    if (group>71 && group <84) {
                        var text = group_code[11] + '<option>' + commodities.hscodes[i].group + ' ' + commodities.hscodes[i].commodity + '<option>'
                        group_code[11]=text
                    }
                    //Group 13
                    if (group>83 && group <86) {
                        var text = group_code[12] + '<option>' + commodities.hscodes[i].group + ' ' + commodities.hscodes[i].commodity + '<option>'
                        group_code[12]=text
                    }
                    //Group 14
                    if (group>85 && group <90) {
                        var text = group_code[13] + '<option>' + commodities.hscodes[i].group + ' ' + commodities.hscodes[i].commodity + '<option>'
                        group_code[13]=text
                    }
                    //Group 15
                    if (group>89 && group <98) {
                        var text = group_code[14] + '<option>' + commodities.hscodes[i].group + ' ' + commodities.hscodes[i].commodity + '<option>'
                        group_code[14]=text
                    }
                    //Group 16
                    if (group>97 && group <100) {
                        var text = group_code[15] + '<option>' + commodities.hscodes[i].group + ' ' + commodities.hscodes[i].commodity + '<option>'
                        group_code[15]=text
                    }
                //}
            }
        }
        //console.log(group_code);
        var contentString = '

Commodities<select id="select"  data-placeholder="Search or select individual or group commodities" style="width:475px;" class="chzn-select-batch" multiple tabindex="6"><option value=""></option>'+ group_code[0] +  group_code[1] + group_code[2] +  group_code[3] + group_code[4] +  group_code[5] + group_code[6] +  group_code[7] + group_code[8] +  group_code[9] + group_code[10] +  group_code[11] + group_code[12] +  group_code[13] + group_code[14] +  group_code[15] +'</optgroup></select>

';
        select = dojo.byId('commodities_selector');
        select.innerHTML = contentString;

        //Chosen-dojo options
        dojo.query(".chzn-select").chosen();
        dojo.query(".chzn-select-deselect").chosen({allow_single_deselect:true});
        dojo.query(".chzn-select-batch").chosen({batch_select:true});

        //Management of the selection
        $('select').on('change', function(event) {
        var select_object = dojo.byId('select');
        var select_div = dojo.byId('msg');
        var selected_values = [];
        for (var x=0; x<=select_object.length; x++) {
            if (select_object[x] && select_object[x].selected) {
                selected_values.push(select_object[x].value);
            }
        }
        select_div.innerHTML = 'Selected value = ' + selected_values;
        console.log(selected_values);
        });
    }

$(main);
<commit_msg>Change Alberto's code in pair programming<commit_after>//variable for the groups of chosenDojo selector
var group_code = [];
//Initial value for region
region='AK'
//main function
function main() {
    $('#tabs').tabs();
    google.load('visualization', '1', {packages: ['geochart']});
    google.setOnLoadCallback(googleReady(region));
    var commodities_select=[];
    dojo.ready(chosenDojo);
}

//Function to launch the googleAPI
function googleReady(region) {
    init_import_export();
    init_hscodes();
    worldMap(region);
    usaMap();
}

//Function to configure options of chosen-dojo commodities selector and fill in the data to select dynamically
function chosenDojo() {
        //Text to display when hovering the languages in map
        for(var i=0; i<commodities.hscodes.length; ++i) {
            //If it is a group code
            if (commodities.hscodes[i].code == 0) {
                group_code.push('<optgroup label= \u0022' + commodities.hscodes[i].group + ' ' + commodities.hscodes[i].commodity +'\u0022>');
            } else {
                //If it is a two digit code
                var group = parseInt(commodities.hscodes[i].group.substring(0,2))
                var g;
                if (group<6) g = 0;
                else if (group>5 && group <16) g = 1;
                else if (group>15 && group <25) g = 2;
                else if (group>24 && group <28) g = 3;
                else if (group>27 && group <39) g = 4;
                else if (group>38 && group <40) g = 5;
                else if (group>39 && group <44) g = 6;
                else if (group>43 && group <50) g = 7;
                else if (group>49 && group <64) g = 8;
                else if (group>63 && group <68) g = 9;
                else if (group>67 && group <72) g = 10;
                else if (group>71 && group <84) g = 11;
                else if (group>83 && group <86) g = 12;
                else if (group>85 && group <90) g = 13;
                else if (group>89 && group <98) g = 14;
                else if (group>97) g = 15;
                group_code[g] = group_code[g] + '<option>' + commodities.hscodes[i].group + ' ' + commodities.hscodes[i].commodity + '<option>';
            }
        }
        //console.log(group_code);
        var contentString = '

Commodities<select id="select"  data-placeholder="Search or select individual or group commodities" style="width:475px;" class="chzn-select-batch" multiple tabindex="6"><option value=""></option>'+ group_code[0] +  group_code[1] + group_code[2] +  group_code[3] + group_code[4] +  group_code[5] + group_code[6] +  group_code[7] + group_code[8] +  group_code[9] + group_code[10] +  group_code[11] + group_code[12] +  group_code[13] + group_code[14] +  group_code[15] +'</optgroup></select>

';
        select = dojo.byId('commodities_selector');
        select.innerHTML = contentString;

        //Chosen-dojo options
        dojo.query(".chzn-select").chosen();
        dojo.query(".chzn-select-deselect").chosen({allow_single_deselect:true});
        dojo.query(".chzn-select-batch").chosen({batch_select:true});

        //Management of the selection
        $('select').on('change', function(event) {
        var select_object = dojo.byId('select');
        var select_div = dojo.byId('msg');
        var selected_values = [];
        for (var x=0; x<=select_object.length; x++) {
            if (select_object[x] && select_object[x].selected) {
                selected_values.push(select_object[x].value);
            }
        }
        select_div.innerHTML = 'Selected value = ' + selected_values;
        console.log(selected_values);
        });
    }

$(main);
<|endoftext|>