<commit_before>/* global app:true */

var socket;
var currenttime;
var username='noname';

var width = 400,
	height = 1200,
	cellWidth = 76,
	cellHeight = 72, // cell size
	gapWidth = 12,
	gapHeight = 6,
	menuWidth = 40,
	menuHeight = 40;

var hour = d3.time.format("%I"),
	minute = d3.time.format("%M"),
	month = d3.time.format("%b"),
	weekday = d3.time.format("%a"),
	date = d3.time.format("%d"),
	ampm = d3.time.format("%p"),
	format = d3.time.format("%b/%d %H:%M%p");

(function() {
  'use strict';

	var myClock;

	function myTimer(){
		socket.emit('lookclock');
	}

  var blockdata = [];
  var clockbar = $('#clock_bar');

  var callBlocks = function(ticket){
	// +- 1 hour blocks range
	var beginT = d3.time.hour.floor(ticket);
	beginT = d3.time.hour.offset(beginT, -1);
	var endT = d3.time.hour.offset(beginT, 3);

	socket.emit('timeline', { type: 'callblocks', user:username, begintime: beginT, endtime: endT});
  }

  var draw = function(blockdata){
    d3.select("svg")
       .remove();
	var tip = d3.tip()
		.attr('class', 'd3-tip')
		.direction('e')
		.offset([0,10])
		.html(function(d) {
			return "time: "+d.time;
		});

	var svg = d3.select("#d3Area").append("svg")
		.attr("width", width)
		.attr("height", height)
		.append("g")
		.attr("transform", "translate(24, 24)");

	svg.call(tip);

	var block = svg.selectAll(".block")
		.data(blockdata)
	.enter().append("g")
		.attr("class", "block")
		.attr("transform", function (d,i)
		{
			var dx = (i-i%12)/12*(cellWidth+gapWidth);
			var dy =  i%12 * (cellHeight+gapHeight);
			return "translate(" + dx + ","+ dy + ")";
		})
		.on('mouseover', tip.show)
		.on('mouseout', tip.hide);

	block.append("rect")
		.attr("class", function (d)
		{
			if (d.lock==1){
				class_name="block-locked";
			}else{
				if (d.current==1){
					class_name="block-current";
				}else{
					var class_name="block-default";
				}
			}
			return class_name;
		})
		.attr("width", cellWidth)
		.attr("height", cellHeight)
		.attr("block-hour", function (d,i){
			var class_name;
			var hour = (i-i%12)/12;

			if (hour==1){
				class_name="current";
			}else{
				if (hour>1){
					class_name="future";
				}else{
					var class_name="past";
				}
			}
			return class_name;
		})
		.on('mouseover', tip.show)
		.on('mouseout', tip.hide)
		.on('click', mouseclick);

	block.append("text")
		.attr("class", "block-name")
		.attr("x",10)
		.attr("y",14)
		.attr("dy", ".3em")
		//.style("text-anchor", "middle")
		.text(function(d) {
			var h = d.time.getHours();
			var ampm = (h<12 ? "AM":"PM");
			//h=("0" + h%12).slice(-2);
			h=(h%12);
			if(h==0){h="12";}
			var m = d.time.getMinutes();
			m=("0" + m).slice(-2);
			return h+":"+m+" "+ampm;
		})
		.on('mouseover', tip.show)
		.on('mouseout', tip.hide);

	var svg_info = d3.select("#d3InfoArea").append("svg")
		.attr("width", width)
		.attr("height", height)
		.append("g")
		.attr("transform", "translate(24, 24)");

	var infobox = svg_info.selectAll(".infobox")
		.enter().append("g")
		.attr("class", "infobox");

	block.append("rect")
		.attr("width",300)
		.attr("height",600);

	infobox.append("text")
		.attr("class", "info-text")
		.attr("x",10)
		.attr("y",14)
		.attr("dy", ".3em")
		//.style("text-anchor", "middle")
		.text("Block Info Box");

  }

  function mouseclick(d,i){
  	// reset to default layout
  	d3.selectAll(".block rect").transition().duration(1000)
  		.attr("width", cellWidth)
  		.attr("height", cellHeight);

	// expand the selected block
  	d3.select(this).transition().duration(1000)
        .attr("width", (cellWidth+gapWidth)*(3-(i-i%12)/12)+menuWidth)
        .attr("height", menuHeight);

    d3.select(this).append("text")
		.attr("class", "block-info")
		.attr("x",((cellWidth+gapWidth)*(3-(i-i%12)/12)+40))
		.attr("y",20)
		.attr("dy", ".3em")
		.text(function(d) {
			//d.user_id
			//d.exp_id
			//d.id
			return "block id: "+d.id;
		})
  }

  socket = io.connect('http://171.65.102.132:3006');

  socket.on('postblocks', function(data){
  	blockdata = [];
  	var num_ele = 9;
	for (var i=0;i<=data.length/num_ele;i++){
		var block = new Object();
		block.id = i;

		var d = new Date(0);
		d.setTime(data[i*num_ele]);
		block.time = d;

		block.lock = data[i*num_ele+1];
		block.user_id = data[i*num_ele+2];
		block.exp_id = data[i*num_ele+3];
		block.pattern_id = data[i*num_ele+4];
		block.past = data[i*num_ele+5];
		block.admin = data[i*num_ele+6];
		block.current = data[i*num_ele+7];
		block.image = data[i*num_ele+8];

		blockdata.push(block);
	}
	blockdata.length = blockdata.length-2;
	console.dir(blockdata);
	draw(blockdata);
  });

  socket.on('server_clock', function(data){
  	//console.log(data);
  	clockbar.html(""+data+"");
  });

  socket.on('message', function(msg){
	console.log(msg);
  });

  socket.on('connect', function() {
	console.log("Connected!");
	currenttime = new Date();
	callBlocks(currenttime);
	myClock=setInterval(function(){myTimer()},500);
  });

  socket.on('disconnect', function() {
	console.log('disconnected');
  });

  app = app || {};

  app.Blocks = Backbone.Model.extend({
    url: '/account/timeline/',
    defaults: {
      username: '',
      timestamp: ''
    }
  });

  app.BlocksView = Backbone.View.extend({
    el: '#blocks_nav',
    template: _.template( $('#tmpl-blocks_nav').html() ),
    events: {
      'click .btn-prev': 'reqPrev',
      'click .btn-now': 'reqNow',
      'click .btn-next': 'reqNext'
    },
    initialize: function() {
      this.model = new app.Blocks();
      this.listenTo(this.model, 'sync', this.render);
      this.render();
    },
    render: function() {
      this.$el.html(this.template( this.model.attributes));
    },
    reqPrev: function() {
      currenttime.setHours(currenttime.getHours() - 1);
      callBlocks(currenttime);
    },
    reqNow: function() {
      currenttime = new Date();
      callBlocks(currenttime);
    },
    reqNext: function() {
      currenttime.setHours(currenttime.getHours() + 1);
      callBlocks(currenttime);
    }
  });

  $(document).ready(function() {
    app.blocksView = new app.BlocksView();
  });

}());
<commit_msg>d3 menu<commit_after>/* global app:true */

var socket;
var currenttime;
var username='noname';

var width = 400,
	height = 1200,
	cellWidth = 76,
	cellHeight = 72, // cell size
	gapWidth = 12,
	gapHeight = 6,
	menuWidth = 40,
	menuHeight = 40;

var hour = d3.time.format("%I"),
	minute = d3.time.format("%M"),
	month = d3.time.format("%b"),
	weekday = d3.time.format("%a"),
	date = d3.time.format("%d"),
	ampm = d3.time.format("%p"),
	format = d3.time.format("%b/%d %H:%M%p");

(function() {
  'use strict';

	var myClock;

	function myTimer(){
		socket.emit('lookclock');
	}

  var blockdata = [];
  var clockbar = $('#clock_bar');

  var callBlocks = function(ticket){
	// +- 1 hour blocks range
	var beginT = d3.time.hour.floor(ticket);
	beginT = d3.time.hour.offset(beginT, -1);
	var endT = d3.time.hour.offset(beginT, 3);

	socket.emit('timeline', { type: 'callblocks', user:username, begintime: beginT, endtime: endT});
  }

  var draw = function(blockdata){
    d3.select("svg")
       .remove();
	var tip = d3.tip()
		.attr('class', 'd3-tip')
		.direction('e')
		.offset([0,10])
		.html(function(d) {
			return "time: "+d.time;
		});

	var svg = d3.select("#d3Area").append("svg")
		.attr("width", width)
		.attr("height", height)
		.append("g")
		.attr("transform", "translate(24, 24)");

	svg.call(tip);

	var block = svg.selectAll(".block")
		.data(blockdata)
	.enter().append("g")
		.attr("class", "block")
		.attr("transform", function (d,i)
		{
			var dx = (i-i%12)/12*(cellWidth+gapWidth);
			var dy =  i%12 * (cellHeight+gapHeight);
			return "translate(" + dx + ","+ dy + ")";
		})
		.on('mouseover', tip.show)
		.on('mouseout', tip.hide);

	block.append("rect")
		.attr("class", function (d)
		{
			if (d.lock==1){
				class_name="block-locked";
			}else{
				if (d.current==1){
					class_name="block-current";
				}else{
					var class_name="block-default";
				}
			}
			return class_name;
		})
		.attr("width", cellWidth)
		.attr("height", cellHeight)
		.attr("block-hour", function (d,i){
			var class_name;
			var hour = (i-i%12)/12;

			if (hour==1){
				class_name="current";
			}else{
				if (hour>1){
					class_name="future";
				}else{
					var class_name="past";
				}
			}
			return class_name;
		})
		.on('mouseover', tip.show)
		.on('mouseout', tip.hide)
		.on('click', mouseclick);

	block.append("text")
		.attr("class", "block-name")
		.attr("x",10)
		.attr("y",14)
		.attr("dy", ".3em")
		//.style("text-anchor", "middle")
		.text(function(d) {
			var h = d.time.getHours();
			var ampm = (h<12 ? "AM":"PM");
			//h=("0" + h%12).slice(-2);
			h=(h%12);
			if(h==0){h="12";}
			var m = d.time.getMinutes();
			m=("0" + m).slice(-2);
			return h+":"+m+" "+ampm;
		})
		.on('mouseover', tip.show)
		.on('mouseout', tip.hide);

	var svg_info = d3.select("#d3InfoArea").append("svg")
		.attr("width", width)
		.attr("height", height)
		.append("g")
		.attr("transform", "translate(24, 24)");

	var infobox = svg_info.selectAll(".infobox")
	.enter().append("g")
		.attr("class", "infobox")
		.attr("transform", function (d,i)
		{
			var dx = 0;
			var dy = 0;
			return "translate(" + dx + ","+ dy + ")";
		});

	infobox.append("rect")
		.attr("class", "infobox")
		.attr("width",300)
		.attr("height",600);

	infobox.append("text")
		.attr("class", "info-text")
		.attr("x",10)
		.attr("y",14)
		.attr("dy", ".3em")
		//.style("text-anchor", "middle")
		.text("Block Info Box");

  }

  function mouseclick(d,i){
  	// reset to default layout
  	d3.selectAll(".block rect").transition().duration(1000)
  		.attr("width", cellWidth)
  		.attr("height", cellHeight);

	// expand the selected block
  	d3.select(this).transition().duration(1000)
        .attr("width", (cellWidth+gapWidth)*(3-(i-i%12)/12)+menuWidth)
        .attr("height", menuHeight);

    d3.select(this).append("text")
		.attr("class", "block-info")
		.attr("x",((cellWidth+gapWidth)*(3-(i-i%12)/12)+40))
		.attr("y",20)
		.attr("dy", ".3em")
		.text(function(d) {
			//d.user_id
			//d.exp_id
			//d.id
			return "block id: "+d.id;
		})
  }

  socket = io.connect('http://171.65.102.132:3006');

  socket.on('postblocks', function(data){
  	blockdata = [];
  	var num_ele = 9;
	for (var i=0;i<=data.length/num_ele;i++){
		var block = new Object();
		block.id = i;

		var d = new Date(0);
		d.setTime(data[i*num_ele]);
		block.time = d;

		block.lock = data[i*num_ele+1];
		block.user_id = data[i*num_ele+2];
		block.exp_id = data[i*num_ele+3];
		block.pattern_id = data[i*num_ele+4];
		block.past = data[i*num_ele+5];
		block.admin = data[i*num_ele+6];
		block.current = data[i*num_ele+7];
		block.image = data[i*num_ele+8];

		blockdata.push(block);
	}
	blockdata.length = blockdata.length-2;
	console.dir(blockdata);
	draw(blockdata);
  });

  socket.on('server_clock', function(data){
  	//console.log(data);
  	clockbar.html(""+data+"");
  });

  socket.on('message', function(msg){
	console.log(msg);
  });

  socket.on('connect', function() {
	console.log("Connected!");
	currenttime = new Date();
	callBlocks(currenttime);
	myClock=setInterval(function(){myTimer()},500);
  });

  socket.on('disconnect', function() {
	console.log('disconnected');
  });

  app = app || {};

  app.Blocks = Backbone.Model.extend({
    url: '/account/timeline/',
    defaults: {
      username: '',
      timestamp: ''
    }
  });

  app.BlocksView = Backbone.View.extend({
    el: '#blocks_nav',
    template: _.template( $('#tmpl-blocks_nav').html() ),
    events: {
      'click .btn-prev': 'reqPrev',
      'click .btn-now': 'reqNow',
      'click .btn-next': 'reqNext'
    },
    initialize: function() {
      this.model = new app.Blocks();
      this.listenTo(this.model, 'sync', this.render);
      this.render();
    },
    render: function() {
      this.$el.html(this.template( this.model.attributes));
    },
    reqPrev: function() {
      currenttime.setHours(currenttime.getHours() - 1);
      callBlocks(currenttime);
    },
    reqNow: function() {
      currenttime = new Date();
      callBlocks(currenttime);
    },
    reqNext: function() {
      currenttime.setHours(currenttime.getHours() + 1);
      callBlocks(currenttime);
    }
  });

  $(document).ready(function() {
    app.blocksView = new app.BlocksView();
  });

}());
<|endoftext|>


<commit_before>{
    doc_type: 'visifile'
    ,
    name: 'search'
    ,
    version: 1
    ,
    type: 'app'
    ,
    text: 'Search app'

    ,
    initText: 'Search is ALIVE!!!!'
    ,
    events: {
        "This will return the search app": {
            on: "app",
            do: function(args, returnfn) {
                returnfn(
                    new Moon({
                      el: "#" + args.root_element
                      ,
                      template: "
this is the moon seach app
"
                      ,
                      data: {
                        msg: ""
                    },
                    methods: {
                    },
                      store: store
                    })
                )

            }, end: null
        }

    }

}
<commit_msg>Can change data in the search app<commit_after>{
    doc_type: 'visifile'
    ,
    name: 'search'
    ,
    version: 1
    ,
    type: 'app'
    ,
    text: 'Search app'

    ,
    initText: 'Search is ALIVE!!!!'
    ,
    events: {
        "This will return the search app": {
            on: "app",
            do: function(args, returnfn) {
                var mm = new Moon({
                  el: "#" + args.root_element
                  ,
                  template: "
this is the moon seach app {{msg}}
"
                  ,
                  data: {
                    msg: "..."
                },
                methods: {
                    search: function() {
                        callDriverMethod( "commandLine",
                                          "ls"
                                          ,{}
                                    ,
                                    function(result) {
                                        console.log("3) returned result: " + JSON.stringify(result,null,2))
                                    })
                    }
                },
                  store: store
                })
                setTimeout(function() {
                    mm.set("msg", "zoo")
                    alert("done")
                }
                ,1000)

                returnfn({})

            }, end: null
        }

    }

}
<|endoftext|>


<commit_before>var Entities = require('../src/entities').Entities;
var Runner = require('../src/runner').Runner;
var Collider = require('../src/collider').Collider;

var MockCoquette = function() {
  this.game = "woo";
  this.entities = new Entities(this, this.game);
  this.runner = new Runner(this);
  this.collider = new Collider(this);
};

var Thing = function() {};

describe('Entities', function() {
  describe('update()', function() {
    it('should call update all entities', function() {
      var update = function() { this.updateCalled = true; };
      var c = new MockCoquette();
      c.entities.all().push({ update: update}, { update: update });
      c.entities.update();
      expect(c.entities.all()[0].updateCalled).toEqual(true);
      expect(c.entities.all()[1].updateCalled).toEqual(true);
    });

    it('should pass interval when call update on entity', function() {
      var c = new MockCoquette();
      c.entities.all().push({ update: function(interval) { this.interval = interval; }});
      c.entities.update(5);
      expect(c.entities.all()[0].interval).toEqual(5);
    });
  });

  describe('all()', function() {
    it('should return all entities when no constructor passed', function() {
      var c = new MockCoquette();
      c.entities.all().push({ }, { });
      expect(c.entities.all().length).toEqual(2);
    });

    it('should return only entities made w constructor when constructor passed', function() {
      var c = new MockCoquette();
      c.entities.all().push({}, new Thing(), new Thing(), {});
      expect(c.entities.all().length).toEqual(4);
      expect(c.entities.all(Thing).length).toEqual(2);
    });
  });

  describe('create()', function() {
    it('should create the thing you ask it to create', function() {
      var c = new MockCoquette();
      c.entities.create(Thing);
      c.runner.update();
      expect(c.entities.all()[0] instanceof Thing).toEqual(true);
    });

    it('should be ok without passed settings ', function() {
      var c = new MockCoquette();
      c.entities.create(Thing);
      c.runner.update();
      expect(c.entities.all().length).toEqual(1);
    });

    it('should be ok without passed callback', function() {
      var c = new MockCoquette();
      c.entities.create(Thing);
      c.runner.update();
      expect(c.entities.all().length).toEqual(1);
    });

    it('should pass game to obj constructor', function() {
      var c = new MockCoquette();
      var Thing = function(game) {
        this.called = true;
        expect(game).toEqual(c.game);
      };
      c.entities.create(Thing, { a:1 });
      c.runner.update();
      expect(c.entities.all()[0].called).toEqual(true);
    });

    it('should pass settings to obj constructor', function() {
      var c = new MockCoquette();
      var Thing = function(__, settings) {
        this.called = true;
        expect(settings).toEqual({ a:1 });
      };
      c.entities.create(Thing, { a:1 });
      c.runner.update();
      expect(c.entities.all()[0].called).toEqual(true);
    });

    it('should call callback after obj has been created', function() {
      var c = new MockCoquette();
      var called = false;
      c.entities.create(Thing, { a:1 }, function() {
        called = true;
      });
      c.runner.update();
      expect(called).toEqual(true);
    });
  });

  describe('destroy()', function() {
    it('should destroy the thing you ask it to destroy', function() {
      var c = new MockCoquette();
      c.entities.create(Thing);
      c.runner.update();
      expect(c.entities.all()[0] instanceof Thing).toEqual(true);
      c.entities.destroy(c.entities.all()[0]);
      c.runner.update();
      expect(c.entities.all()[0]).toBeUndefined();
    });

    it('should call callback after obj has been destroyed', function() {
      var c = new MockCoquette();
      var called = false;
      c.entities.create(Thing);
      c.runner.update();
      expect(c.entities.all()[0] instanceof Thing).toEqual(true);
      c.entities.destroy(c.entities.all()[0], function() {
        called = true;
      });
      c.runner.update();
      expect(called).toEqual(true);
    });
  });
});
<commit_msg>Update entities tests to mutate raw _entities<commit_after>var Entities = require('../src/entities').Entities;
var Runner = require('../src/runner').Runner;
var Collider = require('../src/collider').Collider;

var MockCoquette = function() {
  this.game = "woo";
  this.entities = new Entities(this, this.game);
  this.runner = new Runner(this);
  this.collider = new Collider(this);
};

var Thing = function() {};

describe('Entities', function() {
  describe('update()', function() {
    it('should call update all entities', function() {
      var update = function() { this.updateCalled = true; };
      var c = new MockCoquette();
      c.entities._entities.push({ update: update}, { update: update });
      c.entities.update();
      expect(c.entities.all()[0].updateCalled).toEqual(true);
      expect(c.entities.all()[1].updateCalled).toEqual(true);
    });

    it('should pass interval when call update on entity', function() {
      var c = new MockCoquette();
      c.entities._entities.push({ update: function(interval) { this.interval = interval; }});
      c.entities.update(5);
      expect(c.entities.all()[0].interval).toEqual(5);
    });
  });

  describe('all()', function() {
    it('should return all entities when no constructor passed', function() {
      var c = new MockCoquette();
      c.entities._entities.push({ }, { });
      expect(c.entities.all().length).toEqual(2);
    });

    it('should return only entities made w constructor when constructor passed', function() {
      var c = new MockCoquette();
      c.entities._entities.push({}, new Thing(), new Thing(), {});
      expect(c.entities.all().length).toEqual(4);
      expect(c.entities.all(Thing).length).toEqual(2);
    });
  });

  describe('create()', function() {
    it('should create the thing you ask it to create', function() {
      var c = new MockCoquette();
      c.entities.create(Thing);
      c.runner.update();
      expect(c.entities.all()[0] instanceof Thing).toEqual(true);
    });

    it('should be ok without passed settings ', function() {
      var c = new MockCoquette();
      c.entities.create(Thing);
      c.runner.update();
      expect(c.entities.all().length).toEqual(1);
    });

    it('should be ok without passed callback', function() {
      var c = new MockCoquette();
      c.entities.create(Thing);
      c.runner.update();
      expect(c.entities.all().length).toEqual(1);
    });

    it('should pass game to obj constructor', function() {
      var c = new MockCoquette();
      var Thing = function(game) {
        this.called = true;
        expect(game).toEqual(c.game);
      };
      c.entities.create(Thing, { a:1 });
      c.runner.update();
      expect(c.entities.all()[0].called).toEqual(true);
    });

    it('should pass settings to obj constructor', function() {
      var c = new MockCoquette();
      var Thing = function(__, settings) {
        this.called = true;
        expect(settings).toEqual({ a:1 });
      };
      c.entities.create(Thing, { a:1 });
      c.runner.update();
      expect(c.entities.all()[0].called).toEqual(true);
    });

    it('should call callback after obj has been created', function() {
      var c = new MockCoquette();
      var called = false;
      c.entities.create(Thing, { a:1 }, function() {
        called = true;
      });
      c.runner.update();
      expect(called).toEqual(true);
    });
  });

  describe('destroy()', function() {
    it('should destroy the thing you ask it to destroy', function() {
      var c = new MockCoquette();
      c.entities.create(Thing);
      c.runner.update();
      expect(c.entities.all()[0] instanceof Thing).toEqual(true);
      c.entities.destroy(c.entities.all()[0]);
      c.runner.update();
      expect(c.entities.all()[0]).toBeUndefined();
    });

    it('should call callback after obj has been destroyed', function() {
      var c = new MockCoquette();
      var called = false;
      c.entities.create(Thing);
      c.runner.update();
      expect(c.entities.all()[0] instanceof Thing).toEqual(true);
      c.entities.destroy(c.entities.all()[0], function() {
        called = true;
      });
      c.runner.update();
      expect(called).toEqual(true);
    });
  });
});
<|endoftext|>


<commit_before>/*jslint browser: true, plusplus: true */
/*global jQuery, UWCanvas */
(function ($) {
    'use strict';

    var simcheck_info = '
Try SimCheck, the new plagiarism detection tool.  Did the course you're copying use VeriCite for plagiarism detection? Starting June 15th, 2020, all new and copied assignments must use SimCheck instead. After copying the course, you'll need to change each assignment to use SimCheck.
',
        panopto_info = '
Access to Panopto recordings: When copying any Canvas content from one course to another, students in the new course will be granted access to the Panopto recordings in the original course. You may remove access to recordings.
';

    // Custom text for simcheck
    $('#content').whenExists(function () {
        $(this).prepend(panopto_info);
        $(this).prepend(simcheck_info);
    });
}(jQuery));
<commit_msg>updates course migration content<commit_after>/*jslint browser: true, plusplus: true */
/*global jQuery, UWCanvas */
(function ($) {
    'use strict';

    var zoom_info = '
Zoom meeting access: When copying all content from a Canvas course, calendar events for Zoom meetings scheduled using the Zoom app in Canvas are also copied. To prevent students from accessing previous Zoom meeting links you can:

Delete individual calendar events containing previous Zoom meeting links, or

Select specific content to copy, and exclude all calendar events from being copied

',
        panopto_info = '
Access to Panopto recordings: When copying any Canvas content from one course to another, students in the new course will be granted access to the Panopto recordings in the original course. You may remove access to recordings.
';

    // Custom text for migrating course content
    $('#content').whenExists(function () {
        $(this).prepend(panopto_info);
        $(this).prepend(zoom_info);
    });
}(jQuery));
<|endoftext|>


<commit_before>import {Socket} from "phoenix"

// let socket = new Socket("/ws")
// socket.connect()
// socket.join("topic:subtopic", {}).receive("ok", chan => {
// })

let App = {
}

export default App
<commit_msg>updated example channel info in the app.js<commit_after>import {Socket} from "phoenix"

// let socket = new Socket("/ws")
// socket.connect()
// let chan = socket.chan("topic:subtopic", {})
// chan.join().receive("ok", chan => {
//   console.log("Success!")
// })

let App = {
}

export default App
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2014 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var $documents = [];

if ( window ) $documents.push(window.document);

// TODO: clean this up, hide $WID__ in closure
var $WID__ = 0;
function $addWindow(w) {
   w.window.$WID = $WID__++;
   $documents.push(w.document);
}
function $removeWindow(w) {
  for ( var i = $documents.length - 1 ; i >= 0 ; i-- ) {
    if ( ! $documents[i].defaultView || $documents[i].defaultView === w )
      $documents.splice(i,1);
  }
}

/** Replacement for getElementById **/
// TODO(kgr): remove this is deprecated, use X.$ instead()
var $ = function (id) {
  console.log('Deprecated use of GLOBAL.$.');
  for ( var i = 0 ; i < $documents.length ; i++ ) {
    if ( document.FOAM_OBJECTS && document.FOAM_OBJECTS[id] )
      return document.FOAM_OBJECTS[id];

    var ret = $documents[i].getElementById(id);

    if ( ret ) return ret;
  }
  return undefined;
};
/** Replacement for getElementByClassName **/
// TODO(kgr): remove this is deprecated, use X.$$ instead()
var $$ = function (cls) {
  console.log('Deprecated use of GLOBAL.$$.');
  for ( var i = 0 ; i < $documents.length ; i++ ) {
    var ret = $documents[i].getElementsByClassName(cls);

    if ( ret.length > 0 ) return ret;
  }
  return [];
};

var FOAM = function(map, opt_X) {
   var obj = JSONUtil.mapToObj(opt_X || X, map);
   return obj;
};

/**
 * Register a lazy factory for the specified name within a
 * specified context.
 * The first time the name is looked up, the factory will be invoked
 * and its value will be stored in the named slot and then returned.
 * Future lookups to the same slot will return the originally created
 * value.
 **/
FOAM.putFactory = function(ctx, name, factory) {
  ctx.__defineGetter__(name, function() {
    console.log('Bouncing Factory: ', name);
    delete ctx[name];
    return ctx[name] = factory();
  });
};

var   USED_MODELS = {};
var UNUSED_MODELS = {};
var NONMODEL_INSTANCES = {}; // for things such as interfaces

FOAM.browse = function(model, opt_dao, opt_X) {
   var Y = opt_X || X.sub(undefined, "FOAM BROWSER");

   if ( typeof model === 'string' ) model = Y[model];

   var dao = opt_dao || Y[model.name + 'DAO'] || Y[model.plural];

   if ( ! dao ) {
      dao = Y.StorageDAO.create({ model: model });
      Y[model.name + 'DAO'] = dao;
   }

   var ctrl = Y.DAOController.create({
     model:     model,
     dao:       dao,
     useSearchView: false
   });

  if ( ! Y.stack ) {
    var w = opt_X ? opt_X.window : window;
    var win = Y.Window.create({ window: w });

    Y.stack = Y.StackView.create();
    win.view = Y.stack;
    Y.stack.setTopView(ctrl);
  } else {
    Y.stack.pushView(ctrl);
  }
};

FOAM.lookup = function(key, opt_X) {
  if ( ! ( typeof key === 'string' ) ) return key;

  var path = key.split('.');
  var root = opt_X || X;
  for ( var i = 0 ; root && i < path.length ; i++ ) root = root[path[i]];

  return root;
};

function arequire(modelName, opt_X) {
  var X = opt_X || X;
  var model = FOAM.lookup(modelName, X);

  if ( ! model ) {
    console.warn('Unknown Model in arequire: ', modelName);
    return aconstant(undefined);
  }

  /** This is so that if the model is arequire'd concurrently the
   *  initialization isn't done more than once.
   **/
  if ( ! model ) { console.log(modelName, 'not found'); return; }

  return arequireModel(model, X);
}

function arequireModel(model, X) {
  if ( ! model.required__ ) {
    var args = [];

    if ( model.extendsModel ) args.push(arequire(model.extendsModel, X));

    // TODO(kgr): eventually this should just call the arequire() method on the Model
    if ( model.templates ) for ( var i = 0 ; i < model.templates.length ; i++ ) {
      var t = model.templates[i];
      args.push(aseq(
        aevalTemplate(model.templates[i]),
        (function(t) { return function(ret, m) {
          model.getPrototype()[t.name] = m;
          ret();
        };})(t)
      ));
    }

    // Also arequire required Models.
    for ( var i = 0 ; i < model.requires.length ; i++ ) {
      var r = model.requires[i];
      var m = r.split(' as ');
      args.push(arequire(m[0]));
    }

    model.required__ = amemo(aseq(
      apar.apply(apar, args),
      aconstant(model)));
  }

  return model.required__;
}

var FOAM_POWERED = '\
\
FOAM\
 POWERED';

function packagePath(X, path) {
  function packagePath_(Y, path, i) {
    return i == path.length ? Y : packagePath_(Y[path[i]] || ( Y[path[i]] = {} ), path, i+1);
  }
  return path ? packagePath_(X, path.split('.'), 0) : X;
}

function registerModel(model, opt_name) {
  var root = this;

  function contextualizeModel(path, model, name) {
    if ( ! model.getPrototype ) debugger;

//    console.log('contextulizeModel: ', model.name, ' in ', this.toString());

    // Model which creates Objects with Context X
    var xModel = root == X ? model : {
      __proto__: model,
      create: function(args, opt_X) {
        return model.create(args, opt_X || root);
      }
    };

    Object.defineProperty(
      path,
      name,
      {
        get: function() {
          var THIS = this.__this__ || this;
          if ( THIS === root ) return xModel;
          THIS.registerModel(model, name);
          return THIS[name];
        },
        configurable: true
      });
  }

  var name    = model.name;
  var package = model.package;

  if ( opt_name ) {
    var a = opt_name.split('.');
    name = a.pop();
    package = a.join('.');
  }

  if ( package ) {
    var path = packagePath(root, package);
    Object.defineProperty(path, name, { value: model, configurable: true });
  } else {
    contextualizeModel(root, model, name)
  }

  this.registerModel_(model);
}

function CLASS(m) {

  /** Lazily create and register Model first time it's accessed. **/
  function registerModelLatch(path, m) {
    var id = m.package ? m.package + '.' + m.name : m.name;

    UNUSED_MODELS[id] = true;

    // TODO(adamvy): Remove this once we no longer have code depending on models to being in the global scope.
    if ( ! m.package )
      Object.defineProperty(GLOBAL, m.name, { get: function() { return path[m.name]; }, configurable: true });

    Object.defineProperty(path, m.name, {
      get: function () {
        USED_MODELS[id] = true;
        delete UNUSED_MODELS[id];
        Object.defineProperty(path, m.name, {value: null, configurable: true});
        // TODO: Workaround for apps that redefine the top level X
        _ROOT_X.registerModel(JSONUtil.mapToObj(X, m, Model));
        return this[m.name];
      },
      configurable: true
    });
  }

  if ( document && document.currentScript ) m.sourcePath = document.currentScript.src;

  registerModelLatch(packagePath(X, m.package), m);
}

var MODEL = CLASS;

function INTERFACE(imodel) {
  // Unless in DEBUG mode, just discard interfaces as they're only used for type checking.
  // if ( ! DEBUG ) return;
  var i = JSONUtil.mapToObj(X, imodel, Interface);
  packagePath(X, i.package)[i.name] = i;

  var id = i.package ? i.package + '.' + i.name : i.name;
  NONMODEL_INSTANCES[id] = true;
}

/** Called when a Model is registered. **/
function registerModel_(m) {
  // NOP
}
<commit_msg>Removed 'Deprecated use of GLOBAL...' warnings.<commit_after>/**
 * @license
 * Copyright 2014 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var $documents = [];

if ( window ) $documents.push(window.document);

// TODO: clean this up, hide $WID__ in closure
var $WID__ = 0;
function $addWindow(w) {
   w.window.$WID = $WID__++;
   $documents.push(w.document);
}
function $removeWindow(w) {
  for ( var i = $documents.length - 1 ; i >= 0 ; i-- ) {
    if ( ! $documents[i].defaultView || $documents[i].defaultView === w )
      $documents.splice(i,1);
  }
}

/** Replacement for getElementById **/
// TODO(kgr): remove this is deprecated, use X.$ instead()
var $ = function (id) {
//  console.log('Deprecated use of GLOBAL.$.');
  for ( var i = 0 ; i < $documents.length ; i++ ) {
    if ( document.FOAM_OBJECTS && document.FOAM_OBJECTS[id] )
      return document.FOAM_OBJECTS[id];

    var ret = $documents[i].getElementById(id);

    if ( ret ) return ret;
  }
  return undefined;
};
/** Replacement for getElementByClassName **/
// TODO(kgr): remove this is deprecated, use X.$$ instead()
var $$ = function (cls) {
//  console.log('Deprecated use of GLOBAL.$$.');
  for ( var i = 0 ; i < $documents.length ; i++ ) {
    var ret = $documents[i].getElementsByClassName(cls);

    if ( ret.length > 0 ) return ret;
  }
  return [];
};

var FOAM = function(map, opt_X) {
   var obj = JSONUtil.mapToObj(opt_X || X, map);
   return obj;
};

/**
 * Register a lazy factory for the specified name within a
 * specified context.
 * The first time the name is looked up, the factory will be invoked
 * and its value will be stored in the named slot and then returned.
 * Future lookups to the same slot will return the originally created
 * value.
 **/
FOAM.putFactory = function(ctx, name, factory) {
  ctx.__defineGetter__(name, function() {
    console.log('Bouncing Factory: ', name);
    delete ctx[name];
    return ctx[name] = factory();
  });
};

var   USED_MODELS = {};
var UNUSED_MODELS = {};
var NONMODEL_INSTANCES = {}; // for things such as interfaces

FOAM.browse = function(model, opt_dao, opt_X) {
   var Y = opt_X || X.sub(undefined, "FOAM BROWSER");

   if ( typeof model === 'string' ) model = Y[model];

   var dao = opt_dao || Y[model.name + 'DAO'] || Y[model.plural];

   if ( ! dao ) {
      dao = Y.StorageDAO.create({ model: model });
      Y[model.name + 'DAO'] = dao;
   }

   var ctrl = Y.DAOController.create({
     model:     model,
     dao:       dao,
     useSearchView: false
   });

  if ( ! Y.stack ) {
    var w = opt_X ? opt_X.window : window;
    var win = Y.Window.create({ window: w });

    Y.stack = Y.StackView.create();
    win.view = Y.stack;
    Y.stack.setTopView(ctrl);
  } else {
    Y.stack.pushView(ctrl);
  }
};

FOAM.lookup = function(key, opt_X) {
  if ( ! ( typeof key === 'string' ) ) return key;

  var path = key.split('.');
  var root = opt_X || X;
  for ( var i = 0 ; root && i < path.length ; i++ ) root = root[path[i]];

  return root;
};

function arequire(modelName, opt_X) {
  var X = opt_X || X;
  var model = FOAM.lookup(modelName, X);

  if ( ! model ) {
    console.warn('Unknown Model in arequire: ', modelName);
    return aconstant(undefined);
  }

  /** This is so that if the model is arequire'd concurrently the
   *  initialization isn't done more than once.
   **/
  if ( ! model ) { console.log(modelName, 'not found'); return; }

  return arequireModel(model, X);
}

function arequireModel(model, X) {
  if ( ! model.required__ ) {
    var args = [];

    if ( model.extendsModel ) args.push(arequire(model.extendsModel, X));

    // TODO(kgr): eventually this should just call the arequire() method on the Model
    if ( model.templates ) for ( var i = 0 ; i < model.templates.length ; i++ ) {
      var t = model.templates[i];
      args.push(aseq(
        aevalTemplate(model.templates[i]),
        (function(t) { return function(ret, m) {
          model.getPrototype()[t.name] = m;
          ret();
        };})(t)
      ));
    }

    // Also arequire required Models.
    for ( var i = 0 ; i < model.requires.length ; i++ ) {
      var r = model.requires[i];
      var m = r.split(' as ');
      args.push(arequire(m[0]));
    }

    model.required__ = amemo(aseq(
      apar.apply(apar, args),
      aconstant(model)));
  }

  return model.required__;
}

var FOAM_POWERED = '\
\
FOAM\
 POWERED';

function packagePath(X, path) {
  function packagePath_(Y, path, i) {
    return i == path.length ? Y : packagePath_(Y[path[i]] || ( Y[path[i]] = {} ), path, i+1);
  }
  return path ? packagePath_(X, path.split('.'), 0) : X;
}

function registerModel(model, opt_name) {
  var root = this;

  function contextualizeModel(path, model, name) {
    if ( ! model.getPrototype ) debugger;

//    console.log('contextulizeModel: ', model.name, ' in ', this.toString());

    // Model which creates Objects with Context X
    var xModel = root == X ? model : {
      __proto__: model,
      create: function(args, opt_X) {
        return model.create(args, opt_X || root);
      }
    };

    Object.defineProperty(
      path,
      name,
      {
        get: function() {
          var THIS = this.__this__ || this;
          if ( THIS === root ) return xModel;
          THIS.registerModel(model, name);
          return THIS[name];
        },
        configurable: true
      });
  }

  var name    = model.name;
  var package = model.package;

  if ( opt_name ) {
    var a = opt_name.split('.');
    name = a.pop();
    package = a.join('.');
  }

  if ( package ) {
    var path = packagePath(root, package);
    Object.defineProperty(path, name, { value: model, configurable: true });
  } else {
    contextualizeModel(root, model, name)
  }

  this.registerModel_(model);
}

function CLASS(m) {

  /** Lazily create and register Model first time it's accessed. **/
  function registerModelLatch(path, m) {
    var id = m.package ? m.package + '.' + m.name : m.name;

    UNUSED_MODELS[id] = true;

    // TODO(adamvy): Remove this once we no longer have code depending on models to being in the global scope.
    if ( ! m.package )
      Object.defineProperty(GLOBAL, m.name, { get: function() { return path[m.name]; }, configurable: true });

    Object.defineProperty(path, m.name, {
      get: function () {
        USED_MODELS[id] = true;
        delete UNUSED_MODELS[id];
        Object.defineProperty(path, m.name, {value: null, configurable: true});
        // TODO: Workaround for apps that redefine the top level X
        _ROOT_X.registerModel(JSONUtil.mapToObj(X, m, Model));
        return this[m.name];
      },
      configurable: true
    });
  }

  if ( document && document.currentScript ) m.sourcePath = document.currentScript.src;

  registerModelLatch(packagePath(X, m.package), m);
}

var MODEL = CLASS;

function INTERFACE(imodel) {
  // Unless in DEBUG mode, just discard interfaces as they're only used for type checking.
  // if ( ! DEBUG ) return;
  var i = JSONUtil.mapToObj(X, imodel, Interface);
  packagePath(X, i.package)[i.name] = i;

  var id = i.package ? i.package + '.' + i.name : i.name;
  NONMODEL_INSTANCES[id] = true;
}

/** Called when a Model is registered. **/
function registerModel_(m) {
  // NOP
}
<|endoftext|>


<commit_before>// Import libs
var Asteroid = require("asteroid");
var five = require("johnny-five");

// Get custom meteor port from node arguments
if (process.argv[2]) {
    var port = process.argv[2]
} else {
    var port = 3000; // Standard meteor port
}

// Connect to the OpenWall Meteor backend
var OpenWall = new Asteroid("localhost:" + port);
var collection = OpenWall.getCollection("controller");
var controller = collection.reactiveQuery({});
OpenWall.on("connected", function () {
    console.log("Asteroid connected to Meteor");
});

var currentControllerState = {};

var arduino = new five.Board();
arduino.on("ready", function () {

    motors = [
        {
            stepPin: 3,
            dirPin: 4,
            stepsFromStart: 0,
            stepsForCheckpoint1: 0,
            stepsForCheckpoint2: 0,
            stepsForCheckpoint3: 0
        }, {
            stepPin: 12,
            dirPin: 13,
            stepsFromStart: 0,
            stepsForCheckpoint1: 0,
            stepsForCheckpoint2: 0,
            stepsForCheckpoint3: 0
        }
    ];

    var stepper0 = five.Stepper({
        type: five.Stepper.TYPE.DRIVER,
        stepsPerRev: 200,
        pins: {
            step: motors[0].stepPin,
            dir: motors[0].dirPin
        }
    });
    var stepper1 = five.Stepper({
        type: five.Stepper.TYPE.DRIVER,
        stepsPerRev: 200,
        pins: {
            step: motors[1].stepPin,
            dir: motors[1].dirPin
        }
    });

    // radius for the checkPoint in steps relative to the stepperMotor
    var radius = stepper1.stepsPerRev * 2;

    var maxHeight = '';

    // Checkpoint LED's
    var led1 = new five.Led(6);
    arduino.repl.inject({
        led: led1
    });

    var led2 = new five.Led(7);
    arduino.repl.inject({
        led: led2
    });

    var led3 = new five.Led(8);
    arduino.repl.inject({
        led: led3
    });

    controller.on('change', function () {

        controller.result = controller.result[0];

        // set various locations on the gamefield
        if (currentControllerState.calibrateStart != controller.result.calibrateStart) {
            motors[0].stepsFromStart = 0;
            motors[1].stepsFromStart = 0;
        }

        if (currentControllerState.calibrateCheckPoint1 != controller.result.calibrateCheckPoint1) {
            motors[0].stepsForCheckPoint1 = motors[0].stepsFromStart;
            motors[1].stepsForCheckpoint1 = motors[1].stepsFromStart;
        }

        if (currentControllerState.calibrateCheckPoint2 != controller.result.calibrateCheckPoint2) {
            motors[0].stepsForCheckPoint2 = motors[0].stepsFromStart;
            motors[1].stepsForCheckpoint2 = motors[1].stepsFromStart;
        }

        if (currentControllerState.calibrateCheckPoint3 != controller.result.calibrateCheckPoint3) {
            motors[0].stepsForCheckPoint3 = motors[0].stepsFromStart;
            motors[1].stepsForCheckpoint3 = motors[1].stepsFromStart;
        }

        if (currentControllerState.calibrateMaxHeight != controller.result.calibrateMaxHeight) {
            maxHeight = motors[0].stepsFromStart + motors[1].stepsFromStart
        }

        if (currentControllerState.removeMaxHeight != controller.result.removeMaxHeight) {
            maxHeight = '';
        }

        // change direction of the stepper-Rotation
        if (currentControllerState.state1 != controller.result.state1) {
            motors[0].speed = controller.result.state1 * (-1);
        }

        if (currentControllerState.state2 != controller.result.state2) {
            motors[1].speed = controller.result.state2 * (-1);
        }

        // fall back to startingPoint
        if (currentControllerState.movingToStart != controller.result.movingToStart) {
            if (controller.result.movingToStart == true) {

                var finish0 = false;
                var finish1 = false;

                if (motors[0].stepsFromStart > 0) {
                    stepper0.cw();
                } else {
                    stepper0.ccw();
                }

                stepper0.step(Math.abs(motors[0].stepsFromStart), function () {

                    motors[0].stepsFromStart = 0;

                    if (finish1) {
                        OpenWall.call("movingToStartCompleted");
                        // turn the leds off for a new game
                        led1.off();
                        led2.off();
                        led3.off();
                    } else {
                        finish0 = true;
                    }
                });

                if (motors[1].stepsFromStart > 0) {
                    stepper1.cw();
                } else {
                    stepper1.ccw();
                }

                stepper1.step(Math.abs(motors[1].stepsFromStart), function () {

                    motors[1].stepsFromStart = 0;

                    if (finish0) {
                        OpenWall.call("movingToStartCompleted");
                        // turn the leds off for a new game
                        led1.off();
                        led2.off();
                        led3.off();
                    } else {
                        finish1 = true;
                    }
                });

            }
        }

        currentControllerState = controller.result;
    });

    this.loop(3, function () {

        // check for checkpoints reached by the player
        if (motors[0].stepsFromStart >= motors[0].stepsForCheckpoint1 - radius && motors[0].stepsFromStart <= motors[0].stepsForCheckpoint1 + radius) { // first stepper is in line
            if (motors[1].stepsFromStart >= motors[1].stepsForCheckpoint1 - radius && motors[1].stepsFromStart <= motors[1].stepsForCheckpoint1 + radius) { // second stepper is in line to
                // stepper is in Checkpoint1-Area
                led1.on();
            }
        }

        if (motors[0].stepsFromStart >= motors[0].stepsForCheckpoint2 - radius && motors[0].stepsFromStart <= motors[0].stepsForCheckpoint2 + radius) { // first stepper is in line
            if (motors[1].stepsFromStart >= motors[1].stepsForCheckpoint2 - radius && motors[1].stepsFromStart <= motors[1].stepsForCheckpoint2 + radius) { // second stepper is in line to
                if (led1.isOn()) {
                    // stepper is in Checkpoint2-Area and previous checkedPoints has been passed
                    led2.on();
                }
            }
        }

        if (motors[0].stepsFromStart >= motors[0].stepsForCheckpoint3 - radius && motors[0].stepsFromStart <= motors[0].stepsForCheckpoint3 + radius) { // first stepper is in line
            if (motors[1].stepsFromStart >= motors[1].stepsForCheckpoint3 - radius && motors[1].stepsFromStart <= motors[1].stepsForCheckpoint3 + radius) { // second stepper is in line to
                if (led2.isOn()) {
                    // stepper is in Checkpoint3-Area and previous checkedPoints has been passed
                    led3.on();
                }
            }
        }

        if (motors[0].speed > 0) {
            stepper0.cw().step(1, function () {
                motors[0].stepsFromStart--;
            });
        } else if (motors[0].speed < 0) {
        	if (motors[0].stepsFromStart + motors[1].stepsFromStart <= maxHeight || maxHeight == '') {
                stepper0.ccw().step(1, function () {
               		motors[0].stepsFromStart++;
            	});
            }
        }

        if (motors[1].speed > 0) {
            stepper1.cw().step(1, function () {
                motors[1].stepsFromStart--;
            });
        } else if (motors[1].speed < 0) {
        	if (motors[0].stepsFromStart + motors[1].stepsFromStart <= maxHeight || maxHeight == '') {
         	   stepper1.ccw().step(1, function () {
         	       motors[1].stepsFromStart++;
          	  });
          	}
        }
    });

});<commit_msg>checkPoints angepasst<commit_after>// Import libs
var Asteroid = require("asteroid");
var five = require("johnny-five");

// Get custom meteor port from node arguments
if (process.argv[2]) {
    var port = process.argv[2]
} else {
    var port = 3000; // Standard meteor port
}

// Connect to the OpenWall Meteor backend
var OpenWall = new Asteroid("localhost:" + port);
var collection = OpenWall.getCollection("controller");
var controller = collection.reactiveQuery({});
OpenWall.on("connected", function () {
    console.log("Asteroid connected to Meteor");
});

var currentControllerState = {};

var arduino = new five.Board();
arduino.on("ready", function () {

    motors = [
        {
            stepPin: 3,
            dirPin: 4,
            stepsFromStart: 0,
            stepsForCheckpoint1: 0,
            stepsForCheckpoint2: 0,
            stepsForCheckpoint3: 0
        }, {
            stepPin: 12,
            dirPin: 13,
            stepsFromStart: 0,
            stepsForCheckpoint1: 0,
            stepsForCheckpoint2: 0,
            stepsForCheckpoint3: 0
        }
    ];

    var stepper0 = five.Stepper({
        type: five.Stepper.TYPE.DRIVER,
        stepsPerRev: 200,
        pins: {
            step: motors[0].stepPin,
            dir: motors[0].dirPin
        }
    });
    var stepper1 = five.Stepper({
        type: five.Stepper.TYPE.DRIVER,
        stepsPerRev: 200,
        pins: {
            step: motors[1].stepPin,
            dir: motors[1].dirPin
        }
    });

    // radius for the checkPoint in steps relative to the stepperMotor
    var radius = stepper1.stepsPerRev * 2;

    var maxHeight = '';

    // Checkpoint LED's
    var led1 = new five.Led(6);
    arduino.repl.inject({
        led: led1
    });

    var led2 = new five.Led(7);
    arduino.repl.inject({
        led: led2
    });

    var led3 = new five.Led(8);
    arduino.repl.inject({
        led: led3
    });

    controller.on('change', function () {

        controller.result = controller.result[0];

        // set various locations on the gamefield
        if (currentControllerState.calibrateStart != controller.result.calibrateStart) {
            motors[0].stepsFromStart = 0;
            motors[1].stepsFromStart = 0;
        }

        if (currentControllerState.calibrateCheckPoint1 != controller.result.calibrateCheckPoint1) {
            motors[0].stepsForCheckPoint1 = motors[0].stepsFromStart;
            motors[1].stepsForCheckpoint1 = motors[1].stepsFromStart;
        }

        if (currentControllerState.calibrateCheckPoint2 != controller.result.calibrateCheckPoint2) {
            motors[0].stepsForCheckPoint2 = motors[0].stepsFromStart;
            motors[1].stepsForCheckpoint2 = motors[1].stepsFromStart;
        }

        if (currentControllerState.calibrateCheckPoint3 != controller.result.calibrateCheckPoint3) {
            motors[0].stepsForCheckPoint3 = motors[0].stepsFromStart;
            motors[1].stepsForCheckpoint3 = motors[1].stepsFromStart;
        }

        if (currentControllerState.calibrateMaxHeight != controller.result.calibrateMaxHeight) {
            maxHeight = motors[0].stepsFromStart + motors[1].stepsFromStart
        }

        if (currentControllerState.removeMaxHeight != controller.result.removeMaxHeight) {
            maxHeight = '';
        }

        // change direction of the stepper-Rotation
        if (currentControllerState.state1 != controller.result.state1) {
            motors[0].speed = controller.result.state1 * (-1);
        }

        if (currentControllerState.state2 != controller.result.state2) {
            motors[1].speed = controller.result.state2 * (-1);
        }

        // fall back to startingPoint
        if (currentControllerState.movingToStart != controller.result.movingToStart) {
            if (controller.result.movingToStart == true) {

                var finish0 = false;
                var finish1 = false;

                if (motors[0].stepsFromStart > 0) {
                    stepper0.cw();
                } else {
                    stepper0.ccw();
                }

                stepper0.step(Math.abs(motors[0].stepsFromStart), function () {

                    motors[0].stepsFromStart = 0;

                    if (finish1) {
                        OpenWall.call("movingToStartCompleted");
                        // turn the leds off for a new game
                        led1.off();
                        led2.off();
                        led3.off();
                    } else {
                        finish0 = true;
                    }
                });

                if (motors[1].stepsFromStart > 0) {
                    stepper1.cw();
                } else {
                    stepper1.ccw();
                }

                stepper1.step(Math.abs(motors[1].stepsFromStart), function () {

                    motors[1].stepsFromStart = 0;

                    if (finish0) {
                        OpenWall.call("movingToStartCompleted");
                        // turn the leds off for a new game
                        led1.off();
                        led2.off();
                        led3.off();
                    } else {
                        finish1 = true;
                    }
                });

            }
        }

        currentControllerState = controller.result;
    });

    this.loop(3, function () {

        // check for checkpoints reached by the player
        if (motors[0].stepsFromStart >= motors[0].stepsForCheckpoint1 - radius && motors[1].stepsFromStart >= motors[1].stepsForCheckpoint1 - radius) { // first stepper is in line
            console.log('I passed this stage');
            if (motors[0].stepsFromStart <= motors[0].stepsForCheckpoint1 + radius && motors[1].stepsFromStart <= motors[1].stepsForCheckpoint1 + radius) { // second stepper is in line to
                // stepper is in Checkpoint1-Area
                console.log('LED ON');
                led1.on();
            }
        }

        if (motors[0].stepsFromStart >= motors[0].stepsForCheckpoint2 - radius && motors[1].stepsFromStart >= motors[1].stepsForCheckpoint2 - radius) { // first stepper is in line
            console.log('I passed this stage');
            if (motors[0].stepsFromStart <= motors[0].stepsForCheckpoint2 + radius && motors[1].stepsFromStart <= motors[1].stepsForCheckpoint2 + radius) { // second stepper is in line to
                if (led1.isOn()) {
                    // stepper is in Checkpoint2-Area and previous checkedPoints has been passed
                    led2.on();
                }
            }
        }

        if (motors[0].stepsFromStart >= motors[0].stepsForCheckpoint3 - radius && motors[1].stepsFromStart >= motors[1].stepsForCheckpoint3 - radius) { // first stepper is in line
            console.log('I passed this stage');
            if (motors[0].stepsFromStart <= motors[0].stepsForCheckpoint3 + radius && motors[1].stepsFromStart <= motors[1].stepsForCheckpoint3 + radius) { // second stepper is in line to
                if (led2.isOn()) {
                    // stepper is in Checkpoint3-Area and previous checkedPoints has been passed
                    led3.on();
                }
            }
        }

        if (motors[0].speed > 0) {
            stepper0.cw().step(1, function () {
                motors[0].stepsFromStart--;
            });
        } else if (motors[0].speed < 0) {
            if (motors[0].stepsFromStart + motors[1].stepsFromStart <= maxHeight || maxHeight == '') {
                stepper0.ccw().step(1, function () {
                    motors[0].stepsFromStart++;
                });
            }
        }

        if (motors[1].speed > 0) {
            stepper1.cw().step(1, function () {
                motors[1].stepsFromStart--;
            });
        } else if (motors[1].speed < 0) {
            if (motors[0].stepsFromStart + motors[1].stepsFromStart <= maxHeight || maxHeight == '') {
                stepper1.ccw().step(1, function () {
                    motors[1].stepsFromStart++;
                });
            }
        }
    });

});<|endoftext|>


<commit_before>var Asteroid = require("asteroid");
var five = require("johnny-five");

// Connect to the OpenWall Meteor backend
var OpenWall = new Asteroid("localhost:3000");
var collection = OpenWall.getCollection("controller");
var controller = collection.reactiveQuery({});
OpenWall.on("connected", function() {
	console.log("Asteroid connected to Meteor");
});

var currentControllerState = {};

var arduino = new five.Board();
arduino.on("ready", function() {

	motors = [
		{
			stepPin: 3,
			dirPin: 4,
			stepsFromStart: 0,
			stepsForCheckpoint1: 0,
			stepsForCheckpoint2: 0,
			stepsForCheckpoint3: 0,
			stepsForMaxHeight: 0

		}, {
			stepPin: 12,
			dirPin: 13,
			stepsFromStart: 0,
			stepsForCheckpoint1: 0,
			stepsForCheckpoint2: 0,
			stepsForCheckpoint3: 0,
			stepsForMaxHeight: 0
		}
	];

	var stepper0 = five.Stepper({
		type: five.Stepper.TYPE.DRIVER,
		stepsPerRev: 200,
		pins: {
			step: motors[0].stepPin,
			dir: motors[0].dirPin
		}
	});
	var stepper1 = five.Stepper({
		type: five.Stepper.TYPE.DRIVER,
		stepsPerRev: 200,
		pins: {
			step: motors[1].stepPin,
			dir: motors[1].dirPin
		}
	});

	// radius for the checkPoint in steps relative to the stepperMotor
	var radius = stepper1.stepsPerRev*0.5;

	// Checkpoint LED's
	var led1 = new five.Led(6);
	arduino.repl.inject({
		led: led1
	});

	var led2 = new five.Led(7);
	arduino.repl.inject({
		led: led2
	});

	var led3 = new five.Led(8);
	arduino.repl.inject({
		led: led3
	});

	controller.on('change', function () {

		controller.result = controller.result[0];

		// set various locations on the gamefield
		if (currentControllerState.calibrateStart != controller.result.calibrateStart) {
			motors[0].stepsFromStart = 0;
			motors[1].stepsFromStart = 0;
		}

		if (currentControllerState.calibrateCheckPoint1 != controller.result.calibrateCheckPoint1) {
			motors[0].stepsForCheckPoint1 = motors[0].stepsFromStart;
			motors[1].stepsForCheckpoint1 = motors[1].stepsFromStart;
		}

		if (currentControllerState.calibrateCheckPoint2 != controller.result.calibrateCheckPoint2) {
			motors[0].stepsForCheckPoint2 = motors[0].stepsFromStart;
			motors[1].stepsForCheckpoint2 = motors[1].stepsFromStart;
		}

		if (currentControllerState.calibrateCheckPoint3 != controller.result.calibrateCheckPoint3) {
			motors[0].stepsForCheckPoint3 = motors[0].stepsFromStart;
			motors[1].stepsForCheckpoint3 = motors[1].stepsFromStart;
		}

		if (currentControllerState.calibrateMaxHeight != controller.result.calibrateMaxHeight) {
			motors[0].stepsForMaxHeight = motors[0].stepsFromStart;
			motors[1].stepsForMaxHeight = motors[1].stepsFromStart;
		}

		// change direction of the stepper-Rotation
		if (currentControllerState.state1 != controller.result.state1) {
			motors[0].speed = controller.result.state1 * (-1);
		}

		if (currentControllerState.state2 != controller.result.state2) {
			motors[1].speed = controller.result.state2;
		}

		// fall back to startingPoint
		if (currentControllerState.movingToStart != controller.result.movingToStart) {
			if(controller.result.movingToStart == true) {

				var finish0 = false;
				var finish1 = false;

				if (motors[0].stepsFromStart > 0) {
					stepper0.cw();
				} else {
					stepper0.ccw();
				}

				stepper0.step(Math.abs(motors[0].stepsFromStart), function() {

					motors[0].stepsFromStart = 0;

					if (finish1) {
						OpenWall.call("movingToStartCompleted");
						// turn the leds off for a new game
						led1.off();
						led2.off();
						led3.off();
					} else {
						finish0 = true;
					}
				});

				if (motors[1].stepsFromStart > 0) {
					stepper1.cw();
				} else {
					stepper1.ccw();
				}

				stepper1.step(Math.abs(motors[1].stepsFromStart), function() {

					motors[1].stepsFromStart = 0;

					if (finish0) {
						OpenWall.call("movingToStartCompleted");
						// turn the leds off for a new game
						led1.off();
						led2.off();
						led3.off();
					} else {
						finish1 = true;
					}
				});

			}
		}

	currentControllerState = controller.result;
	});

	this.loop(3, function() {

		// check for checkpoints reached by the player
		if (motors[0].stepsFromStart >= motors[0].stepsForCheckpoint1-radius && motors[0].stepsFromStart <= motors[0].stepsForCheckpoint1+radius) { // first stepper is in line
			if(motors[1].stepsFromStart >= motors[1].stepsForCheckpoint1-radius && motors[1].stepsFromStart <= motors[1].stepsForCheckpoint1+radius) { // second stepper is in line to
				// stepper is in Checkpoint1-Area
				led1.on();
			}
		}

		if (motors[0].stepsFromStart >= motors[0].stepsForCheckpoint2-radius && motors[0].stepsFromStart <= motors[0].stepsForCheckpoint2+radius) { // first stepper is in line
			if(motors[1].stepsFromStart >= motors[1].stepsForCheckpoint2-radius && motors[1].stepsFromStart <= motors[1].stepsForCheckpoint2+radius) { // second stepper is in line to
				if(led1.isOn()){
					// stepper is in Checkpoint2-Area and previous checkedPoints has been passed
					led2.on();
				}
			}
		}

		if (motors[0].stepsFromStart >= motors[0].stepsForCheckpoint3-radius && motors[0].stepsFromStart <= motors[0].stepsForCheckpoint3+radius) { // first stepper is in line
			if(motors[1].stepsFromStart >= motors[1].stepsForCheckpoint3-radius && motors[1].stepsFromStart <= motors[1].stepsForCheckpoint3+radius) { // second stepper is in line to
				if(led2.isOn()){
					// stepper is in Checkpoint3-Area and previous checkedPoints has been passed
					led3.on();
				}
			}
		}

		if (motors[0].speed > 0) {
			stepper0.cw().step(1, function() {
				motors[0].stepsFromStart--;
			});
		} else if (motors[0].speed < 0) {
			// prevent tearing of the line
			if(motors[0].stepsFromStart < motors[0].stepsForMaxHeight) {
				stepper0.ccw().step(1, function() {
					motors[0].stepsFromStart++;
				});
			}
		}

		if (motors[1].speed > 0) {
			stepper1.cw().step(1, function() {
				motors[1].stepsFromStart--;
			});
		} else if (motors[1].speed < 0) {
			// prevent tearing of the line
			if(motors[1].stepsFromStart < motors[1].stepsForMaxHeight) {
				stepper1.ccw().step(1, function() {
					motors[1].stepsFromStart++;
				});
			}
		}

	});
});<commit_msg>maxSteps is empty initially otherwise those cannot set<commit_after>var Asteroid = require("asteroid");
var five = require("johnny-five");

// Connect to the OpenWall Meteor backend
var OpenWall = new Asteroid("localhost:3000");
var collection = OpenWall.getCollection("controller");
var controller = collection.reactiveQuery({});
OpenWall.on("connected", function() {
	console.log("Asteroid connected to Meteor");
});

var currentControllerState = {};

var arduino = new five.Board();
arduino.on("ready", function() {

	motors = [
		{
			stepPin: 3,
			dirPin: 4,
			stepsFromStart: 0,
			stepsForCheckpoint1: 0,
			stepsForCheckpoint2: 0,
			stepsForCheckpoint3: 0,
			stepsForMaxHeight: '' // leave max height empty until set

		}, {
			stepPin: 12,
			dirPin: 13,
			stepsFromStart: 0,
			stepsForCheckpoint1: 0,
			stepsForCheckpoint2: 0,
			stepsForCheckpoint3: 0,
			stepsForMaxHeight: '' // leave max height empty until set
		}
	];

	var stepper0 = five.Stepper({
		type: five.Stepper.TYPE.DRIVER,
		stepsPerRev: 200,
		pins: {
			step: motors[0].stepPin,
			dir: motors[0].dirPin
		}
	});
	var stepper1 = five.Stepper({
		type: five.Stepper.TYPE.DRIVER,
		stepsPerRev: 200,
		pins: {
			step: motors[1].stepPin,
			dir: motors[1].dirPin
		}
	});

	// radius for the checkPoint in steps relative to the stepperMotor
	var radius = stepper1.stepsPerRev*0.5;

	// Checkpoint LED's
	var led1 = new five.Led(6);
	arduino.repl.inject({
		led: led1
	});

	var led2 = new five.Led(7);
	arduino.repl.inject({
		led: led2
	});

	var led3 = new five.Led(8);
	arduino.repl.inject({
		led: led3
	});

	controller.on('change', function () {

		controller.result = controller.result[0];

		// set various locations on the gamefield
		if (currentControllerState.calibrateStart != controller.result.calibrateStart) {
			motors[0].stepsFromStart = 0;
			motors[1].stepsFromStart = 0;
		}

		if (currentControllerState.calibrateCheckPoint1 != controller.result.calibrateCheckPoint1) {
			motors[0].stepsForCheckPoint1 = motors[0].stepsFromStart;
			motors[1].stepsForCheckpoint1 = motors[1].stepsFromStart;
		}

		if (currentControllerState.calibrateCheckPoint2 != controller.result.calibrateCheckPoint2) {
			motors[0].stepsForCheckPoint2 = motors[0].stepsFromStart;
			motors[1].stepsForCheckpoint2 = motors[1].stepsFromStart;
		}

		if (currentControllerState.calibrateCheckPoint3 != controller.result.calibrateCheckPoint3) {
			motors[0].stepsForCheckPoint3 = motors[0].stepsFromStart;
			motors[1].stepsForCheckpoint3 = motors[1].stepsFromStart;
		}

		if (currentControllerState.calibrateMaxHeight != controller.result.calibrateMaxHeight) {
			motors[0].stepsForMaxHeight = motors[0].stepsFromStart;
			motors[1].stepsForMaxHeight = motors[1].stepsFromStart;
		}

		// change direction of the stepper-Rotation
		if (currentControllerState.state1 != controller.result.state1) {
			motors[0].speed = controller.result.state1 * (-1);
		}

		if (currentControllerState.state2 != controller.result.state2) {
			motors[1].speed = controller.result.state2;
		}

		// fall back to startingPoint
		if (currentControllerState.movingToStart != controller.result.movingToStart) {
			if(controller.result.movingToStart == true) {

				var finish0 = false;
				var finish1 = false;

				if (motors[0].stepsFromStart > 0) {
					stepper0.cw();
				} else {
					stepper0.ccw();
				}

				stepper0.step(Math.abs(motors[0].stepsFromStart), function() {

					motors[0].stepsFromStart = 0;

					if (finish1) {
						OpenWall.call("movingToStartCompleted");
						// turn the leds off for a new game
						led1.off();
						led2.off();
						led3.off();
					} else {
						finish0 = true;
					}
				});

				if (motors[1].stepsFromStart > 0) {
					stepper1.cw();
				} else {
					stepper1.ccw();
				}

				stepper1.step(Math.abs(motors[1].stepsFromStart), function() {

					motors[1].stepsFromStart = 0;

					if (finish0) {
						OpenWall.call("movingToStartCompleted");
						// turn the leds off for a new game
						led1.off();
						led2.off();
						led3.off();
					} else {
						finish1 = true;
					}
				});

			}
		}

	currentControllerState = controller.result;
	});

	this.loop(3, function() {

		// check for checkpoints reached by the player
		if (motors[0].stepsFromStart >= motors[0].stepsForCheckpoint1-radius && motors[0].stepsFromStart <= motors[0].stepsForCheckpoint1+radius) { // first stepper is in line
			if(motors[1].stepsFromStart >= motors[1].stepsForCheckpoint1-radius && motors[1].stepsFromStart <= motors[1].stepsForCheckpoint1+radius) { // second stepper is in line to
				// stepper is in Checkpoint1-Area
				led1.on();
			}
		}

		if (motors[0].stepsFromStart >= motors[0].stepsForCheckpoint2-radius && motors[0].stepsFromStart <= motors[0].stepsForCheckpoint2+radius) { // first stepper is in line
			if(motors[1].stepsFromStart >= motors[1].stepsForCheckpoint2-radius && motors[1].stepsFromStart <= motors[1].stepsForCheckpoint2+radius) { // second stepper is in line to
				if(led1.isOn()){
					// stepper is in Checkpoint2-Area and previous checkedPoints has been passed
					led2.on();
				}
			}
		}

		if (motors[0].stepsFromStart >= motors[0].stepsForCheckpoint3-radius && motors[0].stepsFromStart <= motors[0].stepsForCheckpoint3+radius) { // first stepper is in line
			if(motors[1].stepsFromStart >= motors[1].stepsForCheckpoint3-radius && motors[1].stepsFromStart <= motors[1].stepsForCheckpoint3+radius) { // second stepper is in line to
				if(led2.isOn()){
					// stepper is in Checkpoint3-Area and previous checkedPoints has been passed
					led3.on();
				}
			}
		}

		if (motors[0].speed > 0) {
			stepper0.cw().step(1, function() {
				motors[0].stepsFromStart--;
			});
		} else if (motors[0].speed < 0) {
			// prevent tearing of the line
			if(motors[0].stepsFromStart < motors[0].stepsForMaxHeight || motors[0].stepsForMaxHeight == '') {
				stepper0.ccw().step(1, function() {
					motors[0].stepsFromStart++;
				});
			}
		}

		if (motors[1].speed > 0) {
			stepper1.cw().step(1, function() {
				motors[1].stepsFromStart--;
			});
		} else if (motors[1].speed < 0) {
			// prevent tearing of the line
			if(motors[1].stepsFromStart < motors[1].stepsForMaxHeight || motors[1].stepsForMaxHeight == '') {
				stepper1.ccw().step(1, function() {
					motors[1].stepsFromStart++;
				});
			}
		}

	});
});<|endoftext|>


<commit_before>function Scoreboard(options) {
  if (!options) options= {};

  this._message = options.message || '';
  this._score = options.score || 0;

  if (options.onTimeExpired) {
    this._countdown = new __Countdown({
      duration: options.countDownFrom
    });
    this.onTimeExpired(
      options.onTimeExpired ? options.onTimeExpired : function(){}
    );
  }
}

/****
 * Message
 */
Scoreboard.prototype.showMessage = function() {
  this.ensureDom();
  this.message_el.style.display = 'block';
  return this;
};

Scoreboard.prototype.hideMessage = function() {
  this.message_el.style.display = 'none';
  return this;
};

Scoreboard.prototype.setMessage = function(message) {
  this.showMessage();
  this._message = message;
  this.message_el.innerHTML = this._message;

  this.message_el.scrollTop = this.message_el.scrollHeight;

  return this;
};

Scoreboard.prototype.appendMessage = function(message) {
  function div(s) { return '
' + s + '
'; }
  this.setMessage((this._message || '') + div(message));
  return this;
};

Scoreboard.prototype.addMessage = Scoreboard.prototype.appendMessage;
Scoreboard.prototype.message = Scoreboard.prototype.appendMessage;

// Message

/*****
 * Help
 */
Scoreboard.prototype.showHelp = function() {
  this.ensureDom();
  this.help_el.style.display = 'block';
  return this;
};

Scoreboard.prototype.hideHelp = function() {
  this.help_el.style.display = 'none';
  return this;
};

Scoreboard.prototype.toggleHelp = function() {
  this.help_el.style.display = this.help_el.style.display == 'none' ?
    'block' : 'none';
  return this;
};

Scoreboard.prototype.showHelpFooter = function() {
  this.ensureDom();
  this.help_footer.style.display = 'block';
  return this;
};

Scoreboard.prototype.setHelp = function(help) {
  this.showHelpFooter();
  this._help = help;
  this.help_el.innerHTML = this._help;

  this.help_el.scrollTop = this.help_el.scrollHeight;

  return this;
};

Scoreboard.prototype.addHelp = Scoreboard.prototype.setHelp;
Scoreboard.prototype.help = Scoreboard.prototype.setHelp;

// Help

/****
 * Score
 */

Scoreboard.prototype.showScore = function() {
  this.ensureDom();
  this.score_el.style.display = 'block';
  return this;
};

Scoreboard.prototype.setScore = function(score) {
  this.showScore();
  this._score = score;

  this.score_el.innerHTML = "Score: " + this._score;

  return this;
};

Scoreboard.prototype.getScore = function() {
  return this._score;
};

Scoreboard.prototype.score = Scoreboard.prototype.setScore;

Scoreboard.prototype.addPoints = function(points) {
  this._score += points;
};

Scoreboard.prototype.subtractPoints = function(points) {
  this._score -= points;
};

// Timer

/*****
 * Timer
 */

Scoreboard.prototype.showTimer = function() {
  this.ensureDom();
  this._showTimer = true;
  this.timer_el.style.display = 'block';
  this.setTimer();
  return this;
};
Scoreboard.prototype.timer = Scoreboard.prototype.showTimer;

Scoreboard.prototype.hideTimer = function() {
  this.ensureDom();
  this._showTimer = false;
  this.timer_el.style.display = 'none';
  return this;
};

Scoreboard.prototype.setTimer = function() {
  var that = this;
  if (!this._timer) this._timer = new __Timer();
  this._timer.onUpdate(function(time) {
    that.timer_el.innerHTML = 'Time: ' + time;
  });
  this.timer_el.style.display = this._showTimer ? 'block' : 'none';
};

Scoreboard.prototype.stopTimer = function() {
  this._timer.stop();
};

Scoreboard.prototype.startTimer = function() {
  this._timer.start();
};

Scoreboard.prototype.resetTimer = function() {
  this._timer.reset();
};

Scoreboard.prototype.getTime = function() {
  return this._timer.diff() / 1000;
};

// Timer

/*****
 * Countdown
 */

Scoreboard.prototype.showCountdown = function(duration) {
  this.ensureDom();
  this._showCountdown = true;
  this.countdown_el.style.display = 'block';
  this.setCountdown(duration);
  return this;
};

Scoreboard.prototype.countdown = Scoreboard.prototype.showCountdown;

Scoreboard.prototype.hideCountdown = function() {
  this.ensureDom();
  this._showCountdown = false;
  this.countdown_el.style.display = 'none';
  return this;
};

Scoreboard.prototype.setCountdown = function(duration) {
  var that = this;

  if (!this._countdown) this._countdown = new __Countdown({
    duration: duration
  });

  if (duration) this._countdown.reset(duration);
  this._countdown.onUpdate(function(time) {
    that.countdown_el.innerHTML = 'Remaining: ' + time;
  });
  this.countdown_el.style.display = this._showCountdown ? 'block' : 'none';
};

Scoreboard.prototype.stopCountdown = function() {
  this._countdown.stop();
};

Scoreboard.prototype.startCountdown = function() {
  this._countdown.start();
};

Scoreboard.prototype.resetCountdown = function(time) {
  this._countdown.reset(time);
};

Scoreboard.prototype.getTimeRemaining = function() {
  return this._countdown.diff() / 1000;
};

Scoreboard.prototype.onTimeExpired = function(cb) {
  if (!cb) return;

  var that = this;
  this._on_time_expired = (typeof(cb) == 'string') ?
    function() { that.setMessage(cb); } : cb;

  this._countdown.onTimeExpired(function() {
    that.stopTimer();
    that._on_time_expired();
  });
};

// Countdown

Scoreboard.prototype.ensureDom = function() {
  if (this.el) return;

  var el = this.el = document.createElement('div');
  el.id = 'scoreboard';
  el.style.position = 'absolute';
  el.style.backgroundColor = 'black';
  el.style.opacity = 0.7;
  el.style.borderRadius = "5px";
  el.style.padding = "5px 20px";
  el.style.right = "50px";
  el.style.top = "75px";
  el.style.width = (window.innerWidth * 0.2) + "px";
  el.style.minWidth = '200px';

  el.style.color = 'yellow';
  el.style.fontFamily = 'Arial, San Serif';
  el.style.fontWeight = 'bold';
  el.style.fontSize = (window.innerHeight * 0.033) + "px";

  var countdown_el = this.countdown_el = document.createElement('div');
  el.appendChild(countdown_el);

  var timer_el = this.timer_el = document.createElement('div');
  el.appendChild(timer_el);

  var score_el = this.score_el = document.createElement('div');
  el.appendChild(score_el);

  var message_el = this.message_el = document.createElement('div');
  message_el.style.fontWeight = 'normal';
  message_el.style.color = 'white';
  message_el.style.maxHeight = (window.innerHeight * 0.2) + "px";
  message_el.style.overflowY = 'auto';
  el.appendChild(message_el);

  var help_el = this.help_el = document.createElement('div');
  help_el.style.display = 'none';
  help_el.style.fontWeight = 'normal';
  help_el.style.color = 'white';
  help_el.style.fontSize = (window.innerHeight * 0.028) + "px";
  help_el.style.borderTop = "1px #676767 solid";
  help_el.style.marginTop = '5px';
  help_el.style.paddingTop = '3px';
  help_el.style.maxHeight = (window.innerHeight * 0.2) + "px";
  help_el.style.overflowY = 'auto';
  el.appendChild(help_el);

  var help_footer = this.help_footer = document.createElement('div');
  help_footer.style.display = 'none';
  help_footer.style.fontWeight = 'normal';
  help_footer.style.color = 'white';
  help_footer.style.maxHeight = (window.innerHeight * 0.2) + "px";
  help_footer.style.fontSize = (window.innerHeight * 0.02) + "px";
  help_footer.style.borderTop = "1px #676767 solid";
  help_footer.style.marginTop = '5px';
  help_footer.innerHTML = 'Press ? for help';
  el.appendChild(help_footer);

  var that = this;
  document.addEventListener('keypress', function(event) {
    if (event.keyCode == 63) that.toggleHelp();
  });

  document.body.appendChild(el);
};

/****
 * Timer Class
 */
function __Timer() {
  this._start = (new Date).getTime();
}

__Timer.prototype.toString = function() {
  var minutes = "" + this._minutes(),
      seconds = "" + this._seconds();

  if (minutes.length == 1) minutes = "0" + minutes;
  if (seconds.length == 1) seconds = "0" + seconds;

  return minutes + ":" + seconds;
};

__Timer.prototype.diff = function() {
  var now = this.last();
  return now - this._start;
};

__Timer.prototype.last = function() {
  if (this._last) return this._last;
  return (new Date).getTime();
};

__Timer.prototype.stop = function() {
  if (this._last) return;
  this._last = (new Date).getTime();
};

__Timer.prototype.start = function() {
  this._last = undefined;
};

__Timer.prototype.reset = function() {
  this._start = (new Date).getTime();
  this.start();
};

__Timer.prototype._minutes = function() {
  return Math.floor(this.diff()/(60*1000));
};

__Timer.prototype._seconds = function() {
  var ms = this.diff() % (60*1000);
  return Math.floor(ms / 1000);
};

__Timer.prototype.seconds = function() {
  return this.diff() / (60*1000);
};

__Timer.prototype.onUpdate = function(cb) {
  var that = this;
  cb(that.toString());
  setInterval(function() {cb(that.toString());}, 500);
};

// Timer

/*****
 * Countdown
 */

function __Countdown(options) {
  this._start = (new Date).getTime();
  this.duration = options.duration || 60;
  this._onTimeExpired = function(){};
  this.waitForTimeExpired();
}

__Countdown.prototype = new __Timer();

__Countdown.prototype.diff = function() {
  var now = this.last(),
      diff = now - this._start;

  if (diff > this.duration * 1000) return 0;
  return this.duration * 1000 - diff;
};

__Countdown.prototype.reset = function(duration) {
  if (duration) this.duration = duration;
  this._start = (new Date).getTime();
  this.waitForTimeExpired();
  this.start();
};

__Countdown.prototype.waitForTimeExpired = function() {
  var that = this;

  function _wait() {
    if (that.diff() > 0) return setTimeout(_wait, 500);
    that.stop();
    return that._onTimeExpired(that.toString());
  }
  _wait();
};

__Countdown.prototype.onTimeExpired = function(cb) {
  this._onTimeExpired = cb;
};

// Countdown
<commit_msg>Update the UI when adding/subtracting points<commit_after>function Scoreboard(options) {
  if (!options) options= {};

  this._message = options.message || '';
  this._score = options.score || 0;

  if (options.onTimeExpired) {
    this._countdown = new __Countdown({
      duration: options.countDownFrom
    });
    this.onTimeExpired(
      options.onTimeExpired ? options.onTimeExpired : function(){}
    );
  }
}

/****
 * Message
 */
Scoreboard.prototype.showMessage = function() {
  this.ensureDom();
  this.message_el.style.display = 'block';
  return this;
};

Scoreboard.prototype.hideMessage = function() {
  this.message_el.style.display = 'none';
  return this;
};

Scoreboard.prototype.setMessage = function(message) {
  this.showMessage();
  this._message = message;
  this.message_el.innerHTML = this._message;

  this.message_el.scrollTop = this.message_el.scrollHeight;

  return this;
};

Scoreboard.prototype.appendMessage = function(message) {
  function div(s) { return '
' + s + '
'; }
  this.setMessage((this._message || '') + div(message));
  return this;
};

Scoreboard.prototype.addMessage = Scoreboard.prototype.appendMessage;
Scoreboard.prototype.message = Scoreboard.prototype.appendMessage;

// Message

/*****
 * Help
 */
Scoreboard.prototype.showHelp = function() {
  this.ensureDom();
  this.help_el.style.display = 'block';
  return this;
};

Scoreboard.prototype.hideHelp = function() {
  this.help_el.style.display = 'none';
  return this;
};

Scoreboard.prototype.toggleHelp = function() {
  this.help_el.style.display = this.help_el.style.display == 'none' ?
    'block' : 'none';
  return this;
};

Scoreboard.prototype.showHelpFooter = function() {
  this.ensureDom();
  this.help_footer.style.display = 'block';
  return this;
};

Scoreboard.prototype.setHelp = function(help) {
  this.showHelpFooter();
  this._help = help;
  this.help_el.innerHTML = this._help;

  this.help_el.scrollTop = this.help_el.scrollHeight;

  return this;
};

Scoreboard.prototype.addHelp = Scoreboard.prototype.setHelp;
Scoreboard.prototype.help = Scoreboard.prototype.setHelp;

// Help

/****
 * Score
 */

Scoreboard.prototype.showScore = function() {
  this.ensureDom();
  this.score_el.style.display = 'block';
  return this;
};

Scoreboard.prototype.setScore = function(score) {
  this.showScore();
  this._score = score;

  this.score_el.innerHTML = "Score: " + this._score;

  return this;
};

Scoreboard.prototype.getScore = function() {
  return this._score;
};

Scoreboard.prototype.score = Scoreboard.prototype.setScore;

Scoreboard.prototype.addPoints = function(points) {
  this.setScore(this._score + points);
};

Scoreboard.prototype.subtractPoints = function(points) {
  this.setScore(this._score - points);
};

// Timer

/*****
 * Timer
 */

Scoreboard.prototype.showTimer = function() {
  this.ensureDom();
  this._showTimer = true;
  this.timer_el.style.display = 'block';
  this.setTimer();
  return this;
};
Scoreboard.prototype.timer = Scoreboard.prototype.showTimer;

Scoreboard.prototype.hideTimer = function() {
  this.ensureDom();
  this._showTimer = false;
  this.timer_el.style.display = 'none';
  return this;
};

Scoreboard.prototype.setTimer = function() {
  var that = this;
  if (!this._timer) this._timer = new __Timer();
  this._timer.onUpdate(function(time) {
    that.timer_el.innerHTML = 'Time: ' + time;
  });
  this.timer_el.style.display = this._showTimer ? 'block' : 'none';
};

Scoreboard.prototype.stopTimer = function() {
  this._timer.stop();
};

Scoreboard.prototype.startTimer = function() {
  this._timer.start();
};

Scoreboard.prototype.resetTimer = function() {
  this._timer.reset();
};

Scoreboard.prototype.getTime = function() {
  return this._timer.diff() / 1000;
};

// Timer

/*****
 * Countdown
 */

Scoreboard.prototype.showCountdown = function(duration) {
  this.ensureDom();
  this._showCountdown = true;
  this.countdown_el.style.display = 'block';
  this.setCountdown(duration);
  return this;
};

Scoreboard.prototype.countdown = Scoreboard.prototype.showCountdown;

Scoreboard.prototype.hideCountdown = function() {
  this.ensureDom();
  this._showCountdown = false;
  this.countdown_el.style.display = 'none';
  return this;
};

Scoreboard.prototype.setCountdown = function(duration) {
  var that = this;

  if (!this._countdown) this._countdown = new __Countdown({
    duration: duration
  });

  if (duration) this._countdown.reset(duration);
  this._countdown.onUpdate(function(time) {
    that.countdown_el.innerHTML = 'Remaining: ' + time;
  });
  this.countdown_el.style.display = this._showCountdown ? 'block' : 'none';
};

Scoreboard.prototype.stopCountdown = function() {
  this._countdown.stop();
};

Scoreboard.prototype.startCountdown = function() {
  this._countdown.start();
};

Scoreboard.prototype.resetCountdown = function(time) {
  this._countdown.reset(time);
};

Scoreboard.prototype.getTimeRemaining = function() {
  return this._countdown.diff() / 1000;
};

Scoreboard.prototype.onTimeExpired = function(cb) {
  if (!cb) return;

  var that = this;
  this._on_time_expired = (typeof(cb) == 'string') ?
    function() { that.setMessage(cb); } : cb;

  this._countdown.onTimeExpired(function() {
    that.stopTimer();
    that._on_time_expired();
  });
};

// Countdown

Scoreboard.prototype.ensureDom = function() {
  if (this.el) return;

  var el = this.el = document.createElement('div');
  el.id = 'scoreboard';
  el.style.position = 'absolute';
  el.style.backgroundColor = 'black';
  el.style.opacity = 0.7;
  el.style.borderRadius = "5px";
  el.style.padding = "5px 20px";
  el.style.right = "50px";
  el.style.top = "75px";
  el.style.width = (window.innerWidth * 0.2) + "px";
  el.style.minWidth = '200px';

  el.style.color = 'yellow';
  el.style.fontFamily = 'Arial, San Serif';
  el.style.fontWeight = 'bold';
  el.style.fontSize = (window.innerHeight * 0.033) + "px";

  var countdown_el = this.countdown_el = document.createElement('div');
  el.appendChild(countdown_el);

  var timer_el = this.timer_el = document.createElement('div');
  el.appendChild(timer_el);

  var score_el = this.score_el = document.createElement('div');
  el.appendChild(score_el);

  var message_el = this.message_el = document.createElement('div');
  message_el.style.fontWeight = 'normal';
  message_el.style.color = 'white';
  message_el.style.maxHeight = (window.innerHeight * 0.2) + "px";
  message_el.style.overflowY = 'auto';
  el.appendChild(message_el);

  var help_el = this.help_el = document.createElement('div');
  help_el.style.display = 'none';
  help_el.style.fontWeight = 'normal';
  help_el.style.color = 'white';
  help_el.style.fontSize = (window.innerHeight * 0.028) + "px";
  help_el.style.borderTop = "1px #676767 solid";
  help_el.style.marginTop = '5px';
  help_el.style.paddingTop = '3px';
  help_el.style.maxHeight = (window.innerHeight * 0.2) + "px";
  help_el.style.overflowY = 'auto';
  el.appendChild(help_el);

  var help_footer = this.help_footer = document.createElement('div');
  help_footer.style.display = 'none';
  help_footer.style.fontWeight = 'normal';
  help_footer.style.color = 'white';
  help_footer.style.maxHeight = (window.innerHeight * 0.2) + "px";
  help_footer.style.fontSize = (window.innerHeight * 0.02) + "px";
  help_footer.style.borderTop = "1px #676767 solid";
  help_footer.style.marginTop = '5px';
  help_footer.innerHTML = 'Press ? for help';
  el.appendChild(help_footer);

  var that = this;
  document.addEventListener('keypress', function(event) {
    if (event.keyCode == 63) that.toggleHelp();
  });

  document.body.appendChild(el);
};

/****
 * Timer Class
 */
function __Timer() {
  this._start = (new Date).getTime();
}

__Timer.prototype.toString = function() {
  var minutes = "" + this._minutes(),
      seconds = "" + this._seconds();

  if (minutes.length == 1) minutes = "0" + minutes;
  if (seconds.length == 1) seconds = "0" + seconds;

  return minutes + ":" + seconds;
};

__Timer.prototype.diff = function() {
  var now = this.last();
  return now - this._start;
};

__Timer.prototype.last = function() {
  if (this._last) return this._last;
  return (new Date).getTime();
};

__Timer.prototype.stop = function() {
  if (this._last) return;
  this._last = (new Date).getTime();
};

__Timer.prototype.start = function() {
  this._last = undefined;
};

__Timer.prototype.reset = function() {
  this._start = (new Date).getTime();
  this.start();
};

__Timer.prototype._minutes = function() {
  return Math.floor(this.diff()/(60*1000));
};

__Timer.prototype._seconds = function() {
  var ms = this.diff() % (60*1000);
  return Math.floor(ms / 1000);
};

__Timer.prototype.seconds = function() {
  return this.diff() / (60*1000);
};

__Timer.prototype.onUpdate = function(cb) {
  var that = this;
  cb(that.toString());
  setInterval(function() {cb(that.toString());}, 500);
};

// Timer

/*****
 * Countdown
 */

function __Countdown(options) {
  this._start = (new Date).getTime();
  this.duration = options.duration || 60;
  this._onTimeExpired = function(){};
  this.waitForTimeExpired();
}

__Countdown.prototype = new __Timer();

__Countdown.prototype.diff = function() {
  var now = this.last(),
      diff = now - this._start;

  if (diff > this.duration * 1000) return 0;
  return this.duration * 1000 - diff;
};

__Countdown.prototype.reset = function(duration) {
  if (duration) this.duration = duration;
  this._start = (new Date).getTime();
  this.waitForTimeExpired();
  this.start();
};

__Countdown.prototype.waitForTimeExpired = function() {
  var that = this;

  function _wait() {
    if (that.diff() > 0) return setTimeout(_wait, 500);
    that.stop();
    return that._onTimeExpired(that.toString());
  }
  _wait();
};

__Countdown.prototype.onTimeExpired = function(cb) {
  this._onTimeExpired = cb;
};

// Countdown
<|endoftext|>


<commit_before>export { Base };

/**
 * Add two tensor3d. They should have the same dimensions ( height x width x channel ). It could destroy one or two of the input tensors.
 *
 * @member {boolean} bKeepInputTensor0
 *   If false, the first input tensor will be disposed after adding. If true, the first input tensor will be kept after adding.
 *
 * @member {boolean} bKeepInputTensor1
 *   If false, the second input tensor will be disposed after adding. If true, the second input tensor will be kept after adding.
 *
 * @member {function} pfnAdd
 *   This is a method. It has two parameter ( inputTensor0, inputTensor1 ) and return a outputTensor. Both the inputTensor0 and
 * inputTensor1 are tf.tensor3d and represents an images ( height x width x channel ) which will be added. They should have the same
 * ( height x width x channel ). The outputTensor (tf.tensor3d) represents the result of adding the two inputs. The inputTensor may
 * or may not be disposed. In fact, this method calls one of Add_and_keep0_keep1(), Add_and_keep0_destroy1(), Add_and_destroy0_keep1(),
 * Add_and_destroy0_destroy1() according to the parameters.
 *
 */
class Base {

  constructor( bKeepInputTensor0, bKeepInputTensor1 ) {
    this.bKeepInputTensor0 = bKeepInputTensor0;
    this.bKeepInputTensor1 = bKeepInputTensor1;
    Base.adjust_pfnAdd.call( this );
  }

  /**
   * Adjust this.pfnAdd so that this.pfnAdd() will or will not dispose its inputTensors.
   */
  setKeepInputTensor0( bKeepInputTensor0 ) {
    this.bKeepInputTensor0 = bKeepInputTensor0;
    Base.adjust_pfnAdd.call( this );
  }

  /**
   * Adjust this.pfnAdd so that this.pfnAdd() will or will not dispose its inputTensors.
   */
  setKeepInputTensor1( bKeepInputTensor1 ) {
    this.bKeepInputTensor1 = bKeepInputTensor1;
    Base.adjust_pfnAdd.call( this );
  }

  /**
   * Adjust this.pfnAdd so that this.pfnAdd() will or will not dispose its inputTensors.
   */
  setKeepInputTensor( bKeepInputTensor0, bKeepInputTensor1 ) {
    this.bKeepInputTensor0 = bKeepInputTensor0;
    this.bKeepInputTensor1 = bKeepInputTensor1;
    Base.adjust_pfnAdd.call( this );
  }

  /** Set this.pfnAdd according to this.bKeepInputTensor0 and this.bKeepInputTensor1. */
  static adjust_pfnAdd() {
    if ( this.bKeepInputTensor0 ) {
      if ( this.bKeepInputTensor1 ) {
        this.pfnAdd = Base.Add_and_keep0_keep1;
      } else {
        this.pfnAdd = Base.Add_and_keep0_destroy1;
      }
    } else {
      if ( this.bKeepInputTensor1 ) {
        this.pfnAdd = Base.Add_and_destroy0_keep1;
      } else {
        this.pfnAdd = Base.Add_and_destroy0_destroy1;
      }
    }
  }

  /** Add. (Both the inputTensor0 and inputTensor1 will not be disposed. */
  static Add_and_keep0_keep1( inputTensor0, inputTensor1 ) {
    return tf.add( inputTensor0, inputTensor1 );
  }

  /** Add. (The inputTensors0 will not be disposed. The inputTensor1 will be disposed. */
  static Add_and_keep0_destroy1( inputTensor0, inputTensor1 ) {
    let t = tf.add( inputTensor0, inputTensor1 );
    inputTensor1.dispose();
    return t;
  }

  /** Add. (The inputTensor0 will be disposed. The inputTensor1 will not be disposed. */
  static Add_and_destroy0_keep1( inputTensor0, inputTensor1 ) {
    let t = tf.add( inputTensor0, inputTensor1 );
    inputTensor0.dispose();
    return t;
  }

  /** Add. (Both the inputTensor0 and inputTensor1 will be disposed. */
  static Add_and_destroy0_destroy1( inputTensor0, inputTensor1 ) {
    let t = tf.add( inputTensor0, inputTensor1 );
    inputTensor0.dispose();
    inputTensor1.dispose();
    return t;
  }

}
<commit_msg>Update AddTwoTensors.js<commit_after>export { Base };

//!!! ...unfinished... (2021/05/30) may inherit from Pointwise?

/**
 * Add two tensor3d. They should have the same dimensions ( height x width x channel ). It could destroy one or two of the input tensors.
 *
 * @member {boolean} bKeepInputTensor0
 *   If false, the first input tensor will be disposed after adding. If true, the first input tensor will be kept after adding.
 *
 * @member {boolean} bKeepInputTensor1
 *   If false, the second input tensor will be disposed after adding. If true, the second input tensor will be kept after adding.
 *
 * @member {function} pfnAdd
 *   This is a method. It has two parameter ( inputTensor0, inputTensor1 ) and return a outputTensor. Both the inputTensor0 and
 * inputTensor1 are tf.tensor3d and represents an images ( height x width x channel ) which will be added. They should have the same
 * ( height x width x channel ). The outputTensor (tf.tensor3d) represents the result of adding the two inputs. The inputTensor may
 * or may not be disposed. In fact, this method calls one of Add_and_keep0_keep1(), Add_and_keep0_destroy1(), Add_and_destroy0_keep1(),
 * Add_and_destroy0_destroy1() according to the parameters.
 *
 */
class Base {

  constructor( bKeepInputTensor0, bKeepInputTensor1 ) {
    this.bKeepInputTensor0 = bKeepInputTensor0;
    this.bKeepInputTensor1 = bKeepInputTensor1;
    Base.adjust_pfnAdd.call( this );
  }

  /**
   * Adjust this.pfnAdd so that this.pfnAdd() will or will not dispose its inputTensors.
   */
  setKeepInputTensor0( bKeepInputTensor0 ) {
    this.bKeepInputTensor0 = bKeepInputTensor0;
    Base.adjust_pfnAdd.call( this );
  }

  /**
   * Adjust this.pfnAdd so that this.pfnAdd() will or will not dispose its inputTensors.
   */
  setKeepInputTensor1( bKeepInputTensor1 ) {
    this.bKeepInputTensor1 = bKeepInputTensor1;
    Base.adjust_pfnAdd.call( this );
  }

  /**
   * Adjust this.pfnAdd so that this.pfnAdd() will or will not dispose its inputTensors.
   */
  setKeepInputTensor( bKeepInputTensor0, bKeepInputTensor1 ) {
    this.bKeepInputTensor0 = bKeepInputTensor0;
    this.bKeepInputTensor1 = bKeepInputTensor1;
    Base.adjust_pfnAdd.call( this );
  }

  /** Set this.pfnAdd according to this.bKeepInputTensor0 and this.bKeepInputTensor1. */
  static adjust_pfnAdd() {
    if ( this.bKeepInputTensor0 ) {
      if ( this.bKeepInputTensor1 ) {
        this.pfnAdd = Base.Add_and_keep0_keep1;
      } else {
        this.pfnAdd = Base.Add_and_keep0_destroy1;
      }
    } else {
      if ( this.bKeepInputTensor1 ) {
        this.pfnAdd = Base.Add_and_destroy0_keep1;
      } else {
        this.pfnAdd = Base.Add_and_destroy0_destroy1;
      }
    }
  }

  /** Add. (Both the inputTensor0 and inputTensor1 will not be disposed. */
  static Add_and_keep0_keep1( inputTensor0, inputTensor1 ) {
    return tf.add( inputTensor0, inputTensor1 );
  }

  /** Add. (The inputTensors0 will not be disposed. The inputTensor1 will be disposed. */
  static Add_and_keep0_destroy1( inputTensor0, inputTensor1 ) {
    let t = tf.add( inputTensor0, inputTensor1 );
    inputTensor1.dispose();
    return t;
  }

  /** Add. (The inputTensor0 will be disposed. The inputTensor1 will not be disposed. */
  static Add_and_destroy0_keep1( inputTensor0, inputTensor1 ) {
    let t = tf.add( inputTensor0, inputTensor1 );
    inputTensor0.dispose();
    return t;
  }

  /** Add. (Both the inputTensor0 and inputTensor1 will be disposed. */
  static Add_and_destroy0_destroy1( inputTensor0, inputTensor1 ) {
    let t = tf.add( inputTensor0, inputTensor1 );
    inputTensor0.dispose();
    inputTensor1.dispose();
    return t;
  }

}
<|endoftext|>