<commit_before>// Restful Routes, according to Rails: http://guides.rubyonrails.org/routing.html
// HTTP   Verb Path         action  used for
// ****** ***************** ******* ********
// GET    /photos           index   display a list of all photos
// GET    /photos/new       new     return an HTML form for creating a new photo
// POST   /photos           create  create a new photo
// GET    /photos/:id       show    display a specific photo
// GET    /photos/:id/edit  edit    return an HTML form for editing a photo
// PUT    /photos/:id       update  update a specific photo
// DELETE /photos/:id       destroy delete a specific photo

var assert = require('assert')
var sinon = require('sinon')
var tf = require('./fixtures')
var router
var controller = require('./fixtures/controller')

describe('Router', function() {

  beforeEach(function(done) {
    // the router needs to be un-cached for these tests to work properly.
    delete require.cache[require.resolve('../router')]
    delete require.cache[require.resolve('routes')]

    router = require('../router')
    router.setControllerPath(__dirname+'/fixtures')
    done()
  })

  describe('Register', function() {

    it('should have register method', function(done) {
      assert(router.register)
      done()
    })

    it('should correctly register a route', function(done) {
      var route = '/route/:id'
      var handler = {controller:'controller'}
      router.register(route, handler)
      assert.equal(router.routes[route], handler)
      done()
    })

    it('should correctly register a route with object syntax', function(done) {
      var handler = {controller:'controller'}
      router.register({ '/my/:route': handler })
      assert.equal(router.routes['/my/:route'], handler)
      done()
    })

    it('should correctly register a route with object syntax and action string', function(done) {
      var handler = {controller:'controller', action:'index'}
      router.register({ '/my/:route': handler })
      assert.equal(router.routes['/my/:route'], handler)
      done()
    })

    it('should correctly register a route with object syntax and method only', function(done) {
      var handler = {controller:'controller', method:'GET'}
      router.register({ '/my/:route': handler })
      assert.equal(router.routes['/my/:route'], handler)
      done()
    })

    it('should correctly register a route with object syntax, action key, and single method', function(done) {
      var handler = {controller:'controller', index:'GET'}
      router.register({ '/my/:route': handler })
      assert.equal(router.routes['/my/:route'], handler)
      done()
    })

    it('should correctly register a route with object syntax, action key, and method array', function(done) {
      var handler = {controller:'controller', index:['GET','POST']}
      router.register({ '/my/:route': handler })
      assert.equal(router.routes['/my/:route'], handler)
      done()
    })

    it('should correctly register a route with object syntax, many action keys, and method strings', function(done) {
      var handler = {controller:'controller', index:'GET', create:'POST'}
      router.register({ '/my/:route': handler })
      assert.equal(router.routes['/my/:route'], handler)
      done()
    })

    it('should fail to register a route with object syntax, action keys, and conflicting methods', function(done) {
      var handler = {controller:'controller', index:['GET','POST'], create:'POST'}
      router.register({ '/my/:route': handler })
      assert.equal(router.routes['/my/:route'], handler)
      assert.equal('passes', false) // <- forcing a failure until this throws a proper error
      done()
    })

    // Actually, given the above syntax, then this should overwrite the declaration, then I don't have to waste my time munging things together
    it('should overwrite a route declared multiple times', function(done) {
      var handler1 = {controller:'controller', index:'GET'}
      var handler2 = {controller:'controller', create:'POST'}
      router.register('/my/:id', handler1)
      router.register('/my/:id', handler2)
      assert.equal(router.routes['/my/:id'], handler2)
      done()
    })

  })

  describe('Match', function(){

    it('should have a match method', function(done) {
      assert(router.match)
      done()
    })

    it('should return falsey value when the url does not match a route', function(done) {
      var match = router.match({url:'dont match anything', method:'GET'})
      assert(!match)
      done()
    })

    it('should match when the url correctly matches a route', function(done) {
      var handler = {controller:'controller'}
      router.register('/my/:id', handler)

      var match = router.match({url:'/my/value', method:'GET'})
      assert.equal(typeof match, 'object')
      assert.equal(match.controller, controller)
      assert(!match.action)
      done()
    })

    it('should match with an action', function(done) {
      var handler = {controller:'controller', action:'action'}
      router.register('/your/:id', handler)

      var match = router.match({url:'/your/value', method:'GET'})
      assert.equal(typeof match, 'object')
      assert.equal(match.controller, controller)
      assert.equal(match.action, 'action')
      done()
    })

    it('should match single HTTP method', function(done) {
      var handler = {controller:'controller', method:'GET'}
      router.register('/your/:id', handler)

      var match = router.match({url:'/your/value', method:'GET'})
      assert.equal(typeof match, 'object')
      assert.equal(match.controller, controller)
      done()
    })

    it('should match HTTP method array', function(done) {
      var handler = {controller:'controller', method:['GET','POST']}
      router.register('/your/:id', handler)

      var match = router.match({url:'/your/value', method:'GET'})
      assert.equal(typeof match, 'object')
      assert.equal(match.controller, controller)

      match = router.match({url:'/your/value', method:'POST'})
      assert.equal(typeof match, 'object')
      assert.equal(match.controller, controller)
      done()
    })

    it('should not match different HTTP methods', function(done) {
      var handler = {controller:'controller', method:['GET','POST']}
      router.register('/your/:id', handler)

      var match = router.match({url:'/your/value', method:'PUT'})
      assert(!match)
      done()
    })

    it('should match single HTTP method on action key', function(done) {
      var handler = {controller:'controller', index:'GET'}
      router.register('/your/:id', handler)

      var match = router.match({url:'/your/value', method:'GET'})
      assert.equal(typeof match, 'object')
      assert.equal(match.controller, controller)
      assert.equal(match.action, 'index')
      done()
    })

    it('should match HTTP method array on action key', function(done) {
      var handler = {controller:'controller', index:'GET'}
      router.register('/your/:id', handler)

      var match = router.match({url:'/your/value', method:'GET'})
      assert.equal(typeof match, 'object')
      assert.equal(match.controller, controller)
      assert.equal(match.action, 'index')
      done()
    })

    it('should match HTTP method array on action key', function(done) {
      var handler = {controller:'controller', index:'GET', create:'POST'}
      router.register('/your/:id', handler)

      var match = router.match({url:'/your/value', method:'GET'})
      assert.equal(typeof match, 'object')
      assert.equal(match.controller, controller)
      assert.equal(match.action, 'index')

      match = router.match({url:'/your/value', method:'POST'})
      assert.equal(typeof match, 'object')
      assert.equal(match.controller, controller)
      assert.equal(match.action, 'create')
      done()
    })

    it('should match the controller method defined last', function(done){
      var handler1 = {controller:'controller', index:'GET'}
      var handler2 = {controller:'controller', create:'POST'}
      router.register('/your/:id', handler1)
      router.register('/your/:id', handler2)

      var match = router.match({url:'/your/value', method:'GET'})
      assert(!match)

      match = router.match({url:'/your/value', method:'POST'})
      assert(match)
      assert.equal(typeof match, 'object')
      assert.equal(match.controller, controller)
      assert.equal(match.action, 'create')
      done()
    })

  })

})
<commit_msg>updated tests for updated syntax<commit_after>// Restful Routes, according to Rails: http://guides.rubyonrails.org/routing.html
// HTTP   Verb Path         action  used for
// ****** ***************** ******* ********
// GET    /photos           index   display a list of all photos
// GET    /photos/new       new     return an HTML form for creating a new photo
// POST   /photos           create  create a new photo
// GET    /photos/:id       show    display a specific photo
// GET    /photos/:id/edit  edit    return an HTML form for editing a photo
// PUT    /photos/:id       update  update a specific photo
// DELETE /photos/:id       destroy delete a specific photo

/*

  {
    '/photos' : {
      controller: 'controller',
      GET:        'index',
      POST:       'create'
    },
    '/photos/:id' : {
      controller: 'controller',
      GET:        'show',
      PUT:        'update',
      DELETE:     'destroy'
    },
    '/photos/:id/edit' : {
      controller: 'controller',
      GET:        'edit'
    }
  }

*/

var assert = require('assert')
var sinon = require('sinon')
var tf = require('./fixtures')
var router
var controller = require('./fixtures/controller')

describe('Router', function() {

  beforeEach(function(done) {
    // the router needs to be un-cached for these tests to work properly.
    delete require.cache[require.resolve('../router')]
    delete require.cache[require.resolve('routes')]

    router = require('../router')
    router.setControllerPath(__dirname+'/fixtures')
    done()
  })

  describe('Register', function() {

    it('should have register method', function(done) {
      assert(router.register)
      done()
    })

    it('should correctly register a route', function(done) {
      var route = '/route/:id'
      var handler = {controller:'controller'}
      router.register(route, handler)
      assert.equal(router.routes[route], handler)
      done()
    })

    it('should correctly register a route with object syntax', function(done) {
      var handler = {controller:'controller'}
      router.register({ '/my/:route': handler })
      assert.equal(router.routes['/my/:route'], handler)
      done()
    })

    it('should correctly register a route with object syntax and action string', function(done) {
      var handler = {controller:'controller', action:'index'}
      router.register({ '/my/:route': handler })
      assert.equal(router.routes['/my/:route'], handler)
      done()
    })

    it('should correctly register a route with object syntax and method array', function(done) {
      var handler = {controller:'controller', method:['GET','POST']}
      router.register({ '/my/:route': handler })
      assert.equal(router.routes['/my/:route'], handler)
      done()
    })

    it('should correctly register a route with object syntax and method key', function(done) {
      var handler = {controller:'controller', GET:'index'}
      router.register({ '/my/:route': handler })
      assert.equal(router.routes['/my/:route'], handler)
      done()
    })

    it('should correctly register a route with object syntax and many method keys', function(done) {
      var handler = {controller:'controller', GET:'index', POST:'create'}
      router.register({ '/my/:route': handler })
      assert.equal(router.routes['/my/:route'], handler)
      done()
    })

    it('should overwrite a route declared multiple times', function(done) {
      var handler1 = {controller:'controller', GET:'index'}
      var handler2 = {controller:'controller', POST:'index'}
      router.register('/my/:id', handler1)
      router.register('/my/:id', handler2)
      assert.equal(router.routes['/my/:id'], handler2)
      done()
    })

  })

  describe('Match', function(){

    it('should have a match method', function(done) {
      assert(router.match)
      done()
    })

    it('should return falsey value when the url does not match a route', function(done) {
      var match = router.match({url:'dont match anything', method:'GET'})
      assert(!match)
      done()
    })

    it('should match when the url correctly matches a route', function(done) {
      var handler = {controller:'controller'}
      router.register('/my/:id', handler)

      var match = router.match({url:'/my/value', method:'GET'})
      assert.equal(typeof match, 'object')
      assert.equal(match.controller, controller)
      assert(!match.action)
      done()
    })

    it('should match with an action', function(done) {
      var handler = {controller:'controller', action:'action'}
      router.register('/your/:id', handler)

      var match = router.match({url:'/your/value', method:'GET'})
      assert.equal(typeof match, 'object')
      assert.equal(match.controller, controller)
      assert.equal(match.action, 'action')
      done()
    })

    it('should match single HTTP method', function(done) {
      var handler = {controller:'controller', method:'GET'}
      router.register('/your/:id', handler)

      var match = router.match({url:'/your/value', method:'GET'})
      assert.equal(typeof match, 'object')
      assert.equal(match.controller, controller)
      done()
    })

    it('should match HTTP method array', function(done) {
      var handler = {controller:'controller', method:['GET','POST']}
      router.register('/your/:id', handler)

      var match = router.match({url:'/your/value', method:'GET'})
      assert.equal(typeof match, 'object')
      assert.equal(match.controller, controller)

      match = router.match({url:'/your/value', method:'POST'})
      assert.equal(typeof match, 'object')
      assert.equal(match.controller, controller)
      done()
    })

    it('should not match different HTTP methods', function(done) {
      var handler = {controller:'controller', method:['GET','POST']}
      router.register('/your/:id', handler)

      var match = router.match({url:'/your/value', method:'PUT'})
      assert(!match)
      done()
    })

    it('should match method key', function(done) {
      var handler = {controller:'controller', GET:'index'}
      router.register('/your/:id', handler)

      var match = router.match({url:'/your/value', method:'GET'})
      assert.equal(typeof match, 'object')
      assert.equal(match.controller, controller)
      assert.equal(match.action, 'index')
      done()
    })

    it('should match multiple method keys', function(done) {
      var handler = {controller:'controller', GET:'index', POST:'create'}
      router.register('/your/:id', handler)

      var match = router.match({url:'/your/value', method:'GET'})
      assert.equal(typeof match, 'object')
      assert.equal(match.controller, controller)
      assert.equal(match.action, 'index')

      match = router.match({url:'/your/value', method:'POST'})
      assert.equal(typeof match, 'object')
      assert.equal(match.controller, controller)
      assert.equal(match.action, 'create')
      done()
    })

    it('should match the controller method defined last', function(done){
      var handler1 = {controller:'controller', index:'GET'}
      var handler2 = {controller:'controller', create:'POST'}
      router.register('/your/:id', handler1)
      router.register('/your/:id', handler2)

      var match = router.match({url:'/your/value', method:'GET'})
      assert(!match)

      match = router.match({url:'/your/value', method:'POST'})
      assert(match)
      assert.equal(typeof match, 'object')
      assert.equal(match.controller, controller)
      assert.equal(match.action, 'create')
      done()
    })

  })

})
<|endoftext|>


<commit_before>var OverviewBox;
var view = require("backbone-viewj");
var mouse = require("mouse-pos");
var selection = require("../g/selection/Selection");
var jbone = require("jbone");
var _ = require("underscore");

module.exports = OverviewBox = view.extend({

  className: "biojs_msa_overviewbox",
  tagName: "canvas",

  initialize: function(data) {
    this.g = data.g;
    this.listenTo( this.g.zoomer,"change:boxRectWidth change:boxRectHeight change:overviewboxPaddingTop", this.rerender);
    this.listenTo(this.g.selcol, "add reset change", this.rerender);
    this.listenTo(this.g.columns, "change:hidden", this.rerender);
    this.listenTo(this.g.colorscheme, "change:showLowerCase", this.rerender);
    this.listenTo(this.model, "change", _.debounce(this.rerender, 5));

    // color
    this.color = this.g.colorscheme.getSelectedScheme();
    this.listenTo(this.g.colorscheme, "change:scheme", function() {
      this.color = this.g.colorscheme.getSelectedScheme();
      return this.rerender();
    });
    return this.dragStart = [];
  },

  events:
    {click: "_onclick",
    mousedown: "_onmousedown"
    },

  rerender: function() {
    if (!this.g.config.get("manualRendering")) {
      return this.render();
    }
  },

  render: function() {
    this._createCanvas();
    this.el.textContent = "overview";
    this.el.style.marginTop = this.g.zoomer.get("overviewboxPaddingTop");

    // background bg for non-drawed area
    this.ctx.fillStyle = "#999999";
    this.ctx.fillRect(0,0,this.el.width,this.el.height);

    var rectWidth = this.g.zoomer.get("boxRectWidth");
    var rectHeight = this.g.zoomer.get("boxRectHeight");
    var hidden = this.g.columns.get("hidden");
    var showLowerCase = this.g.colorscheme.get("showLowerCase");

    var y = -rectHeight;
    var end = this.model.length - 1;
    for (var i = 0; 0 < end ? i <= end : i >= end; 0 < end ? i++ : i++) {
      var seq = this.model.at(i).get("seq");
      var x = 0;
      y = y + rectHeight;

      if (this.model.at(i).get("hidden")) {
        // hidden seq
        console.log(this.model.at(i).get("hidden"));
        this.ctx.fillStyle = "grey";
        this.ctx.fillRect(0,y,seq.length * rectWidth,rectHeight);
        continue;
      }

      var end1 = seq.length - 1;
      for (var j = 0; 0 < end1 ? j <= end1 : j >= end1; 0 < end1 ? j++ : j++) {
        var c = seq[j];
        // todo: optional uppercasing
        if (showLowerCase) { c = c.toUpperCase(); }
        var color = this.color.getColor(c, {pos: j});

        if (hidden.indexOf(j) >= 0) {
          color = "grey";
        }

        if ((typeof color !== "undefined" && color !== null)) {
          this.ctx.fillStyle = color;
          this.ctx.fillRect(x,y,rectWidth,rectHeight);
        }

        x = x + rectWidth;
      }
    }

    return this._drawSelection();
  },

  _drawSelection: function() {
    // hide during selection
    if (this.dragStart.length > 0 && !this.prolongSelection) { return; }

    var rectWidth = this.g.zoomer.get("boxRectWidth");
    var rectHeight = this.g.zoomer.get("boxRectHeight");
    var maxHeight = rectHeight * this.model.length;
    this.ctx.fillStyle = "#666666";
    this.ctx.globalAlpha = 0.9;
    var end = this.g.selcol.length - 1;
    for (var i = 0; 0 < end ? i <= end : i >= end; 0 < end ? i++ : i++) {
      var sel = this.g.selcol.at(i);
      if(!sel) continue;
      if (sel.get('type') === 'column') {
        this.ctx.fillRect( rectWidth * sel.get('xStart'),0,rectWidth *
        (sel.get('xEnd') - sel.get('xStart') + 1),maxHeight
        );
      } else if (sel.get('type') === 'row') {
        var seq = (this.model.filter(function(el) { return el.get('id') === sel.get('seqId'); }))[0];
        var pos = this.model.indexOf(seq);
        this.ctx.fillRect(0,rectHeight * pos, rectWidth * seq.get('seq').length, rectHeight);
      } else if (sel.get('type') === 'pos') {
        seq = (this.model.filter(function(el) { return el.get('id') === sel.get('seqId'); }))[0];
        pos = this.model.indexOf(seq);
        this.ctx.fillRect(rectWidth * sel.get('xStart'),rectHeight * pos, rectWidth * (sel.get('xEnd') - sel.get('xStart') + 1), rectHeight);
      }
    }

    return this.ctx.globalAlpha = 1;
  },

  _onclick: function(evt) {
    return this.g.trigger("meta:click", {seqId: this.model.get("id", {evt:evt})});
  },

  _onmousemove: function(e) {
    // duplicate events
    if (this.dragStart.length === 0) { return; }

    this.render();
    this.ctx.fillStyle = "#666666";
    this.ctx.globalAlpha = 0.9;

    var rect = this._calcSelection( mouse.abs(e) );
    this.ctx.fillRect(rect[0][0],rect[1][0],rect[0][1] - rect[0][0], rect[1][1] - rect[1][0]);

    // abort selection events of the browser
    e.preventDefault();
    return e.stopPropagation();
  },

  // start the selection mode
  _onmousedown: function(e) {
    this.dragStart = mouse.abs(e);
    this.dragStartRel = mouse.rel(e);

    if (e.ctrlKey || e.metaKey) {
      this.prolongSelection = true;
    } else {
      this.prolongSelection = false;
    }
    // enable global listeners
    jbone(document.body).on('mousemove.overmove', (e) => this._onmousemove(e));
    jbone(document.body).on('mouseup.overup', (e) => this._onmouseup(e));
    return this.dragStart;
  },

  // calculates the current selection
  _calcSelection: function(dragMove) {
    // relative to first click
    var dragRel = [dragMove[0] - this.dragStart[0], dragMove[1] - this.dragStart[1]];

    // relative to target
    for (var i = 0; i <= 1; i++) {
      dragRel[i] = this.dragStartRel[i] + dragRel[i];
    }

    // 0:x, 1: y
    var rect = [[this.dragStartRel[0], dragRel[0]], [this.dragStartRel[1], dragRel[1]]];

    // swap the coordinates if needed
    for (var i = 0; i <= 1; i++) {
      if (rect[i][1] < rect[i][0]) {
        rect[i] = [rect[i][1], rect[i][0]];
      }

      // lower limit
      rect[i][0] = Math.max(rect[i][0], 0);
    }

    return rect;
  },

  _endSelection: function(dragEnd) {
    // remove listeners
    jbone(document.body).off('.overmove');
    jbone(document.body).off('.overup');

    // duplicate events
    if (this.dragStart.length === 0) { return; }

    var rect = this._calcSelection(dragEnd);

    // x
    for (var i = 0; i <= 1; i++) {
      rect[0][i] = Math.floor( rect[0][i] / this.g.zoomer.get("boxRectWidth"));
    }

    // y
    for (var i = 0; i <= 1; i++) {
      rect[1][i] = Math.floor( rect[1][i] / this.g.zoomer.get("boxRectHeight") );
    }

    // upper limit
    rect[0][1] = Math.min(this.model.getMaxLength() - 1, rect[0][1]);
    rect[1][1] = Math.min(this.model.length - 1, rect[1][1]);

    // select
    var selis = [];
    for (var j = rect[1][0]; rect[1][0] < rect[1][1] ? j <= rect[1][1] : j >= rect[1][1]; rect[1][0] < rect[1][1] ? j++ : j++) {
      var args = {seqId: this.model.at(j).get('id'), xStart: rect[0][0], xEnd: rect[0][1]};
      selis.push(new selection.possel(args));
    }

    // reset
    this.dragStart = [];
    // look for ctrl key
    if (this.prolongSelection) {
      this.g.selcol.add(selis);
    } else {
      this.g.selcol.reset(selis);
    }

    // safety check + update offset
    this.g.zoomer.setLeftOffset(rect[0][0]);
    return this.g.zoomer.setTopOffset(rect[1][0]);
  },

  // ends the selection mode
  _onmouseup: function(e) {
    return this._endSelection(mouse.abs(e));
  },

  _onmouseout: function(e) {
    return this._endSelection(mouse.abs(e));
  },

 // init the canvas
  _createCanvas: function() {
    var rectWidth = this.g.zoomer.get("boxRectWidth");
    var rectHeight = this.g.zoomer.get("boxRectHeight");

    this.el.height = this.model.length * rectHeight;
    this.el.width = this.model.getMaxLength() * rectWidth;
    this.ctx = this.el.getContext("2d");
    this.el.style.overflow = "scroll";
    return this.el.style.cursor = "crosshair";
  }
});
<commit_msg>fix #116 (typo in loop conditions)<commit_after>var OverviewBox;
var view = require("backbone-viewj");
var mouse = require("mouse-pos");
var selection = require("../g/selection/Selection");
var jbone = require("jbone");
var _ = require("underscore");

module.exports = OverviewBox = view.extend({

  className: "biojs_msa_overviewbox",
  tagName: "canvas",

  initialize: function(data) {
    this.g = data.g;
    this.listenTo( this.g.zoomer,"change:boxRectWidth change:boxRectHeight change:overviewboxPaddingTop", this.rerender);
    this.listenTo(this.g.selcol, "add reset change", this.rerender);
    this.listenTo(this.g.columns, "change:hidden", this.rerender);
    this.listenTo(this.g.colorscheme, "change:showLowerCase", this.rerender);
    this.listenTo(this.model, "change", _.debounce(this.rerender, 5));

    // color
    this.color = this.g.colorscheme.getSelectedScheme();
    this.listenTo(this.g.colorscheme, "change:scheme", function() {
      this.color = this.g.colorscheme.getSelectedScheme();
      return this.rerender();
    });
    return this.dragStart = [];
  },

  events:
    {click: "_onclick",
    mousedown: "_onmousedown"
    },

  rerender: function() {
    if (!this.g.config.get("manualRendering")) {
      return this.render();
    }
  },

  render: function() {
    this._createCanvas();
    this.el.textContent = "overview";
    this.el.style.marginTop = this.g.zoomer.get("overviewboxPaddingTop");

    // background bg for non-drawed area
    this.ctx.fillStyle = "#999999";
    this.ctx.fillRect(0,0,this.el.width,this.el.height);

    var rectWidth = this.g.zoomer.get("boxRectWidth");
    var rectHeight = this.g.zoomer.get("boxRectHeight");
    var hidden = this.g.columns.get("hidden");
    var showLowerCase = this.g.colorscheme.get("showLowerCase");

    var y = -rectHeight;
    var end = this.model.length - 1;
    for (var i = 0; 0 < end ? i <= end : i >= end; 0 < end ? i++ : i--) {
      var seq = this.model.at(i).get("seq");
      var x = 0;
      y = y + rectHeight;

      if (this.model.at(i).get("hidden")) {
        // hidden seq
        console.log(this.model.at(i).get("hidden"));
        this.ctx.fillStyle = "grey";
        this.ctx.fillRect(0,y,seq.length * rectWidth,rectHeight);
        continue;
      }

      var end1 = seq.length - 1;
      for (var j = 0; 0 < end1 ? j <= end1 : j >= end1; 0 < end1 ? j++ : j--) {
        var c = seq[j];
        // todo: optional uppercasing
        if (showLowerCase) { c = c.toUpperCase(); }
        var color = this.color.getColor(c, {pos: j});

        if (hidden.indexOf(j) >= 0) {
          color = "grey";
        }

        if ((typeof color !== "undefined" && color !== null)) {
          this.ctx.fillStyle = color;
          this.ctx.fillRect(x,y,rectWidth,rectHeight);
        }

        x = x + rectWidth;
      }
    }

    return this._drawSelection();
  },

  _drawSelection: function() {
    // hide during selection
    if (this.dragStart.length > 0 && !this.prolongSelection) { return; }

    var rectWidth = this.g.zoomer.get("boxRectWidth");
    var rectHeight = this.g.zoomer.get("boxRectHeight");
    var maxHeight = rectHeight * this.model.length;
    this.ctx.fillStyle = "#666666";
    this.ctx.globalAlpha = 0.9;
    if ( this.g.selcol.length == 0 ) {
      console.log( "" );
      //return;
    }
    var end = this.g.selcol.length - 1;
    for (var i = 0; 0 < end ? i <= end : i >= end; 0 < end ? i++ : i--) {
      var sel = this.g.selcol.at(i);
      if(!sel) continue;
      if (sel.get('type') === 'column') {
        this.ctx.fillRect( rectWidth * sel.get('xStart'),0,rectWidth *
        (sel.get('xEnd') - sel.get('xStart') + 1),maxHeight
        );
      } else if (sel.get('type') === 'row') {
        var seq = (this.model.filter(function(el) { return el.get('id') === sel.get('seqId'); }))[0];
        var pos = this.model.indexOf(seq);
        this.ctx.fillRect(0,rectHeight * pos, rectWidth * seq.get('seq').length, rectHeight);
      } else if (sel.get('type') === 'pos') {
        seq = (this.model.filter(function(el) { return el.get('id') === sel.get('seqId'); }))[0];
        pos = this.model.indexOf(seq);
        this.ctx.fillRect(rectWidth * sel.get('xStart'),rectHeight * pos, rectWidth * (sel.get('xEnd') - sel.get('xStart') + 1), rectHeight);
      }
    }

    return this.ctx.globalAlpha = 1;
  },

  _onclick: function(evt) {
    return this.g.trigger("meta:click", {seqId: this.model.get("id", {evt:evt})});
  },

  _onmousemove: function(e) {
    // duplicate events
    if (this.dragStart.length === 0) { return; }

    this.render();
    this.ctx.fillStyle = "#666666";
    this.ctx.globalAlpha = 0.9;

    var rect = this._calcSelection( mouse.abs(e) );
    this.ctx.fillRect(rect[0][0],rect[1][0],rect[0][1] - rect[0][0], rect[1][1] - rect[1][0]);

    // abort selection events of the browser
    e.preventDefault();
    return e.stopPropagation();
  },

  // start the selection mode
  _onmousedown: function(e) {
    this.dragStart = mouse.abs(e);
    this.dragStartRel = mouse.rel(e);

    if (e.ctrlKey || e.metaKey) {
      this.prolongSelection = true;
    } else {
      this.prolongSelection = false;
    }
    // enable global listeners
    jbone(document.body).on('mousemove.overmove', (e) => this._onmousemove(e));
    jbone(document.body).on('mouseup.overup', (e) => this._onmouseup(e));
    return this.dragStart;
  },

  // calculates the current selection
  _calcSelection: function(dragMove) {
    // relative to first click
    var dragRel = [dragMove[0] - this.dragStart[0], dragMove[1] - this.dragStart[1]];

    // relative to target
    for (var i = 0; i <= 1; i++) {
      dragRel[i] = this.dragStartRel[i] + dragRel[i];
    }

    // 0:x, 1: y
    var rect = [[this.dragStartRel[0], dragRel[0]], [this.dragStartRel[1], dragRel[1]]];

    // swap the coordinates if needed
    for (var i = 0; i <= 1; i++) {
      if (rect[i][1] < rect[i][0]) {
        rect[i] = [rect[i][1], rect[i][0]];
      }

      // lower limit
      rect[i][0] = Math.max(rect[i][0], 0);
    }

    return rect;
  },

  _endSelection: function(dragEnd) {
    // remove listeners
    jbone(document.body).off('.overmove');
    jbone(document.body).off('.overup');

    // duplicate events
    if (this.dragStart.length === 0) { return; }

    var rect = this._calcSelection(dragEnd);

    // x
    for (var i = 0; i <= 1; i++) {
      rect[0][i] = Math.floor( rect[0][i] / this.g.zoomer.get("boxRectWidth"));
    }

    // y
    for (var i = 0; i <= 1; i++) {
      rect[1][i] = Math.floor( rect[1][i] / this.g.zoomer.get("boxRectHeight") );
    }

    // upper limit
    rect[0][1] = Math.min(this.model.getMaxLength() - 1, rect[0][1]);
    rect[1][1] = Math.min(this.model.length - 1, rect[1][1]);

    // select
    var selis = [];
    for (var j = rect[1][0]; rect[1][0] < rect[1][1] ? j <= rect[1][1] : j >= rect[1][1]; rect[1][0] < rect[1][1] ? j++ : j++) {
      var args = {seqId: this.model.at(j).get('id'), xStart: rect[0][0], xEnd: rect[0][1]};
      selis.push(new selection.possel(args));
    }

    // reset
    this.dragStart = [];
    // look for ctrl key
    if (this.prolongSelection) {
      this.g.selcol.add(selis);
    } else {
      this.g.selcol.reset(selis);
    }

    // safety check + update offset
    this.g.zoomer.setLeftOffset(rect[0][0]);
    return this.g.zoomer.setTopOffset(rect[1][0]);
  },

  // ends the selection mode
  _onmouseup: function(e) {
    return this._endSelection(mouse.abs(e));
  },

  _onmouseout: function(e) {
    return this._endSelection(mouse.abs(e));
  },

 // init the canvas
  _createCanvas: function() {
    var rectWidth = this.g.zoomer.get("boxRectWidth");
    var rectHeight = this.g.zoomer.get("boxRectHeight");

    this.el.height = this.model.length * rectHeight;
    this.el.width = this.model.getMaxLength() * rectWidth;
    this.ctx = this.el.getContext("2d");
    this.el.style.overflow = "scroll";
    return this.el.style.cursor = "crosshair";
  }
});
<|endoftext|>


<commit_before>"use strict";
// Mocha
var chai = require("chai");
var expect = chai.expect;
// server
var express = require("express");
var serveStatic = require("serve-static");
var app = express();
// scraper
var sjs = require("scraperjs");
// constants
var BASE_URL = "http://localhost";
var PORT = 3000;
var MODELS_DIR = "/spec/models/";
var SERVER_LISTENING = BASE_URL + ":" + PORT;
// todo: fix the hardcoded value on json file.

before("start server", function (done) {
  app.use(serveStatic(__dirname + MODELS_DIR));
  isPortTaken(PORT, function (err, data) {
    if (!data) {
      app.listen(PORT);
    }
    done();
  });
});

after(function () {
  console.log("NODE_ENV: %s \n", process.env.NODE_ENV); //eslint-disable-line no-console

});

describe("Server is on \n", function () {

  it("Confirm server & scraper are working with index.html", function () {
    sjs.StaticScraper.create(SERVER_LISTENING)
      .scrape(function ($) {
        return $("h1").text();
      })
      .then(function (data) {
        expect(data).to.eql("Models");
      });
  });

});

function isPortTaken(port, fn) {
  var net = require("net");
  var tester = net.createServer()
    .once("error", function (err) {
      if (err.code != "EADDRINUSE") {
        return fn(err);
      }
      fn(null, true);
    })
    .once("listening", function () {
      tester.once("close", function () {
        fn(null, false);
      })
        .close();
    })
    .listen(port);

}
<commit_msg>cleanup<commit_after>"use strict";
// Mocha
var chai = require("chai");
var expect = chai.expect;
// server
var express = require("express");
var serveStatic = require("serve-static");
var app = express();
// scraper
var sjs = require("scraperjs");
// constants
var BASE_URL = "http://localhost";
var PORT = 3000;
var MODELS_DIR = "/spec/models/";
var SERVER_LISTENING = BASE_URL + ":" + PORT;

before("start server", function (done) {
  app.use(serveStatic(__dirname + MODELS_DIR));
  isPortTaken(PORT, function (err, data) {
    if (!data) {
      app.listen(PORT);
    }
    done();
  });
});

after(function () {
  console.log("NODE_ENV: %s \n", process.env.NODE_ENV); //eslint-disable-line no-console

});

describe("Server is on \n", function () {

  it("Confirm server & scraper are working with index.html", function () {
    sjs.StaticScraper.create(SERVER_LISTENING)
      .scrape(function ($) {
        return $("h1").text();
      })
      .then(function (data) {
        expect(data).to.eql("Models");
      });
  });

});

function isPortTaken(port, fn) {
  var net = require("net");
  var tester = net.createServer()
    .once("error", function (err) {
      if (err.code != "EADDRINUSE") {
        return fn(err);
      }
      fn(null, true);
    })
    .once("listening", function () {
      tester.once("close", function () {
        fn(null, false);
      })
        .close();
    })
    .listen(port);

}
<|endoftext|>


<commit_before>// Import React
import React from "react";

// Import Spectacle Core tags
import {
  Appear,
  BlockQuote,
  Cite,
  CodePane,
  Deck,
  Fill,
  Heading,
  Image,
  Layout,
  Link,
  ListItem,
  List,
  Markdown,
  Quote,
  Slide,
  Spectacle,
  Text
} from "spectacle";

// Import image preloader util
import preloader from "spectacle/lib/utils/preloader";

// Import theme
import createTheme from "spectacle/lib/themes/default";

// Import custom component
import Interactive from "../assets/interactive";

// Require CSS
require("normalize.css");
require("spectacle/lib/themes/default/index.css");

const images = {
  ih: require("../assets/IHZ_150916_master_locations_1.jpg"),
  ih_logo: require("../assets/IHZ_ect_Logo_white.png"),
  logo: require("../assets/FHNW_HT_10mm.png"),
};

preloader(images);

const theme = createTheme({
  primary: "#198caa"
});

export default class Presentation extends React.Component {
  render() {
    return (
      <Spectacle theme={theme}>
        <Deck transition={["zoom", "slide"]} transitionDuration={500}>
          <Slide transition={["slide", "spin"]} bgColor="primary">
            <Heading size={1} fit textColor="white">Bachelorthesis - HubApp</Heading>
            <Text textColor="white">Developed with ❤ by Livio and Raphael</Text>
            <Image src={images.logo} width="300" style={{marginTop: 100}} />
          </Slide>
          <Slide bgImage={images.ih} align="flex-start" bgDarken={0.3}>
            <Layout>
              <Fill>
                <Heading fit size={1} textColor="white">Impact Hub</Heading>
              </Fill>
              <Fill>
                <Image src={images.ih_logo} align="flex-start" width="40%" />
              </Fill>
            </Layout>
            <Layout style={{ marginTop: 20 }}>
              <Fill>
                <Text textColor="white" textAlign="left">
                  Impact Hub hat weltweit über 12000 Mitglieder, davon sind etwa 700 in Zürich.
                </Text>
                <Text textColor="white" textAlign="left">
                  Zurzeit hat es vier Standorte in Zürich.
                </Text>
                <Text textColor="white" textAlign="left">
                  Das Suchen von Personen innerhalb der Community findet zurzeit durch Mundpropaganda statt, da bisherige Tools dazu nicht geeignet sind.
                </Text>
              </Fill>
              <Fill>
                <Text textColor="white" textAlign="left">
                  Dies dauert lange und kostet Ressourcen bei den Mitarbeiter.
                </Text>
                <Text textColor="white" textAlign="left">
                  Dass soll in Zukunft geändert werden.
                </Text>
              </Fill>
            </Layout>
          </Slide>
          <Slide>
            <Heading size={1} textColor="white">Aufgaben</Heading>
            <Layout style={{ marginTop: 20 }}>
              <Fill>
                <Heading size={2} bgColor="white" style={{ margin: 10, marginRight: 5 }} textColor="primary" padding={15}>Word2Vec</Heading>
                <Heading size={2} bgColor="white" style={{ margin: 10, marginRight: 5 }} textColor="primary" padding={15}>Jaccard</Heading>
              </Fill>
              <Fill>
                <Heading size={2} bgColor="white" style={{ margin: 10, marginLeft: 5 }} textColor="primary" padding={15}>Motivation</Heading>
                <Heading size={2} bgColor="white" style={{ margin: 10, marginLeft: 5 }} textColor="primary" padding={15}>Tagging</Heading>
              </Fill>
            </Layout>
          </Slide>
          <Slide transition={["zoom"]} bgColor="primary">
            <Heading size={1} fit caps lineHeight={1} textColor="black">
              Spectacle
            </Heading>
            <Heading size={1} fit caps>
              A ReactJS Presentation Library
            </Heading>
            <Heading size={1} fit caps textColor="black">
              Where You Can Write Your Decks In JSX
            </Heading>
            <Link href="https://github.com/FormidableLabs/spectacle">
              <Text bold caps textColor="tertiary">View on Github</Text>
            </Link>
            <Text textSize="1.5em" margin="20px 0px 0px" bold>Hit Your Right Arrow To Begin!</Text>
          </Slide>
          <Slide transition={["slide"]} bgColor="black" notes="You can even put notes on your slide. How awesome is that?">
            <Image src={images.ih.replace("/", "")} margin="0px auto 40px" height="293px"/>
            <Heading size={2} caps fit textColor="primary" textFont="primary">
              Wait what?
            </Heading>
          </Slide>
          <Slide transition={["zoom", "fade"]} bgColor="primary" notes="

talk about that

and that

">
            <CodePane
              lang="jsx"
              source={require("raw!../assets/deck.example")}
              margin="20px auto"
            />
          </Slide>
          <Slide transition={["slide"]} bgImage={images.ih.replace("/", "")} bgDarken={0.75}>
            <Appear fid="1">
              <Heading size={1} caps fit textColor="primary">
                Full Width
              </Heading>
            </Appear>
            <Appear fid="2">
              <Heading size={1} caps fit textColor="tertiary">
                Adjustable Darkness
              </Heading>
            </Appear>
            <Appear fid="3">
              <Heading size={1} caps fit textColor="primary">
                Background Imagery
              </Heading>
            </Appear>
          </Slide>
          <Slide transition={["zoom", "fade"]} bgColor="primary">
            <Heading caps fit>Flexible Layouts</Heading>
            <Layout>
              <Fill>
                <Heading size={4} caps textColor="secondary" bgColor="white" margin={10}>
                  Left
                </Heading>
              </Fill>
              <Fill>
                <Heading size={4} caps textColor="secondary" bgColor="white" margin={10}>
                  Right
                </Heading>
              </Fill>
            </Layout>
          </Slide>
          <Slide transition={["slide"]} bgColor="black">

              <Quote>Wonderfully formatted quotes</Quote>
              Ken Wheeler

          </Slide>
          <Slide transition={["spin", "zoom"]} bgColor="tertiary">
            <Heading caps fit size={1} textColor="primary">
              Inline Markdown
            </Heading>
            <Markdown>
              {`
You can write inline images, [Markdown Links](http://commonmark.org), paragraph text and most other markdown syntax
* Lists too!
* With ~~strikethrough~~ and _italic_
* And lets not forget **bold**
              `}
            </Markdown>
          </Slide>
          <Slide transition={["slide", "spin"]} bgColor="primary">
            <Heading caps fit size={1} textColor="tertiary">
              Smooth
            </Heading>
            <Heading caps fit size={1} textColor="secondary">
              Combinable Transitions
            </Heading>
          </Slide>
          <Slide transition={["fade"]} bgColor="secondary" textColor="primary">
            <List>
              <Appear><ListItem>Inline style based theme system</ListItem></Appear>
              <Appear><ListItem>Autofit text</ListItem></Appear>
              <Appear><ListItem>Flexbox layout system</ListItem></Appear>
              <Appear><ListItem>React-Router navigation</ListItem></Appear>
              <Appear><ListItem>PDF export</ListItem></Appear>
              <Appear><ListItem>And...</ListItem></Appear>
            </List>
          </Slide>
          <Slide transition={["slide"]} bgColor="primary">
            <Heading size={1} caps fit textColor="tertiary">
              Your presentations are interactive
            </Heading>
            <Interactive/>
          </Slide>
          <Slide transition={["spin", "slide"]} bgColor="tertiary">
            <Heading size={1} caps fit lineHeight={1.5} textColor="primary">
              Made with love in Seattle by
            </Heading>
            <Link href="http://www.formidablelabs.com"><Image width="100%" src={images.logo}/></Link>
          </Slide>
        </Deck>
      </Spectacle>
    );
  }
}
<commit_msg>skeletton<commit_after>// Import React
import React from "react";

// Import Spectacle Core tags
import {
  Appear,
  BlockQuote,
  Cite,
  CodePane,
  Deck,
  Fill,
  Heading,
  Image,
  Layout,
  Link,
  ListItem,
  List,
  Markdown,
  Quote,
  Slide,
  Spectacle,
  Text
} from "spectacle";

// Import image preloader util
import preloader from "spectacle/lib/utils/preloader";

// Import theme
import createTheme from "spectacle/lib/themes/default";

// Import custom component
import Interactive from "../assets/interactive";

// Require CSS
require("normalize.css");
require("spectacle/lib/themes/default/index.css");

const images = {
  ih: require("../assets/IHZ_150916_master_locations_1.jpg"),
  iha: require("../assets/IHZ_150916_master_locations_3.jpg"),
  ih_logo: require("../assets/IHZ_ect_Logo_white.png"),
  logo: require("../assets/FHNW_HT_10mm.png"),
};

preloader(images);

const theme = createTheme({
  primary: "#198caa"
});

export default class Presentation extends React.Component {
  render() {
    return (
      <Spectacle theme={theme}>
        <Deck transition={["zoom", "slide"]} transitionDuration={500}>
          <Slide transition={["slide", "spin"]} bgColor="primary">
            <Heading size={1} fit textColor="white">Bachelorthesis - HubApp</Heading>
            <Text textColor="white">Developed with ❤ by Livio and Raphael</Text>
            <Image src={images.logo} width="300" style={{marginTop: 100}} />
          </Slide>
          <Slide bgImage={images.ih} align="flex-start" bgDarken={0.3}>
            <Layout>
              <Fill>
                <Heading fit size={1} textColor="white">Impact Hub</Heading>
              </Fill>
              <Fill>
                <Image src={images.ih_logo} align="flex-start" width="40%" />
              </Fill>
            </Layout>
            <Layout style={{ marginTop: 20 }}>
              <Fill>
                <Text textColor="white" textAlign="left">
                  Impact Hub hat weltweit über 12000 Mitglieder, davon sind etwa 700 in Zürich.
                </Text>
                <Text textColor="white" textAlign="left">
                  Zurzeit hat es vier Standorte in Zürich.
                </Text>
                <Text textColor="white" textAlign="left">
                  Das Suchen von Personen innerhalb der Community findet zurzeit durch Mundpropaganda statt, da bisherige Tools dazu nicht geeignet sind.
                </Text>
              </Fill>
              <Fill>
                <Text textColor="white" textAlign="left">
                  Dies dauert lange und kostet Ressourcen bei den Mitarbeiter.
                </Text>
                <Text textColor="white" textAlign="left">
                  Dass soll in Zukunft geändert werden.
                </Text>
              </Fill>
            </Layout>
          </Slide>
          <Slide bgImage={images.iha} bgDarken={0.5}>
            <Heading size={1} textColor="primary" padding={20} margin={10} style={{ marginBottom: 0 }} bgColor="white">Herausforderungen</Heading>
            <Layout style={{ marginTop: 0 }}>
              <Fill>
                <Heading size={2} bgColor="white" style={{ margin: 10, marginRight: 5 }} textColor="primary" padding={15}>Word2Vec</Heading>
                <Heading size={2} bgColor="white" style={{ margin: 10, marginRight: 5 }} textColor="primary" padding={15}>Jaccard</Heading>
              </Fill>
              <Fill>
                <Heading size={2} bgColor="white" style={{ margin: 10, marginLeft: 5 }} textColor="primary" padding={15}>Motivation</Heading>
                <Heading size={2} bgColor="white" style={{ margin: 10, marginLeft: 5 }} textColor="primary" padding={15}>Tagging</Heading>
              </Fill>
            </Layout>
          </Slide>
          <Slide>
            <Heading>Herausforderungen</Heading>
          </Slide>
          <Slide>
            <Heading>Highligts</Heading>
          </Slide>
          <Slide>
            <Heading>Reflexion</Heading>
          </Slide>
          <Slide transition={["zoom"]} bgColor="primary">
            <Heading size={1} fit caps lineHeight={1} textColor="black">
              Spectacle
            </Heading>
            <Heading size={1} fit caps>
              A ReactJS Presentation Library
            </Heading>
            <Heading size={1} fit caps textColor="black">
              Where You Can Write Your Decks In JSX
            </Heading>
            <Link href="https://github.com/FormidableLabs/spectacle">
              <Text bold caps textColor="tertiary">View on Github</Text>
            </Link>
            <Text textSize="1.5em" margin="20px 0px 0px" bold>Hit Your Right Arrow To Begin!</Text>
          </Slide>
          <Slide transition={["slide"]} bgColor="black" notes="You can even put notes on your slide. How awesome is that?">
            <Image src={images.ih.replace("/", "")} margin="0px auto 40px" height="293px"/>
            <Heading size={2} caps fit textColor="primary" textFont="primary">
              Wait what?
            </Heading>
          </Slide>
          <Slide transition={["zoom", "fade"]} bgColor="primary" notes="

talk about that

and that

">
            <CodePane
              lang="jsx"
              source={require("raw!../assets/deck.example")}
              margin="20px auto"
            />
          </Slide>
          <Slide transition={["slide"]} bgImage={images.ih.replace("/", "")} bgDarken={0.75}>
            <Appear fid="1">
              <Heading size={1} caps fit textColor="primary">
                Full Width
              </Heading>
            </Appear>
            <Appear fid="2">
              <Heading size={1} caps fit textColor="tertiary">
                Adjustable Darkness
              </Heading>
            </Appear>
            <Appear fid="3">
              <Heading size={1} caps fit textColor="primary">
                Background Imagery
              </Heading>
            </Appear>
          </Slide>
          <Slide transition={["zoom", "fade"]} bgColor="primary">
            <Heading caps fit>Flexible Layouts</Heading>
            <Layout>
              <Fill>
                <Heading size={4} caps textColor="secondary" bgColor="white" margin={10}>
                  Left
                </Heading>
              </Fill>
              <Fill>
                <Heading size={4} caps textColor="secondary" bgColor="white" margin={10}>
                  Right
                </Heading>
              </Fill>
            </Layout>
          </Slide>
          <Slide transition={["slide"]} bgColor="black">

              <Quote>Wonderfully formatted quotes</Quote>
              Ken Wheeler

          </Slide>
          <Slide transition={["spin", "zoom"]} bgColor="tertiary">
            <Heading caps fit size={1} textColor="primary">
              Inline Markdown
            </Heading>
            <Markdown>
              {`
You can write inline images, [Markdown Links](http://commonmark.org), paragraph text and most other markdown syntax
* Lists too!
* With ~~strikethrough~~ and _italic_
* And lets not forget **bold**
              `}
            </Markdown>
          </Slide>
          <Slide transition={["slide", "spin"]} bgColor="primary">
            <Heading caps fit size={1} textColor="tertiary">
              Smooth
            </Heading>
            <Heading caps fit size={1} textColor="secondary">
              Combinable Transitions
            </Heading>
          </Slide>
          <Slide transition={["fade"]} bgColor="secondary" textColor="primary">
            <List>
              <Appear><ListItem>Inline style based theme system</ListItem></Appear>
              <Appear><ListItem>Autofit text</ListItem></Appear>
              <Appear><ListItem>Flexbox layout system</ListItem></Appear>
              <Appear><ListItem>React-Router navigation</ListItem></Appear>
              <Appear><ListItem>PDF export</ListItem></Appear>
              <Appear><ListItem>And...</ListItem></Appear>
            </List>
          </Slide>
          <Slide transition={["slide"]} bgColor="primary">
            <Heading size={1} caps fit textColor="tertiary">
              Your presentations are interactive
            </Heading>
            <Interactive/>
          </Slide>
          <Slide transition={["spin", "slide"]} bgColor="tertiary">
            <Heading size={1} caps fit lineHeight={1.5} textColor="primary">
              Made with love in Seattle by
            </Heading>
            <Link href="http://www.formidablelabs.com"><Image width="100%" src={images.logo}/></Link>
          </Slide>
        </Deck>
      </Spectacle>
    );
  }
}
<|endoftext|>


<commit_before>(function(){

  function DuplicateItemError( errorMessage, listItem ) {
    return {msg:errorMessage, item:listItem};
  }

  function Matrix( x, y ) {
    this.ARRAY = [1,2,3,4,5,6,7,8,9];
    this.x = x;
    this.y = y;
    this.init();
    this.prefill();
    this.draw();
    this.validate();
    this.solve();
  }
  Matrix.prototype = {
    constructor: Matrix,

    init: function() {
      console.log('initialize here ..');
      this.grid = [];
      for (var i = 0; i < this.y; i += 1) {
        this.grid[i] = [];
        for (var y = 0; y < this.x; y += 1) {
          this.grid[i][y] = null;
        }
      }
      //console.log('GRID: %o', this.grid);
    },

    draw: function() {
      console.log('drawing..');
      var $element;
      var x, y;
      for (x = 0; x < this.grid.length; x += 1) {
        for (y = 0; y < this.grid[x].length; y += 1) {
          if (y == 8) {
            $element = $('

').appendTo('#main');
          } else {
            $element = $('

').appendTo('#main');
          }
          if (this.grid[x][y] == null) {
            $element.html(" ");
          } else {
            $element.html(this.grid[x][y]);
            $element.addClass('default-value');
          }
        }
      }
    },

    drawBlock: function( x, y, num ) {
      $('#block-' + x + '-' + y).text(num);
    },

    checkForDuplicates: function( list ) {
      var temporaryList = [];
      for (var i = 0; i < list.length; i += 1) {
        if (temporaryList.indexOf(list[i]) === -1 || list[i] === null) { // does our temp list already contain the item
          temporaryList.push(list[i]);
        } else {
          throw new DuplicateItemError("There is a duplicate in the list", i);
        }
      }
    },

    validate: function() {
      console.log('validating ..');
      var x, y;
      var columns = [[],[],[],[],[],[],[],[],[]];
      // Checking horizontal lines
      for (x = 0; x < this.grid.length; x += 1) {
        try {
          this.checkForDuplicates(this.grid[x]);
        } catch (e) {
          console.log(e);
          $('#block-' + x + '-' + e.item).css('background', 'red');
          return false;
        }

        // Store columns data
        columns[0].push(this.grid[x][0]);
        columns[1].push(this.grid[x][1]);
        columns[2].push(this.grid[x][2]);
        columns[3].push(this.grid[x][3]);
        columns[4].push(this.grid[x][4]);
        columns[5].push(this.grid[x][5]);
        columns[6].push(this.grid[x][6]);
        columns[7].push(this.grid[x][7]);
        columns[8].push(this.grid[x][8]);
      }

      // Checking vertical lines
      for (y = 0; y < columns.length; y += 1) {
        try {
          this.checkForDuplicates(columns[y]);
        } catch (e) {
          console.log(e);
          $('#block-' + e.item + '-' + y).css('background', 'red');
          return false;
        }
      }

      console.log('.. seems valid');
      return true;
    },

    diff: function( arr1, arr2 ) {
      return arr1.filter(function( arr1 ){
        return arr2.indexOf(arr1) == -1;
      })
    },

    checkHorizontalLinesForOneMissingNumber: function() {
      console.log('checking horizontal lines for one missing number ..');
      var empty, index, number;
      for (var i = 0; i < this.grid.length; i += 1) {
        empty = this.grid[i].filter(function( item ) {
          return item === null;
        });
        if (empty.length === 1) {
          index = this.grid[i].indexOf(null);
          number = this.diff(this.ARRAY, this.grid[i]);
          this.grid[i][index] = number[0];
          console.info('solved one number ..');
          this.drawBlock(i, index, number[0]);
          return true;
        }
      }
      return false;
    },

    checkVerticalLinesForOneMissingNumber: function() {
      console.log('checking vertical lines for one missing number ..');
      var x, columns = [[],[],[],[],[],[],[],[],[]];
      for (x = 0; x < this.grid.length; x += 1) {
        // Store columns data
        columns[0].push(this.grid[x][0]);
        columns[1].push(this.grid[x][1]);
        columns[2].push(this.grid[x][2]);
        columns[3].push(this.grid[x][3]);
        columns[4].push(this.grid[x][4]);
        columns[5].push(this.grid[x][5]);
        columns[6].push(this.grid[x][6]);
        columns[7].push(this.grid[x][7]);
        columns[8].push(this.grid[x][8]);
      }
      var empty, index, number;
      for (var i = 0; i < columns.length; i += 1) {
        empty = columns[i].filter(function( item ) {
          return item === null;
        });
        if (empty.length === 1) {
          index = columns[i].indexOf(null);
          number = this.diff(this.ARRAY, columns[i]);
          this.grid[index][i] = number[0];
          console.info('solved one number ..');
          this.drawBlock(index, i, number[0]);
          return true;
        }
      }
      return false;
    },

    checkBlock: function( i, Y, X ) {
      var y, x, block = [];
      block[i] = []; // Initialize block
      for (y = Y.start; y < Y.stop; y += 1) {
        block[i][y] = [];
        for (x = X.start; x < X.stop; x += 1) {
          block[i][y][x] = this.grid[y][x];
        }
      }
      console.log('BLOCK %i: %o', i, block[i]);
      return block[i];
    },

    checkBlocksForOneMissingNumber: function() {
      console.log('checking blocks for one missing number ..');
      var i, block, empty, full, number;
      // iterate over all blocks
      for (i = 0; i < 9; i += 1) {
        empty = []; // Reset empty array
        full = []; // Reset full array
        switch (i) {
          case 0: block = this.checkBlock(i, {start:0, stop:3}, {start:0, stop:3}); break;
          //case 1: block = this.checkBlock(i, {start:0, stop:3}, {start:3, stop:6}); break;
          //case 2: this.checkBlock(i, {start:0, stop:3}, {start:6, stop:9}); break;
          //case 3: this.checkBlock(i, {start:3, stop:6}, {start:0, stop:3}); break;
          //case 4: this.checkBlock(i, {start:3, stop:6}, {start:3, stop:6}); break;
          //case 5: this.checkBlock(i, {start:3, stop:6}, {start:6, stop:9}); break;
          //case 6: this.checkBlock(i, {start:6, stop:9}, {start:0, stop:3}); break;
          //case 7: this.checkBlock(i, {start:6, stop:9}, {start:3, stop:6}); break;
          //case 8: this.checkBlock(i, {start:6, stop:9}, {start:6, stop:9}); break;
        }

        if (i === 0) {
          for (var c = 0; c < block.length; c += 1) {
            full = full.concat(block[c]);
          }
          empty = full.filter(function( item ) {
            return item === null;
          });
          console.log("EMPTY HERE: ", empty);
          if (empty.length === 1) {
            // TODO: continue from here
            // index = ..
            number = this.diff(this.ARRAY, full);
            console.log('MISSING NUMBER IS: ', number[0]);
          }
        }
      }
      return false;
    },

    solve: function() {
      console.log('solving ..\n');
      var notStuck = true;
      while (notStuck) {
        notStuck = this.checkHorizontalLinesForOneMissingNumber();
        if (notStuck) continue;
        notStuck = this.checkVerticalLinesForOneMissingNumber();
        if (notStuck) continue;
        notStuck = this.checkBlocksForOneMissingNumber();
      }
      console.log('\nstuck ..');
    },

    prefill: function() {
      this.grid[0][0] = 8;
      this.grid[0][3] = 6;
      this.grid[0][5] = 3;
      this.grid[0][8] = 2;
      this.grid[1][1] = 6;
      this.grid[1][2] = 3;
      this.grid[1][3] = 2;
      this.grid[1][5] = 4;
      this.grid[1][6] = 9;
      this.grid[1][7] = 5;
      this.grid[2][4] = 5;
      this.grid[3][2] = 5;
      this.grid[3][6] = 7;
      this.grid[4][0] = 7;
      this.grid[4][1] = 8;
      this.grid[4][7] = 4;
      this.grid[4][8] = 3;
      this.grid[5][2] = 4;
      this.grid[5][6] = 2;
      this.grid[6][4] = 6;
      this.grid[7][1] = 2;
      this.grid[7][2] = 9;
      this.grid[7][3] = 1;
      this.grid[7][5] = 7;
      this.grid[7][6] = 5;
      this.grid[7][7] = 6;
      this.grid[8][0] = 5;
      this.grid[8][3] = 3;
      this.grid[8][5] = 9;
      this.grid[8][8] = 7;

      // .. Testing

      // Test if validation works
      //this.grid[0][7] = 8;
      //this.grid[3][5] = 5;
      //this.grid[6][0] = 8;

      // Test if checking horizontal lines for one missing number works
      //this.grid[1][0] = 1;
      //this.grid[1][4] = 8;
      //this.grid[7][0] = 4;
      //this.grid[7][4] = 3;

      // Test if checking vertical lines for one missing number works
      //this.grid[0][2] = 7;
      //this.grid[2][2] = 2;
      //this.grid[4][2] = 6;
      //this.grid[6][2] = 8;
      //this.grid[2][5] = 1;
      //this.grid[4][5] = 6;
      //this.grid[5][5] = 5;
      //this.grid[6][5] = 2;

      // Test if checking blocks for one missing number works
      this.grid[0][1] = 5;
      this.grid[0][2] = 7;
      //this.grid[1][0] = 1;
      this.grid[2][0] = 4;
      this.grid[2][1] = 9;
      this.grid[2][2] = 2;
    }
  };

  new Matrix(9, 9);

}());
<commit_msg>completed simple solution to solve blocks with one missing number<commit_after>(function(){

  function DuplicateItemError( errorMessage, listItem ) {
    return {msg:errorMessage, item:listItem};
  }

  function Matrix( x, y ) {
    this.ARRAY = [1,2,3,4,5,6,7,8,9];
    this.x = x;
    this.y = y;
    this.init();
    this.prefill();
    this.draw();
    this.validate();
    this.solve();
  }
  Matrix.prototype = {
    constructor: Matrix,

    init: function() {
      console.log('initialize here ..');
      this.grid = [];
      for (var i = 0; i < this.y; i += 1) {
        this.grid[i] = [];
        for (var y = 0; y < this.x; y += 1) {
          this.grid[i][y] = null;
        }
      }
      //console.log('GRID: %o', this.grid);
    },

    draw: function() {
      console.log('drawing..');
      var $element;
      var x, y;
      for (x = 0; x < this.grid.length; x += 1) {
        for (y = 0; y < this.grid[x].length; y += 1) {
          if (y == 8) {
            $element = $('

').appendTo('#main');
          } else {
            $element = $('

').appendTo('#main');
          }
          if (this.grid[x][y] == null) {
            $element.html(" ");
          } else {
            $element.html(this.grid[x][y]);
            $element.addClass('default-value');
          }
        }
      }
    },

    drawBlock: function( x, y, num ) {
      $('#block-' + x + '-' + y).text(num);
    },

    checkForDuplicates: function( list ) {
      var temporaryList = [];
      for (var i = 0; i < list.length; i += 1) {
        if (temporaryList.indexOf(list[i]) === -1 || list[i] === null) { // does our temp list already contain the item
          temporaryList.push(list[i]);
        } else {
          throw new DuplicateItemError("There is a duplicate in the list", i);
        }
      }
    },

    validate: function() {
      console.log('validating ..');
      var x, y;
      var columns = [[],[],[],[],[],[],[],[],[]];
      // Checking horizontal lines
      for (x = 0; x < this.grid.length; x += 1) {
        try {
          this.checkForDuplicates(this.grid[x]);
        } catch (e) {
          console.log(e);
          $('#block-' + x + '-' + e.item).css('background', 'red');
          return false;
        }

        // Store columns data
        columns[0].push(this.grid[x][0]);
        columns[1].push(this.grid[x][1]);
        columns[2].push(this.grid[x][2]);
        columns[3].push(this.grid[x][3]);
        columns[4].push(this.grid[x][4]);
        columns[5].push(this.grid[x][5]);
        columns[6].push(this.grid[x][6]);
        columns[7].push(this.grid[x][7]);
        columns[8].push(this.grid[x][8]);
      }

      // Checking vertical lines
      for (y = 0; y < columns.length; y += 1) {
        try {
          this.checkForDuplicates(columns[y]);
        } catch (e) {
          console.log(e);
          $('#block-' + e.item + '-' + y).css('background', 'red');
          return false;
        }
      }

      console.log('.. seems valid');
      return true;
    },

    diff: function( arr1, arr2 ) {
      return arr1.filter(function( arr1 ){
        return arr2.indexOf(arr1) == -1;
      })
    },

    checkHorizontalLinesForOneMissingNumber: function() {
      console.log('checking horizontal lines for one missing number ..');
      var empty, index, number;
      for (var i = 0; i < this.grid.length; i += 1) {
        empty = this.grid[i].filter(function( item ) {
          return item === null;
        });
        if (empty.length === 1) {
          index = this.grid[i].indexOf(null);
          number = this.diff(this.ARRAY, this.grid[i]);
          this.grid[i][index] = number[0];
          console.info('solved one number ..');
          this.drawBlock(i, index, number[0]);
          return true;
        }
      }
      return false;
    },

    checkVerticalLinesForOneMissingNumber: function() {
      console.log('checking vertical lines for one missing number ..');
      var x, columns = [[],[],[],[],[],[],[],[],[]];
      for (x = 0; x < this.grid.length; x += 1) {
        // Store columns data
        columns[0].push(this.grid[x][0]);
        columns[1].push(this.grid[x][1]);
        columns[2].push(this.grid[x][2]);
        columns[3].push(this.grid[x][3]);
        columns[4].push(this.grid[x][4]);
        columns[5].push(this.grid[x][5]);
        columns[6].push(this.grid[x][6]);
        columns[7].push(this.grid[x][7]);
        columns[8].push(this.grid[x][8]);
      }
      var empty, index, number;
      for (var i = 0; i < columns.length; i += 1) {
        empty = columns[i].filter(function( item ) {
          return item === null;
        });
        if (empty.length === 1) {
          index = columns[i].indexOf(null);
          number = this.diff(this.ARRAY, columns[i]);
          this.grid[index][i] = number[0];
          console.info('solved one number ..');
          this.drawBlock(index, i, number[0]);
          return true;
        }
      }
      return false;
    },

    checkBlock: function( i, Y, X ) {
      var y, x, block = [];
      block[i] = []; // Initialize block
      for (y = Y.start; y < Y.stop; y += 1) {
        block[i][y] = [];
        for (x = X.start; x < X.stop; x += 1) {
          block[i][y][x] = this.grid[y][x];
        }
      }
      //console.log('BLOCK %i: %o', i, block[i]);
      return block[i];
    },

    checkBlocksForOneMissingNumber: function() {
      console.log('checking blocks for one missing number ..');
      var i, c, block, empty, full, number, index, blah;
      // iterate over all blocks
      for (i = 0; i < 9; i += 1) {
        empty = []; // Reset empty array
        full = []; // Reset full array
        switch (i) {
          case 0: block = this.checkBlock(i, {start:0, stop:3}, {start:0, stop:3}); break;
          case 1: block = this.checkBlock(i, {start:0, stop:3}, {start:3, stop:6}); break;
          case 2: block = this.checkBlock(i, {start:0, stop:3}, {start:6, stop:9}); break;
          case 3: block = this.checkBlock(i, {start:3, stop:6}, {start:0, stop:3}); break;
          case 4: block = this.checkBlock(i, {start:3, stop:6}, {start:3, stop:6}); break;
          case 5: block = this.checkBlock(i, {start:3, stop:6}, {start:6, stop:9}); break;
          case 6: block = this.checkBlock(i, {start:6, stop:9}, {start:0, stop:3}); break;
          case 7: block = this.checkBlock(i, {start:6, stop:9}, {start:3, stop:6}); break;
          case 8: block = this.checkBlock(i, {start:6, stop:9}, {start:6, stop:9}); break;
        }

        if (i === 0 || i === 1 || i === 2) blah = 0;
        if (i === 3 || i === 4 || i === 5) blah = 3;
        if (i === 6 || i === 7 || i === 8) blah = 6;

        for (c = blah; c < block.length; c += 1) {
          full = full.concat(block[c]);
        }
        empty = full.filter(function( item ) {
          return item === null;
        });
        if (empty.length === 1) {
          number = this.diff(this.ARRAY, full);
          for (c = blah; c < block.length; c += 1) {
            index = block[c].indexOf(null);
            if (index !== -1) {
              this.grid[c][index] = number[0];
              this.drawBlock(c, index, number[0]);
              return true;
            }
          }
        }
      }
      return false;
    },

    solve: function() {
      console.log('solving ..\n');
      var notStuck = true;
      while (notStuck) {
        notStuck = this.checkHorizontalLinesForOneMissingNumber();
        if (notStuck) continue;
        notStuck = this.checkVerticalLinesForOneMissingNumber();
        if (notStuck) continue;
        notStuck = this.checkBlocksForOneMissingNumber();
      }
      console.log('\nstuck ..');
    },

    prefill: function() {
      this.grid[0][0] = 8;
      this.grid[0][3] = 6;
      this.grid[0][5] = 3;
      this.grid[0][8] = 2;
      this.grid[1][1] = 6;
      this.grid[1][2] = 3;
      this.grid[1][3] = 2;
      this.grid[1][5] = 4;
      this.grid[1][6] = 9;
      this.grid[1][7] = 5;
      this.grid[2][4] = 5;
      this.grid[3][2] = 5;
      this.grid[3][6] = 7;
      this.grid[4][0] = 7;
      this.grid[4][1] = 8;
      this.grid[4][7] = 4;
      this.grid[4][8] = 3;
      this.grid[5][2] = 4;
      this.grid[5][6] = 2;
      this.grid[6][4] = 6;
      this.grid[7][1] = 2;
      this.grid[7][2] = 9;
      this.grid[7][3] = 1;
      this.grid[7][5] = 7;
      this.grid[7][6] = 5;
      this.grid[7][7] = 6;
      this.grid[8][0] = 5;
      this.grid[8][3] = 3;
      this.grid[8][5] = 9;
      this.grid[8][8] = 7;

      // .. Testing

      // Test if validation works
      //this.grid[0][7] = 8;
      //this.grid[3][5] = 5;
      //this.grid[6][0] = 8;

      // Test if checking horizontal lines for one missing number works
      //this.grid[1][0] = 1;
      //this.grid[1][4] = 8;
      //this.grid[7][0] = 4;
      //this.grid[7][4] = 3;

      // Test if checking vertical lines for one missing number works
      //this.grid[0][2] = 7;
      //this.grid[2][2] = 2;
      //this.grid[4][2] = 6;
      //this.grid[6][2] = 8;
      //this.grid[2][5] = 1;
      //this.grid[4][5] = 6;
      //this.grid[5][5] = 5;
      //this.grid[6][5] = 2;

      // Test if checking blocks for one missing number works
      //this.grid[0][1] = 5;
      //this.grid[0][2] = 7;
      ////this.grid[1][0] = 1;
      //this.grid[2][0] = 4;
      //this.grid[2][1] = 9;
      //this.grid[2][2] = 2;

      //this.grid[2][5] = 1;

      //this.grid[0][6] = 4;
      ////this.grid[0][7] = 1;
      //this.grid[1][8] = 8;
      //this.grid[2][6] = 3;
      //this.grid[2][7] = 7;
      //this.grid[2][8] = 6;

      //this.grid[3][0] = 2;
      //this.grid[3][1] = 1;
      //this.grid[4][2] = 6;
      //this.grid[5][0] = 9;

      //this.grid[6][6] = 1;
      //this.grid[6][7] = 3;
      //this.grid[6][8] = 9;
      //this.grid[8][6] = 8;
      //this.grid[8][7] = 2;
    }
  };

  new Matrix(9, 9);

}());
<|endoftext|>


<commit_before>#!/usr/bin/env node
var fs = require('fs'),
  deja = require('./lib/deja')
  argv = require('optimist').argv

var home = process.env.HOME

// if HOME not set, die
if (home == undefined) {
  console.log('Error: HOME environmental variable not defined.')
  process.exit(1)
}

var dejaHome = home + '/.deja'

// make sure .deja exists in home directory
try {
  fs.mkdirSync(dejaHome, 0700)
} catch(e) {}

// deal with command line input
if (argv['_'].length < 1 || argv['_'].length > 2) {

  invalid_command()
}
else if(argv['_'].length == 2) {

  var command = argv['_'][0]
  var param   = argv['_'][1]

  switch(command) {

    case 'clone':
      deja.cloneRepo(home, dejaHome, param)
      break

    case 'pull':
      deja.pullRepo(dejaHome, param)
      break

    case 'diff':
      deja.diffRepo(home, dejaHome, param)
      break

    case 'rm':
      deja.rmRepo(dejaHome, param)
      break

    default:
      invalid_command()
  }
}
else {

  var command = argv['_'][0]

  switch(command) {

    case 'ls':
      deja.ls(dejaHome)
      break

    case 'help':
      console.log(deja.usage())
      break

    default:
      invalid_command()
  }
}

function invalid_command() {
  console.log('Unrecognized command.')

  console.log(deja.usage())
  process.exit(1)
}
<commit_msg>Added deletion of associated symlinks when repo is deleted.<commit_after>#!/usr/bin/env node
var fs = require('fs'),
  deja = require('./lib/deja')
  argv = require('optimist').argv

var home = process.env.HOME

// if HOME not set, die
if (home == undefined) {
  console.log('Error: HOME environmental variable not defined.')
  process.exit(1)
}

var dejaHome = home + '/.deja'

// make sure .deja exists in home directory
try {
  fs.mkdirSync(dejaHome, 0700)
} catch(e) {}

// deal with command line input
if (argv['_'].length < 1 || argv['_'].length > 2) {

  invalid_command()
}
else if(argv['_'].length == 2) {

  var command = argv['_'][0]
  var param   = argv['_'][1]

  switch(command) {

    case 'clone':
      deja.cloneRepo(home, dejaHome, param)
      break

    case 'pull':
      deja.pullRepo(dejaHome, param)
      break

    case 'diff':
      deja.diffRepo(home, dejaHome, param)
      break

    case 'rm':
      deja.rmRepo(home, dejaHome, param)
      break

    default:
      invalid_command()
  }
}
else {

  var command = argv['_'][0]

  switch(command) {

    case 'ls':
      deja.ls(dejaHome)
      break

    case 'help':
      console.log(deja.usage())
      break

    default:
      invalid_command()
  }
}

function invalid_command() {
  console.log('Unrecognized command.')

  console.log(deja.usage())
  process.exit(1)
}
<|endoftext|>


<commit_before>// Import React
import React from "react";

// Import Spectacle Core tags
import {
  Appear,
  // BlockQuote,
  // Cite,
  CodePane,
  Deck,
  Fill,
  Heading,
  Image,
  Layout,
  Link,
  ListItem,
  List,
  Markdown,
  // Quote,
  Slide,
  Spectacle,
  Text
  // Table,
  // TableRow,
  // TableHeaderItem,
  // TableItem
} from "spectacle";

// Import image preloader util
import preloader from "spectacle/lib/utils/preloader";

// Import theme
import createTheme from "spectacle/lib/themes/default";

import CodeSplit from "./codesplit";
import TwoPane from './TwoPane';
import Code from "./Code";
// Import Examples
import Example from './Example';
// Require CSS
import 'normalize.css';
import "spectacle/lib/themes/default/index.css";

const images = {
  coding: require("../assets/coding.jpg"),
  control: require("../assets/control.jpg"),
  website: require("../assets/website.jpg"),
};

preloader(images);

const theme = createTheme({
  primary: "#3b5998"
});
const grey = "rgba(125, 125, 125, 0.8)";
theme.screen.progress.bar.bar.background = grey;
theme.screen.controls.nextIcon.fill = grey;
theme.screen.controls.prevIcon.fill = grey;

export default class Presentation extends React.Component {
  render() {
    return (
      <Spectacle theme={theme}>
        <Deck transition={["fade", "slide"]} transitionDuration={500} progress="bar">

          <Slide bgColor="primary">
            <Heading size={1} caps textColor="tertiary">
              JSX
            </Heading>
            <Text textSize="1.5em" margin="100px 0px 0px 0px" textColor="tertiary">
              Fabian Beliza & Jonas Faber
            </Text>
          </Slide>

          <Slide bgColor="tertiary">
            <Heading size={4} caps lineHeight={1.5} textColor="primary">
            Inhalt
            </Heading>
            <List textColor="secondary" textAlign="left">
              <Appear><ListItem>Was ist JSX?</ListItem></Appear>
              <Appear><ListItem>Bezug zu XML</ListItem></Appear>
              <Appear><ListItem>Beispiele</ListItem></Appear>
            </List>
          </Slide>

          <Slide bgColor="tertiary" notes="Type-Safe, Errors werden während compilierung erkannt.">
            <Heading size={4} caps lineHeight={1.5} textColor="primary">
            Was ist JSX?
            </Heading>
            <List textColor="secondary" textAlign="left">
              <Appear><ListItem>XML-ähnliche Syntax-Erweiterung zu ECMAScript</ListItem></Appear>
              <Appear><ListItem>Wird von Preprozessoren transformiert</ListItem></Appear>
              <Appear><ListItem>Optimierungen während Kompilierung in JS</ListItem></Appear>
              <Appear><ListItem>Type-Safe</ListItem></Appear>
              <Appear><ListItem>Vereinfacht Templating (HTML-Syntax)</ListItem></Appear>
              <Appear><ListItem>Besonders im Zusammenhang mit React zu finden</ListItem></Appear>
            </List>
          </Slide>

          <Slide bgColor="tertiary">
            <Heading size={4} caps lineHeight={1.5} textColor="primary">
            Bezug zu XML
            </Heading>
            <List textColor="secondary" textAlign="left">
              <Appear><ListItem><Markdown source="`< JSXElementName JSXAttributes(optional) / >`" /></ListItem></Appear>
              <Appear><ListItem>Strukturierung mit child-Elementen</ListItem></Appear>
              <Appear><ListItem>Baumstruktur</ListItem></Appear>
            </List>
          </Slide>

          <Slide bgColor="tertiary">

          </Slide>

          <Slide bgColor="tertiary">
            <Heading size={4} caps lineHeight={1.5} textColor="primary">
              Andere XML-Ähnliche Sprachergänzungen
            </Heading>
            <Appear>
              <List textColor="secondary" textAlign="left">
                <ListItem><Link href="https://github.com/insin/msx">MSL (JSX for Mithrill)</Link></ListItem>
                <ListItem><Link href="https://github.com/pzavolinsky/elmx">elmx (JSX for Elm)</Link></ListItem>
                <ListItem><Link href="https://github.com/treycordova/nativejsx">nativejsx (JSX without React)</Link></ListItem>
              </List>
            </Appear>
          </Slide>
        </Deck>
      </Spectacle>
    );
  }
}
<commit_msg>Add React Native<commit_after>// Import React
import React from "react";

// Import Spectacle Core tags
import {
  Appear,
  // BlockQuote,
  // Cite,
  CodePane,
  Deck,
  Fill,
  Heading,
  Image,
  Layout,
  Link,
  ListItem,
  List,
  Markdown,
  // Quote,
  Slide,
  Spectacle,
  Text
  // Table,
  // TableRow,
  // TableHeaderItem,
  // TableItem
} from "spectacle";

// Import image preloader util
import preloader from "spectacle/lib/utils/preloader";

// Import theme
import createTheme from "spectacle/lib/themes/default";

import CodeSplit from "./codesplit";
import TwoPane from './TwoPane';
import Code from "./Code";
// Import Examples
import Example from './Example';
// Require CSS
import 'normalize.css';
import "spectacle/lib/themes/default/index.css";

const images = {
  coding: require("../assets/coding.jpg"),
  control: require("../assets/control.jpg"),
  website: require("../assets/website.jpg"),
};

preloader(images);

const theme = createTheme({
  primary: "#3b5998"
});
const grey = "rgba(125, 125, 125, 0.8)";
theme.screen.progress.bar.bar.background = grey;
theme.screen.controls.nextIcon.fill = grey;
theme.screen.controls.prevIcon.fill = grey;

export default class Presentation extends React.Component {
  render() {
    return (
      <Spectacle theme={theme}>
        <Deck transition={["fade", "slide"]} transitionDuration={500} progress="bar">

          <Slide bgColor="primary">
            <Heading size={1} caps textColor="tertiary">
              JSX
            </Heading>
            <Text textSize="1.5em" margin="100px 0px 0px 0px" textColor="tertiary">
              Fabian Beliza & Jonas Faber
            </Text>
          </Slide>

          <Slide bgColor="tertiary">
            <Heading size={4} caps lineHeight={1.5} textColor="primary">
            Inhalt
            </Heading>
            <List textColor="secondary" textAlign="left">
              <Appear><ListItem>Was ist JSX?</ListItem></Appear>
              <Appear><ListItem>Bezug zu XML</ListItem></Appear>
              <Appear><ListItem>Beispiele</ListItem></Appear>
            </List>
          </Slide>

          <Slide bgColor="tertiary" notes="Type-Safe, Errors werden während compilierung erkannt.">
            <Heading size={4} caps lineHeight={1.5} textColor="primary">
            Was ist JSX?
            </Heading>
            <List textColor="secondary" textAlign="left">
              <Appear><ListItem>XML-ähnliche Syntax-Erweiterung zu ECMAScript</ListItem></Appear>
              <Appear><ListItem>Wird von Preprozessoren transformiert</ListItem></Appear>
              <Appear><ListItem>Optimierungen während Kompilierung in JS</ListItem></Appear>
              <Appear><ListItem>Type-Safe</ListItem></Appear>
              <Appear><ListItem>Vereinfacht Templating (HTML-Syntax)</ListItem></Appear>
              <Appear><ListItem>Besonders im Zusammenhang mit React zu finden</ListItem></Appear>
              <Appear><ListItem>Auch React Native nutzt JSX</ListItem></Appear>
            </List>
          </Slide>

          <Slide bgColor="tertiary">
            <Heading size={4} caps lineHeight={1.5} textColor="primary">
            Bezug zu XML
            </Heading>
            <List textColor="secondary" textAlign="left">
              <Appear><ListItem><Markdown source="`< JSXElementName JSXAttributes(optional) / >`" /></ListItem></Appear>
              <Appear><ListItem>Strukturierung mit child-Elementen</ListItem></Appear>
              <Appear><ListItem>Baumstruktur</ListItem></Appear>
            </List>
          </Slide>

          <Slide bgColor="tertiary">

          </Slide>

          <Slide bgColor="tertiary">
            <Heading size={4} caps lineHeight={1.5} textColor="primary">
              Andere XML-Ähnliche Sprachergänzungen
            </Heading>
            <Appear>
              <List textColor="secondary" textAlign="left">
                <ListItem><Link href="https://github.com/insin/msx">MSL (JSX for Mithrill)</Link></ListItem>
                <ListItem><Link href="https://github.com/pzavolinsky/elmx">elmx (JSX for Elm)</Link></ListItem>
                <ListItem><Link href="https://github.com/treycordova/nativejsx">nativejsx (JSX without React)</Link></ListItem>
              </List>
            </Appear>
          </Slide>
        </Deck>
      </Spectacle>
    );
  }
}
<|endoftext|>


<commit_before>const { DEFAULT_COLUMN_WIDTH } = require('../constants')
const { ensureG, T, F, isNull, Y } = require('./utils')

const booleanChart = (g, data, config = {}) => {
  const top   = config.top   || 0
  const left  = config.left  || 0
  const width = config.width || DEFAULT_COLUMN_WIDTH
  const keys  = [false, true]
  const className = config.className
  const barWidth = width / keys.length

  const X = d => d === null ? 0 : keys.indexOf(d) * barWidth
  const W = d => d === null ? width : barWidth - 1
  const T = d => d === true
  const F = d => d === false

  const myG = ensureG(g, className, left, top)

  const update = myG.selectAll('rect')
    .data(data, (d, i) => i)

  const enter = update.enter()
  enter
    .append('rect') // TODO: could do as well with a line.  cheaper?
    .classed('stripe', true)
    .classed('null', isNull)
    .classed('boolean-true', T)
    .classed('boolean-false', F)
    .style('y', Y)
    .style('x', X)
    .style('width', W)

  update
    .classed('null', isNull)
    .classed('boolean-true', T)
    .classed('boolean-false', F)
    .style('y', Y)
    .style('x', X)
    .style('width', W)
}

module.exports = {
  booleanChart
}
<commit_msg>code cleanup<commit_after>const { DEFAULT_COLUMN_WIDTH } = require('../constants')
const { ensureG, isNull, Y } = require('./utils')

const booleanChart = (g, data, config = {}) => {
  const top   = config.top   || 0
  const left  = config.left  || 0
  const width = config.width || DEFAULT_COLUMN_WIDTH
  const keys  = [false, true]
  const className = config.className
  const barWidth = width / keys.length

  const X = d => d === null ? 0 : keys.indexOf(d) * barWidth
  const W = d => d === null ? width : barWidth - 1
  const T = d => d === true
  const F = d => d === false

  const myG = ensureG(g, className, left, top)

  const update = myG.selectAll('rect')
    .data(data, (d, i) => i)

  const enter = update.enter()
  enter
    .append('rect') // TODO: could do as well with a line.  cheaper?
    .classed('stripe', true)
    .classed('null', isNull)
    .classed('boolean-true', T)
    .classed('boolean-false', F)
    .style('y', Y)
    .style('x', X)
    .style('width', W)

  update
    .classed('null', isNull)
    .classed('boolean-true', T)
    .classed('boolean-false', F)
    .style('y', Y)
    .style('x', X)
    .style('width', W)
}

module.exports = {
  booleanChart
}
<|endoftext|>


<commit_before>'use strict';

var Tricanvas = require('./');

var toTritmap9x14 = require('trit-text').toTritmap9x14;
var fromUnicode = require('trit-text').fromUnicode;
var fromEvent = require('trit-text').fromEvent;

window.t = Tricanvas();
console.log(t);

/*
for (var i = 0; i < 81*81*5; ++i)
  t.tritmap[i] = (Math.random()*241-121)|0;
  //t.tritmap[i] = 80; // 1000i
*/

/*
for (var i = 0; i < 100; ++i)
  t.writeTrit(-1, i, i);
  */

t.writeTrits(toTritmap9x14(-75), 9, 14, 0, 0);
t.writeTrits(toTritmap9x14(fromUnicode('☺')), 9, 14, 0, 1);
t.writeTrits(toTritmap9x14(-fromUnicode('X')), 9, 14, 0, 2);
t.writeTrits(toTritmap9x14(-fromUnicode('T')), 9, 14, 1, 0);
//t.writeTrits('i1i1i1i1i1i1i1i1iii1i1i1i1i1i1i1i1iii1i1i1i1i1i1i1i1iii1i1i1i1i1i1i1i1iii1i1i1i1i1i1i1i1iii1i1i1i1i1i1i1i1iii1i1i1i1i1i1i1i1ii',9);
//t.writeTrits('i0i0i0i0i0i0i0i0iii0i0i0i0i0i0i0i0iii0i0i0i0i0i0i0i0iii0i0i0i0i0i0i0i0iii0i0i0i0i0i0i0i0iii0i0i0i0i0i0i0i0iii0i0i0i0i0i0i0i0ii',9);
//t.writeTrits('i1i1i1i1i',9);
//t.writeTrits('1',9);
//t.writeTrits('iii',9,14);

var cursorX = 0, cursorY = 0;
window.addEventListener('keydown', function(ev) {
  console.log(ev);
  ev.preventDefault(); // allow intercepting ctrl-key without executing browser default

  var tt = fromEvent(ev);
  if (tt === null) {
    tt = 75;
  }

  console.log(cursorX,cursorY);
  t.writeTrits(toTritmap9x14(tt), 9, 14, cursorY, cursorX);
  t.refresh();

  ++cursorX;

  if (tt == 12) { // trit-text newline
    cursorY++;
    cursorX = 0;
  }

  if (cursorX >= t.width/9) {
    cursorX = 0;
    ++cursorY;
  }
  if (cursorY >= t.width/14) {
    cursorY = 0;
    cursorX = 0;
  }
});

  global.t = t;

t.refresh();
<commit_msg>Don't capture cmd-keys, interferes with browser operation<commit_after>'use strict';

var Tricanvas = require('./');

var toTritmap9x14 = require('trit-text').toTritmap9x14;
var fromUnicode = require('trit-text').fromUnicode;
var fromEvent = require('trit-text').fromEvent;

window.t = Tricanvas();
console.log(t);

/*
for (var i = 0; i < 81*81*5; ++i)
  t.tritmap[i] = (Math.random()*241-121)|0;
  //t.tritmap[i] = 80; // 1000i
*/

/*
for (var i = 0; i < 100; ++i)
  t.writeTrit(-1, i, i);
  */

t.writeTrits(toTritmap9x14(-75), 9, 14, 0, 0);
t.writeTrits(toTritmap9x14(fromUnicode('☺')), 9, 14, 0, 1);
t.writeTrits(toTritmap9x14(-fromUnicode('X')), 9, 14, 0, 2);
t.writeTrits(toTritmap9x14(-fromUnicode('T')), 9, 14, 1, 0);
//t.writeTrits('i1i1i1i1i1i1i1i1iii1i1i1i1i1i1i1i1iii1i1i1i1i1i1i1i1iii1i1i1i1i1i1i1i1iii1i1i1i1i1i1i1i1iii1i1i1i1i1i1i1i1iii1i1i1i1i1i1i1i1ii',9);
//t.writeTrits('i0i0i0i0i0i0i0i0iii0i0i0i0i0i0i0i0iii0i0i0i0i0i0i0i0iii0i0i0i0i0i0i0i0iii0i0i0i0i0i0i0i0iii0i0i0i0i0i0i0i0iii0i0i0i0i0i0i0i0ii',9);
//t.writeTrits('i1i1i1i1i',9);
//t.writeTrits('1',9);
//t.writeTrits('iii',9,14);

var cursorX = 0, cursorY = 0;
window.addEventListener('keydown', function(ev) {
  console.log(ev);

  if (ev.metaKey) {
    // don't intercept cmd-key, allow e.g. cmd-r to reload browser
    return;
  }

  ev.preventDefault(); // allow intercepting ctrl-key without executing browser default

  var tt = fromEvent(ev);
  if (tt === null) {
    tt = 75;
  }

  console.log(cursorX,cursorY);
  t.writeTrits(toTritmap9x14(tt), 9, 14, cursorY, cursorX);
  t.refresh();

  ++cursorX;

  if (tt == 12) { // trit-text newline
    cursorY++;
    cursorX = 0;
  }

  if (cursorX >= t.width/9) {
    cursorX = 0;
    ++cursorY;
  }
  if (cursorY >= t.width/14) {
    cursorY = 0;
    cursorX = 0;
  }
});

  global.t = t;

t.refresh();
<|endoftext|>


<commit_before>'use strict';

var expect = require('chai').expect;

describe('Treemap', function() {
  it('renders treemap', function() {
    var React = require('react/addons');
    var Treemap = require('../src/treemap').Treemap;
    var generate = require('../utils/datagen').generateArrayOfNumbers;
    var TestUtils = React.addons.TestUtils;

    // Render a treemap using array data
    var data = generate(5);
    var width = 500, height = 250;

    var treemap = TestUtils.renderIntoDocument(
      <Treemap data={data} width={width} height={height} />
    );

    // Verify that it has rendered the main chart svg
    var svg = TestUtils.findRenderedDOMComponentWithTag(treemap, 'svg');
    expect(svg).to.exist;

    // Verify that it has the same number of nodes as the array's length
    var cells = TestUtils.scryRenderedDOMComponentsWithTag(treemap, 'rect');

    // Note that the first node generated will always be the parent node
    expect(Number(cells[0].getDOMNode().getAttribute('width'))).to.equal(width);

    // Magic number '1' is the parent node
    expect(cells.length).to.equal(data.length + 1);

    var labels = TestUtils.scryRenderedDOMComponentsWithTag(
      treemap, 'text');

    expect(labels[0].getDOMNode().textContent).to.be.empty;
    expect(labels.length).to.equal(data.length + 1);

  });
});
<commit_msg>Use className for testing in treemap-tests.js<commit_after>'use strict';

var expect = require('chai').expect;

describe('Treemap', function() {
  it('renders treemap', function() {
    var React = require('react/addons');
    var Treemap = require('../src/treemap').Treemap;
    var generate = require('../utils/datagen').generateArrayOfNumbers;
    var TestUtils = React.addons.TestUtils;
    var points = 5;

    // Render a treemap using array data
    var data = generate(points);
    var width = 500, height = 250;

    var treemap = TestUtils.renderIntoDocument(
      <Treemap data={data} width={width} height={height} />
    );

    var treemapGroup = TestUtils.findRenderedDOMComponentWithClass(treemap, 'rd3-treemap');
    expect(treemapGroup).to.exist;
    expect(treemapGroup.tagName).to.equal('G');

    // Verify that it has the same number of nodes as the array's length
    var cells = TestUtils.scryRenderedDOMComponentsWithClass(treemap, 'rd3-treemap-rect');

    // Note that the first node generated will always be the parent node
    expect(Number(cells[0].getDOMNode().getAttribute('width'))).to.equal(width);

    // Magic number '1' is the parent node
    expect(cells.length).to.equal(data.length + 1);

    var labels = TestUtils.scryRenderedDOMComponentsWithClass(
      treemap, 'rd3-treemap-text');

    expect(labels[0].getDOMNode().textContent).to.be.empty;
    expect(labels.length).to.equal(data.length + 1);

  });
});
<|endoftext|>