<commit_before>var AbstractVisualization = Fiber.extend(function() {
    return {
        init: function(container, history) {
            this.container = container;
            this.history = history;

            this.renderer = null;
            this.scene = null;
            this.camera = null;
            this.controls = null;
            this.stats = null;

            this.gui = null;
            this.guiIteration = null;

            this.iteration = 0;
            this.lastIteration = this.iteration;

            this.timer = null;
            this.playing = false;

            this.speed = 500;
            this.maxSpeed = 1000;

            this.reshape = false;

            this.snapshot = null;
            this.loadLayersTimeout = null;
            this.loadLayersTimeoutDuration = 500; // default (in ms)

            this._initDrawings();
            this._initControls();
            this._initStats();
            this._initGUI();

            this.historyUpdated();
        },

        /* To Override */

        getInputDrawing: function() {return null;},
        getOutputDrawing: function() {return null;},
        initCamera: function(width, height) {return null;},

        // Events
        iterationChanged: function() {},

        /* Public */
        initRenderer: function() {
            return new THREE.WebGLRenderer();
        },

        render: function() {
            if (this.stats) this.stats.begin();

            this._update();
            this.controls.update();
            this.renderer.render(this.scene, this.camera);

            if (this.stats) this.stats.end();

            requestAnimationFrame(this.render.bind(this));
        },

        historyUpdated: function() {
            var num = this.history.length(),
                guiIteration = this.guiIteration;

            var min = Number(num > 0),
                max = num;

            guiIteration.__min = min;
            guiIteration.__max = max;

            if (guiIteration.getValue() === 0) {
                guiIteration.setValue(min);
            }
        },

        play: function() {
            if (!this.playing) {
                this._enableController('speed');
                this._enableController('pause');
                this._player();
            } else {
                this.pause();
            }
            for (var i = 0; i < this.gui.__controllers.length; i++) {
                if (this.gui.__controllers[i].property === "play") {
                    this.gui.__controllers[i].name( (this.playing) ? "play" : "pause");
                }
            }
            this.playing = !this.playing;
        },

        pause: function() {
            clearTimeout(this.timer);
            this._disableController('speed');
        },

        /* Private */

        _player: function() {
            this.timer = _.delay(function(_this){
                _this.iteration++;
                if(_this.iteration < _this.guiIteration.__max) {
                    _this._player();
                } else {
                    _this.pause();
                }
            }, this._calculateSpeed(),this);
        },

        _calculateSpeed: function() {
            return this.maxSpeed - this.speed;
        },

        _findController: function(controllerName) {
            for (var i = 0; i < this.gui.__controllers.length; i++) {
                var controller = this.gui.__controllers[i];

                if (controller.property === controllerName) {
                    return controller;
                }
            }

            return null;
        },

        _disableController: function(controllerName) {
            var controller = this._findController(controllerName);
            if (!controller) return;

            if($(controller.__li).children(".disabled").length > 0) return;
            $(controller.__li).append("

");
        },

        _enableController: function(controllerName) {
            var controller = this._findController(controllerName);
            if (!controller) return;

            $(controller.__li).children().remove(".disabled");
        },

        _hideController: function(controllerName) {
            var controller = this._findController(controllerName);
            if (!controller) return;

            $(controller.__li).addClass("hidden");
        },

        _initDrawings: function() {
            var container = this.container,
                width = container.width(),
                height = container.height();

            var scene = new THREE.Scene();
            var renderer = this.initRenderer();

            var camera = this.initCamera(width, height);
            scene.add(camera);

            renderer.setSize(width, height);
            this.container.append(renderer.domElement);

            this.renderer = renderer;
            this.camera = camera;
            this.scene = scene;

            var inputDrawing = this.getInputDrawing(scene),
                outputDrawing = this.getOutputDrawing(scene);

            outputDrawing.setInputDrawing(inputDrawing);

            this.inputDrawing = inputDrawing;
            this.outputDrawing = outputDrawing;

            this._watchForResize();
        },

        _watchForResize: function() {
            var renderer = this.renderer,
                camera = this.camera,
                container = this.container;

            $(window).resize(function() {
                var width = container.width(),
                    height = container.height();

                renderer.setSize(width, height);

                camera.aspect = width / height;
                camera.updateProjectionMatrix();
            });
        },

        _initControls: function() {
            var camera = this.camera,
                renderer = this.renderer,
                controls = new THREE.TrackballControls(camera, renderer.domElement);

            controls.rotateSpeed = 1.0;
            controls.zoomSpeed = 1.2;
            controls.panSpeed = 0.8;

            controls.noZoom = false;
            controls.noPan = false;

            controls.staticMoving = true;
            controls.dynamicDampingFactor = 0.3;

            controls.keys = [65, 83, 68];

            this.controls = controls;
        },

        _initStats: function() {
            var stats = new Stats(),
                domElement = $(stats.domElement);

            stats.setMode(0); // 0: fps; 1: ms

            domElement.addClass("stats");
            this.container.append(domElement);

            this.stats = stats;
        },

        _initGUI: function() {
            var gui = new dat.GUI({ autoPlace: false }),
                domElement = $(gui.domElement);

            domElement.addClass("controls");
            this.container.append(domElement);

            this.next = this._nextIteration;
            this.prev = this._prevIteration;

            this.guiIteration = gui.add(this, 'iteration', 0, 0).step(1).listen();
            gui.add(this, 'play');
            gui.add(this, 'speed', 0, this.maxSpeed).step(1);
            gui.add(this, 'next');
            gui.add(this, 'prev');

            var outputDrawing = this.outputDrawing,
                updateCells = _.bind(outputDrawing.updateCells, outputDrawing),
                updateProximalSynapses = _.bind(outputDrawing.updateProximalSynapses, outputDrawing),
                updateDistalSynapses = _.bind(outputDrawing.updateDistalSynapses, outputDrawing),
                reshapeUpdated = _.bind(this._reshapeUpdated , this);

            var viewFolder = gui.addFolder('View');
            viewFolder.add(this.outputDrawing, 'showActiveColumns').onChange(updateCells);
            viewFolder.add(this.outputDrawing, 'showActiveCells').onChange(updateCells);
            viewFolder.add(this.outputDrawing, 'showPredictedCells').onChange(updateCells);
            viewFolder.add(this.outputDrawing, 'showProximalSynapses').onChange(updateProximalSynapses);
            viewFolder.add(this.outputDrawing, 'showDistalSynapses').onChange(updateDistalSynapses);
            viewFolder.add(this, 'reshape').onChange(reshapeUpdated);

            this.gui = gui;

            // disable some controllers
            this._disableController('speed');
        },

        _update: function() {
            if (this.lastIteration != this.iteration) {
                this._iterationUpdated();
                this.iterationChanged(); // fire event
                this.lastIteration = this.iteration;
            }
        },

        _nextIteration: function() {
            this.pause();
            this.iteration = Math.min(this.iteration + 1, this.history.length());
        },

        _prevIteration: function() {
            this.pause();
            this.iteration = Math.max(this.iteration - 1, 0);
        },

        _iterationUpdated: function() {
            var lastSnapshot = this.snapshot,
                snapshot = this.history.getSnapshotAtIndex(this.iteration - 1);

            if (!snapshot) {
                console.log("Invalid iteration index: " + this.iteration);
                console.log("History length: " + this.history.length());
                return;
            }

            this.snapshot = snapshot;

            this._loadLayers();

            var inputDimensions = snapshot.getInputLayer().getDimensions(),
                outputDimensions = snapshot.getOutputLayer().getDimensions(),
                inputDimensionsChanged = true,
                outputDimensionsChanged = true,
                inputDrawing = this.inputDrawing,
                outputDrawing = this.outputDrawing;

            inputDrawing.setLayerDimensions(inputDimensions, this.reshape);
            outputDrawing.setLayerDimensions(outputDimensions, this.reshape);

            if (lastSnapshot) {
                var lastInputDimensions = lastSnapshot.getInputLayer().getDimensions(),
                    lastOutputDimensions = lastSnapshot.getOutputLayer().getDimensions();

                if (_.isEqual(inputDimensions, lastInputDimensions))
                    inputDimensionsChanged = false;

                if (_.isEqual(outputDimensions, lastOutputDimensions))
                    outputDimensionsChanged = false;
            }

            if (inputDimensionsChanged) {
                inputDrawing.clear();
                inputDrawing.setup();
            }
            if (outputDimensionsChanged) {
                outputDrawing.clear();
                outputDrawing.setup();
            }
        },

        _reshapeUpdated: function() {
            var inputDrawing = this.inputDrawing,
                outputDrawing = this.outputDrawing,
                snapshot = this.snapshot,
                inputDimensions = snapshot.getInputLayer().getDimensions(),
                outputDimensions = snapshot.getOutputLayer().getDimensions();

            this._loadLayers();

            inputDrawing.setLayerDimensions(inputDimensions, this.reshape);
            outputDrawing.setLayerDimensions(outputDimensions, this.reshape);

            inputDrawing.clear();
            inputDrawing.setup();

            outputDrawing.clear();
            outputDrawing.setup();
        },

        _loadLayers: function() {
            var self = this,
                snapshot = this.snapshot,
                inputLayer = snapshot.getInputLayer(),
                outputLayer = snapshot.getOutputLayer(),
                inputDrawing = this.inputDrawing,
                outputDrawing = this.outputDrawing,
                timeout = this.loadLayersTimeout,
                timeoutDuration = this.loadLayersTimeoutDuration;

            inputDrawing.reset();
            inputDrawing.updateCells();

            outputDrawing.reset();
            outputDrawing.updateCells();
            outputDrawing.updateProximalSynapses();
            outputDrawing.updateDistalSynapses();

            if (timeout) clearTimeout(timeout);

            timeout = setTimeout(function() {
                inputLayer.getActiveCells(_.bind(function(error, activeCells) {
                    if (self.snapshot != this) return;

                    self.inputDrawing.setActiveCells(activeCells);
                    self.inputDrawing.updateCells();
                }, snapshot));

                outputLayer.getActiveColumns(_.bind(function(error, activeColumns) {
                    if (self.snapshot != this) return;

                    self.outputDrawing.setActiveColumns(activeColumns);
                    self.outputDrawing.updateCells();
                }, snapshot));

                outputLayer.getActiveCells(_.bind(function(error, activeCells) {
                    if (self.snapshot != this) return;

                    self.outputDrawing.setActiveCells(activeCells);
                    self.outputDrawing.updateCells();
                }, snapshot));

                outputLayer.getPredictedCells(_.bind(function(error, predictedCells) {
                    if (self.snapshot != this) return;

                    self.outputDrawing.setPredictedCells(predictedCells);
                    self.outputDrawing.updateCells();
                }, snapshot));

                outputLayer.getProximalSynapses(_.bind(function(error, proximalSynapses) {
                    if (self.snapshot != this) return;

                    self.outputDrawing.setProximalSynapses(proximalSynapses);
                    self.outputDrawing.updateProximalSynapses();
                }, snapshot));

                outputLayer.getDistalSynapses(_.bind(function(error, distalSynapses) {
                    if (self.snapshot != this) return;

                    self.outputDrawing.setDistalSynapses(distalSynapses);
                    self.outputDrawing.updateDistalSynapses();
                }, snapshot));
            }, timeoutDuration);

            this.loadLayersTimeout = timeout;
        }
    };
});
<commit_msg>Addresses chetan51/nupic.cerebro2#23. Fixed problem where play/pause button text was not being updated properly.<commit_after>var AbstractVisualization = Fiber.extend(function() {
    return {
        init: function(container, history) {
            this.container = container;
            this.history = history;

            this.renderer = null;
            this.scene = null;
            this.camera = null;
            this.controls = null;
            this.stats = null;

            this.gui = null;
            this.guiIteration = null;

            this.iteration = 0;
            this.lastIteration = this.iteration;

            this.timer = null;
            this.playing = false;

            this.speed = 500;
            this.maxSpeed = 1000;

            this.reshape = false;

            this.snapshot = null;
            this.loadLayersTimeout = null;
            this.loadLayersTimeoutDuration = 500; // default (in ms)

            this._initDrawings();
            this._initControls();
            this._initStats();
            this._initGUI();

            this.historyUpdated();
        },

        /* To Override */

        getInputDrawing: function() {return null;},
        getOutputDrawing: function() {return null;},
        initCamera: function(width, height) {return null;},

        // Events
        iterationChanged: function() {},

        /* Public */
        initRenderer: function() {
            return new THREE.WebGLRenderer();
        },

        render: function() {
            if (this.stats) this.stats.begin();

            this._update();
            this.controls.update();
            this.renderer.render(this.scene, this.camera);

            if (this.stats) this.stats.end();

            requestAnimationFrame(this.render.bind(this));
        },

        historyUpdated: function() {
            var num = this.history.length(),
                guiIteration = this.guiIteration;

            var min = Number(num > 0),
                max = num;

            guiIteration.__min = min;
            guiIteration.__max = max;

            if (guiIteration.getValue() === 0) {
                guiIteration.setValue(min);
            }
        },

        play: function() {
            if (!this.playing) {
                this._enableController('speed');
                this._enableController('pause');
                this._player();
                this.playing = true;
                this._changeControllerText("play", "pause");
            } else {
                this.pause();
            }
        },

        pause: function() {
            clearTimeout(this.timer);
            this.playing = false;
            this._changeControllerText("play", "play");
            this._disableController('speed');
        },

        /* Private */

        _player: function() {
            this.timer = _.delay(function(_this){
                _this.iteration++;
                if(_this.iteration < _this.guiIteration.__max) {
                    _this._player();
                } else {
                    _this.pause();
                }
            }, this._calculateSpeed(),this);
        },

        _changeControllerText: function(name, label) {
            for (var i = 0; i < this.gui.__controllers.length; i++) {
                if (this.gui.__controllers[i].property === name) {
                    this.gui.__controllers[i].name(label);
                }
            }
        },

        _calculateSpeed: function() {
            return this.maxSpeed - this.speed;
        },

        _findController: function(controllerName) {
            for (var i = 0; i < this.gui.__controllers.length; i++) {
                var controller = this.gui.__controllers[i];

                if (controller.property === controllerName) {
                    return controller;
                }
            }

            return null;
        },

        _disableController: function(controllerName) {
            var controller = this._findController(controllerName);
            if (!controller) return;

            if($(controller.__li).children(".disabled").length > 0) return;
            $(controller.__li).append("

");
        },

        _enableController: function(controllerName) {
            var controller = this._findController(controllerName);
            if (!controller) return;

            $(controller.__li).children().remove(".disabled");
        },

        _hideController: function(controllerName) {
            var controller = this._findController(controllerName);
            if (!controller) return;

            $(controller.__li).addClass("hidden");
        },

        _initDrawings: function() {
            var container = this.container,
                width = container.width(),
                height = container.height();

            var scene = new THREE.Scene();
            var renderer = this.initRenderer();

            var camera = this.initCamera(width, height);
            scene.add(camera);

            renderer.setSize(width, height);
            this.container.append(renderer.domElement);

            this.renderer = renderer;
            this.camera = camera;
            this.scene = scene;

            var inputDrawing = this.getInputDrawing(scene),
                outputDrawing = this.getOutputDrawing(scene);

            outputDrawing.setInputDrawing(inputDrawing);

            this.inputDrawing = inputDrawing;
            this.outputDrawing = outputDrawing;

            this._watchForResize();
        },

        _watchForResize: function() {
            var renderer = this.renderer,
                camera = this.camera,
                container = this.container;

            $(window).resize(function() {
                var width = container.width(),
                    height = container.height();

                renderer.setSize(width, height);

                camera.aspect = width / height;
                camera.updateProjectionMatrix();
            });
        },

        _initControls: function() {
            var camera = this.camera,
                renderer = this.renderer,
                controls = new THREE.TrackballControls(camera, renderer.domElement);

            controls.rotateSpeed = 1.0;
            controls.zoomSpeed = 1.2;
            controls.panSpeed = 0.8;

            controls.noZoom = false;
            controls.noPan = false;

            controls.staticMoving = true;
            controls.dynamicDampingFactor = 0.3;

            controls.keys = [65, 83, 68];

            this.controls = controls;
        },

        _initStats: function() {
            var stats = new Stats(),
                domElement = $(stats.domElement);

            stats.setMode(0); // 0: fps; 1: ms

            domElement.addClass("stats");
            this.container.append(domElement);

            this.stats = stats;
        },

        _initGUI: function() {
            var gui = new dat.GUI({ autoPlace: false }),
                domElement = $(gui.domElement);

            domElement.addClass("controls");
            this.container.append(domElement);

            this.next = this._nextIteration;
            this.prev = this._prevIteration;

            this.guiIteration = gui.add(this, 'iteration', 0, 0).step(1).listen();
            gui.add(this, 'play');
            gui.add(this, 'speed', 0, this.maxSpeed).step(1);
            gui.add(this, 'next');
            gui.add(this, 'prev');

            var outputDrawing = this.outputDrawing,
                updateCells = _.bind(outputDrawing.updateCells, outputDrawing),
                updateProximalSynapses = _.bind(outputDrawing.updateProximalSynapses, outputDrawing),
                updateDistalSynapses = _.bind(outputDrawing.updateDistalSynapses, outputDrawing),
                reshapeUpdated = _.bind(this._reshapeUpdated , this);

            var viewFolder = gui.addFolder('View');
            viewFolder.add(this.outputDrawing, 'showActiveColumns').onChange(updateCells);
            viewFolder.add(this.outputDrawing, 'showActiveCells').onChange(updateCells);
            viewFolder.add(this.outputDrawing, 'showPredictedCells').onChange(updateCells);
            viewFolder.add(this.outputDrawing, 'showProximalSynapses').onChange(updateProximalSynapses);
            viewFolder.add(this.outputDrawing, 'showDistalSynapses').onChange(updateDistalSynapses);
            viewFolder.add(this, 'reshape').onChange(reshapeUpdated);

            this.gui = gui;

            // disable some controllers
            this._disableController('speed');
        },

        _update: function() {
            if (this.lastIteration != this.iteration) {
                this._iterationUpdated();
                this.iterationChanged(); // fire event
                this.lastIteration = this.iteration;
            }
        },

        _nextIteration: function() {
            this.pause();
            this.iteration = Math.min(this.iteration + 1, this.history.length());
        },

        _prevIteration: function() {
            this.pause();
            this.iteration = Math.max(this.iteration - 1, 0);
        },

        _iterationUpdated: function() {
            var lastSnapshot = this.snapshot,
                snapshot = this.history.getSnapshotAtIndex(this.iteration - 1);

            if (!snapshot) {
                console.log("Invalid iteration index: " + this.iteration);
                console.log("History length: " + this.history.length());
                return;
            }

            this.snapshot = snapshot;

            this._loadLayers();

            var inputDimensions = snapshot.getInputLayer().getDimensions(),
                outputDimensions = snapshot.getOutputLayer().getDimensions(),
                inputDimensionsChanged = true,
                outputDimensionsChanged = true,
                inputDrawing = this.inputDrawing,
                outputDrawing = this.outputDrawing;

            inputDrawing.setLayerDimensions(inputDimensions, this.reshape);
            outputDrawing.setLayerDimensions(outputDimensions, this.reshape);

            if (lastSnapshot) {
                var lastInputDimensions = lastSnapshot.getInputLayer().getDimensions(),
                    lastOutputDimensions = lastSnapshot.getOutputLayer().getDimensions();

                if (_.isEqual(inputDimensions, lastInputDimensions))
                    inputDimensionsChanged = false;

                if (_.isEqual(outputDimensions, lastOutputDimensions))
                    outputDimensionsChanged = false;
            }

            if (inputDimensionsChanged) {
                inputDrawing.clear();
                inputDrawing.setup();
            }
            if (outputDimensionsChanged) {
                outputDrawing.clear();
                outputDrawing.setup();
            }
        },

        _reshapeUpdated: function() {
            var inputDrawing = this.inputDrawing,
                outputDrawing = this.outputDrawing,
                snapshot = this.snapshot,
                inputDimensions = snapshot.getInputLayer().getDimensions(),
                outputDimensions = snapshot.getOutputLayer().getDimensions();

            this._loadLayers();

            inputDrawing.setLayerDimensions(inputDimensions, this.reshape);
            outputDrawing.setLayerDimensions(outputDimensions, this.reshape);

            inputDrawing.clear();
            inputDrawing.setup();

            outputDrawing.clear();
            outputDrawing.setup();
        },

        _loadLayers: function() {
            var self = this,
                snapshot = this.snapshot,
                inputLayer = snapshot.getInputLayer(),
                outputLayer = snapshot.getOutputLayer(),
                inputDrawing = this.inputDrawing,
                outputDrawing = this.outputDrawing,
                timeout = this.loadLayersTimeout,
                timeoutDuration = this.loadLayersTimeoutDuration;

            inputDrawing.reset();
            inputDrawing.updateCells();

            outputDrawing.reset();
            outputDrawing.updateCells();
            outputDrawing.updateProximalSynapses();
            outputDrawing.updateDistalSynapses();

            if (timeout) clearTimeout(timeout);

            timeout = setTimeout(function() {
                inputLayer.getActiveCells(_.bind(function(error, activeCells) {
                    if (self.snapshot != this) return;

                    self.inputDrawing.setActiveCells(activeCells);
                    self.inputDrawing.updateCells();
                }, snapshot));

                outputLayer.getActiveColumns(_.bind(function(error, activeColumns) {
                    if (self.snapshot != this) return;

                    self.outputDrawing.setActiveColumns(activeColumns);
                    self.outputDrawing.updateCells();
                }, snapshot));

                outputLayer.getActiveCells(_.bind(function(error, activeCells) {
                    if (self.snapshot != this) return;

                    self.outputDrawing.setActiveCells(activeCells);
                    self.outputDrawing.updateCells();
                }, snapshot));

                outputLayer.getPredictedCells(_.bind(function(error, predictedCells) {
                    if (self.snapshot != this) return;

                    self.outputDrawing.setPredictedCells(predictedCells);
                    self.outputDrawing.updateCells();
                }, snapshot));

                outputLayer.getProximalSynapses(_.bind(function(error, proximalSynapses) {
                    if (self.snapshot != this) return;

                    self.outputDrawing.setProximalSynapses(proximalSynapses);
                    self.outputDrawing.updateProximalSynapses();
                }, snapshot));

                outputLayer.getDistalSynapses(_.bind(function(error, distalSynapses) {
                    if (self.snapshot != this) return;

                    self.outputDrawing.setDistalSynapses(distalSynapses);
                    self.outputDrawing.updateDistalSynapses();
                }, snapshot));
            }, timeoutDuration);

            this.loadLayersTimeout = timeout;
        }
    };
});
<|endoftext|>


<commit_before>function setNetwork(config) {
  if (!("network" in config)) {
    return
  }
  if ("proxyType" in config.network) {
    $("networkProxyType").value = config.network.proxyType;
    selectProxyPanel(config.network.proxyType);
    if (config.network.proxyType == 1) {
      if ("proxySocksVersion" in config.network) {
        $("networkProxySOCKSVersion").value = config.network.proxySocksVersion;
      }
    }
  }
}

function getNetwork(config) {
  if ($("networkProxyType").hasAttribute("value")) {
    if (!("network" in config)) {
      config.network = {};
    }
    config.network.proxyType = parseInt($("networkProxyType").getAttribute("value"), 10);
    if (config.network.proxyType == 1) {
      config.network.proxySocksVersion = parseInt($("networkProxySOCKSVersion").value, 10);
    }
  } else {
    if ($("networkLock").checked) {
      config.network = {"locked": true};
    } else {
      delete(config.network);
    }
  }
  return config;
}

function resetNetwork() {
  $("networkProxyType").selectedIndex = 0;
  selectProxyPanel(0);
}

function onProxyType(event) {
  selectProxyPanel(parseInt(event.target.value, 10));
}

function selectProxyPanel(type) {
  switch (type) {
    case 0:
      $("networkProxyTypeDeck").selectedPanel = $("networkProxyTypeNoProxy");
      break;
    case 1:
      $("networkProxyTypeDeck").selectedPanel = $("networkProxyTypeManual");
      break;
    case 2:
      $("networkProxyTypeDeck").selectedPanel = $("networkProxyTypeAuto");
      break;
    case 4:
      $("networkProxyTypeDeck").selectedPanel = $("networkProxyTypeWPAD");
      break;
    case 5:
      $("networkProxyTypeDeck").selectedPanel = $("networkProxyTypeSystem");
      break;
    default:
      $("networkProxyTypeDeck").selectedIndex = $("networkProxyTypeDontChange");
      break;
  }
}

function chooseProxyConfigURL() {
  var retVals = { url: null};
  window.openDialog("chrome://cck2wizard/content/url-dialog.xul", "cck2wizard-url", "modal,centerscreen", retVals);
  if (retVals.cancel) {
    return;
  }
  var url = retVals.url;
  try {
    Services.io.newURI(url, null, null);
  } catch (ex) {
    showErrorMessage("invalidurl");
    return;
  }
  document.querySelector("textbox[config='network.proxyAutoConfig']").value = url;
  return;
}

function chooseProxyConfigFile() {
  var proxyConfigFile = chooseFile(window);
  if (!proxyConfigFile) {
    return;
  }
  document.querySelector("textbox[config='network.proxyAutoConfig']").value = proxyConfigFile.path;
}

function updateControl(id, disabled) {
  var control = document.getElementById(id);
  control.disabled = disabled;
  var labels = document.getElementsByAttribute("control", id);
  if (labels.length > 0)
    labels[0].disabled = disabled;
}

function updateProtocols(share) {
  var shared = ["networkProxySSL", "networkProxyFTP",
				"networkProxySOCKS"]
  var shared_ports = ["networkProxySSL_Port",
				"networkProxyFTP_Port",
				"networkProxySOCKS_Port"]

  for (i = 0; i < shared.length; i++)
    updateControl(shared[i], share.checked);
  for (i = 0; i < shared_ports.length; i++)
    updateControl(shared_ports[i], share.checked);
  if (share.checked) {
	var ProxyHTTP = document.getElementById("networkProxyHTTP").value;
	var ProxyHTTP_Port = document.getElementById("networkProxyHTTP_Port").value;
    for (i = 0; i < shared.length; i++) {
	  var control = document.getElementById(shared[i]);
	  control.backup = control.value;
	  control.value = ProxyHTTP;
    }
    for (i = 0; i < shared_ports.length; i++) {
	  var control = document.getElementById(shared_ports[i]);
	  control.backup = control.value;
	  control.value = ProxyHTTP_Port;
    }
  } else {
    for (i = 0; i < shared.length; i++) {
	  var control = document.getElementById(shared[i]);
	  if (control.backup) {
  	    control.value = control.backup;
	  } else {
		control.value = "";
	  }
    }
    for (i = 0; i < shared_ports.length; i++) {
	  var control = document.getElementById(shared_ports[i]);
	  if (control.backup) {
  	    control.value = control.backup;
	  } else {
		control.value = 0;
	  }
    }
  }
}<commit_msg>Select correct proxy panel on reset<commit_after>function setNetwork(config) {
  if (!("network" in config)) {
    return
  }
  if ("proxyType" in config.network) {
    $("networkProxyType").value = config.network.proxyType;
    selectProxyPanel(config.network.proxyType);
    if (config.network.proxyType == 1) {
      if ("proxySocksVersion" in config.network) {
        $("networkProxySOCKSVersion").value = config.network.proxySocksVersion;
      }
    }
  }
}

function getNetwork(config) {
  if ($("networkProxyType").hasAttribute("value")) {
    if (!("network" in config)) {
      config.network = {};
    }
    config.network.proxyType = parseInt($("networkProxyType").getAttribute("value"), 10);
    if (config.network.proxyType == 1) {
      config.network.proxySocksVersion = parseInt($("networkProxySOCKSVersion").value, 10);
    }
  } else {
    if ($("networkLock").checked) {
      config.network = {"locked": true};
    } else {
      delete(config.network);
    }
  }
  return config;
}

function resetNetwork() {
  $("networkProxyType").selectedIndex = 0;
  selectProxyPanel();
}

function onProxyType(event) {
  selectProxyPanel(parseInt(event.target.value, 10));
}

function selectProxyPanel(type) {
  switch (type) {
    case 0:
      $("networkProxyTypeDeck").selectedPanel = $("networkProxyTypeNoProxy");
      break;
    case 1:
      $("networkProxyTypeDeck").selectedPanel = $("networkProxyTypeManual");
      break;
    case 2:
      $("networkProxyTypeDeck").selectedPanel = $("networkProxyTypeAuto");
      break;
    case 4:
      $("networkProxyTypeDeck").selectedPanel = $("networkProxyTypeWPAD");
      break;
    case 5:
      $("networkProxyTypeDeck").selectedPanel = $("networkProxyTypeSystem");
      break;
    default:
      $("networkProxyTypeDeck").selectedIndex = $("networkProxyTypeDontChange");
      break;
  }
}

function chooseProxyConfigURL() {
  var retVals = { url: null};
  window.openDialog("chrome://cck2wizard/content/url-dialog.xul", "cck2wizard-url", "modal,centerscreen", retVals);
  if (retVals.cancel) {
    return;
  }
  var url = retVals.url;
  try {
    Services.io.newURI(url, null, null);
  } catch (ex) {
    showErrorMessage("invalidurl");
    return;
  }
  document.querySelector("textbox[config='network.proxyAutoConfig']").value = url;
  return;
}

function chooseProxyConfigFile() {
  var proxyConfigFile = chooseFile(window);
  if (!proxyConfigFile) {
    return;
  }
  document.querySelector("textbox[config='network.proxyAutoConfig']").value = proxyConfigFile.path;
}

function updateControl(id, disabled) {
  var control = document.getElementById(id);
  control.disabled = disabled;
  var labels = document.getElementsByAttribute("control", id);
  if (labels.length > 0)
    labels[0].disabled = disabled;
}

function updateProtocols(share) {
  var shared = ["networkProxySSL", "networkProxyFTP",
				"networkProxySOCKS"]
  var shared_ports = ["networkProxySSL_Port",
				"networkProxyFTP_Port",
				"networkProxySOCKS_Port"]

  for (i = 0; i < shared.length; i++)
    updateControl(shared[i], share.checked);
  for (i = 0; i < shared_ports.length; i++)
    updateControl(shared_ports[i], share.checked);
  if (share.checked) {
	var ProxyHTTP = document.getElementById("networkProxyHTTP").value;
	var ProxyHTTP_Port = document.getElementById("networkProxyHTTP_Port").value;
    for (i = 0; i < shared.length; i++) {
	  var control = document.getElementById(shared[i]);
	  control.backup = control.value;
	  control.value = ProxyHTTP;
    }
    for (i = 0; i < shared_ports.length; i++) {
	  var control = document.getElementById(shared_ports[i]);
	  control.backup = control.value;
	  control.value = ProxyHTTP_Port;
    }
  } else {
    for (i = 0; i < shared.length; i++) {
	  var control = document.getElementById(shared[i]);
	  if (control.backup) {
  	    control.value = control.backup;
	  } else {
		control.value = "";
	  }
    }
    for (i = 0; i < shared_ports.length; i++) {
	  var control = document.getElementById(shared_ports[i]);
	  if (control.backup) {
  	    control.value = control.backup;
	  } else {
		control.value = 0;
	  }
    }
  }
}<|endoftext|>


<commit_before>/*
 * Waltz - Enterprise Architecture
 * Copyright (C) 2016, 2017 Waltz open source project
 * See README.md for more information
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import {initialiseData} from "../../../common/index";
import {CORE_API} from "../../../common/services/core-api-utils";
import _ from "lodash";
import template from "./attestation-section.html";

const initialState = {
    attestations: [],
    createType: null,
};

const bindings = {
    parentEntityRef: "<"
};

function mkAttestationData(attestationRuns = [], attestationInstances = []){
    const runsById = _.keyBy(attestationRuns, "id");

    return _.map(attestationInstances, instance => ({
        "instance": instance,
        "run": runsById[instance.attestationRunId]
    }));
}

function controller($q,
                    serviceBroker,
                    notification) {

    const vm = initialiseData(this, initialState);

    const loadData = () => {

        const runsPromise = serviceBroker
            .loadViewData(CORE_API.AttestationRunStore.findByEntityRef, [vm.parentEntityRef], { force: true })
            .then(r => r.data);

        const instancesPromise = serviceBroker
            .loadViewData(CORE_API.AttestationInstanceStore.findByEntityRef, [vm.parentEntityRef], { force: true })
            .then(r => r.data);

        const sectionInfo = {
            "LOGICAL_DATA_FLOW": {
                name: "Logical Flow - latest attestation",
                attestMessage:  "Attest logical flows"
            },
            "PHYSICAL_FLOW": {
                name: "Physical Flow - latest attestation",
                attestMessage:  "Attest physical flows"
            }
        };

        const sections = [
            {
                type: "LOGICAL_DATA_FLOW",
                name: "Logical Flow - latest attestation",
                attestMessage:  "Attest logical flows"
            },
            {
                type: "PHYSICAL_FLOW",
                name: "Physical Flow - latest attestation",
                attestMessage:  "Attest physical flows"
            }
        ];

        return $q.all([runsPromise, instancesPromise])
            .then(([runs, instances]) => {

                vm.attestations = mkAttestationData(runs, instances);

                const attestationsByKind = _
                    .chain(vm.attestations)
                    .filter(d => d.instance.attestedAt != null)
                    .sortBy(d => d.instance.attestedAt)
                    .groupBy(d => d.run.attestedEntityKind)
                    .value();

                vm.groupedAttestations = _
                    .chain(sections)
                    .map(s => {
                        const latestAttestation = _.findLast(attestationsByKind[s.type]);
                        return {
                            section: s,
                            latestAttestation: latestAttestation
                        };
                    })
                    .value();
            });
    };

    vm.$onInit = () => {
        loadData();
    };

    vm.$onChanges = () => {
        if (vm.parentEntityRef) {
            loadData();
        }
    };

    vm.setCreateType = (type) => vm.createType = type;

    vm.attestEntity = () => {
        if (confirm("By clicking confirm, you are attesting that all data flows are present and correct for this entity, and thereby accountable for this validation.")){
            serviceBroker
                .execute(
                    CORE_API.AttestationRunStore.create, [mkCreateCommand(vm.parentEntityRef, vm.createType)])
                .then(() => loadData())
                .then(() => {
                    vm.entityAttestationInstance = vm.attestations != null
                        ?  _.find(
                            vm.attestations,
                            entityAttestation => entityAttestation.run.name === "Entity Attestation"
                                && entityAttestation.instance.attestedAt == null
                                && entityAttestation.run.attestedEntityKind === vm.createType)
                        : null;
                    return serviceBroker
                        .execute(CORE_API.AttestationInstanceStore.attestInstance, [vm.entityAttestationInstance.instance.id])
                        .then(exec => vm.entityAttestationInstance = null, () => notification.error("Failed to attest flows"))
                        .then(() => {
                            notification.success("Attested successfully");
                            return loadData();
                        });
                })
                .then(() => vm.setCreateType(null));
        }
    };

    vm.cancelAttestation = () => {
        vm.setCreateType(null);
    };
}

function mkCreateCommand(parentEntityRef, entityKind){

    const now = new Date(Date.now());
    const sixMonthsAhead = new Date(now.getFullYear() , now.getMonth() + 6, now.getDate()).toISOString();

    return {
        name: "Entity Attestation",
        description: "Attests that all flows are present and correct for this entity",
        selectionOptions: {
            entityReference: parentEntityRef,
            scope: "EXACT"
        },
        targetEntityKind: "APPLICATION",
        attestedEntityKind: entityKind,
        attestedEntityId: null,
        involvementKindIds: null,
        dueDate: sixMonthsAhead
    };
}

controller.$inject = [
    "$q",
    "ServiceBroker",
    "Notification"
];

const component = {
    bindings,
    template,
    controller
};

export default {
    component,
    id: "waltzAttestationSection",
    controllerAs: "$ctrl"
};

<commit_msg>Rework attestations section - no attestations<commit_after>/*
 * Waltz - Enterprise Architecture
 * Copyright (C) 2016, 2017 Waltz open source project
 * See README.md for more information
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import {initialiseData} from "../../../common/index";
import {CORE_API} from "../../../common/services/core-api-utils";
import _ from "lodash";
import template from "./attestation-section.html";

const initialState = {
    attestations: [],
    createType: null,
};

const bindings = {
    parentEntityRef: "<"
};

function mkAttestationData(attestationRuns = [], attestationInstances = []){
    const runsById = _.keyBy(attestationRuns, "id");

    return _.map(attestationInstances, instance => ({
        "instance": instance,
        "run": runsById[instance.attestationRunId]
    }));
}

function controller($q,
                    serviceBroker,
                    notification) {

    const vm = initialiseData(this, initialState);

    const loadData = () => {

        const runsPromise = serviceBroker
            .loadViewData(CORE_API.AttestationRunStore.findByEntityRef, [vm.parentEntityRef], { force: true })
            .then(r => r.data);

        const instancesPromise = serviceBroker
            .loadViewData(CORE_API.AttestationInstanceStore.findByEntityRef, [vm.parentEntityRef], { force: true })
            .then(r => r.data);

        const sections = [
            {
                type: "LOGICAL_DATA_FLOW",
                name: "Logical Flow - latest attestation",
                attestMessage:  "Attest logical flows"
            },
            {
                type: "PHYSICAL_FLOW",
                name: "Physical Flow - latest attestation",
                attestMessage:  "Attest physical flows"
            }
        ];

        return $q.all([runsPromise, instancesPromise])
            .then(([runs, instances]) => {

                vm.attestations = mkAttestationData(runs, instances);

                const attestationsByKind = _
                    .chain(vm.attestations)
                    .filter(d => d.instance.attestedAt != null)
                    .sortBy(d => d.instance.attestedAt)
                    .groupBy(d => d.run.attestedEntityKind)
                    .value();

                vm.groupedAttestations = _
                    .chain(sections)
                    .map(s => {
                        const latestAttestation = _.findLast(attestationsByKind[s.type]);
                        return {
                            section: s,
                            latestAttestation: latestAttestation
                        };
                    })
                    .value();
            });
    };

    vm.$onInit = () => {
        loadData();
    };

    vm.$onChanges = () => {
        if (vm.parentEntityRef) {
            loadData();
        }
    };

    vm.setCreateType = (type) => vm.createType = type;

    vm.attestEntity = () => {
        if (confirm("By clicking confirm, you are attesting that all data flows are present and correct for this entity, and thereby accountable for this validation.")){
            serviceBroker
                .execute(
                    CORE_API.AttestationRunStore.create, [mkCreateCommand(vm.parentEntityRef, vm.createType)])
                .then(() => loadData())
                .then(() => {
                    vm.entityAttestationInstance = vm.attestations != null
                        ?  _.find(
                            vm.attestations,
                            entityAttestation => entityAttestation.run.name === "Entity Attestation"
                                && entityAttestation.instance.attestedAt == null
                                && entityAttestation.run.attestedEntityKind === vm.createType)
                        : null;
                    return serviceBroker
                        .execute(CORE_API.AttestationInstanceStore.attestInstance, [vm.entityAttestationInstance.instance.id])
                        .then(exec => vm.entityAttestationInstance = null, () => notification.error("Failed to attest flows"))
                        .then(() => {
                            notification.success("Attested successfully");
                            return loadData();
                        });
                })
                .then(() => vm.setCreateType(null));
        }
    };

    vm.cancelAttestation = () => {
        vm.setCreateType(null);
    };
}

function mkCreateCommand(parentEntityRef, entityKind){

    const now = new Date(Date.now());
    const sixMonthsAhead = new Date(now.getFullYear() , now.getMonth() + 6, now.getDate()).toISOString();

    return {
        name: "Entity Attestation",
        description: "Attests that all flows are present and correct for this entity",
        selectionOptions: {
            entityReference: parentEntityRef,
            scope: "EXACT"
        },
        targetEntityKind: "APPLICATION",
        attestedEntityKind: entityKind,
        attestedEntityId: null,
        involvementKindIds: null,
        dueDate: sixMonthsAhead
    };
}

controller.$inject = [
    "$q",
    "ServiceBroker",
    "Notification"
];

const component = {
    bindings,
    template,
    controller
};

export default {
    component,
    id: "waltzAttestationSection",
    controllerAs: "$ctrl"
};

<|endoftext|>


<commit_before>import {productsService} from './products-service';

describe('Products Service Testing', () => {

  let $httpBackend;
  let $http;

  beforeEach(window.inject((_$httpBackend_, _$http_) => {
    $httpBackend = _$httpBackend_;
    $http = _$http_;
  }));

  describe('Products Service Behavior', () => {
    it('should get the product list', (done) => {
      $httpBackend.whenGET('/products.json')
          .respond(200, '{"products": []}');

      let success = function (products) {
        (products).should.be.empty();
        done();
      };
      let failure = function () {
        throw new Error('should not be called');
      };

      let service = productsService($http);
      service.getProducts(success, failure);

      $httpBackend.flush();
    });
    it('should handle http error', (done) => {
      $httpBackend.whenGET('/products.json')
          .respond(404, 'Page Not Found.');

      let success = function () {
        throw new Error('should not be called');
      };
      let failure = function (error, status) {
        (status).should.equal(404);
        (error).should.equal('Page Not Found.');
        done();
      };

      let service = productsService($http);
      service.getProducts(success, failure);

      $httpBackend.flush();
    });
  });
});
<commit_msg>update spec console output<commit_after>import {productsService} from './products-service';

describe('the product service', () => {
  let $httpBackend;
  let $http;

  beforeEach(window.inject((_$httpBackend_, _$http_) => {
    $httpBackend = _$httpBackend_;
    $http = _$http_;
  }));

  describe('calls out over http and', () => {
    it('gets the product list', done => {
      $httpBackend.whenGET('/products.json')
          .respond(200, '{"products": []}');

      let success = products => {
        (products).should.be.empty();
        done();
      };
      let failure = () => {
        throw new Error('should not be called');
      };

      let service = productsService($http);
      service.getProducts(success, failure);

      $httpBackend.flush();
    });

    it('handles http errors', (done) => {
      $httpBackend.whenGET('/products.json')
          .respond(404, 'Page Not Found.');

      let success = () => {
        throw new Error('should not be called');
      };

      let failure = function (error, status) {
        (status).should.equal(404);
        (error).should.equal('Page Not Found.');
        done();
      };

      let service = productsService($http);
      service.getProducts(success, failure);

      $httpBackend.flush();
    });
  });
});
<|endoftext|>


<commit_before>/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import Nvd3ChartVisualization from './visualization-nvd3chart';
import PivotTransformation from '../../tabledata/pivot';

/**
 * Visualize data in pie chart
 */
export default class PiechartVisualization extends Nvd3ChartVisualization {
  constructor(targetEl, config) {
    super(targetEl, config);
    this.pivot = new PivotTransformation(config);
  };

  type() {
    return 'pieChart';
  };

  getTransformation() {
    return this.pivot;
  };

  render(pivot) {
    var d3Data = this.d3DataFromPivot(
      pivot.schema,
      pivot.rows,
      pivot.keys,
      pivot.groups,
      pivot.values,
      true,
      false,
      false);
    var d = d3Data.d3g;
    var d3g = [];
    if (d.length > 0) {
      for (var i = 0; i < d[0].values.length ; i++) {
        var e = d[0].values[i];
        d3g.push({
          label: e.x,
          value: e.y
        });
      }
    }
    super.render({d3g: d3g});
  };

  /**
   * Set new config
   */
  setConfig(config) {
    super.setConfig(config);
    this.pivot.setConfig(config);
  };

  configureChart(chart) {
    chart.x(function(d) { return d.label;})
	 .y(function(d) { return d.value;})
	 .showLabels(false)
	 .showTooltipPercent(true);
  };
}
<commit_msg>[ZEPPELIN-2253] Piechart won't render when column selected as 'key' is changed<commit_after>/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import Nvd3ChartVisualization from './visualization-nvd3chart';
import PivotTransformation from '../../tabledata/pivot';

/**
 * Visualize data in pie chart
 */
export default class PiechartVisualization extends Nvd3ChartVisualization {
  constructor(targetEl, config) {
    super(targetEl, config);
    this.pivot = new PivotTransformation(config);
  };

  type() {
    return 'pieChart';
  };

  getTransformation() {
    return this.pivot;
  };

  render(pivot) {
    // [ZEPPELIN-2253] New chart function will be created each time inside super.render()
    this.chart = null;
    var d3Data = this.d3DataFromPivot(
      pivot.schema,
      pivot.rows,
      pivot.keys,
      pivot.groups,
      pivot.values,
      true,
      false,
      false);
    var d = d3Data.d3g;
    var d3g = [];
    if (d.length > 0) {
      for (var i = 0; i < d[0].values.length ; i++) {
        var e = d[0].values[i];
        d3g.push({
          label: e.x,
          value: e.y
        });
      }
    }
    super.render({d3g: d3g});
  };

  /**
   * Set new config
   */
  setConfig(config) {
    super.setConfig(config);
    this.pivot.setConfig(config);
  };

  configureChart(chart) {
    chart.x(function(d) { return d.label;})
	 .y(function(d) { return d.value;})
	 .showLabels(false)
	 .showTooltipPercent(true);
  };
}
<|endoftext|>


<commit_before>/**
 * Copyright 2019, Google, LLC
 * Licensed under the Apache License, Version 2.0 (the `License`);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an `AS IS` BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* eslint-disable no-warning-comments */

'use strict';

function main(
  projectId = process.env.GCLOUD_PROJECT,
  cloudRegion = 'us-central1',
  datasetId,
  dicomStoreId,
  studyUid
) {
  // [START healthcare_dicomweb_retrieve_study]
  const {google} = require('googleapis');
  const healthcare = google.healthcare('v1beta1');
  const fs = require('fs');
  const util = require('util');
  const writeFile = util.promisify(fs.writeFile);
  const fileName = 'study_file.dcm';

  async function dicomWebRetrieveStudy() {
    const auth = await google.auth.getClient({
      scopes: ['https://www.googleapis.com/auth/cloud-platform'],
    });
    google.options({
      auth,
      headers: {
        Accept: 'multipart/related; type=application/dicom; transfer-syntax=*',
      },
      responseType: 'arraybuffer',
    });

    // TODO(developer): uncomment these lines before running the sample
    // const cloudRegion = 'us-central1';
    // const projectId = 'adjective-noun-123';
    // const datasetId = 'my-dataset';
    // const dicomStoreId = 'my-dicom-store';
    // const studyUid = '1.3.6.1.4.1.5062.55.1.2270943358.716200484.1363785608958.61.0';
    const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/dicomStores/${dicomStoreId}`;
    const dicomWebPath = `studies/${studyUid}`;
    const request = {parent, dicomWebPath};

    const study = await healthcare.projects.locations.datasets.dicomStores.studies.retrieveStudy(
      request
    );

    const fileBytes = Buffer.from(study.data);

    await writeFile(fileName, fileBytes);
    console.log(
      `Retrieved study and saved to ${fileName} in current directory`
    );
  }

  dicomWebRetrieveStudy();
  // [END healthcare_dicomweb_retrieve_study]
}

// node dicomWebRetrieveStudy.js <projectId> <cloudRegion> <datasetId> <dicomStoreId> <studyUid>
main(...process.argv.slice(2));
<commit_msg>Change retrieve study output file to use .multipart (#1452)<commit_after>/**
 * Copyright 2019, Google, LLC
 * Licensed under the Apache License, Version 2.0 (the `License`);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an `AS IS` BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* eslint-disable no-warning-comments */

'use strict';

function main(
  projectId = process.env.GCLOUD_PROJECT,
  cloudRegion = 'us-central1',
  datasetId,
  dicomStoreId,
  studyUid
) {
  // [START healthcare_dicomweb_retrieve_study]
  const {google} = require('googleapis');
  const healthcare = google.healthcare('v1beta1');
  const fs = require('fs');
  const util = require('util');
  const writeFile = util.promisify(fs.writeFile);
  // When specifying the output file, use an extension like ".multipart."
  // Then, parse the downloaded multipart file to get each individual
  // DICOM file.
  const fileName = 'study_file.multipart';

  async function dicomWebRetrieveStudy() {
    const auth = await google.auth.getClient({
      scopes: ['https://www.googleapis.com/auth/cloud-platform'],
    });
    google.options({
      auth,
      headers: {
        Accept: 'multipart/related; type=application/dicom; transfer-syntax=*',
      },
      responseType: 'arraybuffer',
    });

    // TODO(developer): uncomment these lines before running the sample
    // const cloudRegion = 'us-central1';
    // const projectId = 'adjective-noun-123';
    // const datasetId = 'my-dataset';
    // const dicomStoreId = 'my-dicom-store';
    // const studyUid = '1.3.6.1.4.1.5062.55.1.2270943358.716200484.1363785608958.61.0';
    const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/dicomStores/${dicomStoreId}`;
    const dicomWebPath = `studies/${studyUid}`;
    const request = {parent, dicomWebPath};

    const study = await healthcare.projects.locations.datasets.dicomStores.studies.retrieveStudy(
      request
    );

    const fileBytes = Buffer.from(study.data);

    await writeFile(fileName, fileBytes);
    console.log(
      `Retrieved study and saved to ${fileName} in current directory`
    );
  }

  dicomWebRetrieveStudy();
  // [END healthcare_dicomweb_retrieve_study]
}

// node dicomWebRetrieveStudy.js <projectId> <cloudRegion> <datasetId> <dicomStoreId> <studyUid>
main(...process.argv.slice(2));
<|endoftext|>


<commit_before>module.exports = {
  source: {
    uri: 'mssql://dbscout:dbscout17@hsin.csrzizhdewvn.us-east-1.rds.amazonaws.com:1433/jabber?encrypt=true'
  },
  target: {
    filename: 'data.json'
  },
  define: {
    team: {
      name: 'hsin',
      display_name: 'HSIN',
      description: 'Homeland Security Information Network',
      type: 'I',
      allow_open_invite: false
    },
    user: {
      auth_service: 'ldap',
      auth_data: 'username-ldap-field'
    }
  }
}
<commit_msg>checkpoint<commit_after><|endoftext|>


<commit_before>Template.singleHomeActivityStatus.onCreated(function () {
    var instance = this;

    // Get ID of current home
    instance.homeId = instance.data.home._id;

    // Add variable to hold activity counts
    instance.activityLevelCounts = new ReactiveVar();

    instance.autorun(function () {
      // Get count of home current residents
      instance.homeCurrentResidentsCount = ReactiveMethod.call("getHomeCurrentResidentCount", instance.homeId);

      // Retrieve home resident activity level counts from server
      const activityLevelCounts = ReactiveMethod.call("getHomeActivityLevelCounts", instance.homeId);

      // Make sure activity level counts exist
      if (activityLevelCounts && instance.homeCurrentResidentsCount) {
        /*
        Re-structure activity level counts data to an object containing:
        type: the type of activity level (inactive, semiActive, active)
        count: the number of residents with a given activity level
        homePercentage: percengage of home residents with the activity level
        */
        const activityLevelTypes = _.keys(activityLevelCounts);

        const activityLevelData = _.map(activityLevelTypes, function (type) {
          // Calculate the percentage of home residents in activity level class
          const homePercentage = activityLevelCounts[type] / instance.homeCurrentResidentsCount;

          // Construct an object with the type and count keys
          const activityLevelCountObject = {
            // Activity level class (inactive, semi-active, active)
            type: type,
            // Number of residents in activity class
            count: activityLevelCounts[type],
            // Percentage of home residents fallint into activity level class
            homePercentage: homePercentage
          };

          return activityLevelCountObject;
        });

        // Update the reactive variable, to trigger the graph to render
        instance.activityLevelCounts.set(activityLevelData);
      }
    });
  });

Template.singleHomeActivityStatus.onRendered(function () {
  // Get reference to template instance
  const instance = this;

  // Get home ID
  const homeId = instance.homeId;

  /*
  Set up chart
  */

  // Set up ID string for chart element
  const svgId = `#activityLevelCountsChart-${homeId}`;

  // Get reference to chart element
  const svg = dimple.newSvg(svgId, "100%", 50);

  // Initialize chart with empty data array
  const activityLevelsChart = new dimple.chart(svg, []);

  // Set chart boundaries
  activityLevelsChart.setBounds(10, 0, "90%", "65%");

  // Add home resident percentage to x axis
  const xAxis = activityLevelsChart.addMeasureAxis("x", "homePercentage");

  // Format x axis as percentage
  // Note: both chart.addPctAxis and axis.showPercentage caused d3 NaN errors
  xAxis.tickFormat = "%";

  // Set x axis max to 100% for easy cross-comparison
  xAxis.overrideMax = 1;

  // Remove x axis grid lines
  xAxis.showGridlines = false;

  // Add activity level type to y axis
  const yAxis = activityLevelsChart.addCategoryAxis("y", "type");

  // Hide the y axis labels
  yAxis.hidden = true;

  // Sort the y axis activity levels
  yAxis.addOrderRule(["active", "semiActive", "inactive"]);

  // Define bar chart series
  activityLevelsChart.addSeries(null, dimple.plot.bar);

  instance.autorun(function () {
    // Get activity level counts
    const activityLevelCounts = instance.activityLevelCounts.get();

    if (activityLevelCounts) {
      // Add activity level data to chart
      activityLevelsChart.data = activityLevelCounts;

      // Draw the chart
      activityLevelsChart.draw(1000);

      // Remove axis titles
      xAxis.titleShape.remove();
      yAxis.titleShape.remove();
    }
  });
});
<commit_msg>Fix error when trying to remove non-existant axis<commit_after>Template.singleHomeActivityStatus.onCreated(function () {
    var instance = this;

    // Get ID of current home
    instance.homeId = instance.data.home._id;

    // Add variable to hold activity counts
    instance.activityLevelCounts = new ReactiveVar();

    instance.autorun(function () {
      // Get count of home current residents
      instance.homeCurrentResidentsCount = ReactiveMethod.call("getHomeCurrentResidentCount", instance.homeId);

      // Retrieve home resident activity level counts from server
      const activityLevelCounts = ReactiveMethod.call("getHomeActivityLevelCounts", instance.homeId);

      // Make sure activity level counts exist
      if (activityLevelCounts && instance.homeCurrentResidentsCount) {
        /*
        Re-structure activity level counts data to an object containing:
        type: the type of activity level (inactive, semiActive, active)
        count: the number of residents with a given activity level
        homePercentage: percengage of home residents with the activity level
        */
        const activityLevelTypes = _.keys(activityLevelCounts);

        const activityLevelData = _.map(activityLevelTypes, function (type) {
          // Calculate the percentage of home residents in activity level class
          const homePercentage = activityLevelCounts[type] / instance.homeCurrentResidentsCount;

          // Construct an object with the type and count keys
          const activityLevelCountObject = {
            // Activity level class (inactive, semi-active, active)
            type: type,
            // Number of residents in activity class
            count: activityLevelCounts[type],
            // Percentage of home residents fallint into activity level class
            homePercentage: homePercentage
          };

          return activityLevelCountObject;
        });

        // Update the reactive variable, to trigger the graph to render
        instance.activityLevelCounts.set(activityLevelData);
      }
    });
  });

Template.singleHomeActivityStatus.onRendered(function () {
  // Get reference to template instance
  const instance = this;

  // Get home ID
  const homeId = instance.homeId;

  /*
  Set up chart
  */

  // Set up ID string for chart element
  const svgId = `#activityLevelCountsChart-${homeId}`;

  // Get reference to chart element
  const svg = dimple.newSvg(svgId, "100%", 50);

  // Initialize chart with empty data array
  const activityLevelsChart = new dimple.chart(svg, []);

  // Set chart boundaries
  activityLevelsChart.setBounds(10, 0, "90%", "65%");

  // Add home resident percentage to x axis
  const xAxis = activityLevelsChart.addMeasureAxis("x", "homePercentage");

  // Format x axis as percentage
  // Note: both chart.addPctAxis and axis.showPercentage caused d3 NaN errors
  xAxis.tickFormat = "%";

  // Set x axis max to 100% for easy cross-comparison
  xAxis.overrideMax = 1;

  // Remove x axis grid lines
  xAxis.showGridlines = false;

  // Add activity level type to y axis
  const yAxis = activityLevelsChart.addCategoryAxis("y", "type");

  // Hide the y axis labels
  yAxis.hidden = true;

  // Sort the y axis activity levels
  yAxis.addOrderRule(["active", "semiActive", "inactive"]);

  // Define bar chart series
  activityLevelsChart.addSeries(null, dimple.plot.bar);

  instance.autorun(function () {
    // Get activity level counts
    const activityLevelCounts = instance.activityLevelCounts.get();

    if (activityLevelCounts) {
      // Add activity level data to chart
      activityLevelsChart.data = activityLevelCounts;

      // Draw the chart
      activityLevelsChart.draw(1000);

      // Remove x axis title
      xAxis.titleShape.remove();
    }
  });
});
<|endoftext|>


<commit_before>import { mapBy, not } from '@ember/object/computed';
import { DeprecatedEvented } from '@ember-data/store/-private';
import ArrayProxy from '@ember/array/proxy';
import { get, computed } from '@ember/object';
import { makeArray, A } from '@ember/array';
import { DEBUG } from '@glimmer/env';

/**
  @module @ember-data/store
*/

/**
  Holds validation errors for a given record, organized by attribute names.

  Every `Model` has an `errors` property that is an instance of
  `Errors`. This can be used to display validation error
  messages returned from the server when a `record.save()` rejects.

  For Example, if you had a `User` model that looked like this:

  ```app/models/user.js
  import Model, { attr } from '@ember-data/model';

  export default Model.extend({
    username: attr('string'),
    email: attr('string')
  });
  ```
  And you attempted to save a record that did not validate on the backend:

  ```javascript
  let user = store.createRecord('user', {
    username: 'tomster',
    email: 'invalidEmail'
  });
  user.save();
  ```

  Your backend would be expected to return an error response that described
  the problem, so that error messages can be generated on the app.

  API responses will be translated into instances of `Errors` differently,
  depending on the specific combination of adapter and serializer used. You
  may want to check the documentation or the source code of the libraries
  that you are using, to know how they expect errors to be communicated.

  Errors can be displayed to the user by accessing their property name
  to get an array of all the error objects for that property. Each
  error object is a JavaScript object with two keys:

  - `message` A string containing the error message from the backend
  - `attribute` The name of the property associated with this error message

  ```handlebars
  <label>Username: {{input value=username}} </label>
  {{#each model.errors.username as |error|}}
    <div class="error">
      {{error.message}}
    </div>
  {{/each}}

  <label>Email: {{input value=email}} </label>
  {{#each model.errors.email as |error|}}
    <div class="error">
      {{error.message}}
    </div>
  {{/each}}
  ```

  You can also access the special `messages` property on the error
  object to get an array of all the error strings.

  ```handlebars
  {{#each model.errors.messages as |message|}}
    <div class="error">
      {{message}}
    </div>
  {{/each}}
  ```

  @class Errors
  @extends Ember.ArrayProxy
  @uses Ember.Evented
 */
export default ArrayProxy.extend(DeprecatedEvented, {
  /**
    Register with target handler

    @method _registerHandlers
    @private
  */
  _registerHandlers(becameInvalid, becameValid) {
    this._registeredHandlers = {
      becameInvalid,
      becameValid,
    };
  },

  /**
    @property errorsByAttributeName
    @type {MapWithDefault}
    @private
  */
  errorsByAttributeName: computed(function() {
    return new Map();
  }),

  /**
    Returns errors for a given attribute

    ```javascript
    let user = store.createRecord('user', {
      username: 'tomster',
      email: 'invalidEmail'
    });
    user.save().catch(function(){
      user.get('errors').errorsFor('email'); // returns:
      // [{attribute: "email", message: "Doesn't look like a valid email."}]
    });
    ```

    @method errorsFor
    @param {String} attribute
    @return {Array}
  */
  errorsFor(attribute) {
    let map = get(this, 'errorsByAttributeName');

    if (!map.has(attribute)) {
      map.set(attribute, A());
    }

    return map.get(attribute);
  },

  /**
    An array containing all of the error messages for this
    record. This is useful for displaying all errors to the user.

    ```handlebars
    {{#each model.errors.messages as |message|}}
      <div class="error">
        {{message}}
      </div>
    {{/each}}
    ```

    @property messages
    @type {Array}
  */
  messages: mapBy('content', 'message'),

  /**
    @property content
    @type {Array}
    @private
  */
  content: computed(function() {
    return A();
  }),

  /**
    @method unknownProperty
    @private
  */
  unknownProperty(attribute) {
    let errors = this.errorsFor(attribute);
    if (errors.length === 0) {
      return undefined;
    }
    return errors;
  },

  /**
    Total number of errors.

    @property length
    @type {Number}
    @readOnly
  */

  /**
    @property isEmpty
    @type {Boolean}
    @readOnly
  */
  isEmpty: not('length').readOnly(),

  /**
   Manually adds errors to the record. This will triger the `becameInvalid` event/ lifecycle method on
    the record and transition the record into an `invalid` state.

   Example
   ```javascript
    let errors = get(user, 'errors');

    // add multiple errors
    errors.add('password', [
      'Must be at least 12 characters',
      'Must contain at least one symbol',
      'Cannot contain your name'
    ]);

    errors.errorsFor('password');
    // =>
    // [
    //   { attribute: 'password', message: 'Must be at least 12 characters' },
    //   { attribute: 'password', message: 'Must contain at least one symbol' },
    //   { attribute: 'password', message: 'Cannot contain your name' },
    // ]

    // add a single error
    errors.add('username', 'This field is required');

    errors.errorsFor('password');
    // =>
    // [
    //   { attribute: 'username', message: 'This field is required' },
    // ]
   ```
  @method add
  @param {string} attribute - the property name of an attribute or relationship
  @param {string[]|string} messages - an error message or array of error messages for the attribute
   */
  add(attribute, messages) {
    let wasEmpty = get(this, 'isEmpty');

    this._add(attribute, messages);

    if (wasEmpty && !get(this, 'isEmpty')) {
      this._registeredHandlers && this._registeredHandlers.becameInvalid();
      if (DEBUG && this._has('becameInvalid')) {
        this.trigger('becameInvalid');
      }
    }
  },

  /**
    Adds error messages to a given attribute without sending event.

    @method _add
    @private
  */
  _add(attribute, messages) {
    messages = this._findOrCreateMessages(attribute, messages);
    this.addObjects(messages);

    this.errorsFor(attribute).addObjects(messages);

    this.notifyPropertyChange(attribute);
  },

  /**
    @method _findOrCreateMessages
    @private
  */
  _findOrCreateMessages(attribute, messages) {
    let errors = this.errorsFor(attribute);
    let messagesArray = makeArray(messages);
    let _messages = new Array(messagesArray.length);

    for (let i = 0; i < messagesArray.length; i++) {
      let message = messagesArray[i];
      let err = errors.findBy('message', message);
      if (err) {
        _messages[i] = err;
      } else {
        _messages[i] = {
          attribute: attribute,
          message: message,
        };
      }
    }

    return _messages;
  },

  /**
   Manually removes all errors for a given member from the record.
     This will transition the record into a `valid` state, and
    triggers the `becameValid` event and lifecycle method.

   Example:

   ```javascript
    let errors = get('user', errors);
    errors.add('phone', ['error-1', 'error-2']);

    errors.errorsFor('phone');
    // =>
    // [
    //   { attribute: 'phone', message: 'error-1' },
    //   { attribute: 'phone', message: 'error-2' },
    // ]

    errors.remove('phone');

    errors.errorsFor('phone');
    // => undefined
   ```
   @method remove
   @param {string} member - the property name of an attribute or relationship
   */
  remove(attribute) {
    if (get(this, 'isEmpty')) {
      return;
    }

    this._remove(attribute);

    if (get(this, 'isEmpty')) {
      this._registeredHandlers && this._registeredHandlers.becameValid();
      if (DEBUG && this._has('becameValid')) {
        this.trigger('becameValid');
      }
    }
  },

  /**
    Removes all error messages from the given attribute without sending event.

    @method _remove
    @private
  */
  _remove(attribute) {
    if (get(this, 'isEmpty')) {
      return;
    }

    let content = this.rejectBy('attribute', attribute);
    get(this, 'content').setObjects(content);
    get(this, 'errorsByAttributeName').delete(attribute);

    this.notifyPropertyChange(attribute);
    this.notifyPropertyChange('length');
  },

  /**
   Manually clears all errors for the record.
     This will transition the record into a `valid` state, and
     will trigger the `becameValid` event and lifecycle method.

  Example:

   ```javascript
   let errors = get('user', errors);
   errors.add('username', ['error-a']);
   errors.add('phone', ['error-1', 'error-2']);

   errors.errorsFor('username');
   // =>
   // [
   //   { attribute: 'username', message: 'error-a' },
   // ]

   errors.errorsFor('phone');
   // =>
   // [
   //   { attribute: 'phone', message: 'error-1' },
   //   { attribute: 'phone', message: 'error-2' },
   // ]

   errors.clear();

   errors.errorsFor('username');
   // => undefined

   errors.errorsFor('phone');
   // => undefined

   errors.get('messages')
   // => []
   ```
   @method remove
   */
  clear() {
    if (get(this, 'isEmpty')) {
      return;
    }

    this._clear();
    this._registeredHandlers && this._registeredHandlers.becameValid();
    if (DEBUG && this._has('becameValid')) {
      this.trigger('becameValid');
    }
  },

  /**
    Removes all error messages.
    to the record.

    @method _clear
    @private
  */
  _clear() {
    if (get(this, 'isEmpty')) {
      return;
    }

    let errorsByAttributeName = get(this, 'errorsByAttributeName');
    let attributes = [];

    errorsByAttributeName.forEach(function(_, attribute) {
      attributes.push(attribute);
    });

    errorsByAttributeName.clear();
    attributes.forEach(attribute => {
      this.notifyPropertyChange(attribute);
    });

    ArrayProxy.prototype.clear.call(this);
  },

  /**
    Checks if there are error messages for the given attribute.

    ```app/routes/user/edit.js
    import Route from '@ember/routing/route';

    export default Route.extend({
      actions: {
        save: function(user) {
          if (user.get('errors').has('email')) {
            return alert('Please update your email before attempting to save.');
          }
          user.save();
        }
      }
    });
    ```

    @method has
    @param {String} attribute
    @return {Boolean} true if there some errors on given attribute
  */
  has(attribute) {
    return this.errorsFor(attribute).length > 0;
  },
});
<commit_msg>[DOC] Fix typo (#6741)<commit_after>import { mapBy, not } from '@ember/object/computed';
import { DeprecatedEvented } from '@ember-data/store/-private';
import ArrayProxy from '@ember/array/proxy';
import { get, computed } from '@ember/object';
import { makeArray, A } from '@ember/array';
import { DEBUG } from '@glimmer/env';

/**
  @module @ember-data/store
*/

/**
  Holds validation errors for a given record, organized by attribute names.

  Every `Model` has an `errors` property that is an instance of
  `Errors`. This can be used to display validation error
  messages returned from the server when a `record.save()` rejects.

  For Example, if you had a `User` model that looked like this:

  ```app/models/user.js
  import Model, { attr } from '@ember-data/model';

  export default Model.extend({
    username: attr('string'),
    email: attr('string')
  });
  ```
  And you attempted to save a record that did not validate on the backend:

  ```javascript
  let user = store.createRecord('user', {
    username: 'tomster',
    email: 'invalidEmail'
  });
  user.save();
  ```

  Your backend would be expected to return an error response that described
  the problem, so that error messages can be generated on the app.

  API responses will be translated into instances of `Errors` differently,
  depending on the specific combination of adapter and serializer used. You
  may want to check the documentation or the source code of the libraries
  that you are using, to know how they expect errors to be communicated.

  Errors can be displayed to the user by accessing their property name
  to get an array of all the error objects for that property. Each
  error object is a JavaScript object with two keys:

  - `message` A string containing the error message from the backend
  - `attribute` The name of the property associated with this error message

  ```handlebars
  <label>Username: {{input value=username}} </label>
  {{#each model.errors.username as |error|}}
    <div class="error">
      {{error.message}}
    </div>
  {{/each}}

  <label>Email: {{input value=email}} </label>
  {{#each model.errors.email as |error|}}
    <div class="error">
      {{error.message}}
    </div>
  {{/each}}
  ```

  You can also access the special `messages` property on the error
  object to get an array of all the error strings.

  ```handlebars
  {{#each model.errors.messages as |message|}}
    <div class="error">
      {{message}}
    </div>
  {{/each}}
  ```

  @class Errors
  @extends Ember.ArrayProxy
  @uses Ember.Evented
 */
export default ArrayProxy.extend(DeprecatedEvented, {
  /**
    Register with target handler

    @method _registerHandlers
    @private
  */
  _registerHandlers(becameInvalid, becameValid) {
    this._registeredHandlers = {
      becameInvalid,
      becameValid,
    };
  },

  /**
    @property errorsByAttributeName
    @type {MapWithDefault}
    @private
  */
  errorsByAttributeName: computed(function() {
    return new Map();
  }),

  /**
    Returns errors for a given attribute

    ```javascript
    let user = store.createRecord('user', {
      username: 'tomster',
      email: 'invalidEmail'
    });
    user.save().catch(function(){
      user.get('errors').errorsFor('email'); // returns:
      // [{attribute: "email", message: "Doesn't look like a valid email."}]
    });
    ```

    @method errorsFor
    @param {String} attribute
    @return {Array}
  */
  errorsFor(attribute) {
    let map = get(this, 'errorsByAttributeName');

    if (!map.has(attribute)) {
      map.set(attribute, A());
    }

    return map.get(attribute);
  },

  /**
    An array containing all of the error messages for this
    record. This is useful for displaying all errors to the user.

    ```handlebars
    {{#each model.errors.messages as |message|}}
      <div class="error">
        {{message}}
      </div>
    {{/each}}
    ```

    @property messages
    @type {Array}
  */
  messages: mapBy('content', 'message'),

  /**
    @property content
    @type {Array}
    @private
  */
  content: computed(function() {
    return A();
  }),

  /**
    @method unknownProperty
    @private
  */
  unknownProperty(attribute) {
    let errors = this.errorsFor(attribute);
    if (errors.length === 0) {
      return undefined;
    }
    return errors;
  },

  /**
    Total number of errors.

    @property length
    @type {Number}
    @readOnly
  */

  /**
    @property isEmpty
    @type {Boolean}
    @readOnly
  */
  isEmpty: not('length').readOnly(),

  /**
   Manually adds errors to the record. This will trigger the `becameInvalid` event/ lifecycle method on
    the record and transition the record into an `invalid` state.

   Example
   ```javascript
    let errors = get(user, 'errors');

    // add multiple errors
    errors.add('password', [
      'Must be at least 12 characters',
      'Must contain at least one symbol',
      'Cannot contain your name'
    ]);

    errors.errorsFor('password');
    // =>
    // [
    //   { attribute: 'password', message: 'Must be at least 12 characters' },
    //   { attribute: 'password', message: 'Must contain at least one symbol' },
    //   { attribute: 'password', message: 'Cannot contain your name' },
    // ]

    // add a single error
    errors.add('username', 'This field is required');

    errors.errorsFor('password');
    // =>
    // [
    //   { attribute: 'username', message: 'This field is required' },
    // ]
   ```
  @method add
  @param {string} attribute - the property name of an attribute or relationship
  @param {string[]|string} messages - an error message or array of error messages for the attribute
   */
  add(attribute, messages) {
    let wasEmpty = get(this, 'isEmpty');

    this._add(attribute, messages);

    if (wasEmpty && !get(this, 'isEmpty')) {
      this._registeredHandlers && this._registeredHandlers.becameInvalid();
      if (DEBUG && this._has('becameInvalid')) {
        this.trigger('becameInvalid');
      }
    }
  },

  /**
    Adds error messages to a given attribute without sending event.

    @method _add
    @private
  */
  _add(attribute, messages) {
    messages = this._findOrCreateMessages(attribute, messages);
    this.addObjects(messages);

    this.errorsFor(attribute).addObjects(messages);

    this.notifyPropertyChange(attribute);
  },

  /**
    @method _findOrCreateMessages
    @private
  */
  _findOrCreateMessages(attribute, messages) {
    let errors = this.errorsFor(attribute);
    let messagesArray = makeArray(messages);
    let _messages = new Array(messagesArray.length);

    for (let i = 0; i < messagesArray.length; i++) {
      let message = messagesArray[i];
      let err = errors.findBy('message', message);
      if (err) {
        _messages[i] = err;
      } else {
        _messages[i] = {
          attribute: attribute,
          message: message,
        };
      }
    }

    return _messages;
  },

  /**
   Manually removes all errors for a given member from the record.
     This will transition the record into a `valid` state, and
    triggers the `becameValid` event and lifecycle method.

   Example:

   ```javascript
    let errors = get('user', errors);
    errors.add('phone', ['error-1', 'error-2']);

    errors.errorsFor('phone');
    // =>
    // [
    //   { attribute: 'phone', message: 'error-1' },
    //   { attribute: 'phone', message: 'error-2' },
    // ]

    errors.remove('phone');

    errors.errorsFor('phone');
    // => undefined
   ```
   @method remove
   @param {string} member - the property name of an attribute or relationship
   */
  remove(attribute) {
    if (get(this, 'isEmpty')) {
      return;
    }

    this._remove(attribute);

    if (get(this, 'isEmpty')) {
      this._registeredHandlers && this._registeredHandlers.becameValid();
      if (DEBUG && this._has('becameValid')) {
        this.trigger('becameValid');
      }
    }
  },

  /**
    Removes all error messages from the given attribute without sending event.

    @method _remove
    @private
  */
  _remove(attribute) {
    if (get(this, 'isEmpty')) {
      return;
    }

    let content = this.rejectBy('attribute', attribute);
    get(this, 'content').setObjects(content);
    get(this, 'errorsByAttributeName').delete(attribute);

    this.notifyPropertyChange(attribute);
    this.notifyPropertyChange('length');
  },

  /**
   Manually clears all errors for the record.
     This will transition the record into a `valid` state, and
     will trigger the `becameValid` event and lifecycle method.

  Example:

   ```javascript
   let errors = get('user', errors);
   errors.add('username', ['error-a']);
   errors.add('phone', ['error-1', 'error-2']);

   errors.errorsFor('username');
   // =>
   // [
   //   { attribute: 'username', message: 'error-a' },
   // ]

   errors.errorsFor('phone');
   // =>
   // [
   //   { attribute: 'phone', message: 'error-1' },
   //   { attribute: 'phone', message: 'error-2' },
   // ]

   errors.clear();

   errors.errorsFor('username');
   // => undefined

   errors.errorsFor('phone');
   // => undefined

   errors.get('messages')
   // => []
   ```
   @method remove
   */
  clear() {
    if (get(this, 'isEmpty')) {
      return;
    }

    this._clear();
    this._registeredHandlers && this._registeredHandlers.becameValid();
    if (DEBUG && this._has('becameValid')) {
      this.trigger('becameValid');
    }
  },

  /**
    Removes all error messages.
    to the record.

    @method _clear
    @private
  */
  _clear() {
    if (get(this, 'isEmpty')) {
      return;
    }

    let errorsByAttributeName = get(this, 'errorsByAttributeName');
    let attributes = [];

    errorsByAttributeName.forEach(function(_, attribute) {
      attributes.push(attribute);
    });

    errorsByAttributeName.clear();
    attributes.forEach(attribute => {
      this.notifyPropertyChange(attribute);
    });

    ArrayProxy.prototype.clear.call(this);
  },

  /**
    Checks if there are error messages for the given attribute.

    ```app/routes/user/edit.js
    import Route from '@ember/routing/route';

    export default Route.extend({
      actions: {
        save: function(user) {
          if (user.get('errors').has('email')) {
            return alert('Please update your email before attempting to save.');
          }
          user.save();
        }
      }
    });
    ```

    @method has
    @param {String} attribute
    @return {Boolean} true if there some errors on given attribute
  */
  has(attribute) {
    return this.errorsFor(attribute).length > 0;
  },
});
<|endoftext|>