<commit_before>angular.module("umbraco.directives")
    .directive('gridRte', function (tinyMceService, stylesheetResource, angularHelper, assetsService, $q, $timeout) {
        return {
            scope: {
                uniqueId: '=',
                value: '=',
                onClick: '&',
                onFocus: '&',
                onBlur: '&',
                configuration:"="
            },
            template: "<textarea ng-model=\"value\" rows=\"10\" class=\"mceNoEditor\" style=\"overflow:hidden\" id=\"{{uniqueId}}\"></textarea>",
            replace: true,
            link: function (scope, element, attrs) {

                var initTiny = function () {

                    //we always fetch the default one, and then override parts with our own
                    tinyMceService.configuration().then(function (tinyMceConfig) {

                        //config value from general tinymce.config file
                        var validElements = tinyMceConfig.validElements;
                        var fallbackStyles = [{title: "Page header", block: "h2"}, {title: "Section header", block: "h3"}, {title: "Paragraph header", block: "h4"}, {title: "Normal", block: "p"}, {title: "Quote", block: "blockquote"}, {title: "Code", block: "code"}];

                        //These are absolutely required in order for the macros to render inline
                        //we put these as extended elements because they get merged on top of the normal allowed elements by tiny mce
                        var extendedValidElements = "@[id|class|style],-div[id|dir|class|align|style],ins[datetime|cite],-ul[class|style],-li[class|style],-h1[id|dir|class|align|style],-h2[id|dir|class|align|style],-h3[id|dir|class|align|style],-h4[id|dir|class|align|style],-h5[id|dir|class|align|style],-h6[id|style|dir|class|align]";

                        var invalidElements = tinyMceConfig.inValidElements;
                        var plugins = _.map(tinyMceConfig.plugins, function (plugin) {
                            if (plugin.useOnFrontend) {
                                return plugin.name;
                            }
                        }).join(" ") + " autoresize";

                        //config value on the data type
                        var toolbar = ["code", "styleselect", "bold", "italic", "alignleft", "aligncenter", "alignright", "bullist", "numlist", "link", "umbmediapicker", "umbembeddialog"].join(" | ");
                        var stylesheets = [];

                        var styleFormats = [];
                        var await = [];

                        //queue file loading
                        if (typeof (tinymce) === "undefined") {
                                await.push(assetsService.loadJs("lib/tinymce/tinymce.min.js", scope));
                        }

                        if(scope.configuration && scope.configuration.toolbar){
                            toolbar = scope.configuration.toolbar.join(' | ');
                        }

                        if(scope.configuration && scope.configuration.stylesheets){
                            angular.forEach(scope.configuration.stylesheets, function(stylesheet, key){

                                    stylesheets.push("/css/" + stylesheet + ".css");
                                    await.push(stylesheetResource.getRulesByName(stylesheet).then(function (rules) {
                                        angular.forEach(rules, function (rule) {
                                          var r = {};
                                          r.title = rule.name;
                                          if (rule.selector[0] === ".") {
                                              r.inline = "span";
                                              r.classes = rule.selector.substring(1);
                                          }else if (rule.selector[0] === "#") {
                                              r.inline = "span";
                                              r.attributes = { id: rule.selector.substring(1) };
                                          }else {
                                              r.block = rule.selector;
                                          }
                                          styleFormats.push(r);
                                        });
                                    }));
                            });
                        }else{
                            stylesheets.push("views/propertyeditors/grid/config/grid.default.rtestyles.css");
                            styleFormats = fallbackStyles;
                        }

                        //stores a reference to the editor
                        var tinyMceEditor = null;
                        $q.all(await).then(function () {

                            var uniqueId = scope.uniqueId;

                            //create a baseline Config to exten upon
                            var baseLineConfigObj = {
                                mode: "exact",
                                skin: "umbraco",
                                plugins: plugins,
                                valid_elements: validElements,
                                invalid_elements: invalidElements,
                                extended_valid_elements: extendedValidElements,
                                menubar: false,
                                statusbar: false,
                                relative_urls: false,
                                toolbar: toolbar,
                                content_css: stylesheets.join(','),
                                style_formats: styleFormats
                            };

                            if (tinyMceConfig.customConfig) {
                                angular.extend(baseLineConfigObj, tinyMceConfig.customConfig);
                            }

                            //set all the things that user configs should not be able to override
                            baseLineConfigObj.elements = uniqueId;
                            baseLineConfigObj.setup = function (editor) {

                                //set the reference
                                tinyMceEditor = editor;

                                //enable browser based spell checking
                                editor.on('init', function (e) {

                                    editor.getBody().setAttribute('spellcheck', true);

                                    //hide toolbar by default
                                    $(editor.editorContainer)
                                        .find(".mce-toolbar")
                                        .css("visibility", "hidden");

                                    //force overflow to hidden to prevent no needed scroll
                                    editor.getBody().style.overflow = "hidden";

                                    $timeout(function(){
                                        if(scope.value === null){
                                            editor.focus();
                                        }
                                    }, 400);

                                });

                                //when we leave the editor (maybe)
                                editor.on('blur', function (e) {
                                    editor.save();
                                    angularHelper.safeApply(scope, function () {
                                        scope.value = editor.getContent();

                                        var _toolbar = $(editor.editorContainer)
                                             .find(".mce-toolbar");

                                        if(scope.onBlur){
                                            scope.onBlur();
                                        }

                                        _toolbar.css("visibility", "hidden");
                                    });
                                });

                                // Focus on editor
                                editor.on('focus', function (e) {
                                    angularHelper.safeApply(scope, function () {

                                        var _toolbar = $(editor.editorContainer)
                                             .find(".mce-toolbar");

                                        if(scope.onFocus){
                                            scope.onFocus();
                                        }

                                        var toolbarHeight = -_toolbar.height() - 2;
                                        _toolbar
                                            .css("visibility", "visible")
                                            .css("margin-top", toolbarHeight + "px");
                                    });
                                });

                                // Click on editor
                                editor.on('click', function (e) {
                                    angularHelper.safeApply(scope, function () {

                                        var _toolbar = $(editor.editorContainer)
                                             .find(".mce-toolbar");

                                        if(scope.onClick){
                                            scope.onClick();
                                        }

                                        var toolbarHeight = -_toolbar.height() - 2;
                                        _toolbar
                                            .css("visibility", "visible")
                                            .css("margin-top", toolbarHeight + "px");
                                    });
                                });

                                //when buttons modify content
                                editor.on('ExecCommand', function (e) {
                                    editor.save();
                                    angularHelper.safeApply(scope, function () {
                                        scope.value = editor.getContent();
                                    });
                                });

                                // Update model on keypress
                                editor.on('KeyUp', function (e) {
                                    editor.save();
                                    angularHelper.safeApply(scope, function () {
                                        scope.value = editor.getContent();
                                    });
                                });

                                // Update model on change, i.e. copy/pasted text, plugins altering content
                                editor.on('SetContent', function (e) {
                                    if (!e.initial) {
                                        editor.save();
                                        angularHelper.safeApply(scope, function () {
                                            scope.value = editor.getContent();
                                        });
                                    }
                                });

                                editor.on('ObjectResized', function (e) {
                                    var qs = "?width=" + e.width + "px&height=" + e.height + "px";
                                    var srcAttr = $(e.target).attr("src");
                                    var path = srcAttr.split("?")[0];
                                    $(e.target).attr("data-mce-src", path + qs);
                                });

                                //Create the insert media plugin
                                tinyMceService.createMediaPicker(editor, scope);

                                //Create the embedded plugin
                                tinyMceService.createInsertEmbeddedMedia(editor, scope);

                                //Create the insert link plugin
                                //tinyMceService.createLinkPicker(editor, scope);

                                //Create the insert macro plugin
                                tinyMceService.createInsertMacro(editor, scope);

                            };

                            /** Loads in the editor */
                            function loadTinyMce() {

                                //we need to add a timeout here, to force a redraw so TinyMCE can find
                                //the elements needed
                                $timeout(function () {
                                    tinymce.DOM.events.domLoaded = true;
                                    tinymce.init(baseLineConfigObj);
                                }, 150, false);
                            }

                            loadTinyMce();

                            //here we declare a special method which will be called whenever the value has changed from the server
                            //this is instead of doing a watch on the model.value = faster
                            //scope.model.onValueChanged = function (newVal, oldVal) {
                            //    //update the display val again if it has changed from the server;
                            //    tinyMceEditor.setContent(newVal, { format: 'raw' });
                            //    //we need to manually fire this event since it is only ever fired based on loading from the DOM, this
                            //    // is required for our plugins listening to this event to execute
                            //    tinyMceEditor.fire('LoadContent', null);
                            //};

                            //listen for formSubmitting event (the result is callback used to remove the event subscription)
                            var unsubscribe = scope.$on("formSubmitting", function () {
                                //TODO: Here we should parse out the macro rendered content so we can save on a lot of bytes in data xfer
                                // we do parse it out on the server side but would be nice to do that on the client side before as well.
                                scope.value = tinyMceEditor.getContent();
                            });

                            //when the element is disposed we need to unsubscribe!
                            // NOTE: this is very important otherwise if this is part of a modal, the listener still exists because the dom
                            // element might still be there even after the modal has been hidden.
                            scope.$on('$destroy', function () {
                                unsubscribe();
                            });

                        });

                    });

                };

                initTiny();

            }
        };
    });
<commit_msg>U4-6288 Changes<commit_after>angular.module("umbraco.directives")
    .directive('gridRte', function (tinyMceService, stylesheetResource, angularHelper, assetsService, $q, $timeout) {
        return {
            scope: {
                uniqueId: '=',
                value: '=',
                onClick: '&',
                onFocus: '&',
                onBlur: '&',
                configuration:"="
            },
            template: "<textarea ng-model=\"value\" rows=\"10\" class=\"mceNoEditor\" style=\"overflow:hidden\" id=\"{{uniqueId}}\"></textarea>",
            replace: true,
            link: function (scope, element, attrs) {

                var initTiny = function () {

                    //we always fetch the default one, and then override parts with our own
                    tinyMceService.configuration().then(function (tinyMceConfig) {

                        //config value from general tinymce.config file
                        var validElements = tinyMceConfig.validElements;
                        var fallbackStyles = [{title: "Page header", block: "h2"}, {title: "Section header", block: "h3"}, {title: "Paragraph header", block: "h4"}, {title: "Normal", block: "p"}, {title: "Quote", block: "blockquote"}, {title: "Code", block: "code"}];

                        //These are absolutely required in order for the macros to render inline
                        //we put these as extended elements because they get merged on top of the normal allowed elements by tiny mce
                        var extendedValidElements = "@[id|class|style],-div[id|dir|class|align|style],ins[datetime|cite],-ul[class|style],-li[class|style],-h1[id|dir|class|align|style],-h2[id|dir|class|align|style],-h3[id|dir|class|align|style],-h4[id|dir|class|align|style],-h5[id|dir|class|align|style],-h6[id|style|dir|class|align]";

                        var invalidElements = tinyMceConfig.inValidElements;
                        var plugins = _.map(tinyMceConfig.plugins, function (plugin) {
                            if (plugin.useOnFrontend) {
                                return plugin.name;
                            }
                        }).join(" ") + " autoresize";

                        //config value on the data type
                        var toolbar = ["code", "styleselect", "bold", "italic", "alignleft", "aligncenter", "alignright", "bullist", "numlist", "link", "umbmediapicker", "umbembeddialog"].join(" | ");
                        var stylesheets = [];

                        var styleFormats = [];
                        var await = [];

                        //queue file loading
                        if (typeof (tinymce) === "undefined") {
                                await.push(assetsService.loadJs("lib/tinymce/tinymce.min.js", scope));
                        }

                        if(scope.configuration && scope.configuration.toolbar){
                            toolbar = scope.configuration.toolbar.join(' | ');
                        }

                        if(scope.configuration && scope.configuration.stylesheets){
                            angular.forEach(scope.configuration.stylesheets, function(stylesheet, key){

                                    stylesheets.push("/css/" + stylesheet + ".css");
                                    await.push(stylesheetResource.getRulesByName(stylesheet).then(function (rules) {
                                        angular.forEach(rules, function (rule) {
                                          var r = {};
                                          r.title = rule.name;
                                          if (rule.selector[0] === ".") {
                                              r.inline = "span";
                                              r.classes = rule.selector.substring(1);
                                          }else if (rule.selector[0] === "#") {
                                              r.inline = "span";
                                              r.attributes = { id: rule.selector.substring(1) };
                                          }else {
                                              r.block = rule.selector;
                                          }
                                          styleFormats.push(r);
                                        });
                                    }));
                            });
                        }else{
                            stylesheets.push("views/propertyeditors/grid/config/grid.default.rtestyles.css");
                            styleFormats = fallbackStyles;
                        }

                        //stores a reference to the editor
                        var tinyMceEditor = null;
                        $q.all(await).then(function () {

                            var uniqueId = scope.uniqueId;

                            //create a baseline Config to exten upon
                            var baseLineConfigObj = {
                                mode: "exact",
                                skin: "umbraco",
                                plugins: plugins,
                                valid_elements: validElements,
                                invalid_elements: invalidElements,
                                extended_valid_elements: extendedValidElements,
                                menubar: false,
                                statusbar: false,
                                relative_urls: false,
                                toolbar: toolbar,
                                content_css: stylesheets.join(','),
                                style_formats: styleFormats
                            };

                            if (tinyMceConfig.customConfig) {
                                angular.extend(baseLineConfigObj, tinyMceConfig.customConfig);
                            }

                            //set all the things that user configs should not be able to override
                            baseLineConfigObj.elements = uniqueId;
                            baseLineConfigObj.setup = function (editor) {

                                //set the reference
                                tinyMceEditor = editor;

                                //enable browser based spell checking
                                editor.on('init', function (e) {

                                    editor.getBody().setAttribute('spellcheck', true);

                                    //hide toolbar by default
                                    $(editor.editorContainer)
                                        .find(".mce-toolbar")
                                        .css("visibility", "hidden");

                                    //force overflow to hidden to prevent no needed scroll
                                    editor.getBody().style.overflow = "hidden";

                                    $timeout(function(){
                                        if(scope.value === null){
                                            editor.focus();
                                        }
                                    }, 400);

                                });

                                // pin toolbar to top of screen if we have focus and it scrolls off the screen
                                var pinToolbar = function () {

                                    var _toolbar = $(editor.editorContainer).find(".mce-toolbar");
                                    var toolbarHeight = _toolbar.height();

                                    var _tinyMce = $(editor.editorContainer);
                                    var tinyMceRect = _tinyMce[0].getBoundingClientRect();
                                    var tinyMceTop = tinyMceRect.top;
                                    var tinyMceBottom = tinyMceRect.bottom;

                                    if (tinyMceTop < 100 && (tinyMceBottom > (100 + toolbarHeight))) {
                                        _toolbar
                                            .css("visibility", "visible")
                                            .css("position", "fixed")
                                            .css("top", "100px")
                                            .css("margin-top", "0");
                                    } else {
                                        _toolbar
                                            .css("visibility", "visible")
                                            .css("position", "absolute")
                                            .css("top", "auto")
                                            .css("margin-top", (-toolbarHeight - 2) + "px");
                                    }
                                };

                                //when we leave the editor (maybe)
                                editor.on('blur', function (e) {
                                    editor.save();
                                    angularHelper.safeApply(scope, function () {
                                        scope.value = editor.getContent();

                                        var _toolbar = $(editor.editorContainer)
                                             .find(".mce-toolbar");

                                        if(scope.onBlur){
                                            scope.onBlur();
                                        }

                                        _toolbar.css("visibility", "hidden");
                                        $('.umb-panel-body').off('scroll', pinToolbar);
                                    });
                                });

                                // Focus on editor
                                editor.on('focus', function (e) {
                                    angularHelper.safeApply(scope, function () {

                                        if(scope.onFocus){
                                            scope.onFocus();
                                        }

                                        pinToolbar();
                                        $('.umb-panel-body').on('scroll', pinToolbar);
                                    });
                                });

                                // Click on editor
                                editor.on('click', function (e) {
                                    angularHelper.safeApply(scope, function () {

                                        if(scope.onClick){
                                            scope.onClick();
                                        }

                                        pinToolbar();
                                        $('.umb-panel-body').on('scroll', pinToolbar);
                                    });
                                });

                                //when buttons modify content
                                editor.on('ExecCommand', function (e) {
                                    editor.save();
                                    angularHelper.safeApply(scope, function () {
                                        scope.value = editor.getContent();
                                    });
                                });

                                // Update model on keypress
                                editor.on('KeyUp', function (e) {
                                    editor.save();
                                    angularHelper.safeApply(scope, function () {
                                        scope.value = editor.getContent();
                                    });
                                });

                                // Update model on change, i.e. copy/pasted text, plugins altering content
                                editor.on('SetContent', function (e) {
                                    if (!e.initial) {
                                        editor.save();
                                        angularHelper.safeApply(scope, function () {
                                            scope.value = editor.getContent();
                                        });
                                    }
                                });

                                editor.on('ObjectResized', function (e) {
                                    var qs = "?width=" + e.width + "px&height=" + e.height + "px";
                                    var srcAttr = $(e.target).attr("src");
                                    var path = srcAttr.split("?")[0];
                                    $(e.target).attr("data-mce-src", path + qs);
                                });

                                //Create the insert media plugin
                                tinyMceService.createMediaPicker(editor, scope);

                                //Create the embedded plugin
                                tinyMceService.createInsertEmbeddedMedia(editor, scope);

                                //Create the insert link plugin
                                //tinyMceService.createLinkPicker(editor, scope);

                                //Create the insert macro plugin
                                tinyMceService.createInsertMacro(editor, scope);

                            };

                            /** Loads in the editor */
                            function loadTinyMce() {

                                //we need to add a timeout here, to force a redraw so TinyMCE can find
                                //the elements needed
                                $timeout(function () {
                                    tinymce.DOM.events.domLoaded = true;
                                    tinymce.init(baseLineConfigObj);
                                }, 150, false);
                            }

                            loadTinyMce();

                            //here we declare a special method which will be called whenever the value has changed from the server
                            //this is instead of doing a watch on the model.value = faster
                            //scope.model.onValueChanged = function (newVal, oldVal) {
                            //    //update the display val again if it has changed from the server;
                            //    tinyMceEditor.setContent(newVal, { format: 'raw' });
                            //    //we need to manually fire this event since it is only ever fired based on loading from the DOM, this
                            //    // is required for our plugins listening to this event to execute
                            //    tinyMceEditor.fire('LoadContent', null);
                            //};

                            //listen for formSubmitting event (the result is callback used to remove the event subscription)
                            var unsubscribe = scope.$on("formSubmitting", function () {
                                //TODO: Here we should parse out the macro rendered content so we can save on a lot of bytes in data xfer
                                // we do parse it out on the server side but would be nice to do that on the client side before as well.
                                scope.value = tinyMceEditor.getContent();
                            });

                            //when the element is disposed we need to unsubscribe!
                            // NOTE: this is very important otherwise if this is part of a modal, the listener still exists because the dom
                            // element might still be there even after the modal has been hidden.
                            scope.$on('$destroy', function () {
                                unsubscribe();
                            });

                        });

                    });

                };

                initTiny();

            }
        };
    });
<|endoftext|>


<commit_before>class SpeechHelpersController {
    /*@ngInject*/
    constructor($location) {
        this.$location = $location;
        this.initData();
    }

    initData() {
        this.data = [
            {
                groupId: 'test',
                groups: [
                    {
                        groupId: 'test',
                        entries: [
                            'test'
                        ]
                    }
                ]
            }
        ];
    }

    showAll() {
        for (let i = 0; i< this.data.length; i++) {
            if (!!this.data[i].groups && !!this.data[i].groups.length > 0) {
                for (let j = 0; i < this.data[i].groups.length; j++) {
                    this.show(this.data[i].groups[j]);
                }
            }
        }
    }

    show(group) {
        group.visible = true;
    }

    isButtonVisible(group) {
        return !group.visible;
    }

    isGroupVisible(group) {
        return !!group.visible;
    }

    back() {
        this.$location.url('/stack');
    }
}

export default SpeechHelpersController;<commit_msg>speech helpers (work in progress)<commit_after>class SpeechHelpersController {
    /*@ngInject*/
    constructor($location) {
        this.$location = $location;
        this.initData();
    }

    initData() {
        this.data = [
            {
                // TODO copyright
                groupId: 'Vorschlag',
                groups: [
                    {
                        groupId: 'Sie machen einen Vorschlag',
                        entries: [
                            'Ich habe eine Idee ...',
                            'Ich schlage vor, dass ...',
                            'Ich möchte etwas vorschlagen: ...',
                            'Wollen wir ...?',
                            'Wir können auch ...',
                            'Was meinst du? / Was meinen Sie?',
                            'Was denkst du / Was denken Sie, wollen wir das machen?',
                            'Was denkst du / Was denken Sie, machen wir das?',
                            'Wie findest du ...? / Wie finden Sie ...?',
                            'Wir können ja ..., oder?'
                        ]
                    },
                    {
                        groupId: 'Sie finden einen Vorschlag gut',
                        entries: [
                            'Okay. Das machen wir.',
                            'Das ist eine gute Idee.',
                            'Wir können auch noch ...',
                            'Das gefällt mir.',
                            'Das finde ich gut / super / prima / toll.',
                            'Du hast / Sie haben Recht, so machen wir es.',
                            'Genau!',
                            'Einverstanden!',
                            'In Ordnung!',
                            'Ja, gut. Machen wir das so.',
                            'Ich bin dafür.',
                            'Super!',
                            'Prima!'
                        ]
                    },
                    {
                        groupId: 'Sie sind nicht sicher',
                        entries: [
                            'Ich weiß nicht. Vielleicht sollten wir lieber ...?',
                            'Vielleicht können wir das so machen, aber ...',
                            'Das ist eine gute Idee, aber ...',
                            'Ich finde es besser, wenn ...',
                            'Vielleicht ist es besser, wenn ...',
                            'Wir könnten aber auch ...'
                        ]
                    },
                    {
                        groupId: 'Sie finden einen Vorschlag nicht gut',
                        entries: [
                            'Das finde ich nicht gut. Ich habe eine andere Idee: ...',
                            'Das kann man doch nicht machen.',
                            'Das ist keine gute Idee.',
                            'Das gefällt mir nicht (so) gut.',
                            'Das finde ich nicht gut.',
                            'Besser ist es, wenn ...',
                            'Wir sollten ...',
                            'Ich finde, wir sollten ...',
                            'Ich bin dagegen.',
                            'Nein, dazu habe ich keine Lust.',
                            'Das ist doch Unsinn.',
                            'Ich bin anderer Meinung.'
                        ]
                    }
                ]
            },
            {
                groupId: 'Termin ausmachen',
                groups: [
                    {
                        groupId: 'Sie wollen einen Termin ausmachen',
                        entries: [
                            'Was hast du / haben Sie am Freitag vor?',
                            'Hast du / Haben Sie am Freitag Zeit?',
                            'Wollen wir uns am Freitag treffen?',
                            'Treffen wir uns am Freitag um acht?',
                            'Wie wäre es mit Freitag?',
                            'Geht es am Freitag um acht?',
                            'Passt es dir / Ihnen am Freitag um acht?',
                            'Wann / Um wie viel Uhr treffen wir uns?',
                            'Wann / Um wie viel Uhr hast du / haben Sie Zeit?'
                        ]
                    },
                    {
                        groupId: 'Sie reagieren auf einen Terminvorschlag',
                        entries: [
                            'Ja, das geht.',
                            'Ja, das passt mir gut.',
                            'Kein Problem.',
                            'Nein, am Freitag kann ich leider nicht.',
                            'Nein, am Freitag geht es leider nicht.',
                            '(Tut mir leid, ) ich habe keine Zeit, weil ich arbeiten muss.'
                        ]
                    }
                ]
            },
            {
                groupId: 'Nicht verstehen etwas',
                groups: [
                    {
                        groupId: 'Sie verstehen Ihren Partner / Ihre Partnerin nicht',
                        entries: [
                            'Wie bitte?',
                            'Tut mir leid, ich habe dich / Sie nicht verstanden.',
                            'Kannst du / Können Sie das bitte wiederholen / noch einmal sagen?'
                        ]
                    },
                    {
                        groupId: 'Sie wissen ein Wort auf Deutsch nicht',
                        entries: [
                            'Entschuldigung. Wie heißt das Wort ... auf Deutsch?',
                            'Ich weiß das Wort nicht auf Deutsch. Ich meine ...'
                        ]
                    }
                ]
            }
        ];
    }

    showAll() {
        for (let i = 0; i< this.data.length; i++) {
            if (!!this.data[i].groups && !!this.data[i].groups.length > 0) {
                for (let j = 0; i < this.data[i].groups.length; j++) {
                    this.show(this.data[i].groups[j]);
                }
            }
        }
    }

    show(group) {
        group.visible = true;
    }

    isButtonVisible(group) {
        return !group.visible;
    }

    isGroupVisible(group) {
        return !!group.visible;
    }

    back() {
        this.$location.url('/stack');
    }
}

export default SpeechHelpersController;<|endoftext|>


<commit_before>
carto_quotables = [
  'text-face-name'
];

carto_variables = [
  'text-name'
];

/**
 * some carto properties depends on others, this function
 * remove or add properties needed to carto works
 */
function manage_carto_properies(props) {
  if(/none/i.test(props['text-name'])) {
    // remove all text-* properties
    for(var p in props) {
      if(isTextProperty(p)) {
        delete props[p];
      }
    }
  }
}

function isTextProperty(p) {
  return /^text-/.test(p);
}

function generate_carto_properties(props) {
  return _(props).map(function(v, k) {
    if(_.include(carto_quotables, k)) {
      v = "'" + v + "'";
    }
    if(_.include(carto_variables, k)) {
      v = "[" + v + "]";
    }
    return "  " + k + ": " + v + ";";
  });
}

function filter_props(props, fn) {
  var p = {};
  for(var k in props) {
    var v = props[k];
    if(fn(k, v)) {
      p[k] = v;
    }
  }
  return p;
}

function simple_polygon_generator(table, props, callback) {

  // remove unnecesary properties, for example
  // if the text-name is not present remove all the
  // properties realted to text
  manage_carto_properies(props);

  var text_properties = filter_props(props, function(k, v) { return isTextProperty(k); });
  var general_properties = filter_props(props, function(k, v) { return !isTextProperty(k); });

  generalLayerProps = generate_carto_properties(general_properties);
  textLayerProps = generate_carto_properties(text_properties);

  // layer with non-text properties
  var generalLayer = "#" + table.get('name') + "{\n" + generalLayerProps.join('\n') + "\n}";
  var textLayer = '';
  if(_.size(textLayerProps)) {
    textLayer = "\n\n#" + table.get('name') + "::labels {\n" + textLayerProps.join('\n') + "\n}\n";
  }

  // text properties layer
  callback(generalLayer + textLayer);
}

function bubble_generator(table, props, callback) {
  var table_name = table.get('name');
  var carto_props = {
   'marker-fill': props['marker-fill'],
   'marker-line-color': props['marker-line-color'],
   'marker-line-width': props['marker-line-width'],
   'marker-line-opacity': props['marker-line-opacity'],
   'marker-opacity': props['marker-opacity'],
   'marker-placement': 'point',
   'marker-type': 'ellipse',
   'marker-allow-overlap': true,
   'marker-clip':false,
   'marker-multi-policy':'whole'
  };
  var prop = props['property'];
  var min = props['radius_min'];
  var max = props['radius_max'];
  var values = [];

  var NPOINS = 10;
  // TODO: make this related to the quartiles size
  // instead of linear. The circle area should be related
  // to the data and a little correction due to the problems
  // humans have to measure the area of a circle

  //calculate the bubles sizes
  for(var i = 0; i < NPOINS; ++i) {
    var t = i/(NPOINS-1);
    values.push(min + t*(max - min));
  }

  // generate carto
  simple_polygon_generator(table, carto_props, function(css) {
    table.originalData().quartiles(NPOINS, prop, function(quartiles)  {
      for(var i = NPOINS - 1; i >= 0; --i) {
        if(quartiles[i] !== undefined) {
          css += "\n#" + table_name +" [ " + prop + " <= " + quartiles[i] + "] {\n"
          css += "   marker-width: " + values[i].toFixed(1) + ";\n}"
        }
      }
      callback(css);
    });
  });
}

/**
 * when quartiles are greater than 1<<31 cast to float added .01
 * at the end. If you append only .0 it is casted to int and it
 * does not work
 */
function normalizeQuartiles(quartiles) {
  var maxNumber = 2147483648; // unsigned (1<<31);
  var normalized = [];
  for(var i = 0;  i < quartiles.length; ++i) {
    var q = quartiles[i];
    if(q > Math.abs(maxNumber)) {
      q = q + ".01";
    }
    normalized.push(q);
  }
  return normalized;
}

function choropleth_generator(table, props, callback) {
  var type = table.geomColumnTypes() && table.geomColumnTypes()[0] || "polygon";

  var carto_props = {
   'line-color': props['line-color'],
   'line-opacity': props['line-opacity'],
   'line-width': props['line-width'],
   'polygon-opacity': type == "line" ? 0 : props['polygon-opacity'],
   'text-name': props['text-name'],
   'text-halo-fill': props['text-halo-fill'],
   'text-halo-radius': props['text-halo-radius'],
   'text-face-name': props['text-face-name'],
   'text-size': props['text-size'],
   'text-fill': props['text-fill']
  }

  var methodMap = {
    '3 Buckets': 3,
    '5 Buckets': 5,
    '7 Buckets': 7
  };

  if(!props['color_ramp']) {
    return;
  }

  var prop = props['property'];
  var nquartiles = methodMap[props['method']];
  var ramp = cdb.admin.color_ramps[props['color_ramp']][nquartiles];
  var table_name = table.get('name');

  if(!ramp) {
    cdb.log.error("no colo ramp defined for " + nquartiles + " quartiles");
  }

  simple_polygon_generator(table, carto_props, function(css) {
    table.originalData().quartiles(nquartiles, prop, function(quartiles)  {
      quartiles = normalizeQuartiles(quartiles);
      for(var i = nquartiles - 1; i >= 0; --i) {
        css += "\n#" + table_name +" [ " + prop + " <= " + quartiles[i] + "] {\n";

        if (type == "line") {
          css += "   line-color: " + ramp[i] + ";\n}"
        } else {
          css += "   polygon-fill: " + ramp[i] + ";\n}"
        }
      }
      callback(css);
    });
  });
}

/*
 *
 */
function density_generator(table, props, callback) {
  var carto_props = {
   'line-color': props['line-color'],
   'line-opacity': props['line-opacity'],
   'line-width': props['line-width'],
   'polygon-opacity': props['polygon-opacity'],
  }

  var methodMap = {
    '3 Buckets': 3,
    '5 Buckets': 5,
    '7 Buckets': 7
  };

  var polygon_size = props['polygon-size'];
  var nquartiles = methodMap[props['method']];
  var ramp = cdb.admin.color_ramps[props['color_ramp']][nquartiles];
  var table_name = table.get('name');

  if(!ramp) {
    cdb.log.error("no colo ramp defined for " + nquartiles + " quartiles");
  }

  carto_props['polygon-fill'] = ramp[ramp.length - 1];

  simple_polygon_generator(table, carto_props, function(css) {

    // density
    var tmpl = _.template("" +
    "WITH clusters as ( " +
    "SELECT  " +
        "cartodb_id,   " +
        "st_snaptogrid(the_geom_webmercator, <%= polygon_size %>*CDB_XYZ_Resolution(<%= z %>)) as center  " +
    "FROM <%= table_name %>" +
    "), " +
    "points as ( " +
        "SELECT  " +
            "count(cartodb_id) as npoints,  " +
            "count(cartodb_id)/power( <%= polygon_size %> * CDB_XYZ_Resolution(<%= z %>), 2 ) as density  " +
        "FROM  " +
            "clusters  " +
        "group by  " +
            "center " +
    "), " +
    "stats as ( " +
        "SELECT  " +
            "npoints,  " +
            "density,  " +
            "ntile(<%= slots %>) over (order by density) as quartile  " +
        "FROM points  " +
    ")  " +
    "SELECT  " +
        "quartile,  " +
        "max(npoints) as maxAmount,  " +
        "max(density) as maxDensity   " +
    "FROM stats  " +
    "GROUP BY quartile ORDER BY quartile ");

    var sql = tmpl({
        slots: nquartiles,
        table_name: table.get('name'),
        polygon_size: polygon_size,
        z: props.zoom
    });

    table.originalData()._sqlQuery(sql, function(data) {
      // extract quartiles by zoom level
      var rows = data.rows;
      var quartiles = [];
      for(var i = 0; i < rows.length; ++i) {
        quartiles.push(rows[i].maxdensity);
      }

      quartiles = normalizeQuartiles(quartiles);

      css += "\n#" + table_name + "{\n"
      for(var i = nquartiles - 1; i >= 0; --i) {
        if(quartiles[i] !== undefined) {
          css += "  [points_density <= " + quartiles[i] + "] { polygon-fill: " + ramp[i] + ";  }\n";
        }
      }
      css += "\n}"
      callback(css);
    });
  });
}

cdb.admin.CartoStyles = Backbone.Model.extend({

    defaults: {
      type: 'polygon',
      properties: {
        'polygon-fill': '#FF6600',
        'line-color': '#FFFFFF',
        'line-width': 1,
        'polygon-opacity': 0.7,
        'line-opacity':1
      }
    },

    initialize: function() {
      this.table = this.get('table');
      if(!this.table) {
        throw "table must be passed as param"
        return;
      }
      this.bind('change:properties', this._generateCarto, this);
      this.generators = {};
      this.registerGenerator('polygon', simple_polygon_generator);
      this.registerGenerator('bubble', bubble_generator);
      this.registerGenerator('choropleth', choropleth_generator);
      this.registerGenerator('density', density_generator); // the same generator than choroplet
    },

    // change a property attribute
    attr: function(name, val) {
      var old = this.attributes.properties[name];
      this.attributes.properties[name] = val;
      if(old != val) {
        this.trigger('change:properties', this, this.attributes.properties);
        this.trigger('changes', this);
      }
    },

    registerGenerator: function(name, gen) {
      this.generators[name] = gen;
    },

    /**
     * generate a informative header
     */
    _generateHeader: function() {
      var c = "/** " + this.get('type') + " visualization */\n\n";
      return c;
    },

    _generateCarto: function(){
      var self = this;
      var gen = this.generators[this.get('type')];
      if(!gen) {
        cdb.log.error("can't get style generator for " + this.get('type'));
        return;
      }

      gen(this.table, this.get('properties'), function(style) {
        self.set({
          style: self._generateHeader() + style
        }, { silence: true});
        self.change({ changes: {'style': ''}});

      })
    },

    /**
     * when cartocss is rendered the generator and properties are written in a comment.
     * This function try to load params from that comment.
     *
     * return true if it is able to load style
     */
    loadFromCartoCSS: function(carto) {
      var genType, params;
      if(!carto)  return false;
      var g = carto.match(/genetor type: (\w+)/);
      if(g) {
        genType = g[1];
      }
      g = carto.match(/params: \{(.*)\}/);
      if(g) {
        try {
          params = JSON.parse("{" + g[1] + "}");
        } catch(e) {
          cdb.log.info("can't parse css options");
        }
      }

      if(params && genType && this.generators[genType]) {
        this.set({
          type: genType,
          properties: params
        });
        return true;
      }
      return false;

    }

});
<commit_msg>fixed #1219 <commit_after>
carto_quotables = [
  'text-face-name'
];

carto_variables = [
  'text-name'
];

/**
 * some carto properties depends on others, this function
 * remove or add properties needed to carto works
 */
function manage_carto_properies(props) {
  if(/none/i.test(props['text-name'])) {
    // remove all text-* properties
    for(var p in props) {
      if(isTextProperty(p)) {
        delete props[p];
      }
    }
  }
}

function isTextProperty(p) {
  return /^text-/.test(p);
}

function generate_carto_properties(props) {
  return _(props).map(function(v, k) {
    if(_.include(carto_quotables, k)) {
      v = "'" + v + "'";
    }
    if(_.include(carto_variables, k)) {
      v = "[" + v + "]";
    }
    return "  " + k + ": " + v + ";";
  });
}

function filter_props(props, fn) {
  var p = {};
  for(var k in props) {
    var v = props[k];
    if(fn(k, v)) {
      p[k] = v;
    }
  }
  return p;
}

function simple_polygon_generator(table, props, callback) {

  // remove unnecesary properties, for example
  // if the text-name is not present remove all the
  // properties realted to text
  manage_carto_properies(props);

  var text_properties = filter_props(props, function(k, v) { return isTextProperty(k); });
  var general_properties = filter_props(props, function(k, v) { return !isTextProperty(k); });

  generalLayerProps = generate_carto_properties(general_properties);
  textLayerProps = generate_carto_properties(text_properties);

  // layer with non-text properties
  var generalLayer = "#" + table.get('name') + "{\n" + generalLayerProps.join('\n') + "\n}";
  var textLayer = '';
  if(_.size(textLayerProps)) {
    textLayer = "\n\n#" + table.get('name') + "::labels {\n" + textLayerProps.join('\n') + "\n}\n";
  }

  // text properties layer
  callback(generalLayer + textLayer);
}

function bubble_generator(table, props, callback) {
  var table_name = table.get('name');
  var carto_props = {
   'marker-fill': props['marker-fill'],
   'marker-line-color': props['marker-line-color'],
   'marker-line-width': props['marker-line-width'],
   'marker-line-opacity': props['marker-line-opacity'],
   'marker-opacity': props['marker-opacity'],
   'marker-placement': 'point',
   'marker-type': 'ellipse',
   'marker-allow-overlap': true,
   'marker-clip':false,
   'marker-multi-policy':'largest'
  };
  var prop = props['property'];
  var min = props['radius_min'];
  var max = props['radius_max'];
  var values = [];

  var NPOINS = 10;
  // TODO: make this related to the quartiles size
  // instead of linear. The circle area should be related
  // to the data and a little correction due to the problems
  // humans have to measure the area of a circle

  //calculate the bubles sizes
  for(var i = 0; i < NPOINS; ++i) {
    var t = i/(NPOINS-1);
    values.push(min + t*(max - min));
  }

  // generate carto
  simple_polygon_generator(table, carto_props, function(css) {
    table.originalData().quartiles(NPOINS, prop, function(quartiles)  {
      for(var i = NPOINS - 1; i >= 0; --i) {
        if(quartiles[i] !== undefined) {
          css += "\n#" + table_name +" [ " + prop + " <= " + quartiles[i] + "] {\n"
          css += "   marker-width: " + values[i].toFixed(1) + ";\n}"
        }
      }
      callback(css);
    });
  });
}

/**
 * when quartiles are greater than 1<<31 cast to float added .01
 * at the end. If you append only .0 it is casted to int and it
 * does not work
 */
function normalizeQuartiles(quartiles) {
  var maxNumber = 2147483648; // unsigned (1<<31);
  var normalized = [];
  for(var i = 0;  i < quartiles.length; ++i) {
    var q = quartiles[i];
    if(q > Math.abs(maxNumber)) {
      q = q + ".01";
    }
    normalized.push(q);
  }
  return normalized;
}

function choropleth_generator(table, props, callback) {
  var type = table.geomColumnTypes() && table.geomColumnTypes()[0] || "polygon";

  var carto_props = {
   'line-color': props['line-color'],
   'line-opacity': props['line-opacity'],
   'line-width': props['line-width'],
   'polygon-opacity': type == "line" ? 0 : props['polygon-opacity'],
   'text-name': props['text-name'],
   'text-halo-fill': props['text-halo-fill'],
   'text-halo-radius': props['text-halo-radius'],
   'text-face-name': props['text-face-name'],
   'text-size': props['text-size'],
   'text-fill': props['text-fill']
  }

  var methodMap = {
    '3 Buckets': 3,
    '5 Buckets': 5,
    '7 Buckets': 7
  };

  if(!props['color_ramp']) {
    return;
  }

  var prop = props['property'];
  var nquartiles = methodMap[props['method']];
  var ramp = cdb.admin.color_ramps[props['color_ramp']][nquartiles];
  var table_name = table.get('name');

  if(!ramp) {
    cdb.log.error("no colo ramp defined for " + nquartiles + " quartiles");
  }

  simple_polygon_generator(table, carto_props, function(css) {
    table.originalData().quartiles(nquartiles, prop, function(quartiles)  {
      quartiles = normalizeQuartiles(quartiles);
      for(var i = nquartiles - 1; i >= 0; --i) {
        css += "\n#" + table_name +" [ " + prop + " <= " + quartiles[i] + "] {\n";

        if (type == "line") {
          css += "   line-color: " + ramp[i] + ";\n}"
        } else {
          css += "   polygon-fill: " + ramp[i] + ";\n}"
        }
      }
      callback(css);
    });
  });
}

/*
 *
 */
function density_generator(table, props, callback) {
  var carto_props = {
   'line-color': props['line-color'],
   'line-opacity': props['line-opacity'],
   'line-width': props['line-width'],
   'polygon-opacity': props['polygon-opacity'],
  }

  var methodMap = {
    '3 Buckets': 3,
    '5 Buckets': 5,
    '7 Buckets': 7
  };

  var polygon_size = props['polygon-size'];
  var nquartiles = methodMap[props['method']];
  var ramp = cdb.admin.color_ramps[props['color_ramp']][nquartiles];
  var table_name = table.get('name');

  if(!ramp) {
    cdb.log.error("no colo ramp defined for " + nquartiles + " quartiles");
  }

  carto_props['polygon-fill'] = ramp[ramp.length - 1];

  simple_polygon_generator(table, carto_props, function(css) {

    // density
    var tmpl = _.template("" +
    "WITH clusters as ( " +
    "SELECT  " +
        "cartodb_id,   " +
        "st_snaptogrid(the_geom_webmercator, <%= polygon_size %>*CDB_XYZ_Resolution(<%= z %>)) as center  " +
    "FROM <%= table_name %>" +
    "), " +
    "points as ( " +
        "SELECT  " +
            "count(cartodb_id) as npoints,  " +
            "count(cartodb_id)/power( <%= polygon_size %> * CDB_XYZ_Resolution(<%= z %>), 2 ) as density  " +
        "FROM  " +
            "clusters  " +
        "group by  " +
            "center " +
    "), " +
    "stats as ( " +
        "SELECT  " +
            "npoints,  " +
            "density,  " +
            "ntile(<%= slots %>) over (order by density) as quartile  " +
        "FROM points  " +
    ")  " +
    "SELECT  " +
        "quartile,  " +
        "max(npoints) as maxAmount,  " +
        "max(density) as maxDensity   " +
    "FROM stats  " +
    "GROUP BY quartile ORDER BY quartile ");

    var sql = tmpl({
        slots: nquartiles,
        table_name: table.get('name'),
        polygon_size: polygon_size,
        z: props.zoom
    });

    table.originalData()._sqlQuery(sql, function(data) {
      // extract quartiles by zoom level
      var rows = data.rows;
      var quartiles = [];
      for(var i = 0; i < rows.length; ++i) {
        quartiles.push(rows[i].maxdensity);
      }

      quartiles = normalizeQuartiles(quartiles);

      css += "\n#" + table_name + "{\n"
      for(var i = nquartiles - 1; i >= 0; --i) {
        if(quartiles[i] !== undefined) {
          css += "  [points_density <= " + quartiles[i] + "] { polygon-fill: " + ramp[i] + ";  }\n";
        }
      }
      css += "\n}"
      callback(css);
    });
  });
}

cdb.admin.CartoStyles = Backbone.Model.extend({

    defaults: {
      type: 'polygon',
      properties: {
        'polygon-fill': '#FF6600',
        'line-color': '#FFFFFF',
        'line-width': 1,
        'polygon-opacity': 0.7,
        'line-opacity':1
      }
    },

    initialize: function() {
      this.table = this.get('table');
      if(!this.table) {
        throw "table must be passed as param"
        return;
      }
      this.bind('change:properties', this._generateCarto, this);
      this.generators = {};
      this.registerGenerator('polygon', simple_polygon_generator);
      this.registerGenerator('bubble', bubble_generator);
      this.registerGenerator('choropleth', choropleth_generator);
      this.registerGenerator('density', density_generator); // the same generator than choroplet
    },

    // change a property attribute
    attr: function(name, val) {
      var old = this.attributes.properties[name];
      this.attributes.properties[name] = val;
      if(old != val) {
        this.trigger('change:properties', this, this.attributes.properties);
        this.trigger('changes', this);
      }
    },

    registerGenerator: function(name, gen) {
      this.generators[name] = gen;
    },

    /**
     * generate a informative header
     */
    _generateHeader: function() {
      var c = "/** " + this.get('type') + " visualization */\n\n";
      return c;
    },

    _generateCarto: function(){
      var self = this;
      var gen = this.generators[this.get('type')];
      if(!gen) {
        cdb.log.error("can't get style generator for " + this.get('type'));
        return;
      }

      gen(this.table, this.get('properties'), function(style) {
        self.set({
          style: self._generateHeader() + style
        }, { silence: true});
        self.change({ changes: {'style': ''}});

      })
    },

    /**
     * when cartocss is rendered the generator and properties are written in a comment.
     * This function try to load params from that comment.
     *
     * return true if it is able to load style
     */
    loadFromCartoCSS: function(carto) {
      var genType, params;
      if(!carto)  return false;
      var g = carto.match(/genetor type: (\w+)/);
      if(g) {
        genType = g[1];
      }
      g = carto.match(/params: \{(.*)\}/);
      if(g) {
        try {
          params = JSON.parse("{" + g[1] + "}");
        } catch(e) {
          cdb.log.info("can't parse css options");
        }
      }

      if(params && genType && this.generators[genType]) {
        this.set({
          type: genType,
          properties: params
        });
        return true;
      }
      return false;

    }

});
<|endoftext|>


<commit_before>(function(window) {
    'use strict';

    // HACK: ie8 does not need to reset the body border,
    // while any other browser does.
    // This hack is obsolete in standards mode, but
    // calibration script is executed on about:blank
    // which is in quirks mode.
    // Needs to find a proper way to open calibration
    // page in standards mode.
    function needsResetBorder() {
        return !/MSIE 8\.0/.test(navigator.userAgent);
    }

    function createRedStripe(side) {
        var div = document.createElement('div');
        div.style.position = 'absolute';
        div.style.width = '1px';
        div.style.backgroundColor = '#ff0000';
        div.style.height = '100%';
        div.style.top = '0';
        div.style[side] = '3px';
        document.body.appendChild(div);
    }

    function createPattern() {
        var bodyStyle = document.body.style;
        bodyStyle.margin = 0;
        bodyStyle.padding = 0;

        if (needsResetBorder()) {
            bodyStyle.border = 0;
        }
        bodyStyle.backgroundColor = '#00ff00';
        bodyStyle.width = '100%';
        bodyStyle.height = '100%';
        createRedStripe('left');
        createRedStripe('right');
    }

    function getBrowserFeatures() {
        var features = {
            hasCSS3Selectors: true
        };
        try {
            document.querySelector('body:nth-child(1)');
        } catch (e) {
            features.hasCSS3Selectors = false;
        }

        return features;
    }

    createPattern();
    return getBrowserFeatures();
}(window));
<commit_msg>Fix calibration in chrome 43+<commit_after>(function(window) {
    'use strict';

    // HACK: ie8 does not need to reset the body border,
    // while any other browser does.
    // This hack is obsolete in standards mode, but
    // calibration script is executed on about:blank
    // which is in quirks mode.
    // Needs to find a proper way to open calibration
    // page in standards mode.
    function needsResetBorder() {
        return !/MSIE 8\.0/.test(navigator.userAgent);
    }

    function createPattern() {
        var bodyStyle = document.body.style;
        bodyStyle.margin = 0;
        bodyStyle.padding = 0;

        if (needsResetBorder()) {
            bodyStyle.border = 0;
        }

        var img = document.createElement('div');
        img.style.width = '4px';
        img.style.height = '1px';
        img.style.margin = '0';
        img.style.padding = '0';

        // 1px high image with pattern: (green, green, green, red)
        img.style.background = 'url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAABCAIAAAB2XpiaAAAAD0lEQVQIW2Ng+M8AQUACABryA/01utvkAAAAAElFTkSuQmCC)';

        document.body.appendChild(img);
    }

    function getBrowserFeatures() {
        var features = {
            hasCSS3Selectors: true
        };
        try {
            document.querySelector('body:nth-child(1)');
        } catch (e) {
            features.hasCSS3Selectors = false;
        }

        return features;
    }

    createPattern();
    return getBrowserFeatures();
}(window));
<|endoftext|>


<commit_before>'use stric'
var constants = require('../../misc/constants')
var console_colors = require('../../misc/console_colors')

var promise = require('../../facades/promise')

var handler_for_put_assets = require('./apply_handler_for_put_assets')
var handler_for_apply = require('./apply_handler_for_apply')
var handler_for_reindex = require('./apply_handler_for_reindex')
var handler_for_update = require('./apply_handler_for_update')

var elasticsearch = require('elasticsearch')

module.exports.put_only = function(params, generated_assets) {
  es_setup = _setup_esclient(params)
  return _put_assets_handler(es_setup, generated_assets).then(
    es_setup.esclient_releaser_on_success
  ).catch(
    es_setup.esclient_releaser_on_error
  )
}

module.exports.put_and_update = function(params, generated_assets) {
  es_setup = _setup_esclient(params)
  return _put_assets_handler(es_setup, generated_assets).then(
    function() {
      return _apply_configs(es_setup, generated_assets.configs, constants.UPDATE_POST_ACTION)
    }
  ).then(
    es_setup.esclient_releaser_on_success
  ).catch(
    es_setup.esclient_releaser_on_error
  )
}

module.exports.put_and_reindex = function(params, generated_assets) {
  es_setup = _setup_esclient(params)
  return _put_assets_handler(es_setup, generated_assets).then(
    function() {
      return _apply_configs(es_setup, generated_assets.configs, constants.REINDEX_POST_ACTION)
    }
  ).then(
    es_setup.esclient_releaser_on_success
  ).catch(
    es_setup.esclient_releaser_on_error
  )
}

module.exports.put_and_auto = function(params, generated_assets) {
  es_setup = _setup_esclient(params)
  return _put_assets_handler(es_setup, generated_assets).then(
    function() {
      return _apply_configs(es_setup, generated_assets.configs)
    }
  ).then(
    es_setup.esclient_releaser_on_success
  ).catch(
    es_setup.esclient_releaser_on_error
  )
}

var _put_assets_handler = function(es_setup, generated_assets) {
  return promise.resolve().then(
    function() {
      return handler_for_put_assets.put_configs(es_setup, generated_assets.configs)
    }
  ).then(
    function() {
      return handler_for_put_assets.put_pipelines(es_setup, generated_assets.configs, generated_assets.pipelines)
    }
  ).then(
    function() {
      return handler_for_put_assets.put_query_templates(es_setup, generated_assets.configs, generated_assets.query_templates)
    }
  )
}

var _setup_esclient = function(params) {
  var esclient = new elasticsearch.Client({
    host: params.base_url,
    httpAuth: params.basic_auth,
    log: 'info',
    ssl: {
      rejectUnauthorized: false
    },
    "requestTimeout" : 7200000 // 2H
  });

  var esclient_releaser_on_success = function(arg) {
    esclient.close()
    return promise.resolve(arg)
  }

  var esclient_releaser_on_error = function(arg) {
    esclient.close()
    return promise.reject(arg)
  }

  return {
    esclient : esclient,
    esclient_releaser_on_success : esclient_releaser_on_success,
    esclient_releaser_on_error : esclient_releaser_on_error
  }
}

var _apply_configs = function(es_setup, configs, forced_post_action) {
  var promise_chain = promise.resolve()

  for (var property in configs) {
    if (configs.hasOwnProperty(property)) {
      var config_name = property
      var config = configs[config_name]

      promise_chain = _apply_config(promise_chain, es_setup, config_name, config, forced_post_action)
    }
  }

  return promise_chain
}

var _apply_config = function(promise_chain, es_setup, config_name, config, forced_post_action) {
  var use_forced_post_action = typeof forced_post_action === 'string' && forced_post_action.trim() !== ''
  return promise_chain.then(
    function() {
      console.log(console_colors.FGBLUE, "")
      console.log(console_colors.FGBLUE, "APPLYING '"+config_name+"' CONFIGURATION ...")
      return promise.resolve()
    }
  ).then(
    function() {
      return handler_for_apply.apply_index_config(es_setup, config_name, config)
    }
  ).then(
    function(update_index_config_result) {
      var post_action =  use_forced_post_action ? forced_post_action : update_index_config_result.post_action
      var current_index_version = update_index_config_result.current_version
      switch(post_action) {

        case constants.UPDATE_POST_ACTION :
          return _update_handler(es_setup, config_name, config)

        case constants.REINDEX_POST_ACTION :
          return _reindex_handler(es_setup, config_name, config, current_index_version)

        default:
          return promise.resolve()
      }
    }
  ).then(
    function() {
      console.log(console_colors.FGBLUE, "APPLYING '"+config_name+"' CONFIGURATION DONE!")
      console.log(console_colors.FGBLUE, "")

      return promise.resolve()
    }
  )
}

var _update_handler = function(es_setup, config_name, config) {
  return promise.resolve().then(
    function() {
      console.log(console_colors.FGWHITE, "  Updating '"+config_name+"' ...")
    }
  ).then(
    function() {
      return handler_for_update.update_by_query_with_pipeline(es_setup, config_name, config)
    }
  ).then(
    function() {
      console.log(console_colors.FGWHITE, "  '"+config_name+"' updated!")
    }
  )
}

var _reindex_handler = function(params, config_name, config, current_index_version) {
  return promise.resolve().then(
    function() {
      console.log(console_colors.FGWHITE, "  Reindexing '"+config_name+"' with version '"+current_index_version+"' ...")
    }
  ).then(
    function() {
      return handler_for_reindex.reindex_with_pipeline(es_setup, config_name, config, current_index_version)
    }
  ).then(
    function(new_current_version) {
      console.log(console_colors.FGWHITE, "  '"+config_name+"' reindexed with version '"+new_current_version+"'")
    }
  )

}
<commit_msg>Adding keepAlive false to really wait for the request timeout<commit_after>'use stric'
var constants = require('../../misc/constants')
var console_colors = require('../../misc/console_colors')

var promise = require('../../facades/promise')

var handler_for_put_assets = require('./apply_handler_for_put_assets')
var handler_for_apply = require('./apply_handler_for_apply')
var handler_for_reindex = require('./apply_handler_for_reindex')
var handler_for_update = require('./apply_handler_for_update')

var elasticsearch = require('elasticsearch')

module.exports.put_only = function(params, generated_assets) {
  es_setup = _setup_esclient(params)
  return _put_assets_handler(es_setup, generated_assets).then(
    es_setup.esclient_releaser_on_success
  ).catch(
    es_setup.esclient_releaser_on_error
  )
}

module.exports.put_and_update = function(params, generated_assets) {
  es_setup = _setup_esclient(params)
  return _put_assets_handler(es_setup, generated_assets).then(
    function() {
      return _apply_configs(es_setup, generated_assets.configs, constants.UPDATE_POST_ACTION)
    }
  ).then(
    es_setup.esclient_releaser_on_success
  ).catch(
    es_setup.esclient_releaser_on_error
  )
}

module.exports.put_and_reindex = function(params, generated_assets) {
  es_setup = _setup_esclient(params)
  return _put_assets_handler(es_setup, generated_assets).then(
    function() {
      return _apply_configs(es_setup, generated_assets.configs, constants.REINDEX_POST_ACTION)
    }
  ).then(
    es_setup.esclient_releaser_on_success
  ).catch(
    es_setup.esclient_releaser_on_error
  )
}

module.exports.put_and_auto = function(params, generated_assets) {
  es_setup = _setup_esclient(params)
  return _put_assets_handler(es_setup, generated_assets).then(
    function() {
      return _apply_configs(es_setup, generated_assets.configs)
    }
  ).then(
    es_setup.esclient_releaser_on_success
  ).catch(
    es_setup.esclient_releaser_on_error
  )
}

var _put_assets_handler = function(es_setup, generated_assets) {
  return promise.resolve().then(
    function() {
      return handler_for_put_assets.put_configs(es_setup, generated_assets.configs)
    }
  ).then(
    function() {
      return handler_for_put_assets.put_pipelines(es_setup, generated_assets.configs, generated_assets.pipelines)
    }
  ).then(
    function() {
      return handler_for_put_assets.put_query_templates(es_setup, generated_assets.configs, generated_assets.query_templates)
    }
  )
}

var _setup_esclient = function(params) {
  var esclient = new elasticsearch.Client({
    host: params.base_url,
    httpAuth: params.basic_auth,
    log: 'info',
    ssl: {
      rejectUnauthorized: false
    },
    requestTimeout : 7200000, // 2H
    keepAlive : false
  });

  var esclient_releaser_on_success = function(arg) {
    esclient.close()
    return promise.resolve(arg)
  }

  var esclient_releaser_on_error = function(arg) {
    esclient.close()
    return promise.reject(arg)
  }

  return {
    esclient : esclient,
    esclient_releaser_on_success : esclient_releaser_on_success,
    esclient_releaser_on_error : esclient_releaser_on_error
  }
}

var _apply_configs = function(es_setup, configs, forced_post_action) {
  var promise_chain = promise.resolve()

  for (var property in configs) {
    if (configs.hasOwnProperty(property)) {
      var config_name = property
      var config = configs[config_name]

      promise_chain = _apply_config(promise_chain, es_setup, config_name, config, forced_post_action)
    }
  }

  return promise_chain
}

var _apply_config = function(promise_chain, es_setup, config_name, config, forced_post_action) {
  var use_forced_post_action = typeof forced_post_action === 'string' && forced_post_action.trim() !== ''
  return promise_chain.then(
    function() {
      console.log(console_colors.FGBLUE, "")
      console.log(console_colors.FGBLUE, "APPLYING '"+config_name+"' CONFIGURATION ...")
      return promise.resolve()
    }
  ).then(
    function() {
      return handler_for_apply.apply_index_config(es_setup, config_name, config)
    }
  ).then(
    function(update_index_config_result) {
      var post_action =  use_forced_post_action ? forced_post_action : update_index_config_result.post_action
      var current_index_version = update_index_config_result.current_version
      switch(post_action) {

        case constants.UPDATE_POST_ACTION :
          return _update_handler(es_setup, config_name, config)

        case constants.REINDEX_POST_ACTION :
          return _reindex_handler(es_setup, config_name, config, current_index_version)

        default:
          return promise.resolve()
      }
    }
  ).then(
    function() {
      console.log(console_colors.FGBLUE, "APPLYING '"+config_name+"' CONFIGURATION DONE!")
      console.log(console_colors.FGBLUE, "")

      return promise.resolve()
    }
  )
}

var _update_handler = function(es_setup, config_name, config) {
  return promise.resolve().then(
    function() {
      console.log(console_colors.FGWHITE, "  Updating '"+config_name+"' ...")
    }
  ).then(
    function() {
      return handler_for_update.update_by_query_with_pipeline(es_setup, config_name, config)
    }
  ).then(
    function() {
      console.log(console_colors.FGWHITE, "  '"+config_name+"' updated!")
    }
  )
}

var _reindex_handler = function(params, config_name, config, current_index_version) {
  return promise.resolve().then(
    function() {
      console.log(console_colors.FGWHITE, "  Reindexing '"+config_name+"' with version '"+current_index_version+"' ...")
    }
  ).then(
    function() {
      return handler_for_reindex.reindex_with_pipeline(es_setup, config_name, config, current_index_version)
    }
  ).then(
    function(new_current_version) {
      console.log(console_colors.FGWHITE, "  '"+config_name+"' reindexed with version '"+new_current_version+"'")
    }
  )

}
<|endoftext|>


<commit_before>'use strict';

/**
 * Expose `Input`.
 */
module.exports = Input;

/**
 * Module dependencies.
 */
var utils = require('../../utils'),
    Abstract = require('./abstract')
;

/**
 * Initialize a new input sequence interpreter.
 *
 * @param {danf:dependencyInjection.sequencesContainer} The sequences container.
 * @param {danf:manipulation.dataResolver} The data resolver.
 */
function Input(sequencesContainer, dataResolver) {
    Abstract.call(this, sequencesContainer);

    this._order = 800;
    if (dataResolver) {
        this.dataResolver = dataResolver;
    }
}

utils.extend(Abstract, Input);

/**
 * Set the data resolver.
 *
 * @param {danf:manipulation.dataResolver} The data resolver.
 * @api public
 */
Object.defineProperty(Input.prototype, 'dataResolver', {
    set: function(dataResolver) {
        this._dataResolver = dataResolver
    }
});

/**
 * @interface {danf:event.sequenceInterpreter}
 */
Object.defineProperty(Input.prototype, 'contract', {
    value: {
        input: {
            type: 'mixed_object'
        }
    }
});

/**
 * @interface {danf:event.sequenceInterpreter}
 */
 Input.prototype.interpret = function(interpretation, definition, context) {
    if (definition.input) {
        interpretation.unshift({
            order: null,
            operations: [interpretInput.call(this, definition.input, definition.id, definition)]
        });
    }

    return interpretation;
}

/**
 * Interpret an input
 *
 * @param {object} input The definition of the input.
 * @param {string} id The identifier of the sequence.
 * @param {mixed_object} defintion The definition of the sequence.
 * @return {function} The interpreted input.
 */
var interpretInput = function(input, id, definition) {
    var self = this;

    return function(flow, callback) {
        definition.input = self._dataResolver.resolve(
            flow.stream,
            input,
            'sequence[{0}]'.format(id)
        );

        callback();
    };
}
<commit_msg>Change input source to current stream<commit_after>'use strict';

/**
 * Expose `Input`.
 */
module.exports = Input;

/**
 * Module dependencies.
 */
var utils = require('../../utils'),
    Abstract = require('./abstract')
;

/**
 * Initialize a new input sequence interpreter.
 *
 * @param {danf:dependencyInjection.sequencesContainer} The sequences container.
 * @param {danf:manipulation.dataResolver} The data resolver.
 */
function Input(sequencesContainer, dataResolver) {
    Abstract.call(this, sequencesContainer);

    this._order = 800;
    if (dataResolver) {
        this.dataResolver = dataResolver;
    }
}

utils.extend(Abstract, Input);

/**
 * Set the data resolver.
 *
 * @param {danf:manipulation.dataResolver} The data resolver.
 * @api public
 */
Object.defineProperty(Input.prototype, 'dataResolver', {
    set: function(dataResolver) {
        this._dataResolver = dataResolver
    }
});

/**
 * @interface {danf:event.sequenceInterpreter}
 */
Object.defineProperty(Input.prototype, 'contract', {
    value: {
        input: {
            type: 'mixed_object'
        }
    }
});

/**
 * @interface {danf:event.sequenceInterpreter}
 */
 Input.prototype.interpret = function(interpretation, definition, context) {
    if (definition.input) {
        interpretation.unshift({
            order: null,
            operations: [interpretInput.call(this, definition.input, definition.id, definition)]
        });
    }

    return interpretation;
}

/**
 * Interpret an input
 *
 * @param {object} input The definition of the input.
 * @param {string} id The identifier of the sequence.
 * @param {mixed_object} defintion The definition of the sequence.
 * @return {function} The interpreted input.
 */
var interpretInput = function(input, id, definition) {
    var self = this;

    return function(flow, callback) {
        definition.input = self._dataResolver.resolve(
            flow.currentStream,
            input,
            'sequence[{0}]'.format(id)
        );

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


<commit_before>{!!l10n}require('basis.l10n');
{!!l10n}require('app.settings.l10n');
require('basis.app');
require('basis.ui');
;;;require('basis.devpanel');

{!!l10n}var dict = basis.l10n.dictionary(__filename);
{!!l10n}
module.exports = basis.app.create({
{ !l10n}{!!appTitle}  title: '{=appTitle}',
{ !l10n}{!!appTitle}
{!!l10n}  title: dict.token('title'),
{!!l10n}
  init: function(){
    return new basis.ui.Node({
      template: resource('./{=name}/template/layout.tmpl'),
      binding: {
        //moduleName: resource('./module/moduleName/index.js')
      }
    });
  }
});
<commit_msg>create: fix main app script template<commit_after>var Node = require('basis.ui').Node;
{!!l10n}var dict = require('basis.l10n').dictionary(__filename);
{!!l10n}require('app.settings.l10n');
/** @cut */ require('basis.devpanel');

module.exports = require('basis.app').create({
{ !l10n}{!!appTitle}  title: '{=appTitle}',
{ !l10n}{!!appTitle}
{!!l10n}  title: dict.token('title'),
{!!l10n}
  init: function(){
    return new Node({
      template: resource('./{=name}/template/layout.tmpl'),
      binding: {
        //moduleName: resource('./module/moduleName/index.js')
      }
    });
  }
});
<|endoftext|>