<commit_before>(function( $ ) {

module( "accordion: events", accordionSetupTeardown() );

test( "beforeActivate", function() {
	expect( 47 );
	var ac = $( "#list1" ).accordion({
		active: false,
		collapsible: true
	});
	var headers = ac.find( ".ui-accordion-header" );
	var content = ac.find( ".ui-accordion-content" );

	ac.one( "accordionbeforeactivate", function( event, ui ) {
		ok( !( "originalEvent" in event ) );
		equals( ui.oldHeader.size(), 0 );
		equals( ui.oldContent.size(), 0 );
		equals( ui.newHeader.size(), 1 );
		strictEqual( ui.newHeader[ 0 ], headers[ 0 ] );
		equals( ui.newContent.size(), 1 );
		strictEqual( ui.newContent[ 0 ], content[ 0 ] );
		state( ac, 0, 0, 0 );
	});
	ac.accordion( "option", "active", 0 );
	state( ac, 1, 0, 0 );

	ac.one( "accordionbeforeactivate", function( event, ui ) {
		equals( event.originalEvent.type, "click" );
		equals( ui.oldHeader.size(), 1 );
		strictEqual( ui.oldHeader[ 0 ], headers[ 0 ] );
		equals( ui.oldContent.size(), 1 );
		strictEqual( ui.oldContent[ 0 ], content[ 0 ] );
		equals( ui.newHeader.size(), 1 );
		strictEqual( ui.newHeader[ 0 ], headers[ 1 ] );
		equals( ui.newContent.size(), 1 );
		strictEqual( ui.newContent[ 0 ], content[ 1 ] );
		state( ac, 1, 0, 0 );
	});
	headers.eq( 1 ).click();
	state( ac, 0, 1, 0 );

	ac.one( "accordionbeforeactivate", function( event, ui ) {
		ok( !( "originalEvent" in event ) );
		equals( ui.oldHeader.size(), 1 );
		strictEqual( ui.oldHeader[ 0 ], headers[ 1 ] );
		equals( ui.oldContent.size(), 1 );
		strictEqual( ui.oldContent[ 0 ], content[ 1 ] );
		equals( ui.newHeader.size(), 0 );
		equals( ui.newContent.size(), 0 );
		state( ac, 0, 1, 0 );
	});
	ac.accordion( "option", "active", false );
	state( ac, 0, 0, 0 );

	ac.one( "accordionbeforeactivate", function( event, ui ) {
		ok( !( "originalEvent" in event ) );
		equals( ui.oldHeader.size(), 0 );
		equals( ui.oldContent.size(), 0 );
		equals( ui.newHeader.size(), 1 );
		strictEqual( ui.newHeader[ 0 ], headers[ 1 ] );
		equals( ui.newContent.size(), 1 );
		strictEqual( ui.newContent[ 0 ], content[ 1 ] );
		event.preventDefault();
		state( ac, 0, 0, 0 );
	});
	ac.accordion( "option", "active", 1 );
	state( ac, 0, 0, 0 );

	ac.one( "accordionbeforeactivate", function( event, ui ) {
		equals( event.originalEvent.type, "click" );
		equals( ui.oldHeader.size(), 0 );
		equals( ui.oldContent.size(), 0 );
		equals( ui.newHeader.size(), 1 );
		strictEqual( ui.newHeader[ 0 ], headers[ 2 ] );
		equals( ui.newContent.size(), 1 );
		strictEqual( ui.newContent[ 0 ], content[ 2 ] );
		event.preventDefault();
		state( ac, 0, 0, 0 );
	});
	headers.eq( 2 ).click();
	state( ac, 0, 0, 0 );
});

test( "activate", function() {
	expect( 20 );
	var ac = $( "#list1" ).accordion({
		active: false,
		collapsible: true
	});
	var headers = ac.find( ".ui-accordion-header" );
	var content = ac.find( ".ui-accordion-content" );

	ac.one( "accordionactivate", function( event, ui ) {
		equals( ui.oldHeader.size(), 0 );
		equals( ui.oldContent.size(), 0 );
		equals( ui.newHeader.size(), 1 );
		strictEqual( ui.newHeader[ 0 ], headers[ 0 ] );
		equals( ui.newContent.size(), 1 );
		strictEqual( ui.newContent[ 0 ], content[ 0 ] );
	});
	ac.accordion( "option", "active", 0 );

	ac.one( "accordionactivate", function( event, ui ) {
		equals( ui.oldHeader.size(), 1 );
		strictEqual( ui.oldHeader[ 0 ], headers[ 0 ] );
		equals( ui.oldContent.size(), 1 );
		strictEqual( ui.oldContent[ 0 ], content[ 0 ] );
		equals( ui.newHeader.size(), 1 );
		strictEqual( ui.newHeader[ 0 ], headers[ 1 ] );
		equals( ui.newContent.size(), 1 );
		strictEqual( ui.newContent[ 0 ], content[ 1 ] );
	});
	headers.eq( 1 ).click();

	ac.one( "accordionactivate", function( event, ui ) {
		equals( ui.oldHeader.size(), 1 );
		strictEqual( ui.oldHeader[ 0 ], headers[ 1 ] );
		equals( ui.oldContent.size(), 1 );
		strictEqual( ui.oldContent[ 0 ], content[ 1 ] );
		equals( ui.newHeader.size(), 0 );
		equals( ui.newContent.size(), 0 );
	});
	ac.accordion( "option", "active", false );
});

}( jQuery ) );
<commit_msg>Accordion: Removed unnecessary test.<commit_after>(function( $ ) {

module( "accordion: events", accordionSetupTeardown() );

test( "beforeActivate", function() {
	expect( 38 );
	var ac = $( "#list1" ).accordion({
		active: false,
		collapsible: true
	});
	var headers = ac.find( ".ui-accordion-header" );
	var content = ac.find( ".ui-accordion-content" );

	ac.one( "accordionbeforeactivate", function( event, ui ) {
		ok( !( "originalEvent" in event ) );
		equals( ui.oldHeader.size(), 0 );
		equals( ui.oldContent.size(), 0 );
		equals( ui.newHeader.size(), 1 );
		strictEqual( ui.newHeader[ 0 ], headers[ 0 ] );
		equals( ui.newContent.size(), 1 );
		strictEqual( ui.newContent[ 0 ], content[ 0 ] );
		state( ac, 0, 0, 0 );
	});
	ac.accordion( "option", "active", 0 );
	state( ac, 1, 0, 0 );

	ac.one( "accordionbeforeactivate", function( event, ui ) {
		equals( event.originalEvent.type, "click" );
		equals( ui.oldHeader.size(), 1 );
		strictEqual( ui.oldHeader[ 0 ], headers[ 0 ] );
		equals( ui.oldContent.size(), 1 );
		strictEqual( ui.oldContent[ 0 ], content[ 0 ] );
		equals( ui.newHeader.size(), 1 );
		strictEqual( ui.newHeader[ 0 ], headers[ 1 ] );
		equals( ui.newContent.size(), 1 );
		strictEqual( ui.newContent[ 0 ], content[ 1 ] );
		state( ac, 1, 0, 0 );
	});
	headers.eq( 1 ).click();
	state( ac, 0, 1, 0 );

	ac.one( "accordionbeforeactivate", function( event, ui ) {
		ok( !( "originalEvent" in event ) );
		equals( ui.oldHeader.size(), 1 );
		strictEqual( ui.oldHeader[ 0 ], headers[ 1 ] );
		equals( ui.oldContent.size(), 1 );
		strictEqual( ui.oldContent[ 0 ], content[ 1 ] );
		equals( ui.newHeader.size(), 0 );
		equals( ui.newContent.size(), 0 );
		state( ac, 0, 1, 0 );
	});
	ac.accordion( "option", "active", false );
	state( ac, 0, 0, 0 );

	ac.one( "accordionbeforeactivate", function( event, ui ) {
		ok( !( "originalEvent" in event ) );
		equals( ui.oldHeader.size(), 0 );
		equals( ui.oldContent.size(), 0 );
		equals( ui.newHeader.size(), 1 );
		strictEqual( ui.newHeader[ 0 ], headers[ 2 ] );
		equals( ui.newContent.size(), 1 );
		strictEqual( ui.newContent[ 0 ], content[ 2 ] );
		event.preventDefault();
		state( ac, 0, 0, 0 );
	});
	ac.accordion( "option", "active", 2 );
	state( ac, 0, 0, 0 );
});

test( "activate", function() {
	expect( 20 );
	var ac = $( "#list1" ).accordion({
		active: false,
		collapsible: true
	});
	var headers = ac.find( ".ui-accordion-header" );
	var content = ac.find( ".ui-accordion-content" );

	ac.one( "accordionactivate", function( event, ui ) {
		equals( ui.oldHeader.size(), 0 );
		equals( ui.oldContent.size(), 0 );
		equals( ui.newHeader.size(), 1 );
		strictEqual( ui.newHeader[ 0 ], headers[ 0 ] );
		equals( ui.newContent.size(), 1 );
		strictEqual( ui.newContent[ 0 ], content[ 0 ] );
	});
	ac.accordion( "option", "active", 0 );

	ac.one( "accordionactivate", function( event, ui ) {
		equals( ui.oldHeader.size(), 1 );
		strictEqual( ui.oldHeader[ 0 ], headers[ 0 ] );
		equals( ui.oldContent.size(), 1 );
		strictEqual( ui.oldContent[ 0 ], content[ 0 ] );
		equals( ui.newHeader.size(), 1 );
		strictEqual( ui.newHeader[ 0 ], headers[ 1 ] );
		equals( ui.newContent.size(), 1 );
		strictEqual( ui.newContent[ 0 ], content[ 1 ] );
	});
	headers.eq( 1 ).click();

	ac.one( "accordionactivate", function( event, ui ) {
		equals( ui.oldHeader.size(), 1 );
		strictEqual( ui.oldHeader[ 0 ], headers[ 1 ] );
		equals( ui.oldContent.size(), 1 );
		strictEqual( ui.oldContent[ 0 ], content[ 1 ] );
		equals( ui.newHeader.size(), 0 );
		equals( ui.newContent.size(), 0 );
	});
	ac.accordion( "option", "active", false );
});

}( jQuery ) );
<|endoftext|>


<commit_before>// ephemeral.js
// scene where glitchy controls thrive
var QUARTER_CIRCLE_RADIANS = 1.57079633; // Math.PI / 2
var SCENE_HEIGHT = 1000;

// create scene, camera, one plane, light,
var camera, scene, renderer, deviceControls, ground;

var clock;

var lastBalloonReset = 0,
    balloons = [];

function init() {
  var plane, light, groundTexture;

  clock = new THREE.Clock();

	scene = new THREE.Scene();
  scene.fog = new THREE.Fog( 0xcce0ff, 500, 10000 );

  scene.add( new THREE.AmbientLight( 0x666666 ) );

  camera = new THREE.PerspectiveCamera( 45, window.innerWidth /
      window.innerHeight, 1, 2000 );

  camera.position.set( 0, 100, 0 );
  // camera.lookAt(scene.position);

  deviceControls = new THREE.DeviceOrientationControls( camera );

  var light = new THREE.PointLight( 0xaaddaa, .5 );
  light.position.set( 50, 1200, -500 );
  scene.add( light );

  groundTexture = THREE.ImageUtils.loadTexture(
      "textures/Moon.png" );

  // groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping;
  // groundTexture.repeat.set( 432, 432 );
  groundTexture.anisotropy = 16;

  var groundMaterial = new THREE.MeshPhongMaterial( { color: 0xffffff,
      specular: 0x111111, map: groundTexture } );

	ground = new THREE.Mesh( new THREE.PlaneBufferGeometry( 10000, 10000 ),
      groundMaterial );

	ground.position.y = -10;
	ground.rotation.x = -Math.PI / 2;
  camera.rotation.x = -Math.PI / 2;
	ground.receiveShadow = true;
	scene.add( ground );

  renderer = new THREE.WebGLRenderer();
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );
  document.body.appendChild( renderer.domElement );

  startBalloons();
  makeHUD();
}

function animate() {

  requestAnimationFrame( animate );

  deviceControls.update();

  movementUpdate();

  TWEEN.update();

  renderer.render( scene, camera );

}

function startBalloons () {
  setInterval(function() {

    if (balloons.length < 50) {
      makeBalloon({
        x: 2000 * Math.random() - 1000,
        y: 0, //-200,
        z: 2000 * Math.random() - 1000
      });

    } else {
      resetBalloon();
    }

  }, 500);
}

/*
 *  make new balloon
 *  setBalloon()
 */
function makeBalloon (pos) {
  // make sphere
  var geometry = new THREE.SphereGeometry(15, 10, 10);

  var groundTexture = THREE.ImageUtils.loadTexture(
      "textures/Moon.png" );

  // TODO: random color
  var material = new THREE.MeshPhongMaterial({
    color: 0xaff00,
    map: groundTexture
  });

  var mesh = new THREE.Mesh( geometry, material );

  mesh.position.set(pos.x, pos.y, pos.z);

  balloons.push(mesh);

  scene.add(mesh);

  // tween up to top position
  var target = {
    x: pos.x,
    y: SCENE_HEIGHT,
    z: pos.z
  };

  doTween(pos, target, mesh, TWEEN.Easing.Cubic.Out, 25000)
}

function resetBalloon () {
  var b, pos, target;

  for (var i = lastBalloonReset; i < balloons.length; i++) {
    b = balloons[i];

    if (b.position.y === SCENE_HEIGHT) {
      target = {
        x: b.position.x,
        y: b.position.y,
        z: b.position.z
      };
      pos = {
        x: b.position.x,
        y: 0,
        z: b.position.z
      };

      doTween(pos, target, b, TWEEN.Easing.Cubic.In, 25000)
      break;
    }

    if (i + 1 === balloons.length) {
      lastBalloonReset = 0;
    }
  }
}

// animate item from start position, to target,
function doTween (position, target, obj, easing, time) {
  var tween = new TWEEN.Tween(position).to(target, time);

  tween.onUpdate(function(){
    obj.position.x = position.x;
    obj.position.y = position.y;
    obj.position.z = position.z;
  });

  tween.easing(easing);

  tween.start();
}

var move = {
  forward: false,
  back: false,
  left: false,
  right: false
};

function movementUpdate () {
  var delta = clock.getDelta(); // seconds.
	var moveDistance = 200 * delta; // 200 pixels / second
	var rotateAngle = Math.PI / 2 * delta;   // pi/2 radians (90 degrees) / second

  if (move.forward) {
    camera.translateZ( -moveDistance );
  }

  if (move.back) {
    camera.translateZ( moveDistance );
  }

  if (move.left) {
    camera.translateX( -moveDistance );
  }

  if (move.right) {
    camera.translateX( moveDistance );
  }

  if (move.up) {
    camera.translateY( moveDistance );
  }

  if (move.down) {
    camera.translateY( -moveDistance );
  }

}

function makeHUD () {
  var geometry = new THREE.SphereGeometry(15, 10, 10);

  var texture = THREE.ImageUtils.loadTexture(
      "textures/golfball.jpg" );

  var material = new THREE.MeshPhongMaterial({
    color: 0xaff00,
    map: texture
  });

  var huds = [];

  for (var i = 0; i < 6; i++) {
    huds[i] = new THREE.Mesh( geometry, material );
    huds[i].position.y =  100;
    scene.add(huds[i]);

  }

  var offset = 250;

  huds[0].position.z =  offset;
  huds[1].position.z = -offset;

  // huds[2].position.y =  100;
  // huds[3].position.y =  100;

  huds[4].position.x =  offset;
  huds[5].position.x = -offset;

  // huds.lookAt(camera.position);

  console.log("mesh", huds);
  console.log("camera", camera);
}

init();
animate();
<commit_msg>updated movement to prevent the camera from going beneath the ground<commit_after>// ephemeral.js
// scene where glitchy controls thrive
var QUARTER_CIRCLE_RADIANS = 1.57079633; // Math.PI / 2
var SCENE_HEIGHT = 1000;

// create scene, camera, one plane, light,
var camera, scene, renderer, deviceControls, ground;

var clock;

var lastBalloonReset = 0,
    balloons = [];

function init() {
  var plane, light, groundTexture;

  clock = new THREE.Clock();

	scene = new THREE.Scene();
  scene.fog = new THREE.Fog( 0xcce0ff, 500, 10000 );

  scene.add( new THREE.AmbientLight( 0x666666 ) );

  camera = new THREE.PerspectiveCamera( 45, window.innerWidth /
      window.innerHeight, 1, 2000 );

  camera.position.set( 0, 100, 0 );
  // camera.lookAt(scene.position);

  deviceControls = new THREE.DeviceOrientationControls( camera );

  var light = new THREE.PointLight( 0xaaddaa, .5 );
  light.position.set( 50, 1200, -500 );
  scene.add( light );

  groundTexture = THREE.ImageUtils.loadTexture(
      "textures/Moon.png" );

  // groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping;
  // groundTexture.repeat.set( 432, 432 );
  groundTexture.anisotropy = 16;

  var groundMaterial = new THREE.MeshPhongMaterial( { color: 0xffffff,
      specular: 0x111111, map: groundTexture } );

	ground = new THREE.Mesh( new THREE.PlaneBufferGeometry( 10000, 10000 ),
      groundMaterial );

	ground.position.y = -10;
	ground.rotation.x = -Math.PI / 2;
  camera.rotation.x = -Math.PI / 2;
	ground.receiveShadow = true;
	scene.add( ground );

  renderer = new THREE.WebGLRenderer();
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );
  document.body.appendChild( renderer.domElement );

  startBalloons();
  makeHUD();
}

function animate() {

  requestAnimationFrame( animate );

  deviceControls.update();

  movementUpdate();

  TWEEN.update();

  renderer.render( scene, camera );

}

function startBalloons () {
  setInterval(function() {

    if (balloons.length < 50) {
      makeBalloon({
        x: 2000 * Math.random() - 1000,
        y: 0, //-200,
        z: 2000 * Math.random() - 1000
      });

    } else {
      resetBalloon();
    }

  }, 500);
}

/*
 *  make new balloon
 *  setBalloon()
 */
function makeBalloon (pos) {
  // make sphere
  var geometry = new THREE.SphereGeometry(15, 10, 10);

  var groundTexture = THREE.ImageUtils.loadTexture(
      "textures/Moon.png" );

  // TODO: random color
  var material = new THREE.MeshPhongMaterial({
    color: 0xaff00,
    map: groundTexture
  });

  var mesh = new THREE.Mesh( geometry, material );

  mesh.position.set(pos.x, pos.y, pos.z);

  balloons.push(mesh);

  scene.add(mesh);

  // tween up to top position
  var target = {
    x: pos.x,
    y: SCENE_HEIGHT,
    z: pos.z
  };

  doTween(pos, target, mesh, TWEEN.Easing.Cubic.Out, 25000)
}

function resetBalloon () {
  var b, pos, target;

  for (var i = lastBalloonReset; i < balloons.length; i++) {
    b = balloons[i];

    if (b.position.y === SCENE_HEIGHT) {
      target = {
        x: b.position.x,
        y: b.position.y,
        z: b.position.z
      };
      pos = {
        x: b.position.x,
        y: 0,
        z: b.position.z
      };

      doTween(pos, target, b, TWEEN.Easing.Cubic.In, 25000)
      break;
    }

    if (i + 1 === balloons.length) {
      lastBalloonReset = 0;
    }
  }
}

// animate item from start position, to target,
function doTween (position, target, obj, easing, time) {
  var tween = new TWEEN.Tween(position).to(target, time);

  tween.onUpdate(function(){
    obj.position.x = position.x;
    obj.position.y = position.y;
    obj.position.z = position.z;
  });

  tween.easing(easing);

  tween.start();
}

var move = {
  forward: false,
  back: false,
  left: false,
  right: false
};

function movementUpdate () {
  var delta = clock.getDelta(); // seconds.
	var moveDistance = 200 * delta; // 200 pixels / second
	var rotateAngle = Math.PI / 2 * delta;   // pi/2 radians (90 degrees) / second

  if (move.forward) {
    camera.translateZ( -moveDistance );
  }

  if (move.back) {
    camera.translateZ( moveDistance );
  }

  if (move.left) {
    camera.translateX( -moveDistance );
  }

  if (move.right) {
    camera.translateX( moveDistance );
  }

  if (move.up) {
    camera.translateY( moveDistance );
  }

  if (move.down && parseFloat(camera.position.y) > parseFloat(ground.position.y + moveDistance) ) {
    camera.translateY( -moveDistance );
  }

  if (camera.position.y <= -10) {
    camera.position.y = 0;
  }

}

function makeHUD () {
  var geometry = new THREE.SphereGeometry(15, 10, 10);

  var texture = THREE.ImageUtils.loadTexture(
      "textures/golfball.jpg" );

  var material = new THREE.MeshPhongMaterial({
    color: 0xaff00,
    map: texture
  });

  var huds = [];

  for (var i = 0; i < 6; i++) {
    huds[i] = new THREE.Mesh( geometry, material );
    huds[i].position.y =  100;
    scene.add(huds[i]);

  }

  var offset = 250;

  huds[0].position.z =  offset;
  huds[1].position.z = -offset;

  // huds[2].position.y =  100;
  // huds[3].position.y =  100;

  huds[4].position.x =  offset;
  huds[5].position.x = -offset;

  // huds.lookAt(camera.position);

  console.log("mesh", huds);
  console.log("camera", camera);
}

init();
animate();
<|endoftext|>


<commit_before>/* ===========================================================
 * Bootstrap: fileinput.js v3.1.1
 * http://jasny.github.com/bootstrap/javascript/#fileinput
 * ===========================================================
 * Copyright 2012-2014 Arnold Daniels
 *
 * Licensed under the Apache License, Version 2.0 (the "License")
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */

+function ($) { "use strict";

  var isIE = window.navigator.appName == 'Microsoft Internet Explorer'

  // FILEUPLOAD PUBLIC CLASS DEFINITION
  // =================================

  var Fileinput = function (element, options) {
    this.$element = $(element)

    this.$input = this.$element.find(':file')
    if (this.$input.length === 0) return

    this.name = this.$input.attr('name') || options.name

    this.$hidden = this.$element.find('input[type=hidden][name="' + this.name + '"]')
    if (this.$hidden.length === 0) {
      this.$hidden = $('<input type="hidden" />')
      this.$element.prepend(this.$hidden)
    }

    this.$preview = this.$element.find('.fileinput-preview')
    var height = this.$preview.css('height')
    if (this.$preview.css('display') != 'inline' && height != '0px' && height != 'none') this.$preview.css('line-height', height)

    this.original = {
      exists: this.$element.hasClass('fileinput-exists'),
      preview: this.$preview.html(),
      hiddenVal: this.$hidden.val()
    }

    this.listen()
  }

  Fileinput.prototype.listen = function() {
    this.$input.on('change.bs.fileinput', $.proxy(this.change, this))
    $(this.$input[0].form).on('reset.bs.fileinput', $.proxy(this.reset, this))

    this.$element.find('[data-trigger="fileinput"]').on('click.bs.fileinput', $.proxy(this.trigger, this))
    this.$element.find('[data-dismiss="fileinput"]').on('click.bs.fileinput', $.proxy(this.clear, this))
  },

  Fileinput.prototype.change = function(e) {
    if (e.target.files === undefined) e.target.files = e.target && e.target.value ? [ {name: e.target.value.replace(/^.+\\/, '')} ] : []

    if (e.target.files.length === 0) {
      this.clear()
      return
    }

    this.$hidden.val('')
    this.$hidden.attr('name', '')
    this.$input.attr('name', this.name)

    var file = e.target.files[0]

    if (this.$preview.length > 0 && (typeof file.type !== "undefined" ? file.type.match('image.*') : file.name.match(/\.(gif|png|jpe?g)$/i)) && typeof FileReader !== "undefined") {
      var reader = new FileReader()
      var preview = this.$preview
      var element = this.$element

      reader.onload = function(re) {
        var $img = $('<img>') // .attr('src', re.target.result)
        $img[0].src = re.target.result
        e.target.files[0].result = re.target.result

        element.find('.fileinput-filename').text(file.name)

        // if parent has max-height, using `(max-)height: 100%` on child doesn't take padding and border into account
        if (preview.css('max-height') != 'none') $img.css('max-height', parseInt(preview.css('max-height'), 10) - parseInt(preview.css('padding-top'), 10) - parseInt(preview.css('padding-bottom'), 10)  - parseInt(preview.css('border-top'), 10) - parseInt(preview.css('border-bottom'), 10))

        preview.html($img)
        element.addClass('fileinput-exists').removeClass('fileinput-new')

        element.trigger('change.bs.fileinput', e.target.files)
      }

      reader.readAsDataURL(file)
    } else {
      this.$element.find('.fileinput-filename').text(file.name)
      this.$preview.text(file.name)

      this.$element.addClass('fileinput-exists').removeClass('fileinput-new')

      this.$element.trigger('change.bs.fileinput')
    }
  },

  Fileinput.prototype.clear = function(e) {
    if (e) e.preventDefault()

    this.$hidden.val('')
    this.$hidden.attr('name', this.name)
    this.$input.attr('name', '')

    //ie8+ doesn't support changing the value of input with type=file so clone instead
    if (isIE) {
      var inputClone = this.$input.clone(true);
      this.$input.after(inputClone);
      this.$input.remove();
      this.$input = inputClone;
    } else {
      this.$input.val('')
    }

    this.$preview.html('')
    this.$element.find('.fileinput-filename').text('')
    this.$element.addClass('fileinput-new').removeClass('fileinput-exists')

    if (e !== false) {
      this.$input.trigger('change')
      this.$element.trigger('clear.bs.fileinput')
    }
  },

  Fileinput.prototype.reset = function() {
    this.clear(false)

    this.$hidden.val(this.original.hiddenVal)
    this.$preview.html(this.original.preview)
    this.$element.find('.fileinput-filename').text('')

    if (this.original.exists) this.$element.addClass('fileinput-exists').removeClass('fileinput-new')
     else this.$element.addClass('fileinput-new').removeClass('fileinput-exists')

    this.$element.trigger('reset.bs.fileinput')
  },

  Fileinput.prototype.trigger = function(e) {
    this.$input.trigger('click')
    e.preventDefault()
  }

  // FILEUPLOAD PLUGIN DEFINITION
  // ===========================

  var old = $.fn.fileinput

  $.fn.fileinput = function (options) {
    return this.each(function () {
      var $this = $(this),
          data = $this.data('fileinput')
      if (!data) $this.data('fileinput', (data = new Fileinput(this, options)))
      if (typeof options == 'string') data[options]()
    })
  }

  $.fn.fileinput.Constructor = Fileinput

  // FILEINPUT NO CONFLICT
  // ====================

  $.fn.fileinput.noConflict = function () {
    $.fn.fileinput = old
    return this
  }

  // FILEUPLOAD DATA-API
  // ==================

  $(document).on('click.fileinput.data-api', '[data-provides="fileinput"]', function (e) {
    var $this = $(this)
    if ($this.data('fileinput')) return
    $this.fileinput($this.data())

    var $target = $(e.target).closest('[data-dismiss="fileinput"],[data-trigger="fileinput"]');
    if ($target.length > 0) {
      e.preventDefault()
      $target.trigger('click.bs.fileinput')
    }
  })

}(window.jQuery);
<commit_msg>Only preview gif, png and jpeg images. Fixes #181<commit_after>/* ===========================================================
 * Bootstrap: fileinput.js v3.1.1
 * http://jasny.github.com/bootstrap/javascript/#fileinput
 * ===========================================================
 * Copyright 2012-2014 Arnold Daniels
 *
 * Licensed under the Apache License, Version 2.0 (the "License")
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */

+function ($) { "use strict";

  var isIE = window.navigator.appName == 'Microsoft Internet Explorer'

  // FILEUPLOAD PUBLIC CLASS DEFINITION
  // =================================

  var Fileinput = function (element, options) {
    this.$element = $(element)

    this.$input = this.$element.find(':file')
    if (this.$input.length === 0) return

    this.name = this.$input.attr('name') || options.name

    this.$hidden = this.$element.find('input[type=hidden][name="' + this.name + '"]')
    if (this.$hidden.length === 0) {
      this.$hidden = $('<input type="hidden" />')
      this.$element.prepend(this.$hidden)
    }

    this.$preview = this.$element.find('.fileinput-preview')
    var height = this.$preview.css('height')
    if (this.$preview.css('display') != 'inline' && height != '0px' && height != 'none') this.$preview.css('line-height', height)

    this.original = {
      exists: this.$element.hasClass('fileinput-exists'),
      preview: this.$preview.html(),
      hiddenVal: this.$hidden.val()
    }

    this.listen()
  }

  Fileinput.prototype.listen = function() {
    this.$input.on('change.bs.fileinput', $.proxy(this.change, this))
    $(this.$input[0].form).on('reset.bs.fileinput', $.proxy(this.reset, this))

    this.$element.find('[data-trigger="fileinput"]').on('click.bs.fileinput', $.proxy(this.trigger, this))
    this.$element.find('[data-dismiss="fileinput"]').on('click.bs.fileinput', $.proxy(this.clear, this))
  },

  Fileinput.prototype.change = function(e) {
    if (e.target.files === undefined) e.target.files = e.target && e.target.value ? [ {name: e.target.value.replace(/^.+\\/, '')} ] : []

    if (e.target.files.length === 0) {
      this.clear()
      return
    }

    this.$hidden.val('')
    this.$hidden.attr('name', '')
    this.$input.attr('name', this.name)

    var file = e.target.files[0]

    if (this.$preview.length > 0 && (typeof file.type !== "undefined" ? file.type.match(/^image\/(gif|png|jpeg)$/) : file.name.match(/\.(gif|png|jpe?g)$/i)) && typeof FileReader !== "undefined") {
      var reader = new FileReader()
      var preview = this.$preview
      var element = this.$element

      reader.onload = function(re) {
        var $img = $('<img>')
        $img[0].src = re.target.result
        e.target.files[0].result = re.target.result

        element.find('.fileinput-filename').text(file.name)

        // if parent has max-height, using `(max-)height: 100%` on child doesn't take padding and border into account
        if (preview.css('max-height') != 'none') $img.css('max-height', parseInt(preview.css('max-height'), 10) - parseInt(preview.css('padding-top'), 10) - parseInt(preview.css('padding-bottom'), 10)  - parseInt(preview.css('border-top'), 10) - parseInt(preview.css('border-bottom'), 10))

        preview.html($img)
        element.addClass('fileinput-exists').removeClass('fileinput-new')

        element.trigger('change.bs.fileinput', e.target.files)
      }

      reader.readAsDataURL(file)
    } else {
      this.$element.find('.fileinput-filename').text(file.name)
      this.$preview.text(file.name)

      this.$element.addClass('fileinput-exists').removeClass('fileinput-new')

      this.$element.trigger('change.bs.fileinput')
    }
  },

  Fileinput.prototype.clear = function(e) {
    if (e) e.preventDefault()

    this.$hidden.val('')
    this.$hidden.attr('name', this.name)
    this.$input.attr('name', '')

    //ie8+ doesn't support changing the value of input with type=file so clone instead
    if (isIE) {
      var inputClone = this.$input.clone(true);
      this.$input.after(inputClone);
      this.$input.remove();
      this.$input = inputClone;
    } else {
      this.$input.val('')
    }

    this.$preview.html('')
    this.$element.find('.fileinput-filename').text('')
    this.$element.addClass('fileinput-new').removeClass('fileinput-exists')

    if (e !== false) {
      this.$input.trigger('change')
      this.$element.trigger('clear.bs.fileinput')
    }
  },

  Fileinput.prototype.reset = function() {
    this.clear(false)

    this.$hidden.val(this.original.hiddenVal)
    this.$preview.html(this.original.preview)
    this.$element.find('.fileinput-filename').text('')

    if (this.original.exists) this.$element.addClass('fileinput-exists').removeClass('fileinput-new')
     else this.$element.addClass('fileinput-new').removeClass('fileinput-exists')

    this.$element.trigger('reset.bs.fileinput')
  },

  Fileinput.prototype.trigger = function(e) {
    this.$input.trigger('click')
    e.preventDefault()
  }

  // FILEUPLOAD PLUGIN DEFINITION
  // ===========================

  var old = $.fn.fileinput

  $.fn.fileinput = function (options) {
    return this.each(function () {
      var $this = $(this),
          data = $this.data('fileinput')
      if (!data) $this.data('fileinput', (data = new Fileinput(this, options)))
      if (typeof options == 'string') data[options]()
    })
  }

  $.fn.fileinput.Constructor = Fileinput

  // FILEINPUT NO CONFLICT
  // ====================

  $.fn.fileinput.noConflict = function () {
    $.fn.fileinput = old
    return this
  }

  // FILEUPLOAD DATA-API
  // ==================

  $(document).on('click.fileinput.data-api', '[data-provides="fileinput"]', function (e) {
    var $this = $(this)
    if ($this.data('fileinput')) return
    $this.fileinput($this.data())

    var $target = $(e.target).closest('[data-dismiss="fileinput"],[data-trigger="fileinput"]');
    if ($target.length > 0) {
      e.preventDefault()
      $target.trigger('click.bs.fileinput')
    }
  })

}(window.jQuery);
<|endoftext|>


<commit_before>import React, {Component} from "react";
import Controls from "./Controls";
import Grid from "./Grid";
import {
    getColor,
    getNeighborsCoord,
    getCellCoordinates,
    getCenterCoordinates,
    getCellCoordinatesToDraw
        } from "../utils/helpers";
import PropTypes from "prop-types";

class App extends Component {
    state = {
        gridWidth: "501px",
        gridHeight: "381px",
        cellSize: 9
    }

    static propTypes = {
        gridWidth: PropTypes.string,
        gridHeight: PropTypes.string,
        onUpdate: PropTypes.func,
        handleReset: PropTypes.func,
        handleStart: PropTypes.func
    }

    /**
     * Draws cell grid on update
     * @param {number} length Canvas length
     * @param {number} height Canvas height
     */
    handleUpdateCanvas = (length, height) => {
        var canvas = document.getElementById("game-grid");
        var context = canvas.getContext("2d");
        for (let x = 0.5; x < length; x += 10) {
            context.moveTo(x, 0);
            context.lineTo(x, height);
        }

        for (let y = 0.5; y < height; y += 10) {
            context.moveTo(0, y);
            context.lineTo(length, y);
        }

        context.strokeStyle = "#ddd";
        context.stroke();
    }

    handleStart = () => {

        let centerCoordinates = getCenterCoordinates();
        let canvas = document.getElementById("game-grid");
        let ctx = canvas.getContext("2d");

        for (let coordinates of centerCoordinates) {
            let cellColor = getColor(ctx, ...coordinates);

            if ( cellColor === 16776960 ) { // decimal for yellow color
                console.log(`Cell is filled. Coordinates: ${coordinates}`)
                console.log( getNeighborsCoord(...coordinates) )
                // getColor()
            }
        }
    }

    handleReset = () => {
        let canvas = document.getElementById("game-grid");
        let ctx = canvas.getContext("2d");

        let width = parseInt(this.state.gridWidth, 10);
        let height = parseInt(this.state.gridHeight, 10);

        ctx.clearRect(0, 0, canvas.width, canvas.height);
        this.handleUpdateCanvas(width, height);
    }

    render() {
        let width= this.state.gridWidth;
        let height = this.state.gridHeight;

        return(

                <Controls handleReset={this.handleReset}
                          handleStart={this.handleStart}/>
                <Grid gridWidth={width}
                      gridHeight={height}
                      onUpdate={this.handleUpdateCanvas}/>

        );
    }
}

export default App;
<commit_msg>Add documentation<commit_after>import React, {Component} from "react";
import Controls from "./Controls";
import Grid from "./Grid";
import {
    getColor,
    getNeighborsCoord,
    getCellCoordinates,
    getCenterCoordinates,
    getCellCoordinatesToDraw
        } from "../utils/helpers";
import PropTypes from "prop-types";

class App extends Component {
    state = {
        gridWidth: "501px",
        gridHeight: "381px",
        cellSize: 9
    }

    static propTypes = {
        /**
         * Game grid length
         */
        gridWidth: PropTypes.string,
        /**
         * Game grid height
         */
        gridHeight: PropTypes.string,
        /**
         * Gets called when game grid updates: at initial run and Reset
         */
        onUpdate: PropTypes.func,
        /**
         * Gets called when user resets game state
         */
        handleReset: PropTypes.func,
        /**
         * Gets called when user clicks game start buttons
         */
        handleStart: PropTypes.func
    }

    /**
     * Draws cell grid on update
     * @param {number} length Canvas length
     * @param {number} height Canvas height
     */
    handleUpdateCanvas = (length, height) => {
        var canvas = document.getElementById("game-grid");
        var context = canvas.getContext("2d");
        for (let x = 0.5; x < length; x += 10) {
            context.moveTo(x, 0);
            context.lineTo(x, height);
        }

        for (let y = 0.5; y < height; y += 10) {
            context.moveTo(0, y);
            context.lineTo(length, y);
        }

        context.strokeStyle = "#ddd";
        context.stroke();
    }

    handleStart = () => {

        let centerCoordinates = getCenterCoordinates();
        let canvas = document.getElementById("game-grid");
        let ctx = canvas.getContext("2d");

        for (let coordinates of centerCoordinates) {
            let cellColor = getColor(ctx, ...coordinates);

            if ( cellColor === 16776960 ) { // decimal for yellow color
                console.log(`Cell is filled. Coordinates: ${coordinates}`)
                console.log( getNeighborsCoord(...coordinates) )
                // getColor()
            }
        }
    }

    handleReset = () => {
        let canvas = document.getElementById("game-grid");
        let ctx = canvas.getContext("2d");

        let width = parseInt(this.state.gridWidth, 10);
        let height = parseInt(this.state.gridHeight, 10);

        ctx.clearRect(0, 0, canvas.width, canvas.height);
        this.handleUpdateCanvas(width, height);
    }

    render() {
        let width= this.state.gridWidth;
        let height = this.state.gridHeight;

        return(

                <Controls handleReset={this.handleReset}
                          handleStart={this.handleStart}/>
                <Grid gridWidth={width}
                      gridHeight={height}
                      onUpdate={this.handleUpdateCanvas}/>

        );
    }
}

export default App;
<|endoftext|>


<commit_before>import React from 'react'

import AvailableNGWords from '../containers/AvailableNGWords'
import ClearNGWords from '../containers/ClearNGWords'

export default class App extends React.Component {
  render() {
    return (
      <div>
        <AvailableNGWords />
        <ClearNGWords />
      </div>
    )
  }
}
<commit_msg>wrap App with MuiThemeProvider<commit_after>import React from 'react'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'

import AvailableNGWords from '../containers/AvailableNGWords'
import ClearNGWords from '../containers/ClearNGWords'

export default class App extends React.Component {
  render() {
    return (
      <MuiThemeProvider>
        <AvailableNGWords />
        <ClearNGWords />
      </MuiThemeProvider>
    )
  }
}
<|endoftext|>


<commit_before>/*
   The state of a ccg type card game.
*/

require("seedrandom")

// The state of a single player.
class PlayerState {
  constructor(data) {
    this.name = data.name
    this.hand = data.hand || []
    this.board = data.board || []
    this.trash = data.trash || []
    this.life = data.life || 30
    this.mana = data.mana || 0
    this.maxMana = data.maxMana || 0
  }

  // Moves a card from hand to trash.
  handToTrash(index) {
    let card = this.getHand(index)
    this.hand.splice(index, 1)
    this.trash.push(card)
  }

  // Moves a card from board to trash.
  boardToTrash(index) {
    let card = this.getBoard(index)
    this.board.splice(index, 1)
    this.trash.push(card)
  }

  // Moves a card from hand to board.
  handToBoard(index) {
    let card = this.getHand(index)
    this.hand.splice(index, 1)
    this.board.push(card)
  }

  // Throws if the index is bad
  getHand(index) {
    if (index >= this.hand.length) {
      throw (this.name + "'s hand has no card at index " + index)
    }
    return this.hand[index]
  }

  // Throws if the index is bad
  getBoard(index) {
    if (index >= this.board.length) {
      throw (this.name + "'s board has no card at index " + index)
    }
    return this.board[index]
  }
}

// A turn goes like
//
// beginTurn
// Some number of selectCard, selectOpponent
// endTurn
//
class GameState {

  // name is the name of the human at the controls.
  constructor(data) {
    this.name = data.name
    this._started = data._started || false

    let playerInfo = data.players || [{name: this.name},
                                      {name: "waiting..."}]
    this.players = playerInfo.map(info => new PlayerState(info))

    // The name of the winner
    this.winner = data.winner || null

    // set this to true for plenty of mana, for testing
    this.godMode = false

    // A list of all moves we have ever made on the game state
    this.history = []
  }

  // The player who's playing locally
  current() {
    return this.players[0]
  }

  // The remote player
  opponent() {
    return this.players[1]
  }

  // Each type of move has a JSON representation.
  //
  // The useful keys include:
  // op: the method name. selectCard, selectOpponent, refreshCards
  // from: the index a card is coming from
  // to: the index a card is going to
  //
  // The move also has a "player" and "id" but those are only used by
  // the networking layer.
  //
  // makeMove makes a move that is provided via a JSON representation.
  //
  // In typical operation, only the Client should call makeMove.
  //
  // Returns whether the move was understood.
  makeMove(move) {
    if (this.winner != null) {
      // You can't make normal moves when the game is over
      return false
    }

    if (move.op == "refreshCards") {
      this.refreshCards()
    } else if (move.op == "resign") {
      this.resign(move)
    } else if (move.op == "selectCard") {
      /*
        the possible container types are board, hand, trash,
        as well as the opponentFoo for each type
      */
      this.selectCard(move.index, move.containerType, move.player)
    } else if (move.op == "selectOpponent") {
      this.selectOpponent(move.player)
    } else if (move.op == "draw") {
      this.draw(move.player, move.card)
    } else {
      console.log("ignoring op: " + move.op)
      return false
    }

    this.history.push(move)
    return true
  }

  logHistory() {
    console.log("" + this.history.length + " moves in history.")
    for (let move of this.history) {
      console.log(JSON.stringify(move))
    }
  }

  startGame(players, seed) {
    this.rng = new Math.seedrandom(seed)
    if (players[0] == this.name) {
      this.players[1].name = players[1]
    } else if (players[1] == this.name) {
      this.players[1].name = players[0]
    } else {
      console.log(`a game started without me, ${this.name}`)
      return
    }

    // always your turn in spacetime
    this._started = true
    this.refreshCards()
  }

  started() {
    return this._started;
  }

  resolveDamage() {

    for (var i=0;i<this.players.length;i++) {
      var player = this.players[i]
      player.board = player.board.filter(card => card.defense > 0)
    }
    if (this.current().life <= 0) {
      this.winner = this.opponent().name
    } else if (this.opponent().life <= 0) {
      this.winner = this.current().name
    }
    if (this.winner != null) {
      console.log(this.winner + " wins!")
    }
  }

  // containerType can be board or hand
  selectCard(index, containerType, selectingPlayerName) {
    let usePlayer
    let opponent
    if (selectingPlayerName == this.current().name) {
      usePlayer = this.current()
      opponent = this.opponent()
    } else {
      usePlayer = this.opponent()
      opponent = this.current()
    }
    if (!usePlayer.selectedCard) {
      this.setSelectedCard(index, containerType, usePlayer)
      return;
    }
    let card;
    if (containerType == "board") {
      if (usePlayer.name == selectingPlayerName) {
        this.faceForPlayer(usePlayer, index)
      } else {
        this.faceForPlayer(opponent, index)
      }
    } else if (containerType == "hand") {
      if (usePlayer.name == selectingPlayerName) {
        this.playForPlayer(usePlayer, index)
      } else {
        this.playForPlayer(opponent, index)
      }
    } else if (containerType == "opponentBoard") {
      // select a card in opponent's board
      if (usePlayer.name == selectingPlayerName) {
        this.attackForPlayerIfBoardSelected(usePlayer, index)
        this.playOnForPlayerIfHandSelected(usePlayer, index)
      } else {
        this.attackForPlayerIfBoardSelected(opponent, index)
        this.playOnForPlayerIfHandSelected(opponent, index)
      }
    }
  }

  attackForPlayerIfBoardSelected(player, index) {
    // check for attack from board
    let boardIndex = player.board.indexOf(player.selectedCard);
    if (boardIndex != -1) {
      player.selectedCard = null;
      this.attack(boardIndex, index, player);
    }
  }

  playOnForPlayerIfHandSelected(player, index) {
    let handIndex = player.hand.indexOf(player.selectedCard);
    if (handIndex != -1) {
      player.selectedCard = null;
      this.playOn(handIndex, index, player)
    }
  }

  faceForPlayer(player, index) {
    let card = player.getBoard(index)
    if (card == player.selectedCard) {
      player.selectedCard = null;
      this.face(index, player)
    }
  }

  playForPlayer(player, index) {
    let card = player.getHand(index)
    if (card == player.selectedCard) {
      player.selectedCard = null;
      this.play(index, player)
    }
  }

  // containerType can be board or hand
  setSelectedCard(index, containerType, player) {
    if (containerType == "board") {
      let card = player.getBoard(index);
      player.selectedCard = card.canAct ? card : null;
    } else if (containerType == "hand") {
      let card = player.getHand(index);
      if (player.mana >= card.cost) {
        player.selectedCard = card
      }
    }
  }

  // select the opponent to cast a spell or target with attack
  selectOpponent(player) {
    let usePlayer
    if (player == this.current().name) {
      usePlayer = this.current()
    } else {
      usePlayer = this.opponent()
    }

    if (usePlayer.selectedCard) {
      return;
    }
    let boardIndex = usePlayer.board.indexOf(usePlayer.selectedCard);
    if (boardIndex != -1) {
      this.face(boardIndex, usePlayer);
    }
    let handIndex = usePlayer.hand.indexOf(usePlayer.selectedCard);
    if (handIndex != -1) {
      this.playFace(handIndex, usePlayer)
    }
  }

  // from and to are indices into board
  attack(from, to, player) {
    let opponent = this.current().name == player.name ? this.opponent() : this.current()
    let attacker = player.getBoard(from)
    let defender = opponent.getBoard(to)
    attacker.defense -= defender.attack
    defender.defense -= attacker.attack
    attacker.canAct = false;
    attacker.needsAttackDisplay = true;
    this.resolveDamage()
  }

  // Plays a card from the hand.
  // Throws if there's not enough mana.
  // from is an index of the hand
  play(from, player) {
    let card = player.getHand(from)
    if (card.requiresTarget) {
      // Player has re-selected this.selectedCard in their hand.
      // In this case, this.selectedCard requiresTarget,
      // so no action occurs besides unselecting the card,
      return;
    }
    if (player.mana < card.cost) {
      throw `need ${card.cost} mana but only have ${player.mana}`
    }
    player.mana -= card.cost

    // move the card to the appropriate container
    if (card.permanent) {
      player.handToBoard(from)
    } else {
      player.handToTrash(from)
    }

    // Finally, play any abilities the card has.

    if (card.kill) {
      let usePlayer
      if (player == this.current()) {
        usePlayer = this.opponent()
      } else {
        usePlayer = this.current()
      }

      if (usePlayer.board.length) {
        let randomIndex = this.rng() * (usePlayer.board.length-1);
        usePlayer.boardToTrash(randomIndex)
      }
    }

    if (card.refreshCards) {
      for (let i = 0; i < card.refreshCards; i++) {
        this.refreshCards()
      }
    }

    if (card.emp) {
      for (let player of this.players) {
        while (player.board.length > 0) {
          player.boardToTrash(0)
        }
      }
    }
  }

  // Plays a card from the hand, onto a target.
  // Throws if there's not enough mana.
  // from is an index of the hand
  playOn(from, to, player) {
    let card = player.getHand(from)
    if (player.mana < card.cost) {
      throw `need ${card.cost} mana but only have ${player.mana}`
    }
    player.handToTrash(from)

    // for direct damage
    if (card.damage) {
      this.damage(to, card.damage, player)
    }
  }

  // Plays a card from the hand, onto a player.
  // Throws if there's not enough mana.
  // from is an index of the hand
  playFace(from, player) {
    let opponent = this.current().name == player.name ? this.opponent() : this.current()
    let card = player.getHand(from)
    if (player.mana < card.cost) {
      throw `need ${card.cost} mana but only have ${player.mana}`
    }
    player.handToTrash(from)

    // for direct damage
    if (card.damage) {
      opponent.life -= card.damage
      this.resolveDamage()
    }
  }

  // for direct damage spells
  damage(to, amount, player) {
    let usePlayer
    if (player == this.current()) {
      usePlayer = this.opponent()
    } else {
      usePlayer = this.current()
    }
    let target = usePlayer.getBoard(to)
    target.defense -= amount
    this.resolveDamage()
  }

  // Whether the game has started
  started() {
    return this._started
  }

  // Attacks face
  face(from, player) {
    let opponent = this.current().name == player.name ? this.opponent() : this.current()
    let attacker = player.getBoard(from)
    opponent.life -= attacker.attack
    attacker.canAct = false
    player.selectedCard = null;
    this.resolveDamage()
  }

  draw(player, card) {
    for (var i = 0; i < this.players.length; i++) {
      var p = this.players[i]
      if (p.name == player.name) {
        p.hand.push(card)
        break;
      }
    }
  }

  refreshCards() {
    this.current().maxMana = Math.min(1 + this.current().maxMana, 10)
    this.opponent().maxMana = Math.min(1 + this.opponent().maxMana, 10)

    if (this.godMode) {
      this.current().maxMana = 99;
      this.opponent().maxMana = 99;
    }

    this.current().mana = this.current().maxMana
    this.opponent().mana = this.opponent().maxMana

    this.selectedCard = null;
    if (this.current().board.length) {
      for (let i = 0; i < this.current().board.length; i++) {
        let card = this.current().board[i];
        card.canAct = true;
      }
    }
    if (this.opponent().board.length) {
      for (let i = 0; i < this.opponent().board.length; i++) {
        let card = this.opponent().board[i];
        card.canAct = true;
      }
    }
  }

  resign(move) {
    let player = this.current().name == move.player ? this.current() : this.opponent()
    player.life = 0
    this.resolveDamage()
  }

}

module.exports = GameState;
<commit_msg>whitespace<commit_after>/*
   The state of a ccg type card game.
*/

require("seedrandom")

// The state of a single player.
class PlayerState {
  constructor(data) {
    this.name = data.name
    this.hand = data.hand || []
    this.board = data.board || []
    this.trash = data.trash || []
    this.life = data.life || 30
    this.mana = data.mana || 0
    this.maxMana = data.maxMana || 0
  }

  // Moves a card from hand to trash.
  handToTrash(index) {
    let card = this.getHand(index)
    this.hand.splice(index, 1)
    this.trash.push(card)
  }

  // Moves a card from board to trash.
  boardToTrash(index) {
    let card = this.getBoard(index)
    this.board.splice(index, 1)
    this.trash.push(card)
  }

  // Moves a card from hand to board.
  handToBoard(index) {
    let card = this.getHand(index)
    this.hand.splice(index, 1)
    this.board.push(card)
  }

  // Throws if the index is bad
  getHand(index) {
    if (index >= this.hand.length) {
      throw (this.name + "'s hand has no card at index " + index)
    }
    return this.hand[index]
  }

  // Throws if the index is bad
  getBoard(index) {
    if (index >= this.board.length) {
      throw (this.name + "'s board has no card at index " + index)
    }
    return this.board[index]
  }
}

// A turn goes like
//
// beginTurn
// Some number of selectCard, selectOpponent
// endTurn
//
class GameState {

  // name is the name of the human at the controls.
  constructor(data) {
    this.name = data.name
    this._started = data._started || false

    let playerInfo = data.players || [{name: this.name},
                                      {name: "waiting..."}]
    this.players = playerInfo.map(info => new PlayerState(info))

    // The name of the winner
    this.winner = data.winner || null

    // set this to true for plenty of mana, for testing
    this.godMode = false

    // A list of all moves we have ever made on the game state
    this.history = []
  }

  // The player who's playing locally
  current() {
    return this.players[0]
  }

  // The remote player
  opponent() {
    return this.players[1]
  }

  // Each type of move has a JSON representation.
  //
  // The useful keys include:
  // op: the method name. selectCard, selectOpponent, refreshCards
  // from: the index a card is coming from
  // to: the index a card is going to
  //
  // The move also has a "player" and "id" but those are only used by
  // the networking layer.
  //
  // makeMove makes a move that is provided via a JSON representation.
  //
  // In typical operation, only the Client should call makeMove.
  //
  // Returns whether the move was understood.
  makeMove(move) {
    if (this.winner != null) {
      // You can't make normal moves when the game is over
      return false
    }

    if (move.op == "refreshCards") {
      this.refreshCards()
    } else if (move.op == "resign") {
      this.resign(move)
    } else if (move.op == "selectCard") {
      /*
        the possible container types are board, hand, trash,
        as well as the opponentFoo for each type
      */
      this.selectCard(move.index, move.containerType, move.player)
    } else if (move.op == "selectOpponent") {
      this.selectOpponent(move.player)
    } else if (move.op == "draw") {
      this.draw(move.player, move.card)
    } else {
      console.log("ignoring op: " + move.op)
      return false
    }

    this.history.push(move)
    return true
  }

  logHistory() {
    console.log("" + this.history.length + " moves in history.")
    for (let move of this.history) {
      console.log(JSON.stringify(move))
    }
  }

  startGame(players, seed) {
    this.rng = new Math.seedrandom(seed)
    if (players[0] == this.name) {
      this.players[1].name = players[1]
    } else if (players[1] == this.name) {
      this.players[1].name = players[0]
    } else {
      console.log(`a game started without me, ${this.name}`)
      return
    }

    // always your turn in spacetime
    this._started = true
    this.refreshCards()
  }

  started() {
    return this._started;
  }

  resolveDamage() {

    for (var i=0;i<this.players.length;i++) {
      var player = this.players[i]
      player.board = player.board.filter(card => card.defense > 0)
    }

    if (this.current().life <= 0) {
      this.winner = this.opponent().name
    } else if (this.opponent().life <= 0) {
      this.winner = this.current().name
    }
    if (this.winner != null) {
      console.log(this.winner + " wins!")
    }
  }

  // containerType can be board or hand
  selectCard(index, containerType, selectingPlayerName) {
    let usePlayer
    let opponent
    if (selectingPlayerName == this.current().name) {
      usePlayer = this.current()
      opponent = this.opponent()
    } else {
      usePlayer = this.opponent()
      opponent = this.current()
    }
    if (!usePlayer.selectedCard) {
      this.setSelectedCard(index, containerType, usePlayer)
      return;
    }
    let card;
    if (containerType == "board") {
      if (usePlayer.name == selectingPlayerName) {
        this.faceForPlayer(usePlayer, index)
      } else {
        this.faceForPlayer(opponent, index)
      }
    } else if (containerType == "hand") {
      if (usePlayer.name == selectingPlayerName) {
        this.playForPlayer(usePlayer, index)
      } else {
        this.playForPlayer(opponent, index)
      }
    } else if (containerType == "opponentBoard") {
      // select a card in opponent's board
      if (usePlayer.name == selectingPlayerName) {
        this.attackForPlayerIfBoardSelected(usePlayer, index)
        this.playOnForPlayerIfHandSelected(usePlayer, index)
      } else {
        this.attackForPlayerIfBoardSelected(opponent, index)
        this.playOnForPlayerIfHandSelected(opponent, index)
      }
    }
  }

  attackForPlayerIfBoardSelected(player, index) {
    // check for attack from board
    let boardIndex = player.board.indexOf(player.selectedCard);
    if (boardIndex != -1) {
      player.selectedCard = null;
      this.attack(boardIndex, index, player);
    }
  }

  playOnForPlayerIfHandSelected(player, index) {
    let handIndex = player.hand.indexOf(player.selectedCard);
    if (handIndex != -1) {
      player.selectedCard = null;
      this.playOn(handIndex, index, player)
    }
  }

  faceForPlayer(player, index) {
    let card = player.getBoard(index)
    if (card == player.selectedCard) {
      player.selectedCard = null;
      this.face(index, player)
    }
  }

  playForPlayer(player, index) {
    let card = player.getHand(index)
    if (card == player.selectedCard) {
      player.selectedCard = null;
      this.play(index, player)
    }
  }

  // containerType can be board or hand
  setSelectedCard(index, containerType, player) {
    if (containerType == "board") {
      let card = player.getBoard(index);
      player.selectedCard = card.canAct ? card : null;
    } else if (containerType == "hand") {
      let card = player.getHand(index);
      if (player.mana >= card.cost) {
        player.selectedCard = card
      }
    }
  }

  // select the opponent to cast a spell or target with attack
  selectOpponent(player) {
    let usePlayer
    if (player == this.current().name) {
      usePlayer = this.current()
    } else {
      usePlayer = this.opponent()
    }

    if (usePlayer.selectedCard) {
      return;
    }
    let boardIndex = usePlayer.board.indexOf(usePlayer.selectedCard);
    if (boardIndex != -1) {
      this.face(boardIndex, usePlayer);
    }
    let handIndex = usePlayer.hand.indexOf(usePlayer.selectedCard);
    if (handIndex != -1) {
      this.playFace(handIndex, usePlayer)
    }
  }

  // from and to are indices into board
  attack(from, to, player) {
    let opponent = this.current().name == player.name ? this.opponent() : this.current()
    let attacker = player.getBoard(from)
    let defender = opponent.getBoard(to)
    attacker.defense -= defender.attack
    defender.defense -= attacker.attack
    attacker.canAct = false;
    attacker.needsAttackDisplay = true;
    this.resolveDamage()
  }

  // Plays a card from the hand.
  // Throws if there's not enough mana.
  // from is an index of the hand
  play(from, player) {
    let card = player.getHand(from)
    if (card.requiresTarget) {
      // Player has re-selected this.selectedCard in their hand.
      // In this case, this.selectedCard requiresTarget,
      // so no action occurs besides unselecting the card,
      return;
    }
    if (player.mana < card.cost) {
      throw `need ${card.cost} mana but only have ${player.mana}`
    }
    player.mana -= card.cost

    // move the card to the appropriate container
    if (card.permanent) {
      player.handToBoard(from)
    } else {
      player.handToTrash(from)
    }

    // Finally, play any abilities the card has.

    if (card.kill) {
      let usePlayer
      if (player == this.current()) {
        usePlayer = this.opponent()
      } else {
        usePlayer = this.current()
      }

      if (usePlayer.board.length) {
        let randomIndex = this.rng() * (usePlayer.board.length-1);
        usePlayer.boardToTrash(randomIndex)
      }
    }

    if (card.refreshCards) {
      for (let i = 0; i < card.refreshCards; i++) {
        this.refreshCards()
      }
    }

    if (card.emp) {
      for (let player of this.players) {
        while (player.board.length > 0) {
          player.boardToTrash(0)
        }
      }
    }
  }

  // Plays a card from the hand, onto a target.
  // Throws if there's not enough mana.
  // from is an index of the hand
  playOn(from, to, player) {
    let card = player.getHand(from)
    if (player.mana < card.cost) {
      throw `need ${card.cost} mana but only have ${player.mana}`
    }
    player.handToTrash(from)

    // for direct damage
    if (card.damage) {
      this.damage(to, card.damage, player)
    }
  }

  // Plays a card from the hand, onto a player.
  // Throws if there's not enough mana.
  // from is an index of the hand
  playFace(from, player) {
    let opponent = this.current().name == player.name ? this.opponent() : this.current()
    let card = player.getHand(from)
    if (player.mana < card.cost) {
      throw `need ${card.cost} mana but only have ${player.mana}`
    }
    player.handToTrash(from)

    // for direct damage
    if (card.damage) {
      opponent.life -= card.damage
      this.resolveDamage()
    }
  }

  // for direct damage spells
  damage(to, amount, player) {
    let usePlayer
    if (player == this.current()) {
      usePlayer = this.opponent()
    } else {
      usePlayer = this.current()
    }
    let target = usePlayer.getBoard(to)
    target.defense -= amount
    this.resolveDamage()
  }

  // Whether the game has started
  started() {
    return this._started
  }

  // Attacks face
  face(from, player) {
    let opponent = this.current().name == player.name ? this.opponent() : this.current()
    let attacker = player.getBoard(from)
    opponent.life -= attacker.attack
    attacker.canAct = false
    player.selectedCard = null;
    this.resolveDamage()
  }

  draw(player, card) {
    for (var i = 0; i < this.players.length; i++) {
      var p = this.players[i]
      if (p.name == player.name) {
        p.hand.push(card)
        break;
      }
    }
  }

  refreshCards() {
    this.current().maxMana = Math.min(1 + this.current().maxMana, 10)
    this.opponent().maxMana = Math.min(1 + this.opponent().maxMana, 10)

    if (this.godMode) {
      this.current().maxMana = 99;
      this.opponent().maxMana = 99;
    }

    this.current().mana = this.current().maxMana
    this.opponent().mana = this.opponent().maxMana

    this.selectedCard = null;
    if (this.current().board.length) {
      for (let i = 0; i < this.current().board.length; i++) {
        let card = this.current().board[i];
        card.canAct = true;
      }
    }
    if (this.opponent().board.length) {
      for (let i = 0; i < this.opponent().board.length; i++) {
        let card = this.opponent().board[i];
        card.canAct = true;
      }
    }
  }

  resign(move) {
    let player = this.current().name == move.player ? this.current() : this.opponent()
    player.life = 0
    this.resolveDamage()
  }

}

module.exports = GameState;
<|endoftext|>


<commit_before>(function($) {
    "use strict"; // Start of use strict

    // Smooth scrolling using jQuery easing
    $('a[href*="#"]:not([href="#"])').click(function() {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
            if (target.length) {
                $('html, body').animate({
                    scrollTop: (target.offset().top - 48)
                }, 1000, "easeInOutExpo");
                return false;
            }
        }
    });

    // Activate scrollspy to add active class to navbar items on scroll
    $('body').scrollspy({
        target: '#mainNav',
        offset: 54
    });

    // Closes responsive menu when a link is clicked
    $('.navbar-collapse>ul>li>a').click(function() {
        $('.navbar-collapse').collapse('hide');
    });

    // Collapse the navbar when page is scrolled
    $(window).scroll(function() {
        if ($("#mainNav").offset().top > 100) {
            $("#mainNav").addClass("navbar-shrink");
        } else {
            $("#mainNav").removeClass("navbar-shrink");
        }
    });

})(jQuery); // End of use strict

// Google Maps Scripts
var map = null;
// When the window has finished loading create our google map below
google.maps.event.addDomListener(window, 'load', init);
google.maps.event.addDomListener(window, 'resize', function() {
    map.setCenter(new google.maps.LatLng(40.6700, -3.129118));
});

function init() {
    // Basic options for a simple Google Map
    // For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions
	var stPierre = {lat: 47.518864, lng: -3.129118};

    var mapOptions = {
        // How zoomed in you want the map to start at (always required)
        zoom: 4,

        // The latitude and longitude to center the map (always required)
        center: stPierre, // ST Pierre

        // Disables the default Google Maps UI components
        //disableDefaultUI: true,
        scrollwheel: false,
        //draggable: false,

        // How you would like to style the map.
        // This is where you would paste any style found on Snazzy Maps.
        /*styles: [{
            "featureType": "water",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }]
        }, {
            "featureType": "landscape",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 20
            }]
        }, {
            "featureType": "road.highway",
            "elementType": "geometry.fill",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }]
        }, {
            "featureType": "road.highway",
            "elementType": "geometry.stroke",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 29
            }, {
                "weight": 0.2
            }]
        }, {
            "featureType": "road.arterial",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 18
            }]
        }, {
            "featureType": "road.local",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 16
            }]
        }, {
            "featureType": "poi",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 21
            }]
        }, {
            "elementType": "labels.text.stroke",
            "stylers": [{
                "visibility": "on"
            }, {
                "color": "#000000"
            }, {
                "lightness": 16
            }]
        }, {
            "elementType": "labels.text.fill",
            "stylers": [{
                "saturation": 36
            }, {
                "color": "#000000"
            }, {
                "lightness": 40
            }]
        }, {
            "elementType": "labels.icon",
            "stylers": [{
                "visibility": "off"
            }]
        }, {
            "featureType": "transit",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 19
            }]
        }, {
            "featureType": "administrative",
            "elementType": "geometry.fill",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 20
            }]
        }, {
            "featureType": "administrative",
            "elementType": "geometry.stroke",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }, {
                "weight": 1.2
            }]
        }]*/
    };

    // Get the HTML DOM element that will contain your map
    // We are using a div with id="map" seen below in the
    var mapElement = document.getElementById('map');

    // Create the Google Map using out element and options defined above
    map = new google.maps.Map(mapElement, mapOptions);

    // Custom Map Marker Icon - Customize the map-marker.png file to customize your icon
    //var image = 'img/map-marker.svg';
    var beachMarker = new google.maps.Marker({
        position: stPierre,
        map: map
        //icon: image
    });
}
<commit_msg>forgot to add the js bit<commit_after>(function($) {
    "use strict"; // Start of use strict

    // Smooth scrolling using jQuery easing
    $('a[href*="#"]:not([href="#"])').click(function() {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
            if (target.length) {
                $('html, body').animate({
                    scrollTop: (target.offset().top - 48)
                }, 1000, "easeInOutExpo");
                return false;
            }
        }
    });

    // Activate scrollspy to add active class to navbar items on scroll
    $('body').scrollspy({
        target: '#mainNav',
        offset: 54
    });

    // Closes responsive menu when a link is clicked
    $('.navbar-collapse>ul>li>a').click(function() {
        $('.navbar-collapse').collapse('hide');
    });

    // Collapse the navbar when page is scrolled
    $(window).scroll(function() {
        if ($("#mainNav").offset().top > 100) {
            $("#mainNav").addClass("navbar-shrink");
        } else {
            $("#mainNav").removeClass("navbar-shrink");
        }
    });

})(jQuery); // End of use strict

// Google Maps Scripts
var map = null;
// When the window has finished loading create our google map below
google.maps.event.addDomListener(window, 'load', init);
google.maps.event.addDomListener(window, 'resize', function() {
    map.setCenter(new google.maps.LatLng(40.6700, -3.129118));
});

function init() {
    // Basic options for a simple Google Map
    // For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions
	var stPierre = {lat: 47.518864, lng: -3.129118};

    var mapOptions = {
        // How zoomed in you want the map to start at (always required)
        zoom: 4,

        // The latitude and longitude to center the map (always required)
        center: stPierre, // ST Pierre

        // Disables the default Google Maps UI components
        //disableDefaultUI: true,
        scrollwheel: false,
        //draggable: false,

        // How you would like to style the map.
        // This is where you would paste any style found on Snazzy Maps.
        /*styles: [{
            "featureType": "water",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }]
        }, {
            "featureType": "landscape",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 20
            }]
        }, {
            "featureType": "road.highway",
            "elementType": "geometry.fill",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }]
        }, {
            "featureType": "road.highway",
            "elementType": "geometry.stroke",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 29
            }, {
                "weight": 0.2
            }]
        }, {
            "featureType": "road.arterial",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 18
            }]
        }, {
            "featureType": "road.local",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 16
            }]
        }, {
            "featureType": "poi",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 21
            }]
        }, {
            "elementType": "labels.text.stroke",
            "stylers": [{
                "visibility": "on"
            }, {
                "color": "#000000"
            }, {
                "lightness": 16
            }]
        }, {
            "elementType": "labels.text.fill",
            "stylers": [{
                "saturation": 36
            }, {
                "color": "#000000"
            }, {
                "lightness": 40
            }]
        }, {
            "elementType": "labels.icon",
            "stylers": [{
                "visibility": "off"
            }]
        }, {
            "featureType": "transit",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 19
            }]
        }, {
            "featureType": "administrative",
            "elementType": "geometry.fill",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 20
            }]
        }, {
            "featureType": "administrative",
            "elementType": "geometry.stroke",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }, {
                "weight": 1.2
            }]
        }]*/
    };

    // Get the HTML DOM element that will contain your map
    // We are using a div with id="map" seen below in the
    var mapElement = document.getElementById('map');

    // Create the Google Map using out element and options defined above
    map = new google.maps.Map(mapElement, mapOptions);

    // Custom Map Marker Icon - Customize the map-marker.png file to customize your icon
    //var image = 'img/map-marker.svg';
    var beachMarker = new google.maps.Marker({
        position: stPierre,
        map: map
        //icon: image
    });
}

$('.with-caption').magnificPopup({
		type: 'image',
		closeOnContentClick: true,
		closeBtnInside: false,
		mainClass: 'mfp-with-zoom mfp-img-mobile',
		image: {
			verticalFit: true,
			titleSrc: function(item) {
				return item.el.attr('title') + ' · image source';
			}
		},
		zoom: {
			enabled: true
		}
	});<|endoftext|>


<commit_before>import React, { Component } from 'react';
import Registry from '../utils/Registry';
import BaseComponent from './BaseComponent';

export default class Div extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div className={this.props.className}>
        {this.props.children.map((element,key) => {
          return React.createElement(Registry.get(element.type), this.props.children[key])
        })}
      </div>
    );
  }
}

Registry.set('Div', Div);
<commit_msg>Remove Div component<commit_after><|endoftext|>


<commit_before>/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = require('fast-isnumeric');
var isArrayOrTypedArray = require('../../lib').isArrayOrTypedArray;
var tinycolor = require('tinycolor2');

var Color = require('../../components/color');
var helpers = require('./helpers');

exports.calc = function calc(gd, trace) {
    var vals = trace.values;
    var hasVals = isArrayOrTypedArray(vals) && vals.length;
    var labels = trace.labels;
    var colors = trace.marker.colors || [];
    var cd = [];
    var fullLayout = gd._fullLayout;
    var colorMap = fullLayout._piecolormap;
    var allThisTraceLabels = {};
    var vTotal = 0;
    var hiddenLabels = fullLayout.hiddenlabels || [];

    var i, v, label, hidden, pt;

    if(trace.dlabel) {
        labels = new Array(vals.length);
        for(i = 0; i < vals.length; i++) {
            labels[i] = String(trace.label0 + i * trace.dlabel);
        }
    }

    function pullColor(color, label) {
        if(!color) return false;

        color = tinycolor(color);
        if(!color.isValid()) return false;

        color = Color.addOpacity(color, color.getAlpha());
        if(!colorMap[label]) colorMap[label] = color;

        return color;
    }

    var seriesLen = (hasVals ? vals : labels).length;

    for(i = 0; i < seriesLen; i++) {
        if(hasVals) {
            v = vals[i];
            if(!isNumeric(v)) continue;
            v = +v;
            if(v < 0) continue;
        }
        else v = 1;

        label = labels[i];
        if(label === undefined || label === '') label = i;
        label = String(label);

        var thisLabelIndex = allThisTraceLabels[label];
        if(thisLabelIndex === undefined) {
            allThisTraceLabels[label] = cd.length;

            hidden = hiddenLabels.indexOf(label) !== -1;

            if(!hidden) vTotal += v;

            cd.push({
                v: v,
                label: label,
                color: pullColor(colors[i], label),
                i: i,
                pts: [i],
                hidden: hidden
            });
        }
        else {
            pt = cd[thisLabelIndex];
            pt.v += v;
            pt.pts.push(i);
            if(!pt.hidden) vTotal += v;

            if(pt.color === false && colors[i]) {
                pt.color = pullColor(colors[i], label);
            }
        }
    }

    if(trace.sort) cd.sort(function(a, b) { return b.v - a.v; });

    // include the sum of all values in the first point
    if(cd[0]) cd[0].vTotal = vTotal;

    // now insert text
    if(trace.textinfo && trace.textinfo !== 'none') {
        var hasLabel = trace.textinfo.indexOf('label') !== -1;
        var hasText = trace.textinfo.indexOf('text') !== -1;
        var hasValue = trace.textinfo.indexOf('value') !== -1;
        var hasPercent = trace.textinfo.indexOf('percent') !== -1;
        var separators = fullLayout.separators;

        var thisText;

        for(i = 0; i < cd.length; i++) {
            pt = cd[i];
            thisText = hasLabel ? [pt.label] : [];
            if(hasText) {
                var texti = helpers.getFirstFilled(trace.text, pt.pts);
                if(texti) thisText.push(texti);
            }
            if(hasValue) thisText.push(helpers.formatPieValue(pt.v, separators));
            if(hasPercent) thisText.push(helpers.formatPiePercent(pt.v / vTotal, separators));
            pt.text = thisText.join('
');
        }
    }

    return cd;
};

/*
 * `calc` filled in (and collated) explicit colors.
 * Now we need to propagate these explicit colors to other traces,
 * and fill in default colors.
 * This is done after sorting, so we pick defaults
 * in the order slices will be displayed
 */
exports.crossTraceCalc = function(gd) {
    var fullLayout = gd._fullLayout;
    var calcdata = gd.calcdata;
    var pieColorWay = fullLayout.piecolorway;
    var colorMap = fullLayout._piecolormap;

    if(fullLayout.extendpiecolors) {
        pieColorWay = generateExtendedColors(pieColorWay);
    }
    var dfltColorCount = 0;

    var i, j, cd, pt;
    for(i = 0; i < calcdata.length; i++) {
        cd = calcdata[i];
        if(cd[0].trace.type !== 'pie') continue;

        for(j = 0; j < cd.length; j++) {
            pt = cd[j];
            if(pt.color === false) {
                // have we seen this label and assigned a color to it in a previous trace?
                if(colorMap[pt.label]) {
                    pt.color = colorMap[pt.label];
                }
                else {
                    colorMap[pt.label] = pt.color = pieColorWay[dfltColorCount % pieColorWay.length];
                    dfltColorCount++;
                }
            }
        }
    }
};

/**
 * pick a default color from the main default set, augmented by
 * itself lighter then darker before repeating
 */
var extendedColorWays = {};

function generateExtendedColors(colorList) {
    var i;
    var colorString = JSON.stringify(colorList);
    var pieColors = extendedColorWays[colorString];
    if(!pieColors) {
        pieColors = colorList.slice();

        for(i = 0; i < colorList.length; i++) {
            pieColors.push(tinycolor(colorList[i]).lighten(20).toHexString());
        }

        for(i = 0; i < colorList.length; i++) {
            pieColors.push(tinycolor(colorList[i]).darken(20).toHexString());
        }
        extendedColorWays[colorString] = pieColors;
    }

    return pieColors;
}
<commit_msg>export a few things in Pie.calc that sunburst will reuse<commit_after>/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = require('fast-isnumeric');
var isArrayOrTypedArray = require('../../lib').isArrayOrTypedArray;
var tinycolor = require('tinycolor2');

var Color = require('../../components/color');
var helpers = require('./helpers');

var pieExtendedColorWays = {};

function calc(gd, trace) {
    var vals = trace.values;
    var hasVals = isArrayOrTypedArray(vals) && vals.length;
    var labels = trace.labels;
    var colors = trace.marker.colors || [];
    var cd = [];
    var fullLayout = gd._fullLayout;
    var allThisTraceLabels = {};
    var vTotal = 0;
    var hiddenLabels = fullLayout.hiddenlabels || [];

    var i, v, label, hidden, pt;

    if(trace.dlabel) {
        labels = new Array(vals.length);
        for(i = 0; i < vals.length; i++) {
            labels[i] = String(trace.label0 + i * trace.dlabel);
        }
    }

    var pullColor = makePullColorFn(fullLayout._piecolormap);
    var seriesLen = (hasVals ? vals : labels).length;

    for(i = 0; i < seriesLen; i++) {
        if(hasVals) {
            v = vals[i];
            if(!isNumeric(v)) continue;
            v = +v;
            if(v < 0) continue;
        }
        else v = 1;

        label = labels[i];
        if(label === undefined || label === '') label = i;
        label = String(label);

        var thisLabelIndex = allThisTraceLabels[label];
        if(thisLabelIndex === undefined) {
            allThisTraceLabels[label] = cd.length;

            hidden = hiddenLabels.indexOf(label) !== -1;

            if(!hidden) vTotal += v;

            cd.push({
                v: v,
                label: label,
                color: pullColor(colors[i], label),
                i: i,
                pts: [i],
                hidden: hidden
            });
        }
        else {
            pt = cd[thisLabelIndex];
            pt.v += v;
            pt.pts.push(i);
            if(!pt.hidden) vTotal += v;

            if(pt.color === false && colors[i]) {
                pt.color = pullColor(colors[i], label);
            }
        }
    }

    if(trace.sort) cd.sort(function(a, b) { return b.v - a.v; });

    // include the sum of all values in the first point
    if(cd[0]) cd[0].vTotal = vTotal;

    // now insert text
    if(trace.textinfo && trace.textinfo !== 'none') {
        var hasLabel = trace.textinfo.indexOf('label') !== -1;
        var hasText = trace.textinfo.indexOf('text') !== -1;
        var hasValue = trace.textinfo.indexOf('value') !== -1;
        var hasPercent = trace.textinfo.indexOf('percent') !== -1;
        var separators = fullLayout.separators;

        var thisText;

        for(i = 0; i < cd.length; i++) {
            pt = cd[i];
            thisText = hasLabel ? [pt.label] : [];
            if(hasText) {
                var texti = helpers.getFirstFilled(trace.text, pt.pts);
                if(texti) thisText.push(texti);
            }
            if(hasValue) thisText.push(helpers.formatPieValue(pt.v, separators));
            if(hasPercent) thisText.push(helpers.formatPiePercent(pt.v / vTotal, separators));
            pt.text = thisText.join('
');
        }
    }

    return cd;
}

function makePullColorFn(colorMap) {
    return function pullColor(color, id) {
        if(!color) return false;

        color = tinycolor(color);
        if(!color.isValid()) return false;

        color = Color.addOpacity(color, color.getAlpha());
        if(!colorMap[id]) colorMap[id] = color;

        return color;
    };
}

/*
 * `calc` filled in (and collated) explicit colors.
 * Now we need to propagate these explicit colors to other traces,
 * and fill in default colors.
 * This is done after sorting, so we pick defaults
 * in the order slices will be displayed
 */
function crossTraceCalc(gd) {
    var fullLayout = gd._fullLayout;
    var calcdata = gd.calcdata;
    var pieColorWay = fullLayout.piecolorway;
    var colorMap = fullLayout._piecolormap;

    if(fullLayout.extendpiecolors) {
        pieColorWay = generateExtendedColors(pieColorWay, pieExtendedColorWays);
    }
    var dfltColorCount = 0;

    for(var i = 0; i < calcdata.length; i++) {
        var cd = calcdata[i];
        if(cd[0].trace.type !== 'pie') continue;

        for(var j = 0; j < cd.length; j++) {
            var pt = cd[j];
            if(pt.color === false) {
                // have we seen this label and assigned a color to it in a previous trace?
                if(colorMap[pt.label]) {
                    pt.color = colorMap[pt.label];
                } else {
                    colorMap[pt.label] = pt.color = pieColorWay[dfltColorCount % pieColorWay.length];
                    dfltColorCount++;
                }
            }
        }
    }
}

/**
 * pick a default color from the main default set, augmented by
 * itself lighter then darker before repeating
 */
function generateExtendedColors(colorList, extendedColorWays) {
    var i;
    var colorString = JSON.stringify(colorList);
    var pieColors = extendedColorWays[colorString];
    if(!pieColors) {
        pieColors = colorList.slice();

        for(i = 0; i < colorList.length; i++) {
            pieColors.push(tinycolor(colorList[i]).lighten(20).toHexString());
        }

        for(i = 0; i < colorList.length; i++) {
            pieColors.push(tinycolor(colorList[i]).darken(20).toHexString());
        }
        extendedColorWays[colorString] = pieColors;
    }

    return pieColors;
}

module.exports = {
    calc: calc,
    crossTraceCalc: crossTraceCalc,

    makePullColorFn: makePullColorFn,
    generateExtendedColors: generateExtendedColors
};
<|endoftext|>


<commit_before>function huckleberryFinnText() {
	var s = "You don't know about me, without you have read a book by the name of The Adventures of Tom Sawyer, but that ain't no matter. That book was made by Mr. Mark Twain, and he told the truth, mainly. There was things which he stretched, but mainly he told the truth. That is nothing. I never seen anybody but lied, one time or another, without it was Aunt Polly, or the widow, or maybe Mary. Aunt Polly- Tom's Aunt Polly, she is- and Mary, and the Widow Douglas, is all told about in that book- which is mostly a true book; with some stretchers, as I said before. Now the way that the book winds up, is this: Tom and me found the money that the robbers hid in the cave, and it made us rich. We got six thousand dollars apiece- all gold. It was an awful sight ofmoney when it was piled up. Well, Judge Thatcher, he took it and put it out at interest, and it fetched us a dollar a day apiece, all the year round- more than a body could tell what to do with. The Widow Douglas, she took me for her son, and allowed she would sivilize me; but it was rough living in the house all the time, considering how dismal regular and decent the widow was in all her ways; and so when I couldn't stand it no longer, I lit out. I got into my old rags, and my sugar-hogshead again, and was free and satisfied. But Tom Sawyer, he hunted me up and said he was going to start a band of robbers and I might join if I would go back to the widow and be respectable."

	var textArr = s.split(" ");
	return textArr;
}

function settingUp(text){
	var nBucks = 157;
	var table = new newHtable(nBucks);
	table = insertFile(text, table);
	return table;
}

function goBabble(){
	document.getElementById("toBabble").innerHTML = "Parsing the text...";
	var huck = huckleberryFinnText();
	document.getElementById("toBabble").innerHTML = "Huck was broken down";
	var t = settingUp(huck);
	document.getElementById("toBabble").innerHTML = "Babbling...";
	//var bab = babble(5, 5, t);
	//document.getElementById("toBabble").innerHTML = "Babble Worked. Printing..."
	/*var text = bab.join("\n");
	document.getElementById("toBabble").innerHTML = text;
	return;*/
}<commit_msg>peculiar that nothing prints when babble is uncommented<commit_after>function huckleberryFinnText() {
	var s = "You don't know about me, without you have read a book by the name of The Adventures of Tom Sawyer, but that ain't no matter. That book was made by Mr. Mark Twain, and he told the truth, mainly. There was things which he stretched, but mainly he told the truth. That is nothing. I never seen anybody but lied, one time or another, without it was Aunt Polly, or the widow, or maybe Mary. Aunt Polly- Tom's Aunt Polly, she is- and Mary, and the Widow Douglas, is all told about in that book- which is mostly a true book; with some stretchers, as I said before. Now the way that the book winds up, is this: Tom and me found the money that the robbers hid in the cave, and it made us rich. We got six thousand dollars apiece- all gold. It was an awful sight ofmoney when it was piled up. Well, Judge Thatcher, he took it and put it out at interest, and it fetched us a dollar a day apiece, all the year round- more than a body could tell what to do with. The Widow Douglas, she took me for her son, and allowed she would sivilize me; but it was rough living in the house all the time, considering how dismal regular and decent the widow was in all her ways; and so when I couldn't stand it no longer, I lit out. I got into my old rags, and my sugar-hogshead again, and was free and satisfied. But Tom Sawyer, he hunted me up and said he was going to start a band of robbers and I might join if I would go back to the widow and be respectable."

	var textArr = s.split(" ");
	return textArr;
}

function settingUp(text){
	var nBucks = 157;
	var table = new newHtable(nBucks);
	table = insertFile(text, table);
	return table;
}

function goBabble(){
	document.getElementById("toBabble").innerHTML = "Parsing the text...";
	var huck = huckleberryFinnText();
	document.getElementById("toBabble").innerHTML = "Huck was broken down";
	var t = settingUp(huck);
	document.getElementById("toBabble").innerHTML = "Babbling...";
	var sentpar = 5;
	var bab = babble(sentpar, sentpar, t);
	//document.getElementById("toBabble").innerHTML = "Babble Worked. Printing..."
	/*var text = bab.join("\n");
	document.getElementById("toBabble").innerHTML = text;
	return;*/
}<|endoftext|>