<commit_before>/* Based on ext-lang-en.js from ext4 with trlKwf() calls added where appropriate */
Ext4.onReady(function() {

    if (Ext4.data && Ext4.data.Types) {
        Ext4.data.Types.stripRe = /[\$,%]/g;
    }

    if (Ext4.Date) {
        Ext4.Date.monthNames = [
            trlKwf("January"),
            trlKwf("February"),
            trlKwf("March"),
            trlKwf("April"),
            trlKwf("May"),
            trlKwf("June"),
            trlKwf("July"),
            trlKwf("August"),
            trlKwf("September"),
            trlKwf("October"),
            trlKwf("November"),
            trlKwf("December")
        ];

        Ext4.Date.getShortMonthName = function(month) {
            return Ext4.Date.monthNames[month].substring(0, 3);
        };

        Ext4.Date.monthNumbers = {
            Jan: 0,
            Feb: 1,
            Mar: 2,
            Apr: 3,
            May: 4,
            Jun: 5,
            Jul: 6,
            Aug: 7,
            Sep: 8,
            Oct: 9,
            Nov: 10,
            Dec: 11
        };

        Ext4.Date.getMonthNumber = function(name) {
            return Ext4.Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()];
        };

        Ext4.Date.dayNames = [
            trlKwf("Sunday"),
            trlKwf("Monday"),
            trlKwf("Tuesday"),
            trlKwf("Wednesday"),
            trlKwf("Thursday"),
            trlKwf("Friday"),
            trlKwf("Saturday")
        ];

        Ext4.Date.getShortDayName = function(day) {
            return Ext4.Date.dayNames[day].substring(0, 3);
        };

        Ext4.Date.parseCodes.S.s = "(?:st|nd|rd|th)";
    }

    if (Ext4.util && Ext4.util.Format) {
        Ext4.apply(Ext4.util.Format, {
            thousandSeparator: '', //shitty trl parser doesn't eat that: trlcKwf('thousands separator', ","),
            decimalSeparator: trlcKwf('decimal separator', "."),
            currencySign: '€', //currencySign in trl, really?
            dateFormat: trlKwf('Y-m-d')
        });
    }
});

Ext4.define("Ext.locale.en.view.View", {
    override: "Ext.view.View",
    emptyText: ""
});

Ext4.define("Ext.locale.en.grid.plugin.DragDrop", {
    override: "Ext.grid.plugin.DragDrop",
    dragText: trlKwf("{0} selected row{1}")
});

// changing the msg text below will affect the LoadMask
Ext4.define("Ext.locale.en.view.AbstractView", {
    override: "Ext.view.AbstractView",
    loadingText: trlKwf("Loading...")
});

Ext4.define("Ext.locale.en.picker.Date", {
    override: "Ext.picker.Date",
    todayText: trlKwf("Today"),
    minText: trlKwf("This date is before the minimum date"),
    maxText: trlKwf("This date is after the maximum date"),
    disabledDaysText: "",
    disabledDatesText: "",
    nextText: trlKwf('Next Month (Control+Right)'),
    prevText: trlKwf('Previous Month (Control+Left)'),
    monthYearText: trlKwf('Choose a month (Control+Up/Down to move years)'),
    todayTip: trlKwf("{0} (Spacebar)"),
    format: trlKwf("m/d/y"),
    startDay: parseInt(trlcKwf('start day of week', '0'))
});

Ext4.define("Ext.locale.en.picker.Month", {
    override: "Ext.picker.Month",
    okText: " "+trlKwf('OK')+" ",
    cancelText: trlKwf("Cancel")
});

Ext4.define("Ext.locale.en.toolbar.Paging", {
    override: "Ext.PagingToolbar",
    beforePageText: trlKwf("Page"),
    afterPageText: trlKwf("of {0}"),
    firstText: trlKwf("First Page"),
    prevText: trlKwf("Previous Page"),
    nextText: trlKwf("Next Page"),
    lastText: trlKwf("Last Page"),
    refreshText: trlKwf("Refresh"),
    displayMsg: trlKwf("Displaying {0} - {1} of {2}"),
    emptyMsg: trlKwf('No data to display')
});

Ext4.define("Ext.locale.en.form.Basic", {
    override: "Ext.form.Basic",
    waitTitle: trlKwf("Please Wait...")
});

Ext4.define("Ext.locale.en.form.field.Base", {
    override: "Ext.form.field.Base",
    invalidText: trlKwf("The value in this field is invalid")
});

Ext4.define("Ext.locale.en.form.field.Text", {
    override: "Ext.form.field.Text",
    minLengthText: trlKwf("The minimum length for this field is {0}"),
    maxLengthText: trlKwf("The maximum length for this field is {0}"),
    blankText: trlKwf("This field is required"),
    regexText: "",
    emptyText: null
});

Ext4.define("Ext.locale.en.form.field.Number", {
    override: "Ext.form.field.Number",
    decimalSeparator: trlcKwf('decimal separator', "."),
    decimalPrecision: 2,
    minText: trlKwf("The minimum value for this field is {0}"),
    maxText: trlKwf("The maximum value for this field is {0}"),
    nanText: trlKwf("{0} is not a valid number")
});

Ext4.define("Ext.locale.en.form.field.Date", {
    override: "Ext.form.field.Date",
    disabledDaysText: trlKwf("Disabled"),
    disabledDatesText: trlKwf("Disabled"),
    minText: trlKwf("The date in this field must be after {0}"),
    maxText: trlKwf("The date in this field must be before {0}"),
    invalidText: trlKwf("{0} is not a valid date - it must be in the format {1}"),
    format: trlKwf("Y-m-d"),
    altFormats: "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d"
});

Ext4.define("Ext.locale.en.form.field.ComboBox", {
    override: "Ext.form.field.ComboBox",
    valueNotFoundText: undefined
}, function() {
    Ext4.apply(Ext4.form.field.ComboBox.prototype.defaultListConfig, {
        loadingText: trlKwf("Loading...")
    });
});

Ext4.define("Ext.locale.en.form.field.VTypes", {
    override: "Ext.form.field.VTypes",
    emailText: trlKwf('This field should be an e-mail address in the format "user@example.com"'),
    urlText: trlKwf('This field should be a URL in the format "http:/' + '/www.example.com"'),
    alphaText: trlKwf('This field should only contain letters and _'),
    alphanumText: trlKwf('This field should only contain letters, numbers and _')
});

Ext4.define("Ext.locale.en.form.field.HtmlEditor", {
    override: "Ext.form.field.HtmlEditor",
    createLinkText: trlKwf('Please enter the URL for the link:')
}, function() {
    Ext4.apply(Ext4.form.field.HtmlEditor.prototype, {
        buttonTips: {
            bold: {
                title: trlKwf('Bold (Ctrl+B)'),
                text: trlKwf('Make the selected text bold.'),
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            italic: {
                title: trlKwf('Italic (Ctrl+I)'),
                text: trlKwf('Make the selected text italic.'),
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            underline: {
                title: trlKwf('Underline (Ctrl+U)'),
                text: trlKwf('Underline the selected text.'),
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            /*
            increasefontsize: {
                title: 'Grow Text'),
                text: 'Increase the font size.',
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            decreasefontsize: {
                title: 'Shrink Text',
                text: 'Decrease the font size.',
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            backcolor: {
                title: 'Text Highlight Color',
                text: 'Change the background color of the selected text.',
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            forecolor: {
                title: 'Font Color',
                text: 'Change the color of the selected text.',
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            justifyleft: {
                title: 'Align Text Left',
                text: 'Align text to the left.',
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            justifycenter: {
                title: 'Center Text',
                text: 'Center text in the editor.',
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            justifyright: {
                title: 'Align Text Right',
                text: 'Align text to the right.',
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            */
            insertunorderedlist: {
                title: trlKwf('Bullet List'),
                text: trlKwf('Start a bulleted list.'),
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            insertorderedlist: {
                title: trlKwf('Numbered List'),
                text: trlKwf('Start a numbered list.'),
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            createlink: {
                title: trlKwf('Hyperlink'),
                text: trlKwf('Make the selected text a hyperlink.'),
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            sourceedit: {
                title: trlKwf('Source Edit'),
                text: trlKwf('Switch to source editing mode.'),
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            }
        }
    });
});

Ext4.define("Ext.locale.en.grid.header.Container", {
    override: "Ext.grid.header.Container",
    sortAscText: trlKwf("Sort Ascending"),
    sortDescText: trlKwf("Sort Descending"),
    columnsText: trlKwf("Columns")
});

Ext4.define("Ext.locale.en.grid.GroupingFeature", {
    override: "Ext.grid.GroupingFeature",
    emptyGroupText: trlKwf('(None)'),
    groupByText: trlKwf('Group By This Field'),
    showGroupsText: trlKwf('Show in Groups')
});

Ext4.define("Ext.locale.en.grid.PropertyColumnModel", {
    override: "Ext.grid.PropertyColumnModel",
    nameText: trlKwf("Name"),
    valueText: trlKwf("Value"),
    dateFormat: trlKwf("Y-m-d"),
    trueText: trlKwf("true"),
    falseText: trlKwf("false")
});

Ext4.define("Ext.locale.en.grid.BooleanColumn", {
    override: "Ext.grid.BooleanColumn",
    trueText: trlKwf("true"),
    falseText: trlKwf("false"),
    undefinedText: ' '
});

Ext4.define("Ext.locale.en.grid.NumberColumn", {
    override: "Ext.grid.NumberColumn",
    format: trlKwf('0,000.00')
});

Ext4.define("Ext.locale.en.grid.DateColumn", {
    override: "Ext.grid.DateColumn",
    format: trlKwf('Y-m-d')
});

Ext4.define("Ext.locale.en.form.field.Time", {
    override: "Ext.form.field.Time",
    minText: trlKwf("The time in this field must be equal to or after {0}"),
    maxText: trlKwf("The time in this field must be equal to or before {0}"),
    invalidText: trlKwf("{0} is not a valid time"),
    format: trlKwf("H:i"),
    altFormats: "g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H"
});

Ext4.define("Ext.locale.en.form.CheckboxGroup", {
    override: "Ext.form.CheckboxGroup",
    blankText: trlKwf("You must select at least one item in this group")
});

Ext4.define("Ext.locale.en.form.RadioGroup", {
    override: "Ext.form.RadioGroup",
    blankText: trlKwf("You must select one item in this group")
});

Ext4.define("Ext.locale.en.window.MessageBox", {
    override: "Ext.window.MessageBox",
    buttonText: {
        ok: trlKwf("OK"),
        cancel: trlKwf("Cancel"),
        yes: trlKwf("Yes"),
        no: trlKwf("No")
    }
});

// This is needed until we can refactor all of the locales into individual files
Ext4.define("Ext.locale.en.Component", {
    override: "Ext.Component"
});

<commit_msg>Ext4 trl: translate startDay for Date field<commit_after>/* Based on ext-lang-en.js from ext4 with trlKwf() calls added where appropriate */
Ext4.onReady(function() {

    if (Ext4.data && Ext4.data.Types) {
        Ext4.data.Types.stripRe = /[\$,%]/g;
    }

    if (Ext4.Date) {
        Ext4.Date.monthNames = [
            trlKwf("January"),
            trlKwf("February"),
            trlKwf("March"),
            trlKwf("April"),
            trlKwf("May"),
            trlKwf("June"),
            trlKwf("July"),
            trlKwf("August"),
            trlKwf("September"),
            trlKwf("October"),
            trlKwf("November"),
            trlKwf("December")
        ];

        Ext4.Date.getShortMonthName = function(month) {
            return Ext4.Date.monthNames[month].substring(0, 3);
        };

        Ext4.Date.monthNumbers = {
            Jan: 0,
            Feb: 1,
            Mar: 2,
            Apr: 3,
            May: 4,
            Jun: 5,
            Jul: 6,
            Aug: 7,
            Sep: 8,
            Oct: 9,
            Nov: 10,
            Dec: 11
        };

        Ext4.Date.getMonthNumber = function(name) {
            return Ext4.Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()];
        };

        Ext4.Date.dayNames = [
            trlKwf("Sunday"),
            trlKwf("Monday"),
            trlKwf("Tuesday"),
            trlKwf("Wednesday"),
            trlKwf("Thursday"),
            trlKwf("Friday"),
            trlKwf("Saturday")
        ];

        Ext4.Date.getShortDayName = function(day) {
            return Ext4.Date.dayNames[day].substring(0, 3);
        };

        Ext4.Date.parseCodes.S.s = "(?:st|nd|rd|th)";
    }

    if (Ext4.util && Ext4.util.Format) {
        Ext4.apply(Ext4.util.Format, {
            thousandSeparator: '', //shitty trl parser doesn't eat that: trlcKwf('thousands separator', ","),
            decimalSeparator: trlcKwf('decimal separator', "."),
            currencySign: '€', //currencySign in trl, really?
            dateFormat: trlKwf('Y-m-d')
        });
    }
});

Ext4.define("Ext.locale.en.view.View", {
    override: "Ext.view.View",
    emptyText: ""
});

Ext4.define("Ext.locale.en.grid.plugin.DragDrop", {
    override: "Ext.grid.plugin.DragDrop",
    dragText: trlKwf("{0} selected row{1}")
});

// changing the msg text below will affect the LoadMask
Ext4.define("Ext.locale.en.view.AbstractView", {
    override: "Ext.view.AbstractView",
    loadingText: trlKwf("Loading...")
});

Ext4.define("Ext.locale.en.picker.Date", {
    override: "Ext.picker.Date",
    todayText: trlKwf("Today"),
    minText: trlKwf("This date is before the minimum date"),
    maxText: trlKwf("This date is after the maximum date"),
    disabledDaysText: "",
    disabledDatesText: "",
    nextText: trlKwf('Next Month (Control+Right)'),
    prevText: trlKwf('Previous Month (Control+Left)'),
    monthYearText: trlKwf('Choose a month (Control+Up/Down to move years)'),
    todayTip: trlKwf("{0} (Spacebar)"),
    format: trlKwf("m/d/y"),
    startDay: parseInt(trlcKwf('start day of week', '0'))
});

Ext4.define("Ext.locale.en.picker.Month", {
    override: "Ext.picker.Month",
    okText: " "+trlKwf('OK')+" ",
    cancelText: trlKwf("Cancel")
});

Ext4.define("Ext.locale.en.toolbar.Paging", {
    override: "Ext.PagingToolbar",
    beforePageText: trlKwf("Page"),
    afterPageText: trlKwf("of {0}"),
    firstText: trlKwf("First Page"),
    prevText: trlKwf("Previous Page"),
    nextText: trlKwf("Next Page"),
    lastText: trlKwf("Last Page"),
    refreshText: trlKwf("Refresh"),
    displayMsg: trlKwf("Displaying {0} - {1} of {2}"),
    emptyMsg: trlKwf('No data to display')
});

Ext4.define("Ext.locale.en.form.Basic", {
    override: "Ext.form.Basic",
    waitTitle: trlKwf("Please Wait...")
});

Ext4.define("Ext.locale.en.form.field.Base", {
    override: "Ext.form.field.Base",
    invalidText: trlKwf("The value in this field is invalid")
});

Ext4.define("Ext.locale.en.form.field.Text", {
    override: "Ext.form.field.Text",
    minLengthText: trlKwf("The minimum length for this field is {0}"),
    maxLengthText: trlKwf("The maximum length for this field is {0}"),
    blankText: trlKwf("This field is required"),
    regexText: "",
    emptyText: null
});

Ext4.define("Ext.locale.en.form.field.Number", {
    override: "Ext.form.field.Number",
    decimalSeparator: trlcKwf('decimal separator', "."),
    decimalPrecision: 2,
    minText: trlKwf("The minimum value for this field is {0}"),
    maxText: trlKwf("The maximum value for this field is {0}"),
    nanText: trlKwf("{0} is not a valid number")
});

Ext4.define("Ext.locale.en.form.field.Date", {
    override: "Ext.form.field.Date",
    disabledDaysText: trlKwf("Disabled"),
    disabledDatesText: trlKwf("Disabled"),
    minText: trlKwf("The date in this field must be after {0}"),
    maxText: trlKwf("The date in this field must be before {0}"),
    invalidText: trlKwf("{0} is not a valid date - it must be in the format {1}"),
    format: trlKwf("Y-m-d"),
    altFormats: "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d",
    startDay: parseInt(trlcKwf('start day of week', '0'))
});

Ext4.define("Ext.locale.en.form.field.ComboBox", {
    override: "Ext.form.field.ComboBox",
    valueNotFoundText: undefined
}, function() {
    Ext4.apply(Ext4.form.field.ComboBox.prototype.defaultListConfig, {
        loadingText: trlKwf("Loading...")
    });
});

Ext4.define("Ext.locale.en.form.field.VTypes", {
    override: "Ext.form.field.VTypes",
    emailText: trlKwf('This field should be an e-mail address in the format "user@example.com"'),
    urlText: trlKwf('This field should be a URL in the format "http:/' + '/www.example.com"'),
    alphaText: trlKwf('This field should only contain letters and _'),
    alphanumText: trlKwf('This field should only contain letters, numbers and _')
});

Ext4.define("Ext.locale.en.form.field.HtmlEditor", {
    override: "Ext.form.field.HtmlEditor",
    createLinkText: trlKwf('Please enter the URL for the link:')
}, function() {
    Ext4.apply(Ext4.form.field.HtmlEditor.prototype, {
        buttonTips: {
            bold: {
                title: trlKwf('Bold (Ctrl+B)'),
                text: trlKwf('Make the selected text bold.'),
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            italic: {
                title: trlKwf('Italic (Ctrl+I)'),
                text: trlKwf('Make the selected text italic.'),
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            underline: {
                title: trlKwf('Underline (Ctrl+U)'),
                text: trlKwf('Underline the selected text.'),
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            /*
            increasefontsize: {
                title: 'Grow Text'),
                text: 'Increase the font size.',
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            decreasefontsize: {
                title: 'Shrink Text',
                text: 'Decrease the font size.',
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            backcolor: {
                title: 'Text Highlight Color',
                text: 'Change the background color of the selected text.',
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            forecolor: {
                title: 'Font Color',
                text: 'Change the color of the selected text.',
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            justifyleft: {
                title: 'Align Text Left',
                text: 'Align text to the left.',
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            justifycenter: {
                title: 'Center Text',
                text: 'Center text in the editor.',
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            justifyright: {
                title: 'Align Text Right',
                text: 'Align text to the right.',
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            */
            insertunorderedlist: {
                title: trlKwf('Bullet List'),
                text: trlKwf('Start a bulleted list.'),
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            insertorderedlist: {
                title: trlKwf('Numbered List'),
                text: trlKwf('Start a numbered list.'),
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            createlink: {
                title: trlKwf('Hyperlink'),
                text: trlKwf('Make the selected text a hyperlink.'),
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            },
            sourceedit: {
                title: trlKwf('Source Edit'),
                text: trlKwf('Switch to source editing mode.'),
                cls: Ext4.baseCSSPrefix + 'html-editor-tip'
            }
        }
    });
});

Ext4.define("Ext.locale.en.grid.header.Container", {
    override: "Ext.grid.header.Container",
    sortAscText: trlKwf("Sort Ascending"),
    sortDescText: trlKwf("Sort Descending"),
    columnsText: trlKwf("Columns")
});

Ext4.define("Ext.locale.en.grid.GroupingFeature", {
    override: "Ext.grid.GroupingFeature",
    emptyGroupText: trlKwf('(None)'),
    groupByText: trlKwf('Group By This Field'),
    showGroupsText: trlKwf('Show in Groups')
});

Ext4.define("Ext.locale.en.grid.PropertyColumnModel", {
    override: "Ext.grid.PropertyColumnModel",
    nameText: trlKwf("Name"),
    valueText: trlKwf("Value"),
    dateFormat: trlKwf("Y-m-d"),
    trueText: trlKwf("true"),
    falseText: trlKwf("false")
});

Ext4.define("Ext.locale.en.grid.BooleanColumn", {
    override: "Ext.grid.BooleanColumn",
    trueText: trlKwf("true"),
    falseText: trlKwf("false"),
    undefinedText: ' '
});

Ext4.define("Ext.locale.en.grid.NumberColumn", {
    override: "Ext.grid.NumberColumn",
    format: trlKwf('0,000.00')
});

Ext4.define("Ext.locale.en.grid.DateColumn", {
    override: "Ext.grid.DateColumn",
    format: trlKwf('Y-m-d')
});

Ext4.define("Ext.locale.en.form.field.Time", {
    override: "Ext.form.field.Time",
    minText: trlKwf("The time in this field must be equal to or after {0}"),
    maxText: trlKwf("The time in this field must be equal to or before {0}"),
    invalidText: trlKwf("{0} is not a valid time"),
    format: trlKwf("H:i"),
    altFormats: "g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H"
});

Ext4.define("Ext.locale.en.form.CheckboxGroup", {
    override: "Ext.form.CheckboxGroup",
    blankText: trlKwf("You must select at least one item in this group")
});

Ext4.define("Ext.locale.en.form.RadioGroup", {
    override: "Ext.form.RadioGroup",
    blankText: trlKwf("You must select one item in this group")
});

Ext4.define("Ext.locale.en.window.MessageBox", {
    override: "Ext.window.MessageBox",
    buttonText: {
        ok: trlKwf("OK"),
        cancel: trlKwf("Cancel"),
        yes: trlKwf("Yes"),
        no: trlKwf("No")
    }
});

// This is needed until we can refactor all of the locales into individual files
Ext4.define("Ext.locale.en.Component", {
    override: "Ext.Component"
});

<|endoftext|>


<commit_before>/**
 * Created by Robert Butterworth on 8/9/2014.
 */

SEQUENCE = function() {

    this.SequenceTime = 0; //Actual time of the Sequence.
    this.SequenceLength = 15*FPS;
    this.Version = 1;
    this.Events = [];
    this.Play = true;

    var previousTime = new Date().getTime();

    this.GetSequenceTime = function()
    {
        return this.SequenceTime;
    };

    this.SetSequenceTime = function(time)
    {
        timer = time;
        this.SequenceTime = time;
    }

    this.ClearSequence = function()
    {
        ClearLights();
        this.Events = [];
    }

    this.GetSequenceLength = function()
    {
        return this.SequenceLength;
    };

    this.RenderFrame = function(frame, returnFrame)
    {
        var x;

        ClearLights();

        //Render Background
        for(x = 0; x < this.Events.length; x++)
        {
            if((this.Events[x].StartTime <= frame)&&
               (this.Events[x].Brush.Duration + this.Events[x].StartTime > frame))
            {
                if(this.Events[x].IsBackground == true) {
                    this.Events[x].Render(frame - this.Events[x].StartTime);
                }
            }
        }
        //Render Foreground
        for(x = 0; x < this.Events.length; x++)
        {
            if((this.Events[x].StartTime <= this.SequenceTime)&&
               (this.Events[x].Brush.Duration + this.Events[x].StartTime > frame))
            {
                if(this.Events[x].IsBackground == false) {
                    this.Events[x].Render(frame- this.Events[x].StartTime);
                }
            }
        }

        //Create Stream
        if(returnFrame == true)
        {
            var binaryFrame = "";

            for (var i = 0; i < 260; i++) {

                var color = new THREE.Color();

                var lightIndex = DomeLightOrder[i];

                color = DomeLightManager.Lights[lightIndex].color;

                binaryFrame += color.getHexString();
                // binaryFrame += String.fromCharCode( color.r );
                // binaryFrame += String.fromCharCode( color.g );
                // binaryFrame += String.fromCharCode( color.b );
            }

            return binaryFrame;
        }
    };

    this.RenderSequence = function(JSONSequenceConstructionFile)
    {
        var BinarySequenceStream = "";

        this.LoadSequence(JSONSequenceConstructionFile);

        if(this.Events.length < 1)
        {
            console.log("--- No Events in Sequence to Render ---");
            return undefined;
        }

        for (var i = 0; i < this.SequenceLength; i++) {
            this.SequenceTime = i;
            BinarySequenceStream += this.RenderFrame(i,true);
        }

        console.log("--- Stream Rendered ---");

        return BinarySequenceStream;
    };

    this.AddEvent = function(event)
    {
        //We need to sort this on addition based on time as we could be adding in an event at any point in time.
        //eg. During playback of other events.
        this.Events.push(event);

        //Now we've added another event, sort to ensure they are in the correct order
        this.Events.sort(function(a,b){
            return a.StartTime - b.StartTime;
        });
    };

    this.RemoveEvent = function(atIndex)
    {
        this.Events.remove(atIndex);
    };

    this.Update = function()
    {
        if(this.Play == true)
        {
            timer += 0.8; //getFrameDelta();
            if (timer > this.SequenceLength) timer = 0.0;

            this.SequenceTime = Math.floor(timer);
        }
    };

    function getFrameDelta()
    {
        var frameDelta = 0;

        var currentTime = new Date().getTime();
        var delta = currentTime - previousTime;
        previousTime = currentTime;

        //console.log(delta);
        frameDelta = delta / (1000/FPS);

        return frameDelta;
    }

    //Used to load Objects with the right types
    function RebuildBrushData(Data)
    {
      var CleanData = [];

      if( Data ) {
	      for(var x =0; x < Object.keys(Data).length; x++)
	      {
	          if(Data[x].r != undefined && Data[x].g != undefined && Data[x].b != undefined)
	              CleanData[x] = new THREE.Color(Data[x].r,Data[x].g,Data[x].b);
	          else
	              CleanData[x] = Data[x];
	      }
      }
      return CleanData;
    }

    this.SaveSequence = function()
    {
        this.SequenceConstructionFile = {};
        this.SequenceConstructionFile.Events = [];

        //Set Sequence Properties
        this.SequenceConstructionFile.Version = this.Version;
        this.SequenceConstructionFile.SequenceLength = this.SequenceLength;

        //Add all the Events
        for(var index = 0; index < this.Events.length; index++) {

            var SequenceConstructionEvent = {};

            SequenceConstructionEvent.StartTime = this.Events[index].StartTime;
            SequenceConstructionEvent.OriginLight = this.Events[index].OriginLight;
            SequenceConstructionEvent.BrushID = this.Events[index].Brush.Index;
            SequenceConstructionEvent.BrushData = this.Events[index].BrushData;

            this.SequenceConstructionFile.Events.push(SequenceConstructionEvent);
        }
        return JSON.stringify(this.SequenceConstructionFile);
    };

    this.LoadSequence = function(JSONSequenceConstructionFile)
    {
        this.Events = [];

        var SequenceConstructionFile = JSON.parse(JSONSequenceConstructionFile);
        //Set Sequence Properties
        if(this.Version > SequenceConstructionFile.Version){
            console.log("--- Sequence Upgrade Maybe Required ---");
        }

        this.SequenceLength = SequenceConstructionFile.SequenceLength;

        //Add all the Events
        for(var index = 0; index < SequenceConstructionFile.Events.length; index++) {

            var newEvent = new EVENT(SequenceConstructionFile.Events[index].StartTime,
                                      SequenceConstructionFile.Events[index].OriginLight,
                                      Brushes[SequenceConstructionFile.Events[index].BrushID],
                                      RebuildBrushData(SequenceConstructionFile.Events[index].BrushData));
            this.AddEvent(newEvent);
        }

        console.log("--- File Loaded ---");
    };
};

var EVENT = function(time, originLight, brush, brushData)
{
    this.IsBackground = false;
    this.StartTime = time; //Offset from the start of the sequence in frames.
    this.OriginLight = originLight; // The Light that the animation is based from.
    this.Brush = brush; // The brush that should be applied.
    this.BrushData = brushData; //The current brush data

    this.ApplyData = function()
    {
        this.BrushData = Clone(this.BrushData);
    };

    this.PrePaint = function()
    {
      if(this.Brush.PrePaint != null) this.Brush.PrePaint();
    };
    this.PostPaint = function()
    {
        if(this.Brush.PostPaint != null) this.Brush.PostPaint();
    };
    this.Render = function(CurrentFrame) // Applies brush to canvas
    {
        if (this.Brush.Render != null) this.Brush.Render(CurrentFrame, this.OriginLight, this.BrushData);
    };

    //Init
    this.init = function()
    {

    };
    this.init();
};
<commit_msg>Undo/Redo Stack<commit_after>/**
 * Created by Robert Butterworth on 8/9/2014.
 */

SEQUENCE = function() {

    var self = this;
    this.SequenceTime = 0; //Actual time of the Sequence.
    this.SequenceLength = 15*FPS;
    this.Version = 1;
    this.Events = [];
    this.Play = true;
    var mUndoIndex = 0;
    var mMaxUndoIndex = 0;

    var previousTime = new Date().getTime();

    this.GetSequenceTime = function()
    {
        return this.SequenceTime;
    };

    this.SetSequenceTime = function(time)
    {
        timer = time;
        this.SequenceTime = time;
    }

    this.ClearSequence = function()
    {
        ClearLights();
        this.Events = [];
    }

    this.GetSequenceLength = function()
    {
        return this.SequenceLength;
    };

    this.__defineGetter__("UndoIndex", function(){
        return mUndoIndex;
    });

    this.__defineSetter__("UndoIndex", function(val){

        if(val > mMaxUndoIndex){val = mMaxUndoIndex;}
        if(val < 0){val = 0;}

        mUndoIndex = val;
        UpdateUndoStack(false);
    });

    this.RenderFrame = function(frame, returnFrame)
    {
        var x;

        ClearLights();

        //Render Background
        for(x = 0; x < this.Events.length; x++)
        {
            if((this.Events[x].StartTime <= frame)&&
               (this.Events[x].Brush.Duration + this.Events[x].StartTime > frame))
            {
                if(this.Events[x].IsBackground == true && this.Events[x].Enabled == true)
                {
                        this.Events[x].Render(frame - this.Events[x].StartTime);
                }
            }
        }
        //Render Foreground
        for(x = 0; x < this.Events.length; x++)
        {
            if((this.Events[x].StartTime <= this.SequenceTime)&&
               (this.Events[x].Brush.Duration + this.Events[x].StartTime > frame))
            {
                if(this.Events[x].IsBackground == false && this.Events[x].Enabled == true)
                {
                        this.Events[x].Render(frame - this.Events[x].StartTime);
                }
            }
        }

        //Create Stream
        if(returnFrame == true)
        {
            var binaryFrame = "";

            for (var i = 0; i < 260; i++) {

                var color = new THREE.Color();

                var lightIndex = DomeLightOrder[i];

                color = DomeLightManager.Lights[lightIndex].color;

                binaryFrame += color.getHexString();
                // binaryFrame += String.fromCharCode( color.r );
                // binaryFrame += String.fromCharCode( color.g );
                // binaryFrame += String.fromCharCode( color.b );
            }

            return binaryFrame;
        }
    };

    this.RenderSequence = function(JSONSequenceConstructionFile)
    {
        var BinarySequenceStream = "";

        this.LoadSequence(JSONSequenceConstructionFile);

        if(this.Events.length < 1)
        {
            console.log("--- No Events in Sequence to Render ---");
            return undefined;
        }

        for (var i = 0; i < this.SequenceLength; i++) {
            this.SequenceTime = i;
            BinarySequenceStream += this.RenderFrame(i,true);
        }

        console.log("--- Stream Rendered ---");

        return BinarySequenceStream;
    };

    this.AddEvent = function(event)
    {
        //We need to sort this on addition based on time as we could be adding in an event at any point in time.
        //eg. During playback of other events.
        UpdateUndoStack(true);

        mUndoIndex++;
        mMaxUndoIndex = mUndoIndex;

        event.ActionID = mUndoIndex;

        this.Events.push(event);

        //Now we've added another event, sort to ensure they are in the correct order
        this.Events.sort(function(a,b){
            return a.StartTime - b.StartTime;
        });
    };

    this.RemoveEvent = function(atIndex)
    {
        this.Events.remove(atIndex);
    };

    this.Update = function()
    {
        if(this.Play == true)
        {
            timer += 0.8; //getFrameDelta();
            if (timer > this.SequenceLength) timer = 0.0;

            this.SequenceTime = Math.floor(timer);
        }
    };

    function getFrameDelta()
    {
        var frameDelta = 0;

        var currentTime = new Date().getTime();
        var delta = currentTime - previousTime;
        previousTime = currentTime;

        //console.log(delta);
        frameDelta = delta / (1000/FPS);

        return frameDelta;
    }

    //Used to load Objects with the right types
    function RebuildBrushData(Data)
    {
      var CleanData = [];

      if( Data ) {
	      for(var x =0; x < Object.keys(Data).length; x++)
	      {
	          if(Data[x].r != undefined && Data[x].g != undefined && Data[x].b != undefined)
	              CleanData[x] = new THREE.Color(Data[x].r,Data[x].g,Data[x].b);
	          else
	              CleanData[x] = Data[x];
	      }
      }
      return CleanData;
    }

    this.SaveSequence = function()
    {
        this.SequenceConstructionFile = {};
        this.SequenceConstructionFile.Events = [];

        //Set Sequence Properties
        this.SequenceConstructionFile.Version = this.Version;
        this.SequenceConstructionFile.SequenceLength = this.SequenceLength;

        //Add all the Events
        for(var index = 0; index < this.Events.length; index++) {

            var SequenceConstructionEvent = {};

            SequenceConstructionEvent.StartTime = this.Events[index].StartTime;
            SequenceConstructionEvent.OriginLight = this.Events[index].OriginLight;
            SequenceConstructionEvent.BrushID = this.Events[index].Brush.Index;
            SequenceConstructionEvent.BrushData = this.Events[index].BrushData;

            this.SequenceConstructionFile.Events.push(SequenceConstructionEvent);
        }
        return JSON.stringify(this.SequenceConstructionFile);
    };

    this.LoadSequence = function(JSONSequenceConstructionFile)
    {
        this.Events = [];

        var SequenceConstructionFile = JSON.parse(JSONSequenceConstructionFile);
        //Set Sequence Properties
        if(this.Version > SequenceConstructionFile.Version){
            console.log("--- Sequence Upgrade Maybe Required ---");
        }

        this.SequenceLength = SequenceConstructionFile.SequenceLength;

        //Add all the Events
        for(var index = 0; index < SequenceConstructionFile.Events.length; index++) {

            var newEvent = new EVENT(SequenceConstructionFile.Events[index].StartTime,
                                      SequenceConstructionFile.Events[index].OriginLight,
                                      Brushes[SequenceConstructionFile.Events[index].BrushID],
                                      RebuildBrushData(SequenceConstructionFile.Events[index].BrushData));
            this.AddEvent(newEvent);
        }

        console.log("--- File Loaded ---");
    };

    this.Undo = function()
    {
        if(mUndoIndex > 0)
        {
            mUndoIndex--;
            UpdateUndoStack(false);
        }
    };

    this.Redo = function()
    {
        if(mUndoIndex < mMaxUndoIndex)
        {
            mUndoIndex++;
            UpdateUndoStack(false);
        }
    };

    var UpdateUndoStack = function(clearPostIndex)
    {
        console.log("Update Stack");
        var mClearPostIndex = clearPostIndex || false;

        for(var i = 0; i < self.Events.length; i++)
        {
            if(self.Events[i].ActionID > mUndoIndex ){
                if(mClearPostIndex == true)
                {
                    self.Events.splice(i, 1);
                    mMaxUndoIndex = mUndoIndex;
                }
                else
                {
                    self.Events[i].Enabled = false;
                }
            }
            else{
                self.Events[i].Enabled = true;
            }
        }
    };

};

var EVENT = function(time, originLight, brush, brushData)
{
    this.ActionID = 0;
    this.Enabled = true;
    this.IsBackground = false;
    this.StartTime = time; //Offset from the start of the sequence in frames.
    this.OriginLight = originLight; // The Light that the animation is based from.
    this.Brush = brush; // The brush that should be applied.
    this.BrushData = brushData; //The current brush data

    this.ApplyData = function()
    {
        this.BrushData = Clone(this.BrushData);
    };

    this.PrePaint = function()
    {
      if(this.Brush.PrePaint != null) this.Brush.PrePaint();
    };
    this.PostPaint = function()
    {
        if(this.Brush.PostPaint != null) this.Brush.PostPaint();
    };
    this.Render = function(CurrentFrame) // Applies brush to canvas
    {
        if (this.Brush.Render != null) this.Brush.Render(CurrentFrame, this.OriginLight, this.BrushData);
    };

    //Init
    this.init = function()
    {

    };
    this.init();
};
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const path = require('path');
const glob = require('glob');
const isCreateReactApp = require('./isCreateReactApp');

const CREATE_REACT_APP_WEBPACK_CONFIG = 'react-scripts/config/webpack.config.dev';
const USER_WEBPACK_CONFIG_NAMES = [
	'webpack.config.dev.js',
	'webpack.config.js',
];
const USER_WEBPACK_CONFIG_MASK = '!(node_modules)*/**/webpack.config{.dev,}.js';

const absolutize = filePath => path.resolve(process.cwd(), filePath);

/**
 * Find user’s Webpack config and return its path.
 * Fixed location for create-react-app or search for the first webpack.config.dev.js or webpack.config.js.
 * Returns false if config not found.
 *
 * @return {string|boolean}
 */
module.exports = function findUserWebpackConfig() {
	// create-react-app
	if (isCreateReactApp()) {
		return CREATE_REACT_APP_WEBPACK_CONFIG;
	}

	// Quick check in the root folder
	for (const configFile of USER_WEBPACK_CONFIG_NAMES) {
		if (fs.existsSync(configFile)) {
			return absolutize(configFile);
		}
	}

	// Slower glob for ancestor folders
	const foundConfig = glob.sync(USER_WEBPACK_CONFIG_MASK);
	if (foundConfig.length) {
		return absolutize(foundConfig[0]);
	}

	return false;
};
<commit_msg>Test: Add cwd to glob<commit_after>'use strict';

const fs = require('fs');
const path = require('path');
const glob = require('glob');
const isCreateReactApp = require('./isCreateReactApp');

const CREATE_REACT_APP_WEBPACK_CONFIG = 'react-scripts/config/webpack.config.dev';
const USER_WEBPACK_CONFIG_NAMES = [
	'webpack.config.dev.js',
	'webpack.config.js',
];
const USER_WEBPACK_CONFIG_MASK = '!(node_modules)*/**/webpack.config{.dev,}.js';

const absolutize = filePath => path.resolve(process.cwd(), filePath);

/**
 * Find user’s Webpack config and return its path.
 * Fixed location for create-react-app or search for the first webpack.config.dev.js or webpack.config.js.
 * Returns false if config not found.
 *
 * @return {string|boolean}
 */
module.exports = function findUserWebpackConfig() {
	// create-react-app
	if (isCreateReactApp()) {
		return CREATE_REACT_APP_WEBPACK_CONFIG;
	}

	// Quick check in the root folder
	for (const configFile of USER_WEBPACK_CONFIG_NAMES) {
		if (fs.existsSync(configFile)) {
			return absolutize(configFile);
		}
	}

	// Slower glob for ancestor folders
	const foundConfig = glob.sync(USER_WEBPACK_CONFIG_MASK, { cwd: process.cwd() });
	if (foundConfig.length) {
		return absolutize(foundConfig[0]);
	}

	return false;
};
<|endoftext|>


<commit_before>//in collection 'gameData'
{
	_id:{
		toaEventKey: 'abc',
		matchInformation:{
			matchNumber: 123,
			robotAlliance: 'abc', //blue or red; with lower case
			teams: [123, 123]
		}
	}
	gameInformation:{	//CHECK IF ALL THSES TYPES ARE CORRECT AND ALSO HAVE COFRRECT MEANING!
		auto:{
			jewel: 123,
			glyphs: 123,
			keys: 123,
			park: 123
		},
		driver:{
			glyphs: 123,
			rows: 123,
			columns: 123,
			cypher: 123
		},
		end:{
			relic1: 123,	//Amount of relics in that zone
			relic2: 123,
			relic3: 123,
			relicsUp: 123,	//Amount of relects standing up
			balanced: 123	//How many robots are balanced
		}
	}
}

//in collection 'schedules'
{
	_id: 'abc', //toaEventKey
	schedule:[ //Aray of JSON
		{
			matchNumber: 123, //Match Number
			teams:{
				red1: 123, //Team Number
				red2: 123,
				blue1: 123,
				blue2: 123,
			}
		}
	]
}

// teams:{	//NOT SURE IF WE ACUALLY NEED THIS; WE HAVE SCHEDULE WHICH SHOULD BE A MATCH OF THIS
// 	red1: {
// 		teamNumber: 123,
// 		surrogate: false	//True if this team was surrgogate
// 	},
// 	red2: {
// 		teamNumber: 123,
// 		surrogate: false
// 	},
// 	blue1: {
// 		teamNumber: 123,
// 		surrogate: false
// 	},
// 	blue2: {
// 		teamNumber: 123,
// 		surrogate: false
// 	}
// }

//in collection 'matchData'
{
	_id:{
		toaEventKey: 'abc',
		matchInformation:{
			matchNumber: 123,
			teams:{	//NOT SURE IF WE ACUALLY NEED THIS; WE HAVE SCHEDULE WHICH SHOULD BE A MATCH OF THIS
				red1: 123,
				red2: 123,
				blue1: 123,
				blue2: 123
			}
		}
	},
	resultInformation:{
		winner: 'abc', //'blue', 'red', 'tie'
		score:{
			// red:{	//This may be better way but for now I'm leaving it the 'old' way
			// 	auto: 123,
			// 	driver: 123,
			// 	end: 123,
			// 	total: 123,
			// 	penalty: 123,
			// 	final: 123
			// },
			// blue:{
			// 	auto: 123,
			// 	driver: 123,
			// 	end: 123,
			// 	total: 123,
			// 	penalty: 123,
			// 	final: 123
			// },
			auto:{
				red: 123, //red alliance autonomous score
				blue: 123 //blue alliance autonomous score
			},
			driver:{
				red: 123, //red alliance tele-op score
				blue: 123 //blue alliance tele-op score
			},
			end:{
				red: 123, //red alliance end-game score
				blue: 123 //blue alliance end-game score
			},
			total:{
				red: 123, //red alliance total score
				blue: 123 //blue alliance total score
			},
			penalty:{
				red: 123, //red alliance penalty score
				blue: 123 //blue alliance penalty score
			},
			final:{
				red: 123, //red alliance final score
				blue: 123 //blue alliance final score
			}
		}
	}
}

//in collection 'events'
{
	_id: 'abc', //toaEventKey //This MUST be unique?? This is Date Place; There shouldn't be another DATEPLACE the same event (Thats the idea...)
	eventInformation:{
		date: ISODate(), //ISO Date of when it occured;
		eventName: 'abc',
		locationName: 'abc',	//Same as the name in the locations collection
		locationID: ObjectId(), //ID of the location in the 'locations' collection
		teamsList:[123, 123, 123],
		season: 'Y1Y2', //for relic recovery 2017-2018 the season is '1718'
	}
}

//in collection 'locations'
{
	_id: ObjectId(),	//This is the id of the location
	name: 'abc',		//Name of the location exmaple: Sage Creek High School
	address:{			//if value is missing, use null
		number: 123,	//Address number?
		street: 'abc',	//Street
		zip: 123,		//Postal Zip
		city: 'abc',	//City
		state: 'abc',	//State (CA)
		country: 'abc'	//USA
	}
}

//in collection 'eventOut' INCOMPLETE
{
	_id: 'abc', //toaEventKey
	lastUpdated: ISODate(), //Time of insert/update
	ranking:[
		{
			rank: 123,
			teamNumber: 123,
			teamName: 123,
			record:{
				wins: 123,
				losses: 123,
				ties: 123
			},
			qualifyingPoints: 123,
			rankingPoints: 123,
			averageScore: .123,
			averageMarginalScore: .123,
			average:{
				auto: .123,
				driver: .123,
				end: .123
			}
		}
	],
	matchHistory:[
		{
			matchNumber: 123,
			alliance: 'abc', //blue or red; lower case
			team1:{
				teamNumber: 123,
				teamName: 'abc',
				rank: 123
			},
			team2:{
				teamNumber: 123,
				teamName: 'abc',
				rank: 123
			},
			result:{
				total: 123,
				penalty: 123,
				final: 123
			},
			prediction: 'abc', //Which alliance will win; CHANGE THIS SCHEMA LATTER!!!!!
			gameInformation:{	//CHECK IF ALL THSES TYPES ARE CORRECT AND ALSO HAVE COFRRECT MEANING!
				auto:{
					jewel: 123,
					glyphs: 123,
					keys: 123,
					park: 123
				},
				driver:{
					glyphs: 123,
					rows: 123,
					columns: 123,
					cypher: 123
				},
				end:{
					relic1: 123,	//Amount of relics in that zone
					relic2: 123,
					relic3: 123,
					relicsUp: 123,	//Amount of relects standing up
					balanced: 123	//How many robots are balanced
				}
			}
		}
	],
	averageScores:[
		{
			teamNumber: 123,
			teamName: 'abc',
			averageScore: .123,
			averageMarginalScore: .123,
			average:{
				auto: .123,
				driver: .123,
				end: .123
			},
			gameAverages:{	//CHECK IF ALL THSES TYPES ARE CORRECT AND ALSO HAVE COFRRECT MEANING! This is the calculated averages of each game element
				auto:{
					jewel: .123,
					glyphs: .123,
					keys: .123,
					park: .123
				},
				driver:{
					glyphs: .123,
					rows: .123,
					columns: .123,
					cypher: .123
				},
				end:{
					relic1: .123,	//Amount of relics in that zone
					relic2: .123,
					relic3: .123,
					relicsUp: .123,	//Amount of relects standing up
					balanced: .123	//How many robots are balanced
				}
			}
		}
	]
}

//in collection 'teams'
{
	_id: 123, //Team Number
	teamName: 'abc'
}

//in collection 'gameData' OLD DO NOT USE
{
	eventInformation:{
		name: 'abc',
		date: ISODate(), //ISO Date of when it occured;
		locationID: ObjectId() //ID of the location in the 'places' collection
	},
	matchInformation:{
		matchNumber: 123,
		robotAlliance: 'abc', //"blue" or "red"
		teamNumber: 123
	},
	gameInformation:{
		auto:{
			jewel: true, //True if score is gained?
			robotParking: true, //True if in safe zone
			cryptobox1:{
				glyphs: 123, //How many glyphs got scored in AUTO
				key: true //If correct key; and gained bonus
			}
			cryptobox2:{
				glyphs: 123, //How many glyphs got scored in AUTO
				key: true //If correct key; and gained bonus
			}
		},
		end:{
			relic1: { //If robot scored a relic; include field always
				zone: 123, //Zone 0 if not scored
				upright: true, //true if upright
			},
			relic2: { //If the robot scored two relics
				zone: 123,
				upright: true
			},
			robotBalanced: true, //True if balanced
			cryptobox1:{
				rows: 123, //Rows completed
				columns: 123, //Columns completed
				cipher: true, //If cipher was completed
				glyphs: 123, //How many glyphs got scored in AUTO
				key: true //If correct key; and gained bonus
			},
			cryptobox2:{
				rows: 123, //Rows completed
				columns: 123, //Columns completed
				cipher: true, //If cipher was completed
				glyphs: 123, //How many glyphs got scored in AUTO
				key: true //If correct key; and gained bonus
			}
		}
	}
}<commit_msg>Added WInner to eventout<commit_after>//in collection 'gameData'
{
	_id:{
		toaEventKey: 'abc',
		matchInformation:{
			matchNumber: 123,
			robotAlliance: 'abc', //blue or red; with lower case
			teams: [123, 123]
		}
	}
	gameInformation:{	//CHECK IF ALL THSES TYPES ARE CORRECT AND ALSO HAVE COFRRECT MEANING!
		auto:{
			jewel: 123,
			glyphs: 123,
			keys: 123,
			park: 123
		},
		driver:{
			glyphs: 123,
			rows: 123,
			columns: 123,
			cypher: 123
		},
		end:{
			relic1: 123,	//Amount of relics in that zone
			relic2: 123,
			relic3: 123,
			relicsUp: 123,	//Amount of relects standing up
			balanced: 123	//How many robots are balanced
		}
	}
}

//in collection 'schedules'
{
	_id: 'abc', //toaEventKey
	schedule:[ //Aray of JSON
		{
			matchNumber: 123, //Match Number
			teams:{
				red1: 123, //Team Number
				red2: 123,
				blue1: 123,
				blue2: 123,
			}
		}
	]
}

// teams:{	//NOT SURE IF WE ACUALLY NEED THIS; WE HAVE SCHEDULE WHICH SHOULD BE A MATCH OF THIS
// 	red1: {
// 		teamNumber: 123,
// 		surrogate: false	//True if this team was surrgogate
// 	},
// 	red2: {
// 		teamNumber: 123,
// 		surrogate: false
// 	},
// 	blue1: {
// 		teamNumber: 123,
// 		surrogate: false
// 	},
// 	blue2: {
// 		teamNumber: 123,
// 		surrogate: false
// 	}
// }

//in collection 'matchData'
{
	_id:{
		toaEventKey: 'abc',
		matchInformation:{
			matchNumber: 123,
			teams:{	//NOT SURE IF WE ACUALLY NEED THIS; WE HAVE SCHEDULE WHICH SHOULD BE A MATCH OF THIS
				red1: 123,
				red2: 123,
				blue1: 123,
				blue2: 123
			}
		}
	},
	resultInformation:{
		winner: 'abc', //'blue', 'red', 'tie'
		score:{
			// red:{	//This may be better way but for now I'm leaving it the 'old' way
			// 	auto: 123,
			// 	driver: 123,
			// 	end: 123,
			// 	total: 123,
			// 	penalty: 123,
			// 	final: 123
			// },
			// blue:{
			// 	auto: 123,
			// 	driver: 123,
			// 	end: 123,
			// 	total: 123,
			// 	penalty: 123,
			// 	final: 123
			// },
			auto:{
				red: 123, //red alliance autonomous score
				blue: 123 //blue alliance autonomous score
			},
			driver:{
				red: 123, //red alliance tele-op score
				blue: 123 //blue alliance tele-op score
			},
			end:{
				red: 123, //red alliance end-game score
				blue: 123 //blue alliance end-game score
			},
			total:{
				red: 123, //red alliance total score
				blue: 123 //blue alliance total score
			},
			penalty:{
				red: 123, //red alliance penalty score
				blue: 123 //blue alliance penalty score
			},
			final:{
				red: 123, //red alliance final score
				blue: 123 //blue alliance final score
			}
		}
	}
}

//in collection 'events'
{
	_id: 'abc', //toaEventKey //This MUST be unique?? This is Date Place; There shouldn't be another DATEPLACE the same event (Thats the idea...)
	eventInformation:{
		date: ISODate(), //ISO Date of when it occured;
		eventName: 'abc',
		locationName: 'abc',	//Same as the name in the locations collection
		locationID: ObjectId(), //ID of the location in the 'locations' collection
		teamsList:[123, 123, 123],
		season: 'Y1Y2', //for relic recovery 2017-2018 the season is '1718'
	}
}

//in collection 'locations'
{
	_id: ObjectId(),	//This is the id of the location
	name: 'abc',		//Name of the location exmaple: Sage Creek High School
	address:{			//if value is missing, use null
		number: 123,	//Address number?
		street: 'abc',	//Street
		zip: 123,		//Postal Zip
		city: 'abc',	//City
		state: 'abc',	//State (CA)
		country: 'abc'	//USA
	}
}

//in collection 'eventOut' INCOMPLETE
{
	_id: 'abc', //toaEventKey
	lastUpdated: ISODate(), //Time of insert/update
	ranking:[
		{
			rank: 123,
			teamNumber: 123,
			teamName: 123,
			record:{
				wins: 123,
				losses: 123,
				ties: 123
			},
			qualifyingPoints: 123,
			rankingPoints: 123,
			averageScore: .123,
			averageMarginalScore: .123,
			average:{
				auto: .123,
				driver: .123,
				end: .123
			}
		}
	],
	matchHistory:[
		{
			matchNumber: 123,
			alliance: 'abc', //blue or red; lower case
			team1:{
				teamNumber: 123,
				teamName: 'abc',
				rank: 123
			},
			team2:{
				teamNumber: 123,
				teamName: 'abc',
				rank: 123
			},
			result:{
				total: 123,
				penalty: 123,
				final: 123
			},
			prediction: 'abc', //Which alliance will win; CHANGE THIS SCHEMA LATTER!!!!!
			winner: 'abc', //blue or red
			gameInformation:{	//CHECK IF ALL THSES TYPES ARE CORRECT AND ALSO HAVE COFRRECT MEANING!
				auto:{
					jewel: 123,
					glyphs: 123,
					keys: 123,
					park: 123
				},
				driver:{
					glyphs: 123,
					rows: 123,
					columns: 123,
					cypher: 123
				},
				end:{
					relic1: 123,	//Amount of relics in that zone
					relic2: 123,
					relic3: 123,
					relicsUp: 123,	//Amount of relects standing up
					balanced: 123	//How many robots are balanced
				}
			}
		}
	],
	averageScores:[
		{
			teamNumber: 123,
			teamName: 'abc',
			averageScore: .123,
			averageMarginalScore: .123,
			average:{
				auto: .123,
				driver: .123,
				end: .123
			},
			gameAverages:{	//CHECK IF ALL THSES TYPES ARE CORRECT AND ALSO HAVE COFRRECT MEANING! This is the calculated averages of each game element
				auto:{
					jewel: .123,
					glyphs: .123,
					keys: .123,
					park: .123
				},
				driver:{
					glyphs: .123,
					rows: .123,
					columns: .123,
					cypher: .123
				},
				end:{
					relic1: .123,	//Amount of relics in that zone
					relic2: .123,
					relic3: .123,
					relicsUp: .123,	//Amount of relects standing up
					balanced: .123	//How many robots are balanced
				}
			}
		}
	]
}

//in collection 'teams'
{
	_id: 123, //Team Number
	teamName: 'abc'
}

//in collection 'gameData' OLD DO NOT USE
{
	eventInformation:{
		name: 'abc',
		date: ISODate(), //ISO Date of when it occured;
		locationID: ObjectId() //ID of the location in the 'places' collection
	},
	matchInformation:{
		matchNumber: 123,
		robotAlliance: 'abc', //"blue" or "red"
		teamNumber: 123
	},
	gameInformation:{
		auto:{
			jewel: true, //True if score is gained?
			robotParking: true, //True if in safe zone
			cryptobox1:{
				glyphs: 123, //How many glyphs got scored in AUTO
				key: true //If correct key; and gained bonus
			}
			cryptobox2:{
				glyphs: 123, //How many glyphs got scored in AUTO
				key: true //If correct key; and gained bonus
			}
		},
		end:{
			relic1: { //If robot scored a relic; include field always
				zone: 123, //Zone 0 if not scored
				upright: true, //true if upright
			},
			relic2: { //If the robot scored two relics
				zone: 123,
				upright: true
			},
			robotBalanced: true, //True if balanced
			cryptobox1:{
				rows: 123, //Rows completed
				columns: 123, //Columns completed
				cipher: true, //If cipher was completed
				glyphs: 123, //How many glyphs got scored in AUTO
				key: true //If correct key; and gained bonus
			},
			cryptobox2:{
				rows: 123, //Rows completed
				columns: 123, //Columns completed
				cipher: true, //If cipher was completed
				glyphs: 123, //How many glyphs got scored in AUTO
				key: true //If correct key; and gained bonus
			}
		}
	}
}<|endoftext|>


<commit_before>/*
	Masked Input plugin for jQuery
	Copyright (c) 2007-2013 Josh Bush (digitalbush.com)
	Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license)
	Version: 1.3.1
*/
(function($) {
	function getPasteEvent() {
    var el = document.createElement('input'),
        name = 'onpaste';
    el.setAttribute(name, '');
    return (typeof el[name] === 'function')?'paste':'input';
}

var pasteEventName = getPasteEvent() + ".mask",
	ua = navigator.userAgent,
	iPhone = /iphone/i.test(ua),
	android=/android/i.test(ua),
	caretTimeoutId;

$.mask = {
	//Predefined character definitions
	definitions: {
		'9': "[0-9]",
		'a': "[A-Za-z]",
		'*': "[A-Za-z0-9]"
	},
	dataName: "rawMaskFn",
	placeholder: '_',
};

$.fn.extend({
	//Helper Function for Caret positioning
	caret: function(begin, end) {
		var range;

		if (this.length === 0 || this.is(":hidden")) {
			return;
		}

		if (typeof begin == 'number') {
			end = (typeof end === 'number') ? end : begin;
			return this.each(function() {
				if (this.setSelectionRange) {
					this.setSelectionRange(begin, end);
				} else if (this.createTextRange) {
					range = this.createTextRange();
					range.collapse(true);
					range.moveEnd('character', end);
					range.moveStart('character', begin);
					range.select();
				}
			});
		} else {
			if (this[0].setSelectionRange) {
				begin = this[0].selectionStart;
				end = this[0].selectionEnd;
			} else if (document.selection && document.selection.createRange) {
				range = document.selection.createRange();
				begin = 0 - range.duplicate().moveStart('character', -100000);
				end = begin + range.text.length;
			}
			return { begin: begin, end: end };
		}
	},
	unmask: function() {
		return this.trigger("unmask");
	},
	mask: function(mask, settings) {
		var input,
			defs,
			tests,
			partialPosition,
			firstNonMaskPos,
			len;

		if (!mask && this.length > 0) {
			input = $(this[0]);
			return input.data($.mask.dataName)();
		}
		settings = $.extend({
			placeholder: $.mask.placeholder, // Load default placeholder
			completed: null
		}, settings);

		defs = $.mask.definitions;
		tests = [];
		partialPosition = len = mask.length;
		firstNonMaskPos = null;

		$.each(mask.split(""), function(i, c) {
			if (c == '?') {
				len--;
				partialPosition = i;
			} else if (defs[c]) {
				tests.push(new RegExp(defs[c]));
				if (firstNonMaskPos === null) {
					firstNonMaskPos = tests.length - 1;
				}
			} else {
				tests.push(null);
			}
		});

		return this.trigger("unmask").each(function() {
			var input = $(this),
				buffer = $.map(
				mask.split(""),
				function(c, i) {
					if (c != '?') {
						return defs[c] ? settings.placeholder : c;
					}
				}),
				focusText = input.val();

			function seekNext(pos) {
				while (++pos < len && !tests[pos]);
				return pos;
			}

			function seekPrev(pos) {
				while (--pos >= 0 && !tests[pos]);
				return pos;
			}

			function shiftL(begin,end) {
				var i,
					j;

				if (begin<0) {
					return;
				}

				for (i = begin, j = seekNext(end); i < len; i++) {
					if (tests[i]) {
						if (j < len && tests[i].test(buffer[j])) {
							buffer[i] = buffer[j];
							buffer[j] = settings.placeholder;
						} else {
							break;
						}

						j = seekNext(j);
					}
				}
				writeBuffer();
				input.caret(Math.max(firstNonMaskPos, begin));
			}

			function shiftR(pos) {
				var i,
					c,
					j,
					t;

				for (i = pos, c = settings.placeholder; i < len; i++) {
					if (tests[i]) {
						j = seekNext(i);
						t = buffer[i];
						buffer[i] = c;
						if (j < len && tests[j].test(t)) {
							c = t;
						} else {
							break;
						}
					}
				}
			}

			function keydownEvent(e) {
				var k = e.which,
					pos,
					begin,
					end;

				//backspace, delete, and escape get special treatment
				if (k === 8 || k === 46 || (iPhone && k === 127)) {
					pos = input.caret();
					begin = pos.begin;
					end = pos.end;

					if (end - begin === 0) {
						begin=k!==46?seekPrev(begin):(end=seekNext(begin-1));
						end=k===46?seekNext(end):end;
					}
					clearBuffer(begin, end);
					shiftL(begin, end - 1);

					e.preventDefault();
				} else if (k == 27) {//escape
					input.val(focusText);
					input.caret(0, checkVal());
					e.preventDefault();
				}
			}

			function keypressEvent(e) {
				var k = e.which,
					pos = input.caret(),
					p,
					c,
					next;

				if (e.ctrlKey || e.altKey || e.metaKey || k < 32) {//Ignore
					return;
				} else if (k) {
					if (pos.end - pos.begin !== 0){
						clearBuffer(pos.begin, pos.end);
						shiftL(pos.begin, pos.end-1);
					}

					p = seekNext(pos.begin - 1);
					if (p < len) {
						c = String.fromCharCode(k);
						if (tests[p].test(c)) {
							shiftR(p);

							buffer[p] = c;
							writeBuffer();
							next = seekNext(p);

							if(android){
								setTimeout($.proxy($.fn.caret,input,next),0);
							}else{
								input.caret(next);
							}

							if (settings.completed && next >= len) {
								settings.completed.call(input);
							}
						}
					}
					e.preventDefault();
				}
			}

			function clearBuffer(start, end) {
				var i;
				for (i = start; i < end && i < len; i++) {
					if (tests[i]) {
						buffer[i] = settings.placeholder;
					}
				}
			}

			function writeBuffer() { input.val(buffer.join('')); }

			function checkVal(allow) {
				//try to place characters where they belong
				var test = input.val(),
					lastMatch = -1,
					i,
					c;

				for (i = 0, pos = 0; i < len; i++) {
					if (tests[i]) {
						buffer[i] = settings.placeholder;
						while (pos++ < test.length) {
							c = test.charAt(pos - 1);
							if (tests[i].test(c)) {
								buffer[i] = c;
								lastMatch = i;
								break;
							}
						}
						if (pos > test.length) {
							break;
						}
					} else if (buffer[i] === test.charAt(pos) && i !== partialPosition) {
						pos++;
						lastMatch = i;
					}
				}
				if (allow) {
					writeBuffer();
				} else if (lastMatch + 1 < partialPosition) {
					input.val("");
					clearBuffer(0, len);
				} else {
					writeBuffer();
					input.val(input.val().substring(0, lastMatch + 1));
				}
				return (partialPosition ? i : firstNonMaskPos);
			}

			input.data($.mask.dataName,function(){
				return $.map(buffer, function(c, i) {
					return tests[i]&&c!=settings.placeholder ? c : null;
				}).join('');
			});

			if (!input.attr("readonly"))
				input
				.one("unmask", function() {
					input
						.unbind(".mask")
						.removeData($.mask.dataName);
				})
				.bind("focus.mask", function() {
					clearTimeout(caretTimeoutId);
					var pos,
						moveCaret;

					focusText = input.val();
					pos = checkVal();

					caretTimeoutId = setTimeout(function(){
						writeBuffer();
						if (pos == mask.length) {
							input.caret(0, pos);
						} else {
							input.caret(pos);
						}
					}, 10);
				})
				.bind("blur.mask", function() {
					checkVal();
					if (input.val() != focusText)
						input.change();
				})
				.bind("keydown.mask", keydownEvent)
				.bind("keypress.mask", keypressEvent)
				.bind(pasteEventName, function() {
					setTimeout(function() {
						var pos=checkVal(true);
						input.caret(pos);
						if (settings.completed && pos == input.val().length)
							settings.completed.call(input);
					}, 0);
				});
			checkVal(); //Perform initial check for existing values
		});
	}
});

})(jQuery);<commit_msg>Properly closed mask object definition to prevent JavaScript error in IE7<commit_after>/*
	Masked Input plugin for jQuery
	Copyright (c) 2007-2013 Josh Bush (digitalbush.com)
	Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license)
	Version: 1.3.1
*/
(function($) {
	function getPasteEvent() {
    var el = document.createElement('input'),
        name = 'onpaste';
    el.setAttribute(name, '');
    return (typeof el[name] === 'function')?'paste':'input';
}

var pasteEventName = getPasteEvent() + ".mask",
	ua = navigator.userAgent,
	iPhone = /iphone/i.test(ua),
	android=/android/i.test(ua),
	caretTimeoutId;

$.mask = {
	//Predefined character definitions
	definitions: {
		'9': "[0-9]",
		'a': "[A-Za-z]",
		'*': "[A-Za-z0-9]"
	},
	dataName: "rawMaskFn",
	placeholder: '_'
};

$.fn.extend({
	//Helper Function for Caret positioning
	caret: function(begin, end) {
		var range;

		if (this.length === 0 || this.is(":hidden")) {
			return;
		}

		if (typeof begin == 'number') {
			end = (typeof end === 'number') ? end : begin;
			return this.each(function() {
				if (this.setSelectionRange) {
					this.setSelectionRange(begin, end);
				} else if (this.createTextRange) {
					range = this.createTextRange();
					range.collapse(true);
					range.moveEnd('character', end);
					range.moveStart('character', begin);
					range.select();
				}
			});
		} else {
			if (this[0].setSelectionRange) {
				begin = this[0].selectionStart;
				end = this[0].selectionEnd;
			} else if (document.selection && document.selection.createRange) {
				range = document.selection.createRange();
				begin = 0 - range.duplicate().moveStart('character', -100000);
				end = begin + range.text.length;
			}
			return { begin: begin, end: end };
		}
	},
	unmask: function() {
		return this.trigger("unmask");
	},
	mask: function(mask, settings) {
		var input,
			defs,
			tests,
			partialPosition,
			firstNonMaskPos,
			len;

		if (!mask && this.length > 0) {
			input = $(this[0]);
			return input.data($.mask.dataName)();
		}
		settings = $.extend({
			placeholder: $.mask.placeholder, // Load default placeholder
			completed: null
		}, settings);

		defs = $.mask.definitions;
		tests = [];
		partialPosition = len = mask.length;
		firstNonMaskPos = null;

		$.each(mask.split(""), function(i, c) {
			if (c == '?') {
				len--;
				partialPosition = i;
			} else if (defs[c]) {
				tests.push(new RegExp(defs[c]));
				if (firstNonMaskPos === null) {
					firstNonMaskPos = tests.length - 1;
				}
			} else {
				tests.push(null);
			}
		});

		return this.trigger("unmask").each(function() {
			var input = $(this),
				buffer = $.map(
				mask.split(""),
				function(c, i) {
					if (c != '?') {
						return defs[c] ? settings.placeholder : c;
					}
				}),
				focusText = input.val();

			function seekNext(pos) {
				while (++pos < len && !tests[pos]);
				return pos;
			}

			function seekPrev(pos) {
				while (--pos >= 0 && !tests[pos]);
				return pos;
			}

			function shiftL(begin,end) {
				var i,
					j;

				if (begin<0) {
					return;
				}

				for (i = begin, j = seekNext(end); i < len; i++) {
					if (tests[i]) {
						if (j < len && tests[i].test(buffer[j])) {
							buffer[i] = buffer[j];
							buffer[j] = settings.placeholder;
						} else {
							break;
						}

						j = seekNext(j);
					}
				}
				writeBuffer();
				input.caret(Math.max(firstNonMaskPos, begin));
			}

			function shiftR(pos) {
				var i,
					c,
					j,
					t;

				for (i = pos, c = settings.placeholder; i < len; i++) {
					if (tests[i]) {
						j = seekNext(i);
						t = buffer[i];
						buffer[i] = c;
						if (j < len && tests[j].test(t)) {
							c = t;
						} else {
							break;
						}
					}
				}
			}

			function keydownEvent(e) {
				var k = e.which,
					pos,
					begin,
					end;

				//backspace, delete, and escape get special treatment
				if (k === 8 || k === 46 || (iPhone && k === 127)) {
					pos = input.caret();
					begin = pos.begin;
					end = pos.end;

					if (end - begin === 0) {
						begin=k!==46?seekPrev(begin):(end=seekNext(begin-1));
						end=k===46?seekNext(end):end;
					}
					clearBuffer(begin, end);
					shiftL(begin, end - 1);

					e.preventDefault();
				} else if (k == 27) {//escape
					input.val(focusText);
					input.caret(0, checkVal());
					e.preventDefault();
				}
			}

			function keypressEvent(e) {
				var k = e.which,
					pos = input.caret(),
					p,
					c,
					next;

				if (e.ctrlKey || e.altKey || e.metaKey || k < 32) {//Ignore
					return;
				} else if (k) {
					if (pos.end - pos.begin !== 0){
						clearBuffer(pos.begin, pos.end);
						shiftL(pos.begin, pos.end-1);
					}

					p = seekNext(pos.begin - 1);
					if (p < len) {
						c = String.fromCharCode(k);
						if (tests[p].test(c)) {
							shiftR(p);

							buffer[p] = c;
							writeBuffer();
							next = seekNext(p);

							if(android){
								setTimeout($.proxy($.fn.caret,input,next),0);
							}else{
								input.caret(next);
							}

							if (settings.completed && next >= len) {
								settings.completed.call(input);
							}
						}
					}
					e.preventDefault();
				}
			}

			function clearBuffer(start, end) {
				var i;
				for (i = start; i < end && i < len; i++) {
					if (tests[i]) {
						buffer[i] = settings.placeholder;
					}
				}
			}

			function writeBuffer() { input.val(buffer.join('')); }

			function checkVal(allow) {
				//try to place characters where they belong
				var test = input.val(),
					lastMatch = -1,
					i,
					c;

				for (i = 0, pos = 0; i < len; i++) {
					if (tests[i]) {
						buffer[i] = settings.placeholder;
						while (pos++ < test.length) {
							c = test.charAt(pos - 1);
							if (tests[i].test(c)) {
								buffer[i] = c;
								lastMatch = i;
								break;
							}
						}
						if (pos > test.length) {
							break;
						}
					} else if (buffer[i] === test.charAt(pos) && i !== partialPosition) {
						pos++;
						lastMatch = i;
					}
				}
				if (allow) {
					writeBuffer();
				} else if (lastMatch + 1 < partialPosition) {
					input.val("");
					clearBuffer(0, len);
				} else {
					writeBuffer();
					input.val(input.val().substring(0, lastMatch + 1));
				}
				return (partialPosition ? i : firstNonMaskPos);
			}

			input.data($.mask.dataName,function(){
				return $.map(buffer, function(c, i) {
					return tests[i]&&c!=settings.placeholder ? c : null;
				}).join('');
			});

			if (!input.attr("readonly"))
				input
				.one("unmask", function() {
					input
						.unbind(".mask")
						.removeData($.mask.dataName);
				})
				.bind("focus.mask", function() {
					clearTimeout(caretTimeoutId);
					var pos,
						moveCaret;

					focusText = input.val();
					pos = checkVal();

					caretTimeoutId = setTimeout(function(){
						writeBuffer();
						if (pos == mask.length) {
							input.caret(0, pos);
						} else {
							input.caret(pos);
						}
					}, 10);
				})
				.bind("blur.mask", function() {
					checkVal();
					if (input.val() != focusText)
						input.change();
				})
				.bind("keydown.mask", keydownEvent)
				.bind("keypress.mask", keypressEvent)
				.bind(pasteEventName, function() {
					setTimeout(function() {
						var pos=checkVal(true);
						input.caret(pos);
						if (settings.completed && pos == input.val().length)
							settings.completed.call(input);
					}, 0);
				});
			checkVal(); //Perform initial check for existing values
		});
	}
});

})(jQuery);
<|endoftext|>


<commit_before>// Copyright 2017 TODO Group. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

const Result = require('../lib/result')
// eslint-disable-next-line no-unused-vars
const FileSystem = require('../lib/file_system')
/** @type {any} */
const fetch = require('node-fetch')

/**
 * Prepend or append text to a file
 *
 * @param {FileSystem} fs A filesystem object configured with filter paths and target directories
 * @param {object} options The rule configuration
 * @param {string[]} targets The files to modify (will be overridden by options if present)
 * @param {boolean} dryRun If true, repolinter will report suggested fixes, but will make no disk modifications.
 * @returns {Promise<Result>} The lint rule result
 */
async function fileModify (fs, options, targets, dryRun = false) {
  const realTargets = options.files || targets
  if (realTargets.length === 0) { return new Result('No files to modify, did you configure this fix correctly?', [], false) }

  // find all files matching the regular expressions specified
  let files = await fs.findAllFiles(realTargets, options.nocase)

  // skip files if necessary
  if (options['skip-paths-matching']) {
    let regexes = []
    const extensions = options['skip-paths-matching'].extensions
    if (extensions && extensions.length > 0) {
      const extJoined = extensions.join('|')
      // \.(svg|png|exe)$
      regexes.push(new RegExp('\.(' + extJoined + ')$', 'i')) // eslint-disable-line no-useless-escape
    }

    const patterns = options['skip-paths-matching'].patterns
    if (patterns && patterns.length > 0) {
      const filteredPatterns = patterns
        .filter(p => typeof p === 'string' && p !== '')
        .map(p => new RegExp(p, options['skip-paths-matching'].flags))
      regexes = regexes.concat(filteredPatterns)
    }
    files = files.filter(file =>
      !regexes.some(regex => file.match(regex))
    )
  }

  // read the text from the source, if necessary
  let content
  if (typeof options.text === 'string') { content = options.text } else if (typeof options.text === 'object') {
    if (options.text.url) {
      const req = await fetch(options.text.url)
      if (!req.ok) { return new Result(`Could not fetch from ${options.text.url}, received status code ${req.status}`, [], false) }
      content = await req.text()
    } else if (options.text.file) {
      const file = await fs.findFirstFile([options.text.file], options.text.nocase === true)
      if (!file) { return new Result(`Could not find file matching pattern ${options.text.file} for file-modify.`, [], false) }
      content = await fs.getFileContents(file)
    }
  }
  if (!content) { return new Result('Text was not specified for file-modify! Did you configure the ruleset correctly?', [], false) }

  // write it to the file
  const resTargets = await Promise.all(files.map(async file => {
    // do file operation
    if (!dryRun) {
      const startNewlines = (options.newlines && options.newlines.begin ? new Array(options.newlines.begin).fill('\n').join('') : '')
      const endNewlines = (options.newlines && options.newlines.end ? new Array(options.newlines.end).fill('\n').join('') : '')
      const fileContent = startNewlines + content + endNewlines
      if (options.write_mode === 'append') {
        await fs.setFileContents(file, await fs.getFileContents(file) + fileContent)
      } else {
        await fs.setFileContents(file, fileContent + await fs.getFileContents(file))
      }
    }
    // return the target information
    const message = typeof options.text === 'object'
      ? `${options.write_mode} text from ${options.text.file || options.text.url} to file`
      : `${options.write_mode} ${JSON.stringify(content)} to file`
    return {
      message,
      passed: true,
      path: file
    }
  }))

  return new Result('', resTargets, true)
}

module.exports = fileModify
<commit_msg>switch to backtick quotes for file-modify<commit_after>// Copyright 2017 TODO Group. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

const Result = require('../lib/result')
// eslint-disable-next-line no-unused-vars
const FileSystem = require('../lib/file_system')
/** @type {any} */
const fetch = require('node-fetch')

/**
 * Prepend or append text to a file
 *
 * @param {FileSystem} fs A filesystem object configured with filter paths and target directories
 * @param {object} options The rule configuration
 * @param {string[]} targets The files to modify (will be overridden by options if present)
 * @param {boolean} dryRun If true, repolinter will report suggested fixes, but will make no disk modifications.
 * @returns {Promise<Result>} The lint rule result
 */
async function fileModify (fs, options, targets, dryRun = false) {
  const realTargets = options.files || targets
  if (realTargets.length === 0) { return new Result('No files to modify, did you configure this fix correctly?', [], false) }

  // find all files matching the regular expressions specified
  let files = await fs.findAllFiles(realTargets, options.nocase)

  // skip files if necessary
  if (options['skip-paths-matching']) {
    let regexes = []
    const extensions = options['skip-paths-matching'].extensions
    if (extensions && extensions.length > 0) {
      const extJoined = extensions.join('|')
      // \.(svg|png|exe)$
      regexes.push(new RegExp('\.(' + extJoined + ')$', 'i')) // eslint-disable-line no-useless-escape
    }

    const patterns = options['skip-paths-matching'].patterns
    if (patterns && patterns.length > 0) {
      const filteredPatterns = patterns
        .filter(p => typeof p === 'string' && p !== '')
        .map(p => new RegExp(p, options['skip-paths-matching'].flags))
      regexes = regexes.concat(filteredPatterns)
    }
    files = files.filter(file =>
      !regexes.some(regex => file.match(regex))
    )
  }

  // read the text from the source, if necessary
  let content
  if (typeof options.text === 'string') { content = options.text } else if (typeof options.text === 'object') {
    if (options.text.url) {
      const req = await fetch(options.text.url)
      if (!req.ok) { return new Result(`Could not fetch from ${options.text.url}, received status code ${req.status}`, [], false) }
      content = await req.text()
    } else if (options.text.file) {
      const file = await fs.findFirstFile([options.text.file], options.text.nocase === true)
      if (!file) { return new Result(`Could not find file matching pattern ${options.text.file} for file-modify.`, [], false) }
      content = await fs.getFileContents(file)
    }
  }
  if (!content) { return new Result('Text was not specified for file-modify! Did you configure the ruleset correctly?', [], false) }

  // write it to the file
  const resTargets = await Promise.all(files.map(async file => {
    // do file operation
    if (!dryRun) {
      const startNewlines = (options.newlines && options.newlines.begin ? new Array(options.newlines.begin).fill('\n').join('') : '')
      const endNewlines = (options.newlines && options.newlines.end ? new Array(options.newlines.end).fill('\n').join('') : '')
      const fileContent = startNewlines + content + endNewlines
      if (options.write_mode === 'append') {
        await fs.setFileContents(file, await fs.getFileContents(file) + fileContent)
      } else {
        await fs.setFileContents(file, fileContent + await fs.getFileContents(file))
      }
    }
    // return the target information
    const message = typeof options.text === 'object'
      ? `${options.write_mode} text from ${options.text.file || options.text.url} to file`
      : `${options.write_mode} \`${JSON.stringify(content).slice(1, -1)}\` to file`
    return {
      message,
      passed: true,
      path: file
    }
  }))

  return new Result('', resTargets, true)
}

module.exports = fileModify
<|endoftext|>


<commit_before>const DEFAULTS = require('./settings.json');

/**
 * Create a triage report
 *
 * @param {Object} payload - The Slack slash command payload
 * @param {Object[]} message - The Slack message history
 * @param {Object} options - (optional) settings overrides
 * @returns {Object} The Slack triage report message
 */
function create(payload, messages, options) {
  let settings = Object.assign({}, DEFAULTS, options);

  let map = getRequest.bind(null, settings);
  let sort = (a, b) => a.priority - b.priority;
  let filter = m => m.emoji && !m.bot;

  let requests = messages.map(map).filter(filter).sort(sort);
  let message = buildMessage(payload, requests, settings);

  return message;
}

/**
 * Get triage request details from a Slack message
 *
 * @param {Object} settings - The triage report settings
 * @param {Object} message - A Slack message
 * @returns {Object} A triage object
 */
function getRequest(settings, message) {
  // the emoji that was matched
  let test = new RegExp(settings.pending.emojis.join('|'));
  let match = message.text.match(test);
  let emoji = match ? match[0] : null;

  // flags based on reactions
  let reactions = (message.reactions || []).map(r => r.name);
  let addressed = settings.addressed.emojis.some(e => reactions.includes(e));
  let review = settings.review.emojis.some(e => reactions.includes(e)) && !addressed;
  let pending = emoji && !review && !addressed;

  let id = message.ts.replace('.', '');                       // deep link id
  let bot = message.subtype === 'bot_message';                // bot posts
  let priority = settings.pending.emojis.indexOf(emoji);      // display order

  return { bot, priority, emoji, looked_at, addressed, pending, id, message };
}

/**
 * Build a Slack triage response
 *
 * @param {Object} settings - The triage report settings
 * @param {Object} payload - The Slack slash command payload
 * @param {Object[]} requests - The triage request details
 * @returns {Object} The Slack triage report message
 */
function buildMessage(payload, requests, settings) {
  let {channel_id, channel_name} = payload;
  let message = { unfurl_links: settings.unfurl_links };
  let publish_test = new RegExp(settings.publish_text, 'i');

  // build display text
  let map = buildSection.bind(null, settings, requests, payload);
  message.text = settings.display.map(map).join('\n\n\n');

  // attach instructions if not publish else make public
  if (publish_test.test(payload.text)) message.response_type = 'in_channel';
  else message.attachments = settings.help;

  return message;
}

/**
 * Build a triage section's text
 *
 * @param {String} name - The section name
 * @param {Object} settings - The triage report settings
 * @param {Object[]} requests - The triage request details
 * @param {Object} payload - The Slack slash command payload
 * @returns {String} The section text
 */
function buildSection(settings, requests, payload, name) {
  let {channel_id, channel_name, team_domain} = payload;
  let baseUrl = `https://${team_domain}.slack.com/archives/${channel_name}/p`;

  let {title} = settings[name];                                     // section title
  let filtered = requests.filter(r => r[name]);                     // filtered list of requests
  let items = filtered.map(r => `:${r.emoji}: ${baseUrl + r.id}`);  // section line item
  let text = [title].concat(items).join('\n');                      // combined text

  // replace template fields
  text = text.replace(/{{count}}/g, filtered.length);
  text = text.replace(/{{channel}}/g, `<#${channel_id}|${channel_name}>`);

  return text;
}

module.exports = create;<commit_msg>change variable name from lookedAt to review in triage.js getRequest return<commit_after>const DEFAULTS = require('./settings.json');

/**
 * Create a triage report
 *
 * @param {Object} payload - The Slack slash command payload
 * @param {Object[]} message - The Slack message history
 * @param {Object} options - (optional) settings overrides
 * @returns {Object} The Slack triage report message
 */
function create(payload, messages, options) {
  let settings = Object.assign({}, DEFAULTS, options);

  let map = getRequest.bind(null, settings);
  let sort = (a, b) => a.priority - b.priority;
  let filter = m => m.emoji && !m.bot;

  let requests = messages.map(map).filter(filter).sort(sort);
  let message = buildMessage(payload, requests, settings);

  return message;
}

/**
 * Get triage request details from a Slack message
 *
 * @param {Object} settings - The triage report settings
 * @param {Object} message - A Slack message
 * @returns {Object} A triage object
 */
function getRequest(settings, message) {
  // the emoji that was matched
  let test = new RegExp(settings.pending.emojis.join('|'));
  let match = message.text.match(test);
  let emoji = match ? match[0] : null;

  // flags based on reactions
  let reactions = (message.reactions || []).map(r => r.name);
  let addressed = settings.addressed.emojis.some(e => reactions.includes(e));
  let review = settings.review.emojis.some(e => reactions.includes(e)) && !addressed;
  let pending = emoji && !review && !addressed;

  let id = message.ts.replace('.', '');                       // deep link id
  let bot = message.subtype === 'bot_message';                // bot posts
  let priority = settings.pending.emojis.indexOf(emoji);      // display order

  return { bot, priority, emoji, review, addressed, pending, id, message };
}

/**
 * Build a Slack triage response
 *
 * @param {Object} settings - The triage report settings
 * @param {Object} payload - The Slack slash command payload
 * @param {Object[]} requests - The triage request details
 * @returns {Object} The Slack triage report message
 */
function buildMessage(payload, requests, settings) {
  let {channel_id, channel_name} = payload;
  let message = { unfurl_links: settings.unfurl_links };
  let publish_test = new RegExp(settings.publish_text, 'i');

  // build display text
  let map = buildSection.bind(null, settings, requests, payload);
  message.text = settings.display.map(map).join('\n\n\n');

  // attach instructions if not publish else make public
  if (publish_test.test(payload.text)) message.response_type = 'in_channel';
  else message.attachments = settings.help;

  return message;
}

/**
 * Build a triage section's text
 *
 * @param {String} name - The section name
 * @param {Object} settings - The triage report settings
 * @param {Object[]} requests - The triage request details
 * @param {Object} payload - The Slack slash command payload
 * @returns {String} The section text
 */
function buildSection(settings, requests, payload, name) {
  let {channel_id, channel_name, team_domain} = payload;
  let baseUrl = `https://${team_domain}.slack.com/archives/${channel_name}/p`;

  let {title} = settings[name];                                     // section title
  let filtered = requests.filter(r => r[name]);                     // filtered list of requests
  let items = filtered.map(r => `:${r.emoji}: ${baseUrl + r.id}`);  // section line item
  let text = [title].concat(items).join('\n');                      // combined text

  // replace template fields
  text = text.replace(/{{count}}/g, filtered.length);
  text = text.replace(/{{channel}}/g, `<#${channel_id}|${channel_name}>`);

  return text;
}

module.exports = create;<|endoftext|>


<commit_before>module.exports = function(){
  var config = require('../configurations/config');
  var mongoose = require('mongoose');
  var log = require('tracer').colorConsole(config.loggingConfig);

  //Mongo DB Database Connection
  mongoose.connect(config.mongoDBconnect, function(err) {
      if (err) {
        log.error(err);
      }
    });
};
<commit_msg>[MinorVersion] Fix Mongoose warning<commit_after>module.exports = function(){
  var config = require('../configurations/config');
  var mongoose = require('mongoose');
  var log = require('tracer').colorConsole(config.loggingConfig);

  //Mongo DB Database Connection
  mongoose.connect(config.mongoDBconnect, { useMongoClient: true }, function(err) {
      if (err) {
        log.error(err);
      }
    });
};
<|endoftext|>