<commit_before>vumi_ureport.api = function() {
    var vumigo = require('vumigo_v02');
    var utils = vumigo.utils;
    var Extendable = utils.Extendable;

    var JsonApi = vumigo.http_api.JsonApi;
    var HttpResponseError = vumigo.http_api.HttpResponseError;

    var UReportApi = Extendable.extend(function(self, im, base_url, backend) {
        self.im = im;
        self.http = new JsonApi(im);
        self.base_url = base_url;
        self.backend = backend;

        self.url = function(path) {
            return join_paths(self.base_url, path);
        };

        self.ureporters = function(user_addr) {
            var rel_path = join_paths('ureporters', self.backend, user_addr);
            return new UReportersApi(self, rel_path);
        };
    });

    var UReportersApi = Extendable.extend(function(self, api, rel_path) {
        self.api = api;
        self.rel_path = rel_path;

        self.url = function(path) {
            return self.api.url(join_paths(self.rel_path, path));
        };

        self.get = function() {
            return self
                .api.http.get(self.url())
                .get('data')
                .get('user');
        };

        self.is_registered = function() {
            return self
                .get()
                .get('registered')
                .catch(catch_code(404, false));
        };

        self.polls = {};

        self.polls.current = function() {
            return self
                .api.http.get(self.url('polls/current'))
                .get('data')
                .get('poll');
        };

        self.polls.topics = function() {
            return self
                .api.http.get(self.url('polls/topics'))
                .get('data')
                .get('poll_topics');
        };

        self.poll = function(id) {
            return new PollApi(self, join_paths('poll', id));
        };

        self.reports = {};
        self.reports.submit = function(report) {
            return self
                .api.http.post(self.url('reports/'), {
                    data: {report: report}
                })
                .get('data')
                .get('result');
        };
    });

    var PollApi = Extendable.extend(function(self, ureporter, rel_path) {
        self.api = ureporter.api;
        self.ureporter = ureporter;
        self.rel_path = rel_path;

        self.url = function(path) {
            return self.ureporter.url(join_paths(self.rel_path, path));
        };

        self.responses = {};

        self.responses.submit = function(response) {
            return self
                .api.http.post(self.url('responses/'), {
                    data: {response: response}
                })
                .get('data')
                .get('result');
        };

        self.summary = function() {
            return self
                .api.http.get(self.url('summary'))
                .get('data')
                .get('poll_result');
        };
    });

    function catch_code(code, result) {
        return function(e) {
            var match = e instanceof HttpResponseError
                     && e.response.code === code;

            if (!match) {
                throw e;
            }

            return utils.maybe_call(result);
        };
    }

    function join_paths() {
        var args = Array.prototype.slice.call(arguments);

        return args
            .filter(function(path) {
                return !!path;
            })
            .join('/');
    }

    return {
        UReportApi: UReportApi,
        UReportersApi: UReportersApi,
        PollApi: PollApi
    };
}();
<commit_msg>Shorten api.join_paths util a little<commit_after>vumi_ureport.api = function() {
    var vumigo = require('vumigo_v02');
    var utils = vumigo.utils;
    var Extendable = utils.Extendable;

    var JsonApi = vumigo.http_api.JsonApi;
    var HttpResponseError = vumigo.http_api.HttpResponseError;

    var UReportApi = Extendable.extend(function(self, im, base_url, backend) {
        self.im = im;
        self.http = new JsonApi(im);
        self.base_url = base_url;
        self.backend = backend;

        self.url = function(path) {
            return join_paths(self.base_url, path);
        };

        self.ureporters = function(user_addr) {
            var rel_path = join_paths('ureporters', self.backend, user_addr);
            return new UReportersApi(self, rel_path);
        };
    });

    var UReportersApi = Extendable.extend(function(self, api, rel_path) {
        self.api = api;
        self.rel_path = rel_path;

        self.url = function(path) {
            return self.api.url(join_paths(self.rel_path, path));
        };

        self.get = function() {
            return self
                .api.http.get(self.url())
                .get('data')
                .get('user');
        };

        self.is_registered = function() {
            return self
                .get()
                .get('registered')
                .catch(catch_code(404, false));
        };

        self.polls = {};

        self.polls.current = function() {
            return self
                .api.http.get(self.url('polls/current'))
                .get('data')
                .get('poll');
        };

        self.polls.topics = function() {
            return self
                .api.http.get(self.url('polls/topics'))
                .get('data')
                .get('poll_topics');
        };

        self.poll = function(id) {
            return new PollApi(self, join_paths('poll', id));
        };

        self.reports = {};
        self.reports.submit = function(report) {
            return self
                .api.http.post(self.url('reports/'), {
                    data: {report: report}
                })
                .get('data')
                .get('result');
        };
    });

    var PollApi = Extendable.extend(function(self, ureporter, rel_path) {
        self.api = ureporter.api;
        self.ureporter = ureporter;
        self.rel_path = rel_path;

        self.url = function(path) {
            return self.ureporter.url(join_paths(self.rel_path, path));
        };

        self.responses = {};

        self.responses.submit = function(response) {
            return self
                .api.http.post(self.url('responses/'), {
                    data: {response: response}
                })
                .get('data')
                .get('result');
        };

        self.summary = function() {
            return self
                .api.http.get(self.url('summary'))
                .get('data')
                .get('poll_result');
        };
    });

    function catch_code(code, result) {
        return function(e) {
            var match = e instanceof HttpResponseError
                     && e.response.code === code;

            if (!match) {
                throw e;
            }

            return utils.maybe_call(result);
        };
    }

    function join_paths() {
        return Array.prototype.filter.call(arguments, function(path) {
            return !!path;
        }).join('/');
    }

    return {
        UReportApi: UReportApi,
        UReportersApi: UReportersApi,
        PollApi: PollApi
    };
}();
<|endoftext|>


<commit_before>(function () {
    var apiData = {
        isInited: false
    };

    var
        baseUrl = location.protocol + '//' + location.host,
        identifyUrl = baseUrl + '/api/identify',
        settingsUrl = baseUrl + '/api/course/' + getURLParameter('courseId') + '/template/' + getURLParameter('templateId'),

        templateUrl = location.toString().substring(0, location.toString().indexOf('/settings/')) + '/',
        manifestUrl = templateUrl + 'manifest.json'; //TODO: Change way of resolving manifest file path

    //  token auth support;
    var token = localStorage['token.settings'];
    var isTokenAuthSupported = token !== undefined;
    var headers = isTokenAuthSupported ? { 'Authorization': 'Bearer ' + token } : {};
    identifyUrl = isTokenAuthSupported ? baseUrl + '/auth/identity' : identifyUrl;
    //  token auth support;

    window.egApi = {
        init: init,
        getManifest: getManifest,
        getUser: getUser,
        getSettings: getSettings,
        saveSettings: saveSettings,
        sendNotificationToEditor: sendNotificationToEditor
    };

    function init() {
        /* DEBUG
        var userDataPromise = $.Deferred().resolve([{ subscription: { accessType: 1, expirationDate: new Date(2016, 1, 1) } }]);
        var settingsPromise = $.getJSON('../../settings.js').then(function (response) { return [{ settings: JSON.stringify(response) }]; });
        var manifestPromise = $.getJSON(manifestUrl);
        END_DEBUG */

        /* RELEASE */
        var userDataPromise = $.ajax({
            url: identifyUrl,
            headers: headers,
            cache: false,
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json'
        });

        var settingsPromise = $.ajax({
            url: settingsUrl,
            headers: headers,
            cache: false,
            contentType: 'application/json',
            dataType: 'json'
        });

        var manifestPromise = $.ajax({
            url: manifestUrl,
            headers: headers,
            cache: false,
            contentType: 'application/json',
            dataType: 'json'
        });
        /* END_RELEASE */

        return $.when(manifestPromise, userDataPromise, settingsPromise).done(function (manifestResponse, userDataResponse, settingsResponse) {
            apiData.manifest = getManifestModel(manifestResponse[0]);
            apiData.user = getUserModel(userDataResponse[0]);
            apiData.settings = getSettingsModel(settingsResponse[0]);
            apiData.isInited = true;
        });
    }

    function isInitedGuard() {
        if (!apiData.isInited) {
            throw "Sorry, but you've tried to use api before it was initialized";
        }
    }

    function getManifest() {
        isInitedGuard();
        return apiData.manifest;
    }

    function getUser() {
        isInitedGuard();
        return apiData.user;
    }

    function getSettings() {
        isInitedGuard();
        return apiData.settings;
    }

    function getManifestModel(manifestData) {
        if (manifestData && manifestData.languages && manifestData.languages.length > 0) {
            for (var i = 0; i < manifestData.languages.length; i++) {
                manifestData.languages[i].url = templateUrl + manifestData.languages[i].url;
            }
        }

        return manifestData;
    }

    function getUserModel(userData) {
        //  token auth support;
        userDatais = isTokenAuthSupported ? userData.data : userData;
        //  token auth support;
        var user = { accessType: 0 };
        var starterAccessType = 1;
        if (userData.subscription &&
                userData.subscription.accessType &&
                userData.subscription.accessType >= starterAccessType &&
                new Date(userData.subscription.expirationDate) >= new Date()
        ) {
            user.accessType = userData.subscription.accessType;
        }
        return user;
    }

    function getSettingsModel(settingsData) {
        var settings;
        if (settingsData.settings && settingsData.settings.length > 0) {
            settings = JSON.parse(settingsData.settings);
        } else {
            //TODO: need to be removed in next implementation
            settings = {
                logo: {},
                xApi: {
                    enabled: true,
                    selectedLrs: 'default',
                    lrs: {
                        credentials: {}
                    }
                },
                masteryScore: {}
            };
        }
        return settings;
    }

    function getURLParameter(name) {
        return decodeURI(
            (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]
        );
    }

    function saveSettings(settings, extraSettings, successSaveMessage, failSaveMessage) {
        freezeEditor();

        var data = {
            settings: settings,
            extraSettings: extraSettings
        };

        var requestArgs = {
            url: settingsUrl,
            type: 'POST',
            headers: headers,
            cache: false,
            contentType: 'application/json',
            dataType: 'json',
            data: data
        }

        return $.ajax(requestArgs).done(function () {
            sendNotificationToEditor(successSaveMessage, true);
        }).fail(function () {
            sendNotificationToEditor(failSaveMessage, false);
        }).always(function () {
            unfreezeEditor();
        });
    }

    function freezeEditor() {
        postMessageToEditor({ type: 'freeze', data: { freezeEditor: true } });
    }

    function unfreezeEditor() {
        postMessageToEditor({ type: 'freeze', data: { freezeEditor: false } });
    }

    function postMessageToEditor(data) {
        var editorWindow = window.top;
        editorWindow.postMessage(data, editorWindow.location.href);
    }

    function sendNotificationToEditor(message, isSuccess) {
        postMessageToEditor({ type: 'notification', data: { success: isSuccess, message: message } });
    }

})();<commit_msg>Bug with default logo settings fixed.<commit_after>(function () {
    var apiData = {
        isInited: false
    };

    var
        baseUrl = location.protocol + '//' + location.host,
        identifyUrl = baseUrl + '/api/identify',
        settingsUrl = baseUrl + '/api/course/' + getURLParameter('courseId') + '/template/' + getURLParameter('templateId'),

        templateUrl = location.toString().substring(0, location.toString().indexOf('/settings/')) + '/',
        manifestUrl = templateUrl + 'manifest.json'; //TODO: Change way of resolving manifest file path

    //  token auth support;
    var token = localStorage['token.settings'];
    var isTokenAuthSupported = token !== undefined;
    var headers = isTokenAuthSupported ? { 'Authorization': 'Bearer ' + token } : {};
    identifyUrl = isTokenAuthSupported ? baseUrl + '/auth/identity' : identifyUrl;
    //  token auth support;

    window.egApi = {
        init: init,
        getManifest: getManifest,
        getUser: getUser,
        getSettings: getSettings,
        saveSettings: saveSettings,
        sendNotificationToEditor: sendNotificationToEditor
    };

    function init() {
        /* DEBUG
        var userDataPromise = $.Deferred().resolve([{ subscription: { accessType: 1, expirationDate: new Date(2016, 1, 1) } }]);
        var settingsPromise = $.getJSON('../../settings.js').then(function (response) { return [{ settings: JSON.stringify(response) }]; });
        var manifestPromise = $.getJSON(manifestUrl);
        END_DEBUG */

        /* RELEASE */
        var userDataPromise = $.ajax({
            url: identifyUrl,
            headers: headers,
            cache: false,
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json'
        });

        var settingsPromise = $.ajax({
            url: settingsUrl,
            headers: headers,
            cache: false,
            contentType: 'application/json',
            dataType: 'json'
        });

        var manifestPromise = $.ajax({
            url: manifestUrl,
            headers: headers,
            cache: false,
            contentType: 'application/json',
            dataType: 'json'
        });
        /* END_RELEASE */

        return $.when(manifestPromise, userDataPromise, settingsPromise).done(function (manifestResponse, userDataResponse, settingsResponse) {
            apiData.manifest = getManifestModel(manifestResponse[0]);
            apiData.user = getUserModel(userDataResponse[0]);
            apiData.settings = getSettingsModel(settingsResponse[0]);
            apiData.isInited = true;
        });
    }

    function isInitedGuard() {
        if (!apiData.isInited) {
            throw "Sorry, but you've tried to use api before it was initialized";
        }
    }

    function getManifest() {
        isInitedGuard();
        return apiData.manifest;
    }

    function getUser() {
        isInitedGuard();
        return apiData.user;
    }

    function getSettings() {
        isInitedGuard();
        return apiData.settings;
    }

    function getManifestModel(manifestData) {
        if (manifestData && manifestData.languages && manifestData.languages.length > 0) {
            for (var i = 0; i < manifestData.languages.length; i++) {
                manifestData.languages[i].url = templateUrl + manifestData.languages[i].url;
            }
        }

        return manifestData;
    }

    function getUserModel(userData) {
        //  token auth support;
        userDatais = isTokenAuthSupported ? userData.data : userData;
        //  token auth support;
        var user = { accessType: 0 };
        var starterAccessType = 1;
        if (userData.subscription &&
                userData.subscription.accessType &&
                userData.subscription.accessType >= starterAccessType &&
                new Date(userData.subscription.expirationDate) >= new Date()
        ) {
            user.accessType = userData.subscription.accessType;
        }
        return user;
    }

    function getSettingsModel(settingsData) {
        var settings;
        if (settingsData.settings && settingsData.settings.length > 0) {
            settings = JSON.parse(settingsData.settings);
        } else {
            //TODO: need to be removed in next implementation
            settings = {
                xApi: {
                    enabled: true,
                    selectedLrs: 'default',
                    lrs: {
                        credentials: {}
                    }
                },
                masteryScore: {}
            };
        }
        return settings;
    }

    function getURLParameter(name) {
        return decodeURI(
            (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]
        );
    }

    function saveSettings(settings, extraSettings, successSaveMessage, failSaveMessage) {
        freezeEditor();

        var data = {
            settings: settings,
            extraSettings: extraSettings
        };

        var requestArgs = {
            url: settingsUrl,
            type: 'POST',
            headers: headers,
            cache: false,
            contentType: 'application/json',
            dataType: 'json',
            data: data
        }

        return $.ajax(requestArgs).done(function () {
            sendNotificationToEditor(successSaveMessage, true);
        }).fail(function () {
            sendNotificationToEditor(failSaveMessage, false);
        }).always(function () {
            unfreezeEditor();
        });
    }

    function freezeEditor() {
        postMessageToEditor({ type: 'freeze', data: { freezeEditor: true } });
    }

    function unfreezeEditor() {
        postMessageToEditor({ type: 'freeze', data: { freezeEditor: false } });
    }

    function postMessageToEditor(data) {
        var editorWindow = window.top;
        editorWindow.postMessage(data, editorWindow.location.href);
    }

    function sendNotificationToEditor(message, isSuccess) {
        postMessageToEditor({ type: 'notification', data: { success: isSuccess, message: message } });
    }

})();<|endoftext|>


<commit_before>function App(app_container) {
    this._container= app_container;
}

reader(App, "container");
accessor(App, "board");

App.prototype.initialize= function() {
    this.board(new Board);
    this.board().add_ant();
};

App.prototype.show_board= function() {
    var board_drawer= new BoardDrawer(this.container());
    board_drawer.display(this.board());
};

App.prototype.update_board= function() {
    if (this.container().html() === "")
	return;
    this.container().html("");
    this.show_board();
};
<commit_msg>Specs pass.<commit_after>function App(app_container) {
    this._container= app_container;
}

reader(App, "container");
accessor(App, "board");

App.prototype.initialize= function() {
    this.board(new Board);
    this.board().add_ant();
};

App.prototype.show_board= function() {
    var board_drawer= new BoardDrawer(this.container());
    board_drawer.display(this.board());
};

App.prototype.update_board= function() {
    if (this.container().html() === "")
	return;
    this.container().html("");
    this.show_board();
};

App.prototype.ant= function() {
    return this.board().ant();
};
<|endoftext|>


<commit_before>export class UtilService {
  /**
   * Are 2 provided arrays equal
   * @param {array} a
   * @param {array} b
   * @return {bool} is eual
   */
  isArrayEqual(a, b) {
    if (a === b) return true;
    if (a === null || b === null) return false;
    if (a.length !== b.length) return false;

    // If you don't care about the order of the elements inside
    // the array, you should sort both arrays here.

    for (let i = 0; i < a.length; ++i) {
      if (a[i] !== b[i]) return false;
    }
    return true;
  }

  /**
   * Are 2 provided variables equal
   * @param {any} a
   * @param {any} b
   * @return {bool} is eual
   */
  isEqual(a, b) {
    if (Array.isArray(a) && Array.isArray(b)) {
      return this.isArrayEqual(a.sort(), b.sort());
    }
    return a === b;
  }

  /**
   * Find if the input array is an array of objects or not
   * @param {array} input array
   * @return {bool} result
   */
  isObjectArray(inputArrray) {
    return Array.isArray(inputArrray) && inputArrray.length > 0 && typeof inputArrray[0] === 'object';
  }

  /**
   * Find if the input argument is an object or not
   * @param {any} argument
   * @return {bool} result
   */
  isObject(arg) {
    return typeof arg === 'object';
  }

  /**
   * Find if the input argument is a string or not
   * @param {any} argument
   * @return {bool} result
   */
  isString(arg) {
    return typeof arg === 'string' || arg instanceof String;
  }

  /**
   * Find if the input array is an array of strings or not
   * @param {array} input array
   * @return {bool} result
   */
  isStringArray(inputArrray) {
    return Array.isArray(inputArrray) && inputArrray.length > 0 && typeof inputArrray[0] === 'string';
  }

  /**
   * Parse the argument to a boolean output
   * @param {any} input value
   * @return {bool} result
   */
  parseBool(value) {
    return (/^(true|1)$/i).test(value);
  }

  /**
   * Parse the argument to a boolean output when available, else return True on empty
   * @param {any} input value
   * @return {bool} result
   */
  parseBoolOrTrueOnEmpty(value) {
    return (value === undefined || value === '') ? true : this.parseBool(value);
  }
}
<commit_msg>Fix order-insensitive array comparison (#75)<commit_after>export class UtilService {
  /**
   * Are 2 provided arrays equal
   * @param {array} a
   * @param {array} b
   * @return {bool} is eual
   */
  isArrayEqual(a, b) {
    if (a === b) return true;
    if (a === null || b === null) return false;
    if (a.length !== b.length) return false;

    for (let i = 0; i < a.length; i++) {
      let aExistsInb = false;
      for (let j = 0; j < b.length && !aExistsInb; j++) {
        if (a[i] === b[j]) {
          aExistsInb = true;
        }
      }
      if (!aExistsInb) {
        return false;
      }
    }
    return true;
  }

  /**
   * Are 2 provided variables equal
   * @param {any} a
   * @param {any} b
   * @return {bool} is eual
   */
  isEqual(a, b) {
    if (Array.isArray(a) && Array.isArray(b)) {
      return this.isArrayEqual(a.sort(), b.sort());
    }
    return a === b;
  }

  /**
   * Find if the input array is an array of objects or not
   * @param {array} input array
   * @return {bool} result
   */
  isObjectArray(inputArrray) {
    return Array.isArray(inputArrray) && inputArrray.length > 0 && typeof inputArrray[0] === 'object';
  }

  /**
   * Find if the input argument is an object or not
   * @param {any} argument
   * @return {bool} result
   */
  isObject(arg) {
    return typeof arg === 'object';
  }

  /**
   * Find if the input argument is a string or not
   * @param {any} argument
   * @return {bool} result
   */
  isString(arg) {
    return typeof arg === 'string' || arg instanceof String;
  }

  /**
   * Find if the input array is an array of strings or not
   * @param {array} input array
   * @return {bool} result
   */
  isStringArray(inputArrray) {
    return Array.isArray(inputArrray) && inputArrray.length > 0 && typeof inputArrray[0] === 'string';
  }

  /**
   * Parse the argument to a boolean output
   * @param {any} input value
   * @return {bool} result
   */
  parseBool(value) {
    return (/^(true|1)$/i).test(value);
  }

  /**
   * Parse the argument to a boolean output when available, else return True on empty
   * @param {any} input value
   * @return {bool} result
   */
  parseBoolOrTrueOnEmpty(value) {
    return (value === undefined || value === '') ? true : this.parseBool(value);
  }
}
<|endoftext|>


<commit_before>/**
 * @fileoverview Test cases for the option "connectSeparatedPoints" especially for the scenario where not every series has a value for each timestamp.
 *
 * @author julian.eichstaedt@ch.sauter-bc.com (Fr. Sauter AG)
 */
var ConnectSeparatedPointsTestCase = TestCase("connect-separated-points");

ConnectSeparatedPointsTestCase.prototype.setUp = function() {
  document.body.innerHTML = "

";
};

ConnectSeparatedPointsTestCase.origFunc = Dygraph.getContext;

ConnectSeparatedPointsTestCase.prototype.setUp = function() {
  document.body.innerHTML = "

";
  Dygraph.getContext = function(canvas) {
    return new Proxy(ConnectSeparatedPointsTestCase.origFunc(canvas));
  };
};

ConnectSeparatedPointsTestCase.prototype.tearDown = function() {
  Dygraph.getContext = ConnectSeparatedPointsTestCase.origFunc;
};

ConnectSeparatedPointsTestCase.prototype.testEdgePointsSimple = function() {
  var opts = {
    width: 480,
    height: 320,
    labels: ["x", "series1", "series2", "additionalSeries"],
    connectSeparatedPoints: true,
    dateWindow: [2.5,7.5]
  };

  var data = [
              [0,-1,0,null],
              [1,null,2,null],
              [2,null,4,null],
              [3,0.5,0,null],
              [4,1,-1,5],
              [5,2,-2,6],
              [6,2.5,-2.5,7],
              [7,3,-3,null],
              [8,4,null,null],
              [9,4,-10,null],
             ];

  var graph = document.getElementById("graph");
  var g = new Dygraph(graph, data, opts);

  htx = g.hidden_ctx_;

  var attrs = {};

  // Test if series1 is drawn correctly.
  // ------------------------------------

  // The first point of the first series
  var x1 = data[0][0];
  var y1 = data[0][1];
  var xy1 = g.toDomCoords(x1, y1);

  // The next valid point of this series
  var x2 = data[3][0];
  var y2 = data[3][1];
  var xy2 = g.toDomCoords(x2, y2);

  // Check if both points are connected at the left edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);

  // Test if series2 is drawn correctly.
  // ------------------------------------

  // The last point of the second series.
  var x2 = data[9][0];
  var y2 = data[9][2];
  var xy2 = g.toDomCoords(x2, y2);

  // The previous valid point of this series
  var x1 = data[7][0];
  var y1 = data[7][2];
  var xy1 = g.toDomCoords(x1, y1);

  // Check if both points are connected at the right edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);
};

ConnectSeparatedPointsTestCase.prototype.testEdgePointsCustomBars = function() {
  var opts = {
    width: 480,
    height: 320,
    labels: ["x", "series1", "series2", "additionalSeries"],
    connectSeparatedPoints: true,
    dateWindow: [2.5,7.5],
    customBars: true
  };

  var data = [
              [0,[4,5,6], [1,2,3], [null, null, null]],
              [1,[null,null,null], [2,3,4], [null, null, null]],
              [2,[null,null,null], [3,4,5], [null, null, null]],
              [3,[0,1,2], [2,3,4], [null, null, null]],
              [4,[1,2,3], [2,3,4], [4, 5, 6]],
              [5,[1,2,3], [3,4,5], [4, 5, 6]],
              [6,[0,1,2], [4,5,6], [5, 6, 7]],
              [7,[0,1,2], [4,5,6], [null, null, null]],
              [8,[2,3,4], [null,null,null], [null, null, null]],
              [9,[0,1,2], [2,4,9], [null, null, null]]

             ];

  var graph = document.getElementById("graph");
  var g = new Dygraph(graph, data, opts);

  htx = g.hidden_ctx_;

  var attrs = {};

  // Test if values of the series1 are drawn correctly.
  // ------------------------------------

  // The first point of the first series
  var x1 = data[0][0];
  var y1 = data[0][1][1];
  var xy1 = g.toDomCoords(x1, y1);

  // The next valid point of this series
  var x2 = data[3][0];
  var y2 = data[3][1][1];
  var xy2 = g.toDomCoords(x2, y2);

  // Check if both points are connected at the left edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);

  // Test if the custom bars of the series1 are drawn correctly
  // --------------------------------------------

  // The first min-point of this series
  x1 = data[0][0];
  y1 = data[0][1][0];
  xy1 = g.toDomCoords(x1, y1);

  // The next valid min-point of the second series.
  x2 = data[3][0];
  y2 = data[3][1][0];
  xy2 = g.toDomCoords(x2, y2);

  // Check if both points are connected at the left edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);

  // The first max-point of this series
  x1 = data[0][0];
  y1 = data[0][1][2];
  xy1 = g.toDomCoords(x1, y1);

  // The next valid max-point of the second series.
  x2 = data[3][0];
  y2 = data[3][1][2];
  xy2 = g.toDomCoords(x2, y2);

  // Check if both points are connected at the left edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);

  // Test if values of the series2 are drawn correctly.
  // ------------------------------------

  // The last point of the second series.
  var x2 = data[9][0];
  var y2 = data[9][2][1];
  var xy2 = g.toDomCoords(x2, y2);

  // The previous valid point of this series
  var x1 = data[7][0];
  var y1 = data[7][2][1];
  var xy1 = g.toDomCoords(x1, y1);

  // Check if both points are connected at the right edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);

  // Test if the custom bars of the series2 are drawn correctly
  // --------------------------------------------

  // The last min-point of the second series.
  x2 = data[9][0];
  y2 = data[9][2][0];
  xy2 = g.toDomCoords(x2, y2);

  // The previous valid min-point of this series
  x1 = data[7][0];
  y1 = data[7][2][0];
  xy1 = g.toDomCoords(x1, y1);

  // Check if both points are connected at the right edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);

  // The last max-point of the second series.
  x2 = data[9][0];
  y2 = data[9][2][2];
  xy2 = g.toDomCoords(x2, y2);

  // The previous valid max-point of this series
  x1 = data[7][0];
  y1 = data[7][2][2];
  xy1 = g.toDomCoords(x1, y1);

  // Check if both points are connected at the right edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);
};

ConnectSeparatedPointsTestCase.prototype.testEdgePointsErrorBars = function() {
  var opts = {
    width: 480,
    height: 320,
    labels: ["x", "series1", "series2", "seriesTestHelper"],
    connectSeparatedPoints: true,
    dateWindow: [2,7.5],
    errorBars: true

  };

  var data = [
              [0,[5,1], [2,1], [null,null]],
              [1,[null,null], [3,1], [null,null]],
              [2,[null,null], [4,1], [null,null]],
              [3,[1,1], [3,1], [null,null]],
              [4,[2,1], [3,1], [5,1]],
              [5,[2,1], [4,1], [5,1]],
              [6,[1,1], [5,1], [6,1]],
              [7,[1,1], [5,1], [null,null]],
              [8,[3,1], [null,null], [null,null]],
              [9,[1,1], [4,1], [null,null]]

             ];

  var graph = document.getElementById("graph");
  var g = new Dygraph(graph, data, opts);

  htx = g.hidden_ctx_;

  var attrs = {};

  // Test if values of the series1 are drawn correctly.
  // ------------------------------------

  // The first point of the first series
  var x1 = data[0][0];
  var y1 = data[0][1][0];
  var xy1 = g.toDomCoords(x1, y1);

  // The next valid point of this series
  var x2 = data[3][0];
  var y2 = data[3][1][0];
  var xy2 = g.toDomCoords(x2, y2);

  // Check if both points are connected at the left edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);

  // Test if the upper error bars of series1 are drawn correctly
  // --------------------------------------------

  // The first upper error-point of this series
  x1 = data[0][0];
  var y1error = y1 + (data[0][1][1]*2);
  xy1 = g.toDomCoords(x1, y1error);

  // The next valid upper error-point of the second series.
  x2 = data[3][0];
  var y2error = y2 + (data[3][1][1]*2);
  xy2 = g.toDomCoords(x2, y2error);

  // Check if both points are connected at the left edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);

  // Test if the lower error bars of series1 are drawn correctly
  // --------------------------------------------

  // The first lower error-point of this series
  x1 = data[0][0];
  y1error = y1 - (data[0][1][1]*2);
  xy1 = g.toDomCoords(x1, y1error);

  //The next valid lower error-point of the second series.
  x2 = data[3][0];
  y2error = y2 - (data[3][1][1]*2);
  xy2 = g.toDomCoords(x2, y2error);

  // Check if both points are connected at the left edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);

  // Test if values of the series2 are drawn correctly.
  // ------------------------------------

  // The last point of this series
  x2 = data[9][0];
  y2 = data[9][2][0];
  xy2 = g.toDomCoords(x2, y2);

  // The previous valid point of the first series
  x1 = data[7][0];
  y1 = data[7][2][0];
  xy1 = g.toDomCoords(x1, y1);

  // Check if both points are connected at the right edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);

  // Test if the upper error bars of series2 are drawn correctly
  // --------------------------------------------

  // The last upper error-point of the second series.
  x2 = data[9][0];
  var y2error = y2 + (data[9][2][1]*2);
  xy2 = g.toDomCoords(x2, y2error);

  // The previous valid upper error-point of this series
  x1 = data[7][0];
  var y1error = y1 + (data[7][2][1]*2);
  xy1 = g.toDomCoords(x1, y1error);

  // Check if both points are connected at the right edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);

  // Test if the lower error bars of series1 are drawn correctly
  // --------------------------------------------

  // The last lower error-point of the second series.
  x2 = data[9][0];
  y2error = y2 - (data[9][2][1]*2);
  xy2 = g.toDomCoords(x2, y2error);

  // The previous valid lower error-point of this series
  x1 = data[7][0];
  y1error = y1 - (data[7][2][1]*2);
  xy1 = g.toDomCoords(x1, y1error);

  // Check if both points are connected at the right edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);
};
<commit_msg>REFACTORING: adapted EOL<commit_after>/**
 * @fileoverview Test cases for the option "connectSeparatedPoints" especially for the scenario where not every series has a value for each timestamp.
 *
 * @author julian.eichstaedt@ch.sauter-bc.com (Fr. Sauter AG)
 */
var ConnectSeparatedPointsTestCase = TestCase("connect-separated-points");

ConnectSeparatedPointsTestCase.prototype.setUp = function() {
  document.body.innerHTML = "

";
};

ConnectSeparatedPointsTestCase.origFunc = Dygraph.getContext;

ConnectSeparatedPointsTestCase.prototype.setUp = function() {
  document.body.innerHTML = "

";
  Dygraph.getContext = function(canvas) {
    return new Proxy(ConnectSeparatedPointsTestCase.origFunc(canvas));
  };
};

ConnectSeparatedPointsTestCase.prototype.tearDown = function() {
  Dygraph.getContext = ConnectSeparatedPointsTestCase.origFunc;
};

ConnectSeparatedPointsTestCase.prototype.testEdgePointsSimple = function() {
  var opts = {
    width: 480,
    height: 320,
    labels: ["x", "series1", "series2", "additionalSeries"],
    connectSeparatedPoints: true,
    dateWindow: [2.5,7.5]
  };

  var data = [
              [0,-1,0,null],
              [1,null,2,null],
              [2,null,4,null],
              [3,0.5,0,null],
              [4,1,-1,5],
              [5,2,-2,6],
              [6,2.5,-2.5,7],
              [7,3,-3,null],
              [8,4,null,null],
              [9,4,-10,null],
             ];

  var graph = document.getElementById("graph");
  var g = new Dygraph(graph, data, opts);

  htx = g.hidden_ctx_;

  var attrs = {};

  // Test if series1 is drawn correctly.
  // ------------------------------------

  // The first point of the first series
  var x1 = data[0][0];
  var y1 = data[0][1];
  var xy1 = g.toDomCoords(x1, y1);

  // The next valid point of this series
  var x2 = data[3][0];
  var y2 = data[3][1];
  var xy2 = g.toDomCoords(x2, y2);

  // Check if both points are connected at the left edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);

  // Test if series2 is drawn correctly.
  // ------------------------------------

  // The last point of the second series.
  var x2 = data[9][0];
  var y2 = data[9][2];
  var xy2 = g.toDomCoords(x2, y2);

  // The previous valid point of this series
  var x1 = data[7][0];
  var y1 = data[7][2];
  var xy1 = g.toDomCoords(x1, y1);

  // Check if both points are connected at the right edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);
};

ConnectSeparatedPointsTestCase.prototype.testEdgePointsCustomBars = function() {
  var opts = {
    width: 480,
    height: 320,
    labels: ["x", "series1", "series2", "additionalSeries"],
    connectSeparatedPoints: true,
    dateWindow: [2.5,7.5],
    customBars: true
  };

  var data = [
              [0,[4,5,6], [1,2,3], [null, null, null]],
              [1,[null,null,null], [2,3,4], [null, null, null]],
              [2,[null,null,null], [3,4,5], [null, null, null]],
              [3,[0,1,2], [2,3,4], [null, null, null]],
              [4,[1,2,3], [2,3,4], [4, 5, 6]],
              [5,[1,2,3], [3,4,5], [4, 5, 6]],
              [6,[0,1,2], [4,5,6], [5, 6, 7]],
              [7,[0,1,2], [4,5,6], [null, null, null]],
              [8,[2,3,4], [null,null,null], [null, null, null]],
              [9,[0,1,2], [2,4,9], [null, null, null]]

             ];

  var graph = document.getElementById("graph");
  var g = new Dygraph(graph, data, opts);

  htx = g.hidden_ctx_;

  var attrs = {};

  // Test if values of the series1 are drawn correctly.
  // ------------------------------------

  // The first point of the first series
  var x1 = data[0][0];
  var y1 = data[0][1][1];
  var xy1 = g.toDomCoords(x1, y1);

  // The next valid point of this series
  var x2 = data[3][0];
  var y2 = data[3][1][1];
  var xy2 = g.toDomCoords(x2, y2);

  // Check if both points are connected at the left edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);

  // Test if the custom bars of the series1 are drawn correctly
  // --------------------------------------------

  // The first min-point of this series
  x1 = data[0][0];
  y1 = data[0][1][0];
  xy1 = g.toDomCoords(x1, y1);

  // The next valid min-point of the second series.
  x2 = data[3][0];
  y2 = data[3][1][0];
  xy2 = g.toDomCoords(x2, y2);

  // Check if both points are connected at the left edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);

  // The first max-point of this series
  x1 = data[0][0];
  y1 = data[0][1][2];
  xy1 = g.toDomCoords(x1, y1);

  // The next valid max-point of the second series.
  x2 = data[3][0];
  y2 = data[3][1][2];
  xy2 = g.toDomCoords(x2, y2);

  // Check if both points are connected at the left edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);

  // Test if values of the series2 are drawn correctly.
  // ------------------------------------

  // The last point of the second series.
  var x2 = data[9][0];
  var y2 = data[9][2][1];
  var xy2 = g.toDomCoords(x2, y2);

  // The previous valid point of this series
  var x1 = data[7][0];
  var y1 = data[7][2][1];
  var xy1 = g.toDomCoords(x1, y1);

  // Check if both points are connected at the right edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);

  // Test if the custom bars of the series2 are drawn correctly
  // --------------------------------------------

  // The last min-point of the second series.
  x2 = data[9][0];
  y2 = data[9][2][0];
  xy2 = g.toDomCoords(x2, y2);

  // The previous valid min-point of this series
  x1 = data[7][0];
  y1 = data[7][2][0];
  xy1 = g.toDomCoords(x1, y1);

  // Check if both points are connected at the right edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);

  // The last max-point of the second series.
  x2 = data[9][0];
  y2 = data[9][2][2];
  xy2 = g.toDomCoords(x2, y2);

  // The previous valid max-point of this series
  x1 = data[7][0];
  y1 = data[7][2][2];
  xy1 = g.toDomCoords(x1, y1);

  // Check if both points are connected at the right edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);
};

ConnectSeparatedPointsTestCase.prototype.testEdgePointsErrorBars = function() {
  var opts = {
    width: 480,
    height: 320,
    labels: ["x", "series1", "series2", "seriesTestHelper"],
    connectSeparatedPoints: true,
    dateWindow: [2,7.5],
    errorBars: true

  };

  var data = [
              [0,[5,1], [2,1], [null,null]],
              [1,[null,null], [3,1], [null,null]],
              [2,[null,null], [4,1], [null,null]],
              [3,[1,1], [3,1], [null,null]],
              [4,[2,1], [3,1], [5,1]],
              [5,[2,1], [4,1], [5,1]],
              [6,[1,1], [5,1], [6,1]],
              [7,[1,1], [5,1], [null,null]],
              [8,[3,1], [null,null], [null,null]],
              [9,[1,1], [4,1], [null,null]]

             ];

  var graph = document.getElementById("graph");
  var g = new Dygraph(graph, data, opts);

  htx = g.hidden_ctx_;

  var attrs = {};

  // Test if values of the series1 are drawn correctly.
  // ------------------------------------

  // The first point of the first series
  var x1 = data[0][0];
  var y1 = data[0][1][0];
  var xy1 = g.toDomCoords(x1, y1);

  // The next valid point of this series
  var x2 = data[3][0];
  var y2 = data[3][1][0];
  var xy2 = g.toDomCoords(x2, y2);

  // Check if both points are connected at the left edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);

  // Test if the upper error bars of series1 are drawn correctly
  // --------------------------------------------

  // The first upper error-point of this series
  x1 = data[0][0];
  var y1error = y1 + (data[0][1][1]*2);
  xy1 = g.toDomCoords(x1, y1error);

  // The next valid upper error-point of the second series.
  x2 = data[3][0];
  var y2error = y2 + (data[3][1][1]*2);
  xy2 = g.toDomCoords(x2, y2error);

  // Check if both points are connected at the left edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);

  // Test if the lower error bars of series1 are drawn correctly
  // --------------------------------------------

  // The first lower error-point of this series
  x1 = data[0][0];
  y1error = y1 - (data[0][1][1]*2);
  xy1 = g.toDomCoords(x1, y1error);

  //The next valid lower error-point of the second series.
  x2 = data[3][0];
  y2error = y2 - (data[3][1][1]*2);
  xy2 = g.toDomCoords(x2, y2error);

  // Check if both points are connected at the left edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);

  // Test if values of the series2 are drawn correctly.
  // ------------------------------------

  // The last point of this series
  x2 = data[9][0];
  y2 = data[9][2][0];
  xy2 = g.toDomCoords(x2, y2);

  // The previous valid point of the first series
  x1 = data[7][0];
  y1 = data[7][2][0];
  xy1 = g.toDomCoords(x1, y1);

  // Check if both points are connected at the right edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);

  // Test if the upper error bars of series2 are drawn correctly
  // --------------------------------------------

  // The last upper error-point of the second series.
  x2 = data[9][0];
  var y2error = y2 + (data[9][2][1]*2);
  xy2 = g.toDomCoords(x2, y2error);

  // The previous valid upper error-point of this series
  x1 = data[7][0];
  var y1error = y1 + (data[7][2][1]*2);
  xy1 = g.toDomCoords(x1, y1error);

  // Check if both points are connected at the right edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);

  // Test if the lower error bars of series1 are drawn correctly
  // --------------------------------------------

  // The last lower error-point of the second series.
  x2 = data[9][0];
  y2error = y2 - (data[9][2][1]*2);
  xy2 = g.toDomCoords(x2, y2error);

  // The previous valid lower error-point of this series
  x1 = data[7][0];
  y1error = y1 - (data[7][2][1]*2);
  xy1 = g.toDomCoords(x1, y1error);

  // Check if both points are connected at the right edge of the canvas and if the option "connectSeparatedPoints" works properly
  // even if the point is outside the visible range and only one series has a valid value for this point.
  CanvasAssertions.assertLineDrawn(htx, xy1, xy2, attrs);
};
<|endoftext|>


<commit_before>var NCubeJsonEditor = (function ($) {
    var nce = null;
    var _editor = null;
    var _saveBtn = null;

    function init(info) {
        var JsonMode;
        // Create JSON Editor (http://jsoneditoronline.org/downloads/)
        if (!nce) {
            nce = info;
            JsonMode = ace.require('ace/mode/json').Mode;
            _editor = ace.edit('editor');
            _editor.$blockScrolling = Infinity;
            _editor.renderer.setShowPrintMargin(false);
            _editor.session.setMode(new JsonMode);

            _editor.on('change', function() {
                updateDirtyStatus();
            });

            _editor.session.on('changeScrollTop', function(scrollTop) {
                saveViewPosition(scrollTop);
            });

            _editor.commands.addCommand({
                name: 'saveCommand',
                bindKey: { win: 'Ctrl-S', mac: 'Command-S' },
                exec: function(editor) {
                    save();
                }
            });
        }
        _saveBtn = $('#saveButton');
        _saveBtn.on('click', function () {
            save();
        });
    }

    function scrollToSavedPosition() {
        var pos = nce.getViewPosition() || 0;
        _editor.session.setScrollTop(pos);
    }

    function saveViewPosition(scrollInfo) {
        nce.saveViewPosition(scrollInfo);
    }

    function save() {
        var result;
        var selectedTabAppId = nce.getSelectedTabAppId();
        nce.clearNote();
        if (selectedTabAppId.branch === 'HEAD') {
            nce.selectBranch();
            return;
        }

        clearDirtyStatus();
        result = nce.call(CONTROLLER + CONTROLLER_METHOD.SAVE_JSON, [selectedTabAppId, _editor.getValue()]);
        if (result.status) {
            nce.updateCubeLeftHandChangedStatus(nce.getSelectedCubeName(), CHANGETYPE.UPDATED);
        } else {
            nce.showNote('Error saving JSON n-cube:
' + result.data);
        }
    }

    function isDirty() {
        return _editor ? !_editor.getSession().getUndoManager().isClean() : false;
    }

    function clearDirtyStatus() {
        var undoMgr;
        if (_editor) {
            undoMgr = _editor.getSession().getUndoManager();
            undoMgr.reset();
            undoMgr.markClean();
        }
        updateDirtyStatus();
    }

    function updateDirtyStatus() {
        var dirty, text;
        dirty = isDirty();
        _saveBtn.prop('disabled', !dirty);
        _saveBtn.html(dirty ? 'Save*' : 'Save');
    }

    function load() {
        var result = nce.call(CONTROLLER + CONTROLLER_METHOD.GET_JSON, [nce.getSelectedTabAppId(), nce.getSelectedCubeName(), {mode:JSON_MODE.PRETTY}], {noResolveRefs:true});
        if (result.status) {
            try {
                _editor.setValue(result.data);
                _editor.clearSelection();
                scrollToSavedPosition();
            } catch (e) {
                nce.showNote('JSON content too large for the JSON Text Editor.  Capture the JSON from the "Revision History" option.');
                console.log(e);
            }
        } else {
            _editor.setValue("Unable to load '" + nce.getSelectedCubeName() + "'. " + result.data);
        }

        clearDirtyStatus();
    }

    function handleCubeSelected() {
        load();
    }

    // Let parent (main frame) know that the child window has loaded.
    // The loading of all of the Javascript (deeply) is continuous on the main thread.
    // Therefore, the setTimeout(, 1) ensures that the main window (parent frame)
    // is called after all Javascript has been loaded.
    if (window.parent.frameLoaded) {
        setTimeout(function () {
            window.parent.frameLoaded(document);
        }, 1);
    }

    return {
        init: init,
        handleCubeSelected: handleCubeSelected,
        load: load
    };

})(jQuery);

function tabActivated(info) {
    NCubeJsonEditor.init(info);
    NCubeJsonEditor.load();
}

function cubeSelected() {
    NCubeJsonEditor.handleCubeSelected();
}

var onNoteEvent = function onNoteEvent(e, element){};<commit_msg>SaveJson being called multiple times.<commit_after>var NCubeJsonEditor = (function ($) {
    var nce = null;
    var _editor = null;
    var _saveBtn = null;

    function init(info) {
        var JsonMode;
        // Create JSON Editor (http://jsoneditoronline.org/downloads/)
        if (!nce) {
            nce = info;
            JsonMode = ace.require('ace/mode/json').Mode;
            _editor = ace.edit('editor');
            _editor.$blockScrolling = Infinity;
            _editor.renderer.setShowPrintMargin(false);
            _editor.session.setMode(new JsonMode);

            _editor.on('change', function() {
                updateDirtyStatus();
            });

            _editor.session.on('changeScrollTop', function(scrollTop) {
                saveViewPosition(scrollTop);
            });

            _editor.commands.addCommand({
                name: 'saveCommand',
                bindKey: { win: 'Ctrl-S', mac: 'Command-S' },
                exec: function(editor) {
                    save();
                }
            });

            _saveBtn = $('#saveButton');
            _saveBtn.on('click', function () {
                save();
            });
        }
    }

    function scrollToSavedPosition() {
        var pos = nce.getViewPosition() || 0;
        _editor.session.setScrollTop(pos);
    }

    function saveViewPosition(scrollInfo) {
        nce.saveViewPosition(scrollInfo);
    }

    function save() {
        var result;
        var selectedTabAppId = nce.getSelectedTabAppId();
        nce.clearNote();
        if (selectedTabAppId.branch === 'HEAD') {
            nce.selectBranch();
            return;
        }

        clearDirtyStatus();
        result = nce.call(CONTROLLER + CONTROLLER_METHOD.SAVE_JSON, [selectedTabAppId, _editor.getValue()]);
        if (result.status) {
            nce.updateCubeLeftHandChangedStatus(nce.getSelectedCubeName(), CHANGETYPE.UPDATED);
        } else {
            nce.showNote('Error saving JSON n-cube:
' + result.data);
        }
    }

    function isDirty() {
        return _editor ? !_editor.getSession().getUndoManager().isClean() : false;
    }

    function clearDirtyStatus() {
        var undoMgr;
        if (_editor) {
            undoMgr = _editor.getSession().getUndoManager();
            undoMgr.reset();
            undoMgr.markClean();
        }
        updateDirtyStatus();
    }

    function updateDirtyStatus() {
        var dirty, text;
        dirty = isDirty();
        _saveBtn.prop('disabled', !dirty);
        _saveBtn.html(dirty ? 'Save*' : 'Save');
    }

    function load() {
        var result = nce.call(CONTROLLER + CONTROLLER_METHOD.GET_JSON, [nce.getSelectedTabAppId(), nce.getSelectedCubeName(), {mode:JSON_MODE.PRETTY}], {noResolveRefs:true});
        if (result.status) {
            try {
                _editor.setValue(result.data);
                _editor.clearSelection();
                scrollToSavedPosition();
            } catch (e) {
                nce.showNote('JSON content too large for the JSON Text Editor.  Capture the JSON from the "Revision History" option.');
                console.log(e);
            }
        } else {
            _editor.setValue("Unable to load '" + nce.getSelectedCubeName() + "'. " + result.data);
        }

        clearDirtyStatus();
    }

    function handleCubeSelected() {
        load();
    }

    // Let parent (main frame) know that the child window has loaded.
    // The loading of all of the Javascript (deeply) is continuous on the main thread.
    // Therefore, the setTimeout(, 1) ensures that the main window (parent frame)
    // is called after all Javascript has been loaded.
    if (window.parent.frameLoaded) {
        setTimeout(function () {
            window.parent.frameLoaded(document);
        }, 1);
    }

    return {
        init: init,
        handleCubeSelected: handleCubeSelected,
        load: load
    };

})(jQuery);

function tabActivated(info) {
    NCubeJsonEditor.init(info);
    NCubeJsonEditor.load();
}

function cubeSelected() {
    NCubeJsonEditor.handleCubeSelected();
}

var onNoteEvent = function onNoteEvent(e, element){};<|endoftext|>


<commit_before>define([
  'jquery',
  'lodash'
],
function ($, _) {
  'use strict';

  function GraphTooltip(elem, dashboard, scope, getSeriesFn) {
    var self = this;
    var ctrl = scope.ctrl;
    var panel = ctrl.panel;

    var $tooltip = $('
');

    this.findHoverIndexFromDataPoints = function(posX, series, last) {
      var ps = series.datapoints.pointsize;
      var initial = last*ps;
      var len = series.datapoints.points.length;
      for (var j = initial; j < len; j += ps) {
        if ((series.datapoints.points[initial] != null && series.datapoints.points[j] == null) || series.datapoints.points[j] > posX) {
          return Math.max(j - ps,  0)/ps;
        }
      }
      return j/ps - 1;
    };

    this.findHoverIndexFromData = function(posX, series) {
      var len = series.data.length;
      for (var j = 0; j < len; j++) {
        if (series.data[j][0] > posX) {
          return Math.max(j - 1,  0);
        }
      }
      return j - 1;
    };

    this.showTooltip = function(absoluteTime, innerHtml, pos) {
      var body = '
'+ absoluteTime + '
';
      body += innerHtml + '
';
      $tooltip.html(body).place_tt(pos.pageX + 20, pos.pageY);
    };

    this.getMultiSeriesPlotHoverInfo = function(seriesList, pos) {
      var value, i, series, hoverIndex, hoverDistance, pointTime, yaxis;
      var results = [];

      //now we know the current X (j) position for X and Y values
      var last_value = 0; //needed for stacked values

      for (i = 0; i < seriesList.length; i++) {
        series = seriesList[i];

        if (!series.data.length || (panel.legend.hideEmpty && series.allIsNull)) {
          results.push({ hidden: true, value: 0, yaxis: 0 });
          continue;
        }

        if (!series.data.length || (panel.legend.hideZero && series.allIsZero)) {
          results.push({ hidden: true, value: 0, yaxis: 0 });
          continue;
        }

        hoverIndex = this.findHoverIndexFromData(pos.x, series);
        hoverDistance = Math.abs(pos.x - series.data[hoverIndex][0]);
        pointTime = series.data[hoverIndex][0];

        if (series.stack) {
          if (panel.tooltip.value_type === 'individual') {
            value = series.data[hoverIndex][1];
          } else if (!series.stack) {
            value = series.data[hoverIndex][1];
          } else {
            last_value += series.data[hoverIndex][1];
            value = last_value;
          }
        } else {
          value = series.data[hoverIndex][1];
        }

        // Highlighting multiple Points depending on the plot type
        if (series.lines.steps || series.stack) {
          // stacked and steppedLine plots can have series with different length.
          // Stacked series can increase its length on each new stacked serie if null points found,
          // to speed the index search we begin always on the last found hoverIndex.
          hoverIndex = this.findHoverIndexFromDataPoints(pos.x, series, hoverIndex);
        }

        yaxis = 0;
        if (series.yaxis) {
          yaxis = series.yaxis.n;
        }

        results.push({
          value: value,
          hoverIndex: hoverIndex,
          color: series.color,
          label: series.label,
          time: pointTime,
          distance: hoverDistance,
          yaxis: yaxis,
          index: i
        });
      }

      // Find point which closer to pointer
      results.time = _.min(results, 'distance').time;

      return results;
    };

    elem.mouseleave(function () {
      if (panel.tooltip.shared) {
        var plot = elem.data().plot;
        if (plot) {
          $tooltip.detach();
          plot.unhighlight();
        }
      }

      if (dashboard.sharedCrosshair) {
        ctrl.publishAppEvent('clearCrosshair');
      }
    });

    elem.bind("plothover", function (event, pos, item) {
      var plot = elem.data().plot;
      var plotData = plot.getData();
      var seriesList = getSeriesFn();
      var group, value, absoluteTime, hoverInfo, i, series, seriesHtml, tooltipFormat;

      if (dashboard.sharedCrosshair) {
        ctrl.publishAppEvent('setCrosshair', {pos: pos, scope: scope});
      }

      if (seriesList.length === 0) {
        return;
      }

      if (seriesList[0].hasMsResolution) {
        tooltipFormat = 'YYYY-MM-DD HH:mm:ss.SSS';
      } else {
        tooltipFormat = 'YYYY-MM-DD HH:mm:ss';
      }

      if (panel.tooltip.shared) {
        plot.unhighlight();

        var seriesHoverInfo = self.getMultiSeriesPlotHoverInfo(plotData, pos);

        seriesHtml = '';

        // Dynamically reorder the hovercard for the current time point if the
        // option is enabled, sort by yaxis by default.
        if (panel.tooltip.sort === 2) {
          seriesHoverInfo.sort(function(a, b) {
            return b.value - a.value;
          });
        } else if (panel.tooltip.sort === 1) {
          seriesHoverInfo.sort(function(a, b) {
            return a.value - b.value;
          });
        } else {
          seriesHoverInfo.sort(function(a, b) {
            return a.yaxis - b.yaxis;
          });
        }

        var distance, time;

        for (i = 0; i < seriesHoverInfo.length; i++) {
          hoverInfo = seriesHoverInfo[i];

          if (hoverInfo.hidden) {
            continue;
          }

          if (! distance || hoverInfo.distance < distance) {
            distance = hoverInfo.distance;
            time = hoverInfo.time;
          }

          var highlightClass = '';
          if (item && i === item.seriesIndex) {
            highlightClass = 'graph-tooltip-list-item--highlight';
          }

          series = seriesList[hoverInfo.index];

          value = series.formatValue(hoverInfo.value);

          seriesHtml += '

';
          seriesHtml += ' ' + hoverInfo.label + ':
';
          seriesHtml += '
' + value + '

';
          plot.highlight(hoverInfo.index, hoverInfo.hoverIndex);
        }

        absoluteTime = dashboard.formatDate(time, tooltipFormat);
        self.showTooltip(absoluteTime, seriesHtml, pos);
      }
      // single series tooltip
      else if (item) {
        series = seriesList[item.seriesIndex];
        group = '

';
        group += ' ' + series.label + ':
';

        if (panel.stack && panel.tooltip.value_type === 'individual') {
          value = item.datapoint[1] - item.datapoint[2];
        }
        else {
          value = item.datapoint[1];
        }

        value = series.formatValue(value);

        absoluteTime = dashboard.formatDate(item.datapoint[0], tooltipFormat);

        group += '
' + value + '
';

        self.showTooltip(absoluteTime, group, pos);
      }
      // no hit
      else {
        $tooltip.detach();
      }
    });
  }

  return GraphTooltip;
});
<commit_msg>Missing values, corect tooltip<commit_after>define([
  'jquery',
  'lodash'
],
function ($, _) {
  'use strict';

  function GraphTooltip(elem, dashboard, scope, getSeriesFn) {
    var self = this;
    var ctrl = scope.ctrl;
    var panel = ctrl.panel;

    var $tooltip = $('
');

    this.findHoverIndexFromDataPoints = function(posX, series, last) {
      var ps = series.datapoints.pointsize;
      var initial = last*ps;
      var len = series.datapoints.points.length;
      for (var j = initial; j < len; j += ps) {
        if ((series.datapoints.points[initial] != null && series.datapoints.points[j] == null && ! series.lines.steps) || series.datapoints.points[j] > posX) {
          return Math.max(j - ps,  0)/ps;
        }
      }
      return j/ps - 1;
    };

    this.findHoverIndexFromData = function(posX, series) {
      var len = series.data.length;
      for (var j = 0; j < len; j++) {
        if (series.data[j][0] > posX) {
          return Math.max(j - 1,  0);
        }
      }
      return j - 1;
    };

    this.showTooltip = function(absoluteTime, innerHtml, pos) {
      var body = '
'+ absoluteTime + '
';
      body += innerHtml + '
';
      $tooltip.html(body).place_tt(pos.pageX + 20, pos.pageY);
    };

    this.getMultiSeriesPlotHoverInfo = function(seriesList, pos) {
      var value, i, series, hoverIndex, hoverDistance, pointTime, yaxis;
      var results = [];

      //now we know the current X (j) position for X and Y values
      var last_value = 0; //needed for stacked values

      for (i = 0; i < seriesList.length; i++) {
        series = seriesList[i];

        if (!series.data.length || (panel.legend.hideEmpty && series.allIsNull)) {
          results.push({ hidden: true, value: 0, yaxis: 0 });
          continue;
        }

        if (!series.data.length || (panel.legend.hideZero && series.allIsZero)) {
          results.push({ hidden: true, value: 0, yaxis: 0 });
          continue;
        }

        hoverIndex = this.findHoverIndexFromData(pos.x, series);
        hoverDistance = pos.x - series.data[hoverIndex][0];
        pointTime = series.data[hoverIndex][0];

        if (series.stack) {
          if (panel.tooltip.value_type === 'individual') {
            value = series.data[hoverIndex][1];
          } else if (!series.stack) {
            value = series.data[hoverIndex][1];
          } else {
            last_value += series.data[hoverIndex][1];
            value = last_value;
          }
        } else {
          value = series.data[hoverIndex][1];
        }

        // Highlighting multiple Points depending on the plot type
        if (series.lines.steps || series.stack) {
          // stacked and steppedLine plots can have series with different length.
          // Stacked series can increase its length on each new stacked serie if null points found,
          // to speed the index search we begin always on the last found hoverIndex.
          hoverIndex = this.findHoverIndexFromDataPoints(pos.x, series, hoverIndex);
        }

        yaxis = 0;
        if (series.yaxis) {
          yaxis = series.yaxis.n;
        }

        results.push({
          value: value,
          hoverIndex: hoverIndex,
          color: series.color,
          label: series.label,
          time: pointTime,
          distance: hoverDistance,
          yaxis: yaxis,
          index: i
        });
      }

      return results;
    };

    elem.mouseleave(function () {
      if (panel.tooltip.shared) {
        var plot = elem.data().plot;
        if (plot) {
          $tooltip.detach();
          plot.unhighlight();
        }
      }

      if (dashboard.sharedCrosshair) {
        ctrl.publishAppEvent('clearCrosshair');
      }
    });

    elem.bind("plothover", function (event, pos, item) {
      var plot = elem.data().plot;
      var plotData = plot.getData();
      var seriesList = getSeriesFn();
      var group, value, absoluteTime, hoverInfo, i, series, seriesHtml, tooltipFormat;

      if (dashboard.sharedCrosshair) {
        ctrl.publishAppEvent('setCrosshair', {pos: pos, scope: scope});
      }

      if (seriesList.length === 0) {
        return;
      }

      if (seriesList[0].hasMsResolution) {
        tooltipFormat = 'YYYY-MM-DD HH:mm:ss.SSS';
      } else {
        tooltipFormat = 'YYYY-MM-DD HH:mm:ss';
      }

      if (panel.tooltip.shared) {
        plot.unhighlight();

        var seriesHoverInfo = self.getMultiSeriesPlotHoverInfo(plotData, pos);

        seriesHtml = '';

        // Dynamically reorder the hovercard for the current time point if the
        // option is enabled, sort by yaxis by default.
        if (panel.tooltip.sort === 2) {
          seriesHoverInfo.sort(function(a, b) {
            return b.value - a.value;
          });
        } else if (panel.tooltip.sort === 1) {
          seriesHoverInfo.sort(function(a, b) {
            return a.value - b.value;
          });
        } else {
          seriesHoverInfo.sort(function(a, b) {
            return a.yaxis - b.yaxis;
          });
        }

        var distance, time;

        for (i = 0; i < seriesHoverInfo.length; i++) {
          hoverInfo = seriesHoverInfo[i];

          if (hoverInfo.hidden) {
            continue;
          }

          if (! distance || (hoverInfo.distance >=0 && (hoverInfo.distance < distance || distance < 0)) || (hoverInfo.distance < 0 && hoverInfo.distance > distance)) {
            distance = hoverInfo.distance;
            time = hoverInfo.time;
          }

          var highlightClass = '';
          if (item && i === item.seriesIndex) {
            highlightClass = 'graph-tooltip-list-item--highlight';
          }

          series = seriesList[hoverInfo.index];

          value = series.formatValue(hoverInfo.value);

          seriesHtml += '

';
          seriesHtml += ' ' + hoverInfo.label + ':
';
          seriesHtml += '
' + value + '

';
          plot.highlight(hoverInfo.index, hoverInfo.hoverIndex);
        }

        absoluteTime = dashboard.formatDate(time, tooltipFormat);
        self.showTooltip(absoluteTime, seriesHtml, pos);
      }
      // single series tooltip
      else if (item) {
        series = seriesList[item.seriesIndex];
        group = '

';
        group += ' ' + series.label + ':
';

        if (panel.stack && panel.tooltip.value_type === 'individual') {
          value = item.datapoint[1] - item.datapoint[2];
        }
        else {
          value = item.datapoint[1];
        }

        value = series.formatValue(value);

        absoluteTime = dashboard.formatDate(item.datapoint[0], tooltipFormat);

        group += '
' + value + '
';

        self.showTooltip(absoluteTime, group, pos);
      }
      // no hit
      else {
        $tooltip.detach();
      }
    });
  }

  return GraphTooltip;
});
<|endoftext|>


<commit_before>deviceTypes.freebox={
    name:'freebox',
    onChange:function(){
        var device=$('
')
            .append('Code télécommande')
            .append('
<input class="form-control" placeholder="Code" id="code" name="code"></select>
')
            .appendTo('#commands');
        var device=$('
')
            .append('Blast through (hd1/hd2/...)')
            .append('
<input class="form-control" id="freebox_name" name="freebox_name"></input>
')
            .appendTo('#commands');
        return 'dynamic';
    },
    onAdd:function(){
    },
    onSave:function(data){
        data.append('code', $('#code').val());
        data.append('fbxName', $('#freebox_name').val())
    },
    onServerSave:function(device, body){
        var ptType={
            subdevices:[
                {
                    name:"power",
                    type:'switch',
                    category:'actuator',
                    commands:
                    {
                        'on':'http://'+body.fbxName+'.freebox.fr/pub/remote_control?code='+body.code+'&key=power',
                        'off':'http://'+body.fbxName+'.freebox.fr/pub/remote_control?code='+body.code+'&key=power',
                    }
                },
                {
                    name:"mute",
                    type:'switch',
                    category:'actuator',
                    commands:
                    {
                        'on':'http://'+body.fbxName+'.freebox.fr/pub/remote_control?code='+body.code+'&key=mute',
                        'off':'http://'+body.fbxName+'.freebox.fr/pub/remote_control?code='+body.code+'&key=mute',
                    }
                },
                {
                    name:"volume",
                    type:'analogic',
                    category:'actuator',
                    commands:
                    {
                        'up':'http://'+body.fbxName+'.freebox.fr/pub/remote_control?code='+body.code+'&key=vol_inc',
                        'down':'http://'+body.fbxName+'.freebox.fr/pub/remote_control?code='+body.code+'&key=vol_dec',
                    },
                },
                {
                    name:"channels",
                    type:'values',
                    category:'actuator',
                    commands:
                    {

                    },
                },
            ],
            commands:{}
        };

        $.map([
            'power','tv','list','0','1','2','3','4','5','6','7','8','9','info', 'mail','help','pip','epg','media','options','vol_inc','vol_dec','prgm_inc','prgm_dec',
            'ok','up','left','right','down','mute','home','rec','bwd','prev','play','fwd','next','red','yellow','green','blue'], function(item){
           var obj={};
           ptType.commands[item]='http://'+body.fbxName+'.freebox.fr/pub/remote_control?code='+body.code+'&key='+item+'&long=false';
           return obj;
        });
        for(var i=1;i<1000;i++)
        {
            if(i<10)
            {
                ptType.subdevices[3].commands[i]='http://'+body.fbxName+'.freebox.fr/pub/remote_control?code='+body.code+'&key='+i+'&long=false';
            }
            else
            {
                ptType.subdevices[3].commands[i]=[];
                for(j=i;Math.floor(j)>0;j=j/10)
                {
                    if(j>10)
                        ptType.subdevices[3].commands[i].unshift('http://'+body.fbxName+'.freebox.fr/pub/remote_control?code='+body.code+'&key='+Math.floor(j%10)+'&long=false');
                    else
                        ptType.subdevices[3].commands[i].unshift('http://'+body.fbxName+'.freebox.fr/pub/remote_control?code='+body.code+'&key='+Math.floor(j%10)+'&long=true');
                }
            }
        }
        $.extend(device, ptType);
    }
};  <commit_msg>small update<commit_after>deviceTypes.freebox={
    name:'freebox',
    onChange:function(){
        var device=$('
')
            .append('Code télécommande')
            .append('
<input class="form-control" placeholder="Code" id="code" name="code"></select>
')
            .appendTo('#commands');
        var device=$('
')
            .append('Blast through (hd1/hd2/...)')
            .append('
<input class="form-control" id="freebox_name" name="freebox_name"></input>
')
            .appendTo('#commands');
        return 'dynamic';
    },
    onAdd:function(){
    },
    onSave:function(data){
        data.append('code', $('#code').val());
        data.append('fbxName', $('#freebox_name').val())
    },
    onServerSave:function(device, body){
        var ptType={
            subdevices:[
                {
                    name:"power",
                    type:'switch',
                    category:'actuator',
                    commands:
                    {
                        'on':'http://'+body.fbxName+'.freebox.fr/pub/remote_control?code='+body.code+'&key=power',
                        'off':'http://'+body.fbxName+'.freebox.fr/pub/remote_control?code='+body.code+'&key=power',
                    }
                },
                {
                    name:"mute",
                    type:'switch',
                    category:'actuator',
                    commands:
                    {
                        'on':'http://'+body.fbxName+'.freebox.fr/pub/remote_control?code='+body.code+'&key=mute',
                        'off':'http://'+body.fbxName+'.freebox.fr/pub/remote_control?code='+body.code+'&key=mute',
                    }
                },
                {
                    name:"volume",
                    type:'analogic',
                    category:'actuator',
                    commands:
                    {
                        'up':'http://'+body.fbxName+'.freebox.fr/pub/remote_control?code='+body.code+'&key=vol_inc',
                        'down':'http://'+body.fbxName+'.freebox.fr/pub/remote_control?code='+body.code+'&key=vol_dec',
                    },
                },
                {
                    name:"channels",
                    type:'values',
                    category:'actuator',
                    commands:
                    {

                    },
                },
            ],
            commands:{}
        };

        $.map([
            'power','tv','list','0','1','2','3','4','5','6','7','8','9','info', 'mail','help','pip','epg','media','options','vol_inc','vol_dec','prgm_inc','prgm_dec',
            'ok','up','left','right','down','mute','home','rec','bwd','prev','play','fwd','next','red','yellow','green','blue'], function(item){
           var obj={};
           ptType.commands[item]='http://'+body.fbxName+'.freebox.fr/pub/remote_control?code='+body.code+'&key='+item+'&long=false';
           return obj;
        });
        for(var i=1;i<1000;i++)
        {
            if(i<10)
            {
                ptType.subdevices[3].commands[i]='http://'+body.fbxName+'.freebox.fr/pub/remote_control?code='+body.code+'&key='+i+'&long=false';
            }
            else
            {
                ptType.subdevices[3].commands[i]=[];
                for(j=i;Math.floor(j)>0;j=j/10)
                {
                    var long=(j>10).toString().toLowerCase();
                    ptType.subdevices[3].commands[i].unshift('http://'+body.fbxName+'.freebox.fr/pub/remote_control?code='+body.code+'&key='+Math.floor(j%10)+'&long='+long);
                }
            }
        }
        $.extend(device, ptType);
    }
};  <|endoftext|>


<commit_before><commit_msg>ADI view supports vertical/horizontal resizing. Options saving/loading. Visibility toggling.<commit_after><|endoftext|>


<commit_before>angular.module('collabjs.controllers')
  .controller('RegistrationController', ['$scope', '$location', 'accountService',
    function ($scope, $location, accountService) {
      'use strict';

      $scope.error = false;
      $scope.account = '';
      $scope.name = '';
      $scope.email = '';
      $scope.password = '';
      $scope.confirmPassword = '';

      $scope.register = function () {
        accountService
          .createAccount($scope.name, $scope.email, $scope.password)
          .then(
            function () { $location.path('/').replace(); },
            function (err) {
              $scope.error = err;
              $scope.password = '';
              $scope.confirmPassword = '';
            }
          );
      };
    }]);<commit_msg>Update RegistrationController.js<commit_after>angular.module('collabjs.controllers')
  .controller('RegistrationController', ['$scope', '$location', 'accountService',
    function ($scope, $location, accountService) {
      'use strict';

      $scope.error = false;
      $scope.account = '';
      $scope.name = '';
      $scope.email = '';
      $scope.password = '';
      $scope.confirmPassword = '';

      $scope.register = function () {
        accountService
          .createAccount($scope.account, $scope.name, $scope.email, $scope.password)
          .then(
            function () { $location.path('/').replace(); },
            function (err) {
              $scope.error = err;
              $scope.password = '';
              $scope.confirmPassword = '';
            }
          );
      };
    }]);
<|endoftext|>