<commit_before>/*
 * Copyright (C) 2013 pingworks - Alexander Birk und Christoph Lukas
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
Ext.define('Dash.controller.Deployment', {
    extend: 'Dash.controller.Base',
    requires: ['Ext.form.field.ComboBox', 'Ext.form.field.Hidden'],
    stores: ['Environments'],
    refs: [{
        selector: 'bundlegrid',
        ref: 'bundleGrid'
    }, {
        selector: 'deploymentwindow',
        ref: 'deploymentWindow'
    }],
    init: function() {
        this.control({
            'bundlegrid': {
                showDeployWindow: this.onShowDeployWindow
            }
        });
        this.control({
            'deploymentwindow': {
                deployment: this.onDeployment
            }
        });
        this.callParent(arguments);
    },
    deploymentAllowed: function(bundle) {
        if (bundle) {
	        var requiredFieldValue = bundle.get(Dash.config.bundlegrid.deployment.required.field);
	        return ( Dash.config.bundlegrid.deployment.enabled
	            && Dash.config.bundlegrid.deployment.required.value == requiredFieldValue);
        }
    },
    onShowDeployWindow: function(bundle) {
        if (bundle && this.deploymentAllowed(bundle)) {
            this.getEnvironmentsStore().reload();
            window = Ext.create('Dash.view.DeploymentWindow', {
                bundle: bundle
            }).show();
        }
    },
    onDeployment: function(bundle, values) {
        var environment = this.getEnvironmentsStore().findRecord('id', values.environment);
        environment.set('locked', true);
        var now = new Date();
        var lockUntil = new Date(now.getTime() + (values.lock * 3600 * 1000));
        var dateFormat = Dash.config.environment.dateformat;
        environment.set('until', Ext.util.Format.date(lockUntil, dateFormat));
        environment.set('by', values.name);
        environment.set('bundle', bundle.get('id'));
        environment.save({
            success: this.onLockSaved,
            failure: this.onDeploymentError,
            scope: this
        });
    },
    onLockSaved: function(environment, operation, success) {
        Ext.Ajax.request({
            url: Dash.config.deployment.triggerUrl,
            params: environment.getData(),
            success: this.onDeploymentTriggered,
            failure: this.onError,
            scope: this
        });
    },
    onDeploymentTriggered: function(response, options) {
        this.getDeploymentWindow().destroy();
        var window = Ext.create('Ext.window.Window', {
                html: '<iframe src="' + Dash.config.deployment.showUrl + '" width="800px", height="600px"/>'
            }).show();
    },
    onDeploymentError: function(response, options) {
        if (response.status == 302) {
            return this.onDeploymentTriggered(response, options);
        }
        if (response.status == 0) {
            return this.onDeploymentTriggered(response, options);
        }
        return this.onError(response, options);
    },
    onError: function(response, options) {
        var window = this.getDeploymentWindow();
        if (window){
            window.destroy();
        }
        this.callParent(arguments);
    }
});<commit_msg>* fix error handling for deployment<commit_after>/*
 * Copyright (C) 2013 pingworks - Alexander Birk und Christoph Lukas
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
Ext.define('Dash.controller.Deployment', {
    extend: 'Dash.controller.Base',
    requires: ['Ext.form.field.ComboBox', 'Ext.form.field.Hidden'],
    stores: ['Environments'],
    refs: [{
        selector: 'bundlegrid',
        ref: 'bundleGrid'
    }, {
        selector: 'deploymentwindow',
        ref: 'deploymentWindow'
    }],
    init: function() {
        this.control({
            'bundlegrid': {
                showDeployWindow: this.onShowDeployWindow
            }
        });
        this.control({
            'deploymentwindow': {
                deployment: this.onDeployment
            }
        });
        this.callParent(arguments);
    },
    deploymentAllowed: function(bundle) {
        if (bundle) {
	        var requiredFieldValue = bundle.get(Dash.config.bundlegrid.deployment.required.field);
	        return ( Dash.config.bundlegrid.deployment.enabled
	            && Dash.config.bundlegrid.deployment.required.value == requiredFieldValue);
        }
    },
    onShowDeployWindow: function(bundle) {
        if (bundle && this.deploymentAllowed(bundle)) {
            this.getEnvironmentsStore().reload();
            window = Ext.create('Dash.view.DeploymentWindow', {
                bundle: bundle
            }).show();
        }
    },
    onDeployment: function(bundle, values) {
        var environment = this.getEnvironmentsStore().findRecord('id', values.environment);
        environment.set('locked', true);
        var now = new Date();
        var lockUntil = new Date(now.getTime() + (values.lock * 3600 * 1000));
        var dateFormat = Dash.config.environment.dateformat;
        environment.set('until', Ext.util.Format.date(lockUntil, dateFormat));
        environment.set('by', values.name);
        environment.set('bundle', bundle.get('id'));
        environment.save({
            success: this.onLockSaved,
            failure: this.onError,
            scope: this
        });
    },
    onLockSaved: function(environment, operation, success) {
        Ext.Ajax.request({
            url: Dash.config.deployment.triggerUrl,
            params: environment.getData(),
            success: this.onDeploymentTriggered,
            failure: this.onDeploymentError,
            scope: this
        });
    },
    onDeploymentTriggered: function(response, options) {
        this.getDeploymentWindow().destroy();
        var window = Ext.create('Ext.window.Window', {
                html: '<iframe src="' + Dash.config.deployment.showUrl + '" width="800px", height="600px"/>'
            }).show();
    },
    onDeploymentError: function(response, options) {
        if (response.status == 302) {
            return this.onDeploymentTriggered(response, options);
        }
        if (response.status == 0) {
            return this.onDeploymentTriggered(response, options);
        }
        return this.onError(response, options);
    },
    onError: function(response, options) {
        var window = this.getDeploymentWindow();
        if (window){
            window.destroy();
        }
        this.callParent(arguments);
    }
});<|endoftext|>


<commit_before>(function(){
	if (window) {
		var maintenanceMode = false;

		if (!window.ClientConfig) {
			console.error("ClientConfig has not been provided...");
			return;
		} else {

			console.log(window.ClientConfig.maintenanceMode);

			if (window.ClientConfig && window.ClientConfig.maintenanceMode === true) {
			  document.getElementById("maintenanceMode").style.display = "block";
			  maintenanceMode = true;
			}

			if (window.ClientConfig.VERSION) {
				console.log("======== 3D REPO - Version " + window.ClientConfig.VERSION + " ======");
			} else {
				console.log("No version number in config...");
			}

			if (window.ClientConfig.unitySettings) {
				// Assign unity settings
				window.Module = ClientConfig.unitySettings;
			} else {
				console.error("ClientConfig does not have any provided Unity settings!");
			}
		}

		if (!maintenanceMode) {

			// Add some offline UX
			window.addEventListener("load", function() {

				var offlineDiv = document.createElement("div");
				offlineDiv.className = "connection";
				document.body.appendChild(offlineDiv);

				function updateOnlineStatus() {
					var condition = navigator.onLine ? "Online" : "Offline";
					document.querySelector(".connection").innerHTML = condition;
					if (condition === "Online") {
						offlineDiv.className = "connection online";
						setTimeout(function(){
							document.querySelector(".connection").innerHTML = "";
						}, 1000 * 20); // Show it for twenty seconds
					} else {
						offlineDiv.className = "connection offline";
					}
				}

				window.addEventListener("online",  updateOnlineStatus);
				window.addEventListener("offline", updateOnlineStatus);
			});

			if (angular) {
				window.TDR = angular.module("3drepo", ["ui.router", "ngMaterial", "ngAnimate", "ngSanitize", "vcRecaptcha"]);
			}
		}

	}

})();
<commit_msg>ISSUE #703 - Remove log<commit_after>(function(){
	if (window) {
		var maintenanceMode = false;

		if (!window.ClientConfig) {
			console.error("ClientConfig has not been provided...");
			return;
		} else {

			if (window.ClientConfig && window.ClientConfig.maintenanceMode === true) {
			  document.getElementById("maintenanceMode").style.display = "block";
			  maintenanceMode = true;
			}

			if (window.ClientConfig.VERSION) {
				console.log("======== 3D REPO - Version " + window.ClientConfig.VERSION + " ======");
			} else {
				console.log("No version number in config...");
			}

			if (window.ClientConfig.unitySettings) {
				// Assign unity settings
				window.Module = ClientConfig.unitySettings;
			} else {
				console.error("ClientConfig does not have any provided Unity settings!");
			}
		}

		if (!maintenanceMode) {

			// Add some offline UX
			window.addEventListener("load", function() {

				var offlineDiv = document.createElement("div");
				offlineDiv.className = "connection";
				document.body.appendChild(offlineDiv);

				function updateOnlineStatus() {
					var condition = navigator.onLine ? "Online" : "Offline";
					document.querySelector(".connection").innerHTML = condition;
					if (condition === "Online") {
						offlineDiv.className = "connection online";
						setTimeout(function(){
							document.querySelector(".connection").innerHTML = "";
						}, 1000 * 20); // Show it for twenty seconds
					} else {
						offlineDiv.className = "connection offline";
					}
				}

				window.addEventListener("online",  updateOnlineStatus);
				window.addEventListener("offline", updateOnlineStatus);
			});

			if (angular) {
				window.TDR = angular.module("3drepo", ["ui.router", "ngMaterial", "ngAnimate", "ngSanitize", "vcRecaptcha"]);
			}
		}

	}

})();
<|endoftext|>


<commit_before>/* global afterEach, beforeEach, describe, expect, it, mongo, sinon */
$.ready = function () {}; // Prevent mongo.init() from running.

describe('The const module', function () {
  it('stores keycode constants', function () {
    var key = mongo.const.keycodes;
    expect(key.enter).toBe(13);
    expect(key.left).toBe(37);
    expect(key.up).toBe(38);
    expect(key.right).toBe(39);
    expect(key.down).toBe(40);
  });
});

describe('Mongo Dom Module', function () {
  it('retrives config', function () {
    var config = mongo.dom.retrieveConfig();
    expect(config.cssPath).toEqual('mongo-web-shell.css');
    expect(config.mwsHost).toEqual('');
    expect(config.baseUrl).toEqual('/mws/');
  });

  it('inject CSS', function () {
    var link = document.getElementsByTagName('link');
    var linkElement;
    var href;

    if (link.length !== 0) {
      linkElement = document.getElementsByTagName('link')[0];
      href = linkElement.getAttribute('href');
      expect(href).toNotEqual('mongo-web-shell.css');
    }

    mongo.dom.injectStylesheet('mongo-web-shell.css');
    linkElement = document.getElementsByTagName('link')[0];
    href = linkElement.getAttribute('href');
    var rel = linkElement.getAttribute('rel');
    var type = linkElement.getAttribute('type');
    expect(href).toEqual('mongo-web-shell.css');
    expect(rel).toEqual('stylesheet');
    expect(type).toEqual('text/css');
  });
});

describe('Mwshell module', function () {
  it('injects HTML', function () {
    var mwsBorder = $('.mws-border');
    expect(mwsBorder.length).toEqual(0);
    var shell = new mongo.Shell($('.mongo-web-shell'));
    shell.injectHTML();
    mwsBorder = $('.mws-border');
    expect(mwsBorder.length).toEqual(1);
    expect(mwsBorder.find('.mshell').length).toEqual(1);
    expect(mwsBorder.find('.mshell').find('.mws-input').length).toEqual(1);
  });
});

describe('MONGO request', function () {
  it('get result url with parameters resID and collection', function () {
    mongo.config = {baseUrl: '/mws/'};
    expect(mongo.request._getResURL(30, 2)).toEqual('/mws/30/db/2/');
  });

  it('pruneKeys', function () {
    function Param (db, query, projection) {
      this.db = db;
      this.query = query;
      this.projection = projection;
    }
    var param = [new Param(0, null, 0), new Param(0, 0, undefined),
                 new Param(0, undefined, null), new Param(0, 0, 0)];
    var keys = ['query', 'projection'];
    for (var i in param) {
      mongo.request._pruneKeys(param[i], keys);
    }
    expect(Object.keys(param[0]).length).toBe(2);
    expect(Object.keys(param[1]).length).toBe(2);
    expect(Object.keys(param[2]).length).toBe(1);
    expect(Object.keys(param[3]).length).toBe(3);
  });

  it('stringifyKeys', function () {
    var a = {'a':{1:2}};
    var res = {'a':'{"1":2}'};
    mongo.request._stringifyKeys(a);
    expect(a).toEqual(res);
  });
});

describe('mongo util module', function () {
  it('uses indices to divide source returns statements as an array',
    function () {
      var ast = new Object();
      var str0 = 'db.inventory.find( { qty: 50 } )';
      var str1 = 'db.collection.totalSize()';
      var str2 = 'db.products.update( { item: "book", qty: { $gt: 5 } } )';
      var src  = str0 + str1 + str2;
      var params  = new Object();
      var params1 = new Object();
      var params2 = new Object();
      ast.body = [];
      params.range  = {0:0, 1:str0.length};
      params1.range = {0:str0.length, 1:str0.length+str1.length};
      params2.range = {0:str0.length+str1.length, 1:(src.length)};
      ast.body.push(params);
      ast.body.push(params1);
      ast.body.push(params2);
      var statements = mongo.util.sourceToStatements(src, ast);
      expect(statements[0]).toEqual(str0);
      expect(statements[1]).toEqual(str1);
      expect(statements[2]).toEqual(str2);
    });
});

describe('MONGO init', function () {
  var xhr, requests;

  beforeEach(function () {
    xhr = sinon.useFakeXMLHttpRequest();
    requests = [];
    xhr.onCreate = function (req) { requests.push(req); };
  });

  afterEach(function () {
    xhr.restore();
  });

  it('makes a post request for todo items', function () {
    mongo.init(sinon.spy());
    expect(requests.length).toEqual(1);
    expect(requests[0].url).toEqual('/mws/');
  });
});
<commit_msg>Stub unspeced code and clean up describe() strings.<commit_after>/* global afterEach, beforeEach, describe, expect, it, mongo, sinon */
/* global xdescribe */
$.ready = function () {}; // Prevent mongo.init() from running.

xdescribe('The init function', function () {
  // TODO: The calls made in mongo.init() need to be stubbed; there should be
  // no side effects to the page (alternatively, have side effects but restore
  // the page to the initial state on afterEach()).
  var xhr, requests;

  beforeEach(function () {
    xhr = sinon.useFakeXMLHttpRequest();
    requests = [];
    xhr.onCreate = function (req) { requests.push(req); };
  });

  afterEach(function () {
    xhr.restore();
  });

  it('makes a post request for todo items', function () {
    mongo.init(sinon.spy());
    expect(requests.length).toBe(1);
    expect(requests[0].url).toBe('/mws/');
  });
});

describe('The const module', function () {
  it('stores keycode constants', function () {
    var key = mongo.const.keycodes;
    expect(key.enter).toBe(13);
    expect(key.left).toBe(37);
    expect(key.up).toBe(38);
    expect(key.right).toBe(39);
    expect(key.down).toBe(40);
  });
});

describe('A Cursor', function () {
  // TODO: Test.
});

describe('The dom module', function () {
  it('retrives config', function () {
    var config = mongo.dom.retrieveConfig();
    expect(config.cssPath).toEqual('mongo-web-shell.css');
    expect(config.mwsHost).toEqual('');
    expect(config.baseUrl).toEqual('/mws/');
  });

  it('inject CSS', function () {
    var link = document.getElementsByTagName('link');
    var linkElement;
    var href;

    if (link.length !== 0) {
      linkElement = document.getElementsByTagName('link')[0];
      href = linkElement.getAttribute('href');
      expect(href).toNotEqual('mongo-web-shell.css');
    }

    mongo.dom.injectStylesheet('mongo-web-shell.css');
    linkElement = document.getElementsByTagName('link')[0];
    href = linkElement.getAttribute('href');
    var rel = linkElement.getAttribute('rel');
    var type = linkElement.getAttribute('type');
    expect(href).toEqual('mongo-web-shell.css');
    expect(rel).toEqual('stylesheet');
    expect(type).toEqual('text/css');
  });
});

describe('The keyword module', function () {
  // TODO: Test.
});

describe('The mutateSource module', function () {
  // TODO: Test.
});

describe('A Query', function () {
  // TODO: Test.
});

describe('A Readline instance', function () {
  // TODO: Test.
});

describe('The request module', function () {
  it('get result url with parameters resID and collection', function () {
    mongo.config = {baseUrl: '/mws/'};
    expect(mongo.request._getResURL(30, 2)).toEqual('/mws/30/db/2/');
  });

  it('pruneKeys', function () {
    function Param (db, query, projection) {
      this.db = db;
      this.query = query;
      this.projection = projection;
    }
    var param = [new Param(0, null, 0), new Param(0, 0, undefined),
                 new Param(0, undefined, null), new Param(0, 0, 0)];
    var keys = ['query', 'projection'];
    for (var i in param) {
      mongo.request._pruneKeys(param[i], keys);
    }
    expect(Object.keys(param[0]).length).toBe(2);
    expect(Object.keys(param[1]).length).toBe(2);
    expect(Object.keys(param[2]).length).toBe(1);
    expect(Object.keys(param[3]).length).toBe(3);
  });

  it('stringifyKeys', function () {
    var a = {'a':{1:2}};
    var res = {'a':'{"1":2}'};
    mongo.request._stringifyKeys(a);
    expect(a).toEqual(res);
  });
});

describe('A Shell', function () {
  it('injects HTML', function () {
    var mwsBorder = $('.mws-border');
    expect(mwsBorder.length).toEqual(0);
    var shell = new mongo.Shell($('.mongo-web-shell'));
    shell.injectHTML();
    mwsBorder = $('.mws-border');
    expect(mwsBorder.length).toEqual(1);
    expect(mwsBorder.find('.mshell').length).toEqual(1);
    expect(mwsBorder.find('.mshell').find('.mws-input').length).toEqual(1);
  });
});

describe('The util module', function () {
  it('uses indices to divide source returns statements as an array',
    function () {
      var ast = new Object();
      var str0 = 'db.inventory.find( { qty: 50 } )';
      var str1 = 'db.collection.totalSize()';
      var str2 = 'db.products.update( { item: "book", qty: { $gt: 5 } } )';
      var src  = str0 + str1 + str2;
      var params  = new Object();
      var params1 = new Object();
      var params2 = new Object();
      ast.body = [];
      params.range  = {0:0, 1:str0.length};
      params1.range = {0:str0.length, 1:str0.length+str1.length};
      params2.range = {0:str0.length+str1.length, 1:(src.length)};
      ast.body.push(params);
      ast.body.push(params1);
      ast.body.push(params2);
      var statements = mongo.util.sourceToStatements(src, ast);
      expect(statements[0]).toEqual(str0);
      expect(statements[1]).toEqual(str1);
      expect(statements[2]).toEqual(str2);
    });
});
<|endoftext|>


<commit_before>var input    = require('./digits.js');
var exercise = {};

exercise.one = function(){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 1st function not implemented 2056';
};

exercise.two = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 2nd function not implemented';
};

exercise.three = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 3rd function not implemented';
};

exercise.four = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 4th function not implemented';
};

exercise.five = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 5th function not implemented';
};

module.exports = exercise;
<commit_msg>Update exercise.js<commit_after>var input    = require('./digits.js');
var exercise = {};

exercise.one = function(){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 1st function not implemented 2057';
};

exercise.two = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 2nd function not implemented';
};

exercise.three = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 3rd function not implemented';
};

exercise.four = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 4th function not implemented';
};

exercise.five = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 5th function not implemented';
};

module.exports = exercise;
<|endoftext|>


<commit_before>add_dependencies({
    people: 'js/people.js',
});

var presence = require('js/presence.js');

set_global('server_events', {});
set_global('blueslip', {});

var OFFLINE_THRESHOLD_SECS = 140;

var me = {
    email: 'me@zulip.com',
    user_id: 999,
    full_name: 'Me Myself',
};

var alice = {
    email: 'alice@zulip.com',
    user_id: 1,
    full_name: 'Alice Smith',
};

var fred = {
    email: 'fred@zulip.com',
    user_id: 2,
    full_name: "Fred Flintstone",
};

var zoe = {
    email: 'zoe@example.com',
    user_id: 6,
    full_name: 'Zoe Yang',
};

var bot = {
    email: 'bot@zulip.com',
    user_id: 7,
    full_name: 'The Bot',
    is_bot: true,
};

people.add_in_realm(me);
people.add_in_realm(alice);
people.add_in_realm(fred);
people.add_in_realm(zoe);
people.add_in_realm(bot);
people.initialize_current_user(me.user_id);

(function test_on_mobile_property() {
    // TODO: move this test to a new test module directly testing presence.js
    var status_from_timestamp = presence._status_from_timestamp;

    var base_time = 500;
    var info = {
        website: {
            status: "active",
            timestamp: base_time,
        },
    };
    var status = status_from_timestamp(
        base_time + OFFLINE_THRESHOLD_SECS - 1, info);
    assert.equal(status.mobile, false);

    info.Android = {
        status: "active",
        timestamp: base_time + OFFLINE_THRESHOLD_SECS / 2,
        pushable: false,
    };
    status = status_from_timestamp(
        base_time + OFFLINE_THRESHOLD_SECS, info);
    assert.equal(status.mobile, true);
    assert.equal(status.status, "active");

    status = status_from_timestamp(
        base_time + OFFLINE_THRESHOLD_SECS - 1, info);
    assert.equal(status.mobile, false);
    assert.equal(status.status, "active");

    status = status_from_timestamp(
        base_time + OFFLINE_THRESHOLD_SECS * 2, info);
    assert.equal(status.mobile, false);
    assert.equal(status.status, "offline");

    info.Android = {
        status: "idle",
        timestamp: base_time + OFFLINE_THRESHOLD_SECS / 2,
        pushable: true,
    };
    status = status_from_timestamp(
        base_time + OFFLINE_THRESHOLD_SECS, info);
    assert.equal(status.mobile, true);
    assert.equal(status.status, "idle");

    status = status_from_timestamp(
        base_time + OFFLINE_THRESHOLD_SECS - 1, info);
    assert.equal(status.mobile, false);
    assert.equal(status.status, "active");

    status = status_from_timestamp(
        base_time + OFFLINE_THRESHOLD_SECS * 2, info);
    assert.equal(status.mobile, true);
    assert.equal(status.status, "offline");

}());

(function test_set_presence_info() {
    var presences = {};
    var base_time = 500;

    presences[alice.email] = {
        website: {
            status: 'active',
            timestamp: base_time,
        },
    };

    presences[fred.email] = {
        website: {
            status: 'idle',
            timestamp: base_time,
        },
    };

    presence.set_info(presences, base_time);

    assert.deepEqual(presence.presence_info[alice.user_id],
        { status: 'active', mobile: false, last_active: 500}
    );

    assert.deepEqual(presence.presence_info[fred.user_id],
        { status: 'idle', mobile: false, last_active: 500}
    );

    assert.deepEqual(presence.presence_info[zoe.user_id],
        { status: 'offline', mobile: false, last_active: undefined}
    );

    assert(!presence.presence_info[bot.user_id]);

    // Make it seem like realm has a lot of people
    var get_realm_count = people.get_realm_count;
    people.get_realm_count = function () { return 1000; };
    assert.equal(presence.set_info(presences, base_time), undefined);
    people.get_realm_count = get_realm_count;

    var unknown = {
        email: 'unknown@zulip.com',
        user_id: 42,
        full_name: 'Unknown Name',
    };
    presences[unknown.email] = {};

    server_events.suspect_offline = false;
    blueslip.error = function (msg) {
        assert.equal(msg, 'Unknown email in presence data: unknown@zulip.com');
    };
    presence.set_info(presences, base_time);
}());

(function test_last_active_date() {
    var unknown_id = 42;
    presence.presence_info = {
        1: { last_active: 500 }, // alice.user_id
        2: {}, // fred.user_id
    };
    set_global('XDate', function (ms) { return {seconds: ms}; });

    assert.equal(presence.last_active_date(unknown_id), undefined);
    assert.equal(presence.last_active_date(fred.user_id), undefined);
    assert.deepEqual(presence.last_active_date(alice.user_id), {seconds: 500000});
}());

<commit_msg>node tests: Fully cover status_from_timestamp in presence.js.<commit_after>add_dependencies({
    people: 'js/people.js',
});

var presence = require('js/presence.js');

set_global('server_events', {});
set_global('blueslip', {});

var OFFLINE_THRESHOLD_SECS = 140;

var me = {
    email: 'me@zulip.com',
    user_id: 999,
    full_name: 'Me Myself',
};

var alice = {
    email: 'alice@zulip.com',
    user_id: 1,
    full_name: 'Alice Smith',
};

var fred = {
    email: 'fred@zulip.com',
    user_id: 2,
    full_name: "Fred Flintstone",
};

var zoe = {
    email: 'zoe@example.com',
    user_id: 6,
    full_name: 'Zoe Yang',
};

var bot = {
    email: 'bot@zulip.com',
    user_id: 7,
    full_name: 'The Bot',
    is_bot: true,
};

people.add_in_realm(me);
people.add_in_realm(alice);
people.add_in_realm(fred);
people.add_in_realm(zoe);
people.add_in_realm(bot);
people.initialize_current_user(me.user_id);

(function test_on_mobile_property() {
    // TODO: move this test to a new test module directly testing presence.js
    var status_from_timestamp = presence._status_from_timestamp;

    var base_time = 500;
    var info = {
        website: {
            status: "active",
            timestamp: base_time,
        },
    };
    var status = status_from_timestamp(
        base_time + OFFLINE_THRESHOLD_SECS - 1, info);
    assert.equal(status.mobile, false);

    info.Android = {
        status: "active",
        timestamp: base_time + OFFLINE_THRESHOLD_SECS / 2,
        pushable: false,
    };
    status = status_from_timestamp(
        base_time + OFFLINE_THRESHOLD_SECS, info);
    assert.equal(status.mobile, true);
    assert.equal(status.status, "active");

    status = status_from_timestamp(
        base_time + OFFLINE_THRESHOLD_SECS - 1, info);
    assert.equal(status.mobile, false);
    assert.equal(status.status, "active");

    status = status_from_timestamp(
        base_time + OFFLINE_THRESHOLD_SECS * 2, info);
    assert.equal(status.mobile, false);
    assert.equal(status.status, "offline");

    info.Android = {
        status: "idle",
        timestamp: base_time + OFFLINE_THRESHOLD_SECS / 2,
        pushable: true,
    };
    status = status_from_timestamp(
        base_time + OFFLINE_THRESHOLD_SECS, info);
    assert.equal(status.mobile, true);
    assert.equal(status.status, "idle");

    status = status_from_timestamp(
        base_time + OFFLINE_THRESHOLD_SECS - 1, info);
    assert.equal(status.mobile, false);
    assert.equal(status.status, "active");

    status = status_from_timestamp(
        base_time + OFFLINE_THRESHOLD_SECS * 2, info);
    assert.equal(status.mobile, true);
    assert.equal(status.status, "offline");

    info.Android = {
        status: "offline",
        timestamp: base_time + OFFLINE_THRESHOLD_SECS / 2,
        pushable: true,
    };
    status = status_from_timestamp(
        base_time + OFFLINE_THRESHOLD_SECS, info);
    assert.equal(status.mobile, true);
    assert.equal(status.status, "offline");

    status = status_from_timestamp(
        base_time + OFFLINE_THRESHOLD_SECS - 1, info);
    assert.equal(status.mobile, false);
    assert.equal(status.status, "active"); // website

    status = status_from_timestamp(
        base_time + OFFLINE_THRESHOLD_SECS * 2, info);
    assert.equal(status.mobile, true);
    assert.equal(status.status, "offline");

    info.Android = {
        status: "unknown",
        timestamp: base_time + OFFLINE_THRESHOLD_SECS / 2,
        pushable: true,
    };
    var called = false;
    blueslip.error = function () {
        assert.equal(arguments[0], 'Unexpected status');
        assert.deepEqual(arguments[1].presence_object, info.Android);
        assert.equal(arguments[2], undefined);
        called = true;
    };
    status = status_from_timestamp(
        base_time + OFFLINE_THRESHOLD_SECS - 1, info);
    assert.equal(status.mobile, false);
    assert.equal(status.status, "active"); // website
    assert(called);
}());

(function test_set_presence_info() {
    var presences = {};
    var base_time = 500;

    presences[alice.email] = {
        website: {
            status: 'active',
            timestamp: base_time,
        },
    };

    presences[fred.email] = {
        website: {
            status: 'idle',
            timestamp: base_time,
        },
    };

    presence.set_info(presences, base_time);

    assert.deepEqual(presence.presence_info[alice.user_id],
        { status: 'active', mobile: false, last_active: 500}
    );

    assert.deepEqual(presence.presence_info[fred.user_id],
        { status: 'idle', mobile: false, last_active: 500}
    );

    assert.deepEqual(presence.presence_info[zoe.user_id],
        { status: 'offline', mobile: false, last_active: undefined}
    );

    assert(!presence.presence_info[bot.user_id]);

    // Make it seem like realm has a lot of people
    var get_realm_count = people.get_realm_count;
    people.get_realm_count = function () { return 1000; };
    assert.equal(presence.set_info(presences, base_time), undefined);
    people.get_realm_count = get_realm_count;

    var unknown = {
        email: 'unknown@zulip.com',
        user_id: 42,
        full_name: 'Unknown Name',
    };
    presences[unknown.email] = {};

    server_events.suspect_offline = false;
    blueslip.error = function (msg) {
        assert.equal(msg, 'Unknown email in presence data: unknown@zulip.com');
    };
    presence.set_info(presences, base_time);
}());

(function test_last_active_date() {
    var unknown_id = 42;
    presence.presence_info = {
        1: { last_active: 500 }, // alice.user_id
        2: {}, // fred.user_id
    };
    set_global('XDate', function (ms) { return {seconds: ms}; });

    assert.equal(presence.last_active_date(unknown_id), undefined);
    assert.equal(presence.last_active_date(fred.user_id), undefined);
    assert.deepEqual(presence.last_active_date(alice.user_id), {seconds: 500000});
}());

<|endoftext|>


<commit_before>/*
---
description: Sets up all inputs with the css class .overtext to have an OverText instance for inline labeling.
provides: [Behavior.OverText]
requires: [/Behavior, More/OverText]
script: Behavior.OverText.js
...
*/

Behavior.OverText = new Behavior.Filter('OverText', function(element, container){
	//create the overtext instance
	var ot = new OverText(element);

	//this method updates the text position with a slight delay
	var updater = function(){
		(function(){
			ot.reposition();
		}).delay(10);
	};

	//update the position whenever the behavior container is shown
	container.addEvent('show', updater);

	this.mark(element, function(){
		container.removeEvent('show', updater);
		ot.destroy();
	});

}).global();
<commit_msg>making my docs a little more clear renaming sweep > cleanup and mark > markForCleanup<commit_after>/*
---
description: Sets up all inputs with the css class .overtext to have an OverText instance for inline labeling. This is a global filter
provides: [Behavior.OverText]
requires: [/Behavior, More/OverText]
script: Behavior.OverText.js
...
*/

Behavior.OverText = new Behavior.Filter('OverText', function(element, container){
	//create the overtext instance
	var ot = new OverText(element);

	//this method updates the text position with a slight delay
	var updater = function(){
		(function(){
			ot.reposition();
		}).delay(10);
	};

	//update the position whenever the behavior container is shown
	container.addEvent('show', updater);

	this.markForCleanup(element, function(){
		container.removeEvent('show', updater);
		ot.destroy();
	});

}).global();
<|endoftext|>


<commit_before>/*
 * Copyright 2011 Joyent, Inc.  All rights reserved.
 *
 * Amon Master "Monitor" model:
 *
 *    id (uuid)
 *    name (short string): Unique for the customer
 *    customer (Customer)
 *    checks (array of Check)
 *    contacts (array of Contact)
 */

var util = require('util');
var uuid = require('node-uuid');
var Entity = require('./entity');

//---- globals

var log = require('restify').log;

//---- model

function Monitor(options) {
  if (!options || typeof(options) !== 'object')
    throw new TypeError('options must be an object');

  options._bucket = 'monitors';
  Entity.call(this, options);

  this.name = options.name;
  this.customer = options.customer;
  this.contacts = options.contacts;
  this.checks = options.checks;
}
util.inherits(Monitor, Entity);

Monitor.prototype._serialize = function() {
  return {
    id: this.id,
    name: this.name,
    customer: this.customer,
    contacts: this.contacts,
    checks: this.checks
  };
};

Monitor.prototype._deserialize = function(object) {
  this.customer = object.customer;
  this.name = object.name;
  this.contacts = object.contacts;
  this.checks = object.checks;
};

Monitor.prototype._validate = function(callback) {
  if (!this.name) throw new TypeError('"name" required');
  if (!this.customer) throw new TypeError('"customer" required');
  if (!this.contacts) throw new TypeError('"contacts" required');
  if (!this.checks) throw new TypeError('"checks" required');
};

Monitor.prototype._addIndices = function(callback) {
  this._addIndex('customers', this.customer, null, callback);
};

Monitor.prototype._deleteIndices = function(callback) {
  this._delIndex('customers', this.customer, null, callback);
};

Monitor.prototype.findByCustomer = function(customer, callback) {
  if (!customer) throw new TypeError('customer is required');
  if (!callback || typeof(callback) !== 'function')
    throw new TypeError('callback is required');

  return this._find('customers', customer, callback);
};

module.exports = Monitor
<commit_msg>id is added automatically by Entity<commit_after>/*
 * Copyright 2011 Joyent, Inc.  All rights reserved.
 *
 * Amon Master "Monitor" model:
 *
 *    id (uuid)
 *    name (short string): Unique for the customer
 *    customer (Customer)
 *    checks (array of Check)
 *    contacts (array of Contact)
 */

var util = require('util');
var uuid = require('node-uuid');
var Entity = require('./entity');

//---- globals

var log = require('restify').log;

//---- model

function Monitor(options) {
  if (!options || typeof(options) !== 'object')
    throw new TypeError('options must be an object');

  options._bucket = 'monitors';
  Entity.call(this, options);

  this.name = options.name;
  this.customer = options.customer;
  this.contacts = options.contacts;
  this.checks = options.checks;
}
util.inherits(Monitor, Entity);

Monitor.prototype._serialize = function() {
  return {
    name: this.name,
    customer: this.customer,
    contacts: this.contacts,
    checks: this.checks
  };
};

Monitor.prototype._deserialize = function(object) {
  this.customer = object.customer;
  this.name = object.name;
  this.contacts = object.contacts;
  this.checks = object.checks;
};

Monitor.prototype._validate = function(callback) {
  if (!this.name) throw new TypeError('"name" required');
  if (!this.customer) throw new TypeError('"customer" required');
  if (!this.contacts) throw new TypeError('"contacts" required');
  if (!this.checks) throw new TypeError('"checks" required');
};

Monitor.prototype._addIndices = function(callback) {
  this._addIndex('customers', this.customer, null, callback);
};

Monitor.prototype._deleteIndices = function(callback) {
  this._delIndex('customers', this.customer, null, callback);
};

Monitor.prototype.findByCustomer = function(customer, callback) {
  if (!customer) throw new TypeError('customer is required');
  if (!callback || typeof(callback) !== 'function')
    throw new TypeError('callback is required');

  return this._find('customers', customer, callback);
};

module.exports = Monitor
<|endoftext|>


<commit_before>/*global define*/
define(['../Core/createGuid',
        '../Core/Cartographic',
        '../Core/Color',
        '../Core/ClockRange',
        '../Core/ClockStep',
        '../Core/DeveloperError',
        '../Core/RuntimeError',
        '../Core/Ellipsoid',
        '../Core/Event',
        '../Core/Iso8601',
        '../Core/loadXML',
        './ConstantProperty',
        './DynamicProperty',
        './DynamicClock',
        './DynamicObject',
        './DynamicObjectCollection',
        './DynamicPoint',
        './DynamicPolyline',
        './DynamicPolygon',
        './DynamicLabel',
        './DynamicBillboard'
        ], function(
                createGuid,
                Cartographic,
                Color,
                ClockRange,
                ClockStep,
                DeveloperError,
                RuntimeError,
                Ellipsoid,
                Event,
                Iso8601,
                loadXML,
                ConstantProperty,
                DynamicProperty,
                DynamicClock,
                DynamicObject,
                DynamicObjectCollection,
                DynamicPoint,
                DynamicPolyline,
                DynamicPolygon,
                DynamicLabel,
                DynamicBillboard) {
    "use strict";

    //Copied from GeoJsonDataSource
    var ConstantPositionProperty = function(value) {
        this._value = value;
    };

    ConstantPositionProperty.prototype.getValueCartesian = function(time, result) {
        var value = this._value;
        if (typeof value.clone === 'function') {
            return value.clone(result);
        }
        return value;
    };

    ConstantPositionProperty.prototype.setValue = function(value) {
        this._value = value;
    };

    function createObject(kml, dynamicObjectCollection) {
        var id = kml.id;
        if (typeof id === 'undefined') {
            id = createGuid();
        } else {
            var finalId = id;
            while (typeof dynamicObjectCollection.getObject(finalId) !== 'undefined') {
                finalId = createGuid();
            }
            id = finalId;
        }
        var dynamicObject = dynamicObjectCollection.getOrCreateObject(id);
        dynamicObject.kml = kml;
        return dynamicObject;
    }

    //Helper functions
    function readCoordinates(el) {
        var text = "", coords = [], i;
        for (i = 0; i < el.childNodes.length; i++) {
            text = text + el.childNodes[i].nodeValue;
        }

        var coordsArray = text.split(' '); //TODO add every whitespace character as a possible separator by using regExp
        var finalCoords = [];
        for(var j = 0; coordsArray[j]; j++){
            var regExp = /(\-?\+?[0-9]+\.?[0-9]*)(,\-?\+?[0-9]+\.?[0-9]*)(,[0-9]+\.?[0-9]?)?$/;
            coords[j] = regExp.exec(coordsArray[j]);
            coords[j].shift(); //the first element is not needed, remove it
            finalCoords.push([]); //new inner array
            finalCoords[j][0] = parseFloat(coords[j][0], 10);
            finalCoords[j][1] = parseFloat(coords[j][1].substring(1), 10);
            finalCoords[j][2] = coords[j][2] && parseFloat(coords[j][2].substring(1), 10);
        }
        if(finalCoords.length === 1){
            return finalCoords[0]; //single tuple
        }
        return finalCoords;
    }

    function getId(node){
        var id = node.attributes.id && node.attributes.id.nodeValue;
        if (typeof id === 'undefined') {
            id = createGuid();
        }
        return id;
    }

    function getElementValue(node, elementType){
        var element = node.getElementsByTagName(elementType)[0];
        if (elementType === 'hotSpot' && typeof element !== 'undefined'){
            var hotSpot = {
              x: element.attributes.x.nodeValue,
              y: element.attributes.y.nodeValue,
              xunits: element.attributes.xunits.nodeValue,
              yunits: element.attributes.yunits.nodeValue
            };
            return hotSpot;
        }
            return element && element.firstChild.data; //protecting from TypeError
    }

    function getEmbeddedStyle(node){
        //TODO find a more efficient solution
        var style = node.getElementsByTagName('IconStyle');
        style = node.getElementsByTagName('LabelStyle');
        style = node.getElementsByTagName('LineStyle');
        style = node.getElementsByTagName('PolyStyle');
        return style;
    }

    function getColor(node, colorType){
        var color;
        if(typeof colorType ===  'undefined'){
            color = getElementValue(node,'color');
        } else {
            color = getElementValue(node, colorType);
        }
        color = parseInt(color,16);
        return color;
    }

    // KML processing functions
    function processPlacemark(dataSource, placemark, dynamicObjectCollection, styleCollection) {
        placemark.id = getId(placemark);
        var dynamicObject = dynamicObjectCollection.getOrCreateObject(placemark.id);
        dynamicObject.name = getElementValue(placemark, 'name');

        // I want to iterate over every placemark
        for(var i = 0, len = placemark.childNodes.length; i < len; i++){
            var node = placemark.childNodes.item(i);
            //Checking if the node holds a supported Geometry type
            if(geometryTypes.hasOwnProperty(node.nodeName)){
                placemark.geometry = node.nodeName;
                var geometryType = placemark.geometry;
                var geometryHandler = geometryTypes[geometryType];
                if (typeof geometryHandler === 'undefined') {
                    throw new RuntimeError('Unknown geometry type: ' + geometryType);
                }
                geometryHandler(dataSource, placemark, node, dynamicObjectCollection, styleCollection);
            }
        }
    }

    function processPoint(dataSource, kml, node, dynamicObjectCollection, styleCollection) {
        var el = node.getElementsByTagName('coordinates');
        var coordinates = [];
        for (var j = 0; j < el.length; j++) {
            coordinates = coordinates.concat(readCoordinates(el[j]));
        }

        var cartographic = Cartographic.fromDegrees(coordinates[0], coordinates[1], coordinates[2]);
        var cartesian3 = Ellipsoid.WGS84.cartographicToCartesian(cartographic);
        var dynamicObject = dynamicObjectCollection.getOrCreateObject(kml.id);

        var embeddedStyle = getEmbeddedStyle(kml);
        if(embeddedStyle.length > 0){
            processStyle(embeddedStyle, dynamicObject);
        } else {
            var styleUrl = kml.getElementsByTagName('styleUrl');
            if(styleUrl.length > 0){
                var styleObj = styleCollection.getObject(styleUrl[0].textContent);
                if(typeof styleObj.label !== 'undefined'){ //TODO find a better way to set the text part of labels...
                    styleObj.label.text = dynamicObject.name;
                }
                dynamicObject.merge(styleObj);
            }
        }
        dynamicObject.position = new ConstantPositionProperty(cartesian3);
    }

    function processLineString(dataSource, kml, node, dynamicObjectCollection, styleCollection){
        var el = node.getElementsByTagName('coordinates');
        var coordinates = [];
        for (var j = 0; j < el.length; j++) {
            coordinates = coordinates.concat(readCoordinates(el[j]));
        }

    }

    function processLinearRing(dataSource, kml, node){

    }

    function processPolygon(dataSource, kml, node){

    }

    function processMultiGeometry(dataSource, kml, node){

    }

    function processModel(dataSource, kml, node){

    }

    function processGxTrack(dataSource, kml, node){

    }

    function processGxMultiTrack(dataSource, kml, node){

    }

    //Object that holds all supported Geometry
    var geometryTypes = {
            Point : processPoint,
            LineString : processLineString,
            LinearRing : processLinearRing,
            Polygon : processPolygon,
            MultiGeometry : processMultiGeometry,
            Model : processModel,
            gxTrack : processGxTrack,
            gxMultitrack : processGxMultiTrack
        };

    function processStyle(styleNode, dynamicObject) {
        for(var i = 0, len = styleNode.childNodes.length; i < len; i++){
            var node = styleNode.childNodes.item(i);

            if(node.nodeName === "IconStyle"){
                dynamicObject.billboard = new DynamicBillboard();
                //Map style to billboard properties
                //TODO heading, hotSpot and ColorMode
                var scale = getElementValue(node, 'scale');
                var icon = getElementValue(node,'href');
                var color = getColor(node);

                dynamicObject.billboard.image = icon && new ConstantProperty(icon);
                dynamicObject.billboard.scale = scale && new ConstantProperty(scale);
                dynamicObject.billboard.color = color && new ConstantProperty(Color.fromRgba(color));
            }
            if(node.nodeName ===  "LabelStyle")   {
                dynamicObject.label = new DynamicLabel();
                //Map style to label properties
                //TODO ColorMode
                var labelScale = getElementValue(node, 'scale');
                var labelColor = getColor(node);

                dynamicObject.label.scale = labelScale && new ConstantProperty(labelScale);
                dynamicObject.label.fillcolor = labelColor && new ConstantProperty(Color.fromRgba(labelColor));
                dynamicObject.label.text = dynamicObject.name && new ConstantProperty(dynamicObject.name);
            }
            if(node.nodeName ===  "LineStyle")   {
                dynamicObject.polyline = new DynamicPolyline();
                //Map style to line properties
                //TODO PhysicalWidth, Visibility, ColorMode
                var lineColor = getColor(node);
                var lineWidth = getElementValue(node,'width');
                var lineOuterColor = getColor(node,'gx:outerColor');
                var lineOuterWidth = getElementValue(node,'gx:outerWidth');

                dynamicObject.polyline.color = lineColor && new ConstantProperty(Color.fromRgba(lineColor));
                dynamicObject.polyline.width = lineWidth && new ConstantProperty(lineWidth);
                dynamicObject.polyline.outlineColor = lineOuterColor && new ConstantProperty(Color.fromRgba(lineOuterColor));
                dynamicObject.polyline.outlineWidth = lineOuterWidth && new ConstantProperty(lineOuterWidth);
            }
            if(node.nodeName === "PolyStyle")   {
                dynamicObject.polygon = new DynamicPolygon();
                //Map style to polygon properties
            }
        }
    }

    function processFolder(){

    }

    function loadKML(dataSource, kml, sourceUri) {
        var dynamicObjectCollection = dataSource._dynamicObjectCollection;

        if (typeof kml === 'undefined') {
            throw new DeveloperError('kml is required.');
        }
        if (typeof dynamicObjectCollection === 'undefined') {
            throw new DeveloperError('dynamicObjectCollection is required.');
        }

        var stylesArray = kml.getElementsByTagName('Style');
        var styleCollection = new DynamicObjectCollection();
        for ( var i = 0, len = stylesArray.length; i < len; i++){
            var styleNode = stylesArray.item(i);
            styleNode.id = '#' + getId(styleNode);
            var styleObject = styleCollection.getOrCreateObject(styleNode.id);

            processStyle(styleNode, styleObject);
        }

        var array = kml.getElementsByTagName('Folder');
        for (i = 0, len = array.length; i < len; i++){
            processFolder(dataSource, array[i], dynamicObjectCollection);
        }

        array = kml.getElementsByTagName('Placemark');
        for (i = 0, len = array.length; i < len; i++){
            var placemarkDynamicObject = new DynamicObject();
            var embeddedStyleNode = getEmbeddedStyle(array[i]);

            if(embeddedStyleNode.length > 0){
                processStyle(embeddedStyleNode, placemarkDynamicObject);
            } else {
                var styleUrl = array[i].getElementsByTagName('styleUrl');
                if(styleUrl.length > 0){
                    var styleObj = styleCollection.getObject(styleUrl[0].textContent);
                    placemarkDynamicObject.merge(styleObj);
                }
            }
            processPlacemark(dataSource, array[i], dynamicObjectCollection, styleCollection); //placemarkDynamicObject?
        }
    }

    /**
     * A {@link DataSource} which processes KML.
     * @alias KmlDataSource
     * @constructor
     */
    var KmlDataSource = function(){
        this._changed = new Event();
        this._error = new Event();
        this._clock = undefined;
        this._dynamicObjectCollection = new DynamicObjectCollection();
        this._timeVarying = true;
    };

    /**
     * Gets an event that will be raised when non-time-varying data changes
     * or if the return value of getIsTimeVarying changes.
     * @memberof DataSource
     *
     * @returns {Event} The event.
     */
    KmlDataSource.prototype.getChangedEvent = function() {
        return this._changed;
    };

    /**
     * Gets an event that will be raised if an error is encountered during processing.
     * @memberof KmlDataSource
     *
     * @returns {Event} The event.
     */
    KmlDataSource.prototype.getErrorEvent = function() {
        return this._error;
    };

    /**
     * Gets the top level clock defined in KML or the availability of the
     * underlying data if no clock is defined.  If the KML document only contains
     * infinite data, undefined will be returned.
     * @memberof KmlDataSource
     *
     * @returns {DynamicClock} The clock associated with the current KML data, or undefined if none exists.
     */
    KmlDataSource.prototype.getClock = function() {
        return undefined;
    };

    /**
     * Gets the DynamicObjectCollection generated by this data source.
     * @memberof DataSource
     *
     * @returns {DynamicObjectCollection} The collection of objects generated by this data source.
     */
    KmlDataSource.prototype.getDynamicObjectCollection = function() {
        return this._dynamicObjectCollection;
    };

    /**
     * Gets a value indicating if the data varies with simulation time.  If the return value of
     * this function changes, the changed event will be raised.
     * @memberof DataSource
     *
     * @returns {Boolean} True if the data is varies with simulation time, false otherwise.
     */
    KmlDataSource.prototype.getIsTimeVarying = function() {
        return true;
    };

    /**
     * Replaces any existing data with the provided KML.
     *
     * @param {Object} KML The KML to be processed.
     * @param {String} source The source of the KML.
     *
     * @exception {DeveloperError} KML is required.
     */
    KmlDataSource.prototype.load = function(kml, source) {
        if (typeof kml === 'undefined') {
            throw new DeveloperError('kml is required.');
        }

        this._dynamicObjectCollection.clear();
        loadKML(this, kml, source);
        this._changed.raiseEvent(this);
    };

    /**
     * Asynchronously loads the KML at the provided url, replacing any existing data.
     *
     * @param {Object} url The url to be processed.
     *
     * @returns {Promise} a promise that will resolve when the KML is processed.
     *
     * @exception {DeveloperError} url is required.
     */
    KmlDataSource.prototype.loadUrl = function(url) {
        if (typeof url === 'undefined') {
            throw new DeveloperError('url is required.');
        }

        var dataSource = this;
        return loadXML(url).then(function(kml) {
            dataSource.load(kml, url);
        }, function(error) {
            this._error.raiseEvent(this, error);
        });
    };

    return KmlDataSource;
});<commit_msg>Fix bugs related to LineStyle processing<commit_after>/*global define*/
define(['../Core/createGuid',
        '../Core/Cartographic',
        '../Core/Color',
        '../Core/ClockRange',
        '../Core/ClockStep',
        '../Core/DeveloperError',
        '../Core/RuntimeError',
        '../Core/Ellipsoid',
        '../Core/Event',
        '../Core/Iso8601',
        '../Core/loadXML',
        './ConstantProperty',
        './DynamicProperty',
        './DynamicClock',
        './DynamicObject',
        './DynamicObjectCollection',
        './DynamicPoint',
        './DynamicPolyline',
        './DynamicPolygon',
        './DynamicLabel',
        './DynamicBillboard'
        ], function(
                createGuid,
                Cartographic,
                Color,
                ClockRange,
                ClockStep,
                DeveloperError,
                RuntimeError,
                Ellipsoid,
                Event,
                Iso8601,
                loadXML,
                ConstantProperty,
                DynamicProperty,
                DynamicClock,
                DynamicObject,
                DynamicObjectCollection,
                DynamicPoint,
                DynamicPolyline,
                DynamicPolygon,
                DynamicLabel,
                DynamicBillboard) {
    "use strict";

    //Copied from GeoJsonDataSource
    var ConstantPositionProperty = function(value) {
        this._value = value;
    };

    ConstantPositionProperty.prototype.getValueCartesian = function(time, result) {
        var value = this._value;
        if (typeof value.clone === 'function') {
            return value.clone(result);
        }
        return value;
    };

    ConstantPositionProperty.prototype.setValue = function(value) {
        this._value = value;
    };

    function createObject(kml, dynamicObjectCollection) {
        var id = kml.id;
        if (typeof id === 'undefined') {
            id = createGuid();
        } else {
            var finalId = id;
            while (typeof dynamicObjectCollection.getObject(finalId) !== 'undefined') {
                finalId = createGuid();
            }
            id = finalId;
        }
        var dynamicObject = dynamicObjectCollection.getOrCreateObject(id);
        dynamicObject.kml = kml;
        return dynamicObject;
    }

    //Helper functions
    function readCoordinates(el) {
        var text = "", coords = [], i;
        for (i = 0; i < el.childNodes.length; i++) {
            text = text + el.childNodes[i].nodeValue;
        }

        var coordsArray = text.split(' '); //TODO add every whitespace character as a possible separator by using regExp
        var finalCoords = [];
        for(var j = 0; coordsArray[j]; j++){
            var regExp = /(\-?\+?[0-9]+\.?[0-9]*)(,\-?\+?[0-9]+\.?[0-9]*)(,[0-9]+\.?[0-9]?)?$/;
            coords[j] = regExp.exec(coordsArray[j]);
            coords[j].shift(); //the first element is not needed, remove it
            finalCoords.push([]); //new inner array
            finalCoords[j][0] = parseFloat(coords[j][0], 10);
            finalCoords[j][1] = parseFloat(coords[j][1].substring(1), 10);
            finalCoords[j][2] = coords[j][2] && parseFloat(coords[j][2].substring(1), 10);
        }
        if(finalCoords.length === 1){
            return finalCoords[0]; //single tuple
        }
        return finalCoords;
    }

    function getId(node){
        var id = node.attributes.id && node.attributes.id.nodeValue;
        if (typeof id === 'undefined') {
            id = createGuid();
        }
        return id;
    }

    function getElementValue(node, elementType){
        var element = node.getElementsByTagName(elementType)[0];
        if (elementType === 'hotSpot' && typeof element !== 'undefined'){
            var hotSpot = {
              x: element.attributes.x.nodeValue,
              y: element.attributes.y.nodeValue,
              xunits: element.attributes.xunits.nodeValue,
              yunits: element.attributes.yunits.nodeValue
            };
            return hotSpot;
        }
            return element && element.firstChild.data; //protecting from TypeError
    }

    function getEmbeddedStyle(node){
        //TODO find a more efficient solution
        var style = node.getElementsByTagName('IconStyle');
        style = node.getElementsByTagName('LabelStyle');
        style = node.getElementsByTagName('LineStyle');
        style = node.getElementsByTagName('PolyStyle');
        return style;
    }

    function getColor(node, colorType){
        var color;
        if(typeof colorType ===  'undefined'){
            color = getElementValue(node,'color');
        } else {
            color = getElementValue(node, colorType);
        }
        color = parseInt(color,16);
        return color;
    }

    // KML processing functions
    function processPlacemark(dataSource, placemark, dynamicObjectCollection, styleCollection) {
        placemark.id = getId(placemark);
        var dynamicObject = dynamicObjectCollection.getOrCreateObject(placemark.id);
        dynamicObject.name = getElementValue(placemark, 'name');

        // I want to iterate over every placemark
        for(var i = 0, len = placemark.childNodes.length; i < len; i++){
            var node = placemark.childNodes.item(i);
            //Checking if the node holds a supported Geometry type
            if(geometryTypes.hasOwnProperty(node.nodeName)){
                placemark.geometry = node.nodeName;
                var geometryType = placemark.geometry;
                var geometryHandler = geometryTypes[geometryType];
                if (typeof geometryHandler === 'undefined') {
                    throw new RuntimeError('Unknown geometry type: ' + geometryType);
                }
                geometryHandler(dataSource, placemark, node, dynamicObjectCollection, styleCollection);
            }
        }
    }

    function processPoint(dataSource, kml, node, dynamicObjectCollection, styleCollection) {
        var el = node.getElementsByTagName('coordinates');
        var coordinates = [];
        for (var j = 0; j < el.length; j++) {
            coordinates = coordinates.concat(readCoordinates(el[j]));
        }

        var cartographic = Cartographic.fromDegrees(coordinates[0], coordinates[1], coordinates[2]);
        var cartesian3 = Ellipsoid.WGS84.cartographicToCartesian(cartographic);
        var dynamicObject = dynamicObjectCollection.getOrCreateObject(kml.id);

        var embeddedStyle = getEmbeddedStyle(kml);
        if(embeddedStyle.length > 0){
            processStyle(embeddedStyle, dynamicObject);
        } else {
            var styleUrl = kml.getElementsByTagName('styleUrl');
            if(styleUrl.length > 0){
                var styleObj = styleCollection.getObject(styleUrl[0].textContent);
                if(typeof styleObj.label !== 'undefined'){ //TODO find a better way to set the text part of labels...
                    styleObj.label.text = new ConstantProperty(dynamicObject.name);
                }
                dynamicObject.merge(styleObj);
            }
        }
        dynamicObject.position = new ConstantPositionProperty(cartesian3);
    }

    function processLineString(dataSource, kml, node, dynamicObjectCollection, styleCollection){
        var el = node.getElementsByTagName('coordinates');
        var coordinates = [];
        for (var j = 0; j < el.length; j++) {
            coordinates = coordinates.concat(readCoordinates(el[j]));
        }

    }

    function processLinearRing(dataSource, kml, node){

    }

    function processPolygon(dataSource, kml, node){

    }

    function processMultiGeometry(dataSource, kml, node){

    }

    function processModel(dataSource, kml, node){

    }

    function processGxTrack(dataSource, kml, node){

    }

    function processGxMultiTrack(dataSource, kml, node){

    }

    //Object that holds all supported Geometry
    var geometryTypes = {
            Point : processPoint,
            LineString : processLineString,
            LinearRing : processLinearRing,
            Polygon : processPolygon,
            MultiGeometry : processMultiGeometry,
            Model : processModel,
            gxTrack : processGxTrack,
            gxMultitrack : processGxMultiTrack
        };

    function processStyle(styleNode, dynamicObject) {
        for(var i = 0, len = styleNode.childNodes.length; i < len; i++){
            var node = styleNode.childNodes.item(i);

            if(node.nodeName === "IconStyle"){
                dynamicObject.billboard = new DynamicBillboard();
                //Map style to billboard properties
                //TODO heading, hotSpot and ColorMode
                var scale = getElementValue(node, 'scale');
                var icon = getElementValue(node,'href');
                var color = getColor(node);

                dynamicObject.billboard.image = icon && new ConstantProperty(icon);
                dynamicObject.billboard.scale = scale && new ConstantProperty(scale);
                dynamicObject.billboard.color = color && new ConstantProperty(Color.fromRgba(color));
            }
            if(node.nodeName ===  "LabelStyle")   {
                dynamicObject.label = new DynamicLabel();
                //Map style to label properties
                //TODO ColorMode
                var labelScale = getElementValue(node, 'scale');
                var labelColor = getColor(node);

                dynamicObject.label.scale = labelScale && new ConstantProperty(labelScale);
                dynamicObject.label.fillColor = labelColor && new ConstantProperty(Color.fromRgba(labelColor)); //not sure how to set font color
                dynamicObject.label.text = dynamicObject.name && new ConstantProperty(dynamicObject.name);
            }
            if(node.nodeName ===  "LineStyle")   {
                dynamicObject.polyline = new DynamicPolyline();
                //Map style to line properties
                //TODO PhysicalWidth, Visibility, ColorMode
                var lineColor = getColor(node);
                var lineWidth = getElementValue(node,'width');
                var lineOuterColor = getColor(node,'gx:outerColor');
                var lineOuterWidth = getElementValue(node,'gx:outerWidth');

                dynamicObject.polyline.color = lineColor && new ConstantProperty(Color.fromRgba(lineColor));
                dynamicObject.polyline.width = lineWidth && new ConstantProperty(lineWidth);
                dynamicObject.polyline.outlineColor = lineOuterColor && new ConstantProperty(Color.fromRgba(lineOuterColor));
                dynamicObject.polyline.outlineWidth = lineOuterWidth && new ConstantProperty(lineOuterWidth);
            }
            if(node.nodeName === "PolyStyle")   {
                dynamicObject.polygon = new DynamicPolygon();
                //Map style to polygon properties
            }
        }
    }

    function processFolder(){

    }

    function loadKML(dataSource, kml, sourceUri) {
        var dynamicObjectCollection = dataSource._dynamicObjectCollection;

        if (typeof kml === 'undefined') {
            throw new DeveloperError('kml is required.');
        }
        if (typeof dynamicObjectCollection === 'undefined') {
            throw new DeveloperError('dynamicObjectCollection is required.');
        }

        var stylesArray = kml.getElementsByTagName('Style');
        var styleCollection = new DynamicObjectCollection();
        for ( var i = 0, len = stylesArray.length; i < len; i++){
            var styleNode = stylesArray.item(i);
            styleNode.id = '#' + getId(styleNode);
            var styleObject = styleCollection.getOrCreateObject(styleNode.id);

            processStyle(styleNode, styleObject);
        }

        var array = kml.getElementsByTagName('Folder');
        for (i = 0, len = array.length; i < len; i++){
            processFolder(dataSource, array[i], dynamicObjectCollection);
        }

        array = kml.getElementsByTagName('Placemark');
        for (i = 0, len = array.length; i < len; i++){
            var placemarkDynamicObject = new DynamicObject();
            var embeddedStyleNode = getEmbeddedStyle(array[i]);

            if(embeddedStyleNode.length > 0){
                processStyle(embeddedStyleNode, placemarkDynamicObject);
            } else {
                var styleUrl = array[i].getElementsByTagName('styleUrl');
                if(styleUrl.length > 0){
                    var styleObj = styleCollection.getObject(styleUrl[0].textContent);
                    placemarkDynamicObject.merge(styleObj);
                }
            }
            processPlacemark(dataSource, array[i], dynamicObjectCollection, styleCollection); //placemarkDynamicObject?
        }
    }

    /**
     * A {@link DataSource} which processes KML.
     * @alias KmlDataSource
     * @constructor
     */
    var KmlDataSource = function(){
        this._changed = new Event();
        this._error = new Event();
        this._clock = undefined;
        this._dynamicObjectCollection = new DynamicObjectCollection();
        this._timeVarying = true;
    };

    /**
     * Gets an event that will be raised when non-time-varying data changes
     * or if the return value of getIsTimeVarying changes.
     * @memberof DataSource
     *
     * @returns {Event} The event.
     */
    KmlDataSource.prototype.getChangedEvent = function() {
        return this._changed;
    };

    /**
     * Gets an event that will be raised if an error is encountered during processing.
     * @memberof KmlDataSource
     *
     * @returns {Event} The event.
     */
    KmlDataSource.prototype.getErrorEvent = function() {
        return this._error;
    };

    /**
     * Gets the top level clock defined in KML or the availability of the
     * underlying data if no clock is defined.  If the KML document only contains
     * infinite data, undefined will be returned.
     * @memberof KmlDataSource
     *
     * @returns {DynamicClock} The clock associated with the current KML data, or undefined if none exists.
     */
    KmlDataSource.prototype.getClock = function() {
        return undefined;
    };

    /**
     * Gets the DynamicObjectCollection generated by this data source.
     * @memberof DataSource
     *
     * @returns {DynamicObjectCollection} The collection of objects generated by this data source.
     */
    KmlDataSource.prototype.getDynamicObjectCollection = function() {
        return this._dynamicObjectCollection;
    };

    /**
     * Gets a value indicating if the data varies with simulation time.  If the return value of
     * this function changes, the changed event will be raised.
     * @memberof DataSource
     *
     * @returns {Boolean} True if the data is varies with simulation time, false otherwise.
     */
    KmlDataSource.prototype.getIsTimeVarying = function() {
        return true;
    };

    /**
     * Replaces any existing data with the provided KML.
     *
     * @param {Object} KML The KML to be processed.
     * @param {String} source The source of the KML.
     *
     * @exception {DeveloperError} KML is required.
     */
    KmlDataSource.prototype.load = function(kml, source) {
        if (typeof kml === 'undefined') {
            throw new DeveloperError('kml is required.');
        }

        this._dynamicObjectCollection.clear();
        loadKML(this, kml, source);
        this._changed.raiseEvent(this);
    };

    /**
     * Asynchronously loads the KML at the provided url, replacing any existing data.
     *
     * @param {Object} url The url to be processed.
     *
     * @returns {Promise} a promise that will resolve when the KML is processed.
     *
     * @exception {DeveloperError} url is required.
     */
    KmlDataSource.prototype.loadUrl = function(url) {
        if (typeof url === 'undefined') {
            throw new DeveloperError('url is required.');
        }

        var dataSource = this;
        return loadXML(url).then(function(kml) {
            dataSource.load(kml, url);
        }, function(error) {
            this._error.raiseEvent(this, error);
        });
    };

    return KmlDataSource;
});<|endoftext|>


<commit_before>// ==UserScript==
// @name         mastodonLangRemover
// @namespace    https://arthurlacoste.com
// @version      0.0.2
// @description  Remove a lang from web interface
// @author       Arthur Lacoste <arthak@gmail.com>
// @match        *://*/web/*
// @match        *://*/settings/preferences
// @require      http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @require      https://raw.githubusercontent.com/pietrasiak/jquery.initialize/master/jquery.initialize.min.js
// @connect      detect-lang-api.irz.fr
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_xmlhttpRequest
// @grant        GM_addStyle
// ==/UserScript==

(function() {
	'use strict';

	$(".status").initialize(function () {
		$(this).hide();
		getTranslation($(this));
	});

	function getTranslation(toot) {
		var langText = {};
		var text = 	toot.children('.status__content').text()
		.replace(/(?:https?|ftp):\/\/[\n\S]+/g, '')
		.substring(0, 200); // analyze first 200 chars (more in japananese don't work !)

		text = encodeURIComponent(text);

		GM_xmlhttpRequest({
			method: 'GET',
			headers: {
				'Accept': 'application/json'
			},
			url: "https://detect-lang-api.irz.fr/lang/"+text,
			onload: function(res) {
				var resJson = JSON.parse(res.responseText);
				langText = resJson.lang;
				if(GM_getValue('lang', ['ja']).includes(langText)) {
					toot.remove();
					console.log("RM--" + toot.children('.status__content').text());
				} else {
					toot.show();
					console.log(langText + '==' + toot.children('.status__content').text());
				}
			},
			onerror: function() {
				toot.show();
				console.log('There was an error');
			}
		});
		return String(langText);
	}

	function saveSettings(event) {
		if (event.target.tagName.toLowerCase() === 'button' && event.target.textContent === 'Save changes') {
			event.preventDefault();
			//var input = document.getElementById('translation_locale');
			//var selectedLanguage = input.options[input.selectedIndex].value;
			var selectedValues = [];
			$("#translation_locale :selected").each(function(){
				selectedValues.push($(this).val());
			});
			//alert(selectedValues);

			GM_setValue('lang', selectedValues);

			setTimeout(function() {
				document.querySelector('body').removeEventListener('click', saveSettings, false);
				actions.children[0].click();
			}, 500);
		}
	}

	if (window.location.pathname === '/settings/preferences') {
		// We're on the settings page
		var form = document.querySelector('form.simple_form');
		var actions = document.querySelector('div.actions');

		var settingsGroup = form.querySelector('div.fields-group').cloneNode(true);
		settingsGroup.children[1].remove(); // Remove the privacy element from the clone

		var notice = document.createElement('div');
		var noticeMsg = 'Select here the langage you want to remove.';
		notice.setAttribute('id', 'translation_notice');
		notice.innerHTML = '
Lang Remover

'+noticeMsg+'
';

		var languageDiv = settingsGroup.children[0];
		languageDiv.classList.remove('user_locale');
		languageDiv.classList.add('translation_locale');
		var label = languageDiv.children[0].children[0];
		label.setAttribute('for', 'translation_locale');
		label.textContent = 'Language to remove';
		var input = languageDiv.children[0].children[1];
		input.setAttribute('multiple','');
		input.setAttribute('name', 'user[translation]');
		input.setAttribute('id', 'translation_locale');
		input.setAttribute('style', 'height: 300px;');

		settingsGroup.insertBefore(notice, languageDiv);
		form.insertBefore(settingsGroup, actions);

		var selectedValues = GM_getValue('lang', ['ja']);
		$("#translation_locale").val(selectedValues);

		document.querySelector('body').addEventListener('click', saveSettings, false);
	}

})();<commit_msg>Changing server to IRZ domain name 🍚<commit_after>// ==UserScript==
// @name         mastodonLangRemover
// @namespace    https://arthurlacoste.com
// @version      0.0.3
// @description  Remove a lang from web interface
// @author       Arthur Lacoste <arthak@gmail.com>
// @match        *://*/web/*
// @match        *://*/settings/preferences
// @require      http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @require      https://raw.githubusercontent.com/pietrasiak/jquery.initialize/master/jquery.initialize.min.js
// @connect      detect-lang-api.irz.fr
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_xmlhttpRequest
// @grant        GM_addStyle
// ==/UserScript==

(function() {
	'use strict';

	$(".status").initialize(function () {
		$(this).hide();
		getTranslation($(this));
	});

	function getTranslation(toot) {
		var langText = {};
		var text = 	toot.children('.status__content').text()
		.replace(/(?:https?|ftp):\/\/[\n\S]+/g, '')
		.substring(0, 200); // analyze first 200 chars (more in japananese don't work !)

		text = encodeURIComponent(text);

		GM_xmlhttpRequest({
			method: 'GET',
			headers: {
				'Accept': 'application/json'
			},
			url: "https://detect-lang-api.irz.fr/lang/"+text,
			onload: function(res) {
				var resJson = JSON.parse(res.responseText);
				langText = resJson.lang;
				if(GM_getValue('lang', ['ja']).includes(langText)) {
					toot.remove();
					console.log("RM--" + toot.children('.status__content').text());
				} else {
					toot.show();
					console.log(langText + '==' + toot.children('.status__content').text());
				}
			},
			onerror: function() {
				toot.show();
				console.log('There was an error');
			}
		});
		return String(langText);
	}

	function saveSettings(event) {
		if (event.target.tagName.toLowerCase() === 'button' && event.target.textContent === 'Save changes') {
			event.preventDefault();
			//var input = document.getElementById('translation_locale');
			//var selectedLanguage = input.options[input.selectedIndex].value;
			var selectedValues = [];
			$("#translation_locale :selected").each(function(){
				selectedValues.push($(this).val());
			});
			//alert(selectedValues);

			GM_setValue('lang', selectedValues);

			setTimeout(function() {
				document.querySelector('body').removeEventListener('click', saveSettings, false);
				actions.children[0].click();
			}, 500);
		}
	}

	if (window.location.pathname === '/settings/preferences') {
		// We're on the settings page
		var form = document.querySelector('form.simple_form');
		var actions = document.querySelector('div.actions');

		var settingsGroup = form.querySelector('div.fields-group').cloneNode(true);
		settingsGroup.children[1].remove(); // Remove the privacy element from the clone

		var notice = document.createElement('div');
		var noticeMsg = 'Select here the langage you want to remove.';
		notice.setAttribute('id', 'translation_notice');
		notice.innerHTML = '
Lang Remover

'+noticeMsg+'
';

		var languageDiv = settingsGroup.children[0];
		languageDiv.classList.remove('user_locale');
		languageDiv.classList.add('translation_locale');
		var label = languageDiv.children[0].children[0];
		label.setAttribute('for', 'translation_locale');
		label.textContent = 'Language to remove';
		var input = languageDiv.children[0].children[1];
		input.setAttribute('multiple','');
		input.setAttribute('name', 'user[translation]');
		input.setAttribute('id', 'translation_locale');
		input.setAttribute('style', 'height: 300px;');

		settingsGroup.insertBefore(notice, languageDiv);
		form.insertBefore(settingsGroup, actions);

		var selectedValues = GM_getValue('lang', ['ja']);
		$("#translation_locale").val(selectedValues);

		document.querySelector('body').addEventListener('click', saveSettings, false);
	}

})();<|endoftext|>


<commit_before>/*
 * See http://www.sudokuwiki.org/Arto_Inkala_Sudoku
 */
define(function()
{
    "use strict";
    var SudokuWiki = {
        UNSOLVABLE_28: "unsolvable28",
        UNSOLVABLE_49: "unsolvable49",
        ARTO_INKALAS_PUZZLE: "artoInkalasPuzzle",
        ESCARGOT: "escargot",

        properties:
        {
            "unsolvable28":
            {
                // See http://www.sudokuwiki.org/Weekly_Sudoku.asp?puz=28
                name: "Unsolvable #28",
                grid: "6....894." + // row A
                    "9....61.." + // row B
                    ".7..4...." + // row C
                    "2..61...." + // row D
                    "......2.." + // row E
                    ".89..2..." + // row F
                    "....6...5" + // row G
                    ".......3." + // row H
                    "8....16..", // row I
                value: "unsolvable28",
            },
            "unsolvable49":
            {
                // See http://www.sudokuwiki.org/Weekly_Sudoku.asp?puz=49
                name: "Unsolvable #49",
                grid: "..28....." + // row A
                    ".3..6...7" + // row B
                    "1......4." + // row C
                    "6...9...." + // row D
                    ".5.6....9" + // row E
                    "....57.6." + // row F
                    "...3..1.." + // row G
                    ".7...6..8" + // row H
                    "4......2.", // row I
                value: "unsolvable49",
            },
            "artoInkalasPuzzle":
            {
                // See http://www.sudokuwiki.org/sudoku.htm?bd=800000000003600000070090200050007000000045700000100030001000068008500010090000400
                name: "Arto Inkala's Puzzle",
                grid: "8........" + // row A
                    "..36....." + // row B
                    ".7..9.2.." + // row C
                    ".5...7..." + // row D
                    "....457.." + // row E
                    "...1...3." + // row F
                    "..1....68" + // row G
                    "..85...1." + // row H
                    ".9....4..", // row I
                value: "artoInkalasPuzzle",
            },
            "escargot":
            {
                // See http://www.sudokuwiki.org/sudoku.htm?bd=100007090030020008009600500005300900010080002600004000300000010041000007007000300
                name: "Escargot",
                grid: "1....7.9." + // row A
                    ".3..2...8" + // row B
                    "..96..5.." + // row C
                    "..53..9.." + // row D
                    ".1..8...2" + // row E
                    "6....4..." + // row F
                    "3......1." + // row G
                    ".41.....7" + // row H
                    "..7...3..", // row I
                value: "escargot",
            },
        },

        values: function()
        {
            return Object.getOwnPropertyNames(SudokuWiki.properties);
        },
    };

    if (Object.freeze)
    {
        Object.freeze(SudokuWiki);
    }

    return SudokuWiki;
});
<commit_msg>Changed order from easiest to hardest.<commit_after>/*
 * See http://www.sudokuwiki.org/Arto_Inkala_Sudoku
 */
define(function()
{
    "use strict";
    var SudokuWiki = {
        ESCARGOT: "escargot",
        ARTO_INKALAS_PUZZLE: "artoInkalasPuzzle",
        UNSOLVABLE_49: "unsolvable49",
        UNSOLVABLE_28: "unsolvable28",

        properties:
        {
            "escargot":
            {
                // See http://www.sudokuwiki.org/sudoku.htm?bd=100007090030020008009600500005300900010080002600004000300000010041000007007000300
                name: "Escargot",
                grid: "1....7.9." + // row A
                    ".3..2...8" + // row B
                    "..96..5.." + // row C
                    "..53..9.." + // row D
                    ".1..8...2" + // row E
                    "6....4..." + // row F
                    "3......1." + // row G
                    ".41.....7" + // row H
                    "..7...3..", // row I
                value: "escargot",
            },
            "artoInkalasPuzzle":
            {
                // See http://www.sudokuwiki.org/sudoku.htm?bd=800000000003600000070090200050007000000045700000100030001000068008500010090000400
                name: "Arto Inkala's Puzzle",
                grid: "8........" + // row A
                    "..36....." + // row B
                    ".7..9.2.." + // row C
                    ".5...7..." + // row D
                    "....457.." + // row E
                    "...1...3." + // row F
                    "..1....68" + // row G
                    "..85...1." + // row H
                    ".9....4..", // row I
                value: "artoInkalasPuzzle",
            },
            "unsolvable49":
            {
                // See http://www.sudokuwiki.org/Weekly_Sudoku.asp?puz=49
                name: "Unsolvable #49",
                grid: "..28....." + // row A
                    ".3..6...7" + // row B
                    "1......4." + // row C
                    "6...9...." + // row D
                    ".5.6....9" + // row E
                    "....57.6." + // row F
                    "...3..1.." + // row G
                    ".7...6..8" + // row H
                    "4......2.", // row I
                value: "unsolvable49",
            },
            "unsolvable28":
            {
                // See http://www.sudokuwiki.org/Weekly_Sudoku.asp?puz=28
                name: "Unsolvable #28",
                grid: "6....894." + // row A
                    "9....61.." + // row B
                    ".7..4...." + // row C
                    "2..61...." + // row D
                    "......2.." + // row E
                    ".89..2..." + // row F
                    "....6...5" + // row G
                    ".......3." + // row H
                    "8....16..", // row I
                value: "unsolvable28",
            },
        },

        values: function()
        {
            return Object.getOwnPropertyNames(SudokuWiki.properties);
        },
    };

    if (Object.freeze)
    {
        Object.freeze(SudokuWiki);
    }

    return SudokuWiki;
});
<|endoftext|>


<commit_before>const { superstruct } = require('superstruct')
const getFileNames = require('./getFileNames')

module.exports = (api, config) => {
  api.logger.debug('Validating config', config)
  const struct = superstruct()

  const entry = struct.optional(struct.union(['string', 'array', 'object']))

  const output = struct(
    {
      dir: 'string',
      sourceMap: 'boolean',
      minimize: 'boolean',
      format: struct.enum(['iife', 'cjs', 'umd']),
      moduleName: struct.optional('string'),
      publicUrl: 'string',
      target: struct.enum([
        'web',
        'node',
        'electron', // Alias to electron-renderer
        'electron-renderer',
        'electron-main',
        'node-webkit',
        'webworker',
        'async-node'
      ]),
      clean: 'boolean',
      fileNames: struct.optional(
        struct.object({
          js: struct.optional('string'),
          css: struct.optional('string'),
          font: struct.optional('string'),
          image: struct.optional('string')
        })
      ),
      html: struct.optional(struct.union(['boolean', 'object']))
    },
    {
      dir: 'dist',
      sourceMap: !api.isProd,
      minimize: api.isProd,
      format: 'iife',
      publicUrl: '/',
      target: 'web',
      default: true,
      clean: true
    }
  )

  const babel = struct(
    {
      jsx: 'string',
      transpileModules: struct.optional(struct.list(['string'])),
      namedImports: struct.optional('object')
    },
    {
      jsx: 'react'
    }
  )

  const css = struct(
    {
      extract: 'boolean',
      loaderOptions: struct.optional(
        struct.object({
          css: struct.optional('object'),
          less: struct.optional('object'),
          postcss: struct.optional('object'),
          sass: struct.optional('object'),
          stylus: struct.optional('object')
        })
      )
    },
    {
      extract: api.isProd
    }
  )

  const devServer = struct(
    {
      hot: 'boolean',
      hotOnly: 'boolean?',
      host: 'string',
      port: struct.union(['string', 'number']),
      hotEntries: struct(['string']),
      proxy: struct.optional(
        struct.union([
          'string',
          'object',
          'function',
          struct([struct.union(['object', 'function'])])
        ])
      ),
      open: 'boolean',
      historyApiFallback: struct.optional(struct.union(['boolean', 'object'])),
      before: struct.optional('function'),
      after: struct.optional('function'),
      https: struct.optional(struct.union(['boolean', 'object']))
    },
    {
      hot: true,
      host: '0.0.0.0',
      port: 4000,
      hotEntries: ['index'],
      open: false
    }
  )

  const plugins = struct.optional([
    struct.union([
      'string',
      struct({
        resolve: struct.union(['string', 'object']),
        options: struct.optional('object')
      })
    ])
  ])

  const assets = struct(
    {
      inlineImageMaxSize: struct.optional('number')
    },
    {
      inlineImageMaxSize: 5000
    }
  )

  const Struct = struct(
    {
      entry,
      output,
      plugins,
      parallel: 'boolean',
      cache: 'boolean',
      babel,
      css,
      devServer,
      envs: struct.optional('object'),
      constants: struct.optional('object'),
      chainWebpack: struct.optional('function'),
      configureWebpack: struct.optional(struct.union(['object', 'function'])),
      assets,
      publicFolder: struct.union(['string', 'boolean']),
      pages: struct.optional('object')
    },
    {
      cache: true,
      parallel: false,
      publicFolder: 'public'
    }
  )

  const [error, result] = Struct.validate(config)

  if (error) {
    throw error
  }

  result.output.fileNames = Object.assign(
    getFileNames({ useHash: api.isProd, format: result.output.format }),
    result.output.fileNames
  )

  if (!result.entry) {
    if (api.pkg.data.source) {
      api.logger.debug(
        'Using the value of `source` field in `package.json` as app entry'
      )
      result.entry = api.pkg.data.source
    } else {
      api.logger.debug('Using `index` as app entry')
      result.entry = 'index'
    }
  }

  // Always disable cache in test mode
  if (process.env.NODE_ENV === 'test') {
    result.cache = false
  }

  // Ensure publicUrl
  result.output.publicUrl = result.output.publicUrl
    // Must end with slash
    .replace(/\/?$/, '/')
    // Remove leading ./
    .replace(/^\.\//, '')

  api.logger.debug('Validated config', result)

  return result
}
<commit_msg>fix(serve): read host and port from env vars<commit_after>const { superstruct } = require('superstruct')
const getFileNames = require('./getFileNames')

module.exports = (api, config) => {
  api.logger.debug('Validating config', config)
  const struct = superstruct()

  const entry = struct.optional(struct.union(['string', 'array', 'object']))

  const output = struct(
    {
      dir: 'string',
      sourceMap: 'boolean',
      minimize: 'boolean',
      format: struct.enum(['iife', 'cjs', 'umd']),
      moduleName: struct.optional('string'),
      publicUrl: 'string',
      target: struct.enum([
        'web',
        'node',
        'electron', // Alias to electron-renderer
        'electron-renderer',
        'electron-main',
        'node-webkit',
        'webworker',
        'async-node'
      ]),
      clean: 'boolean',
      fileNames: struct.optional(
        struct.object({
          js: struct.optional('string'),
          css: struct.optional('string'),
          font: struct.optional('string'),
          image: struct.optional('string')
        })
      ),
      html: struct.optional(struct.union(['boolean', 'object']))
    },
    {
      dir: 'dist',
      sourceMap: !api.isProd,
      minimize: api.isProd,
      format: 'iife',
      publicUrl: '/',
      target: 'web',
      default: true,
      clean: true
    }
  )

  const babel = struct(
    {
      jsx: 'string',
      transpileModules: struct.optional(struct.list(['string'])),
      namedImports: struct.optional('object')
    },
    {
      jsx: 'react'
    }
  )

  const css = struct(
    {
      extract: 'boolean',
      loaderOptions: struct.optional(
        struct.object({
          css: struct.optional('object'),
          less: struct.optional('object'),
          postcss: struct.optional('object'),
          sass: struct.optional('object'),
          stylus: struct.optional('object')
        })
      )
    },
    {
      extract: api.isProd
    }
  )

  const devServer = struct(
    {
      hot: 'boolean',
      hotOnly: 'boolean?',
      host: 'string',
      port: struct.union(['string', 'number']),
      hotEntries: struct(['string']),
      proxy: struct.optional(
        struct.union([
          'string',
          'object',
          'function',
          struct([struct.union(['object', 'function'])])
        ])
      ),
      open: 'boolean',
      historyApiFallback: struct.optional(struct.union(['boolean', 'object'])),
      before: struct.optional('function'),
      after: struct.optional('function'),
      https: struct.optional(struct.union(['boolean', 'object']))
    },
    {
      hot: true,
      // Cloud IDEs use envs
      host: process.env.HOST || '0.0.0.0',
      port: process.env.PORT || 4000,
      hotEntries: ['index'],
      open: false
    }
  )

  const plugins = struct.optional([
    struct.union([
      'string',
      struct({
        resolve: struct.union(['string', 'object']),
        options: struct.optional('object')
      })
    ])
  ])

  const assets = struct(
    {
      inlineImageMaxSize: struct.optional('number')
    },
    {
      inlineImageMaxSize: 5000
    }
  )

  const Struct = struct(
    {
      entry,
      output,
      plugins,
      parallel: 'boolean',
      cache: 'boolean',
      babel,
      css,
      devServer,
      envs: struct.optional('object'),
      constants: struct.optional('object'),
      chainWebpack: struct.optional('function'),
      configureWebpack: struct.optional(struct.union(['object', 'function'])),
      assets,
      publicFolder: struct.union(['string', 'boolean']),
      pages: struct.optional('object')
    },
    {
      cache: true,
      parallel: false,
      publicFolder: 'public'
    }
  )

  const [error, result] = Struct.validate(config)

  if (error) {
    throw error
  }

  result.output.fileNames = Object.assign(
    getFileNames({ useHash: api.isProd, format: result.output.format }),
    result.output.fileNames
  )

  if (!result.entry) {
    if (api.pkg.data.source) {
      api.logger.debug(
        'Using the value of `source` field in `package.json` as app entry'
      )
      result.entry = api.pkg.data.source
    } else {
      api.logger.debug('Using `index` as app entry')
      result.entry = 'index'
    }
  }

  // Always disable cache in test mode
  if (process.env.NODE_ENV === 'test') {
    result.cache = false
  }

  // Ensure publicUrl
  result.output.publicUrl = result.output.publicUrl
    // Must end with slash
    .replace(/\/?$/, '/')
    // Remove leading ./
    .replace(/^\.\//, '')

  api.logger.debug('Validated config', result)

  return result
}
<|endoftext|>


<commit_before><commit_msg>Eliminato il file navigation.js<commit_after><|endoftext|>