<commit_before>
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var async = require('async'); //Asincronous Waterfall
var mongoose = require('mongoose');

// modules of twitter , facebook and db
var DatabaseModule = require('./modules/dbModule'); //require module of database
var TwitterModule = require('./modules/twModule');  //require module of twitter
var FacebookModule = require('./modules/fbModule'); //require module of facebook

var app = express(); //main application

app.use(bodyParser.json());    //return middleware that only parses json (req.body)
app.use(bodyParser.urlencoded({ extended: true })); //return middleware that only parses urlencoded( UTF-8 )
app.use(express.static(__dirname + '/public'));

console.log('Start check problem'); // search block by console.log

//method POST of the app at the path "/message"
app.post('/message',function(req,res,next){

	var msg = req.body.message; //contains the key-value of the body-parsing
	console.log('message',msg); // see object msg

	console.log('PROGRAM START'); // starting voice of  async waterfall

	// Waterfall
	async.waterfall([    //runs an array of functions in series, each passing their results to the next in the array
		// Create Twitter message
		function ( next ){
			console.log( "(App Mex) message by Twitter" );
			TwitterModule.post( msg, function twitterCallback( resultData ){ //method post by module Twitter
				//data error
				if ( resultData.success === false ){ //if the result is false than return error
					next( true, resultData.error );
					return;
				}
				//data twitter is success
				var twitterId = resultData.data ? resultData.data.id_str : null; // if data isn't false use id_str otherwise null
				console.log('Twitter..........'+ twitterId); //output data twitterId
				next( null, resultData.data ); // passed data at next array with argument twitterId
			});
		},
		// Create Facebook message
		function ( twitterId, next){ //take value resultData.data in arg1
			if( !twitterId ){ //if twitterID is false  return error data
				next( true,"(App Mex) Error retrieving twitter data...");
				return;
			}
			// data facebook is success
			FacebookModule.post( msg, function facebookCallback( resultData ){ //method post by module Facebook
				if(resultData.success === false){ //if the result is false than return error
					next( true, resultData.error);
					return;
				}

				var facebookId = resultData.data ? resultData.data.id : null; // if data isn't false use id_str otherwise null
				console.log('Facebook........'+ facebookId); // output data FacebookId
				next(null, twitterId, facebookId); // passed data at next array with two arguments
			});
		},
		//Save Message in DB with Mongoose
		function (twitterId, facebookId, next){ //take two arguments
			if( !facebookId ) { //if facebookId is false return error data
				next( true,"(App Mex) Error retrieving facebook data..");
				return;
			}
			//Key-value JSON
			var dataToSave = {
				user_tw_id: process.env.USER_TW_ID, //use value of user id from twitter
				user_fb_id: process.env.USER_FB_ID, //use value of user id from facebook
				message: msg,  //body of the message
				tweet_id: twitterId, //use value of message id from twitter
				fb_id: facebookId  //use value of message id from facebook
			};

			DatabaseModule.post(dataToSave, function databaseCallback( resultData,next){ //method post by module database
				if(resultData.success === false){ //if the result is false than return error
					next( true, resultData.error);
					return;
				}
				var databaseResult = resultData.data ? resultData.data.id: null;// if data isn't false use id_str otherwise null
				next( null, databaseResult);
			});
		}
		], function(err,result){ //json result
				if(err){
					res.json({'error':result}); //show error json result
				}else{
					console.log('Main callback: '+ result);
			 		res.json(result); //show json result
				}
			}
	);
	console.log('END PROGRAM'); // ending voice of  async waterfall
});

//method GET of the app at the path "../:message_id --> ObjectId("1234567890")"
app.get('/message/:message_id',function(req,res,next){
	var messageId = req.params.message_id; //request at the 'message_id' property
	console.log('PROGRAM START'); // start the async waterfall

	async.waterfall([
		function(next){
			// Database call
			console.log("(AppMex) Fetching a database record by ID");
			DatabaseModule.get(messageId, function databaseCallback( resultData ){ //from module database execute
				if ( resultData.success === false){ //if result is false return error data
					// Error calling the database
					next( true, resultData.error );
					return;
				}

				next(null, resultData.data); // <- Result from the database "resultData.data"
			});
		},
		//Twitter call
		function(databaseResult, next){ // argument is the resultData from database
			// Twitter call
			if ( !databaseResult || !databaseResult.tweet_id ){ //condition: if one of two is false return error
				next(true, "(App Mex) Error retrieving the tweet_id from the database...");
				return;
			}

			var tweet_id = databaseResult.tweet_id;
			TwitterModule.get(tweet_id, function twitterCallback( resultData ){
				if ( resultData.success === false){ // Error retrieving the tweet from Twitter
					// Error calling the database
					next( true, resultData.error );
					return;
				}

				var twitterResult = resultData.data;
				next(null, databaseResult, twitterResult);
			});
		},
		function(databaseResult, twitterResult, next){
			/// TODO: Facebook call
			if ( !databaseResult || !databaseResult.fb_id ){
				next( true, "(App Mex) Error retrieving the fb_id from the database...");
				return;
			}

			var fb_id = databaseResult.fb_id;
			console.log("The facebook id is ", fb_id);
			console.log(JSON.stringify(databaseResult));
			FacebookModule.get(fb_id, function facebookCallback( resultData ){
				if( resultData.success === false){ //Error retrieving the tweet from Facebook
					// Error calling the database
					next( true, resultData.error);
					return;
				}

				var facebookResult = resultData.data;
				next(null,databaseResult, twitterResult, facebookResult);
			});
		},
		function(databaseResult, twitterResult, facebookResult, next){
			var finalResult = {
				db: databaseResult,
				twitter: twitterResult,
				facebook: facebookResult
			};
			next(null, finalResult);
		}],
		function(err,result){ //<- Final function. It will return the result to the client
			if(err){
				res.json({ is_error: err, error: result});
				return;
			}

			res.json(result);
		}
	);
	console.log('END PROGRAM');
});

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});<commit_msg>GET async waterfall : twitter<commit_after>
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var async = require('async'); //Asincronous Waterfall
var mongoose = require('mongoose');

// modules of twitter , facebook and db
var DatabaseModule = require('./modules/dbModule'); //require module of database
var TwitterModule = require('./modules/twModule');  //require module of twitter
var FacebookModule = require('./modules/fbModule'); //require module of facebook

var app = express(); //main application

app.use(bodyParser.json());    //return middleware that only parses json (req.body)
app.use(bodyParser.urlencoded({ extended: true })); //return middleware that only parses urlencoded( UTF-8 )
app.use(express.static(__dirname + '/public'));

console.log('Start check problem'); // search block by console.log

//method POST of the app at the path "/message"
app.post('/message',function(req,res,next){

	var msg = req.body.message; //contains the key-value of the body-parsing
	console.log('message',msg); // see object msg

	console.log('PROGRAM START'); // starting voice of  async waterfall

	// Waterfall
	async.waterfall([    //runs an array of functions in series, each passing their results to the next in the array
		// Create Twitter message
		function ( next ){
			console.log( "(App Mex) message by Twitter" );
			TwitterModule.post( msg, function twitterCallback( resultData ){ //method post by module Twitter
				//data error
				if ( resultData.success === false ){ //if the result is false than return error
					next( true, resultData.error );
					return;
				}
				//data twitter is success
				var twitterId = resultData.data ? resultData.data.id_str : null; // if data isn't false use id_str otherwise null
				console.log('Twitter..........'+ twitterId); //output data twitterId
				next( null, resultData.data ); // passed data at next array with argument twitterId
			});
		},
		// Create Facebook message
		function ( twitterId, next){ //take value resultData.data in arg1
			if( !twitterId ){ //if twitterID is false  return error data
				next( true,"(App Mex) Error retrieving twitter data...");
				return;
			}
			// data facebook is success
			FacebookModule.post( msg, function facebookCallback( resultData ){ //method post by module Facebook
				if(resultData.success === false){ //if the result is false than return error
					next( true, resultData.error);
					return;
				}

				var facebookId = resultData.data ? resultData.data.id : null; // if data isn't false use id_str otherwise null
				console.log('Facebook........'+ facebookId); // output data FacebookId
				next(null, twitterId, facebookId); // passed data at next array with two arguments
			});
		},
		//Save Message in DB with Mongoose
		function (twitterId, facebookId, next){ //take two arguments
			if( !facebookId ) { //if facebookId is false return error data
				next( true,"(App Mex) Error retrieving facebook data..");
				return;
			}
			//Key-value JSON
			var dataToSave = {
				user_tw_id: process.env.USER_TW_ID, //use value of user id from twitter
				user_fb_id: process.env.USER_FB_ID, //use value of user id from facebook
				message: msg,  //body of the message
				tweet_id: twitterId, //use value of message id from twitter
				fb_id: facebookId  //use value of message id from facebook
			};

			DatabaseModule.post(dataToSave, function databaseCallback( resultData,next){ //method post by module database
				if(resultData.success === false){ //if the result is false than return error
					next( true, resultData.error);
					return;
				}
				var databaseResult = resultData.data ? resultData.data.id: null;// if data isn't false use id_str otherwise null
				next( null, databaseResult);
			});
		}
		], function(err,result){ //json result
				if(err){
					res.json({'error':result}); //show error json result
				}else{
					console.log('Main callback: '+ result);
			 		res.json(result); //show json result
				}
			}
	);
	console.log('END PROGRAM'); // ending voice of  async waterfall
});

//method GET of the app at the path "../:message_id --> ObjectId("1234567890")"
app.get('/message/:message_id',function(req,res,next){
	var messageId = req.params.message_id; //request at the 'message_id' property
	console.log('PROGRAM START'); // start the async waterfall

	async.waterfall([
		function(next){
			// Database call
			console.log("(AppMex) Fetching a database record by ID");
			DatabaseModule.get(messageId, function databaseCallback( resultData ){ //from module database execute
				if ( resultData.success === false){ //if result is false return error data
					// Error calling the database
					next( true, resultData.error );
					return;
				}

				next(null, resultData.data); // <- Result from the database "resultData.data"
			});
		},
		//Twitter call
		function(databaseResult, next){ // argument is the resultData from database
			// Twitter call
			if ( !databaseResult || !databaseResult.tweet_id ){ //condition: if one of two is false return error
				next(true, "(App Mex) Error retrieving the tweet_id from the database...");
				return;
			}

			var tweet_id = databaseResult.tweet_id;  // id to the message twitter
			TwitterModule.get(tweet_id, function twitterCallback( resultData ){  // from module twitter
				if ( resultData.success === false){ // Error retrieving the tweet from Twitter
					// Error calling the database
					next( true, resultData.error );
					return;
				}

				var twitterResult = resultData.data; // retrieving data twitter
				next(null, databaseResult, twitterResult); //result from twitter
			});
		},
		//Facebook call
		function(databaseResult, twitterResult, next){
			/// TODO: Facebook call
			if ( !databaseResult || !databaseResult.fb_id ){
				next( true, "(App Mex) Error retrieving the fb_id from the database...");
				return;
			}

			var fb_id = databaseResult.fb_id;
			console.log("The facebook id is ", fb_id);
			console.log(JSON.stringify(databaseResult));
			FacebookModule.get(fb_id, function facebookCallback( resultData ){
				if( resultData.success === false){ //Error retrieving the tweet from Facebook
					// Error calling the database
					next( true, resultData.error);
					return;
				}

				var facebookResult = resultData.data;
				next(null,databaseResult, twitterResult, facebookResult);
			});
		},
		function(databaseResult, twitterResult, facebookResult, next){
			var finalResult = {
				db: databaseResult,
				twitter: twitterResult,
				facebook: facebookResult
			};
			next(null, finalResult);
		}],
		function(err,result){ //<- Final function. It will return the result to the client
			if(err){
				res.json({ is_error: err, error: result});
				return;
			}

			res.json(result);
		}
	);
	console.log('END PROGRAM');
});

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});<|endoftext|>


<commit_before>'use strict';

(function () {
  var jogadorAtivo = 'j1';
  var fagoSelecionado;
  var lado = 20;
  var fabricaFagos = [];
  var quantidadeFagos = 7;

  $(window).load(() => {
    inicializarGrid();
    inicializarFabricaFagos();

    $('#grid').selectable({
      delay: 150,
      stop: realizarJogada,
      selecting: calcularTamanhoRetangulo,
      unselecting: calcularTamanhoRetangulo,
      disabled: true
    });

    $('.fagos').click((evento) => {
      var elemento = evento.target;
      if(elemento.parentNode.id === jogadorAtivo) {
        selecionarFago(elemento);
      };
    });
  });

  function inicializarGrid() {
    for (var i = 1; i <= (lado * lado); i++) {
      $('#grid').append('

');
    }
    $('#grid').css('width', (lado * 2 * 1.1) + 'em');
  }

  function inicializarFabricaFagos() {
    for(var i = 2; i < 10; i++) {
      for(var j = 2; j < 10; j++) {
        var produto = i * j;
        if(fabricaFagos.indexOf(produto) === -1) {
          fabricaFagos.push(produto);
        }
      }
    }

    fabricaFagos = fabricaFagos.sort((a, b) => {
      if(a === b) { return 0; }

      return a < b ? -1 : 1;
    });

    preencherFagosIniciais('j1');
    preencherFagosIniciais('j2');

    function preencherFagosIniciais(jogador) {
      for(var i = 0; i < quantidadeFagos; i++) {
        criarFago(jogador);
      }
    }
  }

  function criarFago(jogador) {
    var fago = obterFagoAleatorio();
    var elemento = $('
' + fago + '
');
    $('#' + jogador).append(elemento);
    elemento.slideDown();
  }

  function calcularTamanhoRetangulo(evento) {
    var selecting = $('.ui-selecting');
    var pontosSelecionados = [];
    for(var i = 0; i < selecting.length; i++) {
      pontosSelecionados.push(extrairPonto(selecting[i]));
    }

    if(pontosSelecionados.length !== 0) {
      mostrarConta(pontosSelecionados);
    }
  }

  function extrairPosicao(quadrado) {
    return Number.parseInt(quadrado.id.substring(1));
  }

  function extrairPonto(quadrado) {
    var posicao = extrairPosicao(quadrado) - 1;
    var x = (posicao % lado) + 1;
    var y = Math.floor(posicao / lado) + 1;
    return {x: x, y: y};
  }

  function cantoDireitoAbaixo(figura) {
    return figura.reduce((canto, ponto) => {
      return {
        x: canto.x > ponto.x ? canto.x : ponto.x,
        y: canto.y > ponto.y ? canto.y : ponto.y
      };
    }, {x: 0, y: 0});
  }

  function cantoEsquerdoAcima(figura) {
    return figura.reduce((canto, ponto) => {
      return {
        x: canto.x < ponto.x ? canto.x : ponto.x,
        y: canto.y < ponto.y ? canto.y : ponto.y
      };
    }, {x: Number.POSITIVE_INFINITY, y: Number.POSITIVE_INFINITY});
  }

  function mostrarConta(pontosSelecionados) {
    var menor = cantoEsquerdoAcima(pontosSelecionados);
    var maior = cantoDireitoAbaixo(pontosSelecionados);

    var x = maior.x - menor.x + 1;
    var y = maior.y - menor.y + 1;
    $('#conta').text(x + " x " + y + " = " + x * y);
  }

  function selecionarFago(fago) {
    fagoSelecionado = fago;
    $('.fagos li').removeClass('selecionado');
    $(fago).addClass('selecionado');
    $('#grid').selectable('enable');
  }

  function realizarJogada(event) {
    if(!fagoSelecionado) {
      return;
    }

    $('#conta').text("");
    var quadradosSelecionados = $('.ui-selected');
    var produtoSelecionado = $(fagoSelecionado).text();
    if(!(produtoSelecionado == quadradosSelecionados.size())
      || quadradosSelecionados.hasClass('ocupado')) {
      $('#grid li').removeClass('ui-selected');
      return;
    };

    $(fagoSelecionado).slideUp();
    criarFago(jogadorAtivo);

    var pontoInicial = preencherQuadradosOcupados(jogadorAtivo);
    var grid = montarGrid();
    fagocitar(jogadorAtivo, grid, pontoInicial);
    contarPontos(grid);

    jogadorAtivo = jogadorAtivo === 'j1' ? 'j2' : 'j1';
    limparJogada();
  }

  function contarPontos(grid) {
    var placarJ1 = 0;
    var placarJ2 = 0;

    for (var y = 0; y < lado + 1; y++) {
      for (var x = 0; x < lado + 1; x++) {
        if(grid[y][x].jogador === "j1") {
          placarJ1++;
        } else if(grid[y][x].jogador === "j2") {
          placarJ2++;
        }
      }
    }

    $('#placar-j1').text(placarJ1);
    $('#placar-j2').text(placarJ2);
  }

  function preencherQuadradosOcupados(jogador) {
    var selecionados = $('#grid .ui-selected');

    selecionados.addClass('ocupado');
    selecionados.addClass('ocupado' + jogador);

    var pontoInicial = extrairPonto(selecionados[0]);

    return pontoInicial;
  }

  function fagocitar(jogador, grid, pontoInicial) {
    function pontosAoRedor(ponto) {
      var pontos = [];

      if(ponto.x > 1) {
        pontos.push({x: ponto.x - 1, y: ponto.y});
      }
      if(ponto.x < lado) {
        pontos.push({x: ponto.x + 1, y: ponto.y});
      }
      if(ponto.y > 1) {
        pontos.push({x: ponto.x, y: ponto.y - 1});
      }
      if(ponto.y < lado) {
        pontos.push({x: ponto.x, y: ponto.y + 1});
      }
      return pontos;
    }

    Array.prototype.pIndexOf = function(p) {
      for (var i = 0; i < this.length; i++) {
        if (this[i].x == p.x && this[i].y == p.y) {
          return i;
        }
      }
      return -1;
    }

    var figura = [pontoInicial];

    for (var i = 0; i < figura.length; i++) {
      var ponto = figura[i];
      var proximosPontos = pontosAoRedor(ponto);

      proximosPontos.forEach((ponto) => {
        if(figura.pIndexOf(ponto) === -1 && grid[ponto.y][ponto.x].jogador === jogador) {
          figura.push(ponto);
        }
      });
    }

    var esquerdoAcima = cantoEsquerdoAcima(figura);
    var direitoAbaixo = cantoDireitoAbaixo(figura);

    var encontrouQuadradoCinza = false;
    for (var y = esquerdoAcima.y; y <= direitoAbaixo.y; y++) {
      for (var x = esquerdoAcima.x; x <= direitoAbaixo.x; x++) {
        if(!grid[y][x]) {
          encontrouQuadradoCinza = true;
          break;
        };
      }
      if(encontrouQuadradoCinza) {
        break;
      }
    }

    if(!encontrouQuadradoCinza) {
      for (var y = esquerdoAcima.y; y <= direitoAbaixo.y; y++) {
        for (var x = esquerdoAcima.x; x <= direitoAbaixo.x; x++) {
          grid[y][x].jogador = jogador; //inócuo
          $('#q' + grid[y][x].id).removeClass('ocupadoj1');
          $('#q' + grid[y][x].id).removeClass('ocupadoj2');
          $('#q' + grid[y][x].id).addClass('ocupado' + jogador);
        }
      }
    }
  }

  function montarGrid() {
    var grid = [];

    for (var y = 0; y < lado + 1; y++) {
      grid.push([]);
      for (var x = 0; x < lado + 1; x++) {
        grid[y][x] = "";
      }
    }

    var selecionados = $('#grid .ocupado');

    for (var i = 0; i < selecionados.length; i++) {
      var posicao = extrairPosicao(selecionados[i]);
      var ponto = extrairPonto(selecionados[i]);
      var jogador = $(selecionados[i]).hasClass("ocupadoj1") ? "j1" : "j2";
      grid[ponto.y][ponto.x] = {id: posicao, jogador: jogador};
    }

    return grid;
  }

  function limparJogada() {
    fagoSelecionado = undefined;
    $('#grid li').removeClass('ui-selected');
    $('#grid').selectable('disable');
  }

  function obterFagoAleatorio() {
    return fabricaFagos[obterNumeroAleatorio(0, fabricaFagos.length - 1)];
  }

  function obterNumeroAleatorio(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
})();
<commit_msg>atribuindo pesos aos fagos<commit_after>'use strict';

(function () {
  var jogadorAtivo = 'j1';
  var fagoSelecionado;
  var lado = 20;
  var fabricaFagos = [];
  var quantidadeFagos = 7;

  $(window).load(() => {
    inicializarGrid();
    inicializarFabricaFagos();

    $('#grid').selectable({
      delay: 150,
      stop: realizarJogada,
      selecting: calcularTamanhoRetangulo,
      unselecting: calcularTamanhoRetangulo,
      disabled: true
    });

    $('.fagos').click((evento) => {
      var elemento = evento.target;
      if(elemento.parentNode.id === jogadorAtivo) {
        selecionarFago(elemento);
      };
    });
  });

  function inicializarGrid() {
    for (var i = 1; i <= (lado * lado); i++) {
      $('#grid').append('

');
    }
    $('#grid').css('width', (lado * 2 * 1.1) + 'em');
  }

  function inicializarFabricaFagos() {
    var fagos = [];
    for(var i = 2; i < 10; i++) {
      for(var j = 2; j < 10; j++) {
        var produto = i * j;
        if(fagos.indexOf(produto) === -1) {
          fagos.push(produto);
        }
      }
    }

    fabricaFagos = fagos.sort((a, b) => {
      if(a === b) { return 0; }

      return a  {
      return {fago: fago, peso: 81 - fago};
    });

    preencherFagosIniciais('j1');
    preencherFagosIniciais('j2');

    function preencherFagosIniciais(jogador) {
      for(var i = 0; i < quantidadeFagos; i++) {
        criarFago(jogador);
      }
    }
  }

  function criarFago(jogador) {
    var fago = obterFagoAleatorio();
    var elemento = $('
' + fago + '
');
    $('#' + jogador).append(elemento);
    elemento.slideDown();
  }

  function calcularTamanhoRetangulo(evento) {
    var selecting = $('.ui-selecting');
    var pontosSelecionados = [];
    for(var i = 0; i < selecting.length; i++) {
      pontosSelecionados.push(extrairPonto(selecting[i]));
    }

    if(pontosSelecionados.length !== 0) {
      mostrarConta(pontosSelecionados);
    }
  }

  function extrairPosicao(quadrado) {
    return Number.parseInt(quadrado.id.substring(1));
  }

  function extrairPonto(quadrado) {
    var posicao = extrairPosicao(quadrado) - 1;
    var x = (posicao % lado) + 1;
    var y = Math.floor(posicao / lado) + 1;
    return {x: x, y: y};
  }

  function cantoDireitoAbaixo(figura) {
    return figura.reduce((canto, ponto) => {
      return {
        x: canto.x > ponto.x ? canto.x : ponto.x,
        y: canto.y > ponto.y ? canto.y : ponto.y
      };
    }, {x: 0, y: 0});
  }

  function cantoEsquerdoAcima(figura) {
    return figura.reduce((canto, ponto) => {
      return {
        x: canto.x < ponto.x ? canto.x : ponto.x,
        y: canto.y < ponto.y ? canto.y : ponto.y
      };
    }, {x: Number.POSITIVE_INFINITY, y: Number.POSITIVE_INFINITY});
  }

  function mostrarConta(pontosSelecionados) {
    var menor = cantoEsquerdoAcima(pontosSelecionados);
    var maior = cantoDireitoAbaixo(pontosSelecionados);

    var x = maior.x - menor.x + 1;
    var y = maior.y - menor.y + 1;
    $('#conta').text(x + " x " + y + " = " + x * y);
  }

  function selecionarFago(fago) {
    fagoSelecionado = fago;
    $('.fagos li').removeClass('selecionado');
    $(fago).addClass('selecionado');
    $('#grid').selectable('enable');
  }

  function realizarJogada(event) {
    if(!fagoSelecionado) {
      return;
    }

    $('#conta').text("");
    var quadradosSelecionados = $('.ui-selected');
    var produtoSelecionado = $(fagoSelecionado).text();
    if(!(produtoSelecionado == quadradosSelecionados.size())
      || quadradosSelecionados.hasClass('ocupado')) {
      $('#grid li').removeClass('ui-selected');
      return;
    };

    $(fagoSelecionado).slideUp();
    criarFago(jogadorAtivo);

    var pontoInicial = preencherQuadradosOcupados(jogadorAtivo);
    var grid = montarGrid();
    fagocitar(jogadorAtivo, grid, pontoInicial);
    contarPontos(grid);

    jogadorAtivo = jogadorAtivo === 'j1' ? 'j2' : 'j1';
    limparJogada();
  }

  function contarPontos(grid) {
    var placarJ1 = 0;
    var placarJ2 = 0;

    for (var y = 0; y < lado + 1; y++) {
      for (var x = 0; x < lado + 1; x++) {
        if(grid[y][x].jogador === "j1") {
          placarJ1++;
        } else if(grid[y][x].jogador === "j2") {
          placarJ2++;
        }
      }
    }

    $('#placar-j1').text(placarJ1);
    $('#placar-j2').text(placarJ2);
  }

  function preencherQuadradosOcupados(jogador) {
    var selecionados = $('#grid .ui-selected');

    selecionados.addClass('ocupado');
    selecionados.addClass('ocupado' + jogador);

    var pontoInicial = extrairPonto(selecionados[0]);

    return pontoInicial;
  }

  function fagocitar(jogador, grid, pontoInicial) {
    function pontosAoRedor(ponto) {
      var pontos = [];

      if(ponto.x > 1) {
        pontos.push({x: ponto.x - 1, y: ponto.y});
      }
      if(ponto.x < lado) {
        pontos.push({x: ponto.x + 1, y: ponto.y});
      }
      if(ponto.y > 1) {
        pontos.push({x: ponto.x, y: ponto.y - 1});
      }
      if(ponto.y < lado) {
        pontos.push({x: ponto.x, y: ponto.y + 1});
      }
      return pontos;
    }

    Array.prototype.pIndexOf = function(p) {
      for (var i = 0; i < this.length; i++) {
        if (this[i].x == p.x && this[i].y == p.y) {
          return i;
        }
      }
      return -1;
    }

    var figura = [pontoInicial];

    for (var i = 0; i < figura.length; i++) {
      var ponto = figura[i];
      var proximosPontos = pontosAoRedor(ponto);

      proximosPontos.forEach((ponto) => {
        if(figura.pIndexOf(ponto) === -1 && grid[ponto.y][ponto.x].jogador === jogador) {
          figura.push(ponto);
        }
      });
    }

    var esquerdoAcima = cantoEsquerdoAcima(figura);
    var direitoAbaixo = cantoDireitoAbaixo(figura);

    var encontrouQuadradoCinza = false;
    for (var y = esquerdoAcima.y; y <= direitoAbaixo.y; y++) {
      for (var x = esquerdoAcima.x; x <= direitoAbaixo.x; x++) {
        if(!grid[y][x]) {
          encontrouQuadradoCinza = true;
          break;
        };
      }
      if(encontrouQuadradoCinza) {
        break;
      }
    }

    if(!encontrouQuadradoCinza) {
      for (var y = esquerdoAcima.y; y <= direitoAbaixo.y; y++) {
        for (var x = esquerdoAcima.x; x <= direitoAbaixo.x; x++) {
          grid[y][x].jogador = jogador; //inócuo
          $('#q' + grid[y][x].id).removeClass('ocupadoj1');
          $('#q' + grid[y][x].id).removeClass('ocupadoj2');
          $('#q' + grid[y][x].id).addClass('ocupado' + jogador);
        }
      }
    }
  }

  function montarGrid() {
    var grid = [];

    for (var y = 0; y < lado + 1; y++) {
      grid.push([]);
      for (var x = 0; x < lado + 1; x++) {
        grid[y][x] = "";
      }
    }

    var selecionados = $('#grid .ocupado');

    for (var i = 0; i < selecionados.length; i++) {
      var posicao = extrairPosicao(selecionados[i]);
      var ponto = extrairPonto(selecionados[i]);
      var jogador = $(selecionados[i]).hasClass("ocupadoj1") ? "j1" : "j2";
      grid[ponto.y][ponto.x] = {id: posicao, jogador: jogador};
    }

    return grid;
  }

  function limparJogada() {
    fagoSelecionado = undefined;
    $('#grid li').removeClass('ui-selected');
    $('#grid').selectable('disable');
  }

  function obterFagoAleatorio() {
    return fabricaFagos[obterNumeroAleatorio(0, fabricaFagos.length - 1)].fago;
  }

  function obterNumeroAleatorio(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
})();
<|endoftext|>


<commit_before>module.exports = RedSess

var redis = require("redis")
RedSess.client = null

var Cookies = require('cookies')
var util = require('util')

// optional dependency
try { var KeyGrip = require('keygrip') } catch (e) {}

function RedSess (req, res, opt) {
  if (!(this instanceof RedSess))
    return new RedSess(req, res, opt)

  opt = opt || {}
  if (!RedSess.client && !opt.client) {
    console.error('RedSess: no client yet', req.url, req.headers)
    res.statusCode = 503
    res.setHeader('content-type', 'text/plain')
    res.setHeader('retry-after', '10')
    res.end('Redis client not yet loaded.\n')
    return
  }

  // if we got an array of strings rather than a keygrip, then
  // keygrip it up.
  if (opt.keys) {
    if (!KeyGrip)
      throw new Error('keys provided by KeyGrip not available')
    else if (Array.isArray(opt.keys))
      this.keys = new KeyGrip(opt.keys)
    else if (opt.keys instanceof KeyGrip)
      this.keys = opt.keys
    else
      throw new Error('invalid keys provided')
  }

  // 2 week sessions by default.
  this.expire = opt.expire || 60 * 60 * 24 * 14

  // set up the cookies thingie
  this.cookies = opt.cookies || new Cookies(req, res, this.keys)

  // set the s-cookie
  var name = this.cookieName = opt.cookieName || 's'
  var expireDate = new Date(Date.now() + (this.expire*1000))
  var cookieOptions = opt && opt.cookieOptions || {}
  var copt = util._extend({
    expires: expireDate,
    signed: !!this.keys
  }, cookieOptions)

  var s = this.cookies.get(name, copt)
  if (!s)
    s = require('crypto').randomBytes(30).toString('base64')

  this.cookies.set(name, s, copt)
  this.token = s

  if (!this.token)
    throw new Error('could not load session token')

  this.id = "session:" + this.token
  this.client = opt.client || RedSess.client
  this.request = req
  this.response = res
}

RedSess.createClient = function (conf) {
  conf = conf || {}
  RedSess.client = redis.createClient(conf.port, conf.host, conf)
  if (conf.auth)
    RedSess.client.auth(conf.auth)
  return RedSess.client
}

RedSess.quit = RedSess.close = RedSess.end = function (cb) {
  if (!RedSess.client)
    return cb && cb()
  if (cb)
    RedSess.client.once("end", cb)
  RedSess.client.quit()
}

RedSess.destroy = function () {
  RedSess.client.end()
}

RedSess.prototype.del = function (k, cb) {
  if (typeof k === 'function' || !k && !cb)
    return this.delAll(k || cb)

  // actually, delete all keys starting with k:* as well
  this.client.hkeys(this.id, function (er, keys) {
    if (er)
      return cb && cb(er)

    var keys = keys.filter(function (key) {
      return key.split(/:/)[0] === k
    })

    if (!keys.length)
      return cb && cb()

    keys.unshift(this.id)
    this.client.hdel(keys, function (er) {
      this.client.expire(this.id, this.expire)
      if (cb)
        return cb(er)
    }.bind(this))
  }.bind(this))
}

RedSess.prototype.delAll = function (cb) {
  this.client.del(this.id, cb || function(){})
}

// delete all data, and kill the session entirely
RedSess.prototype.destroy = function (cb) {
  this.client.del(this.id, function (er) {
    this.cookies.set(this.cookieName, '', {
      expires: new Date(0),
      signed: !!this.keys
    })
    cb(er)
  }.bind(this))
}

RedSess.prototype.set = function (k, v, cb) {
  var kv = {}

  if (typeof v === 'function')
    cb = v, v = null

  if (v)
    kv[k] = v
  else
    kv = k

  kv = flatten(kv)
  this.client.hmset(this.id, kv, function (er) {
    this.client.expire(this.id, this.expire)
    if (cb)
      return cb(er)
  }.bind(this))
}

RedSess.prototype.get = function (k, cb) {
  if (typeof k === 'function' || !k)
    return this.getAll(k || cb)

  if (!cb)
    return this.client.expire(this.id, this.expire)

  this.getAll(function (er, all) {
    if (er || !all)
      return cb(er, null)
    return cb(null, all.hasOwnProperty(k) ? all[k] : null)
  }.bind(this))
}

RedSess.prototype.getAll = function (cb) {
  // if no cb, then just update the expiration
  if (!cb)
    return this.client.expire(this.id, this.expire)

  this.client.hgetall(this.id, function (er, data) {
    this.client.expire(this.id, this.expire)
    if (!er)
      data = unflatten(data)
    cb(er, data)
  }.bind(this))
}

function flatten (obj, into, prefix) {
  if (!obj) return obj
  into = into || {}
  prefix = prefix || ''
  if (prefix) prefix += ':'
  Object.keys(obj).forEach(function (k) {
    if (obj[k] && typeof obj[k] === "object") {
      flatten(obj[k], into, prefix + k)
    } else into[prefix + k] = '' + obj[k]
  })
  return into
}

function unflatten (obj) {
  if (!obj || typeof obj !== "object") return obj
  var into = {}
  Object.keys(obj).forEach(function (k) {
    // actually an object
    var m = k.split(/:/)
    , tail = m.pop()
    , p = into

    m.forEach(function (n) {
      if (!p[n] || typeof p[n] !== "object") p[n] = {}
      p = p[n]
    })
    p[tail] = obj[k]

  })
  return into
}
<commit_msg>don't flatten non-objects<commit_after>module.exports = RedSess

var redis = require("redis")
RedSess.client = null

var Cookies = require('cookies')
var util = require('util')

// optional dependency
try { var KeyGrip = require('keygrip') } catch (e) {}

function RedSess (req, res, opt) {
  if (!(this instanceof RedSess))
    return new RedSess(req, res, opt)

  opt = opt || {}
  if (!RedSess.client && !opt.client) {
    console.error('RedSess: no client yet', req.url, req.headers)
    res.statusCode = 503
    res.setHeader('content-type', 'text/plain')
    res.setHeader('retry-after', '10')
    res.end('Redis client not yet loaded.\n')
    return
  }

  // if we got an array of strings rather than a keygrip, then
  // keygrip it up.
  if (opt.keys) {
    if (!KeyGrip)
      throw new Error('keys provided by KeyGrip not available')
    else if (Array.isArray(opt.keys))
      this.keys = new KeyGrip(opt.keys)
    else if (opt.keys instanceof KeyGrip)
      this.keys = opt.keys
    else
      throw new Error('invalid keys provided')
  }

  // 2 week sessions by default.
  this.expire = opt.expire || 60 * 60 * 24 * 14

  // set up the cookies thingie
  this.cookies = opt.cookies || new Cookies(req, res, this.keys)

  // set the s-cookie
  var name = this.cookieName = opt.cookieName || 's'
  var expireDate = new Date(Date.now() + (this.expire*1000))
  var cookieOptions = opt && opt.cookieOptions || {}
  var copt = util._extend({
    expires: expireDate,
    signed: !!this.keys
  }, cookieOptions)

  var s = this.cookies.get(name, copt)
  if (!s)
    s = require('crypto').randomBytes(30).toString('base64')

  this.cookies.set(name, s, copt)
  this.token = s

  if (!this.token)
    throw new Error('could not load session token')

  this.id = "session:" + this.token
  this.client = opt.client || RedSess.client
  this.request = req
  this.response = res
}

RedSess.createClient = function (conf) {
  conf = conf || {}
  RedSess.client = redis.createClient(conf.port, conf.host, conf)
  if (conf.auth)
    RedSess.client.auth(conf.auth)
  return RedSess.client
}

RedSess.quit = RedSess.close = RedSess.end = function (cb) {
  if (!RedSess.client)
    return cb && cb()
  if (cb)
    RedSess.client.once("end", cb)
  RedSess.client.quit()
}

RedSess.destroy = function () {
  RedSess.client.end()
}

RedSess.prototype.del = function (k, cb) {
  if (typeof k === 'function' || !k && !cb)
    return this.delAll(k || cb)

  // actually, delete all keys starting with k:* as well
  this.client.hkeys(this.id, function (er, keys) {
    if (er)
      return cb && cb(er)

    var keys = keys.filter(function (key) {
      return key.split(/:/)[0] === k
    })

    if (!keys.length)
      return cb && cb()

    keys.unshift(this.id)
    this.client.hdel(keys, function (er) {
      this.client.expire(this.id, this.expire)
      if (cb)
        return cb(er)
    }.bind(this))
  }.bind(this))
}

RedSess.prototype.delAll = function (cb) {
  this.client.del(this.id, cb || function(){})
}

// delete all data, and kill the session entirely
RedSess.prototype.destroy = function (cb) {
  this.client.del(this.id, function (er) {
    this.cookies.set(this.cookieName, '', {
      expires: new Date(0),
      signed: !!this.keys
    })
    cb(er)
  }.bind(this))
}

RedSess.prototype.set = function (k, v, cb) {
  var kv = {}

  if (typeof v === 'function')
    cb = v, v = null

  if (v)
    kv[k] = v
  else
    kv = k

  kv = flatten(kv)
  this.client.hmset(this.id, kv, function (er) {
    this.client.expire(this.id, this.expire)
    if (cb)
      return cb(er)
  }.bind(this))
}

RedSess.prototype.get = function (k, cb) {
  if (typeof k === 'function' || !k)
    return this.getAll(k || cb)

  if (!cb)
    return this.client.expire(this.id, this.expire)

  this.getAll(function (er, all) {
    if (er || !all)
      return cb(er, null)
    return cb(null, all.hasOwnProperty(k) ? all[k] : null)
  }.bind(this))
}

RedSess.prototype.getAll = function (cb) {
  // if no cb, then just update the expiration
  if (!cb)
    return this.client.expire(this.id, this.expire)

  this.client.hgetall(this.id, function (er, data) {
    this.client.expire(this.id, this.expire)
    if (!er)
      data = unflatten(data)
    cb(er, data)
  }.bind(this))
}

function flatten (obj, into, prefix) {
  if (!obj || typeof obj !== 'object') return obj
  into = into || {}
  prefix = prefix || ''
  if (prefix) prefix += ':'
  Object.keys(obj).forEach(function (k) {
    if (obj[k] && typeof obj[k] === "object") {
      flatten(obj[k], into, prefix + k)
    } else into[prefix + k] = '' + obj[k]
  })
  return into
}

function unflatten (obj) {
  if (!obj || typeof obj !== "object") return obj
  var into = {}
  Object.keys(obj).forEach(function (k) {
    // actually an object
    var m = k.split(/:/)
    , tail = m.pop()
    , p = into

    m.forEach(function (n) {
      if (!p[n] || typeof p[n] !== "object") p[n] = {}
      p = p[n]
    })
    p[tail] = obj[k]

  })
  return into
}
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  main: 'bin',
  key: [
    {
      files: [
        'bin'
      ]
    },
    {
      keywords: []
    },
    {
      homepage: ''
    },
    {
      bin: {
        dish: 'bin/index.js'
      }
    }
  ]
};
<commit_msg>feat(npm): add engines to cli-template<commit_after>'use strict';

module.exports = {
  main: 'bin',
  key: [
    {
      files: [
        'bin'
      ]
    },
    {
      keywords: []
    },
    {
      homepage: ''
    },
    {
      bin: {
        dish: 'bin/index.js'
      }
    },
    {
      engines: {
        node: '>=4'
      }
    }
  ]
};
<|endoftext|>


<commit_before>
module.exports = (state, action) => {
  const newState = require('clone')(state)
  const {type, payload} = action
  switch(type) {
    case 'LOGIN_INIT':
      newState.loginInProgress = true
      return newState
    case 'LOGIN_SUCCESSFUL':
      newState.loginInProgress = false
      newState.loginUnsuccessful = false
      newState.currentUser = payload
      return newState
    case 'LOGIN_UNSUCCESSFUL':
      newState.loginInProgress = false
      newState.loginUnsuccessful = true
      return newState
    case 'CHANGE_PAGE':
      newState.currentPage = payload
      return newState
    case 'UP_VOTE':
      newState.flops.find(flop => flop.flopId == payload).upvotes++
      return newState
    case 'DOWN_VOTE':
    var correctFlop = newState.flops.find(flop => flop.flopId == payload)
    correctFlop.downvotes ++
    return newState
    case 'RECEIVE_LIFESTYLES':
      newState.requestingLifestyles = false
      newState.lifestyles = payload
      return newState
    case 'RECEIVE_FLOPS':
      newState.requestingFlops = false
      newState.flops = payload
      return newState
    case 'RECEIVE_CURRENT_USER':
      newState.currentUser = payload
      return newState
    case 'CHANGE_CURRENTLIFESTYLEID':
      newState.currentLifestyleId = payload
      return newState
    case 'REQUEST_LIFESTYLES':
      newState.requestingLifestyles = true
      return newState
    case 'REQUEST_FLOPS':
      newState.requestingFlops = true
      return newState
    default:
      return newState
  }
}
<commit_msg>Fix some indentations on the reducer<commit_after>
module.exports = (state, action) => {
  const newState = require('clone')(state)
  const {type, payload} = action
  switch(type) {
    case 'LOGIN_INIT':
      newState.loginInProgress = true
      return newState
    case 'LOGIN_SUCCESSFUL':
      newState.loginInProgress = false
      newState.loginUnsuccessful = false
      newState.currentUser = payload
      return newState
    case 'LOGIN_UNSUCCESSFUL':
      newState.loginInProgress = false
      newState.loginUnsuccessful = true
      return newState
    case 'CHANGE_PAGE':
      newState.currentPage = payload
      return newState
    case 'UP_VOTE':
      newState.flops.find(flop => flop.flopId == payload).upvotes++
      return newState
    case 'DOWN_VOTE':
      var correctFlop = newState.flops.find(flop => flop.flopId == payload)
      correctFlop.downvotes ++
      return newState
    case 'RECEIVE_LIFESTYLES':
      newState.requestingLifestyles = false
      newState.lifestyles = payload
      return newState
    case 'RECEIVE_FLOPS':
      newState.requestingFlops = false
      newState.flops = payload
      return newState
    case 'RECEIVE_CURRENT_USER':
      newState.currentUser = payload
      return newState
    case 'CHANGE_CURRENTLIFESTYLEID':
      newState.currentLifestyleId = payload
      return newState
    case 'REQUEST_LIFESTYLES':
      newState.requestingLifestyles = true
      return newState
    case 'REQUEST_FLOPS':
      newState.requestingFlops = true
      return newState
    default:
      return newState
  }
}
<|endoftext|>


<commit_before>/**
 * icu-converter
 * https://github.com/alex-dow/icu-converter
 *
 * Copyright (c) 2015 Alex Dowgailenko
 * Licensed under the MIT License
 * https://github.com/alex-dow/icu-converter/blob/master/LICENSE
 */
'use strict';

var _ = require('lodash');
var fs = require('fs');
var parser = require('./icu-format-parser');

/**
 * ICU Converter
 *
 * Converts a resource bundle to a Javascript object
 */
var ICUConverter = function(opts) {

    var defaultOptions = {
        encoding: 'utf-8'
    };

    this.options = _.defaults({}, opts, defaultOptions);

    this.validTypes = [
      'array',
      'string',
      'table'
    ];
};

/**
 * Checks to see if a string ends with a particular suffix
 */
function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

/**
 * Parse a resource bundle
 */
ICUConverter.prototype.parse = function(resourceBundle) {
  return parser.parse(resourceBundle);
};

/**
 * Parses a key name.
 *
 * If the keyname ends in :[datatype] then it is removed
 */
ICUConverter.prototype.parseKeyname = function(keyname) {

  this.validTypes.forEach(function(type) {
    var keyType = ':' + type;
    if (endsWith(keyname, keyType)) {
      keyname = keyname.substr(0, keyname.length - keyType.length);
    }
  });

  return keyname;
};

/**
 * Convert the contents of a file and write it to output dir
 */
ICUConverter.prototype.convertFile = function(fileName) {

  var grammar = fs.readFileSync(fileName, this.options.encoding);

  return this.convert(grammar);

};

/**
 * Convert a resource bundle to a javascript object
 */
ICUConverter.prototype.convert = function(resourceBundle) {

  var ast = this.parse(resourceBundle);

  var processedObject;

  if (_.isArray(ast.elements)) {
    processedObject = [];
    processedObject[this.parseKeyname(ast.keyName)] = {};
    ast.elements.forEach(function(el) {
      processedObject.push(this.deferProcessing(el));
    }.bind(this));
  } else {
    processedObject = this.deferProcessing(ast.elements);
  }

  var res = {};
  if (_.isArray(processedObject)) {
    processedObject.forEach(function(obj) {
      var key = this.parseKeyname(_.keys(obj).pop());
      res[key] = obj[key];
    }.bind(this));
  } else {
    res = processedObject;
  }

  var returnValue = {};
  returnValue[this.parseKeyname(ast.keyName)] = res;

  return returnValue;
};

/**
 * Process a table element
 */
ICUConverter.prototype.processTable = function(obj) {

  var tbl = {};
  if (_.isArray(obj.elements)) {
    obj.elements.forEach(function(el) {
      tbl[this.parseKeyname(el.keyName)] = this.deferProcessing(el);
    }.bind(this));
  } else {
    tbl[this.parseKeyname(obj.keyName)] = this.deferProcessing(obj.elements);
  }
  return tbl;
};

/**
 * Process an array element
 */
ICUConverter.prototype.processArray = function(obj) {
  var res = [];
  obj.value.forEach(function(el) {
    res.push(this.deferProcessing(el));
  }.bind(this));
  return res;
};

/**
 * Process a string element
 */
ICUConverter.prototype.processString = function(obj) {
  return obj.value;
};

/**
 * Take an element, and process it using the appropriate method for that element's type
 */
ICUConverter.prototype.deferProcessing = function(obj) {
  var returnValue;
  switch (obj.type) {
    case 'table':
      returnValue = this.processTable(obj);
      break;
    case 'string':
      returnValue = this.processString(obj);
      break;
    case 'array':
      returnValue = this.processArray(obj);
      break;
    default:
      throw new Error('Unknown type: ' + obj.type);
  }
  return returnValue;
};

module.exports = ICUConverter;
<commit_msg>If a string is multiline, then split by newlines and trim<commit_after>/**
 * icu-converter
 * https://github.com/alex-dow/icu-converter
 *
 * Copyright (c) 2015 Alex Dowgailenko
 * Licensed under the MIT License
 * https://github.com/alex-dow/icu-converter/blob/master/LICENSE
 */
'use strict';

var _ = require('lodash');
var fs = require('fs');
var parser = require('./icu-format-parser');

/**
 * ICU Converter
 *
 * Converts a resource bundle to a Javascript object
 */
var ICUConverter = function(opts) {

    var defaultOptions = {
        encoding: 'utf-8'
    };

    this.options = _.defaults({}, opts, defaultOptions);

    this.validTypes = [
      'array',
      'string',
      'table'
    ];
};

/**
 * Checks to see if a string ends with a particular suffix
 */
function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

/**
 * Parse a resource bundle
 */
ICUConverter.prototype.parse = function(resourceBundle) {
  return parser.parse(resourceBundle);
};

/**
 * Parses a key name.
 *
 * If the keyname ends in :[datatype] then it is removed
 */
ICUConverter.prototype.parseKeyname = function(keyname) {

  this.validTypes.forEach(function(type) {
    var keyType = ':' + type;
    if (endsWith(keyname, keyType)) {
      keyname = keyname.substr(0, keyname.length - keyType.length);
    }
  });

  return keyname;
};

/**
 * Convert the contents of a file and write it to output dir
 */
ICUConverter.prototype.convertFile = function(fileName) {

  var grammar = fs.readFileSync(fileName, this.options.encoding);

  return this.convert(grammar);

};

/**
 * Convert a resource bundle to a javascript object
 */
ICUConverter.prototype.convert = function(resourceBundle) {

  var ast = this.parse(resourceBundle);

  var processedObject;

  if (_.isArray(ast.elements)) {
    processedObject = [];
    processedObject[this.parseKeyname(ast.keyName)] = {};
    ast.elements.forEach(function(el) {
      processedObject.push(this.deferProcessing(el));
    }.bind(this));
  } else {
    processedObject = this.deferProcessing(ast.elements);
  }

  var res = {};
  if (_.isArray(processedObject)) {
    processedObject.forEach(function(obj) {
      var key = this.parseKeyname(_.keys(obj).pop());
      res[key] = obj[key];
    }.bind(this));
  } else {
    res = processedObject;
  }

  var returnValue = {};
  returnValue[this.parseKeyname(ast.keyName)] = res;

  return returnValue;
};

/**
 * Process a table element
 */
ICUConverter.prototype.processTable = function(obj) {

  var tbl = {};
  if (_.isArray(obj.elements)) {
    obj.elements.forEach(function(el) {
      tbl[this.parseKeyname(el.keyName)] = this.deferProcessing(el);
    }.bind(this));
  } else {
    tbl[this.parseKeyname(obj.keyName)] = this.deferProcessing(obj.elements);
  }
  return tbl;
};

/**
 * Process an array element
 */
ICUConverter.prototype.processArray = function(obj) {
  var res = [];
  obj.value.forEach(function(el) {
    res.push(this.deferProcessing(el));
  }.bind(this));
  return res;
};

ICUConverter.prototype.processMultilineString = function(str) {
  var lines = str.split("\n");
  var newString = [];
  for (var i = 0; i < lines.length; i++) {
    newString.push(lines[i].trim());
  }
  return newString.join('\n');
};

/**
 * Process a string element
 */
ICUConverter.prototype.processString = function(obj) {

  var str = obj.value;

  if (str.indexOf("\n") !== -1) {
    str = this.processMultilineString(str);
  }
  return str;
};

/**
 * Take an element, and process it using the appropriate method for that element's type
 */
ICUConverter.prototype.deferProcessing = function(obj) {
  var returnValue;
  switch (obj.type) {
    case 'table':
      returnValue = this.processTable(obj);
      break;
    case 'string':
      returnValue = this.processString(obj);
      break;
    case 'array':
      returnValue = this.processArray(obj);
      break;
    default:
      throw new Error('Unknown type: ' + obj.type);
  }
  return returnValue;
};

module.exports = ICUConverter;
<|endoftext|>


<commit_before>/**
 * icu-converter
 * https://github.com/alex-dow/icu-converter
 *
 * Copyright (c) 2015 Alex Dowgailenko
 * Licensed under the MIT License
 * https://github.com/alex-dow/icu-converter/blob/master/LICENSE
 */
'use strict';

var _ = require('lodash');
var fs = require('fs');
var parser = require('./icu-format-parser');

/**
 * ICU Converter
 *
 * Converts a resource bundle to a Javascript object
 */
var ICUConverter = function(opts) {

    var defaultOptions = {
        encoding: 'utf-8'
    };

    this.options = _.defaults({}, opts, defaultOptions);

    this.validTypes = [
      'array',
      'string',
      'table'
    ];
};

/**
 * Checks to see if a string ends with a particular suffix
 */
function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

/**
 * Parse a resource bundle
 */
ICUConverter.prototype.parse = function(resourceBundle) {
  return parser.parse(resourceBundle);
};

/**
 * Parses a key name.
 *
 * If the keyname ends in :[datatype] then it is removed
 */
ICUConverter.prototype.parseKeyname = function(keyname) {

  this.validTypes.forEach(function(type) {
    var keyType = ':' + type;
    if (endsWith(keyname, keyType)) {
      keyname = keyname.substr(0, keyname.length - keyType.length);
    }
  });

  return keyname;
};

/**
 * Convert the contents of a file and write it to output dir
 */
ICUConverter.prototype.convertFile = function(fileName) {

  var grammar = fs.readFileSync(fileName, this.options.encoding);

  return this.convert(grammar);

};

/**
 * Convert a resource bundle to a javascript object
 */
ICUConverter.prototype.convert = function(resourceBundle) {

  var ast = this.parse(resourceBundle);

  var processedObject;

  if (_.isArray(ast.elements)) {
    processedObject = [];
    processedObject[this.parseKeyname(ast.keyName)] = {};
    ast.elements.forEach(function(el) {
      processedObject.push(this.deferProcessing(el));
    }.bind(this));
  } else {
    processedObject = this.deferProcessing(ast.elements);
  }

  var res = {};
  if (_.isArray(processedObject)) {
    processedObject.forEach(function(obj) {
      var key = this.parseKeyname(_.keys(obj).pop());
      res[key] = obj[key];
    }.bind(this));
  } else {
    res = processedObject;
  }

  var returnValue = {};
  returnValue[this.parseKeyname(ast.keyName)] = res;

  return returnValue;
};

/**
 * Process a table element
 */
ICUConverter.prototype.processTable = function(obj) {

  var tbl = {};
  if (_.isArray(obj.elements)) {
    var tblElements = {};

    obj.elements.forEach(function(el) {
      tbl[this.parseKeyname(el.keyName)] = this.deferProcessing(el);
    }.bind(this));

  } else {
    tbl[this.parseKeyname(obj.keyName)] = this.deferProcessing(obj.elements);
  }
  return tbl;
};

/**
 * Process an array element
 */
ICUConverter.prototype.processArray = function(obj) {
  var res = [];
  obj.value.forEach(function(el) {
    res.push(this.deferProcessing(el));
  }.bind(this));
  return res;
};

/**
 * Process a string element
 */
ICUConverter.prototype.processString = function(obj) {
  return obj.value;
};

/**
 * Take an element, and process it using the appropriate method for that element's type
 */
ICUConverter.prototype.deferProcessing = function(obj) {
  var returnValue;
  switch (obj.type) {
    case 'table':
      returnValue = this.processTable(obj);
      break;
    case 'string':
      returnValue = this.processString(obj);
      break;
    case 'array':
      returnValue = this.processArray(obj);
      break;
    default:
      throw new Error('Unknown type: ' + obj.type);
  }
  return returnValue;
};

module.exports = ICUConverter;
<commit_msg>Removed useless variable<commit_after>/**
 * icu-converter
 * https://github.com/alex-dow/icu-converter
 *
 * Copyright (c) 2015 Alex Dowgailenko
 * Licensed under the MIT License
 * https://github.com/alex-dow/icu-converter/blob/master/LICENSE
 */
'use strict';

var _ = require('lodash');
var fs = require('fs');
var parser = require('./icu-format-parser');

/**
 * ICU Converter
 *
 * Converts a resource bundle to a Javascript object
 */
var ICUConverter = function(opts) {

    var defaultOptions = {
        encoding: 'utf-8'
    };

    this.options = _.defaults({}, opts, defaultOptions);

    this.validTypes = [
      'array',
      'string',
      'table'
    ];
};

/**
 * Checks to see if a string ends with a particular suffix
 */
function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

/**
 * Parse a resource bundle
 */
ICUConverter.prototype.parse = function(resourceBundle) {
  return parser.parse(resourceBundle);
};

/**
 * Parses a key name.
 *
 * If the keyname ends in :[datatype] then it is removed
 */
ICUConverter.prototype.parseKeyname = function(keyname) {

  this.validTypes.forEach(function(type) {
    var keyType = ':' + type;
    if (endsWith(keyname, keyType)) {
      keyname = keyname.substr(0, keyname.length - keyType.length);
    }
  });

  return keyname;
};

/**
 * Convert the contents of a file and write it to output dir
 */
ICUConverter.prototype.convertFile = function(fileName) {

  var grammar = fs.readFileSync(fileName, this.options.encoding);

  return this.convert(grammar);

};

/**
 * Convert a resource bundle to a javascript object
 */
ICUConverter.prototype.convert = function(resourceBundle) {

  var ast = this.parse(resourceBundle);

  var processedObject;

  if (_.isArray(ast.elements)) {
    processedObject = [];
    processedObject[this.parseKeyname(ast.keyName)] = {};
    ast.elements.forEach(function(el) {
      processedObject.push(this.deferProcessing(el));
    }.bind(this));
  } else {
    processedObject = this.deferProcessing(ast.elements);
  }

  var res = {};
  if (_.isArray(processedObject)) {
    processedObject.forEach(function(obj) {
      var key = this.parseKeyname(_.keys(obj).pop());
      res[key] = obj[key];
    }.bind(this));
  } else {
    res = processedObject;
  }

  var returnValue = {};
  returnValue[this.parseKeyname(ast.keyName)] = res;

  return returnValue;
};

/**
 * Process a table element
 */
ICUConverter.prototype.processTable = function(obj) {

  var tbl = {};
  if (_.isArray(obj.elements)) {
    obj.elements.forEach(function(el) {
      tbl[this.parseKeyname(el.keyName)] = this.deferProcessing(el);
    }.bind(this));
  } else {
    tbl[this.parseKeyname(obj.keyName)] = this.deferProcessing(obj.elements);
  }
  return tbl;
};

/**
 * Process an array element
 */
ICUConverter.prototype.processArray = function(obj) {
  var res = [];
  obj.value.forEach(function(el) {
    res.push(this.deferProcessing(el));
  }.bind(this));
  return res;
};

/**
 * Process a string element
 */
ICUConverter.prototype.processString = function(obj) {
  return obj.value;
};

/**
 * Take an element, and process it using the appropriate method for that element's type
 */
ICUConverter.prototype.deferProcessing = function(obj) {
  var returnValue;
  switch (obj.type) {
    case 'table':
      returnValue = this.processTable(obj);
      break;
    case 'string':
      returnValue = this.processString(obj);
      break;
    case 'array':
      returnValue = this.processArray(obj);
      break;
    default:
      throw new Error('Unknown type: ' + obj.type);
  }
  return returnValue;
};

module.exports = ICUConverter;
<|endoftext|>


<commit_before>/* scrollprogress v2.1.2 - 2017 Jeremias Menichelli - MIT License */
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  typeof define === 'function' && define.amd ? define(factory) :
  (global.ScrollProgress = factory());
}(this, (function () { 'use strict';

  /**
   * Fallback noop function
   * @method noop
   * @returns {undefined}
   */
  function noop() {}

  /**
   * ScrollProgress class constructor
   * @constructor ScrollProgress
   * @param {Function} handleUpdate method to call on scroll update
   * @returns {undefined}
   */
  var ScrollProgress = function(handleUpdate) {
    // assign function to call on update
    this._handleUpdate = typeof handleUpdate === 'function'
      ? handleUpdate
      : noop;

    // set initial values
    this._viewportHeight = this._getViewportHeight();
    this._viewportWidth = this._getViewportWidth();

    this._progress = this._getProgress();

    // trigger initial update function
    this._handleUpdate(0, this._progress);

    // bind event functions
    this._onScroll = this._onScroll.bind(this);
    this._onResize = this._onResize.bind(this);

    // add event listeners
    window.addEventListener('scroll', this._onScroll);
    window.addEventListener('resize', this._onResize);
  };

  /**
   * Get vertical trajectory of the viewport
   * @method _getViewportHeight
   * @returns {Number}
   */
  ScrollProgress.prototype._getViewportHeight = function() {
    return document.body.scrollHeight - window.innerHeight;
  };

  /**
   * Get horizontal trajectory of the viewport
   * @method _getViewportWidth
   * @returns {Number}
   */
  ScrollProgress.prototype._getViewportWidth = function() {
    return document.body.scrollWidth - window.innerWidth;
  };

  /**
   * Get scroll progress on both axis
   * @method _getProgress
   * @returns {Object}
   */
  ScrollProgress.prototype._getProgress = function() {
    var x = window.scrollX || window.pageXOffset;
    var y = window.scrollY || window.pageYOffset;

    return {
      x: x / this._viewportWidth,
      y: y / this._viewportHeight
    };
  };

  /**
   * Get scroll progress on both axis
   * @method _getProgress
   * @returns {undefined}
   */
  ScrollProgress.prototype._onScroll = function() {
    this._progress = this._getProgress();
    this._handleUpdate(this._progress.x, this._progress.y);
  };

  /**
   * Update viewport metrics, recalculate progress and call update callback
   * @method _onResize
   * @returns {undefined}
   */
  ScrollProgress.prototype._onResize = function() {
    this._viewportHeight = this._getViewportHeight();
    this._viewportWidth = this._getViewportWidth();

    this._progress = this._getProgress();

    // trigger update function
    this._handleUpdate(this._progress.x, this._progress.y);
  };

  /**
   * Trigger update callback
   * @method trigger
   * @returns {undefined}
   */
  ScrollProgress.prototype.trigger = function() {
    this._handleUpdate(this._progress.x, this._progress.y);
  };

  /**
   * Destroy scroll observer, remove listeners and update callback
   * @method destroy
   * @returns {undefined}
   */
  ScrollProgress.prototype.destroy = function() {
    window.removeEventListener('scroll', this._onScroll);
    window.removeEventListener('resize', this._onResize);
    this._handleUpdate = null;
  };

  return ScrollProgress;

})));
<commit_msg>Bump major version<commit_after>/* scrollprogress v3.0.0 - 2017 Jeremias Menichelli - MIT License */
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  typeof define === 'function' && define.amd ? define(factory) :
  (global.ScrollProgress = factory());
}(this, (function () { 'use strict';

  /**
   * Fallback noop function
   * @method noop
   * @returns {undefined}
   */
  function noop() {}

  /**
   * ScrollProgress class constructor
   * @constructor ScrollProgress
   * @param {Function} handleUpdate method to call on scroll update
   * @returns {undefined}
   */
  var ScrollProgress = function(handleUpdate) {
    // assign function to call on update
    this._handleUpdate = typeof handleUpdate === 'function'
      ? handleUpdate
      : noop;

    // set initial values
    this._viewportHeight = this._getViewportHeight();
    this._viewportWidth = this._getViewportWidth();

    this._progress = this._getProgress();

    // trigger initial update function
    this._handleUpdate(0, this._progress);

    // bind event functions
    this._onScroll = this._onScroll.bind(this);
    this._onResize = this._onResize.bind(this);

    // add event listeners
    window.addEventListener('scroll', this._onScroll);
    window.addEventListener('resize', this._onResize);
  };

  /**
   * Get vertical trajectory of the viewport
   * @method _getViewportHeight
   * @returns {Number}
   */
  ScrollProgress.prototype._getViewportHeight = function() {
    return document.body.scrollHeight - window.innerHeight;
  };

  /**
   * Get horizontal trajectory of the viewport
   * @method _getViewportWidth
   * @returns {Number}
   */
  ScrollProgress.prototype._getViewportWidth = function() {
    return document.body.scrollWidth - window.innerWidth;
  };

  /**
   * Get scroll progress on both axis
   * @method _getProgress
   * @returns {Object}
   */
  ScrollProgress.prototype._getProgress = function() {
    var x = window.scrollX || window.pageXOffset;
    var y = window.scrollY || window.pageYOffset;

    return {
      x: x / this._viewportWidth,
      y: y / this._viewportHeight
    };
  };

  /**
   * Get scroll progress on both axis
   * @method _getProgress
   * @returns {undefined}
   */
  ScrollProgress.prototype._onScroll = function() {
    this._progress = this._getProgress();
    this._handleUpdate(this._progress.x, this._progress.y);
  };

  /**
   * Update viewport metrics, recalculate progress and call update callback
   * @method _onResize
   * @returns {undefined}
   */
  ScrollProgress.prototype._onResize = function() {
    this._viewportHeight = this._getViewportHeight();
    this._viewportWidth = this._getViewportWidth();

    this._progress = this._getProgress();

    // trigger update function
    this._handleUpdate(this._progress.x, this._progress.y);
  };

  /**
   * Trigger update callback
   * @method trigger
   * @returns {undefined}
   */
  ScrollProgress.prototype.trigger = function() {
    this._handleUpdate(this._progress.x, this._progress.y);
  };

  /**
   * Destroy scroll observer, remove listeners and update callback
   * @method destroy
   * @returns {undefined}
   */
  ScrollProgress.prototype.destroy = function() {
    window.removeEventListener('scroll', this._onScroll);
    window.removeEventListener('resize', this._onResize);
    this._handleUpdate = null;
  };

  return ScrollProgress;

})));
<|endoftext|>


<commit_before>"use strict";var inView=require("in-view");var shortid=require("shortid");var isDefine=function(v){return typeof v!=="undefined"},isString=function(v){return typeof v==="string"},isNumber=function(v){return typeof v==="number"},isFunc=function(v){return typeof v==="function"},isArray=function(v){return Array.isArray(v)},isObject=function(v){return!isArray(v)&&typeof v==="object"};var hasKey=function(obj,src){var result=false;var key;for(key in obj){if(obj.hasOwnProperty(key)&&key===src)result=true}return result};var objLength=function(v){var result=0;var key;for(key in v){v.hasOwnProperty(key)&&result++}return result};var hasObj_Array=function(v,search,val){const defined=Object.create(null);defined.is=false;defined.count=0;var length=v.length;var i;for(i=0;i<length;i++){if(isDefine(v[i])&&isDefine(v[i][search])){if(isDefine(val)&&v[i][search]===val){defined.is=true;defined.count+=1}}}return defined};var countEntered=0;var countExits=0;var createEl=Object.create(null);createEl.$enter=[];createEl.$exits=[];createEl.enter="";createEl.exit="";createEl.register=[];createEl.values={};var _element_enter=function(el,classid){createEl.enter=el;var cElm_exits=createEl.$exits.length;var i;for(i=0;i<cElm_exits;i++){if(isDefine(createEl.$exits[i])&&isDefine(createEl.$exits[i])&&createEl.$exits[i].class===classid){createEl.$exits.splice(i,1)}}if(!hasObj_Array(createEl.$enter,"class",classid).is)createEl.$enter.push({"class":classid,el:el})};var element_exit=function(el,classid){createEl.exit=el;var cElm_enter=createEl.$enter.length;var i;for(i=0;i<cElm_enter;i++){if(isDefine(createEl.$enter[i])&&isDefine(createEl.$enter[i].class)&&createEl.$enter[i].class===classid){createEl.$enter.splice(i,1)}}if(!hasObj_Array(createEl.$exits,"class",classid).is)createEl.$exits.push({"class":classid,el:el})};var obsclassreg=function(rw){var result;rgsize=createEl.register.length;var i;for(i=0;i<rgsize;i++){if(createEl.register[i].rawName===rw)result=createEl.register[i].classid}return result};var cssjs=function(css){css=css.split("-");var result=css[0]==="float"?"cssFloat":css[0];var size=css.length;if(size>1){var i;for(i=0;i<size;i++){if(i>0)result+=css[i].charAt(0).toUpperCase()+css[i].substr(1)}}return result};var vue_inview=function(){};var _$eventview=function(arg,classId,callback){var view=inView("."+classId);arg==="on"?view.on("enter",callback.enter).on("exit",callback.exit):arg==="once"?view.once("enter",callback.enter).once("exit",callback.exit):console.warn("[in-view] event handler not found")};var object_modifiers=function($m){var convert;var key;for(key in $m){if($m.hasOwnProperty(key)&&$m[key]===true){if(isDefine(convert))convert+="."+key;else convert=key}}return convert};var $arg=function(arg){var result;switch(arg){case"on":result=arg;break;case"once":result=arg;break;case"class":result=arg;break;case"style":result=arg;break;case"enter":result=arg;break;case"leave":result=arg;break;default:console.warn("[in-view] argument ${arg} undefined")}return result};var defaultAction=function(bidd,callback){if(!isDefine(bidd.arg))callback();if(bidd.arg==="on"||bidd.arg==="once"&&objLength(bidd.modifiers)===0)callback()};var object_class=function(clss,el){if(isString(clss))el.classList.add(clss);if(isObject(clss)){var classArr=el.className.split(" ");var key;for(key in clss){if(classArr.indexOf(key)&&clss[key]===false)el.classList.remove(key);if(clss.hasOwnProperty(key)&&clss[key]===true)el.classList.add(key)}}if(isArray(clss)){var i;for(i=0;i<clss.length;i++){el.classList.add(clss[i])}}};var object_style=function(css,el){var style=el.style;if(isObject(css)){var key;for(key in css){if(isDefine(style[cssjs(key)]))style[cssjs(key)]=css[key]}}if(isArray(css)){var size=css.length;var i;for(i=0;i<size;i++){if(isDefine(style[cssjs(css[i])]))style[cssjs(css[i])]=""}}};var _$elinview=function(el,$bd){var classId=shortid.generate();var elSize=el.classList.length;el.classList.add(classId);createEl.register.push({classid:classId,rawName:$bd.rawName});if(!hasKey(createEl.values,classId)&&isDefine($bd.value))createEl.values[classId]=$bd.value;var regHdlr=!isDefine($bd.arg)?"on":isDefine($arg($bd.arg))&&$arg($bd.arg)==="once"?"once":isDefine($arg($bd.arg))?"on":"undefined";var funcEvent=Object.create(null);defaultAction($bd,function(){if(isDefine(createEl.values[classId])&&isFunc(createEl.values[classId]))createEl.values[classId](funcEvent)});var _$arg=isDefine($arg($bd.arg))&&$arg($bd.arg)!=="on"||$arg($bd.arg)==="once"?$arg($bd.arg):"undefined";_$eventview(regHdlr,classId,{enter:function(el){var elvalue;if(hasKey(createEl.values,classId))elvalue=createEl.values[classId];countEntered+=1;_element_enter(el,classId);if(_$arg!=="undefined"&&objLength($bd.modifiers)===0&&isDefine(elvalue)){_$arg==="class"&&object_class(elvalue,el);_$arg==="style"&&object_style(elvalue,el);if(_$arg==="enter")isFunc(elvalue)?elvalue(el):console.warn("[in-view:${$bd.expression}] invalid method")}if(_$arg==="on"||_$arg==="once"&&objLength($bd.modifiers)>0&&isDefine(elvalue)){var $mdf=object_modifiers($bd.modifiers);if($mdf==="enter")isFunc(elvalue)?elvalue(el):console.warn("[in-view:${$bd.expression}] invalid method");$mdf==="class"&&object_class(elvalue,el);$mdf==="style"&&object_style(elvalue,el)}isDefine(funcEvent.enter)&&funcEvent.enter(el)},exit:function(el){var elvalue;if(hasKey(createEl.values,classId))elvalue=createEl.values[classId];countExits+=1;element_exit(el,classId);if(_$arg!=="undefined"&&isDefine(elvalue)){if(_$arg==="leave"&&objLength($bd.modifiers)===0)isFunc(elvalue)?elvalue(el):console.warn("[in-view:${$bd.expression}] invalid method");if(objLength($bd.modifiers)>0&&object_modifiers($bd.modifiers)==="leave"){_$arg==="class"&&object_class(elvalue,el);_$arg==="style"&&object_style(elvalue,el)}}if(_$arg==="on"||_$arg==="once"&&objLength($bd.modifiers)>0&&isDefine(elvalue)){var $mdf=object_modifiers($bd.modifiers);if($mdf==="leave")isFunc(elvalue)?elvalue(el):console.warn("[in-view:${$bd.expression}] invalid method");$mdf==="class.leave"&&object_class(elvalue,el);$mdf==="style.leave"&&object_style(elvalue,el)}isDefine(funcEvent.exit)&&funcEvent.exit(el)}})};var _directObj={inserted:function(el,$bd){_$elinview(el,$bd)},componentUpdated:function(el,$bd){var elSize=el.classList.length;var getclass;var i;for(i=0;i<elSize;i++){if(isDefine(obsclassreg($bd.rawName))&&obsclassreg($bd.rawName)===el.classList[i])getclass=el.classList[i]}if(isDefine(getclass)&&isDefine($bd.value))createEl.values[getclass]=$bd.value}};var hasAtt=function(el,att){var result=false;if(/^\.[\w]+/.test(att)){var className=att.match(/^\.([\w]+)/)[1];var gClass=el.className.split(" ");if(gClass.indexOf(className)>-1){result=true}}if(/^\#[\w]+/.test(att)){var idName=att.match(/^\#([\w]+)/)[1];if(el.hasAttribute("id")&&el.getAttribute("id")===idName)result=true}if(/^\[[\w]+=\"[\w]+\"\]$/.test(att)){var attr=att.match(/^\[([\w]+)=\"([\w]+)\"\]$/);var attName=attr[1];var attval=attr[2];if(el.hasAttribute(attName)&&el.getAttribute(attName)===attval)result=true}if(/^\[[\w]+=\'[\w]+\'\]$/.test(att)){var attr=att.match(/^\[([\w]+)=\'([\w]+)\'\]$/);var attName=attr[1];var attval=attr[2];if(el.hasAttribute(attName)&&el.getAttribute(attName)===attval)result=true}return result};var updateLifeCycle=function(update){var sync=function(){update();setTimeout(sync,0)};sync()};var _$inview=function($arg,$opt){var lastEnter=0;var lastExit=0;updateLifeCycle(function(){if(isDefine($opt)&&isObject($opt)&&isString($arg)){if(countEntered>lastEnter){isDefine($opt.enter)&&hasAtt(createEl.enter,$arg)&&$opt.enter(createEl.enter);lastEnter=countEntered}if(countExits>lastExit){isDefine($opt.exit)&&hasAtt(createEl.exit,$arg)&&$opt.exit(createEl.exit);lastExit=countExits}}})};var _directive=function($vm){$vm.directive("inview",_directObj)};var _$methods=function($vm){$vm.prototype._$inview=_$inview};var _install=function(Vue,Option){if(isDefine(Option)&&isObject(Option))inView.offset(Option);_directive(Vue);_$methods(Vue)};vue_inview.install=_install;vue_inview.threshold=function(c){inView.threshold(c)};vue_inview.offset=function(c){inView.offset(c)};module.exports=vue_inview;
<commit_msg>update new version<commit_after>"use strict";var inView=require("in-view");var shortid=require("shortid");var isDefine=function(v){return typeof v!=="undefined"},isString=function(v){return typeof v==="string"},isNumber=function(v){return typeof v==="number"},isFunc=function(v){return typeof v==="function"},isArray=function(v){return Array.isArray(v)},isObject=function(v){return!isArray(v)&&typeof v==="object"};var hasKey=function(obj,src){var result=false;var key;for(key in obj){if(obj.hasOwnProperty(key)&&key===src)result=true}return result};var objLength=function(v){var result=0;var key;for(key in v){v.hasOwnProperty(key)&&result++}return result};var hasObj_Array=function(v,search,val){var defined=Object.create(null);defined.is=false;defined.count=0;var length=v.length;var i;for(i=0;i<length;i++){if(isDefine(v[i][search])){if(isDefine(val)&&v[i][search]===val){defined.is=true;defined.count+=1}}}return defined};var countEntered=0;var countExits=0;var createEl=Object.create(null);createEl.$enter=[];createEl.$exits=[];createEl.enter="";createEl.exit="";createEl.register=[];createEl.values={};var _element_enter=function(el,classid){createEl.enter=el;var cElm_exits=createEl.$exits.length;var i;for(i=0;i<cElm_exits;i++){if(createEl.$exits[i].class===classid){createEl.$exits.splice(i,1)}}if(!hasObj_Array(createEl.$enter,"class",classid).is)createEl.$enter.push({"class":classid,el:el})};var element_exit=function(el,classid){createEl.exit=el;var cElm_enter=createEl.$enter.length;var i;for(i=0;i<cElm_enter;i++){if(isDefine(createEl.$enter[i])&&isDefine(createEl.$enter[i].class)&&createEl.$enter[i].class===classid){createEl.$enter.splice(i,1)}}if(!hasObj_Array(createEl.$exits,"class",classid).is)createEl.$exits.push({"class":classid,el:el})};var obsclassreg=function(rw){var result;var rgsize=createEl.register.length;var i;for(i=0;i<rgsize;i++){if(createEl.register[i].rawName===rw)result=createEl.register[i].classid}return result};var cssjs=function(css){css=css.split("-");var result=css[0]==="float"?"cssFloat":css[0];var size=css.length;var i;for(i=0;i<size;i++){if(i>0)result+=css[i].charAt(0).toUpperCase()+css[i].substr(1)}return result};var vue_inview=function(){};var _$eventview=function(arg,classId,callback){var view=inView("."+classId);arg==="on"?view.on("enter",callback.enter).on("exit",callback.exit):arg==="once"?view.once("enter",callback.enter).once("exit",callback.exit):console.warn("[in-view] event handler not found")};var object_modifiers=function($m){var convert;var key;for(key in $m){if($m.hasOwnProperty(key)&&$m[key]===true){if(isDefine(convert))convert+="."+key;else convert=key}}return convert};var $arg=function(arg){var result;switch(arg){case"on":result=arg;break;case"once":result=arg;break;case"class":result=arg;break;case"style":result=arg;break;case"enter":result=arg;break;case"leave":result=arg;break;default:console.warn("[in-view] argument ${arg} undefined")}return result};var defaultAction=function(bidd,callback){if(!isDefine(bidd.arg))callback();if(bidd.arg==="on"||bidd.arg==="once"&&objLength(bidd.modifiers)===0)callback()};var object_class=function(clss,el){if(isString(clss))el.classList.add(clss);if(isObject(clss)){var classArr=el.className.split(" ");var key;for(key in clss){if(classArr.indexOf(key)&&clss[key]===false)el.classList.remove(key);if(clss.hasOwnProperty(key)&&clss[key]===true)el.classList.add(key)}}if(isArray(clss)){var i;for(i=0;i<clss.length;i++){el.classList.add(clss[i])}}};var object_style=function(css,el){var style=el.style;if(isObject(css)){var key;for(key in css){if(isDefine(style[cssjs(key)]))style[cssjs(key)]=css[key]}}if(isArray(css)){var size=css.length;var i;for(i=0;i<size;i++){if(isDefine(style[cssjs(css[i])]))style[cssjs(css[i])]=""}}};var _$elinview=function(el,$bd){var classId=shortid.generate();var elSize=el.classList.length;el.classList.add(classId);createEl.register.push({classid:classId,rawName:$bd.rawName});if(!hasKey(createEl.values,classId)&&isDefine($bd.value))createEl.values[classId]=$bd.value;var regHdlr=!isDefine($bd.arg)?"on":isDefine($arg($bd.arg))&&$arg($bd.arg)==="once"?"once":isDefine($arg($bd.arg))?"on":"undefined";var funcEvent=Object.create(null);defaultAction($bd,function(){if(isDefine(createEl.values[classId])&&isFunc(createEl.values[classId]))createEl.values[classId](funcEvent)});var _$arg=isDefine($arg($bd.arg))&&$arg($bd.arg)!=="on"||$arg($bd.arg)==="once"?$arg($bd.arg):"undefined";_$eventview(regHdlr,classId,{enter:function(el){var elvalue;if(hasKey(createEl.values,classId))elvalue=createEl.values[classId];countEntered+=1;_element_enter(el,classId);if(_$arg!=="undefined"&&objLength($bd.modifiers)===0&&isDefine(elvalue)){_$arg==="class"&&object_class(elvalue,el);_$arg==="style"&&object_style(elvalue,el);if(_$arg==="enter")isFunc(elvalue)?elvalue(el):console.warn("[in-view:${$bd.expression}] invalid method")}if(_$arg==="on"||_$arg==="once"&&objLength($bd.modifiers)>0&&isDefine(elvalue)){var $mdf=object_modifiers($bd.modifiers);if($mdf==="enter")isFunc(elvalue)?elvalue(el):console.warn("[in-view:${$bd.expression}] invalid method");$mdf==="class"&&object_class(elvalue,el);$mdf==="style"&&object_style(elvalue,el)}isDefine(funcEvent.enter)&&funcEvent.enter(el)},exit:function(el){var elvalue;if(hasKey(createEl.values,classId))elvalue=createEl.values[classId];countExits+=1;element_exit(el,classId);if(_$arg!=="undefined"&&isDefine(elvalue)){if(_$arg==="leave"&&objLength($bd.modifiers)===0)isFunc(elvalue)?elvalue(el):console.warn("[in-view:${$bd.expression}] invalid method");if(objLength($bd.modifiers)>0&&object_modifiers($bd.modifiers)==="leave"){_$arg==="class"&&object_class(elvalue,el);_$arg==="style"&&object_style(elvalue,el)}}if(_$arg==="on"||_$arg==="once"&&objLength($bd.modifiers)>0&&isDefine(elvalue)){var $mdf=object_modifiers($bd.modifiers);if($mdf==="leave")isFunc(elvalue)?elvalue(el):console.warn("[in-view:${$bd.expression}] invalid method");$mdf==="class.leave"&&object_class(elvalue,el);$mdf==="style.leave"&&object_style(elvalue,el)}isDefine(funcEvent.exit)&&funcEvent.exit(el)}})};var _directObj={inserted:function(el,$bd){_$elinview(el,$bd)},componentUpdated:function(el,$bd){var elSize=el.classList.length;var getclass;var i;for(i=0;i<elSize;i++){if(isDefine(obsclassreg($bd.rawName))&&obsclassreg($bd.rawName)===el.classList[i])getclass=el.classList[i]}if(isDefine(getclass)&&isDefine($bd.value))createEl.values[getclass]=$bd.value}};var hasAtt=function(el,att){var result=false;if(/^\.[\w]+/.test(att)){var className=att.match(/^\.([\w]+)/)[1];var gClass=el.className.split(" ");if(gClass.indexOf(className)>-1){result=true}}if(/^\#[\w]+/.test(att)){var idName=att.match(/^\#([\w]+)/)[1];if(el.hasAttribute("id")&&el.getAttribute("id")===idName)result=true}if(/^\[[\w]+=\"[\w]+\"\]$/.test(att)){var attr=att.match(/^\[([\w]+)=\"([\w]+)\"\]$/);var attName=attr[1];var attval=attr[2];if(el.hasAttribute(attName)&&el.getAttribute(attName)===attval)result=true}if(/^\[[\w]+=\'[\w]+\'\]$/.test(att)){var attr=att.match(/^\[([\w]+)=\'([\w]+)\'\]$/);var attName=attr[1];var attval=attr[2];if(el.hasAttribute(attName)&&el.getAttribute(attName)===attval)result=true}return result};var updateLifeCycle=function(update){var sync=function(){update();setTimeout(sync,0)};sync()};var _$inview=function($arg,$opt){var lastEnter=0;var lastExit=0;updateLifeCycle(function(){if(isDefine($opt)&&isObject($opt)&&isString($arg)){if(countEntered>lastEnter){isDefine($opt.enter)&&hasAtt(createEl.enter,$arg)&&$opt.enter(createEl.enter);lastEnter=countEntered}if(countExits>lastExit){isDefine($opt.exit)&&hasAtt(createEl.exit,$arg)&&$opt.exit(createEl.exit);lastExit=countExits}}})};var _directive=function($vm){$vm.directive("inview",_directObj)};var _$methods=function($vm){$vm.prototype._$inview=_$inview};var _install=function(Vue,Option){if(isDefine(Option)&&isObject(Option))inView.offset(Option);_directive(Vue);_$methods(Vue)};vue_inview.install=_install;vue_inview.threshold=function(c){inView.threshold(c)};vue_inview.offset=function(c){inView.offset(c)};module.exports=vue_inview;<|endoftext|>


<commit_before>const pify = require('pify')
const rimraf = require('rimraf')
const fs = require('fs')
const assert = require('assert')
const getGitStatus = require('./utils/get-git-status')
const execute = require('./utils/execute')

const log = console.log
const removeDir = pify(rimraf)
const readFile = pify(fs.readFile)
const writeFile = pify(fs.writeFile)

const dryRun = process.argv.includes('--dry-run')

const semver = process.argv[2]
assert.ok(['patch', 'minor', 'major'].includes(semver), 'Must specify the valid semver version: patch | minor | major')

;(async () => {
  log('Doing sanity checks...')
  const {currentBranch: branchToPublish, isCleanWorkingTree} = await getGitStatus()
  if (!dryRun) {
    assert.equal(branchToPublish, 'master', 'Must be on master branch')
  }
  assert.equal(isCleanWorkingTree, true, 'Must have clean working tree')

  log(`Pulling the latest ${branchToPublish} branch from Github...`)
  await execute('git pull origin')

  log(`Running npm version ${semver}...`)
  await execute(`npm version --no-git-tag-version ${semver}`)
  const {version} = require('./package.json')

  log(`Making a version change commit...`)
  await execute(`git add package.json && git commit -m "${version}"`)

  log('Deleting the dist folder (it will conflict with the next step)...')
  await removeDir('dist')

  log('Switching to the dist branch...')
  await execute('git checkout dist')

  log('Pulling the latest dist branch from Github...')
  await execute('git pull origin')

  log(`Merging from "${branchToPublish}" branch...`)
  await execute(`git merge ${branchToPublish}`)

  log('Running the build...')
  await execute('npm run build')

  log('Running the checks...')
  await execute('npm run check')

  if (dryRun) {
    log('Skipping publishing on npm...')
  } else {
    log('Publishing on npm...')
    await execute('npm publish')
  }

  log('Removing "dist" from .gitignore...')
  const gitignore = await readFile('.gitignore', 'utf8')
  const gitignoreWithoutDist = gitignore.split(/\r?\n/).filter(line => line !== 'dist').join('\n')
  await writeFile('.gitignore', gitignoreWithoutDist)

  log('Committing the dist dir...')
  await execute(`git add dist/ && git commit -m "Release v${version}"`)

  log('Reverting the change to .gitignore...')
  await execute('git reset --hard HEAD')

  log(`Tagging commit as "v${version}"...`)
  await execute(`git tag "v${version}"`)

  if (dryRun) {
    log('Skipping pushing to Github...')
  } else {
    log('Pushing to Github both master and dist branches...')
    await execute('git push origin master:master dist:dist --tags')
  }

  log(`Switching back to "${branchToPublish}" (so you can continue to work)...`)
  await execute(`git checkout "${branchToPublish}"`)

  log('OK!')
})().catch(console.error)
<commit_msg>fix(release-script): install npm deps before running npm tasks (#962)<commit_after>const pify = require('pify')
const rimraf = require('rimraf')
const fs = require('fs')
const assert = require('assert')
const getGitStatus = require('./utils/get-git-status')
const execute = require('./utils/execute')

const log = console.log
const removeDir = pify(rimraf)
const readFile = pify(fs.readFile)
const writeFile = pify(fs.writeFile)

const dryRun = process.argv.includes('--dry-run')

const semver = process.argv[2]
assert.ok(['patch', 'minor', 'major'].includes(semver), 'Must specify the valid semver version: patch | minor | major')

;(async () => {
  log('Doing sanity checks...')
  const {currentBranch: branchToPublish, isCleanWorkingTree} = await getGitStatus()
  if (!dryRun) {
    assert.equal(branchToPublish, 'master', 'Must be on master branch')
  }
  assert.equal(isCleanWorkingTree, true, 'Must have clean working tree')

  log(`Pulling the latest ${branchToPublish} branch from Github...`)
  await execute('git pull origin')

  log(`Running npm version ${semver}...`)
  await execute(`npm version --no-git-tag-version ${semver}`)
  const {version} = require('./package.json')

  log(`Making a version change commit...`)
  await execute(`git add package.json && git commit -m "${version}"`)

  log('Deleting the dist folder (it will conflict with the next step)...')
  await removeDir('dist')

  log('Switching to the dist branch...')
  await execute('git checkout dist')

  log('Pulling the latest dist branch from Github...')
  await execute('git pull origin')

  log(`Merging from "${branchToPublish}" branch...`)
  await execute(`git merge ${branchToPublish}`)

  log('Installing npm dependencies...')
  await execute('yarn')

  log('Running the build...')
  await execute('npm run build')

  log('Running the checks...')
  await execute('npm run check')

  if (dryRun) {
    log('Skipping publishing on npm...')
  } else {
    log('Publishing on npm...')
    await execute('npm publish')
  }

  log('Removing "dist" from .gitignore...')
  const gitignore = await readFile('.gitignore', 'utf8')
  const gitignoreWithoutDist = gitignore.split(/\r?\n/).filter(line => line !== 'dist').join('\n')
  await writeFile('.gitignore', gitignoreWithoutDist)

  log('Committing the dist dir...')
  await execute(`git add dist/ && git commit -m "Release v${version}"`)

  log('Reverting the change to .gitignore...')
  await execute('git reset --hard HEAD')

  log(`Tagging commit as "v${version}"...`)
  await execute(`git tag "v${version}"`)

  if (dryRun) {
    log('Skipping pushing to Github...')
  } else {
    log('Pushing to Github both master and dist branches...')
    await execute('git push origin master:master dist:dist --tags')
  }

  log(`Switching back to "${branchToPublish}" (so you can continue to work)...`)
  await execute(`git checkout "${branchToPublish}"`)

  log('OK!')
})().catch(console.error)
<|endoftext|>


<commit_before>import { Component } from 'react';
import { any, string, func, object, number } from 'prop-types';
import invariant from 'invariant';
import cookie from 'cookie';
import isNode from 'is-node';

export default class CookieProvider extends Component {
  static propTypes = {
    header: string,
    children: any,
    decode: func,
    pollInterval: number,
  };

  static defaultProps = {
    pollInterval: 100,
  };

  state = {
    cookies: this.readCookies(),
  };

  static childContextTypes = {
    cookies: object.isRequired,
  };

  getChildContext() {
    return {
      cookies: this.state.cookies,
    };
  }

  componentWillMount() {
    if (!isNode) {
      this.interval = setInterval(
        this.updateCookies.bind(this),
        this.props.pollInterval,
      );
    }
  }

  componentWillUnmount() {
    if (!isNode) {
      clearInterval(this.interval);
    }
  }

  readCookies() {
    invariant(
      !isNode || typeof this.props.header === 'string',
      'You must specify the header to the <CookieProvider> on the server-side',
    );

    const cookieString = isNode
      ? this.props.header
      : this.props.header || document.cookie;

    this.lastCookie = cookieString;

    return cookie.parse(cookieString, {
      decode: this.props.decode,
    });
  }

  updateCookies() {
    if (document.cookie !== this.lastCookie) {
      this.setState({
        cookies: this.readCookies(),
      });
    }
  }

  render() {
    return this.props.children;
  }
}
<commit_msg>Made polling on document cookies optional<commit_after>import { Component } from 'react';
import { any, string, func, object, number } from 'prop-types';
import invariant from 'invariant';
import cookie from 'cookie';
import isNode from 'is-node';

export default class CookieProvider extends Component {
  static propTypes = {
    header: string,
    children: any,
    decode: func,
    pollInterval: number,
  };

  state = {
    cookies: this.readCookies(),
  };

  static childContextTypes = {
    cookies: object.isRequired,
  };

  getChildContext() {
    return {
      cookies: this.state.cookies,
    };
  }

  componentWillMount() {
    if (!isNode && this.props.pollInterval > 0) {
      this.interval = setInterval(
        this.updateCookies.bind(this),
        this.props.pollInterval,
      );
    }
  }

  componentWillUnmount() {
    if (this.interval) {
      clearInterval(this.interval);
    }
  }

  readCookies() {
    invariant(
      !isNode || typeof this.props.header === 'string',
      'You must specify the header to the <CookieProvider> on the server-side',
    );

    const cookieString = isNode
      ? this.props.header
      : this.props.header || document.cookie;

    this.lastCookie = cookieString;

    return cookie.parse(cookieString, {
      decode: this.props.decode,
    });
  }

  updateCookies() {
    if (document.cookie !== this.lastCookie) {
      this.setState({
        cookies: this.readCookies(),
      });
    }
  }

  render() {
    return this.props.children;
  }
}
<|endoftext|>


<commit_before>import Effect from "./Effect";
import Noise from "../Voices/Noise";

export default class Reverb extends Effect {
	constructor (context) {
		super(context);
		this.attack = 0;
		this.decay = 0.2;
		this.release = 0.2;
	}

	setup () {
		this.effect = this.context.createConvolver();

		this.reverbTime = 1;

		this.wet = this.context.createGain();
		this.wet.gain.value = 0.4;
		this.dry = this.context.createGain();
		this.dry.gain.value = 0.8;

		this.buffer = this.renderTail();

	}

	wireUp() {
		this.input.connect(this.dry);
		this.input.connect(this.effect);

		this.dry.connect(this.output);
		this.effect.connect(this.wet);
		this.wet.connect(this.output);
	}

	renderTail () {
		let tailContext = new OfflineAudioContext(2, this.context.sampleRate * this.reverbTime, this.context.sampleRate);
		let buffer = tailContext.createBufferSource();
		let tail = new Noise(tailContext, 1);
		tail.init();
		tail.connect(tailContext.destination);
		tail.attack = this.attack;
		tail.decay = this.decay;
		tail.release = this.release;
		tail.on(100);
		tail.off();
		return tailContext.startRendering().then((buffer) => {
			this.effect.buffer = buffer;
		});
	}
}<commit_msg>added wet/dry and decay time to reverb (untested)<commit_after>import Effect from "./Effect";
import Noise from "../Voices/Noise";

export default class Reverb extends Effect {
	constructor (context) {
		super(context);
		this.attack = 0;
		this.decay = 0.2;
		this.release = 0.2;
	}

	setup () {
		this.effect = this.context.createConvolver();

		this.reverbTime = 1;

		this.wet = this.context.createGain();
		this.wet.gain.value = 1;
		this.dry = this.context.createGain();
		this.dry.gain.value = 1;

		this.buffer = this.renderTail();

	}

	wireUp() {
		this.input.connect(this.dry);
		this.input.connect(this.effect);

		this.dry.connect(this.output);
		this.effect.connect(this.wet);
		this.wet.connect(this.output);
	}

	renderTail () {
		let tailContext = new OfflineAudioContext(2, this.context.sampleRate * this.reverbTime, this.context.sampleRate);
		let buffer = tailContext.createBufferSource();
		let tail = new Noise(tailContext, 1);
		tail.init();
		tail.connect(tailContext.destination);
		tail.attack = this.attack;
		tail.decay = this.decay;
		tail.release = this.release;
		tail.on(100);
		tail.off();
		return tailContext.startRendering().then((buffer) => {
			this.effect.buffer = buffer;
		});
	}

	set decayTime(value) {
		let dc = value/3;
		this.reverbTime = value;
		this.attack = 0;
		this.decay = dc;
		this.release = dc;
		this.buffer = this.renderTail();
	}

	set dry (value) {
		this.dry.gain.value = value;
	}

	get dry () {
		this.dry.gain.value;
	}

	set wet (value) {
		this.wet.gain.value = value;
	}

	get wet () {
		this.wet.gain.value;
	}

}<|endoftext|>


<commit_before>window.storyFormat({
  "name": "Twison",
  "version": "0.0.1",
  "author": "Mike Lazer-Walker",
  "description": "Export your Twine 2 story as a JSON document",
  "proofing": false,
  "source": "\r\n\t\r\n\t\t<title>{{STORY_NAME}}</title>\r\n\t\t\r\n\t\r\n\t\r\n\t\t
\r\n\t\t\r\n\t\t
\r\n\t\t
\r\n\t\t\t{{STORY_DATA}}\r\n\t\t
\r\n\t\r\n"
});<commit_msg>Bump compiled version<commit_after>window.storyFormat({
  "name": "Twison",
  "version": "0.0.1",
  "author": "Mike Lazer-Walker",
  "description": "Export your Twine 2 story as a JSON document",
  "proofing": false,
  "source": "\r\n\t\r\n\t\t<title>{{STORY_NAME}}</title>\r\n\t\t\r\n\t\r\n\t\r\n\t\t
\r\n\t\t\r\n\t\t
\r\n\t\t
\r\n\t\t\t{{STORY_DATA}}\r\n\t\t
\r\n\t\r\n"
});<|endoftext|>