<commit_before>(function (L) {
  'use strict';

  L.EdgeMarker = L.Class.extend({

    options: {
              radius: 12,
              weight: 1,
              color: 'green',
              fillColor: 'yellow',
              fillOpacity: 1,
              distanceOpacity: false,
              distanceOpacityFactor: 4
             },

    initialize: function(options) {
      L.setOptions(this, options);
    },

    addTo: function (map) {
      this._map = map;

      //add a method to get applicable features
      L.extend(map, {
        _getFeatures: function () {
          var out = [];
          for (var l in this._layers) {
            if(typeof this._layers[l].getLatLng !== 'undefined') {
              out.push(this._layers[l]);
            }
          }
          return out;
        }
      });

      map.on('move', this._addEdgeMarkers, this);
      map.on('viewreset', this._addEdgeMarkers, this);

      this._addEdgeMarkers();

      map.addLayer(this);

      return this;
    },

    onAdd: function () {},

    _borderMarkerLayer: undefined,
    onClick : function (e){
      this._map.setView(e.target.options.latlng,this._map.getZoom());
    },

    _addEdgeMarkers: function () {
      if (typeof this._borderMarkerLayer === 'undefined') {
        this._borderMarkerLayer = new L.LayerGroup();
      }
      this._borderMarkerLayer.clearLayers();

      var features = this._map._getFeatures();

      for(var i = 0; i < features.length; i++) {
        var currentMarkerPosition = this._map.latLngToContainerPoint(
                                                  features[i].getLatLng());
        var mapPixelBounds = this._map.getSize();

        if(currentMarkerPosition.y < 0 ||
            currentMarkerPosition.y > mapPixelBounds.y ||
            currentMarkerPosition.x > mapPixelBounds.x ||
            currentMarkerPosition.x < 0) {

          var y = currentMarkerPosition.y;
          if( currentMarkerPosition.y < 0 ) {
            y = 0;
            var markerDistance = -currentMarkerPosition.y;
          } else if (currentMarkerPosition.y > mapPixelBounds.y) {
            y = mapPixelBounds.y;
            var markerDistance = currentMarkerPosition.y - mapPixelBounds.y;
          }

          var x = currentMarkerPosition.x;
          if (currentMarkerPosition.x > mapPixelBounds.x) {
            x = mapPixelBounds.x;
            var markerDistance = currentMarkerPosition.x - mapPixelBounds.x;
          } else if ( currentMarkerPosition.x < 0) {
            x = 0;
            var markerDistance = -currentMarkerPosition.x;
          }

          var newOptions = this.options;
          if(this.options.distanceOpacity){
            newOptions.fillOpacity = (100 - (markerDistance/this.options.distanceOpacityFactor))/100;
          }
	  var ref = { latlng : features[i].getLatLng() };
	  var settings = L.extend({},newOptions,ref);
          var icircle = L.circleMarker(this._map.containerPointToLatLng([x,y]),settings)
              .addTo(this._borderMarkerLayer);
          icircle.on('click',this.onClick,icircle);
        }
      }
      if(!this._map.hasLayer(this._borderMarkerLayer)) {
        this._borderMarkerLayer.addTo(this._map);
      }
    }
  });

  L.edgeMarker = function (options) {
    return new L.EdgeMarker(options);
  };

})(L);
<commit_msg>Update Leaflet.EdgeMarker.js<commit_after>(function (L) {
  'use strict';

  L.EdgeMarker = L.Class.extend({

    options: {
              radius: 12,
              weight: 1,
              color: 'green',
              fillColor: 'yellow',
              fillOpacity: 1,
              distanceOpacity: false,
              distanceOpacityFactor: 4
             },

    initialize: function(options) {
      L.setOptions(this, options);
    },

    addTo: function (map) {
      this._map = map;

      //add a method to get applicable features
      L.extend(map, {
        _getFeatures: function () {
          var out = [];
          for (var l in this._layers) {
            if(typeof this._layers[l].getLatLng !== 'undefined') {
              out.push(this._layers[l]);
            }
          }
          return out;
        }
      });

      map.on('move', this._addEdgeMarkers, this);
      map.on('viewreset', this._addEdgeMarkers, this);

      this._addEdgeMarkers();

      map.addLayer(this);

      return this;
    },

    onAdd: function () {},

    _borderMarkerLayer: undefined,

    onClick : function (e){
      this._map.setView(e.target.options.latlng,this._map.getZoom());
    },

    _addEdgeMarkers: function () {
      if (typeof this._borderMarkerLayer === 'undefined') {
        this._borderMarkerLayer = new L.LayerGroup();
      }
      this._borderMarkerLayer.clearLayers();

      var features = this._map._getFeatures();

      for(var i = 0; i < features.length; i++) {
        var currentMarkerPosition = this._map.latLngToContainerPoint(
                                                  features[i].getLatLng());
        var mapPixelBounds = this._map.getSize();

        if(currentMarkerPosition.y < 0 ||
            currentMarkerPosition.y > mapPixelBounds.y ||
            currentMarkerPosition.x > mapPixelBounds.x ||
            currentMarkerPosition.x < 0) {

          var y = currentMarkerPosition.y;
          if( currentMarkerPosition.y < 0 ) {
            y = 0;
            var markerDistance = -currentMarkerPosition.y;
          } else if (currentMarkerPosition.y > mapPixelBounds.y) {
            y = mapPixelBounds.y;
            var markerDistance = currentMarkerPosition.y - mapPixelBounds.y;
          }

          var x = currentMarkerPosition.x;
          if (currentMarkerPosition.x > mapPixelBounds.x) {
            x = mapPixelBounds.x;
            var markerDistance = currentMarkerPosition.x - mapPixelBounds.x;
          } else if ( currentMarkerPosition.x < 0) {
            x = 0;
            var markerDistance = -currentMarkerPosition.x;
          }

          var newOptions = this.options;
          if(this.options.distanceOpacity){
            newOptions.fillOpacity = (100 - (markerDistance/this.options.distanceOpacityFactor))/100;
          }
	  var ref = { latlng : features[i].getLatLng() };
	  var settings = L.extend({},newOptions,ref);
          var icircle = L.circleMarker(this._map.containerPointToLatLng([x,y]),settings)
              .addTo(this._borderMarkerLayer);
          icircle.on('click',this.onClick,icircle);
        }
      }
      if(!this._map.hasLayer(this._borderMarkerLayer)) {
        this._borderMarkerLayer.addTo(this._map);
      }
    }
  });

  L.edgeMarker = function (options) {
    return new L.EdgeMarker(options);
  };

})(L);
<|endoftext|>


<commit_before>module.exports = {
  CELL_PADDING: 5,
  CELL_SIZE: 30,
  CHAR_POINT: '$',
  CHAR_SNAKE_HEAD: 'X',
  CHAR_SNAKE_TAIL: 'x',
  CLOUD_CANVAS_SIZE: 15,
  CLOUD_RUN_TIMES: 3,
  FN_TIMEOUT_SECONDS: 10,
  LEADERBOARD_LIMIT: 20,
  LOCAL_STORAGE_REDUX_KEY: 'snake-heuristics:redux:v1',
  MAX_USER_SOLUTIONS: 5,
  SNAKE_LENGTH: 4,
};
<commit_msg>Reduced function timeout time<commit_after>module.exports = {
  CELL_PADDING: 5,
  CELL_SIZE: 30,
  CHAR_POINT: '$',
  CHAR_SNAKE_HEAD: 'X',
  CHAR_SNAKE_TAIL: 'x',
  CLOUD_CANVAS_SIZE: 15,
  CLOUD_RUN_TIMES: 3,
  FN_TIMEOUT_SECONDS: 0.15,
  LEADERBOARD_LIMIT: 20,
  LOCAL_STORAGE_REDUX_KEY: 'snake-heuristics:redux:v1',
  MAX_USER_SOLUTIONS: 5,
  SNAKE_LENGTH: 4,
};
<|endoftext|>


<commit_before>
///
// diesel.mixin
///

diesel.mixin.addMixin = function(targetObject, mixin){

	var reservedVars = [
		"prototype",
		"overrideExisting",
	],
	shouldOverride = mixin.shouldOverride||false;

	//add the mixin vars to the object.
	for(attr in mixin){
		if(mixin &&
			mixin[attr]&&
			(!targetObject[attr]||shouldOverride)){
			//this is a shallow copy we only care really about functions or you are mixining wrong.
			targetObject[attr] = mixin[attr];
		}
	}
}
<commit_msg> added debug code to mixin<commit_after>
///
// diesel.mixin
///

diesel.mixin.addMixin = function(targetObject, mixin){
	if(diesel.debug){
		console.log("adding", mixin, "to", targetObject);

	}

	if(!mixin){
		return;
	}

	var reservedVars = [
		"prototype",
		"overrideExisting",
	],
	shouldOverride = mixin.shouldOverride||false;

	//add the mixin vars to the object.
	for(attr in mixin){
		if(mixin &&
			mixin[attr]&&
			(!targetObject[attr]||shouldOverride)){
			//this is a shallow copy we only care really about functions or you are mixining wrong.
			targetObject[attr] = mixin[attr];
		}
	}
}
<|endoftext|>


<commit_before>/*********************************************************************
 *
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2012, Worcester Polytechnic Institute
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the Worcester Polytechnic Institute nor the
 *     names of its contributors may be used to endorse or promote
 *     products derived from this software without specific prior
 *     written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 *   Author: Russell Toris
 *  Version: September 20, 2012
 *
 *********************************************************************/

var MjpegCanvas = function(options) {
	var mjpegCanvas = this;
	options = options || {};
	mjpegCanvas.host = options.host;
	mjpegCanvas.port = options.port || 8080;
	mjpegCanvas.topic = options.topic;
	mjpegCanvas.label = options.label;
	mjpegCanvas.defaultStream = options.defaultStream || 0;
	mjpegCanvas.quality = options.quality;
	mjpegCanvas.canvasID = options.canvasID;
	mjpegCanvas.width = options.width;
	mjpegCanvas.height = options.height;

	// current streaming topic
	var _stream = null;
	var _img = null;

	// grab the canvas
	var _canvas = document.getElementById(mjpegCanvas.canvasID);
	var _context = _canvas.getContext('2d');

	var _createImage = function() {
		// create the image to hold the stream
		_img = new Image();
		var _src = 'http://' + mjpegCanvas.host + ':' + mjpegCanvas.port
				+ '/stream?topic=' + _stream;
		// check for various options
		if (mjpegCanvas.width > 0) {
			_src += '?width=' + mjpegCanvas.width;
		}
		if (mjpegCanvas.width > 0) {
			_src += '?height=' + mjpegCanvas.height;
		}
		if (mjpegCanvas.quality > 0) {
			_src += '?quality=' + mjpegCanvas.quality;
		}
		_img.src = _src;
	};

	// check if the topics is a list or single topic
	if (mjpegCanvas.topic instanceof Array) {
		// check the labels
		if (!(mjpegCanvas.label && mjpegCanvas.label instanceof Array && mjpegCanvas.label.length == mjpegCanvas.topic.length)) {
			mjpegCanvas.label = null;
		}

		// start the stream with the first topic
		_stream = mjpegCanvas.topic[mjpegCanvas.defaultStream];

		// button options
		_context.globalAlpha = 0.66;
		var _buttonMargin = 10;
		var _buttonPadding = 5;
		var _buttonHeight = 25;
		var _buttonWidth = 55;
		var _buttonColor = 'black';
		var _buttonStrokeSize = 5;
		var _buttonStrokeColor = 'blue';
		var _editFont = '16pt Verdana';
		var _editColor = 'white';

		// menu div
		var _menu = document.createElement('div');
		document.getElementsByTagName('body')[0].appendChild(_menu);
		_menu.style.display = 'none';

		// create the mouseovers
		var _mouseEnter = false;
		var _menuOpen = false;
		_canvas.addEventListener('mouseenter', function(e) {
			_mouseEnter = true;
		}, false);
		_canvas.addEventListener('mouseleave', function(e) {
			_mouseEnter = false;
		}, false);
		_canvas
				.addEventListener(
						'click',
						function(e) {
							// create a unique ID
							var id = (new Date()).getTime();

							var offsetLeft = 0;
							var offsetTop = 0;
							var element = _canvas;
							while (element && !isNaN(element.offsetLeft)
									&& !isNaN(element.offsetTop)) {
								offsetLeft += element.offsetLeft
										- element.scrollLeft;
								offsetTop += element.offsetTop
										- element.scrollTop;
								element = element.offsetParent;
							}

							var x = e.pageX - offsetLeft;
							var y = e.pageY - offsetTop;
							var height = _canvas.getAttribute('height');
							var width = _canvas.getAttribute('width');

							// check if we are in the 'edit' button
							if (x < (_buttonWidth + _buttonMargin)
									&& x > _buttonMargin
									&& y > (height - (_buttonHeight + _buttonMargin))
									&& y < height - _buttonMargin) {
								_menuOpen = true;

								// create the menu
								var html = '
Camera Streams

<form>Stream<select name="stream" id="stream-'
										+ id + '" required>';
								for ( var i = 0; i < mjpegCanvas.topic.length; i++) {
									// check if this is the selected option
									var selected = '';
									if (mjpegCanvas.topic[i] === _stream) {
										var selected = 'selected="selected"';
									}
									html += '<option value="'
											+ mjpegCanvas.topic[i] + '" '
											+ selected + '>';
									// check for a label
									if (mjpegCanvas.label) {
										html += mjpegCanvas.label[i];
									} else {
										html += mjpegCanvas.topic[i];
									}
									html += '</option>';
								}
								html += '</select></form>
<button id="button-'
										+ id + '">Close</button>';

								// display the menu
								_menu.innerHTML = html;
								_menu.style.position = 'absolute';
								_menu.style.top = offsetTop + 'px';
								_menu.style.left = offsetLeft + 'px';
								_menu.style.width = width + 'px';
								_menu.style.display = 'block';

								// dropdown change listener
								var select = document.getElementById('stream-'
										+ id);
								select
										.addEventListener(
												'click',
												function() {
													var stream = select.options[select.selectedIndex].value;
													// make sure it is a new
													// stream
													if (stream !== _stream) {
														_stream = stream;
														_img = null;
														_createImage();
													}
												}, false);

								// create the event listener for the close
								var button = document.getElementById('button-'
										+ id);
								button.addEventListener('click', function(e) {
									// close the menu
									_menuOpen = false;
									_menu.style.display = 'none';
								}, false);
							}
						}, false);
	} else {
		_stream = mjpegCanvas.topic;
	}

	// a function to draw the image onto the canvas
	function draw(_img) {
		// grab the current sizes of the canvas
		var width = _canvas.getAttribute('width');
		var height = _canvas.getAttribute('height');

		// grab the drawing context and draw the image
		if (_img) {
			_context.drawImage(_img, 0, 0, width, height);
		} else {
			_context.clearRect(0, 0, width, height);
		}

		if (_mouseEnter && !_menuOpen) {
			// create the "swap" button
			_context.globalAlpha = 0.66;
			_context.beginPath();
			_context.rect(_buttonMargin, height
					- (_buttonHeight + _buttonMargin), _buttonWidth,
					_buttonHeight);
			_context.fillStyle = _buttonColor;
			_context.fill();
			_context.lineWidth = _buttonStrokeSize;
			_context.strokeStyle = _buttonStrokeColor;
			_context.stroke();

			// draw the text on the button
			_context.font = _editFont;
			_context.fillStyle = _editColor;
			_context.fillText('Edit', _buttonMargin + _buttonPadding, height
					- (_buttonMargin + _buttonPadding));
		}

		if (_menuOpen) {
			// create the white box
			_context.globalAlpha = 0.66;
			_context.beginPath();
			_context.rect(0, 0, width, height);
			_context.fillStyle = 'white';
			_context.fill();
		}
		_context.globalAlpha = 1;
	}

	// grab the initial stream
	_createImage();

	// redraw the image every 100 ms
	setInterval(function() {
		draw(_img);
	}, 100);
};
<commit_msg>tabs converted to spaces<commit_after>/*********************************************************************
 *
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2012, Worcester Polytechnic Institute
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the Worcester Polytechnic Institute nor the
 *     names of its contributors may be used to endorse or promote
 *     products derived from this software without specific prior
 *     written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 *   Author: Russell Toris
 *  Version: September 27, 2012
 *
 *********************************************************************/

var MjpegCanvas = function(options) {
  var mjpegCanvas = this;
  options = options || {};
  mjpegCanvas.host = options.host;
  mjpegCanvas.port = options.port || 8080;
  mjpegCanvas.topic = options.topic;
  mjpegCanvas.label = options.label;
  mjpegCanvas.defaultStream = options.defaultStream || 0;
  mjpegCanvas.quality = options.quality;
  mjpegCanvas.canvasID = options.canvasID;
  mjpegCanvas.width = options.width;
  mjpegCanvas.height = options.height;

  // current streaming topic
  var _stream = null;
  var _img = null;

  // grab the canvas
  var _canvas = document.getElementById(mjpegCanvas.canvasID);
  var _context = _canvas.getContext('2d');

  var _createImage = function() {
    // create the image to hold the stream
    _img = new Image();
    var _src = 'http://' + mjpegCanvas.host + ':' + mjpegCanvas.port
        + '/stream?topic=' + _stream;
    // check for various options
    if (mjpegCanvas.width > 0) {
      _src += '?width=' + mjpegCanvas.width;
    }
    if (mjpegCanvas.width > 0) {
      _src += '?height=' + mjpegCanvas.height;
    }
    if (mjpegCanvas.quality > 0) {
      _src += '?quality=' + mjpegCanvas.quality;
    }
    _img.src = _src;
  };

  // check if the topics is a list or single topic
  if (mjpegCanvas.topic instanceof Array) {
    // check the labels
    if (!(mjpegCanvas.label && mjpegCanvas.label instanceof Array && mjpegCanvas.label.length == mjpegCanvas.topic.length)) {
      mjpegCanvas.label = null;
    }

    // start the stream with the first topic
    _stream = mjpegCanvas.topic[mjpegCanvas.defaultStream];

    // button options
    _context.globalAlpha = 0.66;
    var _buttonMargin = 10;
    var _buttonPadding = 5;
    var _buttonHeight = 25;
    var _buttonWidth = 55;
    var _buttonColor = 'black';
    var _buttonStrokeSize = 5;
    var _buttonStrokeColor = 'blue';
    var _editFont = '16pt Verdana';
    var _editColor = 'white';

    // menu div
    var _menu = document.createElement('div');
    document.getElementsByTagName('body')[0].appendChild(_menu);
    _menu.style.display = 'none';

    // create the mouseovers
    var _mouseEnter = false;
    var _menuOpen = false;
    _canvas.addEventListener('mouseenter', function(e) {
      _mouseEnter = true;
    }, false);
    _canvas.addEventListener('mouseleave', function(e) {
      _mouseEnter = false;
    }, false);
    _canvas
        .addEventListener(
            'click',
            function(e) {
              // create a unique ID
              var id = (new Date()).getTime();

              var offsetLeft = 0;
              var offsetTop = 0;
              var element = _canvas;
              while (element && !isNaN(element.offsetLeft)
                  && !isNaN(element.offsetTop)) {
                offsetLeft += element.offsetLeft - element.scrollLeft;
                offsetTop += element.offsetTop - element.scrollTop;
                element = element.offsetParent;
              }

              var x = e.pageX - offsetLeft;
              var y = e.pageY - offsetTop;
              var height = _canvas.getAttribute('height');
              var width = _canvas.getAttribute('width');

              // check if we are in the 'edit' button
              if (x < (_buttonWidth + _buttonMargin) && x > _buttonMargin
                  && y > (height - (_buttonHeight + _buttonMargin))
                  && y < height - _buttonMargin) {
                _menuOpen = true;

                // create the menu
                var html = '
Camera Streams

<form>Stream<select name="stream" id="stream-'
                    + id + '" required>';
                for ( var i = 0; i < mjpegCanvas.topic.length; i++) {
                  // check if this is the selected option
                  var selected = '';
                  if (mjpegCanvas.topic[i] === _stream) {
                    var selected = 'selected="selected"';
                  }
                  html += '<option value="' + mjpegCanvas.topic[i] + '" '
                      + selected + '>';
                  // check for a label
                  if (mjpegCanvas.label) {
                    html += mjpegCanvas.label[i];
                  } else {
                    html += mjpegCanvas.topic[i];
                  }
                  html += '</option>';
                }
                html += '</select></form>
<button id="button-' + id
                    + '">Close</button>';

                // display the menu
                _menu.innerHTML = html;
                _menu.style.position = 'absolute';
                _menu.style.top = offsetTop + 'px';
                _menu.style.left = offsetLeft + 'px';
                _menu.style.width = width + 'px';
                _menu.style.display = 'block';

                // dropdown change listener
                var select = document.getElementById('stream-' + id);
                select.addEventListener('click', function() {
                  var stream = select.options[select.selectedIndex].value;
                  // make sure it is a new
                  // stream
                  if (stream !== _stream) {
                    _stream = stream;
                    _img = null;
                    _createImage();
                  }
                }, false);

                // create the event listener for the close
                var button = document.getElementById('button-' + id);
                button.addEventListener('click', function(e) {
                  // close the menu
                  _menuOpen = false;
                  _menu.style.display = 'none';
                }, false);
              }
            }, false);
  } else {
    _stream = mjpegCanvas.topic;
  }

  // a function to draw the image onto the canvas
  function draw(_img) {
    // grab the current sizes of the canvas
    var width = _canvas.getAttribute('width');
    var height = _canvas.getAttribute('height');

    // grab the drawing context and draw the image
    if (_img) {
      _context.drawImage(_img, 0, 0, width, height);
    } else {
      _context.clearRect(0, 0, width, height);
    }

    if (_mouseEnter && !_menuOpen) {
      // create the "swap" button
      _context.globalAlpha = 0.66;
      _context.beginPath();
      _context.rect(_buttonMargin, height - (_buttonHeight + _buttonMargin),
          _buttonWidth, _buttonHeight);
      _context.fillStyle = _buttonColor;
      _context.fill();
      _context.lineWidth = _buttonStrokeSize;
      _context.strokeStyle = _buttonStrokeColor;
      _context.stroke();

      // draw the text on the button
      _context.font = _editFont;
      _context.fillStyle = _editColor;
      _context.fillText('Edit', _buttonMargin + _buttonPadding, height
          - (_buttonMargin + _buttonPadding));
    }

    if (_menuOpen) {
      // create the white box
      _context.globalAlpha = 0.66;
      _context.beginPath();
      _context.rect(0, 0, width, height);
      _context.fillStyle = 'white';
      _context.fill();
    }
    _context.globalAlpha = 1;
  }

  // grab the initial stream
  _createImage();

  // redraw the image every 100 ms
  setInterval(function() {
    draw(_img);
  }, 100);
};
<|endoftext|>


<commit_before>var osc = require("osc"),
    express = require("express"),
    WebSocket = require("ws");

// serial
var COM_PORT = 'COM5';
var BAUD_RATE = 115200;

//OSC
var OSC_PORT = 57121;
var oscPorts = [];

//Web Sockets
var WS_PORT = 8081;

var getIPAddresses = function () {
    var os = require("os"),
        interfaces = os.networkInterfaces(),
        ipAddresses = [];

    for (var deviceName in interfaces) {
        var addresses = interfaces[deviceName];
        for (var i = 0; i < addresses.length; i++) {
            var addressInfo = addresses[i];
            if (addressInfo.family === "IPv4" && !addressInfo.internal) {
                ipAddresses.push(addressInfo.address);
            }
        }
    }

    return ipAddresses;
};

// Bind to a UDP socket to listen for incoming OSC events.
var udpPort = new osc.UDPPort({
    localAddress: "0.0.0.0",
    localPort: OSC_PORT
});

udpPort.on("ready", function () {
    var ipAddresses = getIPAddresses();
    console.log("Listening for OSC over UDP.");
    ipAddresses.forEach(function (address) {
        console.log(" Host:", address + ", Port:", udpPort.options.localPort);
    });
    console.log("To start the demo, go to http://localhost:8081 in your web browser.");
});

udpPort.open();

// Create an Express-based Web Socket server to which OSC messages will be relayed.
var app = express(),
    server = app.listen(WS_PORT),
    wss = new WebSocket.Server({
        server: server
    });

wss.on("connection", function (socket) {
    console.log("A Web Socket connection has been established!");

    var socketPort = new osc.WebSocketPort({
        socket: socket
    });

    oscPorts.push(socketPort);

    console.log('new oscPort');

    var relay = new osc.Relay(udpPort, socketPort, {
        raw: true
    });

    console.log('new relay');
});

var com = require("serialport");
var serialPort = new com.SerialPort(COM_PORT, {
    baudrate: BAUD_RATE,
    parser: com.parsers.readline('\r\n')
});

function mapVal(value, start1, stop1, start2, stop2) {
    return start2 + (stop2 - start2) * ((value - start1) / (stop1 - start1));
}

function constrain(amt, low, high) {
    return (amt < low) ? low : ((amt > high) ? high : amt);
}

serialPort.on("open", function () {
    console.log('com port open');

    serialPort.on('data', function(data) {
        // data:
        // I0,1023,1023,1023,570,1023,1023,1023,1023,1023,1023,1023,569,1023,1023,1023,1023

        var d = data.split(',');
        if(d[0].substr(1) == '0') {
            var normalizedVal = constrain(mapVal(d[12], 375, 885, 0, 1), 0, 1);
            var n = Math.pow(normalizedVal, 0.55);

            oscPorts.forEach((oscPort, i) => {
                try{
                    oscPort.send({
                        address: "/stepper",
                        args: n
                    })
                }
                catch (err) {
                    oscPorts.splice(i);
                }
            });
        }

    });

    //serialPort.write("ls\n", function(err, results) {
    //    console.log('err ' + err);
    //    console.log('results ' + results);
    //});
});<commit_msg>fix bug removing too many oscPorts in node server<commit_after>var osc = require("osc"),
    express = require("express"),
    WebSocket = require("ws");

// serial
var COM_PORT = 'COM5';
var BAUD_RATE = 115200;

//OSC
var OSC_PORT = 57121;
var oscPorts = [];

//Web Sockets
var WS_PORT = 8081;

var getIPAddresses = function () {
    var os = require("os"),
        interfaces = os.networkInterfaces(),
        ipAddresses = [];

    for (var deviceName in interfaces) {
        var addresses = interfaces[deviceName];
        for (var i = 0; i < addresses.length; i++) {
            var addressInfo = addresses[i];
            if (addressInfo.family === "IPv4" && !addressInfo.internal) {
                ipAddresses.push(addressInfo.address);
            }
        }
    }

    return ipAddresses;
};

// Bind to a UDP socket to listen for incoming OSC events.
var udpPort = new osc.UDPPort({
    localAddress: "0.0.0.0",
    localPort: OSC_PORT
});

udpPort.on("ready", function () {
    var ipAddresses = getIPAddresses();
    console.log("Listening for OSC over UDP.");
    ipAddresses.forEach(function (address) {
        console.log(" Host:", address + ", Port:", udpPort.options.localPort);
    });
    console.log("To start the demo, go to http://localhost:8081 in your web browser.");
});

udpPort.open();

// Create an Express-based Web Socket server to which OSC messages will be relayed.
var app = express(),
    server = app.listen(WS_PORT),
    wss = new WebSocket.Server({
        server: server
    });

wss.on("connection", function (socket) {
    console.log("A Web Socket connection has been established!");

    var socketPort = new osc.WebSocketPort({
        socket: socket
    });

    oscPorts.push(socketPort);

    console.log('new oscPort');

    var relay = new osc.Relay(udpPort, socketPort, {
        raw: true
    });

    console.log('new relay');
});

var com = require("serialport");
var serialPort = new com.SerialPort(COM_PORT, {
    baudrate: BAUD_RATE,
    parser: com.parsers.readline('\r\n')
});

function mapVal(value, start1, stop1, start2, stop2) {
    return start2 + (stop2 - start2) * ((value - start1) / (stop1 - start1));
}

function constrain(amt, low, high) {
    return (amt < low) ? low : ((amt > high) ? high : amt);
}

serialPort.on("open", function () {
    console.log('com port open');

    serialPort.on('data', function(data) {
        // data:
        // I0,1023,1023,1023,570,1023,1023,1023,1023,1023,1023,1023,569,1023,1023,1023,1023

        var d = data.split(',');
        if(d[0].substr(1) == '0') {
            var normalizedVal = constrain(mapVal(d[12], 375, 885, 0, 1), 0, 1);
            var n = Math.pow(normalizedVal, 0.55);

            oscPorts.forEach((oscPort, i) => {
                try{
                    oscPort.send({
                        address: "/stepper",
                        args: n
                    })
                }
                catch (err) {
                    oscPorts.splice(i, 1);
                }
            });
        }

    });

    //serialPort.write("ls\n", function(err, results) {
    //    console.log('err ' + err);
    //    console.log('results ' + results);
    //});
});<|endoftext|>


<commit_before><commit_msg>For merging<commit_after><|endoftext|>


<commit_before>"use strict";

var start = function() {
	document.getElementById("world").style.display = "inline";
	document.getElementById("startButton").style.display = "none";

	var sprites = initGame();

	var audio = initSound();

	var game = new Game(document.getElementById("world"), sprites, audio);
}

function initGame() {
	var spriteLoader = new SpriteLoader();
	var sprites = {};
	var spriteNames = ["enemy", "turtleWithACrown", "coverTurtleWithACrown", "catBoss"];
	for (var i = 1; i < 7; i++) {
		spriteNames.push("connor/connorL" + i);
		spriteNames.push("connor/connorR" + i);
	}
	spriteLoader.load("./assets/images", spriteNames, ".png", function (loadedSprites) {
		for (var spriteName in loadedSprites) {
			sprites[spriteName] = loadedSprites[spriteName];
		}
	});

	return sprites;
}

function initSound() {
	var soundLoader = new SoundLoader();
	var audio = {};
	var audioNames = ["casanova", "jumpFins", "pewPewBizNiss", "enemyDamageBraqoon", "meow", "pokemonRuby"];
	var extensions = [".mp3", ".wav", ".wav", ".wav", ".wav", ".mp3"];
	soundLoader.load("./assets/sounds", audioNames, extensions, function (loadedAudio) {
		for (var audioName in loadedAudio) {
			audio[audioName] = loadedAudio[audioName];
		}
	});
	return audio;
}<commit_msg>Update init.js<commit_after>"use strict";

var start = function() {
	document.getElementById("world").style.display = "inline";
	document.getElementById("startButton").style.display = "none";

	var sprites = initGame();

	var audio = initSound();

	var game = new Game(document.getElementById("world"), sprites, audio);
}

function initGame() {
	var spriteLoader = new SpriteLoader();
	var sprites = {};
	var spriteNames = ["enemy", "turtleWithACrown", "coverTurtleWithACrown", "catBoss"/*, "quadrapusBoss"*/];
	for (var i = 1; i < 7; i++) {
		spriteNames.push("connor/connorL" + i);
		spriteNames.push("connor/connorR" + i);
	}
	spriteLoader.load("./assets/images", spriteNames, ".png", function (loadedSprites) {
		for (var spriteName in loadedSprites) {
			sprites[spriteName] = loadedSprites[spriteName];
		}
	});

	return sprites;
}

function initSound() {
	var soundLoader = new SoundLoader();
	var audio = {};
	var audioNames = ["casanova", "jumpFins", "pewPewBizNiss", "enemyDamageBraqoon", "meow", "pokemonRuby"];
	var extensions = [".mp3", ".wav", ".wav", ".wav", ".wav", ".mp3"];
	soundLoader.load("./assets/sounds", audioNames, extensions, function (loadedAudio) {
		for (var audioName in loadedAudio) {
			audio[audioName] = loadedAudio[audioName];
		}
	});
	return audio;
}
<|endoftext|>


<commit_before>/*global describe:true, it:true, expect: true, Backbone: true, beforeEach: true, chai:true, _:true*/
/*jshint expr:true, browser:true */

describe("Events", function() {

  describe("binding", function() {

    var model = new Backbone.Model();

    function createView(bindTestEvent, done){
      var View = Backbone.ViewMaster.extend({
        constructor: function() {
          Backbone.ViewMaster.prototype.constructor.apply(this, arguments);
          bindTestEvent.call(this);
        },
        callback: function() {
          done(null, this);
        }
      });
      return new View({ model: model });
    }

    it(".bindTo(emitter, event, Function)", function(done){
      createView(function(){
        this.bindTo(this.model, "test", this.callback);
      }, done);
      model.trigger("test");
    });

    it(".bindTo(emitter, event, method string)", function(done){
      createView(function(){
        this.bindTo(this.model, "test", "callback");
      }, done);
      model.trigger("test");
    });

    it(".bindTo(emitter, event, Function, context)", function(done){
      var myContext = {};
      createView(function(){
        this.bindTo(this.model, "test", this.callback, myContext);
      }, function(err, context) {
        expect(context === myContext).to.be.ok;
        done();
      });
      model.trigger("test");
    });

    it("unbindFrom(binding) removes binding", function(done) {
      var view = new Backbone.ViewMaster();
      var emitter = new Backbone.Model();
      var binding = view.bindTo(emitter, "throw", function() {
        throw new Error("Event not unbound!");
      });

      view.unbindFrom(binding);
      emitter.trigger("throw");
      setTimeout(done, 1);
    });

    it("should be removed on view.remove()", function(){
      var model = new Backbone.Model();
      var view = new Backbone.ViewMaster();
      var spy = chai.spy();

      view.bindTo(model, "test", spy);
      model.trigger("test");
      view.remove();
      model.trigger("test");

      expect(spy).to.have.been.called.once;
    });

    it("is unbound on parent.remove()", function(){
      var child = new Backbone.ViewMaster();
      child.template = function() {
        return "
child
";
      };

      var parent = new Backbone.ViewMaster();
      parent.template = function() {
        return "

";
      };

      parent.setView(".container", child);
      parent.render();

      var spy = chai.spy();
      var emitter = new Backbone.Model();
      child.bindTo(emitter, "test", spy);

      parent.remove();

      emitter.trigger("test");
      expect(spy).to.not.have.been.called.once;
    });

  });

  describe("bubble", function() {

    it("from children to parent", function(){
      var child = new Backbone.ViewMaster();
      child.template = function() {
        return "
child
";
      };

      var parent = new Backbone.ViewMaster();
      parent.template = function() {
        return "

";
      };

      // to make sure there are no double event bindings
      parent.setView(".container", child);
      parent.setView(".container", child);

      parent.render();

      var spy = chai.spy();
      parent.on("test", spy);
      child.trigger("test");
      expect(spy).to.have.been.called.once;
    });

    it("passes options to parent", function(done){
      var child = new Backbone.ViewMaster();
      child.template = function() {
        return "
child
";
      };

      var parent = new Backbone.ViewMaster();
      parent.template = function() {
        return "

";
      };

      parent.setView(".container", child);

      parent.render();

      parent.on("test", function(arg1, arg2) {
        expect(arg1).to.eq(1);
        expect(arg2).to.eq(2);
        done();
      });

      child.trigger("test", 1, 2);
    });

    describe("options", function() {
      function bubbleEnv(){
        var child = new Backbone.ViewMaster();
        child.template = function() {
          return "
child
";
        };

        var parent = new Backbone.ViewMaster();
        parent.template = function() {
          return "

";
        };

        parent.setView(".container", child);

        parent.render();

        var spy = chai.spy();
        parent.on("test", spy);

        return {
          parent: parent,
          child: child,
          spy: spy
        };
      }

      it("`{parent: false}` prevents bubbling", function(){
        var env = bubbleEnv();
        env.child.trigger("test", { parent: false });
        expect(env.spy).to.not.have.been.called.once;
      });

      it("`{parent: null}` prevents bubbling", function(){
        var env = bubbleEnv();
        env.child.trigger("test", { parent: null });
        expect(env.spy).to.not.have.been.called.once;
      });

      it("`{parent: true}` does not prevent bubbling", function(){
        var env = bubbleEnv();
        env.child.trigger("test", { parent: true });
        expect(env.spy).to.have.been.called.once;
      });

      it("`{parent: undefined}` does not prevent bubbling", function(){
        var env = bubbleEnv();
        env.child.trigger("test", { parent: undefined });
        expect(env.spy).to.have.been.called.once;
      });

      it("`{}` does not prevent bubbling", function(){
        var env = bubbleEnv();
        env.child.trigger("test", {});
        expect(env.spy).to.have.been.called.once;
      });

    });

    it("dont break dom bubbling", function(){
      var child = new Backbone.ViewMaster();
      child.template = function() {
        return "
child
";
      };

      var parent = new Backbone.ViewMaster();
      parent.template = function() {
        return "

";
      };

      // to make sure there are no double event bindings
      parent.setView(".container", child);
      parent.setView(".container", child);

      parent.render();

      var spy = chai.spy();

      parent.$el.on("click", spy);
      child.$("p").click();
      expect(spy).to.have.been.called.once;

    });

    _.each(["setView", "appendView", "prependView"], function(viewMethod) {
      it("to new parent after a parent change with " + viewMethod, function(){
        var Parent = Backbone.ViewMaster.extend({
          template: function() {
            return "

";
          }
        });

        var parent1 = new Parent();
        var parent2 = new Parent();
        var child = new Backbone.ViewMaster();
        child.template = function() {
          return "child";
        };

        parent1[viewMethod](".container", child);
        parent1.render();

        parent2[viewMethod](".container", child);

        parent2.render();
        parent1.render();

        parent1.on("test", function() {
          throw new Error("Event on old parent");
        });

        var spy = chai.spy();
        parent2.on("test", spy);
        child.trigger("test");

        expect(spy).to.have.been.called.once;
      });
    });

    it("is unbound on remove()", function(){
      var child = new Backbone.ViewMaster();
      child.template = function() {
        return "
child
";
      };

      var parent = new Backbone.ViewMaster();
      parent.template = function() {
        return "

";
      };

      parent.setView(".container", child);
      parent.render();
      child.remove();

      var spy = chai.spy();
      parent.on("test", spy);
      child.trigger("test");

      expect(spy).to.not.have.been.called.once;
    });

    it("is unbound when parent is removed", function(){
      var child = new Backbone.ViewMaster();
      child.template = function() {
        return "
child
";
      };

      var parent = new Backbone.ViewMaster();
      parent.template = function() {
        return "

";
      };

      parent.setView(".container", child);
      parent.render();

      var spy = chai.spy();
      parent.on("test", spy);

      parent.remove();

      child.trigger("test");

      expect(spy).to.not.have.been.called.once;
    });

  });

});
<commit_msg>Test multi level bubbling<commit_after>/*global describe:true, it:true, expect: true, Backbone: true, beforeEach: true, chai:true, _:true*/
/*jshint expr:true, browser:true */

describe("Events", function() {

  describe("binding", function() {

    var model = new Backbone.Model();

    function createView(bindTestEvent, done){
      var View = Backbone.ViewMaster.extend({
        constructor: function() {
          Backbone.ViewMaster.prototype.constructor.apply(this, arguments);
          bindTestEvent.call(this);
        },
        callback: function() {
          done(null, this);
        }
      });
      return new View({ model: model });
    }

    it(".bindTo(emitter, event, Function)", function(done){
      createView(function(){
        this.bindTo(this.model, "test", this.callback);
      }, done);
      model.trigger("test");
    });

    it(".bindTo(emitter, event, method string)", function(done){
      createView(function(){
        this.bindTo(this.model, "test", "callback");
      }, done);
      model.trigger("test");
    });

    it(".bindTo(emitter, event, Function, context)", function(done){
      var myContext = {};
      createView(function(){
        this.bindTo(this.model, "test", this.callback, myContext);
      }, function(err, context) {
        expect(context === myContext).to.be.ok;
        done();
      });
      model.trigger("test");
    });

    it("unbindFrom(binding) removes binding", function(done) {
      var view = new Backbone.ViewMaster();
      var emitter = new Backbone.Model();
      var binding = view.bindTo(emitter, "throw", function() {
        throw new Error("Event not unbound!");
      });

      view.unbindFrom(binding);
      emitter.trigger("throw");
      setTimeout(done, 1);
    });

    it("should be removed on view.remove()", function(){
      var model = new Backbone.Model();
      var view = new Backbone.ViewMaster();
      var spy = chai.spy();

      view.bindTo(model, "test", spy);
      model.trigger("test");
      view.remove();
      model.trigger("test");

      expect(spy).to.have.been.called.once;
    });

    it("is unbound on parent.remove()", function(){
      var child = new Backbone.ViewMaster();
      child.template = function() {
        return "
child
";
      };

      var parent = new Backbone.ViewMaster();
      parent.template = function() {
        return "

";
      };

      parent.setView(".container", child);
      parent.render();

      var spy = chai.spy();
      var emitter = new Backbone.Model();
      child.bindTo(emitter, "test", spy);

      parent.remove();

      emitter.trigger("test");
      expect(spy).to.not.have.been.called.once;
    });

  });

  describe("bubble", function() {

    it("from children to parent", function(){
      var child = new Backbone.ViewMaster();
      child.template = function() {
        return "
child
";
      };

      var parent = new Backbone.ViewMaster();
      parent.template = function() {
        return "

";
      };

      // to make sure there are no double event bindings
      parent.setView(".container", child);
      parent.setView(".container", child);

      parent.render();

      var spy = chai.spy();
      parent.on("test", spy);
      child.trigger("test");
      expect(spy).to.have.been.called.once;
    });

    it("passes options to parent", function(done){
      var child = new Backbone.ViewMaster();
      child.template = function() {
        return "
child
";
      };

      var parent = new Backbone.ViewMaster();
      parent.template = function() {
        return "

";
      };

      parent.setView(".container", child);

      parent.render();

      parent.on("test", function(arg1, arg2) {
        expect(arg1).to.eq(1);
        expect(arg2).to.eq(2);
        done();
      });

      child.trigger("test", 1, 2);
    });

    it("multiple levels", function(done){
      var child = new Backbone.ViewMaster();
      child.template = function() {
        return "
child
";
      };

      var parent = new Backbone.ViewMaster();
      parent.template = function() {
        return "

";
      };

      var grandparent = new Backbone.ViewMaster();
      grandparent.template = function() {
        return "

";
      };

      parent.setView(".container", child);
      grandparent.setView(".container", parent);

      grandparent.render();

      grandparent.on("test", function(arg1, arg2) {
        expect(arg1).to.eq(1);
        expect(arg2).to.eq(2);
        done();
      });

      child.trigger("test", 1, 2);
    });

    describe("options", function() {
      function bubbleEnv(){
        var child = new Backbone.ViewMaster();
        child.template = function() {
          return "
child
";
        };

        var parent = new Backbone.ViewMaster();
        parent.template = function() {
          return "

";
        };

        parent.setView(".container", child);

        parent.render();

        var spy = chai.spy();
        parent.on("test", spy);

        return {
          parent: parent,
          child: child,
          spy: spy
        };
      }

      it("`{parent: false}` prevents bubbling", function(){
        var env = bubbleEnv();
        env.child.trigger("test", { parent: false });
        expect(env.spy).to.not.have.been.called.once;
      });

      it("`{parent: null}` prevents bubbling", function(){
        var env = bubbleEnv();
        env.child.trigger("test", { parent: null });
        expect(env.spy).to.not.have.been.called.once;
      });

      it("`{parent: true}` does not prevent bubbling", function(){
        var env = bubbleEnv();
        env.child.trigger("test", { parent: true });
        expect(env.spy).to.have.been.called.once;
      });

      it("`{parent: undefined}` does not prevent bubbling", function(){
        var env = bubbleEnv();
        env.child.trigger("test", { parent: undefined });
        expect(env.spy).to.have.been.called.once;
      });

      it("`{}` does not prevent bubbling", function(){
        var env = bubbleEnv();
        env.child.trigger("test", {});
        expect(env.spy).to.have.been.called.once;
      });

    });

    it("dont break dom bubbling", function(){
      var child = new Backbone.ViewMaster();
      child.template = function() {
        return "
child
";
      };

      var parent = new Backbone.ViewMaster();
      parent.template = function() {
        return "

";
      };

      // to make sure there are no double event bindings
      parent.setView(".container", child);
      parent.setView(".container", child);

      parent.render();

      var spy = chai.spy();

      parent.$el.on("click", spy);
      child.$("p").click();
      expect(spy).to.have.been.called.once;

    });

    _.each(["setView", "appendView", "prependView"], function(viewMethod) {
      it("to new parent after a parent change with " + viewMethod, function(){
        var Parent = Backbone.ViewMaster.extend({
          template: function() {
            return "

";
          }
        });

        var parent1 = new Parent();
        var parent2 = new Parent();
        var child = new Backbone.ViewMaster();
        child.template = function() {
          return "child";
        };

        parent1[viewMethod](".container", child);
        parent1.render();

        parent2[viewMethod](".container", child);

        parent2.render();
        parent1.render();

        parent1.on("test", function() {
          throw new Error("Event on old parent");
        });

        var spy = chai.spy();
        parent2.on("test", spy);
        child.trigger("test");

        expect(spy).to.have.been.called.once;
      });
    });

    it("is unbound on remove()", function(){
      var child = new Backbone.ViewMaster();
      child.template = function() {
        return "
child
";
      };

      var parent = new Backbone.ViewMaster();
      parent.template = function() {
        return "

";
      };

      parent.setView(".container", child);
      parent.render();
      child.remove();

      var spy = chai.spy();
      parent.on("test", spy);
      child.trigger("test");

      expect(spy).to.not.have.been.called.once;
    });

    it("is unbound when parent is removed", function(){
      var child = new Backbone.ViewMaster();
      child.template = function() {
        return "
child
";
      };

      var parent = new Backbone.ViewMaster();
      parent.template = function() {
        return "

";
      };

      parent.setView(".container", child);
      parent.render();

      var spy = chai.spy();
      parent.on("test", spy);

      parent.remove();

      child.trigger("test");

      expect(spy).to.not.have.been.called.once;
    });

  });

});
<|endoftext|>


<commit_before>module.exports = {
  colors {
    red:    { r: 255, g: 85,  b: 83 };
    orange: { r: 232, g: 134, b: 84 };
    yellow: { r: 255, g: 226, b: 108 };
    green:  { r: 136, g: 233, b: 128 };
    blue:   { r: 047, g: 255, b: 191 };
    purple: { r: 190, g: 112, b: 255 };
    black:  { r: 0,   g: 0,   b: 0   };
    white:  { r: 255, g: 255, b: 255 };
  };
};
<commit_msg>fixed syntax on colors<commit_after>module.exports = {
  colors: {
    red:    { r: 255, g: 85,  b: 83  }
    orange: { r: 232, g: 134, b: 84  }
    yellow: { r: 255, g: 226, b: 108 }
    green:  { r: 136, g: 233, b: 128 }
    blue:   { r: 047, g: 255, b: 191 }
    purple: { r: 190, g: 112, b: 255 }
    black:  { r: 0,   g: 0,   b: 0   }
    white:  { r: 255, g: 255, b: 255 }
  }
};
<|endoftext|>


<commit_before>import { library } from '@fortawesome/fontawesome-svg-core'

library.add(
   require('@fortawesome/free-solid-svg-icons/faBars').definition
  ,require('@fortawesome/free-solid-svg-icons/faBan').definition
  ,require('@fortawesome/free-solid-svg-icons/faChevronLeft').definition
  ,require('@fortawesome/free-solid-svg-icons/faChevronDown').definition
  ,require('@fortawesome/free-solid-svg-icons/faCaretLeft').definition
  ,require('@fortawesome/free-solid-svg-icons/faCaretRight').definition
  ,require('@fortawesome/free-solid-svg-icons/faCamera').definition
  ,require('@fortawesome/free-solid-svg-icons/faExclamationTriangle').definition
  ,require('@fortawesome/free-solid-svg-icons/faEnvelope').definition
  ,require('@fortawesome/free-solid-svg-icons/faGlobeAfrica').definition
  ,require('@fortawesome/free-solid-svg-icons/faLocationArrow').definition
  ,require('@fortawesome/free-solid-svg-icons/faLink').definition
  ,require('@fortawesome/free-solid-svg-icons/faMapMarker').definition
  ,require('@fortawesome/free-solid-svg-icons/faMapMarkerAlt').definition
  ,require('@fortawesome/free-solid-svg-icons/faPlus').definition
  ,require('@fortawesome/free-solid-svg-icons/faPhone').definition
  ,require('@fortawesome/free-solid-svg-icons/faPencilAlt').definition
  ,require('@fortawesome/free-solid-svg-icons/faRoute').definition
  ,require('@fortawesome/free-solid-svg-icons/faSearch').definition
  ,require('@fortawesome/free-solid-svg-icons/faSpinner').definition
  ,require('@fortawesome/free-solid-svg-icons/faSave').definition
  ,require('@fortawesome/free-solid-svg-icons/faUser').definition

  ,require('@fortawesome/free-regular-svg-icons/faFrown').definition

  ,require('@fortawesome/free-brands-svg-icons/faGithub').definition
  ,require('@fortawesome/free-brands-svg-icons/faFacebook').definition
  ,require('@fortawesome/free-brands-svg-icons/faCreativeCommons').definition

  ,require('@fortawesome/free-brands-svg-icons/faGithub').definition
  ,require('@fortawesome/free-brands-svg-icons/faFacebook').definition
  ,require('@fortawesome/free-brands-svg-icons/faCreativeCommons').definition
)
<commit_msg>fix(FontAwesome): add chevron-right icon import<commit_after>import { library } from '@fortawesome/fontawesome-svg-core'

library.add(
   require('@fortawesome/free-solid-svg-icons/faBars').definition
  ,require('@fortawesome/free-solid-svg-icons/faBan').definition
  ,require('@fortawesome/free-solid-svg-icons/faChevronLeft').definition
  ,require('@fortawesome/free-solid-svg-icons/faChevronDown').definition
  ,require('@fortawesome/free-solid-svg-icons/faChevronRight').definition
  ,require('@fortawesome/free-solid-svg-icons/faChevronLeft').definition
  ,require('@fortawesome/free-solid-svg-icons/faCaretLeft').definition
  ,require('@fortawesome/free-solid-svg-icons/faCaretRight').definition
  ,require('@fortawesome/free-solid-svg-icons/faCamera').definition
  ,require('@fortawesome/free-solid-svg-icons/faExclamationTriangle').definition
  ,require('@fortawesome/free-solid-svg-icons/faEnvelope').definition
  ,require('@fortawesome/free-solid-svg-icons/faGlobeAfrica').definition
  ,require('@fortawesome/free-solid-svg-icons/faLocationArrow').definition
  ,require('@fortawesome/free-solid-svg-icons/faLink').definition
  ,require('@fortawesome/free-solid-svg-icons/faMapMarker').definition
  ,require('@fortawesome/free-solid-svg-icons/faMapMarkerAlt').definition
  ,require('@fortawesome/free-solid-svg-icons/faPlus').definition
  ,require('@fortawesome/free-solid-svg-icons/faPhone').definition
  ,require('@fortawesome/free-solid-svg-icons/faPencilAlt').definition
  ,require('@fortawesome/free-solid-svg-icons/faRoute').definition
  ,require('@fortawesome/free-solid-svg-icons/faSearch').definition
  ,require('@fortawesome/free-solid-svg-icons/faSpinner').definition
  ,require('@fortawesome/free-solid-svg-icons/faSave').definition
  ,require('@fortawesome/free-solid-svg-icons/faUser').definition

  ,require('@fortawesome/free-regular-svg-icons/faFrown').definition

  ,require('@fortawesome/free-brands-svg-icons/faGithub').definition
  ,require('@fortawesome/free-brands-svg-icons/faFacebook').definition
  ,require('@fortawesome/free-brands-svg-icons/faCreativeCommons').definition

  ,require('@fortawesome/free-brands-svg-icons/faGithub').definition
  ,require('@fortawesome/free-brands-svg-icons/faFacebook').definition
  ,require('@fortawesome/free-brands-svg-icons/faCreativeCommons').definition
)
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Link } from 'react-router-dom';

import * as FetchAPI from '../fetch_data';

const ChangesetInfo = ({ changeset, push }) => {
  const { author, desc, node, showInfo } = changeset;
  const { linkify, hidden, summary } = push;
  // XXX: For author remove the email address
  // XXX: For desc display only the first line
  // XXX: linkify bug numbers
  const changesetClass = (hidden) ?
    'hidden_changeset' :
    'changeset';
  return (

        {author.substring(0, 22)}

        {(linkify) ?
          <Link to={`/changeset/${node}`}>{node.substring(0, 12)}</Link>
          : {node.substring(0, 12)}}

        {desc.substring(0, 40)}

        {(summary && showInfo && summary.error) &&
          {summary.error}
        }
        {(summary && showInfo && summary.overall_cur) &&
          {summary.overall_cur}
        }

  );
};

const ChangesetsViewer = ({ changesets, pushes, onClick }) => (

        Author
        Changeset
        Description
        Coverage summary

      {changesets.map(cset => (
        <ChangesetInfo
          key={cset.node}
          changeset={cset}
          push={pushes[cset.pushId]}
          onClick={onClick}
        />
      ))}

);

const processJsonPushes = (pushes) => {
  const ignore = ({ desc, author }) => {
    if (
      (author.includes('ffxbld')) ||
      (desc.includes('a=merge') && desc.includes('r=merge')) ||
      (desc.includes('erge') && (desc.includes('to'))) ||
      (desc.includes('ack out')) ||
      (desc.includes('acked out'))) {
      return true;
    }

    return false;
  };
  // In here we're flattening the data structure
  // We're now going to have an array of changeset
  // and each changeset is going to have the original
  // metadata explicitely declared
  // This improves manipulating the data structure
  const filteredCsets = [];
  const filteredPushes = {};

  // Populate filteredPushes and filteredChangesets
  Object.keys(pushes).reverse().forEach((id) => {
    const push = pushes[id];
    // Re-order csets and filter out those we don't want
    const csets = push.changesets.reverse().filter(c => !ignore(c));
    const lenCsets = csets.length - 1;

    if (lenCsets >= 1) {
      // The firstcset changeset expected not to be a merge one
      // Using firstcset terminology instead of tipmost to clarify
      // that it does not necessarily have to be the original tipmost
      // of a push
      const firstcset = csets[lenCsets];
      filteredPushes[id] = {
        date: push.date,
        numCsets: lenCsets,
        firstcset: firstcset.node,
        hidden: true,
        linkify: false,
      };
      csets.map((cset, position) => {
        const newCset = {
          pushId: id,
          ...cset,
        };
        if (position === 0 && lenCsets > 1) {
          newCset.showInfo = true;
        }
        filteredCsets.push(newCset);
        return newCset;
      });
    }
  });
  return {
    csets: filteredCsets,
    pushList: filteredPushes,
  };
};

// XXX: For now, we can only make 1 request a time to the backend
// or we will overwhelm it: https://github.com/mozilla-releng/services/issues/632
// Recursively fetching one summary at a time
const getSummaries = async (pushIds, pushes) => {
  // We're expecting the list of pushIds to be sorted from highest to lowest
  // since we grab the pushId from the end.
  // This is because more recent pushes are likely not to have code coverage data.
  const pushId = pushIds.pop();
  if (!pushId) {
    return {};
  }

  const push = pushes[pushId];
  const processedPushes = {};
  processedPushes[pushId] = {
    ...push,
  };

  try {
    console.log(`About to fetch ${pushId} (${push.firstcset})`);
    // XXX: fetch does not support timeouts. I would like to add a 5 second
    // timeout rather than wait Heroku's default 30 second timeout. Specially
    // since we're doing sequential fetches.
    // XXX: Wrap fetch() in a Promise; add a setTimeout and call reject() if
    // it goes off, otherwise resolve with the result of the fetch()
    const res = await FetchAPI.getChangesetCoverage(push.firstcset);
    if (res.status === 202) {
      processedPushes[pushId].summary = {
        error: 'Pending',
      };
    } else if (res.status === 200) {
      const ccSum = await res.json();
      processedPushes[pushId].summary = ccSum;
      processedPushes[pushId].hidden = false;

      if (ccSum.overall_cur) {
        // We have coverage data, thus, adding links to the coverage diff viewer
        processedPushes[pushId].linkify = true;
      }
    } else {
      processedPushes[pushId].summary = {
        error: res.statusText,
      };
    }
  } catch (e) {
    console.log(e);
    processedPushes[pushId].summary = {
      error: 'Failed to fetch.',
    };
  }

  try {
    const remainingSummaries = await getSummaries(pushIds, pushes);
    return Object.assign(processedPushes, remainingSummaries);
  } catch (e) {
    // Once one fails; let's just stop and return the original list
    return pushes;
  }
};

export default class ChangesetsViewerContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      changesets: [],
      pushes: {},
      errorMessage: '',
    };
  }

  async componentDidMount() {
    const { repoName } = this.props;
    this.fetchPushes(repoName);
  }

  async fetchPushes(repoName) {
    try {
      const text = await (await FetchAPI.getJsonPushes(repoName)).json();
      const { csets, pushList } = processJsonPushes(text.pushes);

      try {
        // Ordered from oldest to most recent
        const pushIds = Object.keys(pushList).reverse();
        const newPushes = await getSummaries(pushIds, pushList);
        this.setState({
          changesets: csets,
          pushes: newPushes,
        });
      } catch (e) {
        console.log(e);
        this.setState({
          changesets: csets,
          pushes: pushList,
          errorMessage: 'We have failed to fetch coverage data.',
        });
      }
    } catch (error) {
      console.log(error);
      this.setState({
        changesets: [],
        pushes: {},
        errorMessage: 'We have failed to fetch pushes.',
      });
    }
  }

  render() {
    const { errorMessage, changesets, pushes } = this.state;
    if (errorMessage) {
      return (
{errorMessage}
);
    }

    return (
      <ChangesetsViewer
        changesets={changesets}
        pushes={pushes}
      />
    );
  }
}
<commit_msg>Issue #46 - Add coverage summary for each changeset<commit_after>import React, { Component } from 'react';
import { Link } from 'react-router-dom';

import * as FetchAPI from '../fetch_data';

const ChangesetInfo = ({ changeset }) => {
  const { author, desc, hidden, linkify, node, summary } = changeset;
  // XXX: For author remove the email address
  // XXX: For desc display only the first line
  // XXX: linkify bug numbers
  return (

        {author.substring(0, 22)}

        {(linkify) ?
          <Link to={`/changeset/${node}`}>{node.substring(0, 12)}</Link>
          : {node.substring(0, 12)}}

        {desc.substring(0, 40)}

        {(summary && summary.error) &&
          {summary.error}
        }
        {(summary && summary.overall_cur) &&
          {summary.overall_cur}
        }

  );
};

const ChangesetsViewer = ({ changesets, onClick }) => (

        Author
        Changeset
        Description
        Coverage summary

      {changesets.map(cset => ((cset) &&
        <ChangesetInfo
          key={cset.node}
          changeset={cset}
          onClick={onClick}
        />
      ))}

);

const processJsonPushes = (pushes) => {
  const ignore = ({ desc, author }) => {
    if (
      (author.includes('ffxbld')) ||
      (desc.includes('a=merge') && desc.includes('r=merge')) ||
      (desc.includes('erge') && (desc.includes('to'))) ||
      (desc.includes('ack out')) ||
      (desc.includes('acked out'))) {
      return true;
    }

    return false;
  };
  // In here we're flattening the data structure
  // We're now going to have an array of changeset
  // and each changeset is going to have the original
  // metadata explicitely declared
  // This improves manipulating the data structure
  const filteredCsets = [];
  const filteredPushes = {};

  // Populate filteredPushes and filteredChangesets
  Object.keys(pushes).reverse().forEach((id) => {
    const push = pushes[id];
    // Re-order csets and filter out those we don't want
    const csets = push.changesets.reverse().filter(c => !ignore(c));
    const lenCsets = csets.length - 1;

    if (lenCsets >= 1) {
      // The firstcset changeset expected not to be a merge one
      // Using firstcset terminology instead of tipmost to clarify
      // that it does not necessarily have to be the original tipmost
      // of a push
      filteredPushes[id] = {
        date: push.date,
      };
      csets.map((cset) => {
        const newCset = {
          pushId: id,
          hidden: true,
          linkify: false,
          ...cset,
        };
        filteredCsets.push(newCset);
        return newCset;
      });
    }
  });
  return {
    csets: filteredCsets,
    pushList: filteredPushes,
  };
};

const csetWithCcovData = async (cset) => {
  const newCset = Object.assign({}, cset);
  // XXX: fetch does not support timeouts. I would like to add a 5 second
  // timeout rather than wait Heroku's default 30 second timeout. Specially
  // since we're doing sequential fetches.
  // XXX: Wrap fetch() in a Promise; add a setTimeout and call reject() if
  // it goes off, otherwise resolve with the result of the fetch()
  const res = await FetchAPI.getChangesetCoverage(cset.node);
  if (res.status === 202) {
    // XXX: We should retry few times before giving up
    newCset.summary = { error: 'Pending' };
  } else if (res.status === 200) {
    const ccSum = await res.json();
    newCset.summary = ccSum;

    // XXX: Document in which cases we would not have overall_cur
    if (ccSum.overall_cur) {
      // We have coverage data, thus, adding links to the coverage diff viewer
      // and unhiding the csets associated to this push
      newCset.linkify = true;
      newCset.hidden = false;
    }
  } else {
    newCset.summary = { error: res.statusText };
  }
  return newCset;
};

// Return list of csets with coverage data if available
const addSummariesToCsets = async (csets) => {
  console.log(csets.length);
  let newCsets = [];
  try {
    const firstCset = csets[0];
    console.log(`About to fetch ${firstCset.pushId} (${firstCset.node})`);
    const newCset = await csetWithCcovData(firstCset);
    newCsets = [newCset];
    if (newCset.linkify) {
      newCsets = newCsets.concat(await Promise.all(csets
        .filter(cset =>
          cset.node !== firstCset.node)
        .map(async cset =>
          (csetWithCcovData(cset)))));
    }
  } catch (e) {
    console.log(e);
    newCsets = csets;
  }
  return newCsets;
};

// Return a new object of csets but with their coverage data.
const csetsWithCoverage = async (csets, pushes) => {
  try {
    return (
      await Promise.all(
        Object
          .keys(pushes)
          .map(pushId => (
            addSummariesToCsets(csets.filter(c => c.pushId === pushId))
          ))))
      .reduce((list, changesets) =>
        list.concat(changesets), []);
  } catch (e) {
    console.log(e);
    return csets;
  }
};

export default class ChangesetsViewerContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      changesets: [],
      pushes: {},
      errorMessage: '',
    };
  }

  async componentDidMount() {
    const { repoName } = this.props;
    this.fetchPushes(repoName);
  }

  async fetchPushes(repoName) {
    try {
      const text = await (await FetchAPI.getJsonPushes(repoName)).json();
      const { csets, pushList } = processJsonPushes(text.pushes);
      const changesets = await csetsWithCoverage(csets, pushList);
      this.setState({
        changesets,
        pushes: pushList,
      });
    } catch (error) {
      console.log(error);
      this.setState({
        changesets: [],
        pushes: {},
        errorMessage: 'We have failed to fetch coverage data.',
      });
    }
  }

  render() {
    const { errorMessage, changesets, pushes } = this.state;
    if (errorMessage) {
      return (
{errorMessage}
);
    }

    return (
      <ChangesetsViewer
        changesets={changesets}
        pushes={pushes}
      />
    );
  }
}
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Paper from 'material-ui/Paper';
import {GoogleIcon, FacebookIcon} from '../../components/Icons';
import {injectIntl} from 'react-intl';
import muiThemeable from 'material-ui/styles/muiThemeable';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import { updateAuth } from '../../actions/auth';
import GoogleLogin from 'react-google-login';
import FacebookLogin from 'react-facebook-login';
import config from '../../config'
import { push } from 'react-router-redux';
import { ResponsiveAppBar } from 'material-ui-responsive-drawer';
import FontIcon from 'material-ui/FontIcon';

const styles={
  paper:{
    height: '100%',
    display: 'block',
    margin:0,
    padding: 15
  },
  container: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    margin: 5,
    marginTop: 100,
  },
  button: {
    margin:6,
    align: 'left'
  },
  sign_up_button: {
    float: 'right',
    overflow: 'none',
    alignSelf: 'flex-end',
    marginRight:-43,
  }
}

const SignIn = (props) => {

  const { muiTheme, intl, updateAuth, push }=props;

  const  responseGoogle = (googleUser) => {
    console.log(googleUser);
    var profile = googleUser.getBasicProfile();
    updateAuth({name: profile.getName(), email: profile.getEmail(), img: profile.getImageUrl() });
    push('/');
  }

  const responseFacebook = (facebookUser) => {
    console.log(facebookUser);
    updateAuth({name: facebookUser.name, email: facebookUser.email, img: facebookUser.picture.data.url });
    push('/');
  }

  return (

      <ResponsiveAppBar
        title={intl.formatMessage({id: 'sign_in'})}
      />

        <Paper  zDepth={2} style={styles.paper}>

{intl.formatMessage({id: 'sign_in'}).toUpperCase()}

            <FloatingActionButton style={styles.sign_up_button}>
              <FontIcon
                className="material-icons">
                person_add
              </FontIcon>
            </FloatingActionButton>

            <TextField
              hintText="Email"
              type="Email"
              fullWidth={true}
            />

            <TextField
              hintText="Password"
              type="Password"
              fullWidth={true}
            />

          <RaisedButton
            label={intl.formatMessage({id: 'sign_in'})}
            secondary={true}
            style={styles.button}
            fullWidth={true}
            icon={
              <FontIcon
                className="material-icons">
                lock
              </FontIcon>
            }
          />

          <GoogleLogin
            style={{backgroundColor: 'transparent', borderRadius:0, border: 0, padding: 0, width: '100%'}}
            clientId={config.google_client_id}
            scope="profile"
            tag="div"
            onSuccess={responseGoogle}>
            <RaisedButton
              label={intl.formatMessage({id: 'sign_in_with_google'})}
              icon={<GoogleIcon color={muiTheme.palette.accent1Color}/>}
              style={styles.button}
              primary={true}
              fullWidth={true}
            />
          </GoogleLogin>

          <FacebookLogin
            appId={config.facebook_app_id}
            //autoLoad={true}
            fields="name,email,picture"
            //redirectUri="https://www.soft-erp.eu/test"
            disableMobileRedirect={true}
            textButton=""
            cssClass=""
            icon={<RaisedButton
              label={intl.formatMessage({id: 'sign_in_with_facebook'})}
              icon={<FacebookIcon color={muiTheme.palette.accent1Color}/>}
              style={styles.button}
              primary={true}
              fullWidth={true}
            />}
            tag="div"
            callback={responseFacebook}/>

          </Paper>

    );
  }
  SignIn.propTypes = {
    updateAuth: PropTypes.func.isRequired,
    auth: PropTypes.object,
    //intl: intlShape.isRequired,
  };

  const mapStateToProps = (state) => {
    const { auth } = state;
    return {
      auth
    };
  };

  const mapDispatchToProps = (dispatch) => {

    return {
      updateAuth: (auth) => {
        dispatch(updateAuth(auth));
      },
      push: (path)=>{
        dispatch(push(path))
      },
    }
  };

  export default connect(
    mapStateToProps,
    mapDispatchToProps
  )(injectIntl(muiThemeable()(SignIn)));
<commit_msg>Repaired signin style<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Paper from 'material-ui/Paper';
import {GoogleIcon, FacebookIcon} from '../../components/Icons';
import {injectIntl} from 'react-intl';
import muiThemeable from 'material-ui/styles/muiThemeable';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import { updateAuth } from '../../actions/auth';
import GoogleLogin from 'react-google-login';
import FacebookLogin from 'react-facebook-login';
import config from '../../config'
import { push } from 'react-router-redux';
import { ResponsiveAppBar } from 'material-ui-responsive-drawer';
import FontIcon from 'material-ui/FontIcon';

const styles={
  paper:{
    height: '100%',
    display: 'block',
    margin:0,
    padding: 15
  },
  container: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    margin: 5,
    marginTop: 100,
  },
  button: {
    margin:6,
    align: 'left'
  },
  sign_up_button: {
    float: 'right',
    overflow: 'none',
    alignSelf: 'flex-end',
    marginRight:-43,
  }
}

const SignIn = (props) => {

  const { muiTheme, intl, updateAuth, push }=props;

  const  responseGoogle = (googleUser) => {
    console.log(googleUser);
    var profile = googleUser.getBasicProfile();
    updateAuth({name: profile.getName(), email: profile.getEmail(), img: profile.getImageUrl() });
    push('/');
  }

  const responseFacebook = (facebookUser) => {
    console.log(facebookUser);
    updateAuth({name: facebookUser.name, email: facebookUser.email, img: facebookUser.picture.data.url });
    push('/');
  }

  return (

      <ResponsiveAppBar
        title={intl.formatMessage({id: 'sign_in'})}
      />

        <Paper  zDepth={2} style={styles.paper}>

{intl.formatMessage({id: 'sign_in'}).toUpperCase()}

            <FloatingActionButton style={styles.sign_up_button}>
              <FontIcon
                className="material-icons">
                person_add
              </FontIcon>
            </FloatingActionButton>

            <TextField
              hintText="Email"
              type="Email"
              fullWidth={true}
            />

            <TextField
              hintText="Password"
              type="Password"
              fullWidth={true}
            />

          <RaisedButton
            label={intl.formatMessage({id: 'sign_in'})}
            secondary={true}
            style={styles.button}
            fullWidth={true}
            icon={
              <FontIcon
                className="material-icons">
                lock
              </FontIcon>
            }
          />

          <GoogleLogin
            style={{backgroundColor: 'transparent', borderRadius:0, border: 0, padding: 0, width: '100%'}}
            clientId={config.google_client_id}
            scope="profile"
            tag="div"
            onSuccess={responseGoogle}>
            <RaisedButton
              label={intl.formatMessage({id: 'sign_in_with_google'})}
              icon={<GoogleIcon color={muiTheme.palette.accent1Color}/>}
              style={styles.button}
              primary={true}
              fullWidth={true}
            />
          </GoogleLogin>

          <FacebookLogin
            appId={config.facebook_app_id}
            //autoLoad={true}
            fields="name,email,picture"
            //redirectUri="https://www.soft-erp.eu/test"
            disableMobileRedirect={true}
            textButton=""
            cssClass=""
            icon={<RaisedButton
              label={intl.formatMessage({id: 'sign_in_with_facebook'})}
              icon={<FacebookIcon color={muiTheme.palette.accent1Color}/>}
              style={styles.button}
              primary={true}
              fullWidth={true}
            />}
            tag="div"
            callback={responseFacebook}/>

          </Paper>

    );
  }
  SignIn.propTypes = {
    updateAuth: PropTypes.func.isRequired,
    auth: PropTypes.object,
    //intl: intlShape.isRequired,
  };

  const mapStateToProps = (state) => {
    const { auth } = state;
    return {
      auth
    };
  };

  const mapDispatchToProps = (dispatch) => {

    return {
      updateAuth: (auth) => {
        dispatch(updateAuth(auth));
      },
      push: (path)=>{
        dispatch(push(path))
      },
    }
  };

  export default connect(
    mapStateToProps,
    mapDispatchToProps
  )(injectIntl(muiThemeable()(SignIn)));
<|endoftext|>


<commit_before>/*global assert:true */
'use strict';

var assert = require('chai').assert;
assert.equalObjects = function (a, b, m) {
  assert.deepEqual(JSON.parse(JSON.stringify(a)), JSON.parse(JSON.stringify(b)), m || 'Objects should be equal!');
};
var mocha = require('mocha');
var coMocha = require('co-mocha');
coMocha(mocha);
var JSData = require('js-data');
JSData.DSUtils.Promise = require('bluebird');
var DSSqlAdapter = require('./');

var adapter, store, DSUtils, DSErrors, Profile, User, Post, Comment;

var globals = module.exports = {
  fail: function (msg) {
    assert.equal('should not reach this!: ' + msg, 'failure');
  },
  TYPES_EXCEPT_STRING: [123, 123.123, null, undefined, {}, [], true, false, function () {
  }],
  TYPES_EXCEPT_STRING_OR_ARRAY: [123, 123.123, null, undefined, {}, true, false, function () {
  }],
  TYPES_EXCEPT_STRING_OR_NUMBER: [null, undefined, {}, [], true, false, function () {
  }],
  TYPES_EXCEPT_STRING_OR_OBJECT: [123, 123.123, null, undefined, [], true, false, function () {
  }],
  TYPES_EXCEPT_STRING_OR_NUMBER_OBJECT: [null, undefined, [], true, false, function () {
  }],
  TYPES_EXCEPT_STRING_OR_ARRAY_OR_NUMBER: [null, undefined, {}, true, false, function () {
  }],
  TYPES_EXCEPT_NUMBER: ['string', null, undefined, {}, [], true, false, function () {
  }],
  TYPES_EXCEPT_OBJECT: ['string', 123, 123.123, null, undefined, true, false, function () {
  }],
  TYPES_EXCEPT_BOOLEAN: ['string', 123, 123.123, null, undefined, {}, [], function () {
  }],
  TYPES_EXCEPT_FUNCTION: ['string', 123, 123.123, null, undefined, {}, [], true, false],
  assert: assert,
  adapter: undefined
};

var test = new mocha();

var testGlobals = [];

for (var key in globals) {
  global[key] = globals[key];
  testGlobals.push(globals[key]);
}
test.globals(testGlobals);

beforeEach(function () {
  store = new JSData.DS({
    log: false
  });
  adapter = new DSSqlAdapter({
    client: 'mysql',
    connection: {
      user: process.env.C9_USER || 'ubuntu',
      database: process.env.C9_USER ? 'c9' : 'circle_test'
      //user: 'root',
      //database: 'test'
    }
  });
  DSUtils = JSData.DSUtils;
  DSErrors = JSData.DSErrors;
  globals.Profile = global.Profile = Profile = store.defineResource({
    name: 'profile'
  });
  globals.User = global.User = User = store.defineResource({
    name: 'user',
    relations: {
      hasMany: {
        post: {
          localField: 'posts',
          foreignKey: 'post'
        }
      },
      hasOne: {
        profile: {
          localField: 'profile',
          localKey: 'profileId'
        }
      }
    }
  });
  globals.Post = global.Post = Post = store.defineResource({
    name: 'post',
    relations: {
      belongsTo: {
        user: {
          localField: 'user',
          localKey: 'userId'
        }
      },
      hasMany: {
        comment: {
          localField: 'comments',
          foreignKey: 'postId'
        }
      }
    }
  });
  globals.Comment = global.Comment = Comment = store.defineResource({
    name: 'comment',
    relations: {
      belongsTo: {
        post: {
          localField: 'post',
          localKey: 'postId'
        },
        user: {
          localField: 'user',
          localKey: 'userId'
        }
      }
    }
  });

  globals.adapter = adapter;
  global.adapter = globals.adapter;

  globals.DSUtils = DSUtils;
  global.DSUtils = globals.DSUtils;

  globals.DSErrors = DSErrors;
  global.DSErrors = globals.DSErrors;
});

afterEach(function* () {
  globals.adapter = null;
  global.adapter = null;

  yield adapter.destroyAll(Comment);
  yield adapter.destroyAll(Post);
  yield adapter.destroyAll(User);
  yield adapter.destroyAll(Profile);
});
<commit_msg>Allow passing database test configuration using environment variables (DB_HOST, DB_USER, DB_NAME)<commit_after>/*global assert:true */
'use strict';

var assert = require('chai').assert;
assert.equalObjects = function (a, b, m) {
  assert.deepEqual(JSON.parse(JSON.stringify(a)), JSON.parse(JSON.stringify(b)), m || 'Objects should be equal!');
};
var mocha = require('mocha');
var coMocha = require('co-mocha');
coMocha(mocha);
var JSData = require('js-data');
JSData.DSUtils.Promise = require('bluebird');
var DSSqlAdapter = require('./');

var adapter, store, DSUtils, DSErrors, Profile, User, Post, Comment;

var globals = module.exports = {
  fail: function (msg) {
    assert.equal('should not reach this!: ' + msg, 'failure');
  },
  TYPES_EXCEPT_STRING: [123, 123.123, null, undefined, {}, [], true, false, function () {
  }],
  TYPES_EXCEPT_STRING_OR_ARRAY: [123, 123.123, null, undefined, {}, true, false, function () {
  }],
  TYPES_EXCEPT_STRING_OR_NUMBER: [null, undefined, {}, [], true, false, function () {
  }],
  TYPES_EXCEPT_STRING_OR_OBJECT: [123, 123.123, null, undefined, [], true, false, function () {
  }],
  TYPES_EXCEPT_STRING_OR_NUMBER_OBJECT: [null, undefined, [], true, false, function () {
  }],
  TYPES_EXCEPT_STRING_OR_ARRAY_OR_NUMBER: [null, undefined, {}, true, false, function () {
  }],
  TYPES_EXCEPT_NUMBER: ['string', null, undefined, {}, [], true, false, function () {
  }],
  TYPES_EXCEPT_OBJECT: ['string', 123, 123.123, null, undefined, true, false, function () {
  }],
  TYPES_EXCEPT_BOOLEAN: ['string', 123, 123.123, null, undefined, {}, [], function () {
  }],
  TYPES_EXCEPT_FUNCTION: ['string', 123, 123.123, null, undefined, {}, [], true, false],
  assert: assert,
  adapter: undefined
};

var test = new mocha();

var testGlobals = [];

for (var key in globals) {
  global[key] = globals[key];
  testGlobals.push(globals[key]);
}
test.globals(testGlobals);

beforeEach(function () {
  store = new JSData.DS({
    log: false
  });
  adapter = new DSSqlAdapter({
    client: 'mysql',
    connection: {
      host: process.env.DB_HOST || 'localhost',
      user: process.env.DB_USER || process.env.C9_USER || 'ubuntu',
      database: process.env.DB_NAME || (process.env.C9_USER ? 'c9' : 'circle_test')
      //user: 'root',
      //database: 'test'
    }
  });
  DSUtils = JSData.DSUtils;
  DSErrors = JSData.DSErrors;
  globals.Profile = global.Profile = Profile = store.defineResource({
    name: 'profile'
  });
  globals.User = global.User = User = store.defineResource({
    name: 'user',
    relations: {
      hasMany: {
        post: {
          localField: 'posts',
          foreignKey: 'post'
        }
      },
      hasOne: {
        profile: {
          localField: 'profile',
          localKey: 'profileId'
        }
      }
    }
  });
  globals.Post = global.Post = Post = store.defineResource({
    name: 'post',
    relations: {
      belongsTo: {
        user: {
          localField: 'user',
          localKey: 'userId'
        }
      },
      hasMany: {
        comment: {
          localField: 'comments',
          foreignKey: 'postId'
        }
      }
    }
  });
  globals.Comment = global.Comment = Comment = store.defineResource({
    name: 'comment',
    relations: {
      belongsTo: {
        post: {
          localField: 'post',
          localKey: 'postId'
        },
        user: {
          localField: 'user',
          localKey: 'userId'
        }
      }
    }
  });

  globals.adapter = adapter;
  global.adapter = globals.adapter;

  globals.DSUtils = DSUtils;
  global.DSUtils = globals.DSUtils;

  globals.DSErrors = DSErrors;
  global.DSErrors = globals.DSErrors;
});

afterEach(function* () {
  globals.adapter = null;
  global.adapter = null;

  yield adapter.destroyAll(Comment);
  yield adapter.destroyAll(Post);
  yield adapter.destroyAll(User);
  yield adapter.destroyAll(Profile);
});
<|endoftext|>


<commit_before>var assert = require('assert');
var jsub = require('../src');

describe('jsub', function() {

  describe('with autorized contents', function() {

    it('should work with simple arithmetics', function() {
      var errors = jsub('1 + 1', {
        conditions: [{
          type: 'Program'
        }, {
          type: 'ExpressionStatement'
        }, {
          type: 'Program'
        }, {
          type: 'BinaryExpression',
          operator: '+'
        }, {
          type: 'Literal',
          raw: /^([0-9]{1,5}|false|true)$/
        }]
      });
      assert.equal(errors.length, 0);
    });

    it('should work with defined functions calls', function() {
      var errors = jsub('1 + 1 + taskValue("abbacacaabbacacaabbacaca")', {
        conditions: [{
          type: 'Program'
        }, {
          type: 'ExpressionStatement'
        }, {
          type: 'Program'
        }, {
          type: 'BinaryExpression',
          operator: '+'
        }, {
          type: 'Literal',
          raw: /^([0-9]{1,5}|false|true)$/
        }, {
          type: 'CallExpression',
          '$_': function(expression) {
            return expression.callee &&
              'Identifier' === expression.callee.type &&
              'taskValue' === expression.callee.name &&
              1 === expression.arguments.length &&
              'Literal' === expression.arguments[0].type &&
              /^([0-9a-f]{24})$/.test(expression.arguments[0].value);
          }
        }]
      });
      assert.equal(errors.length, 0);
    });

    it('should work with array conds', function() {
      var errors = jsub('3 + 9 * 5 - 6', {
        conditions: [{
          type: 'Program'
        }, {
          type: 'ExpressionStatement'
        }, {
          type: 'Program'
        }, {
          type: 'BinaryExpression',
          operator: ['+', '-', '*', '/']
        }, {
          type: 'Literal',
          raw: /^([0-9]{1,5}|false|true)$/
        }]
      });
      assert.equal(errors.length, 0);
    });

    it('should work with complexer nested expressions', function() {
      var errors = jsub('(taskValue("abbacacaabbacacaabbacaca") > 1  || taskValue("abbacacaabbacacaabbacaca") < 2) && (1+2 == 3)', {
        conditions: [{
          type: 'Program'
        }, {
          type: 'ExpressionStatement'
        }, {
          type: 'Program'
        }, {
          type: 'BinaryExpression',
          operator: ['>', '<', '+', '==']
        }, {
          type: 'LogicalExpression',
          operator: ['||', '&&']
        }, {
          type: 'Literal',
          raw: /^([0-9]{1,5}|false|true)$/
        }, {
          type: 'CallExpression',
          '$_': function(expression) {
            return expression.callee &&
              'Identifier' === expression.callee.type &&
              'taskValue' === expression.callee.name &&
              1 === expression.arguments.length &&
              'Literal' === expression.arguments[0].type &&
              /^([0-9a-f]{24})$/.test(expression.arguments[0].value);
          }
        }]
      });
      assert.equal(errors.length, 0);
    });

  });

  describe('with unautorized contents', function() {

    it('should fail when some simple value conds aren\'t matching', function() {
      var errors = jsub('1 + 1', {
        conditions: [{
          type: 'Program'
        }, {
          type: 'ExpressionStatement'
        }, {
          type: 'Program'
        }, {
          type: 'BinaryExpression',
          operator: '-' // Here
        }, {
          type: 'Literal',
          raw: /^([0-9]{1,5}|false|true)$/
        }]
      });
      assert.equal(errors.length, 2);
    });

    it('should fail when some regExp conds aren\'t matching', function() {
      var errors = jsub('1 + 1', {
        conditions: [{
          type: 'Program'
        }, {
          type: 'ExpressionStatement'
        }, {
          type: 'Program'
        }, {
          type: 'BinaryExpression',
          operator: '+'
        }, {
          type: 'Literal',
          raw: /^(false|true)$/ // Here
        }]
      });
      assert.equal(errors.length, 4);
    });

    it('should throw when conds aren\'t recognized', function() {
      assert.throws(function() {
        jsub('1 + 1', {
          conditions: [{
            ahah: null
          }, {
            type: 'Program'
          }, {
            type: 'ExpressionStatement'
          }, {
            type: 'Program'
          }, {
            type: 'BinaryExpression',
            operator: '-' // Here
          }, {
            type: 'Literal',
            raw: /^([0-9]{1,5}|false|true)$/
          }]
        });
      });
    });

  });

});
<commit_msg>Some security tests<commit_after>var assert = require('assert');
var jsub = require('../src');

describe('jsub', function() {

  describe('with autorized contents', function() {

    it('should work with simple arithmetics', function() {
      var errors = jsub('1 + 1', {
        conditions: [{
          type: 'Program'
        }, {
          type: 'ExpressionStatement'
        }, {
          type: 'Program'
        }, {
          type: 'BinaryExpression',
          operator: '+'
        }, {
          type: 'Literal',
          raw: /^([0-9]{1,5}|false|true)$/
        }]
      });
      assert.equal(errors.length, 0);
    });

    it('should work with defined functions calls', function() {
      var errors = jsub('1 + 1 + taskValue("abbacacaabbacacaabbacaca")', {
        conditions: [{
          type: 'Program'
        }, {
          type: 'ExpressionStatement'
        }, {
          type: 'Program'
        }, {
          type: 'BinaryExpression',
          operator: '+'
        }, {
          type: 'Literal',
          raw: /^([0-9]{1,5}|false|true)$/
        }, {
          type: 'CallExpression',
          '$_': function(expression) {
            return expression.callee &&
              'Identifier' === expression.callee.type &&
              'taskValue' === expression.callee.name &&
              1 === expression.arguments.length &&
              'Literal' === expression.arguments[0].type &&
              /^([0-9a-f]{24})$/.test(expression.arguments[0].value);
          }
        }]
      });
      assert.equal(errors.length, 0);
    });

    it('should work with array conds', function() {
      var errors = jsub('3 + 9 * 5 - 6', {
        conditions: [{
          type: 'Program'
        }, {
          type: 'ExpressionStatement'
        }, {
          type: 'Program'
        }, {
          type: 'BinaryExpression',
          operator: ['+', '-', '*', '/']
        }, {
          type: 'Literal',
          raw: /^([0-9]{1,5}|false|true)$/
        }]
      });
      assert.equal(errors.length, 0);
    });

    it('should work with complexer nested expressions', function() {
      var errors = jsub('(taskValue("abbacacaabbacacaabbacaca") > 1  || taskValue("abbacacaabbacacaabbacaca") < 2) && (1+2 == 3)', {
        conditions: [{
          type: 'Program'
        }, {
          type: 'ExpressionStatement'
        }, {
          type: 'Program'
        }, {
          type: 'BinaryExpression',
          operator: ['>', '<', '+', '==']
        }, {
          type: 'LogicalExpression',
          operator: ['||', '&&']
        }, {
          type: 'Literal',
          raw: /^([0-9]{1,5}|false|true)$/
        }, {
          type: 'CallExpression',
          '$_': function(expression) {
            return expression.callee &&
              'Identifier' === expression.callee.type &&
              'taskValue' === expression.callee.name &&
              1 === expression.arguments.length &&
              'Literal' === expression.arguments[0].type &&
              /^([0-9a-f]{24})$/.test(expression.arguments[0].value);
          }
        }]
      });
      assert.equal(errors.length, 0);
    });

  });

  describe('with unautorized contents', function() {

    it('should fail when some simple value conds aren\'t matching', function() {
      var errors = jsub('1 + 1', {
        conditions: [{
          type: 'Program'
        }, {
          type: 'ExpressionStatement'
        }, {
          type: 'Program'
        }, {
          type: 'BinaryExpression',
          operator: '-' // Here
        }, {
          type: 'Literal',
          raw: /^([0-9]{1,5}|false|true)$/
        }]
      });
      assert.equal(errors.length, 2);
    });

    it('should fail when trying to access window', function() {
      var errors = jsub('document.cookies;', {
        conditions: [{
          type: 'Program'
        }, {
          type: 'ExpressionStatement'
        }, {
          type: 'Program'
        }, {
          type: 'BinaryExpression',
          operator: '-' // Here
        }, {
          type: 'Literal',
          raw: /^([0-9]{1,5}|false|true)$/
        }]
      });
      assert.equal(errors.length, 2);
    });

    it('should fail when some regExp conds aren\'t matching', function() {
      var errors = jsub('1 + 1', {
        conditions: [{
          type: 'Program'
        }, {
          type: 'ExpressionStatement'
        }, {
          type: 'Program'
        }, {
          type: 'BinaryExpression',
          operator: '+'
        }, {
          type: 'Literal',
          raw: /^(false|true)$/ // Here
        }]
      });
      assert.equal(errors.length, 4);
    });

    it('should throw when conds aren\'t recognized', function() {
      assert.throws(function() {
        jsub('1 + 1', {
          conditions: [{
            ahah: null
          }, {
            type: 'Program'
          }, {
            type: 'ExpressionStatement'
          }, {
            type: 'Program'
          }, {
            type: 'BinaryExpression',
            operator: '-' // Here
          }, {
            type: 'Literal',
            raw: /^([0-9]{1,5}|false|true)$/
          }]
        });
      });
    });

  });

});
<|endoftext|>


<commit_before>/*
* Requires and test a module.
*/

var myTestableModule = require("../src/scripts/modules/my-testable-module.js");

describe("Function to multiply two numbers", function(){
   var arithmetic = myTestableModule;

   it("should return the result of the multiplication", function(){
      expect(arithmetic).toBeDefined()
      expect(arithmetic.mult(5,2)).toBe(10)
   });
});
<commit_msg>change jasmine matcher<commit_after>/*
* Requires and test a module.
*/

var myTestableModule = require("../src/scripts/modules/my-testable-module.js");

describe("Function to multiply two numbers", function(){
   var arithmetic = myTestableModule;

   it("it should be defined", function(){
      expect(arithmetic).toBeDefined()
   });

   it("5 and 2 should return 10", function(){
      expect(arithmetic.mult(5,2)).toEqual(10)
   });

   it("2 and 2 should return 4", function(){
      expect(arithmetic.mult(2,8)).toEqual(16)
   });
});
<|endoftext|>