<commit_before>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

define([
    'base/js/namespace',
    'jquery',
    'base/js/utils',
], function(IPython, $, utils) {
    "use strict";

    var KernelSelector = function(selector, notebook) {
        var that = this;
        this.selector = selector;
        this.notebook = notebook;
        this.notebook.set_kernelselector(this);
        this.events = notebook.events;
        this.current_selection = null;
        this.kernelspecs = {};
        if (this.selector !== undefined) {
            this.element = $(selector);
            this.request_kernelspecs();
        }
        this.bind_events();
        // Make the object globally available for user convenience & inspection
        IPython.kernelselector = this;
        this._finish_load = null;
        this.loaded = new Promise(function(resolve, reject) {
            that._finish_load = resolve;
        });

        Object.seal(this);
    };

    KernelSelector.prototype.request_kernelspecs = function() {
        var url = utils.url_join_encode(this.notebook.base_url, 'api/kernelspecs');
        utils.promising_ajax(url).then($.proxy(this._got_kernelspecs, this));
    };

    KernelSelector.prototype._got_kernelspecs = function(data) {
        this.kernelspecs = data.kernelspecs;
        var change_kernel_submenu = $("#menu-change-kernel-submenu");
        var new_notebook_submenu = $("#menu-new-notebook-submenu");

        var keys = Object.keys(data.kernelspecs).sort(function (a, b) {
            // sort by display_name
            var da = data.kernelspecs[a].spec.display_name;
            var db = data.kernelspecs[b].spec.display_name;
            if (da === db) {
                return 0;
            } else if (da > db) {
                return 1;
            } else {
                return -1;
            }
        });

        var i, ks, ks_submenu_entry;
        // Create the Kernel > Change kernel submenu
        for (i = 0; i < keys.length; i++) {
            ks = this.kernelspecs[keys[i]];
            ks_submenu_entry = $("<li>").attr("id", "kernel-submenu-"+ks.name).append($('<a>')
                .attr('href', '#')
                .click(function(){
                        $.proxy(this.set_kernel, this, ks.name)
                        event.preventDefault();
                    })
                .text(ks.spec.display_name));
            change_kernel_submenu.append(ks_submenu_entry);
        }

        // Create the File > New Notebook submenu
        for (i = 0; i < keys.length; i++) {
            ks = this.kernelspecs[keys[i]];
            ks_submenu_entry = $("<li>").attr("id", "new-notebook-submenu-"+ks.name).append($('<a>')
                .attr('href', '#')
                .click(function(){
                        $.proxy(this.new_notebook, this, ks.name)
                        event.preventDefault();
                    })
                .text(ks.spec.display_name));
            new_notebook_submenu.append(ks_submenu_entry);
        }
        // trigger loaded promise
        this._finish_load();
    };

    KernelSelector.prototype._spec_changed = function (event, ks) {
        /** event handler for spec_changed */

        // update selection
        this.current_selection = ks.name;

        // put the current kernel at the top of File > New Notebook
        var cur_kernel_entry = $("#new-notebook-submenu-" + ks.name);
        var parent = cur_kernel_entry.parent();
        // do something only if there is more than one kernel
        if (parent.children().length > 1) {
            // first, sort back the submenu
            parent.append(
                parent.children("li[class!='divider']").sort(
                    function (a,b) {
                        var da = $("a",a).text();
                        var db = $("a",b).text();
                        if (da === db) {
                            return 0;
                        } else if (da > db) {
                            return 1;
                        } else {
                            return -1;
                        }}));
            // then, if there is no divider yet, add one
            if (!parent.children("li[class='divider']").length) {
                parent.prepend($("<li>").attr("class","divider"));
            }
            // finally, put the current kernel at the top
            parent.prepend(cur_kernel_entry);
        }

        // load logo
        var logo_img = this.element.find("img.current_kernel_logo");
        $("#kernel_indicator").find('.kernel_indicator_name').text(ks.spec.display_name);
        if (ks.resources['logo-64x64']) {
            logo_img.attr("src", ks.resources['logo-64x64']);
            logo_img.show();
        } else {
            logo_img.hide();
        }

        // load kernel css
        var css_url = ks.resources['kernel.css'];
        if (css_url) {
            $('#kernel-css').attr('href', css_url);
        } else {
            $('#kernel-css').attr('href', '');
        }

        // load kernel js
        if (ks.resources['kernel.js']) {
            require([ks.resources['kernel.js']],
                function (kernel_mod) {
                    if (kernel_mod && kernel_mod.onload) {
                        kernel_mod.onload();
                    } else {
                        console.warn("Kernel " + ks.name + " has a kernel.js file that does not contain "+
                                     "any asynchronous module definition. This is undefined behavior "+
                                     "and not recommended.");
                    }
                }, function (err) {
                    console.warn("Failed to load kernel.js from ", ks.resources['kernel.js'], err);
                }
            );
        }
    };

    KernelSelector.prototype.set_kernel = function (kernel_name) {
        /** set the kernel by name, ensuring kernelspecs have been loaded, first */
        var that = this;
        return this.loaded.then(function () {
            that._set_kernel(kernel_name);
        });
    };

    KernelSelector.prototype._set_kernel = function (kernel_name) {
        /** Actually set the kernel (kernelspecs have been loaded) */
        if (kernel_name === this.current_selection) {
            // only trigger event if value changed
            return;
        }
        var ks = this.kernelspecs[kernel_name];
        if (this.notebook._session_starting) {
            console.error("Cannot change kernel while waiting for pending session start.");
            return;
        }
        this.current_selection = kernel_name;
        this.events.trigger('spec_changed.Kernel', ks);
    };

    KernelSelector.prototype.new_notebook = function (kernel_name) {

        var w = window.open();
        // Create a new notebook in the same path as the current
        // notebook's path.
        var that = this;
        var parent = utils.url_path_split(that.notebook.notebook_path)[0];
        that.notebook.contents.new_untitled(parent, {type: "notebook"}).then(
            function (data) {
                var url = utils.url_join_encode(
                    that.notebook.base_url, 'notebooks', data.path
                );
                url += "?kernel_name=" + kernel_name;
                w.location = url;
            },
            function(error) {
                w.close();
                dialog.modal({
                    title : 'Creating Notebook Failed',
                    body : "The error was: " + error.message,
                    buttons : {'OK' : {'class' : 'btn-primary'}}
                });
            }
        );
    };

    KernelSelector.prototype.lock_switch = function() {
        // should set a flag and display warning+reload if user want to
        // re-change kernel. As UI discussion never finish
        // making that a separate PR.
        console.warn('switching kernel is not guaranteed to work !');
    };

    KernelSelector.prototype.bind_events = function() {
        var that = this;
        this.events.on('spec_changed.Kernel', $.proxy(this._spec_changed, this));

        this.events.on('kernel_created.Session', function (event, data) {
            that.set_kernel(data.kernel.name);
        });

        var logo_img = this.element.find("img.current_kernel_logo");
        logo_img.on("load", function() {
            logo_img.show();
        });
        logo_img.on("error", function() {
            logo_img.hide();
        });
    };

    return {'KernelSelector': KernelSelector};
});
<commit_msg>fix new-notebook and change-kernel menus<commit_after>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

define([
    'jquery',
    'base/js/namespace',
    'base/js/dialog',
    'base/js/utils',
], function($, IPython, dialog, utils) {
    "use strict";

    var KernelSelector = function(selector, notebook) {
        var that = this;
        this.selector = selector;
        this.notebook = notebook;
        this.notebook.set_kernelselector(this);
        this.events = notebook.events;
        this.current_selection = null;
        this.kernelspecs = {};
        if (this.selector !== undefined) {
            this.element = $(selector);
            this.request_kernelspecs();
        }
        this.bind_events();
        // Make the object globally available for user convenience & inspection
        IPython.kernelselector = this;
        this._finish_load = null;
        this.loaded = new Promise(function(resolve, reject) {
            that._finish_load = resolve;
        });

        Object.seal(this);
    };

    KernelSelector.prototype.request_kernelspecs = function() {
        var url = utils.url_join_encode(this.notebook.base_url, 'api/kernelspecs');
        utils.promising_ajax(url).then($.proxy(this._got_kernelspecs, this));
    };

    KernelSelector.prototype._got_kernelspecs = function(data) {
        var that = this;
        this.kernelspecs = data.kernelspecs;
        var change_kernel_submenu = $("#menu-change-kernel-submenu");
        var new_notebook_submenu = $("#menu-new-notebook-submenu");

        var keys = Object.keys(data.kernelspecs).sort(function (a, b) {
            // sort by display_name
            var da = data.kernelspecs[a].spec.display_name;
            var db = data.kernelspecs[b].spec.display_name;
            if (da === db) {
                return 0;
            } else if (da > db) {
                return 1;
            } else {
                return -1;
            }
        });

        keys.map(function (key) {
            // Create the Kernel > Change kernel submenu
            var ks = data.kernelspecs[key];
            change_kernel_submenu.append(
                $("<li>").attr("id", "kernel-submenu-"+ks.name).append(
                    $('<a>')
                        .attr('href', '#')
                        .click( function () {
                            that.set_kernel(ks.name);
                            event.preventDefault();
                        })
                        .text(ks.spec.display_name)
                )
            );
            // Create the File > New Notebook submenu
            new_notebook_submenu.append(
                $("<li>").attr("id", "new-notebook-submenu-"+ks.name).append(
                    $('<a>')
                        .attr('href', '#')
                        .click( function () {
                            that.new_notebook(ks.name);
                            event.preventDefault();
                        })
                        .text(ks.spec.display_name)
                )
            );

        });
        // trigger loaded promise
        this._finish_load();
    };

    KernelSelector.prototype._spec_changed = function (event, ks) {
        /** event handler for spec_changed */

        // update selection
        this.current_selection = ks.name;

        // put the current kernel at the top of File > New Notebook
        var cur_kernel_entry = $("#new-notebook-submenu-" + ks.name);
        var parent = cur_kernel_entry.parent();
        // do something only if there is more than one kernel
        if (parent.children().length > 1) {
            // first, sort back the submenu
            parent.append(
                parent.children("li[class!='divider']").sort(
                    function (a,b) {
                        var da = $("a",a).text();
                        var db = $("a",b).text();
                        if (da === db) {
                            return 0;
                        } else if (da > db) {
                            return 1;
                        } else {
                            return -1;
                        }}));
            // then, if there is no divider yet, add one
            if (!parent.children("li[class='divider']").length) {
                parent.prepend($("<li>").attr("class","divider"));
            }
            // finally, put the current kernel at the top
            parent.prepend(cur_kernel_entry);
        }

        // load logo
        var logo_img = this.element.find("img.current_kernel_logo");
        $("#kernel_indicator").find('.kernel_indicator_name').text(ks.spec.display_name);
        if (ks.resources['logo-64x64']) {
            logo_img.attr("src", ks.resources['logo-64x64']);
            logo_img.show();
        } else {
            logo_img.hide();
        }

        // load kernel css
        var css_url = ks.resources['kernel.css'];
        if (css_url) {
            $('#kernel-css').attr('href', css_url);
        } else {
            $('#kernel-css').attr('href', '');
        }

        // load kernel js
        if (ks.resources['kernel.js']) {
            require([ks.resources['kernel.js']],
                function (kernel_mod) {
                    if (kernel_mod && kernel_mod.onload) {
                        kernel_mod.onload();
                    } else {
                        console.warn("Kernel " + ks.name + " has a kernel.js file that does not contain "+
                                     "any asynchronous module definition. This is undefined behavior "+
                                     "and not recommended.");
                    }
                }, function (err) {
                    console.warn("Failed to load kernel.js from ", ks.resources['kernel.js'], err);
                }
            );
        }
    };

    KernelSelector.prototype.set_kernel = function (kernel_name) {
        /** set the kernel by name, ensuring kernelspecs have been loaded, first */
        var that = this;
        return this.loaded.then(function () {
            that._set_kernel(kernel_name);
        });
    };

    KernelSelector.prototype._set_kernel = function (kernel_name) {
        /** Actually set the kernel (kernelspecs have been loaded) */
        if (kernel_name === this.current_selection) {
            // only trigger event if value changed
            return;
        }
        var ks = this.kernelspecs[kernel_name];
        if (this.notebook._session_starting) {
            console.error("Cannot change kernel while waiting for pending session start.");
            return;
        }
        this.current_selection = kernel_name;
        this.events.trigger('spec_changed.Kernel', ks);
    };

    KernelSelector.prototype.new_notebook = function (kernel_name) {

        var w = window.open();
        // Create a new notebook in the same path as the current
        // notebook's path.
        var that = this;
        var parent = utils.url_path_split(that.notebook.notebook_path)[0];
        that.notebook.contents.new_untitled(parent, {type: "notebook"}).then(
            function (data) {
                var url = utils.url_join_encode(
                    that.notebook.base_url, 'notebooks', data.path
                );
                url += "?kernel_name=" + kernel_name;
                w.location = url;
            },
            function(error) {
                w.close();
                dialog.modal({
                    title : 'Creating Notebook Failed',
                    body : "The error was: " + error.message,
                    buttons : {'OK' : {'class' : 'btn-primary'}}
                });
            }
        );
    };

    KernelSelector.prototype.lock_switch = function() {
        // should set a flag and display warning+reload if user want to
        // re-change kernel. As UI discussion never finish
        // making that a separate PR.
        console.warn('switching kernel is not guaranteed to work !');
    };

    KernelSelector.prototype.bind_events = function() {
        var that = this;
        this.events.on('spec_changed.Kernel', $.proxy(this._spec_changed, this));

        this.events.on('kernel_created.Session', function (event, data) {
            that.set_kernel(data.kernel.name);
        });

        var logo_img = this.element.find("img.current_kernel_logo");
        logo_img.on("load", function() {
            logo_img.show();
        });
        logo_img.on("error", function() {
            logo_img.hide();
        });
    };

    return {'KernelSelector': KernelSelector};
});
<|endoftext|>


<commit_before>(function($){
    $.fn.validationEngineLanguage = function(){};
    $.validationEngineLanguage = {
        newLang: function(){
            $.validationEngineLanguage.allRules = {
                "required": { // Add your regex rules here, you can take telephone as an example
                    "regex": "none",
                    "alertText": "* Campo richiesto",
                    "alertTextCheckboxMultiple": "* Per favore selezionare un'opzione",
                    "alertTextCheckboxe": "* E' richiesta la selezione della casella"
                },
                "requiredInFunction": {
                    "func": function(field, rules, i, options){
                        return (field.val() == "test") ? true : false;
                    },
                    "alertText": "* Il campo deve rispondere al requisito"
                },
                "length": {
                    "regex": "none",
                    "alertText": "* Fra ",
                    "alertText2": " e ",
                    "alertText3": " caratteri permessi"
                },
                "maxCheckbox": {
                    "regex": "none",
                    "alertText": "* Numero di caselle da selezionare in eccesso"
                },
				        "groupRequired": {
                    "regex": "none",
                    "alertText": "* Almeno un campo del gruppo deve essere compilato"
                },
                "min": {
                    "regex": "none",
                    "alertText": "* Valore minimo richiesto "
                },
                "max": {
                    "regex": "none",
                    "alertText": "* Valore massimo superato "
                },
                "minCheckbox": {
                    "regex": "none",
                    "alertText": "* Per favore selezionare almeno ",
                    "alertText2": " opzioni"
                },
                "equals": {
                    "regex": "none",
                    "alertText": "* I campi non corrispondono"
                },
                "creditCard": {
                    "regex": "none",
                    "alertText": "* Non valido numero di carta di credito"
                },
                "phone": {
                    // credit: jquery.h5validate.js / orefalo
                    "regex": /^([\+][0-9]{1,3}([ \.\-])?)?([\(][0-9]{1,6}[\)])?([0-9 \.\-]{1,32})(([A-Za-z \:]{1,11})?[0-9]{1,4}?)$/,
                    "alertText": "* Numero di telefono non corretto"
                },
                "email": {
                    // Shamelessly lifted from Scott Gonzalez via the Bassistance Validation plugin http://projects.scottsplayground.com/email_address_validation/
                    "regex": /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,
                    "alertText": "* Indirizzo non corretto"
                },
                "integer": {
                    "regex": /^[\-\+]?\d+$/,
                    "alertText": "* Numero intero non corretto"
                },
                "number": {
                    // Number, including positive, negative, and floating decimal. Credit: bassistance
                    "regex": /^[\-\+]?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)$/,
                    "alertText": "* Numero decimale non corretto"
                },
                "date": {
                    "regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/,
                    "alertText": "* Data non  corretta, re-inserire secondo formato AAAA-MM-GG"
                },
                "date_mm-yy": {
                    "regex": /^\d{2}\/\d{2}$/,
                    "alertText": "* Data non corretta, re-inserire secondo formato MM/GG"
                },
                "serial_number": {
                    "regex": /^[a-zA-Z]*[a-zA-Z0-9]*$/,
                    "alertText": "Ammesse le lettere solo all'inizio del campo"
                },
                "ipv4": {
                	"regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/,
                    "alertText": "* IP non corretto"
                },
                "url": {
                    "regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,
                    "alertText": "* URL non corretta"
                },
                "onlyNumber": {
                    "regex": /^[0-9\ ]+$/,
                    "alertText": "* Solo numeri"
                },
				        "onlyLetter": {
                    "regex": /^[a-zA-Z\ \']+$/,
                    "alertText": "* Solo lettere"
                },
                "validate2fields": {
                    "nname": "validate2fields",
                    "alertText": "* Occorre inserire nome e cognome"
                },
                "noSpecialCharacters": {
                    "regex": /^[0-9a-zA-Z]+$/,
                    "alertText": "* Caratteri speciali non permessi"
                },
                "ajaxUserCall": {
                    "file": "ajaxValidateFieldName",
                    "extraData": "name=eric",
                    "alertTextLoad": "* Caricamento, attendere per favore",
                    "alertText": "* Questo user � gi� stato utilizzato"
                },
                "ajaxNameCall": {
                    "file": "ajaxValidateFieldName",
                    "alertText": "* Questo nome � gi� stato utilizzato",
                    "alertTextOk": "* Questo nome � disponibile",
                    "alertTextLoad": "* Caricamento, attendere per favore"
                }

            };

        }
    };
    $.validationEngineLanguage.newLang();
})(jQuery);
<commit_msg>eu vat validation added<commit_after>(function($){
    $.fn.validationEngineLanguage = function(){};
    $.validationEngineLanguage = {
        newLang: function(){
            $.validationEngineLanguage.allRules = {
                "required": { // Add your regex rules here, you can take telephone as an example
                    "regex": "none",
                    "alertText": "* Campo richiesto",
                    "alertTextCheckboxMultiple": "* Per favore selezionare un'opzione",
                    "alertTextCheckboxe": "* E' richiesta la selezione della casella"
                },
                "requiredInFunction": {
                    "func": function(field, rules, i, options){
                        return (field.val() == "test") ? true : false;
                    },
                    "alertText": "* Il campo deve rispondere al requisito"
                },
                "length": {
                    "regex": "none",
                    "alertText": "* Fra ",
                    "alertText2": " e ",
                    "alertText3": " caratteri permessi"
                },
                "maxCheckbox": {
                    "regex": "none",
                    "alertText": "* Numero di caselle da selezionare in eccesso"
                },
				        "groupRequired": {
                    "regex": "none",
                    "alertText": "* Almeno un campo del gruppo deve essere compilato"
                },
                "min": {
                    "regex": "none",
                    "alertText": "* Valore minimo richiesto "
                },
                "max": {
                    "regex": "none",
                    "alertText": "* Valore massimo superato "
                },
                "minCheckbox": {
                    "regex": "none",
                    "alertText": "* Per favore selezionare almeno ",
                    "alertText2": " opzioni"
                },
                "equals": {
                    "regex": "none",
                    "alertText": "* I campi non corrispondono"
                },
                "creditCard": {
                    "regex": "none",
                    "alertText": "* Non valido numero di carta di credito"
                },
                "phone": {
                    // credit: jquery.h5validate.js / orefalo
                    "regex": /^([\+][0-9]{1,3}([ \.\-])?)?([\(][0-9]{1,6}[\)])?([0-9 \.\-]{1,32})(([A-Za-z \:]{1,11})?[0-9]{1,4}?)$/,
                    "alertText": "* Numero di telefono non corretto"
                },
                "email": {
                    // Shamelessly lifted from Scott Gonzalez via the Bassistance Validation plugin http://projects.scottsplayground.com/email_address_validation/
                    "regex": /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,
                    "alertText": "* Indirizzo non corretto"
                },
                "integer": {
                    "regex": /^[\-\+]?\d+$/,
                    "alertText": "* Numero intero non corretto"
                },
                "number": {
                    // Number, including positive, negative, and floating decimal. Credit: bassistance
                    "regex": /^[\-\+]?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)$/,
                    "alertText": "* Numero decimale non corretto"
                },
                "date": {
                    "regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/,
                    "alertText": "* Data non  corretta, re-inserire secondo formato AAAA-MM-GG"
                },
                "date_mm-yy": {
                    "regex": /^\d{2}\/\d{2}$/,
                    "alertText": "* Data non corretta, re-inserire secondo formato MM/GG"
                },
                "serial_number": {
                    "regex": /^[a-zA-Z]*[a-zA-Z0-9]*$/,
                    "alertText": "Ammesse le lettere solo all'inizio del campo"
                },
                "eu_vat": {
                    "regex": /(?xi)^((AT)?U[0-9]{8} | (BE)?0[0-9]{9} | (BG)?[0-9]{9,10} | (HR)?[0-9]{11} | (CY)?[0-9]{8}L | (CZ)?[0-9]{8,10} | (DE)?[0-9]{9} | (DK)?[0-9]{8} | (EE)?[0-9]{9} | (EL|GR)?[0-9]{9} | ES[A-Z][0-9]{7}(?:[0-9]|[A-Z]) | (FI)?[0-9]{8} | (FR)?[0-9A-Z]{2}[0-9]{9} | (GB)?([0-9]{9}([0-9]{3})?|[A-Z]{2}[0-9]{3}) | (HU)?[0-9]{8} | (IE)?[0-9]S[0-9]{5}L | (IT)?[0-9]{11} | (LT)?([0-9]{9}|[0-9]{12}) | (LU)?[0-9]{8} | (LV)?[0-9]{11} | (MT)?[0-9]{8} | (NL)?[0-9]{9}B[0-9]{2} | (PL)?[0-9]{10} | (PT)?[0-9]{9} | (RO)?[0-9]{2,10} | (SE)?[0-9]{12} | (SI)?[0-9]{8} | (SK)?[0-9]{10})$/,
                    "alertText": "Partita IVA Europea non corretta"
                },
                "ipv4": {
                  	"regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/,
                    "alertText": "* IP non corretto"
                },
                "url": {
                    "regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,
                    "alertText": "* URL non corretta"
                },
                "onlyNumber": {
                    "regex": /^[0-9\ ]+$/,
                    "alertText": "* Solo numeri"
                },
				        "onlyLetter": {
                    "regex": /^[a-zA-Z\ \']+$/,
                    "alertText": "* Solo lettere"
                },
                "validate2fields": {
                    "nname": "validate2fields",
                    "alertText": "* Occorre inserire nome e cognome"
                },
                "noSpecialCharacters": {
                    "regex": /^[0-9a-zA-Z]+$/,
                    "alertText": "* Caratteri speciali non permessi"
                },
                "ajaxUserCall": {
                    "file": "ajaxValidateFieldName",
                    "extraData": "name=eric",
                    "alertTextLoad": "* Caricamento, attendere per favore",
                    "alertText": "* Questo user � gi� stato utilizzato"
                },
                "ajaxNameCall": {
                    "file": "ajaxValidateFieldName",
                    "alertText": "* Questo nome � gi� stato utilizzato",
                    "alertTextOk": "* Questo nome � disponibile",
                    "alertTextLoad": "* Caricamento, attendere per favore"
                }

            };

        }
    };
    $.validationEngineLanguage.newLang();
})(jQuery);
<|endoftext|>


<commit_before>'use strict';

import init from './component/init';
import events from './component/events';
import classify from './component/classify';
import ripple from './component/ripple';
import emitter from './module/emitter';
import create from './element/create';
import css from './module/css';
import merge from './module/merge';
import insert from './element/insert';
import bind from './module/bind';
// modules
import control from './component/control';

const defaults = {
  prefix: 'material',
  class: 'button',
  tag: 'button',
  modules: [events, control, emitter, bind, ripple],
  build: [],
  bind: {
    'wrapper.click': 'click'
  }
};

/**
 * Button component
 * @class
 * @since 0.0.1
 * @example
 * var button = new Button({
 *   label: 'Button raised',
 *   type: 'raised',
 *   color: 'primary'
 * }).on('press', function(e) {
 *   console.log('button press', e);
 * }).insert(document.body);
 */
class Button {

  /**
   * The init method of the Button class
   * @param  {Object} options [description]
   * @private
   * @return {Object} The class instance
   */
  constructor(options) {
    this.options = merge(defaults, options);

    this.init();
    this.build();
    this.setup();
    this.bind(this.options.bind);

    this.emit('ready');

    return this;
  }

  /**
   * [init description]
   * @param  {?} options [description]
   * @return {?}         [description]
   */
  init() {
    init(this);
    this.emit('init');
  }

  /**
   * Build button's method
   * @override
   * @return {void}
   */
  build() {

    var tag = this.options.tag || 'div';
    this.wrapper = create(tag, this.options.prefix + '-' + this.options.class);

    classify(this.wrapper, this.options);

    this.options.label = this.options.label || this.options.text;

    this.label(this.options.label);
    this.icon(this.options.icon);

    if (this.options.type) {
      css.add(this.wrapper, 'type-' + this.options.type);
    }

    // insert if container options is given
    if (this.options.container) {
      insert(this.wrapper, this.options.container);
      this.emit('injected', this.wrapper);
    }

    this.emit('built', this.wrapper);

    return this;
  }

  insert(container, context) {
    insert(this.wrapper, container, context);

    return this;
  }

  setup() {
    this.element.input = this.wrapper;

    if (this.options.name) {
      //console.log('name', this.options.name);
      this.wrapper.dataset.name = this.options.name;
    }

    if (this.options.label) {
      this.wrapper.title = this.options.label;
    }

    if (this.options.style) {
      var styles = this.options.style.split(/\ /);
      for (var i = 0; i < styles.length; i++) {
        css.add(this.wrapper, 'style-' + styles[i]);
      }
    }

    if (this.options.content) {
      this.wrapper.innerHTML = this.options.content;
    }
  }

  /**
   * Setter
   * @param {string} prop
   * @param {string} value
   * @return {Object} The class instance
   */
  set(prop, value) {

    switch (prop) {
      case 'disabled':
        this.disable(value);
        break;
      case 'value':
        this.setValue(value);
        break;
      case 'label':
        this.setLabel(value);
        break;
      default:
        this.setValue(prop);
    }

    return this;
  }

  /**
   * [disable description]
   * @param  {?} boolean [description]
   * @return {?}         [description]
   */
  disable() {
    this.disabled = true;
    css.add(this.wrapper, 'is-disabled');

    return this;
  }

  /**
   * [disable description]
   * @param  {?} boolean [description]
   * @return {?}         [description]
   */
  enable() {
    this.disabled = false;
    css.remove(this.wrapper, 'is-disabled');

    return this;
  }

  /**
   * [_onElementMouseDown description]
   * @param  {event} e
   * @return {void}
   */
  press(e) {
    e.preventDefault();

    if (this.state === 'disabled') return;

    this.emit('press', e);

    return this;
  }

  /**
   * _onClick
   * @param  {Event} e The related event
   */
  click(e) {
    // e.preventDefault();
    // e.stopPropagation();

    if (this.disabled) return;
    if (this.options.upload) return;

    this.press(e);
  }
}

export default Button;<commit_msg>remove methods already moved in component/control<commit_after>'use strict';

import init from './component/init';
import events from './component/events';
import classify from './component/classify';
import ripple from './component/ripple';
import emitter from './module/emitter';
import create from './element/create';
import css from './module/css';
import merge from './module/merge';
import insert from './element/insert';
import bind from './module/bind';
// modules
import control from './component/control';

const defaults = {
  prefix: 'material',
  class: 'button',
  tag: 'button',
  modules: [events, control, emitter, bind, ripple],
  build: [],
  bind: {
    'wrapper.click': 'click'
  }
};

/**
 * Button component
 * @class
 * @since 0.0.1
 * @example
 * var button = new Button({
 *   label: 'Button raised',
 *   type: 'raised',
 *   color: 'primary'
 * }).on('press', function(e) {
 *   console.log('button press', e);
 * }).insert(document.body);
 */
class Button {

  /**
   * The init method of the Button class
   * @param  {Object} options [description]
   * @private
   * @return {Object} The class instance
   */
  constructor(options) {
    this.options = merge(defaults, options);

    this.init();
    this.build();
    this.setup();
    this.bind(this.options.bind);

    this.emit('ready');

    return this;
  }

  /**
   * [init description]
   * @param  {?} options [description]
   * @return {?}         [description]
   */
  init() {
    init(this);
    this.emit('init');
  }

  /**
   * Build button's method
   * @override
   * @return {void}
   */
  build() {

    var tag = this.options.tag || 'div';
    this.wrapper = create(tag, this.options.prefix + '-' + this.options.class);

    classify(this.wrapper, this.options);

    this.options.label = this.options.label || this.options.text;

    this.label(this.options.label);
    this.icon(this.options.icon);

    if (this.options.type) {
      css.add(this.wrapper, 'type-' + this.options.type);
    }

    // insert if container options is given
    if (this.options.container) {
      insert(this.wrapper, this.options.container);
      this.emit('injected', this.wrapper);
    }

    this.emit('built', this.wrapper);

    return this;
  }

  insert(container, context) {
    insert(this.wrapper, container, context);

    return this;
  }

  setup() {
    this.element.input = this.wrapper;

    if (this.options.name) {
      //console.log('name', this.options.name);
      this.wrapper.dataset.name = this.options.name;
    }

    if (this.options.label) {
      this.wrapper.title = this.options.label;
    }

    if (this.options.style) {
      var styles = this.options.style.split(/\ /);
      for (var i = 0; i < styles.length; i++) {
        css.add(this.wrapper, 'style-' + styles[i]);
      }
    }

    if (this.options.content) {
      this.wrapper.innerHTML = this.options.content;
    }
  }

  /**
   * Setter
   * @param {string} prop
   * @param {string} value
   * @return {Object} The class instance
   */
  set(prop, value) {

    switch (prop) {
      case 'disabled':
        this.disable(value);
        break;
      case 'value':
        this.setValue(value);
        break;
      case 'label':
        this.setLabel(value);
        break;
      default:
        this.setValue(prop);
    }

    return this;
  }

  /**
   * [_onElementMouseDown description]
   * @param  {event} e
   * @return {void}
   */
  press(e) {
    e.preventDefault();

    if (this.disabled === true) return;

    this.emit('press', e);

    return this;
  }

  /**
   * _onClick
   * @param  {Event} e The related event
   */
  click(e) {
    // e.preventDefault();
    // e.stopPropagation();

    if (this.disabled) return;
    if (this.options.upload) return;

    this.press(e);
  }
}

export default Button;<|endoftext|>


<commit_before>import React, {Component} from 'react';
import { withStyles } from 'material-ui/styles';
import axios from 'axios';
import moment from 'moment';
import { DatePicker } from 'material-ui-pickers';
import Drawer from 'material-ui/Drawer';
import Typography from 'material-ui/Typography';
import TextField from 'material-ui/TextField';
import InfiniteScroll from 'react-infinite-scroller';

import CustomProgress from '../CustomProgress/CustomProgress.js';
import EntryWidget from '../EntryWidget/EntryWidget.js';

axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = 'X-CSRFToken';

const styles = theme => ({
  root: {
    margin: '25px auto 50px',
    width: '100%',
    maxWidth: 720,
    backgroundColor: theme.palette.background.paper,
  },
  drawerPaper: {
    width: 240,
  },
  datePicker: {
    margin: '10px',
  },
  textField: {
    margin: '10px',
    display: 'flex',
  },
});

class HistoryView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      categories: [],
      qualityRatings: [],
      entries: [],
      moreEntriesUrl: null,
      entriesCount: null,
      queryParams: {
        date_start: moment(),
        date_end: moment(),
        category: "",
        quality_rating: "",
        entry: "",
      },
    };
    this.getCategoryName = this.getCategoryName.bind(this);
    this.loadMoreEntries = this.loadMoreEntries.bind(this);
    this.handleQueryChange = this.handleQueryChange.bind(this);
  }

  componentDidMount() {
    axios.get('/api/entries/')
      .then(
        (response) => {
          let oldestEntry = response.data.results[0];
          let qPs = {...this.state.queryParams};
          qPs.date_start = moment(oldestEntry.date);
          this.setState({
            entries: response.data.results,
            moreEntriesUrl: response.data.next,
            entriesCount: response.data.count,
            queryParams: qPs
          });
          return axios.get('/api/categories/')
        }
      )
      .then(
        (response) => {
          this.setState({
            categories: response.data
          });
          return axios.get('/api/quality-ratings/')
        }
      )
      .then(
        (response) => {
          this.setState({
            isLoaded: true, // Need for the widgets.
            qualityRatings: response.data
          });
        }
      )
      .catch(
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      );
  }

  //TODO deal with filters.
  loadMoreEntries() {
    axios.get(this.state.moreEntriesUrl)
      .then(
        (response) => {
          this.setState((prevState) => {
            return {
              entries: prevState.entries.concat(response.data.results),
              moreEntriesUrl: response.data.next,
            };
          });
        },
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      );
  }

  /*
   * For EntryWidget. We don't update category in PATCH, so we just need the
   * name, not the pk.
  */
  getCategoryName(pk) {
    let categoryObject = this.state.categories.find(category => category.pk === pk);
    return categoryObject.category
  }

/*
 * For axios calls when filtering. Pass the qPs object, not this.state,
 * b/c state will not have updated yet to match qPs.
*/
  composeQueryString(qPs) {
    let base = '/api/entries/';
    let queryString = '?';
    for (let k in qPs) {
      queryString += k + "=" + qPs[k] + "&";
    }
    queryString = queryString.slice(0, -1);
    let url = base + queryString;
    return url;
  }

/*
 *  Partially applied method for controlled component updating.
 */
  handleQueryChange(field) {
    return (e) => {
      let qPs = {...this.state.queryParams};
      qPs[field] = e.target ? e.target.value : e; // if its just e, it's a date.
      this.setState({
        queryParams: qPs
      });
      //TODO axios call.
    }
  }

  render() {
    const { error, isLoaded, entries, qualityRatings } = this.state;
    if (error) {
      return
Error: {error.message}
;
    } else if (!isLoaded) {
      return (

          <CustomProgress />

      );
    } else {
      let entryWidgets = entries.map(datum =>
        <EntryWidget
          key={datum.url}
          url={datum.url}
          date={datum.date}
          category={this.getCategoryName(datum.category)}
          rating={datum.quality_rating}
          entry={datum.entry}
          qualityRatings={qualityRatings}
          handleDelete={this.handleDelete}
          handleSave={this.handleUpdate}
        />
      );
      return (
        <React.Fragment>
          <Drawer
            variant='permanent'
            classes={{
              paper: this.props.classes.drawerPaper,
            }}
          >
            {'Hello'}
            <DatePicker
              className={this.props.classes.datePicker}
              value={this.state.queryParams.date_start}
              onChange={this.handleQueryChange("date_start")}
              disableFuture={true}
              keyboard
              label="Choose a start date"
            />
            <DatePicker
              className={this.props.classes.datePicker}
              value={this.state.queryParams.date_end}
              onChange={this.handleQueryChange("date_end")}
              disableFuture={true}
              keyboard
              label="Choose a end date"
            />
            <TextField
              id="select-category"
              select
              label="Category"
              className={this.props.classes.textField}
              value={this.state.queryParams.category}
              onChange={this.handleQueryChange("category")}
              SelectProps={{
                native: true,
              }}
              margin="normal"
            >
              <option key={"0"} value={""} />
              {this.state.categories.map(category => (
                <option key={category.pk} value={category.pk}>
                  {category.category}
                </option>
              ))}
            </TextField>
            <TextField
              id="select-rating"
              select
              label="Rating"
              className={this.props.classes.textField}
              value={this.state.queryParams.quality_rating}
              onChange={this.handleQueryChange("quality_rating")}
              SelectProps={{
                native: true,
              }}
              margin="normal"
            >
              <option key={"0"} value={""} />
              {this.state.qualityRatings.map(rating => (
                <option key={rating} value={rating}>
                  {rating}
                </option>
              ))}
            </TextField>
            <TextField
              id="filter-entries"
              label="Entry Text Contains"
              className={this.props.classes.textField}
              value={this.state.queryParams.entry}
              onChange={this.handleQueryChange("entry")}
              margin="normal"
              multiline
            >
            </TextField>
          </Drawer>

          <InfiniteScroll
            hasMore={this.state.moreEntriesUrl ? true : false}
            loader={<CustomProgress />}
            initialLoad={false}
            loadMore={this.loadMoreEntries}
          >

              {entryWidgets}

          </InfiniteScroll>
        </React.Fragment>
      )
    }
  }

}

export default withStyles(styles)(HistoryView);
<commit_msg>filter by date, cat, rating enabled<commit_after>import React, {Component} from 'react';
import { withStyles } from 'material-ui/styles';
import axios from 'axios';
import moment from 'moment';
import { DatePicker } from 'material-ui-pickers';
import Drawer from 'material-ui/Drawer';
import Typography from 'material-ui/Typography';
import TextField from 'material-ui/TextField';
import InfiniteScroll from 'react-infinite-scroller';

import CustomProgress from '../CustomProgress/CustomProgress.js';
import EntryWidget from '../EntryWidget/EntryWidget.js';

axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = 'X-CSRFToken';

const styles = theme => ({
  root: {
    margin: '25px auto 50px',
    width: '100%',
    maxWidth: 720,
    backgroundColor: theme.palette.background.paper,
  },
  drawerPaper: {
    width: 240,
  },
  datePicker: {
    margin: '10px',
  },
  textField: {
    margin: '10px',
    display: 'flex',
  },
});

class HistoryView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      categories: [],
      qualityRatings: [],
      entries: [],
      moreEntriesUrl: null,
      entriesCount: null,
      queryParams: {
        date_start: moment(),
        date_end: moment(),
        category: "",
        quality_rating: "",
        entry: "",
      },
    };
    this.getCategoryName = this.getCategoryName.bind(this);
    this.loadMoreEntries = this.loadMoreEntries.bind(this);
    this.handleQueryChange = this.handleQueryChange.bind(this);
    this.composeFilterUrl = this.composeFilterUrl.bind(this);
    this.getCategoryName = this.getCategoryName.bind(this); // don't think necessary
    this.getFilteredEntries = this.getFilteredEntries.bind(this);
  }

  componentDidMount() {
    axios.get('/api/entries/')
      .then(
        (response) => {
          let oldestEntry = response.data.results[0];
          let qPs = {...this.state.queryParams};
          qPs.date_start = moment(oldestEntry.date);
          this.setState({
            entries: response.data.results,
            moreEntriesUrl: response.data.next,
            entriesCount: response.data.count,
            queryParams: qPs
          });
          return axios.get('/api/categories/')
        }
      )
      .then(
        (response) => {
          this.setState({
            categories: response.data
          });
          return axios.get('/api/quality-ratings/')
        }
      )
      .then(
        (response) => {
          this.setState({
            isLoaded: true, // Need for the widgets.
            qualityRatings: response.data
          });
        }
      )
      .catch(
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      );
  }

  //TODO deal with filters.
  loadMoreEntries() {
    axios.get(this.state.moreEntriesUrl)
      .then(
        (response) => {
          this.setState((prevState) => {
            return {
              entries: prevState.entries.concat(response.data.results),
              moreEntriesUrl: response.data.next,
            };
          });
        },
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      );
  }

  /*
   * For EntryWidget. We don't update category in PATCH, so we just need the
   * name, not the pk.
  */
  getCategoryName(pk) {
    let categoryObject = this.state.categories.find(category => category.pk === pk);
    return categoryObject.category
  }

/*
 * For axios calls when filtering. Pass the qPs object, not this.state,
 * b/c state will not have updated yet to match qPs.
*/
  composeFilterUrl(qPs) {
    let dateKeys = ['date_start', 'date_end'];

    let base = '/api/entries/';
    let queryString = '?';
    for (let k in qPs) {
      if (dateKeys.includes(k)) {
        qPs[k] = qPs[k].format('YYYY-MM-DD');
      }
      queryString += k + "=" + qPs[k] + "&";
    }
    queryString = queryString.slice(0, -1);
    let url = base + queryString;
    return url;
  }

  getFilteredEntries(url) {
    axios.get(url)
      .then(
        (response) => {
          this.setState({
            entries: response.data.results,
            moreEntriesUrl: response.data.next,
            entriesCount: response.data.count,
          });
        },
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      );
  }

/*
 *  Partially applied method for controlled component updating.
 */
  handleQueryChange(field) {
    return (e) => {
      let qPs = {...this.state.queryParams};
      qPs[field] = e.target ? e.target.value : e; // if its just e, it's a date.
      this.setState({
        queryParams: qPs
      });

      if (field === 'entry') {
        return
      } else {
        let filterUrl = this.composeFilterUrl(qPs);
        this.getFilteredEntries(filterUrl);
      }
    }
  }

  render() {
    const { error, isLoaded, entries, qualityRatings } = this.state;
    if (error) {
      return
Error: {error.message}
;
    } else if (!isLoaded) {
      return (

          <CustomProgress />

      );
    } else {
      let entryWidgets = entries.map(datum =>
        <EntryWidget
          key={datum.url}
          url={datum.url}
          date={datum.date}
          category={this.getCategoryName(datum.category)}
          rating={datum.quality_rating}
          entry={datum.entry}
          qualityRatings={qualityRatings}
          handleDelete={this.handleDelete}
          handleSave={this.handleUpdate}
        />
      );
      return (
        <React.Fragment>
          <Drawer
            variant='permanent'
            classes={{
              paper: this.props.classes.drawerPaper,
            }}
          >
            {'Hello'}
            <DatePicker
              className={this.props.classes.datePicker}
              value={this.state.queryParams.date_start}
              onChange={this.handleQueryChange("date_start")}
              disableFuture={true}
              keyboard
              label="Choose a start date"
            />
            <DatePicker
              className={this.props.classes.datePicker}
              value={this.state.queryParams.date_end}
              onChange={this.handleQueryChange("date_end")}
              disableFuture={true}
              keyboard
              label="Choose a end date"
            />
            <TextField
              id="select-category"
              select
              label="Category"
              className={this.props.classes.textField}
              value={this.state.queryParams.category}
              onChange={this.handleQueryChange("category")}
              SelectProps={{
                native: true,
              }}
              margin="normal"
            >
              <option key={"0"} value={""} />
              {this.state.categories.map(category => (
                <option key={category.pk} value={category.pk}>
                  {category.category}
                </option>
              ))}
            </TextField>
            <TextField
              id="select-rating"
              select
              label="Rating"
              className={this.props.classes.textField}
              value={this.state.queryParams.quality_rating}
              onChange={this.handleQueryChange("quality_rating")}
              SelectProps={{
                native: true,
              }}
              margin="normal"
            >
              <option key={"0"} value={""} />
              {this.state.qualityRatings.map(rating => (
                <option key={rating} value={rating}>
                  {rating}
                </option>
              ))}
            </TextField>
            <TextField
              id="filter-entries"
              label="Entry Text Contains"
              className={this.props.classes.textField}
              value={this.state.queryParams.entry}
              onChange={this.handleQueryChange("entry")}
              margin="normal"
              multiline
            >
            </TextField>
          </Drawer>

          <InfiniteScroll
            hasMore={this.state.moreEntriesUrl ? true : false}
            loader={<CustomProgress />}
            initialLoad={false}
            loadMore={this.loadMoreEntries}
          >

              {entryWidgets}

          </InfiniteScroll>
        </React.Fragment>
      )
    }
  }

}

export default withStyles(styles)(HistoryView);
<|endoftext|>


<commit_before><commit_msg>- Prepare for Qt5 where function names have changed.<commit_after><|endoftext|>


<commit_before>
global.cache_g = 0

// For Node.js
var _require = typeof require === 'function' ? require : { cache: {} }

define(function(require) {

  var test = require('../../../test')

  var a = require('./a')
  test.assert(a.name === 'a', a.name)
  test.assert(cache_g === 1, 'cache_g = ' + cache_g)

  var cache = find('module/cache/a.js')
  test.assert(cache.length === 1, 'cache.length = ' + cache.length)

  var m = cache[0]
  test.assert(m === require.resolve('./a'), m)

  var url = require.resolve('./a')
  test.assert(url.indexOf('a.js') > 0, url)

  // Delete './a' from cache
  seajs.cache[url].destroy()

  if (_require) {
    url = url.replace(/\\/g, '/')
  }
  delete _require.cache[url]

  // Load './a' again
  require.async('./a', function(a) {
    test.assert(cache_g === 2, 'cache_g = ' + cache_g)
    test.assert(a.name === 'a', a.name)

    // Load from cache
    require.async('./a', function(a) {
      test.assert(cache_g === 2, 'cache_g = ' + cache_g)
      test.assert(a.name === 'a', a.name)

      test.next()
    })
  })

  function find(filename) {
    var cache = seajs.cache
    var ret = []

    for (var uri in cache) {
      if (uri.indexOf(filename) > 0) {
        ret.push(uri)
      }
    }

    return ret
  }

});

<commit_msg>Fix a bug in Node.js/WinOS<commit_after>
global.cache_g = 0

// For Node.js
var _require = typeof require === 'function' ? require : { cache: {} }

define(function(require) {

  var test = require('../../../test')

  var a = require('./a')
  test.assert(a.name === 'a', a.name)
  test.assert(cache_g === 1, 'cache_g = ' + cache_g)

  var cache = find('module/cache/a.js')
  test.assert(cache.length === 1, 'cache.length = ' + cache.length)

  var m = cache[0]
  test.assert(m === require.resolve('./a'), m)

  var url = require.resolve('./a')
  test.assert(url.indexOf('a.js') > 0, url)

  // Delete './a' from cache
  seajs.cache[url].destroy()

  if (_require && typeof process !== 'undefined' &&
      process.cwd().indexOf('node.exe') > 0) {
    url = url.replace(/\//g, '\\')
  }
  delete _require.cache[url]

  // Load './a' again
  require.async('./a', function(a) {
    test.assert(cache_g === 2, 'cache_g = ' + cache_g)
    test.assert(a.name === 'a', a.name)

    // Load from cache
    require.async('./a', function(a) {
      test.assert(cache_g === 2, 'cache_g = ' + cache_g)
      test.assert(a.name === 'a', a.name)

      test.next()
    })
  })

  function find(filename) {
    var cache = seajs.cache
    var ret = []

    for (var uri in cache) {
      if (uri.indexOf(filename) > 0) {
        ret.push(uri)
      }
    }

    return ret
  }

});

<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

/**
 * Company Schema
 */
var CompanySchema = new Schema({
  name: {
    type: String,
    default: '',
    required: 'Please fill Company name',
    trim: true
  },
  profileImageURL: {
    type: String,
    default: ''
  },
  description: {
    type: String,
    default: '',
  },
  weOffer: [{
    type: String,
  }],
  desiredProgramme: [{ type: String }],
  branch: [{ type: String }],
  whyStudentSession: {
    type: String,
    default: ''
  },
  didYouKnow: {
    type: String,
    default: ''
  },
  website: {
    type: String,
    default: ''
  },
  language: {
    type: String,
  },
  chosenStudents: [{
    type: Schema.ObjectId,
    ref: 'Application'
  }],
  active: {
    type: Boolean,
    default: false
  },
  created: {
    type: Date,
    default: Date.now
  },
  user: {
    type: Schema.ObjectId,
    ref: 'User'
  }
});

mongoose.model('Company', CompanySchema);
<commit_msg>add wed and thur to company-model<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

/**
 * Company Schema
 */
var CompanySchema = new Schema({
  name: {
    type: String,
    default: '',
    required: 'Please fill Company name',
    trim: true
  },
  profileImageURL: {
    type: String,
    default: ''
  },
  description: {
    type: String,
    default: '',
  },
  weOffer: [{
    type: String,
  }],
  desiredProgramme: [{ type: String }],
  branch: [{ type: String }],
  whyStudentSession: {
    type: String,
    default: ''
  },
  didYouKnow: {
    type: String,
    default: ''
  },
  website: {
    type: String,
    default: ''
  },
  language: {
    type: String,
  },
  wednesday: {
    type: Boolean,
    default: false
  },
  thursday: {
    type: Boolean,
    default: false
  },
  chosenStudents: [{
    type: Schema.ObjectId,
    ref: 'Application'
  }],
  active: {
    type: Boolean,
    default: false
  },
  created: {
    type: Date,
    default: Date.now
  },
  user: {
    type: Schema.ObjectId,
    ref: 'User'
  }
});

mongoose.model('Company', CompanySchema);
<|endoftext|>


<commit_before>/**
 * @file GroupList component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import List from '../List';
import Theme from '../Theme';
import Tip from '../Tip';

import SelectMode from '../_statics/SelectMode';
import LIST_SEPARATOR from '../_statics/ListSeparator';

import Util from '../_vendors/Util';
import Event from '../_vendors/Event';
import Calculation from '../_vendors/Calculation';

class GroupList extends Component {

    static SelectMode = SelectMode;
    static LIST_SEPARATOR = LIST_SEPARATOR;
    static Theme = Theme;

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            value: Calculation.getInitValue(props)
        };

    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.value !== this.state.value) {
            this.setState({
                value: Calculation.getInitValue(nextProps)
            });
        }
    }

    render() {

        const {children, className, style, data, disabled, ...restProps} = this.props,
            {value} = this.state,

            listClassName = classNames('group-list', {
                [className]: className
            });

        return (

 Event.wheelHandler(e, this.props)}>

                {
                    data && data.map((item, index) => item === LIST_SEPARATOR ?

                        :

{item.name}

                            <List {...restProps}
                                  data={item.children}
                                  value={value}/>

                    )
                }

                {children}

        );

    }
}

GroupList.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The theme.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The theme of the list item select radio or checkbox.
     */
    selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * Children passed into the ListItem.
     */
    data: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({

        // group name
        name: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

        children: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({

            /**
             * The CSS class name of the list button.
             */
            className: PropTypes.string,

            /**
             * Override the styles of the list button.
             */
            style: PropTypes.object,

            /**
             * The theme of the list button.
             */
            theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

            /**
             * The text value of the list button.Type can be string or number.
             */
            value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

            /**
             * The list item's display text. Type can be string, number or bool.
             */
            text: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

            /**
             * The desc value of the list button. Type can be string or number.
             */
            desc: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

            /**
             * If true,the list item will be disabled.
             */
            disabled: PropTypes.bool,

            /**
             * If true,the button will be have loading effect.
             */
            isLoading: PropTypes.bool,

            /**
             * If true,the element's ripple effect will be disabled.
             */
            disableTouchRipple: PropTypes.bool,

            /**
             * Use this property to display an icon. It will display on the left.
             */
            iconCls: PropTypes.string,

            /**
             * Use this property to display an icon. It will display on the right.
             */
            rightIconCls: PropTypes.string,

            /**
             * The message of tip.
             */
            tip: PropTypes.string,

            /**
             * The position of tip.
             */
            tipPosition: PropTypes.oneOf(Util.enumerateValue(Tip.Position)),

            /**
             * If true,the item will have center displayed ripple effect.
             */
            rippleDisplayCenter: PropTypes.bool,

            /**
             * You can create a complicated renderer callback instead of value and desc prop.
             */
            itemRenderer: PropTypes.func,

            /**
             * Callback function fired when a list item touch-tapped.
             */
            onClick: PropTypes.func

        }), PropTypes.string, PropTypes.number]))

    }), PropTypes.symbol])).isRequired,

    /**
     * The id field name in data. (default: "id")
     */
    idField: PropTypes.string,

    /**
     * The value field name in data. (default: "value")
     */
    valueField: PropTypes.string,

    /**
     * The display field name in data. (default: "text")
     */
    displayField: PropTypes.string,

    /**
     * The description field name in data. (default: "desc")
     */
    descriptionField: PropTypes.string,

    /**
     * If true, the list will be disabled.
     */
    disabled: PropTypes.bool,

    /**
     * If true, the list will be at loading status.
     */
    isLoading: PropTypes.bool,

    /**
     * The mode of listItem.Can be normal,checkbox.
     */
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

    radioUncheckedIconCls: PropTypes.string,
    radioCheckedIconCls: PropTypes.string,
    checkboxUncheckedIconCls: PropTypes.string,
    checkboxCheckedIconCls: PropTypes.string,
    checkboxIndeterminateIconCls: PropTypes.string,

    /**
     * You can create a complicated renderer callback instead of value and desc prop.
     */
    renderer: PropTypes.func,

    /**
     * Callback function fired when the list-item select.
     */
    onItemClick: PropTypes.func,

    /**
     * Callback function fired when the list changed.
     */
    onChange: PropTypes.func,

    /**
     * Callback function fired when wrapper wheeled.
     */
    onWheel: PropTypes.func

};

GroupList.defaultProps = {

    theme: Theme.DEFAULT,
    selectTheme: Theme.DEFAULT,

    data: [],

    idField: 'id',
    valueField: 'value',
    displayField: 'text',
    descriptionField: 'desc',
    disabled: false,
    selectMode: SelectMode.SINGLE_SELECT,

    radioUncheckedIconCls: 'fas fa-check',
    radioCheckedIconCls: 'fas fa-check',
    checkboxUncheckedIconCls: 'far fa-square',
    checkboxCheckedIconCls: 'fas fa-check-square',
    checkboxIndeterminateIconCls: 'fas fa-minus-square'

};

export default GroupList;
<commit_msg>update GroupList<commit_after>/**
 * @file GroupList component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import List from '../List';
import Theme from '../Theme';
import Tip from '../Tip';

import SelectMode from '../_statics/SelectMode';
import LIST_SEPARATOR from '../_statics/ListSeparator';

import Util from '../_vendors/Util';
import Calculation from '../_vendors/Calculation';

class GroupList extends Component {

    static SelectMode = SelectMode;
    static LIST_SEPARATOR = LIST_SEPARATOR;
    static Theme = Theme;

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            value: Calculation.getInitValue(props)
        };

    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.value !== this.state.value) {
            this.setState({
                value: Calculation.getInitValue(nextProps)
            });
        }
    }

    render() {

        const {children, className, style, data, disabled, ...restProps} = this.props,
            {value} = this.state,

            listClassName = classNames('group-list', {
                [className]: className
            });

        return (

                {
                    data && data.map((item, index) => item === LIST_SEPARATOR ?

                        :

{item.name}

                            <List {...restProps}
                                  data={item.children}
                                  value={value}/>

                    )
                }

                {children}

        );

    }
}

GroupList.propTypes = {

    children: PropTypes.any,

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The theme.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The theme of the list item select radio or checkbox.
     */
    selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * Children passed into the ListItem.
     */
    data: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({

        // group name
        name: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

        children: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({

            /**
             * The CSS class name of the list button.
             */
            className: PropTypes.string,

            /**
             * Override the styles of the list button.
             */
            style: PropTypes.object,

            /**
             * The theme of the list button.
             */
            theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

            /**
             * The text value of the list button.Type can be string or number.
             */
            value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

            /**
             * The list item's display text. Type can be string, number or bool.
             */
            text: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

            /**
             * The desc value of the list button. Type can be string or number.
             */
            desc: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

            /**
             * If true,the list item will be disabled.
             */
            disabled: PropTypes.bool,

            /**
             * If true,the button will be have loading effect.
             */
            isLoading: PropTypes.bool,

            /**
             * If true,the element's ripple effect will be disabled.
             */
            disableTouchRipple: PropTypes.bool,

            /**
             * Use this property to display an icon. It will display on the left.
             */
            iconCls: PropTypes.string,

            /**
             * Use this property to display an icon. It will display on the right.
             */
            rightIconCls: PropTypes.string,

            /**
             * The message of tip.
             */
            tip: PropTypes.string,

            /**
             * The position of tip.
             */
            tipPosition: PropTypes.oneOf(Util.enumerateValue(Tip.Position)),

            /**
             * If true,the item will have center displayed ripple effect.
             */
            rippleDisplayCenter: PropTypes.bool,

            /**
             * You can create a complicated renderer callback instead of value and desc prop.
             */
            itemRenderer: PropTypes.func,

            /**
             * Callback function fired when a list item touch-tapped.
             */
            onClick: PropTypes.func

        }), PropTypes.string, PropTypes.number]))

    }), PropTypes.symbol])).isRequired,

    /**
     * The id field name in data. (default: "id")
     */
    idField: PropTypes.string,

    /**
     * The value field name in data. (default: "value")
     */
    valueField: PropTypes.string,

    /**
     * The display field name in data. (default: "text")
     */
    displayField: PropTypes.string,

    /**
     * The description field name in data. (default: "desc")
     */
    descriptionField: PropTypes.string,

    /**
     * If true, the list will be disabled.
     */
    disabled: PropTypes.bool,

    /**
     * If true, the list will be at loading status.
     */
    isLoading: PropTypes.bool,

    /**
     * The mode of listItem.Can be normal,checkbox.
     */
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

    radioUncheckedIconCls: PropTypes.string,
    radioCheckedIconCls: PropTypes.string,
    checkboxUncheckedIconCls: PropTypes.string,
    checkboxCheckedIconCls: PropTypes.string,
    checkboxIndeterminateIconCls: PropTypes.string,

    /**
     * You can create a complicated renderer callback instead of value and desc prop.
     */
    renderer: PropTypes.func,

    /**
     * Callback function fired when the list-item select.
     */
    onItemClick: PropTypes.func,

    /**
     * Callback function fired when the list changed.
     */
    onChange: PropTypes.func

};

GroupList.defaultProps = {

    theme: Theme.DEFAULT,
    selectTheme: Theme.DEFAULT,

    data: [],

    idField: 'id',
    valueField: 'value',
    displayField: 'text',
    descriptionField: 'desc',
    disabled: false,
    selectMode: SelectMode.SINGLE_SELECT,

    radioUncheckedIconCls: 'fas fa-check',
    radioCheckedIconCls: 'fas fa-check',
    checkboxUncheckedIconCls: 'far fa-square',
    checkboxCheckedIconCls: 'fas fa-check-square',
    checkboxIndeterminateIconCls: 'fas fa-minus-square'

};

export default GroupList;
<|endoftext|>


<commit_before>/*
 * RailsAdmin remote form @VERSION
 *
 * License
 *
 * http://www.railsadmin.org
 *
 * Depends:
 *   jquery.ui.core.js
 *   jquery.ui.widget.js
 *   jquery.ui.dialog.js
 */
(function($) {
  $.widget("ra.remoteForm", {

    _create: function() {
      var widget = this
      var dom_widget = widget.element;

      var edit_url = dom_widget.find('select').data('edit-url');
      if(typeof(edit_url) != 'undefined' && edit_url.length) {
        dom_widget.find('.ra-multiselect option').live('dblclick', function(e){
          widget._bindModalOpening(e, edit_url.replace('__ID__', this.value))
        });
      }

      dom_widget.find('.create').unbind().bind("click", function(e){
        widget._bindModalOpening(e, $(this).data('link'))
      });

      dom_widget.find('.update').unbind().bind("click", function(e){
        if(value = dom_widget.find('select').val()) {
          widget._bindModalOpening(e, $(this).data('link').replace('__ID__', value))
        } else {
          e.preventDefault();
        }
      });
    },

    _bindModalOpening: function(e, url) {
      e.preventDefault();
      widget = this;
      if($("#modal").length)
        return false;

      var dialog = this._getModal();
      $.ajax({
        url: url,
        beforeSend: function(xhr) {
          xhr.setRequestHeader("Accept", "text/javascript");
        },
        success: function(data, status, xhr) {
          dialog.find('.modal-body').html(data);
          widget._bindFormEvents();
        },
        error: function(xhr, status, error) {
          dialog.find('.modal-body').html(xhr.responseText);
        },
        dataType: 'text'
      });
    },

    _bindFormEvents: function() {
      var widget = this,
          dialog = this._getModal(),
          form = dialog.find("form"),
          saveButtonText = dialog.find(":submit[name=_save]").text(),
          cancelButtonText = dialog.find(":submit[name=_continue]").text();
      dialog.find('.actions').remove();

      form.attr("data-remote", true);
      dialog.find('.modal-header-title').text(form.data('title'));
      dialog.find('.cancel-action').unbind().click(function(){
        dialog.modal('hide');
        return false;
      }).text(cancelButtonText);

      dialog.find('.save-action').unbind().click(function(){
        form.submit();
        return false;
      }).text(saveButtonText);

      form.bind("ajax:complete", function(xhr, data, status) {
        if (status == 'error') {
          dialog.find('.modal-body').html(data.responseText);
          widget._bindFormEvents();

        } else {

          var json = $.parseJSON(data.responseText);
          var option = '<option value="' + json.id + '" selected>' + json.label + '</option>';
          var select = widget.element.find('select').filter(":hidden");

          if(widget.element.find('.filtering-select').length) { // select input
            var input = widget.element.find('.filtering-select').children('.ra-filtering-select-input');
            input.val(json.label);
            if (!select.find('option[value=' + json.id + ']').length) // replace
              select.html(option).val(json.id);

          } else { // multi-select input

            var input = widget.element.find('.ra-filtering-select-input');
            var multiselect = widget.element.find('.ra-multiselect');
            if (multiselect.find('option[value=' + json.id + ']').length) { // replace
              select.find('option[value=' + json.id + ']').text(json.label);
              multiselect.find('option[value= ' + json.id + ']').text(json.label);
            } else { // add
              select.prepend(option);
              multiselect.find('select.ra-multiselect-selection').prepend(option);
            }
          }
          dialog.modal("hide");
        }
      });
    },

    _getModal: function() {
      var widget = this;
      if (!widget.dialog) {
        widget.dialog = $('\

\

\
              ×\

...
\

\

\
              ...\

\

\
              ...\
              ...\

\

')
          .modal({
            keyboard: true,
            backdrop: true,
            show: true
          })
          .bind('hidden', function(){
            widget.dialog.remove();   // We don't want to reuse closed modals
            widget.dialog = null;
          });
        }
      return this.dialog;
    }
  });
})(jQuery);
<commit_msg>Added success trigger to remoteForm<commit_after>/*
 * RailsAdmin remote form @VERSION
 *
 * License
 *
 * http://www.railsadmin.org
 *
 * Depends:
 *   jquery.ui.core.js
 *   jquery.ui.widget.js
 *   jquery.ui.dialog.js
 */
(function($) {
  $.widget("ra.remoteForm", {

    _create: function() {
      var widget = this
      var dom_widget = widget.element;

      var edit_url = dom_widget.find('select').data('edit-url');
      if(typeof(edit_url) != 'undefined' && edit_url.length) {
        dom_widget.find('.ra-multiselect option').live('dblclick', function(e){
          widget._bindModalOpening(e, edit_url.replace('__ID__', this.value))
        });
      }

      dom_widget.find('.create').unbind().bind("click", function(e){
        widget._bindModalOpening(e, $(this).data('link'))
      });

      dom_widget.find('.update').unbind().bind("click", function(e){
        if(value = dom_widget.find('select').val()) {
          widget._bindModalOpening(e, $(this).data('link').replace('__ID__', value))
        } else {
          e.preventDefault();
        }
      });
    },

    _bindModalOpening: function(e, url) {
      e.preventDefault();
      widget = this;
      if($("#modal").length)
        return false;

      var dialog = this._getModal();
      $.ajax({
        url: url,
        beforeSend: function(xhr) {
          xhr.setRequestHeader("Accept", "text/javascript");
        },
        success: function(data, status, xhr) {
          dialog.find('.modal-body').html(data);
          widget._bindFormEvents();
        },
        error: function(xhr, status, error) {
          dialog.find('.modal-body').html(xhr.responseText);
        },
        dataType: 'text'
      });
    },

    _bindFormEvents: function() {
      var widget = this,
          dialog = this._getModal(),
          form = dialog.find("form"),
          saveButtonText = dialog.find(":submit[name=_save]").text(),
          cancelButtonText = dialog.find(":submit[name=_continue]").text();
      dialog.find('.actions').remove();

      form.attr("data-remote", true);
      dialog.find('.modal-header-title').text(form.data('title'));
      dialog.find('.cancel-action').unbind().click(function(){
        dialog.modal('hide');
        return false;
      }).text(cancelButtonText);

      dialog.find('.save-action').unbind().click(function(){
        form.submit();
        return false;
      }).text(saveButtonText);

      form.bind("ajax:complete", function(xhr, data, status) {
        if (status == 'error') {
          dialog.find('.modal-body').html(data.responseText);
          widget._bindFormEvents();

        } else {

          var json = $.parseJSON(data.responseText);
          var option = '<option value="' + json.id + '" selected>' + json.label + '</option>';
          var select = widget.element.find('select').filter(":hidden");

          if(widget.element.find('.filtering-select').length) { // select input
            var input = widget.element.find('.filtering-select').children('.ra-filtering-select-input');
            input.val(json.label);
            if (!select.find('option[value=' + json.id + ']').length) // replace
              select.html(option).val(json.id);

          } else { // multi-select input

            var input = widget.element.find('.ra-filtering-select-input');
            var multiselect = widget.element.find('.ra-multiselect');
            if (multiselect.find('option[value=' + json.id + ']').length) { // replace
              select.find('option[value=' + json.id + ']').text(json.label);
              multiselect.find('option[value= ' + json.id + ']').text(json.label);
            } else { // add
              select.prepend(option);
              multiselect.find('select.ra-multiselect-selection').prepend(option);
            }
          }
          widget._trigger("success");
          dialog.modal("hide");
        }
      });
    },

    _getModal: function() {
      var widget = this;
      if (!widget.dialog) {
        widget.dialog = $('\

\

\
              ×\

...
\

\

\
              ...\

\

\
              ...\
              ...\

\

')
          .modal({
            keyboard: true,
            backdrop: true,
            show: true
          })
          .bind('hidden', function(){
            widget.dialog.remove();   // We don't want to reuse closed modals
            widget.dialog = null;
          });
        }
      return this.dialog;
    }
  });
})(jQuery);
<|endoftext|>


<commit_before>import audioContext from 'audioContext';
import { circle } from 'consts';
import { beatValue, lineAngles, treeAngles, treeOutlineAngles } from 'store';
import svgImage from 'svgImage';

const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');

const ratio = 16 / 9;
let width;
let height;
let resized = true;

function coords(x, y) {
  return [width * x, height * y];
}

function coordX(x) {
  return width * x;
}

function coordY(y) {
  return height * y;
}

function setSizeFromWindow() {
  width = window.innerWidth;
  height = window.innerHeight;
  width = Math.min(width, Math.floor(innerHeight * ratio));
  height = Math.min(height, Math.floor(width / ratio));
  canvas.width = width;
  canvas.height = height;
}

const strokeStyle = `
  stroke-linejoin="round"
  stroke-width="2"
`;

const treeOutline = svgImage(`
  <svg xmlns="http://www.w3.org/2000/svg" width="40" height="50" viewBox="0 0 40 50">
    <path
      d="M15.5 44v5h10v-5m-5-43L39 44H1z"
      fill="none"
      stroke="rgba(0, 0, 0, 0.3)"
      stroke-dasharray="4 1.5"
      ${strokeStyle}
    />
  </svg>
`);

const tree = svgImage(`
  <svg xmlns="http://www.w3.org/2000/svg" width="40" height="50" viewBox="0 0 40 50">
    <path d="M15.5 44v5h10v-5" fill="#ba8659" stroke="#ba8659" ${strokeStyle} />
    <path d="M20.5 1L39 44H1z" fill="#64a154" stroke="#64a154" ${strokeStyle} />
  </svg>
`);

const midX = 0.2;
const midY = 10;
const baseRadius = 9.2;

function sizeMultiplier() {
  return coordY(baseRadius) / 4000;
}

function drawTree(image, radius, angle, size = 1) {
  const multiplier = sizeMultiplier() * size;
  const width = image.width * multiplier;
  const height = image.height * multiplier;
  const sin = Math.sin(angle);
  const cos = Math.cos(angle);
  context.setTransform(cos, sin, -sin, cos, ...coords(midX, midY));
  context.drawImage(image, -width / 2, -radius - height, width, height);
}

function treeCleanup() {
  context.setTransform(1, 0, 0, 1, 0, 0);
}

function lineSetup() {
  context.strokeStyle = 'rgba(0, 0, 0, 0.3)';
  context.lineWidth = sizeMultiplier() * 2;
  context.setLineDash([sizeMultiplier() * 4, sizeMultiplier() * 1.5]);
}

function drawLine(radius, angle) {
  const sin = Math.sin(angle);
  const cos = Math.cos(angle);
  context.beginPath();
  context.setTransform(cos, sin, -sin, cos, ...coords(midX, midY));
  context.moveTo(0, -radius -coordY(1));
  context.lineTo(0, coordY(0));
  context.stroke();
}

function lineCleanup() {
  context.setTransform(1, 0, 0, 1, 0, 0);
  context.setLineDash([]);
}

function draw(now) {
  requestAnimationFrame(draw);
  if (resized) {
    resized = false;
    setSizeFromWindow();
  }

  const offset = now / 20000;
  const radius = coordY(baseRadius + beatValue() / 500 * baseRadius);

  context.fillStyle = '#BBF3FC';
  context.fillRect(0, 0, ...coords(1, 1));

  context.beginPath();
  context.fillStyle = 'rgba(232, 228, 109, 0.6)';
  context.moveTo(...coords(midX, midY));
  context.lineTo(coordX(midX - 0.03), 0);
  context.lineTo(coordX(midX + 0.03), 0);
  context.fill();

  context.beginPath();
  context.fillStyle = '#8BE075';
  context.arc(...coords(midX, midY), radius, 0, circle);
  context.fill();

  for (const [treeOutlineAngle, size] of treeOutlineAngles()) {
    drawTree(treeOutline, radius, treeOutlineAngle, size);
  }
  for (const treeAngle of treeAngles()) {
    drawTree(tree, radius, treeAngle);
  }
  treeCleanup();

  lineSetup();
  for (const lineAngle of lineAngles()) {
    drawLine(radius, lineAngle);
  }
  lineCleanup();
}

window.onresize = () => {
  resized = true;
};

requestAnimationFrame(draw);
<commit_msg>Draw lines before the outlines and the trees<commit_after>import audioContext from 'audioContext';
import { circle } from 'consts';
import { beatValue, lineAngles, treeAngles, treeOutlineAngles } from 'store';
import svgImage from 'svgImage';

const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');

const ratio = 16 / 9;
let width;
let height;
let resized = true;

function coords(x, y) {
  return [width * x, height * y];
}

function coordX(x) {
  return width * x;
}

function coordY(y) {
  return height * y;
}

function setSizeFromWindow() {
  width = window.innerWidth;
  height = window.innerHeight;
  width = Math.min(width, Math.floor(innerHeight * ratio));
  height = Math.min(height, Math.floor(width / ratio));
  canvas.width = width;
  canvas.height = height;
}

const strokeStyle = `
  stroke-linejoin="round"
  stroke-width="2"
`;

const treeOutline = svgImage(`
  <svg xmlns="http://www.w3.org/2000/svg" width="40" height="50" viewBox="0 0 40 50">
    <path
      d="M15.5 44v5h10v-5m-5-43L39 44H1z"
      fill="none"
      stroke="rgba(0, 0, 0, 0.3)"
      stroke-dasharray="4 1.5"
      ${strokeStyle}
    />
  </svg>
`);

const tree = svgImage(`
  <svg xmlns="http://www.w3.org/2000/svg" width="40" height="50" viewBox="0 0 40 50">
    <path d="M15.5 44v5h10v-5" fill="#ba8659" stroke="#ba8659" ${strokeStyle} />
    <path d="M20.5 1L39 44H1z" fill="#64a154" stroke="#64a154" ${strokeStyle} />
  </svg>
`);

const midX = 0.2;
const midY = 10;
const baseRadius = 9.2;

function sizeMultiplier() {
  return coordY(baseRadius) / 4000;
}

function drawTree(image, radius, angle, size = 1) {
  const multiplier = sizeMultiplier() * size;
  const width = image.width * multiplier;
  const height = image.height * multiplier;
  const sin = Math.sin(angle);
  const cos = Math.cos(angle);
  context.setTransform(cos, sin, -sin, cos, ...coords(midX, midY));
  context.drawImage(image, -width / 2, -radius - height, width, height);
}

function treeCleanup() {
  context.setTransform(1, 0, 0, 1, 0, 0);
}

function lineSetup() {
  context.strokeStyle = 'rgba(0, 0, 0, 0.3)';
  context.lineWidth = sizeMultiplier() * 2;
  context.setLineDash([sizeMultiplier() * 4, sizeMultiplier() * 1.5]);
}

function drawLine(radius, angle) {
  const sin = Math.sin(angle);
  const cos = Math.cos(angle);
  context.beginPath();
  context.setTransform(cos, sin, -sin, cos, ...coords(midX, midY));
  context.moveTo(0, -radius -coordY(1));
  context.lineTo(0, coordY(0));
  context.stroke();
}

function lineCleanup() {
  context.setTransform(1, 0, 0, 1, 0, 0);
  context.setLineDash([]);
}

function draw(now) {
  requestAnimationFrame(draw);
  if (resized) {
    resized = false;
    setSizeFromWindow();
  }

  const offset = now / 20000;
  const radius = coordY(baseRadius + beatValue() / 500 * baseRadius);

  context.fillStyle = '#BBF3FC';
  context.fillRect(0, 0, ...coords(1, 1));

  context.beginPath();
  context.fillStyle = 'rgba(232, 228, 109, 0.6)';
  context.moveTo(...coords(midX, midY));
  context.lineTo(coordX(midX - 0.03), 0);
  context.lineTo(coordX(midX + 0.03), 0);
  context.fill();

  context.beginPath();
  context.fillStyle = '#8BE075';
  context.arc(...coords(midX, midY), radius, 0, circle);
  context.fill();

  lineSetup();
  for (const lineAngle of lineAngles()) {
    drawLine(radius, lineAngle);
  }
  lineCleanup();

  for (const [treeOutlineAngle, size] of treeOutlineAngles()) {
    drawTree(treeOutline, radius, treeOutlineAngle, size);
  }
  for (const treeAngle of treeAngles()) {
    drawTree(tree, radius, treeAngle);
  }
  treeCleanup();
}

window.onresize = () => {
  resized = true;
};

requestAnimationFrame(draw);
<|endoftext|>


<commit_before>let json = {};

function focusFilter() {
  document.getElementById("filter").select();
}

function inputChanged() {
  renderRight(document.getElementById('filter').value);
}

function setFilter(filter) {
  document.getElementById('filter').value = filter;
  renderRight(filter);
}

function renderSidenavList(list) {
  let html = "";
  for(let i of list) {
    html = html + "" + i.name + "
";
  }

  return html;
}

function renderLeft() {
  document.getElementById("sidenav_statements").innerHTML = renderSidenavList(json.statements);
  document.getElementById("sidenav_expressions").innerHTML = renderSidenavList(json.expressions);
  document.getElementById("sidenav_structures").innerHTML = renderSidenavList(json.structures);
}

function renderList(filter, list) {
  let ret = "";
  for(let i of list) {
    if (!filter || i.name.toLowerCase().includes(filter.toLowerCase())) {
      ret = ret + "
" +
        "" + i.name + "
" +
        "

";
    }
  }
  return ret;
}

function renderRight(filter) {
  let html = "";

  const statements = renderList(filter, json.statements);
  if (statements !== "") {
    html = "

Statements
" + statements + "
";
  }

  const expressions = renderList(filter, json.expressions);
  if (expressions !== "") {
    html = html + "

Expressions
" + expressions + "
";
  }

  const structures = renderList(filter, json.structures);
  if (structures !== "") {
    html = html + "

Structures
" + structures + "
";
  }

  document.getElementById("main").innerHTML = html;
}

function renderSyntax(type, name) {
  // lookup
  let found = {};
  let prev = {};
  let next = {};
  let list = json[type+"s"];
  for(let index = 0; index < list.length; index++) {
    if (list[index].name === name) {
      found = list[index];
      prev = list[index - 1];
      next = list[index + 1];
      break;
    }
  }

  let html = "
" + type + ": " + name + "
\n";

  html = html + "Home
\n";
  if (prev) {
    html = html + "Prev: " + prev.name + "
\n";
  }
  if (next) {
    html = html + "Next: " + next.name + "
\n";
  }

  let use = found.using.map((e) => { return "" + e + ""; });
  let by = found.used_by.map((e) => { return "" + e + ""; });

  html = html + found.svg + "
\n" +
    "Using: " + use.join(", ") + "
\n" +
    "Used by: " + by.join(", ") + "
\n";

  document.getElementById("body").innerHTML = html;
}

class Router {
  static popstate() {
    if(window.location.hash === "") {
      renderMain();
    } else {
      let split = window.location.hash.split("/");
      renderSyntax(split[1], split[2]);
    }
  }
}

function renderMain() {
  document.getElementById("body").innerHTML =
    "
\n" +
    "
\n" +
    "
abaplint
\n" +
    "<input type=\"text\" id=\"filter\" oninput=\"javascript:inputChanged();\" onfocus=\"javascript:focusFilter()\"></input>
\n" +
    "
\n" +
    "Statements
\n" +
    "
Loading
\n" +
    "
\n" +
    "Expressions
\n" +
    "
Loading
\n" +
    "
\n" +
    "Structures
\n" +
    "
Loading
\n" +
    "
\n" +
    "
Loading
";

  document.getElementById("filter").focus();
  renderLeft();
  renderRight();
}

function run() {
  window.onpopstate = Router.popstate;
  json = data;
  Router.popstate();
}

run();<commit_msg>syntax: add links to source, does not work for all<commit_after>let json = {};

function focusFilter() {
  document.getElementById("filter").select();
}

function inputChanged() {
  renderRight(document.getElementById('filter').value);
}

function setFilter(filter) {
  document.getElementById('filter').value = filter;
  renderRight(filter);
}

function renderSidenavList(list) {
  let html = "";
  for(let i of list) {
    html = html + "" + i.name + "
";
  }

  return html;
}

function renderLeft() {
  document.getElementById("sidenav_statements").innerHTML = renderSidenavList(json.statements);
  document.getElementById("sidenav_expressions").innerHTML = renderSidenavList(json.expressions);
  document.getElementById("sidenav_structures").innerHTML = renderSidenavList(json.structures);
}

function renderList(filter, list) {
  let ret = "";
  for(let i of list) {
    if (!filter || i.name.toLowerCase().includes(filter.toLowerCase())) {
      ret = ret + "
" +
        "" + i.name + "
" +
        "

";
    }
  }
  return ret;
}

function renderRight(filter) {
  let html = "";

  const statements = renderList(filter, json.statements);
  if (statements !== "") {
    html = "

Statements
" + statements + "
";
  }

  const expressions = renderList(filter, json.expressions);
  if (expressions !== "") {
    html = html + "

Expressions
" + expressions + "
";
  }

  const structures = renderList(filter, json.structures);
  if (structures !== "") {
    html = html + "

Structures
" + structures + "
";
  }

  document.getElementById("main").innerHTML = html;
}

function renderSyntax(type, name) {
  // lookup
  let found = {};
  let prev = {};
  let next = {};
  let list = json[type+"s"];
  for(let index = 0; index < list.length; index++) {
    if (list[index].name === name) {
      found = list[index];
      prev = list[index - 1];
      next = list[index + 1];
      break;
    }
  }

  let html = "
" + type + ": " + name + "
\n";

  html = html + "Home
\n";
  if (prev) {
    html = html + "Prev: " + prev.name + "
\n";
  }
  if (next) {
    html = html + "Next: " + next.name + "
\n";
  }
  let filename = found.name.replace(/(.)([A-Z])/, "$1_$2").toLowerCase();
  html = html + "Source
";

  let use = found.using.map((e) => { return "" + e + ""; });
  let by = found.used_by.map((e) => { return "" + e + ""; });

  html = html + found.svg + "
\n" +
    "Using: " + use.join(", ") + "
\n" +
    "Used by: " + by.join(", ") + "
\n";

  document.getElementById("body").innerHTML = html;
}

class Router {
  static popstate() {
    if(window.location.hash === "") {
      renderMain();
    } else {
      let split = window.location.hash.split("/");
      renderSyntax(split[1], split[2]);
    }
  }
}

function renderMain() {
  document.getElementById("body").innerHTML =
    "
\n" +
    "
\n" +
    "
abaplint
\n" +
    "<input type=\"text\" id=\"filter\" oninput=\"javascript:inputChanged();\" onfocus=\"javascript:focusFilter()\"></input>
\n" +
    "
\n" +
    "Statements
\n" +
    "
Loading
\n" +
    "
\n" +
    "Expressions
\n" +
    "
Loading
\n" +
    "
\n" +
    "Structures
\n" +
    "
Loading
\n" +
    "
\n" +
    "
Loading
";

  document.getElementById("filter").focus();
  renderLeft();
  renderRight();
}

function run() {
  window.onpopstate = Router.popstate;
  json = data;
  Router.popstate();
}

run();<|endoftext|>