<commit_before>// call packages hard ballin af
var https      = require('https'),
    http       = require('http'),
    url        = require('url'),
    express    = require('express'),
    app        = express(),
    bodyParser = require('body-parser'),
    parseString = require('xml2js').parseString;

// Use bodyParser() and get data from POST
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());

// Set the port
var port = process.env.PORT || 8080

// API Routes
var router = express.Router();

function getPage(url, callback) {
  var request = http.get(url, function(response) {
    var body = '';

    response.on('data', function(chunk) {
      body += chunk
    });

    response.on('end', function() {
      parseString(body, function (error, result) {
        callback(JSON.parse(result))
      });
    });

  })
}

// The main shit here boys
router.get('/', function(request, response) {
  var apiUrl = "http://api.wolframalpha.com/v2/query?appid=" + process.env.API_KEY + "&input=" + request.query.i + "&format=plaintext";
  getPage(apiUrl, function(json) {
    response.json({result: json})
  });
});

// All routes prefix with /input
app.use('/input', router);

// Start the server man!!
app.listen(port);

// // API:
// // First result (0) contains info on user input
// // Second result contains result/input of input
// // Third result contains misc extra answers such as word value of a #
// // Fourth result contains extra misc shit we don't need to worry abt
// // Fifth result contains even more misc shit. Get to this later
//
// if (result.queryresult.$.success) {
//   // Status returned is gucci
//   try {
//
//     var final = {
//       success: true,
//       type:   result.queryresult.$.datatypes,
//       input:  result.queryresult.pod[0].subpod[0].plaintext[0],
//       result: {
//         plaintext: result.queryresult.pod[1].subpod[0].plaintext[0],
//       }
//     }
//
//     switch(final.type) {
//       case "City,Weather":
//         break
//       case "Math":
//         final["result"]["words"] = result.queryresult.pod[2].subpod[0].plaintext[0]
//         final["result"]["plaintext"] = final["result"]["plaintext"]
//         break
//       case "Food":
//         break
//       case "Word":
//         var plaintext = final.result.plaintext // 1 | noun | the fleshy part of the human body that you sit on
//         var dict = plaintext.split(" | ") // [1, "noun", ]
//
//         delete final["result"]["plaintext"]
//         dict.splice(0, 1);
//
//         final["result"]["word type"]  = dict[0]
//         final["result"]["definition"] = dict[1].replace('\n2', ''); // "the fleshy part of the human body that you sit on"
//         break
//       default:
//     }
//
//     // Shoot of the Jason (best/fav son) response
//     response.json({result: final});
//   } catch(err) {
//     // The fuck did the user search for
//     // Adam's probably fucking around again smh
//     response.json({result: {success: false, input: request.query.i}})
//   }
// }
<commit_msg>slowly getting this shit together<commit_after>// call packages hard ballin af
var https      = require('https'),
    http       = require('http'),
    url        = require('url'),
    express    = require('express'),
    app        = express(),
    bodyParser = require('body-parser'),
    parseString = require('xml2js').parseString;

// Use bodyParser() and get data from POST
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());

// Set the port
var port = process.env.PORT || 8080

// API Routes
var router = express.Router();

function getPage(url, callback) {
  var request = http.get(url, function(response) {
    var body = '';

    response.on('data', function(chunk) {
      body += chunk
    });

    response.on('end', function() {
      parseString(body, function (error, result) {
        callback(result)
      });
    });

  })
}

// The main shit here boys
router.get('/', function(request, response) {
  var apiUrl = "http://api.wolframalpha.com/v2/query?appid=" + process.env.API_KEY + "&input=" + request.query.i + "&format=plaintext";
  getPage(apiUrl, function(json) {
    response.json({result: json})
  });
});

// All routes prefix with /input
app.use('/input', router);

// Start the server man!!
app.listen(port);

// // API:
// // First result (0) contains info on user input
// // Second result contains result/input of input
// // Third result contains misc extra answers such as word value of a #
// // Fourth result contains extra misc shit we don't need to worry abt
// // Fifth result contains even more misc shit. Get to this later
//
// if (result.queryresult.$.success) {
//   // Status returned is gucci
//   try {
//
//     var final = {
//       success: true,
//       type:   result.queryresult.$.datatypes,
//       input:  result.queryresult.pod[0].subpod[0].plaintext[0],
//       result: {
//         plaintext: result.queryresult.pod[1].subpod[0].plaintext[0],
//       }
//     }
//
//     switch(final.type) {
//       case "City,Weather":
//         break
//       case "Math":
//         final["result"]["words"] = result.queryresult.pod[2].subpod[0].plaintext[0]
//         final["result"]["plaintext"] = final["result"]["plaintext"]
//         break
//       case "Food":
//         break
//       case "Word":
//         var plaintext = final.result.plaintext // 1 | noun | the fleshy part of the human body that you sit on
//         var dict = plaintext.split(" | ") // [1, "noun", ]
//
//         delete final["result"]["plaintext"]
//         dict.splice(0, 1);
//
//         final["result"]["word type"]  = dict[0]
//         final["result"]["definition"] = dict[1].replace('\n2', ''); // "the fleshy part of the human body that you sit on"
//         break
//       default:
//     }
//
//     // Shoot of the Jason (best/fav son) response
//     response.json({result: final});
//   } catch(err) {
//     // The fuck did the user search for
//     // Adam's probably fucking around again smh
//     response.json({result: {success: false, input: request.query.i}})
//   }
// }
<|endoftext|>


<commit_before>var _ = require('lodash');
var path = require('path');
var resolve = require('resolve');
var glob = require('glob');

module.exports = GruntBrowserifyRunner;

function GruntBrowserifyRunner(options) {
  this.browserify = options.browserify;
  this.watchify = options.watchify;
  this.logger = options.logger;
  this.writer = options.writer;
  this.firstBuild = true;
}

GruntBrowserifyRunner.prototype = _.create(GruntBrowserifyRunner.prototype, {
  run: function (files, destination, options, next) {
    var self = this;

    //set constructor options and instantiate
    var bOpts = options.browserifyOptions || {};
    bOpts.entries = files;

    // Watchify requires specific arguments
    if(options.watch) {
      bOpts = _.extend({ cache: {}, packageCache: {}, fullPaths: true }, bOpts);
    }

    //determine watchify or browserify
    var b = options.watch ? this.watchify(this.browserify(bOpts)) : this.browserify(bOpts);

    b.on('error', function (err) {
      self.logger.fail.warn(err);
    });

    if(options.bundleOptions) {
      throw new Error('bundleOptions is no longer used. Move all option in browserifyOptions.');
    }

    // merge options.alias with options.require to get only 1 array of required files
    var requiredFiles = _.merge(options.require || [], options.alias || []);
    if (requiredFiles) {
      _.forEach(requiredFiles, function (file) {
        if(file.match(':')) {
          var filePair = file.split(':');
          b.require(filePair[0], {expose: filePair[1]});
        }
        else {
          b.require(file);
        }
      });
    }

    if (options.exclude) {
      _.forEach(options.exclude, function (file) {
        runOptionForGlob(b, 'exclude', file);
      });
    }

    if (options.ignore) {
      _.forEach(options.ignore, function (file) {
        runOptionForGlob(b, 'ignore', file);
      });
    }

    if (options.external) {
      _.forEach(options.external, function (id) {
        //allow externalizing of alias lists
        if (id.match(':')) {
          id = id.split(':')[1];
        }

        if (testForGlob(id)) {
          runOptionForGlob(b, 'external', id);
        }
        else {
          b.external(id);
        }
      });
    }

    if (options.transform) {
      _.forEach(options.transform, function (transformer) {
        if (typeof transformer !== 'object') {
          b.transform(transformer);
        }
        else {
          b.transform(transformer[1], transformer[0]);
        }
      });
    }

    if (options.plugin) {
      _.forEach(options.plugin, function (plugin) {
        if (typeof plugin !== 'object') {
          b.plugin(plugin);
        }
        else {
          b.plugin(plugin[0], plugin[1]);
        }
      });
    }

    var destPath = this.createDestDir(destination);
    var keepAlive = this.keepAliveFn.bind(this, options);
    var done = options.keepAlive? keepAlive : next;
    var bundleComplete = this.onBundleComplete(destination, options, done);

    if (options.watch) {
      var bundleUpdate = this.onBundleComplete(destination, options, keepAlive);
      b.on('update', function (ids) {
        ids.forEach(function (id) {
          self.logger.log.ok(id + ' changed, updating browserify bundle.');
        });
        doBundle(b, options, bundleUpdate);
      });
    }

    doBundle(b, options, bundleComplete);
  },

  createDestDir: function (destination) {
    var destPath = path.dirname(path.resolve(destination));
    if (!this.writer.exists(destPath)) {
      this.writer.mkdir(destPath);
    }
    return destPath;
  },

  keepAliveFn: function (options) {
    this.logger.log.ok('Watchifying...');
  },

  onBundleComplete: function (destination, options, next) {
    var self = this;
    return function (err, buf) {
      if (err) {
        self.logger.log.error(err);
        if (self.firstBuild || !options.keepAlive) {
          self.logger.fail.warn('Error running grunt-browserify.');
        }
      }
      else if (buf) {
        self.writer.write(destination, buf);
      }

      self.firstBuild = false;
      next();
    };
  }
});

function doBundle(browserifyInstance, opts, bundleComplete) {
  if (opts.preBundleCB) {
    opts.preBundleCB(browserifyInstance);
  }

  browserifyInstance.bundle(function (err, buf) {
    if (opts.postBundleCB) {
      opts.postBundleCB(err, buf, bundleComplete);
    }
    else {
      bundleComplete(err, buf);
    }
  });
}

function testForGlob(id) {
  return (/\*/.test(id));
}

function runOptionForGlob(browserifyInstance, method, pattern) {
  var files = glob.sync(pattern);
  if (!files || files.length < 1) {
    //it's not a glob, it's a file / module path
    files = [pattern];
  }
  files.forEach(function (f) {
    browserifyInstance[method].call(browserifyInstance, f);
  });
}
<commit_msg>fixed concat require & alias file by using array.concat instead of _.merge because merge was not giving the right result<commit_after>var _ = require('lodash');
var path = require('path');
var resolve = require('resolve');
var glob = require('glob');

module.exports = GruntBrowserifyRunner;

function GruntBrowserifyRunner(options) {
  this.browserify = options.browserify;
  this.watchify = options.watchify;
  this.logger = options.logger;
  this.writer = options.writer;
  this.firstBuild = true;
}

GruntBrowserifyRunner.prototype = _.create(GruntBrowserifyRunner.prototype, {
  run: function (files, destination, options, next) {
    var self = this;

    //set constructor options and instantiate
    var bOpts = options.browserifyOptions || {};
    bOpts.entries = files;

    // Watchify requires specific arguments
    if(options.watch) {
      bOpts = _.extend({ cache: {}, packageCache: {}, fullPaths: true }, bOpts);
    }

    //determine watchify or browserify
    var b = options.watch ? this.watchify(this.browserify(bOpts)) : this.browserify(bOpts);

    b.on('error', function (err) {
      self.logger.fail.warn(err);
    });

    if(options.bundleOptions) {
      throw new Error('bundleOptions is no longer used. Move all option in browserifyOptions.');
    }

    // concat both array of require and alias
    var requiredFiles = (options.require || []).concat(options.alias || []);
    _.forEach(requiredFiles, function (file) {
      if(file.match(':')) {
        var filePair = file.split(':');
        console.log(filePair)
        b.require(filePair[0], {expose: filePair[1]});
      }
      else {
        b.require(file);
      }
    });

    if (options.exclude) {
      _.forEach(options.exclude, function (file) {
        runOptionForGlob(b, 'exclude', file);
      });
    }

    if (options.ignore) {
      _.forEach(options.ignore, function (file) {
        runOptionForGlob(b, 'ignore', file);
      });
    }

    if (options.external) {
      _.forEach(options.external, function (id) {
        //allow externalizing of alias lists
        if (id.match(':')) {
          id = id.split(':')[1];
        }

        if (testForGlob(id)) {
          runOptionForGlob(b, 'external', id);
        }
        else {
          b.external(id);
        }
      });
    }

    if (options.transform) {
      _.forEach(options.transform, function (transformer) {
        if (typeof transformer !== 'object') {
          b.transform(transformer);
        }
        else {
          b.transform(transformer[1], transformer[0]);
        }
      });
    }

    if (options.plugin) {
      _.forEach(options.plugin, function (plugin) {
        if (typeof plugin !== 'object') {
          b.plugin(plugin);
        }
        else {
          b.plugin(plugin[0], plugin[1]);
        }
      });
    }

    var destPath = this.createDestDir(destination);
    var keepAlive = this.keepAliveFn.bind(this, options);
    var done = options.keepAlive? keepAlive : next;
    var bundleComplete = this.onBundleComplete(destination, options, done);

    if (options.watch) {
      var bundleUpdate = this.onBundleComplete(destination, options, keepAlive);
      b.on('update', function (ids) {
        ids.forEach(function (id) {
          self.logger.log.ok(id + ' changed, updating browserify bundle.');
        });
        doBundle(b, options, bundleUpdate);
      });
    }

    doBundle(b, options, bundleComplete);
  },

  createDestDir: function (destination) {
    var destPath = path.dirname(path.resolve(destination));
    if (!this.writer.exists(destPath)) {
      this.writer.mkdir(destPath);
    }
    return destPath;
  },

  keepAliveFn: function (options) {
    this.logger.log.ok('Watchifying...');
  },

  onBundleComplete: function (destination, options, next) {
    var self = this;
    return function (err, buf) {
      if (err) {
        self.logger.log.error(err);
        if (self.firstBuild || !options.keepAlive) {
          self.logger.fail.warn('Error running grunt-browserify.');
        }
      }
      else if (buf) {
        self.writer.write(destination, buf);
      }

      self.firstBuild = false;
      next();
    };
  }
});

function doBundle(browserifyInstance, opts, bundleComplete) {
  if (opts.preBundleCB) {
    opts.preBundleCB(browserifyInstance);
  }

  browserifyInstance.bundle(function (err, buf) {
    if (opts.postBundleCB) {
      opts.postBundleCB(err, buf, bundleComplete);
    }
    else {
      bundleComplete(err, buf);
    }
  });
}

function testForGlob(id) {
  return (/\*/.test(id));
}

function runOptionForGlob(browserifyInstance, method, pattern) {
  var files = glob.sync(pattern);
  if (!files || files.length < 1) {
    //it's not a glob, it's a file / module path
    files = [pattern];
  }
  files.forEach(function (f) {
    browserifyInstance[method].call(browserifyInstance, f);
  });
}
<|endoftext|>


<commit_before>/*globals define*/
define([
  'utils'
], function( Utils ) {
  'use strict';

  function Input() {
    this.mouse = {
      x: 0,
      y: 0,

      down: false
    };

    this.controls = {
      TOP:    false,
      RIGHT:  false,
      BOTTOM: false,
      LEFT:   false
    };

    this.keys = [];
    this.game = null;

    this.touches = [];

    this.initialTouch = null;
    this.touch = null;

    // Pixel radius where touch difference does nothing.
    this.deadzone = 20;
    // Maximum radius for touch movement.
    this.touchLimit = 100;
  }

  Input.prototype = {
    onKeyDown: function( event ) {
      this.keys[ event.which ] = true;

      // Arrow keys.
      if ( event.which === 37 ||
           event.which === 38 ||
           event.which === 39 ||
           event.which === 40 ) {
        event.preventDefault();
      }
    },

    onKeyUp: function( event ) {
      this.keys[ event.which ] = false;
    },

    /**
     * Accounts for difference between canvas dimensions and
     * computed CSS-specified dimensions, as well as any canvas offsets.
     */
    normalizeTouch: function( event ) {
      var x = event.pageX,
          y = event.pageY;

      if ( this.game ) {
        var canvasWidth  = this.game.canvas.width,
            canvasHeight = this.game.canvas.height;

        var computedStyle = window.getComputedStyle( this.game.canvas );

        var computedWidth  = parseInt( computedStyle.width,  10 ),
            computedHeight = parseInt( computedStyle.height, 10 );

        x *= canvasWidth  / computedWidth;
        y *= canvasHeight / computedHeight;

        x -= this.game.canvas.offsetLeft;
        y -= this.game.canvas.offsetTop;
      }

      return {
        pageX: x,
        pageY: y
      };
    },

    onTouchStart: function( event ) {
      this.touches = [].slice.call( event.touches );
      if ( !this.initialTouch ) {
        this.initialTouch = this.normalizeTouch( this.touches[0] );
      }
    },

    onTouchMove: function( event ) {
      event.preventDefault();
      this.touches = [].slice.call( event.touches );
      this.touch = this.normalizeTouch( this.touches[0] );
    },

    onTouchEnd: function( event ) {
      this.touches = [].slice.call( event.touches );
      if ( !this.touches.length ) {
        this.initialTouch = null;
        this.touch = null;
      }
    },

    update: function( dt ) {
      var controls = this.controls;

      Object.keys( controls ).forEach(function( control ) {
        controls[ control ] = false;
      });

      // Keyboard update.
      if ( this.keys[ 37 ] ) { controls.LEFT   = true; }
      if ( this.keys[ 38 ] ) { controls.TOP    = true; }
      if ( this.keys[ 39 ] ) { controls.RIGHT  = true; }
      if ( this.keys[ 40 ] ) { controls.BOTTOM = true; }

      this.updatePlayer( dt );
    },

    updatePlayer: function( dt ) {
      if ( this.game ) {
        var controls = this.game.input.controls;

        var ax = 0,
            ay = 0;

        if ( controls.LEFT   ) { ax -= 800; }
        if ( controls.RIGHT  ) { ax += 800; }
        if ( controls.TOP    ) { ay -= 800; }
        if ( controls.BOTTOM ) { ay += 800; }

        if ( this.touch ) {
          var x = this.touch.pageX,
              y = this.touch.pageY;

          var xi = this.initialTouch.pageX,
              yi = this.initialTouch.pageY;

          var dx = x - xi,
              dy = y - yi;

          var dz = this.deadzone;

          var angle;
          // Parameters of touch extents.
          var xt, yt;

          if ( Utils.distanceSquared( x, y, xi, yi ) > dz * dz ) {
            angle = Math.atan2( dy, dx );

            dx -= dz * Math.cos( angle );
            dy -= dz * Math.sin( angle );

            xt = ( dx < 0 ? -1 : 1 ) * Utils.inverseLerp( Math.abs( dx ), 0, this.touchLimit );
            yt = ( dy < 0 ? -1 : 1 ) * Utils.inverseLerp( Math.abs( dy ), 0, this.touchLimit );

            ax = xt * 800;
            ay = yt * 800;
          }
        }

        // Move along camera direction.
        var camera = this.game.camera;
        if ( camera.angle ) {
          var cos = Math.cos( -camera.angle ),
              sin = Math.sin( -camera.angle );

          var rax = cos * ax - sin * ay,
              ray = sin * ax + cos * ay;

          ax = rax;
          ay = ray;
        }

        this.game.player.accelerate( ax * dt, ay * dt );
      }
    },

    draw: function( ctx ) {
      if ( this.game && this.initialTouch ) {
        var x = this.initialTouch.pageX,
            y = this.initialTouch.pageY;

        ctx.lineWidth = 8;
        ctx.strokeStyle = 'rgba(0, 0, 0, 0.2)';

        ctx.beginPath();
        ctx.arc( x, y, this.deadzone, 0, Utils.PI2 );

        ctx.moveTo( x + this.touchLimit, y );
        ctx.arc( x, y, this.touchLimit, 0, Utils.PI2 );

        ctx.moveTo( x + this.deadzone + this.touchLimit, y );
        ctx.arc( x, y, this.deadzone + this.touchLimit, 0, Utils.PI2 );
        ctx.stroke();
      }
    }
  };

  return Input;
});
<commit_msg>Fix touch input not using canvas offsets with correct ratios.<commit_after>/*globals define*/
define([
  'utils'
], function( Utils ) {
  'use strict';

  function Input() {
    this.mouse = {
      x: 0,
      y: 0,

      down: false
    };

    this.controls = {
      TOP:    false,
      RIGHT:  false,
      BOTTOM: false,
      LEFT:   false
    };

    this.keys = [];
    this.game = null;

    this.touches = [];

    this.initialTouch = null;
    this.touch = null;

    // Pixel radius where touch difference does nothing.
    this.deadzone = 20;
    // Maximum radius for touch movement.
    this.touchLimit = 100;
  }

  Input.prototype = {
    onKeyDown: function( event ) {
      this.keys[ event.which ] = true;

      // Arrow keys.
      if ( event.which === 37 ||
           event.which === 38 ||
           event.which === 39 ||
           event.which === 40 ) {
        event.preventDefault();
      }
    },

    onKeyUp: function( event ) {
      this.keys[ event.which ] = false;
    },

    /**
     * Accounts for difference between canvas dimensions and
     * computed CSS-specified dimensions, as well as any canvas offsets.
     */
    normalizeTouch: function( event ) {
      var x = event.pageX,
          y = event.pageY;

      if ( this.game ) {
        var canvasWidth  = this.game.canvas.width,
            canvasHeight = this.game.canvas.height;

        var computedStyle = window.getComputedStyle( this.game.canvas );

        var computedWidth  = parseInt( computedStyle.width,  10 ),
            computedHeight = parseInt( computedStyle.height, 10 );

        var xRatio = canvasWidth  / computedWidth,
            yRatio = canvasHeight / computedHeight;

        x -= this.game.canvas.offsetLeft;
        y -= this.game.canvas.offsetTop;

        x *= xRatio;
        y *= yRatio;
      }

      return {
        pageX: x,
        pageY: y
      };
    },

    onTouchStart: function( event ) {
      this.touches = [].slice.call( event.touches );
      if ( !this.initialTouch ) {
        this.initialTouch = this.normalizeTouch( this.touches[0] );
      }
    },

    onTouchMove: function( event ) {
      event.preventDefault();
      this.touches = [].slice.call( event.touches );
      this.touch = this.normalizeTouch( this.touches[0] );
    },

    onTouchEnd: function( event ) {
      this.touches = [].slice.call( event.touches );
      if ( !this.touches.length ) {
        this.initialTouch = null;
        this.touch = null;
      }
    },

    update: function( dt ) {
      var controls = this.controls;

      Object.keys( controls ).forEach(function( control ) {
        controls[ control ] = false;
      });

      // Keyboard update.
      if ( this.keys[ 37 ] ) { controls.LEFT   = true; }
      if ( this.keys[ 38 ] ) { controls.TOP    = true; }
      if ( this.keys[ 39 ] ) { controls.RIGHT  = true; }
      if ( this.keys[ 40 ] ) { controls.BOTTOM = true; }

      this.updatePlayer( dt );
    },

    updatePlayer: function( dt ) {
      if ( this.game ) {
        var controls = this.game.input.controls;

        var ax = 0,
            ay = 0;

        if ( controls.LEFT   ) { ax -= 800; }
        if ( controls.RIGHT  ) { ax += 800; }
        if ( controls.TOP    ) { ay -= 800; }
        if ( controls.BOTTOM ) { ay += 800; }

        if ( this.touch ) {
          var x = this.touch.pageX,
              y = this.touch.pageY;

          var xi = this.initialTouch.pageX,
              yi = this.initialTouch.pageY;

          var dx = x - xi,
              dy = y - yi;

          var dz = this.deadzone;

          var angle;
          // Parameters of touch extents.
          var xt, yt;

          if ( Utils.distanceSquared( x, y, xi, yi ) > dz * dz ) {
            angle = Math.atan2( dy, dx );

            dx -= dz * Math.cos( angle );
            dy -= dz * Math.sin( angle );

            xt = ( dx < 0 ? -1 : 1 ) * Utils.inverseLerp( Math.abs( dx ), 0, this.touchLimit );
            yt = ( dy < 0 ? -1 : 1 ) * Utils.inverseLerp( Math.abs( dy ), 0, this.touchLimit );

            ax = xt * 800;
            ay = yt * 800;
          }
        }

        // Move along camera direction.
        var camera = this.game.camera;
        if ( camera.angle ) {
          var cos = Math.cos( -camera.angle ),
              sin = Math.sin( -camera.angle );

          var rax = cos * ax - sin * ay,
              ray = sin * ax + cos * ay;

          ax = rax;
          ay = ray;
        }

        this.game.player.accelerate( ax * dt, ay * dt );
      }
    },

    draw: function( ctx ) {
      if ( this.game && this.initialTouch ) {
        var x = this.initialTouch.pageX,
            y = this.initialTouch.pageY;

        ctx.lineWidth = 8;
        ctx.strokeStyle = 'rgba(0, 0, 0, 0.2)';

        ctx.beginPath();
        ctx.arc( x, y, this.deadzone, 0, Utils.PI2 );

        ctx.moveTo( x + this.touchLimit, y );
        ctx.arc( x, y, this.touchLimit, 0, Utils.PI2 );

        ctx.moveTo( x + this.deadzone + this.touchLimit, y );
        ctx.arc( x, y, this.deadzone + this.touchLimit, 0, Utils.PI2 );
        ctx.stroke();
      }
    }
  };

  return Input;
});
<|endoftext|>


<commit_before>// https://github.com/tim-smart/node-closure/blob/master/lib/index.js

var JAR_PATH, JAVA_PATH, OPTIONS, path, spawn;

spawn = require('child_process').spawn;

path = require('path');

JAVA_PATH = exports.JAVA_PATH = 'java';

JAR_PATH = exports.JAR_PATH = path.join(__dirname, '../node_modules/google-closure-compiler/compiler.jar');

OPTIONS = exports.OPTIONS = {};

exports.compile = function(input, options, callback) {
  var args, compiler, result, stderr, stdout;
  if ('function' === typeof options) {
    callback = options;
    options = OPTIONS;
  } else {
    result = {};
    Object.keys(OPTIONS).forEach(function(key) {
      return result[key] = OPTIONS[key];
    });
    Object.keys(options).forEach(function(key) {
      return result[key] = options[key];
    });
    options = result;
  }
  args = [];
  if (!options.jar) {
    options.jar = JAR_PATH;
  }
  args.push('-jar');
  args.push(options.jar);
  delete options.jar;
  Object.keys(options).forEach(function(key) {
    var val, value, _i, _len;
    value = options[key];
    if (Array.isArray(value)) {
      for (_i = 0, _len = value.length; _i < _len; _i++) {
        val = value[_i];
        args.push("--" + key);
        args.push(val);
      }
      return;
    }
    args.push("--" + key);
    return args.push(value);
  });
  compiler = spawn(JAVA_PATH, args);
  stdout = '';
  stderr = '';
  compiler.stdout.setEncoding('utf8');
  compiler.stderr.setEncoding('utf8');
  compiler.stdout.on('data', function(data) {
    return stdout += data;
  });
  compiler.stderr.on('data', function(data) {
    return stderr += data;
  });
  compiler.on('exit', function(code) {
    var error;
    if (code !== 0) {
      error = new Error(stderr);
      error.code = code;
    } else {
      error = null;
    }
    return callback(error, stdout, stderr);
  });
  return compiler.stdin.end(input);
};
<commit_msg>Listen for close event rather than exit<commit_after>// https://github.com/tim-smart/node-closure/blob/master/lib/index.js

var JAR_PATH, JAVA_PATH, OPTIONS, path, spawn;

spawn = require('child_process').spawn;

path = require('path');

JAVA_PATH = exports.JAVA_PATH = 'java';

JAR_PATH = exports.JAR_PATH = path.join(__dirname, '../node_modules/google-closure-compiler/compiler.jar');

OPTIONS = exports.OPTIONS = {};

exports.compile = function(input, options, callback) {
  var args, compiler, result, stderr, stdout;
  if ('function' === typeof options) {
    callback = options;
    options = OPTIONS;
  } else {
    result = {};
    Object.keys(OPTIONS).forEach(function(key) {
      return result[key] = OPTIONS[key];
    });
    Object.keys(options).forEach(function(key) {
      return result[key] = options[key];
    });
    options = result;
  }
  args = [];
  if (!options.jar) {
    options.jar = JAR_PATH;
  }
  args.push('-jar');
  args.push(options.jar);
  delete options.jar;
  Object.keys(options).forEach(function(key) {
    var val, value, _i, _len;
    value = options[key];
    if (Array.isArray(value)) {
      for (_i = 0, _len = value.length; _i < _len; _i++) {
        val = value[_i];
        args.push("--" + key);
        args.push(val);
      }
      return;
    }
    args.push("--" + key);
    return args.push(value);
  });
  compiler = spawn(JAVA_PATH, args);
  stdout = '';
  stderr = '';
  compiler.stdout.setEncoding('utf8');
  compiler.stderr.setEncoding('utf8');
  compiler.stdout.on('data', function(data) {
    return stdout += data;
  });
  compiler.stderr.on('data', function(data) {
    return stderr += data;
  });
  compiler.on('close', function(code) {
    var error;
    if (code !== 0) {
      error = new Error(stderr);
      error.code = code;
    } else {
      error = null;
    }
    return callback(error, stdout, stderr);
  });
  return compiler.stdin.end(input);
};
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var EventEmitter = require('events').EventEmitter
  , debug = require('debug')('mocha:runner')
  , Test = require('./test')
  , utils = require('./utils')
  , filter = utils.filter
  , keys = utils.keys
  , noop = function(){};

/**
 * Non-enumerable globals.
 */

var globals = [
  'setTimeout',
  'clearTimeout',
  'setInterval',
  'clearInterval',
  'XMLHttpRequest',
  'Date'
];

/**
 * Expose `Runner`.
 */

module.exports = Runner;

/**
 * Initialize a `Runner` for the given `suite`.
 *
 * Events:
 *
 *   - `start`  execution started
 *   - `end`  execution complete
 *   - `suite`  (suite) test suite execution started
 *   - `suite end`  (suite) all tests (and sub-suites) have finished
 *   - `test`  (test) test execution started
 *   - `test end`  (test) test completed
 *   - `hook`  (hook) hook execution started
 *   - `hook end`  (hook) hook complete
 *   - `pass`  (test) test passed
 *   - `fail`  (test, err) test failed
 *
 * @api public
 */

function Runner(suite) {
  var self = this;
  this._globals = [];
  this.suite = suite;
  this.total = suite.total();
  this.failures = 0;
  this.on('test end', function(test){ self.checkGlobals(test); });
  this.on('hook end', function(hook){ self.checkGlobals(hook); });
  this.grep(/.*/);
  this.globals(this.globalProps().concat(['errno']));
}

/**
 * Inherit from `EventEmitter.prototype`.
 */

Runner.prototype.__proto__ = EventEmitter.prototype;

/**
 * Run tests with full titles matching `re`. Updates runner.total
 * with number of tests matched.
 *
 * @param {RegExp} re
 * @param {Boolean} invert
 * @return {Runner} for chaining
 * @api public
 */

Runner.prototype.grep = function(re, invert){
  debug('grep %s', re);
  this._grep = re;
  this._invert = invert;
  this.total = this.grepTotal(this.suite);
  return this;
};

/**
 * Returns the number of tests matching the grep search for the
 * given suite.
 *
 * @param {Suite} suite
 * @return {Number}
 * @api public
 */

Runner.prototype.grepTotal = function(suite) {
  var self = this;
  var total = 0;

  suite.eachTest(function(test){
    var match = self._grep.test(test.fullTitle());
    if (self._invert) match = !match;
    if (match) total++;
  });

  return total;
};

/**
 * Return a list of global properties.
 *
 * @return {Array}
 * @api private
 */

Runner.prototype.globalProps = function() {
  var props = utils.keys(global);

  // non-enumerables
  for (var i = 0; i < globals.length; ++i) {
    if (~utils.indexOf(props, globals[i])) continue;
    props.push(globals[i]);
  }

  return props;
};

/**
 * Allow the given `arr` of globals.
 *
 * @param {Array} arr
 * @return {Runner} for chaining
 * @api public
 */

Runner.prototype.globals = function(arr){
  if (0 == arguments.length) return this._globals;
  debug('globals %j', arr);
  utils.forEach(arr, function(arr){
    this._globals.push(arr);
  }, this);
  return this;
};

/**
 * Check for global variable leaks.
 *
 * @api private
 */

Runner.prototype.checkGlobals = function(test){
  if (this.ignoreLeaks) return;
  var ok = this._globals;
  var globals = this.globalProps();
  var isNode = process.kill;
  var leaks;

  // check length - 2 ('errno' and 'location' globals)
  if (isNode && 1 == ok.length - globals.length) return
  else if (2 == ok.length - globals.length) return;

  leaks = filterLeaks(ok, globals);
  this._globals = this._globals.concat(leaks);

  if (leaks.length > 1) {
    this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + ''));
  } else if (leaks.length) {
    this.fail(test, new Error('global leak detected: ' + leaks[0]));
  }
};

/**
 * Fail the given `test`.
 *
 * @param {Test} test
 * @param {Error} err
 * @api private
 */

Runner.prototype.fail = function(test, err){
  ++this.failures;
  test.state = 'failed';

  if ('string' == typeof err) {
    err = new Error('the string "' + err + '" was thrown, throw an Error :)');
  }

  this.emit('fail', test, err);
};

/**
 * Fail the given `hook` with `err`.
 *
 * Hook failures (currently) hard-end due
 * to that fact that a failing hook will
 * surely cause subsequent tests to fail,
 * causing jumbled reporting.
 *
 * @param {Hook} hook
 * @param {Error} err
 * @api private
 */

Runner.prototype.failHook = function(hook, err){
  this.fail(hook, err);
  this.emit('end');
};

/**
 * Run hook `name` callbacks and then invoke `fn()`.
 *
 * @param {String} name
 * @param {Function} function
 * @api private
 */

Runner.prototype.hook = function(name, fn){
  var suite = this.suite
    , hooks = suite['_' + name]
    , self = this
    , timer;

  function next(i) {
    var hook = hooks[i];
    if (!hook) return fn();
    self.currentRunnable = hook;

    self.emit('hook', hook);

    hook.on('error', function(err){
      self.failHook(hook, err);
    });

    hook.run(function(err){
      hook.removeAllListeners('error');
      var testError = hook.error();
      if (testError) self.fail(self.test, testError);
      if (err) return self.failHook(hook, err);
      self.emit('hook end', hook);
      next(++i);
    });
  }

  process.nextTick(function(){
    next(0);
  });
};

/**
 * Run hook `name` for the given array of `suites`
 * in order, and callback `fn(err)`.
 *
 * @param {String} name
 * @param {Array} suites
 * @param {Function} fn
 * @api private
 */

Runner.prototype.hooks = function(name, suites, fn){
  var self = this
    , orig = this.suite;

  function next(suite) {
    self.suite = suite;

    if (!suite) {
      self.suite = orig;
      return fn();
    }

    self.hook(name, function(err){
      if (err) {
        self.suite = orig;
        return fn(err);
      }

      next(suites.pop());
    });
  }

  next(suites.pop());
};

/**
 * Run hooks from the top level down.
 *
 * @param {String} name
 * @param {Function} fn
 * @api private
 */

Runner.prototype.hookUp = function(name, fn){
  var suites = [this.suite].concat(this.parents()).reverse();
  this.hooks(name, suites, fn);
};

/**
 * Run hooks from the bottom up.
 *
 * @param {String} name
 * @param {Function} fn
 * @api private
 */

Runner.prototype.hookDown = function(name, fn){
  var suites = [this.suite].concat(this.parents());
  this.hooks(name, suites, fn);
};

/**
 * Return an array of parent Suites from
 * closest to furthest.
 *
 * @return {Array}
 * @api private
 */

Runner.prototype.parents = function(){
  var suite = this.suite
    , suites = [];
  while (suite = suite.parent) suites.push(suite);
  return suites;
};

/**
 * Run the current test and callback `fn(err)`.
 *
 * @param {Function} fn
 * @api private
 */

Runner.prototype.runTest = function(fn){
  var test = this.test
    , self = this;

  if (this.asyncOnly) test.asyncOnly = true;

  try {
    test.on('error', function(err){
      self.fail(test, err);
    });
    test.run(fn);
  } catch (err) {
    fn(err);
  }
};

/**
 * Run tests in the given `suite` and invoke
 * the callback `fn()` when complete.
 *
 * @param {Suite} suite
 * @param {Function} fn
 * @api private
 */

Runner.prototype.runTests = function(suite, fn){
  var self = this
    , tests = suite.tests.slice()
    , test;

  function next(err) {
    // if we bail after first err
    if (self.failures && suite._bail) return fn();

    // next test
    test = tests.shift();

    // all done
    if (!test) return fn();

    // grep
    var match = self._grep.test(test.fullTitle());
    if (self._invert) match = !match;
    if (!match) return next();

    // pending
    if (test.pending) {
      self.emit('pending', test);
      self.emit('test end', test);
      return next();
    }

    // execute test and hook(s)
    self.emit('test', self.test = test);
    self.hookDown('beforeEach', function(){
      self.currentRunnable = self.test;
      self.runTest(function(err){
        test = self.test;

        if (err) {
          self.fail(test, err);
          self.emit('test end', test);
          return self.hookUp('afterEach', next);
        }

        test.state = 'passed';
        self.emit('pass', test);
        self.emit('test end', test);
        self.hookUp('afterEach', next);
      });
    });
  }

  this.next = next;
  next();
};

/**
 * Run the given `suite` and invoke the
 * callback `fn()` when complete.
 *
 * @param {Suite} suite
 * @param {Function} fn
 * @api private
 */

Runner.prototype.runSuite = function(suite, fn){
  var total = this.grepTotal(suite)
    , self = this
    , i = 0;

  debug('run suite %s', suite.fullTitle());

  if (!total) return fn();

  this.emit('suite', this.suite = suite);

  function next() {
    var curr = suite.suites[i++];
    if (!curr) return done();
    self.runSuite(curr, next);
  }

  function done() {
    self.suite = suite;
    self.hook('afterAll', function(){
      self.emit('suite end', suite);
      fn();
    });
  }

  this.hook('beforeAll', function(){
    self.runTests(suite, next);
  });
};

/**
 * Handle uncaught exceptions.
 *
 * @param {Error} err
 * @api private
 */

Runner.prototype.uncaught = function(err){
  debug('uncaught exception %s', err.message);
  var runnable = this.currentRunnable;
  if (!runnable || 'failed' == runnable.state) return;
  runnable.clearTimeout();
  err.uncaught = true;
  this.fail(runnable, err);

  // recover from test
  if ('test' == runnable.type) {
    this.emit('test end', runnable);
    this.hookUp('afterEach', this.next);
    return;
  }

  // bail on hooks
  this.emit('end');
};

/**
 * Run the root suite and invoke `fn(failures)`
 * on completion.
 *
 * @param {Function} fn
 * @return {Runner} for chaining
 * @api public
 */

Runner.prototype.run = function(fn){
  var self = this
    , fn = fn || function(){};

  debug('start');

  // callback
  this.on('end', function(){
    debug('end');
    process.removeListener('uncaughtException', function(err){
      self.uncaught(err);
    });
    fn(self.failures);
  });

  // run suites
  this.emit('start');
  this.runSuite(this.suite, function(){
    debug('finished running');
    self.emit('end');
  });

  // uncaught exception
  process.on('uncaughtException', function(err){
    self.uncaught(err);
  });

  return this;
};

/**
 * Filter leaks with the given globals flagged as `ok`.
 *
 * @param {Array} ok
 * @param {Array} globals
 * @return {Array}
 * @api private
 */

function filterLeaks(ok, globals) {
  return filter(globals, function(key){
    var matched = filter(ok, function(ok){
      if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]);
      // Opera and IE expose global variables for HTML element IDs (issue #243)
      if (/^mocha-/.test(key)) return true;
      return key == ok;
    });
    return matched.length == 0 && (!global.navigator || 'onerror' !== key);
  });
}
<commit_msg>JohnQ: Fix for issue where uncaught exception listener was not being properly removed.  - Occurs when you re-run a test suite with uncaught exceptions multiple times.  - Store the uncaught function, and remove it properly.<commit_after>
/**
 * Module dependencies.
 */

var EventEmitter = require('events').EventEmitter
  , debug = require('debug')('mocha:runner')
  , Test = require('./test')
  , utils = require('./utils')
  , filter = utils.filter
  , keys = utils.keys
  , noop = function(){};

/**
 * Non-enumerable globals.
 */

var globals = [
  'setTimeout',
  'clearTimeout',
  'setInterval',
  'clearInterval',
  'XMLHttpRequest',
  'Date'
];

/**
 * Expose `Runner`.
 */

module.exports = Runner;

/**
 * Initialize a `Runner` for the given `suite`.
 *
 * Events:
 *
 *   - `start`  execution started
 *   - `end`  execution complete
 *   - `suite`  (suite) test suite execution started
 *   - `suite end`  (suite) all tests (and sub-suites) have finished
 *   - `test`  (test) test execution started
 *   - `test end`  (test) test completed
 *   - `hook`  (hook) hook execution started
 *   - `hook end`  (hook) hook complete
 *   - `pass`  (test) test passed
 *   - `fail`  (test, err) test failed
 *
 * @api public
 */

function Runner(suite) {
  var self = this;
  this._globals = [];
  this.suite = suite;
  this.total = suite.total();
  this.failures = 0;
  this.on('test end', function(test){ self.checkGlobals(test); });
  this.on('hook end', function(hook){ self.checkGlobals(hook); });
  this.grep(/.*/);
  this.globals(this.globalProps().concat(['errno']));
}

/**
 * Inherit from `EventEmitter.prototype`.
 */

Runner.prototype.__proto__ = EventEmitter.prototype;

/**
 * Run tests with full titles matching `re`. Updates runner.total
 * with number of tests matched.
 *
 * @param {RegExp} re
 * @param {Boolean} invert
 * @return {Runner} for chaining
 * @api public
 */

Runner.prototype.grep = function(re, invert){
  debug('grep %s', re);
  this._grep = re;
  this._invert = invert;
  this.total = this.grepTotal(this.suite);
  return this;
};

/**
 * Returns the number of tests matching the grep search for the
 * given suite.
 *
 * @param {Suite} suite
 * @return {Number}
 * @api public
 */

Runner.prototype.grepTotal = function(suite) {
  var self = this;
  var total = 0;

  suite.eachTest(function(test){
    var match = self._grep.test(test.fullTitle());
    if (self._invert) match = !match;
    if (match) total++;
  });

  return total;
};

/**
 * Return a list of global properties.
 *
 * @return {Array}
 * @api private
 */

Runner.prototype.globalProps = function() {
  var props = utils.keys(global);

  // non-enumerables
  for (var i = 0; i < globals.length; ++i) {
    if (~utils.indexOf(props, globals[i])) continue;
    props.push(globals[i]);
  }

  return props;
};

/**
 * Allow the given `arr` of globals.
 *
 * @param {Array} arr
 * @return {Runner} for chaining
 * @api public
 */

Runner.prototype.globals = function(arr){
  if (0 == arguments.length) return this._globals;
  debug('globals %j', arr);
  utils.forEach(arr, function(arr){
    this._globals.push(arr);
  }, this);
  return this;
};

/**
 * Check for global variable leaks.
 *
 * @api private
 */

Runner.prototype.checkGlobals = function(test){
  if (this.ignoreLeaks) return;
  var ok = this._globals;
  var globals = this.globalProps();
  var isNode = process.kill;
  var leaks;

  // check length - 2 ('errno' and 'location' globals)
  if (isNode && 1 == ok.length - globals.length) return
  else if (2 == ok.length - globals.length) return;

  leaks = filterLeaks(ok, globals);
  this._globals = this._globals.concat(leaks);

  if (leaks.length > 1) {
    this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + ''));
  } else if (leaks.length) {
    this.fail(test, new Error('global leak detected: ' + leaks[0]));
  }
};

/**
 * Fail the given `test`.
 *
 * @param {Test} test
 * @param {Error} err
 * @api private
 */

Runner.prototype.fail = function(test, err){
  ++this.failures;
  test.state = 'failed';

  if ('string' == typeof err) {
    err = new Error('the string "' + err + '" was thrown, throw an Error :)');
  }

  this.emit('fail', test, err);
};

/**
 * Fail the given `hook` with `err`.
 *
 * Hook failures (currently) hard-end due
 * to that fact that a failing hook will
 * surely cause subsequent tests to fail,
 * causing jumbled reporting.
 *
 * @param {Hook} hook
 * @param {Error} err
 * @api private
 */

Runner.prototype.failHook = function(hook, err){
  this.fail(hook, err);
  this.emit('end');
};

/**
 * Run hook `name` callbacks and then invoke `fn()`.
 *
 * @param {String} name
 * @param {Function} function
 * @api private
 */

Runner.prototype.hook = function(name, fn){
  var suite = this.suite
    , hooks = suite['_' + name]
    , self = this
    , timer;

  function next(i) {
    var hook = hooks[i];
    if (!hook) return fn();
    self.currentRunnable = hook;

    self.emit('hook', hook);

    hook.on('error', function(err){
      self.failHook(hook, err);
    });

    hook.run(function(err){
      hook.removeAllListeners('error');
      var testError = hook.error();
      if (testError) self.fail(self.test, testError);
      if (err) return self.failHook(hook, err);
      self.emit('hook end', hook);
      next(++i);
    });
  }

  process.nextTick(function(){
    next(0);
  });
};

/**
 * Run hook `name` for the given array of `suites`
 * in order, and callback `fn(err)`.
 *
 * @param {String} name
 * @param {Array} suites
 * @param {Function} fn
 * @api private
 */

Runner.prototype.hooks = function(name, suites, fn){
  var self = this
    , orig = this.suite;

  function next(suite) {
    self.suite = suite;

    if (!suite) {
      self.suite = orig;
      return fn();
    }

    self.hook(name, function(err){
      if (err) {
        self.suite = orig;
        return fn(err);
      }

      next(suites.pop());
    });
  }

  next(suites.pop());
};

/**
 * Run hooks from the top level down.
 *
 * @param {String} name
 * @param {Function} fn
 * @api private
 */

Runner.prototype.hookUp = function(name, fn){
  var suites = [this.suite].concat(this.parents()).reverse();
  this.hooks(name, suites, fn);
};

/**
 * Run hooks from the bottom up.
 *
 * @param {String} name
 * @param {Function} fn
 * @api private
 */

Runner.prototype.hookDown = function(name, fn){
  var suites = [this.suite].concat(this.parents());
  this.hooks(name, suites, fn);
};

/**
 * Return an array of parent Suites from
 * closest to furthest.
 *
 * @return {Array}
 * @api private
 */

Runner.prototype.parents = function(){
  var suite = this.suite
    , suites = [];
  while (suite = suite.parent) suites.push(suite);
  return suites;
};

/**
 * Run the current test and callback `fn(err)`.
 *
 * @param {Function} fn
 * @api private
 */

Runner.prototype.runTest = function(fn){
  var test = this.test
    , self = this;

  if (this.asyncOnly) test.asyncOnly = true;

  try {
    test.on('error', function(err){
      self.fail(test, err);
    });
    test.run(fn);
  } catch (err) {
    fn(err);
  }
};

/**
 * Run tests in the given `suite` and invoke
 * the callback `fn()` when complete.
 *
 * @param {Suite} suite
 * @param {Function} fn
 * @api private
 */

Runner.prototype.runTests = function(suite, fn){
  var self = this
    , tests = suite.tests.slice()
    , test;

  function next(err) {
    // if we bail after first err
    if (self.failures && suite._bail) return fn();

    // next test
    test = tests.shift();

    // all done
    if (!test) return fn();

    // grep
    var match = self._grep.test(test.fullTitle());
    if (self._invert) match = !match;
    if (!match) return next();

    // pending
    if (test.pending) {
      self.emit('pending', test);
      self.emit('test end', test);
      return next();
    }

    // execute test and hook(s)
    self.emit('test', self.test = test);
    self.hookDown('beforeEach', function(){
      self.currentRunnable = self.test;
      self.runTest(function(err){
        test = self.test;

        if (err) {
          self.fail(test, err);
          self.emit('test end', test);
          return self.hookUp('afterEach', next);
        }

        test.state = 'passed';
        self.emit('pass', test);
        self.emit('test end', test);
        self.hookUp('afterEach', next);
      });
    });
  }

  this.next = next;
  next();
};

/**
 * Run the given `suite` and invoke the
 * callback `fn()` when complete.
 *
 * @param {Suite} suite
 * @param {Function} fn
 * @api private
 */

Runner.prototype.runSuite = function(suite, fn){
  var total = this.grepTotal(suite)
    , self = this
    , i = 0;

  debug('run suite %s', suite.fullTitle());

  if (!total) return fn();

  this.emit('suite', this.suite = suite);

  function next() {
    var curr = suite.suites[i++];
    if (!curr) return done();
    self.runSuite(curr, next);
  }

  function done() {
    self.suite = suite;
    self.hook('afterAll', function(){
      self.emit('suite end', suite);
      fn();
    });
  }

  this.hook('beforeAll', function(){
    self.runTests(suite, next);
  });
};

/**
 * Handle uncaught exceptions.
 *
 * @param {Error} err
 * @api private
 */

Runner.prototype.uncaught = function(err){
  debug('uncaught exception %s', err.message);
  var runnable = this.currentRunnable;
  if (!runnable || 'failed' == runnable.state) return;
  runnable.clearTimeout();
  err.uncaught = true;
  this.fail(runnable, err);

  // recover from test
  if ('test' == runnable.type) {
    this.emit('test end', runnable);
    this.hookUp('afterEach', this.next);
    return;
  }

  // bail on hooks
  this.emit('end');
};

/**
 * Run the root suite and invoke `fn(failures)`
 * on completion.
 *
 * @param {Function} fn
 * @return {Runner} for chaining
 * @api public
 */

Runner.prototype.run = function(fn){
  var self = this
    , fn = fn || function(){}
    , uncaught = function(err){
      self.uncaught(err);
    };

  debug('start');

  // callback
  this.on('end', function(){
    debug('end');
    process.removeListener('uncaughtException', uncaught);
    fn(self.failures);
  });

  // run suites
  this.emit('start');
  this.runSuite(this.suite, function(){
    debug('finished running');
    self.emit('end');
  });

  // uncaught exception
  process.on('uncaughtException', uncaught);

  return this;
};

/**
 * Filter leaks with the given globals flagged as `ok`.
 *
 * @param {Array} ok
 * @param {Array} globals
 * @return {Array}
 * @api private
 */

function filterLeaks(ok, globals) {
  return filter(globals, function(key){
    var matched = filter(ok, function(ok){
      if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]);
      // Opera and IE expose global variables for HTML element IDs (issue #243)
      if (/^mocha-/.test(key)) return true;
      return key == ok;
    });
    return matched.length == 0 && (!global.navigator || 'onerror' !== key);
  });
}
<|endoftext|>


<commit_before>
// Copyright (c) 2015 The Forest (Sander Pacheco Hernández)

// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

// Variables de librerias
var gulp = require('gulp'), // Lp
	autoprefixer = require('gulp-autoprefixer'),
	concat = require('gulp-concat'),
	jade = require('gulp-jade'),
	minifyCss= require('gulp-minify-css'),
	rename = require('gulp-rename'),
	sass = require('gulp-sass'),
	uglify = require('gulp-uglify'),
	usemin = require('gulp-usemin'),
	watch = require('gulp-watch'),
	browserSync = require('browser-sync'),
	reload = browserSync.reload;

// Directorios del proyecto
var proyecto = {
	imagenes: './src/img/**/*.*',
	componentes: './src/components/**',
	fuentes: './src/fuentes/**/*.{ttf,woff,eof,svg}',
	sass: './src/scss/*.scss',
	js: './src/js/**/*.js',
	raiz: './src/jade/*.jade',
	templ: './src/jade/templ/**/*.jade'
};

// Directorio final del proyecto (dist)
var produccion = {
	imagenes: './dist/img',
	librerias: './dist/lib',
	estilos: './dist/css',
	js: './dist/js',
	dist: './dist/',
	templ: './dist/templ/',
	//usemin
	index: './dist/index.html'
};

gulp.task('img', function () {
	return gulp.src(proyecto.imagenes)
		.pipe(gulp.dest(produccion.imagenes));
})

// Fuentes
gulp.task('fuentes', function () {
	return gulp.src(proyecto.fuentes)
		.pipe(rename({
			dirname: '/fonts'
		}))
		.pipe(gulp.dest(produccion.librerias));
});

// static assets
gulp.task('componentes', function () {
	return gulp.src(proyecto.componentes)
		.pipe(rename({
			dirname: '/components'
		}))
		.pipe(gulp.dest(produccion.dist));
})

// Comprimiendo SASS -      .pipe(watch(proyecto.sass))
gulp.task('sass', function () {
	return gulp.src(proyecto.sass)
		.pipe(sass())
		.pipe(autoprefixer('> 5%'))
		.pipe(concat('main.min.css'))
		.pipe(gulp.dest(produccion.estilos));
});

// Comprimiendo js
gulp.task('js', function () {
	return gulp.src(proyecto.js)
		.pipe(uglify())
		.pipe(concat('main.min.js'))
		.pipe(gulp.dest(produccion.js));
})

//Jade a html
gulp.task('raiz', function () {
	return gulp.src(proyecto.raiz)
		.pipe(jade({
			'pretty':true
		}))
		.pipe(gulp.dest(produccion.dist))
})

gulp.task('templ', function  () {
	return gulp.src(proyecto.templ)
		.pipe(jade({
			'pretty':true
		}))
		.pipe(gulp.dest(produccion.templ))
})

gulp.task('usemin', function () {
	return gulp.src(produccion.index)
		.pipe(usemin({
			js:[uglify(), 'concat'],
			css: [minifyCss({keepSpecialComments: 0}), 'concat']
		}))
		.pipe(gulp.dest(produccion.dist));
})

gulp.task('watch', function () {
	gulp.watch([proyecto.componentes], ['componentes'], reload({stream:true}));
	gulp.watch([proyecto.sass], ['sass'], reload({stream:true}));
	gulp.watch([proyecto.raiz, proyecto.templ], ['raiz', 'templ'], reload({stream:true}));
	gulp.watch([proyecto.imagenes], ['img'], reload({stream:true}));
	gulp.watch([proyecto.js], ['js'], reload({stream:true}));
})

gulp.task('server', function() {
	browserSync({
		//logConnections: false,
		//logFileChanges: false,
		notify: true,
		open: false,
		server: {
			baseDir: produccion.dist
		}
	});
});

gulp.task('build-custom', ['img', 'componentes', 'fuentes', 'sass', 'js', 'raiz', 'templ']);
gulp.task('build', ['usemin', 'build-custom'])
gulp.task('default', ['build', 'watch']);
<commit_msg>pequeño cambio<commit_after>
// Copyright (c) 2015 The Forest (Sander Pacheco Hernández)

// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

// Variables de librerias
var gulp = require('gulp'), // Lp
	autoprefixer = require('gulp-autoprefixer'),
	concat = require('gulp-concat'),
	jade = require('gulp-jade'),
	minifyCss= require('gulp-minify-css'),
	rename = require('gulp-rename'),
	sass = require('gulp-sass'),
	uglify = require('gulp-uglify'),
	usemin = require('gulp-usemin'),
	watch = require('gulp-watch'),
	browserSync = require('browser-sync'),
	reload = browserSync.reload;

// Directorios del proyecto
var proyecto = {
	imagenes: './src/img/**/*.*',
	componentes: './src/components/**',
	fuentes: './src/fuentes/**/*.{ttf,woff,eof,svg}',
	sass: './src/scss/*.scss',
	js: './src/js/**/*.js',
	raiz: './src/jade/*.jade',
	templ: './src/jade/templ/**/*.jade'
};

// Directorio final del proyecto (dist)
var produccion = {
	imagenes: './dist/img',
	librerias: './dist/lib',
	estilos: './dist/css',
	js: './dist/js',
	dist: './dist/',
	templ: './dist/templ/',
	//usemin
	index: './dist/index.html'
};

gulp.task('img', function () {
	return gulp.src(proyecto.imagenes)
		.pipe(gulp.dest(produccion.imagenes));
})

// Fuentes
gulp.task('fuentes', function () {
	return gulp.src(proyecto.fuentes)
		.pipe(rename({
			dirname: '/fonts'
		}))
		.pipe(gulp.dest(produccion.librerias));
});

// static assets
gulp.task('componentes', function () {
	return gulp.src(proyecto.componentes)
		.pipe(rename({
			dirname: '/components'
		}))
		.pipe(gulp.dest(produccion.dist));
})

// Comprimiendo SASS
gulp.task('sass', function () {
	return gulp.src(proyecto.sass)
		.pipe(sass())
		.pipe(autoprefixer('> 5%'))
		.pipe(concat('main.min.css'))
		.pipe(gulp.dest(produccion.estilos));
});

// Comprimiendo js
gulp.task('js', function () {
	return gulp.src(proyecto.js)
		.pipe(uglify())
		.pipe(concat('main.min.js'))
		.pipe(gulp.dest(produccion.js));
})

//Jade a html
gulp.task('raiz', function () {
	return gulp.src(proyecto.raiz)
		.pipe(jade({
			'pretty':true
		}))
		.pipe(gulp.dest(produccion.dist))
})

gulp.task('templ', function  () {
	return gulp.src(proyecto.templ)
		.pipe(jade({
			'pretty':true
		}))
		.pipe(gulp.dest(produccion.templ))
})

gulp.task('usemin', function () {
	return gulp.src(produccion.index)
		.pipe(usemin({
			js:[uglify(), 'concat'],
			css: [minifyCss({keepSpecialComments: 0}), 'concat']
		}))
		.pipe(gulp.dest(produccion.dist));
})

gulp.task('watch', function () {
	gulp.watch([proyecto.componentes], ['componentes'], reload({stream:true}));
	gulp.watch([proyecto.sass], ['sass'], reload({stream:true}));
	gulp.watch([proyecto.raiz, proyecto.templ], ['raiz', 'templ'], reload({stream:true}));
	gulp.watch([proyecto.imagenes], ['img'], reload({stream:true}));
	gulp.watch([proyecto.js], ['js'], reload({stream:true}));
})

gulp.task('server', function() {
	browserSync({
		//logConnections: false,
		//logFileChanges: false,
		notify: true,
		open: false,
		server: {
			baseDir: produccion.dist
		}
	});
});

gulp.task('build-custom', ['img', 'componentes', 'fuentes', 'sass', 'js', 'raiz', 'templ']);
gulp.task('build', ['usemin', 'build-custom'])
gulp.task('default', ['build', 'watch']);
<|endoftext|>


<commit_before>var benchmarkUtils = require('./benchmark-utils');
var EventsHandler = require('./events-handler');
var giveMe = require('give-me');
var Timer = require('./timer.js');
var _ = require('underscore');

module.exports = function(options){

  this.steps = [];
  this.results = [];
  this.options = options;

  this.add = function(stepName, href, func){
    var self = this;

    var step = {
      name: stepName,
      func: func,
      href: href,
      stats: {
        sample: []
      }
    };

    step.run = function(callback){

      var isSequence = !self.options.runMode || self.options.runMode == 'sequence',
          maxConcurrent = isSequence ? 1 : self.options.maxConcurrentRequests,
          totalRequests = self.options.minSamples,
          cycleLength = (maxConcurrent && totalRequests > maxConcurrent) ? maxConcurrent : totalRequests,
          cycleDelay = isSequence ? self.options.delay : 0;
          callbackDone = false,
          globalTimer = new Timer(),
          sampled = 0,
          i = 0;

      var runNextSample = function(){
        if(isSequence)
          globalTimer.start();
        self.runSample(step.func, sampleDone, i);
        i++;
      };

      var sampleDone = function(sample, pos){

        var currentGlobalTime = self.getCurrentTime(globalTimer, isSequence),
            maxTime = self.options.maxTime;

        step.stats.sample[pos] = sample;
        sampled++;

        if(!callbackDone && totalRequests > i && currentGlobalTime < maxTime){
          setTimeout(runNextSample, cycleDelay);
        } else if(!callbackDone && (sampled == totalRequests || currentGlobalTime >= maxTime)) {
          callbackDone = true;
          callback(self.addResult(step));
        }
      };

      globalTimer.start();

      for(i = 0; i < cycleLength; i++)
        (self.runSample)(step.func, sampleDone, i);

    };
    this.steps.push(step);
  };

  this.runSample = function(func, c, i){
    var timer = new Timer();
    timer.start();
    func(function(){
      c(timer.get(), i);
    });
  };

  this.getCurrentTime = function(timer, isSequence){
    if(isSequence){
      timer.stop();
      return timer.time;
    }
    return timer.get();
  };

  this.addResult = function(step){
    step.stats.sample = _.compact(step.stats.sample);
    var result = benchmarkUtils.getRelevantFields(_.pick(step, 'name', 'href', 'stats'));
    this.results.push(result);
    this.emit('cycle', benchmarkUtils.cycleMessage(result));
    return step;
  };

  this.run = function(){
    var self = this;

    giveMe.sequence(_.map(this.steps, function(step){ return step.run; }), function(callbacks){

      var results = {};
      _.forEach(self.results, function(result, i){ results[i] = result; });

      var sorted = _.compose(benchmarkUtils.sort, benchmarkUtils.getSuccessful)(results);

      if(sorted.length > 1){
        _.find(results, function(result){ return result.name == sorted[0].name}).isFastest = true;
        _.find(results, function(result){ return result.name == sorted[sorted.length - 1].name}).isSlowest = true;
      }

      self.emit('complete', results);
    });
  };

  return _.extend(this, new EventsHandler());
};<commit_msg>Scoping sequence step<commit_after>var benchmarkUtils = require('./benchmark-utils');
var EventsHandler = require('./events-handler');
var giveMe = require('give-me');
var Timer = require('./timer.js');
var _ = require('underscore');

module.exports = function(options){

  this.steps = [];
  this.results = [];
  this.options = options;

  this.add = function(stepName, href, func){
    var self = this;

    var step = {
      name: stepName,
      func: func,
      href: href,
      stats: {
        sample: []
      }
    };

    step.run = function(callback){

      var isSequence = !self.options.runMode || self.options.runMode == 'sequence',
          maxConcurrent = isSequence ? 1 : self.options.maxConcurrentRequests,
          totalRequests = self.options.minSamples,
          cycleLength = (maxConcurrent && totalRequests > maxConcurrent) ? maxConcurrent : totalRequests,
          cycleDelay = isSequence ? self.options.delay : 0;
          callbackDone = false,
          globalTimer = new Timer(),
          sampled = 0,
          i = 0;

      var runNextSample = function(){
        if(isSequence)
          globalTimer.start();
        self.runSample(step.func, sampleDone, i);
        i++;
      };

      var sampleDone = function(sample, pos){

        var currentGlobalTime = self.getCurrentTime(globalTimer, isSequence),
            maxTime = self.options.maxTime;

        step.stats.sample[pos] = sample;
        sampled++;

        if(!callbackDone && totalRequests > i && currentGlobalTime < maxTime){
          setTimeout(runNextSample, cycleDelay);
        } else if(!callbackDone && (sampled == totalRequests || currentGlobalTime >= maxTime)) {
          callbackDone = true;
          callback(self.addResult(step));
        }
      };

      globalTimer.start();

      for(i = 0; i < cycleLength; i++)
        (self.runSample)(step.func, sampleDone, i);

    };
    this.steps.push(step);
  };

  this.runSample = function(func, c, i){
    var timer = new Timer();
    timer.start();
    func(function(){
      c(timer.get(), i);
    });
  };

  this.getCurrentTime = function(timer, isSequence){
    if(isSequence){
      timer.stop();
      return timer.time;
    }
    return timer.get();
  };

  this.addResult = function(step){
    step.stats.sample = _.compact(step.stats.sample);
    var result = benchmarkUtils.getRelevantFields(_.pick(step, 'name', 'href', 'stats'));
    this.results.push(result);
    this.emit('cycle', benchmarkUtils.cycleMessage(result));
    return step;
  };

  this.run = function(){
    var self = this;

    giveMe.sequence(_.map(this.steps, function(step){ return _.bind(step.run, step); }), function(callbacks){

      var results = {};
      _.forEach(self.results, function(result, i){ results[i] = result; });

      var sorted = _.compose(benchmarkUtils.sort, benchmarkUtils.getSuccessful)(results);

      if(sorted.length > 1){
        _.find(results, function(result){ return result.name == sorted[0].name}).isFastest = true;
        _.find(results, function(result){ return result.name == sorted[sorted.length - 1].name}).isSlowest = true;
      }

      self.emit('complete', results);
    });
  };

  return _.extend(this, new EventsHandler());
};<|endoftext|>


<commit_before>// ---------- Plugins and paths ----------

var gulp = require("gulp"),
    autoprefixer = require("gulp-autoprefixer"),
    clean = require("gulp-clean"),
    zip = require("gulp-zip"),
    concat = require("gulp-concat"),
    rename = require("gulp-rename"),
    //uglify = require("gulp-uglify"),
    sass = require("gulp-sass"),
    cssnano = require("gulp-cssnano"),
    htmlreplace = require("gulp-html-replace"),
    eslint = require("gulp-eslint"),
    scsslint = require("gulp-scss-lint"),
    bump = require("gulp-bump"),
    tag_version = require("gulp-tag-version"),
    paths = {
        // All JS files - for linting
        allscripts : ["src/app/**/*.js", "gulpfile.js"],
        // Only source JS files - for building the artefact
        appscripts : ["src/app/app.module.js", "src/app/**/*.js"],
        // All scss files - for linting
        allstyles  : "src/assets/styles/**/*.scss",
        // Only the main scss file - for building the artefact
        appstyles  : "src/assets/styles/app.styles.scss",
        // All image files
        images     : "src/assets/images/**/*.*",
        // The config settings for the app
        config     : "src/app/app.config.json"
    };

// ---------- Code lint and tidy up tasks ----------

// Clean /dist and remove everything
gulp.task("clean", function () {
  return gulp.src("dist/*", {read:false})
    .pipe(clean({
        force : true
    }));
});

// Check the JS code against ESLint standards
gulp.task("eslint", function() {
  return gulp.src(paths.allscripts).pipe(eslint({
    extends : "eslint:recommended",
    rules : {
        "quotes" : [1, "double"],
        "semi"   : [1, "always"]
    },
    globals : {
        "angular"     : true,
        "carousel"    : true,
        "document"    : true,
        "setTimeout"  : true,
        "require"     : true
    }
  }))
  .pipe(eslint.format())
  .pipe(eslint.failOnError()); // Fail task on lint errors
});

// Check the SCSS code against scss-lint standards
gulp.task("scsslint", function() {
  return gulp.src(paths.allstyles)
    .pipe(scsslint())
    .pipe(scsslint.failReporter()); // Report failures in the console
});

// Combination task which checks the .js and .scss files against coding standards
gulp.task("code-check", ["eslint", "scsslint"]);

// ---------- Production build tasks ----------

// Build an artefact and zip everything up
gulp.task("build", ["scripts", "bower_components", "styles", "html", "images", "index", "config", "php", "misc"], function() {
  return gulp.src("dist/**/**")
    .pipe(zip("iframe-carousel.zip"))
    .pipe(gulp.dest("dist"));
});

// Combine all the src JS, minify and then uglify
gulp.task("scripts", function() {
  return gulp.src(paths.appscripts)
    .pipe(concat("app.js"))
    .pipe(gulp.dest("dist"))
    .pipe(rename("app.min.js"))
    //.pipe(uglify()) // Causes problems loading bower.json
    .pipe(gulp.dest("dist"));
});

// Combine sccs into one file, compile into css, minify
gulp.task("styles", function() {
  return gulp.src(paths.appstyles)
    .pipe(sass().on("error", sass.logError)) // Log sass errors
    .pipe(autoprefixer({browsers: ["last 10 versions", "> 10%", "ie >= 11"]}))
    .pipe(concat("app.min.css"))
    .pipe(cssnano())
    .pipe(gulp.dest("dist"));
});

// Move all the html into /dist
gulp.task("html", function() {
  return gulp.src("src/app/**/*.html")
    .pipe(gulp.dest("dist/src/app"));
});

// Move all the php into /dist
gulp.task("php", function() {
  return gulp.src("src/app/**/*.php")
    .pipe(gulp.dest("dist/src/app"));
});

// Move the images into /dist
gulp.task("images", function() {
  return gulp.src(paths.images)
    .pipe(gulp.dest("dist/src/assets/images/"));
});

// Move the app config into /dist
gulp.task("config", function() {
  return gulp.src(paths.config)
    .pipe(gulp.dest("dist/src/app"));
});

// Move index.html into /dist and replace the filepaths as required
gulp.task("index", function() {
  return gulp.src("index.html")
    .pipe(htmlreplace({
        "css" : "app.min.css",
        "js"  : "app.min.js"
    }))
    .pipe(gulp.dest("dist"));
});

// Copy all the required bower dependencies into /dist
gulp.task("bower_components", function() {
  return gulp.src(["bower_components/angular/angular.min.js",
                   "bower_components/angular-animate/angular-animate.min.js",
                   "bower_components/angular-aria/angular-aria.min.js",
                   "bower_components/angular-material/angular-material.min.js",
                   "bower_components/angular-route/angular-route.min.js",
                   "bower_components/angular-material/angular-material.min.css",
                   "bower_components/font-awesome/**"],
                   {base : "bower_components/"})
    .pipe(gulp.dest("dist/bower_components"));
});

// Move other misc files into /dist
gulp.task("misc", function() {
  return gulp.src(["bower.json", "package.json", "README.md"])
    .pipe(gulp.dest("dist/"));
});

// ---------- Local development build tasks ----------

// Compiles scss into css without minifying so debugging is easier
gulp.task("styles-dev", function() {
  return gulp.src(paths.appstyles)
    .pipe(concat("app.scss"))
    .pipe(sass().on("error", sass.logError))
    .pipe(autoprefixer({browsers: ["last 10 versions", "> 10%", "ie >= 11"]}))
    .pipe(rename("app.styles.css"))
    .pipe(gulp.dest("dist"));
});

// ---------- Bump version number tasks ----------

// Pre-release update for bower and npm versions
gulp.task("bump-prerelease", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type  : "prerelease",
        preid : "SNAPSHOT"
    }))
  .pipe(gulp.dest("./"));
});

// Micro update for bower and npm versions
gulp.task("bump-patch", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "patch"
    }))
  .pipe(gulp.dest("./"));
});

// Minor update for bower and npm versions
gulp.task("bump-minor", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "minor"
    }))
  .pipe(gulp.dest("./"));
});

// Major update for bower and npm versions
gulp.task("bump-major", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "major"
    }))
  .pipe(gulp.dest("./"));
});

// ---------- Git tasks ----------

// Tag the git repository using the version number in the package.json
gulp.task("git-tag", function() {
  return gulp.src(["./package.json"])
    .pipe(tag_version());
});

// ---------- Watch task ----------

// Rerun tasks when a file changes, for local development
gulp.task("watch", function() {
  gulp.watch(paths.allstyles, ["styles-dev"]);
});

// ---------- Release tasks ----------

// Dev release
gulp.task("dev-release",   ["code-check", "build"]);
// Check code standards, update the version numbers as
// needed, create the release artefact, tag the branch in git and commit it
gulp.task("micro-release", ["code-check", "bump-patch", "build", "git-tag"]);
gulp.task("minor-release", ["code-check", "bump-minor", "build", "git-tag"]);
gulp.task("major-release", ["code-check", "bump-major", "build", "git-tag"]);

// ---------- Default task ----------

// Compile the scss into css but don"t minify incase of debugging, watch for changes
gulp.task("default", ["code-check", "styles-dev", "watch"]);
<commit_msg>Removed the example images from the final build artefact to reduce its size by around 50% to fix issue #6<commit_after>// ---------- Plugins and paths ----------

var gulp = require("gulp"),
    autoprefixer = require("gulp-autoprefixer"),
    clean = require("gulp-clean"),
    zip = require("gulp-zip"),
    concat = require("gulp-concat"),
    rename = require("gulp-rename"),
    //uglify = require("gulp-uglify"),
    sass = require("gulp-sass"),
    cssnano = require("gulp-cssnano"),
    htmlreplace = require("gulp-html-replace"),
    eslint = require("gulp-eslint"),
    scsslint = require("gulp-scss-lint"),
    bump = require("gulp-bump"),
    tag_version = require("gulp-tag-version"),
    paths = {
        // All JS files - for linting
        allscripts     : ["src/app/**/*.js", "gulpfile.js"],
        // Only source JS files - for building the artefact
        appscripts     : ["src/app/app.module.js", "src/app/**/*.js"],
        // All scss files - for linting
        allstyles      : "src/assets/styles/**/*.scss",
        // Only the main scss file - for building the artefact
        appstyles      : "src/assets/styles/app.styles.scss",
        // All image files
        images         : "src/assets/images/**/*.*",
        // Images that should be excluded from the final build artefact
        excludedimages : "!src/assets/images/examples/*.*",
        // The config settings for the app
        config         : "src/app/app.config.json"
    };

// ---------- Code lint and tidy up tasks ----------

// Clean /dist and remove everything
gulp.task("clean", function () {
  return gulp.src("dist/*", {read:false})
    .pipe(clean({
        force : true
    }));
});

// Check the JS code against ESLint standards
gulp.task("eslint", function() {
  return gulp.src(paths.allscripts).pipe(eslint({
    extends : "eslint:recommended",
    rules : {
        "quotes" : [1, "double"],
        "semi"   : [1, "always"]
    },
    globals : {
        "angular"     : true,
        "carousel"    : true,
        "document"    : true,
        "setTimeout"  : true,
        "require"     : true
    }
  }))
  .pipe(eslint.format())
  .pipe(eslint.failOnError()); // Fail task on lint errors
});

// Check the SCSS code against scss-lint standards
gulp.task("scsslint", function() {
  return gulp.src(paths.allstyles)
    .pipe(scsslint())
    .pipe(scsslint.failReporter()); // Report failures in the console
});

// Combination task which checks the .js and .scss files against coding standards
gulp.task("code-check", ["eslint", "scsslint"]);

// ---------- Production build tasks ----------

// Build an artefact and zip everything up
gulp.task("build", ["scripts", "bower_components", "styles", "html", "images", "index", "config", "php", "misc"], function() {
  return gulp.src("dist/**/**")
    .pipe(zip("iframe-carousel.zip"))
    .pipe(gulp.dest("dist"));
});

// Combine all the src JS, minify and then uglify
gulp.task("scripts", function() {
  return gulp.src(paths.appscripts)
    .pipe(concat("app.js"))
    .pipe(gulp.dest("dist"))
    .pipe(rename("app.min.js"))
    //.pipe(uglify()) // Causes problems loading bower.json
    .pipe(gulp.dest("dist"));
});

// Combine sccs into one file, compile into css, minify
gulp.task("styles", function() {
  return gulp.src(paths.appstyles)
    .pipe(sass().on("error", sass.logError)) // Log sass errors
    .pipe(autoprefixer({browsers: ["last 10 versions", "> 10%", "ie >= 11"]}))
    .pipe(concat("app.min.css"))
    .pipe(cssnano())
    .pipe(gulp.dest("dist"));
});

// Move all the html into /dist
gulp.task("html", function() {
  return gulp.src("src/app/**/*.html")
    .pipe(gulp.dest("dist/src/app"));
});

// Move all the php into /dist
gulp.task("php", function() {
  return gulp.src("src/app/**/*.php")
    .pipe(gulp.dest("dist/src/app"));
});

// Move the images into /dist
gulp.task("images", function() {
  return gulp.src([paths.images, paths.excludedimages])
    .pipe(gulp.dest("dist/src/assets/images/"));
});

// Move the app config into /dist
gulp.task("config", function() {
  return gulp.src(paths.config)
    .pipe(gulp.dest("dist/src/app"));
});

// Move index.html into /dist and replace the filepaths as required
gulp.task("index", function() {
  return gulp.src("index.html")
    .pipe(htmlreplace({
        "css" : "app.min.css",
        "js"  : "app.min.js"
    }))
    .pipe(gulp.dest("dist"));
});

// Copy all the required bower dependencies into /dist
gulp.task("bower_components", function() {
  return gulp.src(["bower_components/angular/angular.min.js",
                   "bower_components/angular-animate/angular-animate.min.js",
                   "bower_components/angular-aria/angular-aria.min.js",
                   "bower_components/angular-material/angular-material.min.js",
                   "bower_components/angular-route/angular-route.min.js",
                   "bower_components/angular-material/angular-material.min.css",
                   "bower_components/font-awesome/**"],
                   {base : "bower_components/"})
    .pipe(gulp.dest("dist/bower_components"));
});

// Move other misc files into /dist
gulp.task("misc", function() {
  return gulp.src(["bower.json", "package.json", "README.md"])
    .pipe(gulp.dest("dist/"));
});

// ---------- Local development build tasks ----------

// Compiles scss into css without minifying so debugging is easier
gulp.task("styles-dev", function() {
  return gulp.src(paths.appstyles)
    .pipe(concat("app.scss"))
    .pipe(sass().on("error", sass.logError))
    .pipe(autoprefixer({browsers: ["last 10 versions", "> 10%", "ie >= 11"]}))
    .pipe(rename("app.styles.css"))
    .pipe(gulp.dest("dist"));
});

// ---------- Bump version number tasks ----------

// Pre-release update for bower and npm versions
gulp.task("bump-prerelease", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type  : "prerelease",
        preid : "SNAPSHOT"
    }))
  .pipe(gulp.dest("./"));
});

// Micro update for bower and npm versions
gulp.task("bump-patch", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "patch"
    }))
  .pipe(gulp.dest("./"));
});

// Minor update for bower and npm versions
gulp.task("bump-minor", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "minor"
    }))
  .pipe(gulp.dest("./"));
});

// Major update for bower and npm versions
gulp.task("bump-major", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "major"
    }))
  .pipe(gulp.dest("./"));
});

// ---------- Git tasks ----------

// Tag the git repository using the version number in the package.json
gulp.task("git-tag", function() {
  return gulp.src(["./package.json"])
    .pipe(tag_version());
});

// ---------- Watch task ----------

// Rerun tasks when a file changes, for local development
gulp.task("watch", function() {
  gulp.watch(paths.allstyles, ["styles-dev"]);
});

// ---------- Release tasks ----------

// Dev release
gulp.task("dev-release",   ["code-check", "build"]);
// Check code standards, update the version numbers as
// needed, create the release artefact, tag the branch in git and commit it
gulp.task("micro-release", ["code-check", "bump-patch", "build", "git-tag"]);
gulp.task("minor-release", ["code-check", "bump-minor", "build", "git-tag"]);
gulp.task("major-release", ["code-check", "bump-major", "build", "git-tag"]);

// ---------- Default task ----------

// Compile the scss into css but don"t minify incase of debugging, watch for changes
gulp.task("default", ["code-check", "styles-dev", "watch"]);
<|endoftext|>


<commit_before>var express = require('express')
  , logger = require('morgan')
  , app = express()
  , template = require('jade').compileFile(__dirname + '/source/templates/homepage.jade');
var session = require('express-session')
var filestore = require('session-file-store')(session)

const Discord = require('discord.js');
const client = new Discord.Client();

const jsonf = require('jsonfile');
var http = require('http').Server(app);
var io = require('socket.io')(http);

const cmd = require('./commands/commands.js');
const songmngr = require('./commands/songmngr.js');

var songlist = './data/songlist.json';
var bottoken = './token/token.json';
var nowplaying = 'No Song Playing';

app.use(logger('dev'));
app.use(express.static(__dirname + '/static'));
app.use(session({
  name: 'server-session-cookie-id',
  secret: 'my express secret'
  saveUninitialized: true,
  resave: true,
  store: new filestore()

}))

//connections to homepage of webserver
//TODO: implement proper session handling & authentication
app.get('/', function (req, res, next) {

  try {

    // make an array of the obj keys
    var k = [];

    //open songlist
    jsonf.readFile(songlist, function(err, obj) {

    // loop index
    var i = 0;

    //create numerical index array for lookup purposes
    Object.keys(obj).forEach(function (key) {
        k[i] = key;
        i++;
    });

    //pass necessary values to the jade template before rendering
    var html = template({ 'songs' : k, 'nowplaying' : nowplaying });

    //send template to the client connection
    res.send(html)
     });
  } catch (e) {

    next(e)

  }
})

//when socket sends connection event
io.on('connection', function(socket){

  console.log('a user connected');

  socket.on('disconnect', function(){
    console.log('user disconnected');
  });

  //stopsong event sent by clicking stop button
  socket.on('stopsong', function() {

    //if voiceConnection exists
    if (client.voiceConnections.first()) {

    //stop playing voice
    client.voiceConnections.first().dispatcher.end();

    //update nowplaying value
    nowplaying = 'No Song Playing';

    //update song listing on website
    socket.emit('updatesong', {'title': nowplaying});

    //update bot's Game value
    client.user.setGame(nowplaying);
  }

  });

    //songplays event sent by songmngr.playSong with the title of current song
  client.on('songplays', function(song) {
    console.log("songplays event received")

    //update nowplaying
    nowplaying = song.title;

    //send updatesong event to the socket to update webpage
    io.emit('updatesong', {'title': nowplaying});

    //update "game" on bot with currently playing song
    client.user.setGame(nowplaying);

  });

  //playsong event sent from webpage
  socket.on('playsong', function(s) {

    console.log("playsong event received with " + s);

    //run playSong with the given string as kw
    songmngr.playSong(s, client);

  });

});

//when discord client is ready
client.on('ready', () => {

  console.log('I am ready!');

});

//when client reads a message in discord
client.on('message', message => {

  try {

    cmd.findCmd(message, client, client.guilds.first())

  } catch(e){

    console.log(e);

  }

});

//send login token
//TODO: remove hardcoded token for security
jsonf.readFile(bottoken, function(err, obj) {
  client.login(obj.token);
})

//start listening for connections to webserver
http.listen(process.env.PORT || 3000, function () {

  console.log('Listening on http://localhost:' + (process.env.PORT || 3000))

})
<commit_msg>missing ,<commit_after>var express = require('express')
  , logger = require('morgan')
  , app = express()
  , template = require('jade').compileFile(__dirname + '/source/templates/homepage.jade');
var session = require('express-session')
var filestore = require('session-file-store')(session)

const Discord = require('discord.js');
const client = new Discord.Client();

const jsonf = require('jsonfile');
var http = require('http').Server(app);
var io = require('socket.io')(http);

const cmd = require('./commands/commands.js');
const songmngr = require('./commands/songmngr.js');

var songlist = './data/songlist.json';
var bottoken = './token/token.json';
var nowplaying = 'No Song Playing';

app.use(logger('dev'));
app.use(express.static(__dirname + '/static'));
app.use(session({
  name: 'server-session-cookie-id',
  secret: 'my express secret',
  saveUninitialized: true,
  resave: true,
  store: new filestore()

}))

//connections to homepage of webserver
//TODO: implement proper session handling & authentication
app.get('/', function (req, res, next) {

  try {

    // make an array of the obj keys
    var k = [];

    //open songlist
    jsonf.readFile(songlist, function(err, obj) {

    // loop index
    var i = 0;

    //create numerical index array for lookup purposes
    Object.keys(obj).forEach(function (key) {
        k[i] = key;
        i++;
    });

    //pass necessary values to the jade template before rendering
    var html = template({ 'songs' : k, 'nowplaying' : nowplaying });

    //send template to the client connection
    res.send(html)
     });
  } catch (e) {

    next(e)

  }
})

//when socket sends connection event
io.on('connection', function(socket){

  console.log('a user connected');

  socket.on('disconnect', function(){
    console.log('user disconnected');
  });

  //stopsong event sent by clicking stop button
  socket.on('stopsong', function() {

    //if voiceConnection exists
    if (client.voiceConnections.first()) {

    //stop playing voice
    client.voiceConnections.first().dispatcher.end();

    //update nowplaying value
    nowplaying = 'No Song Playing';

    //update song listing on website
    socket.emit('updatesong', {'title': nowplaying});

    //update bot's Game value
    client.user.setGame(nowplaying);
  }

  });

    //songplays event sent by songmngr.playSong with the title of current song
  client.on('songplays', function(song) {
    console.log("songplays event received")

    //update nowplaying
    nowplaying = song.title;

    //send updatesong event to the socket to update webpage
    io.emit('updatesong', {'title': nowplaying});

    //update "game" on bot with currently playing song
    client.user.setGame(nowplaying);

  });

  //playsong event sent from webpage
  socket.on('playsong', function(s) {

    console.log("playsong event received with " + s);

    //run playSong with the given string as kw
    songmngr.playSong(s, client);

  });

});

//when discord client is ready
client.on('ready', () => {

  console.log('I am ready!');

});

//when client reads a message in discord
client.on('message', message => {

  try {

    cmd.findCmd(message, client, client.guilds.first())

  } catch(e){

    console.log(e);

  }

});

//send login token
//TODO: remove hardcoded token for security
jsonf.readFile(bottoken, function(err, obj) {
  client.login(obj.token);
})

//start listening for connections to webserver
http.listen(process.env.PORT || 3000, function () {

  console.log('Listening on http://localhost:' + (process.env.PORT || 3000))

})
<|endoftext|>