<commit_before>var TILE_H = 60;
var TILE_W = 60;
var regularTower = $('#tower');
var slowTower = $('#slowTurret');
var fastTower = $('#fastTurret');
var goldTower = $('#goldTurret');
var towerChosen = false;
var clickedTile;
var lastClickedTile = 'Thrower'; //this will be set when you click the toolbar so it knows what kind of tower to place

var levelOne = ["(4,0)","(4,1)","(3,1)","(2,1)","(1,1)","(1,2)","(1,3)","(2,3)","(3,3)","(4,3)","(4,4)"];

// THIS FILE DEALS WITH THE CLASSES FOR THE GAME OBJECTS
// THIS AREA ADDRESSES THE TOWER
function Tower(name, fireRate, damage, range, cost){
    this.name = name;
    this.fireRate = fireRate;
    this.damage = damage;
    this.cost = cost;
    this.range = range;
};

Tower.prototype.upgrade = function(cost, fireRate, damage){
  this.cost += cost;
  this.fireRate = fireRate;
  this.damage = damage;
};

Tower.prototype.sell = function(){
  return Math.floor(this.cost * .8);
};

// THIS AREA ADDRESSES THE ENEMY(FBI)
function Enemy(type, health, armor, speed,direction, x, y){
    this.type = type;
    this.x = x;
    this.y = y;
    this.direction = direction;
    this.health = health;
    this.armor = armor;
    this.speed = speed;
};

Enemy.prototype.move = function(passedtime){
	if(this.direction === "UP"){
		this.y += passedtime*this.speed;
	}else if(this.direction === "DOWN"){
		this.y -= passedtime*this.speed;
	}else if(this.direction === "LEFT"){
		this.x -= passedtime*this.speed;
	}else if(this.direction === "RIGHT"){
		this.y += passedtime*this.speed;
	}
}

Enemy.prototype.checkDirection = function(){
	var tilex = Math.floor(this.x/TILE_W);
	var tiley = Math.floor(this.y/TILE_H);
	var pos = "(" + tilex + "," + tiley + ")";
	this.direction = gameGrid.grid[pos].nextDirection;
}

Enemy.prototype.damage = function(damage){
    this.health -= damage*((100-this.armor)/100);
    return this.health <= 0;
};

// THIS AREA ADDRESSES THE GAME
function Game(){
  this.wave = 0;
  this.money = 500;
  this.health = 100;
  this.enemies = [];
};

Game.prototype.nextWave = function(){
  this.wave ++;
  this.initEnemies();
};

Game.prototype.initEnemies = function(wave){
	var numenemies = 5 + 5*wave;
	for(var i = 0; i < numenemies; i++){
		var starttiley= parseInt(levelOne[0].substr(1,2))*TILE_H-.5*TILE_H;
		var starttilex= parseInt(levelOne[0].substr(3,4))*TILE_W;
		var en = new Enemy("", 100, 100, 1, "RIGHT", starttiley,starttilex);
    	this.enemies.push(en);//Will be changed to dynamic function
	}
	console.log("enemies:"+this.enemies);
};

Game.prototype.spendCredits = function(spent){
  this.credits -= spent;
};

Game.prototype.earnedCredits = function(earn){
  this.credits += earn;
};

Game.prototype.damageBase = function(){
  this.health -=1;
  return this.health <= 0;
};

Game.prototype.fps = 30;

Game.prototype.run = function(){
	Game.prototype._intervalId = setInterval(this.tick, 1000 / Game.fps);
}

Game.prototype.tick = function(){
	var passedtime = new Date().getTime() - Game.prototype.previousTick;
	Game.prototype.previousTick = new Date().getTime();
	this.moveEnemies(passedtime);
	this.shootTowers(passedtime);
	this.drawEnemies();
}

Game.prototype.moveEnemies = function(passedtime){
  //TODO when map is solidified
  for (var enemy in this.enemies){
  	enemy.checkDirection();
  	enemy.move(passedtime);
  	//stuff
  }
}

Game.prototype.drawEnemies = new function(){
	for( var enemy in this.enemies){
		var newTowerDiv = document.createElement("div");
		newTowerDiv.setAttribute("id",(clickedTile + "_T"));
		newTowerDiv.setAttribute("class","mapzone"); //remove hidden here and run if you want to see the prelim. map idea (not going to use the strange level format seen below however)
		newTowerDiv.style.left = enemy.x + "px";
		newTowerDiv.style.top = enemy.y + "px";
		newTowerDiv.style.backgroundImage = "url('http://www.placecage.com/30/30')";
		newTowerDiv.style.backgroundRepeat = "no-repeat";
		newTowerDiv.style.backgroundPosition = "center";
		document.body.appendChild(newTowerDiv);
	}
}

Game.prototype.shootTowers = function(passedtime){
  //TODO when map is solidified
}

var towerPlaceLogic = function(){
	clickedTile = this.id;
	console.log(clickedTile);
	var tile = document.getElementById(clickedTile);
	var clickedPositon = $( this ).offset();
  		event.stopPropagation();
	if((gameGrid.grid[clickedTile.substring(0,5)].hasTower == true || (gameGrid.towers[clickedTile] != null)) &&  $("body").hasClass("cursor_change")){
	turnCursorOff();
	alert("Sorry there is a tower there");
	}
	if(gameGrid.grid[clickedTile.substring(0,5)].hasTower == false &&  $("body").hasClass("cursor_change")){
		var newTowerDiv = document.createElement("div");
		var newTowerObj = new Tower(document.getElementsByTagName("body")[0].classList.item(0), 20, 20, 20, 20); //plan to make the class on the body, which changes cursor, have the name of the tower your trying to place, this will then cascade down for naming / determining stats of everything
		newTowerDiv.setAttribute("id",(clickedTile + "_T"));
		newTowerDiv.setAttribute("class","mapzone"); //remove hidden here and run if you want to see the prelim. map idea (not going to use the strange level format seen below however)
		newTowerDiv.style.left = (TILE_H*(gameGrid.grid[clickedTile].locationY)+200) + "px";
		newTowerDiv.style.top = (TILE_W*(gameGrid.grid[clickedTile].locationX)+200) + "px";
		gameGrid.towers[clickedTile] = newTowerObj;
		console.log(gameGrid.towers[clickedTile]); //array of tower objects indexed at location on grid
		gameGrid.grid[clickedTile].hasTower = true;
		gameGrid.grid[clickedTile].towerType = lastClickedTile;
		console.log(gameGrid.grid[clickedTile]); //updated grid tile to reflect having tower
		turnCursorOff();
		newTowerDiv.style.backgroundImage = "url('http://www.placecage.com/30/30')";
		newTowerDiv.style.backgroundRepeat = "no-repeat";
		newTowerDiv.style.backgroundPosition = "center";
		newTowerDiv.addEventListener("click",towerPlaceLogic);
		document.body.appendChild(newTowerDiv);
	}
}

var Grid = function(mapHeight,mapWidth) {
    var mapHeight = mapHeight;
    var mapWidth = mapWidth;
    this.grid = {};
    this.towers = {};
    this.pathTiles = {};
    // create the map zone

    this.createGrid = function() {
	for(var j = 0; j < mapHeight; j++)
	{
		for(var i = 0; i < mapWidth; i++)
		{
			var mapzone = document.createElement("div");
			var nonPathTile={locationY: i, locationX: j, hasTower: false,  towerType: null}; //create a new key/dictionary value for each cell/tile in our table into our grid obj, which will keep track of what exists in each cell
            var pathTile = {nextDirection: null, hasEnemy: null};
            var pos = "(" + j + "," + i + ")"; //gives us our position for these cells as a coordinate
			mapzone.setAttribute("id",pos);
			mapzone.setAttribute("class","mapzone hidden"); //remove hidden here and run if you want to see the prelim. map idea (not going to use the strange level format seen below however)
			mapzone.style.left = (TILE_H*i+200) + "px";
			mapzone.style.top = (TILE_W*j+200) + "px";
			document.body.appendChild(mapzone);
			if(levelOne.indexOf(pos) > -1)
			{
				mapzone.style.backgroundColor = "brown";
				mapzone.style.backgroundImage = "url('/img/pathtile60.png')";
				this.grid[pos] = pathTile;
				this.pathTiles[pos] = pathTile;
			}
			else
			{
				this.grid[pos] = nonPathTile;
				mapzone.style.backgroundImage = "url('/img/grasstile60.png')";
				document.getElementById(pos).addEventListener("click",towerPlaceLogic);
			}
		}
	}
}
	this.markTileDirections = function() {
		for (var i = 0; i <levelOne.length;i++){
			var tiley= parseInt(levelOne[i].substr(1,2));
			var tilex= parseInt(levelOne[i].substr(3,4));
			var pos = "(" + tiley + "," + tilex + ")";
			if(i<levelOne.length-1){
				var nexttiley= parseInt(levelOne[i+1].substr(1,2));
				var nexttilex= parseInt(levelOne[i+1].substr(3,4));
				if(tiley-nexttiley==1){
					this.pathTiles[pos].nextDirection="UP";
				}else if (tiley-nexttiley==-1){
					this.pathTiles[pos].nextDirection="DOWN";
				}else if (tilex-nexttilex==1){
					this.pathTiles[pos].nextDirection="LEFT";
				}else if (tilex-nexttilex==-1){
					this.pathTiles[pos].nextDirection="RIGHT";
				}else{
					console.log("ERR: ("+tilex+","+tiley+"), ("+nexttilex+","+nexttiley+")");
				}
			}else{
				this.pathTiles[pos].nextDirection="RIGHT";
			}
			console.log("dir:"+this.pathTiles[pos].nextDirection);
		}
	}
}

var turnCursorOn = function(e){

	//Shit that I added
	var clickedTower = this.id;
	$("body").addClass(clickedTower);
	$("body").addClass("cursor_change");
	regularTower.off("click", turnCursorOn);
	$("body").on("click", turnCursorOff);
    towerChosen = true;
    e.stopImmediatePropagation();
	//

	/*
    $("body").toggleClass("cursor_change");
    regularTower.off("click", turnCursorOn);
    $("body").on("click", turnCursorOff);
    towerChosen = true;
    e.stopImmediatePropagation();
    */
}

var turnCursorOff = function(){
    if(towerChosen == true){
    	$("body").removeClass();
    	//$("body").toggleClass("cursor_change");
    	$("body").off("click", turnCursorOff);
    	regularTower.on("click", turnCursorOn);
    	towerChosen = false;
    }
}
<<<<<<< HEAD
testTower.on("click", turnCursorOn);
=======

regularTower.on("click", turnCursorOn);
slowTower.on("click", turnCursorOn);
fastTower.on("click", turnCursorOn);
goldTower.on("click", turnCursorOn);
>>>>>>> d1f478aadfbe1f17c028e01992504c452c966dca
var gameGrid = new Grid(10,15);
gameGrid.createGrid();
gameGrid.markTileDirections();
var newGame = new Game();
newGame.initEnemies(0);
//newGame.run();
<commit_msg>fixed merge issues<commit_after>var TILE_H = 60;
var TILE_W = 60;
var regularTower = $('#tower');
var slowTower = $('#slowTurret');
var fastTower = $('#fastTurret');
var goldTower = $('#goldTurret');
var towerChosen = false;
var clickedTile;
var lastClickedTile = 'Thrower'; //this will be set when you click the toolbar so it knows what kind of tower to place

var levelOne = ["(4,0)","(4,1)","(3,1)","(2,1)","(1,1)","(1,2)","(1,3)","(2,3)","(3,3)","(4,3)","(4,4)"];

// THIS FILE DEALS WITH THE CLASSES FOR THE GAME OBJECTS
// THIS AREA ADDRESSES THE TOWER
function Tower(name, fireRate, damage, range, cost){
    this.name = name;
    this.fireRate = fireRate;
    this.damage = damage;
    this.cost = cost;
    this.range = range;
};

Tower.prototype.upgrade = function(cost, fireRate, damage){
  this.cost += cost;
  this.fireRate = fireRate;
  this.damage = damage;
};

Tower.prototype.sell = function(){
  return Math.floor(this.cost * .8);
};

// THIS AREA ADDRESSES THE ENEMY(FBI)
function Enemy(type, health, armor, speed,direction, x, y){
    this.type = type;
    this.x = x;
    this.y = y;
    this.direction = direction;
    this.health = health;
    this.armor = armor;
    this.speed = speed;
};

Enemy.prototype.move = function(passedtime){
	if(this.direction === "UP"){
		this.y += passedtime*this.speed;
	}else if(this.direction === "DOWN"){
		this.y -= passedtime*this.speed;
	}else if(this.direction === "LEFT"){
		this.x -= passedtime*this.speed;
	}else if(this.direction === "RIGHT"){
		this.y += passedtime*this.speed;
	}
}

Enemy.prototype.checkDirection = function(){
	var tilex = Math.floor(this.x/TILE_W);
	var tiley = Math.floor(this.y/TILE_H);
	var pos = "(" + tilex + "," + tiley + ")";
	this.direction = gameGrid.grid[pos].nextDirection;
}

Enemy.prototype.damage = function(damage){
    this.health -= damage*((100-this.armor)/100);
    return this.health <= 0;
};

// THIS AREA ADDRESSES THE GAME
function Game(){
  this.wave = 0;
  this.money = 500;
  this.health = 100;
  this.enemies = [];
};

Game.prototype.nextWave = function(){
  this.wave ++;
  this.initEnemies();
};

Game.prototype.initEnemies = function(wave){
	var numenemies = 5 + 5*wave;
	for(var i = 0; i < numenemies; i++){
		var starttiley= parseInt(levelOne[0].substr(1,2))*TILE_H-.5*TILE_H;
		var starttilex= parseInt(levelOne[0].substr(3,4))*TILE_W;
		var en = new Enemy("", 100, 100, 1, "RIGHT", starttiley,starttilex);
    	this.enemies.push(en);//Will be changed to dynamic function
	}
	console.log("enemies:"+this.enemies);
};

Game.prototype.spendCredits = function(spent){
  this.credits -= spent;
};

Game.prototype.earnedCredits = function(earn){
  this.credits += earn;
};

Game.prototype.damageBase = function(){
  this.health -=1;
  return this.health <= 0;
};

Game.prototype.fps = 30;

Game.prototype.run = function(){
	Game.prototype._intervalId = setInterval(this.tick, 1000 / Game.fps);
}

Game.prototype.tick = function(){
	var passedtime = new Date().getTime() - Game.prototype.previousTick;
	Game.prototype.previousTick = new Date().getTime();
	this.moveEnemies(passedtime);
	this.shootTowers(passedtime);
	this.drawEnemies();
}

Game.prototype.moveEnemies = function(passedtime){
  //TODO when map is solidified
  for (var enemy in this.enemies){
  	enemy.checkDirection();
  	enemy.move(passedtime);
  	//stuff
  }
}

Game.prototype.drawEnemies = new function(){
	for( var enemy in this.enemies){
		var newTowerDiv = document.createElement("div");
		newTowerDiv.setAttribute("id",(clickedTile + "_T"));
		newTowerDiv.setAttribute("class","mapzone"); //remove hidden here and run if you want to see the prelim. map idea (not going to use the strange level format seen below however)
		newTowerDiv.style.left = enemy.x + "px";
		newTowerDiv.style.top = enemy.y + "px";
		newTowerDiv.style.backgroundImage = "url('http://www.placecage.com/30/30')";
		newTowerDiv.style.backgroundRepeat = "no-repeat";
		newTowerDiv.style.backgroundPosition = "center";
		document.body.appendChild(newTowerDiv);
	}
}

Game.prototype.shootTowers = function(passedtime){
  //TODO when map is solidified
}

var towerPlaceLogic = function(){
	clickedTile = this.id;
	console.log(clickedTile);
	var tile = document.getElementById(clickedTile);
	var clickedPositon = $( this ).offset();
  		event.stopPropagation();
	if((gameGrid.grid[clickedTile.substring(0,5)].hasTower == true || (gameGrid.towers[clickedTile] != null)) &&  $("body").hasClass("cursor_change")){
	turnCursorOff();
	alert("Sorry there is a tower there");
	}
	if(gameGrid.grid[clickedTile.substring(0,5)].hasTower == false &&  $("body").hasClass("cursor_change")){
		var newTowerDiv = document.createElement("div");
		var newTowerObj = new Tower(document.getElementsByTagName("body")[0].classList.item(0), 20, 20, 20, 20); //plan to make the class on the body, which changes cursor, have the name of the tower your trying to place, this will then cascade down for naming / determining stats of everything
		newTowerDiv.setAttribute("id",(clickedTile + "_T"));
		newTowerDiv.setAttribute("class","mapzone"); //remove hidden here and run if you want to see the prelim. map idea (not going to use the strange level format seen below however)
		newTowerDiv.style.left = (TILE_H*(gameGrid.grid[clickedTile].locationY)+200) + "px";
		newTowerDiv.style.top = (TILE_W*(gameGrid.grid[clickedTile].locationX)+200) + "px";
		gameGrid.towers[clickedTile] = newTowerObj;
		console.log(gameGrid.towers[clickedTile]); //array of tower objects indexed at location on grid
		gameGrid.grid[clickedTile].hasTower = true;
		gameGrid.grid[clickedTile].towerType = lastClickedTile;
		console.log(gameGrid.grid[clickedTile]); //updated grid tile to reflect having tower
		turnCursorOff();
		newTowerDiv.style.backgroundImage = "url('http://www.placecage.com/30/30')";
		newTowerDiv.style.backgroundRepeat = "no-repeat";
		newTowerDiv.style.backgroundPosition = "center";
		newTowerDiv.addEventListener("click",towerPlaceLogic);
		document.body.appendChild(newTowerDiv);
	}
}

var Grid = function(mapHeight,mapWidth) {
    var mapHeight = mapHeight;
    var mapWidth = mapWidth;
    this.grid = {};
    this.towers = {};
    this.pathTiles = {};
    // create the map zone

    this.createGrid = function() {
	for(var j = 0; j < mapHeight; j++)
	{
		for(var i = 0; i < mapWidth; i++)
		{
			var mapzone = document.createElement("div");
			var nonPathTile={locationY: i, locationX: j, hasTower: false,  towerType: null}; //create a new key/dictionary value for each cell/tile in our table into our grid obj, which will keep track of what exists in each cell
            var pathTile = {nextDirection: null, hasEnemy: null};
            var pos = "(" + j + "," + i + ")"; //gives us our position for these cells as a coordinate
			mapzone.setAttribute("id",pos);
			mapzone.setAttribute("class","mapzone hidden"); //remove hidden here and run if you want to see the prelim. map idea (not going to use the strange level format seen below however)
			mapzone.style.left = (TILE_H*i+200) + "px";
			mapzone.style.top = (TILE_W*j+200) + "px";
			document.body.appendChild(mapzone);
			if(levelOne.indexOf(pos) > -1)
			{
				mapzone.style.backgroundColor = "brown";
				mapzone.style.backgroundImage = "url('/img/pathtile60.png')";
				this.grid[pos] = pathTile;
				this.pathTiles[pos] = pathTile;
			}
			else
			{
				this.grid[pos] = nonPathTile;
				mapzone.style.backgroundImage = "url('/img/grasstile60.png')";
				document.getElementById(pos).addEventListener("click",towerPlaceLogic);
			}
		}
	}
}
	this.markTileDirections = function() {
		for (var i = 0; i <levelOne.length;i++){
			var tiley= parseInt(levelOne[i].substr(1,2));
			var tilex= parseInt(levelOne[i].substr(3,4));
			var pos = "(" + tiley + "," + tilex + ")";
			if(i<levelOne.length-1){
				var nexttiley= parseInt(levelOne[i+1].substr(1,2));
				var nexttilex= parseInt(levelOne[i+1].substr(3,4));
				if(tiley-nexttiley==1){
					this.pathTiles[pos].nextDirection="UP";
				}else if (tiley-nexttiley==-1){
					this.pathTiles[pos].nextDirection="DOWN";
				}else if (tilex-nexttilex==1){
					this.pathTiles[pos].nextDirection="LEFT";
				}else if (tilex-nexttilex==-1){
					this.pathTiles[pos].nextDirection="RIGHT";
				}else{
					console.log("ERR: ("+tilex+","+tiley+"), ("+nexttilex+","+nexttiley+")");
				}
			}else{
				this.pathTiles[pos].nextDirection="RIGHT";
			}
			console.log("dir:"+this.pathTiles[pos].nextDirection);
		}
	}
}

var turnCursorOn = function(e){

	//Shit that I added
	var clickedTower = this.id;
	$("body").addClass(clickedTower);
	$("body").addClass("cursor_change");
	regularTower.off("click", turnCursorOn);
	$("body").on("click", turnCursorOff);
    towerChosen = true;
    e.stopImmediatePropagation();
	//

	/*
    $("body").toggleClass("cursor_change");
    regularTower.off("click", turnCursorOn);
    $("body").on("click", turnCursorOff);
    towerChosen = true;
    e.stopImmediatePropagation();
    */
}

var turnCursorOff = function(){
    if(towerChosen == true){
    	$("body").removeClass();
    	//$("body").toggleClass("cursor_change");
    	$("body").off("click", turnCursorOff);
    	regularTower.on("click", turnCursorOn);
    	towerChosen = false;
    }
}

regularTower.on("click", turnCursorOn);
slowTower.on("click", turnCursorOn);
fastTower.on("click", turnCursorOn);
goldTower.on("click", turnCursorOn);

var gameGrid = new Grid(10,15);
gameGrid.createGrid();
gameGrid.markTileDirections();
var newGame = new Game();
newGame.initEnemies(0);
newGame.run();
<|endoftext|>


<commit_before>/**
 * @author Jihoon Lee - jihoonlee.in@gmail.com
 * @author Russell Toris - rctoris@wpi.edu
 */

/**
 * A MeshResource is an THREE object that will load from a external mesh file. Currently loads
 * Collada files.
 *
 * @constructor
 * @param options - object with following keys:
 *
 *  * path (optional) - the base path to the associated models that will be loaded
 *  * resource - the resource file name to load
 *  * material (optional) - the material to use for the object
 *  * warnings (optional) - if warnings should be printed
 *  * loader (optional) - the Collada loader to use (e.g., an instance of ROS3D.COLLADA_LOADER
 *                        ROS3D.COLLADA_LOADER_2) -- defaults to ROS3D.COLLADA_LOADER_2
 */
ROS3D.MeshResource = function(options) {
  var that = this;
  options = options || {};
  var path = options.path || '/';
  var resource = options.resource;
  var material = options.material || null;
  this.warnings = options.warnings;
  var loaderType = options.loader || ROS3D.COLLADA_LOADER_2;

  THREE.Object3D.call(this);

  // check for a trailing '/'
  if (path.substr(path.length - 1) !== '/') {
    this.path += '/';
  }

  var uri = path + resource;
  var fileType = uri.substr(-4).toLowerCase();

  // check the type
  var loader;
  if (fileType === '.dae') {
    if (loaderType ===  ROS3D.COLLADA_LOADER) {
      loader = new THREE.ColladaLoader();
    } else {
      loader = new ColladaLoader2();
    }
    loader.log = function(message) {
      if (that.warnings) {
        console.warn(message);
      }
    };
    loader.load(uri, function colladaReady(collada) {
      // check for a scale factor in ColladaLoader2
      if(loaderType === ROS3D.COLLADA_LOADER_2 && collada.dae.asset.unit) {
        var scale = collada.dae.asset.unit;
        collada.scene.scale = new THREE.Vector3(scale, scale, scale);
      }

      if(material !== null) {
        var setMaterial = function(node, material) {
          node.material = material;
          if (node.children) {
            for (var i = 0; i < node.children.length; i++) {
              setMaterial(node.children[i], material);
            }
          }
        };

        setMaterial(collada.scene, material);
      }

      that.add(collada.scene);
    });
  } else if (fileType === '.stl') {
    loader = new THREE.STLLoader();
    loader.addEventListener( 'error', function ( event ) {
      if (that.warnings) {
        console.warn(event.message);
      }
    });
    loader.addEventListener( 'load', function ( event ) {
      var geometry = event.content;
      geometry.computeFaceNormals();
      var mesh;
      if(material !== null) {
        mesh = new THREE.Mesh( geometry, material );
      } else {
        mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { color: 0x999999 } ) );
      }
      that.add(mesh);
    } );
    loader.load(uri);
  }
};
ROS3D.MeshResource.prototype.__proto__ = THREE.Object3D.prototype;
<commit_msg>Fixed STL loader<commit_after>/**
 * @author Jihoon Lee - jihoonlee.in@gmail.com
 * @author Russell Toris - rctoris@wpi.edu
 */

/**
 * A MeshResource is an THREE object that will load from a external mesh file. Currently loads
 * Collada files.
 *
 * @constructor
 * @param options - object with following keys:
 *
 *  * path (optional) - the base path to the associated models that will be loaded
 *  * resource - the resource file name to load
 *  * material (optional) - the material to use for the object
 *  * warnings (optional) - if warnings should be printed
 *  * loader (optional) - the Collada loader to use (e.g., an instance of ROS3D.COLLADA_LOADER
 *                        ROS3D.COLLADA_LOADER_2) -- defaults to ROS3D.COLLADA_LOADER_2
 */
ROS3D.MeshResource = function(options) {
  var that = this;
  options = options || {};
  var path = options.path || '/';
  var resource = options.resource;
  var material = options.material || null;
  this.warnings = options.warnings;
  var loaderType = options.loader || ROS3D.COLLADA_LOADER_2;

  THREE.Object3D.call(this);

  // check for a trailing '/'
  if (path.substr(path.length - 1) !== '/') {
    this.path += '/';
  }

  var uri = path + resource;
  var fileType = uri.substr(-4).toLowerCase();

  // check the type
  var loader;
  if (fileType === '.dae') {
    if (loaderType ===  ROS3D.COLLADA_LOADER) {
      loader = new THREE.ColladaLoader();
    } else {
      loader = new ColladaLoader2();
    }
    loader.log = function(message) {
      if (that.warnings) {
        console.warn(message);
      }
    };
    loader.load(uri, function colladaReady(collada) {
      // check for a scale factor in ColladaLoader2
      if(loaderType === ROS3D.COLLADA_LOADER_2 && collada.dae.asset.unit) {
        var scale = collada.dae.asset.unit;
        collada.scene.scale = new THREE.Vector3(scale, scale, scale);
      }

      if(material !== null) {
        var setMaterial = function(node, material) {
          node.material = material;
          if (node.children) {
            for (var i = 0; i < node.children.length; i++) {
              setMaterial(node.children[i], material);
            }
          }
        };

        setMaterial(collada.scene, material);
      }

      that.add(collada.scene);
    });
  } else if (fileType === '.stl') {
    loader = new THREE.STLLoader();
    {
      loader.load(uri, function ( geometry ) {
        geometry.computeFaceNormals();
        var mesh;
        if(material !== null) {
          mesh = new THREE.Mesh( geometry, material );
        } else {
          mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { color: 0x999999 } ) );
        }
        that.add(mesh);
      } );
    }
  }
};
ROS3D.MeshResource.prototype.__proto__ = THREE.Object3D.prototype;
<|endoftext|>


<commit_before>/*
  RSVP Section
*/

import _ from 'lodash';
import $ from 'jquery';
import {activate, deactivate, isActive, toggle} from "./active.es6";

const MAX_PLUS_NAMES = 4;

/*
  Save info for a guest to Firebase

  data: {
    attending: boolean;
    names: string[];
    email: string;
    address: string;
  }
*/
export function saveGuest(data) {
  var updates = {};
  var key = firebase.database().ref().child('guests').push().key;
  updates['/guests/' + key] = data;
  return firebase.database().ref().update(updates);
}

// Takes serialized name-value pairs and forms it for saving
function formatData(data) {
  var names = _(data)
    .filter((d) => d.name === "guest-name")
    .map((d) => (d.value || "").trim())
    .filter()
    .value();

  return {
    attending: getValue(data, 'attending'),
    names: names,
    email: getValue(data, 'email'),
    address: getValue(data, 'address')
  };
}

function getValue(data, key) {
  var obj = _.find(data, (d) => d.name === key);
  return obj && obj.value;
}

/* Handle error response */

const saveMsg = "#save-msg";
const errorMsg = "#error-msg";

function onSave() {
  activate(saveMsg);
  deactivate(errorMsg);
  $(rsvpForm).hide();
}

function onError(err) {
  activate(errorMsg);
  deactivate(saveMsg);
  if (! err instanceof Error) {
    err = new Error(err);
  }
  try {
    throw err;
  } catch (e) {
    _errs.push(e);
  }
}

/* Form elements */

const rsvpForm = "#rsvp-form";
const groupSelector = ".name-group";
const templateClass = "template";
const addGuestBtn = "#add-guest-btn";
const rmGuestBtn = ".rm-action";
const guestTemplate = groupSelector + "." + templateClass;
const guestContainer = "#plus-ones";
const submitBtn = "#rsvp-submit-btn";
const requiredSelector = "*[required]:visible";
const emailSelector = "input[type=email]"
const errorClass = "has-error";
const attendingYes = '#attending-yes';
const attendingNo = '#attending-no';
const attendingShow = ".attending-show";
const spinner = ".spinner";

export function cloneTemplate() {
  var newGuest = $(guestTemplate).clone();
  newGuest.removeClass(templateClass);
  $(guestContainer).append(newGuest);
  newGuest.find(rmGuestBtn).click(function() {
    $(this).parents(groupSelector).remove();
    $(addGuestBtn).prop("disabled", false);
  });
}

export function toggleYesNo() {
  $(attendingYes).click(function() {
    $(attendingShow).show();
  });

  $(attendingNo).click(function() {
    $(attendingShow).hide();
  });
}

export function validate() {
  var hasError = false;
  $("." + errorClass).removeClass(errorClass);

  $(rsvpForm).find(requiredSelector).each(function(index, elm) {
    if (! $(elm).val().trim()) {
      $(elm).parents('.form-group').first().addClass(errorClass);
      hasError = true;
    }
  });

  return !hasError;
}

export function init() {
  $(addGuestBtn).click(function(e) {
    e.preventDefault();

    var numChildren = $(guestContainer).children().length;
    if (numChildren < MAX_PLUS_NAMES) {
      cloneTemplate();
      if (numChildren + 1 >= MAX_PLUS_NAMES) {
        $(addGuestBtn).prop("disabled", true);
      }
    }
  });

  $(submitBtn).click(function(e) {
    e.preventDefault();

    if (validate()) {
      activate($(submitBtn).find(spinner));
      $(submitBtn).prop("disabled", true);

      var data = $(rsvpForm).serializeArray();
      var post = function() {
        deactivate($(submitBtn).find(spinner));
        $(e).prop("disabled", false);
      };

      saveGuest(formatData(data))
        .then(onSave, onError)
        .then(post, post);
    }
  });

  toggleYesNo();
}
<commit_msg>RSVP timestamp, boolean<commit_after>/*
  RSVP Section
*/

import _ from 'lodash';
import $ from 'jquery';
import {activate, deactivate, isActive, toggle} from "./active.es6";

const MAX_PLUS_NAMES = 4;

/*
  Save info for a guest to Firebase

  data: {
    attending: boolean;
    names: string[];
    email: string;
    address: string;
  }
*/
export function saveGuest(data) {
  var updates = {};
  var key = firebase.database().ref().child('guests').push().key;
  updates['/guests/' + key] = data;
  data.timestamp = firebase.database.ServerValue.TIMESTAMP;
  return firebase.database().ref().update(updates);
}

// Takes serialized name-value pairs and forms it for saving
function formatData(data) {
  var names = _(data)
    .filter((d) => d.name === "guest-name")
    .map((d) => (d.value || "").trim())
    .filter()
    .value();

  return {
    attending: getValue(data, 'attending') === 'yes',
    names: names,
    email: getValue(data, 'email'),
    address: getValue(data, 'address')
  };
}

function getValue(data, key) {
  var obj = _.find(data, (d) => d.name === key);
  return obj && obj.value;
}

/* Handle error response */

const saveMsg = "#save-msg";
const errorMsg = "#error-msg";

function onSave() {
  activate(saveMsg);
  deactivate(errorMsg);
  $(rsvpForm).hide();
}

function onError(err) {
  activate(errorMsg);
  deactivate(saveMsg);
  if (! err instanceof Error) {
    err = new Error(err);
  }
  try {
    throw err;
  } catch (e) {
    _errs.push(e);
  }
}

/* Form elements */

const rsvpForm = "#rsvp-form";
const groupSelector = ".name-group";
const templateClass = "template";
const addGuestBtn = "#add-guest-btn";
const rmGuestBtn = ".rm-action";
const guestTemplate = groupSelector + "." + templateClass;
const guestContainer = "#plus-ones";
const submitBtn = "#rsvp-submit-btn";
const requiredSelector = "*[required]:visible";
const emailSelector = "input[type=email]"
const errorClass = "has-error";
const attendingYes = '#attending-yes';
const attendingNo = '#attending-no';
const attendingShow = ".attending-show";
const spinner = ".spinner";

export function cloneTemplate() {
  var newGuest = $(guestTemplate).clone();
  newGuest.removeClass(templateClass);
  $(guestContainer).append(newGuest);
  newGuest.find(rmGuestBtn).click(function() {
    $(this).parents(groupSelector).remove();
    $(addGuestBtn).prop("disabled", false);
  });
}

export function toggleYesNo() {
  $(attendingYes).click(function() {
    $(attendingShow).show();
  });

  $(attendingNo).click(function() {
    $(attendingShow).hide();
  });
}

export function validate() {
  var hasError = false;
  $("." + errorClass).removeClass(errorClass);

  $(rsvpForm).find(requiredSelector).each(function(index, elm) {
    if (! $(elm).val().trim()) {
      $(elm).parents('.form-group').first().addClass(errorClass);
      hasError = true;
    }
  });

  return !hasError;
}

export function init() {
  $(addGuestBtn).click(function(e) {
    e.preventDefault();

    var numChildren = $(guestContainer).children().length;
    if (numChildren < MAX_PLUS_NAMES) {
      cloneTemplate();
      if (numChildren + 1 >= MAX_PLUS_NAMES) {
        $(addGuestBtn).prop("disabled", true);
      }
    }
  });

  $(submitBtn).click(function(e) {
    e.preventDefault();

    if (validate()) {
      activate($(submitBtn).find(spinner));
      $(submitBtn).prop("disabled", true);

      var data = $(rsvpForm).serializeArray();
      var post = function() {
        deactivate($(submitBtn).find(spinner));
        $(e).prop("disabled", false);
      };

      saveGuest(formatData(data))
        .then(onSave, onError)
        .then(post, post);
    }
  });

  toggleYesNo();
}
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var args = ['commit', outFile, '-m', 'Update character']
    for (var counter = 0; counter < length; counter++)
    {
      fs.writeSync(outFD, data<commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var args = ['commit', outFile, '-m', 'Update character']
    for (var counter = 0; counter < length; counter++)
    {
      fs.writeSync(outFD, data.<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { Link } from 'react-router'
import { getUser } from '../../fetch/fetch'
import { waitForDataAndSetState, cancelAllPromises } from '../../helpers/components'
import { nav, home, log, account, authentification, avatar } from './Header.css'

class Header extends Component {
  constructor(props) {
    super(props)
    this.state = {
      errors: [],
    }
  }

  componentWillMount() {
    return waitForDataAndSetState(getUser(), this, 'user')
  }

  componentWillUnmount() {
    return cancelAllPromises(this)
  }

  render() {
    const { user } = this.state
    const loginRedirect = encodeURI(`${process.env.PUBLIC_URL}/publication`)
    const logoutRedirect = encodeURI(`${process.env.PUBLIC_URL}`)
    const logInUrl = `https://inspire.data.gouv.fr/dgv/login?redirect=${loginRedirect}`
    const logoutUrl = `https://inspire.data.gouv.fr/dgv/logout?redirect=${logoutRedirect}`
    const login = Publier des données

    return (

        Inspire
        {!user ? login : (

            <Link to={'/publication'}>

                {user.first_name} {user.last_name}

            </Link>
            Déconnexion

        )}

    )
  }
}

export default Header
<commit_msg>Encodes during injection<commit_after>import React, { Component } from 'react'
import { Link } from 'react-router'
import { getUser } from '../../fetch/fetch'
import { waitForDataAndSetState, cancelAllPromises } from '../../helpers/components'
import { nav, home, log, account, authentification, avatar } from './Header.css'

class Header extends Component {
  constructor(props) {
    super(props)
    this.state = {
      errors: [],
    }
  }

  componentWillMount() {
    return waitForDataAndSetState(getUser(), this, 'user')
  }

  componentWillUnmount() {
    return cancelAllPromises(this)
  }

  render() {
    const { user } = this.state
    const loginRedirect = `${process.env.PUBLIC_URL}/publication`
    const logoutRedirect = `${process.env.PUBLIC_URL}`
    const logInUrl =`https://inspire.data.gouv.fr/dgv/login?redirect=${encodeURIComponent(loginRedirect)}`
    const logoutUrl =`https://inspire.data.gouv.fr/dgv/logout?redirect=${encodeURIComponent(logoutRedirect)}`
    const login = Publier des données

    return (

        Inspire
        {!user ? login : (

            <Link to={'/publication'}>

                {user.first_name} {user.last_name}

            </Link>
            Déconnexion

        )}

    )
  }
}

export default Header
<|endoftext|>


<commit_before>/** @jsx jsx */

import React, { useEffect } from 'react' //eslint-disable-line
import { jsx, Styled } from 'theme-ui'
import styled from '@emotion/styled'
import PropTypes from 'prop-types'

const Modal = styled.div`
  position: absolute;
  top: 0;
  content: '';
  transition: all 0.3s;
  z-index: 2;
  background: black;
  width: 100%;
  height: 100%;
  opacity: ${props => (props.visible ? '1' : '0')};
  visibility: ${props => (props.visible ? 'visible' : 'hidden')};
  section {
    p {
      line-height: 1.6;
      margin: 0 0 2em 0;
      text-align: center;
    }
  }
`

const Form = styled.form`
  position: relative;
  width: 100%;
  label {
    padding: 0 16px;
  }
  input,
  textarea {
    padding: 12px;
    color: ${props => props.theme.colors.text};
    background: ${props => props.theme.colors.secondary};
    &::placeholder {
      color: ${props => props.theme.colors.shadow};
    }
    &:last-child {
      color: ${props => props.theme.colors.text};
      background: ${props => props.theme.colors.shadow};
    }
  }

  &::invalid {
    box-shadow: none;
  }
  &::required {
    box-shadow: none;
  }
  &::optional {
    box-shadow: none;
  }
`

const Input = styled.input`
  margin: 0 0 8px;
  width: 100%;
`
const TextArea = styled.textarea`
  margin: 0 0 8px;
  width: 100%;
`

const Submit = styled.input`
  cursor: pointer;
  transition: 0.2s;
  width: 100%;
  font-weight: bold;
`

class EmailCapture extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      name: '',
      email: '',
      restaurant: '',
      address: '',
      notes: '',
      tags: [
        {
          name: 'Covid',
        },
      ],
      showModal: false,
      showPrompt: true,
    }
  }

  handleInputChange = event => {
    const target = event.target
    const value = target.value
    const email = target.email
    const name = target.name
    const restaurant = target.restaurant
    const address = target.address
    const notes = target.notes
    const tags = [
      {
        name: 'Covid',
      },
    ]
    this.setState({
      [email]: value,
      [name]: value,
      [restaurant]: value,
      [address]: value,
      [notes]: value,
      [tags]: value,
    })
  }

  componentDidMount() {
    this.handleSubmit = event => {
      event.preventDefault()
      this.handleSuccess()
      window.analytics.identify({
        email: this.state.email,
        name: this.state.name,
        restaurant: this.state.restaurant,
        address: this.state.address,
        notes: this.state.notes,
        tags: [
          {
            name: 'Covid',
          },
        ],
      })
    }
  }

  handleSuccess = () => {
    this.setState({
      email: '',
      name: '',
      restaurant: '',
      address: '',
      notes: '',
      tags: [
        {
          name: 'Covid',
        },
      ],
      showModal: true,
      showPrompt: false,
    })
  }

  closeModal = () => {
    this.setState({ showModal: false, showPrompt: true })
  }

  render(props) {
    return (
      <>
        <Form
          name="subscribe"
          onSubmit={this.handleSubmit}
          overlay={this.state.visible}
          onClick={this.closeModal}
        >
          <Modal visible={this.state.showModal}>

          </Modal>

          <Input
            name="name"
            type="name"
            placeholder="Name*"
            value={this.state.name}
            onChange={this.handleInputChange}
            required
          />
          <Input
            name="email"
            type="email"
            placeholder="Email*"
            value={this.state.email}
            onChange={this.handleInputChange}
            required
          />
          <Input
            name="restaurant"
            type="restaurant"
            placeholder="Restaurant*"
            value={this.state.restaurant}
            onChange={this.handleInputChange}
            required
          />
          <Input
            name="address"
            type="address"
            placeholder="Address*"
            value={this.state.address}
            onChange={this.handleInputChange}
            required
          />
          <TextArea
            name="notes"
            type="notes"
            placeholder="Notes"
            value={this.state.notes}
            onChange={this.handleInputChange}
            required
          />
          <Submit className="button" name="submit" type="submit" value="Send" />
        </Form>
      </>
    )
  }
}

EmailCapture.propTypes = {
  data: PropTypes.object,
}

export default EmailCapture
<commit_msg>Remove tags in favor of a better solution<commit_after>/** @jsx jsx */

import React, { useEffect } from 'react' //eslint-disable-line
import { jsx, Styled } from 'theme-ui'
import styled from '@emotion/styled'
import PropTypes from 'prop-types'

const Modal = styled.div`
  position: absolute;
  top: 0;
  content: '';
  transition: all 0.3s;
  z-index: 2;
  background: black;
  width: 100%;
  height: 100%;
  opacity: ${props => (props.visible ? '1' : '0')};
  visibility: ${props => (props.visible ? 'visible' : 'hidden')};
  section {
    p {
      line-height: 1.6;
      margin: 0 0 2em 0;
      text-align: center;
    }
  }
`

const Form = styled.form`
  position: relative;
  width: 100%;
  label {
    padding: 0 16px;
  }
  input,
  textarea {
    padding: 12px;
    color: ${props => props.theme.colors.text};
    background: ${props => props.theme.colors.secondary};
    &::placeholder {
      color: ${props => props.theme.colors.shadow};
    }
    &:last-child {
      color: ${props => props.theme.colors.text};
      background: ${props => props.theme.colors.shadow};
    }
  }

  &::invalid {
    box-shadow: none;
  }
  &::required {
    box-shadow: none;
  }
  &::optional {
    box-shadow: none;
  }
`

const Input = styled.input`
  margin: 0 0 8px;
  width: 100%;
`
const TextArea = styled.textarea`
  margin: 0 0 8px;
  width: 100%;
`

const Submit = styled.input`
  cursor: pointer;
  transition: 0.2s;
  width: 100%;
  font-weight: bold;
`

class EmailCapture extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      name: '',
      email: '',
      restaurant: '',
      address: '',
      notes: '',
      showModal: false,
      showPrompt: true,
    }
  }

  handleInputChange = event => {
    const target = event.target
    const value = target.value
    const email = target.email
    const name = target.name
    const restaurant = target.restaurant
    const address = target.address
    const notes = target.notes
    this.setState({
      [email]: value,
      [name]: value,
      [restaurant]: value,
      [address]: value,
      [notes]: value,
    })
  }

  componentDidMount() {
    this.handleSubmit = event => {
      event.preventDefault()
      this.handleSuccess()
      window.analytics.identify({
        email: this.state.email,
        name: this.state.name,
        restaurant: this.state.restaurant,
        address: this.state.address,
        notes: this.state.notes,
        tags: [
          {
            name: 'Covid',
          },
        ],
      })
    }
  }

  handleSuccess = () => {
    this.setState({
      email: '',
      name: '',
      restaurant: '',
      address: '',
      notes: '',
      showModal: true,
      showPrompt: false,
    })
  }

  closeModal = () => {
    this.setState({ showModal: false, showPrompt: true })
  }

  render(props) {
    return (
      <>
        <Form
          name="subscribe"
          onSubmit={this.handleSubmit}
          overlay={this.state.visible}
          onClick={this.closeModal}
        >
          <Modal visible={this.state.showModal}>

          </Modal>

          <Input
            name="name"
            type="name"
            placeholder="Name*"
            value={this.state.name}
            onChange={this.handleInputChange}
            required
          />
          <Input
            name="email"
            type="email"
            placeholder="Email*"
            value={this.state.email}
            onChange={this.handleInputChange}
            required
          />
          <Input
            name="restaurant"
            type="restaurant"
            placeholder="Restaurant*"
            value={this.state.restaurant}
            onChange={this.handleInputChange}
            required
          />
          <Input
            name="address"
            type="address"
            placeholder="Address*"
            value={this.state.address}
            onChange={this.handleInputChange}
            required
          />
          <TextArea
            name="notes"
            type="notes"
            placeholder="Notes"
            value={this.state.notes}
            onChange={this.handleInputChange}
            required
          />
          <Submit className="button" name="submit" type="submit" value="Send" />
        </Form>
      </>
    )
  }
}

EmailCapture.propTypes = {
  data: PropTypes.object,
}

export default EmailCapture
<|endoftext|>


<commit_before>var curryFn = {
    /* First we need the curry function
        expects a function as its argument
        */
    curry: function(fn) {
        // Variable with the arguments length
        argsLength = fn.length;

        return (function resolver() {
            // variable with the copy of the arguments received
            var argsReceived = Array.prototype.slice.call(arguments);
            // return function
            return function() {
                // argsReceived copy
                var localArgs = argsReceived.slice();
                Array.prototype.push.apply(localArgs, arguments);
                // compare the length of arguments we’ve received with the argsLength of our curried function
                var next = localArgs.length >= argsLength ? fn : resolver;
                return next.apply(null, localArgs);
            };
        }());
    }
};
<commit_msg>Improved code of curry function<commit_after>    /**
     * First we need the curry function inside the prototype of Function Class
     * @return {[type]} [description]
     */
    Function.prototype.curry = function() {
        // Variable with the arguments length
        var argsLength = this.length,
            self = this;

        return (function resolver() {
            // variable with the copy of the arguments received
            var argsReceived = Array.prototype.slice.call(arguments);
            // return function
            return function() {
                // argsReceived copy
                var localArgs = argsReceived.slice();
                Array.prototype.push.apply(localArgs, arguments);
                // compare the length of arguments we’ve received with the argsLength of our curried function
                var next = localArgs.length >= argsLength ? self : resolver;
                return next.apply(null, localArgs);
            };
        }());
    };
<|endoftext|>


<commit_before>require("./wscript/setup.js");
require("./cscript.js");
<commit_msg>Fixing linter (#226)<commit_after>"use strict";

require("./wscript/setup.js");
require("./cscript.js");
<|endoftext|>


<commit_before>/*jslint browser: true */

define([
	'underscore',
	'jquery',
	'backbone',
	'module',
	'models/LinkCollection',
	'models/PublicationContributorCollection'
], function(_, $, Backbone, module, LinkCollection, PublicationContributorCollection) {
	"use strict";

	var model = Backbone.Model.extend({
		urlRoot : module.config().scriptRoot + '/manager/services/mppublications',

		/*
		 * The contributors attribute is a backbone model. This model contains attributes whose value
		 * is a PublicationContributorCollection.
		 */
		defaults : function() {
			return {
				links: new LinkCollection(),
				contributors : new Backbone.Model()
			}
		},

		parse : function(response, options) {
			var links = this.get('links');
			var contributors = this.get('contributors');
			if (_.has(response, 'links') && response.links.length) {
				links.set(_.sortBy(response.links, 'rank'));
				response.links = links;
			}
			else {
				links.reset(null);
			}
			if (_.has(response, 'contributors')) {
				_.each(contributors.keys, function(contribType) {
					// Clear out collection if response doesn't contain the contribType
					if (!_.has(response.contributors, contribType)) {
						contributors.unset(contribType);
					}
				});
				_.each(response.contributors, function(contribs, contribType) {
					if (contributors.has(contribType)){
						contributors.get(contribType).set(contribs).sort();
					}
					else {
						contributors.set(contribType, new PublicationContributorCollection(contribs));
					}
				});

			}
			else {
				contributors.clear();
			}
			response.contributors = contributors;

			/*
				Need to remove interactions and text to work around an issue with some properties being returned that shouldn't be.
				When PUBSTWO-1272 has been resolved, this code can be removed.
		 	*/
			return _.omit(response, ['interactions', 'text']);
		},

		fetch : function(options) {
			var params = {
				data : {
					mimetype : 'json'
				}
			};
			if (_.isObject(options)) {
				_.extend(params, options);
			}
			return Backbone.Model.prototype.fetch.call(this, params);
		},

		/*
		 * @param {String} op - command that will be added to the url to perform an action on the pub
		 * @return {Jquery.Promise} - If the model is empty, resolves returning nothing. If not emtpy,
		 *     resolves with the received response if call succeeds, rejects with the validationErrors
		 *     array if the response contains validation errors, rejects with an error message if the failed response does
		 *     not contain validation errors.
		 */
		changeState : function(op) {
			var self = this;
			var deferred = $.Deferred();
			if (!this.isNew()) {
				$.ajax({
					url: this.urlRoot +  '/' + op,
					method : 'POST',
					headers : {
						'Accept' : 'application/json'
					},
					contentType : 'application/json',
					processData : false,
					data: '{"id" : ' + this.get('id') + '}',
					success : function(response) {
						deferred.resolve(response)
					},
					error : function(jqXHR, textStatus, error) {
						var resp = jqXHR.responseJSON;
						if (_.has(resp, 'validationErrors')
							&& _.isArray(resp.validationErrors)
							&& (resp.validationErrors.length > 0)) {
							self.set('validationErrors', resp.validationErrors);
							deferred.reject(resp);
						}
						else {
							deferred.reject('Unable to ' + op + ' the publication with error: ' + error);
						}
					}
				});
			}
			else {
				deferred.resolve();
			}
			return deferred.promise();
		},

		/*
		 * @return {Jquery.Promise} - resolves with the received response if the release succeeds, rejects with the validationErrors
		 *     array if the response contains validation errors, rejects with an error message if the failed response does
		 *     not contain validation errors.
		 */
		release : function() {
			return this.changeState('release');
		},

		/*
		 * @return {Jquery.Promise} - resolves with the received response if publish succeeds, rejects with the validationErrors
		 *     array if the response contains validation errors, rejects with an error message if the failed response does
		 *     not contain validation errors.
		 */
		publish : function() {
			return this.changeState('publish');
		},

		save : function(attributes, options) {
			/* Don't send validationErrors to the server */
			this.unset('validationErrors');
			return Backbone.Model.prototype.save.apply(this, arguments);
		}
	});

	return model;
});
<commit_msg>Fixed PublicationModel to handle the situation where the contributors and links properties are missing.<commit_after>/*jslint browser: true */

define([
	'underscore',
	'jquery',
	'backbone',
	'module',
	'models/LinkCollection',
	'models/PublicationContributorCollection'
], function(_, $, Backbone, module, LinkCollection, PublicationContributorCollection) {
	"use strict";

	var model = Backbone.Model.extend({
		urlRoot : module.config().scriptRoot + '/manager/services/mppublications',

		/*
		 * The contributors attribute is a backbone model. This model contains attributes whose value
		 * is a PublicationContributorCollection.
		 */
		defaults : function() {
			return {
				links: new LinkCollection(),
				contributors : new Backbone.Model()
			}
		},

		parse : function(response, options) {
			var links = (this.has('links')) ? this.get('links') : new LinkCollection();
			var contributors = (this.has('contributors')) ? this.get('contributors') : new Backbone.Model();
			if (_.has(response, 'links') && response.links.length) {
				links.set(_.sortBy(response.links, 'rank'));
			}
			else {
				links.reset(null);
			}
			response.links = links;

			if (_.has(response, 'contributors')) {
				_.each(contributors.keys, function(contribType) {
					// Clear out collection if response doesn't contain the contribType
					if (!_.has(response.contributors, contribType)) {
						contributors.unset(contribType);
					}
				});
				_.each(response.contributors, function(contribs, contribType) {
					if (contributors.has(contribType)){
						contributors.get(contribType).set(contribs).sort();
					}
					else {
						contributors.set(contribType, new PublicationContributorCollection(contribs));
					}
				});

			}
			else {
				contributors.clear();
			}
			response.contributors = contributors;

			/*
				Need to remove interactions and text to work around an issue with some properties being returned that shouldn't be.
				When PUBSTWO-1272 has been resolved, this code can be removed.
		 	*/
			return _.omit(response, ['interactions', 'text']);
		},

		fetch : function(options) {
			var params = {
				data : {
					mimetype : 'json'
				}
			};
			if (_.isObject(options)) {
				_.extend(params, options);
			}
			return Backbone.Model.prototype.fetch.call(this, params);
		},

		/*
		 * @param {String} op - command that will be added to the url to perform an action on the pub
		 * @return {Jquery.Promise} - If the model is empty, resolves returning nothing. If not emtpy,
		 *     resolves with the received response if call succeeds, rejects with the validationErrors
		 *     array if the response contains validation errors, rejects with an error message if the failed response does
		 *     not contain validation errors.
		 */
		changeState : function(op) {
			var self = this;
			var deferred = $.Deferred();
			if (!this.isNew()) {
				$.ajax({
					url: this.urlRoot +  '/' + op,
					method : 'POST',
					headers : {
						'Accept' : 'application/json'
					},
					contentType : 'application/json',
					processData : false,
					data: '{"id" : ' + this.get('id') + '}',
					success : function(response) {
						deferred.resolve(response)
					},
					error : function(jqXHR, textStatus, error) {
						var resp = jqXHR.responseJSON;
						if (_.has(resp, 'validationErrors')
							&& _.isArray(resp.validationErrors)
							&& (resp.validationErrors.length > 0)) {
							self.set('validationErrors', resp.validationErrors);
							deferred.reject(resp);
						}
						else {
							deferred.reject('Unable to ' + op + ' the publication with error: ' + error);
						}
					}
				});
			}
			else {
				deferred.resolve();
			}
			return deferred.promise();
		},

		/*
		 * @return {Jquery.Promise} - resolves with the received response if the release succeeds, rejects with the validationErrors
		 *     array if the response contains validation errors, rejects with an error message if the failed response does
		 *     not contain validation errors.
		 */
		release : function() {
			return this.changeState('release');
		},

		/*
		 * @return {Jquery.Promise} - resolves with the received response if publish succeeds, rejects with the validationErrors
		 *     array if the response contains validation errors, rejects with an error message if the failed response does
		 *     not contain validation errors.
		 */
		publish : function() {
			return this.changeState('publish');
		},

		save : function(attributes, options) {
			/* Don't send validationErrors to the server */
			this.unset('validationErrors');
			return Backbone.Model.prototype.save.apply(this, arguments);
		}
	});

	return model;
});
<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.12.3
(function() {
  'use strict';
  module.exports = function(dd, that) {
    return dd.drive({
      it: "include 'ddry'",
      i: [],
      e: 'node_modules/ddry/index.js'
    });
  };

}).call(this);
<commit_msg>Misplaced file removed<commit_after><|endoftext|>


<commit_before>var homepage = "http://192.168.1.8/wm/admin/conteudo/sync/"

// Criação do Banco de Dados
var db = new Dexie("WMRepresentacoes");
// s = 0 -> Não sincronizado / Criado aqui
// s = 1 -> Não sincronizado / Criado lá
// s = 2 -> Sincronizado
db.version(1).stores({
	clientes: "++idx, id, razaoSocial, nomeFantasia, cnpj, inscEstadual, suframa, endereco, complemento, cep, bairro, cidade, estado, telefone1, telefone2, fax, email1, email2, informacoesAdicionais, contato1, cargoContato1, telefoneContato1, emailContato1, contato2, cargoContato2, telefoneContato2, emailContato2, ultimaCompra, s",
	representadas: "++idx, id, razaoSocial, nomeFantasia, cnpj, comissao, telefone, email, informacoesAdicionais, contato1, cargoContato1, telefoneContato1, emailContato1, contato2, cargoContato2, telefoneContato2, emailContato2, cep, endereco, complemento, bairro, cidade, estado, s",
	produtos: "++idx, id, representada, nome, codigo, ipi, precoTabela, precoTabela2, precoTabela3, precoTabela4, s",
	listadeprodutos: "++idx, id, produto, quantidade, descontos, precoLiquido, subtotal, pedido, s",
	pedidos: "++idx, id, representada, cliente, vendedor, dataEmissao, dataFaturamento, quantidadeTotal, totalSemDescontos, semitotal, total, transportadora, condicaoDePagamento, informacoesAdicionais, status, s"
});
db.open();

function mostrarTodosOsClientes() {
	var a = '';
	db.clientes.each(function(c){
		a = a + "
Cliente: "+ c.nomeFantasia +" - CNPJ: "+ c.cnpj +" -
";
		var x = document.getElementById("listagem");
		x.innerHTML = a;
	});
}

$(document).ready(function(){

	$.mask.definitions['~']='[ 9]';
	$(".cnpj_field").mask("99.999.999/9999-99");
	$(".cep_field").mask("99999-999");
	$(".phone_field").mask("(99) ~9999-9999");
	$(".inscEstadual_field").mask("99999999-9");

	$("#cad-cliente_form").submit(function(e){
		e.preventDefault();

		db.clientes.add({
			id: 0,
			razaoSocial: $("#razaoSocial").val(),
			nomeFantasia: $("#nomeFantasia").val(),
			cnpj: $("#cnpj").val(),
			inscEstadual: $("#inscEstadual").val(),
			suframa: $("#suframa").val(),
			endereco: $("#endereco").val(),
			complemento: $("#complemento").val(),
			cep: $("#cep").val(),
			bairro: $("#bairro").val(),
			cidade: $("#cidade").val(),
			estado: $("#estado").val(),
			telefone1: $("#telefone1").val(),
			telefone2: $("#telefone2").val(),
			email1: $("#email1").val(),
			email2: $("#email2").val(),
			informacoesAdicionais: $("#informacoesAdicionais").val(),
			contato1: $("#contato1").val(),
			cargoContato1: $("#cargoContato1").val(),
			telefoneContato1: $("#telefoneContato1").val(),
			emailContato1: $("#emailContato1").val(),
			contato2: $("#contato2").val(),
			cargoContato2: $("#cargoContato2").val(),
			telefoneContato2: $("#telefoneContato2").val(),
			emailContato2: $("#emailContato2").val(),
			ultimaCompra: $("#ultimaCompra").val(),
			s: 0,
		}).then(function(){
			window.location.href = "../index.html";
		});
	});

	$("#limpa_form").click(function(){
		$(this).parent()[0].reset();
	});

	$("#sincronizar").click(function(){
		var f = 0;
		db.transaction("r", db.clientes, db.representadas, db.produtos, db.listadeprodutos, db.pedidos, function(){
			db.clientes.where("s").below(2).each(function(c){
				if( c.s == 0 ) // Nova entrada
				{
					$.ajax({
						type: 'GET',
						url: homepage + "clientes.php",
						dataType: "jsonp",
						crossDomain: true,
						data: "opt=2&razaoSocial=" + c.razaoSocial + "&nomeFantasia=" + c.nomeFantasia + "&CNPJ=" + c.cnpj + "&telefone1=" + c.telefone1 + "&telefone2=" + c.telefone2 + "&email1=" + c.email1 + "&email2=" + c.email2 + "&inscEstadual=" + c.inscEstadual + "&suframa=" + c.suframa + "&informacoesAdicionais=" + c.informacoesAdicionais + "&contato1=" + c.contato1 + "&cargoContato1=" + c.cargoContato1 + "&telefoneContato1=" + c.telefoneContato1 + "&emailContato1=" + c.emailContato1 + "&contato2=" + c.contato2 + "&cargoContato2=" + c.cargoContato2 + "&telefoneContato2=" + c.telefoneContato2 + "&emailContato2=" + c.emailContato2 + "&cep=" + c.cep + "&endereco=" + c.endereco + "&complemento=" + c.complemento + "&bairro=" + c.bairro + "&cidade=" + c.cidade + "&estado=" + c.estado,
						sucess: function(){
							console.log("Success 1");
						},
						error: function(e) {
							console.error(e);
						}
					});
				}
				else if( c.s == 1 )
				{
					$.ajax({
						type: 'GET',
						url: homepage + "clientes.php",
						dataType: "jsonp",
						crossDomain: true,
						data: "opt=3&razaoSocial=" + c.razaoSocial + "&nomeFantasia=" + c.nomeFantasia + "&CNPJ=" + c.cnpj + "&telefone1=" + c.telefone1 + "&telefone2=" + c.telefone2 + "&email1=" + c.email1 + "&email2=" + c.email2 + "&inscEstadual=" + c.inscEstadual + "&suframa=" + c.suframa + "&informacoesAdicionais=" + c.informacoesAdicionais + "&contato1=" + c.contato1 + "&cargoContato1=" + c.cargoContato1 + "&telefoneContato1=" + c.telefoneContato1 + "&emailContato1=" + c.emailContato1 + "&contato2=" + c.contato2 + "&cargoContato2=" + c.cargoContato2 + "&telefoneContato2=" + c.telefoneContato2 + "&emailContato2=" + c.emailContato2 + "&cep=" + c.cep + "&endereco=" + c.endereco + "&complemento=" + c.complemento + "&bairro=" + c.bairro + "&cidade=" + c.cidade + "&estado=" + c.estado + "&id=" + c.id,
						sucess: function(){
							console.log("Success 2");
						},
						error: function(e) {
							console.error(e);
						}
					});
				}
			});
		}).then(function(){
			// Dados enviados com sucesso
			// Agora receber tudo
			$.ajax({
				type: 'GET',
				url: homepage + "clientes.php?callback=successClients&opt=1",
				dataType: "jsonp",
				crossDomain: true,
				jsonpCallback: "successClients",
				jsonp: false,
				sucess: successClients,
				error: function(a, b, e) {
					console.log(a);
					console.log(b);
					console.error(e);
				}
			});
		});
	});

	$("#sinc_result").click(function(){
		$("#sinc_result").hide(1000);
	});
});

function successClients(data) {
	db.clientes.clear().then(function(){
		for( i = 0; a = data[i]; ++i )
		{
			a = JSON.parse(a);

			db.clientes.add({
				id: a.id,
				razaoSocial: a.razaoSocial,
				nomeFantasia: a.nomeFantasia,
				cnpj: a.CNPJ,
				inscEstadual: a.inscEstadual,
				suframa: a.suframa,
				endereco: a.endereco,
				complemento: a.complemento,
				cep: a.cep,
				bairro: a.bairro,
				cidade: a.cidade,
				estado: a.estado,
				telefone1: a.telefone1,
				telefone2: a.telefone2,
				email1: a.email1,
				email2: a.email2,
				informacoesAdicionais: a.informacoesAdicionais,
				contato1: a.contato1,
				cargoContato1: a.cargoContato1,
				telefoneContato1: a.telefoneContato1,
				emailContato1: a.emailContato1,
				contato2: a.contato2,
				cargoContato2: a.cargoContato2,
				telefoneContato2: a.telefoneContato2,
				emailContato2: a.emailContato2,
				ultimaCompra: a.ultimaCompra,
				s: 2,
			});
			$("#index_content").append("" + i + " - " + a.razaoSocial + "
");
		}

		$("#sinc_result").append("Dados sincronizados com sucesso.");
		$("#sinc_result").show(1000);
	});

}<commit_msg>Teste<commit_after>var homepage = "http://192.168.1.8/wm/admin/conteudo/sync/"

// Criação do Banco de Dados
var db = new Dexie("WMRepresentacoes");
// s = 0 -> Não sincronizado / Criado aqui
// s = 1 -> Não sincronizado / Criado lá
// s = 2 -> Sincronizado
db.version(1).stores({
	clientes: "++idx, id, razaoSocial, nomeFantasia, cnpj, inscEstadual, suframa, endereco, complemento, cep, bairro, cidade, estado, telefone1, telefone2, fax, email1, email2, informacoesAdicionais, contato1, cargoContato1, telefoneContato1, emailContato1, contato2, cargoContato2, telefoneContato2, emailContato2, ultimaCompra, s",
	representadas: "++idx, id, razaoSocial, nomeFantasia, cnpj, comissao, telefone, email, informacoesAdicionais, contato1, cargoContato1, telefoneContato1, emailContato1, contato2, cargoContato2, telefoneContato2, emailContato2, cep, endereco, complemento, bairro, cidade, estado, s",
	produtos: "++idx, id, representada, nome, codigo, ipi, precoTabela, precoTabela2, precoTabela3, precoTabela4, s",
	listadeprodutos: "++idx, id, produto, quantidade, descontos, precoLiquido, subtotal, pedido, s",
	pedidos: "++idx, id, representada, cliente, vendedor, dataEmissao, dataFaturamento, quantidadeTotal, totalSemDescontos, semitotal, total, transportadora, condicaoDePagamento, informacoesAdicionais, status, s"
});
db.open();

function mostrarTodosOsClientes() {
	var a = '';
	db.clientes.each(function(c){
		a = a + "
Cliente: "+ c.nomeFantasia +" - CNPJ: "+ c.cnpj +" -
";
		var x = document.getElementById("listagem");
		x.innerHTML = a;
	});
}

$(document).ready(function(){

	$.mask.definitions['~']='[ 9]';
	$(".cnpj_field").mask("99.999.999/9999-99");
	$(".cep_field").mask("99999-999");
	$(".phone_field").mask("(99) ~9999-9999");
	$(".inscEstadual_field").mask("99999999-9");

	$("#cad-cliente_form").submit(function(e){
		e.preventDefault();

		db.clientes.add({
			id: 0,
			razaoSocial: $("#razaoSocial").val(),
			nomeFantasia: $("#nomeFantasia").val(),
			cnpj: $("#cnpj").val(),
			inscEstadual: $("#inscEstadual").val(),
			suframa: $("#suframa").val(),
			endereco: $("#endereco").val(),
			complemento: $("#complemento").val(),
			cep: $("#cep").val(),
			bairro: $("#bairro").val(),
			cidade: $("#cidade").val(),
			estado: $("#estado").val(),
			telefone1: $("#telefone1").val(),
			telefone2: $("#telefone2").val(),
			email1: $("#email1").val(),
			email2: $("#email2").val(),
			informacoesAdicionais: $("#informacoesAdicionais").val(),
			contato1: $("#contato1").val(),
			cargoContato1: $("#cargoContato1").val(),
			telefoneContato1: $("#telefoneContato1").val(),
			emailContato1: $("#emailContato1").val(),
			contato2: $("#contato2").val(),
			cargoContato2: $("#cargoContato2").val(),
			telefoneContato2: $("#telefoneContato2").val(),
			emailContato2: $("#emailContato2").val(),
			ultimaCompra: $("#ultimaCompra").val(),
			s: 0,
		}).then(function(){
			window.location.href = "../index.html";
		});
	});

	$("#limpa_form").click(function(){
		$(this).parent()[0].reset();
	});

	$("#sincronizar").click(function(){
		var f = 0;
		db.transaction("r", db.clientes, db.representadas, db.produtos, db.listadeprodutos, db.pedidos, function(){
			db.clientes.where("s").below(2).each(function(c){
				if( c.s == 0 ) // Nova entrada
				{
					$.ajax({
						type: 'GET',
						url: homepage + "clientes.php",
						dataType: "jsonp",
						crossDomain: true,
						data: "opt=2&razaoSocial=" + c.razaoSocial + "&nomeFantasia=" + c.nomeFantasia + "&CNPJ=" + c.cnpj + "&telefone1=" + c.telefone1 + "&telefone2=" + c.telefone2 + "&email1=" + c.email1 + "&email2=" + c.email2 + "&inscEstadual=" + c.inscEstadual + "&suframa=" + c.suframa + "&informacoesAdicionais=" + c.informacoesAdicionais + "&contato1=" + c.contato1 + "&cargoContato1=" + c.cargoContato1 + "&telefoneContato1=" + c.telefoneContato1 + "&emailContato1=" + c.emailContato1 + "&contato2=" + c.contato2 + "&cargoContato2=" + c.cargoContato2 + "&telefoneContato2=" + c.telefoneContato2 + "&emailContato2=" + c.emailContato2 + "&cep=" + c.cep + "&endereco=" + c.endereco + "&complemento=" + c.complemento + "&bairro=" + c.bairro + "&cidade=" + c.cidade + "&estado=" + c.estado,
						sucess: function(){
							console.log("Success 1");
						},
						error: function(e) {
							console.error(e);
						}
					});
				}
				else if( c.s == 1 )
				{
					$.ajax({
						type: 'GET',
						url: homepage + "clientes.php",
						dataType: "jsonp",
						crossDomain: true,
						data: "opt=3&razaoSocial=" + c.razaoSocial + "&nomeFantasia=" + c.nomeFantasia + "&CNPJ=" + c.cnpj + "&telefone1=" + c.telefone1 + "&telefone2=" + c.telefone2 + "&email1=" + c.email1 + "&email2=" + c.email2 + "&inscEstadual=" + c.inscEstadual + "&suframa=" + c.suframa + "&informacoesAdicionais=" + c.informacoesAdicionais + "&contato1=" + c.contato1 + "&cargoContato1=" + c.cargoContato1 + "&telefoneContato1=" + c.telefoneContato1 + "&emailContato1=" + c.emailContato1 + "&contato2=" + c.contato2 + "&cargoContato2=" + c.cargoContato2 + "&telefoneContato2=" + c.telefoneContato2 + "&emailContato2=" + c.emailContato2 + "&cep=" + c.cep + "&endereco=" + c.endereco + "&complemento=" + c.complemento + "&bairro=" + c.bairro + "&cidade=" + c.cidade + "&estado=" + c.estado + "&id=" + c.id,
						sucess: function(){
							console.log("Success 2");
						},
						error: function(e) {
							console.error(e);
						}
					});
				}
			});
		}).then(function(){
			// Dados enviados com sucesso
			// Agora receber tudo
			$.ajax({
				type: 'GET',
				url: homepage + "clientes.php?callback=successClients&opt=1",
				dataType: "jsonp",
				crossDomain: true,
				jsonpCallback: "successClients",
				jsonp: false,
				sucess: successClients,
				error: function(a, b, e) {
					console.log(a);
					console.log(b);
					console.error(e);
					$("#index_content").append(e);
				}
			});
		});
	});

	$("#sinc_result").click(function(){
		$("#sinc_result").hide(1000);
	});
});

function successClients(data) {
	db.clientes.clear().then(function(){
		for( i = 0; a = data[i]; ++i )
		{
			a = JSON.parse(a);

			db.clientes.add({
				id: a.id,
				razaoSocial: a.razaoSocial,
				nomeFantasia: a.nomeFantasia,
				cnpj: a.CNPJ,
				inscEstadual: a.inscEstadual,
				suframa: a.suframa,
				endereco: a.endereco,
				complemento: a.complemento,
				cep: a.cep,
				bairro: a.bairro,
				cidade: a.cidade,
				estado: a.estado,
				telefone1: a.telefone1,
				telefone2: a.telefone2,
				email1: a.email1,
				email2: a.email2,
				informacoesAdicionais: a.informacoesAdicionais,
				contato1: a.contato1,
				cargoContato1: a.cargoContato1,
				telefoneContato1: a.telefoneContato1,
				emailContato1: a.emailContato1,
				contato2: a.contato2,
				cargoContato2: a.cargoContato2,
				telefoneContato2: a.telefoneContato2,
				emailContato2: a.emailContato2,
				ultimaCompra: a.ultimaCompra,
				s: 2,
			});
			$("#index_content").append("" + i + " - " + a.razaoSocial + "
");
		}

		$("#sinc_result").append("Dados sincronizados com sucesso.");
		$("#sinc_result").show(1000);
	});

}<|endoftext|>


<commit_before>function Time() {
    this._start = 0;
    this._now = 0;
    this._prev = 0;
    this._delta = 0;
    this._deltaSeconds = 0;
    this._elapsedSeconds = 0;
    this._frames = 0;
    this._stopped = false;

    this._fpsUpdateFrequency = 3000; //3s
    this._fpsFrames = 0;
    this._fpsTime = 0;
    this._fps = 0;
}

Time.prototype._update = function(now) {
    this._prev = this._now;
    this._now = now;
    this._delta = this._now - this._prev;

    this._deltaSeconds = this._delta / 1000;
    this._elapsedSeconds = (this._now - this._start) / 1000;

    this._frames++;

    if (this._fpsTime > this._fpsUpdateFrequency) {
        this._fps = Math.floor(this._fpsFrames / (this._fpsTime / 1000)*10)/10;
        this._fpsTime = 0;
        this._fpsFrames = 0;
    }
    else {
        this._fpsTime += this._delta;
        this._fpsFrames++;
    }
}

Time.prototype._stop = function() {
    this._stopped = true;
    this._delta = 0;
    this._deltaSeconds = 0;

    this._fpsFrames = 0;
    this._fpsTime = 0;
    this._fps = 0;
}

Time.prototype._restart = function(now) {
    this._start = now;
    this._now = now;
    this._prev = now;
    this._delta = 0;
    this._frames = 0;
    this._stopped = false;
    this._deltaSeconds = 0;
    this._elapsedSeconds = 0;

    this._fpsFrames = 0;
    this._fpsTime = 0;
    this._fps = 0;
}

Time.prototype._resume = function(now) {
    this._now = now;
    this._prev = now;
    this._delta = 0;
    this._stopped = false;

    this._fpsFrames = 0;
    this._fpsTime = 0;
    this._fps = 0;
}

Time.prototype.getDelta = function() {
    return this._delta;
}

Time.prototype.getDeltaSeconds = function() {
    return this._deltaSeconds;
}

//FIXME: cache that?
Time.prototype.getElapsedSeconds = function() {
    return this._elapsedSeconds;
}

Time.prototype.getElapsedFrames = function() {
    return this._frames;
}

Time.prototype.getFPS = function() {
    return this._fps;
}

module.exports = Time;
<commit_msg>Starting counting frames from -1<commit_after>function Time() {
    this._start = 0;
    this._now = 0;
    this._prev = 0;
    this._delta = 0;
    this._deltaSeconds = 0;
    this._elapsedSeconds = 0;
    this._frames = -1;
    this._stopped = false;

    this._fpsUpdateFrequency = 3000; //3s
    this._fpsFrames = 0;
    this._fpsTime = 0;
    this._fps = 0;
}

Time.prototype._update = function(now) {
    this._prev = this._now;
    this._now = now;
    this._delta = this._now - this._prev;

    this._deltaSeconds = this._delta / 1000;
    this._elapsedSeconds = (this._now - this._start) / 1000;

    this._frames++;

    if (this._fpsTime > this._fpsUpdateFrequency) {
        this._fps = Math.floor(this._fpsFrames / (this._fpsTime / 1000)*10)/10;
        this._fpsTime = 0;
        this._fpsFrames = 0;
    }
    else {
        this._fpsTime += this._delta;
        this._fpsFrames++;
    }
}

Time.prototype._stop = function() {
    this._stopped = true;
    this._delta = 0;
    this._deltaSeconds = 0;

    this._fpsFrames = 0;
    this._fpsTime = 0;
    this._fps = 0;
}

Time.prototype._restart = function(now) {
    this._start = now;
    this._now = now;
    this._prev = now;
    this._delta = 0;
    this._frames = 0;
    this._stopped = false;
    this._deltaSeconds = 0;
    this._elapsedSeconds = 0;

    this._fpsFrames = 0;
    this._fpsTime = 0;
    this._fps = 0;
}

Time.prototype._resume = function(now) {
    this._now = now;
    this._prev = now;
    this._delta = 0;
    this._stopped = false;

    this._fpsFrames = 0;
    this._fpsTime = 0;
    this._fps = 0;
}

Time.prototype.getDelta = function() {
    return this._delta;
}

Time.prototype.getDeltaSeconds = function() {
    return this._deltaSeconds;
}

//FIXME: cache that?
Time.prototype.getElapsedSeconds = function() {
    return this._elapsedSeconds;
}

Time.prototype.getElapsedFrames = function() {
    return this._frames;
}

Time.prototype.getFPS = function() {
    return this._fps;
}

module.exports = Time;
<|endoftext|>


<commit_before>var z = d3.scaleOrdinal()
    .range(["#590CE8", "#C500DB", "#E80C35", "#AAAAAA", "#a05d56", "#d0743c", "#ff8c00"]);

var corner1 = L.latLng(49.254074, -123.003616),
  corner2 = L.latLng(49.162721, -122.857018),
bounds = L.latLngBounds(corner1, corner2);

var map = L.map('map', {
    renderer: L.svg(),
    maxBounds: bounds
  })
  .setView([49.205718, -122.910956], 13);

var mapLink = 'OpenStreetMap';

L.tileLayer(
  'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
  {
    attribution: '© ' + mapLink + ' Contributors',
    maxZoom: 18,
  }
).addTo(map);

var svgLayer = L.svg();
svgLayer.addTo(map);

var svg = d3.select("#map").select("svg");
var g = d3.select("#map").select("svg").select('g');
g.attr("class", "leaflet-zoom-hide");

var viewMapInfo = function(d) {
    d3.select("#infoBox")
        .style("left", function(temp) {
            var shift = (d3.event.pageX + 5) + "px";
            if (d3.event.pageX > 500) {
                shift = (d3.event.pageX - 330) + "px";
            }
            return shift;
        })
        .style("top", function(temp) {
            var shift = (d3.event.pageY - 12) + "px";
            if (d.Y < 49.20752788) {
                shift = (d3.event.pageY - 420) + "px";
            }
            return shift;
        });

    d3.select("#area").text(d.Area);
    d3.select("#type").text(d.Type);
    d3.select("#neighbourhood").text(d.Neighbourhood);
    d3.select("#colour").text(d["Colour/Material"]);
    if (d.Style === "-") {
        d3.select("#styleLine").classed("hidden", true);
    } else {
        d3.select("#style").text(d.Style);
        d3.select("#styleLine").classed("hidden", false);
    }
    if (d["Bowl Height"] === "-") {
        d3.select("#bowlLine").classed("hidden", true);
    } else {
        d3.select("#height").text(d["Bowl Height"]);
        d3.select("#bowlLine").classed("hidden", false);
    }
    d3.select("#objid").text(d.OBJECTID);

    d3.select("#infoImg").attr("src", "img/" + d.OBJECTID + ".jpg");

    d3.select("#infoBox").classed("hidden", false);
};

d3.csv("data/fountains.csv", function(error, fountains) {
    if (error) throw error;

    fountains.forEach(function(d) {
      d.LatLng = new L.LatLng(d.Y, d.X);
    });

    var fountainCircles = g.selectAll(".fountain")
        .data(fountains)
        .enter()
        .append("circle")
        .attr("class", "fountain")
        .attr("r", 3)
        .style("fill", function(d) {
            return z(d.Type);
        })
        .on("mouseover", viewMapInfo)
        .on("mouseout", function(d) {
            d3.select("#infoBox").classed("hidden", true);
        });

    map.on("zoomend", update);
    update();

    function update() {
      fountainCircles.attr("transform", function(d) {
        return "translate(" +
          map.latLngToLayerPoint(d.LatLng).x + ","+
          map.latLngToLayerPoint(d.LatLng).y + ")";
      });
    }
});<commit_msg>Resize circles with zoom<commit_after>var z = d3.scaleOrdinal()
    .range(["#590CE8", "#C500DB", "#E80C35", "#AAAAAA", "#a05d56", "#d0743c", "#ff8c00"]);

var corner1 = L.latLng(49.254074, -123.003616),
  corner2 = L.latLng(49.162721, -122.857018),
bounds = L.latLngBounds(corner1, corner2);

var map = L.map('map', {
    renderer: L.svg(),
    maxBounds: bounds,
    minZoom: 14
  })
  .setView([49.205718, -122.910956], 13);

var mapLink = 'OpenStreetMap';

L.tileLayer(
  'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
  {
    attribution: '© ' + mapLink + ' Contributors',
    maxZoom: 18,
  }
).addTo(map);

var svgLayer = L.svg();
svgLayer.addTo(map);

var svg = d3.select("#map").select("svg");
var g = d3.select("#map").select("svg").select('g');
g.attr("class", "leaflet-zoom-hide");

var viewMapInfo = function(d) {
    d3.select("#infoBox")
        .style("left", function(temp) {
            var shift = (d3.event.pageX + 5) + "px";
            if (d3.event.pageX > 500) {
                shift = (d3.event.pageX - 330) + "px";
            }
            return shift;
        })
        .style("top", function(temp) {
            var shift = (d3.event.pageY - 12) + "px";
            if (d.Y < 49.20752788) {
                shift = (d3.event.pageY - 420) + "px";
            }
            return shift;
        });

    d3.select("#area").text(d.Area);
    d3.select("#type").text(d.Type);
    d3.select("#neighbourhood").text(d.Neighbourhood);
    d3.select("#colour").text(d["Colour/Material"]);
    if (d.Style === "-") {
        d3.select("#styleLine").classed("hidden", true);
    } else {
        d3.select("#style").text(d.Style);
        d3.select("#styleLine").classed("hidden", false);
    }
    if (d["Bowl Height"] === "-") {
        d3.select("#bowlLine").classed("hidden", true);
    } else {
        d3.select("#height").text(d["Bowl Height"]);
        d3.select("#bowlLine").classed("hidden", false);
    }
    d3.select("#objid").text(d.OBJECTID);

    d3.select("#infoImg").attr("src", "img/" + d.OBJECTID + ".jpg");

    d3.select("#infoBox").classed("hidden", false);
};

d3.csv("data/fountains.csv", function(error, fountains) {
    if (error) throw error;

    fountains.forEach(function(d) {
      d.LatLng = new L.LatLng(d.Y, d.X);
    });

    var fountainCircles = g.selectAll(".fountain")
        .data(fountains)
        .enter()
        .append("circle")
        .attr("class", "fountain")
        .style("fill", function(d) {
            return z(d.Type);
        })
        .on("mouseover", viewMapInfo)
        .on("mouseout", function(d) {
            d3.select("#infoBox").classed("hidden", true);
        });

    map.on("zoomend", update);
    update();

    function update() {
      fountainCircles.attr("transform", function(d) {
        return "translate(" +
          map.latLngToLayerPoint(d.LatLng).x + ","+
          map.latLngToLayerPoint(d.LatLng).y + ")";
      })
      .attr("r", function(d) {
        switch (map.getZoom()) {
          case 15:
            return 4;
            break;
          case 16:
            return 5;
            break;
          case 17:
            return 8;
            break;
          case 18:
            return 12;
            break;
          default:
            return 3;
        }
      });
    }
});<|endoftext|>


<commit_before>// Used https://github.com/mapbox/geojson.io/blob/gh-pages/data/share.html as the basis for this template

shareTemplate = "<!DOCTYPE html> \
 \
 \
  <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no' /> \
   \
   \
   \
  <link href='http://api.tiles.mapbox.com/mapbox.js/v1.6.2/mapbox.css' rel='stylesheet' /> \
 \
 \

 \

 \
\
\
"<commit_msg>share template legend styling<commit_after>// Used https://github.com/mapbox/geojson.io/blob/gh-pages/data/share.html as the basis for this template

shareTemplate = "<!DOCTYPE html> \
 \
 \
  <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no' /> \
   \
   \
   \
  <link href='http://api.tiles.mapbox.com/mapbox.js/v1.6.2/mapbox.css' rel='stylesheet' /> \
 \
 \

 \

 \
\
\
"<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting la<commit_msg>Cleaned out the intertubes<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting las<|endoftext|>


<commit_before>function format(flat) {

  var map = {};
  flat.forEach(function(a) {
    map[a["@id"]] = a;
  });

  var ontology = {};

  (function(a) {
    ontology.version = a["http://www.w3.org/2002/07/owl#versionInfo"][0]["@value"];
    ontology.label = a["http://www.w3.org/2000/01/rdf-schema#label"].find(function(a) {
      return a["@language"] === "ja";
    })["@value"];
    ontology.comment = a["http://www.w3.org/2000/01/rdf-schema#comment"].find(function(a) {
      return a["@language"] === "ja";
    })["@value"];
  })(map["http://imi.go.jp/ns/core/rdf"]);

  var dig = function(id) {
    var a = map[id];
    var json = {
      id: id,
      label: a["http://www.w3.org/2000/01/rdf-schema#label"].find(function(a) {
        return a["@language"] === "ja";
      })["@value"],
      comment: a["http://www.w3.org/2000/01/rdf-schema#comment"].find(function(a) {
        return a["@language"] === "ja";
      })["@value"]
    };

    json.children = flat.filter(function(a) {
      return (a["http://www.w3.org/2000/01/rdf-schema#subClassOf"] || []).find(function(b) {
        return b["@id"] === id;
      });
    }).map(function(a) {
      return dig(a["@id"]);
    });

    json.properties = (a["http://www.w3.org/2000/01/rdf-schema#subClassOf"] || []).filter(function(b) {
      return b["@id"].indexOf("_:") === 0;
    }).map(function(b) {
      return map[b["@id"]];
    }).map(function(b) {
      var id = b["http://www.w3.org/2002/07/owl#onProperty"][0]["@id"];
      var prop = {
        id: id,
        min: 0,
        range: map[id]["http://www.w3.org/2000/01/rdf-schema#range"][0]["@id"]
      };
      if (b["http://www.w3.org/2002/07/owl#maxQualifiedCardinality"]) prop.max = 1;
      if (b["http://www.w3.org/2002/07/owl#maxCardinality"]) prop.max = 1;
      return prop;
    });

    return json;
  };

  ontology.root = dig("http://imi.go.jp/ns/core/rdf#概念型");

  return ontology;
}

var defaultInstance = {
  "http://www.w3.org/2001/XMLSchema#string": "文字列",
  "http://www.w3.org/2002/07/owl#Thing": "http://example.org/",
  "http://www.w3.org/2001/XMLSchema#integer": 1234567890,
  "http://www.w3.org/2001/XMLSchema#nonNegativeInteger": 1234567890,
  "http://www.w3.org/2001/XMLSchema#date": "2017-05-11",
  "http://www.w3.org/2001/XMLSchema#time": "00:00:00",
  "http://www.w3.org/2001/XMLSchema#dateTime": "2017-05-11T00:00:00",
  "http://www.w3.org/2001/XMLSchema#decimal": 1234.56789,
  "http://www.w3.org/2001/XMLSchema#double": 10.0e25,
  "urn:un:unece:uncefact:codelist:standard:ISO:ISO3AlphaCurrencyCode:2012-08-31#ISO3AlphaCurrencyCodeContentType": "YEN"
};

fetch("https://imi.go.jp/ns/core/rdf.jsonld").then(function(a) {
  return a.json();
}).then(function(json) {
  return new Promise(function(resolve, reject) {
    jsonld.flatten(json, function(err, flat) {
      resolve(format(flat));
    });
  });
}).then(function(ontology) {
  console.log(ontology);

  $("#version").text(ontology.version);

  var render = function(anc) {
    var a = anc[anc.length - 1];
    var div = $("
");
    div.attr("id", a.label);

    $("#menu>ul").append($("
").css("text-indent", (anc.length - 1) + "em").append(
      $("").attr("href", "#" + a.label).text(a.label)));

    var ul = $("
").appendTo(div);
    anc.forEach(function(v, i) {
      var a = $("").attr("href", "#" + v.label).text(v.label);
      if (i === anc.length - 1) a = $("").text(v.label);
      ul.append($("
").append(a));
    });
    div.append($("
").text(a.comment));

    var compact = function(v) {
      return v.replace(/.*#/, "");
    };

    var instance1 = {
      "@context": "http://imi.go.jp/ns/core/context.jsonld"
    };
    var instance2 = {
      "@context": "http://imi.go.jp/ns/core/context.jsonld"
    };
    anc.forEach(function(v) {
      instance1["@type"] = compact(v.id);
      instance2["@type"] = compact(v.id);
      v.properties.forEach(function(w) {
        var val = defaultInstance[w.range] || {
          "@type": compact(w.range)
        };
        instance1[compact(w.id)] = w.max === 1 ? val : [val];
        instance2[compact(w.id)] = val;
      });
    });

    div.append($("<button>配列あり</button>").attr("value", JSON.stringify(instance1, null, "  ")));
    div.append($("<button>配列なし</button>").attr("value", JSON.stringify(instance2, null, "  ")));
    div.append($("
").text(JSON.stringify(instance2, null, "  ")));
    $("#container").append(div);

    a.children.forEach(function(v) {
      render(anc.concat(v));
    });
  };

  render([ontology.root]);

  $("button").click(function() {
    $(this).parent().find("pre").text($(this).val());
  });
});
<commit_msg>Add contentEditable to
<commit_after>function format(flat) {

  var map = {};
  flat.forEach(function(a) {
    map[a["@id"]] = a;
  });

  var ontology = {};

  (function(a) {
    ontology.version = a["http://www.w3.org/2002/07/owl#versionInfo"][0]["@value"];
    ontology.label = a["http://www.w3.org/2000/01/rdf-schema#label"].find(function(a) {
      return a["@language"] === "ja";
    })["@value"];
    ontology.comment = a["http://www.w3.org/2000/01/rdf-schema#comment"].find(function(a) {
      return a["@language"] === "ja";
    })["@value"];
  })(map["http://imi.go.jp/ns/core/rdf"]);

  var dig = function(id) {
    var a = map[id];
    var json = {
      id: id,
      label: a["http://www.w3.org/2000/01/rdf-schema#label"].find(function(a) {
        return a["@language"] === "ja";
      })["@value"],
      comment: a["http://www.w3.org/2000/01/rdf-schema#comment"].find(function(a) {
        return a["@language"] === "ja";
      })["@value"]
    };

    json.children = flat.filter(function(a) {
      return (a["http://www.w3.org/2000/01/rdf-schema#subClassOf"] || []).find(function(b) {
        return b["@id"] === id;
      });
    }).map(function(a) {
      return dig(a["@id"]);
    });

    json.properties = (a["http://www.w3.org/2000/01/rdf-schema#subClassOf"] || []).filter(function(b) {
      return b["@id"].indexOf("_:") === 0;
    }).map(function(b) {
      return map[b["@id"]];
    }).map(function(b) {
      var id = b["http://www.w3.org/2002/07/owl#onProperty"][0]["@id"];
      var prop = {
        id: id,
        min: 0,
        range: map[id]["http://www.w3.org/2000/01/rdf-schema#range"][0]["@id"]
      };
      if (b["http://www.w3.org/2002/07/owl#maxQualifiedCardinality"]) prop.max = 1;
      if (b["http://www.w3.org/2002/07/owl#maxCardinality"]) prop.max = 1;
      return prop;
    });

    return json;
  };

  ontology.root = dig("http://imi.go.jp/ns/core/rdf#概念型");

  return ontology;
}

var defaultInstance = {
  "http://www.w3.org/2001/XMLSchema#string": "文字列",
  "http://www.w3.org/2002/07/owl#Thing": "http://example.org/",
  "http://www.w3.org/2001/XMLSchema#integer": 1234567890,
  "http://www.w3.org/2001/XMLSchema#nonNegativeInteger": 1234567890,
  "http://www.w3.org/2001/XMLSchema#date": "2017-05-11",
  "http://www.w3.org/2001/XMLSchema#time": "00:00:00",
  "http://www.w3.org/2001/XMLSchema#dateTime": "2017-05-11T00:00:00",
  "http://www.w3.org/2001/XMLSchema#decimal": 1234.56789,
  "http://www.w3.org/2001/XMLSchema#double": 10.0e25,
  "urn:un:unece:uncefact:codelist:standard:ISO:ISO3AlphaCurrencyCode:2012-08-31#ISO3AlphaCurrencyCodeContentType": "YEN"
};

fetch("https://imi.go.jp/ns/core/rdf.jsonld").then(function(a) {
  return a.json();
}).then(function(json) {
  return new Promise(function(resolve, reject) {
    jsonld.flatten(json, function(err, flat) {
      resolve(format(flat));
    });
  });
}).then(function(ontology) {
  console.log(ontology);

  $("#version").text(ontology.version);

  var render = function(anc) {
    var a = anc[anc.length - 1];
    var div = $("
");
    div.attr("id", a.label);

    $("#menu>ul").append($("
").css("text-indent", (anc.length - 1) + "em").append(
      $("").attr("href", "#" + a.label).text(a.label)));

    var ul = $("
").appendTo(div);
    anc.forEach(function(v, i) {
      var a = $("").attr("href", "#" + v.label).text(v.label);
      if (i === anc.length - 1) a = $("").text(v.label);
      ul.append($("
").append(a));
    });
    div.append($("
").text(a.comment));

    var compact = function(v) {
      return v.replace(/.*#/, "");
    };

    var instance1 = {
      "@context": "http://imi.go.jp/ns/core/context.jsonld"
    };
    var instance2 = {
      "@context": "http://imi.go.jp/ns/core/context.jsonld"
    };
    anc.forEach(function(v) {
      instance1["@type"] = compact(v.id);
      instance2["@type"] = compact(v.id);
      v.properties.forEach(function(w) {
        var val = defaultInstance[w.range] || {
          "@type": compact(w.range)
        };
        instance1[compact(w.id)] = w.max === 1 ? val : [val];
        instance2[compact(w.id)] = val;
      });
    });

    div.append($("<button>配列あり</button>").attr("value", JSON.stringify(instance1, null, "  ")));
    div.append($("<button>配列なし</button>").attr("value", JSON.stringify(instance2, null, "  ")));
    div.append($("
").text(JSON.stringify(instance2, null, "  ")));
    $("#container").append(div);

    a.children.forEach(function(v) {
      render(anc.concat(v));
    });
  };

  render([ontology.root]);

  $("button").click(function() {
    $(this).parent().find("pre").text($(this).val());
  });
});
<|endoftext|>


<commit_before>document.body.classList.remove('site-left-aligned');
if(document.getElementById('watch7-video-container').style.backgroundColor == 'rgb(0, 0, 0)')document.body.classList.add('black-video-background')
<commit_msg>Update YT Native Center Layout/js/script.js<commit_after>document.body.classList.remove('site-left-aligned');
var tmp = setInterval(function(){
  if(document.getElementById('watch7-video-container').style.backgroundColor == 'rgb(0, 0, 0)')document.body.classList.add('black-video-background');
	if(document.readyState)clearInterval(tmp);
},250);
<|endoftext|>


<commit_before>/**
 * Created by Oleg Rusak on 08.01.2017.
 */

'use strict';
//  todo: lib di

class DebugService {
    static log (option, message, data) {
        if (!option.debug) {
            return null;
        }

        if (option.log) {
            option.log(message, data)
        } else {
            console.log(message, data)
        }
    }
}

module.exports = DebugService;
<commit_msg>- remove unused. use lib debug<commit_after><|endoftext|>


<commit_before>Package.describe({
  name: 'ardatan:angular-ts-compiler',
  version: '0.2.5',
  summary: 'Angular TypeScript Compiler Package',
  git: 'https://github.com/ardatan/angular-meteor',
  documentation: null
});

Npm.depends({
  'meteor-typescript': '0.8.10',
  '@angular/core': '5.0.0-rc.5',
  '@angular/common': '5.0.0-rc.5',
  '@angular/compiler': '5.0.0-rc.5',
  '@angular/compiler-cli': '5.0.0-rc.5',
  'typescript': '2.4.2'
});

Package.onUse(function(api) {
  api.versionsFrom('1.5.2.2');
  api.use([
    'ecmascript',
    'babel-compiler',
    'ardatan:angular-html-compiler@0.2.5',
    'ardatan:angular-scss-compiler@0.2.5'
  ], 'server');
  api.mainModule('index.js', 'server');
});
<commit_msg>chore(deps): renovate angular monorepo packages<commit_after>Package.describe({
  name: 'ardatan:angular-ts-compiler',
  version: '0.2.5',
  summary: 'Angular TypeScript Compiler Package',
  git: 'https://github.com/ardatan/angular-meteor',
  documentation: null
});

Npm.depends({
  'meteor-typescript': '0.8.10',
  '@angular/core': '5.0.0-rc.6',
  '@angular/common': '5.0.0-rc.6',
  '@angular/compiler': '5.0.0-rc.6',
  '@angular/compiler-cli': '5.0.0-rc.6',
  'typescript': '2.4.2'
});

Package.onUse(function(api) {
  api.versionsFrom('1.5.2.2');
  api.use([
    'ecmascript',
    'babel-compiler',
    'ardatan:angular-html-compiler@0.2.5',
    'ardatan:angular-scss-compiler@0.2.5'
  ], 'server');
  api.mainModule('index.js', 'server');
});
<|endoftext|>