<commit_before>import assert from 'assert';

import {
  validateRange,
  validateWidths,
  validateWidthTolerance,
  validateVariableQuality
} from '../src/validators';

describe('Validators:', function () {
  describe('Testing validateWidths', function () {
    it('throws an error if any width is negative', () => {
      assert.throws(() => {
        validateWidths([100, 200, 300, -400])
      })
    });

    it('throws an error if given an empty list', () => {
      assert.throws(() => {
        validateWidths([])
      })
    });

    it('throws an error if given a list of non-numeric input', () => {
      assert.throws(() => {
        validateWidths([100, 200, 300, '400', '500'])
      })
    });

    it('throws an error if given a list of non-integer input', () => {
      assert.throws(() => {
        validateWidths([399.99, 499.50])
      })
    });

    it('succeeds silently', () => {
      let result = validateWidths([100, 200, 300, 400, 500]);
      assert.strictEqual(result, undefined);
    });
  });

  describe('Testing validateRange', function () {
    it('throws an error if minWidth is not an integer', () => {
      assert.throws(() => {
        validateRange(500.9123, 1000)
      })
    });

    it('throws an error if maxWidth is not an integer', () => {
      assert.throws(() => {
        validateRange(100, 500.9123)
      })
    });

    it('throws an error if minWidth is less than 0', () => {
      assert.throws(() => {
        validateRange(-1, 100)
      })
    });

    it('throws an error if maxWidth is less than 0', () => {
      assert.throws(() => {
        validateRange(100, -1)
      })
    });

    it('throws an error if maxWidth is less than minWidth', () => {
      assert.throws(() => {
        validateRange(500, 100)
      })
    });

    it('succeeds silently', () => {
      let result = validateRange(100, 8192);
      assert.strictEqual(result, undefined);
    });
  });

  describe('Testing validateWidthTolerance', function () {
    it('throws if typeof widthTolerance is not a number', () => {
      assert.throws(() => {
        validateWidthTolerance('0.08')
      })
    });

    it('throws if widthTolerance is <= 0', () => {
      assert.throws(() => {
        validateWidthTolerance(0)
      })
    });

    it('succeeds silently', () => {
      let result = validateWidthTolerance(0.08);
      assert.strictEqual(result, undefined);
    });

    // TODO: should fail.
    it('succeeds silently when widthTolerance === 0.001', () => {
      let result = validateWidthTolerance(0.001);
      assert.strictEqual(result, undefined);
    });
  });

  describe('Testing validateVariableQuality', function () {
    it('throws an error if variable quality flag is not a boolean', () => {
      assert.throws(() => {
        validateVariableQuality('false')
      })

      assert.throws(() => {
        validateVariableQuality('true')
      })

      assert.throws(() => {
        validateVariableQuality(0)
      })

      assert.throws(() => {
        validateVariableQuality(1)
      })
    });
  });
});<commit_msg>test: strengthen pharsing of descriptions<commit_after>import assert from 'assert';

import {
  validateRange,
  validateWidths,
  validateWidthTolerance,
  validateVariableQuality
} from '../src/validators';

describe('Validators:', function () {
  describe('Testing validateWidths', function () {
    it('throws if a width in width list is negative', () => {
      assert.throws(() => { validateWidths([100, 200, 300, -400]) })
    });

    it('throws if given an empty list', () => {
      assert.throws(() => { validateWidths([]) })
    });

    it('throws if given a list of non-numeric input', () => {
      assert.throws(() => { validateWidths([100, 200, 300, '400', '500']) })
    });

    it('throws if given a list of non-integer input', () => {
      assert.throws(() => { validateWidths([399.99, 499.50]) })
    });

    it('does not throw given valid width list', () => {
      assert.doesNotThrow(() => { validateWidths([100, 200, 300, 400, 500]) })
    });
  });

  describe('Testing validateRange', function () {
    it('throws an error if minWidth is not an integer', () => {
      assert.throws(() => { validateRange(500.9123, 1000) })
    });

    it('throws if maxWidth is not an integer', () => {
      assert.throws(() => { validateRange(100, 500.9123) })
    });

    it('throws if minWidth is less than 0', () => {
      assert.throws(() => { validateRange(-1, 100) })
    });

    it('throws if maxWidth is less than 0', () => {
      assert.throws(() => { validateRange(100, -1) })
    });

    it('throws if maxWidth is less than minWidth', () => {
      assert.throws(() => { validateRange(500, 100) })
    });

    it('does not throw given a valid range', () => {
      assert.doesNotThrow(() => { validateRange(100, 8192) })
    });
  });

  describe('Testing validateWidthTolerance', function () {
    it('throws if typeof widthTolerance is not a number', () => {
      assert.throws(() => {
        validateWidthTolerance('0.08')
      })
    });

    it('throws if widthTolerance is <= 0', () => {
      assert.throws(() => { validateWidthTolerance(0) })
    });

    it('does not throw on valid widthTolerance', () => {
      assert.doesNotThrow(() => { validateWidthTolerance(0.08) })
    });

    // TODO: should fail.
    it('widthTolerance === 0.001', () => {
    });
  });

  describe('Testing validateVariableQuality', function () {
    it('throws an error if variable quality flag is not a boolean', () => {
      assert.throws(() => {
        validateVariableQuality('false')
      })

      assert.throws(() => {
        validateVariableQuality('true')
      })

      assert.throws(() => {
        validateVariableQuality(0)
      })

      assert.throws(() => {
        validateVariableQuality(1)
      })
    });
  });
});<|endoftext|>


<commit_before>/* 控制导航按钮动作 */
function nav_click(is_show) {
  if (is_show) {
    /* 显示左侧aside */
    $('.aside')
      .addClass('visible-md visible-lg')
      .removeClass('hidden-md hidden-lg')
    /* 调整右侧内容 */
    $('.aside3')
      .removeClass('col-md-12 col-lg-12')
      .addClass('col-md-8 col-lg-8');
    /* 调整文字内容格式 */
    $('.aside3-content')
      .removeClass('col-md-10 col-lg-10 col-md-offset-1 col-lg-offset-1')
      .addClass('col-md-12');
    /* 变化按钮 */
    $('#nav_btn i')
      .removeClass('fa-angle-right')
      .addClass('fa-angle-left');
  } else {
    /* 隐藏左侧aside */
    $('.aside')
      .removeClass('visible-md visible-lg')
      .addClass('hidden-md hidden-lg');
    /* 右侧内容最大化 */
    $('.aside3')
      .removeClass('col-md-8 col-lg-8')
      .addClass('col-md-12 col-lg-12');
    /* 修改文字排版 */
    $('.aside3-content')
      .removeClass('col-md-12')
      .addClass('col-md-10 col-lg-10 col-md-offset-1 col-lg-offset-1');
    /* 变化按钮图标 */
    $('#nav_btn i').removeClass('fa-angle-left').addClass('fa-angle-right');
  }
}
/* 控制文章章节列表按钮 */
function content_click(is_show){
  if (is_show) {
    $('#content_table').show();
    $('#content_btn i').removeClass('fa-angle-down').addClass('fa-angle-up');
  } else {
    $('#content_table').hide();
    $('#content_btn i').removeClass('fa-angle-up').addClass('fa-angle-down');
  }
}

$(document).ready(function() {
  /* 控制左侧 aside 的动作 */
  $("#nav_btn").on('click', function() {
    isClicked = $(this).data('clicked');

    nav_click(isClicked);

    $(this).data('clicked', !isClicked);
  });

  $("#content_btn").on('click', function(){
    isClicked = $(this).data('clicked');

    content_click(!isClicked);

    $(this).data('clicked',!isClicked);

  });

  $(document).pjax('.pjaxlink', '#pjax', { fragment: "#pjax", timeout: 10000 });
  $(document).on("pjax:end", function() {
    if($("body").find('.container').width() < 992)
      $('#nav_btn').click();
    $('.aside3').scrollTop(0);
    contentEffects();
  });
  $('body').on('click', '.show-commend', function(){
    var ds_loaded = false;
    window.disqus_shortname = $('.show-commend').attr('name');
    $.ajax({
      type: "GET",
      url: "http://" + disqus_shortname + ".disqus.com/embed.js",
      dataType: "script",
      cache: true
    });
  });
  contentEffects();
});

function addDS(){
	$.ajax({
      type: "GET",
      url: (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js',
      dataType: "script",
      cache: true
    });
	window.DUOSHUO.init();
}

function addDuoShuo(){

	if(document.getElementById('duosjs')) {
		window.DUOSHUO.init();
		return;
	}

	var ds = document.createElement('script');
	ds.type = 'text/javascript';ds.async = true;
	ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
	ds.charset = 'UTF-8';
	ds.id = 'duosjs';
	(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ds);
}

function contentEffects(){
  //remove the asidebar
  $('.row-offcanvas').removeClass('active');
  if($("#nav").length > 0 && document.getElementById("nav").innerHTML!='' ){
    $("#content > h2,#content > h3,#content > h4,#content > h5,#content > h6").each(function(i) {
        var current = $(this);
        current.attr("id", "title" + i);
        tag = current.prop('tagName').substr(-1);
        $("#nav").append("
" + current.html() + "
");
    });
    $("pre").addClass("prettyprint");
    prettyPrint();
    $('#content img').addClass('img-thumbnail').parent('p').addClass('center');
    $('#content_btn').show();
  }else{
    $('#content_btn').hide();
  }

  addDuoShuo();
}<commit_msg>update<commit_after>/* 控制导航按钮动作 */
function nav_click(is_show) {
  if (is_show) {
    /* 显示左侧aside */
    $('.aside')
      .addClass('visible-md visible-lg')
      .removeClass('hidden-md hidden-lg')
    /* 调整右侧内容 */
    $('.aside3')
      .removeClass('col-md-12 col-lg-12')
      .addClass('col-md-8 col-lg-8');
    /* 调整文字内容格式 */
    $('.aside3-content')
      .removeClass('col-md-10 col-lg-10 col-md-offset-1 col-lg-offset-1')
      .addClass('col-md-12');
    /* 变化按钮 */
    $('#nav_btn i')
      .removeClass('fa-angle-right')
      .addClass('fa-angle-left');
  } else {
    /* 隐藏左侧aside */
    $('.aside')
      .removeClass('visible-md visible-lg')
      .addClass('hidden-md hidden-lg');
    /* 右侧内容最大化 */
    $('.aside3')
      .removeClass('col-md-8 col-lg-8')
      .addClass('col-md-12 col-lg-12');
    /* 修改文字排版 */
    $('.aside3-content')
      .removeClass('col-md-12')
      .addClass('col-md-10 col-lg-10 col-md-offset-1 col-lg-offset-1');
    /* 变化按钮图标 */
    $('#nav_btn i').removeClass('fa-angle-left').addClass('fa-angle-right');
  }
}
/* 控制文章章节列表按钮 */
function content_click(is_show){
  if (is_show) {
    $('#content_table').show();
    $('#content_btn i').removeClass('fa-angle-down').addClass('fa-angle-up');
  } else {
    $('#content_table').hide();
    $('#content_btn i').removeClass('fa-angle-up').addClass('fa-angle-down');
  }
}

$(document).ready(function() {
  /* 控制左侧 aside 的动作 */
  $("#nav_btn").on('click', function() {
    isClicked = $(this).data('clicked');

    nav_click(isClicked);

    $(this).data('clicked', !isClicked);
  });

  $("#content_btn").on('click', function(){
    isClicked = $(this).data('clicked');

    content_click(!isClicked);

    $(this).data('clicked',!isClicked);

  });

  $(document).pjax('.pjaxlink', '#pjax', { fragment: "#pjax", timeout: 10000 });
  $(document).on("pjax:end", function() {
    if($("body").find('.container').width() < 992)
      $('#nav_btn').click();
    $('.aside3').scrollTop(0);
    contentEffects();
  });
  $('body').on('click', '.show-commend', function(){
    var ds_loaded = false;
    window.disqus_shortname = $('.show-commend').attr('name');
    $.ajax({
      type: "GET",
      url: "http://" + disqus_shortname + ".disqus.com/embed.js",
      dataType: "script",
      cache: true
    });
  });
  contentEffects();
});

function addDuoShuo(){
	if(document.getElementById('duosjs')) {
		window.DUOSHUO.init();
		return;
	}
	var ds = document.createElement('script');
	ds.type = 'text/javascript';ds.async = true;
	ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
	ds.charset = 'UTF-8';
	ds.id = 'duosjs';
	(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ds);
}

function contentEffects(){
  //remove the asidebar
  $('.row-offcanvas').removeClass('active');
  if($("#nav").length > 0 && document.getElementById("nav").innerHTML!='' ){
    $("#content > h2,#content > h3,#content > h4,#content > h5,#content > h6").each(function(i) {
        var current = $(this);
        current.attr("id", "title" + i);
        tag = current.prop('tagName').substr(-1);
        $("#nav").append("
" + current.html() + "
");
    });
    $("pre").addClass("prettyprint");
    prettyPrint();
    $('#content img').addClass('img-thumbnail').parent('p').addClass('center');
    $('#content_btn').show();
  }else{
    $('#content_btn').hide();
  }

  addDuoShuo();
}<|endoftext|>


<commit_before>'use strict';

var IsoForm = require('../lib/iso-form'),
    isoFormTestDom = require('./processors/test-dom'),
    should = require('chai').should();

describe('IsoForm processors', function () {
    it('should accept processor and bootstrap types', function () {
        var isoForm = new IsoForm(isoFormTestDom);
        var checkboxItem = isoForm._registry.get('checkbox');
        checkboxItem.should.have.property('template');
    });
});
<commit_msg>Trigger travis<commit_after>'use strict';

var IsoForm = require('../lib/iso-form'),
    isoFormTestDom = require('./processors/test-dom'),
    should = require('chai').should();

describe('IsoForm processors', function () {
    it('should accept processor and bootstrap types', function () {
        var isoForm = new IsoForm(isoFormTestDom);
        var checkboxItem = isoForm._registry.get('checkbox');
        checkboxItem.should.have.property('template');
    });
});
<|endoftext|>


<commit_before>
/* call functions on all clients using eurecaServer.distribute*/

function sendAllReady() {
  eurecaServer.distribute("setAllReady",null);
}

function sendPlatform() {
  //sounds.ping.note();
  eurecaServer.distribute("setPlatform", {
    x: cursorX,
    y: cursorY
  })
}

function updateMan1(args) {
  if (playerRole != "astronaut1") {
    player.x = args.x
    player.y = args.y
    var xVelocity = args.vel
    if(xVelocity < 0){
      player.animations.play('left');
    } else if(xVelocity > 0) {
      player.animations.play('right');
    } else {player.frame = 8}
    if (args.newsound) {
      switch(args.newsound) {
        case "turn":
            sounds.dude.turn();
          break;
        case "jump":
            sounds.dude.jump();
          break;
        case "land":
            sounds.dude.land();
          break;
      }
    }
  }
}
function updateMan2(args) {
  if (playerRole != "astronaut2") {
    player2.x = args.x
    player2.y = args.y
    var xVelocity = args.vel
    if(xVelocity < 0){
      player2.animations.play('left');
    } else if(xVelocity > 0) {
      player2.animations.play('right');
    } else {player2.frame = 8}
    if (args.newsound) {
      switch(args.newsound) {
        case "turn":
            sounds.dude.turn();
          break;
        case "jump":
            sounds.dude.jump();
          break;
        case "land":
            sounds.dude.land();
          break;
      }
    }
  }
}

function setProp(args) {
  window[args.prop] = args.val
}

var p1touchdown = true;
var p2touchdown = true;

// player1

function movePlayer1() {
  player.newsound = false;
  if (cursors.left.isDown || leftButtonDown) {
      if (!player.turningLeft) {
        sounds.dude.turn()
        player.newsound = "turn";
        player.turningLeft = true;
        player.turningRight = false;
      }
      player.body.velocity.x = -150
      player.animations.play("left");
    } else if (cursors.right.isDown || rightButtonDown) {
      if (!player.turningRight) {
        sounds.dude.turn()
        player.newsound = "turn";
        player.turningRight = true;
        player.turningLeft = false;
      }
      sounds.dude.turn()
      player.newsound = "turn";
      player.body.velocity.x = 150;
      player.animations.play('right');
    } else {
      if (player.body.velocity.x > 0) {
        player.body.velocity.x -= 5;
        player.animations.play('left');
      } else if (player.body.velocity.x < 0) {
        player.body.velocity.x += 5;
        player.animations.play('right');
      } else if (player.body.velocity.x === 0) {
        player.frame = 8;
      }
    }

    if (player.body.touching.down && player.body.touching.down != p1touchdown) {
      sounds.dude.land()
      player.newsound = "land";
    }
    p1touchdown = player.body.touching.down;

    if (cursors.up.isDown && player.body.touching.down) {
      sounds.dude.jump()
      player.newsound = "jump";
      player.body.velocity.y = -300;
      gameStarted = true;
    }

     if (player.x < 0) {
      player.x = 300;
    }
    if (player.x > 320) {
      player.x = 0;
    }
    if (player.y < 8000) {
      var playerGravity = 300;
      if (cameraScrollRate!=.75) {
        eurecaServer.distribute("setProp",{
          prop: "cameraScrollRate",
          val: .75
        })
      }
      player.body.gravity.y = playerGravity;
    } else if (player.y < 7000) {
      var playerGravity = 275;
      player.body.gravity.y = playerGravity;
      if (cameraScrollRate!=1) {
        eurecaServer.distribute("setProp",{
          prop: "cameraScrollRate",
          val: 1
        })
      }
    }

    if (player.y > game.camera.y + 480 || playerHealth <= 0) {
      var gameOverTime = game.time.now + 3000;
      gameOverText = game.add.text(game.camera.x + 70, game.camera.y + 160, "GAME OVER", { fontSize: '32px', fill: 'white' });
      cameraScrollRate = 0;
      if (game.time.now > gameOverTime) {
        game.state.start('gameOver');
      }
    }

}

// player2

function movePlayer2() {
    if (cursors.left.isDown || leftButtonDown) {
      if (!player2.turningLeft) {
        sounds.dude.turn()
        player2.newsound = "turn";
        player2.turningLeft = true;
        player2.turningRight = false;
      }
      player2.body.velocity.x = -150
      player2.animations.play('left')
    } else if (cursors.right.isDown || rightButtonDown) {
      if (!player2.turningRight) {
        sounds.dude.turn()
        player2.newsound = "turn";
        player2.turningRight = true;
        player2.turningLeft = false;
      }
      player2.body.velocity.x = 150;
      player2.animations.play('right')
    } else {
      player2.body.velocity.x = 0;
      player2.frame = 8;
    }

    if (player2.body.touching.down && player2.body.touching.down != p2touchdown) {
      sounds.dude.land()
      player2.newsound = "land";
    }
    p2touchdown = player2.body.touching.down;

    if (cursors.up.isDown && player2.body.touching.down) {
      sounds.dude.jump()
      player2.newsound = "jump";
      player2.body.velocity.y = -300;
      gameStarted = true;
    }

     if (player2.x < 0) {
      player2.x = 300;
    }
    if (player2.x > 320) {
      player2.x = 0;
    }
    if (player2.y < 8000) {
      var playerGravity = 300;
      if (cameraScrollRate!=.75) {
        eurecaServer.distribute("setProp",{
          prop: "cameraScrollRate",
          val: .75
        })
      }
      player2.body.gravity.y = playerGravity;
    } else if (player2.y < 7000) {
      var playerGravity = 275;
      player2.body.gravity.y = playerGravity;
      if (cameraScrollRate!=1) {
        eurecaServer.distribute("setProp",{
          prop: "cameraScrollRate",
          val: 1
        })
      }
    }

    if (player2.y > game.camera.y + 480) {
      gameOverText = game.add.text(game.camera.x + 70, game.camera.y + 160, "GAME OVER", { fontSize: '32px', fill: 'white' });
      cameraScrollRate = 0;
    }

}

<commit_msg>sound<commit_after>
/* call functions on all clients using eurecaServer.distribute*/

function sendAllReady() {
  eurecaServer.distribute("setAllReady",null);
}

function sendPlatform() {
  //sounds.ping.note();
  eurecaServer.distribute("setPlatform", {
    x: cursorX,
    y: cursorY
  })
}

function updateMan1(args) {
  if (playerRole != "astronaut1") {
    player.x = args.x
    player.y = args.y
    var xVelocity = args.vel
    if(xVelocity < 0){
      player.animations.play('left');
    } else if(xVelocity > 0) {
      player.animations.play('right');
    } else {player.frame = 8}
    if (args.newsound) {
      switch(args.newsound) {
        case "turn":
            sounds.dude.turn();
          break;
        case "jump":
            sounds.dude.jump();
          break;
        case "land":
            sounds.dude.land();
          break;
      }
    }
  }
}
function updateMan2(args) {
  if (playerRole != "astronaut2") {
    player2.x = args.x
    player2.y = args.y
    var xVelocity = args.vel
    if(xVelocity < 0){
      player2.animations.play('left');
    } else if(xVelocity > 0) {
      player2.animations.play('right');
    } else {player2.frame = 8}
    if (args.newsound) {
      switch(args.newsound) {
        case "turn":
            sounds.dude.turn();
          break;
        case "jump":
            sounds.dude.jump();
          break;
        case "land":
            sounds.dude.land();
          break;
      }
    }
  }
}

function setProp(args) {
  window[args.prop] = args.val
}

var p1touchdown = true;
var p2touchdown = true;

// player1

function movePlayer1() {
  player.newsound = false;
  if (cursors.left.isDown || leftButtonDown) {
      if (!player.turningLeft) {
        sounds.dude.turn()
        player.newsound = "turn";
        player.turningLeft = true;
        player.turningRight = false;
      }
      player.body.velocity.x = -150
      player.animations.play("left");
    } else if (cursors.right.isDown || rightButtonDown) {
      if (!player.turningRight) {
        sounds.dude.turn()
        player.newsound = "turn";
        player.turningRight = true;
        player.turningLeft = false;
      }
      player.body.velocity.x = 150;
      player.animations.play('right');
    } else {
      if (player.body.velocity.x > 0) {
        player.body.velocity.x -= 5;
        player.animations.play('left');
      } else if (player.body.velocity.x < 0) {
        player.body.velocity.x += 5;
        player.animations.play('right');
      } else if (player.body.velocity.x === 0) {
        player.frame = 8;
      }
    }

    if (player.body.touching.down && player.body.touching.down != p1touchdown) {
      sounds.dude.land()
      player.newsound = "land";
    }
    p1touchdown = player.body.touching.down;

    if (cursors.up.isDown && player.body.touching.down) {
      sounds.dude.jump()
      player.newsound = "jump";
      player.body.velocity.y = -300;
      gameStarted = true;
    }

     if (player.x < 0) {
      player.x = 300;
    }
    if (player.x > 320) {
      player.x = 0;
    }
    if (player.y < 8000) {
      var playerGravity = 300;
      if (cameraScrollRate!=.75) {
        eurecaServer.distribute("setProp",{
          prop: "cameraScrollRate",
          val: .75
        })
      }
      player.body.gravity.y = playerGravity;
    } else if (player.y < 7000) {
      var playerGravity = 275;
      player.body.gravity.y = playerGravity;
      if (cameraScrollRate!=1) {
        eurecaServer.distribute("setProp",{
          prop: "cameraScrollRate",
          val: 1
        })
      }
    }

    if (player.y > game.camera.y + 480 || playerHealth <= 0) {
      var gameOverTime = game.time.now + 3000;
      gameOverText = game.add.text(game.camera.x + 70, game.camera.y + 160, "GAME OVER", { fontSize: '32px', fill: 'white' });
      cameraScrollRate = 0;
      if (game.time.now > gameOverTime) {
        game.state.start('gameOver');
      }
    }

}

// player2

function movePlayer2() {
    if (cursors.left.isDown || leftButtonDown) {
      if (!player2.turningLeft) {
        sounds.dude.turn()
        player2.newsound = "turn";
        player2.turningLeft = true;
        player2.turningRight = false;
      }
      player2.body.velocity.x = -150
      player2.animations.play('left')
    } else if (cursors.right.isDown || rightButtonDown) {
      if (!player2.turningRight) {
        sounds.dude.turn()
        player2.newsound = "turn";
        player2.turningRight = true;
        player2.turningLeft = false;
      }
      player2.body.velocity.x = 150;
      player2.animations.play('right')
    } else {
      player2.body.velocity.x = 0;
      player2.frame = 8;
    }

    if (player2.body.touching.down && player2.body.touching.down != p2touchdown) {
      sounds.dude.land()
      player2.newsound = "land";
    }
    p2touchdown = player2.body.touching.down;

    if (cursors.up.isDown && player2.body.touching.down) {
      sounds.dude.jump()
      player2.newsound = "jump";
      player2.body.velocity.y = -300;
      gameStarted = true;
    }

     if (player2.x < 0) {
      player2.x = 300;
    }
    if (player2.x > 320) {
      player2.x = 0;
    }
    if (player2.y < 8000) {
      var playerGravity = 300;
      if (cameraScrollRate!=.75) {
        eurecaServer.distribute("setProp",{
          prop: "cameraScrollRate",
          val: .75
        })
      }
      player2.body.gravity.y = playerGravity;
    } else if (player2.y < 7000) {
      var playerGravity = 275;
      player2.body.gravity.y = playerGravity;
      if (cameraScrollRate!=1) {
        eurecaServer.distribute("setProp",{
          prop: "cameraScrollRate",
          val: 1
        })
      }
    }

    if (player2.y > game.camera.y + 480) {
      gameOverText = game.add.text(game.camera.x + 70, game.camera.y + 160, "GAME OVER", { fontSize: '32px', fill: 'white' });
      cameraScrollRate = 0;
    }

}

<|endoftext|>


<commit_before>/**
 * Copyright 2014, 2015 IBM Corp. 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.
 */
/*global $:false, SPEECH_SYNTHESIS_VOICES */

'use strict';

$(document).ready(function() {
  function showError(msg) {
    console.error('Error: ', msg);
    var errorAlert = $('.error-row');
    errorAlert.css('visibility','hidden');
    errorAlert.css('background-color', '#d74108');
    errorAlert.css('color', 'white');
    var errorMessage = $('#errorMessage');
    errorMessage.text(msg);
    errorAlert.css('visibility','');

    $('#errorClose').click(function(e) {
      e.preventDefault();
      errorAlert.css('visibility','hidden');
      return false;
    });
  }

  function synthesizeRequest(options, audio) {
    var sessionPermissions = JSON.parse(localStorage.getItem('sessionPermissions')) ? 0 : 1;
    var downloadURL = '/api/synthesize' +
      '?voice=' + options.voice +
      '&text=' + encodeURIComponent(options.text) +
      '&X-WDC-PL-OPT-OUT=' +  sessionPermissions;

    if (options.download) {
      downloadURL += '&download=true';
      window.location.href = downloadURL;
      return true;
    }
    audio.pause();
    try {
      audio.currentTime = 0;
    }
    catch(ex) {
      // ignore. Firefox just freaks out here for no apparent reason.
    }
    audio.src = downloadURL;
    enableButtons(true);
    audio.play();
    $('body').css('cursor', 'wait');
    $('.speak-button').css('cursor', 'wait');
    return true;
  }

  // Global comes from file constants.js
  var voices = SPEECH_SYNTHESIS_VOICES.voices;
  showVoices(voices);

  var voice = 'en-US_AllisonVoice';

  function isSSMLSupported() {
    if($('#ssmlArea').val() == italianSSML ||
       $('#ssmlArea').val() == japaneseSSML ||
       $('#ssmlArea').val() == brazilianPortugueseSSML ||
       $('#ssmlArea').val() == spanishSSML) {
      return false;
    }
    return true;
  }

  function disableButtons() {
    $('.download-button').prop('disabled', true);
    $('.speak-button').prop('disabled', true);
  }

  function enableButtons() {
    $('.download-button').prop('disabled', false);
    $('.speak-button').prop('disabled', false);
  }

  function showVoices(voices) {

    var currentTab = 'Text';

    // Show tabs
    $('#nav-tabs a').click(function (e) {
      e.preventDefault();
      $(this).tab('show');
    });

    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
      currentTab = $(e.target).text();
      audio.src = "";
      audio.controls = false;
      if(currentTab == "SSML" && isSSMLSupported() == false) {
        disableButtons();
      }
      else {
        enableButtons();
      }
    });

    var LANGUAGE_TABLE = {
      'en-US': 'American English (en-US)',
      'en-GB': 'British English (en-GB)',
      'ja-JP': 'Japanese (ja-JP)',
      'es-US': 'North American Spanish (es-US)',
      'de-DE': 'German (de-DE)',
      'fr-FR': 'French (fr-FR)',
      'it-IT': 'Italian (it-IT)',
      'pt-BR': 'Brazilian Portuguese (pt-BR)',
      'es-ES': 'Castilian Spanish (es-ES)'
    };

    $.each(voices, function(idx, voice) {
      var voiceName = voice.name.substring(6, voice.name.length - 5);
      var optionText = LANGUAGE_TABLE[voice.language] + ': ' + voiceName + ' ('  + voice.gender + ')';
      $('#dropdownMenuList').append(
        $('<li>')
        .attr('role', 'presentation')
        .append(
          $('<a>').attr('role', 'menu-item')
          .attr('href', '/')
          .attr('data-voice', voice.name)
          .append(optionText)
          )
        );
    });

    var audio = $('.audio').get(0),
        textArea = $('#textArea');

    var textChanged = false;

    $('#textArea').val(englishExpressiveText);
    $('#ssmlArea').val(englishExpresiveSSML);

    $('#textArea').change(function(){
      textChanged = true;
    });

    $('#dropdownMenuList').click(function(evt) {
      evt.preventDefault();
      evt.stopPropagation();
      var newVoiceDescription = $(evt.target).text();
      voice = $(evt.target).data('voice');
      $('#dropdownMenuDefault').empty().text(newVoiceDescription);
      $('#dropdownMenu1').dropdown('toggle');
      $('#ssml_caption').text('SSML');
      audio.src = ""; // to stop currently playing audio
      audio.controls = false; // to hide the player
      enableButtons();

      var lang = voice.substring(0, 2);
        switch(lang) {
          case 'es':
            $('#textArea').val(spanishText);
            $('#ssmlArea').val(spanishSSML);
            if(currentTab == "SSML" || currentTab == "Expressive SSML") disableButtons();
            break;
          case 'fr':
            $('#textArea').val(frenchText);
            $('#ssmlArea').val(frenchSSML);
            break;
          case 'de':
            $('#textArea').val(germanText);
            $('#ssmlArea').val(germanSSML);
            break;
          case 'it':
            $('#textArea').val(italianText);
            $('#ssmlArea').val(italianSSML);
            if(currentTab == "SSML" || currentTab == "Expressive SSML") disableButtons();
            break;
          case 'ja':
            $('#textArea').val(japaneseText);
            $('#ssmlArea').val(japaneseSSML);
            if(currentTab == "SSML" || currentTab == "Expressive SSML") disableButtons();
            break;
          case 'pt':
            $('#textArea').val(brazilianPortugueseText);
            $('#ssmlArea').val(brazilianPortugueseSSML);
            if(currentTab == "SSML" || currentTab == "Expressive SSML") disableButtons();
            break;
          case 'en':
            if(voice === 'en-US_AllisonVoice') {
              $('#ssml_caption').text('Expressive SSML');
              $('#textArea').val(englishExpressiveText);
              $('#ssmlArea').val(englishExpresiveSSML);
            }
            else {
              $('#textArea').val(englishText);
              var en_accent = voice.substring(0, 5);
              if(en_accent === 'en-US') {
                $('#ssmlArea').val(usEnglishSSML);
              }
              else if(en_accent === 'en-GB') {
                $('#ssmlArea').val(ukEnglishSSML);
              }
            }
            break;
        }
    });

    // IE and Safari not supported disabled Speak button
    if ($('body').hasClass('ie') || $('body').hasClass('safari')) {
      $('.speak-button').prop('disabled', true);
    }

    if ($('.speak-button').prop('disabled')) {
      $('.ie-speak .arrow-box').show();
    }

    $('.audio').on('error', function (err) {
      if(this.src == this.baseURI) {
        console.log('audio.src was reset');
        return;
      }
      $.get('/api/synthesize?text=test').always(function (response) {
        showError(response.responseText || 'Error processing the request');
      });
    });

    $('.audio').on('canplaythrough', function () {
      console.log('canplaythrough');
      audio.controls = true;
      $('.result').show();
      $('.error-row').css('visibility','hidden');
      $('html, body').animate({scrollTop: $(".audio").offset().top}, 500);
      $('body').css('cursor', 'default');
      $('.speak-button').css('cursor', 'pointer');
    });

    $('.download-button').click(function() {
      textArea.focus();
      if (validText(voice, textArea.val())) {
        var utteranceDownloadOptions = {
          text: currentTab === 'SSML' || currentTab === 'Expressive SSML' ? $('#ssmlArea').val(): $('#textArea').val(),
          voice: voice,
          download: true
        };
        synthesizeRequest(utteranceDownloadOptions);
      }
    });

    $('.speak-button').click(function(evt) {
      evt.stopPropagation();
      evt.preventDefault();
      $('.result').hide();

      $('#textArea').focus();
      var text = currentTab === 'SSML' || currentTab === 'Expressive SSML' ? $('#ssmlArea').val() : $('#textArea').val();
      if (validText(voice, text)) {
        var utteranceOptions = {
          text: text,
          voice: voice,
          sessionPermissions: JSON.parse(localStorage.getItem('sessionPermissions')) ? 0 : 1
        };

        synthesizeRequest(utteranceOptions, audio);
      }
      return false;
    });

    /**
    * Check that the text contains Japanese characters only
    * @return true if the string contains only Japanese characters
    */
    function containsAllJapanese(str) {
       return str.match(/^[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\uff00-\uff9f\u4e00-\u9faf\u3400-\u4dbf]+$/);
    }

    function validText(voice, text) {
      $('.error-row').css('visibility','hidden');
      $('.errorMsg').text('');
      $('.latin').hide();

      if ($.trim(text).length === 0) { // empty text
        showError('Please enter the text you would like to synthesize in the text window.');
        return false;
      }

      return true;
    }
  }

  (function() {
    // Radio buttons for session permissions
    localStorage.setItem('sessionPermissions', true);
    var sessionPermissionsRadio = $('#sessionPermissionsRadioGroup input[type="radio"]');
    sessionPermissionsRadio.click(function() {
      var checkedValue = sessionPermissionsRadio.filter(':checked').val();
      localStorage.setItem('sessionPermissions', checkedValue);
    });
  }());

});
<commit_msg>change 'wait' cursor to 'default' (body) and 'pointer' (speak button) once error message is closed<commit_after>/**
 * Copyright 2014, 2015 IBM Corp. 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.
 */
/*global $:false, SPEECH_SYNTHESIS_VOICES */

'use strict';

$(document).ready(function() {
  function showError(msg) {
    console.error('Error: ', msg);
    var errorAlert = $('.error-row');
    errorAlert.css('visibility','hidden');
    errorAlert.css('background-color', '#d74108');
    errorAlert.css('color', 'white');
    var errorMessage = $('#errorMessage');
    errorMessage.text(msg);
    errorAlert.css('visibility','');

    $('#errorClose').click(function(e) {
      e.preventDefault();
      errorAlert.css('visibility','hidden');
      $('body').css('cursor', 'default');
      $('.speak-button').css('cursor', 'pointer');
      return false;
    });
  }

  function synthesizeRequest(options, audio) {
    var sessionPermissions = JSON.parse(localStorage.getItem('sessionPermissions')) ? 0 : 1;
    var downloadURL = '/api/synthesize' +
      '?voice=' + options.voice +
      '&text=' + encodeURIComponent(options.text) +
      '&X-WDC-PL-OPT-OUT=' +  sessionPermissions;

    if (options.download) {
      downloadURL += '&download=true';
      window.location.href = downloadURL;
      return true;
    }
    audio.pause();
    try {
      audio.currentTime = 0;
    }
    catch(ex) {
      // ignore. Firefox just freaks out here for no apparent reason.
    }
    audio.src = downloadURL;
    enableButtons(true);
    audio.play();
    $('body').css('cursor', 'wait');
    $('.speak-button').css('cursor', 'wait');
    return true;
  }

  // Global comes from file constants.js
  var voices = SPEECH_SYNTHESIS_VOICES.voices;
  showVoices(voices);

  var voice = 'en-US_AllisonVoice';

  function isSSMLSupported() {
    if($('#ssmlArea').val() == italianSSML ||
       $('#ssmlArea').val() == japaneseSSML ||
       $('#ssmlArea').val() == brazilianPortugueseSSML ||
       $('#ssmlArea').val() == spanishSSML) {
      return false;
    }
    return true;
  }

  function disableButtons() {
    $('.download-button').prop('disabled', true);
    $('.speak-button').prop('disabled', true);
  }

  function enableButtons() {
    $('.download-button').prop('disabled', false);
    $('.speak-button').prop('disabled', false);
  }

  function showVoices(voices) {

    var currentTab = 'Text';

    // Show tabs
    $('#nav-tabs a').click(function (e) {
      e.preventDefault();
      $(this).tab('show');
    });

    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
      currentTab = $(e.target).text();
      audio.src = "";
      audio.controls = false;
      if(currentTab == "SSML" && isSSMLSupported() == false) {
        disableButtons();
      }
      else {
        enableButtons();
      }
    });

    var LANGUAGE_TABLE = {
      'en-US': 'American English (en-US)',
      'en-GB': 'British English (en-GB)',
      'ja-JP': 'Japanese (ja-JP)',
      'es-US': 'North American Spanish (es-US)',
      'de-DE': 'German (de-DE)',
      'fr-FR': 'French (fr-FR)',
      'it-IT': 'Italian (it-IT)',
      'pt-BR': 'Brazilian Portuguese (pt-BR)',
      'es-ES': 'Castilian Spanish (es-ES)'
    };

    $.each(voices, function(idx, voice) {
      var voiceName = voice.name.substring(6, voice.name.length - 5);
      var optionText = LANGUAGE_TABLE[voice.language] + ': ' + voiceName + ' ('  + voice.gender + ')';
      $('#dropdownMenuList').append(
        $('<li>')
        .attr('role', 'presentation')
        .append(
          $('<a>').attr('role', 'menu-item')
          .attr('href', '/')
          .attr('data-voice', voice.name)
          .append(optionText)
          )
        );
    });

    var audio = $('.audio').get(0),
        textArea = $('#textArea');

    var textChanged = false;

    $('#textArea').val(englishExpressiveText);
    $('#ssmlArea').val(englishExpresiveSSML);

    $('#textArea').change(function(){
      textChanged = true;
    });

    $('#dropdownMenuList').click(function(evt) {
      evt.preventDefault();
      evt.stopPropagation();
      var newVoiceDescription = $(evt.target).text();
      voice = $(evt.target).data('voice');
      $('#dropdownMenuDefault').empty().text(newVoiceDescription);
      $('#dropdownMenu1').dropdown('toggle');
      $('#ssml_caption').text('SSML');
      audio.src = ""; // to stop currently playing audio
      audio.controls = false; // to hide the player
      enableButtons();

      var lang = voice.substring(0, 2);
        switch(lang) {
          case 'es':
            $('#textArea').val(spanishText);
            $('#ssmlArea').val(spanishSSML);
            if(currentTab == "SSML" || currentTab == "Expressive SSML") disableButtons();
            break;
          case 'fr':
            $('#textArea').val(frenchText);
            $('#ssmlArea').val(frenchSSML);
            break;
          case 'de':
            $('#textArea').val(germanText);
            $('#ssmlArea').val(germanSSML);
            break;
          case 'it':
            $('#textArea').val(italianText);
            $('#ssmlArea').val(italianSSML);
            if(currentTab == "SSML" || currentTab == "Expressive SSML") disableButtons();
            break;
          case 'ja':
            $('#textArea').val(japaneseText);
            $('#ssmlArea').val(japaneseSSML);
            if(currentTab == "SSML" || currentTab == "Expressive SSML") disableButtons();
            break;
          case 'pt':
            $('#textArea').val(brazilianPortugueseText);
            $('#ssmlArea').val(brazilianPortugueseSSML);
            if(currentTab == "SSML" || currentTab == "Expressive SSML") disableButtons();
            break;
          case 'en':
            if(voice === 'en-US_AllisonVoice') {
              $('#ssml_caption').text('Expressive SSML');
              $('#textArea').val(englishExpressiveText);
              $('#ssmlArea').val(englishExpresiveSSML);
            }
            else {
              $('#textArea').val(englishText);
              var en_accent = voice.substring(0, 5);
              if(en_accent === 'en-US') {
                $('#ssmlArea').val(usEnglishSSML);
              }
              else if(en_accent === 'en-GB') {
                $('#ssmlArea').val(ukEnglishSSML);
              }
            }
            break;
        }
    });

    // IE and Safari not supported disabled Speak button
    if ($('body').hasClass('ie') || $('body').hasClass('safari')) {
      $('.speak-button').prop('disabled', true);
    }

    if ($('.speak-button').prop('disabled')) {
      $('.ie-speak .arrow-box').show();
    }

    $('.audio').on('error', function (err) {
      if(this.src == this.baseURI) {
        console.log('audio.src was reset');
        return;
      }
      $.get('/api/synthesize?text=test').always(function (response) {
        showError(response.responseText || 'Error processing the request');
      });
    });

    $('.audio').on('canplaythrough', function () {
      console.log('canplaythrough');
      audio.controls = true;
      $('.result').show();
      $('.error-row').css('visibility','hidden');
      $('html, body').animate({scrollTop: $(".audio").offset().top}, 500);
      $('body').css('cursor', 'default');
      $('.speak-button').css('cursor', 'pointer');
    });

    $('.download-button').click(function() {
      textArea.focus();
      if (validText(voice, textArea.val())) {
        var utteranceDownloadOptions = {
          text: currentTab === 'SSML' || currentTab === 'Expressive SSML' ? $('#ssmlArea').val(): $('#textArea').val(),
          voice: voice,
          download: true
        };
        synthesizeRequest(utteranceDownloadOptions);
      }
    });

    $('.speak-button').click(function(evt) {
      evt.stopPropagation();
      evt.preventDefault();
      $('.result').hide();

      $('#textArea').focus();
      var text = currentTab === 'SSML' || currentTab === 'Expressive SSML' ? $('#ssmlArea').val() : $('#textArea').val();
      if (validText(voice, text)) {
        var utteranceOptions = {
          text: text,
          voice: voice,
          sessionPermissions: JSON.parse(localStorage.getItem('sessionPermissions')) ? 0 : 1
        };

        synthesizeRequest(utteranceOptions, audio);
      }
      return false;
    });

    /**
    * Check that the text contains Japanese characters only
    * @return true if the string contains only Japanese characters
    */
    function containsAllJapanese(str) {
       return str.match(/^[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\uff00-\uff9f\u4e00-\u9faf\u3400-\u4dbf]+$/);
    }

    function validText(voice, text) {
      $('.error-row').css('visibility','hidden');
      $('.errorMsg').text('');
      $('.latin').hide();

      if ($.trim(text).length === 0) { // empty text
        showError('Please enter the text you would like to synthesize in the text window.');
        return false;
      }

      return true;
    }
  }

  (function() {
    // Radio buttons for session permissions
    localStorage.setItem('sessionPermissions', true);
    var sessionPermissionsRadio = $('#sessionPermissionsRadioGroup input[type="radio"]');
    sessionPermissionsRadio.click(function() {
      var checkedValue = sessionPermissionsRadio.filter(':checked').val();
      localStorage.setItem('sessionPermissions', checkedValue);
    });
  }());

});
<|endoftext|>


<commit_before>var t = require("tap")
var fs = require("fs")

var currentTest

var strings = ['b', 'z', 'a']
var buffs = strings.map(function (s) { return new Buffer(s) })
var hexes = buffs.map(function (b) { return b.toString('hex') })

function getRet (encoding) {
  switch (encoding) {
    case 'hex':
      return hexes
    case 'buffer':
      return buffs
    default:
      return strings
  }
}

var readdir = fs.readdir
var failed = false
fs.readdir = function(path, options, cb) {
  if (!failed) {
    // simulate an EMFILE and then open and close a thing to retry
    failed = true
    process.nextTick(function () {
      var er = new Error('synthetic emfile')
      er.code = 'EMFILE'
      cb(er)
      process.nextTick(function () {
        g.closeSync(fs.openSync(__filename, 'r'))
      })
    })
    return
  }

  failed = false
  currentTest.isa(cb, 'function')
  currentTest.isa(options, 'object')
  currentTest.ok(options)
  process.nextTick(function() {
    var ret = getRet(options.encoding)
    cb(null, ret)
  })
}

var g = require("../")

var encodings = ['buffer', 'hex', 'utf8', null]
encodings.forEach(function (enc) {
  t.test('encoding=' + enc, function (t) {
    currentTest = t
    g.readdir("whatevers", { encoding: enc }, function (er, files) {
      if (er)
        throw er
      t.same(files, getRet(enc).sort())
      t.end()
    })
  })
})
<commit_msg>remove deprecated Buffer ctor from tests<commit_after>var t = require("tap")
var fs = require("fs")

var currentTest

var strings = ['b', 'z', 'a']
var buffs = strings.map(function (s) { return Buffer.from(s) })
var hexes = buffs.map(function (b) { return b.toString('hex') })

function getRet (encoding) {
  switch (encoding) {
    case 'hex':
      return hexes
    case 'buffer':
      return buffs
    default:
      return strings
  }
}

var readdir = fs.readdir
var failed = false
fs.readdir = function(path, options, cb) {
  if (!failed) {
    // simulate an EMFILE and then open and close a thing to retry
    failed = true
    process.nextTick(function () {
      var er = new Error('synthetic emfile')
      er.code = 'EMFILE'
      cb(er)
      process.nextTick(function () {
        g.closeSync(fs.openSync(__filename, 'r'))
      })
    })
    return
  }

  failed = false
  currentTest.isa(cb, 'function')
  currentTest.isa(options, 'object')
  currentTest.ok(options)
  process.nextTick(function() {
    var ret = getRet(options.encoding)
    cb(null, ret)
  })
}

var g = require("../")

var encodings = ['buffer', 'hex', 'utf8', null]
encodings.forEach(function (enc) {
  t.test('encoding=' + enc, function (t) {
    currentTest = t
    g.readdir("whatevers", { encoding: enc }, function (er, files) {
      if (er)
        throw er
      t.same(files, getRet(enc).sort())
      t.end()
    })
  })
})
<|endoftext|>


<commit_before>suite("scopeMatch", function() {
  var assert  = require('assert');
  var utils   = require('../utils.js');

  var mktest = function(scopePatterns, scopesets, matches) {
    return function() {
      var res;
      var exception;

      try {
        res = utils.scopeMatch(scopePatterns, scopesets);
      } catch (e) {
        res = 'exception';
        exception = e
      }
      assert(res == matches,
        "Incorrect result for scopeMatch(" +
        JSON.stringify(scopePatterns) +
        ", " + JSON.stringify(scopesets) + ") -> " + res + ' ' + exception)
    };
  };

  test("single exact match, string",
    mktest(["foo:bar"], "foo:bar", 'exception'));
  test("single exact match, [string]",
    mktest(["foo:bar"], ["foo:bar"], 'exception'));
  test("single exact match, [[string]]",
    mktest(["foo:bar"], [["foo:bar"]], true));
  test("empty string in scopesets",
    mktest(["foo:bar"], '', 'exception'));
  test("empty [string] in scopesets",
    mktest(["foo:bar"], [''], 'exception'));
  test("empty [[string]] in scopesets",
    mktest(["foo:bar"], [['']], false));
  test("prefix",
    mktest(["foo:*"], [['foo:bar']], true));
  test("prefix with no star",
    mktest(["foo:"], [['foo:bar']], false));
  test("star but not prefix",
    mktest(["foo:bar:*"], [['bar:bing']], false));
  test("star but not prefix",
    mktest(["bar:*"], [['foo:bar:bing']], false));
  test("disjunction strings",
    mktest(["bar:*"], ['foo:x', 'bar:x'], 'exception'));
  test("disjunction [strings]",
    mktest(["bar:*"], [['foo:x'], ['bar:x']], true));
  test("conjunction",
    mktest(["bar:*", 'foo:x'], [['foo:x', 'bar:y']], true));
  test("empty pattern",
    mktest([""], [['foo:bar']], false));
  test("empty patterns",
    mktest([], [['foo:bar']], false));
  test("bare star",
    mktest(["*"], [['foo:bar', 'bar:bing']], true));
  test("empty conjunction in scopesets",
    mktest(["foo:bar"], [[]], true));
  test("non-string scopesets",
    mktest(["foo:bar"], {}, 'exception'));
  test("non-string scopeset",
    mktest(["foo:bar"], [{}], 'exception'));
  test("non-string scope",
    mktest(["foo:bar"], [[{}]], 'exception'));
  test("empty disjunction in scopesets",
    mktest(["foo:bar"], [], false));
});

<commit_msg>Verify that star is only matched at the end of a string<commit_after>suite("scopeMatch", function() {
  var assert  = require('assert');
  var utils   = require('../utils.js');

  var mktest = function(scopePatterns, scopesets, matches) {
    return function() {
      var res;
      var exception;

      try {
        res = utils.scopeMatch(scopePatterns, scopesets);
      } catch (e) {
        res = 'exception';
        exception = e
      }
      assert(res == matches,
        "Incorrect result for scopeMatch(" +
        JSON.stringify(scopePatterns) +
        ", " + JSON.stringify(scopesets) + ") -> " + res + ' ' + exception)
    };
  };

  test("single exact match, string",
    mktest(["foo:bar"], "foo:bar", 'exception'));
  test("single exact match, [string]",
    mktest(["foo:bar"], ["foo:bar"], 'exception'));
  test("single exact match, [[string]]",
    mktest(["foo:bar"], [["foo:bar"]], true));
  test("empty string in scopesets",
    mktest(["foo:bar"], '', 'exception'));
  test("empty [string] in scopesets",
    mktest(["foo:bar"], [''], 'exception'));
  test("empty [[string]] in scopesets",
    mktest(["foo:bar"], [['']], false));
  test("prefix",
    mktest(["foo:*"], [['foo:bar']], true));
  test("star not at end",
    mktest(["foo:*:bing"], [['foo:bar:bing']], false));
  test("star at beginnging",
    mktest(["*:bar"], [['foo:bar']], false));
  test("prefix with no star",
    mktest(["foo:"], [['foo:bar']], false));
  test("star but not prefix",
    mktest(["foo:bar:*"], [['bar:bing']], false));
  test("star but not prefix",
    mktest(["bar:*"], [['foo:bar:bing']], false));
  test("disjunction strings",
    mktest(["bar:*"], ['foo:x', 'bar:x'], 'exception'));
  test("disjunction [strings]",
    mktest(["bar:*"], [['foo:x'], ['bar:x']], true));
  test("conjunction",
    mktest(["bar:*", 'foo:x'], [['foo:x', 'bar:y']], true));
  test("empty pattern",
    mktest([""], [['foo:bar']], false));
  test("empty patterns",
    mktest([], [['foo:bar']], false));
  test("bare star",
    mktest(["*"], [['foo:bar', 'bar:bing']], true));
  test("empty conjunction in scopesets",
    mktest(["foo:bar"], [[]], true));
  test("non-string scopesets",
    mktest(["foo:bar"], {}, 'exception'));
  test("non-string scopeset",
    mktest(["foo:bar"], [{}], 'exception'));
  test("non-string scope",
    mktest(["foo:bar"], [[{}]], 'exception'));
  test("empty disjunction in scopesets",
    mktest(["foo:bar"], [], false));
});

<|endoftext|>


<commit_before>// encrypt_tag

jsToolBar.prototype.elements.wikicipher = {
  type: 'button',
  title: 'Wikicipher tag',
  fn: {
    wiki: function() { this.encloseSelection('{{cipher(0)', '}}') }
  }
}

window.onload=function(){
	var warn = document.getElementsByClassName('flash warning');
	if (warn.length>0){
		jQuery('.jstb_wikicipher').hide();
	}
};
<commit_msg>Fixed hided cipher button on error<commit_after>// encrypt_tag

jsToolBar.prototype.elements.wikicipher = {
  type: 'button',
  title: 'Wikicipher tag',
  fn: {
    wiki: function() { this.encloseSelection('{{cipher(0)', '}}') }
  }
}

jQuery(function($){
	if ($('.flash.warning').length > 0){
		$('.jstb_wikicipher').hide();
	}
});
<|endoftext|>


<commit_before>
//
//  jibe.js - Jibe: be in accord; agree.
//
//  - A modern, lightweight, collaborative editing environment.
//
//  Copyright (c) 2015 Visionist, Inc.
//
//  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 Jibe = (function (BCSocket, CodeMirror, Showdown, Timestamps, TextFormat) {
  /*
   *  Returns location string based on URL hash; else default to The Dark Side.
   */
  function getLocation () {
    return location.hash !== '' ? location.hash.substring (1) : 'The Dark Side';
  }

  /*
   *  Reads stored cookie --
   *  -- intended for defining the user via a username cookie.
   */
  function getCookie (name) {
    var nameEQ = name + "=";
    var cookies = document.cookie.split (';');
    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        while (cookie.charAt(0) == ' ') {
          cookie = cookie.substring (1, cookie.length);
        }
        if (cookie.indexOf (nameEQ) == 0) {
          return cookie.substring (nameEQ.length, cookie.length);
        }
    }
    return null;
  }

  /*
   *  Sets up the socket and channel for a specific room.
   */
  function setSocket (tool, socket, channel, room) {
    if (tool === 'io') {
      return io (window.location.host + channel, function () {
      	socket.emit ('subscribe', room);
      });
    } else {
      var socket = new BCSocket (null, { reconnect: true });
      var share  = new window.sharejs.Connection (socket);
      return share.get ('users', room);
    }
  }

  /*
   *  Sets up the CodeMirror object (editor) for a specific room.
   */
  function setCodeMirror () {
    return CodeMirror.fromTextArea (document.getElementById ('entry-markdown'), {
			mode         : 'markdown',
			tabMode      : 'indent',
			lineWrapping : true
		});
  }

  /*
   *  Instantiates the timestamps handler --
   *  -- leverages timestamps.js.
   */
  function setTimestamps (editor) {
    return new Timestamps ({
      container  : '#timestamps-container',
      codemirror : editor,
      format     : 'YYYY-MM-DD HH:MI:SS'
    });
  }

  /*
   *  Instantiates the text formatting handler --
   *  -- leverages textformat.js.
   */
  function setTextFormat (editor) {
    return new TextFormat ({ codemirror: editor });
  }

  /*
   *  Really not the best way to do things as it includes Markdown formatting along with words --
   *  -- updates the word count located on the editor.
   */
  function updateWordCount (editor) {
    var word_count   = $('.entry-word-count');
    var editor_value = editor.getValue ();

    if (editor_value.length) {
      if (editor_value.match(/\S+/g) === null) {
        word_count.html ('0 words');
      } else {
        word_count.html (editor_value.match(/\S+/g).length + ' words');
      }
    }
  }

  /*
   *  Updates the Jibe preview tab --
   *  -- works in real time (updates while other type).
   */
  function updatePreview (editor, converter) {
    var preview = $('.rendered-markdown');
    preview.html (converter.makeHtml (editor.getValue ()));
    updateWordCount (editor);
  }

  return {
    agree : function (string) {
      var client     = getCookie ('username') || Math.floor ((Math.random () * 10000000)).toString ();
      var room       = getLocation ();
      var stamps_io  = setSocket ('io', stamps_io, '/stamps', room);
      var editor_bc  = setSocket ('bc', null, null, room);
      var editor     = setCodeMirror ();
      var converter  = new Showdown.converter ();
      var timestamps = setTimestamps (editor);
      var textformat = setTextFormat (editor);

      $('#format-bold'  ).click (function () { textformat.bold      (); });
			$('#format-code'  ).click (function () { textformat.monospace (); });
			$('#format-italic').click (function () { textformat.italic    (); });

      /*
       *  Subscribes to BrowserChannel connection and attaches CodeMirror editor --
       *  -- using sharejs for all of the OT tasking.
       */
      editor_bc.subscribe ();
      editor_bc.whenReady (function () {
        if (!editor_bc.type) editor_bc.create ('text');
      	if (editor_bc.type && editor_bc.type.name === 'text') {
          editor_bc.attachCodeMirror (editor);
        }
      });

      /*
       *  Fires whenever the editor changes --
       *  -- updates timestamps.
       */
      editor.on ("change", function (event) {
				timestamps.draw ();
				updatePreview (editor, converter);
			});

      /*
       *  Fires whenever the user finished typing a characters --
       *  -- sends current line and author to server to timestamp author color coding.
       */
      editor.on ('keyup', function (event) {
				var cursor = editor.getCursor ();
				if (editor.getLine (cursor.line) !== '') {
					// window.chat.emit ('active', {
					// 	pad_id : window.pad_id,
					// 	client : clientID,
					// 	line   : cursor.line
					// });``
				}
			});

      /*
       *  Updates the Preview panel.
       */
      updatePreview (editor, converter);
    }
  }
})(BCSocket, CodeMirror, Showdown, Timestamps, TextFormat);

/*
 *  Sets up scope and protects the jQuery $ sign --
 *  -- plays nice with other jQuery plugins.
 *
 *  Utilization: $('div').jibe ()
 *  ...the rest is magic!
 */
(function ($, Jibe) {
	$.fn.jibe = function () {
    var jibe_container = this; // e.g. #jibe-container
    /*
     *	Downloads required HTML for firing Jibe into the coolest jibe you'll ever jibe.
     */
    $.ajax ({
    	url: "templates/editor.html",
    	type: "GET",
    	success: function (data) {
        // Replaces container div with Jibe HTML
    		$(jibe_container).html (data);
        // Jibe!
        Jibe.agree ();
    	},
      async: false
    });
	};
}(jQuery, Jibe));
<commit_msg>Made the setSocket 'bc' condition to be somewhat more generic<commit_after>
//
//  jibe.js - Jibe: be in accord; agree.
//
//  - A modern, lightweight, collaborative editing environment.
//
//  Copyright (c) 2015 Visionist, Inc.
//
//  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 Jibe = (function (BCSocket, CodeMirror, Showdown, Timestamps, TextFormat) {
  /*
   *  Returns location string based on URL hash; else default to The Dark Side.
   */
  function getLocation () {
    return location.hash !== '' ? location.hash.substring (1) : 'The Dark Side';
  }

  /*
   *  Reads stored cookie --
   *  -- intended for defining the user via a username cookie.
   */
  function getCookie (name) {
    var nameEQ = name + "=";
    var cookies = document.cookie.split (';');
    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        while (cookie.charAt(0) == ' ') {
          cookie = cookie.substring (1, cookie.length);
        }
        if (cookie.indexOf (nameEQ) == 0) {
          return cookie.substring (nameEQ.length, cookie.length);
        }
    }
    return null;
  }

  /*
   *  Sets up the socket and channel for a specific room.
   */
  function setSocket (tool, socket, channel, room) {
    if (tool === 'io') {
      return io (window.location.host + channel, function () {
      	socket.emit ('subscribe', room);
      });
    } else {
      var socket = new BCSocket (null, { reconnect: true });
      var share  = new window.sharejs.Connection (socket);
      return share.get (channel, room);
    }
  }

  /*
   *  Sets up the CodeMirror object (editor) for a specific room.
   */
  function setCodeMirror () {
    return CodeMirror.fromTextArea (document.getElementById ('entry-markdown'), {
			mode         : 'markdown',
			tabMode      : 'indent',
			lineWrapping : true
		});
  }

  /*
   *  Instantiates the timestamps handler --
   *  -- leverages timestamps.js.
   */
  function setTimestamps (editor) {
    return new Timestamps ({
      container  : '#timestamps-container',
      codemirror : editor,
      format     : 'YYYY-MM-DD HH:MI:SS'
    });
  }

  /*
   *  Instantiates the text formatting handler --
   *  -- leverages textformat.js.
   */
  function setTextFormat (editor) {
    return new TextFormat ({ codemirror: editor });
  }

  /*
   *  Really not the best way to do things as it includes Markdown formatting along with words --
   *  -- updates the word count located on the editor.
   */
  function updateWordCount (editor) {
    var word_count   = $('.entry-word-count');
    var editor_value = editor.getValue ();

    if (editor_value.length) {
      if (editor_value.match(/\S+/g) === null) {
        word_count.html ('0 words');
      } else {
        word_count.html (editor_value.match(/\S+/g).length + ' words');
      }
    }
  }

  /*
   *  Updates the Jibe preview tab --
   *  -- works in real time (updates while other type).
   */
  function updatePreview (editor, converter) {
    var preview = $('.rendered-markdown');
    preview.html (converter.makeHtml (editor.getValue ()));
    updateWordCount (editor);
  }

  return {
    agree : function (string) {
      var client     = getCookie ('username') || Math.floor ((Math.random () * 10000000)).toString ();
      var room       = getLocation ();
      var stamps_io  = setSocket ('io', stamps_io, '/stamps', room);
      var editor_bc  = setSocket ('bc', null, 'jibe', room);
      var editor     = setCodeMirror ();
      var converter  = new Showdown.converter ();
      var timestamps = setTimestamps (editor);
      var textformat = setTextFormat (editor);

      $('#format-bold'  ).click (function () { textformat.bold      (); });
			$('#format-code'  ).click (function () { textformat.monospace (); });
			$('#format-italic').click (function () { textformat.italic    (); });

      /*
       *  Subscribes to BrowserChannel connection and attaches CodeMirror editor --
       *  -- using sharejs for all of the OT tasking.
       */
      editor_bc.subscribe ();
      editor_bc.whenReady (function () {
        if (!editor_bc.type) editor_bc.create ('text');
      	if (editor_bc.type && editor_bc.type.name === 'text') {
          editor_bc.attachCodeMirror (editor);
        }
      });

      /*
       *  Fires whenever the editor changes --
       *  -- updates timestamps.
       */
      editor.on ("change", function (event) {
				timestamps.draw ();
				updatePreview (editor, converter);
			});

      /*
       *  Fires whenever the user finished typing a characters --
       *  -- sends current line and author to server to timestamp author color coding.
       */
      editor.on ('keyup', function (event) {
				var cursor = editor.getCursor ();
				if (editor.getLine (cursor.line) !== '') {
					// window.chat.emit ('active', {
					// 	pad_id : window.pad_id,
					// 	client : clientID,
					// 	line   : cursor.line
					// });``
				}
			});

      /*
       *  Updates the Preview panel.
       */
      updatePreview (editor, converter);
    }
  }
})(BCSocket, CodeMirror, Showdown, Timestamps, TextFormat);

/*
 *  Sets up scope and protects the jQuery $ sign --
 *  -- plays nice with other jQuery plugins.
 *
 *  Utilization: $('div').jibe ()
 *  ...the rest is magic! :-)
 */
(function ($, Jibe) {
	$.fn.jibe = function () {
    var jibe_container = this; // e.g. #jibe-container
    /*
     *	Downloads required HTML for firing Jibe into the coolest jibe you'll ever jibe.
     */
    $.ajax ({
    	url: "templates/editor.html",
    	type: "GET",
    	success: function (data) {
        // Replaces container div with Jibe HTML
    		$(jibe_container).html (data);
        // Jibe!
        Jibe.agree ();
    	},
      async: false
    });
	};
}(jQuery, Jibe));
<|endoftext|>


<commit_before>var MusicModel = Backbone.Model.extend({});
var MusicList = Backbone.Collection.extend({ model: MusicModel });

musicList = new MusicList({});
musicList.reset([
    {
	num: 1,
	title: 'Setting Forth',
	album: 'Into the Wild',
	artist: 'Eddie Vedder'
    },
    {
	num: 2,
	title: 'No Ceiling',
	album: 'Into the Wild',
	artist: 'Eddie Vedder'
    }
]);

var MusicView = Backbone.View.extend({
    tagName: 'div',
    className: 'music entry',
    initialize: function(){
	this.template = _.template('<%= num %> | <%= title %> | <%= album %> | <%= artist %>');
    },
    render: function(){
	this.$el.html(this.template(this.model.attributes));
	return this;
    }
});

var MusicFormView = Backbone.View.extend({
    el: 'div.wrapper',
    events: {
	'submit #musicform': 'submit'
    },
    submit: function(event){
	$.post(this.$el.attr('action'),
	       this.$el.serialize())
	    .done(function(data){
		console.log(data);
	    });
	return false;
    }
});

var MusicListView = Backbone.View.extend({
    el: '#toEdit',
    collection: musicList,
    addOne: function(thisModel) {
	var musicView = new MusicView({ model: thisModel });
	this.$el.append(musicView.render().el);
    },
    addAll: function() {
	this.collection.forEach(this.addOne, this);
    },
    render: function() {
	this.addAll();
    }
});

var musicApp = new (Backbone.Router.extend({
    routes: { '': 'index' },
    initialize: function(){
	this.musicListView = new MusicListView({});
	this.musicFormView = new MusicFormView({});
    },
    start: function(){
	Backbone.history.start({ pushState: true });
    },
    index: function(){
	this.musicListView.render();
    }
}));

$(function(){
    musicApp.initialize();
    musicApp.start();
});
<commit_msg>main.js: make the form-submit addOne()<commit_after>var MusicModel = Backbone.Model.extend({});
var MusicList = Backbone.Collection.extend({ model: MusicModel });

musicList = new MusicList({});
musicList.reset([
    {
	num: 1,
	title: 'Setting Forth',
	album: 'Into the Wild',
	artist: 'Eddie Vedder'
    },
    {
	num: 2,
	title: 'No Ceiling',
	album: 'Into the Wild',
	artist: 'Eddie Vedder'
    }
]);

var MusicView = Backbone.View.extend({
    tagName: 'div',
    className: 'music entry',
    initialize: function(){
	this.template = _.template('<%= num %> | <%= title %> | <%= album %> | <%= artist %>');
    },
    render: function(){
	this.$el.html(this.template(this.model.attributes));
	return this;
    }
});

var MusicFormView = Backbone.View.extend({
    el: 'div.wrapper',
    initialize: function(){
	this.musicListView = new MusicListView({});
    },
    events: {
	'submit #musicform': 'submit'
    },
    submit: function(event){
	/* Post to the server */
	$.post($('#musicform').attr('action'),
	       $('#musicform').serialize())
	    .done(function(data){
		console.log(data);
	    });

	/* Update the DOM */
	thisModel = new MusicModel($('#musicform').serializeObject());
	this.musicListView.addOne(thisModel);
	return false;
    }
});

var MusicListView = Backbone.View.extend({
    el: '#toEdit',
    collection: musicList,
    addOne: function(thisModel) {
	var musicView = new MusicView({ model: thisModel });
	this.$el.append(musicView.render().el);
    },
    addAll: function() {
	this.collection.forEach(this.addOne, this);
    },
    render: function() {
	this.addAll();
    }
});

var musicApp = new (Backbone.Router.extend({
    routes: { '': 'index' },
    initialize: function(){
	this.musicListView = new MusicListView({});
	this.musicFormView = new MusicFormView({});
    },
    start: function(){
	Backbone.history.start({ pushState: true });
    },
    index: function(){
	this.musicListView.render();
    }
}));

$(function(){
    musicApp.initialize();
    musicApp.start();
});
<|endoftext|>


<commit_before>'use strict'

const assert = require('assert')
const rmrf = require('rimraf')
const IPFSRepo = require('ipfs-repo')
const DatastoreLevel = require('datastore-level')
const Keystore = require('orbit-db-keystore')
const Log = require('../src/log.js')

const apis = [require('ipfs')]

const dataDir = './ipfs/tests/log'

const repoConf = {
  storageBackends: {
    blocks: DatastoreLevel,
  },
}

const ipfsConf = {
  repo: new IPFSRepo(dataDir, repoConf),
  EXPERIMENTAL: {
    pubsub: true,
    dht: false,
    sharding: false,
  },
}

let ipfs, key1, key2, key3

const last = (arr) => {
  return arr[arr.length - 1]
}

apis.forEach((IPFS) => {
  describe('Signed Log', function() {
    this.timeout(10000)

    const keystore = Keystore.create('./test/fixtures/keystore')

    before((done) => {
      rmrf.sync(dataDir)
      key1 = keystore.getKey('A')
      key2 = keystore.getKey('B')
      key3 = keystore.getKey('C')
      ipfs = new IPFS(ipfsConf)
      ipfs.keystore = keystore
      ipfs.on('error', done)
      ipfs.on('ready', () => done())
    })

    after(async () => {
      if (ipfs)
        await ipfs.stop()
    })

    it('creates a signed log', () => {
      const log = new Log(ipfs, 'A', null, null, null, key1)
      assert.notEqual(log.id, null)
      assert.deepEqual(log._key, key1)
      assert.deepEqual(log._keys, [])
    })

    it('takes an array of write-access public keys as an argument', () => {
      const log = new Log(ipfs, 'A', null, null, null, key1, [key2.getPublic('hex'), key3.getPublic('hex')])
      assert.notEqual(log.id, null)
      assert.deepEqual(log._key, key1)
      assert.deepEqual(log._keys, [key2.getPublic('hex'), key3.getPublic('hex')])
    })

    it('takes a single write-access public key as an argument', () => {
      const log = new Log(ipfs, 'A', null, null, null, key1, key2.getPublic('hex'))
      assert.notEqual(log.id, null)
      assert.deepEqual(log._key, key1)
      assert.deepEqual(log._keys, [key2.getPublic('hex')])
    })

    it('entries contain a signature and a public signing key', async () => {
      const log = new Log(ipfs, 'A', null, null, null, key1, [key1.getPublic('hex')])
      await log.append('one')
      assert.notEqual(log.values[0].sig, null)
      assert.equal(log.values[0].key, key1.getPublic('hex'))
    })

    it('doesn\'t sign entries when key is not defined', async () => {
      const log = new Log(ipfs, 'A')
      await log.append('one')
      assert.equal(log.values[0].sig, null)
      assert.equal(log.values[0].key, null)
    })

    it('allows only the owner to write when write-access keys are defined', async () => {
      const log1 = new Log(ipfs, 'A', null, null, null, key1, [key1.getPublic('hex')])
      const log2 = new Log(ipfs, 'B', null, null, null, key2)

      let err
      try {
        await log1.append('one')
        await log2.append('two')
        await log1.join(log2)
      } catch (e) {
        err = e.toString()
      }
      assert.equal(err, 'Error: Not allowed to write')
    })

    it('allows only the specified keys to write when write-access keys are defined', async () => {
      const log1 = new Log(ipfs, 'A', null, null, null, key1, [key1.getPublic('hex'), key2.getPublic('hex')])
      const log2 = new Log(ipfs, 'A', null, null, null, key2, [key1.getPublic('hex'), key2.getPublic('hex')])

      let err
      try {
        await log1.append('one')
        await log2.append('two')
        await log1.join(log2)
      } catch (e) {
        err = e.toString()
        throw e
      }
      assert.equal(err, null)
      assert.equal(log1.id, 'A')
      assert.equal(log1.values.length, 2)
      assert.equal(log1.values[0].payload, 'one')
      assert.equal(log1.values[1].payload, 'two')
    })

    it('allows others than the owner to write', async () => {
      const log1 = new Log(ipfs, 'A', null, null, null, key1, [key2.getPublic('hex')])
      const log2 = new Log(ipfs, 'A', null, null, null, key2, [key2.getPublic('hex')])

      let err
      try {
        await log2.append('one')
        await log2.append('two')
        await log1.join(log2)
      } catch (e) {
        err = e.toString()
        throw e
      }
      assert.equal(err, null)
      assert.equal(log1.id, 'A')
      assert.equal(log1.values.length, 2)
      assert.equal(log1.values[0].payload, 'one')
      assert.equal(log1.values[1].payload, 'two')
    })

    it('allows anyone to write', async () => {
      const log1 = new Log(ipfs, 'A', null, null, null, key1, ['*'])
      const log2 = new Log(ipfs, 'A', null, null, null, key2, ['*'])

      let err
      try {
        await log2.append('one')
        await log2.append('two')
        await log1.join(log2)
      } catch (e) {
        err = e.toString()
        throw e
      }
      assert.equal(err, null)
      assert.equal(log1.id, 'A')
      assert.equal(log1.values.length, 2)
      assert.equal(log1.values[0].payload, 'one')
      assert.equal(log1.values[1].payload, 'two')
    })

    it('doesn\'t join logs with different IDs ', async () => {
      const log1 = new Log(ipfs, 'A', null, null, null, key1, ['*'])
      const log2 = new Log(ipfs, 'B', null, null, null, key1, ['*'])

      let err
      try {
        await log1.append('one')
        await log2.append('two')
        await log2.append('three')
        await log1.join(log2)
      } catch (e) {
        err = e.toString()
        throw e
      }
      assert.equal(err, null)
      assert.equal(log1.id, 'A')
      assert.equal(log1.values.length, 1)
      assert.equal(log1.values[0].payload, 'one')
    })

    it('doesn\'t allows the owner to write if write-keys defines non-owner key', async () => {
      const log1 = new Log(ipfs, 'A', null, null, null, key1, [key2.getPublic('hex')])

      let err
      try {
        await log1.append('one')
      } catch (e) {
        err = e.toString()
      }
      assert.equal(err, 'Error: Not allowed to write')
    })

    it('allows nobody to write when write-access keys are not defined', async () => {
      const log1 = new Log(ipfs, 'A', null, null, null, key1, [])

      let err
      try {
        await log1.append('one')
      } catch (e) {
        err = e.toString()
      }
      assert.equal(err.toString(), 'Error: Not allowed to write')
    })

    it('throws an error if log is signed but trying to merge with an entry that doesn\'t have public signing key', async () => {
      const log1 = new Log(ipfs, 'A', null, null, null, key1, [key1.getPublic('hex'), key2.getPublic('hex')])
      const log2 = new Log(ipfs, 'A', null, null, null, key2, [key1.getPublic('hex'), key2.getPublic('hex')])

      let err
      try {
        await log1.append('one')
        await log2.append('two')
        delete log2.values[0].key
        await log1.join(log2)
      } catch (e) {
        err = e.toString()
      }
      assert.equal(err, 'Error: Entry doesn\'t have a public key')
    })

    it('throws an error if log is signed but trying to merge an entry that doesn\'t have a signature', async () => {
      const log1 = new Log(ipfs, 'A', null, null, null, key1, [key1.getPublic('hex'), key2.getPublic('hex')])
      const log2 = new Log(ipfs, 'A', null, null, null, key2, [key1.getPublic('hex'), key2.getPublic('hex')])

      let err
      try {
        await log1.append('one')
        await log2.append('two')
        delete log2.values[0].sig
        await log1.join(log2)
      } catch (e) {
        err = e.toString()
      }
      assert.equal(err, 'Error: Entry doesn\'t have a signature')
    })

    it('throws an error if log is signed but the signature doesn\'t verify', async () => {

      const replaceAt = (str, index, replacement) => {
        return str.substr(0, index) + replacement+ str.substr(index + replacement.length)
      }

      const log1 = new Log(ipfs, 'A', null, null, null, key1, [key1.getPublic('hex'), key2.getPublic('hex')])
      const log2 = new Log(ipfs, 'A', null, null, null, key2, [key1.getPublic('hex'), key2.getPublic('hex')])
      let err

      try {
        await log1.append('one')
        await log2.append('two')
        log2.values[0].sig = replaceAt(log2.values[0].sig, 0, 'X')
        await log1.join(log2)
      } catch (e) {
        err = e.toString()
      }
      assert.equal(err, `Error: Invalid signature in entry '${log2.values[0].hash}'`)
      assert.equal(log1.values.length, 1)
      assert.equal(log1.values[0].payload, 'one')
    })

    it('throws an error if log is signed but the signature is valid and doesn\'t verify', async () => {

      const log1 = new Log(ipfs, 'A', null, null, null, key1, [key1.getPublic('hex'), key2.getPublic('hex')])
      const log2 = new Log(ipfs, 'A', null, null, null, key2, [key1.getPublic('hex'), key2.getPublic('hex')])
      let err

      await log1.append('one')
      await log2.append('two')
      console.log("Sig is:", log2.values[0].sig)
      log2.values[0].sig = { r: "0".repeat(64), s: "0".repeat(64) }
      await log1.join(log2)

      assert.equal(log1.values.length, 1)
      assert.equal(log1.values[0].payload, 'one')
    })
  })
})
<commit_msg>Removed debug message<commit_after>'use strict'

const assert = require('assert')
const rmrf = require('rimraf')
const IPFSRepo = require('ipfs-repo')
const DatastoreLevel = require('datastore-level')
const Keystore = require('orbit-db-keystore')
const Log = require('../src/log.js')

const apis = [require('ipfs')]

const dataDir = './ipfs/tests/log'

const repoConf = {
  storageBackends: {
    blocks: DatastoreLevel,
  },
}

const ipfsConf = {
  repo: new IPFSRepo(dataDir, repoConf),
  EXPERIMENTAL: {
    pubsub: true,
    dht: false,
    sharding: false,
  },
}

let ipfs, key1, key2, key3

const last = (arr) => {
  return arr[arr.length - 1]
}

apis.forEach((IPFS) => {
  describe('Signed Log', function() {
    this.timeout(10000)

    const keystore = Keystore.create('./test/fixtures/keystore')

    before((done) => {
      rmrf.sync(dataDir)
      key1 = keystore.getKey('A')
      key2 = keystore.getKey('B')
      key3 = keystore.getKey('C')
      ipfs = new IPFS(ipfsConf)
      ipfs.keystore = keystore
      ipfs.on('error', done)
      ipfs.on('ready', () => done())
    })

    after(async () => {
      if (ipfs)
        await ipfs.stop()
    })

    it('creates a signed log', () => {
      const log = new Log(ipfs, 'A', null, null, null, key1)
      assert.notEqual(log.id, null)
      assert.deepEqual(log._key, key1)
      assert.deepEqual(log._keys, [])
    })

    it('takes an array of write-access public keys as an argument', () => {
      const log = new Log(ipfs, 'A', null, null, null, key1, [key2.getPublic('hex'), key3.getPublic('hex')])
      assert.notEqual(log.id, null)
      assert.deepEqual(log._key, key1)
      assert.deepEqual(log._keys, [key2.getPublic('hex'), key3.getPublic('hex')])
    })

    it('takes a single write-access public key as an argument', () => {
      const log = new Log(ipfs, 'A', null, null, null, key1, key2.getPublic('hex'))
      assert.notEqual(log.id, null)
      assert.deepEqual(log._key, key1)
      assert.deepEqual(log._keys, [key2.getPublic('hex')])
    })

    it('entries contain a signature and a public signing key', async () => {
      const log = new Log(ipfs, 'A', null, null, null, key1, [key1.getPublic('hex')])
      await log.append('one')
      assert.notEqual(log.values[0].sig, null)
      assert.equal(log.values[0].key, key1.getPublic('hex'))
    })

    it('doesn\'t sign entries when key is not defined', async () => {
      const log = new Log(ipfs, 'A')
      await log.append('one')
      assert.equal(log.values[0].sig, null)
      assert.equal(log.values[0].key, null)
    })

    it('allows only the owner to write when write-access keys are defined', async () => {
      const log1 = new Log(ipfs, 'A', null, null, null, key1, [key1.getPublic('hex')])
      const log2 = new Log(ipfs, 'B', null, null, null, key2)

      let err
      try {
        await log1.append('one')
        await log2.append('two')
        await log1.join(log2)
      } catch (e) {
        err = e.toString()
      }
      assert.equal(err, 'Error: Not allowed to write')
    })

    it('allows only the specified keys to write when write-access keys are defined', async () => {
      const log1 = new Log(ipfs, 'A', null, null, null, key1, [key1.getPublic('hex'), key2.getPublic('hex')])
      const log2 = new Log(ipfs, 'A', null, null, null, key2, [key1.getPublic('hex'), key2.getPublic('hex')])

      let err
      try {
        await log1.append('one')
        await log2.append('two')
        await log1.join(log2)
      } catch (e) {
        err = e.toString()
        throw e
      }
      assert.equal(err, null)
      assert.equal(log1.id, 'A')
      assert.equal(log1.values.length, 2)
      assert.equal(log1.values[0].payload, 'one')
      assert.equal(log1.values[1].payload, 'two')
    })

    it('allows others than the owner to write', async () => {
      const log1 = new Log(ipfs, 'A', null, null, null, key1, [key2.getPublic('hex')])
      const log2 = new Log(ipfs, 'A', null, null, null, key2, [key2.getPublic('hex')])

      let err
      try {
        await log2.append('one')
        await log2.append('two')
        await log1.join(log2)
      } catch (e) {
        err = e.toString()
        throw e
      }
      assert.equal(err, null)
      assert.equal(log1.id, 'A')
      assert.equal(log1.values.length, 2)
      assert.equal(log1.values[0].payload, 'one')
      assert.equal(log1.values[1].payload, 'two')
    })

    it('allows anyone to write', async () => {
      const log1 = new Log(ipfs, 'A', null, null, null, key1, ['*'])
      const log2 = new Log(ipfs, 'A', null, null, null, key2, ['*'])

      let err
      try {
        await log2.append('one')
        await log2.append('two')
        await log1.join(log2)
      } catch (e) {
        err = e.toString()
        throw e
      }
      assert.equal(err, null)
      assert.equal(log1.id, 'A')
      assert.equal(log1.values.length, 2)
      assert.equal(log1.values[0].payload, 'one')
      assert.equal(log1.values[1].payload, 'two')
    })

    it('doesn\'t join logs with different IDs ', async () => {
      const log1 = new Log(ipfs, 'A', null, null, null, key1, ['*'])
      const log2 = new Log(ipfs, 'B', null, null, null, key1, ['*'])

      let err
      try {
        await log1.append('one')
        await log2.append('two')
        await log2.append('three')
        await log1.join(log2)
      } catch (e) {
        err = e.toString()
        throw e
      }
      assert.equal(err, null)
      assert.equal(log1.id, 'A')
      assert.equal(log1.values.length, 1)
      assert.equal(log1.values[0].payload, 'one')
    })

    it('doesn\'t allows the owner to write if write-keys defines non-owner key', async () => {
      const log1 = new Log(ipfs, 'A', null, null, null, key1, [key2.getPublic('hex')])

      let err
      try {
        await log1.append('one')
      } catch (e) {
        err = e.toString()
      }
      assert.equal(err, 'Error: Not allowed to write')
    })

    it('allows nobody to write when write-access keys are not defined', async () => {
      const log1 = new Log(ipfs, 'A', null, null, null, key1, [])

      let err
      try {
        await log1.append('one')
      } catch (e) {
        err = e.toString()
      }
      assert.equal(err.toString(), 'Error: Not allowed to write')
    })

    it('throws an error if log is signed but trying to merge with an entry that doesn\'t have public signing key', async () => {
      const log1 = new Log(ipfs, 'A', null, null, null, key1, [key1.getPublic('hex'), key2.getPublic('hex')])
      const log2 = new Log(ipfs, 'A', null, null, null, key2, [key1.getPublic('hex'), key2.getPublic('hex')])

      let err
      try {
        await log1.append('one')
        await log2.append('two')
        delete log2.values[0].key
        await log1.join(log2)
      } catch (e) {
        err = e.toString()
      }
      assert.equal(err, 'Error: Entry doesn\'t have a public key')
    })

    it('throws an error if log is signed but trying to merge an entry that doesn\'t have a signature', async () => {
      const log1 = new Log(ipfs, 'A', null, null, null, key1, [key1.getPublic('hex'), key2.getPublic('hex')])
      const log2 = new Log(ipfs, 'A', null, null, null, key2, [key1.getPublic('hex'), key2.getPublic('hex')])

      let err
      try {
        await log1.append('one')
        await log2.append('two')
        delete log2.values[0].sig
        await log1.join(log2)
      } catch (e) {
        err = e.toString()
      }
      assert.equal(err, 'Error: Entry doesn\'t have a signature')
    })

    it('throws an error if log is signed but the signature doesn\'t verify', async () => {

      const replaceAt = (str, index, replacement) => {
        return str.substr(0, index) + replacement+ str.substr(index + replacement.length)
      }

      const log1 = new Log(ipfs, 'A', null, null, null, key1, [key1.getPublic('hex'), key2.getPublic('hex')])
      const log2 = new Log(ipfs, 'A', null, null, null, key2, [key1.getPublic('hex'), key2.getPublic('hex')])
      let err

      try {
        await log1.append('one')
        await log2.append('two')
        log2.values[0].sig = replaceAt(log2.values[0].sig, 0, 'X')
        await log1.join(log2)
      } catch (e) {
        err = e.toString()
      }
      assert.equal(err, `Error: Invalid signature in entry '${log2.values[0].hash}'`)
      assert.equal(log1.values.length, 1)
      assert.equal(log1.values[0].payload, 'one')
    })

    it('throws an error if log is signed but the signature is valid and doesn\'t verify', async () => {
      const log1 = new Log(ipfs, 'A', null, null, null, key1, [key1.getPublic('hex'), key2.getPublic('hex')])
      const log2 = new Log(ipfs, 'A', null, null, null, key2, [key1.getPublic('hex'), key2.getPublic('hex')])
      let err

      await log1.append('one')
      await log2.append('two')
      log2.values[0].sig = { r: "0".repeat(64), s: "0".repeat(64) }
      await log1.join(log2)

      assert.equal(log1.values.length, 1)
      assert.equal(log1.values[0].payload, 'one')
    })
  })
})
<|endoftext|>


<commit_before>var _ = require('highland');
var R = require('ramda');
var input = require('./input.js');
var gun = require('./gun.js')
var platforms, player, map, layer;
var width, height, lastTime;
var bullets;

var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update });

function preload() {

  game.load.tilemap('map', '../resources/maps/test.json', null, Phaser.Tilemap.TILED_JSON);
  game.load.spritesheet('tiles', '../resources/tiles.png', 32, 32);

  game.load.image('star', '../resources/star.png');
  game.load.spritesheet('player', '../resources/player.png', 72, 72);
  game.load.image('bullet', '../resources/pl-bullet.png');
}

function create() {
  game.stage.backgroundColor = '#3399FF';
  game.physics.startSystem(Phaser.Physics.ARCADE);

  map = game.add.tilemap('map');
  map.addTilesetImage('tiles');
  layer = map.createLayer('Tile Layer 1');
  map.setCollisionBetween(1, 6);
  layer.resizeWorld();

  layer.enableBody = true;

  player = game.add.sprite(200, game.world.height - 400, 'player');
  game.physics.arcade.enable(player);
  player.body.bounce.y = 0.2;
  player.body.gravity.y = 700;
  player.body.collideWorldBounds = true;
  player.animations.add('walk', [0, 1, 2, 3, 4], 10, true);
  player.anchor.setTo(0.5, 0.5)
  game.camera.follow(player);

  bullets = game.add.group();
  bullets.enableBody = true;

  input().each(function(state){
    if (state.left){
      player.body.velocity.x = -150;
      player.scale.x = -1
      player.animations.play('walk');
    } else if (state.right){
      player.body.velocity.x = 150;
      player.scale.x = 1
      player.animations.play('walk');
    } else {
      player.body.velocity.x = 0;
      player.animations.stop();
      player.frame = 0;
    }

    if (state.space) {
      gun.switchType();
    }

    if(state.mousedown) {
      gun.startCharging(game)
    } else if(state.mouseup) {
      gun.fire(game, bullets, player, state.x, state.y)
    }

    if (state.up && player.body.onFloor()){
        player.body.velocity.y = -350;
    }
  })
}

function update() {
  game.physics.arcade.collide(player, layer);
  game.physics.arcade.collide(bullets, layer, function(bullet, tile) {
    bullet.destroy();
  });
  // for(i = 0; i < bullets.length; i++) {
  //   var preCollisionVelocityX;
  //   var preCollisionVelocityY;
  //   game.physics.arcade.collide(bullets[i], layer, function(bullet, tile) {
  //     // Some really shitty inference to work out what way we should bounce
  //     console.log("Hello")
  //     orig_x = bullet.x
  //     orig_y = bullet.y

  //     bullet.x = orig_x - 1
  //     if(game.physics.arcade.overlap(bullet, tile)) {
  //       bullet.body.velocity.x = -preCollisionVelocityX;
  //     } else {
  //       bullet.x = orig_x + 1
  //       if(game.physics.arcade.overlap(bullet, tile)) {
  //         bullet.body.velocity.x = -preCollisionVelocityX
  //       } else {
  //         bullet.body.velocity.y = -preCollisionVelocityY
  //       }
  //     }

  //     bullet.x = orig_x
  //     bullet.y = orig_y
  //   }, function(bullet, tile) {
  //     preCollisionVelocityX = bullet.body.velocity.x;
  //     preCollisionVelocityY = bullet.body.velocity.y;
  //     return true;
  //   });
  // }
}
<commit_msg>Save all the destruction to the end of update, fix error being thrown from phaser.js<commit_after>var _ = require('highland');
var R = require('ramda');
var input = require('./input.js');
var gun = require('./gun.js')
var platforms, player, map, layer;
var width, height, lastTime;
var bullets;

var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update });

function preload() {

  game.load.tilemap('map', '../resources/maps/test.json', null, Phaser.Tilemap.TILED_JSON);
  game.load.spritesheet('tiles', '../resources/tiles.png', 32, 32);

  game.load.image('star', '../resources/star.png');
  game.load.spritesheet('player', '../resources/player.png', 72, 72);
  game.load.image('bullet', '../resources/pl-bullet.png');
}

function create() {
  game.stage.backgroundColor = '#3399FF';
  game.physics.startSystem(Phaser.Physics.ARCADE);

  map = game.add.tilemap('map');
  map.addTilesetImage('tiles');
  layer = map.createLayer('Tile Layer 1');
  map.setCollisionBetween(1, 6);
  layer.resizeWorld();

  layer.enableBody = true;

  player = game.add.sprite(200, game.world.height - 400, 'player');
  game.physics.arcade.enable(player);
  player.body.bounce.y = 0.2;
  player.body.gravity.y = 700;
  player.body.collideWorldBounds = true;
  player.animations.add('walk', [0, 1, 2, 3, 4], 10, true);
  player.anchor.setTo(0.5, 0.5)
  game.camera.follow(player);

  bullets = game.add.group();
  bullets.enableBody = true;

  input().each(function(state){
    if (state.left){
      player.body.velocity.x = -150;
      player.scale.x = -1
      player.animations.play('walk');
    } else if (state.right){
      player.body.velocity.x = 150;
      player.scale.x = 1
      player.animations.play('walk');
    } else {
      player.body.velocity.x = 0;
      player.animations.stop();
      player.frame = 0;
    }

    if (state.space) {
      gun.switchType();
    }

    if(state.mousedown) {
      gun.startCharging(game)
    } else if(state.mouseup) {
      gun.fire(game, bullets, player, state.x, state.y)
    }

    if (state.up && player.body.onFloor()){
        player.body.velocity.y = -350;
    }
  })
}

function update() {
  game.physics.arcade.collide(player, layer);

  var thingsToDestroy = [];
  game.physics.arcade.collide(bullets, layer, function(bullet, tile) {
    thingsToDestroy.push(bullet);
  });

  for(i = 0; i < thingsToDestroy.length; i++) {
    thingsToDestroy[i].destroy();
  }

  // for(i = 0; i < bullets.length; i++) {
  //   var preCollisionVelocityX;
  //   var preCollisionVelocityY;
  //   game.physics.arcade.collide(bullets[i], layer, function(bullet, tile) {
  //     // Some really shitty inference to work out what way we should bounce
  //     console.log("Hello")
  //     orig_x = bullet.x
  //     orig_y = bullet.y

  //     bullet.x = orig_x - 1
  //     if(game.physics.arcade.overlap(bullet, tile)) {
  //       bullet.body.velocity.x = -preCollisionVelocityX;
  //     } else {
  //       bullet.x = orig_x + 1
  //       if(game.physics.arcade.overlap(bullet, tile)) {
  //         bullet.body.velocity.x = -preCollisionVelocityX
  //       } else {
  //         bullet.body.velocity.y = -preCollisionVelocityY
  //       }
  //     }

  //     bullet.x = orig_x
  //     bullet.y = orig_y
  //   }, function(bullet, tile) {
  //     preCollisionVelocityX = bullet.body.velocity.x;
  //     preCollisionVelocityY = bullet.body.velocity.y;
  //     return true;
  //   });
  // }
}
<|endoftext|>