<commit_before>import React, { Component } from 'react';
import './App.css';
import Tone from 'tone';

export default class Timer extends Component {
  constructor() {
    super();
    this.state = {
      timer: '',
      remainingTime: 0,
      intervalId: null,
      countdownRunning: false,
      buttonName: "Start",
    }

    this.synth = new Tone.Synth().toMaster();
    this.updateTimer = this.updateTimer.bind(this);
    this.beep = this.beep.bind(this);
  }

  handleOnChange(ev) {
    this.setState({
      timer: ev.target.value
    });
  }

  handleOnBlur(ev) {
    this.setState({
      remainingTime: parseInt(this.state.timer, 10),
    });
  }

  handleOnSubmit(ev) {
    ev.preventDefault();
    if (!this.state.countdownRunning) {
      const intervalId = setInterval(this.updateTimer, 1000);
      this.setState({
        intervalId: intervalId,
        buttonName: "Stop",
        countdownRunning: true,
      });
    } else {
      clearInterval(this.state.intervalId);
      this.setState({
        buttonName: "Start",
        countdownRunning: false,
      });
    }
  }

  updateTimer() {
    if (this.state.remainingTime > 0) {
      this.setState({
        remainingTime: this.state.remainingTime - 1,
      });
      console.log(this.state.remainingTime);
      if(this.state.remainingTime <= 3 && this.state.remainingTime > 0) {
        this.beep("C4", "8n");
      } else if (this.state.remainingTime === 0 ){
        this.beep("C5", "4n");
      }
    } else {
      clearInterval(this.state.intervalId);
      this.setState({
        intervalId: null,
        remainingTime: parseInt(this.state.timer, 10),
        buttonName: "Start",
        countdownRunning: false,
      });
    }
  }

  beep(note, duration) {
    this.synth.triggerAttackRelease(note, duration);
  }

  render() {
    return (

Countdown!

        <Display remainingTime={this.state.remainingTime} />
        <form onSubmit={(ev) => this.handleOnSubmit(ev)}>
          <input type="text"
            onChange={(ev) => this.handleOnChange(ev)}
            onBlur={(ev) => this.handleOnBlur(ev) }
            value={this.state.timer} />
          <input type="submit" value={this.state.buttonName} />
        </form>

    );
  }
}

class Display extends Component {
  render() {
    return (

{this.props.remainingTime}

    )
  }
}
<commit_msg>Style Timer<commit_after>import React, { Component } from 'react';
import Tone from 'tone';

import './App.css';
import { displayTime } from '../utils/displayTime';

import { Segment, Button, Grid, Form, Header } from 'semantic-ui-react';

export default class Timer extends Component {
  constructor() {
    super();
    this.state = {
      timer: '',
      remainingTime: 0,
      intervalId: null,
      countdownRunning: false,
      buttonName: "Start",
    }

    this.synth = new Tone.Synth().toMaster();
    this.updateTimer = this.updateTimer.bind(this);
    this.beep = this.beep.bind(this);
  }

  handleOnChange(ev) {
    this.setState({
      timer: ev.target.value
    });
  }

  handleOnBlur(ev) {
    this.setState({
      remainingTime: parseInt(this.state.timer, 10),
    });
  }

  handleOnSubmit(ev) {
    ev.preventDefault();
    if (!this.state.countdownRunning) {
      const intervalId = setInterval(this.updateTimer, 1000);
      this.setState({
        intervalId: intervalId,
        buttonName: "Stop",
        countdownRunning: true,
      });
    } else {
      clearInterval(this.state.intervalId);
      this.setState({
        buttonName: "Start",
        countdownRunning: false,
      });
    }
  }

  updateTimer() {
    if (this.state.remainingTime > 0) {
      this.setState({
        remainingTime: this.state.remainingTime - 1,
      });
      console.log(this.state.remainingTime);
      if(this.state.remainingTime <= 3 && this.state.remainingTime > 0) {
        this.beep("C4", "8n");
      } else if (this.state.remainingTime === 0 ){
        this.beep("C5", "4n");
      }
    } else {
      clearInterval(this.state.intervalId);
      this.setState({
        intervalId: null,
        remainingTime: parseInt(this.state.timer, 10),
        buttonName: "Start",
        countdownRunning: false,
      });
    }
  }

  beep(note, duration) {
    this.synth.triggerAttackRelease(note, duration);
  }

  render() {
    return (
      <Grid
        verticalAlign="middle"
        centered
        style={{
          height: '100%',
          margin: 0,
        }}>
        <Grid.Column width={6} textAlign="center">
          <Segment padded>
            React Timer
            <Display remainingTime={this.state.remainingTime} />
            <Form onSubmit={(ev) => this.handleOnSubmit(ev)}>
              <Form.Field>
                <input
                  placeholder="Time in Seconds"
                  type="text"
                  onChange={(ev) => this.handleOnChange(ev)}
                  onBlur={(ev) => this.handleOnBlur(ev) }
                  value={this.state.timer} />
              </Form.Field>
              <Button
                color="blue"
                type="submit">
                {this.state.buttonName}
              </Button>
            </Form>
          </Segment>
        </Grid.Column>
      </Grid>
    );
  }
}

class Display extends Component {
  render() {
    return (
      <Segment>
        {displayTime(this.props.remainingTime)}
      </Segment>
    )
  }
}
<|endoftext|>


<commit_before>var GameState = function (game) {
};

//load assets
GameState.prototype.preload = function(){

    this.game.load.image('map', 'assets/map.png'); // thjs is the background
    this.game.load.image('ground', 'assets/block.png');//this is the ground
    this.game.load.image('block', 'assets/pixel_1.png');//this is the image for the platforms, the block argument in the create function below links the sprite to the platform
    this.game.load.spritesheet('player', 'assets/dude.png', 32, 48);
    this.game.load.image('cat', 'assets/cat.png');

};

GameState.prototype.create = function () {
    //this.game.add.sprite(0,0, 'map');

    //movement:
    this.MAX_SPEED = 500; //px/s
    this.ACCELERATION = 1500; //px/s/s
    this.DRAG = 900; //px/s
    this.GRAVITY = 2600;
    this.JUMP_SPEED = -1000;
    //create player
    this.player = this.game.add.sprite(this.game.width/2, this.game.height - 90, 'player');
    this.player.anchor.set(0.5);

    this.player.yOrig = this.player.y;
    this.player.yChange = 0;

    //add player movement animations;
    this.player.animations.add('left', [0,1,2,3], 10, true);
    this.player.animations.add('right', [5,6,7,8], 10, true);

    //physics
    this.game.physics.enable(this.player, Phaser.Physics.ARCADE);
    //make player collide with the boundaries of the game
    this.player.body.collideWorldBounds = true;
    this.player.body.maxVelocity.setTo(this.MAX_SPEED, this.MAX_SPEED * 10);
    this.player.body.drag.setTo(this.DRAG,0);

    this.player.body.gravity.y = this.GRAVITY;
    this.player.body.checkCollision.up = false;
    //this.player.body.checkCollision.left = false;
    //this.player.body.checkCollision.right = false;

    //create floor
    this.ground = this.game.add.group();
    for(var x = 0; x < this.game.width; x += 32) {
        // Add the ground blocks, enable physics on each, make them immovable
        var groundBlock = this.game.add.sprite(x, this.game.height - 32, 'ground');
        this.game.physics.enable(groundBlock, Phaser.Physics.ARCADE);
        groundBlock.body.immovable = true;
        groundBlock.body.allowGravity = false;
        this.ground.add(groundBlock);
    }

    //console.log("this is the players y pos" + this.player.y);
    //create platforms
    this.platformsCreate();

    //controls:
    this.game.input.keyboard.addKeyCapture([
        Phaser.Keyboard.LEFT,
        Phaser.Keyboard.RIGHT,
        Phaser.Keyboard.UP,
        Phaser.Keyboard.DOWN
    ]);

    //scaling
    this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
    this.scale.maxWidth = this.game.width;
    this.scale.maxHeight = this.game.height;
    this.scale.pageAlignHorizontally = true;
    this.scale.pageAlignVertically = true;
    this.scale.setScreenSize( true );

    //camera
    this.cameraYMin = 99999;
    this.platformYMin = 99999;

    //trigger the counter which destroys the floor
    this.destructionCounter();

    //initialize Platformcounter
    this.platformCounter = 0;

};

    /****************************************************************************************************************/
    /*                      Player related settings and controls                                                                  /
    /************************************************************************************************************** */

 GameState.prototype.update = function() {
     //collission checking
     this.physics.arcade.collide(this.player, this.ground);
     this.physics.arcade.collide(this.player, this.platforms);

     this.platforms.forEachAlive(function(platform){
         platform.body.y += 1;
     });

     //controls
     if (this.leftInputIsActive()) {
         this.player.body.acceleration.x = -this.ACCELERATION;
         this.player.animations.play('left');
     } else if (this.rightInputIsActive()) {
         this.player.body.acceleration.x = this.ACCELERATION;
         this.player.animations.play('right');
     } else {
         this.player.body.acceleration.x = 0;
         this.player.animations.stop();
         //we need to do this to display the static position when standing
         this.player.frame = 4;
     }

     //check whether the player is on the ground
     var onTheGround = this.player.body.touching.down;
     if (onTheGround && this.upInputIsActive()){
         this.player.body.velocity.y = this.JUMP_SPEED;
     }

     this.world.setBounds(0, -this.player.yChange, this.world.width, this.game.height + this.player.yChange);

     this.platforms.forEachAlive(function (elem) {
         this.platformYMin = Math.min(this.platformYMin, elem.y);
         if (elem.y > this.camera.y + this.game.height) {
             elem.kill();
             this.score();
         }
     }, this);

     //make player die on ground contact
     this.die();
 };

GameState.prototype.score = function(){
    this.platformCounter ++;
    console.log(this.platformCounter);
    this.game.debug.text(this.platformCounter, 20, 20);
};

GameState.prototype.platformsCreate = function(){
         //FUCK EVERYTHING
         this.platforms = this.add.group();
         this.platforms.enableBody = true;

         //determine the number of platforms you want to create (the wide ones)
         var numberofPlatforms = 1000;
         this.platforms.createMultiple( numberofPlatforms, 'block' );

         // create the base platform, with buffer on either side so that the hero doesn't fall through
         //this.platformsCreateOne( -16, this.world.height - 16, this.world.width + 16 );
         // create a batch of platforms that start to move up the level
         for( var i = 0; i < numberofPlatforms; i++ ) {
             //modify the last parameter in this line to change the width of the platforms
             this.platformsCreateOne( this.rnd.integerInRange( 0, this.world.width - 45 ), this.world.height - 100 - 100 * i, 160 );
         }
     };

GameState.prototype.platformsCreateOne = function( x, y, width) {
    // this is a helper function since writing all of this out can get verbose elsewhere
    var platform = this.platforms.getFirstDead();

         //should this turn out to be backstabby later on, simply remove the if statement and only write the codeblock
         //but this is textbook-like error handling....probably a little shady

         if(platform) {
             platform.reset(x, y);
             platform.scale.x = width;
             platform.scale.y = 16;
             platform.body.immovable = true;
             return platform;
         }
     };

GameState.prototype.destructionCounter = function(){
    //this sets a timer that calls the floor destruction method after a while
    game.time.events.add(Phaser.Timer.SECOND * 10, this.destroyFloor, this);
};

GameState.prototype.destroyFloor = function () {
    //this destroys the floor
    this.ground.destroy();
};

GameState.prototype.die = function () {
    //make the player die
    if(this.player.y > 725){
        this.game.add.sprite(250,200,'cat');
        //console.log("you have died");
        this.player.destroy();
        this.platforms.destroy();
        this.game.debug.text("Game over. Your score is" + this.platformCounter, 20, 20);

    }

};

//Player-left movement:
GameState.prototype.leftInputIsActive = function(){
    var isActive = false;

    isActive = this.input.keyboard.isDown(Phaser.Keyboard.LEFT);
    isActive |= (this.game.input.activePointer.isDown &&
                this.game.input.activePointer.x < this.game.width/4);

    return isActive;
};

GameState.prototype.rightInputIsActive = function(){
    var isActive = false;

    isActive = this.input.keyboard.isDown(Phaser.Keyboard.RIGHT);
    isActive |= (this.game.input.activePointer.isDown &&
                this.game.input.activePointer.x > this.game.width/2 + this.game.width/4);

    return isActive;
};

GameState.prototype.upInputIsActive = function(duration){
    var isActive = false;

    isActive = this.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR, duration);
    isActive |= (this.game.input.activePointer.justPressed(duration + 1000/60) &&
                this.game.input.activePointer.x > this.game.width/4 &&
                this.game.input.activePointer.x < this.game.width/2 + this.game.width/4);

    return isActive;
};

var game = new Phaser.Game(848,750, Phaser.AUTO, 'game');
game.state.add('game', GameState, true);<commit_msg>score output working<commit_after>var GameState = function (game) {
};

//load assets
GameState.prototype.preload = function(){

    this.game.load.image('map', 'assets/map.png'); // thjs is the background
    this.game.load.image('ground', 'assets/block.png');//this is the ground
    this.game.load.image('block', 'assets/pixel_1.png');//this is the image for the platforms, the block argument in the create function below links the sprite to the platform
    this.game.load.spritesheet('player', 'assets/dude.png', 32, 48);
    this.game.load.image('cat', 'assets/cat.png');

};

GameState.prototype.create = function () {
    //this.game.add.sprite(0,0, 'map');

    //movement:
    this.MAX_SPEED = 500; //px/s
    this.ACCELERATION = 1500; //px/s/s
    this.DRAG = 900; //px/s
    this.GRAVITY = 2600;
    this.JUMP_SPEED = -1000;
    //create player
    this.player = this.game.add.sprite(this.game.width/2, this.game.height - 90, 'player');
    this.player.anchor.set(0.5);

    this.player.yOrig = this.player.y;
    this.player.yChange = 0;

    //add player movement animations;
    this.player.animations.add('left', [0,1,2,3], 10, true);
    this.player.animations.add('right', [5,6,7,8], 10, true);

    //physics
    this.game.physics.enable(this.player, Phaser.Physics.ARCADE);
    //make player collide with the boundaries of the game
    this.player.body.collideWorldBounds = true;
    this.player.body.maxVelocity.setTo(this.MAX_SPEED, this.MAX_SPEED * 10);
    this.player.body.drag.setTo(this.DRAG,0);

    this.player.body.gravity.y = this.GRAVITY;
    this.player.body.checkCollision.up = false;
    //this.player.body.checkCollision.left = false;
    //this.player.body.checkCollision.right = false;

    //create floor
    this.ground = this.game.add.group();
    for(var x = 0; x < this.game.width; x += 32) {
        // Add the ground blocks, enable physics on each, make them immovable
        var groundBlock = this.game.add.sprite(x, this.game.height - 32, 'ground');
        this.game.physics.enable(groundBlock, Phaser.Physics.ARCADE);
        groundBlock.body.immovable = true;
        groundBlock.body.allowGravity = false;
        this.ground.add(groundBlock);
    }

    //console.log("this is the players y pos" + this.player.y);
    //create platforms
    this.platformsCreate();

    //controls:
    this.game.input.keyboard.addKeyCapture([
        Phaser.Keyboard.LEFT,
        Phaser.Keyboard.RIGHT,
        Phaser.Keyboard.UP,
        Phaser.Keyboard.DOWN
    ]);

    //scaling
    this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
    this.scale.maxWidth = this.game.width;
    this.scale.maxHeight = this.game.height;
    this.scale.pageAlignHorizontally = true;
    this.scale.pageAlignVertically = true;
    this.scale.setScreenSize( true );

    //camera
    this.cameraYMin = 99999;
    this.platformYMin = 99999;

    //trigger the counter which destroys the floor
    this.destructionCounter();

    //initialize Platformcounter
    this.platformCounter = 0;

};

    /****************************************************************************************************************/
    /*                      Player related settings and controls                                                                  /
    /************************************************************************************************************** */

 GameState.prototype.update = function() {
     //collission checking
     this.physics.arcade.collide(this.player, this.ground);
     this.physics.arcade.collide(this.player, this.platforms);

     this.platforms.forEachAlive(function(platform){
         platform.body.y += 1;
     });

     //controls
     if (this.leftInputIsActive()) {
         this.player.body.acceleration.x = -this.ACCELERATION;
         this.player.animations.play('left');
     } else if (this.rightInputIsActive()) {
         this.player.body.acceleration.x = this.ACCELERATION;
         this.player.animations.play('right');
     } else {
         this.player.body.acceleration.x = 0;
         this.player.animations.stop();
         //we need to do this to display the static position when standing
         this.player.frame = 4;
     }

     //check whether the player is on the ground
     var onTheGround = this.player.body.touching.down;
     if (onTheGround && this.upInputIsActive()){
         this.player.body.velocity.y = this.JUMP_SPEED;
     }

     this.world.setBounds(0, -this.player.yChange, this.world.width, this.game.height + this.player.yChange);

     this.platforms.forEachAlive(function (elem) {
         this.platformYMin = Math.min(this.platformYMin, elem.y);
         if (elem.y > this.camera.y + this.game.height) {
             elem.kill();
             this.score();
         }
     }, this);

     //make player die on ground contact
     this.die();
 };

GameState.prototype.score = function(){
    this.platformCounter ++;
    console.log(this.platformCounter);
    this.game.debug.text(this.platformCounter, 20, 20);
};

GameState.prototype.platformsCreate = function(){
         //FUCK EVERYTHING
         this.platforms = this.add.group();
         this.platforms.enableBody = true;

         //determine the number of platforms you want to create (the wide ones)
         var numberofPlatforms = 1000;
         this.platforms.createMultiple( numberofPlatforms, 'block' );

         // create the base platform, with buffer on either side so that the hero doesn't fall through
         //this.platformsCreateOne( -16, this.world.height - 16, this.world.width + 16 );
         // create a batch of platforms that start to move up the level
         for( var i = 0; i < numberofPlatforms; i++ ) {
             //modify the last parameter in this line to change the width of the platforms
             this.platformsCreateOne( this.rnd.integerInRange( 0, this.world.width - 45 ), this.world.height - 100 - 100 * i, 160 );
         }
     };

GameState.prototype.platformsCreateOne = function( x, y, width) {
    // this is a helper function since writing all of this out can get verbose elsewhere
    var platform = this.platforms.getFirstDead();

         //should this turn out to be backstabby later on, simply remove the if statement and only write the codeblock
         //but this is textbook-like error handling....probably a little shady

         if(platform) {
             platform.reset(x, y);
             platform.scale.x = width;
             platform.scale.y = 16;
             platform.body.immovable = true;
             return platform;
         }
     };

GameState.prototype.destructionCounter = function(){
    //this sets a timer that calls the floor destruction method after a while
    game.time.events.add(Phaser.Timer.SECOND * 10, this.destroyFloor, this);
};

GameState.prototype.destroyFloor = function () {
    //this destroys the floor
    this.ground.destroy();
};

GameState.prototype.die = function () {
    //make the player die
    if(this.player.y > 725){
        this.game.add.sprite(250,200,'cat');
        //console.log("you have died");
        this.player.destroy();
        this.platforms.destroy();
        //this.game.debug.text("Game over. Your score is" + this.platformCounter, 20, 20);
        this.displayText();
    }

};

GameState.prototype.displayText = function () {
    this.text = this.game.add.text(this.game.world.centerX, this.game.world.centerY,this.platformCounter + "Punkte", {
        font:"65px Arial",
        fill: "#ff0044",
        align: "center"
    });

    this.text.anchor.setTo(0.5, 0.5);
};

//Player-left movement:
GameState.prototype.leftInputIsActive = function(){
    var isActive = false;

    isActive = this.input.keyboard.isDown(Phaser.Keyboard.LEFT);
    isActive |= (this.game.input.activePointer.isDown &&
                this.game.input.activePointer.x < this.game.width/4);

    return isActive;
};

GameState.prototype.rightInputIsActive = function(){
    var isActive = false;

    isActive = this.input.keyboard.isDown(Phaser.Keyboard.RIGHT);
    isActive |= (this.game.input.activePointer.isDown &&
                this.game.input.activePointer.x > this.game.width/2 + this.game.width/4);

    return isActive;
};

GameState.prototype.upInputIsActive = function(duration){
    var isActive = false;

    isActive = this.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR, duration);
    isActive |= (this.game.input.activePointer.justPressed(duration + 1000/60) &&
                this.game.input.activePointer.x > this.game.width/4 &&
                this.game.input.activePointer.x < this.game.width/2 + this.game.width/4);

    return isActive;
};

var game = new Phaser.Game(848,750, Phaser.AUTO, 'game');
game.state.add('game', GameState, true);<|endoftext|>


<commit_before>var root_url = window.location.protocol + '//' + window.location.host;
var data,det_row;
var row_exists = false;

function loadSelectors() {
    $.getJSON(root_url + "/getvalues", function (data) {

        function compare(a, b) {
            a = a.toString().toLowerCase();
            b = b.toString().toLowerCase();
            if (a  b)
                return 1;
            return 0;
        }

        var tests = data['test'].sort(compare);
        var revs = data['rev'];
        var platforms = data['platform'].sort(compare);
        if (parseInt(results['showAll']) == 1) {
            document.getElementById("checkbox").checked = true;
        }

        for (var i in tests) {
            var newoption = document.createElement("option");
            newoption.id = "test";
            var value = tests[i][0];
            $("#test").append("<option value=\"" + value + "\">" + value + "</option>");
        }

        for (i in revs) {
            var newoption = document.createElement("option");
            newoption.id = "rev";
            var value = revs[i][0];
            $("#rev").append("<option value=\"" + value + "\">" + value + "</option>");
        }

        for (i in platforms) {
            var newoption = document.createElement("option");
            newoption.id = "platform";
            var value = platforms[i][0];
            $("#platform").append("<option value=\"" + value + "\">" + value + "</option>");
        }

        try {
            document.getElementById("rev").value = results['rev'];
            document.getElementById("test").selectedIndex = results['testIndex'];
            document.getElementById("platform").selectedIndex = results['platIndex'];
        } catch (e) {
            throw e;
        }

    });

    $('#button').click(function () {
        var rev = $('#rev').val();
        var test = $('#test').val();
        var platform = $('#platform').val();
        var showall = 0;
        var testIndex = $("select[id='test'] option:selected").index();
        var platIndex = $("select[id='platform'] option:selected").index();
        if ($('#checkbox').is(":checked")) {
            console.log("checked");
            showall = 1;
        }
        document.cookie = "platform = " + platform;
        document.cookie = "test = " + test;

        var href = "alerts.html";
        var flag = '?';
        if (rev && rev != '') {
            href += flag + "rev=" + rev;
            flag = '&';
        }
        if (showall && showall != '') {
            href += flag + "showAll=" + showall;
            flag = '&';
        }
        if (testIndex && testIndex != '') {
            href += flag + "testIndex=" + testIndex;
            flag = '&';
        }
        if (platIndex && platIndex != '') {
            href += flag + "platIndex=" + platIndex;
            flag = '&';
        }
        location.href = href;

    });
}

function hideMerged(originalkeyrev, showall) {
    var req = new XMLHttpRequest();
    req.onload = function (e) {
        var raw_data = JSON.parse(req.response);

        var fields = ["date", "branch", "test", "platform", "percent", "graphurl", "changeset", "tbplurl", "comment", "bug", "status"]
        var alerts = raw_data.alerts;

        var keyrev = "";
        var tbl = "";
        // insert revisions into lower table
        for (var alert in alerts) {
            if (alerts[alert]["mergedfrom"] == originalkeyrev) {
                tbl = document.getElementById(originalkeyrev + "-tbl");
            } else {
                continue;
            }
            var row = $(document.getElementById(alerts[alert]["id"] + "-" + originalkeyrev));
            if (row) {
                row.remove();
            }
        }
        var mergedfromhtml = "view merged alerts";

        $(document.getElementById(originalkeyrev + "-hdr")).html("
" + originalkeyrev + "
" + mergedfromhtml);
    }
    req.open('get', root_url + '/mergedalerts?keyrev=' + originalkeyrev, true);
    req.send();
}

function showMerged(originalkeyrev, showall) {
    var req = new XMLHttpRequest();
    req.onload = function (e) {
        var raw_data = JSON.parse(req.response);
        var alerts = raw_data.alerts;

        var tbl = "";
        // insert revisions into lower table
        for (var alert in alerts) {
            if (alerts[alert]["mergedfrom"] != originalkeyrev) {
                continue;
            }
            tbl = document.getElementById(originalkeyrev + "-tbl");
            addAlertToUI(tbl, alerts[alert], showall, originalkeyrev);
        }
        var mergedfromhtml = "hide merged alerts";
        $(document.getElementById(originalkeyrev + "-hdr")).html("
" + originalkeyrev + "
" + mergedfromhtml);
    }
    req.open('get', root_url + '/mergedalerts?keyrev=' + originalkeyrev, true);
    req.send();
}

function addMergedLinks(showall) {
    var req = new XMLHttpRequest();
    req.onload = function (e) {
        var raw_data = JSON.parse(req.response);

        var fields = ["id", "date", "bug", "status", "keyrevision", "bugcount", "mergedfrom"]
        var alerts = raw_data.alerts;

        var count = 0;
        for (var alert in alerts) {
            if (alerts[alert]['mergedfrom'] != '') {
                var mf = alerts[alert]['mergedfrom'];
                if ($(document.getElementById(mf + "-hdr")).html() == "") {
                    continue;
                }

                var mergedfromhtml = "view merged alerts";
                $(document.getElementById(mf + "-hdr")).html("
" + mf + "
" + mergedfromhtml);
            }
        }
    }
    req.open('get', root_url + '/mergedids', true);
    req.send();
}

function updateStatus(alertid, duplicate, bugid, mergedfrom) {
    var status = $(document.getElementById(alertid + "-status")).val();
    if (status == 'Duplicate') {
        // popup window with field for duplicate, seeded with alert['duplicate']
        // consider merged rev if needed
        suggestedDuplicate = duplicate;
        if (suggestedDuplicate == 'null' || suggestedDuplicate == '') {
            suggestedDuplicate = mergedfrom;
        }

        AddDuplicateUI.openDuplicateBox(alertid, suggestedDuplicate);
    } else if (status == 'Backout') {
        var bug = bugid;
        if (bug == '') {
            bug = $(document.getElementById(alertid + "-bug")).val();
        }
        AddBugUI.openBugBox(alertid, bug, 'Backout');
    } else {
        $.ajax({
            url: "updatestatus",
            type: "POST",
            data: {
                id: alertid,
                status: status,
            }
        });
    }
}

function updateBug(alertid, bugid, status) {
    var bug = bugid;
    if (bug == '') {
        bug = $(document.getElementById(alertid + "-bug")).val();
    }
    if (status == '') {
        status = 'NEW';
    }

    AddBugUI.openBugBox(alertid, bug, status);
}

function updateTbplURL(alertid, tbplurl) {
    AddTbplUI.openTbplBox(alertid, tbplurl);
}

function addAlertToUI(tbl, alert, showall) {
    addMergedAlertToUI(tbl, alert, showall, "");
}

// Function idDescending sorts the objects in the descending order of their id. This way, we can view the most recent alerts at the top.
// The objects have been sorted based on their id and not on their date as sorting by the date field was not working.
function idDescending(a, b) {
    if (a["id"] < b["id"]) {
        return 1;
    }
    else {
        return -1;
    }
}

function showDetails(i) {
    var table = document.getElementById("detail");
    if (row_exists) {

        det_row.deleteCell(0);
        det_row.deleteCell(0);
        det_row.deleteCell(0);
        det_row.deleteCell(0);
        row_exists = false;

    }
    det_row = table.insertRow(0);
    var cell0 = det_row.insertCell(0);
    cell0.innerHTML = " "+ data[i]["bug"] +" ";
    var cell1 = det_row.insertCell(1);
    cell1.innerHTML = "  graphurl  ";
    var cell2 = det_row.insertCell(2);
    cell2.innerHTML = "  tbplurl   ";
    var cell3 = det_row.insertCell(3);
    cell3.innerHTML = "  changeset   ";
    row_exists=true;
}

function loadAllAlertsTable(showall, rev, test, platform, current, improve) {
    if (rev == '') {
        document.getElementById("warn").innerHTML = "
Table view is available per revision and not for the entire list
";
    }
    document.getElementById("jump").innerHTML="
Toggle View
";
    document.getElementById("hide").innerHTML="
Toggle Improvement
";
    var req = new XMLHttpRequest();
    req.onload = function(e) {
        var raw_data = JSON.parse(req.response);
        data = raw_data.alerts;
        var plats = [];
        var tests = [];
        var rowlist = [];
        var celllist= [];

        var table = document.getElementById("data");
        var row = table.insertRow(0);
        var cell = row.insertCell(0);
        cell.innerHTML=" ";
        for (var i=0;i<data.length;i++) {
            if (plats.indexOf(data[i]["platform"]) == -1) {
                plats.push(data[i]["platform"]);
                cell = row.insertCell(1);
                cell.innerHTML=""+data[i]["platform"]+"";
            }

            if (tests.indexOf(data[i]["test"]) == -1) {
                tests.push(data[i]["test"]);
                var row0 = table.insertRow(1);
                rowlist.push(row0);
                var cell0 = row0.insertCell(0);
                cell0.innerHTML =""+data[i]["test"]+"";
            }
        }
        for (var y=0;y<tests.length;y++) {
            for (var x=0;x<plats.length;x++) {
                var cell00= rowlist[y].insertCell(1)
                celllist.push(cell00);
            }
        }
        for (var i=0;i<data.length;i++) {
            var cell1 = celllist[(tests.indexOf(data[i]["test"])*plats.length)+plats.indexOf(data[i]["platform"])];
            var percent = parseInt((data[i]["percent"].split("%"))[0]);
            if (percent<=-10) {
                cell1.style.backgroundColor="red";
            } else if (percent<0 && percent>-10) {
                cell1.style.backgroundColor="orange";
            } else if (percent>0 && percent<10) {
                if(improve == 1)
                    continue;
                cell1.style.backgroundColor="lime";
            } else {
                if(improve == 1)
                    continue;
                cell1.style.backgroundColor="green";
            }
            cell1.innerHTML = "
"+data[i]["percent"]+"
";
        }
    }
    req.open('get', root_url+'/alertsbyrev?keyrevision='+rev, true);
    req.send();
}

function loadAllAlerts(showall, rev, test, platform, current) {
    var req = new XMLHttpRequest();
    req.onload = function (e) {
        var raw_data = JSON.parse(req.response);
        var alerts = raw_data.alerts;
        alerts.sort(idDescending);

        var keyrev = "";
        var tbl = "";
        // insert revisions into lower table
        for (var alert = 0; alert < alerts.length; alert++) {
            if (alerts[alert]["keyrevision"] != keyrev) {
                keyrev = alerts[alert]["keyrevision"];
                if ($(document.getElementById(keyrev + "-hdr")).html() == null) {
                    var newdiv = document.createElement("div");
                    newdiv.id = keyrev;
                    $("#revisions").append(newdiv);

                    $(document.getElementById(keyrev)).append("
" + keyrev + "
");

                }
                if ($(document.getElementById(keyrev + "-tbl")).html() == null) {
                    var kdiv = document.getElementById(keyrev);
                    var newtbl = document.createElement("table");
                    newtbl.id = keyrev + '-tbl';
                    $(document.getElementById(keyrev)).append(newtbl);
                }

                $(document.getElementById(keyrev + "-hdr")).html("
" + keyrev + "
");
                tbl = document.getElementById(keyrev + "-tbl");
            }
            var r = addAlertToUI(tbl, alerts[alert], showall);
            if ($(document.getElementById(keyrev + '-tbl')).find('tr').size() == 0) {
                $(document.getElementById(keyrev + "-hdr")).html("");
            }
        }
        addMergedLinks(showall);
        AddCommentUI.init();
        AddDuplicateUI.init();
        AddBugUI.init();
        AddTbplUI.init();
    }
    if (current == "true") {
        url = "/alertsbyrev";
    } else {
        url = "/alertsbyexpiredrev";
    }
    flag = '?';
    if (rev && rev != '') {
        url += flag + "rev=" + rev;
    }
    if (test && test != '') {
        url += flag + "test=" + test;
    }
    if (platform && platform != '') {
        url += flag + "platform=" + platform;
    }
    req.open('get', (root_url + url), true);
    req.send();
}

function editAlert(id, body) {
    return function () {
        AddCommentUI.openCommentBox(id, body);
    }
}

function hideDiv(name) {
    document.getElementById(name).style.display = "none";
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}

function getJsonFromUrl() {
    var query = location.search.substr(1);
    var data = query.split("&");
    var result = {};
    for (var i = 0; i < data.length; i++) {
        var item = data[i].split("=");
        if (item[0].trim().length > 0) result[item[0]] = item[1];
    }
    return result;
}

//RETURN FIRST NOT NULL, AND DEFINED VALUE
function nvl() {
    var args = arguments.length == 1 ? arguments[0] : arguments;
    var a;
    for (var i = 0; i < args.length; i++) {
        a = args[i];
        if (a !== undefined && a != null) return a;
    }//for
    return null;
}//method

coalesce = nvl;
<commit_msg>Removed blank argument of addMergedAlertToUI<commit_after>var root_url = window.location.protocol + '//' + window.location.host;
var data,det_row;
var row_exists = false;

function loadSelectors() {
    $.getJSON(root_url + "/getvalues", function (data) {

        function compare(a, b) {
            a = a.toString().toLowerCase();
            b = b.toString().toLowerCase();
            if (a  b)
                return 1;
            return 0;
        }

        var tests = data['test'].sort(compare);
        var revs = data['rev'];
        var platforms = data['platform'].sort(compare);
        if (parseInt(results['showAll']) == 1) {
            document.getElementById("checkbox").checked = true;
        }

        for (var i in tests) {
            var newoption = document.createElement("option");
            newoption.id = "test";
            var value = tests[i][0];
            $("#test").append("<option value=\"" + value + "\">" + value + "</option>");
        }

        for (i in revs) {
            var newoption = document.createElement("option");
            newoption.id = "rev";
            var value = revs[i][0];
            $("#rev").append("<option value=\"" + value + "\">" + value + "</option>");
        }

        for (i in platforms) {
            var newoption = document.createElement("option");
            newoption.id = "platform";
            var value = platforms[i][0];
            $("#platform").append("<option value=\"" + value + "\">" + value + "</option>");
        }

        try {
            document.getElementById("rev").value = results['rev'];
            document.getElementById("test").selectedIndex = results['testIndex'];
            document.getElementById("platform").selectedIndex = results['platIndex'];
        } catch (e) {
            throw e;
        }

    });

    $('#button').click(function () {
        var rev = $('#rev').val();
        var test = $('#test').val();
        var platform = $('#platform').val();
        var showall = 0;
        var testIndex = $("select[id='test'] option:selected").index();
        var platIndex = $("select[id='platform'] option:selected").index();
        if ($('#checkbox').is(":checked")) {
            console.log("checked");
            showall = 1;
        }
        document.cookie = "platform = " + platform;
        document.cookie = "test = " + test;

        var href = "alerts.html";
        var flag = '?';
        if (rev && rev != '') {
            href += flag + "rev=" + rev;
            flag = '&';
        }
        if (showall && showall != '') {
            href += flag + "showAll=" + showall;
            flag = '&';
        }
        if (testIndex && testIndex != '') {
            href += flag + "testIndex=" + testIndex;
            flag = '&';
        }
        if (platIndex && platIndex != '') {
            href += flag + "platIndex=" + platIndex;
            flag = '&';
        }
        location.href = href;

    });
}

function hideMerged(originalkeyrev, showall) {
    var req = new XMLHttpRequest();
    req.onload = function (e) {
        var raw_data = JSON.parse(req.response);

        var fields = ["date", "branch", "test", "platform", "percent", "graphurl", "changeset", "tbplurl", "comment", "bug", "status"]
        var alerts = raw_data.alerts;

        var keyrev = "";
        var tbl = "";
        // insert revisions into lower table
        for (var alert in alerts) {
            if (alerts[alert]["mergedfrom"] == originalkeyrev) {
                tbl = document.getElementById(originalkeyrev + "-tbl");
            } else {
                continue;
            }
            var row = $(document.getElementById(alerts[alert]["id"] + "-" + originalkeyrev));
            if (row) {
                row.remove();
            }
        }
        var mergedfromhtml = "view merged alerts";

        $(document.getElementById(originalkeyrev + "-hdr")).html("
" + originalkeyrev + "
" + mergedfromhtml);
    }
    req.open('get', root_url + '/mergedalerts?keyrev=' + originalkeyrev, true);
    req.send();
}

function showMerged(originalkeyrev, showall) {
    var req = new XMLHttpRequest();
    req.onload = function (e) {
        var raw_data = JSON.parse(req.response);
        var alerts = raw_data.alerts;

        var tbl = "";
        // insert revisions into lower table
        for (var alert in alerts) {
            if (alerts[alert]["mergedfrom"] != originalkeyrev) {
                continue;
            }
            tbl = document.getElementById(originalkeyrev + "-tbl");
            addAlertToUI(tbl, alerts[alert], showall, originalkeyrev);
        }
        var mergedfromhtml = "hide merged alerts";
        $(document.getElementById(originalkeyrev + "-hdr")).html("
" + originalkeyrev + "
" + mergedfromhtml);
    }
    req.open('get', root_url + '/mergedalerts?keyrev=' + originalkeyrev, true);
    req.send();
}

function addMergedLinks(showall) {
    var req = new XMLHttpRequest();
    req.onload = function (e) {
        var raw_data = JSON.parse(req.response);

        var fields = ["id", "date", "bug", "status", "keyrevision", "bugcount", "mergedfrom"]
        var alerts = raw_data.alerts;

        var count = 0;
        for (var alert in alerts) {
            if (alerts[alert]['mergedfrom'] != '') {
                var mf = alerts[alert]['mergedfrom'];
                if ($(document.getElementById(mf + "-hdr")).html() == "") {
                    continue;
                }

                var mergedfromhtml = "view merged alerts";
                $(document.getElementById(mf + "-hdr")).html("
" + mf + "
" + mergedfromhtml);
            }
        }
    }
    req.open('get', root_url + '/mergedids', true);
    req.send();
}

function updateStatus(alertid, duplicate, bugid, mergedfrom) {
    var status = $(document.getElementById(alertid + "-status")).val();
    if (status == 'Duplicate') {
        // popup window with field for duplicate, seeded with alert['duplicate']
        // consider merged rev if needed
        suggestedDuplicate = duplicate;
        if (suggestedDuplicate == 'null' || suggestedDuplicate == '') {
            suggestedDuplicate = mergedfrom;
        }

        AddDuplicateUI.openDuplicateBox(alertid, suggestedDuplicate);
    } else if (status == 'Backout') {
        var bug = bugid;
        if (bug == '') {
            bug = $(document.getElementById(alertid + "-bug")).val();
        }
        AddBugUI.openBugBox(alertid, bug, 'Backout');
    } else {
        $.ajax({
            url: "updatestatus",
            type: "POST",
            data: {
                id: alertid,
                status: status,
            }
        });
    }
}

function updateBug(alertid, bugid, status) {
    var bug = bugid;
    if (bug == '') {
        bug = $(document.getElementById(alertid + "-bug")).val();
    }
    if (status == '') {
        status = 'NEW';
    }

    AddBugUI.openBugBox(alertid, bug, status);
}

function updateTbplURL(alertid, tbplurl) {
    AddTbplUI.openTbplBox(alertid, tbplurl);
}

function addAlertToUI(tbl, alert, showall) {
    addMergedAlertToUI(tbl, alert, showall);
}

// Function idDescending sorts the objects in the descending order of their id. This way, we can view the most recent alerts at the top.
// The objects have been sorted based on their id and not on their date as sorting by the date field was not working.
function idDescending(a, b) {
    if (a["id"] < b["id"]) {
        return 1;
    }
    else {
        return -1;
    }
}

function showDetails(i) {
    var table = document.getElementById("detail");
    if (row_exists) {

        det_row.deleteCell(0);
        det_row.deleteCell(0);
        det_row.deleteCell(0);
        det_row.deleteCell(0);
        row_exists = false;

    }
    det_row = table.insertRow(0);
    var cell0 = det_row.insertCell(0);
    cell0.innerHTML = " "+ data[i]["bug"] +" ";
    var cell1 = det_row.insertCell(1);
    cell1.innerHTML = "  graphurl  ";
    var cell2 = det_row.insertCell(2);
    cell2.innerHTML = "  tbplurl   ";
    var cell3 = det_row.insertCell(3);
    cell3.innerHTML = "  changeset   ";
    row_exists=true;
}

function loadAllAlertsTable(showall, rev, test, platform, current, improve) {
    if (rev == '') {
        document.getElementById("warn").innerHTML = "
Table view is available per revision and not for the entire list
";
    }
    document.getElementById("jump").innerHTML="
Toggle View
";
    document.getElementById("hide").innerHTML="
Toggle Improvement
";
    var req = new XMLHttpRequest();
    req.onload = function(e) {
        var raw_data = JSON.parse(req.response);
        data = raw_data.alerts;
        var plats = [];
        var tests = [];
        var rowlist = [];
        var celllist= [];

        var table = document.getElementById("data");
        var row = table.insertRow(0);
        var cell = row.insertCell(0);
        cell.innerHTML=" ";
        for (var i=0;i<data.length;i++) {
            if (plats.indexOf(data[i]["platform"]) == -1) {
                plats.push(data[i]["platform"]);
                cell = row.insertCell(1);
                cell.innerHTML=""+data[i]["platform"]+"";
            }

            if (tests.indexOf(data[i]["test"]) == -1) {
                tests.push(data[i]["test"]);
                var row0 = table.insertRow(1);
                rowlist.push(row0);
                var cell0 = row0.insertCell(0);
                cell0.innerHTML =""+data[i]["test"]+"";
            }
        }
        for (var y=0;y<tests.length;y++) {
            for (var x=0;x<plats.length;x++) {
                var cell00= rowlist[y].insertCell(1)
                celllist.push(cell00);
            }
        }
        for (var i=0;i<data.length;i++) {
            var cell1 = celllist[(tests.indexOf(data[i]["test"])*plats.length)+plats.indexOf(data[i]["platform"])];
            var percent = parseInt((data[i]["percent"].split("%"))[0]);
            if (percent<=-10) {
                cell1.style.backgroundColor="red";
            } else if (percent<0 && percent>-10) {
                cell1.style.backgroundColor="orange";
            } else if (percent>0 && percent<10) {
                if(improve == 1)
                    continue;
                cell1.style.backgroundColor="lime";
            } else {
                if(improve == 1)
                    continue;
                cell1.style.backgroundColor="green";
            }
            cell1.innerHTML = "
"+data[i]["percent"]+"
";
        }
    }
    req.open('get', root_url+'/alertsbyrev?keyrevision='+rev, true);
    req.send();
}

function loadAllAlerts(showall, rev, test, platform, current) {
    var req = new XMLHttpRequest();
    req.onload = function (e) {
        var raw_data = JSON.parse(req.response);
        var alerts = raw_data.alerts;
        alerts.sort(idDescending);

        var keyrev = "";
        var tbl = "";
        // insert revisions into lower table
        for (var alert = 0; alert < alerts.length; alert++) {
            if (alerts[alert]["keyrevision"] != keyrev) {
                keyrev = alerts[alert]["keyrevision"];
                if ($(document.getElementById(keyrev + "-hdr")).html() == null) {
                    var newdiv = document.createElement("div");
                    newdiv.id = keyrev;
                    $("#revisions").append(newdiv);

                    $(document.getElementById(keyrev)).append("
" + keyrev + "
");

                }
                if ($(document.getElementById(keyrev + "-tbl")).html() == null) {
                    var kdiv = document.getElementById(keyrev);
                    var newtbl = document.createElement("table");
                    newtbl.id = keyrev + '-tbl';
                    $(document.getElementById(keyrev)).append(newtbl);
                }

                $(document.getElementById(keyrev + "-hdr")).html("
" + keyrev + "
");
                tbl = document.getElementById(keyrev + "-tbl");
            }
            var r = addAlertToUI(tbl, alerts[alert], showall);
            if ($(document.getElementById(keyrev + '-tbl')).find('tr').size() == 0) {
                $(document.getElementById(keyrev + "-hdr")).html("");
            }
        }
        addMergedLinks(showall);
        AddCommentUI.init();
        AddDuplicateUI.init();
        AddBugUI.init();
        AddTbplUI.init();
    }
    if (current == "true") {
        url = "/alertsbyrev";
    } else {
        url = "/alertsbyexpiredrev";
    }
    flag = '?';
    if (rev && rev != '') {
        url += flag + "rev=" + rev;
    }
    if (test && test != '') {
        url += flag + "test=" + test;
    }
    if (platform && platform != '') {
        url += flag + "platform=" + platform;
    }
    req.open('get', (root_url + url), true);
    req.send();
}

function editAlert(id, body) {
    return function () {
        AddCommentUI.openCommentBox(id, body);
    }
}

function hideDiv(name) {
    document.getElementById(name).style.display = "none";
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}

function getJsonFromUrl() {
    var query = location.search.substr(1);
    var data = query.split("&");
    var result = {};
    for (var i = 0; i < data.length; i++) {
        var item = data[i].split("=");
        if (item[0].trim().length > 0) result[item[0]] = item[1];
    }
    return result;
}

//RETURN FIRST NOT NULL, AND DEFINED VALUE
function nvl() {
    var args = arguments.length == 1 ? arguments[0] : arguments;
    var a;
    for (var i = 0; i < args.length; i++) {
        a = args[i];
        if (a !== undefined && a != null) return a;
    }//for
    return null;
}//method

coalesce = nvl;
<|endoftext|>


<commit_before>import _ from 'underscore';
import {CollectionView, CompositeView} from 'backbone.marionette'

var _insertAfterFn1 = CollectionView.prototype._insertAfter;
var _insertAfterFn2 = CompositeView.prototype._insertAfter;

function _insertAfter(method, childView) {
    // Ensure delay
    if (_.isUndefined(this._animateDelay)) {
        this._animateDelay = 0;
    }

    // Reset delay
    _.delay(() => {
        this._animateDelay = 0;
    }, 1300);

    childView.$el.css('opacity', 0);

    method.call(this, childView);

    this._animateDelay = Math.min(1200, this._animateDelay + 100);

    childView.$el.delay(this._animateDelay).animate({ opacity: 1 }, 150);
}

_.extend(CollectionView.prototype, {
    _insertAfter: function (childView) {
        _insertAfter.call(this, _insertAfterFn1, childView);
    }
});

_.extend(CompositeView.prototype, {
    _insertAfter: function (childView) {
        _insertAfter.call(this, _insertAfterFn2, childView);
    }
});<commit_msg>Added comments<commit_after>import _ from 'underscore';
import {CollectionView, CompositeView} from 'backbone.marionette'

var _insertAfterFn1 = CollectionView.prototype._insertAfter;
var _insertAfterFn2 = CompositeView.prototype._insertAfter;

function _insertAfter(method, childView) {
    // Ensure delay
    if (_.isUndefined(this._animateDelay)) {
        this._animateDelay = 0;
    }

    // Reset delay
    _.delay(() => {
        this._animateDelay = 0;
    }, 1300);

    // Initial hide element
    childView.$el.css('opacity', 0);

    // Call original _insertAfter method
    method.call(this, childView);

    // Calculate delay
    this._animateDelay = Math.min(1200, this._animateDelay + 100);

    // FadeIn
    childView.$el.delay(this._animateDelay).animate({ opacity: 1 }, 150);
}

_.extend(CollectionView.prototype, {
    _insertAfter: function (childView) {
        _insertAfter.call(this, _insertAfterFn1, childView);
    }
});

_.extend(CompositeView.prototype, {
    _insertAfter: function (childView) {
        _insertAfter.call(this, _insertAfterFn2, childView);
    }
});<|endoftext|>


<commit_before>var DESCRIPTORS = require('../internals/descriptors');
var global = require('../internals/global');
var isForced = require('../internals/is-forced');
var inheritIfRequired = require('../internals/inherit-if-required');
var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
var defineProperty = require('../internals/object-define-property').f;
var getOwnPropertyNames = require('../internals/object-get-own-property-names').f;
var isRegExp = require('../internals/is-regexp');
var getFlags = require('../internals/regexp-flags');
var stickyHelpers = require('../internals/regexp-sticky-helpers');
var redefine = require('../internals/redefine');
var fails = require('../internals/fails');
var has = require('../internals/has');
var enforceInternalState = require('../internals/internal-state').enforce;
var setSpecies = require('../internals/set-species');
var wellKnownSymbol = require('../internals/well-known-symbol');
var UNSUPPORTED_DOT_ALL = require('../internals/regexp-unsupported-dot-all');
var UNSUPPORTED_NCG = require('../internals/regexp-unsupported-ncg');

var MATCH = wellKnownSymbol('match');
var NativeRegExp = global.RegExp;
var RegExpPrototype = NativeRegExp.prototype;
// TODO: Use only propper RegExpIdentifierName
var IS_NCG = /^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/;
var re1 = /a/g;
var re2 = /a/g;

// "new" should create a new object, old webkit bug
var CORRECT_NEW = new NativeRegExp(re1) !== re1;

var UNSUPPORTED_Y = stickyHelpers.UNSUPPORTED_Y;

var BASE_FORCED = DESCRIPTORS &&
  (!CORRECT_NEW || UNSUPPORTED_Y || UNSUPPORTED_DOT_ALL || UNSUPPORTED_NCG || fails(function () {
    re2[MATCH] = false;
    // RegExp constructor can alter flags and IsRegExp works correct with @@match
    return NativeRegExp(re1) != re1 || NativeRegExp(re2) == re2 || NativeRegExp(re1, 'i') != '/a/i';
  }));

var handleDotAll = function (string) {
  var length = string.length;
  var index = 0;
  var result = '';
  var brackets = false;
  var chr;
  for (; index <= length; index++) {
    chr = string.charAt(index);
    if (chr === '\\') {
      result += chr + string.charAt(++index);
      continue;
    }
    if (!brackets && chr === '.') {
      result += '[\\s\\S]';
    } else {
      if (chr === '[') {
        brackets = true;
      } else if (chr === ']') {
        brackets = false;
      } result += chr;
    }
  } return result;
};

var handleNCG = function (string) {
  var length = string.length;
  var index = 0;
  var result = '';
  var named = [];
  var names = {};
  var brackets = false;
  var ncg = false;
  var groupid = 0;
  var groupname = '';
  var chr;
  for (; index <= length; index++) {
    chr = string.charAt(index);
    if (chr === '\\') {
      chr = chr + string.charAt(++index);
    } else if (chr === ']') {
      brackets = false;
    } else if (!brackets) switch (true) {
      case chr === '[':
        brackets = true;
        break;
      case chr === '(':
        if (IS_NCG.test(string.slice(index + 1))) {
          index += 2;
          ncg = true;
        }
        result += chr;
        groupid++;
        continue;
      case chr === '>' && ncg:
        if (groupname === '' || has(names, groupname)) {
          throw new SyntaxError('Invalid capture group name');
        }
        names[groupname] = true;
        named.push([groupname, groupid]);
        ncg = false;
        groupname = '';
        continue;
    }
    if (ncg) groupname += chr;
    else result += chr;
  } return [result, named];
};

// `RegExp` constructor
// https://tc39.es/ecma262/#sec-regexp-constructor
if (isForced('RegExp', BASE_FORCED)) {
  var RegExpWrapper = function RegExp(pattern, flags) {
    var thisIsRegExp = this instanceof RegExpWrapper;
    var patternIsRegExp = isRegExp(pattern);
    var flagsAreUndefined = flags === undefined;
    var groups = [];
    var rawPattern, rawFlags, dotAll, sticky, handled, result, state;

    if (!thisIsRegExp && patternIsRegExp && pattern.constructor === RegExpWrapper && flagsAreUndefined) {
      return pattern;
    }

    if (CORRECT_NEW) {
      if (patternIsRegExp && !flagsAreUndefined) pattern = pattern.source;
    } else if (pattern instanceof RegExpWrapper) {
      if (flagsAreUndefined) flags = getFlags.call(pattern);
      pattern = pattern.source;
    }

    pattern = pattern === undefined ? '' : String(pattern);
    if (pattern === '') pattern = '(?:)';
    rawPattern = pattern;

    if (UNSUPPORTED_DOT_ALL) {
      dotAll = !!flags && flags.indexOf('s') > -1;
      if (dotAll) flags = flags.replace(/s/g, '');
    }

    rawFlags = flags;

    if (UNSUPPORTED_Y) {
      sticky = !!flags && flags.indexOf('y') > -1;
      if (sticky) flags = flags.replace(/y/g, '');
    }

    if (UNSUPPORTED_NCG) {
      handled = handleNCG(pattern);
      pattern = handled[0];
      groups = handled[1];
    }

    result = inheritIfRequired(
      CORRECT_NEW ? new NativeRegExp(pattern, flags) : NativeRegExp(pattern, flags),
      thisIsRegExp ? this : RegExpPrototype,
      RegExpWrapper
    );

    if (dotAll || sticky || groups.length) {
      state = enforceInternalState(result);
      if (dotAll) {
        state.dotAll = true;
        state.raw = RegExpWrapper(handleDotAll(pattern), rawFlags);
      }
      if (sticky) state.sticky = true;
      if (groups.length) state.groups = groups;
    }

    if (pattern !== rawPattern) try {
      // fails in old engines, but we have no alternatives for unsupported regex syntax
      createNonEnumerableProperty(result, 'source', rawPattern);
    } catch (error) { /* empty */ }

    return result;
  };

  var proxy = function (key) {
    key in RegExpWrapper || defineProperty(RegExpWrapper, key, {
      configurable: true,
      get: function () { return NativeRegExp[key]; },
      set: function (it) { NativeRegExp[key] = it; }
    });
  };

  for (var keys = getOwnPropertyNames(NativeRegExp), index = 0; keys.length > index;) {
    proxy(keys[index++]);
  }

  RegExpPrototype.constructor = RegExpWrapper;
  RegExpWrapper.prototype = RegExpPrototype;
  redefine(global, 'RegExp', RegExpWrapper);
}

// https://tc39.es/ecma262/#sec-get-regexp-@@species
setSpecies('RegExp');
<commit_msg>some protections<commit_after>var DESCRIPTORS = require('../internals/descriptors');
var global = require('../internals/global');
var isForced = require('../internals/is-forced');
var inheritIfRequired = require('../internals/inherit-if-required');
var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
var defineProperty = require('../internals/object-define-property').f;
var getOwnPropertyNames = require('../internals/object-get-own-property-names').f;
var isRegExp = require('../internals/is-regexp');
var getFlags = require('../internals/regexp-flags');
var stickyHelpers = require('../internals/regexp-sticky-helpers');
var redefine = require('../internals/redefine');
var fails = require('../internals/fails');
var has = require('../internals/has');
var enforceInternalState = require('../internals/internal-state').enforce;
var setSpecies = require('../internals/set-species');
var wellKnownSymbol = require('../internals/well-known-symbol');
var UNSUPPORTED_DOT_ALL = require('../internals/regexp-unsupported-dot-all');
var UNSUPPORTED_NCG = require('../internals/regexp-unsupported-ncg');

var MATCH = wellKnownSymbol('match');
var NativeRegExp = global.RegExp;
var RegExpPrototype = NativeRegExp.prototype;
// TODO: Use only propper RegExpIdentifierName
var IS_NCG = /^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/;
var re1 = /a/g;
var re2 = /a/g;

// "new" should create a new object, old webkit bug
var CORRECT_NEW = new NativeRegExp(re1) !== re1;

var UNSUPPORTED_Y = stickyHelpers.UNSUPPORTED_Y;

var BASE_FORCED = DESCRIPTORS &&
  (!CORRECT_NEW || UNSUPPORTED_Y || UNSUPPORTED_DOT_ALL || UNSUPPORTED_NCG || fails(function () {
    re2[MATCH] = false;
    // RegExp constructor can alter flags and IsRegExp works correct with @@match
    return NativeRegExp(re1) != re1 || NativeRegExp(re2) == re2 || NativeRegExp(re1, 'i') != '/a/i';
  }));

var handleDotAll = function (string) {
  var length = string.length;
  var index = 0;
  var result = '';
  var brackets = false;
  var chr;
  for (; index <= length; index++) {
    chr = string.charAt(index);
    if (chr === '\\') {
      result += chr + string.charAt(++index);
      continue;
    }
    if (!brackets && chr === '.') {
      result += '[\\s\\S]';
    } else {
      if (chr === '[') {
        brackets = true;
      } else if (chr === ']') {
        brackets = false;
      } result += chr;
    }
  } return result;
};

var handleNCG = function (string) {
  var length = string.length;
  var index = 0;
  var result = '';
  var named = [];
  var names = {};
  var brackets = false;
  var ncg = false;
  var groupid = 0;
  var groupname = '';
  var chr;
  for (; index <= length; index++) {
    chr = string.charAt(index);
    if (chr === '\\') {
      chr = chr + string.charAt(++index);
    } else if (chr === ']') {
      brackets = false;
    } else if (!brackets) switch (true) {
      case chr === '[':
        brackets = true;
        break;
      case chr === '(':
        if (IS_NCG.test(string.slice(index + 1))) {
          index += 2;
          ncg = true;
        }
        result += chr;
        groupid++;
        continue;
      case chr === '>' && ncg:
        if (groupname === '' || has(names, groupname)) {
          throw new SyntaxError('Invalid capture group name');
        }
        names[groupname] = true;
        named.push([groupname, groupid]);
        ncg = false;
        groupname = '';
        continue;
    }
    if (ncg) groupname += chr;
    else result += chr;
  } return [result, named];
};

// `RegExp` constructor
// https://tc39.es/ecma262/#sec-regexp-constructor
if (isForced('RegExp', BASE_FORCED)) {
  var RegExpWrapper = function RegExp(pattern, flags) {
    var thisIsRegExp = this instanceof RegExpWrapper;
    var patternIsRegExp = isRegExp(pattern);
    var flagsAreUndefined = flags === undefined;
    var groups = [];
    var rawPattern, rawFlags, dotAll, sticky, handled, result, state;

    if (!thisIsRegExp && patternIsRegExp && pattern.constructor === RegExpWrapper && flagsAreUndefined) {
      return pattern;
    }

    if (CORRECT_NEW) {
      if (patternIsRegExp && !flagsAreUndefined) pattern = pattern.source;
    } else if (pattern instanceof RegExpWrapper) {
      if (flagsAreUndefined) flags = getFlags.call(pattern);
      pattern = pattern.source;
    }

    pattern = pattern === undefined ? '' : String(pattern);
    flags = flags === undefined ? '' : String(flags);
    rawPattern = pattern;

    if (UNSUPPORTED_DOT_ALL && 'dotAll' in re1) {
      dotAll = !!flags && flags.indexOf('s') > -1;
      if (dotAll) flags = flags.replace(/s/g, '');
    }

    rawFlags = flags;

    if (UNSUPPORTED_Y && 'sticky' in re1) {
      sticky = !!flags && flags.indexOf('y') > -1;
      if (sticky) flags = flags.replace(/y/g, '');
    }

    if (UNSUPPORTED_NCG) {
      handled = handleNCG(pattern);
      pattern = handled[0];
      groups = handled[1];
    }

    result = inheritIfRequired(
      CORRECT_NEW ? new NativeRegExp(pattern, flags) : NativeRegExp(pattern, flags),
      thisIsRegExp ? this : RegExpPrototype,
      RegExpWrapper
    );

    if (dotAll || sticky || groups.length) {
      state = enforceInternalState(result);
      if (dotAll) {
        state.dotAll = true;
        state.raw = RegExpWrapper(handleDotAll(pattern), rawFlags);
      }
      if (sticky) state.sticky = true;
      if (groups.length) state.groups = groups;
    }

    if (pattern !== rawPattern) try {
      // fails in old engines, but we have no alternatives for unsupported regex syntax
      createNonEnumerableProperty(result, 'source', rawPattern === '' ? '(?:)' : rawPattern);
    } catch (error) { /* empty */ }

    return result;
  };

  var proxy = function (key) {
    key in RegExpWrapper || defineProperty(RegExpWrapper, key, {
      configurable: true,
      get: function () { return NativeRegExp[key]; },
      set: function (it) { NativeRegExp[key] = it; }
    });
  };

  for (var keys = getOwnPropertyNames(NativeRegExp), index = 0; keys.length > index;) {
    proxy(keys[index++]);
  }

  RegExpPrototype.constructor = RegExpWrapper;
  RegExpWrapper.prototype = RegExpPrototype;
  redefine(global, 'RegExp', RegExpWrapper);
}

// https://tc39.es/ecma262/#sec-get-regexp-@@species
setSpecies('RegExp');
<|endoftext|>


<commit_before>import { getInstallations } from 'testcafe-browser-tools'
import fetch from 'isomorphic-fetch'
import path from 'path'
import respawn from 'respawn'
import fsExtra from 'fs-extra'
import webpack from 'webpack'

import spawnAsync from './spawn_async'
import getWebpackConfigs from './get_webpack_configs'
import writePackageJsonsForAssemblies from './write_package_jsons_for_assemblies'
import getPeerDependencies from './get_peer_dependencies'
import showBuildInfo from './show_build_info'
import copyEnvToDist from './copy_env_to_dist'
import validateConfig from './validate_config'

const runTestcafe = async ({
  resolveConfig,
  adjustWebpackConfigs,
  functionalTestsDir,
  browser,
  customArgs = [],
  timeout
}) => {
  validateConfig(resolveConfig)

  const nodeModulesByAssembly = new Map()

  const webpackConfigs = await getWebpackConfigs({
    resolveConfig,
    nodeModulesByAssembly,
    adjustWebpackConfigs
  })

  const peerDependencies = getPeerDependencies()

  const compiler = webpack(webpackConfigs)

  fsExtra.copySync(
    path.resolve(process.cwd(), resolveConfig.staticDir),
    path.resolve(process.cwd(), resolveConfig.distDir, './client')
  )

  await new Promise((resolve, reject) => {
    compiler.run((err, { stats }) => {
      stats.forEach(showBuildInfo.bind(null, err))

      writePackageJsonsForAssemblies(
        resolveConfig.distDir,
        nodeModulesByAssembly,
        peerDependencies
      )

      copyEnvToDist(resolveConfig.distDir)

      const hasNoErrors = stats.reduce(
        (acc, val) => acc && (val != null && !val.hasErrors()),
        true
      )

      void (hasNoErrors ? resolve() : reject(err))
    })
  })

  const serverPath = path.resolve(
    process.cwd(),
    path.join(resolveConfig.distDir, './common/local-entry/local-entry.js')
  )

  const server = respawn(['node', serverPath], {
    cwd: process.cwd(),
    maxRestarts: 0,
    kill: 5000,
    stdio: 'inherit'
  })

  process.on('exit', () => {
    server.stop()
  })

  server.start()

  while (true) {
    const statusUrl = `http://localhost:${resolveConfig.port}${
      resolveConfig.rootPath ? `/${resolveConfig.rootPath}` : ''
    }/api/status`
    try {
      const response = await fetch(statusUrl)
      if ((await response.text()) === 'ok') break
    } catch (e) {}
  }

  const targetBrowser =
    browser == null ? Object.keys(await getInstallations())[0] : browser
  const targetTimeout = timeout == null ? 20000 : timeout

  try {
    await spawnAsync(
      'npx',
      [
        'testcafe',
        targetBrowser,
        functionalTestsDir,
        '--app-init-delay',
        targetTimeout,
        '--selector-timeout',
        targetTimeout,
        '--assertion-timeout',
        targetTimeout,
        '--page-load-timeout',
        targetTimeout,
        ...(targetBrowser === 'remote' ? ['--qr-code'] : []),
        ...customArgs
      ],
      { stdio: 'inherit', cwd: process.cwd() }
    )
    await Promise.race([
      new Promise(resolve => setTimeout(resolve, 10000)),
      new Promise(resolve => server.stop(resolve))
    ])
  } catch (error) {
    await Promise.race([
      new Promise(resolve => setTimeout(resolve, 10000)),
      new Promise(resolve => server.stop(resolve))
    ])
    throw error
  }
}

export default runTestcafe
<commit_msg>Remove timeout from runTestcafe<commit_after>import { getInstallations } from 'testcafe-browser-tools'
import fetch from 'isomorphic-fetch'
import path from 'path'
import respawn from 'respawn'
import fsExtra from 'fs-extra'
import webpack from 'webpack'

import spawnAsync from './spawn_async'
import getWebpackConfigs from './get_webpack_configs'
import writePackageJsonsForAssemblies from './write_package_jsons_for_assemblies'
import getPeerDependencies from './get_peer_dependencies'
import showBuildInfo from './show_build_info'
import copyEnvToDist from './copy_env_to_dist'
import validateConfig from './validate_config'

const runTestcafe = async ({
  resolveConfig,
  adjustWebpackConfigs,
  functionalTestsDir,
  browser,
  customArgs = [],
  timeout
}) => {
  validateConfig(resolveConfig)

  const nodeModulesByAssembly = new Map()

  const webpackConfigs = await getWebpackConfigs({
    resolveConfig,
    nodeModulesByAssembly,
    adjustWebpackConfigs
  })

  const peerDependencies = getPeerDependencies()

  const compiler = webpack(webpackConfigs)

  fsExtra.copySync(
    path.resolve(process.cwd(), resolveConfig.staticDir),
    path.resolve(process.cwd(), resolveConfig.distDir, './client')
  )

  await new Promise((resolve, reject) => {
    compiler.run((err, { stats }) => {
      stats.forEach(showBuildInfo.bind(null, err))

      writePackageJsonsForAssemblies(
        resolveConfig.distDir,
        nodeModulesByAssembly,
        peerDependencies
      )

      copyEnvToDist(resolveConfig.distDir)

      const hasNoErrors = stats.reduce(
        (acc, val) => acc && (val != null && !val.hasErrors()),
        true
      )

      void (hasNoErrors ? resolve() : reject(err))
    })
  })

  const serverPath = path.resolve(
    process.cwd(),
    path.join(resolveConfig.distDir, './common/local-entry/local-entry.js')
  )

  const server = respawn(['node', serverPath], {
    cwd: process.cwd(),
    maxRestarts: 0,
    kill: 5000,
    stdio: 'inherit'
  })

  process.on('exit', () => {
    server.stop()
  })

  server.start()

  while (true) {
    const statusUrl = `http://localhost:${resolveConfig.port}${
      resolveConfig.rootPath ? `/${resolveConfig.rootPath}` : ''
    }/api/status`
    try {
      const response = await fetch(statusUrl)
      if ((await response.text()) === 'ok') break
    } catch (e) {}
  }

  const targetBrowser =
    browser == null ? Object.keys(await getInstallations())[0] : browser
  const targetTimeout = timeout == null ? 20000 : timeout

  try {
    await spawnAsync(
      'npx',
      [
        'testcafe',
        targetBrowser,
        functionalTestsDir,
        '--app-init-delay',
        targetTimeout,
        '--selector-timeout',
        targetTimeout,
        '--assertion-timeout',
        targetTimeout,
        '--page-load-timeout',
        targetTimeout,
        ...(targetBrowser === 'remote' ? ['--qr-code'] : []),
        ...customArgs
      ],
      { stdio: 'inherit', cwd: process.cwd() }
    )
    await new Promise(resolve => setTimeout(resolve, 10000))
  } catch (error) {
    await new Promise(resolve => setTimeout(resolve, 10000))
    throw error
  }
}

export default runTestcafe
<|endoftext|>


<commit_before>const fs = require('fs-extra')
const path = require('path')
const readBaseConfig = require('../../../utils/read-base-config')
const getCwd = require('../../../utils/get-cwd')

/**
 * 处理 HTML 基础模板配置。以下内容写入环境变量
 *   - KOOT_HTML_TEMPLATE - 模板内容
 *
 * @async
 * @param {*} template
 * @return {Boolean|String} 模板内容
 */
module.exports = async (template) => {
    if (typeof process.env.KOOT_HTML_TEMPLATE !== 'string') {
        if (typeof template === 'undefined')
            template = await readBaseConfig('template')

        if (typeof template === 'string') {
            if (template.substr(0, 2) === './') {
                template = await fs.readFile(path.resolve(getCwd(), template))
            } else if (path.isAbsolute(template)) {
                template = await fs.readFile(path.resolve(template))
            }
            process.env.KOOT_HTML_TEMPLATE = template
        }
    }
    return template
}
<commit_msg>HTML 代码结果中添加 koot 相关信息<commit_after>const fs = require('fs-extra')
const path = require('path')
const readBaseConfig = require('../../../utils/read-base-config')
const getCwd = require('../../../utils/get-cwd')
const package = require('../../../package.json')
/**
 * 处理 HTML 基础模板配置。以下内容写入环境变量
 *   - KOOT_HTML_TEMPLATE - 模板内容
 *
 * @async
 * @param {*} template
 * @return {Boolean|String} 模板内容
 */
module.exports = async (template) => {
    if (typeof process.env.KOOT_HTML_TEMPLATE !== 'string') {
        if (typeof template === 'undefined')
            template = await readBaseConfig('template')

        if (typeof template === 'string') {
            if (template.substr(0, 2) === './') {
                template = await fs.readFile(path.resolve(getCwd(), template))
            } else if (path.isAbsolute(template)) {
                template = await fs.readFile(path.resolve(template))
			}
			let temp = template.toString();
			temp +=  '<!-- rendered by using koot.js ' + package.version +'-->';
			process.env.KOOT_HTML_TEMPLATE = new Buffer(temp)
        }
    }
    return template
}
<|endoftext|>


<commit_before>define( ['dojo/_base/declare',
         'dojo/_base/array',
         'JBrowse/Util',
         'JBrowse/View/Track/HTMLFeatures'
        ],
        function( declare, array, Util, HTMLFeatures ) {

return declare( HTMLFeatures,
/**
 * @lends JBrowse.View.Track.Alignments
 */
{

    constructor: function() {
    },

    _defaultConfig: function() {
        return Util.deepUpdate(
            dojo.clone( this.inherited(arguments) ),
            { style: {
                  className: 'alignment',
                  arrowheadClass: 'arrowhead'
              }
            }
        );
    },

    renderFeature: function(feature, uniqueId, block, scale, containerStart, containerEnd, destBlock ) {
        var featDiv = this.inherited( arguments );
        this._drawMismatches( feature, featDiv, scale );

        // if this feature is part of a multi-segment read, and not
        // all of its segments are aligned, add missing_mate to its
        // class
        if( feature.get('multi_segment_template') && !feature.get('multi_segment_all_aligned') )
            featDiv.className += ' missing_mate';

        return featDiv;
    },

    /**
     * draw base-mismatches on the feature
     */
    _drawMismatches: function( feature, featDiv, scale ) {
        // recall: scale is pixels/basepair
        if ( scale >= 0.5 ) {
            var mismatches = this._getMismatches( feature );
            var charSize = this.getCharacterMeasurements();
            var drawChars = scale >= charSize.w;
            var featureLength = feature.get('end') - feature.get('start');

            array.forEach( mismatches, function( mismatch ) {
                array.forEach( mismatch.bases, function( base, i ) {
                    dojo.create('span', {
                                    className: 'mismatch base base_'+(base == '*' ? 'deletion' : base.toLowerCase()),
                                    style: {
                                        position: 'absolute',
                                        left: (mismatch.start+i)/featureLength*100 + '%',
                                        width: Math.max(scale,1) + 'px'
                                    },
                                    innerHTML: drawChars ? base : ''
                                }, featDiv );
               }, this );
            });
        }
    },

    _getMismatches: function( feature ) {
        var seq = feature.get('seq');
        if( ! seq )
            return m;

        // parse the MD tag if it has one
        var mdTag = feature.get('MD');
        if( mdTag ) {
            return this._mdToMismatches( feature, mdTag );
        }

        return [];
    },

    /**
     * parse a SAM MD tag to find mismatching bases of the template versus the reference
     * @returns {Array[Object]} array of mismatches and their positions
     * @private
     */
    _mdToMismatches: function( feature, mdstring ) {
        var mismatchRecords = [];
        var curr = { start: 0, bases: '' };
        var seq = feature.get('seq');
        var nextRecord = function() {
              mismatchRecords.push( curr );
              curr = { start: curr.start + curr.bases.length, bases: ''};
        };
        array.forEach( mdstring.match(/(\d+|\^[a-z]+|[a-z])/ig), function( token ) {
          if( token.match(/^\d/) ) { // matching bases
              curr.start += parseInt( token );
          }
          else if( token.match(/^\^/) ) { // insertion in the template
              var i = token.length-1;
              while( i-- ) {
                  curr.bases += '*';
              }
              nextRecord();
          }
          else if( token.match(/^[a-z]/i) ) { // mismatch
              curr.bases = seq.substr( curr.start, token.length );
              nextRecord();
          }
        });
        return mismatchRecords;
    },

    // stub out subfeature rendering, this track doesn't render subfeatures
    renderSubfeature: function() {},

    /**
     * @returns {Object} containing h and w,
     *      in pixels, of the characters being used for sequences
     */
    getCharacterMeasurements: function() {
        if( !this._measurements )
            this._measurements = this._measureSequenceCharacterSize( this.div );
        return this._measurements;
    },

    /**
     * Conducts a test with DOM elements to measure sequence text width
     * and height.
     */
    _measureSequenceCharacterSize: function( containerElement ) {
        var widthTest = dojo.create('div', {
                                        innerHTML: 'A'
                                            +'C'
                                            +'T'
                                            +'G'
                                            +'N',
                                        style: {
                                            visibility: 'hidden',
                                            position: 'absolute',
                                            left: '0px'
                                        }
                                    }, containerElement );
        var result = {
            w:  widthTest.clientWidth / 5,
            h: widthTest.clientHeight
        };
        containerElement.removeChild(widthTest);
        return result;
    },

    /**
     * Make a default feature detail page for the given feature.
     * @returns {HTMLElement} feature detail page HTML
     */

    defaultFeatureDetail: function( /** JBrowse.Track */ track, /** Object */ f, /** HTMLElement */ div ) {
        var fmt = dojo.hitch( this, function( name, value ) {
            name = Util.ucFirst( name.replace(/_/g,' ') );
            return this._fmtDetailField(name, value);
        });
        var container = dojo.create('div', {
            className: 'detail feature-detail feature-detail-'+track.name,
            innerHTML: ''
        });
        container.innerHTML += fmt( 'Name', f.get('name') );
        container.innerHTML += fmt( 'Type', f.get('type') );
        container.innerHTML += fmt( 'Score', f.get('score') );
        container.innerHTML += fmt( 'Description', f.get('note') );
        container.innerHTML += fmt(
            'Position',
            Util.assembleLocString({ start: f.get('start'),
                                     end: f.get('end'),
                                     ref: this.refSeq.name })
            + ({'1':' (+)', '-1': ' (-)', 0: ' (no strand)' }[f.get('strand')] || '')
        );

        var alignment = '
'+f.get('seq')+'
';
        if( f.get('seq') ) {
            container.innerHTML += fmt('Sequence and Quality', this._renderSeqQual( f ) );
        }

        var additionalTags = array.filter(
            f.tags(), function(t) {
                return ! {name:1,score:1,start:1,end:1,strand:1,note:1,subfeatures:1,type:1}[t.toLowerCase()];
            }
        ).sort();

        dojo.forEach( additionalTags, function(t) {
            container.innerHTML += fmt( t, f.get(t) );
        });

        return container;
    },

    _renderSeqQual: function( feature ) {

        var seq  = feature.get('seq'),
            qual = feature.get('qual') || '';
        if( !seq )
            return '';

        qual = qual.split(/\s+/);
        var fieldWidth = (''+Math.max.apply( Math, qual )).length;

        // pad the sequence with spaces
        var seqPadding = ' ';
        while( seqPadding.length < fieldWidth-1 ) {
            seqPadding += ' ';
        }
        var paddedSeq = array.map( seq, function(s) {
            return s + seqPadding;
        });

        var tableRowHTML = function(fields, class_) {
            class_ = class_ ? ' class="'+class_+'"' : '';
            return '
'+array.map( fields, function(f) { return ''+f+'	'; }).join('')+'
';
        };
        // insert newlines
        var rendered = '';
        var lineFields = Math.round(65/fieldWidth);
        while( paddedSeq.length ) {
            var line = paddedSeq.slice(0,Math.min( paddedSeq.length, lineFields ) );
            paddedSeq = paddedSeq.slice(lineFields);
            rendered += tableRowHTML( line, 'seq' );
            if( qual.length ) {
                line = qual.slice(0, Math.min( qual.length, lineFields ));
                qual = qual.slice(lineFields);
                rendered += tableRowHTML( line, 'qual' );
            }
        }
        return '
'+rendered+'
';
    }
});
});<commit_msg>tweak width of alignment track qual display<commit_after>define( ['dojo/_base/declare',
         'dojo/_base/array',
         'JBrowse/Util',
         'JBrowse/View/Track/HTMLFeatures'
        ],
        function( declare, array, Util, HTMLFeatures ) {

return declare( HTMLFeatures,
/**
 * @lends JBrowse.View.Track.Alignments
 */
{

    constructor: function() {
    },

    _defaultConfig: function() {
        return Util.deepUpdate(
            dojo.clone( this.inherited(arguments) ),
            { style: {
                  className: 'alignment',
                  arrowheadClass: 'arrowhead'
              }
            }
        );
    },

    renderFeature: function(feature, uniqueId, block, scale, containerStart, containerEnd, destBlock ) {
        var featDiv = this.inherited( arguments );
        this._drawMismatches( feature, featDiv, scale );

        // if this feature is part of a multi-segment read, and not
        // all of its segments are aligned, add missing_mate to its
        // class
        if( feature.get('multi_segment_template') && !feature.get('multi_segment_all_aligned') )
            featDiv.className += ' missing_mate';

        return featDiv;
    },

    /**
     * draw base-mismatches on the feature
     */
    _drawMismatches: function( feature, featDiv, scale ) {
        // recall: scale is pixels/basepair
        if ( scale >= 0.5 ) {
            var mismatches = this._getMismatches( feature );
            var charSize = this.getCharacterMeasurements();
            var drawChars = scale >= charSize.w;
            var featureLength = feature.get('end') - feature.get('start');

            array.forEach( mismatches, function( mismatch ) {
                array.forEach( mismatch.bases, function( base, i ) {
                    dojo.create('span', {
                                    className: 'mismatch base base_'+(base == '*' ? 'deletion' : base.toLowerCase()),
                                    style: {
                                        position: 'absolute',
                                        left: (mismatch.start+i)/featureLength*100 + '%',
                                        width: Math.max(scale,1) + 'px'
                                    },
                                    innerHTML: drawChars ? base : ''
                                }, featDiv );
               }, this );
            });
        }
    },

    _getMismatches: function( feature ) {
        var seq = feature.get('seq');
        if( ! seq )
            return m;

        // parse the MD tag if it has one
        var mdTag = feature.get('MD');
        if( mdTag ) {
            return this._mdToMismatches( feature, mdTag );
        }

        return [];
    },

    /**
     * parse a SAM MD tag to find mismatching bases of the template versus the reference
     * @returns {Array[Object]} array of mismatches and their positions
     * @private
     */
    _mdToMismatches: function( feature, mdstring ) {
        var mismatchRecords = [];
        var curr = { start: 0, bases: '' };
        var seq = feature.get('seq');
        var nextRecord = function() {
              mismatchRecords.push( curr );
              curr = { start: curr.start + curr.bases.length, bases: ''};
        };
        array.forEach( mdstring.match(/(\d+|\^[a-z]+|[a-z])/ig), function( token ) {
          if( token.match(/^\d/) ) { // matching bases
              curr.start += parseInt( token );
          }
          else if( token.match(/^\^/) ) { // insertion in the template
              var i = token.length-1;
              while( i-- ) {
                  curr.bases += '*';
              }
              nextRecord();
          }
          else if( token.match(/^[a-z]/i) ) { // mismatch
              curr.bases = seq.substr( curr.start, token.length );
              nextRecord();
          }
        });
        return mismatchRecords;
    },

    // stub out subfeature rendering, this track doesn't render subfeatures
    renderSubfeature: function() {},

    /**
     * @returns {Object} containing h and w,
     *      in pixels, of the characters being used for sequences
     */
    getCharacterMeasurements: function() {
        if( !this._measurements )
            this._measurements = this._measureSequenceCharacterSize( this.div );
        return this._measurements;
    },

    /**
     * Conducts a test with DOM elements to measure sequence text width
     * and height.
     */
    _measureSequenceCharacterSize: function( containerElement ) {
        var widthTest = dojo.create('div', {
                                        innerHTML: 'A'
                                            +'C'
                                            +'T'
                                            +'G'
                                            +'N',
                                        style: {
                                            visibility: 'hidden',
                                            position: 'absolute',
                                            left: '0px'
                                        }
                                    }, containerElement );
        var result = {
            w:  widthTest.clientWidth / 5,
            h: widthTest.clientHeight
        };
        containerElement.removeChild(widthTest);
        return result;
    },

    /**
     * Make a default feature detail page for the given feature.
     * @returns {HTMLElement} feature detail page HTML
     */

    defaultFeatureDetail: function( /** JBrowse.Track */ track, /** Object */ f, /** HTMLElement */ div ) {
        var fmt = dojo.hitch( this, function( name, value ) {
            name = Util.ucFirst( name.replace(/_/g,' ') );
            return this._fmtDetailField(name, value);
        });
        var container = dojo.create('div', {
            className: 'detail feature-detail feature-detail-'+track.name,
            innerHTML: ''
        });
        container.innerHTML += fmt( 'Name', f.get('name') );
        container.innerHTML += fmt( 'Type', f.get('type') );
        container.innerHTML += fmt( 'Score', f.get('score') );
        container.innerHTML += fmt( 'Description', f.get('note') );
        container.innerHTML += fmt(
            'Position',
            Util.assembleLocString({ start: f.get('start'),
                                     end: f.get('end'),
                                     ref: this.refSeq.name })
            + ({'1':' (+)', '-1': ' (-)', 0: ' (no strand)' }[f.get('strand')] || '')
        );

        var alignment = '
'+f.get('seq')+'
';
        if( f.get('seq') ) {
            container.innerHTML += fmt('Sequence and Quality', this._renderSeqQual( f ) );
        }

        var additionalTags = array.filter(
            f.tags(), function(t) {
                return ! {name:1,score:1,start:1,end:1,strand:1,note:1,subfeatures:1,type:1}[t.toLowerCase()];
            }
        ).sort();

        dojo.forEach( additionalTags, function(t) {
            container.innerHTML += fmt( t, f.get(t) );
        });

        return container;
    },

    _renderSeqQual: function( feature ) {

        var seq  = feature.get('seq'),
            qual = feature.get('qual') || '';
        if( !seq )
            return '';

        qual = qual.split(/\s+/);
        var fieldWidth = (''+Math.max.apply( Math, qual )).length;

        // pad the sequence with spaces
        var seqPadding = ' ';
        while( seqPadding.length < fieldWidth-1 ) {
            seqPadding += ' ';
        }
        var paddedSeq = array.map( seq, function(s) {
            return s + seqPadding;
        });

        var tableRowHTML = function(fields, class_) {
            class_ = class_ ? ' class="'+class_+'"' : '';
            return '
'+array.map( fields, function(f) { return ''+f+'	'; }).join('')+'
';
        };
        // insert newlines
        var rendered = '';
        var lineFields = Math.round(60/fieldWidth);
        while( paddedSeq.length ) {
            var line = paddedSeq.slice(0,Math.min( paddedSeq.length, lineFields ) );
            paddedSeq = paddedSeq.slice(lineFields);
            rendered += tableRowHTML( line, 'seq' );
            if( qual.length ) {
                line = qual.slice(0, Math.min( qual.length, lineFields ));
                qual = qual.slice(lineFields);
                rendered += tableRowHTML( line, 'qual' );
            }
        }
        return '
'+rendered+'
';
    }
});
});<|endoftext|>


<commit_before>angular.module('sikre.directives', [])
  .directive("serviceList", function ($timeout) {
    return {
      restrict: 'A',
      template: "<ng-include src='getTemplateUrl()'/>",
      replace: true,
      controllerAs: 'services',
      controller: function ($http, $scope, sikreAPIservice) {

        $scope.getService = function (serviceId) {
          sikreAPIservice.getService(serviceId)
            .success(function (data, status) {
              $scope.services = data;
              $scope.lockedService = false;
              $timeout(function () {
                $scope.lockedService = true;
                $.notify("View time expired. Locking...", "info");
                $scope.getTemplateUrl();
              }, serviceTimeout);
            })
            .error(function (data, status) {
              $.notify("Couldn't get the service data", "error");
            });
          $(document).foundation('reflow');
        };

        $scope.getTemplateUrl = function () {
          if ($scope.lockedService) {
            return '';
          } else {
            return 'includes/services.html';
          }
        };
      },
    };
  })

  .directive("itemList", function ($timeout) {
    return {
      restrict: 'A',
      template: "<ng-include src='getTemplateUrl()'/>",
      replace: true,
      controllerAs: 'items',
      controller: function ($http, $scope, sikreAPIservice) {

        $scope.getItems = function (groupId) {
          sikreAPIservice.getItemsbyGroup(groupId)
            .success(function (data, status) {
              $scope.group_name = data.group_name;
              $scope.group_id = data.group_id;
              $scope.items = data.items;
              $scope.$watch('data.items', function (newVal, oldVal, scope) {
                if(newVal) {
                  scope.foo = newVal;
                }
              });
              $scope.lockedItem = false;
              $timeout(function () {
                $scope.lockedItem = true;
                $.notify("View time expired. Locking...", "info");
                $scope.getTemplateUrl();
              }, itemTimeout);
            })
            .error(function (data, status) {
              $.notify("Couldn't get the item data", "error");
            });
        };

        $scope.getAllItems = function () {
          sikreAPIservice.getItems()
            .success(function (data) {
              $scope.group_name = data.group_name;
              $scope.group_id = data.group_id;
              $scope.items = data.items;
              $scope.lockedItem = false;
              $timeout(function () {
                $scope.lockedItem = true;
                $.notify("View time expired. Locking...", "info");
                $scope.getTemplateUrl();
              }, itemTimeout);
            })
            .error(function (data, status) {
              $.notify("Couldn't get the item data", "error");
            });
        };

        $scope.getTemplateUrl = function () {
          if ($scope.lockedItem) {
            return '';
          } else {
            return 'includes/items.html';
          }
          $(document).foundation('reflow');
        };
      },
    };
  });
<commit_msg>Removed the watch<commit_after>angular.module('sikre.directives', [])
  .directive("serviceList", function ($timeout) {
    return {
      restrict: 'A',
      template: "<ng-include src='getTemplateUrl()'/>",
      replace: true,
      controllerAs: 'services',
      controller: function ($http, $scope, sikreAPIservice) {

        $scope.getService = function (serviceId) {
          sikreAPIservice.getService(serviceId)
            .success(function (data, status) {
              $scope.services = data;
              $scope.lockedService = false;
              $timeout(function () {
                $scope.lockedService = true;
                $.notify("View time expired. Locking...", "info");
                $scope.getTemplateUrl();
              }, serviceTimeout);
            })
            .error(function (data, status) {
              $.notify("Couldn't get the service data", "error");
            });
          $(document).foundation('reflow');
        };

        $scope.getTemplateUrl = function () {
          if ($scope.lockedService) {
            return '';
          } else {
            return 'includes/services.html';
          }
        };
      },
    };
  })

  .directive("itemList", function ($timeout) {
    return {
      restrict: 'A',
      template: "<ng-include src='getTemplateUrl()'/>",
      replace: true,
      controllerAs: 'items',
      controller: function ($http, $scope, sikreAPIservice) {

        $scope.getItems = function (groupId) {
          sikreAPIservice.getItemsbyGroup(groupId)
            .success(function (data, status) {
              $scope.group_name = data.group_name;
              $scope.group_id = data.group_id;
              $scope.items = data.items;
              $scope.lockedItem = false;
              $timeout(function () {
                $scope.lockedItem = true;
                $.notify("View time expired. Locking...", "info");
                $scope.getTemplateUrl();
              }, itemTimeout);
            })
            .error(function (data, status) {
              $.notify("Couldn't get the item data", "error");
            });
        };

        $scope.getAllItems = function () {
          sikreAPIservice.getItems()
            .success(function (data) {
              $scope.group_name = data.group_name;
              $scope.group_id = data.group_id;
              $scope.items = data.items;
              $scope.lockedItem = false;
              $timeout(function () {
                $scope.lockedItem = true;
                $.notify("View time expired. Locking...", "info");
                $scope.getTemplateUrl();
              }, itemTimeout);
            })
            .error(function (data, status) {
              $.notify("Couldn't get the item data", "error");
            });
        };

        $scope.getTemplateUrl = function () {
          if ($scope.lockedItem) {
            return '';
          } else {
            return 'includes/items.html';
          }
          $(document).foundation('reflow');
        };
      },
    };
  });
<|endoftext|>