<commit_before> function UGC () {
    // the id of the form in the HTML
    this.formId = arguments[0];

    // the mappings from form field id's to XML content xpath
    this.mappings = {};

    // UCG session
    this.session = null;
    // the content as it was provided from the server
    this.content = null;

    // a copy / clone of the content, used for the modified result
    this.contentClone = null;

    this.OPTIONAL = "OPTIONAL";
    this.UPLOAD = "UPLOAD";

    // element that directly returns the form DOM element after initialization
    this.form = null;
 }

function UGCMapping (ugc, args) {
    // this is the main mapping object that maps a form Id to a content xpath
    this.formId = args[0];
    this.contentPath = args[1];
    this.isUpload = false;
    this.deleteEmptyValue = false;
    this.notEmpty = false;
    if (args.length > 1) {
        // check the additional arguments for further options
        for (i = 2; i < args.length; i++) {
            if (ugc.UPLOAD === args[i]) {
                // mark this as an upload field, which means we don't fill it automatically in the form and content
                this.isUpload = true;
            } else if (ugc.OPTIONAL === args[i]) {
                // decides if an empty value is actually deleted in the modified content,
                // or kept as an empty string (the default)
                // use this for optional values in the XML content that should be fully removed
                // if only an empty string is provided in the form
                this.deleteEmptyValue = true;
            }
            // else { alert("Ignoring: " + args[i]); }
        }
    }
}

UGC.prototype.map = function() {
    // add a new mapping
    var mapping = new UGCMapping(this, arguments);
    // this.debugMap(mapping);
    this.mappings[arguments[0]] = mapping;
}

UGC.prototype.debugMap = function(mapping) {
    alert("Xpath: " + mapping.contentPath + "\nFormId: " +  mapping.formId + "\nDeleteEmpty: " + mapping.deleteEmptyValue + "\nUpload: " + mapping.isUpload);
}

UGC.prototype.debugContent = function(contentArray) {
    var result = "";
    for (var key in contentArray) {
        if (contentArray.hasOwnProperty(key)) {
            var value = contentArray[key];
            result += "Xpath: " + key + "\nValue: " + value + "\n\n";
        }
    }
    alert(result);
}

 UGC.prototype.getForm = function() {
    // check if we have one or more arguments
    if (arguments.length == 1) {
        // lookup the form element with the given name
        return $("#" + this.formId + " :input[name='" + arguments[0] + "']");
    } else if (arguments.length == 0) {
        // zero arguments, return the complete form
        var theForm = $("#" + this.formId);
        if (this.form == null) {
            // set the form DOM access element
            this.form = theForm[0];
        }
        return theForm;
    }
    // no argument returns null
    return null;
};

UGC.prototype.getFormVal = function(name) {
    // lookup the value from the form element with the given name
    return this.getForm(name).val();
};

UGC.prototype.getXpath = function() {
    // check if we have one or more arguments
    if (arguments.length == 1) {
        return this.mappings[arguments[0]].contentPath;
    }
    return null;
}

 UGC.prototype.formHas = function() {
    // check if we have one or more arguments
    if (arguments.length == 1) {
        // single value: lookup the value from the form element with the given name
        return this.getFormVal(arguments[0]).trim().length > 0;
    } else {
        // iterate the array of arguments and check for all with shout-circuit
        for (i = 0; i < arguments.length; i++) {
            if (this.formHasNot(arguments[i])) {
                return false;
            }
        }
        return true;
    }
    // in case of no arguments at all
    return false;
};

 UGC.prototype.formHasNot = function() {
    // check if we have one or more arguments
    if (arguments.length == 1) {
        // single value: lookup the value from the form element with the given name
        return this.getFormVal(arguments[0]).trim().length <= 0;
    } else {
        // iterate the array of arguments and check for all with shout-circuit
        for (i = 0; i < arguments.length; ++i) {
            if (this.formHas(arguments[i])) {
                return false;
            }
        }
        return true;
    }
    // in case of no arguments at all
    return false;
};

 UGC.prototype.formHasOne = function() {
    // check if we have one or more arguments
    if (arguments.length == 1) {
        // single value: lookup the value from the form element with the given name
        return this.formHas(arguments[0]);
    } else {
        // iterate the array of arguments and check for all with shout-circuit
        for (i = 0; i < arguments.length; ++i) {
            if (this.formHas(arguments[i])) {
                return true;
            }
        }
        return false;
    }
    // in case of no arguments at all
    return false;
};

 UGC.prototype.contentHas = function() {
    // check if we have one or more arguments
    if (arguments.length == 1) {
        // single value: lookup the value from the content array
        var value = this.getContent(arguments[0]);
        return (typeof value === "undefined") ? false : true;
    } else {
        // iterate the array of arguments and check for all with shout-circuit
        for (i = 0; i < arguments.length; i++) {
            if (this.contentHasNot(arguments[i])) {
                return false;
            }
        }
        return true;
    }
    // in case of no arguments at all
    return false;
};

 UGC.prototype.contentHasNot = function() {
    // check if we have one or more arguments
    if (arguments.length == 1) {
        // single value: lookup the value from the content array
        var value = this.getContent(arguments[0]);
        return (typeof value === "undefined") ? true : false;
    } else {
        // iterate the array of arguments and check for all with shout-circuit
        for (i = 0; i < arguments.length; i++) {
            if (this.contentHas(arguments[i])) {
                return false;
            }
        }
        return true;
    }
    // in case of no arguments at all
    return false;
};

 UGC.prototype.contentHasOne = function() {
    // check if we have one or more arguments
    if (arguments.length == 1) {
        // single value: lookup the value from the content array
        return this.contentHas(arguments[0]);
    } else {
        // iterate the array of arguments and check for all with shout-circuit
        for (i = 0; i < arguments.length; ++i) {
            if (this.contentHas(arguments[i])) {
                return true;
            }
        }
        return false;
    }
    // in case of no arguments at all
    return false;
};

 UGC.prototype.setForm = function() {
    // check if the name parameter was provided, if not we have to initialize everything later
    if (this.content != null) {
        if (arguments.length == 1) {
            // set the form element with the given name to the content value stored in the mapping with the same name
            this.getForm(arguments[0]).val(this.content[this.mappings[arguments[0]].contentPath]);
        } else if (arguments.length == 2) {
            // set the form element with the given name to the given value
            this.getForm(arguments[0]).val(arguments[1]);
        } else {
            // fill the complete form with all mapped values
            this.fillForm();
        }
    }
};

 UGC.prototype.setContent = function() {
    // check if the name parameter was provided, if not we have to initialize everything later
    var formId = (arguments.length > 0) ? arguments[0] : null;
    if (formId != null) {
        // set the content (clone) value stored in the mapping with the given name to the form element value with the same
        var value = (arguments.length > 1) ? arguments[1] : this.getFormVal(formId);
        var mapping = this.mappings[formId];
        this.contentClone[mapping.contentPath] = value;
        if (value.trim().length <= 0) {
            if (mapping.deleteEmptyValue) {
                this.contentClone[mapping.contentPath] = null;
            }
        }
    } else {
        // no form id provided, set the complete content with all mapped values
        this.fillContent();
    }
};

 UGC.prototype.deleteContent = function(name) {
    if (this.contentClone != null) {
        // delete the content (clone) value stored in the mapping with the given name
        this.contentClone[this.mappings[name].contentPath] = null;
    }
};

 UGC.prototype.deleteParentContent = function(name) {
    if (this.contentClone != null) {
        // delete the content (clone) value stored in the mapping with the given name
        var xpath = this.mappings[name].contentPath;
        var parentName = xpath.substring(0, xpath.lastIndexOf("/"));
        for (var key in this.contentClone) {
            if (this.content.hasOwnProperty(key) && (key.indexOf(parentName) == 0)) {
                delete this.contentClone[key];
            }
        }
        this.contentClone[parentName] = null;
    }
};

 UGC.prototype.getContent = function() {
    // check if we have one or more arguments
    if (arguments.length == 1) {
        // return the selected value from the original content array
        return this.contentClone[this.getXpath(arguments[0])];
    }
    // return the content complete clone map
    return this.contentClone;
};

UGC.prototype.createContentClone = function() {
    // initialize the clone array
    this.contentClone = {};
    if (this.content != null) {
        // copy all the elements from the content to the clone
        for (var key in this.content) {
            if (this.content.hasOwnProperty(key)) {
                this.contentClone[key] = this.content[key];
            }
        }
    }
    // return the generated clone
    return this.contentClone;
}

UGC.prototype.fillForm = function() {
    // iterate over all mappings, fill the form with the mapped values
    for (var key in this.mappings) {
        var mapping = this.mappings[key];
        if (!mapping.isUpload) {
            this.setForm(mapping.formId);
        } // else { alert("Ignoring: " + mapping.contentPath); }
    }
}

UGC.prototype.fillContent = function() {
    // iterate over all mappings, fill the content with values from the mapped form elements
    for (var key in this.mappings) {
        var mapping = this.mappings[key];
        if (!mapping.isUpload) {
            this.setContent(mapping.formId);
        } // else { alert("Ignoring: " + mapping.contentPath); }
    }
}

UGC.prototype.setSession = function() {
    // set the session to the provided parameter
    this.session = arguments[0];
    // initialize the content from the session
    this.content = this.session.getValues();
    if (this.contentClone == null) {
        // initialize the content clone on first call
        this.createContentClone();
    }
};

UGC.prototype.getSession = function() {
    // wrapper for session
    return this.session;
};

UGC.prototype.destroySession = function() {
    // wrapper for session
    if (this.session != null) this.session.destroy();
};

// global UGC variable to avoid context problems when initializing
var globalUGC = null;

UGC.prototype.init = function() {
    // method to be used in callback from UGC main API
    globalUGC.setSession(arguments[0]);
    // initialize the form with the data from the context
    globalUGC.setForm();
};

UGC.prototype.initForm = function() {
    // method to be used for checking if the form exists and initializing the mappings
    if ((arguments.length == 1) && (this.getForm() != null)) {
        // store the used UGC object to access later in the init function
        globalUGC = this;
        // first argument must be the form mapping callback
        arguments[0]();
        return true;
    }
    return false;
};<commit_msg>Improved UGC jQuery object and demo content<commit_after> function UGC () {

    if (arguments.length < 3) {
        alert(
            "UGC requires at least 3 arguments:\n\n" +
            "1: The id of the form in the HTML\n" +
            "2: The mapping callback function\n" +
            "3: The error callback function\n" +
            "4: (optional) The custom form init callback function\n" +
            "5: (optional) The wait indicator callback function"
        );
    }

    this.formId = arguments[0];
    this.mappingsCallback = arguments[1];
    this.errorCallback = arguments[2];
    this.formInitCallback = arguments.length > 3 ? arguments[3] : null;
    this.waitIndicatorCallback = arguments.length > 4 ? arguments[4] : null;

    // the mappings from form field id's to XML content xpath
    this.mappings = {};

    // UCG session
    this.session = null;
    // the content as it was provided from the server
    this.content = null;

    // a copy / clone of the content, used for the modified result
    this.contentClone = null;

    this.OPTIONAL = "OPTIONAL";
    this.UPLOAD = "UPLOAD";

    // element that directly returns the form DOM element after initialization
    this.form = null;
 }

function UGCMapping (ugc, args) {
    // this is the main mapping object that maps a form Id to a content xpath
    this.formId = args[0];
    this.contentPath = args[1];
    this.isUpload = false;
    this.deleteEmptyValue = false;
    this.notEmpty = false;
    if (args.length > 1) {
        // check the additional arguments for further options
        for (i = 2; i < args.length; i++) {
            if (ugc.UPLOAD === args[i]) {
                // mark this as an upload field, which means we don't fill it automatically in the form and content
                this.isUpload = true;
            } else if (ugc.OPTIONAL === args[i]) {
                // decides if an empty value is actually deleted in the modified content,
                // or kept as an empty string (the default)
                // use this for optional values in the XML content that should be fully removed
                // if only an empty string is provided in the form
                this.deleteEmptyValue = true;
            }
            // else { alert("Ignoring: " + args[i]); }
        }
    }
}

UGC.prototype.map = function() {
    // add a new mapping
    var mapping = new UGCMapping(this, arguments);
    // this.debugMap(mapping);
    this.mappings[arguments[0]] = mapping;
}

UGC.prototype.debugMap = function(mapping) {
    alert("Xpath: " + mapping.contentPath + "\nFormId: " +  mapping.formId + "\nDeleteEmpty: " + mapping.deleteEmptyValue + "\nUpload: " + mapping.isUpload);
}

UGC.prototype.debugContent = function(contentArray) {
    var result = "";
    for (var key in contentArray) {
        if (contentArray.hasOwnProperty(key)) {
            var value = contentArray[key];
            result += "Xpath: " + key + "\nValue: " + value + "\n\n";
        }
    }
    alert(result);
}

 UGC.prototype.getForm = function() {
    // check if we have one or more arguments
    if (arguments.length == 1) {
        // lookup the form element with the given name
        return $("#" + this.formId + " :input[name='" + arguments[0] + "']");
    } else if (arguments.length == 0) {
        // zero arguments, return the complete form
        var theForm = $("#" + this.formId);
        if (this.form == null) {
            // set the form DOM access element
            this.form = theForm[0];
        }
        return theForm;
    }
    // no argument returns null
    return null;
};

UGC.prototype.getFormVal = function(name) {
    // lookup the value from the form element with the given name
    return this.getForm(name).val();
};

UGC.prototype.getXpath = function() {
    // check if we have one or more arguments
    if (arguments.length == 1) {
        return this.mappings[arguments[0]].contentPath;
    }
    return null;
}

 UGC.prototype.formHas = function() {
    // check if we have one or more arguments
    if (arguments.length == 1) {
        // single value: lookup the value from the form element with the given name
        return this.getFormVal(arguments[0]).trim().length > 0;
    } else {
        // iterate the array of arguments and check for all with shout-circuit
        for (i = 0; i < arguments.length; i++) {
            if (this.formHasNot(arguments[i])) {
                return false;
            }
        }
        return true;
    }
    // in case of no arguments at all
    return false;
};

 UGC.prototype.formHasNot = function() {
    // check if we have one or more arguments
    if (arguments.length == 1) {
        // single value: lookup the value from the form element with the given name
        return this.getFormVal(arguments[0]).trim().length <= 0;
    } else {
        // iterate the array of arguments and check for all with shout-circuit
        for (i = 0; i < arguments.length; ++i) {
            if (this.formHas(arguments[i])) {
                return false;
            }
        }
        return true;
    }
    // in case of no arguments at all
    return false;
};

 UGC.prototype.formHasOne = function() {
    // check if we have one or more arguments
    if (arguments.length == 1) {
        // single value: lookup the value from the form element with the given name
        return this.formHas(arguments[0]);
    } else {
        // iterate the array of arguments and check for all with shout-circuit
        for (i = 0; i < arguments.length; ++i) {
            if (this.formHas(arguments[i])) {
                return true;
            }
        }
        return false;
    }
    // in case of no arguments at all
    return false;
};

 UGC.prototype.contentHas = function() {
    // check if we have one or more arguments
    if (arguments.length == 1) {
        // single value: lookup the value from the content array
        var value = this.getContent(arguments[0]);
        return (typeof value === "undefined") ? false : true;
    } else {
        // iterate the array of arguments and check for all with shout-circuit
        for (i = 0; i < arguments.length; i++) {
            if (this.contentHasNot(arguments[i])) {
                return false;
            }
        }
        return true;
    }
    // in case of no arguments at all
    return false;
};

 UGC.prototype.contentHasNot = function() {
    // check if we have one or more arguments
    if (arguments.length == 1) {
        // single value: lookup the value from the content array
        var value = this.getContent(arguments[0]);
        return (typeof value === "undefined") ? true : false;
    } else {
        // iterate the array of arguments and check for all with shout-circuit
        for (i = 0; i < arguments.length; i++) {
            if (this.contentHas(arguments[i])) {
                return false;
            }
        }
        return true;
    }
    // in case of no arguments at all
    return false;
};

 UGC.prototype.contentHasOne = function() {
    // check if we have one or more arguments
    if (arguments.length == 1) {
        // single value: lookup the value from the content array
        return this.contentHas(arguments[0]);
    } else {
        // iterate the array of arguments and check for all with shout-circuit
        for (i = 0; i < arguments.length; ++i) {
            if (this.contentHas(arguments[i])) {
                return true;
            }
        }
        return false;
    }
    // in case of no arguments at all
    return false;
};

 UGC.prototype.setForm = function() {
    // check if the name parameter was provided, if not we have to initialize everything later
    if (this.content != null) {
        if (arguments.length == 1) {
            // set the form element with the given name to the content value stored in the mapping with the same name
            this.getForm(arguments[0]).val(this.content[this.mappings[arguments[0]].contentPath]);
        } else if (arguments.length == 2) {
            // set the form element with the given name to the given value
            this.getForm(arguments[0]).val(arguments[1]);
        } else {
            // fill the complete form with all mapped values
            this.fillForm();
        }
    }
};

 UGC.prototype.setContent = function() {
    // check if the name parameter was provided, if not we have to initialize everything later
    var formId = (arguments.length > 0) ? arguments[0] : null;
    if (formId != null) {
        // set the content (clone) value stored in the mapping with the given name to the form element value with the same
        var value = (arguments.length > 1) ? arguments[1] : this.getFormVal(formId);
        var mapping = this.mappings[formId];
        this.contentClone[mapping.contentPath] = value;
        if (value.trim().length <= 0) {
            if (mapping.deleteEmptyValue) {
                this.contentClone[mapping.contentPath] = null;
            }
        }
    } else {
        // no form id provided, set the complete content with all mapped values
        this.fillContent();
    }
};

 UGC.prototype.deleteContent = function(name) {
    if (this.contentClone != null) {
        // delete the content (clone) value stored in the mapping with the given name
        this.contentClone[this.mappings[name].contentPath] = null;
    }
};

 UGC.prototype.deleteParentContent = function(name) {
    if (this.contentClone != null) {
        // delete the content (clone) value stored in the mapping with the given name
        var xpath = this.mappings[name].contentPath;
        var parentName = xpath.substring(0, xpath.lastIndexOf("/"));
        for (var key in this.contentClone) {
            if (this.content.hasOwnProperty(key) && (key.indexOf(parentName) == 0)) {
                delete this.contentClone[key];
            }
        }
        this.contentClone[parentName] = null;
    }
};

 UGC.prototype.getContent = function() {
    // check if we have one or more arguments
    if (arguments.length == 1) {
        // return the selected value from the original content array
        return this.contentClone[this.getXpath(arguments[0])];
    }
    // return the content complete clone map
    return this.contentClone;
};

UGC.prototype.createContentClone = function() {
    // initialize the clone array
    this.contentClone = {};
    if (this.content != null) {
        // copy all the elements from the content to the clone
        for (var key in this.content) {
            if (this.content.hasOwnProperty(key)) {
                this.contentClone[key] = this.content[key];
            }
        }
    }
    // return the generated clone
    return this.contentClone;
}

UGC.prototype.fillForm = function() {
    // iterate over all mappings, fill the form with the mapped values
    for (var key in this.mappings) {
        var mapping = this.mappings[key];
        if (!mapping.isUpload) {
            this.setForm(mapping.formId);
        } // else { alert("Ignoring: " + mapping.contentPath); }
    }
}

UGC.prototype.fillContent = function() {
    // iterate over all mappings, fill the content with values from the mapped form elements
    for (var key in this.mappings) {
        var mapping = this.mappings[key];
        if (!mapping.isUpload) {
            this.setContent(mapping.formId);
        } // else { alert("Ignoring: " + mapping.contentPath); }
    }
}

UGC.prototype.setSession = function() {
    // set the session to the provided parameter
    this.session = arguments[0];
    // initialize the content from the session
    this.content = this.session.getValues();
    if (this.contentClone == null) {
        // initialize the content clone on first call
        this.createContentClone();
    }
};

UGC.prototype.getSession = function() {
    // wrapper for session
    return this.session;
};

UGC.prototype.destroySession = function() {
    // wrapper for session
    if (this.session != null) this.session.destroy();
};

// global UGC variable to avoid context problems when initializing
var globalUGC = null;

UGC.prototype.initSession = function() {
    // method to be used in callback from UGC main API
    globalUGC.setSession(arguments[0]);
    // initialize the form with the data from the context
    globalUGC.setForm();
    if (globalUGC.formInitCallback != null) {
        // custom user form initialization
        globalUGC.formInitCallback();
    }
};

UGC.prototype.init = function() {
    // initialize the mappings
    this.mappingsCallback();
    // initialize the user generated content API
    var sessionId = arguments[0];
    if (this.waitIndicatorCallback != null) {
        OpenCmsXmlContentFormApi.setWaitIndicatorCallback(this.waitIndicatorCallback);
    }
    OpenCmsXmlContentFormApi.initFormForSession(sessionId, this.form, this.initSession, this.errorCallback);
};

UGC.prototype.setWaitIndicator = function() {
    // set the wait indicator callback
    this.waitIndicatorCallback = arguments[0];
}

UGC.prototype.setMappings = function() {
    // set the wait indicator callback
    this.mappingsCallback = arguments[0];
}

UGC.prototype.setError = function() {
    // set the wait indicator callback
    this.errorCallback = arguments[0];
}

UGC.prototype.setFormInit = function() {
    // set the wait indicator callback
    this.formInitCallback = arguments[0];
}

UGC.prototype.initForm = function() {
    // method to be used for checking if the form exists and initializing the mappings
    if ((arguments.length == 0) && (this.getForm() != null)) {
        // store the used UGC object to access later in the init function
        globalUGC = this;
        return true;
    }
    return false;
};

UGC.prototype.uploadFiles = function() {
    // convenience wrapper to access "uploadFiles" in the UGC session
    if (arguments.length != 2) {
        alert(
            "UGC.uploadFiles requires 2 arguments:\n\n" +
            "1: Array of id's that indicate the fields with the file uploads\n" +
            "2: The after upload handler function callback"
        );
    }
    this.getSession().uploadFiles(arguments[0], arguments[1], this.errorCallback);
}

UGC.prototype.saveContent = function() {
    // convenience wrapper to access "saveContent" in the UGC session
    if (arguments.length != 2) {
        alert(
            "UGC.saveContent requires 2 arguments:\n\n" +
            "1: Content object to save\n" +
            "2: The after save handler function callback"
        );
    }
    this.getSession().saveContent(arguments[0], arguments[1], this.errorCallback);
}

UGC.prototype.validate = function() {
    // convenience wrapper to access "validate" in the UGC session
    if (arguments.length != 2) {
        alert(
            "UGC.validate requires 2 arguments:\n\n" +
            "1: Content object to validate\n" +
            "2: The validation results handler function callback"
        );
    }
    this.getSession().validate(arguments[0], arguments[1]);
}
<|endoftext|>


<commit_before>function getInput(name) {
    return $('#' + name).val();
}
function getInputAsPercent(name) {
    return getInput(name) / 100;
}

function buildURL() {
    var base_URL =  "http://localhost:4001/api/d3/amort";

    var term = $('#termbtn').text();
    if (term.indexOf("Year") != -1)
        base_URL += '/year?';
    else
        base_URL += "?";

    var rate = "r=" + getInputAsPercent('r'); // $('#r').val() / 100);
    var prin = "&P=" + getInput('P'); // $('#P').val();
    var num = "&n=" + getInput('n'); // $('#n').val();
    var taxes = "&t=" + getInput('t'); // $('#t').val();
    var ins = "&i=" + getInput('i'); //$('#i').val();

    URL = base_URL + rate + prin + num + taxes + ins;

    if ($('#arm_type').is(':checked')) {
        var adj_freq = "&af=" + getInput('af'); // $('#af').val();
        var adj_cap = "&ac=" + getInputAsPercent('ac'); // $('#ac').val() / 100);
        var life_cap = "&lc=" + getInputAsPercent('lc'); // $('#lc').val() / 100);

        URL += adj_freq + adj_cap + life_cap;
    }

    return [URL, term];
}

function addToChart() {
    name = prompt("Please name this mortgage: ", "Mortgage 1");

    if (name != 'null') {
        $('#myTable').show();
        $('#myTable tr:last').after('
')
            .after('' + getInput('t') + '	')
            .after('' + getInputAsPercent('r') + '	')
            .after('' + getInput('P') + '	')
            .after('' + name + '	')
            .after('
');
    }
}

function submitUpdate() {
    val = buildURL();
    URL = val[0];
    term = val[1];

    d3.json(URL, function(error, json) {
        if (error) return console.warn(error);
        var data = json;

        nv.addGraph(function() {
            var chart1 = nv.models.lineChart()
                .x(function(d) { return d[0] })
                .y(function(d) { return d[1] });

            chart1.xAxis
                .axisLabel(term)
                .tickFormat(d3.format("d"));

            chart1.yAxis
                .axisLabel("Dollars")
                .tickFormat(d3.format(",.2f"));

            d3.select("#chart1 svg")
                .datum(data)
                .transition().duration(500).call(chart1);

            nv.utils.windowResize(chart1.update);

            return chart1;
        });
    });
}

// initial display of the chart
submitUpdate();<commit_msg>Feature to add mortgages to chart done!<commit_after>var dataSet = [];

function getInput(name) {
    return $('#' + name).val();
}
function getInputAsPercent(name) {
    return getInput(name) / 100;
}

function buildURL() {
    var base_URL =  "http://localhost:4001/api/d3/amort";

    var term = $('#termbtn').text();
    if (term.indexOf("Year") != -1)
        base_URL += '/year?';
    else
        base_URL += "?";

    var rate = "r=" + getInputAsPercent('r'); // $('#r').val() / 100);
    var prin = "&P=" + getInput('P'); // $('#P').val();
    var num = "&n=" + getInput('n'); // $('#n').val();
    var taxes = "&t=" + getInput('t'); // $('#t').val();
    var ins = "&i=" + getInput('i'); //$('#i').val();

    URL = base_URL + rate + prin + num + taxes + ins;

    if ($('#arm_type').is(':checked')) {
        var adj_freq = "&af=" + getInput('af'); // $('#af').val();
        var adj_cap = "&ac=" + getInputAsPercent('ac'); // $('#ac').val() / 100);
        var life_cap = "&lc=" + getInputAsPercent('lc'); // $('#lc').val() / 100);

        URL += adj_freq + adj_cap + life_cap;
    }

    return [URL, term];
}

function addToChart(add) {
    name = prompt("Please name this mortgage: ", "Mortgage 1");
    add = typeof add !== 'undefined' ? add : true;

    if (name != 'null') {
        $('#myTable').show();
        $('#myTable tr:last').after('
')
            .after('' + getInput('t') + '	')
            .after('' + getInputAsPercent('r') + '	')
            .after('' + getInput('P') + '	')
            .after('' + name + '	')
            .after('
');

        submitUpdate(name, add);
    }
}

function submitUpdate(name, add) {
    // default for name
    name = typeof name !== 'undefined' ? name : "";
    add = typeof add !== 'undefined' ? add : false;

    val = buildURL();
    URL = val[0];
    term = val[1];

    d3.json(URL, function(error, json) {
        if (error) return console.warn(error);

        if (add) {
            json.forEach(function(d) {
                var new_key = name + " " + d['key'];
                console.debug("Old key: " + d['key'] + " New key: " + new_key);
                d['key'] = new_key;

                dataSet.push(d);
            });
        } else {
            dataSet = json;
        }

        console.info("Length " + dataSet.length);

        nv.addGraph(function() {
            var chart1 = nv.models.lineChart()
                .x(function(d) { return d[0] })
                .y(function(d) { return d[1] });

            chart1.xAxis
                .axisLabel(term)
                .tickFormat(d3.format("d"));

            chart1.yAxis
                .axisLabel("Dollars")
                .tickFormat(d3.format(",.2f"));

            d3.select("#chart1 svg")
                .datum(dataSet)
                .transition().duration(500).call(chart1);

            nv.utils.windowResize(chart1.update);

            return chart1;
        });
    });
}

// initial display of the chart
//submitUpdate();<|endoftext|>


<commit_before>#!/usr/bin/env node
/* eslint-env node, es6 */

require('shelljs/global');

var chalk = require('chalk'),
    async = require('async'),
    _ = require('lodash'),
    fs = require('fs'),
    path = require('path'),
    Mocha = require('mocha'),

    SPEC_SOURCE_DIR = path.join(__dirname, '..', 'test', 'system'),

    /**
     * Load a JSON from file synchronously
     *
     * @param {String} file
     * @returns {String}
     */
    loadJSON = function (file) {
        return JSON.parse(fs.readFileSync(path.join(__dirname, file)).toString());
    };

module.exports = function (exit) {
    // banner line
    console.log(chalk.yellow.bold('\nRunning system tests using mocha and nsp...'));

    async.series([
        // ensure all dependencies are okay
        function (next) {
            console.log(chalk.yellow('checking package dependencies...\n'));

            exec('dependency-check ./package.json --extra --no-dev --missing', next);
        },

        // run test specs using mocha
        function (next) {
            var mocha = new Mocha();

            console.log(chalk.yellow('running system specs using mocha...\n'));
            fs.readdir(SPEC_SOURCE_DIR, function (err, files) {
                if (err) { return next(err); }

                files.filter(function (file) {
                    return (file.substr(-8) === '.test.js');
                }).forEach(function (file) {
                    mocha.addFile(path.join(SPEC_SOURCE_DIR, file));
                });

                // start the mocha run
                mocha.run(next);
                mocha = null; // cleanup
            });
        },

        // execute nsp
        // programmatically executing nsp is a bit tricky as we have to emulate the cli script's usage of internal
        // nsp functions.
        function (next) {
            var nsp = require('nsp'),
                pkg = loadJSON('../package.json'),
                nsprc = loadJSON('../.nsprc');

            console.log(chalk.yellow('processing nsp for security vulnerabilities...\n'));

            // we do not pass full package for privacy concerns and also to add the ability to ignore exclude packages,
            // hence we customise the package before we send it
            nsp.check({
                offline: false,
                package: {
                    name: pkg.name,
                    dependencies: _.omit(pkg.dependencies, _.keys(nsprc.exclusions))
                }
            }, function (err, result) {
                // if processing nsp had an error, simply print that and exit
                if (err) {
                    console.error(chalk.red('There was an error processing NSP!\n') + chalk.gray(err.message || err) +
                        '\n\nSince NSP server failure is not a blocker for tests, tests are not marked as failure!');
                    return next();
                }

                // in case an nsp violation is found, we raise an error
                if (result.length) {
                    console.error(nsp.formatters.default(err, result));
                    return next(1);
                }

                console.log(chalk.green('nsp ok!\n'));
                return next();
            });
        }
    ], exit);
};

// ensure we run this script exports if this is a direct stdin.tty run
!module.parent && module.exports(exit);
<commit_msg>Added global chai `expect` for system tests and removed nsp checks<commit_after>#!/usr/bin/env node
/* eslint-env node, es6 */

require('shelljs/global');

var chalk = require('chalk'),
    async = require('async'),
    fs = require('fs'),
    path = require('path'),

    expect = require('chai').expect,
    Mocha = require('mocha'),

    SPEC_SOURCE_DIR = path.join(__dirname, '..', 'test', 'system');

module.exports = function (exit) {
    // banner line
    console.log(chalk.yellow.bold('\nRunning system tests using mocha...'));

    async.series([
        // ensure all dependencies are okay
        function (next) {
            console.log(chalk.yellow('checking package dependencies...\n'));

            exec('dependency-check ./package.json --extra --no-dev --missing', next);
        },

        // run test specs using mocha
        function (next) {
            var mocha = new Mocha();

            console.log(chalk.yellow('running system specs using mocha...\n'));
            fs.readdir(SPEC_SOURCE_DIR, function (err, files) {
                if (err) { return next(err); }

                files.filter(function (file) {
                    return (file.substr(-8) === '.test.js');
                }).forEach(function (file) {
                    mocha.addFile(path.join(SPEC_SOURCE_DIR, file));
                });

                // start the mocha run
                global.expect = expect; // for easy reference

                mocha.run(function (err) {
                    // clear references and overrides
                    delete global.expect;

                    err && console.error(err.stack || err);
                    next(err ? 1 : 0);
                });
                // cleanup
                mocha = null;
            });
        }
    ], exit);
};

// ensure we run this script exports if this is a direct stdin.tty run
!module.parent && module.exports(exit);
<|endoftext|>


<commit_before>class Registrant {

  constructor( eth, eos = "", balance = 0 ){
    // let {unclaimed, wallet, recovered} = balances
    this.eth      = eth
    this.eos      = eos
    this.balance  = typeof balance == 'object' ? balance : new Balance()
    this.accepted = null
    this.error    = false
  }

  accept ( callback ) {
    this.accepted = true
  }

  reject ( error ) {
    if(!error) return;
    this.error    = error
    this.accepted = false
  }

  is_accepted () {
    return this.accepted === true
  }

}

class Transaction {

  constructor( eth, tx, type = "transfer", amount ) {
    this.eth     = eth
    this.hash    = tx
    this.amount  = amount
    this.claimed = false
    this.type    = type
  }

  claim( eth ) {
    return ( eth == this.eth )
      ? this.claimed = true
      : log("error", `${eth} should't be claiming ${this.eth}'s transaction`)
  }

}

class RejectedRegistrant extends Registrant {
  constructor( error, registrant ) {

    const { eth, eos, balance } = registrant

    super( registrant.eth, registrant.eos, registrant.balance )

    this.error             = error

  }
}

class Balance {

  constructor(){
    this.wallet    = web3.toBigNumber(0)
    this.unclaimed = web3.toBigNumber(0)
    this.reclaimed = web3.toBigNumber(0)
    this.total     = web3.toBigNumber(0)
  }

  set( type, balance ){
    this[ type ] = balance
    return this //chaining
  }

  add( type, balance ){
    this['type'].plus( balance )
  }

  readable( type = 'total' ){
    this[ type ] = formatEOS( this[ type ] )
  }

  exists( type ){
    return (typeof this[ type ] !== "undefined" && this[type].gt( 0 ))
  }

  get( type ){
    return (typeof this[ type ] !== "undefined" && this[type].gt( 0 )) ? this[type] : false;
  }

  sum(){
    this.total = this.wallet.plus(this.unclaimed).plus(this.reclaimed)
  }
}
<commit_msg>move acceptance/rejection in Registrant scope<commit_after>class Registrant {

  constructor( eth, eos = "", balance = 0 ){
    // let {unclaimed, wallet, recovered} = balances
    this.eth      = eth
    this.eos      = eos
    this.balance  = typeof balance == 'object' ? balance : new Balance()
    this.accepted = null
    this.error    = false
    this.index    = null
  }

  accept ( callback ) {
    this.accepted = true

    log("message", `[#${this.index}] accepted ${this.eth} => ${this.eos} => ${ this.balance.total.toFormat(4) }`)
  }

  reject () {
    this.accepted = false

    let msg = ""
    if(this.balance.exists('reclaimed'))
      log("reject", `[#${this.index}] rejected ${this.eth} => ${this.eos} => ${this.balance.total.toFormat(4)} => ${this.error} ( ${this.balance.reclaimed.toFormat(4)} reclaimed EOS tokens moved back to Reclaimable )`)
    else
      log("reject", `[#${this.index}] rejected ${this.eth} => ${this.eos} => ${this.balance.total.toFormat(4)} => ${this.error}`)
  }

  test() {
    return this.valid() ? this.accept() : this.reject()
  }

    // Reject bad keys and zero balances, elseif was fastest? :/
  valid() {

    //Reject 0 balances
    if( formatEOS( this.balance.total ) === "0.0000" ) {
      this.error = 'balance_is_zero'
    }

    //Everything else
    else if(!this.eos.startsWith('EOS')) {

      //It's an empty key
      if(this.eos.length == 0) {
        this.error = 'key_is_empty'
      }

      //It may be an EOS private key
      else if(this.eos.startsWith('5')) {
        this.error = 'key_is_private'
      }

      // It almost looks like an EOS key // #TODO ACTUALLY VALIDATE KEY?
      else if(this.eos.startsWith('EOS') && this.eos.length != 53) {
        this.error = 'key_is_malformed'
      }

      // ETH address
      else if(this.eos.startsWith('0x')) {
        this.error = 'key_is_eth'
      }

      //Reject everything else with label malformed
      else {
        this.error = 'key_is_junk'
      }
    }

    //Accept BTS and STM keys, assume advanced users and correct format
    if(this.eos.startsWith('BTS') || this.eos.startsWith('STM')) {
      this.error = false
    }

    return !this.error ? true : false;

  }

  is_accepted () {
    return this.accepted === true
  }

}

class Transaction {

  constructor( eth, tx, type = "transfer", amount ) {
    this.eth     = eth
    this.eos     = null
    this.hash    = tx
    this.amount  = amount
    this.claimed = false
    this.type    = type
  }

  claim( eth ) {
    return ( eth == this.eth )
      ? this.claimed = true
      : log("error", `${eth} should't be claiming ${this.eth}'s transaction`)
  }

}

class RejectedRegistrant extends Registrant {
  constructor( error, registrant ) {

    const { eth, eos, balance } = registrant

    super( registrant.eth, registrant.eos, registrant.balance )

    this.error             = error

  }
}

class Balance {

  constructor(){
    this.wallet    = web3.toBigNumber(0)
    this.unclaimed = web3.toBigNumber(0)
    this.reclaimed = web3.toBigNumber(0)
    this.total     = web3.toBigNumber(0)
  }

  set( type, balance ){
    this[ type ] = balance
    return this //chaining
  }

  add( type, balance ){
    this['type'].plus( balance )
  }

  readable( type = 'total' ){
    this[ type ] = formatEOS( this[ type ] )
  }

  exists( type ){
    return (typeof this[ type ] !== "undefined" && this[type].gt( 0 ))
  }

  get( type ){
    return (typeof this[ type ] !== "undefined" && this[type].gt( 0 )) ? this[type] : false;
  }

  sum(){
    this.total = this.wallet.plus(this.unclaimed).plus(this.reclaimed)
  }
}
<|endoftext|>


<commit_before>'use strict'

const {encode, isFunction, isString, isObject} = require('./helpers')

module.exports = class Validations {
  constructor (client, promotionsNamespace) {
    this.client = client
    this.promotions = promotionsNamespace
  }

  validateVoucher (code, params = {}, callback = null) {
    if (isFunction(params)) {
      callback = params
      params = {}
    }

    return this.client.post(`/vouchers/${encode(code)}/validate`, params, callback)
  }

  validate (code, context = {}, callback = null) {
    if (isObject(code)) {
      if (isFunction(context)) {
        callback = context
      }
      return this.promotions.validate(code, callback)
    }

    return this.validateVoucher(code, context, callback)
  }
}
<commit_msg>Remove useless import<commit_after>'use strict'

const {encode, isFunction, isObject} = require('./helpers')

module.exports = class Validations {
  constructor (client, promotionsNamespace) {
    this.client = client
    this.promotions = promotionsNamespace
  }

  validateVoucher (code, params = {}, callback = null) {
    if (isFunction(params)) {
      callback = params
      params = {}
    }

    return this.client.post(`/vouchers/${encode(code)}/validate`, params, callback)
  }

  validate (code, context = {}, callback = null) {
    if (isObject(code)) {
      if (isFunction(context)) {
        callback = context
      }
      return this.promotions.validate(code, callback)
    }

    return this.validateVoucher(code, context, callback)
  }
}
<|endoftext|>


<commit_before><commit_msg>match and consume methods return this<commit_after><|endoftext|>


<commit_before>/**
 * Created by Dean on 6/21/2015.
 */

var QUESTIFY = (function (QUESTIFY) {
	"use strict";
	function createAtomicAction (preCondition, postCondition) {
		var that = {},
			started = false,
			finished = false;

		that.preCondition = preCondition;
		that.postCondition = postCondition;

		that.preConditionMet = function () {
			return this.preCondition() === true;
		};
		that.postConditionMet = function () {
			return this.postCondition() === true;
		};

		that.start = function () {
			started = true;
		};

		that.finish = function () {
			finished = true;
		};

		that.isStarted = function () {
			return started === true;
		};

		that.isFinished = function () {
			return finished === true;
		};

		that.withArguments = function(pre, post) {
			var newValue = {};
			newValue.preCondition = this.preCondition;
			newValue.postCondition = this.postCondition;
			newValue.preConditionMet = this.preConditionMet;
			newValue.postConditionMet = this.postConditionMet;
			newValue.start = this.start;
			newValue.finish = this.finish;
			newValue.isStarted = this.isStarted;
			newValue.isFinished = this.isFinished;
			newValue.started = false;
			newValue.finished = false;

			newValue.preConditionArguments = pre;
			newValue.postConditionArguments = post;

			return newValue;
		};

		return that;
	}

	QUESTIFY.createAtomicAction = createAtomicAction;

	return QUESTIFY;
}(QUESTIFY || {}));<commit_msg>Reworked to accept various #'s of conditions<commit_after>/**
 * Created by Dean on 6/21/2015.
 */

var QUESTIFY = (function (QUESTIFY) {
	"use strict";
	function createAtomicAction (conditions) {
		var that = {},
			started = false,
			finished = false;

		that.conditions = conditions;

		that.start = function () {
			started = true;
		};

		that.forceFinish = function () {
			finished = true;
		};

		that.isStarted = function () {
			return started === true;
		};

		that.isFinished = function () {
			return finished === true;
		};

		that.update = function() {
			finished = true;

			if (!this.isStarted()) { this.start(); }

			for (var c = 0, cl = this.conditions.length; c < cl; c++) {
				if (this.conditions[c]() !== true) {
					finished = false;
				}
			}

			return finished;
		};

		that.withArguments = function(conditionArguments) {
			var newValue = {};

			//Rebinding the conditions creates new functions,
			//guaranteeing we aren't going to overwrite functions
			newValue.conditions = (function (bindTo, conditionsArg) {
				var boundConditions = [];
				for (var c = 0, cl = conditionsArg.length; c < cl; c++) {
					boundConditions.push(conditionsArg[c].bind(bindTo));
				}
				return boundConditions;
			}(this, this.conditions));

			newValue.start = this.start;
			newValue.forceFinish = this.forceFinish;
			newValue.isStarted = this.isStarted;
			newValue.isFinished = this.isFinished;
			newValue.update = this.update;
			newValue.started = false;
			newValue.finished = false;

			newValue.conditionArguments = conditionArguments;

			return newValue;
		};

		return that;
	}

	QUESTIFY.createAtomicAction = createAtomicAction;

	return QUESTIFY;
}(QUESTIFY || {}));<|endoftext|>


<commit_before>var async = require('async');
var chalk = require('chalk');
var chai = require("chai");
var expect = chai.expect;
var inspect = require("util").inspect;

var Cluster = require('../cluster');
var cluster;

var ERROR_THRESHOLD = 10;

function SIGN_COLOR(value, threshold, inverse) {
    var scavenge = value, color = "black";
    // If value is string account for single character pre/postfix (very specific/awful implementation)
    if(typeof value === 'string') {
        // Ignore First & Last Chars
        if(typeof value[0] === 'string') value = value.substring(1);
        if(typeof value[value.length - 1] === 'string') value = value.substr(0, scavenge.length - 2);
        // Ends with MS
        if(value.slice(-2) === 'ms') value = value.substr(0, scavenge.length - 3);
        value = parseFloat(value);
    }
    if(!threshold) threshold = 0;
    if(inverse) color = (value > threshold)?'red':((value < threshold)?'green':'yellow');
    else color = (value > threshold)?'green':((value < threshold)?'red':'yellow');

    return chalk[color](scavenge);
}

function NANO_TO_MS(val, decimals) {
    var m = Math.pow(10, (decimals || 3));
    return Math.round((val/1e+6) * m)/m;
}

function REDUCE_STATS(array) {
    var MIN = Math.min.apply(Math, array), MAX = Math.max.apply(Math, array);
    var SUM = array.reduce(function(a, b) { return a + b; });
    var AVG = SUM / array.length;
    for(var i=0; i<array.length; i++) {

    }
    return {
        min: MIN,
        max: MAX,
        average: AVG,
        error: Math.round((Math.abs(AVG - MIN)/Math.abs(MIN) + Math.abs(AVG - MAX)/Math.abs(MAX))/2 * 100000)/1000,
        sum: SUM,
        total: array.length
    };
}

function MAKE_BENCHMARK(func, options, callback) {
    var count = 0;
    var stats = [];
    var Total_Started = process.hrtime();
    async.doWhilst(function BENCHMARK_WRAPPER(callback){
        count++;
        function BENCHMARK_CALLBACK(unique_callback){
            var started = process.hrtime();
            return function BENCHMARK_CALLBACK__FUNC(error) {
                var finished = process.hrtime(started);
                // Calculate Time Difference
                var diff = finished[0] * 1e9 + finished[1];
                // Push difference to stats
                stats.push(diff);
                unique_callback(error, stats);
            };
        }
        if(options.parallel) {
            // Parallelize on all cores
            async.times(options.parallel, function(n, parallel_callback){
                func(BENCHMARK_CALLBACK(parallel_callback));
            }, callback);
        }else{
            func(BENCHMARK_CALLBACK(callback));
        }
    }, function BENCHMARK_ITERATOR(){
        return count < (options.iterations || 10);
    }, function BENCHMARK_RESULTS(error){
        var Reduced = REDUCE_STATS(stats);
        var Total_Finished = process.hrtime(Total_Started);
        // Calculate Time Difference
        Reduced.overall = Total_Finished[0] * 1e9 + Total_Finished[1];
        callback(error, Reduced);
    });
}

function OUTPUT_BENCHMARK(func, options, callback) {
    function LOG() {
        // Mocha ident
        var prepend = "    ";
        var args = Array.prototype.slice.call(arguments);
        args.unshift(prepend);
        args = args.map(function(v){
            // Add prepend after all new lines created with \n\r ...
            if(typeof v === 'string') v = v.replace(/(?:\r\n|\r|\n)/g, "\n" + prepend);
            return chalk.gray(v);
        });
        console.log.apply(console, args);
    }
    MAKE_BENCHMARK(func, options, function(error, stats) {
        LOG("\n" + chalk.green('√'), chalk.white("BENCHMARK RESULTS FOR"), chalk.cyan(func.name || 'Unknown'));
        if(error) {
            LOG(chalk.red("> BENCHMARK FAILED <"));
            console.trace(error);
        }else{
            LOG("\tAveraged at", NANO_TO_MS(stats.average) + 'ms', SIGN_COLOR("±" + stats.error + '%', options.threshold || ERROR_THRESHOLD, true));
            LOG("\tWorst Case:", NANO_TO_MS(stats.max) + 'ms', "Best Case:", NANO_TO_MS(stats.min) + 'ms');
            LOG("\tTotal time:", NANO_TO_MS(stats.overall) + 'ms', "for", stats.total, "rounds");
        }
        LOG();
        if(callback) callback(error, stats);
    });
}

// Finish the compare method
/*function COMPARE_BENCHMARK(funcs, iterations, callback) {
    async.series(funcs, function BENCHMARK_COMPARER(error, results) {

    });
}*/

describe("Init Test Suite", function() {
    this.timeout(20000);
    it('should construct an instance', function() {
        cluster = new Cluster();
        cluster.deploy();
    });
    it('should run tasks on the cluster with arguments', function(done) {
        cluster.addShared('multiply', 'module.exports = function m(a, b, callback){ callback(null, a*b); }', function(error, task) {
            if(error) throw error;
            task.distribute(function(error, success) {
                if(error) throw error;
                expect(success[0]).to.be.gt(0);
                OUTPUT_BENCHMARK(function Basic_Parallel_Test(callback){
                    cluster.do('multiply', 4, 8, function(error, r) {
                        if(!error && (r !== 4*8)) error = new Error("Wrong output");
                        callback(error);
                    });
                }, { iterations: 100, threshold: 15, parallel: require('os').cpus().length }, function(){
                    done();
                });
            });
        });
    });
});<commit_msg>Added precompile hack to improve accuracy<commit_after>var async = require('async');
var chalk = require('chalk');
var chai = require("chai");
var expect = chai.expect;
var inspect = require("util").inspect;

var Cluster = require('../cluster');
var cluster;

var ERROR_THRESHOLD = 10;

function SIGN_COLOR(value, threshold, inverse) {
    var scavenge = value, color = "black";
    // If value is string account for single character pre/postfix (very specific/awful implementation)
    if(typeof value === 'string') {
        // Ignore First & Last Chars
        if(typeof value[0] === 'string') value = value.substring(1);
        if(typeof value[value.length - 1] === 'string') value = value.substr(0, scavenge.length - 2);
        // Ends with MS
        if(value.slice(-2) === 'ms') value = value.substr(0, scavenge.length - 3);
        value = parseFloat(value);
    }
    if(!threshold) threshold = 0;
    if(inverse) color = (value > threshold)?'red':((value < threshold)?'green':'yellow');
    else color = (value > threshold)?'green':((value < threshold)?'red':'yellow');

    return chalk[color](scavenge);
}

function NANO_TO_MS(val, decimals) {
    var m = Math.pow(10, (decimals || 3));
    return Math.round((val/1e+6) * m)/m;
}

function REDUCE_STATS(array) {
    var MIN = Math.min.apply(Math, array), MAX = Math.max.apply(Math, array);
    var SUM = array.reduce(function(a, b) { return a + b; });
    var AVG = SUM / array.length;
    for(var i=0; i<array.length; i++) {

    }
    return {
        min: MIN,
        max: MAX,
        average: AVG,
        error: Math.round((Math.abs(AVG - MIN)/Math.abs(MIN) + Math.abs(AVG - MAX)/Math.abs(MAX))/2 * 100000)/1000,
        sum: SUM,
        total: array.length
    };
}

function MAKE_BENCHMARK(func, options, callback) {
    var count = 0;
    var stats = [];
    var Total_Started = process.hrtime();
    async.doWhilst(function BENCHMARK_WRAPPER(callback){
        count++;
        function BENCHMARK_CALLBACK(unique_callback){
            var started = process.hrtime();
            return function BENCHMARK_CALLBACK__FUNC(error) {
                var finished = process.hrtime(started);
                // Calculate Time Difference
                var diff = finished[0] * 1e9 + finished[1];
                // Push difference to stats
                stats.push(diff);
                unique_callback(error, stats);
            };
        }
        if(options.parallel) {
            // Parallelize on all cores
            async.times(options.parallel, function(n, parallel_callback){
                func(BENCHMARK_CALLBACK(parallel_callback));
            }, callback);
        }else{
            func(BENCHMARK_CALLBACK(callback));
        }
    }, function BENCHMARK_ITERATOR(){
        return count < (options.iterations || 10);
    }, function BENCHMARK_RESULTS(error){
        var Reduced = REDUCE_STATS(stats);
        var Total_Finished = process.hrtime(Total_Started);
        // Calculate Time Difference
        Reduced.overall = Total_Finished[0] * 1e9 + Total_Finished[1];
        callback(error, Reduced);
    });
}

function OUTPUT_BENCHMARK(func, options, callback) {
    function LOG() {
        // Mocha ident
        var prepend = "    ";
        var args = Array.prototype.slice.call(arguments);
        args.unshift(prepend);
        args = args.map(function(v){
            // Add prepend after all new lines created with \n\r ...
            if(typeof v === 'string') v = v.replace(/(?:\r\n|\r|\n)/g, "\n" + prepend);
            return chalk.gray(v);
        });
        console.log.apply(console, args);
    }
    MAKE_BENCHMARK(func, options, function(error, stats) {
        LOG("\n" + chalk.green('√'), chalk.white("BENCHMARK RESULTS FOR"), chalk.cyan(func.name || 'Unknown'));
        if(error) {
            LOG(chalk.red("> BENCHMARK FAILED <"));
            console.trace(error);
        }else{
            LOG("\tAveraged at", NANO_TO_MS(stats.average) + 'ms', SIGN_COLOR("±" + stats.error + '%', options.threshold || ERROR_THRESHOLD, true));
            LOG("\tWorst Case:", NANO_TO_MS(stats.max) + 'ms', "Best Case:", NANO_TO_MS(stats.min) + 'ms');
            LOG("\tTotal time:", NANO_TO_MS(stats.overall) + 'ms', "for", stats.total, "rounds");
        }
        LOG();
        if(callback) callback(error, stats);
    });
}

// Finish the compare method
/*function COMPARE_BENCHMARK(funcs, iterations, callback) {
    async.series(funcs, function BENCHMARK_COMPARER(error, results) {

    });
}*/

describe("Init Test Suite", function() {
    this.timeout(20000);
    it('should construct an instance', function() {
        cluster = new Cluster();
        cluster.deploy();
    });
    it('should add and compile on cluster', function(done) {
        cluster.addShared('multiply', 'module.exports = function m(a, b, callback){ callback(null, a*b); }', function(error, task) {
            if(error) throw error;
            task.distribute(function(error, success) {
                if(error) throw error;
                expect(success[0]).to.be.gt(0);
                // Run n times to compile across Workers
                // A precompile method is not implemented yet
                async.times(require('os').cpus().length, function(n, callback){
                    cluster.do('multiply', 4, 8, function(error, r) {
                        if(!error && (r !== 4*8)) error = new Error("Wrong output");
                        callback(error);
                    });
                }, done);
            });
        });
    });
    it('should run tasks on the cluster with arguments', function(done) {
        OUTPUT_BENCHMARK(function Basic_Parallel_Test(callback){
            cluster.do('multiply', 4, 8, function(error, r) {
                if(!error && (r !== 4*8)) error = new Error("Wrong output");
                callback(error);
            });
        }, { iterations: 15, threshold: 90, parallel: require('os').cpus().length }, function(){
            done();
        });
    });
});<|endoftext|>


<commit_before>$(document).ready(function () {

    var KEY_F11 = 122;
    var KEY_ESC = 27;

    ({
        initialize: function () {

            this.orientation = $.Storage.get('console.orientation') || 'vertical';
            this.eastSize = $.Storage.get('console.eastSize') || '50%';
            this.southSize = $.Storage.get('console.southSize') || '50%';

            this.initLayout();
            this.initEditor();

            $('#editor button.submit').click($.proxy(this.executeCode, this));
            $('#editor button.clear').click($.proxy(this.clearEditor, this));
            $('.results button.clear').click($.proxy(this.clearResults, this));

            $('button.vertical').click($.proxy(function (event) { this.showOrientation('vertical'); }, this));
            $('button.horizontal').click($.proxy(function (event) { this.showOrientation('horizontal'); }, this));

            $(document).bind('keydown', 'Ctrl+return', $.proxy(this.executeCode, this));
            $(document).bind('keydown', 'esc', $.proxy(this.clearResults, this));
            $(document).bind('keydown', 'Ctrl+esc', $.proxy(this.clearEditor, this));

            this.showOrientation(this.orientation);
        },

        initLayout: function () {
            this.layout = $('body').layout({
                north__paneSelector: '#header',
                north__spacing_open: 0,
                center__paneSelector: '#editor',
                center__contentSelector: '#code-wrapper',
                east__paneSelector: '.east',
                east__contentSelector: '#result',
                east__initHidden: this.orientation !== 'vertical',
                east__size: this.eastSize,
                east__onresize_end: $.proxy(function (name, $el, state, opts) {
                    this.eastSize = state.size;
                    this.storeSettings();
                }, this),
                south__paneSelector: '.south',
                south__contentSelector: '#result',
                south__initHidden: this.orientation !== 'horizontal',
                south__size: this.southSize,
                south__onresize_end: $.proxy(function (name, $el, state, opts) {
                    this.southSize = state.size;
                    this.storeSettings();
                }, this),
                resizable: true,
                fxName: ''
            });
        },

        initEditor: function () {
            this.editor = CodeMirror.fromTextArea($('#code')[0], {
                matchBrackets: true,
                mode: 'groovy',
                autoMatchParens: true,
//                indentUnit: 3,
                lineNumbers: true,
                extraKeys: {
                    'Ctrl-Enter': $.proxy(this.executeCode, this),
                    'Esc': $.proxy(this.clearResults, this),
                    'Ctrl-Esc': $.proxy(this.clearEditor, this)
                }
            });
            window.e = this.editor;
        },

        executeCode: function () {
            var $result = $('
Executing Script...
');
            $('#result').append($result);

            var scroll = $result.position().top + $('#result').scrollTop();
            $('#result').animate({scrollTop: scroll});

            $.post(gconsole.executeLink, {
                code: this.editor.getValue(),
                captureStdout: 'on'
            }).done($.proxy(function (response) {
                $result.removeClass('loading');
                var timeSpan = '' + response.totalTime + ' ms';
                if (response.exception) {
                    $result.html(timeSpan + response.exception + response.result).addClass('stacktrace').removeClass('script-result');
                } else {
                    $result.html(timeSpan + response.output + response.result);
                }
            }, this)).fail(function(){
                $result.removeClass('loading script-result').addClass('stacktrace');
                $result.html('An error occurred.');
            });
        },

        clearResults: function () { $('#result').html(''); },

        clearEditor: function () { this.editor.setValue(''); },

        showOrientation: function (orientation) {
            if (orientation === 'vertical') {
                $('button.vertical').addClass('selected');
                $('button.horizontal').removeClass('selected');
                $('.east').append($('.south').children());
                this.layout.hide('south');
                this.layout.show('east');
                this.layout.initContent('east');
            } else {
                $('button.vertical').removeClass('selected');
                $('button.horizontal').addClass('selected');
                $('.south').append($('.east').children());
                this.layout.hide('east');
                this.layout.show('south');
                this.layout.initContent('south');
            }
            this.editor.refresh();
            this.orientation = orientation;
            this.storeSettings();
        },

        storeSettings: function () {
            $.Storage.set({
                'console.orientation': this.orientation,
                'console.eastSize': this.eastSize,
                'console.southSize': this.southSize
            });
        }

    }.initialize());

});
<commit_msg>add scrollTo after load<commit_after>$(document).ready(function () {

    var KEY_F11 = 122;
    var KEY_ESC = 27;

    ({
        initialize: function () {

            this.orientation = $.Storage.get('console.orientation') || 'vertical';
            this.eastSize = $.Storage.get('console.eastSize') || '50%';
            this.southSize = $.Storage.get('console.southSize') || '50%';

            this.initLayout();
            this.initEditor();

            $('#editor button.submit').click($.proxy(this.executeCode, this));
            $('#editor button.clear').click($.proxy(this.clearEditor, this));
            $('.results button.clear').click($.proxy(this.clearResults, this));

            $('button.vertical').click($.proxy(function (event) { this.showOrientation('vertical'); }, this));
            $('button.horizontal').click($.proxy(function (event) { this.showOrientation('horizontal'); }, this));

            $(document).bind('keydown', 'Ctrl+return', $.proxy(this.executeCode, this));
            $(document).bind('keydown', 'esc', $.proxy(this.clearResults, this));
            $(document).bind('keydown', 'Ctrl+esc', $.proxy(this.clearEditor, this));

            this.showOrientation(this.orientation);
        },

        initLayout: function () {
            this.layout = $('body').layout({
                north__paneSelector: '#header',
                north__spacing_open: 0,
                center__paneSelector: '#editor',
                center__contentSelector: '#code-wrapper',
                east__paneSelector: '.east',
                east__contentSelector: '#result',
                east__initHidden: this.orientation !== 'vertical',
                east__size: this.eastSize,
                east__onresize_end: $.proxy(function (name, $el, state, opts) {
                    this.eastSize = state.size;
                    this.storeSettings();
                }, this),
                south__paneSelector: '.south',
                south__contentSelector: '#result',
                south__initHidden: this.orientation !== 'horizontal',
                south__size: this.southSize,
                south__onresize_end: $.proxy(function (name, $el, state, opts) {
                    this.southSize = state.size;
                    this.storeSettings();
                }, this),
                resizable: true,
                fxName: ''
            });
        },

        initEditor: function () {
            this.editor = CodeMirror.fromTextArea($('#code')[0], {
                matchBrackets: true,
                mode: 'groovy',
                autoMatchParens: true,
//                indentUnit: 3,
                lineNumbers: true,
                extraKeys: {
                    'Ctrl-Enter': $.proxy(this.executeCode, this),
                    'Esc': $.proxy(this.clearResults, this),
                    'Ctrl-Esc': $.proxy(this.clearEditor, this)
                }
            });
            window.e = this.editor;
        },

        executeCode: function () {
            var $result = $('
Executing Script...
');
            $('#result').append($result);

            this.scrollToResult($result);
            $.post(gconsole.executeLink, {
                code: this.editor.getValue(),
                captureStdout: 'on'
            }).done($.proxy(function (response) {
                $result.removeClass('loading');
                var timeSpan = '' + response.totalTime + ' ms';
                if (response.exception) {
                    $result.html(timeSpan + response.exception + response.result).addClass('stacktrace').removeClass('script-result');
                } else {
                    $result.html(timeSpan + response.output + response.result);
                }
                this.scrollToResult($result);
            }, this)).fail(function(){
                $result.removeClass('loading script-result').addClass('stacktrace');
                $result.html('An error occurred.');
            });
        },

        clearResults: function () { $('#result').html(''); },

        clearEditor: function () { this.editor.setValue(''); },

        scrollToResult: function($result) {
            var scroll = $result.position().top + $('#result').scrollTop();
            $('#result').animate({scrollTop: scroll});
        },

        showOrientation: function (orientation) {
            if (orientation === 'vertical') {
                $('button.vertical').addClass('selected');
                $('button.horizontal').removeClass('selected');
                $('.east').append($('.south').children());
                this.layout.hide('south');
                this.layout.show('east');
                this.layout.initContent('east');
            } else {
                $('button.vertical').removeClass('selected');
                $('button.horizontal').addClass('selected');
                $('.south').append($('.east').children());
                this.layout.hide('east');
                this.layout.show('south');
                this.layout.initContent('south');
            }
            this.editor.refresh();
            this.orientation = orientation;
            this.storeSettings();
        },

        storeSettings: function () {
            $.Storage.set({
                'console.orientation': this.orientation,
                'console.eastSize': this.eastSize,
                'console.southSize': this.southSize
            });
        }

    }.initialize());

});
<|endoftext|>


<commit_before>/**
 * VclController
 *
 * @description :: Server-side logic for managing vcls
 * @help        :: See http://links.sailsjs.org/docs/controllers
 */
var child_process = require('child_process');
var fs = require('fs');
var path = require('path');
var temp = require('temp');
var url = require('url');

module.exports = {
	index: function (req, res) {
    const defaultVcl = 'vcl 4.0; backend default { .host = "www.vclfiddle.net"; .port = "80"; }';

    var fiddleid = req.params.fiddleid || '';
    var runindex = req.params.runindex || '0';

    if (!fiddleid) {
      return res.view({
        fiddleid: '',
        vcl: defaultVcl,
        har: '',
        log: ''
      });
    }

    FiddlePersistenceService.getFiddleRun(fiddleid, runindex, function (err, fiddle) {

      if (err) return res.serverError(err);

      if (fiddle === null) return res.notFound();

      FiddlePersistenceService.loadViewState(fiddle, function (err, viewState) {

        return res.view({
          fiddleid: fiddle.id,
          vcl: viewState.vcl,
          har: viewState.har,
          log: viewState.log,
          results: viewState.results
        })

      });

    });

  },

  result: function (req, res) {
    var fiddleid = req.query.fiddleid || '';
    var runindex = req.query.runindex || '0';
    sails.log(req.query);
    if (!fiddleid) return res.badRequest();

    FiddlePersistenceService.getFiddleRun(fiddleid, runindex, function (err, fiddle) {

      if (err) return res.serverError(err);

      if (fiddle === null) return res.notFound();

      ContainerService.getReplayResult(fiddle.path, function (err, completedData) {
        if (err) return res.serverError(err);

        if (!completedData.completedAt) {
          // not complete yet
          // TODO timeout if too long to complete
          // TODO instruct client to cache only briefly if at all
          return res.ok({});
        }

        if (completedData.error) {
          // complete but failed
          return res.ok({
            log: completedData.error
          });
        }

        var output = completedData.result;
        if (output.runlog.length > 0) {
          return res.ok({
            log: 'Error: ' + output.runlog
          });
        }

        var parsedNcsa = RequestMetadataService.parseVarnish4NCSA(output.varnishncsa);

        // TODO recover requests for correlation:
        var results = [];
        //var results = RequestMetadataService.correlateResults(allRequests.includedRequests, output.responses, parsedNcsa, null);
        //results = results.concat(allRequests.excludedRequests.map(function (r) { return { request: r }; }));

        return res.ok({
          log: output.varnishlog,
          results: results
        });

      });

    });
  },

  run: function (req, res) {
    var fiddleid = req.body.fiddleid || '';
    var vcl = req.body.vcl;
    var rawRequests = req.body.har;

    if (!vcl || !rawRequests) return res.badRequest();

    RequestMetadataService.parseInputRequests(rawRequests, function (err, _ignored, allRequests) {

      if (err) {
        return res.ok({
          fiddleid: fiddleid,
          vcl: vcl,
          har: rawRequests,
          log: err.toString()
        }, 'vcl/index');
      }

      if (allRequests.includedRequests.length == 0) {
        return res.ok({
          fiddleid: fiddleid,
          vcl: vcl,
          har: rawRequests,
          log: 'HAR does not contain any supported requests.'
        }, 'vcl/index');
      }

      if (!!req.body.dbl) {
        allRequests.includedRequests = allRequests.includedRequests.concat(allRequests.includedRequests);
      }

      FiddlePersistenceService.prepareFiddle(fiddleid, function (err, fiddle) {
        if (err) return res.serverError(err);

        // TODO persist state of 'replay requests twice' option

        ContainerService.beginReplay(fiddle.path, allRequests.includedRequests, vcl, function (err) {

          var results = null;

          var viewState = {
            vcl: vcl,
            har: rawRequests
          };
          if (err) {
            viewState.log = 'Error: ' + err;
          }

          FiddlePersistenceService.saveViewState(fiddle, viewState, function (err) {
            if (err) return res.serverError(err);

            return res.ok({
              fiddleid: fiddle.id,
              runindex: fiddle.runIndex,
              vcl: viewState.vcl,
              har: viewState.har,
              log: viewState.log
            });

          });

        });

      });

    });

  }

};

<commit_msg>Fix failing test<commit_after>/**
 * VclController
 *
 * @description :: Server-side logic for managing vcls
 * @help        :: See http://links.sailsjs.org/docs/controllers
 */
var child_process = require('child_process');
var fs = require('fs');
var path = require('path');
var temp = require('temp');
var url = require('url');

module.exports = {
	index: function (req, res) {
    const defaultVcl = 'vcl 4.0; backend default { .host = "www.vclfiddle.net"; .port = "80"; }';

    var fiddleid = req.params.fiddleid || '';
    var runindex = req.params.runindex || '0';

    if (!fiddleid) {
      return res.view({
        fiddleid: '',
        vcl: defaultVcl,
        har: '',
        log: ''
      });
    }

    FiddlePersistenceService.getFiddleRun(fiddleid, runindex, function (err, fiddle) {

      if (err) return res.serverError(err);

      if (fiddle === null) return res.notFound();

      FiddlePersistenceService.loadViewState(fiddle, function (err, viewState) {

        return res.view({
          fiddleid: fiddle.id,
          vcl: viewState.vcl,
          har: viewState.har,
          log: viewState.log,
          results: viewState.results
        })

      });

    });

  },

  result: function (req, res) {
    var fiddleid = req.query.fiddleid || '';
    var runindex = req.query.runindex || '0';
    sails.log(req.query);
    if (!fiddleid) return res.badRequest();

    FiddlePersistenceService.getFiddleRun(fiddleid, runindex, function (err, fiddle) {

      if (err) return res.serverError(err);

      if (fiddle === null) return res.notFound();

      ContainerService.getReplayResult(fiddle.path, function (err, completedData) {
        if (err) return res.serverError(err);

        if (!completedData.completedAt) {
          // not complete yet
          // TODO timeout if too long to complete
          // TODO instruct client to cache only briefly if at all
          return res.ok({});
        }

        if (completedData.error) {
          // complete but failed
          return res.ok({
            log: completedData.error
          });
        }

        var output = completedData.result;
        if (output.runlog.length > 0) {
          return res.ok({
            log: 'Error: ' + output.runlog
          });
        }

        var parsedNcsa = RequestMetadataService.parseVarnish4NCSA(output.varnishncsa);

        // TODO recover requests for correlation:
        var results = [];
        //var results = RequestMetadataService.correlateResults(allRequests.includedRequests, output.responses, parsedNcsa, null);
        //results = results.concat(allRequests.excludedRequests.map(function (r) { return { request: r }; }));

        return res.ok({
          log: output.varnishlog,
          results: results
        });

      });

    });
  },

  run: function (req, res) {
    var fiddleid = req.body.fiddleid || '';
    var vcl = req.body.vcl;
    var rawRequests = req.body.har;

    if (typeof vcl !== 'string' || typeof rawRequests !== 'string') return res.badRequest();

    RequestMetadataService.parseInputRequests(rawRequests, function (err, _ignored, allRequests) {

      if (err) {
        return res.ok({
          fiddleid: fiddleid,
          vcl: vcl,
          har: rawRequests,
          log: err.toString()
        }, 'vcl/index');
      }

      if (allRequests.includedRequests.length == 0) {
        return res.ok({
          fiddleid: fiddleid,
          vcl: vcl,
          har: rawRequests,
          log: 'HAR does not contain any supported requests.'
        }, 'vcl/index');
      }

      if (!!req.body.dbl) {
        allRequests.includedRequests = allRequests.includedRequests.concat(allRequests.includedRequests);
      }

      FiddlePersistenceService.prepareFiddle(fiddleid, function (err, fiddle) {
        if (err) return res.serverError(err);

        // TODO persist state of 'replay requests twice' option

        ContainerService.beginReplay(fiddle.path, allRequests.includedRequests, vcl, function (err) {

          var results = null;

          var viewState = {
            vcl: vcl,
            har: rawRequests
          };
          if (err) {
            viewState.log = 'Error: ' + err;
          }

          FiddlePersistenceService.saveViewState(fiddle, viewState, function (err) {
            if (err) return res.serverError(err);

            return res.ok({
              fiddleid: fiddle.id,
              runindex: fiddle.runIndex,
              vcl: viewState.vcl,
              har: viewState.har,
              log: viewState.log
            });

          });

        });

      });

    });

  }

};

<|endoftext|>