<commit_before>// import

var assert = require('assert'),
  synaptic = require('../src/synaptic');

var Perceptron = synaptic.Architect.Perceptron,
  LSTM = synaptic.Architect.LSTM,
  Layer = synaptic.Layer,
  Network = synaptic.Network,
  Trainer = synaptic.Trainer;

// utils

var noRepeat = function(range, avoid) {
  var number = Math.random() * range | 0;
  var used = false;
  for (var i in avoid)
    if (number == avoid[i])
      used = true;
  return used ? noRepeat(range, avoid) : number;
};

var equal = function(prediction, output) {
  for (var i in prediction)
    if (Math.round(prediction[i]) != output[i])
      return false;
  return true;
};

var generateRandomArray = function(size){
    var array = [];
    for (var j = 0; j < size; j++)
        array.push(Math.random() + .5 | 0);
    return array;
}

// specs

describe('Basic Neural Network', function() {

  it("trains an AND gate", function() {

    var inputLayer = new Layer(2),
        outputLayer = new Layer(1);

    inputLayer.project(outputLayer);

    var network = new Network({
      input: inputLayer,
      output: outputLayer
    });

    var trainer = new Trainer(network);

    var trainingSet = [{
      input: [0, 0],
      output: [0]
    }, {
      input: [0, 1],
      output: [0]
    }, {
      input: [1, 0],
      output: [0]
    }, {
      input: [1, 1],
      output: [1]
    }];

    trainer.train(trainingSet, {
      iterations: 1000,
      error: .001
    });

    var test00 = Math.round(network.activate([0, 0]));
    assert.equal(test00, 0, "[0,0] did not output 0");

    var test01 = Math.round(network.activate([0, 1]));
    assert.equal(test01, 0, "[0,1] did not output 0");

    var test10 = Math.round(network.activate([0, 1]));
    assert.equal(test10, 0, "[1,0] did not output 0");

    var test11 = Math.round(network.activate([1, 1]));
    assert.equal(test11, 1, "[1,1] did not output 1");
  });

  it("trains an OR gate", function() {

    var inputLayer = new Layer(2),
      outputLayer = new Layer(1);

    inputLayer.project(outputLayer);

    var network = new Network({
      input: inputLayer,
      output: outputLayer
    });

    var trainer = new Trainer(network);

    var trainingSet = [{
      input: [0, 0],
      output: [0]
    }, {
      input: [0, 1],
      output: [1]
    }, {
      input: [1, 0],
      output: [1]
    }, {
      input: [1, 1],
      output: [1]
    }];

    trainer.train(trainingSet, {
      iterations: 1000,
      error: .001
    });

    var test00 = Math.round(network.activate([0, 0]));
    assert.equal(test00, 0, "[0,0] did not output 0");

    var test01 = Math.round(network.activate([0, 1]));
    assert.equal(test01, 1, "[0,1] did not output 1");

    var test10 = Math.round(network.activate([0, 1]));
    assert.equal(test10, 1, "[1,0] did not output 1");

    var test11 = Math.round(network.activate([1, 1]));
    assert.equal(test11, 1, "[1,1] did not output 1");
  });

  it("trains a NOT gate", function() {

    var inputLayer = new Layer(1),
      outputLayer = new Layer(1),
      network;

    inputLayer.project(outputLayer);

    var network = new Network({
      input: inputLayer,
      output: outputLayer
    });

    var trainer = new Trainer(network);
    var trainingSet = [{
      input: [0],
      output: [1]
    }, {
      input: [1],
      output: [0]
    }];

    trainer.train(trainingSet, {
      iterations: 1000,
      error: .001
    });

    var test0 = Math.round(network.activate([0]));
    assert.equal(test0, 1, "0 did not output 1");

    var test1 = Math.round(network.activate([1]));
    assert.equal(test1, 0, "1 did not output 0");
  });
});

describe("Perceptron - XOR", function() {

  var perceptron = new Perceptron(2, 3, 1);
  perceptron.trainer.XOR();

  var test00 = Math.round(perceptron.activate([0, 0]));
  it("input: [0,0] output: " + test00, function() {

    assert.equal(test00, 0, "[0,0] did not output 0");
  });

  var test01 = Math.round(perceptron.activate([0, 1]));
  it("input: [0,1] output: " + test01, function() {

    assert.equal(test01, 1, "[0,1] did not output 1");
  });

  var test10 = Math.round(perceptron.activate([1, 0]));
  it("input: [1,0] output: " + test10, function() {

    assert.equal(test10, 1, "[1,0] did not output 1");
  });

  var test11 = Math.round(perceptron.activate([1, 1]));
  it("input: [1,1] output: " + test11, function() {

    assert.equal(test11, 0, "[1,1] did not output 0");
  });
});

describe("LSTM - Discrete Sequence Recall", function() {

  var targets = [2, 4];
  var distractors = [3, 5];
  var prompts = [0, 1];
  var length = 9;

  var lstm = new LSTM(5, 3, 2);
  lstm.trainer.DSR({
    targets: targets,
    distractors: distractors,
    prompts: prompts,
    length: length,
    rate: .17,
    iterations: 250000
  });

  var symbols = targets.length + distractors.length + prompts.length;
  var sequence = [],
    indexes = [],
    positions = [];
  var sequenceLength = length - prompts.length;

  for (i = 0; i < sequenceLength; i++) {
    var any = Math.random() * distractors.length | 0;
    sequence.push(distractors[any]);
  }
  indexes = [], positions = [];
  for (i = 0; i < prompts.length; i++) {
    indexes.push(Math.random() * targets.length | 0);
    positions.push(noRepeat(sequenceLength, positions));
  }
  positions = positions.sort();
  for (i = 0; i < prompts.length; i++) {
    sequence[positions[i]] = targets[indexes[i]];
    sequence.push(prompts[i]);
  }

  var check = function(which) {
    // generate input from sequence
    var input = [];
    for (j = 0; j < symbols; j++)
      input[j] = 0;
    input[sequence[which]] = 1;

    // generate target output
    var output = [];
    for (j = 0; j < targets.length; j++)
      output[j] = 0;

    if (which >= sequenceLength) {
      var index = which - sequenceLength;
      output[indexes[index]] = 1;
    }

    // check result
    var prediction = lstm.activate(input);
    return {
      prediction: prediction,
      output: output
    };
  };

  var value = function(array) {
    var max = .5;
    var res = -1;
    for (var i in array)
      if (array[i] > max) {
        max = array[i];
        res = i;
      }
    return res == -1 ? '-' : targets[res];
  };

  it("targets: " + targets, function() {
    assert(true);
  });
  it("distractors: " + distractors, function() {
    assert(true);
  });
  it("prompts: " + prompts, function() {
    assert(true);
  });
  it("length: " + length + "\n", function() {
    assert(true);
  });

  for (var i = 0; i < length; i++) {
    var test = check(i);
    it((i + 1) + ") input: " + sequence[i] + " output: " + value(test.prediction),
      function() {
        var ok = equal(test.prediction, test.output);
        assert(ok);
      });
  }
});

describe("Optimized and Unoptimized Networks Equivalency", function() {
  var optimized = new Perceptron(10,15,5);

  var unoptimized = optimized.clone();
  unoptimized.setOptimize(false);

  var learningRate = .5;
  var iterations = 1000;

  for (var i = 1; i <= iterations; i++)
  {
      //random input
      var input = generateRandomArray(10);

      // activate networks
      var output1 = optimized.activate(input);
      var output2 = unoptimized.activate(input);

      if (i % 100 == 0)
        it(' same output for both networks after ' + i + ' iterations', function(){
          var diff = false;
          for (var k in output1)
            if (output1[k] - output2[k] != 0)
              diff = true;
          assert(!diff);
        });

      // random target
      var target = generateRandomArray(5);

      // propagate networks
      optimized.propagate(learningRate, target);
      unoptimized.propagate(learningRate, target);
  }
});

describe("toJSON/fromJSON Networks Equivalency", function() {
  var original = new Perceptron(10,15,5);

  var exported = original.toJSON();
  var imported = Network.fromJSON(exported);

  var learningRate = .5;
  var iterations = 1000;

  for (var i = 1; i <= iterations; i++)
  {
      //random input
      var input = generateRandomArray(10);

      // activate networks
      var output1 = original.activate(input);
      var output2 = imported.activate(input);

      if (i % 100 == 0)
        it(' same output for both networks after ' + i + ' iterations', function(){
          var diff = false;
          for (var k in output1)
            if (output1[k] - output2[k] != 0)
              diff = true;
          assert(!diff);
        });

      // random target
      var target = generateRandomArray(5);

      // propagate networks
      original.propagate(learningRate, target);
      imported.propagate(learningRate, target);
  }
});

describe("Cloned Networks Equivalency", function() {
  var original = new Perceptron(10,15,5);
  var cloned = original.clone();

  var learningRate = .5;
  var iterations = 1000;

  for (var i = 1; i <= iterations; i++)
  {
      //random input
      var input = generateRandomArray(10);

      // activate networks
      var output1 = original.activate(input);
      var output2 = cloned.activate(input);

      if (i % 100 == 0)
        it(' same output for both networks after ' + i + ' iterations', function(){
          var diff = false;
          for (var k in output1)
            if (output1[k] - output2[k] != 0)
              diff = true;
          assert(!diff);
        });

      // random target
      var target = generateRandomArray(5);

      // propagate networks
      original.propagate(learningRate, target);
      cloned.propagate(learningRate, target);
  }
});

describe("Manual Override", function() {
  var perceptron = new Perceptron(2, 3, 1);

  it('iterations ended at full 3000', function(){
    var final_stats = perceptron.trainer.XOR({
      iterations: 3000,
      rate: 0.000001,
      error: 0.000001,
      schedule: {
          every: 1000,
          do: function(data) {
            if( data.iterations == 20000){
              return true
            }
          }
        }
    });
    assert.equal( final_stats.iterations, 3000 )
  });

  it('iterations ended at 2000, not full 3000', function(){
    var final_stats = perceptron.trainer.XOR({
      iterations: 3000,
      rate: 0.000001,
      error: 0.000001,
      schedule: {
          every: 1000,
          do: function(data) {
            if( data.iterations == 2000){
              return true
            }
          }
        }
    });
    assert.equal( final_stats.iterations, 2000 )
  });

  it('training works even when schedule() has no return value', function(){
    var final_stats = perceptron.trainer.XOR({
      iterations: 3000,
      rate: 0.000001,
      error: 0.000001,
      schedule: {
          every: 1000,
          do: function(data) {}
        }
    });
    assert.equal( final_stats.iterations, 3000 )
  });

  it('using depreciated customLog still works', function(){
    var counter = 0
    var final_stats = perceptron.trainer.XOR({
      iterations: 3000,
      rate: 0.000001,
      error: 0.000001,
      customLog: {
          every: 1000,
          do: function(data) { counter++ }
        }
    });
    assert.equal( counter, 3 )
  });

});
<commit_msg>Update synaptic.js<commit_after>// import

var assert = require('assert'),
  synaptic = require('../src/synaptic');

var Perceptron = synaptic.Architect.Perceptron,
  LSTM = synaptic.Architect.LSTM,
  Layer = synaptic.Layer,
  Network = synaptic.Network,
  Trainer = synaptic.Trainer;

// utils

var noRepeat = function(range, avoid) {
  var number = Math.random() * range | 0;
  for (var i in avoid){
    if (number == avoid[i]){
      return noRepeat(range,avoid);
    }
  }
  return number;
};

var equal = function(prediction, output) {
  for (var i in prediction)
    if (Math.round(prediction[i]) != output[i])
      return false;
  return true;
};

var generateRandomArray = function(size){
    var array = [];
    for (var j = 0; j < size; j++)
        array.push(Math.random() + .5 | 0);
    return array;
}

// specs

describe('Basic Neural Network', function() {

  it("trains an AND gate", function() {

    var inputLayer = new Layer(2),
        outputLayer = new Layer(1);

    inputLayer.project(outputLayer);

    var network = new Network({
      input: inputLayer,
      output: outputLayer
    });

    var trainer = new Trainer(network);

    var trainingSet = [{
      input: [0, 0],
      output: [0]
    }, {
      input: [0, 1],
      output: [0]
    }, {
      input: [1, 0],
      output: [0]
    }, {
      input: [1, 1],
      output: [1]
    }];

    trainer.train(trainingSet, {
      iterations: 1000,
      error: .001
    });

    var test00 = Math.round(network.activate([0, 0]));
    assert.equal(test00, 0, "[0,0] did not output 0");

    var test01 = Math.round(network.activate([0, 1]));
    assert.equal(test01, 0, "[0,1] did not output 0");

    var test10 = Math.round(network.activate([0, 1]));
    assert.equal(test10, 0, "[1,0] did not output 0");

    var test11 = Math.round(network.activate([1, 1]));
    assert.equal(test11, 1, "[1,1] did not output 1");
  });

  it("trains an OR gate", function() {

    var inputLayer = new Layer(2),
      outputLayer = new Layer(1);

    inputLayer.project(outputLayer);

    var network = new Network({
      input: inputLayer,
      output: outputLayer
    });

    var trainer = new Trainer(network);

    var trainingSet = [{
      input: [0, 0],
      output: [0]
    }, {
      input: [0, 1],
      output: [1]
    }, {
      input: [1, 0],
      output: [1]
    }, {
      input: [1, 1],
      output: [1]
    }];

    trainer.train(trainingSet, {
      iterations: 1000,
      error: .001
    });

    var test00 = Math.round(network.activate([0, 0]));
    assert.equal(test00, 0, "[0,0] did not output 0");

    var test01 = Math.round(network.activate([0, 1]));
    assert.equal(test01, 1, "[0,1] did not output 1");

    var test10 = Math.round(network.activate([0, 1]));
    assert.equal(test10, 1, "[1,0] did not output 1");

    var test11 = Math.round(network.activate([1, 1]));
    assert.equal(test11, 1, "[1,1] did not output 1");
  });

  it("trains a NOT gate", function() {

    var inputLayer = new Layer(1),
      outputLayer = new Layer(1),
      network;

    inputLayer.project(outputLayer);

    var network = new Network({
      input: inputLayer,
      output: outputLayer
    });

    var trainer = new Trainer(network);
    var trainingSet = [{
      input: [0],
      output: [1]
    }, {
      input: [1],
      output: [0]
    }];

    trainer.train(trainingSet, {
      iterations: 1000,
      error: .001
    });

    var test0 = Math.round(network.activate([0]));
    assert.equal(test0, 1, "0 did not output 1");

    var test1 = Math.round(network.activate([1]));
    assert.equal(test1, 0, "1 did not output 0");
  });
});

describe("Perceptron - XOR", function() {

  var perceptron = new Perceptron(2, 3, 1);
  perceptron.trainer.XOR();

  var test00 = Math.round(perceptron.activate([0, 0]));
  it("input: [0,0] output: " + test00, function() {

    assert.equal(test00, 0, "[0,0] did not output 0");
  });

  var test01 = Math.round(perceptron.activate([0, 1]));
  it("input: [0,1] output: " + test01, function() {

    assert.equal(test01, 1, "[0,1] did not output 1");
  });

  var test10 = Math.round(perceptron.activate([1, 0]));
  it("input: [1,0] output: " + test10, function() {

    assert.equal(test10, 1, "[1,0] did not output 1");
  });

  var test11 = Math.round(perceptron.activate([1, 1]));
  it("input: [1,1] output: " + test11, function() {

    assert.equal(test11, 0, "[1,1] did not output 0");
  });
});

describe("LSTM - Discrete Sequence Recall", function() {

  var targets = [2, 4];
  var distractors = [3, 5];
  var prompts = [0, 1];
  var length = 9;

  var lstm = new LSTM(5, 3, 2);
  lstm.trainer.DSR({
    targets: targets,
    distractors: distractors,
    prompts: prompts,
    length: length,
    rate: .17,
    iterations: 250000
  });

  var symbols = targets.length + distractors.length + prompts.length;
  var sequence = [],
    indexes = [],
    positions = [];
  var sequenceLength = length - prompts.length;

  for (i = 0; i < sequenceLength; i++) {
    var any = Math.random() * distractors.length | 0;
    sequence.push(distractors[any]);
  }
  indexes = [], positions = [];
  for (i = 0; i < prompts.length; i++) {
    indexes.push(Math.random() * targets.length | 0);
    positions.push(noRepeat(sequenceLength, positions));
  }
  positions = positions.sort();
  for (i = 0; i < prompts.length; i++) {
    sequence[positions[i]] = targets[indexes[i]];
    sequence.push(prompts[i]);
  }

  var check = function(which) {
    // generate input from sequence
    var input = [];
    for (j = 0; j < symbols; j++)
      input[j] = 0;
    input[sequence[which]] = 1;

    // generate target output
    var output = [];
    for (j = 0; j < targets.length; j++)
      output[j] = 0;

    if (which >= sequenceLength) {
      var index = which - sequenceLength;
      output[indexes[index]] = 1;
    }

    // check result
    var prediction = lstm.activate(input);
    return {
      prediction: prediction,
      output: output
    };
  };

  var value = function(array) {
    var max = .5;
    var res = -1;
    for (var i in array)
      if (array[i] > max) {
        max = array[i];
        res = i;
      }
    return res == -1 ? '-' : targets[res];
  };

  it("targets: " + targets, function() {
    assert(true);
  });
  it("distractors: " + distractors, function() {
    assert(true);
  });
  it("prompts: " + prompts, function() {
    assert(true);
  });
  it("length: " + length + "\n", function() {
    assert(true);
  });

  for (var i = 0; i < length; i++) {
    var test = check(i);
    it((i + 1) + ") input: " + sequence[i] + " output: " + value(test.prediction),
      function() {
        var ok = equal(test.prediction, test.output);
        assert(ok);
      });
  }
});

describe("Optimized and Unoptimized Networks Equivalency", function() {
  var optimized = new Perceptron(10,15,5);

  var unoptimized = optimized.clone();
  unoptimized.setOptimize(false);

  var learningRate = .5;
  var iterations = 1000;

  for (var i = 1; i <= iterations; i++)
  {
      //random input
      var input = generateRandomArray(10);

      // activate networks
      var output1 = optimized.activate(input);
      var output2 = unoptimized.activate(input);

      if (i % 100 == 0)
        it(' same output for both networks after ' + i + ' iterations', function(){
          var diff = false;
          for (var k in output1)
            if (output1[k] - output2[k] != 0)
              diff = true;
          assert(!diff);
        });

      // random target
      var target = generateRandomArray(5);

      // propagate networks
      optimized.propagate(learningRate, target);
      unoptimized.propagate(learningRate, target);
  }
});

describe("toJSON/fromJSON Networks Equivalency", function() {
  var original = new Perceptron(10,15,5);

  var exported = original.toJSON();
  var imported = Network.fromJSON(exported);

  var learningRate = .5;
  var iterations = 1000;

  for (var i = 1; i <= iterations; i++)
  {
      //random input
      var input = generateRandomArray(10);

      // activate networks
      var output1 = original.activate(input);
      var output2 = imported.activate(input);

      if (i % 100 == 0)
        it(' same output for both networks after ' + i + ' iterations', function(){
          var diff = false;
          for (var k in output1)
            if (output1[k] - output2[k] != 0)
              diff = true;
          assert(!diff);
        });

      // random target
      var target = generateRandomArray(5);

      // propagate networks
      original.propagate(learningRate, target);
      imported.propagate(learningRate, target);
  }
});

describe("Cloned Networks Equivalency", function() {
  var original = new Perceptron(10,15,5);
  var cloned = original.clone();

  var learningRate = .5;
  var iterations = 1000;

  for (var i = 1; i <= iterations; i++)
  {
      //random input
      var input = generateRandomArray(10);

      // activate networks
      var output1 = original.activate(input);
      var output2 = cloned.activate(input);

      if (i % 100 == 0)
        it(' same output for both networks after ' + i + ' iterations', function(){
          var diff = false;
          for (var k in output1)
            if (output1[k] - output2[k] != 0)
              diff = true;
          assert(!diff);
        });

      // random target
      var target = generateRandomArray(5);

      // propagate networks
      original.propagate(learningRate, target);
      cloned.propagate(learningRate, target);
  }
});

describe("Manual Override", function() {
  var perceptron = new Perceptron(2, 3, 1);

  it('iterations ended at full 3000', function(){
    var final_stats = perceptron.trainer.XOR({
      iterations: 3000,
      rate: 0.000001,
      error: 0.000001,
      schedule: {
          every: 1000,
          do: function(data) {
            if( data.iterations == 20000){
              return true
            }
          }
        }
    });
    assert.equal( final_stats.iterations, 3000 )
  });

  it('iterations ended at 2000, not full 3000', function(){
    var final_stats = perceptron.trainer.XOR({
      iterations: 3000,
      rate: 0.000001,
      error: 0.000001,
      schedule: {
          every: 1000,
          do: function(data) {
            if( data.iterations == 2000){
              return true
            }
          }
        }
    });
    assert.equal( final_stats.iterations, 2000 )
  });

  it('training works even when schedule() has no return value', function(){
    var final_stats = perceptron.trainer.XOR({
      iterations: 3000,
      rate: 0.000001,
      error: 0.000001,
      schedule: {
          every: 1000,
          do: function(data) {}
        }
    });
    assert.equal( final_stats.iterations, 3000 )
  });

  it('using depreciated customLog still works', function(){
    var counter = 0
    var final_stats = perceptron.trainer.XOR({
      iterations: 3000,
      rate: 0.000001,
      error: 0.000001,
      customLog: {
          every: 1000,
          do: function(data) { counter++ }
        }
    });
    assert.equal( counter, 3 )
  });

});
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var appdmg = require('appdmg');
var chalk = require('chalk');

module.exports = function (grunt) {
  grunt.registerMultiTask('appdmg', 'Generate DMG-images for Mac OSX', function () {
    var options = this.options();
    var done = this.async();

    if (options.configFile) {
      grunt.log.warn('"configFile" option has been deprecated.');
      delete options.configFile;
    }

    var basepath = options.basepath || process.cwd();
    delete options.basepath;

    // Iterate over all specified file groups.
    this.files.forEach(function (filePair) {
      var dirname = path.dirname(filePair.dest);
      var emitter;

      // Create directory beforehand to prevent error.
      grunt.file.mkdir(dirname);

      // Run appdmg module.
      // Remove logging and use native appdmg's method in the future release.
      emitter = appdmg({basepath: basepath, specification: options, target: filePair.dest});
      emitter.on('progress', function (info) {
        if (info.type === 'step-begin') {
          var line = '[' + (info.current <= 9 ? ' ' : '') + info.current + '/' + info.total + '] ' + info.title + '...';
          grunt.log.write(line + grunt.util.repeat(45 - line.length, ' '));
        }
        if (info.type === 'step-end') {
          var op = ({
            ok: ['green', ' OK '],
            skip: ['yellow', 'SKIP'],
            error: ['red', 'FAIL']
          }[info.status]);
          grunt.log.write('[' + chalk[op[0]](op[1]) + ']\n');
        }
      });
      emitter.on('finish', function () {
        grunt.log.writeln('\nImage: ' + chalk.cyan(filePair.dest) + ' was created');
        done();
      });
      emitter.on('error', function (err) {
        grunt.log.error(err.toString());
        done(false);
      });
    });
  });
};
<commit_msg>Comfortable lines<commit_after>'use strict';

var path = require('path');
var appdmg = require('appdmg');
var chalk = require('chalk');

module.exports = function (grunt) {
  grunt.registerMultiTask('appdmg', 'Generate DMG-images for Mac OSX', function () {
    var options = this.options();
    var done = this.async();

    if (options.configFile) {
      grunt.log.warn('"configFile" option has been deprecated.');
      delete options.configFile;
    }

    var basepath = options.basepath || process.cwd();
    delete options.basepath;

    // Iterate over all specified file groups.
    this.files.forEach(function (filePair) {
      var dirname = path.dirname(filePair.dest);
      var emitter;

      // Create directory beforehand to prevent error.
      grunt.file.mkdir(dirname);

      // Run appdmg module.
      emitter = appdmg({basepath: basepath, specification: options, target: filePair.dest});

      // Logging.
      // This should be removed when appdmg provides logging method.
      emitter.on('progress', function (info) {
        if (info.type === 'step-begin') {
          var line = '[' + (info.current <= 9 ? ' ' : '') + info.current + '/' + info.total + '] ' + info.title + '...';
          grunt.log.write(line + grunt.util.repeat(45 - line.length, ' '));
        }

        if (info.type === 'step-end') {
          var op = ({
            ok: ['green', ' OK '],
            skip: ['yellow', 'SKIP'],
            error: ['red', 'FAIL']
          }[info.status]);
          grunt.log.write('[' + chalk[op[0]](op[1]) + ']\n');
        }
      });

      emitter.on('finish', function () {
        grunt.log.writeln('\nImage: ' + chalk.cyan(filePair.dest) + ' created');
        done();
      });

      emitter.on('error', function (err) {
        grunt.log.error(err.toString());
        done(false);
      });
    });
  });
};
<|endoftext|>


<commit_before>'use strict';
/* global it, expect */

var h = require('../helpers');

h.describe('Graph API methods', function() {
    it('can get me', function() {
        h.runAsync(function(done) {
            h.request('GET', h.baseURL + 'graph/me').end(function(res) {
                expect(res.statusCode).toBe(200);

                // Make sure we get nodes and links
                expect(typeof res.body.nodes).toEqual('object');
                expect(typeof res.body.links).toEqual('object');

                // Check that there's the right amount of nodes and links
                var nodeKeys = Object.keys(res.body.nodes);
                expect(nodeKeys.length).toBe(5);
                expect(res.body.links.length).toBe(4);

                // Validate all the nodes
                nodeKeys.forEach(function(id) {
                    var node = res.body.nodes[id];

                    expect(typeof node.id).toBe('string');
                    expect(typeof node.type).toBe('string');
                    expect(node.type).toMatch(/^(user|baby|maybe)$/);
                    expect(typeof node.team).toBe('string');
                    expect(typeof node.relation).toBe('string');
                    switch (node.relation) {
                    case 'me':
                        expect(typeof node.fullName).toBe('string');
                        expect(typeof node.coordX).toBe('number');
                        expect(typeof node.coordY).toBe('number');
                        break;
                    case 'friend':
                        expect(typeof node.fullName).toBe('string');
                        break;
                    case 'friendOfFriend':
                        expect(node.fullName).toBeUndefined();
                        break;
                    default:
                        expect('unkown node type').toBe('never happening');
                    }
                });

                // TODO: check that not too much information is exposed (no names or num activity infos for friends of friends)
                done();
            });
        });
    });

    it('cannot get graph of a full user if not logged in as that user', function() {
        h.runAsync(function(done) {
            h.request('GET', h.baseURL + 'graph/000000000000000000000001').end(function(res) {
                expect(res.statusCode).toBe(403);
                done();
            });
        }) ;
    });

    it('can get graph of a maybe user', function() {
        h.runAsync(function(done) {
            h.request('GET', h.baseURL + 'graph/000000000000000000000003').end(function(res) {
                expect(res.statusCode).toBe(200);

                expect(typeof res.body.nodes).toEqual('object');
                expect(typeof res.body.links).toEqual('object');
                expect(Object.keys(res.body.nodes).length).toBe(4); // 1 me, 1 the other use, 2 friends of that friend
                expect(res.body.links.length).toBe(3);
                done();
            });
        });
    });
});
<commit_msg>Fix graph tests.<commit_after>'use strict';
/* global it, expect */

var _ = require('lodash');
var h = require('../helpers');

h.describe('Graph API methods', function() {
    it('can get me', function() {
        h.runAsync(function(done) {
            h.request('GET', h.baseURL + 'graph/me').end(function(res) {
                expect(res.statusCode).toBe(200);

                // Make sure we get nodes and links
                expect(_.isPlainObject(res.body.nodes)).toBe(true);
                expect(_.isArray(res.body.links)).toBe(true);

                // Check that there's the right amount of nodes and links
                var nodeKeys = Object.keys(res.body.nodes);
                expect(nodeKeys.length).toBe(5);
                expect(res.body.links.length).toBe(4);

                // Validate all the nodes
                nodeKeys.forEach(function(id) {
                    var node = res.body.nodes[id];

                    expect(typeof node.id).toBe('string');
                    expect(typeof node.type).toBe('string');
                    expect(node.type).toMatch(/^(user|baby|maybe)$/);
                    expect(typeof node.team).toBe('string');
                    expect(typeof node.relation).toBe('string');
                    switch (node.relation) {
                    case 'me':
                        expect(typeof node.fullName).toBe('string');
                        expect(typeof node.coordX).toBe('number');
                        expect(typeof node.coordY).toBe('number');
                        break;
                    case 'friend':
                        expect(typeof node.fullName).toBe('string');
                        break;
                    case 'friendOfFriend':
                        expect(node.fullName).toBeUndefined();
                        break;
                    default:
                        expect('unkown node type').toBe('never happening');
                    }
                });

                // TODO: check that not too much information is exposed (no names or num activity infos for friends of friends)
                done();
            });
        });
    });

    it('cannot get graph of a full user if not logged in as that user', function() {
        h.runAsync(function(done) {
            h.request('GET', h.baseURL + 'graph/000000000000000000000001').end(function(res) {
                expect(res.statusCode).toBe(403);
                done();
            });
        }) ;
    });

    it('can get graph of a maybe user', function() {
        h.runAsync(function(done) {
            h.request('GET', h.baseURL + 'graph/000000000000000000000003').end(function(res) {
                expect(res.statusCode).toBe(200);

                expect(typeof res.body.nodes).toEqual('object');
                expect(typeof res.body.links).toEqual('object');
                expect(Object.keys(res.body.nodes).length).toBe(4); // 1 me, 1 the other use, 2 friends of that friend
                expect(res.body.links.length).toBe(3);
                done();
            });
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

var expect = require('expect.js'),
    isFile = require('../helpers/util/is-file'),
    fs     = require('fs')
;

module.exports = function (automaton) {
    describe('cp', function () {
        var target = __dirname + '/../tmp/cp/';

        beforeEach(function () {
            fs.mkdirSync(target, '0777');
        });

        it('should copy file to file', function (done) {
            var files = {};
            files[__dirname + '/../helpers/assets/file1.json'] = target + 'file1.json';
            files[__dirname + '/../helpers/assets/file2'] = target;

            automaton.run('cp', {
                files: files
            }, function (err) {
                if (err) {
                    throw err;
                }

                expect(isFile(target + 'file1.json')).to.be(true);
                expect(isFile(target + 'file2')).to.be(true);
                done();
            });
        });

        it.skip('should copy file to folder', function () {
            // test file to folder/
            // test file to folder where folder already exists
            // please confirm this behavior in the command line
        });

        it.skip('should copy folder to folder', function () {
            // test folder to folder/
            // test folder to folder where folder does not exist
            //  - it should copy folder to folder
            // test folder to folder where folder alredy exist
            //  - it should copy folder to folder/folder
        });

        it.skip('should copy files with single star pattern', function () {
            // test if ONLY files are copied with source/*
        });

        it.skip('should copy files and folders recursivelly', function () {
            // test if files and folders are recursivelly copied with source/**/*
        });

        it.skip('should give error if source file does not exist');
        it.skip('should give error if source folder does not exist');
        it.skip('should give error if sources do not exist', function () {
            // test with source/* and source/**/*
        });

        it('should work with sources as symlinks', function (done) {
            var dir     = 'cp_dst/',
                file    = 'file.js',
                symlink = target + '../file.js',
                files   = {};

            // create file
            fs.writeFileSync(target + file, 'dummy');

            // create dir
            fs.mkdirSync(target + '../' + dir);

            // create symlink to folder in tmp
            fs.symlinkSync(target + file, symlink, 'file');

            // copy file
            files[symlink] = target + '../' + dir;

            automaton.run('cp', {
                files: files
            }, function (err) {
                if (err) {
                    throw err;
                }

                expect(isFile(target + '../' + dir + file)).to.be(true);
                done();
            });
        });

        it.skip('should work sources containing symlinks deeply inside them', function () {
            // test with a symlink inside the folder being copied
            // also test with source/**/* with a symlink deeply inside the source
            // it's important to make those separate tests because they have different piecies of code handling it
            //
            // check what is the unix behavior here.. to copy it as a symlink or follow the symlink
            // still an ISSUE should be created to add an option to the cp in order to change this behavior
        });

        it('should work with destinations as symlinks', function (done) {
            var folder  = target + 'folder/',
                file    = 'file.js',
                symlink = target + '../symlink_to_folder',
                files   = {};

            // create file
            fs.writeFileSync(target + file, 'dummy');

            // create dir
            fs.mkdirSync(folder);

            // create symlink to folder in tmp
            fs.symlinkSync(folder, symlink, 'dir');

            // copy file in /tmp/cp/file.js to /tmp/symlink/file.js
            // where symlink = cp/folder
            files[target + file] = symlink + '/';

            automaton.run('cp', {
                files: files
            }, function (err) {
                if (err) {
                    throw err;
                }

                expect(isFile(symlink + '/' + file)).to.be(true);
                fs.unlinkSync(symlink);

                // copy file in /tmp/cp/file.js to /tmp/symlink
                // where symlink = cp/folder
                files[target + file] = symlink;

                automaton.run('cp', {
                    files: files
                }, function (err) {
                    if (err) {
                        throw err;
                    }

                    expect(isFile(symlink)).to.be(true);
                    done();
                });

            });
        });

        it('should copy with default permissions', function (done) {
            var dir         = target + 'permissions/',
                folder      = 'folder/',
                file        = 'file.js',
                toCopy      = {},
                mode_dir,
                mode_file;

            // create dirs
            fs.mkdirSync(dir);
            fs.mkdirSync(target + folder);

            // get default dir mode
            mode_dir = fs.statSync(target + folder).mode;

            // change it to something else
            fs.chmodSync(target + folder, '0777');

            // create file
            fs.writeFileSync(target + file, 'dummy');

            // get file mode
            mode_file = fs.statSync(target + file).mode;

            // change it to something else
            fs.chmodSync(target + file, '0777');

            // file to copy
            toCopy[target + file]   = dir;
            toCopy[target + folder] = dir + 'folder/';

            automaton.run('cp', {
                files: toCopy
            }, function (err) {
                if (err) {
                    throw err;
                }

                expect(fs.statSync(toCopy[target + file] + file).mode).to.equal(mode_file);
                expect(fs.statSync(toCopy[target + folder]).mode).to.equal(mode_dir);
                done();
            });
        });

        it('should pass over the glob options - should not copy the file', function (done) {
            var files = {};
            files[__dirname + '/../helpers/assets/*file'] = target;

            automaton.run('cp', {
                files: files
            }, function (err) {
                if (err) {
                    throw err;
                }

                expect(isFile(target + '.file')).to.be(false);
                done();
            });
        });

        it('should pass over the glob options - should copy the file', function (done) {
            var files = {};
            files[__dirname + '/../helpers/assets/.file'] = target;

            automaton.run('cp', {
                files: files,
                glob: {
                    dot: true
                }
            }, function (err) {
                if (err) {
                    throw err;
                }
                expect(isFile(target + '.file')).to.be(true);
                done();
            });
        });
    });
};
<commit_msg>Updated cp tests<commit_after>'use strict';

var expect = require('expect.js'),
    isFile = require('../helpers/util/is-file'),
    isDir  = require('../helpers/util/is-dir'),
    fs     = require('fs')
;

module.exports = function (automaton) {
    describe('cp', function () {
        var target = __dirname + '/../tmp/cp/';

        beforeEach(function () {
            fs.mkdirSync(target, '0777');
        });

        it('should copy file to file', function (done) {
            var files = {};
            files[__dirname + '/../helpers/assets/file1.json'] = target + 'file1.json';
            files[__dirname + '/../helpers/assets/file2'] = target;

            automaton.run('cp', {
                files: files
            }, function (err) {
                if (err) {
                    throw err;
                }

                expect(isFile(target + 'file1.json')).to.be(true);
                expect(isFile(target + 'file2')).to.be(true);
                done();
            });
        });

        it('should copy file to folder', function (done) {
            var files         = {},
                folder        = 'file_to_folder/',
                folder_exists = 'file_to_folder_exists/';

            files[__dirname + '/../helpers/assets/file1.json'] = target + folder;
            files[__dirname + '/../helpers/assets/file2'] = target + folder_exists;

            // create dir
            fs.mkdirSync(target + folder_exists);

            automaton.run('cp', {
                files: files
            }, function (err) {
                if (err) {
                    throw err;
                }

                expect(isFile(target + folder + 'file1.json')).to.be(true);
                expect(isFile(target + folder_exists + 'file2')).to.be(true);
                done();
            });
        });

        it('should copy folder to folder', function (done) {
            var files  = {},
                src    = 'src/',
                dst    = 'dst/',
                file   = 'file.js';

            // create dir
            fs.mkdirSync(target + src);
            fs.mkdirSync(target + dst);

            // create file
            fs.writeFileSync(target + src + file, 'dummy');

            files[target + src + file] = target + dst;

            automaton.run('cp', {
                files: files
            }, function (err) {
                if (err) {
                    throw err;
                }

                expect(isFile(target + dst + file)).to.be(true);
                done();
            });
        });

        it('should copy folder to folder - destination folder does not exist', function (done) {
            // test folder to folder/
            // test folder to folder where folder does not exist
            //  - it should copy folder to folder
            // test folder to folder where folder alredy exist
            //  - it should copy folder to folder/folder
            var files  = {},
                src    = 'src/',
                dst    = 'dst/',
                file   = 'file.js';

            // create dir
            fs.mkdirSync(target + src);

            // create file
            fs.writeFileSync(target + src + file, 'dummy');

            files[target + src + file] = target + dst;

            automaton.run('cp', {
                files: files
            }, function (err) {
                if (err) {
                    throw err;
                }

                expect(isFile(target + dst + file)).to.be(true);
                done();
            });
        });

        it('should copy folder to folder - destination folder already exist', function (done) {
            var files  = {},
                src    = 'src/',
                dst    = 'dst/',
                folder = 'folder/',
                file   = 'file.js';

            // create dir
            fs.mkdirSync(target + src);
            fs.mkdirSync(target + src + folder);
            fs.mkdirSync(target + dst);
            fs.mkdirSync(target + dst + folder);

            // create file
            fs.writeFileSync(target + src + file, 'dummy');

            files[target + src + file] = target + dst;
            files[target + src + folder] = target + dst;

            automaton.run('cp', {
                files: files
            }, function (err) {
                if (err) {
                    throw err;
                }

                expect(isFile(target + dst + file)).to.be(true);
                expect(isDir(target + dst + folder + folder)).to.be(true);
                done();
            });
        });

        it('should copy files with single star pattern - source/*', function (done) {
            // test if ONLY files are copied with source/*
            var files  = {},
                src    = '../cp_single_star/',
                dst    = 'dst/',
                folder = 'folder',
                file   = 'file.js'
            ;
            // create dir
            fs.mkdirSync(target + src);
            fs.mkdirSync(target + src + folder);
            fs.mkdirSync(target + dst);

            // create file
            fs.writeFileSync(target + src + file, 'dummy');

            files[target + src + '*'] = target + dst;

            automaton.run('cp', {
                files: files
            }, function (err) {
                if (err) {
                    throw err;
                }

                expect(isFile(target + dst + file)).to.be(true);
                expect(isDir(target + dst + folder)).to.be(false);
                done();
            });
        });

        it('should copy files and folders recursivelly - source/**/*', function (done) {
            // test if files and folders are recursivelly copied with source/**/*
            var files  = {},
                src    = '../cp_single_star/',
                dst    = 'dst/',
                folder = 'folder',
                file   = 'file.js'
            ;
            // create dir
            fs.mkdirSync(target + src);
            fs.mkdirSync(target + src + folder);
            fs.mkdirSync(target + dst);

            // create file
            fs.writeFileSync(target + src + file, 'dummy');

            files[target + src + '**/*'] = target + dst;

            automaton.run('cp', {
                files: files
            }, function (err) {
                if (err) {
                    throw err;
                }

                expect(isFile(target + dst + file)).to.be(true);
                expect(isDir(target + dst + folder)).to.be(true);
                done();
            });
        });

        it('should give error if source file does not exist', function (done) {
            var files  = {},
                dst    = 'dst/';

            // create dir
            fs.mkdirSync(target + dst);

            files[target + 'file.js'] = target + dst;

            automaton.run('cp', {
                files: files
            }, function (err) {

                expect(err).to.be.ok();
                expect(err.message).to.match(/ENOENT/);
                done();
            });
        });

        it('should give error if source folder does not exist', function (done) {
            var files  = {},
                dst    = 'dst/';

            // create dir
            fs.mkdirSync(target + dst);

            files[target + 'folder'] = target + dst;

            automaton.run('cp', {
                files: files
            }, function (err) {

                expect(err).to.be.ok();
                expect(err.message).to.match(/ENOENT/);
                done();
            });
        });

        it('should give error if sources do not exist - simple', function (done) {
            var files  = {},
                dst    = 'dst/';

            // create dir
            fs.mkdirSync(target + dst);

            files[target + 'folder'] = target + dst;
            files[target + 'file.js'] = target + dst;

            automaton.run('cp', {
                files: files
            }, function (err) {

                expect(err).to.be.ok();
                expect(err.message).to.match(/ENOENT/);
                done();
            });
        });

        it('should give error if sources do not exist - source/*', function (done) {
            var files  = {},
                dst    = 'dst/';

            // create dir
            fs.mkdirSync(target + dst);

            files[target + 'folder/*'] = target + dst;

            automaton.run('cp', {
                files: files
            }, function (err) {

                expect(err).to.be.ok();
                expect(err.message).to.match(/ENOENT/);
                done();
            });
        });

        it('should give error if sources do not exist - source/**/*', function (done) {
            var files  = {},
                dst    = 'dst/';

            // create dir
            fs.mkdirSync(target + dst);

            files[target + 'folder/**/*'] = target + dst;

            automaton.run('cp', {
                files: files
            }, function (err) {

                expect(err).to.be.ok();
                expect(err.message).to.match(/ENOENT/);
                done();
            });
        });

        it('should work with sources as symlinks', function (done) {
            var dir     = 'cp_dst/',
                file    = 'file.js',
                symlink = target + '../file.js',
                files   = {};

            // create file
            fs.writeFileSync(target + file, 'dummy');

            // create dir
            fs.mkdirSync(target + '../' + dir);

            // create symlink to file
            fs.symlinkSync(target + file, symlink, 'file');

            // copy file
            files[symlink] = target + '../' + dir;

            automaton.run('cp', {
                files: files
            }, function (err) {
                if (err) {
                    throw err;
                }

                expect(isFile(target + '../' + dir + file)).to.be(true);
                done();
            });
        });

        it('should work sources containing symlinks deeply inside them', function (done) {
            var files     = {},
                cp_folder = '../cp_folder_to_symlink/',
                src       = 'src_with_symlink/',
                dst       = 'dst_with_symlink/',
                symlink   = 'symlink',
                file      = 'file.js';

            fs.mkdirSync(target + cp_folder);
            fs.mkdirSync(target + src);

            // create file
            fs.writeFileSync(target + cp_folder + file, 'dummy');

            // create symlink to folder
            fs.symlinkSync(target + cp_folder, target + src + symlink, 'dir');

            files[target + src] = target + dst;

            automaton.run('cp', {
                files: files
            }, function (err) {
                if (err) {
                    throw err;
                }

                expect(isDir(target + dst + src)).to.be(true);
                expect(isDir(target + dst + src + symlink)).to.be(true);
                expect(isFile(target + dst + src + symlink + '/' + file)).to.be(true);
                done();
            });

        });

        it('should work sources containing symlinks deeply inside them - with source/**/* ', function (done) {
            var files     = {},
                cp_folder = '../cp_folder_to_symlink/',
                src       = 'src_with_symlink/',
                dst       = 'dst_with_symlink/',
                symlink   = 'symlink',
                file      = 'file.js';

            fs.mkdirSync(target + cp_folder);
            fs.mkdirSync(target + src);

            // create file
            fs.writeFileSync(target + cp_folder + file, 'dummy');

            // create symlink to folder
            fs.symlinkSync(target + cp_folder, target + src + symlink, 'dir');

            files[target + src + '/**/*'] = target + dst;

            automaton.run('cp', {
                files: files
            }, function (err) {
                if (err) {
                    throw err;
                }

                expect(isDir(target + dst)).to.be(true);
                expect(isDir(target + dst + symlink)).to.be(true);
                expect(isFile(target + dst + symlink + '/' + file)).to.be(true);
                done();
            });

        });

        it('should work with destinations as symlinks', function (done) {
            var folder  = target + 'folder/',
                file    = 'file.js',
                symlink = target + '../symlink_to_folder',
                files   = {};

            // create file
            fs.writeFileSync(target + file, 'dummy');

            // create dir
            fs.mkdirSync(folder);

            // create symlink to folder in tmp
            fs.symlinkSync(folder, symlink, 'dir');

            // copy file in /tmp/cp/file.js to /tmp/symlink/file.js
            // where symlink = cp/folder
            files[target + file] = symlink + '/';

            automaton.run('cp', {
                files: files
            }, function (err) {
                if (err) {
                    throw err;
                }

                expect(isFile(symlink + '/' + file)).to.be(true);
                fs.unlinkSync(symlink);

                // copy file in /tmp/cp/file.js to /tmp/symlink
                // where symlink = cp/folder
                files[target + file] = symlink;

                automaton.run('cp', {
                    files: files
                }, function (err) {
                    if (err) {
                        throw err;
                    }

                    expect(isFile(symlink)).to.be(true);
                    done();
                });

            });
        });

        it('should copy with default permissions', function (done) {
            var dir         = target + 'permissions/',
                folder      = 'folder/',
                file        = 'file.js',
                toCopy      = {},
                mode_dir,
                mode_file;

            // create dirs
            fs.mkdirSync(dir);
            fs.mkdirSync(target + folder);

            // get default dir mode
            mode_dir = fs.statSync(target + folder).mode;

            // change it to something else
            fs.chmodSync(target + folder, '0777');

            // create file
            fs.writeFileSync(target + file, 'dummy');

            // get file mode
            mode_file = fs.statSync(target + file).mode;

            // change it to something else
            fs.chmodSync(target + file, '0777');

            // file to copy
            toCopy[target + file]   = dir;
            toCopy[target + folder] = dir + 'folder/';

            automaton.run('cp', {
                files: toCopy
            }, function (err) {
                if (err) {
                    throw err;
                }

                expect(fs.statSync(toCopy[target + file] + file).mode).to.equal(mode_file);
                expect(fs.statSync(toCopy[target + folder]).mode).to.equal(mode_dir);
                done();
            });
        });

        it('should copy empty folders', function (done) {
            var files         = {},
                destination   = 'empty_folders/',
                folder1       = 'not_empty_folder/',
                folder2       = 'folder2/',
                folder3       = 'folder3/',
                file          = 'file.js';

            files[target + folder1] = target + destination;

            // create folders
            fs.mkdirSync(target + folder1);
            fs.mkdirSync(target + folder1 + folder2);
            fs.mkdirSync(target + folder1 + folder2 + folder3);

            // create file
            fs.writeFileSync(target + folder1 + folder2 + file, 'dummy');

            automaton.run('cp', {
                files: files
            }, function (err) {
                if (err) {
                    throw err;
                }

                expect(isDir(target + destination + folder1)).to.be(true);
                expect(isDir(target + destination + folder1 + folder2)).to.be(true);
                expect(isDir(target + destination + folder1 + folder2 + folder3)).to.be(true);
                expect(isFile(target + destination + folder1 + folder2 + file)).to.be(true);
                done();
            });
        });

        it('should pass over the glob options - should not copy the file', function (done) {
            var files = {};
            files[__dirname + '/../helpers/assets/*file'] = target;

            automaton.run('cp', {
                files: files
            }, function (err) {
                if (err) {
                    throw err;
                }

                expect(isFile(target + '.file')).to.be(false);
                done();
            });
        });

        it('should pass over the glob options - should copy the file', function (done) {
            var files = {};
            files[__dirname + '/../helpers/assets/.file'] = target;

            automaton.run('cp', {
                files: files,
                glob: {
                    dot: true
                }
            }, function (err) {
                if (err) {
                    throw err;
                }
                expect(isFile(target + '.file')).to.be(true);
                done();
            });
        });
    });
};
<|endoftext|>


<commit_before>var path = require('path');
var tmpDir = path.resolve(__dirname, 'tmp/');
var wrapperDir = path.resolve(__dirname, 'lib/wrapper/');

// Task arguments.
var withWatch = false;
var isDeploying = false;

/**
 * Write a file that declares if application is in development mode.
 *
 * @function writeDevFile
 * @param {Object} grunt
 * @return {String}
 * @api private
 */

function writeDevFile (grunt) {
    var filePath = path.join(tmpDir, 'dev.js');

    // Set $development to false if isDeploying is true.
    grunt.file.write(filePath, 'var $development = ' + String(!isDeploying) + ';\x0A');

    return filePath;
}

/**
 * Only Javascript is allowed to be added into files list.
 *
 * @function isInvalidFile
 * @param {String} file
 * @param {Object} stats
 * @return {Boolean}
 * @api private
 */

function isInvalidFile (file, stats) {
    // Do not block access to sub directories.
    if (stats.isDirectory()) {
        return false;
    } else if (path.extname(file) === '.js') {
        return false;
    } else {
        return true;
    }
}

/**
 * @function buildFileList
 * @param {Object} grunt
 * @param {Object} task
 * @api private
 */

function buildFileList (grunt, task) {
    if (!grunt.file.isDir(task.data.src) || typeof task.data.dest !== 'string') { return undefined; }

    // recursive-readdir is asynchronous.
    var done = task.async();
    var files = [];

    // Start wrap.
    files.push(path.join(wrapperDir, 'init.js'));
    files.push(writeDevFile(grunt));
    files.push(path.join(wrapperDir, 'dependency.js'));

    require('recursive-readdir')(task.data.src, [isInvalidFile], function (err, srcFiles) {
        // Finish recursive-addir.
        done();

        // All Javascript files in src directory.
        files = files.concat(srcFiles);

        // End wrap.
        files.push(path.join(wrapperDir, 'final.js'));

        concat(grunt, task, files);
    });
}

/**
 * Concatenate all the modules into a single Javascript file.
 *
 * @function concat
 * @param {Object} grunt
 * @param {Object} task
 * @param {Array} files
 * @api private
 */

function concat (grunt, task, files) {
    if (!grunt.task.exists('concat')) {
        grunt.loadNpmTasks('grunt-contrib-concat');
    }

    grunt.config('concat.catena', {
        src: files,
        dest: task.data.dest
    });

    // Minify and license dest file after concatening it when deploying.
    if (isDeploying) {
        grunt.registerTask('minify:catena', '', function () {
            require('./lib/compiler/minify.js')(grunt, task);
        });

        grunt.registerTask('license:catena', '', function () {
            license(grunt, task);
        });

        grunt.task.run('concat:catena', 'minify:catena', 'license:catena');

    } else {
        grunt.task.run('concat:catena');

        watch(grunt, task);
    }
}

/**
 * Prepend license file content to dest file.
 *
 * @function license
 * @param {Object} grunt
 * @param {Object} task
 * @api private
 */

function license (grunt, task) {
    if (!grunt.file.isFile(task.data.license)) { return undefined; }

    var destFile = grunt.file.read(task.data.dest);
    var licenseFile = grunt.file.read(task.data.license);

    grunt.file.write(task.data.dest, licenseFile + '\x0A' + destFile);
}

/**
 * Watch all .js files in src directory.
 *
 * @function watch
 * @param {Object} grunt
 * @param {Object} task
 * @api private
 */

function watch (grunt, task) {
    // No need to run watch if application is being deployed or already being watched.
    if (!Boolean(task.data.watch) || withWatch || isDeploying) { return undefined; }

    if (!grunt.task.exists('watch')) {
        grunt.loadNpmTasks('grunt-contrib-watch');
    }

    grunt.config('watch.catena', {
        files: path.join(task.data.src, '**/*.js'),
        tasks: ['catena:with_watch'],
        options: {
            spawn: false,
            interval: 1000
        }
    });

    grunt.task.run('watch:catena');
}

module.exports = function (grunt) {
    grunt.registerTask('catena', function () {
        withWatch = this.args.indexOf('with_watch') !== -1;
        isDeploying = this.args.indexOf('deploy') !== -1;

        // Treat catena as a subtask.
        this.data = grunt.config.get('catena');

        buildFileList(grunt, this);
    });
};
<commit_msg>{Update: catena.js} Check if src and license are strings.<commit_after>var path = require('path');
var tmpDir = path.resolve(__dirname, 'tmp/');
var wrapperDir = path.resolve(__dirname, 'lib/wrapper/');

// Task arguments.
var withWatch = false;
var isDeploying = false;

/**
 * Write a file that declares if application is in development mode.
 *
 * @function writeDevFile
 * @param {Object} grunt
 * @return {String}
 * @api private
 */

function writeDevFile (grunt) {
    var filePath = path.join(tmpDir, 'dev.js');

    // Set $development to false if isDeploying is true.
    grunt.file.write(filePath, 'var $development = ' + String(!isDeploying) + ';\x0A');

    return filePath;
}

/**
 * Only Javascript is allowed to be added into files list.
 *
 * @function isInvalidFile
 * @param {String} file
 * @param {Object} stats
 * @return {Boolean}
 * @api private
 */

function isInvalidFile (file, stats) {
    // Do not block access to sub directories.
    if (stats.isDirectory()) {
        return false;
    } else if (path.extname(file) === '.js') {
        return false;
    } else {
        return true;
    }
}

/**
 * @function buildFileList
 * @param {Object} grunt
 * @param {Object} task
 * @api private
 */

function buildFileList (grunt, task) {
    if (typeof task.data.src !== 'string' || typeof task.data.dest !== 'string') {
        return undefined;
    } else if (!grunt.file.isDir(task.data.src)) {
        return undefined;
    }

    // recursive-readdir is asynchronous.
    var done = task.async();
    var files = [];

    // Start wrap.
    files.push(path.join(wrapperDir, 'init.js'));
    files.push(writeDevFile(grunt));
    files.push(path.join(wrapperDir, 'dependency.js'));

    require('recursive-readdir')(task.data.src, [isInvalidFile], function (err, srcFiles) {
        // Finish recursive-addir.
        done();

        // All Javascript files in src directory.
        files = files.concat(srcFiles);

        // End wrap.
        files.push(path.join(wrapperDir, 'final.js'));

        concat(grunt, task, files);
    });
}

/**
 * Concatenate all the modules into a single Javascript file.
 *
 * @function concat
 * @param {Object} grunt
 * @param {Object} task
 * @param {Array} files
 * @api private
 */

function concat (grunt, task, files) {
    if (!grunt.task.exists('concat')) {
        grunt.loadNpmTasks('grunt-contrib-concat');
    }

    grunt.config('concat.catena', {
        src: files,
        dest: task.data.dest
    });

    // Minify and license dest file after concatening it when deploying.
    if (isDeploying) {
        grunt.registerTask('minify:catena', '', function () {
            require('./lib/compiler/minify.js')(grunt, task);
        });

        grunt.registerTask('license:catena', '', function () {
            license(grunt, task);
        });

        grunt.task.run('concat:catena', 'minify:catena', 'license:catena');

    } else {
        grunt.task.run('concat:catena');

        watch(grunt, task);
    }
}

/**
 * Prepend license file content to dest file.
 *
 * @function license
 * @param {Object} grunt
 * @param {Object} task
 * @api private
 */

function license (grunt, task) {
    if (typeof task.data.license !== 'string' || !grunt.file.isFile(task.data.license)) { return undefined; }

    var destFile = grunt.file.read(task.data.dest);
    var licenseFile = grunt.file.read(task.data.license);

    grunt.file.write(task.data.dest, licenseFile + '\x0A' + destFile);
}

/**
 * Watch all .js files in src directory.
 *
 * @function watch
 * @param {Object} grunt
 * @param {Object} task
 * @api private
 */

function watch (grunt, task) {
    // No need to run watch if application is being deployed or already being watched.
    if (!Boolean(task.data.watch) || withWatch || isDeploying) { return undefined; }

    if (!grunt.task.exists('watch')) {
        grunt.loadNpmTasks('grunt-contrib-watch');
    }

    grunt.config('watch.catena', {
        files: path.join(task.data.src, '**/*.js'),
        tasks: ['catena:with_watch'],
        options: {
            spawn: false,
            interval: 1000
        }
    });

    grunt.task.run('watch:catena');
}

module.exports = function (grunt) {
    grunt.registerTask('catena', function () {
        withWatch = this.args.indexOf('with_watch') !== -1;
        isDeploying = this.args.indexOf('deploy') !== -1;

        // Treat catena as a subtask.
        this.data = grunt.config.get('catena');

        buildFileList(grunt, this);
    });
};
<|endoftext|>


<commit_before>var vows = require( 'vows' ),
	assert = require('assert' )
	suite = vows.describe( 'jStat.' );

require( '../env.js' );

suite.addBatch({
	'' : {
		'topic' : function() {
			return jStat.;
		},
		'' : function(  ) {
		}
	}
});

suite.export( module );
<commit_msg>improve default testing template<commit_after>var vows = require( 'vows' ),
	assert = require('assert' )
	suite = vows.describe( 'jStat' );

require( '../env.js' );

suite.addBatch({
	'' : {
		'topic' : function() {
			return jStat;
		},
		'' : function( jStat ) {
		}
	}
});

suite.export( module );
<|endoftext|>


<commit_before>// Just trying to do the manual checking of the method existenance
// Will remove the file when we can communicate with the real libarary
// and can add the mocha test files.

var ECLib = require('../node-eclib.js');
var enums = require('../eclib-enum.js');
var ECLibUtil = require('../eclib-util.js');
var buffertools = require("buffertools");

console.log("ECLib testing");

var eclib = new ECLib({
    "bc_id": enums.BackendId["EC_BACKEND_JERASURE_RS_CAUCHY"],
    "k": 9,
    "m": 3
});

desc = eclib.init();

//eclib.testpad();

function test_one() {
    ref_buf = new Buffer(100000);
    buffertools.fill(ref_buf, 'z');

    eclib.encode(ref_buf,
		 function(status, encoded_data, encoded_parity, encoded_fragment_length) {
		     console.log("Encode Done status=" + status + " fragment_length=" + encoded_fragment_length);

		     k = eclib.opt.k;
		     m = eclib.opt.m;

		     x = k-m; //available data fragments
		     y = m;   //available parity fragments

		     var fragments = [];
		     var i, j;
		     j = 0;
		     for (i = 0;i < x;i++) {
			 fragments[j++] = encoded_data[i];
		     }
		     for (i = 0;i < y;i++) {
			 fragments[j++] = encoded_parity[i];
		     }

		     eclib.decode(fragments, x+y, encoded_fragment_length, 0,
				  function(status, out_data, out_data_length) {
				      console.log("Decode Done status=" + status + " data_length=" + out_data_length);

				      if (buffertools.compare(out_data, ref_buf) == 0)
					  console.log("OK Buffers are identical");
				      else
					  console.log("Nok buffers differ");
				  }
				 );

		 }
		);

    delete ref_buf;
}

test_one();
//test_one();
//test_one();

eclib.destroy();

global.gc(); //requires --expose-gc
<commit_msg>do a more sophisticated test<commit_after>// Just trying to do the manual checking of the method existenance
// Will remove the file when we can communicate with the real libarary
// and can add the mocha test files.

var ECLib = require('../node-eclib.js');
var enums = require('../eclib-enum.js');
var ECLibUtil = require('../eclib-util.js');
var buffertools = require("buffertools");
var crypto = require('crypto');
var hexdump = require('hexdump-nodejs');

console.log("ECLib testing");

function test_one(opts) {
    var eclib = new ECLib(opts);

    desc = eclib.init();

    //eclib.testpad();

    //ref_buf = new Buffer(10000);
    //buffertools.fill(ref_buf, 'z');
    ref_buf = crypto.randomBytes(1000);

    console.log(hexdump(ref_buf));

    eclib.encode(ref_buf,
		 function(status, encoded_data, encoded_parity, encoded_fragment_length) {
		     console.log("Encode Done status=" + status + " fragment_length=" + encoded_fragment_length);

		     k = eclib.opt.k;
		     m = eclib.opt.m;

		     x = k-m; //available data fragments
		     y = m;   //available parity fragments

		     var fragments = [];
		     var i, j;
		     j = 0;
		     console.log('data:');
		     for (i = 0;i < x;i++) {
			 console.log(hexdump(encoded_data[i]));
			 fragments[j++] = encoded_data[i];
		     }
		     console.log('codings:');
		     for (i = 0;i < y;i++) {
			 console.log(hexdump(encoded_parity[i]));
			 fragments[j++] = encoded_parity[i];
		     }

		     eclib.decode(fragments, x+y, encoded_fragment_length, 0,
				  function(status, out_data, out_data_length) {
				      console.log("Decode Done status=" + status + " data_length=" + out_data_length);

				      console.log(hexdump(out_data));

				      if (buffertools.compare(out_data, ref_buf) == 0)
					  console.log("OK Buffers are identical");
				      else
					  console.log("Nok buffers differ");
				  }
				 );

		 }
		);

    delete ref_buf;

    eclib.destroy();
}

//EC_BACKEND_NULL
//EC_BACKEND_JERASURE_RS_VAND
//EC_BACKEND_JERASURE_RS_CAUCHY
//EC_BACKEND_FLAT_XOR_HD
//EC_BACKEND_ISA_L_RS_VAND
//EC_BACKEND_SHSS

test_one({
    "bc_id": enums.BackendId["EC_BACKEND_ISA_L_RS_CAUCHY"],
    "k": 9,
    "m": 3
});

global.gc(); //requires --expose-gc
<|endoftext|>


<commit_before>/*
 * grunt-contrib-coffee
 * http://gruntjs.com/
 *
 * Copyright (c) 2012 Eric Woroshow, contributors
 * Licensed under the MIT license.
 */

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

  var path = require('path');
  var _ = grunt.util._;

  grunt.registerMultiTask('coffee', 'Compile CoffeeScript files into JavaScript', function() {

    var options = this.options({
      bare: false,
      join: false,
      separator: grunt.util.linefeed
    });

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

    this.files.forEach(function (f) {
      var validFiles = removeInvalidFiles(f);
      var output;

      // get all extensions for input files
      var ext = validFiles.map(function (f) {
        return path.extname(f);
      });

      if (options.join === true) {
        if(_.uniq(ext).length > 1) {
          grunt.fail.warn('Join options requires input files share the same extension (found '+_.uniq(ext).join(', ')+').');
        } else {
          output = concatInput(validFiles, options);
        }
      } else {
        output = concatOutput(validFiles, options);
      }

      if (output.length < 1) {
        grunt.log.warn('Destination not written because compiled files were empty.');
      } else {
        grunt.file.write(f.dest, output);
        grunt.log.writeln('File ' + f.dest + ' created.');
      }
    });
  });

  var isLiterate = function (ext) {
    return (ext === ".litcoffee" || ext === ".md");
  };

  var removeInvalidFiles = function(files) {
    return files.src.filter(function(filepath) {
      if (!grunt.file.exists(filepath)) {
        grunt.log.warn('Source file "' + filepath + '" not found.');
        return false;
      } else {
        return true;
      }
    });
  };

  var concatInput = function (files, options) {
    var code = files.map(function (filePath) {
      return grunt.file.read(filePath);
    }).join(grunt.util.normalizelf(options.separator));
    return compileCoffee(code, options);
  };

  var concatOutput = function(files, options) {
    return files.map(function(filepath) {
      var code = grunt.file.read(filepath);
      return compileCoffee(code, options, filepath);
    }).join(grunt.util.normalizelf(options.separator));
  };

  var compileCoffee = function(code, options, filepath) {
    options = _.clone(options);
    if(filepath) {
      options.filename = filepath;
      options.literate = isLiterate(path.extname(filepath));
    }

    try {
      return require('coffee-script').compile(code, options);
    } catch (e) {
      grunt.log.error(e);
      grunt.fail.warn('CoffeeScript failed to compile.');
    }
  };
};
<commit_msg>Slightly more verbose error messaging.<commit_after>/*
 * grunt-contrib-coffee
 * http://gruntjs.com/
 *
 * Copyright (c) 2012 Eric Woroshow, contributors
 * Licensed under the MIT license.
 */

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

  var path = require('path');
  var _ = grunt.util._;

  grunt.registerMultiTask('coffee', 'Compile CoffeeScript files into JavaScript', function() {

    var options = this.options({
      bare: false,
      join: false,
      separator: grunt.util.linefeed
    });

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

    this.files.forEach(function (f) {
      var validFiles = removeInvalidFiles(f);
      var output;

      // get all extensions for input files
      var ext = validFiles.map(function (f) {
        return path.extname(f);
      });

      if (options.join === true) {
        if(_.uniq(ext).length > 1) {
          grunt.fail.warn('Join options requires input files share the same extension (found '+_.uniq(ext).join(', ')+').');
        } else {
          output = concatInput(validFiles, options);
        }
      } else {
        output = concatOutput(validFiles, options);
      }

      if (output.length < 1) {
        grunt.log.warn('Destination not written because compiled files were empty.');
      } else {
        grunt.file.write(f.dest, output);
        grunt.log.writeln('File ' + f.dest + ' created.');
      }
    });
  });

  var isLiterate = function (ext) {
    return (ext === ".litcoffee" || ext === ".md");
  };

  var removeInvalidFiles = function(files) {
    return files.src.filter(function(filepath) {
      if (!grunt.file.exists(filepath)) {
        grunt.log.warn('Source file "' + filepath + '" not found.');
        return false;
      } else {
        return true;
      }
    });
  };

  var concatInput = function (files, options) {
    var code = files.map(function (filePath) {
      return grunt.file.read(filePath);
    }).join(grunt.util.normalizelf(options.separator));
    return compileCoffee(code, options);
  };

  var concatOutput = function(files, options) {
    return files.map(function(filepath) {
      var code = grunt.file.read(filepath);
      return compileCoffee(code, options, filepath);
    }).join(grunt.util.normalizelf(options.separator));
  };

  var compileCoffee = function(code, options, filepath) {
    options = _.clone(options);
    if(filepath) {
      options.filename = filepath;
      options.literate = isLiterate(path.extname(filepath));
    }

    try {
      return require('coffee-script').compile(code, options);
    } catch (e) {
      grunt.log.error(e);
      grunt.log.error('In file: '+filepath);
      grunt.log.error('On line: '+e.location.first_line);
      grunt.fail.warn('CoffeeScript failed to compile.');
    }
  };
};
<|endoftext|>


<commit_before>/* jslint node: true */
/* global describe: false, it: false */
'use strict';

process.argv.push('--arg1', 'arg1Val', '--arg2', '-arg3', 'arg3Val', 'arg4', 'arg5', '-c', 'test/config-test.json');

var utilex = require('../'),
    fs     = require('fs'),
    expect = require('chai').expect;

// Tests

describe('utilex', function() {

  describe('appArgs()', function() {
    var appArgs = utilex.appArgs();

    it('should return command line arguments', function(done) {
      expect(appArgs).to.be.a('object');
      expect(appArgs).to.have.property('arg1', 'arg1Val');
      expect(appArgs).to.have.property('arg2', '');
      expect(appArgs).to.have.property('arg3', 'arg3Val');
      expect(appArgs).to.have.property('arg4', '');
      expect(appArgs).to.have.property('arg5', '');
      expect(appArgs).to.have.property('c', 'test/config-test.json');
      done();
    });
  });

  describe('appConfig()', function() {
    var appConfig = utilex.appConfig();

    it('should return configuration (' + JSON.stringify(appConfig) + ')', function(done) {
      expect(appConfig).to.be.a('object');
      expect(appConfig).to.have.property('file', 'test/config-test.json');
      expect(appConfig).to.have.property('config');
      expect(appConfig.config).to.be.a('object');
      expect(appConfig.config).to.have.property('testKey', 'testVal');
      done();
    });
  });

  describe('asyncFunc()', function() {
    it('should run correctly', function(done) {
      utilex.asyncFunc('hello', function(result) {
        expect(result).to.be.a('object');
        expect(result).to.have.property('input').to.be.equal('hello');
        expect(result).to.have.property('execTime').to.be.a('number').to.be.above(0);
        done();
      });
    });

    it('should run correctly (options)', function(done) {
      utilex.asyncFunc('hello', {delay: 99}, function(result) {
        expect(result).to.be.a('object');
        expect(result).to.have.property('input').to.be.equal('hello');
        expect(result).to.have.property('execTime').to.be.equal(99);
        done();
      });
    });
  });

  describe('conLog()', function() {
    var conLog = utilex.conLog('Tidy log...', false);

    it('should return a tidy log message (' + JSON.stringify(conLog) + ')', function(done) {
      expect(conLog).to.be.a('object');
      expect(conLog).to.have.property('time');
      expect(conLog).to.have.property('message').to.be.equal('Tidy log...');
      done();
    });
  });

  describe('datetime()', function() {
    var datetime1 = utilex.datetime(),
        datetime2 = utilex.datetime(new Date(1421370000000));

    it('should return a tidy time (' + datetime1 + ')', function(done) {
      expect(datetime1).to.be.a('string');
      done();
    });

    it('should return a tidy time (arg) (' + datetime2 + ')', function(done) {
      expect(datetime2).to.be.a('string');
      done();
    });
  });

  describe('dirIsWritable()', function() {
    var dirIsWritable = utilex.dirIsWritable(__dirname);

    it('should check whether a directory is writable or not (' + dirIsWritable + ')', function(done) {
      expect(dirIsWritable).to.be.a('boolean');
      done();
    });
  });

  describe('httpGetFile()', function() {
    it('should get a file', function(done) {
      utilex.httpGetFile('http://www.google.com/images/srpr/logo11w.png', './google-logo.png', function(err, fp) {
        if(err) done(err);

        fs.unlink(fp, function(err) {
          if(err) done(err);
          done();
        });
      });
    });
  });

  describe('jsonLoad()', function() {
    var jsonLoad = utilex.jsonLoad('test/config-test.json');

    it('should load a JSON file', function(done) {
      expect(jsonLoad).to.be.a('object');
      expect(jsonLoad).to.have.property('testKey', 'testVal');
      done();
    });
  });

  describe('strLen()', function() {
    var helloStr      = 'Hello 世界',
        helloStrLen   = utilex.strLen(helloStr),
        helloStrLenB  = utilex.strLen(helloStr, true);

    it('should return correct string length (' + helloStr + ' / 8)', function(done) {
      expect(helloStrLen).to.be.a('number').to.be.equal(8);
      done();
    });

    it('should return correct byte length (' + helloStr + ' / 12)', function(done) {
      expect(helloStrLenB).to.be.a('number').be.equal(12);
      done();
    });
  });

  describe('tasker()', function() {
    it('should run correctly', function(done) {

      var tasker = utilex.tasker();
      tasker.results = [];
      tasker.add({counter: 0});
      tasker.run(function(task, next) {
        tasker.results.push(++task.counter);
        if(task.counter < 5) {
          tasker.add({counter: task.counter});
        }
        next();
      }, function() {
        expect(tasker.results).to.be.a('array').to.be.deep.equal([1,2,3,4,5]);
        done();
      });
    });
  });

});<commit_msg>Add test for uid<commit_after>/* jslint node: true */
/* global describe: false, it: false */
'use strict';

process.argv.push('--arg1', 'arg1Val', '--arg2', '-arg3', 'arg3Val', 'arg4', 'arg5', '-c', 'test/config-test.json');

var utilex = require('../'),
    fs     = require('fs'),
    expect = require('chai').expect;

// Tests

describe('utilex', function() {

  describe('appArgs()', function() {
    var appArgs = utilex.appArgs();

    it('should return command line arguments', function(done) {
      expect(appArgs).to.be.a('object');
      expect(appArgs).to.have.property('arg1', 'arg1Val');
      expect(appArgs).to.have.property('arg2', '');
      expect(appArgs).to.have.property('arg3', 'arg3Val');
      expect(appArgs).to.have.property('arg4', '');
      expect(appArgs).to.have.property('arg5', '');
      expect(appArgs).to.have.property('c', 'test/config-test.json');
      done();
    });
  });

  describe('appConfig()', function() {
    var appConfig = utilex.appConfig();

    it('should return configuration (' + JSON.stringify(appConfig) + ')', function(done) {
      expect(appConfig).to.be.a('object');
      expect(appConfig).to.have.property('file', 'test/config-test.json');
      expect(appConfig).to.have.property('config');
      expect(appConfig.config).to.be.a('object');
      expect(appConfig.config).to.have.property('testKey', 'testVal');
      done();
    });
  });

  describe('asyncFunc()', function() {
    it('should run correctly', function(done) {
      utilex.asyncFunc('hello', function(result) {
        expect(result).to.be.a('object');
        expect(result).to.have.property('input').to.be.equal('hello');
        expect(result).to.have.property('execTime').to.be.a('number').to.be.above(0);
        done();
      });
    });

    it('should run correctly (options)', function(done) {
      utilex.asyncFunc('hello', {delay: 99}, function(result) {
        expect(result).to.be.a('object');
        expect(result).to.have.property('input').to.be.equal('hello');
        expect(result).to.have.property('execTime').to.be.equal(99);
        done();
      });
    });
  });

  describe('conLog()', function() {
    var conLog = utilex.conLog('Tidy log...', false);

    it('should return a tidy log message (' + JSON.stringify(conLog) + ')', function(done) {
      expect(conLog).to.be.a('object');
      expect(conLog).to.have.property('time');
      expect(conLog).to.have.property('message').to.be.equal('Tidy log...');
      done();
    });
  });

  describe('datetime()', function() {
    var datetime1 = utilex.datetime(),
        datetime2 = utilex.datetime(new Date(1421370000000));

    it('should return a tidy time (' + datetime1 + ')', function(done) {
      expect(datetime1).to.be.a('string');
      done();
    });

    it('should return a tidy time (arg) (' + datetime2 + ')', function(done) {
      expect(datetime2).to.be.a('string');
      done();
    });
  });

  describe('dirIsWritable()', function() {
    var dirIsWritable = utilex.dirIsWritable(__dirname);

    it('should check whether a directory is writable or not (' + dirIsWritable + ')', function(done) {
      expect(dirIsWritable).to.be.a('boolean');
      done();
    });
  });

  describe('httpGetFile()', function() {
    it('should get a file', function(done) {
      utilex.httpGetFile('http://www.google.com/images/srpr/logo11w.png', './google-logo.png', function(err, fp) {
        if(err) done(err);

        fs.unlink(fp, function(err) {
          if(err) done(err);
          done();
        });
      });
    });
  });

  describe('jsonLoad()', function() {
    var jsonLoad = utilex.jsonLoad('test/config-test.json');

    it('should load a JSON file', function(done) {
      expect(jsonLoad).to.be.a('object');
      expect(jsonLoad).to.have.property('testKey', 'testVal');
      done();
    });
  });

  describe('strLen()', function() {
    var helloStr      = 'Hello 世界',
        helloStrLen   = utilex.strLen(helloStr),
        helloStrLenB  = utilex.strLen(helloStr, true);

    it('should return correct string length (' + helloStr + ' / 8)', function(done) {
      expect(helloStrLen).to.be.a('number').to.be.equal(8);
      done();
    });

    it('should return correct byte length (' + helloStr + ' / 12)', function(done) {
      expect(helloStrLenB).to.be.a('number').be.equal(12);
      done();
    });
  });

  describe('tasker()', function() {
    it('should run correctly', function(done) {

      var tasker = utilex.tasker();
      tasker.results = [];
      tasker.add({counter: 0});
      tasker.run(function(task, next) {
        tasker.results.push(++task.counter);
        if(task.counter < 5) {
          tasker.add({counter: task.counter});
        }
        next();
      }, function() {
        expect(tasker.results).to.be.a('array').to.be.deep.equal([1,2,3,4,5]);
        done();
      });
    });
  });

  describe('uid()', function() {
    var uid = utilex.uid();

    it('should return a unique id', function(done) {
      expect(uid).to.be.a('string');
      expect(uid).to.have.property('length', 40);
      done();
    });
  });

});<|endoftext|>


<commit_before>/* jslint node: true */
/* global describe: false, it: false */
'use strict';

process.argv.push('--arg1', 'arg1Val', '--arg2', '-arg3', 'arg3Val', 'arg4', 'arg5', '-c', 'test/config-test.json');

var utilex = require('../'),
    fs     = require('fs'),
    expect = require('chai').expect;

// Tests

describe('utilex', function() {

  describe('datetime()', function() {
    var datetime1 = utilex.datetime(),
        datetime2 = utilex.datetime(new Date(1421370000000));

    it('should return a tidy time (' + datetime1 + ')', function(done) {
      expect(datetime1).to.be.a('string');
      done();
    });

    it('should return a tidy time (arg) (' + datetime2 + ')', function(done) {
      expect(datetime2).to.be.a('string').to.be.equal('2015-01-15 20:00:00');
      done();
    });
  });

  describe('conLog()', function() {
    var conLog = utilex.conLog('Tidy log...', false);

    it("should return a tidy log message (" + JSON.stringify(conLog) + ')', function(done) {
      expect(conLog).to.be.a('object');
      expect(conLog).to.have.property('time');
      expect(conLog).to.have.property('message').to.be.equal('Tidy log...');
      done();
    });
  });

  describe('appArgs()', function() {
    var appArgs = utilex.appArgs();

    it('should return command line arguments', function(done) {
      expect(appArgs).to.be.a('object');
      expect(appArgs).to.have.property('arg1', 'arg1Val');
      expect(appArgs).to.have.property('arg2', '');
      expect(appArgs).to.have.property('arg3', 'arg3Val');
      expect(appArgs).to.have.property('arg4', '');
      expect(appArgs).to.have.property('arg5', '');
      expect(appArgs).to.have.property('c', 'test/config-test.json');
      done();
    });
  });

  describe('appConfig()', function() {
    var appConfig = utilex.appConfig();

    it('should return configuration (' + JSON.stringify(appConfig) + ')', function(done) {
      expect(appConfig).to.be.a('object');
      expect(appConfig).to.have.property('file', 'test/config-test.json');
      expect(appConfig).to.have.property('config');
      expect(appConfig.config).to.be.a('object');
      expect(appConfig.config).to.have.property('testKey', 'testVal');
      done();
    });
  });

  describe('strLen()', function() {
    var helloStr      = 'Hello 世界',
        helloStrLen   = utilex.strLen(helloStr),
        helloStrLenB  = utilex.strLen(helloStr, true);

    it('should return correct string length (' + helloStr + ' / 8)', function(done) {
      expect(helloStrLen).to.be.a('number').to.be.equal(8);
      done();
    });

    it('should return correct byte length (' + helloStr + ' / 12)', function(done) {
      expect(helloStrLenB).to.be.a('number').be.equal(12);
      done();
    });
  });

  describe('dirIsWritable()', function() {
    var dirIsWritable = utilex.dirIsWritable(__dirname);

    it('should check whether a directory is writable or not (' + dirIsWritable + ')', function(done) {
      expect(dirIsWritable).to.be.a('boolean');
      done();
    });
  });

  describe('httpGetFile()', function() {
    it('should get a file', function(done) {
      utilex.httpGetFile('http://nodejs.org/images/logo.svg', './nodejs-logo.svg', function(err, fp) {
        if(err) done(err);

        fs.unlink(fp, function(err) {
          if(err) done(err);
          done();
        });
      });
    });
  });

  describe('jsonLoad()', function() {
    var jsonLoad = utilex.jsonLoad('test/config-test.json');

    it('should load a JSON file', function(done) {
      expect(jsonLoad).to.be.a('object');
      expect(jsonLoad).to.have.property('testKey', 'testVal');
      done();
    });
  });

  // Test for asyncFunc
  describe('asyncFunc()', function() {
    it('should run correctly', function(done) {
      utilex.asyncFunc('hello', function(result) {
        expect(result).to.be.a('object');
        expect(result).to.have.property('input').to.be.equal('hello');
        expect(result).to.have.property('execTime').to.be.a('number').to.be.above(0);
        done();
      });
    });

    it('should run correctly (options)', function(done) {
      utilex.asyncFunc('hello', {delay: 99}, function(result) {
        expect(result).to.be.a('object');
        expect(result).to.have.property('input').to.be.equal('hello');
        expect(result).to.have.property('execTime').to.be.equal(99);
        done();
      });
    });
  });

});<commit_msg>Add test for tasker<commit_after>/* jslint node: true */
/* global describe: false, it: false */
'use strict';

process.argv.push('--arg1', 'arg1Val', '--arg2', '-arg3', 'arg3Val', 'arg4', 'arg5', '-c', 'test/config-test.json');

var utilex = require('../'),
    fs     = require('fs'),
    expect = require('chai').expect;

// Tests

describe('utilex', function() {

  describe('datetime()', function() {
    var datetime1 = utilex.datetime(),
        datetime2 = utilex.datetime(new Date(1421370000000));

    it('should return a tidy time (' + datetime1 + ')', function(done) {
      expect(datetime1).to.be.a('string');
      done();
    });

    it('should return a tidy time (arg) (' + datetime2 + ')', function(done) {
      expect(datetime2).to.be.a('string').to.be.equal('2015-01-15 20:00:00');
      done();
    });
  });

  describe('conLog()', function() {
    var conLog = utilex.conLog('Tidy log...', false);

    it("should return a tidy log message (" + JSON.stringify(conLog) + ')', function(done) {
      expect(conLog).to.be.a('object');
      expect(conLog).to.have.property('time');
      expect(conLog).to.have.property('message').to.be.equal('Tidy log...');
      done();
    });
  });

  describe('appArgs()', function() {
    var appArgs = utilex.appArgs();

    it('should return command line arguments', function(done) {
      expect(appArgs).to.be.a('object');
      expect(appArgs).to.have.property('arg1', 'arg1Val');
      expect(appArgs).to.have.property('arg2', '');
      expect(appArgs).to.have.property('arg3', 'arg3Val');
      expect(appArgs).to.have.property('arg4', '');
      expect(appArgs).to.have.property('arg5', '');
      expect(appArgs).to.have.property('c', 'test/config-test.json');
      done();
    });
  });

  describe('appConfig()', function() {
    var appConfig = utilex.appConfig();

    it('should return configuration (' + JSON.stringify(appConfig) + ')', function(done) {
      expect(appConfig).to.be.a('object');
      expect(appConfig).to.have.property('file', 'test/config-test.json');
      expect(appConfig).to.have.property('config');
      expect(appConfig.config).to.be.a('object');
      expect(appConfig.config).to.have.property('testKey', 'testVal');
      done();
    });
  });

  describe('strLen()', function() {
    var helloStr      = 'Hello 世界',
        helloStrLen   = utilex.strLen(helloStr),
        helloStrLenB  = utilex.strLen(helloStr, true);

    it('should return correct string length (' + helloStr + ' / 8)', function(done) {
      expect(helloStrLen).to.be.a('number').to.be.equal(8);
      done();
    });

    it('should return correct byte length (' + helloStr + ' / 12)', function(done) {
      expect(helloStrLenB).to.be.a('number').be.equal(12);
      done();
    });
  });

  describe('dirIsWritable()', function() {
    var dirIsWritable = utilex.dirIsWritable(__dirname);

    it('should check whether a directory is writable or not (' + dirIsWritable + ')', function(done) {
      expect(dirIsWritable).to.be.a('boolean');
      done();
    });
  });

  describe('httpGetFile()', function() {
    it('should get a file', function(done) {
      utilex.httpGetFile('http://nodejs.org/images/logo.svg', './nodejs-logo.svg', function(err, fp) {
        if(err) done(err);

        fs.unlink(fp, function(err) {
          if(err) done(err);
          done();
        });
      });
    });
  });

  describe('jsonLoad()', function() {
    var jsonLoad = utilex.jsonLoad('test/config-test.json');

    it('should load a JSON file', function(done) {
      expect(jsonLoad).to.be.a('object');
      expect(jsonLoad).to.have.property('testKey', 'testVal');
      done();
    });
  });

  // Test for asyncFunc
  describe('asyncFunc()', function() {
    it('should run correctly', function(done) {
      utilex.asyncFunc('hello', function(result) {
        expect(result).to.be.a('object');
        expect(result).to.have.property('input').to.be.equal('hello');
        expect(result).to.have.property('execTime').to.be.a('number').to.be.above(0);
        done();
      });
    });

    it('should run correctly (options)', function(done) {
      utilex.asyncFunc('hello', {delay: 99}, function(result) {
        expect(result).to.be.a('object');
        expect(result).to.have.property('input').to.be.equal('hello');
        expect(result).to.have.property('execTime').to.be.equal(99);
        done();
      });
    });
  });

  describe('tasker()', function() {
    it('should run correctly', function(done) {

      var tasker = utilex.tasker();
      tasker.results = [];
      tasker.add({counter: 0});
      tasker.run(function(task, next) {
        tasker.results.push(++task.counter);
        if(task.counter < 5) {
          tasker.add({counter: task.counter});
        }
        next();
      }, function() {
        expect(tasker.results).to.be.a('array').to.be.deep.equal([1,2,3,4,5]);
        done();
      });
    });
  });

});<|endoftext|>