<commit_before>var express = require('express');
var etrace = require('express-tracer');

var dte = require('../');
var app = express();
etrace(app);

// Helpers to generate random ids.
function random(){
  return Math.random().toString(36).slice(2);
}
// Add a middleware that runs trace function.
app.use(dte.start);

// Add another middleware that runs trace after an asynchronous call.
app.use(function(req, res, next){
  res.trace('wait:before');
  setTimeout(function () {
    res.trace('wait:after');
    next();
  }, Math.random() * 100);
});

// Add a route to show request traces.
app.get('/', function(req, res, next){
  res.trace('user.id', random());
  res.trace('some.event', random(), random());
  res.trace('another.event', random(), random());
  res.set('X-Response-Time', (Date.now() - res.start) + 'ms');
  res.send('Hello world!');
  next();
});

// Add an after request processing middleware that runs trace.
app.use(dte.finish);

// Configure tracer.
app.instrument(dte.instrument);

/* istanbul ignore next */
if (!module.parent) {
  app.listen(3000);
  console.log('Express started on port 3000');
}
<commit_msg>Simplified the example<commit_after>var express = require('express');
var etrace = require('express-tracer');

var dte = require('../');
var app = express();
etrace(app);

// Helpers to generate random ids.
function random(){
  return Math.random().toString(36).slice(2);
}
// Add a middleware that runs trace function.
app.use(dte.start);

// Add a route to show request traces.
app.get('/', function(req, res, next){
  res.trace('some.event', 'some event data');
  res.send('Hello world!');
  next();
});

// Add an after request processing middleware that runs trace.
app.use(dte.finish);

// Configure tracer.
app.instrument(dte.instrument);

/* istanbul ignore next */
if (!module.parent) {
  app.listen(3000);
  console.log('Express started on port 3000');
}
<|endoftext|>


<commit_before>// === DEFAULT / CUSTOM STYLE ===
// WARNING! always comment out ONE of the two require() calls below.
// 1. use next line to activate CUSTOM STYLE (./src/themes)
// require(`./themes/app.${__THEME}.styl`)
// 2. or, use next line to activate DEFAULT QUASAR STYLE
require(`quasar/dist/quasar.${__THEME}.css`)
// ==============================

// Uncomment the following lines if you need IE11/Edge support
// require(`quasar/dist/quasar.ie`)
// require(`quasar/dist/quasar.ie.${__THEME}.css`)

import Vue from 'vue'
import Quasar from 'quasar'
import router from './router'

Vue.config.productionTip = false
Vue.use(Quasar) // Install Quasar Framework

if (__THEME === 'mat') {
  require('quasar-extras/roboto-font')
}
import 'quasar-extras/material-icons'
// import 'quasar-extras/ionicons'
// import 'quasar-extras/fontawesome'
// import 'quasar-extras/animate'

Quasar.start(() => {
  /* eslint-disable no-new */
  new Vue({
    el: '#q-app',
    router,
    render: h => h(require('./App'))
  })
})
<commit_msg>vue-loader v13.0+ support<commit_after>// === DEFAULT / CUSTOM STYLE ===
// WARNING! always comment out ONE of the two require() calls below.
// 1. use next line to activate CUSTOM STYLE (./src/themes)
// require(`./themes/app.${__THEME}.styl`)
// 2. or, use next line to activate DEFAULT QUASAR STYLE
require(`quasar/dist/quasar.${__THEME}.css`)
// ==============================

// Uncomment the following lines if you need IE11/Edge support
// require(`quasar/dist/quasar.ie`)
// require(`quasar/dist/quasar.ie.${__THEME}.css`)

import Vue from 'vue'
import Quasar from 'quasar'
import router from './router'

Vue.config.productionTip = false
Vue.use(Quasar) // Install Quasar Framework

if (__THEME === 'mat') {
  require('quasar-extras/roboto-font')
}
import 'quasar-extras/material-icons'
// import 'quasar-extras/ionicons'
// import 'quasar-extras/fontawesome'
// import 'quasar-extras/animate'

Quasar.start(() => {
  /* eslint-disable no-new */
  new Vue({
    el: '#q-app',
    router,
    render: h => h(require('./App').default)
  })
})
<|endoftext|>


<commit_before>/**
*	Binary Search Tree (BST)
*	unbalanced
*
*	@author Lakha Singh
*/

(function(){
	// to create a new tree node
	var _createNode = function( data ){
		var children = [];

		// set left and right child
		children[0] = null;
		children[1] = null;

		return {
			parent: null,
			data: data,
			children: children
		}
	}

	// to traverse the tree
	var _traverse = function( data ){
		var found = null, node;

		if ( !data ){
			return null;
		}

		// start from root
		node = root;

		while( node != null ){
			found = node;
			if ( data == node.data ){
				break;
			}else if ( data < node.data ){
				node = node.children[0];
			}else{
				node = node.children[1];
			}
		}

		return found;
	}

	// Root node for tree
	var root = null;

	var BST = function( data ){
		if ( data ){
			if ( typeof data == 'number' ){
				this.insert( data );
			}else if ( data.length ){
				for ( i = 0; i < data.length; i++ ){
					this.insert( data[i] );
				}
			}
		}
	}

	// Insert new node
	BST.prototype.insert = function( data ){
		var found = _traverse( data.data || data );

		var node;

		// Duplicates not suppoted
		if ( found && found.data == data ){
			console.log('Duplicate nodes are not currently Supported');
			return null;
		}

		node = data.data && data || _createNode( data );

		// it is a root
		if( found == null ){
			root = node;
		}

		// Insert new node
		else {
			node.parent = found;

			if( (data.data || data) < found.data ){
				found.children[0] = node;
			}else{
				found.children[1] = node;
			}
		}
	}

	// delete node
	BST.prototype.delete = function( data ){
		var found = _traverse( data );

		var node, parent, leftChild, rightChild;

		// If found
		if ( found && found.data == data ){
			parent = found.parent;
			leftChild = found.children[0];
			rightChild = found.children[1];

			if ( parent.children[0] == found ){
				parent.children[0] = null;
			}else{
				parent.children[1] = null;
			}

			// Re-insert left / right subtrees
			this.insert( leftChild );
			this.insert( rightChild );
		}
	}

	// Search for node
	BST.prototype.search = function( data ){
		var found = _traverse( data );

		// when found
		if ( found && found.data == data ){
			return data;
		}else{
			return -1;
		}
	}

	// Supporting browser and node env
	if ( typeof window === 'object' ){
		window.tree = window.tree || {};
		window.tree.BST = BST;
	}
	else if ( typeof module === 'object' ){
		module.exports = BST;
	}
}());
<commit_msg>completed BST<commit_after>/**
*	Binary Search Tree (BST)
*	unbalanced
*
*	@author Lakha Singh
*/

(function(){
	var CHILD = {
		left: 0,
		right: 1
	};

	// to create a new tree node
	var _createNode = function( data ){
		var children = [];

		// set left and right child
		children[0] = null;
		children[1] = null;

		return {
			parent: null,
			data: data,
			children: children
		}
	}

	// searches for data, returns its node from tree
	// if not found, it returns position where it can be inserted
	var _search = function( data, start ){
		var found = null, node;

		if ( !data ){
			return null;
		}

		// start from root
		node = start || root;

		while( node != null ){
			found = node;
			if ( data == node.data ){
				break;
			}else if ( data < node.data ){
				node = node.children[0];
			}else{
				node = node.children[1];
			}
		}

		return found;
	}

	var _print = function( node ){
		if ( !node ){
			return false;
		}

		if ( node.children[0] == null ){
			console.log( node.data );

			if ( node.children[1] == null ){
				return true;
			}else{
				return _print( node.children[1] );
			}
		}
		_print( node.children[0]);
		console.log( node.data );
		_print( node.children[1]);
	}

	// Root node for tree
	var root = null;

	var BST = function( data ){
		if ( data ){
			if ( typeof data == 'number' ){
				this.insert( data );
			}else if ( data.length ){
				for ( i = 0; i < data.length; i++ ){
					this.insert( data[i] );
				}
			}
		}
	}

	// Insert new node
	BST.prototype.insert = function( data ){
		var found = _search( data.data || data );

		var node;

		// Duplicates not suppoted
		if ( found && found.data == data ){
			console.log('Duplicate nodes are not currently Supported');
			return null;
		}

		node = data.data && data || _createNode( data );

		// tree not yet exists, create its root
		if( found == null ){
			root = node;
		}

		// Insert new node
		else {
			node.parent = found;

			if( (data.data || data) < found.data ){
				found.children[0] = node;
			}else{
				found.children[1] = node;
			}
		}
	}

	// delete node
	BST.prototype.delete = function( data ){
		var found = _search( data );

		var parent, leftChild, rightChild;

		// If node is found
		if ( found && found.data == data ){
			parent = found.parent;
			leftChild = found.children[0];
			rightChild = found.children[1];

			if ( parent.children[0] == found ){
				parent.children[0] = null;
			}else{
				parent.children[1] = null;
			}

			// Re-insert left / right subtrees
			this.insert( leftChild );
			this.insert( rightChild );
		}else{
			console.log('Data doesn\'t exists');
		}
	}

	// Search for node
	BST.prototype.search = function( data ){
		var found = _search( data );

		// when found
		if ( found && found.data == data ){
			return data;
		}else{
			return -1;
		}
	}

	// Prints tree
	BST.prototype.print = function(){
		var node = root;

		_print( node );
	}

	// Supporting browser and node env
	if ( typeof window === 'object' ){
		window.tree = window.tree || {};
		window.tree.BST = BST;
	}
	else if ( typeof module === 'object' ){
		module.exports = BST;
	}
}());
<|endoftext|>


<commit_before>/*
 * grunt-color-svg-icons
 * https://github.com/philliprower/color-svg-icons
 *
 * Copyright (c) 2015 Phillip Rower
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

  var fs = require("fs"),
    path = require("path"),
    SVGO = require("svgo");

  var svgo = new SVGO();
  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  function transform (data, fill) {
    if (fill) {
      if (data.match(/fill="/)) {
        data = data.replace(/(fill=")[^none][^"]+(")/g, "$1" + fill + "$2");
      }
      if (data.match(/stroke="/)) {
        data = data.replace(/(stroke=")[^"]+(")/g, "$1" + fill + "$2");
      }
      else {
        var attributes = " fill=\"" + fill + "\"";
        data = data.replace(/<path/g, "<path" + attributes);
        data = data.replace(/<circle/g, "<circle" + attributes);
        data = data.replace(/<rect/g, "<rect" + attributes);
      }
    }
    return data;
  }

  //function transform (data, fill) {
  //
  //  if (data !== data.match(/^<g>(?:.*?)<\/g>/)) {
  //    data = "<g>" + data + "</g>";
  //  }
  //  var attributes = "";
  //  if (fill) {
  //    if (data.match(/fill="/)) {
  //      data = data.replace(/(fill=")[^"]+(")/g, "$1" + fill + "$2");
  //    }
  //    else {
  //      attributes += " fill=\"" + fill + "\"";
  //    }
  //  }
  //  data = data.replace(/^<g/, "<g" + attributes);
  //  return data;
  //}

  grunt.registerMultiTask('color_svg_icons', 'Color svg icons.', function () {
    var colors = this.data.options.colors;
    var prepend = this.data.options.prepend;
    if (!colors) {
      grunt.log.error('Must define colors to set svgs.');
    }
    // Iterate over all specified file groups.
    this.files.forEach(function (f) {
      // Concat specified files.
      var src = f.src.filter(function (filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function (filepath) {
        var rObj = {};
        rObj['filename']=filepath;
        // Read file source.
        rObj['file'] = grunt.file.read(filepath);
        return rObj;
      });

      src.forEach(function(data) {
        grunt.log.writeln('Source filename ' + data['filename']);
        grunt.verbose.writeln('Source filename contents ' + data['file']);
        //svgo.optimize(data['file'],function(result) {
        //  for (var c in colors) {
        //    var output = transform(result.data, colors[c]);
        //    grunt.verbose.writeln('Changed svg to color ' + colors[c] + ' svg contents : ' + output);
        //    var outpath = f.dest + path.sep +  c + '_' + path.basename(data['filename']);
        //    grunt.log.writeln('File "' + outpath + '" created.');
        //    grunt.file.write(outpath, output);
        //  }
        //});
        var result = data['file'];
          for (var c in colors) {
            var output = transform(result, colors[c]);
            grunt.verbose.writeln('Changed svg to color ' + colors[c] + ' svg contents : ' + output);
            var name = '';
            if(c !== 'base') {
              name = c;
            }
            var outpath;
            if(prepend === undefined) {
              prepend = true;
            }
            if(prepend) {
              name = c !== 'base'? name + '_':name;
              outpath = f.dest + path.sep +  name + path.basename(data['filename']);
            } else {
              name = c !== 'base'? '_' + name:name;
              outpath = f.dest + path.sep + path.basename(data['filename'], '.svg') + name + '.svg';
            }
            grunt.log.writeln('File "' + outpath + '" created.');
            grunt.file.write(outpath, output);
          }

      });

      // Print a success message.
      grunt.log.writeln('File "' + f.dest + '" created.');
    });
  });

};
<commit_msg>Added option.stateToken<commit_after>/*
 * grunt-color-svg-icons
 * https://github.com/philliprower/color-svg-icons
 *
 * Copyright (c) 2015 Phillip Rower
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

  var fs = require("fs"),
    path = require("path"),
    SVGO = require("svgo");

  var svgo = new SVGO();
  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  function transform (data, fill) {
    if (fill) {
      if (data.match(/fill="/)) {
        data = data.replace(/(fill=")[^none][^"]+(")/g, "$1" + fill + "$2");
      }
      if (data.match(/stroke="/)) {
        data = data.replace(/(stroke=")[^"]+(")/g, "$1" + fill + "$2");
      }
      else {
        var attributes = " fill=\"" + fill + "\"";
        data = data.replace(/<path/g, "<path" + attributes);
        data = data.replace(/<circle/g, "<circle" + attributes);
        data = data.replace(/<rect/g, "<rect" + attributes);
      }
    }
    return data;
  }

  //function transform (data, fill) {
  //
  //  if (data !== data.match(/^<g>(?:.*?)<\/g>/)) {
  //    data = "<g>" + data + "</g>";
  //  }
  //  var attributes = "";
  //  if (fill) {
  //    if (data.match(/fill="/)) {
  //      data = data.replace(/(fill=")[^"]+(")/g, "$1" + fill + "$2");
  //    }
  //    else {
  //      attributes += " fill=\"" + fill + "\"";
  //    }
  //  }
  //  data = data.replace(/^<g/, "<g" + attributes);
  //  return data;
  //}

  grunt.registerMultiTask('color_svg_icons', 'Color svg icons.', function () {
    var colors = this.data.options.colors;
    var stateToken = this.data.options.stateToken;
    var prepend = this.data.options.prepend;
    if (!colors) {
      grunt.log.error('Must define colors to set svgs.');
    }
    // Iterate over all specified file groups.
    this.files.forEach(function (f) {
      // Concat specified files.
      var src = f.src.filter(function (filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function (filepath) {
        var rObj = {};
        rObj['filename']=filepath;
        // Read file source.
        rObj['file'] = grunt.file.read(filepath);
        return rObj;
      });

      src.forEach(function(data) {
        grunt.log.writeln('Source filename ' + data['filename']);
        grunt.verbose.writeln('Source filename contents ' + data['file']);
        //svgo.optimize(data['file'],function(result) {
        //  for (var c in colors) {
        //    var output = transform(result.data, colors[c]);
        //    grunt.verbose.writeln('Changed svg to color ' + colors[c] + ' svg contents : ' + output);
        //    var outpath = f.dest + path.sep +  c + '_' + path.basename(data['filename']);
        //    grunt.log.writeln('File "' + outpath + '" created.');
        //    grunt.file.write(outpath, output);
        //  }
        //});
        var result = data['file'];
          for (var c in colors) {
            var output = transform(result, colors[c]);
            grunt.verbose.writeln('Changed svg to color ' + colors[c] + ' svg contents : ' + output);
            var name = '';
            if(c !== 'base') {
              name = c;
            }
            var outpath;
            if(stateToken === undefined) {
              stateToken = '_';
            }
            if(prepend === undefined) {
              prepend = true;
            }
            if(prepend) {
              name = c !== 'base'? name + stateToken:name;
              outpath = f.dest + path.sep +  name + path.basename(data['filename']);
            } else {
              name = c !== 'base'? stateToken + name:name;
              outpath = f.dest + path.sep + path.basename(data['filename'], '.svg') + name + '.svg';
            }
            grunt.log.writeln('File "' + outpath + '" created.');
            grunt.file.write(outpath, output);
          }

      });

      // Print a success message.
      grunt.log.writeln('File "' + f.dest + '" created.');
    });
  });

};
<|endoftext|>


<commit_before>/*
 * grunt-es3-safe-recast
 * https://github.com/phpro/grunt-es3-safe-recast
 *
 * Copyright (c) 2014 Toon Verwerft
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  grunt.registerMultiTask('es3_safe_recast', 'Recasts all ECMA3 reserved words to their safe alternatives, optionally removes trailing commas', function() {

    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      trailingComma: false
    });

    // The compiler
    var compiler = require('es3-safe-recast');

    // Compile all selected files:
    this.files.forEach(function (file) {

      var content = file.src.reduce((result, src) => {
        result.push(grunt.file.read(src));
        return result;
      },[]).join("\n");

      var compiled = compiler.compile(content, options);

      grunt.file.write(file.dest, compiled);
      grunt.log.writeln('Saved compiled file(s) at: ' + file.dest);
    });

  });

};
<commit_msg>add special case for equal src/dest and input/output (no file written)<commit_after>/*
 * grunt-es3-safe-recast
 * https://github.com/phpro/grunt-es3-safe-recast
 *
 * Copyright (c) 2014 Toon Verwerft
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  grunt.registerMultiTask('es3_safe_recast', 'Recasts all ECMA3 reserved words to their safe alternatives, optionally removes trailing commas', function() {

    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      trailingComma: false
    });

    // The compiler
    var compiler = require('es3-safe-recast');

    // Compile all selected files:
    this.files.forEach(function (file) {

      var content = file.src.reduce((result, src) => {
        result.push(grunt.file.read(src));
        return result;
      },[]).join("\n");

      var compiled = compiler.compile(content, options);

      if (file.src.length === 1 && file.src[0] === file.dest && compiled === content) {
        grunt.log.writeln('No change necessary (src=dest, input=output): ' + file.src[0]);
        return;
      }

      grunt.file.write(file.dest, compiled);
      grunt.log.writeln('Saved compiled file(s) at: ' + file.dest);
    });

  });

};
<|endoftext|>


<commit_before>define(['board', 'tile'], function (Board, Tile) {
  return function (c) {
    c.c('Board', {
      init: function () {
        this.rows = 13;
        this.cols = 7;

        this.addComponent('2D, Canvas, Keyboard');

        this.x = BOARD_LEFT;
        this.y = BOARD_TOP;

        this.w = BOARD_WIDTH;
        this.h = BOARD_HEIGHT;

      },

      updateBoard: function() {
       var moveOccured = false;

        for(var i=this.board.board.length-1; i >= 0; i--) {
          for(var j=this.board.board[i].length-1; j >= 0; j--) {
            var current = this.board.board[i][j];

            if(current) {
              var np = this.board.board[i+1][j];
              if(!np && i < 11) {
                c(current.entity).moveTo(i+1, j);
                this.board.board[i][j] = false;
                current.row = i+1;
                current.col = j;
                current.updated = true;
                this.board.board[i+1][j] = current;
                moveOccured = true;
              }
              else {
                this.board.get(i,j).updated = false;
              }
            }
          }
        }

        while(this.omNomNom()){
          this.updateBoard();
        }

        return moveOccured;
      },

      loop: function() {
        if(!this.updateBoard()) {
          this.newTurn();
        }
      },

      omNomNom: function() {
        var hasNommed = false;
        for(var i=this.board.board.length-1; i >= 0; i--) {
          for(var j=this.board.board[i].length-1; j >= 0; j--) {
            var current = this.board.board[i][j];
            if(current && current.monster){
              hasNommed = this.nomAdjacent(current, current.color);
            }
          }
        }

        return hasNommed;
      },

      nomAdjacent: function(current, colorToNom){
        var nommed = false;
        var destroyable = false;

        var siblings = [
          this.board.get(current.row, current.col - 1),
          this.board.get(current.row, current.col + 1),
          this.board.get(current.row - 1, current.col),
          this.board.get(current.row + 1, current.col)
        ]

        for (var i = 0; i < siblings.length; i++) {
          var adj = siblings[i];
          if (adj && adj.color == colorToNom){
            this.board.board[adj.row][adj.col] = false;
            c(adj.entity).destroy();
            this.nomAdjacent(adj, colorToNom);
          }
        }

        return nommed;
      },

      newTurn: function() {
        var t1 = new Tile(0,2);
        var t2 = new Tile(0,3);

        t1.randomType();
        t2.randomType();
        t1.link = t2;
        t2.link = t1;

        t1.entity = c.e('Tile').create(t1, this.x, this.y)[0];
        t2.entity = c.e('Tile').create(t2, this.x, this.y)[0];

        this.board.set(0,2,t1);
        this.board.set(0,3,t2);

        this.drop.t1 = t1;
        this.drop.t2 = t2;

      },

      left: function() {

        if(!this.drop.t1) {
          return false;
        }

        var t1 = this.drop.t1, t2 = this.drop.t2;
        var left = t2.left();

        //this.moveLeft(this.drop.t1.row, this.drop.t1.col);
        //this.moveLeft(this.drop.t2.row, this.drop.t2.col);

        if(t1.inPos(left.row, left.col)) {
          this.moveLeft(t1.row, t1.col);
          this.moveLeft(t2.row, t2.col);
        }
        else {
          this.moveLeft(t2.row, t2.col);
          this.moveLeft(t1.row, t1.col);
        }

      },

      moveLeft: function(row, col) {

        var np = this.board.get(row, col - 1);
        var current = this.board.get(row, col);

        if(!np && col != 0) {

          this.board.move(row, col, row, col - 1);
          c(current.entity).moveTo(row, col - 1);
          return true;
        }
        else {
          return false;
        }

      },

      right: function() {

        if(!this.drop.t1) {
          return false;
        }
        var t1 = this.drop.t1, t2 = this.drop.t2;
        var right = t2.right();

        if(t1.inPos(right.row, right.col)) {
          this.moveRight(t1.row, t1.col);
          this.moveRight(t2.row, t2.col);
        }
        else {
          this.moveRight(t2.row, t2.col);
          this.moveRight(t1.row, t1.col);
        }

      },

      moveRight: function(row, col) {
        var np = this.board.get(row, col + 1);
        var current = this.board.get(row, col);

        if(!np && col != (this.cols-1)) {
          this.board.move(row, col, row, col + 1);
          c(current.entity).moveTo(row, col + 1);
          return true;
        }
        else {
          return false;
        }

      },

      down: function() {
        if(!this.drop.t1) {
          return false;
        }

        this.moveDown(this.drop.t1.row, this.drop.t1.col);
        this.moveDown(this.drop.t2.row, this.drop.t2.col);

      },

      moveDown: function(row, col) {

        var np = this.board.get(row + 1, col);
        var current = this.board.get(row, col);

        if(!np && row < (this.rows - 2)) {
          this.board.move(row, col, row + 1, col);
          c(current.entity).moveTo(row + 1, col);
          return true;
        }
        else {
          return false;
        }
      },

      rotateTiles: function() {
        if(!this.drop.t1 && this.drop.t1.updated && this.drop.t2.updated) {

          return false;
        }

        // left to down
        // down to right
        // right to top
        // top to left

        var t1 = this.drop.t1;
        var t2 = this.drop.t2;

        var top = t2.top(), bottom = t2.bottom()
          , left = t2.left(), right = t2.right();

        if(t1.inPos(left.row, left.col)) {
          this.moveToBottomOf(t1, t2);
        }
        else if(t1.inPos(bottom.row, bottom.col)) {
          this.moveToRightOf(t1, t2);
        }
        else if(t1.inPos(right.row, right.col)) {
          this.moveToTopOf(t1, t2);
        }
        else if(t1.inPos(top.row, top.col)) {
          this.moveToLeftOf(t1, t2);
        }

      },

      availableToMove: function(row, col) {
        if(row < 0 || row >= this.rows) {
          return true;
        }

        if(col < 0 || col >= this.cols) {
          return true;
        }

        return this.board.get(row, col) ? false : true;
      },

      moveTile: function(ox, oy, dx, dy) {

        var current = this.board.get(ox, oy);

        if(this.availableToMove(dx, dy)) {
          this.board.move(ox, oy, dx, dy);
          c(current.entity).moveTo(dx, dy);
          return true;
        }
        else {
          return false;
        }
      },

      /* move t1 to the top of t2 */
      moveToTopOf: function(t1, t2) {
        var pos = t2.top();
        return this.moveTile(t1.row, t1.col, pos.row, pos.col);
      },
      /* move t1 to the left of t2 */
      moveToLeftOf: function(t1, t2) {
        var pos = t2.left();
        return this.moveTile(t1.row, t1.col, pos.row, pos.col);
      },

      moveToBottomOf: function(t1, t2) {
        var pos = t2.bottom();
        return this.moveTile(t1.row, t1.col, pos.row, pos.col);
      },

      moveToRightOf: function(t1, t2) {
        var pos = t2.right();
        return this.moveTile(t1.row, t1.col, pos.row, pos.col);
      },

      create: function (x, y, keys) {
        this.attr({ x: x, y: y });
        // this.addComponent('2D, Canvas');
        this.board = new Board(x+y);
        this.board.init(this.rows, this.cols);
        this.addComponent('board_right');

        this.drop = {t1: false, t2: false};

        setInterval($.proxy(this.loop, this), UPDATE_INTERVAL);

        this.bind("KeyEvent", function() {
          if(this.isDown(keys.left)) {
            this.left();
          }

          if(this.isDown(keys.right)) {
            this.right();
          }

          if(this.isDown(keys.down)) {
            this.down();
          }

        });

        this.bind("KeyRotateEvent", function() {
          if(this.isDown(keys.rotate)) {
            this.rotateTiles();
          }
        });

        this.newTurn();

        setInterval($.proxy(function() {
          this.trigger("KeyEvent")
          }, this), 75);

        setInterval($.proxy(function() {
          this.trigger("KeyRotateEvent")
          }, this), 120);

        return this;
      }
    });
  };
});
<commit_msg>Refined scoring logic to build an array for combos instead of incrementing a counter<commit_after>define(['board', 'tile'], function (Board, Tile) {
  return function (c) {
    c.c('Board', {
      init: function () {
        this.rows = 13;
        this.cols = 7;

        this.addComponent('2D, Canvas, Keyboard');

        this.x = BOARD_LEFT;
        this.y = BOARD_TOP;

        this.w = BOARD_WIDTH;
        this.h = BOARD_HEIGHT;

      },

      updateBoard: function() {
       var moveOccured = false;

        for(var i=this.board.board.length-1; i >= 0; i--) {
          for(var j=this.board.board[i].length-1; j >= 0; j--) {
            var current = this.board.board[i][j];

            if(current) {
              var np = this.board.board[i+1][j];
              if(!np && i < 11) {
                c(current.entity).moveTo(i+1, j);
                this.board.board[i][j] = false;
                current.row = i+1;
                current.col = j;
                current.updated = true;
                this.board.board[i+1][j] = current;
                moveOccured = true;
              }
              else {
                this.board.get(i,j).updated = false;
              }
            }
          }
        }

        while(this.omNomNom()){
          this.updateBoard();
        }

        return moveOccured;
      },

      loop: function() {
        // No updates were made to the board
        if(!this.updateBoard()) {

          var scores = [this.omNomNom()];
          if (scores[0] > 0) {
            while (this.updateBoard()){
              scores.push(this.omNomNom());
            }
          }
          else
            this.newTurn();

          console.log(scores);
        }

      },

      omNomNom: function() {
        var hasNommed = false;
        for(var i=this.board.board.length-1; i >= 0; i--) {
          for(var j=this.board.board[i].length-1; j >= 0; j--) {
            var current = this.board.board[i][j];
            if(current && current.monster){
              hasNommed = this.nomAdjacent(current, current.color);
            }
          }
        }

        return hasNommed;
      },

      nomAdjacent: function(current, colorToNom){
        var nommed = false;
        var destroyable = false;

        var siblings = [
          this.board.get(current.row, current.col - 1),
          this.board.get(current.row, current.col + 1),
          this.board.get(current.row - 1, current.col),
          this.board.get(current.row + 1, current.col)
        ]

        for (var i = 0; i < siblings.length; i++) {
          var adj = siblings[i];
          if (adj && adj.color == colorToNom){
            this.board.board[adj.row][adj.col] = false;
            c(adj.entity).destroy();
            this.nomAdjacent(adj, colorToNom);
          }
        }

        return nommed;
      },

      newTurn: function() {
        var t1 = new Tile(0,2);
        var t2 = new Tile(0,3);

        t1.randomType();
        t2.randomType();
        t1.link = t2;
        t2.link = t1;

        t1.entity = c.e('Tile').create(t1, this.x, this.y)[0];
        t2.entity = c.e('Tile').create(t2, this.x, this.y)[0];

        this.board.set(0,2,t1);
        this.board.set(0,3,t2);

        this.drop.t1 = t1;
        this.drop.t2 = t2;

      },

      left: function() {

        if(!this.drop.t1) {
          return false;
        }

        var t1 = this.drop.t1, t2 = this.drop.t2;
        var left = t2.left();

        //this.moveLeft(this.drop.t1.row, this.drop.t1.col);
        //this.moveLeft(this.drop.t2.row, this.drop.t2.col);

        if(t1.inPos(left.row, left.col)) {
          this.moveLeft(t1.row, t1.col);
          this.moveLeft(t2.row, t2.col);
        }
        else {
          this.moveLeft(t2.row, t2.col);
          this.moveLeft(t1.row, t1.col);
        }

      },

      moveLeft: function(row, col) {

        var np = this.board.get(row, col - 1);
        var current = this.board.get(row, col);

        if(!np && col != 0) {

          this.board.move(row, col, row, col - 1);
          c(current.entity).moveTo(row, col - 1);
          return true;
        }
        else {
          return false;
        }

      },

      right: function() {

        if(!this.drop.t1) {
          return false;
        }
        var t1 = this.drop.t1, t2 = this.drop.t2;
        var right = t2.right();

        if(t1.inPos(right.row, right.col)) {
          this.moveRight(t1.row, t1.col);
          this.moveRight(t2.row, t2.col);
        }
        else {
          this.moveRight(t2.row, t2.col);
          this.moveRight(t1.row, t1.col);
        }

      },

      moveRight: function(row, col) {
        var np = this.board.get(row, col + 1);
        var current = this.board.get(row, col);

        if(!np && col != (this.cols-1)) {
          this.board.move(row, col, row, col + 1);
          c(current.entity).moveTo(row, col + 1);
          return true;
        }
        else {
          return false;
        }

      },

      down: function() {
        if(!this.drop.t1) {
          return false;
        }

        this.moveDown(this.drop.t1.row, this.drop.t1.col);
        this.moveDown(this.drop.t2.row, this.drop.t2.col);

      },

      moveDown: function(row, col) {

        var np = this.board.get(row + 1, col);
        var current = this.board.get(row, col);

        if(!np && row < (this.rows - 2)) {
          this.board.move(row, col, row + 1, col);
          c(current.entity).moveTo(row + 1, col);
          return true;
        }
        else {
          return false;
        }
      },

      rotateTiles: function() {
        if(!this.drop.t1 && this.drop.t1.updated && this.drop.t2.updated) {

          return false;
        }

        // left to down
        // down to right
        // right to top
        // top to left

        var t1 = this.drop.t1;
        var t2 = this.drop.t2;

        var top = t2.top(), bottom = t2.bottom()
          , left = t2.left(), right = t2.right();

        if(t1.inPos(left.row, left.col)) {
          this.moveToBottomOf(t1, t2);
        }
        else if(t1.inPos(bottom.row, bottom.col)) {
          this.moveToRightOf(t1, t2);
        }
        else if(t1.inPos(right.row, right.col)) {
          this.moveToTopOf(t1, t2);
        }
        else if(t1.inPos(top.row, top.col)) {
          this.moveToLeftOf(t1, t2);
        }

      },

      availableToMove: function(row, col) {
        if(row < 0 || row >= this.rows) {
          return true;
        }

        if(col < 0 || col >= this.cols) {
          return true;
        }

        return this.board.get(row, col) ? false : true;
      },

      moveTile: function(ox, oy, dx, dy) {

        var current = this.board.get(ox, oy);

        if(this.availableToMove(dx, dy)) {
          this.board.move(ox, oy, dx, dy);
          c(current.entity).moveTo(dx, dy);
          return true;
        }
        else {
          return false;
        }
      },

      /* move t1 to the top of t2 */
      moveToTopOf: function(t1, t2) {
        var pos = t2.top();
        return this.moveTile(t1.row, t1.col, pos.row, pos.col);
      },
      /* move t1 to the left of t2 */
      moveToLeftOf: function(t1, t2) {
        var pos = t2.left();
        return this.moveTile(t1.row, t1.col, pos.row, pos.col);
      },

      moveToBottomOf: function(t1, t2) {
        var pos = t2.bottom();
        return this.moveTile(t1.row, t1.col, pos.row, pos.col);
      },

      moveToRightOf: function(t1, t2) {
        var pos = t2.right();
        return this.moveTile(t1.row, t1.col, pos.row, pos.col);
      },

      create: function (x, y, keys) {
        this.attr({ x: x, y: y });
        // this.addComponent('2D, Canvas');
        this.board = new Board(x+y);
        this.board.init(this.rows, this.cols);
        this.addComponent('board_right');

        this.drop = {t1: false, t2: false};

        setInterval($.proxy(this.loop, this), UPDATE_INTERVAL);

        this.bind("KeyEvent", function() {
          if(this.isDown(keys.left)) {
            this.left();
          }

          if(this.isDown(keys.right)) {
            this.right();
          }

          if(this.isDown(keys.down)) {
            this.down();
          }

        });

        this.bind("KeyRotateEvent", function() {
          if(this.isDown(keys.rotate)) {
            this.rotateTiles();
          }
        });

        this.newTurn();

        setInterval($.proxy(function() {
          this.trigger("KeyEvent")
          }, this), 75);

        setInterval($.proxy(function() {
          this.trigger("KeyRotateEvent")
          }, this), 120);

        return this;
      }
    });
  };
});
<|endoftext|>


<commit_before>var sinter = {};
sinter.login = function(assertion){
	$.ajax({
		type:'POST',
		url:'login',
		data:{assertion:assertion},
		success:function(res,status,xhr){
			$("#user_login").hide();
			$('#user_logout').show();
			console.log(res);
		},
		error:function(xhr,status,err){

		}

	});
};

sinter.logout = function(){
	$.ajax({
		type:'POST',
		url:'logout',
		success:function(res,status,xhr){
		},
		error:function(xhr,status,err){

		}

	});
};

sinter.validate = function(){
	$article_title = $('#article_title');
	$article_content = $('#article_content');
	if($article_title && $article_content){
		var canpublish = true;
		if($.trim($article_title.val()) === ''){
			canpublish = false;
			$article_title.css('border-color','red');
		}else{
			console.log($article_title.val());
		}
		if($.trim($article_content.val()) === ''){
			canpublish = false;
		}else{
			console.log($article_content.val());
		}
		return canpublish;
	}
};
sinter.preview = function(){
		// do preview
};
sinter.publish = function(){
		// do publish

};
sinter.edit = function(){
	console.log('edit')
};
sinter.draft = function(){
	console.log('draft');
};
window.sinter = sinter;

$(function(){
	var $user_login = $('#user_login');
	var $user_logout = $('#user_logout');
	if($user_login){
		$user_login.click(function(){
			navigator.id.request();
		});

	}
	if($user_logout){
		$user_logout.click(function(){
			navigator.id.logout();
		});
	}
	var $preview = $('#preview');
	var $publish = $('#publish');
	var $save_draft = $('#save_draft');
	if($preview){
		$preview.click(function(){
			sinter.validate();
			sinter.preview();
		});
	}
	if($publish){
		$publish.click(function(){
			sinter.validate();
			sinter.publish();
		});
	}
	if($save_draft){
		$save_draft.click(function(){
			sinter.validate();
			sinter.draft();
		});
	}
	navigator.id.watch({
		onlogin:sinter.login,
		onlogout:sinter.logout
	});
});
<commit_msg>update login<commit_after>var sinter = {};
sinter.login = function(assertion){
    $.ajax({
        type:'POST',
        url:'login',
        data:{assertion:assertion},
        success:function(res,status,xhr){
            if(res.login){
                if(res.needname){
                    var name = '';
                    while(!name){
                        name=prompt('please input a name');
                    }
                    var email = res.email;
                    var issuccess = sinter.saveName(name,email);
                    console.log(issuccess);
                }else{
                    $("#user_login").hide();
                    $('#user_logout').show();
                }
            }else{
                alert('login error, please try again');
            }

            console.log(res);
        },
        error:function(xhr,status,err){

        }

    });
};
sinter.saveName = function(name,email){
    var url = 'saveName';
    var data ={'name':name,'email':email};
    var saveSuccess;
    $.ajax({
        url:url,
        data:data,
        type:'POST',
        success:function(res,status){
            saveSuccess = res.success;
        }
    }).complete(function(){
        return saveSuccess;
    });
}
sinter.logout = function(){
    $.ajax({
        type:'POST',
        url:'logout',
        success:function(res,status,xhr){
        },
        error:function(xhr,status,err){

        }

    });
};

sinter.validate = function(){
    $article_title = $('#article_title');
    $article_content = $('#article_content');
    if($article_title && $article_content){
        var canpublish = true;
        if($.trim($article_title.val()) === ''){
            canpublish = false;
            $article_title.css('border-color','red');
        }else{
            console.log($article_title.val());
        }
        if($.trim($article_content.val()) === ''){
            canpublish = false;
        }else{
            console.log($article_content.val());
        }
        return canpublish;
    }
};
sinter.preview = function(){
        // do preview
};
sinter.publish = function(){
        // do publish

};
sinter.edit = function(){
    console.log('edit')
};
sinter.draft = function(){
    console.log('draft');
};
window.sinter = sinter;

$(function(){
    var $user_login = $('#user_login');
    var $user_logout = $('#user_logout');
    if($user_login){
        $user_login.click(function(){
            navigator.id.request();
        });

    }
    if($user_logout){
        $user_logout.click(function(){
            navigator.id.logout();
        });
    }
    var $preview = $('#preview');
    var $publish = $('#publish');
    var $save_draft = $('#save_draft');
    if($preview){
        $preview.click(function(){
            sinter.validate();
            sinter.preview();
        });
    }
    if($publish){
        $publish.click(function(){
            sinter.validate();
            sinter.publish();
        });
    }
    if($save_draft){
        $save_draft.click(function(){
            sinter.validate();
            sinter.draft();
        });
    }
    navigator.id.watch({
        onlogin:sinter.login,
        onlogout:sinter.logout
    });
});
<|endoftext|>


<commit_before>const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;

var EXPORTED_SYMBOLS = ["loadButtons", "unloadButtons"];
var usingCustomizableUI = true;

try {
	Cu.import("resource:///modules/CustomizableUI.jsm");
} catch(e) {
	usingCustomizableUI = false;
	var CustomizableUIs = {};
	var CustomizableUI = null;
	Cu.import("chrome://{{chrome-name}}/content/customizable.jsm");
}
Cu.import("resource://services-common/stringbundle.js");
{{modules}}

var toolbar_buttons = {
	interfaces: {},
	// the important global objects used by the extension
	toolbar_button_loader: function(parent, child) {
		var object_name;
		for(object_name in child){
			if(object_name == 'interfaces') {
				toolbar_buttons.toolbar_button_loader(parent.interfaces, child.interfaces);
			} else {
				parent[object_name] = child[object_name];
			}
		}
	}
};
var loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(Ci.mozIJSSubScriptLoader);
var gScope = this;

function loadButtons(window) {
	var toolbox = window.document.getElementById('{{toolbox}}');
	if(!toolbox) {
		return;
	}
	var scope = gScope;
	scope.window = window;
	scope.document = window.document;
	if(!usingCustomizableUI) { //this is out own hacked up version
		CustomizableUI = new customizableUI(toolbox);
		CustomizableUIs[window] = CustomizableUI;
	}
	let buttonStrings = new StringBundle("chrome://{{chrome-name}}/locale/{{locale-file-prefix}}button_labels.properties");
	{{scripts}}

	{{toolbars}}
	registerToolbars(window, document, {{toolbar_ids}});

{{buttons}}

	{{menu}}

	{{keys}}

	{{end}}
}

function unloadButtons(window) {
	var gScope = null;
	var toolbar_buttons = null;

	var document = window.document;
	var button_ids = {{button_ids}};
	var toolbar_ids = {{toolbar_ids}};
	if(!usingCustomizableUI) { //this is out own hacked up version
		CustomizableUI = CustomizableUIs[window];
		delete CustomizableUIs[window];
	}
	for(var i in button_ids) {
		var button_id = button_ids[i];
		CustomizableUI.destroyWidget(button_id);
		var key = document.getElementById(button_id + '-key');
		if(key) {
			key.parentNode.removeChild(key);
		}
		var menuitem = document.getElementById(button_id + '-menu-item');
		if(menuitem) {
			menuitem.parentNode.removeChild(menuitem);
		}
	}
	var menu = document.getElementById('{{menu_id}}');
	if(menu && !menu.firstChild.firstChild) {
		menu.parentNode.removeChild(menu);
	}
	for(var t in toolbar_ids) {
		var toolbar = document.getElementById(toolbar_ids[t]);
		if(toolbar) {
			toolbar.parentNode.removeChild(toolbar);
			CustomizableUI.unregisterArea(toolbar_ids[t], false);
		}
	}
}

function registerToolbars(window, document, toolbar_ids) {
	if(!usingCustomizableUI) { //this is out own hacked up version
		CustomizableUI = CustomizableUIs[window];
	}
	for(var i in toolbar_ids) {
		observeToolbar(toolbar_ids[i]);
		CustomizableUI.registerArea(toolbar_ids[i], {
			type: CustomizableUI.TYPE_TOOLBAR,
			defaultPlacements: [],
			defaultCollapsed: false
		}, true);
	}
}

function observeToolbar(toolbar_id) {
	var prefs = Cc['@mozilla.org/preferences-service;1'].getService(Ci.nsIPrefService)
			.getBranch("{{pref_root}}" + 'toolbar_status.' + toolbar_id + '.');
	var toolbar = document.getElementById(toolbar_id);
	var mutationObserver = new window.MutationObserver(function(mutations) {
		mutations.forEach(function(mutation) {
			if(mutation.attributeName && (!usingCustomizableUI || mutation.attributeName != 'currentset')) {
				prefs.setCharPref(mutation.attributeName, toolbar.getAttribute(mutation.attributeName));
			}
		});
	});
	var attrList = prefs.getChildList('', {});
	for(var i in attrList) {
		toolbar.setAttribute(attrList[i], prefs.getCharPref(attrList[i]));
	}
	mutationObserver.observe(toolbar, { attributes: true, subtree: false });
}<commit_msg>extra clean up code<commit_after>const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;

var EXPORTED_SYMBOLS = ["loadButtons", "unloadButtons"];
var usingCustomizableUI = true;

try {
	Cu.import("resource:///modules/CustomizableUI.jsm");
} catch(e) {
	usingCustomizableUI = false;
	var CustomizableUIs = {};
	var CustomizableUI = null;
	Cu.import("chrome://{{chrome-name}}/content/customizable.jsm");
}

Cu.import('resource://gre/modules/Services.jsm');
Cu.import("resource://services-common/stringbundle.js");
{{modules}}

var toolbar_buttons = {
	interfaces: {},
	// the important global objects used by the extension
	toolbar_button_loader: function(parent, child) {
		var object_name;
		for(object_name in child){
			if(object_name == 'interfaces') {
				toolbar_buttons.toolbar_button_loader(parent.interfaces, child.interfaces);
			} else {
				parent[object_name] = child[object_name];
			}
		}
	}
};
var loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(Ci.mozIJSSubScriptLoader);
var gScope = this;

function loadButtons(window) {
	var toolbox = window.document.getElementById('{{toolbox}}');
	if(!toolbox) {
		return;
	}
	var scope = gScope;
	scope.window = window;
	scope.document = window.document;
	if(!usingCustomizableUI) { //this is out own hacked up version
		CustomizableUI = new customizableUI(toolbox);
		CustomizableUIs[window] = CustomizableUI;
	}
	let buttonStrings = new StringBundle("chrome://{{chrome-name}}/locale/{{locale-file-prefix}}button_labels.properties");
	{{scripts}}

	{{toolbars}}
	registerToolbars(window, document, {{toolbar_ids}});

{{buttons}}

	{{menu}}

	{{keys}}

	{{end}}
}

function unloadButtons(window) {
	var gScope = null;
	var toolbar_buttons = null;

	var document = window.document;
	var button_ids = {{button_ids}};
	var toolbar_ids = {{toolbar_ids}};
	if(!usingCustomizableUI) { //this is out own hacked up version
		CustomizableUI = CustomizableUIs[window];
		delete CustomizableUIs[window];
	}
	for(var i in button_ids) {
		var button_id = button_ids[i];
		CustomizableUI.destroyWidget(button_id);
		var key = document.getElementById(button_id + '-key');
		if(key) {
			key.parentNode.removeChild(key);
		}
		var menuitem = document.getElementById(button_id + '-menu-item');
		if(menuitem) {
			menuitem.parentNode.removeChild(menuitem);
		}
	}
	var menu = document.getElementById('{{menu_id}}');
	if(menu && !menu.firstChild.firstChild) {
		menu.parentNode.removeChild(menu);
	}
	for(var t in toolbar_ids) {
		var toolbar = document.getElementById(toolbar_ids[t]);
		if(toolbar) {
			toolbar.parentNode.removeChild(toolbar);
			CustomizableUI.unregisterArea(toolbar_ids[t], false);
		}
	}
}

function registerToolbars(window, document, toolbar_ids) {
	if(!usingCustomizableUI) { //this is out own hacked up version
		CustomizableUI = CustomizableUIs[window];
	}
	for(var i in toolbar_ids) {
		observeToolbar(toolbar_ids[i]);
		CustomizableUI.registerArea(toolbar_ids[i], {
			type: CustomizableUI.TYPE_TOOLBAR,
			defaultPlacements: [],
			defaultCollapsed: false
		}, true);
	}
}

function observeToolbar(toolbar_id) {
	var prefs = Cc['@mozilla.org/preferences-service;1'].getService(Ci.nsIPrefService)
			.getBranch("{{pref_root}}" + 'toolbar_status.' + toolbar_id + '.');
	var toolbar = document.getElementById(toolbar_id);
	var mutationObserver = new window.MutationObserver(function(mutations) {
		mutations.forEach(function(mutation) {
			if(mutation.attributeName && (!usingCustomizableUI || mutation.attributeName != 'currentset')) {
				prefs.setCharPref(mutation.attributeName, toolbar.getAttribute(mutation.attributeName));
			}
		});
	});
	var attrList = prefs.getChildList('', {});
	for(var i in attrList) {
		toolbar.setAttribute(attrList[i], prefs.getCharPref(attrList[i]));
	}
	mutationObserver.observe(toolbar, { attributes: true, subtree: false });
}<|endoftext|>


<commit_before>import UAParser from 'ua-parser-js';

const uaParser = new UAParser();
const ua = uaParser.getResult();

export const hasModulesSupport = () => {
    const script = document.createElement('script');
    return 'noModule' in script;
};

export const isFileSaverSupported = () => 'download' in document.createElement('a') || navigator.msSaveOrOpenBlob;

export const textToClipboard = (text) => {
    const dummy = document.createElement('textarea');

    document.body.appendChild(dummy);
    dummy.value = text;
    dummy.select();
    document.execCommand('copy');
    document.body.removeChild(dummy);
};

export const getOS = () => {
    const { name = 'other', version = '' } = ua.os;
    return { name, version };
};

export const isSafari = () => ['Safari', 'Mobile Safari'].includes(ua.browser.name);
export const isSafariMobile = () => ua.browser.name === 'Mobile Safari';
export const isIE11 = () => ua.browser.name === 'IE' && ua.browser.major === '11';
export const isEdge = () => ua.browser.name === 'Edge';
export const isFirefox = () => ua.browser.name === 'Firefox';
export const isChrome = () => ua.browser.name === 'Chrome';
export const isMac = () => ua.os.name === 'Mac OS';
export const hasTouch = 'ontouchstart' in document.documentElement;
export const hasCookie = () => navigator.cookieEnabled;
export const getBrowser = () => ua.browser;
export const getDevice = () => ua.device;
export const isMobile = () => {
    const { type } = getDevice();
    return type === 'mobile';
};

export const doNotTrack = () => {
    return (
        navigator.doNotTrack === '1' ||
        navigator.doNotTrack === 'yes' ||
        navigator.msDoNotTrack === '1' ||
        window.doNotTrack === '1'
    );
};

export const parseURL = (url = '') => {
    const parser = document.createElement('a');
    const searchObject = {};
    // Let the browser do the work
    parser.href = url;
    // Convert query string to object
    const queries = parser.search.replace(/^\?/, '').split('&');

    for (let i = 0; i < queries.length; i++) {
        const [key, value] = queries[i].split('=');
        searchObject[key] = value;
    }

    return {
        protocol: parser.protocol,
        host: parser.host,
        hostname: parser.hostname,
        port: parser.port,
        pathname: parser.pathname,
        search: parser.search,
        searchObject,
        hash: parser.hash
    };
};

export const getActiveXObject = (name) => {
    try {
        // eslint-disable-next-line no-undef
        return new ActiveXObject(name);
    } catch (error) {
        // eslint-disable-next-line no-console
        console.error(error);
    }
};

export const isIos = () => /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
export const hasAcrobatInstalled = () => getActiveXObject('AcroPDF.PDF') || getActiveXObject('PDF.PdfCtrl');
export const hasPDFSupport = () => navigator.mimeTypes['application/pdf'] || hasAcrobatInstalled() || isIos();
export const redirectTo = (url = '') => document.location.replace(`${document.location.origin}${url}`);
<commit_msg>Add requireDirectAction detector<commit_after>import UAParser from 'ua-parser-js';

const uaParser = new UAParser();
const ua = uaParser.getResult();

export const hasModulesSupport = () => {
    const script = document.createElement('script');
    return 'noModule' in script;
};

export const isFileSaverSupported = () => 'download' in document.createElement('a') || navigator.msSaveOrOpenBlob;

export const textToClipboard = (text) => {
    const dummy = document.createElement('textarea');

    document.body.appendChild(dummy);
    dummy.value = text;
    dummy.select();
    document.execCommand('copy');
    document.body.removeChild(dummy);
};

export const getOS = () => {
    const { name = 'other', version = '' } = ua.os;
    return { name, version };
};

export const isSafari = () => ['Safari', 'Mobile Safari'].includes(ua.browser.name);
export const isSafariMobile = () => ua.browser.name === 'Mobile Safari';
export const isIE11 = () => ua.browser.name === 'IE' && ua.browser.major === '11';
export const isEdge = () => ua.browser.name === 'Edge';
export const isFirefox = () => ua.browser.name === 'Firefox';
export const isChrome = () => ua.browser.name === 'Chrome';
export const isMac = () => ua.os.name === 'Mac OS';
export const hasTouch = 'ontouchstart' in document.documentElement;
export const hasCookie = () => navigator.cookieEnabled;
export const getBrowser = () => ua.browser;
export const getDevice = () => ua.device;
export const isMobile = () => {
    const { type } = getDevice();
    return type === 'mobile';
};

export const doNotTrack = () => {
    return (
        navigator.doNotTrack === '1' ||
        navigator.doNotTrack === 'yes' ||
        navigator.msDoNotTrack === '1' ||
        window.doNotTrack === '1'
    );
};

export const parseURL = (url = '') => {
    const parser = document.createElement('a');
    const searchObject = {};
    // Let the browser do the work
    parser.href = url;
    // Convert query string to object
    const queries = parser.search.replace(/^\?/, '').split('&');

    for (let i = 0; i < queries.length; i++) {
        const [key, value] = queries[i].split('=');
        searchObject[key] = value;
    }

    return {
        protocol: parser.protocol,
        host: parser.host,
        hostname: parser.hostname,
        port: parser.port,
        pathname: parser.pathname,
        search: parser.search,
        searchObject,
        hash: parser.hash
    };
};

export const getActiveXObject = (name) => {
    try {
        // eslint-disable-next-line no-undef
        return new ActiveXObject(name);
    } catch (error) {
        // eslint-disable-next-line no-console
        console.error(error);
    }
};

export const isIos = () => /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
export const hasAcrobatInstalled = () => getActiveXObject('AcroPDF.PDF') || getActiveXObject('PDF.PdfCtrl');
export const hasPDFSupport = () => navigator.mimeTypes['application/pdf'] || hasAcrobatInstalled() || isIos();
export const redirectTo = (url = '') => document.location.replace(`${document.location.origin}${url}`);

/**
 * Detect browser requiring direct action
 * Like opening a new tab
 * @returns {Boolean}
 */
export const requireDirectAction = () => isSafari() || isFirefox();
<|endoftext|>


<commit_before>'use strict';

var BaseService = require('./service');
var inherits = require('util').inherits;
var fs = require('fs');

var InsightUI = function(options) {
  BaseService.call(this, options);
  this.routePrefix = options.routePrefix;
  if (typeof options.apiPrefix !== 'undefined') {
    this.apiPrefix = options.apiPrefix;
  } else {
    this.apiPrefix = 'insight-api';
  }
  if (typeof options.routePrefix !== 'undefined') {
    this.routePrefix = options.routePrefix;
  } else {
    this.routePrefix = 'insight';
  }
};

InsightUI.dependencies = ['insight-api'];

inherits(InsightUI, BaseService);

InsightUI.prototype.start = function(callback) {
  this.indexFile = this.filterIndexHTML(fs.readFileSync(__dirname + '/../public/index.html', {encoding: 'utf8'}));
  setImmediate(callback);
};

InsightUI.prototype.getRoutePrefix = function() {
  return this.routePrefix;
};

InsightUI.prototype.setupRoutes = function(app, express) {
  var self = this;

  app.use('/', function(req, res, next){
    if (req.headers.accept && req.headers.accept.indexOf('text/html') !== -1 &&
      req.headers["X-Requested-With"] !== 'XMLHttpRequest'
    ) {
      res.setHeader('Content-Type', 'text/html');
      res.send(self.indexFile);
    } else {
      express.static(__dirname + '/../public')(req, res, next);
    }
  });
};

InsightUI.prototype.filterIndexHTML = function(data) {
  var transformed = data
    .replace(/apiPrefix = '\/api'/, "apiPrefix = '/" + this.apiPrefix + "'");

  if (this.routePrefix) {
    transformed = transformed.replace(/<base href=\"\/\"/, '<base href="/' + this.routePrefix + '/"');
  }

  return transformed;
};

module.exports = InsightUI;
<commit_msg>Remove unnecessary line.<commit_after>'use strict';

var BaseService = require('./service');
var inherits = require('util').inherits;
var fs = require('fs');

var InsightUI = function(options) {
  BaseService.call(this, options);
  if (typeof options.apiPrefix !== 'undefined') {
    this.apiPrefix = options.apiPrefix;
  } else {
    this.apiPrefix = 'insight-api';
  }
  if (typeof options.routePrefix !== 'undefined') {
    this.routePrefix = options.routePrefix;
  } else {
    this.routePrefix = 'insight';
  }
};

InsightUI.dependencies = ['insight-api'];

inherits(InsightUI, BaseService);

InsightUI.prototype.start = function(callback) {
  this.indexFile = this.filterIndexHTML(fs.readFileSync(__dirname + '/../public/index.html', {encoding: 'utf8'}));
  setImmediate(callback);
};

InsightUI.prototype.getRoutePrefix = function() {
  return this.routePrefix;
};

InsightUI.prototype.setupRoutes = function(app, express) {
  var self = this;

  app.use('/', function(req, res, next){
    if (req.headers.accept && req.headers.accept.indexOf('text/html') !== -1 &&
      req.headers["X-Requested-With"] !== 'XMLHttpRequest'
    ) {
      res.setHeader('Content-Type', 'text/html');
      res.send(self.indexFile);
    } else {
      express.static(__dirname + '/../public')(req, res, next);
    }
  });
};

InsightUI.prototype.filterIndexHTML = function(data) {
  var transformed = data
    .replace(/apiPrefix = '\/api'/, "apiPrefix = '/" + this.apiPrefix + "'");

  if (this.routePrefix) {
    transformed = transformed.replace(/<base href=\"\/\"/, '<base href="/' + this.routePrefix + '/"');
  }

  return transformed;
};

module.exports = InsightUI;
<|endoftext|>


<commit_before>function getFirstLine(message) {
  const index = message.indexOf('\n');
  if (index === -1) {
    return message;
  }

  return message.slice(0, index);
}

async function getBody({ github, core, context, target }) {
  const res = await github.repos.getLatestRelease({
    owner: context.repo.owner,
    repo: context.repo.repo,
  });

  const latestRelease = res.data;
  const diff = await github.repos.compareCommits({
    owner: context.repo.owner,
    repo: context.repo.repo,
    base: latestRelease.tag_name,
    head: target,
  });

  const commits = diff.data.commits;
  if (!commits.length) {
    return 'No changes';
  }

  const format = (log) => `* ${log.title} (${log.hash}) ${log.name} <${log.email}>`;
  const lines = commits.map((c) => {
    const payload = {
      title: getFirstLine(c.commit.message),
      hash: c.sha.slice(0, 7),
      name: c.commit.author.name,
      email: c.commit.author.email,
    };
    return format(payload);
  });

  return lines.join('\n');
}

/**
 * Create Github Release given the version (provided by a tag)
 */
async function createRelease({ context, core, github, sha, version }) {
  const title = `### Release Note (${version})`;
  const body = await getBody({ github, core, context, target: sha });
  const releaseBody = `${title}\n\n${body}`;

  // TODO: Update ChangeLog.md or perhaps take release body from manual
  // ChangeLog updates.

  const release = {
    owner: context.repo.owner,
    repo: context.repo.repo,
    tag_name: version,
    target_commitish: sha,
    name: version,
    body: releaseBody,
    draft: false,
    prelease: false,
  };

  await github.repos.createRelease(release);
}

module.exports = createRelease;
<commit_msg>Remove generated release note (#1135)<commit_after>/**
 * Create Github Release given the version (provided by a tag)
 */
async function createRelease({ context, core, github, sha, version }) {
  const title = `### Release Note (${version})`;
  const body = '[Insert ChangeLog update]';
  const releaseBody = `${title}\n\n${body}`;

  const release = {
    owner: context.repo.owner,
    repo: context.repo.repo,
    tag_name: version,
    target_commitish: sha,
    name: version,
    body: releaseBody,
    draft: false,
    prelease: false,
  };

  await github.repos.createRelease(release);
}

module.exports = createRelease;
<|endoftext|>


<commit_before>'use strict';

/* private */

const childproc = require('child_process');
const plist = require('simple-plist');
const which = require('which');
const fs = require('fs');

var use7zip = false;
var useOpenSSL = false;

const cmd = {
  '7z': '/usr/local/bin/7z',
  zip: '/usr/bin/zip',
  unzip: '/usr/bin/unzip',
  codesign: '/usr/bin/codesign',
  security: '/usr/bin/security',
  xcodebuild: '/usr/bin/xcodebuild',
  /* only when useOpenSSL is true */
  openssl: '/usr/local/bin/openssl',
  insert_dylib: 'insert_dylib',
  lipo: '/usr/bin/lipo'
};

function execProgram (bin, arg, opt, cb) {
  // new code
  let _out = Buffer.alloc(0);
  let _err = Buffer.alloc(0);
  const child = childproc.spawn(bin, arg);
  child.stdout.on('data', data => {
    _out = Buffer.concat([_out, data]);
  });
  child.stderr.on('data', data => {
    _err = Buffer.concat([_err, data]);
  });
  child.stdin.end(); // ^D works fine for unzip (y/n/^C)
  child.on('close', code => {
    if (code !== 0) {
      let msg = 'stdout: ' + _out.toString('utf8');
      msg += '\nstderr: ' + _err.toString('utf8');
      msg += '\ncode: ' + code;
      return cb(new Error(msg));
    }
    cb(null, _out, _err);
  });
  return;
}

/* public */

function findInPath (cb, user) {
  const keys = Object.keys(cmd);
  let pending = keys.length;
  for (let key of keys) {
    which(key, function (err, loc) {
      if (err !== undefined) {
        cmd[key] = loc;
        if (--pending === 0) {
          cb(err, user);
        }
      }
    });
  }
}

function codesign (identity, entitlement, keychain, file, cb) {
  /* use the --no-strict to avoid the "resource envelope is obsolete" error */
  const args = [ '--no-strict' ]; // http://stackoverflow.com/a/26204757
  if (identity === undefined) {
    return cb(new Error('--identity is required to sign'));
  }
  args.push('-fs', identity);
  if (typeof entitlement === 'string') {
    args.push('--entitlements=' + entitlement);
  }
  if (typeof keychain === 'string') {
    args.push('--keychain=' + keychain);
  }
  args.push(file);
  execProgram(cmd.codesign, args, null, cb);
}

function verifyCodesign (file, keychain, cb) {
  const args = ['-v', '--no-strict'];
  if (typeof keychain === 'string') {
    args.push('--keychain=' + keychain);
  }
  args.push(file);
  execProgram(cmd.codesign, args, null, cb);
}

function getMobileProvisionPlist (file, cb) {
  function parseMobileProvisioning (error, stdout) {
    if (error) {
      return cb(error);
    }
    if (stdout === '') {
      const msg = `Empty entitlements for ${file}.\nAre you providing a mobile provisioning with -m?`;
      cb(new Error(msg));
    } else {
      try {
        cb(null, plist.parse(stdout));
      } catch (e) {
        cb(e);
      }
    }
  }
  if (useOpenSSL === true) {
    try {
      /* portable using openssl */
      const args = [ 'cms', '-in', file, '-inform', 'der', '-verify' ];
      execProgram(cmd.openssl, args, null, parseMobileProvisioning);
    } catch (e) {
      cb(e);
    }
  } else {
    try {
      /* OSX specific using security */
      const args = [ 'cms', '-D', '-i', file ];
      execProgram(cmd.security, args, null, parseMobileProvisioning);
    } catch (e) {
      cb(e);
    }
  }
}

function getEntitlementsFromMobileProvision (file, cb) {
  return getMobileProvisionPlist(file, (e, o) => {
    return e? cb(e, o): cb(e, o['Entitlements']);
  });
}

function zip (cwd, ofile, src, cb) {
  if (use7zip) {
    fs.unlink(ofile, () => {
      const zipFile = ofile + '.zip';
      const args = [ 'a', zipFile, src ];
      execProgram(cmd['7z'], args, { cwd: cwd }, (error, message) => {
        if (error) {
          return cb(error, message);
        }
        fs.rename(zipFile, ofile, cb);
      });
    });
  } else {
    fs.unlink(ofile, () => {
      const args = [ '-qry', ofile, src ];
      execProgram(cmd.zip, args, { cwd: cwd }, cb);
    });
  }
}

function unzip (ifile, odir, cb) {
  if (use7zip) {
    const args = [ 'x', '-y', '-o' + odir, ifile ];
    return execProgram(cmd['7z'], args, null, cb);
  }
  const args = [ '-o', ifile, '-d', odir ];
  execProgram(cmd.unzip, args, null, cb);
}

function xcaToIpa (ifile, odir, cb) {
  const args = [ '-exportArchive', '-exportFormat', 'ipa', '-archivePath', ifile, '-exportPath', odir ];
  execProgram(cmd.xcodebuild, args, null, cb);
}

function insertLibrary (lib, bin, out, cb) {
  try {
    const machoMangle = require('macho-mangle');
    try {
      let src = fs.readFileSync(bin);
      if (lib.indexOf('@rpath') === 0) {
        src = machoMangle(src, {
          type: 'rpath',
          name: '@executable_path/Frameworks'
        });
      }
      const dst = machoMangle(src, {
        type: 'load_dylib',
        name: lib,
        version: {
          current: '1.0.0',
          compat: '0.0.0'
        }
      });
      fs.writeFileSync(bin, dst);
      console.log('Library inserted');
      cb();
    } catch (error) {
      return cb(error);
    }
  } catch (_) {
    const args = [ '--strip-codesig', '--all-yes', lib, bin, bin ];
    execProgram(cmd.insert_dylib, args, null, (error, stdout) => {
      if (error) {
        return cb(error);
      }
      cb();
    });
  }
}

function getIdentities (cb) {
  const args = [ 'find-identity', '-v', '-p', 'codesigning' ];
  execProgram(cmd.security, args, null, (error, stdout) => {
    if (error) {
      return cb(error);
    }
    const lines = stdout.split('\n');
    lines.pop(); // remove last line
    let ids = [];
    lines.filter(entry => {
      return entry.indexOf('CSSMERR_TP_CERT_REVOKED') === -1;
    }).forEach((line) => {
      const tok = line.indexOf(') ');
      if (tok !== -1) {
        const msg = line.substring(tok + 2).trim();
        const tok2 = msg.indexOf(' ');
        if (tok2 !== -1) {
          ids.push({
            'hash': msg.substring(0, tok2),
            'name': msg.substring(tok2 + 1)
          });
        }
      }
    });
    cb(undefined, ids);
  });
}

function lipoFile (file, arch, cb) {
  const args = [ file, '-thin', arch, '-output', file ];
  execProgram(cmd.lipo, args, null, cb);
}

function setOptions (obj) {
  if (typeof obj.use7zip !== 'undefined') {
    use7zip = obj.use7zip;
  }
  if (typeof obj.useOpenSSL !== 'undefined') {
    useOpenSSL = obj.useOpenSSL;
  }
}

[ findInPath,
  codesign,
  verifyCodesign,
  getEntitlementsFromMobileProvision,
  getMobileProvisionPlist,
  zip,
  unzip,
  xcaToIpa,
  getIdentities,
  insertLibrary,
  lipoFile,
  setOptions
].forEach(function (x) {
  module.exports[x.name] = x;
});
<commit_msg>Honor spawn options<commit_after>'use strict';

/* private */

const childproc = require('child_process');
const plist = require('simple-plist');
const which = require('which');
const fs = require('fs');

var use7zip = false;
var useOpenSSL = false;

const cmd = {
  '7z': '/usr/local/bin/7z',
  zip: '/usr/bin/zip',
  unzip: '/usr/bin/unzip',
  codesign: '/usr/bin/codesign',
  security: '/usr/bin/security',
  xcodebuild: '/usr/bin/xcodebuild',
  /* only when useOpenSSL is true */
  openssl: '/usr/local/bin/openssl',
  insert_dylib: 'insert_dylib',
  lipo: '/usr/bin/lipo'
};

function execProgram (bin, arg, opt, cb) {
  let _out = Buffer.alloc(0);
  let _err = Buffer.alloc(0);
  const child = childproc.spawn(bin, arg, opt || {});
  child.stdout.on('data', data => {
    _out = Buffer.concat([_out, data]);
  });
  child.stderr.on('data', data => {
    _err = Buffer.concat([_err, data]);
  });
  child.stdin.end();
  child.on('close', code => {
    if (code !== 0) {
      let msg = 'stdout: ' + _out.toString('utf8');
      msg += '\nstderr: ' + _err.toString('utf8');
      msg += '\ncommand: ' + bin + ' ' + arg.join(' ');
      msg += '\ncode: ' + code;
      return cb(new Error(msg));
    }
    cb(null, _out, _err);
  });
}

/* public */

function findInPath (cb, user) {
  const keys = Object.keys(cmd);
  let pending = keys.length;
  for (let key of keys) {
    which(key, function (err, loc) {
      if (err !== undefined) {
        cmd[key] = loc;
        if (--pending === 0) {
          cb(err, user);
        }
      }
    });
  }
}

function codesign (identity, entitlement, keychain, file, cb) {
  /* use the --no-strict to avoid the "resource envelope is obsolete" error */
  const args = [ '--no-strict' ]; // http://stackoverflow.com/a/26204757
  if (identity === undefined) {
    return cb(new Error('--identity is required to sign'));
  }
  args.push('-fs', identity);
  if (typeof entitlement === 'string') {
    args.push('--entitlements=' + entitlement);
  }
  if (typeof keychain === 'string') {
    args.push('--keychain=' + keychain);
  }
  args.push(file);
  execProgram(cmd.codesign, args, null, cb);
}

function verifyCodesign (file, keychain, cb) {
  const args = ['-v', '--no-strict'];
  if (typeof keychain === 'string') {
    args.push('--keychain=' + keychain);
  }
  args.push(file);
  execProgram(cmd.codesign, args, null, cb);
}

function getMobileProvisionPlist (file, cb) {
  function parseMobileProvisioning (error, stdout) {
    if (error) {
      return cb(error);
    }
    if (stdout === '') {
      const msg = `Empty entitlements for ${file}.\nAre you providing a mobile provisioning with -m?`;
      cb(new Error(msg));
    } else {
      try {
        cb(null, plist.parse(stdout));
      } catch (e) {
        cb(e);
      }
    }
  }
  if (useOpenSSL === true) {
    try {
      /* portable using openssl */
      const args = [ 'cms', '-in', file, '-inform', 'der', '-verify' ];
      execProgram(cmd.openssl, args, null, parseMobileProvisioning);
    } catch (e) {
      cb(e);
    }
  } else {
    try {
      /* OSX specific using security */
      const args = [ 'cms', '-D', '-i', file ];
      execProgram(cmd.security, args, null, parseMobileProvisioning);
    } catch (e) {
      cb(e);
    }
  }
}

function getEntitlementsFromMobileProvision (file, cb) {
  return getMobileProvisionPlist(file, (e, o) => {
    return e? cb(e, o): cb(e, o['Entitlements']);
  });
}

function zip (cwd, ofile, src, cb) {
  if (use7zip) {
    fs.unlink(ofile, () => {
      const zipFile = ofile + '.zip';
      const args = [ 'a', zipFile, src ];
      execProgram(cmd['7z'], args, { cwd: cwd }, (error, message) => {
        if (error) {
          return cb(error, message);
        }
        fs.rename(zipFile, ofile, cb);
      });
    });
  } else {
    fs.unlink(ofile, () => {
      const args = [ '-qry', ofile, src ];
      execProgram(cmd.zip, args, { cwd: cwd }, cb);
    });
  }
}

function unzip (ifile, odir, cb) {
  if (use7zip) {
    const args = [ 'x', '-y', '-o' + odir, ifile ];
    return execProgram(cmd['7z'], args, null, cb);
  }
  const args = [ '-o', ifile, '-d', odir ];
  execProgram(cmd.unzip, args, null, cb);
}

function xcaToIpa (ifile, odir, cb) {
  const args = [ '-exportArchive', '-exportFormat', 'ipa', '-archivePath', ifile, '-exportPath', odir ];
  execProgram(cmd.xcodebuild, args, null, cb);
}

function insertLibrary (lib, bin, out, cb) {
  try {
    const machoMangle = require('macho-mangle');
    try {
      let src = fs.readFileSync(bin);
      if (lib.indexOf('@rpath') === 0) {
        src = machoMangle(src, {
          type: 'rpath',
          name: '@executable_path/Frameworks'
        });
      }
      const dst = machoMangle(src, {
        type: 'load_dylib',
        name: lib,
        version: {
          current: '1.0.0',
          compat: '0.0.0'
        }
      });
      fs.writeFileSync(bin, dst);
      console.log('Library inserted');
      cb();
    } catch (error) {
      return cb(error);
    }
  } catch (_) {
    const args = [ '--strip-codesig', '--all-yes', lib, bin, bin ];
    execProgram(cmd.insert_dylib, args, null, (error, stdout) => {
      if (error) {
        return cb(error);
      }
      cb();
    });
  }
}

function getIdentities (cb) {
  const args = [ 'find-identity', '-v', '-p', 'codesigning' ];
  execProgram(cmd.security, args, null, (error, stdout) => {
    if (error) {
      return cb(error);
    }
    const lines = stdout.split('\n');
    lines.pop(); // remove last line
    let ids = [];
    lines.filter(entry => {
      return entry.indexOf('CSSMERR_TP_CERT_REVOKED') === -1;
    }).forEach((line) => {
      const tok = line.indexOf(') ');
      if (tok !== -1) {
        const msg = line.substring(tok + 2).trim();
        const tok2 = msg.indexOf(' ');
        if (tok2 !== -1) {
          ids.push({
            'hash': msg.substring(0, tok2),
            'name': msg.substring(tok2 + 1)
          });
        }
      }
    });
    cb(undefined, ids);
  });
}

function lipoFile (file, arch, cb) {
  const args = [ file, '-thin', arch, '-output', file ];
  execProgram(cmd.lipo, args, null, cb);
}

function setOptions (obj) {
  if (typeof obj.use7zip !== 'undefined') {
    use7zip = obj.use7zip;
  }
  if (typeof obj.useOpenSSL !== 'undefined') {
    useOpenSSL = obj.useOpenSSL;
  }
}

[ findInPath,
  codesign,
  verifyCodesign,
  getEntitlementsFromMobileProvision,
  getMobileProvisionPlist,
  zip,
  unzip,
  xcaToIpa,
  getIdentities,
  insertLibrary,
  lipoFile,
  setOptions
].forEach(function (x) {
  module.exports[x.name] = x;
});
<|endoftext|>


<commit_before>'use strict';

var app = angular.module('contactserverApp', ['ngRoute', 'contactserverApp.services']);

app.config(['$routeProvider', function($routeProvider) {
    $routeProvider.
    when('/', {
        controller: 'ContactListCtrl',
        resolve: {
            contacts: function(MultiContactLoader) {
                return MultiContactLoader();
            }
        },
        templateUrl: 'views/view_contact_list.html'
    }).when('/view/:contactId', {
        controller: 'ContactViewCtrl',
        resolve: {
            contact: function(ContactLoader) {
                return ContactLoader();
            }
        },
        templateUrl: 'views/view_contact.html'
    }).otherwise({
        redirectTo: '/'
    });
}]);

app.controller('ContactListCtrl', ['$scope', '$http', function($scope, $http) {
    $http.get('/contacts').success(function(data, status, headers, config) {
        $scope.contacts = data;
    });
}]);

app.controller('ContactViewCtrl', ['$scope', 'contact', function($scope, contact) {
    $scope.contact = contact;
}]);<commit_msg>Using my custom services to get contact list instead of<commit_after>'use strict';

var app = angular.module('contactserverApp', ['ngRoute', 'contactserverApp.services']);

app.config(['$routeProvider', function($routeProvider) {
    $routeProvider.
    when('/', {
        controller: 'ContactListCtrl',
        resolve: {
            contacts: function(MultiContactLoader) {
                return MultiContactLoader();
            }
        },
        templateUrl: 'views/view_contact_list.html'
    }).when('/view/:contactId', {
        controller: 'ContactViewCtrl',
        resolve: {
            contact: function(ContactLoader) {
                return ContactLoader();
            }
        },
        templateUrl: 'views/view_contact.html'
    }).otherwise({
        redirectTo: '/'
    });
}]);

app.controller('ContactListCtrl', ['$scope', 'contacts', function($scope, contacts) {
    $scope.contacts = contacts;
}]);

app.controller('ContactViewCtrl', ['$scope', 'contact', function($scope, contact) {
    $scope.contact = contact;
}]);<|endoftext|>


<commit_before>var iconv = require('iconv-lite');
var zlib = require('zlib');
var MAX_REQ_SIZE = 128 * 1024;
var MAX_RES_SIZE = 256 * 1024;
var TIMEOUT = 36000;
var CLEAR_INTERVAL = 5000;
var CACHE_TIME = CLEAR_INTERVAL * 2;
var MAX_LENGTH = 512;
var MIN_LENGTH = 412;
var COUNT = 100;
var count = 0;
var ids = [];
var data = {};
var proxy, binded, timeout, interval, util;

function disable() {
	proxy.removeListener('request', handleRequest);
	proxy.removeListener('tunnel', handleTunnel);
	proxy.removeListener('tunnelProxy', handleTunnelProxy);

	ids = [];
	data = {};
	interval && clearInterval(interval);
	interval = null;
	binded = false;
}

function enable() {
	if (!binded) {
		proxy.on('request', handleRequest);
		proxy.on('tunnel', handleTunnel);
		proxy.on('tunnelProxy', handleTunnelProxy);
	}

	binded = true;
	clearTimeout(timeout);
	timeout = setTimeout(disable, TIMEOUT);
	if (!interval) {
		interval = setInterval(clearCache, CLEAR_INTERVAL);
	}
}

/**
 * 如果超过最大缓存数，清理如下请求数据：
 * 1. 已经请求结束且结束时间超过10秒
 * 2. 请求#1前面的未结束且未被ui读取过的请求
 */
function clearCache() {
	var len = ids.length;
	if (len <= MAX_LENGTH) {
		return;
	}

	var index = -1; //已经完成，且缓存超过10s的最后一个请求
	var now = Date.now();
	for (var i = len - 1; i >= 0; i--) {
		var curData = data[ids[i]];
		if (curData.endTime && now - curData.endTime > TIMEOUT) {
			index = i;
			break;
		}
	}

	if (index < 0) {
		return;
	}

	var _ids = [];
	var end;
	++index;
	for (var i = 0; i < index; i++) {
		var id = ids[i];
		var curData = data[id];
		if (curData.read && (!curData.endTime || now - curData.endTime < CACHE_TIME
				|| now - curData.startTime < TIMEOUT)) {
			_ids.push(id);
		} else {
			delete data[id];
			if (--len <= MIN_LENGTH) {
				_ids.push.apply(_ids, ids.slice(i + 1, index));
				break;
			}
		}
	}
	ids = _ids.concat(ids.slice(index));
}

function passThrough(chunk, encoding, callback) {
	callback(null, chunk);
}

function decode(body) {
	if (body) {
		var _body = body + '';
		if (_body.indexOf('�') != -1) {
			_body = iconv.decode(body, 'gbk');
		}
		body = _body;
	}

	return body;
}

function get(options) {
	enable();
	options = options || {};
	var data = {};
	var newIds = options.startTime == -1 ? [] : getIds(options.startTime, options.count);
	var list = getList(newIds).concat(getList(options.ids));
	for (var i = 0, len = list.length; i < len; i++) {
		var item = list[i];
		if (item) {
			data[item.id] = item;
		}
	}

	return {
		ids: options.ids || [],
		newIds: newIds,
		data: data
	};
}

function getIds(startTime, count) {
	var len = ids.length;
	if (!len) {
		return [];
	}

	startTime = (startTime || Date.now() - 6000) + '';
	count = Math.min(count || COUNT, len);
	if (ids[0] > startTime) {

		return ids.slice(0, count);
	}

	if (len === 1 || ids[len - 1] <= startTime) {

		return  [];
	}

	var index = getIndex(startTime, 0, len - 1);
	return ids.slice(index, index + count);
}

function getIndex(startTime, start, end) {
	if (end - start <= 1) {
		return ids[start] > startTime ? start : end;
	}

	var mid = Math.floor((start + end) / 2);
	var id = ids[mid];
	return id == startTime ? mid + 1 : (id < startTime ? getIndex(startTime, mid + 1, end)
			: getIndex(startTime, start, mid));
}

function getList(ids) {
	var result = [];
	for (var i = 0, len = ids && ids.length; i < len; i++) {
		var id = ids[i];
		var curData = data[id];
		if (curData) {
			curData.read = true;
			result[i] = curData;
		}
	}

	return result;
}

function handleTunnel(req) {
	handleTunnelRequest(req, true);
}

function handleTunnelProxy(req) {
	handleTunnelRequest(req);
}

function handleTunnelRequest(req, isHttps) {
	var dnsTime = req.dnsTime || 0;
	var now = req.dnsTime = Date.now();
	var startTime = req.dnsTime - dnsTime;
	var id = startTime + '-' + ++count;

	ids.push(id);

	var curData = data[id] = {
			id: id,
			url: util.removeProtocol(req.url, true),
			isHttps: true,
			isHttpsProxy: !isHttps,
			startTime: startTime,
			dnsTime: req.dnsTime,
			requestTime: now,
			responseTime: now,
			endTime: now,
			reqError: !!req.error,
			req: {
				method: req.method || 'CONNECT',
				httpVersion: req.httpVersion || '1.1',
	            ip: util.getClientIp(req) || '::ffff:127.0.0.1',
	            headers: req.headers,
	            body: req.error && req.error.stack
			},
			res: {
				statusCode: req.error ? 502 : '0',
				headers: {},
				ip: req.host
			},
			rules: req.rules
	};
}

function handleRequest(req) {
	var dnsTime = req.dnsTime || 0;
	req.dnsTime = Date.now();
	var startTime = req.dnsTime - dnsTime;
	var id = startTime + '-' + ++count;
	var reqData = {
			method: req.method || 'GET',
			httpVersion: req.httpVersion || '1.1',
            ip: req.ip || '::ffff:127.0.0.1',
            headers: req.headers
		};
	var resData = {
			ip: req.host
	};

	var curData = data[id] = {
			id: id,
			url: req.url,
			startTime: startTime,
			dnsTime: req.dnsTime,
			req: reqData,
			res: resData,
			rules: req.rules
	};

	ids.push(id);
	req.on('response', handleResponse);
	req.on('error', function(err) {
		resData.ip = req.host;
		reqData.body = err && err.stack;
		curData.endTime = curData.requestTime = Date.now();
		curData.reqError = true;
		req.removeListener('response', handleResponse);
		req._transform = passThrough;
	});

	var reqBody;
	var reqSize = 0;

	if (util.hasRequestBody(req)) {
		reqBody = false;
	}
	req._transform = function(chunk, encoding, callback) {

		if (chunk) {
			if (reqBody || reqBody === false) {
				reqBody = reqBody ? Buffer.concat([reqBody, chunk]) : chunk;
			}
			reqSize += chunk.length;
		}

		if (reqBody && reqBody.length > MAX_REQ_SIZE) {
			reqBody = null;
		}

		if (!chunk) {
			curData.requestTime = Date.now();
			curData.reqEnd = true;
			reqData.size = reqSize;
			reqData.body = decode(reqBody);
		}

		callback(null, chunk);
	};

	function handleResponse(res) {
		curData.responseTime = Date.now();
		resData.headers = res.headers;
		resData.statusCode = res.statusCode;
		resData.ip = req.host;
		res.on('error', function(err) {
			resData.ip = req.host;
			resData.body = err && err.stack;
			curData.endTime = Date.now();
			curData.resError = true;
			res._transform = passThrough;
		});

		var resBody;
		var resSize = 0;
		var contentType = util.getContentType(res.headers);
		if (contentType && contentType != 'IMG' && util.hasBody(res)) {
			resBody = false;
		}

		res._transform = function(chunk, encoding, callback) {
			if (chunk) {
				if (resBody || resBody === false) {
					resBody = resBody ? Buffer.concat([resBody, chunk]) : chunk;
				}

				resSize += chunk.length;
			}

			if (resBody && resBody.length > MAX_RES_SIZE) {
				resBody = null;
			}

			if (!chunk) {
				curData.endTime = Date.now();
				curData.resEnd = true;
				resData.size = resSize;
				if (resBody) {
					var unzip;
					switch (util.toLowerCase(res.headers['content-encoding'])) {
					    case 'gzip':
					    	unzip = zlib.gunzip.bind(zlib);
					      break;
					    case 'deflate':
					    	unzip = zlib.inflate.bind(zlib);
					      break;
					}

					if (unzip) {
						unzip(resBody, function(err, body) {
							if (err) {
								callback(err, chunk);
								return;
							}
							resData.body = decode(body);
							callback(null, chunk);
						});
						return;
					}
				}
				resData.body = decode(resBody);
			}

			callback(null, chunk);
		};
	}

}

module.exports = function init(_proxy) {
	proxy = _proxy;
	util = proxy.util;
	enable();
	module.exports = get;
};<commit_msg>compare id<commit_after>var iconv = require('iconv-lite');
var zlib = require('zlib');
var MAX_REQ_SIZE = 128 * 1024;
var MAX_RES_SIZE = 256 * 1024;
var TIMEOUT = 36000;
var CLEAR_INTERVAL = 5000;
var CACHE_TIME = CLEAR_INTERVAL * 2;
var MAX_LENGTH = 512;
var MIN_LENGTH = 412;
var COUNT = 100;
var count = 0;
var ids = [];
var data = {};
var proxy, binded, timeout, interval, util;

function disable() {
	proxy.removeListener('request', handleRequest);
	proxy.removeListener('tunnel', handleTunnel);
	proxy.removeListener('tunnelProxy', handleTunnelProxy);

	ids = [];
	data = {};
	interval && clearInterval(interval);
	interval = null;
	binded = false;
}

function enable() {
	if (!binded) {
		proxy.on('request', handleRequest);
		proxy.on('tunnel', handleTunnel);
		proxy.on('tunnelProxy', handleTunnelProxy);
	}

	binded = true;
	clearTimeout(timeout);
	timeout = setTimeout(disable, TIMEOUT);
	if (!interval) {
		interval = setInterval(clearCache, CLEAR_INTERVAL);
	}
}

/**
 * 如果超过最大缓存数，清理如下请求数据：
 * 1. 已经请求结束且结束时间超过10秒
 * 2. 请求#1前面的未结束且未被ui读取过的请求
 */
function clearCache() {
	var len = ids.length;
	if (len <= MAX_LENGTH) {
		return;
	}

	var index = -1; //已经完成，且缓存超过10s的最后一个请求
	var now = Date.now();
	for (var i = len - 1; i >= 0; i--) {
		var curData = data[ids[i]];
		if (curData.endTime && now - curData.endTime > TIMEOUT) {
			index = i;
			break;
		}
	}

	if (index < 0) {
		return;
	}

	var _ids = [];
	var end;
	++index;
	for (var i = 0; i < index; i++) {
		var id = ids[i];
		var curData = data[id];
		if (curData.read && (!curData.endTime || now - curData.endTime < CACHE_TIME
				|| now - curData.startTime < TIMEOUT)) {
			_ids.push(id);
		} else {
			delete data[id];
			if (--len <= MIN_LENGTH) {
				_ids.push.apply(_ids, ids.slice(i + 1, index));
				break;
			}
		}
	}
	ids = _ids.concat(ids.slice(index));
}

function passThrough(chunk, encoding, callback) {
	callback(null, chunk);
}

function decode(body) {
	if (body) {
		var _body = body + '';
		if (_body.indexOf('�') != -1) {
			_body = iconv.decode(body, 'gbk');
		}
		body = _body;
	}

	return body;
}

function get(options) {
	enable();
	options = options || {};
	var data = {};
	var newIds = options.startTime == -1 ? [] : getIds(options.startTime, options.count);
	var list = getList(newIds).concat(getList(options.ids));
	for (var i = 0, len = list.length; i < len; i++) {
		var item = list[i];
		if (item) {
			data[item.id] = item;
		}
	}

	return {
		ids: options.ids || [],
		newIds: newIds,
		data: data
	};
}

function getIds(startTime, count) {
	var len = ids.length;
	if (!len) {
		return [];
	}

	startTime = ((startTime || Date.now() - 6000) + '').split('-');
	count = Math.min(count || COUNT, len);

	startTime[0] = parseInt(startTime[0], 10) || 0;
	startTime[1] = parseInt(startTime[1], 10) || 0;

	if (compareId(ids[0], startTime)) {

		return ids.slice(0, count);
	}

	var end = len - 1;
	if (!end || !compareId(ids[end], startTime)) {

		return  [];
	}

	var index = getIndex(startTime, 0, end);
	return ids.slice(index, index + count);
}

function compareId(curId, refId) {
	curId = curId.split('-');
	return curId[0] == refId[0] && curId[1] > refId[1] || curId[0] > refId[0];
}

function getIndex(startTime, start, end) {
	if (end - start <= 1) {
		return compareId(ids[start], startTime) ? start : end;
	}

	var mid = Math.floor((start + end) / 2);
	var id = ids[mid];
	return compareId(id, startTime) ? getIndex(startTime, start, mid) : getIndex(startTime, mid + 1, end);
}

function getList(ids) {
	var result = [];
	for (var i = 0, len = ids && ids.length; i < len; i++) {
		var id = ids[i];
		var curData = data[id];
		if (curData) {
			curData.read = true;
			result[i] = curData;
		}
	}

	return result;
}

function handleTunnel(req) {
	handleTunnelRequest(req, true);
}

function handleTunnelProxy(req) {
	handleTunnelRequest(req);
}

function handleTunnelRequest(req, isHttps) {
	var dnsTime = req.dnsTime || 0;
	var now = req.dnsTime = Date.now();
	var startTime = req.dnsTime - dnsTime;
	var id = startTime + '-' + ++count;

	ids.push(id);

	var curData = data[id] = {
			id: id,
			url: util.removeProtocol(req.url, true),
			isHttps: true,
			isHttpsProxy: !isHttps,
			startTime: startTime,
			dnsTime: req.dnsTime,
			requestTime: now,
			responseTime: now,
			endTime: now,
			reqError: !!req.error,
			req: {
				method: req.method || 'CONNECT',
				httpVersion: req.httpVersion || '1.1',
	            ip: util.getClientIp(req) || '::ffff:127.0.0.1',
	            headers: req.headers,
	            body: req.error && req.error.stack
			},
			res: {
				statusCode: req.error ? 502 : '0',
				headers: {},
				ip: req.host
			},
			rules: req.rules
	};
}

function handleRequest(req) {
	var dnsTime = req.dnsTime || 0;
	req.dnsTime = Date.now();
	var startTime = req.dnsTime - dnsTime;
	var id = startTime + '-' + ++count;
	var reqData = {
			method: req.method || 'GET',
			httpVersion: req.httpVersion || '1.1',
            ip: req.ip || '::ffff:127.0.0.1',
            headers: req.headers
		};
	var resData = {
			ip: req.host
	};

	var curData = data[id] = {
			id: id,
			url: req.url,
			startTime: startTime,
			dnsTime: req.dnsTime,
			req: reqData,
			res: resData,
			rules: req.rules
	};

	ids.push(id);
	req.on('response', handleResponse);
	req.on('error', function(err) {
		resData.ip = req.host;
		reqData.body = err && err.stack;
		curData.endTime = curData.requestTime = Date.now();
		curData.reqError = true;
		req.removeListener('response', handleResponse);
		req._transform = passThrough;
	});

	var reqBody;
	var reqSize = 0;

	if (util.hasRequestBody(req)) {
		reqBody = false;
	}
	req._transform = function(chunk, encoding, callback) {

		if (chunk) {
			if (reqBody || reqBody === false) {
				reqBody = reqBody ? Buffer.concat([reqBody, chunk]) : chunk;
			}
			reqSize += chunk.length;
		}

		if (reqBody && reqBody.length > MAX_REQ_SIZE) {
			reqBody = null;
		}

		if (!chunk) {
			curData.requestTime = Date.now();
			curData.reqEnd = true;
			reqData.size = reqSize;
			reqData.body = decode(reqBody);
		}

		callback(null, chunk);
	};

	function handleResponse(res) {
		curData.responseTime = Date.now();
		resData.headers = res.headers;
		resData.statusCode = res.statusCode;
		resData.ip = req.host;
		res.on('error', function(err) {
			resData.ip = req.host;
			resData.body = err && err.stack;
			curData.endTime = Date.now();
			curData.resError = true;
			res._transform = passThrough;
		});

		var resBody;
		var resSize = 0;
		var contentType = util.getContentType(res.headers);
		if (contentType && contentType != 'IMG' && util.hasBody(res)) {
			resBody = false;
		}

		res._transform = function(chunk, encoding, callback) {
			if (chunk) {
				if (resBody || resBody === false) {
					resBody = resBody ? Buffer.concat([resBody, chunk]) : chunk;
				}

				resSize += chunk.length;
			}

			if (resBody && resBody.length > MAX_RES_SIZE) {
				resBody = null;
			}

			if (!chunk) {
				curData.endTime = Date.now();
				curData.resEnd = true;
				resData.size = resSize;
				if (resBody) {
					var unzip;
					switch (util.toLowerCase(res.headers['content-encoding'])) {
					    case 'gzip':
					    	unzip = zlib.gunzip.bind(zlib);
					      break;
					    case 'deflate':
					    	unzip = zlib.inflate.bind(zlib);
					      break;
					}

					if (unzip) {
						unzip(resBody, function(err, body) {
							if (err) {
								callback(err, chunk);
								return;
							}
							resData.body = decode(body);
							callback(null, chunk);
						});
						return;
					}
				}
				resData.body = decode(resBody);
			}

			callback(null, chunk);
		};
	}

}

module.exports = function init(_proxy) {
	proxy = _proxy;
	util = proxy.util;
	enable();
	module.exports = get;
};<|endoftext|>