<commit_before>/*!
 * jQuery bsValidate Plugin v0.7.2
 * Form Validation for Twitter Bootstrap Forms (https://github.com/matthewjmink/bsValidate)
 * Copyright 2016 Matt Mink
 * Licensed under MIT (https://github.com/matthewjmink/bsValidate/blob/master/LICENSE)
 */

;(function ( $, window, document, undefined ) {

    "use strict";

    var bsValidate = "bsValidate",

    defaults = {
        requiredSelector: "input.required,textarea.required,select.required,[required]",
        fields: {},
        mergeAlerts: false,
        alertMessage: null,
        blankSelectValue: "",
        novalidate: true,
        before: function(){},
        success: function(){},
        fail: function(e){e.preventDefault();}
    };

    $.extend(Plugin.prototype, {

        init: function () {
            var bsv = this;
            var form = $(bsv.element);
            var required = form.find(bsv.settings.requiredSelector);
            var fields = bsv.settings.fields;
            var novalidate = form.attr('novalidate');

            if(novalidate === undefined && bsv.settings.novalidate){
                form.attr('novalidate', '');
            }

            required.each(function(){
                var name = $(this).attr('name');
                if(fields[name] === undefined || fields[name].required === undefined){
                    var formGroup = $(this).parents('.form-group');
                    var label = formGroup.find('.label,label').text();
                    fields[name] = (fields[name] === undefined) ? {} : fields[name];
                    fields[name].el = $(this);
                    fields[name].required = {
                        alert: label + " is required."
                    };
                }
            });

            $.each( fields, function( key, value ) {
                if(typeof fields[key].el !== "object" || fields[key].el.jquery === undefined){
                    fields[key].el = form.find('[name="'+key+'"]');
                }
                if(fields[key].required && fields[key].required.dependency){
                    $.each( fields[key].required.dependency, function( depKey, depValue ) {
                        var depFields = depValue.split(',');
                        for (var i = 0; i < depFields.length; i++) {
                            if(!fields[depFields[i]]) {
                                fields[depFields[i]] = {
                                    el: form.find('[name="'+depFields[i]+'"]')
                                };
                                fields[depFields[i]].el.on('blur', {bsv:bsv, fields:fields, key:depFields[i], value:fields[depFields[i]]} , bsvFieldChange);
                            }
                            if(fields[depFields[i]].hasDependency) {
                                fields[depFields[i]].hasDependency += ',' + key;
                            } else {
                                fields[depFields[i]].hasDependency = key;
                            }
                        }
                    });
                }
                if(fields[key].el.length > 0){
                    fields[key].el.on('blur', {bsv:bsv, fields:fields, key:key, value:value} , bsvFieldChange);
                }else{
                    delete fields[key];
                }
            });

            form.submit(function(e){
                bsv.settings.before();
                var isValid = true;
                var alertMessage = (bsv.settings.mergeAlerts) ? bsv.settings.alertMessage : '';
                var isList = false;
                if(alertMessage === null){
                    alertMessage = '
';
                    isList = true;
                }
                $.each( fields, function( key, value ) {
                    var styleClass;
                    var formGroup = fields[key].el.parents('.form-group');
                    var errCnt = 0;
                    var v = fields[key].el.val();
                    var styleKey = key.replace(/[^a-zA-Z\d-]/g, '-');
                    if(fields[key].required !== undefined){
                        var requiredTest = fields[key].el.isBlank(bsv);
                        styleClass = 'alert-'+styleKey+'-required';
                        requiredTest = requiredTest && isDependent(fields, key);
                        errCnt += (bsv.settings.mergeAlerts) ? requiredTest | 0 : toggleAlert(requiredTest, fields[key].required.alert, bsv.settings.alertTarget, styleClass);
                        alertMessage += (isList) ? '
'+fields[key].required.alert+'
' : '';
                    }
                    if(fields[key].email !== undefined){
                        styleClass = 'alert-'+styleKey+'-email';
                        errCnt += (bsv.settings.mergeAlerts) ? !isValidEmail(v) && !fields[key].el.isBlank(bsv) | 0 : toggleAlert(!isValidEmail(v) && !fields[key].el.isBlank(bsv), fields[key].email.alert, bsv.settings.alertTarget, styleClass);
                        alertMessage += (isList) ? '
'+fields[key].email.alert+'
' : '';
                    }
                    if(fields[key].characters !== undefined){
                        styleClass = 'alert-'+styleKey+'-characters';
                        errCnt += (bsv.settings.mergeAlerts) ? v.length > fields[key].characters.limit | 0 : toggleAlert(v.length > fields[key].characters.limit, fields[key].characters.alert, bsv.settings.alertTarget, styleClass);
                        alertMessage += (isList) ? '
'+fields[key].characters.alert+'
' : '';
                    }
                    if(fields[key].regex !== undefined){
                        styleClass = 'alert-'+styleKey+'-regex';
                        errCnt += (bsv.settings.mergeAlerts) ? !regexMatch(fields[key].regex.pattern, v) && !fields[key].el.isBlank(bsv) | 0 : toggleAlert(!regexMatch(fields[key].regex.pattern, v) && !fields[key].el.isBlank(bsv), fields[key].regex.alert, bsv.settings.alertTarget, styleClass);
                        alertMessage += (isList) ? '
'+fields[key].regex.alert+'
' : '';
                    }
                    if(fields[key].match !== undefined){
                        styleClass = 'alert-'+styleKey+'-match';
                        var matchFieldValue = form.find('[name="'+fields[key].match.field+'"]').val();
                        errCnt += (bsv.settings.mergeAlerts) ? matchFieldValue !== v && !fields[key].el.isBlank(bsv) | 0 : toggleAlert(matchFieldValue !== v && !fields[key].el.isBlank(bsv), fields[key].match.alert, bsv.settings.alertTarget, styleClass);
                        alertMessage += (isList) ? '
'+fields[key].regex.alert+'
' : '';
                    }
                    if(errCnt > 0){
                        formGroup.addClass('has-error');
                        isValid = false;
                    }else{
                        formGroup.removeClass('has-error');
                    }
                });
                toggleAlert(!isValid && bsv.settings.mergeAlerts, alertMessage, bsv.settings.alertTarget, 'bsv-alert');
                if(isValid){
                    bsv.settings.success(e);
                }else{
                    bsv.settings.fail(e);
                }
            });
        },
        destroy: function(callback) {
            var bsv = this;
            var fields = bsv.settings.fields;
            bsv.settings.fields = {};
            $.each( fields, function( key, field ) {
                if(typeof field.el === "object" && field.el.jquery !== undefined){
                    field.el.off('change blur', bsvFieldChange);
                }
            });
            $(bsv.element).off("submit").removeData();
            if(callback){
                callback();
            }
        }
    });

    $.fn[ bsValidate ] = function ( options ) {
        return this.each(function() {
            var el = this;
            var plugin = $.data( this, "plugin_" + bsValidate );
            if ( !plugin ) {
                $.data( this, "plugin_" + bsValidate, new Plugin( this, options ) );
            }else if(options === "destroy"){
                plugin.destroy();
            }
        });
    };

    $.fn.isBlank = function ( bsv ) {
        var val = this.val();
        if(this.is(':checkbox')){
            return !this.is(':checked');
        }
        return (val === "" || val === null || val.length < 1 || (this[0].nodeName.toLowerCase() === 'select' && val == bsv.settings.blankSelectValue));
    };

    $.fn.destroy = function ( ) {
        return this.each(function() {
            var plugin = $.data( this, "plugin_" + bsValidate );
            if ( !!plugin ) {
                plugin.destroy();
            }
        });
    };

    function Plugin ( element, options ) {
        defaults.alertTarget = $(element);
        this.element = element;
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = bsValidate;
        this.init();
    }

    function isDependent(fields, key){
        var requiredTest = true;
        if(fields[key].required.dependency){
            if(fields[key].required.dependency.isBlank){
                requiredTest = requiredTest && fieldGroupIsBlank(fields, fields[key].required.dependency.isBlank);
            }
            if(fields[key].required.dependency.isNotBlank){
                requiredTest = requiredTest && fieldGroupIsNotBlank(fields, fields[key].required.dependency.isNotBlank);
            }
        }
        return requiredTest;
    }

    function fieldGroupIsBlank(fields, dependencies){
        var blankCount = 0;
        if(typeof dependencies === 'string') {
            dependencies = dependencies.split(',');
        }
        for (var i = 0; i < dependencies.length; i++) {
            if(fields[dependencies[i]].el.isBlank()){
                blankCount++;
            }
        }
        return blankCount === dependencies.length;
    }

    function fieldGroupIsNotBlank(fields, dependencies){
        var filledCount = 0;
        if(typeof dependencies === 'string') {
            dependencies = dependencies.split(',');
        }
        for (var i = 0; i < dependencies.length; i++) {
            if(!fields[dependencies[i]].el.isBlank()){
                filledCount++;
            }
        }
        return filledCount === dependencies.length;
    }

    function toggleHelpText(test, helpText, formGroup, styleClass){
        if(test){
            if(helpText !== undefined){
                addHelpText(formGroup, helpText, styleClass);
            }
            return 1;
        }else{
            if(helpText !== undefined){
                removeHelpText(formGroup, styleClass);
            }
        }
        return 0;
    }

    function toggleAlert(test, alertText, alertTarget, styleClass){
        if(test){
            if(alertText !== undefined){
                addAlert(alertTarget, alertText, styleClass);
            }
            return 1;
        }else{
            if(alertText !== undefined){
                removeAlert(alertTarget, styleClass);
            }
        }
        return 0;
    }

    function addHelpText(formGroup, message, styleClass){
        if(formGroup.find('.'+styleClass).length < 1){
            var helpText = $(''+message+'');
            formGroup.append(helpText);
        }
    }

    function removeHelpText(formGroup, styleClass){
        var helpText = formGroup.find('.'+styleClass);
        helpText.remove();
    }

    function addAlert(target, message, styleClass){
        if(target.find('.'+styleClass).length < 1){
            var alert = $('
'+message+'
');
            target.prepend(alert);
        }
    }

    function removeAlert(target, styleClass){
        var alert = target.find('.'+styleClass);
        alert.remove();
    }

    function bsvFieldChange(event){
        var data = event.data;
        var bsv = data.bsv;
        var form = $(bsv.element);
        var el = $(event.target);
        var fields = data.fields;
        var key = data.key;
        var formGroup = el.parents('.form-group');
        var errCnt = 0;
        var styleClass;
        var v = el.val();
        if(fields[key].hasDependency !== undefined){
            var depFields = fields[key].hasDependency.split(',');
            if(depFields.length > 1 || fields[depFields[0]].el[0] !== event.relatedTarget) {
                for (var i = 0; i < depFields.length; i++) {
                    var depRequiredTest = fields[depFields[i]].el.isBlank(bsv);
                    var depFormGroup = fields[depFields[i]].el.parents('.form-group');
                    styleClass = 'help-required';
                    depRequiredTest = depRequiredTest && isDependent(fields, depFields[i]);
                    var hasError = toggleHelpText(depRequiredTest, fields[depFields[i]].required.helpText, depFormGroup, styleClass);
                    if(hasError) {
                        depFormGroup.addClass('has-error');
                    } else {
                        depFormGroup.removeClass('has-error');
                    }
                }
            }
        }
        if(fields[key].required !== undefined){
            var requiredTest = fields[key].el.isBlank(bsv);
            styleClass = 'help-required';
            requiredTest = requiredTest && isDependent(fields, key);
            errCnt += toggleHelpText(requiredTest, fields[key].required.helpText, formGroup, styleClass);
        }
        if(fields[key].email !== undefined){
            styleClass = 'help-email';
            errCnt += toggleHelpText(!isValidEmail(v) && v !== "", fields[key].email.helpText, formGroup, styleClass);
        }
        if(fields[key].characters !== undefined){
            styleClass = 'help-characters';
            errCnt += toggleHelpText(v.length > fields[key].characters.limit, fields[key].characters.helpText, formGroup, styleClass);
        }
        if(fields[key].regex !== undefined){
            styleClass = 'help-regex';
            errCnt += toggleHelpText(!regexMatch(fields[key].regex.pattern, v) && !el.isBlank(bsv), fields[key].regex.helpText, formGroup, styleClass);
        }
        if(fields[key].match !== undefined){
            styleClass = 'help-match';
            var matchFieldValue = form.find('[name="'+fields[key].match.field+'"]').val();
            errCnt += toggleHelpText(matchFieldValue !== v && !el.isBlank(bsv), fields[key].match.helpText, formGroup, styleClass);
        }
        if(errCnt > 0){
            formGroup.addClass('has-error');
        }else{
            formGroup.removeClass('has-error');
        }
    }

    function regexMatch(regex, value){
        return value.match(regex);
    }

    function isValidEmail(email){
         var re = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/i;
         return re.test(email);
    }

})( jQuery, window, document );
<commit_msg>Added toggleHelpTextOnSubmit property to allow further customization of how error messages display<commit_after>/*!
 * jQuery bsValidate Plugin v0.7.2
 * Form Validation for Twitter Bootstrap Forms (https://github.com/matthewjmink/bsValidate)
 * Copyright 2016 Matt Mink
 * Licensed under MIT (https://github.com/matthewjmink/bsValidate/blob/master/LICENSE)
 */

;(function ( $, window, document, undefined ) {

    "use strict";

    var bsValidate = "bsValidate",

    defaults = {
        requiredSelector: "input.required,textarea.required,select.required,[required]",
        fields: {},
        mergeAlerts: false,
        alertMessage: null,
        blankSelectValue: "",
        novalidate: true,
        toggleHelpTextOnSubmit: false,
        before: function(){},
        success: function(){},
        fail: function(e){e.preventDefault();}
    };

    $.extend(Plugin.prototype, {

        init: function () {
            var bsv = this;
            var form = $(bsv.element);
            var required = form.find(bsv.settings.requiredSelector);
            var fields = bsv.settings.fields;
            var novalidate = form.attr('novalidate');

            if(novalidate === undefined && bsv.settings.novalidate){
                form.attr('novalidate', '');
            }

            required.each(function(){
                var name = $(this).attr('name');
                if(fields[name] === undefined || fields[name].required === undefined){
                    var formGroup = $(this).parents('.form-group');
                    var label = formGroup.find('.label,label').text();
                    fields[name] = (fields[name] === undefined) ? {} : fields[name];
                    fields[name].el = $(this);
                    fields[name].required = {
                        alert: label + " is required."
                    };
                }
            });

            $.each( fields, function( key, value ) {
                if(typeof fields[key].el !== "object" || fields[key].el.jquery === undefined){
                    fields[key].el = form.find('[name="'+key+'"]');
                }
                if(fields[key].required && fields[key].required.dependency){
                    $.each( fields[key].required.dependency, function( depKey, depValue ) {
                        var depFields = depValue.split(',');
                        for (var i = 0; i < depFields.length; i++) {
                            if(!fields[depFields[i]]) {
                                fields[depFields[i]] = {
                                    el: form.find('[name="'+depFields[i]+'"]')
                                };
                                fields[depFields[i]].el.on('blur', {bsv:bsv, fields:fields, key:depFields[i], value:fields[depFields[i]]} , bsvFieldChange);
                            }
                            if(fields[depFields[i]].hasDependency) {
                                fields[depFields[i]].hasDependency += ',' + key;
                            } else {
                                fields[depFields[i]].hasDependency = key;
                            }
                        }
                    });
                }
                if(fields[key].el.length > 0){
                    fields[key].el.on('blur', {bsv:bsv, fields:fields, key:key, value:value} , bsvFieldChange);
                }else{
                    delete fields[key];
                }
            });

            form.submit(function(e){
                bsv.settings.before();
                var isValid = true;
                var alertMessage = (bsv.settings.mergeAlerts) ? bsv.settings.alertMessage : '';
                var isList = false;
                if(alertMessage === null){
                    alertMessage = '
';
                    isList = true;
                }
                try{
                    $.each( fields, function( key, value ) {
                        var styleClass, alertType;
                        var formGroup = fields[key].el.parents('.form-group');
                        var errCnt = 0;
                        var v = fields[key].el.val();
                        var styleKey = key.replace(/[^a-zA-Z\d-]/g, '-');
                        var formGroup = fields[key].el.parents('.form-group');
                        if(fields[key].required !== undefined){
                            alertType = 'required'
                            styleClass = 'alert-'+styleKey+'-'+alertType;
                            var requiredTest = fields[key].el.isBlank(bsv);
                            requiredTest = requiredTest && isDependent(fields, key);
                            errCnt += (bsv.settings.mergeAlerts) ? requiredTest | 0 : toggleAlert(requiredTest, fields[key][alertType].alert, bsv.settings.alertTarget, styleClass);
                            alertMessage += (isList) ? '
'+fields[key][alertType].alert+'
' : '';
                            if(bsv.settings.toggleHelpTextOnSubmit){
                                toggleHelpText(requiredTest, fields[key][alertType].helpText, formGroup, 'help-' + alertType);
                            }
                        }
                        if(fields[key].email !== undefined){
                            alertType = 'email'
                            styleClass = 'alert-'+styleKey+'-'+alertType;
                            var emailTest = !isValidEmail(v) && !fields[key].el.isBlank(bsv);
                            errCnt += (bsv.settings.mergeAlerts) ? emailTest | 0 : toggleAlert(emailTest, fields[key].email.alert, bsv.settings.alertTarget, styleClass);
                            alertMessage += (isList) ? '
'+fields[key].email.alert+'
' : '';
                            if(bsv.settings.toggleHelpTextOnSubmit){
                                toggleHelpText(emailTest, fields[key][alertType].helpText, formGroup, 'help-' + alertType);
                            }
                        }
                        if(fields[key].characters !== undefined){
                            alertType = 'characters'
                            styleClass = 'alert-'+styleKey+'-'+alertType;
                            var charactersTest = v.length > fields[key][alertType].limit;
                            errCnt += (bsv.settings.mergeAlerts) ? charactersTest | 0 : toggleAlert(charactersTest, fields[key][alertType].alert, bsv.settings.alertTarget, styleClass);
                            alertMessage += (isList) ? '
'+fields[key][alertType].alert+'
' : '';
                            if(bsv.settings.toggleHelpTextOnSubmit){
                                toggleHelpText(charactersTest, fields[key][alertType].helpText, formGroup, 'help-' + alertType);
                            }
                        }
                        if(fields[key].regex !== undefined){
                            alertType = 'regex'
                            styleClass = 'alert-'+styleKey+'-'+alertType;
                            var regexTest = !regexMatch(fields[key][alertType].pattern, v) && !fields[key].el.isBlank(bsv);
                            errCnt += (bsv.settings.mergeAlerts) ? regexTest | 0 : toggleAlert(regexTest, fields[key][alertType].alert, bsv.settings.alertTarget, styleClass);
                            alertMessage += (isList) ? '
'+fields[key][alertType].alert+'
' : '';
                            if(bsv.settings.toggleHelpTextOnSubmit){
                                toggleHelpText(regexTest, fields[key][alertType].helpText, formGroup, 'help-' + alertType);
                            }
                        }
                        if(fields[key].match !== undefined){
                            alertType = 'match'
                            styleClass = 'alert-'+styleKey+'-'+alertType;
                            var matchFieldValue = form.find('[name="'+fields[key][alertType].field+'"]').val();
                            var matchTest = matchFieldValue !== v && !fields[key].el.isBlank(bsv);
                            errCnt += (bsv.settings.mergeAlerts) ? matchTest | 0 : toggleAlert(matchTest, fields[key][alertType].alert, bsv.settings.alertTarget, styleClass);
                            alertMessage += (isList) ? '
'+fields[key][alertType].alert+'
' : '';
                            if(bsv.settings.toggleHelpTextOnSubmit){
                                toggleHelpText(matchTest, fields[key][alertType].helpText, formGroup, 'help-' + alertType);
                            }
                        }
                        if(errCnt > 0){
                            formGroup.addClass('has-error');
                            isValid = false;
                        }else{
                            formGroup.removeClass('has-error');
                        }
                    });
                    toggleAlert(!isValid && bsv.settings.mergeAlerts, alertMessage, bsv.settings.alertTarget, 'bsv-alert');
                } catch(e){
                    console.log(e);
                    isValid = false;
                }
                if(isValid){
                    bsv.settings.success(e);
                }else{
                    bsv.settings.fail(e);
                }
            });
        },
        destroy: function(callback) {
            var bsv = this;
            var fields = bsv.settings.fields;
            bsv.settings.fields = {};
            $.each( fields, function( key, field ) {
                if(typeof field.el === "object" && field.el.jquery !== undefined){
                    field.el.off('change blur', bsvFieldChange);
                }
            });
            $(bsv.element).off("submit").removeData();
            if(callback){
                callback();
            }
        }
    });

    $.fn[ bsValidate ] = function ( options ) {
        return this.each(function() {
            var el = this;
            var plugin = $.data( this, "plugin_" + bsValidate );
            if ( !plugin ) {
                $.data( this, "plugin_" + bsValidate, new Plugin( this, options ) );
            }else if(options === "destroy"){
                plugin.destroy();
            }
        });
    };

    $.fn.isBlank = function ( bsv ) {
        var val = this.val();
        if(this.is(':checkbox')){
            return !this.is(':checked');
        }
        return (val === "" || val === null || val.length < 1 || (this[0].nodeName.toLowerCase() === 'select' && val == bsv.settings.blankSelectValue));
    };

    $.fn.destroy = function ( ) {
        return this.each(function() {
            var plugin = $.data( this, "plugin_" + bsValidate );
            if ( !!plugin ) {
                plugin.destroy();
            }
        });
    };

    function Plugin ( element, options ) {
        defaults.alertTarget = $(element);
        this.element = element;
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = bsValidate;
        this.init();
    }

    function isDependent(fields, key){
        var requiredTest = true;
        if(fields[key].required.dependency){
            if(fields[key].required.dependency.isBlank){
                requiredTest = requiredTest && fieldGroupIsBlank(fields, fields[key].required.dependency.isBlank);
            }
            if(fields[key].required.dependency.isNotBlank){
                requiredTest = requiredTest && fieldGroupIsNotBlank(fields, fields[key].required.dependency.isNotBlank);
            }
        }
        return requiredTest;
    }

    function fieldGroupIsBlank(fields, dependencies){
        var blankCount = 0;
        if(typeof dependencies === 'string') {
            dependencies = dependencies.split(',');
        }
        for (var i = 0; i < dependencies.length; i++) {
            if(fields[dependencies[i]].el.isBlank()){
                blankCount++;
            }
        }
        return blankCount === dependencies.length;
    }

    function fieldGroupIsNotBlank(fields, dependencies){
        var filledCount = 0;
        if(typeof dependencies === 'string') {
            dependencies = dependencies.split(',');
        }
        for (var i = 0; i < dependencies.length; i++) {
            if(!fields[dependencies[i]].el.isBlank()){
                filledCount++;
            }
        }
        return filledCount === dependencies.length;
    }

    function toggleHelpText(test, helpText, formGroup, styleClass){
        if(test){
            if(helpText !== undefined){
                addHelpText(formGroup, helpText, styleClass);
            }
            return 1;
        }else{
            if(helpText !== undefined){
                removeHelpText(formGroup, styleClass);
            }
        }
        return 0;
    }

    function toggleAlert(test, alertText, alertTarget, styleClass){
        if(test){
            if(alertText !== undefined){
                addAlert(alertTarget, alertText, styleClass);
            }
            return 1;
        }else{
            if(alertText !== undefined){
                removeAlert(alertTarget, styleClass);
            }
        }
        return 0;
    }

    function addHelpText(formGroup, message, styleClass){
        if(formGroup.find('.'+styleClass).length < 1){
            var helpText = $(''+message+'');
            formGroup.append(helpText);
        }
    }

    function removeHelpText(formGroup, styleClass){
        var helpText = formGroup.find('.'+styleClass);
        helpText.remove();
    }

    function addAlert(target, message, styleClass){
        if(target.find('.'+styleClass).length < 1){
            var alert = $('
'+message+'
');
            target.prepend(alert);
        }
    }

    function removeAlert(target, styleClass){
        var alert = target.find('.'+styleClass);
        alert.remove();
    }

    function bsvFieldChange(event){
        var data = event.data;
        var bsv = data.bsv;
        var form = $(bsv.element);
        var el = $(event.target);
        var fields = data.fields;
        var key = data.key;
        var formGroup = el.parents('.form-group');
        var errCnt = 0;
        var styleClass;
        var v = el.val();
        if(fields[key].hasDependency !== undefined){
            var depFields = fields[key].hasDependency.split(',');
            if(depFields.length > 1 || fields[depFields[0]].el[0] !== event.relatedTarget) {
                for (var i = 0; i < depFields.length; i++) {
                    var depRequiredTest = fields[depFields[i]].el.isBlank(bsv);
                    var depFormGroup = fields[depFields[i]].el.parents('.form-group');
                    styleClass = 'help-required';
                    depRequiredTest = depRequiredTest && isDependent(fields, depFields[i]);
                    var hasError = toggleHelpText(depRequiredTest, fields[depFields[i]].required.helpText, depFormGroup, styleClass);
                    if(hasError) {
                        depFormGroup.addClass('has-error');
                    } else {
                        depFormGroup.removeClass('has-error');
                    }
                }
            }
        }
        if(fields[key].required !== undefined){
            var requiredTest = fields[key].el.isBlank(bsv);
            styleClass = 'help-required';
            requiredTest = requiredTest && isDependent(fields, key);
            errCnt += toggleHelpText(requiredTest, fields[key].required.helpText, formGroup, styleClass);
        }
        if(fields[key].email !== undefined){
            styleClass = 'help-email';
            errCnt += toggleHelpText(!isValidEmail(v) && v !== "", fields[key].email.helpText, formGroup, styleClass);
        }
        if(fields[key].characters !== undefined){
            styleClass = 'help-characters';
            errCnt += toggleHelpText(v.length > fields[key].characters.limit, fields[key].characters.helpText, formGroup, styleClass);
        }
        if(fields[key].regex !== undefined){
            styleClass = 'help-regex';
            errCnt += toggleHelpText(!regexMatch(fields[key].regex.pattern, v) && !el.isBlank(bsv), fields[key].regex.helpText, formGroup, styleClass);
        }
        if(fields[key].match !== undefined){
            styleClass = 'help-match';
            var matchFieldValue = form.find('[name="'+fields[key].match.field+'"]').val();
            errCnt += toggleHelpText(matchFieldValue !== v && !el.isBlank(bsv), fields[key].match.helpText, formGroup, styleClass);
        }
        if(errCnt > 0){
            formGroup.addClass('has-error');
        }else{
            formGroup.removeClass('has-error');
        }
    }

    function regexMatch(regex, value){
        return value.match(regex);
    }

    function isValidEmail(email){
         var re = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/i;
         return re.test(email);
    }

})( jQuery, window, document );
<|endoftext|>


<commit_before>'use strict';

// modules
try {
    require('graphdat'); // manually installed, not part of package.json
} catch(e) {
    console.log('[NOTE]: graphdat is not installed, given that it\'s a manually installed module and not part of package.json, we\'re ignoring error and continuing.');
}

var env = process.env.NODE_ENV || 'development';

var path    = require('path');
var fs      = require('fs');
var yaml    = require('js-yaml');
var express = require('express');
var http    = require('http');
var app     = express();

// middleware
var favicon        = require('serve-favicon');
var logger         = require('morgan');
var serveStatic    = require('serve-static');
var errorHandler   = require('errorhandler');

var config = yaml.safeLoad(fs.readFileSync(path.join(__dirname, 'config', '_config.yml'), 'utf8'));
var tweets = yaml.safeLoad(fs.readFileSync(path.join(__dirname, 'config', '_tweets.yml'), 'utf8'));

// all environments
app.set('port', process.env.PORT || config.port || 3000);
app.set('views', path.join(__dirname, '/views'));
app.set('view engine', 'jade');
app.disable('x-powered-by');

// production
if (env === 'production') {
    app.use(logger());
} else {
    app.locals.pretty = true;
    app.use(logger('dev'));
    app.use(errorHandler({ dumpExceptions: true, showStack: true }));
}

// in line middleware actions
app.use(function(req, res, next) {
    // make config available in routes
    req.config = config;
    next();
});

app.use(function(req, res, next) {
  // overwrite default cache-control header
  // drop to 10 minutes
  res.setHeader("Cache-Control", "public, max-age=600");

  // enable bootlint where applicable
  if (req.query.bootlint && req.query.bootlint === 'true') {
      config.bootlint.forEach(function (bootlint) {
          if (bootlint.latest === true) {
              app.locals.bootlint = bootlint.javascript;

              if (env !== 'production') {
                  app.locals.bootlint = app.locals.bootlint.replace('//maxcdn.bootstrapcdn.com', '');
              }

          }
      });
  }

  next();
});

// middleware
app.use(favicon(path.join(__dirname, 'public' + config.favicon)));
app.use(serveStatic(path.join(__dirname, 'public')));

// locals
app.locals.helpers = require('./lib/helpers');
app.locals.commaIt = require('comma-it');
app.locals.config  = config;
app.locals.tweets  = tweets;

// routes
var extras = require('./routes/extras');
app.get('/',                require('./routes').index);
app.get('/extras/popular',  extras.popular);
app.get('/extras/app',      extras.app);
app.get('/extras/birthday', extras.birthday);

// redirects
var redirects = yaml.safeLoad(fs.readFileSync(path.join(__dirname, 'config', '_redirects.yml'), 'utf8'));
Object.keys(redirects).forEach(function(requested) {
    app.get(requested, function(req, res) { res.redirect(301, redirects[requested]); });
});

// start
http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

// vim: ft=javascript sw=4 sts=4 et:
<commit_msg>Fix morgan deprecation warning.<commit_after>'use strict';

// modules
try {
    require('graphdat'); // manually installed, not part of package.json
} catch(e) {
    console.log('[NOTE]: graphdat is not installed, given that it\'s a manually installed module and not part of package.json, we\'re ignoring error and continuing.');
}

var env = process.env.NODE_ENV || 'development';

var path    = require('path');
var fs      = require('fs');
var yaml    = require('js-yaml');
var express = require('express');
var http    = require('http');
var app     = express();

// middleware
var favicon        = require('serve-favicon');
var logger         = require('morgan');
var serveStatic    = require('serve-static');
var errorHandler   = require('errorhandler');

var config = yaml.safeLoad(fs.readFileSync(path.join(__dirname, 'config', '_config.yml'), 'utf8'));
var tweets = yaml.safeLoad(fs.readFileSync(path.join(__dirname, 'config', '_tweets.yml'), 'utf8'));

// all environments
app.set('port', process.env.PORT || config.port || 3000);
app.set('views', path.join(__dirname, '/views'));
app.set('view engine', 'jade');
app.disable('x-powered-by');

// production
if (env === 'production') {
    app.use(logger('combined'));
} else {
    app.locals.pretty = true;
    app.use(logger('dev'));
    app.use(errorHandler({ dumpExceptions: true, showStack: true }));
}

// in line middleware actions
app.use(function(req, res, next) {
    // make config available in routes
    req.config = config;
    next();
});

app.use(function(req, res, next) {
  // overwrite default cache-control header
  // drop to 10 minutes
  res.setHeader("Cache-Control", "public, max-age=600");

  // enable bootlint where applicable
  if (req.query.bootlint && req.query.bootlint === 'true') {
      config.bootlint.forEach(function (bootlint) {
          if (bootlint.latest === true) {
              app.locals.bootlint = bootlint.javascript;

              if (env !== 'production') {
                  app.locals.bootlint = app.locals.bootlint.replace('//maxcdn.bootstrapcdn.com', '');
              }

          }
      });
  }

  next();
});

// middleware
app.use(favicon(path.join(__dirname, 'public' + config.favicon)));
app.use(serveStatic(path.join(__dirname, 'public')));

// locals
app.locals.helpers = require('./lib/helpers');
app.locals.commaIt = require('comma-it');
app.locals.config  = config;
app.locals.tweets  = tweets;

// routes
var extras = require('./routes/extras');
app.get('/',                require('./routes').index);
app.get('/extras/popular',  extras.popular);
app.get('/extras/app',      extras.app);
app.get('/extras/birthday', extras.birthday);

// redirects
var redirects = yaml.safeLoad(fs.readFileSync(path.join(__dirname, 'config', '_redirects.yml'), 'utf8'));
Object.keys(redirects).forEach(function(requested) {
    app.get(requested, function(req, res) { res.redirect(301, redirects[requested]); });
});

// start
http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

// vim: ft=javascript sw=4 sts=4 et:
<|endoftext|>


<commit_before>// Copyright (c) 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
 * @implements {SDK.SDKModelObserver<!SDK.ResourceTreeModel>}
 * @unrestricted
 */
Resources.AppManifestView = class extends UI.VBox {
  constructor() {
    super(true);
    this.registerRequiredCSS('resources/appManifestView.css');

    this._emptyView = new UI.EmptyWidget(Common.UIString('No manifest detected'));
    const p = this._emptyView.appendParagraph();
    const linkElement = UI.XLink.create(
        'https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/?utm_source=devtools',
        Common.UIString('Read more about the web manifest'));
    p.appendChild(UI.formatLocalized('A web manifest allows you to control how your app behaves when launched and displayed to the user. %s', [linkElement]));

    this._emptyView.show(this.contentElement);
    this._emptyView.hideWidget();

    this._reportView = new UI.ReportView(Common.UIString('App Manifest'));
    this._reportView.show(this.contentElement);
    this._reportView.hideWidget();

    this._errorsSection = this._reportView.appendSection(Common.UIString('Errors and warnings'));
    this._identitySection = this._reportView.appendSection(Common.UIString('Identity'));
    const toolbar = this._identitySection.createToolbar();
    toolbar.renderAsLinks();
    const addToHomeScreen =
        new UI.ToolbarButton(Common.UIString('Add to homescreen'), undefined, Common.UIString('Add to homescreen'));
    addToHomeScreen.addEventListener(UI.ToolbarButton.Events.Click, this._addToHomescreen, this);
    toolbar.appendToolbarItem(addToHomeScreen);

    this._presentationSection = this._reportView.appendSection(Common.UIString('Presentation'));
    this._iconsSection = this._reportView.appendSection(Common.UIString('Icons'));

    this._nameField = this._identitySection.appendField(Common.UIString('Name'));
    this._shortNameField = this._identitySection.appendField(Common.UIString('Short name'));

    this._startURLField = this._presentationSection.appendField(Common.UIString('Start URL'));

    const themeColorField = this._presentationSection.appendField(Common.UIString('Theme color'));
    this._themeColorSwatch = InlineEditor.ColorSwatch.create();
    themeColorField.appendChild(this._themeColorSwatch);

    const backgroundColorField = this._presentationSection.appendField(Common.UIString('Background color'));
    this._backgroundColorSwatch = InlineEditor.ColorSwatch.create();
    backgroundColorField.appendChild(this._backgroundColorSwatch);

    this._orientationField = this._presentationSection.appendField(Common.UIString('Orientation'));
    this._displayField = this._presentationSection.appendField(Common.UIString('Display'));

    SDK.targetManager.observeModels(SDK.ResourceTreeModel, this);
  }

  /**
   * @override
   * @param {!SDK.ResourceTreeModel} resourceTreeModel
   */
  modelAdded(resourceTreeModel) {
    if (this._resourceTreeModel)
      return;
    this._resourceTreeModel = resourceTreeModel;
    this._updateManifest();
    resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated, this._updateManifest, this);
  }

  /**
   * @override
   * @param {!SDK.ResourceTreeModel} resourceTreeModel
   */
  modelRemoved(resourceTreeModel) {
    if (!this._resourceTreeModel || this._resourceTreeModel !== resourceTreeModel)
      return;
    resourceTreeModel.removeEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated, this._updateManifest, this);
    delete this._resourceTreeModel;
  }

  _updateManifest() {
    this._resourceTreeModel.fetchAppManifest(this._renderManifest.bind(this));
  }

  /**
   * @param {string} url
   * @param {?string} data
   * @param {!Array<!Protocol.Page.AppManifestError>} errors
   */
  _renderManifest(url, data, errors) {
    if (!data && !errors.length) {
      this._emptyView.showWidget();
      this._reportView.hideWidget();
      return;
    }
    this._emptyView.hideWidget();
    this._reportView.showWidget();

    this._reportView.setURL(Components.Linkifier.linkifyURL(url));
    this._errorsSection.clearContent();
    this._errorsSection.element.classList.toggle('hidden', !errors.length);
    for (const error of errors) {
      this._errorsSection.appendRow().appendChild(
          UI.createLabel(error.message, error.critical ? 'smallicon-error' : 'smallicon-warning'));
    }

    if (!data)
      return;

    if (data.charCodeAt(0) === 0xFEFF)
      data = data.slice(1);  // Trim the BOM as per https://tools.ietf.org/html/rfc7159#section-8.1.

    const parsedManifest = JSON.parse(data);
    this._nameField.textContent = stringProperty('name');
    this._shortNameField.textContent = stringProperty('short_name');
    this._startURLField.removeChildren();
    const startURL = stringProperty('start_url');
    if (startURL) {
      const completeURL = /** @type {string} */ (Common.ParsedURL.completeURL(url, startURL));
      this._startURLField.appendChild(Components.Linkifier.linkifyURL(completeURL, {text: startURL}));
    }

    this._themeColorSwatch.classList.toggle('hidden', !stringProperty('theme_color'));
    const themeColor = Common.Color.parse(stringProperty('theme_color') || 'white') || Common.Color.parse('white');
    this._themeColorSwatch.setColor(/** @type {!Common.Color} */ (themeColor));
    this._backgroundColorSwatch.classList.toggle('hidden', !stringProperty('background_color'));
    const backgroundColor =
        Common.Color.parse(stringProperty('background_color') || 'white') || Common.Color.parse('white');
    this._backgroundColorSwatch.setColor(/** @type {!Common.Color} */ (backgroundColor));

    this._orientationField.textContent = stringProperty('orientation');
    this._displayField.textContent = stringProperty('display');

    const icons = parsedManifest['icons'] || [];
    this._iconsSection.clearContent();
    for (const icon of icons) {
      const title = (icon['sizes'] || '') + '\n' + (icon['type'] || '');
      const field = this._iconsSection.appendField(title);
      const imageElement = field.createChild('img');
      imageElement.style.maxWidth = '200px';
      imageElement.style.maxHeight = '200px';
      imageElement.src = Common.ParsedURL.completeURL(url, icon['src']);
    }

    /**
     * @param {string} name
     * @return {string}
     */
    function stringProperty(name) {
      const value = parsedManifest[name];
      if (typeof value !== 'string')
        return '';
      return value;
    }
  }

  /**
   * @param {!Common.Event} event
   */
  _addToHomescreen(event) {
    const target = SDK.targetManager.mainTarget();
    if (target && target.type() === SDK.Target.Type.Frame) {
      target.pageAgent().requestAppBanner();
      Common.console.show();
    }
  }
};
<commit_msg>DevTools: surface the PWA installability warnings in the manifest view.<commit_after>// Copyright (c) 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
 * @implements {SDK.SDKModelObserver<!SDK.ResourceTreeModel>}
 * @unrestricted
 */
Resources.AppManifestView = class extends UI.VBox {
  constructor() {
    super(true);
    this.registerRequiredCSS('resources/appManifestView.css');

    this._emptyView = new UI.EmptyWidget(Common.UIString('No manifest detected'));
    const p = this._emptyView.appendParagraph();
    const linkElement = UI.XLink.create(
        'https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/?utm_source=devtools',
        Common.UIString('Read more about the web manifest'));
    p.appendChild(UI.formatLocalized('A web manifest allows you to control how your app behaves when launched and displayed to the user. %s', [linkElement]));

    this._emptyView.show(this.contentElement);
    this._emptyView.hideWidget();

    this._reportView = new UI.ReportView(Common.UIString('App Manifest'));
    this._reportView.show(this.contentElement);
    this._reportView.hideWidget();

    this._errorsSection = this._reportView.appendSection(Common.UIString('Errors and warnings'));
    this._installabilitySection = this._reportView.appendSection(Common.UIString('Installability'));
    this._identitySection = this._reportView.appendSection(Common.UIString('Identity'));

    this._presentationSection = this._reportView.appendSection(Common.UIString('Presentation'));
    this._iconsSection = this._reportView.appendSection(Common.UIString('Icons'));

    this._nameField = this._identitySection.appendField(Common.UIString('Name'));
    this._shortNameField = this._identitySection.appendField(Common.UIString('Short name'));

    this._startURLField = this._presentationSection.appendField(Common.UIString('Start URL'));

    const themeColorField = this._presentationSection.appendField(Common.UIString('Theme color'));
    this._themeColorSwatch = InlineEditor.ColorSwatch.create();
    themeColorField.appendChild(this._themeColorSwatch);

    const backgroundColorField = this._presentationSection.appendField(Common.UIString('Background color'));
    this._backgroundColorSwatch = InlineEditor.ColorSwatch.create();
    backgroundColorField.appendChild(this._backgroundColorSwatch);

    this._orientationField = this._presentationSection.appendField(Common.UIString('Orientation'));
    this._displayField = this._presentationSection.appendField(Common.UIString('Display'));

    SDK.targetManager.observeModels(SDK.ResourceTreeModel, this);
  }

  /**
   * @override
   * @param {!SDK.ResourceTreeModel} resourceTreeModel
   */
  modelAdded(resourceTreeModel) {
    if (this._resourceTreeModel)
      return;
    this._resourceTreeModel = resourceTreeModel;
    this._updateManifest();
    resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.DOMContentLoaded, this._updateManifest, this);
  }

  /**
   * @override
   * @param {!SDK.ResourceTreeModel} resourceTreeModel
   */
  modelRemoved(resourceTreeModel) {
    if (!this._resourceTreeModel || this._resourceTreeModel !== resourceTreeModel)
      return;
    resourceTreeModel.removeEventListener(SDK.ResourceTreeModel.Events.DOMContentLoaded, this._updateManifest, this);
    delete this._resourceTreeModel;
  }

  _updateManifest() {
    this._resourceTreeModel.fetchAppManifest(this._renderManifest.bind(this));
  }

  /**
   * @param {string} url
   * @param {?string} data
   * @param {!Array<!Protocol.Page.AppManifestError>} errors
   */
  _renderManifest(url, data, errors) {
    if (!data && !errors.length) {
      this._emptyView.showWidget();
      this._reportView.hideWidget();
      return;
    }
    this._emptyView.hideWidget();
    this._reportView.showWidget();

    this._reportView.setURL(Components.Linkifier.linkifyURL(url));
    this._errorsSection.clearContent();
    this._errorsSection.element.classList.toggle('hidden', !errors.length);
    for (const error of errors) {
      this._errorsSection.appendRow().appendChild(
          UI.createLabel(error.message, error.critical ? 'smallicon-error' : 'smallicon-warning'));
    }

    if (!data)
      return;

    const installabilityErrors = [];

    if (data.charCodeAt(0) === 0xFEFF)
      data = data.slice(1);  // Trim the BOM as per https://tools.ietf.org/html/rfc7159#section-8.1.

    const parsedManifest = JSON.parse(data);
    this._nameField.textContent = stringProperty('name');
    this._shortNameField.textContent = stringProperty('short_name');
    if (!this._nameField.textContent && !this._shortNameField.textContent)
      installabilityErrors.push(ls`Either 'name' or 'short_name' is required`);

    this._startURLField.removeChildren();
    const startURL = stringProperty('start_url');
    if (startURL) {
      const completeURL = /** @type {string} */ (Common.ParsedURL.completeURL(url, startURL));
      this._startURLField.appendChild(Components.Linkifier.linkifyURL(completeURL, {text: startURL}));
    } else {
      installabilityErrors.push(ls`'start_url' needs to be a valid URL`);
    }

    this._themeColorSwatch.classList.toggle('hidden', !stringProperty('theme_color'));
    const themeColor = Common.Color.parse(stringProperty('theme_color') || 'white') || Common.Color.parse('white');
    this._themeColorSwatch.setColor(/** @type {!Common.Color} */ (themeColor));
    this._backgroundColorSwatch.classList.toggle('hidden', !stringProperty('background_color'));
    const backgroundColor =
        Common.Color.parse(stringProperty('background_color') || 'white') || Common.Color.parse('white');
    this._backgroundColorSwatch.setColor(/** @type {!Common.Color} */ (backgroundColor));

    this._orientationField.textContent = stringProperty('orientation');
    const displayType = stringProperty('display');
    this._displayField.textContent = displayType;
    if (!['minimal-ui', 'standalone', 'fullscreen'].includes(displayType))
      installabilityErrors.push(ls`'display' property must be set to 'standalone', 'fullscreen' or 'minimal-ui'`);

    const icons = parsedManifest['icons'] || [];
    let hasInstallableIcon = false;
    this._iconsSection.clearContent();
    for (const icon of icons) {
      if (!icon.sizes)
        hasInstallableIcon = true;  // any
      const title = (icon['sizes'] || '') + '\n' + (icon['type'] || '');
      try {
        const widthHeight = icon['sizes'].split('x');
        if (parseInt(widthHeight[0], 10) >= 144 && parseInt(widthHeight[1], 10) >= 144)
          hasInstallableIcon = true;
      } catch (e) {
      }
      const field = this._iconsSection.appendField(title);
      const imageElement = field.createChild('img');
      imageElement.style.maxWidth = '200px';
      imageElement.style.maxHeight = '200px';
      imageElement.src = Common.ParsedURL.completeURL(url, icon['src']);
    }
    if (!hasInstallableIcon)
      installabilityErrors.push(ls`An icon at least 144px x 144px large is required`);
    this._installabilitySection.clearContent();
    this._installabilitySection.element.classList.toggle('hidden', !installabilityErrors.length);
    for (const error of installabilityErrors)
      this._installabilitySection.appendRow().appendChild(UI.createLabel(error, 'smallicon-warning'));

    /**
     * @param {string} name
     * @return {string}
     */
    function stringProperty(name) {
      const value = parsedManifest[name];
      if (typeof value !== 'string')
        return '';
      return value;
    }
  }
};
<|endoftext|>


<commit_before>(function () {

    var setup = function () {
        document.open();
    };

    var close = function () {
        document.close();
    };

    var renderPlayerTable = function (nPlayer, aPlayerTable) {

        var i, oPlayerTableView = document.getElementById('table' + nPlayer);

        while (oPlayerTableView.firstChild) {
            oPlayerTableView.removeChild(oPlayerTableView.firstChild);
        }

        for (i = 0; i < aPlayerTable.length; i++) {
            addCardToView(oPlayerTableView, aPlayerTable[i]);
        }

    };

    var renderPlayerHand = function (nPlayer, aPlayerCards) {

        var oPlayerHandView = document.getElementById('hand' + nPlayer);

        while (oPlayerHandView.firstChild) {
            oPlayerHandView.removeChild(oPlayerHandView.firstChild);
        }

        for (i = 0; i < aPlayerCards.length; i++) {
            addCardToView(oPlayerHandView, aPlayerCards[i]);
        }
    };

    var putCardOnTable = function (aPlayerTable, aPlayerCards) {
        aPlayerTable.push(aPlayerCards[0]);
        aPlayerCards.splice(0, 1);
    };

    var clearTable = function (aPlayerTable) {
        aPlayerTable.splice(0);
    };

    var getTableCard = function (aPlayerTable) {
        return aPlayerTable[aPlayerTable.length - 1];
    };

    var isGameFinished = function (aPlayer1Cards, aPlayer2Cards) {
        if (aPlayer1Cards.length === 0) {
            console.log('player 2 wins');
            return true;
        } else if (aPlayer2Cards.length === 0) {
            console.log('player 1 wins');
            return true;
        }
        return false;
    };

    var makeView = function (aPlayer1Cards, aPlayer2Cards) {

        var nPlayState = 0;
        var aPlayer1Table = [];
        var aPlayer2Table = [];

        var PLAY_STATE = {
            movingToTable: 0,
            checkingTable: 1
        }

        var doTurn = function (aPlayer1Cards, aPlayer2Cards) {

        switch (nPlayState) {
            case PLAY_STATE.movingToTable:

                if (isGameFinished(aPlayer1Cards, aPlayer2Cards)) {
                    return;
                }

                putCardOnTable(aPlayer1Table, aPlayer1Cards);
                putCardOnTable(aPlayer2Table, aPlayer2Cards);

                nPlayState = PLAY_STATE.checkingTable;

                break;

            case PLAY_STATE.checkingTable:

                if (getTableCard(aPlayer1Table) > getTableCard(aPlayer2Table)) {
                    Array.prototype.push.apply(aPlayer1Cards, aPlayer1Table);
                    Array.prototype.push.apply(aPlayer1Cards, aPlayer2Table);
                    clearTable(aPlayer1Table);
                    clearTable(aPlayer2Table);
                } else if (getTableCard(aPlayer1Table) < getTableCard(aPlayer2Table)) {
                    Array.prototype.push.apply(aPlayer2Cards, aPlayer1Table);
                    Array.prototype.push.apply(aPlayer2Cards, aPlayer2Table);
                    clearTable(aPlayer1Table);
                    clearTable(aPlayer2Table);
                } else if (getTableCard(aPlayer1Table) === getTableCard(aPlayer2Table)) {
                    putCardOnTable(aPlayer1Table, aPlayer1Cards);
                    putCardOnTable(aPlayer2Table, aPlayer2Cards);
                }

                isGameFinished(aPlayer1Cards, aPlayer2Cards);
                nPlayState = PLAY_STATE.movingToTable;

                break;
            default:
                break;
            }

            renderPlayerTable(1, aPlayer1Table);
            renderPlayerTable(2, aPlayer2Table);
            renderPlayerHand(1, aPlayer1Cards);
            renderPlayerHand(2, aPlayer2Cards);
        };

        var oPlayBtn = document.createElement('button');
        var oContent = document.createTextNode('Play');
        oPlayBtn.appendChild(oContent);
        oPlayBtn.onclick = doTurn.bind(this, aPlayer1Cards, aPlayer2Cards);
        document.body.insertBefore(oPlayBtn, null);

        var oPlayer1View = document.createElement('div');
        oPlayer1View.setAttribute('class', 'player');
        oPlayer1View.setAttribute('id', 'player1');

        document.body.insertBefore(oPlayer1View, null);

        var oPlayer2View = document.createElement('div');
        oPlayer2View.setAttribute('class', 'player');
        oPlayer2View.setAttribute('id', 'player2');

        document.body.insertBefore(oPlayer2View, null);

        var oPlayer1TableView = document.createElement('div');
        oPlayer1TableView.setAttribute('class', 'table');
        oPlayer1TableView.setAttribute('id', 'table1');

        oPlayer1View.insertBefore(oPlayer1TableView, null);

        var oPlayer2TableView = document.createElement('div');
        oPlayer2TableView.setAttribute('class', 'table');
        oPlayer2TableView.setAttribute('id', 'table2');

        oPlayer2View.insertBefore(oPlayer2TableView, null);

        var oPlayer1HandView = document.createElement('div');
        oPlayer1HandView.setAttribute('class', 'hand');
        oPlayer1HandView.setAttribute('id', 'hand1');

        oPlayer1View.insertBefore(oPlayer1HandView, null);

        var oPlayer2HandView = document.createElement('div');
        oPlayer2HandView.setAttribute('class', 'hand');
        oPlayer2HandView.setAttribute('id', 'hand2');

        oPlayer2View.insertBefore(oPlayer2HandView, null);

        renderPlayerTable(1, aPlayer1Table);
        renderPlayerTable(2, aPlayer2Table);
        renderPlayerHand(1, aPlayer1Cards);
        renderPlayerHand(2, aPlayer2Cards);
    };

    var addCardToView = function (oView, nCard) {

        var oCardView = document.createElement('div');
        oCardView.setAttribute('class', 'card');
        oCardView.setAttribute('id', 'card' + nCard);

        var oCardFaceView = document.createElement('div');
        oCardFaceView.setAttribute('class', 'content');

        var oCardFaceText = document.createTextNode(nCard);
        oCardFaceView.appendChild(oCardFaceText);

        oCardView.insertBefore(oCardFaceView, null);

        oView.insertBefore(oCardView, null);
    };

    var distribute = function (aCards) {

        var oGameView = document.getElementById('game');

        var i, oCard;
        var aPlayer1Cards = [],
            aPlayer2Cards = [];

        var aDistributedCards = [];

        for (i = 0; i < aCards.length; i++) {
            oCard = aCards[i];

            if (i % 2 === 0) {
                aPlayer1Cards.push(oCard);
            } else {
                aPlayer2Cards.push(oCard);
            }
        }

        aDistributedCards[0] = aPlayer1Cards;
        aDistributedCards[1] = aPlayer2Cards;

        return aDistributedCards;
    };

    setup();

    aCards = [1, 4, 6, 5, 3, 1, 2, 6, 6, 1, 4];

    aDistributedCards = distribute(aCards);
    makeView(aDistributedCards[0], aDistributedCards[1]);

    close();
} ());<commit_msg>more jslint<commit_after>(function () {

    var setup = function () {
        document.open();
    };

    var close = function () {
        document.close();
    };

    var renderPlayerTable = function (nPlayer, aPlayerTable) {

        var i, oPlayerTableView = document.getElementById('table' + nPlayer);

        while (oPlayerTableView.firstChild) {
            oPlayerTableView.removeChild(oPlayerTableView.firstChild);
        }

        for (i = 0; i < aPlayerTable.length; i++) {
            addCardToView(oPlayerTableView, aPlayerTable[i]);
        }

    };

    var renderPlayerHand = function (nPlayer, aPlayerCards) {

        var oPlayerHandView = document.getElementById('hand' + nPlayer);

        while (oPlayerHandView.firstChild) {
            oPlayerHandView.removeChild(oPlayerHandView.firstChild);
        }

        for (i = 0; i < aPlayerCards.length; i++) {
            addCardToView(oPlayerHandView, aPlayerCards[i]);
        }
    };

    var putCardOnTable = function (aPlayerTable, aPlayerCards) {
        aPlayerTable.push(aPlayerCards[0]);
        aPlayerCards.splice(0, 1);
    };

    var clearTable = function (aPlayerTable) {
        aPlayerTable.splice(0);
    };

    var getTableCard = function (aPlayerTable) {
        return aPlayerTable[aPlayerTable.length - 1];
    };

    var isGameFinished = function (aPlayer1Cards, aPlayer2Cards) {
        if (aPlayer1Cards.length === 0) {
            console.log('player 2 wins');
            return true;
        } else if (aPlayer2Cards.length === 0) {
            console.log('player 1 wins');
            return true;
        }
        return false;
    };

    var makeView = function (aPlayer1Cards, aPlayer2Cards) {

        var nPlayState = 0;
        var aPlayer1Table = [];
        var aPlayer2Table = [];

        var PLAY_STATE = {
            movingToTable: 0,
            checkingTable: 1
        }

        var doTurn = function (aPlayer1Cards, aPlayer2Cards) {

            switch (nPlayState) {
                case PLAY_STATE.movingToTable:

                    if (isGameFinished(aPlayer1Cards, aPlayer2Cards)) {
                        return;
                    }

                    putCardOnTable(aPlayer1Table, aPlayer1Cards);
                    putCardOnTable(aPlayer2Table, aPlayer2Cards);

                    nPlayState = PLAY_STATE.checkingTable;

                    break;

                case PLAY_STATE.checkingTable:

                    if (getTableCard(aPlayer1Table) > getTableCard(aPlayer2Table)) {
                        Array.prototype.push.apply(aPlayer1Cards, aPlayer1Table);
                        Array.prototype.push.apply(aPlayer1Cards, aPlayer2Table);
                        clearTable(aPlayer1Table);
                        clearTable(aPlayer2Table);
                    } else if (getTableCard(aPlayer1Table) < getTableCard(aPlayer2Table)) {
                        Array.prototype.push.apply(aPlayer2Cards, aPlayer1Table);
                        Array.prototype.push.apply(aPlayer2Cards, aPlayer2Table);
                        clearTable(aPlayer1Table);
                        clearTable(aPlayer2Table);
                    } else if (getTableCard(aPlayer1Table) === getTableCard(aPlayer2Table)) {
                        putCardOnTable(aPlayer1Table, aPlayer1Cards);
                        putCardOnTable(aPlayer2Table, aPlayer2Cards);
                    }

                    isGameFinished(aPlayer1Cards, aPlayer2Cards);
                    nPlayState = PLAY_STATE.movingToTable;

                    break;
                default:
                    break;
            }

            renderPlayerTable(1, aPlayer1Table);
            renderPlayerTable(2, aPlayer2Table);
            renderPlayerHand(1, aPlayer1Cards);
            renderPlayerHand(2, aPlayer2Cards);
        };

        var oPlayBtn = document.createElement('button');
        var oContent = document.createTextNode('Play');
        oPlayBtn.appendChild(oContent);
        oPlayBtn.onclick = doTurn.bind(this, aPlayer1Cards, aPlayer2Cards);
        document.body.insertBefore(oPlayBtn, null);

        var oPlayer1View = document.createElement('div');
        oPlayer1View.setAttribute('class', 'player');
        oPlayer1View.setAttribute('id', 'player1');

        document.body.insertBefore(oPlayer1View, null);

        var oPlayer2View = document.createElement('div');
        oPlayer2View.setAttribute('class', 'player');
        oPlayer2View.setAttribute('id', 'player2');

        document.body.insertBefore(oPlayer2View, null);

        var oPlayer1TableView = document.createElement('div');
        oPlayer1TableView.setAttribute('class', 'table');
        oPlayer1TableView.setAttribute('id', 'table1');

        oPlayer1View.insertBefore(oPlayer1TableView, null);

        var oPlayer2TableView = document.createElement('div');
        oPlayer2TableView.setAttribute('class', 'table');
        oPlayer2TableView.setAttribute('id', 'table2');

        oPlayer2View.insertBefore(oPlayer2TableView, null);

        var oPlayer1HandView = document.createElement('div');
        oPlayer1HandView.setAttribute('class', 'hand');
        oPlayer1HandView.setAttribute('id', 'hand1');

        oPlayer1View.insertBefore(oPlayer1HandView, null);

        var oPlayer2HandView = document.createElement('div');
        oPlayer2HandView.setAttribute('class', 'hand');
        oPlayer2HandView.setAttribute('id', 'hand2');

        oPlayer2View.insertBefore(oPlayer2HandView, null);

        renderPlayerTable(1, aPlayer1Table);
        renderPlayerTable(2, aPlayer2Table);
        renderPlayerHand(1, aPlayer1Cards);
        renderPlayerHand(2, aPlayer2Cards);
    };

    var addCardToView = function (oView, nCard) {

        var oCardView = document.createElement('div');
        oCardView.setAttribute('class', 'card');
        oCardView.setAttribute('id', 'card' + nCard);

        var oCardFaceView = document.createElement('div');
        oCardFaceView.setAttribute('class', 'content');

        var oCardFaceText = document.createTextNode(nCard);
        oCardFaceView.appendChild(oCardFaceText);

        oCardView.insertBefore(oCardFaceView, null);

        oView.insertBefore(oCardView, null);
    };

    var distribute = function (aCards) {

        var oGameView = document.getElementById('game');

        var i, oCard;
        var aPlayer1Cards = [],
            aPlayer2Cards = [];

        var aDistributedCards = [];

        for (i = 0; i < aCards.length; i++) {
            oCard = aCards[i];

            if (i % 2 === 0) {
                aPlayer1Cards.push(oCard);
            } else {
                aPlayer2Cards.push(oCard);
            }
        }

        aDistributedCards[0] = aPlayer1Cards;
        aDistributedCards[1] = aPlayer2Cards;

        return aDistributedCards;
    };

    setup();

    aCards = [1, 4, 6, 5, 3, 1, 2, 6, 6, 1, 4];

    aDistributedCards = distribute(aCards);
    makeView(aCards, aDistributedCards[0], aDistributedCards[1]);

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


<commit_before>require('bitcoin-math');

var bitcoin = require('bitcoin');
var blib = require('bitcoinjs-lib');
var AllowFreeThreshold = 57600000; // COIN * 144 / 250
var config = require('./config');
var threshold = AllowFreeThreshold;
var client = new bitcoin.Client(config.client);
var HubAddress = config.address;
var Addresses = {};

//client.walletPassphrase('',5,function(err,wallet){
//  if (err) return console.log(err);
//});
function getAddresFromScriptPubKey(scriptPubKey){
  return blib.Address.fromOutputScript(blib.Script.fromHex(scriptPubKey),blib.networks.bitcoin).toString();
}

function getAddressInfo(tx){
  var addr = getAddresFromScriptPubKey(tx.scriptPubKey);
  if (!Addresses[addr] && tx.spendable){
    client.validateAddress(addr,function(err,data){
      if (err) return console.log(err);
      Addresses[addr] = data;
    });
  }
}

function mergeTransactions(){
  console.log((new Date()).toString());
  client.listUnspent(1,function(err, unspend, resHeaders) {
    if (err) return console.log(err);
    unspend.sort(function(a,b){
      // send unspandble to the end
      if(!a.spendable) return 1;
      if(!b.spendable) return -1;
      // this is a hack to get all the addresses info
      getAddressInfo(a);
      getAddressInfo(b);
      // !compressed nInputSize = 29
      //double dPriority = ((double)out.tx->vout[out.i].nValue  / (nInputSize + 78)) * (out.nDepth+1); // 78 = 2 * 34 + 10
      return b.amount.toSatoshi() * b.confirmations - a.amount.toSatoshi() * a.confirmations;
    });

    if(unspend.length < 6) {
      console.log('Not enought unspend transactions');
    } else {
      client.estimatePriority(25,function(err,minPriority){
        if (err) return console.log(err);
        if (minPriority > 0){
          threshold = minPriority;
        } else {
          threshold = AllowFreeThreshold;
        }
        while (unspend.length > 4){
          var output = {};
          output[HubAddress] = 0;
          var trx = findTransaction(unspend,output);
          if (trx) {
            if(config.passPhrase){
              client.walletPassphrase(config.passPhrase,1,function(err){
                if (err) return console.log(err);
                processTransaction(this.trx,this.output,function(){
                  client.walletLock(function(err){
                    if (err) return console.log(err);
                  });
                });
              }.bind({trx:trx,output:output}));
            } else {
              processTransaction(trx,output);
            }
          }
        }
      });
    }
  });
}

function processTransaction(trx,output,callback){
  client.createRawTransaction(trx,output,function(err,rawTransaction){
    if (err) return console.log(err);
    client.decodeRawTransaction(rawTransaction,function(err,transaction){
      if (err) return console.log(err);
        console.log('Will send txid: '+transaction.txid);
        console.log('  with total amount of '+transaction.vout[0].value+' to address '+HubAddress);
        console.log('  rawTransaction: '+rawTransaction);
      if (config.dryRun){
        console.log('  dry run nothing is send');
      } else {
        client.signRawTransaction(rawTransaction,function(err,signedTransaction){
          if (err) return console.log(err);
          client.sendRawTransaction(signedTransaction.hex,function(err){
            if (err) return console.log(err);
            console.log('Send txid: '+transaction.txid);
            if(callback){
              callback();
            }
          });
        });
      }
    });
  });
};

function findTransaction(inputs,output){
  var dPriorityInputs = 0.0;
  var nQuantityUncompressed = 0;
  var nBytes = 0;
  var nBytesInputs = 0;
  var i = 0;
  var res = [];

  function calcTx(){
    if (input.spendable) { // filter watch-only wallet transactions
      var addr = getAddresFromScriptPubKey(input.scriptPubKey);
      dPriorityInputs = dPriorityInputs + input.amount.toSatoshi() * (input.confirmations+1);
      if (Addresses[addr] && !Addresses[addr].iscompressed){
        nQuantityUncompressed++;
        nBytesInputs += 180;
      } else {
        nBytesInputs += 148;
      }
      nBytes = nBytesInputs + ((1 * 34) + 10);
    }
  }
  function addTx(){
    if (input.spendable) { // filter watch-only wallet transactions
      output[HubAddress] = output[HubAddress] + input.amount.toSatoshi();
      res.push({txid:input.txid,vout:input.vout});
      i++;
      console.log(nBytes,input.amount,nQuantityUncompressed,threshold,dPriorityInputs/(nBytes - nBytesInputs + (nQuantityUncompressed*29)));
    }
  }

  do {
    var input = inputs[0];
    calcTx();
    addTx();
    inputs.shift();
  } while (nBytes<1024 && dPriorityInputs/(nBytes - nBytesInputs + (nQuantityUncompressed*29)) < threshold && inputs.length);
  console.log('----');
  if (nBytes > 1024){
    console.log('Transaction too large');
    return false;
  }
  // Add more transactions
  while (nBytes<1024 && inputs.length){
    input = inputs.pop();
    calcTx();
    if (nBytes<1024){
      addTx();
    } else if(inputs.length && input.spendable){ //Return last transaction for next pass
      inputs.unshift(input);
    }
  }
  console.log('=====');
  if(dPriorityInputs/(nBytes - nBytesInputs + (nQuantityUncompressed*29)) < threshold){
    console.log('Not enought priority');
    return false;
  }
  if (i < 5){
    console.log('Not enought unspend transactions');
    return false;
  }
  if (output[HubAddress] < 1000000){
    console.log('Not enought bitcoin amount');
    return false;
  }
  output[HubAddress] = output[HubAddress].toBitcoin();
  return res;
}

mergeTransactions();
if (config.daemon){
  setInterval(mergeTransactions,1000 * 60 * 10);
}<commit_msg>Removed debug<commit_after>require('bitcoin-math');

var bitcoin = require('bitcoin');
var blib = require('bitcoinjs-lib');
var AllowFreeThreshold = 57600000; // COIN * 144 / 250
var config = require('./config');
var threshold = AllowFreeThreshold;
var client = new bitcoin.Client(config.client);
var HubAddress = config.address;
var Addresses = {};

//client.walletPassphrase('',5,function(err,wallet){
//  if (err) return console.log(err);
//});
function getAddresFromScriptPubKey(scriptPubKey){
  return blib.Address.fromOutputScript(blib.Script.fromHex(scriptPubKey),blib.networks.bitcoin).toString();
}

function getAddressInfo(tx){
  var addr = getAddresFromScriptPubKey(tx.scriptPubKey);
  if (!Addresses[addr] && tx.spendable){
    client.validateAddress(addr,function(err,data){
      if (err) return console.log(err);
      Addresses[addr] = data;
    });
  }
}

function mergeTransactions(){
  console.log((new Date()).toString());
  client.listUnspent(1,function(err, unspend, resHeaders) {
    if (err) return console.log(err);
    unspend.sort(function(a,b){
      // send unspandble to the end
      if(!a.spendable) return 1;
      if(!b.spendable) return -1;
      // this is a hack to get all the addresses info
      getAddressInfo(a);
      getAddressInfo(b);
      // !compressed nInputSize = 29
      //double dPriority = ((double)out.tx->vout[out.i].nValue  / (nInputSize + 78)) * (out.nDepth+1); // 78 = 2 * 34 + 10
      return b.amount.toSatoshi() * b.confirmations - a.amount.toSatoshi() * a.confirmations;
    });

    if(unspend.length < 6) {
      console.log('Not enought unspend transactions');
    } else {
      client.estimatePriority(25,function(err,minPriority){
        if (err) return console.log(err);
        if (minPriority > 0){
          threshold = minPriority;
        } else {
          threshold = AllowFreeThreshold;
        }
        while (unspend.length > 4){
          var output = {};
          output[HubAddress] = 0;
          var trx = findTransaction(unspend,output);
          if (trx) {
            if(config.passPhrase){
              client.walletPassphrase(config.passPhrase,1,function(err){
                if (err) return console.log(err);
                processTransaction(this.trx,this.output,function(){
                  client.walletLock(function(err){
                    if (err) return console.log(err);
                  });
                });
              }.bind({trx:trx,output:output}));
            } else {
              processTransaction(trx,output);
            }
          }
        }
      });
    }
  });
}

function processTransaction(trx,output,callback){
  client.createRawTransaction(trx,output,function(err,rawTransaction){
    if (err) return console.log(err);
    client.decodeRawTransaction(rawTransaction,function(err,transaction){
      if (err) return console.log(err);
        console.log('Will send txid: '+transaction.txid);
        console.log('  with total amount of '+transaction.vout[0].value+' to address '+HubAddress);
        console.log('  rawTransaction: '+rawTransaction);
      if (config.dryRun){
        console.log('  dry run nothing is send');
      } else {
        client.signRawTransaction(rawTransaction,function(err,signedTransaction){
          if (err) return console.log(err);
          client.sendRawTransaction(signedTransaction.hex,function(err){
            if (err) return console.log(err);
            console.log('Send txid: '+transaction.txid);
            if(callback){
              callback();
            }
          });
        });
      }
    });
  });
};

function findTransaction(inputs,output){
  var dPriorityInputs = 0.0;
  var nQuantityUncompressed = 0;
  var nBytes = 0;
  var nBytesInputs = 0;
  var i = 0;
  var res = [];

  function calcTx(){
    if (input.spendable) { // filter watch-only wallet transactions
      var addr = getAddresFromScriptPubKey(input.scriptPubKey);
      dPriorityInputs = dPriorityInputs + input.amount.toSatoshi() * (input.confirmations+1);
      if (Addresses[addr] && !Addresses[addr].iscompressed){
        nQuantityUncompressed++;
        nBytesInputs += 180;
      } else {
        nBytesInputs += 148;
      }
      nBytes = nBytesInputs + ((1 * 34) + 10);
    }
  }
  function addTx(){
    if (input.spendable) { // filter watch-only wallet transactions
      output[HubAddress] = output[HubAddress] + input.amount.toSatoshi();
      res.push({txid:input.txid,vout:input.vout});
      i++;
      //console.log(nBytes,input.amount,nQuantityUncompressed,threshold,dPriorityInputs/(nBytes - nBytesInputs + (nQuantityUncompressed*29)));
    }
  }

  do {
    var input = inputs[0];
    calcTx();
    addTx();
    inputs.shift();
  } while (nBytes<1024 && dPriorityInputs/(nBytes - nBytesInputs + (nQuantityUncompressed*29)) < threshold && inputs.length);
  //console.log('----');
  if (nBytes > 1024){
    console.log('Transaction too large');
    return false;
  }
  // Add more transactions
  while (nBytes<1024 && inputs.length){
    input = inputs.pop();
    calcTx();
    if (nBytes<1024){
      addTx();
    } else if(inputs.length && input.spendable){ //Return last transaction for next pass
      inputs.unshift(input);
    }
  }
  //console.log('=====');
  if(dPriorityInputs/(nBytes - nBytesInputs + (nQuantityUncompressed*29)) < threshold){
    console.log('Not enought priority');
    return false;
  }
  if (nBytes < 1024 - 180){ // Max bytes - 1 uncompressed
    console.log('Not enought unspend transactions');
    return false;
  }
  if (output[HubAddress] < 1000000){
    console.log('Not enought bitcoin amount');
    return false;
  }
  output[HubAddress] = output[HubAddress].toBitcoin();
  return res;
}

mergeTransactions();
if (config.daemon){
  setInterval(mergeTransactions,1000 * 60 * 10);
}<|endoftext|>


<commit_before>/*!
 * jQuery JSON Cookie
 *
 * Version: @VERSION
 * Released: @DATE
 * Source: http://github.com/appendto/jquery-jsoncookie
 *
 * Copyright 2010 appendTo LLC. (http://appendto.com/team)
 * Dual licensed under the MIT or GPL licenses.
 * http://appendto.com/open-source-licenses
 */
(function( $ ) {

function now() {
	return (new Date()).getTime();
}

$.cookie = function( key, value, options ) {
	options = $.extend( {}, options );
	var expires = options.expires;

	if ( arguments.length === 1 ) {
		var result = new RegExp( "(?:^|; )" + key + "=([^;]*)").exec( document.cookie );
		return result && JSON.parse( result[ 1 ] );
	} else {
		if ( value === null ) {
			expires = -1;
		}
		if ( typeof expires === "number" ) {
			expires = new Date( now() + ( expires * 864e5 ) );
		}

		document.cookie = [
			key, "=", JSON.stringify( value ),
			expires ? "; expires=" + expires.toUTCString() : "",
			options.path ? "; path=" + options.path : "",
			options.domain ? "; domain=" + options.domain : "",
			options.secure ? "; secure" : ""
		].join( "" );
	}
};

// support test
var test = "jsoncookie" + now();
$.cookie( test, test );
$.support.cookie = $.cookie( test ) === test;
$.cookie( test, null );

})( jQuery );
<commit_msg>Added ability to git all cookies as a hash.<commit_after>/*!
 * jQuery JSON Cookie
 *
 * Version: @VERSION
 * Released: @DATE
 * Source: http://github.com/appendto/jquery-jsoncookie
 *
 * Copyright 2010 appendTo LLC. (http://appendto.com/team)
 * Dual licensed under the MIT or GPL licenses.
 * http://appendto.com/open-source-licenses
 */
(function( $ ) {

var encode = encodeURIComponent,
	decode = decodeURIComponent;

function now() {
	return (new Date()).getTime();
}

$.cookie = function( key, value, options ) {
	options = $.extend( {}, options );
	var expires = options.expires,
		result;

	// get all cookies
	if ( !key ) {
		result = {};
		$.each( document.cookie.split( "; " ), function( i, cookie ) {
			var parts = cookie.split( "=" );
			result[ decode( parts[ 0 ] ) ] = JSON.parse( decode( parts[ 1 ] ) );
		});
		return result;
	}

	// get/set a specific cookie
	key = encode( key );
	if ( arguments.length === 1 ) {
		result = new RegExp( "(?:^|; )" + key + "=([^;]*)" ).exec( document.cookie );
		return result && JSON.parse( decode( result[ 1 ] ) );
	} else {
		if ( value === null ) {
			expires = -1;
		}
		if ( typeof expires === "number" ) {
			expires = new Date( now() + ( expires * 864e5 ) );
		}

		document.cookie = [
			key, "=", encode( JSON.stringify( value ) ),
			expires ? "; expires=" + expires.toUTCString() : "",
			options.path ? "; path=" + options.path : "",
			options.domain ? "; domain=" + options.domain : "",
			options.secure ? "; secure" : ""
		].join( "" );
	}
};

// support test
(function() {
	var test = "jsoncookie" + now();
	$.cookie( test, test );
	$.support.cookie = $.cookie( test ) === test;
	$.cookie( test, null );
})();

})( jQuery );
<|endoftext|>


<commit_before>/*
Data comes from https://stat.ethz.ch/R-manual/R-devel/library/MASS/html/biopsy.html
*/
var biopsyViewModel = function (data) {
    var _self = this;
    _self.SampleNumber = ko.observable(data.ID);
    _self.ClumpThickness = ko.observable(data.V1);
    _self.CellSizeUniformity = ko.observable(data.V2);
    _self.CellShapeUniformity = ko.observable(data.V3);
    _self.MarginalAdhesion = ko.observable(data.V4);
    _self.EpithelialCellSize = ko.observable(data.V5);
    _self.BareNuclei = ko.observable(data.V6);
    _self.BlandChromatin = ko.observable(data.V7);
    _self.NormalNucleoli = ko.observable(data.V8);
    _self.Mitoses = ko.observable(data.V9);
    _self.Class = ko.observable(data.class);
};

function keyMapper(key){
    switch(key){
        case "ID": return "SampleNumber";
        case "V1": return "ClumpThickness";
        case "V2": return "CellSizeUniformity";
        case "V3": return "CellShapeUniformity";
        case "V4": return "MarginalAdhesion";
        case "V5": return "EpithelialCellSize";
        case "V6": return "BareNuclei";
        case "V7": return "BlandChromatin";
        case "V8": return "NormalNucleoli";
        case "V9": return "Mitoses";
        case "class": return "Class";
    }
}

var ViewModel = function () {
    var self = this;
    self.biopsyData = ko.observableArray();
    self.valueCounts = ko.observableArray();
    self.error = ko.observable('');
    var opencpu_root = '/ocpu/library/appdemo/';
    var data_uri = opencpu_root+'data/biopsy/json';
    ocpu.seturl(opencpu_root+"/R");
    self.availableClasses = ko.observableArray();
    self.selectedClass = ko.observable();
    self.selectedClass.subscribe(function(){
        var mappedClass = keyMapper(self.selectedClass());
        var classValues =  ko.utils.arrayMap(self.biopsyData(), function(item){
            return item[mappedClass];
        });
        var distinctValues = ko.utils.arrayGetDistinctValues(classValues);
        self.valueCounts([]);
        for(var i =0; i < distinctValues.length; i++){
            var distinctValue = distinctValues[i];
            var valueCount = ko.utils.arrayFilter(self.biopsyData(), function(item){
                return item[self.selectedClass()] == keyMapper(distinctValue);
            }).length;
            self.valueCounts.push({name : distinctValue, count: valueCount});
        }
        //d3.select("svg").remove();
        var svg = d3.select("svg");
        var margin = {top: 20, right: 20, bottom: 30, left: 40};
        var width = +svg.attr("width") - margin.left - margin.right;
        var height = +svg.attr("height") - margin.top - margin.bottom;

        svg.selectAll("*").remove();
        var x = d3.scaleBand().rangeRound([0, width]).padding(0.1),
        y = d3.scaleLinear().rangeRound([height, 0]);

        var g = svg.append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
        x.domain(['benign', 'malignant']);
        y.domain([0, 500]);
        g.append("g")
              .attr("class", "axis axis--x")
              .attr("transform", "translate(0," + height + ")")
              .call(d3.axisBottom(x));

          g.append("g")
              .attr("class", "axis axis--y")
              .call(d3.axisLeft(y).ticks(10))
              .append("text")
              .attr("transform", "rotate(-90)")
              .attr("y", 6)
              .attr("dy", "0.71em")
              .attr("text-anchor", "end")
              .text("Frequency");

          g.selectAll(".bar")
            .data(self.valueCounts())
            .enter().append("rect")
            .attr("class", "bar")
            .attr("x", function(d) { return x(d.distinctValue); })
            .attr("y", function(d) { return y(d.count); })
            .attr("width", x.bandwidth())
            .attr("height", function(d) { return height - y(d.count); });
    });

    function ajaxHelper(uri, method, data) {
        self.error(''); // Clear error message
        return $.ajax({
            type: method,
            url: uri,
            dataType: 'json',
            contentType: 'application/json',
            data: data ? JSON.stringify(data) : null
        }).fail(function (jqXHR, textStatus, errorThrown) {
            self.error(errorThrown);
        });
    }

    self.getAllData = function() {
        ajaxHelper(data_uri, 'GET').done(function (json) {
            for (var i = 0; i < json.length; i++) {
                var item = new biopsyViewModel(json[i]);
                self.biopsyData.push(item);
            }
            ko.utils.arrayPushAll(self.availableClasses, Object.keys(json[0]));

            printsummary(json);
        });
    };

    function addD3Chart(){

    }

    function printsummary(mydata){
        //perform the request
        var req = ocpu.call("printsummary", {
          mydata : mydata
        }, function(session){
          session.getConsole(function(output){
            $("#output code").text(output);
          });
        }).fail(function(){
          alert("Server error: " + req.responseText);
        });
  }
};

var vm = new ViewModel();
ko.applyBindings(vm);
vm.getAllData();

<commit_msg>more mapping issues<commit_after>/*
Data comes from https://stat.ethz.ch/R-manual/R-devel/library/MASS/html/biopsy.html
*/
var biopsyViewModel = function (data) {
    var _self = this;
    _self.SampleNumber = ko.observable(data.ID);
    _self.ClumpThickness = ko.observable(data.V1);
    _self.CellSizeUniformity = ko.observable(data.V2);
    _self.CellShapeUniformity = ko.observable(data.V3);
    _self.MarginalAdhesion = ko.observable(data.V4);
    _self.EpithelialCellSize = ko.observable(data.V5);
    _self.BareNuclei = ko.observable(data.V6);
    _self.BlandChromatin = ko.observable(data.V7);
    _self.NormalNucleoli = ko.observable(data.V8);
    _self.Mitoses = ko.observable(data.V9);
    _self.Class = ko.observable(data.class);
};

function keyMapper(key){
    switch(key){
        case "ID": return "SampleNumber";
        case "V1": return "ClumpThickness";
        case "V2": return "CellSizeUniformity";
        case "V3": return "CellShapeUniformity";
        case "V4": return "MarginalAdhesion";
        case "V5": return "EpithelialCellSize";
        case "V6": return "BareNuclei";
        case "V7": return "BlandChromatin";
        case "V8": return "NormalNucleoli";
        case "V9": return "Mitoses";
        case "class": return "Class";
    }
}

var ViewModel = function () {
    var self = this;
    self.biopsyData = ko.observableArray();
    self.valueCounts = ko.observableArray();
    self.error = ko.observable('');
    var opencpu_root = '/ocpu/library/appdemo/';
    var data_uri = opencpu_root+'data/biopsy/json';
    ocpu.seturl(opencpu_root+"/R");
    self.availableClasses = ko.observableArray();
    self.selectedClass = ko.observable();
    self.selectedClass.subscribe(function(){
        var mappedClass = keyMapper(self.selectedClass());
        var classValues =  ko.utils.arrayMap(self.biopsyData(), function(item){
            return item[mappedClass]();
        });
        var distinctValues = ko.utils.arrayGetDistinctValues(classValues);
        self.valueCounts([]);
        for(var i =0; i < distinctValues.length; i++){
            var distinctValue = distinctValues[i];
            var valueCount = ko.utils.arrayFilter(self.biopsyData(), function(item){
                return item[mappedClass] == distinctValue;
            }).length;
            self.valueCounts.push({name : distinctValue, count: valueCount});
        }
        //d3.select("svg").remove();
        var svg = d3.select("svg");
        var margin = {top: 20, right: 20, bottom: 30, left: 40};
        var width = +svg.attr("width") - margin.left - margin.right;
        var height = +svg.attr("height") - margin.top - margin.bottom;

        svg.selectAll("*").remove();
        var x = d3.scaleBand().rangeRound([0, width]).padding(0.1),
        y = d3.scaleLinear().rangeRound([height, 0]);

        var g = svg.append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
        x.domain(['benign', 'malignant']);
        y.domain([0, 500]);
        g.append("g")
              .attr("class", "axis axis--x")
              .attr("transform", "translate(0," + height + ")")
              .call(d3.axisBottom(x));

          g.append("g")
              .attr("class", "axis axis--y")
              .call(d3.axisLeft(y).ticks(10))
              .append("text")
              .attr("transform", "rotate(-90)")
              .attr("y", 6)
              .attr("dy", "0.71em")
              .attr("text-anchor", "end")
              .text("Frequency");

          g.selectAll(".bar")
            .data(self.valueCounts())
            .enter().append("rect")
            .attr("class", "bar")
            .attr("x", function(d) { return x(d.distinctValue); })
            .attr("y", function(d) { return y(d.count); })
            .attr("width", x.bandwidth())
            .attr("height", function(d) { return height - y(d.count); });
    });

    function ajaxHelper(uri, method, data) {
        self.error(''); // Clear error message
        return $.ajax({
            type: method,
            url: uri,
            dataType: 'json',
            contentType: 'application/json',
            data: data ? JSON.stringify(data) : null
        }).fail(function (jqXHR, textStatus, errorThrown) {
            self.error(errorThrown);
        });
    }

    self.getAllData = function() {
        ajaxHelper(data_uri, 'GET').done(function (json) {
            for (var i = 0; i < json.length; i++) {
                var item = new biopsyViewModel(json[i]);
                self.biopsyData.push(item);
            }
            ko.utils.arrayPushAll(self.availableClasses, Object.keys(json[0]));

            printsummary(json);
        });
    };

    function addD3Chart(){

    }

    function printsummary(mydata){
        //perform the request
        var req = ocpu.call("printsummary", {
          mydata : mydata
        }, function(session){
          session.getConsole(function(output){
            $("#output code").text(output);
          });
        }).fail(function(){
          alert("Server error: " + req.responseText);
        });
  }
};

var vm = new ViewModel();
ko.applyBindings(vm);
vm.getAllData();

<|endoftext|>


<commit_before>var Discord = require('discord');
var http = require('http');

var cmdPing = require('./commands/ping');
var cmdUptime = require('./commands/uptime');
var cmdTeam = require('./commands/team');
var cmdAwards = require('./commands/awards');

var client = new Discord.Client();
var token = process.env.DISCORD_TOKEN;
var prefix = '^';

client.on('ready', () => {
	console.log('I am ready!');
});

client.on('message', message => {
	if (message.content.startsWith(prefix)) {
		handleCommand(message);
	}
});

var handleCommand = message => {
	var [cmd, args] = message.content.substring(prefix.length).split(' ', 2);

	switch (cmd) {
		case 'ping':
			cmdPing(message, args);
			break;

		case 'uptime':
			cmdUptime(message, args);
			break;

		case 'team':
			cmdTeam(message, args);
			break;

		case 'awards':
			cmdAwards(message, args);

		default:
			message.reply('Unrecognized command.');
			break;
	}
}

client.login(token);
<commit_msg>Debugging.<commit_after>var Discord = require('discord.js');
var http = require('http');

var cmdPing = require('./commands/ping');
var cmdUptime = require('./commands/uptime');
var cmdTeam = require('./commands/team');
var cmdAwards = require('./commands/awards');

var client = new Discord.Client();
var token = process.env.DISCORD_TOKEN;
var prefix = '^';

client.on('ready', () => {
	console.log('I am ready!');
});

client.on('message', message => {
	if (message.content.startsWith(prefix)) {
		handleCommand(message);
	}
});

var handleCommand = message => {
	var [cmd, args] = message.content.substring(prefix.length).split(' ', 2);

	switch (cmd) {
		case 'ping':
			cmdPing(message, args);
			break;

		case 'uptime':
			cmdUptime(message, args);
			break;

		case 'team':
			cmdTeam(message, args);
			break;

		case 'awards':
			cmdAwards(message, args);

		default:
			message.reply('Unrecognized command.');
			break;
	}
}

client.login(token);
<|endoftext|>