<commit_before>(function() {
    angular.module("TodoApp").controller("TodoController", TodoController);

    function TodoController( $http, $rootScope, $filter, $scope, todoService) {
        var vm = this;
        var deregisters = [];
        $http.defaults.transformRequest.push(function(config) {
            vm.loading = true;
            return config;
        });
        $http.defaults.transformResponse.push(function(response) {
            vm.loading = false;
            return response;
        });

        deregisters.push($rootScope.$on("todosChanged", reloadTodoList));
        deregisters.push($rootScope.$on("errorResponse", handleError));
        $scope.$on("$destroy", destroyThis);

        vm.loading = false;
        vm.items = [];

        vm.submitForm = function() {
            todoService.createTodo(vm.newTodo);
            vm.newTodo = "";
        };

        vm.toggleTodoComplete = function(todo) {
            todo.isComplete = !todo.isComplete;
            todoService.updateTodo(todo);
        };

        vm.todoDeleted = function(todoId) {
            todoService.deleteTodo(todoId);
        };

        function reloadTodoList() {
            todoService.getTodoList().success(function(data) {
                data.forEach(function(newTodo) {
                    if ($filter('filter')(vm.items, newTodo).length > 0 ) {
                        return;
                    }else if($filter('filter')(vm.items, {id : newTodo.id}).length > 0 ) {
                        var oldTodo = $filter('filter')(vm.items, {id : newTodo.id})[0];
                        var index = vm.items.indexOf(oldTodo);
                        vm.items[index] = newTodo;
                    }else{
                        vm.items.push(newTodo);
                    }

                });
                vm.items = vm.items.filter(function(oldTodo) {
                    return $filter('filter')(data, {id : oldTodo.id}).length > 0
                });
        }

        function handleError(event, text, status){
            vm.error = "Failed to do action. Server returned " + status + " - " + text;
        }

        function destroyThis(){
            deregisters.forEach(function(eventDereg) { eventDereg();});
        }

        vm.onDropComplete = function (index, obj, evt) {
            var otherObj = vm.items[index];
            var otherIndex = vm.items.indexOf(obj);
            vm.items[index] = obj;
            vm.items[otherIndex] = otherObj;
        }
        reloadTodoList();
    }
})();
<commit_msg>GOing to squash this<commit_after>(function() {
    angular.module("TodoApp").controller("TodoController", TodoController);

    function TodoController( $http, $rootScope, $filter, $scope, todoService) {
        var vm = this;
        var deregisters = [];
        $http.defaults.transformRequest.push(function(config) {
            vm.loading = true;
            return config;
        });
        $http.defaults.transformResponse.push(function(response) {
            vm.loading = false;
            return response;
        });

        deregisters.push($rootScope.$on("todosChanged", reloadTodoList));
        deregisters.push($rootScope.$on("errorResponse", handleError));
        $scope.$on("$destroy", destroyThis);

        vm.loading = false;
        vm.items = [];

        vm.submitForm = function() {
            todoService.createTodo(vm.newTodo);
            vm.newTodo = "";
        };

        vm.toggleTodoComplete = function(todo) {
            todo.isComplete = !todo.isComplete;
            todoService.updateTodo(todo);
        };

        vm.todoDeleted = function(todoId) {
            todoService.deleteTodo(todoId);
        };

        function reloadTodoList() {
            todoService.getTodoList().success(function(data) {
                data.forEach(function(newTodo) {
                    if ($filter('filter')(vm.items, newTodo).length > 0 ) {
                        return;
                    }else if($filter('filter')(vm.items, {id : newTodo.id}).length > 0 ) {
                        var oldTodo = $filter('filter')(vm.items, {id : newTodo.id})[0];
                        var index = vm.items.indexOf(oldTodo);
                        vm.items[index] = newTodo;
                    }else{
                        vm.items.push(newTodo);
                    }

                });
                vm.items = vm.items.filter(function(oldTodo) {
                    return $filter('filter')(data, {id : oldTodo.id}).length > 0
                });
            });
        }

        function handleError(event, text, status){
            vm.error = "Failed to do action. Server returned " + status + " - " + text;
        }

        function destroyThis(){
            deregisters.forEach(function(eventDereg) { eventDereg();});
        }

        vm.onDropComplete = function (index, obj, evt) {
            var otherObj = vm.items[index];
            var otherIndex = vm.items.indexOf(obj);
            vm.items[index] = obj;
            vm.items[otherIndex] = otherObj;
        }
        reloadTodoList();
    }
})();
<|endoftext|>


<commit_before>'use strict';

const rethinkDB = require('rethinkdb');
const program = require('commander');

const common = require('./common');
const log = require('./log');

/*
The system of locations.
0.* Passable blocks
  1.1 a ground
  1.2 a grass

1.* Impassable blocks
  0.1 a wall (!!!should be renamed!!!)
  0.2 a tree

 */

class Location {
  constructor(conn, locationSize, locationId) {
    this.conn = conn;
    this.locationSize = locationSize;
    this.locationId = locationId;

    this.locationMap = [];
    for (let i = 0; i < locationSize; i++) this.locationMap.push([]);
  }

  createTable() {
    rethinkDB
      .tableCreate(this.locationId)
      .run(this.conn, (err) => {
        if (err) throw err;

        log.info(`Table for ${this.locationId} created`);
        this.writeNewLocationMap();
      });
  }

  writeNewLocationMap() {
    let buffer = [];

    for (let y = 0; y < this.locationMap.length; y++) {
      let mapRow = this.locationMap[y];

      for (let x = 0; x < mapRow.length; x++) {
        let elem = {};
        elem['x'] = x;
        elem['y'] = y;
        elem['type'] = mapRow[x];
        buffer.push(elem);
      }
    }

    rethinkDB
      .table(this.locationId)
      .insert(buffer)
      .run(this.conn, (err, res) => {
        if (err) throw err;

        log.info(`Location map done. We inserted ${res['inserted']} elements to ${this.locationId}`);
        log.info(`Let's create the index for ${this.locationId}!`);

        rethinkDB
          .table(this.locationId)
          .indexCreate('coord', [rethinkDB.row('x'), rethinkDB.row('y')])
          .run(this.conn, (err) => {
            if (err) throw err;

            rethinkDB
              .table(this.locationId)
              .indexWait('coord')
              .run(this.conn, (err) => {
                if (err) throw err;

                log.info(`Index for ${this.locationId} created!`);
              });
          });
      });
  }
}

class ForestLocation extends Location {
  generate () {
    for (let i = 0; i < this.locationMap.length; i++) {
      for (let ii = 0; ii < this.locationSize; ii++) {
        let x = common.getRandomInt(0, 100);

        if (x <= 50) {
          // add grass
          this.locationMap[i].push(1.2);
        } else if (x >= 51 && x <= 97) {
          // add tree
          this.locationMap[i].push(0.2);
        } else {
          // add ground
          this.locationMap[i].push(1.2)
        }
      }
    }

    this.createTable();
  }
}

class MeadowLocation extends Location {
  generate () {
    for (let i = 0; i < this.locationMap.length; i++) {
      for (let ii = 0; ii < this.locationSize; ii++) {
        let x = common.getRandomInt(0, 100);

        if (x <= 90) {
          // add grass
          this.locationMap[i].push(1.2);
        } else if (x >= 91 && x <= 97) {
          // add tree
          this.locationMap[i].push(0.2);
        } else {
          // add ground
          this.locationMap[i].push(1.1)
        }
      }
    }

    this.createTable();
  }
}

class WorldGenerator {
  constructor (conn, worldSize, locationSize) {
    this.conn = conn;
    this.worldSize = worldSize;
    this.locationSize = locationSize;

    this.world = [];
    for (let i = 0; i < this.worldSize; i++) this.world.push([]);

    this.locationTypes = [ForestLocation, MeadowLocation];
  }

  getLocation (locationId) {
    const location = this.locationTypes[common.getRandomInt(0, 1)];
    return new location(this.conn, this.locationSize, locationId);
  }

  getStartLocationId () {
    return this.world[0][0];
  }

  writeWorldMap () {
    let buffer = [];

    for (let i = 0; i < this.world.length; i++) {
      for (let ii =0; ii < this.world[i].length; ii++) {
        let locationElem = {};

        locationElem.id = this.world[i][ii];

        if (i > 0) {
          locationElem.neighborUp = this.world[i - 1][ii];
        }

        if (i < this.worldSize - 1) {
          locationElem.neighborDown = this.world[i + 1][ii];
        }

        if (ii > 0) {
          locationElem.neighborLeft = this.world[i][ii - 1];
        }

        if (ii < this.worldSize - 1) {
          locationElem.neighborRight = this.world[i][ii + 1];
        }

        buffer.push(locationElem);
      }
    }

    rethinkDB
      .tableCreate('worldMap')
      .run(this.conn, (err) => {
        if (err) throw err;

        log.info(`Table for world map created`);

        rethinkDB
          .table('worldMap')
          .insert(buffer)
          .run(this.conn, (err) => {
            if (err) throw err;

            log.info(`World's map created and written to the disk.`)
          });
      });
  }

  generate () {
    for (let i = 0; i < this.world.length; i++) {
      for (let ii =0; ii < this.worldSize; ii++) {
        const locationId = `location_${i}_${ii}`;
        const location = this.getLocation(locationId);

        location.generate();
        this.world[i].push(locationId);
      }
    }

    this.writeWorldMap();
    return this.getStartLocationId();
  }
}

class CoralUserGenerator {
  constructor (conn, number, startLocationId) {
    this.conn = conn;
    this.name = 'coral';
    this.number = number;

    this.user = {x: 0, y: 0, direction: 'up', login: undefined, location: startLocationId};
  }

  generate () {
    rethinkDB
      .tableCreate('userPosition')
      .run(this.conn, (err) => {
        if (err) throw err;

        let login;

        for (let i = 0; i < this.number; i++) {
          this.user.login = `${this.name}${i}`;

          log.info(`Create test user ${this.user.login}`);

          rethinkDB
            .table('userPosition')
            .insert(this.user)
            .run(this.conn, (err) => {
              if (err) throw err;
            });
        }
      });
  }
}

if (require.main === module) {
  program
  .version('0.0.1')
  .option('-d, --dbname [name]', 'Name of world database')
  .option('-p, --port <n>', 'Port for RethinkDB, default is 28015', parseInt, {isDefault: 28015})
  .option('-t, --test <n>', 'Create n Corals', parseInt)
  .parse(process.argv);

  rethinkDB.connect( {host: 'localhost', port: program.port}, function(err, conn) {
    if (err) throw err;

    rethinkDB
      .dbCreate(program.dbname)
      .run(conn, (err) => {
        if (err) {
          log.error(`The world is exist. `
            + `If you really want create a new world, `
            + `delete the database "${program.dbname}".`);

          throw  err;
        }

        conn.use(program.dbname);

        const worldGenerator = new WorldGenerator(conn, 3, 100);
        const startLocationId = worldGenerator.generate();
        log.info(`start location id is ${startLocationId}`);

        if (program.test) {
          const userGenerator = new CoralUserGenerator(conn, program.test, startLocationId);
          userGenerator.generate();
        }
      });
  });
}
<commit_msg>change field names and coefficients<commit_after>'use strict';

const rethinkDB = require('rethinkdb');
const program = require('commander');

const common = require('./common');
const log = require('./log');

/*
The system of locations.
0.* Passable blocks
  1.1 a ground
  1.2 a grass

1.* Impassable blocks
  0.1 a wall (!!!should be renamed!!!)
  0.2 a tree

 */

class Location {
  constructor(conn, locationSize, locationId) {
    this.conn = conn;
    this.locationSize = locationSize;
    this.locationId = locationId;

    this.locationMap = [];
    for (let i = 0; i < locationSize; i++) this.locationMap.push([]);
  }

  createTable() {
    rethinkDB
      .tableCreate(this.locationId)
      .run(this.conn, (err) => {
        if (err) throw err;

        log.info(`Table for ${this.locationId} created`);
        this.writeNewLocationMap();
      });
  }

  writeNewLocationMap() {
    let buffer = [];

    for (let y = 0; y < this.locationMap.length; y++) {
      let mapRow = this.locationMap[y];

      for (let x = 0; x < mapRow.length; x++) {
        let elem = {};
        elem['x'] = x;
        elem['y'] = y;
        elem['type'] = mapRow[x];
        buffer.push(elem);
      }
    }

    rethinkDB
      .table(this.locationId)
      .insert(buffer)
      .run(this.conn, (err, res) => {
        if (err) throw err;

        log.info(`Location map done. We inserted ${res['inserted']} elements to ${this.locationId}`);
        log.info(`Let's create the index for ${this.locationId}!`);

        rethinkDB
          .table(this.locationId)
          .indexCreate('coord', [rethinkDB.row('x'), rethinkDB.row('y')])
          .run(this.conn, (err) => {
            if (err) throw err;

            rethinkDB
              .table(this.locationId)
              .indexWait('coord')
              .run(this.conn, (err) => {
                if (err) throw err;

                log.info(`Index for ${this.locationId} created!`);
              });
          });
      });
  }
}

class ForestLocation extends Location {
  generate () {
    for (let i = 0; i < this.locationMap.length; i++) {
      for (let ii = 0; ii < this.locationSize; ii++) {
        let x = common.getRandomInt(0, 100);

        if (x <= 75) {
          // add grass
          this.locationMap[i].push(1.2);
        } else if (x > 75 && x < 98) {
          // add tree
          this.locationMap[i].push(0.2);
        } else {
          // add ground
          this.locationMap[i].push(1.2)
        }
      }
    }

    this.createTable();
  }
}

class MeadowLocation extends Location {
  generate () {
    for (let i = 0; i < this.locationMap.length; i++) {
      for (let ii = 0; ii < this.locationSize; ii++) {
        let x = common.getRandomInt(0, 100);

        if (x <= 95) {
          // add grass
          this.locationMap[i].push(1.2);
        } else if (x > 95 && x < 98) {
          // add tree
          this.locationMap[i].push(0.2);
        } else {
          // add ground
          this.locationMap[i].push(1.1)
        }
      }
    }

    this.createTable();
  }
}

class WorldGenerator {
  constructor (conn, worldSize, locationSize) {
    this.conn = conn;
    this.worldSize = worldSize;
    this.locationSize = locationSize;

    this.world = [];
    for (let i = 0; i < this.worldSize; i++) this.world.push([]);

    this.locationTypes = [ForestLocation, MeadowLocation];
  }

  getLocation (locationId) {
    const location = this.locationTypes[common.getRandomInt(0, 1)];
    return new location(this.conn, this.locationSize, locationId);
  }

  getStartLocationId () {
    return this.world[0][0];
  }

  writeWorldMap () {
    let buffer = [];

    for (let i = 0; i < this.world.length; i++) {
      for (let ii =0; ii < this.world[i].length; ii++) {
        let locationElem = {};

        locationElem.location_id = this.world[i][ii];

        if (i > 0) {
          locationElem.up = this.world[i - 1][ii];
        }

        if (i < this.worldSize - 1) {
          locationElem.down = this.world[i + 1][ii];
        }

        if (ii > 0) {
          locationElem.left = this.world[i][ii - 1];
        }

        if (ii < this.worldSize - 1) {
          locationElem.right = this.world[i][ii + 1];
        }

        buffer.push(locationElem);
      }
    }

    rethinkDB
      .tableCreate('worldMap')
      .run(this.conn, (err) => {
        if (err) throw err;

        log.info(`Table for world map created`);

        rethinkDB
          .table('worldMap')
          .insert(buffer)
          .run(this.conn, (err) => {
            if (err) throw err;

            log.info(`World's map created and written to the disk.`)
          });
      });
  }

  generate () {
    for (let i = 0; i < this.world.length; i++) {
      for (let ii =0; ii < this.worldSize; ii++) {
        const locationId = `location_${i}_${ii}`;
        const location = this.getLocation(locationId);

        location.generate();
        this.world[i].push(locationId);
      }
    }

    this.writeWorldMap();
    return this.getStartLocationId();
  }
}

class CoralUserGenerator {
  constructor (conn, number, startLocationId) {
    this.conn = conn;
    this.name = 'coral';
    this.number = number;

    this.user = {x: 0, y: 0, direction: 'up', login: undefined, location: startLocationId};
  }

  generate () {
    rethinkDB
      .tableCreate('userPosition')
      .run(this.conn, (err) => {
        if (err) throw err;

        let login;

        for (let i = 0; i < this.number; i++) {
          this.user.login = `${this.name}${i}`;

          log.info(`Create test user ${this.user.login}`);

          rethinkDB
            .table('userPosition')
            .insert(this.user)
            .run(this.conn, (err) => {
              if (err) throw err;
            });
        }
      });
  }
}

if (require.main === module) {
  program
  .version('0.0.1')
  .option('-d, --dbname [name]', 'Name of world database')
  .option('-p, --port <n>', 'Port for RethinkDB, default is 28015', parseInt, {isDefault: 28015})
  .option('-t, --test <n>', 'Create n Corals', parseInt)
  .parse(process.argv);

  rethinkDB.connect( {host: 'localhost', port: program.port}, function(err, conn) {
    if (err) throw err;

    rethinkDB
      .dbCreate(program.dbname)
      .run(conn, (err) => {
        if (err) {
          log.error(`The world is exist. `
            + `If you really want create a new world, `
            + `delete the database "${program.dbname}".`);

          throw  err;
        }

        conn.use(program.dbname);

        const worldGenerator = new WorldGenerator(conn, 3, 100);
        const startLocationId = worldGenerator.generate();
        log.info(`start location id is ${startLocationId}`);

        if (program.test) {
          const userGenerator = new CoralUserGenerator(conn, program.test, startLocationId);
          userGenerator.generate();
        }
      });
  });
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2012 - Syu Kato <ukyo.web@gmail.com>
 *
 * License: MIT
 *
 * utils of jsziptools.
 */

jz.utils = jz.utils || {};

(function(window, jz){

/**
 * If a argument is ArrayBuffer, return a Uint8Array view.
 *
 * @param {ArrayBuffer|Uint8Array} buffer
 * @return {Uint8Array}
 */
jz.utils.arrayBufferToBytes = function(buffer){
	return buffer.constructor === Uint8Array ? buffer : new Uint8Array(buffer);
};

/**
 * Convert a UTF-8 string to a ArrayBuffer.
 *
 * @param {string} str
 * @return {ArrayBuffer}
 */
jz.utils.stringToArrayBuffer = function(str){
	var n = str.length,
		idx = -1,
		utf8 = [],
		i, j, c;

	//http://user1.matsumoto.ne.jp/~goma/js/utf.js
	for(i = 0; i < n; ++i){
		c = str.charCodeAt(i);
		if(c <= 0x7F){
			utf8[++idx] = c;
		} else if(c <= 0x7FF){
			utf8[++idx] = 0xC0 | (c >>> 6);
			utf8[++idx] = 0x80 | (c & 0x3F);
		} else if(c <= 0xFFFF){
			utf8[++idx] = 0xE0 | (c >>> 12);
			utf8[++idx] = 0x80 | ((c >>> 6) & 0x3F);
			utf8[++idx] = 0x80 | (c & 0x3F);
		} else {
			j = 4;
			while(c >> (6 * j)) ++j;
			utf8[++idx] = ((0xFF00 >>> j) & 0xFF) | (c >>> (6 * --j));
			while(j--)
				utf8[++idx] = 0x80 | ((c >>> (6 * j)) & 0x3F);
		}
	}
	return new Uint8Array(utf8).buffer;
};

/**
 * Read a 32bit unsigned number(little endian).
 *
 * @param {ArrayBuffer|Uint8Array} bytes
 * @param {number} offset
 * @return {number}
 */
jz.utils.readUintLE = function(bytes, offset){
	bytes = jz.utils.arrayBufferToBytes(bytes);
	return bytes[offset] | bytes[offset + 1] << 8 | bytes[offset + 2] << 16 | bytes[offset + 3] << 24;
};

/**
 * Read a 16bit unsigned number(little endian).
 *
 * @param {ArrayBuffer|Uint8Array} bytes
 * @param {number} offset
 * @return {number}
 */
jz.utils.readUshortLE = function(bytes, offset){
	bytes = jz.utils.arrayBufferToBytes(bytes);
	return bytes[offset] | bytes[offset + 1] << 8;
};

/**
 * Read a 32bit unsigned number(big endian).
 *
 * @param {ArrayBuffer|Uint8Array} bytes
 * @param {number} offset
 * @return {number}
 */
jz.utils.readUintBE = function(bytes, offset){
	bytes = jz.utils.arrayBufferToBytes(bytes);
	return bytes[offset + 3] | bytes[offset + 2] << 8 | bytes[offset + 1] << 16 | bytes[offset] << 24;
};

/**
 * Read a 16bit unsigned number(big endian).
 *
 * @param {ArrayBuffer|Uint8Array} bytes
 * @param {number} offset
 * @return {number}
 */
jz.utils.readUshortBE = function(bytes, offset){
	bytes = jz.utils.arrayBufferToBytes(bytes);
	return bytes[offset + 1] | bytes[offset] << 8;
};

/**
 * Read a string(ascii only).
 *
 * @param {ArrayBuffer|Uint8Array} bytes
 * @param {number} offset
 * @param {number} length
 * @return {number}
 */
jz.utils.readString = function(bytes, offset, len){
	var ret = '';
	bytes = jz.utils.arrayBufferToBytes(bytes);

	for(var i = offset, l = offset + len; i < l; ++i) ret += String.fromCharCode(bytes[i]);
	return ret;
};

/**
 * Load a Buffer with Ajax.
 *
 * @param {string} url
 * @return {ArrayBuffer}
 */
jz.utils.loadFileBuffer = function(url){
	var xhr = new XMLHttpRequest();
	xhr.open('GET', url, false);
	//304対策
	xhr.setRequestHeader('If-Modified-Since', '01 Jan 1970 00:00:00 GMT');
	xhr.responseType = 'arraybuffer';
	xhr.send();
	return xhr.response;
};

/**
 * @param {...(Uint8Array|int8Array)} byteArrays
 * @return {Uint8Array}
 */
jz.utils.concatByteArrays = function(byteArrays){
	var byteArrays = Array.isArray(byteArrays) ? byteArrays : Array.prototype.slice.call(arguments, 0),
		size = 0,
		offset = 0,
		i, n, ret;

	for(i = 0, n = byteArrays.length; i < n; ++i) size += byteArrays[i].length;
	ret = new Uint8Array(size);
	for(i = 0; i < n; ++i) {
		ret.set(byteArrays[i], offset);
		offset += byteArrays[i].length;
	}
	return ret;
};

})(this, jz);
<commit_msg>use DataView<commit_after>/**
 * Copyright (c) 2012 - Syu Kato <ukyo.web@gmail.com>
 *
 * License: MIT
 *
 * utils of jsziptools.
 */

jz.utils = jz.utils || {};

(function(window, jz){

/**
 * If a argument is ArrayBuffer, return a Uint8Array view.
 *
 * @param {ArrayBuffer|Uint8Array} buffer
 * @return {Uint8Array}
 */
jz.utils.arrayBufferToBytes = function(buffer){
	return buffer.constructor === Uint8Array ? buffer : new Uint8Array(buffer);
};

/**
 * Convert a UTF-8 string to a ArrayBuffer.
 *
 * @param {string} str
 * @return {ArrayBuffer}
 */
jz.utils.stringToArrayBuffer = function(str){
	var n = str.length,
		idx = -1,
		utf8 = [],
		i, j, c;

	//http://user1.matsumoto.ne.jp/~goma/js/utf.js
	for(i = 0; i < n; ++i){
		c = str.charCodeAt(i);
		if(c <= 0x7F){
			utf8[++idx] = c;
		} else if(c <= 0x7FF){
			utf8[++idx] = 0xC0 | (c >>> 6);
			utf8[++idx] = 0x80 | (c & 0x3F);
		} else if(c <= 0xFFFF){
			utf8[++idx] = 0xE0 | (c >>> 12);
			utf8[++idx] = 0x80 | ((c >>> 6) & 0x3F);
			utf8[++idx] = 0x80 | (c & 0x3F);
		} else {
			j = 4;
			while(c >> (6 * j)) ++j;
			utf8[++idx] = ((0xFF00 >>> j) & 0xFF) | (c >>> (6 * --j));
			while(j--)
				utf8[++idx] = 0x80 | ((c >>> (6 * j)) & 0x3F);
		}
	}
	return new Uint8Array(utf8).buffer;
};

/**
 * Load a Buffer with Ajax.
 *
 * @param {string} url
 * @return {ArrayBuffer}
 */
jz.utils.loadFileBuffer = function(url){
	var xhr = new XMLHttpRequest();
	xhr.open('GET', url, false);
	//304対策
	xhr.setRequestHeader('If-Modified-Since', '01 Jan 1970 00:00:00 GMT');
	xhr.responseType = 'arraybuffer';
	xhr.send();
	return xhr.response;
};

/**
 * @param {...(Uint8Array|int8Array)} byteArrays
 * @return {Uint8Array}
 */
jz.utils.concatByteArrays = function(byteArrays){
	var byteArrays = Array.isArray(byteArrays) ? byteArrays : Array.prototype.slice.call(arguments, 0),
		size = 0,
		offset = 0,
		i, n, ret;

	for(i = 0, n = byteArrays.length; i < n; ++i) size += byteArrays[i].length;
	ret = new Uint8Array(size);
	for(i = 0; i < n; ++i) {
		ret.set(byteArrays[i], offset);
		offset += byteArrays[i].length;
	}
	return ret;
};

})(this, jz);
<|endoftext|>


<commit_before>import _trim from 'lodash.trim'
import decode from 'jwt-decode'
import inflection from 'inflection'

export function stripSlashes (location) {
  return Array.isArray(location) ? location.map(l => _trim(l, '/')) : _trim(location, '/')
}

export function upperCaseFirst (string) {
  return string.charAt(0).toUpperCase() + string.slice(1)
}

export function getShortName (service) {
  let namespace = stripSlashes(service)
  if (Array.isArray(namespace)) {
    namespace = namespace.slice(-1)
  } else if (namespace.includes('/')) {
    namespace = namespace.slice(namespace.lastIndexOf('/') + 1)
  }
  return namespace
}

export function getNameFromPath (service) {
  return stripSlashes(service)
}

// from https://github.com/iliakan/detect-node
export const isNode = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'

export const isBrowser = !isNode

const authDefaults = {
  commit: undefined,
  req: undefined,
  moduleName: 'auth',
  cookieName: 'feathers-jwt'
}

export const initAuth = function initAuth (options) {
  const { commit, req, moduleName, cookieName } = Object.assign({}, authDefaults, options)

  if (typeof commit !== 'function') {
    throw new Error('You must pass the `commit` function in the `initAuth` function options.')
  }
  if (!req) {
    throw new Error('You must pass the `req` object in the `initAuth` function options.')
  }

  const accessToken = readCookie(req.headers.cookie, cookieName)
  const payload = getValidPayloadFromToken(accessToken)

  if (payload) {
    commit(`${moduleName}/setAccessToken`, accessToken)
    commit(`${moduleName}/setPayload`, payload)
  }
  return Promise.resolve(payload)
}

export function getValidPayloadFromToken (token) {
  if (token) {
    try {
      var payload = decode(token)
      return payloadIsValid(payload) ? payload : undefined
    } catch (error) {
      return undefined
    }
  }
  return undefined
}

// Pass a decoded payload and it will return a boolean based on if it hasn't expired.
export function payloadIsValid (payload) {
  return payload && payload.exp * 1000 > new Date().getTime()
}

// Reads and returns the contents of a cookie with the provided name.
export function readCookie (cookies, name) {
  if (!cookies) {
    console.log('no cookies found')
    return undefined
  }
  var nameEQ = name + '='
  var ca = cookies.split(';')
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i]
    while (c.charAt(0) === ' ') {
      c = c.substring(1, c.length)
    }
    if (c.indexOf(nameEQ) === 0) {
      return c.substring(nameEQ.length, c.length)
    }
  }
  return null
}

export function checkId (id, item, debug) {
  if (id === undefined || id === null) {
    if (debug) {
      console.error('No id found for item. Do you need to customize the `idField`?', item)
    }
    return false
  }
  return true
}

export function registerModel (Model, globalModels, apiPrefix, servicePath) {
  const modelName = getModelName(Model)
  let path = apiPrefix ? `${apiPrefix}.${modelName}` : modelName
  setByDot(globalModels, path, Model)
  globalModels.byServicePath[servicePath] = Model
  return path
}

// Creates a Model class name from the last part of the servicePath
export function getModelName (Model) {
  // If the Model.name has been customized, use it.
  if (Model.name !== 'FeathersVuexModel') {
    return Model.name
  }

  // Otherwise, use an inflection of the last bit of the servicePath
  const parts = Model.servicePath.split('/')
  let name = parts[parts.length - 1]
  name = inflection.classify(name)
  return name
}

//  From feathers-plus/feathers-hooks-common
export function setByDot (obj, path, value, ifDelete) {
  if (ifDelete) {
    console.log('DEPRECATED. Use deleteByDot instead of setByDot(obj,path,value,true). (setByDot)')
  }

  if (path.indexOf('.') === -1) {
    obj[path] = value

    if (value === undefined && ifDelete) {
      delete obj[path]
    }

    return
  }

  const parts = path.split('.')
  const lastIndex = parts.length - 1
  return parts.reduce(
    (obj1, part, i) => {
      if (i !== lastIndex) {
        if (!obj1.hasOwnProperty(part) || typeof obj1[part] !== 'object') {
          obj1[part] = {}
        }
        return obj1[part]
      }

      obj1[part] = value
      if (value === undefined && ifDelete) {
        delete obj1[part]
      }
      return obj1
    },
    obj
  )
}
<commit_msg>Fix class names<commit_after>import _trim from 'lodash.trim'
import decode from 'jwt-decode'
import inflection from 'inflection'

export function stripSlashes (location) {
  return Array.isArray(location) ? location.map(l => _trim(l, '/')) : _trim(location, '/')
}

export function upperCaseFirst (string) {
  return string.charAt(0).toUpperCase() + string.slice(1)
}

export function getShortName (service) {
  let namespace = stripSlashes(service)
  if (Array.isArray(namespace)) {
    namespace = namespace.slice(-1)
  } else if (namespace.includes('/')) {
    namespace = namespace.slice(namespace.lastIndexOf('/') + 1)
  }
  return namespace
}

export function getNameFromPath (service) {
  return stripSlashes(service)
}

// from https://github.com/iliakan/detect-node
export const isNode = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'

export const isBrowser = !isNode

const authDefaults = {
  commit: undefined,
  req: undefined,
  moduleName: 'auth',
  cookieName: 'feathers-jwt'
}

export const initAuth = function initAuth (options) {
  const { commit, req, moduleName, cookieName } = Object.assign({}, authDefaults, options)

  if (typeof commit !== 'function') {
    throw new Error('You must pass the `commit` function in the `initAuth` function options.')
  }
  if (!req) {
    throw new Error('You must pass the `req` object in the `initAuth` function options.')
  }

  const accessToken = readCookie(req.headers.cookie, cookieName)
  const payload = getValidPayloadFromToken(accessToken)

  if (payload) {
    commit(`${moduleName}/setAccessToken`, accessToken)
    commit(`${moduleName}/setPayload`, payload)
  }
  return Promise.resolve(payload)
}

export function getValidPayloadFromToken (token) {
  if (token) {
    try {
      var payload = decode(token)
      return payloadIsValid(payload) ? payload : undefined
    } catch (error) {
      return undefined
    }
  }
  return undefined
}

// Pass a decoded payload and it will return a boolean based on if it hasn't expired.
export function payloadIsValid (payload) {
  return payload && payload.exp * 1000 > new Date().getTime()
}

// Reads and returns the contents of a cookie with the provided name.
export function readCookie (cookies, name) {
  if (!cookies) {
    console.log('no cookies found')
    return undefined
  }
  var nameEQ = name + '='
  var ca = cookies.split(';')
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i]
    while (c.charAt(0) === ' ') {
      c = c.substring(1, c.length)
    }
    if (c.indexOf(nameEQ) === 0) {
      return c.substring(nameEQ.length, c.length)
    }
  }
  return null
}

export function checkId (id, item, debug) {
  if (id === undefined || id === null) {
    if (debug) {
      console.error('No id found for item. Do you need to customize the `idField`?', item)
    }
    return false
  }
  return true
}

export function registerModel (Model, globalModels, apiPrefix, servicePath) {
  const modelName = getModelName(Model)
  let path = apiPrefix ? `${apiPrefix}.${modelName}` : modelName
  setByDot(globalModels, path, Model)
  globalModels.byServicePath[servicePath] = Model
  return path
}

// Creates a Model class name from the last part of the servicePath
export function getModelName (Model) {
  // If the Model.name has been customized, use it.
  if (Model.name !== 'FeathersVuexModel') {
    return Model.name
  }

  // Otherwise, use an inflection of the last bit of the servicePath
  const parts = Model.servicePath.split('/')
  let name = parts[parts.length - 1]
  name = inflection.titleize(name)
  name = inflection.singularize(name)
  return name
}

//  From feathers-plus/feathers-hooks-common
export function setByDot (obj, path, value, ifDelete) {
  if (ifDelete) {
    console.log('DEPRECATED. Use deleteByDot instead of setByDot(obj,path,value,true). (setByDot)')
  }

  if (path.indexOf('.') === -1) {
    obj[path] = value

    if (value === undefined && ifDelete) {
      delete obj[path]
    }

    return
  }

  const parts = path.split('.')
  const lastIndex = parts.length - 1
  return parts.reduce(
    (obj1, part, i) => {
      if (i !== lastIndex) {
        if (!obj1.hasOwnProperty(part) || typeof obj1[part] !== 'object') {
          obj1[part] = {}
        }
        return obj1[part]
      }

      obj1[part] = value
      if (value === undefined && ifDelete) {
        delete obj1[part]
      }
      return obj1
    },
    obj
  )
}
<|endoftext|>


<commit_before>(function (angular) {
    angular.module('colorbreaker')
    .controller('gameController', function($scope) {
        var emptyRow = [null, null, null, null].map(function() {return {color: '', active: false};}),
            emptyFeedback = ['', '', '', ''];
        $scope.colors = ['red', 'orange', 'yellow', 'green', 'teal', 'blue', 'purple', 'brown'];
        $scope.activePin = null;
        $scope.rows = [];
        $scope.victory = false;

        var hiddenCombination = null;

        function generateHiddenCombination() {
            var colors = angular.copy($scope.colors);
            hiddenCombination = [null, null, null, null].map(function() {
                return colors.splice(Math.floor(Math.random() * colors.length), 1)[0];
            });
        }

        function createNewRow() {
            $scope.rows.push({pins: angular.copy(emptyRow), feedback: angular.copy(emptyFeedback)});
        };

        $scope.play = function() {
            $scope.victory = false;
            $scope.rows = [];
            createNewRow();
            generateHiddenCombination();
            console.log(hiddenCombination);
        };

        $scope.pinClicked = function(pin) {
            if($scope.activePin) {
                $scope.activePin.active = false;
            }
            $scope.activePin = pin;
            $scope.activePin.active = true;
        };

        $scope.selectColor = function(color) {
            $scope.activePin.color = color;
            $scope.activePin.active = false;
            $scope.activePin = null;
        };

        $scope.getPinClass = function(pin) {
            var classes = [];
            if(pin.active) {
                classes.push('active');
            }
            if(pin.color) {
                classes.push(pin.color + '-pin');
            } else {
                classes.push('hole-pin');
            }
            return classes;
        };

        $scope.getFeedbackPinClass = function(pin) {
            return pin ? pin + '-feedback-pin' : '';
        };

        $scope.lastRowIsFilled = function() {
            return $scope.rows[$scope.rows.length-1].pins.every(function(pin) {
                return pin.color;
            });
        };

        $scope.giveFeedback = function() {
            var feedbackPinIter = 0;
            var lastRow = $scope.rows[$scope.rows.length-1];
            lastRow.pins.forEach(function(pin, pinIndex) {
                var combinationPinIndex = hiddenCombination.indexOf(pin.color);
                if(combinationPinIndex >= 0) {
                    lastRow.feedback[feedbackPinIter] = combinationPinIndex === pinIndex ? 'black' : 'white';
                    feedbackPinIter++;
                }
            });
            lastRow.feedback.sort(function(a, b) {
                return !b || a < b ? -1 : 1;
            });
            var win = lastRow.feedback.every(function(color) {
                return color === 'black';
            });
            if(win) {
                $scope.victory = true;
            } else {
                createNewRow();
            }
        };

        $scope.play();
    });
})(angular);<commit_msg>Removed debug code<commit_after>(function (angular) {
    angular.module('colorbreaker')
    .controller('gameController', function($scope) {
        var emptyRow = [null, null, null, null].map(function() {return {color: '', active: false};}),
            emptyFeedback = ['', '', '', '']
            hiddenCombination = null;
        $scope.colors = ['red', 'orange', 'yellow', 'green', 'teal', 'blue', 'purple', 'brown'];
        $scope.activePin = null;
        $scope.rows = [];
        $scope.victory = false;

        function generateHiddenCombination() {
            var colors = angular.copy($scope.colors);
            hiddenCombination = [null, null, null, null].map(function() {
                return colors.splice(Math.floor(Math.random() * colors.length), 1)[0];
            });
        }

        function createNewRow() {
            $scope.rows.push({pins: angular.copy(emptyRow), feedback: angular.copy(emptyFeedback)});
        };

        $scope.play = function() {
            $scope.victory = false;
            $scope.rows = [];
            createNewRow();
            generateHiddenCombination();
        };

        $scope.pinClicked = function(pin) {
            if($scope.activePin) {
                $scope.activePin.active = false;
            }
            $scope.activePin = pin;
            $scope.activePin.active = true;
        };

        $scope.selectColor = function(color) {
            $scope.activePin.color = color;
            $scope.activePin.active = false;
            $scope.activePin = null;
        };

        $scope.getPinClass = function(pin) {
            var classes = [];
            if(pin.active) {
                classes.push('active');
            }
            if(pin.color) {
                classes.push(pin.color + '-pin');
            } else {
                classes.push('hole-pin');
            }
            return classes;
        };

        $scope.getFeedbackPinClass = function(pin) {
            return pin ? pin + '-feedback-pin' : '';
        };

        $scope.lastRowIsFilled = function() {
            return $scope.rows[$scope.rows.length-1].pins.every(function(pin) {
                return pin.color;
            });
        };

        $scope.giveFeedback = function() {
            var feedbackPinIter = 0;
            var lastRow = $scope.rows[$scope.rows.length-1];
            lastRow.pins.forEach(function(pin, pinIndex) {
                var combinationPinIndex = hiddenCombination.indexOf(pin.color);
                if(combinationPinIndex >= 0) {
                    lastRow.feedback[feedbackPinIter] = combinationPinIndex === pinIndex ? 'black' : 'white';
                    feedbackPinIter++;
                }
            });
            lastRow.feedback.sort(function(a, b) {
                return !b || a < b ? -1 : 1;
            });
            var win = lastRow.feedback.every(function(color) {
                return color === 'black';
            });
            if(win) {
                $scope.victory = true;
            } else {
                createNewRow();
            }
        };

        $scope.play();
    });
})(angular);<|endoftext|>


<commit_before>/* Omega JumpGate JS Representation
 *
 * Copyright (C) 2013 Mohammed Morsi <mo@morsi.org>
 *  Licensed under the AGPLv3+ http://www.gnu.org/licenses/agpl.txt
 */

//= require "ui/command"

Omega.JumpGate = function(parameters){
  this.components = [];
  this.shader_components = [];
  $.extend(this, parameters);

  this.location = Omega.convert_entity(this.location)
};

Omega.JumpGate.prototype = {
  constructor : Omega.JumpGate,
  json_class : 'Cosmos::Entities::JumpGate',

  toJSON : function(){
    return {json_class  : this.json_class,
            id          : this.id,
            name        : this.name,
            location    : this.location ? this.location.toJSON() : null,
            parent_id   : this.parent_id,
            endpoint_id : this.endpoint_id};
  },

  has_details : true,

  retrieve_details : function(page, details_cb){
    var title = 'Jump Gate to ' + this.endpoint_id;
    var loc   = '@ ' + this.location.to_s();
    var trigger_cmd   = $('',
      {id    : 'trigger_jg_' + this.id,
       class : 'trigger_jg details_command',
       text  : 'trigger'});
    trigger_cmd.data('jump_gate', this);

    var _this = this;
    trigger_cmd.click(function(){ _this._trigger(page); });

    /// exclude trigger_cmd if page.session is null
    var details_text = title + '
' + loc + '

';
    var details = page.session ? [details_text, trigger_cmd] : [details_text];
    details_cb(details);
  },

  selected : function(page){
    var _this = this;
    page.canvas.reload(this, function(){
      if($.inArray(_this.selection_sphere, _this.components) == -1)
        _this.components.push(_this.selection_sphere);
    });
  },

  unselected : function(page){
    var _this = this;
    page.canvas.reload(this, function(){
      var index;
      if((index = $.inArray(_this.selection_sphere, _this.components)) != -1)
        _this.components.splice(index, 1);
    });
  },

  // XXX not a big fan of having this here, should eventually be moved elsewhere
  dialog : function(){
    if(typeof(this._dialog) === "undefined")
      this._dialog = new Omega.UI.CommandDialog();
    return this._dialog;
  },

  _trigger : function(page){
    var _this = this;
    var ships = $.grep(page.all_entities(), function(e){
                  return _this._should_trigger_ship(e, page);
                });

    for(var s = 0; s < ships.length; s++){
      var ship = ships[s];
      (function(ship){ /// XXX need new scope to preserve ship
        /// XXX make sure endpoint is set! (won't come in w/ server jg)
        ship.location.parent_id = _this.endpoint.location.id;
        page.node.http_invoke('manufactured::move_entity', ship.id, ship.location,
          function(response){
            if(response.error){
              _this.dialog().title = 'Jump Gate Trigger Error';
              _this.dialog().show_error_dialog();
              _this.dialog().append_error(response.error.message);

            }else{
              ship.system_id = _this.endpoint_id;
              page.canvas.remove(ship);
            }
          });
       })(ship);
    }
  },

  _should_trigger_ship : function(entity, page){
    return entity.json_class == 'Manufactured::Ship' &&
           entity.belongs_to_user(page.session.user_id) &&
           entity.location.is_within(this.trigger_distance,
                                     this.location);
  },

  gfx_props : {
    particle_plane :  20,
    particle_life  : 200,
    lamp_x         : -22,
    lamp_y         : -17,
    lamp_z         : 175,
  },

  async_gfx : 3,

  load_gfx : function(config, event_cb){
    if(typeof(Omega.JumpGate.gfx) !== 'undefined') return;
    Omega.JumpGate.gfx = {};

    //// mesh
      var texture_path    = config.url_prefix + config.images_path + config.resources.jump_gate.material;
      var geometry_path   = config.url_prefix + config.images_path + config.resources.jump_gate.geometry;
      var geometry_prefix = config.url_prefix + config.images_path + config.meshes_path;
      var rotation        = config.resources.jump_gate.rotation;
      var offset          = config.resources.jump_gate.offset;
      var scale           = config.resources.jump_gate.scale;

      var texture         = THREE.ImageUtils.loadTexture(texture_path, {}, event_cb);
      texture.wrapS       = texture.wrapT    = THREE.RepeatWrapping;
      texture.repeat.x    = texture.repeat.y = 5;
      var mesh_material   = new THREE.MeshLambertMaterial({ map: texture });

      Omega.UI.Loader.json().load(geometry_path, function(mesh_geometry){
        var mesh = new THREE.Mesh(mesh_geometry, mesh_material);
        Omega.JumpGate.gfx.mesh = mesh;
        if(offset)
          mesh.position.set(offset[0], offset[1], offset[2]);
        if(scale)
          mesh.scale.set(scale[0], scale[1], scale[2]);
        if(rotation){
          mesh.rotation.set(rotation[0], rotation[1], rotation[2]);
          mesh.matrix.makeRotationFromEuler(mesh.rotation);
        }
        Omega.JumpGate.prototype.loaded_resource('template_mesh', mesh);
        if(event_cb) event_cb();
      }, geometry_prefix);

    //// lamp
      Omega.JumpGate.gfx.lamp = Omega.create_lamp(10, 0xff0000);

    //// particles
      var particle_path = config.url_prefix + config.images_path + "/particle.png";
      var texture       = THREE.ImageUtils.loadTexture(particle_path, {}, event_cb);
      var lifespan      = this.gfx_props.particle_life,
          plane         = this.gfx_props.particle_plane;
      var particles_material =
        new THREE.ParticleBasicMaterial({
          color: 0x0000FF, size        : 20,
          map  : texture,  transparent : true,
          blending: THREE.AdditiveBlending
        });

      var particles = new THREE.Geometry();
      for(var i = 0; i < plane; ++i){
        for(var j = 0; j < plane; ++j){
          var pv = new THREE.Vector3(i, j, 0);
          pv.velocity = Math.random();
          pv.lifespan = lifespan;
          pv.moving = false;
          particles.vertices.push(pv)
        }
      }

      var particle_system = new THREE.ParticleSystem(particles, particles_material);
      particle_system.sortParticles = true;
      Omega.JumpGate.gfx.particles = particle_system;

    //// selection sphere
      Omega.JumpGate.gfx.selection_sphere_material =
        new THREE.MeshBasicMaterial({color       : 0xffffff,
                                     transparent : true,
                                     opacity     : 0.1});
  },

  init_gfx : function(config, event_cb){
    if(this.components.length > 0) return; /// return if already initialized
    this.load_gfx(config, event_cb);

    this.components = [];

    var _this = this;
    Omega.JumpGate.prototype.retrieve_resource('template_mesh', function(template_mesh){
      _this.mesh = template_mesh.clone();
      if(_this.location)
        _this.mesh.position.add(new THREE.Vector3(_this.location.x,
                                                  _this.location.y,
                                                  _this.location.z));
      _this.mesh.omega_entity = _this;
      _this.components.push(_this.mesh);
      _this.loaded_resource('mesh', _this.mesh);
    });

    var lamp_offset = [this.gfx_props.lamp_x,
                       this.gfx_props.lamp_y,
                       this.gfx_props.lamp_z];
    this.lamp = Omega.JumpGate.gfx.lamp.clone();
    this.lamp.run_effects = Omega.JumpGate.gfx.lamp.run_effects; /// XXX
    if(this.location)
      this.lamp.position.set(this.location.x + lamp_offset[0],
                             this.location.y + lamp_offset[1],
                             this.location.z + lamp_offset[2]);

    this.particles = Omega.JumpGate.gfx.particles.clone();
    if(this.location) this.particles.position.set(this.location.x - 30,
                                                  this.location.y - 25,
                                                  this.location.z + 75);

    var segments = 32, rings = 32,
        material = Omega.JumpGate.gfx.selection_sphere_material;
    var geometry =
      new THREE.SphereGeometry(this.trigger_distance/2, segments, rings);
    this.selection_sphere = new THREE.Mesh(geometry, material);
    if(this.location) this.selection_sphere.position.set(this.location.x - 20,
                                                         this.location.y,
                                                         this.location.z)

    this.components.push(this.lamp);
    this.components.push(this.particles);
  },

  run_effects : function(){
    /// update lamp
    this.lamp.run_effects();

    /// update particles
    var plane    = this.gfx_props.particle_plane,
        lifespan = this.gfx_props.particle_life;

    var p = plane*plane;
    var not_moving = [];
    while(p--){
      var pv = this.particles.geometry.vertices[p]
      if(pv.moving){
        pv.z -= pv.velocity;
        pv.lifespan -= 1;
        if(pv.lifespan < 0){
          pv.z = 0;
          pv.lifespan = 200;
          pv.moving = false;
        }
      }else{
        not_moving.push(pv);
      }
    }
    /// pick random particle to start moving
    var index = Math.floor(Math.random()*(not_moving.length-1));
    if(index != -1) not_moving[index].moving = true;
    this.particles.geometry.__dirtyVertices = true;
  }
};

Omega.UI.ResourceLoader.prototype.apply(Omega.JumpGate.prototype);
<commit_msg>Small ui fix: store jg trigger distance in json data<commit_after>/* Omega JumpGate JS Representation
 *
 * Copyright (C) 2013 Mohammed Morsi <mo@morsi.org>
 *  Licensed under the AGPLv3+ http://www.gnu.org/licenses/agpl.txt
 */

//= require "ui/command"

Omega.JumpGate = function(parameters){
  this.components = [];
  this.shader_components = [];
  $.extend(this, parameters);

  this.location = Omega.convert_entity(this.location)
};

Omega.JumpGate.prototype = {
  constructor : Omega.JumpGate,
  json_class : 'Cosmos::Entities::JumpGate',

  toJSON : function(){
    return {json_class  : this.json_class,
            id          : this.id,
            name        : this.name,
            location    : this.location ? this.location.toJSON() : null,
            parent_id   : this.parent_id,
            endpoint_id : this.endpoint_id,
            trigger_distance : this.trigger_distance};
  },

  has_details : true,

  retrieve_details : function(page, details_cb){
    var title = 'Jump Gate to ' + this.endpoint_id;
    var loc   = '@ ' + this.location.to_s();
    var trigger_cmd   = $('',
      {id    : 'trigger_jg_' + this.id,
       class : 'trigger_jg details_command',
       text  : 'trigger'});
    trigger_cmd.data('jump_gate', this);

    var _this = this;
    trigger_cmd.click(function(){ _this._trigger(page); });

    /// exclude trigger_cmd if page.session is null
    var details_text = title + '
' + loc + '

';
    var details = page.session ? [details_text, trigger_cmd] : [details_text];
    details_cb(details);
  },

  selected : function(page){
    var _this = this;
    page.canvas.reload(this, function(){
      if($.inArray(_this.selection_sphere, _this.components) == -1)
        _this.components.push(_this.selection_sphere);
    });
  },

  unselected : function(page){
    var _this = this;
    page.canvas.reload(this, function(){
      var index;
      if((index = $.inArray(_this.selection_sphere, _this.components)) != -1)
        _this.components.splice(index, 1);
    });
  },

  // XXX not a big fan of having this here, should eventually be moved elsewhere
  dialog : function(){
    if(typeof(this._dialog) === "undefined")
      this._dialog = new Omega.UI.CommandDialog();
    return this._dialog;
  },

  _trigger : function(page){
    var _this = this;
    var ships = $.grep(page.all_entities(), function(e){
                  return _this._should_trigger_ship(e, page);
                });

    for(var s = 0; s < ships.length; s++){
      var ship = ships[s];
      (function(ship){ /// XXX need new scope to preserve ship
        /// XXX make sure endpoint is set! (won't come in w/ server jg)
        ship.location.parent_id = _this.endpoint.location.id;
        page.node.http_invoke('manufactured::move_entity', ship.id, ship.location,
          function(response){
            if(response.error){
              _this.dialog().title = 'Jump Gate Trigger Error';
              _this.dialog().show_error_dialog();
              _this.dialog().append_error(response.error.message);

            }else{
              ship.system_id = _this.endpoint_id;
              page.canvas.remove(ship);
            }
          });
       })(ship);
    }
  },

  _should_trigger_ship : function(entity, page){
    return entity.json_class == 'Manufactured::Ship' &&
           entity.belongs_to_user(page.session.user_id) &&
           entity.location.is_within(this.trigger_distance,
                                     this.location);
  },

  gfx_props : {
    particle_plane :  20,
    particle_life  : 200,
    lamp_x         : -22,
    lamp_y         : -17,
    lamp_z         : 175,
  },

  async_gfx : 3,

  load_gfx : function(config, event_cb){
    if(typeof(Omega.JumpGate.gfx) !== 'undefined') return;
    Omega.JumpGate.gfx = {};

    //// mesh
      var texture_path    = config.url_prefix + config.images_path + config.resources.jump_gate.material;
      var geometry_path   = config.url_prefix + config.images_path + config.resources.jump_gate.geometry;
      var geometry_prefix = config.url_prefix + config.images_path + config.meshes_path;
      var rotation        = config.resources.jump_gate.rotation;
      var offset          = config.resources.jump_gate.offset;
      var scale           = config.resources.jump_gate.scale;

      var texture         = THREE.ImageUtils.loadTexture(texture_path, {}, event_cb);
      texture.wrapS       = texture.wrapT    = THREE.RepeatWrapping;
      texture.repeat.x    = texture.repeat.y = 5;
      var mesh_material   = new THREE.MeshLambertMaterial({ map: texture });

      Omega.UI.Loader.json().load(geometry_path, function(mesh_geometry){
        var mesh = new THREE.Mesh(mesh_geometry, mesh_material);
        Omega.JumpGate.gfx.mesh = mesh;
        if(offset)
          mesh.position.set(offset[0], offset[1], offset[2]);
        if(scale)
          mesh.scale.set(scale[0], scale[1], scale[2]);
        if(rotation){
          mesh.rotation.set(rotation[0], rotation[1], rotation[2]);
          mesh.matrix.makeRotationFromEuler(mesh.rotation);
        }
        Omega.JumpGate.prototype.loaded_resource('template_mesh', mesh);
        if(event_cb) event_cb();
      }, geometry_prefix);

    //// lamp
      Omega.JumpGate.gfx.lamp = Omega.create_lamp(10, 0xff0000);

    //// particles
      var particle_path = config.url_prefix + config.images_path + "/particle.png";
      var texture       = THREE.ImageUtils.loadTexture(particle_path, {}, event_cb);
      var lifespan      = this.gfx_props.particle_life,
          plane         = this.gfx_props.particle_plane;
      var particles_material =
        new THREE.ParticleBasicMaterial({
          color: 0x0000FF, size        : 20,
          map  : texture,  transparent : true,
          blending: THREE.AdditiveBlending
        });

      var particles = new THREE.Geometry();
      for(var i = 0; i < plane; ++i){
        for(var j = 0; j < plane; ++j){
          var pv = new THREE.Vector3(i, j, 0);
          pv.velocity = Math.random();
          pv.lifespan = lifespan;
          pv.moving = false;
          particles.vertices.push(pv)
        }
      }

      var particle_system = new THREE.ParticleSystem(particles, particles_material);
      particle_system.sortParticles = true;
      Omega.JumpGate.gfx.particles = particle_system;

    //// selection sphere
      Omega.JumpGate.gfx.selection_sphere_material =
        new THREE.MeshBasicMaterial({color       : 0xffffff,
                                     transparent : true,
                                     opacity     : 0.1});
  },

  init_gfx : function(config, event_cb){
    if(this.components.length > 0) return; /// return if already initialized
    this.load_gfx(config, event_cb);

    this.components = [];

    var _this = this;
    Omega.JumpGate.prototype.retrieve_resource('template_mesh', function(template_mesh){
      _this.mesh = template_mesh.clone();
      if(_this.location)
        _this.mesh.position.add(new THREE.Vector3(_this.location.x,
                                                  _this.location.y,
                                                  _this.location.z));
      _this.mesh.omega_entity = _this;
      _this.components.push(_this.mesh);
      _this.loaded_resource('mesh', _this.mesh);
    });

    var lamp_offset = [this.gfx_props.lamp_x,
                       this.gfx_props.lamp_y,
                       this.gfx_props.lamp_z];
    this.lamp = Omega.JumpGate.gfx.lamp.clone();
    this.lamp.run_effects = Omega.JumpGate.gfx.lamp.run_effects; /// XXX
    if(this.location)
      this.lamp.position.set(this.location.x + lamp_offset[0],
                             this.location.y + lamp_offset[1],
                             this.location.z + lamp_offset[2]);

    this.particles = Omega.JumpGate.gfx.particles.clone();
    if(this.location) this.particles.position.set(this.location.x - 30,
                                                  this.location.y - 25,
                                                  this.location.z + 75);

    var segments = 32, rings = 32,
        material = Omega.JumpGate.gfx.selection_sphere_material;
    var geometry =
      new THREE.SphereGeometry(this.trigger_distance/2, segments, rings);
    this.selection_sphere = new THREE.Mesh(geometry, material);
    if(this.location) this.selection_sphere.position.set(this.location.x - 20,
                                                         this.location.y,
                                                         this.location.z)

    this.components.push(this.lamp);
    this.components.push(this.particles);
  },

  run_effects : function(){
    /// update lamp
    this.lamp.run_effects();

    /// update particles
    var plane    = this.gfx_props.particle_plane,
        lifespan = this.gfx_props.particle_life;

    var p = plane*plane;
    var not_moving = [];
    while(p--){
      var pv = this.particles.geometry.vertices[p]
      if(pv.moving){
        pv.z -= pv.velocity;
        pv.lifespan -= 1;
        if(pv.lifespan < 0){
          pv.z = 0;
          pv.lifespan = 200;
          pv.moving = false;
        }
      }else{
        not_moving.push(pv);
      }
    }
    /// pick random particle to start moving
    var index = Math.floor(Math.random()*(not_moving.length-1));
    if(index != -1) not_moving[index].moving = true;
    this.particles.geometry.__dirtyVertices = true;
  }
};

Omega.UI.ResourceLoader.prototype.apply(Omega.JumpGate.prototype);
<|endoftext|>


<commit_before>Hammer.utils = {
  /**
   * extend method,
   * also used for cloning when dest is an empty object
   * @param   {Object}    dest
   * @param   {Object}    src
   * @parm  {Boolean}  merge    do a merge
   * @returns {Object}    dest
   */
  extend: function extend(dest, src, merge) {
    for(var key in src) {
      if(dest[key] !== undefined && merge) {
        continue;
      }
      dest[key] = src[key];
    }
    return dest;
  },

  /**
   * for each
   * @param obj
   * @param iterator
   */
  each: function(obj, iterator, context) {
    var i, length;
    // native forEach on arrays
    if ('forEach' in obj) {
      obj.forEach(iterator, context);
    }
    // arrays
    else if(obj.length !== undefined) {
      for (i = 0, length = obj.length; i < length; i++) {
        if (iterator.call(context, obj[i], i, obj) === false) {
          return;
        }
      }
    }
    // objects
    else {
      for (i in obj) {
        if (obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj) === false) {
          return;
        }
      }
    }
  },

  /**
   * find if a node is in the given parent
   * used for event delegation tricks
   * @param   {HTMLElement}   node
   * @param   {HTMLElement}   parent
   * @returns {boolean}       has_parent
   */
  hasParent: function(node, parent) {
    while(node) {
      if(node == parent) {
        return true;
      }
      node = node.parentNode;
    }
    return false;
  },

  /**
   * get the center of all the touches
   * @param   {Array}     touches
   * @returns {Object}    center
   */
  getCenter: function getCenter(touches) {
    var valuesX = [], valuesY = [];

    Hammer.utils.each(touches, function(touch) {
      // I prefer clientX because it ignore the scrolling position
      valuesX.push(typeof touch.clientX !== 'undefined' ? touch.clientX : touch.pageX );
      valuesY.push(typeof touch.clientY !== 'undefined' ? touch.clientY : touch.pageY );
    });

    return {
      pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
      pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
    };
  },

  /**
   * calculate the velocity between two points
   * @param   {Number}    delta_time
   * @param   {Number}    delta_x
   * @param   {Number}    delta_y
   * @returns {Object}    velocity
   */
  getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
    return {
      x: Math.abs(delta_x / delta_time) || 0,
      y: Math.abs(delta_y / delta_time) || 0
    };
  },

  /**
   * calculate the angle between two coordinates
   * @param   {Touch}     touch1
   * @param   {Touch}     touch2
   * @returns {Number}    angle
   */
  getAngle: function getAngle(touch1, touch2) {
    var y = touch2.pageY - touch1.pageY,
      x = touch2.pageX - touch1.pageX;
    return Math.atan2(y, x) * 180 / Math.PI;
  },

  /**
   * angle to direction define
   * @param   {Touch}     touch1
   * @param   {Touch}     touch2
   * @returns {String}    direction constant, like Hammer.DIRECTION_LEFT
   */
  getDirection: function getDirection(touch1, touch2) {
    var x = Math.abs(touch1.pageX - touch2.pageX),
      y = Math.abs(touch1.pageY - touch2.pageY);

    if(x >= y) {
      return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
    }
    else {
      return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
    }
  },

  /**
   * calculate the distance between two touches
   * @param   {Touch}     touch1
   * @param   {Touch}     touch2
   * @returns {Number}    distance
   */
  getDistance: function getDistance(touch1, touch2) {
    var x = touch2.pageX - touch1.pageX,
      y = touch2.pageY - touch1.pageY;
    return Math.sqrt((x * x) + (y * y));
  },

  /**
   * calculate the scale factor between two touchLists (fingers)
   * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
   * @param   {Array}     start
   * @param   {Array}     end
   * @returns {Number}    scale
   */
  getScale: function getScale(start, end) {
    // need two fingers...
    if(start.length >= 2 && end.length >= 2) {
      return this.getDistance(end[0], end[1]) /
        this.getDistance(start[0], start[1]);
    }
    return 1;
  },

  /**
   * calculate the rotation degrees between two touchLists (fingers)
   * @param   {Array}     start
   * @param   {Array}     end
   * @returns {Number}    rotation
   */
  getRotation: function getRotation(start, end) {
    // need two fingers
    if(start.length >= 2 && end.length >= 2) {
      return this.getAngle(end[1], end[0]) -
        this.getAngle(start[1], start[0]);
    }
    return 0;
  },

  /**
   * boolean if the direction is vertical
   * @param    {String}    direction
   * @returns  {Boolean}   is_vertical
   */
  isVertical: function isVertical(direction) {
    return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  },

  /**
   * stop browser default behavior with css props
   * @param   {HtmlElement}   element
   * @param   {Object}        css_props
   */
  stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
    if(!css_props || !element || !element.style) {
      return;
    }

    // with css properties for modern browsers
    Hammer.utils.each(['webkit', 'khtml', 'moz', 'Moz', 'ms', 'o', ''], function(vendor) {
      Hammer.utils.each(css_props, function(prop) {
          // vender prefix at the property
          if(vendor) {
            prop = vendor + prop.substring(0, 1).toUpperCase() + prop.substring(1);
          }
          // set the style
          if(prop in element.style) {
            element.style[prop] = prop;
          }
      });
    });

    // also the disable onselectstart
    if(css_props.userSelect == 'none') {
      element.onselectstart = function() {
        return false;
      };
    }

    // and disable ondragstart
    if(css_props.userDrag == 'none') {
      element.ondragstart = function() {
        return false;
      };
    }
  }
};
<commit_msg>fix wrong usage of each on object<commit_after>Hammer.utils = {
  /**
   * extend method,
   * also used for cloning when dest is an empty object
   * @param   {Object}    dest
   * @param   {Object}    src
   * @parm  {Boolean}  merge    do a merge
   * @returns {Object}    dest
   */
  extend: function extend(dest, src, merge) {
    for(var key in src) {
      if(dest[key] !== undefined && merge) {
        continue;
      }
      dest[key] = src[key];
    }
    return dest;
  },

  /**
   * for each
   * @param obj
   * @param iterator
   */
  each: function(obj, iterator, context) {
    var i, length;
    // native forEach on arrays
    if ('forEach' in obj) {
      obj.forEach(iterator, context);
    }
    // arrays
    else if(obj.length !== undefined) {
      for (i = 0, length = obj.length; i < length; i++) {
        if (iterator.call(context, obj[i], i, obj) === false) {
          return;
        }
      }
    }
    // objects
    else {
      for (i in obj) {
        if (obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj) === false) {
          return;
        }
      }
    }
  },

  /**
   * find if a node is in the given parent
   * used for event delegation tricks
   * @param   {HTMLElement}   node
   * @param   {HTMLElement}   parent
   * @returns {boolean}       has_parent
   */
  hasParent: function(node, parent) {
    while(node) {
      if(node == parent) {
        return true;
      }
      node = node.parentNode;
    }
    return false;
  },

  /**
   * get the center of all the touches
   * @param   {Array}     touches
   * @returns {Object}    center
   */
  getCenter: function getCenter(touches) {
    var valuesX = [], valuesY = [];

    Hammer.utils.each(touches, function(touch) {
      // I prefer clientX because it ignore the scrolling position
      valuesX.push(typeof touch.clientX !== 'undefined' ? touch.clientX : touch.pageX );
      valuesY.push(typeof touch.clientY !== 'undefined' ? touch.clientY : touch.pageY );
    });

    return {
      pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
      pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
    };
  },

  /**
   * calculate the velocity between two points
   * @param   {Number}    delta_time
   * @param   {Number}    delta_x
   * @param   {Number}    delta_y
   * @returns {Object}    velocity
   */
  getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
    return {
      x: Math.abs(delta_x / delta_time) || 0,
      y: Math.abs(delta_y / delta_time) || 0
    };
  },

  /**
   * calculate the angle between two coordinates
   * @param   {Touch}     touch1
   * @param   {Touch}     touch2
   * @returns {Number}    angle
   */
  getAngle: function getAngle(touch1, touch2) {
    var y = touch2.pageY - touch1.pageY,
      x = touch2.pageX - touch1.pageX;
    return Math.atan2(y, x) * 180 / Math.PI;
  },

  /**
   * angle to direction define
   * @param   {Touch}     touch1
   * @param   {Touch}     touch2
   * @returns {String}    direction constant, like Hammer.DIRECTION_LEFT
   */
  getDirection: function getDirection(touch1, touch2) {
    var x = Math.abs(touch1.pageX - touch2.pageX),
      y = Math.abs(touch1.pageY - touch2.pageY);

    if(x >= y) {
      return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
    }
    else {
      return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
    }
  },

  /**
   * calculate the distance between two touches
   * @param   {Touch}     touch1
   * @param   {Touch}     touch2
   * @returns {Number}    distance
   */
  getDistance: function getDistance(touch1, touch2) {
    var x = touch2.pageX - touch1.pageX,
      y = touch2.pageY - touch1.pageY;
    return Math.sqrt((x * x) + (y * y));
  },

  /**
   * calculate the scale factor between two touchLists (fingers)
   * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
   * @param   {Array}     start
   * @param   {Array}     end
   * @returns {Number}    scale
   */
  getScale: function getScale(start, end) {
    // need two fingers...
    if(start.length >= 2 && end.length >= 2) {
      return this.getDistance(end[0], end[1]) /
        this.getDistance(start[0], start[1]);
    }
    return 1;
  },

  /**
   * calculate the rotation degrees between two touchLists (fingers)
   * @param   {Array}     start
   * @param   {Array}     end
   * @returns {Number}    rotation
   */
  getRotation: function getRotation(start, end) {
    // need two fingers
    if(start.length >= 2 && end.length >= 2) {
      return this.getAngle(end[1], end[0]) -
        this.getAngle(start[1], start[0]);
    }
    return 0;
  },

  /**
   * boolean if the direction is vertical
   * @param    {String}    direction
   * @returns  {Boolean}   is_vertical
   */
  isVertical: function isVertical(direction) {
    return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  },

  /**
   * stop browser default behavior with css props
   * @param   {HtmlElement}   element
   * @param   {Object}        css_props
   */
  stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
    if(!css_props || !element || !element.style) {
      return;
    }

    // with css properties for modern browsers
    Hammer.utils.each(['webkit', 'khtml', 'moz', 'Moz', 'ms', 'o', ''], function(vendor) {
      Hammer.utils.each(css_props, function(value, prop) {
          // vender prefix at the property
          if(vendor) {
            prop = vendor + prop.substring(0, 1).toUpperCase() + prop.substring(1);
          }
          // set the style
          if(prop in element.style) {
            element.style[prop] = value;
          }
      });
    });

    // also the disable onselectstart
    if(css_props.userSelect == 'none') {
      element.onselectstart = function() {
        return false;
      };
    }

    // and disable ondragstart
    if(css_props.userDrag == 'none') {
      element.ondragstart = function() {
        return false;
      };
    }
  }
};
<|endoftext|>


<commit_before>import * as firebase from 'firebase';
import router from 'app';

export default class User {

    static currentUser() {
        return {
            email: firebase.auth().currentUser.email,
            uid: firebase.auth().currentUser.uid
        }
    }

    static registerUser(email, password, onSuccess, onError) {
        firebase.auth().createUserWithEmailAndPassword(email, password)
            .catch(function (error) {
                var errorCode = error.code;
                var errorMessage = error.message;

                if (onError) {
                    onError(error);
                } else {
                    if (errorCode == 'auth/weak-password') {
                        alert('The password is too weak.');
                    } else {
                        alert(errorMessage);
                    }
                }
            })
            .then(() => {
                firebase.auth().signInWithEmailAndPassword(email, password);
                if (onSuccess) {
                    onSuccess();

                }
            });
    }

    static initAuthStatusChange() {
        firebase.auth().onAuthStateChanged(function (user) {
            $('#verify-btn').addClass('hidden');
            if (user) {
                var email = user.email;
                var emailVerified = user.emailVerified;
                $('#sign-in-status').text(`Signed in with ${email}`);
                $('#register-btn').addClass('hidden');
                $('#sign-in-btn').text('Sign out');
                if (!emailVerified) {
                    $('#verify-btn').removeClass('hidden');
                    $('#verify-btn').click(User.verifyAcocunt);
                }
                router.navigate('user/' + User.currentUser().email.split('@')[0]);
            } else {
                $('#sign-in-status').text('Signed out');
                $('#sign-in-btn').text('Sign in');
                $('#register-btn').removeClass('hidden');
            }
        });
    }

    static verifyAcocunt() {
        firebase.auth().currentUser.sendEmailVerification()
            .then(() => alert(`Verification e-mail sent to ${User.currentUser().email}`))
            .catch(() => alert('Something went wrong. Please try again!'));
    }

    static signOut() {
        firebase.auth().signOut()
            .catch(() => alert('Something went wrong. Please try again!'));
    }

    static signIn(email, password, onSuccess, onError) {
        firebase.auth().signInWithEmailAndPassword(email, password)
            .catch(error => {
                if (onError) {
                    onError(error);
                } else {
                    var errorCode = error.code;
                    var errorMessage = error.message;
                    if (errorCode === 'auth/wrong-password') {
                        alert('Wrong password.');
                    } else {
                        alert(errorMessage);
                    }
                }
            })
            .then(() => {
                if (onSuccess) {
                    onSuccess();
                }
            });
    }
}<commit_msg>final fix<commit_after>import * as firebase from 'firebase';
import router from 'app';

export default class User {

    static currentUser() {
        return {
            email: firebase.auth().currentUser.email,
            uid: firebase.auth().currentUser.uid
        }
    }

    static registerUser(email, password, onSuccess, onError) {
        firebase.auth().createUserWithEmailAndPassword(email, password)
            .catch(function (error) {
                var errorCode = error.code;
                var errorMessage = error.message;

                if (onError) {
                    onError(error);
                } else {
                    if (errorCode == 'auth/weak-password') {
                        alert('The password is too weak.');
                    } else {
                        alert(errorMessage);
                    }
                }
            })
            .then(() => {
                firebase.auth().signInWithEmailAndPassword(email, password);
                if (onSuccess) {
                    onSuccess();

                }
            });
    }

    static initAuthStatusChange() {
        firebase.auth().onAuthStateChanged(function (user) {
            $('#verify-btn').addClass('hidden');
            if (user) {
                var email = user.email;
                var emailVerified = user.emailVerified;
                $('#sign-in-status').text(`Signed in with ${email}`);
                $('#register-btn').addClass('hidden');
                $('#sign-in-btn').text('Sign out');
                if (!emailVerified) {
                    $('#verify-btn').removeClass('hidden');
                    $('#verify-btn').click(User.verifyAcocunt);
                }
                router.navigate('#/user/' + User.currentUser().email.split('@')[0]);
            } else {
                $('#sign-in-status').text('Signed out');
                $('#sign-in-btn').text('Sign in');
                $('#register-btn').removeClass('hidden');
            }
        });
    }

    static verifyAcocunt() {
        firebase.auth().currentUser.sendEmailVerification()
            .then(() => alert(`Verification e-mail sent to ${User.currentUser().email}`))
            .catch(() => alert('Something went wrong. Please try again!'));
    }

    static signOut() {
        firebase.auth().signOut()
            .catch(() => alert('Something went wrong. Please try again!'));
    }

    static signIn(email, password, onSuccess, onError) {
        firebase.auth().signInWithEmailAndPassword(email, password)
            .catch(error => {
                if (onError) {
                    onError(error);
                } else {
                    var errorCode = error.code;
                    var errorMessage = error.message;
                    if (errorCode === 'auth/wrong-password') {
                        alert('Wrong password.');
                    } else {
                        alert(errorMessage);
                    }
                }
            })
            .then(() => {
                if (onSuccess) {
                    onSuccess();
                }
            });
    }
}<|endoftext|>


<commit_before>function noop() {}

function isFn(t) {
  return typeof t === 'function' ? t : void 0
}

const strProto = Object.getPrototypeOf('')
function isStr(s) {
  return Object.getPrototypeOf(Object(s)) === strProto
}

function empty(t) {
  return !t || (!t.length && !Object.keys(t).length)
}

export { noop, isFn, isStr, empty }

const invokeFn = Function.prototype.call.bind(Function.prototype.call)

function pipe(...fns) {
  function invoke(v) {
    return fns.reduce((acc, fn) => (fn ? fn.call(this, acc) : acc), v)
  }
  return invoke
}

const m2f = (mKey, fn) => fn && (arr => Array.prototype[mKey].call(arr, fn))

const flattenToObj = (arr, base = {}) => Object.assign(base, ...arr)
const pipeOverKeys = (obj, ...fns) => obj && pipe(...fns)(Object.keys(obj))
const mapOverKeys = (obj, mapper) => pipeOverKeys(obj, m2f('map', mapper))

const hasOwn = Object.prototype.hasOwnProperty

function shieldProps(t, ...keys) {
  let keep = flattenToObj(Object.keys(t).filter(k => !keys.includes(k)).map(k => ({ [k]: t[k] })))
  return Object.setPrototypeOf(keep, t)
}

function substitute(literals, values, removeEmpty) {
  if (removeEmpty && literals.length > values.length) {
    values = Array.from(values)
    literals = Array.from(literals)
    literals = [literals[0], ...literals.slice(1).map((l, i) => l || (values[i] = ''))]
  }
  return String.raw({ raw: literals }, ...values)
}

function escapeRx(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}

export { invokeFn, pipe, flattenToObj, mapOverKeys, hasOwn, shieldProps, substitute, escapeRx }
<commit_msg>convert falsy to empty by default in substitute<commit_after>function noop() {}

function isFn(t) {
  return typeof t === 'function' ? t : void 0
}

const strProto = Object.getPrototypeOf('')
function isStr(s) {
  return Object.getPrototypeOf(Object(s)) === strProto
}

function empty(t) {
  return !t || (!t.length && !Object.keys(t).length)
}

export { noop, isFn, isStr, empty }

const invokeFn = Function.prototype.call.bind(Function.prototype.call)

function pipe(...fns) {
  function invoke(v) {
    return fns.reduce((acc, fn) => (fn ? fn.call(this, acc) : acc), v)
  }
  return invoke
}

const m2f = (mKey, fn) => fn && (arr => Array.prototype[mKey].call(arr, fn))

const flattenToObj = (arr, base = {}) => Object.assign(base, ...arr)
const pipeOverKeys = (obj, ...fns) => obj && pipe(...fns)(Object.keys(obj))
const mapOverKeys = (obj, mapper) => pipeOverKeys(obj, m2f('map', mapper))

const hasOwn = Object.prototype.hasOwnProperty

function shieldProps(t, ...keys) {
  let keep = flattenToObj(Object.keys(t).filter(k => !keys.includes(k)).map(k => ({ [k]: t[k] })))
  return Object.setPrototypeOf(keep, t)
}

function substitute(literals, values, removeEmpty) {
  let falsyToEmpty = v => v || ''
  values = Array.from(values, falsyToEmpty)
  literals = Array.from(literals, falsyToEmpty)
  if (removeEmpty && literals.length > values.length) {
    literals = Array.from(literals, (l, i) => (i === 0 || l ? l : (values[i] = l)))
  }
  return String.raw({ raw: literals }, ...values)
}

function escapeRx(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}

export { invokeFn, pipe, flattenToObj, mapOverKeys, hasOwn, shieldProps, substitute, escapeRx }
<|endoftext|>


<commit_before>/****************************************************
 *
 * CKEditor Extension
 *
 * Written by Larix Kortbeek for Grrr
 *
 *****************************************************/
Ext.form.CKEditor = function(config) {
    this.config = config;

    config.CKEditor = {
        // Allow only these tags (=true for all of them)
        allowedContent: true,

        format_tags: 'p;h2;h3',

        // Available buttons
        toolbar: [
            ['Bold', 'Italic', '-', 'RemoveFormat'],
            ['Link', 'Unlink'],
            ['NumberedList','BulletedList', 'Format'],
            ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo', '-', 'Source']
        ],

        // Disable CKEditor's own image plugin
        removePlugins: 'image'
    };

    // Load the site's own styling
    if (window.WYSIWYG_CSS_URL) {
        config.CKEditor.contentsCss = window.WYSIWYG_CSS_URL;
    }

    // Load the garp content plugins for richwyswig editor types
    if (config.rich) {
        // Always load the images picker
        var extraPlugins = "garpimages";
        var richButtons = ["Garpimage"];

        // Only load the video picker when a VIDEO_WIDTH template is defined
        if (VIDEO_WIDTH) {
            extraPlugins += ",garpvideos";
            richButtons.push("Garpvideo");
        }

        config.CKEditor.height = "400px";

        // Let the editor know
        config.CKEditor.extraPlugins = extraPlugins;
        config.CKEditor.toolbar.push(richButtons);
    }

    // Attach to Ext
    Ext.form.CKEditor.superclass.constructor.call(this, config);
};

Ext.extend(Ext.form.CKEditor, Ext.form.TextArea, {
    onRender: function(ct, position) {
        Ext.form.CKEditor.superclass.onRender.call(this, ct, position);

        this.editor = CKEDITOR.replace(this.id, this.config.CKEditor);

        // Closure for quick access in the event listener
        var that = this;
        this.editor.on('dataReady', function() {
            this.resetDirty();
            that.waitingForSetData = false;
        });
        this.setValue(this.orgValue);
    },

    setValue: function(value) {
        // Save the value as the elements original value
        this.orgValue = value;

        // Wait for an editor (the setValue function will be called on render)
        if (!this.editor) {
            return;
        }
        // Convert undefineds and nulls to empty string
        value = value || "";

        // Working around CKEditor's crazy-assync setData
        // (When setting data twice in short succession only the first data gets set)
        var that = this;

        function retrySetValue(event) {
            that.setValue(that.orgValue);
            that.waitingForSetData = false;
            event.removeListener();
        }
        if (this.waitingForSetData) {
            this.editor.on('dataReady', retrySetValue);
        }
        this.waitingForSetData = true;

        // Set CKEditor's content
        this.editor.setData(value);
    },

    getValue: function() {
        var val = this.orgValue;

        // If an editor is available and content has changed
        if (this.editor && this.editor.checkDirty()) {
            val = this.editor.getData();
        }

        // Convert falsy values to the empty string
        return val || "";
    },

    getRawValue: function() {
        return this.getValue();
    }
});

// Define "Rich CKEditor" (which allows for some more options such as image and video embeds)
Ext.form.RichCKEditor = function(config) {
    config.rich = true;
    Ext.form.RichCKEditor.superclass.constructor.call(this, config);
};
Ext.extend(Ext.form.RichCKEditor, Ext.form.CKEditor);

// Enable the CKEditor as default richtexteditor
Ext.reg('wysiwygeditor', Ext.form.CKEditor);
Ext.reg('richwysiwygeditor', Ext.form.RichCKEditor);
<commit_msg>Added styling for fckeditor<commit_after>/****************************************************
 *
 * CKEditor Extension
 *
 * Written by Larix Kortbeek for Grrr
 *
 *****************************************************/
Ext.form.CKEditor = function(config) {
    this.config = config;

    config.CKEditor = {
        // Allow only these tags (=true for all of them)
        allowedContent: true,

        format_tags: 'p;h2;h3',

        // Available buttons
        toolbar: [
            ['Bold', 'Italic', '-', 'RemoveFormat'],
            ['Link', 'Unlink'],
            ['NumberedList','BulletedList', 'Format'],
            ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo', '-', 'Source']
        ],

        // Disable CKEditor's own image plugin
        removePlugins: 'image'
    };

    // Load the site's own styling
    if (window.WYSIWYG_CSS_URL) {
        config.CKEditor.contentsCss = window.WYSIWYG_CSS_URL;
    }

    config.CKEditor.height = "400px";

    // Load the garp content plugins for richwyswig editor types
    if (config.rich) {
        // Always load the images picker
        var extraPlugins = "garpimages";
        var richButtons = ["Garpimage"];

        // Only load the video picker when a VIDEO_WIDTH template is defined
        if (VIDEO_WIDTH) {
            extraPlugins += ",garpvideos";
            richButtons.push("Garpvideo");
        }

        // Let the editor know
        config.CKEditor.extraPlugins = extraPlugins;
        config.CKEditor.toolbar.push(richButtons);
    }

    // Attach to Ext
    Ext.form.CKEditor.superclass.constructor.call(this, config);
};

Ext.extend(Ext.form.CKEditor, Ext.form.TextArea, {
    onRender: function(ct, position) {
        Ext.form.CKEditor.superclass.onRender.call(this, ct, position);

        this.editor = CKEDITOR.replace(this.id, this.config.CKEditor);

        // Closure for quick access in the event listener
        var that = this;
        this.editor.on('dataReady', function() {
            this.resetDirty();
            that.waitingForSetData = false;
        });
        this.setValue(this.orgValue);
    },

    setValue: function(value) {
        // Save the value as the elements original value
        this.orgValue = value;

        // Wait for an editor (the setValue function will be called on render)
        if (!this.editor) {
            return;
        }
        // Convert undefineds and nulls to empty string
        value = value || "";

        // Working around CKEditor's crazy-assync setData
        // (When setting data twice in short succession only the first data gets set)
        var that = this;

        function retrySetValue(event) {
            that.setValue(that.orgValue);
            that.waitingForSetData = false;
            event.removeListener();
        }
        if (this.waitingForSetData) {
            this.editor.on('dataReady', retrySetValue);
        }
        this.waitingForSetData = true;

        // Set CKEditor's content
        this.editor.setData(value);
    },

    getValue: function() {
        var val = this.orgValue;

        // If an editor is available and content has changed
        if (this.editor && this.editor.checkDirty()) {
            val = this.editor.getData();
        }

        // Convert falsy values to the empty string
        return val || "";
    },

    getRawValue: function() {
        return this.getValue();
    }
});

// Define "Rich CKEditor" (which allows for some more options such as image and video embeds)
Ext.form.RichCKEditor = function(config) {
    config.rich = true;
    Ext.form.RichCKEditor.superclass.constructor.call(this, config);
};
Ext.extend(Ext.form.RichCKEditor, Ext.form.CKEditor);

// Enable the CKEditor as default richtexteditor
Ext.reg('wysiwygeditor', Ext.form.CKEditor);
Ext.reg('richwysiwygeditor', Ext.form.RichCKEditor);
<|endoftext|>


<commit_before>export function preventTouchMove(e) {
  e.preventDefault();
}

export function allowTouchMove(e) {
  e.stopPropagation();
}

export function preventInertiaScroll() {
  const top = this.scrollTop;
  const totalScroll = this.scrollHeight;
  const currentScroll = top + this.offsetHeight;

  if (top === 0) {
    this.scrollTop = 1;
  } else if (currentScroll === totalScroll) {
    this.scrollTop = top - 1;
  }
}

// `ontouchstart` check works on most browsers
// `maxTouchPoints` works on IE10/11 and Surface
export function isTouchDevice() {
  if (!window) return false;
  return 'ontouchstart' in window || navigator.maxTouchPoints;
}

export function getPadding() {
  if (!document || !window) return 0;

  const currentPadding = parseInt(document.body.paddingRight, 10) || 0;
  const clientWidth = document.body ? document.body.clientWidth : 0;
  const adjustedPadding = window.innerWidth - clientWidth + currentPadding || 0;

  return adjustedPadding;
}

export function camelToKebab(str: string): string {
  return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}

export function getWindowHeight(multiplier = 1) {
  if (window && window.innerHeight) {
    return window.innerHeight * multiplier;
  }
}

export function getDocumentHeight() {
  if (document && document.body) {
    return document.body.clientHeight;
  }
}

export function parse(val: number | string): string {
  return isNaN(val) ? val : `${val}px`;
}

// ==============================
// Style Sheets
// ==============================

export function makeStyleTag(id) {
  let tag = document.createElement('style');
  tag.type = 'text/css';
  tag.setAttribute('data-react-scrolllock', '');

  return tag;
}
export function injectStyles(tag, css) {
  if (tag.styleSheet) {
    tag.styleSheet.cssText = css;
  } else {
    tag.appendChild(document.createTextNode(css));
  }
}
export function insertStyleTag(tag) {
  const head = document.head || document.getElementsByTagName('head')[0];
  head.appendChild(tag);
}
<commit_msg>Include checks for typeof window for SSR (#31)<commit_after>export function preventTouchMove(e) {
  e.preventDefault();
}

export function allowTouchMove(e) {
  e.stopPropagation();
}

export function preventInertiaScroll() {
  const top = this.scrollTop;
  const totalScroll = this.scrollHeight;
  const currentScroll = top + this.offsetHeight;

  if (top === 0) {
    this.scrollTop = 1;
  } else if (currentScroll === totalScroll) {
    this.scrollTop = top - 1;
  }
}

// `ontouchstart` check works on most browsers
// `maxTouchPoints` works on IE10/11 and Surface
export function isTouchDevice() {
  if (typeof window === 'undefined' || !window) return false;
  return 'ontouchstart' in window || navigator.maxTouchPoints;
}

export function getPadding() {
  if (typeof window === 'undefined' || !window || !document) return 0;

  const currentPadding = parseInt(document.body.paddingRight, 10) || 0;
  const clientWidth = document.body ? document.body.clientWidth : 0;
  const adjustedPadding = window.innerWidth - clientWidth + currentPadding || 0;

  return adjustedPadding;
}

export function camelToKebab(str: string): string {
  return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}

export function getWindowHeight(multiplier = 1) {
  if (typeof window !== 'undefined' && window && window.innerHeight) {
    return window.innerHeight * multiplier;
  }
}

export function getDocumentHeight() {
  if (typeof window !== 'undefined' && document && document.body) {
    return document.body.clientHeight;
  }
}

export function parse(val: number | string): string {
  return isNaN(val) ? val : `${val}px`;
}

// ==============================
// Style Sheets
// ==============================

export function makeStyleTag(id) {
  let tag = document.createElement('style');
  tag.type = 'text/css';
  tag.setAttribute('data-react-scrolllock', '');

  return tag;
}
export function injectStyles(tag, css) {
  if (tag.styleSheet) {
    tag.styleSheet.cssText = css;
  } else {
    tag.appendChild(document.createTextNode(css));
  }
}
export function insertStyleTag(tag) {
  const head = document.head || document.getElementsByTagName('head')[0];
  head.appendChild(tag);
}
<|endoftext|>