<commit_before>(function() {
    function require(path, parent, orig) {
        var resolved = require.resolve(path);
        if (null == resolved) {
            orig = orig || path;
            parent = parent || "root";
            var err = new Error('Failed to require "' + orig + '" from "' + parent + '"');
            err.path = orig;
            err.parent = parent;
            err.require = true;
            throw err;
        }
        var module = require.modules[resolved];
        if (!module.exports) {
            module.exports = {};
            module.client = module.component = true;
            module.call(this, module.exports, require.relative(resolved), module);
        }
        return module.exports;
    }
    require.modules = {};
    require.aliases = {};
    require.resolve = function(path) {
        if (path.charAt(0) === "/") path = path.slice(1);
        var index = path + "/index.js";
        var paths = [ path, path + ".js", path + ".json", path + "/index.js", path + "/index.json" ];
        for (var i = 0; i < paths.length; i++) {
            var path = paths[i];
            if (require.modules.hasOwnProperty(path)) return path;
        }
        if (require.aliases.hasOwnProperty(index)) {
            return require.aliases[index];
        }
    };
    require.normalize = function(curr, path) {
        var segs = [];
        if ("." != path.charAt(0)) return path;
        curr = curr.split("/");
        path = path.split("/");
        for (var i = 0; i < path.length; ++i) {
            if (".." == path[i]) {
                curr.pop();
            } else if ("." != path[i] && "" != path[i]) {
                segs.push(path[i]);
            }
        }
        return curr.concat(segs).join("/");
    };
    require.register = function(path, definition) {
        require.modules[path] = definition;
    };
    require.alias = function(from, to) {
        if (!require.modules.hasOwnProperty(from)) {
            throw new Error('Failed to alias "' + from + '", it does not exist');
        }
        require.aliases[to] = from;
    };
    require.relative = function(parent) {
        var p = require.normalize(parent, "..");
        function lastIndexOf(arr, obj) {
            var i = arr.length;
            while (i--) {
                if (arr[i] === obj) return i;
            }
            return -1;
        }
        function localRequire(path) {
            var resolved = localRequire.resolve(path);
            return require(resolved, parent, path);
        }
        localRequire.resolve = function(path) {
            var c = path.charAt(0);
            if ("/" == c) return path.slice(1);
            if ("." == c) return require.normalize(p, path);
            var segs = parent.split("/");
            var i = lastIndexOf(segs, "deps") + 1;
            if (!i) i = 0;
            path = segs.slice(0, i + 1).join("/") + "/deps/" + path;
            return path;
        };
        localRequire.exists = function(path) {
            return require.modules.hasOwnProperty(localRequire.resolve(path));
        };
        return localRequire;
    };
    require.register("visionmedia-configurable.js/index.js", function(exports, require, module) {
        module.exports = function(obj) {
            obj.settings = {};
            obj.set = function(name, val) {
                if (1 == arguments.length) {
                    for (var key in name) {
                        this.set(key, name[key]);
                    }
                } else {
                    this.settings[name] = val;
                }
                return this;
            };
            obj.get = function(name) {
                return this.settings[name];
            };
            obj.enable = function(name) {
                return this.set(name, true);
            };
            obj.disable = function(name) {
                return this.set(name, false);
            };
            obj.enabled = function(name) {
                return !!this.get(name);
            };
            obj.disabled = function(name) {
                return !this.get(name);
            };
            return obj;
        };
    });
    require.register("gitemplate/index.js", function(exports, require, module) {
        "use strict";
        module.exports = {
            Gitemplate: Gitemplate,
            require: require
        };
        var configurable = require("configurable.js");
        var sprintf;
        var shelljs;
        var defShellOpt = {
            silent: true
        };
        function Gitemplate() {
            this.settings = {
                name: null,
                json: {},
                repo: null
            };
        }
        configurable(Gitemplate.prototype);
        Gitemplate.prototype.init = function() {
            var nativeRequire = this.get("nativeRequire");
            shelljs = nativeRequire("shelljs");
            sprintf = nativeRequire("util").format;
        };
        Gitemplate.prototype.cloneRepo = function() {
            return shelljs.exec(sprintf("git clone %s %s", this.get("src"), this.get("dst")), defShellOpt);
        };
        Gitemplate.prototype.rmGitDir = function() {
            shelljs.rm("-rf", this.get("dst") + "/.git");
        };
        Gitemplate.prototype.replaceContentVars = function() {
            var cmdHead = "find %s -type f -exec perl -p -i -e 's/\\{\\{";
            var cmdFoot = "\\}\\}/%s/g' {} \\;";
            var dst = this.get("dst");
            var res = shelljs.exec(sprintf(cmdHead + ESC_TMPL_VAR("name") + cmdFoot, dst, this.get("name")), defShellOpt);
            if (res.code !== 0) {
                return res;
            }
            res = shelljs.exec(sprintf(cmdHead + ESC_TMPL_VAR("year") + cmdFoot, dst, new Date().getFullYear()), defShellOpt);
            if (res.code !== 0) {
                return res;
            }
            var repo = this.get("repo");
            if (repo) {
                res = shelljs.exec(sprintf(cmdHead + ESC_TMPL_VAR("repo") + cmdFoot, dst, repo.replace("/", "\\/")), defShellOpt);
                if (res.code !== 0) {
                    return res;
                }
            }
            var json = this.get("json");
            Object.keys(json).forEach(function(key) {
                res = shelljs.exec(sprintf(cmdHead + ESC_TMPL_VAR(key) + cmdFoot, dst, json[key]), defShellOpt);
                if (res.code !== 0) {
                    return res;
                }
            });
            return res;
        };
        Gitemplate.prototype.replaceNameVars = function() {
            var name = this.get("name");
            var dst = this.get("dst");
            var nameVar = TMPL_VAR("name");
            var targets = shelljs.find(dst).filter(function(file) {
                return file.match(nameVar);
            });
            targets.forEach(function(target) {
                shelljs.mv(target, target.replace(nameVar, name));
            });
            var json = this.get("json");
            console.error("json", json);
            Object.keys(json).forEach(function(key) {
                var targets = shelljs.find(dst).filter(function(file) {
                    return file.match(ESC_TMPL_VAR(key));
                });
                console.error("targets", targets);
                targets.forEach(function(target) {
                    console.error(target, target.replace(TMPL_VAR(key), json[key]));
                    shelljs.mv(target, target.replace(TMPL_VAR(key), json[key]));
                });
            });
        };
        Gitemplate.prototype.initRepo = function() {
            shelljs.cd(this.get("dst"));
            return shelljs.exec("git init", defShellOpt);
        };
        Gitemplate.prototype.setGithubOrigin = function() {
            shelljs.cd(this.get("dst"));
            return shelljs.exec(sprintf("git remote add origin git@github.com:%s.git", this.get("repo")), defShellOpt);
        };
        function TMPL_VAR(key) {
            return "gitemplate." + key;
        }
        function ESC_TMPL_VAR(key) {
            return TMPL_VAR(key).replace(/\./, "\\.");
        }
    });
    require.alias("visionmedia-configurable.js/index.js", "gitemplate/deps/configurable.js/index.js");
    if (typeof exports == "object") {
        module.exports = require("gitemplate");
    } else if (typeof define == "function" && define.amd) {
        define(function() {
            return require("gitemplate");
        });
    } else {
        window["gitemplate"] = require("gitemplate");
    }
})();<commit_msg>Update dist<commit_after>(function() {
    function require(path, parent, orig) {
        var resolved = require.resolve(path);
        if (null == resolved) {
            orig = orig || path;
            parent = parent || "root";
            var err = new Error('Failed to require "' + orig + '" from "' + parent + '"');
            err.path = orig;
            err.parent = parent;
            err.require = true;
            throw err;
        }
        var module = require.modules[resolved];
        if (!module.exports) {
            module.exports = {};
            module.client = module.component = true;
            module.call(this, module.exports, require.relative(resolved), module);
        }
        return module.exports;
    }
    require.modules = {};
    require.aliases = {};
    require.resolve = function(path) {
        if (path.charAt(0) === "/") path = path.slice(1);
        var index = path + "/index.js";
        var paths = [ path, path + ".js", path + ".json", path + "/index.js", path + "/index.json" ];
        for (var i = 0; i < paths.length; i++) {
            var path = paths[i];
            if (require.modules.hasOwnProperty(path)) return path;
        }
        if (require.aliases.hasOwnProperty(index)) {
            return require.aliases[index];
        }
    };
    require.normalize = function(curr, path) {
        var segs = [];
        if ("." != path.charAt(0)) return path;
        curr = curr.split("/");
        path = path.split("/");
        for (var i = 0; i < path.length; ++i) {
            if (".." == path[i]) {
                curr.pop();
            } else if ("." != path[i] && "" != path[i]) {
                segs.push(path[i]);
            }
        }
        return curr.concat(segs).join("/");
    };
    require.register = function(path, definition) {
        require.modules[path] = definition;
    };
    require.alias = function(from, to) {
        if (!require.modules.hasOwnProperty(from)) {
            throw new Error('Failed to alias "' + from + '", it does not exist');
        }
        require.aliases[to] = from;
    };
    require.relative = function(parent) {
        var p = require.normalize(parent, "..");
        function lastIndexOf(arr, obj) {
            var i = arr.length;
            while (i--) {
                if (arr[i] === obj) return i;
            }
            return -1;
        }
        function localRequire(path) {
            var resolved = localRequire.resolve(path);
            return require(resolved, parent, path);
        }
        localRequire.resolve = function(path) {
            var c = path.charAt(0);
            if ("/" == c) return path.slice(1);
            if ("." == c) return require.normalize(p, path);
            var segs = parent.split("/");
            var i = lastIndexOf(segs, "deps") + 1;
            if (!i) i = 0;
            path = segs.slice(0, i + 1).join("/") + "/deps/" + path;
            return path;
        };
        localRequire.exists = function(path) {
            return require.modules.hasOwnProperty(localRequire.resolve(path));
        };
        return localRequire;
    };
    require.register("visionmedia-configurable.js/index.js", function(exports, require, module) {
        module.exports = function(obj) {
            obj.settings = {};
            obj.set = function(name, val) {
                if (1 == arguments.length) {
                    for (var key in name) {
                        this.set(key, name[key]);
                    }
                } else {
                    this.settings[name] = val;
                }
                return this;
            };
            obj.get = function(name) {
                return this.settings[name];
            };
            obj.enable = function(name) {
                return this.set(name, true);
            };
            obj.disable = function(name) {
                return this.set(name, false);
            };
            obj.enabled = function(name) {
                return !!this.get(name);
            };
            obj.disabled = function(name) {
                return !this.get(name);
            };
            return obj;
        };
    });
    require.register("gitemplate/index.js", function(exports, require, module) {
        "use strict";
        module.exports = {
            Gitemplate: Gitemplate,
            require: require
        };
        var configurable = require("configurable.js");
        var sprintf;
        var shelljs;
        var defShellOpt = {
            silent: true
        };
        function Gitemplate() {
            this.settings = {
                name: null,
                json: {},
                repo: null
            };
        }
        configurable(Gitemplate.prototype);
        Gitemplate.prototype.init = function() {
            var nativeRequire = this.get("nativeRequire");
            shelljs = nativeRequire("shelljs");
            sprintf = nativeRequire("util").format;
        };
        Gitemplate.prototype.cloneRepo = function() {
            return shelljs.exec(sprintf("git clone %s %s", this.get("src"), this.get("dst")), defShellOpt);
        };
        Gitemplate.prototype.rmGitDir = function() {
            shelljs.rm("-rf", this.get("dst") + "/.git");
        };
        Gitemplate.prototype.replaceContentVars = function() {
            var cmdHead = "find %s -type f -exec perl -p -i -e 's/\\{\\{";
            var cmdFoot = "\\}\\}/%s/g' {} \\;";
            var dst = this.get("dst");
            var res = shelljs.exec(sprintf(cmdHead + ESC_TMPL_VAR("name") + cmdFoot, dst, this.get("name")), defShellOpt);
            if (res.code !== 0) {
                return res;
            }
            res = shelljs.exec(sprintf(cmdHead + ESC_TMPL_VAR("year") + cmdFoot, dst, new Date().getFullYear()), defShellOpt);
            if (res.code !== 0) {
                return res;
            }
            var repo = this.get("repo");
            if (repo) {
                res = shelljs.exec(sprintf(cmdHead + ESC_TMPL_VAR("repo") + cmdFoot, dst, repo.replace("/", "\\/")), defShellOpt);
                if (res.code !== 0) {
                    return res;
                }
            }
            var json = this.get("json");
            Object.keys(json).forEach(function(key) {
                res = shelljs.exec(sprintf(cmdHead + ESC_TMPL_VAR(key) + cmdFoot, dst, json[key]), defShellOpt);
                if (res.code !== 0) {
                    return res;
                }
            });
            return res;
        };
        Gitemplate.prototype.replaceNameVars = function() {
            var name = this.get("name");
            var dst = this.get("dst");
            var nameVar = TMPL_VAR("name");
            var targets = shelljs.find(dst).filter(function(file) {
                return file.match(nameVar);
            });
            targets.forEach(function(target) {
                shelljs.mv(target, target.replace(nameVar, name));
            });
            var json = this.get("json");
            Object.keys(json).forEach(function(key) {
                var targets = shelljs.find(dst).filter(function(file) {
                    return file.match(ESC_TMPL_VAR(key));
                });
                targets.forEach(function(target) {
                    shelljs.mv(target, target.replace(TMPL_VAR(key), json[key]));
                });
            });
        };
        Gitemplate.prototype.initRepo = function() {
            shelljs.cd(this.get("dst"));
            return shelljs.exec("git init", defShellOpt);
        };
        Gitemplate.prototype.setGithubOrigin = function() {
            shelljs.cd(this.get("dst"));
            return shelljs.exec(sprintf("git remote add origin git@github.com:%s.git", this.get("repo")), defShellOpt);
        };
        function TMPL_VAR(key) {
            return "gitemplate." + key;
        }
        function ESC_TMPL_VAR(key) {
            return TMPL_VAR(key).replace(/\./, "\\.");
        }
    });
    require.alias("visionmedia-configurable.js/index.js", "gitemplate/deps/configurable.js/index.js");
    if (typeof exports == "object") {
        module.exports = require("gitemplate");
    } else if (typeof define == "function" && define.amd) {
        define(function() {
            return require("gitemplate");
        });
    } else {
        window["gitemplate"] = require("gitemplate");
    }
})();<|endoftext|>


<commit_before>

function SubServiceControl($scope, $routeParams, $location, $interval, resourcesService, authService, $serviceHealth) {
    // Ensure logged in
    authService.checkLogin($scope);
    $scope.name = "servicedetails";
    $scope.params = $routeParams;
    $scope.servicesService = resourcesService;

    $scope.defaultHostAlias = location.hostname;
    var re = /\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/;
    if (re.test(location.hostname) || location.hostname == "localhost") {
        $.getJSON("/hosts/defaultHostAlias", "", function(data) {
            $scope.defaultHostAlias = data.hostalias;
        });
    }

    $scope.breadcrumbs = [
        { label: 'breadcrumb_deployed', url: '#/apps' }
    ];

    $scope.services = buildTable('Name', [
        { id: 'Name', name: 'deployed_tbl_name'},
        { id: 'DesiredState', name: 'deployed_tbl_state' },
        { id: 'Startup', name: 'label_service_startup' }
    ]);

    $scope.vhosts = buildTable('Name', [
        { id: 'Name', name: 'vhost_name'},
        { id: 'Application', name: 'vhost_application'},
        { id: 'ServiceEndpoint', name: 'vhost_service_endpoint'},
        { id: 'Name', name: 'vhost_url'},
        { id: 'Action', name: 'vhost_actions'},
    ]);

    $scope.ips = buildTable('ServiceID', [
        { id: 'ServiceName', name: 'tbl_virtual_ip_service'},
        { id: 'EndpointName', name: 'tbl_virtual_ip_application'},
        { id: 'AssignmentType', name: 'tbl_virtual_ip_assignment_type'},
        { id: 'HostName', name: 'tbl_virtual_ip_host'},
        { id: 'PoolID', name: 'tbl_virtual_ip_pool'},
        { id: 'IPAddr', name: 'tbl_virtual_ip'},
        { id: 'Port', name: 'tbl_virtual_ip_port'},
        { id: 'Actions', name: 'tbl_virtual_ip_actions'}
    ]);

    //add vhost data (includes name, app & service endpoint)
    $scope.vhosts.add = {};

    //app & service endpoint option for adding a new virtual host
    $scope.vhosts.options = [];

    $scope.click_app = function(id) {
        $location.path('/services/' + id);
    };

    $scope.click_pool = function(id) {
        $location.path('/pools/' + id);
    };

    $scope.click_host = function(id) {
        $location.path('/hosts/' + id);
    };

    $scope.modalAddVHost = function() {
        $('#addVHost').modal('show');
    };

    $scope.addVHost = function() {
        if (!$scope.vhosts.add.name || $scope.vhosts.add.name.length <= 0) {
            console.error( "Cannot add vhost -- missing name");
            return;
        }

        if ($scope.vhosts.options.length <= 0) {
            console.error( "Cannot add vhost -- no available application and service");
            return;
        }

        var name = $scope.vhosts.add.name;
        var serviceId = $scope.services.current.ID;
        var serviceEndpoint = $scope.vhosts.add.app_ep.ServiceEndpoint;
        resourcesService.add_vhost( serviceId, serviceEndpoint, name, function() {
            $scope.vhosts.add = {};
            refreshServices($scope, resourcesService, false);
        });
    };

    // modalAssignIP opens a modal view to assign an ip address to a service
    $scope.modalAssignIP = function(ip, poolID) {
      $scope.ips.assign = {'ip':ip, 'value':null};
      resourcesService.get_pool_ips(poolID, function(data) {
        var options= [{'Value':'Automatic', 'IPAddr':null}];

        //host ips
        if ( data && data.HostIPs) {
          for(var i = 0; i < data.HostIPs.length; ++i) {
            var IPAddr = data.HostIPs[i].IPAddress;
            var value = 'Host: ' + IPAddr + ' - ' + data.HostIPs[i].InterfaceName;
            options.push({'Value': value, 'IPAddr':IPAddr});
            // set the default value to the currently assigned value
            if ($scope.ips.assign.ip.IPAddr == IPAddr) {
              $scope.ips.assign.value = options[ options.length-1];
            }
          }
        }

        //host ips
        if ( data && data.VirtualIPs) {
          for(var i = 0; i < data.VirtualIPs.length; ++i) {
            var IPAddr = data.VirtualIPs[i].IP;
            var value =  "Virtual IP: " + IPAddr;
            options.push({'Value': value, 'IPAddr':IPAddr});
            // set the default value to the currently assigned value
            if ($scope.ips.assign.ip.IPAddr == IPAddr) {
              $scope.ips.assign.value = options[ options.length-1];
            }
          }
        }

        //default to automatic
        if(!$scope.ips.assign.value) {
          $scope.ips.assign.value = options[0];
        }

        $scope.ips.assign.options = options;
        $('#assignIP').modal('show');
      });
    };

    $scope.AssignIP = function() {
        var serviceID = $scope.ips.assign.ip.ServiceID;
        var IP = $scope.ips.assign.value.IPAddr;
        resourcesService.assign_ip(serviceID, IP, function(data) {
            refreshServices($scope, resourcesService, false);
        });
    };

    $scope.vhost_url = function(vhost) {
        var port = location.port === "" ? "" : ":"+location.port;
        return location.protocol + "//" + vhost + "." + $scope.defaultHostAlias + port;
    };

    $scope.indent = indentClass;

    $scope.clickRunning = function(app, status, servicesService){
        toggleRunning(app, status, servicesService);
        $serviceHealth.update(app.ID);
    };

    $scope.viewConfig = function(service) {
        $scope.editService = $.extend({}, service);
        $scope.editService.config = 'TODO: Implement';
        $('#editConfig').modal('show');
    };

    $scope.clickRemoveVirtualHost = function(vhost) {
        resourcesService.delete_vhost( vhost.ApplicationId, vhost.ServiceEndpoint, vhost.Name, function( data) {
            refreshServices($scope, resourcesService, false);
        });
    };

    $scope.editConfig = function(service, config) {
        $scope.editService = $.extend({}, service);
        $scope.editService.config = config;
        $('#editConfig').modal('show');
    };

    $scope.viewLog = function(serviceState) {
        $scope.editService = $.extend({}, serviceState);
        resourcesService.get_service_state_logs(serviceState.ServiceID, serviceState.ID, function(log) {
            $scope.editService.log = log.Detail;
            $('#viewLog').modal('show');
        });
    };

    $scope.snapshotService = function(service) {
        resourcesService.snapshot_service(service.ID, function(label) {
            console.log('Snapshotted service name:%s label:%s', service.Name, label.Detail);
            // TODO: add the snapshot label to some partial view in the UI
        });
    };

    $scope.updateService = function() {
        resourcesService.update_service($scope.services.current.ID, $scope.services.current, function() {
            console.log('Updated %s', $scope.services.current.ID);
            var lastCrumb = $scope.breadcrumbs[$scope.breadcrumbs.length - 1];
            lastCrumb.label = $scope.services.current.Name;
        });
    };

    // Update the running instances so it is reflected when we save the changes
    //TODO: Destroy/cancel this interval when we are not on the subservices page, or get rid of it all together
    function updateRunning() {
        if ($scope.params.serviceId) {
            refreshRunningForService($scope, resourcesService, $scope.params.serviceId, function() {
                wait.running = true;
                mashHostsToInstances();
            });
        }
    }

    if(!angular.isDefined($scope.updateRunningInterval)) {
        $scope.updateRunningInterval = $interval(updateRunning, 3000);
    }

    // Get a list of deployed apps
    refreshServices($scope, resourcesService, true, function() {
        if ($scope.services.current) {
            var lineage = getServiceLineage($scope.services.mapped, $scope.services.current);
            for (var i=0; i < lineage.length; i++) {
                var crumb = {
                    label: lineage[i].Name
                };
                if (i == lineage.length - 1) {
                    crumb.itemClass = 'active';
                } else {
                    crumb.url = '#/services/' + lineage[i].ID;
                }
                $scope.breadcrumbs.push(crumb);
            }
        }
        $serviceHealth.update();
    });

    $scope.$on('$destroy', function() {
        $interval.cancel($scope.updateRunningInterval);
        $scope.updateRunningInterval = undefined;
    });

    var wait = { hosts: false, running: false };
    var mashHostsToInstances = function() {
        if (!wait.hosts || !wait.running) return;

        for (var i=0; i < $scope.running.data.length; i++) {
            var instance = $scope.running.data[i];
            instance.hostName = $scope.hosts.mapped[instance.HostID].Name;
        }
    };
    refreshHosts($scope, resourcesService, true, function() {
        wait.hosts = true;
        mashHostsToInstances();
    });
    refreshRunningForService($scope, resourcesService, $scope.params.serviceId, function() {
        wait.running = true;
        mashHostsToInstances();
    });

    $scope.killRunning = function(app) {
        resourcesService.kill_running(app.HostID, app.ID, function() {
            refreshRunningForService($scope, resourcesService, $scope.params.serviceId, function() {
                wait.running = true;
                mashHostsToInstances();
            });
        });
    };

    $scope.startTerminal = function(app) {
        window.open("http://" + window.location.hostname + ":50000");
    };

    var setupNewService = function() {
        $scope.newService = {
            poolID: 'default',
            ParentServiceID: $scope.params.serviceId,
            DesiredState: 1,
            Launch: 'auto',
            Instances: 1,
            Description: '',
            ImageID: ''
        };
    };

    if ($scope.dev) {
        setupNewService();
        $scope.add_service = function() {
            resourcesService.add_service($scope.newService, function() {
                refreshServices($scope, resourcesService, false);
                setupNewService();
            });
        };
        $scope.showAddService = function() {
            $('#addService').modal('show');
        };
        $scope.deleteService = function() {
            var parent = $scope.services.current.ParentServiceID;
            console.log('Parent: %s, Length: %d', parent, parent.length);
            resourcesService.remove_service($scope.params.serviceId, function() {
                refreshServices($scope, resourcesService, false, function() {
                    if (parent && parent.length > 0) {
                        $location.path('/services/' + parent);
                    } else {
                        $location.path('/apps');
                    }
                });
            });
        };
    }
}
<commit_msg>remove unnessary edit<commit_after>

function SubServiceControl($scope, $routeParams, $location, $interval, resourcesService, authService, $serviceHealth) {
    // Ensure logged in
    authService.checkLogin($scope);
    $scope.name = "servicedetails";
    $scope.params = $routeParams;
    $scope.servicesService = resourcesService;

    $scope.defaultHostAlias = location.hostname;
    var re = /\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/;
    if (re.test(location.hostname) || location.hostname == "localhost") {
        $.getJSON("/hosts/defaultHostAlias", "", function(data) {
            $scope.defaultHostAlias = data.hostalias;
        });
    }

    $scope.breadcrumbs = [
        { label: 'breadcrumb_deployed', url: '#/apps' }
    ];

    $scope.services = buildTable('Name', [
        { id: 'Name', name: 'deployed_tbl_name'},
        { id: 'DesiredState', name: 'deployed_tbl_state' },
        { id: 'Startup', name: 'label_service_startup' }
    ]);

    $scope.vhosts = buildTable('Name', [
        { id: 'Name', name: 'vhost_name'},
        { id: 'Application', name: 'vhost_application'},
        { id: 'ServiceEndpoint', name: 'vhost_service_endpoint'},
        { id: 'Name', name: 'vhost_url'},
        { id: 'Action', name: 'vhost_actions'},
    ]);

    $scope.ips = buildTable('ServiceID', [
        { id: 'ServiceName', name: 'tbl_virtual_ip_service'},
        { id: 'EndpointName', name: 'tbl_virtual_ip_application'},
        { id: 'AssignmentType', name: 'tbl_virtual_ip_assignment_type'},
        { id: 'HostName', name: 'tbl_virtual_ip_host'},
        { id: 'PoolID', name: 'tbl_virtual_ip_pool'},
        { id: 'IPAddr', name: 'tbl_virtual_ip'},
        { id: 'Port', name: 'tbl_virtual_ip_port'},
        { id: 'Actions', name: 'tbl_virtual_ip_actions'}
    ]);

    //add vhost data (includes name, app & service endpoint)
    $scope.vhosts.add = {};

    //app & service endpoint option for adding a new virtual host
    $scope.vhosts.options = [];

    $scope.click_app = function(id) {
        $location.path('/services/' + id);
    };

    $scope.click_pool = function(id) {
        $location.path('/pools/' + id);
    };

    $scope.click_host = function(id) {
        $location.path('/hosts/' + id);
    };

    $scope.modalAddVHost = function() {
        $('#addVHost').modal('show');
    };

    $scope.addVHost = function() {
        if (!$scope.vhosts.add.name || $scope.vhosts.add.name.length <= 0) {
            console.error( "Cannot add vhost -- missing name");
            return;
        }

        if ($scope.vhosts.options.length <= 0) {
            console.error( "Cannot add vhost -- no available application and service");
            return;
        }

        var name = $scope.vhosts.add.name;
        var serviceId = $scope.vhosts.add.app_ep.ServiceID;
        var serviceEndpoint = $scope.vhosts.add.app_ep.ServiceEndpoint;
        resourcesService.add_vhost( serviceId, serviceEndpoint, name, function() {
            $scope.vhosts.add = {};
            refreshServices($scope, resourcesService, false);
        });
    };

    // modalAssignIP opens a modal view to assign an ip address to a service
    $scope.modalAssignIP = function(ip, poolID) {
      $scope.ips.assign = {'ip':ip, 'value':null};
      resourcesService.get_pool_ips(poolID, function(data) {
        var options= [{'Value':'Automatic', 'IPAddr':null}];

        //host ips
        if ( data && data.HostIPs) {
          for(var i = 0; i < data.HostIPs.length; ++i) {
            var IPAddr = data.HostIPs[i].IPAddress;
            var value = 'Host: ' + IPAddr + ' - ' + data.HostIPs[i].InterfaceName;
            options.push({'Value': value, 'IPAddr':IPAddr});
            // set the default value to the currently assigned value
            if ($scope.ips.assign.ip.IPAddr == IPAddr) {
              $scope.ips.assign.value = options[ options.length-1];
            }
          }
        }

        //host ips
        if ( data && data.VirtualIPs) {
          for(var i = 0; i < data.VirtualIPs.length; ++i) {
            var IPAddr = data.VirtualIPs[i].IP;
            var value =  "Virtual IP: " + IPAddr;
            options.push({'Value': value, 'IPAddr':IPAddr});
            // set the default value to the currently assigned value
            if ($scope.ips.assign.ip.IPAddr == IPAddr) {
              $scope.ips.assign.value = options[ options.length-1];
            }
          }
        }

        //default to automatic
        if(!$scope.ips.assign.value) {
          $scope.ips.assign.value = options[0];
        }

        $scope.ips.assign.options = options;
        $('#assignIP').modal('show');
      });
    };

    $scope.AssignIP = function() {
        var serviceID = $scope.ips.assign.ip.ServiceID;
        var IP = $scope.ips.assign.value.IPAddr;
        resourcesService.assign_ip(serviceID, IP, function(data) {
            refreshServices($scope, resourcesService, false);
        });
    };

    $scope.vhost_url = function(vhost) {
        var port = location.port === "" ? "" : ":"+location.port;
        return location.protocol + "//" + vhost + "." + $scope.defaultHostAlias + port;
    };

    $scope.indent = indentClass;

    $scope.clickRunning = function(app, status, servicesService){
        toggleRunning(app, status, servicesService);
        $serviceHealth.update(app.ID);
    };

    $scope.viewConfig = function(service) {
        $scope.editService = $.extend({}, service);
        $scope.editService.config = 'TODO: Implement';
        $('#editConfig').modal('show');
    };

    $scope.clickRemoveVirtualHost = function(vhost) {
        resourcesService.delete_vhost( vhost.ApplicationId, vhost.ServiceEndpoint, vhost.Name, function( data) {
            refreshServices($scope, resourcesService, false);
        });
    };

    $scope.editConfig = function(service, config) {
        $scope.editService = $.extend({}, service);
        $scope.editService.config = config;
        $('#editConfig').modal('show');
    };

    $scope.viewLog = function(serviceState) {
        $scope.editService = $.extend({}, serviceState);
        resourcesService.get_service_state_logs(serviceState.ServiceID, serviceState.ID, function(log) {
            $scope.editService.log = log.Detail;
            $('#viewLog').modal('show');
        });
    };

    $scope.snapshotService = function(service) {
        resourcesService.snapshot_service(service.ID, function(label) {
            console.log('Snapshotted service name:%s label:%s', service.Name, label.Detail);
            // TODO: add the snapshot label to some partial view in the UI
        });
    };

    $scope.updateService = function() {
        resourcesService.update_service($scope.services.current.ID, $scope.services.current, function() {
            console.log('Updated %s', $scope.services.current.ID);
            var lastCrumb = $scope.breadcrumbs[$scope.breadcrumbs.length - 1];
            lastCrumb.label = $scope.services.current.Name;
        });
    };

    // Update the running instances so it is reflected when we save the changes
    //TODO: Destroy/cancel this interval when we are not on the subservices page, or get rid of it all together
    function updateRunning() {
        if ($scope.params.serviceId) {
            refreshRunningForService($scope, resourcesService, $scope.params.serviceId, function() {
                wait.running = true;
                mashHostsToInstances();
            });
        }
    }

    if(!angular.isDefined($scope.updateRunningInterval)) {
        $scope.updateRunningInterval = $interval(updateRunning, 3000);
    }

    // Get a list of deployed apps
    refreshServices($scope, resourcesService, true, function() {
        if ($scope.services.current) {
            var lineage = getServiceLineage($scope.services.mapped, $scope.services.current);
            for (var i=0; i < lineage.length; i++) {
                var crumb = {
                    label: lineage[i].Name
                };
                if (i == lineage.length - 1) {
                    crumb.itemClass = 'active';
                } else {
                    crumb.url = '#/services/' + lineage[i].ID;
                }
                $scope.breadcrumbs.push(crumb);
            }
        }
        $serviceHealth.update();
    });

    $scope.$on('$destroy', function() {
        $interval.cancel($scope.updateRunningInterval);
        $scope.updateRunningInterval = undefined;
    });

    var wait = { hosts: false, running: false };
    var mashHostsToInstances = function() {
        if (!wait.hosts || !wait.running) return;

        for (var i=0; i < $scope.running.data.length; i++) {
            var instance = $scope.running.data[i];
            instance.hostName = $scope.hosts.mapped[instance.HostID].Name;
        }
    };
    refreshHosts($scope, resourcesService, true, function() {
        wait.hosts = true;
        mashHostsToInstances();
    });
    refreshRunningForService($scope, resourcesService, $scope.params.serviceId, function() {
        wait.running = true;
        mashHostsToInstances();
    });

    $scope.killRunning = function(app) {
        resourcesService.kill_running(app.HostID, app.ID, function() {
            refreshRunningForService($scope, resourcesService, $scope.params.serviceId, function() {
                wait.running = true;
                mashHostsToInstances();
            });
        });
    };

    $scope.startTerminal = function(app) {
        window.open("http://" + window.location.hostname + ":50000");
    };

    var setupNewService = function() {
        $scope.newService = {
            poolID: 'default',
            ParentServiceID: $scope.params.serviceId,
            DesiredState: 1,
            Launch: 'auto',
            Instances: 1,
            Description: '',
            ImageID: ''
        };
    };

    if ($scope.dev) {
        setupNewService();
        $scope.add_service = function() {
            resourcesService.add_service($scope.newService, function() {
                refreshServices($scope, resourcesService, false);
                setupNewService();
            });
        };
        $scope.showAddService = function() {
            $('#addService').modal('show');
        };
        $scope.deleteService = function() {
            var parent = $scope.services.current.ParentServiceID;
            console.log('Parent: %s, Length: %d', parent, parent.length);
            resourcesService.remove_service($scope.params.serviceId, function() {
                refreshServices($scope, resourcesService, false, function() {
                    if (parent && parent.length > 0) {
                        $location.path('/services/' + parent);
                    } else {
                        $location.path('/apps');
                    }
                });
            });
        };
    }
}
<|endoftext|>


<commit_before>'use strict';

/* global d3 */
angular.module('courses').controller('CourseReportController', ['$scope', '$stateParams','$window', 'CoursesService', 'DiagramsCalendarService',
    'DiagramsCardsInPlayService', 'DiagramsTimeSpentService', 'DiagramsTimeSeriesService','Courses',
    function ($scope, $stateParams, $window, CoursesService, DiagramsCalendarService, DiagramsCardsInPlayService, DiagramsTimeSpentService, DiagramsTimeSeriesService, Courses) {

        $scope.init = function () {

            $scope.course = Courses.get({
                courseId: $stateParams.courseId
            }, function () {

                var res = CoursesService.serverLoadCards();
                var promise = res.get({courseId: $stateParams.courseId});
                promise.$promise.then(function (cards) {

                    $scope.cards = cards;
                    DiagramsCalendarService.drawCalendar(cards, '#cal', '#practice-date', '#number-of-cards', ($window.innerWidth / 2)-130);

                    var w = $window.innerWidth + 110;
                    if ($window.innerWidth > 990){
                        w = ($window.innerWidth / 2) + 60;
                    }
                    DiagramsCardsInPlayService.drawLineChart(cards, '#inplay', '#total-cards-learned', w);
                    DiagramsTimeSpentService.drawBarChart(cards, '#timespent', '#spent-practice-date', '#spent-practice-time','#spent-all-time', ($window.innerWidth / 2)-130);
                });
            });

        };

        $scope.diagramShown = false;
        $scope.initProgress = function (id, index) {

            var res = CoursesService.serverLoadCards();
            var promise = res.get({courseId: id});
            promise.$promise.then(function (cards) {

                var repetitions = 0;
                for (var i=0; i<cards.length; i++) {
                    repetitions+=cards[i].history.length;
                }

                if (repetitions < 3) {
                    $scope.diagramShown = false;
                } else {
                    $scope.diagramShown = true;
                }
                var w = $window.innerWidth + 110;
                if ($window.innerWidth > 990){
                    w = ($window.innerWidth / 2) + 60;
                }
                DiagramsCardsInPlayService.drawLineChart(cards, '#inplay'+index, undefined, w);
                //DiagramsTimeSpentService.drawBarChart(cards, '#timespent'+index, '#spent-practice-date'+index, '#spent-practice-time'+index, ($window.innerWidth / 2)-130);
            });
        };

        $scope.score = 0;

        $scope.selectedCards = [];
        $scope.initTimeSeries = function (item, model, label) {
            //console.log(item);
            //console.log(model);
            //console.log(label);

            var w = $window.innerWidth + 110;
            if ($window.innerWidth > 990){
                w = ($window.innerWidth / 2) + 60;
            }
            DiagramsTimeSeriesService.drawTimeSeries($scope.selectedCards, '#timeseries', w);
        };

    }
]);
<commit_msg>slowly bringing alternative answers in<commit_after>'use strict';

/* global d3 */
angular.module('courses').controller('CourseReportController', ['$scope', '$stateParams','$window', 'CoursesService', 'DiagramsCalendarService',
    'DiagramsCardsInPlayService', 'DiagramsTimeSpentService', 'DiagramsTimeSeriesService','Courses',
    function ($scope, $stateParams, $window, CoursesService, DiagramsCalendarService, DiagramsCardsInPlayService, DiagramsTimeSpentService, DiagramsTimeSeriesService, Courses) {

        $scope.init = function () {

            $scope.course = Courses.get({
                courseId: $stateParams.courseId
            }, function () {

                var res = CoursesService.serverLoadCards();
                var promise = res.get({courseId: $stateParams.courseId});
                promise.$promise.then(function (cards) {

                    $scope.cards = cards;
                    DiagramsCalendarService.drawCalendar(cards, '#cal', '#practice-date', '#number-of-cards', ($window.innerWidth / 2)-130);

                    var w = $window.innerWidth + 110;
                    //if ($window.innerWidth > 990){
                    //    w = ($window.innerWidth) + 60;
                    //}
                    DiagramsCardsInPlayService.drawLineChart(cards, '#inplay', '#total-cards-learned', w);
                    DiagramsTimeSpentService.drawBarChart(cards, '#timespent', '#spent-practice-date', '#spent-practice-time','#spent-all-time', w);
                });
            });

        };

        $scope.diagramShown = false;
        $scope.initProgress = function (id, index) {

            var res = CoursesService.serverLoadCards();
            var promise = res.get({courseId: id});
            promise.$promise.then(function (cards) {

                var repetitions = 0;
                for (var i=0; i<cards.length; i++) {
                    repetitions+=cards[i].history.length;
                }

                if (repetitions < 3) {
                    $scope.diagramShown = false;
                } else {
                    $scope.diagramShown = true;
                }
                var w = $window.innerWidth + 110;
                //if ($window.innerWidth > 990){
                //    w = ($window.innerWidth) + 60;
                //}
                DiagramsCardsInPlayService.drawLineChart(cards, '#inplay'+index, undefined, w);
                //DiagramsTimeSpentService.drawBarChart(cards, '#timespent'+index, '#spent-practice-date'+index, '#spent-practice-time'+index, ($window.innerWidth / 2)-130);
            });
        };

        $scope.score = 0;

        $scope.selectedCards = [];
        $scope.initTimeSeries = function (item, model, label) {
            //console.log(item);
            //console.log(model);
            //console.log(label);

            var w = $window.innerWidth + 110;
            //if ($window.innerWidth > 990){
            //    w = ($window.innerWidth / 2) + 60;
            //}
            DiagramsTimeSeriesService.drawTimeSeries($scope.selectedCards, '#timeseries', w);
        };

    }
]);
<|endoftext|>


<commit_before>'use strict';

const EDITOR_MODE_CREATE = 1;
const EDITOR_MODE_EDIT   = 2;

const ADD_NEW_FIELD_BUTTON_ROW = 'add_new_field_button';

function EntityEditor(entity_event_subscriber, base_wall) {
    this.__init__(entity_event_subscriber, base_wall);
}

EntityEditor.prototype = {

    __init__: function(entity_event_subscriber, base_wall) {
        this.entity_event_subscriber = entity_event_subscriber;
        this.base_wall = base_wall;
        this.world = this.base_wall.world;
        this.current_mode = null;
    },

    create_or_save_changes_button_pressed: function() {
        if (this.current_mode === EDITOR_MODE_CREATE) {
            this._entity_created();
        } else {
            this._modify_entity();
        }
    },

    cancel_or_delete_button_pressed: function() {
        this.wall_entity_editor.detach_from_parent();
        this.wall_entity_editor.force_hide_self_and_all_child_attachments_recursively();
        if (this.current_mode === EDITOR_MODE_EDIT) {
            MANAGER_ENTITY.delete_entity_by_id(this.entity_id_being_edited);
        }
    },

    delete_entity_field: function(field_name) {
        delete this.entity_field_rows[field_name];
        this.wall_entity_editor.delete_row_by_name(field_name);

        if (this.current_mode === EDITOR_MODE_EDIT) {
            var entity_modify = MANAGER_ENTITY.get_entity_by_id(this.entity_id_being_edited);
            entity_modify.delete_property(field_name, true);
        }
    },

    create: function(edit_mode) {
        if (!is_defined(this.wall_entity_editor)) {
            this.wall_entity_editor = new FloatingWall(600, 400, null, null, this.world, false, COLOR_FLOATING_WALL_SUCCESS);
            this.wall_entity_editor.manual_visibility = true;
            this.wall_entity_editor.set_attachment_depth_offset(10);
            this.wall_entity_editor.add_close_button();

            this.wall_title = this.wall_entity_editor.add_row(-1).add_3D_element('HODL IOTA', TYPE_TITLE);

            this.entity_field_rows = {};

            // Default field : entity type selector.
            this.entity_field_rows[ENTITY_DEFAULT_PROPERTY_TYPE] = new FieldRowEntityType(this);
            this.entity_field_rows[ENTITY_DEFAULT_PROPERTY_TYPE].create(null);

            // Default field : entity name.
            this.entity_field_rows[ENTITY_PROPERTY_NAME] = new FieldRowName(this);
            this.entity_field_rows[ENTITY_PROPERTY_NAME].create(null);

            // Both creating a new entity and editing an existing entity will contain an add a new field button.
            this.add_new_field_button = this.wall_entity_editor.add_row(null, ADD_NEW_FIELD_BUTTON_ROW).add_2D_button([0, 1], 'add new field', COLOR_BLUE, null);

            // Both creating a new entity and editing an existing entity will contain an create/save-changes button.
            this.create_or_save_changes_button = this.wall_entity_editor.add_row(null).add_2D_button([0, 1], 'SET MY TEXT', COLOR_GREEN, this.create_or_save_changes_button_pressed.bind(this));

            // Both creating a new entity and editing an existing entity will contain an delete/cancel button.
            this.cancel_or_delete_button = this.wall_entity_editor.add_row(null).add_2D_button([0, 1], 'SET MY TEXT', COLOR_RED, this.cancel_or_delete_button_pressed.bind(this));

            // Create the entity field creator.
            this.wall_entity_field_creater = new EntityFieldCreator(this);
            this.wall_entity_field_creater.set_display_button(this.add_new_field_button);
        } else {
            this.wall_entity_editor.detach_from_parent();
        }

        // Delete all previously made non-default entity field rows.
        this.wall_entity_editor.set_auto_adjust_height(false);
        var field_rows_to_delete = [];
        for (var key in this.entity_field_rows) {
            if (this.entity_field_rows.hasOwnProperty(key)) {
                if (key !== ENTITY_DEFAULT_PROPERTY_TYPE && key !== ENTITY_PROPERTY_NAME) {
                    field_rows_to_delete.push(key);
                }
            }
        }
        for (var r = 0; r < field_rows_to_delete.length; r++) {
            this.wall_entity_editor.delete_row_by_name(field_rows_to_delete[r]);
            delete this.entity_field_rows[field_rows_to_delete[r]];
        }

        if (edit_mode === EDITOR_MODE_CREATE) {
            this.current_mode = EDITOR_MODE_CREATE;

            this.wall_entity_editor.attach_to(this.create_new_entity_button);
            this.wall_title.update_text('Create New Entity');

            this.entity_field_rows[ENTITY_DEFAULT_PROPERTY_TYPE].set_value_to_default();
            this.entity_field_rows[ENTITY_PROPERTY_NAME].set_value_to_default();

            this.create_or_save_changes_button.update_text('create entity');
            this.cancel_or_delete_button.update_text('cancel');
        } else {

            this.current_mode = EDITOR_MODE_EDIT;

            this.wall_entity_editor.attach_to(this.entity_being_edited_button);

            var entity_being_edited = MANAGER_ENTITY.get_entity_by_id(this.entity_id_being_edited);

            this.wall_title.update_text('Editing : ' + entity_being_edited.get_value(ENTITY_PROPERTY_NAME));

            this.create_or_save_changes_button.update_text('save changes');
            this.cancel_or_delete_button.update_text('delete entity');

            this.entity_field_rows[ENTITY_DEFAULT_PROPERTY_TYPE].set_value_from_entity();
            this.entity_field_rows[ENTITY_PROPERTY_NAME].set_value_from_entity();

            // TODO : Populate all the required entity field rows.
            var all_non_default_editable_fields = entity_being_edited.get_all_non_default_editable_fields();
            // Sort the fields alphabetically.
            all_non_default_editable_fields = all_non_default_editable_fields.sort(function(a, b) {
                return a[0] > b[0];
            });

            for (var f = 0; f < all_non_default_editable_fields.length; f++) {
                this.add_entity_field(all_non_default_editable_fields[f][0], all_non_default_editable_fields[f][1]);
            }
        }

        this.wall_entity_editor.set_auto_adjust_height(true);
        this.wall_entity_editor.auto_adjust_height_if_needed();
        this.wall_entity_editor.force_display_self_and_all_child_attachments_recursively();
        this.base_wall.refresh_position_and_look_at();
    },

    _add_entity_field: function(field_name) {
        if (field_name === ENTITY_PROPERTY_START_DATE_TIME || field_name === ENTITY_PROPERTY_END_DATE_TIME) {
            this.entity_field_rows[field_name] = new FieldRowDateTime(this, field_name);
        } else if (field_name === ENTITY_PROPERTY_COMPLETED) {
            this.entity_field_rows[field_name] = new FieldRowCompleted(this);
        } else {
            this.entity_field_rows[field_name] = new FieldRowRegular(this, field_name);
        }
        return this.entity_field_rows[field_name];
    },

    add_entity_field: function(field_name, field_value) {
        // Check if the field was already added.
        if (!this.wall_entity_editor.has_row_with_name(field_name)) {

            // Get the row index of the 'add new field' button.
            var insert_index_for_row = this.wall_entity_editor.get_row_with_name(ADD_NEW_FIELD_BUTTON_ROW).row_number;

            var new_entity_field = this._add_entity_field(field_name);
            new_entity_field.create(insert_index_for_row, field_value);
        }
    },

    _opened_for_first_time: function() {
        this.entity_field_rows[ENTITY_DEFAULT_PROPERTY_TYPE].hide_extra_elements();
    },

    _hide_self_and_update: function() {
        this.wall_entity_editor.force_hide_self_and_all_child_attachments_recursively();
    },

    /*___      ___   ___         ___  __    ___         __
     |__  |\ |  |  |  |  \ /    |__  |  \ |  |  | |\ | / _`
     |___ | \|  |  |  |   |     |___ |__/ |  |  | | \| \__> */
    edit_entity: function(entity_relative_id, entity_row_button) {
        this.entity_being_edited_button = entity_row_button;
        this.entity_id_being_edited = entity_relative_id;
        this.create(EDITOR_MODE_EDIT);
        this._opened_for_first_time();
    },

    _modify_entity: function() {
        var entity_being_edited = MANAGER_ENTITY.get_entity_by_id(this.entity_id_being_edited);
        var all_entities_fields_and_values = this._get_all_entity_fields_and_values();
        for (var f = 0; f < all_entities_fields_and_values.length; f++) {
            entity_being_edited.set_property(all_entities_fields_and_values[f][0], all_entities_fields_and_values[f][1], true);
            // TODO : Move the location of this?
            this.entity_being_edited_button.update_text(entity_being_edited.get_value(ENTITY_PROPERTY_NAME));
        }
        this._hide_self_and_update();
    },

    /*___      ___   ___         __   __   ___      ___    __
     |__  |\ |  |  |  |  \ /    /  ` |__) |__   /\   |  | /  \ |\ |
     |___ | \|  |  |  |   |     \__, |  \ |___ /~~\  |  | \__/ | \| */
    _entity_created: function() {
        var entity_properties = {};
        var all_entities_fields_and_values = this._get_all_entity_fields_and_values();
        for (var f = 0; f < all_entities_fields_and_values.length; f++) {
            entity_properties[all_entities_fields_and_values[f][0]] = all_entities_fields_and_values[f][1];
        }
        var entity_created = new Entity(entity_properties, true);
        this.entity_event_subscriber.entity_added(entity_created);
        this._hide_self_and_update();
    },

    set_create_entity_display_button: function(button) {
        this.create_new_entity_button = button;
        this.create_new_entity_button.set_engage_function(this._create_new_entity_button_pressed.bind(this));
    },

    _create_new_entity_button_pressed: function() {
        this.create(EDITOR_MODE_CREATE);
        this._opened_for_first_time();
    },

    /*__   ___ ___ ___  ___  __   __
     / _` |__   |   |  |__  |__) /__`
     \__> |___  |   |  |___ |  \ .__/ */
    in_creation_mode: function() {
        if (is_defined(this.current_mode)) {
            return this.current_mode === EDITOR_MODE_CREATE;
        }
        return false;
    },

    in_editing_mode: function() {
        if (is_defined(this.current_mode)) {
            return this.current_mode === EDITOR_MODE_EDIT;
        }
        return false;
    },

    _get_all_entity_fields_and_values: function() {
        var entity_fields_and_values = [];
        for (var key in this.entity_field_rows) {
            if (this.entity_field_rows.hasOwnProperty(key)) {
                if (key.startsWith(ENTITY_PROPERTY_START_TOKEN)) {
                    entity_fields_and_values.push([key, this.entity_field_rows[key].get_value()]);
                }
            }
        }
        return entity_fields_and_values;
    },

    has_field: function(field_name) {
        return this.wall_entity_editor.has_row_with_name(field_name);
    }

};<commit_msg>general pushing<commit_after>/*

no fap

                                 _,..----.._
                               _/  . -.     \_
                              /     \  \      \_
                             /    _  \ _`-.  -. \
                            /  _-'_.  /    \   \ \
                           /  /  /     \-_  \_ /  .
                          /  /  /     / \_\_  '   `.
                         (   `._'    /    \ \_     |
                          \         /      ; |    -.
                          /  /     /       \ |._   |
                         (  / ._.-'         )/ |  ||
                          \`|  ---.  .---. //  ' .'|
                          . \  `-' )  `''  '  /  ' |
                         /  | (   /          // /  '
                         `. |\ \  ._.       // /  /____
                           \|| |\ ____     // '/  /    `-
                            '| \ \`..'  / / .-'  /       \
                             | |  \_  _/ / '( ) |         \
                ___..__      | /    `'  /  `./  \          \
             _-'       `-.   |      /   \   /  / \          .
           _/             `- |  // /   .-  /  /   \         `
          /   _.-           `'.   .-' /     _// /| \_
         /   /        _    )   `./    \ .--'-' / /\_ \       \
        /   /      .-' `-./      |     `-'__.-' /  \\|
       /    |   -\ |      - ._   \  _          '    /'
       |    /  / | |       \  )   -' .-.            \         :
       |   / . | | |   .--.|  /  /  /o |             \        `
       |  / /  | : |   .--.| .  /   \_/               \        \
       / / (   | \ |  `._O'| ! .                       \        .
      // .  `  |  \ \      |.' |                       .        |
      /|  -._  |   \|   )  |   `              /       . \       `
       |     \ |           '  ) \            /        '  .       .
     _/     -._ \  .----. /  /   \._     _.-'        .   \       \
  .-'_-'-,     \ \  `--' /  (     . `---'            '    \       \
 |.-'  _/       \ \     / .-.\  \\ \                /     \        \
 \\   /          ) )-._.'/    `.  \|               |       \  _     )
  \|  /|     _.-'//     /       `-.|               |        -'      |
      |\ \  /    / _.-'/           -.              |        |       |
      |   `-.    \'  .'              \             \        '       '
      \\    `.   |  /                 `.            \      .        '
      /      -  _/                      `.           `.    |        '
      \   _.'  /                          -.          |    |       ,
     / -.     /           _.-               `.        |    |       '
    /    -   _.              `\               -.      `.   |      /
    \ -.   .'                  `._              \      |   !     ,
     |  ._/                       -.             `. .-=\  .'
     |   /._            |           `.             \-'  |.'     /
     |  /,o ;                        |-            _`.--'       ;
     \ .|`.'            |            | `-_      _.'_.          /
     -' |               '            |    `.   (_ .           /
    /   \              /             |      `-_ _' _         /`.
   /     \           .'              |      /(_' _'         .' !
  .       `._     _.'                |     / ( -'_.-'     _.'  |
  (       |  `---'                    \-._'   (._ _.- _.-'      .
  `.      |  \                         \ :F_P:|: `---'  |       !
    \     |   \                         \     ||        |        .
     `.__.|    \                         \`-._/`.       |        !
          |                               \   \ |       |         .
           \                               \_  \|       |         |
            \                            .-' `. `.      |         `

*/
'use strict';

const EDITOR_MODE_CREATE = 1;
const EDITOR_MODE_EDIT   = 2;

const ADD_NEW_FIELD_BUTTON_ROW = 'add_new_field_button';

function EntityEditor(entity_event_subscriber, base_wall) {
    this.__init__(entity_event_subscriber, base_wall);
}

EntityEditor.prototype = {

    __init__: function(entity_event_subscriber, base_wall) {
        this.entity_event_subscriber = entity_event_subscriber;
        this.base_wall = base_wall;
        this.world = this.base_wall.world;
        this.current_mode = null;
    },

    create_or_save_changes_button_pressed: function() {
        if (this.current_mode === EDITOR_MODE_CREATE) {
            this._entity_created();
        } else {
            this._modify_entity();
        }
    },

    cancel_or_delete_button_pressed: function() {
        this.wall_entity_editor.detach_from_parent();
        this.wall_entity_editor.force_hide_self_and_all_child_attachments_recursively();
        if (this.current_mode === EDITOR_MODE_EDIT) {
            MANAGER_ENTITY.delete_entity_by_id(this.entity_id_being_edited);
        }
    },

    delete_entity_field: function(field_name) {
        delete this.entity_field_rows[field_name];
        this.wall_entity_editor.delete_row_by_name(field_name);

        if (this.current_mode === EDITOR_MODE_EDIT) {
            var entity_modify = MANAGER_ENTITY.get_entity_by_id(this.entity_id_being_edited);
            entity_modify.delete_property(field_name, true);
        }
    },

    create: function(edit_mode) {
        if (!is_defined(this.wall_entity_editor)) {
            this.wall_entity_editor = new FloatingWall(600, 400, null, null, this.world, false, COLOR_FLOATING_WALL_SUCCESS);
            this.wall_entity_editor.manual_visibility = true;
            this.wall_entity_editor.set_attachment_depth_offset(10);
            this.wall_entity_editor.add_close_button();

            this.wall_title = this.wall_entity_editor.add_row(-1).add_3D_element('HODL IOTA', TYPE_TITLE);

            this.entity_field_rows = {};

            // Default field : entity type selector.
            this.entity_field_rows[ENTITY_DEFAULT_PROPERTY_TYPE] = new FieldRowEntityType(this);
            this.entity_field_rows[ENTITY_DEFAULT_PROPERTY_TYPE].create(null);

            // Default field : entity name.
            this.entity_field_rows[ENTITY_PROPERTY_NAME] = new FieldRowName(this);
            this.entity_field_rows[ENTITY_PROPERTY_NAME].create(null);

            // Both creating a new entity and editing an existing entity will contain an add a new field button.
            this.add_new_field_button = this.wall_entity_editor.add_row(null, ADD_NEW_FIELD_BUTTON_ROW).add_2D_button([0, 1], 'add new field', COLOR_BLUE, null);

            // Both creating a new entity and editing an existing entity will contain an create/save-changes button.
            this.create_or_save_changes_button = this.wall_entity_editor.add_row(null).add_2D_button([0, 1], 'SET MY TEXT', COLOR_GREEN, this.create_or_save_changes_button_pressed.bind(this));

            // Both creating a new entity and editing an existing entity will contain an delete/cancel button.
            this.cancel_or_delete_button = this.wall_entity_editor.add_row(null).add_2D_button([0, 1], 'SET MY TEXT', COLOR_RED, this.cancel_or_delete_button_pressed.bind(this));

            // Create the entity field creator.
            this.wall_entity_field_creater = new EntityFieldCreator(this);
            this.wall_entity_field_creater.set_display_button(this.add_new_field_button);
        } else {
            this.wall_entity_editor.detach_from_parent();
        }

        // Delete all previously made non-default entity field rows.
        this.wall_entity_editor.set_auto_adjust_height(false);
        var field_rows_to_delete = [];
        for (var key in this.entity_field_rows) {
            if (this.entity_field_rows.hasOwnProperty(key)) {
                if (key !== ENTITY_DEFAULT_PROPERTY_TYPE && key !== ENTITY_PROPERTY_NAME) {
                    field_rows_to_delete.push(key);
                }
            }
        }
        for (var r = 0; r < field_rows_to_delete.length; r++) {
            this.wall_entity_editor.delete_row_by_name(field_rows_to_delete[r]);
            delete this.entity_field_rows[field_rows_to_delete[r]];
        }

        if (edit_mode === EDITOR_MODE_CREATE) {
            this.current_mode = EDITOR_MODE_CREATE;

            this.wall_entity_editor.attach_to(this.create_new_entity_button);
            this.wall_title.update_text('Create New Entity');

            this.entity_field_rows[ENTITY_DEFAULT_PROPERTY_TYPE].set_value_to_default();
            this.entity_field_rows[ENTITY_PROPERTY_NAME].set_value_to_default();

            this.create_or_save_changes_button.update_text('create entity');
            this.cancel_or_delete_button.update_text('cancel');
        } else {

            this.current_mode = EDITOR_MODE_EDIT;

            this.wall_entity_editor.attach_to(this.entity_being_edited_button);

            var entity_being_edited = MANAGER_ENTITY.get_entity_by_id(this.entity_id_being_edited);

            this.wall_title.update_text('Editing : ' + entity_being_edited.get_value(ENTITY_PROPERTY_NAME));

            this.create_or_save_changes_button.update_text('save changes');
            this.cancel_or_delete_button.update_text('delete entity');

            this.entity_field_rows[ENTITY_DEFAULT_PROPERTY_TYPE].set_value_from_entity();
            this.entity_field_rows[ENTITY_PROPERTY_NAME].set_value_from_entity();

            // TODO : Populate all the required entity field rows.
            var all_non_default_editable_fields = entity_being_edited.get_all_non_default_editable_fields();
            // Sort the fields alphabetically.
            all_non_default_editable_fields = all_non_default_editable_fields.sort(function(a, b) {
                return a[0] > b[0];
            });

            for (var f = 0; f < all_non_default_editable_fields.length; f++) {
                this.add_entity_field(all_non_default_editable_fields[f][0], all_non_default_editable_fields[f][1]);
            }
        }

        this.wall_entity_editor.set_auto_adjust_height(true);
        this.wall_entity_editor.auto_adjust_height_if_needed();
        this.wall_entity_editor.force_display_self_and_all_child_attachments_recursively();
        this.base_wall.refresh_position_and_look_at();
    },

    _add_entity_field: function(field_name) {
        if (field_name === ENTITY_PROPERTY_START_DATE_TIME || field_name === ENTITY_PROPERTY_END_DATE_TIME) {
            this.entity_field_rows[field_name] = new FieldRowDateTime(this, field_name);
        } else if (field_name === ENTITY_PROPERTY_COMPLETED) {
            this.entity_field_rows[field_name] = new FieldRowCompleted(this);
        } else {
            this.entity_field_rows[field_name] = new FieldRowRegular(this, field_name);
        }
        return this.entity_field_rows[field_name];
    },

    add_entity_field: function(field_name, field_value) {
        // Check if the field was already added.
        if (!this.wall_entity_editor.has_row_with_name(field_name)) {

            // Get the row index of the 'add new field' button.
            var insert_index_for_row = this.wall_entity_editor.get_row_with_name(ADD_NEW_FIELD_BUTTON_ROW).row_number;

            var new_entity_field = this._add_entity_field(field_name);
            new_entity_field.create(insert_index_for_row, field_value);
        }
    },

    _opened_for_first_time: function() {
        this.entity_field_rows[ENTITY_DEFAULT_PROPERTY_TYPE].hide_extra_elements();
    },

    _hide_self_and_update: function() {
        this.wall_entity_editor.force_hide_self_and_all_child_attachments_recursively();
    },

    /*___      ___   ___         ___  __    ___         __
     |__  |\ |  |  |  |  \ /    |__  |  \ |  |  | |\ | / _`
     |___ | \|  |  |  |   |     |___ |__/ |  |  | | \| \__> */
    edit_entity: function(entity_relative_id, entity_row_button) {
        this.entity_being_edited_button = entity_row_button;
        this.entity_id_being_edited = entity_relative_id;
        this.create(EDITOR_MODE_EDIT);
        this._opened_for_first_time();
    },

    _modify_entity: function() {
        var entity_being_edited = MANAGER_ENTITY.get_entity_by_id(this.entity_id_being_edited);
        var all_entities_fields_and_values = this._get_all_entity_fields_and_values();
        for (var f = 0; f < all_entities_fields_and_values.length; f++) {
            entity_being_edited.set_property(all_entities_fields_and_values[f][0], all_entities_fields_and_values[f][1], true);
            // TODO : Move the location of this?
            this.entity_being_edited_button.update_text(entity_being_edited.get_value(ENTITY_PROPERTY_NAME));
        }
        this._hide_self_and_update();
    },

    /*___      ___   ___         __   __   ___      ___    __
     |__  |\ |  |  |  |  \ /    /  ` |__) |__   /\   |  | /  \ |\ |
     |___ | \|  |  |  |   |     \__, |  \ |___ /~~\  |  | \__/ | \| */
    _entity_created: function() {
        var entity_properties = {};
        var all_entities_fields_and_values = this._get_all_entity_fields_and_values();
        for (var f = 0; f < all_entities_fields_and_values.length; f++) {
            entity_properties[all_entities_fields_and_values[f][0]] = all_entities_fields_and_values[f][1];
        }
        var entity_created = new Entity(entity_properties, true);
        this.entity_event_subscriber.entity_added(entity_created);
        this._hide_self_and_update();
    },

    set_create_entity_display_button: function(button) {
        this.create_new_entity_button = button;
        this.create_new_entity_button.set_engage_function(this._create_new_entity_button_pressed.bind(this));
    },

    _create_new_entity_button_pressed: function() {
        this.create(EDITOR_MODE_CREATE);
        this._opened_for_first_time();
    },

    /*__   ___ ___ ___  ___  __   __
     / _` |__   |   |  |__  |__) /__`
     \__> |___  |   |  |___ |  \ .__/ */
    in_creation_mode: function() {
        if (is_defined(this.current_mode)) {
            return this.current_mode === EDITOR_MODE_CREATE;
        }
        return false;
    },

    in_editing_mode: function() {
        if (is_defined(this.current_mode)) {
            return this.current_mode === EDITOR_MODE_EDIT;
        }
        return false;
    },

    _get_all_entity_fields_and_values: function() {
        var entity_fields_and_values = [];
        for (var key in this.entity_field_rows) {
            if (this.entity_field_rows.hasOwnProperty(key)) {
                if (key.startsWith(ENTITY_PROPERTY_START_TOKEN)) {
                    entity_fields_and_values.push([key, this.entity_field_rows[key].get_value()]);
                }
            }
        }
        return entity_fields_and_values;
    },

    has_field: function(field_name) {
        return this.wall_entity_editor.has_row_with_name(field_name);
    }

};<|endoftext|>


<commit_before>import "../polyfill/dom";
import {isElement} from "./utils";

/**
 * Returns whether the given element is - in fact - an HTMLElement and
 * it matches the optional selector
 *
 * @param {Node|HTMLElement} element
 * @param {?string} selector
 * @return {boolean}
 */
function elementMatches (element, selector)
{
    return isElement(element) && (null === selector || element.matches(selector));
}

/**
 *
 * @param {HTMLElement} element
 * @param {?string} selector
 * @param {string} method
 * @param {boolean} onlyFirst
 * @return {HTMLElement[]|HTMLElement}
 */
function fetchSiblings (element, selector, method, onlyFirst)
{
    let sibling = element[method];
    const list = [];

    while (sibling)
    {
        if (elementMatches(sibling, selector))
        {
            if (onlyFirst)
            {
                return sibling;
            }

            list.push(sibling);
        }

        sibling = element[method];
    }

    return onlyFirst ? null : list;
}

/**
 * Finds all DOM elements matching the selector
 *
 * @param {string} selector
 * @param {Document|HTMLElement} context
 * @return {HTMLElement[]}
 */
export function find (selector, context = document)
{
    return Array.prototype.slice.call(context.querySelectorAll(selector));
}

/**
 * Finds a single DOM node matching the selector
 *
 * @param {string} selector
 * @param {Document|HTMLElement} context
 * @return {?HTMLElement}
 */
export function findOne (selector, context = document)
{
    return context.querySelector(selector);
}

/**
 * Filters a list of DOM elements that match the given selector
 *
 * @param {HTMLElement[]} list
 * @param {string} selector
 * @return {HTMLElement[]}
 */
export function filter (list, selector)
{
    return list.filter(
        (e) => e.matches(selector)
    );
}

/**
 * Filters a list of DOM elements that DO NOT match the given selector
 *
 * @param {HTMLElement[]} list
 * @param {string} selector
 * @return {HTMLElement[]}
 */
export function not (list, selector)
{
    return list.filter(
        (e) => !e.matches(selector)
    );
}

/**
 * Returns all children
 *
 * @param {HTMLElement} parent
 * @param {?string} selector
 * @return {HTMLElement[]}
 */
export function children (parent, selector = null)
{
    const list = [];
    let child = parent.firstChild;

    while (child)
    {
        if (elementMatches(child, selector))
        {
            list.push(child);
        }

        child = child.nextSibling;
    }

    return list;
}

/**
 * Returns the nearest previous sibling matching
 * (optionally matching the given selector)
 *
 * @param {HTMLElement} element
 * @param {?string} selector
 * @return {?HTMLElement}
 */
export function prev (element, selector = null)
{
    return fetchSiblings(element, selector, "previousSibling", true);
}

/**
 * Returns the nearest following sibling
 * (optionally matching the given selector)
 *
 * @param {HTMLElement} element
 * @param {?string} selector
 * @return {?HTMLElement}
 */
export function next (element, selector = null)
{
    return fetchSiblings(element, selector, "nextSibling", true);
}

/**
 * Returns all previous siblings
 * (optionally matching the given selector)
 *
 * The nearest sibling is the first element in the list.
 *
 * @param {HTMLElement} element
 * @param {?string} selector
 * @return {HTMLElement[]}
 */
export function prevAll (element, selector = null)
{
    return fetchSiblings(element, selector, "previousSibling", false);
}

/**
 * Returns all following siblings
 * (optionally matching the given selector)
 *
 * The nearest sibling is the first element in the list.
 *
 * @param {HTMLElement} element
 * @param {?string} selector
 * @return {HTMLElement[]}
 */
export function nextAll (element, selector = null)
{
    return fetchSiblings(element, selector, "nextSibling", false);
}

/**
 * Returns all siblings
 * (optionally matching the given selector)
 *
 * @param {HTMLElement} element
 * @param {?string} selector
 * @return {HTMLElement[]}
 */
export function siblings (element, selector = null)
{
    let sibling = element.parentNode.firstChild;
    const list = [];

    while (sibling)
    {
        if (sibling !== element && elementMatches(sibling, selector))
        {
            list.push(element);
        }

        sibling = element.nextSibling;
    }

    return list;
}

/**
 * Returns the closest parent that matches the selector
 *
 * @param {HTMLElement} element
 * @param {string} selector
 * @return {?HTMLElement}
 */
export function closest (element, selector)
{
    let parent = element.parentNode;

    /** @type {HTMLElement} node */
    while (parent)
    {
        if (parent.matches(selector))
        {
            return parent;
        }

        parent = parent.parentNode;
    }

    return null;
}
<commit_msg>Use correct variable in traverse methods<commit_after>import "../polyfill/dom";
import {isElement} from "./utils";

/**
 * Returns whether the given element is - in fact - an HTMLElement and
 * it matches the optional selector
 *
 * @param {Node|HTMLElement} element
 * @param {?string} selector
 * @return {boolean}
 */
function elementMatches (element, selector)
{
    return isElement(element) && (null === selector || element.matches(selector));
}

/**
 *
 * @param {HTMLElement} element
 * @param {?string} selector
 * @param {string} method
 * @param {boolean} onlyFirst
 * @return {HTMLElement[]|HTMLElement}
 */
function fetchSiblings (element, selector, method, onlyFirst)
{
    let sibling = element[method];
    const list = [];

    while (sibling)
    {
        if (elementMatches(sibling, selector))
        {
            if (onlyFirst)
            {
                return sibling;
            }

            list.push(sibling);
        }

        sibling = sibling[method];
    }

    return onlyFirst ? null : list;
}

/**
 * Finds all DOM elements matching the selector
 *
 * @param {string} selector
 * @param {Document|HTMLElement} context
 * @return {HTMLElement[]}
 */
export function find (selector, context = document)
{
    return Array.prototype.slice.call(context.querySelectorAll(selector));
}

/**
 * Finds a single DOM node matching the selector
 *
 * @param {string} selector
 * @param {Document|HTMLElement} context
 * @return {?HTMLElement}
 */
export function findOne (selector, context = document)
{
    return context.querySelector(selector);
}

/**
 * Filters a list of DOM elements that match the given selector
 *
 * @param {HTMLElement[]} list
 * @param {string} selector
 * @return {HTMLElement[]}
 */
export function filter (list, selector)
{
    return list.filter(
        (e) => e.matches(selector)
    );
}

/**
 * Filters a list of DOM elements that DO NOT match the given selector
 *
 * @param {HTMLElement[]} list
 * @param {string} selector
 * @return {HTMLElement[]}
 */
export function not (list, selector)
{
    return list.filter(
        (e) => !e.matches(selector)
    );
}

/**
 * Returns all children
 *
 * @param {HTMLElement} parent
 * @param {?string} selector
 * @return {HTMLElement[]}
 */
export function children (parent, selector = null)
{
    const list = [];
    let child = parent.firstChild;

    while (child)
    {
        if (elementMatches(child, selector))
        {
            list.push(child);
        }

        child = child.nextSibling;
    }

    return list;
}

/**
 * Returns the nearest previous sibling matching
 * (optionally matching the given selector)
 *
 * @param {HTMLElement} element
 * @param {?string} selector
 * @return {?HTMLElement}
 */
export function prev (element, selector = null)
{
    return fetchSiblings(element, selector, "previousSibling", true);
}

/**
 * Returns the nearest following sibling
 * (optionally matching the given selector)
 *
 * @param {HTMLElement} element
 * @param {?string} selector
 * @return {?HTMLElement}
 */
export function next (element, selector = null)
{
    return fetchSiblings(element, selector, "nextSibling", true);
}

/**
 * Returns all previous siblings
 * (optionally matching the given selector)
 *
 * The nearest sibling is the first element in the list.
 *
 * @param {HTMLElement} element
 * @param {?string} selector
 * @return {HTMLElement[]}
 */
export function prevAll (element, selector = null)
{
    return fetchSiblings(element, selector, "previousSibling", false);
}

/**
 * Returns all following siblings
 * (optionally matching the given selector)
 *
 * The nearest sibling is the first element in the list.
 *
 * @param {HTMLElement} element
 * @param {?string} selector
 * @return {HTMLElement[]}
 */
export function nextAll (element, selector = null)
{
    return fetchSiblings(element, selector, "nextSibling", false);
}

/**
 * Returns all siblings
 * (optionally matching the given selector)
 *
 * @param {HTMLElement} element
 * @param {?string} selector
 * @return {HTMLElement[]}
 */
export function siblings (element, selector = null)
{
    let sibling = element.parentNode.firstChild;
    const list = [];

    while (sibling)
    {
        if (sibling !== element && elementMatches(sibling, selector))
        {
            list.push(element);
        }

        sibling = sibling.nextSibling;
    }

    return list;
}

/**
 * Returns the closest parent that matches the selector
 *
 * @param {HTMLElement} element
 * @param {string} selector
 * @return {?HTMLElement}
 */
export function closest (element, selector)
{
    let parent = element.parentNode;

    /** @type {HTMLElement} node */
    while (parent)
    {
        if (parent.matches(selector))
        {
            return parent;
        }

        parent = parent.parentNode;
    }

    return null;
}
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Authors Simen Brekken @simenbrekken, Einar Löve @einarlove
*/
var DefinePlugin = require("./DefinePlugin");

function EnvironmentPlugin(keys) {
	this.defaultValues = {};

	if (Array.isArray(keys)) {
		this.keys = keys;
	}

	else if (keys === Object(keys)) {
		this.keys = Object.keys(keys);
		this.defaultValues = keys;
	}

	else {
		this.keys = Array.prototype.slice.call(arguments);
	}
}

EnvironmentPlugin.prototype.apply = function(compiler) {
	var definitions = this.keys.reduce(function(defs, key) {
		var value = process.env[key] || this.defaultValues[key];

		if(value === undefined) {
			compiler.plugin("this-compilation", function(compilation) {
				var error = new Error(
					'EnvironmentPlugin - ' + key + ' environment variable is undefined. \033[0m\n\n' +
					'You can pass an object with default values to suppress this warning. \n' +
					'See http://webpack.github.io/docs/list-of-plugins.html#environmentplugin for example.'
				);

				error.name = "EnvVariableNotDefinedError";
				compilation.warnings.push(error);
			});
		}

		defs["process.env." + key] = value ? JSON.stringify(value) : "undefined";

		return defs;
	}.bind(this), {});

	compiler.apply(new DefinePlugin(definitions));
};

module.exports = EnvironmentPlugin;
<commit_msg>Run through beautify<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Authors Simen Brekken @simenbrekken, Einar Löve @einarlove
*/
var DefinePlugin = require("./DefinePlugin");

function EnvironmentPlugin(keys) {
	this.defaultValues = {};

	if(Array.isArray(keys)) {
		this.keys = keys;
	} else if(keys === Object(keys)) {
		this.keys = Object.keys(keys);
		this.defaultValues = keys;
	} else {
		this.keys = Array.prototype.slice.call(arguments);
	}
}

EnvironmentPlugin.prototype.apply = function(compiler) {
	var definitions = this.keys.reduce(function(defs, key) {
		var value = process.env[key] || this.defaultValues[key];

		if(value === undefined) {
			compiler.plugin("this-compilation", function(compilation) {
				var error = new Error(
					'EnvironmentPlugin - ' + key + ' environment variable is undefined. \033[0m\n\n' +
					'You can pass an object with default values to suppress this warning. \n' +
					'See http://webpack.github.io/docs/list-of-plugins.html#environmentplugin for example.'
				);

				error.name = "EnvVariableNotDefinedError";
				compilation.warnings.push(error);
			});
		}

		defs["process.env." + key] = value ? JSON.stringify(value) : "undefined";

		return defs;
	}.bind(this), {});

	compiler.apply(new DefinePlugin(definitions));
};

module.exports = EnvironmentPlugin;
<|endoftext|>


<commit_before>// api/policies/localize.js
module.exports = function(req, res, next) {
  req.setLocale(req.session.languagePreference);
  next();
};<commit_msg>remove localize policy<commit_after><|endoftext|>


<commit_before>const path = require('path')
const electron = require('electron')

const app = electron.app
let tray = null

exports.create = win => {
  if (tray) {
    return
  }

  const iconPath = path.join(__dirname, 'assets/icons/win/icon.ico')

  const toggleWindow = () => {
    if (win.isVisible()) {
      win.hide()
    } else {
      win.show()
    }
  }

  const contextMenu = electron.Menu.buildFromTemplate([
    {
      label: 'Toggle',
      click () {
        toggleWindow()
      }
    },
    {
      type: 'separator'
    },
    {
      role: 'quit'
    }
  ])

  tray = new electron.Tray(iconPath)
  tray.setToolTip(`${app.getName()}`)
  tray.setContextMenu(contextMenu)
  tray.on('click', toggleWindow)
}
<commit_msg>fix: TrayIcon for #6<commit_after>const path = require('path')
const electron = require('electron')

const app = electron.app
let tray = null

exports.create = win => {
  if (tray) {
    return
  }

  const iconPath = path.join(__dirname, 'assets/icons/png/64x64.png')

  const toggleWindow = () => {
    if (win.isVisible()) {
      win.hide()
    } else {
      win.show()
    }
  }

  const contextMenu = electron.Menu.buildFromTemplate([
    {
      label: 'Toggle',
      click () {
        toggleWindow()
      }
    },
    {
      type: 'separator'
    },
    {
      role: 'quit'
    }
  ])

  tray = new electron.Tray(iconPath)
  tray.setToolTip(`${app.getName()}`)
  tray.setContextMenu(contextMenu)
  tray.on('click', toggleWindow)
}
<|endoftext|>