<commit_before>var newGame = {
	totalPlayers: 0,
	init: function(){
		newGame.UpdateEventListeners();
		document.getElementById("addMember").addEventListener("click", function() {newGame.AddPlayer()}, false);
		document.getElementById("saveNewRP").addEventListener("click", function() {newGame.CreateRP()}, false);
	},
	setCookie: function (cname, cvalue, exdays) {
		var d = new Date();
		d.setTime(d.getTime() + (exdays*24*60*60*1000));
		var expires = "expires="+d.toUTCString();
		document.cookie = cname + "=" + cvalue + "; " + expires;
	},
	UpdateEventListeners: function(){

		var table = document.getElementById("addPlayerList");
		for (index = 1;index < table.rows.length;index++){
			var row = table.rows[index];
			//var col = row.columns[2];
			var col = row.cells[1];
			col.innerHTML = "";
			col.innerHTML = 'Remove';
		}

		var removebtns = document.getElementsByClassName("btn-danger");
		var index;
		for (index = 0; index < removebtns.length; index++) {
				//removebtns[index].removeEventListener("click",newGame.RemovePlayer);
				removebtns[index].addEventListener("click",newGame.RemovePlayer(index),false);
				//removebtns[index].remove();
		}
	},

	RemovePlayer: function(index){
		//closure!
		return function(){
			newGame.totalPlayers = newGame.totalPlayers -1;
			var table = document.getElementById("addPlayerList");
			table.rows[index].remove();

			newGame.UpdateEventListeners();
			//console.log(index);
			//document.getElementById(player).remove();
			//newGame.totalPlayers = newGame.totalPlayers - 1;
		}
	},

	AddPlayer: function(){

		var player = document.getElementById("AddPlayerName").value;
		if (player == ""){
			alert("Please enter a player name");
			return;
		}

		//do additional backend verification before proceeding to lookup the user's email

		var jqxhr = $.post( "dbEdits/playerExists.php",{userid:player});
		jqxhr.done(function(msg){if(msg!=0){

			//console.log("Adding Player");
			var table = document.getElementById("addPlayerList");
			newGame.totalPlayers = newGame.totalPlayers ;
			var row = table.insertRow(newGame.totalPlayers);//append to the end of the table
			newGame.totalPlayers++;
			var colName = row.insertCell(0);
			//var colEmail = row.insertCell(1);
			var colAction = row.insertCell(1);

			colName.innerHTML = document.getElementById("AddPlayerName").value;
			//colEmail.innerHTML = "email@website.com";
			colAction.innerHTML = 'Remove';

			newGame.UpdateEventListeners();

		}else alert("Not a valid player.");});
		jqxhr.fail(function(){alert("Error getting players.")});

	},

	CreateRP: function(){
		//client side form validation before submitting

		var gameName = document.getElementById("gameName").value;
		var gameDescription = document.getElementById("gamedescription").value;
		var imgLink = $("#gameImg").val();

		//console.log("img:"+imgLink);

		if (gameName == ""){
			alert("Please enter a game name");
			return;
		}
		else if (gameDescription ==  ""){
			alert("Please enter a game description");
			return;
		}
		else if (imgLink ==  ""){
			alert("Please enter an image link.");
			return;
		}
		else if (newGame.totalPlayers == 0){
			alert("Please add players before continuing");
			return;
		}

		var jqxhr = $.post( "dbEdits/addGame.php",{gameid:gameName, description:gameDescription, img:imgLink});

		jqxhr.done(function(msg){
			console.log(msg);

			$('#addPlayerList tr').each(function() {
				var userName = $(this).find("td:first").html();
				console.log("attempting to add "+userName);
				var send = $.post( "dbEdits/addPlayerToGame.php",{gameid:gameName,userid:userName});
				send.done(function(msg){if(msg!=0)
					alert("failed to add "+userName +"\n"+msg);
				});
			});

			newGame.setCookie("gameid",gameName, 30);

			window.location = 'gameSettings.php';
		});
		jqxhr.fail(function(){alert("Error posting game.")});

	}
}

newGame.init();

//ValidateFileUpload taken from the author newbieinjavaversion2 from the following URL:
//http://stackoverflow.com/questions/21396279/display-image-and-validation-of-image-extension-before-uploading-file-using-java
function ValidateFileUpload() {
	var fuData = document.getElementById('fileChooser');
    var FileUploadPath = fuData.value;

	//To check if user upload any file
    if (FileUploadPath == '') {
        alert("Please upload an image");

        } else {
        var Extension = FileUploadPath.substring(FileUploadPath.lastIndexOf('.') + 1).toLowerCase();

	//The file uploaded is an image

	if (Extension == "gif" || Extension == "png" || Extension == "bmp" || Extension == "jpeg" || Extension == "jpg") {
		// To Display
		if (fuData.files && fuData.files[0]) {
			var reader = new FileReader();
			reader.onload = function(e) {$('#avatar').attr('src', e.target.result);}
			reader.readAsDataURL(fuData.files[0]);
			}
    }

	//The file upload is NOT an image
	else {
			alert("Photo only allows file types of GIF, PNG, JPG, JPEG and BMP. ");

		}
	}
}<commit_msg>Fixed game creation to game settings screen<commit_after>var newGame = {
	totalPlayers: 0,
	init: function(){
		newGame.UpdateEventListeners();
		document.getElementById("addMember").addEventListener("click", function() {newGame.AddPlayer()}, false);
		document.getElementById("saveNewRP").addEventListener("click", function() {newGame.CreateRP()}, false);
	},
	setCookie: function (cname, cvalue, exdays) {
		var d = new Date();
		d.setTime(d.getTime() + (exdays*24*60*60*1000));
		var expires = "expires="+d.toUTCString();
		document.cookie = cname + "=" + cvalue + "; " + expires;
	},
	UpdateEventListeners: function(){

		var table = document.getElementById("addPlayerList");
		for (index = 1;index < table.rows.length;index++){
			var row = table.rows[index];
			//var col = row.columns[2];
			var col = row.cells[1];
			col.innerHTML = "";
			col.innerHTML = 'Remove';
		}

		var removebtns = document.getElementsByClassName("btn-danger");
		var index;
		for (index = 0; index < removebtns.length; index++) {
				//removebtns[index].removeEventListener("click",newGame.RemovePlayer);
				removebtns[index].addEventListener("click",newGame.RemovePlayer(index),false);
				//removebtns[index].remove();
		}
	},

	RemovePlayer: function(index){
		//closure!
		return function(){
			newGame.totalPlayers = newGame.totalPlayers -1;
			var table = document.getElementById("addPlayerList");
			table.rows[index].remove();

			newGame.UpdateEventListeners();
			//console.log(index);
			//document.getElementById(player).remove();
			//newGame.totalPlayers = newGame.totalPlayers - 1;
		}
	},

	AddPlayer: function(){

		var player = document.getElementById("AddPlayerName").value;
		if (player == ""){
			alert("Please enter a player name");
			return;
		}

		//do additional backend verification before proceeding to lookup the user's email

		var jqxhr = $.post( "dbEdits/playerExists.php",{userid:player});
		jqxhr.done(function(msg){if(msg!=0){

			//console.log("Adding Player");
			var table = document.getElementById("addPlayerList");
			newGame.totalPlayers = newGame.totalPlayers ;
			var row = table.insertRow(newGame.totalPlayers);//append to the end of the table
			newGame.totalPlayers++;
			var colName = row.insertCell(0);
			//var colEmail = row.insertCell(1);
			var colAction = row.insertCell(1);

			colName.innerHTML = document.getElementById("AddPlayerName").value;
			//colEmail.innerHTML = "email@website.com";
			colAction.innerHTML = 'Remove';

			newGame.UpdateEventListeners();

		}else alert("Not a valid player.");});
		jqxhr.fail(function(){alert("Error getting players.")});

	},

	CreateRP: function(){
		//client side form validation before submitting

		var gameName = document.getElementById("gameName").value;
		var gameDescription = document.getElementById("gamedescription").value;
		var imgLink = $("#gameImg").val();

		//console.log("img:"+imgLink);

		if (gameName == ""){
			alert("Please enter a game name");
			return;
		}
		else if (gameDescription ==  ""){
			alert("Please enter a game description");
			return;
		}
		else if (imgLink ==  ""){
			alert("Please enter an image link.");
			return;
		}
		else if (newGame.totalPlayers == 0){
			alert("Please add players before continuing");
			return;
		}

		var jqxhr = $.post( "dbEdits/addGame.php",{gameid:gameName, description:gameDescription, img:imgLink});

		jqxhr.done(function(msg){
			console.log(msg);

			$('#addPlayerList tr').each(function() {
				var userName = $(this).find("td:first").html();
				console.log("attempting to add "+userName);
				var send = $.post( "dbEdits/addPlayerToGame.php",{gameid:gameName,userid:userName});
				send.done(function(msg){if(msg!=0)
					alert("failed to add "+userName +"\n"+msg);
				});
			});

			newGame.setCookie("gameid",gameName, 30);
			setTimeout(function(){
				window.location = 'gameSettings.php';
			},500)

		});
		jqxhr.fail(function(){alert("Error posting game.")});

	}
}

newGame.init();

//ValidateFileUpload taken from the author newbieinjavaversion2 from the following URL:
//http://stackoverflow.com/questions/21396279/display-image-and-validation-of-image-extension-before-uploading-file-using-java
function ValidateFileUpload() {
	var fuData = document.getElementById('fileChooser');
    var FileUploadPath = fuData.value;

	//To check if user upload any file
    if (FileUploadPath == '') {
        alert("Please upload an image");

        } else {
        var Extension = FileUploadPath.substring(FileUploadPath.lastIndexOf('.') + 1).toLowerCase();

	//The file uploaded is an image

	if (Extension == "gif" || Extension == "png" || Extension == "bmp" || Extension == "jpeg" || Extension == "jpg") {
		// To Display
		if (fuData.files && fuData.files[0]) {
			var reader = new FileReader();
			reader.onload = function(e) {$('#avatar').attr('src', e.target.result);}
			reader.readAsDataURL(fuData.files[0]);
			}
    }

	//The file upload is NOT an image
	else {
			alert("Photo only allows file types of GIF, PNG, JPG, JPEG and BMP. ");

		}
	}
}<|endoftext|>


<commit_before>var allTestFiles = [];
var TEST_REGEXP = /test\.js$/;

console.log("WHAT IS GOING ON?");

Object.keys(window.__karma__.files).forEach(function(file) {
  if (TEST_REGEXP.test(file)) {
    // Normalize paths to RequireJS module names.
    allTestFiles.push(file);
  }
});

require.config({
  // Karma serves files under /base, which is the basePath from your config file
  baseUrl: '/base',

  // example of using a couple path translations (paths), to allow us to refer to different library dependencies, without using relative paths
  /*
  paths: {
    'jquery': '../lib/jquery',
    'underscore': '../lib/underscore',
  },
  */
  /*
  packages: [
    {
      name: 'num',
      location: 'num',
      main: 'num'
    },
    {
      name: 'jello',
      location: 'physics',
      main: 'jello'
    }
  ],
  */

  // example of using a shim, to load non AMD libraries (such as underscore)
  /*
  shim: {
    'underscore': {
      exports: '_'
    }
  },
  */

  // dynamically load all test files
  deps: allTestFiles,

  // we have to kickoff jasmine, as it is asynchronous
  callback: window.__karma__.start
});
<commit_msg>hacking gulp-karma<commit_after>var allTestFiles = [];
var TEST_REGEXP = /test\.js$/;

Object.keys(window.__karma__.files).forEach(function(file) {
  if (TEST_REGEXP.test(file)) {
    // Normalize paths to RequireJS module names.
    allTestFiles.push(file);
  }
});

console.log("TEST FILES in require config:");
allTestFiles.forEach(function(file) {
console.log(file);
});
console.log("");

require.config({
  // Karma serves files under /base, which is the basePath from your config file
  baseUrl: '/base',

  // example of using a couple path translations (paths), to allow us to refer to different library dependencies, without using relative paths
  /*
  paths: {
    'jquery': '../lib/jquery',
    'underscore': '../lib/underscore',
  },
  */
  /*
  packages: [
    {
      name: 'num',
      location: 'num',
      main: 'num'
    },
    {
      name: 'jello',
      location: 'physics',
      main: 'jello'
    }
  ],
  */

  // example of using a shim, to load non AMD libraries (such as underscore)
  /*
  shim: {
    'underscore': {
      exports: '_'
    }
  },
  */

  // dynamically load all test files
  deps: allTestFiles,

  // we have to kickoff jasmine, as it is asynchronous
  callback: window.__karma__.start
});
<|endoftext|>


<commit_before>'use strict';

var concatStream = require('concat-stream');
var replacePlugin = require('../');
var fs = require('fs');
var should = require('should');
var File = require('vinyl');

describe('gulp-replace', function() {
  describe('replacePlugin()', function() {
    describe('buffered input', function () {
      var file;

      beforeEach(function () {
        file = new File({
          path: 'test/fixtures/helloworld.txt',
          cwd: 'test/',
          base: 'test/fixtures',
          contents: fs.readFileSync('test/fixtures/helloworld.txt')
        });
      });

      it('should replace string on a buffer', function(done) {
        var stream = replacePlugin('world', 'person');
        stream.on('data', function(newFile) {
          String(newFile.contents).should.equal(fs.readFileSync('test/expected/helloworld.txt', 'utf8'));
          done();
        });

        stream.write(file);
        stream.end();
      });

      it('should replace regex on a buffer', function(done) {
        var stream = replacePlugin(/world/g, 'person');
        stream.on('data', function(newFile) {
          String(newFile.contents).should.equal(fs.readFileSync('test/expected/helloworld.txt', 'utf8'));
          done();
        });

        stream.write(file);
        stream.end();
      });

      it('should replace regex on a buffer with a function', function(done) {
        var stream = replacePlugin(/world/g, function() { return 'person'; });
        stream.on('data', function(newFile) {
          String(newFile.contents).should.equal(fs.readFileSync('test/expected/helloworld.txt', 'utf8'));
          done();
        });

        stream.write(file);
        stream.end();
      });

      it('should replace string on a buffer with a function', function(done) {
        var stream = replacePlugin('world', function() { return 'person'; });
        stream.on('data', function(newFile) {
          String(newFile.contents).should.equal(fs.readFileSync('test/expected/helloworld.txt', 'utf8'));
          done();
        });

        stream.write(file);
        stream.end();
      });

      it('should call function once for each replacement when replacing a string on a buffer', function(done) {
        var replacements = [
          'cow',
          'chicken',
          'duck',
          'person'
        ];
        var stream = replacePlugin('world', function() { return replacements.shift(); });
        stream.on('data', function(newFile) {
          String(newFile.contents).should.equal(fs.readFileSync('test/expected/hellofarm.txt', 'utf8'));
          done();
        });

        stream.write(file);
        stream.end();
      });

      it('should call function once for each replacement when replacing a regex on a buffer', function(done) {
        var replacements = [
          'cow',
          'chicken',
          'duck',
          'person'
        ];
        var stream = replacePlugin(/world/g, function() { return replacements.shift(); });
        stream.on('data', function(newFile) {
          String(newFile.contents).should.equal(fs.readFileSync('test/expected/hellofarm.txt', 'utf8'));
          done();
        });

        stream.write(file);
        stream.end();
      });

      it('should trigger events on a buffer', function(done) {
        var stream = replacePlugin('world', 'elephant')
        .on('finish', function() {
          // No assertion required, we should end up here, if we don't the test will time out
          done();
        });

        stream.write(file);
        stream.end();
      });
    });

    describe('streamed input', function () {
      var file;

      beforeEach(function () {
        file = new File({
            path: 'test/fixtures/helloworld.txt',
            cwd: 'test/',
            base: 'test/fixtures',
            contents: fs.createReadStream('test/fixtures/helloworld.txt')
          });
      });

      it('should replace string on a stream', function(done) {
        var stream = replacePlugin('world', 'person');
        stream.on('data', function(newFile) {
          should.exist(newFile);
          should.exist(newFile.contents);

          newFile.contents.pipe(concatStream({encoding: 'string'}, function(data) {
            data.should.equal(fs.readFileSync('test/expected/helloworld.txt', 'utf8'));
            done();
          }));
        });

        stream.write(file);
        stream.end();
      });

      it('should replace regex on a stream', function(done) {
        var stream = replacePlugin(/world/g, 'person');
        stream.on('data', function(newFile) {
          should.exist(newFile);
          should.exist(newFile.contents);

          newFile.contents.pipe(concatStream({encoding: 'string'}, function(data) {
            data.should.equal(fs.readFileSync('test/expected/helloworld.txt', 'utf8'));
            done();
          }));
        });

        stream.write(file);
        stream.end();
      });

      it('should replace regex on a stream with a function', function(done) {
        var stream = replacePlugin(/world/g, function() { return 'person'; });
        stream.on('data', function(newFile) {
          should.exist(newFile);
          should.exist(newFile.contents);

          newFile.contents.pipe(concatStream({encoding: 'string'}, function(data) {
            data.should.equal(fs.readFileSync('test/expected/helloworld.txt', 'utf8'));
            done();
          }));
        });

        stream.write(file);
        stream.end();
      });

      it('should replace string on a stream with a function', function(done) {
        var stream = replacePlugin('world', function() { return 'person'; });
        stream.on('data', function(newFile) {
          should.exist(newFile);
          should.exist(newFile.contents);

          newFile.contents.pipe(concatStream({encoding: 'string'}, function(data) {
            data.should.equal(fs.readFileSync('test/expected/helloworld.txt', 'utf8'));
            done();
          }));
        });

        stream.write(file);
        stream.end();
      });

      it('should call function once for each replacement when replacing a string on a stream', function(done) {
        var replacements = [
          'cow',
          'chicken',
          'duck',
          'person'
        ];
        var stream = replacePlugin('world', function() { return replacements.shift(); });
        stream.on('data', function(newFile) {
          should.exist(newFile);
          should.exist(newFile.contents);

          newFile.contents.pipe(concatStream({encoding: 'string'}, function(data) {
            data.should.equal(fs.readFileSync('test/expected/hellofarm.txt', 'utf8'));
            done();
          }));
        });

        stream.write(file);
        stream.end();
      });

      it('should call function once for each replacement when replacing a regex on a stream', function(done) {
        var replacements = [
          'cow',
          'chicken',
          'duck',
          'person'
        ];
        var stream = replacePlugin(/world/g, function() { return replacements.shift(); });
        stream.on('data', function(newFile) {
          should.exist(newFile);
          should.exist(newFile.contents);

          newFile.contents.pipe(concatStream({encoding: 'string'}, function(data) {
            data.should.equal(fs.readFileSync('test/expected/hellofarm.txt', 'utf8'));
            done();
          }));
        });

        stream.write(file);
        stream.end();
      });
    });

    it('should ignore binary files when skipBinary is enabled', function(done) {
      var file = new File({
        path: 'test/fixtures/binary.png',
        cwd: 'test/',
        base: 'test/fixtures',
        contents: fs.readFileSync('test/fixtures/binary.png')
      });

      var stream = replacePlugin('world', 'person', {skipBinary: true});
      stream.on('data', function(newFile) {
        should.exist(newFile);
        should.exist(newFile.contents);

        newFile.contents.should.eql(fs.readFileSync('test/expected/binary.png'));
        done();
      });

      stream.write(file);
      stream.end();
    });

    it('should replace string on non binary files when skipBinary is enabled', function(done) {
      var file = new File({
        path: 'test/fixtures/helloworld.txt',
        cwd: 'test/',
        base: 'test/fixtures',
        contents: fs.createReadStream('test/fixtures/helloworld.txt')
      });

      var stream = replacePlugin('world', 'person', {skipBinary: true});
      stream.on('data', function(newFile) {
        should.exist(newFile);
        should.exist(newFile.contents);

        newFile.contents.pipe(concatStream({encoding: 'string'}, function(data) {
          data.should.equal(fs.readFileSync('test/expected/helloworld.txt', 'utf8'));
          done();
        }));
      });

      stream.write(file);
      stream.end();
    });

  });
});
<commit_msg>Removes file existence testing from streaming input, because there's no need to test existence of test data<commit_after>'use strict';

var concatStream = require('concat-stream');
var replacePlugin = require('../');
var fs = require('fs');
var should = require('should');
var File = require('vinyl');

describe('gulp-replace', function() {
  describe('replacePlugin()', function() {
    describe('buffered input', function () {
      var file;

      beforeEach(function () {
        file = new File({
          path: 'test/fixtures/helloworld.txt',
          cwd: 'test/',
          base: 'test/fixtures',
          contents: fs.readFileSync('test/fixtures/helloworld.txt')
        });
      });

      it('should replace string on a buffer', function(done) {
        var stream = replacePlugin('world', 'person');
        stream.on('data', function(newFile) {
          String(newFile.contents).should.equal(fs.readFileSync('test/expected/helloworld.txt', 'utf8'));
          done();
        });

        stream.write(file);
        stream.end();
      });

      it('should replace regex on a buffer', function(done) {
        var stream = replacePlugin(/world/g, 'person');
        stream.on('data', function(newFile) {
          String(newFile.contents).should.equal(fs.readFileSync('test/expected/helloworld.txt', 'utf8'));
          done();
        });

        stream.write(file);
        stream.end();
      });

      it('should replace regex on a buffer with a function', function(done) {
        var stream = replacePlugin(/world/g, function() { return 'person'; });
        stream.on('data', function(newFile) {
          String(newFile.contents).should.equal(fs.readFileSync('test/expected/helloworld.txt', 'utf8'));
          done();
        });

        stream.write(file);
        stream.end();
      });

      it('should replace string on a buffer with a function', function(done) {
        var stream = replacePlugin('world', function() { return 'person'; });
        stream.on('data', function(newFile) {
          String(newFile.contents).should.equal(fs.readFileSync('test/expected/helloworld.txt', 'utf8'));
          done();
        });

        stream.write(file);
        stream.end();
      });

      it('should call function once for each replacement when replacing a string on a buffer', function(done) {
        var replacements = [
          'cow',
          'chicken',
          'duck',
          'person'
        ];
        var stream = replacePlugin('world', function() { return replacements.shift(); });
        stream.on('data', function(newFile) {
          String(newFile.contents).should.equal(fs.readFileSync('test/expected/hellofarm.txt', 'utf8'));
          done();
        });

        stream.write(file);
        stream.end();
      });

      it('should call function once for each replacement when replacing a regex on a buffer', function(done) {
        var replacements = [
          'cow',
          'chicken',
          'duck',
          'person'
        ];
        var stream = replacePlugin(/world/g, function() { return replacements.shift(); });
        stream.on('data', function(newFile) {
          String(newFile.contents).should.equal(fs.readFileSync('test/expected/hellofarm.txt', 'utf8'));
          done();
        });

        stream.write(file);
        stream.end();
      });

      it('should trigger events on a buffer', function(done) {
        var stream = replacePlugin('world', 'elephant')
        .on('finish', function() {
          // No assertion required, we should end up here, if we don't the test will time out
          done();
        });

        stream.write(file);
        stream.end();
      });
    });

    describe('streamed input', function () {
      var file;

      beforeEach(function () {
        file = new File({
            path: 'test/fixtures/helloworld.txt',
            cwd: 'test/',
            base: 'test/fixtures',
            contents: fs.createReadStream('test/fixtures/helloworld.txt')
          });
      });

      it('should replace string on a stream', function(done) {
        var stream = replacePlugin('world', 'person');
        stream.on('data', function(newFile) {
          newFile.contents.pipe(concatStream({encoding: 'string'}, function(data) {
            data.should.equal(fs.readFileSync('test/expected/helloworld.txt', 'utf8'));
            done();
          }));
        });

        stream.write(file);
        stream.end();
      });

      it('should replace regex on a stream', function(done) {
        var stream = replacePlugin(/world/g, 'person');
        stream.on('data', function(newFile) {
          newFile.contents.pipe(concatStream({encoding: 'string'}, function(data) {
            data.should.equal(fs.readFileSync('test/expected/helloworld.txt', 'utf8'));
            done();
          }));
        });

        stream.write(file);
        stream.end();
      });

      it('should replace regex on a stream with a function', function(done) {
        var stream = replacePlugin(/world/g, function() { return 'person'; });
        stream.on('data', function(newFile) {
          newFile.contents.pipe(concatStream({encoding: 'string'}, function(data) {
            data.should.equal(fs.readFileSync('test/expected/helloworld.txt', 'utf8'));
            done();
          }));
        });

        stream.write(file);
        stream.end();
      });

      it('should replace string on a stream with a function', function(done) {
        var stream = replacePlugin('world', function() { return 'person'; });
        stream.on('data', function(newFile) {
          newFile.contents.pipe(concatStream({encoding: 'string'}, function(data) {
            data.should.equal(fs.readFileSync('test/expected/helloworld.txt', 'utf8'));
            done();
          }));
        });

        stream.write(file);
        stream.end();
      });

      it('should call function once for each replacement when replacing a string on a stream', function(done) {
        var replacements = [
          'cow',
          'chicken',
          'duck',
          'person'
        ];
        var stream = replacePlugin('world', function() { return replacements.shift(); });
        stream.on('data', function(newFile) {
          newFile.contents.pipe(concatStream({encoding: 'string'}, function(data) {
            data.should.equal(fs.readFileSync('test/expected/hellofarm.txt', 'utf8'));
            done();
          }));
        });

        stream.write(file);
        stream.end();
      });

      it('should call function once for each replacement when replacing a regex on a stream', function(done) {
        var replacements = [
          'cow',
          'chicken',
          'duck',
          'person'
        ];
        var stream = replacePlugin(/world/g, function() { return replacements.shift(); });
        stream.on('data', function(newFile) {
          newFile.contents.pipe(concatStream({encoding: 'string'}, function(data) {
            data.should.equal(fs.readFileSync('test/expected/hellofarm.txt', 'utf8'));
            done();
          }));
        });

        stream.write(file);
        stream.end();
      });
    });

    it('should ignore binary files when skipBinary is enabled', function(done) {
      var file = new File({
        path: 'test/fixtures/binary.png',
        cwd: 'test/',
        base: 'test/fixtures',
        contents: fs.readFileSync('test/fixtures/binary.png')
      });

      var stream = replacePlugin('world', 'person', {skipBinary: true});
      stream.on('data', function(newFile) {
        should.exist(newFile);
        should.exist(newFile.contents);

        newFile.contents.should.eql(fs.readFileSync('test/expected/binary.png'));
        done();
      });

      stream.write(file);
      stream.end();
    });

    it('should replace string on non binary files when skipBinary is enabled', function(done) {
      var file = new File({
        path: 'test/fixtures/helloworld.txt',
        cwd: 'test/',
        base: 'test/fixtures',
        contents: fs.createReadStream('test/fixtures/helloworld.txt')
      });

      var stream = replacePlugin('world', 'person', {skipBinary: true});
      stream.on('data', function(newFile) {
        should.exist(newFile);
        should.exist(newFile.contents);

        newFile.contents.pipe(concatStream({encoding: 'string'}, function(data) {
          data.should.equal(fs.readFileSync('test/expected/helloworld.txt', 'utf8'));
          done();
        }));
      });

      stream.write(file);
      stream.end();
    });

  });
});
<|endoftext|>


<commit_before>(function() {
    'use strict';

    var fs      = require('fs'),
        path    = require('path'),
        os      = require('os'),
        zlib    = require('zlib'),

        pipe    = require('..'),
        test    = require('tape'),

        random  = Math.random();

    test('check parameters', function(t) {
        t.throws(pipe, /streams could not be empty!/, 'check streams');
        t.throws(pipe.bind(null, []), /callback could not be empty!/, 'check callback');
        t.end();
    });

    test('getBody', function(t) {
        var read = fs.createReadStream(__filename);

        pipe.getBody(read, function(error, data) {
            var file = fs.readFileSync(__filename, 'utf8');

            t.equal(data, file, 'getbody <-> readFile');

            t.end();
        });
    });

    test('file1 | file2: no error', function(t) {
        var tmp     = os.tmpdir(),
            name    = path.basename(__filename),
            nameTmp = path.join(tmp, name + random);

         tryPipe(__filename, nameTmp, function() {
            var file1 = fs.readFileSync(__filename, 'utf8'),
                file2 = fs.readFileSync(nameTmp, 'utf8');

            fs.unlinkSync(nameTmp);

            t.equal(file1, file2, 'files equal');
            t.end();
         });
    });

    test('file1 | file2: write open EACESS', function(t) {
        var name    = path.basename(__filename),
            nameTmp = '/' + name + random;

        tryPipe(__filename, nameTmp, function(error) {
            t.ok(error, error && error.message);

            t.end();
        });
    });

    test('file1 | file2: read open ENOENT', function(t) {
        var tmp     = os.tmpdir(),
            name    = path.basename(__filename),
            nameTmp = path.join(tmp, name + random);

        tryPipe(__filename + random, nameTmp, function(error) {
            t.ok(error, error && error.message);

            t.end();
        });
    });

    test('file1 | file2: error read EISDIR', function(t) {
        var tmp         = os.tmpdir(),
            name        = path.basename(__filename),
            nameTmp     = path.join(tmp, name + random);

        tryPipe('/', nameTmp, function(error) {
            fs.unlinkSync(nameTmp);
            t.equal(error.code, 'EISDIR', 'EISDIR: read error');
            t.end();
        });
    });

    test('file1 | file2: error write EISDIR', function(t) {
        tryPipe(__filename, '/', function(error) {
            t.equal(error.code, 'EISDIR', 'EISDIR: write error');
            t.end();
        });
    });

    test('file1 | file2: error read/write EISDIR', function(t) {
        tryPipe(__dirname, '/', function(error) {
            t.equal(error.code, 'EISDIR', 'read/write EISDIR');
            t.end();
        });
    });

    test('file1 | gzip | file2: no errors', function(t) {
        var tmp         = os.tmpdir(),
            name        = path.basename(__filename),
            nameTmp     = path.join(tmp, name + random),

            read        = fs.createReadStream(__filename),
            write       = fs.createWriteStream(nameTmp),
            zip         = zlib.createGzip();

        pipe([read, zip, write], function(error) {
            var file1   = fs.readFileSync(__filename, 'utf8'),
                file2   = fs.readFileSync(nameTmp),
                zip     = zlib.gzipSync(file1);

            fs.unlinkSync(nameTmp);

            t.notOk(error, 'no errors');
            t.deepEqual(zip, file2, 'file gziped');
            t.end();
        });
    });

    test('file1 | gzip', function(t) {
        var read        = fs.createReadStream(__filename),
            zip         = zlib.createGzip();

        pipe([read, zip], function(error) {
            t.notOk(error, 'no errors');
            t.end();
        });
    });

    test('file1 | gzip: error ENOENT', function(t) {
        var read        = fs.createReadStream(__filename + random),
            zip         = zlib.createGzip();

        pipe([read, zip], function(error) {
            t.ok(error, error.message);
            t.end();
        });
    });

    test('file1 | gzip: error EISDIR', function(t) {
        var read        = fs.createReadStream('/'),
            zip         = zlib.createGzip();

        pipe([read, zip], function(error) {
            t.ok(error, error.message);
            t.end();
        });
    });

    function tryPipe(from, to, fn) {
        var read    = fs.createReadStream(from),
            write   = fs.createWriteStream(to);

        pipe([read, write], function(error) {
            fn(error);
        });
    }

})();
<commit_msg>test(pipe) add checkListenersLeak<commit_after>(function() {
    'use strict';

    var fs      = require('fs'),
        path    = require('path'),
        os      = require('os'),
        zlib    = require('zlib'),

        pipe    = require('..'),
        test    = require('tape'),

        random  = Math.random();

    test('check parameters', function(t) {
        t.throws(pipe, /streams could not be empty!/, 'check streams');
        t.throws(pipe.bind(null, []), /callback could not be empty!/, 'check callback');
        t.end();
    });

    test('getBody', function(t) {
        var read = fs.createReadStream(__filename);

        pipe.getBody(read, function(error, data) {
            var file = fs.readFileSync(__filename, 'utf8');

            t.equal(data, file, 'getbody <-> readFile');

            t.end();
        });
    });

    test('file1 | file2: no error', function(t) {
        var tmp     = os.tmpdir(),
            name    = path.basename(__filename),
            nameTmp = path.join(tmp, name + random);

         tryPipe(__filename, nameTmp, function() {
            var file1 = fs.readFileSync(__filename, 'utf8'),
                file2 = fs.readFileSync(nameTmp, 'utf8');

            fs.unlinkSync(nameTmp);

            t.equal(file1, file2, 'files equal');
            t.end();
         });
    });

    test('file1 | file2: write open EACESS', function(t) {
        var name    = path.basename(__filename),
            nameTmp = '/' + name + random;

        tryPipe(__filename, nameTmp, function(error) {
            t.ok(error, error && error.message);

            t.end();
        });
    });

    test('file1 | file2: read open ENOENT', function(t) {
        var tmp     = os.tmpdir(),
            name    = path.basename(__filename),
            nameTmp = path.join(tmp, name + random);

        tryPipe(__filename + random, nameTmp, function(error) {
            t.ok(error, error && error.message);

            t.end();
        });
    });

    test('file1 | file2: error read EISDIR', function(t) {
        var tmp         = os.tmpdir(),
            name        = path.basename(__filename),
            nameTmp     = path.join(tmp, name + random);

        tryPipe('/', nameTmp, function(error) {
            fs.unlinkSync(nameTmp);
            t.equal(error.code, 'EISDIR', 'EISDIR: read error');
            t.end();
        });
    });

    test('file1 | file2: error write EISDIR', function(t) {
        tryPipe(__filename, '/', function(error) {
            t.equal(error.code, 'EISDIR', 'EISDIR: write error');
            t.end();
        });
    });

    test('file1 | file2: error read/write EISDIR', function(t) {
        tryPipe(__dirname, '/', function(error) {
            t.equal(error.code, 'EISDIR', 'read/write EISDIR');
            t.end();
        });
    });

    test('file1 | gzip | file2: no errors', function(t) {
        var tmp         = os.tmpdir(),
            name        = path.basename(__filename),
            nameTmp     = path.join(tmp, name + random),

            read        = fs.createReadStream(__filename),
            write       = fs.createWriteStream(nameTmp),
            zip         = zlib.createGzip();

        pipe([read, zip, write], function(error) {
            var file1   = fs.readFileSync(__filename, 'utf8'),
                file2   = fs.readFileSync(nameTmp),
                zip     = zlib.gzipSync(file1);

            fs.unlinkSync(nameTmp);

            t.notOk(error, 'no errors');
            t.deepEqual(zip, file2, 'file gziped');
            t.end();
        });
    });

    test('file1 | gzip', function(t) {
        var read        = fs.createReadStream(__filename),
            zip         = zlib.createGzip();

        pipe([read, zip], function(error) {
            t.notOk(error, 'no errors');
            t.end();
        });
    });

    test('file1 | gzip: error ENOENT', function(t) {
        var read        = fs.createReadStream(__filename + random),
            zip         = zlib.createGzip();

        pipe([read, zip], function(error) {
            t.ok(error, error.message);
            t.end();
        });
    });

    test('file1 | gzip: error EISDIR', function(t) {
        var read        = fs.createReadStream('/'),
            zip         = zlib.createGzip();

        pipe([read, zip], function(error) {
            t.ok(error, error.message);
            t.end();
        });
    });

    function tryPipe(from, to, fn) {
        var read    = fs.createReadStream(from),
            write   = fs.createWriteStream(to);

        pipe([read, write], function(error) {
            var name = checkListenersLeak([read, write]);

            if (name)
                console.error('possible memory leak: ', name);

            fn(error);
        });
    }

    function checkListenersLeak(streams) {
        var name,
            events  = ['open', 'error', 'end', 'finish'],
            regExp  = /^function (onError|onReadError|onWriteError|onReadEnd|onWriteFinish)/;

        streams.some(function(stream) {
            events.some(function(event) {
                stream.listeners(event).some(function(fn) {
                    var is = (fn + '').match(regExp);

                    if (is)
                        name = is[1];

                    return name;
                });

                return name;
            });

            return name;
        });

        return name;
    }

})();
<|endoftext|>


<commit_before>import Reflux from 'reflux';

import Vector from 'immutable-vector2d';
import uuid from 'node-uuid';

import {CircuitActions, AddElementActions} from '../actions/CircuitActions.js';

import {GRID_SIZE} from '../components/utils/Constants.js';
import handleHover from '../components/HighlightOnHover.jsx';

const getConnectorPositions = function(component, startPoint, dragPoint) {
  return !component.getConnectorPositions || component.getConnectorPositions(startPoint, dragPoint);
};

export default Reflux.createStore({

  listenables: AddElementActions,

  element: null,

  getInitialState() {
    return this.element;
  },

  onStart(elemType, coords) {
    const startPoint = Vector.fromObject(coords).snap(GRID_SIZE);
    this.element = {
        id: uuid.v4(),
        component: elemType,
        props: {},
        startPoint: startPoint,
        dragPoint: startPoint
      };
  },

  onMove(coords) {
    const startPoint = this.element.startPoint,
          dragPoint = Vector.fromObject(coords).snap(GRID_SIZE);

    if (dragPoint.equals(startPoint)) {
      return; // prevent zero size elements
    }

    this.element.props.connectors = getConnectorPositions(this.element.component, startPoint, dragPoint);

    this.trigger(this.element);
  },

  onFinish() {
    const element = this.element;
    element.component = handleHover(element.component);

    this.element = null;

    this.trigger();
    CircuitActions.addElement(element);
  }

});
<commit_msg>Fix adding element before initialising<commit_after>import Reflux from 'reflux';

import Vector from 'immutable-vector2d';
import uuid from 'node-uuid';

import {CircuitActions, AddElementActions} from '../actions/CircuitActions.js';

import {GRID_SIZE} from '../components/utils/Constants.js';
import handleHover from '../components/HighlightOnHover.jsx';

const getConnectorPositions = function(component, startPoint, dragPoint) {
  return !component.getConnectorPositions || component.getConnectorPositions(startPoint, dragPoint);
};

export default Reflux.createStore({

  listenables: AddElementActions,

  element: null,
  init: false,

  getInitialState() {
    return this.element;
  },

  onStart(elemType, coords) {
    const startPoint = Vector.fromObject(coords).snap(GRID_SIZE);
    this.element = {
        id: uuid.v4(),
        component: elemType,
        props: {},
        startPoint: startPoint,
        dragPoint: startPoint
      };
    this.init = false;
  },

  onMove(coords) {
    const startPoint = this.element.startPoint,
          dragPoint = Vector.fromObject(coords).snap(GRID_SIZE);

    if (dragPoint.equals(startPoint)) {
      return; // prevent zero size elements
    }

    this.element.props.connectors = getConnectorPositions(this.element.component, startPoint, dragPoint);

    this.init = true;

    this.trigger(this.element);
  },

  onFinish() {
    const element = this.element;
    element.component = handleHover(element.component);

    this.element = null;

    this.trigger();
    if (this.init) { CircuitActions.addElement(element); } // only add element if its position has been initialised

    this.init = false;
  }

});
<|endoftext|>


<commit_before>THREE.ViveController = function( id ){

	var scope = this

	THREE.Object3D.call( this )
	this.matrixAutoUpdate = false
	this.standingMatrix   = new THREE.Matrix4()

	//  Button value storage for comparing live data to prior state.
	//  Making these properties visible rather than private allows you
	//  more flexibilty -- for example, do you just fire when the
	//  TriggerPressed event fires? Or does your animation loop continue
	//  to react as long as controller.triggerIsPressed === true?

	this.axes              = [ 0, 0 ]
	this.thumbpadIsPressed = false
	this.triggerIsPressed  = false
	this.gripsArePressed   = false
	this.menuIsPressed     = false

	//  Example use case:
	//  window.addEventListener( 'viveControllerTriggerPressed', function( event ){
	//
	//  	console.log( 'Vive controller', id, 'trigger was pressed.', event )
	//  })

	function dispatchViveControllerEvent( name, data ){

		var event

		if( data === undefined ) event = new CustomEvent( 'viveController'+ name )
		else event = new CustomEvent( 'viveController'+ name, { detail: data })
		window.dispatchEvent( event )
	}

	//  Continuous polling...
	//  You will need to call this function from your main animation loop
	//  and that main loop ought to use VRDisplay.requestAnimationFrame which
	//  aims for 90fps -- rather than window.requestAnimationFrame which aims.
	//  for 60fps. Thanks to Jaume Sanchez Elias (@thespite) and Brandon Jones
	//  (@Tojiro) for pointing this out!

	function update(){

		var gamepad, pose

		gamepad = navigator.getGamepads()[ id ]
		if( gamepad !== undefined && gamepad.pose !== null ){

			//  Position and orientation.

			pose = gamepad.pose
			scope.position.fromArray( pose.position )
			scope.quaternion.fromArray( pose.orientation )
			scope.matrix.compose( scope.position, scope.quaternion, scope.scale )
			scope.matrix.multiplyMatrices( scope.standingMatrix, scope.matrix )
			scope.matrixWorldNeedsUpdate = true
			scope.visible = true

			//  Thumbpad and Buttons.

			if( scope.axes[ 0 ] !== gamepad.axes[ 0 ] ||
				scope.axes[ 1 ] !== gamepad.axes[ 1 ]){

				scope.axes[ 0 ] = gamepad.axes[ 0 ]//  X axis: -1 = Left, +1 = Right.
				scope.axes[ 1 ] = gamepad.axes[ 1 ]//  Y axis: -1 = Bottom, +1 = Top.
				dispatchViveControllerEvent( 'AxisChanged', scope.axes )
			}
			if( scope.thumbpadIsPressed !== gamepad.buttons[ 0 ].pressed ){

				scope.thumbpadIsPressed = gamepad.buttons[ 0 ].pressed
				dispatchViveControllerEvent( scope.thumbpadIsPressed ? 'ThumbpadPressed' : 'ThumbpadReleased' )
			}
			if( scope.triggerIsPressed !== gamepad.buttons[ 1 ].pressed ){

				scope.triggerIsPressed = gamepad.buttons[ 1 ].pressed
				dispatchViveControllerEvent( scope.triggerIsPressed ? 'TriggerPressed' : 'TriggerReleased' )
			}
			if( scope.gripsArePressed !== gamepad.buttons[ 2 ].pressed ){

				scope.gripsArePressed = gamepad.buttons[ 2 ].pressed
				dispatchViveControllerEvent( scope.gripsArePressed ? 'GripsPressed' : 'GripsReleased' )
			}
			if( scope.menuIsPressed !== gamepad.buttons[ 3 ].pressed ){

				scope.menuIsPressed = gamepad.buttons[ 3 ].pressed
				dispatchViveControllerEvent( scope.menuIsPressed ? 'MenuPressed' : 'MenuReleased' )
			}
		}
		else scope.visible = false
	}
}
THREE.ViveController.prototype = Object.create( THREE.Object3D.prototype )
THREE.ViveController.prototype.constructor = THREE.ViveController<commit_msg>Helps when the method is visible.<commit_after>THREE.ViveController = function( id ){

	var scope = this

	THREE.Object3D.call( this )
	this.matrixAutoUpdate = false
	this.standingMatrix   = new THREE.Matrix4()

	//  Button value storage for comparing live data to prior state.
	//  Making these properties visible rather than private allows you
	//  more flexibilty -- for example, do you just fire when the
	//  TriggerPressed event fires? Or does your animation loop continue
	//  to react as long as controller.triggerIsPressed === true?

	this.axes              = [ 0, 0 ]
	this.thumbpadIsPressed = false
	this.triggerIsPressed  = false
	this.gripsArePressed   = false
	this.menuIsPressed     = false

	//  Example use case:
	//  window.addEventListener( 'viveControllerTriggerPressed', function( event ){
	//
	//  	console.log( 'Vive controller', id, 'trigger was pressed.', event )
	//  })

	function dispatchViveControllerEvent( name, data ){

		var event

		if( data === undefined ) event = new CustomEvent( 'viveController'+ name )
		else event = new CustomEvent( 'viveController'+ name, { detail: data })
		window.dispatchEvent( event )
	}

	//  Continuous polling...
	//  You will need to call this function from your main animation loop
	//  and that main loop ought to use VRDisplay.requestAnimationFrame which
	//  aims for 90fps -- rather than window.requestAnimationFrame which aims.
	//  for 60fps. Thanks to Jaume Sanchez Elias (@thespite) and Brandon Jones
	//  (@Tojiro) for pointing this out!

	this.update = function(){

		var gamepad, pose

		gamepad = navigator.getGamepads()[ id ]
		if( gamepad !== undefined && gamepad.pose !== null ){

			//  Position and orientation.

			pose = gamepad.pose
			scope.position.fromArray( pose.position )
			scope.quaternion.fromArray( pose.orientation )
			scope.matrix.compose( scope.position, scope.quaternion, scope.scale )
			scope.matrix.multiplyMatrices( scope.standingMatrix, scope.matrix )
			scope.matrixWorldNeedsUpdate = true
			scope.visible = true

			//  Thumbpad and Buttons.

			if( scope.axes[ 0 ] !== gamepad.axes[ 0 ] ||
				scope.axes[ 1 ] !== gamepad.axes[ 1 ]){

				scope.axes[ 0 ] = gamepad.axes[ 0 ]//  X axis: -1 = Left, +1 = Right.
				scope.axes[ 1 ] = gamepad.axes[ 1 ]//  Y axis: -1 = Bottom, +1 = Top.
				dispatchViveControllerEvent( 'AxisChanged', scope.axes )
			}
			if( scope.thumbpadIsPressed !== gamepad.buttons[ 0 ].pressed ){

				scope.thumbpadIsPressed = gamepad.buttons[ 0 ].pressed
				if( scope.thumbpadIsPressed ) dispatchViveControllerEvent( 'ThumbpadPressed' )
				else dispatchViveControllerEvent( 'ThumbpadReleased' )
			}
			if( scope.triggerIsPressed !== gamepad.buttons[ 1 ].pressed ){

				scope.triggerIsPressed = gamepad.buttons[ 1 ].pressed
				if( scope.triggerIsPressed ) dispatchViveControllerEvent( 'TriggerPressed' )
				else dispatchViveControllerEvent( 'TriggerReleased' )
			}
			if( scope.gripsArePressed !== gamepad.buttons[ 2 ].pressed ){

				scope.gripsArePressed = gamepad.buttons[ 2 ].pressed
				if( scope.gripsArePressed ) dispatchViveControllerEvent( 'GripsPressed' )
				else dispatchViveControllerEvent( 'GripsReleased' )
			}
			if( scope.menuIsPressed !== gamepad.buttons[ 3 ].pressed ){

				scope.menuIsPressed = gamepad.buttons[ 3 ].pressed
				if( scope.menuIsPressed ) dispatchViveControllerEvent( 'MenuPressed' )
				else dispatchViveControllerEvent( 'MenuReleased' )
			}
		}
		else scope.visible = false
	}
}
THREE.ViveController.prototype = Object.create( THREE.Object3D.prototype )
THREE.ViveController.prototype.constructor = THREE.ViveController<|endoftext|>


<commit_before>'use strict';
var DOCS_OVERWRITELINK = true;

angular.module('docApp', ['ngMaterial'])
.constant('DOCS_OVERWRITELINK', typeof DOCS_OVERWRITELINK === 'undefined' ? false : DOCS_OVERWRITELINK)
.provider('DOCS_OVERWRITELINK', function (DOCS_OVERWRITELINK) {
    return {
        $get: function () {
            return DOCS_OVERWRITELINK;
        }
    };
})
.config(function($locationProvider, DOCS_OVERWRITELINK){
    if(!DOCS_OVERWRITELINK){
        $locationProvider.hashPrefix('!');
            $locationProvider.html5Mode({
            enabled: true,
            requireBase: true,
            rewriteLinks: true
        });
    }
})
.config(function($provide, DOCS_NAVIGATION, DOCS_AREA_DATA) {
    // configure navbar navigation
    var nav = DOCS_AREA_DATA.map(function (id) {
        var nav = DOCS_NAVIGATION[id];
        return {
            title: nav.name,
            href: nav.id,
            path: nav.path,
            key: nav.id
        };
    })
    $provide.constant('NAV', nav);
})
.config(function($mdThemingProvider) {
    // default theme
    $mdThemingProvider.theme('default')
        .primaryPalette('grey')
        .accentPalette('red');
})
.run(function($location, CONFIG){
    // show api root by default
    if(!$location.path && CONFIG.ROOT) {
        $location.path(CONFIG.ROOT).replace();
    }
});

<commit_msg>fixed default path<commit_after>'use strict';
var DOCS_OVERWRITELINK = true;

angular.module('docApp', ['ngMaterial'])
.constant('DOCS_OVERWRITELINK', typeof DOCS_OVERWRITELINK === 'undefined' ? false : DOCS_OVERWRITELINK)
.provider('DOCS_OVERWRITELINK', function (DOCS_OVERWRITELINK) {
    return {
        $get: function () {
            return DOCS_OVERWRITELINK;
        }
    };
})
.config(function($locationProvider, DOCS_OVERWRITELINK){
    if(!DOCS_OVERWRITELINK){
        $locationProvider.hashPrefix('!');
            $locationProvider.html5Mode({
            enabled: true,
            requireBase: true,
            rewriteLinks: true
        });
    }
})
.config(function($provide, DOCS_NAVIGATION, DOCS_AREA_DATA) {
    // configure navbar navigation
    var nav = DOCS_AREA_DATA.map(function (id) {
        var nav = DOCS_NAVIGATION[id];
        return {
            title: nav.name,
            href: nav.id,
            path: nav.path,
            key: nav.id
        };
    })
    $provide.constant('NAV', nav);
})
.config(function($mdThemingProvider) {
    // default theme
    $mdThemingProvider.theme('default')
        .primaryPalette('grey')
        .accentPalette('red');
})
.run(function($location, CONFIG){
    // show api root by default
    if(!$location.path() && CONFIG.ROOT) {
        $location.path(CONFIG.ROOT).replace();
    }
});

<|endoftext|>


<commit_before>import { module, test } from '../qunit';
import moment from '../../moment';

module('getters and setters');

test('getters', function (assert) {
    var a = moment([2011, 9, 12, 6, 7, 8, 9]);
    assert.equal(a.year(), 2011, 'year');
    assert.equal(a.month(), 9, 'month');
    assert.equal(a.date(), 12, 'date');
    assert.equal(a.day(), 3, 'day');
    assert.equal(a.hours(), 6, 'hour');
    assert.equal(a.minutes(), 7, 'minute');
    assert.equal(a.seconds(), 8, 'second');
    assert.equal(a.milliseconds(), 9, 'milliseconds');
});

test('getters programmatic', function (assert) {
    var a = moment([2011, 9, 12, 6, 7, 8, 9]);
    assert.equal(a.get('year'), 2011, 'year');
    assert.equal(a.get('month'), 9, 'month');
    assert.equal(a.get('date'), 12, 'date');
    assert.equal(a.get('day'), 3, 'day');
    assert.equal(a.get('hour'), 6, 'hour');
    assert.equal(a.get('minute'), 7, 'minute');
    assert.equal(a.get('second'), 8, 'second');
    assert.equal(a.get('milliseconds'), 9, 'milliseconds');

    //actual getters tested elsewhere
    assert.equal(a.get('weekday'), a.weekday(), 'weekday');
    assert.equal(a.get('isoWeekday'), a.isoWeekday(), 'isoWeekday');
    assert.equal(a.get('week'), a.week(), 'week');
    assert.equal(a.get('isoWeek'), a.isoWeek(), 'isoWeek');
    assert.equal(a.get('dayOfYear'), a.dayOfYear(), 'dayOfYear');
});

test('setters plural', function (assert) {
    var a = moment();
    a.years(2011);
    a.months(9);
    a.dates(12);
    a.hours(6);
    a.minutes(7);
    a.seconds(8);
    a.milliseconds(9);
    assert.equal(a.years(), 2011, 'years');
    assert.equal(a.months(), 9, 'months');
    assert.equal(a.dates(), 12, 'dates');
    assert.equal(a.days(), 3, 'days');
    assert.equal(a.hours(), 6, 'hours');
    assert.equal(a.minutes(), 7, 'minutes');
    assert.equal(a.seconds(), 8, 'seconds');
    assert.equal(a.milliseconds(), 9, 'milliseconds');
});

test('setters singular', function (assert) {
    var a = moment();
    a.year(2011);
    a.month(9);
    a.date(12);
    a.hour(6);
    a.minute(7);
    a.second(8);
    a.millisecond(9);
    assert.equal(a.year(), 2011, 'year');
    assert.equal(a.month(), 9, 'month');
    assert.equal(a.date(), 12, 'date');
    assert.equal(a.day(), 3, 'day');
    assert.equal(a.hour(), 6, 'hour');
    assert.equal(a.minute(), 7, 'minute');
    assert.equal(a.second(), 8, 'second');
    assert.equal(a.millisecond(), 9, 'milliseconds');
});

test('setters', function (assert) {
    var a = moment();
    a.year(2011);
    a.month(9);
    a.date(12);
    a.hours(6);
    a.minutes(7);
    a.seconds(8);
    a.milliseconds(9);
    assert.equal(a.year(), 2011, 'year');
    assert.equal(a.month(), 9, 'month');
    assert.equal(a.date(), 12, 'date');
    assert.equal(a.day(), 3, 'day');
    assert.equal(a.hours(), 6, 'hour');
    assert.equal(a.minutes(), 7, 'minute');
    assert.equal(a.seconds(), 8, 'second');
    assert.equal(a.milliseconds(), 9, 'milliseconds');

    // Test month() behavior. See https://github.com/timrwood/moment/pull/822
    a = moment('20130531', 'YYYYMMDD');
    a.month(3);
    assert.equal(a.month(), 3, 'month edge case');
});

test('setter programmatic', function (assert) {
    var a = moment();
    a.set('year', 2011);
    a.set('month', 9);
    a.set('date', 12);
    a.set('hours', 6);
    a.set('minutes', 7);
    a.set('seconds', 8);
    a.set('milliseconds', 9);
    assert.equal(a.year(), 2011, 'year');
    assert.equal(a.month(), 9, 'month');
    assert.equal(a.date(), 12, 'date');
    assert.equal(a.day(), 3, 'day');
    assert.equal(a.hours(), 6, 'hour');
    assert.equal(a.minutes(), 7, 'minute');
    assert.equal(a.seconds(), 8, 'second');
    assert.equal(a.milliseconds(), 9, 'milliseconds');

    // Test month() behavior. See https://github.com/timrwood/moment/pull/822
    a = moment('20130531', 'YYYYMMDD');
    a.month(3);
    assert.equal(a.month(), 3, 'month edge case');
});

// Disable this, until we weekYear setter is fixed.
// https://github.com/moment/moment/issues/1379
// test('setters programatic with weeks', function (assert) {
//     var a = moment();
//     a.set('weekYear', 2001);
//     a.set('week', 49);
//     a.set('day', 4);
//     assert.equals(a.weekYear(), 2001);
//     assert.equals(a.week(), 49);
//     assert.equals(a.day(), 4);

//     a.set('weekday', 1);
//     assert.equals(a.weekday(), 1);

//     assert.done();
//},

// I think this suffers from the same issue as the non-iso version.
// test('setters programatic with weeks ISO', function (assert) {
//     var a = moment();
//     a.set('isoWeekYear', 2001);
//     a.set('isoWeek', 49);
//     a.set('isoWeekday', 4);

//     assert.equals(a.weekYear(), 2001);
//     assert.equals(a.week(), 49);
//     assert.equals(a.day(), 4);

//     assert.done();
//},

test('setters strings', function (assert) {
    var a = moment([2012]).locale('en');
    assert.equal(a.clone().day(0).day('Wednesday').day(), 3, 'day full name');
    assert.equal(a.clone().day(0).day('Wed').day(), 3, 'day short name');
    assert.equal(a.clone().day(0).day('We').day(), 3, 'day minimal name');
    assert.equal(a.clone().day(0).day('invalid').day(), 0, 'invalid day name');
    assert.equal(a.clone().month(0).month('April').month(), 3, 'month full name');
    assert.equal(a.clone().month(0).month('Apr').month(), 3, 'month short name');
    assert.equal(a.clone().month(0).month('invalid').month(), 0, 'invalid month name');
});

test('setters - falsey values', function (assert) {
    var a = moment();
    // ensure minutes wasn't coincidentally 0 already
    a.minutes(1);
    a.minutes(0);
    assert.equal(a.minutes(), 0, 'falsey value');
});

test('chaining setters', function (assert) {
    var a = moment();
    a.year(2011)
     .month(9)
     .date(12)
     .hours(6)
     .minutes(7)
     .seconds(8);
    assert.equal(a.year(), 2011, 'year');
    assert.equal(a.month(), 9, 'month');
    assert.equal(a.date(), 12, 'date');
    assert.equal(a.day(), 3, 'day');
    assert.equal(a.hours(), 6, 'hour');
    assert.equal(a.minutes(), 7, 'minute');
    assert.equal(a.seconds(), 8, 'second');
});

test('setter with multiple unit values', function (assert) {
    var a = moment();
    a.set({
        year: 2011,
        month: 9,
        date: 12,
        hours: 6,
        minutes: 7,
        seconds: 8,
        milliseconds: 9
    });
    assert.equal(a.year(), 2011, 'year');
    assert.equal(a.month(), 9, 'month');
    assert.equal(a.date(), 12, 'date');
    assert.equal(a.day(), 3, 'day');
    assert.equal(a.hours(), 6, 'hour');
    assert.equal(a.minutes(), 7, 'minute');
    assert.equal(a.seconds(), 8, 'second');
    assert.equal(a.milliseconds(), 9, 'milliseconds');
});

test('day setter', function (assert) {
    var a = moment([2011, 0, 15]);
    assert.equal(moment(a).day(0).date(), 9, 'set from saturday to sunday');
    assert.equal(moment(a).day(6).date(), 15, 'set from saturday to saturday');
    assert.equal(moment(a).day(3).date(), 12, 'set from saturday to wednesday');

    a = moment([2011, 0, 9]);
    assert.equal(moment(a).day(0).date(), 9, 'set from sunday to sunday');
    assert.equal(moment(a).day(6).date(), 15, 'set from sunday to saturday');
    assert.equal(moment(a).day(3).date(), 12, 'set from sunday to wednesday');

    a = moment([2011, 0, 12]);
    assert.equal(moment(a).day(0).date(), 9, 'set from wednesday to sunday');
    assert.equal(moment(a).day(6).date(), 15, 'set from wednesday to saturday');
    assert.equal(moment(a).day(3).date(), 12, 'set from wednesday to wednesday');

    assert.equal(moment(a).day(-7).date(), 2, 'set from wednesday to last sunday');
    assert.equal(moment(a).day(-1).date(), 8, 'set from wednesday to last saturday');
    assert.equal(moment(a).day(-4).date(), 5, 'set from wednesday to last wednesday');

    assert.equal(moment(a).day(7).date(), 16, 'set from wednesday to next sunday');
    assert.equal(moment(a).day(13).date(), 22, 'set from wednesday to next saturday');
    assert.equal(moment(a).day(10).date(), 19, 'set from wednesday to next wednesday');

    assert.equal(moment(a).day(14).date(), 23, 'set from wednesday to second next sunday');
    assert.equal(moment(a).day(20).date(), 29, 'set from wednesday to second next saturday');
    assert.equal(moment(a).day(17).date(), 26, 'set from wednesday to second next wednesday');
});

test('string setters', function (assert) {
    var a = moment();
    a.year('2011');
    a.month('9');
    a.date('12');
    a.hours('6');
    a.minutes('7');
    a.seconds('8');
    a.milliseconds('9');
    assert.equal(a.year(), 2011, 'year');
    assert.equal(a.month(), 9, 'month');
    assert.equal(a.date(), 12, 'date');
    assert.equal(a.day(), 3, 'day');
    assert.equal(a.hours(), 6, 'hour');
    assert.equal(a.minutes(), 7, 'minute');
    assert.equal(a.seconds(), 8, 'second');
    assert.equal(a.milliseconds(), 9, 'milliseconds');
});
<commit_msg>Restore unit tests commented out in #1379<commit_after>import { module, test } from '../qunit';
import moment from '../../moment';

module('getters and setters');

test('getters', function (assert) {
    var a = moment([2011, 9, 12, 6, 7, 8, 9]);
    assert.equal(a.year(), 2011, 'year');
    assert.equal(a.month(), 9, 'month');
    assert.equal(a.date(), 12, 'date');
    assert.equal(a.day(), 3, 'day');
    assert.equal(a.hours(), 6, 'hour');
    assert.equal(a.minutes(), 7, 'minute');
    assert.equal(a.seconds(), 8, 'second');
    assert.equal(a.milliseconds(), 9, 'milliseconds');
});

test('getters programmatic', function (assert) {
    var a = moment([2011, 9, 12, 6, 7, 8, 9]);
    assert.equal(a.get('year'), 2011, 'year');
    assert.equal(a.get('month'), 9, 'month');
    assert.equal(a.get('date'), 12, 'date');
    assert.equal(a.get('day'), 3, 'day');
    assert.equal(a.get('hour'), 6, 'hour');
    assert.equal(a.get('minute'), 7, 'minute');
    assert.equal(a.get('second'), 8, 'second');
    assert.equal(a.get('milliseconds'), 9, 'milliseconds');

    //actual getters tested elsewhere
    assert.equal(a.get('weekday'), a.weekday(), 'weekday');
    assert.equal(a.get('isoWeekday'), a.isoWeekday(), 'isoWeekday');
    assert.equal(a.get('week'), a.week(), 'week');
    assert.equal(a.get('isoWeek'), a.isoWeek(), 'isoWeek');
    assert.equal(a.get('dayOfYear'), a.dayOfYear(), 'dayOfYear');
});

test('setters plural', function (assert) {
    var a = moment();
    a.years(2011);
    a.months(9);
    a.dates(12);
    a.hours(6);
    a.minutes(7);
    a.seconds(8);
    a.milliseconds(9);
    assert.equal(a.years(), 2011, 'years');
    assert.equal(a.months(), 9, 'months');
    assert.equal(a.dates(), 12, 'dates');
    assert.equal(a.days(), 3, 'days');
    assert.equal(a.hours(), 6, 'hours');
    assert.equal(a.minutes(), 7, 'minutes');
    assert.equal(a.seconds(), 8, 'seconds');
    assert.equal(a.milliseconds(), 9, 'milliseconds');
});

test('setters singular', function (assert) {
    var a = moment();
    a.year(2011);
    a.month(9);
    a.date(12);
    a.hour(6);
    a.minute(7);
    a.second(8);
    a.millisecond(9);
    assert.equal(a.year(), 2011, 'year');
    assert.equal(a.month(), 9, 'month');
    assert.equal(a.date(), 12, 'date');
    assert.equal(a.day(), 3, 'day');
    assert.equal(a.hour(), 6, 'hour');
    assert.equal(a.minute(), 7, 'minute');
    assert.equal(a.second(), 8, 'second');
    assert.equal(a.millisecond(), 9, 'milliseconds');
});

test('setters', function (assert) {
    var a = moment();
    a.year(2011);
    a.month(9);
    a.date(12);
    a.hours(6);
    a.minutes(7);
    a.seconds(8);
    a.milliseconds(9);
    assert.equal(a.year(), 2011, 'year');
    assert.equal(a.month(), 9, 'month');
    assert.equal(a.date(), 12, 'date');
    assert.equal(a.day(), 3, 'day');
    assert.equal(a.hours(), 6, 'hour');
    assert.equal(a.minutes(), 7, 'minute');
    assert.equal(a.seconds(), 8, 'second');
    assert.equal(a.milliseconds(), 9, 'milliseconds');

    // Test month() behavior. See https://github.com/timrwood/moment/pull/822
    a = moment('20130531', 'YYYYMMDD');
    a.month(3);
    assert.equal(a.month(), 3, 'month edge case');
});

test('setter programmatic', function (assert) {
    var a = moment();
    a.set('year', 2011);
    a.set('month', 9);
    a.set('date', 12);
    a.set('hours', 6);
    a.set('minutes', 7);
    a.set('seconds', 8);
    a.set('milliseconds', 9);
    assert.equal(a.year(), 2011, 'year');
    assert.equal(a.month(), 9, 'month');
    assert.equal(a.date(), 12, 'date');
    assert.equal(a.day(), 3, 'day');
    assert.equal(a.hours(), 6, 'hour');
    assert.equal(a.minutes(), 7, 'minute');
    assert.equal(a.seconds(), 8, 'second');
    assert.equal(a.milliseconds(), 9, 'milliseconds');

    // Test month() behavior. See https://github.com/timrwood/moment/pull/822
    a = moment('20130531', 'YYYYMMDD');
    a.month(3);
    assert.equal(a.month(), 3, 'month edge case');
});

test('setters programatic with weeks', function (assert) {
    var a = moment();
    a.set('weekYear', 2001);
    a.set('week', 49);
    a.set('day', 4);

    assert.equal(a.weekYear(), 2001, 'weekYear');
    assert.equal(a.week(), 49, 'week');
    assert.equal(a.day(), 4, 'day');

    a.set('weekday', 1);
    assert.equal(a.weekday(), 1, 'weekday');
});

test('setters programatic with weeks ISO', function (assert) {
    var a = moment();
    a.set('isoWeekYear', 2001);
    a.set('isoWeek', 49);
    a.set('isoWeekday', 4);

    assert.equal(a.weekYear(), 2001, 'weekYear');
    assert.equal(a.week(), 49, 'week');
    assert.equal(a.day(), 4, 'day');
});

test('setters strings', function (assert) {
    var a = moment([2012]).locale('en');
    assert.equal(a.clone().day(0).day('Wednesday').day(), 3, 'day full name');
    assert.equal(a.clone().day(0).day('Wed').day(), 3, 'day short name');
    assert.equal(a.clone().day(0).day('We').day(), 3, 'day minimal name');
    assert.equal(a.clone().day(0).day('invalid').day(), 0, 'invalid day name');
    assert.equal(a.clone().month(0).month('April').month(), 3, 'month full name');
    assert.equal(a.clone().month(0).month('Apr').month(), 3, 'month short name');
    assert.equal(a.clone().month(0).month('invalid').month(), 0, 'invalid month name');
});

test('setters - falsey values', function (assert) {
    var a = moment();
    // ensure minutes wasn't coincidentally 0 already
    a.minutes(1);
    a.minutes(0);
    assert.equal(a.minutes(), 0, 'falsey value');
});

test('chaining setters', function (assert) {
    var a = moment();
    a.year(2011)
     .month(9)
     .date(12)
     .hours(6)
     .minutes(7)
     .seconds(8);
    assert.equal(a.year(), 2011, 'year');
    assert.equal(a.month(), 9, 'month');
    assert.equal(a.date(), 12, 'date');
    assert.equal(a.day(), 3, 'day');
    assert.equal(a.hours(), 6, 'hour');
    assert.equal(a.minutes(), 7, 'minute');
    assert.equal(a.seconds(), 8, 'second');
});

test('setter with multiple unit values', function (assert) {
    var a = moment();
    a.set({
        year: 2011,
        month: 9,
        date: 12,
        hours: 6,
        minutes: 7,
        seconds: 8,
        milliseconds: 9
    });
    assert.equal(a.year(), 2011, 'year');
    assert.equal(a.month(), 9, 'month');
    assert.equal(a.date(), 12, 'date');
    assert.equal(a.day(), 3, 'day');
    assert.equal(a.hours(), 6, 'hour');
    assert.equal(a.minutes(), 7, 'minute');
    assert.equal(a.seconds(), 8, 'second');
    assert.equal(a.milliseconds(), 9, 'milliseconds');
});

test('day setter', function (assert) {
    var a = moment([2011, 0, 15]);
    assert.equal(moment(a).day(0).date(), 9, 'set from saturday to sunday');
    assert.equal(moment(a).day(6).date(), 15, 'set from saturday to saturday');
    assert.equal(moment(a).day(3).date(), 12, 'set from saturday to wednesday');

    a = moment([2011, 0, 9]);
    assert.equal(moment(a).day(0).date(), 9, 'set from sunday to sunday');
    assert.equal(moment(a).day(6).date(), 15, 'set from sunday to saturday');
    assert.equal(moment(a).day(3).date(), 12, 'set from sunday to wednesday');

    a = moment([2011, 0, 12]);
    assert.equal(moment(a).day(0).date(), 9, 'set from wednesday to sunday');
    assert.equal(moment(a).day(6).date(), 15, 'set from wednesday to saturday');
    assert.equal(moment(a).day(3).date(), 12, 'set from wednesday to wednesday');

    assert.equal(moment(a).day(-7).date(), 2, 'set from wednesday to last sunday');
    assert.equal(moment(a).day(-1).date(), 8, 'set from wednesday to last saturday');
    assert.equal(moment(a).day(-4).date(), 5, 'set from wednesday to last wednesday');

    assert.equal(moment(a).day(7).date(), 16, 'set from wednesday to next sunday');
    assert.equal(moment(a).day(13).date(), 22, 'set from wednesday to next saturday');
    assert.equal(moment(a).day(10).date(), 19, 'set from wednesday to next wednesday');

    assert.equal(moment(a).day(14).date(), 23, 'set from wednesday to second next sunday');
    assert.equal(moment(a).day(20).date(), 29, 'set from wednesday to second next saturday');
    assert.equal(moment(a).day(17).date(), 26, 'set from wednesday to second next wednesday');
});

test('string setters', function (assert) {
    var a = moment();
    a.year('2011');
    a.month('9');
    a.date('12');
    a.hours('6');
    a.minutes('7');
    a.seconds('8');
    a.milliseconds('9');
    assert.equal(a.year(), 2011, 'year');
    assert.equal(a.month(), 9, 'month');
    assert.equal(a.date(), 12, 'date');
    assert.equal(a.day(), 3, 'day');
    assert.equal(a.hours(), 6, 'hour');
    assert.equal(a.minutes(), 7, 'minute');
    assert.equal(a.seconds(), 8, 'second');
    assert.equal(a.milliseconds(), 9, 'milliseconds');
});
<|endoftext|>


<commit_before>/*
 * grunt-bowerful
 * https://github.com/gyllstromk/grunt-bowerful
 *
 * Copyright (c) 2012 Karl Gyllstrom
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {
    var path = require('path'),
        util = require('util'),
        fs = require('fs');

  // Please see the grunt documentation for more information regarding task and
  // helper creation: https://github.com/gruntjs/grunt/blob/master/docs/toc.md

  // ==========================================================================
  // TASKS
  // ==========================================================================

    grunt.registerMultiTask('bowerful', 'Install bower packages.', function() {
        var done = this.async();
        var deps = {};
        var configs = {};
        var cherryPicks = {};

        var bower = require('bower');
        var config = require('bower/lib/core/config');
        var Manager = require('bower/lib/core/manager');

        var packages = this.data.packages;
        config.directory = this.data.store || 'components';
        config.dest = this.data.dest;
        config.destfile = this.data.destfile || 'assets';
        config.customtarget = this.data.customtarget || {};

        function buildConfig(packageName) {
            if (deps[packageName]) {
                return;
            }

            var base = path.join(config.directory, packageName.split('/').pop());

            var componentJson = path.join(base, 'bower.json');
            if (! fs.existsSync(componentJson)) {
                componentJson = path.join(base, 'component.json');
            }

            var json = {};

            if (fs.existsSync(componentJson)) {
                json = grunt.file.readJSON(componentJson);
            }

            if (! json.main) {
                grunt.log.error(util.format('Package %s did not specify a `main` file in components.json.', packageName));
                grunt.log.error('Trying `package.json`');
                var content = grunt.file.readJSON(path.join(base, 'package.json'));
                json.main = content.main;
            }

            if (! json.main) {
                grunt.log.error('Nothing in `package.json`. Reverting to guesswork based on package name.');
                var guess = path.join(base, packageName + '.js');
                if (fs.existsSync(guess)) {
                    grunt.log.error(util.format('%s exists, assuming this is the correct file.', guess));
                    json.main = guess;
                } else {
                    grunt.log.error(util.format('Cannot find main file for %s. Please install manually (or file bug report to %s with your grunt.js).', packageName, 'https://github.com/gyllstromk/grunt-bowerful/issues'));
                }
            }

            if (! Array.isArray(json.main)) {
                json.main = [ json.main ];
            }

            var picks = cherryPicks[packageName] || {};
            if (picks.select) {
                json.main = json.main.filter(function (each) {
                    return picks.select.indexOf(each) !== -1;
                });
            }

            if (picks.exclude) {
                json.main = json.main.filter(function (each) {
                    return picks.exclude.indexOf(each) === -1;
                });
            }

            deps[packageName] = Object.keys(json.dependencies || []);
            configs[packageName] = json;
            deps[packageName].forEach(buildConfig);
        }

        function installed(packages) {
            if (config.dest) {
                var written = {};
                var contents = {};

                Object.keys(packages).forEach(buildConfig);

                var appendContent = function(file, ext) {
                    contents[ext] += grunt.file.read(file);
                };

                var updateContent = function( pkg, file, ext ) {

                    // if we havent specified a custom target default to same file
                    if(! config.customtarget[pkg.name] ) {
                        appendContent(file, ext);
                    } else {
                        // first use extension to allow lookup on config data
                        var _ext = ext.replace('.', '');

                        // check if we have a custom path based on extension for example customtarget['js']
                        // if the target exists use its file path destination, if they dont check to see
                        // if the general definition is a string example 'myfilename', if it is use it to name the file and add ext to it
                        // if we still dont have a valid target, append to our default merged file.
                        var _target = config.customtarget[pkg.name][_ext] ?
                            config.customtarget[pkg.name][_ext] :
                                typeof config.customtarget[pkg.name] === 'string' ?
                                    config.customtarget[pkg.name] + ext :
                                    false;

                        if( _target ) {
                            grunt.file.write(path.join(_target), grunt.file.read(file));
                        } else {
                            appendContent(file, ext);
                        }
                    }
                };

                var write = function(packageName) {
                    var pkg = configs[packageName];
                    if (! pkg) {
                        return;
                    }

                    (deps[pkg.name] || []).forEach(function(dep) {
                        if (! written[dep]) {
                            write(dep);
                        }
                    });

                    pkg.main.forEach(function(file) {
                        var ext = path.extname(file);
                        if (! contents[ext]) {
                            contents[ext] = '';
                        }

                        var base = path.join(config.directory, pkg.name);

                        file = path.join(config.directory, pkg.name, file);

                        if (! fs.existsSync(file)) {
                            grunt.log.error(file + ' not found. Skipping.');
                        } else {
                            updateContent( pkg, file, ext );
                        }
                    });

                    written[pkg.name] = true;
                };

                grunt.util._.keys(configs).forEach(write);

                Object.keys(contents).forEach(function(ext) {
                    if( contents[ext] ) {
                        grunt.file.write(path.join(config.dest, config.destfile + ext), contents[ext]);
                    }
                });
            }

            done();
        }

        // manager endpointNames argument requires inverted packages
        var install = [];
        grunt.util._.keys(packages).forEach(function(each) {
            var version = packages[each];

            cherryPicks[each] = {};

            if (typeof version === 'object') {
                [ 'select', 'exclude' ].forEach(function (inclusionType) {
                    if (version[inclusionType]) {
                        if (! Array.isArray(version[inclusionType])) {
                            version[inclusionType] = [ version[inclusionType] ];
                        }

                        cherryPicks[each][inclusionType] = version[inclusionType];
                    }
                });

                version = version.version;
            }

            if (! fs.existsSync(path.join(config.directory, each))) {
                if (version) {
                    each += '#' + version;
                }

                install.push(each);
            } else {
                grunt.log.ok(each + ' already installed. Skipping.');
            }
        });

        var installField = [ 'install' ].concat(install);
        var options = {
            argv: {
                remain:   installField,
                cooked:   installField,
                original: installField
            }
        };

        if (install.length) {
            bower.commands
                .install(install, options)
                .on('end', function (data) {
                    installed(packages);
                }
            );
        } else {
            installed(packages);
        }
    });
};
<commit_msg>customtarget - recursive folderstructure #19<commit_after>/*
 * grunt-bowerful
 * https://github.com/gyllstromk/grunt-bowerful
 *
 * Copyright (c) 2012 Karl Gyllstrom
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {
    var path = require('path'),
        util = require('util'),
        fs = require('fs');

  // Please see the grunt documentation for more information regarding task and
  // helper creation: https://github.com/gruntjs/grunt/blob/master/docs/toc.md

  // ==========================================================================
  // TASKS
  // ==========================================================================

    grunt.registerMultiTask('bowerful', 'Install bower packages.', function() {
        var done = this.async();
        var deps = {};
        var configs = {};
        var cherryPicks = {};

        var bower = require('bower');
        var config = require('bower/lib/core/config');
        var Manager = require('bower/lib/core/manager');

        var packages = this.data.packages;
        config.directory = this.data.store || 'components';
        config.dest = this.data.dest;
        config.destfile = this.data.destfile || 'assets';
        config.customtarget = this.data.customtarget || {};

        function buildConfig(packageName) {
            if (deps[packageName]) {
                return;
            }

            var base = path.join(config.directory, packageName.split('/').pop());

            var componentJson = path.join(base, 'bower.json');
            if (! fs.existsSync(componentJson)) {
                componentJson = path.join(base, 'component.json');
            }

            var json = {};

            if (fs.existsSync(componentJson)) {
                json = grunt.file.readJSON(componentJson);
            }

            if (! json.main) {
                grunt.log.error(util.format('Package %s did not specify a `main` file in components.json.', packageName));
                grunt.log.error('Trying `package.json`');
                var content = grunt.file.readJSON(path.join(base, 'package.json'));
                json.main = content.main;
            }

            if (! json.main) {
                grunt.log.error('Nothing in `package.json`. Reverting to guesswork based on package name.');
                var guess = path.join(base, packageName + '.js');
                if (fs.existsSync(guess)) {
                    grunt.log.error(util.format('%s exists, assuming this is the correct file.', guess));
                    json.main = guess;
                } else {
                    grunt.log.error(util.format('Cannot find main file for %s. Please install manually (or file bug report to %s with your grunt.js).', packageName, 'https://github.com/gyllstromk/grunt-bowerful/issues'));
                }
            }

            if (! Array.isArray(json.main)) {
                json.main = [ json.main ];
            }

            var picks = cherryPicks[packageName] || {};
            if (picks.select) {
                json.main = json.main.filter(function (each) {
                    return picks.select.indexOf(each) !== -1;
                });
            }

            if (picks.exclude) {
                json.main = json.main.filter(function (each) {
                    return picks.exclude.indexOf(each) === -1;
                });
            }

            deps[packageName] = Object.keys(json.dependencies || []);
            configs[packageName] = json;
            deps[packageName].forEach(buildConfig);
        }

        function installed(packages) {
            if (config.dest) {
                var written = {};
                var contents = {};

                Object.keys(packages).forEach(buildConfig);

                var appendContent = function(file, ext) {
                    contents[ext] += grunt.file.read(file);
                };

                var updateContent = function( pkg, file, ext ) {

                    // if we havent specified a custom target default to same file
                    if(! config.customtarget[pkg.name] ) {
                        appendContent(file, ext);
                    } else {
                        // first use extension to allow lookup on config data
                        var _ext = ext.replace('.', '');

                        // check if we have a custom path based on extension for example customtarget['js']
                        // if the target exists use its file path destination, if they dont check to see
                        // if the general definition is a string example 'myfilename', if it is use it to name the file and add ext to it
                        // if we still dont have a valid target, append to our default merged file.
                        var _target = config.customtarget[pkg.name][_ext] ?
                            config.customtarget[pkg.name][_ext] :
                                typeof config.customtarget[pkg.name] === 'string' ?
                                    config.customtarget[pkg.name] + ext :
                                    false;

                        if(grunt.file.isDir(file)) {
                            grunt.file.recurse(file, function(abspath, rootdir, subdir, filename) {
                                grunt.file.copy(abspath, path.join(_target, subdir, filename));
                            });
                        } else if( _target ) {
                            grunt.file.write(path.join(_target), grunt.file.read(file));
                        } else {
                            appendContent(file, ext);
                        }
                    }
                };

                var write = function(packageName) {
                    var pkg = configs[packageName];
                    if (! pkg) {
                        return;
                    }

                    (deps[pkg.name] || []).forEach(function(dep) {
                        if (! written[dep]) {
                            write(dep);
                        }
                    });

                    pkg.main.forEach(function(file) {
                        var ext = path.extname(file);
                        if (! contents[ext]) {
                            contents[ext] = '';
                        }

                        var base = path.join(config.directory, pkg.name);

                        file = path.join(config.directory, pkg.name, file);

                        if (! fs.existsSync(file)) {
                            grunt.log.error(file + ' not found. Skipping.');
                        } else {
                            updateContent( pkg, file, ext );
                        }
                    });

                    written[pkg.name] = true;
                };

                grunt.util._.keys(configs).forEach(write);

                Object.keys(contents).forEach(function(ext) {
                    if( contents[ext] ) {
                        grunt.file.write(path.join(config.dest, config.destfile + ext), contents[ext]);
                    }
                });
            }

            done();
        }

        // manager endpointNames argument requires inverted packages
        var install = [];
        grunt.util._.keys(packages).forEach(function(each) {
            var version = packages[each];

            cherryPicks[each] = {};

            if (typeof version === 'object') {
                [ 'select', 'exclude' ].forEach(function (inclusionType) {
                    if (version[inclusionType]) {
                        if (! Array.isArray(version[inclusionType])) {
                            version[inclusionType] = [ version[inclusionType] ];
                        }

                        cherryPicks[each][inclusionType] = version[inclusionType];
                    }
                });

                version = version.version;
            }

            if (! fs.existsSync(path.join(config.directory, each))) {
                if (version) {
                    each += '#' + version;
                }

                install.push(each);
            } else {
                grunt.log.ok(each + ' already installed. Skipping.');
            }
        });

        var installField = [ 'install' ].concat(install);
        var options = {
            argv: {
                remain:   installField,
                cooked:   installField,
                original: installField
            }
        };

        if (install.length) {
            bower.commands
                .install(install, options)
                .on('end', function (data) {
                    installed(packages);
                }
            );
        } else {
            installed(packages);
        }
    });
};
<|endoftext|>


<commit_before>module.exports = function(grunt) {
  'use strict';

  // Create a new multi task.
  grunt.registerMultiTask('casperjs', 'This triggers casperjs.', function() {
    // Tell grunt this task is asynchronous.
    var done = this.async(),
        files = grunt.file.expandFiles(this.file.src),
        filepaths = [];

    grunt.file.expandFiles(this.file.src).forEach(function(filepath) {
      filepaths.push(filepath);
    });

   grunt.utils.async.forEachSeries(filepaths, function(filepath, callback) {
     grunt.helper('casperjs', filepath, function(err) {
       if (err) {
         grunt.warn(err);
       }
       callback();
     });
   }, done);
 });

 grunt.registerHelper('casperjs', function(filepath, callback) {
   var command = 'casperjs "' + filepath + '"',
       exec = require('child_process').exec;

   function puts(error, stdout, stderr) {
     grunt.log.write('\nRunning tests from "' + filepath + '":\n');
     grunt.log.write(stdout);
     //grunt.log.error( stderr );

     if ( error !== null ) {
       callback(error);
     } else {
       callback();
     }
   }
   exec(command, puts);
 });
};
<commit_msg>Added the support for the CLI options.<commit_after>module.exports = function(grunt) {
  'use strict';

  // Create a new multi task.
  grunt.registerMultiTask('casperjs', 'This triggers casperjs.', function() {
    // Tell grunt this task is asynchronous.
    var done = this.async(),
        files = grunt.file.expandFiles(this.file.src),
        filepaths = [],
        helpers = require('grunt-contrib-lib').init(grunt),
        options = helpers.options(this);

   grunt.verbose.writeflags(options, 'Options');

    grunt.file.expandFiles(this.file.src).forEach(function(filepath) {
      filepaths.push(filepath);
    });

   grunt.utils.async.forEachSeries(
       filepaths, function(filepath, callback) {
     grunt.helper('casperjs', filepath, options, function(err) {
       if (err) {
         grunt.warn(err);
       }
       callback();
     });
   }, done);
 });

 grunt.registerHelper('casperjs', function(filepath, options, callback) {
   var command = 'casperjs test',
       exec = require('child_process').exec;

   // Add options documented in the following web site:
   //   http://casperjs.org/testing.html
   if (options.xunit) {
     command += ' --xunit=' + options.xunit;
   }
   if (options.direct) {
     command += ' --direct';
   }
   if (options.includes) {
     command += ' --includes=' + options.includes.join(',');
   }
   if (options.logLevel) {
     command += ' --log-level=' + options.logLevel;
   }
   if (options.pre) {
     command += ' --pre=' + options.pre.join(',');
   }
   if (options.post) {
     command += ' --post=' + options.post.join(',');
   }

   command += " " + filepath;

   grunt.log.write("Command: " + command);

   function puts(error, stdout, stderr) {
     grunt.log.write('\nRunning tests from "' + filepath + '":\n');
     grunt.log.write(stdout);
     //grunt.log.error( stderr );

     if ( error !== null ) {
       callback(error);
     } else {
       callback();
     }
   }
   exec(command, puts);
 });
};
<|endoftext|>