<commit_before>/*---------------------------------------------------------
 * OpenERP diagram library
 *---------------------------------------------------------*/

openerp.web_diagram = function (instance) {
var QWeb = instance.web.qweb,
      _t = instance.web._t,
     _lt = instance.web._lt;
instance.web.views.add('diagram', 'instance.web.DiagramView');
instance.web.DiagramView = instance.web.View.extend({
    display_name: _lt('Diagram'),
    searchable: false,
    init: function(parent, dataset, view_id, options) {
        this._super(parent);
        this.set_default_options(options);
        this.view_manager = parent;
        this.dataset = dataset;
        this.model = this.dataset.model;
        this.view_id = view_id;
        this.domain = this.dataset._domain || [];
        this.context = {};
        this.ids = this.dataset.ids;
    },
    start: function() {
        return this.rpc("/web_diagram/diagram/load", {"model": this.model, "view_id": this.view_id}, this.on_loaded);
    },

    toTitleCase: function(str) {
        return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    },

    on_loaded: function(result) {

        var self = this;
        if(this.ids && this.ids.length) {
            this.id = this.ids[self.dataset.index || 0];
        }

        this.fields_view = result.fields_view,
        this.view_id = this.fields_view.view_id,
        this.fields = this.fields_view.fields,
        this.nodes = this.fields_view.arch.children[0],
        this.connectors = this.fields_view.arch.children[1],
        this.node = this.nodes.attrs.object,
        this.connector = this.connectors.attrs.object;
        this.labels = _.filter(this.fields_view.arch.children, function(label) {
            return label.tag == "label";
        });

        this.$el.html(QWeb.render("DiagramView", {'widget': this}));
        this.$el.addClass(this.fields_view.arch.attrs['class']);

        _.each(self.labels,function(label){
            html_label = '
' + label.attrs.string + "
";
            self.$el.find('.oe_diagram_header').append(html_label);
        })

        this.$el.find('div.oe_diagram_pager button[data-pager-action]').click(function() {
            var action = $(this).data('pager-action');
            self.on_pager_action(action);
        });

        this.do_update_pager();

        // New Node,Edge
        this.$el.find('#new_node.oe_diagram_button_new').click(function(){self.add_node();});

        if(this.id) {
            self.get_diagram_info();
        }

    },

    get_diagram_info: function() {
        var self = this;
        var params = {
            'id': this.id,
            'model': this.model,
            'node': this.node,
            'connector': this.connector,
            'bgcolor': this.nodes.attrs.bgcolor,
            'shape': this.nodes.attrs.shape,
            'src_node': this.connectors.attrs.source,
            'des_node': this.connectors.attrs.destination,
            'label': this.connectors.attrs.label || false,
            'visible_nodes': [],
            'invisible_nodes': [],
            'node_fields': [],
            'connectors': [],
            'connectors_fields': []
        };

        _.each(this.nodes.children, function(child) {
            if(child.attrs.invisible == '1')
                params['invisible_nodes'].push(child.attrs.name);
            else {
                params['visible_nodes'].push(child.attrs.name);
                params['node_fields'].push(self.fields[child.attrs.name]['string']|| this.toTitleCase(child.attrs.name));
            }
        });

        _.each(this.connectors.children, function(conn) {
            params['connectors_fields'].push(self.fields[conn.attrs.name]['string']|| this.toTitleCase(conn.attrs.name));
            params['connectors'].push(conn.attrs.name);
        });

        this.rpc(
            '/web_diagram/diagram/get_diagram_info',params).then(function(result) {
                self.draw_diagram(result);
            }
        );
    },

    on_diagram_loaded: function(record) {
        var id_record = record['id'];
        if(id_record) {
            this.id = id_record;
            this.get_diagram_info();
        }
    },

    // Set-up the drawing elements of the diagram
    draw_diagram: function(result) {
        var self = this;
        var res_nodes  = result['nodes'];
        var res_edges  = result['conn'];
        this.parent_field = result.parent_field;
        this.$el.find('h3.oe_diagram_title').text(result.name);

        var id_to_node = {};

        var style = {
            edge_color: "#A0A0A0",
            edge_label_color: "#555",
            edge_label_font_size: 10,
            edge_width: 2,
            edge_spacing: 100,
            edge_loop_radius: 100,

            node_label_color: "#333",
            node_label_font_size: 12,
            node_outline_color: "#333",
            node_outline_width: 1,
            node_selected_color: "#0097BE",
            node_selected_width: 2,
            node_size_x: 110,
            node_size_y: 80,
            connector_active_color: "#FFF",
            connector_radius: 4,

            close_button_radius: 8,
            close_button_color: "#333",
            close_button_x_color: "#FFF",

            gray: "#DCDCDC",
            white: "#FFF",

            viewport_margin: 50
        };

        // remove previous diagram
        var canvas = self.$el.find('div.oe_diagram_diagram')
                             .empty().get(0);

        var r  = new Raphael(canvas, '100%','100%');

        var graph  = new CuteGraph(r,style,canvas.parentNode);

        var confirm_dialog = $('#dialog').dialog({
            autoOpen: false,
            title: _t("Are you sure?") });

        _.each(res_nodes, function(node) {
            var n = new CuteNode(
                graph,
                node.x + 50,  //FIXME the +50 should be in the layout algorithm
                node.y + 50,
                CuteGraph.wordwrap(node.name, 14),
                node.shape === 'rectangle' ? 'rect' : 'circle',
                node.color === 'white' ? style.white : style.gray);

            n.id = node.id;
            id_to_node[node.id] = n;
        });

        _.each(res_edges, function(edge) {
            var e =  new CuteEdge(
                graph,
                CuteGraph.wordwrap(edge.signal, 32),
                id_to_node[edge.s_id],
                id_to_node[edge.d_id] || id_to_node[edge.s_id]  );  //WORKAROUND
            e.id = edge.id;
        });

        CuteNode.double_click_callback = function(cutenode){
            self.edit_node(cutenode.id);
        };
        var i = 0;
        CuteNode.destruction_callback = function(cutenode){
            if(!confirm(_t("Deleting this node cannot be undone.\nIt will also delete all connected transitions.\n\nAre you sure ?"))){
                return $.Deferred().reject().promise();
            }
            return new instance.web.DataSet(self,self.node).unlink([cutenode.id]);
        };
        CuteEdge.double_click_callback = function(cuteedge){
            self.edit_connector(cuteedge.id);
        };

        CuteEdge.creation_callback = function(node_start, node_end){
            return {label:_t("")};
        };
        CuteEdge.new_edge_callback = function(cuteedge){
            self.add_connector(cuteedge.get_start().id,
                               cuteedge.get_end().id,
                               cuteedge);
        };
        CuteEdge.destruction_callback = function(cuteedge){
            if(!confirm(_t("Deleting this transition cannot be undone.\n\nAre you sure ?"))){
                return $.Deferred().reject().promise();
            }
            return new instance.web.DataSet(self,self.connector).unlink([cuteedge.id]);
        };

    },

    // Creates a popup to edit the content of the node with id node_id
    edit_node: function(node_id){
        var self = this;
        var title = _t('Activity');
        var pop = new instance.web.form.FormOpenPopup(self);

        pop.show_element(
                self.node,
                node_id,
                self.context || self.dataset.context,
                {
                    title: _t("Open: ") + title
                }
            );

        pop.on('on_write_complete', self, function() {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
            });

        var form_fields = [self.parent_field];
        var form_controller = pop.view_form;

       form_controller.on("load_record", self, function(){
            _.each(form_fields, function(fld) {
                if (!(fld in form_controller.fields)) { return; }
                var field = form_controller.fields[fld];
                field.$input.prop('disabled', true);
                field.$drop_down.unbind();
            });
         });

    },

    // Creates a popup to add a node to the diagram
    add_node: function(){
        var self = this;
        var title = _t('Activity');
        var pop = new instance.web.form.SelectCreatePopup(self);
        pop.select_element(
            self.node,
            {
                title: _t("Create:") + title,
                initial_view: 'form',
                disable_multiple_selection: true
            },
            self.dataset.domain,
            self.context || self.dataset.context
        );
        pop.on_select_elements.add_last(function(element_ids) {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });

        var form_controller = pop.view_form;
        var form_fields = [this.parent_field];

        form_controller.on("load_record", self, function(){
            _.each(form_fields, function(fld) {
                if (!(fld in form_controller.fields)) { return; }
                var field = form_controller.fields[fld];
                field.set_value(self.id);
                field.dirty = true;
            });
        });
    },

    // Creates a popup to edit the connector of id connector_id
    edit_connector: function(connector_id){
        var self = this;
        var title = _t('Transition');
        var pop = new instance.web.form.FormOpenPopup(self);
        pop.show_element(
            self.connector,
            parseInt(connector_id,10),      //FIXME Isn't connector_id supposed to be an int ?
            self.context || self.dataset.context,
            {
                title: _t("Open: ") + title
            }
        );
        pop.on('on_write_complete', self, function() {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });
    },

    // Creates a popup to add a connector from node_source_id to node_dest_id.
    // dummy_cuteedge if not null, will be removed form the graph after the popup is closed.
    add_connector: function(node_source_id, node_dest_id, dummy_cuteedge){
        var self = this;
        var title = _t('Transition');
        var pop = new instance.web.form.SelectCreatePopup(self);

        pop.select_element(
            self.connector,
            {
                title: _t("Create:") + title,
                initial_view: 'form',
                disable_multiple_selection: true
            },
            this.dataset.domain,
            this.context || this.dataset.context
        );

        pop.on_select_elements.add_last(function(element_ids) {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });
        // We want to destroy the dummy edge after a creation cancel. This destroys it even if we save the changes.
        // This is not a problem since the diagram is completely redrawn on saved changes.
        pop.$el.bind("dialogbeforeclose",function(){
            if(dummy_cuteedge){
                dummy_cuteedge.remove();
            }
        });

        var form_controller = pop.view_form;

       form_controller.on("load_record", self, function(){
            form_controller.fields[self.connectors.attrs.source].set_value(node_source_id);
            form_controller.fields[self.connectors.attrs.source].dirty = true;
            form_controller.fields[self.connectors.attrs.destination].set_value(node_dest_id);
            form_controller.fields[self.connectors.attrs.destination].dirty = true;
       });
    },

    on_pager_action: function(action) {
        switch (action) {
            case 'first':
                this.dataset.index = 0;
                break;
            case 'previous':
                this.dataset.previous();
                break;
            case 'next':
                this.dataset.next();
                break;
            case 'last':
                this.dataset.index = this.dataset.ids.length - 1;
                break;
        }
        var loaded = this.dataset.read_index(_.keys(this.fields_view.fields))
                .pipe(this.on_diagram_loaded);
        this.do_update_pager();
        return loaded;
    },

    do_update_pager: function(hide_index) {
        var $pager = this.$el.find('div.oe_diagram_pager');
        var index = hide_index ? '-' : this.dataset.index + 1;
        if(!this.dataset.count) {
            this.dataset.count = this.dataset.ids.length;
        }
        $pager.find('span.oe_pager_index').html(index);
        $pager.find('span.oe_pager_count').html(this.dataset.count);
    },

    do_show: function() {
        this.do_push_state({});
        return $.when(this._super(), this.on_pager_action('reload'));
    }
});
};

// vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax:
<commit_msg>[FIX]change event name<commit_after>/*---------------------------------------------------------
 * OpenERP diagram library
 *---------------------------------------------------------*/

openerp.web_diagram = function (instance) {
var QWeb = instance.web.qweb,
      _t = instance.web._t,
     _lt = instance.web._lt;
instance.web.views.add('diagram', 'instance.web.DiagramView');
instance.web.DiagramView = instance.web.View.extend({
    display_name: _lt('Diagram'),
    searchable: false,
    init: function(parent, dataset, view_id, options) {
        this._super(parent);
        this.set_default_options(options);
        this.view_manager = parent;
        this.dataset = dataset;
        this.model = this.dataset.model;
        this.view_id = view_id;
        this.domain = this.dataset._domain || [];
        this.context = {};
        this.ids = this.dataset.ids;
    },
    start: function() {
        return this.rpc("/web_diagram/diagram/load", {"model": this.model, "view_id": this.view_id}, this.on_loaded);
    },

    toTitleCase: function(str) {
        return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    },

    on_loaded: function(result) {

        var self = this;
        if(this.ids && this.ids.length) {
            this.id = this.ids[self.dataset.index || 0];
        }

        this.fields_view = result.fields_view,
        this.view_id = this.fields_view.view_id,
        this.fields = this.fields_view.fields,
        this.nodes = this.fields_view.arch.children[0],
        this.connectors = this.fields_view.arch.children[1],
        this.node = this.nodes.attrs.object,
        this.connector = this.connectors.attrs.object;
        this.labels = _.filter(this.fields_view.arch.children, function(label) {
            return label.tag == "label";
        });

        this.$el.html(QWeb.render("DiagramView", {'widget': this}));
        this.$el.addClass(this.fields_view.arch.attrs['class']);

        _.each(self.labels,function(label){
            html_label = '
' + label.attrs.string + "
";
            self.$el.find('.oe_diagram_header').append(html_label);
        })

        this.$el.find('div.oe_diagram_pager button[data-pager-action]').click(function() {
            var action = $(this).data('pager-action');
            self.on_pager_action(action);
        });

        this.do_update_pager();

        // New Node,Edge
        this.$el.find('#new_node.oe_diagram_button_new').click(function(){self.add_node();});

        if(this.id) {
            self.get_diagram_info();
        }

    },

    get_diagram_info: function() {
        var self = this;
        var params = {
            'id': this.id,
            'model': this.model,
            'node': this.node,
            'connector': this.connector,
            'bgcolor': this.nodes.attrs.bgcolor,
            'shape': this.nodes.attrs.shape,
            'src_node': this.connectors.attrs.source,
            'des_node': this.connectors.attrs.destination,
            'label': this.connectors.attrs.label || false,
            'visible_nodes': [],
            'invisible_nodes': [],
            'node_fields': [],
            'connectors': [],
            'connectors_fields': []
        };

        _.each(this.nodes.children, function(child) {
            if(child.attrs.invisible == '1')
                params['invisible_nodes'].push(child.attrs.name);
            else {
                params['visible_nodes'].push(child.attrs.name);
                params['node_fields'].push(self.fields[child.attrs.name]['string']|| this.toTitleCase(child.attrs.name));
            }
        });

        _.each(this.connectors.children, function(conn) {
            params['connectors_fields'].push(self.fields[conn.attrs.name]['string']|| this.toTitleCase(conn.attrs.name));
            params['connectors'].push(conn.attrs.name);
        });

        this.rpc(
            '/web_diagram/diagram/get_diagram_info',params).then(function(result) {
                self.draw_diagram(result);
            }
        );
    },

    on_diagram_loaded: function(record) {
        var id_record = record['id'];
        if(id_record) {
            this.id = id_record;
            this.get_diagram_info();
        }
    },

    // Set-up the drawing elements of the diagram
    draw_diagram: function(result) {
        var self = this;
        var res_nodes  = result['nodes'];
        var res_edges  = result['conn'];
        this.parent_field = result.parent_field;
        this.$el.find('h3.oe_diagram_title').text(result.name);

        var id_to_node = {};

        var style = {
            edge_color: "#A0A0A0",
            edge_label_color: "#555",
            edge_label_font_size: 10,
            edge_width: 2,
            edge_spacing: 100,
            edge_loop_radius: 100,

            node_label_color: "#333",
            node_label_font_size: 12,
            node_outline_color: "#333",
            node_outline_width: 1,
            node_selected_color: "#0097BE",
            node_selected_width: 2,
            node_size_x: 110,
            node_size_y: 80,
            connector_active_color: "#FFF",
            connector_radius: 4,

            close_button_radius: 8,
            close_button_color: "#333",
            close_button_x_color: "#FFF",

            gray: "#DCDCDC",
            white: "#FFF",

            viewport_margin: 50
        };

        // remove previous diagram
        var canvas = self.$el.find('div.oe_diagram_diagram')
                             .empty().get(0);

        var r  = new Raphael(canvas, '100%','100%');

        var graph  = new CuteGraph(r,style,canvas.parentNode);

        var confirm_dialog = $('#dialog').dialog({
            autoOpen: false,
            title: _t("Are you sure?") });

        _.each(res_nodes, function(node) {
            var n = new CuteNode(
                graph,
                node.x + 50,  //FIXME the +50 should be in the layout algorithm
                node.y + 50,
                CuteGraph.wordwrap(node.name, 14),
                node.shape === 'rectangle' ? 'rect' : 'circle',
                node.color === 'white' ? style.white : style.gray);

            n.id = node.id;
            id_to_node[node.id] = n;
        });

        _.each(res_edges, function(edge) {
            var e =  new CuteEdge(
                graph,
                CuteGraph.wordwrap(edge.signal, 32),
                id_to_node[edge.s_id],
                id_to_node[edge.d_id] || id_to_node[edge.s_id]  );  //WORKAROUND
            e.id = edge.id;
        });

        CuteNode.double_click_callback = function(cutenode){
            self.edit_node(cutenode.id);
        };
        var i = 0;
        CuteNode.destruction_callback = function(cutenode){
            if(!confirm(_t("Deleting this node cannot be undone.\nIt will also delete all connected transitions.\n\nAre you sure ?"))){
                return $.Deferred().reject().promise();
            }
            return new instance.web.DataSet(self,self.node).unlink([cutenode.id]);
        };
        CuteEdge.double_click_callback = function(cuteedge){
            self.edit_connector(cuteedge.id);
        };

        CuteEdge.creation_callback = function(node_start, node_end){
            return {label:_t("")};
        };
        CuteEdge.new_edge_callback = function(cuteedge){
            self.add_connector(cuteedge.get_start().id,
                               cuteedge.get_end().id,
                               cuteedge);
        };
        CuteEdge.destruction_callback = function(cuteedge){
            if(!confirm(_t("Deleting this transition cannot be undone.\n\nAre you sure ?"))){
                return $.Deferred().reject().promise();
            }
            return new instance.web.DataSet(self,self.connector).unlink([cuteedge.id]);
        };

    },

    // Creates a popup to edit the content of the node with id node_id
    edit_node: function(node_id){
        var self = this;
        var title = _t('Activity');
        var pop = new instance.web.form.FormOpenPopup(self);

        pop.show_element(
                self.node,
                node_id,
                self.context || self.dataset.context,
                {
                    title: _t("Open: ") + title
                }
            );

        pop.on('write_completed', self, function() {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
            });

        var form_fields = [self.parent_field];
        var form_controller = pop.view_form;

       form_controller.on("load_record", self, function(){
            _.each(form_fields, function(fld) {
                if (!(fld in form_controller.fields)) { return; }
                var field = form_controller.fields[fld];
                field.$input.prop('disabled', true);
                field.$drop_down.unbind();
            });
         });

    },

    // Creates a popup to add a node to the diagram
    add_node: function(){
        var self = this;
        var title = _t('Activity');
        var pop = new instance.web.form.SelectCreatePopup(self);
        pop.select_element(
            self.node,
            {
                title: _t("Create:") + title,
                initial_view: 'form',
                disable_multiple_selection: true
            },
            self.dataset.domain,
            self.context || self.dataset.context
        );
        pop.on_select_elements.add_last(function(element_ids) {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });

        var form_controller = pop.view_form;
        var form_fields = [this.parent_field];

        form_controller.on("load_record", self, function(){
            _.each(form_fields, function(fld) {
                if (!(fld in form_controller.fields)) { return; }
                var field = form_controller.fields[fld];
                field.set_value(self.id);
                field.dirty = true;
            });
        });
    },

    // Creates a popup to edit the connector of id connector_id
    edit_connector: function(connector_id){
        var self = this;
        var title = _t('Transition');
        var pop = new instance.web.form.FormOpenPopup(self);
        pop.show_element(
            self.connector,
            parseInt(connector_id,10),      //FIXME Isn't connector_id supposed to be an int ?
            self.context || self.dataset.context,
            {
                title: _t("Open: ") + title
            }
        );
        pop.on('write_completed', self, function() {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });
    },

    // Creates a popup to add a connector from node_source_id to node_dest_id.
    // dummy_cuteedge if not null, will be removed form the graph after the popup is closed.
    add_connector: function(node_source_id, node_dest_id, dummy_cuteedge){
        var self = this;
        var title = _t('Transition');
        var pop = new instance.web.form.SelectCreatePopup(self);

        pop.select_element(
            self.connector,
            {
                title: _t("Create:") + title,
                initial_view: 'form',
                disable_multiple_selection: true
            },
            this.dataset.domain,
            this.context || this.dataset.context
        );

        pop.on_select_elements.add_last(function(element_ids) {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });
        // We want to destroy the dummy edge after a creation cancel. This destroys it even if we save the changes.
        // This is not a problem since the diagram is completely redrawn on saved changes.
        pop.$el.bind("dialogbeforeclose",function(){
            if(dummy_cuteedge){
                dummy_cuteedge.remove();
            }
        });

        var form_controller = pop.view_form;

       form_controller.on("load_record", self, function(){
            form_controller.fields[self.connectors.attrs.source].set_value(node_source_id);
            form_controller.fields[self.connectors.attrs.source].dirty = true;
            form_controller.fields[self.connectors.attrs.destination].set_value(node_dest_id);
            form_controller.fields[self.connectors.attrs.destination].dirty = true;
       });
    },

    on_pager_action: function(action) {
        switch (action) {
            case 'first':
                this.dataset.index = 0;
                break;
            case 'previous':
                this.dataset.previous();
                break;
            case 'next':
                this.dataset.next();
                break;
            case 'last':
                this.dataset.index = this.dataset.ids.length - 1;
                break;
        }
        var loaded = this.dataset.read_index(_.keys(this.fields_view.fields))
                .pipe(this.on_diagram_loaded);
        this.do_update_pager();
        return loaded;
    },

    do_update_pager: function(hide_index) {
        var $pager = this.$el.find('div.oe_diagram_pager');
        var index = hide_index ? '-' : this.dataset.index + 1;
        if(!this.dataset.count) {
            this.dataset.count = this.dataset.ids.length;
        }
        $pager.find('span.oe_pager_index').html(index);
        $pager.find('span.oe_pager_count').html(this.dataset.count);
    },

    do_show: function() {
        this.do_push_state({});
        return $.when(this._super(), this.on_pager_action('reload'));
    }
});
};

// vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax:
<|endoftext|>


<commit_before>fixScale = function(doc) {

	var addEvent = 'addEventListener',
	    type = 'gesturestart',
	    qsa = 'querySelectorAll',
	    scales = [1, 1],
	    meta = qsa in doc ? doc[qsa]('meta[name=viewport]') : [];

	function fix() {
		meta.content = 'width=device-width,minimum-scale=' + scales[0] + ',maximum-scale=' + scales[1];
		doc.removeEventListener(type, fix, true);
	}

	if ((meta = meta[meta.length - 1]) && addEvent in doc) {
		fix();
		scales = [.25, 1.6];
		doc[addEvent](type, fix, true);
	}

};<commit_msg>Delete scale.fix.js<commit_after><|endoftext|>


<commit_before>var channelstreamApp = angular.module('channelstreamApp', []);

channelstreamApp.controller('chatCtl', function ($scope, $http) {
    $scope.user = {
        username: 'user_' + Math.round(Math.random() * 10000)
    };
    $scope.channels = ['pub_chan', 'pub_chan2'];
    $scope.selected_channel = {value: $scope.channels[0]}
    $scope.stream = [];
    $scope.conn_id = null;
    $scope.websocket = null;

    var use_websocket = false;

    var webapp_url = window.location.toString();
    var ws_url = webapp_url.replace('/demo', '').replace('http://', 'ws://');
    var longpoll_url = webapp_url.replace('/demo', '').replace('http://', '//');

    $scope.subscribe_channel = function () {
        var json_data = {
            channels: ['notify'],
            conn_id: $scope.conn_id
        };
        $http({
            method: 'POST',
            url: webapp_url + '/subscribe',
            data: json_data
        }).
            success(function (data, status, headers, config) {
                $scope.channels = data;
            }).
            error(function (data, status, headers, config) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
            });
    }

    $scope.send_message = function () {
        var json_data = {
            message: $scope.message,
            channel: $scope.selected_channel.value,
            user: $scope.user.username
        };
        $http({method: 'POST', url: webapp_url + '/message', data: json_data}).
            success(function (data, status, headers, config) {
                $scope.message = ''
            }).
            error(function (data, status, headers, config) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
            });
    }

    var on_message = function (data) {
        console.log('message');
        $scope.$apply(function (scope) {
            _.each(data, function (message) {
                if (scope.stream.length > 10) {
                    scope.stream.shift();
                }
                scope.stream.push(message);

            });
        });
    }
    var on_close = function (event) {
        console.log('closed');
        setTimeout(authorize, 5000);
    }
    var on_error = function () {
        console.log('error');
    }
    var on_open = function (event) {
        console.log('open');
    }
    var json_data = {
        'user': $scope.user.username,
        'channels': $scope.channels
    }

    var poll = function (url) {
        $http({
            method: 'GET',
            url: longpoll_url + '/listen?conn_id=' + $scope.conn_id
        }).
            success(function (data, status, headers, config) {
                console.log(data);
                setTimeout(function () {
                    on_message(data)
                }, 0);
                poll(url);
            }).
            error(function (data, status, headers, config) {
                on_close()
            });
    };

    var connect = function (use_websocket) {
        if (use_websocket) {
            var url = ws_url + '/ws?conn_id=' + $scope.conn_id;
            console.log(url);
            $scope.websocket = new WebSocket(url);
            $scope.websocket.onopen = on_open;
            $scope.websocket.onclose = on_close;
            $scope.websocket.onerror = on_error;
            $scope.websocket.onmessage = function (event) {
                on_message(JSON.parse(event.data));
            };
        }
        else {
            var url = longpoll_url + '/listen?conn_id=' + $scope.conn_id;
            console.log(url);
            poll(url);
        }
    }

    var authorize = function () {
        $http({method: 'POST', url: webapp_url + '/connect', data: json_data}).
            success(function (data, status, headers, config) {
                $scope.conn_id = data.conn_id;
                connect(use_websocket);
            }).
            error(function (data, status, headers, config) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
            });
    }

    authorize();

});
<commit_msg>enable websockets again<commit_after>var channelstreamApp = angular.module('channelstreamApp', []);

channelstreamApp.controller('chatCtl', function ($scope, $http) {
    $scope.user = {
        username: 'user_' + Math.round(Math.random() * 10000)
    };
    $scope.channels = ['pub_chan', 'pub_chan2'];
    $scope.selected_channel = {value: $scope.channels[0]}
    $scope.stream = [];
    $scope.conn_id = null;
    $scope.websocket = null;

    var use_websocket = true;

    var webapp_url = window.location.toString();
    var ws_url = webapp_url.replace('/demo', '').replace('http://', 'ws://');
    var longpoll_url = webapp_url.replace('/demo', '').replace('http://', '//');

    $scope.subscribe_channel = function () {
        var json_data = {
            channels: ['notify'],
            conn_id: $scope.conn_id
        };
        $http({
            method: 'POST',
            url: webapp_url + '/subscribe',
            data: json_data
        }).
            success(function (data, status, headers, config) {
                $scope.channels = data;
            }).
            error(function (data, status, headers, config) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
            });
    }

    $scope.send_message = function () {
        var json_data = {
            message: $scope.message,
            channel: $scope.selected_channel.value,
            user: $scope.user.username
        };
        $http({method: 'POST', url: webapp_url + '/message', data: json_data}).
            success(function (data, status, headers, config) {
                $scope.message = ''
            }).
            error(function (data, status, headers, config) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
            });
    }

    var on_message = function (data) {
        console.log('message');
        $scope.$apply(function (scope) {
            _.each(data, function (message) {
                if (scope.stream.length > 10) {
                    scope.stream.shift();
                }
                scope.stream.push(message);

            });
        });
    }
    var on_close = function (event) {
        console.log('closed');
        setTimeout(authorize, 5000);
    }
    var on_error = function () {
        console.log('error');
    }
    var on_open = function (event) {
        console.log('open');
    }
    var json_data = {
        'user': $scope.user.username,
        'channels': $scope.channels
    }

    var poll = function (url) {
        $http({
            method: 'GET',
            url: longpoll_url + '/listen?conn_id=' + $scope.conn_id
        }).
            success(function (data, status, headers, config) {
                console.log(data);
                setTimeout(function () {
                    on_message(data)
                }, 0);
                poll(url);
            }).
            error(function (data, status, headers, config) {
                on_close()
            });
    };

    var connect = function (use_websocket) {
        if (use_websocket) {
            var url = ws_url + '/ws?conn_id=' + $scope.conn_id;
            console.log(url);
            $scope.websocket = new WebSocket(url);
            $scope.websocket.onopen = on_open;
            $scope.websocket.onclose = on_close;
            $scope.websocket.onerror = on_error;
            $scope.websocket.onmessage = function (event) {
                on_message(JSON.parse(event.data));
            };
        }
        else {
            var url = longpoll_url + '/listen?conn_id=' + $scope.conn_id;
            console.log(url);
            poll(url);
        }
    }

    var authorize = function () {
        $http({method: 'POST', url: webapp_url + '/connect', data: json_data}).
            success(function (data, status, headers, config) {
                $scope.conn_id = data.conn_id;
                connect(use_websocket);
            }).
            error(function (data, status, headers, config) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
            });
    }

    authorize();

});
<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var validator = require('validator');

var Schema = mongoose.Schema;

var DocSchema = new Schema({
    created: {
        type: Date,
        default: Date.now
    },
    updated: {
        type: Date,
        default: Date.now
    },
    email: {
        type: String,
        required: true,
        validate: [ validator.isEmail, 'invalid email' ]
    }
});

DocSchema.statics = {
    load: function(id, cb) {
        this.findOne({
            _id: id
        }).exec(cb);
    }
};

mongoose.model('Doc', DocSchema);
<commit_msg>DocSchema<commit_after>var mongoose = require('mongoose');
var validator = require('validator');

var Schema = mongoose.Schema;

var DocSchema = new Schema({
    created: {
        type: Date,
        default: Date.now
    },
    updated: {
        type: Date,
        default: Date.now
    },
    email: {
        type: String,
        required: true,
        validate: [ validator.isEmail, 'invalid email' ]
    },
    projectName: {
      type: String,
      required: true
    },
    //Toggle editable boolean according to project status
    editable: {
      type: Boolean,
      required: true
    }
    //Part1 study description - English
    part1english: {
      q01: String, //Title of project = projectName; prefill with projectName; edit if experimenter makes changes
      q02: String, //Name of the lead researcher, position and lab
      q03: String, //Time scale of data collection (range)
      q04: String, //theme and purpose of the study
      q05: String, //procedure
      q06: String, //duration
      q07: String, //all risks
      q08: String, //benefits
    },
    //Part1 study description - German
    part1german: {
      q01: String, //Title of project = projectName; maybe not required
      q02: String, //Name of the lead researcher, position and lab
      q03: String, //Time scale of data collection (range)
      q04: String, //theme and purpose of the study
      q05: String, //procedure
      q06: String, //duration
      q07: String, //all risks
      q08: String, //benefits
    },
    //Part2 ethics checklist
    part2ethics: {
      q01: { //
        checkbox: String, //[yes,no]
        comment: String, //comment if checked yes
        review: String //reviewers comment on experimenters answer
      },
      q02: { //
        checkbox: String, //[yes,no]
        comment: String, //comment if checked yes
        review: String //reviewers comment on experimenters answer
      },
      q03: { //
        checkbox: String, //[yes,no]
        comment: String, //comment if checked yes
        review: String //reviewers comment on experimenters answer
      },
      q04: { //
        checkbox: String, //[yes,no]
        comment: String, //comment if checked yes
        review: String //reviewers comment on experimenters answer
      },
      q05: { //
        checkbox: String, //[yes,no]
        comment: String, //comment if checked yes
        review: String //reviewers comment on experimenters answer
      },
      q06: { //
        checkbox: String, //[yes,no]
        comment: String, //comment if checked yes
        review: String //reviewers comment on experimenters answer
      },
      q07: { //
        checkbox: String, //[yes,no]
        comment: String, //comment if checked yes
        review: String //reviewers comment on experimenters answer
      },
      q08: { //
        checkbox: String, //[yes,no]
        comment: String, //comment if checked yes
        review: String //reviewers comment on experimenters answer
      },
      q09: { //
        checkbox: String, //[yes,no]
        comment: String, //comment if checked yes
        review: String //reviewers comment on experimenters answer
      },
      q10: { //
        checkbox: String, //[yes,no]
        comment: String, //comment if checked yes
        review: String //reviewers comment on experimenters answer
      },
      q11: { //
        checkbox: String, //[yes,no]
        q11_1: {
          checkbox: String, //[yes,no]
          comment: String, //comment if checked yes
        }
        review: String //reviewers comment on experimenters answer
      },
      q12: { //
        checkbox: String, //[yes,no]
        comment: String, //comment if checked yes
        review: String //reviewers comment on experimenters answer
      },
      q13: { //
        checkbox: String, //[yes,no]
        comment: String, //comment if checked yes
        review: String //reviewers comment on experimenters answer
      },
      generalComment: String
    }
});

DocSchema.statics = {
    load: function(id, cb) {
        this.findOne({
            _id: id
        }).exec(cb);
    }
};

mongoose.model('Doc', DocSchema);
<|endoftext|>


<commit_before>var found = [];
var words = [];

function find_words() {
    var letters = "dog";
    var reg = new RegExp("^(?!.*?(.).*?\1)["+letters+"]*["+letters+"]*$");

    var f = [];
    for ( var i in words ) {
      w = words[i];

      contains = w.match(reg);

      if ( contains ) {
        f.push(w);
      }
    }

  for ( var i in f ) {
	for ( var j in letters ) {
		var num_letters = letters.split(letters[j]).length -1;
		var num_of_occurences = f[i].split(letters[j]).length-1;
		if ( num_of_occurences <= num_letters ) {
			found.push(f[i]);
		}
	}
  }

  found.sort(function(a, b){
    return b.length - a.length; // ASC -> a - b; DESC -> b - a
  });

}

var client = new XMLHttpRequest();

client.open('GET', 'word-list-en.txt');

client.onreadystatechange = function() {

  	if ( client.readyState==4 && client.status==200 ) {
	  	file = client.responseText;
		words = file.split(/\n\r|\n/);

		find_words();
	}
}

client.send();

<commit_msg>try some stuff<commit_after>var found = [];
var words = [];

function find_words() {
    var letters = "dog";
    var reg = new RegExp("^(?!.*?(.).*?\1)["+letters+"]*["+letters+"]*$");

    var f = [];
    for ( var i in words ) {
      w = words[i];

      contains = w.match(reg);

      if ( contains ) {
        f.push(w);
      }
    }

  for ( var i in f ) {
  	var dont_add = false;
	for ( var j in letters ) {
		var num_letters = letters.split(letters[j]).length -1;
		var num_of_occurences = f[i].split(letters[j]).length-1;

		if ( num_of_occurences > num_letters ) {
			dont_add = true;
		}
	}

	if ( !dont_add ) {
		found.push(f[i]);
	}
  }

  found.sort(function(a, b){
    return b.length - a.length; // ASC -> a - b; DESC -> b - a
  });

}

var client = new XMLHttpRequest();

client.open('GET', 'word-list-en.txt');

client.onreadystatechange = function() {

  	if ( client.readyState==4 && client.status==200 ) {
	  	file = client.responseText;
		words = file.split(/\n\r|\n/);

		find_words();
	}
}

client.send();

<|endoftext|>


<commit_before>// Meteor._localStorage is not an ideal name, but we can change it later.

if (window.localStorage) {
  // Let's test to make sure that localStorage actually works. For example, in
  // Safari with private browsing on, window.localStorage exists but actually
  // trying to use it throws.

  var key = '_localstorage_test_' + Random.id();
  var retrieved;
  try {
    window.localStorage.setItem(key, key);
    retrieved = window.localStorage.getItem(key);
    window.localStorage.removeItem(key);
  } catch (e) {
    // ... ignore
  }
  if (key === retrieved) {
    Meteor._localStorage = {
      getItem: function (key) {
        return window.localStorage.getItem(key);
      },
      setItem: function (key, value) {
        window.localStorage.setItem(key, value);
      },
      removeItem: function (key) {
        window.localStorage.removeItem(key);
      }
    };
  }
}

// XXX eliminate dependency on jQuery, detect browsers ourselves
// Else, if we are on IE, which support userData
if (!Meteor._localStorage && $.browser.msie) {
  var userdata = document.createElement('span'); // could be anything
  userdata.style.behavior = 'url("#default#userData")';
  userdata.id = 'localstorage-helper';
  userdata.style.display = 'none';
  document.getElementsByTagName("head")[0].appendChild(userdata);

  var userdataKey = 'localStorage';
  userdata.load(userdataKey);

  Meteor._localStorage = {
    setItem: function (key, val) {
      userdata.setAttribute(key, val);
      userdata.save(userdataKey);
    },

    removeItem: function (key) {
      userdata.removeAttribute(key);
      userdata.save(userdataKey);
    },

    getItem: function (key) {
      userdata.load(userdataKey);
      return userdata.getAttribute(key);
    }
  };
}

if (!Meteor._localStorage) {
  Meteor._debug(
    "You are running a browser with no localStorage or userData "
      + "support. Logging in from one tab will not cause another "
      + "tab to be logged in.");

  Meteor._localStorage = {
    _data: {},

    setItem: function (key, val) {
      this._data[key] = val;
    },
    removeItem: function (key) {
      delete this._data[key];
    },
    getItem: function (key) {
      var value = this._data[key];
      if (value === undefined)
        return null;
      else
        return value;
    }
  };
}
<commit_msg>Kill malfunctioning shim for localStorage in IE 7<commit_after>// Meteor._localStorage is not an ideal name, but we can change it later.

if (window.localStorage) {
  // Let's test to make sure that localStorage actually works. For example, in
  // Safari with private browsing on, window.localStorage exists but actually
  // trying to use it throws.

  var key = '_localstorage_test_' + Random.id();
  var retrieved;
  try {
    window.localStorage.setItem(key, key);
    retrieved = window.localStorage.getItem(key);
    window.localStorage.removeItem(key);
  } catch (e) {
    // ... ignore
  }
  if (key === retrieved) {
    Meteor._localStorage = {
      getItem: function (key) {
        return window.localStorage.getItem(key);
      },
      setItem: function (key, value) {
        window.localStorage.setItem(key, value);
      },
      removeItem: function (key) {
        window.localStorage.removeItem(key);
      }
    };
  }
}

if (!Meteor._localStorage) {
  Meteor._debug(
    "You are running a browser with no localStorage or userData "
      + "support. Logging in from one tab will not cause another "
      + "tab to be logged in.");

  Meteor._localStorage = {
    _data: {},

    setItem: function (key, val) {
      this._data[key] = val;
    },
    removeItem: function (key) {
      delete this._data[key];
    },
    getItem: function (key) {
      var value = this._data[key];
      if (value === undefined)
        return null;
      else
        return value;
    }
  };
}
<|endoftext|>


<commit_before>import { observer } from 'binary-common-utils/lib/observer'
import CustomApi from 'binary-common-utils/lib/customApi'
import { getToken } from 'binary-common-utils/lib/storageManager'
import _ from 'underscore'
import PurchaseCtrl from './purchaseCtrl'
import _Symbol from './symbol'
import { number as expectNumber, barrierOffset as expectBarrierOffset } from '../../common/expect'

const decorateTradeOptions = (tradeOption, otherOptions = {}) => {
  const option = {
    duration_unit: tradeOption.duration_unit,
    basis: tradeOption.basis,
    currency: tradeOption.currency,
    symbol: tradeOption.symbol,
    ...otherOptions,
  }
  option.duration = expectNumber('duration', tradeOption.duration)
  option.amount = expectNumber('amount', tradeOption.amount).toFixed(2)
  if ('prediction' in tradeOption) {
    option.barrier = expectNumber('prediction', tradeOption.prediction)
  }
  if ('barrierOffset' in tradeOption) {
    option.barrier = expectBarrierOffset(tradeOption.barrierOffset)
  }
  if ('secondBarrierOffset' in tradeOption) {
    option.barrier2 = expectBarrierOffset(tradeOption.secondBarrierOffset)
  }
  return option
}

export default class Bot {
  constructor(api = null) {
    this.ticks = []
    this.candles = []
    this.currentCandleInterval = 0
    this.currentToken = ''
    this.balanceStr = ''
    this.currentSymbol = ''
    this.unregisterOnFinish = []
    this.totalProfit = 0
    this.totalRuns = 0
    this.totalWins = 0
    this.totalLosses = 0
    this.totalStake = 0
    this.totalPayout = 0
    this.balance = 0
    this.api = (api === null) ? new CustomApi() : api
    this.symbol = new _Symbol(this.api)
    this.initPromise = this.symbol.initPromise
    this.shouldRestartOnError = () => this.tradeOption && this.tradeOption.restartOnError
    this.restartOnError = () => {
      if (this.shouldRestartOnError()) {
        this.start(...this.startArgs)
      }
    }
  }
  start(...args) {
    const [token, tradeOption, beforePurchase, duringPurchase, afterPurchase, sameTrade, tickAnalysisList = []] = args
    this.startArgs = args
    if (!this.purchaseCtrl || sameTrade) {
      if (this.purchaseCtrl) {
        this.purchaseCtrl.destroy()
      }
      this.purchaseCtrl = new PurchaseCtrl(this.api, beforePurchase, duringPurchase, afterPurchase)
      this.tickAnalysisList = tickAnalysisList
      this.tradeOption = tradeOption
      observer.emit('log.bot.start', {
        again: !!sameTrade,
      })
      const accountName = getToken(token).account_name
      if (typeof amplitude !== 'undefined') {
        amplitude.getInstance().setUserId(accountName)
      }
      if (typeof trackJs !== 'undefined') {
        trackJs.configure({
          userId: accountName,
        })
      }
      if (sameTrade) {
        this.startTrading()
      } else {
        const promises = []
        if (this.currentToken !== token) {
          promises.push(this.login(token))
        }
        if (!_.isEmpty(this.tradeOption)) {
          if (this.tradeOption.symbol !== this.currentSymbol) {
            observer.unregisterAll('api.ohlc')
            observer.unregisterAll('api.tick')
            promises.push(this.subscribeToTickHistory())
            promises.push(this.subscribeToCandles())
          } else if (this.tradeOption.candleInterval !== this.currentCandleInterval) {
            observer.unregisterAll('api.ohlc')
            promises.push(this.subscribeToCandles())
          }
        }
        Promise.all(promises).then(() => {
          this.startTrading()
        }).catch((error) => {
          if (error.name === 'BlocklyError') {
            // pass
          } else {
            throw error
          }
        })
      }
    }
  }
  login(token) {
    return new Promise((resolve) => {
      const apiAuthorize = () => {
        observer.emit('log.bot.login', {
          lastToken: this.currentToken,
          token,
        })
        this.currentToken = token
        this.subscribeToBalance()
        this.observeStreams()
        resolve()
      }
      observer.register('api.authorize', apiAuthorize, true, {
        type: 'authorize',
        unregister: [['api.authorize', apiAuthorize]],
      }, true)
      this.api.authorize(token)
    })
  }
  setTradeOptions() {
    this.tradeOptions = []
    if (!_.isEmpty(this.tradeOption)) {
      this.pip = this.symbol.activeSymbols.getSymbols()[this.tradeOption.symbol.toLowerCase()].pip
      for (const type of JSON.parse(this.tradeOption.contractTypes)) {
        this.tradeOptions.push(decorateTradeOptions(this.tradeOption, {
          contract_type: type,
        }))
      }
    }
  }
  subscribeToBalance() {
    const apiBalance = (balance) => {
      this.balance = balance.balance
      this.balanceStr = `${Number(balance.balance).toFixed(2)} ${balance.currency}`
      observer.emit('bot.tradeInfo', {
        balance: this.balanceStr,
      })
    }
    observer.register('api.balance', apiBalance, false, {
      type: 'balance',
      unregister: [['api.balance', apiBalance]],
    })
    this.api.originalApi.send({
      forget_all: 'balance',
    }).then(() => this.api.balance())
  }
  subscribeToCandles() {
    return new Promise((resolve) => {
      const apiCandles = (candles) => {
        this.observeOhlc()
        this.currentCandleInterval = this.tradeOption.candleInterval
        this.candles = candles
        resolve()
      }
      observer.register('api.candles', apiCandles, true, {
        type: 'candles',
        unregister: ['api.ohlc', 'api.candles', 'api.tick', 'bot.tickUpdate'],
      })
      this.api.originalApi.unsubscribeFromAllCandles().then(() => 0, () => 0)
      this.api.history(this.tradeOption.symbol, {
        end: 'latest',
        count: 5000,
        granularity: this.tradeOption.candleInterval,
        style: 'candles',
        subscribe: 1,
      })
    })
  }
  subscribeToTickHistory() {
    return new Promise((resolve) => {
      const apiHistory = (history) => {
        this.observeTicks()
        this.currentSymbol = this.tradeOption.symbol
        this.ticks = history
        resolve()
      }
      observer.register('api.history', apiHistory, true, {
        type: 'history',
        unregister: [['api.history', apiHistory], 'api.tick',
          'bot.tickUpdate', 'api.ohlc', 'api.candles'],
      }, true)
      this.api.originalApi.unsubscribeFromAllTicks().then(() => 0, () => 0)
      this.api.history(this.tradeOption.symbol, {
        end: 'latest',
        count: 5000,
        subscribe: 1,
      })
    })
  }
  observeTicks() {
    if (!observer.isRegistered('api.tick')) {
      const apiTick = (tick) => {
        this.ticks = [...this.ticks, tick]
        this.ticks.splice(0, 1)
        let direction = ''
        const length = this.ticks.length
        const tick1 = this.ticks.slice(-1)[0]
        const tick2 = this.ticks.slice(-2)[0]
        if (length >= 2) {
          if (tick1.quote > tick2.quote) {
            direction = 'rise'
          }
          if (tick1.quote < tick2.quote) {
            direction = 'fall'
          }
        }
        const ticks = {
          direction,
          ticks: this.ticks,
          ohlc: this.candles,
        }
        for (const tickAnalysis of this.tickAnalysisList) {
          tickAnalysis.call({
            ticks,
          })
        }
        if (this.purchaseCtrl) {
          this.purchaseCtrl.updateTicks(ticks)
        }
        observer.emit('bot.tickUpdate', {
          ...ticks,
          pip: this.pip,
        })
      }
      observer.register('api.tick', apiTick)
    }
  }
  observeOhlc() {
    if (!observer.isRegistered('api.ohlc')) {
      const apiOHLC = (candle) => {
        if (this.candles.length && this.candles.slice(-1)[0].epoch === candle.epoch) {
          this.candles = [...this.candles.slice(0, -1), candle]
        } else {
          this.candles = [...this.candles, candle]
          this.candles.splice(0, 1)
        }
      }
      observer.register('api.ohlc', apiOHLC)
    }
  }
  observeTradeUpdate() {
    if (!observer.isRegistered('purchase.tradeUpdate')) {
      const beforePurchaseTradeUpdate = (contract) => {
        if (this.purchaseCtrl) {
          observer.emit('bot.tradeUpdate', contract)
        }
      }
      observer.register('purchase.tradeUpdate', beforePurchaseTradeUpdate)
    }
  }
  observeStreams() {
    this.observeTradeUpdate()
    this.observeTicks()
    this.observeOhlc()
  }
  subscribeProposals() {
    this.setTradeOptions()
    observer.unregisterAll('api.proposal')
    if (this.purchaseCtrl) {
      this.purchaseCtrl.setNumOfProposals(this.tradeOptions.length)
    }
    const apiProposal = (proposal) => {
      if (this.purchaseCtrl) {
        observer.emit('log.bot.proposal', proposal)
        this.purchaseCtrl.updateProposal(proposal)
      }
    }
    observer.register('api.proposal', apiProposal, false)
    this.unregisterOnFinish.push(['api.proposal', apiProposal])
    this.api.originalApi.unsubscribeFromAllProposals().then(() => {
      for (const tradeOption of this.tradeOptions) {
        this.api.proposal(tradeOption)
      }
    }, () => 0)
  }
  waitForBeforePurchaseFinish() {
    const beforePurchaseFinish = (contract) => {
      this.botFinish(contract)
    }
    observer.register('purchase.finish', beforePurchaseFinish, true, null, true)
    this.unregisterOnFinish.push(['purchase.finish', beforePurchaseFinish])
  }
  waitForTradePurchase() {
    const tradePurchase = (info) => {
      this.totalRuns += 1
      observer.emit('bot.tradeInfo', {
        totalRuns: this.totalRuns,
        transaction_ids: {
          buy: info.purchasedContract.transaction_id,
        },
        contract_type: info.contract.contract_type,
        buy_price: info.purchasedContract.buy_price,
      })
    }
    observer.register('trade.purchase', tradePurchase, true, null, true)
    this.unregisterOnFinish.push(['trade.purchase', tradePurchase])
  }
  startTrading() {
    this.waitForBeforePurchaseFinish()
    this.waitForTradePurchase()
    this.subscribeProposals()
  }
  updateTotals(contract) {
    const profit = +(Number(contract.sell_price) - Number(contract.buy_price)).toFixed(2)
    const user = getToken(this.currentToken)
    observer.emit('log.revenue', {
      user,
      profit,
      contract,
    })

    if (+profit > 0) {
      this.totalWins += 1
    } else if (+profit < 0) {
      this.totalLosses += 1
    }
    this.totalProfit = +(this.totalProfit + profit).toFixed(2)
    this.totalStake = +(this.totalStake + Number(contract.buy_price)).toFixed(2)
    this.totalPayout = +(this.totalPayout + Number(contract.sell_price)).toFixed(2)

    observer.emit('bot.tradeInfo', {
      totalProfit: this.totalProfit,
      totalWins: this.totalWins,
      totalLosses: this.totalLosses,
      totalStake: this.totalStake,
      totalPayout: this.totalPayout,
    })
  }
  botFinish(contract) {
    for (const obs of this.unregisterOnFinish) {
      observer.unregisterAll(...obs)
    }
    this.unregisterOnFinish = []
    this.updateTotals(contract)
    observer.emit('bot.finish', contract)
    // order matters
    this.purchaseCtrl.destroy()
    this.purchaseCtrl = null
  //
  }
  stop(contract) {
    if (!this.purchaseCtrl) {
      observer.emit('bot.stop', contract)
      return
    }
    for (const obs of this.unregisterOnFinish) {
      observer.unregisterAll(...obs)
    }
    this.unregisterOnFinish = []
    // order matters
    if (this.purchaseCtrl) {
      this.purchaseCtrl.destroy()
      this.purchaseCtrl = null
    }
    //
    this.api.originalApi.unsubscribeFromAllProposals().then(() => 0, () => 0)
    if (contract) {
      observer.emit('log.bot.stop', contract)
    }
    observer.emit('bot.stop', contract)
  }
}

export const bot = process.browser ? new Bot() : null
<commit_msg>start iff this.purchaseCtrl is not available<commit_after>import { observer } from 'binary-common-utils/lib/observer'
import CustomApi from 'binary-common-utils/lib/customApi'
import { getToken } from 'binary-common-utils/lib/storageManager'
import _ from 'underscore'
import PurchaseCtrl from './purchaseCtrl'
import _Symbol from './symbol'
import { number as expectNumber, barrierOffset as expectBarrierOffset } from '../../common/expect'

const decorateTradeOptions = (tradeOption, otherOptions = {}) => {
  const option = {
    duration_unit: tradeOption.duration_unit,
    basis: tradeOption.basis,
    currency: tradeOption.currency,
    symbol: tradeOption.symbol,
    ...otherOptions,
  }
  option.duration = expectNumber('duration', tradeOption.duration)
  option.amount = expectNumber('amount', tradeOption.amount).toFixed(2)
  if ('prediction' in tradeOption) {
    option.barrier = expectNumber('prediction', tradeOption.prediction)
  }
  if ('barrierOffset' in tradeOption) {
    option.barrier = expectBarrierOffset(tradeOption.barrierOffset)
  }
  if ('secondBarrierOffset' in tradeOption) {
    option.barrier2 = expectBarrierOffset(tradeOption.secondBarrierOffset)
  }
  return option
}

export default class Bot {
  constructor(api = null) {
    this.ticks = []
    this.candles = []
    this.currentCandleInterval = 0
    this.currentToken = ''
    this.balanceStr = ''
    this.currentSymbol = ''
    this.unregisterOnFinish = []
    this.totalProfit = 0
    this.totalRuns = 0
    this.totalWins = 0
    this.totalLosses = 0
    this.totalStake = 0
    this.totalPayout = 0
    this.balance = 0
    this.api = (api === null) ? new CustomApi() : api
    this.symbol = new _Symbol(this.api)
    this.initPromise = this.symbol.initPromise
    this.shouldRestartOnError = () => this.tradeOption && this.tradeOption.restartOnError
    this.restartOnError = () => {
      if (this.shouldRestartOnError()) {
        this.start(...this.startArgs)
      }
    }
  }
  start(...args) {
    const [token, tradeOption, beforePurchase, duringPurchase, afterPurchase, sameTrade, tickAnalysisList = []] = args
    this.startArgs = args
    if (!this.purchaseCtrl) {
      this.purchaseCtrl = new PurchaseCtrl(this.api, beforePurchase, duringPurchase, afterPurchase)
      this.tickAnalysisList = tickAnalysisList
      this.tradeOption = tradeOption
      observer.emit('log.bot.start', {
        again: !!sameTrade,
      })
      const accountName = getToken(token).account_name
      if (typeof amplitude !== 'undefined') {
        amplitude.getInstance().setUserId(accountName)
      }
      if (typeof trackJs !== 'undefined') {
        trackJs.configure({
          userId: accountName,
        })
      }
      if (sameTrade) {
        this.startTrading()
      } else {
        const promises = []
        if (this.currentToken !== token) {
          promises.push(this.login(token))
        }
        if (!_.isEmpty(this.tradeOption)) {
          if (this.tradeOption.symbol !== this.currentSymbol) {
            observer.unregisterAll('api.ohlc')
            observer.unregisterAll('api.tick')
            promises.push(this.subscribeToTickHistory())
            promises.push(this.subscribeToCandles())
          } else if (this.tradeOption.candleInterval !== this.currentCandleInterval) {
            observer.unregisterAll('api.ohlc')
            promises.push(this.subscribeToCandles())
          }
        }
        Promise.all(promises).then(() => {
          this.startTrading()
        }).catch((error) => {
          if (error.name === 'BlocklyError') {
            // pass
          } else {
            throw error
          }
        })
      }
    }
  }
  login(token) {
    return new Promise((resolve) => {
      const apiAuthorize = () => {
        observer.emit('log.bot.login', {
          lastToken: this.currentToken,
          token,
        })
        this.currentToken = token
        this.subscribeToBalance()
        this.observeStreams()
        resolve()
      }
      observer.register('api.authorize', apiAuthorize, true, {
        type: 'authorize',
        unregister: [['api.authorize', apiAuthorize]],
      }, true)
      this.api.authorize(token)
    })
  }
  setTradeOptions() {
    this.tradeOptions = []
    if (!_.isEmpty(this.tradeOption)) {
      this.pip = this.symbol.activeSymbols.getSymbols()[this.tradeOption.symbol.toLowerCase()].pip
      for (const type of JSON.parse(this.tradeOption.contractTypes)) {
        this.tradeOptions.push(decorateTradeOptions(this.tradeOption, {
          contract_type: type,
        }))
      }
    }
  }
  subscribeToBalance() {
    const apiBalance = (balance) => {
      this.balance = balance.balance
      this.balanceStr = `${Number(balance.balance).toFixed(2)} ${balance.currency}`
      observer.emit('bot.tradeInfo', {
        balance: this.balanceStr,
      })
    }
    observer.register('api.balance', apiBalance, false, {
      type: 'balance',
      unregister: [['api.balance', apiBalance]],
    })
    this.api.originalApi.send({
      forget_all: 'balance',
    }).then(() => this.api.balance())
  }
  subscribeToCandles() {
    return new Promise((resolve) => {
      const apiCandles = (candles) => {
        this.observeOhlc()
        this.currentCandleInterval = this.tradeOption.candleInterval
        this.candles = candles
        resolve()
      }
      observer.register('api.candles', apiCandles, true, {
        type: 'candles',
        unregister: ['api.ohlc', 'api.candles', 'api.tick', 'bot.tickUpdate'],
      })
      this.api.originalApi.unsubscribeFromAllCandles().then(() => 0, () => 0)
      this.api.history(this.tradeOption.symbol, {
        end: 'latest',
        count: 5000,
        granularity: this.tradeOption.candleInterval,
        style: 'candles',
        subscribe: 1,
      })
    })
  }
  subscribeToTickHistory() {
    return new Promise((resolve) => {
      const apiHistory = (history) => {
        this.observeTicks()
        this.currentSymbol = this.tradeOption.symbol
        this.ticks = history
        resolve()
      }
      observer.register('api.history', apiHistory, true, {
        type: 'history',
        unregister: [['api.history', apiHistory], 'api.tick',
          'bot.tickUpdate', 'api.ohlc', 'api.candles'],
      }, true)
      this.api.originalApi.unsubscribeFromAllTicks().then(() => 0, () => 0)
      this.api.history(this.tradeOption.symbol, {
        end: 'latest',
        count: 5000,
        subscribe: 1,
      })
    })
  }
  observeTicks() {
    if (!observer.isRegistered('api.tick')) {
      const apiTick = (tick) => {
        this.ticks = [...this.ticks, tick]
        this.ticks.splice(0, 1)
        let direction = ''
        const length = this.ticks.length
        const tick1 = this.ticks.slice(-1)[0]
        const tick2 = this.ticks.slice(-2)[0]
        if (length >= 2) {
          if (tick1.quote > tick2.quote) {
            direction = 'rise'
          }
          if (tick1.quote < tick2.quote) {
            direction = 'fall'
          }
        }
        const ticks = {
          direction,
          ticks: this.ticks,
          ohlc: this.candles,
        }
        for (const tickAnalysis of this.tickAnalysisList) {
          tickAnalysis.call({
            ticks,
          })
        }
        if (this.purchaseCtrl) {
          this.purchaseCtrl.updateTicks(ticks)
        }
        observer.emit('bot.tickUpdate', {
          ...ticks,
          pip: this.pip,
        })
      }
      observer.register('api.tick', apiTick)
    }
  }
  observeOhlc() {
    if (!observer.isRegistered('api.ohlc')) {
      const apiOHLC = (candle) => {
        if (this.candles.length && this.candles.slice(-1)[0].epoch === candle.epoch) {
          this.candles = [...this.candles.slice(0, -1), candle]
        } else {
          this.candles = [...this.candles, candle]
          this.candles.splice(0, 1)
        }
      }
      observer.register('api.ohlc', apiOHLC)
    }
  }
  observeTradeUpdate() {
    if (!observer.isRegistered('purchase.tradeUpdate')) {
      const beforePurchaseTradeUpdate = (contract) => {
        if (this.purchaseCtrl) {
          observer.emit('bot.tradeUpdate', contract)
        }
      }
      observer.register('purchase.tradeUpdate', beforePurchaseTradeUpdate)
    }
  }
  observeStreams() {
    this.observeTradeUpdate()
    this.observeTicks()
    this.observeOhlc()
  }
  subscribeProposals() {
    this.setTradeOptions()
    observer.unregisterAll('api.proposal')
    if (this.purchaseCtrl) {
      this.purchaseCtrl.setNumOfProposals(this.tradeOptions.length)
    }
    const apiProposal = (proposal) => {
      if (this.purchaseCtrl) {
        observer.emit('log.bot.proposal', proposal)
        this.purchaseCtrl.updateProposal(proposal)
      }
    }
    observer.register('api.proposal', apiProposal, false)
    this.unregisterOnFinish.push(['api.proposal', apiProposal])
    this.api.originalApi.unsubscribeFromAllProposals().then(() => {
      for (const tradeOption of this.tradeOptions) {
        this.api.proposal(tradeOption)
      }
    }, () => 0)
  }
  waitForBeforePurchaseFinish() {
    const beforePurchaseFinish = (contract) => {
      this.botFinish(contract)
    }
    observer.register('purchase.finish', beforePurchaseFinish, true, null, true)
    this.unregisterOnFinish.push(['purchase.finish', beforePurchaseFinish])
  }
  waitForTradePurchase() {
    const tradePurchase = (info) => {
      this.totalRuns += 1
      observer.emit('bot.tradeInfo', {
        totalRuns: this.totalRuns,
        transaction_ids: {
          buy: info.purchasedContract.transaction_id,
        },
        contract_type: info.contract.contract_type,
        buy_price: info.purchasedContract.buy_price,
      })
    }
    observer.register('trade.purchase', tradePurchase, true, null, true)
    this.unregisterOnFinish.push(['trade.purchase', tradePurchase])
  }
  startTrading() {
    this.waitForBeforePurchaseFinish()
    this.waitForTradePurchase()
    this.subscribeProposals()
  }
  updateTotals(contract) {
    const profit = +(Number(contract.sell_price) - Number(contract.buy_price)).toFixed(2)
    const user = getToken(this.currentToken)
    observer.emit('log.revenue', {
      user,
      profit,
      contract,
    })

    if (+profit > 0) {
      this.totalWins += 1
    } else if (+profit < 0) {
      this.totalLosses += 1
    }
    this.totalProfit = +(this.totalProfit + profit).toFixed(2)
    this.totalStake = +(this.totalStake + Number(contract.buy_price)).toFixed(2)
    this.totalPayout = +(this.totalPayout + Number(contract.sell_price)).toFixed(2)

    observer.emit('bot.tradeInfo', {
      totalProfit: this.totalProfit,
      totalWins: this.totalWins,
      totalLosses: this.totalLosses,
      totalStake: this.totalStake,
      totalPayout: this.totalPayout,
    })
  }
  botFinish(contract) {
    for (const obs of this.unregisterOnFinish) {
      observer.unregisterAll(...obs)
    }
    this.unregisterOnFinish = []
    this.updateTotals(contract)
    observer.emit('bot.finish', contract)
    // order matters
    this.purchaseCtrl.destroy()
    this.purchaseCtrl = null
  //
  }
  stop(contract) {
    if (!this.purchaseCtrl) {
      observer.emit('bot.stop', contract)
      return
    }
    for (const obs of this.unregisterOnFinish) {
      observer.unregisterAll(...obs)
    }
    this.unregisterOnFinish = []
    // order matters
    if (this.purchaseCtrl) {
      this.purchaseCtrl.destroy()
      this.purchaseCtrl = null
    }
    //
    this.api.originalApi.unsubscribeFromAllProposals().then(() => 0, () => 0)
    if (contract) {
      observer.emit('log.bot.stop', contract)
    }
    observer.emit('bot.stop', contract)
  }
}

export const bot = process.browser ? new Bot() : null
<|endoftext|>


<commit_before>function initWysihtml5(element) {
  var editor = new wysihtml5.Editor(element, {
    toolbar: element.id + "-toolbar",
    parserRules: wysihtml5ParserRules
  });
  editor.on("load", function() {
  });
  editor.on("change", function() {
    console.log("EDITOR", editor.value);
    element.value = editor.value;
    console.log("ELEMENT", element.value);
  });
  return editor;
}

(function() {
  var elements = document.querySelectorAll("[role='wysihtml5-rich-text']");
  var elementArr = [];
  for (var i = 0; i < elements.length; i++) {
    elementArr.push(elements[i]);
  }
  elementArr.forEach(initWysihtml5);
})();
<commit_msg>remove debug no-ops and don't call init on load. closes #410<commit_after>function initWysihtml5(element) {
  var editor = new wysihtml5.Editor(element, {
    toolbar: element.id + "-toolbar",
    parserRules: wysihtml5ParserRules
  });
  return editor;
}
<|endoftext|>


<commit_before>'use strict';

Controller.$inject = ['Demo.PAGES'];
export default function Controller(pages) {
	this.pages = pages;
}<commit_msg>Toggle menu<commit_after>'use strict';

Controller.$inject = ['Demo.PAGES', '$mdSidenav'];
export default function Controller(pages, $mdSidenav) {
	this.pages = pages;

	this.toggleMenu = () => {
		$mdSidenav('left').toggle();
	};
}<|endoftext|>


<commit_before>/*! batjs v0.0.0 - MIT license */

;(function (global) { function moduleDefinition($, async, _) {

// ---------------------------------------------------------------------------

'use strict';

/**
 * @param {}
 * @return {}
 * @api public
 */

function batjs() {
  var context = document.getElementById("batContext");
  var batCache = [];
  var windowWidth = $(window).width();
  var windowHeight = $(window).height();
  var randomY = function () {
    return Math.floor(Math.random() * (windowHeight - 0) + 0);
  }
  var batQ = async.queue(function (bat, callback) {
    async.series([
      function(callback){
        callback(null, bat.create());
      },
      function(callback){
        callback(null, bat.draw());
      }
    ],
    function () {
      if(_.isFunction(callback)) {
        callback();
      }
    });
  }, 100);
  var Bat = function () {
    var batEl;
    return {
      create: function () {
        batEl = document.createElement("div");
        batEl.className = "pixel";
        fastdom.write(function() {
          context.appendChild(batEl);
        });
      },
      draw: function () {
        TweenMax.to (batEl, 3, {
          delay: Math.random(),
          x: windowWidth + batEl.offsetWidth,
          y: randomY(),
          ease: randomY() % 2 ? 'easeInSine' : 'easeOutSine',
          onComplete: function (bat) {
            bat.destroy();
          },
          onCompleteParams: [this]
        });
      },
      destroy: function () {
        context.removeChild(batEl);
      }
    };
  };

  var addBats = function (num) {
    if(num < 1) {
      return;
    } else {
      batQ.push(new Bat());
      addBats(num - 1);
    }
  };

  return {
    addBats: addBats
  };

}

/**
 * Expose batjs
 */

return batjs;

// ---------------------------------------------------------------------------

} if (typeof exports === 'object') {
    // node export
    module.exports = moduleDefinition(/*require('dependency')*/);
} else if (typeof define === 'function' && define.amd) {
    // amd anonymous module registration
    define([/*'dependency'*/], moduleDefinition);
} else {
    // browser global
    global.batjs = moduleDefinition(jQuery, async, _);
}}(this));
<commit_msg>Over 1000 bats<commit_after>/*! batjs v0.0.0 - MIT license */

;(function (global) { function moduleDefinition($, async, _) {

// ---------------------------------------------------------------------------

'use strict';

/**
 * @param {}
 * @return {}
 * @api public
 */

function batjs() {
  var context = document.getElementById("batContext");
  var batCache = [];
  var windowWidth = $(window).width();
  var windowHeight = $(window).height();
  var randomY = function () {
    return Math.floor(Math.random() * (windowHeight - 0) + 0);
  };
  var Bat = function () {
    this.batEl;
  };
  Bat.prototype.create = function () {
    var that = this;
    this.batEl = document.createElement("div");
    this.batEl.className = "pixel";
    fastdom.write(function() {
      context.appendChild(this.batEl);
    }, this);
  };
  Bat.prototype.draw = function () {
    TweenMax.set(this.batEl, {
      x: this.batEl.offsetWidth,
      y: randomY()
    });
    TweenMax.to (this.batEl, 3, {
      delay: Math.random(),
      x: windowWidth + this.batEl.offsetWidth,
      y: randomY(),
      ease: randomY() % 2 ? 'easeInSine' : 'easeOutSine',
      onComplete: function (bat) {
        bat.destroy();
      },
      onCompleteParams: [this]
    });
  };
  Bat.prototype.destroy = function () {
    fastdom.write(function () {
      context.removeChild(this.batEl);
      this.batEl = "";
    }, this);
  };

  var addBats = function (num) {
    var b;
    while(num-- > -1) {
      //batQ.push(new Bat());
      b = new Bat();
      b.create();
      b.draw();
    }
  };

  return {
    addBats: addBats
  };

}

/**
 * Expose batjs
 */

return batjs;

// ---------------------------------------------------------------------------

} if (typeof exports === 'object') {
    // node export
    module.exports = moduleDefinition(/*require('dependency')*/);
} else if (typeof define === 'function' && define.amd) {
    // amd anonymous module registration
    define([/*'dependency'*/], moduleDefinition);
} else {
    // browser global
    global.batjs = moduleDefinition(jQuery, async, _);
}}(this));
<|endoftext|>


<commit_before>gfw.ui.model.AnalysisButton = Backbone.Model.extend({ });

gfw.ui.view.AnalysisButton = Backbone.View.extend({
  className: 'analysis_control',

  events: {
    'click a#analysis_control': '_onClickButton'
  },

  initialize: function() {
    this.model.bind("change:toggleButton",  this._toggleButton, this);

    var template = $("#analysis_control-template").html();

    this.template = new gfw.core.Template({
      template: template,
      type: 'mustache'
    });
  },

  // Button
  _toggleButton: function() {
    if (this.model.get("toggleButton")) {
      this.model.set({tip: "Analysis: count forest change"});
      this.model.set({"disabled": false});
    } else {
      this.model.set({tip: "Analysis: remove user defined area to analyse other areas"});
      this.model.set({"disabled": true});
    }

    this.render();
  },

  _enableButton: function() {
    this.model.set("toggleButton", true);
  },

  _disableButton: function() {
    this.model.set("toggleButton", false);
  },

  _isDisabled: function() {
    return this.model.get("disabled");
  },

  _onClickButton: function(e) {
    e.preventDefault();

    if(!this._isDisabled()) {
      analysis._showHelper();
      analysis._setupDrawingManager();
    }
  },

  render: function() {
    this.$el.html(this.template.render( this.model.toJSON() ));

    this.$button = this.$("#analysis_control");

    this.$button.tipsy({title: 'data-tip', gravity: 'w'});

    if(this._isDisabled()) {
      this.$button.addClass("disabled");
    }

    return this.$el;
  }
});

gfw.ui.model.AnalysisInfo = Backbone.Model.extend({ });

gfw.ui.view.AnalysisInfo = gfw.ui.view.Widget.extend({
  className: 'info_bar',

  events: {
    "click .toggle" : "_toggleOpen",
    'click a.reset' : '_onClickReset'
  },

  defaults: {
    speed: 250,
    minHeight: 15
  },

  initialize: function() {
    _.bindAll( this, "toggleDraggable", "onStopDragging");

    this.model.bind("change:draggable", this.toggleDraggable);
    this.model.bind("change:show", this._toggle, this);
    this.model.bind("change:closed", this.toggleOpen, this);

    this.model.set("containment", "#map-container .map");

    var template = $("#analysis-info-template").html();

    this.template = new gfw.core.Template({
      template: template,
      type: 'mustache'
    });
  },

  _toggle: function() {
    if (this.model.get("show")) this.render().fadeIn(250);
    else this.$el.fadeOut(250);
  },

  _onClickReset: function(e) {
    e.preventDefault();

    analysis._clearAnalysis();

    this.hide();
  },

  _onClickDownload: function() {
    //TODO: SUBSCRIBE DIALOG
  },

  show: function() {
    this.model.set("show", true);
  },

  hide: function() {
    this.model.set("show", false);
  },

  toggleOpen: function() {
    var that = this;

    if (this.model.get("closed")) {
      that.model.set("contentHeight", that.$content.height());

      this.$info_title.html("User defined area analysis");

      that.$content.animate({ opacity: 0, height: that.defaults.minHeight }, that.defaults.speed, function() {
        that.$info_title.fadeIn(250);
        that.$shadow.fadeOut(250);
      });

      that.$el.addClass("closed");
    } else {
      that.$info_title.fadeOut(250, function() {
        that.$content.animate({ opacity: 1, height: that.model.get("contentHeight") }, that.defaults.speed);
        that.$shadow.fadeIn(250);
      });

      that.$el.removeClass("closed");
    }
  },

  render: function() {
    this.$el.html(this.template.render( this.model.toJSON() ));

    this.$content     = this.$el.find(".content");
    this.$info_title  = this.$el.find(".info_title");
    this.$shadow      = this.$el.find(".shadow");

    return this.$el;
  }
});

gfw.ui.model.Analysis = Backbone.Model.extend({ });

gfw.ui.view.Analysis = gfw.core.View.extend({
  className: 'analysis',

  events: {
    'click a.done'    : '_onClickDone',
    'click a.cancel'  : '_onClickCancel',
    'click a.reset'   : '_onClickDone',
  },

  initialize: function() {
    _.bindAll(this, "_onOverlayComplete");

    this.map = this.options.map;
    this.selectedShapes = [];

    this.model = new gfw.ui.model.Analysis({});

    this.model.bind("change:toggleDoneButton",  this._toggleDoneButton, this);
    this.model.bind("change:toggleHelper",  this._toggleHelper, this);

    var template = $("#analysis-template").html();

    this.template = new gfw.core.Template({
      template: template,
      type: 'mustache'
    });

    var selectedShapes = [];
  },

  _setupDrawingManager: function() {
    var self = this;

    var options = {
      drawingModes: [ google.maps.drawing.OverlayType.POLYGON ],
      drawingControl: false,
      markerOptions: {
        draggable: false,
        icon: new google.maps.MarkerImage(
          '/assets/icons/marker_exclamation.png',
          new google.maps.Size(45, 45), // desired size
          new google.maps.Point(0, 0),  // offset within the scaled sprite
          new google.maps.Point(20, 20) // anchor point is half of the desired size
        )
      },

      drawingControlOptions: {
        position: google.maps.ControlPosition.RIGHT_TOP,
        drawingModes: [google.maps.drawing.OverlayType.POLYGON, google.maps.drawing.OverlayType.MARKER]
      },

      polygonOptions: config.ANALYSIS_OVERLAYS_STYLE,
      panControl: false,
      map: self.map
    };

    // Create the drawing manager
    this.drawingManager = new google.maps.drawing.DrawingManager(options);

    // Start drawing right away
    this.drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYGON);

    // Event binding
    google.maps.event.addListener(this.drawingManager, 'overlaycomplete', this._onOverlayComplete);
  },

  _onOverlayComplete: function(e) {
    this.drawingManager.setDrawingMode(null);
    this.drawingManager.path = e.overlay.getPath().getArray();
    this.drawingManager.setOptions({ drawingControl: false });
    this._enableDoneButton();

    var newShape = e.overlay;
    newShape.type = e.type;

    this._setSelection(newShape);

    polygon = {
      "type": "MultiPolygon",
      "coordinates": [
        [
          $.map(this.drawingManager.path, function(latlong, index) {
            return [[latlong.lng(), latlong.lat()]];
          })
        ]
      ]
    }

    // https://github.com/maxogden/geojson-js-utils
    var area = 0;
    var points = polygon.coordinates[0][0];
    var j = points.length - 1;
    var p1, p2;

    for (var i = 0; i < points.length; j = i++) {
      var p1 = {
        x: points[i][1],
        y: points[i][0]
      };
      var p2 = {
        x: points[j][1],
        y: points[j][0]
      };
      area += p1.x * p2.y;
      area -= p1.y * p2.x;
    }

    area /= 2;

    area = (area*1000000).toFixed(2)

    analysis.info.model.set("ha", area);
  },

  _clearSelection: function() {
    if(this.selectedShapes.length > 0) {
      for(var i in selectedShapes) {
        if (selectedShapes[i]) {
          selectedShapes[i].setEditable(false);
        }
      }

      this.selectedShapes = [];
      this.drawingManager.path = null;
    }
  },

  _setSelection: function(shape) {
    this._clearSelection();
    selectedShape = shape;
  },

  _clearAnalysis: function() {
    this.drawingManager.setDrawingMode(null);
    this.drawingManager.setOptions({ drawingControl: false });
    this.drawingManager.path = null;

    this.button._enableButton();
  },

  _onClickCancel: function(e) {
    e.preventDefault();

    this._clearAnalysis();
    this._hideHelper();
  },

  // Done button
  _toggleDoneButton: function() {
    if (this.model.get("toggleDoneButton")) {
      this.$doneButton.removeClass("disabled");
    } else {
      this.$doneButton.addClass("disabled");
    }
  },

  _enableDoneButton: function() {
    this.model.set("toggleDoneButton", true);
  },

  _disableDoneButton: function() {
    this.model.set("toggleDoneButton", false);
  },

  _onClickDone: function(e) {
    e.preventDefault();

    this.button._disableButton();
    this._hideHelper();
    this.info.show();
  },

  // Helper
  _toggleHelper: function() {
    if (this.model.get("toggleHelper")) {
      $(".legend").fadeOut(250);

      if(GFW.app.currentBaseLayer == "semi_monthly") {
        Timeline.hide();
        this.$helper.delay(650).fadeIn(250);
      } else {
        this.$helper.fadeIn(250);
      }
    } else {
      this.$helper.fadeOut(250);

      setTimeout(function() {
        if (GFW.app.currentBaseLayer === "semi_monthly") Timeline.show();

        $(".legend").fadeIn(250);
      }, 300);
    }
  },

  _showHelper: function() {
    this.model.set("toggleHelper", true);
  },

  _hideHelper: function() {
    this.model.set("toggleHelper", false);
  },

  render: function() {
    var that = this;

    this.$el.append(this.template.render( this.model.toJSON() ));

    this.$helper = this.$(".analysis.helper_bar");
    this.$doneButton = this.$(".done");

    var analysisModel = new gfw.ui.model.AnalysisInfo({
      show: false,
      subtitle: "Analysis from Nov 06 to Dec 10",
      ha: "",
      alert_count: "15,384",
      alert_title: "Forma alerts",
      closed: false
    });

    var buttonModel = new gfw.ui.model.AnalysisButton({
      tip: "Analysis: count forest change"
    });

    this.info = new gfw.ui.view.AnalysisInfo({
      model: analysisModel
    });

    this.button = new gfw.ui.view.AnalysisButton({
      model: buttonModel
    });

    $("#map").append(this.button.render());

    $("#map").append(this.info.render());

    return this.$el;
  }
});
<commit_msg>Removes selected shape<commit_after>gfw.ui.model.AnalysisButton = Backbone.Model.extend({ });

gfw.ui.view.AnalysisButton = Backbone.View.extend({
  className: 'analysis_control',

  events: {
    'click a#analysis_control': '_onClickButton'
  },

  initialize: function() {
    this.model.bind("change:toggleButton",  this._toggleButton, this);

    var template = $("#analysis_control-template").html();

    this.template = new gfw.core.Template({
      template: template,
      type: 'mustache'
    });
  },

  // Button
  _toggleButton: function() {
    if (this.model.get("toggleButton")) {
      this.model.set({tip: "Analysis: count forest change"});
      this.model.set({"disabled": false});
    } else {
      this.model.set({tip: "Analysis: remove user defined area to analyse other areas"});
      this.model.set({"disabled": true});
    }

    this.render();
  },

  _enableButton: function() {
    this.model.set("toggleButton", true);
  },

  _disableButton: function() {
    this.model.set("toggleButton", false);
  },

  _isDisabled: function() {
    return this.model.get("disabled");
  },

  _onClickButton: function(e) {
    e.preventDefault();

    if (!this._isDisabled()) {
      analysis._deleteSelectedShape();
      analysis._showHelper();
      analysis._setupDrawingManager();
    }

  },

  render: function() {
    this.$el.html(this.template.render( this.model.toJSON() ));

    this.$button = this.$("#analysis_control");

    this.$button.tipsy({title: 'data-tip', gravity: 'w'});

    if(this._isDisabled()) {
      this.$button.addClass("disabled");
    }

    return this.$el;
  }
});

gfw.ui.model.AnalysisInfo = Backbone.Model.extend({ });

gfw.ui.view.AnalysisInfo = gfw.ui.view.Widget.extend({
  className: 'info_bar',

  events: {
    "click .toggle" : "_toggleOpen",
    'click a.reset' : '_onClickReset'
  },

  defaults: {
    speed: 250,
    minHeight: 15
  },

  initialize: function() {
    _.bindAll( this, "toggleDraggable", "onStopDragging");

    this.model.bind("change:draggable", this.toggleDraggable);
    this.model.bind("change:show", this._toggle, this);
    this.model.bind("change:closed", this.toggleOpen, this);

    this.model.set("containment", "#map-container .map");

    var template = $("#analysis-info-template").html();

    this.template = new gfw.core.Template({
      template: template,
      type: 'mustache'
    });
  },

  _toggle: function() {
    if (this.model.get("show")) this.render().fadeIn(250);
    else this.$el.fadeOut(250);
  },

  _onClickReset: function(e) {
    e.preventDefault();

    analysis._clearAnalysis();

    this.hide();
  },

  _onClickDownload: function() {
    //TODO: SUBSCRIBE DIALOG
  },

  show: function() {
    this.model.set("show", true);
  },

  hide: function() {
    this.model.set("show", false);
  },

  toggleOpen: function() {
    var that = this;

    if (this.model.get("closed")) {
      that.model.set("contentHeight", that.$content.height());

      this.$info_title.html("User defined area analysis");

      that.$content.animate({ opacity: 0, height: that.defaults.minHeight }, that.defaults.speed, function() {
        that.$info_title.fadeIn(250);
        that.$shadow.fadeOut(250);
      });

      that.$el.addClass("closed");
    } else {
      that.$info_title.fadeOut(250, function() {
        that.$content.animate({ opacity: 1, height: that.model.get("contentHeight") }, that.defaults.speed);
        that.$shadow.fadeIn(250);
      });

      that.$el.removeClass("closed");
    }
  },

  render: function() {
    this.$el.html(this.template.render( this.model.toJSON() ));

    this.$content     = this.$el.find(".content");
    this.$info_title  = this.$el.find(".info_title");
    this.$shadow      = this.$el.find(".shadow");

    return this.$el;
  }
});

gfw.ui.model.Analysis = Backbone.Model.extend({ });

gfw.ui.view.Analysis = gfw.core.View.extend({
  className: 'analysis',

  events: {
    'click a.done'    : '_onClickDone',
    'click a.cancel'  : '_onClickCancel',
    'click a.reset'   : '_onClickDone',
  },

  initialize: function() {
    _.bindAll(this, "_onOverlayComplete", "_clearSelection", "_clearAnalysis");

    this.map = this.options.map;
    this.selectedShapes = [];
    this.selectedShape;

    this.model = new gfw.ui.model.Analysis({});

    this.model.bind("change:toggleDoneButton",  this._toggleDoneButton, this);
    this.model.bind("change:toggleHelper",  this._toggleHelper, this);

    var template = $("#analysis-template").html();

    this.template = new gfw.core.Template({
      template: template,
      type: 'mustache'
    });

  },

  _setupDrawingManager: function() {
    var self = this;

    var options = {
      drawingModes: [ google.maps.drawing.OverlayType.POLYGON ],
      drawingControl: false,
      markerOptions: {
        draggable: false,
        icon: new google.maps.MarkerImage(
          '/assets/icons/marker_exclamation.png',
          new google.maps.Size(45, 45), // desired size
          new google.maps.Point(0, 0),  // offset within the scaled sprite
          new google.maps.Point(20, 20) // anchor point is half of the desired size
        )
      },

      drawingControlOptions: {
        position: google.maps.ControlPosition.RIGHT_TOP,
        drawingModes: [google.maps.drawing.OverlayType.POLYGON, google.maps.drawing.OverlayType.MARKER]
      },

      polygonOptions: config.ANALYSIS_OVERLAYS_STYLE,
      panControl: false,
      map: self.map
    };

    // Create the drawing manager
    this.drawingManager = new google.maps.drawing.DrawingManager(options);

    // Start drawing right away
    this.drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYGON);

    // Event binding
    google.maps.event.addListener(this.drawingManager, 'overlaycomplete', this._onOverlayComplete);
  },

  _onOverlayComplete: function(e) {
    this.drawingManager.setDrawingMode(null);
    this.drawingManager.path = e.overlay.getPath().getArray();
    this.drawingManager.setOptions({ drawingControl: false });
    this._enableDoneButton();

    var newShape = e.overlay;
    newShape.type = e.type;

    this._setSelection(newShape);

    polygon = {
      "type": "MultiPolygon",
      "coordinates": [
        [
          $.map(this.drawingManager.path, function(latlong, index) {
            return [[latlong.lng(), latlong.lat()]];
          })
        ]
      ]
    }

    // https://github.com/maxogden/geojson-js-utils
    var area = 0;
    var points = polygon.coordinates[0][0];
    var j = points.length - 1;
    var p1, p2;

    for (var i = 0; i < points.length; j = i++) {
      var p1 = {
        x: points[i][1],
        y: points[i][0]
      };
      var p2 = {
        x: points[j][1],
        y: points[j][0]
      };
      area += p1.x * p2.y;
      area -= p1.y * p2.x;
    }

    area /= 2;

    area = (area*1000000).toFixed(2)

    analysis.info.model.set("ha", area);
  },

  _clearSelection: function() {
    if (this.selectedShapes.length > 0) {
      for(var i in this.selectedShapes) {
        if (selectedShapes[i]) {
          selectedShapes[i].setEditable(false);
        }
      }

      this.selectedShapes = [];
      this.drawingManager.path = null;
    }
  },

  _deleteSelectedShape: function() {
    if (this.selectedShape) {
      this.selectedShape.setMap(null);
      this.selectedShape = null;
    }
  },

  _setSelection: function(shape) {
    this._clearSelection();
    this.selectedShape = shape;
  },

  _clearAnalysis: function() {

    this._deleteSelectedShape();

    if (this.drawingManager) {
      this.drawingManager.setDrawingMode(null);
      this.drawingManager.setOptions({ drawingControl: false });
      this.drawingManager.path = null;
    }

    this.button._enableButton();
  },

  _onClickCancel: function(e) {
    e.preventDefault();

    this._clearAnalysis();
    this._hideHelper();
  },

  // Done button
  _toggleDoneButton: function() {
    if (this.model.get("toggleDoneButton")) {
      this.$doneButton.removeClass("disabled");
    } else {
      this.$doneButton.addClass("disabled");
    }
  },

  _enableDoneButton: function() {
    this.model.set("toggleDoneButton", true);
  },

  _disableDoneButton: function() {
    this.model.set("toggleDoneButton", false);
  },

  _onClickDone: function(e) {
    e.preventDefault();

    this.button._disableButton();
    this._hideHelper();
    this.info.show();
  },

  // Helper
  _toggleHelper: function() {
    if (this.model.get("toggleHelper")) {
      $(".legend").fadeOut(250);

      if(GFW.app.currentBaseLayer == "semi_monthly") {
        Timeline.hide();
        this.$helper.delay(650).fadeIn(250);
      } else {
        this.$helper.fadeIn(250);
      }
    } else {
      this.$helper.fadeOut(250);

      setTimeout(function() {
        if (GFW.app.currentBaseLayer === "semi_monthly") Timeline.show();

        $(".legend").fadeIn(250);
      }, 300);
    }
  },

  _showHelper: function() {
    this.model.set("toggleHelper", true);
  },

  _hideHelper: function() {
    this.model.set("toggleHelper", false);
  },

  render: function() {
    var that = this;

    this.$el.append(this.template.render( this.model.toJSON() ));

    this.$helper = this.$(".analysis.helper_bar");
    this.$doneButton = this.$(".done");

    var analysisModel = new gfw.ui.model.AnalysisInfo({
      show: false,
      subtitle: "Analysis from Nov 06 to Dec 10",
      ha: "",
      alert_count: "15,384",
      alert_title: "Forma alerts",
      closed: false
    });

    var buttonModel = new gfw.ui.model.AnalysisButton({
      tip: "Analysis: count forest change"
    });

    this.info = new gfw.ui.view.AnalysisInfo({
      model: analysisModel
    });

    this.button = new gfw.ui.view.AnalysisButton({
      model: buttonModel
    });

    $("#map").append(this.button.render());

    $("#map").append(this.info.render());

    return this.$el;
  }
});
<|endoftext|>


<commit_before>'use strict';

const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');

module.exports = function(defaults) {
  let app = new EmberAddon(defaults, {
    /*
      Leave jQuery out of this addon's own test suite & dummy app by default,
      so that the addon can be used in apps without jQuery. If you really need
      jQuery, it's safe to remove this line.
    */
    vendorFiles: { 'jquery.js': null, 'app-shims.js': null }

    // Add options here
  });

  /*
    This build file specifies the options for the dummy test app of this
    addon, located in `/tests/dummy`
    This build file does *not* influence how the addon or the app using it
    behave. You most likely want to be modifying `./index.js` or app's build file
  */

  return app.toTree();
};
<commit_msg>ember-faker in prod<commit_after>'use strict';

const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');

module.exports = function(defaults) {
  let app = new EmberAddon(defaults, {
    /*
      Leave jQuery out of this addon's own test suite & dummy app by default,
      so that the addon can be used in apps without jQuery. If you really need
      jQuery, it's safe to remove this line.
    */
    vendorFiles: { 'jquery.js': null, 'app-shims.js': null },

    // our dummy app always uses faker, even in production
    'ember-faker': { enabled: true }

    // Add options here
  });

  /*
    This build file specifies the options for the dummy test app of this
    addon, located in `/tests/dummy`
    This build file does *not* influence how the addon or the app using it
    behave. You most likely want to be modifying `./index.js` or app's build file
  */

  return app.toTree();
};
<|endoftext|>


<commit_before><commit_msg>Automatically built.<commit_after><|endoftext|>