<commit_before>
$(document).ready(function(){

  var canvas = $('#canvas')[0];
  var ctx = canvas.getContext('2d');
  var raf;

  var paddle = new Paddle()
  paddle.drawPaddle = function() {
    ctx.fillRect(this.x,this.y,this.width,this.height);
    ctx.fillStyle = "red";
  }

  var ball = new Ball()
  ball.drawBall = function(){
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2, true);
    ctx.closePath();
    ctx.fillStyle = this.color;
    ctx.fill();
  }

  var move = function(){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ball.drawBall()
    paddle.drawPaddle()
    ball.x += ball.velocityX;
    ball.y += ball.velocityY;
    raf = window.requestAnimationFrame(move);

    if (ball.y + ball.velocityY > canvas.height || ball.y + ball.velocityY < 0) {
      ball.velocityY = -ball.velocityY;
    }
    if (ball.x + ball.velocityX > canvas.width || ball.x + ball.velocityX < 0) {
      ball.velocityX = -ball.velocityX;
    }

    if (ball.y > canvas.height - 30 ){
      if (ball.x > paddle.surfaceRange()[0] && ball.x < paddle.surfaceRange()[1]){
        console.log('hit');
        ball.velocityY = -ball.velocityY;
      };
    }

  }

  $(document).keydown(function(event){

    if(event.which == 37){ // move paddle left
      if(paddle.leftPaddleBoudary()){
        return paddle.x -= 10;
      } else {
        console.log('Reached left boundary')
      }

    }
    if(event.which == 39){ // move paddle right
      if(paddle.rightPaddleBoudary()){ //if paddle has reached the edge of the game screen, allow no further movement
        paddle.x += 10;
      } else {
        console.log('Reached right boundary')
      }
    }
  });

  raf = window.requestAnimationFrame(move);

  // $('#canvas').on('mouseover', function(event){
  //   console.log('enter');
  //   // raf = window.requestAnimationFrame(move);
  // });

  // $('#canvas').on('mouseout', function(event){
  //   console.log('exit');
  //   window.cancelAnimationFrame(raf);
  // });

});
<commit_msg>Remove unused code<commit_after>
$(document).ready(function(){

  var canvas = $('#canvas')[0];
  var ctx = canvas.getContext('2d');
  var raf;

  var paddle = new Paddle()
  paddle.drawPaddle = function() {
    ctx.fillRect(this.x,this.y,this.width,this.height);
    ctx.fillStyle = "red";
  }

  var ball = new Ball()
  ball.drawBall = function(){
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2, true);
    ctx.closePath();
    ctx.fillStyle = this.color;
    ctx.fill();
  }

  var move = function(){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ball.drawBall()
    paddle.drawPaddle()
    ball.x += ball.velocityX;
    ball.y += ball.velocityY;
    raf = window.requestAnimationFrame(move);

    if (ball.y + ball.velocityY > canvas.height || ball.y + ball.velocityY < 0) {
      ball.velocityY = -ball.velocityY;
    }
    if (ball.x + ball.velocityX > canvas.width || ball.x + ball.velocityX < 0) {
      ball.velocityX = -ball.velocityX;
    }

    if (ball.y > canvas.height - 30 ){
      if (ball.x > paddle.surfaceRange()[0] && ball.x < paddle.surfaceRange()[1]){
        console.log('hit');
        ball.velocityY = -ball.velocityY;
      };
    }

  }

  $(document).keydown(function(event){

    if(event.which == 37){ // move paddle left
      if(paddle.leftPaddleBoudary()){
        return paddle.x -= 10;
      } else {
        console.log('Reached left boundary')
      }

    }
    if(event.which == 39){ // move paddle right
      if(paddle.rightPaddleBoudary()){ //if paddle has reached the edge of the game screen, allow no further movement
        paddle.x += 10;
      } else {
        console.log('Reached right boundary')
      }
    }
  });

  raf = window.requestAnimationFrame(move);

});
<|endoftext|>


<commit_before>'use strict';

var yeoman = require('yeoman-generator');
var helpers = require('yeoman-test');
var assert = require('yeoman-assert');
var path = require('path');
var yaml = require('yamljs');
var expect = require('expect');

describe('Replication Controller without Ingress scenarios', function () {

    beforeEach(function () {
        return helpers.run(path.join(__dirname, '../generators/app'))
            .withPrompts({
                name: 'nginx',
                namespace: 'default',
                podControllerType: 'Replication Controller',
                image: 'nginx',
                replicas: 1,
                containerPort: 80,
                servicePort: 8080,
                shouldExpose: false
            });
    });

    it('File rc.yml is generated and filled in', function () {
        assert.file(['rc.yml']);
        var rc = yaml.load('rc.yml');
        assert.equal(rc.apiVersion, 'v1');
        assert.equal(rc.kind, 'ReplicationController');
        assert.equal(rc.metadata.name, 'nginx');
        assert.equal(rc.metadata.namespace, 'default');
        assert.equal(rc.spec.replicas, 1);
        assert.equal(rc.spec.selector.app, 'nginx');
        assert.equal(rc.spec.template.metadata.labels.app, 'nginx');
        assert.equal(rc.spec.template.spec.containers[0].name, 'nginx');
        assert.equal(rc.spec.template.spec.containers[0].image, 'nginx');
    });

    it('File svc.yml is generated and filled in', function () {
        assert.file(['svc.yml']);
        var svc = yaml.load('svc.yml');
        assert.equal(svc.apiVersion, 'v1');
        assert.equal(svc.kind, 'Service');
        assert.equal(svc.metadata.name, 'nginx');
        assert.equal(svc.metadata.namespace, 'default');
        assert.equal(svc.spec.ports[0].port, 8080);
        assert.equal(svc.spec.ports[0].targetPort, 80);
        assert.equal(svc.spec.selector.app, 'nginx');
    });

    it('File ing.yml is not generated', function () {
        assert.noFile(['ing.yml']);
    });

    it('File deployment.yml is not generated', function () {
        assert.noFile(['deployment.yml']);
    });

});

describe('Replication Controller with Ingress scenarios', function () {

    beforeEach(function () {
        return helpers.run(path.join(__dirname, '../generators/app'))
            .withPrompts({
                name: 'nginx',
                namespace: 'default',
                podControllerType: 'Replication Controller',
                image: 'nginx',
                replicas: 1,
                containerPort: 80,
                servicePort: 80,
                shouldExpose: 'yes',
                host: 'nginx.ingress.com',
                path: '/',
                ingressPort: 80
            });
    });

    it('File rc.yml is generated and filled in', function () {
        assert.file(['rc.yml']);
        var rc = yaml.load('rc.yml');
        assert.equal(rc.apiVersion, 'v1');
        assert.equal(rc.kind, 'ReplicationController');
        assert.equal(rc.metadata.name, 'nginx');
        assert.equal(rc.metadata.namespace, 'default');
        assert.equal(rc.spec.replicas, 1);
        assert.equal(rc.spec.selector.app, 'nginx');
        assert.equal(rc.spec.template.metadata.labels.app, 'nginx');
        assert.equal(rc.spec.template.spec.containers[0].name, 'nginx');
        assert.equal(rc.spec.template.spec.containers[0].image, 'nginx');
    });

    it('File svc.yml is generated and filled in', function () {
        assert.file(['svc.yml']);
        var svc = yaml.load('svc.yml');
        assert.equal(svc.apiVersion, 'v1');
        assert.equal(svc.kind, 'Service');
        assert.equal(svc.metadata.name, 'nginx');
        assert.equal(svc.metadata.namespace, 'default');
        assert.equal(svc.spec.ports[0].port, 80);
        assert.equal(svc.spec.ports[0].targetPort, 80);
        assert.equal(svc.spec.selector.app, 'nginx');
    });

    it('File ing.yml is generated and filled in', function () {
        assert.file(['ing.yml']);
        var ing = yaml.load('ing.yml');
        expect(ing.apiVersion).toBe('extensions/v1beta1');
        expect(ing.kind).toBe('Ingress');
        expect(ing.metadata.name).toBe('nginx');
        expect(ing.metadata.namespace).toBe('default');
        expect(ing.spec.rules).toExist('Expected rules to exist');
        expect(ing.spec.rules[0].host).toBe('nginx.ingress.com');
        expect(ing.spec.rules[0].http.paths[0].path).toBe('/');
        expect(ing.spec.rules[0].http.paths[0].backend.serviceName).toBe('nginx');
        expect(ing.spec.rules[0].http.paths[0].backend.servicePort).toBe(80);
    });

    it('File deployment.yml is not generated', function () {
        assert.noFile(['deployment.yml']);
    });

});

describe('Deployment without Ingress scenarios', function () {

    beforeEach(function () {
        return helpers.run(path.join(__dirname, '../generators/app'))
            .withPrompts({
                name: 'nginx',
                namespace: 'default',
                podControllerType: 'Deployment',
                image: 'nginx',
                replicas: 1,
                containerPort: 80,
                servicePort: 8080,
                shouldExpose: false
            });
    });

    it('File rc.yml is not generated', function () {
        assert.noFile(['rc.yml']);
    });

    it('File svc.yml is generated and filled in', function () {
        assert.file(['svc.yml']);
        var svc = yaml.load('svc.yml');
        assert.equal(svc.apiVersion, 'v1');
        assert.equal(svc.kind, 'Service');
        assert.equal(svc.metadata.name, 'nginx');
        assert.equal(svc.metadata.namespace, 'default');
        assert.equal(svc.spec.ports[0].port, 8080);
        assert.equal(svc.spec.ports[0].targetPort, 80);
        assert.equal(svc.spec.selector.app, 'nginx');
    });

    it('File ing.yml is not generated', function () {
        assert.noFile(['ing.yml']);
    });

    it('File deployment.yml is generated and filled in', function () {
        assert.file(['deployment.yml']);
        var deployment = yaml.load('deployment.yml');
        assert.equal(deployment.apiVersion, 'extensions/v1beta1');
        assert.equal(deployment.kind, 'Deployment');
        assert.equal(deployment.metadata.labels.name, 'nginx');
        assert.equal(deployment.metadata.name, 'nginx');
        assert.equal(deployment.metadata.namespace, 'default');
        assert.equal(deployment.spec.replicas, 1);
        assert.equal(deployment.spec.template.metadata.labels.app, 'nginx');
        assert.equal(deployment.spec.template.spec.containers[0].name, 'nginx');
        assert.equal(deployment.spec.template.spec.containers[0].image, 'nginx');
    });

});

describe('Deployment with Ingress scenarios', function () {

    beforeEach(function () {
        return helpers.run(path.join(__dirname, '../generators/app'))
            .withPrompts({
                name: 'nginx',
                namespace: 'default',
                podControllerType: 'Deployment',
                image: 'nginx',
                replicas: 1,
                containerPort: 80,
                servicePort: 80,
                shouldExpose: 'yes',
                host: 'nginx.ingress.com',
                path: '/',
                ingressPort: 80
            });
    });

    it('File rc.yml is not generated', function () {
        assert.noFile(['rc.yml']);
    });

    it('File svc.yml is generated and filled in', function () {
        assert.file(['svc.yml']);
        var svc = yaml.load('svc.yml');
        assert.equal(svc.apiVersion, 'v1');
        assert.equal(svc.kind, 'Service');
        assert.equal(svc.metadata.name, 'nginx');
        assert.equal(svc.metadata.namespace, 'default');
        assert.equal(svc.spec.ports[0].port, 80);
        assert.equal(svc.spec.ports[0].targetPort, 80);
        assert.equal(svc.spec.selector.app, 'nginx');
    });

    it('File ing.yml is generated and filled in', function () {
        assert.file(['ing.yml']);
        var ing = yaml.load('ing.yml');
        expect(ing.apiVersion).toBe('extensions/v1beta1');
        expect(ing.kind).toBe('Ingress');
        expect(ing.metadata.name).toBe('nginx');
        expect(ing.metadata.namespace).toBe('default');
        expect(ing.spec.rules).toExist('Expected rules to exist');
        expect(ing.spec.rules[0].host).toBe('nginx.ingress.com');
        expect(ing.spec.rules[0].http.paths[0].path).toBe('/');
        expect(ing.spec.rules[0].http.paths[0].backend.serviceName).toBe('nginx');
        expect(ing.spec.rules[0].http.paths[0].backend.servicePort).toBe(80);
    });

    it('File deployment.yml is generated and filled in', function () {
        assert.file(['deployment.yml']);
        var deployment = yaml.load('deployment.yml');
        assert.equal(deployment.apiVersion, 'extensions/v1beta1');
        assert.equal(deployment.kind, 'Deployment');
        assert.equal(deployment.metadata.labels.name, 'nginx');
        assert.equal(deployment.metadata.name, 'nginx');
        assert.equal(deployment.metadata.namespace, 'default');
        assert.equal(deployment.spec.replicas, 1);
        assert.equal(deployment.spec.template.metadata.labels.app, 'nginx');
        assert.equal(deployment.spec.template.spec.containers[0].name, 'nginx');
        assert.equal(deployment.spec.template.spec.containers[0].image, 'nginx');
    });
});

describe('Invalid podControllerType stops the writing process', function () {

    beforeEach(function () {
        return helpers.run(path.join(__dirname, '../generators/app'))
            .withArguments(['--create'])
            .withPrompts({
                name: 'nginx',
                namespace: 'default',
                podControllerType: 'InvalidType',
                image: 'nginx',
                replicas: 1,
                containerPort: 80,
                servicePort: 80,
                shouldExpose: 'yes',
                host: 'nginx.ingress.com',
                path: '/',
                ingressPort: 80
            });
    });

    it('File rc.yml is not generated', function () {
        assert.noFile(['rc.yml']);
    });

    it('File svc.yml is not generated', function () {
        assert.noFile(['svc.yml']);
    });

    it('File ing.yml is not generated', function () {
        assert.noFile(['ing.yml']);
    });

    it('File deployment.yml is not generated', function () {
        assert.noFile(['deployment.yml']);
    });
});

describe('Spawn create command with Deployment', function () {

    beforeEach(function () {
        return helpers.run(path.join(__dirname, '../generators/app'))
            .withArguments(['--create'])
            .withPrompts({
                name: 'nginx',
                namespace: 'default',
                podControllerType: 'Deployment',
                image: 'nginx',
                replicas: 1,
                containerPort: 80,
                servicePort: 80,
                shouldExpose: 'yes',
                host: 'nginx.ingress.com',
                path: '/',
                ingressPort: 80
            });
    });

    it('File rc.yml is not generated', function () {
        assert.noFile(['rc.yml']);
    });

    it('File svc.yml is generated', function () {
        assert.file(['svc.yml']);
    });

    it('File ing.yml is generated', function () {
        assert.file(['ing.yml']);
    });

    it('File deployment.yml is generated', function () {
        assert.file(['deployment.yml']);
    });
});

describe('Spawn apply command with Deployment', function () {

    beforeEach(function () {
        return helpers.run(path.join(__dirname, '../generators/app'))
            .withArguments(['--apply'])
            .withPrompts({
                name: 'nginx',
                namespace: 'default',
                podControllerType: 'Deployment',
                image: 'nginx',
                replicas: 1,
                containerPort: 80,
                servicePort: 80,
                shouldExpose: 'yes',
                host: 'nginx.ingress.com',
                path: '/',
                ingressPort: 80
            });
    });

    it('File rc.yml is not generated', function () {
        assert.noFile(['rc.yml']);
    });

    it('File svc.yml is generated', function () {
        assert.file(['svc.yml']);
    });

    it('File ing.yml is generated', function () {
        assert.file(['ing.yml']);
    });

    it('File deployment.yml is generated', function () {
        assert.file(['deployment.yml']);
    });
});

describe('Spawn delete command with Deployment', function () {

    beforeEach(function () {
        return helpers.run(path.join(__dirname, '../generators/app'))
            .withArguments(['--delete'])
            .withPrompts({
                name: 'nginx',
                namespace: 'default',
                podControllerType: 'Deployment',
                image: 'nginx',
                replicas: 1,
                containerPort: 80,
                servicePort: 80,
                shouldExpose: 'yes',
                host: 'nginx.ingress.com',
                path: '/',
                ingressPort: 80
            });
    });

    it('File rc.yml is not generated', function () {
        assert.noFile(['rc.yml']);
    });

    it('File svc.yml is not generated', function () {
        assert.noFile(['svc.yml']);
    });

    it('File ing.yml is not generated', function () {
        assert.noFile(['ing.yml']);
    });

    it('File deployment.yml is not generated', function () {
        assert.noFile(['deployment.yml']);
    });
});<commit_msg>Added test to check hostname is not added to yaml when user has not entered any value<commit_after>'use strict';

var yeoman = require('yeoman-generator');
var helpers = require('yeoman-test');
var assert = require('yeoman-assert');
var path = require('path');
var yaml = require('yamljs');
var expect = require('expect');

describe('Replication Controller without Ingress scenarios', function () {

    beforeEach(function () {
        return helpers.run(path.join(__dirname, '../generators/app'))
            .withPrompts({
                name: 'nginx',
                namespace: 'default',
                podControllerType: 'Replication Controller',
                image: 'nginx',
                replicas: 1,
                containerPort: 80,
                servicePort: 8080,
                shouldExpose: false
            });
    });

    it('File rc.yml is generated and filled in', function () {
        assert.file(['rc.yml']);
        var rc = yaml.load('rc.yml');
        assert.equal(rc.apiVersion, 'v1');
        assert.equal(rc.kind, 'ReplicationController');
        assert.equal(rc.metadata.name, 'nginx');
        assert.equal(rc.metadata.namespace, 'default');
        assert.equal(rc.spec.replicas, 1);
        assert.equal(rc.spec.selector.app, 'nginx');
        assert.equal(rc.spec.template.metadata.labels.app, 'nginx');
        assert.equal(rc.spec.template.spec.containers[0].name, 'nginx');
        assert.equal(rc.spec.template.spec.containers[0].image, 'nginx');
    });

    it('File svc.yml is generated and filled in', function () {
        assert.file(['svc.yml']);
        var svc = yaml.load('svc.yml');
        assert.equal(svc.apiVersion, 'v1');
        assert.equal(svc.kind, 'Service');
        assert.equal(svc.metadata.name, 'nginx');
        assert.equal(svc.metadata.namespace, 'default');
        assert.equal(svc.spec.ports[0].port, 8080);
        assert.equal(svc.spec.ports[0].targetPort, 80);
        assert.equal(svc.spec.selector.app, 'nginx');
    });

    it('File ing.yml is not generated', function () {
        assert.noFile(['ing.yml']);
    });

    it('File deployment.yml is not generated', function () {
        assert.noFile(['deployment.yml']);
    });

});

describe('Replication Controller with Ingress scenarios', function () {

    beforeEach(function () {
        return helpers.run(path.join(__dirname, '../generators/app'))
            .withPrompts({
                name: 'nginx',
                namespace: 'default',
                podControllerType: 'Replication Controller',
                image: 'nginx',
                replicas: 1,
                containerPort: 80,
                servicePort: 80,
                shouldExpose: 'yes',
                host: 'nginx.ingress.com',
                path: '/',
                ingressPort: 80
            });
    });

    it('File rc.yml is generated and filled in', function () {
        assert.file(['rc.yml']);
        var rc = yaml.load('rc.yml');
        assert.equal(rc.apiVersion, 'v1');
        assert.equal(rc.kind, 'ReplicationController');
        assert.equal(rc.metadata.name, 'nginx');
        assert.equal(rc.metadata.namespace, 'default');
        assert.equal(rc.spec.replicas, 1);
        assert.equal(rc.spec.selector.app, 'nginx');
        assert.equal(rc.spec.template.metadata.labels.app, 'nginx');
        assert.equal(rc.spec.template.spec.containers[0].name, 'nginx');
        assert.equal(rc.spec.template.spec.containers[0].image, 'nginx');
    });

    it('File svc.yml is generated and filled in', function () {
        assert.file(['svc.yml']);
        var svc = yaml.load('svc.yml');
        assert.equal(svc.apiVersion, 'v1');
        assert.equal(svc.kind, 'Service');
        assert.equal(svc.metadata.name, 'nginx');
        assert.equal(svc.metadata.namespace, 'default');
        assert.equal(svc.spec.ports[0].port, 80);
        assert.equal(svc.spec.ports[0].targetPort, 80);
        assert.equal(svc.spec.selector.app, 'nginx');
    });

    it('File ing.yml is generated and filled in', function () {
        assert.file(['ing.yml']);
        var ing = yaml.load('ing.yml');
        expect(ing.apiVersion).toBe('extensions/v1beta1');
        expect(ing.kind).toBe('Ingress');
        expect(ing.metadata.name).toBe('nginx');
        expect(ing.metadata.namespace).toBe('default');
        expect(ing.spec.rules).toExist('Expected rules to exist');
        expect(ing.spec.rules[0].host).toBe('nginx.ingress.com');
        expect(ing.spec.rules[0].http.paths[0].path).toBe('/');
        expect(ing.spec.rules[0].http.paths[0].backend.serviceName).toBe('nginx');
        expect(ing.spec.rules[0].http.paths[0].backend.servicePort).toBe(80);
    });

    it('File deployment.yml is not generated', function () {
        assert.noFile(['deployment.yml']);
    });

});

describe('Deployment without Ingress scenarios', function () {

    beforeEach(function () {
        return helpers.run(path.join(__dirname, '../generators/app'))
            .withPrompts({
                name: 'nginx',
                namespace: 'default',
                podControllerType: 'Deployment',
                image: 'nginx',
                replicas: 1,
                containerPort: 80,
                servicePort: 8080,
                shouldExpose: false
            });
    });

    it('File rc.yml is not generated', function () {
        assert.noFile(['rc.yml']);
    });

    it('File svc.yml is generated and filled in', function () {
        assert.file(['svc.yml']);
        var svc = yaml.load('svc.yml');
        assert.equal(svc.apiVersion, 'v1');
        assert.equal(svc.kind, 'Service');
        assert.equal(svc.metadata.name, 'nginx');
        assert.equal(svc.metadata.namespace, 'default');
        assert.equal(svc.spec.ports[0].port, 8080);
        assert.equal(svc.spec.ports[0].targetPort, 80);
        assert.equal(svc.spec.selector.app, 'nginx');
    });

    it('File ing.yml is not generated', function () {
        assert.noFile(['ing.yml']);
    });

    it('File deployment.yml is generated and filled in', function () {
        assert.file(['deployment.yml']);
        var deployment = yaml.load('deployment.yml');
        assert.equal(deployment.apiVersion, 'extensions/v1beta1');
        assert.equal(deployment.kind, 'Deployment');
        assert.equal(deployment.metadata.labels.name, 'nginx');
        assert.equal(deployment.metadata.name, 'nginx');
        assert.equal(deployment.metadata.namespace, 'default');
        assert.equal(deployment.spec.replicas, 1);
        assert.equal(deployment.spec.template.metadata.labels.app, 'nginx');
        assert.equal(deployment.spec.template.spec.containers[0].name, 'nginx');
        assert.equal(deployment.spec.template.spec.containers[0].image, 'nginx');
    });

});

describe('Deployment with Ingress scenarios', function () {

    beforeEach(function () {
        return helpers.run(path.join(__dirname, '../generators/app'))
            .withPrompts({
                name: 'nginx',
                namespace: 'default',
                podControllerType: 'Deployment',
                image: 'nginx',
                replicas: 1,
                containerPort: 80,
                servicePort: 80,
                shouldExpose: 'yes',
                host: 'nginx.ingress.com',
                path: '/',
                ingressPort: 80
            });
    });

    it('File rc.yml is not generated', function () {
        assert.noFile(['rc.yml']);
    });

    it('File svc.yml is generated and filled in', function () {
        assert.file(['svc.yml']);
        var svc = yaml.load('svc.yml');
        assert.equal(svc.apiVersion, 'v1');
        assert.equal(svc.kind, 'Service');
        assert.equal(svc.metadata.name, 'nginx');
        assert.equal(svc.metadata.namespace, 'default');
        assert.equal(svc.spec.ports[0].port, 80);
        assert.equal(svc.spec.ports[0].targetPort, 80);
        assert.equal(svc.spec.selector.app, 'nginx');
    });

    it('File ing.yml is generated and filled in', function () {
        assert.file(['ing.yml']);
        var ing = yaml.load('ing.yml');
        expect(ing.apiVersion).toBe('extensions/v1beta1');
        expect(ing.kind).toBe('Ingress');
        expect(ing.metadata.name).toBe('nginx');
        expect(ing.metadata.namespace).toBe('default');
        expect(ing.spec.rules).toExist('Expected rules to exist');
        expect(ing.spec.rules[0].host).toBe('nginx.ingress.com');
        expect(ing.spec.rules[0].http.paths[0].path).toBe('/');
        expect(ing.spec.rules[0].http.paths[0].backend.serviceName).toBe('nginx');
        expect(ing.spec.rules[0].http.paths[0].backend.servicePort).toBe(80);
    });

    it('File deployment.yml is generated and filled in', function () {
        assert.file(['deployment.yml']);
        var deployment = yaml.load('deployment.yml');
        assert.equal(deployment.apiVersion, 'extensions/v1beta1');
        assert.equal(deployment.kind, 'Deployment');
        assert.equal(deployment.metadata.labels.name, 'nginx');
        assert.equal(deployment.metadata.name, 'nginx');
        assert.equal(deployment.metadata.namespace, 'default');
        assert.equal(deployment.spec.replicas, 1);
        assert.equal(deployment.spec.template.metadata.labels.app, 'nginx');
        assert.equal(deployment.spec.template.spec.containers[0].name, 'nginx');
        assert.equal(deployment.spec.template.spec.containers[0].image, 'nginx');
    });
});

describe('Ingress with no host', function () {

    beforeEach(function () {
        return helpers.run(path.join(__dirname, '../generators/app'))
            .withPrompts({
                name: 'nginx',
                namespace: 'default',
                podControllerType: 'Deployment',
                image: 'nginx',
                replicas: 1,
                containerPort: 80,
                servicePort: 80,
                shouldExpose: 'yes',
                path: '/',
                ingressPort: 80
            });
    });

    it('File rc.yml is not generated', function () {
        assert.noFile(['rc.yml']);
    });

    it('File svc.yml is generated and filled in', function () {
        assert.file(['svc.yml']);
        var svc = yaml.load('svc.yml');
        assert.equal(svc.apiVersion, 'v1');
        assert.equal(svc.kind, 'Service');
        assert.equal(svc.metadata.name, 'nginx');
        assert.equal(svc.metadata.namespace, 'default');
        assert.equal(svc.spec.ports[0].port, 80);
        assert.equal(svc.spec.ports[0].targetPort, 80);
        assert.equal(svc.spec.selector.app, 'nginx');
    });

    it('File ing.yml is generated and filled in', function () {
        assert.file(['ing.yml']);
        var ing = yaml.load('ing.yml');
        expect(ing.apiVersion).toBe('extensions/v1beta1');
        expect(ing.kind).toBe('Ingress');
        expect(ing.metadata.name).toBe('nginx');
        expect(ing.metadata.namespace).toBe('default');
        expect(ing.spec.rules).toExist('Expected rules to exist');
        expect(ing.spec.rules[0].host).toNotExist();
        expect(ing.spec.rules[0].http.paths[0].path).toBe('/');
        expect(ing.spec.rules[0].http.paths[0].backend.serviceName).toBe('nginx');
        expect(ing.spec.rules[0].http.paths[0].backend.servicePort).toBe(80);
    });

    it('File deployment.yml is generated and filled in', function () {
        assert.file(['deployment.yml']);
        var deployment = yaml.load('deployment.yml');
        assert.equal(deployment.apiVersion, 'extensions/v1beta1');
        assert.equal(deployment.kind, 'Deployment');
        assert.equal(deployment.metadata.labels.name, 'nginx');
        assert.equal(deployment.metadata.name, 'nginx');
        assert.equal(deployment.metadata.namespace, 'default');
        assert.equal(deployment.spec.replicas, 1);
        assert.equal(deployment.spec.template.metadata.labels.app, 'nginx');
        assert.equal(deployment.spec.template.spec.containers[0].name, 'nginx');
        assert.equal(deployment.spec.template.spec.containers[0].image, 'nginx');
    });
});

describe('Invalid podControllerType stops the writing process', function () {

    beforeEach(function () {
        return helpers.run(path.join(__dirname, '../generators/app'))
            .withArguments(['--create'])
            .withPrompts({
                name: 'nginx',
                namespace: 'default',
                podControllerType: 'InvalidType',
                image: 'nginx',
                replicas: 1,
                containerPort: 80,
                servicePort: 80,
                shouldExpose: 'yes',
                host: 'nginx.ingress.com',
                path: '/',
                ingressPort: 80
            });
    });

    it('File rc.yml is not generated', function () {
        assert.noFile(['rc.yml']);
    });

    it('File svc.yml is not generated', function () {
        assert.noFile(['svc.yml']);
    });

    it('File ing.yml is not generated', function () {
        assert.noFile(['ing.yml']);
    });

    it('File deployment.yml is not generated', function () {
        assert.noFile(['deployment.yml']);
    });
});

describe('Spawn create command with Deployment', function () {

    beforeEach(function () {
        return helpers.run(path.join(__dirname, '../generators/app'))
            .withArguments(['--create'])
            .withPrompts({
                name: 'nginx',
                namespace: 'default',
                podControllerType: 'Deployment',
                image: 'nginx',
                replicas: 1,
                containerPort: 80,
                servicePort: 80,
                shouldExpose: 'yes',
                host: 'nginx.ingress.com',
                path: '/',
                ingressPort: 80
            });
    });

    it('File rc.yml is not generated', function () {
        assert.noFile(['rc.yml']);
    });

    it('File svc.yml is generated', function () {
        assert.file(['svc.yml']);
    });

    it('File ing.yml is generated', function () {
        assert.file(['ing.yml']);
    });

    it('File deployment.yml is generated', function () {
        assert.file(['deployment.yml']);
    });
});

describe('Spawn apply command with Deployment', function () {

    beforeEach(function () {
        return helpers.run(path.join(__dirname, '../generators/app'))
            .withArguments(['--apply'])
            .withPrompts({
                name: 'nginx',
                namespace: 'default',
                podControllerType: 'Deployment',
                image: 'nginx',
                replicas: 1,
                containerPort: 80,
                servicePort: 80,
                shouldExpose: 'yes',
                host: 'nginx.ingress.com',
                path: '/',
                ingressPort: 80
            });
    });

    it('File rc.yml is not generated', function () {
        assert.noFile(['rc.yml']);
    });

    it('File svc.yml is generated', function () {
        assert.file(['svc.yml']);
    });

    it('File ing.yml is generated', function () {
        assert.file(['ing.yml']);
    });

    it('File deployment.yml is generated', function () {
        assert.file(['deployment.yml']);
    });
});

describe('Spawn delete command with Deployment', function () {

    beforeEach(function () {
        return helpers.run(path.join(__dirname, '../generators/app'))
            .withArguments(['--delete'])
            .withPrompts({
                name: 'nginx',
                namespace: 'default',
                podControllerType: 'Deployment',
                image: 'nginx',
                replicas: 1,
                containerPort: 80,
                servicePort: 80,
                shouldExpose: 'yes',
                host: 'nginx.ingress.com',
                path: '/',
                ingressPort: 80
            });
    });

    it('File rc.yml is not generated', function () {
        assert.noFile(['rc.yml']);
    });

    it('File svc.yml is not generated', function () {
        assert.noFile(['svc.yml']);
    });

    it('File ing.yml is not generated', function () {
        assert.noFile(['ing.yml']);
    });

    it('File deployment.yml is not generated', function () {
        assert.noFile(['deployment.yml']);
    });
});<|endoftext|>


<commit_before>const config = require('./config')

let debug = require('debug')

// Import and Set Nuxt.js options
if (config.debug) {
    debug.enable('*')
}

debug = debug('viblo-frontend')

debug('Loading components.')

const nuxt = require('./nuxt')
const session = require('./session')
const proxy = require('./proxy')
const router = require('./router')
const cookie = require('cookie-parser')()
const csrf = require('csurf')()
const axios = require('axios')
const viewCounter = require('./middleware/views')
var timeout = require('connect-timeout')

debug('Components loaded.')

const app = require('express')()

process.on('unhandledRejection', r => console.log(r))

app.use(timeout('4s'))
app.use(session)
app.use(cookie)
app.use(csrf)
app.use(haltOnTimedout)

axios.interceptors.request.use(function (request) {
    if (request.url.startsWith(config.node.url + '/api')) {
        let url = config.api.url + request.url.substr(config.node.url.length + 4)
        debug(request.url + ' > ' + url)
        request.url = url
    }
    return request
})

axios.interceptors.response.use(function (response) {
    return response
}, function (error) {
    if (error.response) {
        console.log(error.response.data)
    } else {
        console.log(error)
    }
    return Promise.reject(error)
})

app.use((req, res, next) => {
    if (req.session && req.session.token) {
        // Temporary workaround to inject token into server-side requests
        // after finished refactoring of API routes, must be changed
        let authorization = `${req.session.token.token_type} ${req.session.token.access_token}`
        axios.defaults.headers.common['Authorization'] = authorization
    }
    next()
})

app.use((req, res, next) => {
    res.cookie('XSRF-TOKEN', req.csrfToken(), {})
    res.locals.csrftoken = req.csrfToken()
    next()
})

app.use((req, res, next) => {
    // Share public config to frontend
    req.config = config
    next()
})

router.get(['/:user/posts/:post', '/api/posts/:post', '/p/:post'], viewCounter)

app.use('/api', proxy)
app.use('/', router)

app.use('/admin', (req, res, next) => {
    if (!req.session || !req.session.user || !req.session.user.admin_access) {
        res.redirect('/')
    } else {
        return next()
    }
})

app.get('/sitemap.xml', require('./routes/sitemap'))

app.use(nuxt.render)

function haltOnTimedout (req, res, next) {
    if (!req.timedout) next()
}

module.exports = app
<commit_msg>Fixes<commit_after>const config = require('./config')

let debug = require('debug')

// Import and Set Nuxt.js options
if (config.debug) {
    debug.enable('*')
}

debug = debug('viblo-frontend')

debug('Loading components.')

const nuxt = require('./nuxt')
const session = require('./session')
const proxy = require('./proxy')
const router = require('./router')
const cookie = require('cookie-parser')()
const csrf = require('csurf')()
const axios = require('axios')
const viewCounter = require('./middleware/views')

debug('Components loaded.')

const app = require('express')()

process.on('unhandledRejection', r => console.log(r))

app.use(session)
app.use(cookie)
app.use(csrf)

axios.interceptors.request.use(function (request) {
    if (request.url.startsWith(config.node.url + '/api')) {
        let url = config.api.url + request.url.substr(config.node.url.length + 4)
        debug(request.url + ' > ' + url)
        request.url = url
    }
    return request
})

axios.interceptors.response.use(function (response) {
    return response
}, function (error) {
    if (error.response) {
        console.log(error.response.data)
    } else {
        console.log(error)
    }
    return Promise.reject(error)
})

app.use((req, res, next) => {
    if (req.session && req.session.token) {
        // Temporary workaround to inject token into server-side requests
        // after finished refactoring of API routes, must be changed
        let authorization = `${req.session.token.token_type} ${req.session.token.access_token}`
        axios.defaults.headers.common['Authorization'] = authorization
    }
    next()
})

app.use((req, res, next) => {
    res.cookie('XSRF-TOKEN', req.csrfToken(), {})
    res.locals.csrftoken = req.csrfToken()
    next()
})

app.use((req, res, next) => {
    // Share public config to frontend
    req.config = config
    next()
})

router.get(['/:user/posts/:post', '/api/posts/:post', '/p/:post'], viewCounter)

app.use('/api', proxy)
app.use('/', router)

app.use('/admin', (req, res, next) => {
    if (!req.session || !req.session.user || !req.session.user.admin_access) {
        res.redirect('/')
    } else {
        return next()
    }
})

app.get('/sitemap.xml', require('./routes/sitemap'))

app.use(nuxt.render)

module.exports = app
<|endoftext|>


<commit_before>function Game(scale, dev) {
	var self = this;

	self.moves = new Array();

	generate();

	function generate() {
		if (scale == 4) {
			self.starter = defaultFour[Math.floor(Math.random() * defaultFour.length)];
		}
		else if (scale == 6) {
			self.starter = defaultSix[Math.floor(Math.random() * defaultSix.length)];
		}
		else if (scale == 8) {
			self.starter = defaultEight[Math.floor(Math.random() * defaultEight.length)];
		}
		else {
			self.starter = new Object();
			emptyGrid = Array.apply(null, Array(scale)).map(function (_, i) {return i;});
			for (var row in emptyGrid) {
				gridRow = new Object();
				for (var cell in emptyGrid) {
					gridRow[cell] = 1;
				}
				self.starter[row] = gridRow;
			}
		}
		self.puzzle = new GameGrid(scale, self, self.starter);
		buttonSetup();
	}

	function buttonSetup() {
		restartButton = document.getElementById('restartBtn');
		restartButton.onclick = function() {
			restart();
		}
		mainMenuButton = document.getElementById('mainMenuBtn');
		mainMenuButton.onclick = function() {
			endGame();
		}
		surrenderButton = document.getElementById('surrenderBtn');
		surrenderButton.onclick = function() {
			surrender();
		}
		undoButton = document.getElementById('undoBtn');
		undoButton.onclick = function() {
			undo();
		}
	}

	function restart() {
		self.puzzle.element.remove();
		self.puzzle = new GameGrid(scale, self, self.starter);
	}

	function undo() {
		if (self.moves.length > 0) {
			var block = self.moves.pop(self.moves.length-1);
			var x = block[0];
			var y = block[1];
			var oldState = block[2];
			var newState = block[3];
			self.puzzle.setDirect(x, y, oldState);
		}
	}

	function solve() {
		// todo: fade in solution
	}

	function exit() {
		$('#MainMenu').fadeIn();
	}

	function endGame() {
		setTimeout(function() {
			self.puzzle.destroy();
			self.puzzle = null;
		}, 1000);
		exit();
	}

	function surrender()  {
		solve();
		$('#gameHeading').text('You lose!');
		self.puzzle.setState(3);
		setTimeout(function() {
			endGame();
			$('#gameHeading').text('Enumerate');
		}, 2000);
	}

	self.update = function(x, y, oldState, newState) {
		self.moves.push([x, y, oldState, newState]);
		for (var row in self.puzzle.grid) {
			if ((self.puzzle.triples(self.puzzle.grid[row])) || (self.puzzle.equalTiles(self.puzzle.grid[row]))) {
				return false;
			}
		}
		if (self.puzzle.duplicates(self.puzzle.grid)) {
			return false;
		}
		var columns = new Object();
		for (var i in self.puzzle.grid) {
			columns[i] = new Object();
		}
		for (var i in self.puzzle.grid) {
			for (var e in self.puzzle.grid) {
				columns[e][i] = self.puzzle.grid[i][e];
			}
		}
		for (var column in columns) {
			if ((self.puzzle.triples(columns[column])) || (self.puzzle.equalTiles(columns[column]))) {
				return false;
			}
		}
		if (self.puzzle.duplicates(columns)) {
			return false;
		}
		if (self.puzzle.isFull()) {
			document.cookie = 'score=' + (getCookie(score) + (scale * scale)).toString() + ';';
			$('#gameHeading').text('You win!');
			self.puzzle.setState(2);
			setTimeout(function() {
				endGame();
				$('#gameHeading').text('Enumerate');
			}, 2000);
		}
	}
}
<commit_msg>final score tweak<commit_after>function Game(scale, dev) {
	var self = this;

	self.moves = new Array();

	generate();

	function generate() {
		if (scale == 4) {
			self.starter = defaultFour[Math.floor(Math.random() * defaultFour.length)];
		}
		else if (scale == 6) {
			self.starter = defaultSix[Math.floor(Math.random() * defaultSix.length)];
		}
		else if (scale == 8) {
			self.starter = defaultEight[Math.floor(Math.random() * defaultEight.length)];
		}
		else {
			self.starter = new Object();
			emptyGrid = Array.apply(null, Array(scale)).map(function (_, i) {return i;});
			for (var row in emptyGrid) {
				gridRow = new Object();
				for (var cell in emptyGrid) {
					gridRow[cell] = 1;
				}
				self.starter[row] = gridRow;
			}
		}
		self.puzzle = new GameGrid(scale, self, self.starter);
		buttonSetup();
	}

	function buttonSetup() {
		restartButton = document.getElementById('restartBtn');
		restartButton.onclick = function() {
			restart();
		}
		mainMenuButton = document.getElementById('mainMenuBtn');
		mainMenuButton.onclick = function() {
			endGame();
		}
		surrenderButton = document.getElementById('surrenderBtn');
		surrenderButton.onclick = function() {
			surrender();
		}
		undoButton = document.getElementById('undoBtn');
		undoButton.onclick = function() {
			undo();
		}
	}

	function restart() {
		self.puzzle.element.remove();
		self.puzzle = new GameGrid(scale, self, self.starter);
	}

	function undo() {
		if (self.moves.length > 0) {
			var block = self.moves.pop(self.moves.length-1);
			var x = block[0];
			var y = block[1];
			var oldState = block[2];
			var newState = block[3];
			self.puzzle.setDirect(x, y, oldState);
		}
	}

	function solve() {
		// todo: fade in solution
	}

	function exit() {
		$('#MainMenu').fadeIn();
	}

	function endGame() {
		setTimeout(function() {
			self.puzzle.destroy();
			self.puzzle = null;
		}, 1000);
		exit();
	}

	function surrender()  {
		solve();
		$('#gameHeading').text('You lose!');
		self.puzzle.setState(3);
		setTimeout(function() {
			endGame();
			$('#gameHeading').text('Enumerate');
		}, 2000);
	}

	self.update = function(x, y, oldState, newState) {
		self.moves.push([x, y, oldState, newState]);
		for (var row in self.puzzle.grid) {
			if ((self.puzzle.triples(self.puzzle.grid[row])) || (self.puzzle.equalTiles(self.puzzle.grid[row]))) {
				return false;
			}
		}
		if (self.puzzle.duplicates(self.puzzle.grid)) {
			return false;
		}
		var columns = new Object();
		for (var i in self.puzzle.grid) {
			columns[i] = new Object();
		}
		for (var i in self.puzzle.grid) {
			for (var e in self.puzzle.grid) {
				columns[e][i] = self.puzzle.grid[i][e];
			}
		}
		for (var column in columns) {
			if ((self.puzzle.triples(columns[column])) || (self.puzzle.equalTiles(columns[column]))) {
				return false;
			}
		}
		if (self.puzzle.duplicates(columns)) {
			return false;
		}
		if (self.puzzle.isFull()) {
			document.cookie = 'score=' + (getCookie(score) + (scale * scale)).toString() + ';';
			$('.score').text(getCookie('score'));
			$('#gameHeading').text('You win!');
			self.puzzle.setState(2);
			setTimeout(function() {
				endGame();
				$('#gameHeading').text('Enumerate');
			}, 2000);
		}
	}
}
<|endoftext|>


<commit_before>/**
 * Created by yangm11 on 4/7/2017.
 */
'use strict';

// get one item from an array randomly
function sample(arr) {
  var t = Math.floor(arr.length * Math.random());
  return arr[t];
}

// shuffle an array
function shuffle(arr) {
  var result = [];
  var len = arr.length;
  var cp = arr.slice();
  for (var i = 0; i < len; i++) {
    var idx = Math.floor(cp.length * Math.random());
    result.push(cp.splice(idx, 1)[0]);
  }
  return result;
}

// console.log(shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9]));

//<commit_msg>find unique and duplicate<commit_after>/**
 * Created by yangm11 on 4/7/2017.
 */
'use strict';

// get one item from an array randomly
function sample(arr) {
  var t = Math.floor(arr.length * Math.random());
  return arr[t];
}

// shuffle an array
function shuffle(arr) {
  var result = [];
  var len = arr.length;
  var cp = arr.slice();
  for (var i = 0; i < len; i++) {
    var idx = Math.floor(cp.length * Math.random());
    result.push(cp.splice(idx, 1)[0]);
  }
  return result;
}

// console.log(shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9]));

function findUnique(arr) {
  let uniq = [];
  let dupl = [];

  for (let i = 0; i < arr.length; i++) {
    let elem = arr[i];
    let count = 1;
    for (let j = i + 1; j < arr.length - 1; j++) {
      if (elem === arr[j]) {
        count += 1;
      }
    }
    if (count === 1) {
      uniq.push(elem);
    } else {
      dupl.push({
        elem: elem,
        count: count
      });
    }
  }
  return {
    unique: uniq,
    duplicate: dupl
  };
}<|endoftext|>


<commit_before>(function () {
/**
 * Options:
 *
 * element - element housing visualization
 *
 */

var
  TEMPLATE = '

';

function Visualization (options) {
  this.options = options || {};
  this.children = [];
  this.container = null;
  this.rendered = false;
}

Visualization.prototype = {

  render : function (element) {

    var o = this.options;

    element = element || o.element;
    if (!element) throw 'No element to render within.';

    this.container = bonzo.create(TEMPLATE);
    bonzo(element).append(this.container);

    _.each(this.children, function (child) {
      child.render(this.container);
    }, this);

    this.rendered = true;
  },

  add : function (child) {
    this.children.push(child);
    if (this.rendered) child.render(this.container);
    return child;
  },

  remove : function (child) {
    var
      children  = this.children,
      index     = this.indexOf(child);
    if (index !== -1) {
      children.splice(index, 1);
      bonzo(child.node).remove();
    }
  },

  indexOf : function (child) {
    return _.indexOf(this.children, child);
  }

};

Humble.Vis.Visualization = Visualization;

})();
<commit_msg>Added setPosition.<commit_after>(function () {
/**
 * Options:
 *
 * element - element housing visualization
 *
 */

var
  TEMPLATE = '

';

function Visualization (options) {
  this.options = options || {};
  this.children = [];
  this.container = null;
  this.rendered = false;
}

Visualization.prototype = {

  render : function (element) {

    var o = this.options;

    element = element || o.element;
    if (!element) throw 'No element to render within.';

    this.container = bonzo.create(TEMPLATE);
    bonzo(element).append(this.container);

    _.each(this.children, function (child) {
      child.render(this.container);
    }, this);

    this.rendered = true;
  },

  add : function (child) {
    this.children.push(child);
    if (this.rendered) child.render(this.container);
    return child;
  },

  remove : function (child) {
    var
      children  = this.children,
      index     = this.indexOf(child);
    if (index !== -1) {
      children.splice(index, 1);
      bonzo(child.node).remove();
      return true;
    }
  },

  setPosition : function (child, newIndex) {
    var
      children  = this.children;
    if (newIndex >= 0 && newIndex < children.length && this.remove(child)) {
      this.children.splice(newIndex, 0, [child]);
      if (newIndex === 0)
        bonzo(this.container).prepend(child.node);
      else
        bonzo(child.node).insertAfter(children[newIndex-1].node);
      return true;
    }
  },

  indexOf : function (child) {
    return _.indexOf(this.children, child);
  }

};

Humble.Vis.Visualization = Visualization;

})();
<|endoftext|>


<commit_before>// Represents a BAM file.
// Code is based heavily on bam.js, part of the Dalliance Genome Explorer,  (c) Thomas Down 2006-2001.

var igv = (function (igv) {

    var BAM_MAGIC = 21840194;
    var BAI_MAGIC = 21578050;
    var SECRET_DECODER = ['=', 'A', 'C', 'x', 'G', 'x', 'x', 'x', 'T', 'x', 'x', 'x', 'x', 'x', 'x', 'N'];
    var CIGAR_DECODER = ['M', 'I', 'D', 'N', 'S', 'H', 'P', '=', 'X', '?', '?', '?', '?', '?', '?', '?'];
    var READ_PAIRED_FLAG = 0x1;
    var PROPER_PAIR_FLAG = 0x2;
    var READ_UNMAPPED_FLAG = 0x4;
    var MATE_UNMAPPED_FLAG = 0x8;
    var READ_STRAND_FLAG = 0x10;
    var MATE_STRAND_FLAG = 0x20;
    var FIRST_OF_PAIR_FLAG = 0x40;
    var SECOND_OF_PAIR_FLAG = 0x80;
    var NOT_PRIMARY_ALIGNMENT_FLAG = 0x100;
    var READ_FAILS_VENDOR_QUALITY_CHECK_FLAG = 0x200;
    var DUPLICATE_READ_FLAG = 0x400;
    var SUPPLEMENTARY_ALIGNMENT_FLAG = 0x800;

    const MAX_GZIP_BLOCK_SIZE = (1 << 16);   //  APPARENTLY.  Where is this documented???

    /**
     * Class for reading a bam file
     *
     * @param bamPath
     * @param baiPath
     * @constructor
     */
    igv.BamReader = function (config) {

        this.config = config;
        this.bamPath = config.url;
        this.baiPath = config.indexUrl || (this.bamPath + ".bai"); // Todo - deal with Picard convention.  WHY DOES THERE HAVE TO BE 2?
        this.headPath = config.headUrl || this.bamPath;

    };

    /**
     * Read the bam header.  This function is public to support unit testing
     * @param continuation
     */
    igv.BamReader.prototype.readHeader = function (continuation) {

        var bam = this;

        getContentLength(bam, function (contentLength) {

            getIndex(bam, function (index) {

                var len = index.headerSize + MAX_GZIP_BLOCK_SIZE;   // Insure we get the complete compressed block containing the header

                if (contentLength > 0) len = Math.min(contentLength, len);

                igvxhr.loadArrayBuffer(bam.bamPath,
                    {
                        headers: bam.config.headers,

                        range: {start: 0, size: len},

                        success: function (compressedBuffer) {

                            var unc = igv.unbgzf(compressedBuffer, len);

                            var uncba = new Uint8Array(unc);

                            var magic = readInt(uncba, 0);
                            var samHeaderLen = readInt(uncba, 4);
                            var samHeader = '';
                            for (var i = 0; i < samHeaderLen; ++i) {
                                samHeader += String.fromCharCode(uncba[i + 8]);
                            }

                            var nRef = readInt(uncba, samHeaderLen + 8);
                            var p = samHeaderLen + 12;

                            bam.chrToIndex = {};
                            bam.indexToChr = [];
                            for (var i = 0; i < nRef; ++i) {
                                var lName = readInt(uncba, p);
                                var name = '';
                                for (var j = 0; j < lName - 1; ++j) {
                                    name += String.fromCharCode(uncba[p + 4 + j]);
                                }
                                var lRef = readInt(uncba, p + lName + 4);
                                //dlog(name + ': ' + lRef);

                                bam.chrToIndex[name] = i;
                                bam.indexToChr.push(name);

                                p = p + 8 + lName;
                            }

                            continuation();

                        }
                    });
            });

        });
    }

    igv.BamReader.prototype.readAlignments = function (chr, min, max, continuation, task) {

        var bam = this;

        getChrIndex(this, function (chrToIndex) {

            var chrId = chrToIndex[chr];
            var chunks;
            if (chrId === undefined) {
                if (chr.startsWith("chr")) chr = chr.substr(3);
                else chr = "chr" + chr;
                chrId = bam.chrToIndex[chr];
            }
            if (chrId === undefined) {
                continuation([]);
            } else {

                getIndex(bam, function (bamIndex) {

                    chunks = bamIndex.blocksForRange(chrId, min, max);

                    if (!chunks) {
                        continuation(null, 'Error in index fetch');
                    }

                    var records = [];
                    loadNextChunk(0);

                    function loadNextChunk(chunkNumber) {

                        var c = chunks[chunkNumber];
                        var fetchMin = c.minv.block;
                        var fetchMax = Math.min(bam.contentLength, c.maxv.block + 65000);   // Make sure we get the whole block.

                        igvxhr.loadArrayBuffer(bam.bamPath,
                            {
                                task: task,
                                headers: bam.config.headers,
                                range: {start: fetchMin, size: fetchMax - fetchMin + 1},
                                success: function (compressed) {

                                    try {
                                        var ba = new Uint8Array(igv.unbgzf(compressed)); //, c.maxv.block - c.minv.block + 1));
                                    } catch (e) {
                                        console.log(e);
                                        continuation(records);
                                    }

                                    decodeBamRecords(ba, chunks[chunkNumber].minv.offset, records, min, max, chrId);

                                    chunkNumber++;

                                    if (chunkNumber >= chunks.length) {

                                        // If we have combined multiple chunks. Sort records by start position.  I'm not sure this is neccessary
                                        if (chunkNumber > 0 && records.length > 1) {
                                            records.sort(function (a, b) {
                                                return a.start - b.start;
                                            });
                                        }
                                        continuation(records);
                                    }
                                    else {
                                        loadNextChunk(chunkNumber);
                                    }
                                }
                            });

                    }
                });
            }
        });

        function decodeBamRecords(ba, offset, records, min, max, chrId) {

            var blockSize,
                blockEnd,
                record,
                refID,
                pos,
                bmn,
                bin,
                mq,
                nl,
                flag_nc,
                flag,
                nc,
                lseq,
                mateRefID,
                matePos,
                tlen,
                readName,
                j,
                p,
                lengthOnRef,
                cigar,
                c,
                cigarArray,
                seq,
                seqBytes,
                qseq;

            while (true) {

                blockSize = readInt(ba, offset);
                blockEnd = offset + blockSize + 4;

                if (blockEnd >= ba.length) {
                    return;
                }

                record = new igv.BamAlignment();

                refID = readInt(ba, offset + 4);
                pos = readInt(ba, offset + 8);

                if (refID > chrId || pos > max) return;  // We've gone off the right edge => we're done
                else if (refID < chrId) continue;    // Not sure this is possible

                bmn = readInt(ba, offset + 12);
                bin = (bmn & 0xffff0000) >> 16;
                mq = (bmn & 0xff00) >> 8;
                nl = bmn & 0xff;

                flag_nc = readInt(ba, offset + 16);
                flag = (flag_nc & 0xffff0000) >> 16;
                nc = flag_nc & 0xffff;

                record.flags = flag;
                record.strand = !(flag & READ_STRAND_FLAG);

                lseq = readInt(ba, offset + 20);

                mateRefID = readInt(ba, offset + 24);
                record.matePos = readInt(ba, offset + 28);

                record.tlen = readInt(ba, offset + 32);

                readName = '';
                for (j = 0; j < nl - 1; ++j) {
                    readName += String.fromCharCode(ba[offset + 36 + j]);
                }

                p = offset + 36 + nl;

                lengthOnRef = 0;
                cigar = '';

                /**
                 * @param cigarette CIGAR element (operator + length) encoded as an unsigned int.
                 * @return Object representation of the CIGAR element.
                 */
                    //private static CigarElement binaryCigarToCigarElement(final int cigarette) {
                    //    final int binaryOp = cigarette & 0xf;
                    //    final int length = cigarette >> 4;
                    //    return new CigarElement(length, CigarOperator.binaryToEnum(binaryOp));
                    //}

                cigarArray = [];
                for (c = 0; c < nc; ++c) {
                    var cigop = readInt(ba, p);
                    var opLen = (cigop >> 4);
                    var opLtr = CIGAR_DECODER[cigop & 0xf];
                    if (opLtr == 'M' || opLtr == 'EQ' || opLtr == 'X' || opLtr == 'D' || opLtr == 'N' || opLtr == '=')
                        lengthOnRef += opLen;
                    cigar = cigar + opLen + opLtr;
                    p += 4;

                    cigarArray.push({len: opLen, ltr: opLtr});
                }
                record.cigar = cigar;
                record.lengthOnRef = lengthOnRef;

                if (record.start + record.lengthOnRef < min) continue;  // Record out-of-range "to the left", skip to next one

                seq = '';
                seqBytes = (lseq + 1) >> 1;
                for (j = 0; j < seqBytes; ++j) {
                    var sb = ba[p + j];
                    seq += SECRET_DECODER[(sb & 0xf0) >> 4];
                    seq += SECRET_DECODER[(sb & 0x0f)];
                }
                seq = seq.substring(0, lseq);  // seq might have one extra character (if lseq is an odd number)

                p += seqBytes;
                record.seq = seq;

                qseq = '';
                for (j = 0; j < lseq; ++j) {
                    qseq += String.fromCharCode(ba[p + j] + 33);
                }
                p += lseq;

                record.qual = qseq;
                record.start = pos;
                record.mq = mq;
                record.readName = readName;
                record.chr = bam.indexToChr[refID];
                record.mateChr = bam.indexToChr[mateRefID];

                record.tagBA = new Uint8Array(ba.buffer.slice(p, blockEnd));  // decode thiese on demand
                p += blockEnd;

                if (!min || record.start <= max && record.start + record.lengthOnRef >= min) {
                    if (chrId === undefined || refID == chrId) {
                        record.blocks = makeBlocks(record, cigarArray);
                        records.push(record);
                    }
                }
                offset = blockEnd;
            }
            // Exits via top of loop.
        }

        /**
         * Split the alignment record into blocks as specified in the cigarArray.  Each aligned block contains
         * its portion of the read sequence and base quality strings.  A read sequence or base quality string
         * of "*" indicates the value is not recorded.  In all other cases the length of the block sequence (block.seq)
         * and quality string (block.qual) must == the block length.
         *
         * NOTE: Insertions are not yet treated // TODO
         *
         * @param record
         * @param cigarArray
         * @returns array of blocks
         */
        function makeBlocks(record, cigarArray) {

            var blocks = [],
                seqOffset = 0,
                pos = record.start,
                len = cigarArray.length,
                blockSeq,
                blockQuals;

            for (var i = 0; i < len; i++) {

                var c = cigarArray[i];

                switch (c.ltr) {
                    case 'H' :
                        break; // ignore hard clips
                    case 'P' :
                        break; // ignore pads
                    case 'S' :
                        seqOffset += c.len;
                        break; // soft clip read bases
                    case 'N' :
                        pos += c.len;
                        break;  // reference skip
                    case 'D' :
                        pos += c.len;
                        break;
                    case 'I' :
                        seqOffset += c.len;
                        break;
                    case 'M' :
                    case 'EQ' :
                    case '=' :
                    case 'X' :
                        blockSeq = record.seq === "*" ? "*" : record.seq.substr(seqOffset, c.len);
                        blockQuals = record.qual === "*" ? "*" : record.qual.substr(seqOffset, c.len);
                        blocks.push({start: pos, len: c.len, seq: blockSeq, qual: blockQuals});
                        seqOffset += c.len;
                        pos += c.len;
                        break;
                    default :
                        console.log("Error processing cigar element: " + c.len + c.ltr);
                }
            }

            return blocks;

        }

    }

    function getIndex(bam, continuation) {

        if (bam.index) {
            continuation(bam.index);
        }
        else {
            igv.loadBamIndex(bam.baiPath, bam.config, function (index) {
                bam.index = index;
                continuation(bam.index);
            });
        }

    }

    function getContentLength(bam, continuation) {
        if (bam.contentLength) {
            continuation(bam.contentLength);
        }
        else {

            // Gen the content length first, so we don't try to read beyond the end of the file
            igvxhr.getContentLength(bam.headPath, {
                headers: bam.headers,
                success: function (contentLength) {
                    bam.contentLength = contentLength;
                    continuation(bam.contentLength);

                },
                error: function () {
                    bam.contentLength = -1;
                    continuation(bam.contentLength);
                }

            });
        }
    }

    function getChrIndex(bam, continuation) {

        if (bam.chrToIndex) {
            continuation(bam.chrToIndex);
        }
        else {
            bam.readHeader(function () {
                continuation(bam.chrToIndex);
            })
        }
    }

    function readInt(ba, offset) {
        return (ba[offset + 3] << 24) | (ba[offset + 2] << 16) | (ba[offset + 1] << 8) | (ba[offset]);
    }

    function readShort(ba, offset) {
        return (ba[offset + 1] << 8) | (ba[offset]);
    }

    return igv;

})
(igv || {});

<commit_msg>Handle bam query in region with no chunks<commit_after>// Represents a BAM file.
// Code is based heavily on bam.js, part of the Dalliance Genome Explorer,  (c) Thomas Down 2006-2001.

var igv = (function (igv) {

    var BAM_MAGIC = 21840194;
    var BAI_MAGIC = 21578050;
    var SECRET_DECODER = ['=', 'A', 'C', 'x', 'G', 'x', 'x', 'x', 'T', 'x', 'x', 'x', 'x', 'x', 'x', 'N'];
    var CIGAR_DECODER = ['M', 'I', 'D', 'N', 'S', 'H', 'P', '=', 'X', '?', '?', '?', '?', '?', '?', '?'];
    var READ_PAIRED_FLAG = 0x1;
    var PROPER_PAIR_FLAG = 0x2;
    var READ_UNMAPPED_FLAG = 0x4;
    var MATE_UNMAPPED_FLAG = 0x8;
    var READ_STRAND_FLAG = 0x10;
    var MATE_STRAND_FLAG = 0x20;
    var FIRST_OF_PAIR_FLAG = 0x40;
    var SECOND_OF_PAIR_FLAG = 0x80;
    var NOT_PRIMARY_ALIGNMENT_FLAG = 0x100;
    var READ_FAILS_VENDOR_QUALITY_CHECK_FLAG = 0x200;
    var DUPLICATE_READ_FLAG = 0x400;
    var SUPPLEMENTARY_ALIGNMENT_FLAG = 0x800;

    const MAX_GZIP_BLOCK_SIZE = (1 << 16);   //  APPARENTLY.  Where is this documented???

    /**
     * Class for reading a bam file
     *
     * @param bamPath
     * @param baiPath
     * @constructor
     */
    igv.BamReader = function (config) {

        this.config = config;
        this.bamPath = config.url;
        this.baiPath = config.indexUrl || (this.bamPath + ".bai"); // Todo - deal with Picard convention.  WHY DOES THERE HAVE TO BE 2?
        this.headPath = config.headUrl || this.bamPath;

    };

    /**
     * Read the bam header.  This function is public to support unit testing
     * @param continuation
     */
    igv.BamReader.prototype.readHeader = function (continuation) {

        var bam = this;

        getContentLength(bam, function (contentLength) {

            getIndex(bam, function (index) {

                var len = index.headerSize + MAX_GZIP_BLOCK_SIZE;   // Insure we get the complete compressed block containing the header

                if (contentLength > 0) len = Math.min(contentLength, len);

                igvxhr.loadArrayBuffer(bam.bamPath,
                    {
                        headers: bam.config.headers,

                        range: {start: 0, size: len},

                        success: function (compressedBuffer) {

                            var unc = igv.unbgzf(compressedBuffer, len);

                            var uncba = new Uint8Array(unc);

                            var magic = readInt(uncba, 0);
                            var samHeaderLen = readInt(uncba, 4);
                            var samHeader = '';
                            for (var i = 0; i < samHeaderLen; ++i) {
                                samHeader += String.fromCharCode(uncba[i + 8]);
                            }

                            var nRef = readInt(uncba, samHeaderLen + 8);
                            var p = samHeaderLen + 12;

                            bam.chrToIndex = {};
                            bam.indexToChr = [];
                            for (var i = 0; i < nRef; ++i) {
                                var lName = readInt(uncba, p);
                                var name = '';
                                for (var j = 0; j < lName - 1; ++j) {
                                    name += String.fromCharCode(uncba[p + 4 + j]);
                                }
                                var lRef = readInt(uncba, p + lName + 4);
                                //dlog(name + ': ' + lRef);

                                bam.chrToIndex[name] = i;
                                bam.indexToChr.push(name);

                                p = p + 8 + lName;
                            }

                            continuation();

                        }
                    });
            });

        });
    }

    igv.BamReader.prototype.readAlignments = function (chr, min, max, continuation, task) {

        var bam = this;

        getChrIndex(this, function (chrToIndex) {

            var chrId = chrToIndex[chr];
            var chunks;
            if (chrId === undefined) {
                if (chr.startsWith("chr")) chr = chr.substr(3);
                else chr = "chr" + chr;
                chrId = bam.chrToIndex[chr];
            }
            if (chrId === undefined) {
                continuation([]);
            } else {

                getIndex(bam, function (bamIndex) {

                    chunks = bamIndex.blocksForRange(chrId, min, max);

                    if (!chunks) {
                        continuation(null, 'Error in index fetch');
                        return;
                    }
                    if(chunks.length === 0) {
                        console.log('No chunks for range ' + chrId + ":" + min + "-" + max);
                        continuation([]);
                        return;
                    }

                    var records = [];
                    loadNextChunk(0);

                    function loadNextChunk(chunkNumber) {

                        var c = chunks[chunkNumber];
                        var fetchMin = c.minv.block;
                        var fetchMax = Math.min(bam.contentLength, c.maxv.block + 65000);   // Make sure we get the whole block.

                        igvxhr.loadArrayBuffer(bam.bamPath,
                            {
                                task: task,
                                headers: bam.config.headers,
                                range: {start: fetchMin, size: fetchMax - fetchMin + 1},
                                success: function (compressed) {

                                    try {
                                        var ba = new Uint8Array(igv.unbgzf(compressed)); //, c.maxv.block - c.minv.block + 1));
                                    } catch (e) {
                                        console.log(e);
                                        continuation(records);
                                    }

                                    decodeBamRecords(ba, chunks[chunkNumber].minv.offset, records, min, max, chrId);

                                    chunkNumber++;

                                    if (chunkNumber >= chunks.length) {

                                        // If we have combined multiple chunks. Sort records by start position.  I'm not sure this is neccessary
                                        if (chunkNumber > 0 && records.length > 1) {
                                            records.sort(function (a, b) {
                                                return a.start - b.start;
                                            });
                                        }
                                        continuation(records);
                                    }
                                    else {
                                        loadNextChunk(chunkNumber);
                                    }
                                }
                            });

                    }
                });
            }
        });

        function decodeBamRecords(ba, offset, records, min, max, chrId) {

            var blockSize,
                blockEnd,
                record,
                refID,
                pos,
                bmn,
                bin,
                mq,
                nl,
                flag_nc,
                flag,
                nc,
                lseq,
                mateRefID,
                matePos,
                tlen,
                readName,
                j,
                p,
                lengthOnRef,
                cigar,
                c,
                cigarArray,
                seq,
                seqBytes,
                qseq;

            while (true) {

                blockSize = readInt(ba, offset);
                blockEnd = offset + blockSize + 4;

                if (blockEnd >= ba.length) {
                    return;
                }

                record = new igv.BamAlignment();

                refID = readInt(ba, offset + 4);
                pos = readInt(ba, offset + 8);

                if (refID > chrId || pos > max) return;  // We've gone off the right edge => we're done
                else if (refID < chrId) continue;    // Not sure this is possible

                bmn = readInt(ba, offset + 12);
                bin = (bmn & 0xffff0000) >> 16;
                mq = (bmn & 0xff00) >> 8;
                nl = bmn & 0xff;

                flag_nc = readInt(ba, offset + 16);
                flag = (flag_nc & 0xffff0000) >> 16;
                nc = flag_nc & 0xffff;

                record.flags = flag;
                record.strand = !(flag & READ_STRAND_FLAG);

                lseq = readInt(ba, offset + 20);

                mateRefID = readInt(ba, offset + 24);
                record.matePos = readInt(ba, offset + 28);

                record.tlen = readInt(ba, offset + 32);

                readName = '';
                for (j = 0; j < nl - 1; ++j) {
                    readName += String.fromCharCode(ba[offset + 36 + j]);
                }

                p = offset + 36 + nl;

                lengthOnRef = 0;
                cigar = '';

                /**
                 * @param cigarette CIGAR element (operator + length) encoded as an unsigned int.
                 * @return Object representation of the CIGAR element.
                 */
                    //private static CigarElement binaryCigarToCigarElement(final int cigarette) {
                    //    final int binaryOp = cigarette & 0xf;
                    //    final int length = cigarette >> 4;
                    //    return new CigarElement(length, CigarOperator.binaryToEnum(binaryOp));
                    //}

                cigarArray = [];
                for (c = 0; c < nc; ++c) {
                    var cigop = readInt(ba, p);
                    var opLen = (cigop >> 4);
                    var opLtr = CIGAR_DECODER[cigop & 0xf];
                    if (opLtr == 'M' || opLtr == 'EQ' || opLtr == 'X' || opLtr == 'D' || opLtr == 'N' || opLtr == '=')
                        lengthOnRef += opLen;
                    cigar = cigar + opLen + opLtr;
                    p += 4;

                    cigarArray.push({len: opLen, ltr: opLtr});
                }
                record.cigar = cigar;
                record.lengthOnRef = lengthOnRef;

                if (record.start + record.lengthOnRef < min) continue;  // Record out-of-range "to the left", skip to next one

                seq = '';
                seqBytes = (lseq + 1) >> 1;
                for (j = 0; j < seqBytes; ++j) {
                    var sb = ba[p + j];
                    seq += SECRET_DECODER[(sb & 0xf0) >> 4];
                    seq += SECRET_DECODER[(sb & 0x0f)];
                }
                seq = seq.substring(0, lseq);  // seq might have one extra character (if lseq is an odd number)

                p += seqBytes;
                record.seq = seq;

                qseq = '';
                for (j = 0; j < lseq; ++j) {
                    qseq += String.fromCharCode(ba[p + j] + 33);
                }
                p += lseq;

                record.qual = qseq;
                record.start = pos;
                record.mq = mq;
                record.readName = readName;
                record.chr = bam.indexToChr[refID];
                record.mateChr = bam.indexToChr[mateRefID];

                record.tagBA = new Uint8Array(ba.buffer.slice(p, blockEnd));  // decode thiese on demand
                p += blockEnd;

                if (!min || record.start <= max && record.start + record.lengthOnRef >= min) {
                    if (chrId === undefined || refID == chrId) {
                        record.blocks = makeBlocks(record, cigarArray);
                        records.push(record);
                    }
                }
                offset = blockEnd;
            }
            // Exits via top of loop.
        }

        /**
         * Split the alignment record into blocks as specified in the cigarArray.  Each aligned block contains
         * its portion of the read sequence and base quality strings.  A read sequence or base quality string
         * of "*" indicates the value is not recorded.  In all other cases the length of the block sequence (block.seq)
         * and quality string (block.qual) must == the block length.
         *
         * NOTE: Insertions are not yet treated // TODO
         *
         * @param record
         * @param cigarArray
         * @returns array of blocks
         */
        function makeBlocks(record, cigarArray) {

            var blocks = [],
                seqOffset = 0,
                pos = record.start,
                len = cigarArray.length,
                blockSeq,
                blockQuals;

            for (var i = 0; i < len; i++) {

                var c = cigarArray[i];

                switch (c.ltr) {
                    case 'H' :
                        break; // ignore hard clips
                    case 'P' :
                        break; // ignore pads
                    case 'S' :
                        seqOffset += c.len;
                        break; // soft clip read bases
                    case 'N' :
                        pos += c.len;
                        break;  // reference skip
                    case 'D' :
                        pos += c.len;
                        break;
                    case 'I' :
                        seqOffset += c.len;
                        break;
                    case 'M' :
                    case 'EQ' :
                    case '=' :
                    case 'X' :
                        blockSeq = record.seq === "*" ? "*" : record.seq.substr(seqOffset, c.len);
                        blockQuals = record.qual === "*" ? "*" : record.qual.substr(seqOffset, c.len);
                        blocks.push({start: pos, len: c.len, seq: blockSeq, qual: blockQuals});
                        seqOffset += c.len;
                        pos += c.len;
                        break;
                    default :
                        console.log("Error processing cigar element: " + c.len + c.ltr);
                }
            }

            return blocks;

        }

    }

    function getIndex(bam, continuation) {

        if (bam.index) {
            continuation(bam.index);
        }
        else {
            igv.loadBamIndex(bam.baiPath, bam.config, function (index) {
                bam.index = index;
                continuation(bam.index);
            });
        }

    }

    function getContentLength(bam, continuation) {
        if (bam.contentLength) {
            continuation(bam.contentLength);
        }
        else {

            // Gen the content length first, so we don't try to read beyond the end of the file
            igvxhr.getContentLength(bam.headPath, {
                headers: bam.headers,
                success: function (contentLength) {
                    bam.contentLength = contentLength;
                    continuation(bam.contentLength);

                },
                error: function () {
                    bam.contentLength = -1;
                    continuation(bam.contentLength);
                }

            });
        }
    }

    function getChrIndex(bam, continuation) {

        if (bam.chrToIndex) {
            continuation(bam.chrToIndex);
        }
        else {
            bam.readHeader(function () {
                continuation(bam.chrToIndex);
            })
        }
    }

    function readInt(ba, offset) {
        return (ba[offset + 3] << 24) | (ba[offset + 2] << 16) | (ba[offset + 1] << 8) | (ba[offset]);
    }

    function readShort(ba, offset) {
        return (ba[offset + 1] << 8) | (ba[offset]);
    }

    return igv;

})
(igv || {});

<|endoftext|>


<commit_before>
var snakeCells = [];
var initialSnakeLength = 3;
var cellWidth = 10;
var numberOfsnakeCells = 40;
var gameWidth = numberOfsnakeCells * cellWidth;
var snakeSpeed = 0.5;
var game = new Phaser.Game(gameWidth, gameWidth, Phaser.AUTO, 'snake', { preload: preload, create: create, update: update });

var DIRECTION = {
    UP: 1,
    RIGHT: 2,
    DOWN: 3,
    LEFT: 4
};

var direction = DIRECTION.RIGHT;
var arrowKeys;

function getAdjacentCellPosition(x, y, size, direction) {
    var newX;
    var newY;
    if (direction == DIRECTION.UP) {
        newY = y - size;
        if (newY < 0) {
            newY = newY + gameWidth;
        }
        return {x:x, y:newY};
    } else if (direction == DIRECTION.RIGHT) {
        newX = x + size;
        if (newX >= gameWidth) {
            newX = newX - gameWidth;
        }
        return {x:newX, y:y};
    } else if (direction == DIRECTION.DOWN) {
        newY = y + size;
        if (newY >= gameWidth) {
            newY = newY - gameWidth;
        }
        return {x:x, y:newY};
    } else if (direction == DIRECTION.LEFT) {
        newX = x - size;
        if (newX < 0) {
            newX = newX + gameWidth;
        }
        return {x:newX, y:y};
    }
}

function moveSnake() {
    var head = snakeCells[0];
    var last = snakeCells.pop();
    var nextPosition = getAdjacentCellPosition(head.x, head.y, cellWidth, direction);
    last.x = nextPosition.x;
    last.y = nextPosition.y;
    snakeCells.unshift(last);
}

function preload() {
    game.load.image('cell', 'images/cell.png');
}

function create() {
    game.stage.backgroundColor = '#ffffff';

    for (var i = initialSnakeLength - 1;i >= 0;--i) {
        snakeCells.push(game.add.sprite(i * cellWidth, 0, 'cell'));
    }

    game.time.events.loop(Phaser.Timer.SECOND * snakeSpeed, moveSnake, this);
    arrowKeys = game.input.keyboard.createCursorKeys();
}

function update() {
    if (arrowKeys.right.isDown && direction != DIRECTION.LEFT) {
        direction = DIRECTION.RIGHT;
    } else if (arrowKeys.left.isDown && direction != DIRECTION.RIGHT) {
        direction = DIRECTION.LEFT;
    } else if (arrowKeys.up.isDown && direction != DIRECTION.DOWN) {
        direction = DIRECTION.UP;
    } else if (arrowKeys.down.isDown && direction != DIRECTION.UP) {
        direction = DIRECTION.DOWN;
    }
}<commit_msg>Better input handling<commit_after>
var snakeCells = [];
var initialSnakeLength = 3;
var cellWidth = 10;
var numberOfsnakeCells = 40;
var gameWidth = numberOfsnakeCells * cellWidth;
var snakeSpeed = 5;
var game = new Phaser.Game(gameWidth, gameWidth, Phaser.AUTO, 'snake', { preload: preload, create: create, update: update });

var DIRECTION = {
    UP: 1,
    RIGHT: 2,
    DOWN: 3,
    LEFT: 4
};

var direction = DIRECTION.RIGHT;
var inputBuffer = [];
var inputBufferSize = 2;
var upArrowKey;
var rightArrowKey;
var downArrowKey;
var leftArrowKey;

function getAdjacentCellPosition(x, y, size, direction) {
    var newX;
    var newY;
    if (direction == DIRECTION.UP) {
        newY = y - size;
        if (newY < 0) {
            newY = newY + gameWidth;
        }
        return {x:x, y:newY};
    } else if (direction == DIRECTION.RIGHT) {
        newX = x + size;
        if (newX >= gameWidth) {
            newX = newX - gameWidth;
        }
        return {x:newX, y:y};
    } else if (direction == DIRECTION.DOWN) {
        newY = y + size;
        if (newY >= gameWidth) {
            newY = newY - gameWidth;
        }
        return {x:x, y:newY};
    } else if (direction == DIRECTION.LEFT) {
        newX = x - size;
        if (newX < 0) {
            newX = newX + gameWidth;
        }
        return {x:newX, y:y};
    }
}

function moveSnake() {
    var head = snakeCells[0];
    var last = snakeCells.pop();
    var newDirection = inputBuffer.shift();
    if (!newDirection) {
        newDirection = direction;
    }
    var nextPosition = getAdjacentCellPosition(head.x, head.y, cellWidth, newDirection);
    last.x = nextPosition.x;
    last.y = nextPosition.y;
    snakeCells.unshift(last);
    direction = newDirection;
}

function preload() {
    game.load.image('cell', 'images/cell.png');
}

function create() {
    game.stage.backgroundColor = '#ffffff';

    for (var i = initialSnakeLength - 1;i >= 0;--i) {
        snakeCells.push(game.add.sprite(i * cellWidth, 0, 'cell'));
    }

    game.time.events.loop(Phaser.Timer.SECOND / snakeSpeed, moveSnake, this);

    upArrowKey = game.input.keyboard.addKey(Phaser.Keyboard.UP);
    upArrowKey.onDown.add(onUpArrowKeyPressed, this);
    rightArrowKey = game.input.keyboard.addKey(Phaser.Keyboard.RIGHT);
    rightArrowKey.onDown.add(onRightArrowKeyPressed, this);
    downArrowKey = game.input.keyboard.addKey(Phaser.Keyboard.DOWN);
    downArrowKey.onDown.add(onDownArrowKeyPressed, this);
    leftArrowKey = game.input.keyboard.addKey(Phaser.Keyboard.LEFT);
    leftArrowKey.onDown.add(onLeftArrowKeyPressed, this);
}

function update() {

}

function onUpArrowKeyPressed() {
    var newDirection;
    var oldDirection = direction;
    if (inputBuffer.length > 0) {
        oldDirection = inputBuffer[inputBuffer.length - 1];
    }
    if (oldDirection != DIRECTION.DOWN) {
        newDirection = DIRECTION.UP;
    }
    if (newDirection && inputBuffer.length < inputBufferSize) {
        inputBuffer.push(newDirection);
    }
}

function onRightArrowKeyPressed() {
    var newDirection;
    var oldDirection = direction;
    if (inputBuffer.length > 0) {
        oldDirection = inputBuffer[inputBuffer.length - 1];
    }
    if (oldDirection != DIRECTION.LEFT) {
        newDirection = DIRECTION.RIGHT;
    }
    if (newDirection && inputBuffer.length < inputBufferSize) {
        inputBuffer.push(newDirection);
    }
}

function onDownArrowKeyPressed() {
    var newDirection;
    var oldDirection = direction;
    if (inputBuffer.length > 0) {
        oldDirection = inputBuffer[inputBuffer.length - 1];
    }
    if (oldDirection != DIRECTION.UP) {
        newDirection = DIRECTION.DOWN;
    }
    if (newDirection && inputBuffer.length < inputBufferSize) {
        inputBuffer.push(newDirection);
    }
}

function onLeftArrowKeyPressed() {
    var newDirection;
    var oldDirection = direction;
    if (inputBuffer.length > 0) {
        oldDirection = inputBuffer[inputBuffer.length - 1];
    }
    if (oldDirection != DIRECTION.RIGHT) {
        newDirection = DIRECTION.LEFT;
    }
    if (newDirection && inputBuffer.length < inputBufferSize) {
        inputBuffer.push(newDirection);
    }
}
<|endoftext|>


<commit_before>"use strict";

const ccxt = require ('ccxt')
    , WebSocketClient = require ('./WebSocketClient')
    , {
        ExternallyResolvablePromise,
        externallyResolvablePromise
    } = require ('./MultiPromise')
    , {
        OrderBook,
        LimitedOrderBook,
        IndexedOrderBook,
        LimitedIndexedOrderBook,
        LimitedCountedOrderBook,
        CountedOrderBook,
    } = require ('./OrderBook')
    , log = require ('ololog').unlimited

module.exports = class Exchange extends ccxt.Exchange {

    orderbook (snapshot = {}) {
        return new OrderBook (snapshot)
    }

    limitedOrderBook (snapshot = {}, depth = undefined) {
        return new LimitedOrderBook (snapshot, depth)
    }

    indexedOrderBook (snapshot = {}) {
        return new IndexedOrderBook (snapshot)
    }

    limitedIndexedOrderBook (snapshot = {}, depth = undefined) {
        return new LimitedIndexedOrderBook (snapshot, depth)
    }

    limitedCountOrderBook (snapshot = {}, depth = undefined) {
        return new LimitedCountedOrderBook (snapshot, depth)
    }

    countedOrderBook (snapshot = {}) {
        return new CountedOrderBook (snapshot)
    }

    websocket (url) {
        this.clients = this.clients || {}
        if (!this.clients[url]) {
            const callback = this.handleWsMessage.bind (this)
            this.clients[url] = new WebSocketClient (url, callback)
        }
        return this.clients[url]
    }

    sendWsMessage (url, messageHash, message = undefined, subscribeHash = undefined) {
        const client = this.websocket (url)
        if (!client.futures[messageHash]) {
            client.futures[messageHash] = externallyResolvablePromise ()
        }
        if (message && !client.subscriptions[subscribeHash]) {
            client.subscriptions[subscribeHash] = true
            message = this.signWsMessage (client, messageHash, message)
            client.send (message)
        }
        return client.futures[messageHash]
    }

    resolveWsFuture (client, messageHash, result) {
        if (client.futures[messageHash]) {
            const promise = client.futures[messageHash]
            promise.resolve (result)
            delete client.futures[messageHash]
        }
        return result
    }

    rejectWsFuture (client, messageHash, result) {
        if (client.futures[messageHash]) {
            const promise = client.futures[messageHash]
            promise.reject (result)
            delete client.futures[messageHash]
        }
        return result
    }

    async close () {
        const clients = Object.values (this.clients)
        for (let i = 0; i < clients.length; i++) {
            const client = clients[i]
            await client.close ()
        }
    }
}
<commit_msg>Exchange.js limitCountOrderBook → limitedCountedOrderBook typo<commit_after>"use strict";

const ccxt = require ('ccxt')
    , WebSocketClient = require ('./WebSocketClient')
    , {
        ExternallyResolvablePromise,
        externallyResolvablePromise
    } = require ('./MultiPromise')
    , {
        OrderBook,
        LimitedOrderBook,
        IndexedOrderBook,
        LimitedIndexedOrderBook,
        LimitedCountedOrderBook,
        CountedOrderBook,
    } = require ('./OrderBook')
    , log = require ('ololog').unlimited

module.exports = class Exchange extends ccxt.Exchange {

    orderbook (snapshot = {}) {
        return new OrderBook (snapshot)
    }

    limitedOrderBook (snapshot = {}, depth = undefined) {
        return new LimitedOrderBook (snapshot, depth)
    }

    indexedOrderBook (snapshot = {}) {
        return new IndexedOrderBook (snapshot)
    }

    limitedIndexedOrderBook (snapshot = {}, depth = undefined) {
        return new LimitedIndexedOrderBook (snapshot, depth)
    }

    limitedCountedOrderBook (snapshot = {}, depth = undefined) {
        return new LimitedCountedOrderBook (snapshot, depth)
    }

    countedOrderBook (snapshot = {}) {
        return new CountedOrderBook (snapshot)
    }

    websocket (url) {
        this.clients = this.clients || {}
        if (!this.clients[url]) {
            const callback = this.handleWsMessage.bind (this)
            this.clients[url] = new WebSocketClient (url, callback)
        }
        return this.clients[url]
    }

    sendWsMessage (url, messageHash, message = undefined, subscribeHash = undefined) {
        const client = this.websocket (url)
        if (!client.futures[messageHash]) {
            client.futures[messageHash] = externallyResolvablePromise ()
        }
        if (message && !client.subscriptions[subscribeHash]) {
            client.subscriptions[subscribeHash] = true
            message = this.signWsMessage (client, messageHash, message)
            client.send (message)
        }
        return client.futures[messageHash]
    }

    resolveWsFuture (client, messageHash, result) {
        if (client.futures[messageHash]) {
            const promise = client.futures[messageHash]
            promise.resolve (result)
            delete client.futures[messageHash]
        }
        return result
    }

    rejectWsFuture (client, messageHash, result) {
        if (client.futures[messageHash]) {
            const promise = client.futures[messageHash]
            promise.reject (result)
            delete client.futures[messageHash]
        }
        return result
    }

    async close () {
        const clients = Object.values (this.clients)
        for (let i = 0; i < clients.length; i++) {
            const client = clients[i]
            await client.close ()
        }
    }
}
<|endoftext|>