<commit_before>
/* medea.js - Open Source, High-Performance 3D Engine based on WebGL.
 *
 * (c) 2011-2013, Alexander C. Gessler
 *  https://github.com/acgessler/medea.js
 *
 * Made available under the terms and conditions of a 3-clause BSD license.
 *
 */

medealib.define('skydome',['mesh'],function(medealib, undefined) {
	"use strict";
	var medea = this;

	// based on my old engine code, which itself took this algorithm from
	// this paper on athmospheric scattering:
	// http://www2.imm.dtu.dk/pubdb/views/edoc_download.php/2554/pdf/imm2554.pdf
	var CreateDomeMesh = function(mat, lower_amount, rings) {
		var pi = Math.PI, sin = Math.sin, cos = Math.cos, sqrt = Math.sqrt, round = Math.round, abs = Math.abs;

		rings = rings || 35;
		lower_amount = lower_amount || 0.0;

		// gather storage requirements upfront and populate ring_info
		var ring_info = new Array(rings);
		ring_info[0] = [0,0.0];

		var lat = 0.0, lad = pi*0.5/rings, fac = pi*2.0/sin(lad), pcnt = 1;
		for(var r = 1; r < rings; ++r) {
			lat += lad;

			var rad = sin(lat)*fac, nmp = round(rad);
			ring_info[r] = [nmp,nmp - ring_info[r-1][0]];
			pcnt += nmp;
		}

		var pos = new Float32Array(pcnt*3);
		var nor = new Float32Array(pcnt*3);
		var uv = new Float32Array(pcnt*2);

		// pole
		pos[0] = 0;
		pos[1] = 1.0 - lower_amount;
		pos[2] = 0;

		nor[0] = 0;
		nor[1] = -1.0;
		nor[2] = 0;

		uv[0] = 0.5;
		uv[1] = 0.5;

		// generate vertices
		var ipos = 3, iuv = 2;
		lat = 0.0;
		for(var r = 1; r < rings; ++r) {
			lat += lad;
			nmp = ring_info[r][0];

			var sinlat = sin(lat);
			var coslat = cos(lat);

			var lon = 0.0, ldf = pi*2.0/nmp;
			for(var p = 0; p < nmp; ++p, lon += ldf) {

				var x = pos[ipos+0] = cos(lon) * sinlat;
				var y = pos[ipos+1] = coslat - lower_amount;
				var z = pos[ipos+2] = sin(lon) * sinlat;

				if(y < 0) {
					y = 0;
				}

				var l = -sqrt( x*x + y*y + z*z );
				nor[ipos++] = x/l;
				nor[ipos++] = y/l;
				nor[ipos++] = z/l;

				uv[iuv++] = (x + 1.0)*0.5;
				uv[iuv++] = (z + 1.0)*0.5;
			}
		}

		// assert(pcnt * 3 == ipos);
		// assert(pcnt * 2 == iuv);

		var n = 0;
		for(var i = 1; i < rings; ++i) {
			n += ring_info[i][0]*3; // XXX improve accuracy, this is just a very rough upper boundary
		}

		var ind = new Array(n);
		n = 0;

		// generate indices
		var ct1 = 0, ct2 = 1;
		for(var i = 1; i < rings; ++i) {

			var rinfo = ring_info[i], fs = abs(rinfo[0]/rinfo[1]), spaces = 0, ct1s = ct1, ct2s = ct2, ns = 0;
			for(var j = 0; j < rinfo[0]; ++j) {

				if (j === 0 && rinfo[1] > 0) {
					ind[n++] = ct2;
					ind[n++] = ct1;
					ind[n++] = ct2+1;

					++ct2, ++spaces;
					ns = round(spaces*fs);
				}
				else if (j === 0 && rinfo[1] < 0) {
					ind[n++] = ct2;
					ind[n++] = ct1;
					ind[n++] = ct1+1;

					ind[n++] = ct2;
					ind[n++] = ct1+1;
					ind[n++] = ct2+1;

					++ct2, ++ct1, ++spaces;
					ns = round(spaces*fs);
				}
				else if (j === rinfo[0]-1 && ct1 === 0) {
					ind[n++] = ct2;
					ind[n++] = ct1;
					ind[n++] = ct2s;

					++ct2, ++ct1;
				}
				else if (j === rinfo[0]-1 && rinfo[1] >= 0 && ct1 > 0) {
					ind[n++] = ct2;
					ind[n++] = ct1;
					ind[n++] = ct1s;

					ind[n++] = ct2;
					ind[n++] = ct1s;
					ind[n++] = ct2s;

					++ct2, ++ct1;
				}
				else if (j === rinfo[0]-1 && rinfo[1] < 0) {
					ind[n++] = ct2;
					ind[n++] = ct1;
					ind[n++] = ct1+1;

					ind[n++] = ct2;
					ind[n++] = ct1+1;
					ind[n++] = ct2s;

					ind[n++] = ct2s;
					ind[n++] = ct1+1;
					ind[n++] = ct1s;

					++ct2, ct1 += 2;
				}
				else if (j === ns && rinfo[1] > 0) {
					ind[n++] = ct2;
					ind[n++] = ct1;
					ind[n++] = ct2+1;

					++ct2, ++spaces;
					ns = round(spaces*fs);
				}
				else if (j === ns && rinfo[1] < 0) {
					ind[n++] = ct2;
					ind[n++] = ct1;
					ind[n++] = ct1+1;

					--j, ++ct1, ++spaces;
					ns = round(spaces*fs);
				}
				else {
					ind[n++] = ct2;
					ind[n++] = ct1;
					ind[n++] = ct1+1;

					ind[n++] = ct2;
					ind[n++] = ct1+1;
					ind[n++] = ct2+1;

					++ct2, ++ct1;
				}
			}
		}

		ind.length = n;
		return medea.CreateSimpleMesh({ positions:pos, normals:nor, uvs:[uv] }, ind, mat);
	};

	/*

	// second version, creates rings with equal triangle counts and thus much
	// higher density at the pole than at the equator.
	var CreateDomeMesh2 = function(mat, lower_amount, rings, hres) {
		var pi = Math.PI, sin = Math.sin, cos = Math.cos, sqrt = Math.sqrt, round = Math.round, abs = Math.abs;

		hres = hres || rings;

		var pcnt = hres * rings + 1;

		var pos = new Array(pcnt*3);
		var nor = new Array(pcnt*3);
		var uv = new Array(pcnt*2);

		pos[0] = 0;
		pos[1] = 1.0 - lower_amount;
		pos[2] = 0;

		nor[0] = 0;
		nor[1] = -1.0;
		nor[2] = 0;

		uv[0] = 0.5;
		uv[1] = 0.5;

		// generate vertices and indices
		var ipos = 3, iuv = 3, lat = 0.0, lad = pi*0.5/rings, x,z,y, l;
		for(var r = 0; r < rings; ++r) {
			lat += lad;

			var sinlat = sin(lat);
			var coslat = cos(lat);

			var lon = 0.0, ldf = pi*2.0/hres;
			for(var p = 0; p < hres; ++p) {

				x = pos[ipos+0] = Math.cos(lon) * sinlat;
				y = pos[ipos+1] = coslat - lower_amount;
				z = pos[ipos+2] = Math.sin(lon) * sinlat;

				if(y < 0) {
					y = 0;
				}

				l = -sqrt( x*x + y*y + z*z );
				nor[ipos++] = x/l;
				nor[ipos++] = y/l;
				nor[ipos++] = z/l;

				uv[iuv++] = (x + 1.0)*0.485;
				uv[iuv++] = (z + 1.0)*0.485;
				lon += ldf;
			}
		}

		// generate indices
		var ind = new Array( ((rings-2) * hres * 2 + hres ) * 3 );
		var il = ind.length;
		var n = 0;
		var base_src = 1;
		for(var r = 0; r < rings - 1; ++r) {
			if(r === 0) {
				for(var i = 0; i < hres; ++i) {
					ind[n++] = base_src + i;
					ind[n++] = 0;
					ind[n++] = base_src + (i + 1) % hres;
				}
			}
			else {
				for(var i = 0; i < hres; ++i) {
					ind[n++] = base_src + i;
					ind[n++] = base_src + i - hres;
					ind[n++] = base_src + (i + 1) % hres;

					ind[n++] = base_src + (i + 1) % hres;
					ind[n++] = base_src + i - hres;
					ind[n++] = base_src + ((i + 1) % hres) - hres;
				}
			}
			base_src += hres;
		}
		return medea.CreateSimpleMesh({ positions:pos, normals:nor, uvs:[uv] }, ind, mat);
	} */

	/* --{
	@entry medea CreateSkydomeNode

	Create a scenegraph node and attach a skydome to it. The skydome is simply a mesh
	that is configured to add itself to the {background rendering queue -> medea
	RenderQueue}. The default skydome effect is located in "mcore/shaders/skydome"
	and draws the skydome behind the rest of the scene, using a single sphere texture.

	`CreateSkydomeNode(texbase, lower_amount, rings)`

	texbase:
	@a URI; of the texture to be displayed on the skydome.

	lower_amount:
	Amount by which the skydome is shifted downwards on the y-axis. This is to make
	sure that the horizon is fully covered. Typical values are 0 ... 0.5 depending
	on the setting.

	rings:
	Number of longitudial 'rings' to subdivide the skydome into. This determines
	how smooth the texture will look on the dome, but high values affect rendering
	speed negatively. Typical values range from 10 ... 35.

	Returns a {medea Node} instance.
	}-- */
	medea.CreateSkydomeNode = function(texbase, lower_amount, rings) {
		var nd = medea.CreateNode("skydome");

		var mesh = CreateDomeMesh(medea.CreateSimpleMaterialFromShaderPair('remote:mcore/shaders/skydome',{
			texture : medea.CreateTexture( texbase )
		}), lower_amount, rings);

		mesh.BB(medea.BB_INFINITE);

		mesh.RenderQueue(medea.RENDERQUEUE_BACKGROUND);
		mesh.Material().Passes().forEach( function(p) {
			p.State({
			'depth_test'  : true,
			'depth_write' : false,
			'cull_face'   : true,
			'cull_face_mode' : 'front'
			});
		});

		nd.AddEntity(mesh);
		return nd;
	};
});
<commit_msg>Skydome: add parameter to stretch the skydome further than the equator.<commit_after>
/* medea.js - Open Source, High-Performance 3D Engine based on WebGL.
 *
 * (c) 2011-2013, Alexander C. Gessler
 *  https://github.com/acgessler/medea.js
 *
 * Made available under the terms and conditions of a 3-clause BSD license.
 *
 */

medealib.define('skydome',['mesh'],function(medealib, undefined) {
	"use strict";
	var medea = this;

	// based on my old engine code, which itself took this algorithm from
	// this paper on athmospheric scattering:
	// http://www2.imm.dtu.dk/pubdb/views/edoc_download.php/2554/pdf/imm2554.pdf
	var CreateDomeMesh = medea.CreateDomeMesh = function(mat, lower_amount, rings, equator_overlap) {
		var pi = Math.PI, sin = Math.sin, cos = Math.cos, sqrt = Math.sqrt, round = Math.round, abs = Math.abs;

		rings = rings || 35;
		lower_amount = lower_amount || 0.0;

		// gather storage requirements upfront and populate ring_info
		var ring_info = new Array(rings);
		ring_info[0] = [0,0.0];

		var lat = 0.0, lad = pi*0.5/(rings - (equator_overlap | 0)), fac = pi*2.0/sin(lad), pcnt = 1;
		for(var r = 1; r < rings; ++r) {
			lat += lad;

			var rad = sin(lat)*fac, nmp = round(rad);
			ring_info[r] = [nmp,nmp - ring_info[r-1][0]];
			pcnt += nmp;
		}

		var pos = new Float32Array(pcnt*3);
		var nor = new Float32Array(pcnt*3);
		var uv = new Float32Array(pcnt*2);

		// pole
		pos[0] = 0;
		pos[1] = 1.0 - lower_amount;
		pos[2] = 0;

		nor[0] = 0;
		nor[1] = -1.0;
		nor[2] = 0;

		uv[0] = 0.5;
		uv[1] = 0.5;

		// generate vertices
		var ipos = 3, iuv = 2;
		lat = 0.0;
		for(var r = 1; r < rings; ++r) {
			lat += lad;
			nmp = ring_info[r][0];

			var sinlat = sin(lat);
			var coslat = cos(lat);

			var lon = 0.0, ldf = pi*2.0/nmp;
			for(var p = 0; p < nmp; ++p, lon += ldf) {

				var x = pos[ipos+0] = cos(lon) * sinlat;
				var y = pos[ipos+1] = coslat - lower_amount;
				var z = pos[ipos+2] = sin(lon) * sinlat;

				if(y < 0) {
					y = 0;
				}

				var l = -sqrt( x*x + y*y + z*z );
				nor[ipos++] = x/l;
				nor[ipos++] = y/l;
				nor[ipos++] = z/l;

				uv[iuv++] = (x + 1.0)*0.5;
				uv[iuv++] = (z + 1.0)*0.5;
			}
		}

		// assert(pcnt * 3 == ipos);
		// assert(pcnt * 2 == iuv);

		var n = 0;
		for(var i = 1; i < rings; ++i) {
			n += ring_info[i][0]*3; // XXX improve accuracy, this is just a very rough upper boundary
		}

		var ind = new Array(n);
		n = 0;

		// generate indices
		var ct1 = 0, ct2 = 1;
		for(var i = 1; i < rings; ++i) {

			var rinfo = ring_info[i], fs = abs(rinfo[0]/rinfo[1]), spaces = 0, ct1s = ct1, ct2s = ct2, ns = 0;
			for(var j = 0; j < rinfo[0]; ++j) {

				if (j === 0 && rinfo[1] > 0) {
					ind[n++] = ct2;
					ind[n++] = ct1;
					ind[n++] = ct2+1;

					++ct2, ++spaces;
					ns = round(spaces*fs);
				}
				else if (j === 0 && rinfo[1] < 0) {
					ind[n++] = ct2;
					ind[n++] = ct1;
					ind[n++] = ct1+1;

					ind[n++] = ct2;
					ind[n++] = ct1+1;
					ind[n++] = ct2+1;

					++ct2, ++ct1, ++spaces;
					ns = round(spaces*fs);
				}
				else if (j === rinfo[0]-1 && ct1 === 0) {
					ind[n++] = ct2;
					ind[n++] = ct1;
					ind[n++] = ct2s;

					++ct2, ++ct1;
				}
				else if (j === rinfo[0]-1 && rinfo[1] >= 0 && ct1 > 0) {
					ind[n++] = ct2;
					ind[n++] = ct1;
					ind[n++] = ct1s;

					ind[n++] = ct2;
					ind[n++] = ct1s;
					ind[n++] = ct2s;

					++ct2, ++ct1;
				}
				else if (j === rinfo[0]-1 && rinfo[1] < 0) {
					ind[n++] = ct2;
					ind[n++] = ct1;
					ind[n++] = ct1+1;

					ind[n++] = ct2;
					ind[n++] = ct1+1;
					ind[n++] = ct2s;

					ind[n++] = ct2s;
					ind[n++] = ct1+1;
					ind[n++] = ct1s;

					++ct2, ct1 += 2;
				}
				else if (j === ns && rinfo[1] > 0) {
					ind[n++] = ct2;
					ind[n++] = ct1;
					ind[n++] = ct2+1;

					++ct2, ++spaces;
					ns = round(spaces*fs);
				}
				else if (j === ns && rinfo[1] < 0) {
					ind[n++] = ct2;
					ind[n++] = ct1;
					ind[n++] = ct1+1;

					--j, ++ct1, ++spaces;
					ns = round(spaces*fs);
				}
				else {
					ind[n++] = ct2;
					ind[n++] = ct1;
					ind[n++] = ct1+1;

					ind[n++] = ct2;
					ind[n++] = ct1+1;
					ind[n++] = ct2+1;

					++ct2, ++ct1;
				}
			}
		}

		ind.length = n;
		return medea.CreateSimpleMesh({ positions:pos, normals:nor, uvs:[uv] }, ind, mat);
	};

	/*

	// second version, creates rings with equal triangle counts and thus much
	// higher density at the pole than at the equator.
	var CreateDomeMesh2 = function(mat, lower_amount, rings, hres) {
		var pi = Math.PI, sin = Math.sin, cos = Math.cos, sqrt = Math.sqrt, round = Math.round, abs = Math.abs;

		hres = hres || rings;

		var pcnt = hres * rings + 1;

		var pos = new Array(pcnt*3);
		var nor = new Array(pcnt*3);
		var uv = new Array(pcnt*2);

		pos[0] = 0;
		pos[1] = 1.0 - lower_amount;
		pos[2] = 0;

		nor[0] = 0;
		nor[1] = -1.0;
		nor[2] = 0;

		uv[0] = 0.5;
		uv[1] = 0.5;

		// generate vertices and indices
		var ipos = 3, iuv = 3, lat = 0.0, lad = pi*0.5/rings, x,z,y, l;
		for(var r = 0; r < rings; ++r) {
			lat += lad;

			var sinlat = sin(lat);
			var coslat = cos(lat);

			var lon = 0.0, ldf = pi*2.0/hres;
			for(var p = 0; p < hres; ++p) {

				x = pos[ipos+0] = Math.cos(lon) * sinlat;
				y = pos[ipos+1] = coslat - lower_amount;
				z = pos[ipos+2] = Math.sin(lon) * sinlat;

				if(y < 0) {
					y = 0;
				}

				l = -sqrt( x*x + y*y + z*z );
				nor[ipos++] = x/l;
				nor[ipos++] = y/l;
				nor[ipos++] = z/l;

				uv[iuv++] = (x + 1.0)*0.485;
				uv[iuv++] = (z + 1.0)*0.485;
				lon += ldf;
			}
		}

		// generate indices
		var ind = new Array( ((rings-2) * hres * 2 + hres ) * 3 );
		var il = ind.length;
		var n = 0;
		var base_src = 1;
		for(var r = 0; r < rings - 1; ++r) {
			if(r === 0) {
				for(var i = 0; i < hres; ++i) {
					ind[n++] = base_src + i;
					ind[n++] = 0;
					ind[n++] = base_src + (i + 1) % hres;
				}
			}
			else {
				for(var i = 0; i < hres; ++i) {
					ind[n++] = base_src + i;
					ind[n++] = base_src + i - hres;
					ind[n++] = base_src + (i + 1) % hres;

					ind[n++] = base_src + (i + 1) % hres;
					ind[n++] = base_src + i - hres;
					ind[n++] = base_src + ((i + 1) % hres) - hres;
				}
			}
			base_src += hres;
		}
		return medea.CreateSimpleMesh({ positions:pos, normals:nor, uvs:[uv] }, ind, mat);
	} */

	/* --{
	@entry medea CreateSkydomeNode

	Create a scenegraph node and attach a skydome to it. The skydome is simply a mesh
	that is configured to add itself to the {background rendering queue -> medea
	RenderQueue}. The default skydome effect is located in "mcore/shaders/skydome"
	and draws the skydome behind the rest of the scene, using a single sphere texture.

	`CreateSkydomeNode(texbase, lower_amount, rings)`

	texbase:
	@a URI; of the texture to be displayed on the skydome.

	lower_amount:
	Amount by which the skydome is shifted downwards on the y-axis. This is to make
	sure that the horizon is fully covered. Typical values are 0 ... 0.5 depending
	on the setting.

	rings:
	Number of longitudial 'rings' to subdivide the skydome into. This determines
	how smooth the texture will look on the dome, but high values affect rendering
	speed negatively. Typical values range from 10 ... 35.

	Returns a {medea Node} instance.
	}-- */
	medea.CreateSkydomeNode = function(texbase, lower_amount, rings) {
		var nd = medea.CreateNode("skydome");

		var mesh = CreateDomeMesh(medea.CreateSimpleMaterialFromShaderPair('remote:mcore/shaders/skydome',{
			texture : medea.CreateTexture( texbase )
		}), lower_amount, rings);

		mesh.BB(medea.BB_INFINITE);

		mesh.RenderQueue(medea.RENDERQUEUE_BACKGROUND);
		mesh.Material().Passes().forEach( function(p) {
			p.State({
			'depth_test'  : true,
			'depth_write' : false,
			'cull_face'   : true,
			'cull_face_mode' : 'front'
			});
		});

		nd.AddEntity(mesh);
		return nd;
	};
});
<|endoftext|>


<commit_before>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

export default class DynamicButton extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.android.js
        </Text>
        <Text style={styles.instructions}>
          Double tap R on your keyboard to reload,{'\n'}
          Shake or press menu button for dev menu
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('DynamicButton', () => DynamicButton);
<commit_msg>Test create Play Shape<commit_after>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

import {
  Surface,
  Shape,
  Path
} from 'ReactNativeART';

export default class DynamicButton extends Component {
  render() {
    const d = Path().moveTo(80, 20).lineTo(280, 150).lineTo(80, 280).close();
    return (
      <View style={styles.container}>
        <Surface width="300" height="300">
          <Shape stroke="#ff0000" strokeWidth="8" strokeJoin="round" strokeCap="round" d = {d} />
        </Surface>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  }
});

AppRegistry.registerComponent('DynamicButton', () => DynamicButton);
<|endoftext|>


<commit_before>/* jshint node: true */
/* global require, module */

var EmberAddon = require('ember-cli/lib/broccoli/ember-addon');

/*
  This Brocfile specifes the options for the dummy test app of this
  addon, located in `/tests/dummy`

  This Brocfile does *not* influence how the addon or the app using it
  behave. You most likely want to be modifying `./index.js` or app's Brocfile
*/

var app = new EmberAddon();

module.exports = app.toTree();
<commit_msg>Remove unused brocfile<commit_after><|endoftext|>


<commit_before>+(function (factory) {
  if (typeof exports === 'undefined') {
    factory(webduino || {});
  } else {
    module.exports = factory;
  }
}(function (scope) {
  'use strict';

  var Pin = scope.Pin,
    Module = scope.Module,
    proto;

  function Max7219(board, din, cs, clk) {
    Module.call(this);
    this._board = board;
    this._din = din;
    this._cs = cs;
    this._clk = clk;
    this._intensity = 0;
    this._data = 'ffffffffffffffff';
    this._board.send([0xf0, 4, 8, 0, din.number, cs.number, clk.number, 0xf7]);
  }

  Max7219.prototype = proto = Object.create(Module.prototype, {
    constructor: {
      value: Max7219
    },
    intensity: {
      get: function () {
        return this._intensity;
      },
      set: function (val) {
        if (val >= 0 && val <= 15) {
          this._board.send([0xf0, 4, 8, 3, val, 0xf7]);
          this._intensity = val;
        }
      }
    }
  });

  proto.on = function (data) {
    if (data) {
      this._data = data;
    }

    if (!this._data) {
      return false;
    }

    var sendData = [0xf0, 4, 8, 1];
    var hex;
    for (var i = 0; i < this._data.length; i = i + 2) {
      hex = '0x' + this._data.substring(i, i + 2);
      sendData.push(parseInt(hex));
    }
    sendData.push(0xf7);
    this._board.send(sendData);
  };

  proto.off = function () {
    this._board.send([0xf0, 4, 8, 2, 0xf7]);
  };

  scope.module.Max7219 = Max7219;
}));<commit_msg>Fixed bug: animate of max7219.<commit_after>+(function (factory) {
  if (typeof exports === 'undefined') {
    factory(webduino || {});
  } else {
    module.exports = factory;
  }
}(function (scope) {
  'use strict';

  var Pin = scope.Pin,
    Module = scope.Module,
    proto;

  function Max7219(board, din, cs, clk) {
    Module.call(this);
    this._board = board;
    this._din = din;
    this._cs = cs;
    this._clk = clk;
    this._intensity = 0;
    this._data = 'ffffffffffffffff';
    this._board.send([0xf0, 4, 8, 0, din.number, cs.number, clk.number, 0xf7]);
  }

  Max7219.prototype = proto = Object.create(Module.prototype, {
    constructor: {
      value: Max7219
    },
    intensity: {
      get: function () {
        return this._intensity;
      },
      set: function (val) {
        if (val >= 0 && val <= 15) {
          this._board.send([0xf0, 4, 8, 3, val, 0xf7]);
          this._intensity = val;
        }
      }
    }
  });

  proto.on = function (data) {
    if (data) {
      this._data = data;
    }

    if (!this._data) {
      return false;
    }

    var sendData = [0xf0, 4, 8, 1];
    var hex;
    for (var i = 0; i < this._data.length; i = i + 2) {
      hex = '0x' + this._data.substring(i, i + 2);
      sendData.push(parseInt(hex));
    }
    sendData.push(0xf7);
    this._board.send(sendData);
  };

  proto.off = function () {
    this._board.send([0xf0, 4, 8, 2, 0xf7]);
  };

  proto.animate = function(data, times, duration, callback) {
    var p = 0;

    if (typeof arguments[arguments.length - 1] === 'function') {
      callback = arguments[arguments.length - 1];
    } else {
      callback = function() {};
    }

    var run = function() {
      this.on(data[p++ % data.length]);
      this._timer = setTimeout(run, times);
    }.bind(this);

    var stop = function() {
      clearTimeout(this._timer);
      callback();
    }.bind(this);

    if (times && times > 0) {
      run();
    }

    if (duration && duration > 0) {
      this._timerDuration = setTimeout(stop, duration);
    }
  };

  proto.animateStop = function() {
    clearTimeout(this._timer);
    clearTimeout(this._timerDuration);
  };

  scope.module.Max7219 = Max7219;
}));<|endoftext|>


<commit_before>"use strict";

/* eslint no-use-before-define: 0 */

var sphero = require("../");

// make sure you install this first - `npm install keypress`
var keypress = require("keypress");

var orb = sphero("/dev/rfcomm0");

orb.connect(listen);

function handle(ch, key) {
  if (key.ctrl && key.name === "c") {
    process.stdin.pause();
  }

  var stop = orb.roll.bind(orb, 0, 0),
      roll = orb.roll.bind(orb, 60);

  if (key.name === "up") {
    roll(0);
  }

  if (key.name === "down") {
    roll(180);
  }

  if (key.name === "left") {
    roll(270);
  }

  if (key.name === "right") {
    roll(90);
  }

  if (key.name === "space") {
    stop();
  }
}

function listen() {
  keypress(process.stdin);
  process.stdin.on("keypress", handle);

  console.log("starting to listen for arrow key presses");

  process.stdin.setRawMode(true);
  process.stdin.resume();
}
<commit_msg>Update keyboard example<commit_after>"use strict";

/* eslint no-use-before-define: 0 */
/* eslint no-process-exit: 0 */

var sphero = require("../");

// make sure you install this first - `npm install keypress`
var keypress = require("keypress");

var orb = sphero("/dev/rfcomm0");

orb.connect(listen);

function handle(ch, key) {
  var stop = orb.roll.bind(orb, 0, 0),
      roll = orb.roll.bind(orb, 60);

  if (key.ctrl && key.name === "c") {
    process.stdin.pause();
    process.exit();
  }

  if (key.name === "e") {
    orb.startCalibration();
  }

  if (key.name === "q") {
    orb.finishCalibration();
  }

  if (key.name === "up") {
    roll(0);
  }

  if (key.name === "down") {
    roll(180);
  }

  if (key.name === "left") {
    roll(270);
  }

  if (key.name === "right") {
    roll(90);
  }

  if (key.name === "space") {
    stop();
  }
}

function listen() {
  keypress(process.stdin);
  process.stdin.on("keypress", handle);

  console.log("starting to listen for arrow key presses");

  process.stdin.setRawMode(true);
  process.stdin.resume();
}
<|endoftext|>


<commit_before>window.OTP_config = {
  initLatLng: [45.52, -122.681944],

  osmMapKey: 'your-mapbox-osm-key',
  aerialMapKey: 'your-mapbox-aerial-key',

  // mapzenApiKey: "your-key", // your Mapzen Search API key
  // geocoderSearchRadius : 25, // search radius in km for mapzen geocoder from initLatLng (defaults to 50 if not specified)

  otpApi: 'http://localhost:8001/otp/routers/',

  // geocoders to use:
  geocoders: [ 'edsi' ], // possible choices: esri, otp, nominatim, mapzen, mapbox
  reverseGeocoder: 'esri', // possible choices: esri, nominatim, mapzen, mapbox
  reverseGeocode: true,

  // geocoder api endpoints
  nominatimApi: 'https://nominatim.openstreetmap.org/',
  esriApi: 'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/',
  mapzenApi: 'https://search.mapzen.com/v1/'
}
<commit_msg>fix typo<commit_after>window.OTP_config = {
  initLatLng: [45.52, -122.681944],

  osmMapKey: 'your-mapbox-osm-key',
  aerialMapKey: 'your-mapbox-aerial-key',

  // mapzenApiKey: "your-key", // your Mapzen Search API key
  // geocoderSearchRadius : 25, // search radius in km for mapzen geocoder from initLatLng (defaults to 50 if not specified)

  otpApi: 'http://localhost:8001/otp/routers/',

  // geocoders to use:
  geocoders: [ 'esri' ], // possible choices: esri, otp, nominatim, mapzen, mapbox
  reverseGeocoder: 'esri', // possible choices: esri, nominatim, mapzen, mapbox
  reverseGeocode: true,

  // geocoder api endpoints
  nominatimApi: 'https://nominatim.openstreetmap.org/',
  esriApi: 'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/',
  mapzenApi: 'https://search.mapzen.com/v1/'
}
<|endoftext|>


<commit_before>/**
 * Top-level Android app.
 *
 * @flow
 */
'use strict';

import React from 'react';
import {
    AppRegistry,
    DeviceEventEmitter,
    Image,
    Linking,
    NativeModules,
    PanResponder,
    Text,
    ToolbarAndroid,
    View,
} from 'react-native';
import {connect, Provider} from 'react-redux';
import DialogAndroid from 'react-native-dialogs';

import './DebugGlobals';
import ExecuteButton from './ExecuteButton';
import {Definition, Expression} from './Expression';
import generateDisplayState from './generateDisplayState';
import Palette from './Palette';
import SimpleComponent from './SimpleComponent';
import StatelessComponent from './StatelessComponent';
import store from './store';
import {IList} from './types-collections';
import * as t from './types';

import type {
    DisplayState,
    MeasureRequest,
    ScreenDefinition,
    ScreenExpression,
    ScreenPoint,
} from './types'
import {IMap, ISet} from './types-collections'

type TopLevelExpressionPropTypes = {
    screenExpr: ScreenExpression,
}
type TopLevelExpressionState = {
    measuredSize: ?{
        width: number,
        height: number,
    }
}
class TopLevelExpression extends SimpleComponent<TopLevelExpressionPropTypes, TopLevelExpressionState> {
    constructor(props) {
        super(props);
        this.state = {
            measuredSize: null,
        }
    }

    handleLayout({nativeEvent: {layout: {width, height}}}) {
        this.setState({
            measuredSize: {width, height},
        });
    }

    render() {
        const {
            expr, pos: {screenX, screenY}, isDragging, executeHandler
        } = this.props.screenExpr;
        const transform: Array<any> = [
            {translateX: screenX},
            {translateY: screenY},
        ];
        if (isDragging) {
            transform.push(
                {scaleX: 1.1},
                {scaleY: 1.1},
            )
        }

        let executeButton = null;
        if (executeHandler && this.state.measuredSize != null) {
            const {width, height} = this.state.measuredSize;
            executeButton = <ExecuteButton onPress={executeHandler} style={{
                elevation: 5,
                position: 'absolute',
                transform: [
                    {translateX: screenX + width - 20 + 8},
                    {translateY: screenY + height - 20 + 8},
                ],
            }} />
        }
        return <View>
            <View
                onLayout={this.handleLayout.bind(this)}
                style={{
                    position: 'absolute',
                    transform,
            }}>
                <Expression expr={expr} />
            </View>
            {executeButton}
        </View>;
    }
}

type TopLevelDefinitionPropTypes = {
    screenDef: ScreenDefinition,
}
class TopLevelDefinition extends StatelessComponent<TopLevelDefinitionPropTypes> {
    render() {
        const {
            defName, expr, pos: {screenX, screenY}, defKey, refKey,
            emptyBodyKey, shouldHighlightEmptyBody, isDragging
        } = this.props.screenDef;
        const transform: Array<any> = [
            {translateX: screenX},
            {translateY: screenY},
        ];
        if (isDragging) {
            transform.push(
                {scaleX: 1.1},
                {scaleY: 1.1},
            )
        }

        return <View style={{
            position: 'absolute',
            transform,
        }}>
            <Definition
                defName={defName}
                defKey={defKey}
                emptyBodyKey={emptyBodyKey}
                refKey={refKey}
                shouldHighlightEmptyBody={shouldHighlightEmptyBody}
                expr={expr} />
        </View>;
    }
}

/**
 * Component used for taking measurements of expressions so we know where to
 * position them when they're placed for real.
 */
type MeasureHandlerPropTypes = {
    measureRequest: MeasureRequest,
}
class MeasureHandler extends StatelessComponent<MeasureHandlerPropTypes> {
    handleLayout({nativeEvent: {layout: {width, height}}}) {
        this.props.measureRequest.resultHandler(width, height);
    }

    render() {
        const {expr} = this.props.measureRequest;
        return <View onLayout={this.handleLayout.bind(this)} style={{
            position: 'absolute',
            opacity: 0,
        }}>
            <Expression expr={expr} />
        </View>;
    }
}

type ToolbarProps = {
    definitionNames: IList<string>,
    recognizeNumbers: boolean,
}
class Toolbar extends StatelessComponent<ToolbarProps> {
    actions: Array<any>;

    constructor() {
        super();
        this.actions = [
            {
                title: 'Lambda palette',
                onPress() {
                    store.dispatch(t.ToggleLambdaPalette.make());
                }
            },
            {
                title: 'Definition palette',
                onPress() {
                    store.dispatch(t.ToggleDefinitionPalette.make());
                }
            },
            {
                title: 'Delete definition',
                onPress: this.handleDeleteDefinition.bind(this),
            },
            {
                title: 'Automatically recognize numbers',
                onPress() {
                    // TODO.
                }
            },
            {
                title: 'View demo video',
                onPress() {
                    // TODO: Show the video in the app itself instead of going to
                    // YouTube.
                    Linking.openURL('https://www.youtube.com/watch?v=0OzpqDDniDs');
                }
            },
            {
                title: 'Create lambda',
                onPress: this.handleCreateLambda.bind(this),
            },
            {
                title: 'Create definition',
                onPress: this.handleCreateDefinition.bind(this),
            },
            {
                title: 'Dev: Show options',
                onPress() {
                    NativeModules.DeveloperSupportModule.showDevOptionsDialog();
                }
            },
            {
                title: 'Dev: Refresh JS',
                onPress() {
                    NativeModules.DeveloperSupportModule.reloadJs();
                }
            },
        ];
    }

    handleActionSelected(position) {
        this.actions[position].onPress();
    }

    handleDeleteDefinition() {
        const dialog = new DialogAndroid();
        dialog.set({
            title: 'Choose a definition to delete',
            items: this.props.definitionNames.toArray(),
            itemsCallback: (index, item) => {
                store.dispatch(t.DeleteDefinition.make(item));
            },
            negativeText: 'Cancel'
        });
        dialog.show();
    }

    handleCreateLambda() {
        const dialog = new DialogAndroid();
        dialog.set({
            title: 'Choose a variable name',
            positiveText: 'OK',
            negativeText: 'Cancel',
            input: {
                allowEmptyInput: false,
                callback: (varName) => {
                    // TODO: Validate name.
                    store.dispatch(t.AddExpression.make(
                        t.CanvasExpression.make(
                            t.UserLambda.make(varName, null),
                            t.CanvasPoint.make(100, 100))
                    ));
                },
            }
        });
        dialog.show();
    }

    handleCreateDefinition() {
        const dialog = new DialogAndroid();
        dialog.set({
            title: 'Create or show definition',
            positiveText: 'OK',
            negativeText: 'Cancel',
            input: {
                allowEmptyInput: false,
                callback: (defName) => {
                    // TODO: Validate name.
                    store.dispatch(t.PlaceDefinition.make(
                        defName,
                        t.ScreenPoint.make(100, 100),
                    ));
                },
            }
        });
        dialog.show();
    }

    render() {
        return <ToolbarAndroid
            title="Lambda Calculus Playground"
            actions={this.actions}
            onActionSelected={this.handleActionSelected.bind(this)}
            style={{
            elevation: 4,
            height: 56,
            backgroundColor: '#e9eaed',
            position: 'absolute',
            left: 0,
            right: 0,
            top: 0,
        }}
        />
    }
}

type PlaygroundCanvasProps = {
    displayState: DisplayState,
};
class PlaygroundCanvasView extends SimpleComponent<PlaygroundCanvasProps, {}> {
    _responderMethods: any;

    componentWillMount() {
        this._responderMethods = this.getResponderMethods();
    }

    getResponderMethods() {
        let lastTouches: IMap<number, ScreenPoint> = IMap.make();
        const processEvent = ({nativeEvent: {touches}}) => {
            const newTouches = IMap.make(touches.map((touch) =>
                [touch.identifier, t.ScreenPoint.make(touch.pageX, touch.pageY)]
            ));

            const fingers = ISet.make(lastTouches.keys())
                .union(newTouches.keys());
            for (const fingerId of fingers) {
                const beforePoint = lastTouches.get(fingerId);
                const afterPoint = newTouches.get(fingerId);
                if (beforePoint && afterPoint) {
                    store.dispatch(t.FingerMove.make(fingerId, afterPoint));
                } else if (afterPoint) {
                    store.dispatch(t.FingerDown.make(fingerId, afterPoint));
                } else if (beforePoint) {
                    store.dispatch(t.FingerUp.make(fingerId, beforePoint));
                }
            }
            lastTouches = newTouches;
        };

        // The different callbacks don't let us distinguish individual fingers;
        // we need to look at the event data directly.
        return {
            onStartShouldSetResponder: (event) => true,
            onResponderGrant: processEvent,
            onResponderMove: processEvent,
            onResponderRelease: processEvent,
            onResponderTerminate: processEvent,
        }
    }

    render() {
        const {
            screenExpressions, screenDefinitions, paletteState, measureRequests,
            definitionNames,
        } = this.props.displayState;
        const measureHandlers = measureRequests.map((measureRequest, i) =>
            <MeasureHandler
                measureRequest={measureRequest}
                key={"measure" + i} />);
        const exprNodes = screenExpressions.map((screenExpr) =>
            <TopLevelExpression
                screenExpr={screenExpr}
                key={screenExpr.key}
            />
        );
        const definitionNodes = screenDefinitions.map((screenDef) =>
            <TopLevelDefinition
                screenDef={screenDef}
                key={screenDef.key}
            />
        );

        return <View {...this._responderMethods} style={{
                backgroundColor: '#AAAAAA',
                flex: 1,
            }}>
            <Toolbar
                definitionNames={definitionNames}
            />
            {measureHandlers}
            {exprNodes}
            {definitionNodes}
            <Palette displayState={paletteState} />
        </View>;
    }
}

const ConnectedPlaygroundCanvasView =
    connect((state) => ({
            displayState: generateDisplayState(state),
        })
    )(PlaygroundCanvasView);

class PlaygroundCanvas extends SimpleComponent<{}, {}> {
    render() {
        return <Provider store={store}>
            <ConnectedPlaygroundCanvasView />
        </Provider>
    }
}

AppRegistry.registerComponent('PlaygroundCanvas', () => PlaygroundCanvas);
<commit_msg>Make the definition dialog use capital letters by default<commit_after>/**
 * Top-level Android app.
 *
 * @flow
 */
'use strict';

import React from 'react';
import {
    AppRegistry,
    DeviceEventEmitter,
    Image,
    Linking,
    NativeModules,
    PanResponder,
    Text,
    ToolbarAndroid,
    View,
} from 'react-native';
import {connect, Provider} from 'react-redux';
import DialogAndroid from 'react-native-dialogs';

import './DebugGlobals';
import ExecuteButton from './ExecuteButton';
import {Definition, Expression} from './Expression';
import generateDisplayState from './generateDisplayState';
import Palette from './Palette';
import SimpleComponent from './SimpleComponent';
import StatelessComponent from './StatelessComponent';
import store from './store';
import {IList} from './types-collections';
import * as t from './types';

import type {
    DisplayState,
    MeasureRequest,
    ScreenDefinition,
    ScreenExpression,
    ScreenPoint,
} from './types'
import {IMap, ISet} from './types-collections'

type TopLevelExpressionPropTypes = {
    screenExpr: ScreenExpression,
}
type TopLevelExpressionState = {
    measuredSize: ?{
        width: number,
        height: number,
    }
}
class TopLevelExpression extends SimpleComponent<TopLevelExpressionPropTypes, TopLevelExpressionState> {
    constructor(props) {
        super(props);
        this.state = {
            measuredSize: null,
        }
    }

    handleLayout({nativeEvent: {layout: {width, height}}}) {
        this.setState({
            measuredSize: {width, height},
        });
    }

    render() {
        const {
            expr, pos: {screenX, screenY}, isDragging, executeHandler
        } = this.props.screenExpr;
        const transform: Array<any> = [
            {translateX: screenX},
            {translateY: screenY},
        ];
        if (isDragging) {
            transform.push(
                {scaleX: 1.1},
                {scaleY: 1.1},
            )
        }

        let executeButton = null;
        if (executeHandler && this.state.measuredSize != null) {
            const {width, height} = this.state.measuredSize;
            executeButton = <ExecuteButton onPress={executeHandler} style={{
                elevation: 5,
                position: 'absolute',
                transform: [
                    {translateX: screenX + width - 20 + 8},
                    {translateY: screenY + height - 20 + 8},
                ],
            }} />
        }
        return <View>
            <View
                onLayout={this.handleLayout.bind(this)}
                style={{
                    position: 'absolute',
                    transform,
            }}>
                <Expression expr={expr} />
            </View>
            {executeButton}
        </View>;
    }
}

type TopLevelDefinitionPropTypes = {
    screenDef: ScreenDefinition,
}
class TopLevelDefinition extends StatelessComponent<TopLevelDefinitionPropTypes> {
    render() {
        const {
            defName, expr, pos: {screenX, screenY}, defKey, refKey,
            emptyBodyKey, shouldHighlightEmptyBody, isDragging
        } = this.props.screenDef;
        const transform: Array<any> = [
            {translateX: screenX},
            {translateY: screenY},
        ];
        if (isDragging) {
            transform.push(
                {scaleX: 1.1},
                {scaleY: 1.1},
            )
        }

        return <View style={{
            position: 'absolute',
            transform,
        }}>
            <Definition
                defName={defName}
                defKey={defKey}
                emptyBodyKey={emptyBodyKey}
                refKey={refKey}
                shouldHighlightEmptyBody={shouldHighlightEmptyBody}
                expr={expr} />
        </View>;
    }
}

/**
 * Component used for taking measurements of expressions so we know where to
 * position them when they're placed for real.
 */
type MeasureHandlerPropTypes = {
    measureRequest: MeasureRequest,
}
class MeasureHandler extends StatelessComponent<MeasureHandlerPropTypes> {
    handleLayout({nativeEvent: {layout: {width, height}}}) {
        this.props.measureRequest.resultHandler(width, height);
    }

    render() {
        const {expr} = this.props.measureRequest;
        return <View onLayout={this.handleLayout.bind(this)} style={{
            position: 'absolute',
            opacity: 0,
        }}>
            <Expression expr={expr} />
        </View>;
    }
}

type ToolbarProps = {
    definitionNames: IList<string>,
    recognizeNumbers: boolean,
}
class Toolbar extends StatelessComponent<ToolbarProps> {
    actions: Array<any>;

    constructor() {
        super();
        this.actions = [
            {
                title: 'Lambda palette',
                onPress() {
                    store.dispatch(t.ToggleLambdaPalette.make());
                }
            },
            {
                title: 'Definition palette',
                onPress() {
                    store.dispatch(t.ToggleDefinitionPalette.make());
                }
            },
            {
                title: 'Delete definition',
                onPress: this.handleDeleteDefinition.bind(this),
            },
            {
                title: 'Automatically recognize numbers',
                onPress() {
                    // TODO.
                }
            },
            {
                title: 'View demo video',
                onPress() {
                    // TODO: Show the video in the app itself instead of going to
                    // YouTube.
                    Linking.openURL('https://www.youtube.com/watch?v=0OzpqDDniDs');
                }
            },
            {
                title: 'Create lambda',
                onPress: this.handleCreateLambda.bind(this),
            },
            {
                title: 'Create definition',
                onPress: this.handleCreateDefinition.bind(this),
            },
            {
                title: 'Dev: Show options',
                onPress() {
                    NativeModules.DeveloperSupportModule.showDevOptionsDialog();
                }
            },
            {
                title: 'Dev: Refresh JS',
                onPress() {
                    NativeModules.DeveloperSupportModule.reloadJs();
                }
            },
        ];
    }

    handleActionSelected(position) {
        this.actions[position].onPress();
    }

    handleDeleteDefinition() {
        const dialog = new DialogAndroid();
        dialog.set({
            title: 'Choose a definition to delete',
            items: this.props.definitionNames.toArray(),
            itemsCallback: (index, item) => {
                store.dispatch(t.DeleteDefinition.make(item));
            },
            negativeText: 'Cancel'
        });
        dialog.show();
    }

    handleCreateLambda() {
        const dialog = new DialogAndroid();
        dialog.set({
            title: 'Choose a variable name',
            positiveText: 'OK',
            negativeText: 'Cancel',
            input: {
                allowEmptyInput: false,
                callback: (varName) => {
                    // TODO: Validate name.
                    store.dispatch(t.AddExpression.make(
                        t.CanvasExpression.make(
                            t.UserLambda.make(varName, null),
                            t.CanvasPoint.make(100, 100))
                    ));
                },
            }
        });
        dialog.show();
    }

    handleCreateDefinition() {
        const dialog = new DialogAndroid();
        dialog.set({
            title: 'Create or show definition',
            positiveText: 'OK',
            negativeText: 'Cancel',
            input: {
                allowEmptyInput: false,
                type: 0x00001000, // InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS
                callback: (defName) => {
                    // TODO: Validate name.
                    store.dispatch(t.PlaceDefinition.make(
                        defName,
                        t.ScreenPoint.make(100, 100),
                    ));
                },
            }
        });
        dialog.show();
    }

    render() {
        return <ToolbarAndroid
            title="Lambda Calculus Playground"
            actions={this.actions}
            onActionSelected={this.handleActionSelected.bind(this)}
            style={{
            elevation: 4,
            height: 56,
            backgroundColor: '#e9eaed',
            position: 'absolute',
            left: 0,
            right: 0,
            top: 0,
        }}
        />
    }
}

type PlaygroundCanvasProps = {
    displayState: DisplayState,
};
class PlaygroundCanvasView extends SimpleComponent<PlaygroundCanvasProps, {}> {
    _responderMethods: any;

    componentWillMount() {
        this._responderMethods = this.getResponderMethods();
    }

    getResponderMethods() {
        let lastTouches: IMap<number, ScreenPoint> = IMap.make();
        const processEvent = ({nativeEvent: {touches}}) => {
            const newTouches = IMap.make(touches.map((touch) =>
                [touch.identifier, t.ScreenPoint.make(touch.pageX, touch.pageY)]
            ));

            const fingers = ISet.make(lastTouches.keys())
                .union(newTouches.keys());
            for (const fingerId of fingers) {
                const beforePoint = lastTouches.get(fingerId);
                const afterPoint = newTouches.get(fingerId);
                if (beforePoint && afterPoint) {
                    store.dispatch(t.FingerMove.make(fingerId, afterPoint));
                } else if (afterPoint) {
                    store.dispatch(t.FingerDown.make(fingerId, afterPoint));
                } else if (beforePoint) {
                    store.dispatch(t.FingerUp.make(fingerId, beforePoint));
                }
            }
            lastTouches = newTouches;
        };

        // The different callbacks don't let us distinguish individual fingers;
        // we need to look at the event data directly.
        return {
            onStartShouldSetResponder: (event) => true,
            onResponderGrant: processEvent,
            onResponderMove: processEvent,
            onResponderRelease: processEvent,
            onResponderTerminate: processEvent,
        }
    }

    render() {
        const {
            screenExpressions, screenDefinitions, paletteState, measureRequests,
            definitionNames,
        } = this.props.displayState;
        const measureHandlers = measureRequests.map((measureRequest, i) =>
            <MeasureHandler
                measureRequest={measureRequest}
                key={"measure" + i} />);
        const exprNodes = screenExpressions.map((screenExpr) =>
            <TopLevelExpression
                screenExpr={screenExpr}
                key={screenExpr.key}
            />
        );
        const definitionNodes = screenDefinitions.map((screenDef) =>
            <TopLevelDefinition
                screenDef={screenDef}
                key={screenDef.key}
            />
        );

        return <View {...this._responderMethods} style={{
                backgroundColor: '#AAAAAA',
                flex: 1,
            }}>
            <Toolbar
                definitionNames={definitionNames}
            />
            {measureHandlers}
            {exprNodes}
            {definitionNodes}
            <Palette displayState={paletteState} />
        </View>;
    }
}

const ConnectedPlaygroundCanvasView =
    connect((state) => ({
            displayState: generateDisplayState(state),
        })
    )(PlaygroundCanvasView);

class PlaygroundCanvas extends SimpleComponent<{}, {}> {
    render() {
        return <Provider store={store}>
            <ConnectedPlaygroundCanvasView />
        </Provider>
    }
}

AppRegistry.registerComponent('PlaygroundCanvas', () => PlaygroundCanvas);
<|endoftext|>


<commit_before>function preview_home_page(homePageContentId, homePageContent){
    var previewContent = null;

    if(homePageContentId){
        previewContent = document.getElementById(homePageContentId).value;
    }
    else if (homePageContent){
        previewContent = decodeURIComponent(homePageContent);
    }

    if (!previewContent)
    {
        return;
    }

    var previewWindow = window.open('','preview_window','height = 700 width = 800, resizable = 1, scrollbars = 1');
    if (!previewWindow)
    {
        // Window did not open. Popup blocker?
        return;
    }

    var formString = '<form id="preview_project_form" action="/home/preview_home_page" method="post" style="display: none;" enctype="application/x-www-form-urlencoded">' +
                     '<textarea class="mceNoEditor" cols="40" id="preview_content_container" name="home_page_preview_content" rows="20" style="opacity:0;">' +
                     previewContent +
                     '</textarea>' +
                     '</form>';

    var previewWindowDocument = previewWindow.document;

    previewWindowDocument.open();
    previewWindowDocument.write(formString);
    previewWindowDocument.close();

    previewWindowDocument.getElementById('preview_project_form').submit();

    return;
}<commit_msg>Refine preview home page<commit_after>function preview_home_page(homePageContentId, homePageContent){
    var previewContent = null;

    if(homePageContentId){
        previewContent = document.getElementById(homePageContentId).value;
    }
    else if (homePageContent == "" || homePageContent){
        previewContent = decodeURIComponent(homePageContent);
    }

    if (previewContent != "" && !previewContent)
    {
        return;
    }

    var previewWindow = window.open('','preview_window','height = 700 width = 800, resizable = 1, scrollbars = 1');
    if (!previewWindow)
    {
        // Window did not open. Popup blocker?
        return;
    }

    var formString = '<form id="preview_project_form" action="/home/preview_home_page" method="post" style="display: none;" enctype="application/x-www-form-urlencoded">' +
                     '<textarea class="mceNoEditor" cols="40" id="preview_content_container" name="home_page_preview_content" rows="20" style="opacity:0;">' +
                     previewContent +
                     '</textarea>' +
                     '</form>';

    var previewWindowDocument = previewWindow.document;

    previewWindowDocument.open();
    previewWindowDocument.write(formString);
    previewWindowDocument.close();

    previewWindowDocument.getElementById('preview_project_form').submit();

    return;
}<|endoftext|>


<commit_before>/* global require, module, process */

var EmberApp = require('ember-cli/lib/broccoli/ember-app');
var env = EmberApp.env();
var isProductionLikeBuild = ['production', 'staging'].indexOf(env) > -1;
var prepend = null;

if(isProductionLikeBuild) {
  prepend = env==='production' ? '//assets.ember-twiddle.com/' : '//staging-assets.ember-twiddle.com/';
}

var app = new EmberApp({
  fingerprint: {
    enabled: isProductionLikeBuild,
    prepend: prepend
  },
  codemirror: {
    modes: ['xml', 'javascript', 'htmlmixed'],
  },
  'ember-cli-bootstrap-sassy': {
    'js': ['dropdown']
  },
  sourcemaps: {
    enabled: !isProductionLikeBuild,
  },
  minifyCSS: { enabled: isProductionLikeBuild },
  minifyJS: { enabled: isProductionLikeBuild },

  tests: process.env.EMBER_CLI_TEST_COMMAND || !isProductionLikeBuild,
  hinting: process.env.EMBER_CLI_TEST_COMMAND || !isProductionLikeBuild,

  vendorFiles: {
    'handlebars.js': {
      staging:  'bower_components/handlebars/handlebars.runtime.js'
    },
    'ember.js': {
      staging:  'bower_components/ember/ember.prod.js'
    }
  }
});

// Use `app.import` to add additional libraries to the generated
// output files.
app.import('bower_components/ember/ember-template-compiler.js');

// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.

module.exports = app.toTree();
<commit_msg>Brocfile fix<commit_after>/* global require, module, process */

var EmberApp = require('ember-cli/lib/broccoli/ember-app');
var env = EmberApp.env();
var isProductionLikeBuild = ['production', 'staging'].indexOf(env) > -1;
var prepend = null;

if(isProductionLikeBuild) {
  prepend = env==='production' ? '//assets.ember-twiddle.com/' : '//staging-assets.ember-twiddle.com/';
}

var app = new EmberApp({
  fingerprint: {
    enabled: isProductionLikeBuild,
    prepend: prepend
  },
  codemirror: {
    modes: ['xml', 'javascript', 'htmlmixed'],
  },
  'ember-cli-bootstrap-sassy': {
    'js': ['dropdown']
  },
  sourcemaps: {
    enabled: !isProductionLikeBuild,
  },
  minifyCSS: { enabled: isProductionLikeBuild },
  minifyJS: { enabled: isProductionLikeBuild },

  tests: process.env.EMBER_CLI_TEST_COMMAND || !isProductionLikeBuild,
  hinting: process.env.EMBER_CLI_TEST_COMMAND || !isProductionLikeBuild,

  vendorFiles: {
    'ember.js': {
      staging:  'bower_components/ember/ember.prod.js'
    }
  }
});

// Use `app.import` to add additional libraries to the generated
// output files.
app.import('bower_components/ember/ember-template-compiler.js');

// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.

module.exports = app.toTree();
<|endoftext|>


<commit_before>import React from "react";
import ReactDOM from "react-dom";
import * as Router from "rouct";
import kofi from "kofi";

import {createToaster} from "@siimple/neutrine";
import {createConfirmer} from "@siimple/neutrine";

import {HomePage} from "./pages/Home/index.js";
import {NewPage} from "./pages/New/index.js";
import {EditorPage} from "./pages/Editor/index.js";
import {initSandboxStorage} from "./utils/sandbox.js";
import "./style.scss";

//Main app component
class App extends React.Component {
    constructor(props) {
        super(props);
    }
    //Render the app component
    render() {
        return (
            <Router.BrowserRouter>
                <Router.Switch>
                    <Router.Route path="/editor" exact component={EditorPage} />
                    <Router.Route path="/new" exact component={NewPage} />
                    <Router.Route path="/" exact component={HomePage} />
                </Router.Switch>
            </Router.BrowserRouter>
        );
    }
}

//Mount the app component
kofi.ready(function () {
    //Create the toaster
    window["toast"] = createToaster({
        "width": "400px",
        "align": "right",
        "time": 1500
    });
    window["confirm"] = createConfirmer({});
    //Initialize sandbox storage
    return initSandboxStorage().then(function () {
        ReactDOM.render(<App />, document.getElementById("root")); //Mount app
    });
});

<commit_msg>lab: redesigned main App component and fixed imports<commit_after>import React from "react";
import ReactDOM from "react-dom";
import * as Router from "rouct";
import kofi from "kofi";
import {createToaster} from "neutrine/lib/widgets";
import {createConfirmer} from "neutrine/lib/widgets";
import {whenReady} from "neutrine/lib/utils";

//Import global styles
import "siimple/dist/siimple.css";
import "siimple-experiments/dist/siimple-experiments.css";
import "siimple-icons/dist/siimple-icons.css";
import "neutrine/lib/components.css";
import "neutrine/lib/editor.css";
import "neutrine/lib/widgets.css";

import {HomePage} from "./pages/Home/index.js";
import {NewPage} from "./pages/New/index.js";
import {EditorPage} from "./pages/Editor/index.js";
import {initSandboxStorage} from "./utils/sandbox.js";
import {Splash} from "./components/Splash/index.js";
import "./style.scss";

//Main app component
class App extends React.Component {
    constructor(props) {
        super(props);
        //Initial lab state
        this.state = {
            "loading": true
        };
    }
    //Component did mount --> init sandbox storage
    componentDidMount() {
        let self = this;
        return initSandboxStorage().then(function () {
            return kofi.delay(1000);
        }).then(function () {
            return self.setState({"loading": false});
        });
    }
    //Render the app component
    render() {
        //Check for loading app state --> display loading splash
        if (this.state.loading === true) {
            return React.createElement(Splash, {});
        }
        //Render the lab router
        return (
            <Router.BrowserRouter>
                <Router.Switch>
                    <Router.Route path="/editor" exact component={EditorPage} />
                    <Router.Route path="/new" exact component={NewPage} />
                    <Router.Route path="/" exact component={HomePage} />
                </Router.Switch>
            </Router.BrowserRouter>
        );
    }
}

//Mount the app component
whenReady(function () {
    //Create the toaster
    window["toast"] = createToaster({
        "width": "400px",
        "align": "right",
        "time": 1500
    });
    window["confirm"] = createConfirmer({});
    ReactDOM.render(<App />, document.getElementById("root")); //Mount app
});

<|endoftext|>


<commit_before>const {readFileSync, writeFileSync} = require('fs');
const libui = require('../index.js');
libui.Ui.init();
const {
	label,
	window,
	tab,
	menu,
	multilineEntry
} = require('./utils.js');

const onClosing = () => libui.stopLoop();

const winProps = {
	hasMenubar: true,
	title: 'Node Pad',
	width: 640,
	height: 480,
	onClosing
};

libui.Ui.init();

let win;
let editor;
let status;
let currentFileName = '';

function newFile() {
	editor.text = '';
	currentFileName = '';
}

function openFile() {
	const filename = libui.UiDialogs.openFile(win);
	if (filename) {
		const content = readFileSync(filename, 'utf8');
		editor.text = content;
		status.text = `Open ${filename}`;
		currentFileName = filename;
	}
}

function saveFileAs() {
	const filename = libui.UiDialogs.saveFile(win);
	if (filename) {
		currentFileName = filename;
		writeFileSync(currentFileName, editor.text);
	}
}

function saveFile() {
	if (!currentFileName) {
		return saveFileAs();
	}
	writeFileSync(currentFileName, editor.text);
}

menu([{
	label: 'File',
	submenu: [
		{
			label: 'New file',
			click: newFile
		}, {
			label: 'Open',
			click: openFile
		}, {
			label: 'Close current tab',
			click: () => {}
		}, {
			label: 'Save',
			click: saveFile
		}, {
			label: 'Save as',
			click: saveFileAs
		}, {
			role: 'quit'
		}
	]
}, {
	label: 'Edit',
	submenu: [
		{
			label: 'Copy'
		}, {
			label: 'Paste'
		}, {
			label: 'Cut'
		}, {
			label: 'Select all'
		}
	]
}, {
	label: 'Help',
	submenu: [
		{
			label: 'Help',
			click: () => {}
		}, {
			role: 'about'
		}
	]
}]);

win = window(winProps,
	tab({stretchy: true},
		editor = multilineEntry({stretchy: true, tabTitle: 'New file'})
	),
	status = label({stretchy: false, text: 'File not changed'})
);

win.show();
libui.startLoop();

<commit_msg>make file reading async<commit_after>const {readFile, writeFile} = require('fs');
const libui = require('../index.js');
libui.Ui.init();
const {
	label,
	window,
	tab,
	menu,
	multilineEntry
} = require('./utils.js');

const onClosing = () => libui.stopLoop();

const winProps = {
	hasMenubar: true,
	title: 'Node Pad',
	width: 640,
	height: 480,
	onClosing
};

libui.Ui.init();

let win;
let editor;
let status;
let currentFileName = '';

function newFile() {
	editor.text = '';
	currentFileName = '';
}

function openFile() {
	const filename = libui.UiDialogs.openFile(win);
	if (filename) {
		readFile(filename, 'utf8', function (err, content) {
			editor.text = content;
			status.text = `Open ${filename}`;
			currentFileName = filename;
		});
	}
}

function saveFileAs() {
	const filename = libui.UiDialogs.saveFile(win);
	if (filename) {
		writeFile(currentFileName, editor.text, function (err) {
			currentFileName = filename;
		});
	}
}

function saveFile() {
	if (!currentFileName) {
		return saveFileAs();
	}
	writeFile(currentFileName, editor.text, function (err) {
	});
}

menu([{
	label: 'File',
	submenu: [
		{
			label: 'New file',
			click: newFile
		}, {
			label: 'Open',
			click: openFile
		}, {
			label: 'Close current tab',
			click: () => {}
		}, {
			label: 'Save',
			click: saveFile
		}, {
			label: 'Save as',
			click: saveFileAs
		}, {
			role: 'quit'
		}
	]
}, {
	label: 'Edit',
	submenu: [
		{
			label: 'Copy'
		}, {
			label: 'Paste'
		}, {
			label: 'Cut'
		}, {
			label: 'Select all'
		}
	]
}, {
	label: 'Help',
	submenu: [
		{
			label: 'Help',
			click: () => {}
		}, {
			role: 'about'
		}
	]
}]);

win = window(winProps,
	tab({stretchy: true},
		editor = multilineEntry({stretchy: true, tabTitle: 'New file'})
	),
	status = label({stretchy: false, text: 'File not changed'})
);

win.show();
libui.startLoop();

<|endoftext|>


<commit_before>
  var context;
  init();

  function freq (key_index) {
    return 440 * Math.pow(2, (key_index - 49) / 12.0)
  }

  function init() {
    try {
      window.AudioContext = window.AudioContext || window.webkitAudioContext;
      context = new AudioContext();
    }
    catch(e) {
      alert('Web Audio API is not supported in this browser');
    }

    var height = $('#keys').height();
    $('#visualization-container').height(height - 30);
    $('.btn').on('click', function () {
      var frequency = $(this).data('frequency');
      var duration = $(this).data('duration');
      var startTime = context.currentTime;
      sequence(frequency, duration, 4, 10, startTime);
    });

    $('#sequence').on('click', function () {
      var startTime = context.currentTime;
      for (var i=0; i<12; i++) {
        var frequency = freq(40 + i);
        sequence(frequency, 1/8, (i+1)/8, 10, startTime);
        startTime = startTime + 1;
      }
    });
  }

  function sequence (frequency, duration, period, count, startTime) {
    var offset = startTime;
    for (var i=0; i<count; i++) {
      new Note(frequency, duration, offset);
      offset = offset + period;
    }
  }

  var Note = function (frequency, duration, startTime) {
    this.oscillator = context.createOscillator();
    this.oscillator.frequency.value = frequency;
    this.oscillator.connect(context.destination);
    this.oscillator.start(startTime);
    this.oscillator.stop(startTime + duration);
  };

<commit_msg>need to figure out how to generate scales<commit_after>(function () {

  var context;
  var scales = {
    c_major: [
      freq(40),
      freq(42),
      freq(44),
      freq(45),
      freq(47),
      freq(49),
      freq(51),
      freq(52)
    ]
  };

  init();

  function init() {
    try {
      window.AudioContext = window.AudioContext || window.webkitAudioContext;
      context = new AudioContext();
    }
    catch(e) {
      alert('Web Audio API is not supported in this browser');
    }

    var height = $('#keys').height();
    $('#visualization-container').height(height);
    $('.btn').on('click', function () {
      var frequency = $(this).data('frequency');
      var duration = $(this).data('duration');
      var startTime = context.currentTime;
      sequence(frequency, duration, 4, 10, startTime);
    });

    $('#sequence').on('click', function () {
      var startTime = context.currentTime;
      for (var i=0; i<scales.c_major.length; i++) {
        var frequency = scales.c_major[i];
        sequence(frequency, 1/16, 1, 2, startTime);
        startTime = startTime + 1/16;
      }
    });
  }

  function freq (key_index) {
    return 440 * Math.pow(2, (key_index - 49) / 12.0)
  }

  function sequence (frequency, duration, period, count, startTime) {
    var offset = startTime;
    for (var i=0; i<count; i++) {
      new Note(frequency, duration, offset);
      offset = offset + period;
    }
  }

  var Note = function (frequency, duration, startTime) {
    this.oscillator = context.createOscillator();
    this.oscillator.frequency.value = frequency;
    this.oscillator.connect(context.destination);
    this.oscillator.start(startTime);
    this.oscillator.stop(startTime + duration);
  };

})();<|endoftext|>


<commit_before>import 'es6-symbol/implement';
import {Provider} from 'react-redux';
import store from './src/redux/store';
import AppViewContainer from './src/modules/AppViewContainer';
import React from 'react';
import {AppRegistry, BackAndroid} from 'react-native';
import * as NavigationStateActions from './src/modules/navigation/NavigationState';

const Softala3SuperAda = React.createClass({

  componentWillMount() {
    BackAndroid.addEventListener('hardwareBackPress', this.navigateBack);
  },

  navigateBack() {
    const navigationState = store.getState().get('navigationState');
    const tabs = navigationState.get('tabs');
    const tabKey = tabs.getIn(['routes', tabs.get('index')]).get('key');
    const currentTab = navigationState.get(tabKey);

    // if we are in the beginning of our tab stack
    if (currentTab.get('index') === 0) {

      // if we are not in the first tab, switch tab to the leftmost one
      if (navigationState.get('index') !== 0) {
        store.dispatch(NavigationStateActions.switchTab(0));
        return true;
      }

      // otherwise let OS handle the back button action
      return false;
    }

    store.dispatch(NavigationStateActions.popRoute());
    return true;
  },

  render() {
    return (
      <Provider store={store}>
        <AppViewContainer />
      </Provider>
    );
  }
});

AppRegistry.registerComponent('Softala3SuperAda', () => Softala3SuperAda);
<commit_msg>Testaan :3<commit_after>import 'es6-symbol/implement';
import {Provider} from 'react-redux';
import store from './src/redux/store';
import AppViewContainer from './src/modules/AppViewContainer';
import React from 'react';
import {AppRegistry, BackAndroid} from 'react-native';
import * as NavigationStateActions from './src/modules/navigation/NavigationState';

const Softala3SuperAda = React.createClass({

  componentWillMount() {
    BackAndroid.addEventListener('hardwareBackPress', this.navigateBack);
  },

  navigateBack() {
    const navigationState = store.getState().get('navigationState');
    const tabs = navigationState.get('tabs');
    const tabKey = tabs.getIn(['routes', tabs.get('index')]).get('key');
    const currentTab = navigationState.get(tabKey);

    // If we are in the beginning of our tab stack :3
    if (currentTab.get('index') === 0) {

      // if we are not in the first tab, switch tab to the leftmost one
      if (navigationState.get('index') !== 0) {
        store.dispatch(NavigationStateActions.switchTab(0));
        return true;
      }

      // otherwise let OS handle the back button action
      return false;
    }

    store.dispatch(NavigationStateActions.popRoute());
    return true;
  },

  render() {
    return (
      <Provider store={store}>
        <AppViewContainer />
      </Provider>
    );
  }
});

AppRegistry.registerComponent('Softala3SuperAda', () => Softala3SuperAda);
<|endoftext|>


<commit_before>$(document).ready(function(){
    $.ajax({
        url: '/graph/expense_percentages_data',
        method: "get"
    }).done(function(data){
        percentageChart(data);
    }).fail(function(e){
        console.log("Failed:" + e);
    })

    var percentageChart = function(data) {
        $('#spending-averages').highcharts({
            chart: {
                type: 'bar'
            },
            title: {
                text: 'Your Spending Percentages'
            },
            subtitle: {
                text: 'Compared to National Averages'
            },
            xAxis: {
                categories: ['Housing', 'Transportation', 'Food', 'Phone', 'Misc'],
                title: {
                    text: 'Categories'
                }
            },
            yAxis: {
                min: 0,
                title: {
                    text: 'Percentage',
                    align: 'high'
                },
                labels: {
                    overflow: 'justify'
                }
            },
            tooltip: {
                valueSuffix: ' millions'
            },
            plotOptions: {
                bar: {
                    dataLabels: {
                        enabled: true
                    }
                }
            },
            legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'top',
                x: -40,
                y: 80,
                floating: true,
                borderWidth: 1,
                backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
                shadow: true
            },
            credits: {
                enabled: false
            },
            series: [{
                name: 'Your spending',
                data: data.expenses
            }, {
                name: 'Average Spending',
                data: [35, 15, 7, 3, 30]
            }]
        });
    };
})<commit_msg>Fix millions into percengtage on highcharts<commit_after>$(document).ready(function(){
    $.ajax({
        url: '/graph/expense_percentages_data',
        method: "get"
    }).done(function(data){
        percentageChart(data);
    }).fail(function(e){
        console.log("Failed:" + e);
    })

    var percentageChart = function(data) {
        $('#spending-averages').highcharts({
            chart: {
                type: 'bar'
            },
            title: {
                text: 'Your Spending Percentages'
            },
            subtitle: {
                text: 'Compared to National Averages'
            },
            xAxis: {
                categories: ['Housing', 'Transportation', 'Food', 'Phone', 'Misc'],
                title: {
                    text: 'Categories'
                }
            },
            yAxis: {
                min: 0,
                title: {
                    text: 'Percentage',
                    align: 'high'
                },
                labels: {
                    overflow: 'justify'
                }
            },
            tooltip: {
                valueSuffix: ' percent'
            },
            plotOptions: {
                bar: {
                    dataLabels: {
                        enabled: true
                    }
                }
            },
            legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'top',
                x: -40,
                y: 80,
                floating: true,
                borderWidth: 1,
                backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
                shadow: true
            },
            credits: {
                enabled: false
            },
            series: [{
                name: 'Your spending',
                data: data.expenses
            }, {
                name: 'Average Spending',
                data: [35, 15, 7, 3, 30]
            }]
        });
    };
})<|endoftext|>


<commit_before>/* jshint node: true */
/* global require, module */

var EmberAddon = require('ember-cli/lib/broccoli/ember-addon');

var app = new EmberAddon();

// Use `app.import` to add additional libraries to the generated
// output files.
//
// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.

app.import('bower_components/gmaps-markerclusterer-plus/src/markerclusterer.js',{});

module.exports = app.toTree();

<commit_msg>switched over to using dist min of marker clusterer plus<commit_after>/* jshint node: true */
/* global require, module */

var EmberAddon = require('ember-cli/lib/broccoli/ember-addon');

var app = new EmberAddon();

// Use `app.import` to add additional libraries to the generated
// output files.
//
// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.

app.import('bower_components/gmaps-markerclusterer-plus/dist/markerclusterer.min.js',{});

module.exports = app.toTree();

<|endoftext|>


<commit_before>'use strict';

import $ from 'jquery';
import React from 'react';
import { render } from 'react-dom';
import { Button } from 'react-bootstrap';

import Solitaire from 'solitaire';
import Multiplayer from 'multiplayer';

class SetApp extends React.Component {
  startSolitaire() {
    $.get('/solitaire').then((response) => {
      render(
        <Solitaire url="/solitaire" />, document.getElementById('content')
      );
    });
  }

  startMultiplayer() {
    $.get('/multiplayer').then((response) => {
      render(
        <Multiplayer url="/game" />, document.getElementById('content')
      );
    });
  }

  render() {
    return (

        <Button bsSize="large" bsStyle="default" onClick={this.startSolitaire}>Solitaire Set</Button>
        <Button bsSize="large" bsStyle="default" onClick={this.startMultiplayer}>Multiplayer Set</Button>

    );
  }
}

render(
  <SetApp />, document.getElementById('content')
);
<commit_msg>list multiplayer games attached to the web service<commit_after>'use strict';

import $ from 'jquery';
import React from 'react';
import { render } from 'react-dom';
import { Button, SplitButton, MenuItem } from 'react-bootstrap';

import Solitaire from 'solitaire';
import Multiplayer from 'multiplayer';

class SetApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      games: {}
    };
  }

  componentWillMount() {
    let onSuccess = function(response) {
      this.setState({
        'games': response
      });
    }.bind(this);
    let onError = function(response) {
      this.setState({
        'error': response
      });
    }.bind(this);
    $.get('/multiplayer').then(onSuccess, onError);
  }

  startSolitaire() {
    $.get('/solitaire').then((response) => {
      render(
        <Solitaire url="/solitaire" />, document.getElementById('content')
      );
    });
  }

  startMultiplayer() {
    $.get('/multiplayer').then((response) => {
      render(
        <Multiplayer url="/game" />, document.getElementById('content')
      );
    });
  }

  render() {
    return (

        <Button bsSize="large"
                bsStyle="default"
                key="solitaire"
                onClick={this.startSolitaire}
                id="solitaire_button">Solitaire Set</Button>
        <SplitButton bsSize="large"
                     bsStyle="default"
                     key="multiplayer"
                     title="Multiplayer Set"
                     id="multiplayer_split_button"
                     onClick={this.startMultiplayer}>
          {$.map(this.state.games, (value, key) => {
            return (
              <MenuItem eventKey={key} key={key}>{`${key} => ${value} player${value == 1 ? '' : 's'}`}</MenuItem>
            );
          })}
        </SplitButton>

    );
  }
}

render(
  <SetApp />, document.getElementById('content')
);
<|endoftext|>


<commit_before>
import React, { AppRegistry } from 'react-native';

import { Scene, Router, Reducer } from 'react-native-router-flux';

import Login from './js/components/Login';
import TabView from './js/components/TabView';
import MissionsTab from './js/components/MissionsTab';
import TabIcon from './js/components/TabIcon';

/*
const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: 'transparent', justifyContent: 'center',
      alignItems: 'center' },
});
*/

const reducerCreate = params => {
  const defaultReducer = new Reducer(params);
  return (state, action) => {
    console.log('ACTION:', action);
    return defaultReducer(state, action);
  };
};

const App = React.createClass({
  getInitialState() { return { }; },

  render() {
    return (
      <Router createReducer={reducerCreate} sceneStyle={{ backgroundColor: '#F7F7F7' }}>
        <Scene key="root" hideNavBar>
          <Scene key="login"
            component={Login}
            title="Login"
            initial
            style={ { flex: 1, backgroundColor: 'transparent' } }
          />
            <Scene key="tabbar" tabs>
              <Scene key="missions"
                component={MissionsTab}
                title="Missions"
                hideNavBar
                icon={TabIcon}
              />
              <Scene key="profile"
                component={TabView}
                title="Profile"
                hideNavBar
                icon={TabIcon}
              />
              <Scene key="highscore"
                component={TabView}
                title="Highscore"
                hideNavBar
                icon={TabIcon}
              />
              <Scene key="about"
                component={TabView}
                title="About"
                hideNavBar
                icon={TabIcon}
              />
            </Scene>
        </Scene>
      </Router>
    );
  },
});

AppRegistry.registerComponent('Kort', () => App);
<commit_msg>update<commit_after>
import React, { AppRegistry } from 'react-native';

import { Scene, Router, Reducer } from 'react-native-router-flux';

import Login from './js/components/Login';
import TabView from './js/components/TabView';
import MissionsTab from './js/components/MissionsTab';
import TabIcon from './js/components/TabIcon';

/*
const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: 'transparent', justifyContent: 'center',
      alignItems: 'center' },
});
*/

const reducerCreate = params => {
  const defaultReducer = new Reducer(params);
  return (state, action) => {
    console.log('ACTION:', action);
    return defaultReducer(state, action);
  };
};

const App = React.createClass({
  getInitialState() { return { }; },

  render() {
    return (
      <Router createReducer={reducerCreate} sceneStyle={{ backgroundColor: '#F7F7F7' }}>
        <Scene key="root" hideNavBar>
          <Scene key="login"
            component={Login}
            title="Login"
            initial
            style={ { flex: 1, backgroundColor: 'transparent' } }
          />
            <Scene key="tabbar" tabs>
              <Scene key="missions"
                component={MissionsTab}
                title="Missions"
                hideNavBar
                icon={TabIcon}
              />
              <Scene key="highscore"
                component={TabView}
                title="Highscore"
                hideNavBar
                icon={TabIcon}
              />
              <Scene key="profile"
                component={TabView}
                title="Profile"
                hideNavBar
                icon={TabIcon}
              />
              <Scene key="about"
                component={TabView}
                title="About"
                hideNavBar
                icon={TabIcon}
              />
            </Scene>
        </Scene>
      </Router>
    );
  },
});

AppRegistry.registerComponent('Kort', () => App);
<|endoftext|>


<commit_before>// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ngResource'])

.config(function($stateProvider, $urlRouterProvider, $httpProvider) {

  // Ionic uses AngularUI Router which uses the concept of states
  // Learn more here: https://github.com/angular-ui/ui-router
  // Set up the various states which the app can be in.
  // Each state's controller can be found in controllers.js
  $stateProvider.state('home', {
    url: "/",
    templateUrl: "templates/home.html",
    controller: 'HomeCtrl'
  })

  .state('form', {
    url: "/form",
    templateUrl: "templates/form.html",
    controller: 'FormCtrl'
  })

  .state('register', {
    url: "/register",
    templateUrl: "templates/register.html",
    controller: 'RegisterCtrl'
  })

  .state('login', {
    url: "/login",
    templateUrl: "templates/login.html",
    controller: 'LoginCtrl'
  })

  .state('one', {
    url: "/one",
    templateUrl: "templates/one.html",
    controller: 'OneCtrl'
  })

   .state('two', {
   url: "/two",
   templateUrl: "templates/two.html",
   controller: 'TwoCtrl'
  })

   .state('three', {
    url: "/three",
    templateUrl: "templates/three.html",
    controller: 'ThreeCtrl'
  })

   .state('all', {
   url: "/all",
   templateUrl: "templates/all.html",
   controller: 'HomeCtrl'
  })

  .state('1B1', {
  url: "/1B1",
  templateUrl: "templates/1B1.html",
  controller: '1B1Ctrl'
  })

   .state('1B2', {
   url: "/1B2",
   templateUrl: "templates/1B2.html",
   controller: '1B2Ctrl'
  })

  .state('1B3', {
  url: "/1B3",
  templateUrl: "templates/1B3.html",
  controller: '1B3Ctrl'
  })

  .state('2B1', {
  url: "/2B1",
  templateUrl: "templates/2B1.html",
  controller: '2B1Ctrl'
  })

   .state('2B2', {
   url: "/2B2",
   templateUrl: "templates/2B2.html",
   controller: '2B2Ctrl'
  })

  .state('2B3', {
  url: "/2B3",
  templateUrl: "templates/2B3.html",
  controller: '2B3Ctrl'
  })

    .state('2B4', {
  url: "/2B4",
  templateUrl: "templates/2B4.html",
  controller: '2B4Ctrl'
  })

   .state('2B5', {
   url: "/2B5",
   templateUrl: "templates/2B5.html",
   controller: '2B5Ctrl'
  })

  .state('2B6', {
  url: "/2B6",
  templateUrl: "templates/2B6.html",
  controller: '2B6Ctrl'
  })

    .state('3B1', {
  url: "/3B1",
  templateUrl: "templates/3B1.html",
  controller: '3B1Ctrl'
  })

   .state('3B2', {
   url: "/3B2",
   templateUrl: "templates/3B2.html",
   controller: '3B2Ctrl'
  })

  .state('3B3', {
  url: "/3B3",
  templateUrl: "templates/3B3.html",
  controller: '3B3Ctrl'
  })

    .state('3B4', {
  url: "/3B4",
  templateUrl: "templates/3B4.html",
  controller: '3B4Ctrl'
  })

   .state('3B5', {
   url: "/3B5",
   templateUrl: "templates/3B5.html",
   controller: '3B5Ctrl'
  })

  .state('3B6', {
  url: "/3B6",
  templateUrl: "templates/3B6.html",
  controller: '3B6Ctrl'
  })

  .state('C1', {
  url: "/C1",
  templateUrl: "templates/C1.html",
  controller: 'CalendarCtrl'
 })

  .state('C2', {
  url: "/C2",
  templateUrl: "templates/C2.html",
  controller: 'CalendarCtrl'
 })

  .state('C3', {
  url: "/C3",
  templateUrl: "templates/C3.html",
  controller: 'CalendarCtrl'
 })

   .state('C4', {
  url: "/C4",
  templateUrl: "templates/C4.html",
  controller: 'CalendarCtrl'
 })

  .state('C5', {
  url: "/C5",
  templateUrl: "templates/C5.html",
  controller: 'CalendarCtrl'
 })

  .state('C6', {
  url: "/C6",
  templateUrl: "templates/C6.html",
  controller: 'CalendarCtrl'
 })

  .state('C7', {
  url: "/C7",
  templateUrl: "templates/C7.html",
  controller: 'CalendarCtrl'
 })

  .state('C8', {
  url: "/C8",
  templateUrl: "templates/C8.html",
  controller: 'CalendarCtrl'
 })

  .state('C9', {
  url: "/C9",
  templateUrl: "templates/C9.html",
  controller: 'CalendarCtrl'
 })

  .state('C10', {
  url: "/C10",
  templateUrl: "templates/C10.html",
  controller: 'CalendarCtrl'
 })

   .state('C11', {
  url: "/C11",
  templateUrl: "templates/C11.html",
  controller: 'CalendarCtrl'
 })

  .state('C12', {
  url: "/C12",
  templateUrl: "templates/C12.html",
  controller: 'CalendarCtrl'
 })

  .state('C13', {
  url: "/C13",
  templateUrl: "templates/C13.html",
  controller: 'CalendarCtrl'
 })

  .state('C14', {
  url: "/C14",
  templateUrl: "templates/C14.html",
  controller: 'CalendarCtrl'
 })

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/');

  // Register middleware to ensure our auth token is passed to the server
  $httpProvider.interceptors.push('TokenInterceptor');

})

.run(function($window, $location, $ionicPlatform, $rootScope, AuthenticationService) {
  $rootScope.user = {
    name: $window.sessionStorage.name,
    is_admin: $window.sessionStorage.is_admin
  };

  if ($rootScope.user.is_admin) {
    AuthenticationService.isAdmin = true;
  }

  $rootScope.$on('$stateChangeStart',function(event, toState, toParams, fromState, fromParams){
  console.log('$stateChangeStart to '+toState.name+'- fired when the transition begins. toState,toParams : \n',toState, toParams);
});
$rootScope.$on('$stateChangeError',function(event, toState, toParams, fromState, fromParams, error){
  console.log('$stateChangeError - fired when an error occurs during transition.');
  console.log(arguments);
});
$rootScope.$on('$stateChangeSuccess',function(event, toState, toParams, fromState, fromParams){
  console.log('$stateChangeSuccess to '+toState.name+'- fired once the state transition is complete.');
});
$rootScope.$on('$viewContentLoading',function(event, viewConfig){
   console.log('$viewContentLoading - view begins loading - dom not rendered',viewConfig);
});

/* $rootScope.$on('$viewContentLoaded',function(event){
     // runs on individual scopes, so putting it in "run" doesn't work.
     console.log('$viewContentLoaded - fired after dom rendered',event);
   }); */

$rootScope.$on('$stateNotFound',function(event, unfoundState, fromState, fromParams){
  console.log('$stateNotFound '+unfoundState.to+'  - fired when a state cannot be found by its name.');
  console.log(unfoundState, fromState, fromParams);
});

  $rootScope.$on("$stateChangeStart", function(event, toState) {
    //redirect only if both isAuthenticated is false and no token is set

    if (['home', 'login', 'logout', 'register', 'one', 'two', 'three', 'all', 'form', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'C10', 'C11', 'C12', 'C13', 'C14', '1B1', '1B2', '1B3', '2B1', '2B2', '2B3', '2B4', '2B5', '2B6', '3B1', '3B2', '3B3', '3B4', '3B5', '3B6'].indexOf(toState.name) === -1) {
      if (!AuthenticationService.isAuthenticated && !$window.localStorage.token) {
        event.preventDefault();
        $location.path("/home");
      }
    }

  });

  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });
})
<commit_msg>Update app.js<commit_after>// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ngResource'])

.config(function($stateProvider, $urlRouterProvider, $httpProvider) {

  // Ionic uses AngularUI Router which uses the concept of states
  // Learn more here: https://github.com/angular-ui/ui-router
  // Set up the various states which the app can be in.
  // Each state's controller can be found in controllers.js
  $stateProvider.state('home', {
    url: "/",
    templateUrl: "templates/home.html",
    controller: 'HomeCtrl'
  })

  .state('form', {
    url: "/form",
    templateUrl: "templates/form.html",
    controller: 'FormCtrl'
  })

  .state('register', {
    url: "/register",
    templateUrl: "templates/register.html",
    controller: 'RegisterCtrl'
  })

  .state('login', {
    url: "/login",
    templateUrl: "templates/login.html",
    controller: 'LoginCtrl'
  })

  .state('one', {
    url: "/one",
    templateUrl: "templates/one.html",
    controller: 'OneCtrl'
  })

   .state('two', {
   url: "/two",
   templateUrl: "templates/two.html",
   controller: 'TwoCtrl'
  })

   .state('three', {
    url: "/three",
    templateUrl: "templates/three.html",
    controller: 'ThreeCtrl'
  })

   .state('all', {
   url: "/all",
   templateUrl: "templates/all.html",
   controller: 'HomeCtrl'
  })

  .state('1B1', {
  url: "/1B1",
  templateUrl: "templates/1B1.html",
  controller: '1B1Ctrl'
  })

   .state('1B2', {
   url: "/1B2",
   templateUrl: "templates/1B2.html",
   controller: '1B2Ctrl'
  })

  .state('1B3', {
  url: "/1B3",
  templateUrl: "templates/1B3.html",
  controller: '1B3Ctrl'
  })

  .state('2B1', {
  url: "/2B1",
  templateUrl: "templates/2B1.html",
  controller: '2B1Ctrl'
  })

   .state('2B2', {
   url: "/2B2",
   templateUrl: "templates/2B2.html",
   controller: '2B2Ctrl'
  })

  .state('2B3', {
  url: "/2B3",
  templateUrl: "templates/2B3.html",
  controller: '2B3Ctrl'
  })

    .state('2B4', {
  url: "/2B4",
  templateUrl: "templates/2B4.html",
  controller: '2B4Ctrl'
  })

   .state('2B5', {
   url: "/2B5",
   templateUrl: "templates/2B5.html",
   controller: '2B5Ctrl'
  })

  .state('2B6', {
  url: "/2B6",
  templateUrl: "templates/2B6.html",
  controller: '2B6Ctrl'
  })

    .state('3B1', {
  url: "/3B1",
  templateUrl: "templates/3B1.html",
  controller: '3B1Ctrl'
  })

   .state('3B2', {
   url: "/3B2",
   templateUrl: "templates/3B2.html",
   controller: '3B2Ctrl'
  })

  .state('3B3', {
  url: "/3B3",
  templateUrl: "templates/3B3.html",
  controller: '3B3Ctrl'
  })

    .state('3B4', {
  url: "/3B4",
  templateUrl: "templates/3B4.html",
  controller: '3B4Ctrl'
  })

   .state('3B5', {
   url: "/3B5",
   templateUrl: "templates/3B5.html",
   controller: '3B5Ctrl'
  })

  .state('3B6', {
  url: "/3B6",
  templateUrl: "templates/3B6.html",
  controller: '3B6Ctrl'
  })

  .state('C1', {
  url: "/C1",
  templateUrl: "templates/C1.html",
  controller: 'CalendarCtrl'
 })

  .state('C2', {
  url: "/C2",
  templateUrl: "templates/C2.html",
  controller: 'CalendarCtrl'
 })

  .state('C3', {
  url: "/C3",
  templateUrl: "templates/C3.html",
  controller: 'CalendarCtrl'
 })

   .state('C4', {
  url: "/C4",
  templateUrl: "templates/C4.html",
  controller: 'CalendarCtrl'
 })

  .state('C5', {
  url: "/C5",
  templateUrl: "templates/C5.html",
  controller: 'CalendarCtrl'
 })

  .state('C6', {
  url: "/C6",
  templateUrl: "templates/C6.html",
  controller: 'CalendarCtrl'
 })

  .state('C7', {
  url: "/C7",
  templateUrl: "templates/C7.html",
  controller: 'CalendarCtrl'
 })

  .state('C8', {
  url: "/C8",
  templateUrl: "templates/C8.html",
  controller: 'CalendarCtrl'
 })

  .state('C9', {
  url: "/C9",
  templateUrl: "templates/C9.html",
  controller: 'CalendarCtrl'
 })

  .state('C10', {
  url: "/C10",
  templateUrl: "templates/C10.html",
  controller: 'CalendarCtrl'
 })

   .state('C11', {
  url: "/C11",
  templateUrl: "templates/C11.html",
  controller: 'CalendarCtrl'
 })

  .state('C12', {
  url: "/C12",
  templateUrl: "templates/C12.html",
  controller: 'CalendarCtrl'
 })

  .state('C13', {
  url: "/C13",
  templateUrl: "templates/C13.html",
  controller: 'CalendarCtrl'
 })

  .state('C14', {
  url: "/C14",
  templateUrl: "templates/C14.html",
  controller: 'CalendarCtrl'
 })

  .state('C15', {
  url: "/C14",
  templateUrl: "templates/C15.html",
  controller: 'CalendarCtrl'
 })

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/');

  // Register middleware to ensure our auth token is passed to the server
  $httpProvider.interceptors.push('TokenInterceptor');

})

.run(function($window, $location, $ionicPlatform, $rootScope, AuthenticationService) {
  $rootScope.user = {
    name: $window.sessionStorage.name,
    is_admin: $window.sessionStorage.is_admin
  };

  if ($rootScope.user.is_admin) {
    AuthenticationService.isAdmin = true;
  }

  $rootScope.$on('$stateChangeStart',function(event, toState, toParams, fromState, fromParams){
  console.log('$stateChangeStart to '+toState.name+'- fired when the transition begins. toState,toParams : \n',toState, toParams);
});
$rootScope.$on('$stateChangeError',function(event, toState, toParams, fromState, fromParams, error){
  console.log('$stateChangeError - fired when an error occurs during transition.');
  console.log(arguments);
});
$rootScope.$on('$stateChangeSuccess',function(event, toState, toParams, fromState, fromParams){
  console.log('$stateChangeSuccess to '+toState.name+'- fired once the state transition is complete.');
});
$rootScope.$on('$viewContentLoading',function(event, viewConfig){
   console.log('$viewContentLoading - view begins loading - dom not rendered',viewConfig);
});

/* $rootScope.$on('$viewContentLoaded',function(event){
     // runs on individual scopes, so putting it in "run" doesn't work.
     console.log('$viewContentLoaded - fired after dom rendered',event);
   }); */

$rootScope.$on('$stateNotFound',function(event, unfoundState, fromState, fromParams){
  console.log('$stateNotFound '+unfoundState.to+'  - fired when a state cannot be found by its name.');
  console.log(unfoundState, fromState, fromParams);
});

  $rootScope.$on("$stateChangeStart", function(event, toState) {
    //redirect only if both isAuthenticated is false and no token is set

    if (['home', 'login', 'logout', 'register', 'one', 'two', 'three', 'all', 'form', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'C10', 'C11', 'C12', 'C13', 'C14', 'C15', '1B1', '1B2', '1B3', '2B1', '2B2', '2B3', '2B4', '2B5', '2B6', '3B1', '3B2', '3B3', '3B4', '3B5', '3B6'].indexOf(toState.name) === -1) {
      if (!AuthenticationService.isAuthenticated && !$window.localStorage.token) {
        event.preventDefault();
        $location.path("/home");
      }
    }

  });

  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });
})
<|endoftext|>