<commit_before>module.exports = {
  loadPriority:  500,
  initialize: function(api, next){

    api.routes = {};
    api.routes.routes = {};

    api.routes.verbs = ['get', 'post', 'put', 'patch', 'delete'];

    ////////////////////////////////////////////////////////////////////////////
    // route processing for web clients
    api.routes.processRoute = function(connection, pathParts){
      if(connection.params.action === undefined || api.actions.actions[connection.params.action] === undefined){
        var method = connection.rawConnection.method.toLowerCase();
        if(method === 'head'){ method = 'get'; }
        for(var i in api.routes.routes[method]){
          var route = api.routes.routes[method][i];
          var match = api.routes.matchURL(pathParts, route.path);
          if(match.match === true){
            for(var param in match.params){
              try{
                var decodedName = decodeURIComponent(param.replace(/\+/g, ' '));
                var decodedValue = decodeURIComponent(match.params[param].replace(/\+/g, ' '));
                connection.params[decodedName] = decodedValue;
              }catch(e){
                // malformed URL
              }
            }
            connection.params.action = route.action;
            break;
          }
        }
      }
    }

    api.routes.matchURL = function(pathParts, match){
      var response = {match: false, params: {} }
      var matchParts = match.split('/');
      var regexp = '';
      var variable = '';

      if(matchParts[0] === ''){ matchParts.splice(0, 1) }
      if(matchParts[(matchParts.length - 1)] === ''){ matchParts.pop() }

      if(matchParts.length !== pathParts.length){
        return response;
      }

      for(var i in matchParts){
        var part = matchParts[i];
        if(!pathParts[i]){
          return response;
        } else if(part[0] === ':' && part.indexOf('(') < 0){
          variable = part.replace(':', '');
          response.params[variable] = pathParts[i];
        } else if(part[0] === ':' && part.indexOf('(') >= 0){
          variable = part.replace(':', '').split('(')[0];
          regexp = part.split('(')[1];
          var matches = pathParts[i].match(new RegExp(regexp.substring(0, regexp.length - 1), 'g'));
          if(matches){
            response.params[variable] = pathParts[i];
          } else {
            return response;
          }
        } else {
          if(pathParts[i] === null || pathParts[i] === undefined || pathParts[i].toLowerCase() !== matchParts[i].toLowerCase()){
            return response;
          }
        }
      }

      response.match = true;
      return response;
    }

    // load in the routes file
    api.routes.loadRoutes = function(rawRoutes){
      var counter = 0;
      api.routes.routes = { 'get': [], 'post': [], 'put': [], 'patch' : [], 'delete': [] };

      if(!rawRoutes){
        if(api.config.routes){
          rawRoutes = api.config.routes;
        }
      }

      var v, verb;
      for(var i in rawRoutes){
        var method = i.toLowerCase();
        for(var j in rawRoutes[i]){
          var route = rawRoutes[i][j];
          if(method === 'all'){
            for(v in api.routes.verbs){
              verb = api.routes.verbs[v];
              api.routes.routes[verb].push({ path: route.path, action: route.action });
            }
          } else {
            api.routes.routes[method].push({ path: route.path, action: route.action });
          }
          counter++;
        }
      }

      api.params.postVariables = api.utils.arrayUniqueify(api.params.postVariables)
      api.log(counter + ' routes loaded from ' + api.routes.routesFile, 'debug');

      if(api.config.servers.web && api.config.servers.web.simpleRouting === true){
        var simplePaths = [];
        for(var action in api.actions.actions){
          simplePaths.push('/' + action);
          // api.routes.verbs.forEach(function(verb){
          for(v in api.routes.verbs){
            verb = api.routes.verbs[v];
            api.routes.routes[verb].push({ path: '/' + action, action: action });
          }
        }
        api.log(simplePaths.length + ' simple routes loaded from action names', 'debug');

        api.log('routes:', 'debug', api.routes.routes);
      }
    };

    api.routes.loadRoutes();
    next();
  }
}<commit_msg>fix route regexp<commit_after>module.exports = {
  loadPriority:  500,
  initialize: function(api, next){

    api.routes = {};
    api.routes.routes = {};

    api.routes.verbs = ['get', 'post', 'put', 'patch', 'delete'];

    ////////////////////////////////////////////////////////////////////////////
    // route processing for web clients
    api.routes.processRoute = function(connection, pathParts){
      if(connection.params.action === undefined || api.actions.actions[connection.params.action] === undefined){
        var method = connection.rawConnection.method.toLowerCase();
        if(method === 'head'){ method = 'get'; }
        for(var i in api.routes.routes[method]){
          var route = api.routes.routes[method][i];
          var match = api.routes.matchURL(pathParts, route.path);
          if(match.match === true){
            for(var param in match.params){
              try{
                var decodedName = decodeURIComponent(param.replace(/\+/g, ' '));
                var decodedValue = decodeURIComponent(match.params[param].replace(/\+/g, ' '));
                connection.params[decodedName] = decodedValue;
              }catch(e){
                // malformed URL
              }
            }
            connection.params.action = route.action;
            break;
          }
        }
      }
    }

    api.routes.matchURL = function(pathParts, match){
      var response = {match: false, params: {} }
      var matchParts = match.split('/');
      var regexp = '';
      var variable = '';

      if(matchParts[0] === ''){ matchParts.splice(0, 1) }
      if(matchParts[(matchParts.length - 1)] === ''){ matchParts.pop() }

      if(matchParts.length !== pathParts.length){
        return response;
      }

      for(var i in matchParts){
        var part = matchParts[i];
        if(!pathParts[i]){
          return response;
        } else if(part[0] === ':' && part.indexOf('(') < 0){
          variable = part.replace(':', '');
          response.params[variable] = pathParts[i];
        } else if(part[0] === ':' && part.indexOf('(') >= 0){
          variable = part.replace(':', '').split('(')[0];
          regexp = part.substring(part.indexOf('(') + 1, part.length - 1);
          var matches = pathParts[i].match(new RegExp(regexp, 'g'));
          if(matches){
            response.params[variable] = pathParts[i];
          } else {
            return response;
          }
        } else {
          if(pathParts[i] === null || pathParts[i] === undefined || pathParts[i].toLowerCase() !== matchParts[i].toLowerCase()){
            return response;
          }
        }
      }

      response.match = true;
      return response;
    }

    // load in the routes file
    api.routes.loadRoutes = function(rawRoutes){
      var counter = 0;
      api.routes.routes = { 'get': [], 'post': [], 'put': [], 'patch' : [], 'delete': [] };

      if(!rawRoutes){
        if(api.config.routes){
          rawRoutes = api.config.routes;
        }
      }

      var v, verb;
      for(var i in rawRoutes){
        var method = i.toLowerCase();
        for(var j in rawRoutes[i]){
          var route = rawRoutes[i][j];
          if(method === 'all'){
            for(v in api.routes.verbs){
              verb = api.routes.verbs[v];
              api.routes.routes[verb].push({ path: route.path, action: route.action });
            }
          } else {
            api.routes.routes[method].push({ path: route.path, action: route.action });
          }
          counter++;
        }
      }

      api.params.postVariables = api.utils.arrayUniqueify(api.params.postVariables)
      api.log(counter + ' routes loaded from ' + api.routes.routesFile, 'debug');

      if(api.config.servers.web && api.config.servers.web.simpleRouting === true){
        var simplePaths = [];
        for(var action in api.actions.actions){
          simplePaths.push('/' + action);
          // api.routes.verbs.forEach(function(verb){
          for(v in api.routes.verbs){
            verb = api.routes.verbs[v];
            api.routes.routes[verb].push({ path: '/' + action, action: action });
          }
        }
        api.log(simplePaths.length + ' simple routes loaded from action names', 'debug');

        api.log('routes:', 'debug', api.routes.routes);
      }
    };

    api.routes.loadRoutes();
    next();
  }
}<|endoftext|>


<commit_before>$(function() {
	var singleArr = [ 1, 2, 3 ],
		doubleArr = [[ 1, 2, 3 ],[ 4, 5, 6 ],[ 7, 8, 9 ]];

	module( 'core' );

	test( 'sequence generation', function() {
		deepEqual( jStat.seq( 0, 1, 5 ), [ 0, 0.25, 0.5, 0.75, 1 ], 'seq( 0, 1, 5 )' );
	});

	test( 'row count', function() {
		equals( jStat( singleArr.slice() ).rows(), 1, 'fn.rows()' );
		equals( jStat( doubleArr.slice() ).rows(), 3, 'fn.rows()' );
	});

	test( 'column count', function() {
		equals( jStat( singleArr.slice() ).cols(), 3, 'fn.cols()' );
		equals( jStat( doubleArr.slice() ).cols(), 3, 'fn.cols()' );
	});

	test( 'dimensions', function() {
		deepEqual( jStat( singleArr.slice()).dimensions(), {
			rows : 1,
			cols : 3
		}, 'fn.dimensions()' );
		deepEqual( jStat( doubleArr.slice()).dimensions(), {
			rows : 3,
			cols : 3
		}, 'fn.dimensions()' );
	});

	test( 'row vector', function() {
		deepEqual( jStat( singleArr.slice()).row( 0 ).toArray(), [[ 1, 2, 3 ]], 'fn.row()' );
		deepEqual( jStat( doubleArr.slice()).row( 1 ).toArray(), [[ 4, 5, 6 ]], 'fn.row()' );
	});

	test( 'column vector', function() {
		deepEqual( jStat( singleArr.slice()).col( 0 ).toArray(), [[ 1 ]], 'fn.col()' );
		deepEqual( jStat( doubleArr.slice()).col( 1 ).toArray(), [[ 2 ],[ 5 ],[ 8 ]], 'fn.col()' );
	});

	test( 'matrix diagonal', function() {
		deepEqual( jStat( doubleArr.slice()).diag().toArray(), [[ 1 ],[ 5 ],[ 9 ]], 'fn.diag()' );
	});

	test( 'matrix anti-diagonal', function() {
		deepEqual( jStat( doubleArr.slice()).antidiag().toArray(), [[ 3 ],[ 5 ],[ 7 ]], 'fn.antidiag()' );
	});

	test( 'matrix transpose', function() {
		deepEqual( jStat.transpose( doubleArr ), [[ 1, 4, 7 ],[ 2, 5, 8 ],[ 3, 6, 9 ]], 'transpose()' );
	});

	test( 'map', function() {
		deepEqual( jStat.map( doubleArr, function( x ) {
			return x * 2;
		}), [[ 2, 4, 6 ],[ 8, 10, 12 ],[ 14, 16, 18 ]], 'map()' );
	});

	test( 'add', function() {
		deepEqual( jStat.add( doubleArr, 2 ), [[ 3, 4, 5 ],[ 6, 7, 8 ],[ 9, 10, 11 ]], 'add()' );
	});

	test( 'subtract', function() {
		deepEqual( jStat.subtract( doubleArr, 2 ), [[ -1, 0, 1 ],[ 2, 3, 4 ],[ 5, 6, 7 ]], 'subtract()' );
	});

	test( 'multiply', function() {
		deepEqual( jStat.multiply( doubleArr, 2 ), [[ 2, 4, 6 ],[ 8, 10, 12 ],[ 14, 16, 18 ]], 'multiply()' );
	});

	test( 'divide', function() {
		deepEqual( jStat.divide( singleArr, 2 ), [ 1 / 2, 1, 3 / 2 ], 'divide()' );
	});

	test( 'dot', function() {
		deepEqual( jStat.dot([[ 1, 2 ],[ 3, 4 ]],[[ 5, 6 ],[ 7, 8 ]]), [ 17, 53 ], 'dot()' );
	});

	test( 'pow', function() {
		deepEqual( jStat.pow( singleArr, 2 ), [ 1, 4, 9 ], 'pow()' );
	});

	test( 'abs', function() {
		deepEqual( jStat.abs([ 1, -1, -2 ]), [ 1, 1, 2 ], 'abs()' );
	});

	test( 'vector norm', function() {
		equals( jStat.norm([ 1, 2, 3 ], 1 ), 6, 'norm()' );
		equals( jStat.norm([ 1, 2, 3 ]), 3.7416573867739413, 'norm()' );
	});

	test( 'vector angle', function() {
		equals( jStat.angle([ 1, 0, 1 ],[ 0, 1, 0 ]), Math.PI / 2, 'angle()' );
	});

	test( 'symmetric', function() {
		equals( jStat.symmetric( singleArr ), false, 'symmetric()' );
		equals( jStat.symmetric( doubleArr ), false, 'symmetric()' );
		equals( jStat.symmetric([[ 1, 2 ],[ 2, 1 ]]), true, 'symmetric()' );
	});

	test('sum',function(){
		equals(jStat.sum([1,2,3,4,5,6]),21,'sum([1,2,3,4,5,6])');
	});

	test('min',function(){
		equals(jStat.min([1,2,3,4,5,6]),1,'min([1,2,3,4,5,6])');
	});

	test('max',function(){
		equals(jStat.max([1,2,3,4,5,6]),6,'max([1,2,3,4,5,6])');
	});

	test('mean',function(){
		equals(jStat.mean([1,2,3,4,5,6]),3.5,'mean([1,2,3,4,5,6])');
	});

	test('median',function(){
		equals(jStat.median([1,2,3,3,4,5,6]),3,'median([1,2,3,3,4,5,6])');
		equals(jStat.median([1,2,3,4,5,6]),3.5,'median([1,2,3,4,5,6])');
	});

	test('mode',function(){
		equals(jStat.mode([1,2,3,3,4,5,6]),3,'mode([1,2,3,3,4,5,6])');
		equals(jStat.mode([1,1,2,3,3,4,5,6]),false,'mode([1,1,2,3,3,4,5,6])');
	});

	test('range',function(){
		equals(jStat.range([1,2,3,3,4,5,6]),5,'range([1,2,3,3,4,5,6])');
		equals(jStat.range([-3,-6,-4]),3,'range([-3,-6,-4])');
	});

	test('variance',function(){
		equals(jStat.variance([3,4,5,6,7]),2,'variance([3,4,5,6,7])');
	});

	test('stdev',function(){
		equals(jStat.stdev([3,4,5]),1,'stdev([3,4,5])');
		equals(jStat.stdev([-3,-4,-5]),1,'stdev([-3,-4,-5])');
	});

	test('meandev',function(){
		equals(jStat.meandev([2,2,3,4,14]),3.6,'meandev([2,2,3,4,14])');
	});

	test('meddev',function(){
		equals(jStat.meddev([2,2,3,4,14]),2.8,'meddev([2,2,3,4,14])');
	});

	test('factorial',function(){
		equals(jStat.factorial(5),120,'factorial(5)');
		equals(jStat.factorial(.5).toFixed(7),'0.8862269','factorial(.5)');
	});

	test('combination',function(){
		equals(jStat.combination(10,4),210,'combination(10,4)');
	});

	test('permutation',function(){
		equals(jStat.permutation(10,4),5040,'permutation(10,4)');
	});

	test('gamma',function(){
		equals(jStat.gammafn(.5).toFixed(7),'1.7724539','gamma(.5)');
		equals(jStat.gammafn(15),87178291200,'gamma(5)');
	});

	test('quartiles',function(){
		equals(jStat.quartiles([1,2,3,6,9,3,1,2,5]).toString(),'1,3,5','quartiles([1,2,3,6,9,3,1,2,5])');
	});

	test('covariance',function(){
		equals(jStat.covariance([1,2,3,6,9,3,1,2,5],[2,3,5,2,5,7,8,9,6]),-1.1234567901234565,'covariance([1,2,3,6,9,3,1,2,5],[2,3,5,2,5,7,8,9,6])');
	});

	test('corrcoeff',function(){
		equals(jStat.corrcoeff([1,2,3,6,9,3,1,2,5],[2,3,5,2,5,7,8,9,6]),-0.16693777514921238,'corrcoeff([1,2,3,6,9,3,1,2,5],[2,3,5,2,5,7,8,9,6])');
	});

	module('distribution');

	test('uniformcdf',function(){
		equals(jStat.uniform.cdf(0.5, 0, 2),0.25,'uniform.cdf(0, 2, 0.5)');
	});

	test('binomial',function(){
		equals(jStat.binomial.pdf(2, 5, 0.5),0.3125,'binomial.pdf(5, 1/2, 2)');
	});

	test('weibull',function(){
		equals(jStat.weibull.pdf(1,1,1),0.36787944117144233,'weibull(1,1,1)');
		equals(jStat.weibull.pdf(2,1,2),0.18393972058572117,'weibull(2,1,2)');
	});

	test('weibullcdf',function(){
		equals(jStat.weibull.cdf(1,1,1),0.6321205588285577,'weibull.cdf(1,1,1)');
		equals(jStat.weibull.cdf(2,1,2),0.6321205588285577,'weibull.cdf(2,1,2)');
	});

});
<commit_msg>update qunit for stdev and variance<commit_after>$(function() {
	var singleArr = [ 1, 2, 3 ],
		doubleArr = [[ 1, 2, 3 ],[ 4, 5, 6 ],[ 7, 8, 9 ]];

	module( 'core' );

	test( 'sequence generation', function() {
		deepEqual( jStat.seq( 0, 1, 5 ), [ 0, 0.25, 0.5, 0.75, 1 ], 'seq( 0, 1, 5 )' );
	});

	test( 'row count', function() {
		equals( jStat( singleArr.slice() ).rows(), 1, 'fn.rows()' );
		equals( jStat( doubleArr.slice() ).rows(), 3, 'fn.rows()' );
	});

	test( 'column count', function() {
		equals( jStat( singleArr.slice() ).cols(), 3, 'fn.cols()' );
		equals( jStat( doubleArr.slice() ).cols(), 3, 'fn.cols()' );
	});

	test( 'dimensions', function() {
		deepEqual( jStat( singleArr.slice()).dimensions(), {
			rows : 1,
			cols : 3
		}, 'fn.dimensions()' );
		deepEqual( jStat( doubleArr.slice()).dimensions(), {
			rows : 3,
			cols : 3
		}, 'fn.dimensions()' );
	});

	test( 'row vector', function() {
		deepEqual( jStat( singleArr.slice()).row( 0 ).toArray(), [[ 1, 2, 3 ]], 'fn.row()' );
		deepEqual( jStat( doubleArr.slice()).row( 1 ).toArray(), [[ 4, 5, 6 ]], 'fn.row()' );
	});

	test( 'column vector', function() {
		deepEqual( jStat( singleArr.slice()).col( 0 ).toArray(), [[ 1 ]], 'fn.col()' );
		deepEqual( jStat( doubleArr.slice()).col( 1 ).toArray(), [[ 2 ],[ 5 ],[ 8 ]], 'fn.col()' );
	});

	test( 'matrix diagonal', function() {
		deepEqual( jStat( doubleArr.slice()).diag().toArray(), [[ 1 ],[ 5 ],[ 9 ]], 'fn.diag()' );
	});

	test( 'matrix anti-diagonal', function() {
		deepEqual( jStat( doubleArr.slice()).antidiag().toArray(), [[ 3 ],[ 5 ],[ 7 ]], 'fn.antidiag()' );
	});

	test( 'matrix transpose', function() {
		deepEqual( jStat.transpose( doubleArr ), [[ 1, 4, 7 ],[ 2, 5, 8 ],[ 3, 6, 9 ]], 'transpose()' );
	});

	test( 'map', function() {
		deepEqual( jStat.map( doubleArr, function( x ) {
			return x * 2;
		}), [[ 2, 4, 6 ],[ 8, 10, 12 ],[ 14, 16, 18 ]], 'map()' );
	});

	test( 'add', function() {
		deepEqual( jStat.add( doubleArr, 2 ), [[ 3, 4, 5 ],[ 6, 7, 8 ],[ 9, 10, 11 ]], 'add()' );
	});

	test( 'subtract', function() {
		deepEqual( jStat.subtract( doubleArr, 2 ), [[ -1, 0, 1 ],[ 2, 3, 4 ],[ 5, 6, 7 ]], 'subtract()' );
	});

	test( 'multiply', function() {
		deepEqual( jStat.multiply( doubleArr, 2 ), [[ 2, 4, 6 ],[ 8, 10, 12 ],[ 14, 16, 18 ]], 'multiply()' );
	});

	test( 'divide', function() {
		deepEqual( jStat.divide( singleArr, 2 ), [ 1 / 2, 1, 3 / 2 ], 'divide()' );
	});

	test( 'dot', function() {
		deepEqual( jStat.dot([[ 1, 2 ],[ 3, 4 ]],[[ 5, 6 ],[ 7, 8 ]]), [ 17, 53 ], 'dot()' );
	});

	test( 'pow', function() {
		deepEqual( jStat.pow( singleArr, 2 ), [ 1, 4, 9 ], 'pow()' );
	});

	test( 'abs', function() {
		deepEqual( jStat.abs([ 1, -1, -2 ]), [ 1, 1, 2 ], 'abs()' );
	});

	test( 'vector norm', function() {
		equals( jStat.norm([ 1, 2, 3 ], 1 ), 6, 'norm()' );
		equals( jStat.norm([ 1, 2, 3 ]), 3.7416573867739413, 'norm()' );
	});

	test( 'vector angle', function() {
		equals( jStat.angle([ 1, 0, 1 ],[ 0, 1, 0 ]), Math.PI / 2, 'angle()' );
	});

	test( 'symmetric', function() {
		equals( jStat.symmetric( singleArr ), false, 'symmetric()' );
		equals( jStat.symmetric( doubleArr ), false, 'symmetric()' );
		equals( jStat.symmetric([[ 1, 2 ],[ 2, 1 ]]), true, 'symmetric()' );
	});

	test('sum',function(){
		equals(jStat.sum([1,2,3,4,5,6]),21,'sum([1,2,3,4,5,6])');
	});

	test('min',function(){
		equals(jStat.min([1,2,3,4,5,6]),1,'min([1,2,3,4,5,6])');
	});

	test('max',function(){
		equals(jStat.max([1,2,3,4,5,6]),6,'max([1,2,3,4,5,6])');
	});

	test('mean',function(){
		equals(jStat.mean([1,2,3,4,5,6]),3.5,'mean([1,2,3,4,5,6])');
	});

	test('median',function(){
		equals(jStat.median([1,2,3,3,4,5,6]),3,'median([1,2,3,3,4,5,6])');
		equals(jStat.median([1,2,3,4,5,6]),3.5,'median([1,2,3,4,5,6])');
	});

	test('mode',function(){
		equals(jStat.mode([1,2,3,3,4,5,6]),3,'mode([1,2,3,3,4,5,6])');
		equals(jStat.mode([1,1,2,3,3,4,5,6]),false,'mode([1,1,2,3,3,4,5,6])');
	});

	test('range',function(){
		equals(jStat.range([1,2,3,3,4,5,6]),5,'range([1,2,3,3,4,5,6])');
		equals(jStat.range([-3,-6,-4]),3,'range([-3,-6,-4])');
	});

	test('variance',function(){
		equals(jStat.variance([3,4,5,6,7]),2,'variance([3,4,5,6,7])');
		equals(jStat.variance([1,2,3,4,5,6], 1),3.5,'variance([1,2,3,4,5,6], 1)');
	});

	test('stdev',function(){
		equals(jStat.stdev([3,4,5], 1),1,'stdev([3,4,5], 1)');
		equals(jStat.stdev([-3,-4,-5], 1),1,'stdev([-3,-4,-5], 1)');
		equals(jStat.stdev([1,2,3]), 0.816496580927726, 'stdev([1,2,3])');
	});

	test('meandev',function(){
		equals(jStat.meandev([2,2,3,4,14]),3.6,'meandev([2,2,3,4,14])');
	});

	test('meddev',function(){
		equals(jStat.meddev([2,2,3,4,14]),2.8,'meddev([2,2,3,4,14])');
	});

	test('factorial',function(){
		equals(jStat.factorial(5),120,'factorial(5)');
		equals(jStat.factorial(.5).toFixed(7),'0.8862269','factorial(.5)');
	});

	test('combination',function(){
		equals(jStat.combination(10,4),210,'combination(10,4)');
	});

	test('permutation',function(){
		equals(jStat.permutation(10,4),5040,'permutation(10,4)');
	});

	test('gamma',function(){
		equals(jStat.gammafn(.5).toFixed(7),'1.7724539','gamma(.5)');
		equals(jStat.gammafn(15),87178291200,'gamma(5)');
	});

	test('quartiles',function(){
		equals(jStat.quartiles([1,2,3,6,9,3,1,2,5]).toString(),'1,3,5','quartiles([1,2,3,6,9,3,1,2,5])');
	});

	test('covariance',function(){
		equals(jStat.covariance([1,2,3,6,9,3,1,2,5],[2,3,5,2,5,7,8,9,6]),-1.1234567901234565,'covariance([1,2,3,6,9,3,1,2,5],[2,3,5,2,5,7,8,9,6])');
	});

	test('corrcoeff',function(){
		equals(jStat.corrcoeff([1,2,3,6,9,3,1,2,5],[2,3,5,2,5,7,8,9,6]),-0.16693777514921238,'corrcoeff([1,2,3,6,9,3,1,2,5],[2,3,5,2,5,7,8,9,6])');
	});

	module('distribution');

	test('uniformcdf',function(){
		equals(jStat.uniform.cdf(0.5, 0, 2),0.25,'uniform.cdf(0, 2, 0.5)');
	});

	test('binomial',function(){
		equals(jStat.binomial.pdf(2, 5, 0.5),0.3125,'binomial.pdf(5, 1/2, 2)');
	});

	test('weibull',function(){
		equals(jStat.weibull.pdf(1,1,1),0.36787944117144233,'weibull(1,1,1)');
		equals(jStat.weibull.pdf(2,1,2),0.18393972058572117,'weibull(2,1,2)');
	});

	test('weibullcdf',function(){
		equals(jStat.weibull.cdf(1,1,1),0.6321205588285577,'weibull.cdf(1,1,1)');
		equals(jStat.weibull.cdf(2,1,2),0.6321205588285577,'weibull.cdf(2,1,2)');
	});

});
<|endoftext|>


<commit_before>require('proof')(1, okay => {
    const language = require('../../language')
    okay(language({ packet: { value: -16 } }), [{
        type: 'structure',
        vivify: 'object',
        name: 'packet',
        fixed: true,
        bits: 16,
        dotted: '',
        fields: [{
            type: 'integer',
            vivify: 'number',
            name: 'value',
            dotted: '.value',
            fixed: true,
            bits: 16,
            bytes: [{
                mask: 255, size: 8, shift: 8, set: 0
            }, {
                mask: 255, size: 8, shift: 0, set: 0
            }],
            endianness: 'big',
            compliment: true
        }]
    }], 'negative')
})
<commit_msg>Remove islolated integer language test.<commit_after><|endoftext|>


<commit_before>var lanyrd = require('../lib/lanyrd-scraper.js'),
	express = require('express');

/*
	======== A Handy Little Nodeunit Reference ========
	https://github.com/caolan/nodeunit

	Test methods:
	test.expect(numAssertions)
	test.done()
	Test assertions:
	test.ok(value, [message])
	test.equal(actual, expected, [message])
	test.notEqual(actual, expected, [message])
	test.deepEqual(actual, expected, [message])
	test.notDeepEqual(actual, expected, [message])
	test.strictEqual(actual, expected, [message])
	test.notStrictEqual(actual, expected, [message])
	test.throws(block, [error], [message])
	test.doesNotThrow(block, [error], [message])
	test.ifError(value)
*/

var app = express.createServer();
var PORT = 8535;

app.configure(function(){
    app.use(express.methodOverride());
    app.use(express.bodyParser());
    app.use(app.router);
    app.use(express['static'](__dirname + '/mock-pages'));
});

app.listen(PORT);

var multiDayEventData;
exports['multi-day event'] = {
	setUp: function(done) {
		if (multiDayEventData) {
			done();
			return;
		}

		lanyrd.scrape('http://localhost:' + PORT + '/multi-day-event.html', function(err, res){
			multiDayEventData = res;
			done();
		});
	},
	'has title': function(test) {
		test.expect(1);
		test.equal(multiDayEventData.title, 'Web Directions Code');
		test.done();
	},
	'has tagline': function(test) {
		test.expect(1);
		test.equal(multiDayEventData.tagline, 'Melbourne, get your code on.');
		test.done();
	},
	'has website': function(test) {
		test.expect(1);
		test.equal(multiDayEventData.websiteUrl, 'http://code12melb.webdirections.org/');
		test.done();
	},
	'has schedule': function(test) {
		test.expect(1);
		test.equal(multiDayEventData.scheduleUrl, 'http://lanyrd.com/2012/web-directions-code/schedule/');
		test.done();
	},
	'has location': function(test) {
		test.expect(1);
		test.equal(multiDayEventData.location, 'Melbourne, Australia');
		test.done();
	},
	'has venue': function(test) {
		test.expect(4);
		test.equal(multiDayEventData.venue.name, 'The RACV City Club');
		test.equal(multiDayEventData.venue.address, '501 Bourke St, Melbourne, 3000');
		test.equal(multiDayEventData.venue.note, 'Enter through the front door - you\'ll see where to go');
		test.equal(multiDayEventData.venue.googleMapsUrl, 'http://maps.google.com/maps?q=-37.8154734594,144.959473427+(The RACV City Club)');
		test.done();
	},
	'has start date': function(test) {
		test.expect(1);
		test.equal(multiDayEventData.startDate, 'May 23, 2012');
		test.done();
	},
	'has end date': function(test) {
		test.expect(1);
		test.equal(multiDayEventData.endDate, 'May 24, 2012');
		test.done();
	},
	'has hashtag': function(test) {
		test.expect(1);
		test.equal(multiDayEventData.hashtag, '#wdc12');
		test.done();
	},
	'has Twitter account': function(test) {
		test.expect(1);
		test.equal(multiDayEventData.twitterHandle, '@webdirections');
		test.done();
	},
	'has speakers': function(test) {
		test.expect(5);
		test.equal(multiDayEventData.speakers.length, 19);
		test.equal(multiDayEventData.speakers[15].name, 'Mark Dalgleish');
		test.equal(multiDayEventData.speakers[15].twitterHandle, '@markdalgleish');
		test.equal(multiDayEventData.speakers[11].name, 'Anette Bergo', 'supports speakers without Twitter handles');
		test.equal(multiDayEventData.speakers[11].twitterHandle, undefined, 'supports speakers without Twitter handles');
		test.done();
	},
	'has sessions': function(test) {
		test.expect(6);
		test.equal(multiDayEventData.sessions.length, 20);
		test.equal(multiDayEventData.sessions[14].title, 'JavaScript: Getting Closure');
		test.equal(multiDayEventData.sessions[14].speakerName, 'Mark Dalgleish');
		test.equal(multiDayEventData.sessions[14].speakerTwitterHandle, '@markdalgleish');
		test.equal(multiDayEventData.sessions[18].speakerName, 'Anette Bergo', 'supports speakers without Twitter handles');
		test.equal(multiDayEventData.sessions[18].speakerTwitterHandle, undefined, 'supports speakers without Twitter handles');
		test.done();
	},
	'has attendees': function(test) {
		test.expect(3);
		test.equal(multiDayEventData.attendees.length, 27);
		test.equal(multiDayEventData.attendees[15].name, 'Mark Dalgleish');
		test.equal(multiDayEventData.attendees[15].twitterHandle, '@markdalgleish');
		test.done();
	},
	'has trackers': function(test) {
		test.expect(3);
		test.equal(multiDayEventData.trackers.length, 25);
		test.equal(multiDayEventData.trackers[0].name, 'Paul Irish ◕‿◕');
		test.equal(multiDayEventData.trackers[0].twitterHandle, '@paul_irish');
		test.done();
	}
};

var EVENT_URL = 'http://lanyrd.com/2012/web-directions-code';
exports['resolveUrl'] = {
	'ignores complete url': function(test) {
		test.expect(1);
		test.equal(lanyrd.resolveUrl(EVENT_URL), EVENT_URL);
		test.done();
	},
	'resolves urls correctly': function(test) {
		test.expect(2);
		test.equal(lanyrd.resolveUrl('2012/web-directions-code'), EVENT_URL);
		test.equal(lanyrd.resolveUrl('/2012/web-directions-code'), EVENT_URL);
		test.done();
	}
}<commit_msg>Lint fix<commit_after>var lanyrd = require('../lib/lanyrd-scraper.js'),
	express = require('express');

/*
	======== A Handy Little Nodeunit Reference ========
	https://github.com/caolan/nodeunit

	Test methods:
	test.expect(numAssertions)
	test.done()
	Test assertions:
	test.ok(value, [message])
	test.equal(actual, expected, [message])
	test.notEqual(actual, expected, [message])
	test.deepEqual(actual, expected, [message])
	test.notDeepEqual(actual, expected, [message])
	test.strictEqual(actual, expected, [message])
	test.notStrictEqual(actual, expected, [message])
	test.throws(block, [error], [message])
	test.doesNotThrow(block, [error], [message])
	test.ifError(value)
*/

var app = express.createServer();
var PORT = 8535;

app.configure(function(){
    app.use(express.methodOverride());
    app.use(express.bodyParser());
    app.use(app.router);
    app.use(express['static'](__dirname + '/mock-pages'));
});

app.listen(PORT);

var multiDayEventData;
exports['multi-day event'] = {
	setUp: function(done) {
		if (multiDayEventData) {
			done();
			return;
		}

		lanyrd.scrape('http://localhost:' + PORT + '/multi-day-event.html', function(err, res){
			multiDayEventData = res;
			done();
		});
	},
	'has title': function(test) {
		test.expect(1);
		test.equal(multiDayEventData.title, 'Web Directions Code');
		test.done();
	},
	'has tagline': function(test) {
		test.expect(1);
		test.equal(multiDayEventData.tagline, 'Melbourne, get your code on.');
		test.done();
	},
	'has website': function(test) {
		test.expect(1);
		test.equal(multiDayEventData.websiteUrl, 'http://code12melb.webdirections.org/');
		test.done();
	},
	'has schedule': function(test) {
		test.expect(1);
		test.equal(multiDayEventData.scheduleUrl, 'http://lanyrd.com/2012/web-directions-code/schedule/');
		test.done();
	},
	'has location': function(test) {
		test.expect(1);
		test.equal(multiDayEventData.location, 'Melbourne, Australia');
		test.done();
	},
	'has venue': function(test) {
		test.expect(4);
		test.equal(multiDayEventData.venue.name, 'The RACV City Club');
		test.equal(multiDayEventData.venue.address, '501 Bourke St, Melbourne, 3000');
		test.equal(multiDayEventData.venue.note, 'Enter through the front door - you\'ll see where to go');
		test.equal(multiDayEventData.venue.googleMapsUrl, 'http://maps.google.com/maps?q=-37.8154734594,144.959473427+(The RACV City Club)');
		test.done();
	},
	'has start date': function(test) {
		test.expect(1);
		test.equal(multiDayEventData.startDate, 'May 23, 2012');
		test.done();
	},
	'has end date': function(test) {
		test.expect(1);
		test.equal(multiDayEventData.endDate, 'May 24, 2012');
		test.done();
	},
	'has hashtag': function(test) {
		test.expect(1);
		test.equal(multiDayEventData.hashtag, '#wdc12');
		test.done();
	},
	'has Twitter account': function(test) {
		test.expect(1);
		test.equal(multiDayEventData.twitterHandle, '@webdirections');
		test.done();
	},
	'has speakers': function(test) {
		test.expect(5);
		test.equal(multiDayEventData.speakers.length, 19);
		test.equal(multiDayEventData.speakers[15].name, 'Mark Dalgleish');
		test.equal(multiDayEventData.speakers[15].twitterHandle, '@markdalgleish');
		test.equal(multiDayEventData.speakers[11].name, 'Anette Bergo', 'supports speakers without Twitter handles');
		test.equal(multiDayEventData.speakers[11].twitterHandle, undefined, 'supports speakers without Twitter handles');
		test.done();
	},
	'has sessions': function(test) {
		test.expect(6);
		test.equal(multiDayEventData.sessions.length, 20);
		test.equal(multiDayEventData.sessions[14].title, 'JavaScript: Getting Closure');
		test.equal(multiDayEventData.sessions[14].speakerName, 'Mark Dalgleish');
		test.equal(multiDayEventData.sessions[14].speakerTwitterHandle, '@markdalgleish');
		test.equal(multiDayEventData.sessions[18].speakerName, 'Anette Bergo', 'supports speakers without Twitter handles');
		test.equal(multiDayEventData.sessions[18].speakerTwitterHandle, undefined, 'supports speakers without Twitter handles');
		test.done();
	},
	'has attendees': function(test) {
		test.expect(3);
		test.equal(multiDayEventData.attendees.length, 27);
		test.equal(multiDayEventData.attendees[15].name, 'Mark Dalgleish');
		test.equal(multiDayEventData.attendees[15].twitterHandle, '@markdalgleish');
		test.done();
	},
	'has trackers': function(test) {
		test.expect(3);
		test.equal(multiDayEventData.trackers.length, 25);
		test.equal(multiDayEventData.trackers[0].name, 'Paul Irish ◕‿◕');
		test.equal(multiDayEventData.trackers[0].twitterHandle, '@paul_irish');
		test.done();
	}
};

var EVENT_URL = 'http://lanyrd.com/2012/web-directions-code';
exports['resolveUrl'] = {
	'ignores complete url': function(test) {
		test.expect(1);
		test.equal(lanyrd.resolveUrl(EVENT_URL), EVENT_URL);
		test.done();
	},
	'resolves urls correctly': function(test) {
		test.expect(2);
		test.equal(lanyrd.resolveUrl('2012/web-directions-code'), EVENT_URL);
		test.equal(lanyrd.resolveUrl('/2012/web-directions-code'), EVENT_URL);
		test.done();
	}
};<|endoftext|>


<commit_before>const bunyan = require('bunyan');
const settings = require('../settings');

const logger = bunyan.createLogger({ name: 'pix-api', streams: [] });

if (settings.logging.enabled) {

  logger.addStream({
    name: 'standard-output',
    stream: process.stdout,
    level: 'debug'
  });
}

module.exports = logger;
<commit_msg> change logging level to info<commit_after>const bunyan = require('bunyan');
const settings = require('../settings');

const logger = bunyan.createLogger({ name: 'pix-api', streams: [] });

if (settings.logging.enabled) {

  logger.addStream({
    name: 'standard-output',
    stream: process.stdout,
    level: 'info'
  });
}

module.exports = logger;
<|endoftext|>


<commit_before>const util = require('util');
import {
    translateSearch,
    translateAggBuckets,
    translateCrowdAggBuckets,
    translateOpenAggBuckets,
    translateOpenCrowdAggBuckets,
} from './translator';
import * as elastic from './elastic';
import { keysToCamel } from '../util/case.convert';
import logger from '../util/logger';
import { query } from '../util/db';

const QUERY_SHORT_LINK = 'select * from short_links where short=$1';
const QUERY_LONG_LINK = 'select * from short_links where long=$1';
const QUERY_NEW_HASH = `insert into short_links (short,long, created_at, updated_at) values ($1,$2, to_timestamp(${Date.now()} / 1000.0), to_timestamp(${Date.now()} / 1000.0))`;
const crypto = require('crypto');

export async function searchDIS(args) {
    // logger.info('ARGSDIS!:', + args)
    try {
        const translated = await translateSearch(args.params, true);
        let esResults = await elastic.query(translated, process.env.ELASTICSEARCH_INDEX_DIS);
        const diseases = esResults.body.hits.hits
        .filter(disease => (disease._source.condition_id ? true : false))
        .map(disease => esToGraphql(disease));
        return {
            recordsTotal: esResults.body.hits.total,
            diseases,
        };
    } catch (err) {
        logger.error('Error running search: ' + err);
    }
}

export async function search(args) {
    logger.info('ARGS!:', + args)

    try {
        const translated = await translateSearch(args.params, true);
        // console.log("-------------->  ELASTIC SEARCH QUERY <------------- " + util.inspect(translated, false, null, true))
        let esResults = await elastic.query(translated,  process.env.ELASTICSEARCH_INDEX);
        const studies = esResults.body.hits.hits
            .filter(study => (study._source.nct_id ? true : false))
            .map(study => esToGraphql(study));
        return {
            recordsTotal: esResults.body.hits.total,
            studies,
        };
    } catch (err) {
        logger.error('Error running search: ' + err);
    }
}
export async function searchParams(args) {
    try {
        let params;
        const results = await query(QUERY_SHORT_LINK, [args.hash]);
        //logger.info('PARAMS', results)
        if (results.rows.length === 1) {
            const link = results.rows[0];
            params = link.long;
        }

        let parsedParams = JSON.parse(params);
        // The following if block is currently needed as there is still old hashes we need to handle.
        //Ruby syntax is to snake case so all hashes prior to node where using snake_case variables
        //Now that functionality of our searchPageHash mutation is being handled by node our hashes are being created with camelCased Values
        if (parsedParams['agg_filters'] || parsedParams['crowd_agg_filters']) {
            let aggFilter = [];
            parsedParams['agg_filters'].map((agg, index) => {
                let tempAgg = {};
                for (const [key, value] of Object.entries(agg)) {
                    if (key == 'include_missing_fields') {
                        tempAgg['includeMissingFields'] = value;
                    } else {
                        tempAgg[key] = value;
                    }
                }
                aggFilter.push(tempAgg);
            });
            parsedParams['agg_filters'] = aggFilter;

            let crowdAggFilter = [];
            parsedParams['crowd_agg_filters'].map((agg, index) => {
                let tempAgg = {};

                for (const [key, value] of Object.entries(agg)) {
                    if (key == 'include_missing_fields') {
                        tempAgg['includeMissingFields'] = value;
                    } else {
                        tempAgg[key] = value;
                    }
                }
                crowdAggFilter.push(tempAgg);
            });
            parsedParams['crowd_agg_filters'] = crowdAggFilter;
        }

        return {
            //reParsing to string as app is expecting that. May want to rework to just return JSON
            searchParams: JSON.stringify(parsedParams),
        };
    } catch (err) {
        logger.error('Error running searchParams: ' + err);
    }
}
export async function provisionSearchHash(args) {
    try {
        logger.info('SEARCH_PAGE_HASH_MUTATION');
        let paramString = JSON.stringify(args.input.params);
        const results = await query(QUERY_LONG_LINK, [paramString]);
        let hash_short;
        if (results.rows.length === 1) {
            const link = results.rows[0];
            hash_short = link.short;
            console.log('HASH FOUND', hash_short);
            return { searchHash: { short: hash_short } };
        }
        console.log('No HASH!');
        const hash = crypto
            .createHash('sha256')
            .update(paramString)
            .digest('hex');
        console.log(hash);
        let short = hash.slice(0, 8);
        console.log('SHORT', short);
        const newHash = await query(QUERY_NEW_HASH, [short, paramString]);
        console.log('NewHASH', newHash);

        return { searchHash: { short: short } };
    } catch (err) {
        logger.error('Error running provisionSearchHash: ' + err);
    }
}

export async function openAggBuckets(args) {
    console.log('ARGS AGG BUCKETS ', args)
    try {
        const translated = await translateOpenAggBuckets(
            args.params,
            args.aggBucketsWanted
        );
        console.log("TRANSLATED", translated)
        let esResults = await elastic.query(translated, process.env.ELASTICSEARCH_INDEX);
        console.log("TRANSLATED OPEN AGG Buckets" + util.inspect(esResults.body.aggregations, true, null, false))
        const studies = esResults.body.hits.hits.map(study =>
            esToGraphql(study)
        );
        let aggs = [];
        let i = 0;
        let j = 0;
        // console.log("TRANSLATED OPEN  Buckets" + util.inspect(translated,false,null,true))
        for (const [key, value] of Object.entries(
            esResults.body.aggregations
        )) {
            const agg = aggToGraphql2(key, value);
            aggs.push(agg);
            i++;
        }
        console.log("CHECK HERE", aggs)
        return {
            recordsTotal: esResults.body.hits.total,
            aggs: aggs,
        };
    } catch (err) {
        logger.error(err);
    }
}
export async function aggBuckets(args) {
    console.log('ARGS AGG BUCKETS ', args)
    try {
        const translated = await translateOpenAggBuckets(
            args.params,
            args.aggBucketsWanted,

        );
        console.log("TRANSLATED", translated)
        let esResults = await elastic.query(translated, process.env.ELASTICSEARCH_INDEX);
        console.log("TRANSLATED AGG Buckets" + util.inspect(esResults.body.aggregations, true, null, false))
        const studies = esResults.body.hits.hits.map(study =>
            esToGraphql(study)
        );
        let aggs = [];
        let i = 0;
        let j = 0;
        // console.log("TRANSLATED OPEN  Buckets" + util.inspect(translated,false,null,true))
        for (const [key, value] of Object.entries(
            esResults.body.aggregations
        )) {
            const agg = aggToGraphql2(key, value[key]);

            aggs.push(agg);
            i++;
        }
        console.log("CHECK HERE", aggs)
        return {
            recordsTotal: esResults.body.hits.total,
            aggs: aggs,
        };
    } catch (err) {
        logger.error(err);
    }
}

function esToGraphql(study) {
    let obj = keysToCamel(study._source);
    // console.log("--------->>>>>> STUDY <<<<<<-----------")
    //  console.log(study)
    obj.studyViewCount = obj.studyViewsCount;
    obj.isFdaRegulated = obj.isFdaRegulatedDrug | obj.isFdaRegulatedDevice;
    obj.averageRating = 0;
    return obj;
}

function aggToGraphql(key, value) {
    let buckets = [];
    if (value[key].buckets) {
        buckets = value[key].buckets.map(bucket => ({
            key: bucket.key,
            keyAsString: bucket.key,
            docCount: bucket.doc_count,
        }));
    }

    let agg = {
        name: key,
        buckets,
    };

    return agg;
}
function aggToGraphql2(key, value) {
    let buckets = [];
    if (value.buckets) {
        buckets = value.buckets.map(bucket => ({
            key: bucket.key,
            keyAsString: bucket.key,
            docCount: bucket.doc_count,
        }));
    }

    let agg = {
        name: key,
        buckets,
    };

    return agg;
}
<commit_msg>ternary for bucket elastic index to hit<commit_after>const util = require('util');
import {
    translateSearch,
    translateAggBuckets,
    translateCrowdAggBuckets,
    translateOpenAggBuckets,
    translateOpenCrowdAggBuckets,
} from './translator';
import * as elastic from './elastic';
import { keysToCamel } from '../util/case.convert';
import logger from '../util/logger';
import { query } from '../util/db';

const QUERY_SHORT_LINK = 'select * from short_links where short=$1';
const QUERY_LONG_LINK = 'select * from short_links where long=$1';
const QUERY_NEW_HASH = `insert into short_links (short,long, created_at, updated_at) values ($1,$2, to_timestamp(${Date.now()} / 1000.0), to_timestamp(${Date.now()} / 1000.0))`;
const crypto = require('crypto');

export async function searchDIS(args) {
    // logger.info('ARGSDIS!:', + args)
    try {
        const translated = await translateSearch(args.params, true);
        let esResults = await elastic.query(translated, process.env.ELASTICSEARCH_INDEX_DIS);
        const diseases = esResults.body.hits.hits
        .filter(disease => (disease._source.condition_id ? true : false))
        .map(disease => esToGraphql(disease));
        return {
            recordsTotal: esResults.body.hits.total,
            diseases,
        };
    } catch (err) {
        logger.error('Error running search: ' + err);
    }
}

export async function search(args) {
    logger.info('ARGS!:', + args)

    try {
        const translated = await translateSearch(args.params, true);
        // console.log("-------------->  ELASTIC SEARCH QUERY <------------- " + util.inspect(translated, false, null, true))
        let esResults = await elastic.query(translated,  process.env.ELASTICSEARCH_INDEX);
        const studies = esResults.body.hits.hits
            .filter(study => (study._source.nct_id ? true : false))
            .map(study => esToGraphql(study));
        return {
            recordsTotal: esResults.body.hits.total,
            studies,
        };
    } catch (err) {
        logger.error('Error running search: ' + err);
    }
}
export async function searchParams(args) {
    try {
        let params;
        const results = await query(QUERY_SHORT_LINK, [args.hash]);
        //logger.info('PARAMS', results)
        if (results.rows.length === 1) {
            const link = results.rows[0];
            params = link.long;
        }

        let parsedParams = JSON.parse(params);
        // The following if block is currently needed as there is still old hashes we need to handle.
        //Ruby syntax is to snake case so all hashes prior to node where using snake_case variables
        //Now that functionality of our searchPageHash mutation is being handled by node our hashes are being created with camelCased Values
        if (parsedParams['agg_filters'] || parsedParams['crowd_agg_filters']) {
            let aggFilter = [];
            parsedParams['agg_filters'].map((agg, index) => {
                let tempAgg = {};
                for (const [key, value] of Object.entries(agg)) {
                    if (key == 'include_missing_fields') {
                        tempAgg['includeMissingFields'] = value;
                    } else {
                        tempAgg[key] = value;
                    }
                }
                aggFilter.push(tempAgg);
            });
            parsedParams['agg_filters'] = aggFilter;

            let crowdAggFilter = [];
            parsedParams['crowd_agg_filters'].map((agg, index) => {
                let tempAgg = {};

                for (const [key, value] of Object.entries(agg)) {
                    if (key == 'include_missing_fields') {
                        tempAgg['includeMissingFields'] = value;
                    } else {
                        tempAgg[key] = value;
                    }
                }
                crowdAggFilter.push(tempAgg);
            });
            parsedParams['crowd_agg_filters'] = crowdAggFilter;
        }

        return {
            //reParsing to string as app is expecting that. May want to rework to just return JSON
            searchParams: JSON.stringify(parsedParams),
        };
    } catch (err) {
        logger.error('Error running searchParams: ' + err);
    }
}
export async function provisionSearchHash(args) {
    try {
        logger.info('SEARCH_PAGE_HASH_MUTATION');
        let paramString = JSON.stringify(args.input.params);
        const results = await query(QUERY_LONG_LINK, [paramString]);
        let hash_short;
        if (results.rows.length === 1) {
            const link = results.rows[0];
            hash_short = link.short;
            console.log('HASH FOUND', hash_short);
            return { searchHash: { short: hash_short } };
        }
        console.log('No HASH!');
        const hash = crypto
            .createHash('sha256')
            .update(paramString)
            .digest('hex');
        console.log(hash);
        let short = hash.slice(0, 8);
        console.log('SHORT', short);
        const newHash = await query(QUERY_NEW_HASH, [short, paramString]);
        console.log('NewHASH', newHash);

        return { searchHash: { short: short } };
    } catch (err) {
        logger.error('Error running provisionSearchHash: ' + err);
    }
}

export async function openAggBuckets(args) {
    console.log('ARGS AGG BUCKETS ', args)
    try {
        const translated = await translateOpenAggBuckets(
            args.params,
            args.aggBucketsWanted
        );
        console.log("TRANSLATED", translated)
        let esResults = process.env.DEFAULT_APPLICATION == "clinwiki" ? await elastic.query(translated, process.env.ELASTICSEARCH_INDEX) : await elastic.query(translated, process.env.ELASTICSEARCH_INDEX_DIS);
        console.log("TRANSLATED OPEN AGG Buckets" + util.inspect(esResults.body.aggregations, true, null, false))
        const studies = esResults.body.hits.hits.map(study =>
            esToGraphql(study)
        );
        let aggs = [];
        let i = 0;
        let j = 0;
        // console.log("TRANSLATED OPEN  Buckets" + util.inspect(translated,false,null,true))
        for (const [key, value] of Object.entries(
            esResults.body.aggregations
        )) {
            const agg = aggToGraphql2(key, value);
            aggs.push(agg);
            i++;
        }
        console.log("CHECK HERE", aggs)
        return {
            recordsTotal: esResults.body.hits.total,
            aggs: aggs,
        };
    } catch (err) {
        logger.error(err);
    }
}
export async function aggBuckets(args) {
    console.log('ARGS AGG BUCKETS ', args)
    try {
        const translated = await translateOpenAggBuckets(
            args.params,
            args.aggBucketsWanted,

        );
        console.log("TRANSLATED", translated)
        let esResults = await elastic.query(translated, process.env.ELASTICSEARCH_INDEX);
        console.log("TRANSLATED AGG Buckets" + util.inspect(esResults.body.aggregations, true, null, false))
        const studies = esResults.body.hits.hits.map(study =>
            esToGraphql(study)
        );
        let aggs = [];
        let i = 0;
        let j = 0;
        // console.log("TRANSLATED OPEN  Buckets" + util.inspect(translated,false,null,true))
        for (const [key, value] of Object.entries(
            esResults.body.aggregations
        )) {
            const agg = aggToGraphql2(key, value[key]);

            aggs.push(agg);
            i++;
        }
        console.log("CHECK HERE", aggs)
        return {
            recordsTotal: esResults.body.hits.total,
            aggs: aggs,
        };
    } catch (err) {
        logger.error(err);
    }
}

function esToGraphql(study) {
    let obj = keysToCamel(study._source);
    // console.log("--------->>>>>> STUDY <<<<<<-----------")
    //  console.log(study)
    obj.studyViewCount = obj.studyViewsCount;
    obj.isFdaRegulated = obj.isFdaRegulatedDrug | obj.isFdaRegulatedDevice;
    obj.averageRating = 0;
    return obj;
}

function aggToGraphql(key, value) {
    let buckets = [];
    if (value[key].buckets) {
        buckets = value[key].buckets.map(bucket => ({
            key: bucket.key,
            keyAsString: bucket.key,
            docCount: bucket.doc_count,
        }));
    }

    let agg = {
        name: key,
        buckets,
    };

    return agg;
}
function aggToGraphql2(key, value) {
    let buckets = [];
    if (value.buckets) {
        buckets = value.buckets.map(bucket => ({
            key: bucket.key,
            keyAsString: bucket.key,
            docCount: bucket.doc_count,
        }));
    }

    let agg = {
        name: key,
        buckets,
    };

    return agg;
}
<|endoftext|>


<commit_before>import babelify from 'babelify';
import browserify from 'browserify';
import buffer from 'vinyl-buffer';
import del from 'del';
import eslint from 'gulp-eslint';
import gulp from 'gulp';
import gutil from 'gulp-util';
import nodemon from 'nodemon';
import packageJson from './package.json';
import path from 'path';
import source from 'vinyl-source-stream';
import sequence from 'run-sequence';
import swPrecache from 'sw-precache';

const SRC_DIR = 'src';
const BUILD_DIR = 'build';
const THIRD_PARTY_MODULES = ['react', 'react-router'];

gulp.task('clean', () => {
  return del(BUILD_DIR);
});

gulp.task('bundle-app', () => {
  const bundler = browserify({
    entries: path.join(SRC_DIR, 'components', 'client.jsx'),
    extensions: ['.jsx'],
    transform: [babelify]
  });
  THIRD_PARTY_MODULES.forEach(module => bundler.external(module));

  return bundler.bundle()
    .pipe(source('app.js'))
    .pipe(buffer())
    .on('error', gutil.log)
    .pipe(gulp.dest(`${BUILD_DIR}/js`));
});

gulp.task('bundle-third-party', () => {
  const bundler = browserify();
  THIRD_PARTY_MODULES.forEach(module => bundler.require(module));

  return bundler.bundle()
    .pipe(source('third-party.js'))
    .pipe(buffer())
    .on('error', gutil.log)
    .pipe(gulp.dest(`${BUILD_DIR}/js`));
});

gulp.task('copy-static', () => {
  return gulp.src(`${SRC_DIR}/static/**/*`)
    .pipe(gulp.dest(BUILD_DIR));
});

gulp.task('copy-third-party', () => {
  return gulp.src('node_modules/sw-toolbox/sw-toolbox.js')
    .pipe(gulp.dest(`${BUILD_DIR}/js`));
});

gulp.task('generate-service-worker', () => {
  const serviceWorkerFile = path.join(BUILD_DIR, 'service-worker.js');
  return del(serviceWorkerFile).then(() => {
    return swPrecache.write(serviceWorkerFile, {
      cacheId: packageJson.name,
      directoryIndex: null,
      dynamicUrlToDependencies: {
        '/shell': [`${SRC_DIR}/views/index.handlebars`]
      },
      importScripts: ['sw-toolbox.js', 'sw-toolbox-config.js'].map(script => `js/${script}`),
      logger: gutil.log,
      navigateFallback: '/shell',
      staticFileGlobs: [`${BUILD_DIR}/**/*.js`],
      stripPrefix: 'build/',
      verbose: true
    });
  });
});

gulp.task('build', callback => {
  sequence(
    ['bundle-app', 'bundle-third-party', 'copy-static', 'copy-third-party'],
    'generate-service-worker',
    callback
  );
});

gulp.task('serve', callback => {
  nodemon({
    script: 'index.js',
    ext: 'js jsx html',
    watch: [SRC_DIR, BUILD_DIR],
    verbose: true
  }).on('start', () => {
    gutil.log('Server started.');
  }).on('restart', files => {
    gutil.log('Restarted server. Changed files: ', files);
  }).on('quit', callback);
});

gulp.task('lint', () => {
  return gulp.src([`${SRC_DIR}/**/*.{js,jsx}`, '*.js'])
    .pipe(eslint())
    .pipe(eslint.format());
});

gulp.task('watch', () => {
  gulp.watch(`${SRC_DIR}/**/*.{js,jsx}`, ['bundle-app', 'lint']);
  gulp.watch(`${SRC_DIR}/static/**/*`, ['copy-static']);
});

gulp.task('default', callback => {
  sequence('clean', 'build', ['serve', 'watch'], callback);
});
<commit_msg>Handle Babelify errors without breaking watching.<commit_after>import babelify from 'babelify';
import browserify from 'browserify';
import buffer from 'vinyl-buffer';
import del from 'del';
import eslint from 'gulp-eslint';
import gulp from 'gulp';
import gutil from 'gulp-util';
import nodemon from 'nodemon';
import packageJson from './package.json';
import path from 'path';
import source from 'vinyl-source-stream';
import sequence from 'run-sequence';
import swPrecache from 'sw-precache';

const SRC_DIR = 'src';
const BUILD_DIR = 'build';
const THIRD_PARTY_MODULES = ['react', 'react-router'];

gulp.task('clean', () => {
  return del(BUILD_DIR);
});

gulp.task('bundle-app', () => {
  const bundler = browserify({
    entries: path.join(SRC_DIR, 'components', 'client.jsx'),
    extensions: ['.jsx'],
    transform: [babelify]
  });
  THIRD_PARTY_MODULES.forEach(module => bundler.external(module));

  return bundler.bundle()
    .on('error', function(error) {
      gutil.log('Babelify error:', error.message);
      this.emit('end');
    })
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe(gulp.dest(`${BUILD_DIR}/js`));
});

gulp.task('bundle-third-party', () => {
  const bundler = browserify();
  THIRD_PARTY_MODULES.forEach(module => bundler.require(module));

  return bundler.bundle()
    .on('error', function(error) {
      gutil.log('Babelify error:', error.message);
      this.emit('end');
    })
    .pipe(source('third-party.js'))
    .pipe(buffer())
    .on('error', gutil.log)
    .pipe(gulp.dest(`${BUILD_DIR}/js`));
});

gulp.task('copy-static', () => {
  return gulp.src(`${SRC_DIR}/static/**/*`)
    .pipe(gulp.dest(BUILD_DIR));
});

gulp.task('copy-third-party', () => {
  return gulp.src('node_modules/sw-toolbox/sw-toolbox.js')
    .pipe(gulp.dest(`${BUILD_DIR}/js`));
});

gulp.task('generate-service-worker', () => {
  const serviceWorkerFile = path.join(BUILD_DIR, 'service-worker.js');
  return del(serviceWorkerFile).then(() => {
    return swPrecache.write(serviceWorkerFile, {
      cacheId: packageJson.name,
      directoryIndex: null,
      dynamicUrlToDependencies: {
        '/shell': [`${SRC_DIR}/views/index.handlebars`]
      },
      importScripts: ['sw-toolbox.js', 'sw-toolbox-config.js'].map(script => `js/${script}`),
      logger: gutil.log,
      navigateFallback: '/shell',
      staticFileGlobs: [`${BUILD_DIR}/**/*.js`],
      stripPrefix: 'build/',
      verbose: true
    });
  });
});

gulp.task('build', callback => {
  sequence(
    ['bundle-app', 'bundle-third-party', 'copy-static', 'copy-third-party'],
    'generate-service-worker',
    callback
  );
});

gulp.task('serve', callback => {
  nodemon({
    script: 'index.js',
    ext: 'js jsx html',
    watch: [SRC_DIR, BUILD_DIR],
    verbose: true
  }).on('start', () => {
    gutil.log('Server started.');
  }).on('crash', () => {
    gutil.log('Server crashed.');
  }).on('restart', files => {
    gutil.log('Restarted server. Changed files: ', files);
  }).on('quit', callback);
});

gulp.task('lint', () => {
  return gulp.src([`${SRC_DIR}/**/*.{js,jsx}`, '*.js'])
    .pipe(eslint())
    .pipe(eslint.format());
});

gulp.task('watch', () => {
  gulp.watch(`${SRC_DIR}/**/*.{js,jsx}`, ['bundle-app', 'lint']);
  gulp.watch(`${SRC_DIR}/static/**/*`, ['copy-static']);
});

gulp.task('default', callback => {
  sequence('clean', 'build', ['serve', 'watch'], callback);
});
<|endoftext|>


<commit_before>var bowerPath = fis.config.get('bower.path') || 'bower_components';

fis.config.set('project.exclude', bowerPath);
var fs = require('fs');
var path = require('path');
var originGetSource = fis.project.getSource;

function loadAllBowerFile(componentPath, source) {
    var exclude = fis.config.get('project.exclude');
    var root = fis.project.getProjectPath();
    fis.util.find(bowerPath + path.sep + componentPath, null, exclude, root).forEach(function (file) {
        file = fis.file(file);
        if (file.release) {
            source[file.subpath] = file;
        }
    });
}

fis.project.getSource = function () {
    var source = originGetSource();
    var root = fis.project.getProjectPath();
    var bowerRootPath = root + path.sep + bowerPath;
    var componentPaths;
    try {
        componentPaths = fs.readdirSync(bowerRootPath);
    } catch (e) {
        // no bower components
    }
    if (componentPaths) {
        var mainFiles = componentPaths.map(function getBowerJSON(componentPath) {
            try {
                var bowerJSON = require(bowerRootPath + path.sep + componentPath + path.sep + 'bower.json');
                if (!bowerJSON.main) {
                    fis.log.warning('No main file(s) specified in bower component [' + componentPath + ']');
                    loadAllBowerFile(componentPath, source);
                    return false;
                }
                return {
                    componentPath: componentPath,
                    main: bowerJSON.main
                };
            } catch (e) {
                fis.log.warning('No bower.json in bower component [' + componentPath + ']');
                loadAllBowerFile(componentPath, source);
                return false;
            }
        }).forEach(function (conf) {
            if (conf && conf.main) {
                var main = conf.main instanceof Array ? conf.main : [conf.main];
                var componentPath = bowerRootPath + path.sep + conf.componentPath + path.sep;
                main.forEach(function addMainFile(filePath) {
                    var files = [];
                    if (filePath.indexOf('*') !== -1) {
                        filePath = filePath.replace(/^\.\//, '');
                        fis.util.find(componentPath).forEach(function (file) {
                            var relativePath = path.relative(componentPath, file);
                            if (fis.util.glob(filePath, relativePath)) {
                                files.push(fis.file(file));
                            }
                        });
                    } else {
                        files.push(fis.file(componentPath + path.sep + filePath));
                    }
                    files.forEach(function (file) {
                        source[file.subpath] = file;
                    });
                });
            }
        });
    }
    return source;
};<commit_msg>[fix] fix path problem in windows<commit_after>var bowerPath = fis.config.get('bower.path') || 'bower_components';

fis.config.set('project.exclude', bowerPath);
var fs = require('fs');
var path = require('path');
var originGetSource = fis.project.getSource;

function loadAllBowerFile(componentPath, source) {
    var exclude = fis.config.get('project.exclude');
    var root = fis.project.getProjectPath();
    fis.util.find(bowerPath + path.sep + componentPath, null, exclude, root).forEach(function (file) {
        file = fis.file(file);
        if (file.release) {
            source[file.subpath] = file;
        }
    });
}

fis.project.getSource = function () {
    var source = originGetSource();
    var root = fis.project.getProjectPath();
    var bowerRootPath = root + path.sep + bowerPath;
    var componentPaths;
    try {
        componentPaths = fs.readdirSync(bowerRootPath);
    } catch (e) {
        // no bower components
    }
    if (componentPaths) {
        var mainFiles = componentPaths.map(function getBowerJSON(componentPath) {
            try {
                var bowerJSON = require(bowerRootPath + path.sep + componentPath + path.sep + 'bower.json');
                if (!bowerJSON.main) {
                    fis.log.warning('No main file(s) specified in bower component [' + componentPath + ']');
                    loadAllBowerFile(componentPath, source);
                    return false;
                }
                return {
                    componentPath: componentPath,
                    main: bowerJSON.main
                };
            } catch (e) {
                fis.log.warning('No bower.json in bower component [' + componentPath + ']');
                loadAllBowerFile(componentPath, source);
                return false;
            }
        }).forEach(function (conf) {
            if (conf && conf.main) {
                var main = conf.main instanceof Array ? conf.main : [conf.main];
                var componentPath = bowerRootPath + path.sep + conf.componentPath + path.sep;
                main.forEach(function addMainFile(filePath) {
                    var files = [];
                    if (filePath.indexOf('*') !== -1) {
                        filePath = filePath.replace(/^\.\//, '');
                        fis.util.find(componentPath).forEach(function (file) {
                            var relativePath = path.relative(componentPath, file).replace(/\\/g, '\/');
                            if (fis.util.glob(filePath, relativePath)) {
                                files.push(fis.file(file));
                            }
                        });
                    } else {
                        files.push(fis.file(componentPath + path.sep + filePath));
                    }
                    files.forEach(function (file) {
                        source[file.subpath] = file;
                    });
                });
            }
        });
    }
    return source;
};<|endoftext|>


<commit_before>if (typeof define !== 'function') {
    var define = require('amdefine')(module);
}
define(['requirejs'], function(requirejs, undefined) {
var suites = [];
suites.push({
    name: "videos module",
    desc: "collections of tests for the videos.js module",
    setup: function(env) {
        env.presets = {};
        // a sample data set which should properly represet the way remoteStorage
        // data is stored.
        env.remoteStorage = new this.Stub.mock.remoteStorage({
            '12345': {
                'title': 'lolcats',
                'description': 'lolcat video compilation',
                'embed_url': 'http://youtube.com/yasysy.swf',
                'thumbnail': 'http://youtube.com/yasysy.png',
                'duration': 192,
                'vid_id': 'yasysy',
                'visit_url': 'http://youtube.com/watch?v=yasysy',
                'source': 'youtube'
            },
            'abcde': {
                'title': 'cars',
                'description': 'cars are magic',
                'embed_url': 'http://youtube.com/hayehs.swf',
                'thumbnail': 'http://youtube.com/hayehs.png',
                'duration': 251,
                'vid_id': 'hayehs',
                'visit_url': 'http://youtube.com/watch?v=hayehs',
                'source': 'youtube'
            }
        });

        this.assertTypeAnd(env.remoteStorage, 'function');
        this.assertTypeAnd(env.remoteStorage.baseClient, 'function');
        this.assertType(env.remoteStorage.defineModule, 'function');

        global.remoteStorage = env.remoteStorage;
        var moduleImport = requirejs('./js/rs_modules/videos.js');
        // if we loaded the tag module correctly, it should have returned
        // a function for us to use.
        console.log(env.moduleImport);
        this.assertTypeAnd(env.moduleImport, 'function');
        env.vidModule = moduleImport[1](env.remoteStorage.baseClient, env.remoteStorage.baseClient).exports;
        this.assertType(env.vidModule, 'object');
    },
    tests: [
        {
            desc: "vid module has getIds function",
            run: function(env) {
                this.assertType(env.vidModule.getIds, 'function');
            }
        },
        {
            desc: "getIds should return our preset list of video ids",
            run: function(env) {
                var d = env.vidModule.getIds();
                var should_be = ['12345', 'abcde'];
                this.assert(d, should_be);
            }
        },
        {
            desc: "get should return an object",
            run: function(env) {
                var d = env.vidModule.get('12345');
                var should_be = {
                    'title': 'lolcats',
                    'description': 'lolcat video compilation',
                    'embed_url': 'http://youtube.com/yasysy.swf',
                    'thumbnail': 'http://youtube.com/yasysy.png',
                    'duration': 192,
                    'vid_id': 'yasysy',
                    'visit_url': 'http://youtube.com/watch?v=yasysy',
                    'source': 'youtube'
                };
                this.assert(d, should_be);
            }
        },
        {
            desc: "add should add a new record",
            run: function(env) {
                var new_record = {
                    'title': 'dogs and bacon',
                    'description': 'dogs love bacon',
                    'embed_url': 'http://youtube.com/098765.swf',
                    'thumbnail': 'http://youtube.com/098765.png',
                    'duration': 781,
                    'vid_id': '098765',
                    'visit_url': 'http://youtube.com/watch?v=098765',
                    'source': 'youtube'
                };
                var id = env.vidModule.add(new_record, '098765');

                var retrieve = env.vidModule.get('098765');
                this.assert(new_record, retrieve);
            }
        },
        {
            desc: "lets add a record with an invalid schema",
            willFail: true,
            run: function(env) {
                var new_record = {
                    'title': 'dogs and bacon',
                    'description': 'dogs love bacon',
                    'embed_url': 'http://youtube.com/098765.swf',
                    'thumbnail': 'http://youtube.com/098765.png',
                    'duration': "781", // should be a number
                    'vid_id': '098765',
                    'visit_url': 'http://youtube.com/watch?v=098765',
                    'source': 'youtube'
                };

                env.vidModule.on('error', function(err) {
                    console.log('DB ERROR: videos (teste) - '+err);
                });

                var id = env.vidModule.add(new_record, '098765');

                var retrieve = env.vidModule.get('098765');
                this.assert(new_record, retrieve);
            }
        }
    ],
    takedown: function(env) {
        delete global.remoteStorage;
        env.vidModule.on('error', function(err) {});
        this.result(true);
    }
});

suites.push({
    name: "test global namespace reset",
    desc: "the global namespace should no longer have remoteStorage in it",
    tests: [
        {
            desc: "make sure the global namespace doesn't have remoteStorage anymore",
            run: function(env) {
                this.assertType(global.remoteStorage, 'undefined');
            }
        }
    ]
});
return suites;
});
<commit_msg>updated suite, tests now pass<commit_after>if (typeof define !== 'function') {
  var define = require('amdefine')(module);
}
define(['requirejs'], function(requirejs, undefined) {
var suites = [];
suites.push({
  name: "videos module",
  desc: "collections of tests for the videos.js module",
  setup: function(env) {
    env.presets = {};
    // a sample data set which should properly represet the way remoteStorage
    // data is stored.
    env.remoteStorage = new this.Stub.mock.remoteStorage({
      '12345': {
        'title': 'lolcats',
        'description': 'lolcat video compilation',
        'embed_url': 'http://youtube.com/yasysy.swf',
        'thumbnail': 'http://youtube.com/yasysy.png',
        'duration': 192,
        'vid_id': 'yasysy',
        'visit_url': 'http://youtube.com/watch?v=yasysy',
        'source': 'youtube',
        'content_type': 'application/x-shockwave-flash'
      },
      'abcde': {
        'title': 'cars',
        'description': 'cars are magic',
        'embed_url': 'http://youtube.com/hayehs.swf',
        'thumbnail': 'http://youtube.com/hayehs.png',
        'duration': 251,
        'vid_id': 'hayehs',
        'visit_url': 'http://youtube.com/watch?v=hayehs',
        'source': 'youtube',
        'content_type': 'application/x-shockwave-flash'
      }
    });

    this.assertTypeAnd(env.remoteStorage, 'function');
    this.assertTypeAnd(env.remoteStorage.baseClient, 'function');
    this.assertType(env.remoteStorage.defineModule, 'function');

    global.remoteStorage = env.remoteStorage;
    var moduleImport = requirejs('./js/rs_modules/videos.js');
    // if we loaded the tag module correctly, it should have returned
    // a function for us to use.
    console.log(env.moduleImport);
    this.assertTypeAnd(env.moduleImport, 'function');
    env.vidModule = moduleImport[1](env.remoteStorage.baseClient, env.remoteStorage.baseClient).exports;
    this.assertType(env.vidModule, 'object');
  },
  tests: [
    {
      desc: "vid module has getIds function",
      run: function(env) {
        this.assertType(env.vidModule.getIds, 'function');
      }
    },
    {
      desc: "getIds should return our preset list of video ids",
      run: function(env) {
        var d = env.vidModule.getIds();
        var should_be = ['12345', 'abcde'];
        this.assert(d, should_be);
      }
    },
    {
      desc: "get should return an object",
      run: function(env) {
        var d = env.vidModule.get('12345');
        var should_be = {
          'title': 'lolcats',
          'description': 'lolcat video compilation',
          'embed_url': 'http://youtube.com/yasysy.swf',
          'thumbnail': 'http://youtube.com/yasysy.png',
          'duration': 192,
          'vid_id': 'yasysy',
          'visit_url': 'http://youtube.com/watch?v=yasysy',
          'source': 'youtube',
          'content_type': 'application/x-shockwave-flash'
        };
        this.assert(d, should_be);
      }
    },
    {
      desc: "add should add a new record",
      run: function(env) {
        var new_record = {
          'title': 'dogs and bacon',
          'description': 'dogs love bacon',
          'embed_url': 'http://youtube.com/098765.swf',
          'thumbnail': 'http://youtube.com/098765.png',
          'duration': 781,
          'vid_id': '098765a',
          'visit_url': 'http://youtube.com/watch?v=098765',
          'source': 'youtube',
          'content_type': 'application/x-shockwave-flash'
        };
        env.vidModule.on('error', function(err) {
          console.log('DB ERROR: videos (teste) - ',err);
        });
        var id = env.vidModule.add(new_record, '098765a');

        var retrieve = env.vidModule.get('098765a');
        this.assert(new_record, retrieve);
      }
    },
    {
      desc: "lets add a record with an invalid schema",
      willFail: true,
      run: function(env) {
        var new_record = {
          'title': 'dogs and bacon',
          'description': 'dogs love bacon',
          'embed_url': 'http://youtube.com/098765.swf',
          'thumbnail': 'http://youtube.com/098765.png',
          'duration': "781", // should be a number
          'vid_id': '098765',
          'visit_url': 'http://youtube.com/watch?v=098765',
          'source': 'youtube',
          'content_type': 'application/x-shockwave-flash'
        };

        env.vidModule.on('error', function(err) {
          console.log('DB ERROR: videos (teste) - '+err);
        });

        var id = env.vidModule.add(new_record, '098765');

        var retrieve = env.vidModule.get('098765');
        this.assert(new_record, retrieve);
      }
    }
  ],
  takedown: function(env) {
    delete global.remoteStorage;
    env.vidModule.on('error', function(err) {});
    this.result(true);
  }
});

suites.push({
  name: "test global namespace reset",
  desc: "the global namespace should no longer have remoteStorage in it",
  tests: [
    {
      desc: "make sure the global namespace doesn't have remoteStorage anymore",
      run: function(env) {
        this.assertType(global.remoteStorage, 'undefined');
      }
    }
  ]
});
return suites;
});
<|endoftext|>


<commit_before>// need to subtract 2 from source maps
import 'source-map-support/register';

import chai from 'chai';
import fs from 'fs';
import os from 'os';
import path from 'path';
import pngToIcns from './../../lib/pngToIcns';

let assert = chai.assert;

// Prerequisite for test: to use OSX with sips, iconutil and imagemagick convert

function testConvertPng(pngName, done) {
    if (os.platform() !== 'darwin') {
        console.warn('Skipping png conversion tests, OSX is required');
        done();
    }
    pngToIcns(path.join(__dirname, '../../', 'test-resources', pngName), (error, icnsPath) => {
        if (error) {
            done(error);
            return;
        }

        let stat = fs.statSync(icnsPath);
        assert.isTrue(stat.isFile(), 'Output icns file should be a path');
        done();
    });
}

describe('Get Icon Module', function() {
    it('Can convert a rgb png to icns', function(done) {
        testConvertPng('iconSample.png', done);
    });

    it('Can convert a grey png to icns', function(done) {
        testConvertPng('iconSampleGrey.png', done);
    });
});
<commit_msg>Fix test for non darwin platforms<commit_after>// need to subtract 2 from source maps
import 'source-map-support/register';

import chai from 'chai';
import fs from 'fs';
import os from 'os';
import path from 'path';
import pngToIcns from './../../lib/pngToIcns';

let assert = chai.assert;

// Prerequisite for test: to use OSX with sips, iconutil and imagemagick convert

function testConvertPng(pngName, done) {
    pngToIcns(path.join(__dirname, '../../', 'test-resources', pngName), (error, icnsPath) => {
        if (error) {
            done(error);
            return;
        }

        let stat = fs.statSync(icnsPath);
        assert.isTrue(stat.isFile(), 'Output icns file should be a path');
        done();
    });
}

describe('Get Icon Module', function() {
    it('Can convert icons', function() {
        if (os.platform() !== 'darwin') {
            console.warn('Skipping png conversion tests, OSX is required');
            return;
        }

        it('Can convert a rgb png to icns', function(done) {
            testConvertPng('iconSample.png', done);
        });

        it('Can convert a grey png to icns', function(done) {
            testConvertPng('iconSampleGrey.png', done);
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

require('./lib/test-env.js');

// const projectRouter = require('../route/project-router.js');
const projectMock = require('./lib/project-mock.js');
const userMock = require('./lib/user-mock.js');
const cleanUpDB = require('./lib/clean-up-mock.js');

const expect = require('chai').expect;
const request = require('superagent');
const server = require('../server.js');
const serverControl = require('./lib/server-control.js');
const mongoose = require('mongoose');
const Promise = require('bluebird');

const url = `http://localhost:${process.env.PORT}`;

mongoose.Promise = Promise;

const exampleProjectData = {
  name: 'IVSCC',
};

describe('testing project router', function(done) {
  before(done => serverControl.serverUp(server, done));
  after(done => serverControl.serverDown(server, done));
  afterEach(done => cleanUpDB(done));

  describe('testing POST /api/project', function() {
    describe('with valid body', function() {
      before(done => userMock.call(this, done));

      it('should return a project', (done) => {
        request.post(`${url}/api/project`)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .send(exampleProjectData)
        .end((err, res) => {
          if (err) return done(err);
          expect(res.status).to.equal(200);
          done();
        });
        // done();
      }); //end of it should return a project
    }); //end of valid body

    describe('with invalid body', function() {
      before(done => userMock.call(this, done));

      it('should return a 400 bad request', (done) => {
        request.post(`${url}/api/project`)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .send('INVALID')
        .set('Character-Type', 'application/json')
        .end((err, res) => {
          // console.log('THE SECOND ERRORRRRRRRRR', err);
          // if (err) return done(err);
          expect(res.status).to.equal(400);
          done();
        });
      });
    }); //end of describe with invalid body

    describe('with no body', function() {
      before(done => userMock.call(this, done));
      it('should return a 400 bad request', (done) => {

        request.post(`${url}/api/project`)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .send()
        .set('Character-Type', 'application/json')
        .end((err, res) => {
          expect(res.status).to.equal(400);
          done();
        });
      });
    }); //end of describe with no body

    describe('with invalid token', function() {
      before(done => userMock.call(this, done));
      it('should return a 401 unauthorized', (done) => {

        request.post(`${url}/api/project`)
        .set({Authorization: `Bearer badtoken`})
        .send(exampleProjectData)
        .end((err, res) => {
          expect(res.status).to.equal(401);
          done();
        });
      });
    }); //end of describe with invalid token

    describe('with duplicate project name', function() {
      before(done => projectMock.call(this, done));

      it('should return a 409 duplicate error', (done) => {
        request.post(`${url}/api/project`)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .send({
          name: this.tempProject.name,
        })
        .end((err, res) => {
          expect(res.status).to.equal(409);
          done();
        });
      }); //end of it should return 409
      // before(done => userMock.call(this, done));
    });
  }); //end of describe POST

  describe('testing GET /api/project/:id', function() {
    describe('with valid project ID and token', function() {
      before(done => projectMock.call(this, done));

      it('should return a project', (done) => {
        request.get(`${url}/api/project/${this.tempProject._id}`)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .end((err, res) => {
          if (err) return done(err);
          expect(res.status).to.equal(200);
          done();
        });
      }); //end of it should return a project
    }); //end of describe with valid project ID and token

    describe('with valid projectID and invalid token', function() {
      before(done => projectMock.call(this, done));

      it('should return a 401 unauthorized', (done) => {
        request.get(`${url}/api/project/${this.tempProject._id}`)
        .set({Authorization: 'Bearer badtoken'})
        .end((err, res) => {
          expect(res.status).to.equal(401);
          done();
        });
      }); //end of it should return 401
    }); //end of describe with valid id and invalid token

    describe('with invalid projectID and valid token', function() {
      before(done => projectMock.call(this, done));

      it('should return a 404 not found', (done) => {
        request.get(`${url}/api/project/1234`)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .end((err, res) => {
          expect(res.status).to.equal(404);
          done();
        });
      });
    }); //end of describe with invalid
  }); //end of describe GET
});
<commit_msg>POST and GET tests done<commit_after>'use strict';

require('./lib/test-env.js');

// const projectRouter = require('../route/project-router.js');
const projectMock = require('./lib/project-mock.js');
const userMock = require('./lib/user-mock.js');
const cleanUpDB = require('./lib/clean-up-mock.js');

const expect = require('chai').expect;
const request = require('superagent');
const server = require('../server.js');
const serverControl = require('./lib/server-control.js');
const mongoose = require('mongoose');
const Promise = require('bluebird');

const url = `http://localhost:${process.env.PORT}`;

mongoose.Promise = Promise;

const exampleProjectData = {
  name: 'IVSCC',
};

describe('testing project router', function(done) {
  before(done => serverControl.serverUp(server, done));
  after(done => serverControl.serverDown(server, done));
  afterEach(done => cleanUpDB(done));

  describe('testing POST /api/project', function() {
    describe('with valid body', function() {
      before(done => userMock.call(this, done));

      it('should return a project', (done) => {
        request.post(`${url}/api/project`)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .send(exampleProjectData)
        .end((err, res) => {
          if (err) return done(err);
          expect(res.status).to.equal(200);
          done();
        });
        // done();
      }); //end of it should return a project
    }); //end of valid body

    describe('with invalid body', function() {
      before(done => userMock.call(this, done));

      it('should return a 400 bad request', (done) => {
        request.post(`${url}/api/project`)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .send('INVALID')
        .set('Character-Type', 'application/json')
        .end((err, res) => {
          // console.log('THE SECOND ERRORRRRRRRRR', err);
          // if (err) return done(err);
          expect(res.status).to.equal(400);
          done();
        });
      });
    }); //end of describe with invalid body

    describe('with no body', function() {
      before(done => userMock.call(this, done));
      it('should return a 400 bad request', (done) => {

        request.post(`${url}/api/project`)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .send()
        .set('Character-Type', 'application/json')
        .end((err, res) => {
          expect(res.status).to.equal(400);
          done();
        });
      });
    }); //end of describe with no body

    describe('with invalid token', function() {
      before(done => userMock.call(this, done));
      it('should return a 401 unauthorized', (done) => {

        request.post(`${url}/api/project`)
        .set({Authorization: `Bearer badtoken`})
        .send(exampleProjectData)
        .end((err, res) => {
          expect(res.status).to.equal(401);
          done();
        });
      });
    }); //end of describe with invalid token

    describe('with duplicate project name', function() {
      before(done => projectMock.call(this, done));

      it('should return a 409 duplicate error', (done) => {
        request.post(`${url}/api/project`)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .send({
          name: this.tempProject.name,
        })
        .end((err, res) => {
          expect(res.status).to.equal(409);
          done();
        });
      }); //end of it should return 409
      // before(done => userMock.call(this, done));
    });
  }); //end of describe POST

  describe('testing GET /api/project/:id', function() {
    describe('with valid project ID and token', function() {
      before(done => projectMock.call(this, done));

      it('should return a project', (done) => {
        request.get(`${url}/api/project/${this.tempProject._id}`)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .end((err, res) => {
          if (err) return done(err);
          expect(res.status).to.equal(200);
          done();
        });
      }); //end of it should return a project
    }); //end of describe with valid project ID and token

    describe('with valid projectID and invalid token', function() {
      before(done => projectMock.call(this, done));

      it('should return a 401 unauthorized', (done) => {
        request.get(`${url}/api/project/${this.tempProject._id}`)
        .set({Authorization: 'Bearer badtoken'})
        .end((err, res) => {
          expect(res.status).to.equal(401);
          done();
        });
      }); //end of it should return 401
    }); //end of describe with valid id and invalid token

    describe('with invalid projectID and valid token', function() {
      before(done => projectMock.call(this, done));

      it('should return a 404 not found', (done) => {
        request.get(`${url}/api/project/1234`)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .end((err, res) => {
          expect(res.status).to.equal(404);
          done();
        });
      }); //end of it should return 404 not found
    }); //end of describe with invalid

    describe('with no header', function() {
      before(done => projectMock.call(this, done));

      it('should return a 401 unauthorized error', (done) => {
        request.get(`${url}/api/project/${this.tempProject._id}`)
        .end((err, res) => {
          expect(res.status).to.equal(401);
          done();
        });
      });
    }); //end of describe with no header
  }); //end of describe GET

  describe('testing DELETE /api/project/:id', function() {
    before(done => project)
  }); //end of describe DELETE
});
<|endoftext|>


<commit_before>// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import * as React from 'react';
import {BuilderDataTable} from './BuilderDataTable';
import {BuilderGrid} from './BuilderGrid';
import toggleIcon from './resources/play.svg';

/**
 * Component used to render Build Information.
 *
 * @param {Object[]} props.buildData - Aggregated data on latest commit build.
 * @param {string} props.buildData[].description - Commit message.
 * @param {Object[]} props.buildData[].builders - Bots that built this commit.
 * @param {string} props.buildData[].commitHash - Commit hash.
 * @param {string} props.buildData[].repository - URL to the GitHub repository.
 * @param {string} props.buildData[].status - The status of the build.
 * @param {string} props.buildData[].timestamp - Timestamp of commit push.
 */
export const BuildSnapshot = (props) => {
  // State variable indicating whether the BuildSnapshot is open or closed.
  // isOpen === true indicates the tray should be visible
  // and the indicator arrow on the Header should be facing downwards.
  const [isOpen, setIsOpen] = React.useState(false);

  const {builders, commitHash, description,
      repository, status, timestamp} = props.buildData;

  const headerData = {commitHash, description, repository, status};
  const trayData = {builders, timestamp};

  return (

      <Tray isOpen={isOpen} data={trayData}/>

  );
}

/**
 * Subcomponent that holds the content displayed
 * when the BuildSnapshot is collapsed.
 *
 * @param {boolean} props.isOpen - Indicates if the Tray should be open.
 * @param {Object} onClick - A callback function responsible
 * for toggling the visibility of the Tray via the onClick event.
 * @param {Object} props.data - Build information to be displayed on Header.
 * @param {string} props.data[].description - The commit message.
 * @param {string} props.data[].commitHash - The commit hash.
 * @param {string} props.data[].repository - URL to the GitHub repository.
 * @param {string} props.data[].status - The status of the build.
 */
const Header = (props) => {
  let headerClassName = 'snapshot-header';
  if (props.isOpen === true) {
    headerClassName = 'snapshot-header active';
  }

  return (

 props.onClick(!props.isOpen)}>

      {props.data.commitHash}
      {props.data.description}
      Group
      {props.data.status}

  );
}

/**
 * Subcomponent that holds the content revealed
 * when the BuildSnapshot is open (props.isOpen === true).
 *
 * @param {boolean} props.isOpen - Indicates if the Tray should be open.
 * @param {Object[]} props.data.builders - Bots that built this commit.
 * @param {string} props.data.builders[].name - The name of the given build bot.
 * @param {string} props.data.timestamp - The timestamp of the given build bot.
 */
const Tray = (props) => {
  // State variable indicating the builder whose data
  // should be rendered to the BuilderDataTable.
  // Represents the index of the builder in props.data.builders
  const [selectedBuilder, selectBuilder] = React.useState(0);
  const builder = props.data.builders[selectedBuilder];

  if (props.isOpen !== true) { return null };
  return (

      {props.data.timestamp}

        {builder.name}

      <BuilderGrid onClick={selectBuilder} builders={props.data.builders}/>
      <BuilderDataTable buildSteps={builder.buildSteps}/>

  );
}
<commit_msg>Check if builder is undefined before accessing buildername<commit_after>// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import * as React from 'react';
import {BuilderDataTable} from './BuilderDataTable';
import {BuilderGrid} from './BuilderGrid';
import toggleIcon from './resources/play.svg';

/**
 * Component used to render Build Information.
 *
 * @param {Object[]} props.buildData - Aggregated data on latest commit build.
 * @param {string} props.buildData[].description - Commit message.
 * @param {Object[]} props.buildData[].builders - Bots that built this commit.
 * @param {string} props.buildData[].commitHash - Commit hash.
 * @param {string} props.buildData[].repository - URL to the GitHub repository.
 * @param {string} props.buildData[].status - The status of the build.
 * @param {string} props.buildData[].timestamp - Timestamp of commit push.
 */
export const BuildSnapshot = (props) => {
  // State variable indicating whether the BuildSnapshot is open or closed.
  // isOpen === true indicates the tray should be visible
  // and the indicator arrow on the Header should be facing downwards.
  const [isOpen, setIsOpen] = React.useState(false);

  const {builders, commitHash, description,
      repository, status, timestamp} = props.buildData;

  const headerData = {commitHash, description, repository, status};
  const trayData = {builders, timestamp};

  return (

      <Tray isOpen={isOpen} data={trayData}/>

  );
}

/**
 * Subcomponent that holds the content displayed
 * when the BuildSnapshot is collapsed.
 *
 * @param {boolean} props.isOpen - Indicates if the Tray should be open.
 * @param {Object} onClick - A callback function responsible
 * for toggling the visibility of the Tray via the onClick event.
 * @param {Object} props.data - Build information to be displayed on Header.
 * @param {string} props.data[].description - The commit message.
 * @param {string} props.data[].commitHash - The commit hash.
 * @param {string} props.data[].repository - URL to the GitHub repository.
 * @param {string} props.data[].status - The status of the build.
 */
const Header = (props) => {
  let headerClassName = 'snapshot-header';
  if (props.isOpen === true) {
    headerClassName = 'snapshot-header active';
  }

  return (

 props.onClick(!props.isOpen)}>

      {props.data.commitHash}
      {props.data.description}
      Group
      {props.data.status}

  );
}

/**
 * Subcomponent that holds the content revealed
 * when the BuildSnapshot is open (props.isOpen === true).
 *
 * @param {boolean} props.isOpen - Indicates if the Tray should be open.
 * @param {Object[]} props.data.builders - Bots that built this commit.
 * @param {string} props.data.builders[].name - The name of the given build bot.
 * @param {string} props.data.timestamp - The timestamp of the given build bot.
 */
const Tray = (props) => {
  // State variable indicating the builder whose data
  // should be rendered to the BuilderDataTable.
  // Represents the index of the builder in props.data.builders
  const [selectedBuilder, selectBuilder] = React.useState(0);
  const builder = props.data.builders[selectedBuilder];

  let builderName = "";
  if (builder !== undefined) {
    builderName = builder.name;
  }

  if (props.isOpen !== true) { return null };
  return (

      {props.data.timestamp}

        {builderName}

      <BuilderGrid onClick={selectBuilder} builders={props.data.builders}/>
      <BuilderDataTable buildSteps={builder.buildSteps}/>

  );
}
<|endoftext|>


<commit_before>import HotReloader from './hot-reloader.js';
new HotReloader('http://localhost:5776');<commit_msg>standard style<commit_after>import HotReloader from './hot-reloader.js'
HotReloader('http://localhost:5776')<|endoftext|>