<commit_before>define([
	"dojo/_base/kernel",
	"dojo/_base/declare",
	"dojo/_base/lang",
	"dojo/on",
	"dojo/query",
	"dojo/dom-style",
	"dojo/_base/fx",
	"dijit/_WidgetBase",
	"dojo/fx/easing"

], function(kernel, declare, lang, on, query, domStyle, fx, _WidgetBase, easing){

	lang.getObject("widget", true, dojox);
	kernel.experimental("dojox/widget/FisheyeLite");

	return dojo.declare("dojox.widget.FisheyeLite", [_WidgetBase], {
		// summary:
		//		A Light-weight Fisheye Component, or an exhanced version
		//		of dojo/fx/Toggler ...
		// description:
		//		A Simple FisheyeList-like widget which (in the interest of
		//		performance) relies on well-styled content for positioning,
		//		and natural page layout for rendering.
		//
		//		use position:absolute/relative nodes to prevent layout
		//		changes, and use caution when seleting properties to
		//		scale. Negative scaling works, but some properties
		//		react poorly to being set to negative values, IE being
		//		particularly annoying in that regard.
		//
		//		quirk: uses the domNode as the target of the animation
		//		unless it finds a node class="fisheyeTarget" in the container
		//		being turned into a FisheyeLite instance
		//
		// example:
		//	|	// make all the LI's in a node Fisheye's:
		//	|	require(["dojo/query", "dojox/widget/FisheyeLite"],
		//	|		function(query, FisheyeLite){
		//	|   	query("#node li").forEach(function(n){
		// 	|			new FisheyeLite({},n);
		//	|		});
		//	|	});
		//
		//
		// example:
		//	|	require(["dojox/widget/FisheyeLite"], function(FisheyeLite){
		//	|		new FisheyeLite({
		//	|			properties:{
		//	|				// height is literal, width is multiplied
		//	|				height:{ end: 200 }, width:2.3
		//	|			}
		//	|		}, "someNode");
		//	|	});

		// durationIn: Integer
		//		The time (in ms) the run the show animation
		durationIn: 350,

		// easeIn: Function
		//		An easing function to use for the show animation
		easeIn: easing.backOut,

		// durationOut: Integer
		//		The Time (in ms) to run the hide animation
		durationOut: 1420,

		// easeOut: Function
		//		An easing function to use for the hide animation
		easeOut: easing.elasticOut,

		// properties: Object
		//		An object of "property":scale pairs, or "property":{} pairs.
		//		defaults to font-size with a scale of 2.75
		//		If a named property is an integer or float, the "scale multiplier"
		//		is used. If the named property is an object, that object is mixed
		//		into the animation directly. eg: height:{ end:20, units:"em" }
		properties: null,

		// units: String
		//		Sometimes, you need to specify a unit. Should be part of
		//		properties attrib, but was trying to shorthand the logic there
		units:"px",

		constructor: function(props, node){
			this.properties = props.properties || {
				fontSize: 2.75
			}
		},

		postCreate: function(){

			this.inherited(arguments);
			this._target = query(".fisheyeTarget", this.domNode)[0] || this.domNode;
			this._makeAnims();

			this.connect(this.domNode, "onmouseover", "show");
			this.connect(this.domNode, "onmouseout", "hide");
			this.connect(this._target, "onclick", "onClick");

		},

		show: function(){
			// summary:
			//		Show this Fisheye item.
			this._runningOut.stop();
			this._runningIn.play();
		},

		hide: function(){
			// summary:
			//		Hide this fisheye item on mouse leave
			this._runningIn.stop();
			this._runningOut.play();
		},

		_makeAnims: function(){
			// summary:
			//		Pre-generate the animations

			// create two properties: objects, one for each "state"
			var _in = {}, _out = {}, cs = domStyle.getComputedStyle(this._target);
			for(var p in this.properties){
				var prop = this.properties[p],
					deep = lang.isObject(prop),
					v = parseInt(cs[p])
				;
				// note: do not set negative scale for [a list of properties] for IE support
				// note: filter:'s are your own issue, too ;)
				// FIXME: this.units here is bad, likely. d._toPixelValue ?
				_out[p] = { end: v, units:this.units };
				_in[p] = deep ? prop : { end: prop * v, units:this.units };
			}

			this._runningIn = fx.animateProperty({
				node: this._target,
				easing: this.easeIn,
				duration: this.durationIn,
				properties: _in
			});

			this._runningOut = fx.animateProperty({
				node: this._target,
				duration: this.durationOut,
				easing: this.easeOut,
				properties: _out
			});

			this.connect(this._runningIn, "onEnd", lang.hitch(this, "onSelected", this));
		},

		onClick: function(/* Event */e){
			// summary:
			//		stub function fired when target is clicked
			//		connect or override to use.
		},

		onSelected: function(/* Object */e){
			// summary:
			//		stub function fired when Fisheye Item is fully visible and
			//		hovered. connect or override use.
		}

	});

});
<commit_msg>fixes #15378, make opacity setting work correctly on dojox/widget/FisheyeLite by parsing as a float rather than as an int<commit_after>define([
	"dojo/_base/kernel",
	"dojo/_base/declare",
	"dojo/_base/lang",
	"dojo/on",
	"dojo/query",
	"dojo/dom-style",
	"dojo/_base/fx",
	"dijit/_WidgetBase",
	"dojo/fx/easing"

], function(kernel, declare, lang, on, query, domStyle, fx, _WidgetBase, easing){

	lang.getObject("widget", true, dojox);
	kernel.experimental("dojox/widget/FisheyeLite");

	return dojo.declare("dojox.widget.FisheyeLite", [_WidgetBase], {
		// summary:
		//		A Light-weight Fisheye Component, or an exhanced version
		//		of dojo/fx/Toggler ...
		// description:
		//		A Simple FisheyeList-like widget which (in the interest of
		//		performance) relies on well-styled content for positioning,
		//		and natural page layout for rendering.
		//
		//		use position:absolute/relative nodes to prevent layout
		//		changes, and use caution when seleting properties to
		//		scale. Negative scaling works, but some properties
		//		react poorly to being set to negative values, IE being
		//		particularly annoying in that regard.
		//
		//		quirk: uses the domNode as the target of the animation
		//		unless it finds a node class="fisheyeTarget" in the container
		//		being turned into a FisheyeLite instance
		//
		// example:
		//	|	// make all the LI's in a node Fisheye's:
		//	|	require(["dojo/query", "dojox/widget/FisheyeLite"],
		//	|		function(query, FisheyeLite){
		//	|   	query("#node li").forEach(function(n){
		// 	|			new FisheyeLite({},n);
		//	|		});
		//	|	});
		//
		//
		// example:
		//	|	require(["dojox/widget/FisheyeLite"], function(FisheyeLite){
		//	|		new FisheyeLite({
		//	|			properties:{
		//	|				// height is literal, width is multiplied
		//	|				height:{ end: 200 }, width:2.3
		//	|			}
		//	|		}, "someNode");
		//	|	});

		// durationIn: Integer
		//		The time (in ms) the run the show animation
		durationIn: 350,

		// easeIn: Function
		//		An easing function to use for the show animation
		easeIn: easing.backOut,

		// durationOut: Integer
		//		The Time (in ms) to run the hide animation
		durationOut: 1420,

		// easeOut: Function
		//		An easing function to use for the hide animation
		easeOut: easing.elasticOut,

		// properties: Object
		//		An object of "property":scale pairs, or "property":{} pairs.
		//		defaults to font-size with a scale of 2.75
		//		If a named property is an integer or float, the "scale multiplier"
		//		is used. If the named property is an object, that object is mixed
		//		into the animation directly. eg: height:{ end:20, units:"em" }
		properties: null,

		// units: String
		//		Sometimes, you need to specify a unit. Should be part of
		//		properties attrib, but was trying to shorthand the logic there
		units:"px",

		constructor: function(props, node){
			this.properties = props.properties || {
				fontSize: 2.75
			}
		},

		postCreate: function(){

			this.inherited(arguments);
			this._target = query(".fisheyeTarget", this.domNode)[0] || this.domNode;
			this._makeAnims();

			this.connect(this.domNode, "onmouseover", "show");
			this.connect(this.domNode, "onmouseout", "hide");
			this.connect(this._target, "onclick", "onClick");

		},

		show: function(){
			// summary:
			//		Show this Fisheye item.
			this._runningOut.stop();
			this._runningIn.play();
		},

		hide: function(){
			// summary:
			//		Hide this fisheye item on mouse leave
			this._runningIn.stop();
			this._runningOut.play();
		},

		_makeAnims: function(){
			// summary:
			//		Pre-generate the animations

			// create two properties: objects, one for each "state"
			var _in = {}, _out = {}, cs = domStyle.getComputedStyle(this._target);
			for(var p in this.properties){
				var prop = this.properties[p],
					deep = lang.isObject(prop),
					v = parseFloat(cs[p])
				;
				// note: do not set negative scale for [a list of properties] for IE support
				// note: filter:'s are your own issue, too ;)
				// FIXME: this.units here is bad, likely. d._toPixelValue ?
				_out[p] = { end: v, units:this.units };
				_in[p] = deep ? prop : { end: prop * v, units:this.units };
			}

			this._runningIn = fx.animateProperty({
				node: this._target,
				easing: this.easeIn,
				duration: this.durationIn,
				properties: _in
			});

			this._runningOut = fx.animateProperty({
				node: this._target,
				duration: this.durationOut,
				easing: this.easeOut,
				properties: _out
			});

			this.connect(this._runningIn, "onEnd", lang.hitch(this, "onSelected", this));
		},

		onClick: function(/* Event */e){
			// summary:
			//		stub function fired when target is clicked
			//		connect or override to use.
		},

		onSelected: function(/* Object */e){
			// summary:
			//		stub function fired when Fisheye Item is fully visible and
			//		hovered. connect or override use.
		}

	});

});
<|endoftext|>


<commit_before>var Path = require('path');
var Webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    context: Path.resolve(__dirname, './src'),
    entry: './banner/banner.jsx',
    output: {
        path: Path.resolve(__dirname, './dist'),
        filename: 'library.bundle.js',
        library: 'Banner',
        libraryTarget: 'umd'
    },

    resolve: {
        extensions: [ '', '.js', '.jsx', '.css' ]
    },

    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                loaders: [
                    'babel-loader',
                    'eslint-loader'
                ],
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                loader: ExtractTextPlugin.extract(
                    'style-loader',
                    'css-loader'
                )
            },
            {
                test: /\.svg$/,
                loaders: [
                    'file-loader'
                ]
            }
        ]
    },

    plugins: [
        new ExtractTextPlugin('style.css'),
        new Webpack.optimize.UglifyJsPlugin({
            comments: false
        })
    ],

    externals: {
        react: {
            root: "React",
            commonjs2: "react",
            commonjs: "react",
            amd: "react"
        },
        'react-dom': {
            root: "ReactDOM",
            commonjs2: "react-dom",
            commonjs: "react-dom",
            amd: "react-dom"
        }
    },

    eslint: {
        fix: true,
        configFile: Path.resolve(__dirname, './.eslintrc')
    },

    stats: {
        children: false
    }
}
<commit_msg>Minor organization in library config<commit_after>var Path = require('path');
var Webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    context: Path.resolve(__dirname, './src'),
    entry: './banner/banner.jsx',

    resolve: {
        extensions: [ '', '.js', '.jsx', '.css' ]
    },

    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                loaders: [
                    'babel-loader',
                    'eslint-loader'
                ],
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                loader: ExtractTextPlugin.extract(
                    'style-loader',
                    'css-loader'
                )
            },
            {
                test: /\.svg$/,
                loaders: [
                    'file-loader'
                ]
            }
        ]
    },

    eslint: {
        fix: true,
        configFile: Path.resolve(__dirname, './.eslintrc')
    },

    plugins: [
        new ExtractTextPlugin('style.css'),
        new Webpack.optimize.UglifyJsPlugin({
            comments: false
        })
    ],

    externals: {
        react: {
            root: "React",
            commonjs2: "react",
            commonjs: "react",
            amd: "react"
        },
        'react-dom': {
            root: "ReactDOM",
            commonjs2: "react-dom",
            commonjs: "react-dom",
            amd: "react-dom"
        }
    },

    output: {
        path: Path.resolve(__dirname, './dist'),
        filename: 'library.bundle.js',
        library: 'Banner',
        libraryTarget: 'umd'
    },

    stats: {
        children: false
    }
}
<|endoftext|>


<commit_before>'use strict'

let express = require('express');
let multer  = require('multer');
let router = express.Router();
let upload = multer();

var lastMove = {
  dir: "stop",
  speed: 0
}

var resetAt = Date()
let resetAfterSec = 5;

router.get('/move', (req, res) => {
  let dir = req.query.dir
  let speed = req.query.speed
  res.send('You moved ' + speed + ' meters ' + dir);
  lastMove = {
    dir: dir,
    speed: speed
  }
  resetAt = new Date((new Date()).getTime() + resetAfterSec * 1000);

  // Autoreset
  setTimeout(() => {
    if ((new Date()).getTime() > resetAt.getTime()) {
      lastMove = {
        dir: "stop",
        speed: 0
      }
    }
  }, resetAfterSec * 1000 + 200);
});

router.get('/getmove', (req, res) => {
  res.json(lastMove);
})

var imgbuffer = new Buffer([]);

router.post('/img', upload.single('file'), (req,res) => {
  imgbuffer = req.file.buffer;
  res.send('1');
})

router.get('/img', (req, res) => {
  res.type('jpeg');
  res.set('Cache-Control', 'no-store');
  res.send(imgbuffer);
})

module.exports = router
<commit_msg>api changes<commit_after>'use strict'

let express = require('express');
let multer  = require('multer');
let router = express.Router();
let upload = multer();

var lastMove = {
  // direction vector { [0,360), [0,1] }
  dir: [0,0],
  vertical: 0
}

var resetAt = Date()
let resetAfterSec = 5;

router.get('/move', (req, res) => {
  let dir = req.query.dir
  let vertical = req.query.vertical
  res.send('You moved ' + speed + ' meters ' + dir);
  lastMove = {
    dir: dir,
    vertical: vertical
  }
  resetAt = new Date((new Date()).getTime() + resetAfterSec * 1000);

  // Autoreset
  setTimeout(() => {
    if ((new Date()).getTime() > resetAt.getTime()) {
      lastMove = {
        dir: [0,0],
        vertical: 0
      }
    }
  }, resetAfterSec * 1000 + 200);
});

router.get('/getmove', (req, res) => {
  res.json(lastMove);
})

var imgbuffer = new Buffer([]);

router.post('/img', upload.single('file'), (req,res) => {
  imgbuffer = req.file.buffer;
  res.send('1');
})

router.get('/img', (req, res) => {
  res.type('jpeg');
  res.set('Cache-Control', 'no-store');
  res.send(imgbuffer);
})

module.exports = router
<|endoftext|>


<commit_before>// dna.js Website
// MIT/GPLv3 ~~ dnajs.org/license.html
// Copyright (c) 2013-2016 individual contributors

var app = {};

app.bookstore = {
   books: [
      { title: 'Go JavaScript', author: 'Jake' },
      { title: 'Styling CSS3',  author: 'Abby' },
      { title: 'Howdy HTML5',   author: 'Ed' }
      ],
   clear: function() {
      dna.empty('book', { fade: true });
      },
   feelLucky: function() {
      var lucky = Math.floor(Math.random() * app.bookstore.books.length);
      dna.clone('book', app.bookstore.books[lucky], { fade: true });
      },
   setup: function() {
      dna.clone('book', { title: 'The DOM', author: 'Jan' });
      }
   };

app.nav = {
   setup: function() {
      var current = $('header nav a')
         .filter('[href="' + window.location.pathname.split('/').pop() + '"]')
         .closest('li');
      if (!current.length)
         current = $('header nav li').first();
      current.addClass('current');
      }
   };

app.documenation = {
   setup: function() {
      function addOutlineNumber(elemIndex) {
         var letter = String.fromCharCode('A'.charCodeAt() + elemIndex);
         $(this).text(letter + '. ' + $(this).text());
         }
      if (window.location.pathname.indexOf('manual.html') !== -1)
         $('h3').each(addOutlineNumber);
      }
   };

app.start = {
   go: function() {
      app.nav.setup();
      app.documenation.setup();
      }
   };

$(app.start.go);
<commit_msg>Explicit declaration off window object<commit_after>// dna.js Website
// MIT/GPLv3 ~~ dnajs.org/license.html
// Copyright (c) 2013-2016 individual contributors

window.app = {};

app.bookstore = {
   books: [
      { title: 'Go JavaScript', author: 'Jake' },
      { title: 'Styling CSS3',  author: 'Abby' },
      { title: 'Howdy HTML5',   author: 'Ed' }
      ],
   clear: function() {
      dna.empty('book', { fade: true });
      },
   feelLucky: function() {
      var lucky = Math.floor(Math.random() * app.bookstore.books.length);
      dna.clone('book', app.bookstore.books[lucky], { fade: true });
      },
   setup: function() {
      dna.clone('book', { title: 'The DOM', author: 'Jan' });
      }
   };

app.nav = {
   setup: function() {
      var current = $('header nav a')
         .filter('[href="' + window.location.pathname.split('/').pop() + '"]')
         .closest('li');
      if (!current.length)
         current = $('header nav li').first();
      current.addClass('current');
      }
   };

app.documenation = {
   setup: function() {
      function addOutlineNumber(elemIndex) {
         var letter = String.fromCharCode('A'.charCodeAt() + elemIndex);
         $(this).text(letter + '. ' + $(this).text());
         }
      if (window.location.pathname.indexOf('manual.html') !== -1)
         $('h3').each(addOutlineNumber);
      }
   };

app.start = {
   go: function() {
      app.nav.setup();
      app.documenation.setup();
      }
   };

$(app.start.go);
<|endoftext|>


<commit_before>var d3 = require('d3'),
    Tuple = require('vega-dataflow').Tuple,
    log = require('vega-logging'),
    Transform = require('./Transform');

function Force(graph) {
  Transform.prototype.init.call(this, graph);
  Transform.addParameters(this, {
    size: {type: 'array<value>', default: [500, 500]},
    links: {type: 'data'},
    linkDistance: {type: 'field|value', default: 20},
    linkStrength: {type: 'field|value', default: 1},
    charge: {type: 'field|value', default: -30},
    chargeDistance: {type: 'field|value', default: Infinity},
    iterations: {type: 'value', default: 500},
    friction: {type: 'value', default: 0.9},
    theta: {type: 'value', default: 0.8},
    gravity: {type: 'value', default: 0.1},
    alpha: {type: 'value', default: 0.1}
  });

  this._nodes  = [];
  this._links = [];
  this._layout = d3.layout.force();

  this._output = {
    'x': 'layout_x',
    'y': 'layout_y',
    'px': 'layout_px',
    'py': 'layout_py',
    'fixed': 'layout_fixed',
    'weight': 'layout_weight',
    'source': '_source',
    'target': '_target'
  };

  return this.mutates(true);
}

var prototype = (Force.prototype = Object.create(Transform.prototype));
prototype.constructor = Force;

prototype.transform = function(nodeInput) {
  log.debug(nodeInput, ['force']);

  // get variables
  var linkInput = this.param('links').source.last(),
      layout = this._layout,
      output = this._output,
      nodes = this._nodes,
      links = this._links,
      iter = this.param('iterations');

  // process added nodes
  nodeInput.add.forEach(function(n) {
    nodes.push({tuple: n});
  });

  // process added edges
  linkInput.add.forEach(function(l) {
    var link = {
      tuple: l,
      source: nodes[l.source],
      target: nodes[l.target]
    };
    Tuple.set(l, output.source, link.source.tuple);
    Tuple.set(l, output.target, link.target.tuple);
    links.push(link);
  });

  // TODO process 'mod' of edge source or target?

  // configure layout
  layout
    .size(this.param('size'))
    .linkDistance(this.param('linkDistance'))
    .linkStrength(this.param('linkStrength'))
    .charge(this.param('charge'))
    .chargeDistance(this.param('chargeDistance'))
    .friction(this.param('friction'))
    .theta(this.param('theta'))
    .gravity(this.param('gravity'))
    .alpha(this.param('alpha'))
    .nodes(nodes)
    .links(links);

  // run layout
  layout.start();
  for (var i=0; i<iter; ++i) {
    layout.tick();
  }
  layout.stop();

  // copy layout values to nodes
  nodes.forEach(function(n) {
    Tuple.set(n.tuple, output.x, n.x);
    Tuple.set(n.tuple, output.y, n.y);
    Tuple.set(n.tuple, output.px, n.px);
    Tuple.set(n.tuple, output.py, n.py);
    Tuple.set(n.tuple, output.fixed, n.fixed);
    Tuple.set(n.tuple, output.weight, n.weight);
  });

  // process removed nodes
  if (nodeInput.rem.length > 0) {
    this._nodes = Tuple.idFilter(nodes, nodeInput.rem);
  }

  // process removed edges
  if (linkInput.rem.length > 0) {
    this.links = Tuple.idFilter(links, linkInput.rem);
  }

  // return changeset
  nodeInput.fields[output.x] = 1;
  nodeInput.fields[output.y] = 1;
  return nodeInput;
};

module.exports = Force;

Force.schema = {
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Force transform",
  "description": "Performs force-directed layout for network data.",
  "type": "object",
  "properties": {
    "type": {"enum": ["force"]},
    "size": {
      "description": "The dimensions [width, height] of this force layout.",
      "oneOf": [
        {
          "type": "array",
          "minItems": 2,
          "maxItems": 2,
          "items": {"oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}]}
        },
        {"$ref": "#/refs/signal"}
      ],

      "default": [500, 500]
    },
    "links": {
      "type": "string",
      "description": "The name of the link (edge) data set."
    },
    "linkDistance": {
      "description": "Determines the length of edges, in pixels.",
      "oneOf": [{"type": "number"}, {"type": "string"}, {"$ref": "#/refs/signal"}],
      "default": 20
    },
    "linkStrength": {
      "oneOf": [{"type": "number"}, {"type": "string"}, {"$ref": "#/refs/signal"}],
      "description": "Determines the tension of edges (the spring constant).",
      "default": 1
    },
    "charge": {
      "oneOf": [{"type": "number"}, {"type": "string"}, {"$ref": "#/refs/signal"}],
      "description": "The strength of the charge each node exerts.",
      "default": -30
    },
    "chargeDistance": {
      "oneOf": [{"type": "number"}, {"type": "string"}, {"$ref": "#/refs/signal"}],
      "description": "The maximum distance over which charge forces are applied.",
      "default": Infinity
    },
    "iterations": {
      "description": "The number of iterations to run the force directed layout.",
      "oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}],
      "default": 500
    },
    "friction": {
      "description": "The strength of the friction force used to stabilize the layout.",
      "oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}],
      "default": 0.9
    },
    "theta": {
      "description": "The theta parameter for the Barnes-Hut algorithm, which is used to compute charge forces between nodes.",
      "oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}],
      "default": 0.8
    },
    "gravity": {
      "description": "The strength of the pseudo-gravity force that pulls nodes towards the center of the layout area.",
      "oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}],
      "default": 0.1
    },
    "alpha": {
      "description": "A \"temperature\" parameter that determines how much node positions are adjusted at each step.",
      "oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}],
      "default": 0.1
    },
    "output": {
      "type": "object",
      "description": "Rename the output data fields",
      "properties": {
        "x": {"type": "string", "default": "layout_x"},
        "y": {"type": "string", "default": "layout_y"},
        "source": {"type": "string", "default": "_source"},
        "target": {"type": "string", "default": "_target"}
      },
      "additionalProperties": false
    }
  },
  "additionalProperties": false,
  "required": ["type", "links"]
};<commit_msg>Add interactivity to force layout.<commit_after>var d3 = require('d3'),
    Tuple = require('vega-dataflow').Tuple,
    ChangeSet = require('vega-dataflow/src/ChangeSet'),
    Tuple = require('vega-dataflow/src/Tuple'),
    log = require('vega-logging'),
    Transform = require('./Transform');

function Force(graph) {
  Transform.prototype.init.call(this, graph);

  this._prev = null;
  this._setup = true;
  this._nodes  = [];
  this._links = [];
  this._layout = d3.layout.force();

  Transform.addParameters(this, {
    size: {type: 'array<value>', default: [500, 500]},
    bound: {type: 'value', default: true},

    links: {type: 'data'},
    linkStrength: {type: 'field|value', default: 1},
    linkDistance: {type: 'field|value', default: 20},
    charge: {type: 'field|value', default: -30},
    chargeDistance: {type: 'field|value', default: Infinity},
    friction: {type: 'value', default: 0.9},
    theta: {type: 'value', default: 0.8},
    gravity: {type: 'value', default: 0.1},
    alpha: {type: 'value', default: 0.1},
    iterations: {type: 'value', default: 500},

    interactive: {type: 'value', default: false},
    active: {type: 'value', default: this._prev},
    fixed: {type: 'data'}
  });

  this._output = {
    'x': 'layout_x',
    'y': 'layout_y',
    'px': 'layout_px',
    'py': 'layout_py',
    'fixed': 'layout_fixed',
    'weight': 'layout_weight',
    'source': '_source',
    'target': '_target'
  };

  return this.mutates(true);
}

var prototype = (Force.prototype = Object.create(Transform.prototype));
prototype.constructor = Force;

prototype.transform = function(nodeInput) {
  log.debug(nodeInput, ['force']);

  // get variables
  var interactive = this.param('interactive'),
      linkInput = this.param('links').source.last(),
      active = this.param('active'),
      output = this._output,
      layout = this._layout,
      nodes = this._nodes,
      links = this._links;

  // configure nodes, links and layout
  // TODO what if interactive or charge/linkDistance/linkStrength has changed?
  if (this._setup || nodeInput.add.length || linkInput.add.length) {
    this.configure(nodeInput, linkInput, interactive);
    this._setup = false;
  }

  // run batch layout
  if (!interactive) {
    var iterations = this.param('iterations');
    for (var i=0; i<iterations; ++i) layout.tick();
    layout.stop();
  }

  // update node positions
  this.update(active);

  // update active node status
  if (active !== this._prev) {
    if (active && active.update) {
      layout.alpha(this.param('alpha')); // re-start layout
    }
    this._prev = active;
  }

  // process removed nodes or edges
  if (nodeInput.rem.length) {
    layout.nodes(this._nodes = Tuple.idFilter(nodes, nodeInput.rem));
  }
  if (linkInput.rem.length) {
    layout.links(this._links = Tuple.idFilter(links, linkInput.rem));
  }

  // return changeset
  nodeInput.fields[output.x] = 1;
  nodeInput.fields[output.y] = 1;
  return nodeInput;
};

prototype.configure = function(nodeInput, linkInput, interactive) {
  var force = this,
      graph = this._graph,
      output = this._output,
      layout = this._layout,
      nodes = this._nodes,
      links = this._links,
      a, i, x, link;

  // process added nodes
  for (a=nodeInput.add, i=0; i<a.length; ++i) {
    nodes.push({tuple: a[i]});
  }

  // process added edges
  for (a=linkInput.add, i=0; i<a.length; ++i) {
    x = a[i];
    link = {
      tuple:  x,
      source: nodes[x.source],
      target: nodes[x.target]
    };
    Tuple.set(x, output.source, link.source.tuple);
    Tuple.set(x, output.target, link.target.tuple);
    links.push(link);
  }

  // TODO process 'mod' of edge source or target?

  // setup handler for force layout tick events
  var tickHandler = !interactive ? null : function() {
    // re-schedule the transform, force reflow
    graph.propagate(ChangeSet.create(null, true), force);

    // hard-code propagation to links
    // TODO: dataflow graph should propagate automatically
    var lnode = force.param('links').source._pipeline[0];
    graph.propagate(ChangeSet.create(null, true), lnode);
  };

  // configure layout
  layout
    .size(this.param('size'))
    .linkStrength(this.param('linkStrength'))
    .linkDistance(this.param('linkDistance'))
    .chargeDistance(this.param('chargeDistance'))
    .charge(this.param('charge'))
    .theta(this.param('theta'))
    .gravity(this.param('gravity'))
    .friction(this.param('friction'))
    .nodes(nodes)
    .links(links)
    .on('tick', tickHandler)
    .start().alpha(this.param('alpha'));
};

prototype.update = function(active) {
  var output = this._output,
      bound = this.param('bound'),
      fixed = this.param('fixed'),
      size = this.param('size'),
      nodes = this._nodes,
      lut = {}, id, i, n, t, x, y;

  if (fixed) {
    fixed = fixed.source.values();
    for (i=0, n=fixed.length; i<n; ++i) {
      lut[fixed[i].id] = 1;
    }
  }

  for (i=0; i<nodes.length; ++i) {
    n = nodes[i];
    t = n.tuple;
    id = t._id;

    if (active && active.id === id) {
      n.fixed = 1;
      if (active.update) {
        n.x = n.px = active.x;
        n.y = n.py = active.y;
      }
    } else {
      n.fixed = lut[id] || 0;
    }

    x = bound ? Math.max(0, Math.min(n.x, size[0])) : n.x;
    y = bound ? Math.max(0, Math.min(n.y, size[1])) : n.y;
    Tuple.set(t, output.x, x);
    Tuple.set(t, output.y, y);
  }
};

module.exports = Force;

Force.schema = {
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Force transform",
  "description": "Performs force-directed layout for network data.",
  "type": "object",
  "properties": {
    "type": {"enum": ["force"]},
    "size": {
      "description": "The dimensions [width, height] of this force layout.",
      "oneOf": [
        {
          "type": "array",
          "minItems": 2,
          "maxItems": 2,
          "items": {"oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}]}
        },
        {"$ref": "#/refs/signal"}
      ],

      "default": [500, 500]
    },
    "links": {
      "type": "string",
      "description": "The name of the link (edge) data set."
    },
    "linkDistance": {
      "description": "Determines the length of edges, in pixels.",
      "oneOf": [{"type": "number"}, {"type": "string"}, {"$ref": "#/refs/signal"}],
      "default": 20
    },
    "linkStrength": {
      "oneOf": [{"type": "number"}, {"type": "string"}, {"$ref": "#/refs/signal"}],
      "description": "Determines the tension of edges (the spring constant).",
      "default": 1
    },
    "charge": {
      "oneOf": [{"type": "number"}, {"type": "string"}, {"$ref": "#/refs/signal"}],
      "description": "The strength of the charge each node exerts.",
      "default": -30
    },
    "chargeDistance": {
      "oneOf": [{"type": "number"}, {"type": "string"}, {"$ref": "#/refs/signal"}],
      "description": "The maximum distance over which charge forces are applied.",
      "default": Infinity
    },
    "iterations": {
      "description": "The number of iterations to run the force directed layout.",
      "oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}],
      "default": 500
    },
    "friction": {
      "description": "The strength of the friction force used to stabilize the layout.",
      "oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}],
      "default": 0.9
    },
    "theta": {
      "description": "The theta parameter for the Barnes-Hut algorithm, which is used to compute charge forces between nodes.",
      "oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}],
      "default": 0.8
    },
    "gravity": {
      "description": "The strength of the pseudo-gravity force that pulls nodes towards the center of the layout area.",
      "oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}],
      "default": 0.1
    },
    "alpha": {
      "description": "A \"temperature\" parameter that determines how much node positions are adjusted at each step.",
      "oneOf": [{"type": "number"}, {"$ref": "#/refs/signal"}],
      "default": 0.1
    },
    "output": {
      "type": "object",
      "description": "Rename the output data fields",
      "properties": {
        "x": {"type": "string", "default": "layout_x"},
        "y": {"type": "string", "default": "layout_y"},
        "source": {"type": "string", "default": "_source"},
        "target": {"type": "string", "default": "_target"}
      },
      "additionalProperties": false
    }
  },
  "additionalProperties": false,
  "required": ["type", "links"]
};<|endoftext|>


<commit_before> // U3.W7: Design Basic Game Solo Challenge

// This is a solo challenge

// Your mission description:
// Overall mission: Collect 3 jewels by slaying and dragon, and placing jewels correctly on the crown
// Goals: defeat a dragon
// Characters: arthur & dragon
// Objects: Arthur(health, jewels, attack and position. Crown(position)

/* Pseudocode
Create variable dragon with health, jewels and attack
Create variable arthur with health, jewels, attack, position and fights function
In fights function input will be attackstrength which will be a random number between 1 & 100
Create while or do block with if conditional inside. The while/do will keep running until dragon or arthur health is below zero.
	Create if block that pending on attackstrength number the dragon health will decrease by attackstrength
		if attackstrenght is low arthur will take damage.
		print to console what the current health level of dragon or arthur.
	If coniditional if arthur wins the jewels from dragon become arthurs
Create crown variable that will have a function for the placement of jewels if arthur slays the dragon.
	If conditional - arthurs position is the same as the random position of how the jewels should be placed, he wins
	else he did slayed a dragon to be defeated by jewel placement.
*/
// Initial Code
var dragon = {
	health: 100,
	jewels:3,
	attack:20,
}
var arthur = {
	health: 100,
	jewels: 0,
	attack: 0,
	posX: Math.floor((Math.random()*3)+1)
	};
function fights(){
	do {
		var attackstrength = Math.floor((Math.random()*100)+1);
		if (attackstrength > 50){
			arthur.attack = 50;
			dragon.health = dragon.health - arthur.attack;
			console.log("Arthur attacked dragon with 50xp. The dragon health is at "+ dragon.health);
		}
		else if (attackstrength < 50 && attackstrength > 25){
			arthur.attack = 20;
			dragon.health = dragon.health - arthur.attack;
			console.log("Arthur attacked dragon with 20xp. The dragon health is at "+ dragon.health);
		}
		else if (attackstrength < 25){
			arthur.health = arthur.health- dragon.attack;
			console.log("Dragon attacked Arthur with 20xp. Arthurs health is at "+ arthur.health);
		}
	}

	while (arthur.health > 0 && dragon.health > 0 );
		if (dragon.health <= 0){
			arthur.jewels = 3;
			dragon.jewels = 0;
			console.log("Arthur defeated the dragon and got all of his jewels.")
		}
		else console.log("Dragon kept all his jewels & Arthur died.")
}

var picture = '\u2654';
var crown = {
	posX: Math.floor((Math.random()*3)+1),
	};
function placement(){
	if (arthur.jewels > 0 && arthur.posX === crown.posX){
		console.log("Arthur placed all the jewels correctly on the crown" + picture)
	}
	else console.log("All that work slaying a dragon and he couldnt place the jewels correctly for the princess.")
	}

fights();
placement();

/* Reflection:
What was the most difficult part of this challenge?
Coming up with a game! Also the random function gave me so problems it took me a little bit to understand the + 1.
What did you learn about creating objects and functions that interact with one another?
I loved that the variables are all global and easily accesiable . I created functions as properties of the objects in this game and then called them. In my other I created functions separate from the objects.
Did you learn about any new built-in methods you could use in your refactored solution? If so, what were they and how do they work?
I didnt refactor this, I instead tried to create an interactive game with my remaining time. It looks like a kindergarden built it but helped me by creating more objects and functions to better get the grasp of them interating.
How can you access and manipulate properties of objects?
*/

<commit_msg> Fix Link<commit_after> // U3.W7: Design Basic Game Solo Challenge

// This is a solo challenge

// Your mission description:
// Overall mission: Collect 3 jewels by slaying and dragon, and placing jewels correctly on the crown
// Goals: defeat a dragon, place jewels correctly.
// Characters: arthur & dragon
// Objects: Arthur(health, jewels, attack and position. Crown(position), dragaon(health jewels, attack)

/* Pseudocode
Create variable dragon with health, jewels and attack
Create variable arthur with health, jewels, attack, position and fights function
In fights function input will be attackstrength which will be a random number between 1 & 100
Create while or do block with if conditional inside. The while/do will keep running until dragon or arthur health is below zero.
	Create if block that pending on attackstrength number the dragon health will decrease by attackstrength
		if attackstrenght is low arthur will take damage.
		print to console what the current health level of dragon or arthur.
	If coniditional if arthur wins the jewels from dragon become arthurs
Create crown variable that will have a function for the placement of jewels if arthur slays the dragon.
	If conditional - arthurs position is the same as the random position of how the jewels should be placed, he wins
	else he did slayed a dragon to be defeated by jewel placement.
*/
// Initial Code
var dragon = {
	health: 100,
	jewels:3,
	attack:20,
}
var arthur = {
	health: 100,
	jewels: 0,
	attack: 0,
	posX: Math.floor((Math.random()*3)+1)
	};
function fights(){
	do {
		var attackstrength = Math.floor((Math.random()*100)+1);
		if (attackstrength > 50){
			arthur.attack = 50;
			dragon.health = dragon.health - arthur.attack;
			console.log("Arthur attacked dragon with 50xp. The dragon health is at "+ dragon.health);
		}
		else if (attackstrength < 50 && attackstrength > 25){
			arthur.attack = 20;
			dragon.health = dragon.health - arthur.attack;
			console.log("Arthur attacked dragon with 20xp. The dragon health is at "+ dragon.health);
		}
		else if (attackstrength < 25){
			arthur.health = arthur.health- dragon.attack;
			console.log("Dragon attacked Arthur with 20xp. Arthurs health is at "+ arthur.health);
		}
	}

	while (arthur.health > 0 && dragon.health > 0 );
		if (dragon.health <= 0){
			arthur.jewels = 3;
			dragon.jewels = 0;
			console.log("Arthur defeated the dragon and got all of his jewels.")
		}
		else console.log("Dragon kept all his jewels & Arthur died.")
}

var picture = '\u2654';
var crown = {
	posX: Math.floor((Math.random()*3)+1),
	};
function placement(){
	if (arthur.jewels > 0 && arthur.posX === crown.posX){
		console.log("Arthur placed all the jewels correctly on the crown" + picture)
	}
	else console.log("All that work slaying a dragon and he couldnt place the jewels correctly for the princess.")
	}

fights();
placement();

/*Refactored Solution:
I tried making an interactive game instead of refactoring.
Link to it : https://danyell85.github.io/projects/wackamole.html */

/* Reflection:
What was the most difficult part of this challenge?
Coming up with a game! Also the random function gave me so problems it took me a little bit to understand the + 1.
What did you learn about creating objects and functions that interact with one another?
I loved that the variables are all global and easily accesiable.
Did you learn about any new built-in methods you could use in your refactored solution? If so, what were they and how do they work?
I didnt refactor this, I instead tried to create an interactive game with my remaining time. It looks like a kindergarden built it but helped me by creating more objects and functions to better get the grasp of them interating.
How can you access and manipulate properties of objects?
You can access properties of objects by calling them with . notation. ex object.property.
Changing properties you can by giving them a new value ex.  object.property = newproperty.
*/

<|endoftext|>


<commit_before>import React from 'react';
import Transition, { ENTERED, ENTERING, EXITING, EXITED } from 'react-transition-group/Transition'
import { Component, PropTypes } from '../utils/';
import "./style/index.less";

/**
 * 老的文档
 * https://facebook.github.io/react/docs/animation.html
 * 新的文档
 * https://reactcommunity.org/react-transition-group/
 * 动画效果
 * https://daneden.github.io/animate.css/
 */
export default class Animate extends Component {
  constructor(props) {
    super(props);
    this.state = {
      in: false
    }
  }
  componentDidMount() {
    if (this.props.in === true) {
      this.setState({ in: true })
    }
  }
  componentWillReceiveProps(nextProps, nextState) {
    if (nextProps.in === undefined) return;
    this.setState({
      in: nextProps.in
    })
  }
  refsSizeChange(elm, status) {
    const { sequence } = this.props;
    if (!elm || !/(?:^|\s)(width|height)(?!\S)/.test(sequence)) return;
    if (status === EXITED) {
      elm.style.height = 0
    } else if (status === ENTERED) {
      elm.style.height = `${elm.scrollHeight}px`
    }
  }
  render() {
    const { prefixCls, sequence, className, wait, children, duration, ...other } = this.props;
    const transitionIn = this.state.in
    const timeout = {
      enter: wait,
      exit: wait
    }
    // 样式动画
    const sequenceClassNames = sequence ? sequence.split(' ').map(s => `is-${s}`).join(' ') : null;
    const animationStyles = {
      [ENTERING]: 'is-mounting',
      [ENTERED]: 'is-mounted',
      [EXITING]: 'is-unmounting',
      [EXITED]: 'is-unmounted'
    }
    const childStyle = (child) => {
      return Object.assign({}, child && child.props ? child.props.style : {}, other.style, {
        transitionDuration: `${duration}ms`
      })
    }
    const childClassName = (child, transitionStatus) => {
      const clss = this.classNames(
        prefixCls, {
          [`${className}`]: className
        },
        sequenceClassNames,
        transitionStatus && animationStyles[transitionStatus],
        child && child.props && child.props.className
      )
      return clss;
    }
    return (
      <Transition
        {...other}
        style={other.style}
        ref="tran"
        className={prefixCls}
        in={transitionIn}
        timeout={timeout}
      >
        {status => React.cloneElement(children, {
          className: childClassName(children, status),
          style: childStyle(children, status),
          ref: elm => this.refsSizeChange(elm, status),
        })}
      </Transition>
    )
  }
}

Animate.propTypes = {
  animateOnMount: PropTypes.bool,
  unmountOnExit: PropTypes.bool,
  prefixCls: PropTypes.string,
  className: PropTypes.string,
  duration: PropTypes.number,
  in: PropTypes.bool,
  sequence: PropTypes.string,
  wait: PropTypes.number
};
Animate.defaultProps = {
  prefixCls: "w-animate",
  unmountOnExit: true,  // 设置 true 销毁根节点
  animateOnMount: true, // 安装动画
  duration: 200,        // 持续时间
  wait: 200             // 等待出现和退出时间
};<commit_msg>fix(Transition):Change ref name.<commit_after>import React from 'react';
import Transition, { ENTERED, ENTERING, EXITING, EXITED } from 'react-transition-group/Transition'
import { Component, PropTypes } from '../utils/';
import "./style/index.less";

/**
 * 老的文档
 * https://facebook.github.io/react/docs/animation.html
 * 新的文档
 * https://reactcommunity.org/react-transition-group/
 * 动画效果
 * https://daneden.github.io/animate.css/
 */
export default class Animate extends Component {
  constructor(props) {
    super(props);
    this.state = {
      in: false
    }
  }
  componentDidMount() {
    if (this.props.in === true) {
      this.setState({ in: true })
    }
  }
  componentWillReceiveProps(nextProps, nextState) {
    if (nextProps.in === undefined) return;
    this.setState({
      in: nextProps.in
    })
  }
  refsSizeChange(elm, status) {
    const { sequence } = this.props;
    if (!elm || !/(?:^|\s)(width|height)(?!\S)/.test(sequence)) return;
    if (status === EXITED) {
      elm.style.height = 0
    } else if (status === ENTERED) {
      elm.style.height = `${elm.scrollHeight}px`
    }
  }
  render() {
    const { prefixCls, sequence, className, wait, children, duration, ...other } = this.props;
    const transitionIn = this.state.in
    const timeout = {
      enter: wait,
      exit: wait
    }
    // 样式动画
    const sequenceClassNames = sequence ? sequence.split(' ').map(s => `is-${s}`).join(' ') : null;
    const animationStyles = {
      [ENTERING]: 'is-mounting',
      [ENTERED]: 'is-mounted',
      [EXITING]: 'is-unmounting',
      [EXITED]: 'is-unmounted'
    }
    const childStyle = (child) => {
      return Object.assign({}, child && child.props ? child.props.style : {}, other.style, {
        transitionDuration: `${duration}ms`
      })
    }
    const childClassName = (child, transitionStatus) => {
      const clss = this.classNames(
        prefixCls, {
          [`${className}`]: className
        },
        sequenceClassNames,
        transitionStatus && animationStyles[transitionStatus],
        child && child.props && child.props.className
      )
      return clss;
    }
    return (
      <Transition
        {...other}
        style={other.style}
        ref="transition"
        className={prefixCls}
        in={transitionIn}
        timeout={timeout}
      >
        {status => React.cloneElement(children, {
          className: childClassName(children, status),
          style: childStyle(children, status),
          ref: elm => this.refsSizeChange(elm, status),
        })}
      </Transition>
    )
  }
}

Animate.propTypes = {
  animateOnMount: PropTypes.bool,
  unmountOnExit: PropTypes.bool,
  prefixCls: PropTypes.string,
  className: PropTypes.string,
  duration: PropTypes.number,
  in: PropTypes.bool,
  sequence: PropTypes.string,
  wait: PropTypes.number
};
Animate.defaultProps = {
  prefixCls: "w-animate",
  unmountOnExit: true,  // 设置 true 销毁根节点
  animateOnMount: true, // 安装动画
  duration: 200,        // 持续时间
  wait: 200             // 等待出现和退出时间
};<|endoftext|>


<commit_before>// Design Basic Game Solo Challenge

// This is a solo challenge

// THE MISSION -
// Mission Description: Help Tom Brady lead a game-winning drive in the Superbowl.
// Goals: Score a Touch-Down.
// Characters: Tom Brady, Rob Gronkowski, Julian Edelman, Danny Amendola, Dion Lewis
// Objects: Tom Brady, Football
// Functions: Throw, Run

/**
PSEUDOCODE
1. Create a tomBrady object

**/

// Initial Code

var tomBrady = {
	firstDown: 0,
	yardsToGo: 10,
	touchdown: 80,
	throw: function() {
		var yards = Math.floor((Math.random() * tomBrady.yardsToGo) + 1)
		tomBrady.yardsToGo = tomBrady.yardsToGo - yards
		tomBrady.touchdown = tomBrady.touchdown - yards
		console.log(tomBrady.yardsToGo)
		console.log(tomBrady.touchdown)
		if (tomBrady.touchdown == 0) {
			return "Touchdown Patriots!";
		}
		else if (tomBrady.yardsToGo <= 0) {
			tomBrady.yardsToGo = 10;
			return "Tom Brady throws a completion for " + yards + " yards! First down Patriots!";
		}
		else {
			return "Tom Brady throws a completion for " + yards + " yards!";
		}
	}
};

field = {
	tomBrady: 50,
	touchdown: false,
};

var receivers = {
	"Rob Gronkowski": 0,
	"Julian Edelman": 0,
	"Danny Amendola": 0,
	"Dion Lewis": 0,
};

console.log(tomBrady.throw())
console.log(tomBrady.throw())
console.log(tomBrady.throw())
console.log(tomBrady.throw())
console.log(tomBrady.throw())
console.log(tomBrady.throw())
console.log(tomBrady.throw())
console.log(tomBrady.throw())
console.log(tomBrady.throw())
console.log(tomBrady.throw())
console.log(tomBrady.throw())
console.log(tomBrady.throw())
console.log(tomBrady.throw())
console.log(tomBrady.throw())
console.log(tomBrady.throw())
console.log(tomBrady.throw())
console.log(tomBrady.throw())
console.log(tomBrady.throw())
console.log(tomBrady.throw())
console.log(tomBrady.throw())
console.log(tomBrady.throw())

// Refactored Code

// Reflection

/*

1. What was the most difficult part of this challenge?
2. What did you learn about creating objects and functions that interact with one another?
3. Did you learn about any new built-in methods you could use in your refactored solution? If so, what were they and how do they work?
4. How can you access and manipulate properties of objects?

*/<commit_msg>Add field, receivers, runningback objects with yards gained by each player. Also add run function.<commit_after>// Design Basic Game Solo Challenge

// This is a solo challenge

// THE MISSION -
// Mission Description: Help Tom Brady lead a game-winning drive in the Superbowl.
// Goals: Score a Touch-Down.
// Characters: Tom Brady, Rob Gronkowski, Julian Edelman, Danny Amendola, Dion Lewis
// Objects: Tom Brady, Football
// Functions: Throw, Run

/**
PSEUDOCODE
1. Create a tomBrady object

**/

// Initial Code

var tomBrady = {
	totalYards: 0,
	runningYards: 0,
	pass: function() {
		if (field.down < 5) {
			var yards = Math.floor((Math.random() * 10) + 1)
			field.firstDown = field.firstDown - yards
			field.yardsToTouchDown = field.yardsToTouchDown - yards
			var options = ["Rob Gronkowski","Julian Edelman","Danny Amendola","Dion Lewis"];
			var routes = ["hitch","slant","out","dig","post","corner","go"];
			var receiver = options[Math.floor(Math.random() * options.length)]
			var route = routes[Math.floor(Math.random() * options.length)]
			receivers[receiver] += yards;
			tomBrady.totalYards += yards;
			// console.log(field.firstDown)
			// console.log(field.yardsToTouchDown)
			// console.log(receiver)
			// console.log(route)
			if (field.touchdown == false) {
				if (field.yardsToTouchDown <= 0) {
					field.touchdown = true;
					field.playerTD = receiver;
					return "Brady throws it into the endzone for " + receiver + "! Touchdown Patriots!";
				}
				else if (field.firstDown <= 0) {
					field.firstDown = 10;
					field.down = 1;
					return "Tom Brady throws a completion for " + yards + " yards to " + receiver + "! First down Patriots!";
				}
				else {
					field.down += 1;
					return "Brady throws to " + receiver + " on a " + route + " route for a " + yards + " yard gain!"
				}
			}
		}
	},

	run: function() {
		if (field.down < 5) {
			var yards = Math.floor((Math.random() * 10) + 1)
			field.firstDown = field.firstDown - yards
			field.yardsToTouchDown = field.yardsToTouchDown - yards
			var options = ["Dion Lewis","LeGarrette Blount","Brandon Bolden"];
			var routes = ["blast","draw","pitch","sweep",];
			var runningBack = options[Math.floor(Math.random() * options.length)]
			var route = routes[Math.floor(Math.random() * options.length)]
			runningBacks[runningBack] += yards;
			tomBrady.runningYards += yards;
			// console.log(field.firstDown)
			// console.log(field.yardsToTouchDown)
			// console.log(runningBack)
			// console.log(route)
			if (field.touchdown == false) {
				if (field.yardsToTouchDown <= 0) {
					field.touchdown = true;
					field.playerTD = runningBack;
					return runningBack + " takes the handoff from Brady and muscles his way into the endzone! Touchdown Patriots!";
				}
				else if (field.firstDown <= 0) {
					field.firstDown = 10;
					field.down = 1;
					return "Tom Brady hands it off to " + runningBack + " for a " + yards + " yard gain! First down Patriots!";
				}
				else {
					field.down += 1;
					return runningBack + " gets the ball on a " + route + " route and takes it for a " + yards + " yard gain!"
				}
			}
		}
	}
};

field = {
	firstDown: 10,
	yardsToTouchDown: 80,
	touchdown: false,
	playerTD: "",
	down: 1,
};

var receivers = {
	"Rob Gronkowski": 0,
	"Julian Edelman": 0,
	"Danny Amendola": 0,
	"Dion Lewis": 0,
};

var runningBacks = {
	"Dion Lewis": 0,
	"LeGarrette Blount": 0,
	"Brandon Bolden": 0,
}

for (var i = 1; field.touchdown == false; i+=3) {
	console.log(tomBrady.pass());
	console.log(tomBrady.run());
}

console.log("Tom Brady led a " + i + " play - " + (tomBrady.totalYards + tomBrady.runningYards) + " yard drive to win the Superbowl!")

if (field.touchdown == true) {
	console.log(field.playerTD + " scored the game winning Touchdown!");
}

for (var key in receivers) {
	console.log(key + " had " + receivers[key] + " receiving yards on that game winning drive!");
}

for (var key in runningBacks) {
	console.log(key + " ran for " + runningBacks[key] + " yards on that game winning drive!");
}

// Refactored Code

// Reflection

/*

1. What was the most difficult part of this challenge?
2. What did you learn about creating objects and functions that interact with one another?
3. Did you learn about any new built-in methods you could use in your refactored solution? If so, what were they and how do they work?
4. How can you access and manipulate properties of objects?

*/<|endoftext|>


<commit_before>'use strict';

// MODULES //

var tape = require( 'tape' );
var proxyquire = require( 'proxyquire' );
var ENV = require( '@stdlib/utils/env' );
var configdir = require( './../lib' );

// VARIABLES //

var mpath = './../lib/configdir.js';

// FUNCTIONS //

/**
* Mock function returning a home directory.
*
* @private
* @returns {string} directory
*/
function homedir() {
	return '/Beep/Boop';
} // end FUNCTION homedir()

/**
* Mock joining a path according to the POSIX path convention.
*
* @private
* @param {...string} p - path components
* @returns {string} path
*/
function joinPosix() {
	var str;
	var p;
	var i;

	str = '';
	str += arguments[ 0 ];
	for ( i = 1; i < arguments.length; i++ ) {
		p = arguments[ i ];
		if ( p ) {
			if ( p[ p.length-1 ] !== '/' ) {
				str += '/';
			}
			str += p;
		}
	}
	return str;
} // end FUNCTION joinPosix()

/**
* Returns a copy of the default proxyquire options.
*
* @private
* @returns {Object} options object
*/
function makeOpts() {
	var opts = {
		'@stdlib/utils/platform': 'darwin',
		'@stdlib/utils/is-windows': false,
		'@stdlib/utils/homedir': homedir,
		'@stdlib/utils/env': ENV,
		'path': {
			'join': joinPosix
		}
	};
	return opts;
} // end FUNCTION makeOpts()

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.strictEqual( typeof configdir, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function throws an error if provided a path value which is not a string primitive', function test( t ) {
	var configdir;
	var values;
	var opts;
	var i;

	values = [
		5,
		NaN,
		true,
		null,
		undefined,
		[],
		{},
		function(){}
	];
	opts = makeOpts();
	configdir = proxyquire( mpath, opts );

	for ( i = 0; i < values.length; i++ ) {
		t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
	}
	t.end();

	function badValue( value ) {
		return function badValue() {
			configdir( value );
		};
	}
});

tape( 'the function supports Mac OS X', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/platform' ] = 'darwin';
	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir(), '/Beep/Boop/Library/Preferences', 'returns directory' );
	t.end();
});

tape( 'the function supports Mac OS X and appends a path', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/platform' ] = 'darwin';
	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir( 'appy/config' ), '/Beep/Boop/Library/Preferences/appy/config', 'returns directory' );
	t.end();
});

tape( 'the function supports Linux (XDG_CONFIG_HOME)', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/env' ] = {
		'XDG_CONFIG_HOME': '/Beep/bop/.config'
	};
	opts[ '@stdlib/utils/platform' ] = 'linux';
	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir(), '/Beep/bop/.config', 'returns directory' );

	t.end();
});

tape( 'the function supports Linux and appends a path (XDG_CONFIG_HOME)', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/env' ] = {
		'XDG_CONFIG_HOME': '/Beep/bop/.config'
	};
	opts[ '@stdlib/utils/platform' ] = 'linux';
	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir( 'appy/config' ), '/Beep/bop/.config/appy/config', 'returns directory' );

	t.end();
});

tape( 'the function supports Linux and falls back to a `.config` directory in a user\'s home directory', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/env' ] = {};
	opts[ '@stdlib/utils/platform' ] = 'linux';
	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir(), '/Beep/Boop/.config', 'returns directory' );

	t.end();
});

tape( 'the function supports Linux and falls back to a `.config` directory in a user\'s home directory and appends a path', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/env' ] = {};
	opts[ '@stdlib/utils/platform' ] = 'linux';
	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir( 'appy/config' ), '/Beep/Boop/.config/appy/config', 'returns directory' );

	t.end();
});

tape( 'the function returns `null` if unable to locate a home directory on non-Windows platforms', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/env' ] = {};
	opts[ '@stdlib/utils/homedir' ] = mock;

	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir(), null, 'returns null' );

	t.end();

	function mock() {
		return null;
	}
});

tape( 'the function supports Windows (LOCALAPPDATA)', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/env' ] = {
		'LOCALAPPDATA': 'C:\\Users\\beep\\AppData\\Local'
	};
	opts[ '@stdlib/utils/is-windows' ] = true;
	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir(), 'C:\\Users\\beep\\AppData\\Local', 'returns directory' );

	t.end();
});

tape( 'the function supports Windows and appends a path (LOCALAPPDATA)', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/env' ] = {
		'LOCALAPPDATA': 'C:\\Users\\beep\\AppData\\Local'
	};
	opts[ '@stdlib/utils/is-windows' ] = true;
	opts[ 'path' ] = { 'join': join };
	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir( 'appy\\config' ), 'C:\\Users\\beep\\AppData\\Local\\appy\\config', 'returns directory' );

	t.end();

	function join( a, b ) {
		return a + '\\' + b;
	}
});

tape( 'the function supports Windows (APPDATA)', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/env' ] = {
		'APPDATA': 'C:\\Users\\beep\\AppData\\Roaming'
	};
	opts[ '@stdlib/utils/is-windows' ] = true;
	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir(), 'C:\\Users\\beep\\AppData\\Roaming', 'returns directory' );

	t.end();
});

tape( 'the function supports Windows and appends a path (APPDATA)', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/env' ] = {
		'LOCALAPPDATA': 'C:\\Users\\beep\\AppData\\Roaming'
	};
	opts[ '@stdlib/utils/is-windows' ] = true;
	opts[ 'path' ] = { 'join': join };
	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir( 'appy\\config' ), 'C:\\Users\\beep\\AppData\\Roaming\\appy\\config', 'returns appended path' );

	t.end();

	function join( a, b ) {
		return a + '\\' + b;
	}
});

tape( 'the function returns `null` if unable to locate an application data directory on Windows', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/env' ] = {};
	opts[ '@stdlib/utils/is-windows' ] = true;

	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir(), null, 'returns null' );

	t.end();
});

<commit_msg>Fix test regression on Windows<commit_after>'use strict';

// MODULES //

var tape = require( 'tape' );
var proxyquire = require( 'proxyquire' );
var ENV = require( '@stdlib/utils/env' );
var configdir = require( './../lib' );

// VARIABLES //

var mpath = './../lib/configdir.js';

// FUNCTIONS //

/**
* Mock function returning a home directory.
*
* @private
* @returns {string} directory
*/
function homedir() {
	return '/Beep/Boop';
} // end FUNCTION homedir()

/**
* Mock joining a path according to the POSIX path convention.
*
* @private
* @param {...string} p - path components
* @returns {string} path
*/
function joinPosix() {
	var str;
	var p;
	var i;

	str = '';
	str += arguments[ 0 ];
	for ( i = 1; i < arguments.length; i++ ) {
		p = arguments[ i ];
		if ( p ) {
			if ( p[ p.length-1 ] !== '/' ) {
				str += '/';
			}
			str += p;
		}
	}
	return str;
} // end FUNCTION joinPosix()

/**
* Returns a copy of the default proxyquire options.
*
* @private
* @returns {Object} options object
*/
function makeOpts() {
	var opts = {
		'@stdlib/utils/platform': 'darwin',
		'@stdlib/utils/is-windows': false,
		'@stdlib/utils/homedir': homedir,
		'@stdlib/utils/env': ENV,
		'path': {
			'join': joinPosix
		}
	};
	return opts;
} // end FUNCTION makeOpts()

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.strictEqual( typeof configdir, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function throws an error if provided a path value which is not a string primitive', function test( t ) {
	var configdir;
	var values;
	var opts;
	var i;

	values = [
		5,
		NaN,
		true,
		null,
		undefined,
		[],
		{},
		function(){}
	];
	opts = makeOpts();
	configdir = proxyquire( mpath, opts );

	for ( i = 0; i < values.length; i++ ) {
		t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
	}
	t.end();

	function badValue( value ) {
		return function badValue() {
			configdir( value );
		};
	}
});

tape( 'the function supports Mac OS X', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/platform' ] = 'darwin';
	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir(), '/Beep/Boop/Library/Preferences', 'returns directory' );
	t.end();
});

tape( 'the function supports Mac OS X and appends a path', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/platform' ] = 'darwin';
	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir( 'appy/config' ), '/Beep/Boop/Library/Preferences/appy/config', 'returns directory' );
	t.end();
});

tape( 'the function supports Linux (XDG_CONFIG_HOME)', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/env' ] = {
		'XDG_CONFIG_HOME': '/Beep/bop/.config',
		'@noCallThru': true
	};
	opts[ '@stdlib/utils/platform' ] = 'linux';
	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir(), '/Beep/bop/.config', 'returns directory' );

	t.end();
});

tape( 'the function supports Linux and appends a path (XDG_CONFIG_HOME)', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/env' ] = {
		'XDG_CONFIG_HOME': '/Beep/bop/.config',
		'@noCallThru': true
	};
	opts[ '@stdlib/utils/platform' ] = 'linux';
	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir( 'appy/config' ), '/Beep/bop/.config/appy/config', 'returns directory' );

	t.end();
});

tape( 'the function supports Linux and falls back to a `.config` directory in a user\'s home directory', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/env' ] = {
		'@noCallThru': true
	};
	opts[ '@stdlib/utils/platform' ] = 'linux';
	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir(), '/Beep/Boop/.config', 'returns directory' );

	t.end();
});

tape( 'the function supports Linux and falls back to a `.config` directory in a user\'s home directory and appends a path', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/env' ] = {
		'@noCallThru': true
	};
	opts[ '@stdlib/utils/platform' ] = 'linux';
	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir( 'appy/config' ), '/Beep/Boop/.config/appy/config', 'returns directory' );

	t.end();
});

tape( 'the function returns `null` if unable to locate a home directory on non-Windows platforms', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/env' ] = {
		'@noCallThru': true
	};
	opts[ '@stdlib/utils/homedir' ] = mock;

	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir(), null, 'returns null' );

	t.end();

	function mock() {
		return null;
	}
});

tape( 'the function supports Windows (LOCALAPPDATA)', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/env' ] = {
		'LOCALAPPDATA': 'C:\\Users\\beep\\AppData\\Local',
		'@noCallThru': true
	};
	opts[ '@stdlib/utils/is-windows' ] = true;
	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir(), 'C:\\Users\\beep\\AppData\\Local', 'returns directory' );

	t.end();
});

tape( 'the function supports Windows and appends a path (LOCALAPPDATA)', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/env' ] = {
		'LOCALAPPDATA': 'C:\\Users\\beep\\AppData\\Local',
		'@noCallThru': true
	};
	opts[ '@stdlib/utils/is-windows' ] = true;
	opts[ 'path' ] = { 'join': join };
	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir( 'appy\\config' ), 'C:\\Users\\beep\\AppData\\Local\\appy\\config', 'returns directory' );

	t.end();

	function join( a, b ) {
		return a + '\\' + b;
	}
});

tape( 'the function supports Windows (APPDATA)', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/env' ] = {
		'APPDATA': 'C:\\Users\\beep\\AppData\\Roaming',
		'@noCallThru': true
	};
	opts[ '@stdlib/utils/is-windows' ] = true;
	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir(), 'C:\\Users\\beep\\AppData\\Roaming', 'returns directory' );

	t.end();
});

tape( 'the function supports Windows and appends a path (APPDATA)', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/env' ] = {
		'LOCALAPPDATA': 'C:\\Users\\beep\\AppData\\Roaming',
		'@noCallThru': true
	};
	opts[ '@stdlib/utils/is-windows' ] = true;
	opts[ 'path' ] = { 'join': join };
	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir( 'appy\\config' ), 'C:\\Users\\beep\\AppData\\Roaming\\appy\\config', 'returns appended path' );

	t.end();

	function join( a, b ) {
		return a + '\\' + b;
	}
});

tape( 'the function returns `null` if unable to locate an application data directory on Windows', function test( t ) {
	var configdir;
	var opts;

	opts = makeOpts();
	opts[ '@stdlib/utils/env' ] = {
		'@noCallThru': true
	};
	opts[ '@stdlib/utils/is-windows' ] = true;

	configdir = proxyquire( mpath, opts );

	t.strictEqual( configdir(), null, 'returns null' );

	t.end();
});

<|endoftext|>


<commit_before>'use strict';

// VARIABLES //

var re = /^\{[\s\S]*\}$|^\[[\s\S]*\]$/;
/**
* REGEX
*	^\{
		- match a '{' literal which is the first character
*	[\s\S]*
		- match any whitespace and non-whitespace characters which occur 0 or more times
*	\}$
		- match a '}' literal which is the last character
*	|
		- alternatively
*	^\[
		- match a '[' literal which is the first character
*	[\s\S]*
		- match any whitespace and non-whitespace characters which occur 0 or more times
*	\]$
		- match a ']' literal which is the last character
*
*	e.g.,
*		'{}'
*		'[]'
*		'{adjlkfaj3743.,><\n\t\rdf}'
*		'[adjlkfaj3743.,><\n\t\rdf]'
*		'{"a":5}'
*/

// MAIN //

/**
* Tests if a value is a parseable JSON string.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a parseable JSON string
*
* @example
* var v = isJSON( '{"a":5}' );
* // returns true
* @example
* var v = isJSON( '{a":5}' );
* // returns false
*/
function isJSON( value ) {
	if ( typeof value !== 'string' ) {
		return false;
	}
	if ( !re.test( value ) ) {
		return false;
	}
	try {
		JSON.parse( value );
	} catch ( err ) {
		return false;
	}
	return true;
} // end FUNCTION isJSON()

// EXPORTS //

module.exports = isJSON;
<commit_msg>Fix lint errors and update JSDoc formatting<commit_after>'use strict';

// VARIABLES //

/**
* Detects a JSON string.
*
* Regular expression: `/^\{[\s\S]*\}$|^\[[\s\S]*\]$/`
*
* * `^\{`
*   - match a `{` literal which is the first character
* * `[\s\S]*`
*   - match any whitespace and non-whitespace characters which occur `0` or more times
* * `\}$`
*   - match a `}` literal which is the last character
* * `|`
*   - alternatively
* * `^\[`
*   - match a `[` literal which is the first character
* * `[\s\S]*`
*   - match any whitespace and non-whitespace characters which occur `0` or more times
* * `\]$`
*   - match a `]` literal which is the last character
*
* Example matching strings:
*
* * `'{}'`
* * `'[]'`
* * `'{adjlkfaj3743.,><\n\t\rdf}'`
* * `'[adjlkfaj3743.,><\n\t\rdf]'`
* * `'{"a":5}'`
*
* @constant
* @type {RegExp}
* @default /^\{[\s\S]*\}$|^\[[\s\S]*\]$/
*/
var re = /^\{[\s\S]*\}$|^\[[\s\S]*\]$/; // eslint-disable-line no-useless-escape

// MAIN //

/**
* Tests if a value is a parseable JSON string.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a parseable JSON string
*
* @example
* var v = isJSON( '{"a":5}' );
* // returns true
* @example
* var v = isJSON( '{a":5}' );
* // returns false
*/
function isJSON( value ) {
	if ( typeof value !== 'string' ) {
		return false;
	}
	if ( !re.test( value ) ) {
		return false;
	}
	try {
		JSON.parse( value );
	} catch ( err ) { // eslint-disable-line no-unused-vars
		return false;
	}
	return true;
} // end FUNCTION isJSON()

// EXPORTS //

module.exports = isJSON;
<|endoftext|>


<commit_before>/* wheatonDice is an opensource project to study the legendary dice curse of Wil Wheaton
 * and get to the bottom of bad juju. At the moment, it's just a dice roller, but later
 * functions will include a rolls database that can track any sinking feeling that the kind of
 * cheetos you're eating is influencing your rolls. Also v.1.0 is aiming at 5th edition D&D rules
 * usage. Later versions will be more system agnostic. This is intended for mobile release, but
 * for now, this is just the engine. Minus the actual engine. Broad strokes to get the system
 * working. Much to be built! -Ian
 */

//public variables
var displaySides = 0,
    displayNumDc = 0,
    displayRolls = [],
    displayTotal = 0;

/*the physics engine (to be built: a different abstract function than builtin Math.random().
It will access the device's accelerometer and add physics + chaos to generate the roll.
it'll be totally sweet!*/
function physics(diceNumber, diceSides) {

    var rolls = [];

    displaySides = diceSides;
    displayNumDc = diceNumber;

    //warning! no edge case protection! You gotta use it just right! Todo: handle edge cases

    //rolls each die separately then pushes to "rolls" array.
    for (var i = 0; i < diceNumber; i++) {
	    rolls.push(Math.ceil( Math.random() * diceSides ));
    }

    displayRolls = rolls;

    //folds the array into a neat total
    var rollTotal = rolls.reduce(function(a ,b) {
	return a + b;
    });

    displayTotal = rollTotal;
    return rollOut(displayNumDc, displaySides, displayRolls, displayTotal);
}

//Separate output function, so that code is easy to delete.
//make it so every lowest possible roll that's rolled displays "Wheaton!"
    //instead of the number
//comment out any portion if you don't want Wil distracting you so much.
//uncomment Percy if you're an optimist.
function rollOut(diceNumber, diceSides, rolls, rollTotal) {
    if (rollTotal === diceNumber) {
	rollTotal = "Wheaton!";
    } else if (rollTotal < (0.33 * (diceSides * diceNumber))){
	rollTotal += " lesser Wheaton.";
    } /*else if (rollTotal === (diceSides * diceNumber)) {
	rollTotal = "Percy!";
    } else if (rollTotal > (0.66 * (diceSides * diceNumber))) {
	rollTotal += " lesser Percy.";
    }*/

    //returns a neat string that shows what you rolled, how each roll went, and the total.
    //This will probably be numberfied and separated out when the actual UI gets built
    if (diceNumber === 1) {
	return ("1 d" + diceSides + ": " + rollTotal);
    } else {
	return (diceNumber + " d" + diceSides + ": " + rolls.join(", ") + " Total: " + rollTotal);}
}

//input functions.
//uses public variables to access physics() function.
function roll(diceNumber, diceSides) {
    return physics(diceNumber, diceSides);
}

//Special kinds of D&D rolls, Advantage, Disadvantage, Inspiration and mixed rolls
function rollAdvantage () {
    roll(2, 20);
    displayTotal = Math.max(displayRolls[0], displayRolls[1]);
    return (displayRolls.join(" and ") + ". Result: " + displayTotal);
}

function rollDisadvantage () {
    roll(2, 20);
    displayTotal = Math.min(displayRolls[0], displayRolls[1]);
    return (displayRolls.join(" and ") + ". Result: " + displayTotal);
}

//Accesses the last most recent roll, check if it is a d20 roll, then add itself to that roll.
//Handles Advantage, & Disadvantage rolls as well.
function rollInspiration () {
    var lastRoll = 0;

    if (displaySides === 20) {
	lastRoll = displayTotal;
	roll(1, 10);
	return ("+" + displayTotal + " to " + lastRoll + ": " + (lastRoll + displayTotal));
    } else {
	return ("You can only add an inspiration die to a d20 roll.");
    }
}

//input for manual rolls (like if you're using real dice). changes public variables directly.
function rollManual(diceNumber, diceSides, rolls) {
    displayNumDc = diceNumber;
    displaySides = diceSides;
    //todo: create an if statement that checks that rolls is an Array.
    displayRolls = rolls;

    displayTotal = rolls.reduce(function(a ,b) {
	return a + b;
    });

    return rollOut(displayNumDc, displaySides, displayRolls, displayTotal);
}

//manual testing, no edge cases yet.
console.log(roll(1,20));
console.log(rollInspiration());
console.log(roll(2,12));
console.log(rollInspiration());
console.log(roll(10,6));
console.log(rollAdvantage());
console.log(rollInspiration());
console.log(rollDisadvantage());
console.log(rollInspiration());
console.log(rollManual(10, 6, [4, 4, 4, 2, 5, 2, 3, 2, 1, 6]));
console.log(rollManual(2, 12, [5, 2]));
console.log(rollInspiration());
console.log(rollManual(1, 20, [20]));
console.log(rollInspiration());
<commit_msg>add percent die & mixed rolls<commit_after>/* wheatonDice is an opensource project to study the legendary dice curse of Wil Wheaton
 * and get to the bottom of bad juju. At the moment, it's just a dice roller, but later
 * functions will include a rolls database that can track any sinking feeling that the kind of
 * cheetos you're eating is influencing your rolls. Also v.1.0 is aiming at 5th edition D&D rules
 * usage. Later versions will be more system agnostic. This is intended for mobile release, but
 * for now, this is just the engine. Minus the actual engine. Broad strokes to get the system
 * working. Much to be built! -Ian
 */

//public variables
var displaySides = 0,
    displayNumDc = 0,
    displayRolls = [],
    displayTotal = 0;

/*the physics engine (to be built: a different abstract function than builtin Math.random().
It will access the device's accelerometer and add physics + chaos to generate the roll.
it'll be totally sweet!*/
function physics(diceNumber, diceSides) {

    var rolls = [];

    displaySides = diceSides;
    displayNumDc = diceNumber;

    //warning! no edge case protection! You gotta use it just right! Todo: handle edge cases

    //rolls each die separately then pushes to "rolls" array.
    for (var i = 0; i < diceNumber; i++) {
	    rolls.push(Math.ceil( Math.random() * diceSides ));
    }

    displayRolls = rolls;

    //folds the array into a neat total
    var rollTotal = rolls.reduce(function(a ,b) {
	return a + b;
    });

    displayTotal = rollTotal;
    return rollOut(displayNumDc, displaySides, displayRolls, displayTotal);
}

//Separate output function, so that code is easy to delete.
//make it so every lowest possible roll that's rolled displays "Wheaton!"
    //instead of the number
//comment out any portion if you don't want Wil distracting you so much.
//uncomment Percy if you're an optimist.
function rollOut(diceNumber, diceSides, rolls, rollTotal) {
    if (rollTotal === diceNumber) {
	rollTotal = "Wheaton!";
    } else if (rollTotal < (0.33 * (diceSides * diceNumber))){
	rollTotal += " lesser Wheaton.";
    } /*else if (rollTotal === (diceSides * diceNumber)) {
	rollTotal = "Percy!";
    } else if (rollTotal > (0.66 * (diceSides * diceNumber))) {
	rollTotal += " lesser Percy.";
    }*/

    //returns a neat string that shows what you rolled, how each roll went, and the total.
    //This will probably be numberfied and separated out when the actual UI gets built
    if (diceNumber === 1) {
	return ("1 d" + diceSides + ": " + rollTotal);
    } else {
	return (diceNumber + " d" + diceSides + ": " + rolls.join(", ") + " Total: " + rollTotal);}
}

//input functions.
//uses public variables to access physics() function.
//ATM roll is a dependency for special roll functions, may need to correct.
function roll(diceNumber, diceSides) {
    return physics(diceNumber, diceSides);
}

/*Mixed dice rolls. There are 6 Standard dice in D&D.
d4, d6, d8, d10, d12, and d20. It would be quite unusual for all these
types of dice to be rolled at the same time, but just in case,
rollMix will be able to handle up to 6 different kinds of dice rolls. */
function rollMix(dNum1, dSid1, dNum2, dSid2, dNum3, dSid3,
		 dNum4, dSid4, dNum5, dSid5, dNum6, dSid6) {
    var diceMix = [],
	mixTotal = 0;
	diceRold = [];

    roll(dNum1, dSid1);
    diceRold.push(dNum1 + " d" + dSid1);
    for (var i = 0; i < displayRolls.length; i++) {
	diceMix.push(displayRolls[i]);
    }

    if (dNum2 > 0) {
	roll(dNum2, dSid2);
	diceRold.push(dNum2 + " d" + dSid2);
	for (var i = 0; i < displayRolls.length; i++) {
		diceMix.push(displayRolls[i]);
	}
    }
    if (dNum3 > 0) {
	roll(dNum3, dSid3);
	diceRold.push(dNum3 + " d" + dSid3);
	for (var i = 0; i < displayRolls.length; i++) {
		diceMix.push(displayRolls[i]);
	}
    }
    if (dNum4 > 0) {
	roll(dNum4, dSid4);
	diceRold.push(dNum4 + " d" + dSid4);
	for (var i = 0; i < displayRolls.length; i++) {
		diceMix.push(displayRolls[i]);
	}
    }
    if (dNum5 > 0) {
	roll(dNum5, dSid5);
	diceRold.push(dNum5 + " d" + dSid5);
	for (var i = 0; i < displayRolls.length; i++) {
		diceMix.push(displayRolls[i]);
	}
    }
    if (dNum6 > 0) {
	roll(dNum6, dSid6);
	diceRold.push(dNum6 + " d" + dSid6);
	for (var i = 0; i < displayRolls.length; i++) {
		diceMix.push(displayRolls[i]);
	}
    }

    mixTotal = diceMix.reduce(function(a ,b) {
	return a + b;
    });

    var dispString = (diceRold.join(", ") + ": "
	+ diceMix.join(", ") + " Total: " + mixTotal);

    return dispString;
}

//Special kinds of D&D rolls, Advantage, Disadvantage, Percent, Inspiration and mixed rolls
function rollAdvantage() {
    roll(2, 20);
    displayTotal = Math.max(displayRolls[0], displayRolls[1]);
    return (displayRolls.join(" & ") + ". Result: " + displayTotal);
}

function rollDisadvantage() {
    roll(2, 20);
    displayTotal = Math.min(displayRolls[0], displayRolls[1]);
    return (displayRolls.join(" & ") + ". Result: " + displayTotal);
}

function rollPercent() {
    roll(2, 10);

    dicePercent = 0;

    dicePercent = ((displayRolls[0] % 10) * 10) + (displayRolls[1] % 10);

    if (dicePercent < 1) {
	dicePercent = 100;
    }

    displayTotal = dicePercent;

    return (displayRolls.join(" & ") + " %Score: " + displayTotal);
}

//Accesses the last most recent roll, check if it is a d20 roll,
//then add itself to that roll.
//Handles Advantage, & Disadvantage rolls as well.
function rollInspiration() {
    var lastRoll = 0;

    if (displaySides === 20) {
	lastRoll = displayTotal;
	roll(1, 10);
	return ("+" + displayTotal + " to " + lastRoll + ": "
		+ (lastRoll + displayTotal));
    } else {
	return ("You can only add an inspiration die to a d20 roll.");
    }
}

//input for manual rolls (like if you're using real dice). changes public variables directly.
function rollManual(diceNumber, diceSides, rolls) {
    displayNumDc = diceNumber;
    displaySides = diceSides;
    //todo: create an if statement that checks that rolls is an Array.
    displayRolls = rolls;

    displayTotal = rolls.reduce(function(a ,b) {
	return a + b;
    });

    return rollOut(displayNumDc, displaySides, displayRolls, displayTotal);
}

//manual testing, no edge cases yet.
console.log(roll(1,20));
console.log(rollInspiration());
console.log(roll(2,12));
console.log(rollInspiration());
console.log(roll(10,6));
console.log(rollAdvantage());
console.log(rollInspiration());
console.log(rollDisadvantage());
console.log(rollInspiration());
console.log(rollManual(10, 6, [4, 4, 4, 2, 5, 2, 3, 2, 1, 6]));
console.log(rollManual(2, 12, [5, 2]));
console.log(rollInspiration());
console.log(rollManual(1, 20, [20]));
console.log(rollInspiration());
console.log(rollMix(2, 12));
console.log(rollMix(2, 12, 3, 10));
console.log(rollPercent());
console.log(rollPercent());
console.log(rollPercent());
console.log(rollPercent());
console.log(rollPercent());

<|endoftext|>


<commit_before>"use strict";

var isFile = /\.[a-z]{3,4}$/i;

function resourceNotFound(req, res, next){
    res.writeHead(404, {"Content-Type": "text/html"});
    res.end("Static File not found: '" + req.parsedURL.pathname + "' \n");
}

/**
 * we respond with 404 if the path is an asset-path
 * if it's no asset, we next, so the index.html will be returned
 * @param req
 * @param res
 * @param next
 */
function notFoundAsset(req, res, next) {

    var parsedURL = req.parsedURL;

    //check for assets folder and all requests containing a "." for file extensions
    if(isFile.test(parsedURL.pathname)) {
        resourceNotFound(req, res, next);
        return;
    }

    next();
}

module.exports = notFoundAsset;

<commit_msg>- fixed isFile regex<commit_after>"use strict";

var isFile = /\.[a-z]{2,4}$/i;

function resourceNotFound(req, res, next){
    res.writeHead(404, {"Content-Type": "text/html"});
    res.end("Static File not found: '" + req.parsedURL.pathname + "' \n");
}

/**
 * we respond with 404 if the path is an asset-path
 * if it's no asset, we next, so the index.html will be returned
 * @param req
 * @param res
 * @param next
 */
function notFoundAsset(req, res, next) {

    var parsedURL = req.parsedURL;

    //check for assets folder and all requests containing a "." for file extensions
    if (isFile.test(parsedURL.pathname)) {
        resourceNotFound(req, res, next);
        return;
    }

    next();
}

module.exports = notFoundAsset;

<|endoftext|>


<commit_before>import * as Types from './all';

'use strict';

QUnit.module('element types', {
	beforeEach() {
		this.title = new Types.Title({
			boundVariableName: 'foo',
			defaultValue: 'foo',
			stringTemplate: 'foo',
			value: 'foo'
		});

		this.field = new Types.Field({
			boundVariableName: 'foo',
			defaultValue: 'foo',
			label: 'foo',
			stringTemplate: 'foo'
		});

		this.image = new Types.Image({
			boundVariableName: 'foo',
			defaultValue: 'foo',
			altBoundVariableName: 'foo',
			altDefaultValue: 'foo',
			caption: new Types.Group({
				boundVariableName: 'foo',
				defaultValue: 'foo',
				label: 'foo',
				stringTemplate: 'foo'
			})
		});
	}
});

QUnit.test('Title', function (assert) {
	assert.strictEqual(this.title.get('boundVariableName'), 'foo', 'boundVariableName should be set');
	assert.strictEqual(this.title.get('defaultValue'), 'foo', 'defaultValue should be set');
	assert.strictEqual(this.title.get('stringTemplate'), 'foo', 'stringTemplate should be set');
	assert.strictEqual(this.title.get('value'), 'foo', 'value should be set');
});

QUnit.test('Field', function (assert) {
	assert.strictEqual(this.field.get('boundVariableName'), 'foo', 'boundVariableName should be set');
	assert.strictEqual(this.field.get('defaultValue'), 'foo', 'defaultValue should be set');
	assert.strictEqual(this.field.get('label'), 'foo', 'label should be set');
	assert.strictEqual(this.field.get('stringTemplate'), 'foo', 'stringTemplate should be set');
});

QUnit.test('Image', function (assert) {
	assert.strictEqual(this.image.get('boundVariableName'), 'foo', 'boundVariableName should be set');
	assert.strictEqual(this.image.get('defaultValue'), 'foo', 'defaultValue should be set');
	assert.strictEqual(this.image.get('altBoundVariableName'), 'foo', 'altBoundVariableName should be set');
	assert.strictEqual(this.image.get('altDefaultValue'), 'foo', 'altDefaultValue should be set');
});

QUnit.test('Caption', function (assert) {
	assert.strictEqual(this.image.get('caption').get('boundVariableName'), 'foo', 'boundVariableName should be set');
	assert.strictEqual(this.image.get('caption').get('defaultValue'), 'foo', 'defaultValue should be set');
	assert.strictEqual(this.image.get('caption').get('stringTemplate'), 'foo', 'stringTemplate should be set');
});

QUnit.test('Group', function (assert) {
	let group = new Types.Group({
		items: [
			this.title,
			this.image,
			this.field
		]
	});

	assert.ok(group.get('items')[0] instanceof Types.Title, 'Title object should be set');
	assert.ok(group.get('items')[1] instanceof Types.Image, 'Image object should be set');
	assert.ok(group.get('items')[2] instanceof Types.Field, 'Field object should be set');
});
<commit_msg>CONSF-66 reordering<commit_after>import * as Types from './all';

'use strict';

QUnit.module('element types', {
	beforeEach() {
		this.title = new Types.Title({
			boundVariableName: 'foo',
			defaultValue: 'foo',
			stringTemplate: 'foo',
			value: 'foo'
		});

		this.image = new Types.Image({
			boundVariableName: 'foo',
			defaultValue: 'foo',
			altBoundVariableName: 'foo',
			altDefaultValue: 'foo',
			caption: new Types.Group({
				boundVariableName: 'foo',
				defaultValue: 'foo',
				label: 'foo',
				stringTemplate: 'foo'
			})
		});

		this.field = new Types.Field({
			boundVariableName: 'foo',
			defaultValue: 'foo',
			label: 'foo',
			stringTemplate: 'foo'
		});
	}
});

QUnit.test('Title', function (assert) {
	assert.strictEqual(this.title.get('boundVariableName'), 'foo', 'boundVariableName should be set');
	assert.strictEqual(this.title.get('defaultValue'), 'foo', 'defaultValue should be set');
	assert.strictEqual(this.title.get('stringTemplate'), 'foo', 'stringTemplate should be set');
	assert.strictEqual(this.title.get('value'), 'foo', 'value should be set');
});

QUnit.test('Image', function (assert) {
	assert.strictEqual(this.image.get('boundVariableName'), 'foo', 'boundVariableName should be set');
	assert.strictEqual(this.image.get('defaultValue'), 'foo', 'defaultValue should be set');
	assert.strictEqual(this.image.get('altBoundVariableName'), 'foo', 'altBoundVariableName should be set');
	assert.strictEqual(this.image.get('altDefaultValue'), 'foo', 'altDefaultValue should be set');
});

QUnit.test('Caption', function (assert) {
	assert.strictEqual(this.image.get('caption').get('boundVariableName'), 'foo', 'boundVariableName should be set');
	assert.strictEqual(this.image.get('caption').get('defaultValue'), 'foo', 'defaultValue should be set');
	assert.strictEqual(this.image.get('caption').get('stringTemplate'), 'foo', 'stringTemplate should be set');
});

QUnit.test('Field', function (assert) {
	assert.strictEqual(this.field.get('boundVariableName'), 'foo', 'boundVariableName should be set');
	assert.strictEqual(this.field.get('defaultValue'), 'foo', 'defaultValue should be set');
	assert.strictEqual(this.field.get('label'), 'foo', 'label should be set');
	assert.strictEqual(this.field.get('stringTemplate'), 'foo', 'stringTemplate should be set');
});

QUnit.test('Group', function (assert) {
	let group = new Types.Group({
		items: [
			this.title,
			this.image,
			this.field
		]
	});

	assert.ok(group.get('items')[0] instanceof Types.Title, 'Title object should be set');
	assert.ok(group.get('items')[1] instanceof Types.Image, 'Image object should be set');
	assert.ok(group.get('items')[2] instanceof Types.Field, 'Field object should be set');
});
<|endoftext|>