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

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

    //-----------------------------------------------------------------------
    // CommManager class
    //-----------------------------------------------------------------------

    var CommManager = function (kernel) {
        this.comms = {};
        this.targets = {};
        if (kernel !== undefined) {
            this.init_kernel(kernel);
        }
    };

    CommManager.prototype.init_kernel = function (kernel) {
        // connect the kernel, and register message handlers
        this.kernel = kernel;
        var msg_types = ['comm_open', 'comm_msg', 'comm_close'];
        for (var i = 0; i < msg_types.length; i++) {
            var msg_type = msg_types[i];
            kernel.register_iopub_handler(msg_type, $.proxy(this[msg_type], this));
        }
    };

    CommManager.prototype.new_comm = function (target_name, data, callbacks, metadata) {
        // Create a new Comm, register it, and open its Kernel-side counterpart
        // Mimics the auto-registration in `Comm.__init__` in the IPython Comm
        var comm = new Comm(target_name);
        this.register_comm(comm);
        comm.open(data, callbacks, metadata);
        return comm;
    };

    CommManager.prototype.register_target = function (target_name, f) {
        // Register a target function for a given target name
        this.targets[target_name] = f;
    };

    CommManager.prototype.unregister_target = function (target_name, f) {
        // Unregister a target function for a given target name
        delete this.targets[target_name];
    };

    CommManager.prototype.register_comm = function (comm) {
        // Register a comm in the mapping
        this.comms[comm.comm_id] = comm;
        comm.kernel = this.kernel;
        return comm.comm_id;
    };

    CommManager.prototype.unregister_comm = function (comm) {
        // Remove a comm from the mapping
        delete this.comms[comm.comm_id];
    };

    // comm message handlers

    CommManager.prototype.comm_open = function (msg) {
        var content = msg.content;
        var that = this;

        var instantiate_comm = function(target) {
            var comm = new Comm(content.target_name, content.comm_id);
            that.register_comm(comm);
            try {
                target(comm, msg);
            } catch (e) {
                console.log("Exception opening new comm:", e, e.stack, msg);
                comm.close();
                that.unregister_comm(comm);
            }
        };

        if (content.target_module) {
            // Load requirejs module for comm target
            require([content.target_module], function(mod) {
                var target = mod[content.target_name];
                if (target !== undefined) {
                    instantiate_comm(target)
                } else {
                    console.log("Comm target " + content.target_name +
                        " not found in module " + content.target_module);
                }
            }, function(err) { console.log(err); });
        } else {
            // No requirejs module specified: look for target in registry
            var f = this.targets[content.target_name];
            if (f === undefined) {
                console.log("No such target registered: ", content.target_name);
                console.log("Available targets are: ", this.targets);
                return;
            }
            instantiate_comm(f)
        }
    };

    CommManager.prototype.comm_close = function (msg) {
        var content = msg.content;
        var comm = this.comms[content.comm_id];
        if (comm === undefined) {
            return;
        }
        this.unregister_comm(comm);
        try {
            comm.handle_close(msg);
        } catch (e) {
            console.log("Exception closing comm: ", e, e.stack, msg);
        }
    };

    CommManager.prototype.comm_msg = function (msg) {
        var content = msg.content;
        var comm = this.comms[content.comm_id];
        if (comm === undefined) {
            return;
        }
        try {
            comm.handle_msg(msg);
        } catch (e) {
            console.log("Exception handling comm msg: ", e, e.stack, msg);
        }
    };

    //-----------------------------------------------------------------------
    // Comm base class
    //-----------------------------------------------------------------------

    var Comm = function (target_name, comm_id) {
        this.target_name = target_name;
        this.comm_id = comm_id || utils.uuid();
        this._msg_callback = this._close_callback = null;
    };

    // methods for sending messages
    Comm.prototype.open = function (data, callbacks, metadata) {
        var content = {
            comm_id : this.comm_id,
            target_name : this.target_name,
            data : data || {},
        };
        return this.kernel.send_shell_message("comm_open", content, callbacks, metadata);
    };

    Comm.prototype.send = function (data, callbacks, metadata, buffers) {
        var content = {
            comm_id : this.comm_id,
            data : data || {},
        };
        return this.kernel.send_shell_message("comm_msg", content, callbacks, metadata, buffers);
    };

    Comm.prototype.close = function (data, callbacks, metadata) {
        var content = {
            comm_id : this.comm_id,
            data : data || {},
        };
        return this.kernel.send_shell_message("comm_close", content, callbacks, metadata);
    };

    // methods for registering callbacks for incoming messages
    Comm.prototype._register_callback = function (key, callback) {
        this['_' + key + '_callback'] = callback;
    };

    Comm.prototype.on_msg = function (callback) {
        this._register_callback('msg', callback);
    };

    Comm.prototype.on_close = function (callback) {
        this._register_callback('close', callback);
    };

    // methods for handling incoming messages

    Comm.prototype._maybe_callback = function (key, msg) {
        var callback = this['_' + key + '_callback'];
        if (callback) {
            try {
                callback(msg);
            } catch (e) {
                console.log("Exception in Comm callback", e, e.stack, msg);
            }
        }
    };

    Comm.prototype.handle_msg = function (msg) {
        this._maybe_callback('msg', msg);
    };

    Comm.prototype.handle_close = function (msg) {
        this._maybe_callback('close', msg);
    };

    // For backwards compatability.
    IPython.CommManager = CommManager;
    IPython.Comm = Comm;

    return {
        'CommManager': CommManager,
        'Comm': Comm
    };
});
<commit_msg>Use load_class in comms instead of callbacks.<commit_after>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

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

    //-----------------------------------------------------------------------
    // CommManager class
    //-----------------------------------------------------------------------

    var CommManager = function (kernel) {
        this.comms = {};
        this.targets = {};
        if (kernel !== undefined) {
            this.init_kernel(kernel);
        }
    };

    CommManager.prototype.init_kernel = function (kernel) {
        // connect the kernel, and register message handlers
        this.kernel = kernel;
        var msg_types = ['comm_open', 'comm_msg', 'comm_close'];
        for (var i = 0; i < msg_types.length; i++) {
            var msg_type = msg_types[i];
            kernel.register_iopub_handler(msg_type, $.proxy(this[msg_type], this));
        }
    };

    CommManager.prototype.new_comm = function (target_name, data, callbacks, metadata) {
        // Create a new Comm, register it, and open its Kernel-side counterpart
        // Mimics the auto-registration in `Comm.__init__` in the IPython Comm
        var comm = new Comm(target_name);
        this.register_comm(comm);
        comm.open(data, callbacks, metadata);
        return comm;
    };

    CommManager.prototype.register_target = function (target_name, f) {
        // Register a target function for a given target name
        this.targets[target_name] = f;
    };

    CommManager.prototype.unregister_target = function (target_name, f) {
        // Unregister a target function for a given target name
        delete this.targets[target_name];
    };

    CommManager.prototype.register_comm = function (comm) {
        // Register a comm in the mapping
        this.comms[comm.comm_id] = comm;
        comm.kernel = this.kernel;
        return comm.comm_id;
    };

    CommManager.prototype.unregister_comm = function (comm) {
        // Remove a comm from the mapping
        delete this.comms[comm.comm_id];
    };

    // comm message handlers

    CommManager.prototype.comm_open = function (msg) {
        var content = msg.content;
        var that = this;

        utils.load_class(content.target_name, content.target_module, this.targets)
        .then(function(target) {
            var comm = new Comm(content.target_name, content.comm_id);
            that.register_comm(comm);
            try {
                target(comm, msg);
            } catch (e) {
                console.log("Exception opening new comm:", e, e.stack, msg);
                comm.close();
                that.unregister_comm(comm);
            }
        }, console.error);
    };

    CommManager.prototype.comm_close = function (msg) {
        var content = msg.content;
        var comm = this.comms[content.comm_id];
        if (comm === undefined) {
            return;
        }
        this.unregister_comm(comm);
        try {
            comm.handle_close(msg);
        } catch (e) {
            console.log("Exception closing comm: ", e, e.stack, msg);
        }
    };

    CommManager.prototype.comm_msg = function (msg) {
        var content = msg.content;
        var comm = this.comms[content.comm_id];
        if (comm === undefined) {
            return;
        }
        try {
            comm.handle_msg(msg);
        } catch (e) {
            console.log("Exception handling comm msg: ", e, e.stack, msg);
        }
    };

    //-----------------------------------------------------------------------
    // Comm base class
    //-----------------------------------------------------------------------

    var Comm = function (target_name, comm_id) {
        this.target_name = target_name;
        this.comm_id = comm_id || utils.uuid();
        this._msg_callback = this._close_callback = null;
    };

    // methods for sending messages
    Comm.prototype.open = function (data, callbacks, metadata) {
        var content = {
            comm_id : this.comm_id,
            target_name : this.target_name,
            data : data || {},
        };
        return this.kernel.send_shell_message("comm_open", content, callbacks, metadata);
    };

    Comm.prototype.send = function (data, callbacks, metadata, buffers) {
        var content = {
            comm_id : this.comm_id,
            data : data || {},
        };
        return this.kernel.send_shell_message("comm_msg", content, callbacks, metadata, buffers);
    };

    Comm.prototype.close = function (data, callbacks, metadata) {
        var content = {
            comm_id : this.comm_id,
            data : data || {},
        };
        return this.kernel.send_shell_message("comm_close", content, callbacks, metadata);
    };

    // methods for registering callbacks for incoming messages
    Comm.prototype._register_callback = function (key, callback) {
        this['_' + key + '_callback'] = callback;
    };

    Comm.prototype.on_msg = function (callback) {
        this._register_callback('msg', callback);
    };

    Comm.prototype.on_close = function (callback) {
        this._register_callback('close', callback);
    };

    // methods for handling incoming messages

    Comm.prototype._maybe_callback = function (key, msg) {
        var callback = this['_' + key + '_callback'];
        if (callback) {
            try {
                callback(msg);
            } catch (e) {
                console.log("Exception in Comm callback", e, e.stack, msg);
            }
        }
    };

    Comm.prototype.handle_msg = function (msg) {
        this._maybe_callback('msg', msg);
    };

    Comm.prototype.handle_close = function (msg) {
        this._maybe_callback('close', msg);
    };

    // For backwards compatability.
    IPython.CommManager = CommManager;
    IPython.Comm = Comm;

    return {
        'CommManager': CommManager,
        'Comm': Comm
    };
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2019 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.auth',
  name: 'AuthorizationDAO',
  extends: 'foam.dao.ProxyDAO',

  documentation: 'A DAO decorator to run authorization checks.',

  javaImports: [
    'foam.core.FObject',
    'foam.core.InvalidX',
    'foam.core.X',
    'foam.dao.*',
    'foam.mlang.order.Comparator',
    'foam.mlang.predicate.Predicate',
    'foam.nanos.auth.AuthorizationException',
    'foam.nanos.auth.User',

    'static foam.mlang.MLang.AND',
    'static foam.mlang.MLang.IS_AUTHORIZED_TO_READ',
    'static foam.mlang.MLang.IS_AUTHORIZED_TO_DELETE'
  ],

  axioms: [
    {
      name: 'javaExtras',
      buildJavaClass: function(cls) {
        cls.extras.push(foam.java.Code.create({
          data:`
  public AuthorizationDAO(X x, DAO delegate, Authorizer authorizer) {
    AuthorizationException exception = new AuthorizationException("When " +
        "using a DAO decorated by AuthorizationDAO, you may only call the " +
        "context-oriented methods: put_(), find_(), select_(), remove_(), " +
        "removeAll_(). Alternatively, you can also " +
        "use .inX() to set the context on the DAO.");
    setX(new InvalidX(exception));
    setDelegate(delegate);
    setAuthorizer(authorizer);
  }
`
        }));
      }
    }
  ],

  properties: [
    {
      name: 'authorizer',
      class: 'FObjectProperty',
      of: 'foam.nanos.auth.Authorizer'
    }
  ],

  methods: [
    {
      name: 'init_',
      javaCode: `
      AuthorizationException exception = new AuthorizationException("When " +
          "using a DAO decorated by AuthorizationDAO, you may only call the " +
          "context-oriented methods: put_(), find_(), select_(), remove_(), " +
          "removeAll_(). Alternatively, you can also " +
          "use .inX() to set the context on the DAO.");
      setX(new InvalidX(exception));
      `
    },
    {
      name: 'put_',
      javaThrows: [
        'foam.nanos.auth.AuthorizationException'
      ],
      javaCode: `
   if ( obj == null ) throw new RuntimeException("Cannot put null.");

    Object id = obj.getProperty("id");
    FObject oldObj = getDelegate().inX(x).find(id);
    boolean isCreate = id == null || oldObj == null;

    if ( isCreate ) {
      getAuthorizer().authorizeOnCreate(x, obj);
    } else {
      getAuthorizer().authorizeOnUpdate(x, oldObj, obj);
    }

    return super.put_(x, obj);
`
    },
    {
      name: 'remove_',
      javaCode: `
    Object id = obj.getProperty("id");
    FObject oldObj = getDelegate().inX(x).find(id);
    if ( id == null || oldObj == null ) return null;
    getAuthorizer().authorizeOnDelete(x, oldObj);
    return super.remove_(x, obj);
 `
    },
    {
      name: 'find_',
      javaCode: `
    if ( id == null ) return null;
    if ( getAuthorizer().checkGlobalRead(x) ) return super.find_(x, id);

    FObject obj = super.find_(x, id);
    if ( obj != null ) getAuthorizer().authorizeOnRead(x, obj);
    return obj;
 `
    },
    {
      name: 'select_',
      javaCode: `
    if ( ! getAuthorizer().checkGlobalRead(x) ) predicate = augmentPredicate(x, false, predicate);
    return super.select_(x, sink, skip, limit, order, predicate);
 `
    },
    {
      name: 'removeAll_',
      javaCode: `
    if ( ! getAuthorizer().checkGlobalRemove(x) ) predicate = augmentPredicate(x, true, predicate);
    this.select_(x, new RemoveSink(x, this), skip, limit, order, predicate);
 `
    },
    {
      name: 'augmentPredicate',
      args: [
        {
          name: 'x',
          type: 'foam.core.X'
        },
        {
          name: 'remove',
          type: 'Boolean'
        },
        {
          name: 'existingPredicate',
          type: 'Predicate'
        }
      ],
      javaType: 'Predicate',
      javaCode: `
    Predicate newPredicate = remove ? IS_AUTHORIZED_TO_DELETE(x, getAuthorizer()) : IS_AUTHORIZED_TO_READ(x, getAuthorizer());
    return existingPredicate != null ?
      AND(
        existingPredicate,
        newPredicate
      ) :
      newPredicate;
 `
    }
  ]
});
<commit_msg>remove authorizationdao usages of invalidx<commit_after>/**
 * @license
 * Copyright 2019 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.auth',
  name: 'AuthorizationDAO',
  extends: 'foam.dao.ProxyDAO',

  documentation: 'A DAO decorator to run authorization checks.',

  javaImports: [
    'foam.core.FObject',
    'foam.core.InvalidX',
    'foam.core.X',
    'foam.dao.*',
    'foam.mlang.order.Comparator',
    'foam.mlang.predicate.Predicate',
    'foam.nanos.auth.AuthorizationException',
    'foam.nanos.auth.User',

    'static foam.mlang.MLang.AND',
    'static foam.mlang.MLang.IS_AUTHORIZED_TO_READ',
    'static foam.mlang.MLang.IS_AUTHORIZED_TO_DELETE'
  ],

  axioms: [
    {
      name: 'javaExtras',
      buildJavaClass: function(cls) {
        cls.extras.push(foam.java.Code.create({
          data:`
  public AuthorizationDAO(X x, DAO delegate, Authorizer authorizer) {
    setX(x);
    setDelegate(delegate);
    setAuthorizer(authorizer);
  }
`
        }));
      }
    }
  ],

  properties: [
    {
      name: 'authorizer',
      class: 'FObjectProperty',
      of: 'foam.nanos.auth.Authorizer'
    }
  ],

  methods: [
    {
      name: 'put_',
      javaThrows: [
        'foam.nanos.auth.AuthorizationException'
      ],
      javaCode: `
   if ( obj == null ) throw new RuntimeException("Cannot put null.");

    Object id = obj.getProperty("id");
    FObject oldObj = getDelegate().inX(x).find(id);
    boolean isCreate = id == null || oldObj == null;

    if ( isCreate ) {
      getAuthorizer().authorizeOnCreate(x, obj);
    } else {
      getAuthorizer().authorizeOnUpdate(x, oldObj, obj);
    }

    return super.put_(x, obj);
`
    },
    {
      name: 'remove_',
      javaCode: `
    Object id = obj.getProperty("id");
    FObject oldObj = getDelegate().inX(x).find(id);
    if ( id == null || oldObj == null ) return null;
    getAuthorizer().authorizeOnDelete(x, oldObj);
    return super.remove_(x, obj);
 `
    },
    {
      name: 'find_',
      javaCode: `
    if ( id == null ) return null;
    if ( getAuthorizer().checkGlobalRead(x) ) return super.find_(x, id);

    FObject obj = super.find_(x, id);
    if ( obj != null ) getAuthorizer().authorizeOnRead(x, obj);
    return obj;
 `
    },
    {
      name: 'select_',
      javaCode: `
    if ( ! getAuthorizer().checkGlobalRead(x) ) predicate = augmentPredicate(x, false, predicate);
    return super.select_(x, sink, skip, limit, order, predicate);
 `
    },
    {
      name: 'removeAll_',
      javaCode: `
    if ( ! getAuthorizer().checkGlobalRemove(x) ) predicate = augmentPredicate(x, true, predicate);
    this.select_(x, new RemoveSink(x, this), skip, limit, order, predicate);
 `
    },
    {
      name: 'augmentPredicate',
      args: [
        {
          name: 'x',
          type: 'foam.core.X'
        },
        {
          name: 'remove',
          type: 'Boolean'
        },
        {
          name: 'existingPredicate',
          type: 'Predicate'
        }
      ],
      javaType: 'Predicate',
      javaCode: `
    Predicate newPredicate = remove ? IS_AUTHORIZED_TO_DELETE(x, getAuthorizer()) : IS_AUTHORIZED_TO_READ(x, getAuthorizer());
    return existingPredicate != null ?
      AND(
        existingPredicate,
        newPredicate
      ) :
      newPredicate;
 `
    }
  ]
});
<|endoftext|>


<commit_before><commit_msg>možnost stahovat soubory pro uživatel ID=1<commit_after><|endoftext|>


<commit_before>/**
 * Developer: Stepan Burguchev
 * Date: 10/13/2014
 * Copyright: 2009-2016 Comindware®
 *       All Rights Reserved
 * Published under the MIT license
 */

"use strict";

import { keypress } from '../../libApi';
import dropdown from '../../dropdown/dropdownApi';
import template from './templates/referenceEditor.hbs';
import BaseLayoutEditorView from './base/BaseLayoutEditorView';
import ReferenceButtonView from './impl/reference/views/ReferenceButtonView';
import ReferencePanelView from './impl/reference/views/ReferencePanelView';
import DefaultReferenceModel from './impl/reference/models/DefaultReferenceModel';
import ReferenceListItemView from './impl/reference/views/ReferenceListItemView';

const classes = {
};

const defaultOptions = {
    'controller': null,
    'showAddNewButton': false,
    'buttonView': ReferenceButtonView,
    'listItemView': ReferenceListItemView
};

/**
 * @name ReferenceEditorView
 * @memberof module:core.form.editors
 * @class Editor to select object in the format { id, text }, using async fetch for 'options collection'.
 * @extends module:core.form.editors.base.BaseEditorView
 * @param {Object} options Options object. All the properties of {@link module:core.form.editors.base.BaseEditorView BaseEditorView} class are also supported.
 * @param {BaseReferenceEditorController} [options.controller=null] Data provider, instance.
 * @param {Boolean} [options.showAddNewButton=false] responsible for displaying button, which providing to user adding new elements.
 * @param {Marionette.ItemView} [options.buttonView=ReferenceButtonView] view to display button (what we click on to show dropdown).
 * @param {Marionette.ItemView} [options.listItemView=ReferenceListItemView] view to display item in the dropdown list.
 * {@link module:core.form.editors.reference.controllers.BaseReferenceEditorController BaseReferenceEditorController}.
 * */
Backbone.Form.editors.Reference = BaseLayoutEditorView.extend(/** @lends module:core.form.editors.ReferenceEditorView.prototype */{
    initialize: function (options) {
        if (options.schema) {
            _.extend(this.options, defaultOptions, _.pick(options.schema, _.keys(defaultOptions)));
        } else {
            _.extend(this.options, defaultOptions, _.pick(options || {}, _.keys(defaultOptions)));
        }

        this.reqres = new Backbone.Wreqr.RequestResponse();
        this.controller = this.options.controller;
        this.value = this.__adjustValue(this.value);
        this.showAddNewButton = this.options.showAddNewButton;

        this.reqres.setHandler('panel:open', this.onPanelOpenRequest, this);
        this.reqres.setHandler('value:clear', this.onValueClear, this);
        this.reqres.setHandler('value:set', this.onValueSet, this);
        this.reqres.setHandler('value:navigate', this.onValueNavigate, this);
        this.reqres.setHandler('filter:text', this.onFilterText, this);
        this.reqres.setHandler('add:new:item',this.onAddNewItem, this );

        this.viewModel = new Backbone.Model({
            button: new Backbone.Model({
                value: this.getValue(),
                state: 'view',
                enabled: this.getEnabled(),
                readonly: this.getReadonly()

            }),
            panel: new Backbone.Model({
                value: this.getValue(),
                collection: this.controller.collection,
                totalCount: this.controller.totalCount || 0
            })
        });
    },

    focusElement: null,

    attributes: {
        tabindex: 0
    },

    regions: {
        dropdownRegion: '.js-dropdown-region'
    },

    className: 'editor editor_reference',

    template: template,

    setValue: function (value) {
        value = this.__adjustValue(value);
        this.__value(value, false);
    },

    onRender: function () {
        // dropdown
        this.dropdownView = dropdown.factory.createDropdown({
            buttonView: this.options.buttonView,
            buttonViewOptions: {
                model: this.viewModel.get('button'),
                reqres: this.reqres
            },
            panelView: ReferencePanelView,
            panelViewOptions: {
                model: this.viewModel.get('panel'),
                reqres: this.reqres,
                showAddNewButton: this.showAddNewButton,
                listItemView: this.options.listItemView
            },
            panelPosition: 'down-over',
            autoOpen: false
        });
        this.listenTo(this.dropdownView, 'open', this.onFocus);
        this.listenTo(this.dropdownView, 'close', this.onBlur);
        this.dropdownRegion.show(this.dropdownView);

        // hotkeys
        if (this.keyListener) {
            this.keyListener.reset();
        }
        this.keyListener = new keypress.Listener(this.el);
        _.each('down,enter,num_enter'.split(','), function (key) {
            this.keyListener.simple_combo(key, function () {
                if (this.getEnabled() && !this.getReadonly()) {
                    this.dropdownView.open();
                }
            }.bind(this));
        }, this);
    },

    __adjustValue: function (value) {
        if (!value || !value.id) {
            return null;
        }
        if (value instanceof DefaultReferenceModel) {
            return value;
        }
        if (value instanceof Backbone.Model) {
            value = value.attributes;
        }

        return new DefaultReferenceModel(value);
    },

    __value: function (value, triggerChange) {
        if (this.value === value) {
            return;
        }
        this.value = value;
        this.viewModel.get('button').set('value', value);
        this.viewModel.get('panel').set('value', value);
        if (triggerChange) {
            this.__triggerChange();
        }
    },

    isEmptyValue: function () {
        let value = this.getValue();
        return !value || _.isEmpty(value);
    },

    onValueClear: function () {
        this.__value(null, true);
    },

    onValueSet: function (model) {
        this.__value(model, true);
        this.dropdownView.close();
        this.$el.focus();
    },

    onValueNavigate: function () {
       return this.controller.navigate(this.getValue());
    },

    onFilterText: function (options) {
        var deferred = $.Deferred();
        this.controller.fetch(options).then(function () {
            this.viewModel.get('panel').set('totalCount', this.controller.totalCount);
            deferred.resolve();
        }.bind(this));
        return deferred.promise();
    },

    onPanelOpenRequest: function () {
        if (this.getEnabled() && !this.getReadonly()) {
            this.dropdownView.open();
        }
    },

    onAddNewItem:function(){
        this.controller.addNewItem();
    },

    setReadonly: function (readonly) {
        BaseLayoutEditorView.prototype.__setReadonly.call(this, readonly);
        this.viewModel.get('button').set('readonly', this.getReadonly());
    },

    setEnabled: function (enabled) {
        BaseLayoutEditorView.prototype.__setEnabled.call(this, enabled);
        this.viewModel.get('button').set('enabled', this.getEnabled());
    },

    focus: function () {
        this.dropdownView.open();
    },

    blur: function () {
        this.dropdownView.close();
    }
});

export default Backbone.Form.editors.Reference;
<commit_msg>Fixed component description.<commit_after>/**
 * Developer: Stepan Burguchev
 * Date: 10/13/2014
 * Copyright: 2009-2016 Comindware®
 *       All Rights Reserved
 * Published under the MIT license
 */

"use strict";

import { keypress } from '../../libApi';
import dropdown from '../../dropdown/dropdownApi';
import template from './templates/referenceEditor.hbs';
import BaseLayoutEditorView from './base/BaseLayoutEditorView';
import ReferenceButtonView from './impl/reference/views/ReferenceButtonView';
import ReferencePanelView from './impl/reference/views/ReferencePanelView';
import DefaultReferenceModel from './impl/reference/models/DefaultReferenceModel';
import ReferenceListItemView from './impl/reference/views/ReferenceListItemView';

const classes = {
};

const defaultOptions = {
    'controller': null,
    'showAddNewButton': false,
    'buttonView': ReferenceButtonView,
    'listItemView': ReferenceListItemView
};

/**
 * @name ReferenceEditorView
 * @memberof module:core.form.editors
 * @class Editor to select object in the format { id, text }, using async fetch for 'options collection'.
 * @extends module:core.form.editors.base.BaseEditorView
 * @param {Object} options Options object. All the properties of {@link module:core.form.editors.base.BaseEditorView BaseEditorView} class are also supported.
 * @param {BaseReferenceEditorController} [options.controller=null] Data provider, instance
 * {@link module:core.form.editors.reference.controllers.BaseReferenceEditorController BaseReferenceEditorController}.
 * @param {Boolean} [options.showAddNewButton=false] responsible for displaying button, which providing to user adding new elements.
 * @param {Marionette.ItemView} [options.buttonView=ReferenceButtonView] view to display button (what we click on to show dropdown).
 * @param {Marionette.ItemView} [options.listItemView=ReferenceListItemView] view to display item in the dropdown list.
 * */
Backbone.Form.editors.Reference = BaseLayoutEditorView.extend(/** @lends module:core.form.editors.ReferenceEditorView.prototype */{
    initialize: function (options) {
        if (options.schema) {
            _.extend(this.options, defaultOptions, _.pick(options.schema, _.keys(defaultOptions)));
        } else {
            _.extend(this.options, defaultOptions, _.pick(options || {}, _.keys(defaultOptions)));
        }

        this.reqres = new Backbone.Wreqr.RequestResponse();
        this.controller = this.options.controller;
        this.value = this.__adjustValue(this.value);
        this.showAddNewButton = this.options.showAddNewButton;

        this.reqres.setHandler('panel:open', this.onPanelOpenRequest, this);
        this.reqres.setHandler('value:clear', this.onValueClear, this);
        this.reqres.setHandler('value:set', this.onValueSet, this);
        this.reqres.setHandler('value:navigate', this.onValueNavigate, this);
        this.reqres.setHandler('filter:text', this.onFilterText, this);
        this.reqres.setHandler('add:new:item',this.onAddNewItem, this );

        this.viewModel = new Backbone.Model({
            button: new Backbone.Model({
                value: this.getValue(),
                state: 'view',
                enabled: this.getEnabled(),
                readonly: this.getReadonly()

            }),
            panel: new Backbone.Model({
                value: this.getValue(),
                collection: this.controller.collection,
                totalCount: this.controller.totalCount || 0
            })
        });
    },

    focusElement: null,

    attributes: {
        tabindex: 0
    },

    regions: {
        dropdownRegion: '.js-dropdown-region'
    },

    className: 'editor editor_reference',

    template: template,

    setValue: function (value) {
        value = this.__adjustValue(value);
        this.__value(value, false);
    },

    onRender: function () {
        // dropdown
        this.dropdownView = dropdown.factory.createDropdown({
            buttonView: this.options.buttonView,
            buttonViewOptions: {
                model: this.viewModel.get('button'),
                reqres: this.reqres
            },
            panelView: ReferencePanelView,
            panelViewOptions: {
                model: this.viewModel.get('panel'),
                reqres: this.reqres,
                showAddNewButton: this.showAddNewButton,
                listItemView: this.options.listItemView
            },
            panelPosition: 'down-over',
            autoOpen: false
        });
        this.listenTo(this.dropdownView, 'open', this.onFocus);
        this.listenTo(this.dropdownView, 'close', this.onBlur);
        this.dropdownRegion.show(this.dropdownView);

        // hotkeys
        if (this.keyListener) {
            this.keyListener.reset();
        }
        this.keyListener = new keypress.Listener(this.el);
        _.each('down,enter,num_enter'.split(','), function (key) {
            this.keyListener.simple_combo(key, function () {
                if (this.getEnabled() && !this.getReadonly()) {
                    this.dropdownView.open();
                }
            }.bind(this));
        }, this);
    },

    __adjustValue: function (value) {
        if (!value || !value.id) {
            return null;
        }
        if (value instanceof DefaultReferenceModel) {
            return value;
        }
        if (value instanceof Backbone.Model) {
            value = value.attributes;
        }

        return new DefaultReferenceModel(value);
    },

    __value: function (value, triggerChange) {
        if (this.value === value) {
            return;
        }
        this.value = value;
        this.viewModel.get('button').set('value', value);
        this.viewModel.get('panel').set('value', value);
        if (triggerChange) {
            this.__triggerChange();
        }
    },

    isEmptyValue: function () {
        let value = this.getValue();
        return !value || _.isEmpty(value);
    },

    onValueClear: function () {
        this.__value(null, true);
    },

    onValueSet: function (model) {
        this.__value(model, true);
        this.dropdownView.close();
        this.$el.focus();
    },

    onValueNavigate: function () {
       return this.controller.navigate(this.getValue());
    },

    onFilterText: function (options) {
        var deferred = $.Deferred();
        this.controller.fetch(options).then(function () {
            this.viewModel.get('panel').set('totalCount', this.controller.totalCount);
            deferred.resolve();
        }.bind(this));
        return deferred.promise();
    },

    onPanelOpenRequest: function () {
        if (this.getEnabled() && !this.getReadonly()) {
            this.dropdownView.open();
        }
    },

    onAddNewItem:function(){
        this.controller.addNewItem();
    },

    setReadonly: function (readonly) {
        BaseLayoutEditorView.prototype.__setReadonly.call(this, readonly);
        this.viewModel.get('button').set('readonly', this.getReadonly());
    },

    setEnabled: function (enabled) {
        BaseLayoutEditorView.prototype.__setEnabled.call(this, enabled);
        this.viewModel.get('button').set('enabled', this.getEnabled());
    },

    focus: function () {
        this.dropdownView.open();
    },

    blur: function () {
        this.dropdownView.close();
    }
});

export default Backbone.Form.editors.Reference;
<|endoftext|>


<commit_before>/**
 * Internal dependencies
 */
import { MIN_FONT_SIZE, MAX_FONT_SIZE } from '../constants';

/**
 * Calculates font size that fits to the text element based on the element's size.
 * Replicates amp-fit-text's logic in the editor.
 *
 * @see https://github.com/ampproject/amphtml/blob/e7a1b3ff97645ec0ec482192205134bd0735943c/extensions/amp-fit-text/0.1/amp-fit-text.js
 *
 * @param {Object} measurer       HTML element.
 * @param {number} expectedHeight Maximum height.
 * @param {number} expectedWidth  Maximum width.
 *
 * @return {number|boolean} Calculated font size. False if calculation wasn't possible.
 */
export const calculateFitTextFontSize = ( measurer, expectedHeight, expectedWidth ) => {
	let maxFontSize = MAX_FONT_SIZE;
	let minFontSize = MIN_FONT_SIZE;

	// Return false if calculation is not possible due to width and height missing, e.g. in disabled preview.
	if ( ! measurer.offsetHeight || ! measurer.offsetWidth ) {
		return false;
	}
	// @todo Alternatively we could assign a class add CSS for that class.
	// @todo Use isMeasuring state perhaps instead which could influence the CSS directly in the Text block's display.
	// Add necessary styles for measuring:
	measurer.style.display = 'inline-block';
	measurer.style.height = 'initial';
	measurer.style.width = 'initial';
	measurer.style.position = 'absolute';

	maxFontSize++;

	// Binomial search for the best font size.
	while ( maxFontSize - minFontSize > 1 ) {
		const mid = Math.floor( ( minFontSize + maxFontSize ) / 2 );
		measurer.style.fontSize = mid + 'px';
		const currentHeight = measurer.offsetHeight;
		const currentWidth = measurer.offsetWidth;
		if ( currentHeight > expectedHeight || currentWidth > expectedWidth ) {
			maxFontSize = mid;
		} else {
			minFontSize = mid;
		}
	}

	// Let's restore the correct font size, too.
	measurer.style.fontSize = minFontSize + 'px';
	// Restore style values. @todo Get style from the original element instead of just emptying.
	measurer.style.display = '';
	measurer.style.height = '';
	measurer.style.width = '';
	measurer.style.position = '';

	return minFontSize;
};
<commit_msg>Add helper for assigning style.<commit_after>/**
 * Internal dependencies
 */
import { MIN_FONT_SIZE, MAX_FONT_SIZE } from '../constants';

/**
 * Calculates font size that fits to the text element based on the element's size.
 * Replicates amp-fit-text's logic in the editor.
 *
 * @see https://github.com/ampproject/amphtml/blob/e7a1b3ff97645ec0ec482192205134bd0735943c/extensions/amp-fit-text/0.1/amp-fit-text.js
 *
 * @param {Object} measurer       HTML element.
 * @param {number} expectedHeight Maximum height.
 * @param {number} expectedWidth  Maximum width.
 *
 * @return {number|boolean} Calculated font size. False if calculation wasn't possible.
 */
export const calculateFitTextFontSize = ( measurer, expectedHeight, expectedWidth ) => {
	let maxFontSize = MAX_FONT_SIZE;
	let minFontSize = MIN_FONT_SIZE;

	// Return false if calculation is not possible due to width and height missing, e.g. in disabled preview.
	if ( ! measurer.offsetHeight || ! measurer.offsetWidth ) {
		return false;
	}

	const setStyle = ( style ) => {
		const rules = Object.entries( style );
		for ( const [ k, value ] of rules ) {
			measurer.style[ k ] = value;
		}
	};

	const originalStyle = {
		display: measurer.style.display,
		height: measurer.style.height,
		width: measurer.style.width,
		position: measurer.style.position,
	};

	const measuringStyle = {
		display: 'inline-block',
		height: 'initial',
		width: 'initial',
		position: 'absolute',
	};

	// Add necessary styles for measuring:
	setStyle( measuringStyle );

	maxFontSize++;

	// Binomial search for the best font size.
	while ( maxFontSize - minFontSize > 1 ) {
		const mid = Math.floor( ( minFontSize + maxFontSize ) / 2 );
		measurer.style.fontSize = mid + 'px';
		const currentHeight = measurer.offsetHeight;
		const currentWidth = measurer.offsetWidth;
		if ( currentHeight > expectedHeight || currentWidth > expectedWidth ) {
			maxFontSize = mid;
		} else {
			minFontSize = mid;
		}
	}

	// Let's restore the correct font size, too.
	measurer.style.fontSize = minFontSize + 'px';
	// Restore style values.
	setStyle( originalStyle );

	return minFontSize;
};
<|endoftext|>


<commit_before>var MarkupText = {
    HandlesType: function(type) {
        return type == 'text';
    },

    Paint: function(elementObject) {
        $('#' + elementObject.Handle).text(elementObject.text);
    },

    Activate: function(elementObject) {

    },

    Update: function(elementObject) {

    },

    New: function(markup, text) {
       markup.AddElement({
           type: "text",
           text: text ? text : "New textfield",
           x: 10,
           y: 10
       });
    }
};
<commit_msg>Add tool window properties for the Text plugin<commit_after>var MarkupText = {
    HandlesType: function(type) {
        return type == 'text';
    },

    Paint: function(elementObject) {
        $('#' + elementObject.Handle)
            .text(elementObject.text)
            .css({
                whiteSpace: 'pre-wrap',
                left: SizeCalculator.ToPixels(elementObject.x) + 'px',
                top: SizeCalculator.ToPixels(elementObject.y) + 'px',
                color: elementObject.color,
                fontSize: elementObject.size + 'px',
                fontWeight: elementObject.bold ? 'bold' : 'normal'
            });
    },

    Activate: function(elementObject) {

    },

    Update: function(elementObject) {
        this.Paint(elementObject);
    },

    New: function(markup, text) {
       markup.AddElement({
           type: "text",
           text: text ? text : "New textfield",
           x: 10,
           y: 10,
           color: '#00000',
           size: 12,
           bold: false,
           properties: {
               text: {
                   label: 'Text',
                   component: 'textarea'
               },
               x: {
                   label: 'Left (mm)',
                   component: 'number'
               },
               y: {
                   label: 'Top (mm)',
                   component: 'number'
               },
               color: {
                   label: 'Color',
                   component: 'select',
                   items: {
                       'Black': '#00000',
                       'Silver': '#C0C0C0',
                   }
               },
               size: {
                   label: 'Size',
                   component: 'select',
                   items: {
                       '8': '8',
                       '9': '9',
                       '10': '10',
                       '11': '11',
                       '12': '12',
                       '13': '13',
                       '14': '14',
                       '15': '15',
                       '16': '16',
                       '17': '17',
                       '18': '18',
                       '19': '19',
                       '20': '20'
                   }
               },
               bold: {
                   'label': 'Bold',
                   component: 'boolean'
               }
           }
       });
    }
};
<|endoftext|>


<commit_before>const average = numbers => {
  const valid = numbers.filter(number => undefined !== number && 0 !== number);
  const total = valid.reduce((sum, val) => sum + val, 0);
  return total / valid.length;
};

const terrainObject = (detailLevel) => {
  const size = Math.pow(2, detailLevel) + 1;
  let heightMap = new Float32Array(size * size);
  return {
    get: (x, y) => heightMap[x + (size) * y],
    set: (x, y, val) => heightMap[x + (size)  * y] = val,
    heightMap: heightMap,
    size: size,
    maxXY: size - 1,
  };
};

/**
 * Generate random terrain using diamond-square algorithm.
 *
 * Code adapted from @hunterloftis (https://github.com/hunterloftis/playfuljs-demos/blob/gh-pages/terrain/index.html)
 */
const diamondSquareGeneration = (terrain, roughness = 0.7) => {
  // Set corners
  terrain.set(0, 0, 0.1);
  terrain.set(terrain.maxXY, 0, 0.1);
  terrain.set(0, terrain.maxXY, 0.1);
  terrain.set(terrain.maxXY, terrain.maxXY, 0.1);

  const square = (x, y, size, offset) => {
    const avg = average([
      terrain.get(x - size, y - size),
      terrain.get(x + size, y - size),
      terrain.get(x + size, y + size),
      terrain.get(x - size, y + size),
    ]);
    terrain.set(x, y, avg + offset);
  };

  const diamond = (x, y, size, offset) => {
    const avg = average([
      terrain.get(x, y - size),
      terrain.get(x + size, y),
      terrain.get(x, y + size),
      terrain.get(x - size, y),
    ]);
    terrain.set(x, y, avg + offset);
  };

  const divide = (size) => {
    const half = size / 2;
    if (half < 1) return;
    const scale = size * roughness;

    for (let y = half; y < terrain.maxXY; y += size) {
      for (let x = half; x < terrain.maxXY; x += size) {
        square(x, y, half, Math.random() * scale * 2 - scale);
      }
    }

    for (let y = 0; y <= terrain.maxXY; y += half) {
      for (let x = (y + half) % size; x <= terrain.maxXY; x += size) {
        diamond(x, y, half, Math.random() * scale * 2 - scale);
      }
    }

    divide(half);
  };

  divide(terrain.maxXY);
};

const generate = (detailLevel) => {
  let terrain = terrainObject(detailLevel);

  diamondSquareGeneration(terrain);

  return terrain;
};

export default {
  generate
};
<commit_msg>Tweaked settings of diamondSquareGeneration and made corners random height<commit_after>const average = numbers => {
  const valid = numbers.filter(number => undefined !== number && 0 !== number);
  const total = valid.reduce((sum, val) => sum + val, 0);
  return total / valid.length;
};

const terrainObject = (detailLevel) => {
  const size = Math.pow(2, detailLevel) + 1;
  let heightMap = new Float32Array(size * size);
  return {
    get: (x, y) => heightMap[x + (size) * y],
    set: (x, y, val) => heightMap[x + (size)  * y] = val,
    heightMap: heightMap,
    size: size,
    maxXY: size - 1,
  };
};

/**
 * Generate random terrain using diamond-square algorithm.
 *
 * Code adapted from @hunterloftis (https://github.com/hunterloftis/playfuljs-demos/blob/gh-pages/terrain/index.html)
 */
const diamondSquareGeneration = (terrain, roughness = 0.4) => {
  // Set corners
  terrain.set(0, 0, Math.random());
  terrain.set(terrain.maxXY, 0, Math.random());
  terrain.set(0, terrain.maxXY, Math.random());
  terrain.set(terrain.maxXY, terrain.maxXY, Math.random());

  const square = (x, y, size, offset) => {
    const avg = average([
      terrain.get(x - size, y - size),
      terrain.get(x + size, y - size),
      terrain.get(x + size, y + size),
      terrain.get(x - size, y + size),
    ]);
    terrain.set(x, y, avg + offset);
  };

  const diamond = (x, y, size, offset) => {
    const avg = average([
      terrain.get(x, y - size),
      terrain.get(x + size, y),
      terrain.get(x, y + size),
      terrain.get(x - size, y),
    ]);
    terrain.set(x, y, avg + offset);
  };

  const divide = (size) => {
    const half = size / 2;
    if (half < 1) return;
    const scale = size * roughness;

    for (let y = half; y < terrain.maxXY; y += size) {
      for (let x = half; x < terrain.maxXY; x += size) {
        square(x, y, half, Math.random() * scale * 2 - scale);
      }
    }

    for (let y = 0; y <= terrain.maxXY; y += half) {
      for (let x = (y + half) % size; x <= terrain.maxXY; x += size) {
        diamond(x, y, half, Math.random() * scale * 2 - scale);
      }
    }

    divide(half);
  };

  divide(terrain.maxXY);
};

const generate = (detailLevel) => {
  let terrain = terrainObject(detailLevel);

  diamondSquareGeneration(terrain);

  return terrain;
};

export default {
  generate
};
<|endoftext|>


<commit_before>'use strict';

APP_LOCAL_ROUTES.dynamics = '/dynamics/:simulationId';

app.config(function($routeProvider, localRoutesProvider) {
    var localRoutes = localRoutesProvider.$get();
    $routeProvider
        .when(localRoutes.source, {
            controller: 'WARPSourceController as source',
            templateUrl: '/static/html/warp-source.html?' + SIREPO_APP_VERSION,
        })
        .when(localRoutes.dynamics, {
            controller: 'WARPDynamicsController as dynamics',
            templateUrl: '/static/html/warp-dynamics.html?' + SIREPO_APP_VERSION,
        });
});

app.controller('WARPDynamicsController', function(activeSection, appState, panelState, requestSender, frameCache, $timeout, $scope) {
    activeSection.setActiveSection('dynamics');
    var self = this;
    self.panelState = panelState;
    self.percentComplete = 0;
    self.totalFrames = 0;
    self.isDestroyed = false;
    self.isAborting = false;
    self.dots = '.';

    frameCache.setAnimationArgs({
        fieldAnimation: ['field', 'coordinate', 'mode'],
        particleAnimation: ['x', 'y', 'histogramBins'],
    });
    frameCache.setFrameCount(0);

    $scope.$on('$destroy', function () {
        self.isDestroyed = true;
    });

    function refreshStatus() {
        requestSender.sendRequest(
            'runStatus',
            function(data) {
                frameCache.setFrameCount(data.frameCount);
                self.totalFrames = data.totalFrames;
                if (self.isAborting)
                    return;
                if (data.state != 'running') {
                    if (data.state != appState.models.simulationStatus.state)
                        appState.saveChanges('simulationStatus');
                }
                else {
                    self.percentComplete = data.percentComplete;
                    if (! self.isDestroyed) {
                        self.dots += '.';
                        if (self.dots.length > 3)
                            self.dots = '.';
                        $timeout(refreshStatus, 2000);
                    }
                }
                appState.models.simulationStatus.state = data.state;
            },
            {
                models: appState.applicationState(),
                simulationType: APP_SCHEMA.simulationType,
            });
    }

    self.cancelSimulation = function() {
        if (appState.models.simulationStatus.state != 'running')
            return;
        appState.models.simulationStatus.state = 'canceled';
        self.isAborting = true;
        requestSender.sendRequest(
            'runCancel',
            function(data) {
                self.isAborting = false;
                appState.saveChanges('simulationStatus');
            },
            {
                models: appState.applicationState(),
                simulationType: APP_SCHEMA.simulationType,
            });
    };

    self.displayPercentComplete = function() {
        if (self.percentComplete < 1)
            return 100;
        return self.percentComplete;
    };

    self.getFrameCount = function() {
        return frameCache.frameCount;
    };

    self.isInitializing = function() {
        if (self.isState('running'))
            return self.percentComplete < 1;
        return false;
    };

    self.isState = function(state) {
        if (appState.isLoaded())
            return appState.models.simulationStatus.state == state;
        return false;
    };

    self.runSimulation = function() {
        if (appState.models.simulationStatus.state == 'running')
            return;
        frameCache.setFrameCount(0);
        appState.models.simulationStatus.state = 'running';
        requestSender.sendRequest(
            'runBackground',
            function(data) {
                appState.models.simulationStatus.startTime = data['startTime'];
                appState.saveChanges('simulationStatus');
                refreshStatus();
            },
            {
                models: appState.applicationState(),
                simulationType: APP_SCHEMA.simulationType,
            });
    };

    if (appState.isLoaded())
        refreshStatus();
    else {
        $scope.$on('modelsLoaded', refreshStatus);
    }
});

app.controller('WARPSourceController', function($scope, activeSection, appState) {
    activeSection.setActiveSection('source');
    var self = this;
    $scope.appState = appState;
    var constants = {
        echarge: 1.602176565e-19,
        eps0: 8.85418781762e-12,
        emass: 9.10938291e-31,
        clight: 299792458.0,
        gammafrm: 1.0,
    };
    constants.betafrm = Math.sqrt(1.0 -1.0 / Math.pow(constants.gammafrm, 2));

    function calculateWaistAndLength(newValue, oldValue) {
        if (newValue)
            recalculateWaistAndLength();
    }

    function recalculateWaistAndLength() {
        var laserPulse = appState.models.laserPulse;
        if (laserPulse.pulseDimensions == 'r') {
            var wplab = Math.sqrt(
                appState.models.electronPlasma.density
                    * Math.pow(constants.echarge, 2)
                    / (constants.eps0 * constants.emass));
            var kplab = wplab / constants.clight;
            laserPulse.waist = (1e6 * laserPulse.spotSize / kplab).toFixed(12);
            laserPulse.duration = (1e12 * laserPulse.length / kplab / constants.clight).toFixed(12);
            recalculateXZMinMax();
        }
    }

    function calculateXZMinMax(newValue, oldValue) {
        if (newValue)
            recalculateXZMinMax();
    }

    function recalculateXZMinMax() {
        var grid = appState.models.simulationGrid;
        if (grid.gridDimensions == 's') {
            var laserPulse = appState.models.laserPulse;
            var totalLength = laserPulse.duration / 1e12 * 4 * constants.clight;
            grid.xMax = (2.5 * totalLength * 1e6).toFixed(12);
            grid.xMin = (-grid.xMax).toFixed(12);
            grid.zMin = (-1.3 * totalLength * 1e6).toFixed(12);
            var lambdaLaser = laserPulse.wavelength / 1e6 * constants.gammafrm * (1.0 + constants.betafrm);
            grid.zMax = (2.0 * lambdaLaser * 1e6).toFixed(12);
            grid.zCount = Math.round((grid.zMax - grid.zMin) / 1e6 * grid.zLambda / lambdaLaser);
        }
    }

    function fieldClass(field) {
        return '.model-' + field.replace('.', '-');
    }

    function setVisibility(fields, isVisible, oldValue) {
        for (var i = 0; i < fields.length; i++) {
            var fc = fieldClass(fields[i]);
            if (isVisible) {
                if (oldValue)
                    $(fc).parent().slideDown()
            }
            else {
                if (oldValue)
                    $(fc).parent().slideUp()
                else
                    $(fc).parent().hide();
            }
        }
    }

    function setReadOnly(fields, isReadOnly) {
        for (var i = 0; i < fields.length; i++) {
            $(fieldClass(fields[i]) + ' input').prop('readonly', isReadOnly);
        }
    }

    function gridDimensionsChanged(newValue, oldValue) {
        if (newValue) {
            var fields = ['simulationGrid.xMin', 'simulationGrid.xMax', 'simulationGrid.zMin', 'simulationGrid.zMax', 'simulationGrid.zCount'];
            if (newValue == 'a') {
                setVisibility(['simulationGrid.zLambda'], false, oldValue);
                setReadOnly(fields, false);
            }
            else {
                setVisibility(['simulationGrid.zLambda'], true, oldValue);
                setReadOnly(fields, true);
                recalculateXZMinMax();
            }
        }
    }

    function pulseDimensionsChanged(newValue, oldValue) {
        if (newValue) {
            var fields = ['laserPulse.waist', 'laserPulse.duration'];
            if (newValue == 'a') {
                setVisibility(['laserPulse.length', 'laserPulse.spotSize'], false, oldValue);
                setReadOnly(fields, false);
            }
            else {
                setVisibility(['laserPulse.length', 'laserPulse.spotSize'], true, oldValue);
                setReadOnly(fields, true);
                recalculateWaistAndLength();
            }
        }
    }

    $scope.$watch('appState.models.laserPulse.pulseDimensions', pulseDimensionsChanged);
    $scope.$watch('appState.models.laserPulse.length', calculateWaistAndLength);
    $scope.$watch('appState.models.laserPulse.spotSize', calculateWaistAndLength);
    $scope.$watch('appState.models.electronPlasma.density', calculateWaistAndLength);
    $scope.$watch('appState.models.simulationGrid.gridDimensions', gridDimensionsChanged);
    $scope.$watch('appState.models.simulationGrid.zLambda', calculateXZMinMax);
    $scope.$watch('appState.models.laserPulse.duration', calculateXZMinMax);
    $scope.$watch('appState.models.laserPulse.wavelength', calculateXZMinMax);

    $scope.$on(
        'laserPulse.changed',
        function() {
            if (appState.models.simulationGrid.gridDimensions == 's')
                appState.saveQuietly('simulationGrid');
        });
    $scope.$on(
        'electronPlasma.changed',
        function() {
            if (appState.models.simulationGrid.gridDimensions == 's')
                appState.saveQuietly('simulationGrid');
            if (appState.models.laserPulse.pulseDimensions == 'r')
                appState.saveQuietly('laserPulse');
        });

});
<commit_msg>simplified value recalculation, ensure visible/enabled state gets set if UI is not yet available<commit_after>'use strict';

APP_LOCAL_ROUTES.dynamics = '/dynamics/:simulationId';

app.config(function($routeProvider, localRoutesProvider) {
    var localRoutes = localRoutesProvider.$get();
    $routeProvider
        .when(localRoutes.source, {
            controller: 'WARPSourceController as source',
            templateUrl: '/static/html/warp-source.html?' + SIREPO_APP_VERSION,
        })
        .when(localRoutes.dynamics, {
            controller: 'WARPDynamicsController as dynamics',
            templateUrl: '/static/html/warp-dynamics.html?' + SIREPO_APP_VERSION,
        });
});

app.controller('WARPDynamicsController', function(activeSection, appState, panelState, requestSender, frameCache, $timeout, $scope) {
    activeSection.setActiveSection('dynamics');
    var self = this;
    self.panelState = panelState;
    self.percentComplete = 0;
    self.totalFrames = 0;
    self.isDestroyed = false;
    self.isAborting = false;
    self.dots = '.';

    frameCache.setAnimationArgs({
        fieldAnimation: ['field', 'coordinate', 'mode'],
        particleAnimation: ['x', 'y', 'histogramBins'],
    });
    frameCache.setFrameCount(0);

    $scope.$on('$destroy', function () {
        self.isDestroyed = true;
    });

    function refreshStatus() {
        requestSender.sendRequest(
            'runStatus',
            function(data) {
                frameCache.setFrameCount(data.frameCount);
                self.totalFrames = data.totalFrames;
                if (self.isAborting)
                    return;
                if (data.state != 'running') {
                    if (data.state != appState.models.simulationStatus.state)
                        appState.saveChanges('simulationStatus');
                }
                else {
                    self.percentComplete = data.percentComplete;
                    if (! self.isDestroyed) {
                        self.dots += '.';
                        if (self.dots.length > 3)
                            self.dots = '.';
                        $timeout(refreshStatus, 2000);
                    }
                }
                appState.models.simulationStatus.state = data.state;
            },
            {
                models: appState.applicationState(),
                simulationType: APP_SCHEMA.simulationType,
            });
    }

    self.cancelSimulation = function() {
        if (appState.models.simulationStatus.state != 'running')
            return;
        appState.models.simulationStatus.state = 'canceled';
        self.isAborting = true;
        requestSender.sendRequest(
            'runCancel',
            function(data) {
                self.isAborting = false;
                appState.saveChanges('simulationStatus');
            },
            {
                models: appState.applicationState(),
                simulationType: APP_SCHEMA.simulationType,
            });
    };

    self.displayPercentComplete = function() {
        if (self.percentComplete < 1)
            return 100;
        return self.percentComplete;
    };

    self.getFrameCount = function() {
        return frameCache.frameCount;
    };

    self.isInitializing = function() {
        if (self.isState('running'))
            return self.percentComplete < 1;
        return false;
    };

    self.isState = function(state) {
        if (appState.isLoaded())
            return appState.models.simulationStatus.state == state;
        return false;
    };

    self.runSimulation = function() {
        if (appState.models.simulationStatus.state == 'running')
            return;
        frameCache.setFrameCount(0);
        appState.models.simulationStatus.state = 'running';
        requestSender.sendRequest(
            'runBackground',
            function(data) {
                appState.models.simulationStatus.startTime = data['startTime'];
                appState.saveChanges('simulationStatus');
                refreshStatus();
            },
            {
                models: appState.applicationState(),
                simulationType: APP_SCHEMA.simulationType,
            });
    };

    if (appState.isLoaded())
        refreshStatus();
    else {
        $scope.$on('modelsLoaded', refreshStatus);
    }
});

app.controller('WARPSourceController', function($scope, activeSection, appState, $timeout) {
    activeSection.setActiveSection('source');
    var self = this;
    $scope.appState = appState;
    var constants = {
        echarge: 1.602176565e-19,
        eps0: 8.85418781762e-12,
        emass: 9.10938291e-31,
        clight: 299792458.0,
        gammafrm: 1.0,
    };
    constants.betafrm = Math.sqrt(1.0 -1.0 / Math.pow(constants.gammafrm, 2));

    function fieldClass(field) {
        return '.model-' + field.replace('.', '-');
    }

    function setVisibility(fields, isVisible, oldValue) {
        for (var i = 0; i < fields.length; i++) {
            var el = $(fieldClass(fields[i])).parent();
            if (isVisible) {
                if (oldValue)
                    el.slideDown()
            }
            else {
                if (oldValue)
                    el.slideUp()
                else
                    el.hide();
            }
        }
    }

    function setReadOnly(fields, isReadOnly) {
        for (var i = 0; i < fields.length; i++) {
            $(fieldClass(fields[i]) + ' input').prop('readonly', isReadOnly);
        }
    }

    function gridDimensionsChanged(newValue, oldValue) {
        if (! appState.isLoaded())
            return;
        var fields = {
            visible: ['simulationGrid.zLambda'],
            editable: ['simulationGrid.xMin', 'simulationGrid.xMax', 'simulationGrid.zMin', 'simulationGrid.zMax', 'simulationGrid.zCount'],
        };
        var isAbsolute = appState.models.simulationGrid.gridDimensions == 'a';
        setVisibility(fields.visible, ! isAbsolute, oldValue);
        setReadOnly(fields.editable, ! isAbsolute);
        recalcValues();
    }

    function pulseDimensionsChanged(newValue, oldValue) {
        if (! appState.isLoaded())
            return;
        var fields = {
            visible: ['laserPulse.length', 'laserPulse.spotSize'],
            editable: ['laserPulse.waist', 'laserPulse.duration'],
        };
        var isAbsolute = appState.models.laserPulse.pulseDimensions == 'a';
        setVisibility(fields.visible, ! isAbsolute, oldValue);
        setReadOnly(fields.editable, ! isAbsolute);
        recalcValues();
    }

    function recalcValues() {
        if (! appState.isLoaded())
            return;
        var laserPulse = appState.models.laserPulse;
        // resonant wth plasma density
        if (laserPulse.pulseDimensions == 'r') {
            var wplab = Math.sqrt(
                appState.models.electronPlasma.density
                    * Math.pow(constants.echarge, 2)
                    / (constants.eps0 * constants.emass));
            var kplab = wplab / constants.clight;
            laserPulse.waist = (1e6 * laserPulse.spotSize / kplab).toFixed(12);
            laserPulse.duration = (1e12 * laserPulse.length / kplab / constants.clight).toFixed(12);
        }
        var grid = appState.models.simulationGrid;
        // scale to laser pulse
        if (grid.gridDimensions == 's') {
            var totalLength = laserPulse.duration / 1e12 * 4 * constants.clight;
            grid.xMax = (2.5 * totalLength * 1e6).toFixed(12);
            grid.xMin = (-grid.xMax).toFixed(12);
            grid.zMin = (-1.3 * totalLength * 1e6).toFixed(12);
            var lambdaLaser = laserPulse.wavelength / 1e6 * constants.gammafrm * (1.0 + constants.betafrm);
            grid.zMax = (2.0 * lambdaLaser * 1e6).toFixed(12);
            grid.zCount = Math.round((grid.zMax - grid.zMin) / 1e6 * grid.zLambda / lambdaLaser);
        }
    }

    $scope.$watch('appState.models.laserPulse.pulseDimensions', pulseDimensionsChanged);
    $scope.$watch('appState.models.laserPulse.length', recalcValues);
    $scope.$watch('appState.models.laserPulse.spotSize', recalcValues);
    $scope.$watch('appState.models.electronPlasma.density', recalcValues);
    $scope.$watch('appState.models.simulationGrid.gridDimensions', gridDimensionsChanged);
    $scope.$watch('appState.models.simulationGrid.zLambda', recalcValues);
    $scope.$watch('appState.models.laserPulse.duration', recalcValues);
    $scope.$watch('appState.models.laserPulse.wavelength', recalcValues);

    if (appState.isLoaded()) {
        if (! $(fieldClass('simulationGrid.xMin') + ' input').length) {
            $timeout(function() {
                gridDimensionsChanged();
                pulseDimensionsChanged();
            }, 100);
        }
    }

    $scope.$on(
        'laserPulse.changed',
        function() {
            if (appState.models.simulationGrid.gridDimensions == 's')
                appState.saveQuietly('simulationGrid');
        });
    $scope.$on(
        'electronPlasma.changed',
        function() {
            if (appState.models.simulationGrid.gridDimensions == 's')
                appState.saveQuietly('simulationGrid');
            if (appState.models.laserPulse.pulseDimensions == 'r')
                appState.saveQuietly('laserPulse');
        });

});
<|endoftext|>


<commit_before>import angular from 'angular';
import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import { Quizzes } from "../publishers/quizPublisher";
import { Questions } from "../publishers/questionPublisher.js";

export const QuizzesStatistics = new Mongo.Collection('QuizzesStatistics');
export const QuestionsStatistics = new Mongo.Collection('QuestionsStatistics');
export const UsersStatistics = new Mongo.Collection('UsersStatistics');

if (Meteor.isServer)
{
	Meteor.publish('QuizzesStatistics', function tasksPublication() {
	return QuizzesStatistics.find();
	});
}
if (Meteor.isServer)
{
	Meteor.publish('QuestionsStatistics', function tasksPublication() {
	return QuestionsStatistics.find();
	});
}
if (Meteor.isServer)
{
	Meteor.publish('UsersStatistics', function tasksPublication() {
	return UsersStatistics.find();
	});
}

Meteor.methods({
	"statistics.QuizExecutionStats" (QuizObject, UserID) {
		QuizzesStatistics.insert({
			QuizObject,
			UserID,
			doneAt: new Date()
		});

		Quizzes.update(
			{ "_id" : QuizObject._id },
			{ $inc: { "esecuzioni" : 1 } }
		);

		for (var i = 0, len = arr.length; i < len; i++) {
			var conta = 0;
			if (QuizObject.questions[i].type === "VF")
			{	if(QuizObject.questions[i].ans === QuizObject.questions[i].risp)
				{
					conta = 1;
				}

			}
			else if (this.myQuiz[i].type === "MU")
			{	if(QuizObject.questions[i].rightAns == QuizObject.questions[i].risp )
				{
					conta = 1;
				}

			}
			else if (QuizObject.questions[i].type === "MX")
			{	var sentinella = true;
				var lo_quiz = QuizObject.questions[i];
				var lo_ans = lo_quiz.ans;
				if(lo_quiz.risp !== undefined)
				{
					for(var j = 0; j < lo_ans.length; j++)
					{
						if(  lo_quiz.risp[lo_ans[j].id] === undefined )
						{
							lo_quiz.risp[lo_ans[j].id] = false;
						}
						if( lo_quiz.rightAns[lo_ans[j].id] !== lo_quiz.risp[lo_ans[j].id] )
						{
							sentinella = false;
						}
					}
					if( sentinella === true ){ conta = 1;}
				}
			}
			else if (QuizObject.questions[i].type === "AS")
			{
				if ( angular.equals( QuizObject.questions[i].rightAns , QuizObject.questions[i].risp ) )
				{
					conta = 1;
				}
			}
			else if (QuizObject.questions[i].type === "OD")
			{
				if ( angular.equals( QuizObject.questions[i].rightAns , QuizObject.questions[i].risp ) )
				{
					conta = 1;
				}
			}

			Meteor.call("statistics.QuestionExecutionStats", QuizObject.questions[i]._id, conta);
			Meteor.call("statistics.UserExecutionStats", QuizObject._idUser, 1, conta);
		}
	},

	"statistics.UserExecutionStats" (UserID, QuestionAnswered, QuestionCorrectAnswered) {
		UsersStatistics.update(
			{"_id" : UserID},
			{ $inc: { "AnsweredQuestions" : QuestionAnswered, "CorrectAnswers" : QuestionCorrectAnswered} }
		);
	},

	"statistics.QuestionExecutionStats" (QuestionID, Correct) {
		QuestionsStatistics.update(
			{"_id" : QuestionID},
			{ $inc: { "rispCorrette" : Correct, "voltePresentata" : 1 } }
		);
	}
});<commit_msg>dubbio enorme<commit_after>import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import { Quizzes } from "../publishers/quizPublisher";
import { Questions } from "../publishers/questionPublisher.js";

export const QuizzesStatistics = new Mongo.Collection('QuizzesStatistics');
export const QuestionsStatistics = new Mongo.Collection('QuestionsStatistics');
export const UsersStatistics = new Mongo.Collection('UsersStatistics');

if (Meteor.isServer)
{
	Meteor.publish('QuizzesStatistics', function tasksPublication() {
	return QuizzesStatistics.find();
	});
}
if (Meteor.isServer)
{
	Meteor.publish('QuestionsStatistics', function tasksPublication() {
	return QuestionsStatistics.find();
	});
}
if (Meteor.isServer)
{
	Meteor.publish('UsersStatistics', function tasksPublication() {
	return UsersStatistics.find();
	});
}

Meteor.methods({
	"statistics.QuizExecutionStats" (QuizObject, UserID) {
		QuizzesStatistics.insert({
			QuizObject,
			UserID,
			doneAt: new Date()
		});

		Quizzes.update(
			{ "_id" : QuizObject._id },
			{ $inc: { "esecuzioni" : 1 } }
		);

		for (var i = 0, len = arr.length; i < len; i++) {
			var conta = 0;
			if (QuizObject.questions[i].type === "VF")
			{	if(QuizObject.questions[i].ans === QuizObject.questions[i].risp)
				{
					conta = 1;
				}

			}
			else if (this.myQuiz[i].type === "MU")
			{	if(QuizObject.questions[i].rightAns == QuizObject.questions[i].risp )
				{
					conta = 1;
				}

			}
			else if (QuizObject.questions[i].type === "MX")
			{	var sentinella = true;
				var lo_quiz = QuizObject.questions[i];
				var lo_ans = lo_quiz.ans;
				if(lo_quiz.risp !== undefined)
				{
					for(var j = 0; j < lo_ans.length; j++)
					{
						if(  lo_quiz.risp[lo_ans[j].id] === undefined )
						{
							lo_quiz.risp[lo_ans[j].id] = false;
						}
						if( lo_quiz.rightAns[lo_ans[j].id] !== lo_quiz.risp[lo_ans[j].id] )
						{
							sentinella = false;
						}
					}
					if( sentinella === true ){ conta = 1;}
				}
			}
			else if (QuizObject.questions[i].type === "AS")
			{
				if ( angular.equals( QuizObject.questions[i].rightAns , QuizObject.questions[i].risp ) )
				{
					conta = 1;
				}
			}
			else if (QuizObject.questions[i].type === "OD")
			{
				if ( angular.equals( QuizObject.questions[i].rightAns , QuizObject.questions[i].risp ) )
				{
					conta = 1;
				}
			}

			Meteor.call("statistics.QuestionExecutionStats", QuizObject.questions[i]._id, conta);
			Meteor.call("statistics.UserExecutionStats", QuizObject._idUser, 1, conta);
		}
	},

	"statistics.UserExecutionStats" (UserID, QuestionAnswered, QuestionCorrectAnswered) {
		UsersStatistics.update(
			{"_id" : UserID},
			{ $inc: { "AnsweredQuestions" : QuestionAnswered, "CorrectAnswers" : QuestionCorrectAnswered} }
		);
	},

	"statistics.QuestionExecutionStats" (QuestionID, Correct) {
		QuestionsStatistics.update(
			{"_id" : QuestionID},
			{ $inc: { "rispCorrette" : Correct, "voltePresentata" : 1 } }
		);
	}
});<|endoftext|>


<commit_before>'use strict';
angular.module('core',['ngGrid']).controller('UtilizationController', ['$scope', 'Authentication',
	function($scope, Authentication) {
		// This provides Authentication context.
		$scope.authentication = Authentication;

        // Some example string
        $scope.helloText = 'Utilization View';
        $scope.descriptionText = 'This shows the utilization of the resources';

        //Data For Table
        $scope.ngData = [
        {Name: "Moroni", Age: 50, Position: 'PR Menager', Status: 'active', Date: '12.12.2014'},
        {Name: "Teancum", Age: 43, Position: 'CEO/CFO', Status: 'deactive', Date: '10.10.2014'},
        {Name: "Jacob", Age: 27, Position: 'UI Designer', Status: 'active', Date: '09.11.2013'},
        {Name: "Nephi", Age: 29, Position: 'Java programmer', Status: 'deactive', Date: '22.10.2014'},
        {Name: "Joseph", Age: 22, Position: 'Marketing manager', Status: 'active', Date: '24.08.2013'},
        {Name: "Monica", Age: 43, Position: 'President', Status: 'active', Date: '11.12.2014'},
        {Name: "Arnold", Age: 12, Position: 'CEO', Status: 'active', Date: '07.10.2013'},
        {Name: "Mark", Age: 54, Position: 'Analyst', Status: 'deactive', Date: '03.03.2014'},
        {Name: "Amelia", Age: 33, Position: 'Sales manager', Status: 'deactive', Date: '26.09.2013'},
        {Name: "Jesica", Age: 41, Position: 'Ruby programmer', Status: 'active', Date: '22.12.2013'},
        {Name: "John", Age: 48, Position: 'Marketing manager', Status: 'deactive', Date: '09.10.2014'},
        {Name: "Berg", Age: 19, Position: 'UI/UX Designer', Status: 'active', Date: '12.11.2013'}
    ];

    $scope.utilTable = { data: 'ngData' };

        //Data for Line Chart

   /**
     * Data for Line chart
     */
    this.lineData = {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [
            {
                label: "Example dataset",
                fillColor: "rgba(220,220,220,0.5)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "rgba(220,220,220,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: [65, 59, 80, 81, 56, 55, 40]
            },
            {
                label: "Example dataset",
                fillColor: "rgba(26,179,148,0.5)",
                strokeColor: "rgba(26,179,148,0.7)",
                pointColor: "rgba(26,179,148,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(26,179,148,1)",
                data: [28, 48, 40, 19, 86, 27, 90]
            }
        ]
    };

    /**
     * Options for Line chart
     */
    this.lineOptions = {
        scaleShowGridLines : true,
        scaleGridLineColor : "rgba(0,0,0,.05)",
        scaleGridLineWidth : 1,
        bezierCurve : true,
        bezierCurveTension : 0.4,
        pointDot : true,
        pointDotRadius : 4,
        pointDotStrokeWidth : 1,
        pointHitDetectionRadius : 20,
        datasetStroke : true,
        datasetStrokeWidth : 2,
        datasetFill : true
    };
   /* var ctx = document.getElementById("lineChart").getContext('2d');
    var myLineChart= new Chart(ctx).Line(data,option);*/

        this.polarData = [
        {
            value: 300,
            color:"#a3e1d4",
            highlight: "#1ab394",
            label: "App"
        },
        {
            value: 140,
            color: "#dedede",
            highlight: "#1ab394",
            label: "Software"
        },
        {
            value: 200,
            color: "#A4CEE8",
            highlight: "#1ab394",
            label: "Laptop"
        }
    ];

    /**
     * Options for Polar chart
     */
    this.polarOptions = {
        scaleShowLabelBackdrop : true,
        scaleBackdropColor : "rgba(255,255,255,0.75)",
        scaleBeginAtZero : true,
        scaleBackdropPaddingY : 1,
        scaleBackdropPaddingX : 1,
        scaleShowLine : true,
        segmentShowStroke : true,
        segmentStrokeColor : "#fff",
        segmentStrokeWidth : 2,
        animationSteps : 100,
        animationEasing : "easeOutBounce",
        animateRotate : true,
        animateScale : false
    };

   	}
]);<commit_msg>Bower updates<commit_after>'use strict';
angular.module('core').controller('UtilizationController', ['$scope', 'Authentication',
	function($scope, Authentication) {
		// This provides Authentication context.
		$scope.authentication = Authentication;

        // Some example string
        $scope.helloText = 'Utilization View';
        $scope.descriptionText = 'This shows the utilization of the resources';

        //Data For Table
        $scope.ngData = [
        {Name: "Moroni", Age: 50, Position: 'PR Menager', Status: 'active', Date: '12.12.2014'},
        {Name: "Teancum", Age: 43, Position: 'CEO/CFO', Status: 'deactive', Date: '10.10.2014'},
        {Name: "Jacob", Age: 27, Position: 'UI Designer', Status: 'active', Date: '09.11.2013'},
        {Name: "Nephi", Age: 29, Position: 'Java programmer', Status: 'deactive', Date: '22.10.2014'},
        {Name: "Joseph", Age: 22, Position: 'Marketing manager', Status: 'active', Date: '24.08.2013'},
        {Name: "Monica", Age: 43, Position: 'President', Status: 'active', Date: '11.12.2014'},
        {Name: "Arnold", Age: 12, Position: 'CEO', Status: 'active', Date: '07.10.2013'},
        {Name: "Mark", Age: 54, Position: 'Analyst', Status: 'deactive', Date: '03.03.2014'},
        {Name: "Amelia", Age: 33, Position: 'Sales manager', Status: 'deactive', Date: '26.09.2013'},
        {Name: "Jesica", Age: 41, Position: 'Ruby programmer', Status: 'active', Date: '22.12.2013'},
        {Name: "John", Age: 48, Position: 'Marketing manager', Status: 'deactive', Date: '09.10.2014'},
        {Name: "Berg", Age: 19, Position: 'UI/UX Designer', Status: 'active', Date: '12.11.2013'}
    ];

    $scope.utilTable = { data: 'ngData' };

        //Data for Line Chart

   /**
     * Data for Line chart
     */
    this.lineData = {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [
            {
                label: "Example dataset",
                fillColor: "rgba(220,220,220,0.5)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "rgba(220,220,220,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: [65, 59, 80, 81, 56, 55, 40]
            },
            {
                label: "Example dataset",
                fillColor: "rgba(26,179,148,0.5)",
                strokeColor: "rgba(26,179,148,0.7)",
                pointColor: "rgba(26,179,148,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(26,179,148,1)",
                data: [28, 48, 40, 19, 86, 27, 90]
            }
        ]
    };

    /**
     * Options for Line chart
     */
    this.lineOptions = {
        scaleShowGridLines : true,
        scaleGridLineColor : "rgba(0,0,0,.05)",
        scaleGridLineWidth : 1,
        bezierCurve : true,
        bezierCurveTension : 0.4,
        pointDot : true,
        pointDotRadius : 4,
        pointDotStrokeWidth : 1,
        pointHitDetectionRadius : 20,
        datasetStroke : true,
        datasetStrokeWidth : 2,
        datasetFill : true
    };
   /* var ctx = document.getElementById("lineChart").getContext('2d');
    var myLineChart= new Chart(ctx).Line(data,option);*/

        this.polarData = [
        {
            value: 300,
            color:"#a3e1d4",
            highlight: "#1ab394",
            label: "App"
        },
        {
            value: 140,
            color: "#dedede",
            highlight: "#1ab394",
            label: "Software"
        },
        {
            value: 200,
            color: "#A4CEE8",
            highlight: "#1ab394",
            label: "Laptop"
        }
    ];

    /**
     * Options for Polar chart
     */
    this.polarOptions = {
        scaleShowLabelBackdrop : true,
        scaleBackdropColor : "rgba(255,255,255,0.75)",
        scaleBeginAtZero : true,
        scaleBackdropPaddingY : 1,
        scaleBackdropPaddingX : 1,
        scaleShowLine : true,
        segmentShowStroke : true,
        segmentStrokeColor : "#fff",
        segmentStrokeWidth : 2,
        animationSteps : 100,
        animationEasing : "easeOutBounce",
        animateRotate : true,
        animateScale : false
    };

   	}
]);<|endoftext|>


<commit_before>var interactiveBrowse_overview = d3.select("#interactiveBrowse_overview");

var ecology = interactiveBrowse_overview.append("rect")
        .attr("x", 680)
        .attr("y", 90)
        .attr("width", 600)
        .attr("height", 200)
        .attr("id", "ecology")
        .attr("text", "Search for traits related to ecology")
        .style("opacity", 0.01)
        .style("fill", "#fff")
        .style("cursor", "pointer")
//        .on("mouseover", function(){
//            add_Tooltip(d3.select(this).attr("text"));
//        })
        .on("mouseout", function(){
            remove_Tooltip();
        })
        .on("click", function(){
            displayPage(d3.select(this).attr("id"));
        });

function remove_Tooltip(){
    div.transition()
        .duration(10)
        .style("opacity", 0);
}

function displayPage(name){
    var resultPage =  WebRoot+"/trait/search/"+name;
    window.location.href = resultPage;
}
<commit_msg>Add template for click event to overview img<commit_after>var interactiveBrowse_overview = d3.select("#interactiveBrowse_overview");

var ecology = interactiveBrowse_overview.append("rect")
        .attr("x", 680)
        .attr("y", 90)
        .attr("width", 600)
        .attr("height", 200)
        .attr("id", "ecology")
        .attr("text", "Search for traits related to ecology")
        .style("opacity", 0.01)
        .style("fill", "#fff")
        .style("cursor", "pointer")
//        .on("mouseover", function(){
//            add_Tooltip(d3.select(this).attr("text"));
//        })
        .on("mouseout", function(){
            remove_Tooltip();
        })
        .on("click", function(){
            displayPage(d3.select(this).attr("id"));
        });

var humanEco = interactiveBrowse_overview.append("rect")
        .attr("x", 500)
        .attr("y", 430)
        .attr("width", 600)
        .attr("height", 280)
        .attr("id", "humanAndEcosystems")
        .attr("text", "Search for traits related to the relevance to humans and ecosystems")
        .style("opacity", 0.01)
        .style("fill", "#fff")
        .style("cursor", "pointer")
//        .on("mouseover", function(){
//            add_Tooltip(d3.select(this).attr("text"));
//        })
        .on("mouseout", function(){
            remove_Tooltip();
        })
        .on("click", function(){
            displayPage(d3.select(this).attr("id"));
        });

function remove_Tooltip(){
    div.transition()
        .duration(10)
        .style("opacity", 0);
}

function displayPage(name){
    var resultPage =  WebRoot+"/trait/search/"+name;
    window.location.href = resultPage;
}
<|endoftext|>


<commit_before>module.exports = {
    'expected LDAP codemirror fields are rendered when returning from another tab': client => {
        const authTab = '#auth_tab';
        const authView = 'div[ui-view="auth"]';
        const ldapForm = '#configuration_ldap_template_form';
        const systemTab = '#system_tab';
        const systemView = 'div[ui-view="system"]';

        const { navigation } = client.page.dashboard().section;
        const configuration = client.page.configuration();

        client.login();
        client.waitForAngular();

        navigation
            .waitForElementVisible('@settings')
            .click('@settings');

        configuration.waitForElementVisible(authView);

        configuration.waitForElementVisible(systemTab);
        configuration.click(systemTab);
        configuration.waitForElementNotVisible(authView);
        configuration.waitForElementVisible(systemView);

        configuration.waitForElementVisible(authTab);
        configuration.click(authTab);
        configuration.waitForElementNotVisible(systemView);
        configuration.waitForElementVisible(authView);

        configuration.selectSubcategory('LDAP');
        configuration.waitForElementVisible(ldapForm);

        const expectedCodemirrorFields = [
            'AUTH_LDAP_USER_SEARCH',
            'AUTH_LDAP_GROUP_SEARCH',
            'AUTH_LDAP_USER_ATTR_MAP',
            'AUTH_LDAP_GROUP_TYPE_PARAMS',
            'AUTH_LDAP_USER_FLAGS_BY_GROUP',
            'AUTH_LDAP_ORGANIZATION_MAP',
            'AUTH_LDAP_TEAM_MAP',
        ];

        const ldapCodeMirrors = `${ldapForm} div[class^="CodeMirror"] textarea`;

        client.elements('css selector', ldapCodeMirrors, ({ value }) => {
            client.assert.equal(value.length, expectedCodemirrorFields.length);
        });

        expectedCodemirrorFields.forEach(fieldName => {
            const codemirror = `#cm-${fieldName}-container div[class^="CodeMirror"]`;

            configuration.expect.element(codemirror).visible;
            configuration.expect.element(codemirror).enabled;
        });

        client.end();
    },
};
<commit_msg>Updating e2e tests to match new settings nav<commit_after>module.exports = {
    'expected LDAP codemirror fields are rendered when returning from another tab': client => {
        const authView = 'div[ui-view="auth"]';
        const ldapForm = '#configuration_ldap_template_form';
        const systemView = 'div[ui-view="system"]';

        const { navigation } = client.page.dashboard().section;
        const configuration = client.page.configuration();

        client.login();
        client.waitForAngular();

        navigation
            .waitForElementVisible('@settings')
            .moveToElement('@settings',0,0)
            .waitForElementVisible('@settingsSubPaneSystem')
            .click('@settingsSubPaneSystem');

        configuration.waitForElementVisible(systemView);

        navigation
            .waitForElementVisible('@settings')
            .moveToElement('@settings',0,0)
            .waitForElementVisible('@settingsSubPane')
            .waitForElementVisible('@settingsSubPaneAuth')
            .click('@settingsSubPaneAuth');

        configuration.waitForElementVisible(authView);

        // works as xpath const categoryName = `//*[@id="configuration_edit"]/div[1]/div/div/div[4]`;
        configuration.selectSubcategory('LDAP');
        configuration.waitForElementVisible(ldapForm);

        const expectedCodemirrorFields = [
            'AUTH_LDAP_USER_SEARCH',
            'AUTH_LDAP_GROUP_SEARCH',
            'AUTH_LDAP_USER_ATTR_MAP',
            'AUTH_LDAP_GROUP_TYPE_PARAMS',
            'AUTH_LDAP_USER_FLAGS_BY_GROUP',
            'AUTH_LDAP_ORGANIZATION_MAP',
            'AUTH_LDAP_TEAM_MAP',
        ];

        const ldapCodeMirrors = `${ldapForm}  div[class^="CodeMirror"] textarea`;

        client.elements('css selector', ldapCodeMirrors, ({ value }) => {
            client.assert.equal(value.length, expectedCodemirrorFields.length);
        });

        expectedCodemirrorFields.forEach(fieldName => {
            const codemirror = `#cm-${fieldName}-container div[class^="CodeMirror"]`;

            configuration.expect.element(codemirror).visible;
            configuration.expect.element(codemirror).enabled;
        });

        client.end();
    },
};
<|endoftext|>