<commit_before>/*!
    Copyright (C) 2016 Google Inc.
    Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
*/

describe("display prefs model", function() {

  var display_prefs, exp;
  beforeAll(function() {
    display_prefs = new CMS.Models.DisplayPrefs();
    exp = CMS.Models.DisplayPrefs.exports;
  });

  afterEach(function() {
    display_prefs.removeAttr(window.location.pathname);
    display_prefs.isNew() || display_prefs.destroy();
  });

  describe("#init", function( ){
    it("sets autoupdate to true by default", function() {
      expect(display_prefs.autoupdate).toBe(true);
    });

  });

  describe("low level accessors", function() {
    beforeEach(function() {
      display_prefs.attr("foo", "bar");
    });

    afterEach(function() {
      display_prefs.removeAttr("foo");
      display_prefs.removeAttr("baz");
    });

    describe("#makeObject", function() {

      it("returns the model itself with no args", function() {
        expect(display_prefs.makeObject()).toBe(display_prefs);
      });

      it("returns an empty can.Observe when the key does not resolve to an Observable", function() {
        expect(display_prefs.makeObject("foo")).not.toBe("bar");
        var newval = display_prefs.makeObject("baz");
        expect(newval instanceof can.Observe).toBeTruthy();
        expect(newval.serialize()).toEqual({});
      });

      it("makes a nested path of can.Observes when the key has multiple levels", function() {
        var newval = display_prefs.makeObject("baz", "quux");
        expect(display_prefs.baz.quux instanceof can.Observe).toBeTruthy();
      });

    });

    describe("#getObject", function() {
      it("returns a set value whether or not the value is an Observe", function() {
        expect(display_prefs.getObject("foo")).toBe("bar");
        display_prefs.makeObject("baz", "quux");
        expect(display_prefs.getObject("baz").serialize()).toEqual({ "quux" : {}});
      });

      it("returns undefined when the key is not found", function(){
        expect(display_prefs.getObject("xyzzy")).not.toBeDefined();
      });
    });
  });

  describe("top nav", function () {
    afterEach(function() {
      display_prefs.resetPagePrefs();
      //display_prefs.removeAttr(exp.path);
    });

    describe("hiddenness", function () {
      it("sets nav hidden", function() {
        display_prefs.setTopNavHidden("this arg is ignored", true);

        expect(
          display_prefs.attr(exp.path).top_nav.is_hidden
        ).toBe(true);
      });

      it("gets nav hidden", function () {
        display_prefs.setTopNavHidden("this arg is ignored", true);

        expect(display_prefs.getTopNavHidden()).toBe(true);
      });

      it("returns false by default", function () {
        expect(display_prefs.getTopNavHidden()).toBe(false);
      });
    });

    describe("widget list", function () {
      it("sets widget list", function () {
        display_prefs.setTopNavWidgets("this arg is ignored", {a:1, b: 2});

        expect(
          display_prefs.attr(exp.path).top_nav.widget_list.serialize()
        ).toEqual({a: 1, b: 2});
      });

      it("gets widget list", function () {
        display_prefs.setTopNavWidgets("this arg is ignored", {a: 1, b: 2});

        expect(display_prefs.getTopNavWidgets()).toEqual({a: 1, b: 2});
      });

      it("returns {} by default", function () {
        expect(display_prefs.getTopNavWidgets()).toEqual({});
      });
    });
  });

   describe("filter hiding", function () {
     afterEach(function() {
       display_prefs.resetPagePrefs();
     });

     it("sets filter hidden", function() {
       display_prefs.setFilterHidden(true);

       expect(
         display_prefs.attr(exp.path).filter_widget.is_hidden
       ).toBe(true);
     });

     it("gets filter hidden", function () {
       display_prefs.setFilterHidden(true);

       expect(display_prefs.getFilterHidden()).toBe(true);
     });

     it("returns false by default", function () {
       expect(display_prefs.getFilterHidden()).toBe(false);
     });
   });

  describe("#setCollapsed", function() {
    afterEach(function() {
      display_prefs.removeAttr(exp.COLLAPSE);
      display_prefs.removeAttr(exp.path);
    });

    it("sets the collapse value for a widget", function() {
      display_prefs.setCollapsed("this arg is ignored", "foo", true);

      expect(display_prefs.attr([exp.path, exp.COLLAPSE, "foo"].join("."))).toBe(true);
    });
  });

  function getSpecs (func, token, fooValue, barValue) {
    var fooMatcher = typeof fooValue === "object" ? "toEqual" : "toBe";
    var barMatcher = typeof barValue === "object" ? "toEqual" : "toBe";

    return function() {
      function getTest() {
        var fooActual = display_prefs[func]("unit_test", "foo");
        var barActual = display_prefs[func]("unit_test", "bar");

        expect(fooActual.serialize ? fooActual.serialize() : fooActual)[fooMatcher](fooValue);
        expect(barActual.serialize ? barActual.serialize() : barActual)[barMatcher](barValue);
      }

      var exp_token;
      beforeEach(function() {
        exp_token = exp[token]; //late binding b/c not available when describe block is created
      });

      // TODO: figure out why these fail, error is "can.Map: Object does not exist thrown"
      describe("when set for a page", function() {
        beforeEach(function() {
          display_prefs.makeObject(exp.path, exp_token).attr("foo", fooValue);
          display_prefs.makeObject(exp.path, exp_token).attr("bar", barValue);
        });
        afterEach(function() {
          display_prefs.removeAttr(exp.path);
        });

        it("returns the value set for the page", getTest);
      });

      describe("when not set for a page", function() {
        beforeEach(function() {
          display_prefs.makeObject(exp_token, "unit_test").attr("foo", fooValue);
          display_prefs.makeObject(exp_token, "unit_test").attr("bar", barValue);
        });
        afterEach(function() {
          display_prefs.removeAttr(exp.path);
          display_prefs.removeAttr(exp_token);
        });

        it("returns the value set for the page type default", getTest);

        it("sets the default value as the page value", function() {
          display_prefs[func]("unit_test", "foo");
          var fooActual = display_prefs.attr([exp.path, exp_token, "foo"].join("."));
          expect(fooActual.serialize ? fooActual.serialize() : fooActual)[fooMatcher](fooValue);
        });
      });
    };
  }

  describe("#getCollapsed", getSpecs("getCollapsed", "COLLAPSE", true, false));

  describe("#getSorts", getSpecs("getSorts", "SORTS", ["baz, quux"], ["thud", "jeek"]));

  function setSpecs(func, token, fooValue, barValue) {
    return function() {
      var exp_token;
      beforeEach(function() {
        exp_token = exp[token];
      });
      afterEach(function() {
        display_prefs.removeAttr(exp_token);
        display_prefs.removeAttr(exp.path);
      });

      it("sets the value for a widget", function() {
        display_prefs[func]("this arg is ignored", "foo", fooValue);
        var fooActual  = display_prefs.attr([exp.path, exp_token, "foo"].join("."));
        expect(fooActual.serialize ? fooActual.serialize() : fooActual).toEqual(fooValue);
      });

      it("sets all values as a collection", function() {
        display_prefs[func]("this arg is ignored", {"foo" : fooValue, "bar" : barValue});
        var fooActual = display_prefs.attr([exp.path, exp_token, "foo"].join("."));
        var barActual = display_prefs.attr([exp.path, exp_token, "bar"].join("."));
        expect(fooActual.serialize ? fooActual.serialize() : fooActual).toEqual(fooValue);
        expect(barActual.serialize ? barActual.serialize() : barActual).toEqual(barValue);
      });
    };
  }

  describe("#setSorts", setSpecs("setSorts", "SORTS", ["bar", "baz"], ["thud", "jeek"]));

  describe("#getWidgetHeights", function() {});

  describe("#getWidgetHeight", getSpecs("getWidgetHeight", "HEIGHTS", 100, 200));

  describe("#setWidgetHeight", setSpecs("setWidgetHeight", "HEIGHTS", 100, 200));

  describe("#getColumnWidths", getSpecs("getColumnWidths", "COLUMNS", [6, 6], [8, 4]));

  describe("#getColumnWidthsForSelector", function() {
    it("calls getColumnWidths with the ID of the supplied element", function() {
      var $foo = affix("#foo");
      var $bar = affix("#bar");

      spyOn(display_prefs, "getColumnWidths");

      display_prefs.getColumnWidthsForSelector("unit_test", $foo);
      expect(display_prefs.getColumnWidths).toHaveBeenCalledWith("unit_test", "foo");
    });
  });

  describe("#setColumnWidths", setSpecs("setColumnWidths", "COLUMNS", [6,6], [4,8]));

  describe("Set/Reset functions", function() {

    describe("#resetPagePrefs", function() {

      beforeEach(function() {
        can.each([exp.COLUMNS, exp.HEIGHTS, exp.SORTS, exp.COLLAPSE], function(exp_token) {
          display_prefs.makeObject(exp_token, "unit_test").attr("foo", "bar"); //page type defaults
          display_prefs.makeObject(exp.path, exp_token).attr("foo", "baz"); //page custom settings
        });
      });
      afterEach(function() {
        display_prefs.removeAttr(exp.path);
        can.each([exp.COLUMNS, exp.HEIGHTS, exp.SORTS, exp.COLLAPSE], function(exp_token) {
          display_prefs.removeAttr(exp_token);
        });
      });

      it("sets the page layout to the default for the page type", function() {
        display_prefs.resetPagePrefs();
        can.each(["getSorts", "getCollapsed", "getWidgetHeight", "getColumnWidths"], function(func) {
          expect(display_prefs[func]("unit_test", "foo")).toBe("bar");
        });
      });

    });

    describe("#setPageAsDefault", function() {
      beforeEach(function() {
        can.each([exp.COLUMNS, exp.HEIGHTS, exp.SORTS, exp.COLLAPSE], function(exp_token) {
          display_prefs.makeObject(exp_token, "unit_test").attr("foo", "bar"); //page type defaults
          display_prefs.makeObject(exp.path, exp_token).attr("foo", "baz"); //page custom settings
        });
      });
      afterEach(function() {
        display_prefs.removeAttr(exp.path);
        can.each([exp.COLUMNS, exp.HEIGHTS, exp.SORTS, exp.COLLAPSE], function(exp_token) {
          display_prefs.removeAttr(exp_token);
        });
      });

      it("sets the page layout to the default for the page type", function() {
        display_prefs.setPageAsDefault("unit_test");
        can.each([exp.COLUMNS, exp.HEIGHTS, exp.SORTS, exp.COLLAPSE], function(exp_token) {
          expect(display_prefs.attr([exp_token, "unit_test", "foo"].join("."))).toBe("baz");
        })
      });

      it("keeps the page and the defaults separated", function() {
        display_prefs.setPageAsDefault("unit_test");
        can.each(["setColumnWidths", "setCollapsed", "setWidgetHeight", "setSorts"], function(func) {
          display_prefs[func]("unit_test", "foo", "quux");
        });
        can.each([exp.COLUMNS, exp.HEIGHTS, exp.SORTS, exp.COLLAPSE], function(exp_token) {
          expect(display_prefs.attr([exp_token, "unit_test", "foo"].join("."))).toBe("baz");
        });
      });

    });

  });

  describe("#findAll", function() {
    var dp_noversion, dp2_outdated, dp3_current;
    beforeEach(function() {
      dp_noversion = new CMS.Models.DisplayPrefs({});
      dp2_outdated = new CMS.Models.DisplayPrefs({ version : 1});
      dp3_current = new CMS.Models.DisplayPrefs({ version : CMS.Models.DisplayPrefs.version });

      spyOn(can.Model.LocalStorage, "findAll").and.returnValue(new $.Deferred().resolve([dp_noversion, dp2_outdated, dp3_current]));
      spyOn(dp_noversion, "destroy");
      spyOn(dp2_outdated, "destroy");
      spyOn(dp3_current, "destroy");
    });
    it("deletes any prefs that do not have a version set", function(done) {
      var dfd = CMS.Models.DisplayPrefs.findAll().done(function(dps) {
        expect(dps).not.toContain(dp_noversion);
        expect(dp_noversion.destroy).toHaveBeenCalled();
      });

      waitsFor(function() { //sanity check --ensure deferred resolves/rejects
        return dfd.state() !== "pending";
      }, done);
    });
    it("deletes any prefs that have an out of date version", function() {
      CMS.Models.DisplayPrefs.findAll().done(function(dps) {
        expect(dps).not.toContain(dp2_outdated);
        expect(dp2_outdated.destroy).toHaveBeenCalled();
      });
    });
    it("retains any prefs that do not have a version set", function() {
      CMS.Models.DisplayPrefs.findAll().done(function(dps) {
        expect(dps).toContain(dp3_current);
        expect(dp3_current.destroy).not.toHaveBeenCalled();
      });
    });
  });

  describe("#findOne", function() {
    var dp_noversion, dp2_outdated, dp3_current;
    beforeEach(function() {
      dp_noversion = new CMS.Models.DisplayPrefs({});
      dp2_outdated = new CMS.Models.DisplayPrefs({ version : 1});
      dp3_current = new CMS.Models.DisplayPrefs({ version : CMS.Models.DisplayPrefs.version });
    });
    it("404s if the display pref does not have a version set", function(done) {
      spyOn(can.Model.LocalStorage, "findOne").and.returnValue(new $.Deferred().resolve(dp_noversion));
      spyOn(dp_noversion, "destroy");
      var dfd = CMS.Models.DisplayPrefs.findOne().done(function(dps) {
        fail("Should not have resolved findOne for the unversioned display pref");
      }).fail(function(pseudoxhr) {
        expect(pseudoxhr.status).toBe(404);
        expect(dp_noversion.destroy).toHaveBeenCalled();
      });
      waitsFor(function() { //sanity check --ensure deferred resolves/rejects
        return dfd.state() !== "pending";
      }, done);
    });
    it("404s if the display pref has an out of date version", function() {
      spyOn(can.Model.LocalStorage, "findOne").and.returnValue(new $.Deferred().resolve(dp2_outdated));
      spyOn(dp2_outdated, "destroy");
      CMS.Models.DisplayPrefs.findOne().done(function(dps) {
        fail("Should not have resolved findOne for the outdated display pref");
      }).fail(function(pseudoxhr) {
        expect(pseudoxhr.status).toBe(404);
        expect(dp2_outdated.destroy).toHaveBeenCalled();
      });
    });
    it("retains any prefs that do not have a version set", function() {
      spyOn(can.Model.LocalStorage, "findOne").and.returnValue(new $.Deferred().resolve(dp3_current));
      spyOn(dp3_current, "destroy");
      CMS.Models.DisplayPrefs.findOne().done(function(dps) {
        expect(dp3_current.destroy).not.toHaveBeenCalled();
      }).fail(function() {
        fail("Should have resolved on findOne for the current display pref");
      });
    });
  });

});
<commit_msg>Fix whitespace issues in display_prefs_spec.js<commit_after>/*!
    Copyright (C) 2016 Google Inc.
    Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
*/

describe("display prefs model", function() {

  var display_prefs, exp;
  beforeAll(function() {
    display_prefs = new CMS.Models.DisplayPrefs();
    exp = CMS.Models.DisplayPrefs.exports;
  });

  afterEach(function() {
    display_prefs.removeAttr(window.location.pathname);
    display_prefs.isNew() || display_prefs.destroy();
  });

  describe("#init", function( ){
    it("sets autoupdate to true by default", function() {
      expect(display_prefs.autoupdate).toBe(true);
    });

  });

  describe("low level accessors", function() {
    beforeEach(function() {
      display_prefs.attr("foo", "bar");
    });

    afterEach(function() {
      display_prefs.removeAttr("foo");
      display_prefs.removeAttr("baz");
    });

    describe("#makeObject", function() {

      it("returns the model itself with no args", function() {
        expect(display_prefs.makeObject()).toBe(display_prefs);
      });

      it("returns an empty can.Observe when the key does not resolve to an Observable", function() {
        expect(display_prefs.makeObject("foo")).not.toBe("bar");
        var newval = display_prefs.makeObject("baz");
        expect(newval instanceof can.Observe).toBeTruthy();
        expect(newval.serialize()).toEqual({});
      });

      it("makes a nested path of can.Observes when the key has multiple levels", function() {
        var newval = display_prefs.makeObject("baz", "quux");
        expect(display_prefs.baz.quux instanceof can.Observe).toBeTruthy();
      });

    });

    describe("#getObject", function() {
      it("returns a set value whether or not the value is an Observe", function() {
        expect(display_prefs.getObject("foo")).toBe("bar");
        display_prefs.makeObject("baz", "quux");
        expect(display_prefs.getObject("baz").serialize()).toEqual({ "quux" : {}});
      });

      it("returns undefined when the key is not found", function(){
        expect(display_prefs.getObject("xyzzy")).not.toBeDefined();
      });
    });
  });

  describe("top nav", function () {
    afterEach(function() {
      display_prefs.resetPagePrefs();
      //display_prefs.removeAttr(exp.path);
    });

    describe("hiddenness", function () {
      it("sets nav hidden", function() {
        display_prefs.setTopNavHidden("this arg is ignored", true);
        expect(
          display_prefs.attr(exp.path).top_nav.is_hidden
        ).toBe(true);
      });

      it("gets nav hidden", function () {
        display_prefs.setTopNavHidden("this arg is ignored", true);

        expect(display_prefs.getTopNavHidden()).toBe(true);
      });

      it("returns false by default", function () {
        expect(display_prefs.getTopNavHidden()).toBe(false);
      });
    });

    describe("widget list", function () {
      it("sets widget list", function () {
        display_prefs.setTopNavWidgets("this arg is ignored", {a:1, b: 2});

        expect(
          display_prefs.attr(exp.path).top_nav.widget_list.serialize()
        ).toEqual({a: 1, b: 2});
      });

      it("gets widget list", function () {
        display_prefs.setTopNavWidgets("this arg is ignored", {a: 1, b: 2});

        expect(display_prefs.getTopNavWidgets()).toEqual({a: 1, b: 2});
      });

      it("returns {} by default", function () {
        expect(display_prefs.getTopNavWidgets()).toEqual({});
      });
    });
  });

   describe("filter hiding", function () {
     afterEach(function() {
       display_prefs.resetPagePrefs();
     });

     it("sets filter hidden", function() {
       display_prefs.setFilterHidden(true);

       expect(
         display_prefs.attr(exp.path).filter_widget.is_hidden
       ).toBe(true);
     });

     it("gets filter hidden", function () {
       display_prefs.setFilterHidden(true);

       expect(display_prefs.getFilterHidden()).toBe(true);
     });

     it("returns false by default", function () {
       expect(display_prefs.getFilterHidden()).toBe(false);
     });
   });

  describe("#setCollapsed", function() {
    afterEach(function() {
      display_prefs.removeAttr(exp.COLLAPSE);
      display_prefs.removeAttr(exp.path);
    });

    it("sets the collapse value for a widget", function() {
      display_prefs.setCollapsed("this arg is ignored", "foo", true);

      expect(display_prefs.attr([exp.path, exp.COLLAPSE, "foo"].join("."))).toBe(true);
    });
  });

  function getSpecs (func, token, fooValue, barValue) {
    var fooMatcher = typeof fooValue === "object" ? "toEqual" : "toBe";
    var barMatcher = typeof barValue === "object" ? "toEqual" : "toBe";

    return function() {
      function getTest() {
        var fooActual = display_prefs[func]("unit_test", "foo");
        var barActual = display_prefs[func]("unit_test", "bar");

        expect(fooActual.serialize ? fooActual.serialize() : fooActual)[fooMatcher](fooValue);
        expect(barActual.serialize ? barActual.serialize() : barActual)[barMatcher](barValue);
      }

      var exp_token;
      beforeEach(function() {
        exp_token = exp[token]; //late binding b/c not available when describe block is created
      });

      // TODO: figure out why these fail, error is "can.Map: Object does not exist thrown"
      describe("when set for a page", function() {
        beforeEach(function() {
          display_prefs.makeObject(exp.path, exp_token).attr("foo", fooValue);
          display_prefs.makeObject(exp.path, exp_token).attr("bar", barValue);
        });
        afterEach(function() {
          display_prefs.removeAttr(exp.path);
        });

        it("returns the value set for the page", getTest);
      });

      describe("when not set for a page", function() {
        beforeEach(function() {
          display_prefs.makeObject(exp_token, "unit_test").attr("foo", fooValue);
          display_prefs.makeObject(exp_token, "unit_test").attr("bar", barValue);
        });
        afterEach(function() {
          display_prefs.removeAttr(exp.path);
          display_prefs.removeAttr(exp_token);
        });

        it("returns the value set for the page type default", getTest);

        it("sets the default value as the page value", function() {
          display_prefs[func]("unit_test", "foo");
          var fooActual = display_prefs.attr([exp.path, exp_token, "foo"].join("."));
          expect(fooActual.serialize ? fooActual.serialize() : fooActual)[fooMatcher](fooValue);
        });
      });
    };
  }

  describe("#getCollapsed", getSpecs("getCollapsed", "COLLAPSE", true, false));

  describe("#getSorts", getSpecs("getSorts", "SORTS", ["baz, quux"], ["thud", "jeek"]));

  function setSpecs(func, token, fooValue, barValue) {
    return function() {
      var exp_token;
      beforeEach(function() {
        exp_token = exp[token];
      });
      afterEach(function() {
        display_prefs.removeAttr(exp_token);
        display_prefs.removeAttr(exp.path);
      });

      it("sets the value for a widget", function() {
        display_prefs[func]("this arg is ignored", "foo", fooValue);
        var fooActual  = display_prefs.attr([exp.path, exp_token, "foo"].join("."));
        expect(fooActual.serialize ? fooActual.serialize() : fooActual).toEqual(fooValue);
      });

      it("sets all values as a collection", function() {
        display_prefs[func]("this arg is ignored", {"foo" : fooValue, "bar" : barValue});
        var fooActual = display_prefs.attr([exp.path, exp_token, "foo"].join("."));
        var barActual = display_prefs.attr([exp.path, exp_token, "bar"].join("."));
        expect(fooActual.serialize ? fooActual.serialize() : fooActual).toEqual(fooValue);
        expect(barActual.serialize ? barActual.serialize() : barActual).toEqual(barValue);
      });
    };
  }

  describe("#setSorts", setSpecs("setSorts", "SORTS", ["bar", "baz"], ["thud", "jeek"]));

  describe("#getWidgetHeights", function() {});

  describe("#getWidgetHeight", getSpecs("getWidgetHeight", "HEIGHTS", 100, 200));

  describe("#setWidgetHeight", setSpecs("setWidgetHeight", "HEIGHTS", 100, 200));

  describe("#getColumnWidths", getSpecs("getColumnWidths", "COLUMNS", [6, 6], [8, 4]));

  describe("#getColumnWidthsForSelector", function() {
    it("calls getColumnWidths with the ID of the supplied element", function() {
      var $foo = affix("#foo");
      var $bar = affix("#bar");

      spyOn(display_prefs, "getColumnWidths");

      display_prefs.getColumnWidthsForSelector("unit_test", $foo);
      expect(display_prefs.getColumnWidths).toHaveBeenCalledWith("unit_test", "foo");
    });
  });

  describe("#setColumnWidths", setSpecs("setColumnWidths", "COLUMNS", [6,6], [4,8]));

  describe("Set/Reset functions", function() {

    describe("#resetPagePrefs", function() {

      beforeEach(function() {
        can.each([exp.COLUMNS, exp.HEIGHTS, exp.SORTS, exp.COLLAPSE], function(exp_token) {
          display_prefs.makeObject(exp_token, "unit_test").attr("foo", "bar"); //page type defaults
          display_prefs.makeObject(exp.path, exp_token).attr("foo", "baz"); //page custom settings
        });
      });
      afterEach(function() {
        display_prefs.removeAttr(exp.path);
        can.each([exp.COLUMNS, exp.HEIGHTS, exp.SORTS, exp.COLLAPSE], function(exp_token) {
          display_prefs.removeAttr(exp_token);
        });
      });

      it("sets the page layout to the default for the page type", function() {
        display_prefs.resetPagePrefs();
        can.each(["getSorts", "getCollapsed", "getWidgetHeight", "getColumnWidths"], function(func) {
          expect(display_prefs[func]("unit_test", "foo")).toBe("bar");
        });
      });

    });

    describe("#setPageAsDefault", function() {
      beforeEach(function() {
        can.each([exp.COLUMNS, exp.HEIGHTS, exp.SORTS, exp.COLLAPSE], function(exp_token) {
          display_prefs.makeObject(exp_token, "unit_test").attr("foo", "bar"); //page type defaults
          display_prefs.makeObject(exp.path, exp_token).attr("foo", "baz"); //page custom settings
        });
      });
      afterEach(function() {
        display_prefs.removeAttr(exp.path);
        can.each([exp.COLUMNS, exp.HEIGHTS, exp.SORTS, exp.COLLAPSE], function(exp_token) {
          display_prefs.removeAttr(exp_token);
        });
      });

      it("sets the page layout to the default for the page type", function() {
        display_prefs.setPageAsDefault("unit_test");
        can.each([exp.COLUMNS, exp.HEIGHTS, exp.SORTS, exp.COLLAPSE], function(exp_token) {
          expect(display_prefs.attr([exp_token, "unit_test", "foo"].join("."))).toBe("baz");
        })
      });

      it("keeps the page and the defaults separated", function() {
        display_prefs.setPageAsDefault("unit_test");
        can.each(["setColumnWidths", "setCollapsed", "setWidgetHeight", "setSorts"], function(func) {
          display_prefs[func]("unit_test", "foo", "quux");
        });
        can.each([exp.COLUMNS, exp.HEIGHTS, exp.SORTS, exp.COLLAPSE], function(exp_token) {
          expect(display_prefs.attr([exp_token, "unit_test", "foo"].join("."))).toBe("baz");
        });
      });

    });

  });

  describe("#findAll", function() {
    var dp_noversion, dp2_outdated, dp3_current;
    beforeEach(function() {
      dp_noversion = new CMS.Models.DisplayPrefs({});
      dp2_outdated = new CMS.Models.DisplayPrefs({ version : 1});
      dp3_current = new CMS.Models.DisplayPrefs({ version : CMS.Models.DisplayPrefs.version });

      spyOn(can.Model.LocalStorage, "findAll").and.returnValue(new $.Deferred().resolve([dp_noversion, dp2_outdated, dp3_current]));
      spyOn(dp_noversion, "destroy");
      spyOn(dp2_outdated, "destroy");
      spyOn(dp3_current, "destroy");
    });
    it("deletes any prefs that do not have a version set", function(done) {
      var dfd = CMS.Models.DisplayPrefs.findAll().done(function(dps) {
        expect(dps).not.toContain(dp_noversion);
        expect(dp_noversion.destroy).toHaveBeenCalled();
      });

      waitsFor(function() { //sanity check --ensure deferred resolves/rejects
        return dfd.state() !== "pending";
      }, done);
    });
    it("deletes any prefs that have an out of date version", function() {
      CMS.Models.DisplayPrefs.findAll().done(function(dps) {
        expect(dps).not.toContain(dp2_outdated);
        expect(dp2_outdated.destroy).toHaveBeenCalled();
      });
    });
    it("retains any prefs that do not have a version set", function() {
      CMS.Models.DisplayPrefs.findAll().done(function(dps) {
        expect(dps).toContain(dp3_current);
        expect(dp3_current.destroy).not.toHaveBeenCalled();
      });
    });
  });

  describe("#findOne", function() {
    var dp_noversion, dp2_outdated, dp3_current;
    beforeEach(function() {
      dp_noversion = new CMS.Models.DisplayPrefs({});
      dp2_outdated = new CMS.Models.DisplayPrefs({ version : 1});
      dp3_current = new CMS.Models.DisplayPrefs({ version : CMS.Models.DisplayPrefs.version });
    });
    it("404s if the display pref does not have a version set", function(done) {
      spyOn(can.Model.LocalStorage, "findOne").and.returnValue(new $.Deferred().resolve(dp_noversion));
      spyOn(dp_noversion, "destroy");
      var dfd = CMS.Models.DisplayPrefs.findOne().done(function(dps) {
        fail("Should not have resolved findOne for the unversioned display pref");
      }).fail(function(pseudoxhr) {
        expect(pseudoxhr.status).toBe(404);
        expect(dp_noversion.destroy).toHaveBeenCalled();
      });
      waitsFor(function() { //sanity check --ensure deferred resolves/rejects
        return dfd.state() !== "pending";
      }, done);
    });
    it("404s if the display pref has an out of date version", function() {
      spyOn(can.Model.LocalStorage, "findOne").and.returnValue(new $.Deferred().resolve(dp2_outdated));
      spyOn(dp2_outdated, "destroy");
      CMS.Models.DisplayPrefs.findOne().done(function(dps) {
        fail("Should not have resolved findOne for the outdated display pref");
      }).fail(function(pseudoxhr) {
        expect(pseudoxhr.status).toBe(404);
        expect(dp2_outdated.destroy).toHaveBeenCalled();
      });
    });
    it("retains any prefs that do not have a version set", function() {
      spyOn(can.Model.LocalStorage, "findOne").and.returnValue(new $.Deferred().resolve(dp3_current));
      spyOn(dp3_current, "destroy");
      CMS.Models.DisplayPrefs.findOne().done(function(dps) {
        expect(dp3_current.destroy).not.toHaveBeenCalled();
      }).fail(function() {
        fail("Should have resolved on findOne for the current display pref");
      });
    });
  });

});
<|endoftext|>


<commit_before>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 * @stability 3 stable
 *
 * OCM :
 * 	basics : http://en.wikipedia.org/wiki/Object-capability_model or http://en.wikipedia.org/wiki/Capability-based_security
 * 	more : Mark S. Miller, Ka-Ping Yee, Jonathan S. Shapiro (2003). ["Capability Myths Demolished"](http://srl.cs.jhu.edu/pubs/SRL2003-02.pdf) (PDF). Technical Report SRL2003-02. Systems Research Lab, Johns Hopkins University.
 *
 *
 */

//________________________________________________________________________ OCM for the mass !!!
if (typeof define !== 'function') {
	var define = require('amdefine')(module);
}
define(["require", "./utils/misc", "./promise", "./flatten", "./sheet", "./errors", "./protocol", "./compiler"],
	function(require, utils, prom, flattener, sheet, errors, protoc, compiler) {

	var argToArr = Array.prototype.slice;
	var generalModes = {};
	/**
     * OCM for the mass !!
     * @example
     * var manager = ocm({
    	...
     },{
        sensibleTo:"roles"
     })
     * return an Object Capabilities Manager
     * @param  {Object} layer (optional) initial layer
     * @param  {Object} options : { sensibleTo:"string", afterCompilation:Func, protocol:"string" }.  afterCompilation = any function that will be fired on newly compiled object
     * @return {ocm} an Object Capabilities Manager
     */
		var ocm = function(layer, options) {
			//console.log("deep.ocm : ", layer, options);
			//console.log("prom.Promise.context : ", prom.Promise.context)
			options = options || {};
			var params = {
				nocache: options.nocache ||  false,
				sensibleTo: options.sensibleTo|| null,
				flattened: options.flattened || false,
				strict: options.strict || false,
				layer: layer || {},
				currentModes: options.modes || null,
				compiled: {},
				multiModes: (typeof options.multiModes !== 'undefined') ? options.multiModes : true,
				afterCompilation: options.afterCompilation ||  null,
				compile: function(modes, layer) {
					var self = this,
						res = null,
						sheetsPromises = [];
					if (this.multiModes === false && modes.length > 1) {
						deep.warn("OCM : no mulitMode allowed : provided modes : ", modes, " (protocol : ", options.protocol, ")");
						return res;
					}
					var ok = modes.every(function(m) {
						var r = self.layer[m];
						if (typeof r === 'undefined') {
							if (self.strict) {
								deep.warn("OCM : no associate entry found with : ", modes, " (protocol : ", options.protocol, ")");
								return false;
							}
							return true;
						}
						if(res && r && r._deep_sheet_)
							deep.sheet(res, r);
						else
							res = compiler.aup(r, res);
						return true;
					});
					if (!ok)
						return undefined;
					return res;
				}
			};
			var getM = function(key, modes){
				var mod;
				if ((prom.Promise.context.modes && (mod = prom.Promise.context.modes[key])) || (mod = generalModes[key]))
					true;
				if(mod === true)
					return modes.concat(key);
				else if(mod)
					return modes.concat(mod);
				return modes;
			}
			var m = function() {
				var modes = argToArr.call(arguments);
				if (modes.length === 0 /* || params.blocked*/ )
				{
					if (params.currentModes && params.currentModes.length > 0)
						modes = params.currentModes;
					else if (params.sensibleTo) {
						if (params.sensibleTo.forEach) {
							for (var i = 0, len = params.sensibleTo.length; i < len; ++i)
								modes = getM(params.sensibleTo[i], modes);
						}
						else modes = getM(params.sensibleTo, modes);
					}
				}
				if (!modes || modes.length === 0)
					throw errors.OCM("You need to set a mode before using ocm objects.");
				if (!modes.forEach)
					modes = [modes];
				var joined = modes.join(".");
				if (typeof params.compiled[joined] !== 'undefined')
					return params.compiled[joined];
				var compiled = params.compile(modes, params.layer);
				if (!ocm.nocache &&  !params.nocache)
					params.compiled[joined] = compiled;
				if (params.afterCompilation)
					return params.afterCompilation(compiled) || compiled;
				return compiled;
			};
			if (options.protocol) {
				m.name = options.protocol;
				protoc.protocol(options.protocol, m);
			}
			m._deep_ocm_ = true;
			m._deep_compiler_ = true;
			m._deep_flattener_ = true;
			m.multiModes = function(yes) { // allow multiple modes : i.e. : allow ["xxx","yyy", ...] (default : true)
				params.multiModes = yes;
			};
			m.sensibleTo = function(arg) { // define OCM group(s) on what
				if (params.blocked)
					return m;
				params.sensibleTo = arg;
				return m;
			};
			m.layer = function(){ return params.layer; };
			m.modes = m.mode = function(arg) { // set current (local to this manager) mode(s)
				if (params.blocked)
					return m;
				if (arg === null)
					params.currentModes = null;
				else
					params.currentModes = argToArr.call(arguments);
				return m;
			};
			/*m.block = function(key) {                   // block current modes
            params.block = true;
            m.unblock = function(ukey) {
                if (ukey === key)
                    params.blocked = false;
            };
        };
        m.unblock = function(key) {};*/
			m.flatten = function(entry, force) { // flatten inner-layer
				// console.log("trying flatten ocm : ", prom.Promise.context.modes, params.blocked, params.flattened)
				if (params.blocked)
					return prom.when(null);
				if (!force && params.flattened)
					return params.flattened.promise();
				params.compiled = {};
				if (entry) {
					entry.value = params.layer;
					if (entry.ancestor)
						entry.ancestor.value[entry.key] = params.layer;
				}
				var def = params.flattened = prom.Deferred();
				flattener
					.flatten(entry || params.layer)
					.always(function() {
						if (entry) {
							entry.value = m;
							if (entry.ancestor)
								entry.ancestor.value[entry.key] = m;
						}
					})
					.done(function(res) {
						//console.log("ocm flten res : ", res);
						params.layer = res;
						def.resolve(m);
					}).fail(function(error) {
						def.reject(error);
					});
				return def.promise();
			};
			m._up = function() { // apply arguments (up) on inner-layer
				params.flattened = false;
				for (var i = 0; i < arguments.length; ++i)
					params.layer = compiler.aup(arguments[i], params.layer);
				return params.layer;
			};
			m._bottom = function() { // apply arguments (bottom) on inner-layer
				params.flattened = false;
				for (var i = 0; i < arguments.length; ++i)
					params.layer = compiler.abottom(arguments[i], params.layer);
				return params.layer;
			};
			m._clone = function() {
				var o = null;
				options.flattened = params.flattened;
				if (typeof protocol === 'string')
					o = ocm(utils.copy(params.layer), options);
				else
					o = ocm(utils.copy(params.layer), options);
				o.multiModes(params.multiModes);
				if (params.currentModes)
					o.modes(params.currentModes);
				return o;
			};
			return m;
		};
		ocm.nocache = false;

		//______________________________ OCM MODES MODIFIERS

		var setModes = function(obj, arg, arg2){
			if (typeof arg === 'string')
					obj[arg] = arg2;
			else
			{
				for (var i in arg)
					obj[i] = arg[i];
			}
		};

		ocm.Modes = function(arg, arg2) { // general MODES
			if (!arg)
				return generalModes;
			setModes(generalModes, arg, arg2);
		};

		ocm.currentModes = function(arg) {
			var context = prom.Promise.context;
			if (arguments.length > 0 && (typeof arg === 'string' || arg.forEach)) {
				var modes = [],
					args = arguments;
				if (arg.forEach)
					args = arg;
				for (var i = 0, len = args.length; i < len; ++i) {
					var argi = args[i];
					if (context.modes && context.modes[argi])
						modes = modes.concat(context.modes[argi]);
					else if (generalModes[argi])
						modes = modes.concat(generalModes[argi]);
				}
				return modes;
			}
			var base = utils.copy(generalModes);
			if (context.modes)
				for (var i in context.modes)
					base[i] = context.modes[i];
			if (!arg)
				return base;
			for (var i in arg)
				base[i] = arg[i];
			return base;
		};

		/**
		 * set current context modes. See OCM docs and Asynch context management.
		 * @param  {String|Object} arg  if it's an object : will use it as a map. If it's a string : use it as key (need second arguments)
		 * @param  {String} arg2 (optional) the value for the key (if provided)
		 * @return {deep.NodesChain}        this
		 */
		prom.Promise._up({
			modes : function(arg, arg2, noContextualisation) {
				var self = this;
				//console.log("chain.mode : ", arg, arg2, Promise.context.modes);
				//console.log("chain.mode obj: ", arg);
				var func = function(s, e) {
					if(!noContextualisation && !self._contextualised)
						prom.Promise.contextualise(self);
					self._context.modes = self._context.modes || {};
					setModes(self._context.modes, arg, arg2);
					//console.log("Promise.context.mode setted : ",self._context.modes);
					return s;
				};
				func._isDone_ = true;
				return self._enqueue(func);
			}
		});

		return ocm;
	});<commit_msg>OCM : clean and refine flatten procedure<commit_after>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 * @stability 3 stable
 *
 * OCM :
 * 	basics : http://en.wikipedia.org/wiki/Object-capability_model or http://en.wikipedia.org/wiki/Capability-based_security
 * 	more : Mark S. Miller, Ka-Ping Yee, Jonathan S. Shapiro (2003). ["Capability Myths Demolished"](http://srl.cs.jhu.edu/pubs/SRL2003-02.pdf) (PDF). Technical Report SRL2003-02. Systems Research Lab, Johns Hopkins University.
 *
 *
 */

//________________________________________________________________________ OCM for the mass !!!
if (typeof define !== 'function') {
	var define = require('amdefine')(module);
}
define(["require", "./utils/misc", "./promise", "./flatten", "./sheet", "./errors", "./protocol", "./compiler"],
	function(require, utils, prom, flattener, sheet, errors, protoc, compiler) {

	var argToArr = Array.prototype.slice;
	var generalModes = {};
	/**
     * OCM for the mass !!
     * @example
     * var manager = ocm({
    	...
     },{
        sensibleTo:"roles"
     })
     * return an Object Capabilities Manager
     * @param  {Object} layer (optional) initial layer
     * @param  {Object} options : { sensibleTo:"string", afterCompilation:Func, protocol:"string" }.  afterCompilation = any function that will be fired on newly compiled object
     * @return {ocm} an Object Capabilities Manager
     */
		var ocm = function(layer, options) {
			//console.log("deep.ocm : ", layer, options);
			//console.log("prom.Promise.context : ", prom.Promise.context)
			options = options || {};
			var params = {
				nocache: options.nocache ||  false,
				sensibleTo: options.sensibleTo|| null,
				flattened: options.flattened || false,
				strict: options.strict || false,
				layer: layer || {},
				currentModes: options.modes || null,
				compiled: {},
				multiModes: (typeof options.multiModes !== 'undefined') ? options.multiModes : true,
				afterCompilation: options.afterCompilation ||  null,
				compile: function(modes, layer) {
					var self = this,
						res = null,
						sheetsPromises = [];
					if (this.multiModes === false && modes.length > 1) {
						deep.warn("OCM : no mulitMode allowed : provided modes : ", modes, " (protocol : ", options.protocol, ")");
						return res;
					}
					var ok = modes.every(function(m) {
						var r = self.layer[m];
						if (typeof r === 'undefined') {
							if (self.strict) {
								deep.warn("OCM : no associate entry found with : ", modes, " (protocol : ", options.protocol, ")");
								return false;
							}
							return true;
						}
						if(res && r && r._deep_sheet_)
							deep.sheet(res, r);
						else
							res = compiler.aup(r, res);
						return true;
					});
					if (!ok)
						return undefined;
					return res;
				}
			};
			var getM = function(key, modes){
				var mod;
				if ((prom.Promise.context.modes && (mod = prom.Promise.context.modes[key])) || (mod = generalModes[key]))
					true;
				if(mod === true)
					return modes.concat(key);
				else if(mod)
					return modes.concat(mod);
				return modes;
			}
			var m = function() {
				var modes = argToArr.call(arguments);
				if (modes.length === 0 /* || params.blocked*/ )
				{
					if (params.currentModes && params.currentModes.length > 0)
						modes = params.currentModes;
					else if (params.sensibleTo) {
						if (params.sensibleTo.forEach) {
							for (var i = 0, len = params.sensibleTo.length; i < len; ++i)
								modes = getM(params.sensibleTo[i], modes);
						}
						else modes = getM(params.sensibleTo, modes);
					}
				}
				if (!modes || modes.length === 0)
					throw errors.OCM("You need to set a mode before using ocm objects.");
				if (!modes.forEach)
					modes = [modes];
				var joined = modes.join(".");
				if (typeof params.compiled[joined] !== 'undefined')
					return params.compiled[joined];
				var compiled = params.compile(modes, params.layer);
				if (!ocm.nocache &&  !params.nocache)
					params.compiled[joined] = compiled;
				if (params.afterCompilation)
					return params.afterCompilation(compiled) || compiled;
				return compiled;
			};
			if (options.protocol) {
				m.name = options.protocol;
				protoc.protocol(options.protocol, m);
			}
			m._deep_ocm_ = true;
			m._deep_compiler_ = true;
			m._deep_flattener_ = true;
			m.multiModes = function(yes) { // allow multiple modes : i.e. : allow ["xxx","yyy", ...] (default : true)
				params.multiModes = yes;
			};
			m.sensibleTo = function(arg) { // define OCM group(s) on what
				if (params.blocked)
					return m;
				params.sensibleTo = arg;
				return m;
			};
			m.layer = function(){ return params.layer; };
			m.modes = m.mode = function(arg) { // set current (local to this manager) mode(s)
				if (params.blocked)
					return m;
				if (arg === null)
					params.currentModes = null;
				else
					params.currentModes = argToArr.call(arguments);
				return m;
			};
			/*m.block = function(key) {                   // block current modes
            params.block = true;
            m.unblock = function(ukey) {
                if (ukey === key)
                    params.blocked = false;
            };
        };
        m.unblock = function(key) {};*/
			m.flatten = function(entry, force) { // flatten inner-layer
				// console.log("flatten inner layer ocm : ");
				if (params.blocked)
					return prom.when(null);
				if (!force && params.flattened)
					if(params.flattened.then)
						return prom.when(params.flattened);
					else
						return prom.immediate(m);
				params.compiled = {};
				if (entry) {
					entry.value = params.layer;
					if (entry.ancestor)
						entry.ancestor.value[entry.key] = params.layer;
				}

				var def = params.flattened = new prom.Promise();
				deep.when(flattener
					.flatten(entry || params.layer))
					.always(function() {
						if (entry)
							entry.set(m);
					})
					.done(function(res) {
						// console.log("ocm flattened : ", res);
						params.layer = res;
						params.flattened = true;
						def.resolve(m);
					})
					.fail(function(error) {
						def.reject(error);
					});
				return def;
			};
			m._up = function() { // apply arguments (up) on inner-layer
				params.flattened = false;
				for (var i = 0; i < arguments.length; ++i)
					params.layer = compiler.aup(arguments[i], params.layer);
				return params.layer;
			};
			m._bottom = function() { // apply arguments (bottom) on inner-layer
				params.flattened = false;
				for (var i = 0; i < arguments.length; ++i)
					params.layer = compiler.abottom(arguments[i], params.layer);
				return params.layer;
			};
			m._clone = function() {
				var o = null;
				options.flattened = params.flattened;
				if (typeof protocol === 'string')
					o = ocm(utils.copy(params.layer), options);
				else
					o = ocm(utils.copy(params.layer), options);
				o.multiModes(params.multiModes);
				if (params.currentModes)
					o.modes(params.currentModes);
				return o;
			};
			return m;
		};
		ocm.nocache = false;

		//______________________________ OCM MODES MODIFIERS

		var setModes = function(obj, arg, arg2){
			if (typeof arg === 'string')
					obj[arg] = arg2;
			else
			{
				for (var i in arg)
					obj[i] = arg[i];
			}
		};

		ocm.Modes = function(arg, arg2) { // general MODES
			if (!arg)
				return generalModes;
			setModes(generalModes, arg, arg2);
		};

		ocm.currentModes = function(arg) {
			var context = prom.Promise.context;
			if (arguments.length > 0 && (typeof arg === 'string' || arg.forEach)) {
				var modes = [],
					args = arguments;
				if (arg.forEach)
					args = arg;
				for (var i = 0, len = args.length; i < len; ++i) {
					var argi = args[i];
					if (context.modes && context.modes[argi])
						modes = modes.concat(context.modes[argi]);
					else if (generalModes[argi])
						modes = modes.concat(generalModes[argi]);
				}
				return modes;
			}
			var base = utils.copy(generalModes);
			if (context.modes)
				for (var i in context.modes)
					base[i] = context.modes[i];
			if (!arg)
				return base;
			for (var i in arg)
				base[i] = arg[i];
			return base;
		};

		/**
		 * set current context modes. See OCM docs and Asynch context management.
		 * @param  {String|Object} arg  if it's an object : will use it as a map. If it's a string : use it as key (need second arguments)
		 * @param  {String} arg2 (optional) the value for the key (if provided)
		 * @return {deep.NodesChain}        this
		 */
		prom.Promise._up({
			modes : function(arg, arg2, noContextualisation) {
				var self = this;
				//console.log("chain.mode : ", arg, arg2, Promise.context.modes);
				//console.log("chain.mode obj: ", arg);
				var func = function(s, e) {
					if(!noContextualisation && !self._contextualised)
						prom.Promise.contextualise(self);
					self._context.modes = self._context.modes || {};
					setModes(self._context.modes, arg, arg2);
					//console.log("Promise.context.mode setted : ",self._context.modes);
					return s;
				};
				func._isDone_ = true;
				return self._enqueue(func);
			}
		});

		return ocm;
	});<|endoftext|>


<commit_before>define('chrome.socket', function(require, module) {

var stringToArrayBuffer = function(str) {
    var ret = new Int8Array(str.length);
    for (var i = 0; i < str.length; i++) {
        ret[i] = str.charCodeAt(i);
    }
    return ret;
};

var encodeUint8ArrayAsBase64 = function(arr) {
    var binary = '';
    var len = arr.length;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode(arr[i]);
    }
    return window.btoa(binary);
};

var decodeUint8ArrayFromBase64 = function(b64) {
    var decoded = atob(b64);
    return stringToArrayBuffer(decoded);
};

var exports = module.exports;

exports.create = function(socketMode, stuff, callback) {
    cordova.exec(function(socketId) {
        var socketInfo = {};
        socketInfo.socketId = socketId;
        if (!!callback && typeof callback == 'function') {
            callback(socketInfo);
        }
    }, null, 'Socket', 'create', [{ socketMode: socketMode }]);
};

exports.connect = function(socketId, address, port, callback) {
    cordova.exec(function(result) {
        if (!!callback && typeof callback == 'function') {
            callback(result);
        }
    }, null, 'Socket', 'connect', [{ socketId: socketId, address: address, port: port }]);
};

exports.write = function(socketId, data, callback) {
    if (typeof data == 'string') {
        data = stringToArrayBuffer(data).buffer;
    }
    data = encodeUint8ArrayAsBase64(new Uint8Array(data));

    cordova.exec(function(bytesWritten) {
        var writeInfo = {};
        writeInfo.bytesWritten = bytesWritten;
        if (!!callback && typeof callback == 'function') {
            callback(writeInfo);
        }
    }, null, 'Socket', 'write', [{ socketId: socketId, data: data }]);
};

exports.read = function(socketId, bufferSize, callback) {
    if (!callback) {
        callback = bufferSize;
        bufferSize = 1;
    }
    cordova.exec(function(base64data) {
        var readInfo = {};
        readInfo.resultCode = 0;
        readInfo.data = decodeUint8ArrayFromBase64(base64data).buffer;
        if (!!callback && typeof callback == 'function') {
            callback(readInfo);
        }
    }, null, 'Socket', 'read', [{ socketId: socketId, bufferSize: bufferSize }]);
};

exports.disconnect = function(socketId) {
    cordova.exec(null, null, 'Socket', 'disconnect', [{ socketId: socketId }]);
};

exports.destroy = function(socketId) {
    cordova.exec(null, null, 'Socket', 'destroy', [{ socketId: socketId }]);
};

});
<commit_msg>minor changes<commit_after>define('chrome.socket', function(require, module) {

var stringToArrayBuffer = function(str) {
    var ret = new Uint8Array(str.length);
    for (var i = 0; i < str.length; i++) {
        ret[i] = str.charCodeAt(i);
    }
    return ret;
};

var encodeUint8ArrayAsBase64 = function(arr) {
    var binary = '';
    var len = arr.length;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode(arr[i]);
    }
    return window.btoa(binary);
};

var decodeUint8ArrayFromBase64 = function(b64) {
    var decoded = atob(b64);
    return stringToArrayBuffer(decoded);
};

var exports = module.exports;

exports.create = function(socketMode, stuff, callback) {
    cordova.exec(function(socketId) {
        var socketInfo = {};
        socketInfo.socketId = socketId;
        if (!!callback && typeof callback == 'function') {
            callback(socketInfo);
        }
    }, null, 'Socket', 'create', [{ socketMode: socketMode }]);
};

exports.connect = function(socketId, address, port, callback) {
    cordova.exec(function(result) {
        if (!!callback && typeof callback == 'function') {
            callback(result);
        }
    }, null, 'Socket', 'connect', [{ socketId: socketId, address: address, port: port }]);
};

exports.write = function(socketId, data, callback) {
    if (typeof data == 'string') {
        data = stringToArrayBuffer(data).buffer;
    }
    data = encodeUint8ArrayAsBase64(new Uint8Array(data));

    cordova.exec(function(bytesWritten) {
        var writeInfo = {};
        writeInfo.bytesWritten = bytesWritten;
        if (!!callback && typeof callback == 'function') {
            callback(writeInfo);
        }
    }, null, 'Socket', 'write', [{ socketId: socketId, data: data }]);
};

exports.read = function(socketId, bufferSize, callback) {
    if (!callback) {
        callback = bufferSize;
        bufferSize = 0;
    }
    cordova.exec(function(base64data) {
        //console.log('received');
        var readInfo = {};
        readInfo.resultCode = 1;
        readInfo.data = decodeUint8ArrayFromBase64(base64data).buffer;
        //console.log(new Uint8Array(readInfo.data));
        if (!!callback && typeof callback == 'function') {
            callback(readInfo);
        }
    }, null, 'Socket', 'read', [{ socketId: socketId, bufferSize: bufferSize }]);
};

exports.disconnect = function(socketId) {
    cordova.exec(null, null, 'Socket', 'disconnect', [{ socketId: socketId }]);
};

exports.destroy = function(socketId) {
    cordova.exec(null, null, 'Socket', 'destroy', [{ socketId: socketId }]);
};

});
<|endoftext|>


<commit_before>/**
 * Copyright 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
 * Please see distribution for license.
 */
$.register_module({
    name: 'og.blotter.forms.swaptionsecurity',
    dependencies: [],
    obj: function () {
        return function (config) {
            config = og.blotter.util.FAKE_SWAPTION;
            config.swap = og.blotter.util.FAKE_SWAP;
            config.swap.floating = og.blotter.util.FAKE_FLOATING;
            config.swap.fixed = og.blotter.util.FAKE_FIXED;
            var constructor = this, ui = og.common.util.ui, data = config || {},
            floating = "swapsecurity.floatingspreadirleg.";
            fixed = "swapsecurity.fixedinterestrateleg.";
            constructor.load = function () {
                constructor.title = 'Swaption';
                var form = new og.common.util.ui.Form({
                    module: 'og.blotter.forms.swaption_tash',
                    selector: '.OG-blotter-form-block'
                });
                form.children.push(
                    new og.blotter.forms.blocks.Portfolio({form: form}),
                    new form.Block({
                        module: 'og.blotter.forms.blocks.long_short_tash'
                    }),
                    new form.Block({
                        module: 'og.blotter.forms.blocks.swaption_details_tash',
                        extras: {notional: data.notional, expiry: data.expiry, settlement: data.settlementDate},
                        children: [
                            new form.Block({module:'og.views.forms.currency_tash'}),
                            new ui.Dropdown({
                                form: form, resource: 'blotter.exercisetypes', index: 'exerciseType',
                                value: data.exerciseType, placeholder: 'Select Exercise Type'
                            })
                        ]
                    }),
                    new form.Block({
                        module: 'og.blotter.forms.blocks.swap_quick_entry_tash'
                    }),
                    new form.Block({
                        module: 'og.blotter.forms.blocks.swap_details_tash',
                        extras: {trade: data.swap.tradeDate, maturity: data.swap.maturityDate,
                            effective: data.swap.effectiveDate}
                    }),
                    new form.Block({
                        module: 'og.blotter.forms.blocks.swap_details_fixed_tash',
                        extras: {rate: data.swap.fixed.rate, notional: data.swap.fixed.notional},
                        children : [
                            new form.Block({module:'og.views.forms.currency_tash'}),
                            new ui.Dropdown({
                                form: form, resource: 'blotter.daycountconventions',
                                index: fixed + 'dayCount',
                                value: data.swap.fixed.dayCount, placeholder: 'Select Day Count'
                            }),
                            new ui.Dropdown({
                                form: form, resource: 'blotter.frequencies',
                                index: fixed + 'frequency',
                                value: data.swap.fixed.frequency, placeholder: 'Select Frequency'
                            })
                        ]
                    }),
                    new form.Block({
                        module: 'og.blotter.forms.blocks.swap_details_floating_tash',
                        extras: {type: floating, initial: data.swap.floating.initialFloatingRate,
                            settlement: data.swap.floating.settlementDays, spread: data.swap.floating.spread,
                            gearing: data.swap.floating.gearing, notional: data.swap.floating.notional},
                        children: [
                            new form.Block({module:'og.views.forms.currency_tash',extras:{name: floating +'currency'}}),
                            new ui.Dropdown({
                                form: form, resource: 'blotter.daycountconventions', index: floating + 'dayCount',
                                value: data.swap.floating.dayCount, placeholder: 'Select Day Count'
                            }),
                            new ui.Dropdown({
                                form: form, resource: 'blotter.frequencies', index: floating + 'frequency',
                                value: data.swap.floating.frequency, placeholder: 'Select Frequency'
                            }),
                            new ui.Dropdown({
                                form: form, resource: 'blotter.businessdayconventions',
                                index: floating + 'businessDayConvention',
                                value: data.swap.floating.businessDayConvention,
                                placeholder: 'Select Business Day Convention'
                            }),
                            new ui.Dropdown({
                                form: form, resource: 'blotter.floatingratetypes',
                                index: floating + 'floatingRateTypes',
                                value: data.swap.floating.floatingRateType, placeholder: 'Select Floating Rate Type'
                            }),
                            new ui.Dropdown({
                                form: form, resource: 'blotter.frequencies', index: floating + 'offsetFixing',
                                value: data.swap.floating.offsetFixing, placeholder: 'Select Offset Fixing'
                            })
                        ]
                    }),
                    new og.common.util.ui.Attributes({form: form, attributes: data.attributes})
                );
                form.dom();
                form.on('form:load', function (){
                    if(data.length) return;
                    og.blotter.util.check_checkbox(floating + 'eom', data.swap.floating.eom);
                    og.blotter.util.check_checkbox(fixed + 'eom', data.swap.fixed.eom);
                    og.blotter.util.set_select("currency", data.currency);
                    og.blotter.util.check_radio("payer", data.payer);
                    og.blotter.util.check_radio("cashSettled", data.cashSettled);
                    og.blotter.util.check_radio("longShort", data.longShort);
                });
            };
            constructor.load();
            constructor.kill = function () {
            };
        };
    }
});<commit_msg>floating and fixed blocks added to swaption<commit_after>/**
 * Copyright 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
 * Please see distribution for license.
 */
$.register_module({
    name: 'og.blotter.forms.swaptionsecurity',
    dependencies: [],
    obj: function () {
        return function (config) {
            config = og.blotter.util.FAKE_SWAPTION;
            config.swap = og.blotter.util.FAKE_SWAP;
            config.swap.floating = og.blotter.util.FAKE_FLOATING;
            config.swap.fixed = og.blotter.util.FAKE_FIXED;
            var constructor = this, ui = og.common.util.ui, data = config || {},
            floating = "swapsecurity.floatingspreadirleg.";
            fixed = "swapsecurity.fixedinterestrateleg.";
            constructor.load = function () {
                constructor.title = 'Swaption';
                var form = new og.common.util.ui.Form({
                    module: 'og.blotter.forms.swaption_tash',
                    selector: '.OG-blotter-form-block'
                });
                form.children.push(
                    new og.blotter.forms.blocks.Portfolio({form: form}),
                    new form.Block({
                        module: 'og.blotter.forms.blocks.long_short_tash'
                    }),
                    new form.Block({
                        module: 'og.blotter.forms.blocks.swaption_details_tash',
                        extras: {notional: data.notional, expiry: data.expiry, settlement: data.settlementDate},
                        children: [
                            new form.Block({module:'og.views.forms.currency_tash'}),
                            new ui.Dropdown({
                                form: form, resource: 'blotter.exercisetypes', index: 'exerciseType',
                                value: data.exerciseType, placeholder: 'Select Exercise Type'
                            })
                        ]
                    }),
                    new form.Block({
                        module: 'og.blotter.forms.blocks.swap_quick_entry_tash'
                    }),
                    new form.Block({
                        module: 'og.blotter.forms.blocks.swap_details_tash',
                        extras: {trade: data.swap.tradeDate, maturity: data.swap.maturityDate,
                            effective: data.swap.effectiveDate}
                    }),
                    new og.blotter.forms.blocks.Fixedleg({form: form, data: data, leg: 'recieveLeg.'}),
                    new og.blotter.forms.blocks.Floatingleg({form: form, data: data, leg: 'pagLeg.'}),
                    new og.common.util.ui.Attributes({form: form, attributes: data.attributes})
                );
                form.dom();
                form.on('form:load', function (){
                    if(data.length) return;
                    og.blotter.util.check_checkbox(floating + 'eom', data.swap.floating.eom);
                    og.blotter.util.check_checkbox(fixed + 'eom', data.swap.fixed.eom);
                    og.blotter.util.set_select("currency", data.currency);
                    og.blotter.util.check_radio("payer", data.payer);
                    og.blotter.util.check_radio("cashSettled", data.cashSettled);
                    og.blotter.util.check_radio("longShort", data.longShort);
                });
            };
            constructor.load();
            constructor.kill = function () {
            };
        };
    }
});<|endoftext|>


<commit_before>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 * @stability 3 stable
 *
 *
 *
 * TODO : refactor 'group' in 'modes'
 *
 *
 */

//________________________________________________________________________ OCM for the mass !!!
if (typeof define !== 'function') {
	var define = require('amdefine')(module);
}
define(["require", "./utils", "./promise", "./flatten", "./sheet", "./errors", "./protocol", "./compiler"],
	function(require, utils, prom, flattener, sheet, errors, protoc, compiler) {

		var argToArr = Array.prototype.slice;
		var generalModes = {};
		/*
        deep.paranos = function(full)
        {
            if(full)
                delete deep.context.protocols;
            if(deep.context.protocols)
            {
                deep.context.protocols = utils.simpleCopy(deep.context.protocols);
                for(var i in deep.context.protocols)
                    if(deep.context.protocols[i]._deep_ocm_)
                       deep.context.protocols[i] = deep.context.protocols[i]();
            }
//          delete deep.context.generalModes;
            delete deep.context.modes;
        };
*/

		/**
     * OCM for the mass !!
     * @example
     * var manager = ocm({

     },{
        groups:"roles",
        protocol:"myGeneralProtoc",
        afterCompilation:function(){
            return this;
        },
        mode:"public"
     })
     * return an Object Capabilities Manager
     * @param  {Object} layer (optional) initial layer
     * @param  {Object} options : { group:"string", afterCompilation:Func, protocol:"string" }.  afterCompilation = any function that will be fired on newly compiled object
     * @return {ocm} an Object Capabilities Manager
     */
		var ocm = function(layer, options) {
			//console.log("deep.ocm : ", layer, options);
			//console.log("prom.Promise.context : ", prom.Promise.context)
			options = options || {};
			var params = {
				nocache: options.nocache ||  false,
				groups: options.groups || options.group || null,
				flattened: options.flattened || false,
				strict: options.strict || false,
				layer: layer || {},
				currentModes: options.modes || null,
				compiled: {},
				multiModes: (typeof options.multiModes !== 'undefined') ? options.multiModes : true,
				afterCompilation: options.afterCompilation ||  null,
				compile: function(modes, layer) {
					var self = this,
						res = null,
						sheetsPromises = [];
					if (this.multiModes === false && modes.length > 1) {
						deep.warn("OCM : no mulitMode allowed : provided modes : ", modes, " (protocol : ", options.protocol, ")");
						return res;
					}
					var ok = modes.every(function(m) {
						var r = self.layer[m];
						if (typeof r === 'undefined') {
							if (self.strict) {
								deep.warn("OCM : no associate entry found with : ", modes, " (protocol : ", options.protocol, ")");
								return false;
							}
							return true;
						}
						if(res && r && r._deep_sheet_)
							deep.sheet(r,res);
						else
							res = compiler.up(r, res);
						return true;
					});
					if (!ok)
						return {};
					return res;
				}
			};
			var m = function() {
				var modes = argToArr.call(arguments);
				if (modes.length === 0 /* || params.blocked*/ )
				{
					if (params.currentModes && params.currentModes.length > 0)
						modes = params.currentModes;
					else if (params.groups) {
						if (params.groups.forEach) {
							modes = [];
							for (var i = 0, len = params.groups.length; i < len; ++i) {
								var groupi = params.groups[i];
								if (prom.Promise.context.modes && prom.Promise.context.modes[groupi])
									modes = modes.concat(prom.Promise.context.modes[groupi]);
								else if (generalModes[groupi])
									modes = modes.concat(generalModes[groupi]);
							}
						} else if (prom.Promise.context.modes && prom.Promise.context.modes[params.groups])
							modes = modes.concat(prom.Promise.context.modes[params.groups]);
						else if (generalModes[params.groups])
							modes = modes.concat(generalModes[params.groups]);
					}
				}
				if (!modes || modes.length === 0)
					throw errors.OCM("You need to set a mode before using ocm objects.");
				if (!modes.forEach)
					modes = [modes];
				var joined = modes.join(".");
				if (params.compiled[joined])
					return params.compiled[joined];
				var compiled = params.compile(modes, params.layer);
				if (!ocm.nocache &&  !params.nocache)
					params.compiled[joined] = compiled;
				if (params.afterCompilation)
					return params.afterCompilation(compiled) || compiled;
				return compiled;
			};
			if (options.protocol) {
				m.name = options.protocol;
				protoc.protocol(options.protocol, m);
			}
			m._deep_ocm_ = true;
			m._deep_compiler_ = true;
			m._deep_flattener_ = true;
			m.multiModes = function(yes) { // allow multiple modes : i.e. : allow ["xxx","yyy", ...] (default : true)
				params.multiModes = yes;
			};
			m.groups = m.group = function(arg) { // define OCM group(s) on what
				if (params.blocked)
					return m;
				params.groups = arg;
				return m;
			};
			m.modes = m.mode = function(arg) { // set current (local to this manager) mode(s)
				if (params.blocked)
					return m;
				if (arg === null)
					params.currentModes = null;
				else
					params.currentModes = argToArr.call(arguments);
				return m;
			};
			/*m.block = function(key) {                   // block current modes
            params.block = true;
            m.unblock = function(ukey) {
                if (ukey === key)
                    params.blocked = false;
            };
        };
        m.unblock = function(key) {};*/
			m.flatten = function(entry, force) { // flatten inner-layer
				// console.log("trying flatten ocm : ", prom.Promise.context.modes, params.blocked, params.flattened)
				if (params.blocked)
					return prom.when(null);
				if (!force && params.flattened)
					return params.flattened.promise();
				params.compiled = {};
				if (entry) {
					entry.value = params.layer;
					if (entry.ancestor)
						entry.ancestor.value[entry.key] = params.layer;
				}
				var def = params.flattened = prom.Deferred();
				flattener
					.flatten(entry || params.layer)
					.always(function() {
						if (entry) {
							entry.value = m;
							if (entry.ancestor)
								entry.ancestor.value[entry.key] = m;
						}
					})
					.done(function(res) {
						//console.log("ocm flten res : ", res);
						params.layer = res;
						def.resolve(m);
					}).fail(function(error) {
						def.reject(error);
					});
				return def.promise();
			};
			m._up = function() { // apply arguments (up) on inner-layer
				params.flattened = false;
				for (var i = 0; i < arguments.length; ++i)
					params.layer = utils.up(arguments[i], params.layer);
				return params.layer;
			};
			m._bottom = function() { // apply arguments (bottom) on inner-layer
				params.flattened = false;
				for (var i = 0; i < arguments.length; ++i)
					params.layer = utils.bottom(arguments[i], params.layer);
				return params.layer;
			};
			m._clone = function() {
				var o = null;
				options.flattened = params.flattened;
				if (typeof protocol === 'string')
					o = ocm(utils.copy(params.layer), options);
				else
					o = ocm(utils.copy(params.layer), options);
				o.multiModes(params.multiModes);
				if (params.currentModes)
					o.modes(params.currentModes);
				return o;
			};
			return m;
		};
		ocm.nocache = false;

		//______________________________ OCM MODES MODIFIERS

		ocm.Roles = function(roles) { // general ROLES
			if (!roles)
				return generalModes.roles;
			return ocm.Modes({
				roles: roles
			});
		}
		ocm.Modes = function(arg, arg2) { // general MODES
			if (!arg)
				return generalModes;
			if (typeof arg === 'string') {
				if (arg2)
					generalModes[arg] = arg2;
				else
					return generalModes[arg];
			} else
				for (var i in arg)
					generalModes[i] = arg[i];
		};

		ocm.getModes = function(arg) {
			if (arguments.length > 0 && (typeof arg === 'string' || arg.forEach)) {
				var modes = [],
					args = arguments;
				if (arg.forEach)
					args = arg;
				for (var i = 0, len = args.length; i < len; ++i) {
					var argi = args[i];
					if (prom.Promise.context.modes && prom.Promise.context.modes[argi])
						modes = modes.concat(prom.Promise.context.modes[argi]);
					else if (generalModes[argi])
						modes = modes.concat(generalModes[argi]);
				}
				return modes;
			}
			var base = utils.copy(generalModes);
			if (prom.Promise.context.modes)
				for (var i in prom.Promise.context.modes)
					base[i] = prom.Promise.context.modes[i];
			if (!arg)
				return base;
			for (var i in arg)
				base[i] = arg[i];
			return base;
		}

		// deep chain's mode management
		ocm.modes = function(name, modes) { // local roles (i.e. in chain's context)
			return deep({}).modes(name, modes);
		};

		// deep chain's roles management
		ocm.roles = function() { // local modes (i.e. in chain's context)
			return deep({}).roles(argToArr.call(arguments));
		};
		return ocm;
	});<commit_msg>remove parano (to be rethinked)<commit_after>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 * @stability 3 stable
 *
 *
 *
 * TODO : refactor 'group' in 'modes'
 *
 *
 */

//________________________________________________________________________ OCM for the mass !!!
if (typeof define !== 'function') {
	var define = require('amdefine')(module);
}
define(["require", "./utils", "./promise", "./flatten", "./sheet", "./errors", "./protocol", "./compiler"],
	function(require, utils, prom, flattener, sheet, errors, protoc, compiler) {

		var argToArr = Array.prototype.slice;
		var generalModes = {};
		/**
     * OCM for the mass !!
     * @example
     * var manager = ocm({

     },{
        groups:"roles",
        protocol:"myGeneralProtoc",
        afterCompilation:function(){
            return this;
        },
        mode:"public"
     })
     * return an Object Capabilities Manager
     * @param  {Object} layer (optional) initial layer
     * @param  {Object} options : { group:"string", afterCompilation:Func, protocol:"string" }.  afterCompilation = any function that will be fired on newly compiled object
     * @return {ocm} an Object Capabilities Manager
     */
		var ocm = function(layer, options) {
			//console.log("deep.ocm : ", layer, options);
			//console.log("prom.Promise.context : ", prom.Promise.context)
			options = options || {};
			var params = {
				nocache: options.nocache ||  false,
				groups: options.groups || options.group || null,
				flattened: options.flattened || false,
				strict: options.strict || false,
				layer: layer || {},
				currentModes: options.modes || null,
				compiled: {},
				multiModes: (typeof options.multiModes !== 'undefined') ? options.multiModes : true,
				afterCompilation: options.afterCompilation ||  null,
				compile: function(modes, layer) {
					var self = this,
						res = null,
						sheetsPromises = [];
					if (this.multiModes === false && modes.length > 1) {
						deep.warn("OCM : no mulitMode allowed : provided modes : ", modes, " (protocol : ", options.protocol, ")");
						return res;
					}
					var ok = modes.every(function(m) {
						var r = self.layer[m];
						if (typeof r === 'undefined') {
							if (self.strict) {
								deep.warn("OCM : no associate entry found with : ", modes, " (protocol : ", options.protocol, ")");
								return false;
							}
							return true;
						}
						if(res && r && r._deep_sheet_)
							deep.sheet(r,res);
						else
							res = compiler.up(r, res);
						return true;
					});
					if (!ok)
						return {};
					return res;
				}
			};
			var m = function() {
				var modes = argToArr.call(arguments);
				if (modes.length === 0 /* || params.blocked*/ )
				{
					if (params.currentModes && params.currentModes.length > 0)
						modes = params.currentModes;
					else if (params.groups) {
						if (params.groups.forEach) {
							modes = [];
							for (var i = 0, len = params.groups.length; i < len; ++i) {
								var groupi = params.groups[i];
								if (prom.Promise.context.modes && prom.Promise.context.modes[groupi])
									modes = modes.concat(prom.Promise.context.modes[groupi]);
								else if (generalModes[groupi])
									modes = modes.concat(generalModes[groupi]);
							}
						} else if (prom.Promise.context.modes && prom.Promise.context.modes[params.groups])
							modes = modes.concat(prom.Promise.context.modes[params.groups]);
						else if (generalModes[params.groups])
							modes = modes.concat(generalModes[params.groups]);
					}
				}
				if (!modes || modes.length === 0)
					throw errors.OCM("You need to set a mode before using ocm objects.");
				if (!modes.forEach)
					modes = [modes];
				var joined = modes.join(".");
				if (params.compiled[joined])
					return params.compiled[joined];
				var compiled = params.compile(modes, params.layer);
				if (!ocm.nocache &&  !params.nocache)
					params.compiled[joined] = compiled;
				if (params.afterCompilation)
					return params.afterCompilation(compiled) || compiled;
				return compiled;
			};
			if (options.protocol) {
				m.name = options.protocol;
				protoc.protocol(options.protocol, m);
			}
			m._deep_ocm_ = true;
			m._deep_compiler_ = true;
			m._deep_flattener_ = true;
			m.multiModes = function(yes) { // allow multiple modes : i.e. : allow ["xxx","yyy", ...] (default : true)
				params.multiModes = yes;
			};
			m.groups = m.group = function(arg) { // define OCM group(s) on what
				if (params.blocked)
					return m;
				params.groups = arg;
				return m;
			};
			m.modes = m.mode = function(arg) { // set current (local to this manager) mode(s)
				if (params.blocked)
					return m;
				if (arg === null)
					params.currentModes = null;
				else
					params.currentModes = argToArr.call(arguments);
				return m;
			};
			/*m.block = function(key) {                   // block current modes
            params.block = true;
            m.unblock = function(ukey) {
                if (ukey === key)
                    params.blocked = false;
            };
        };
        m.unblock = function(key) {};*/
			m.flatten = function(entry, force) { // flatten inner-layer
				// console.log("trying flatten ocm : ", prom.Promise.context.modes, params.blocked, params.flattened)
				if (params.blocked)
					return prom.when(null);
				if (!force && params.flattened)
					return params.flattened.promise();
				params.compiled = {};
				if (entry) {
					entry.value = params.layer;
					if (entry.ancestor)
						entry.ancestor.value[entry.key] = params.layer;
				}
				var def = params.flattened = prom.Deferred();
				flattener
					.flatten(entry || params.layer)
					.always(function() {
						if (entry) {
							entry.value = m;
							if (entry.ancestor)
								entry.ancestor.value[entry.key] = m;
						}
					})
					.done(function(res) {
						//console.log("ocm flten res : ", res);
						params.layer = res;
						def.resolve(m);
					}).fail(function(error) {
						def.reject(error);
					});
				return def.promise();
			};
			m._up = function() { // apply arguments (up) on inner-layer
				params.flattened = false;
				for (var i = 0; i < arguments.length; ++i)
					params.layer = utils.up(arguments[i], params.layer);
				return params.layer;
			};
			m._bottom = function() { // apply arguments (bottom) on inner-layer
				params.flattened = false;
				for (var i = 0; i < arguments.length; ++i)
					params.layer = utils.bottom(arguments[i], params.layer);
				return params.layer;
			};
			m._clone = function() {
				var o = null;
				options.flattened = params.flattened;
				if (typeof protocol === 'string')
					o = ocm(utils.copy(params.layer), options);
				else
					o = ocm(utils.copy(params.layer), options);
				o.multiModes(params.multiModes);
				if (params.currentModes)
					o.modes(params.currentModes);
				return o;
			};
			return m;
		};
		ocm.nocache = false;

		//______________________________ OCM MODES MODIFIERS

		ocm.Roles = function(roles) { // general ROLES
			if (!roles)
				return generalModes.roles;
			return ocm.Modes({
				roles: roles
			});
		}
		ocm.Modes = function(arg, arg2) { // general MODES
			if (!arg)
				return generalModes;
			if (typeof arg === 'string') {
				if (arg2)
					generalModes[arg] = arg2;
				else
					return generalModes[arg];
			} else
				for (var i in arg)
					generalModes[i] = arg[i];
		};

		ocm.getModes = function(arg) {
			if (arguments.length > 0 && (typeof arg === 'string' || arg.forEach)) {
				var modes = [],
					args = arguments;
				if (arg.forEach)
					args = arg;
				for (var i = 0, len = args.length; i < len; ++i) {
					var argi = args[i];
					if (prom.Promise.context.modes && prom.Promise.context.modes[argi])
						modes = modes.concat(prom.Promise.context.modes[argi]);
					else if (generalModes[argi])
						modes = modes.concat(generalModes[argi]);
				}
				return modes;
			}
			var base = utils.copy(generalModes);
			if (prom.Promise.context.modes)
				for (var i in prom.Promise.context.modes)
					base[i] = prom.Promise.context.modes[i];
			if (!arg)
				return base;
			for (var i in arg)
				base[i] = arg[i];
			return base;
		}

		// deep chain's mode management
		ocm.modes = function(name, modes) { // local roles (i.e. in chain's context)
			return deep({}).modes(name, modes);
		};

		// deep chain's roles management
		ocm.roles = function() { // local modes (i.e. in chain's context)
			return deep({}).roles(argToArr.call(arguments));
		};
		return ocm;
	});<|endoftext|>


<commit_before>var express  = require('express');
var router   = express.Router();
var passport = require("passport");

var authenticationsController = require('../controllers/authenticationsController');
var startupsController = require('../controllers/startupsController');
var workspacesController = require('../controllers/workspacesController');

router.post('/login', authenticationsController.login);
router.post('/register', authenticationsController.register);

router.route('/startups')
  .get(startupsController.startupsIndex)

router.route('/startups/:id')
  .get(startupsController.startupsShow)
  .put(startupsController.startupsUpdate)
  .patch(startupsController.startupsUpdate)
  .delete(startupsController.startupsDelete)

router.route('/workspaces')
  .get(workspacesController.workspacesIndex)

router.route('/workspaces/:id')
  .get(workspacesController.workspacesShow)
  .put(workspacesController.workspacesUpdate)
  .patch(workspacesController.workspacesUpdate)
  .delete(workspacesController.workspacesDelete)

module.exports = router<commit_msg>Commented out routes for startups & workspaces<commit_after>var express  = require('express');
var router   = express.Router();
var passport = require("passport");

var authenticationsController = require('../controllers/authenticationsController');
var startupsController = require('../controllers/startupsController');
var workspacesController = require('../controllers/workspacesController');

router.post('/login', authenticationsController.login);
router.post('/register', authenticationsController.register);

// router.route('/startups')
//   .get(startupsController.startupsIndex)

// router.route('/startups/:id')
//   .get(startupsController.startupsShow)
//   .put(startupsController.startupsUpdate)
//   .patch(startupsController.startupsUpdate)
//   .delete(startupsController.startupsDelete)

// router.route('/workspaces')
//   .get(workspacesController.workspacesIndex)

// router.route('/workspaces/:id')
//   .get(workspacesController.workspacesShow)
//   .put(workspacesController.workspacesUpdate)
//   .patch(workspacesController.workspacesUpdate)
//   .delete(workspacesController.workspacesDelete)

module.exports = router<|endoftext|>


<commit_before>'use strict';

var Action = require('./action');
var Layout = require('./layout');
var Notification = require('./notification');
var Reminder = require('./reminder');

/**
 * Pin
 *
 * @constructor
 * @param {Object} [opts]
 */
var Pin = module.exports = function (opts) {

  this.reminders = [];
  this.actions = [];

  if (opts && opts.id) {
    if (typeof opts.id !== 'string') {
      throw new Error('Expected id to be a string.');
    }
    this.id = opts.id;
  }

  if (opts && opts.time) {
    if (!(opts.time instanceof Date)) {
      throw new Error('Expected time to be a Date.');
    }
    this.time = opts.time;
  }

  if (opts && opts.duration) {
    if (typeof opts.duration !== 'number') {
      throw new Error('Expected duration to be a number.');
    }
    this.duration = opts.duration;
  }

  if (opts && opts.createNotification) {
    this.createNotification = opts.createNotification instanceof Notification ?
      opts.createNotification : new Notification(opts.createNotification);
  }

  if (opts && opts.updateNotification) {
    if (!opts.updateNotification.time) {
      throw new Error('`time` is required by updateNotification.');
    }
    this.updateNotification = opts.updateNotification instanceof Notification ?
      opts.updateNotification : new Notification(opts.updateNotification);
  }

  if (opts && opts.layout) {
    if (!(opts.layout instanceof Layout)) {
      opts.layout = new Layout(opts.layout);
    }
    this.layout = opts.layout;
  }

  if (opts && opts.reminders) {
    if (!(opts.reminders instanceof Array)) {
      throw new Error('Expected reminders to be an array.');
    }
    opts.reminders.forEach(function (reminder) {
      this.reminders.push(new Reminder(reminder));
    }.bind(this));
  }

  if (opts && opts.actions) {
    if (!(opts.actions instanceof Array)) {
      throw new Error('Expected actions to be an array.');
    }
    opts.actions.forEach(function (action) {
      this.actions.push(new Action(action));
    }.bind(this));
  }

  if (!this.time) {
    throw new Error('`time` is required by Pin.');
  }

  if (!this.layout) {
    throw new Error('`layout` is required by Pin.');
  }
};

Pin.Icon = {
  NOTIFICATION_GENERIC: 'system://images/NOTIFICATION_GENERIC',
  NOTIFICATION_REMINDER: 'system://images/NOTIFICATION_REMINDER',
  NOTIFICATION_FLAG: 'system://images/NOTIFICATION_FLAG',
  NOTIFICATION_FACEBOOK_MESSENGER: 'system://images/NOTIFICATION_FACEBOOK_MESSENGER',
  NOTIFICATION_WHATSAPP: 'system://images/NOTIFICATION_WHATSAPP',
  NOTIFICATION_GMAIL: 'system://images/NOTIFICATION_GMAIL',
  NOTIFICATION_FACEBOOK: 'system://images/NOTIFICATION_FACEBOOK',
  NOTIFICATION_GOOGLE_HANGOUTS: 'system://images/NOTIFICATION_GOOGLE_HANGOUTS',
  NOTIFICATION_TELEGRAM: 'system://images/NOTIFICATION_TELEGRAM',
  NOTIFICATION_TWITTER: 'system://images/NOTIFICATION_TWITTER',
  GENERIC_EMAIL: 'system://images/GENERIC_EMAIL',
  GENERIC_SMS: 'system://images/GENERIC_SMS',
  GENERIC_WARNING: 'system://images/GENERIC_WARNING',
  GENERIC_CONFIRMATION: 'system://images/GENERIC_CONFIRMATION',
  PARTLY_CLOUDY: 'system://images/PARTLY_CLOUDY',
  CLOUDY_DAY: 'system://images/CLOUDY_DAY',
  LIGHT_SNOW: 'system://images/LIGHT_SNOW',
  LIGHT_RAIN: 'system://images/LIGHT_RAIN',
  HEAVY_RAIN: 'system://images/HEAVY_RAIN',
  HEAVY_SNOW: 'system://images/HEAVY_SNOW',
  TIMELINE_WEATHER: 'system://images/TIMELINE_WEATHER',
  TIMELINE_SUN: 'system://images/TIMELINE_SUN',
  TIMELINE_MISSED_CALL: 'system://images/TIMELINE_MISSED_CALL',
  TIMELINE_CALENDAR: 'system://images/TIMELINE_CALENDAR',
  TIMELINE_SPORTS: 'system://images/TIMELINE_SPORTS',
  TIMELINE_BASEBALL: 'system://images/TIMELINE_BASEBALL',
  AMERICAN_FOOTBALL: 'system://images/AMERICAN_FOOTBALL',
  CRICKET_GAME: 'system://images/CRICKET_GAME',
  SOCCER_GAME: 'system://images/SOCCER_GAME',
  HOCKEY_GAME: 'system://images/HOCKEY_GAME',
  RESULT_DISMISSED: 'system://images/RESULT_DISMISSED',
  RESULT_DELETED: 'system://images/RESULT_DELETED',
  RESULT_MUTE: 'system://images/RESULT_MUTE',
  RESULT_SENT: 'system://images/RESULT_SENT',
  WATCH_DISCONNECTED: 'system://images/WATCH_DISCONNECTED',
  STOCKS_EVENT: 'system://images/STOCKS_EVENT',
  MUSIC_EVENT: 'system://images/MUSIC_EVENT',
  BIRTHDAY_EVENT: 'system://images/BIRTHDAY_EVENT',
  PAY_BILL: 'system://images/PAY_BILL',
  HOTEL_RESERVATION: 'system://images/HOTEL_RESERVATION',
  TIDE_IS_HIGH: 'system://images/TIDE_IS_HIGH',
  NEWS_EVENT: 'system://images/NEWS_EVENT',
  SCHEDULED_EVENT: 'system://images/SCHEDULED_EVENT',
  DURING_PHONE_CALL: 'system://images/DURING_PHONE_CALL',
  CHECK_INTERNET_CONNECTION: 'system://images/CHECK_INTERNET_CONNECTION',
  MOVIE_EVENT: 'system://images/MOVIE_EVENT',
  GLUCOSE_MONITOR: 'system://images/GLUCOSE_MONITOR',
  ALARM_CLOCK: 'system://images/ALARM_CLOCK',
  CAR_RENTAL: 'system://images/CAR_RENTAL',
  DINNER_RESERVATION: 'system://images/DINNER_RESERVATION',
  RADIO_SHOW: 'system://images/RADIO_SHOW',
  AUDIO_CASSETTE: 'system://images/AUDIO_CASSETTE',
  SCHEDULED_FLIGHT: 'system://images/SCHEDULED_FLIGHT',

  /* deprecated */
  BASEBALL: 'system://images/TIMELINE_BASEBALL',
  CHAT: 'system://images/GENERIC_EMAIL',
  TAPE: 'system://images/AUDIO_CASSETTE',
  FOOTBALL: 'system://images/AMERICAN_FOOTBALL',
  MAIL: 'system://images/GENERIC_EMAIL',
  BULB: 'system://images/NOTIFICATION_FLAG',
  CALENDAR: 'system://images/TIMELINE_CALENDAR',
  SUN: 'system://images/TIMELINE_SUN',
  PIN: 'system://images/NOTIFICATION_FLAG',
  BATT_FULL: 'system://images/NOTIFICATION_FLAG',
  BATT_EMPTY: 'system://images/NOTIFICATION_FLAG',
  ALARM: 'system://images/ALARM_CLOCK',
};

Pin.LayoutType = {
  GENERIC_PIN: 'genericPin',
  CALENDAR_PIN: 'calendarPin',
  GENERIC_REMINDER: 'genericReminder',
  GENERIC_NOTIFICATION: 'genericNotification',
  COMM_NOTIFICATION: 'commNotification',
  WEATHER_PIN: 'weatherPin',
  SPORTS_PIN: 'sportsPin',
};

Pin.ActionType = {
  OPEN_WATCH_APP: 'openWatchApp',
};

Pin.Action = Action;
Pin.Layout = Layout;
Pin.Notification = Notification;
Pin.Reminder = Reminder;

/**
 * Add a reminder
 *
 * @param {(Reminder|Object)} reminder
 */
Pin.prototype.addReminder = function (reminder) {
  this.reminders.push(
    reminder instanceof Reminder ? reminder : new Reminder(reminder)
  );
  return this;
};

/**
 * Add an action
 *
 * @param {(Action|Object)} action
 */
Pin.prototype.addAction = function (action) {
  this.actions.push(
    action instanceof Action ? action : new Action(action)
  );
  return this;
};
<commit_msg>More icons!<commit_after>'use strict';

var Action = require('./action');
var Layout = require('./layout');
var Notification = require('./notification');
var Reminder = require('./reminder');

/**
 * Pin
 *
 * @constructor
 * @param {Object} [opts]
 */
var Pin = module.exports = function (opts) {

  this.reminders = [];
  this.actions = [];

  if (opts && opts.id) {
    if (typeof opts.id !== 'string') {
      throw new Error('Expected id to be a string.');
    }
    this.id = opts.id;
  }

  if (opts && opts.time) {
    if (!(opts.time instanceof Date)) {
      throw new Error('Expected time to be a Date.');
    }
    this.time = opts.time;
  }

  if (opts && opts.duration) {
    if (typeof opts.duration !== 'number') {
      throw new Error('Expected duration to be a number.');
    }
    this.duration = opts.duration;
  }

  if (opts && opts.createNotification) {
    this.createNotification = opts.createNotification instanceof Notification ?
      opts.createNotification : new Notification(opts.createNotification);
  }

  if (opts && opts.updateNotification) {
    if (!opts.updateNotification.time) {
      throw new Error('`time` is required by updateNotification.');
    }
    this.updateNotification = opts.updateNotification instanceof Notification ?
      opts.updateNotification : new Notification(opts.updateNotification);
  }

  if (opts && opts.layout) {
    if (!(opts.layout instanceof Layout)) {
      opts.layout = new Layout(opts.layout);
    }
    this.layout = opts.layout;
  }

  if (opts && opts.reminders) {
    if (!(opts.reminders instanceof Array)) {
      throw new Error('Expected reminders to be an array.');
    }
    opts.reminders.forEach(function (reminder) {
      this.reminders.push(new Reminder(reminder));
    }.bind(this));
  }

  if (opts && opts.actions) {
    if (!(opts.actions instanceof Array)) {
      throw new Error('Expected actions to be an array.');
    }
    opts.actions.forEach(function (action) {
      this.actions.push(new Action(action));
    }.bind(this));
  }

  if (!this.time) {
    throw new Error('`time` is required by Pin.');
  }

  if (!this.layout) {
    throw new Error('`layout` is required by Pin.');
  }
};

Pin.Icon = {
  NOTIFICATION_GENERIC: 'system://images/NOTIFICATION_GENERIC',
  NOTIFICATION_REMINDER: 'system://images/NOTIFICATION_REMINDER',
  NOTIFICATION_FLAG: 'system://images/NOTIFICATION_FLAG',
  NOTIFICATION_FACEBOOK_MESSENGER: 'system://images/NOTIFICATION_FACEBOOK_MESSENGER',
  NOTIFICATION_WHATSAPP: 'system://images/NOTIFICATION_WHATSAPP',
  NOTIFICATION_GMAIL: 'system://images/NOTIFICATION_GMAIL',
  NOTIFICATION_FACEBOOK: 'system://images/NOTIFICATION_FACEBOOK',
  NOTIFICATION_GOOGLE_HANGOUTS: 'system://images/NOTIFICATION_GOOGLE_HANGOUTS',
  NOTIFICATION_TELEGRAM: 'system://images/NOTIFICATION_TELEGRAM',
  NOTIFICATION_TWITTER: 'system://images/NOTIFICATION_TWITTER',
  NOTIFICATION_GOOGLE_INBOX: 'system://images/NOTIFICATION_GOOGLE_INBOX',
  NOTIFICATION_MAILBOX: 'system://images/NOTIFICATION_MAILBOX',
  NOTIFICATION_OUTLOOK: 'system://images/NOTIFICATION_OUTLOOK',
  NOTIFICATION_INSTAGRAM: 'system://images/NOTIFICATION_INSTAGRAM',
  NOTIFICATION_BLACKBERRY_MESSENGER: 'system://images/NOTIFICATION_BLACKBERRY_MESSENGER',
  NOTIFICATION_LINE: 'system://images/NOTIFICATION_LINE',
  NOTIFICATION_SNAPCHAT: 'system://images/NOTIFICATION_SNAPCHAT',
  NOTIFICATION_WECHAT: 'system://images/NOTIFICATION_WECHAT',
  NOTIFICATION_VIBER: 'system://images/NOTIFICATION_VIBER',
  NOTIFICATION_SKYPE: 'system://images/NOTIFICATION_SKYPE',
  NOTIFICATION_YAHOO_MAIL: 'system://images/NOTIFICATION_YAHOO_MAIL',
  GENERIC_EMAIL: 'system://images/GENERIC_EMAIL',
  GENERIC_SMS: 'system://images/GENERIC_SMS',
  GENERIC_WARNING: 'system://images/GENERIC_WARNING',
  GENERIC_CONFIRMATION: 'system://images/GENERIC_CONFIRMATION',
  GENERIC_QUESTION: 'system://images/GENERIC_QUESTION',
  PARTLY_CLOUDY: 'system://images/PARTLY_CLOUDY',
  CLOUDY_DAY: 'system://images/CLOUDY_DAY',
  LIGHT_SNOW: 'system://images/LIGHT_SNOW',
  LIGHT_RAIN: 'system://images/LIGHT_RAIN',
  HEAVY_RAIN: 'system://images/HEAVY_RAIN',
  HEAVY_SNOW: 'system://images/HEAVY_SNOW',
  TIMELINE_WEATHER: 'system://images/TIMELINE_WEATHER',
  TIMELINE_SUN: 'system://images/TIMELINE_SUN',
  RAINING_AND_SNOWING: 'system://images/RAINING_AND_SNOWING',
  TIMELINE_MISSED_CALL: 'system://images/TIMELINE_MISSED_CALL',
  TIMELINE_CALENDAR: 'system://images/TIMELINE_CALENDAR',
  TIMELINE_SPORTS: 'system://images/TIMELINE_SPORTS',
  TIMELINE_BASEBALL: 'system://images/TIMELINE_BASEBALL',
  AMERICAN_FOOTBALL: 'system://images/AMERICAN_FOOTBALL',
  CRICKET_GAME: 'system://images/CRICKET_GAME',
  SOCCER_GAME: 'system://images/SOCCER_GAME',
  HOCKEY_GAME: 'system://images/HOCKEY_GAME',
  RESULT_DISMISSED: 'system://images/RESULT_DISMISSED',
  RESULT_DELETED: 'system://images/RESULT_DELETED',
  RESULT_MUTE: 'system://images/RESULT_MUTE',
  RESULT_SENT: 'system://images/RESULT_SENT',
  RESULT_FAILED: 'system://images/RESULT_FAILED',
  STOCKS_EVENT: 'system://images/STOCKS_EVENT',
  MUSIC_EVENT: 'system://images/MUSIC_EVENT',
  BIRTHDAY_EVENT: 'system://images/BIRTHDAY_EVENT',
  PAY_BILL: 'system://images/PAY_BILL',
  HOTEL_RESERVATION: 'system://images/HOTEL_RESERVATION',
  TIDE_IS_HIGH: 'system://images/TIDE_IS_HIGH',
  NEWS_EVENT: 'system://images/NEWS_EVENT',
  SCHEDULED_EVENT: 'system://images/SCHEDULED_EVENT',
  DURING_PHONE_CALL: 'system://images/DURING_PHONE_CALL',
  CHECK_INTERNET_CONNECTION: 'system://images/CHECK_INTERNET_CONNECTION',
  MOVIE_EVENT: 'system://images/MOVIE_EVENT',
  GLUCOSE_MONITOR: 'system://images/GLUCOSE_MONITOR',
  ALARM_CLOCK: 'system://images/ALARM_CLOCK',
  CAR_RENTAL: 'system://images/CAR_RENTAL',
  DINNER_RESERVATION: 'system://images/DINNER_RESERVATION',
  RADIO_SHOW: 'system://images/RADIO_SHOW',
  AUDIO_CASSETTE: 'system://images/AUDIO_CASSETTE',
  SCHEDULED_FLIGHT: 'system://images/SCHEDULED_FLIGHT',
  NO_EVENTS: 'system://images/NO_EVENTS',
  REACHED_FITNESS_GOAL: 'system://images/REACHED_FITNESS_GOAL',
  DAY_SEPARATOR: 'system://images/DAY_SEPARATOR',
  WATCH_DISCONNECTED: 'system://images/WATCH_DISCONNECTED',
  TV_SHOW: 'system://images/TV_SHOW',

  /* deprecated */
  BASEBALL: 'system://images/TIMELINE_BASEBALL',
  CHAT: 'system://images/GENERIC_EMAIL',
  TAPE: 'system://images/AUDIO_CASSETTE',
  FOOTBALL: 'system://images/AMERICAN_FOOTBALL',
  MAIL: 'system://images/GENERIC_EMAIL',
  BULB: 'system://images/NOTIFICATION_FLAG',
  CALENDAR: 'system://images/TIMELINE_CALENDAR',
  SUN: 'system://images/TIMELINE_SUN',
  PIN: 'system://images/NOTIFICATION_FLAG',
  BATT_FULL: 'system://images/NOTIFICATION_FLAG',
  BATT_EMPTY: 'system://images/NOTIFICATION_FLAG',
  ALARM: 'system://images/ALARM_CLOCK',
};

Pin.LayoutType = {
  GENERIC_PIN: 'genericPin',
  CALENDAR_PIN: 'calendarPin',
  GENERIC_REMINDER: 'genericReminder',
  GENERIC_NOTIFICATION: 'genericNotification',
  COMM_NOTIFICATION: 'commNotification',
  WEATHER_PIN: 'weatherPin',
  SPORTS_PIN: 'sportsPin',
};

Pin.ActionType = {
  OPEN_WATCH_APP: 'openWatchApp',
};

Pin.Action = Action;
Pin.Layout = Layout;
Pin.Notification = Notification;
Pin.Reminder = Reminder;

/**
 * Add a reminder
 *
 * @param {(Reminder|Object)} reminder
 */
Pin.prototype.addReminder = function (reminder) {
  this.reminders.push(
    reminder instanceof Reminder ? reminder : new Reminder(reminder)
  );
  return this;
};

/**
 * Add an action
 *
 * @param {(Action|Object)} action
 */
Pin.prototype.addAction = function (action) {
  this.actions.push(
    action instanceof Action ? action : new Action(action)
  );
  return this;
};
<|endoftext|>


<commit_before>function towel_add_subform(slug) {
    var total_forms = $('#id_' + slug + '-TOTAL_FORMS');
    var new_id = parseInt(total_forms.val());

    total_forms.val(new_id + 1);
    var empty = $('#' + slug + '-empty');
    var form = empty.clone(true);
    form.removeClass('empty').attr('id', slug + '-' + new_id);

    var attributes = ['id', 'name', 'for'];
    for (var i=0; i<attributes.length; ++i) {
        var attr = attributes[i];

        form.find('*[' + attr + '*=__prefix__]').each(function() {
            var el = $(this);
            el.attr(attr, el.attr(attr).replace(/__prefix__/, new_id));
        });
    }

    form.appendTo(empty.parent()).hide().fadeIn();
    return false;
}
<commit_msg>Be a bit smarter when finding the insertion point for new subforms<commit_after>function towel_add_subform(slug) {
    var total_forms = $('#id_' + slug + '-TOTAL_FORMS');
    var new_id = parseInt(total_forms.val());

    total_forms.val(new_id + 1);
    var empty = $('#' + slug + '-empty');
    var form = empty.clone(true);
    form.removeClass('empty').attr('id', slug + '-' + new_id);

    var attributes = ['id', 'name', 'for'];
    for (var i=0; i<attributes.length; ++i) {
        var attr = attributes[i];

        form.find('*[' + attr + '*=__prefix__]').each(function() {
            var el = $(this);
            el.attr(attr, el.attr(attr).replace(/__prefix__/, new_id));
        });
    }

    // insert the form after the last sibling with the same tagName
    // cannot use siblings() here, because the empty element may be the
    // only one (if no objects exist until now)
    form.insertAfter(empty.parent().children('[id|=' + slug + ']:last')).hide().fadeIn();
    return false;
}
<|endoftext|>