<commit_before>exports.config = {
    seleniumAddress: 'http://192.168.2.130:4444/wd/hub',
    getPageTimeout: 600001,
    allScriptsTimeout: 5000001,
    framework: 'custom',
    // path relative to the current config file
    frameworkPath: require.resolve('protractor-cucumber-framework'),
    capabilities: {
        'browserName': 'chrome',
    },

    // Spec patterns are relative to this directory.
    specs: [
        'test/e2e/features/e2e.feature'
    ],

    ignoreUncaughtExceptions: true,

    baseUrl: 'https://www.google.nl/',

    cucumberOpts: {
        require: ['test/e2e/features/step_definitions/*.js',
        'test/e2e/conf/env.js'],
        tags: '@checkApi',
        format: 'pretty',
        profile: false,
        'no-source': true
    },
    onPrepare: function () {
        global.chai = require('chai');
        var chaiAsPromised = require('chai-as-promised')
        chai.use(chaiAsPromised);
        global.expect = chai.expect;
    }
};
<commit_msg>Update teamServer.conf.js<commit_after>exports.config = {
    seleniumAddress: 'http://192.168.2.130:4444/wd/hub',
    getPageTimeout: 600001,
    allScriptsTimeout: 5000001,
    framework: 'custom',
    // path relative to the current config file
    frameworkPath: require.resolve('protractor-cucumber-framework'),
    capabilities: {
        'browserName': 'firefox',
    },

    // Spec patterns are relative to this directory.
    specs: [
        'test/e2e/features/e2e.feature'
    ],

    ignoreUncaughtExceptions: true,

    baseUrl: 'https://www.google.nl/',

    cucumberOpts: {
        require: ['test/e2e/features/step_definitions/*.js',
        'test/e2e/conf/env.js'],
        tags: '@checkApi',
        format: 'pretty',
        profile: false,
        'no-source': true
    },
    onPrepare: function () {
        global.chai = require('chai');
        var chaiAsPromised = require('chai-as-promised')
        chai.use(chaiAsPromised);
        global.expect = chai.expect;
    }
};
<|endoftext|>


<commit_before>import SPELLS from 'common/SPELLS';

export const ABILITIES_AFFECTED_BY_HEALING_INCREASES = [
  SPELLS.DIVINE_HYMN_HEAL.id,
  SPELLS.GREATER_HEAL.id,
  SPELLS.FLASH_HEAL.id,
  SPELLS.PRAYER_OF_MENDING_HEAL.id,
  SPELLS.PRAYER_OF_HEALING.id,
  SPELLS.RENEW.id,
  SPELLS.HOLY_WORD_SERENITY.id,
  SPELLS.HOLY_WORD_SANCTIFY.id,
  SPELLS.HOLY_WORD_SALVATION_TALENT.id,
  SPELLS.DESPERATE_PRAYER.id,
  SPELLS.COSMIC_RIPPLE_TALENT.id,
  SPELLS.BINDING_HEAL_TALENT.id,
  SPELLS.CIRCLE_OF_HEALING_TALENT.id,
  SPELLS.HALO_HEAL.id,
  SPELLS.DIVINE_STAR_TALENT.id, // might have diff id for heal?
  SPELLS.GUILTY_CONSCIENCE.id,
  SPELLS.TRAIL_OF_LIGHT_TALENT.id,
];

// better off making things that -dont- proc it perhaps?
export const ABILITIES_THAT_TRIGGER_MASTERY = [
  SPELLS.DIVINE_HYMN_HEAL.id,
  SPELLS.GREATER_HEAL.id,
  SPELLS.FLASH_HEAL.id,
  SPELLS.PRAYER_OF_MENDING_HEAL.id,
  SPELLS.PRAYER_OF_HEALING.id,
  SPELLS.HOLY_WORD_SERENITY.id,
  SPELLS.HOLY_WORD_SANCTIFY.id,
  SPELLS.HOLY_WORD_SALVATION_TALENT.id,
  SPELLS.DESPERATE_PRAYER.id,
  SPELLS.COSMIC_RIPPLE_HEAL.id,
  SPELLS.BINDING_HEAL_TALENT.id,
  SPELLS.CIRCLE_OF_HEALING_TALENT.id,
  SPELLS.HALO_HEAL.id,
  SPELLS.DIVINE_STAR_HEAL.id, // might have diff id for heal?
  SPELLS.GUILTY_CONSCIENCE.id,
  SPELLS.RENEW.id, // this is reduced in calculations, due to the initial tick proccing EoL but not the periodic ticks
  SPELLS.TRAIL_OF_LIGHT_TALENT.id,
];

export const ABILITIES_THAT_TRIGGER_ENDURING_RENEWAL = [
  SPELLS.GREATER_HEAL.id,
  SPELLS.FLASH_HEAL.id,
  SPELLS.HOLY_WORD_SERENITY.id,
  SPELLS.BINDING_HEAL_TALENT.id,
];

export const ABILITIES_AFFECTED_BY_APOTHEOSIS_TALENT = [
  SPELLS.HOLY_WORD_SERENITY.id,
  SPELLS.HOLY_WORD_SANCTIFY.id,
];
<commit_msg>Adding holy nova to the mastery spells<commit_after>import SPELLS from 'common/SPELLS';

export const ABILITIES_AFFECTED_BY_HEALING_INCREASES = [
  SPELLS.DIVINE_HYMN_HEAL.id,
  SPELLS.GREATER_HEAL.id,
  SPELLS.FLASH_HEAL.id,
  SPELLS.PRAYER_OF_MENDING_HEAL.id,
  SPELLS.PRAYER_OF_HEALING.id,
  SPELLS.RENEW.id,
  SPELLS.HOLY_WORD_SERENITY.id,
  SPELLS.HOLY_WORD_SANCTIFY.id,
  SPELLS.HOLY_WORD_SALVATION_TALENT.id,
  SPELLS.DESPERATE_PRAYER.id,
  SPELLS.COSMIC_RIPPLE_TALENT.id,
  SPELLS.BINDING_HEAL_TALENT.id,
  SPELLS.CIRCLE_OF_HEALING_TALENT.id,
  SPELLS.HALO_HEAL.id,
  SPELLS.DIVINE_STAR_TALENT.id, // might have diff id for heal?
  SPELLS.GUILTY_CONSCIENCE.id,
  SPELLS.TRAIL_OF_LIGHT_TALENT.id,
];

// better off making things that -dont- proc it perhaps?
export const ABILITIES_THAT_TRIGGER_MASTERY = [
  SPELLS.DIVINE_HYMN_HEAL.id,
  SPELLS.GREATER_HEAL.id,
  SPELLS.FLASH_HEAL.id,
  SPELLS.PRAYER_OF_MENDING_HEAL.id,
  SPELLS.PRAYER_OF_HEALING.id,
  SPELLS.HOLY_WORD_SERENITY.id,
  SPELLS.HOLY_WORD_SANCTIFY.id,
  SPELLS.HOLY_WORD_SALVATION_TALENT.id,
  SPELLS.DESPERATE_PRAYER.id,
  SPELLS.COSMIC_RIPPLE_HEAL.id,
  SPELLS.BINDING_HEAL_TALENT.id,
  SPELLS.CIRCLE_OF_HEALING_TALENT.id,
  SPELLS.HALO_HEAL.id,
  SPELLS.DIVINE_STAR_HEAL.id, // might have diff id for heal?
  SPELLS.GUILTY_CONSCIENCE.id,
  SPELLS.RENEW.id, // this is reduced in calculations, due to the initial tick proccing EoL but not the periodic ticks
  SPELLS.TRAIL_OF_LIGHT_TALENT.id,
  SPELLS.HOLY_NOVA_HEAL.id,
];

export const ABILITIES_THAT_TRIGGER_ENDURING_RENEWAL = [
  SPELLS.GREATER_HEAL.id,
  SPELLS.FLASH_HEAL.id,
  SPELLS.HOLY_WORD_SERENITY.id,
  SPELLS.BINDING_HEAL_TALENT.id,
];

export const ABILITIES_AFFECTED_BY_APOTHEOSIS_TALENT = [
  SPELLS.HOLY_WORD_SERENITY.id,
  SPELLS.HOLY_WORD_SANCTIFY.id,
];
<|endoftext|>


<commit_before>if(self.location.protocol === "file:"){
	alert("The documentation is not going to work properly if accessed from a file system. You should use an HTTP server instead.");
}

luga.namespace("luga.docs");

(function(){
	"use strict";

	var Controller = function(){

		var CONST = {
			CSS_CLASSES: {
				CURRENT: "current"
			},
			SELECTORS: {
				CONTENT: "#content",
				NAVIGATION: "#navigation"
			},
			INCLUDES_PATH: "fragments/",
			INCLUDES_SUFFIX: ".inc",
			DEFAULT_INCLUDE_ID: "index",
			LOCAL_NAV_ID: "nav-local.inc"
		};

		/**
		 * @type {luga.router.Router}
		 */
		var router = new luga.router.Router();

		var init = function(){
			initRouter();
			if(router.resolve(router.normalizeHash(location.hash)) === false){
				// Current hash is not resolved, load default content
				loadPage(CONST.DEFAULT_INCLUDE_ID);
			}
		};

		var initRouter = function(){
			router.add("index", routeResolver);

			router.add("common/index", routeResolver);
			router.add("common/form", routeResolver);
			router.add("common/string", routeResolver);
			router.add("common/notifier", routeResolver);

			router.add("ajaxform/index", routeResolver);
			router.add("ajaxform/getting-started", routeResolver);
			router.add("ajaxform/syntax", routeResolver);
			router.add("ajaxform/samples/complete", routeResolver);
			router.add("ajaxform/samples/success-handler", routeResolver);
			router.add("ajaxform/samples/error-handler", routeResolver);
			router.add("ajaxform/samples/before-after", routeResolver);
			router.add("ajaxform/samples/validator", routeResolver);
			router.add("ajaxform/api/syntax", routeResolver);
			router.add("ajaxform/api/samples", routeResolver);
			router.add("ajaxform/api/raw-json", routeResolver);

			router.add("data/index", routeResolver);
			router.add("data/getting-started", routeResolver);
			router.add("data/faq", routeResolver);
			router.add("data/debugging", routeResolver);

			router.add("data/dataset/getting-started", routeResolver);
			router.add("data/dataset/databinding", routeResolver);
			router.add("data/dataset/filter", routeResolver);
			router.add("data/dataset/formatter", routeResolver);
			router.add("data/dataset/sort", routeResolver);
			router.add("data/dataset/api", routeResolver);

			router.add("data/json-dataset/getting-started", routeResolver);
			router.add("data/json-dataset/path", routeResolver);
			router.add("data/json-dataset/master-details", routeResolver);
			router.add("data/json-dataset/showmore-scrolling-body", routeResolver);
			router.add("data/json-dataset/showmore-scrolling-div", routeResolver);
			router.add("data/json-dataset/showmore-button", routeResolver);
			router.add("data/json-dataset/api", routeResolver);

			router.add("data/xml-dataset/getting-started", routeResolver);
			router.add("data/xml-dataset/path", routeResolver);
			router.add("data/xml-dataset/master-details", routeResolver);
			router.add("data/xml-dataset/api", routeResolver);

			router.add("data/detailset/master-details", routeResolver);
			router.add("data/detailset/api", routeResolver);

			router.add("data/region/getting-started", routeResolver);
			router.add("data/region/handlebars", routeResolver);
			router.add("data/region/context", routeResolver);
			router.add("data/region/state", routeResolver);
			router.add("data/region/traits", routeResolver);
			router.add("data/region/syntax", routeResolver);
			router.add("data/region/scripting", routeResolver);

			router.add("data/extensibility/custom-dataset", routeResolver);
			router.add("data/extensibility/custom-region-type", routeResolver);
			router.add("data/extensibility/custom-trait", routeResolver);

			router.add("validator/index", routeResolver);
			router.add("validator/getting-started", routeResolver);
			router.add("validator/syntax", routeResolver);
			router.add("validator/faq", routeResolver);

			router.add("validator/samples/complete", routeResolver);
			router.add("validator/samples/registration", routeResolver);
			router.add("validator/samples/date", routeResolver);
			router.add("validator/samples/checkboxes", routeResolver);
			router.add("validator/samples/radio", routeResolver);
			router.add("validator/samples/select", routeResolver);
			router.add("validator/samples/conditional-validation", routeResolver);
			router.add("validator/samples/handlers-errorbox", routeResolver);
			router.add("validator/samples/dom-changes", routeResolver);
			router.add("validator/samples/html5", routeResolver);

			router.add("validator/extensibility/custom-patterns", routeResolver);
			router.add("validator/extensibility/custom-date-patterns", routeResolver);
			router.add("validator/extensibility/custom-validation", routeResolver);
			router.add("validator/extensibility/handlers-custom", routeResolver);
			router.add("validator/extensibility/custom-error", routeResolver);

			router.add("validator/bootstrap/samples", routeResolver);

			router.add("validator/api/syntax", routeResolver);
			router.add("validator/api/samples", routeResolver);

			router.start();
		};

		/**
		 * Execute registered enter callbacks, if any
		 * @param {luga.router.routeContext} context
		 */
		var routeResolver = function(context){

			luga.data.dataSourceRegistry = {};

			jQuery(CONST.SELECTORS.CONTENT).empty();
			jQuery(CONST.SELECTORS.NAVIGATION).empty();

			var tokens = context.fragment.split("/");
			loadPage(context.fragment);

			// Needs navigation
			if(tokens.length > 1){
				loadNavigation(tokens[0], context.fragment);
			}
		};

		var loadPage = function(id){
			var fragmentUrl = CONST.INCLUDES_PATH + id + CONST.INCLUDES_SUFFIX;

			jQuery.ajax(fragmentUrl)
					.done(function(response, textStatus, jqXHR){
						// Read include and inject content
						jQuery(CONST.SELECTORS.CONTENT).html(jqXHR.responseText);

						// Bootstrap libs
						luga.ajaxform.initForms();
						jQuery(luga.data.region.CONST.SELECTORS.REGION).each(function(index, item){
							luga.data.region.init(jQuery(item));
						});
						luga.validator.initForms();

						Prism.highlightAll();

					})
					.fail(function(){
						// TODO: implement error handling
						console.log("Error loading fragment");
					});

		};

		var loadNavigation = function(id, fragment){
			var fragmentUrl = CONST.INCLUDES_PATH + id + "/" + CONST.LOCAL_NAV_ID;
			jQuery.ajax(fragmentUrl)
					.done(function(response, textStatus, jqXHR){
						// Read include and inject content
						jQuery(CONST.SELECTORS.NAVIGATION).html(jqXHR.responseText);
						highlightNav(fragment);
					})
					.fail(function(){
						// TODO: implement error handling
						console.log("Error loading fragment");
					});

		};

		var highlightNav = function(fragment){
			jQuery(CONST.SELECTORS.NAVIGATION).find("a").each(function(index, item){
				if(isCurrentFragment(jQuery(item).attr("href"))){
					jQuery(item).parent().addClass(CONST.CSS_CLASSES.CURRENT);
				}
			});
		};

		var isCurrentFragment = function(href){
			var tokens = href.split("/");
			var destination = tokens[tokens.length -2] + "/" + tokens[tokens.length -1];
			return location.href.indexOf(destination) > 0;
		};

		init();

	};

	jQuery(document).ready(function(){
		luga.docs.controller = new Controller();
	});

}());<commit_msg>Docs: Dynamically set page title<commit_after>if(self.location.protocol === "file:"){
	alert("The documentation is not going to work properly if accessed from a file system. You should use an HTTP server instead.");
}

luga.namespace("luga.docs");

(function(){
	"use strict";

	var Controller = function(){

		var CONST = {
			TITLE_ROOT: "Luga",
			TITLE_SEPARATOR : " :: ",
			CSS_CLASSES: {
				CURRENT: "current"
			},
			SELECTORS: {
				CONTENT: "#content",
				NAVIGATION: "#navigation"
			},
			INCLUDES_PATH: "fragments/",
			INCLUDES_SUFFIX: ".inc",
			DEFAULT_INCLUDE_ID: "index",
			LOCAL_NAV_ID: "nav-local.inc"
		};

		/**
		 * @type {luga.router.Router}
		 */
		var router = new luga.router.Router();

		var init = function(){
			initRouter();
			if(router.resolve(router.normalizeHash(location.hash)) === false){
				// Current hash is not resolved, load default content
				loadPage(CONST.DEFAULT_INCLUDE_ID);
			}
		};

		var initRouter = function(){
			router.add("index", routeResolver);

			router.add("common/index", routeResolver);
			router.add("common/form", routeResolver);
			router.add("common/string", routeResolver);
			router.add("common/notifier", routeResolver);

			router.add("ajaxform/index", routeResolver);
			router.add("ajaxform/getting-started", routeResolver);
			router.add("ajaxform/syntax", routeResolver);
			router.add("ajaxform/samples/complete", routeResolver);
			router.add("ajaxform/samples/success-handler", routeResolver);
			router.add("ajaxform/samples/error-handler", routeResolver);
			router.add("ajaxform/samples/before-after", routeResolver);
			router.add("ajaxform/samples/validator", routeResolver);
			router.add("ajaxform/api/syntax", routeResolver);
			router.add("ajaxform/api/samples", routeResolver);
			router.add("ajaxform/api/raw-json", routeResolver);

			router.add("data/index", routeResolver);
			router.add("data/getting-started", routeResolver);
			router.add("data/faq", routeResolver);
			router.add("data/debugging", routeResolver);

			router.add("data/dataset/getting-started", routeResolver);
			router.add("data/dataset/databinding", routeResolver);
			router.add("data/dataset/filter", routeResolver);
			router.add("data/dataset/formatter", routeResolver);
			router.add("data/dataset/sort", routeResolver);
			router.add("data/dataset/api", routeResolver);

			router.add("data/json-dataset/getting-started", routeResolver);
			router.add("data/json-dataset/path", routeResolver);
			router.add("data/json-dataset/master-details", routeResolver);
			router.add("data/json-dataset/showmore-scrolling-body", routeResolver);
			router.add("data/json-dataset/showmore-scrolling-div", routeResolver);
			router.add("data/json-dataset/showmore-button", routeResolver);
			router.add("data/json-dataset/api", routeResolver);

			router.add("data/xml-dataset/getting-started", routeResolver);
			router.add("data/xml-dataset/path", routeResolver);
			router.add("data/xml-dataset/master-details", routeResolver);
			router.add("data/xml-dataset/api", routeResolver);

			router.add("data/detailset/master-details", routeResolver);
			router.add("data/detailset/api", routeResolver);

			router.add("data/region/getting-started", routeResolver);
			router.add("data/region/handlebars", routeResolver);
			router.add("data/region/context", routeResolver);
			router.add("data/region/state", routeResolver);
			router.add("data/region/traits", routeResolver);
			router.add("data/region/syntax", routeResolver);
			router.add("data/region/scripting", routeResolver);

			router.add("data/extensibility/custom-dataset", routeResolver);
			router.add("data/extensibility/custom-region-type", routeResolver);
			router.add("data/extensibility/custom-trait", routeResolver);

			router.add("validator/index", routeResolver);
			router.add("validator/getting-started", routeResolver);
			router.add("validator/syntax", routeResolver);
			router.add("validator/faq", routeResolver);

			router.add("validator/samples/complete", routeResolver);
			router.add("validator/samples/registration", routeResolver);
			router.add("validator/samples/date", routeResolver);
			router.add("validator/samples/checkboxes", routeResolver);
			router.add("validator/samples/radio", routeResolver);
			router.add("validator/samples/select", routeResolver);
			router.add("validator/samples/conditional-validation", routeResolver);
			router.add("validator/samples/handlers-errorbox", routeResolver);
			router.add("validator/samples/dom-changes", routeResolver);
			router.add("validator/samples/html5", routeResolver);

			router.add("validator/extensibility/custom-patterns", routeResolver);
			router.add("validator/extensibility/custom-date-patterns", routeResolver);
			router.add("validator/extensibility/custom-validation", routeResolver);
			router.add("validator/extensibility/handlers-custom", routeResolver);
			router.add("validator/extensibility/custom-error", routeResolver);

			router.add("validator/bootstrap/samples", routeResolver);

			router.add("validator/api/syntax", routeResolver);
			router.add("validator/api/samples", routeResolver);

			router.start();
		};

		/**
		 * Execute registered enter callbacks, if any
		 * @param {luga.router.routeContext} context
		 */
		var routeResolver = function(context){

			luga.data.dataSourceRegistry = {};

			jQuery(CONST.SELECTORS.CONTENT).empty();
			jQuery(CONST.SELECTORS.NAVIGATION).empty();

			var tokens = context.fragment.split("/");
			loadPage(context.fragment);
			setPageTitle(tokens);

			// Needs navigation
			if(tokens.length > 1){
				loadNavigation(tokens[0], context.fragment);
			}
		};

		var setPageTitle = function(tokens){
			var title = CONST.TITLE_ROOT;
			if(tokens[1] !== undefined){
				title += CONST.TITLE_SEPARATOR + tokens[0][0].toUpperCase() + tokens[0].substring(1);
			}
			if(tokens[2] !== undefined){
				title += CONST.TITLE_SEPARATOR + tokens[1];
			}
			document.title = title;
		};

		var loadPage = function(id){
			var fragmentUrl = CONST.INCLUDES_PATH + id + CONST.INCLUDES_SUFFIX;

			jQuery.ajax(fragmentUrl)
					.done(function(response, textStatus, jqXHR){
						// Read include and inject content
						jQuery(CONST.SELECTORS.CONTENT).html(jqXHR.responseText);

						// Bootstrap libs
						luga.ajaxform.initForms();
						jQuery(luga.data.region.CONST.SELECTORS.REGION).each(function(index, item){
							luga.data.region.init(jQuery(item));
						});
						luga.validator.initForms();

						Prism.highlightAll();

					})
					.fail(function(){
						// TODO: implement error handling
						console.log("Error loading fragment");
					});

		};

		var loadNavigation = function(id, fragment){
			var fragmentUrl = CONST.INCLUDES_PATH + id + "/" + CONST.LOCAL_NAV_ID;
			jQuery.ajax(fragmentUrl)
					.done(function(response, textStatus, jqXHR){
						// Read include and inject content
						jQuery(CONST.SELECTORS.NAVIGATION).html(jqXHR.responseText);
						highlightNav(fragment);
					})
					.fail(function(){
						// TODO: implement error handling
						console.log("Error loading fragment");
					});

		};

		var highlightNav = function(fragment){
			jQuery(CONST.SELECTORS.NAVIGATION).find("a").each(function(index, item){
				if(isCurrentFragment(jQuery(item).attr("href"))){
					jQuery(item).parent().addClass(CONST.CSS_CLASSES.CURRENT);
				}
			});
		};

		var isCurrentFragment = function(href){
			var tokens = href.split("/");
			var destination = tokens[tokens.length -2] + "/" + tokens[tokens.length -1];
			return location.href.indexOf(destination) > 0;
		};

		init();

	};

	jQuery(document).ready(function(){
		luga.docs.controller = new Controller();
	});

}());<|endoftext|>


<commit_before>var _ = require('underscore-cdb-v3');
var cdb = require('cartodb.js-v3');
var ContentControllerView = require('../../../../javascripts/cartodb/dashboard/content_controller_view_static');
var Router = require('../../../../javascripts/cartodb/dashboard/router');
var LocalStorage = require('../../../../javascripts/cartodb/common/local_storage');

describe('dashboard/content_controller_view_static', function () {
  beforeEach(function () {
    this.collection = new cdb.admin.Visualizations();
    spyOn(this.collection, 'bind').and.callThrough();

    var attrs = {
      username: 'pepe',
      base_url: 'http://pepe.carto.com',
      email: 'pepe@carto.com',
      account_type: 'FREE'
    };

    this.user = new cdb.admin.User(attrs);
    spyOn(this.user, 'featureEnabled').and.returnValue(true);

    this.router = new Router({
      dashboardUrl: this.user.viewUrl().dashboard()
    });
    spyOn(this.router.model, 'bind').and.callThrough();

    this.localStorage = new LocalStorage('test');

    this.view = new ContentControllerView({
      headerHeight: 80,
      user: this.user,
      router: this.router,
      collection: this.collection,
      localStorage: this.localStorage
    });

    this.vis = new cdb.admin.Visualization({
      privacy: 'public',
      permission: {
        owner: attrs
      }
    });

    window.defaultFallbackMapBaselayer = {
      url: ''
    };
  });

  describe('.render', function () {
    it('should render properly', function () {
      spyOn(this.view, '_initViews');

      this.view.render();

      expect(this.view.$el.html()).toContain('

');
      expect(this.view.$el.html()).toContain('

');
      expect(this.view.$el.html()).toContain('

');
      expect(this.view.$el.html()).toContain('

');
      expect(this.view._initViews).toHaveBeenCalled();
    });
  });

  describe('._initViews', function () {
    it('should init views', function () {
      this.view.render();

      expect(_.size(this.view._subviews)).toBe(9);
    });
  });

  describe('router changes', function () {
    beforeEach(function () {
      this.view.render();
    });

    describe('when content type is not defined', function () {
      it('should show main loader when content_type changes', function () {
        this.collection.total_user_entries = 10;
        this.router.model.set({ content_type: 'datasets' });

        expect(this.view._isBlockEnabled('main_loader')).toBe(true);

        this.collection.reset([ this.vis ]);
        this.router.model.set({ tag: 'test' });

        expect(this.view._isBlockEnabled('main_loader')).toBe(false);
      });
    });

    describe('when content type has changed', function () {
      it('should show main loader when content_type changes', function () {
        this.router.model.set({ content_type: 'datasets' }, { silent: true });
        this.collection.reset([ this.vis ]);

        expect(this.view._isBlockEnabled('list')).toBe(true);

        this.router.model.set({ content_type: 'maps' });

        expect(this.view._isBlockEnabled('main_loader')).toBe(true);
      });
    });

    describe('when content type hasn\'t changed', function () {
      it('should show small loader when router changes', function () {
        this.collection.total_user_entries = 3;
        this.router.model.set({ content_type: 'datasets' }, { silent: true });
        this.collection.reset([ this.vis ]);
        this.router.model.set({ tag: 'paco' });

        expect(this.view._isBlockEnabled('main_loader')).toBe(false);
      });

      it('should show main loader when content type doesn\'t change but user didn\'t have entries', function () {
        this.router.model.set({ content_type: 'datasets' }, { silent: true });
        this.collection.total_user_entries = 0;
        this.collection.reset([ this.vis ]);
        this.router.model.set({ shared: 'only' });

        expect(this.view._isBlockEnabled('main_loader')).toBe(true);
      });
    });
  });

  describe('collection changes', function () {
    beforeEach(function () {
      this.view.render();
    });

    it('should show list when collection fetch works', function () {
      this.router.model.set({ content_type: 'datasets' });
      this.collection.reset([ this.vis ]);

      expect(this.view._isBlockEnabled('list')).toBe(true);
      expect(this.view._isBlockEnabled('content_footer')).toBe(true);
      expect(this.view._isBlockEnabled('main_loader')).toBe(false);
      expect(_.size(this.view.enabledViews)).toBe(3);
    });

    it('should show error block when collection fetch fails', function () {
      this.router.model.set({ content_type: 'datasets' });
      this.collection.trigger('loading');

      expect(this.view._isBlockEnabled('error')).toBe(false);

      this.collection.trigger('error');

      expect(this.view._isBlockEnabled('error')).toBe(true);
      expect(this.view._isBlockEnabled('list')).toBe(false);
      expect(_.size(this.view.enabledViews)).toBe(2);
    });

    it('shouldn\'t show error block when collection fetch is aborted', function () {
      this.router.model.set({ content_type: 'datasets' });
      this.collection.trigger('loading');

      expect(this.view._isBlockEnabled('error')).toBe(false);

      this.collection.trigger('error', this.collection, { statusText: 'abort' }, {});

      expect(this.view._isBlockEnabled('error')).toBe(false);
      expect(_.size(this.view.enabledViews)).toBe(2);
    });

    it('should not redirect to shared route when collection is empty, none of the filters are applied but shared datasets are present, being in datasets', function () {
      var url = '';
      var options;
      this.router.navigate = function (u, opts) {
        url = u;
        options = opts;
      };
      this.router.model.set({ content_type: 'datasets' }, { silent: true });
      this.collection.total_shared = 10;
      this.collection.reset([]);

      expect(url.toString().search('shared') === -1).toBe(true);
    });

    it('should not redirect to library route when collection is empty and none of the filters are applied, being in datasets', function () {
      cdb.config.set('data_library_enabled', true);
      var url = '';
      var options;
      this.router.navigate = function (u, opts) {
        url = u;
        options = opts;
      };
      this.router.model.set({ content_type: 'datasets' }, { silent: true });
      this.collection.total_shared = 0;
      this.collection.reset([]);

      expect(url.toString().search('library') !== -1).toBe(true);
    });

    it('should show empty datasets when collection is empty, none of the filters are applied and data library is disabled', function () {
      cdb.config.set('data_library_enabled', false);
      this.router.model.set({ content_type: 'datasets', library: true });
      this.collection.total_user_entries = 0;
      this.collection.reset([]);

      expect(this.view._isBlockEnabled('no_datasets')).toBe(true);
    });

    it('should show empty datasets when visits library and user didn\'t have any dataset', function () {
      this.router.model.set({ content_type: 'datasets', library: true });
      this.collection.total_user_entries = 0;
      this.collection.reset([]);

      expect(this.view._isBlockEnabled('no_datasets')).toBe(true);
    });

    it('should show onboarding map when collection is empty and content_type is in maps', function () {
      spyOn(cdb, 'createVis'); // mock the fallback map
      this.router.model.set({ content_type: 'maps' }, { silent: true });
      this.collection.reset([]);

      expect(this.view._isBlockEnabled('no_results')).toBe(false);
      expect(this.view._isBlockEnabled('onboarding')).toBe(true);
      expect(cdb.createVis).toHaveBeenCalled();
    });

    it('should show loading library when collection is empty and trying to see library', function () {
      this.router.model.set({ library: true, shared: 'no' }, { silent: true });
      this.collection.reset([]);

      expect(this.view._isBlockEnabled('loading_library')).toBe(true);
      expect(this.view._isBlockEnabled('no_datasets')).toBe(false);
    });

    it('should show no_results block when collection is empty and any of the filters are enabled', function () {
      this.router.model.set({ content_type: 'datasets', tag: 'jar' }, { silent: true });
      this.collection.reset([]);

      expect(this.view._isBlockEnabled('no_results')).toBe(true);

      this.router.model.set({ q: 'paco' }, { silent: true });
      this.collection.reset([]);

      expect(this.view._isBlockEnabled('no_results')).toBe(true);
    });
  });

  it('should not have leaks', function () {
    this.view.render();

    expect(this.view).toHaveNoLeaks();
  });

  afterEach(function () {
    this.view.clean();
    window.defaultFallbackBasemapTemplateUrl = undefined;
    delete window.defaultFallbackBasemapTemplateUrl;
  });
});
<commit_msg>fix specs for real this time<commit_after>var _ = require('underscore-cdb-v3');
var cdb = require('cartodb.js-v3');
var ContentControllerView = require('../../../../javascripts/cartodb/dashboard/content_controller_view_static');
var Router = require('../../../../javascripts/cartodb/dashboard/router');
var LocalStorage = require('../../../../javascripts/cartodb/common/local_storage');

describe('dashboard/content_controller_view_static', function () {
  beforeEach(function () {
    this.collection = new cdb.admin.Visualizations();
    spyOn(this.collection, 'bind').and.callThrough();

    var attrs = {
      username: 'pepe',
      base_url: 'http://pepe.carto.com',
      email: 'pepe@carto.com',
      account_type: 'FREE'
    };

    this.user = new cdb.admin.User(attrs);
    spyOn(this.user, 'featureEnabled').and.returnValue(true);

    this.router = new Router({
      dashboardUrl: this.user.viewUrl().dashboard()
    });
    spyOn(this.router.model, 'bind').and.callThrough();

    this.localStorage = new LocalStorage('test');

    this.view = new ContentControllerView({
      headerHeight: 80,
      user: this.user,
      router: this.router,
      collection: this.collection,
      localStorage: this.localStorage
    });

    this.vis = new cdb.admin.Visualization({
      privacy: 'public',
      permission: {
        owner: attrs
      }
    });

    window.defaultFallbackMapBaselayer = {
      url: ''
    };
  });

  describe('.render', function () {
    it('should render properly', function () {
      spyOn(this.view, '_initViews');

      this.view.render();

      expect(this.view.$el.html()).toContain('

');
      expect(this.view.$el.html()).toContain('

');
      expect(this.view.$el.html()).toContain('

');
      expect(this.view.$el.html()).toContain('

');
      expect(this.view._initViews).toHaveBeenCalled();
    });
  });

  describe('._initViews', function () {
    it('should init views', function () {
      this.view.render();

      expect(_.size(this.view._subviews)).toBe(9);
    });
  });

  describe('router changes', function () {
    beforeEach(function () {
      this.view.render();
    });

    describe('when content type is not defined', function () {
      it('should show main loader when content_type changes', function () {
        this.collection.total_user_entries = 10;
        this.router.model.set({ content_type: 'datasets' });

        expect(this.view._isBlockEnabled('main_loader')).toBe(true);

        this.collection.reset([ this.vis ]);
        this.router.model.set({ tag: 'test' });

        expect(this.view._isBlockEnabled('main_loader')).toBe(false);
      });
    });

    describe('when content type has changed', function () {
      it('should show main loader when content_type changes', function () {
        this.router.model.set({ content_type: 'datasets' }, { silent: true });
        this.collection.reset([ this.vis ]);

        expect(this.view._isBlockEnabled('list')).toBe(true);

        this.router.model.set({ content_type: 'maps' });

        expect(this.view._isBlockEnabled('main_loader')).toBe(true);
      });
    });

    describe('when content type hasn\'t changed', function () {
      it('should show small loader when router changes', function () {
        this.collection.total_user_entries = 3;
        this.router.model.set({ content_type: 'datasets' }, { silent: true });
        this.collection.reset([ this.vis ]);
        this.router.model.set({ tag: 'paco' });

        expect(this.view._isBlockEnabled('main_loader')).toBe(false);
      });

      it('should show main loader when content type doesn\'t change but user didn\'t have entries', function () {
        this.router.model.set({ content_type: 'datasets' }, { silent: true });
        this.collection.total_user_entries = 0;
        this.collection.reset([ this.vis ]);
        this.router.model.set({ shared: 'only' });

        expect(this.view._isBlockEnabled('main_loader')).toBe(true);
      });
    });
  });

  describe('collection changes', function () {
    beforeEach(function () {
      this.view.render();
    });

    it('should show list when collection fetch works', function () {
      this.router.model.set({ content_type: 'datasets' });
      this.collection.reset([ this.vis ]);

      expect(this.view._isBlockEnabled('list')).toBe(true);
      expect(this.view._isBlockEnabled('content_footer')).toBe(true);
      expect(this.view._isBlockEnabled('main_loader')).toBe(false);
      expect(_.size(this.view.enabledViews)).toBe(3);
    });

    it('should show error block when collection fetch fails', function () {
      this.router.model.set({ content_type: 'datasets' });
      this.collection.trigger('loading');

      expect(this.view._isBlockEnabled('error')).toBe(false);

      this.collection.trigger('error');

      expect(this.view._isBlockEnabled('error')).toBe(true);
      expect(this.view._isBlockEnabled('list')).toBe(false);
      expect(_.size(this.view.enabledViews)).toBe(2);
    });

    it('shouldn\'t show error block when collection fetch is aborted', function () {
      this.router.model.set({ content_type: 'datasets' });
      this.collection.trigger('loading');

      expect(this.view._isBlockEnabled('error')).toBe(false);

      this.collection.trigger('error', this.collection, { statusText: 'abort' }, {});

      expect(this.view._isBlockEnabled('error')).toBe(false);
      expect(_.size(this.view.enabledViews)).toBe(2);
    });

    it('should not redirect to shared route when collection is empty, none of the filters are applied but shared datasets are present, being in datasets', function () {
      var url = '';
      var options;
      this.router.navigate = function (u, opts) {
        url = u;
        options = opts;
      };
      this.router.model.set({ content_type: 'datasets' }, { silent: true });
      this.collection.total_shared = 10;
      this.collection.reset([]);

      expect(url.toString().search('shared') === -1).toBe(true);
    });

    it('should not redirect to library route when collection is empty and none of the filters are applied, being in datasets', function () {
      cdb.config.set('data_library_enabled', true);
      var url = '';
      var options;
      this.router.navigate = function (u, opts) {
        url = u;
        options = opts;
      };
      this.router.model.set({ content_type: 'datasets' }, { silent: true });
      this.collection.total_shared = 0;
      this.collection.reset([]);

      expect(url.toString().search('library') === -1).toBe(true);
    });

    it('should show empty datasets when collection is empty, none of the filters are applied and data library is disabled', function () {
      cdb.config.set('data_library_enabled', false);
      this.router.model.set({ content_type: 'datasets', library: true });
      this.collection.total_user_entries = 0;
      this.collection.reset([]);

      expect(this.view._isBlockEnabled('no_datasets')).toBe(true);
    });

    it('should show empty datasets when visits library and user didn\'t have any dataset', function () {
      this.router.model.set({ content_type: 'datasets', library: true });
      this.collection.total_user_entries = 0;
      this.collection.reset([]);

      expect(this.view._isBlockEnabled('no_datasets')).toBe(true);
    });

    it('should show onboarding map when collection is empty and content_type is in maps', function () {
      spyOn(cdb, 'createVis'); // mock the fallback map
      this.router.model.set({ content_type: 'maps' }, { silent: true });
      this.collection.reset([]);

      expect(this.view._isBlockEnabled('no_results')).toBe(false);
      expect(this.view._isBlockEnabled('onboarding')).toBe(true);
      expect(cdb.createVis).toHaveBeenCalled();
    });

    it('should show loading library when collection is empty and trying to see library', function () {
      this.router.model.set({ library: true, shared: 'no' }, { silent: true });
      this.collection.reset([]);

      expect(this.view._isBlockEnabled('loading_library')).toBe(true);
      expect(this.view._isBlockEnabled('no_datasets')).toBe(false);
    });

    it('should show no_results block when collection is empty and any of the filters are enabled', function () {
      this.router.model.set({ content_type: 'datasets', tag: 'jar' }, { silent: true });
      this.collection.reset([]);

      expect(this.view._isBlockEnabled('no_results')).toBe(true);

      this.router.model.set({ q: 'paco' }, { silent: true });
      this.collection.reset([]);

      expect(this.view._isBlockEnabled('no_results')).toBe(true);
    });
  });

  it('should not have leaks', function () {
    this.view.render();

    expect(this.view).toHaveNoLeaks();
  });

  afterEach(function () {
    this.view.clean();
    window.defaultFallbackBasemapTemplateUrl = undefined;
    delete window.defaultFallbackBasemapTemplateUrl;
  });
});
<|endoftext|>


<commit_before>/* globals __dirname, process */
const b = require('substance-bundler')
const path = require('path')
const install = require('substance-bundler/extensions/install')
const fork = require('substance-bundler/extensions/fork')
const karma = require('substance-bundler/extensions/karma')
const rng = require('substance-bundler/extensions/rng')

const UGLIFY_VERSION = '^3.3.9'

// Constants
// ---------

const DIST = 'dist/'

// Helpers
// -------
// Doing the actual work

function css() {
  b.css('substance.css', DIST+'substance.css', { variables: true })
  b.css('substance.css', DIST+'substance.next.css')
  b.css('substance-pagestyle.css', DIST+'substance-pagestyle.css', {variables: true})
  b.css('substance-pagestyle.css', DIST+'substance-pagestyle.next.css')
  b.css('substance-reset.css', DIST+'substance-reset.css', {variables: true})
  b.css('substance-reset.css', DIST+'substance-reset.next.css')
}

function buildLib(target, production) {
  let targets = []
  const useStrict = production
  if (target === 'browser' || target === 'all') {
    targets.push({
      dest: DIST+'substance.js',
      format: 'umd', moduleName: 'substance',
      sourceMapRoot: __dirname, sourceMapPrefix: 'substance',
    })
  }
  if (target === 'browser:legacy') {
    targets.push({
      dest: DIST+'substance.es5.js',
      format: 'umd', moduleName: 'substance',
      sourceMapRoot: __dirname, sourceMapPrefix: 'substance',
      strict: useStrict
    })
  }
  if (target === 'node' || target === 'all') {
    targets.push({
      dest: DIST+'substance.cjs.js',
      format: 'cjs',
      sourceMapRoot: __dirname, sourceMapPrefix: 'substance'
    })
  }
  if (target === 'es' || target === 'all') {
    targets.push({
      dest: DIST+'substance.es.js',
      format: 'es',
      sourceMapRoot: __dirname, sourceMapPrefix: 'substance'
    })
  }
  if (target === 'coverage') {
    targets.push({
      dest: 'tmp/substance.cov.js',
      format: 'umd', moduleName: 'substance',
      sourceMapRoot: __dirname, sourceMapPrefix: 'substance'
    })
  }
  const config = {
    targets,
    alias: {
      'domutils': path.join(__dirname, 'vendor/domutils.js'),
      'entities': path.join(__dirname, 'vendor/entities.js'),
      'lodash-es': path.join(__dirname, 'vendor/lodash-es.js'),
    },
    commonjs: {
      include: [
        'node_modules/boolbase/**/*',
        'node_modules/css-what/**/*',
        'node_modules/domelementtype/**/*',
        'node_modules/nth-check/**/*',
      ]
    }
  }
  if (target === 'coverage') {
    config.istanbul = {
      include: [
        'collab/*.js',
        'dar/*.js',
        'dom/*.js',
        'model/**/*.js',
        'packages/**/*.js',
        'util/*.js',
        'ui/*.js',
        'xml/*.js'
      ]
    }
  }
  if (target === 'browser:legacy') {
    config.buble = true
  }
  if (production) {
    config.cleanup = true
  }
  b.js('./index.es.js', config)
}

function buildTestsBrowser() {
  b.js('test/**/*.test.js', {
    dest: 'tmp/tests.js',
    format: 'umd', moduleName: 'tests',
    external: {
      'substance': 'window.substance',
      'substance-test': 'window.substanceTest'
    },
  })
}

function buildTestsNode() {
  b.js('test/**/*.test.js', {
    dest: 'tmp/tests.cjs.js',
    format: 'cjs',
    external: ['substance-test'],
    alias: {
      'substance':
        path.join(__dirname, 'dist/substance.es.js')
    }
  })
}

function buildVendor() {
  install(b, 'uglify-es', UGLIFY_VERSION)
  const CLEANUP = true
  const MINIFY = false
  vendorRollup('entities', {
    commonjs: true,
    json: true,
    cleanup: CLEANUP,
    minify: MINIFY
  })
  vendorRollup('css-select', {
    external: [
      'domelementtype', 'entities', 'boolbase',
      'css-what', 'domutils', 'nth-check'
    ],
    commonjs: {
      include: ['vendor/css-select/**']
    },
    json: true,
    cleanup: CLEANUP,
    minify: MINIFY
  })
  vendorRollup('htmlparser2', {
    commonjs: {
      include: ['node_modules/**', 'vendor/htmlparser2/**']
    },
    ignore: ['events'],
    // attention: the order is important:
    // first the more specific ones
    alias: {
      'entities/lib/decode_codepoint.js':
        path.join(__dirname, 'vendor/_entities_decodeCodepoint.js'),
      'entities/maps/entities.json':
        path.join(__dirname, 'vendor/_entities_entitiesJSON.js'),
      'entities/maps/legacy.json':
        path.join(__dirname, 'vendor/_entities_legacyJSON.js'),
      'entities/maps/xml.json':
        path.join(__dirname, 'vendor/_entities_xmlJSON.js'),
      'entities':
        path.join(__dirname, 'vendor/entities.js'),
      'inherits':
        path.join(__dirname, 'vendor/_inherits.js')
    },
    json: true,
    cleanup: CLEANUP,
    minify: MINIFY
  })
  vendorRollup('lodash-es', {
    commonjs: true,
    cleanup: CLEANUP,
    minify: MINIFY
  })
}

function vendorRollup(name, opts = {}) {
  let src = `./vendor/_${name}.js`
  let dest = `./vendor/${name}.js`
  let min = `./vendor/${name}.min.js`
  const minify = opts.minify
  delete opts.minify
  b.js(src, Object.assign({
    dest: dest,
    format: 'es',
    sourceMap: false,
    cleanup: true
  }, opts))
  if (minify !== false) {
    b.minify(dest, {
      debug: false
    })
    b.copy(min, dest)
    b.rm(min)
  }
}

// Tasks
// -----

b.task('clean', () => {
  b.rm('./dist')
  b.rm('./.test')
})

b.task('css', css)

b.task('schema', () => {
  rng(b, './dar/Manifest.rng', { dir: 'tmp' })
})

b.task('lib:browser', ['css', 'schema'], () => {
  buildLib('browser', 'production')
})

b.task('lib:browser:legacy', ['css', 'schema'], () => {
  buildLib('browser:legacy', 'production')
})

b.task('lib:browser:dev', ['css', 'schema'], () => {
  buildLib('browser')
})

b.task('lib:dev', ['css', 'schema'], () => {
  buildLib('all')
})

b.task('lib', ['css', 'schema'], () => {
  buildLib('all', 'production')
  // Note: legacy build can not be mixed with the other builds
  buildLib('browser:legacy', 'production')
})

b.task('test:browser', ['lib:browser:dev'], buildTestsBrowser)
.describe('builds the test-suite for the browser (open test/index.html)')

b.task('test:node', () => {
  buildLib('es')
  buildTestsNode()
  fork(b, require.resolve('substance-test/bin/test'),
    './tmp/tests.cjs.js', { verbose: true })
})
.describe('runs the test suite in nodejs')

b.task('cover', () => {
  buildLib('coverage')
  buildTestsBrowser()
  karma(b, {
    browsers: process.env.TRAVIS?['ChromeTravis', 'Firefox']:['Chrome']
  })
})

b.task('vendor', buildVendor)
.describe('pre-bundles vendor libraries')

b.task('default', ['clean', 'lib'])

b.task('publish', ['clean', 'lib'])

// Default dev mode, only browser bundles are made and no ES5 transpilation happens
b.task('dev', ['clean', 'lib:browser:dev', 'test:browser'])

b.task('test', ['test:node', 'cover'])
.describe('runs the test suite')

b.setServerPort(4001)
b.serve({ static: true, route: '/', folder: '.' })
<commit_msg>Resolve bundler deprecation warnings.<commit_after>/* globals __dirname, process */
const b = require('substance-bundler')
const path = require('path')
const install = require('substance-bundler/extensions/install')
const fork = require('substance-bundler/extensions/fork')
const karma = require('substance-bundler/extensions/karma')
const rng = require('substance-bundler/extensions/rng')

const UGLIFY_VERSION = '^3.3.9'

// Constants
// ---------

const DIST = 'dist/'

// Helpers
// -------
// Doing the actual work

function css() {
  b.css('substance.css', DIST+'substance.css', { variables: true })
  b.css('substance.css', DIST+'substance.next.css')
  b.css('substance-pagestyle.css', DIST+'substance-pagestyle.css', {variables: true})
  b.css('substance-pagestyle.css', DIST+'substance-pagestyle.next.css')
  b.css('substance-reset.css', DIST+'substance-reset.css', {variables: true})
  b.css('substance-reset.css', DIST+'substance-reset.next.css')
}

function buildLib(target, production) {
  let targets = []
  const useStrict = production
  if (target === 'browser' || target === 'all') {
    targets.push({
      file: DIST+'substance.js',
      format: 'umd',
      name: 'substance',
      sourcemapRoot: __dirname, sourcemapPrefix: 'substance',
    })
  }
  if (target === 'browser:legacy') {
    targets.push({
      file: DIST+'substance.es5.js',
      format: 'umd',
      name: 'substance',
      sourcemapRoot: __dirname, sourcemapPrefix: 'substance',
      strict: useStrict
    })
  }
  if (target === 'node' || target === 'all') {
    targets.push({
      file: DIST+'substance.cjs.js',
      format: 'cjs',
      sourcemapRoot: __dirname, sourcemapPrefix: 'substance'
    })
  }
  if (target === 'es' || target === 'all') {
    targets.push({
      file: DIST+'substance.es.js',
      format: 'es',
      sourcemapRoot: __dirname, sourcemapPrefix: 'substance'
    })
  }
  if (target === 'coverage') {
    targets.push({
      file: 'tmp/substance.cov.js',
      format: 'umd',
      name: 'substance',
      sourcemapRoot: __dirname, sourcemapPrefix: 'substance'
    })
  }
  const config = {
    output: targets,
    alias: {
      'domutils': path.join(__dirname, 'vendor/domutils.js'),
      'entities': path.join(__dirname, 'vendor/entities.js'),
      'lodash-es': path.join(__dirname, 'vendor/lodash-es.js'),
    },
    commonjs: {
      include: [
        'node_modules/boolbase/**/*',
        'node_modules/css-what/**/*',
        'node_modules/domelementtype/**/*',
        'node_modules/nth-check/**/*',
      ]
    }
  }
  if (target === 'coverage') {
    config.istanbul = {
      include: [
        'collab/*.js',
        'dar/*.js',
        'dom/*.js',
        'model/**/*.js',
        'packages/**/*.js',
        'util/*.js',
        'ui/*.js',
        'xml/*.js'
      ]
    }
  }
  if (target === 'browser:legacy') {
    config.buble = true
  }
  if (production) {
    config.cleanup = true
  }
  b.js('./index.es.js', config)
}

function buildTestsBrowser() {
  b.js('test/**/*.test.js', {
    output: [{
      file: 'tmp/tests.js',
      format: 'umd',
      name: 'tests'
    }],
    external: {
      'substance': 'window.substance',
      'substance-test': 'window.substanceTest'
    }
  })
}

function buildTestsNode() {
  b.js('test/**/*.test.js', {
    output: [{
      file: 'tmp/tests.cjs.js',
      format: 'cjs'
    }],
    external: ['substance-test'],
    alias: {
      'substance': path.join(__dirname, 'dist/substance.es.js')
    }
  })
}

function buildVendor() {
  install(b, 'uglify-es', UGLIFY_VERSION)
  const CLEANUP = true
  const MINIFY = false
  vendorRollup('entities', {
    commonjs: true,
    json: true,
    cleanup: CLEANUP,
    minify: MINIFY
  })
  vendorRollup('css-select', {
    external: [
      'domelementtype', 'entities', 'boolbase',
      'css-what', 'domutils', 'nth-check'
    ],
    commonjs: {
      include: ['vendor/css-select/**']
    },
    json: true,
    cleanup: CLEANUP,
    minify: MINIFY
  })
  vendorRollup('htmlparser2', {
    commonjs: {
      include: ['node_modules/**', 'vendor/htmlparser2/**']
    },
    ignore: ['events'],
    // attention: the order is important:
    // first the more specific ones
    alias: {
      'entities/lib/decode_codepoint.js':
        path.join(__dirname, 'vendor/_entities_decodeCodepoint.js'),
      'entities/maps/entities.json':
        path.join(__dirname, 'vendor/_entities_entitiesJSON.js'),
      'entities/maps/legacy.json':
        path.join(__dirname, 'vendor/_entities_legacyJSON.js'),
      'entities/maps/xml.json':
        path.join(__dirname, 'vendor/_entities_xmlJSON.js'),
      'entities':
        path.join(__dirname, 'vendor/entities.js'),
      'inherits':
        path.join(__dirname, 'vendor/_inherits.js')
    },
    json: true,
    cleanup: CLEANUP,
    minify: MINIFY
  })
  vendorRollup('lodash-es', {
    commonjs: true,
    cleanup: CLEANUP,
    minify: MINIFY
  })
}

function vendorRollup(name, opts = {}) {
  let src = `./vendor/_${name}.js`
  let dest = `./vendor/${name}.js`
  let min = `./vendor/${name}.min.js`
  const minify = opts.minify
  delete opts.minify
  b.js(src, Object.assign({
    dest: dest,
    format: 'es',
    sourceMap: false,
    cleanup: true
  }, opts))
  if (minify !== false) {
    b.minify(dest, {
      debug: false
    })
    b.copy(min, dest)
    b.rm(min)
  }
}

// Tasks
// -----

b.task('clean', () => {
  b.rm('./dist')
  b.rm('./.test')
})

b.task('css', css)

b.task('schema', () => {
  rng(b, './dar/Manifest.rng', { dir: 'tmp' })
})

b.task('lib:browser', ['css', 'schema'], () => {
  buildLib('browser', 'production')
})

b.task('lib:browser:legacy', ['css', 'schema'], () => {
  buildLib('browser:legacy', 'production')
})

b.task('lib:browser:dev', ['css', 'schema'], () => {
  buildLib('browser')
})

b.task('lib:dev', ['css', 'schema'], () => {
  buildLib('all')
})

b.task('lib', ['css', 'schema'], () => {
  buildLib('all', 'production')
  // Note: legacy build can not be mixed with the other builds
  buildLib('browser:legacy', 'production')
})

b.task('test:browser', ['lib:browser:dev'], buildTestsBrowser)
.describe('builds the test-suite for the browser (open test/index.html)')

b.task('test:node', () => {
  buildLib('es')
  buildTestsNode()
  fork(b, require.resolve('substance-test/bin/test'),
    './tmp/tests.cjs.js', { verbose: true })
})
.describe('runs the test suite in nodejs')

b.task('cover', () => {
  buildLib('coverage')
  buildTestsBrowser()
  karma(b, {
    browsers: process.env.TRAVIS?['ChromeTravis', 'Firefox']:['Chrome']
  })
})

b.task('vendor', buildVendor)
.describe('pre-bundles vendor libraries')

b.task('default', ['clean', 'lib'])

b.task('publish', ['clean', 'lib'])

// Default dev mode, only browser bundles are made and no ES5 transpilation happens
b.task('dev', ['clean', 'lib:browser:dev', 'test:browser'])

b.task('test', ['test:node', 'cover'])
.describe('runs the test suite')

b.setServerPort(4001)
b.serve({ static: true, route: '/', folder: '.' })
<|endoftext|>


<commit_before>var should =require("should");
var constructBrowsePath = require("../lib/common/address_space").constructBrowsePath;
var AddressSpace = require("../lib/common/address_space").AddressSpace;
var generate_address_space = require("../lib/common/load_nodeset2").generate_address_space;
var makeNodeId = require("../lib/nodeId").makeNodeId;
var util = require("util");

describe("constructBrowsePath and simpleBrowsePath",function(){

    var nodeset_filename = __dirname+ "/../lib/server/mini.Node.Set2.xml";
    var address_space = new AddressSpace();

    before(function(done){
        generate_address_space(address_space, nodeset_filename,function(){
            done();
        });
    });

    it(" should construct a browse path",function(){
        var browsePath = constructBrowsePath("/","Folder.Foo.Bar.Fizz");
        browsePath._schema.name.should.eql("BrowsePath");
        browsePath.relativePath.elements.length.should.equal(4);
    });
    it(" should construct a browse path",function(){
        var browsePath = constructBrowsePath("/","Objects.4:Boilers");
        browsePath._schema.name.should.eql("BrowsePath");
        browsePath.relativePath.elements.length.should.equal(2);

        browsePath.relativePath.elements[0].targetName.namespaceIndex.should.equal(0);
        browsePath.relativePath.elements[0].targetName.name.should.equal("Objects");

        browsePath.relativePath.elements[1].targetName.namespaceIndex.should.equal(4);
        browsePath.relativePath.elements[1].targetName.name.should.equal("Boilers");
    });
    it("should browse some path",function(){

        var nodeId = address_space.simpleBrowsePath("/","Objects.Server");
        nodeId.should.eql(makeNodeId(2253));
        address_space.findObject(nodeId).browseName.should.eql("Server");
    });

});

<commit_msg>fix filename typo<commit_after>var should =require("should");
var constructBrowsePath = require("../lib/common/address_space").constructBrowsePath;
var AddressSpace = require("../lib/common/address_space").AddressSpace;
var generate_address_space = require("../lib/common/load_nodeset2").generate_address_space;
var makeNodeId = require("../lib/nodeid").makeNodeId;
var util = require("util");

describe("constructBrowsePath and simpleBrowsePath",function(){

    var nodeset_filename = __dirname+ "/../lib/server/mini.Node.Set2.xml";
    var address_space = new AddressSpace();

    before(function(done){
        generate_address_space(address_space, nodeset_filename,function(){
            done();
        });
    });

    it(" should construct a browse path",function(){
        var browsePath = constructBrowsePath("/","Folder.Foo.Bar.Fizz");
        browsePath._schema.name.should.eql("BrowsePath");
        browsePath.relativePath.elements.length.should.equal(4);
    });
    it(" should construct a browse path",function(){
        var browsePath = constructBrowsePath("/","Objects.4:Boilers");
        browsePath._schema.name.should.eql("BrowsePath");
        browsePath.relativePath.elements.length.should.equal(2);

        browsePath.relativePath.elements[0].targetName.namespaceIndex.should.equal(0);
        browsePath.relativePath.elements[0].targetName.name.should.equal("Objects");

        browsePath.relativePath.elements[1].targetName.namespaceIndex.should.equal(4);
        browsePath.relativePath.elements[1].targetName.name.should.equal("Boilers");
    });
    it("should browse some path",function(){

        var nodeId = address_space.simpleBrowsePath("/","Objects.Server");
        nodeId.should.eql(makeNodeId(2253));
        address_space.findObject(nodeId).browseName.should.eql("Server");
    });

});

<|endoftext|>


<commit_before>exports.config = {
    seleniumAddress: 'http://192.168.2.130:4444/wd/hub',
    getPageTimeout: 600001,
    allScriptsTimeout: 5000001,
    framework: 'custom',
    // path relative to the current config file
    frameworkPath: require.resolve('protractor-cucumber-framework'),
    capabilities: {
        'browserName': 'firefox',
    },

    // Spec patterns are relative to this directory.
    specs: [
        'test/e2e/features/e2e.feature'
    ],

    ignoreUncaughtExceptions: true,

    baseUrl: 'https://www.google.nl/',

    cucumberOpts: {
        require: ['test/e2e/features/step_definitions/*.js',
        'test/e2e/conf/env.js'],
        tags: '@checkApi',
        format: 'pretty',
        profile: false,
        'no-source': true
    },
    onPrepare: function () {
        global.chai = require('chai');
        var chaiAsPromised = require('chai-as-promised')
        chai.use(chaiAsPromised);
        global.expect = chai.expect;
    }
};
<commit_msg>Update teamServer.conf.js<commit_after>exports.config = {
    seleniumAddress: 'http://192.168.2.130:4444/wd/hub',
    getPageTimeout: 600001,
    allScriptsTimeout: 5000001,
    framework: 'custom',
    // path relative to the current config file
    frameworkPath: require.resolve('protractor-cucumber-framework'),
    capabilities: {
        'browserName': 'chrome',
    },

    // Spec patterns are relative to this directory.
    specs: [
        'test/e2e/features/e2e.feature'
    ],

    ignoreUncaughtExceptions: true,

    baseUrl: 'https://www.google.nl/',

    cucumberOpts: {
        require: ['test/e2e/features/step_definitions/*.js',
        'test/e2e/conf/env.js'],
        tags: '@checkApi',
        format: 'pretty',
        profile: false,
        'no-source': true
    },
    onPrepare: function () {
        global.chai = require('chai');
        var chaiAsPromised = require('chai-as-promised')
        chai.use(chaiAsPromised);
        global.expect = chai.expect;
    }
};
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var tape = require( 'tape' );
var betaCDF = require( '@stdlib/math/base/dist/beta/cdf' );
var cauchyCDF = require( '@stdlib/math/base/dist/cauchy/cdf' );
var chisquareCDF = require( '@stdlib/math/base/dist/chisquare/cdf' );
var erlangCDF = require( '@stdlib/math/base/dist/erlang/cdf' );
var exponentialCDF = require( '@stdlib/math/base/dist/exponential/cdf' );
var fCDF = require( '@stdlib/math/base/dist/f/cdf' );
var gammaCDF = require( '@stdlib/math/base/dist/gamma/cdf' );
var gumbelCDF = require( '@stdlib/math/base/dist/gumbel/cdf' );
var invgammaCDF = require( '@stdlib/math/base/dist/invgamma/cdf' );
var laplaceCDF = require( '@stdlib/math/base/dist/laplace/cdf' );
var logisticCDF = require( '@stdlib/math/base/dist/logistic/cdf' );
var lognormalCDF = require( '@stdlib/math/base/dist/lognormal/cdf' );
var rayleighCDF = require( '@stdlib/math/base/dist/rayleigh/cdf' );
var tCDF = require( '@stdlib/math/base/dist/t/cdf' );
var uniformCDF = require( '@stdlib/math/base/dist/uniform/cdf' );
var normalCDF = require( '@stdlib/math/base/dist/normal/cdf' );
var paretoCDF = require( '@stdlib/math/base/dist/pareto-type1/cdf' );
var triangularCDF = require( '@stdlib/math/base/dist/triangular/cdf' );
var weibullCDF = require( '@stdlib/math/base/dist/weibull/cdf' );
var getCDF = require( './../lib/get_cdf.js' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof getCDF, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function returns the correct CDF if provided a valid input string', function test( t ) {
	t.equal( getCDF( 'beta' ), betaCDF );
	t.equal( getCDF( 'cauchy' ), cauchyCDF );
	t.equal( getCDF( 'chisquare' ), chisquareCDF );
	t.equal( getCDF( 'erlang' ), erlangCDF );
	t.equal( getCDF( 'exponential' ), exponentialCDF );
	t.equal( getCDF( 'f' ), fCDF );
	t.equal( getCDF( 'gamma' ), gammaCDF );
	t.equal( getCDF( 'gumbel' ), gumbelCDF );
	t.equal( getCDF( 'invgamma' ), invgammaCDF );
	t.equal( getCDF( 'laplace' ), laplaceCDF );
	t.equal( getCDF( 'logistic' ), logisticCDF );
	t.equal( getCDF( 'lognormal' ), lognormalCDF );
	t.equal( getCDF( 'rayleigh' ), rayleighCDF );
	t.equal( getCDF( 't' ), tCDF );
	t.equal( getCDF( 'uniform' ), uniformCDF );
	t.equal( getCDF( 'normal' ), normalCDF );
	t.equal( getCDF( 'pareto-type1' ), paretoCDF );
	t.equal( getCDF( 'triangular' ), triangularCDF );
	t.equal( getCDF( 'weibull' ), weibullCDF );
	t.end();
});

tape( 'the function throws an error if provided the name of a discrete distribution', function test( t ) {
	var values;
	var i;

	values = [
		'binomial',
		'geometric',
		'hypergeometric',
		'negative-binomial',
		'poisson'
	];

	for ( i = 0; i < values.length; i++ ) {
		t.throws( badValue( values[i] ), Error, 'throws an error when provided '+values[i] );
	}
	t.end();

	function badValue( value ) {
		return function() {
			getCDF( value );
		};
	}
});

tape( 'the function throws an error if the provided a name which does not match any distribution', function test( t ) {
	var values;
	var i;

	values = [
		'not_a_distribution',
		'5',
		5,
		true,
		undefined,
		null,
		NaN,
		[],
		{},
		function(){}
	];

	for ( i = 0; i < values.length; i++ ) {
		t.throws( badValue( values[i] ), Error, 'throws an error when provided '+values[i] );
	}
	t.end();

	function badValue( value ) {
		return function() {
			getCDF( value );
		};
	}
});
<commit_msg>Fix lint errors<commit_after>'use strict';

// MODULES //

var tape = require( 'tape' );
var betaCDF = require( '@stdlib/math/base/dist/beta/cdf' );
var cauchyCDF = require( '@stdlib/math/base/dist/cauchy/cdf' );
var chisquareCDF = require( '@stdlib/math/base/dist/chisquare/cdf' );
var erlangCDF = require( '@stdlib/math/base/dist/erlang/cdf' );
var exponentialCDF = require( '@stdlib/math/base/dist/exponential/cdf' );
var fCDF = require( '@stdlib/math/base/dist/f/cdf' );
var gammaCDF = require( '@stdlib/math/base/dist/gamma/cdf' );
var gumbelCDF = require( '@stdlib/math/base/dist/gumbel/cdf' );
var invgammaCDF = require( '@stdlib/math/base/dist/invgamma/cdf' );
var laplaceCDF = require( '@stdlib/math/base/dist/laplace/cdf' );
var logisticCDF = require( '@stdlib/math/base/dist/logistic/cdf' );
var lognormalCDF = require( '@stdlib/math/base/dist/lognormal/cdf' );
var rayleighCDF = require( '@stdlib/math/base/dist/rayleigh/cdf' );
var tCDF = require( '@stdlib/math/base/dist/t/cdf' );
var uniformCDF = require( '@stdlib/math/base/dist/uniform/cdf' );
var normalCDF = require( '@stdlib/math/base/dist/normal/cdf' );
var paretoCDF = require( '@stdlib/math/base/dist/pareto-type1/cdf' );
var triangularCDF = require( '@stdlib/math/base/dist/triangular/cdf' );
var weibullCDF = require( '@stdlib/math/base/dist/weibull/cdf' );
var getCDF = require( './../lib/get_cdf.js' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof getCDF, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function returns the correct CDF if provided a valid input string', function test( t ) {
	t.equal( getCDF( 'beta' ), betaCDF );
	t.equal( getCDF( 'cauchy' ), cauchyCDF );
	t.equal( getCDF( 'chisquare' ), chisquareCDF );
	t.equal( getCDF( 'erlang' ), erlangCDF );
	t.equal( getCDF( 'exponential' ), exponentialCDF );
	t.equal( getCDF( 'f' ), fCDF );
	t.equal( getCDF( 'gamma' ), gammaCDF );
	t.equal( getCDF( 'gumbel' ), gumbelCDF );
	t.equal( getCDF( 'invgamma' ), invgammaCDF );
	t.equal( getCDF( 'laplace' ), laplaceCDF );
	t.equal( getCDF( 'logistic' ), logisticCDF );
	t.equal( getCDF( 'lognormal' ), lognormalCDF );
	t.equal( getCDF( 'rayleigh' ), rayleighCDF );
	t.equal( getCDF( 't' ), tCDF );
	t.equal( getCDF( 'uniform' ), uniformCDF );
	t.equal( getCDF( 'normal' ), normalCDF );
	t.equal( getCDF( 'pareto-type1' ), paretoCDF );
	t.equal( getCDF( 'triangular' ), triangularCDF );
	t.equal( getCDF( 'weibull' ), weibullCDF );
	t.end();
});

tape( 'the function throws an error if provided the name of a discrete distribution', function test( t ) {
	var values;
	var i;

	values = [
		'binomial',
		'geometric',
		'hypergeometric',
		'negative-binomial',
		'poisson'
	];

	for ( i = 0; i < values.length; i++ ) {
		t.throws( badValue( values[i] ), Error, 'throws an error when provided '+values[i] );
	}
	t.end();

	function badValue( value ) {
		return function badValue() {
			getCDF( value );
		};
	}
});

tape( 'the function throws an error if the provided a name which does not match any distribution', function test( t ) {
	var values;
	var i;

	values = [
		'not_a_distribution',
		'5',
		5,
		true,
		undefined,
		null,
		NaN,
		[],
		{},
		function noop() {}
	];

	for ( i = 0; i < values.length; i++ ) {
		t.throws( badValue( values[i] ), Error, 'throws an error when provided '+values[i] );
	}
	t.end();

	function badValue( value ) {
		return function badValue() {
			getCDF( value );
		};
	}
});
<|endoftext|>


<commit_before>define(["dojo/_base/declare",
        "../PersistentObject", "../IdNotFoundException", "../CrudDao",
        "dojo/Deferred"],
  function(declare, PersistentObject, IdNotFoundException, CrudDao, Deferred) {

    function cacheKey(/*String*/ type, /*Number*/ persistenceId) {
      // summary:
      //   Returns a key.
      // description:
      //   Returns `type + "@" + persistenceId`

      return type + "@" + persistenceId;
    }

    function declaredClass(/*Function*/ c) {
      var proto = c.prototype;
      return proto.declaredClass;
    }

    var CrudDaoMock = declare([CrudDao], {
      // summary:
      //   This is a mock of CrudDao. We inherit from CrudDao, and overwrite meaningful methods.
      //   All methods are supported. They're behavior can be changed for a number of cases, with
      //   extra properties on parameters that are already there.
      //   Private. Contains a CacheEntry for each retrieved object, that is not yet released.

      get: function(/*Function*/ PoType, /*Number*/ persistenceId, /*Any*/ referer) {
        // description:
        //   referer.error will result in that error
        //   referer.idNotFoundException will result in that exception
        //   referer.resultJson will be the result
        //   referer.waitMillis is the time the promise will take

        var key = cacheKey(declaredClass(PoType), persistenceId);
        var entry = this._cache[key];
        var p = null;
        if (! entry) {
          p = new PoType();
          p._changeAttrValue("peristenceId", persistenceId);
        }
        else {
          p = entry.persistentObject;
        }
        this.track(p, referer);
        var thisDao = this;
        var resultDeferred = new Deferred();
        var action;
        if (referer.error) {
          action = function() {
            var PoType = Object.getPrototypeOf(p).constructor;
            var url = thisDao.getUrl(PoType, persistenceId);
            thisDao._incrementErrorCount(referer.error, "GET " + url);
            resultDeferred.reject("ERROR: could not GET " + persistenceId + " (" + referer.error + ")");
          };
        }
        else if (referer.idNotFoundException) {
          action = function() {
            thisDao._resetErrorCount();
            thisDao._noLongerInServer(entry);
            resultDeferred.reject(referer.idNotFoundException);
          };
        }
        else {
          action = function() {
            thisDao._resetErrorCount();
            p.reload(referer.resultJson);
            resultDeferred.resolve(p);
          };
        }
        if ((referer.error && referer.idNotFoundException) && ! referer.waitMillis) {
          action();
        }
        else {
          setTimeout(action, referer.waitMillis);
        }
        var result = {
          promise: resultDeferred.promise,
          persistentObject: p
        };
        return result;
      },

      create: function(/*PersistentObject*/ p, /*Any*/ referer) {
        var thisDao = this;
        var resultDeferred = new Deferred();
        var action;
        if (p.error) {
          action = function() {
            var PoType = Object.getPrototypeOf(p).constructor;
            var url = thisDao.getUrl(PoType);
            thisDao._incrementErrorCount(p.error, "POST " + url + " (" + p.toString() + ")");
            resultDeferred.reject("ERROR: could not POST " + p.toString() + " (" + p.error + ")");
          };
        }
        else if (p.semanticException) {
          action = function() {
            thisDao._resetErrorCount();
            resultDeferred.reject(p.semanticException);
          };
        }
        else {
          action = function() {
            console.log("Simulated positive outcome of remote create - " + p.toString());
            thisDao._resetErrorCount();
            var json = p.toJsonObject();
            json.persistenceId = Math.floor(Math.random() * 1000000000);
            json.persistenceVersion = 1;
            p.reload(json);
            thisDao.track(p, referer);
            resultDeferred.resolve(p);
          };
        }
        if(p.waitMillis) { // TODO: we will alway have a delay
          setTimeout(action, p.waitMillis);
        }
        else {
          action();
        }
        var result = {
          promise: resultDeferred.promise,
          persistentObject: p
        };
        return result;
      },

      update: function(/*PersistentObject*/ p) {
        var thisDao = this;
        var resultDeferred = new Deferred();
        var action;
        if (p.error) {
          action = function() {
            var PoType = Object.getPrototypeOf(p).constructor;
            var url = thisDao.getUrl(PoType, p.get("persistenceId"));
            thisDao._incrementErrorCount(p.error, "PUT " + url + " (" + p.toString() + ")");
            resultDeferred.reject("ERROR: could not PUT " + p.toString() + " (" + p.error + ")");
          };
        }
        else if (p.semanticException) {
          action = function() {
            thisDao._resetErrorCount();
            if (p.semanticException.isInstanceOf && p.semanticException.isInstanceOf(IdNotFoundException)) {
              var entry = thisDao._getExistingCacheEntry(p);
              thisDao._noLongerInServer(entry);
            }
            resultDeferred.reject(p.semanticException);
          };
        }
        else {
          action = function() {
            thisDao._resetErrorCount();
            var previousVersion = p.get("persistenceVersion");
            var json = p.toJsonObject();
            json.persistenceVersion = previousVersion + 1;
            p.reload(json);
            resultDeferred.resolve(p);
          };
        }
        if(p.waitMillis) { // TODO: we will alway have a delay
          setTimeout(action, p.waitMillis);
        }
        else {
          action();
        }
        var result = {
          promise: resultDeferred.promise,
          persistentObject: p
        };
        return result;
      },

      delete: function(/*PersistentObject*/ p) {
        var thisDao = this;
        var resultDeferred = new Deferred();
        // TODO: we will alway have a delay
        if (p.error) {
          setTimeout(function() {
              var PoType = Object.getPrototypeOf(p).constructor;
              var url = thisDao.getUrl(PoType, p.get("persistenceId"));
              thisDao._incrementErrorCount(p.error, "DELETE " + url + " (" + p.toString() + ")");
              resultDeferred.reject("ERROR: could not DELETE " + p.toString() + " (" + p.error + ")");
            },
            p.waitMillis);
        }
        else if (p.semanticException) {
          setTimeout(function() {
              thisDao._resetErrorCount();
              resultDeferred.reject(p.semanticException);
            },
            p.waitMillis);
        }
        else {
          setTimeout(function() {
              thisDao._resetErrorCount();
              var entry = thisDao._getExistingCacheEntry(p);
              thisDao._noLongerInServer(entry);
              var json = p.toJsonObject();
              json.persistenceVersion = null;
              p.reload(json);
              resultDeferred.resolve(p);
            },
            p.waitMillis);
        }
        var result = {
          promise: resultDeferred.promise,
          persistentObject: p
        };
        return result;
      }

    });

    return CrudDaoMock; // return Function
  }
);
<commit_msg>typo<commit_after>define(["dojo/_base/declare",
        "../PersistentObject", "../IdNotFoundException", "../CrudDao",
        "dojo/Deferred"],
  function(declare, PersistentObject, IdNotFoundException, CrudDao, Deferred) {

    function cacheKey(/*String*/ type, /*Number*/ persistenceId) {
      // summary:
      //   Returns a key.
      // description:
      //   Returns `type + "@" + persistenceId`

      return type + "@" + persistenceId;
    }

    function declaredClass(/*Function*/ c) {
      var proto = c.prototype;
      return proto.declaredClass;
    }

    var CrudDaoMock = declare([CrudDao], {
      // summary:
      //   This is a mock of CrudDao. We inherit from CrudDao, and overwrite meaningful methods.
      //   All methods are supported. They're behavior can be changed for a number of cases, with
      //   extra properties on parameters that are already there.
      //   Private. Contains a CacheEntry for each retrieved object, that is not yet released.

      get: function(/*Function*/ PoType, /*Number*/ persistenceId, /*Any*/ referer) {
        // description:
        //   referer.error will result in that error
        //   referer.idNotFoundException will result in that exception
        //   referer.resultJson will be the result
        //   referer.waitMillis is the time the promise will take

        var key = cacheKey(declaredClass(PoType), persistenceId);
        var entry = this._cache[key];
        var p = null;
        if (! entry) {
          p = new PoType();
          p._changeAttrValue("persistenceId", persistenceId);
        }
        else {
          p = entry.persistentObject;
        }
        this.track(p, referer);
        var thisDao = this;
        var resultDeferred = new Deferred();
        var action;
        if (referer.error) {
          action = function() {
            var PoType = Object.getPrototypeOf(p).constructor;
            var url = thisDao.getUrl(PoType, persistenceId);
            thisDao._incrementErrorCount(referer.error, "GET " + url);
            resultDeferred.reject("ERROR: could not GET " + persistenceId + " (" + referer.error + ")");
          };
        }
        else if (referer.idNotFoundException) {
          action = function() {
            thisDao._resetErrorCount();
            thisDao._noLongerInServer(entry);
            resultDeferred.reject(referer.idNotFoundException);
          };
        }
        else {
          action = function() {
            thisDao._resetErrorCount();
            p.reload(referer.resultJson);
            resultDeferred.resolve(p);
          };
        }
        if ((referer.error && referer.idNotFoundException) && ! referer.waitMillis) {
          action();
        }
        else {
          setTimeout(action, referer.waitMillis);
        }
        var result = {
          promise: resultDeferred.promise,
          persistentObject: p
        };
        return result;
      },

      create: function(/*PersistentObject*/ p, /*Any*/ referer) {
        var thisDao = this;
        var resultDeferred = new Deferred();
        var action;
        if (p.error) {
          action = function() {
            var PoType = Object.getPrototypeOf(p).constructor;
            var url = thisDao.getUrl(PoType);
            thisDao._incrementErrorCount(p.error, "POST " + url + " (" + p.toString() + ")");
            resultDeferred.reject("ERROR: could not POST " + p.toString() + " (" + p.error + ")");
          };
        }
        else if (p.semanticException) {
          action = function() {
            thisDao._resetErrorCount();
            resultDeferred.reject(p.semanticException);
          };
        }
        else {
          action = function() {
            console.log("Simulated positive outcome of remote create - " + p.toString());
            thisDao._resetErrorCount();
            var json = p.toJsonObject();
            json.persistenceId = Math.floor(Math.random() * 1000000000);
            json.persistenceVersion = 1;
            p.reload(json);
            thisDao.track(p, referer);
            resultDeferred.resolve(p);
          };
        }
        if(p.waitMillis) { // TODO: we will alway have a delay
          setTimeout(action, p.waitMillis);
        }
        else {
          action();
        }
        var result = {
          promise: resultDeferred.promise,
          persistentObject: p
        };
        return result;
      },

      update: function(/*PersistentObject*/ p) {
        var thisDao = this;
        var resultDeferred = new Deferred();
        var action;
        if (p.error) {
          action = function() {
            var PoType = Object.getPrototypeOf(p).constructor;
            var url = thisDao.getUrl(PoType, p.get("persistenceId"));
            thisDao._incrementErrorCount(p.error, "PUT " + url + " (" + p.toString() + ")");
            resultDeferred.reject("ERROR: could not PUT " + p.toString() + " (" + p.error + ")");
          };
        }
        else if (p.semanticException) {
          action = function() {
            thisDao._resetErrorCount();
            if (p.semanticException.isInstanceOf && p.semanticException.isInstanceOf(IdNotFoundException)) {
              var entry = thisDao._getExistingCacheEntry(p);
              thisDao._noLongerInServer(entry);
            }
            resultDeferred.reject(p.semanticException);
          };
        }
        else {
          action = function() {
            thisDao._resetErrorCount();
            var previousVersion = p.get("persistenceVersion");
            var json = p.toJsonObject();
            json.persistenceVersion = previousVersion + 1;
            p.reload(json);
            resultDeferred.resolve(p);
          };
        }
        if(p.waitMillis) { // TODO: we will alway have a delay
          setTimeout(action, p.waitMillis);
        }
        else {
          action();
        }
        var result = {
          promise: resultDeferred.promise,
          persistentObject: p
        };
        return result;
      },

      delete: function(/*PersistentObject*/ p) {
        var thisDao = this;
        var resultDeferred = new Deferred();
        // TODO: we will alway have a delay
        if (p.error) {
          setTimeout(function() {
              var PoType = Object.getPrototypeOf(p).constructor;
              var url = thisDao.getUrl(PoType, p.get("persistenceId"));
              thisDao._incrementErrorCount(p.error, "DELETE " + url + " (" + p.toString() + ")");
              resultDeferred.reject("ERROR: could not DELETE " + p.toString() + " (" + p.error + ")");
            },
            p.waitMillis);
        }
        else if (p.semanticException) {
          setTimeout(function() {
              thisDao._resetErrorCount();
              resultDeferred.reject(p.semanticException);
            },
            p.waitMillis);
        }
        else {
          setTimeout(function() {
              thisDao._resetErrorCount();
              var entry = thisDao._getExistingCacheEntry(p);
              thisDao._noLongerInServer(entry);
              var json = p.toJsonObject();
              json.persistenceVersion = null;
              p.reload(json);
              resultDeferred.resolve(p);
            },
            p.waitMillis);
        }
        var result = {
          promise: resultDeferred.promise,
          persistentObject: p
        };
        return result;
      }

    });

    return CrudDaoMock; // return Function
  }
);
<|endoftext|>


<commit_before>"use strict";

var assert = require('assert');

var statistics = function(s) {

    var minFn = function(x,y) { return Math.min(x,y); };
    var maxFn = function(x,y) { return Math.max(x,y); };
    var avgFn = function(x,y) { return (y / s.length) + x; };

    return {
	count: s.length,
	maximum: s.length === 0 ? undefined : s.reduce(maxFn, s[0]),
	minimum: s.length === 0 ? undefined : s.reduce(minFn, s[0]),
	average: s.length === 0 ? undefined : s.reduce(avgFn, 0)
    };
};

describe('sequence processing', function() {
    it('should return the count', function() {
	assert.equal(0, statistics([]).count);
	assert.equal(3, statistics([1,2,3]).count);
    });

    it('avg, min and max should be undefined for empty lists', function() {
	var stats = statistics([]);

	assert.equal(undefined, stats.minimum);
	assert.equal(undefined, stats.maximum);
	assert.equal(undefined, stats.average);
    });

    it('min works as expected', function() {
	assert.equal(0, statistics([0]).minimum);
	assert.equal(3, statistics([5,4,3]).minimum);
    });

    it('max works as expected', function() {
	assert.equal(0, statistics([0]).maximum);
	assert.equal(5, statistics([5,4,3]).maximum);
    });

    it('average works as expected', function() {
	assert.equal(0, statistics([0]).average);
	assert.equal(3, statistics([2,4]).average);
    });
});
<commit_msg>refactor to sensible<commit_after>"use strict";

var assert = require('assert');

var statistics = function(s) {

    var n = s.length;
    var isEmpty = n === 0;
    var minFn = function(x,y) { return Math.min(x,y); };
    var maxFn = function(x,y) { return Math.max(x,y); };
    var avgFn = function(x,y) { return (y / n) + x; };

    return {
	count: n,
	maximum: isEmpty ? undefined : s.reduce(maxFn, s[0]),
	minimum: isEmpty ? undefined : s.reduce(minFn, s[0]),
	average: isEmpty ? undefined : s.reduce(avgFn, 0)
    };
};

describe('sequence processing', function() {
    it('should return the count', function() {
	assert.equal(0, statistics([]).count);
	assert.equal(3, statistics([1,2,3]).count);
    });

    it('avg, min and max should be undefined for empty lists', function() {
	var stats = statistics([]);

	assert.equal(undefined, stats.minimum);
	assert.equal(undefined, stats.maximum);
	assert.equal(undefined, stats.average);
    });

    it('min works as expected', function() {
	assert.equal(0, statistics([0]).minimum);
	assert.equal(3, statistics([5,4,3]).minimum);
    });

    it('max works as expected', function() {
	assert.equal(0, statistics([0]).maximum);
	assert.equal(5, statistics([5,4,3]).maximum);
    });

    it('average works as expected', function() {
	assert.equal(0, statistics([0]).average);
	assert.equal(3, statistics([2,4]).average);
    });
});
<|endoftext|>


<commit_before>var exec = require('cordova/exec');

var AudioPlugin = {
    create: function (successCallback, errorCallback, url) {
        exec(successCallback, errorCallback, 'AudioPlugin', 'play', [url]);
    },
    play: function (successCallback, errorCallback, url) {
        exec(successCallback, errorCallback, 'AudioPlugin', 'play', []);
    },
    pause: function(successCallback, errorCallback) {
        exec(successCallback, errorCallback, 'AudioPlugin', 'pause', []);
    },
    stop: function(successCallback, errorCallback) {
        exec(successCallback, errorCallback, 'AudioPlugin', 'stop', []);
    }
};

module.exports = AudioPlugin;

<commit_msg>fix player create method js signature<commit_after>var exec = require('cordova/exec');

var AudioPlugin = {
    create: function (successCallback, errorCallback, url) {
        exec(successCallback, errorCallback, 'AudioPlugin', 'create', [url]);
    },
    play: function (successCallback, errorCallback, url) {
        exec(successCallback, errorCallback, 'AudioPlugin', 'play', []);
    },
    pause: function(successCallback, errorCallback) {
        exec(successCallback, errorCallback, 'AudioPlugin', 'pause', []);
    },
    stop: function(successCallback, errorCallback) {
        exec(successCallback, errorCallback, 'AudioPlugin', 'stop', []);
    }
};

module.exports = AudioPlugin;

<|endoftext|>


<commit_before>var exec = require('cordova/exec');

// Refer to MediaPicker.java:136
exports.ERROR_CANCELLED = 'Cancelled';

exports.getPictures = function (success, error, options) {
	options = options || {};

	options.height = options.height || 0;
	options.isTemporaryFile = typeof options.isTemporaryFile == 'undefined' || options.isTemporaryFile == true;
	options.maxImages = options.maxImages || 5;
	options.mediaType = options.mediaType || 'any';
	options.minImages = options.minImages || 0;
	options.quality = options.quality || 100;
	options.width = options.width || 0;

	exec(success, error, 'MediaPicker', 'getPictures', [options]);
};

<commit_msg>Exposed cleanUp<commit_after>var exec = require('cordova/exec');

// Refer to MediaPicker.java:136
exports.ERROR_CANCELLED = 'Cancelled';

exports.cleanUp = function (success, error) {
	options = {};

	exec(success, error, 'MediaPicker', 'cleanUp', [options]);
}

exports.getPictures = function (success, error, options) {
	options = options || {};

	options.height = options.height || 0;
	options.isTemporaryFile = typeof options.isTemporaryFile == 'undefined' || options.isTemporaryFile == true;
	options.maxImages = options.maxImages || 5;
	options.mediaType = options.mediaType || 'any';
	options.minImages = options.minImages || 0;
	options.quality = options.quality || 100;
	options.width = options.width || 0;

	exec(success, error, 'MediaPicker', 'getPictures', [options]);
};

<|endoftext|>


<commit_before>//download.js v3.1, by dandavis; 2008-2014. [CCBY2] see http://danml.com/download.html for tests/usage
// v1 landed a FF+Chrome compat way of downloading strings to local un-named files, upgraded to use a hidden frame and optional mime
// v2 added named files via a[download], msSaveBlob, IE (10+) support, and window.URL support for larger+faster saves than dataURLs
// v3 added dataURL and Blob Input, bind-toggle arity, and legacy dataURL fallback was improved with force-download mime and base64 support. 3.1 improved safari handling.

// https://github.com/rndme/download

// data can be a string, Blob, File, or dataURL
function download(data, strFileName, strMimeType) {

	var self = window, // this script is only for browsers anyway...
		u = "application/octet-stream", // this default mime also triggers iframe downloads
		m = strMimeType || u,
		x = data,
		D = document,
		a = D.createElement("a"),
		z = function(a){return String(a);},
		B = (self.Blob || self.MozBlob || self.WebKitBlob || z);
		B=B.call ? B.bind(self) : Blob ;
		var fn = strFileName || "download",
		blob,
		fr;

	if(String(this)==="true"){ //reverse arguments, allowing download.bind(true, "text/xml", "export.xml") to act as a callback
		x=[x, m];
		m=x[0];
		x=x[1];
	}

	//go ahead and download dataURLs right away
	if(String(x).match(/^data\:[\w+\-]+\/[\w+\-]+[,;]/)){
		return navigator.msSaveBlob ?  // IE10 can't do a[download], only Blobs:
			navigator.msSaveBlob(d2b(x), fn) :
			saver(x) ; // everyone else can save dataURLs un-processed
	}//end if dataURL passed?

	blob = x instanceof B ?
		x :
		new B([x], {type: m}) ;

	function d2b(u) {
		var p= u.split(/[:;,]/),
		t= p[1],
		dec= p[2] == "base64" ? atob : decodeURIComponent,
		bin= dec(p.pop()),
		mx= bin.length,
		i= 0,
		uia= new Uint8Array(mx);

		for(i;i<mx;++i) uia[i]= bin.charCodeAt(i);

		return new B([uia], {type: t});
	 }

	function saver(url, winMode){

		if ('download' in a) { //html5 A[download]
			a.href = url;
			a.setAttribute("download", fn);
			a.innerHTML = "downloading...";
			D.body.appendChild(a);
			setTimeout(function() {
				a.click();
				D.body.removeChild(a);
				if(winMode===true){setTimeout(function(){ self.URL.revokeObjectURL(a.href);}, 250 );}
			}, 66);
			return true;
		}

		if(typeof safari !=="undefined" ){ // handle non-a[download] safari as best we can:
			url="data:"+url.replace(/^data:([\w\/\-\+]+)/, u);
			if(!window.open(url)){ // popup blocked, offer direct download:
				if(confirm("Displaying New Document\n\nUse Save As... to download, then click back to return to this page.")){ location.href=url; }
			}
			return true;
		}

		//do iframe dataURL download (old ch+FF):
		var f = D.createElement("iframe");
		D.body.appendChild(f);

		if(!winMode){ // force a mime that will download:
			url="data:"+url.replace(/^data:([\w\/\-\+]+)/, u);
		}
		f.src=url;
		setTimeout(function(){ D.body.removeChild(f); }, 333);

	}//end saver

	if (navigator.msSaveBlob) { // IE10+ : (has Blob, but not a[download] or URL)
		return navigator.msSaveBlob(blob, fn);
	}

	if(self.URL && typeof safari ==="undefined" ){ // simple fast and modern way using Blob and URL:
		saver(self.URL.createObjectURL(blob), true);
	}else{
		// handle non-Blob()+non-URL browsers:
		if(typeof blob === "string" || blob.constructor===z ){
			try{
				return saver( "data:" +  m   + ";base64,"  +  self.btoa(blob)  );
			}catch(y){
				return saver( "data:" +  m   + "," + encodeURIComponent(blob)  );
			}
		}

		// Blob but not URL:
		fr=new FileReader();
		fr.onload=function(e){
			saver(this.result);
		};
		fr.readAsDataURL(blob);
	}
	return true;
} /* end download() */<commit_msg>made safari handling future-friendly<commit_after>//download.js v3.1, by dandavis; 2008-2014. [CCBY2] see http://danml.com/download.html for tests/usage
// v1 landed a FF+Chrome compat way of downloading strings to local un-named files, upgraded to use a hidden frame and optional mime
// v2 added named files via a[download], msSaveBlob, IE (10+) support, and window.URL support for larger+faster saves than dataURLs
// v3 added dataURL and Blob Input, bind-toggle arity, and legacy dataURL fallback was improved with force-download mime and base64 support. 3.1 improved safari handling.

// https://github.com/rndme/download

// data can be a string, Blob, File, or dataURL
function download(data, strFileName, strMimeType) {

	var self = window, // this script is only for browsers anyway...
		u = "application/octet-stream", // this default mime also triggers iframe downloads
		m = strMimeType || u,
		x = data,
		D = document,
		a = D.createElement("a"),
		z = function(a){return String(a);},
		B = (self.Blob || self.MozBlob || self.WebKitBlob || z);
		B=B.call ? B.bind(self) : Blob ;
		var fn = strFileName || "download",
		blob,
		fr;

	if(String(this)==="true"){ //reverse arguments, allowing download.bind(true, "text/xml", "export.xml") to act as a callback
		x=[x, m];
		m=x[0];
		x=x[1];
	}

	//go ahead and download dataURLs right away
	if(String(x).match(/^data\:[\w+\-]+\/[\w+\-]+[,;]/)){
		return navigator.msSaveBlob ?  // IE10 can't do a[download], only Blobs:
			navigator.msSaveBlob(d2b(x), fn) :
			saver(x) ; // everyone else can save dataURLs un-processed
	}//end if dataURL passed?

	blob = x instanceof B ?
		x :
		new B([x], {type: m}) ;

	function d2b(u) {
		var p= u.split(/[:;,]/),
		t= p[1],
		dec= p[2] == "base64" ? atob : decodeURIComponent,
		bin= dec(p.pop()),
		mx= bin.length,
		i= 0,
		uia= new Uint8Array(mx);

		for(i;i<mx;++i) uia[i]= bin.charCodeAt(i);

		return new B([uia], {type: t});
	 }

	function saver(url, winMode){

		if ('download' in a) { //html5 A[download]
			a.href = url;
			a.setAttribute("download", fn);
			a.innerHTML = "downloading...";
			D.body.appendChild(a);
			setTimeout(function() {
				a.click();
				D.body.removeChild(a);
				if(winMode===true){setTimeout(function(){ self.URL.revokeObjectURL(a.href);}, 250 );}
			}, 66);
			return true;
		}

		if(typeof safari !=="undefined" ){ // handle non-a[download] safari as best we can:
			url="data:"+url.replace(/^data:([\w\/\-\+]+)/, u);
			if(!window.open(url)){ // popup blocked, offer direct download:
				if(confirm("Displaying New Document\n\nUse Save As... to download, then click back to return to this page.")){ location.href=url; }
			}
			return true;
		}

		//do iframe dataURL download (old ch+FF):
		var f = D.createElement("iframe");
		D.body.appendChild(f);

		if(!winMode){ // force a mime that will download:
			url="data:"+url.replace(/^data:([\w\/\-\+]+)/, u);
		}
		f.src=url;
		setTimeout(function(){ D.body.removeChild(f); }, 333);

	}//end saver

	if (navigator.msSaveBlob) { // IE10+ : (has Blob, but not a[download] or URL)
		return navigator.msSaveBlob(blob, fn);
	}

	if(self.URL){ // simple fast and modern way using Blob and URL:
		saver(self.URL.createObjectURL(blob), true);
	}else{
		// handle non-Blob()+non-URL browsers:
		if(typeof blob === "string" || blob.constructor===z ){
			try{
				return saver( "data:" +  m   + ";base64,"  +  self.btoa(blob)  );
			}catch(y){
				return saver( "data:" +  m   + "," + encodeURIComponent(blob)  );
			}
		}

		// Blob but not URL:
		fr=new FileReader();
		fr.onload=function(e){
			saver(this.result);
		};
		fr.readAsDataURL(blob);
	}
	return true;
} /* end download() */<|endoftext|>