<commit_before>class ApplicationController extends VisualController {

    constructor(model, editorController) {
        super(model);
        this.editorController = editorController;
        this.item = null;
        this.databasesItem = null;
        this.dataSourcesItem = null;
        this.pagesItem = null;
        this.pageItems = {};

        this.databases   = {};
        this.dataSources = {};
        this.pageLinks   = {};
    }
    init() {

        // databases
        if (this.model.data.databases) {
            for (const name in this.model.data.databases) {
                const database = this.model.databases[name];
                this.databases[name] = new DatabaseController(database, this);
            }
        }
    }

    createTree(item) {
        this.item = item;

        // databases
        this.databasesItem = this.item.addItem('Databases');
        if (this.model.data.databases) {
            for (const name in this.model.data.databases) {
                const databaseData = this.model.data.databases[name];
                this.addDatabaseItem(databaseData, name);
            }
        }
        // data sources
        this.dataSourcesItem = this.item.addItem('Data Sources');
        if (this.model.data.dataSources) {
            for (const name in this.model.data.dataSources) {
                const dataSourceData = this.model.data.dataSources[name];
                this.addDataSourceItem(dataSourceData, name);
            }
        }
        // pages
        this.pagesItem = this.item.addItem('Pages', 'opened');
        if (this.model.data.pageLinks) {
            for (const name in this.model.data.pageLinks) {
                const pageLinkData = this.model.data.pageLinks[name];
                this.pageItems[name] = this.addPageLinkItem(pageLinkData, name);
            }
        }
    }

    addDatabaseItem(databaseData, name) {
        const caption = DatabaseController.prototype.getCaption(databaseData);
        const databaseItem = this.databasesItem.addItem(caption);
        databaseItem.ctrl = this.databases[name];
        databaseItem.ctrl.createTree(databaseItem);
        return databaseItem;
    }

    addDataSourceItem(dataSourceData, name) {
        const caption = DataSourceController.prototype.getCaption(dataSourceData);
        const dataSource = this.model.dataSources[name];
        this.dataSources[name] = new DataSourceController(dataSource, null, this);

        // item
        const dataSourceItem = this.dataSourcesItem.addItem(caption);
        dataSourceItem.ctrl = this.dataSources[name];
        dataSourceItem.ctrl.createTree(dataSourceItem);
        return dataSourceItem;
    }

    addPageLinkItem(pageLinkData, name) {
        const caption = PageLinkController.prototype.getCaption(pageLinkData);
        const pageLinkItem = this.pagesItem.addItem(caption);
        pageLinkItem.node.className = 'node';
        const pageLink = this.model.pageLinks[name];
        this.pageLinks[name] = pageLinkItem.ctrl = new PageLinkController(pageLink, pageLinkItem);
        return pageLinkItem;
    }

    addPageItem(pageData, pageLinkData) {
        const caption = PageController.prototype.getCaption(pageData);
        const pageItem = this.pagesItem.addItem(caption);
        pageItem.node.className = 'node';
        const pageLink = new PageLink(pageLinkData, this.model);
        const page = new Page(pageData, this.model, pageLink);
        pageItem.ctrl = new PageController(page, pageItem, pageLink);
        pageItem.ctrl.createTree();
        return pageItem;
    }

    getActions() {
        return [
            {'action': 'newDatabase'  , 'caption': 'New Database'   },
            {'action': 'newDataSource', 'caption': 'New Data Source'},
            {'action': 'newPage'      , 'caption': 'New Page'       }
        ];
    }

    doAction(action) {
        switch (action) {
            case 'newDatabase':
                this.newDatabaseAction();
                break;
            case 'newDataSource':
                this.newDataSourceAction();
                break;
            case 'newPage':
                this.newPageAction();
                break;
            default:
                console.log(action);
        }
    }

    async newPageAction() {
        const self = this;
        const result = await Page.prototype.getView('new.html');
        $(document.body).append(result.view);
        $('#myModal').on('hidden.bs.modal', function(e){$(this).remove();});
        $("#myModal button[name='create']").click(function() {
            const name = $("#myModal input[id='name']").val();
            const caption = $("#myModal input[id='caption']").val();
            const startup = $("#myModal select[id='startup']").val();
            const params = {
                name:name,
                caption:caption,
                startup:startup
            };
            self.model.newPage(params).then(([pageData, pageLinkData]) => {
                self.pageItems[name] = self.addPageItem(pageData, pageLinkData);
                self.pageItems[name].select();
            });
            $('#myModal').modal('hide');
        });
        $('#myModal').modal('show');
        $("#myModal input[id='name']").focus();
    }

    async newDataSourceAction() {
        const self = this;
        const result = await DataSource.prototype.getView('new.html');
        $(document.body).append(result.view);
        $('#myModal').on('hidden.bs.modal', function(e){$(this).remove();});
        $("#myModal button[name='create']").click(function() {
            const dsName = $("#myModal input[id='dsName']").val();
            const dsClass = $("#myModal select[id='dsClass']").val();
            const params = {
                name :dsName,
                class:dsClass
            };
            self.model.newDataSource(params).then((dataSourceData) => {
                self.addDataSourceItem(dataSourceData).select();
            });
            $('#myModal').modal('hide');
        });
        $('#myModal').modal('show');
        $("#myModal input[id='dsName']").focus();
    }

    async newDatabaseAction() {
        const self = this;
        const result = await Database.prototype.getView('new.html');
        $(document.body).append(result.view);
        $('#myModal').on('hidden.bs.modal', function(e){$(this).remove();});
        $("#myModal button[name='create']").click(async () => {
            const _class = $("#myModal select[id='class']").val();
            const name     = $("#myModal input[id='name']").val();
            const host     = $("#myModal input[id='host']").val();
            const dbname   = $("#myModal input[id='dbname']").val();
            const user     = $("#myModal input[id='user']").val();
            const password = $("#myModal input[id='password']").val();
            const params = {
                _class: _class,
                name  : name,
                params: {
                    host    : {name: 'host'    , value: host    },
                    database: {name: 'database', value: dbname  },
                    user    : {name: 'user'    , value: user    },
                    password: {name: 'password', value: password}
                }
            };
            // console.log('params:', params);
            const databaseData = await self.model.newDatabase(params);
            self.addDatabaseItem(databaseData).select();
            $('#myModal').modal('hide');
        });
        $('#myModal').modal('show');
        $("#myModal input[id='name']").focus();
    }

    getPropList() {
        const propList = super.getPropList();
        propList.options['authentication'] = ['true', 'false'];
        propList.options['lang']           = ['en'  , 'ru'   ];
        return propList;
    }

    getItem() {
        return {
            ctrl  : this,
            title : this.model.getName(),
            opened: true,
            items : [
                {
                    title: 'Databases',
                    items: Object.keys(this.databases).map(name => this.databases[name].getItem())
                },
                {
                    title: 'Data Sources',
                    items: Object.keys(this.dataSources).map(name => this.dataSources[name].getItem())
                },
                {
                    title : 'Pages',
                    opened: true,
                    items : Object.keys(this.pageLinks).map(name => this.pageLinks[name].getItem())
                }
            ]
        };
    }

}
<commit_msg>create ds controllers in init<commit_after>class ApplicationController extends VisualController {

    constructor(model, editorController) {
        super(model);
        this.editorController = editorController;
        this.item = null;
        this.databasesItem = null;
        this.dataSourcesItem = null;
        this.pagesItem = null;
        this.pageItems = {};

        this.databases   = {};
        this.dataSources = {};
        this.pageLinks   = {};
    }
    init() {

        // databases
        if (this.model.data.databases) {
            for (const name in this.model.data.databases) {
                const database = this.model.databases[name];
                this.databases[name] = new DatabaseController(database, this);
            }
        }

        // dataSources
        if (this.model.data.dataSources) {
            for (const name in this.model.data.dataSources) {
                const dataSource = this.model.dataSources[name];
                this.dataSources[name] = new DataSourceController(dataSource, null, this);
            }
        }
    }

    createTree(item) {
        this.item = item;

        // databases
        this.databasesItem = this.item.addItem('Databases');
        if (this.model.data.databases) {
            for (const name in this.model.data.databases) {
                const databaseData = this.model.data.databases[name];
                this.addDatabaseItem(databaseData, name);
            }
        }
        // data sources
        this.dataSourcesItem = this.item.addItem('Data Sources');
        if (this.model.data.dataSources) {
            for (const name in this.model.data.dataSources) {
                const dataSourceData = this.model.data.dataSources[name];
                this.addDataSourceItem(dataSourceData, name);
            }
        }
        // pages
        this.pagesItem = this.item.addItem('Pages', 'opened');
        if (this.model.data.pageLinks) {
            for (const name in this.model.data.pageLinks) {
                const pageLinkData = this.model.data.pageLinks[name];
                this.pageItems[name] = this.addPageLinkItem(pageLinkData, name);
            }
        }
    }

    addDatabaseItem(databaseData, name) {
        const caption = DatabaseController.prototype.getCaption(databaseData);
        const databaseItem = this.databasesItem.addItem(caption);
        databaseItem.ctrl = this.databases[name];
        databaseItem.ctrl.createTree(databaseItem);
        return databaseItem;
    }

    addDataSourceItem(dataSourceData, name) {
        const caption = DataSourceController.prototype.getCaption(dataSourceData);
        const dataSourceItem = this.dataSourcesItem.addItem(caption);
        dataSourceItem.ctrl = this.dataSources[name];
        dataSourceItem.ctrl.createTree(dataSourceItem);
        return dataSourceItem;
    }

    addPageLinkItem(pageLinkData, name) {
        const caption = PageLinkController.prototype.getCaption(pageLinkData);
        const pageLinkItem = this.pagesItem.addItem(caption);
        pageLinkItem.node.className = 'node';
        const pageLink = this.model.pageLinks[name];
        this.pageLinks[name] = pageLinkItem.ctrl = new PageLinkController(pageLink, pageLinkItem);
        return pageLinkItem;
    }

    addPageItem(pageData, pageLinkData) {
        const caption = PageController.prototype.getCaption(pageData);
        const pageItem = this.pagesItem.addItem(caption);
        pageItem.node.className = 'node';
        const pageLink = new PageLink(pageLinkData, this.model);
        const page = new Page(pageData, this.model, pageLink);
        pageItem.ctrl = new PageController(page, pageItem, pageLink);
        pageItem.ctrl.createTree();
        return pageItem;
    }

    getActions() {
        return [
            {'action': 'newDatabase'  , 'caption': 'New Database'   },
            {'action': 'newDataSource', 'caption': 'New Data Source'},
            {'action': 'newPage'      , 'caption': 'New Page'       }
        ];
    }

    doAction(action) {
        switch (action) {
            case 'newDatabase':
                this.newDatabaseAction();
                break;
            case 'newDataSource':
                this.newDataSourceAction();
                break;
            case 'newPage':
                this.newPageAction();
                break;
            default:
                console.log(action);
        }
    }

    async newPageAction() {
        const self = this;
        const result = await Page.prototype.getView('new.html');
        $(document.body).append(result.view);
        $('#myModal').on('hidden.bs.modal', function(e){$(this).remove();});
        $("#myModal button[name='create']").click(function() {
            const name = $("#myModal input[id='name']").val();
            const caption = $("#myModal input[id='caption']").val();
            const startup = $("#myModal select[id='startup']").val();
            const params = {
                name:name,
                caption:caption,
                startup:startup
            };
            self.model.newPage(params).then(([pageData, pageLinkData]) => {
                self.pageItems[name] = self.addPageItem(pageData, pageLinkData);
                self.pageItems[name].select();
            });
            $('#myModal').modal('hide');
        });
        $('#myModal').modal('show');
        $("#myModal input[id='name']").focus();
    }

    async newDataSourceAction() {
        const self = this;
        const result = await DataSource.prototype.getView('new.html');
        $(document.body).append(result.view);
        $('#myModal').on('hidden.bs.modal', function(e){$(this).remove();});
        $("#myModal button[name='create']").click(function() {
            const dsName = $("#myModal input[id='dsName']").val();
            const dsClass = $("#myModal select[id='dsClass']").val();
            const params = {
                name :dsName,
                class:dsClass
            };
            self.model.newDataSource(params).then((dataSourceData) => {
                self.addDataSourceItem(dataSourceData).select();
            });
            $('#myModal').modal('hide');
        });
        $('#myModal').modal('show');
        $("#myModal input[id='dsName']").focus();
    }

    async newDatabaseAction() {
        const self = this;
        const result = await Database.prototype.getView('new.html');
        $(document.body).append(result.view);
        $('#myModal').on('hidden.bs.modal', function(e){$(this).remove();});
        $("#myModal button[name='create']").click(async () => {
            const _class = $("#myModal select[id='class']").val();
            const name     = $("#myModal input[id='name']").val();
            const host     = $("#myModal input[id='host']").val();
            const dbname   = $("#myModal input[id='dbname']").val();
            const user     = $("#myModal input[id='user']").val();
            const password = $("#myModal input[id='password']").val();
            const params = {
                _class: _class,
                name  : name,
                params: {
                    host    : {name: 'host'    , value: host    },
                    database: {name: 'database', value: dbname  },
                    user    : {name: 'user'    , value: user    },
                    password: {name: 'password', value: password}
                }
            };
            // console.log('params:', params);
            const databaseData = await self.model.newDatabase(params);
            self.addDatabaseItem(databaseData).select();
            $('#myModal').modal('hide');
        });
        $('#myModal').modal('show');
        $("#myModal input[id='name']").focus();
    }

    getPropList() {
        const propList = super.getPropList();
        propList.options['authentication'] = ['true', 'false'];
        propList.options['lang']           = ['en'  , 'ru'   ];
        return propList;
    }

    getItem() {
        return {
            ctrl  : this,
            title : this.model.getName(),
            opened: true,
            items : [
                {
                    title: 'Databases',
                    items: Object.keys(this.databases).map(name => this.databases[name].getItem())
                },
                {
                    title: 'Data Sources',
                    items: Object.keys(this.dataSources).map(name => this.dataSources[name].getItem())
                },
                {
                    title : 'Pages',
                    opened: true,
                    items : Object.keys(this.pageLinks).map(name => this.pageLinks[name].getItem())
                }
            ]
        };
    }

}
<|endoftext|>


<commit_before>/** Apanel for editing RestfulSimplified models. */
Ext.define('devilry.extjshelpers.RestfulSimplifiedEditPanel', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.restfulsimplified_editpanel',
    requires: ['devilry.extjshelpers.RestSubmit'],

    config: {
        /**
         * @cfg
         * The name of the ``Ext.data.Model`` to present in the body. (Required).
         */
        modelname: undefined,

        /**
         * @cfg
         * Items for the ``Ext.form.Panel`` used to edit the RestfulSimplified object. (Required).
         */
        editformitems: undefined,

        /**
         * @cfg
         * List of foreign key field names in the model. (Required).
         */
        foreignkeyfieldnames: undefined,

        /**
         * @cfg
         * A instance of the ``Ext.data.Model`` which should be loaded into the
         * form.
         */
        record: undefined
    },
    cls: 'editform',
    bodyCls: 'editform-body',

    constructor: function(config) {
        this.callParent([config]);
        this.initConfig(config);
    },

    initComponent: function() {
        this.errorlist = Ext.create('devilry.extjshelpers.ErrorList');
        this.model = Ext.ModelManager.getModel(this.model);

        if(this.editformitems) {
            this.editform = Ext.ComponentManager.create({
                xtype: 'form',
                model: this.modelname,
                items: this.editformitems,

                // Fields will be arranged vertically, stretched to full width
                layout: 'anchor',
                defaults: {
                    anchor: '100%',
                },
            });
        }

        this.editform.frame = false;
        if(this.editform.flex == undefined) {
            this.editform.flex = 15;
        }
        this.editform.border = 0;

        Ext.apply(this, {
            layout: {
                type: 'vbox',
                align: 'stretch'
            },

            layout: {
                type: 'hbox',
                align: 'stretch'
            },

            items: [this.editform, {
                xtype: 'panel',
                frame: false,
                border: false,
                bodyCls: 'editform-sidebar',
                flex: 5,
                items: [this.errorlist, {
                    xtype: 'box',
                    html: this.parseHelp()
                }]
            }],

            dockedItems: [{
                xtype: 'toolbar',
                dock: 'bottom',
                ui: 'footer',
                defaults: {minWidth: 75},

                items: ['->', {
                    xtype: 'button',
                    text: 'Save',
                    scale: 'large',
                    iconCls: 'icon-save-32',
                    listeners: {
                        scope: this,
                        click: this.onSave
                    }
                }]
            }]
        });
        this.callParent(arguments);

        if(this.record) {
            this.loadRecord();
        }
    },

    parseHelp: function() {
        if(!this.editform.help) {
            return '';
        }
        var help = '';
        var me = this;
        var state = this.record == undefined? 'new': 'existing';
        Ext.Array.each(this.editform.help, function(helpobj) {
            if(Ext.typeOf(helpobj) === 'string') {
                helpobj = {text: helpobj};
            }
            if(helpobj.state == undefined || (helpobj.state == state)) {
                help += Ext.String.format('
{0}
', helpobj.text);
            }
        });
        return help;
    },

    onSave: function() {
        this.errorlist.clearErrors();
        var me = this;

        this.editform.getForm().doAction('devilryrestsubmit', {
            submitEmptyText: true,
            waitMsg: 'Saving item...',
            model: this.model,
            success: function(form, action) {
                me.onSaveSuccess(form, action);
            },
            failure: function(form, action) {
                me.onSaveFailure(form, action);
            }
        });
    },

    onSaveSuccess: function(form, action) {
        var record = action.record;
        this.fireEvent('saveSucess', record);
    },

    onSaveFailure: function(record, action) {
        var errormessages = action.operation.responseData.items.errormessages;
        var me = this;
        Ext.each(errormessages, function(errormessage) {
            me.errorlist.addError(errormessage);
        });
    },

    loadRecord: function() {
        this.editform.loadRecord(this.record);
    }
});
<commit_msg>apps.extjshelpers: Remove editformitems from RestfulSimplifiedEditPanel.<commit_after>/** Apanel for editing RestfulSimplified models. */
Ext.define('devilry.extjshelpers.RestfulSimplifiedEditPanel', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.restfulsimplified_editpanel',
    requires: ['devilry.extjshelpers.RestSubmit'],

    config: {
        /**
         * @cfg
         * The name of the ``Ext.data.Model`` to present in the body. (Required).
         */
        modelname: undefined,

        /**
         * @cfg
         * List of foreign key field names in the model. (Required).
         */
        foreignkeyfieldnames: undefined,

        /**
         * @cfg
         * A instance of the ``Ext.data.Model`` which should be loaded into the
         * form.
         */
        record: undefined
    },
    cls: 'editform',
    bodyCls: 'editform-body',

    constructor: function(config) {
        this.callParent([config]);
        this.initConfig(config);
    },

    initComponent: function() {
        this.errorlist = Ext.create('devilry.extjshelpers.ErrorList');
        this.model = Ext.ModelManager.getModel(this.model);

        this.editform.frame = false;
        if(this.editform.flex == undefined) {
            this.editform.flex = 15;
        }
        this.editform.border = 0;

        Ext.apply(this, {
            layout: {
                type: 'vbox',
                align: 'stretch'
            },

            layout: {
                type: 'hbox',
                align: 'stretch'
            },

            items: [this.editform, {
                xtype: 'panel',
                frame: false,
                border: false,
                bodyCls: 'editform-sidebar',
                flex: 5,
                items: [this.errorlist, {
                    xtype: 'box',
                    html: this.parseHelp()
                }]
            }],

            dockedItems: [{
                xtype: 'toolbar',
                dock: 'bottom',
                ui: 'footer',
                defaults: {minWidth: 75},

                items: ['->', {
                    xtype: 'button',
                    text: 'Save',
                    scale: 'large',
                    iconCls: 'icon-save-32',
                    listeners: {
                        scope: this,
                        click: this.onSave
                    }
                }]
            }]
        });
        this.callParent(arguments);

        if(this.record) {
            this.loadRecord();
        }
    },

    parseHelp: function() {
        if(!this.editform.help) {
            return '';
        }
        var help = '';
        var me = this;
        var state = this.record == undefined? 'new': 'existing';
        Ext.Array.each(this.editform.help, function(helpobj) {
            if(Ext.typeOf(helpobj) === 'string') {
                helpobj = {text: helpobj};
            }
            if(helpobj.state == undefined || (helpobj.state == state)) {
                help += Ext.String.format('
{0}
', helpobj.text);
            }
        });
        return help;
    },

    onSave: function() {
        this.errorlist.clearErrors();
        var me = this;

        this.editform.getForm().doAction('devilryrestsubmit', {
            submitEmptyText: true,
            waitMsg: 'Saving item...',
            model: this.model,
            success: function(form, action) {
                me.onSaveSuccess(form, action);
            },
            failure: function(form, action) {
                me.onSaveFailure(form, action);
            }
        });
    },

    onSaveSuccess: function(form, action) {
        var record = action.record;
        this.fireEvent('saveSucess', record);
    },

    onSaveFailure: function(record, action) {
        var errormessages = action.operation.responseData.items.errormessages;
        var me = this;
        Ext.each(errormessages, function(errormessage) {
            me.errorlist.addError(errormessage);
        });
    },

    loadRecord: function() {
        this.editform.loadRecord(this.record);
    }
});
<|endoftext|>


<commit_before>/*global angular, define*/
define(['app/appaffinity/appaffinity.module'], function(appaff) {

    appaff.factory('ODLRest', function(Restangular, ENV) {
        return Restangular.withConfig(function(RestangularConfig) {
            RestangularConfig.setBaseUrl(ENV.getBaseURL("MD_SAL"));
        });
    });

    appaff.factory('AARest', function(Restangular) {
        return Restangular.withConfig(function(RestangularConfig) {
          var url = window.location.protocol+"//"+window.location.hostname+":"+"8089/";
          RestangularConfig.setBaseUrl(url);
        });
      });

    appaff.factory('appaffinitySvc', function(AARest, ODLRest) {
        var svc = {

            // TODO: determine them someway and cut this out!
            P : 3,
            W : 2,

            inventory: function() {
                return ODLRest.one('restconf/config/opendaylight-inventory:nodes');
            },
            affinity: function() {
                return AARest.one('affinity');
            },
            tMat: function() {
                return AARest.one('trafficmatrix/matrix');
            }
        };

        svc.getTraffic = function(cb) {
            return svc.tMat().get().then(function(mat) {
                nodes = {};
                var i,j;
                var n = mat.length;
                for (i = 0; i < n; i++) {
                    for (j = 0; j < n; j++) {
                        if (mat[i][j] !== 0){

                            var pSrc = Math.floor(i/svc.W),
                            wSrc = i % svc.W,
                            srcId = 'p' + pSrc + '-w' + wSrc;

                            var pDes = Math.floor(j/svc.W),
                            wDes = j % svc.W,
                            desId = 'p' + pDes + '-w' + wDes;

                            if (nodes[srcId] === undefined) {
                                nodes[srcId] = {id:srcId, incoming: [], outgoing: []};
                            }
                            if (nodes[desId] === undefined) {
                                nodes[desId] = {id:desId, incoming: [], outgoing: []};
                            }
                            nodes[desId].incoming.push([srcId, mat[i][j]]);
                            nodes[srcId].outgoing.push([desId, mat[i][j]]);
                            ;
                        }
                    }
                }
                for (var key in nodes){
                    var node = nodes[key];
                    var inLen = 0, outLen = 0;
                    if (node.incoming) {
                        inLen = Object.keys(node.incoming).length;
                    }
                    if (node.outgoing) {
                        outLen = Object.keys(node.outgoing).length;
                    }
                    node.rows = inLen + outLen;
                }
                cb(nodes);
            },
            function(response) {
                console.log("Error with status code ", response.status);
                cb(undefined); //sends null data to the controller since the call failed
            });
        };

        svc.parseFlow = function(flow) {
            var output = {};
            output.id = flow.id;

            var outAction = flow.instructions.instruction[0]['apply-actions'].action[0]['output-action'];
            output.outPort = outAction['output-node-connector'];
            if (outAction.timeslot) {
                output.timeslot = outAction.timeslot;
            }
            if (outAction.wavelength) {
                output.wavelength = outAction.wavelength;
            }

            output.inPort = flow.match['in-port'];

            return output;
        }

        svc.parseNode = function(node) {
            node.rows = 0;
            var flowList;
            for (var i = 0; i< node['flow-node-inventory:table'].length; i++) {
                 if (node['flow-node-inventory:table'][i].id == 0) {
                     flowList = node['flow-node-inventory:table'][i].flow;
                 }
            }
            var outflows = [];
            for (var flow in flowList) {
                outflows.push(svc.parseFlow(flow));
                node.rows = node.rows + 1;
            }
            return outflows;
        };

        svc.getFlows= function(cb) {
            return svc.inventory().get().then(function(inventory) {
                lst = inventory['nodes']['node'];
                var nodes = [];
                for (var data in lst) {
                    var node = {};
                    node.id = data.id;
                    node.flows = svc.parseNode(node);
                    nodes.push(node);
                }
                cb(nodes);
            }, function(response) {
                console.log("error with status code " + response.status);
            }
        };

        svc.submitService = function(service) {
            return svc.affinity().one('connection').post(service)
        }
        return svc;
    });
});
<commit_msg>DLUX bugfix<commit_after>/*global angular, define*/
define(['app/appaffinity/appaffinity.module'], function(appaff) {

    appaff.factory('ODLRest', function(Restangular, ENV) {
        return Restangular.withConfig(function(RestangularConfig) {
            RestangularConfig.setBaseUrl(ENV.getBaseURL("MD_SAL"));
        });
    });

    appaff.factory('AARest', function(Restangular) {
        return Restangular.withConfig(function(RestangularConfig) {
          var url = window.location.protocol+"//"+window.location.hostname+":"+"8089/";
          RestangularConfig.setBaseUrl(url);
        });
      });

    appaff.factory('appaffinitySvc', function(AARest, ODLRest) {
        var svc = {

            // TODO: determine them someway and cut this out!
            P : 3,
            W : 2,

            inventory: function() {
                return ODLRest.one('restconf/config/opendaylight-inventory:nodes');
            },
            affinity: function() {
                return AARest.one('affinity');
            },
            tMat: function() {
                return AARest.one('trafficmatrix/matrix');
            }
        };

        svc.getTraffic = function(cb) {
            return svc.tMat().get().then(function(mat) {
                nodes = {};
                var i,j;
                var n = mat.length;
                for (i = 0; i < n; i++) {
                    for (j = 0; j < n; j++) {
                        if (mat[i][j] !== 0){

                            var pSrc = Math.floor(i/svc.W),
                            wSrc = i % svc.W,
                            srcId = 'p' + pSrc + '-w' + wSrc;

                            var pDes = Math.floor(j/svc.W),
                            wDes = j % svc.W,
                            desId = 'p' + pDes + '-w' + wDes;

                            if (nodes[srcId] === undefined) {
                                nodes[srcId] = {id:srcId, incoming: [], outgoing: []};
                            }
                            if (nodes[desId] === undefined) {
                                nodes[desId] = {id:desId, incoming: [], outgoing: []};
                            }
                            nodes[desId].incoming.push([srcId, mat[i][j]]);
                            nodes[srcId].outgoing.push([desId, mat[i][j]]);
                            ;
                        }
                    }
                }
                for (var key in nodes){
                    var node = nodes[key];
                    var inLen = 0, outLen = 0;
                    if (node.incoming) {
                        inLen = Object.keys(node.incoming).length;
                    }
                    if (node.outgoing) {
                        outLen = Object.keys(node.outgoing).length;
                    }
                    node.rows = inLen + outLen;
                }
                cb(nodes);
            },
            function(response) {
                console.log("Error with status code ", response.status);
                cb(undefined); //sends null data to the controller since the call failed
            });
        };

        svc.parseFlow = function(flow) {
            var output = {};
            output.id = flow.id;

            var outAction = flow.instructions.instruction[0]['apply-actions'].action[0]['output-action'];
            output.outPort = outAction['output-node-connector'];
            if (outAction.timeslot) {
                output.timeslot = outAction.timeslot;
            }
            if (outAction.wavelength) {
                output.wavelength = outAction.wavelength;
            }

            output.inPort = flow.match['in-port'];

            return output;
        };

        svc.parseNode = function(node) {
            node.rows = 0;
            var flowList;
            for (var i = 0; i< node['flow-node-inventory:table'].length; i++) {
                 if (node['flow-node-inventory:table'][i].id == 0) {
                     flowList = node['flow-node-inventory:table'][i].flow;
                 }
            }
            var outflows = [];
            for (var flow in flowList) {
                outflows.push(svc.parseFlow(flow));
                node.rows = node.rows + 1;
            }
            return outflows;
        };

        svc.getFlows= function(cb) {
            return svc.inventory().get().then(function(inventory) {
                lst = inventory['nodes']['node'];
                var nodes = [];
                for (var data in lst) {
                    var node = {};
                    node.id = data.id;
                    node.flows = svc.parseNode(node);
                    nodes.push(node);
                }
                cb(nodes);
            }, function(response) {
                console.log("error with status code " + response.status);
            });
        };

        svc.submitService = function(service) {
            return svc.affinity().one('connection').post(service)
        }
        return svc;
    });
});
<|endoftext|>


<commit_before>/**
* ownCloud
*
* @author Vincent Petry
* @copyright 2015 Vincent Petry <pvince81@owncloud.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*
*/

describe('OCA.Files.MainFileInfoDetailView tests', function() {
	var view, tipsyStub;

	beforeEach(function() {
		tipsyStub = sinon.stub($.fn, 'tipsy');
		view = new OCA.Files.MainFileInfoDetailView();
	});
	afterEach(function() {
		view.destroy();
		view = undefined;
		tipsyStub.restore();
	});
	describe('rendering', function() {
		var testFileInfo;
		beforeEach(function() {
			view = new OCA.Files.MainFileInfoDetailView();
			testFileInfo = {
				id: 5,
				name: 'One.txt',
				path: '/subdir',
				size: 123456789,
				dateLabel: new Date(Date.UTC(2015, 6, 17, 1, 2, 3, 4))
			};
		});
		it('displays basic info', function() {
			var clock = sinon.useFakeTimers(Date.UTC(2015, 6, 17, 1, 2, 0, 0));
			view.setFileInfo(testFileInfo);
			expect(view.$el.find('.fileName').text()).toEqual('One.txt');
			expect(view.$el.find('.fileName').attr('title')).toEqual('One.txt');
			expect(view.$el.find('.size').text()).toEqual('117.7 MB');
			expect(view.$el.find('.size').attr('title')).toEqual('123456789 bytes');
			expect(view.$el.find('.date').text()).toEqual('a few seconds ago');
			expect(view.$el.find('.date').attr('title')).toEqual('July 17, 2015 3:02 AM');
			clock.restore();
		});
		it('displays favorite icon', function() {
			view.setFileInfo(_.extend(testFileInfo, {
				tags: [OC.FAVORITE]
			}));
			expect(OC.TestUtil.getImageUrl(view.$el.find('.favorite img')))
				.toEqual(OC.imagePath('core', 'actions/starred'));

			view.setFileInfo(_.extend(testFileInfo, {
				tags: []
			}));
			expect(OC.TestUtil.getImageUrl(view.$el.find('.favorite img')))
				.toEqual(OC.imagePath('core', 'actions/star'));
		});
		it('displays mime icon', function() {
			// TODO
		});
		it('displays thumbnail', function() {
			// TODO
		});
	});
});
<commit_msg>More work on right sidebar unit tests<commit_after>/**
* ownCloud
*
* @author Vincent Petry
* @copyright 2015 Vincent Petry <pvince81@owncloud.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*
*/

describe('OCA.Files.MainFileInfoDetailView tests', function() {
	var view, tipsyStub;

	beforeEach(function() {
		tipsyStub = sinon.stub($.fn, 'tipsy');
		view = new OCA.Files.MainFileInfoDetailView();
	});
	afterEach(function() {
		view.destroy();
		view = undefined;
		tipsyStub.restore();
	});
	describe('rendering', function() {
		var testFileInfo;
		beforeEach(function() {
			view = new OCA.Files.MainFileInfoDetailView();
			testFileInfo = {
				id: 5,
				name: 'One.txt',
				path: '/subdir',
				size: 123456789,
				dateLabel: new Date(Date.UTC(2015, 6, 17, 1, 2, 3, 4))
			};
		});
		it('displays basic info', function() {
			var clock = sinon.useFakeTimers(Date.UTC(2015, 6, 17, 1, 2, 0, 0));
			view.setFileInfo(testFileInfo);
			expect(view.$el.find('.fileName').text()).toEqual('One.txt');
			expect(view.$el.find('.fileName').attr('title')).toEqual('One.txt');
			expect(view.$el.find('.size').text()).toEqual('117.7 MB');
			expect(view.$el.find('.size').attr('title')).toEqual('123456789 bytes');
			expect(view.$el.find('.date').text()).toEqual('a few seconds ago');
			expect(view.$el.find('.date').attr('title')).toEqual('July 17, 2015 3:02 AM');
			clock.restore();
		});
		it('displays favorite icon', function() {
			view.setFileInfo(_.extend(testFileInfo, {
				tags: [OC.TAG_FAVORITE]
			}));
			expect(view.$el.find('.favorite img').attr('src'))
				.toEqual(OC.imagePath('core', 'actions/starred'));

			view.setFileInfo(_.extend(testFileInfo, {
				tags: []
			}));
			expect(view.$el.find('.favorite img').attr('src'))
				.toEqual(OC.imagePath('core', 'actions/star'));
		});
		it('displays mime icon', function() {
			// TODO
		});
		it('displays thumbnail', function() {
			// TODO
		});
	});
});
<|endoftext|>


<commit_before>// Command line args for mongo queries

var MongoClient = require('mongodb').MongoClient,
    commandLineArgs = require('command-line-args'),
    commandLineUsage = require('command-line-usage');

// Generate cli help usage template
function generateCliUsageTemplate() {
    var templ = [{
        header: 'Mongo query using Command line arguments',
        content: 'Define a query using the CLI for fetching data from mongodb'
    }, {
        header: 'Options',
        optionList: [{
            name: 'firstYear',
            typeLabel: '[underline]{Number} [underline]{required} (alias: -f)',
        }, {
            name: 'lastYear',
            typeLabel: '[underline]{Number} [underline]{required} (alias: -l)',
        }, {
            name: 'employees',
            typeLabel: '[underline]{Number} (alias: -e)',
        }]
    }];

    return templ;
};

// Request data from database
function getData(query) {
    return MongoClient.connect('mongodb://localhost:27017/crunchbase')
        .then(function(db) {
            return db.collection('companies').find(query, {
                '_id': 0,
                'name': 1,
                'founded_year': 1
            });
        })
        .then(function(cursor) {
            var i = 0;
            cursor.forEach(function(doc) {
                console.log(doc);
                i++;
            }, function(err) {
                console.log('Docs found - '+i);
            })
        })
        .catch(function(err) {
            console.log('Some error occurred!');
        });
};

// Generate mongo query using provided command line arguments
function generateMongoQuery(firstYear, lastYear, employees) {
    var query = {
        'founded_year': {
            '$gte': firstYear,
            '$lte': lastYear
        }
    }
    if (employees) {
       query.number_of_employees = { '$lt': employees };
    }

    getData(query);
};

// Initialise cli app
function initCliScript() {
    var cli = commandLineArgs([
        { name: "firstYear", alias: "f", type: Number },
        { name: "lastYear", alias: "l", type: Number },
        { name: "employees", alias: "e", type: Number }
    ]);

    if (('firstYear' in cli) && ('lastYear' in cli)) {
        var firstYear = parseInt(cli.firstYear, 10),
            lastYear = parseInt(cli.lastYear, 10),
            employees = parseInt(cli.employees, 10),
            query;

        generateMongoQuery(firstYear, lastYear, employees);

    } else {
        var cliHelp = commandLineUsage(generateCliUsageTemplate());
        console.log(cliHelp);
    }
};

initCliScript();
<commit_msg>Support for sort, skip and limit added in command-line-args script<commit_after>// Command line args for mongo queries

var MongoClient = require('mongodb').MongoClient,
    commandLineArgs = require('command-line-args'),
    commandLineUsage = require('command-line-usage');

// Generate cli help usage template
function generateCliUsageTemplate() {
    var templ = [{
        header: 'Mongo query using Command line arguments',
        content: 'Define a query using the CLI for fetching data from mongodb'
    }, {
        header: 'Options',
        optionList: [{
            name: 'firstYear',
            typeLabel: '[underline]{Number} [underline]{required} (alias: -f)',
        }, {
            name: 'lastYear',
            typeLabel: '[underline]{Number} [underline]{required} (alias: -l)',
        }, {
            name: 'employees',
            typeLabel: '[underline]{Number} (alias: -e)',
        }, {
            name: 'skip',
            typeLabel: '[underline]{Number} (alias: -s)',
        }, {
            name: 'limit',
            typeLabel: '[underline]{Number} (alias: -l)',
        }]
    }];

    return templ;
};

// Request data from database
function getData(query, skip, limit) {
    return MongoClient.connect('mongodb://localhost:27017/crunchbase')
        .then(function(db) {
            return db.collection('companies').find(query, {
                '_id': 0,
                'name': 1,
                'founded_year': 1
            }).sort({'founded_year': 1}).skip(skip).limit(limit);
        })
        .then(function(cursor) {
            var i = 0;
            cursor.forEach(function(doc) {
                console.log(doc);
                i++;
            }, function(err) {
                console.log('Docs found - '+i);
            })
        })
        .catch(function(err) {
            console.log('Some error occurred!');
        });
};

// Generate mongo query using provided command line arguments
function generateMongoQuery(firstYear, lastYear, employees, skip, limit) {
    var query = {
        'founded_year': {
            '$gte': firstYear,
            '$lte': lastYear
        }
    }
    if (employees) {
       query.number_of_employees = { '$lt': employees };
    }

    getData(query, skip, limit);
};

// Initialise cli app
function initCliScript() {
    var cli = commandLineArgs([
        { name: "firstYear", alias: "f", type: Number },
        { name: "lastYear", alias: "l", type: Number },
        { name: "employees", alias: "e", type: Number },
        { name: "skip", alias: "s", type: Number },
        { name: "limit", alias: "i", type: Number }
    ]);

    if (('firstYear' in cli) && ('lastYear' in cli)) {
        var firstYear = parseInt(cli.firstYear, 10),
            lastYear = parseInt(cli.lastYear, 10),
            employees = parseInt(cli.employees, 10),
            skip = parseInt(cli.skip, 10),
            limit = parseInt(cli.limit, 10),
            query;

        generateMongoQuery(firstYear, lastYear, employees, skip, limit);

    } else {
        var cliHelp = commandLineUsage(generateCliUsageTemplate());
        console.log(cliHelp);
    }
};

initCliScript();
<|endoftext|>


<commit_before>var Binary = require('./example');

describe('binary', function() {

  it('1 is decimal 1', function() {
    expect(1).toEqual(new Binary('1').toDecimal());
  });

  it('10 is decimal 2', function() {
    expect(2).toEqual(new Binary('10').toDecimal());
  });

  it('11 is decimal 3', function() {
    expect(3).toEqual(new Binary('11').toDecimal());
  });

  it('100 is decimal 4', function() {
    expect(4).toEqual(new Binary('100').toDecimal());
  });

  it('1001 is decimal 9', function() {
    expect(9).toEqual(new Binary('1001').toDecimal());
  });

  it('11010 is decimal 26', function() {
    expect(26).toEqual(new Binary('11010').toDecimal());
  });

  it('10001101000 is decimal 1128', function() {
    expect(1128).toEqual(new Binary('10001101000').toDecimal());
  });

  it('carrot is decimal 0', function() {
    expect(0).toEqual(new Binary('carrot').toDecimal());
  });

});
<commit_msg>2nd and subsequent tests skipped<commit_after>var Binary = require('./example');

describe('binary', function() {

  it('1 is decimal 1', function() {
    expect(1).toEqual(new Binary('1').toDecimal());
  });

  xit('10 is decimal 2', function() {
    expect(2).toEqual(new Binary('10').toDecimal());
  });

  xit('11 is decimal 3', function() {
    expect(3).toEqual(new Binary('11').toDecimal());
  });

  xit('100 is decimal 4', function() {
    expect(4).toEqual(new Binary('100').toDecimal());
  });

  xit('1001 is decimal 9', function() {
    expect(9).toEqual(new Binary('1001').toDecimal());
  });

  xit('11010 is decimal 26', function() {
    expect(26).toEqual(new Binary('11010').toDecimal());
  });

  xit('10001101000 is decimal 1128', function() {
    expect(1128).toEqual(new Binary('10001101000').toDecimal());
  });

  xit('carrot is decimal 0', function() {
    expect(0).toEqual(new Binary('carrot').toDecimal());
  });

});
<|endoftext|>


<commit_before>function prepareTimeSelector() {

	// util functions
	var getGeneric = function (seq, type) {
		return $('.time-selector-' + type).filterByData('sequence', seq);
	};
	var getHourSelect = function (seq) {
		return getGeneric(seq, 'hour');
	};
	var getMinSelect = function (seq) {
		return getGeneric(seq, 'min');
	};
	var getOutput = function (seq) {
		return getGeneric(seq, 'output');
	};
	var getSequence = function (e) {
		return $(e).attr('data-sequence');
	};

	// update output
	var updateOutput = function (seq) {
		// get values
		var hour = getHourSelect(seq).val();
		var min = getMinSelect(seq).val();

		// update output
		var out = getOutput(seq);
		if (hour == 'x' || min == 'x') {
			if (out.attr('data-default') != null) {
				out.val(out.attr('data-default'));
			} else {
				out.val('');
			}
		} else {
			out.val((hour < 10 ? '0' : '') + hour + ':' + (min < 10 ? '0' : '') + min);
		}
	};

	// create fields
	var timeSelectors = $('div.time-selector');
	var ts, sequence;
	for (var t = 0; t < timeSelectors.length; ++t) {
		ts = timeSelectors.eq(t);
		sequence = ts.data('sequence');
		ts.html('
<select class="form-control time-selector-hour" data-sequence="' + sequence + '" style="display: inline; width: auto;"></select>  :  <select class="form-control time-selector-min" data-sequence="' + sequence + '" style="display: inline; width: auto;"></select>
');
	}

	// get fields and clear
	var hourFields = $('.time-selector-hour');
	var minFields = $('.time-selector-min');
	hourFields.empty().unbind('change').append('<option value="x" selected>HH</option>');
	minFields.empty().unbind('change').append('<option value="x" selected>MM</option>');

	// add hours
	for (var i = 0; i < 24; ++i) {
		hourFields.append('<option value="' + i + '">' + (i < 10 ? '0' : '') + i + '</option>');
	}

	// add hours
	for (i = 0; i < 60; ++i) {
		minFields.append('<option value="' + i + '">' + (i < 10 ? '0' : '') + i + '</option>');
	}

	// hour change listener
	hourFields.change(function () {
		updateOutput(getSequence(this));
	});

	// min change listener
	minFields.change(function () {
		updateOutput(getSequence(this));
	});

	// attempt pre-fill
	$('.time-selector-output').each(function (i, e) {
		// match?
		if ($(e).val().match(/[0-9]{2}:[0-9]{2}/)) {
			// split
			var parts = $(e).val().split(':', 2);

			// get sequence
			var seq = getSequence(e);

			// set values
			getHourSelect(seq).val(parseInt(parts[0])).trigger('change');
			getMinSelect(seq).val(parseInt(parts[1])).trigger('change');
		}
	});
}<commit_msg>Default pre-filling on time selector<commit_after>function prepareTimeSelector() {

	// util functions
	var getGeneric = function (seq, type) {
		return $('.time-selector-' + type).filterByData('sequence', seq);
	};
	var getHourSelect = function (seq) {
		return getGeneric(seq, 'hour');
	};
	var getMinSelect = function (seq) {
		return getGeneric(seq, 'min');
	};
	var getOutput = function (seq) {
		return getGeneric(seq, 'output');
	};
	var getSequence = function (e) {
		return $(e).attr('data-sequence');
	};

	// update output
	var updateOutput = function (seq) {
		// get values
		var hour = getHourSelect(seq).val();
		var min = getMinSelect(seq).val();

		// update output
		var out = getOutput(seq);
		if (hour == 'x' || min == 'x') {
			if (out.attr('data-default') != null) {
				out.val(out.attr('data-default'));
			} else {
				out.val('');
			}
		} else {
			out.val((hour < 10 ? '0' : '') + hour + ':' + (min < 10 ? '0' : '') + min);
		}
	};

	// create fields
	var timeSelectors = $('div.time-selector');
	var ts, sequence;
	for (var t = 0; t < timeSelectors.length; ++t) {
		ts = timeSelectors.eq(t);
		sequence = ts.data('sequence');
		ts.html('
<select class="form-control time-selector-hour" data-sequence="' + sequence + '" style="display: inline; width: auto;"></select>  :  <select class="form-control time-selector-min" data-sequence="' + sequence + '" style="display: inline; width: auto;"></select>
');
	}

	// get fields and clear
	var hourFields = $('.time-selector-hour');
	var minFields = $('.time-selector-min');
	hourFields.empty().unbind('change').append('<option value="x" selected>HH</option>');
	minFields.empty().unbind('change').append('<option value="x" selected>MM</option>');

	// add hours
	for (var i = 0; i < 24; ++i) {
		hourFields.append('<option value="' + i + '">' + (i < 10 ? '0' : '') + i + '</option>');
	}

	// add hours
	for (i = 0; i < 60; ++i) {
		minFields.append('<option value="' + i + '">' + (i < 10 ? '0' : '') + i + '</option>');
	}

	// hour change listener
	hourFields.change(function () {
		updateOutput(getSequence(this));
	});

	// min change listener
	minFields.change(function () {
		updateOutput(getSequence(this));
	});

	// attempt pre-fill
	$('.time-selector-output').each(function (i, e) {
		// match?
		if ($(e).val().match(/[0-9]{2}:[0-9]{2}/)) {
			// split
			var parts = $(e).val().split(':', 2);

			// get sequence
			var seq = getSequence(e);

			// set values
			getHourSelect(seq).val(parseInt(parts[0])).trigger('change');
			getMinSelect(seq).val(parseInt(parts[1])).trigger('change');
		} else {
			if ($(e).attr('data-default') != null) {
				$(e).val($(e).attr('data-default'));
			}
		}
	});
}<|endoftext|>


<commit_before>Ext.define('devilry_subjectadmin.view.guides.CreateNewAssignment', {
    extend: 'Ext.container.Container',
    alias: 'widget.guide-createnewassignment',

    /**
     * @cfg {devilry_subjectadmin.controller.GuideSystem} [guideSystem]
     */

    layout: 'card',
    defaults: {
        xtype: 'box'
    },
    items: [{
        itemId: 'loading',
        html: ['
', gettext('Loading') + ' ...', '
'].join('')
    }, {
        itemId: 'dashboard',
        tpl: [
            '
',
                gettext('Select an active {subject_term} from the list at the top of the left side of this page.'),
            '
',
            '
',
                gettext('For {subjects_term} where you only have admin rights for selected assignments, those assignments will be listed. If you only have assignments in your list, you do not have the required rights to create new assignments.'),
            '
'
        ],
        data: {
            subject_term: gettext('subject'),
            subjects_term: gettext('subjects')
        }
    }, {
        itemId: 'period',
        tpl: [
            '
',
                gettext('Click Create new assignment.'),
            '
'
        ],
        data: {
        }
    }, {
        itemId: 'createnewassignment1',
        tpl: [
            '
',
                gettext('Fill out the visible fields in the form.'),
            '
',

            '
', gettext('Exam?'), '
',
            '
',
                gettext('Click Advanced, and choose Anonymous.'),
            '
',

            '
', gettext('Paper deliveries?'), '
',
            '
',
                gettext('If your students hand in deliveries on paper, choose Not using Devilry.'),
            '
'
        ],
        data: {
        }
    }, {
        itemId: 'createnewassignment2',
        tpl: [
            '
',
                gettext('Keep the defaults, or make sure you understand the consequence of unchecking the checkboxes.'),
            '
',
            '
',
                gettext('This guide closes when you click Create assignment.'),
            '
'
        ],
        data: {
        }
    }]
});
<commit_msg>devilry_subjectadmin.guides.CreateNewAssignment: Improved text.<commit_after>Ext.define('devilry_subjectadmin.view.guides.CreateNewAssignment', {
    extend: 'Ext.container.Container',
    alias: 'widget.guide-createnewassignment',

    /**
     * @cfg {devilry_subjectadmin.controller.GuideSystem} [guideSystem]
     */

    layout: 'card',
    defaults: {
        xtype: 'box'
    },
    items: [{
        itemId: 'loading',
        html: ['
', gettext('Loading') + ' ...', '
'].join('')
    }, {
        itemId: 'dashboard',
        tpl: [
            '
',
                gettext('Select an active {subject_term} from the list at the top of the left side of this page.'),
            '
',
            '
',
                gettext('For {subjects_term} where you only have admin rights for selected assignments, those assignments will be listed. If you only have assignments in your list, you do not have the required rights to create new assignments.'),
            '
'
        ],
        data: {
            subject_term: gettext('subject'),
            subjects_term: gettext('subjects')
        }
    }, {
        itemId: 'period',
        tpl: [
            '
',
                gettext('Click Create new assignment.'),
            '
'
        ],
        data: {
        }
    }, {
        itemId: 'createnewassignment1',
        tpl: [
            '
',
                gettext('Fill out the visible fields in the form.'),
            '
',

            '
', gettext('Exam?'), '
',
            '
',
                gettext('Click Advanced, and choose Anonymous.'),
            '
',

            '
', gettext('Paper deliveries?'), '
',
            '
',
                gettext('If your students hand in deliveries on paper, choose Not using Devilry.'),
            '
'
        ],
        data: {
        }
    }, {
        itemId: 'createnewassignment2',
        tpl: [
            '
',
                gettext('Keeping the defaults is usually the best choice if you are uncertain.'),
            '
',

            '
', gettext('Need to edit students or examiners?'), '
',
            '
',
                gettext('The links to view or edit students and examiners open a new browser window, so will not loose your progress when you click them.'),
            '
',

            '
', gettext('Create another?'), '
',
            '
',
                gettext('This guide closes when you click Create assignment. At the top of the next page, you will get a link to quickly create another assignment with the same settings that you used for this assignment.'),
            '
'
        ],
        data: {
            subject_term: gettext('subject')
        }
    }]
});
<|endoftext|>


<commit_before>
//{namespace name=backend/plugin_manager/translation}
Ext.define('Shopware.apps.PluginManager.view.list.LocalPluginListingPage', {
    extend: 'Shopware.grid.Panel',
    alias: 'widget.plugin-manager-local-plugin-listing',
    cls: 'plugin-manager-local-plugin-listing',

    mixins: {
        events: 'Shopware.apps.PluginManager.view.PluginHelper'
    },
    viewConfig: {
        markDirty: false
    },

    configure: function() {
        return {
            addButton: false,
            pageSizeCombo: false,
            deleteButton: false,
            deleteColumn: false,
            editColumn: false,
            columns: {
                label: {
                    flex: 2,
                    header: '{s name="plugin_name"}{/s}',
                    renderer: this.nameRenderer,
                    editor: null
                },
                version: {
                    width: 30,
                    header: '{s name="version"}{/s}',
                    editor: null
                },
                installationDate: {
                    header: '{s name="installed_on"}{/s}',
                    renderer: this.dateRenderer,
                    editor: null
                },
                updateDate: {
                    header: '{s name="updated_on"}{/s}',
                    renderer: this.dateRenderer,
                    editor: null
                },
                licenceCheck: {
                    flex: 2,
                    sortable: false,
                    cls: 'licence-column',
                    header: '{s name="licence"}{/s}',
                    renderer: this.licenceRenderer,
                    editor: null
                },
                active: this.createActiveColumn,
                author: {
                    header: '{s name="from_producer"}{/s}',
                    renderer: this.authorRenderer,
                    editor: null
                }
            }
        };
    },

    initComponent: function() {
        var me = this;

        me.callParent(arguments);

        Shopware.app.Application.on('plugin-reloaded', function(plugin) {
            me.store.each(function(record, index) {
                if (record && record.get('technicalName') == plugin.get('technicalName')) {
                    me.store.remove(record);
                }
            });

            if (plugin.get('id') > 0) {
                plugin.set('groupingState', null);
                plugin.dirty = false;
                try {
                    me.store.add(plugin);
                } catch (e) {
                    me.store.load();
                }
            }

            me.store.sort();
            me.store.group();
            me.reconfigure(me.store);
            me.hideLoadingMask();
        });
    },

    createActionColumn: function () {
        var me = this;

        var actionColumn = me.callParent(arguments);

        actionColumn.width = 120;
        return actionColumn;
    },

    createSelectionModel: function() { },

    createActiveColumn: function() {
        var me = this,
            items = [];

        items.push({
            tooltip: '{s name="activate_deactivate"}{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                if (record.allowActivate()) {
                    me.activatePluginEvent(record);

                } else if (record.allowDeactivate()) {
                    me.deactivatePluginEvent(record);
                }
            },
            getClass: function(value, metaData, record) {
                if (!record.allowActivate() && !record.allowDeactivate()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }

                if (record.allowActivate()) {
                    return 'sprite-ui-check-box-uncheck';
                } else {
                    return 'sprite-ui-check-box';
                }
            }
        });

        return {
            xtype: 'actioncolumn',
            width: 60,
            align: 'center',
            header: '{s name="active"}{/s}',
            items: items
        };
    },

    searchEvent: function(field, value) {
        var me = this;

        me.store.clearFilter();

        me.store.filterBy(function(record, id) {
            var description = record.get('description') + '';
            var name = record.get('label') + '';
            var producer = '';

            if (record['getProducerStore']) {
                producer = record['getProducerStore'].first().get('name') + '';
            }

            return (
                name.indexOf(value) > -1
                || description.indexOf(value) > -1
                || producer.indexOf(value) > -1
            );
        });
    },

    createFeatures: function() {
        var me = this,
            items = me.callParent(arguments);

        me.groupingFeature = Ext.create('Ext.grid.feature.Grouping', {
            groupHeaderTpl: new Ext.XTemplate(
                '{literal}{name:this.formatName} ({rows.length} Plugins){/literal}',
                {
                    formatName: function(name) {
                        switch(name) {
                            case 2:
                                return '{s name="group_headline_installed"}{/s}';
                            case 1:
                                return '{s name="group_headline_deactivated"}{/s}';
                            case 0:
                                return '{s name="group_headline_uninstalled"}{/s}';
                        }
                    }
                }
            )
        });

        items.push(me.groupingFeature);
        return items;
    },

    nameRenderer: function(value, metaData, record) {
        var name = record.get('label');

        if (!record.get('localIcon') || record.get('localIcon') == 'false') {
            return name;
        }

        return '

' + name;
    },

    authorRenderer: function(value, metaData, record) {
        if (!record || !record['getProducerStore']) {
            return value;
        }

        var producer = record['getProducerStore'].first();
        var website = producer.get('website');

        if (producer.get('name') == 'shopware AG' && !website) {
            website = 'http://www.shopware.com';
        }

        if (website && website.length > 0) {
            return ''+producer.get('name')+''
        } else {
            return producer.get('name');
        }
    },

    dateRenderer: function(value) {
        if (!value || !value.hasOwnProperty('date')) {
            return value;
        }
        var date = this.formatDate(value.date);
        return Ext.util.Format.date(date);
    },

    licenceRenderer: function(value, metaData, record) {
        if (!record || !record['getLicenceStore']) {
            return;
        }

        try {
            var licence = record['getLicenceStore'].first();
            var price = licence['getPriceStore'].first();
            var type = this.getTextForPriceType(price.get('type'));
            var expiration = licence.get('expirationDate');
            var result = type;
        } catch (e) {
            return result;
        }

        if (!expiration) {
            return result;
        }

        if (expiration) {
            result += '
{s name="till"}{/s}: ' + Ext.util.Format.date(expiration.date) + '';
        }

        return result;
    },

    createToolbarItems: function() {
        var me = this,
            items = me.callParent(arguments);

        Ext.Array.insert(items, 0, [
            me.createUploadButton()
        ]);

        return items;
    },

    createUploadButton: function() {
        var me = this;

        me.uploadButton = Ext.create('Ext.button.Button', {
            text: '{s name="upload_plugin"}{/s}',
            iconCls: 'sprite-plus-circle',
            handler: function() {
                me.fireEvent('open-plugin-upload');
            }
        });

        return me.uploadButton;
    },

    createActionColumnItems: function() {
        var me = this, items = [];

        items.push({
            iconCls: 'sprite-pencil',
            tooltip: '{s name="open"}{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                me.displayPluginEvent(record);
            }
        });

        items.push({
            iconCls: 'sprite-plus-circle',
            tooltip: '{s name="install"}{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                me.updateDummyPluginEvent(record);
            },
            getClass: function(value, metaData, record) {
                if (!record.allowDummyUpdate()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }
            }
        });

        items.push({
            iconCls: 'sprite-minus-circle',
            tooltip: '{s name="install_uninstall"}{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                if (record.allowInstall()) {
                    me.installPluginEvent(record);
                } else {
                    me.uninstallPluginEvent(record);
                }
            },
            getClass: function(value, metaData, record) {
                if (record.allowDummyUpdate()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }

                if (record.allowInstall()) {
                    return 'sprite-plus-circle';
                }
            }
        });

        items.push({
            iconCls: 'sprite-arrow-continue',
            tooltip: '{s name="reinstall"}{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                me.reinstallPluginEvent(record);
            },
            getClass: function(value, metaData, record) {
                if (!record.allowReinstall()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }
            }
        });

        items.push({
            iconCls: 'sprite-arrow-circle-135',
            tooltip: '{s name="update_plugin"}{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                me.updatePluginEvent(record);
            },
            getClass: function(value, metaData, record) {
                if (!record.allowUpdate()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }
            }
        });

        items.push({
            iconCls: 'sprite-bin-metal-full',
            tooltip: '{s name="delete"}{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                me.deletePluginEvent(record);
            },
            getClass: function(value, metaData, record) {
                if (!record.allowDelete()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }
            }
        });

        return items;
    }
});<commit_msg>SW-10177 - Fix local plugin search<commit_after>
//{namespace name=backend/plugin_manager/translation}
Ext.define('Shopware.apps.PluginManager.view.list.LocalPluginListingPage', {
    extend: 'Shopware.grid.Panel',
    alias: 'widget.plugin-manager-local-plugin-listing',
    cls: 'plugin-manager-local-plugin-listing',

    mixins: {
        events: 'Shopware.apps.PluginManager.view.PluginHelper'
    },
    viewConfig: {
        markDirty: false
    },

    configure: function() {
        return {
            addButton: false,
            pageSizeCombo: false,
            deleteButton: false,
            deleteColumn: false,
            editColumn: false,
            columns: {
                label: {
                    flex: 2,
                    header: '{s name="plugin_name"}{/s}',
                    renderer: this.nameRenderer,
                    editor: null
                },
                version: {
                    width: 30,
                    header: '{s name="version"}{/s}',
                    editor: null
                },
                installationDate: {
                    header: '{s name="installed_on"}{/s}',
                    renderer: this.dateRenderer,
                    editor: null
                },
                updateDate: {
                    header: '{s name="updated_on"}{/s}',
                    renderer: this.dateRenderer,
                    editor: null
                },
                licenceCheck: {
                    flex: 2,
                    sortable: false,
                    cls: 'licence-column',
                    header: '{s name="licence"}{/s}',
                    renderer: this.licenceRenderer,
                    editor: null
                },
                active: this.createActiveColumn,
                author: {
                    header: '{s name="from_producer"}{/s}',
                    renderer: this.authorRenderer,
                    editor: null
                }
            }
        };
    },

    initComponent: function() {
        var me = this;

        me.callParent(arguments);

        Shopware.app.Application.on('plugin-reloaded', function(plugin) {
            me.store.each(function(record, index) {
                if (record && record.get('technicalName') == plugin.get('technicalName')) {
                    me.store.remove(record);
                }
            });

            if (plugin.get('id') > 0) {
                plugin.set('groupingState', null);
                plugin.dirty = false;
                try {
                    me.store.add(plugin);
                } catch (e) {
                    me.store.load();
                }
            }

            me.store.sort();
            me.store.group();
            me.reconfigure(me.store);
            me.hideLoadingMask();
        });
    },

    createActionColumn: function () {
        var me = this;

        var actionColumn = me.callParent(arguments);

        actionColumn.width = 120;
        return actionColumn;
    },

    createSelectionModel: function() { },

    createActiveColumn: function() {
        var me = this,
            items = [];

        items.push({
            tooltip: '{s name="activate_deactivate"}{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                if (record.allowActivate()) {
                    me.activatePluginEvent(record);

                } else if (record.allowDeactivate()) {
                    me.deactivatePluginEvent(record);
                }
            },
            getClass: function(value, metaData, record) {
                if (!record.allowActivate() && !record.allowDeactivate()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }

                if (record.allowActivate()) {
                    return 'sprite-ui-check-box-uncheck';
                } else {
                    return 'sprite-ui-check-box';
                }
            }
        });

        return {
            xtype: 'actioncolumn',
            width: 60,
            align: 'center',
            header: '{s name="active"}{/s}',
            items: items
        };
    },

    searchEvent: function(field, value) {
        var me = this;

        me.store.clearFilter();

        value = value.toLowerCase();

        me.store.filterBy(function(record, id) {
            var description = record.get('description') + '';
            var name = record.get('label') + '';
            var technicalName = record.get('technicalName') + '';
            var producer = '';

            if (record['getProducerStore']) {
                producer = record['getProducerStore'].first().get('name') + '';
            }

            name = name.toLowerCase();
            technicalName = technicalName.toLowerCase();
            producer = producer.toLowerCase();
            description = description.toLowerCase();

            return (
                name.indexOf(value) > -1
                || description.indexOf(value) > -1
                || producer.indexOf(value) > -1
                || technicalName.indexOf(value) > -1
            );
        });
    },

    createFeatures: function() {
        var me = this,
            items = me.callParent(arguments);

        me.groupingFeature = Ext.create('Ext.grid.feature.Grouping', {
            groupHeaderTpl: new Ext.XTemplate(
                '{literal}{name:this.formatName} ({rows.length} Plugins){/literal}',
                {
                    formatName: function(name) {
                        switch(name) {
                            case 2:
                                return '{s name="group_headline_installed"}{/s}';
                            case 1:
                                return '{s name="group_headline_deactivated"}{/s}';
                            case 0:
                                return '{s name="group_headline_uninstalled"}{/s}';
                        }
                    }
                }
            )
        });

        items.push(me.groupingFeature);
        return items;
    },

    nameRenderer: function(value, metaData, record) {
        var name = record.get('label');

        if (!record.get('localIcon') || record.get('localIcon') == 'false') {
            return name;
        }

        return '

' + name;
    },

    authorRenderer: function(value, metaData, record) {
        if (!record || !record['getProducerStore']) {
            return value;
        }

        var producer = record['getProducerStore'].first();
        var website = producer.get('website');

        if (producer.get('name') == 'shopware AG' && !website) {
            website = 'http://www.shopware.com';
        }

        if (website && website.length > 0) {
            return ''+producer.get('name')+''
        } else {
            return producer.get('name');
        }
    },

    dateRenderer: function(value) {
        if (!value || !value.hasOwnProperty('date')) {
            return value;
        }
        var date = this.formatDate(value.date);
        return Ext.util.Format.date(date);
    },

    licenceRenderer: function(value, metaData, record) {
        if (!record || !record['getLicenceStore']) {
            return;
        }

        try {
            var licence = record['getLicenceStore'].first();
            var price = licence['getPriceStore'].first();
            var type = this.getTextForPriceType(price.get('type'));
            var expiration = licence.get('expirationDate');
            var result = type;
        } catch (e) {
            return result;
        }

        if (!expiration) {
            return result;
        }

        if (expiration) {
            result += '
{s name="till"}{/s}: ' + Ext.util.Format.date(expiration.date) + '';
        }

        return result;
    },

    createToolbarItems: function() {
        var me = this,
            items = me.callParent(arguments);

        Ext.Array.insert(items, 0, [
            me.createUploadButton()
        ]);

        return items;
    },

    createUploadButton: function() {
        var me = this;

        me.uploadButton = Ext.create('Ext.button.Button', {
            text: '{s name="upload_plugin"}{/s}',
            iconCls: 'sprite-plus-circle',
            handler: function() {
                me.fireEvent('open-plugin-upload');
            }
        });

        return me.uploadButton;
    },

    createActionColumnItems: function() {
        var me = this, items = [];

        items.push({
            iconCls: 'sprite-pencil',
            tooltip: '{s name="open"}{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                me.displayPluginEvent(record);
            }
        });

        items.push({
            iconCls: 'sprite-plus-circle',
            tooltip: '{s name="install"}{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                me.updateDummyPluginEvent(record);
            },
            getClass: function(value, metaData, record) {
                if (!record.allowDummyUpdate()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }
            }
        });

        items.push({
            iconCls: 'sprite-minus-circle',
            tooltip: '{s name="install_uninstall"}{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                if (record.allowInstall()) {
                    me.installPluginEvent(record);
                } else {
                    me.uninstallPluginEvent(record);
                }
            },
            getClass: function(value, metaData, record) {
                if (record.allowDummyUpdate()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }

                if (record.allowInstall()) {
                    return 'sprite-plus-circle';
                }
            }
        });

        items.push({
            iconCls: 'sprite-arrow-continue',
            tooltip: '{s name="reinstall"}{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                me.reinstallPluginEvent(record);
            },
            getClass: function(value, metaData, record) {
                if (!record.allowReinstall()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }
            }
        });

        items.push({
            iconCls: 'sprite-arrow-circle-135',
            tooltip: '{s name="update_plugin"}{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                me.updatePluginEvent(record);
            },
            getClass: function(value, metaData, record) {
                if (!record.allowUpdate()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }
            }
        });

        items.push({
            iconCls: 'sprite-bin-metal-full',
            tooltip: '{s name="delete"}{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                me.deletePluginEvent(record);
            },
            getClass: function(value, metaData, record) {
                if (!record.allowDelete()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }
            }
        });

        return items;
    }
});<|endoftext|>


<commit_before>document.addEventListener("DOMContentLoaded", () => {
    // get all edit buttons
    var btns = document.getElementsByClassName("btnEdit");
    Array.from(btns).forEach(editHandler);
});

function editHandler(btn) {
    btn.addEventListener("click", function(e) {
        e.preventDefault();
        // get row data
        document.querySelector("#single-form").classList.add("fadeIn");
        var row = btn.parentElement.parentElement;
        for (x = 0; x < row.childElementCount - 1; x++) {
            let data = row.children[x].dataset.name;
            let input = document.querySelector("input[name=" + data + "]");
            let barID = document.querySelector("#barID");
            console.log(data);

            switch (input.type) {
                case "text":
                    input.value = row.children[x].innerHTML;
                    break;
                case "number":
                    input.value = row.children[x].innerHTML;
                    break;
                case "datetime-local":
                    input.value = new Date(row.children[x].innerHTML).toISOString().substr(0, 16);
                    break;
                case "checkbox":
                    input.checked = row.children[x].children[0].checked;
                    break;
                case "email":
                    input.value = row.children[x].innerHTML;
                    break;
                case "hidden":
                    input.value = row.children[x].innerHTML;
                    barID.innerHTML = input.value;
            }
        }
    });

}<commit_msg>update<commit_after>document.addEventListener("DOMContentLoaded", () => {
    // get all edit buttons
    var btns = document.getElementsByClassName("btnEdit");
    Array.from(btns).forEach(editHandler);
});

function editHandler(btn) {
    btn.addEventListener("click", function(e) {
        e.preventDefault();
        // get row data
        document.querySelector("#single-form").classList.add("fadeIn");
        var row = btn.parentElement.parentElement;
        for (x = 0; x < row.childElementCount - 1; x++) {
            let data = row.children[x].dataset.name;
            let input = document.querySelector("input[name=" + data + "]");
            let barID = document.querySelector("#barID");

            if (data == "ID") barID.innerHTML = input.value;

            // @fabio, you just need to handle special cases :)
            switch (input.type) {
                case "datetime-local":
                    input.value = new Date(row.children[x].innerHTML).toISOString().substr(0, 16);
                    break;
                case "checkbox":
                    input.checked = row.children[x].children[0].checked;
                    break;
                default:
                    input.value = row.children[x].innerHTML;
            }
        }
    });
}
<|endoftext|>