<commit_before>odoo.define('web_editor.backend', function (require) {
'use strict';

var core = require('web.core');
var session = require('web.session');
var Model = require('web.DataModel');
var common = require('web.form_common');
var base = require('web_editor.base');
var editor = require('web_editor.editor');
var summernote = require('web_editor.summernote');
var transcoder = require('web_editor.transcoder');

var QWeb = core.qweb;
var _t = core._t;

/**
 * FieldTextHtml Widget
 * Intended for FieldText widgets meant to display HTML content. This
 * widget will instantiate an iframe with the editor summernote improved by odoo
 */

var widget = common.AbstractField.extend(common.ReinitializeFieldMixin);

var FieldTextHtmlSimple = widget.extend({
    template: 'web_editor.FieldTextHtmlSimple',
    _config: function () {
        var self = this;
        var config = {
            'focus': false,
            'height': 180,
            'toolbar': [
                ['style', ['style']],
                ['font', ['bold', 'italic', 'underline', 'clear']],
                ['fontsize', ['fontsize']],
                ['color', ['color']],
                ['para', ['ul', 'ol', 'paragraph']],
                ['table', ['table']],
                ['insert', ['link', 'picture']],
                ['history', ['undo', 'redo']]
            ],
            'prettifyHtml': false,
            'styleWithSpan': false,
            'inlinemedia': ['p'],
            'lang': "odoo",
            'onChange': function (value) {
                self.internal_set_value(value);
                self.trigger('changed_value');
            }
        };
        if (session.debug) {
            config.toolbar.splice(7, 0, ['view', ['codeview']]);
        }
        return config;
    },
    start: function() {
        var def = this._super.apply(this, arguments);
        this.$translate.remove();
        this.$translate = $();
        // Triggers a mouseup to refresh the editor toolbar
        this.$content.trigger('mouseup');
        return def;
    },
    initialize_content: function() {
        var self = this;
        this.$textarea = this.$("textarea").val(this.get('value') || "

");
        this.$content = $();

        if (this.get("effective_readonly")) {
            if (this.options['style-inline']) {
                var $iframe = $('');
                this.$textarea.hide().after($iframe);
                var load = function () {
                    self.$content = $($iframe.contents()[0]).find("body");
                    self.$content.html(self.text_to_html(self.get('value')));
                    self.resize();
                };
                setTimeout(load);
                $iframe.on('load', load);
            } else {
                this.$content = $('
');
                this.$textarea.hide().after(this.$content);
            }
        } else {
            this.$textarea.summernote(this._config());

            if (this.field.translate && this.view) {
                $(QWeb.render('web_editor.FieldTextHtml.button.translate', {'widget': this}))
                    .appendTo(this.$('.note-toolbar'))
                    .on('click', this.on_translate);
            }

            var reset = _.bind(this.reset_history, this);
            this.view.on('load_record', this, reset);
            setTimeout(reset, 0);

            this.$content = this.$('.note-editable:first');
            if (this.options['style-inline']) {
                transcoder.style_to_class(this.$content);
            }
        }

        $(".oe-view-manager-content").on("scroll", function () {
            $('.o_table_handler').remove();
        });
        this._super();
    },
    reset_history: function () {
        var history = this.$content.data('NoteHistory');
        if (history) {
            history.reset();
            self.$('.note-toolbar').find('button[data-event="undo"]').attr('disabled', true);
        }
    },
    text_to_html: function (text) {
        var value = text || "";
        try {
            $(text)[0].innerHTML;
            return text;
        } catch (e) {
            if (value.match(/^\s*$/)) {
                value = '

';
            } else {
                value = "
"+value.split(/
/).join("

")+"
";
                value = value.replace(/
<\/p>/g, '').replace('

', '
').replace('
<p ', ' iframe.o_readonly').css('height', '0px').css('height', Math.max(30, Math.min(this.$content[0] ? this.$content[0].scrollHeight : 0, 500)) + 'px');
    },
    render_value: function() {
        var value = this.get('value');
        this.$textarea.val(value || '');
        this.$content.html(this.text_to_html(value));
        if (this.get("effective_readonly")) {
            this.resize();
        } else {
            transcoder.style_to_class(this.$content);
        }
        if (this.$content.is(document.activeElement)) {
            this.focus();
        }
        var history = this.$content.data('NoteHistory');
        if (history && history.recordUndo()) {
            this.$('.note-toolbar').find('button[data-event="undo"]').attr('disabled', false);
        }
    },
    is_false: function() {
        return !this.get('value') || this.get('value') === "

" || !this.get('value').match(/\S/);
    },
    commit_value: function() {
        /* Switch to WYSIWYG mode if currently in code view */
        if (session.debug) {
            var layoutInfo = this.$textarea.data('layoutInfo');
            $.summernote.pluginEvents.codeview(undefined, undefined, layoutInfo, false);
        }
        if (this.options['style-inline']) {
            transcoder.class_to_style(this.$content);
            transcoder.font_to_img(this.$content);
        }
        this.internal_set_value(this.$content.html());
    },
    destroy_content: function () {
        $(".oe-view-manager-content").off("scroll");
        this.$textarea.destroy();
        this._super();
    }
});

var FieldTextHtml = widget.extend({
    template: 'web_editor.FieldTextHtml',
    willStart: function () {
        var self = this;

        if (this.field.translate === false) {
            this.languages = [];
            return $.when();
        }
        return new Model('res.lang').call("search_read", [[['code', '!=', 'en_US']], ["name", "code"]]).then(function (res) {
            self.languages = res;
        });
    },
    start: function () {
        var self = this;

        this.callback = _.uniqueId('FieldTextHtml_');
        window.odoo[this.callback+"_editor"] = function (EditorBar) {
            setTimeout(function () {
                self.on_editor_loaded(EditorBar);
            },0);
        };
        window.odoo[this.callback+"_content"] = function (EditorBar) {
            self.on_content_loaded();
        };
        window.odoo[this.callback+"_updown"] = null;
        window.odoo[this.callback+"_downup"] = function (value) {
            self.internal_set_value(value);
            self.trigger('changed_value');
            self.resize();
        };

        // init jqery objects
        this.$iframe = this.$el.find('iframe');
        this.document = null;
        this.$body = $();
        this.$content = $();

        this.$iframe.css('min-height', 'calc(100vh - 360px)');

        // init resize
        this.resize = function resize() {
            if (self.get('effective_readonly')) { return; }
            if ($("body").hasClass("o_form_FieldTextHtml_fullscreen")) {
                self.$iframe.css('height', (document.body.clientHeight - self.$iframe.offset().top) + 'px');
            } else {
                self.$iframe.css("height", (self.$body.find("#oe_snippets").length ? 500 : 300) + "px");
            }
        };
        $(window).on('resize', this.resize);

        var def = this._super.apply(this, arguments);
        this.$translate.remove();
        this.$translate = $();
        return def;
    },
    get_datarecord: function() {
        return this.view.get_fields_values();
    },
    get_url: function (_attr) {
        var src = this.options.editor_url || "/web_editor/field/html";
        var datarecord = this.get_datarecord();

        var attr = {
            'model': this.view.model,
            'field': this.name,
            'res_id': datarecord.id || '',
            'callback': this.callback
        };
        _attr = _attr || {};

        if (this.options['style-inline']) {
            attr.inline_mode = 1;
        }
        if (this.options.snippets) {
            attr.snippets = this.options.snippets;
        }
        if (this.options.template) {
            attr.template = this.options.template;
        }
        if (!this.get("effective_readonly")) {
            attr.enable_editor = 1;
        }
        if (this.field.translate) {
            attr.translatable = 1;
        }
        if (session.debug) {
            attr.debug = 1;
        }

        attr.lang = attr.enable_editor ? 'en_US' : this.session.user_context.lang;

        for (var k in _attr) {
            attr[k] = _attr[k];
        }

        if (src.indexOf('?') === -1) {
            src += "?";
        }

        for (var k in attr) {
            if (attr[k] !== null) {
                src += "&"+k+"="+(_.isBoolean(attr[k]) ? +attr[k] : attr[k]);
            }
        }

        delete datarecord[this.name];
        src += "&datarecord="+ encodeURIComponent(JSON.stringify(datarecord));
        return src;
    },
    initialize_content: function() {
        var self = this;
        this.$el.closest('.modal-body').css('max-height', 'none');
        this.$iframe = this.$el.find('iframe');
        // deactivate any button to avoid saving a not ready iframe
        $('.o_cp_buttons, .o_statusbar_buttons').find('button').addClass('o_disabled').attr('disabled', true);
        this.document = null;
        this.$body = $();
        this.$content = $();
        this.editor = false;
        window.odoo[this.callback+"_updown"] = null;
        this.$iframe.attr("src", this.get_url());
        this.view.on("load_record", this, function(r){
            if (!self.$body.find('.o_dirty').length){
                var url = self.get_url();
                if(url !== self.$iframe.attr("src")){
                    self.$iframe.attr("src", url);
                }
            }
        });
    },
    on_content_loaded: function () {
        var self = this;
        this.document = this.$iframe.contents()[0];
        this.$body = $("body", this.document);
        this.$content = this.$body.find("#editable_area");
        this._toggle_label();
        this.lang = this.$iframe.attr('src').match(/[?&]lang=([^&]+)/);
        this.lang = this.lang ? this.lang[1] : this.view.dataset.context.lang;
        this._dirty_flag = false;
        this.render_value();
        // reactivate all the buttons when the field's content (the iframe) is loaded
        $('.o_cp_buttons, .o_statusbar_buttons').find('button').removeClass('o_disabled').attr('disabled', false);
        setTimeout(function () {
            self.add_button();
            setTimeout(self.resize,0);
        }, 0);
    },
    on_editor_loaded: function (EditorBar) {
        var self = this;
        this.editor = EditorBar;
        if (this.get('value') && window.odoo[self.callback+"_updown"] && !(this.$content.html()||"").length) {
            this.render_value();
        }
        setTimeout(function () {
            setTimeout(self.resize,0);
        }, 0);
    },
    add_button: function () {
        var self = this;
        var $to = this.$body.find("#web_editor-top-edit, #wrapwrap").first();

        $(QWeb.render('web_editor.FieldTextHtml.translate', {'widget': this}))
            .appendTo($to)
            .on('change', 'select', function () {
                var lang = $(this).val();
                var edit = !self.get("effective_readonly");
                var trans = lang !== 'en_US';
                self.$iframe.attr("src", self.get_url({
                    'edit_translations': edit && trans,
                    'enable_editor': edit && !trans,
                    'lang': lang
                }));
            });

        $(QWeb.render('web_editor.FieldTextHtml.fullscreen'))
            .appendTo($to)
            .on('click', '.o_fullscreen', function () {
                $("body").toggleClass("o_form_FieldTextHtml_fullscreen");
                var full = $("body").hasClass("o_form_FieldTextHtml_fullscreen");
                self.$iframe.parents().toggleClass('o_form_fullscreen_ancestor', full);
                self.resize();
            });

        this.$body.on('click', '[data-action="cancel"]', function (event) {
            event.preventDefault();
            self.initialize_content();
        });
    },
    render_value: function() {
        if (this.$iframe.attr('src').match(/[?&]edit_translations=1/)) {
            return;
        }
        // ONLY HAVE THIS IN 9.0 AND SAAS-11
        var is_editor_onchange = this.get('value') === '
on_change_model_and_list
';
        if (this.lang !== this.view.dataset.context.lang && !is_editor_onchange) {
            return;
        }
        var value = (this.get('value') || "").replace(/^
]*>(\s*|
)<\/p>$/, '');
        if (!this.$content) {
            return;
        }
        if (!this.get("effective_readonly")) {
            if(window.odoo[this.callback+"_updown"]) {
                window.odoo[this.callback+"_updown"](value, this.view.get_fields_values(), this.name);
                this.resize();
            }
        } else {
            this.$content.html(value);
            if (this.$iframe[0].contentWindow) {
                this.$iframe.css("height", (this.$body.height()+20) + "px");
            }
        }
    },
    is_false: function() {
        return this.get('value') === false || !this.$content.html() || !this.$content.html().match(/\S/);
    },
    commit_value: function () {
        if (this.lang !== 'en_US' && this.$body.find('.o_dirty').length) {
            this.internal_set_value( this.view.datarecord[this.name] );
            this._dirty_flag = false;
            return this.editor.save();
        } else if (this._dirty_flag && this.editor && this.editor.buildingBlock) {
            /* Switch to WYSIWYG mode if currently in code view */
            if (session.debug) {
                var layoutInfo = this.editor.rte.editable().data('layoutInfo');
                $.summernote.pluginEvents.codeview(undefined, undefined, layoutInfo, false);
            }
            this.editor.buildingBlock.clean_for_save();
            this.internal_set_value( this.$content.html() );
        }
    },
    destroy: function () {
        $(window).off('resize', this.resize);
        delete window.odoo[this.callback+"_editor"];
        delete window.odoo[this.callback+"_content"];
        delete window.odoo[this.callback+"_updown"];
        delete window.odoo[this.callback+"_downup"];
    }
});

core.form_widget_registry
    .add('html', FieldTextHtmlSimple)
    .add('html_frame', FieldTextHtml);

return {
    FieldTextHtmlSimple: FieldTextHtmlSimple,
    FieldTextHtml: FieldTextHtml,
};

});
<commit_msg>[FIX] web_editor: firefox editor hidden mass mail<commit_after>odoo.define('web_editor.backend', function (require) {
'use strict';

var core = require('web.core');
var session = require('web.session');
var Model = require('web.DataModel');
var common = require('web.form_common');
var base = require('web_editor.base');
var editor = require('web_editor.editor');
var summernote = require('web_editor.summernote');
var transcoder = require('web_editor.transcoder');

var QWeb = core.qweb;
var _t = core._t;

/**
 * FieldTextHtml Widget
 * Intended for FieldText widgets meant to display HTML content. This
 * widget will instantiate an iframe with the editor summernote improved by odoo
 */

var widget = common.AbstractField.extend(common.ReinitializeFieldMixin);

var FieldTextHtmlSimple = widget.extend({
    template: 'web_editor.FieldTextHtmlSimple',
    _config: function () {
        var self = this;
        var config = {
            'focus': false,
            'height': 180,
            'toolbar': [
                ['style', ['style']],
                ['font', ['bold', 'italic', 'underline', 'clear']],
                ['fontsize', ['fontsize']],
                ['color', ['color']],
                ['para', ['ul', 'ol', 'paragraph']],
                ['table', ['table']],
                ['insert', ['link', 'picture']],
                ['history', ['undo', 'redo']]
            ],
            'prettifyHtml': false,
            'styleWithSpan': false,
            'inlinemedia': ['p'],
            'lang': "odoo",
            'onChange': function (value) {
                self.internal_set_value(value);
                self.trigger('changed_value');
            }
        };
        if (session.debug) {
            config.toolbar.splice(7, 0, ['view', ['codeview']]);
        }
        return config;
    },
    start: function() {
        var def = this._super.apply(this, arguments);
        this.$translate.remove();
        this.$translate = $();
        // Triggers a mouseup to refresh the editor toolbar
        this.$content.trigger('mouseup');
        return def;
    },
    initialize_content: function() {
        var self = this;
        this.$textarea = this.$("textarea").val(this.get('value') || "

");
        this.$content = $();

        if (this.get("effective_readonly")) {
            if (this.options['style-inline']) {
                var $iframe = $('');
                this.$textarea.hide().after($iframe);
                var load = function () {
                    self.$content = $($iframe.contents()[0]).find("body");
                    self.$content.html(self.text_to_html(self.get('value')));
                    self.resize();
                };
                setTimeout(load);
                $iframe.on('load', load);
            } else {
                this.$content = $('
');
                this.$textarea.hide().after(this.$content);
            }
        } else {
            this.$textarea.summernote(this._config());

            if (this.field.translate && this.view) {
                $(QWeb.render('web_editor.FieldTextHtml.button.translate', {'widget': this}))
                    .appendTo(this.$('.note-toolbar'))
                    .on('click', this.on_translate);
            }

            var reset = _.bind(this.reset_history, this);
            this.view.on('load_record', this, reset);
            setTimeout(reset, 0);

            this.$content = this.$('.note-editable:first');
            if (this.options['style-inline']) {
                transcoder.style_to_class(this.$content);
            }
        }

        $(".oe-view-manager-content").on("scroll", function () {
            $('.o_table_handler').remove();
        });
        this._super();
    },
    reset_history: function () {
        var history = this.$content.data('NoteHistory');
        if (history) {
            history.reset();
            self.$('.note-toolbar').find('button[data-event="undo"]').attr('disabled', true);
        }
    },
    text_to_html: function (text) {
        var value = text || "";
        try {
            $(text)[0].innerHTML;
            return text;
        } catch (e) {
            if (value.match(/^\s*$/)) {
                value = '

';
            } else {
                value = "
"+value.split(/
/).join("

")+"
";
                value = value.replace(/
<\/p>/g, '').replace('

', '
').replace('
<p ', ' iframe.o_readonly').css('height', '0px').css('height', Math.max(30, Math.min(this.$content[0] ? this.$content[0].scrollHeight : 0, 500)) + 'px');
    },
    render_value: function() {
        var value = this.get('value');
        this.$textarea.val(value || '');
        this.$content.html(this.text_to_html(value));
        if (this.get("effective_readonly")) {
            this.resize();
        } else {
            transcoder.style_to_class(this.$content);
        }
        if (this.$content.is(document.activeElement)) {
            this.focus();
        }
        var history = this.$content.data('NoteHistory');
        if (history && history.recordUndo()) {
            this.$('.note-toolbar').find('button[data-event="undo"]').attr('disabled', false);
        }
    },
    is_false: function() {
        return !this.get('value') || this.get('value') === "

" || !this.get('value').match(/\S/);
    },
    commit_value: function() {
        /* Switch to WYSIWYG mode if currently in code view */
        if (session.debug) {
            var layoutInfo = this.$textarea.data('layoutInfo');
            $.summernote.pluginEvents.codeview(undefined, undefined, layoutInfo, false);
        }
        if (this.options['style-inline']) {
            transcoder.class_to_style(this.$content);
            transcoder.font_to_img(this.$content);
        }
        this.internal_set_value(this.$content.html());
    },
    destroy_content: function () {
        $(".oe-view-manager-content").off("scroll");
        this.$textarea.destroy();
        this._super();
    }
});

var FieldTextHtml = widget.extend({
    template: 'web_editor.FieldTextHtml',
    willStart: function () {
        var self = this;

        if (this.field.translate === false) {
            this.languages = [];
            return $.when();
        }
        return new Model('res.lang').call("search_read", [[['code', '!=', 'en_US']], ["name", "code"]]).then(function (res) {
            self.languages = res;
        });
    },
    start: function () {
        var self = this;

        this.callback = _.uniqueId('FieldTextHtml_');
        window.odoo[this.callback+"_editor"] = function (EditorBar) {
            setTimeout(function () {
                self.on_editor_loaded(EditorBar);
            },0);
        };
        window.odoo[this.callback+"_content"] = function (EditorBar) {
            self.on_content_loaded();
        };
        window.odoo[this.callback+"_updown"] = null;
        window.odoo[this.callback+"_downup"] = function (value) {
            self.internal_set_value(value);
            self.trigger('changed_value');
            self.resize();
        };

        // init jqery objects
        this.$iframe = this.$el.find('iframe');
        this.document = null;
        this.$body = $();
        this.$content = $();

        this.$iframe.css('min-height', 'calc(100vh - 360px)');

        // init resize
        this.resize = function resize() {
            if (self.get('effective_readonly')) { return; }
            if ($("body").hasClass("o_form_FieldTextHtml_fullscreen")) {
                self.$iframe.css('height', (document.body.clientHeight - self.$iframe.offset().top) + 'px');
            } else {
                self.$iframe.css("height", (self.$body.find("#oe_snippets").length ? 500 : 300) + "px");
            }
        };
        $(window).on('resize', this.resize);

        var def = this._super.apply(this, arguments);
        this.$translate.remove();
        this.$translate = $();
        return def;
    },
    get_datarecord: function() {
        return this.view.get_fields_values();
    },
    get_url: function (_attr) {
        var src = this.options.editor_url || "/web_editor/field/html";
        var datarecord = this.get_datarecord();

        var attr = {
            'model': this.view.model,
            'field': this.name,
            'res_id': datarecord.id || '',
            'callback': this.callback
        };
        _attr = _attr || {};

        if (this.options['style-inline']) {
            attr.inline_mode = 1;
        }
        if (this.options.snippets) {
            attr.snippets = this.options.snippets;
        }
        if (this.options.template) {
            attr.template = this.options.template;
        }
        if (!this.get("effective_readonly")) {
            attr.enable_editor = 1;
        }
        if (this.field.translate) {
            attr.translatable = 1;
        }
        if (session.debug) {
            attr.debug = 1;
        }

        attr.lang = attr.enable_editor ? 'en_US' : this.session.user_context.lang;

        for (var k in _attr) {
            attr[k] = _attr[k];
        }

        if (src.indexOf('?') === -1) {
            src += "?";
        }

        for (var k in attr) {
            if (attr[k] !== null) {
                src += "&"+k+"="+(_.isBoolean(attr[k]) ? +attr[k] : attr[k]);
            }
        }

        delete datarecord[this.name];
        src += "&datarecord="+ encodeURIComponent(JSON.stringify(datarecord));
        return src;
    },
    initialize_content: function() {
        var self = this;
        this.$el.closest('.modal-body').css('max-height', 'none');
        this.$iframe = this.$el.find('iframe');
        // deactivate any button to avoid saving a not ready iframe
        $('.o_cp_buttons, .o_statusbar_buttons').find('button').addClass('o_disabled').attr('disabled', true);
        this.document = null;
        this.$body = $();
        this.$content = $();
        this.editor = false;
        window.odoo[this.callback+"_updown"] = null;
        this.$iframe.attr("src", this.get_url());
        this.view.on("load_record", this, function(r){
            if (!self.$body.find('.o_dirty').length){
                var url = self.get_url();
                if(url !== self.$iframe.attr("src")){
                    self.$iframe.attr("src", url);
                }
            }
        });
    },
    on_content_loaded: function () {
        var self = this;
        this.document = this.$iframe.contents()[0];
        this.$body = $("body", this.document);
        this.$content = this.$body.find("#editable_area");
        this._toggle_label();
        this.lang = this.$iframe.attr('src').match(/[?&]lang=([^&]+)/);
        this.lang = this.lang ? this.lang[1] : this.view.dataset.context.lang;
        this._dirty_flag = false;
        this.render_value();
        // reactivate all the buttons when the field's content (the iframe) is loaded
        $('.o_cp_buttons, .o_statusbar_buttons').find('button').removeClass('o_disabled').attr('disabled', false);
        setTimeout(function () {
            self.add_button();
            setTimeout(self.resize,0);
        }, 0);
    },
    on_editor_loaded: function (EditorBar) {
        var self = this;
        this.editor = EditorBar;
        if (this.get('value') && window.odoo[self.callback+"_updown"] && !(this.$content.html()||"").length) {
            this.render_value();
        }
        setTimeout(function () {
            setTimeout(self.resize,0);
        }, 0);
    },
    add_button: function () {
        var self = this;
        var $to = this.$body.find("#web_editor-top-edit, #wrapwrap").first();

        $(QWeb.render('web_editor.FieldTextHtml.translate', {'widget': this}))
            .appendTo($to)
            .on('change', 'select', function () {
                var lang = $(this).val();
                var edit = !self.get("effective_readonly");
                var trans = lang !== 'en_US';
                self.$iframe.attr("src", self.get_url({
                    'edit_translations': edit && trans,
                    'enable_editor': edit && !trans,
                    'lang': lang
                }));
            });

        $(QWeb.render('web_editor.FieldTextHtml.fullscreen'))
            .appendTo($to)
            .on('click', '.o_fullscreen', function () {
                $("body").toggleClass("o_form_FieldTextHtml_fullscreen");
                var full = $("body").hasClass("o_form_FieldTextHtml_fullscreen");
                self.$iframe.parents().toggleClass('o_form_fullscreen_ancestor', full);
                self.resize();
            });

        this.$body.on('click', '[data-action="cancel"]', function (event) {
            event.preventDefault();
            self.initialize_content();
        });
    },
    render_value: function() {
        if (this.$iframe.attr('src').match(/[?&]edit_translations=1/)) {
            return;
        }
        // ONLY HAVE THIS IN 9.0 AND SAAS-11
        var is_editor_onchange = this.get('value') === '
on_change_model_and_list
';
        if (this.lang !== this.view.dataset.context.lang && !is_editor_onchange) {
            return;
        }
        var value = (this.get('value') || "").replace(/^
]*>(\s*|
)<\/p>$/, '');
        if (!this.$content) {
            return;
        }
        if (!this.get("effective_readonly")) {
            if(window.odoo[this.callback+"_updown"]) {
                window.odoo[this.callback+"_updown"](value, this.view.get_fields_values(), this.name);
                this.resize();
            }
        } else {
            this.$content.html(value);
            if (this.$iframe[0].contentWindow) {
                this.$iframe.css("height", (this.$body.height()+20) + "px");
            }
        }
    },
    is_false: function() {
        return this.get('value') === false || !this.$content.html() || !this.$content.html().match(/\S/);
    },
    commit_value: function () {
        if (this.lang !== 'en_US' && this.$body.find('.o_dirty').length) {
            this.internal_set_value( this.view.datarecord[this.name] );
            this._dirty_flag = false;
            return this.editor.save();
        } else if (this._dirty_flag && this.editor && this.editor.buildingBlock) {
            /* Switch to WYSIWYG mode if currently in code view */
            if (session.debug) {
                var layoutInfo = this.editor.rte.editable().data('layoutInfo');
                $.summernote.pluginEvents.codeview(undefined, undefined, layoutInfo, false);
            }
            var $ancestors = this.$iframe.filter(':not(:visible)').parentsUntil(':visible').addBack();
            var ancestorsStyle = [];
            // temporarily force displaying iframe (needed for firefox)
            _.each($ancestors, function (el) {
                var $el = $(el);
                ancestorsStyle.unshift($el.attr('style') || null);
                $el.css({display: 'initial', visibility: 'hidden', height: 1});
            });
            this.editor.buildingBlock.clean_for_save();
            _.each($ancestors, function (el) {
                var $el = $(el);
                $el.attr('style', ancestorsStyle.pop());
            });
            this.internal_set_value( this.$content.html() );
        }
    },
    destroy: function () {
        $(window).off('resize', this.resize);
        delete window.odoo[this.callback+"_editor"];
        delete window.odoo[this.callback+"_content"];
        delete window.odoo[this.callback+"_updown"];
        delete window.odoo[this.callback+"_downup"];
    }
});

core.form_widget_registry
    .add('html', FieldTextHtmlSimple)
    .add('html_frame', FieldTextHtml);

return {
    FieldTextHtmlSimple: FieldTextHtmlSimple,
    FieldTextHtml: FieldTextHtml,
};

});
<|endoftext|>


<commit_before>/*
 * RPSLS by Ross Ward 2015
 * micward2[at]gmail[dot]com
*/

// Players and Weapons
var human    = prompt("Choose rock, paper, scissors, lizard or spock:");
var computer = Math.random();
var weapons  = ['rock', 'paper', 'scissors', 'lizard', 'spock'];

// Downcase input on var human
human = human.toLowerCase();

// Assign weapon to computer based on random value
if (computer < 0.19) {
    computer = 'rock';
} else if (computer <= 0.38) {
    computer = 'paper';
} else if (computer <= 0.57) {
    computer = 'scissors';
} else if (computer <= 0.76) {
    computer = 'lizard';
} else {
    computer = 'spock';
}

// Function to check that weapon choice is valid
// Function to check losing combinations
function inArray(needle, haystack) {
    var i = 0;
    while (i < haystack.length) {
        haystack[i] === needle ? true : false;
        i++;
    }
}

inArray(human, weapons);

// Announce weapons chosen with a summary
alert("Human: " + human + "\n" + "Computer: " + computer);

// Declare score variables, set to 0
var humanScore = 0;
var compScore  = 0;

// Combinations where particular weapons lose
var rock_loses     = ['spock', 'paper'];  // if rock draws spock OR paper he loses
var paper_loses    = ['lizard', 'scissors'];
var scissors_loses = ['rock', 'spock'];
var lizard_loses   = ['rock', 'scissors'];
var spock_loses    = ['lizard', 'paper'];

// Main logic to determine Winner
function calcWinner() {
    human === computer ? compScore += 0 : humanScore += 0;

    if (human === 'rock') {
        inArray(computer, rock_loses) ? compScore += 1 : humanScore +=1;
    }

    if (human === 'paper') {
        inArray(computer, paper_loses) ? compScore += 1 : humanScore += 1;
    }

    if (human === 'scissors') {
        inArray(computer, scissors_loses) ? compScore += 1 : humanScore += 1;
    }

    if (human === 'lizard') {
        inArray(computer, lizard_loses) ? compScore += 1 : humanScore += 1;
    }

    if (human === 'spock') {
        inArray(computer, spock_loses) ? compScore += 1 : humanScore += 1;
    }
}

calcWinner();

// Function to get final score
function finalScore() {
    if (humanScore > compScore) {
        alert("User wins game!");
    } else if (humanScore === compScore) {
        alert("Game is tied");
    } else {
        alert("Computer wins");
    }
}

finalScore();
<commit_msg>sanitize if. revert ternary to if.<commit_after>/*
 * RPSLS by Ross Ward 2015
 * micward2[at]gmail[dot]com
*/

// Players and Weapons
var human    = prompt("Choose rock, paper, scissors, lizard or spock:");
var computer = Math.random();
var weapons  = ['rock', 'paper', 'scissors', 'lizard', 'spock'];
var reDigit  = /\d/;
var reChar   = /[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]/;

// Sanitize input
if (human === '' || reDigit.exec(human) || reChar.exec(human)) {
    alert("Invalid input - Page will now reload!");
    window.location.reload();
} else {
    human = human.toLowerCase();
}

// Assign weapon to computer based on random value
if (computer < 0.19) {
    computer = 'rock';
} else if (computer <= 0.38) {
    computer = 'paper';
} else if (computer <= 0.57) {
    computer = 'scissors';
} else if (computer <= 0.76) {
    computer = 'lizard';
} else {
    computer = 'spock';
}

// Function to check that weapon choice is valid
// Function to check losing combinations
function inArray(needle, haystack) {
    var i = 0;
    while (i < haystack.length) {
        haystack[i] === needle ? true : false;
        i++;
    }
}

inArray(human, weapons);

// Announce weapons chosen with a summary
alert("Human: " + human + "\n" + "Computer: " + computer);

// Declare score variables, set to 0
var humanScore = 0;
var compScore  = 0;

// Combinations where particular weapons lose
var rock_loses     = ['spock', 'paper'];  // if rock draws spock OR paper he loses
var paper_loses    = ['lizard', 'scissors'];
var scissors_loses = ['rock', 'spock'];
var lizard_loses   = ['rock', 'scissors'];
var spock_loses    = ['lizard', 'paper'];

// Main logic to determine Winner
function calcWinner() {
    if (human === 'rock' && inArray(computer, rock_loses)) {
        compScore += 1;
    } else if (human === 'paper' && inArray(computer, paper_loses)) {
        compScore += 1;
    } else if (human === 'scissors') {
        compScore += 1;
    } else if (human === 'lizard') {
        compScore += 1;
    } else if (human === 'spock') {
        compScore += 1;
    } else {
        compScore += 0;
        humanScore += 0;
    }
}

calcWinner();

// Function to get final score
function finalScore() {
    if (humanScore > compScore) {
        alert("User wins game!");
    } else if (humanScore === compScore) {
        alert("Game is tied");
    } else {
        alert("Computer wins");
    }
}

finalScore();
<|endoftext|>


<commit_before>/**
 * Created by truthlighting on 9/20/2016.
 */
var proto = {
    /**
     * The creep for this role
     *
     * @type creep
     */
    creep: null,

    /**
     * Set the creep for this role
     *
     * @param {Creep} creep
     */
    setCreep: function(creep)
    {
        this.creep = creep;
        return this;
    },

    run: function()
    {
        if(this.creep.memory.onSpawned == undefined) {
            this.onSpawn();
            this.creep.memory.onSpawned = true;
        }

        this.action(this.creep);

        if(this.creep.ticksToLive == 1)
            this.beforeAge();
    },

    handleEvents: function()
    {
        if(this.creep.memory.onSpawned == undefined) {
            this.onSpawnStart();
            this.onSpawn();
            this.creep.memory.onSpawned = true;
        }

        if(this.creep.memory.onSpawnEnd == undefined && !this.creep.spawning) {
            this.onSpawnEnd();
            this.creep.memory.onSpawnEnd = true;
        }
    },

    getParts: function() {
        //var _ = require('lodash');

        var extensions = Game.rooms['W2N48'].find(FIND_MY_STRUCTURES, {
            filter: function(structure)
            {
                return (structure.structureType == STRUCTURE_EXTENSION && structure.energy >= 50);
            }
        }).length;
        console.log("extensions: " + extensions);

        var parts = _.cloneDeep(this.parts);
        //console.log("parts: " + parts);
        if(typeof parts[0] != "object")
            return this.parts;

        parts.reverse();

        for(var i in parts)
        {
            if((parts[i].length - 5) <= extensions) {
                return parts[i];
            }
        }
    },

    action: function() { },

    onSpawn: function() { },

    onSpawnStart: function() { },

    onSpawnEnd: function() { },

    beforeAge: function() { },

    /**
     * All credit goes to Djinni
     * @url https://bitbucket.org/Djinni/screeps/
     */
    rest: function(civilian)
    {
        var creep = this.creep;

        var distance = 4;
        var restTarget = creep.pos.findClosestByPath(FIND_MY_SPAWNS);

        if(!civilian) {
            var flags = Game.flags;
            for (var i in flags) {
                var flag = flags[i];
                if (creep.pos.inRangeTo(flag, distance) || creep.pos.findPathTo(flag).length > 0) {
                    restTarget = flag;
                    break;
                }
            }
        }

//		var flag = Game.flags['Flag1'];
//		if(flag !== undefined && civilian !== true)
//			restTarget = flag;
//
//		var flag2 = Game.flags['Flag2'];
//		if(flag !== undefined && civilian !== true && !creep.pos.inRangeTo(flag, distance) && !creep.pos.findPathTo(flag).length)
//			restTarget = flag2;

        if (creep.getActiveBodyparts(Game.HEAL)) {
//			distance = distance - 1;
        }
        else if (creep.getActiveBodyparts(Game.RANGED_ATTACK)) {
//			distance = distance - 1;
        }
        if (creep.pos.findPathTo(restTarget).length > distance) {
            creep.moveTo(restTarget);
        }
    },

    /**
     * All credit goes to Djinni
     * @url https://bitbucket.org/Djinni/screeps/
     */
    rangedAttack: function(target) {
        var creep = this.creep;

        if(!target)
            target = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS);

        if(target) {
            if (target.pos.inRangeTo(creep.pos, 3) ) {
                creep.rangedAttack(target);
                return target;
            }
        }
        return null;
    },

    keepAwayFromEnemies: function()
    {
        var creep = this.creep;

        var target = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS);
        if(target !== null && target.pos.inRangeTo(creep.pos, 3))
            creep.moveTo(creep.pos.x + creep.pos.x - target.pos.x, creep.pos.y + creep.pos.y - target.pos.y );
    },

    /**
     * All credit goes to Djinni
     * @url https://bitbucket.org/Djinni/screeps/
     */
    kite: function(target) {
        var creep = this.creep;

        if (target.pos.inRangeTo(creep.pos, 2)) {
            creep.moveTo(creep.pos.x + creep.pos.x - target.pos.x, creep.pos.y + creep.pos.y - target.pos.y );
            return true;
        } else if (target.pos.inRangeTo(creep.pos, 3)) {
            return true;
        }
        else {
            creep.moveTo(target);
            return true;
        }

        return false;
    },

    getRangedTarget: function()
    {
        var creep = this.creep;

        var closeArchers = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {
            filter: function(enemy)
            {
                return enemy.getActiveBodyparts(Game.RANGED_ATTACK) > 0
                    && creep.pos.inRangeTo(enemy, 3);
            }
        });

        if(closeArchers != null)
            return closeArchers;

        var closeMobileMelee = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {
            filter: function(enemy)
            {
                return enemy.getActiveBodyparts(Game.ATTACK) > 0
                    && enemy.getActiveBodyparts(Game.MOVE) > 0
                    && creep.pos.inRangeTo(enemy, 3);
            }
        });

        if(closeMobileMelee != null)
            return closeMobileMelee;

        var closeHealer = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {
            filter: function(enemy)
            {
                return enemy.getActiveBodyparts(Game.HEAL) > 0
                    && enemy.getActiveBodyparts(Game.MOVE) > 0
                    && creep.pos.inRangeTo(enemy, 3);
            }
        });

        if(closeHealer != null)
            return closeHealer;

        return creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS);
    }
};

module.exports = proto;<commit_msg>Starting the long process of fixing old code<commit_after>/**
 * Created by truthlighting on 9/20/2016.
 */
var proto = {
    /**
     * The creep for this role
     *
     * @type creep
     */
    creep: null,

    /**
     * Set the creep for this role
     *
     * @param {Creep} creep
     */
    setCreep: function(creep)
    {
        this.creep = creep;
        return this;
    },

    run: function()
    {
        if(this.creep.memory.onSpawned == undefined) {
            this.onSpawn();
            this.creep.memory.onSpawned = true;
        }

        this.action(this.creep);

        if(this.creep.ticksToLive == 1)
            this.beforeAge();
    },

    handleEvents: function()
    {
        if(this.creep.memory.onSpawned == undefined) {
            this.onSpawnStart();
            this.onSpawn();
            this.creep.memory.onSpawned = true;
        }

        if(this.creep.memory.onSpawnEnd == undefined && !this.creep.spawning) {
            this.onSpawnEnd();
            this.creep.memory.onSpawnEnd = true;
        }
    },

    getParts: function() {
        //var _ = require('lodash');

        var extensions = Game.rooms['W2N48'].find(FIND_MY_STRUCTURES, {
            filter: function(structure)
            {
                return (structure.structureType == STRUCTURE_EXTENSION && structure.energy >= 50);
            }
        }).length;
        //console.log("extensions: " + extensions);

        var parts = _.cloneDeep(this.parts);
        //console.log("parts: " + parts);
        if(typeof parts[0] != "object")
            return this.parts;

        parts.reverse();

        for(var i in parts)
        {
            if((parts[i].length - 5) <= extensions) {
                return parts[i];
            }
        }
    },

    action: function() { },

    onSpawn: function() { },

    onSpawnStart: function() { },

    onSpawnEnd: function() { },

    beforeAge: function() { },

    /**
     * All credit goes to Djinni
     * @url https://bitbucket.org/Djinni/screeps/
     */
    rest: function(civilian)
    {
        var creep = this.creep;

        var distance = 4;
        var restTarget = creep.pos.findClosestByPath(FIND_MY_SPAWNS);

        if(!civilian) {
            var flags = Game.flags;
            for (var i in flags) {
                var flag = flags[i];
                if (creep.pos.inRangeTo(flag, distance) || creep.pos.findPathTo(flag).length > 0) {
                    restTarget = flag;
                    break;
                }
            }
        }

//		var flag = Game.flags['Flag1'];
//		if(flag !== undefined && civilian !== true)
//			restTarget = flag;
//
//		var flag2 = Game.flags['Flag2'];
//		if(flag !== undefined && civilian !== true && !creep.pos.inRangeTo(flag, distance) && !creep.pos.findPathTo(flag).length)
//			restTarget = flag2;

        if (creep.getActiveBodyparts(Game.HEAL)) {
//			distance = distance - 1;
        }
        else if (creep.getActiveBodyparts(Game.RANGED_ATTACK)) {
//			distance = distance - 1;
        }
        if (creep.pos.findPathTo(restTarget).length > distance) {
            creep.moveTo(restTarget);
        }
    },

    /**
     * All credit goes to Djinni
     * @url https://bitbucket.org/Djinni/screeps/
     */
    rangedAttack: function(target) {
        var creep = this.creep;

        if(!target)
            target = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS);

        if(target) {
            if (target.pos.inRangeTo(creep.pos, 3) ) {
                creep.rangedAttack(target);
                return target;
            }
        }
        return null;
    },

    keepAwayFromEnemies: function()
    {
        var creep = this.creep;

        var target = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS);
        if(target !== null && target.pos.inRangeTo(creep.pos, 3))
            creep.moveTo(creep.pos.x + creep.pos.x - target.pos.x, creep.pos.y + creep.pos.y - target.pos.y );
    },

    /**
     * All credit goes to Djinni
     * @url https://bitbucket.org/Djinni/screeps/
     */
    kite: function(target) {
        var creep = this.creep;

        if (target.pos.inRangeTo(creep.pos, 2)) {
            creep.moveTo(creep.pos.x + creep.pos.x - target.pos.x, creep.pos.y + creep.pos.y - target.pos.y );
            return true;
        } else if (target.pos.inRangeTo(creep.pos, 3)) {
            return true;
        }
        else {
            creep.moveTo(target);
            return true;
        }

        return false;
    },

    getRangedTarget: function()
    {
        var creep = this.creep;

        var closeArchers = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {
            filter: function(enemy)
            {
                return enemy.getActiveBodyparts(Game.RANGED_ATTACK) > 0
                    && creep.pos.inRangeTo(enemy, 3);
            }
        });

        if(closeArchers != null)
            return closeArchers;

        var closeMobileMelee = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {
            filter: function(enemy)
            {
                return enemy.getActiveBodyparts(Game.ATTACK) > 0
                    && enemy.getActiveBodyparts(Game.MOVE) > 0
                    && creep.pos.inRangeTo(enemy, 3);
            }
        });

        if(closeMobileMelee != null)
            return closeMobileMelee;

        var closeHealer = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {
            filter: function(enemy)
            {
                return enemy.getActiveBodyparts(Game.HEAL) > 0
                    && enemy.getActiveBodyparts(Game.MOVE) > 0
                    && creep.pos.inRangeTo(enemy, 3);
            }
        });

        if(closeHealer != null)
            return closeHealer;

        return creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS);
    }
};

module.exports = proto;<|endoftext|>


<commit_before>import Head from 'next/head'
import { THEMES } from '../lib/constants'
import Reset from './style/Reset'
import Font from './style/Font'
import Typography from './style/Typography'

export const LOCAL_STYLESHEETS = ['one-dark', 'verminal', 'night-owl', 'nord']

const CDN_STYLESHEETS = THEMES.filter(
  t => t.hasStylesheet !== false && LOCAL_STYLESHEETS.indexOf(t.id) < 0
)

export const CodeMirrorLink = () => (
  <link
    rel="stylesheet"
    href="//cdnjs.cloudflare.com/ajax/libs/codemirror/5.39.2/codemirror.min.css"
  />
)

export const MetaTags = () => (
  <>
    <meta charSet="utf-8" />
    <meta httpEquiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta
      name="description"
      content="Carbon is the easiest way to create and share beautiful images of your source code."
    />
    <meta name="application-name" content="Carbon" />
    <meta name="twitter:title" content="Carbon" />
    <meta
      name="twitter:description"
      content="Carbon is the easiest way to create and share beautiful images of your source code."
    />
    <meta name="og:title" content="Carbon" />
    <meta
      name="og:description"
      content="Carbon is the easiest way to create and share beautiful images of your source code."
    />
    <meta name="og:image" content="/static/banner.png" />
    <meta name="theme-color" content="#121212" />
    <title>Carbon</title>
    <link rel="shortcut icon" href="/static/favicon.ico" />
  </>
)

/*
 * Before supporting <link rel="preload"> verify that it is widely supported in FireFox
 * with out a flag here: https://caniuse.com/#feat=link-rel-preload
 */
export default function Meta() {
  const onBrowser = typeof window !== 'undefined'
  return (

        <MetaTags />
        <link rel="stylesheet" href="/static/react-crop.css" />
        <link rel="manifest" href="/static/manifest.json" />
        <link
          rel="stylesheet"
          href="//cdnjs.cloudflare.com/ajax/libs/codemirror/5.39.2/theme/seti.min.css"
        />
        <CodeMirrorLink />
        <link
          rel="stylesheet"
          href="//cdnjs.cloudflare.com/ajax/libs/codemirror/5.39.2/theme/solarized.min.css"
        />
        {LOCAL_STYLESHEETS.map(id => (
          <link key={id} rel="stylesheet" href={`/static/themes/${id}.css`} />
        ))}
        {onBrowser
          ? CDN_STYLESHEETS.map(theme => (
              <link
                key={theme.id}
                rel="stylesheet"
                href={
                  theme.link ||
                  `//cdnjs.cloudflare.com/ajax/libs/codemirror/5.39.2/theme/${theme.id}.min.css`
                }
              />
            ))
          : null}

      <Reset />

      <Typography />

  )
}
<commit_msg>move manifest to all pages<commit_after>import Head from 'next/head'
import { THEMES } from '../lib/constants'
import Reset from './style/Reset'
import Font from './style/Font'
import Typography from './style/Typography'

export const LOCAL_STYLESHEETS = ['one-dark', 'verminal', 'night-owl', 'nord']

const CDN_STYLESHEETS = THEMES.filter(
  t => t.hasStylesheet !== false && LOCAL_STYLESHEETS.indexOf(t.id) < 0
)

export const CodeMirrorLink = () => (
  <link
    rel="stylesheet"
    href="//cdnjs.cloudflare.com/ajax/libs/codemirror/5.39.2/codemirror.min.css"
  />
)

export const MetaTags = () => (
  <>
    <meta charSet="utf-8" />
    <meta httpEquiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta
      name="description"
      content="Carbon is the easiest way to create and share beautiful images of your source code."
    />
    <meta name="application-name" content="Carbon" />
    <meta name="twitter:title" content="Carbon" />
    <meta
      name="twitter:description"
      content="Carbon is the easiest way to create and share beautiful images of your source code."
    />
    <meta name="og:title" content="Carbon" />
    <meta
      name="og:description"
      content="Carbon is the easiest way to create and share beautiful images of your source code."
    />
    <meta name="og:image" content="/static/banner.png" />
    <meta name="theme-color" content="#121212" />
    <title>Carbon</title>
    <link rel="shortcut icon" href="/static/favicon.ico" />
    <link rel="manifest" href="/static/manifest.json" />
  </>
)

/*
 * Before supporting <link rel="preload"> verify that it is widely supported in FireFox
 * with out a flag here: https://caniuse.com/#feat=link-rel-preload
 */
export default function Meta() {
  const onBrowser = typeof window !== 'undefined'
  return (

        <MetaTags />
        <link rel="stylesheet" href="/static/react-crop.css" />
        <link
          rel="stylesheet"
          href="//cdnjs.cloudflare.com/ajax/libs/codemirror/5.39.2/theme/seti.min.css"
        />
        <CodeMirrorLink />
        <link
          rel="stylesheet"
          href="//cdnjs.cloudflare.com/ajax/libs/codemirror/5.39.2/theme/solarized.min.css"
        />
        {LOCAL_STYLESHEETS.map(id => (
          <link key={id} rel="stylesheet" href={`/static/themes/${id}.css`} />
        ))}
        {onBrowser
          ? CDN_STYLESHEETS.map(theme => (
              <link
                key={theme.id}
                rel="stylesheet"
                href={
                  theme.link ||
                  `//cdnjs.cloudflare.com/ajax/libs/codemirror/5.39.2/theme/${theme.id}.min.css`
                }
              />
            ))
          : null}

      <Reset />

      <Typography />

  )
}
<|endoftext|>


<commit_before>//----------------------------------------------------------------------------
//  Copyright (C) 2012  The IPython Development Team
//
//  Distributed under the terms of the BSD License.  The full license is in
//  the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------

//============================================================================
// CellToolbar Example
//============================================================================

/**
 * Example Use for the CellToolbar library
 * add the following to your custom.js to load
 * Celltoolbar UI for slideshow
 *
 * ```
 * $.getScript('/static/js/examples/celltoolbar.example.js');
 * ```
 */
 // IIFE without asignement, we don't modifiy the IPython namespace
(function (IPython) {
    "use strict";

    var CellToolbar = IPython.CellToolbar;

    var raw_edit = function(cell){

        var md = cell.metadata
        var error_div = $('
').css('color','red')

        var textarea = $('<textarea/>')
            .attr('rows','13')
            .attr('cols','75')
            .attr('name','metadata')
            .text(JSON.stringify(md, null,4)||'');
        var dialogform = $('
').attr('title','Edit the metadata')
            .append(
                $('<form/>').append(
                    $('<fieldset/>').append(
                        $('')
                        .attr('for','metadata')
                        .text("Metadata (I know what I'm dooing and I won't complain if it breaks my notebook)")
                        )
                        .append(error_div)
                        .append($('
'))
                        .append(
                            textarea
                        )
                    )
            );
        var editor = CodeMirror.fromTextArea(textarea[0], {
            lineNumbers: true,
            matchBrackets: true,
        });
        $(dialogform).dialog({
                autoOpen: true,
                height: 300,
                width: 650,
                modal: true,
                buttons: {
                    "Ok": function() {
                        //validate json and set it
                        try {
                           var json = JSON.parse(editor.getValue());
                           cell.metadata = json;
                           $( this ).dialog( "close" );
                        }
                        catch(e)
                        {
                           error_div.text('Warning, invalid json, not saved');
                        }
                    },
                    Cancel: function() {
                        $( this ).dialog( "close" );
                    }
                },
                close: function() {
                    //cleanup on close
                    $(this).remove();
                }
        });
        editor.refresh();
    }

    var add_raw_edit_button = function(div, cell) {
        var button_container = div
        var button = $('
').button({label:'Raw Edit'})
                .click(function(){raw_edit(cell); return false;})
        button_container.append(button);
    }

    CellToolbar.register_callback('example.rawedit',add_raw_edit_button);
    var example_preset = []
    example_preset.push('example.rawedit');

    var simple_button = function(div, cell) {
        var button_container = $(div);
        var button = $('
').button({icons:{primary:'ui-icon-locked'}});
        var fun = function(value){
                try{
                    if(value){
                        cell.code_mirror.setOption('readOnly','nocursor')
                        button.button('option','icons',{primary:'ui-icon-locked'})
                    } else {
                        cell.code_mirror.setOption('readOnly','false')
                        button.button('option','icons',{primary:'ui-icon-unlocked'})
                    }
                } catch(e){}

        }
            fun(cell.metadata.ro)
            button.click(function(){
                    var v = cell.metadata.ro;
                    var locked = !v;
                    cell.metadata.ro = locked;
                    fun(locked)
                    })
                .css('height','16px')
                .css('width','35px');
        button_container.append(button);
    }

    CellToolbar.register_callback('example.lock',simple_button);
    example_preset.push('example.lock');

    var toggle_test =  function(div, cell) {
        var button_container = $(div)
        var button = $('
')
            .button({label:String(cell.metadata.foo)}).
            css('width','65px');
        button.click(function(){
                    var v = cell.metadata.foo;
                    cell.metadata.foo = !v;
                    button.button("option","label",String(!v));
                })
       button_container.append(button);
    }

    CellToolbar.register_callback('example.toggle',toggle_test);
    example_preset.push('example.toggle');

    var checkbox_test = CellToolbar.utils.checkbox_ui_generator('Yes/No',
         // setter
         function(cell, value){
             // we check that the slideshow namespace exist and create it if needed
             if (cell.metadata.yn_test == undefined){cell.metadata.yn_test = {}}
             // set the value
             cell.metadata.yn_test.value = value
             },
         //geter
         function(cell){ var ns = cell.metadata.yn_test;
             // if the slideshow namespace does not exist return `undefined`
             // (will be interpreted as `false` by checkbox) otherwise
             // return the value
             return (ns == undefined)? undefined: ns.value
             }
    );

    CellToolbar.register_callback('example.checkbox',checkbox_test);
    example_preset.push('example.checkbox');

    var select_test = CellToolbar.utils.select_ui_generator([
            ["-"            ,undefined      ],
            ["Header Slide" ,"header_slide" ],
            ["Slide"        ,"slide"        ],
            ["Fragment"     ,"fragment"     ],
            ["Skip"         ,"skip"         ],
            ],
            // setter
            function(cell,value){
                // we check that the slideshow namespace exist and create it if needed
                if (cell.metadata.test == undefined){cell.metadata.test = {}}
                // set the value
                cell.metadata.test.slide_type = value
                },
            //geter
            function(cell){ var ns = cell.metadata.test;
                // if the slideshow namespace does not exist return `undefined`
                // (will be interpreted as `false` by checkbox) otherwise
                // return the value
                return (ns == undefined)? undefined: ns.slide_type
                });

    CellToolbar.register_callback('example.select',select_test);
    example_preset.push('example.select');

    var simple_dialog = function(title,text){
        var dlg = $('
').attr('title',title)
            .append($('
').text(text))
        $(dlg).dialog({
                autoOpen: true,
                height: 300,
                width: 650,
                modal: true,
                close: function() {
                    //cleanup on close
                    $(this).remove();
                }
        });
    }

    var add_simple_dialog_button = function(div, cell) {
        var help_text = ["This is the Metadata editting UI.",
                         "It heavily rely on plugin to work ",
                         "and is still under developpement. You shouldn't wait too long before",
                         " seeing some customisable buttons in those toolbar."
                        ].join('\n')
        var button_container = $(div)
        var button = $('
').button({label:'?'})
                .click(function(){simple_dialog('help',help_text); return false;})
        button_container.append(button);
    }

    CellToolbar.register_callback('example.help',add_simple_dialog_button)
    example_preset.push('example.help')

    CellToolbar.register_preset('example',example_preset);
    console.log('Example extension for metadata editting loaded.');

}(IPython));
<commit_msg>fix lock cell button<commit_after>//----------------------------------------------------------------------------
//  Copyright (C) 2012  The IPython Development Team
//
//  Distributed under the terms of the BSD License.  The full license is in
//  the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------

//============================================================================
// CellToolbar Example
//============================================================================

/**
 * Example Use for the CellToolbar library
 * add the following to your custom.js to load
 * Celltoolbar UI for slideshow
 *
 * ```
 * $.getScript('/static/js/examples/celltoolbar.example.js');
 * ```
 */
 // IIFE without asignement, we don't modifiy the IPython namespace
(function (IPython) {
    "use strict";

    var CellToolbar = IPython.CellToolbar;

    var raw_edit = function(cell){

        var md = cell.metadata
        var error_div = $('
').css('color','red')

        var textarea = $('<textarea/>')
            .attr('rows','13')
            .attr('cols','75')
            .attr('name','metadata')
            .text(JSON.stringify(md, null,4)||'');
        var dialogform = $('
').attr('title','Edit the metadata')
            .append(
                $('<form/>').append(
                    $('<fieldset/>').append(
                        $('')
                        .attr('for','metadata')
                        .text("Metadata (I know what I'm dooing and I won't complain if it breaks my notebook)")
                        )
                        .append(error_div)
                        .append($('
'))
                        .append(
                            textarea
                        )
                    )
            );
        var editor = CodeMirror.fromTextArea(textarea[0], {
            lineNumbers: true,
            matchBrackets: true,
        });
        $(dialogform).dialog({
                autoOpen: true,
                height: 300,
                width: 650,
                modal: true,
                buttons: {
                    "Ok": function() {
                        //validate json and set it
                        try {
                           var json = JSON.parse(editor.getValue());
                           cell.metadata = json;
                           $( this ).dialog( "close" );
                        }
                        catch(e)
                        {
                           error_div.text('Warning, invalid json, not saved');
                        }
                    },
                    Cancel: function() {
                        $( this ).dialog( "close" );
                    }
                },
                close: function() {
                    //cleanup on close
                    $(this).remove();
                }
        });
        editor.refresh();
    }

    var add_raw_edit_button = function(div, cell) {
        var button_container = div
        var button = $('
').button({label:'Raw Edit'})
                .click(function(){raw_edit(cell); return false;})
        button_container.append(button);
    }

    CellToolbar.register_callback('example.rawedit',add_raw_edit_button);
    var example_preset = []
    example_preset.push('example.rawedit');

    var simple_button = function(div, cell) {
        var button_container = $(div);
        var button = $('
').button({icons:{primary:'ui-icon-locked'}});
        var fun = function(value){
                try{
                    if(value){
                        cell.code_mirror.setOption('readOnly','nocursor')
                        button.button('option','icons',{primary:'ui-icon-locked'})
                    } else {
                        cell.code_mirror.setOption('readOnly',false)
                        button.button('option','icons',{primary:'ui-icon-unlocked'})
                    }
                } catch(e){}

        }
            fun(cell.metadata.ro)
            button.click(function(){
                    var v = cell.metadata.ro;
                    var locked = !v;
                    cell.metadata.ro = locked;
                    fun(locked)
                    })
                .css('height','16px')
                .css('width','35px');
        button_container.append(button);
    }

    CellToolbar.register_callback('example.lock',simple_button);
    example_preset.push('example.lock');

    var toggle_test =  function(div, cell) {
        var button_container = $(div)
        var button = $('
')
            .button({label:String(cell.metadata.foo)}).
            css('width','65px');
        button.click(function(){
                    var v = cell.metadata.foo;
                    cell.metadata.foo = !v;
                    button.button("option","label",String(!v));
                })
       button_container.append(button);
    }

    CellToolbar.register_callback('example.toggle',toggle_test);
    example_preset.push('example.toggle');

    var checkbox_test = CellToolbar.utils.checkbox_ui_generator('Yes/No',
         // setter
         function(cell, value){
             // we check that the slideshow namespace exist and create it if needed
             if (cell.metadata.yn_test == undefined){cell.metadata.yn_test = {}}
             // set the value
             cell.metadata.yn_test.value = value
             },
         //geter
         function(cell){ var ns = cell.metadata.yn_test;
             // if the slideshow namespace does not exist return `undefined`
             // (will be interpreted as `false` by checkbox) otherwise
             // return the value
             return (ns == undefined)? undefined: ns.value
             }
    );

    CellToolbar.register_callback('example.checkbox',checkbox_test);
    example_preset.push('example.checkbox');

    var select_test = CellToolbar.utils.select_ui_generator([
            ["-"            ,undefined      ],
            ["Header Slide" ,"header_slide" ],
            ["Slide"        ,"slide"        ],
            ["Fragment"     ,"fragment"     ],
            ["Skip"         ,"skip"         ],
            ],
            // setter
            function(cell,value){
                // we check that the slideshow namespace exist and create it if needed
                if (cell.metadata.test == undefined){cell.metadata.test = {}}
                // set the value
                cell.metadata.test.slide_type = value
                },
            //geter
            function(cell){ var ns = cell.metadata.test;
                // if the slideshow namespace does not exist return `undefined`
                // (will be interpreted as `false` by checkbox) otherwise
                // return the value
                return (ns == undefined)? undefined: ns.slide_type
                });

    CellToolbar.register_callback('example.select',select_test);
    example_preset.push('example.select');

    var simple_dialog = function(title,text){
        var dlg = $('
').attr('title',title)
            .append($('
').text(text))
        $(dlg).dialog({
                autoOpen: true,
                height: 300,
                width: 650,
                modal: true,
                close: function() {
                    //cleanup on close
                    $(this).remove();
                }
        });
    }

    var add_simple_dialog_button = function(div, cell) {
        var help_text = ["This is the Metadata editting UI.",
                         "It heavily rely on plugin to work ",
                         "and is still under developpement. You shouldn't wait too long before",
                         " seeing some customisable buttons in those toolbar."
                        ].join('\n')
        var button_container = $(div)
        var button = $('
').button({label:'?'})
                .click(function(){simple_dialog('help',help_text); return false;})
        button_container.append(button);
    }

    CellToolbar.register_callback('example.help',add_simple_dialog_button)
    example_preset.push('example.help')

    CellToolbar.register_preset('example',example_preset);
    console.log('Example extension for metadata editting loaded.');

}(IPython));
<|endoftext|>


<commit_before>/** For conditions of distribution and use, see copyright notice in LICENSE

    Test.js - Demo scene for profiling object movement replication. */

// Number of boxes = numRows x numColumns
var numRows = 100;
var numColums = 10;
var boxes = []; // All the created boxes are stored here.
var startPositions = [];
var destinationPositions = [];
var moveTimer = 0;
var dirChangeFreq = 2; // seconds

function OnScriptDestroyed()
{
    DeleteBoxes();
}

// Entry point for the script.
if (server.IsAboutToStart())
{
    CreateBoxes();
    frame.Updated.connect(MoveBoxes);
}

function DeleteBoxes()
{
    for(var i = 0; i < boxes.length; ++i)
        try
        {
            scene.RemoveEntity(boxes[i].id);
        }
        catch(e)
        {
            // We end up here when quitting the app.
            //console.LogWarning(e);
        }
}

function CreateBoxes()
{
    for(var i = 0; i < numRows; ++i)
        for(var j = 0; j < numColums; ++j)
        {
            var box = scene.CreateEntity(scene.NextFreeId(), ["EC_Name", "EC_Mesh", "EC_Placeable"]);
            box.name = "Box" + i.toString() + j.toString();

            var meshRef = box.mesh.meshRef;
            meshRef.ref = "Box.mesh";
            box.mesh.meshRef = meshRef;

            var matRefs = new AssetReferenceList();
            matRefs = [ "Box.material" ];
            box.mesh.meshMaterial = matRefs;

            box.placeable.SetScale(new float3(5, 5, 5));
            box.placeable.SetPosition(new float3(6*i, 0, 6*j));
            boxes.push(box);

            // Save initial destination points.
            var pos = box.placeable.transform.pos;
            var dest = new float3(pos);
            dest.y = (Math.random() > 0.5) ? -2 : 2;
            startPositions.push(pos);
            destinationPositions.push(dest);
        }

    console.LogInfo("CreateBoxes: " + boxes.length + " boxes created.");
}

function MoveBoxes(frameTime)
{
    profiler.BeginBlock("MoveBoxes");

    moveTimer += frameTime;
    if (moveTimer > dirChangeFreq)
        moveTimer = 0;

    for(var i = 0; i < boxes.length; ++i)
    {
        var box = boxes[i];
        var currentPos = box.placeable.transform.pos;
        var dest = destinationPositions[i];

        if (moveTimer == 0)
        {
            startPositions[i] = currentPos;
            destinationPositions[i].y = -destinationPositions[i].y;
        }

        currentPos = float3.Lerp(startPositions[i], destinationPositions[i], moveTimer/dirChangeFreq);
        box.placeable.SetPosition(currentPos);
    }

    profiler.EndBlock();
}
<commit_msg>EntityMoveTest - create 100 boxes by default.<commit_after>/** For conditions of distribution and use, see copyright notice in LICENSE

    EntityMoveTest.js - Demo scene for profiling object movement replication. */

// Number of boxes = numRows x numColumns
var numRows = 10;
var numColums = 10;
var boxes = []; // All the created boxes are stored here.
var startPositions = [];
var destinationPositions = [];
var moveTimer = 0;
var dirChangeFreq = 2; // seconds

function OnScriptDestroyed()
{
    DeleteBoxes();
}

// Entry point for the script.
if (server.IsAboutToStart())
{
    CreateBoxes();
    frame.Updated.connect(MoveBoxes);
}

function DeleteBoxes()
{
    for(var i = 0; i < boxes.length; ++i)
        try
        {
            scene.RemoveEntity(boxes[i].id);
        }
        catch(e)
        {
            // We end up here when quitting the app.
            //console.LogWarning(e);
        }
}

function CreateBoxes()
{
    for(var i = 0; i < numRows; ++i)
        for(var j = 0; j < numColums; ++j)
        {
            var box = scene.CreateEntity(scene.NextFreeId(), ["EC_Name", "EC_Mesh", "EC_Placeable"]);
            box.name = "Box" + i.toString() + j.toString();

            var meshRef = box.mesh.meshRef;
            meshRef.ref = "Box.mesh";
            box.mesh.meshRef = meshRef;

            var matRefs = new AssetReferenceList();
            matRefs = [ "Box.material" ];
            box.mesh.meshMaterial = matRefs;

            box.placeable.SetScale(new float3(5, 5, 5));
            box.placeable.SetPosition(new float3(6*i, 0, 6*j));
            boxes.push(box);

            // Save initial destination points.
            var pos = box.placeable.transform.pos;
            var dest = new float3(pos);
            dest.y = (Math.random() > 0.5) ? -2 : 2;
            startPositions.push(pos);
            destinationPositions.push(dest);
        }

    console.LogInfo("CreateBoxes: " + boxes.length + " boxes created.");
}

function MoveBoxes(frameTime)
{
    profiler.BeginBlock("MoveBoxes");

    moveTimer += frameTime;
    if (moveTimer > dirChangeFreq)
        moveTimer = 0;

    for(var i = 0; i < boxes.length; ++i)
    {
        var box = boxes[i];
        var currentPos = box.placeable.transform.pos;
        var dest = destinationPositions[i];

        if (moveTimer == 0)
        {
            startPositions[i] = currentPos;
            destinationPositions[i].y = -destinationPositions[i].y;
        }

        currentPos = float3.Lerp(startPositions[i], destinationPositions[i], moveTimer/dirChangeFreq);
        box.placeable.SetPosition(currentPos);
    }

    profiler.EndBlock();
}
<|endoftext|>


<commit_before>var Binding = require('../binding')
var Observer = require('../observe/observer')

/**
 * Setup the binding tree.
 *
 * Bindings form a tree-like structure that maps the Object structure
 * of observed data. However, only paths present in the templates are
 * created in the binding tree. When a change event from the data
 * observer arrives on the instance, we traverse the binding tree
 * along the changed path, triggering binding updates along the way.
 * When we reach the path endpoint, if it has any children, we also
 * trigger updates on the entire sub-tree.
 *
 * Each instance has a root binding and it has three special children:
 * `$data`, `$parent` & `$root`. `$data` points to the root binding
 * itself. `$parent` and `$root` point to the instance's parent and
 * root's root bindings, respectively.
 */

exports._initBindings = function () {
  var root = this._rootBinding = new Binding()
  // the $data binding points to the root itself!
  root.addChild('$data', root)
  // point $parent and $root bindings to their
  // repective owners.
  if (this.$parent) {
    root.addChild('$parent', this.$parent._rootBinding)
    root.addChild('$root', this.$root._rootBinding)
  }
  var self = this
  var updateBinding = function (path) {
    self._updateBinding(path)
  }
  this._observer
    .on('set', updateBinding)
    .on('add', updateBinding)
    .on('delete', updateBinding)
    .on('mutate', updateBinding)
}

/**
 * Create a binding for a given path, and create necessary
 * parent bindings along the path. Returns the binding at
 * the end of the path.
 *
 * @param {Array} path - this should already be a parsed Array.
 * @return {Binding} - the binding created/retrieved at the destination.
 */

exports._createBindingAt = function (path) {
  var b = this._rootBinding
  var child, key
  for (var i = 0, l = path.length; i < l; i++) {
    key = path[i]
    child = b.getChild(key) || b.addChild(key)
    b = child
  }
  return b
}

/**
 * Trigger a path update on the root binding.
 *
 * @param {String} path - this path comes directly from the
 *                        data observer, so it is a single string
 *                        delimited by "\b".
 */

exports._updateBinding = function (path) {
  path = path.split(Observer.pathDelimiter)
  this._rootBinding.updatePath(path)
}<commit_msg>callback context<commit_after>var Binding = require('../binding')
var Observer = require('../observe/observer')

/**
 * Setup the binding tree.
 *
 * Bindings form a tree-like structure that maps the Object structure
 * of observed data. However, only paths present in the templates are
 * created in the binding tree. When a change event from the data
 * observer arrives on the instance, we traverse the binding tree
 * along the changed path, triggering binding updates along the way.
 * When we reach the path endpoint, if it has any children, we also
 * trigger updates on the entire sub-tree.
 *
 * Each instance has a root binding and it has three special children:
 * `$data`, `$parent` & `$root`. `$data` points to the root binding
 * itself. `$parent` and `$root` point to the instance's parent and
 * root's root bindings, respectively.
 */

exports._initBindings = function () {
  var root = this._rootBinding = new Binding()
  // the $data binding points to the root itself!
  root.addChild('$data', root)
  // point $parent and $root bindings to their
  // repective owners.
  if (this.$parent) {
    root.addChild('$parent', this.$parent._rootBinding)
    root.addChild('$root', this.$root._rootBinding)
  }
  // observer already has callback context set to `this`
  var updateBinding = this._updateBinding
  this._observer
    .on('set', updateBinding)
    .on('add', updateBinding)
    .on('delete', updateBinding)
    .on('mutate', updateBinding)
}

/**
 * Create a binding for a given path, and create necessary
 * parent bindings along the path. Returns the binding at
 * the end of the path.
 *
 * @param {Array} path - this should already be a parsed Array.
 * @return {Binding} - the binding created/retrieved at the destination.
 */

exports._createBindingAt = function (path) {
  var b = this._rootBinding
  var child, key
  for (var i = 0, l = path.length; i < l; i++) {
    key = path[i]
    child = b.getChild(key) || b.addChild(key)
    b = child
  }
  return b
}

/**
 * Trigger a path update on the root binding.
 *
 * @param {String} path - this path comes directly from the
 *                        data observer, so it is a single string
 *                        delimited by "\b".
 */

exports._updateBinding = function (path) {
  path = path.split(Observer.pathDelimiter)
  this._rootBinding.updatePath(path)
}<|endoftext|>


<commit_before>var kue = require('kue')
  , jobs = kue.createQueue();

var Twitter = require('node-tweet-stream')
  , t = new Twitter({
    consumer_key: process.env.TWITTER,
    consumer_secret: process.env.TWITTER_SECRET,
    token: process.env.TWITTER_OATH,
    token_secret: process.env.TWITTER_OATH_SECRET
  })

t.on('tweet', function (tweet) {
    var job = jobs.create('tweet', tweet).save( function(err){
       if( !err ) console.log( job.id );
    });
})

t.on('error', function (err) {
  console.log('Oh no')
})

t.track('#celebratenvrd')
t.track('#govote')
t.track('#imregistered')
<commit_msg>Add kue config to tweets<commit_after>var kue = require('kue')
  , jobs = kue.createQueue();

kue.redis.createClient = function() {
    var redisUrl = url.parse(process.env.REDISTOGO_URL)
    var client = redis.createClient(redisUrl.port, redisUrl.hostname)

    if (redisUrl.auth) {
        client.auth(redisUrl.auth.split(":")[1]);
    }

    return client;
}

var Twitter = require('node-tweet-stream')
  , t = new Twitter({
    consumer_key: process.env.TWITTER,
    consumer_secret: process.env.TWITTER_SECRET,
    token: process.env.TWITTER_OATH,
    token_secret: process.env.TWITTER_OATH_SECRET
  })

t.on('tweet', function (tweet) {
    var job = jobs.create('tweet', tweet).save( function(err){
       if( !err ) console.log( job.id );
    });
})

t.on('error', function (err) {
  console.log('Oh no')
})

t.track('#celebratenvrd')
t.track('#govote')
t.track('#imregistered')
<|endoftext|>